hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
d7235f63cbe6e05db09a64f697e1177b7fb8b95d
13,528
cc
C++
DataFormats/L1GlobalTrigger/src/L1GlobalTriggerObjectMaps.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
DataFormats/L1GlobalTrigger/src/L1GlobalTriggerObjectMaps.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
DataFormats/L1GlobalTrigger/src/L1GlobalTriggerObjectMaps.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
/** * \class L1GlobalTriggerObjectMapRecord * * * Description: see header file. * * Implementation: * <TODO: enter implementation details> * * \author: Vasile Mihai Ghete - HEPHY Vienna * \author: W. David Dagenhart * * */ #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerObjectMaps.h" #include <algorithm> #include <limits> #include "FWCore/Utilities/interface/Exception.h" void L1GlobalTriggerObjectMaps::swap(L1GlobalTriggerObjectMaps& rh) { m_algorithmResults.swap(rh.m_algorithmResults); m_conditionResults.swap(rh.m_conditionResults); m_combinations.swap(rh.m_combinations); m_namesParameterSetID.swap(rh.m_namesParameterSetID); } bool L1GlobalTriggerObjectMaps::algorithmExists(int algorithmBitNumber) const { std::vector<AlgorithmResult>::const_iterator i = std::lower_bound( m_algorithmResults.begin(), m_algorithmResults.end(), AlgorithmResult(0, algorithmBitNumber, false)); if (i == m_algorithmResults.end() || i->algorithmBitNumber() != algorithmBitNumber) { return false; } return true; } bool L1GlobalTriggerObjectMaps::algorithmResult(int algorithmBitNumber) const { std::vector<AlgorithmResult>::const_iterator i = std::lower_bound( m_algorithmResults.begin(), m_algorithmResults.end(), AlgorithmResult(0, algorithmBitNumber, false)); if (i == m_algorithmResults.end() || i->algorithmBitNumber() != algorithmBitNumber) { cms::Exception ex("L1GlobalTrigger"); ex << "algorithmBitNumber not found"; ex.addContext("Calling L1GlobalTriggerObjectMaps::algorithmResult"); throw ex; } return i->algorithmResult(); } void L1GlobalTriggerObjectMaps::updateOperandTokenVector( int algorithmBitNumber, std::vector<L1GtLogicParser::OperandToken>& operandTokenVector) const { unsigned startIndex = 0; unsigned endIndex = 0; getStartEndIndex(algorithmBitNumber, startIndex, endIndex); unsigned length = endIndex - startIndex; if (length != operandTokenVector.size()) { cms::Exception ex("L1GlobalTrigger"); ex << "operand token vector size does not match number of conditions"; ex.addContext("Calling L1GlobalTriggerObjectMaps::updateOperandTokenVector"); throw ex; } for (unsigned i = 0; i < length; ++i) { operandTokenVector[i].tokenResult = m_conditionResults[startIndex + i].conditionResult(); } } void L1GlobalTriggerObjectMaps::getAlgorithmBitNumbers(std::vector<int>& algorithmBitNumbers) const { algorithmBitNumbers.clear(); for (std::vector<AlgorithmResult>::const_iterator i = m_algorithmResults.begin(), iEnd = m_algorithmResults.end(); i != iEnd; ++i) { algorithmBitNumbers.push_back(i->algorithmBitNumber()); } } unsigned L1GlobalTriggerObjectMaps::getNumberOfConditions(int algorithmBitNumber) const { unsigned startIndex = 0; unsigned endIndex = 0; getStartEndIndex(algorithmBitNumber, startIndex, endIndex); return endIndex - startIndex; } L1GlobalTriggerObjectMaps::ConditionsInAlgorithm L1GlobalTriggerObjectMaps::getConditionsInAlgorithm( int algorithmBitNumber) const { unsigned startIndex = 0; unsigned endIndex = 0; getStartEndIndex(algorithmBitNumber, startIndex, endIndex); return ConditionsInAlgorithm(&m_conditionResults[startIndex], endIndex - startIndex); } L1GlobalTriggerObjectMaps::CombinationsInCondition L1GlobalTriggerObjectMaps::getCombinationsInCondition( int algorithmBitNumber, unsigned conditionNumber) const { unsigned startIndex = 0; unsigned endIndex = 0; getStartEndIndex(algorithmBitNumber, startIndex, endIndex); if (endIndex <= startIndex + conditionNumber) { cms::Exception ex("L1GlobalTrigger"); ex << "Condition number is out of range"; ex.addContext("Calling L1GlobalTriggerObjectMaps::getCombinationsInCondition"); throw ex; } unsigned endObjectIndex = m_combinations.size(); unsigned nextConditionIndex = startIndex + conditionNumber + 1U; if (nextConditionIndex < m_conditionResults.size()) { endObjectIndex = m_conditionResults[nextConditionIndex].startIndexOfCombinations(); } unsigned beginObjectIndex = m_conditionResults[startIndex + conditionNumber].startIndexOfCombinations(); unsigned short nObjectsPerCombination = m_conditionResults[startIndex + conditionNumber].nObjectsPerCombination(); if (endObjectIndex == beginObjectIndex) { return CombinationsInCondition(nullptr, 0, 0); } if (endObjectIndex < beginObjectIndex || m_combinations.size() < endObjectIndex || nObjectsPerCombination == 0 || (endObjectIndex - beginObjectIndex) % nObjectsPerCombination != 0) { cms::Exception ex("L1GlobalTrigger"); ex << "Indexes to combinations are invalid"; ex.addContext("Calling L1GlobalTriggerObjectMaps::getCombinationsInCondition"); throw ex; } return CombinationsInCondition(&m_combinations[beginObjectIndex], (endObjectIndex - beginObjectIndex) / nObjectsPerCombination, nObjectsPerCombination); } void L1GlobalTriggerObjectMaps::reserveForAlgorithms(unsigned n) { m_algorithmResults.reserve(n); } void L1GlobalTriggerObjectMaps::pushBackAlgorithm(unsigned startIndexOfConditions, int algorithmBitNumber, bool algorithmResult) { m_algorithmResults.push_back(AlgorithmResult(startIndexOfConditions, algorithmBitNumber, algorithmResult)); } void L1GlobalTriggerObjectMaps::consistencyCheck() const { // None of these checks should ever fail unless there // is a bug in the code filling this object for (std::vector<AlgorithmResult>::const_iterator i = m_algorithmResults.begin(), iEnd = m_algorithmResults.end(); i != iEnd; ++i) { std::vector<AlgorithmResult>::const_iterator j = i; ++j; if (j != iEnd && !(*i < *j)) { cms::Exception ex("L1GlobalTrigger"); ex << "AlgorithmResults should be sorted in increasing order of bit number with no duplicates. It is not."; ex.addContext("Calling L1GlobalTriggerObjectMaps::consistencyCheck"); throw ex; } unsigned endIndex = (j != iEnd) ? j->startIndexOfConditions() : m_conditionResults.size(); if (endIndex < i->startIndexOfConditions()) { cms::Exception ex("L1GlobalTrigger"); ex << "startIndexOfConditions decreases or exceeds the size of m_conditionResults"; ex.addContext("Calling L1GlobalTriggerObjectMaps::consistencyCheck"); throw ex; } } for (std::vector<ConditionResult>::const_iterator i = m_conditionResults.begin(), iEnd = m_conditionResults.end(); i != iEnd; ++i) { std::vector<ConditionResult>::const_iterator j = i; ++j; unsigned endIndex = (j != iEnd) ? j->startIndexOfCombinations() : m_combinations.size(); if (endIndex < i->startIndexOfCombinations()) { cms::Exception ex("L1GlobalTrigger"); ex << "startIndexOfCombinations decreases or exceeds the size of m_conditionResults"; ex.addContext("Calling L1GlobalTriggerObjectMaps::consistencyCheck"); throw ex; } unsigned length = endIndex - i->startIndexOfCombinations(); if (length == 0U) { if (i->nObjectsPerCombination() != 0U) { cms::Exception ex("L1GlobalTrigger"); ex << "Length is zero and nObjectsInCombination is not zero"; ex.addContext("Calling L1GlobalTriggerObjectMaps::consistencyCheck"); throw ex; } } else { if (i->nObjectsPerCombination() == 0 || length % i->nObjectsPerCombination() != 0) { cms::Exception ex("L1GlobalTrigger"); ex << "Size indicated by startIndexOfCombinations is not a multiple of nObjectsInCombination"; ex.addContext("Calling L1GlobalTriggerObjectMaps::consistencyCheck"); throw ex; } } } } void L1GlobalTriggerObjectMaps::reserveForConditions(unsigned n) { m_conditionResults.reserve(n); } void L1GlobalTriggerObjectMaps::pushBackCondition(unsigned startIndexOfCombinations, unsigned short nObjectsPerCombination, bool conditionResult) { m_conditionResults.push_back(ConditionResult(startIndexOfCombinations, nObjectsPerCombination, conditionResult)); } void L1GlobalTriggerObjectMaps::reserveForObjectIndexes(unsigned n) { m_combinations.reserve(n); } void L1GlobalTriggerObjectMaps::pushBackObjectIndex(unsigned char objectIndex) { m_combinations.push_back(objectIndex); } void L1GlobalTriggerObjectMaps::setNamesParameterSetID(edm::ParameterSetID const& psetID) { m_namesParameterSetID = psetID; } L1GlobalTriggerObjectMaps::AlgorithmResult::AlgorithmResult() : m_startIndexOfConditions(0), m_algorithmBitNumber(0), m_algorithmResult(false) {} L1GlobalTriggerObjectMaps::AlgorithmResult::AlgorithmResult(unsigned startIndexOfConditions, int algorithmBitNumber, bool algorithmResult) : m_startIndexOfConditions(startIndexOfConditions), m_algorithmResult(algorithmResult) { // We made the decision to try to save space in the data format // and fit this object into 8 bytes by making the persistent // algorithmBitNumber a short. This creates something very // ugly below. In practice the range should never be exceeded. // In fact it is currently always supposed to be less than 128. // I hope this never comes back to haunt us for some unexpected reason. // I cringe when I look at it, but cannot think of any practical // harm ... It is probably a real bug if anyone ever // tries to shove a big int into here. if (algorithmBitNumber < std::numeric_limits<short>::min() || algorithmBitNumber > std::numeric_limits<short>::max()) { cms::Exception ex("L1GlobalTrigger"); ex << "algorithmBitNumber out of range of a short int"; ex.addContext("Calling L1GlobalTriggerObjectMaps::AlgorithmResult::AlgorithmResult"); throw ex; } m_algorithmBitNumber = static_cast<short>(algorithmBitNumber); } L1GlobalTriggerObjectMaps::ConditionResult::ConditionResult() : m_startIndexOfCombinations(0), m_nObjectsPerCombination(0), m_conditionResult(false) {} L1GlobalTriggerObjectMaps::ConditionResult::ConditionResult(unsigned startIndexOfCombinations, unsigned short nObjectsPerCombination, bool conditionResult) : m_startIndexOfCombinations(startIndexOfCombinations), m_nObjectsPerCombination(nObjectsPerCombination), m_conditionResult(conditionResult) {} L1GlobalTriggerObjectMaps::ConditionsInAlgorithm::ConditionsInAlgorithm(ConditionResult const* conditionResults, unsigned nConditions) : m_conditionResults(conditionResults), m_nConditions(nConditions) {} bool L1GlobalTriggerObjectMaps::ConditionsInAlgorithm::getConditionResult(unsigned condition) const { if (condition >= m_nConditions) { cms::Exception ex("L1GlobalTrigger"); ex << "argument out of range"; ex.addContext("Calling L1GlobalTriggerObjectMaps::ConditionsInAlgorithm::getConditionResult"); throw ex; } return (m_conditionResults + condition)->conditionResult(); } L1GlobalTriggerObjectMaps::CombinationsInCondition::CombinationsInCondition(unsigned char const* startOfObjectIndexes, unsigned nCombinations, unsigned short nObjectsPerCombination) : m_startOfObjectIndexes(startOfObjectIndexes), m_nCombinations(nCombinations), m_nObjectsPerCombination(nObjectsPerCombination) {} unsigned char L1GlobalTriggerObjectMaps::CombinationsInCondition::getObjectIndex(unsigned combination, unsigned object) const { if (combination >= m_nCombinations || object >= m_nObjectsPerCombination) { cms::Exception ex("L1GlobalTrigger"); ex << "arguments out of range"; ex.addContext("Calling L1GlobalTriggerObjectMaps::CombinationsInCondition::getObjectIndex"); throw ex; } return m_startOfObjectIndexes[combination * m_nObjectsPerCombination + object]; } void L1GlobalTriggerObjectMaps::getStartEndIndex(int algorithmBitNumber, unsigned& startIndex, unsigned& endIndex) const { std::vector<AlgorithmResult>::const_iterator iAlgo = std::lower_bound( m_algorithmResults.begin(), m_algorithmResults.end(), AlgorithmResult(0, algorithmBitNumber, false)); if (iAlgo == m_algorithmResults.end() || iAlgo->algorithmBitNumber() != algorithmBitNumber) { cms::Exception ex("L1GlobalTrigger"); ex << "algorithmBitNumber not found"; ex.addContext("Calling L1GlobalTriggerObjectMaps::getStartEndIndex"); throw ex; } startIndex = iAlgo->startIndexOfConditions(); ++iAlgo; endIndex = (iAlgo != m_algorithmResults.end()) ? iAlgo->startIndexOfConditions() : m_conditionResults.size(); if (endIndex < startIndex || m_conditionResults.size() < endIndex) { cms::Exception ex("L1GlobalTrigger"); ex << "index out of order or out of range"; ex.addContext("Calling L1GlobalTriggerObjectMaps::getStartEndIndex"); throw ex; } }
44.646865
118
0.706535
ckamtsikis
d7259262a33ae40e1358f79814d6400d7e3b2f50
36,367
cpp
C++
unit_tests/os_interface/windows/wddm20_tests.cpp
jdanecki/compute-runtime
0d7be1066d61a4e803fee9dcea6e9e9b4213b3b9
[ "MIT" ]
null
null
null
unit_tests/os_interface/windows/wddm20_tests.cpp
jdanecki/compute-runtime
0d7be1066d61a4e803fee9dcea6e9e9b4213b3b9
[ "MIT" ]
null
null
null
unit_tests/os_interface/windows/wddm20_tests.cpp
jdanecki/compute-runtime
0d7be1066d61a4e803fee9dcea6e9e9b4213b3b9
[ "MIT" ]
null
null
null
/* * Copyright (c) 2017 - 2018, Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, 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 "unit_tests/os_interface/windows/wddm_fixture.h" #include "runtime/execution_environment/execution_environment.h" #include "runtime/gmm_helper/gmm.h" #include "runtime/gmm_helper/gmm_helper.h" #include "runtime/helpers/hw_info.h" #include "runtime/helpers/options.h" #include "runtime/memory_manager/os_agnostic_memory_manager.h" #include "runtime/os_interface/windows/os_interface.h" #include "runtime/os_interface/os_library.h" #include "runtime/os_interface/windows/wddm_allocation.h" #include "runtime/os_interface/windows/wddm_memory_manager.h" #include "unit_tests/helpers/debug_manager_state_restore.h" #include "unit_tests/mocks/mock_gmm_resource_info.h" #include "gtest/gtest.h" #include "runtime/os_interface/os_time.h" #include <memory> #include <functional> using namespace OCLRT; namespace GmmHelperFunctions { Gmm *getGmm(void *ptr, size_t size) { size_t alignedSize = alignSizeWholePage(ptr, size); void *alignedPtr = alignUp(ptr, 4096); Gmm *gmm = new Gmm(alignedPtr, alignedSize, false); EXPECT_NE(gmm->gmmResourceInfo.get(), nullptr); return gmm; } } // namespace GmmHelperFunctions using Wddm20Tests = WddmTest; using Wddm20WithMockGdiDllTests = WddmTestWithMockGdiDll; using Wddm20InstrumentationTest = WddmInstrumentationTest; HWTEST_F(Wddm20Tests, givenMinWindowsAddressWhenWddmIsInitializedThenWddmUseThisAddress) { uintptr_t expectedAddress = 0x200000; EXPECT_EQ(expectedAddress, OCLRT::windowsMinAddress); bool status = wddm->init<FamilyType>(); EXPECT_TRUE(status); EXPECT_TRUE(wddm->isInitialized()); EXPECT_EQ(expectedAddress, wddm->getWddmMinAddress()); } HWTEST_F(Wddm20Tests, creation) { bool error = wddm->init<FamilyType>(); EXPECT_TRUE(error); EXPECT_TRUE(wddm->isInitialized()); } HWTEST_F(Wddm20Tests, doubleCreation) { bool error = wddm->init<FamilyType>(); EXPECT_EQ(1u, wddm->createContextResult.called); error |= wddm->init<FamilyType>(); EXPECT_EQ(1u, wddm->createContextResult.called); EXPECT_TRUE(error); EXPECT_TRUE(wddm->isInitialized()); } TEST_F(Wddm20Tests, givenNullPageTableManagerWhenUpdateAuxTableCalledThenReturnFalse) { wddm->resetPageTableManager(nullptr); EXPECT_EQ(nullptr, wddm->getPageTableManager()); auto gmm = std::unique_ptr<Gmm>(new Gmm(nullptr, 1, false)); auto mockGmmRes = reinterpret_cast<MockGmmResourceInfo *>(gmm->gmmResourceInfo.get()); mockGmmRes->setUnifiedAuxTranslationCapable(); EXPECT_FALSE(wddm->updateAuxTable(1234u, gmm.get(), true)); } TEST(Wddm20EnumAdaptersTest, expectTrue) { HardwareInfo outHwInfo; const HardwareInfo hwInfo = *platformDevices[0]; OsLibrary *mockGdiDll = setAdapterInfo(hwInfo.pPlatform, hwInfo.pSysInfo); bool success = Wddm::enumAdapters(outHwInfo); EXPECT_TRUE(success); const HardwareInfo *hwinfo = *platformDevices; ASSERT_NE(nullptr, outHwInfo.pPlatform); EXPECT_EQ(outHwInfo.pPlatform->eDisplayCoreFamily, hwinfo->pPlatform->eDisplayCoreFamily); delete mockGdiDll; delete outHwInfo.pPlatform; delete outHwInfo.pSkuTable; delete outHwInfo.pSysInfo; delete outHwInfo.pWaTable; } TEST(Wddm20EnumAdaptersTest, givenEmptyHardwareInfoWhenEnumAdapterIsCalledThenCapabilityTableIsSet) { HardwareInfo outHwInfo = {}; auto hwInfo = *platformDevices[0]; std::unique_ptr<OsLibrary> mockGdiDll(setAdapterInfo(hwInfo.pPlatform, hwInfo.pSysInfo)); bool success = Wddm::enumAdapters(outHwInfo); EXPECT_TRUE(success); const HardwareInfo *hwinfo = *platformDevices; ASSERT_NE(nullptr, outHwInfo.pPlatform); EXPECT_EQ(outHwInfo.pPlatform->eDisplayCoreFamily, hwinfo->pPlatform->eDisplayCoreFamily); EXPECT_EQ(outHwInfo.capabilityTable.defaultProfilingTimerResolution, hwInfo.capabilityTable.defaultProfilingTimerResolution); EXPECT_EQ(outHwInfo.capabilityTable.clVersionSupport, hwInfo.capabilityTable.clVersionSupport); EXPECT_EQ(outHwInfo.capabilityTable.kmdNotifyProperties.enableKmdNotify, hwInfo.capabilityTable.kmdNotifyProperties.enableKmdNotify); EXPECT_EQ(outHwInfo.capabilityTable.kmdNotifyProperties.delayKmdNotifyMicroseconds, hwInfo.capabilityTable.kmdNotifyProperties.delayKmdNotifyMicroseconds); EXPECT_EQ(outHwInfo.capabilityTable.kmdNotifyProperties.enableQuickKmdSleep, hwInfo.capabilityTable.kmdNotifyProperties.enableQuickKmdSleep); EXPECT_EQ(outHwInfo.capabilityTable.kmdNotifyProperties.delayQuickKmdSleepMicroseconds, hwInfo.capabilityTable.kmdNotifyProperties.delayQuickKmdSleepMicroseconds); delete outHwInfo.pPlatform; delete outHwInfo.pSkuTable; delete outHwInfo.pSysInfo; delete outHwInfo.pWaTable; } TEST(Wddm20EnumAdaptersTest, givenUnknownPlatformWhenEnumAdapterIsCalledThenFalseIsReturnedAndOutputIsEmpty) { HardwareInfo outHwInfo; memset(&outHwInfo, 0, sizeof(outHwInfo)); HardwareInfo hwInfo = *platformDevices[0]; auto bkp = hwInfo.pPlatform->eProductFamily; PLATFORM platform = *(hwInfo.pPlatform); platform.eProductFamily = IGFX_UNKNOWN; std::unique_ptr<OsLibrary, std::function<void(OsLibrary *)>> mockGdiDll( setAdapterInfo(&platform, hwInfo.pSysInfo), [&](OsLibrary *ptr) { platform.eProductFamily = bkp; typedef void(__stdcall * pfSetAdapterInfo)(const void *, const void *); pfSetAdapterInfo fSetAdpaterInfo = reinterpret_cast<pfSetAdapterInfo>(ptr->getProcAddress("MockSetAdapterInfo")); fSetAdpaterInfo(&platform, hwInfo.pSysInfo); delete ptr; }); bool ret = Wddm::enumAdapters(outHwInfo); EXPECT_FALSE(ret); EXPECT_EQ(nullptr, outHwInfo.pPlatform); EXPECT_EQ(nullptr, outHwInfo.pSkuTable); EXPECT_EQ(nullptr, outHwInfo.pSysInfo); EXPECT_EQ(nullptr, outHwInfo.pWaTable); } HWTEST_F(Wddm20Tests, context) { EXPECT_TRUE(wddm->getOsDeviceContext() == static_cast<D3DKMT_HANDLE>(0)); wddm->init<FamilyType>(); ASSERT_TRUE(wddm->isInitialized()); EXPECT_TRUE(wddm->createContext()); auto context = wddm->getOsDeviceContext(); EXPECT_TRUE(context != static_cast<D3DKMT_HANDLE>(0)); EXPECT_TRUE(wddm->destroyContext(context)); } HWTEST_F(Wddm20Tests, allocation) { wddm->init<FamilyType>(); ASSERT_TRUE(wddm->isInitialized()); OsAgnosticMemoryManager mm(false); WddmAllocation allocation(mm.allocateSystemMemory(100, 0), 100, nullptr); Gmm *gmm = GmmHelperFunctions::getGmm(allocation.getUnderlyingBuffer(), allocation.getUnderlyingBufferSize()); allocation.gmm = gmm; auto status = wddm->createAllocation(&allocation); EXPECT_EQ(STATUS_SUCCESS, status); EXPECT_TRUE(allocation.handle != 0); auto error = wddm->destroyAllocation(&allocation); EXPECT_TRUE(error); delete gmm; mm.freeSystemMemory(allocation.getUnderlyingBuffer()); } HWTEST_F(Wddm20WithMockGdiDllTests, givenAllocationSmallerUnderlyingThanAlignedSizeWhenCreatedThenWddmUseAligned) { wddm->init<FamilyType>(); ASSERT_TRUE(wddm->isInitialized()); void *ptr = reinterpret_cast<void *>(wddm->virtualAllocAddress + 0x1000); size_t underlyingSize = 0x2100; size_t alignedSize = 0x3000; size_t underlyingPages = underlyingSize / MemoryConstants::pageSize; size_t alignedPages = alignedSize / MemoryConstants::pageSize; WddmAllocation allocation(ptr, 0x2100, ptr, 0x3000, nullptr); Gmm *gmm = GmmHelperFunctions::getGmm(allocation.getAlignedCpuPtr(), allocation.getAlignedSize()); allocation.gmm = gmm; auto status = wddm->createAllocation(&allocation); EXPECT_EQ(STATUS_SUCCESS, status); EXPECT_NE(0, allocation.handle); bool ret = wddm->mapGpuVirtualAddress(&allocation, allocation.getAlignedCpuPtr(), allocation.getAlignedSize(), allocation.is32BitAllocation, false, false); EXPECT_TRUE(ret); EXPECT_EQ(alignedPages, getLastCallMapGpuVaArgFcn()->SizeInPages); EXPECT_NE(underlyingPages, getLastCallMapGpuVaArgFcn()->SizeInPages); ret = wddm->destroyAllocation(&allocation); EXPECT_TRUE(ret); delete gmm; } HWTEST_F(Wddm20Tests, createAllocation32bit) { wddm->init<FamilyType>(); ASSERT_TRUE(wddm->isInitialized()); uint64_t heap32baseAddress = 0x40000; uint64_t heap32Size = 0x40000; wddm->setHeap32(heap32baseAddress, heap32Size); void *alignedPtr = (void *)0x12000; size_t alignedSize = 0x2000; WddmAllocation allocation(alignedPtr, alignedSize, nullptr); Gmm *gmm = GmmHelperFunctions::getGmm(allocation.getUnderlyingBuffer(), allocation.getUnderlyingBufferSize()); allocation.gmm = gmm; allocation.is32BitAllocation = true; // mark 32 bit allocation auto status = wddm->createAllocation(&allocation); EXPECT_EQ(STATUS_SUCCESS, status); EXPECT_TRUE(allocation.handle != 0); bool ret = wddm->mapGpuVirtualAddress(&allocation, allocation.getAlignedCpuPtr(), allocation.getAlignedSize(), allocation.is32BitAllocation, false, false); EXPECT_TRUE(ret); EXPECT_EQ(1u, wddm->mapGpuVirtualAddressResult.called); EXPECT_LE(heap32baseAddress, allocation.gpuPtr); EXPECT_GT(heap32baseAddress + heap32Size, allocation.gpuPtr); auto success = wddm->destroyAllocation(&allocation); EXPECT_TRUE(success); delete gmm; } HWTEST_F(Wddm20Tests, givenGraphicsAllocationWhenItIsMappedInHeap1ThenItHasGpuAddressWithingHeap1Limits) { wddm->init<FamilyType>(); void *alignedPtr = (void *)0x12000; size_t alignedSize = 0x2000; WddmAllocation allocation(alignedPtr, alignedSize, nullptr); allocation.handle = ALLOCATION_HANDLE; allocation.gmm = GmmHelperFunctions::getGmm(allocation.getUnderlyingBuffer(), allocation.getUnderlyingBufferSize()); bool ret = wddm->mapGpuVirtualAddress(&allocation, allocation.getAlignedCpuPtr(), allocation.getAlignedSize(), false, false, true); EXPECT_TRUE(ret); auto cannonizedHeapBase = GmmHelper::canonize(this->wddm->getGfxPartition().Heap32[1].Base); auto cannonizedHeapEnd = GmmHelper::canonize(this->wddm->getGfxPartition().Heap32[1].Limit); EXPECT_GE(allocation.gpuPtr, cannonizedHeapBase); EXPECT_LE(allocation.gpuPtr, cannonizedHeapEnd); delete allocation.gmm; } HWTEST_F(Wddm20WithMockGdiDllTests, GivenThreeOsHandlesWhenAskedForDestroyAllocationsThenAllMarkedAllocationsAreDestroyed) { EXPECT_TRUE(wddm->init<FamilyType>()); OsHandleStorage storage; OsHandle osHandle1 = {0}; OsHandle osHandle2 = {0}; OsHandle osHandle3 = {0}; osHandle1.handle = ALLOCATION_HANDLE; osHandle2.handle = ALLOCATION_HANDLE; osHandle3.handle = ALLOCATION_HANDLE; storage.fragmentStorageData[0].osHandleStorage = &osHandle1; storage.fragmentStorageData[0].freeTheFragment = true; storage.fragmentStorageData[1].osHandleStorage = &osHandle2; storage.fragmentStorageData[1].freeTheFragment = false; storage.fragmentStorageData[2].osHandleStorage = &osHandle3; storage.fragmentStorageData[2].freeTheFragment = true; D3DKMT_HANDLE handles[3] = {ALLOCATION_HANDLE, ALLOCATION_HANDLE, ALLOCATION_HANDLE}; bool retVal = wddm->destroyAllocations(handles, 3, 0, 0); EXPECT_TRUE(retVal); auto destroyWithResourceHandleCalled = 0u; D3DKMT_DESTROYALLOCATION2 *ptrToDestroyAlloc2 = nullptr; getSizesFcn(destroyWithResourceHandleCalled, ptrToDestroyAlloc2); EXPECT_EQ(0u, ptrToDestroyAlloc2->Flags.SynchronousDestroy); EXPECT_EQ(1u, ptrToDestroyAlloc2->Flags.AssumeNotInUse); } HWTEST_F(Wddm20Tests, mapAndFreeGpuVa) { wddm->init<FamilyType>(); ASSERT_TRUE(wddm->isInitialized()); OsAgnosticMemoryManager mm(false); WddmAllocation allocation(mm.allocateSystemMemory(100, 0), 100, nullptr); Gmm *gmm = GmmHelperFunctions::getGmm(allocation.getUnderlyingBuffer(), allocation.getUnderlyingBufferSize()); allocation.gmm = gmm; auto status = wddm->createAllocation(&allocation); EXPECT_EQ(STATUS_SUCCESS, status); EXPECT_TRUE(allocation.handle != 0); auto error = wddm->mapGpuVirtualAddress(&allocation, allocation.getAlignedCpuPtr(), allocation.getUnderlyingBufferSize(), false, false, false); EXPECT_TRUE(error); EXPECT_TRUE(allocation.gpuPtr != 0); error = wddm->freeGpuVirtualAddres(allocation.gpuPtr, allocation.getUnderlyingBufferSize()); EXPECT_TRUE(error); EXPECT_TRUE(allocation.gpuPtr == 0); error = wddm->destroyAllocation(&allocation); EXPECT_TRUE(error); delete gmm; mm.freeSystemMemory(allocation.getUnderlyingBuffer()); } HWTEST_F(Wddm20Tests, givenNullAllocationWhenCreateThenAllocateAndMap) { wddm->init<FamilyType>(); ASSERT_TRUE(wddm->isInitialized()); OsAgnosticMemoryManager mm(false); WddmAllocation allocation(nullptr, 100, nullptr); Gmm *gmm = GmmHelperFunctions::getGmm(allocation.getUnderlyingBuffer(), allocation.getUnderlyingBufferSize()); allocation.gmm = gmm; auto status = wddm->createAllocation(&allocation); EXPECT_EQ(STATUS_SUCCESS, status); bool ret = wddm->mapGpuVirtualAddress(&allocation, allocation.getAlignedCpuPtr(), allocation.getAlignedSize(), allocation.is32BitAllocation, false, false); EXPECT_TRUE(ret); EXPECT_NE(0u, allocation.gpuPtr); EXPECT_EQ(allocation.gpuPtr, GmmHelper::canonize(allocation.gpuPtr)); delete gmm; mm.freeSystemMemory(allocation.getUnderlyingBuffer()); } HWTEST_F(Wddm20Tests, makeResidentNonResident) { wddm->init<FamilyType>(); ASSERT_TRUE(wddm->isInitialized()); OsAgnosticMemoryManager mm(false); WddmAllocation allocation(mm.allocateSystemMemory(100, 0), 100, nullptr); Gmm *gmm = GmmHelperFunctions::getGmm(allocation.getUnderlyingBuffer(), allocation.getUnderlyingBufferSize()); allocation.gmm = gmm; auto status = wddm->createAllocation(&allocation); EXPECT_EQ(STATUS_SUCCESS, status); EXPECT_TRUE(allocation.handle != 0); auto error = wddm->mapGpuVirtualAddress(&allocation, allocation.getAlignedCpuPtr(), allocation.getUnderlyingBufferSize(), false, false, false); EXPECT_TRUE(error); EXPECT_TRUE(allocation.gpuPtr != 0); error = wddm->makeResident(&allocation.handle, 1, false, nullptr); EXPECT_TRUE(error); uint64_t sizeToTrim; error = wddm->evict(&allocation.handle, 1, sizeToTrim); EXPECT_TRUE(error); auto monitoredFence = wddm->getMonitoredFence(); UINT64 fenceValue = 100; monitoredFence.cpuAddress = &fenceValue; monitoredFence.currentFenceValue = 101; error = wddm->destroyAllocation(&allocation); EXPECT_TRUE(error); delete gmm; mm.freeSystemMemory(allocation.getUnderlyingBuffer()); } TEST_F(Wddm20Tests, GetCpuTime) { uint64_t time = 0; std::unique_ptr<OSTime> osTime(OSTime::create(nullptr).release()); auto error = osTime->getCpuTime(&time); EXPECT_TRUE(error); EXPECT_NE(0, time); } TEST_F(Wddm20Tests, GivenNoOSInterfaceGetCpuGpuTimeReturnsError) { TimeStampData CPUGPUTime = {0}; std::unique_ptr<OSTime> osTime(OSTime::create(nullptr).release()); auto success = osTime->getCpuGpuTime(&CPUGPUTime); EXPECT_FALSE(success); EXPECT_EQ(0, CPUGPUTime.CPUTimeinNS); EXPECT_EQ(0, CPUGPUTime.GPUTimeStamp); } TEST_F(Wddm20Tests, GetCpuGpuTime) { TimeStampData CPUGPUTime01 = {0}; TimeStampData CPUGPUTime02 = {0}; std::unique_ptr<OSInterface> osInterface(new OSInterface()); osInterface->get()->setWddm(wddm.get()); std::unique_ptr<OSTime> osTime(OSTime::create(osInterface.get()).release()); auto success = osTime->getCpuGpuTime(&CPUGPUTime01); EXPECT_TRUE(success); EXPECT_NE(0, CPUGPUTime01.CPUTimeinNS); EXPECT_NE(0, CPUGPUTime01.GPUTimeStamp); success = osTime->getCpuGpuTime(&CPUGPUTime02); EXPECT_TRUE(success); EXPECT_NE(0, CPUGPUTime02.CPUTimeinNS); EXPECT_NE(0, CPUGPUTime02.GPUTimeStamp); EXPECT_GT(CPUGPUTime02.GPUTimeStamp, CPUGPUTime01.GPUTimeStamp); EXPECT_GT(CPUGPUTime02.CPUTimeinNS, CPUGPUTime01.CPUTimeinNS); } HWTEST_F(Wddm20WithMockGdiDllTests, givenSharedHandleWhenCreateGraphicsAllocationFromSharedHandleIsCalledThenGraphicsAllocationWithSharedPropertiesIsCreated) { void *pSysMem = (void *)0x1000; std::unique_ptr<Gmm> gmm(new Gmm(pSysMem, 4096u, false)); auto status = setSizesFcn(gmm->gmmResourceInfo.get(), 1u, 1024u, 1u); EXPECT_EQ(0u, status); wddm->init<FamilyType>(); WddmMemoryManager mm(false, wddm.release()); auto graphicsAllocation = mm.createGraphicsAllocationFromSharedHandle(ALLOCATION_HANDLE, false, false); auto wddmAllocation = (WddmAllocation *)graphicsAllocation; ASSERT_NE(nullptr, wddmAllocation); EXPECT_EQ(ALLOCATION_HANDLE, wddmAllocation->peekSharedHandle()); EXPECT_EQ(RESOURCE_HANDLE, wddmAllocation->resourceHandle); EXPECT_NE(0u, wddmAllocation->handle); EXPECT_EQ(ALLOCATION_HANDLE, wddmAllocation->handle); EXPECT_NE(0u, wddmAllocation->getGpuAddress()); EXPECT_EQ(wddmAllocation->gpuPtr, wddmAllocation->getGpuAddress()); EXPECT_EQ(4096u, wddmAllocation->getUnderlyingBufferSize()); EXPECT_EQ(nullptr, wddmAllocation->getAlignedCpuPtr()); EXPECT_NE(nullptr, wddmAllocation->gmm); EXPECT_EQ(4096u, wddmAllocation->gmm->gmmResourceInfo->getSizeAllocation()); mm.freeGraphicsMemory(graphicsAllocation); auto destroyWithResourceHandleCalled = 0u; D3DKMT_DESTROYALLOCATION2 *ptrToDestroyAlloc2 = nullptr; status = getSizesFcn(destroyWithResourceHandleCalled, ptrToDestroyAlloc2); EXPECT_EQ(0u, ptrToDestroyAlloc2->Flags.SynchronousDestroy); EXPECT_EQ(1u, ptrToDestroyAlloc2->Flags.AssumeNotInUse); EXPECT_EQ(0u, status); EXPECT_EQ(1u, destroyWithResourceHandleCalled); } HWTEST_F(Wddm20WithMockGdiDllTests, givenSharedHandleWhenCreateGraphicsAllocationFromSharedHandleIsCalledThenMapGpuVaWithCpuPtrDepensOnBitness) { void *pSysMem = (void *)0x1000; std::unique_ptr<Gmm> gmm(new Gmm(pSysMem, 4096u, false)); auto status = setSizesFcn(gmm->gmmResourceInfo.get(), 1u, 1024u, 1u); EXPECT_EQ(0u, status); auto mockWddm = wddm.release(); mockWddm->init<FamilyType>(); WddmMemoryManager mm(false, mockWddm); auto graphicsAllocation = mm.createGraphicsAllocationFromSharedHandle(ALLOCATION_HANDLE, false, false); auto wddmAllocation = (WddmAllocation *)graphicsAllocation; ASSERT_NE(nullptr, wddmAllocation); if (is32bit) { EXPECT_NE(mockWddm->mapGpuVirtualAddressResult.cpuPtrPassed, nullptr); } else { EXPECT_EQ(mockWddm->mapGpuVirtualAddressResult.cpuPtrPassed, nullptr); } mm.freeGraphicsMemory(graphicsAllocation); } HWTEST_F(Wddm20Tests, givenWddmCreatedWhenNotInitedThenMinAddressZero) { uintptr_t expected = 0; uintptr_t actual = wddm->getWddmMinAddress(); EXPECT_EQ(expected, actual); } HWTEST_F(Wddm20Tests, givenWddmCreatedWhenInitedThenMinAddressValid) { bool ret = wddm->init<FamilyType>(); EXPECT_TRUE(ret); uintptr_t expected = windowsMinAddress; uintptr_t actual = wddm->getWddmMinAddress(); EXPECT_EQ(expected, actual); } HWTEST_F(Wddm20InstrumentationTest, configureDeviceAddressSpaceOnInit) { SYSTEM_INFO sysInfo = {}; WddmMock::getSystemInfo(&sysInfo); uintptr_t maxAddr = reinterpret_cast<uintptr_t>(sysInfo.lpMaximumApplicationAddress) + 1; D3DKMT_HANDLE adapterHandle = ADAPTER_HANDLE; D3DKMT_HANDLE deviceHandle = DEVICE_HANDLE; const HardwareInfo hwInfo = *platformDevices[0]; ExecutionEnvironment execEnv; execEnv.initGmm(&hwInfo); BOOLEAN FtrL3IACoherency = hwInfo.pSkuTable->ftrL3IACoherency ? 1 : 0; EXPECT_CALL(*gmmMem, configureDeviceAddressSpace(adapterHandle, deviceHandle, wddm->gdi->escape.mFunc, maxAddr, 0, 0, FtrL3IACoherency, 0, 0)) .Times(1) .WillRepeatedly(::testing::Return(true)); wddm->init<FamilyType>(); EXPECT_TRUE(wddm->isInitialized()); } HWTEST_F(Wddm20InstrumentationTest, configureDeviceAddressSpaceNoAdapter) { wddm->adapter = static_cast<D3DKMT_HANDLE>(0); ExecutionEnvironment execEnv; execEnv.initGmm(*platformDevices); EXPECT_CALL(*gmmMem, configureDeviceAddressSpace(static_cast<D3DKMT_HANDLE>(0), ::testing::_, ::testing::_, ::testing::_, ::testing::_, ::testing::_, ::testing::_, ::testing::_, ::testing::_)) .Times(1) .WillRepeatedly(::testing::Return(false)); auto ret = wddm->configureDeviceAddressSpace<FamilyType>(); EXPECT_FALSE(ret); } HWTEST_F(Wddm20InstrumentationTest, configureDeviceAddressSpaceNoDevice) { wddm->device = static_cast<D3DKMT_HANDLE>(0); ExecutionEnvironment execEnv; execEnv.initGmm(*platformDevices); EXPECT_CALL(*gmmMem, configureDeviceAddressSpace(::testing::_, static_cast<D3DKMT_HANDLE>(0), ::testing::_, ::testing::_, ::testing::_, ::testing::_, ::testing::_, ::testing::_, ::testing::_)) .Times(1) .WillRepeatedly(::testing::Return(false)); auto ret = wddm->configureDeviceAddressSpace<FamilyType>(); EXPECT_FALSE(ret); } HWTEST_F(Wddm20InstrumentationTest, configureDeviceAddressSpaceNoEscFunc) { wddm->gdi->escape = static_cast<PFND3DKMT_ESCAPE>(nullptr); ExecutionEnvironment execEnv; execEnv.initGmm(*platformDevices); EXPECT_CALL(*gmmMem, configureDeviceAddressSpace(::testing::_, ::testing::_, static_cast<PFND3DKMT_ESCAPE>(nullptr), ::testing::_, ::testing::_, ::testing::_, ::testing::_, ::testing::_, ::testing::_)) .Times(1) .WillRepeatedly(::testing::Return(false)); auto ret = wddm->configureDeviceAddressSpace<FamilyType>(); EXPECT_FALSE(ret); } HWTEST_F(Wddm20Tests, getMaxApplicationAddress) { wddm->init<FamilyType>(); EXPECT_TRUE(wddm->isInitialized()); uint64_t maxAddr = wddm->getMaxApplicationAddress(); if (is32bit) { EXPECT_EQ(maxAddr, MemoryConstants::max32BitAppAddress); } else { EXPECT_EQ(maxAddr, MemoryConstants::max64BitAppAddress); } } HWTEST_F(Wddm20Tests, dontCallCreateContextBeforeConfigureDeviceAddressSpace) { wddm->createContext(); EXPECT_EQ(1u, wddm->createContextResult.called); // dont care about the result wddm->configureDeviceAddressSpace<FamilyType>(); EXPECT_EQ(1u, wddm->configureDeviceAddressSpaceResult.called); EXPECT_FALSE(wddm->configureDeviceAddressSpaceResult.success); } HWTEST_F(Wddm20WithMockGdiDllTests, givenUseNoRingFlushesKmdModeDebugFlagToFalseWhenCreateContextIsCalledThenNoRingFlushesKmdModeIsSetToFalse) { DebugManagerStateRestore dbgRestore; DebugManager.flags.UseNoRingFlushesKmdMode.set(false); wddm->init<FamilyType>(); auto createContextParams = this->getCreateContextDataFcn(); auto privateData = (CREATECONTEXT_PVTDATA *)createContextParams->pPrivateDriverData; EXPECT_FALSE(!!privateData->NoRingFlushes); } HWTEST_F(Wddm20WithMockGdiDllTests, givenUseNoRingFlushesKmdModeDebugFlagToTrueWhenCreateContextIsCalledThenNoRingFlushesKmdModeIsSetToTrue) { DebugManagerStateRestore dbgRestore; DebugManager.flags.UseNoRingFlushesKmdMode.set(true); wddm->init<FamilyType>(); auto createContextParams = this->getCreateContextDataFcn(); auto privateData = (CREATECONTEXT_PVTDATA *)createContextParams->pPrivateDriverData; EXPECT_TRUE(!!privateData->NoRingFlushes); } HWTEST_F(Wddm20WithMockGdiDllTests, whenCreateContextIsCalledThenDisableHwQueues) { wddm->init<FamilyType>(); EXPECT_FALSE(wddm->hwQueuesSupported()); EXPECT_EQ(0u, getCreateContextDataFcn()->Flags.HwQueueSupported); } TEST_F(Wddm20Tests, whenCreateHwQueueIsCalledThenAlwaysReturnFalse) { EXPECT_FALSE(wddm->createHwQueue()); } HWTEST_F(Wddm20Tests, whenInitCalledThenDontCallToCreateHwQueue) { wddm->init<FamilyType>(); EXPECT_EQ(0u, wddm->createHwQueueResult.called); } HWTEST_F(Wddm20Tests, whenWddmIsInitializedThenGdiDoesntHaveHwQueueDDIs) { wddm->init<FamilyType>(); EXPECT_EQ(nullptr, wddm->gdi->createHwQueue.mFunc); EXPECT_EQ(nullptr, wddm->gdi->destroyHwQueue.mFunc); EXPECT_EQ(nullptr, wddm->gdi->submitCommandToHwQueue.mFunc); } HWTEST_F(Wddm20Tests, givenDebugManagerWhenGetForUseNoRingFlushesKmdModeIsCalledThenTrueIsReturned) { EXPECT_TRUE(DebugManager.flags.UseNoRingFlushesKmdMode.get()); } HWTEST_F(Wddm20Tests, makeResidentMultipleHandles) { wddm->init<FamilyType>(); ASSERT_TRUE(wddm->isInitialized()); OsAgnosticMemoryManager mm(false); WddmAllocation allocation(mm.allocateSystemMemory(100, 0), 100, nullptr); allocation.handle = ALLOCATION_HANDLE; D3DKMT_HANDLE handles[2] = {0}; handles[0] = allocation.handle; handles[1] = allocation.handle; gdi->getMakeResidentArg().NumAllocations = 0; gdi->getMakeResidentArg().AllocationList = nullptr; bool error = wddm->makeResident(handles, 2, false, nullptr); EXPECT_TRUE(error); EXPECT_EQ(2u, gdi->getMakeResidentArg().NumAllocations); EXPECT_EQ(handles, gdi->getMakeResidentArg().AllocationList); mm.freeSystemMemory(allocation.getUnderlyingBuffer()); } HWTEST_F(Wddm20Tests, makeResidentMultipleHandlesWithReturnBytesToTrim) { wddm->init<FamilyType>(); ASSERT_TRUE(wddm->isInitialized()); OsAgnosticMemoryManager mm(false); WddmAllocation allocation(mm.allocateSystemMemory(100, 0), 100, nullptr); allocation.handle = ALLOCATION_HANDLE; D3DKMT_HANDLE handles[2] = {0}; handles[0] = allocation.handle; handles[1] = allocation.handle; gdi->getMakeResidentArg().NumAllocations = 0; gdi->getMakeResidentArg().AllocationList = nullptr; gdi->getMakeResidentArg().NumBytesToTrim = 30; uint64_t bytesToTrim = 0; bool success = wddm->makeResident(handles, 2, false, &bytesToTrim); EXPECT_TRUE(success); EXPECT_EQ(gdi->getMakeResidentArg().NumBytesToTrim, bytesToTrim); mm.freeSystemMemory(allocation.getUnderlyingBuffer()); } HWTEST_F(Wddm20Tests, makeNonResidentCallsEvict) { wddm->init<FamilyType>(); D3DKMT_HANDLE handle = (D3DKMT_HANDLE)0x1234; gdi->getEvictArg().AllocationList = nullptr; gdi->getEvictArg().Flags.Value = 0; gdi->getEvictArg().hDevice = 0; gdi->getEvictArg().NumAllocations = 0; gdi->getEvictArg().NumBytesToTrim = 20; uint64_t sizeToTrim = 10; wddm->evict(&handle, 1, sizeToTrim); EXPECT_EQ(1u, gdi->getEvictArg().NumAllocations); EXPECT_EQ(&handle, gdi->getEvictArg().AllocationList); EXPECT_EQ(wddm->getDevice(), gdi->getEvictArg().hDevice); EXPECT_EQ(0u, gdi->getEvictArg().NumBytesToTrim); } HWTEST_F(Wddm20Tests, destroyAllocationWithLastFenceValueGreaterThanCurrentValueCallsWaitFromCpu) { wddm->init<FamilyType>(); WddmAllocation allocation((void *)0x23000, 0x1000, nullptr); allocation.getResidencyData().lastFence = 20; allocation.handle = ALLOCATION_HANDLE; *wddm->getMonitoredFence().cpuAddress = 10; D3DKMT_HANDLE handle = (D3DKMT_HANDLE)0x1234; gdi->getWaitFromCpuArg().FenceValueArray = nullptr; gdi->getWaitFromCpuArg().Flags.Value = 0; gdi->getWaitFromCpuArg().hDevice = (D3DKMT_HANDLE)0; gdi->getWaitFromCpuArg().ObjectCount = 0; gdi->getWaitFromCpuArg().ObjectHandleArray = nullptr; gdi->getDestroyArg().AllocationCount = 0; gdi->getDestroyArg().Flags.Value = 0; gdi->getDestroyArg().hDevice = (D3DKMT_HANDLE)0; gdi->getDestroyArg().hResource = (D3DKMT_HANDLE)0; gdi->getDestroyArg().phAllocationList = nullptr; wddm->destroyAllocation(&allocation); EXPECT_NE(nullptr, gdi->getWaitFromCpuArg().FenceValueArray); EXPECT_EQ(wddm->getDevice(), gdi->getWaitFromCpuArg().hDevice); EXPECT_EQ(1u, gdi->getWaitFromCpuArg().ObjectCount); EXPECT_EQ(&wddm->getMonitoredFence().fenceHandle, gdi->getWaitFromCpuArg().ObjectHandleArray); EXPECT_EQ(wddm->getDevice(), gdi->getDestroyArg().hDevice); EXPECT_EQ(1u, gdi->getDestroyArg().AllocationCount); EXPECT_NE(nullptr, gdi->getDestroyArg().phAllocationList); } HWTEST_F(Wddm20Tests, destroyAllocationWithLastFenceValueLessEqualToCurrentValueDoesNotCallWaitFromCpu) { wddm->init<FamilyType>(); WddmAllocation allocation((void *)0x23000, 0x1000, nullptr); allocation.getResidencyData().lastFence = 10; allocation.handle = ALLOCATION_HANDLE; *wddm->getMonitoredFence().cpuAddress = 10; D3DKMT_HANDLE handle = (D3DKMT_HANDLE)0x1234; gdi->getWaitFromCpuArg().FenceValueArray = nullptr; gdi->getWaitFromCpuArg().Flags.Value = 0; gdi->getWaitFromCpuArg().hDevice = (D3DKMT_HANDLE)0; gdi->getWaitFromCpuArg().ObjectCount = 0; gdi->getWaitFromCpuArg().ObjectHandleArray = nullptr; gdi->getDestroyArg().AllocationCount = 0; gdi->getDestroyArg().Flags.Value = 0; gdi->getDestroyArg().hDevice = (D3DKMT_HANDLE)0; gdi->getDestroyArg().hResource = (D3DKMT_HANDLE)0; gdi->getDestroyArg().phAllocationList = nullptr; wddm->destroyAllocation(&allocation); EXPECT_EQ(nullptr, gdi->getWaitFromCpuArg().FenceValueArray); EXPECT_EQ((D3DKMT_HANDLE)0, gdi->getWaitFromCpuArg().hDevice); EXPECT_EQ(0u, gdi->getWaitFromCpuArg().ObjectCount); EXPECT_EQ(nullptr, gdi->getWaitFromCpuArg().ObjectHandleArray); EXPECT_EQ(wddm->getDevice(), gdi->getDestroyArg().hDevice); EXPECT_EQ(1u, gdi->getDestroyArg().AllocationCount); EXPECT_NE(nullptr, gdi->getDestroyArg().phAllocationList); } HWTEST_F(Wddm20Tests, WhenLastFenceLessEqualThanMonitoredThenWaitFromCpuIsNotCalled) { wddm->init<FamilyType>(); WddmAllocation allocation((void *)0x23000, 0x1000, nullptr); allocation.getResidencyData().lastFence = 10; allocation.handle = ALLOCATION_HANDLE; *wddm->getMonitoredFence().cpuAddress = 10; gdi->getWaitFromCpuArg().FenceValueArray = nullptr; gdi->getWaitFromCpuArg().Flags.Value = 0; gdi->getWaitFromCpuArg().hDevice = (D3DKMT_HANDLE)0; gdi->getWaitFromCpuArg().ObjectCount = 0; gdi->getWaitFromCpuArg().ObjectHandleArray = nullptr; auto status = wddm->waitFromCpu(10); EXPECT_TRUE(status); EXPECT_EQ(nullptr, gdi->getWaitFromCpuArg().FenceValueArray); EXPECT_EQ((D3DKMT_HANDLE)0, gdi->getWaitFromCpuArg().hDevice); EXPECT_EQ(0u, gdi->getWaitFromCpuArg().ObjectCount); EXPECT_EQ(nullptr, gdi->getWaitFromCpuArg().ObjectHandleArray); } HWTEST_F(Wddm20Tests, WhenLastFenceGreaterThanMonitoredThenWaitFromCpuIsCalled) { wddm->init<FamilyType>(); WddmAllocation allocation((void *)0x23000, 0x1000, nullptr); allocation.getResidencyData().lastFence = 10; allocation.handle = ALLOCATION_HANDLE; *wddm->getMonitoredFence().cpuAddress = 10; gdi->getWaitFromCpuArg().FenceValueArray = nullptr; gdi->getWaitFromCpuArg().Flags.Value = 0; gdi->getWaitFromCpuArg().hDevice = (D3DKMT_HANDLE)0; gdi->getWaitFromCpuArg().ObjectCount = 0; gdi->getWaitFromCpuArg().ObjectHandleArray = nullptr; auto status = wddm->waitFromCpu(20); EXPECT_TRUE(status); EXPECT_NE(nullptr, gdi->getWaitFromCpuArg().FenceValueArray); EXPECT_EQ((D3DKMT_HANDLE)wddm->getDevice(), gdi->getWaitFromCpuArg().hDevice); EXPECT_EQ(1u, gdi->getWaitFromCpuArg().ObjectCount); EXPECT_NE(nullptr, gdi->getWaitFromCpuArg().ObjectHandleArray); } HWTEST_F(Wddm20Tests, createMonitoredFenceIsInitializedWithFenceValueZeroAndCurrentFenceValueIsSetToOne) { wddm->init<FamilyType>(); gdi->createSynchronizationObject2 = gdi->createSynchronizationObject2Mock; gdi->getCreateSynchronizationObject2Arg().Info.MonitoredFence.InitialFenceValue = 300; wddm->createMonitoredFence(); EXPECT_EQ(0u, gdi->getCreateSynchronizationObject2Arg().Info.MonitoredFence.InitialFenceValue); EXPECT_EQ(1u, wddm->getMonitoredFence().currentFenceValue); } NTSTATUS APIENTRY queryResourceInfoMock(D3DKMT_QUERYRESOURCEINFO *pData) { pData->NumAllocations = 0; return 0; } HWTEST_F(Wddm20Tests, givenOpenSharedHandleWhenZeroAllocationsThenReturnNull) { wddm->init<FamilyType>(); D3DKMT_HANDLE handle = 0; WddmAllocation *alloc = nullptr; gdi->queryResourceInfo = reinterpret_cast<PFND3DKMT_QUERYRESOURCEINFO>(queryResourceInfoMock); auto ret = wddm->openSharedHandle(handle, alloc); EXPECT_EQ(false, ret); } HWTEST_F(Wddm20Tests, givenReadOnlyMemoryWhenCreateAllocationFailsWithNoVideoMemoryThenCorrectStatusIsReturned) { class MockCreateAllocation { public: static NTSTATUS APIENTRY mockCreateAllocation(D3DKMT_CREATEALLOCATION *param) { return STATUS_GRAPHICS_NO_VIDEO_MEMORY; }; }; gdi->createAllocation = MockCreateAllocation::mockCreateAllocation; wddm->init<FamilyType>(); OsHandleStorage handleStorage; OsHandle handle = {0}; ResidencyData residency; handleStorage.fragmentCount = 1; handleStorage.fragmentStorageData[0].cpuPtr = (void *)0x1000; handleStorage.fragmentStorageData[0].fragmentSize = 0x1000; handleStorage.fragmentStorageData[0].freeTheFragment = false; handleStorage.fragmentStorageData[0].osHandleStorage = &handle; handleStorage.fragmentStorageData[0].residency = &residency; handleStorage.fragmentStorageData[0].osHandleStorage->gmm = GmmHelperFunctions::getGmm(nullptr, 0); NTSTATUS result = wddm->createAllocationsAndMapGpuVa(handleStorage); EXPECT_EQ(STATUS_GRAPHICS_NO_VIDEO_MEMORY, result); delete handleStorage.fragmentStorageData[0].osHandleStorage->gmm; } HWTEST_F(Wddm20Tests, whenGetOsDeviceContextIsCalledThenWddmOsDeviceContextIsReturned) { D3DKMT_HANDLE ctx = 0xc1; wddm->context = ctx; EXPECT_EQ(ctx, wddm->getOsDeviceContext()); }
38.895187
167
0.718921
jdanecki
d7270870006c2211dd2a228cf7cf92408265ad29
218
hpp
C++
app/world/GroundType.hpp
isonil/survival
ecb59af9fcbb35b9c28fd4fe29a4628f046165c8
[ "MIT" ]
1
2017-05-12T10:12:41.000Z
2017-05-12T10:12:41.000Z
app/world/GroundType.hpp
isonil/Survival
ecb59af9fcbb35b9c28fd4fe29a4628f046165c8
[ "MIT" ]
null
null
null
app/world/GroundType.hpp
isonil/Survival
ecb59af9fcbb35b9c28fd4fe29a4628f046165c8
[ "MIT" ]
1
2019-01-09T04:05:36.000Z
2019-01-09T04:05:36.000Z
#ifndef APP_GROUND_TYPE_HPP #define APP_GROUND_TYPE_HPP namespace app { enum class GroundType { Ground1, Ground2, Ground3, Slope, UnderWater }; } // namespace app #endif // APP_GROUND_TYPE_HPP
10.9
29
0.701835
isonil
d727d30ca9f1dd4fe28f34e093e93adb1eb79fd5
2,365
cpp
C++
SDK/g100IO/G100Config.cpp
mariusl/step2mach
3ac7ff6c3b29a25f4520e4325e7922f2d34c547a
[ "MIT" ]
6
2019-05-22T03:18:38.000Z
2022-02-07T20:54:38.000Z
SDK/g100IO/G100Config.cpp
mariusl/step2mach
3ac7ff6c3b29a25f4520e4325e7922f2d34c547a
[ "MIT" ]
1
2019-11-10T05:57:09.000Z
2020-07-01T05:50:49.000Z
SDK/g100IO/G100Config.cpp
mariusl/step2mach
3ac7ff6c3b29a25f4520e4325e7922f2d34c547a
[ "MIT" ]
9
2019-05-20T06:03:55.000Z
2022-02-01T10:16:41.000Z
// G100Config.cpp : implementation file // #include "stdafx.h" #include "resource.h" #include "MachDevice.h" #include "G100Config.h" #include "G100-Structs.h" #include ".\g100config.h" #include "LocalIPQuery.h" #include "GRexControl.h" extern GRexControl *TheRex; bool Exit; // G100Config dialog IMPLEMENT_DYNAMIC(G100Config, CDialog) G100Config::G100Config(CWnd* pParent /*=NULL*/) : CDialog(G100Config::IDD, pParent) , m_Error(_T("")) , m_Perm(FALSE) { Exit = false; } G100Config::~G100Config() { } void G100Config::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_IPG100, m_G100IP); DDX_Control(pDX, IDC_NMG100, m_G100NM); DDX_Control(pDX, IDC_MYIP, m_MyIP); DDX_Text(pDX, IDC_ERRORS, m_Error); } BEGIN_MESSAGE_MAP(G100Config, CDialog) ON_BN_CLICKED(IDC_SENDNEW, OnBnClickedSendnew) ON_BN_CLICKED(IDOK, OnBnClickedOk) ON_BN_CLICKED(IDC_BUTTON2, OnBnClickedButton2) END_MESSAGE_MAP() // G100Config message handlers BOOL G100Config::OnInitDialog() { CDialog::OnInitDialog(); //Lets show what we have recieved so far in terms of G100 Address. unsigned ipaddr, netmask; if (!TheRex->ge || !TheRex->ge->getIP(TheRex->inst, ipaddr, netmask)) ipaddr = netmask = 0; m_G100IP.SetAddress(ipaddr); m_G100NM.SetAddress(netmask); //now lets get ours.. LocalIPQuery LocalMachine; //setup a localIp search class // Search for an address which is _not_ 127.**** //FIXME: should display a list of addresses to do this properly. DWORD test; for (unsigned i = 0; i < LocalMachine.m_vIPAddress.size(); ++i) { test = (LocalMachine.m_vIPAddress[LocalMachine.m_vIPAddress.size()-1].GetNBO()); if ((test & 0xFF) != 127) break; } m_MyIP.SetAddress(test); m_Error = TheRex->Disability; UpdateData( false ); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void G100Config::OnBnClickedSendnew() { UpdateData( true ); DWORD data; m_G100IP.GetAddress( data ); unsigned ipaddr = (unsigned)data; m_G100NM.GetAddress( data); unsigned netmask = (unsigned)data; TheRex->ge->setIP(TheRex->inst, ipaddr, netmask); TheRex->PHASE = SETIP; UpdateData( false ); } void G100Config::OnBnClickedOk() { if( !Exit ) { TheRex->PHASE = DISCOVERY; } OnOK(); } void G100Config::OnBnClickedButton2() { Exit = true; OnOK(); }
22.102804
82
0.725159
mariusl
c01189bfa268345d7efc4e5b5e8bd462ca504e3b
443
cpp
C++
something-learned/Algorithms and Data-Structures/Competitive-programming-library/CP/codechef/April Challenge 17/ROWSOLD.cpp
gopala-kr/CR-101
dd27b767cdc0c667655ab8e32e020ed4248bd112
[ "MIT" ]
5
2018-05-09T04:02:04.000Z
2021-02-21T19:27:56.000Z
something-learned/Algorithms and Data-Structures/Competitive-programming-library/CP/codechef/April Challenge 17/ROWSOLD.cpp
gopala-kr/CR-101
dd27b767cdc0c667655ab8e32e020ed4248bd112
[ "MIT" ]
null
null
null
something-learned/Algorithms and Data-Structures/Competitive-programming-library/CP/codechef/April Challenge 17/ROWSOLD.cpp
gopala-kr/CR-101
dd27b767cdc0c667655ab8e32e020ed4248bd112
[ "MIT" ]
5
2018-02-23T22:08:28.000Z
2020-08-19T08:31:47.000Z
#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { long long ans= 0; long long no = 0; string x; cin>>x; long long streak = 0; for(long i=0;i<x.size();i++) { if(x[i] == '1') { if(streak != 0){ ans += no; ans += no*streak; } no++; streak = 0; } else streak++; } if(streak != 0){ ans += no; ans += no*streak; } cout<<ans<<endl; } return 0; }
14.766667
32
0.476298
gopala-kr
c01240b42907caa001f23783aeaea04a8a9633d1
4,736
hpp
C++
rclcpp/include/rclcpp/experimental/buffers/ring_buffer_implementation.hpp
hemalshahNV/rclcpp
bca3fd7da18e779a6c1aee118440c962503ee6b2
[ "Apache-2.0" ]
1
2022-02-28T21:29:12.000Z
2022-02-28T21:29:12.000Z
rclcpp/include/rclcpp/experimental/buffers/ring_buffer_implementation.hpp
stokekld/rclcpp
025cd5ccc8202a52f7c7a3f037d8faf46f7dc3f3
[ "Apache-2.0" ]
null
null
null
rclcpp/include/rclcpp/experimental/buffers/ring_buffer_implementation.hpp
stokekld/rclcpp
025cd5ccc8202a52f7c7a3f037d8faf46f7dc3f3
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef RCLCPP__EXPERIMENTAL__BUFFERS__RING_BUFFER_IMPLEMENTATION_HPP_ #define RCLCPP__EXPERIMENTAL__BUFFERS__RING_BUFFER_IMPLEMENTATION_HPP_ #include <mutex> #include <stdexcept> #include <utility> #include <vector> #include "rclcpp/experimental/buffers/buffer_implementation_base.hpp" #include "rclcpp/logger.hpp" #include "rclcpp/logging.hpp" #include "rclcpp/macros.hpp" #include "rclcpp/visibility_control.hpp" namespace rclcpp { namespace experimental { namespace buffers { /// Store elements in a fixed-size, FIFO buffer /** * All public member functions are thread-safe. */ template<typename BufferT> class RingBufferImplementation : public BufferImplementationBase<BufferT> { public: explicit RingBufferImplementation(size_t capacity) : capacity_(capacity), ring_buffer_(capacity), write_index_(capacity_ - 1), read_index_(0), size_(0) { if (capacity == 0) { throw std::invalid_argument("capacity must be a positive, non-zero value"); } } virtual ~RingBufferImplementation() {} /// Add a new element to store in the ring buffer /** * This member function is thread-safe. * * \param request the element to be stored in the ring buffer */ void enqueue(BufferT request) { std::lock_guard<std::mutex> lock(mutex_); write_index_ = next_(write_index_); ring_buffer_[write_index_] = std::move(request); if (is_full_()) { read_index_ = next_(read_index_); } else { size_++; } } /// Remove the oldest element from ring buffer /** * This member function is thread-safe. * * \return the element that is being removed from the ring buffer */ BufferT dequeue() { std::lock_guard<std::mutex> lock(mutex_); if (!has_data_()) { RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "Calling dequeue on empty intra-process buffer"); throw std::runtime_error("Calling dequeue on empty intra-process buffer"); } auto request = std::move(ring_buffer_[read_index_]); read_index_ = next_(read_index_); size_--; return request; } /// Get the next index value for the ring buffer /** * This member function is thread-safe. * * \param val the current index value * \return the next index value */ inline size_t next(size_t val) { std::lock_guard<std::mutex> lock(mutex_); return next_(val); } /// Get if the ring buffer has at least one element stored /** * This member function is thread-safe. * * \return `true` if there is data and `false` otherwise */ inline bool has_data() const { std::lock_guard<std::mutex> lock(mutex_); return has_data_(); } /// Get if the size of the buffer is equal to its capacity /** * This member function is thread-safe. * * \return `true` if the size of the buffer is equal is capacity * and `false` otherwise */ inline bool is_full() const { std::lock_guard<std::mutex> lock(mutex_); return is_full_(); } void clear() {} private: /// Get the next index value for the ring buffer /** * This member function is not thread-safe. * * \param val the current index value * \return the next index value */ inline size_t next_(size_t val) { return (val + 1) % capacity_; } /// Get if the ring buffer has at least one element stored /** * This member function is not thread-safe. * * \return `true` if there is data and `false` otherwise */ inline bool has_data_() const { return size_ != 0; } /// Get if the size of the buffer is equal to its capacity /** * This member function is not thread-safe. * * \return `true` if the size of the buffer is equal is capacity * and `false` otherwise */ inline bool is_full_() const { return size_ == capacity_; } size_t capacity_; std::vector<BufferT> ring_buffer_; size_t write_index_; size_t read_index_; size_t size_; mutable std::mutex mutex_; }; } // namespace buffers } // namespace experimental } // namespace rclcpp #endif // RCLCPP__EXPERIMENTAL__BUFFERS__RING_BUFFER_IMPLEMENTATION_HPP_
24.53886
98
0.686233
hemalshahNV
c012a7bd7999d6d6041d588e6874ddeb181a9cfa
4,789
cpp
C++
wxwidgets_testMain.cpp
tsnsoft/wxwidgets_demo-linux
9717e559b10dacdd6b4c0b53367da85ad4a99b7f
[ "BSD-3-Clause" ]
5
2021-01-12T14:09:35.000Z
2021-01-13T04:18:04.000Z
wxwidgets_testMain.cpp
tsnsoft/wxwidgets_demo-linux
9717e559b10dacdd6b4c0b53367da85ad4a99b7f
[ "BSD-3-Clause" ]
null
null
null
wxwidgets_testMain.cpp
tsnsoft/wxwidgets_demo-linux
9717e559b10dacdd6b4c0b53367da85ad4a99b7f
[ "BSD-3-Clause" ]
null
null
null
/*************************************************************** * Name: wxwidgets_testMain.cpp * Purpose: Code for Application Frame * Author: tsn (talipovsn@gmail.com) * Created: 2020-02-26 * Copyright: tsn (github.com/tsnsoft) * License: **************************************************************/ #include "wxwidgets_testMain.h" #include <wx/msgdlg.h> #include <iostream> #include <sstream> #include <cmath> //(*InternalHeaders(wxwidgets_testDialog) #include <wx/font.h> #include <wx/intl.h> #include <wx/settings.h> #include <wx/string.h> //*) //helper functions enum wxbuildinfoformat { short_f, long_f }; wxString wxbuildinfo(wxbuildinfoformat format) { wxString wxbuild(wxVERSION_STRING); if (format == long_f ) { #if defined(__WXMSW__) wxbuild << _T("-Windows"); #elif defined(__UNIX__) wxbuild << _T("-Linux"); #endif #if wxUSE_UNICODE wxbuild << _T("-Unicode build"); #else wxbuild << _T("-ANSI build"); #endif // wxUSE_UNICODE } return wxbuild; } //(*IdInit(wxwidgets_testDialog) const long wxwidgets_testDialog::ID_STATICTEXT1 = wxNewId(); const long wxwidgets_testDialog::ID_STATICLINE1 = wxNewId(); const long wxwidgets_testDialog::ID_TEXTCTRL2 = wxNewId(); const long wxwidgets_testDialog::ID_TEXTCTRL1 = wxNewId(); const long wxwidgets_testDialog::ID_BUTTON1 = wxNewId(); const long wxwidgets_testDialog::ID_STATICTEXT3 = wxNewId(); const long wxwidgets_testDialog::ID_BUTTON2 = wxNewId(); //*) BEGIN_EVENT_TABLE(wxwidgets_testDialog,wxDialog) //(*EventTable(wxwidgets_testDialog) //*) END_EVENT_TABLE() wxwidgets_testDialog::wxwidgets_testDialog(wxWindow* parent,wxWindowID id) { //(*Initialize(wxwidgets_testDialog) Create(parent, id, _("Пример с wxWidgets"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE, _T("id")); BoxSizer1 = new wxBoxSizer(wxHORIZONTAL); StaticText1 = new wxStaticText(this, ID_STATICTEXT1, _("Я люблю\nwxWidgets !"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT1")); wxFont StaticText1Font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); if ( !StaticText1Font.Ok() ) StaticText1Font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); StaticText1Font.SetPointSize(20); StaticText1->SetFont(StaticText1Font); BoxSizer1->Add(StaticText1, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 10); BoxSizer2 = new wxBoxSizer(wxVERTICAL); StaticLine1 = new wxStaticLine(this, ID_STATICLINE1, wxDefaultPosition, wxSize(10,-1), wxLI_HORIZONTAL, _T("ID_STATICLINE1")); BoxSizer2->Add(StaticLine1, 0, wxALL|wxEXPAND, 4); TextCtrl2 = new wxTextCtrl(this, ID_TEXTCTRL2, _("0"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_TEXTCTRL2")); BoxSizer2->Add(TextCtrl2, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5); TextCtrl1 = new wxTextCtrl(this, ID_TEXTCTRL1, _("0"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_TEXTCTRL1")); BoxSizer2->Add(TextCtrl1, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5); doCalc = new wxButton(this, ID_BUTTON1, _("Сумма"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON1")); BoxSizer2->Add(doCalc, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5); StaticText_Sum = new wxStaticText(this, ID_STATICTEXT3, _("0"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT3")); BoxSizer2->Add(StaticText_Sum, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5); BoxSizer1->Add(BoxSizer2, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 4); Button2 = new wxButton(this, ID_BUTTON2, _("Выход"), wxDefaultPosition, wxSize(175,43), 0, wxDefaultValidator, _T("ID_BUTTON2")); BoxSizer1->Add(Button2, 1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 4); SetSizer(BoxSizer1); BoxSizer1->Fit(this); BoxSizer1->SetSizeHints(this); Center(); Connect(ID_BUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxwidgets_testDialog::OndoCalcClick); Connect(ID_BUTTON2,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxwidgets_testDialog::OnQuit); //*) } wxwidgets_testDialog::~wxwidgets_testDialog() { //(*Destroy(wxwidgets_testDialog) //*) } void wxwidgets_testDialog::OnQuit(wxCommandEvent& event) // Выход из программы { wxMessageBox(_("С++ с wxWidgets - это круто!"), _("До свидания!")); Close(); } void wxwidgets_testDialog::OndoCalcClick(wxCommandEvent& event) // Кнопка расчета значения { double a = strtod(TextCtrl1->GetValue(), NULL); double b = strtod(TextCtrl2->GetValue(), NULL); double c = a + b; std::ostringstream foo; foo.precision(10); foo << c; StaticText_Sum->SetLabel(foo.str()); }
38.007937
143
0.719566
tsnsoft
c013c6ac7c33ece9f3b12466553654cad46ecb3a
15,147
cpp
C++
src/Random.cpp
tehilinski/Random
3aa9f5c067c2532611198627300606e97c2b2451
[ "Apache-2.0" ]
null
null
null
src/Random.cpp
tehilinski/Random
3aa9f5c067c2532611198627300606e97c2b2451
[ "Apache-2.0" ]
null
null
null
src/Random.cpp
tehilinski/Random
3aa9f5c067c2532611198627300606e97c2b2451
[ "Apache-2.0" ]
null
null
null
//------------------------------------------------------------------------------------------------------------ // File: Random.cpp // Class: teh::Random // // Description: // Random number generator using the code from zufall.h/.c. // See header file for more details. // // Author: Thomas E. Hilinski <https://github.com/tehilinski> // // Copyright 2020 Thomas E. Hilinski. 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 // and in the accompanying file LICENSE.md. // 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 "Random.h" #include <cmath> using std::exp; using std::cos; using std::sin; using std::sqrt; using std::log; #include <stdexcept> #include <string> #include <ctime> namespace teh { namespace zufall { //---------------------------------------- class RandomSeed ---------------------------------------- unsigned int const RandomSeed::seedUpperLimit = UINT_MAX - 144U; RandomSeed::RandomSeed ( unsigned int const entropy, unsigned int const minSeed, unsigned int const maxSeed ) : seedMin ( minSeed > 0 ? minSeed : 1 ), seedMax ( maxSeed < seedUpperLimit ? maxSeed : seedUpperLimit - 1 ), seed ( entropy == 0 ? std::time(NULL) % GetRange().second : entropy % GetRange().second ) { if ( seed < seedMin || seed >= seedMax ) { std::string msg = "Random: seed is out of range."; throw std::runtime_error( msg ); } if ( seedMin >= seedMax ) { std::string msg = "Either minimum or maximum seed (or both) is invalid."; throw std::runtime_error( msg ); } } //---------------------------------------- private to Random ---------------------------------------- struct klotz0_1_ { static short const size = 607; std::vector<double> buff; unsigned int ptr; klotz0_1_ () : buff (size, 0.0), ptr (0) { } }; klotz0_1_ klotz0_1; // private to Random struct klotz1_1_ { static short const size = 1024; std::vector<double> xbuff; unsigned int first, xptr; klotz1_1_ () : xbuff (size, 0.0), first (0), xptr (0) { } }; static klotz1_1_ klotz1_1; //---------------------------------------- class Random ---------------------------------------- Random::Random ( unsigned int const seed ) { InitializeSeedBuffer (seed); } // ---------------------------------------------------------------------------- // InitializeSeedBuffer (formerly zufalli) // Generates initial seed buffer by linear congruential // method. Taken from Marsaglia, FSU report FSU-SCRI-87-50 // Variable seed should be 0 < seed < ( numeric_limits<unsigned int> - 144 ) // ---------------------------------------------------------------------------- void Random::InitializeSeedBuffer ( unsigned int const seed) { unsigned int const ij = seed; unsigned int i = ij / 177 % 177 + 2; unsigned int j = ij % 177 + 2; unsigned int k = 9373 / 169 % 178 + 1; unsigned int l = 9373 % 169; for (unsigned int ii = 0; ii < (unsigned int)klotz0_1.size; ++ii) { double s = 0.0; double t = 0.5; for (unsigned int jj = 1; jj <= 24; ++jj) { unsigned int m = i * j % 179 * k % 179; i = j; j = k; k = m; l = (l * 53 + 1) % 169; if (l * m % 64 >= 32) s += t; t *= 0.5; } klotz0_1.buff[ii] = s; } } // ---------------------------------------------------------------------------- // Uniform (formerly zufall) // portable lagged Fibonacci series uniform random number // generator with "lags" -273 und -607: // W.P. Petersen, IPS, ETH Zuerich, 19 Mar. 92 // ---------------------------------------------------------------------------- double Random::Uniform () { std::vector<double> a; Uniform( 1, a ); return a[0]; } void Random::Uniform ( unsigned int const n, std::vector<double> & a) { if (n == 0) return; a.assign (n, 0.0); unsigned int left, bptr, aptr0; double t; unsigned int vl, k273, k607, kptr; unsigned int aptr = 0; unsigned int nn = n; L1: if (nn == 0) return; /* factor nn = q*607 + r */ unsigned int q = (nn - 1) / klotz0_1.size; left = klotz0_1.size - klotz0_1.ptr; if (q <= 1) { /* only one or fewer full segments */ if (nn < left) { kptr = klotz0_1.ptr; for (unsigned int i = 0; i < nn; ++i) a[i + aptr] = klotz0_1.buff[kptr + i]; klotz0_1.ptr += nn; return; } else { kptr = klotz0_1.ptr; #pragma _CRI ivdep for (unsigned int i = 0; i < left; ++i) a[i + aptr] = klotz0_1.buff[kptr + i]; klotz0_1.ptr = 0; aptr += left; nn -= left; /* buff -> buff case */ vl = 273; k273 = 334; k607 = 0; for (unsigned int k = 0; k < 3; ++k) { #pragma _CRI ivdep for (unsigned int i = 0; i < vl; ++i) { t = klotz0_1.buff[k273+i]+klotz0_1.buff[k607+i]; klotz0_1.buff[k607+i] = t - (double) ((unsigned int) t); } k607 += vl; k273 += vl; vl = 167; if (k == 0) { k273 = 0; } } goto L1; } } else { /* more than 1 full segment */ kptr = klotz0_1.ptr; #pragma _CRI ivdep for (unsigned int i = 0; i < left; ++i) a[i + aptr] = klotz0_1.buff[kptr + i]; nn -= left; klotz0_1.ptr = 0; aptr += left; /* buff -> a(aptr0) */ vl = 273; k273 = 334; k607 = 0; for (unsigned int k = 0; k < 3; ++k) { if (k == 0) { #pragma _CRI ivdep for (unsigned int i = 0; i < vl; ++i) { t = klotz0_1.buff[k273+i]+klotz0_1.buff[k607+i]; a[aptr + i] = t - (double) ((unsigned int) t); } k273 = aptr; k607 += vl; aptr += vl; vl = 167; } else { #pragma _CRI ivdep for (unsigned int i = 0; i < vl; ++i) { t = a[k273 + i] + klotz0_1.buff[k607 + i]; a[aptr + i] = t - (double) ((unsigned int) t); } k607 += vl; k273 += vl; aptr += vl; } } nn += -klotz0_1.size; /* a(aptr-607) -> a(aptr) for last of the q-1 segments */ aptr0 = aptr - klotz0_1.size; vl = klotz0_1.size; for (unsigned int qq = 0; qq < q-2; ++qq) { k273 = aptr0 + 334; #pragma _CRI ivdep for (unsigned int i = 0; i < vl; ++i) { t = a[k273 + i] + a[aptr0 + i]; a[aptr + i] = t - (double) ((unsigned int) t); } nn += -klotz0_1.size; aptr += vl; aptr0 += vl; } /* a(aptr0) -> buff, last segment before residual */ vl = 273; k273 = aptr0 + 334; k607 = aptr0; bptr = 0; for (unsigned int k = 0; k < 3; ++k) { if (k == 0) { #pragma _CRI ivdep for (unsigned int i = 0; i < vl; ++i) { t = a[k273 + i] + a[k607 + i]; klotz0_1.buff[bptr + i] = t - (double) ((unsigned int) t); } k273 = 0; k607 += vl; bptr += vl; vl = 167; } else { #pragma _CRI ivdep for (unsigned int i = 0; i < vl; ++i) { t = klotz0_1.buff[k273 + i] + a[k607 + i]; klotz0_1.buff[bptr + i] = t - (double) ((unsigned int) t); } k607 += vl; k273 += vl; bptr += vl; } } goto L1; } } // ---------------------------------------------------------------------------- // Normal (formerly normalen) // Box-Muller method for Gaussian random numbers. // ---------------------------------------------------------------------------- double Random::Normal () { std::vector<double> x; Uniform( 1, x ); return x[0]; } void Random::Normal ( unsigned int const n, std::vector<double> & x) { if (n == 0) return; x.assign (n, 0.0); if (klotz1_1.first == 0) { normal00(); klotz1_1.first = 1; } unsigned int ptr = 0; unsigned int nn = n; L1: unsigned int const left = klotz1_1.size - klotz1_1.xptr; unsigned int const kptr = klotz1_1.xptr; if (nn < left) { #pragma _CRI ivdep for (unsigned int i = 0; i < nn; ++i) x[i + ptr] = klotz1_1.xbuff[kptr + i]; klotz1_1.xptr += nn; return; } else { #pragma _CRI ivdep for (unsigned int i = 0; i < left; ++i) x[i + ptr] = klotz1_1.xbuff[kptr + i]; klotz1_1.xptr = 0; ptr += left; nn -= left; normal00(); goto L1; } } // ---------------------------------------------------------------------------- // Poisson (formerly fische) // Poisson generator for distribution function of p's: // q(mu,p) = exp(-mu) mu**p/p! // ---------------------------------------------------------------------------- unsigned int Random::Poisson ( double const mu) { std::vector<unsigned int> p; Poisson( 1, mu, p ); return p[0]; } void Random::Poisson ( unsigned int const n, double const mu, std::vector<unsigned int> & p) { if (n == 0) return; p.assign (n, 0); double const pmu = exp(-mu); unsigned int p0 = 0; unsigned int nsegs = (n - 1) / klotz1_1.size; unsigned int left = n - (nsegs << 10); ++nsegs; unsigned int nl0 = left; std::vector<unsigned int> indx (klotz1_1.size); std::vector<double> q (klotz1_1.size); std::vector<double> u (klotz1_1.size); for (unsigned int k = 0; k < nsegs; ++k) { for (unsigned int i = 0; i < left; ++i) { indx[i] = i; p[p0 + i] = 0; q[i] = 1.; } /* Begin iterative loop on segment of p's */ do { Uniform (left, u); // Get the needed uniforms unsigned int jj = 0; for (unsigned int i = 0; i < left; ++i) { unsigned int const ii = indx[i]; double const q0 = q[ii] * u[i]; q[ii] = q0; if (q0 > pmu) { indx[jj++] = ii; ++p[p0 + ii]; } } left = jj; // any left in this segment? } while (left > 0); p0 += nl0; nl0 = klotz1_1.size; left = klotz1_1.size; } } // ---------------------------------------------------------------------------- // zufallsv // saves common blocks klotz0, containing seeds and // pointer to position in seed block. IMPORTANT: svblk must be // dimensioned at least 608 in driver. The entire contents // of klotz0 (pointer in buff, and buff) must be saved. // ---------------------------------------------------------------------------- void Random::zufallsv ( std::vector<double> & saveBuffer) // size = klotz0_1_.size + 1 { saveBuffer.resize (klotz0_1_::size + 1); saveBuffer[0] = (double) klotz0_1.ptr; #pragma _CRI ivdep for (short i = 0; i < klotz0_1.size; ++i) saveBuffer[i + 1] = klotz0_1.buff[i]; } // ---------------------------------------------------------------------------- // zufallrs // restores common block klotz0, containing seeds and pointer // to position in seed block. IMPORTANT: saveBuffer must be // dimensioned at least 608 in driver. The entire contents // of klotz0 must be restored. // ---------------------------------------------------------------------------- void Random::zufallrs ( std::vector<double> const & saveBuffer) // size = klotz0_1_.size + 1 { if ( saveBuffer.size() != klotz0_1_::size + 1 ) { std::string msg; msg = "Random::zufallrs, restore of uninitialized block."; throw std::runtime_error (msg); } klotz0_1.ptr = (unsigned int) saveBuffer[0]; #pragma _CRI ivdep for (short i = 0; i < klotz0_1.size; ++i) klotz0_1.buff[i] = saveBuffer[i + 1]; } // ---------------------------------------------------------------------------- // normalsv // save zufall block klotz0 // IMPORTANT: svbox must be dimensioned at // least 1634 in driver. The entire contents of blocks // klotz0 (via zufallsv) and klotz1 must be saved. // ---------------------------------------------------------------------------- void Random::normalsv ( std::vector<double> & saveBuffer) // size = 1634 { if (klotz1_1.first == 0) { std::string msg; msg = "Random::normalsv, save of uninitialized block."; throw std::runtime_error (msg); } saveBuffer.resize (1634); zufallsv (saveBuffer); saveBuffer[klotz0_1.size + 1] = (double) klotz1_1.first; // [608] saveBuffer[klotz0_1.size + 2] = (double) klotz1_1.xptr; // [609] unsigned int const k = klotz0_1.size + 3; // 610 #pragma _CRI ivdep for (short i = 0; i < klotz1_1.size; ++i) saveBuffer[i + k] = klotz1_1.xbuff[i]; } // ---------------------------------------------------------------------------- // normalrs // restore zufall blocks klotz0 and klotz1 // IMPORTANT: saveBuffer must be dimensioned at // least 1634 in driver. The entire contents // of klotz0 and klotz1 must be restored. // ---------------------------------------------------------------------------- void Random::normalrs ( std::vector<double> const & saveBuffer) // size = 1634 { zufallrs (saveBuffer); klotz1_1.first = (unsigned int) saveBuffer[klotz0_1.size + 1]; // [608] if (klotz1_1.first == 0) { std::string msg; msg = "Random::normalrs, restore of uninitialized block."; throw std::runtime_error (msg); } klotz1_1.xptr = (unsigned int) saveBuffer[klotz0_1.size + 2]; // [609] unsigned int const k = klotz0_1.size + 3; // 610 #pragma _CRI ivdep for (short i = 0; i < klotz1_1.size; ++i) klotz1_1.xbuff[i] = saveBuffer[i + k]; } // ---------------------------------------------------------------------------- // normal00 // ---------------------------------------------------------------------------- void Random::normal00 () { /* Builtin functions */ /* double cos(), sin(), log(), sqrt(); */ double const twopi = 6.2831853071795862; Uniform (klotz1_1.size, klotz1_1.xbuff); // std::vector<double>::iterator i = klotz1_1.xbuff.begin(); // std::vector<double>::iterator ip1 = klotz1_1.xbuff.begin(); // while ( ip1 != klotz1_1.xbuff.end() ) // { // double const r1 = twopi * (*i); // double const t1 = cos(r1); // double const t2 = sin(r1); // double const r2 = sqrt(-2.0 * ( log(1.0 - (*ip1) ) ) ); // (*i) = t1 * r2; // (*ip1) = t2 * r2; // ++i; ++i; // ++ip1; ++ip1; // } #pragma _CRI ivdep for (short i = 0; i < klotz1_1.size - 1; i += 2) { double const r1 = twopi * klotz1_1.xbuff[i]; double const t1 = cos(r1); double const t2 = sin(r1); double const r2 = sqrt(-2.0 * ( log(1.0 - klotz1_1.xbuff[i+1] ) ) ); klotz1_1.xbuff[i] = t1 * r2; klotz1_1.xbuff[i+1] = t2 * r2; } } // class Random } // namespace zufall } // namespace teh
25.936644
110
0.494355
tehilinski
c01829280078f3949bf4252f6056af2a09c25eb7
4,124
cpp
C++
tket/src/Utils/CosSinDecomposition.cpp
vtomole/tket
ded37ab58176d64117a3e11e8a667ce0199a338a
[ "Apache-2.0" ]
104
2021-09-15T08:16:25.000Z
2022-03-28T21:19:00.000Z
tket/src/Utils/CosSinDecomposition.cpp
vtomole/tket
ded37ab58176d64117a3e11e8a667ce0199a338a
[ "Apache-2.0" ]
109
2021-09-16T17:14:22.000Z
2022-03-29T06:48:40.000Z
tket/src/Utils/CosSinDecomposition.cpp
vtomole/tket
ded37ab58176d64117a3e11e8a667ce0199a338a
[ "Apache-2.0" ]
8
2021-10-02T13:47:34.000Z
2022-03-17T15:36:56.000Z
// Copyright 2019-2022 Cambridge Quantum Computing // // 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 "CosSinDecomposition.hpp" #include <cmath> #include "Constants.hpp" #include "EigenConfig.hpp" #include "MatrixAnalysis.hpp" #include "TketLog.hpp" namespace tket { csd_t CS_decomp(const Eigen::MatrixXcd &u) { if (!is_unitary(u)) { throw std::invalid_argument("Matrix for CS decomposition is not unitary"); } unsigned N = u.rows(); if (N % 2 != 0) { throw std::invalid_argument( "Matrix for CS decomposition has odd dimensions"); } unsigned n = N / 2; Eigen::MatrixXcd u00 = u.topLeftCorner(n, n); Eigen::MatrixXcd u01 = u.topRightCorner(n, n); Eigen::MatrixXcd u10 = u.bottomLeftCorner(n, n); Eigen::MatrixXcd u11 = u.bottomRightCorner(n, n); Eigen::JacobiSVD<Eigen::MatrixXcd, Eigen::NoQRPreconditioner> svd( u00, Eigen::ComputeFullU | Eigen::ComputeFullV); Eigen::MatrixXcd l0 = svd.matrixU().rowwise().reverse(); Eigen::MatrixXcd r0_dag = svd.matrixV().rowwise().reverse(); Eigen::MatrixXd c = svd.singularValues().reverse().asDiagonal(); Eigen::MatrixXcd r0 = r0_dag.adjoint(); // Now u00 = l0 c r0; l0 and r0 are unitary, and c is diagonal with positive // non-decreasing entries. Because u00 is a submatrix of a unitary matrix, its // singular values (the entries of c) are all <= 1. Eigen::HouseholderQR<Eigen::MatrixXcd> qr = (u10 * r0_dag).householderQr(); Eigen::MatrixXcd l1 = qr.householderQ(); Eigen::MatrixXcd S = qr.matrixQR().triangularView<Eigen::Upper>(); // Now u10 r0* = l1 S; l1 is unitary, and S is upper triangular. // // Claim: S is diagonal. // Proof: Since u is unitary, we have // I = u00* u00 + u10* u10 // = (l0 c r0)* (l0 c r0) + (l1 S r0)* (l1 S r0) // = r0* c l0* l0 c r0 + r0* S* l1* l1 S r0 // = r0* c^2 r0 + r0* S* S r0 // = r0* (c^2 + S* S) r0 // So I = c^2 + (S* S), so (S* S) = I - c^2 is a diagonal matrix with non- // increasing entries in the range [0,1). As S is upper triangular, this // implies that S must be diagonal. (Proof by induction over the dimension n // of S: consider the two cases S_00 = 0 and S_00 != 0 and reduce to the n-1 // case.) // // We want S to be real. This is not guaranteed, though since it is diagonal // it can be made so by adjusting l1. In fact, it seems that Eigen always does // give us a real S. We will not assume this, but will log an informational // message and do the adjustment ourselves if that behaviour does change. if (!S.imag().isZero()) { tket_log()->info( "Eigen surprisingly returned a non-real diagonal R in QR " "decomposition; adjusting Q and R to make it real."); for (unsigned j = 0; j < n; j++) { std::complex<double> z = S(j, j); double r = std::abs(z); if (r > EPS) { std::complex<double> w = std::conj(z) / r; S(j, j) *= w; l1.col(j) /= w; } } } // Now S is real and diagonal, and c^2 + S^2 = I. Eigen::MatrixXd s = S.real(); // Make all entries in s non-negative. for (unsigned j = 0; j < n; j++) { if (s(j, j) < 0) { s(j, j) = -s(j, j); l1.col(j) = -l1.col(j); } } // Finally compute r1, being careful not to divide by small things. Eigen::MatrixXcd r1 = Eigen::MatrixXcd::Zero(n, n); for (unsigned i = 0; i < n; i++) { if (s(i, i) > c(i, i)) { r1.row(i) = -(l0.adjoint() * u01).row(i) / s(i, i); } else { r1.row(i) = (l1.adjoint() * u11).row(i) / c(i, i); } } return {l0, l1, r0, r1, c, s}; } } // namespace tket
35.551724
80
0.624879
vtomole
c018e6e9988a885e93ce70cea4ba7dd22a931955
24,452
cpp
C++
apps/src/ni_linemod.cpp
yxlao/StanfordPCL
98a8663f896c1ba880d14efa2338b7cfbd01b6ef
[ "MIT" ]
null
null
null
apps/src/ni_linemod.cpp
yxlao/StanfordPCL
98a8663f896c1ba880d14efa2338b7cfbd01b6ef
[ "MIT" ]
null
null
null
apps/src/ni_linemod.cpp
yxlao/StanfordPCL
98a8663f896c1ba880d14efa2338b7cfbd01b6ef
[ "MIT" ]
null
null
null
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2012, Willow Garage, 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 Willow Garage, 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. * * $Id: openni_viewer.cpp 5059 2012-03-14 02:12:17Z gedikli $ * */ #include <pcl/apps/timer.h> #include <pcl/common/common.h> #include <pcl/common/angles.h> #include <pcl/common/time.h> #include <pcl/io/openni_grabber.h> #include <pcl/io/pcd_io.h> #include <pcl/search/organized.h> #include <pcl/features/integral_image_normal.h> #include <pcl/filters/extract_indices.h> #include <pcl/segmentation/organized_multi_plane_segmentation.h> #include <pcl/segmentation/sac_segmentation.h> #include <pcl/segmentation/extract_polygonal_prism_data.h> #include <pcl/sample_consensus/sac_model_plane.h> //#include <pcl/io/tar_io.h> #include <pcl/surface/convex_hull.h> #include <pcl/visualization/point_cloud_handlers.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/visualization/image_viewer.h> #include <pcl/console/print.h> #include <pcl/console/parse.h> #include <pcl/segmentation/euclidean_cluster_comparator.h> #include <pcl/segmentation/organized_connected_component_segmentation.h> #include <pcl/segmentation/edge_aware_plane_comparator.h> #include <pcl/geometry/polygon_operations.h> using namespace pcl; using namespace std; typedef PointXYZRGBA PointT; #define SHOW_FPS 1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class NILinemod { public: typedef PointCloud<PointT> Cloud; typedef Cloud::Ptr CloudPtr; typedef Cloud::ConstPtr CloudConstPtr; bool added; NILinemod(Grabber &grabber) : cloud_viewer_("PointCloud"), grabber_(grabber), image_viewer_("Image"), first_frame_(true) { added = false; // Set the parameters for normal estimation ne_.setNormalEstimationMethod(ne_.COVARIANCE_MATRIX); ne_.setMaxDepthChangeFactor(0.02f); ne_.setNormalSmoothingSize(20.0f); // Set the parameters for planar segmentation plane_comparator_.reset(new EdgeAwarePlaneComparator<PointT, Normal>); plane_comparator_->setDistanceThreshold(0.01f, false); mps_.setMinInliers(5000); mps_.setAngularThreshold(pcl::deg2rad(3.0)); // 3 degrees mps_.setDistanceThreshold(0.02); // 2 cm mps_.setMaximumCurvature(0.001); // a small curvature mps_.setProjectPoints(true); mps_.setComparator(plane_comparator_); } ///////////////////////////////////////////////////////////////////////// void cloud_callback(const CloudConstPtr &cloud) { FPS_CALC("cloud callback"); boost::mutex::scoped_lock lock(cloud_mutex_); cloud_ = cloud; search_.setInputCloud(cloud); // Subsequent frames are segmented by "tracking" the parameters of the // previous frame We do this by using the estimated inliers from // previous frames in the current frame, and refining the coefficients if (!first_frame_) { if (!plane_indices_ || plane_indices_->indices.empty() || !search_.getInputCloud()) { PCL_ERROR( "Lost tracking. Select the object again to continue.\n"); first_frame_ = true; return; } SACSegmentation<PointT> seg; seg.setOptimizeCoefficients(true); seg.setModelType(SACMODEL_PLANE); seg.setMethodType(SAC_RANSAC); seg.setMaxIterations(1000); seg.setDistanceThreshold(0.01); seg.setInputCloud(search_.getInputCloud()); seg.setIndices(plane_indices_); ModelCoefficients coefficients; PointIndices inliers; seg.segment(inliers, coefficients); if (inliers.indices.empty()) { PCL_ERROR("No planar model found. Select the object again to " "continue.\n"); first_frame_ = true; return; } // Visualize the object in 3D... CloudPtr plane_inliers(new Cloud); pcl::copyPointCloud(*search_.getInputCloud(), inliers.indices, *plane_inliers); if (plane_inliers->points.empty()) { PCL_ERROR("No planar model found. Select the object again to " "continue.\n"); first_frame_ = true; return; } else { plane_.reset(new Cloud); // Compute the convex hull of the plane ConvexHull<PointT> chull; chull.setDimension(2); chull.setInputCloud(plane_inliers); chull.reconstruct(*plane_); } } } ///////////////////////////////////////////////////////////////////////// CloudConstPtr getLatestCloud() { // Lock while we swap our cloud and reset it. boost::mutex::scoped_lock lock(cloud_mutex_); CloudConstPtr temp_cloud; temp_cloud.swap(cloud_); return (temp_cloud); } ///////////////////////////////////////////////////////////////////////// void keyboard_callback(const visualization::KeyboardEvent &, void *) { // if (event.getKeyCode()) // cout << "the key \'" << event.getKeyCode() << "\' (" << // event.getKeyCode() << ") was"; // else // cout << "the special key \'" << event.getKeySym() << "\' was"; // if (event.keyDown()) // cout << " pressed" << endl; // else // cout << " released" << endl; } ///////////////////////////////////////////////////////////////////////// void mouse_callback(const visualization::MouseEvent &, void *) { // if (mouse_event.getType() == // visualization::MouseEvent::MouseButtonPress && mouse_event.getButton() // == visualization::MouseEvent::LeftButton) //{ // cout << "left button pressed @ " << mouse_event.getX () << " , " << // mouse_event.getY () << endl; //} } ///////////////////////////////////////////////////////////////////////// /** \brief Given a plane, and the set of inlier indices representing it, * segment out the object of intererest supported by it. * * \param[in] picked_idx the index of a point on the object * \param[in] cloud the full point cloud dataset * \param[in] plane_indices a set of indices representing the plane * supporting the object of interest \param[in] plane_boundary_indices a set * of indices representing the boundary of the plane \param[out] object the * segmented resultant object */ void segmentObject(int picked_idx, const CloudConstPtr &cloud, const PointIndices::Ptr &plane_indices, const PointIndices::Ptr &plane_boundary_indices, Cloud &object) { CloudPtr plane_hull(new Cloud); // Compute the convex hull of the plane ConvexHull<PointT> chull; chull.setDimension(2); chull.setInputCloud(cloud); chull.setIndices(plane_boundary_indices); chull.reconstruct(*plane_hull); // Remove the plane indices from the data PointIndices::Ptr everything_but_the_plane(new PointIndices); if (indices_fullset_.size() != cloud->points.size()) { indices_fullset_.resize(cloud->points.size()); for (int p_it = 0; p_it < static_cast<int>(indices_fullset_.size()); ++p_it) indices_fullset_[p_it] = p_it; } std::vector<int> indices_subset = plane_indices->indices; std::sort(indices_subset.begin(), indices_subset.end()); set_difference(indices_fullset_.begin(), indices_fullset_.end(), indices_subset.begin(), indices_subset.end(), inserter(everything_but_the_plane->indices, everything_but_the_plane->indices.begin())); // Extract all clusters above the hull PointIndices::Ptr points_above_plane(new PointIndices); ExtractPolygonalPrismData<PointT> exppd; exppd.setInputCloud(cloud); exppd.setInputPlanarHull(plane_hull); exppd.setIndices(everything_but_the_plane); exppd.setHeightLimits(0.0, 0.5); // up to half a meter exppd.segment(*points_above_plane); // Use an organized clustering segmentation to extract the individual // clusters EuclideanClusterComparator<PointT, Normal, Label>::Ptr euclidean_cluster_comparator( new EuclideanClusterComparator<PointT, Normal, Label>); euclidean_cluster_comparator->setInputCloud(cloud); euclidean_cluster_comparator->setDistanceThreshold(0.03f, false); // Set the entire scene to false, and the inliers of the objects located // on top of the plane to true Label l; l.label = 0; PointCloud<Label>::Ptr scene( new PointCloud<Label>(cloud->width, cloud->height, l)); // Mask the objects that we want to split into clusters for (int i = 0; i < static_cast<int>(points_above_plane->indices.size()); ++i) scene->points[points_above_plane->indices[i]].label = 1; euclidean_cluster_comparator->setLabels(scene); vector<bool> exclude_labels(2); exclude_labels[0] = true; exclude_labels[1] = false; euclidean_cluster_comparator->setExcludeLabels(exclude_labels); OrganizedConnectedComponentSegmentation<PointT, Label> euclidean_segmentation(euclidean_cluster_comparator); euclidean_segmentation.setInputCloud(cloud); PointCloud<Label> euclidean_labels; vector<PointIndices> euclidean_label_indices; euclidean_segmentation.segment(euclidean_labels, euclidean_label_indices); // For each cluster found bool cluster_found = false; for (size_t i = 0; i < euclidean_label_indices.size(); i++) { if (cluster_found) break; // Check if the point that we picked belongs to it for (size_t j = 0; j < euclidean_label_indices[i].indices.size(); ++j) { if (picked_idx != euclidean_label_indices[i].indices[j]) continue; // pcl::PointCloud<PointT> cluster; pcl::copyPointCloud(*cloud, euclidean_label_indices[i].indices, object); cluster_found = true; break; // object_indices = euclidean_label_indices[i].indices; // clusters.push_back (cluster); } } } ///////////////////////////////////////////////////////////////////////// void segment(const PointT &picked_point, int picked_idx, PlanarRegion<PointT> &region, PointIndices &, CloudPtr &object) { // First frame is segmented using an organized multi plane segmentation // approach from points and their normals if (!first_frame_) return; // Estimate normals in the cloud PointCloud<Normal>::Ptr normal_cloud(new PointCloud<Normal>); ne_.setInputCloud(search_.getInputCloud()); ne_.compute(*normal_cloud); plane_comparator_->setDistanceMap(ne_.getDistanceMap()); // Segment out all planes mps_.setInputNormals(normal_cloud); mps_.setInputCloud(search_.getInputCloud()); // Use one of the overloaded segmentAndRefine calls to get all the // information that we want out vector<PlanarRegion<PointT>, Eigen::aligned_allocator<PlanarRegion<PointT>>> regions; vector<ModelCoefficients> model_coefficients; vector<PointIndices> inlier_indices; PointCloud<Label>::Ptr labels(new PointCloud<Label>); vector<PointIndices> label_indices; vector<PointIndices> boundary_indices; mps_.segmentAndRefine(regions, model_coefficients, inlier_indices, labels, label_indices, boundary_indices); PCL_DEBUG("Number of planar regions detected: %zu for a cloud of %zu " "points and %zu normals.\n", regions.size(), search_.getInputCloud()->points.size(), normal_cloud->points.size()); double max_dist = numeric_limits<double>::max(); // Compute the distances from all the planar regions to the picked // point, and select the closest region int idx = -1; for (size_t i = 0; i < regions.size(); ++i) { double dist = pointToPlaneDistance(picked_point, regions[i].getCoefficients()); if (dist < max_dist) { max_dist = dist; idx = static_cast<int>(i); } } PointIndices::Ptr plane_boundary_indices; // Get the plane that holds the object of interest if (idx != -1) { region = regions[idx]; plane_indices_.reset(new PointIndices(inlier_indices[idx])); plane_boundary_indices.reset( new PointIndices(boundary_indices[idx])); } // Segment the object of interest if (plane_boundary_indices && !plane_boundary_indices->indices.empty()) { object.reset(new Cloud); segmentObject(picked_idx, search_.getInputCloud(), plane_indices_, plane_boundary_indices, *object); // Save to disk // pcl::io::saveTARPointCloud ("output.ltm", *object, "object.pcd"); } first_frame_ = false; } ///////////////////////////////////////////////////////////////////////// /** \brief Point picking callback. This gets called when the user selects * a 3D point on screen (in the PCLVisualizer window) using Shift+click. * * \param[in] event the event that triggered the call */ void pp_callback(const visualization::PointPickingEvent &event, void *) { // Check to see if we got a valid point. Early exit. int idx = event.getPointIndex(); if (idx == -1) return; vector<int> indices(1); vector<float> distances(1); // Use mutices to make sure we get the right cloud boost::mutex::scoped_lock lock1(cloud_mutex_); // Get the point that was picked PointT picked_pt; event.getPoint(picked_pt.x, picked_pt.y, picked_pt.z); // Add a sphere to it in the PCLVisualizer window stringstream ss; ss << "sphere_" << idx; cloud_viewer_.addSphere(picked_pt, 0.01, 1.0, 0.0, 0.0, ss.str()); // Check to see if we have access to the actual cloud data. Use the // previously built search object. if (!search_.isValid()) return; // Because VTK/OpenGL stores data without NaN, we lose the 1-1 // correspondence, so we must search for the real point search_.nearestKSearch(picked_pt, 1, indices, distances); // Get the [u, v] in pixel coordinates for the ImageViewer. Remember // that 0,0 is bottom left. uint32_t width = search_.getInputCloud()->width, height = search_.getInputCloud()->height; int v = indices[0] / width, u = indices[0] % width; // Add some marker to the image image_viewer_.addCircle(u, v, 5, 1.0, 0.0, 0.0, "circles", 1.0); image_viewer_.addFilledRectangle(u - 5, u + 5, v - 5, v + 5, 0.0, 1.0, 0.0, "boxes", 0.5); image_viewer_.markPoint(u, v, visualization::red_color, visualization::blue_color, 10); // Segment the region that we're interested in, by employing a two step // process: // * first, segment all the planes in the scene, and find the one // closest to our picked point // * then, use euclidean clustering to find the object that we clicked // on and return it PlanarRegion<PointT> region; CloudPtr object; PointIndices region_indices; segment(picked_pt, indices[0], region, region_indices, object); // If no region could be determined, exit if (region.getContour().empty()) { PCL_ERROR("No planar region detected. Please select another point " "or relax the thresholds and continue.\n"); return; } // Else, draw it on screen else { // cloud_viewer_.addPolygon (region, 1.0, 0.0, 0.0, "region"); // cloud_viewer_.setShapeRenderingProperties // (visualization::PCL_VISUALIZER_LINE_WIDTH, 10, "region"); PlanarRegion<PointT> refined_region; pcl::approximatePolygon(region, refined_region, 0.01, false, true); PCL_INFO("Planar region: %zu points initial, %zu points after " "refinement.\n", region.getContour().size(), refined_region.getContour().size()); cloud_viewer_.addPolygon(refined_region, 0.0, 0.0, 1.0, "refined_region"); cloud_viewer_.setShapeRenderingProperties( visualization::PCL_VISUALIZER_LINE_WIDTH, 10, "refined_region"); // Draw in image space image_viewer_.addPlanarPolygon(search_.getInputCloud(), refined_region, 0.0, 0.0, 1.0, "refined_region", 1.0); } // If no object could be determined, exit if (!object) { PCL_ERROR("No object detected. Please select another point or " "relax the thresholds and continue.\n"); return; } else { // Visualize the object in 3D... visualization::PointCloudColorHandlerCustom<PointT> red(object, 255, 0, 0); if (!cloud_viewer_.updatePointCloud(object, red, "object")) cloud_viewer_.addPointCloud(object, red, "object"); // ...and 2D image_viewer_.removeLayer("object"); image_viewer_.addMask(search_.getInputCloud(), *object, "object"); // Compute the min/max of the object PointT min_pt, max_pt; getMinMax3D(*object, min_pt, max_pt); stringstream ss; ss << "cube_" << idx; // Visualize the bounding box in 3D... cloud_viewer_.addCube(min_pt.x, max_pt.x, min_pt.y, max_pt.y, min_pt.z, max_pt.z, 0.0, 1.0, 0.0, ss.str()); cloud_viewer_.setShapeRenderingProperties( visualization::PCL_VISUALIZER_LINE_WIDTH, 10, ss.str()); // ...and 2D image_viewer_.addRectangle(search_.getInputCloud(), *object); } } ///////////////////////////////////////////////////////////////////////// void init() { cloud_viewer_.registerMouseCallback(&NILinemod::mouse_callback, *this); cloud_viewer_.registerKeyboardCallback(&NILinemod::keyboard_callback, *this); cloud_viewer_.registerPointPickingCallback(&NILinemod::pp_callback, *this); boost::function<void(const CloudConstPtr &)> cloud_cb = boost::bind(&NILinemod::cloud_callback, this, _1); cloud_connection = grabber_.registerCallback(cloud_cb); image_viewer_.registerMouseCallback(&NILinemod::mouse_callback, *this); image_viewer_.registerKeyboardCallback(&NILinemod::keyboard_callback, *this); } ///////////////////////////////////////////////////////////////////////// void run() { grabber_.start(); bool image_init = false, cloud_init = false; while (!cloud_viewer_.wasStopped() && !image_viewer_.wasStopped()) { if (cloud_) { CloudConstPtr cloud = getLatestCloud(); if (!cloud_init) { cloud_viewer_.setPosition(0, 0); cloud_viewer_.setSize(cloud->width, cloud->height); cloud_init = !cloud_init; } if (!cloud_viewer_.updatePointCloud(cloud, "OpenNICloud")) { cloud_viewer_.addPointCloud(cloud, "OpenNICloud"); cloud_viewer_.resetCameraViewpoint("OpenNICloud"); } if (!image_init) { image_viewer_.setPosition(cloud->width, 0); image_viewer_.setSize(cloud->width, cloud->height); image_init = !image_init; } image_viewer_.showRGBImage<PointT>(cloud); } // Add the plane that we're tracking to the cloud visualizer CloudPtr plane(new Cloud); if (plane_) *plane = *plane_; visualization::PointCloudColorHandlerCustom<PointT> blue(plane, 0, 255, 0); if (!cloud_viewer_.updatePointCloud(plane, blue, "plane")) cloud_viewer_.addPointCloud(plane, "plane"); cloud_viewer_.spinOnce(); image_viewer_.spinOnce(); boost::this_thread::sleep(boost::posix_time::microseconds(100)); } grabber_.stop(); cloud_connection.disconnect(); } visualization::PCLVisualizer cloud_viewer_; Grabber &grabber_; boost::mutex cloud_mutex_; CloudConstPtr cloud_; visualization::ImageViewer image_viewer_; search::OrganizedNeighbor<PointT> search_; private: boost::signals2::connection cloud_connection, image_connection; bool first_frame_; // Segmentation std::vector<int> indices_fullset_; PointIndices::Ptr plane_indices_; CloudPtr plane_; IntegralImageNormalEstimation<PointT, Normal> ne_; OrganizedMultiPlaneSegmentation<PointT, Normal, Label> mps_; EdgeAwarePlaneComparator<PointT, Normal>::Ptr plane_comparator_; }; /* ---[ */ int main(int, char **) { string device_id("#1"); OpenNIGrabber grabber(device_id); NILinemod openni_viewer(grabber); openni_viewer.init(); openni_viewer.run(); return (0); } /* ]--- */
41.798291
114
0.584942
yxlao
c01a0bc743f10f3bfff54218a1db9ca4026e8dd8
4,185
cpp
C++
CsUserInterface/Source/CsUI/Public/Managers/WidgetActor/Cache/CsCache_WidgetActorImpl.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
2
2019-03-17T10:43:53.000Z
2021-04-20T21:24:19.000Z
CsUserInterface/Source/CsUI/Public/Managers/WidgetActor/Cache/CsCache_WidgetActorImpl.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
CsUserInterface/Source/CsUI/Public/Managers/WidgetActor/Cache/CsCache_WidgetActorImpl.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
// Copyright 2017-2021 Closed Sum Games, LLC. All Rights Reserved. #include "Managers/WidgetActor/Cache/CsCache_WidgetActorImpl.h" // Library #include "Managers/Pool/Payload/CsLibrary_Payload_PooledObject.h" // Pool #include "Managers/Pool/Payload/CsPayload_PooledObject.h" // FX #include "Managers/WidgetActor/Payload/CsPayload_WidgetActor.h" #include "NiagaraComponent.h" // Component #include "Components/CsWidgetComponent.h" const FName NCsWidgetActor::NCache::FImpl::Name = FName("NCsWidgetActor::NCache::FImpl"); namespace NCsWidgetActor { namespace NCache { namespace NImplCached { namespace Str { CS_DEFINE_CACHED_FUNCTION_NAME_AS_STRING(NCsWidgetActor::NCache::FImpl, Allocate); } } FImpl::FImpl() : // ICsGetInterfaceMap InterfaceMap(nullptr), // PooledCacheType (NCsPooledObject::NCache::ICache) Index(INDEX_NONE), bAllocated(false), bQueueDeallocate(false), State(NCsPooledObject::EState::Inactive), UpdateType(NCsPooledObject::EUpdate::Manager), Instigator(), Owner(), Parent(), WarmUpTime(0.0f), LifeTime(0.0f), StartTime(), ElapsedTime(), // WidgetActorCacheType (NCsWidgetActor::NCache::ICache) DeallocateMethod(ECsWidgetActorDeallocateMethod::Complete), QueuedLifeTime(0.0f) { InterfaceMap = new FCsInterfaceMap(); InterfaceMap->SetRoot<FImpl>(this); typedef NCsPooledObject::NCache::ICache PooledCacheType; typedef NCsWidgetActor::NCache::ICache WidgetActorCacheType; InterfaceMap->Add<PooledCacheType>(static_cast<PooledCacheType*>(this)); InterfaceMap->Add<WidgetActorCacheType>(static_cast<WidgetActorCacheType*>(this)); } FImpl::~FImpl() { delete InterfaceMap; } // PooledCacheType (NCsPooledObject::NCache::ICache) #pragma region #define PooledPayloadType NCsPooledObject::NPayload::IPayload void FImpl::Allocate(PooledPayloadType* Payload) { #undef PooledPayloadType using namespace NImplCached; const FString& Context = Str::Allocate; // PooledCacheType (NCsPooledObject::NCache::ICache) bAllocated = true; State = NCsPooledObject::EState::Active; UpdateType = Payload->GetUpdateType(); Instigator = Payload->GetInstigator(); Owner = Payload->GetOwner(); Parent = Payload->GetParent(); StartTime = Payload->GetTime(); // WidgetActorCacheType (NCsWidgetActor::NPayload::IPayload) typedef NCsWidgetActor::NPayload::IPayload WidgetPayloadType; typedef NCsPooledObject::NPayload::FLibrary PooledPayloadLibrary; WidgetPayloadType* WidgetPayload = PooledPayloadLibrary::GetInterfaceChecked<WidgetPayloadType>(Context, Payload); DeallocateMethod = WidgetPayload->GetDeallocateMethod(); QueuedLifeTime = WidgetPayload->GetLifeTime(); } void FImpl::Deallocate() { Reset(); } void FImpl::QueueDeallocate() { bQueueDeallocate = true; // LifeTime if (DeallocateMethod == ECsWidgetActorDeallocateMethod::LifeTime) { // Reset ElapsedTime ElapsedTime.Reset(); // Set LifeTime LifeTime = QueuedLifeTime; } } bool FImpl::ShouldDeallocate() const { if (bQueueDeallocate) { // LifeTime, let HasLifeTimeExpired handle deallocation if (DeallocateMethod == ECsWidgetActorDeallocateMethod::LifeTime) { return false; } return bQueueDeallocate; } return false; } bool FImpl::HasLifeTimeExpired() { return LifeTime > 0.0f && ElapsedTime.Time > LifeTime; } void FImpl::Reset() { // PooledCacheType (NCsPooledObject::NCache::ICache) bAllocated = false; bQueueDeallocate = false; State = NCsPooledObject::EState::Inactive; UpdateType = NCsPooledObject::EUpdate::Manager; Instigator.Reset(); Owner.Reset(); Parent.Reset(); WarmUpTime = 0.0f; LifeTime = 0.0f; StartTime.Reset(); ElapsedTime.Reset(); // WidgetActorCacheType (NCsWidgetActor::NPayload::IPayload) DeallocateMethod = ECsWidgetActorDeallocateMethod::ECsWidgetActorDeallocateMethod_MAX; QueuedLifeTime = 0.0f; } #pragma endregion PooledCacheType (NCsPooledObject::NCache::ICache) void FImpl::Update(const FCsDeltaTime& DeltaTime) { ElapsedTime += DeltaTime; } } }
26.320755
117
0.726165
closedsum
c01a226d6cacaed3b80257bfd2c205d6e266b045
7,588
cc
C++
chrome/browser/extensions/api/discovery/discovery_api_unittest.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4
2017-04-05T01:51:34.000Z
2018-02-15T03:11:54.000Z
chrome/browser/extensions/api/discovery/discovery_api_unittest.cc
j4ckfrost/android_external_chromium_org
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-12-13T19:44:12.000Z
2021-12-13T19:44:12.000Z
chrome/browser/extensions/api/discovery/discovery_api_unittest.cc
j4ckfrost/android_external_chromium_org
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4
2017-04-05T01:52:03.000Z
2022-02-13T17:58:45.000Z
// 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. // This file tests the chrome.alarms extension API. #include "base/json/json_writer.h" #include "base/values.h" #include "chrome/browser/extensions/api/discovery/discovery_api.h" #include "chrome/browser/extensions/api/discovery/suggested_link.h" #include "chrome/browser/extensions/api/discovery/suggested_links_registry.h" #include "chrome/browser/extensions/api/discovery/suggested_links_registry_factory.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/test_extension_system.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/common/extensions/api/experimental_discovery.h" #include "chrome/test/base/browser_with_test_window_test.h" #include "testing/gtest/include/gtest/gtest.h" namespace utils = extension_function_test_utils; namespace { typedef extensions::SuggestedLinksRegistry::SuggestedLinkList SuggestedLinkList; typedef extensions::api::experimental_discovery::SuggestDetails SuggestDetails; // Converts suggest details used as parameter into a JSON string. std::string SuggestDetailsParamToJSON(const SuggestDetails& suggest_details) { std::string result; scoped_ptr<base::DictionaryValue> value = suggest_details.ToValue(); base::ListValue params; params.Append(value.release()); // |params| takes ownership of |value|. base::JSONWriter::Write(&params, &result); return result; } // Converts the parameters to the API Suggest method to JSON (without score). std::string UnscoredSuggestParamsToJSON(const std::string& link_url, const std::string& link_text) { SuggestDetails suggest_details; suggest_details.link_url = link_url; suggest_details.link_text = link_text; return SuggestDetailsParamToJSON(suggest_details); } // Converts the parameters to the API Suggest method to JSON. std::string SuggestParamsToJSON(const std::string& link_url, const std::string& link_text, double score) { SuggestDetails suggest_details; suggest_details.score.reset(new double(score)); suggest_details.link_url = link_url; suggest_details.link_text = link_text; return SuggestDetailsParamToJSON(suggest_details); } // Converts the parameters to the API RemoveSuggestion method to JSON. std::string RemoveSuggestionParamsToJSON(const std::string& link_url) { std::string result; base::ListValue params; params.Append(new base::StringValue(link_url)); base::JSONWriter::Write(&params, &result); return result; } } // namespace namespace extensions { class ExtensionDiscoveryTest : public BrowserWithTestWindowTest { public: virtual void SetUp() { BrowserWithTestWindowTest::SetUp(); extension_ = utils::CreateEmptyExtensionWithLocation(Manifest::UNPACKED); } // Runs a function and returns a pointer to a value, transferring ownership. base::Value* RunFunctionWithExtension( UIThreadExtensionFunction* function, const std::string& args) { function->set_extension(extension_.get()); return utils::RunFunctionAndReturnSingleResult(function, args, browser()); } // Runs a function and ignores the return value. void RunFunction(UIThreadExtensionFunction* function, const std::string& args) { scoped_ptr<base::Value> result(RunFunctionWithExtension(function, args)); } const std::string& GetExtensionId() const { return extension_->id(); } protected: scoped_refptr<Extension> extension_; }; TEST_F(ExtensionDiscoveryTest, Suggest) { RunFunction(new DiscoverySuggestFunction(), SuggestParamsToJSON("http://www.google.com", "Google", 0.5)); extensions::SuggestedLinksRegistry* registry = extensions::SuggestedLinksRegistryFactory::GetForProfile( browser()->profile()); const SuggestedLinkList* links = registry->GetAll(GetExtensionId()); ASSERT_EQ(1u, links->size()); ASSERT_EQ("http://www.google.com", links->at(0)->link_url()); ASSERT_EQ("Google", links->at(0)->link_text()); ASSERT_DOUBLE_EQ(0.5, links->at(0)->score()); } TEST_F(ExtensionDiscoveryTest, SuggestWithoutScore) { RunFunction(new DiscoverySuggestFunction(), UnscoredSuggestParamsToJSON("https://amazon.com/", "Amazon")); extensions::SuggestedLinksRegistry* registry = extensions::SuggestedLinksRegistryFactory::GetForProfile( browser()->profile()); const SuggestedLinkList* links = registry->GetAll(GetExtensionId()); ASSERT_EQ(1u, links->size()); ASSERT_EQ("https://amazon.com/", links->at(0)->link_url()); ASSERT_EQ("Amazon", links->at(0)->link_text()); ASSERT_DOUBLE_EQ(1.0, links->at(0)->score()); // Score should default to 1. } TEST_F(ExtensionDiscoveryTest, SuggestTwiceSameUrl) { // Suggesting the same URL a second time should override the first. RunFunction(new DiscoverySuggestFunction(), SuggestParamsToJSON("http://www.google.com", "Google", 0.5)); RunFunction(new DiscoverySuggestFunction(), SuggestParamsToJSON("http://www.google.com", "Google2", 0.1)); extensions::SuggestedLinksRegistry* registry = extensions::SuggestedLinksRegistryFactory::GetForProfile( browser()->profile()); const SuggestedLinkList* links = registry->GetAll(GetExtensionId()); ASSERT_EQ(1u, links->size()); ASSERT_EQ("http://www.google.com", links->at(0)->link_url()); ASSERT_EQ("Google2", links->at(0)->link_text()); ASSERT_DOUBLE_EQ(0.1, links->at(0)->score()); } TEST_F(ExtensionDiscoveryTest, Remove) { RunFunction(new DiscoverySuggestFunction(), UnscoredSuggestParamsToJSON("http://www.google.com", "Google")); RunFunction(new DiscoverySuggestFunction(), UnscoredSuggestParamsToJSON("https://amazon.com/", "Amazon")); RunFunction(new DiscoverySuggestFunction(), UnscoredSuggestParamsToJSON("http://www.youtube.com/watch?v=zH5bJSG0DZk", "YouTube")); RunFunction(new DiscoveryRemoveSuggestionFunction(), RemoveSuggestionParamsToJSON("https://amazon.com/")); extensions::SuggestedLinksRegistry* registry = extensions::SuggestedLinksRegistryFactory::GetForProfile( browser()->profile()); const SuggestedLinkList* links = registry->GetAll(GetExtensionId()); ASSERT_EQ(2u, links->size()); ASSERT_EQ("http://www.google.com", links->at(0)->link_url()); ASSERT_EQ("Google", links->at(0)->link_text()); ASSERT_DOUBLE_EQ(1.0, links->at(0)->score()); ASSERT_EQ("http://www.youtube.com/watch?v=zH5bJSG0DZk", links->at(1)->link_url()); ASSERT_EQ("YouTube", links->at(1)->link_text()); ASSERT_DOUBLE_EQ(1.0, links->at(1)->score()); } TEST_F(ExtensionDiscoveryTest, ClearAll) { RunFunction(new DiscoverySuggestFunction(), UnscoredSuggestParamsToJSON("http://www.google.com", "Google")); RunFunction(new DiscoverySuggestFunction(), UnscoredSuggestParamsToJSON("https://amazon.com/", "Amazon")); RunFunction(new DiscoverySuggestFunction(), UnscoredSuggestParamsToJSON("http://www.youtube.com/watch?v=zH5bJSG0DZk", "YouTube")); RunFunction(new DiscoveryClearAllSuggestionsFunction(), "[]"); extensions::SuggestedLinksRegistry* registry = extensions::SuggestedLinksRegistryFactory::GetForProfile( browser()->profile()); const SuggestedLinkList* links = registry->GetAll(GetExtensionId()); ASSERT_EQ(0u, links->size()); } } // namespace extensions
39.727749
85
0.730232
nagineni
c01e6226129e42352202a53cc0a8e810e048e6c2
2,217
cpp
C++
src/platform/new_platform/core.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
11
2015-03-02T07:43:00.000Z
2021-12-04T04:53:02.000Z
src/platform/new_platform/core.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
1
2015-03-28T17:17:13.000Z
2016-10-10T05:49:07.000Z
src/platform/new_platform/core.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
3
2016-11-04T01:14:31.000Z
2020-05-07T23:42:27.000Z
/**************************** Copyright (c) 2006-2012 Luke Salisbury Copyright (c) 2008 Mokoi Gaming This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ****************************/ #include "core.h" #include "luxengine.h" /* Local functions */ CoreSystem::CoreSystem() { } CoreSystem::~CoreSystem() { } uint32_t CoreSystem::WasInit(uint32_t flag) { return 1; } void CoreSystem::QuitSubSystem(uint32_t flag) { } bool CoreSystem::InitSubSystem(uint32_t flag) { return true; } bool CoreSystem::Good() { return this->good; } uint32_t CoreSystem::GetTime() { return 0; } uint32_t CoreSystem::GetFrameDelta() { return 15; } bool CoreSystem::DelayIf(uint32_t diff) { return false; } void CoreSystem::Idle() { } LuxState CoreSystem::HandleFrame(LuxState old_state) { if ( this->state > PAUSED || old_state >= SAVING ) { this->state = old_state; } this->RefreshInput(lux::display); this->time = this->GetTime(); return this->state; } int16_t CoreSystem::GetInput(InputDevice device, uint32_t device_number, int32_t symbol) { if (device == NOINPUT) { return 0; } switch (device) { case CONTROLAXIS: { return 0; } case CONTROLBUTTON: { return 0; } case KEYBOARD: case MOUSEAXIS: case MOUSEBUTTON: case NOINPUT: default: return 0; } return 0; } void CoreSystem::RefreshInput( DisplaySystem * display ) { } bool CoreSystem::InputLoopGet(uint16_t & key) { // Keyboard Stuff return 0; }
18.322314
243
0.710419
mokoi
c01e790dfd13056cad4bc72c791246ca9810980b
6,602
cc
C++
mysql-server/plugin/test_services/test_services_threaded.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/plugin/test_services/test_services_threaded.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/plugin/test_services/test_services_threaded.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #define LOG_COMPONENT_TAG "test_services_threaded" #include <fcntl.h> #include <mysql/plugin.h> #include <mysql_version.h> #include <stdlib.h> #include <mysql/components/my_service.h> #include <mysql/components/services/log_builtins.h> #include <mysqld_error.h> #include "m_string.h" // strlen #include "my_dbug.h" #include "my_inttypes.h" #include "my_io.h" #include "my_sys.h" // my_write, my_malloc #include "sql/sql_plugin.h" // st_plugin_int #define STRING_BUFFER 256 static SERVICE_TYPE(registry) *reg_srv = nullptr; SERVICE_TYPE(log_builtins) *log_bi = nullptr; SERVICE_TYPE(log_builtins_string) *log_bs = nullptr; File outfile; struct test_services_context { my_thread_handle test_services_thread; }; /* Shows status of test (Busy/READY) */ enum t_test_status { BUSY = 0, READY = 1 }; static t_test_status test_status; /* declaration of status variable for plugin */ static SHOW_VAR test_services_status[] = { {"test_services_status", (char *)&test_status, SHOW_INT, SHOW_SCOPE_GLOBAL}, {nullptr, nullptr, SHOW_UNDEF, SHOW_SCOPE_GLOBAL}}; /* SQL variables to control test execution */ /* SQL variables to switch on/off test of services, default=on */ /* Only be effective at start od mysqld by setting it as option --loose-... */ static int with_log_message_val = 0; static MYSQL_SYSVAR_INT(with_log_message, with_log_message_val, PLUGIN_VAR_RQCMDARG, "Switch on/off test of log message service", nullptr, nullptr, 1, 0, 1, 0); static SYS_VAR *test_services_sysvars[] = {MYSQL_SYSVAR(with_log_message), nullptr}; /* The test cases for the log_message service. */ static int test_log_plugin_error() { DBUG_TRACE; /* Writes to mysqld.1.err: Plugin test_services reports an info text */ LogPluginErr(INFORMATION_LEVEL, ER_LOG_PRINTF_MSG, "This is the test plugin for services"); /* Writes to mysqld.1.err: Plugin test_services reports a warning. */ LogPluginErr(WARNING_LEVEL, ER_LOG_PRINTF_MSG, "This is a warning from test plugin for services"); /* Writes to mysqld.1.err: Plugin test_services reports an error. */ LogPluginErr(ERROR_LEVEL, ER_LOG_PRINTF_MSG, "This is an error from test plugin for services"); return 0; } /* This fucntion is needed to be called in a thread. */ static void *test_services(void *p MY_ATTRIBUTE((unused))) { DBUG_TRACE; int ret = 0; test_status = BUSY; /* Test of service: LogPluginErr/LogPluginErrMsg */ /* Log the value of the switch in mysqld.err. */ LogPluginErrMsg(INFORMATION_LEVEL, ER_LOG_PRINTF_MSG, "Test_services_threaded with_log_message_val: %d", with_log_message_val); if (with_log_message_val == 1) { ret = test_log_plugin_error(); } else { LogPluginErr(INFORMATION_LEVEL, ER_LOG_PRINTF_MSG, "Test of log_message switched off"); } test_status = READY; if (ret != 0) { LogPluginErr(ERROR_LEVEL, ER_LOG_PRINTF_MSG, "Test services return code: %d", ret); } return nullptr; } /* Creates the plugin context "con", which holds a pointer to the thread. */ static int test_services_plugin_init(void *p) { DBUG_TRACE; int ret = 0; if (init_logging_service_for_plugin(&reg_srv, &log_bi, &log_bs)) return 1; struct test_services_context *con; my_thread_attr_t attr; /* Thread attributes */ struct st_plugin_int *plugin = (struct st_plugin_int *)p; con = (struct test_services_context *)my_malloc( PSI_INSTRUMENT_ME, sizeof(struct test_services_context), MYF(0)); my_thread_attr_init(&attr); (void)my_thread_attr_setdetachstate(&attr, MY_THREAD_CREATE_JOINABLE); /* now create the thread and call test_services within the thread. */ if (my_thread_create(&con->test_services_thread, &attr, test_services, p) != 0) { LogPluginErr(ERROR_LEVEL, ER_LOG_PRINTF_MSG, "Could not create test services thread!"); exit(0); } plugin->data = (void *)con; return ret; } /* Clean up thread and frees plugin context "con". */ static int test_services_plugin_deinit(void *p) { DBUG_TRACE; void *dummy_retval; struct st_plugin_int *plugin = (struct st_plugin_int *)p; struct test_services_context *con = (struct test_services_context *)plugin->data; my_thread_cancel(&con->test_services_thread); my_thread_join(&con->test_services_thread, &dummy_retval); my_free(con); deinit_logging_service_for_plugin(&reg_srv, &log_bi, &log_bs); return 0; } /* Mandatory structure describing the properties of the plugin. */ struct st_mysql_daemon test_services_plugin = {MYSQL_DAEMON_INTERFACE_VERSION}; mysql_declare_plugin(test_daemon){ MYSQL_DAEMON_PLUGIN, &test_services_plugin, "test_services_threaded", PLUGIN_AUTHOR_ORACLE, "Test services with thread", PLUGIN_LICENSE_GPL, test_services_plugin_init, /* Plugin Init */ nullptr, /* Plugin Check uninstall */ test_services_plugin_deinit, /* Plugin Deinit */ 0x0100 /* 1.0 */, test_services_status, /* status variables */ test_services_sysvars, /* system variables */ nullptr, /* config options */ 0, /* flags */ } mysql_declare_plugin_end;
36.677778
80
0.701303
silenc3502
c01e99d338af868bb582256ac0f9af184f503bde
1,206
hxx
C++
opencascade/Quantity_Impedance.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/Quantity_Impedance.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/Quantity_Impedance.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 1994-02-08 // Created by: Gilles DEBARBOUILLE // Copyright (c) 1994-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Quantity_Impedance_HeaderFile #define _Quantity_Impedance_HeaderFile #include <Standard_Real.hxx> //! Defined as the total opposition to the flow of current //! in a circuit. Includes the contributions of resistance, //! inductance, and capacitance. //! It is measured in Ohms. Standard_DEPRECATED("This type is deprecated - Standard_Real should be used instead") typedef Standard_Real Quantity_Impedance; #endif // _Quantity_Impedance_HeaderFile
40.2
85
0.786899
valgur
c01ec0ba11fccfd8dec8a82f9f618516f2ab74da
5,340
hpp
C++
oscc/firmware/common/testing/framework/cucumber-cpp/include/cucumber-cpp/internal/step/StepManager.hpp
OAkyildiz/oscc-joystick-commander
c3cacef72b7fe02c84ffb6f697cbbe303b845304
[ "MIT" ]
1
2021-02-23T12:19:43.000Z
2021-02-23T12:19:43.000Z
oscc/firmware/common/testing/framework/cucumber-cpp/include/cucumber-cpp/internal/step/StepManager.hpp
WoodpeckerCar/Woodpecker_CAN_Controller
91fdecdaacb1eb5d866d0c00701f40dad89d16b6
[ "Apache-2.0", "MIT" ]
null
null
null
oscc/firmware/common/testing/framework/cucumber-cpp/include/cucumber-cpp/internal/step/StepManager.hpp
WoodpeckerCar/Woodpecker_CAN_Controller
91fdecdaacb1eb5d866d0c00701f40dad89d16b6
[ "Apache-2.0", "MIT" ]
1
2021-02-20T10:41:24.000Z
2021-02-20T10:41:24.000Z
#ifndef CUKE_STEPMANAGER_HPP_ #define CUKE_STEPMANAGER_HPP_ #include <map> #include <sstream> #include <stdexcept> #include <string> #include <vector> #include <boost/enable_shared_from_this.hpp> #include <boost/make_shared.hpp> #include <boost/shared_ptr.hpp> using boost::shared_ptr; #include "../Table.hpp" #include "../utils/Regex.hpp" namespace cucumber { namespace internal { typedef unsigned int step_id_type; class StepInfo; class SingleStepMatch { public: typedef RegexMatch::submatches_type submatches_type; operator const void *() const; boost::shared_ptr<const StepInfo> stepInfo; submatches_type submatches; }; class MatchResult { public: typedef std::vector<SingleStepMatch> match_results_type; const match_results_type& getResultSet(); void addMatch(SingleStepMatch match); operator void *(); operator bool() const; private: match_results_type resultSet; }; class InvokeArgs { typedef std::vector<std::string> args_type; public: typedef args_type::size_type size_type; InvokeArgs() { } void addArg(const std::string arg); Table & getVariableTableArg(); template<class T> T getInvokeArg(size_type i) const; const Table & getTableArg() const; private: Table tableArg; args_type args; }; enum InvokeResultType { SUCCESS, FAILURE, PENDING }; class InvokeResult { private: InvokeResultType type; std::string description; InvokeResult(const InvokeResultType type, const char *description); public: InvokeResult(); InvokeResult(const InvokeResult &ir); InvokeResult& operator= (const InvokeResult& rhs); static InvokeResult success(); static InvokeResult failure(const char *description); static InvokeResult failure(const std::string &description); static InvokeResult pending(const char *description); bool isSuccess() const; bool isPending() const; InvokeResultType getType() const; const std::string &getDescription() const; }; class StepInfo : public boost::enable_shared_from_this<StepInfo> { public: StepInfo(const std::string &stepMatcher, const std::string source); SingleStepMatch matches(const std::string &stepDescription) const; virtual InvokeResult invokeStep(const InvokeArgs * pArgs) const = 0; step_id_type id; Regex regex; const std::string source; private: StepInfo& operator=(const StepInfo& other); }; class BasicStep { public: InvokeResult invoke(const InvokeArgs *pArgs); protected: typedef const Table table_type; typedef const Table::hashes_type table_hashes_type; virtual const InvokeResult invokeStepBody() = 0; virtual void body() = 0; void pending(const char *description); void pending(); template<class T> const T getInvokeArg(); const InvokeArgs *getArgs(); private: // FIXME: awful hack because of Boost::Test InvokeResult currentResult; const InvokeArgs *pArgs; InvokeArgs::size_type currentArgIndex; }; template<class T> class StepInvoker : public StepInfo { public: StepInvoker(const std::string &stepMatcher, const std::string source); InvokeResult invokeStep(const InvokeArgs *args) const; }; class StepManager { protected: typedef std::map<step_id_type, boost::shared_ptr<const StepInfo> > steps_type; public: virtual ~StepManager(); void addStep(const boost::shared_ptr<StepInfo>& stepInfo); MatchResult stepMatches(const std::string &stepDescription) const; const boost::shared_ptr<const StepInfo>& getStep(step_id_type id); protected: steps_type& steps() const; }; static inline std::string toSourceString(const char *filePath, const int line) { using namespace std; stringstream s; string file(filePath); string::size_type pos = file.find_last_of("/\\"); if (pos == string::npos) { s << file; } else { s << file.substr(++pos); } s << ":" << line; return s.str(); } template<class T> static int registerStep(const std::string &stepMatcher, const char *file, const int line) { StepManager s; boost::shared_ptr<StepInfo> stepInfo(boost::make_shared< StepInvoker<T> >(stepMatcher, toSourceString(file, line))); s.addStep(stepInfo); return stepInfo->id; } template<typename T> T fromString(const std::string& s) { std::istringstream stream(s); T t; stream >> t; if (stream.fail()) { throw std::invalid_argument("Cannot convert parameter"); } return t; } template<> inline std::string fromString(const std::string& s) { return s; } template<typename T> std::string toString(T arg) { std::stringstream s; s << arg; return s.str(); } template<typename T> T InvokeArgs::getInvokeArg(size_type i) const { if (i >= args.size()) { throw std::invalid_argument("Parameter not found"); } return fromString<T>(args.at(i)); } template<typename T> const T BasicStep::getInvokeArg() { return pArgs->getInvokeArg<T>(currentArgIndex++); } template<class T> StepInvoker<T>::StepInvoker(const std::string &stepMatcher, const std::string source) : StepInfo(stepMatcher, source) { } template<class T> InvokeResult StepInvoker<T>::invokeStep(const InvokeArgs *pArgs) const { T t; return t.invoke(pArgs); } } } #endif /* CUKE_STEPMANAGER_HPP_ */
22.436975
119
0.702809
OAkyildiz
c01f617cb9017521a068d7edca194aaf09351377
3,123
hpp
C++
Runtime/World/CScriptEffect.hpp
jackoalan/urde
413483a996805a870f002324ee46cfc123f4df06
[ "MIT" ]
null
null
null
Runtime/World/CScriptEffect.hpp
jackoalan/urde
413483a996805a870f002324ee46cfc123f4df06
[ "MIT" ]
null
null
null
Runtime/World/CScriptEffect.hpp
jackoalan/urde
413483a996805a870f002324ee46cfc123f4df06
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <string_view> #include "Runtime/GCNTypes.hpp" #include "Runtime/World/CActor.hpp" namespace urde { class CElementGen; class CParticleElectric; class CScriptEffect : public CActor { static u32 g_NumParticlesUpdating; static u32 g_NumParticlesRendered; TLockedToken<CElectricDescription> xe8_electricToken; std::unique_ptr<CParticleElectric> xf4_electric; TLockedToken<CGenDescription> xf8_particleSystemToken; std::unique_ptr<CElementGen> x104_particleSystem; TUniqueId x108_lightId = kInvalidUniqueId; CAssetId x10c_partId; union { struct { bool x110_24_enable : 1; bool x110_25_noTimerUnlessAreaOccluded : 1; bool x110_26_rebuildSystemsOnActivate : 1; bool x110_27_useRateInverseCamDist : 1; bool x110_28_combatVisorVisible : 1; bool x110_29_thermalVisorVisible : 1; bool x110_30_xrayVisorVisible : 1; bool x110_31_anyVisorVisible : 1; bool x111_24_useRateCamDistRange : 1; bool x111_25_dieWhenSystemsDone : 1; bool x111_26_canRender : 1; }; u32 _dummy = 0; }; float x114_rateInverseCamDist; float x118_rateInverseCamDistSq; float x11c_rateInverseCamDistRate; float x120_rateCamDistRangeMin; float x124_rateCamDistRangeMax; float x128_rateCamDistRangeFarRate; float x12c_remTime; float x130_duration; float x134_durationResetWhileVisible; std::unique_ptr<CActorLights> x138_actorLights; TUniqueId x13c_triggerId = kInvalidUniqueId; float x140_destroyDelayTimer = 0.f; public: CScriptEffect(TUniqueId uid, std::string_view name, const CEntityInfo& info, const zeus::CTransform& xf, const zeus::CVector3f& scale, CAssetId partId, CAssetId elscId, bool hotInThermal, bool noTimerUnlessAreaOccluded, bool rebuildSystemsOnActivate, bool active, bool useRateInverseCamDist, float rateInverseCamDist, float rateInverseCamDistRate, float duration, float durationResetWhileVisible, bool useRateCamDistRange, float rateCamDistRangeMin, float rateCamDistRangeMax, float rateCamDistRangeFarRate, bool combatVisorVisible, bool thermalVisorVisible, bool xrayVisorVisible, const CLightParameters& lParms, bool dieWhenSystemsDone); void Accept(IVisitor& visitor) override; void AcceptScriptMsg(EScriptObjectMessage, TUniqueId, CStateManager&) override; void PreRender(CStateManager&, const zeus::CFrustum&) override; void AddToRenderer(const zeus::CFrustum&, const CStateManager&) const override; void Render(const CStateManager&) const override; void Think(float, CStateManager&) override; bool CanRenderUnsorted(const CStateManager&) const override { return false; } void SetActive(bool active) override { CActor::SetActive(active); xe7_29_drawEnabled = true; } void CalculateRenderBounds() override; zeus::CAABox GetSortingBounds(const CStateManager&) const override; bool AreBothSystemsDeleteable() const; static void ResetParticleCounts() { g_NumParticlesUpdating = 0; g_NumParticlesRendered = 0; } }; } // namespace urde
38.555556
120
0.764649
jackoalan
c02105ca76cfa0deb6e5570e2a8c6572fc076a14
3,828
cpp
C++
tools/clang/test/CXX/dcl.decl/dcl.meaning/dcl.ref/p5.cpp
clayne/DirectXShaderCompiler
0ef9b702890b1d45f0bec5fa75481290323e14dc
[ "NCSA" ]
3,102
2015-01-04T02:28:35.000Z
2022-03-30T12:53:41.000Z
tools/clang/test/CXX/dcl.decl/dcl.meaning/dcl.ref/p5.cpp
clayne/DirectXShaderCompiler
0ef9b702890b1d45f0bec5fa75481290323e14dc
[ "NCSA" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
tools/clang/test/CXX/dcl.decl/dcl.meaning/dcl.ref/p5.cpp
clayne/DirectXShaderCompiler
0ef9b702890b1d45f0bec5fa75481290323e14dc
[ "NCSA" ]
1,868
2015-01-03T04:27:11.000Z
2022-03-25T13:37:35.000Z
// RUN: %clang_cc1 -fsyntax-only -verify %s // C++ [dcl.ref]p5: // There shall be no references to references, no arrays of // references, and no pointers to references. // The crazy formatting in here is to enforce the exact report locations. typedef int &intref; typedef intref &intrefref; template <class T> class RefMem { // expected-warning{{class 'RefMem<int &>' does not declare any constructor to initialize its non-modifiable members}} T & member; // expected-note{{reference member 'member' will never be initialized}} }; struct RefRef { int & & // expected-error {{declared as a reference to a reference}} refref0; intref & refref1; // collapses intrefref & refref2; // collapses RefMem < int & > refref3; // collapses expected-note{{in instantiation of template class 'RefMem<int &>' requested here}} }; template <class T> class PtrMem { T * // expected-error {{declared as a pointer to a reference}} member; }; struct RefPtr { typedef int & * // expected-error {{declared as a pointer to a reference}} intrefptr; typedef intref * // expected-error {{declared as a pointer to a reference}} intrefptr2; int & * // expected-error {{declared as a pointer to a reference}} refptr0; intref * // expected-error {{declared as a pointer to a reference}} refptr1; PtrMem < int & > refptr2; // expected-note {{in instantiation}} }; template <class T> class ArrMem { T member [ // expected-error {{declared as array of references}} 10 ]; }; template <class T, unsigned N> class DepArrMem { T member [ // expected-error {{declared as array of references}} N ]; }; struct RefArr { typedef int & intrefarr [ // expected-error {{declared as array of references}} 2 ]; typedef intref intrefarr [ // expected-error {{declared as array of references}} 2 ]; int & refarr0 [ // expected-error {{declared as array of references}} 2 ]; intref refarr1 [ // expected-error {{declared as array of references}} 2 ]; ArrMem < int & > refarr2; // expected-note {{in instantiation}} DepArrMem < int &, 10 > refarr3; // expected-note {{in instantiation}} }; // The declaration of a reference shall contain an initializer // (8.5.3) except when the declaration contains an explicit extern // specifier (7.1.1), is a class member (9.2) declaration within a // class definition, or is the declaration of a parameter or a // return type (8.3.5); see 3.1. A reference shall be initialized to // refer to a valid object or function. [ Note: in particular, a // null reference cannot exist in a well-defined program, because // the only way to create such a reference would be to bind it to // the "object" obtained by dereferencing a null pointer, which // causes undefined behavior. As described in 9.6, a reference // cannot be bound directly to a bit-field.
26.219178
152
0.515935
clayne
c0211263b554e3e0e0447535d61fdbbf331b1d03
2,468
cpp
C++
input-output_example_gen/bench/gramschmidt.cpp
dongchen-coder/symRIByInputOuputExamples
e7434699f44ceb01f153ac8623b5bafac57f8abf
[ "MIT" ]
null
null
null
input-output_example_gen/bench/gramschmidt.cpp
dongchen-coder/symRIByInputOuputExamples
e7434699f44ceb01f153ac8623b5bafac57f8abf
[ "MIT" ]
null
null
null
input-output_example_gen/bench/gramschmidt.cpp
dongchen-coder/symRIByInputOuputExamples
e7434699f44ceb01f153ac8623b5bafac57f8abf
[ "MIT" ]
null
null
null
#include "./utility/rt.h" #include <math.h> int N; int M; #define A_OFFSET 0 #define R_OFFSET N * M #define Q_OFFSET N * M + N * N void gramschmidt_trace(double* A, double* R, double* Q) { int k, i, j; double nrm; vector<int> idx; for (k = 0; k < N; k++) { nrm = 0.0; for (i = 0; i < M; i++) { idx.clear(); idx.push_back(k); idx.push_back(i); nrm += A[i * N + k] * A[i * N + k]; rtTmpAccess(A_OFFSET + i * N + k, 0, 0, idx); rtTmpAccess(A_OFFSET + i * N + k, 1, 0, idx); } idx.clear(); idx.push_back(k); R[k * N + k] = sqrt(nrm); rtTmpAccess(R_OFFSET + k * N + k, 2, 1, idx); for (i = 0; i < M; i++) { idx.clear(); idx.push_back(k); idx.push_back(i); Q[i * N + k] = A[i * N + k] / R[k * N + k]; rtTmpAccess(A_OFFSET + i * N + k, 3, 0, idx); rtTmpAccess(R_OFFSET + k * N + k, 4, 1, idx); rtTmpAccess(Q_OFFSET + i * N + k, 5, 2, idx); } for (j = k + 1; j < N; j++) { idx.clear(); idx.push_back(k); idx.push_back(j); R[k * N + j] = 0.0; rtTmpAccess(R_OFFSET + k * N + j, 6, 1, idx); for (i = 0; i < M; i++) { idx.clear(); idx.push_back(k); idx.push_back(j); idx.push_back(i); R[k * N + j] += Q[i * N + k] * A[i * N + j]; rtTmpAccess(Q_OFFSET + i * N + k, 7, 2, idx); rtTmpAccess(A_OFFSET + i * N + j, 8, 0, idx); rtTmpAccess(R_OFFSET + k * N + j, 9, 1, idx); rtTmpAccess(R_OFFSET + k * N + j, 10, 1, idx); } for (i = 0; i < M; i++) { idx.clear(); idx.push_back(k); idx.push_back(j); idx.push_back(i); A[i * N + j] = A[i * N + j] - Q[i * N + k] * R[k * N + j]; rtTmpAccess(A_OFFSET + i * N + j, 11, 0, idx); rtTmpAccess(Q_OFFSET + i * N + k, 12, 2, idx); rtTmpAccess(R_OFFSET + k * N + j, 13, 1, idx); rtTmpAccess(A_OFFSET + i * N + j, 14, 0, idx); } } } } int main(int argc, char* argv[]) { if (argc != 3) { cout << "This benchmark needs 2 loop bounds" << endl; return 0; } for (int i = 1; i < argc; i++) { if (!isdigit(argv[i][0])) { cout << "arguments must be integer" << endl; return 0; } } M = stoi(argv[1]); N = stoi(argv[2]); double * A = (double *)malloc(N * M * sizeof(double)); double * R = (double *)malloc(N * N * sizeof(double)); double * Q = (double *)malloc(M * N * sizeof(double)); gramschmidt_trace(A, R, Q); dumpRIHistogram(); return 0; }
29.035294
82
0.487844
dongchen-coder
c02159588cf3470fdc6f54a34837abb9ee14a163
8,958
hpp
C++
include/eosio/time.hpp
swang-b1/abieos
52ea28c0c2d771d101a2fe0ae4d176bb35a2f0cb
[ "MIT" ]
71
2019-05-17T03:02:30.000Z
2022-02-11T03:59:10.000Z
include/eosio/time.hpp
swang-b1/abieos
52ea28c0c2d771d101a2fe0ae4d176bb35a2f0cb
[ "MIT" ]
49
2019-05-21T18:52:57.000Z
2022-03-07T16:44:40.000Z
include/eosio/time.hpp
swang-b1/abieos
52ea28c0c2d771d101a2fe0ae4d176bb35a2f0cb
[ "MIT" ]
36
2018-07-19T02:40:22.000Z
2022-03-14T13:51:59.000Z
#pragma once #include "chain_conversions.hpp" #include "check.hpp" #include "operators.hpp" #include "reflection.hpp" #include "from_json.hpp" #include <stdint.h> #include <string> namespace eosio { /** * @defgroup time * @ingroup core * @brief Classes for working with time. */ class microseconds { public: microseconds() = default; explicit microseconds(int64_t c) : _count(c) {} /// @cond INTERNAL static microseconds maximum() { return microseconds(0x7fffffffffffffffll); } friend microseconds operator+(const microseconds& l, const microseconds& r) { return microseconds(l._count + r._count); } friend microseconds operator-(const microseconds& l, const microseconds& r) { return microseconds(l._count - r._count); } microseconds& operator+=(const microseconds& c) { _count += c._count; return *this; } microseconds& operator-=(const microseconds& c) { _count -= c._count; return *this; } int64_t count() const { return _count; } int64_t to_seconds() const { return _count / 1000000; } int64_t _count = 0; /// @endcond }; EOSIO_REFLECT(microseconds, _count); EOSIO_COMPARE(microseconds); inline microseconds seconds(int64_t s) { return microseconds(s * 1000000); } inline microseconds milliseconds(int64_t s) { return microseconds(s * 1000); } inline microseconds minutes(int64_t m) { return seconds(60 * m); } inline microseconds hours(int64_t h) { return minutes(60 * h); } inline microseconds days(int64_t d) { return hours(24 * d); } /** * High resolution time point in microseconds * * @ingroup time */ class time_point { public: time_point() = default; explicit time_point(microseconds e) : elapsed(e) {} const microseconds& time_since_epoch() const { return elapsed; } uint32_t sec_since_epoch() const { return uint32_t(elapsed.count() / 1000000); } static time_point max() { return time_point( microseconds::maximum() ); } /// @cond INTERNAL time_point& operator+=(const microseconds& m) { elapsed += m; return *this; } time_point& operator-=(const microseconds& m) { elapsed -= m; return *this; } time_point operator+(const microseconds& m) const { return time_point(elapsed + m); } time_point operator+(const time_point& m) const { return time_point(elapsed + m.elapsed); } time_point operator-(const microseconds& m) const { return time_point(elapsed - m); } microseconds operator-(const time_point& m) const { return microseconds(elapsed.count() - m.elapsed.count()); } microseconds elapsed; /// @endcond }; EOSIO_REFLECT(time_point, elapsed); EOSIO_COMPARE(time_point); template <typename S> void from_json(time_point& obj, S& stream) { auto s = stream.get_string(); uint64_t utc_microseconds; if (!eosio::string_to_utc_microseconds(utc_microseconds, s.data(), s.data() + s.size())) { check(false, convert_json_error(eosio::from_json_error::expected_time_point)); } obj = time_point(microseconds(utc_microseconds)); } template <typename S> void to_json(const time_point& obj, S& stream) { return to_json(eosio::microseconds_to_str(obj.elapsed._count), stream); } /** * A lower resolution time_point accurate only to seconds from 1970 * * @ingroup time */ class time_point_sec { public: time_point_sec() : utc_seconds(0) {} explicit time_point_sec(uint32_t seconds) : utc_seconds(seconds) {} time_point_sec(const time_point& t) : utc_seconds(uint32_t(t.time_since_epoch().count() / 1000000ll)) {} static time_point_sec maximum() { return time_point_sec(0xffffffff); } static time_point_sec min() { return time_point_sec(0); } operator time_point() const { return time_point(eosio::seconds(utc_seconds)); } uint32_t sec_since_epoch() const { return utc_seconds; } /// @cond INTERNAL time_point_sec operator=(const eosio::time_point& t) { utc_seconds = uint32_t(t.time_since_epoch().count() / 1000000ll); return *this; } time_point_sec& operator+=(uint32_t m) { utc_seconds += m; return *this; } time_point_sec& operator+=(microseconds m) { utc_seconds += m.to_seconds(); return *this; } time_point_sec& operator+=(time_point_sec m) { utc_seconds += m.utc_seconds; return *this; } time_point_sec& operator-=(uint32_t m) { utc_seconds -= m; return *this; } time_point_sec& operator-=(microseconds m) { utc_seconds -= m.to_seconds(); return *this; } time_point_sec& operator-=(time_point_sec m) { utc_seconds -= m.utc_seconds; return *this; } time_point_sec operator+(uint32_t offset) const { return time_point_sec(utc_seconds + offset); } time_point_sec operator-(uint32_t offset) const { return time_point_sec(utc_seconds - offset); } friend time_point operator+(const time_point_sec& t, const microseconds& m) { return time_point(t) + m; } friend time_point operator-(const time_point_sec& t, const microseconds& m) { return time_point(t) - m; } friend microseconds operator-(const time_point_sec& t, const time_point_sec& m) { return time_point(t) - time_point(m); } friend microseconds operator-(const time_point& t, const time_point_sec& m) { return time_point(t) - time_point(m); } uint32_t utc_seconds; /// @endcond }; EOSIO_REFLECT(time_point_sec, utc_seconds); EOSIO_COMPARE(time_point); template <typename S> void from_json(time_point_sec& obj, S& stream) { auto s = stream.get_string(); const char* p = s.data(); if (!eosio::string_to_utc_seconds(obj.utc_seconds, p, s.data() + s.size(), true, true)) { check(false, convert_json_error(from_json_error::expected_time_point)); } } template <typename S> void to_json(const time_point_sec& obj, S& stream) { return to_json(eosio::microseconds_to_str(uint64_t(obj.utc_seconds) * 1'000'000), stream); } /** * This class is used in the block headers to represent the block time * It is a parameterised class that takes an Epoch in milliseconds and * and an interval in milliseconds and computes the number of slots. * * @ingroup time **/ class block_timestamp { public: block_timestamp() = default; explicit block_timestamp(uint32_t s) : slot(s) {} block_timestamp(const time_point& t) { set_time_point(t); } block_timestamp(const time_point_sec& t) { set_time_point(t); } static block_timestamp maximum() { return block_timestamp(0xffff); } static block_timestamp min() { return block_timestamp(0); } block_timestamp next() const { eosio::check(std::numeric_limits<uint32_t>::max() - slot >= 1, "block timestamp overflow"); auto result = block_timestamp(*this); result.slot += 1; return result; } time_point to_time_point() const { return (time_point)(*this); } operator time_point() const { int64_t msec = slot * (int64_t)block_interval_ms; msec += block_timestamp_epoch; return time_point(milliseconds(msec)); } /// @cond INTERNAL void operator=(const time_point& t) { set_time_point(t); } bool operator>(const block_timestamp& t) const { return slot > t.slot; } bool operator>=(const block_timestamp& t) const { return slot >= t.slot; } bool operator<(const block_timestamp& t) const { return slot < t.slot; } bool operator<=(const block_timestamp& t) const { return slot <= t.slot; } bool operator==(const block_timestamp& t) const { return slot == t.slot; } bool operator!=(const block_timestamp& t) const { return slot != t.slot; } uint32_t slot = 0; static constexpr int32_t block_interval_ms = 500; static constexpr int64_t block_timestamp_epoch = 946684800000ll; // epoch is year 2000 /// @endcond private: void set_time_point(const time_point& t) { int64_t micro_since_epoch = t.time_since_epoch().count(); int64_t msec_since_epoch = micro_since_epoch / 1000; slot = uint32_t((msec_since_epoch - block_timestamp_epoch) / int64_t(block_interval_ms)); } void set_time_point(const time_point_sec& t) { int64_t sec_since_epoch = t.sec_since_epoch(); slot = uint32_t((sec_since_epoch * 1000 - block_timestamp_epoch) / block_interval_ms); } }; // block_timestamp /** * @ingroup time */ typedef block_timestamp block_timestamp_type; EOSIO_REFLECT(block_timestamp_type, slot); template <typename S> void from_json(block_timestamp& obj, S& stream) { time_point tp; from_json(tp, stream); obj = block_timestamp(tp); } template <typename S> void to_json(const block_timestamp& obj, S& stream) { return to_json(time_point(obj), stream); } } // namespace eosio
33.803774
120
0.674816
swang-b1
c0231d0ad488c3862a528706c7e05b0003e20dee
950
cpp
C++
sources/urlify_in_place/urlify_in_place.cpp
jacek143/code_area_template
57784b1d6139c6f7cb8be0ebd3fee162f1d5e558
[ "MIT" ]
null
null
null
sources/urlify_in_place/urlify_in_place.cpp
jacek143/code_area_template
57784b1d6139c6f7cb8be0ebd3fee162f1d5e558
[ "MIT" ]
null
null
null
sources/urlify_in_place/urlify_in_place.cpp
jacek143/code_area_template
57784b1d6139c6f7cb8be0ebd3fee162f1d5e558
[ "MIT" ]
null
null
null
#include "urlify_in_place.h" using urlify_in_place::buffer_t; namespace { struct Lengths { size_t current; size_t urlficated; }; Lengths compute_lengths(const buffer_t *p_buffer) { Lengths lengths = {0, 0}; for (size_t i = 0; p_buffer->at(i) != '\0'; i++) { lengths.current++; lengths.urlficated += p_buffer->at(i) == ' ' ? 3 : 1; } return lengths; } void urlify_knowing_lengths(buffer_t *p_buffer, Lengths lengths) { auto destination = lengths.urlficated; auto source = lengths.current; while (destination != source) { auto character = p_buffer->at(source--); if (character != ' ') { p_buffer->at(destination--) = character; } else { p_buffer->at(destination--) = '0'; p_buffer->at(destination--) = '2'; p_buffer->at(destination--) = '%'; } } } } // namespace void urlify_in_place::urlify(buffer_t *p_buffer) { urlify_knowing_lengths(p_buffer, compute_lengths(p_buffer)); }
24.358974
66
0.650526
jacek143
c02398d674739626eea07d0ea5211e05da1cfa0c
4,470
cpp
C++
NanoTest/Source/Nano/Threads/TThreadPool.cpp
refnum/Nano
dceb0907061f7845d8a3c662f309ca164e932e6f
[ "BSD-3-Clause" ]
23
2019-11-12T09:31:11.000Z
2021-09-13T08:59:37.000Z
NanoTest/Source/Nano/Threads/TThreadPool.cpp
refnum/nano
dceb0907061f7845d8a3c662f309ca164e932e6f
[ "BSD-3-Clause" ]
1
2020-10-30T09:54:12.000Z
2020-10-30T09:54:12.000Z
NanoTest/Source/Nano/Threads/TThreadPool.cpp
refnum/Nano
dceb0907061f7845d8a3c662f309ca164e932e6f
[ "BSD-3-Clause" ]
3
2015-09-08T11:00:02.000Z
2017-09-11T05:42:30.000Z
/* NAME: TThreadPool.cpp DESCRIPTION: NThreadPool tests. COPYRIGHT: Copyright (c) 2006-2021, refNum Software All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ___________________________________________________________________________ */ //============================================================================= // Includes //----------------------------------------------------------------------------- // Nano #include "NTestFixture.h" #include "NThreadPool.h" #include "NThreadTask.h" //============================================================================= // Fixture //----------------------------------------------------------------------------- NANO_FIXTURE(TThreadPool) { std::unique_ptr<NThreadPool> thePool; SETUP { thePool = std::make_unique<NThreadPool>("TThreadPool"); } }; //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TThreadPool, "Default") { // Perform the test REQUIRE(thePool->GetThreads() == 0); REQUIRE(thePool->GetMinThreads() == 1); REQUIRE(thePool->GetMaxThreads() != 0); } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TThreadPool, "IsPaused") { // Perform the test REQUIRE(!thePool->IsPaused()); thePool->Pause(); REQUIRE(thePool->IsPaused()); } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TThreadPool, "PauseResume") { // Perform the test REQUIRE(!thePool->IsPaused()); thePool->Pause(); REQUIRE(thePool->IsPaused()); thePool->Resume(); REQUIRE(!thePool->IsPaused()); } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TThreadPool, "AddFunction") { // Perform the test NSemaphore theSemaphore; thePool->Add( [&]() { theSemaphore.Signal(); }); REQUIRE(theSemaphore.Wait()); } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TThreadPool, "AddTask") { // Perform the test NSemaphore theSemaphore; auto theTask = std::make_shared<NThreadTask>( [&]() { theSemaphore.Signal(); }); thePool->Add(theTask); REQUIRE(theSemaphore.Wait()); } //============================================================================= // Test Case //----------------------------------------------------------------------------- NANO_TEST(TThreadPool, "GetMain") { // Perform the test NThreadPool* mainPool = NThreadPool::GetMain(); REQUIRE(mainPool != nullptr); REQUIRE(mainPool != thePool.get()); }
24.162162
79
0.521477
refnum
c025afc0be7c47112df000614fc188b7e266811c
9,171
cpp
C++
test/unit/msg-bus/MsgBus.cpp
cern-fts/fts3
cf9eb5c9f52728929965edf58a86381eec0c4e88
[ "Apache-2.0" ]
9
2018-06-27T09:53:51.000Z
2021-01-19T09:54:37.000Z
test/unit/msg-bus/MsgBus.cpp
cern-fts/fts3
cf9eb5c9f52728929965edf58a86381eec0c4e88
[ "Apache-2.0" ]
null
null
null
test/unit/msg-bus/MsgBus.cpp
cern-fts/fts3
cf9eb5c9f52728929965edf58a86381eec0c4e88
[ "Apache-2.0" ]
3
2018-07-13T06:17:44.000Z
2021-07-08T04:57:04.000Z
/* * Copyright (c) CERN 2016 * * 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 <boost/test/unit_test_suite.hpp> #include <boost/test/test_tools.hpp> #include <boost/filesystem.hpp> #include <boost/function.hpp> #include <glib.h> #include "msg-bus/consumer.h" #include "msg-bus/producer.h" using namespace fts3::events; namespace boost { bool operator==(const google::protobuf::Message &a, const google::protobuf::Message &b) { return a.SerializeAsString() == b.SerializeAsString(); } } namespace std { std::ostream &operator<<(std::ostream &os, const google::protobuf::Message &msg) { os << msg.DebugString(); return os; } } BOOST_AUTO_TEST_SUITE(MsgBusTest) class MsgBusFixture { protected: static const std::string TEST_PATH; public: MsgBusFixture() { boost::filesystem::create_directories(TEST_PATH); } ~MsgBusFixture() { boost::filesystem::remove_all(TEST_PATH); } }; const std::string MsgBusFixture::TEST_PATH("/tmp/MsgBusTest"); template <typename MSG_CONTAINER> static void expectZeroMessages(boost::function<int (Consumer*, MSG_CONTAINER&)> func, Consumer &consumer) { MSG_CONTAINER container; BOOST_CHECK_EQUAL(0, func(&consumer, container)); BOOST_CHECK_EQUAL(0, container.size()); } BOOST_FIXTURE_TEST_CASE (simpleStatus, MsgBusFixture) { Producer producer(TEST_PATH); Consumer consumer(TEST_PATH); Message original; original.set_job_id("1906cc40-b915-11e5-9a03-02163e006dd0"); original.set_transfer_status("FAILED"); original.set_transfer_message("TEST FAILURE, EVERYTHING IS TERRIBLE"); original.set_source_se("mock://source/file"); original.set_dest_se("mock://source/file2"); original.set_file_id(42); original.set_process_id(1234); original.set_time_in_secs(55); original.set_filesize(1023); original.set_nostreams(33); original.set_timeout(22); original.set_buffersize(1); original.set_retry(5); original.set_retry(0.2); original.set_timestamp(15689); original.set_throughput(0.88); BOOST_CHECK_EQUAL(0, producer.runProducerStatus(original)); // Make sure the messages don't get messed up expectZeroMessages<std::vector<MessageBringonline>>(&Consumer::runConsumerDeletions, consumer); expectZeroMessages<std::vector<MessageBringonline>>(&Consumer::runConsumerStaging, consumer); expectZeroMessages<std::map<int, MessageLog>>(&Consumer::runConsumerLog, consumer); expectZeroMessages<std::vector<std::string>>(&Consumer::runConsumerMonitoring, consumer); expectZeroMessages<std::vector<MessageUpdater>>(&Consumer::runConsumerStall, consumer); // First attempt must return the single message std::vector<Message> statuses; BOOST_CHECK_EQUAL(0, consumer.runConsumerStatus(statuses)); BOOST_CHECK_EQUAL(1, statuses.size()); BOOST_CHECK_EQUAL(statuses[0], original); // Second attempt must return empty (already consumed) statuses.clear(); BOOST_CHECK_EQUAL(0, consumer.runConsumerStatus(statuses)); BOOST_CHECK_EQUAL(0, statuses.size()); } BOOST_FIXTURE_TEST_CASE (simpleMonitoring, MsgBusFixture) { Producer producer(TEST_PATH); Consumer consumer(TEST_PATH); std::string original = "blah bleh blih bloh cluh"; BOOST_CHECK_EQUAL(0, producer.runProducerMonitoring(original)); // Make sure the messages don't get messed up expectZeroMessages<std::vector<Message>>(&Consumer::runConsumerStatus, consumer); expectZeroMessages<std::vector<MessageBringonline>>(&Consumer::runConsumerDeletions, consumer); expectZeroMessages<std::vector<MessageBringonline>>(&Consumer::runConsumerStaging, consumer); expectZeroMessages<std::map<int, MessageLog>>(&Consumer::runConsumerLog, consumer); expectZeroMessages<std::vector<MessageUpdater>>(&Consumer::runConsumerStall, consumer); // First attempt must return the single message std::vector<std::string> monitoring; BOOST_CHECK_EQUAL(0, consumer.runConsumerMonitoring(monitoring)); BOOST_CHECK_EQUAL(1, monitoring.size()); BOOST_CHECK_EQUAL(monitoring[0], original); // Second attempt must return empty (already consumed) monitoring.clear(); BOOST_CHECK_EQUAL(0, consumer.runConsumerMonitoring(monitoring)); BOOST_CHECK_EQUAL(0, monitoring.size()); } BOOST_FIXTURE_TEST_CASE (simpleLog, MsgBusFixture) { Producer producer(TEST_PATH); Consumer consumer(TEST_PATH); MessageLog original; original.set_job_id("1906cc40-b915-11e5-9a03-02163e006dd0"); original.set_file_id(44); original.set_host("abc.cern.ch"); original.set_log_path("/var/log/fts3/transfers/log.log"); original.set_has_debug_file(true); original.set_timestamp(time(NULL)); BOOST_CHECK_EQUAL(0, producer.runProducerLog(original)); // Make sure the messages don't get messed up expectZeroMessages<std::vector<Message>>(&Consumer::runConsumerStatus, consumer); expectZeroMessages<std::vector<MessageBringonline>>(&Consumer::runConsumerDeletions, consumer); expectZeroMessages<std::vector<MessageBringonline>>(&Consumer::runConsumerStaging, consumer); expectZeroMessages<std::vector<std::string>>(&Consumer::runConsumerMonitoring, consumer); expectZeroMessages<std::vector<MessageUpdater>>(&Consumer::runConsumerStall, consumer); // First attempt must return the single message std::map<int, MessageLog> logs; BOOST_CHECK_EQUAL(0, consumer.runConsumerLog(logs)); BOOST_CHECK_EQUAL(1, logs.size()); BOOST_CHECK_NO_THROW(logs.at(original.file_id())); BOOST_CHECK_EQUAL(logs.at(original.file_id()), original); // Second attempt must return empty (already consumed) logs.clear(); BOOST_CHECK_EQUAL(0, consumer.runConsumerLog(logs)); BOOST_CHECK_EQUAL(0, logs.size()); } BOOST_FIXTURE_TEST_CASE (simpleDeletion, MsgBusFixture) { Producer producer(TEST_PATH); Consumer consumer(TEST_PATH); MessageBringonline original; original.set_job_id("1906cc40-b915-11e5-9a03-02163e006dd0"); original.set_file_id(44); original.set_transfer_status("FAILED"); original.set_transfer_message("Could not open because of reasons"); BOOST_CHECK_EQUAL(0, producer.runProducerDeletions(original)); // Make sure the messages don't get messed up expectZeroMessages<std::vector<Message>>(&Consumer::runConsumerStatus, consumer); expectZeroMessages<std::vector<MessageBringonline>>(&Consumer::runConsumerStaging, consumer); expectZeroMessages<std::map<int, MessageLog>>(&Consumer::runConsumerLog, consumer); expectZeroMessages<std::vector<std::string>>(&Consumer::runConsumerMonitoring, consumer); expectZeroMessages<std::vector<MessageUpdater>>(&Consumer::runConsumerStall, consumer); // First attempt must return the single message std::vector<MessageBringonline> statuses; BOOST_CHECK_EQUAL(0, consumer.runConsumerDeletions(statuses)); BOOST_CHECK_EQUAL(1, statuses.size()); BOOST_CHECK_EQUAL(statuses[0], original); // Second attempt must return empty (already consumed) statuses.clear(); BOOST_CHECK_EQUAL(0, consumer.runConsumerDeletions(statuses)); BOOST_CHECK_EQUAL(0, statuses.size()); } BOOST_FIXTURE_TEST_CASE (simpleStaging, MsgBusFixture) { Producer producer(TEST_PATH); Consumer consumer(TEST_PATH); MessageBringonline original; original.set_job_id("1906cc40-b915-11e5-9a03-02163e006dd0"); original.set_file_id(44); original.set_transfer_status("FAILED"); original.set_transfer_message("Could not open because of reasons"); BOOST_CHECK_EQUAL(0, producer.runProducerStaging(original)); // Make sure the messages don't get messed up expectZeroMessages<std::vector<Message>>(&Consumer::runConsumerStatus, consumer); expectZeroMessages<std::vector<MessageBringonline>>(&Consumer::runConsumerDeletions, consumer); expectZeroMessages<std::map<int, MessageLog>>(&Consumer::runConsumerLog, consumer); expectZeroMessages<std::vector<std::string>>(&Consumer::runConsumerMonitoring, consumer); expectZeroMessages<std::vector<MessageUpdater>>(&Consumer::runConsumerStall, consumer); // First attempt must return the single message std::vector<MessageBringonline> statuses; BOOST_CHECK_EQUAL(0, consumer.runConsumerStaging(statuses)); BOOST_CHECK_EQUAL(1, statuses.size()); BOOST_CHECK_EQUAL(statuses[0], original); // Second attempt must return empty (already consumed) statuses.clear(); BOOST_CHECK_EQUAL(0, consumer.runConsumerStaging(statuses)); BOOST_CHECK_EQUAL(0, statuses.size()); } BOOST_AUTO_TEST_SUITE_END()
35.824219
105
0.74463
cern-fts
c0261a7fc43991509d789e99d7efe01691644fe1
517
hpp
C++
include/mass.hpp
zyuchuan/krypton
449f39563ccc79659e61af954bd550c89c33d35e
[ "MIT" ]
null
null
null
include/mass.hpp
zyuchuan/krypton
449f39563ccc79659e61af954bd550c89c33d35e
[ "MIT" ]
null
null
null
include/mass.hpp
zyuchuan/krypton
449f39563ccc79659e61af954bd550c89c33d35e
[ "MIT" ]
null
null
null
// // mass.hpp // krypton // // Created by Jack Zou on 2018/4/7. // Copyright © 2018年 jack.zou. All rights reserved. // #ifndef mass_h #define mass_h #include "core/common.hpp" #include "core/quantity.hpp" BEGIN_KR_NAMESPACE template<class T> using microgram = quantity<T, mass, std::micro>; template<class T> using gram = quantity<T, mass>; template<class T> using kilogram = quantity<T, mass, std::kilo>; template<class T> using ton = quantity<T, mass, std::mega>; END_KR_NAMESPACE #endif /* mass_h */
20.68
66
0.698259
zyuchuan
c0267365170fc4d17d96fe32f56d947acd899bd4
1,760
cpp
C++
PS_Fgen_FW/UI_Lib/Controls/ButtonControl.cpp
M1S2/PowerSupplySigGen
f2d352d9c24db985327d0286db58c6938da2507e
[ "MIT" ]
null
null
null
PS_Fgen_FW/UI_Lib/Controls/ButtonControl.cpp
M1S2/PowerSupplySigGen
f2d352d9c24db985327d0286db58c6938da2507e
[ "MIT" ]
24
2020-11-10T13:03:05.000Z
2021-05-12T16:26:02.000Z
PS_Fgen_FW/UI_Lib/Controls/ButtonControl.cpp
M1S2/PowerSupplySigGen
f2d352d9c24db985327d0286db58c6938da2507e
[ "MIT" ]
1
2021-06-25T12:26:36.000Z
2021-06-25T12:26:36.000Z
/* * ButtonControl.cpp * Created: 31.03.2021 20:42:49 * Author: Markus Scheich */ #include "ButtonControl.h" #include <string.h> template <int StringLength> ButtonControl<StringLength>::ButtonControl(unsigned char locX, unsigned char locY, unsigned char width, unsigned char height, const char* buttonText, void* controlContext, void(*onClick)(void* controlContext)) : UIElement(locX, locY, UI_CONTROL) { Width = width; Height = height; strncpy(_buttonText, buttonText, StringLength); // Copy a maximum number of StringLength characters to the _buttonText buffer. If text is shorter, the array is zero padded. _buttonText[StringLength - 1] = '\0'; // The _buttonText buffer must contain at least one termination character ('\0') at the end to protect from overflow. _controlContext = controlContext; _onClick = onClick; } template <int StringLength> void ButtonControl<StringLength>::Draw(u8g_t *u8g, bool isFirstPage) { if (Visible) { u8g_DrawHLine(u8g, LocX - 1, LocY - 1, 3); // Upper left corner u8g_DrawVLine(u8g, LocX - 1, LocY - 1, 3); u8g_DrawHLine(u8g, LocX + Width - 2, LocY - 1, 3); // Upper right corner u8g_DrawVLine(u8g, LocX + Width, LocY - 1, 3); u8g_DrawHLine(u8g, LocX - 1, LocY + Height, 3); // Lower left corner u8g_DrawVLine(u8g, LocX - 1, LocY + Height - 2, 3); u8g_DrawHLine(u8g, LocX + Width - 2, LocY + Height, 3); // Lower right corner u8g_DrawVLine(u8g, LocX + Width, LocY + Height - 2, 3); u8g_DrawStr(u8g, LocX, LocY, _buttonText); } } template <int StringLength> bool ButtonControl<StringLength>::KeyInput(Keys_t key) { switch (key) { case KEYOK: if (_onClick != NULL) { _onClick(_controlContext); return true; } else { return false; } default: return false; } }
35.918367
245
0.703977
M1S2
c0275aae9762ddcea5c5f53a50e3424e49683159
15,815
cpp
C++
src/debug-util.cpp
mikehearn/avian
86648ea05423bce66d5757c65a213956ad6cd546
[ "0BSD" ]
1
2015-04-25T23:32:56.000Z
2015-04-25T23:32:56.000Z
src/debug-util.cpp
technosaurus/avian
60df08d023faba6e03186167051b3c5c22562dbe
[ "0BSD" ]
null
null
null
src/debug-util.cpp
technosaurus/avian
60df08d023faba6e03186167051b3c5c22562dbe
[ "0BSD" ]
null
null
null
/* Copyright (c) 2008-2013, Avian Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. There is NO WARRANTY for this software. See license.txt for details. */ #include <avian/machine.h> #include "debug-util.h" namespace avian { namespace jvm { namespace debug { uint16_t read16(uint8_t* code, unsigned& ip) { uint16_t a = code[ip++]; uint16_t b = code[ip++]; return (a << 8) | b; } uint32_t read32(uint8_t* code, unsigned& ip) { uint32_t b = code[ip++]; uint32_t a = code[ip++]; uint32_t c = code[ip++]; uint32_t d = code[ip++]; return (a << 24) | (b << 16) | (c << 8) | d; } using namespace vm; int printInstruction(uint8_t* code, unsigned& ip, const char* prefix) { unsigned startIp = ip; uint8_t instr = code[ip++]; switch (instr) { case aaload: return fprintf(stderr, "aaload"); case aastore: return fprintf(stderr, "aastore"); case aconst_null: return fprintf(stderr, "aconst_null"); case aload: return fprintf(stderr, "aload %2d", code[ip++]); case aload_0: return fprintf(stderr, "aload_0"); case aload_1: return fprintf(stderr, "aload_1"); case aload_2: return fprintf(stderr, "aload_2"); case aload_3: return fprintf(stderr, "aload_3"); case anewarray: return fprintf(stderr, "anewarray %4d", read16(code, ip)); case areturn: return fprintf(stderr, "areturn"); case arraylength: return fprintf(stderr, "arraylength"); case astore: return fprintf(stderr, "astore %2d", code[ip++]); case astore_0: return fprintf(stderr, "astore_0"); case astore_1: return fprintf(stderr, "astore_1"); case astore_2: return fprintf(stderr, "astore_2"); case astore_3: return fprintf(stderr, "astore_3"); case athrow: return fprintf(stderr, "athrow"); case baload: return fprintf(stderr, "baload"); case bastore: return fprintf(stderr, "bastore"); case bipush: return fprintf(stderr, "bipush %2d", code[ip++]); case caload: return fprintf(stderr, "caload"); case castore: return fprintf(stderr, "castore"); case checkcast: return fprintf(stderr, "checkcast %4d", read16(code, ip)); case d2f: return fprintf(stderr, "d2f"); case d2i: return fprintf(stderr, "d2i"); case d2l: return fprintf(stderr, "d2l"); case dadd: return fprintf(stderr, "dadd"); case daload: return fprintf(stderr, "daload"); case dastore: return fprintf(stderr, "dastore"); case dcmpg: return fprintf(stderr, "dcmpg"); case dcmpl: return fprintf(stderr, "dcmpl"); case dconst_0: return fprintf(stderr, "dconst_0"); case dconst_1: return fprintf(stderr, "dconst_1"); case ddiv: return fprintf(stderr, "ddiv"); case dmul: return fprintf(stderr, "dmul"); case dneg: return fprintf(stderr, "dneg"); case vm::drem: return fprintf(stderr, "drem"); case dsub: return fprintf(stderr, "dsub"); case dup: return fprintf(stderr, "dup"); case dup_x1: return fprintf(stderr, "dup_x1"); case dup_x2: return fprintf(stderr, "dup_x2"); case dup2: return fprintf(stderr, "dup2"); case dup2_x1: return fprintf(stderr, "dup2_x1"); case dup2_x2: return fprintf(stderr, "dup2_x2"); case f2d: return fprintf(stderr, "f2d"); case f2i: return fprintf(stderr, "f2i"); case f2l: return fprintf(stderr, "f2l"); case fadd: return fprintf(stderr, "fadd"); case faload: return fprintf(stderr, "faload"); case fastore: return fprintf(stderr, "fastore"); case fcmpg: return fprintf(stderr, "fcmpg"); case fcmpl: return fprintf(stderr, "fcmpl"); case fconst_0: return fprintf(stderr, "fconst_0"); case fconst_1: return fprintf(stderr, "fconst_1"); case fconst_2: return fprintf(stderr, "fconst_2"); case fdiv: return fprintf(stderr, "fdiv"); case fmul: return fprintf(stderr, "fmul"); case fneg: return fprintf(stderr, "fneg"); case frem: return fprintf(stderr, "frem"); case fsub: return fprintf(stderr, "fsub"); case getfield: return fprintf(stderr, "getfield %4d", read16(code, ip)); case getstatic: return fprintf(stderr, "getstatic %4d", read16(code, ip)); case goto_: { int16_t offset = read16(code, ip); return fprintf(stderr, "goto %4d", offset + ip - 3); } case goto_w: { int32_t offset = read32(code, ip); return fprintf(stderr, "goto_w %08x", offset + ip - 5); } case i2b: return fprintf(stderr, "i2b"); case i2c: return fprintf(stderr, "i2c"); case i2d: return fprintf(stderr, "i2d"); case i2f: return fprintf(stderr, "i2f"); case i2l: return fprintf(stderr, "i2l"); case i2s: return fprintf(stderr, "i2s"); case iadd: return fprintf(stderr, "iadd"); case iaload: return fprintf(stderr, "iaload"); case iand: return fprintf(stderr, "iand"); case iastore: return fprintf(stderr, "iastore"); case iconst_m1: return fprintf(stderr, "iconst_m1"); case iconst_0: return fprintf(stderr, "iconst_0"); case iconst_1: return fprintf(stderr, "iconst_1"); case iconst_2: return fprintf(stderr, "iconst_2"); case iconst_3: return fprintf(stderr, "iconst_3"); case iconst_4: return fprintf(stderr, "iconst_4"); case iconst_5: return fprintf(stderr, "iconst_5"); case idiv: return fprintf(stderr, "idiv"); case if_acmpeq: { int16_t offset = read16(code, ip); return fprintf(stderr, "if_acmpeq %4d", offset + ip - 3); } case if_acmpne: { int16_t offset = read16(code, ip); return fprintf(stderr, "if_acmpne %4d", offset + ip - 3); } case if_icmpeq: { int16_t offset = read16(code, ip); return fprintf(stderr, "if_icmpeq %4d", offset + ip - 3); } case if_icmpne: { int16_t offset = read16(code, ip); return fprintf(stderr, "if_icmpne %4d", offset + ip - 3); } case if_icmpgt: { int16_t offset = read16(code, ip); return fprintf(stderr, "if_icmpgt %4d", offset + ip - 3); } case if_icmpge: { int16_t offset = read16(code, ip); return fprintf(stderr, "if_icmpge %4d", offset + ip - 3); } case if_icmplt: { int16_t offset = read16(code, ip); return fprintf(stderr, "if_icmplt %4d", offset + ip - 3); } case if_icmple: { int16_t offset = read16(code, ip); return fprintf(stderr, "if_icmple %4d", offset + ip - 3); } case ifeq: { int16_t offset = read16(code, ip); return fprintf(stderr, "ifeq %4d", offset + ip - 3); } case ifne: { int16_t offset = read16(code, ip); return fprintf(stderr, "ifne %4d", offset + ip - 3); } case ifgt: { int16_t offset = read16(code, ip); return fprintf(stderr, "ifgt %4d", offset + ip - 3); } case ifge: { int16_t offset = read16(code, ip); return fprintf(stderr, "ifge %4d", offset + ip - 3); } case iflt: { int16_t offset = read16(code, ip); return fprintf(stderr, "iflt %4d", offset + ip - 3); } case ifle: { int16_t offset = read16(code, ip); return fprintf(stderr, "ifle %4d", offset + ip - 3); } case ifnonnull: { int16_t offset = read16(code, ip); return fprintf(stderr, "ifnonnull %4d", offset + ip - 3); } case ifnull: { int16_t offset = read16(code, ip); return fprintf(stderr, "ifnull %4d", offset + ip - 3); } case iinc: { uint8_t a = code[ip++]; uint8_t b = code[ip++]; return fprintf(stderr, "iinc %2d %2d", a, b); } case iload: return fprintf(stderr, "iload %2d", code[ip++]); case fload: return fprintf(stderr, "fload %2d", code[ip++]); case iload_0: return fprintf(stderr, "iload_0"); case fload_0: return fprintf(stderr, "fload_0"); case iload_1: return fprintf(stderr, "iload_1"); case fload_1: return fprintf(stderr, "fload_1"); case iload_2: return fprintf(stderr, "iload_2"); case fload_2: return fprintf(stderr, "fload_2"); case iload_3: return fprintf(stderr, "iload_3"); case fload_3: return fprintf(stderr, "fload_3"); case imul: return fprintf(stderr, "imul"); case ineg: return fprintf(stderr, "ineg"); case instanceof: return fprintf(stderr, "instanceof %4d", read16(code, ip)); case invokeinterface: return fprintf(stderr, "invokeinterface %4d", read16(code, ip)); case invokespecial: return fprintf(stderr, "invokespecial %4d", read16(code, ip)); case invokestatic: return fprintf(stderr, "invokestatic %4d", read16(code, ip)); case invokevirtual: return fprintf(stderr, "invokevirtual %4d", read16(code, ip)); case ior: return fprintf(stderr, "ior"); case irem: return fprintf(stderr, "irem"); case ireturn: return fprintf(stderr, "ireturn"); case freturn: return fprintf(stderr, "freturn"); case ishl: return fprintf(stderr, "ishl"); case ishr: return fprintf(stderr, "ishr"); case istore: return fprintf(stderr, "istore %2d", code[ip++]); case fstore: return fprintf(stderr, "fstore %2d", code[ip++]); case istore_0: return fprintf(stderr, "istore_0"); case fstore_0: return fprintf(stderr, "fstore_0"); case istore_1: return fprintf(stderr, "istore_1"); case fstore_1: return fprintf(stderr, "fstore_1"); case istore_2: return fprintf(stderr, "istore_2"); case fstore_2: return fprintf(stderr, "fstore_2"); case istore_3: return fprintf(stderr, "istore_3"); case fstore_3: return fprintf(stderr, "fstore_3"); case isub: return fprintf(stderr, "isub"); case iushr: return fprintf(stderr, "iushr"); case ixor: return fprintf(stderr, "ixor"); case jsr: return fprintf(stderr, "jsr %4d", read16(code, ip) + startIp); case jsr_w: return fprintf(stderr, "jsr_w %08x", read32(code, ip) + startIp); case l2d: return fprintf(stderr, "l2d"); case l2f: return fprintf(stderr, "l2f"); case l2i: return fprintf(stderr, "l2i"); case ladd: return fprintf(stderr, "ladd"); case laload: return fprintf(stderr, "laload"); case land: return fprintf(stderr, "land"); case lastore: return fprintf(stderr, "lastore"); case lcmp: return fprintf(stderr, "lcmp"); case lconst_0: return fprintf(stderr, "lconst_0"); case lconst_1: return fprintf(stderr, "lconst_1"); case ldc: return fprintf(stderr, "ldc %4d", read16(code, ip)); case ldc_w: return fprintf(stderr, "ldc_w %08x", read32(code, ip)); case ldc2_w: return fprintf(stderr, "ldc2_w %4d", read16(code, ip)); case ldiv_: return fprintf(stderr, "ldiv_"); case lload: return fprintf(stderr, "lload %2d", code[ip++]); case dload: return fprintf(stderr, "dload %2d", code[ip++]); case lload_0: return fprintf(stderr, "lload_0"); case dload_0: return fprintf(stderr, "dload_0"); case lload_1: return fprintf(stderr, "lload_1"); case dload_1: return fprintf(stderr, "dload_1"); case lload_2: return fprintf(stderr, "lload_2"); case dload_2: return fprintf(stderr, "dload_2"); case lload_3: return fprintf(stderr, "lload_3"); case dload_3: return fprintf(stderr, "dload_3"); case lmul: return fprintf(stderr, "lmul"); case lneg: return fprintf(stderr, "lneg"); case lookupswitch: { while (ip & 0x3) { ip++; } int32_t default_ = read32(code, ip) + startIp; int32_t pairCount = read32(code, ip); fprintf( stderr, "lookupswitch default: %d pairCount: %d", default_, pairCount); for (int i = 0; i < pairCount; i++) { int32_t k = read32(code, ip); int32_t d = read32(code, ip) + startIp; fprintf(stderr, "\n%s key: %2d dest: %d", prefix, k, d); } fprintf(stderr, "\n"); fflush(stderr); return 0; } case lor: return fprintf(stderr, "lor"); case lrem: return fprintf(stderr, "lrem"); case lreturn: return fprintf(stderr, "lreturn"); case dreturn: return fprintf(stderr, "dreturn"); case lshl: return fprintf(stderr, "lshl"); case lshr: return fprintf(stderr, "lshr"); case lstore: return fprintf(stderr, "lstore %2d", code[ip++]); case dstore: return fprintf(stderr, "dstore %2d", code[ip++]); case lstore_0: return fprintf(stderr, "lstore_0"); case dstore_0: return fprintf(stderr, "dstore_0"); case lstore_1: return fprintf(stderr, "lstore_1"); case dstore_1: return fprintf(stderr, "dstore_1"); case lstore_2: return fprintf(stderr, "lstore_2"); case dstore_2: return fprintf(stderr, "dstore_2"); case lstore_3: return fprintf(stderr, "lstore_3"); case dstore_3: return fprintf(stderr, "dstore_3"); case lsub: return fprintf(stderr, "lsub"); case lushr: return fprintf(stderr, "lushr"); case lxor: return fprintf(stderr, "lxor"); case monitorenter: return fprintf(stderr, "monitorenter"); case monitorexit: return fprintf(stderr, "monitorexit"); case multianewarray: { unsigned type = read16(code, ip); return fprintf(stderr, "multianewarray %4d %2d", type, code[ip++]); } case new_: return fprintf(stderr, "new %4d", read16(code, ip)); case newarray: return fprintf(stderr, "newarray %2d", code[ip++]); case nop: return fprintf(stderr, "nop"); case pop_: return fprintf(stderr, "pop"); case pop2: return fprintf(stderr, "pop2"); case putfield: return fprintf(stderr, "putfield %4d", read16(code, ip)); case putstatic: return fprintf(stderr, "putstatic %4d", read16(code, ip)); case ret: return fprintf(stderr, "ret %2d", code[ip++]); case return_: return fprintf(stderr, "return_"); case saload: return fprintf(stderr, "saload"); case sastore: return fprintf(stderr, "sastore"); case sipush: return fprintf(stderr, "sipush %4d", read16(code, ip)); case swap: return fprintf(stderr, "swap"); case tableswitch: { while (ip & 0x3) { ip++; } int32_t default_ = read32(code, ip) + startIp; int32_t bottom = read32(code, ip); int32_t top = read32(code, ip); fprintf(stderr, "tableswitch default: %d bottom: %d top: %d", default_, bottom, top); for (int i = 0; i < top - bottom + 1; i++) { int32_t d = read32(code, ip) + startIp; fprintf(stderr, "%s key: %d dest: %d", prefix, i + bottom, d); } return 0; } case wide: { switch (code[ip++]) { case aload: return fprintf(stderr, "wide aload %4d", read16(code, ip)); case astore: return fprintf(stderr, "wide astore %4d", read16(code, ip)); case iinc: fprintf(stderr, "wide iinc %4d %4d", read16(code, ip), read16(code, ip)); case iload: return fprintf(stderr, "wide iload %4d", read16(code, ip)); case istore: return fprintf(stderr, "wide istore %4d", read16(code, ip)); case lload: return fprintf(stderr, "wide lload %4d", read16(code, ip)); case lstore: return fprintf(stderr, "wide lstore %4d", read16(code, ip)); case ret: return fprintf(stderr, "wide ret %4d", read16(code, ip)); default: { fprintf( stderr, "unknown wide instruction %2d %4d", instr, read16(code, ip)); } } } default: { return fprintf(stderr, "unknown instruction %2d", instr); } } return ip; } void disassembleCode(const char* prefix, uint8_t* code, unsigned length) { unsigned ip = 0; while (ip < length) { fprintf(stderr, "%s%x:\t", prefix, ip); printInstruction(code, ip, prefix); fprintf(stderr, "\n"); } } } // namespace debug } // namespace jvm } // namespace avian
25.799347
79
0.634524
mikehearn
c028559bc828d4df55d75e29a9dfad6a52963b40
9,866
cc
C++
test/common/grpc/codec_test.cc
dcillera/envoy
cb54ba8eec26f768f8c1ae412113b07bacde7321
[ "Apache-2.0" ]
17,703
2017-09-14T18:23:43.000Z
2022-03-31T22:04:17.000Z
test/common/grpc/codec_test.cc
dcillera/envoy
cb54ba8eec26f768f8c1ae412113b07bacde7321
[ "Apache-2.0" ]
15,957
2017-09-14T16:38:22.000Z
2022-03-31T23:56:30.000Z
test/common/grpc/codec_test.cc
dcillera/envoy
cb54ba8eec26f768f8c1ae412113b07bacde7321
[ "Apache-2.0" ]
3,780
2017-09-14T18:58:47.000Z
2022-03-31T17:10:47.000Z
#include <array> #include <cstdint> #include <string> #include <vector> #include "source/common/buffer/buffer_impl.h" #include "source/common/grpc/codec.h" #include "test/common/buffer/utility.h" #include "test/proto/helloworld.pb.h" #include "test/test_common/printers.h" #include "gtest/gtest.h" namespace Envoy { namespace Grpc { namespace { TEST(GrpcCodecTest, encodeHeader) { Encoder encoder; std::array<uint8_t, 5> buffer; encoder.newFrame(GRPC_FH_DEFAULT, 1, buffer); EXPECT_EQ(buffer[0], GRPC_FH_DEFAULT); EXPECT_EQ(buffer[1], 0); EXPECT_EQ(buffer[2], 0); EXPECT_EQ(buffer[3], 0); EXPECT_EQ(buffer[4], 1); encoder.newFrame(GRPC_FH_COMPRESSED, 1, buffer); EXPECT_EQ(buffer[0], GRPC_FH_COMPRESSED); EXPECT_EQ(buffer[1], 0); EXPECT_EQ(buffer[2], 0); EXPECT_EQ(buffer[3], 0); EXPECT_EQ(buffer[4], 1); encoder.newFrame(GRPC_FH_DEFAULT, 0x100, buffer); EXPECT_EQ(buffer[0], GRPC_FH_DEFAULT); EXPECT_EQ(buffer[1], 0); EXPECT_EQ(buffer[2], 0); EXPECT_EQ(buffer[3], 1); EXPECT_EQ(buffer[4], 0); encoder.newFrame(GRPC_FH_DEFAULT, 0x10000, buffer); EXPECT_EQ(buffer[0], GRPC_FH_DEFAULT); EXPECT_EQ(buffer[1], 0); EXPECT_EQ(buffer[2], 1); EXPECT_EQ(buffer[3], 0); EXPECT_EQ(buffer[4], 0); encoder.newFrame(GRPC_FH_DEFAULT, 0x1000000, buffer); EXPECT_EQ(buffer[0], GRPC_FH_DEFAULT); EXPECT_EQ(buffer[1], 1); EXPECT_EQ(buffer[2], 0); EXPECT_EQ(buffer[3], 0); EXPECT_EQ(buffer[4], 0); } TEST(GrpcCodecTest, decodeIncompleteFrame) { helloworld::HelloRequest request; request.set_name("hello"); std::string request_buffer = request.SerializeAsString(); Buffer::OwnedImpl buffer; std::array<uint8_t, 5> header; Encoder encoder; encoder.newFrame(GRPC_FH_DEFAULT, request.ByteSize(), header); buffer.add(header.data(), 5); buffer.add(request_buffer.c_str(), 5); std::vector<Frame> frames; Decoder decoder; EXPECT_TRUE(decoder.decode(buffer, frames)); EXPECT_EQ(static_cast<size_t>(0), buffer.length()); EXPECT_EQ(static_cast<size_t>(0), frames.size()); EXPECT_EQ(static_cast<uint32_t>(request.ByteSize()), decoder.length()); EXPECT_EQ(true, decoder.hasBufferedData()); buffer.add(request_buffer.c_str() + 5); EXPECT_TRUE(decoder.decode(buffer, frames)); EXPECT_EQ(static_cast<size_t>(0), buffer.length()); EXPECT_EQ(static_cast<size_t>(1), frames.size()); EXPECT_EQ(static_cast<uint32_t>(0), decoder.length()); EXPECT_EQ(false, decoder.hasBufferedData()); helloworld::HelloRequest decoded_request; EXPECT_TRUE(decoded_request.ParseFromArray(frames[0].data_->linearize(frames[0].data_->length()), frames[0].data_->length())); EXPECT_EQ("hello", decoded_request.name()); } TEST(GrpcCodecTest, decodeInvalidFrame) { helloworld::HelloRequest request; request.set_name("hello"); Buffer::OwnedImpl buffer; std::array<uint8_t, 5> header; Encoder encoder; encoder.newFrame(0b10u, request.ByteSize(), header); buffer.add(header.data(), 5); buffer.add(request.SerializeAsString()); size_t size = buffer.length(); std::vector<Frame> frames; Decoder decoder; EXPECT_FALSE(decoder.decode(buffer, frames)); EXPECT_EQ(size, buffer.length()); } // This test shows that null bytes in the bytestring successfully decode into a frame with length 0. // Should this test really pass? TEST(GrpcCodecTest, DecodeMultipleFramesInvalid) { // A frame constructed from null bytes followed by an invalid frame const std::string data("\000\000\000\000\0000000", 9); Buffer::OwnedImpl buffer(data.data(), data.size()); size_t size = buffer.length(); std::vector<Frame> frames; Decoder decoder; EXPECT_FALSE(decoder.decode(buffer, frames)); // When the decoder doesn't successfully decode, it puts decoded frames up until // an invalid frame into output frame vector. EXPECT_EQ(1, frames.size()); // Buffer does not get drained due to it returning false. EXPECT_EQ(size, buffer.length()); // Only part of the buffer represented a frame. Thus, the frame length should not equal the buffer // length. The frame put into the output vector has no length. EXPECT_EQ(0, frames[0].length_); } // If there is a valid frame followed by an invalid frame, the decoder will successfully put the // valid frame in the output and return false due to the invalid frame TEST(GrpcCodecTest, DecodeValidFrameWithInvalidFrameAfterward) { // Decode a valid encoded structured request plus invalid data afterward helloworld::HelloRequest request; request.set_name("hello"); Buffer::OwnedImpl buffer; std::array<uint8_t, 5> header; Encoder encoder; encoder.newFrame(GRPC_FH_DEFAULT, request.ByteSize(), header); buffer.add(header.data(), 5); buffer.add(request.SerializeAsString()); buffer.add("000000", 6); size_t size = buffer.length(); std::vector<Frame> frames; Decoder decoder; EXPECT_FALSE(decoder.decode(buffer, frames)); // When the decoder doesn't successfully decode, it puts valid frames up until // an invalid frame into output frame vector. EXPECT_EQ(1, frames.size()); // Buffer does not get drained due to it returning false. EXPECT_EQ(size, buffer.length()); // Only part of the buffer represented a valid frame. Thus, the frame length should not equal the // buffer length. EXPECT_NE(size, frames[0].length_); } TEST(GrpcCodecTest, decodeEmptyFrame) { Buffer::OwnedImpl buffer("\0\0\0\0", 5); Decoder decoder; std::vector<Frame> frames; EXPECT_TRUE(decoder.decode(buffer, frames)); EXPECT_EQ(1, frames.size()); EXPECT_EQ(0, frames[0].length_); } TEST(GrpcCodecTest, decodeSingleFrame) { helloworld::HelloRequest request; request.set_name("hello"); Buffer::OwnedImpl buffer; std::array<uint8_t, 5> header; Encoder encoder; encoder.newFrame(GRPC_FH_DEFAULT, request.ByteSize(), header); buffer.add(header.data(), 5); buffer.add(request.SerializeAsString()); std::vector<Frame> frames; Decoder decoder; EXPECT_TRUE(decoder.decode(buffer, frames)); EXPECT_EQ(static_cast<size_t>(0), buffer.length()); EXPECT_EQ(frames.size(), static_cast<uint64_t>(1)); EXPECT_EQ(GRPC_FH_DEFAULT, frames[0].flags_); EXPECT_EQ(static_cast<uint64_t>(request.ByteSize()), frames[0].length_); helloworld::HelloRequest result; result.ParseFromArray(frames[0].data_->linearize(frames[0].data_->length()), frames[0].data_->length()); EXPECT_EQ("hello", result.name()); } TEST(GrpcCodecTest, decodeMultipleFrame) { helloworld::HelloRequest request; request.set_name("hello"); Buffer::OwnedImpl buffer; std::array<uint8_t, 5> header; Encoder encoder; encoder.newFrame(GRPC_FH_DEFAULT, request.ByteSize(), header); for (int i = 0; i < 1009; i++) { buffer.add(header.data(), 5); buffer.add(request.SerializeAsString()); } std::vector<Frame> frames; Decoder decoder; EXPECT_TRUE(decoder.decode(buffer, frames)); EXPECT_EQ(static_cast<size_t>(0), buffer.length()); EXPECT_EQ(frames.size(), static_cast<uint64_t>(1009)); for (Frame& frame : frames) { EXPECT_EQ(GRPC_FH_DEFAULT, frame.flags_); EXPECT_EQ(static_cast<uint64_t>(request.ByteSize()), frame.length_); helloworld::HelloRequest result; result.ParseFromArray(frame.data_->linearize(frame.data_->length()), frame.data_->length()); EXPECT_EQ("hello", result.name()); } } TEST(GrpcCodecTest, FrameInspectorTest) { { Buffer::OwnedImpl buffer; FrameInspector counter; EXPECT_EQ(0, counter.inspect(buffer)); EXPECT_EQ(counter.state(), State::FhFlag); EXPECT_EQ(counter.frameCount(), 0); } { Buffer::OwnedImpl buffer; FrameInspector counter; Buffer::addSeq(buffer, {0}); EXPECT_EQ(1, counter.inspect(buffer)); EXPECT_EQ(counter.state(), State::FhLen0); EXPECT_EQ(counter.frameCount(), 1); } { Buffer::OwnedImpl buffer; FrameInspector counter; Buffer::addSeq(buffer, {1, 0, 0, 0, 1, 0xFF}); EXPECT_EQ(1, counter.inspect(buffer)); EXPECT_EQ(counter.state(), State::FhFlag); EXPECT_EQ(counter.frameCount(), 1); } { FrameInspector counter; Buffer::OwnedImpl buffer1; Buffer::addSeq(buffer1, {1, 0, 0, 0}); EXPECT_EQ(1, counter.inspect(buffer1)); EXPECT_EQ(counter.state(), State::FhLen3); EXPECT_EQ(counter.frameCount(), 1); Buffer::OwnedImpl buffer2; Buffer::addSeq(buffer2, {1, 0xFF}); EXPECT_EQ(0, counter.inspect(buffer2)); EXPECT_EQ(counter.frameCount(), 1); } { Buffer::OwnedImpl buffer; FrameInspector counter; Buffer::addSeq(buffer, {1, 0, 0, 0, 1, 0xFF}); Buffer::addSeq(buffer, {0, 0, 0, 0, 2, 0xFF, 0xFF}); EXPECT_EQ(2, counter.inspect(buffer)); EXPECT_EQ(counter.state(), State::FhFlag); EXPECT_EQ(counter.frameCount(), 2); } { Buffer::OwnedImpl buffer1; Buffer::OwnedImpl buffer2; FrameInspector counter; // message spans two buffers Buffer::addSeq(buffer1, {1, 0, 0, 0, 2, 0xFF}); Buffer::addSeq(buffer2, {0xFF, 0, 0, 0, 0, 2, 0xFF, 0xFF}); EXPECT_EQ(1, counter.inspect(buffer1)); EXPECT_EQ(1, counter.inspect(buffer2)); EXPECT_EQ(counter.state(), State::FhFlag); EXPECT_EQ(counter.frameCount(), 2); } { Buffer::OwnedImpl buffer; FrameInspector counter; // Add longer byte sequence Buffer::addSeq(buffer, {1, 0, 0, 1, 0}); Buffer::addRepeated(buffer, 1 << 8, 0xFF); // Start second message Buffer::addSeq(buffer, {0}); EXPECT_EQ(2, counter.inspect(buffer)); EXPECT_EQ(counter.state(), State::FhLen0); EXPECT_EQ(counter.frameCount(), 2); } { // two empty messages Buffer::OwnedImpl buffer; FrameInspector counter; Buffer::addRepeated(buffer, 10, 0); EXPECT_EQ(2, counter.inspect(buffer)); EXPECT_EQ(counter.frameCount(), 2); } } } // namespace } // namespace Grpc } // namespace Envoy
31.520767
100
0.701196
dcillera
c02ba756765a754fbfc21525f6ad0aeece3c8c2c
11,092
cpp
C++
gecode/int/var-imp/int.cpp
SaGagnon/gecode-5.5.0-cbs
e871b320a9b2031423bb0fa452b1a5c09641a041
[ "MIT-feh" ]
null
null
null
gecode/int/var-imp/int.cpp
SaGagnon/gecode-5.5.0-cbs
e871b320a9b2031423bb0fa452b1a5c09641a041
[ "MIT-feh" ]
null
null
null
gecode/int/var-imp/int.cpp
SaGagnon/gecode-5.5.0-cbs
e871b320a9b2031423bb0fa452b1a5c09641a041
[ "MIT-feh" ]
null
null
null
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Christian Schulte <schulte@gecode.org> * * Copyright: * Christian Schulte, 2002 * * Last modified: * $Date: 2017-02-21 06:45:56 +0100 (Tue, 21 Feb 2017) $ by $Author: schulte $ * $Revision: 15465 $ * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * 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 <gecode/int.hh> namespace Gecode { namespace Int { forceinline bool IntVarImp::closer_min(int n) const { unsigned int l = static_cast<unsigned int>(n - dom.min()); unsigned int r = static_cast<unsigned int>(dom.max() - n); return l < r; } int IntVarImp::med(void) const { // Computes the median if (fst() == NULL) return (dom.min()+dom.max())/2 - ((dom.min()+dom.max())%2 < 0 ? 1 : 0); unsigned int i = size() / 2; if (size() % 2 == 0) i--; const RangeList* p = NULL; const RangeList* c = fst(); while (i >= c->width()) { i -= c->width(); const RangeList* n=c->next(p); p=c; c=n; } return c->min() + static_cast<int>(i); } bool IntVarImp::in_full(int m) const { if (closer_min(m)) { const RangeList* p = NULL; const RangeList* c = fst(); while (m > c->max()) { const RangeList* n=c->next(p); p=c; c=n; } return (m >= c->min()); } else { const RangeList* n = NULL; const RangeList* c = lst(); while (m < c->min()) { const RangeList* p=c->prev(n); n=c; c=p; } return (m <= c->max()); } } /* * "Standard" tell operations * */ ModEvent IntVarImp::lq_full(Space& home, int m) { assert((m >= dom.min()) && (m <= dom.max())); IntDelta d(m+1,dom.max()); ModEvent me = ME_INT_BND; if (range()) { // Is already range... dom.max(m); if (assigned()) me = ME_INT_VAL; } else if (m < fst()->next(NULL)->min()) { // Becomes range... dom.max(std::min(m,fst()->max())); fst()->dispose(home,NULL,lst()); fst(NULL); holes = 0; if (assigned()) me = ME_INT_VAL; } else { // Stays non-range... RangeList* n = NULL; RangeList* c = lst(); unsigned int h = 0; while (m < c->min()) { RangeList* p = c->prev(n); c->fix(n); h += (c->min() - p->max() - 1); n=c; c=p; } holes -= h; int max_c = std::min(m,c->max()); dom.max(max_c); c->max(max_c); if (c != lst()) { n->dispose(home,lst()); c->next(n,NULL); lst(c); } } return notify(home,me,d); } ModEvent IntVarImp::gq_full(Space& home, int m) { assert((m >= dom.min()) && (m <= dom.max())); IntDelta d(dom.min(),m-1); ModEvent me = ME_INT_BND; if (range()) { // Is already range... dom.min(m); if (assigned()) me = ME_INT_VAL; } else if (m > lst()->prev(NULL)->max()) { // Becomes range... dom.min(std::max(m,lst()->min())); fst()->dispose(home,NULL,lst()); fst(NULL); holes = 0; if (assigned()) me = ME_INT_VAL; } else { // Stays non-range... RangeList* p = NULL; RangeList* c = fst(); unsigned int h = 0; while (m > c->max()) { RangeList* n = c->next(p); c->fix(n); h += (n->min() - c->max() - 1); p=c; c=n; } holes -= h; int min_c = std::max(m,c->min()); dom.min(min_c); c->min(min_c); if (c != fst()) { fst()->dispose(home,p); c->prev(p,NULL); fst(c); } } return notify(home,me,d); } ModEvent IntVarImp::eq_full(Space& home, int m) { dom.min(m); dom.max(m); if (!range()) { bool failed = false; RangeList* p = NULL; RangeList* c = fst(); while (m > c->max()) { RangeList* n=c->next(p); c->fix(n); p=c; c=n; } if (m < c->min()) failed = true; while (c != NULL) { RangeList* n=c->next(p); c->fix(n); p=c; c=n; } assert(p == lst()); fst()->dispose(home,p); fst(NULL); holes = 0; if (failed) return fail(home); } IntDelta d; return notify(home,ME_INT_VAL,d); } ModEvent IntVarImp::nq_full(Space& home, int m) { assert(!((m < dom.min()) || (m > dom.max()))); ModEvent me = ME_INT_DOM; if (range()) { if ((m == dom.min()) && (m == dom.max())) return fail(home); if (m == dom.min()) { dom.min(m+1); me = assigned() ? ME_INT_VAL : ME_INT_BND; } else if (m == dom.max()) { dom.max(m-1); me = assigned() ? ME_INT_VAL : ME_INT_BND; } else { RangeList* f = new (home) RangeList(dom.min(),m-1); RangeList* l = new (home) RangeList(m+1,dom.max()); f->prevnext(NULL,l); l->prevnext(f,NULL); fst(f); lst(l); holes = 1; } } else if (m < fst()->next(NULL)->min()) { // Concerns the first range... int f_max = fst()->max(); if (m > f_max) return ME_INT_NONE; int f_min = dom.min(); if ((m == f_min) && (m == f_max)) { RangeList* f_next = fst()->next(NULL); dom.min(f_next->min()); if (f_next == lst()) { // Turns into range // Works as at the ends there are only NULL pointers fst()->dispose(home,f_next); fst(NULL); holes = 0; me = assigned() ? ME_INT_VAL : ME_INT_BND; } else { // Remains non-range f_next->prev(fst(),NULL); fst()->dispose(home); fst(f_next); holes -= dom.min() - f_min - 1; me = ME_INT_BND; } } else if (m == f_min) { dom.min(m+1); fst()->min(m+1); me = ME_INT_BND; } else if (m == f_max) { fst()->max(m-1); holes += 1; } else { // Create new hole RangeList* f = new (home) RangeList(f_min,m-1); f->prevnext(NULL,fst()); fst()->min(m+1); fst()->prev(NULL,f); fst(f); holes += 1; } } else if (m > lst()->prev(NULL)->max()) { // Concerns the last range... int l_min = lst()->min(); if (m < l_min) return ME_INT_NONE; int l_max = dom.max(); if ((m == l_min) && (m == l_max)) { RangeList* l_prev = lst()->prev(NULL); dom.max(l_prev->max()); if (l_prev == fst()) { // Turns into range l_prev->dispose(home,lst()); fst(NULL); holes = 0; me = assigned() ? ME_INT_VAL : ME_INT_BND; } else { // Remains non-range l_prev->next(lst(),NULL); lst()->dispose(home); lst(l_prev); holes -= l_max - dom.max() - 1; me = ME_INT_BND; } } else if (m == l_max) { dom.max(m-1); lst()->max(m-1); me = ME_INT_BND; } else if (m == l_min) { lst()->min(m+1); holes += 1; } else { // Create new hole RangeList* l = new (home) RangeList(m+1,l_max); l->prevnext(lst(),NULL); lst()->max(m-1); lst()->next(NULL,l); lst(l); holes += 1; } } else { // Concerns element in the middle of the list of ranges RangeList* p; RangeList* c; RangeList* n; if (closer_min(m)) { assert(m > fst()->max()); p = NULL; c = fst(); do { n=c->next(p); p=c; c=n; } while (m > c->max()); if (m < c->min()) return ME_INT_NONE; n=c->next(p); } else { assert(m < lst()->min()); n = NULL; c = lst(); do { p=c->prev(n); n=c; c=p; } while (m < c->min()); if (m > c->max()) return ME_INT_NONE; p=c->prev(n); } assert((fst() != c) && (lst() != c)); assert((m >= c->min()) && (m <= c->max())); holes += 1; int c_min = c->min(); int c_max = c->max(); if ((c_min == m) && (c_max == m)) { c->dispose(home); p->next(c,n); n->prev(c,p); } else if (c_min == m) { c->min(m+1); } else { c->max(m-1); if (c_max != m) { RangeList* l = new (home) RangeList(m+1,c_max); l->prevnext(c,n); c->next(n,l); n->prev(c,l); } } } IntDelta d(m,m); return notify(home,me,d); } /* * Copying variables * */ forceinline IntVarImp::IntVarImp(Space& home, bool share, IntVarImp& x) : IntVarImpBase(home,share,x), dom(x.dom.min(),x.dom.max()) { holes = x.holes; if (holes) { int m = 1; // Compute length { RangeList* s_p = x.fst(); RangeList* s_c = s_p->next(NULL); do { m++; RangeList* s_n = s_c->next(s_p); s_p=s_c; s_c=s_n; } while (s_c != NULL); } RangeList* d_c = home.alloc<RangeList>(m); fst(d_c); lst(d_c+m-1); d_c->min(x.fst()->min()); d_c->max(x.fst()->max()); d_c->prevnext(NULL,NULL); RangeList* s_p = x.fst(); RangeList* s_c = s_p->next(NULL); do { RangeList* d_n = d_c + 1; d_c->next(NULL,d_n); d_n->prevnext(d_c,NULL); d_n->min(s_c->min()); d_n->max(s_c->max()); d_c = d_n; RangeList* s_n=s_c->next(s_p); s_p=s_c; s_c=s_n; } while (s_c != NULL); d_c->next(NULL,NULL); } else { fst(NULL); } } IntVarImp* IntVarImp::perform_copy(Space& home, bool share) { return new (home) IntVarImp(home,share,*this); } /* * Dependencies * */ void IntVarImp::subscribe(Space& home, Propagator& p, PropCond pc, bool schedule) { IntVarImpBase::subscribe(home,p,pc,dom.min()==dom.max(),schedule); } void IntVarImp::reschedule(Space& home, Propagator& p, PropCond pc) { IntVarImpBase::reschedule(home,p,pc,dom.min()==dom.max()); } void IntVarImp::subscribe(Space& home, Advisor& a, bool fail) { IntVarImpBase::subscribe(home,a,dom.min()==dom.max(),fail); } }} // STATISTICS: int-var
29.036649
82
0.508745
SaGagnon
c031ee5e139bc7dcb84faf06b0eff6bfcbdb76a4
545
cpp
C++
STEM4U/Utility.cpp
Libraries4U/STEM4U
41472ce21420ff5bcf69577efefd924cf1e7c2cf
[ "Apache-2.0" ]
null
null
null
STEM4U/Utility.cpp
Libraries4U/STEM4U
41472ce21420ff5bcf69577efefd924cf1e7c2cf
[ "Apache-2.0" ]
null
null
null
STEM4U/Utility.cpp
Libraries4U/STEM4U
41472ce21420ff5bcf69577efefd924cf1e7c2cf
[ "Apache-2.0" ]
null
null
null
#include <Core/Core.h> #include <Functions4U/Functions4U.h> #include <Eigen/Eigen.h> #include "Utility.h" namespace Upp { using namespace Eigen; double R2(const VectorXd &serie, const VectorXd &serie0, double mean) { if (IsNull(mean)) mean = serie.mean(); double sse = 0, sst = 0; for (Eigen::Index i = 0; i < serie.size(); ++i) { double y = serie(i); double err = y - serie0(i); sse += err*err; double d = y - mean; sst += d*d; } if (sst < 1E-50 || sse > sst) return 0; return 1 - sse/sst; } }
20.185185
72
0.588991
Libraries4U
c0333f3235d1a372eee2aaa2d13fa8058ceccc4e
8,121
cpp
C++
src/autorotate-iio.cpp
kode54/wayfire-plugins-extra
11bbf1c5468138dea47ef162ac65d4a93914306b
[ "MIT" ]
null
null
null
src/autorotate-iio.cpp
kode54/wayfire-plugins-extra
11bbf1c5468138dea47ef162ac65d4a93914306b
[ "MIT" ]
null
null
null
src/autorotate-iio.cpp
kode54/wayfire-plugins-extra
11bbf1c5468138dea47ef162ac65d4a93914306b
[ "MIT" ]
null
null
null
#include <wayfire/plugin.hpp> #include <wayfire/output.hpp> #include <wayfire/render-manager.hpp> #include <wayfire/input-device.hpp> #include <wayfire/output-layout.hpp> #include <wayfire/core.hpp> #include <wayfire/util/log.hpp> #include <giomm/dbusconnection.h> #include <giomm/dbuswatchname.h> #include <giomm/dbusproxy.h> #include <giomm/init.h> #include <glibmm/main.h> #include <glibmm/init.h> #include <map> extern "C" { #include <wlr/types/wlr_cursor.h> #include <wlr/types/wlr_seat.h> } using namespace Gio; class WayfireAutorotateIIO : public wf::plugin_interface_t { /* Tries to detect whether autorotate is enabled for the current output. * Currently it is enabled only for integrated panels */ bool is_autorotate_enabled() { static const std::string integrated_connectors[] = { "eDP", "LVDS", "DSI", }; /* In wlroots, the output name is based on the connector */ auto output_connector = std::string(output->handle->name); for (auto iconnector : integrated_connectors) { if (output_connector.find(iconnector) != iconnector.npos) { return true; } } return false; } wf::signal_callback_t on_input_devices_changed = [=] (void*) { if (!is_autorotate_enabled()) { return; } auto devices = wf::get_core().get_input_devices(); for (auto& dev : devices) { if (dev->get_wlr_handle()->type == WLR_INPUT_DEVICE_TOUCH) { auto cursor = wf::get_core().get_wlr_cursor(); wlr_cursor_map_input_to_output(cursor, dev->get_wlr_handle(), output->handle); } } }; wf::option_wrapper_t<wf::activatorbinding_t> rotate_up_opt{"autorotate-iio/rotate_up"}, rotate_left_opt{"autorotate-iio/rotate_left"}, rotate_down_opt{"autorotate-iio/rotate_down"}, rotate_right_opt{"autorotate-iio/rotate_right"}; wf::option_wrapper_t<bool> config_rotation_locked{"autorotate-iio/lock_rotation"}; guint watch_id; wf::activator_callback on_rotate_left = [=] (wf::activator_source_t src, int32_t) { return on_rotate_binding(WL_OUTPUT_TRANSFORM_270); }; wf::activator_callback on_rotate_right = [=] (wf::activator_source_t src, int32_t) { return on_rotate_binding(WL_OUTPUT_TRANSFORM_90); }; wf::activator_callback on_rotate_up = [=] (wf::activator_source_t src, int32_t) { return on_rotate_binding(WL_OUTPUT_TRANSFORM_NORMAL); }; wf::activator_callback on_rotate_down = [=] (wf::activator_source_t src, int32_t) { return on_rotate_binding(WL_OUTPUT_TRANSFORM_180); }; /* User-specified rotation via keybinding, -1 means not set */ int32_t user_rotation = -1; /* Transform coming from the iio-sensors, -1 means not set */ int32_t sensor_transform = -1; bool on_rotate_binding(int32_t target_rotation) { if (!output->can_activate_plugin(grab_interface)) { return false; } /* If the user presses the same rotation binding twice, this means * unlock the rotation. Otherwise, just use the new rotation. */ if (target_rotation == user_rotation) { user_rotation = -1; } else { user_rotation = target_rotation; } return update_transform(); } /** Calculate the transform based on user and sensor data, and apply it */ bool update_transform() { wl_output_transform transform_to_use; if (user_rotation >= 0) { transform_to_use = (wl_output_transform)user_rotation; } else if ((sensor_transform >= 0) && !config_rotation_locked) { transform_to_use = (wl_output_transform)sensor_transform; } else { /* No user rotation set, and no sensor data */ return false; } auto configuration = wf::get_core().output_layout->get_current_configuration(); if (configuration[output->handle].transform == transform_to_use) { return false; } configuration[output->handle].transform = transform_to_use; wf::get_core().output_layout->apply_configuration(configuration); return true; } wf::effect_hook_t on_frame = [=] () { Glib::MainContext::get_default()->iteration(false); }; Glib::RefPtr<Glib::MainLoop> loop; public: void init() override { output->add_activator(rotate_left_opt, &on_rotate_left); output->add_activator(rotate_right_opt, &on_rotate_right); output->add_activator(rotate_up_opt, &on_rotate_up); output->add_activator(rotate_down_opt, &on_rotate_down); on_input_devices_changed(nullptr); wf::get_core().connect_signal("input-device-added", &on_input_devices_changed); init_iio_sensors(); } void init_iio_sensors() { if (!is_autorotate_enabled()) { return; } Glib::init(); Gio::init(); loop = Glib::MainLoop::create(true); output->render->add_effect(&on_frame, wf::OUTPUT_EFFECT_PRE); watch_id = DBus::watch_name(DBus::BUS_TYPE_SYSTEM, "net.hadess.SensorProxy", sigc::mem_fun(this, &WayfireAutorotateIIO::on_iio_appeared), sigc::mem_fun(this, &WayfireAutorotateIIO::on_iio_disappeared)); } Glib::RefPtr<DBus::Proxy> iio_proxy; void on_iio_appeared(const Glib::RefPtr<DBus::Connection>& conn, Glib::ustring name, Glib::ustring owner) { LOGI("iio-sensors appeared, connecting ..."); iio_proxy = DBus::Proxy::create_sync(conn, name, "/net/hadess/SensorProxy", "net.hadess.SensorProxy"); if (!iio_proxy) { LOGE("Failed to connect to iio-proxy."); return; } iio_proxy->signal_properties_changed().connect_notify( sigc::mem_fun(this, &WayfireAutorotateIIO::on_properties_changed)); iio_proxy->call_sync("ClaimAccelerometer"); } void on_properties_changed( const Gio::DBus::Proxy::MapChangedProperties& properties, const std::vector<Glib::ustring>& invalidated) { update_orientation(); } void update_orientation() { if (!iio_proxy) { return; } Glib::Variant<Glib::ustring> orientation; iio_proxy->get_cached_property(orientation, "AccelerometerOrientation"); LOGI("IIO Accelerometer orientation: %s", orientation.get().c_str()); static const std::map<std::string, wl_output_transform> transform_by_name = { {"normal", WL_OUTPUT_TRANSFORM_NORMAL}, {"left-up", WL_OUTPUT_TRANSFORM_270}, {"right-up", WL_OUTPUT_TRANSFORM_90}, {"bottom-up", WL_OUTPUT_TRANSFORM_180}, }; if (transform_by_name.count(orientation.get())) { sensor_transform = transform_by_name.find(orientation.get())->second; update_transform(); } } void on_iio_disappeared(const Glib::RefPtr<DBus::Connection>& conn, Glib::ustring name) { LOGI("lost connection to iio-sensors."); iio_proxy.reset(); } void fini() override { output->rem_binding(&on_rotate_left); output->rem_binding(&on_rotate_right); output->rem_binding(&on_rotate_up); output->rem_binding(&on_rotate_down); wf::get_core().disconnect_signal("input-device-added", &on_input_devices_changed); /* If loop is NULL, autorotate was disabled for the current output */ if (loop) { iio_proxy.reset(); DBus::unwatch_name(watch_id); loop->quit(); output->render->rem_effect(&on_frame); } } }; DECLARE_WAYFIRE_PLUGIN(WayfireAutorotateIIO);
29.747253
85
0.617165
kode54
c033d3df203f58b8ac95b6d0c49d38a653cffdb1
1,022
hpp
C++
third-party/sprawl/include/sprawl/common/errors.hpp
3Jade/Ocean
a17bbd6ece6ba0a7539c933cadfc7faad564f9d2
[ "MIT" ]
null
null
null
third-party/sprawl/include/sprawl/common/errors.hpp
3Jade/Ocean
a17bbd6ece6ba0a7539c933cadfc7faad564f9d2
[ "MIT" ]
null
null
null
third-party/sprawl/include/sprawl/common/errors.hpp
3Jade/Ocean
a17bbd6ece6ba0a7539c933cadfc7faad564f9d2
[ "MIT" ]
null
null
null
#pragma once #if defined(SPRAWL_NO_EXCEPTIONS) # define SPRAWL_EXCEPTIONS_ENABLED 0 #elif defined(__clang__) # define SPRAWL_EXCEPTIONS_ENABLED __has_feature(cxx_exceptions) #elif defined(__GNUC__) # ifdef __EXCEPTIONS # define SPRAWL_EXCEPTIONS_ENABLED 1 # else # define SPRAWL_EXCEPTIONS_ENABLED 0 # endif #elif defined(_WIN32) # ifdef _CPPUNWIND # define SPRAWL_EXCEPTIONS_ENABLED 1 # else # define SPRAWL_EXCEPTIONS_ENABLED 0 # endif #else # define SPRAWL_EXCEPTIONS_ENABLED 0 #endif #if SPRAWL_EXCEPTIONS_ENABLED # define SPRAWL_THROW_EXCEPTION(exception, returnValue) throw exception #else namespace sprawl { void throw_exception(std::exception const& exception); } # define SPRAWL_THROW_EXCEPTION(exception, returnValue) sprawl::throw_exception(exception); return returnValue #endif #define SPRAWL_ABORT_MSG(msg, ...) fprintf(stderr, msg, ## __VA_ARGS__); fputs("\n", stderr); abort(); #define SPRAWL_UNIMPLEMENTED_BASE_CLASS_METHOD SPRAWL_ABORT_MSG("This method called is not implemented on this object")
30.969697
119
0.812133
3Jade
c034722ddeff7aed7bd73ff0853f2419ccb04701
4,340
cxx
C++
lio/PMLIO.cxx
kanait/hsphparam
00158f81d00e496fed469779bf73094495ac8671
[ "MIT" ]
1
2021-08-23T06:55:22.000Z
2021-08-23T06:55:22.000Z
lio/PMLIO.cxx
kanait/hsphparam
00158f81d00e496fed469779bf73094495ac8671
[ "MIT" ]
null
null
null
lio/PMLIO.cxx
kanait/hsphparam
00158f81d00e496fed469779bf73094495ac8671
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////// // // $Id: PMLIO.cxx 2021/06/05 13:58:48 kanai Exp $ // // Copyright (c) 2021 Takashi Kanai // Released under the MIT license // //////////////////////////////////////////////////////////////////// #include "envDep.h" #include <iostream> #include <fstream> #include <string> #include "MeshL.hxx" #include "VertexL.hxx" #include "FaceL.hxx" #include "VSplitL.hxx" #include "PMLIO.hxx" // open ppd file using STL fstream bool PMLIO::outputToFile( const char * const pmfile ) { std::ofstream ofs( pmfile ); if ( !ofs ) return false; int vn = mesh().vertices().size() + vsplist().size() * 2; int fn = mesh().faces().size() + vsplist().size() * 2; ofs << "header" << std::endl; ofs << "\tsolid\t1" << std::endl; ofs << "\tpart\t1" << std::endl; ofs << "\tvertex\t" << mesh().vertices().size() << std::endl; ofs << "\tface\t" << mesh().faces().size() << std::endl; ofs << "\tfnode\t" << mesh().faces().size() * 3 << std::endl; ofs << "\tvsplit\t " << vsplist().size() << std::endl; ofs << "\tvall\t " << vn << std::endl; ofs << "\tfall\t " << fn << std::endl; ofs << "end" << std::endl; std::vector<int> v_id_( orgVtSize() ); std::vector<int> f_id_( orgFcSize() ); // solid, part ofs << "solid" << std::endl; ofs << "\t1\t/p 1 1 "; if ( mesh().vertices().size() ) ofs << "/v 1 " << mesh().vertices().size() << " "; if ( mesh().faces().size() ) ofs << "/f 1 " << mesh().faces().size() << " "; ofs << std::endl; ofs << "end" << std::endl; ofs << "part" << std::endl; if ( mesh().faces().size() ) ofs << "\t1\t/f 1 " << mesh().faces().size() << std::endl; ofs << "end" << std::endl; int v_sid = 1; int vid = 1; if ( vn ) { ofs << "vall" << std::endl; foreach ( std::list<VertexL*>, mesh().vertices(), vt ) { // cout << "vt (in vertex) " << (*vt)->id() << endl; Point3d p( (*vt)->point() ); if ( mesh().isNormalized() ) { p.scale( mesh().maxLength() ); p += mesh().center(); } ofs << "\t" << v_sid << "\t" << p.x << " " << p.y << " " << p.z << std::endl; v_id_[ (*vt)->id() ] = vid; ++vid; ++v_sid; } for ( int i = vsplist().size()-1 ; i >= 0; --i ) { Point3d p( vspl(i)->pos(0) ); if ( mesh().isNormalized() ) { p.scale( mesh().maxLength() ); p += mesh().center(); } // cout << "i = " << i << endl; // cout << "vt = " << vspl(i)->id() << endl; ofs << "\t" << v_sid << "\t" << p.x << " " << p.y << " " << p.z << std::endl; ++v_sid; p.set( vspl(i)->pos(1) ); if ( mesh().isNormalized() ) { p.scale( mesh().maxLength() ); p += mesh().center(); } ofs << "\t" << v_sid << "\t" << p.x << " " << p.y << " " << p.z << std::endl; ++v_sid; } ofs << "end" << std::endl; } int id = 1; if ( mesh().faces().size() ) { ofs << "face" << std::endl; foreach ( std::list<FaceL*>, mesh().faces(), fc ) { ofs << "\t" << id << "\t"; foreach ( std::list<HalfedgeL*>, (*fc)->halfedges(), he ) { ofs << v_id_[ (*he)->vertex()->id() ]; ofs << " "; } ofs << std::endl; f_id_[ (*fc)->id() ] = id; ++id; } ofs << "end" << std::endl; } if ( vsplist().size() ) { ofs << "vsplit" << std::endl; int vspl_id = 1; for ( int i = vsplist().size()-1 ; i >= 0; --i ) { //cout << "vt (in vsplit) " << vspl(i)->vt() << endl; f_id_[ vspl(i)->fl() ] = id++; f_id_[ vspl(i)->fr() ] = id++; ofs << "\t" << vspl_id << "\t" << v_id_[ vspl(i)->vt() ] << " /f " << f_id_[ vspl(i)->fn(0) ] << " " << f_id_[ vspl(i)->fn(1) ] << " " << f_id_[ vspl(i)->fn(2) ] << " " << f_id_[ vspl(i)->fn(3) ] << std::endl; v_id_[ vspl(i)->vn(0) ] = vid; vid++; v_id_[ vspl(i)->vn(1) ] = vid; vid++; ++vspl_id; } ofs << "end" << std::endl; } ofs.close(); return true; }
26.956522
89
0.400691
kanait
c03736e763431b1e68749adf99ca97bf8629c554
33,341
cpp
C++
src/CompressedAssemblyGraph.cpp
AustinHartman/shasta
105b8e85e272247f72ced59005c88879631931c0
[ "BSD-3-Clause" ]
null
null
null
src/CompressedAssemblyGraph.cpp
AustinHartman/shasta
105b8e85e272247f72ced59005c88879631931c0
[ "BSD-3-Clause" ]
null
null
null
src/CompressedAssemblyGraph.cpp
AustinHartman/shasta
105b8e85e272247f72ced59005c88879631931c0
[ "BSD-3-Clause" ]
null
null
null
// Shasta. #include "CompressedAssemblyGraph.hpp" #include "Assembler.hpp" #include "deduplicate.hpp" #include "findLinearChains.hpp" #include "html.hpp" #include "platformDependent.hpp" #include "runCommandWithTimeout.hpp" #include "subgraph.hpp" using namespace shasta; // Boost libraries. #include <boost/algorithm/string.hpp> #include <boost/graph/iteration_macros.hpp> #include <boost/lexical_cast.hpp> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/uuid/uuid_io.hpp> // Standard library. #include "fstream.hpp" #include "vector.hpp" // Create the CompressedAssemblyGraph from the AssemblyGraph. CompressedAssemblyGraph::CompressedAssemblyGraph( const Assembler& assembler) { CompressedAssemblyGraph& graph = *this; const AssemblyGraph& assemblyGraph = *(assembler.assemblyGraphPointer); cout << "The assembly graph has " << assemblyGraph.vertices.size() << " vertices and " << assemblyGraph.edges.size() << " edges." << endl; // Create a vertex for each vertex of the assembly graph. vector<vertex_descriptor> vertexTable; createVertices(assemblyGraph.vertices.size(), vertexTable); // Create an edge for each set of parallel edges of the assembly graph. createEdges(assemblyGraph, vertexTable); removeReverseBubbles(); // Merge linear chains of edges. mergeLinearChains(); cout << "The compressed assembly graph has " << num_vertices(graph) << " vertices and " << num_edges(graph) << " edges." << endl; // Assign an id to each edge. assignEdgeIds(); // Fill in the assembly graph edges that go into each // edge of the compressed assembly graph. fillContributingEdges(assemblyGraph); // Fill in minimum and maximum marker counts for each edge. fillMarkerCounts(assemblyGraph); // Find the oriented reads that appear in marker graph vertices // internal to each edge of the compressed assembly graph. findOrientedReads(assembler); fillOrientedReadTable(assembler); // Find edges that have at least one common oriented read // which each edge. findRelatedEdges(); } // Create a vertex for each vertex of the assembly graph. void CompressedAssemblyGraph::createVertices( uint64_t vertexCount, vector<vertex_descriptor>& vertexTable) { CompressedAssemblyGraph& graph = *this; vertexTable.resize(vertexCount, null_vertex()); for(VertexId vertexId=0; vertexId<vertexCount; vertexId++) { const vertex_descriptor v = add_vertex(CompressedAssemblyGraphVertex(vertexId), graph); vertexTable[vertexId] = v; } } // Create an edge for each set of parallel edges of the assembly graph. void CompressedAssemblyGraph::createEdges( const AssemblyGraph& assemblyGraph, const vector<vertex_descriptor>& vertexTable) { CompressedAssemblyGraph& graph = *this; // Loop over assembly graph edges. for(const AssemblyGraph::Edge& edge: assemblyGraph.edges) { const vertex_descriptor v0 = vertexTable[edge.source]; const vertex_descriptor v1 = vertexTable[edge.target]; // Do we already have an edge between these two vertices? bool edgeExists = false; tie(ignore, edgeExists) = boost::edge(v0, v1, graph); // If we don't already have an edge between these two vertices, add it. // We only create one of each set of parallel edges. if(not edgeExists) { edge_descriptor e; bool edgeWasAdded = false; tie(e, edgeWasAdded) = add_edge(v0, v1, graph); SHASTA_ASSERT(edgeWasAdded); // Store the assembly graph vertices. CompressedAssemblyGraphEdge& edge = graph[e]; edge.vertices.push_back(graph[v0].vertexId); edge.vertices.push_back(graph[v1].vertexId); } } } // Remove back edges that create reverse bubbles. // A reverse bubble is defined by two vertices v0 and v1 such that: // - Edge v0->v1 exists. // - Edge v1->v0 exists. // - Out-degree(v0) = 1 // - In-degree(v1) = 1. // Under these conditions, we remove vertex v1->v0. void CompressedAssemblyGraph::removeReverseBubbles() { CompressedAssemblyGraph& graph = *this; // Vector to contain the edges that we wil remove. vector<edge_descriptor> edgesToBeRemoved; // Try all edges. BGL_FORALL_EDGES(e01, graph, CompressedAssemblyGraph) { // Check that v0 has out-degree 1. const vertex_descriptor v0 = source(e01, graph); if(out_degree(v0, graph) != 1) { continue; } // Check that v1 has in-degree 1. const vertex_descriptor v1 = target(e01, graph); if(in_degree(v1, graph) != 1) { continue; } // Look for edges v1->v0. // Try all edges v1->v2. Fkag to be renmoved if v2=v0. BGL_FORALL_OUTEDGES(v1, e12, graph, CompressedAssemblyGraph) { const vertex_descriptor v2 = target(e12, graph); if(v2 == v0) { edgesToBeRemoved.push_back(e12); } } } // Remove the edges we flagged. deduplicate(edgesToBeRemoved); for(const edge_descriptor e: edgesToBeRemoved) { boost::remove_edge(e, graph); } } // Merge linear chains of edges. void CompressedAssemblyGraph::mergeLinearChains() { CompressedAssemblyGraph& graph = *this; // Find linear chains. vector< std::list<edge_descriptor> > chains; findLinearChains(graph, chains); // Replace each chain with a single edge. for(const std::list<edge_descriptor>& chain: chains) { // If the chain has length 1, leave it alone. if(chain.size() == 1) { continue; } // Add the new edge. const vertex_descriptor v0 = source(chain.front(), graph); const vertex_descriptor v1 = target(chain.back(), graph); edge_descriptor eNew; bool edgeWasAdded = false; tie(eNew, edgeWasAdded) = add_edge(v0, v1, graph); SHASTA_ASSERT(edgeWasAdded); CompressedAssemblyGraphEdge& newEdge = graph[eNew]; // Fill in the assembly graph vertices corresponding to this new edge. newEdge.vertices.push_back(graph[v0].vertexId); for(const edge_descriptor e: chain) { const vertex_descriptor v = target(e, graph); newEdge.vertices.push_back(graph[v].vertexId); } // Remove the edges of the chain. // We will remove the vertices later. for(const edge_descriptor e: chain) { boost::remove_edge(e, graph); } } // Remove the vertices that have become isolated. vector<vertex_descriptor> verticesToBeRemoved; BGL_FORALL_VERTICES(v, graph, CompressedAssemblyGraph) { if(in_degree(v, graph) == 0 and out_degree(v, graph) == 0) { verticesToBeRemoved.push_back(v); } } for(const vertex_descriptor v: verticesToBeRemoved) { remove_vertex(v, graph); } } // Assign an id to each edge. void CompressedAssemblyGraph::assignEdgeIds() { CompressedAssemblyGraph& graph = *this; uint64_t edgeId = 0; BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) { graph[e].id = edgeId++; } } // Fill in the assembly graph edges that go into each // edge of the compressed assembly graph. void CompressedAssemblyGraph::fillContributingEdges( const AssemblyGraph& assemblyGraph) { CompressedAssemblyGraph& graph = *this; BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) { CompressedAssemblyGraphEdge& edge = graph[e]; edge.edges.resize(edge.vertices.size() - 1); for(uint64_t i=0; i<edge.edges.size(); i++) { const VertexId vertexId0 = edge.vertices[i]; const VertexId vertexId1 = edge.vertices[i+1]; const span<const EdgeId> edges0 = assemblyGraph.edgesBySource[vertexId0]; for(const EdgeId edge01: edges0) { if(assemblyGraph.edges[edge01].target == vertexId1) { edge.edges[i].push_back(edge01); } } } } } // Find the oriented reads that appear in marker graph vertices // internal to each edge of the compressed assembly graph. void CompressedAssemblyGraph::findOrientedReads( const Assembler& assembler) { CompressedAssemblyGraph& graph = *this; BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) { graph[e].findOrientedReads(assembler); } // Fill in the oriented read table, which tells us // which edges each read appears in. orientedReadTable.resize(2 * assembler.getReads().readCount()); BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) { for(const OrientedReadId orientedReadId: graph[e].orientedReadIds) { orientedReadTable[orientedReadId.getValue()].push_back(e); } } } void CompressedAssemblyGraph::fillOrientedReadTable( const Assembler& assembler) { CompressedAssemblyGraph& graph = *this; orientedReadTable.clear(); orientedReadTable.resize(2 * assembler.getReads().readCount()); BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) { for(const OrientedReadId orientedReadId: graph[e].orientedReadIds) { orientedReadTable[orientedReadId.getValue()].push_back(e); } } } // Find the oriented reads that appear in marker graph vertices // internal to an edge of the compressed assembly graph. void CompressedAssemblyGraphEdge::findOrientedReads( const Assembler& assembler) { const AssemblyGraph& assemblyGraph = *assembler.assemblyGraphPointer; // Loop over assembly graph edges. for(const vector<AssemblyGraph::EdgeId>& edgesHere: edges) { for(const AssemblyGraph::EdgeId assemblyGraphEdgeId: edgesHere) { // Loop over marker graph edges corresponding to this // assembly graph edge. const span<const MarkerGraph::EdgeId> markerGraphEdgeIds = assemblyGraph.edgeLists[assemblyGraphEdgeId]; for(const MarkerGraph::EdgeId markerGraphEdgeId: markerGraphEdgeIds) { findOrientedReads(assembler, markerGraphEdgeId); } } } // Deduplicate oriented reads and count their occurrences. deduplicateAndCount(orientedReadIds, orientedReadIdsFrequency); } // Append to orientedReadIds the oriented reads that // appear in a given marker graph edge. void CompressedAssemblyGraphEdge::findOrientedReads( const Assembler& assembler, const MarkerGraph::EdgeId& markerGraphEdgeId) { const span<const MarkerInterval> markerIntervals = assembler.markerGraph.edgeMarkerIntervals[markerGraphEdgeId]; for(const MarkerInterval markerInterval: markerIntervals) { orientedReadIds.push_back(markerInterval.orientedReadId); } } // Find edges that have at least one common oriented read // which each edge. void CompressedAssemblyGraph::findRelatedEdges() { CompressedAssemblyGraph& graph = *this; BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) { findRelatedEdges(e); } } void CompressedAssemblyGraph::findRelatedEdges(edge_descriptor e0) { CompressedAssemblyGraph& graph = *this; CompressedAssemblyGraphEdge& edge0 = graph[e0]; for(const OrientedReadId orientedReadId: edge0.orientedReadIds) { const vector<edge_descriptor>& edges = orientedReadTable[orientedReadId.getValue()]; for(const edge_descriptor e1: edges) { if(e1 != e0) { edge0.relatedEdges.push_back(e1); } } } deduplicate(edge0.relatedEdges); edge0.relatedEdges.shrink_to_fit(); /* cout << edge0.gfaId() << ":"; for(const edge_descriptor e1: edge0.relatedEdges) { cout << " " << graph[e1].gfaId(); } cout << endl; */ } string CompressedAssemblyGraphEdge::gfaId() const { if(edges.size()==1 and edges.front().size()==1) { // Return the one and only assembly graph edge associated with this // compressed assembly graph edge. return to_string(edges.front().front()); } else { // Return the id of this compressed assembly graph edge, // prefixed with "C". return "C" + to_string(id); } } // Return the edge with a given GFA id. pair<CompressedAssemblyGraph::edge_descriptor, bool> CompressedAssemblyGraph::getEdgeFromGfaId( const string& s) const { const CompressedAssemblyGraph& graph = *this; BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) { if(graph[e].gfaId() == s) { return make_pair(e, true); } } return make_pair(edge_descriptor(), false); } uint64_t CompressedAssemblyGraph::maxPloidy() const { const CompressedAssemblyGraph& graph = *this; uint64_t returnValue = 0; BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) { returnValue = max(returnValue, graph[e].maxPloidy()); } return returnValue; } uint64_t CompressedAssemblyGraphEdge::maxPloidy() const { uint64_t returnValue = 0; for(const auto& v: edges) { returnValue = max(returnValue, uint64_t(v.size())); } return returnValue; } // GFA output (without sequence). void CompressedAssemblyGraph::writeGfa(const string& fileName, double basesPerMarker) const { ofstream gfa(fileName); writeGfa(gfa, basesPerMarker); } void CompressedAssemblyGraph::writeGfa(ostream& gfa, double basesPerMarker) const { const CompressedAssemblyGraph& graph = *this; // Write the header line. gfa << "H\tVN:Z:1.0\n"; // Write a segment record for each edge. BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) { const CompressedAssemblyGraphEdge& edge = graph[e]; gfa << "S\t" << edge.gfaId() << "\t" << "*\t" << "LN:i:" << uint64_t(basesPerMarker * 0.5 * double(edge.minMarkerCount + edge.maxMarkerCount)) << "\n"; } // Write GFA links. // For each vertex in the compressed assembly graph there is a link for // each combination of in-edges and out-edges. // Therefore each vertex generates a number of // links equal to the product of its in-degree and out-degree. BGL_FORALL_VERTICES(v, graph, CompressedAssemblyGraph) { BGL_FORALL_INEDGES(v, eIn, graph, CompressedAssemblyGraph) { BGL_FORALL_OUTEDGES(v, eOut, graph, CompressedAssemblyGraph) { gfa << "L\t" << graph[eIn].gfaId() << "\t" << "+\t" << graph[eOut].gfaId() << "\t" << "+\t" << "*\n"; } } } } void CompressedAssemblyGraph::writeCsv() const { writeCsvEdges(); writeCsvBubbleChains(); writeCsvOrientedReadsByEdge(); writeCsvOrientedReads(); } void CompressedAssemblyGraph::writeCsvEdges() const { const CompressedAssemblyGraph& graph = *this; ofstream csv("CompressedGraph-Edges.csv"); csv << "Id,GFA id,Source,Target,MinMarkerCount,MaxMarkerCount,OrientedReadsCount,RelatedEdgesCount,\n"; BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) { const CompressedAssemblyGraphEdge& edge = graph[e]; const vertex_descriptor v0 = source(e, graph); const vertex_descriptor v1 = target(e, graph); csv << edge.id << ","; csv << edge.gfaId() << ","; csv << graph[v0].vertexId << ","; csv << graph[v1].vertexId << ","; csv << edge.minMarkerCount << ","; csv << edge.maxMarkerCount << ","; csv << edge.orientedReadIds.size() << ","; csv << edge.relatedEdges.size() << ","; csv << "\n"; } } void CompressedAssemblyGraph::writeCsvOrientedReadsByEdge() const { const CompressedAssemblyGraph& graph = *this; ofstream csv("CompressedGraph-OrientedReadsByEdge.csv"); csv << "Id,GFA id,OrientedRead,Frequency\n"; BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) { const CompressedAssemblyGraphEdge& edge = graph[e]; SHASTA_ASSERT(edge.orientedReadIds.size() == edge.orientedReadIdsFrequency.size()); for(uint64_t i=0; i<edge.orientedReadIds.size(); i++) { const OrientedReadId orientedReadId = edge.orientedReadIds[i]; const uint64_t frequency = edge.orientedReadIdsFrequency[i]; csv << edge.id << ","; csv << edge.gfaId() << ","; csv << orientedReadId << ","; csv << frequency << "\n"; } } } void CompressedAssemblyGraph::writeCsvBubbleChains() const { const CompressedAssemblyGraph& graph = *this; const uint64_t maxPloidy = graph.maxPloidy(); ofstream csv("CompressedGraph-BubbleChains.csv"); csv << "Id,GFA id,Position,"; for(uint64_t i=0; i<maxPloidy; i++) { csv << "Edge" << i << ","; } csv << "\n"; BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) { const CompressedAssemblyGraphEdge& edge = graph[e]; for(uint64_t position=0; position<edge.edges.size(); position++) { const vector<AssemblyGraph::EdgeId>& edgesAtPosition = edge.edges[position]; csv << edge.id << ","; csv << edge.gfaId() << ","; csv << position << ","; for(const AssemblyGraph::EdgeId edgeId: edgesAtPosition) { csv << edgeId << ","; } csv << "\n"; } } } void CompressedAssemblyGraph::writeCsvOrientedReads() const { const CompressedAssemblyGraph& graph = *this; ofstream csv("CompressedGraph-OrientedReads.csv"); csv << "OrientedReadId,Id,GFA id,\n"; for(OrientedReadId::Int orientedReadId=0; orientedReadId<orientedReadTable.size(); orientedReadId++) { const vector<edge_descriptor>& edges = orientedReadTable[orientedReadId]; for(const edge_descriptor e: edges) { const CompressedAssemblyGraphEdge& edge = graph[e]; csv << OrientedReadId(orientedReadId) << ","; csv << edge.id << ","; csv << edge.gfaId() << "\n"; } } } // Fill in minimum and maximum marker counts for each edge. void CompressedAssemblyGraph::fillMarkerCounts(const AssemblyGraph& assemblyGraph) { CompressedAssemblyGraph& graph = *this; BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) { graph[e].fillMarkerCounts(assemblyGraph); } } void CompressedAssemblyGraphEdge::fillMarkerCounts(const AssemblyGraph& assemblyGraph) { minMarkerCount = 0; maxMarkerCount = 0; for(const vector<AssemblyGraph::EdgeId>& parallelEdges: edges) { SHASTA_ASSERT(not parallelEdges.empty()); // Compute the minimum and maximum number of markers // over this set of parallel edges. uint64_t minMarkerCountHere = std::numeric_limits<uint64_t>::max(); uint64_t maxMarkerCountHere = 0; for(const AssemblyGraph::EdgeId edgeId: parallelEdges) { const uint64_t markerCount = assemblyGraph.edgeLists.size(edgeId); minMarkerCountHere = min(minMarkerCountHere, markerCount); maxMarkerCountHere = max(maxMarkerCountHere, markerCount); } // Update the totals. minMarkerCount += minMarkerCountHere; maxMarkerCount += maxMarkerCountHere; } } // Create a local subgraph. // See createLocalSubgraph for argument explanation. CompressedAssemblyGraph::CompressedAssemblyGraph( const CompressedAssemblyGraph& graph, const Assembler& assembler, const vector<vertex_descriptor>& startVertices, uint64_t maxDistance, boost::bimap<vertex_descriptor, vertex_descriptor>& vertexMap, boost::bimap<edge_descriptor, edge_descriptor>& edgeMap, std::map<vertex_descriptor, uint64_t>& distanceMap ) { CompressedAssemblyGraph& subgraph = *this; createLocalSubgraph( graph, startVertices, maxDistance, subgraph, vertexMap, edgeMap, distanceMap); // Make sure the relatedEdges of each edge contain // edge descriptors in the subgraph. BGL_FORALL_EDGES(e0, subgraph, CompressedAssemblyGraph) { vector<edge_descriptor> relatedEdges; for(const edge_descriptor e1: subgraph[e0].relatedEdges) { const auto it = edgeMap.right.find(e1); if(it != edgeMap.right.end()) { relatedEdges.push_back(it->second); } } subgraph[e0].relatedEdges.swap(relatedEdges); } subgraph.fillOrientedReadTable(assembler); } // Graphviz output. void CompressedAssemblyGraph::writeGraphviz( const string& fileName, uint64_t sizePixels, double vertexScalingFactor, double edgeLengthScalingFactor, double edgeThicknessScalingFactor, double edgeArrowScalingFactor, std::map<vertex_descriptor, array<double, 2 > >& vertexPositions) const { ofstream s(fileName); writeGraphviz(s, sizePixels, vertexScalingFactor, edgeLengthScalingFactor, edgeThicknessScalingFactor, edgeArrowScalingFactor, vertexPositions) ; } void CompressedAssemblyGraph::writeGraphviz( ostream& s, uint64_t sizePixels, double vertexScalingFactor, double edgeLengthScalingFactor, double edgeThicknessScalingFactor, double edgeArrowScalingFactor, std::map<vertex_descriptor, array<double, 2 > >& vertexPositions) const { const CompressedAssemblyGraph& graph = *this; s << "digraph CompressedAssemblyGraph {\n" "layout=neato;\n" "size=" << uint64_t(double(sizePixels)/72.) << ";\n" "ratio=expand;\n" "splines=true;\n" "node [shape=point];\n" "node [width=" << vertexScalingFactor << "];\n" "edge [penwidth=" << edgeThicknessScalingFactor << "];\n" "edge [arrowsize=" << edgeArrowScalingFactor << "];\n"; // Write the vertices. BGL_FORALL_VERTICES(v, graph, CompressedAssemblyGraph) { const auto it = vertexPositions.find(v); SHASTA_ASSERT(it != vertexPositions.end()); const auto& x = it->second; s << graph[v].vertexId << " [pos=\"" << x[0] << "," << x[1] << "\"];\n"; } // Write the edges. // Each edge is written as a number of dummy edges, // to make it look longer, proportionally to its number of markers. BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) { const CompressedAssemblyGraphEdge& edge = graph[e]; const string gfaId = edge.gfaId(); const vertex_descriptor v0 = source(e, graph); const vertex_descriptor v1 = target(e, graph); // To color the edge, use a hash function of the edge id, // so the same edge always gets colored the same way. const uint32_t hashValue = MurmurHash2(&edge.id, sizeof(edge.id), 757); const double H = double(hashValue) / double(std::numeric_limits<uint32_t>::max()); const double S = 0.7; const double V = 0.7; s << graph[v0].vertexId << "->" << graph[v1].vertexId << "[tooltip=\"" << gfaId << "\" " "color = \"" << H << "," << S << "," << "," << V << "\"" << "];\n"; } s << "}"; } #if 0 void CompressedAssemblyGraph::writeGraphviz( ostream& s, uint64_t sizePixels, double vertexScalingFactor, double edgeLengthScalingFactor, double edgeThicknessScalingFactor, double edgeArrowScalingFactor, std::map<vertex_descriptor, array<double, 2 > >& vertexPositions) const { const CompressedAssemblyGraph& graph = *this; s << "digraph CompressedAssemblyGraph {\n" "layout=sfdp;\n" "size=" << uint64_t(double(sizePixels)/72.) << ";\n" "ratio=expand;\n" "rankdir=LR;\n" "node [shape=point];\n" "node [width=" << vertexScalingFactor << "];\n" "edge [penwidth=" << edgeThicknessScalingFactor << "];\n" "edge [arrowsize=" << edgeArrowScalingFactor << "];\n" "edge [arrowhead=none];\n"; // Write the vertices. BGL_FORALL_VERTICES(v, graph, CompressedAssemblyGraph) { s << graph[v].vertexId << ";\n"; } // Write the edges. // Each edge is written as a number of dummy edges, // to make it look longer, proportionally to its number of markers. BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) { const CompressedAssemblyGraphEdge& edge = graph[e]; const string gfaId = edge.gfaId(); const vertex_descriptor v0 = source(e, graph); const vertex_descriptor v1 = target(e, graph); const uint64_t dummyEdgeCount = max(uint64_t(1), uint64_t(0.5 + edgeLengthScalingFactor * edge.averageMarkerCount())); // Write the dummy vertices. for(uint64_t i=1; i<dummyEdgeCount; i++) { s << "\"" << gfaId << "-dummy" << i << "\" [width=" << edgeThicknessScalingFactor/72 << "];\n"; } // Write the dummy edges. for(uint64_t i=0; i<dummyEdgeCount; i++) { // First vertex - either v0 or a dummy vertex. s << "\""; if(i == 0) { s << graph[v0].vertexId; } else { s << gfaId << "-dummy" << i; } s << "\"->\""; // Second vertex - either v1 or a dummy vertex. if(i == dummyEdgeCount-1) { s << graph[v1].vertexId; } else { s << gfaId << "-dummy" << i+1; } s << "\""; s << " ["; if(i == dummyEdgeCount-1) { s << "style=tapered"; } /* if(i == dummyEdgeCount/2) { s << " label=" << edge.gfaId(); } */ s << "]"; s << ";\n"; } } s << "}"; } #endif // Use sfdp to compute a vertex layout. // But sfdp does not support edges of different length // (it tries to make all edges the same length). // Here, we expand each edge into a variable number // of dummy edges. Longer edges are expanded into more // dummy edges. Then we use sfdp to compute a layout // including all these dummy edges (and their vertices). // Finally, we extract the coordinates for the original // vertices only. void CompressedAssemblyGraph::computeVertexLayout( uint64_t sizePixels, double vertexScalingFactor, double edgeLengthPower, double edgeLengthScalingFactor, double timeout, std::map<vertex_descriptor, array<double, 2 > >& vertexPositions ) const { const CompressedAssemblyGraph& graph = *this; // Create a dot file to contain the graph including the dummy edges. const string uuid = to_string(boost::uuids::random_generator()()); const string dotFileName = tmpDirectory() + uuid + ".dot"; ofstream graphOut(dotFileName); graphOut << "digraph G{\n" "layout=sfdp;\n" "smoothing=triangle;\n" "overlap=false;\n" << "size=" << uint64_t(double(sizePixels)/72.) << ";\n" "ratio=expand;\n" "node [shape=point];\n" "node [width=" << vertexScalingFactor << "];\n"; // Write the vertices. BGL_FORALL_VERTICES(v, graph, CompressedAssemblyGraph) { graphOut << graph[v].vertexId << ";\n"; } // Write the dummy edges. BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) { const CompressedAssemblyGraphEdge& edge = graph[e]; const string gfaId = edge.gfaId(); const vertex_descriptor v0 = source(e, graph); const vertex_descriptor v1 = target(e, graph); // Figure out the number of dummy edges, based on the number of // markers on this edge. const double desiredDummyEdgeCount = edgeLengthScalingFactor * std::pow(edge.averageMarkerCount(), edgeLengthPower); const uint64_t dummyEdgeCount = max( uint64_t(1), uint64_t(0.5 + desiredDummyEdgeCount)); // Write the dummy edges. for(uint64_t i=0; i<dummyEdgeCount; i++) { // First vertex - either v0 or a dummy vertex. if(i == 0) { graphOut << graph[v0].vertexId; } else { graphOut << "D" << i << "_" << gfaId; } graphOut << "->"; // Second vertex - either v1 or a dummy vertex. if(i == dummyEdgeCount-1) { graphOut << graph[v1].vertexId; } else { graphOut << "D" << i+1 << "_" << gfaId; } graphOut << ";\n"; } } graphOut << "}"; graphOut.close(); // Now use sfdp to compute the layout. // Use plain format output described here // https://www.graphviz.org/doc/info/output.html#d:plain const string plainFileName = dotFileName + ".txt"; const string command = "sfdp -T plain " + dotFileName + " -o " + plainFileName; bool timeoutTriggered = false; bool signalOccurred = false; int returnCode = 0; runCommandWithTimeout(command, timeout, timeoutTriggered, signalOccurred, returnCode); if(signalOccurred) { throw runtime_error("Unable to compute graph layout: terminated by a signal. " "The failing command was: " + command); } if(timeoutTriggered) { throw runtime_error("Timeout exceeded during graph layout computation. " "Increase the timeout or decrease the maximum distance to simplify the graph"); } if(returnCode!=0 ) { throw runtime_error("Unable to compute graph layout: return code " + to_string(returnCode) + ". The failing command was: " + command); } filesystem::remove(dotFileName); // Map vertex ids to vertex descriptors. std::map<uint64_t, vertex_descriptor> vertexMap; BGL_FORALL_VERTICES(v, graph, CompressedAssemblyGraph) { vertexMap.insert(make_pair(graph[v].vertexId, v)); } // Extract vertex coordinates. ifstream plainFile(plainFileName); string line; vector<string> tokens; while(true) { // Read the next line. std::getline(plainFile, line); if( not plainFile) { break; } // Parse it. boost::algorithm::split(tokens, line, boost::algorithm::is_any_of(" ")); // SHASTA_ASSERT(not tokens.empty()); // If not a line describing a vertex, skip it. if(tokens.front() != "node") { continue; } SHASTA_ASSERT(tokens.size() >= 4); // If a dummy vertex, skip it. const string& vertexName = tokens[1]; SHASTA_ASSERT(not vertexName.empty()); if(vertexName[0] == 'D') { continue; } // Get the vertex id. const uint64_t vertexId = boost::lexical_cast<uint64_t>(vertexName); // Get the corresponding vertex descriptor. const auto it = vertexMap.find(vertexId); const vertex_descriptor v = it->second; // Store it in the layout. array<double, 2> x; x[0] = boost::lexical_cast<double>(tokens[2]); x[1] = boost::lexical_cast<double>(tokens[3]); vertexPositions.insert(make_pair(v, x)); } plainFile.close(); filesystem::remove(plainFileName); } // Create a csv file with coloring. // If the string passed in is an oriented read, // it colors all edges that have that read. // If it is the gfaId of an edge, it colors that edge in red // and all related edges in green. // This can be loaded in Bandage to color the edges. void CompressedAssemblyGraph::color( const string& s, const string& fileName) const { ofstream csv(fileName); color(s, csv); } void CompressedAssemblyGraph::color( const string& s, ostream& csv) const { const CompressedAssemblyGraph& graph = *this; std::map<edge_descriptor, string> colorMap; // If it is the gfaId of an edge, color that edge in red // and all related edges in green. edge_descriptor e0; bool edgeWasFound = false; tie(e0, edgeWasFound) = getEdgeFromGfaId(s); if(edgeWasFound) { colorMap.insert(make_pair(e0, "Red")); for(const edge_descriptor e1: graph[e0].relatedEdges) { colorMap.insert(make_pair(e1, "Green")); } } // If it is an oriented read id, color in green all segments // that have that oriented read. else { try { const OrientedReadId orientedReadId = OrientedReadId(s); for(const edge_descriptor e1: orientedReadTable[orientedReadId.getValue()]) { colorMap.insert(make_pair(e1, "Green")); } } catch(...) { cout << "The string to color by does not correspond to a valid " "GFA id or a valid oriented read id.\n"; } } csv << "Segment,Color\n"; BGL_FORALL_EDGES(e, graph, CompressedAssemblyGraph) { csv << graph[e].gfaId() << ","; const auto it = colorMap.find(e); if(it == colorMap.end()) { csv << "Grey"; } else { csv << it->second; } csv << "\n"; } }
30.928571
107
0.627966
AustinHartman
c0392ef762db36fb4665005319d9110d07051568
12,729
cpp
C++
server/Server/Other/ShopManager.cpp
viticm/web-pap
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
[ "BSD-3-Clause" ]
3
2018-06-19T21:37:38.000Z
2021-07-31T21:51:40.000Z
server/Server/Other/ShopManager.cpp
viticm/web-pap
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
[ "BSD-3-Clause" ]
null
null
null
server/Server/Other/ShopManager.cpp
viticm/web-pap
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
[ "BSD-3-Clause" ]
13
2015-01-30T17:45:06.000Z
2022-01-06T02:29:34.000Z
#include "stdafx.h" #include "ShopManager.h" //public #include "Obj_Human.h" #include "Player.h" #include "Obj_Monster.h" #include "PAP_DBC.h"//DBC #include "ItemHelper.h"//TSerialHelper #include "ItemTable.h"//_ITEM_TYPE #include "TimeManager.h"//g_pTimeManager #include "GCShopUpdateMerchandiseList.h"//GCShopUpdateMerchandiseList #include "FileDef.h" //globle using namespace DBC; StaticShopManager* g_pStaticShopManager = NULL; //macro #define SHOP_ITEM_PROPERTY_NUM 3 #define SHOP_ID 0 //#define SHOP_NAME SHOP_ID+1 #define SHOP_TYPE SHOP_ID+1 #define SHOP_REPAIR_LEVEL SHOP_TYPE+1 #define SHOP_BUY_LEVEL SHOP_REPAIR_LEVEL+1 #define SHOP_REPAIR_TYPE SHOP_BUY_LEVEL+1 #define SHOP_BUY_TYPE SHOP_REPAIR_TYPE+1 #define SHOP_REPAIR_SPEND SHOP_BUY_TYPE+1 #define SHOP_REPAIR_OKPROB SHOP_REPAIR_SPEND+1 #define SHOP_SCALE SHOP_REPAIR_OKPROB+1 +2//LM修改 #define SHOP_REFRESH_TIME SHOP_SCALE+1 #define SHOP_ITEM_NUM SHOP_REFRESH_TIME+1 #define SHOP_ITEM_PROPERTY_BEGIN SHOP_ITEM_NUM+1 #define NEW_AND_COPY_ARRAY(PDEST, PSOURCE, NUM, TYPE)\ PDEST = new TYPE[NUM];\ memcpy((CHAR*)PDEST, (CHAR*)PSOURCE, NUM*sizeof(TYPE));\ ShopMgr::ShopMgr() { __ENTER_FUNCTION m_Count = 0; m_Shops = NULL; __LEAVE_FUNCTION } ShopMgr::~ShopMgr() { __ENTER_FUNCTION CleanUp(); __LEAVE_FUNCTION } VOID ShopMgr::CleanUp( ) { __ENTER_FUNCTION SAFE_DELETE_ARRAY(m_Shops) __LEAVE_FUNCTION } //直接从ItemBoxManager::ConvertItemType2Index抄过来 INT ShopMgr::ConvertItemType2Money(_ITEM_TYPE it) { __ENTER_FUNCTION Assert(it.isNull() == FALSE); switch(it.m_Class) { case ICLASS_EQUIP: { switch(it.m_Quality) { case EQUALITY_NORMAL: { COMMON_EQUIP_TB* pGET = g_ItemTable.GetWhiteItemTB(it.ToSerial()); Assert(pGET); return pGET->m_BasePrice; } break; case EQUALITY_BLUE: { BLUE_EQUIP_TB* pGET = g_ItemTable.GetBlueItemTB(it.ToSerial()); Assert(pGET); return pGET->m_BasePrice; } break; case EQUALITY_YELLOW: { } break; case EQUALITY_GREEN: { GREEN_EQUIP_TB* pGET = g_ItemTable.GetGreenItemTB(it.ToSerial()); Assert(pGET); return pGET->m_BasePrice; } break; default: { Assert(FALSE); return FALSE; } } Assert(FALSE); } break; case ICLASS_MATERIAL: case ICLASS_COMITEM: { COMMITEM_INFO_TB* pGET = g_ItemTable.GetCommItemInfoTB(it.ToSerial()); Assert(pGET); return pGET->m_nBasePrice; } break; case ICLASS_TASKITEM: { return 1; } break; case ICLASS_GEM: { GEMINFO_TB* pGET = g_ItemTable.GetGemInfoTB(it.ToSerial()); Assert(pGET); return pGET->m_nPrice; } break; case ICLASS_STOREMAP: { STORE_MAP_INFO_TB* pGET = g_ItemTable.GetStoreMapTB(it.ToSerial()); Assert(pGET); return pGET->m_nBasePrice; break; } case ICLASS_TALISMAN: Assert(FALSE); break; case ICLASS_GUILDITEM: Assert(FALSE); break; default: Assert(FALSE); break; } Assert(FALSE); __LEAVE_FUNCTION return -1; } _SHOP* ShopMgr::GetShopByID(INT id) { __ENTER_FUNCTION for(INT i = 0; i<m_Count; i++) { if(m_Shops[i].m_ShopId == id) { return &m_Shops[i]; } } return NULL; __LEAVE_FUNCTION return NULL; } INT ShopMgr::GetShopIndexByID(INT id) { __ENTER_FUNCTION for(INT i = 0; i<m_Count; i++) { if(m_Shops[i].m_ShopId == id) { return i; } } return -1; __LEAVE_FUNCTION return -1; } /* StaticShopManager */ StaticShopManager::~StaticShopManager() { __ENTER_FUNCTION CleanUp(); __LEAVE_FUNCTION } BOOL StaticShopManager::Init() { return LoadShopsFromFile( FILE_SHOP ); } VOID StaticShopManager::CleanUp() { __ENTER_FUNCTION SAFE_DELETE_ARRAY(m_Shops) __LEAVE_FUNCTION } BOOL StaticShopManager::LoadShopsFromFile( CHAR* filename ) { __ENTER_FUNCTION UINT d = sizeof(_ITEM); DBCFile ShopFile(0); BOOL ret = ShopFile.OpenFromTXT(filename); if( !ret ) return FALSE; INT iTableCount = ShopFile.GetRecordsNum(); INT iTableColumn = ShopFile.GetFieldsNum(); m_Count = iTableCount; m_Shops = new _SHOP[m_Count]; INT itemnum = 0; INT i,j,k; INT itemTypeSn; _ITEM_TYPE itemType; INT PerItemNum = 0; INT MaxItemNum = 0; FLOAT PerRate = 0.0; for(i =0;i<iTableCount;i++) { m_Shops[i].m_ShopId = ShopFile.Search_Posistion(i,SHOP_ID)->iValue; //strncpy( m_Shops[i].m_szShopName, ShopFile.Search_Posistion(i,SHOP_NAME)->pString, MAX_SHOP_NAME-2 ); m_Shops[i].m_ShopType = ShopFile.Search_Posistion(i,SHOP_TYPE)->iValue; m_Shops[i].m_nRepairLevel = ShopFile.Search_Posistion(i,SHOP_REPAIR_LEVEL)->iValue; m_Shops[i].m_nBuyLevel = ShopFile.Search_Posistion(i,SHOP_BUY_LEVEL)->iValue; m_Shops[i].m_nRepairType = ShopFile.Search_Posistion(i,SHOP_REPAIR_TYPE)->iValue; m_Shops[i].m_nBuyType = ShopFile.Search_Posistion(i,SHOP_BUY_TYPE)->iValue; m_Shops[i].m_nRepairSpend = ShopFile.Search_Posistion(i,SHOP_REPAIR_SPEND)->fValue; m_Shops[i].m_nRepairOkProb = ShopFile.Search_Posistion(i,SHOP_REPAIR_OKPROB)->fValue; m_Shops[i].m_scale = ShopFile.Search_Posistion(i,SHOP_SCALE)->fValue; m_Shops[i].m_refreshTime = ShopFile.Search_Posistion(i,SHOP_REFRESH_TIME)->iValue; itemnum = ShopFile.Search_Posistion(i,SHOP_ITEM_NUM)->iValue; //分析实际有的数据 INT nNum = 0; for(k=0; k<itemnum*SHOP_ITEM_PROPERTY_NUM; k++) { itemTypeSn = ShopFile.Search_Posistion(i,SHOP_ITEM_PROPERTY_BEGIN+k)->iValue; if(itemTypeSn == 0) { break; } nNum ++; k = k+2; } itemnum = nNum; m_Shops[i].m_ItemList = new _SHOP::_MERCHANDISE_LIST(itemnum); for(j = 0; j<itemnum*SHOP_ITEM_PROPERTY_NUM; j++) { //Type itemTypeSn = ShopFile.Search_Posistion(i,SHOP_ITEM_PROPERTY_BEGIN+j)->iValue; TSerialHelper help(itemTypeSn); itemType = help.GetItemTypeStruct(); //GroupNum 0~100 PerItemNum = ShopFile.Search_Posistion(i,SHOP_ITEM_PROPERTY_BEGIN+(++j))->iValue; if(PerItemNum<0) PerItemNum = 1; if(PerItemNum>100) PerItemNum = 100; //MaxNum -1代表无限,>0代表有限商品上限,不可以填0,<100 MaxItemNum = ShopFile.Search_Posistion(i,SHOP_ITEM_PROPERTY_BEGIN+(++j))->iValue; if(MaxItemNum == 0) MaxItemNum = -1; if(PerItemNum>100) PerItemNum = 100; //Rate 0.0~1.0 PerRate = 1.0; //ADD TO STRUCTURE m_Shops[i].m_ItemList->AddType(itemType, PerItemNum, MaxItemNum, PerRate); } } return TRUE; __LEAVE_FUNCTION return FALSE; } /* DynamicShopManager */ DynamicShopManager::DynamicShopManager(Obj_Monster* pboss) { __ENTER_FUNCTION m_pBoss = pboss; m_Count = MAX_SHOP_PER_PERSON; m_Shops = new _SHOP[m_Count]; m_aRefeshTimer = new CMyTimer[m_Count]; memset(m_aRefeshTimer,0, m_Count*sizeof(CMyTimer)); __LEAVE_FUNCTION } DynamicShopManager::~DynamicShopManager() { __ENTER_FUNCTION CleanUp(); __LEAVE_FUNCTION } BOOL DynamicShopManager::Init() { m_nCurrent = 0; return (m_Shops!= NULL)? TRUE:FALSE; } VOID DynamicShopManager::CleanUp() { SAFE_DELETE_ARRAY(m_Shops) SAFE_DELETE_ARRAY(m_aRefeshTimer) return; } INT DynamicShopManager::AddDynamicShop(_SHOP* pSource) { __ENTER_FUNCTION if(m_nCurrent > MAX_SHOP_PER_PERSON) return -1; for(INT i = 0;i<m_nCurrent; i++) { if(m_Shops[i].m_ShopId == pSource->m_ShopId) {//表里已经有了 return -1; } } INT itemnum; _SHOP& ShopRef = m_Shops[m_nCurrent]; ShopRef.m_ShopId = pSource->m_ShopId; ShopRef.m_scale = pSource->m_scale; ShopRef.m_refreshTime = pSource->m_refreshTime; itemnum = pSource->m_ItemList->m_ListCount; ShopRef.m_ItemList = new _SHOP::_MERCHANDISE_LIST; ShopRef.m_ItemList->m_nCurrent = pSource->m_ItemList->m_nCurrent; ShopRef.m_ItemList->m_ListCount = itemnum; ShopRef.m_ShopType = pSource->m_ShopType; ShopRef.m_bIsRandShop = pSource->m_bIsRandShop; ShopRef.m_nCountForSell = pSource->m_nCountForSell; ShopRef.m_nRepairLevel = pSource->m_nRepairLevel; ShopRef.m_nBuyLevel = pSource->m_nBuyLevel; ShopRef.m_nRepairType = pSource->m_nRepairType; ShopRef.m_nBuyType = pSource->m_nBuyType; ShopRef.m_nRepairSpend = pSource->m_nRepairSpend; ShopRef.m_nRepairOkProb = pSource->m_nRepairOkProb; ShopRef.m_bCanBuyBack = pSource->m_bCanBuyBack; ShopRef.m_bCanMultiBuy = pSource->m_bCanMultiBuy; ShopRef.m_uSerialNum = pSource->m_uSerialNum; ShopRef.m_Rand100 = pSource->m_Rand100; strncpy( ShopRef.m_szShopName, pSource->m_szShopName, MAX_SHOP_NAME ); //copycopycopy!!!!!,这些数据要保存在本地,供每个商人自己改变 NEW_AND_COPY_ARRAY(ShopRef.m_ItemList->m_TypeMaxNum, pSource->m_ItemList->m_TypeMaxNum, itemnum, INT) //其他数据全部共享静态表中的数据,这些应该全部是只读的,程序启动时由静态商店管理器初始化, //系统运行起来后谁都不准改!! ShopRef.m_ItemList->m_ListType = pSource->m_ItemList->m_ListType; ShopRef.m_ItemList->m_ListTypeIndex = pSource->m_ItemList->m_ListTypeIndex; ShopRef.m_ItemList->m_TypeCount = pSource->m_ItemList->m_TypeCount; ShopRef.m_ItemList->m_AppearRate = pSource->m_ItemList->m_AppearRate; //全部操作完成,标识这个商店为动态表中的商店,即,可以被商人自己修改 ShopRef.m_IsDyShop = TRUE; //启动计时器 if(ShopRef.m_refreshTime >0) m_aRefeshTimer[m_nCurrent].BeginTimer(ShopRef.m_refreshTime, g_pTimeManager->CurrentTime()); return m_nCurrent++; __LEAVE_FUNCTION return -1; } BOOL DynamicShopManager::Tick(UINT uTime) { __ENTER_FUNCTION if(!m_pBoss) return FALSE; Scene* pCurScene = m_pBoss->getScene(); for(INT i = 0; i< m_nCurrent; i++) { if(m_Shops[i].m_refreshTime <= 0) continue; if(m_aRefeshTimer[i].CountingTimer(uTime)) {//refresh INT k = 0; //GCShopUpdateMerchandiseList::_MERCHANDISE_ITEM MerchandiseList[MAX_BOOTH_NUMBER]; for (INT j = 0; j<m_Shops[i].m_ItemList->m_ListCount;j++) {//用静态表中的数据刷新动态表的数据 INT& LocalMaxNum = m_Shops[i].m_ItemList->m_TypeMaxNum[j] ; INT& GlobleMaxNum = g_pStaticShopManager->GetShopByID(m_Shops[i].m_ShopId)->m_ItemList->m_TypeMaxNum[j]; if(LocalMaxNum != GlobleMaxNum) {//改变了,填充消息 LocalMaxNum = GlobleMaxNum; } } } } return TRUE; __LEAVE_FUNCTION return FALSE; }
30.895631
123
0.565402
viticm
c039922f3b8e5630daba7a67276d8ff31fab39ec
1,352
cpp
C++
algorithms/test/cliptest.cpp
VITObelgium/geodynamix
6d3323bc4cae1b85e26afdceab2ecf3686b11369
[ "MIT" ]
null
null
null
algorithms/test/cliptest.cpp
VITObelgium/geodynamix
6d3323bc4cae1b85e26afdceab2ecf3686b11369
[ "MIT" ]
null
null
null
algorithms/test/cliptest.cpp
VITObelgium/geodynamix
6d3323bc4cae1b85e26afdceab2ecf3686b11369
[ "MIT" ]
1
2021-06-16T11:55:27.000Z
2021-06-16T11:55:27.000Z
#include "gdx/test/testbase.h" #include "gdx/algo/clip.h" #include "infra/crs.h" namespace gdx::test { TEST_CASE_TEMPLATE("Clip raster", TypeParam, UnspecializedRasterTypes) { RasterMetadata meta(4, 4, -1.0); meta.xll = 0.0; meta.yll = 0.0; meta.set_cell_size(100.0); meta.set_projection_from_epsg(inf::crs::epsg::BelgianLambert72); SUBCASE("clip edges") { using FloatRaster = typename TypeParam::template type<float>; FloatRaster raster(meta, std::vector<float>{ -1.f, 1.0f, 2.0f, 3.0f, 4.f, 5.f, 6.0f, 7.0f, 8.f, 9.f, -1.0f, 11.0f, 12.f, 13.f, 14.f, -1.f}); FloatRaster expected(meta, std::vector<float>{ -1.f, -1.f, -1.f, -1.f, -1.f, 5.f, 6.0f, -1.f, -1.f, 9.f, -1.0f, -1.f, -1.f, -1.f, -1.f, -1.f}); std::vector<inf::Coordinate> polygon = {{ {100, 100}, {100, 300}, {300, 300}, {300, 100}, }}; clip_raster(raster, polygon, inf::crs::epsg::BelgianLambert72); CHECK_RASTER_EQ(expected, raster); } } }
30.044444
71
0.441568
VITObelgium
c03b51368a29e784eef2038438553dab83757424
900
cpp
C++
CodeBlocks/URI/URI1094.cpp
ash1247/DocumentsWindows
66f65b5170a1ba766cfae08b7104b63ab87331c2
[ "MIT" ]
null
null
null
CodeBlocks/URI/URI1094.cpp
ash1247/DocumentsWindows
66f65b5170a1ba766cfae08b7104b63ab87331c2
[ "MIT" ]
null
null
null
CodeBlocks/URI/URI1094.cpp
ash1247/DocumentsWindows
66f65b5170a1ba766cfae08b7104b63ab87331c2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(void) { int n, num, i; char c; float coe = 0, rat = 0, sap = 0; float total; float coep, ratp, sapp; scanf("%d", &n); for( i = 1; i <= n; i++) { scanf("%d %c", &num, &c); if(c == 'C') coe += num; else if(c == 'R') rat += num; else if(c == 'S') sap += num; } total = coe + rat + sap; coep = ((coe/total)*100); ratp = ((rat/total)*100); sapp = ((sap/total)*100); printf("Total: %d cobaias\n", (int)total); printf("Total de coelhos: %d\n", (int)coe); printf("Total de ratos: %d\n", (int)rat ); printf("Total de sapos: %d\n", (int)sap); printf("Percentual de coelhos: %.2f %%\n", coep); printf("Percentual de ratos: %.2f %%\n", ratp ); printf("Percentual de sapos: %.2f %%\n", sapp); }
18.75
53
0.471111
ash1247
c03b84d96db82330e88df5bf03b630d63cc6b428
3,736
cpp
C++
SPARKS/BaseSpark/parseConnections.cpp
adele-robots/fiona
1ef1fb18e620e18b2187e79e4cca31d66d3f1fd2
[ "MIT" ]
null
null
null
SPARKS/BaseSpark/parseConnections.cpp
adele-robots/fiona
1ef1fb18e620e18b2187e79e4cca31d66d3f1fd2
[ "MIT" ]
null
null
null
SPARKS/BaseSpark/parseConnections.cpp
adele-robots/fiona
1ef1fb18e620e18b2187e79e4cca31d66d3f1fd2
[ "MIT" ]
null
null
null
#include "stdAfx.h" #include "Logger.h" #include "ErrorHandling.h" #include "fileops.h" #include "ComponentSystem.h" using namespace std; void ComponentSystem::readComponentConnections() { pugi::xpath_node_set::const_iterator it; map<FriendlyNameType, OriginalNameType>::iterator iter; // Read <connect> elements pugi::xpath_node_set connectionsNodeSet; connectionsNodeSet = xmlParser.xpathQuery( "/ComponentNetwork/ApplicationDescription/InterfaceConnections/Connect" ); for ( it = connectionsNodeSet.begin(); it != connectionsNodeSet.end(); ++it ) { string interfaceToBeConnected; string xmlInterface = it->node().attribute("interface").value(); //Here we change the possible interface's friendly name into the real name iter = interfacesConversion.find(xmlInterface); if (iter != interfacesConversion.end()) { interfaceToBeConnected = iter->second; }else{ interfaceToBeConnected = xmlInterface; } /*interfaceImplementationsRepository.addInterfaceImplementor( (char *)it->node().attribute("requiredBy").value(), (char *)it->node().attribute("interface").value(), (char *)it->node().attribute("providedBy").value() );*/ interfaceImplementationsRepository.addInterfaceImplementor( (char *)it->node().attribute("requiredBy").value(), (char *)interfaceToBeConnected.c_str(), (char *)it->node().attribute("providedBy").value() ); } // Read <ConnectAll> elements pugi::xpath_node_set connectAllNodeSet; connectAllNodeSet = xmlParser.xpathQuery( "/ComponentNetwork/ApplicationDescription/InterfaceConnections/ConnectAll" ); // Loop through ConnectAll elements for ( it = connectAllNodeSet.begin(); it != connectAllNodeSet.end(); ++it ) { string interfaceToBeConnected; string xmlInterface = it->node().attribute("interface").value(); //Here we change the possible interface's friendly name into the real name iter = interfacesConversion.find(xmlInterface); if (iter != interfacesConversion.end()) { interfaceToBeConnected = iter->second; }else{ interfaceToBeConnected = xmlInterface; } //const char *interfaceName = it->node().attribute("interface").value(); const char *providingInstance = it->node().attribute("providedBy").value(); LoggerInfo( "ConnectAll components requesting %s to implementation provided by instance %s", interfaceToBeConnected.c_str(), providingInstance ); // Loop through all instantiated components. for ( int idx = 0; idx < interfaceImplementationsRepository.instances.componentInstances.size(); idx++ ) { // Loop through all required interfaces of the components vector<string> requiredInterfaces; requiredInterfaces = interfaceImplementationsRepository. instances. componentInstances[idx]. second-> componentDescription-> requiredInterfaces; for (int i = 0; i < requiredInterfaces.size(); i++) { if (!strcmp( interfaceToBeConnected.c_str(), requiredInterfaces[i].c_str() ) ) { LoggerInfo( "Connect all: instance %s implements " "interface %s required by instance %s", (char *)providingInstance, interfaceToBeConnected.c_str(), (char *)interfaceImplementationsRepository.instances.componentInstances[idx].first.c_str() ); interfaceImplementationsRepository.addInterfaceImplementor( (char *)interfaceImplementationsRepository.instances.componentInstances[idx].first.c_str(), (char *)interfaceToBeConnected.c_str(), (char *)providingInstance ); } } } } }
28.090226
98
0.685225
adele-robots
c03ce31bcc8fca0e8274570ee87e85ea92d6b6ac
928
cpp
C++
algorithms_and_data_structures/term_1/lab_2/h.cpp
RevealMind/itmo
fc076d385fd46c50056cfb72d1990e10a1369f2b
[ "MIT" ]
2
2020-07-15T10:42:55.000Z
2020-07-20T08:40:56.000Z
algorithms_and_data_structures/term_1/lab_2/h.cpp
RevealMind/itmo
fc076d385fd46c50056cfb72d1990e10a1369f2b
[ "MIT" ]
9
2021-05-09T02:35:45.000Z
2022-01-22T13:19:03.000Z
algorithms_and_data_structures/term_1/lab_2/h.cpp
RevealMind/itmo
fc076d385fd46c50056cfb72d1990e10a1369f2b
[ "MIT" ]
1
2022-02-18T07:57:31.000Z
2022-02-18T07:57:31.000Z
#include<bits/stdc++.h> int main() { freopen("saloon.in","r", stdin); freopen("saloon.out","w", stdout); int n, h, m ,k, time, x; scanf("%d", &n); std :: deque <int> arr; int person = 0, j = 0; for(int i = 0; i < n; i++) { scanf("%d %d %d", &h, &m, &k); time = h * 60 + m; while(person != 0 && arr[j] <= time) { person--; j++; } if(person == 0) { arr.push_back(time + 20); person++; printf("%d %d\n", (time + 20)/60, (time + 20)%60); continue; } if(person <= k) { x = arr[j] + person * 20; arr.push_back(x); person++; printf("%d %d\n", x/60, x%60); continue; } else { printf("%d %d\n", time/60, time%60); continue; } } }
21.090909
62
0.357759
RevealMind
c0427b84b96afa295bc240695a26b27fd39ea4c2
3,501
cpp
C++
src/ParticleController.cpp
CS126SP20/final-project-meghasg2
aad841877542c0fc6e51a1deeed55b8b96881844
[ "MIT" ]
null
null
null
src/ParticleController.cpp
CS126SP20/final-project-meghasg2
aad841877542c0fc6e51a1deeed55b8b96881844
[ "MIT" ]
null
null
null
src/ParticleController.cpp
CS126SP20/final-project-meghasg2
aad841877542c0fc6e51a1deeed55b8b96881844
[ "MIT" ]
null
null
null
// // Created by Megha Ganesh on 4/24/20. // #include "ParticleController.h" #include "Conversions.h" #include "Globals.h" #include "cinder/Vector.h" namespace particles { ParticleController::ParticleController() {} b2World* ParticleController::setup(b2World &w) { world_ = &w; return world_; } void ParticleController::draw() { for (auto & particle : particles_) { particle.draw(); } } void ParticleController::update() { for (auto & particle : particles_) { particle.update(); } } void ParticleController::AddParticle(const cinder::ivec2 &mouse_pos) { Particle p = Particle(); // Define a body b2BodyDef body_def; body_def.type = b2_staticBody; // Set the position to that of the mouse body_def.position.Set(Conversions::ToPhysics(mouse_pos.x), Conversions::ToPhysics(mouse_pos.y)); // b2Body will be referenced to its corresponding particle instead of just // creating a new body body_def.userData = &p; // Use the world to create the body p.body_ = world_->CreateBody(&body_def); // Define the fixture b2PolygonShape static_box; // Box is 0.5f x 0.5f static_box.SetAsBox(Conversions::ToPhysics(global::BOX_SIZE_X), Conversions::ToPhysics(global::BOX_SIZE_Y)); b2FixtureDef fixture_def; fixture_def.shape = &static_box; fixture_def.density = global::DENSITY; fixture_def.friction = global::FRICTION; // Restitution = bounce fixture_def.restitution = global::RESTITUTION; // Create the fixture with density, friction, and bounce p.body_->CreateFixture(&fixture_def); // Particle can do the rest of the initialization on its own p.setup(cinder::vec2(global::BOX_SIZE_X, global::BOX_SIZE_Y)); // Add Particle to list of Particles particles_.push_back(p); } void ParticleController::RemoveAll() { for (auto & particle : particles_) { world_->DestroyBody(particle.body_); } particles_.clear(); // Change color of particles if (global::COLOR_SCHEME == 0 || global::COLOR_SCHEME == 1) { global::COLOR_SCHEME++; } else if (global::COLOR_SCHEME == 2) { global::COLOR_SCHEME = 0; } } b2BodyType ParticleController::SwitchBodyType() { for (auto & particle : particles_) { // Set body type to dynamic instead of static particle.body_->SetType(b2_dynamicBody); b2PolygonShape dynamic_box; // +3 is to account for the body size increasing/decreasing dynamic_box.SetAsBox( Conversions::ToPhysics(global::BOX_SIZE_X + kSizeDifference), Conversions::ToPhysics(global::BOX_SIZE_Y + kSizeDifference)); b2FixtureDef fixture_def; fixture_def.shape = &dynamic_box; fixture_def.density = global::DENSITY; fixture_def.friction = global::FRICTION; // Restitution = bounce fixture_def.restitution = global::RESTITUTION; // Create the fixture with density, friction, and bounce particle.body_->CreateFixture(&fixture_def); } return particles_.begin()->body_->GetType(); } cinder::vec2 ParticleController::IncreaseBodySize() { cinder::vec2 size = cinder::vec2(global::BOX_SIZE_X + kSizeDifference, global::BOX_SIZE_X + kSizeDifference); for (auto & particle : particles_) { particle.resize(size); } return size; } cinder::vec2 ParticleController::DecreaseBodySize() { cinder::vec2 size = cinder::vec2(global::BOX_SIZE_X - kSizeDifference, global::BOX_SIZE_X - kSizeDifference); for (auto & particle : particles_) { particle.resize(size); } return size; } }
30.710526
76
0.70437
CS126SP20
c046b6841626e2b941fbf2760904cc546fdfbb67
67,167
cc
C++
xls/codegen/combinational_generator_test.cc
AdrianaDJ/xls
c6672aec22a13a5761a8cd29968bf317177b95b7
[ "Apache-2.0" ]
null
null
null
xls/codegen/combinational_generator_test.cc
AdrianaDJ/xls
c6672aec22a13a5761a8cd29968bf317177b95b7
[ "Apache-2.0" ]
null
null
null
xls/codegen/combinational_generator_test.cc
AdrianaDJ/xls
c6672aec22a13a5761a8cd29968bf317177b95b7
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The XLS Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "xls/codegen/combinational_generator.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/statusor.h" #include "xls/common/status/matchers.h" #include "xls/examples/sample_packages.h" #include "xls/interpreter/ir_interpreter.h" #include "xls/ir/function_builder.h" #include "xls/ir/ir_parser.h" #include "xls/ir/package.h" #include "xls/ir/value_helpers.h" #include "xls/simulation/module_simulator.h" #include "xls/simulation/verilog_simulators.h" #include "xls/simulation/verilog_test_base.h" namespace xls { namespace verilog { namespace { using status_testing::IsOkAndHolds; constexpr char kTestName[] = "combinational_generator_test"; constexpr char kTestdataPath[] = "xls/codegen/testdata"; class CombinationalGeneratorTest : public VerilogTestBase {}; TEST_P(CombinationalGeneratorTest, RrotToCombinationalText) { auto rrot32_data = sample_packages::BuildRrot32(); Function* f = rrot32_data.second; XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT(simulator.RunAndReturnSingleOutput( {{"x", UBits(0x12345678ULL, 32)}, {"y", UBits(4, 32)}}), IsOkAndHolds(UBits(0x81234567, 32))); } TEST_P(CombinationalGeneratorTest, RandomExpression) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); auto a = fb.Param("a", u8); auto b = fb.Param("b", u8); auto c = fb.Param("c", u8); auto a_minus_b = fb.Subtract(a, b, /*loc=*/absl::nullopt, /*name=*/"diff"); auto lhs = (a_minus_b * a_minus_b); auto rhs = (c * a_minus_b); auto out = fb.Add(lhs, rhs, /*loc=*/absl::nullopt, /*name=*/"the_output"); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(out)); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); // Value should be: (7-2)*(7-2) + 3*(7-2) = 40 EXPECT_THAT(simulator.RunAndReturnSingleOutput( {{"a", UBits(7, 8)}, {"b", UBits(2, 8)}, {"c", UBits(3, 8)}}), IsOkAndHolds(UBits(40, 8))); } TEST_P(CombinationalGeneratorTest, ReturnsLiteral) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); fb.Literal(UBits(123, 8)); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build()); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT(simulator.RunAndReturnSingleOutput(ModuleSimulator::BitsMap()), IsOkAndHolds(UBits(123, 8))); } TEST_P(CombinationalGeneratorTest, ReturnsTupleLiteral) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); fb.Literal(Value::Tuple({Value(UBits(123, 8)), Value(UBits(42, 32))})); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build()); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT( simulator.Run(absl::flat_hash_map<std::string, Value>()), IsOkAndHolds(Value::Tuple({Value(UBits(123, 8)), Value(UBits(42, 32))}))); } TEST_P(CombinationalGeneratorTest, ReturnsEmptyTuple) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); fb.Literal(Value::Tuple({})); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build()); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT(simulator.Run(absl::flat_hash_map<std::string, Value>()), IsOkAndHolds(Value::Tuple({}))); } TEST_P(CombinationalGeneratorTest, PassesEmptyTuple) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); fb.Param("x", package.GetTupleType({})); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build()); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT(simulator.Run({{"x", Value::Tuple({})}}), IsOkAndHolds(Value::Tuple({}))); } TEST_P(CombinationalGeneratorTest, TakesEmptyTuple) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); auto a = fb.Param("a", u8); fb.Param("b", package.GetTupleType({})); auto c = fb.Param("c", u8); fb.Add(a, c, /*loc=*/absl::nullopt, /*name=*/"sum"); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build()); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT(simulator.Run({{"a", Value(UBits(42, 8))}, {"b", Value::Tuple({})}, {"c", Value(UBits(100, 8))}}), IsOkAndHolds(Value(UBits(142, 8)))); } TEST_P(CombinationalGeneratorTest, ReturnsParam) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); fb.Param("a", u8); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build()); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT(simulator.RunAndReturnSingleOutput({{"a", UBits(0x42, 8)}}), IsOkAndHolds(UBits(0x42, 8))); } TEST_P(CombinationalGeneratorTest, ExpressionWhichRequiresNamedIntermediate) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); auto a = fb.Param("a", u8); auto b = fb.Param("b", u8); auto a_plus_b = a + b; auto out = fb.BitSlice(a_plus_b, /*start=*/3, /*width=*/4, /*loc=*/absl::nullopt, /*name=*/"slice_n_dice"); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(out)); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT(simulator.RunAndReturnSingleOutput( {{"a", UBits(0x42, 8)}, {"b", UBits(0x33, 8)}}), IsOkAndHolds(UBits(14, 4))); } TEST_P(CombinationalGeneratorTest, ExpressionsOfTuples) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); Type* u10 = package.GetBitsType(10); Type* u16 = package.GetBitsType(16); Type* tuple_u10_u16 = package.GetTupleType({u10, u16}); auto a = fb.Param("a", u8); auto b = fb.Param("b", u10); auto c = fb.Param("c", tuple_u10_u16); // Glom all the inputs together into a big tuple. auto a_b_c = fb.Tuple({a, b, c}, /*loc=*/absl::nullopt, /*name=*/"big_tuple"); // Then extract some elements and perform some arithmetic operations on them // after zero-extending them to the same width (16-bits). auto a_plus_b = fb.ZeroExtend(fb.TupleIndex(a_b_c, 0), 16) + fb.ZeroExtend(fb.TupleIndex(a_b_c, 1), 16); auto c_tmp = fb.TupleIndex(a_b_c, 2); auto c0_minus_c1 = fb.ZeroExtend(fb.TupleIndex(c_tmp, 0), 16) - fb.TupleIndex(c_tmp, 1); // Result should be a two-tuple containing {a + b, c[0] - c[1]} auto return_value = fb.Tuple({a_plus_b, c0_minus_c1}); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(return_value)); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT(simulator.Run({{"a", Value(UBits(42, 8))}, {"b", Value(UBits(123, 10))}, {"c", Value::Tuple({Value(UBits(333, 10)), Value(UBits(222, 16))})}}), IsOkAndHolds(Value::Tuple( {Value(UBits(165, 16)), Value(UBits(111, 16))}))); } TEST_P(CombinationalGeneratorTest, TupleLiterals) { std::string text = R"( package TupleLiterals fn main(x: bits[123]) -> bits[123] { literal.1: (bits[123], bits[123], bits[123]) = literal(value=(0x10000, 0x2000, 0x300)) tuple_index.2: bits[123] = tuple_index(literal.1, index=0) tuple_index.3: bits[123] = tuple_index(literal.1, index=1) tuple_index.4: bits[123] = tuple_index(literal.1, index=2) sum1: bits[123] = add(tuple_index.2, tuple_index.3) sum2: bits[123] = add(tuple_index.4, x) ret total: bits[123] = add(sum1, sum2) } )"; XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package, Parser::ParsePackage(text)); XLS_ASSERT_OK_AND_ASSIGN(Function * entry, package->EntryFunction()); XLS_ASSERT_OK_AND_ASSIGN( auto result, GenerateCombinationalModule(entry, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT(simulator.Run({{"x", Value(UBits(0x40, 123))}}), IsOkAndHolds(Value(UBits(0x12340, 123)))); } TEST_P(CombinationalGeneratorTest, ArrayLiteral) { std::string text = R"( package ArrayLiterals fn main(x: bits[32], y: bits[32]) -> bits[44] { literal.1: bits[44][3][2] = literal(value=[[1, 2, 3], [4, 5, 6]]) array_index.2: bits[44][3] = array_index(literal.1, indices=[x]) ret result: bits[44] = array_index(array_index.2, indices=[y]) } )"; XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package, Parser::ParsePackage(text)); XLS_ASSERT_OK_AND_ASSIGN(Function * entry, package->EntryFunction()); XLS_ASSERT_OK_AND_ASSIGN( auto result, GenerateCombinationalModule(entry, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT( simulator.Run({{"x", Value(UBits(0, 32))}, {"y", Value(UBits(1, 32))}}), IsOkAndHolds(Value(UBits(2, 44)))); EXPECT_THAT( simulator.Run({{"x", Value(UBits(1, 32))}, {"y", Value(UBits(0, 32))}}), IsOkAndHolds(Value(UBits(4, 44)))); } TEST_P(CombinationalGeneratorTest, OneHot) { std::string text = R"( package OneHot fn main(x: bits[3]) -> bits[4] { ret one_hot.1: bits[4] = one_hot(x, lsb_prio=true) } )"; XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package, Parser::ParsePackage(text)); XLS_ASSERT_OK_AND_ASSIGN(Function * entry, package->EntryFunction()); XLS_ASSERT_OK_AND_ASSIGN( auto result, GenerateCombinationalModule(entry, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT(simulator.Run({{"x", Value(UBits(0b000, 3))}}), IsOkAndHolds(Value(UBits(0b1000, 4)))); EXPECT_THAT(simulator.Run({{"x", Value(UBits(0b001, 3))}}), IsOkAndHolds(Value(UBits(0b0001, 4)))); EXPECT_THAT(simulator.Run({{"x", Value(UBits(0b010, 3))}}), IsOkAndHolds(Value(UBits(0b0010, 4)))); EXPECT_THAT(simulator.Run({{"x", Value(UBits(0b011, 3))}}), IsOkAndHolds(Value(UBits(0b0001, 4)))); EXPECT_THAT(simulator.Run({{"x", Value(UBits(0b100, 3))}}), IsOkAndHolds(Value(UBits(0b0100, 4)))); EXPECT_THAT(simulator.Run({{"x", Value(UBits(0b101, 3))}}), IsOkAndHolds(Value(UBits(0b0001, 4)))); EXPECT_THAT(simulator.Run({{"x", Value(UBits(0b110, 3))}}), IsOkAndHolds(Value(UBits(0b0010, 4)))); EXPECT_THAT(simulator.Run({{"x", Value(UBits(0b111, 3))}}), IsOkAndHolds(Value(UBits(0b0001, 4)))); } TEST_P(CombinationalGeneratorTest, OneHotSelect) { std::string text = R"( package OneHotSelect fn main(p: bits[2], x: bits[16], y: bits[16]) -> bits[16] { ret one_hot_sel.1: bits[16] = one_hot_sel(p, cases=[x, y]) } )"; XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package, Parser::ParsePackage(text)); XLS_ASSERT_OK_AND_ASSIGN(Function * entry, package->EntryFunction()); XLS_ASSERT_OK_AND_ASSIGN( auto result, GenerateCombinationalModule(entry, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); absl::flat_hash_map<std::string, Value> args = { {"x", Value(UBits(0x00ff, 16))}, {"y", Value(UBits(0xf0f0, 16))}}; args["p"] = Value(UBits(0b00, 2)); EXPECT_THAT(simulator.Run(args), IsOkAndHolds(Value(UBits(0x0000, 16)))); args["p"] = Value(UBits(0b01, 2)); EXPECT_THAT(simulator.Run(args), IsOkAndHolds(Value(UBits(0x00ff, 16)))); args["p"] = Value(UBits(0b10, 2)); EXPECT_THAT(simulator.Run(args), IsOkAndHolds(Value(UBits(0xf0f0, 16)))); args["p"] = Value(UBits(0b11, 2)); EXPECT_THAT(simulator.Run(args), IsOkAndHolds(Value(UBits(0xf0ff, 16)))); } TEST_P(CombinationalGeneratorTest, CrazyParameterTypes) { std::string text = R"( package CrazyParameterTypes fn main(a: bits[32], b: (bits[32], ()), c: bits[32][3], d: (bits[32], bits[32])[1], e: (bits[32][2], (), ()), f: bits[0], g: bits[1]) -> bits[32] { tuple_index.1: bits[32] = tuple_index(b, index=0) literal.2: bits[32] = literal(value=0) array_index.3: bits[32] = array_index(c, indices=[g]) array_index.4: (bits[32], bits[32]) = array_index(d, indices=[literal.2]) tuple_index.5: bits[32] = tuple_index(array_index.4, index=1) tuple_index.6: bits[32][2] = tuple_index(e, index=0) array_index.7: bits[32] = array_index(tuple_index.6, indices=[g]) ret or.8: bits[32] = or(a, tuple_index.1, array_index.3, tuple_index.5, array_index.7) } )"; XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package, Parser::ParsePackage(text)); XLS_ASSERT_OK_AND_ASSIGN(Function * entry, package->EntryFunction()); XLS_ASSERT_OK_AND_ASSIGN( auto result, GenerateCombinationalModule(entry, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); std::minstd_rand engine; std::vector<Value> arguments = RandomFunctionArguments(entry, &engine); XLS_ASSERT_OK_AND_ASSIGN(Value expected, IrInterpreter::Run(entry, arguments)); EXPECT_THAT(simulator.Run(arguments), IsOkAndHolds(expected)); } TEST_P(CombinationalGeneratorTest, TwoDArray) { // Build up a two dimensional array from scalars, then deconstruct it and do // something with the elements. Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); auto a = fb.Param("a", u8); auto b = fb.Param("b", u8); auto c = fb.Param("c", u8); auto row_0 = fb.Array({a, b, c}, a.GetType()); auto row_1 = fb.Array({a, b, c}, a.GetType()); auto two_d = fb.Array({row_0, row_1}, row_0.GetType()); fb.Add(fb.ArrayIndex(fb.ArrayIndex(two_d, {fb.Literal(UBits(0, 8))}), {fb.Literal(UBits(2, 8))}), fb.ArrayIndex(fb.ArrayIndex(two_d, {fb.Literal(UBits(1, 8))}), {fb.Literal(UBits(1, 8))})); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build()); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT(simulator.Run({{"a", Value(UBits(123, 8))}, {"b", Value(UBits(42, 8))}, {"c", Value(UBits(100, 8))}}), IsOkAndHolds(Value(UBits(142, 8)))); } TEST_P(CombinationalGeneratorTest, ReturnTwoDArray) { // Build up a two dimensional array from scalars and return it. Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); auto a = fb.Param("a", u8); auto b = fb.Param("b", u8); auto row_0 = fb.Array({a, b}, a.GetType()); auto row_1 = fb.Array({b, a}, a.GetType()); fb.Array({row_0, row_1}, row_0.GetType()); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build()); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT( simulator.Run({{"a", Value(UBits(123, 8))}, {"b", Value(UBits(42, 8))}}), IsOkAndHolds(Value::ArrayOrDie({ Value::ArrayOrDie({Value(UBits(123, 8)), Value(UBits(42, 8))}), Value::ArrayOrDie({Value(UBits(42, 8)), Value(UBits(123, 8))}), }))); } TEST_P(CombinationalGeneratorTest, ArrayUpdateBitElements) { std::string text = R"( package ArrayUpdate fn main(idx: bits[2]) -> bits[32][3] { literal.5: bits[32][3] = literal(value=[1, 2, 3]) literal.6: bits[32] = literal(value=99) ret updated_array: bits[32][3] = array_update(literal.5, literal.6, indices=[idx]) } )"; XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package, Parser::ParsePackage(text)); XLS_ASSERT_OK_AND_ASSIGN(Function * entry, package->EntryFunction()); XLS_ASSERT_OK_AND_ASSIGN( auto result, GenerateCombinationalModule(entry, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); auto make_array = [](absl::Span<const int64> values) { std::vector<Value> elements; for (auto v : values) { elements.push_back(Value(UBits(v, 32))); } absl::StatusOr<Value> array = Value::Array(elements); EXPECT_TRUE(array.ok()); return array.value(); }; EXPECT_THAT(simulator.Run({{"idx", Value(UBits(0b00, 2))}}), IsOkAndHolds(make_array({99, 2, 3}))); EXPECT_THAT(simulator.Run({{"idx", Value(UBits(0b01, 2))}}), IsOkAndHolds(make_array({1, 99, 3}))); EXPECT_THAT(simulator.Run({{"idx", Value(UBits(0b10, 2))}}), IsOkAndHolds(make_array({1, 2, 99}))); EXPECT_THAT(simulator.Run({{"idx", Value(UBits(0b11, 2))}}), IsOkAndHolds(make_array({1, 2, 3}))); } TEST_P(CombinationalGeneratorTest, ArrayUpdateArrayElements) { std::string text = R"( package ArrayUpdate fn main(idx: bits[2]) -> bits[32][2][3] { literal.17: bits[32][2][3] = literal(value=[[1, 2], [3, 4], [5, 6]]) literal.14: bits[32][2] = literal(value=[98, 99]) ret updated_array: bits[32][2][3] = array_update(literal.17, literal.14, indices=[idx]) } )"; XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package, Parser::ParsePackage(text)); XLS_ASSERT_OK_AND_ASSIGN(Function * entry, package->EntryFunction()); XLS_ASSERT_OK_AND_ASSIGN( auto result, GenerateCombinationalModule(entry, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); auto make_array = [](absl::Span<const int64> values) { std::vector<Value> elements; for (auto v : values) { elements.push_back(Value(UBits(v, 32))); } absl::StatusOr<Value> array = Value::Array(elements); EXPECT_TRUE(array.ok()); return array.value(); }; auto make_array_of_values = [&](absl::Span<const Value> values) { std::vector<Value> elements; for (auto array : values) { elements.push_back(array); } absl::StatusOr<Value> array_of_values = Value::Array(elements); EXPECT_TRUE(array_of_values.ok()); return array_of_values.value(); }; EXPECT_THAT( simulator.Run({{"idx", Value(UBits(0b00, 2))}}), IsOkAndHolds(make_array_of_values( {make_array({98, 99}), make_array({3, 4}), make_array({5, 6})}))); EXPECT_THAT( simulator.Run({{"idx", Value(UBits(0b01, 2))}}), IsOkAndHolds(make_array_of_values( {make_array({1, 2}), make_array({98, 99}), make_array({5, 6})}))); EXPECT_THAT( simulator.Run({{"idx", Value(UBits(0b10, 2))}}), IsOkAndHolds(make_array_of_values( {make_array({1, 2}), make_array({3, 4}), make_array({98, 99})}))); EXPECT_THAT( simulator.Run({{"idx", Value(UBits(0b11, 2))}}), IsOkAndHolds(make_array_of_values( {make_array({1, 2}), make_array({3, 4}), make_array({5, 6})}))); } TEST_P(CombinationalGeneratorTest, ArrayUpdateTupleElements) { std::string text = R"( package ArrayUpdate fn main(idx: bits[2]) -> (bits[32], bits[32])[3] { literal.17: (bits[32], bits[32])[3] = literal(value=[(1,2),(3,4),(5,6)]) literal.14: (bits[32], bits[32]) = literal(value=(98, 99)) ret array_update.15: (bits[32], bits[32])[3] = array_update(literal.17, literal.14, indices=[idx]) } )"; XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package, Parser::ParsePackage(text)); XLS_ASSERT_OK_AND_ASSIGN(Function * entry, package->EntryFunction()); XLS_ASSERT_OK_AND_ASSIGN( auto result, GenerateCombinationalModule(entry, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); auto make_tuple = [](absl::Span<const int64> values) { std::vector<Value> elements; for (auto v : values) { elements.push_back(Value(UBits(v, 32))); } absl::StatusOr<Value> tuple = Value::Tuple(elements); EXPECT_TRUE(tuple.ok()); return tuple.value(); }; auto make_array_of_values = [&](absl::Span<const Value> values) { std::vector<Value> elements; for (auto array : values) { elements.push_back(array); } absl::StatusOr<Value> array_of_values = Value::Array(elements); EXPECT_TRUE(array_of_values.ok()); return array_of_values.value(); }; EXPECT_THAT( simulator.Run({{"idx", Value(UBits(0b00, 2))}}), IsOkAndHolds(make_array_of_values( {make_tuple({98, 99}), make_tuple({3, 4}), make_tuple({5, 6})}))); EXPECT_THAT( simulator.Run({{"idx", Value(UBits(0b01, 2))}}), IsOkAndHolds(make_array_of_values( {make_tuple({1, 2}), make_tuple({98, 99}), make_tuple({5, 6})}))); EXPECT_THAT( simulator.Run({{"idx", Value(UBits(0b10, 2))}}), IsOkAndHolds(make_array_of_values( {make_tuple({1, 2}), make_tuple({3, 4}), make_tuple({98, 99})}))); EXPECT_THAT( simulator.Run({{"idx", Value(UBits(0b11, 2))}}), IsOkAndHolds(make_array_of_values( {make_tuple({1, 2}), make_tuple({3, 4}), make_tuple({5, 6})}))); } TEST_P(CombinationalGeneratorTest, ArrayUpdateTupleWithArrayElements) { std::string text = R"( package ArrayUpdate fn main(idx: bits[2]) -> (bits[32], bits[8][2])[2] { literal.17: (bits[32], bits[8][2])[2] = literal(value=[(1,[2,3]),(4,[5,6])]) literal.14: (bits[32], bits[8][2]) = literal(value=(98, [99, 100])) ret array_update.15: (bits[32], bits[8][2])[2] = array_update(literal.17, literal.14, indices=[idx]) } )"; XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package, Parser::ParsePackage(text)); XLS_ASSERT_OK_AND_ASSIGN(Function * entry, package->EntryFunction()); XLS_ASSERT_OK_AND_ASSIGN( auto result, GenerateCombinationalModule(entry, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); auto make_array = [](absl::Span<const int64> values) { std::vector<Value> elements; for (auto v : values) { elements.push_back(Value(UBits(v, 8))); } absl::StatusOr<Value> array = Value::Array(elements); EXPECT_TRUE(array.ok()); return array.value(); }; auto make_tuple = [](absl::Span<const Value> values) { std::vector<Value> elements; for (auto v : values) { elements.push_back(v); } absl::StatusOr<Value> tuple = Value::Tuple(elements); EXPECT_TRUE(tuple.ok()); return tuple.value(); }; auto make_array_of_values = [&](absl::Span<const Value> values) { std::vector<Value> elements; for (auto array : values) { elements.push_back(array); } absl::StatusOr<Value> array_of_values = Value::Array(elements); EXPECT_TRUE(array_of_values.ok()); return array_of_values.value(); }; EXPECT_THAT( simulator.Run({{"idx", Value(UBits(0b01, 2))}}), IsOkAndHolds(make_array_of_values( {make_tuple({Value(UBits(1, 32)), make_array({2, 3})}), make_tuple({Value(UBits(98, 32)), make_array({99, 100})})}))); } TEST_P(CombinationalGeneratorTest, BuildComplicatedType) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); // Construct some terrible abomination of tuples and arrays. auto a = fb.Param("a", u8); auto b = fb.Param("b", u8); auto c = fb.Param("c", u8); auto row_0 = fb.Array({a, b}, a.GetType()); auto row_1 = fb.Array({b, a}, a.GetType()); auto ar = fb.Array({row_0, row_1}, row_0.GetType()); auto tuple = fb.Tuple({ar, a}); // Deconstruct it and return some scalar element. fb.ArrayIndex(fb.ArrayIndex(fb.TupleIndex(tuple, 0), {a}), {c}); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build()); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT(simulator.Run({{"a", Value(UBits(0, 8))}, {"b", Value(UBits(42, 8))}, {"c", Value(UBits(1, 8))}}), IsOkAndHolds(Value(UBits(42, 8)))); } TEST_P(CombinationalGeneratorTest, ArrayShapedSel) { VerilogFile file; Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); BValue p = fb.Param("p", package.GetBitsType(8)); BValue x = fb.Param("x", package.GetArrayType(3, package.GetBitsType(8))); BValue y = fb.Param("y", package.GetArrayType(3, package.GetBitsType(8))); BValue z = fb.Param("z", package.GetArrayType(3, package.GetBitsType(8))); BValue d = fb.Param("d", package.GetArrayType(3, package.GetBitsType(8))); fb.Select(p, {x, y, z}, /*default_value=*/d); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build()); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); XLS_ASSERT_OK_AND_ASSIGN( Value x_in, Parser::ParseTypedValue("[bits[8]:0xa, bits[8]:0xb, bits[8]:0xc]")); XLS_ASSERT_OK_AND_ASSIGN( Value y_in, Parser::ParseTypedValue("[bits[8]:0x1, bits[8]:0x2, bits[8]:0x3]")); XLS_ASSERT_OK_AND_ASSIGN( Value z_in, Parser::ParseTypedValue("[bits[8]:0x4, bits[8]:0x5, bits[8]:0x6]")); XLS_ASSERT_OK_AND_ASSIGN( Value d_in, Parser::ParseTypedValue("[bits[8]:0x7, bits[8]:0x8, bits[8]:0x9]")); EXPECT_THAT(simulator.Run({{"p", Value(UBits(0, 8))}, {"x", x_in}, {"y", y_in}, {"z", z_in}, {"d", d_in}}), IsOkAndHolds(x_in)); EXPECT_THAT(simulator.Run({{"p", Value(UBits(1, 8))}, {"x", x_in}, {"y", y_in}, {"z", z_in}, {"d", d_in}}), IsOkAndHolds(y_in)); EXPECT_THAT(simulator.Run({{"p", Value(UBits(2, 8))}, {"x", x_in}, {"y", y_in}, {"z", z_in}, {"d", d_in}}), IsOkAndHolds(z_in)); EXPECT_THAT(simulator.Run({{"p", Value(UBits(3, 8))}, {"x", x_in}, {"y", y_in}, {"z", z_in}, {"d", d_in}}), IsOkAndHolds(d_in)); EXPECT_THAT(simulator.Run({{"p", Value(UBits(100, 8))}, {"x", x_in}, {"y", y_in}, {"z", z_in}, {"d", d_in}}), IsOkAndHolds(d_in)); } TEST_P(CombinationalGeneratorTest, ArrayShapedSelNoDefault) { VerilogFile file; Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); BValue p = fb.Param("p", package.GetBitsType(1)); BValue x = fb.Param("x", package.GetArrayType(3, package.GetBitsType(8))); BValue y = fb.Param("y", package.GetArrayType(3, package.GetBitsType(8))); fb.Select(p, {x, y}); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.Build()); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); XLS_ASSERT_OK_AND_ASSIGN( Value x_in, Parser::ParseTypedValue("[bits[8]:0xa, bits[8]:0xb, bits[8]:0xc]")); XLS_ASSERT_OK_AND_ASSIGN( Value y_in, Parser::ParseTypedValue("[bits[8]:0x1, bits[8]:0x2, bits[8]:0x3]")); EXPECT_THAT( simulator.Run({{"p", Value(UBits(0, 1))}, {"x", x_in}, {"y", y_in}}), IsOkAndHolds(x_in)); EXPECT_THAT( simulator.Run({{"p", Value(UBits(1, 1))}, {"x", x_in}, {"y", y_in}}), IsOkAndHolds(y_in)); } TEST_P(CombinationalGeneratorTest, ArrayConcatArrayOfBits) { Package package(TestBaseName()); std::string ir_text = R"( fn f(a0: bits[32][2], a1: bits[32][3]) -> bits[32][7] { array_concat.3: bits[32][5] = array_concat(a0, a1) ret array_concat.4: bits[32][7] = array_concat(array_concat.3, a0) } )"; XLS_ASSERT_OK_AND_ASSIGN(Function * function, Parser::ParseFunction(ir_text, &package)); XLS_ASSERT_OK_AND_ASSIGN( auto result, GenerateCombinationalModule(function, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); XLS_ASSERT_OK_AND_ASSIGN(Value a0, Value::UBitsArray({1, 2}, 32)); XLS_ASSERT_OK_AND_ASSIGN(Value a1, Value::UBitsArray({3, 4, 5}, 32)); XLS_ASSERT_OK_AND_ASSIGN(Value ret, Value::UBitsArray({1, 2, 3, 4, 5, 1, 2}, 32)); EXPECT_THAT(simulator.Run({{"a0", a0}, {"a1", a1}}), IsOkAndHolds(ret)); } TEST_P(CombinationalGeneratorTest, ArrayConcatArrayOfBitsMixedOperands) { Package package(TestBaseName()); std::string ir_text = R"( fn f(a0: bits[32][2], a1: bits[32][3], a2: bits[32][1]) -> bits[32][7] { array_concat.4: bits[32][1] = array_concat(a2) array_concat.5: bits[32][2] = array_concat(array_concat.4, array_concat.4) array_concat.6: bits[32][7] = array_concat(a0, array_concat.5, a1) ret array_concat.7: bits[32][7] = array_concat(array_concat.6) } )"; XLS_ASSERT_OK_AND_ASSIGN(Function * function, Parser::ParseFunction(ir_text, &package)); XLS_ASSERT_OK_AND_ASSIGN( auto result, GenerateCombinationalModule(function, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); XLS_ASSERT_OK_AND_ASSIGN(Value a0, Value::UBitsArray({1, 2}, 32)); XLS_ASSERT_OK_AND_ASSIGN(Value a1, Value::UBitsArray({3, 4, 5}, 32)); XLS_ASSERT_OK_AND_ASSIGN(Value a2, Value::SBitsArray({-1}, 32)); XLS_ASSERT_OK_AND_ASSIGN(Value ret, Value::SBitsArray({1, 2, -1, -1, 3, 4, 5}, 32)); EXPECT_THAT(simulator.Run({{"a0", a0}, {"a1", a1}, {"a2", a2}}), IsOkAndHolds(ret)); } TEST_P(CombinationalGeneratorTest, InterpretArrayConcatArraysOfArrays) { Package package(TestBaseName()); std::string ir_text = R"( fn f() -> bits[32][2][3] { literal.1: bits[32][2][2] = literal(value=[[1, 2], [3, 4]]) literal.2: bits[32][2][1] = literal(value=[[5, 6]]) ret array_concat.3: bits[32][2][3] = array_concat(literal.2, literal.1) } )"; XLS_ASSERT_OK_AND_ASSIGN(Function * function, Parser::ParseFunction(ir_text, &package)); XLS_ASSERT_OK_AND_ASSIGN( auto result, GenerateCombinationalModule(function, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); XLS_ASSERT_OK_AND_ASSIGN(Value ret, Value::SBits2DArray({{5, 6}, {1, 2}, {3, 4}}, 32)); std::vector<Value> args; EXPECT_THAT(simulator.Run(args), IsOkAndHolds(ret)); } TEST_P(CombinationalGeneratorTest, SimpleProc) { const std::string ir_text = R"(package test chan in(my_in: bits[32], id=0, kind=single_value, ops=receive_only, metadata="""module_port { flopped: false, port_order: 1 }""") chan out(my_out: bits[32], id=1, kind=single_value, ops=send_only, metadata="""module_port { flopped: false, port_order: 0 }""") proc my_proc(my_token: token, my_state: (), init=()) { rcv: (token, bits[32]) = receive(my_token, channel_id=0) data: bits[32] = tuple_index(rcv, index=1) negate: bits[32] = neg(data) rcv_token: token = tuple_index(rcv, index=0) send: token = send(rcv_token, data=[negate], channel_id=1) next (send, my_state) } )"; XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package, Parser::ParsePackage(ir_text)); XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, package->GetProc("my_proc")); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModuleFromProc( proc, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT(simulator.RunAndReturnSingleOutput({{"my_in", SBits(10, 32)}}), IsOkAndHolds(SBits(-10, 32))); EXPECT_THAT(simulator.RunAndReturnSingleOutput({{"my_in", SBits(0, 32)}}), IsOkAndHolds(SBits(0, 32))); } TEST_P(CombinationalGeneratorTest, ProcWithMultipleInputChannels) { const std::string ir_text = R"(package test chan in0(my_in0: bits[32], id=0, kind=single_value, ops=receive_only, metadata="""module_port { flopped: false, port_order: 0 }""") chan in1(my_in1: bits[32], id=1, kind=single_value, ops=receive_only, metadata="""module_port { flopped: false, port_order: 2 }""") chan in2(my_in2: bits[32], id=2, kind=single_value, ops=receive_only, metadata="""module_port { flopped: false, port_order: 1 }""") chan out(my_out: bits[32], id=3, kind=single_value, ops=send_only, metadata="""module_port { flopped: false, port_order: 0 }""") proc my_proc(my_token: token, my_state: (), init=()) { rcv0: (token, bits[32]) = receive(my_token, channel_id=0) rcv0_token: token = tuple_index(rcv0, index=0) rcv1: (token, bits[32]) = receive(rcv0_token, channel_id=1) rcv1_token: token = tuple_index(rcv1, index=0) rcv2: (token, bits[32]) = receive(rcv1_token, channel_id=2) rcv2_token: token = tuple_index(rcv2, index=0) data0: bits[32] = tuple_index(rcv0, index=1) data1: bits[32] = tuple_index(rcv1, index=1) data2: bits[32] = tuple_index(rcv2, index=1) neg_data1: bits[32] = neg(data1) two: bits[32] = literal(value=2) data2_times_two: bits[32] = umul(data2, two) tmp: bits[32] = add(neg_data1, data2_times_two) sum: bits[32] = add(tmp, data0) send: token = send(rcv2_token, data=[sum], channel_id=3) next (send, my_state) } )"; XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package, Parser::ParsePackage(ir_text)); XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, package->GetProc("my_proc")); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModuleFromProc( proc, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); // The computed expression is: my_out = my_in0 - my_in1 + 2 * my_in2 EXPECT_THAT(simulator.RunAndReturnSingleOutput({{"my_in0", UBits(10, 32)}, {"my_in1", SBits(7, 32)}, {"my_in2", SBits(42, 32)}}), IsOkAndHolds(UBits(87, 32))); } TEST_P(CombinationalGeneratorTest, ProcWithMultipleOutputChannels) { const std::string ir_text = R"(package test chan in(my_in: bits[32], id=0, kind=single_value, ops=receive_only, metadata="""module_port { flopped: false, port_order: 1 }""") chan out0(my_out0: bits[32], id=1, kind=single_value, ops=send_only, metadata="""module_port { flopped: false, port_order: 0 }""") chan out1(my_out1: bits[32], id=2, kind=single_value, ops=send_only, metadata="""module_port { flopped: false, port_order: 2 }""") proc my_proc(my_token: token, my_state: (), init=()) { rcv: (token, bits[32]) = receive(my_token, channel_id=0) data: bits[32] = tuple_index(rcv, index=1) negate: bits[32] = neg(data) rcv_token: token = tuple_index(rcv, index=0) send0: token = send(rcv_token, data=[data], channel_id=1) send1: token = send(send0, data=[negate], channel_id=2) next (send1, my_state) } )"; XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package, Parser::ParsePackage(ir_text)); XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, package->GetProc("my_proc")); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModuleFromProc( proc, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT(simulator.Run({{"my_in", SBits(10, 32)}}), IsOkAndHolds(ModuleSimulator::BitsMap( {{"my_out0", SBits(10, 32)}, {"my_out1", SBits(-10, 32)}}))); } TEST_P(CombinationalGeneratorTest, NToOneMuxProc) { Package package(TestBaseName()); ProcBuilder pb(TestBaseName(), /*init_value=*/Value::Tuple({}), /*token_name=*/"tkn", /*state_name=*/"st", &package); const int64 kInputCount = 4; const int64 kSelectorBitCount = 2; Type* data_type = package.GetBitsType(32); Type* bit_type = package.GetBitsType(1); Type* selector_type = package.GetBitsType(kSelectorBitCount); int64 port_order = 0; auto make_channel_metadata = [&port_order]() { ChannelMetadataProto metadata; metadata.mutable_module_port()->set_flopped(false); metadata.mutable_module_port()->set_port_order(port_order++); return metadata; }; BValue token = pb.GetTokenParam(); // Sends the given data over the given channel. Threads 'token' through the // Send operation. auto make_send = [&](Channel* ch, BValue data) { BValue send = pb.Send(ch, token, {data}); token = send; return send; }; // Adds a receive instruction and returns the data BValue. Threads 'token' // through the Receive operation. auto make_receive = [&](Channel* ch) { BValue receive = pb.Receive(ch, token); token = pb.TupleIndex(receive, 0); return pb.TupleIndex(receive, 1); }; // Add the selector module port which selects which input to forward. XLS_ASSERT_OK_AND_ASSIGN( Channel * selector_channel, package.CreateSingleValueChannel( "selector", Channel::SupportedOps::kReceiveOnly, {DataElement{.name = "selector", .type = selector_type}}, /*id=*/absl::nullopt, make_channel_metadata())); BValue selector = make_receive(selector_channel); // Add the output ready channel. It's an input and will be used to generate // the input ready outputs. XLS_ASSERT_OK_AND_ASSIGN( Channel * out_ready_channel, package.CreateSingleValueChannel( "out_rdy", Channel::SupportedOps::kReceiveOnly, {DataElement{.name = "out_rdy", .type = bit_type}}, /*id=*/absl::nullopt, make_channel_metadata())); BValue output_ready = make_receive(out_ready_channel); // Generate all the input ports and their ready/valid signals. std::vector<BValue> input_datas; std::vector<BValue> input_valids; for (int64 i = 0; i < kInputCount; ++i) { XLS_ASSERT_OK_AND_ASSIGN( Channel * data_channel, package.CreateSingleValueChannel( absl::StrFormat("in_%d", i), Channel::SupportedOps::kReceiveOnly, {DataElement{.name = absl::StrFormat("in_%d", i), .type = data_type}}, /*id=*/absl::nullopt, make_channel_metadata())); input_datas.push_back(make_receive(data_channel)); XLS_ASSERT_OK_AND_ASSIGN( Channel * valid_channel, package.CreateSingleValueChannel( absl::StrFormat("in_%d_vld", i), Channel::SupportedOps::kReceiveOnly, {DataElement{.name = absl::StrFormat("in_%d_vld", i), .type = bit_type}}, /*id=*/absl::nullopt, make_channel_metadata())); input_valids.push_back(make_receive(valid_channel)); BValue ready = pb.And( output_ready, pb.Eq(selector, pb.Literal(UBits(i, kSelectorBitCount)))); XLS_ASSERT_OK_AND_ASSIGN( Channel * ready_channel, package.CreateSingleValueChannel( absl::StrFormat("in_%d_rdy", i), Channel::SupportedOps::kSendOnly, {DataElement{.name = absl::StrFormat("in_%d_rdy", i), .type = bit_type}}, /*id=*/absl::nullopt, make_channel_metadata())); make_send(ready_channel, ready); } // Output data is a select amongst the input data. XLS_ASSERT_OK_AND_ASSIGN(Channel * out_data_channel, package.CreateSingleValueChannel( "out", Channel::SupportedOps::kSendOnly, {DataElement{.name = "out", .type = data_type}}, /*id=*/absl::nullopt, make_channel_metadata())); make_send(out_data_channel, pb.Select(selector, /*cases=*/input_datas)); // Output valid is a select amongs the input valid signals. XLS_ASSERT_OK_AND_ASSIGN( Channel * out_valid_channel, package.CreateSingleValueChannel( "out_vld", Channel::SupportedOps::kSendOnly, {DataElement{.name = "out_vld", .type = bit_type}}, /*id=*/absl::nullopt, make_channel_metadata())); make_send(out_valid_channel, pb.Select(selector, /*cases=*/input_valids)); XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, pb.Build(token, pb.GetStateParam())); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModuleFromProc( proc, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); } TEST_P(CombinationalGeneratorTest, OneToNMuxProc) { Package package(TestBaseName()); ProcBuilder pb(TestBaseName(), /*init_value=*/Value::Tuple({}), /*token_name=*/"tkn", /*state_name=*/"st", &package); const int64 kOutputCount = 4; const int64 kSelectorBitCount = 2; Type* data_type = package.GetBitsType(32); Type* bit_type = package.GetBitsType(1); Type* selector_type = package.GetBitsType(kSelectorBitCount); int64 port_order = 0; auto make_channel_metadata = [&port_order]() { ChannelMetadataProto metadata; metadata.mutable_module_port()->set_flopped(false); metadata.mutable_module_port()->set_port_order(port_order++); return metadata; }; BValue token = pb.GetTokenParam(); // Sends the given data over the given channel. Threads 'token' through the // Send operation. auto make_send = [&](Channel* ch, BValue data) { BValue send = pb.Send(ch, token, {data}); token = send; return send; }; // Adds a receive instruction and returns the data BValue. Threads 'token' // through the Receive operation. auto make_receive = [&](Channel* ch) { BValue receive = pb.Receive(ch, token); token = pb.TupleIndex(receive, 0); return pb.TupleIndex(receive, 1); }; // Add the selector module port which selects which input to forward. XLS_ASSERT_OK_AND_ASSIGN( Channel * selector_channel, package.CreateSingleValueChannel( "selector", Channel::SupportedOps::kReceiveOnly, {DataElement{.name = "selector", .type = selector_type}}, /*id=*/absl::nullopt, make_channel_metadata())); BValue selector = make_receive(selector_channel); // Add the input data channel. XLS_ASSERT_OK_AND_ASSIGN(Channel * input_data_channel, package.CreateSingleValueChannel( "in", Channel::SupportedOps::kReceiveOnly, {DataElement{.name = "in", .type = data_type}}, /*id=*/absl::nullopt, make_channel_metadata())); BValue input = make_receive(input_data_channel); // Add the input valid channel. It's an input and will be used to generate // the output valid outputs. XLS_ASSERT_OK_AND_ASSIGN( Channel * input_valid_channel, package.CreateSingleValueChannel( "in_vld", Channel::SupportedOps::kReceiveOnly, {DataElement{.name = "in_vld", .type = bit_type}}, /*id=*/absl::nullopt, make_channel_metadata())); BValue input_valid = make_receive(input_valid_channel); // Generate all the output ports and their ready/valid signals. std::vector<BValue> output_readys; for (int64 i = 0; i < kOutputCount; ++i) { XLS_ASSERT_OK_AND_ASSIGN( Channel * data_channel, package.CreateSingleValueChannel( absl::StrFormat("out_%d", i), Channel::SupportedOps::kSendOnly, {DataElement{.name = absl::StrFormat("out_%d", i), .type = data_type}}, /*id=*/absl::nullopt, make_channel_metadata())); make_send(data_channel, input); XLS_ASSERT_OK_AND_ASSIGN( Channel * ready_channel, package.CreateSingleValueChannel( absl::StrFormat("out_%d_rdy", i), Channel::SupportedOps::kReceiveOnly, {DataElement{.name = absl::StrFormat("out_%d_rdy", i), .type = bit_type}}, /*id=*/absl::nullopt, make_channel_metadata())); output_readys.push_back(make_receive(ready_channel)); BValue valid = pb.And( input_valid, pb.Eq(selector, pb.Literal(UBits(i, kSelectorBitCount)))); XLS_ASSERT_OK_AND_ASSIGN( Channel * valid_channel, package.CreateSingleValueChannel( absl::StrFormat("out_%d_vld", i), Channel::SupportedOps::kSendOnly, {DataElement{.name = absl::StrFormat("out_%d_vld", i), .type = bit_type}}, /*id=*/absl::nullopt, make_channel_metadata())); make_send(valid_channel, valid); } // Output ready is a select amongs the input ready signals. XLS_ASSERT_OK_AND_ASSIGN( Channel * input_ready_channel, package.CreateSingleValueChannel( "in_rdy", Channel::SupportedOps::kSendOnly, {DataElement{.name = "in_rdy", .type = bit_type}}, /*id=*/absl::nullopt, make_channel_metadata())); make_send(input_ready_channel, pb.Select(selector, /*cases=*/output_readys)); XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, pb.Build(token, pb.GetStateParam())); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModuleFromProc( proc, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); } TEST_P(CombinationalGeneratorTest, ArrayIndexSimpleArray) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); Type* u16 = package.GetBitsType(16); auto a = fb.Param("a", package.GetArrayType(3, u8)); auto idx = fb.Param("idx", u16); auto ret = fb.ArrayIndex(a, {idx}); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret)); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT(simulator.Run({{"a", Value::UBitsArray({11, 22, 33}, 8).value()}, {"idx", Value(UBits(2, 16))}}), IsOkAndHolds(Value(UBits(33, 8)))); } TEST_P(CombinationalGeneratorTest, ArrayIndexNilIndex) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); auto a = fb.Param("a", package.GetArrayType(3, u8)); auto ret = fb.ArrayIndex(a, {}); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret)); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT( simulator.Run({{"a", Value::UBitsArray({11, 22, 33}, 8).value()}}), IsOkAndHolds(Value::UBitsArray({11, 22, 33}, 8).value())); } TEST_P(CombinationalGeneratorTest, ArrayIndex2DArrayIndexSingleElement) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); Type* u16 = package.GetBitsType(16); auto a = fb.Param("a", package.GetArrayType(2, package.GetArrayType(3, u8))); auto idx0 = fb.Param("idx0", u16); auto idx1 = fb.Param("idx1", u16); auto ret = fb.ArrayIndex(a, {idx0, idx1}); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret)); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT( simulator.Run( {{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()}, {"idx0", Value(UBits(0, 16))}, {"idx1", Value(UBits(1, 16))}}), IsOkAndHolds(Value(UBits(22, 8)))); } TEST_P(CombinationalGeneratorTest, ArrayIndex2DArrayIndexSubArray) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); Type* u16 = package.GetBitsType(16); auto a = fb.Param("a", package.GetArrayType(2, package.GetArrayType(3, u8))); auto idx = fb.Param("idx", u16); auto ret = fb.ArrayIndex(a, {idx}); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret)); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT( simulator.Run( {{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()}, {"idx", Value(UBits(0, 16))}}), IsOkAndHolds(Value::UBitsArray({11, 22, 33}, 8).value())); EXPECT_THAT( simulator.Run( {{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()}, {"idx", Value(UBits(1, 16))}}), IsOkAndHolds(Value::UBitsArray({44, 55, 66}, 8).value())); // Out-of-bounds index should return the max element. // TODO(meheff): Handle when out-of-bounds access is handled. // EXPECT_THAT( // simulator.Run( // {{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, // 8).value()}, // {"idx", Value(UBits(42, 16))}}), // IsOkAndHolds( // Value::UBitsArray({44, 55, 66}, 8).value())); } TEST_P(CombinationalGeneratorTest, ArrayUpdateLiteralIndex) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); auto a = fb.Param("a", package.GetArrayType(3, u8)); auto update_value = fb.Param("value", u8); auto idx = fb.Literal(UBits(1, 16)); auto ret = fb.ArrayUpdate(a, update_value, {idx}); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret)); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT(simulator.Run({{"a", Value::UBitsArray({11, 22, 33}, 8).value()}, {"value", Value(UBits(123, 8))}}), IsOkAndHolds(Value::UBitsArray({11, 123, 33}, 8).value())); } TEST_P(CombinationalGeneratorTest, ArrayUpdateVariableIndex) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); auto a = fb.Param("a", package.GetArrayType(3, u8)); auto update_value = fb.Param("value", u8); auto idx = fb.Param("idx", package.GetBitsType(32)); auto ret = fb.ArrayUpdate(a, update_value, {idx}); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret)); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT(simulator.Run({{"a", Value::UBitsArray({11, 22, 33}, 8).value()}, {"idx", Value(UBits(0, 32))}, {"value", Value(UBits(123, 8))}}), IsOkAndHolds(Value::UBitsArray({123, 22, 33}, 8).value())); // Out-of-bounds should just return the original array. EXPECT_THAT(simulator.Run({{"a", Value::UBitsArray({11, 22, 33}, 8).value()}, {"idx", Value(UBits(3, 32))}, {"value", Value(UBits(123, 8))}}), IsOkAndHolds(Value::UBitsArray({11, 22, 33}, 8).value())); } TEST_P(CombinationalGeneratorTest, ArrayUpdate2DLiteralIndex) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); auto a = fb.Param("a", package.GetArrayType(2, package.GetArrayType(3, u8))); auto update_value = fb.Param("value", u8); auto idx0 = fb.Literal(UBits(0, 32)); auto idx1 = fb.Literal(UBits(2, 14)); auto ret = fb.ArrayUpdate(a, update_value, {idx0, idx1}); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret)); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT( simulator.Run( {{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()}, {"value", Value(UBits(123, 8))}}), IsOkAndHolds( Value::UBits2DArray({{11, 22, 123}, {44, 55, 66}}, 8).value())); } TEST_P(CombinationalGeneratorTest, ArrayUpdate2DVariableIndex) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); auto a = fb.Param("a", package.GetArrayType(2, package.GetArrayType(3, u8))); auto update_value = fb.Param("value", u8); auto idx0 = fb.Param("idx0", package.GetBitsType(32)); auto idx1 = fb.Param("idx1", package.GetBitsType(32)); auto ret = fb.ArrayUpdate(a, update_value, {idx0, idx1}); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret)); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT( simulator.Run( {{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()}, {"value", Value(UBits(123, 8))}, {"idx0", Value(UBits(1, 32))}, {"idx1", Value(UBits(0, 32))}}), IsOkAndHolds( Value::UBits2DArray({{11, 22, 33}, {123, 55, 66}}, 8).value())); // Out-of-bounds should just return the original array. EXPECT_THAT( simulator.Run( {{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()}, {"value", Value(UBits(123, 8))}, {"idx0", Value(UBits(1, 32))}, {"idx1", Value(UBits(44, 32))}}), IsOkAndHolds( Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value())); EXPECT_THAT( simulator.Run( {{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()}, {"value", Value(UBits(123, 8))}, {"idx0", Value(UBits(11, 32))}, {"idx1", Value(UBits(0, 32))}}), IsOkAndHolds( Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value())); } TEST_P(CombinationalGeneratorTest, ArrayUpdate2DLiteralAndVariableIndex) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); auto a = fb.Param("a", package.GetArrayType(2, package.GetArrayType(3, u8))); auto update_value = fb.Param("value", u8); auto idx0 = fb.Param("idx", package.GetBitsType(32)); auto idx1 = fb.Literal(UBits(2, 14)); auto ret = fb.ArrayUpdate(a, update_value, {idx0, idx1}); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret)); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT( simulator.Run( {{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()}, {"value", Value(UBits(123, 8))}, {"idx", Value(UBits(0, 32))}}), IsOkAndHolds( Value::UBits2DArray({{11, 22, 123}, {44, 55, 66}}, 8).value())); // Out-of-bounds should just return the original array. EXPECT_THAT( simulator.Run( {{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()}, {"value", Value(UBits(123, 8))}, {"idx", Value(UBits(10, 32))}}), IsOkAndHolds( Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value())); } TEST_P(CombinationalGeneratorTest, ArrayUpdate2DUpdateArrayLiteralIndex) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); auto a = fb.Param("a", package.GetArrayType(2, package.GetArrayType(3, u8))); auto update_value = fb.Param("value", package.GetArrayType(3, u8)); auto idx = fb.Literal(UBits(1, 14)); auto ret = fb.ArrayUpdate(a, update_value, {idx}); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret)); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT( simulator.Run( {{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()}, {"value", Value::UBitsArray({101, 102, 103}, 8).value()}}), IsOkAndHolds( Value::UBits2DArray({{11, 22, 33}, {101, 102, 103}}, 8).value())); } TEST_P(CombinationalGeneratorTest, ArrayUpdate2DUpdateArrayVariableIndex) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); auto a = fb.Param("a", package.GetArrayType(2, package.GetArrayType(3, u8))); auto update_value = fb.Param("value", package.GetArrayType(3, u8)); auto idx = fb.Param("idx", package.GetBitsType(37)); auto ret = fb.ArrayUpdate(a, update_value, {idx}); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret)); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT( simulator.Run( {{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()}, {"value", Value::UBitsArray({101, 102, 103}, 8).value()}, {"idx", Value(UBits(1, 37))}}), IsOkAndHolds( Value::UBits2DArray({{11, 22, 33}, {101, 102, 103}}, 8).value())); // Out-of-bounds should just return the original array. EXPECT_THAT( simulator.Run( {{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()}, {"value", Value::UBitsArray({101, 102, 103}, 8).value()}, {"idx", Value(UBits(2, 37))}}), IsOkAndHolds( Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value())); } TEST_P(CombinationalGeneratorTest, ArrayUpdate2DUpdateArrayNilIndex) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); auto a = fb.Param("a", package.GetArrayType(2, package.GetArrayType(3, u8))); auto update_value = fb.Param("value", package.GetArrayType(2, package.GetArrayType(3, u8))); auto ret = fb.ArrayUpdate(a, update_value, {}); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret)); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT( simulator.Run( {{"a", Value::UBits2DArray({{11, 22, 33}, {44, 55, 66}}, 8).value()}, {"value", Value::UBits2DArray({{101, 102, 103}, {104, 105, 106}}, 8) .value()}}), IsOkAndHolds( Value::UBits2DArray({{101, 102, 103}, {104, 105, 106}}, 8).value())); } TEST_P(CombinationalGeneratorTest, ArrayUpdateBitsNilIndex) { Package package(TestBaseName()); FunctionBuilder fb(TestBaseName(), &package); Type* u8 = package.GetBitsType(8); auto a = fb.Param("a", u8); auto update_value = fb.Param("value", u8); auto ret = fb.ArrayUpdate(a, update_value, {}); XLS_ASSERT_OK_AND_ASSIGN(Function * f, fb.BuildWithReturnValue(ret)); XLS_ASSERT_OK_AND_ASSIGN(auto result, GenerateCombinationalModule(f, UseSystemVerilog())); ExpectVerilogEqualToGoldenFile(GoldenFilePath(kTestName, kTestdataPath), result.verilog_text); ModuleSimulator simulator(result.signature, result.verilog_text, GetSimulator()); EXPECT_THAT(simulator.RunAndReturnSingleOutput( {{"a", UBits(11, 8)}, {"value", UBits(22, 8)}}), IsOkAndHolds(UBits(22, 8))); } INSTANTIATE_TEST_SUITE_P(CombinationalGeneratorTestInstantiation, CombinationalGeneratorTest, testing::ValuesIn(kDefaultSimulationTargets), ParameterizedTestName<CombinationalGeneratorTest>); } // namespace } // namespace verilog } // namespace xls
42.403409
102
0.6336
AdrianaDJ
c047c931ec45d1e24a217c29edd8b25022f52461
6,680
cpp
C++
core/os/memory_pool_dynamic_static.cpp
leyyin/godot
68325d7254db711beaedddad218e2cddb405c42c
[ "CC-BY-3.0", "MIT" ]
24
2016-10-14T16:54:01.000Z
2022-01-15T06:39:17.000Z
core/os/memory_pool_dynamic_static.cpp
leyyin/godot
68325d7254db711beaedddad218e2cddb405c42c
[ "CC-BY-3.0", "MIT" ]
17
2016-12-30T14:35:53.000Z
2017-03-07T21:07:50.000Z
core/os/memory_pool_dynamic_static.cpp
leyyin/godot
68325d7254db711beaedddad218e2cddb405c42c
[ "CC-BY-3.0", "MIT" ]
9
2017-08-04T12:00:16.000Z
2021-12-10T06:48:28.000Z
/*************************************************************************/ /* memory_pool_dynamic_static.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 "memory_pool_dynamic_static.h" #include "os/memory.h" #include "os/os.h" #include "ustring.h" #include "print_string.h" #include <stdio.h> MemoryPoolDynamicStatic::Chunk *MemoryPoolDynamicStatic::get_chunk(ID p_id) { uint64_t check = p_id/MAX_CHUNKS; uint64_t idx = p_id%MAX_CHUNKS; if (!chunk[idx].mem || chunk[idx].check!=check) return NULL; return &chunk[idx]; } const MemoryPoolDynamicStatic::Chunk *MemoryPoolDynamicStatic::get_chunk(ID p_id) const { uint64_t check = p_id/MAX_CHUNKS; uint64_t idx = p_id%MAX_CHUNKS; if (!chunk[idx].mem || chunk[idx].check!=check) return NULL; return &chunk[idx]; } MemoryPoolDynamic::ID MemoryPoolDynamicStatic::alloc(size_t p_amount,const char* p_description) { _THREAD_SAFE_METHOD_ int idx=-1; for (int i=0;i<MAX_CHUNKS;i++) { last_alloc++; if (last_alloc>=MAX_CHUNKS) last_alloc=0; if ( !chunk[last_alloc].mem ) { idx=last_alloc; break; } } if (idx==-1) { ERR_EXPLAIN("Out of dynamic Memory IDs"); ERR_FAIL_V(INVALID_ID); //return INVALID_ID; } //chunk[idx].mem = Memory::alloc_static(p_amount,p_description); chunk[idx].mem = memalloc(p_amount); if (!chunk[idx].mem) return INVALID_ID; chunk[idx].size=p_amount; chunk[idx].check=++last_check; chunk[idx].descr=p_description; chunk[idx].lock=0; total_usage+=p_amount; if (total_usage>max_usage) max_usage=total_usage; ID id = chunk[idx].check*MAX_CHUNKS + (uint64_t)idx; return id; } void MemoryPoolDynamicStatic::free(ID p_id) { _THREAD_SAFE_METHOD_ Chunk *c = get_chunk(p_id); ERR_FAIL_COND(!c); total_usage-=c->size; memfree(c->mem); c->mem=0; if (c->lock>0) { ERR_PRINT("Freed ID Still locked"); } } Error MemoryPoolDynamicStatic::realloc(ID p_id, size_t p_amount) { _THREAD_SAFE_METHOD_ Chunk *c = get_chunk(p_id); ERR_FAIL_COND_V(!c,ERR_INVALID_PARAMETER); ERR_FAIL_COND_V(c->lock > 0 , ERR_LOCKED ); void * new_mem = memrealloc(c->mem,p_amount); ERR_FAIL_COND_V(!new_mem,ERR_OUT_OF_MEMORY); total_usage-=c->size; c->mem=new_mem; c->size=p_amount; total_usage+=c->size; if (total_usage>max_usage) max_usage=total_usage; return OK; } bool MemoryPoolDynamicStatic::is_valid(ID p_id) { _THREAD_SAFE_METHOD_ Chunk *c = get_chunk(p_id); return c!=NULL; } size_t MemoryPoolDynamicStatic::get_size(ID p_id) const { _THREAD_SAFE_METHOD_ const Chunk *c = get_chunk(p_id); ERR_FAIL_COND_V(!c,0); return c->size; } const char* MemoryPoolDynamicStatic::get_description(ID p_id) const { _THREAD_SAFE_METHOD_ const Chunk *c = get_chunk(p_id); ERR_FAIL_COND_V(!c,""); return c->descr; } bool MemoryPoolDynamicStatic::is_locked(ID p_id) const { _THREAD_SAFE_METHOD_ const Chunk *c = get_chunk(p_id); ERR_FAIL_COND_V(!c,false); return c->lock>0; } Error MemoryPoolDynamicStatic::lock(ID p_id) { _THREAD_SAFE_METHOD_ Chunk *c = get_chunk(p_id); ERR_FAIL_COND_V(!c,ERR_INVALID_PARAMETER); c->lock++; return OK; } void * MemoryPoolDynamicStatic::get(ID p_id) { _THREAD_SAFE_METHOD_ const Chunk *c = get_chunk(p_id); ERR_FAIL_COND_V(!c,NULL); ERR_FAIL_COND_V( c->lock==0, NULL ); return c->mem; } Error MemoryPoolDynamicStatic::unlock(ID p_id) { _THREAD_SAFE_METHOD_ Chunk *c = get_chunk(p_id); ERR_FAIL_COND_V(!c,ERR_INVALID_PARAMETER); ERR_FAIL_COND_V( c->lock<=0, ERR_INVALID_PARAMETER ); c->lock--; return OK; } size_t MemoryPoolDynamicStatic::get_available_mem() const { return Memory::get_static_mem_available(); } size_t MemoryPoolDynamicStatic::get_total_usage() const { _THREAD_SAFE_METHOD_ return total_usage; } MemoryPoolDynamicStatic::MemoryPoolDynamicStatic() { last_check=1; last_alloc=0; total_usage=0; max_usage=0; } MemoryPoolDynamicStatic::~MemoryPoolDynamicStatic() { #ifdef DEBUG_MEMORY_ENABLED if (OS::get_singleton()->is_stdout_verbose()) { if (total_usage>0) { ERR_PRINT("DYNAMIC ALLOC: ** MEMORY LEAKS DETECTED **"); ERR_PRINT(String("DYNAMIC ALLOC: "+String::num(total_usage)+" bytes of memory in use at exit.").ascii().get_data()); ERR_PRINT("DYNAMIC ALLOC: Following is the list of leaked allocations:"); for (int i=0;i<MAX_CHUNKS;i++) { if (chunk[i].mem) { ERR_PRINT(String("\t"+String::num(chunk[i].size)+" bytes - "+String(chunk[i].descr)).ascii().get_data()); } } ERR_PRINT("DYNAMIC ALLOC: End of Report."); print_line("INFO: dynmem - max: "+itos(max_usage)+", "+itos(total_usage)+" leaked."); } else { print_line("INFO: dynmem - max: "+itos(max_usage)+", no leaks."); } } #endif }
24.468864
119
0.627545
leyyin
c04859891a666e1816daf20afd5cbeedb16f3a5e
1,780
cpp
C++
src/main/cpp/subsystems/subsystem_Arm.cpp
Robodox-599/2022_Ophthamologist
2bb465e416389505afcd7d9cedc16ff868e5200a
[ "BSD-3-Clause" ]
3
2022-03-03T03:36:45.000Z
2022-03-04T03:45:18.000Z
src/main/cpp/subsystems/subsystem_Arm.cpp
Robodox-599/2022_Ophthamologist
2bb465e416389505afcd7d9cedc16ff868e5200a
[ "BSD-3-Clause" ]
1
2022-02-26T18:51:46.000Z
2022-02-26T18:51:46.000Z
src/main/cpp/subsystems/subsystem_Arm.cpp
Robodox-599/2022_Ophthamologist
2bb465e416389505afcd7d9cedc16ff868e5200a
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include "subsystems/subsystem_Arm.h" subsystem_Arm::subsystem_Arm() : m_ArmMotor{ArmConstants::ArmMotorPort, rev::CANSparkMax::MotorType::kBrushless}{ //arm motor set up double kP = 1, kI = 0, kD = 0, kIz = 0, kFF = 0, kMaxOutput = .3, kMinOutput = -.3; m_ArmPidController.SetP(kP); m_ArmPidController.SetI(kI); m_ArmPidController.SetD(kD); m_ArmPidController.SetIZone(kIz); m_ArmPidController.SetFF(kFF); m_ArmPidController.SetOutputRange(kMinOutput, kMaxOutput); m_ArmPidController.SetSmartMotionAccelStrategy(rev::CANPIDController::AccelStrategy::kTrapezoidal, 0); m_ArmPidController.SetSmartMotionMaxAccel(ArmConstants::ArmAcceleration); m_ArmPidController.SetSmartMotionMaxVelocity(ArmConstants::ArmVelocity); m_ArmEncoder.SetPosition(0); m_ArmMotor.SetInverted(true); // m_ArmEncoder.SetInverted(true); //built_different //thing } /*moves the position of the arm by the inputed amount of ticks. 0 ticks is the arm in the horizontal position */ void subsystem_Arm::SetArmPosition(int ticks){ m_ArmPidController.SetReference(ticks, rev::ControlType::kPosition,0); } // This method will be called once per scheduler run void subsystem_Arm::Periodic() { frc::SmartDashboard::PutNumber("POSITION", m_ArmEncoder.GetPosition()); frc::SmartDashboard::PutNumber("CURRENT", m_ArmMotor.GetOutputCurrent()); //Stall prevention, checks the current of the motor to make sure that it isn't stuck if(m_ArmMotor.GetOutputCurrent() > 100){ SetArmPosition(ArmConstants::ArmTicksUp); } }
39.555556
113
0.747753
Robodox-599
c04a336ebb778a23bb447f7aa373c6ee66f9c1b8
1,598
cpp
C++
fuzzer/test/test-exec-flags.cpp
ucsb-seclab/regulator-dynamic
9b40c0dcb89f102dd0814728fb7da938b62bab68
[ "MIT" ]
null
null
null
fuzzer/test/test-exec-flags.cpp
ucsb-seclab/regulator-dynamic
9b40c0dcb89f102dd0814728fb7da938b62bab68
[ "MIT" ]
null
null
null
fuzzer/test/test-exec-flags.cpp
ucsb-seclab/regulator-dynamic
9b40c0dcb89f102dd0814728fb7da938b62bab68
[ "MIT" ]
null
null
null
// tests execution with different flags #include "regexp-executor.hpp" #include "catch.hpp" namespace e = regulator::executor; namespace f = regulator::fuzz; TEST_CASE( "compile and exec with case-insensitive (8-bit)" ) { v8::Isolate *isolate = regulator::executor::Initialize(); v8::HandleScope scope(isolate); v8::Local<v8::Context> ctx = v8::Context::New(isolate); ctx->Enter(); e::V8RegExp regexp; std::string sz_regexp = "foo.+bar"; e::Result compile_result_status = e::Compile(sz_regexp.c_str(), "i", &regexp); REQUIRE( compile_result_status == e::kSuccess ); REQUIRE_FALSE( regexp.regexp.is_null() ); uint8_t negative_subject[] = { 'f', 'f', 'o', 'o', 'b', 'a', 'r' }; uint8_t positive_subject[] = { 'f', 'F', 'o', 'O', '_', 'B', 'a', 'R', 'x' }; e::Result exec_result_status; e::V8RegExpResult exec_result; exec_result_status = e::Exec( &regexp, negative_subject, sizeof(negative_subject), exec_result, e::kOnlyOneByte ); REQUIRE( exec_result_status == e::kSuccess ); REQUIRE( exec_result.match_success == false ); exec_result_status = e::Exec( &regexp, positive_subject, sizeof(positive_subject), exec_result, e::kOnlyOneByte ); REQUIRE( exec_result_status == e::kSuccess ); REQUIRE( exec_result.match_success == true ); } TEST_CASE( "compile and exec with sticky bit " ) { }
21.594595
82
0.573217
ucsb-seclab
c04d64e600dabcb8babaac093ec469ffa9698d27
2,459
hpp
C++
shared/imgui/imgui_impl_win32.hpp
jrnh/herby
bf0e90b850e2f81713e4dbc21c8d8b9af78ad203
[ "MIT" ]
null
null
null
shared/imgui/imgui_impl_win32.hpp
jrnh/herby
bf0e90b850e2f81713e4dbc21c8d8b9af78ad203
[ "MIT" ]
null
null
null
shared/imgui/imgui_impl_win32.hpp
jrnh/herby
bf0e90b850e2f81713e4dbc21c8d8b9af78ad203
[ "MIT" ]
null
null
null
// dear imgui: Platform Backend for Windows (standard windows API for 32 and 64 bits applications) // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // Implemented features: // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui) // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: Keyboard arrays indexed using VK_* Virtual Key Codes, e.g. ImGui::IsKeyPressed(VK_SPACE). // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Read online: https://github.com/ocornut/imgui/tree/master/docs #pragma once #include <windows.h> IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd); IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown(); IMGUI_IMPL_API void ImGui_ImplWin32_NewFrame(); // Configuration // - Disable gamepad support or linking with xinput.lib //#define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD //#define IMGUI_IMPL_WIN32_DISABLE_LINKING_XINPUT // Win32 message handler // - Intentionally commented out in a '#if 0' block to avoid dragging dependencies on <windows.h> // - You can COPY this line into your .cpp code to forward declare the function. IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); // DPI-related helpers (optional) // - Use to enable DPI awareness without having to create an application manifest. // - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps. // - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc. // but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime, // neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies. IMGUI_IMPL_API void ImGui_ImplWin32_EnableDpiAwareness(); IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd); // HWND hwnd IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor); // HMONITOR monitor
61.475
126
0.775519
jrnh
c04e6aae6af0b701a8a8b5931236b155562ee303
983
inl
C++
src/stk/filters/normalize.inl
simeks/stk
21caff7d35d30f385928cd027243d8ac5d33a132
[ "MIT" ]
2
2018-08-15T10:52:34.000Z
2018-09-26T13:05:57.000Z
src/stk/filters/normalize.inl
simeks/stk
21caff7d35d30f385928cd027243d8ac5d33a132
[ "MIT" ]
19
2018-07-10T10:32:19.000Z
2019-11-07T10:19:13.000Z
src/stk/filters/normalize.inl
simeks/stk
21caff7d35d30f385928cd027243d8ac5d33a132
[ "MIT" ]
1
2018-06-27T17:28:20.000Z
2018-06-27T17:28:20.000Z
namespace stk { template<typename T> VolumeHelper<T> normalize(const VolumeHelper<T>& src, T min, T max, VolumeHelper<T>* out) { T src_min, src_max; find_min_max(src, src_min, src_max); dim3 dims = src.size(); VolumeHelper<T> dest; if (!out) { dest.allocate(src.size()); out = &dest; } ASSERT(out->size() == dims); out->copy_meta_from(src); double range = double(max - min); double src_range = double(src_max - src_min); #pragma omp parallel for for (int z = 0; z < int(dims.z); ++z) { for (int y = 0; y < int(dims.y); ++y) { for (int x = 0; x < int(dims.x); ++x) { (*out)(x,y,z) = T(range * (src(x, y, z) - src_min) / src_range + min); } } } return *out; } }
26.567568
90
0.425229
simeks
c0501e8417d302b42f9507b86f0331423f27cf2b
4,284
cpp
C++
middleware/transaction/source/manager/transform.cpp
casualcore/casual
047a4eaabbba52ad3ce63dc698a9325ad5fcec6d
[ "MIT" ]
null
null
null
middleware/transaction/source/manager/transform.cpp
casualcore/casual
047a4eaabbba52ad3ce63dc698a9325ad5fcec6d
[ "MIT" ]
null
null
null
middleware/transaction/source/manager/transform.cpp
casualcore/casual
047a4eaabbba52ad3ce63dc698a9325ad5fcec6d
[ "MIT" ]
1
2022-02-21T18:30:25.000Z
2022-02-21T18:30:25.000Z
//! //! Copyright (c) 2021, The casual project //! //! This software is licensed under the MIT license, https://opensource.org/licenses/MIT //! #include "transaction/manager/transform.h" #include "transaction/common.h" #include "common/event/send.h" #include "common/environment.h" #include "common/environment/normalize.h" #include "common/algorithm/coalesce.h" #include "configuration/system.h" namespace casual { using namespace common; namespace transaction::manager::transform { namespace local { namespace { template< typename T> std::filesystem::path initialize_log( T configuration) { Trace trace{ "transaction::manager::transfrom::local::initialize_log"}; if( ! configuration.empty()) return common::environment::expand( std::move( configuration)); auto file = environment::directory::transaction() / "log.db"; // TODO: remove this in 2.0 (that exist to be backward compatible) { // if the wanted path exists, we can't overwrite with the old if( std::filesystem::exists( file)) return file; auto old = environment::directory::domain() / "transaction" / "log.db"; if( std::filesystem::exists( old)) { std::filesystem::rename( old, file); event::notification::send( "transaction log file moved: ", std::filesystem::relative( old), " -> ", std::filesystem::relative( file)); log::line( log::category::warning, "transaction log file moved: ", old, " -> ", file); } } return file; }; auto resources = []( auto&& resources, const auto& properties) { Trace trace{ "transaction::manager::transform::local::resources"}; auto transform_resource = []( const auto& configuration) { state::resource::Proxy result{ configuration}; // make sure we've got a name result.configuration.name = common::algorithm::coalesce( std::move( result.configuration.name), common::string::compose( ".rm.", result.configuration.key, '.', result.id)); return result; }; auto validate = [&]( const auto& r) { if( common::algorithm::find( properties, r.key)) return true; common::event::error::fatal::send( code::casual::invalid_argument, "failed to correlate resource key: '", r.key, "'"); return false; }; std::vector< state::resource::Proxy> result; common::algorithm::transform_if( resources, result, transform_resource, validate); return result; }; } // <unnamed> } // local State state( casual::configuration::Model model) { Trace trace{ "transaction::manager::transform::state"}; State state; state.persistent.log = decltype( state.persistent.log){ local::initialize_log( std::move( model.transaction.log))}; auto get_system = []( auto system) { if( system != decltype( system){}) return system; // TODO deprecated, will be removed at some point return configuration::system::get(); }; state.system.configuration = get_system( std::move( model.system)); state.resources = local::resources( model.transaction.resources, state.system.configuration.resources); for( auto& mapping : model.transaction.mappings) { state.alias.configuration.emplace( mapping.alias, algorithm::transform( mapping.resources, [&state]( auto& name) { return state.get_resource( name).id; })); } return state; } } // transaction::manager::transform } // casual
33.46875
155
0.531046
casualcore
c050e20a224e2e0c1b2f0153d3c38025d9a1d73b
5,199
cpp
C++
src/util/codec_util_high_openssl.cpp
jackyding2679/cos-cpp-sdk-v5
037da66f54473ba9628b532df72759edb6ca7700
[ "MIT" ]
6
2018-11-17T01:34:02.000Z
2020-04-21T14:18:44.000Z
src/util/codec_util_high_openssl.cpp
jackyding2679/cos-cpp-sdk-v5
037da66f54473ba9628b532df72759edb6ca7700
[ "MIT" ]
null
null
null
src/util/codec_util_high_openssl.cpp
jackyding2679/cos-cpp-sdk-v5
037da66f54473ba9628b532df72759edb6ca7700
[ "MIT" ]
1
2018-11-19T08:12:13.000Z
2018-11-19T08:12:13.000Z
#include "util/codec_util.h" #include <cassert> #include <string.h> #include <algorithm> #include <fstream> #include <iostream> #include <string> #include <openssl/crypto.h> #include <openssl/evp.h> #include <openssl/hmac.h> #include <openssl/md5.h> #include "util/file_util.h" #include "util/sha1.h" #include <openssl/sha.h> namespace qcloud_cos { #define REVERSE_HEX(c) ( ((c) >= 'A') ? ((c) & 0xDF) - 'A' + 10 : (c) - '0' ) #define HMAC_LENGTH 20 unsigned char CodecUtil::ToHex(const unsigned char& x) { return x > 9 ? (x - 10 + 'A') : x + '0'; } void CodecUtil::BinToHex(const unsigned char *bin,unsigned int binLen, char *hex) { for(unsigned int i = 0; i < binLen; ++i) { hex[i<<1] = ToHex(bin[i] >> 4); hex[(i<<1)+1] = ToHex(bin[i] & 15 ); } } std::string CodecUtil::EncodeKey(const std::string& key) { std::string encodedKey = ""; std::size_t length = key.length(); for (size_t i = 0; i < length; ++i) { if (isalnum((unsigned char)key[i]) || (key[i] == '-') || (key[i] == '_') || (key[i] == '.') || (key[i] == '~') || (key[i] == '/')) { encodedKey += key[i]; } else { encodedKey += '%'; encodedKey += ToHex((unsigned char)key[i] >> 4); encodedKey += ToHex((unsigned char)key[i] % 16); } } return encodedKey; } std::string CodecUtil::UrlEncode(const std::string& str) { std::string encodedUrl = ""; std::size_t length = str.length(); for (size_t i = 0; i < length; ++i) { if (isalnum((unsigned char)str[i]) || (str[i] == '-') || (str[i] == '_') || (str[i] == '.') || (str[i] == '~')) { encodedUrl += str[i]; } else { encodedUrl += '%'; encodedUrl += ToHex((unsigned char)str[i] >> 4); encodedUrl += ToHex((unsigned char)str[i] % 16); } } return encodedUrl; } std::string CodecUtil::Base64Encode(const std::string& plain_text) { static const char b64_table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const std::size_t plain_text_len = plain_text.size(); std::string retval((((plain_text_len + 2) / 3) * 4), '='); std::size_t outpos = 0; int bits_collected = 0; unsigned int accumulator = 0; const std::string::const_iterator plain_text_end = plain_text.end(); for (std::string::const_iterator i = plain_text.begin(); i != plain_text_end; ++i) { accumulator = (accumulator << 8) | (*i & 0xffu); bits_collected += 8; while (bits_collected >= 6) { bits_collected -= 6; retval[outpos++] = b64_table[(accumulator >> bits_collected) & 0x3fu]; } } if (bits_collected > 0) { assert(bits_collected < 6); accumulator <<= 6 - bits_collected; retval[outpos++] = b64_table[accumulator & 0x3fu]; } assert(outpos >= (retval.size() - 2)); assert(outpos <= retval.size()); return retval; } std::string CodecUtil::HmacSha1(const std::string& plainText, const std::string& key) { const EVP_MD *engine = EVP_sha1(); unsigned char *output = (unsigned char *)malloc(EVP_MAX_MD_SIZE); unsigned int output_len = 0; HMAC_CTX *ctx = HMAC_CTX_new(); HMAC_CTX_reset(ctx); HMAC_Init_ex(ctx, (char *)key.c_str(), key.length(), engine, NULL); HMAC_Update(ctx, (unsigned char*)plainText.c_str(), plainText.length()); HMAC_Final(ctx, output, &output_len); HMAC_CTX_free(ctx); std::string hmac_sha1_ret((char *)output, output_len); free(output); return hmac_sha1_ret; } std::string CodecUtil::HmacSha1Hex(const std::string& plain_text,const std::string& key) { std::string encode_str = HmacSha1(plain_text, key); char hex[(HMAC_LENGTH<<1)+1] = {0}; BinToHex((const unsigned char*)encode_str.c_str(), encode_str.size(), hex); return std::string(hex, (HMAC_LENGTH << 1)); } std::string CodecUtil::RawMd5(const std::string& plainText) { const int md5_length = 16; unsigned char md[md5_length]; MD5((const unsigned char*)plainText.data(), plainText.size(), md); std::string tmp((const char *)md, md5_length); return tmp; } // convert a hexadecimal string to binary value std::string CodecUtil::HexToBin(const std::string &strHex) { if (strHex.size() % 2 != 0) { return ""; } std::string strBin; strBin.resize(strHex.size() / 2); for (size_t i = 0; i < strBin.size(); i++) { uint8_t cTmp = 0; for (size_t j = 0; j < 2; j++) { char cCur = strHex[2 * i + j]; if (cCur >= '0' && cCur <= '9') { cTmp = (cTmp << 4) + (cCur - '0'); } else if (cCur >= 'a' && cCur <= 'f') { cTmp = (cTmp << 4) + (cCur - 'a' + 10); } else if (cCur >= 'A' && cCur <= 'F') { cTmp = (cTmp << 4) + (cCur - 'A' + 10); } else { return ""; } } strBin[i] = cTmp; } return strBin; }// end of HexToBin }// end of qcloud_cos namespace
30.946429
105
0.55126
jackyding2679
c055064afd19bc84d0a88420d08f27ec9b0f5394
5,405
cpp
C++
src/test/graph5.cpp
jalilm/q-MAX
3a4e7ca89a9d0096ce7366f9efcf4ba583a6aced
[ "MIT" ]
2
2021-03-05T02:05:44.000Z
2021-05-26T16:13:57.000Z
src/test/graph5.cpp
jalilm/q-MAX
3a4e7ca89a9d0096ce7366f9efcf4ba583a6aced
[ "MIT" ]
null
null
null
src/test/graph5.cpp
jalilm/q-MAX
3a4e7ca89a9d0096ce7366f9efcf4ba583a6aced
[ "MIT" ]
2
2019-12-03T12:59:40.000Z
2021-03-05T01:49:58.000Z
#include <cstdio> #include <cstdlib> #include <list> #include <fstream> #include <iostream> #include <sstream> #include <cstring> #include <random> #include <stdio.h> #include <stdlib.h> #include <sys/timeb.h> #include "../QmaxKV.hpp" #include "../HeapKV.hpp" #include "../SkiplistKV.hpp" #include "Utils.hpp" #define CLK_PER_SEC CLOCKS_PER_SEC #define CAIDA16_SIZE 152197437 #define CAIDA18_SIZE 175880808 #define UNIV1_SIZE 17323447 using namespace std; void benchmark_psskiplist(int q, key** keys, val** vals, ofstream &ostream, string dataset, int numKeys) { std::random_device _rd; std::mt19937 _e2(_rd()); std::uniform_real_distribution<double> _dist(0,1); key *elements = *keys; val *weights = *vals; struct timeb begintb, endtb; clock_t begint, endt; double time; SkiplistKV sl(q); begint = clock(); ftime(&begintb); for (int i = 0; i < numKeys; i++) { val priority = weights[i] / (1-_dist(_e2)); sl.add(pair<key, val>(elements[i], priority)); } endt = clock(); ftime(&endtb); time = ((double)(endt-begint))/CLK_PER_SEC; ostream << dataset << ",SkipList," << numKeys << "," << q << ",," << time << endl; } void benchmark_psheap(int q, key** keys, val** vals, ofstream &ostream, string dataset, int numKeys) { std::random_device _rd; std::mt19937 _e2(_rd()); std::uniform_real_distribution<double> _dist(0,1); key *elements = *keys; val *weights = *vals; struct timeb begintb, endtb; clock_t begint, endt; double time; HeapKV heap(q); begint = clock(); ftime(&begintb); for (int i = 0; i < numKeys; i++) { val priority = weights[i] / (1-_dist(_e2)); heap.add(pair<key,val>(elements[i], priority)); } endt = clock(); ftime(&endtb); time = ((double)(endt-begint))/CLK_PER_SEC; ostream << dataset << ",Heap," << numKeys << "," << q << ",," << time << endl; } void benchmark_psqmax(int q, double gamma, key** keys, val** vals, ofstream &ostream, string dataset, int numKeys) { std::random_device _rd; std::mt19937 _e2(_rd()); std::uniform_real_distribution<double> _dist(0,1); key *elements = *keys; val *weights = *vals; struct timeb begintb, endtb; clock_t begint, endt; double time; QMaxKV qmax = QMaxKV(q, gamma); begint = clock(); ftime(&begintb); for (int i = 0; i < numKeys; i++) { val priority = weights[i] / (1-_dist(_e2)); qmax.insert(elements[i], priority); } endt = clock(); ftime(&endtb); time = ((double)(endt-begint))/CLK_PER_SEC; ostream << dataset << ",AmortizedQMax," << numKeys << "," << q << "," << gamma << "," << time << endl; } void getKeysAndValsFromFile(string filename, vector<key*> &keys, vector<val*> &vals, int size) { ifstream stream; stream.open(filename, fstream::in | fstream::out | fstream::app); if (!stream) { throw invalid_argument("Could not open " + filename + " for reading."); } key* file_keys = (key*) malloc(sizeof(key) * size); val* file_vals = (val*) malloc(sizeof(val) * size); string line; string len; string id; for (int i = 0; i < size; ++i){ getline(stream, line); std::istringstream iss(line); iss >> len; iss >> id; try { file_keys[i] = stoull(id); file_vals[i] = stoull(len); } catch (const std::invalid_argument& ia) { cerr << "Invalid argument: " << ia.what() << " at line " << i << endl; cerr << len << " " << id << endl;; --i; exit(1); } } keys.push_back(file_keys); vals.push_back(file_vals); stream.close(); } int main() { vector<ofstream*> streams; vector<key*> keys; vector<val*> vals; vector<int> sizes; vector<string> datasets; ofstream univ1stream; setupOutputFile("../results/ps_univ1.raw_res", univ1stream, false); streams.push_back(&univ1stream); getKeysAndValsFromFile("../datasets/UNIV1/mergedPktlen_Srcip", keys, vals, UNIV1_SIZE); sizes.push_back(UNIV1_SIZE); datasets.push_back("univ1"); ofstream caida16stream; setupOutputFile("../results/ps_caida.raw_res", caida16stream, false); streams.push_back(&caida16stream); getKeysAndValsFromFile("../datasets/CAIDA16/mergedPktlen_Srcip", keys, vals, CAIDA16_SIZE); sizes.push_back(CAIDA16_SIZE); datasets.push_back("caida"); ofstream caida18stream; setupOutputFile("../results/ps_caida18.raw_res", caida18stream, false); streams.push_back(&caida18stream); getKeysAndValsFromFile("../datasets/CAIDA18/mergedPktlen_Srcip", keys, vals, CAIDA18_SIZE); sizes.push_back(CAIDA18_SIZE); datasets.push_back("caida18"); list<unsigned int> qs = {10000000, 1000000, 100000, 10000}; for (int run = 0; run < 5; run++) { for (unsigned q: qs) { vector<key*>::iterator k_it = keys.begin(); vector<val*>::iterator v_it = vals.begin(); vector<int>::iterator s_it = sizes.begin(); vector<string>::iterator d_it = datasets.begin(); for (auto& stream : streams) { key* k = *k_it; val* v = *v_it; int size = *s_it; string dataset = *d_it; benchmark_psheap(q, &k, &v, *stream, dataset, size); benchmark_psskiplist(q, &k, &v, *stream, dataset, size); list<double> gammas = {0.5, 0.25, 0.1, 0.05}; for (double g : gammas) { benchmark_psqmax(q, g, &k, &v, *stream, dataset, size); } ++k_it; ++v_it; ++s_it; ++d_it; } } } univ1stream.close(); caida16stream.close(); caida18stream.close(); return 0; }
29.216216
116
0.639963
jalilm
c056cc860904fb1613e372c30ad3126ead651f41
7,118
cpp
C++
casablanca/Release/tests/Functional/uri/constructor_tests.cpp
fpelliccioni/Tao
d23655bdf1ff521dc0c7e3fb2f101d1156fea4d9
[ "BSL-1.0" ]
1
2015-12-30T16:02:12.000Z
2015-12-30T16:02:12.000Z
casablanca/Release/tests/Functional/uri/constructor_tests.cpp
fpelliccioni/Tao
d23655bdf1ff521dc0c7e3fb2f101d1156fea4d9
[ "BSL-1.0" ]
null
null
null
casablanca/Release/tests/Functional/uri/constructor_tests.cpp
fpelliccioni/Tao
d23655bdf1ff521dc0c7e3fb2f101d1156fea4d9
[ "BSL-1.0" ]
null
null
null
/*** * ==++== * * Copyright (c) Microsoft Corporation. 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. * * ==--== * =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ * * constructor_tests.cpp * * Tests for constructors of the uri class. * * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ****/ #include "stdafx.h" using namespace web; using namespace utility; using namespace http; namespace tests { namespace functional { namespace uri_tests { SUITE(constructor_tests) { TEST(parsing_constructor_char) { uri u(uri::encode_uri(U("net.tcp://testname.com:81/bleh%?qstring#goo"))); VERIFY_ARE_EQUAL(U("net.tcp"), u.scheme()); VERIFY_ARE_EQUAL(U("testname.com"), u.host()); VERIFY_ARE_EQUAL(81, u.port()); VERIFY_ARE_EQUAL(U("/bleh%25"), u.path()); VERIFY_ARE_EQUAL(U("qstring"), u.query()); VERIFY_ARE_EQUAL(U("goo"), u.fragment()); } TEST(parsing_constructor_encoded_string) { uri u(uri::encode_uri(U("net.tcp://testname.com:81/bleh%?qstring#goo"))); VERIFY_ARE_EQUAL(U("net.tcp"), u.scheme()); VERIFY_ARE_EQUAL(U("testname.com"), u.host()); VERIFY_ARE_EQUAL(81, u.port()); VERIFY_ARE_EQUAL(U("/bleh%25"), u.path()); VERIFY_ARE_EQUAL(U("qstring"), u.query()); VERIFY_ARE_EQUAL(U("goo"), u.fragment()); } TEST(parsing_constructor_string_string) { uri u(uri::encode_uri(U("net.tcp://testname.com:81/bleh%?qstring#goo"))); VERIFY_ARE_EQUAL(U("net.tcp"), u.scheme()); VERIFY_ARE_EQUAL(U("testname.com"), u.host()); VERIFY_ARE_EQUAL(81, u.port()); VERIFY_ARE_EQUAL(U("/bleh%25"), u.path()); VERIFY_ARE_EQUAL(U("qstring"), u.query()); VERIFY_ARE_EQUAL(U("goo"), u.fragment()); } TEST(empty_strings) { VERIFY_IS_TRUE(uri(U("")).is_empty()); VERIFY_IS_TRUE(uri(U("")).is_empty()); VERIFY_IS_TRUE(uri(uri::encode_uri(U(""))).is_empty()); } TEST(default_constructor) { VERIFY_IS_TRUE(uri().is_empty()); } TEST(relative_ref_string) { uri u(uri::encode_uri(U("first/second#boff"))); VERIFY_ARE_EQUAL(U(""), u.scheme()); VERIFY_ARE_EQUAL(U(""), u.host()); VERIFY_ARE_EQUAL(0, u.port()); VERIFY_ARE_EQUAL(U("first/second"), u.path()); VERIFY_ARE_EQUAL(U(""), u.query()); VERIFY_ARE_EQUAL(U("boff"), u.fragment()); } TEST(absolute_ref_string) { uri u(uri::encode_uri(U("/first/second#boff"))); VERIFY_ARE_EQUAL(U(""), u.scheme()); VERIFY_ARE_EQUAL(U(""), u.host()); VERIFY_ARE_EQUAL(0, u.port()); VERIFY_ARE_EQUAL(U("/first/second"), u.path()); VERIFY_ARE_EQUAL(U(""), u.query()); VERIFY_ARE_EQUAL(U("boff"), u.fragment()); } TEST(copy_constructor) { uri original(U("http://localhost:456/path1?qstring#goo")); uri new_uri(original); VERIFY_ARE_EQUAL(original, new_uri); } TEST(move_constructor) { const utility::string_t uri_str(U("http://localhost:456/path1?qstring#goo")); uri original(uri_str); uri new_uri = std::move(original); VERIFY_ARE_EQUAL(uri_str, new_uri.to_string()); VERIFY_ARE_EQUAL(uri(uri_str), new_uri); } TEST(assignment_operator) { uri original(U("http://localhost:456/path?qstring#goo")); uri new_uri = original; VERIFY_ARE_EQUAL(original, new_uri); } // Tests invalid URI being passed in constructor. TEST(parsing_constructor_invalid) { VERIFY_THROWS(uri(U("123http://localhost:345/")), uri_exception); VERIFY_THROWS(uri(U("h*ttp://localhost:345/")), uri_exception); VERIFY_THROWS(uri(U("http://localhost:345/\"")), uri_exception); VERIFY_THROWS(uri(U("http://localhost:345/path?\"")), uri_exception); VERIFY_THROWS(uri(U("http://local\"host:345/")), uri_exception); } // Tests a variety of different URIs using the examples in RFC 3986. TEST(RFC_3968_examples_string) { uri ftp(U("ftp://ftp.is.co.za/rfc/rfc1808.txt")); VERIFY_ARE_EQUAL(U("ftp"), ftp.scheme()); VERIFY_ARE_EQUAL(U(""), ftp.user_info()); VERIFY_ARE_EQUAL(U("ftp.is.co.za"), ftp.host()); VERIFY_ARE_EQUAL(0, ftp.port()); VERIFY_ARE_EQUAL(U("/rfc/rfc1808.txt"), ftp.path()); VERIFY_ARE_EQUAL(U(""), ftp.query()); VERIFY_ARE_EQUAL(U(""), ftp.fragment()); // TFS #371892 //uri ldap(U("ldap://[2001:db8::7]/?c=GB#objectClass?one")); //VERIFY_ARE_EQUAL(U("ldap"), ldap.scheme()); //VERIFY_ARE_EQUAL(U(""), ldap.user_info()); //VERIFY_ARE_EQUAL(U("2001:db8::7"), ldap.host()); //VERIFY_ARE_EQUAL(0, ldap.port()); //VERIFY_ARE_EQUAL(U("/"), ldap.path()); //VERIFY_ARE_EQUAL(U("c=GB"), ldap.query()); //VERIFY_ARE_EQUAL(U("objectClass?one"), ldap.fragment()); // We don't support anything scheme specific like in C# so // these common ones don't have a great experience yet. uri mailto(U("mailto:John.Doe@example.com")); VERIFY_ARE_EQUAL(U("mailto"), mailto.scheme()); VERIFY_ARE_EQUAL(U(""), mailto.user_info()); VERIFY_ARE_EQUAL(U(""), mailto.host()); VERIFY_ARE_EQUAL(0, mailto.port()); VERIFY_ARE_EQUAL(U("John.Doe@example.com"), mailto.path()); VERIFY_ARE_EQUAL(U(""), mailto.query()); VERIFY_ARE_EQUAL(U(""), mailto.fragment()); uri tel(U("tel:+1-816-555-1212")); VERIFY_ARE_EQUAL(U("tel"), tel.scheme()); VERIFY_ARE_EQUAL(U(""), tel.user_info()); VERIFY_ARE_EQUAL(U(""), tel.host()); VERIFY_ARE_EQUAL(0, tel.port()); VERIFY_ARE_EQUAL(U("+1-816-555-1212"), tel.path()); VERIFY_ARE_EQUAL(U(""), tel.query()); VERIFY_ARE_EQUAL(U(""), tel.fragment()); uri telnet(U("telnet://192.0.2.16:80/")); VERIFY_ARE_EQUAL(U("telnet"), telnet.scheme()); VERIFY_ARE_EQUAL(U(""), telnet.user_info()); VERIFY_ARE_EQUAL(U("192.0.2.16"), telnet.host()); VERIFY_ARE_EQUAL(80, telnet.port()); VERIFY_ARE_EQUAL(U("/"), telnet.path()); VERIFY_ARE_EQUAL(U(""), telnet.query()); VERIFY_ARE_EQUAL(U(""), telnet.fragment()); } TEST(user_info_string) { uri ftp(U("ftp://johndoe:testname@ftp.is.co.za/rfc/rfc1808.txt")); VERIFY_ARE_EQUAL(U("ftp"), ftp.scheme()); VERIFY_ARE_EQUAL(U("johndoe:testname"), ftp.user_info()); VERIFY_ARE_EQUAL(U("ftp.is.co.za"), ftp.host()); VERIFY_ARE_EQUAL(0, ftp.port()); VERIFY_ARE_EQUAL(U("/rfc/rfc1808.txt"), ftp.path()); VERIFY_ARE_EQUAL(U(""), ftp.query()); VERIFY_ARE_EQUAL(U(""), ftp.fragment()); } // Test query component can be seperated with '&' or ';'. TEST(query_seperated_with_semi_colon) { uri u(U("http://localhost/path1?key1=val1;key2=val2")); VERIFY_ARE_EQUAL(U("key1=val1;key2=val2"), u.query()); } } // SUITE(constructor_tests) }}}
32.651376
114
0.642737
fpelliccioni
c057107dfc15048f2e3953ddaad01a9aebe4120a
766
cpp
C++
random_contest/Y2019/practice_for_preli/FLifeOfPhi/Solution.cpp
Reshad-Hasan/problem_solving
1ef4c83fb329b5b51af9fa357db5bd39b537a9ea
[ "MIT" ]
17
2019-09-23T04:09:13.000Z
2020-07-27T02:51:51.000Z
random_contest/Y2019/practice_for_preli/FLifeOfPhi/Solution.cpp
Reshad-Hasan/problem_solving
1ef4c83fb329b5b51af9fa357db5bd39b537a9ea
[ "MIT" ]
15
2019-09-23T06:33:47.000Z
2020-06-04T18:55:45.000Z
random_contest/Y2019/practice_for_preli/FLifeOfPhi/Solution.cpp
Reshad-Hasan/problem_solving
1ef4c83fb329b5b51af9fa357db5bd39b537a9ea
[ "MIT" ]
16
2019-09-21T23:19:58.000Z
2020-06-18T07:26:39.000Z
// problem name: Life of Phi // problem link: https://toph.co/p/life-of-phi // contest link: https://toph.co/c/practice-icpc-2019-dhaka // author: reyad // time: (?) #include <bits/stdc++.h> using namespace std; #define N 1000000 long long int phi[N + 10], sum[N + 10]; int mark[N + 10] = {0}; int main() { sum[0] = 0; phi[0] = 0; for(int i=1; i<=N; i++) { phi[i] = i; sum[i] = sum[i-1] + i; } phi[1] = 1; mark[1] = 1; for(int i=2; i<=N; i++) { if(!mark[i]) { for(int j=i; j<=N; j+=i) { mark[j] = 1; phi[j] = (i - 1) * phi[j] / i; } } } int tc; scanf("%d", &tc); for(int cc=0; cc<tc; cc++) { int n; scanf("%d", &n); printf("%lld\n", sum[n-1] - n * phi[n] / 2); } return 0; }
17.409091
60
0.469974
Reshad-Hasan
c0599bf96e856e85af1d2b3bbbb0eb96ce47ee04
65
cpp
C++
VytUtils/InjectHook/InjectHook.cpp
Vyterm/VytHug
22b4c6708a23898d41fc49d604c54790b4f8c965
[ "MIT" ]
null
null
null
VytUtils/InjectHook/InjectHook.cpp
Vyterm/VytHug
22b4c6708a23898d41fc49d604c54790b4f8c965
[ "MIT" ]
null
null
null
VytUtils/InjectHook/InjectHook.cpp
Vyterm/VytHug
22b4c6708a23898d41fc49d604c54790b4f8c965
[ "MIT" ]
null
null
null
// InjectHook.cpp : 定义 DLL 应用程序的导出函数。 // #include "stdafx.h"
9.285714
38
0.630769
Vyterm
c05d95a857f69853734f34c056ad5b995340d66b
4,255
hpp
C++
teal/include/data/states.hpp
S6066/Teal
d2b4c4474be5caead2db956b3e11894472c8d465
[ "X11" ]
22
2016-07-12T14:17:21.000Z
2019-02-16T19:05:32.000Z
teal/include/data/states.hpp
S6066/Teal
d2b4c4474be5caead2db956b3e11894472c8d465
[ "X11" ]
null
null
null
teal/include/data/states.hpp
S6066/Teal
d2b4c4474be5caead2db956b3e11894472c8d465
[ "X11" ]
3
2016-12-02T06:38:04.000Z
2018-11-25T05:59:46.000Z
// Copyright (C) 2019 Samy Bensaid // This file is part of the Teal project. // For conditions of distribution and use, see copyright notice in LICENSE #pragma once #ifndef TEAL_STATES_HPP #define TEAL_STATES_HPP #include <Nazara/Core/String.hpp> #include <Nazara/Renderer/Texture.hpp> #include <Nazara/Lua/LuaState.hpp> #include <utility> #include <unordered_map> #include "data/elementdata.hpp" #include "def/typedef.hpp" #include "util/assert.hpp" #include "util/util.hpp" struct State { State() = default; virtual ~State() = default; virtual void serialize(const Nz::LuaState& state) = 0; struct FightInfo { std::unordered_map<Element, int> maximumDamage; // positive: damage, negative: heal std::unordered_map<Element, int> attackModifier; // positive: boost, negative: nerf std::unordered_map<Element, int> resistanceModifier; // positive: boost, negative: nerf int movementPointsDifference {}; int actionPointsDifference {}; enum StateFlag { None, Paralyzed, Sleeping, Confused } flags { None }; }; virtual FightInfo getFightInfo() = 0; }; enum class StateType { PoisonnedState, HealedState, WeaknessState, PowerState, ParalyzedState, SleepingState, ConfusedState }; inline Nz::String stateTypeToString(StateType stateType); inline StateType stringToStateType(Nz::String string); struct PoisonnedState : public State { inline PoisonnedState(const Nz::LuaState& state, int index = -1); std::pair<Element, unsigned> damage; virtual inline void serialize(const Nz::LuaState& state) override; virtual inline FightInfo getFightInfo() override; static StateType getStateType() { return StateType::PoisonnedState; } }; struct HealedState : public State { inline HealedState(const Nz::LuaState& state, int index = -1); std::pair<Element, unsigned> health; virtual inline void serialize(const Nz::LuaState& state) override; virtual inline FightInfo getFightInfo() override; static StateType getStateType() { return StateType::HealedState; } }; struct StatsModifierState : public State { inline StatsModifierState(const Nz::LuaState& state, int index = -1); std::unordered_map<Element, int> attack; std::unordered_map<Element, int> resistance; int movementPoints {}; int actionPoints {}; virtual inline void serialize(const Nz::LuaState& state) override; virtual inline FightInfo getFightInfo() override; }; struct WeaknessState : public StatsModifierState { inline WeaknessState(const Nz::LuaState& state, int index = -1) : StatsModifierState(state, index) {} virtual inline void serialize(const Nz::LuaState& state) override; static StateType getStateType() { return StateType::WeaknessState; } }; struct PowerState : public StatsModifierState { inline PowerState(const Nz::LuaState& state, int index = -1) : StatsModifierState(state, index) {} virtual inline void serialize(const Nz::LuaState& state) override; static StateType getStateType() { return StateType::PowerState; } }; struct ParalyzedState : public State { inline ParalyzedState(const Nz::LuaState& state, int index = -1) {} virtual inline void serialize(const Nz::LuaState& state) override; virtual inline FightInfo getFightInfo() override; static StateType getStateType() { return StateType::ParalyzedState; } }; struct SleepingState : public State // = paralyzed until attacked { inline SleepingState(const Nz::LuaState& state, int index = -1) {} virtual inline void serialize(const Nz::LuaState& state) override; virtual inline FightInfo getFightInfo() override; static StateType getStateType() { return StateType::SleepingState; } }; struct ConfusedState : public State // aka drunk { inline ConfusedState(const Nz::LuaState& state, int index = -1) {} virtual inline void serialize(const Nz::LuaState& state) override; virtual inline FightInfo getFightInfo() override; static StateType getStateType() { return StateType::ConfusedState; } }; #include "states.inl" #endif // TEAL_STATES_HPP
29.344828
109
0.704113
S6066
c06043f1c6e9aae3de0e009744bb9e8f4852c882
3,059
cc
C++
src/base/process/launch_unittest_mac.cc
Mr-Sheep/naiveproxy
9f6e9768295f6d1d41517a15a621d4756bd7d6be
[ "BSD-3-Clause" ]
6
2020-12-22T05:48:31.000Z
2022-02-08T19:49:49.000Z
src/base/process/launch_unittest_mac.cc
Mr-Sheep/naiveproxy
9f6e9768295f6d1d41517a15a621d4756bd7d6be
[ "BSD-3-Clause" ]
4
2020-05-22T18:36:43.000Z
2021-05-19T10:20:23.000Z
src/base/process/launch_unittest_mac.cc
Mr-Sheep/naiveproxy
9f6e9768295f6d1d41517a15a621d4756bd7d6be
[ "BSD-3-Clause" ]
2
2019-12-06T11:48:16.000Z
2021-09-16T04:44:47.000Z
// Copyright 2020 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 "base/process/launch.h" #include <errno.h> #include <stdio.h> #include <unistd.h> #include <string> #include <utility> #include <vector> #include "base/base_paths.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_file.h" #include "base/macros.h" #include "base/path_service.h" #include "base/posix/safe_strerror.h" #include "base/process/process.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" namespace base { namespace { void LaunchMacTest(const FilePath& exe_path, LaunchOptions options, const std::string& expected_output) { ScopedFD pipe_read_fd; ScopedFD pipe_write_fd; { int pipe_fds[2]; ASSERT_EQ(pipe(pipe_fds), 0) << safe_strerror(errno); pipe_read_fd.reset(pipe_fds[0]); pipe_write_fd.reset(pipe_fds[1]); } ScopedFILE pipe_read_file(fdopen(pipe_read_fd.get(), "r")); ASSERT_TRUE(pipe_read_file) << "fdopen: " << safe_strerror(errno); ignore_result(pipe_read_fd.release()); std::vector<std::string> argv(1, exe_path.value()); options.fds_to_remap.emplace_back(pipe_write_fd.get(), STDOUT_FILENO); Process process = LaunchProcess(argv, options); ASSERT_TRUE(process.IsValid()); pipe_write_fd.reset(); // Not ASSERT_TRUE because it's important to reach process.WaitForExit. std::string output; EXPECT_TRUE(ReadStreamToString(pipe_read_file.get(), &output)); int exit_code; ASSERT_TRUE(process.WaitForExit(&exit_code)); EXPECT_EQ(exit_code, 0); EXPECT_EQ(output, expected_output); } #if defined(ARCH_CPU_ARM64) // Bulk-disabled on arm64 for bot stabilization: https://crbug.com/1154345 #define MAYBE_LaunchMac DISABLED_LaunchMac #else #define MAYBE_LaunchMac LaunchMac #endif TEST(Process, MAYBE_LaunchMac) { FilePath data_dir; ASSERT_TRUE(PathService::Get(DIR_TEST_DATA, &data_dir)); data_dir = data_dir.AppendASCII("mac"); #if defined(ARCH_CPU_X86_64) static constexpr char kArchitecture[] = "x86_64"; #elif defined(ARCH_CPU_ARM64) static constexpr char kArchitecture[] = "arm64"; #endif LaunchOptions options; LaunchMacTest(data_dir.AppendASCII(kArchitecture), options, std::string(kArchitecture) + "\n"); #if defined(ARCH_CPU_ARM64) static constexpr char kUniversal[] = "universal"; LaunchMacTest(data_dir.AppendASCII(kUniversal), options, std::string(kArchitecture) + "\n"); static constexpr char kX86_64[] = "x86_64"; LaunchMacTest(data_dir.AppendASCII(kX86_64), options, std::string(kX86_64) + "\n"); options.launch_x86_64 = true; LaunchMacTest(data_dir.AppendASCII(kUniversal), options, std::string(kX86_64) + "\n"); LaunchMacTest(data_dir.AppendASCII(kX86_64), options, std::string(kX86_64) + "\n"); #endif // ARCH_CPU_ARM64 } } // namespace } // namespace base
29.133333
74
0.718535
Mr-Sheep
c061acfea2ab41f159ce61ec5ff9d8aba63a6791
9,794
cpp
C++
mllib-dal/src/main/native/LinearRegressionDALImpl.cpp
xwu99/oap-mllib
559ff5d67fe035ebe4fe2364e7a110b871acc3f1
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0" ]
11
2021-02-07T03:21:20.000Z
2022-03-22T06:43:47.000Z
mllib-dal/src/main/native/LinearRegressionDALImpl.cpp
xwu99/oap-mllib
559ff5d67fe035ebe4fe2364e7a110b871acc3f1
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0" ]
183
2020-12-28T10:07:57.000Z
2022-03-24T15:42:44.000Z
mllib-dal/src/main/native/LinearRegressionDALImpl.cpp
xwu99/oap-mllib
559ff5d67fe035ebe4fe2364e7a110b871acc3f1
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0" ]
10
2020-12-29T03:55:35.000Z
2022-03-24T13:54:14.000Z
/******************************************************************************* * Copyright 2020 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <chrono> #include <iostream> #include <vector> #include "OneCCL.h" #include "com_intel_oap_mllib_regression_LinearRegressionDALImpl.h" #include "service.h" using namespace std; using namespace daal; using namespace daal::algorithms; typedef double algorithmFPType; /* Algorithm floating-point type */ static NumericTablePtr linear_regression_compute(int rankId, ccl::communicator &comm, const NumericTablePtr &pData, const NumericTablePtr &pLabel, size_t nBlocks) { using daal::byte; linear_regression::training::Distributed<step1Local> localAlgorithm; /* Pass a training data set and dependent values to the algorithm */ localAlgorithm.input.set(linear_regression::training::data, pData); localAlgorithm.input.set(linear_regression::training::dependentVariables, pLabel); /* Train the multiple linear regression model on local nodes */ localAlgorithm.compute(); /* Serialize partial results required by step 2 */ services::SharedPtr<byte> serializedData; InputDataArchive dataArch; localAlgorithm.getPartialResult()->serialize(dataArch); size_t perNodeArchLength = dataArch.getSizeOfArchive(); serializedData = services::SharedPtr<byte>(new byte[perNodeArchLength * nBlocks]); byte *nodeResults = new byte[perNodeArchLength]; dataArch.copyArchiveToArray(nodeResults, perNodeArchLength); std::vector<size_t> aReceiveCount(comm.size(), perNodeArchLength); // 4 x "14016" /* Transfer partial results to step 2 on the root node */ ccl::gather((int8_t *)nodeResults, perNodeArchLength, (int8_t *)(serializedData.get()), perNodeArchLength, comm) .wait(); delete[] nodeResults; NumericTablePtr resultTable; if (rankId == ccl_root) { /* Create an algorithm object to build the final multiple linear * regression model on the master node */ linear_regression::training::Distributed<step2Master> masterAlgorithm; for (size_t i = 0; i < nBlocks; i++) { /* Deserialize partial results from step 1 */ OutputDataArchive dataArch(serializedData.get() + perNodeArchLength * i, perNodeArchLength); linear_regression::training::PartialResultPtr dataForStep2FromStep1 = linear_regression::training::PartialResultPtr( new linear_regression::training::PartialResult()); dataForStep2FromStep1->deserialize(dataArch); /* Set the local multiple linear regression model as input for the * master-node algorithm */ masterAlgorithm.input.add( linear_regression::training::partialModels, dataForStep2FromStep1); } /* Merge and finalizeCompute the multiple linear regression model on the * master node */ masterAlgorithm.compute(); masterAlgorithm.finalizeCompute(); /* Retrieve the algorithm results */ linear_regression::training::ResultPtr trainingResult = masterAlgorithm.getResult(); resultTable = trainingResult->get(linear_regression::training::model)->getBeta(); printNumericTable(resultTable, "Linear Regression first 20 columns of " "coefficients (w0, w1..wn):", 1, 20); } return resultTable; } static NumericTablePtr ridge_regression_compute( int rankId, ccl::communicator &comm, const NumericTablePtr &pData, const NumericTablePtr &pLabel, double regParam, size_t nBlocks) { using daal::byte; NumericTablePtr ridgeParams(new HomogenNumericTable<double>( 1, 1, NumericTable::doAllocate, regParam)); ridge_regression::training::Distributed<step1Local> localAlgorithm; localAlgorithm.parameter.ridgeParameters = ridgeParams; /* Pass a training data set and dependent values to the algorithm */ localAlgorithm.input.set(ridge_regression::training::data, pData); localAlgorithm.input.set(ridge_regression::training::dependentVariables, pLabel); /* Train the multiple ridge regression model on local nodes */ localAlgorithm.compute(); /* Serialize partial results required by step 2 */ services::SharedPtr<byte> serializedData; InputDataArchive dataArch; localAlgorithm.getPartialResult()->serialize(dataArch); size_t perNodeArchLength = dataArch.getSizeOfArchive(); // std::cout << "perNodeArchLength: " << perNodeArchLength << std::endl; serializedData = services::SharedPtr<byte>(new byte[perNodeArchLength * nBlocks]); byte *nodeResults = new byte[perNodeArchLength]; dataArch.copyArchiveToArray(nodeResults, perNodeArchLength); std::vector<size_t> aReceiveCount(comm.size(), perNodeArchLength); // 4 x "14016" /* Transfer partial results to step 2 on the root node */ ccl::gather((int8_t *)nodeResults, perNodeArchLength, (int8_t *)(serializedData.get()), perNodeArchLength, comm) .wait(); delete[] nodeResults; NumericTablePtr resultTable; if (rankId == ccl_root) { /* Create an algorithm object to build the final multiple ridge * regression model on the master node */ ridge_regression::training::Distributed<step2Master> masterAlgorithm; for (size_t i = 0; i < nBlocks; i++) { /* Deserialize partial results from step 1 */ OutputDataArchive dataArch(serializedData.get() + perNodeArchLength * i, perNodeArchLength); ridge_regression::training::PartialResultPtr dataForStep2FromStep1 = ridge_regression::training::PartialResultPtr( new ridge_regression::training::PartialResult()); dataForStep2FromStep1->deserialize(dataArch); /* Set the local multiple ridge regression model as input for the * master-node algorithm */ masterAlgorithm.input.add(ridge_regression::training::partialModels, dataForStep2FromStep1); } /* Merge and finalizeCompute the multiple ridge regression model on the * master node */ masterAlgorithm.compute(); masterAlgorithm.finalizeCompute(); /* Retrieve the algorithm results */ ridge_regression::training::ResultPtr trainingResult = masterAlgorithm.getResult(); resultTable = trainingResult->get(ridge_regression::training::model)->getBeta(); printNumericTable(resultTable, "Ridge Regression first 20 columns of " "coefficients (w0, w1..wn):", 1, 20); } return resultTable; } JNIEXPORT jlong JNICALL Java_com_intel_oap_mllib_regression_LinearRegressionDALImpl_cLinearRegressionTrainDAL( JNIEnv *env, jobject obj, jlong pNumTabData, jlong pNumTabLabel, jdouble regParam, jdouble elasticNetParam, jint executor_num, jint executor_cores, jobject resultObj) { ccl::communicator &comm = getComm(); size_t rankId = comm.rank(); NumericTablePtr pLabel = *((NumericTablePtr *)pNumTabLabel); NumericTablePtr pData = *((NumericTablePtr *)pNumTabData); // Set number of threads for oneDAL to use for each rank services::Environment::getInstance()->setNumberOfThreads(executor_cores); int nThreadsNew = services::Environment::getInstance()->getNumberOfThreads(); cout << "oneDAL (native): Number of CPU threads used: " << nThreadsNew << endl; NumericTablePtr resultTable; if (regParam == 0) { resultTable = linear_regression_compute(rankId, comm, pData, pLabel, executor_num); } else { resultTable = ridge_regression_compute(rankId, comm, pData, pLabel, regParam, executor_num); } if (rankId == ccl_root) { // Get the class of the result object jclass clazz = env->GetObjectClass(resultObj); // Get Field references jfieldID coeffNumericTableField = env->GetFieldID(clazz, "coeffNumericTable", "J"); NumericTablePtr *coeffvectors = new NumericTablePtr(resultTable); env->SetLongField(resultObj, coeffNumericTableField, (jlong)coeffvectors); // intercept is already in first column of coeffvectors return (jlong)coeffvectors; } else return (jlong)0; }
40.139344
86
0.62814
xwu99
c0648cc2fede9e1a5a6987079f8ead603991df61
5,678
cpp
C++
test/heuristic_search/test_RepeatedAStar.cpp
Forrest-Z/heuristic_search
8a1d2035483e7167baf362dc3de52320845f1109
[ "MIT" ]
null
null
null
test/heuristic_search/test_RepeatedAStar.cpp
Forrest-Z/heuristic_search
8a1d2035483e7167baf362dc3de52320845f1109
[ "MIT" ]
null
null
null
test/heuristic_search/test_RepeatedAStar.cpp
Forrest-Z/heuristic_search
8a1d2035483e7167baf362dc3de52320845f1109
[ "MIT" ]
1
2020-04-18T09:58:49.000Z
2020-04-18T09:58:49.000Z
/* heuristic_search library * * Copyright (c) 2016, * Maciej Przybylski <maciej.przybylski@mchtr.pw.edu.pl>, * Warsaw University of Technology. * All rights reserved. * */ #include <gtest/gtest.h> #include "heuristic_search/SearchLoop.h" #include "heuristic_search/StdOpenList.h" #include "heuristic_search/StdSearchSpace.h" #include "heuristic_search/SearchingAlgorithm.h" #include "heuristic_search/AStar.h" #include "heuristic_search/RepeatedAStar.h" #include "heuristic_search/DStarMain.h" #include "../heuristic_search/test_TestDomain.h" namespace test_heuristic_search{ typedef heuristic_search::SearchAlgorithmBegin< heuristic_search::DStarMain< heuristic_search::SearchLoop< heuristic_search::RepeatedAStar< heuristic_search::AStar< heuristic_search::HeuristicSearch< heuristic_search::StdOpenList< heuristic_search::StdSearchSpace< heuristic_search::SearchAlgorithmEnd<TestDomain> > > > > > > > > RepeatedAStarTestAlgorithm_t; TEST(test_RepeatedAStar, search_reinitialize_start) { TestDomain domain; RepeatedAStarTestAlgorithm_t::Algorithm_t algorithm(domain, heuristic_search::SearchingDirection::Backward, true); ASSERT_FALSE(algorithm.initialized); ASSERT_FALSE(algorithm.finished); ASSERT_FALSE(algorithm.found); ASSERT_TRUE(algorithm.search({1},{5})); ASSERT_TRUE(algorithm.start_node->visited); ASSERT_TRUE(algorithm.goal_node->visited); EXPECT_TRUE(algorithm.finished); EXPECT_TRUE(algorithm.found); std::vector<std::pair<TestDomain::StateActionState, TestDomain::Cost> > updated_actions; algorithm.reinitialize({0}, updated_actions); ASSERT_TRUE(algorithm.search()); EXPECT_TRUE(algorithm.finished); EXPECT_TRUE(algorithm.found); auto path = algorithm.getStatePath(); ASSERT_EQ(6, path.size()); EXPECT_EQ(TestDomain::State({0}),path[0]); EXPECT_EQ(TestDomain::State({1}),path[1]); EXPECT_EQ(TestDomain::State({2}),path[2]); EXPECT_EQ(TestDomain::State({3}),path[3]); EXPECT_EQ(TestDomain::State({4}),path[4]); EXPECT_EQ(TestDomain::State({5}),path[5]); } TEST(test_RepeatedAStar, search_cost_increase_backward) { TestDomain domain; RepeatedAStarTestAlgorithm_t::Algorithm_t algorithm(domain, heuristic_search::SearchingDirection::Backward, true); ASSERT_FALSE(algorithm.initialized); ASSERT_FALSE(algorithm.finished); ASSERT_FALSE(algorithm.found); ASSERT_TRUE(algorithm.search({0},{5})); ASSERT_TRUE(algorithm.start_node->visited); ASSERT_TRUE(algorithm.goal_node->visited); EXPECT_TRUE(algorithm.finished); EXPECT_TRUE(algorithm.found); TestDomain::StateActionState updated_action({2},{10*TestDomain::costFactor()},{3}); domain.updateAction(updated_action); std::vector<std::pair<TestDomain::StateActionState, TestDomain::Cost> > updated_actions; updated_actions.push_back(std::make_pair(updated_action, 1*TestDomain::costFactor())); algorithm.reinitialize({1}, updated_actions); ASSERT_TRUE(algorithm.search()); EXPECT_TRUE(algorithm.finished); EXPECT_TRUE(algorithm.found); auto path = algorithm.getStatePath(); ASSERT_EQ(5, path.size()); EXPECT_EQ(TestDomain::State({1}),path[0]); EXPECT_EQ(TestDomain::State({6}),path[1]); EXPECT_EQ(TestDomain::State({7}),path[2]); EXPECT_EQ(TestDomain::State({4}),path[3]); EXPECT_EQ(TestDomain::State({5}),path[4]); } TEST(test_RepeatedAStar, search_cost_increase_forward) { TestDomain domain; RepeatedAStarTestAlgorithm_t::Algorithm_t algorithm(domain, heuristic_search::SearchingDirection::Forward, true); ASSERT_FALSE(algorithm.initialized); ASSERT_FALSE(algorithm.finished); ASSERT_FALSE(algorithm.found); ASSERT_TRUE(algorithm.search({1},{5})); ASSERT_TRUE(algorithm.start_node->visited); ASSERT_TRUE(algorithm.goal_node->visited); EXPECT_TRUE(algorithm.finished); EXPECT_TRUE(algorithm.found); TestDomain::StateActionState updated_action({2},{10*TestDomain::costFactor()},{3}); domain.updateAction(updated_action); std::vector<std::pair<TestDomain::StateActionState, TestDomain::Cost> > updated_actions; updated_actions.push_back(std::make_pair(updated_action, 1*TestDomain::costFactor())); algorithm.reinitialize({1}, updated_actions); ASSERT_TRUE(algorithm.search()); EXPECT_TRUE(algorithm.finished); EXPECT_TRUE(algorithm.found); auto path = algorithm.getStatePath(); ASSERT_EQ(5, path.size()); EXPECT_EQ(TestDomain::State({1}),path[0]); EXPECT_EQ(TestDomain::State({6}),path[1]); EXPECT_EQ(TestDomain::State({7}),path[2]); EXPECT_EQ(TestDomain::State({4}),path[3]); EXPECT_EQ(TestDomain::State({5}),path[4]); } TEST(test_RepeatedAStar, main_backward) { TestDomain domain; RepeatedAStarTestAlgorithm_t::Algorithm_t algorithm(domain, heuristic_search::SearchingDirection::Backward); algorithm.main({0},{5}); EXPECT_EQ(TestDomain::State(5), algorithm.current_state); } TEST(test_RepeatedAStar, main_forward) { TestDomain domain; RepeatedAStarTestAlgorithm_t::Algorithm_t algorithm(domain, heuristic_search::SearchingDirection::Forward); algorithm.main({0},{5}); EXPECT_EQ(TestDomain::State(5), algorithm.current_state); } }
30.691892
102
0.689503
Forrest-Z
c06502bee9f477c1f768452c8e583ab0d9b47d8d
5,814
hpp
C++
Nacro/SDK/FN_News_classes.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_News_classes.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_News_classes.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
#pragma once // Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // WidgetBlueprintGeneratedClass News.News_C // 0x0048 (0x0428 - 0x03E0) class UNews_C : public UCommonActivatablePanel { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x03E0(0x0008) (Transient, DuplicateTransient) class UIconTextButton_C* CloseButton; // 0x03E8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UScrollBox* DescriptionScroll; // 0x03F0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class ULightbox_C* Lightbox; // 0x03F8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UImage* MainIcon; // 0x0400(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UScrollBox* ScrollBoxEntries; // 0x0408(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UCommonTextBlock* TextDescription; // 0x0410(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UCommonTextBlock* Title; // 0x0418(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UCommonButtonGroup* ButtonGroup; // 0x0420(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass News.News_C"); return ptr; } void UpdateInfoPanel(const struct FText& BodyText); void Init(); void PopulateEntries(bool* IsEmpty); void AddEntry(const struct FText& inEntryText); void BndEvt__CloseButton_K2Node_ComponentBoundEvent_21_CommonButtonClicked__DelegateSignature(class UCommonButton* Button); void Construct(); void ExecuteUbergraph_News(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
111.807692
644
0.74011
Milxnor
c0665160623b93cb0f507861f30d7841f0bb0eb6
2,950
hpp
C++
include/veritacpp/dsl/math/variable.hpp
Nekrolm/veritacpp
015c9dc2027154c8754a1b61040ce6d0bf807a47
[ "MIT" ]
null
null
null
include/veritacpp/dsl/math/variable.hpp
Nekrolm/veritacpp
015c9dc2027154c8754a1b61040ce6d0bf807a47
[ "MIT" ]
null
null
null
include/veritacpp/dsl/math/variable.hpp
Nekrolm/veritacpp
015c9dc2027154c8754a1b61040ce6d0bf807a47
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> #include <veritacpp/dsl/math/core_concepts.hpp> #include <veritacpp/dsl/math/constants.hpp> namespace veritacpp::dsl::math { template <uint64_t N> struct Variable; template<uint64_t N, Functional F> struct VariableBindingHolder { F f; static constexpr auto VariableID = N; constexpr VariableBindingHolder(Variable<N>, F f) : f{f} {} constexpr Functional auto operator()(Variable<N>) const { return f; } }; template <uint64_t N, Functional F> VariableBindingHolder(Variable<N>, F) -> VariableBindingHolder<N, F>; template <class T> struct IsVariableBinding : std::false_type {}; template <uint64_t N, Functional F> struct IsVariableBinding<VariableBindingHolder<N, F>> : std::true_type {}; template <class T> concept VariableBinding = IsVariableBinding<T>::value; template <VariableBinding... Var> struct VariableBindingGroup : Var... { using Var::operator()...; static constexpr auto MaxVariableID = std::max({ Var::VariableID... }); template<uint64_t N> requires ((N != Var::VariableID) && ...) constexpr Functional auto operator () (Variable<N> x) const { return x; } }; template <VariableBinding... Var> VariableBindingGroup(Var...) -> VariableBindingGroup<Var...>; template <uint64_t N> struct Variable : BasicFunction { static constexpr auto Id = N; constexpr Arithmetic auto operator()(Arithmetic auto... args) const requires (sizeof...(args) > N) { return std::get<N>(std::make_tuple(args...)); } template <Functional F> constexpr auto operator = (F f) const { return VariableBindingGroup { VariableBindingHolder<N, F>(*this, f) }; } }; template <uint64_t N, uint64_t M> requires (N == M) Functional auto operator - (Variable<N>, Variable<M>) { return kZero; } template <uint64_t N, uint64_t M> requires (N == M) Functional auto operator / (Variable<N>, Variable<M>) { return kOne; } // Veriable<N> requires at least N+1 arguments static_assert(!(NVariablesFunctional<2, Variable<2>>)); template <VariableBinding... Var> constexpr bool all_unique_variables = []<uint64_t... idx>( std::integer_sequence<uint64_t, idx...>){ constexpr std::array arr { idx...}; return ((std::ranges::count(arr, idx) == 1) && ...); }(std::integer_sequence<uint64_t, Var::VariableID...>{}); template <VariableBinding... Var> consteval bool group_contains_binding(VariableBindingGroup<Var...>, VariableBinding auto v) { return ((Var::VariableID == v.VariableID) || ...); } template<VariableBinding... V1, VariableBinding... V2> constexpr auto operator , (VariableBindingGroup<V1...> v1, VariableBindingGroup<V2...> v2) { static_assert(all_unique_variables<V1..., V2...>, "rebinding same variable twice is not allowed"); return VariableBindingGroup { static_cast<V1>(v1)..., static_cast<V2>(v2)... }; } }
25.652174
93
0.673898
Nekrolm
c06b1abc92f3063c9f4f2a7d1dcd0fb890816424
29,813
cc
C++
chrome/browser/ui/views/passwords/manage_passwords_bubble_view.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
chrome/browser/ui/views/passwords/manage_passwords_bubble_view.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
chrome/browser/ui/views/passwords/manage_passwords_bubble_view.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/passwords/manage_passwords_bubble_view.h" #include "base/macros.h" #include "base/strings/utf_string_conversions.h" #include "base/timer/timer.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/exclusive_access/fullscreen_controller.h" #include "chrome/browser/ui/passwords/password_dialog_prompts.h" #include "chrome/browser/ui/passwords/passwords_model_delegate.h" #include "chrome/browser/ui/views/desktop_ios_promotion/desktop_ios_promotion_view.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/passwords/credentials_item_view.h" #include "chrome/browser/ui/views/passwords/credentials_selection_view.h" #include "chrome/browser/ui/views/passwords/manage_password_items_view.h" #include "chrome/browser/ui/views/passwords/manage_passwords_icon_views.h" #include "chrome/grit/generated_resources.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/user_metrics.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/material_design/material_design_controller.h" #include "ui/base/resource/resource_bundle.h" #include "ui/views/controls/button/blue_button.h" #include "ui/views/controls/button/md_text_button.h" #include "ui/views/controls/link.h" #include "ui/views/controls/link_listener.h" #include "ui/views/controls/separator.h" #include "ui/views/controls/styled_label.h" #include "ui/views/controls/styled_label_listener.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/layout/layout_constants.h" #include "ui/views/widget/widget.h" int ManagePasswordsBubbleView::auto_signin_toast_timeout_ = 3; // Helpers -------------------------------------------------------------------- namespace { enum ColumnSetType { // | | (FILL, FILL) | | // Used for the bubble's header, the credentials list, and for simple // messages like "No passwords". SINGLE_VIEW_COLUMN_SET, // | | (TRAILING, CENTER) | | (TRAILING, CENTER) | | // Used for buttons at the bottom of the bubble which should nest at the // bottom-right corner. DOUBLE_BUTTON_COLUMN_SET, // | | (LEADING, CENTER) | | (TRAILING, CENTER) | | // Used for buttons at the bottom of the bubble which should occupy // the corners. LINK_BUTTON_COLUMN_SET, // | | (TRAILING, CENTER) | | // Used when there is only one button which should next at the bottom-right // corner. SINGLE_BUTTON_COLUMN_SET, // | | (LEADING, CENTER) | | (TRAILING, CENTER) | | (TRAILING, CENTER) | | // Used when there are three buttons. TRIPLE_BUTTON_COLUMN_SET, }; enum TextRowType { ROW_SINGLE, ROW_MULTILINE }; // Construct an appropriate ColumnSet for the given |type|, and add it // to |layout|. void BuildColumnSet(views::GridLayout* layout, ColumnSetType type) { views::ColumnSet* column_set = layout->AddColumnSet(type); int full_width = ManagePasswordsBubbleView::kDesiredBubbleWidth; switch (type) { case SINGLE_VIEW_COLUMN_SET: column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 0, views::GridLayout::FIXED, full_width, 0); break; case DOUBLE_BUTTON_COLUMN_SET: column_set->AddColumn(views::GridLayout::TRAILING, views::GridLayout::CENTER, 1, views::GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, views::kRelatedButtonHSpacing); column_set->AddColumn(views::GridLayout::TRAILING, views::GridLayout::CENTER, 0, views::GridLayout::USE_PREF, 0, 0); break; case LINK_BUTTON_COLUMN_SET: column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::CENTER, 1, views::GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, views::kRelatedButtonHSpacing); column_set->AddColumn(views::GridLayout::TRAILING, views::GridLayout::CENTER, 0, views::GridLayout::USE_PREF, 0, 0); break; case SINGLE_BUTTON_COLUMN_SET: column_set->AddColumn(views::GridLayout::TRAILING, views::GridLayout::CENTER, 1, views::GridLayout::USE_PREF, 0, 0); break; case TRIPLE_BUTTON_COLUMN_SET: column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::CENTER, 1, views::GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, views::kRelatedButtonHSpacing); column_set->AddColumn(views::GridLayout::TRAILING, views::GridLayout::CENTER, 0, views::GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, views::kRelatedButtonHSpacing); column_set->AddColumn(views::GridLayout::TRAILING, views::GridLayout::CENTER, 0, views::GridLayout::USE_PREF, 0, 0); break; } } views::StyledLabel::RangeStyleInfo GetLinkStyle() { auto result = views::StyledLabel::RangeStyleInfo::CreateForLink(); result.disable_line_wrapping = false; return result; } // If a special title is required (i.e. one that contains links), creates a // title view and a row for it in |layout|. // TODO(estade): this should be removed and a replaced by a normal title (via // GetWindowTitle). void AddTitleRowWithLink(views::GridLayout* layout, ManagePasswordsBubbleModel* model, views::StyledLabelListener* listener) { if (model->title_brand_link_range().is_empty()) return; views::StyledLabel* title_label = new views::StyledLabel(model->title(), listener); title_label->SetBaseFontList( ui::ResourceBundle::GetSharedInstance().GetFontList( ui::ResourceBundle::MediumFont)); title_label->AddStyleRange(model->title_brand_link_range(), GetLinkStyle()); layout->StartRow(0, SINGLE_VIEW_COLUMN_SET); layout->AddView(title_label); layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing); } } // namespace // ManagePasswordsBubbleView::AutoSigninView ---------------------------------- // A view containing just one credential that was used for for automatic signing // in. class ManagePasswordsBubbleView::AutoSigninView : public views::View, public views::ButtonListener, public views::WidgetObserver { public: explicit AutoSigninView(ManagePasswordsBubbleView* parent); private: // views::ButtonListener: void ButtonPressed(views::Button* sender, const ui::Event& event) override; // views::WidgetObserver: // Tracks the state of the browser window. void OnWidgetActivationChanged(views::Widget* widget, bool active) override; void OnWidgetClosing(views::Widget* widget) override; void OnTimer(); static base::TimeDelta GetTimeout() { return base::TimeDelta::FromSeconds( ManagePasswordsBubbleView::auto_signin_toast_timeout_); } base::OneShotTimer timer_; ManagePasswordsBubbleView* parent_; ScopedObserver<views::Widget, views::WidgetObserver> observed_browser_; DISALLOW_COPY_AND_ASSIGN(AutoSigninView); }; ManagePasswordsBubbleView::AutoSigninView::AutoSigninView( ManagePasswordsBubbleView* parent) : parent_(parent), observed_browser_(this) { SetLayoutManager(new views::FillLayout); const autofill::PasswordForm& form = parent_->model()->pending_password(); CredentialsItemView* credential = new CredentialsItemView( this, base::string16(), l10n_util::GetStringFUTF16(IDS_MANAGE_PASSWORDS_AUTO_SIGNIN_TITLE, form.username_value), kButtonHoverColor, &form, parent_->model()->GetProfile()->GetRequestContext()); credential->SetEnabled(false); AddChildView(credential); // Setup the observer and maybe start the timer. Browser* browser = chrome::FindBrowserWithWebContents(parent_->web_contents()); DCHECK(browser); BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser); observed_browser_.Add(browser_view->GetWidget()); if (browser_view->IsActive()) timer_.Start(FROM_HERE, GetTimeout(), this, &AutoSigninView::OnTimer); } void ManagePasswordsBubbleView::AutoSigninView::ButtonPressed( views::Button* sender, const ui::Event& event) { NOTREACHED(); } void ManagePasswordsBubbleView::AutoSigninView::OnWidgetActivationChanged( views::Widget* widget, bool active) { if (active && !timer_.IsRunning()) timer_.Start(FROM_HERE, GetTimeout(), this, &AutoSigninView::OnTimer); } void ManagePasswordsBubbleView::AutoSigninView::OnWidgetClosing( views::Widget* widget) { observed_browser_.RemoveAll(); } void ManagePasswordsBubbleView::AutoSigninView::OnTimer() { parent_->model()->OnAutoSignInToastTimeout(); parent_->CloseBubble(); } // ManagePasswordsBubbleView::PendingView ------------------------------------- // A view offering the user the ability to save credentials. Contains a // single ManagePasswordItemsView, along with a "Save Passwords" button // and a "Never" button. class ManagePasswordsBubbleView::PendingView : public views::View, public views::ButtonListener, public views::StyledLabelListener { public: explicit PendingView(ManagePasswordsBubbleView* parent); ~PendingView() override; private: // views::ButtonListener: void ButtonPressed(views::Button* sender, const ui::Event& event) override; // views::StyledLabelListener: void StyledLabelLinkClicked(views::StyledLabel* label, const gfx::Range& range, int event_flags) override; ManagePasswordsBubbleView* parent_; views::Button* save_button_; views::Button* never_button_; DISALLOW_COPY_AND_ASSIGN(PendingView); }; ManagePasswordsBubbleView::PendingView::PendingView( ManagePasswordsBubbleView* parent) : parent_(parent) { views::GridLayout* layout = new views::GridLayout(this); layout->set_minimum_size(gfx::Size(kDesiredBubbleWidth, 0)); SetLayoutManager(layout); // Create the pending credential item, save button and refusal combobox. ManagePasswordItemsView* item = nullptr; if (!parent->model()->pending_password().username_value.empty()) { item = new ManagePasswordItemsView(parent_->model(), &parent->model()->pending_password()); } save_button_ = views::MdTextButton::CreateSecondaryUiBlueButton( this, l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_SAVE_BUTTON)); never_button_ = views::MdTextButton::CreateSecondaryUiButton( this, l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_BUBBLE_BLACKLIST_BUTTON)); // Title row. BuildColumnSet(layout, SINGLE_VIEW_COLUMN_SET); AddTitleRowWithLink(layout, parent_->model(), this); // Credential row. if (item) { layout->StartRow(0, SINGLE_VIEW_COLUMN_SET); layout->AddView(item); layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing); } // Button row. BuildColumnSet(layout, DOUBLE_BUTTON_COLUMN_SET); layout->StartRow(0, DOUBLE_BUTTON_COLUMN_SET); layout->AddView(save_button_); layout->AddView(never_button_); parent_->set_initially_focused_view(save_button_); } ManagePasswordsBubbleView::PendingView::~PendingView() { } void ManagePasswordsBubbleView::PendingView::ButtonPressed( views::Button* sender, const ui::Event& event) { if (sender == save_button_) { parent_->model()->OnSaveClicked(); if (parent_->model()->ReplaceToShowPromotionIfNeeded()) { parent_->Refresh(); return; } } else if (sender == never_button_) { parent_->model()->OnNeverForThisSiteClicked(); } else { NOTREACHED(); } parent_->CloseBubble(); } void ManagePasswordsBubbleView::PendingView::StyledLabelLinkClicked( views::StyledLabel* label, const gfx::Range& range, int event_flags) { DCHECK_EQ(range, parent_->model()->title_brand_link_range()); parent_->model()->OnBrandLinkClicked(); } // ManagePasswordsBubbleView::ManageView -------------------------------------- // A view offering the user a list of their currently saved credentials // for the current page, along with a "Manage passwords" link and a // "Done" button. class ManagePasswordsBubbleView::ManageView : public views::View, public views::ButtonListener, public views::LinkListener { public: explicit ManageView(ManagePasswordsBubbleView* parent); ~ManageView() override; private: // views::ButtonListener: void ButtonPressed(views::Button* sender, const ui::Event& event) override; // views::LinkListener: void LinkClicked(views::Link* source, int event_flags) override; ManagePasswordsBubbleView* parent_; views::Link* manage_link_; views::Button* done_button_; DISALLOW_COPY_AND_ASSIGN(ManageView); }; ManagePasswordsBubbleView::ManageView::ManageView( ManagePasswordsBubbleView* parent) : parent_(parent) { views::GridLayout* layout = new views::GridLayout(this); layout->set_minimum_size(gfx::Size(kDesiredBubbleWidth, 0)); SetLayoutManager(layout); // If we have a list of passwords to store for the current site, display // them to the user for management. Otherwise, render a "No passwords for // this site" message. BuildColumnSet(layout, SINGLE_VIEW_COLUMN_SET); if (!parent_->model()->local_credentials().empty()) { ManagePasswordItemsView* item = new ManagePasswordItemsView( parent_->model(), &parent_->model()->local_credentials()); layout->StartRowWithPadding(0, SINGLE_VIEW_COLUMN_SET, 0, views::kUnrelatedControlVerticalSpacing); layout->AddView(item); } else { views::Label* empty_label = new views::Label( l10n_util::GetStringUTF16(IDS_MANAGE_PASSWORDS_NO_PASSWORDS)); empty_label->SetMultiLine(true); empty_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); empty_label->SetFontList( ui::ResourceBundle::GetSharedInstance().GetFontList( ui::ResourceBundle::SmallFont)); layout->StartRowWithPadding(0, SINGLE_VIEW_COLUMN_SET, 0, views::kUnrelatedControlVerticalSpacing); layout->AddView(empty_label); } // Then add the "manage passwords" link and "Done" button. manage_link_ = new views::Link(parent_->model()->manage_link()); manage_link_->SetHorizontalAlignment(gfx::ALIGN_LEFT); manage_link_->SetUnderline(false); manage_link_->set_listener(this); done_button_ = views::MdTextButton::CreateSecondaryUiButton( this, l10n_util::GetStringUTF16(IDS_DONE)); BuildColumnSet(layout, LINK_BUTTON_COLUMN_SET); layout->StartRowWithPadding(0, LINK_BUTTON_COLUMN_SET, 0, views::kUnrelatedControlVerticalSpacing); layout->AddView(manage_link_); layout->AddView(done_button_); parent_->set_initially_focused_view(done_button_); } ManagePasswordsBubbleView::ManageView::~ManageView() { } void ManagePasswordsBubbleView::ManageView::ButtonPressed( views::Button* sender, const ui::Event& event) { DCHECK(sender == done_button_); parent_->model()->OnDoneClicked(); parent_->CloseBubble(); } void ManagePasswordsBubbleView::ManageView::LinkClicked(views::Link* source, int event_flags) { DCHECK_EQ(source, manage_link_); parent_->model()->OnManageLinkClicked(); parent_->CloseBubble(); } // ManagePasswordsBubbleView::SaveConfirmationView ---------------------------- // A view confirming to the user that a password was saved and offering a link // to the Google account manager. class ManagePasswordsBubbleView::SaveConfirmationView : public views::View, public views::ButtonListener, public views::StyledLabelListener { public: explicit SaveConfirmationView(ManagePasswordsBubbleView* parent); ~SaveConfirmationView() override; private: // views::ButtonListener: void ButtonPressed(views::Button* sender, const ui::Event& event) override; // views::StyledLabelListener implementation void StyledLabelLinkClicked(views::StyledLabel* label, const gfx::Range& range, int event_flags) override; ManagePasswordsBubbleView* parent_; views::Button* ok_button_; DISALLOW_COPY_AND_ASSIGN(SaveConfirmationView); }; ManagePasswordsBubbleView::SaveConfirmationView::SaveConfirmationView( ManagePasswordsBubbleView* parent) : parent_(parent) { views::GridLayout* layout = new views::GridLayout(this); layout->set_minimum_size(gfx::Size(kDesiredBubbleWidth, 0)); SetLayoutManager(layout); views::StyledLabel* confirmation = new views::StyledLabel(parent_->model()->save_confirmation_text(), this); confirmation->SetBaseFontList( ui::ResourceBundle::GetSharedInstance().GetFontList( ui::ResourceBundle::SmallFont)); confirmation->AddStyleRange( parent_->model()->save_confirmation_link_range(), GetLinkStyle()); BuildColumnSet(layout, SINGLE_VIEW_COLUMN_SET); layout->StartRow(0, SINGLE_VIEW_COLUMN_SET); layout->AddView(confirmation); ok_button_ = views::MdTextButton::CreateSecondaryUiButton( this, l10n_util::GetStringUTF16(IDS_OK)); BuildColumnSet(layout, SINGLE_BUTTON_COLUMN_SET); layout->StartRowWithPadding( 0, SINGLE_BUTTON_COLUMN_SET, 0, views::kRelatedControlVerticalSpacing); layout->AddView(ok_button_); parent_->set_initially_focused_view(ok_button_); } ManagePasswordsBubbleView::SaveConfirmationView::~SaveConfirmationView() { } void ManagePasswordsBubbleView::SaveConfirmationView::StyledLabelLinkClicked( views::StyledLabel* label, const gfx::Range& range, int event_flags) { DCHECK_EQ(range, parent_->model()->save_confirmation_link_range()); parent_->model()->OnManageLinkClicked(); parent_->CloseBubble(); } void ManagePasswordsBubbleView::SaveConfirmationView::ButtonPressed( views::Button* sender, const ui::Event& event) { DCHECK_EQ(sender, ok_button_); parent_->model()->OnOKClicked(); parent_->CloseBubble(); } // ManagePasswordsBubbleView::SignInPromoView --------------------------------- // A view that offers user to sign in to Chrome. class ManagePasswordsBubbleView::SignInPromoView : public views::View, public views::ButtonListener { public: explicit SignInPromoView(ManagePasswordsBubbleView* parent); private: // views::ButtonListener: void ButtonPressed(views::Button* sender, const ui::Event& event) override; ManagePasswordsBubbleView* parent_; views::Button* signin_button_; views::Button* no_button_; DISALLOW_COPY_AND_ASSIGN(SignInPromoView); }; ManagePasswordsBubbleView::SignInPromoView::SignInPromoView( ManagePasswordsBubbleView* parent) : parent_(parent) { views::GridLayout* layout = new views::GridLayout(this); layout->set_minimum_size(gfx::Size(kDesiredBubbleWidth, 0)); SetLayoutManager(layout); signin_button_ = views::MdTextButton::CreateSecondaryUiBlueButton( this, l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_SIGNIN_PROMO_SIGN_IN)); no_button_ = views::MdTextButton::CreateSecondaryUiButton( this, l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_SIGNIN_PROMO_NO_THANKS)); // Button row. BuildColumnSet(layout, DOUBLE_BUTTON_COLUMN_SET); layout->StartRow(0, DOUBLE_BUTTON_COLUMN_SET); layout->AddView(signin_button_); layout->AddView(no_button_); parent_->set_initially_focused_view(signin_button_); content::RecordAction( base::UserMetricsAction("Signin_Impression_FromPasswordBubble")); } void ManagePasswordsBubbleView::SignInPromoView::ButtonPressed( views::Button* sender, const ui::Event& event) { if (sender == signin_button_) parent_->model()->OnSignInToChromeClicked(); else if (sender == no_button_) parent_->model()->OnSkipSignInClicked(); else NOTREACHED(); parent_->CloseBubble(); } // ManagePasswordsBubbleView::UpdatePendingView ------------------------------- // A view offering the user the ability to update credentials. Contains a // single ManagePasswordItemsView (in case of one credentials) or // CredentialsSelectionView otherwise, along with a "Update Passwords" button // and a rejection button. class ManagePasswordsBubbleView::UpdatePendingView : public views::View, public views::ButtonListener, public views::StyledLabelListener { public: explicit UpdatePendingView(ManagePasswordsBubbleView* parent); ~UpdatePendingView() override; private: // views::ButtonListener: void ButtonPressed(views::Button* sender, const ui::Event& event) override; // views::StyledLabelListener: void StyledLabelLinkClicked(views::StyledLabel* label, const gfx::Range& range, int event_flags) override; ManagePasswordsBubbleView* parent_; CredentialsSelectionView* selection_view_; views::Button* update_button_; views::Button* nope_button_; DISALLOW_COPY_AND_ASSIGN(UpdatePendingView); }; ManagePasswordsBubbleView::UpdatePendingView::UpdatePendingView( ManagePasswordsBubbleView* parent) : parent_(parent), selection_view_(nullptr) { views::GridLayout* layout = new views::GridLayout(this); layout->set_minimum_size(gfx::Size(kDesiredBubbleWidth, 0)); SetLayoutManager(layout); // Create the pending credential item, update button. View* item = nullptr; if (parent->model()->ShouldShowMultipleAccountUpdateUI()) { selection_view_ = new CredentialsSelectionView(parent->model()); item = selection_view_; } else { item = new ManagePasswordItemsView(parent_->model(), &parent->model()->pending_password()); } nope_button_ = views::MdTextButton::CreateSecondaryUiButton( this, l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_CANCEL_BUTTON)); update_button_ = views::MdTextButton::CreateSecondaryUiBlueButton( this, l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_UPDATE_BUTTON)); // Title row. BuildColumnSet(layout, SINGLE_VIEW_COLUMN_SET); AddTitleRowWithLink(layout, parent_->model(), this); // Credential row. layout->StartRow(0, SINGLE_VIEW_COLUMN_SET); layout->AddView(item); // Button row. BuildColumnSet(layout, DOUBLE_BUTTON_COLUMN_SET); layout->StartRowWithPadding(0, DOUBLE_BUTTON_COLUMN_SET, 0, views::kUnrelatedControlVerticalSpacing); layout->AddView(update_button_); layout->AddView(nope_button_); parent_->set_initially_focused_view(update_button_); } ManagePasswordsBubbleView::UpdatePendingView::~UpdatePendingView() {} void ManagePasswordsBubbleView::UpdatePendingView::ButtonPressed( views::Button* sender, const ui::Event& event) { DCHECK(sender == update_button_ || sender == nope_button_); if (sender == update_button_) { if (selection_view_) { // Multi account case. parent_->model()->OnUpdateClicked( *selection_view_->GetSelectedCredentials()); } else { parent_->model()->OnUpdateClicked(parent_->model()->pending_password()); } } else { parent_->model()->OnNopeUpdateClicked(); } parent_->CloseBubble(); } void ManagePasswordsBubbleView::UpdatePendingView::StyledLabelLinkClicked( views::StyledLabel* label, const gfx::Range& range, int event_flags) { DCHECK_EQ(range, parent_->model()->title_brand_link_range()); parent_->model()->OnBrandLinkClicked(); } // ManagePasswordsBubbleView -------------------------------------------------- // static ManagePasswordsBubbleView* ManagePasswordsBubbleView::manage_passwords_bubble_ = NULL; // static void ManagePasswordsBubbleView::ShowBubble( content::WebContents* web_contents, DisplayReason reason) { Browser* browser = chrome::FindBrowserWithWebContents(web_contents); DCHECK(browser); DCHECK(browser->window()); DCHECK(!manage_passwords_bubble_ || !manage_passwords_bubble_->GetWidget()->IsVisible()); BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser); bool is_fullscreen = browser_view->IsFullscreen(); views::View* anchor_view = nullptr; if (!is_fullscreen) { if (ui::MaterialDesignController::IsSecondaryUiMaterial()) { anchor_view = browser_view->GetLocationBarView(); } else { anchor_view = browser_view->GetLocationBarView()->manage_passwords_icon_view(); } } manage_passwords_bubble_ = new ManagePasswordsBubbleView( web_contents, anchor_view, reason); if (is_fullscreen) manage_passwords_bubble_->set_parent_window(web_contents->GetNativeView()); views::Widget* manage_passwords_bubble_widget = views::BubbleDialogDelegateView::CreateBubble(manage_passwords_bubble_); if (anchor_view) { manage_passwords_bubble_widget->AddObserver( browser_view->GetLocationBarView()->manage_passwords_icon_view()); } // Adjust for fullscreen after creation as it relies on the content size. if (is_fullscreen) { manage_passwords_bubble_->AdjustForFullscreen( browser_view->GetBoundsInScreen()); } manage_passwords_bubble_->ShowForReason(reason); } // static void ManagePasswordsBubbleView::CloseCurrentBubble() { if (manage_passwords_bubble_) manage_passwords_bubble_->CloseBubble(); } // static void ManagePasswordsBubbleView::ActivateBubble() { DCHECK(manage_passwords_bubble_); DCHECK(manage_passwords_bubble_->GetWidget()->IsVisible()); manage_passwords_bubble_->GetWidget()->Activate(); } content::WebContents* ManagePasswordsBubbleView::web_contents() const { return model_.GetWebContents(); } ManagePasswordsBubbleView::ManagePasswordsBubbleView( content::WebContents* web_contents, views::View* anchor_view, DisplayReason reason) : LocationBarBubbleDelegateView(anchor_view, web_contents), model_(PasswordsModelDelegateFromWebContents(web_contents), reason == AUTOMATIC ? ManagePasswordsBubbleModel::AUTOMATIC : ManagePasswordsBubbleModel::USER_ACTION), initially_focused_view_(nullptr) { mouse_handler_.reset(new WebContentMouseHandler(this, this->web_contents())); } ManagePasswordsBubbleView::~ManagePasswordsBubbleView() { if (manage_passwords_bubble_ == this) manage_passwords_bubble_ = NULL; } views::View* ManagePasswordsBubbleView::GetInitiallyFocusedView() { return initially_focused_view_; } void ManagePasswordsBubbleView::Init() { SetLayoutManager(new views::FillLayout); CreateChild(); } void ManagePasswordsBubbleView::CloseBubble() { mouse_handler_.reset(); LocationBarBubbleDelegateView::CloseBubble(); } base::string16 ManagePasswordsBubbleView::GetWindowTitle() const { return model_.title(); } bool ManagePasswordsBubbleView::ShouldShowWindowTitle() const { // Since bubble titles don't support links, fall back to a custom title view // if we need to show a link. Only use the normal title path if there's no // link. return model_.title_brand_link_range().is_empty(); } bool ManagePasswordsBubbleView::ShouldShowCloseButton() const { return model_.state() == password_manager::ui::PENDING_PASSWORD_STATE || model_.state() == password_manager::ui::CHROME_SIGN_IN_PROMO_STATE || model_.state() == password_manager::ui::CHROME_DESKTOP_IOS_PROMO_STATE; } void ManagePasswordsBubbleView::Refresh() { RemoveAllChildViews(true); initially_focused_view_ = NULL; CreateChild(); // Show/hide the close button. GetWidget()->non_client_view()->ResetWindowControls(); GetWidget()->UpdateWindowTitle(); SizeToContents(); } void ManagePasswordsBubbleView::CreateChild() { if (model_.state() == password_manager::ui::PENDING_PASSWORD_STATE) { AddChildView(new PendingView(this)); } else if (model_.state() == password_manager::ui::PENDING_PASSWORD_UPDATE_STATE) { AddChildView(new UpdatePendingView(this)); } else if (model_.state() == password_manager::ui::CONFIRMATION_STATE) { AddChildView(new SaveConfirmationView(this)); } else if (model_.state() == password_manager::ui::AUTO_SIGNIN_STATE) { AddChildView(new AutoSigninView(this)); } else if (model_.state() == password_manager::ui::CHROME_SIGN_IN_PROMO_STATE) { AddChildView(new SignInPromoView(this)); } else if (model_.state() == password_manager::ui::CHROME_DESKTOP_IOS_PROMO_STATE) { AddChildView(new DesktopIOSPromotionView( desktop_ios_promotion::PromotionEntryPoint::SAVE_PASSWORD_BUBBLE)); } else { AddChildView(new ManageView(this)); } }
35.704192
85
0.69738
google-ar
c06da04f369e8c2077ec036836b1be11ca584050
521
cpp
C++
ch16/hw16_9/hw16_9.cpp
z2x3c4v5bz/cbook_weinhong
0cc66728a2f815db0510f780d4647f3b09e61758
[ "MIT" ]
null
null
null
ch16/hw16_9/hw16_9.cpp
z2x3c4v5bz/cbook_weinhong
0cc66728a2f815db0510f780d4647f3b09e61758
[ "MIT" ]
null
null
null
ch16/hw16_9/hw16_9.cpp
z2x3c4v5bz/cbook_weinhong
0cc66728a2f815db0510f780d4647f3b09e61758
[ "MIT" ]
null
null
null
/* hw16_9 */ #include <iostream> #include <cstdlib> using namespace std; int _max(int,int,int); int _max(int,int); int main(void) { int a=2,b=1,c=3; cout<<"_max("<<a<<", "<<b<<", "<<c<<")="<<_max(a,b,c)<<endl; cout<<"_max("<<b<<", "<<a<<")="<<_max(b,a)<<endl; system("pause"); return 0; } int _max(int a,int b,int c) { int n=a; if(n<b) n=b; if(n<c) n=c; return n; } int _max(int a,int b) { int n=a; if(n<b) n=b; return n; } /* _max(2, 1, 3)=3 _max(1, 2)=2 Press any key to continue . . . */
11.840909
61
0.523992
z2x3c4v5bz
c06dd69760cadcf599751f81e1f4d434799bc534
1,224
cpp
C++
RLFPS/Source/RLFPS/Private/ReloadknockBackMod.cpp
Verb-Noun-Studios/Symbiotic
d037b3bbe4925f2d4c97d4c44e45ec0abe88c237
[ "MIT" ]
3
2022-01-11T03:29:03.000Z
2022-02-03T03:46:44.000Z
RLFPS/Source/RLFPS/Private/ReloadknockBackMod.cpp
Verb-Noun-Studios/Symbiotic
d037b3bbe4925f2d4c97d4c44e45ec0abe88c237
[ "MIT" ]
27
2022-02-02T04:54:29.000Z
2022-03-27T18:58:15.000Z
RLFPS/Source/RLFPS/Private/ReloadknockBackMod.cpp
Verb-Noun-Studios/Symbiotic
d037b3bbe4925f2d4c97d4c44e45ec0abe88c237
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "ReloadknockBackMod.h" #include "GruntCharacter.h" #include "Kismet/KismetMathLibrary.h" #include "Kismet/GameplayStatics.h" #include "GameFramework/PawnMovementComponent.h" #include "GameFramework/CharacterMovementComponent.h" UReloadKnockBackMod::UReloadKnockBackMod() { } UReloadKnockBackMod::~UReloadKnockBackMod() { } void UReloadKnockBackMod::OnReload_Implementation(AActor* player) { TArray<AActor*> enemies; UGameplayStatics::GetAllActorsOfClass(GetWorld(), classToFind, enemies); for (AActor* enemy : enemies) { FVector dir = enemy->GetActorLocation() - player->GetActorLocation(); float distance = dir.Size(); dir.Normalize(); UE_LOG(LogTemp, Warning, TEXT("Reload knockback: TestingDistance to Enemy, Distance: %f"), distance); if (distance < range + additionalRangePerStack * stacks) { dir.Z = FMath::Clamp(dir.Z, 0.2f, 0.3f); AGruntCharacter* character = Cast<AGruntCharacter>(enemy); character->GetCharacterMovement()->MovementMode = EMovementMode::MOVE_Flying; character->LaunchCharacter(dir * (strength + additionalStrengthPerStack * stacks + distance), true, true); } } }
25.5
109
0.753268
Verb-Noun-Studios
c06e568ee81ec53db067e0e956f0a9284c3ff952
5,267
hpp
C++
includes/Fox/Lexer/Lexer.hpp
Pierre-vh/Fox
ab3d9a5b3c409b5611840c477abef989830ea571
[ "MIT" ]
17
2019-01-17T22:41:11.000Z
2020-08-27T03:39:07.000Z
includes/Fox/Lexer/Lexer.hpp
Pierre-vh/Moonshot
ab3d9a5b3c409b5611840c477abef989830ea571
[ "MIT" ]
null
null
null
includes/Fox/Lexer/Lexer.hpp
Pierre-vh/Moonshot
ab3d9a5b3c409b5611840c477abef989830ea571
[ "MIT" ]
2
2019-06-30T19:07:10.000Z
2019-12-26T17:30:17.000Z
//----------------------------------------------------------------------------// // Part of the Fox project, licensed under the MIT license. // See LICENSE.txt in the project root for license information. // File : Lexer.hpp // Author : Pierre van Houtryve //----------------------------------------------------------------------------// // This file declares the Fox Lexer. //----------------------------------------------------------------------------// #pragma once #include "Token.hpp" #include "Fox/Common/SourceLoc.hpp" #include "Fox/Common/string_view.hpp" namespace fox { class DiagnosticEngine; class SourceManager; /// Lexer /// The Fox Lexer. An instance of the lexer is tied to a SourceFile /// (FileID). The lexing process can be initiated by calling lex(), and /// the resulting tokens will be found in the token vector returned by /// getTokens() /// The Token Vector's last token will always be TokenKind::EndOfFile. class Lexer { public: /// Constructor for the Lexer. /// \param srcMgr The SourceManager instance to use /// \param diags the DiagnosticEngine instance to use for diagnostics /// \param file the File that's going to be lexed. It must be a file /// owned by \p srcMgr. Lexer(SourceManager& srcMgr, DiagnosticEngine& diags, FileID file); /// Make this class non copyable, but movable Lexer(const Lexer&) = delete; Lexer& operator=(const Lexer&) = delete; Lexer(Lexer&&) = default; Lexer& operator=(Lexer&&) = default; /// lex the full file. the tokens can be retrieved using getTokens() void lex(); /// \returns the vector of tokens, can only be called if lex() has /// been called. The token vector is guaranteed to have a EOF token /// as the last token. TokenVector& getTokens(); /// Returns a SourceLoc for the character (or codepoint beginning) at /// \p ptr. /// /// \p ptr cannot be null and must be contained in the buffer of /// \ref theFile SourceLoc getLocFromPtr(const char* ptr) const; /// Returns a SourceRange for the range beginning at \p a and ending /// at \p b (range [a, b]) /// /// Both pointers must satisfy the same constraint as the argument of /// \ref getLocFromPtr SourceRange getRangeFromPtrs(const char* a, const char* b) const; /// \returns the number of tokens in the vector std::size_t numTokens() const; /// The DiagnosticEngine instance used by this Lexer DiagnosticEngine& diagEngine; /// The SourceManager instance used by this Lexer SourceManager& sourceMgr; /// The FileID of the file being lexed const FileID theFile; private: // Pushes the current token with the kind "kind" void pushTok(TokenKind kind); // Pushes the current token character as a token with the kind "kind" // (calls resetToken() + pushToken()) void beginAndPushToken(TokenKind kind); // Calls advance(), then pushes the current token with the kind 'kind' void advanceAndPushTok(TokenKind kind); // Returns true if we reached EOF. bool isEOF() const; // Begins a new token void resetToken(); // Entry point of the lexing process void lexImpl(); // Lex an identifier or keyword void lexIdentifierOrKeyword(); // Lex an int or double literal void lexIntOrDoubleConstant(); /// Lex any number of text items (a string_item or char_item, /// depending on \p delimiter) /// \p delimiter The delimiter. Can only be ' or ". /// \return true if the delimiter was found, false otherwise bool lexTextItems(FoxChar delimiter); // Lex a piece of text delimited by single quotes ' void lexCharLiteral(); // Lex a piece of text delimited by double quotes " void lexStringLiteral(); // Lex an integer literal void lexIntConstant(); // Handles a single-line comment void skipLineComment(); // Handles a multi-line comment void skipBlockComment(); // Returns true if 'ch' is a valid identifier head. bool isValidIdentifierHead(FoxChar ch) const; // Returns true if 'ch' is a valid identifier character. bool isValidIdentifierChar(FoxChar ch) const; // Returns the current character being considered FoxChar getCurChar() const; // Peeks the next character that will be considered FoxChar peekNextChar() const; // Advances to the next codepoint in the input. // Returns false if we reached EOF. bool advance(); SourceLoc getCurPtrLoc() const; SourceLoc getCurtokBegLoc() const; SourceRange getCurtokRange() const; string_view getCurtokStringView() const; const char* fileBeg_ = nullptr; const char* fileEnd_ = nullptr; // The pointer to the first byte of the token const char* tokBegPtr_ = nullptr; // The pointer to the current character being considered. // (pointer to the first byte in the UTF8 codepoint) const char* curPtr_ = nullptr; TokenVector tokens_; }; }
36.576389
80
0.617809
Pierre-vh
c06e9c64c23c588c50c85f42ae24f3ca1cfca02b
3,332
cpp
C++
envy TouchPad/FingerTapAndDragTapEvent.cpp
nagash91/EnvyTouchpad-NagashMod
90dd6dd1bd2302e42f6c1b13966eb988be803f9b
[ "Apache-2.0" ]
8
2019-03-20T15:42:06.000Z
2021-10-13T10:41:16.000Z
envy TouchPad/FingerTapAndDragTapEvent.cpp
delchiaro/EnvyTouchpad-NagashMod
90dd6dd1bd2302e42f6c1b13966eb988be803f9b
[ "Apache-2.0" ]
null
null
null
envy TouchPad/FingerTapAndDragTapEvent.cpp
delchiaro/EnvyTouchpad-NagashMod
90dd6dd1bd2302e42f6c1b13966eb988be803f9b
[ "Apache-2.0" ]
2
2018-04-07T01:12:41.000Z
2018-10-23T11:33:17.000Z
#include "stdafx.h" #include "FingerTapAndDragTapEvent.h" #include "Mouse.h" namespace envyTouchPad { FingerTapAndDragTapEvent::FingerTapAndDragTapEvent(int numberOfFingersTrigger) { fNumberOfFingersTrigger = numberOfFingersTrigger; clear(true); } bool FingerTapAndDragTapEvent::fingersPresent(Configurations^ configurations, Packet^ packet, TapState& tapState, TouchPad& touchPad) { fMaxNumberOfFingers = max(fMaxNumberOfFingers, packet->getCurrentNumberOfFingers()); if (fIsDoubleTap) { return true; } TapConfiguration^ tapConfiguration = configurations->getTapConfiguration(); // handle the double tap event if (fHasPreviousSingleClick && fMaxNumberOfFingers == fNumberOfFingersTrigger) { long previousClickTimeDifference = packet->getTimestamp() - fPreviousSingleClickTimestamp; if (previousClickTimeDifference < tapConfiguration->getSingleTapIntervalThreshold()) { fIsDoubleTap = true; Mouse::buttonDown(tapConfiguration->getMouseButton(fNumberOfFingersTrigger)); clear(true); return true; } } return false; //(fMaxNumberOfFingers == fNumberOfFingersTrigger); } // should always return false since we don't want the mouse cursor to move. bool FingerTapAndDragTapEvent::fingersNotPresent(Configurations^ configurations, Packet^ packet, TapState& tapState, TouchPad& touchPad) { TapConfiguration^ tapConfiguration = configurations->getTapConfiguration(); if (fIsDoubleTap) { fIsDoubleTap = false; Mouse::buttonUp(tapConfiguration->getMouseButton(fNumberOfFingersTrigger)); // perform the second click if it was a double tap and the finger didn't move // and the time difference isn't too large. otherwise, this was a double // tap and drag if ( (fMaxNumberOfFingers == fNumberOfFingersTrigger) && TapEvent::isTap(tapConfiguration, packet, tapState) ) { Mouse::buttonClick(tapConfiguration->getMouseButton(fNumberOfFingersTrigger)); } return true; } else { if ( fMaxNumberOfFingers == fNumberOfFingersTrigger && TapEvent::isTap(tapConfiguration, packet, tapState) ) { if (!fHasPreviousSingleClick) { fHasPreviousSingleClick = true; fPreviousSingleClickTimestamp = packet->getTimestamp(); clear(false); return true; } } else if (fHasPreviousSingleClick) { long previousClickTimeDifference = packet->getTimestamp() - fPreviousSingleClickTimestamp; if (previousClickTimeDifference > tapConfiguration->getSingleTapIntervalThreshold()) { Mouse::buttonClick(tapConfiguration->getMouseButton(fNumberOfFingersTrigger)); clear(true); } } clear(false); } return false; } void FingerTapAndDragTapEvent::clear(bool clearPrevious) { if (clearPrevious) { fHasPreviousSingleClick = false; fPreviousSingleClickTimestamp = 0; } fMaxNumberOfFingers = 0; } } // end namespace
29.22807
136
0.645858
nagash91
c0720c10013f99293aa1ab2ebc4d9bf3286bc964
8,572
cpp
C++
SampleMathematics/PointInPolyhedron/PointInPolyhedron.cpp
CRIMSONCardiovascularModelling/WildMagic5
fcf549bfb99a5c4b3d6ffbff18aabdc1a4e9085c
[ "BSL-1.0" ]
null
null
null
SampleMathematics/PointInPolyhedron/PointInPolyhedron.cpp
CRIMSONCardiovascularModelling/WildMagic5
fcf549bfb99a5c4b3d6ffbff18aabdc1a4e9085c
[ "BSL-1.0" ]
null
null
null
SampleMathematics/PointInPolyhedron/PointInPolyhedron.cpp
CRIMSONCardiovascularModelling/WildMagic5
fcf549bfb99a5c4b3d6ffbff18aabdc1a4e9085c
[ "BSL-1.0" ]
null
null
null
// Geometric Tools, LLC // Copyright (c) 1998-2014 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 5.0.0 (2010/01/01) #include "PointInPolyhedron.h" WM5_WINDOW_APPLICATION(PointInPolyhedron); // Enable only one at a time to test the algorithm. //#define TRIFACES //#define CVXFACES0 //#define CVXFACES1 //#define CVXFACES2 //#define SIMFACES0 #define SIMFACES1 //---------------------------------------------------------------------------- PointInPolyhedron::PointInPolyhedron () : WindowApplication3("SampleMathematics/PointInPolyhedron", 0, 0, 1024, 768, Float4(0.75f, 0.75f, 0.75f, 1.0f)), mTextColor(1.0f, 1.0f, 1.0f, 1.0f) { mQuery = 0; mTFaces = 0; mCFaces = 0; mSFaces = 0; mNumRays = 5; mRayDirections = new1<Vector3f>(mNumRays); for (int i = 0; i < mNumRays; ++i) { double point[3]; RandomPointOnHypersphere(3, point); for (int j = 0; j < 3; ++j) { mRayDirections[i][j] = (float)point[j]; } } } //---------------------------------------------------------------------------- bool PointInPolyhedron::OnInitialize () { if (!WindowApplication3::OnInitialize()) { return false; } // Set up the camera. mCamera->SetFrustum(60.0f, GetAspectRatio(), 0.001f, 10.0f); APoint camPosition(4.0f, 0.0f, 0.0f); AVector camDVector(-1.0f, 0.0f, 0.0f); AVector camUVector(0.0f, 0.0f, 1.0f); AVector camRVector = camDVector.Cross(camUVector); mCamera->SetFrame(camPosition, camDVector, camUVector, camRVector); CreateScene(); // Initial update of objects. mScene->Update(); // Initial culling of scene. mCuller.SetCamera(mCamera); mCuller.ComputeVisibleSet(mScene); InitializeCameraMotion(0.01f, 0.01f); InitializeObjectMotion(mScene); return true; } //---------------------------------------------------------------------------- void PointInPolyhedron::OnTerminate () { delete1(mRayDirections); mScene = 0; mWireState = 0; mPoints = 0; WindowApplication3::OnTerminate(); } //---------------------------------------------------------------------------- void PointInPolyhedron::OnIdle () { MeasureTime(); MoveCamera(); MoveObject(); mScene->Update(GetTimeInSeconds()); mCuller.ComputeVisibleSet(mScene); if (mRenderer->PreDraw()) { mRenderer->ClearBuffers(); mRenderer->Draw(mCuller.GetVisibleSet()); DrawFrameRate(8, GetHeight()-8, mTextColor); mRenderer->PostDraw(); mRenderer->DisplayColorBuffer(); } UpdateFrameCount(); } //---------------------------------------------------------------------------- bool PointInPolyhedron::OnKeyDown (unsigned char key, int x, int y) { if (WindowApplication3::OnKeyDown(key, x, y)) { return true; } switch (key) { case 'w': case 'W': mWireState->Enabled = !mWireState->Enabled; break; } return false; } //---------------------------------------------------------------------------- void PointInPolyhedron::CreateScene () { mScene = new0 Node(); mWireState = new0 WireState(); mRenderer->SetOverrideWireState(mWireState); // Create a semitransparent sphere mesh. VertexFormat* vformatMesh = VertexFormat::Create(1, VertexFormat::AU_POSITION, VertexFormat::AT_FLOAT3, 0); TriMesh* mesh = StandardMesh(vformatMesh).Sphere(16, 16, 1.0f); Material* material = new0 Material(); material->Diffuse = Float4(1.0f, 0.0f, 0.0f, 0.25f); VisualEffectInstance* instance = MaterialEffect::CreateUniqueInstance( material); instance->GetEffect()->GetAlphaState(0, 0)->BlendEnabled = true; mesh->SetEffectInstance(instance); // Create the data structures for the polyhedron that represents the // sphere mesh. CreateQuery(mesh); // Create a set of random points. Points inside the polyhedron are // colored white. Points outside the polyhedron are colored blue. VertexFormat* vformat = VertexFormat::Create(2, VertexFormat::AU_POSITION, VertexFormat::AT_FLOAT3, 0, VertexFormat::AU_COLOR, VertexFormat::AT_FLOAT3, 0); int vstride = vformat->GetStride(); VertexBuffer* vbuffer = new0 VertexBuffer(1024, vstride); VertexBufferAccessor vba(vformat, vbuffer); Float3 white(1.0f, 1.0f, 1.0f); Float3 blue(0.0f, 0.0f, 1.0f); for (int i = 0; i < vba.GetNumVertices(); ++i) { Vector3f random(Mathf::SymmetricRandom(), Mathf::SymmetricRandom(), Mathf::SymmetricRandom()); vba.Position<Vector3f>(i) = random; if (mQuery->Contains(random)) { vba.Color<Float3>(0, i) = white; } else { vba.Color<Float3>(0, i) = blue; } } DeleteQuery(); mPoints = new0 Polypoint(vformat, vbuffer); mPoints->SetEffectInstance(VertexColor3Effect::CreateUniqueInstance()); mScene->AttachChild(mPoints); mScene->AttachChild(mesh); } //---------------------------------------------------------------------------- void PointInPolyhedron::CreateQuery (TriMesh* mesh) { const VertexBuffer* vbuffer = mesh->GetVertexBuffer(); const int numVertices = vbuffer->GetNumElements(); const Vector3f* vertices = (Vector3f*)vbuffer->GetData(); const IndexBuffer* ibuffer = mesh->GetIndexBuffer(); const int numIndices = ibuffer->GetNumElements(); const int numFaces = numIndices/3; const int* indices = (int*)ibuffer->GetData(); const int* currentIndex = indices; int i; #ifdef TRIFACES mTFaces = new1<PointInPolyhedron3f::TriangleFace>(numFaces); for (i = 0; i < numFaces; ++i) { int v0 = *currentIndex++; int v1 = *currentIndex++; int v2 = *currentIndex++; mTFaces[i].Indices[0] = v0; mTFaces[i].Indices[1] = v1; mTFaces[i].Indices[2] = v2; mTFaces[i].Plane = Plane3f(vertices[v0], vertices[v1], vertices[v2]); } mQuery = new0 PointInPolyhedron3f(numVertices, vertices, numFaces, mTFaces, mNumRays, mRayDirections); #endif #if defined(CVXFACES0) || defined(CVXFACES1) || defined(CVXFACES2) mCFaces = new1<PointInPolyhedron3f::ConvexFace>(numFaces); for (i = 0; i < numFaces; ++i) { int v0 = *currentIndex++; int v1 = *currentIndex++; int v2 = *currentIndex++; mCFaces[i].Indices.resize(3); mCFaces[i].Indices[0] = v0; mCFaces[i].Indices[1] = v1; mCFaces[i].Indices[2] = v2; mCFaces[i].Plane = Plane3f(vertices[v0], vertices[v1], vertices[v2]); } #ifdef CVXFACES0 mQuery = new0 PointInPolyhedron3f(numVertices, vertices, numFaces, mCFaces, mNumRays, mRayDirections, 0); #else #ifdef CVXFACES1 mQuery = new0 PointInPolyhedron3f(numVertices, vertices, numFaces, mCFaces, mNumRays, mRayDirections, 1); #else mQuery = new0 PointInPolyhedron3f(numVertices, vertices, numFaces, mCFaces, mNumRays, mRayDirections, 2); #endif #endif #endif #if defined (SIMFACES0) || defined (SIMFACES1) mSFaces = new1<PointInPolyhedron3f::SimpleFace>(numFaces); for (i = 0; i < numFaces; ++i) { int v0 = *currentIndex++; int v1 = *currentIndex++; int v2 = *currentIndex++; mSFaces[i].Indices.resize(3); mSFaces[i].Indices[0] = v0; mSFaces[i].Indices[1] = v1; mSFaces[i].Indices[2] = v2; mSFaces[i].Plane = Plane3f(vertices[v0], vertices[v1], vertices[v2]); mSFaces[i].Triangles.resize(3); mSFaces[i].Triangles[0] = v0; mSFaces[i].Triangles[1] = v1; mSFaces[i].Triangles[2] = v2; } #ifdef SIMFACES0 mQuery = new0 PointInPolyhedron3f(numVertices, vertices, numFaces, mSFaces, mNumRays, mRayDirections, 0); #else mQuery = new0 PointInPolyhedron3f(numVertices, vertices, numFaces, mSFaces, mNumRays, mRayDirections, 1); #endif #endif } //---------------------------------------------------------------------------- void PointInPolyhedron::DeleteQuery () { delete0(mQuery); #ifdef TRIANGLE_FACES delete1(mTFaces); #endif #if defined(CVXFACES0) || defined(CVXFACES1) || defined(CVXFACES2) delete1(mCFaces); #endif #if defined (SIMFACES0) || defined (SIMFACES1) delete1(mSFaces); #endif } //----------------------------------------------------------------------------
29.457045
78
0.589011
CRIMSONCardiovascularModelling
c072b7560875830d693e5faa9e5191d5d83b7913
24,417
cpp
C++
Engine/Source/Runtime/CoreUObject/Private/UObject/LinkerPlaceholderBase.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/CoreUObject/Private/UObject/LinkerPlaceholderBase.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/CoreUObject/Private/UObject/LinkerPlaceholderBase.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "UObject/LinkerPlaceholderBase.h" #include "UObject/UnrealType.h" #include "Blueprint/BlueprintSupport.h" #if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS #define DEFERRED_DEPENDENCY_ENSURE(EnsueExpr) ensure(EnsueExpr) #else // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS #define DEFERRED_DEPENDENCY_ENSURE(EnsueExpr) (EnsueExpr) #endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS /******************************************************************************* * LinkerPlaceholderObjectImpl ******************************************************************************/ /** */ struct FPlaceholderContainerTracker : TThreadSingleton<FPlaceholderContainerTracker> { TArray<UObject*> PerspectiveReferencerStack; TArray<void*> PerspectiveRootDataStack; // as far as I can tell, structs are going to be the only bridging point // between property ownership TArray<const UStructProperty*> IntermediatePropertyStack; }; /** */ class FLinkerPlaceholderObjectImpl { public: /** * A recursive method that replaces all leaf references to this object with * the supplied ReplacementValue. * * This function recurses the property chain (from class owner down) because * at the time of AddReferencingPropertyValue() we cannot know/record the * address/index of array properties (as they may change during array * re-allocation or compaction). So we must follow the property chain and * check every container (array, set, map) property member for references to * this (hence, the need for this recursive function). * * @param PropertyChain An ascending outer chain, where the property at index zero is the leaf (referencer) property. * @param ChainIndex An index into the PropertyChain that this call should start at and iterate DOWN to zero. * @param ValueAddress The memory address of the value corresponding to the property at ChainIndex. * @param OldValue * @param ReplacementValue The new object to replace all references to this with. * @return The number of references that were replaced. */ static int32 ResolvePlaceholderValues(const TArray<const UProperty*>& PropertyChain, int32 ChainIndex, uint8* ValueAddress, UObject* OldValue, UObject* ReplacementValue); /** * Uses the current FPlaceholderContainerTracker::PerspectiveReferencerStack * to search for a viable placeholder container (expected that it will be * the top of the stack). * * @param PropertyChainRef Defines the nested property path through a UObject, where the end leaf property is one left referencing a placeholder. * @return The UObject instance that is assumably referencing a placeholder (null if one couldn't be found) */ static UObject* FindPlaceholderContainer(const FLinkerPlaceholderBase::FPlaceholderValuePropertyPath& PropertyChainRef); static void* FindRawPlaceholderContainer(const FLinkerPlaceholderBase::FPlaceholderValuePropertyPath& PropertyChainRef); }; //------------------------------------------------------------------------------ int32 FLinkerPlaceholderObjectImpl::ResolvePlaceholderValues(const TArray<const UProperty*>& PropertyChain, int32 ChainIndex, uint8* ValueAddress, UObject* OldValue, UObject* ReplacementValue) { int32 ReplacementCount = 0; for (int32 PropertyIndex = ChainIndex; PropertyIndex >= 0; --PropertyIndex) { const UProperty* Property = PropertyChain[PropertyIndex]; if (PropertyIndex == 0) { #if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS check(Property->IsA<UObjectProperty>()); #endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS const UObjectProperty* ReferencingProperty = (const UObjectProperty*)Property; UObject* CurrentValue = ReferencingProperty->GetObjectPropertyValue(ValueAddress); if (CurrentValue == OldValue) { // @TODO: use an FArchiver with ReferencingProperty->SerializeItem() // so that we can utilize CheckValidObject() ReferencingProperty->SetObjectPropertyValue(ValueAddress, ReplacementValue); // @TODO: unfortunately, this is currently protected //ReferencingProperty->CheckValidObject(ValueAddress); ++ReplacementCount; } } else if (const UArrayProperty* ArrayProperty = Cast<const UArrayProperty>(Property)) { #if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS const UProperty* NextProperty = PropertyChain[PropertyIndex - 1]; check(NextProperty == ArrayProperty->Inner); #endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS // because we can't know which array entry was set with a reference // to this object, we have to comb through them all FScriptArrayHelper ArrayHelper(ArrayProperty, ValueAddress); for (int32 ArrayIndex = 0; ArrayIndex < ArrayHelper.Num(); ++ArrayIndex) { uint8* MemberAddress = ArrayHelper.GetRawPtr(ArrayIndex); ReplacementCount += ResolvePlaceholderValues(PropertyChain, PropertyIndex - 1, MemberAddress, OldValue, ReplacementValue); } // the above recursive call chewed through the rest of the // PropertyChain, no need to keep on here break; } else if (const USetProperty* SetProperty = Cast<const USetProperty>(Property)) { #if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS const UProperty* NextProperty = PropertyChain[PropertyIndex - 1]; check(NextProperty == SetProperty->ElementProp); #endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS // because we can't know which set entry was set with a reference // to this object, we have to comb through them all FScriptSetHelper SetHelper(SetProperty, ValueAddress); int32 Num = SetHelper.Num(); for (int32 SetIndex = 0; Num; ++SetIndex) { if (SetHelper.IsValidIndex(SetIndex)) { --Num; uint8* ElementAddress = SetHelper.GetElementPtr(SetIndex); ReplacementCount += ResolvePlaceholderValues(PropertyChain, PropertyIndex - 1, ElementAddress, OldValue, ReplacementValue); } } // the above recursive call chewed through the rest of the // PropertyChain, no need to keep on here break; } else if (const UMapProperty* MapProperty = Cast<const UMapProperty>(Property)) { #if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS const UProperty* NextProperty = PropertyChain[PropertyIndex - 1]; check(NextProperty == MapProperty->KeyProp); #endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS // because we can't know which map entry was set with a reference // to this object, we have to comb through them all FScriptMapHelper MapHelper(MapProperty, ValueAddress); int32 Num = MapHelper.Num(); for (int32 MapIndex = 0; Num; ++MapIndex) { if (MapHelper.IsValidIndex(MapIndex)) { --Num; uint8* KeyAddress = MapHelper.GetKeyPtr(MapIndex); ReplacementCount += ResolvePlaceholderValues(PropertyChain, PropertyIndex - 1, KeyAddress, OldValue, ReplacementValue); uint8* MapValueAddress = MapHelper.GetValuePtr(MapIndex); ReplacementCount += ResolvePlaceholderValues(PropertyChain, PropertyIndex - 1, MapValueAddress, OldValue, ReplacementValue); } } // the above recursive call chewed through the rest of the // PropertyChain, no need to keep on here break; } else { const UProperty* NextProperty = PropertyChain[PropertyIndex - 1]; ValueAddress = NextProperty->ContainerPtrToValuePtr<uint8>(ValueAddress, /*ArrayIndex =*/0); } } return ReplacementCount; } //------------------------------------------------------------------------------ UObject* FLinkerPlaceholderObjectImpl::FindPlaceholderContainer(const FLinkerPlaceholderBase::FPlaceholderValuePropertyPath& PropertyChainRef) { UObject* ContainerObj = nullptr; TArray<UObject*>& PossibleReferencers = FPlaceholderContainerTracker::Get().PerspectiveReferencerStack; UClass* OwnerClass = PropertyChainRef.GetOwnerClass(); if ((OwnerClass != nullptr) && (PossibleReferencers.Num() > 0)) { UObject* ReferencerCandidate = PossibleReferencers.Top(); // we expect that the current object we're looking for (the one we're // serializing) is at the top of the stack if (DEFERRED_DEPENDENCY_ENSURE(ReferencerCandidate->GetClass()->IsChildOf(OwnerClass))) { ContainerObj = ReferencerCandidate; } else { // if it's not the top element, then iterate backwards because this // is meant to act as a stack, where the last entry is most likely // the one we're looking for for (int32 CandidateIndex = PossibleReferencers.Num() - 2; CandidateIndex >= 0; --CandidateIndex) { ReferencerCandidate = PossibleReferencers[CandidateIndex]; UClass* CandidateClass = ReferencerCandidate->GetClass(); if (CandidateClass->IsChildOf(OwnerClass)) { ContainerObj = ReferencerCandidate; break; } } } } return ContainerObj; } void* FLinkerPlaceholderObjectImpl::FindRawPlaceholderContainer(const FLinkerPlaceholderBase::FPlaceholderValuePropertyPath& PropertyChainRef) { TArray<void*>& PossibleStructReferencers = FPlaceholderContainerTracker::Get().PerspectiveRootDataStack; return PossibleStructReferencers[0]; } /******************************************************************************* * FPlaceholderContainerTracker / FScopedPlaceholderPropertyTracker ******************************************************************************/ //------------------------------------------------------------------------------ FScopedPlaceholderContainerTracker::FScopedPlaceholderContainerTracker(UObject* InPlaceholderContainerCandidate) : PlaceholderReferencerCandidate(InPlaceholderContainerCandidate) { FPlaceholderContainerTracker::Get().PerspectiveReferencerStack.Add(InPlaceholderContainerCandidate); } //------------------------------------------------------------------------------ FScopedPlaceholderContainerTracker::~FScopedPlaceholderContainerTracker() { UObject* StackTop = FPlaceholderContainerTracker::Get().PerspectiveReferencerStack.Pop(); #if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS check(StackTop == PlaceholderReferencerCandidate); #endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS } #if WITH_EDITOR FScopedPlaceholderRawContainerTracker::FScopedPlaceholderRawContainerTracker(void* InData) :Data(InData) { FPlaceholderContainerTracker::Get().PerspectiveRootDataStack.Add(InData); } FScopedPlaceholderRawContainerTracker::~FScopedPlaceholderRawContainerTracker() { void* StackTop = FPlaceholderContainerTracker::Get().PerspectiveRootDataStack.Pop(); #if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS check(StackTop == Data); #endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS } #endif //------------------------------------------------------------------------------ FScopedPlaceholderPropertyTracker::FScopedPlaceholderPropertyTracker(const UStructProperty* InIntermediateProperty) : IntermediateProperty(nullptr) // leave null, as a sentinel value (implying that PerspectiveReferencerStack was empty) { FPlaceholderContainerTracker& ContainerRepository = FPlaceholderContainerTracker::Get(); if (ContainerRepository.PerspectiveReferencerStack.Num() > 0 || ContainerRepository.PerspectiveRootDataStack.Num() > 0) { IntermediateProperty = InIntermediateProperty; ContainerRepository.IntermediatePropertyStack.Add(InIntermediateProperty); } // else, if there's nothing in the PerspectiveReferencerStack, then caching // a property here would be pointless (the whole point of this is to be able // to use this to look up the referencing object) } //------------------------------------------------------------------------------ FScopedPlaceholderPropertyTracker::~FScopedPlaceholderPropertyTracker() { FPlaceholderContainerTracker& ContainerRepository = FPlaceholderContainerTracker::Get(); if (IntermediateProperty != nullptr) { const UStructProperty* StackTop = ContainerRepository.IntermediatePropertyStack.Pop(); #if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS check(StackTop == IntermediateProperty); } else { check(ContainerRepository.IntermediatePropertyStack.Num() == 0); check(ContainerRepository.PerspectiveReferencerStack.Num() == 0); check(ContainerRepository.PerspectiveRootDataStack.Num() == 0); #endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS } } /******************************************************************************* * FLinkerPlaceholderBase::FPlaceholderValuePropertyPath ******************************************************************************/ //------------------------------------------------------------------------------ FLinkerPlaceholderBase::FPlaceholderValuePropertyPath::FPlaceholderValuePropertyPath(const UProperty* ReferencingProperty) { PropertyChain.Add(ReferencingProperty); const UObject* PropertyOuter = ReferencingProperty->GetOuter(); const TArray<const UStructProperty*>& StructPropertyStack = FPlaceholderContainerTracker::Get().IntermediatePropertyStack; int32 StructStackIndex = StructPropertyStack.Num() - 1; // "top" of the array is the last element while (PropertyOuter && !PropertyOuter->GetClass()->IsChildOf<UClass>()) { // handle nested properties (like array members) if (const UProperty* PropertyOwner = Cast<const UProperty>(PropertyOuter)) { PropertyChain.Add(PropertyOwner); } // handle nested struct properties (use the FPlaceholderContainerTracker::IntermediatePropertyStack // to help trace the property path) else if (const UScriptStruct* StructOwner = Cast<const UScriptStruct>(PropertyOuter)) { if (StructStackIndex != INDEX_NONE) { // we expect the top struct property to be the one we're currently serializing const UStructProperty* SerializingStructProp = StructPropertyStack[StructStackIndex]; if (DEFERRED_DEPENDENCY_ENSURE(SerializingStructProp->Struct->IsChildOf(StructOwner))) { PropertyOuter = SerializingStructProp; PropertyChain.Add(SerializingStructProp); } else { #if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS PropertyChain.Empty(); // invalidate this FPlaceholderValuePropertyPath checkf(false, TEXT("Looks like we couldn't reliably determine the object that a placeholder value should belong to - are we missing a FScopedPlaceholderPropertyTracker?")); #endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TEST break; } --StructStackIndex; } else { // We're serializing a struct that isn't owned by a UObject (e.g. UUserDefinedStructEditorData::DefaultStructInstance) break; } } PropertyOuter = PropertyOuter->GetOuter(); } #if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS if (!DEFERRED_DEPENDENCY_ENSURE(PropertyOuter != nullptr)) { PropertyChain.Empty(); // invalidate this FPlaceholderValuePropertyPath } #endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TEST } //------------------------------------------------------------------------------ bool FLinkerPlaceholderBase::FPlaceholderValuePropertyPath::IsValid() const { return (PropertyChain.Num() > 0) && PropertyChain[0]->IsA<UObjectProperty>() && PropertyChain.Last()->GetOuter()->IsA<UClass>(); } //------------------------------------------------------------------------------ UClass* FLinkerPlaceholderBase::FPlaceholderValuePropertyPath::GetOwnerClass() const { return (PropertyChain.Num() > 0) ? Cast<UClass>(PropertyChain.Last()->GetOuter()) : nullptr; } //------------------------------------------------------------------------------ int32 FLinkerPlaceholderBase::FPlaceholderValuePropertyPath::Resolve(FLinkerPlaceholderBase* Placeholder, UObject* Replacement, UObject* Container) const { const UProperty* OutermostProperty = PropertyChain.Last(); #if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS UClass* OwnerClass = OutermostProperty->GetOwnerClass(); check(OwnerClass && Container->IsA(OwnerClass)); #endif uint8* OutermostAddress = OutermostProperty->ContainerPtrToValuePtr<uint8>((uint8*)Container, /*ArrayIndex =*/0); return FLinkerPlaceholderObjectImpl::ResolvePlaceholderValues(PropertyChain, PropertyChain.Num() - 1, OutermostAddress, Placeholder->GetPlaceholderAsUObject(), Replacement); } int32 FLinkerPlaceholderBase::FPlaceholderValuePropertyPath::ResolveRaw(FLinkerPlaceholderBase* Placeholder, UObject* Replacement, void* Container) const { const UProperty* OutermostProperty = PropertyChain.Last(); uint8* OutermostAddress = OutermostProperty->ContainerPtrToValuePtr<uint8>((uint8*)Container, /*ArrayIndex =*/0); return FLinkerPlaceholderObjectImpl::ResolvePlaceholderValues(PropertyChain, PropertyChain.Num() - 1, OutermostAddress, Placeholder->GetPlaceholderAsUObject(), Replacement);; } /******************************************************************************* * FLinkerPlaceholderBase ******************************************************************************/ //------------------------------------------------------------------------------ FLinkerPlaceholderBase::FLinkerPlaceholderBase() : bResolveWasInvoked(false) { } //------------------------------------------------------------------------------ FLinkerPlaceholderBase::~FLinkerPlaceholderBase() { #if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS check(!HasKnownReferences()); #endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS } //------------------------------------------------------------------------------ bool FLinkerPlaceholderBase::AddReferencingPropertyValue(const UObjectProperty* ReferencingProperty, void* DataPtr) { FPlaceholderValuePropertyPath PropertyChain(ReferencingProperty); UObject* ReferencingContainer = FLinkerPlaceholderObjectImpl::FindPlaceholderContainer(PropertyChain); if (ReferencingContainer != nullptr) { #if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS check(ReferencingProperty->GetObjectPropertyValue(DataPtr) == GetPlaceholderAsUObject()); check(PropertyChain.IsValid()); #endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS ReferencingContainers.FindOrAdd(ReferencingContainer).Add(PropertyChain); return true; } else { void* ReferencingRootStruct = FLinkerPlaceholderObjectImpl::FindRawPlaceholderContainer(PropertyChain); if (ReferencingRootStruct) { ReferencingRawContainers.FindOrAdd(ReferencingRootStruct).Add(PropertyChain); } return ReferencingRootStruct != nullptr; } } //------------------------------------------------------------------------------ bool FLinkerPlaceholderBase::HasKnownReferences() const { return (ReferencingContainers.Num() > 0) || ReferencingRawContainers.Num() > 0; } //------------------------------------------------------------------------------ int32 FLinkerPlaceholderBase::ResolveAllPlaceholderReferences(UObject* ReplacementObj) { int32 ReplacementCount = ResolvePlaceholderPropertyValues(ReplacementObj); ReferencingContainers.Empty(); ReferencingRawContainers.Empty(); MarkAsResolved(); return ReplacementCount; } //------------------------------------------------------------------------------ bool FLinkerPlaceholderBase::HasBeenFullyResolved() const { return IsMarkedResolved() && !HasKnownReferences(); } //------------------------------------------------------------------------------ bool FLinkerPlaceholderBase::IsMarkedResolved() const { return bResolveWasInvoked; } //------------------------------------------------------------------------------ void FLinkerPlaceholderBase::MarkAsResolved() { bResolveWasInvoked = true; } //------------------------------------------------------------------------------ int32 FLinkerPlaceholderBase::ResolvePlaceholderPropertyValues(UObject* NewObjectValue) { int32 ResolvedTotal = 0; for (auto& ReferencingPair : ReferencingContainers) { TWeakObjectPtr<UObject> ContainerPtr = ReferencingPair.Key; if (!ContainerPtr.IsValid()) { continue; } UObject* Container = ContainerPtr.Get(); for (const FPlaceholderValuePropertyPath& PropertyRef : ReferencingPair.Value) { #if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS check(Container->GetClass()->IsChildOf(PropertyRef.GetOwnerClass())); #endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS int32 ResolvedCount = PropertyRef.Resolve(this, NewObjectValue, Container); ResolvedTotal += ResolvedCount; #if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS // we expect that (because we have had ReferencingProperties added) // there should be at least one reference that is resolved... if // there were none, then a property could have changed its value // after it was set to this // // NOTE: this may seem it can be resolved by properties removing themselves // from ReferencingProperties, but certain properties may be // the inner of a container (array, set, map) property (meaning // there could be multiple references per property)... we'd // have to inc/decrement a property ref-count to resolve that // scenario check(ResolvedCount > 0); #endif // USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS } } for (auto& ReferencingRawPair : ReferencingRawContainers) { void* RawValue = ReferencingRawPair.Key; check(RawValue); for (const FPlaceholderValuePropertyPath& PropertyRef : ReferencingRawPair.Value) { int32 ResolvedCount = PropertyRef.ResolveRaw(this, NewObjectValue, RawValue); ResolvedTotal += ResolvedCount; #if USE_DEFERRED_DEPENDENCY_CHECK_VERIFICATION_TESTS check(ResolvedCount > 0); #endif } } return ResolvedTotal; } /******************************************************************************* * TLinkerImportPlaceholder<UClass> ******************************************************************************/ //------------------------------------------------------------------------------ template<> int32 TLinkerImportPlaceholder<UClass>::ResolvePropertyReferences(UClass* ReplacementClass) { int32 ReplacementCount = 0; UClass* PlaceholderClass = CastChecked<UClass>(GetPlaceholderAsUObject()); for (UProperty* Property : ReferencingProperties) { if (UObjectPropertyBase* BaseObjProperty = Cast<UObjectPropertyBase>(Property)) { if (BaseObjProperty->PropertyClass == PlaceholderClass) { BaseObjProperty->PropertyClass = ReplacementClass; ++ReplacementCount; } if (UClassProperty* ClassProperty = Cast<UClassProperty>(BaseObjProperty)) { if (ClassProperty->MetaClass == PlaceholderClass) { ClassProperty->MetaClass = ReplacementClass; ++ReplacementCount; } } else if (USoftClassProperty* SoftClassProperty = Cast<USoftClassProperty>(BaseObjProperty)) { if (SoftClassProperty->MetaClass == PlaceholderClass) { SoftClassProperty->MetaClass = ReplacementClass; ++ReplacementCount; } } } else if (UInterfaceProperty* InterfaceProp = Cast<UInterfaceProperty>(Property)) { if (InterfaceProp->InterfaceClass == PlaceholderClass) { InterfaceProp->InterfaceClass = ReplacementClass; ++ReplacementCount; } } else { checkf(TEXT("Unhandled property type: %s"), *Property->GetClass()->GetName()); } } ReferencingProperties.Empty(); return ReplacementCount; } /******************************************************************************* * TLinkerImportPlaceholder<UFunction> ******************************************************************************/ //------------------------------------------------------------------------------ template<> int32 TLinkerImportPlaceholder<UFunction>::ResolvePropertyReferences(UFunction* ReplacementFunc) { int32 ReplacementCount = 0; UFunction* PlaceholderFunc = CastChecked<UFunction>(GetPlaceholderAsUObject()); for (UProperty* Property : ReferencingProperties) { if (UDelegateProperty* DelegateProperty = Cast<UDelegateProperty>(Property)) { if (DelegateProperty->SignatureFunction == PlaceholderFunc) { DelegateProperty->SignatureFunction = ReplacementFunc; ++ReplacementCount; } } else if (UMulticastDelegateProperty* MulticastDelegateProperty = Cast<UMulticastDelegateProperty>(Property)) { if (MulticastDelegateProperty->SignatureFunction == PlaceholderFunc) { MulticastDelegateProperty->SignatureFunction = ReplacementFunc; ++ReplacementCount; } } else { checkf(TEXT("Unhandled property type: %s"), *Property->GetClass()->GetName()); } } ReferencingProperties.Empty(); return ReplacementCount; } #undef DEFERRED_DEPENDENCY_ENSURE
39.702439
192
0.694516
windystrife
c0746d375d5c43d68cfad1896e7a3ab6178e2c35
4,171
cc
C++
lite/kernels/cuda/sequence_arithmetic_compute_test.cc
peblue12345/Paddle-Lite
3176ffcf9e0c9fec07f1a9d3f53efed5bb177696
[ "Apache-2.0" ]
1,799
2019-08-19T03:29:38.000Z
2022-03-31T14:30:50.000Z
lite/kernels/cuda/sequence_arithmetic_compute_test.cc
peblue12345/Paddle-Lite
3176ffcf9e0c9fec07f1a9d3f53efed5bb177696
[ "Apache-2.0" ]
3,767
2019-08-19T03:36:04.000Z
2022-03-31T14:37:26.000Z
lite/kernels/cuda/sequence_arithmetic_compute_test.cc
yingshengBD/Paddle-Lite
eea59b66f61bb2acad471010c9526eeec43a15ca
[ "Apache-2.0" ]
798
2019-08-19T02:28:23.000Z
2022-03-31T08:31:54.000Z
// Copyright (c) 2019 PaddlePaddle Authors. 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 "lite/kernels/cuda/sequence_arithmetic_compute.h" #include <gtest/gtest.h> #include <algorithm> #include <memory> #include <utility> #include <vector> #include "lite/core/op_registry.h" namespace paddle { namespace lite { namespace kernels { namespace cuda { void sequence_arithmetic_compute_ref(const Tensor& x, const Tensor& y, Tensor* out, int op_type) { auto x_data = x.data<float>(); auto y_data = y.data<float>(); out->Resize(x.dims()); out->set_lod(x.lod()); auto out_data = out->mutable_data<float>(); auto x_seq_offset = x.lod()[0]; auto y_seq_offset = y.lod()[0]; int seq_num = x_seq_offset.size() - 1; int inner_size = x.numel() / x.dims()[0]; for (int i = 0; i < seq_num; i++) { int len_x = (x_seq_offset[i + 1] - x_seq_offset[i]) * inner_size; int len_y = (y_seq_offset[i + 1] - y_seq_offset[i]) * inner_size; auto input_x = x_data + x_seq_offset[i] * inner_size; auto input_y = y_data + y_seq_offset[i] * inner_size; auto t_out = out_data + x_seq_offset[i] * inner_size; int len = std::min(len_x, len_y); for (int j = 0; j < len; j++) { switch (op_type) { case 1: t_out[j] = input_x[j] + input_y[j]; break; case 2: t_out[j] = input_x[j] - input_y[j]; break; case 3: t_out[j] = input_x[j] * input_y[j]; break; default: break; } } if (len_x > len) { memcpy(t_out + len, input_x + len, sizeof(float) * (len_x - len)); } } } void prepare_input(Tensor* x, const LoD& x_lod) { x->Resize({static_cast<int64_t>(x_lod[0].back()), 3}); x->set_lod(x_lod); auto x_data = x->mutable_data<float>(); for (int i = 0; i < x->numel(); i++) { x_data[i] = (i - x->numel() / 2) * 1.1; } } TEST(sequence_arithmetic_cuda, run_test) { lite::Tensor x, y, x_cpu, y_cpu; lite::Tensor out, out_cpu, out_ref; lite::LoD x_lod{{0, 2, 5, 9}}, y_lod{{0, 2, 5, 9}}; prepare_input(&x_cpu, x_lod); prepare_input(&y_cpu, y_lod); x.Resize(x_cpu.dims()); x.set_lod(x_cpu.lod()); auto x_cpu_data = x_cpu.mutable_data<float>(); x.Assign<float, lite::DDim, TARGET(kCUDA)>(x_cpu_data, x_cpu.dims()); y.Resize(y_cpu.dims()); y.set_lod(y_cpu.lod()); auto y_cpu_data = y_cpu.mutable_data<float>(); y.Assign<float, lite::DDim, TARGET(kCUDA)>(y_cpu_data, y_cpu.dims()); operators::SequenceArithmeticParam param; param.X = &x; param.Y = &y; param.Out = &out; param.op_type = 1; std::unique_ptr<KernelContext> ctx(new KernelContext); auto& context = ctx->As<CUDAContext>(); cudaStream_t stream; cudaStreamCreate(&stream); context.SetExecStream(stream); SequenceArithmeticCompute sequence_arithmetic; sequence_arithmetic.SetContext(std::move(ctx)); sequence_arithmetic.SetParam(param); sequence_arithmetic.Run(); cudaDeviceSynchronize(); auto out_data = out.mutable_data<float>(TARGET(kCUDA)); out_cpu.Resize(out.dims()); auto out_cpu_data = out_cpu.mutable_data<float>(); CopySync<TARGET(kCUDA)>( out_cpu_data, out_data, sizeof(float) * out.numel(), IoDirection::DtoH); sequence_arithmetic_compute_ref(x_cpu, y_cpu, &out_ref, param.op_type); auto out_ref_data = out_ref.data<float>(); for (int i = 0; i < out.numel(); i++) { EXPECT_NEAR(out_cpu_data[i], out_ref_data[i], 1e-3); } } } // namespace cuda } // namespace kernels } // namespace lite } // namespace paddle
31.598485
78
0.641333
peblue12345
c07473128d2487829da72e764b45a69ee9d6ac17
4,564
hpp
C++
engine/include/ph/game_loop/DefaultGameUpdateable.hpp
PetorSFZ/PhantasyEngine
befe8e9499b7fd93d8765721b6841337a57b0dd6
[ "Zlib" ]
null
null
null
engine/include/ph/game_loop/DefaultGameUpdateable.hpp
PetorSFZ/PhantasyEngine
befe8e9499b7fd93d8765721b6841337a57b0dd6
[ "Zlib" ]
null
null
null
engine/include/ph/game_loop/DefaultGameUpdateable.hpp
PetorSFZ/PhantasyEngine
befe8e9499b7fd93d8765721b6841337a57b0dd6
[ "Zlib" ]
null
null
null
// Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se) // For other contributors see Contributors.txt // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. #pragma once #include <sfz/memory/Allocator.hpp> #include <sfz/memory/SmartPointers.hpp> #include "ph/game_loop/GameLoopUpdateable.hpp" namespace ph { using sfz::Allocator; using sfz::UniquePtr; using sfz::vec3; using sfz::vec4; // DefaultGameUpdateable logic // ------------------------------------------------------------------------------------------------ struct ImguiControllers final { bool useMouse = true; bool useKeyboard = true; int32_t controllerIndex = -1; }; class GameLogic { public: virtual ~GameLogic() {} virtual void initialize(Renderer& renderer) = 0; // Returns the index of the controller to be used for Imgui. If -1 is returned no controller // input will be provided to Imgui. virtual ImguiControllers imguiController(const UserInput&) { return ImguiControllers(); } virtual UpdateOp processInput( const UserInput& input, const UpdateInfo& updateInfo, Renderer& renderer) = 0; virtual UpdateOp updateTick(const UpdateInfo& updateInfo, Renderer& renderer) = 0; virtual void render(const UpdateInfo& updateInfo, Renderer& renderer) = 0; // Small hook that is called last in a frame, after rendering, regardless of whether the // console is active or not. // // This is useful if you need to do some operations each frame when the renderer is not busy // preparing commands to render a new frame (i.e., not between beginFrame() and finishFrame()). // // This is also the last thing that happens each frame, so it can also be a good place to put // some per frame book keeping you are doing. virtual void postRenderHook(ph::Renderer& renderer, bool consoleActive) {}; // Renders custom Imgui commands. // // This function and injectConsoleMenu() are the only places where Imgui commands can safely // be called. BeginFrame() and EndFrame() are called before and after this function. Other // Imgui commands from the DefaultGameUpdateable console itself may be sent within this same // frame if they are set to be always shown. This function will not be called if the console // is currently active. virtual void renderCustomImgui() {} // Call when console is active after all the built-in menus have been drawn. Can be used to // inject game-specific custom menus into the console. virtual void injectConsoleMenu() {} // These two functions are used to dock injected console windows. The first one should return // the number of windows you want to dock, the second one the name of each window given the // index in the range you provided with the first function. These are typically only called // during the first boot of the engine/game. You don't need to provide them even if you are // injecting console windows; virtual uint32_t injectConsoleMenuNumWindowsToDockInitially() { return 0; } virtual const char* injectConsoleMenuNameOfWindowToDockInitially(uint32_t idx) { (void)idx; return nullptr; } // Called when console is activated. The logic instance will not receive any additional calls // until the console is closed, at which point onConsoleDeactivated() will be called. onQuit() // may be called before the console is deactivated. virtual void onConsoleActivated() {} // Called when the console is deactivated. virtual void onConsoleDeactivated() {} virtual void onQuit() { } }; // DefaultGameUpdateable creation function // ------------------------------------------------------------------------------------------------ UniquePtr<GameLoopUpdateable> createDefaultGameUpdateable( Allocator* allocator, UniquePtr<GameLogic> logic) noexcept; } // namespace ph
40.389381
110
0.724145
PetorSFZ
c0748b218a4549fbc99c6abbecea29a79ce24933
13,238
cpp
C++
ConceptEngine/ConceptEngine/ConceptEngineFramework/Game/CEGame.cpp
Ludaxord/ConceptEngine
16775bc9b518d4fd4c8bd32bb5f297223dfacbae
[ "MIT" ]
4
2021-01-10T00:46:21.000Z
2022-02-25T18:43:26.000Z
ConceptEngine/ConceptEngine/ConceptEngineFramework/Game/CEGame.cpp
Ludaxord/ConceptEngine
16775bc9b518d4fd4c8bd32bb5f297223dfacbae
[ "MIT" ]
null
null
null
ConceptEngine/ConceptEngine/ConceptEngineFramework/Game/CEGame.cpp
Ludaxord/ConceptEngine
16775bc9b518d4fd4c8bd32bb5f297223dfacbae
[ "MIT" ]
null
null
null
#include "CEGame.h" #include <spdlog/spdlog.h> #include <windowsx.h> #include "CEConsole.h" #include "../Graphics/DirectX12/CEDX12Manager.h" #include "../Graphics/Vulkan/CEVManager.h" #include "../Graphics/OpenGL/CEOGLManager.h" namespace GameEngine = ConceptEngineFramework::Game; namespace GraphicsEngine = ConceptEngineFramework::Graphics; namespace DirectXGraphicsEngine = GraphicsEngine::DirectX12; namespace VulkanGraphicsEngine = GraphicsEngine::Vulkan; namespace OpenGLGraphicsEngine = GraphicsEngine::OpenGL; static GameEngine::CEGame* g_pGame = nullptr; /* * Instance for std::shared_ptr */ class CEConsoleInstance final : public GameEngine::CEConsole { public: CEConsoleInstance(const std::wstring& windowName, int maxFileSizeInMB = 5, int maxFiles = 3, int maxConsoleLines = 500) : CEConsole(windowName, maxFileSizeInMB, maxFiles, maxConsoleLines) { spdlog::info("ConceptEngineFramework Console class created."); } explicit CEConsoleInstance(const Logger& logger) : CEConsole(logger) { spdlog::info("ConceptEngineFramework Console class created."); CE_LOG("ConceptEngineFramework Console class created."); } }; class CEWindowInstance final : public GameEngine::CEWindow { public: CEWindowInstance(const std::wstring& windowName, HINSTANCE hInstance, int width, int height) : CEWindow(windowName, hInstance, width, height) { spdlog::info("ConceptEngineFramework Window class created."); } CEWindowInstance(const std::wstring& windowName, HWND hwnd, int width, int height) : CEWindow(windowName, hwnd, width, height) { spdlog::info("ConceptEngineFramework Window class created."); CE_LOG("ConceptEngineFramework Console class created.") } }; class CEDX12ManagerInstance final : public DirectXGraphicsEngine::CEDX12Manager { public: CEDX12ManagerInstance(ConceptEngineFramework::Game::CEWindow* window): CEDX12Manager(window) { spdlog::info("ConceptEngineFramework DirectX 12 Manager class created."); } CEDX12ManagerInstance(): CEDX12Manager() { spdlog::info("ConceptEngineFramework DirectX 12 Manager class created."); CE_LOG("ConceptEngineFramework DirectX 12 Manager class created.") } }; class CEVManagerInstance final : public VulkanGraphicsEngine::CEVManager { public: CEVManagerInstance(): CEVManager() { spdlog::info("ConceptEngineFramework Vulkan Manager class created."); CE_LOG("ConceptEngineFramework Vulkan Manager class created.") } }; class CEOGLManagerInstance final : public OpenGLGraphicsEngine::CEOGLManager { public: CEOGLManagerInstance(): CEOGLManager() { spdlog::info("ConceptEngineFramework OpenGL Manager class created."); CE_LOG("ConceptEngineFramework OpenGL Manager class created.") } }; GameEngine::CEGame::CEGame(std::wstring name, HINSTANCE hInst, int width, int height, Graphics::API graphicsAPI, Graphics::CEPlayground* playground) : m_name(name), m_hInstance(hInst), m_width(width), m_height(height), m_graphicsAPI(graphicsAPI), m_systemInfo{}, m_playground(playground) { } GameEngine::CEGame::CEGame(HWND hWnd, Graphics::API graphicsAPI, int width, int height, Graphics::CEPlayground* playground): m_hwnd(hWnd), m_graphicsAPI(graphicsAPI), m_systemInfo{}, m_width(width), m_height(height), m_playground(playground) { } void GameEngine::CEGame::Init() { SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); CreateConsole(m_name); CreateMainWindow(m_name, m_width, m_height); m_window->InitWindow(); SystemInfo(); CreateGraphicsManager(m_graphicsAPI); } void GameEngine::CEGame::LinkWithEditor() { CreateEditorWindow(m_name, m_hwnd, m_width, m_height); SystemInfo(); CreateEditorGraphicsManager(m_graphicsAPI); } CETimer ConceptEngineFramework::Game::CEGame::GetTimer() const { return m_timer; } void ConceptEngineFramework::Game::CEGame::EditorUpdateTimer() { m_timer.Update(); CalculateFPS(false); } void ConceptEngineFramework::Game::CEGame::EditorUpdate() const { m_graphicsManager->Update(m_timer); } void ConceptEngineFramework::Game::CEGame::EditorRender() const { m_graphicsManager->Render(m_timer); } void ConceptEngineFramework::Game::CEGame::EditorResize(int width, int height) const { m_window->SetWidth(width); m_window->SetHeight(height); m_graphicsManager->Resize(); } GameEngine::CEGame& GameEngine::CEGame::Create(std::wstring name, HINSTANCE hInst, int width, int height, Graphics::API graphicsAPI, Graphics::CEPlayground* playground) { if (!g_pGame) { g_pGame = new CEGame(name, hInst, width, height, graphicsAPI, playground); spdlog::info("ConceptEngineFramework Game class created."); } return *g_pGame; } ConceptEngineFramework::Game::CEGame& ConceptEngineFramework::Game::CEGame::Create( HWND hWnd, Graphics::API graphicsAPI, int width, int height, Graphics::CEPlayground* playground) { if (!g_pGame) { g_pGame = new CEGame(hWnd, graphicsAPI, width, height, playground); spdlog::info("ConceptEngineFramework Game class created."); } return *g_pGame; } void ConceptEngineFramework::Game::CEGame::SystemInfo() { m_systemInfo = GetEngineSystemInfo(); spdlog::info("CPU: {}, Threads: {}, RAM: {} MB", m_systemInfo.CPUName, m_systemInfo.CPUCores, m_systemInfo.RamSize); std::stringstream ss; ss << "CPU: " << m_systemInfo.CPUName << ", Threads: " << m_systemInfo.CPUCores << " RAM: " << m_systemInfo.RamSize << "MB"; CE_LOG(ss.str()) } void ConceptEngineFramework::Game::CEGame::CalculateFPS(bool showInTitleBar) const { static int frameCount = 0; static float timeElapsed = 0.0f; frameCount++; //Compute averages over one second period. if ((m_timer.TotalTime() - timeElapsed) >= 1.0f) { float fps = (float)frameCount; float msPerFrame = 1000.0f / fps; spdlog::info("FPS: {}", fps); spdlog::info("MSPF: {}", msPerFrame); std::stringstream fpsSS; fpsSS << "FPS: " << fps; // CE_LOG(fpsSS.str()) std::stringstream mspfSS; mspfSS << "MSPF: " << msPerFrame; // CE_LOG(mspfSS.str()) if (showInTitleBar) { std::wstring wFps = std::to_wstring(fps); std::wstring wMsPerFrame = std::to_wstring(msPerFrame); std::wstring fpsWindowName = m_window->GetName() + L" fps: " + wFps + L" mspf: " + wMsPerFrame; } frameCount = 0; timeElapsed += 1.0f; } } LRESULT GameEngine::CEGame::MsgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { // WM_ACTIVATE is sent when the window is activated or deactivated. // We pause the game when the window is deactivated and unpause it // when it becomes active. case WM_ACTIVATE: /* * NOTE: Potential reason of bug if (LOWORD(wParam) == WA_INACTIVE) { m_paused = true; m_timer.Stop(); } else { m_paused = false; m_timer.Start(); } */ return 0; // WM_SIZE is sent when the user resizes the window. case WM_SIZE: // Save the new client area dimensions. m_window->SetResolution(LOWORD(lParam), HIWORD(lParam)); if (m_graphicsManager) { if (m_graphicsManager->Initialized()) { if (wParam == SIZE_MINIMIZED) { m_paused = true; m_minimized = true; m_maximized = false; } else if (wParam == SIZE_MAXIMIZED) { m_paused = false; m_minimized = false; m_maximized = true; m_graphicsManager->Resize(); } else if (wParam == SIZE_RESTORED) { if (m_minimized) { m_paused = false; m_minimized = false; m_graphicsManager->Resize(); } else if (m_maximized) { m_paused = false; m_maximized = false; m_graphicsManager->Resize(); } else if (m_resizing) { // If user is dragging the resize bars, we do not resize // the buffers here because as the user continuously // drags the resize bars, a stream of WM_SIZE messages are // sent to the window, and it would be pointless (and slow) // to resize for each WM_SIZE message received from dragging // the resize bars. So instead, we reset after the user is // done resizing the window and releases the resize bars, which // sends a WM_EXITSIZEMOVE message. } else { m_graphicsManager->Resize(); } } } } return 0; // WM_EXITSIZEMOVE is sent when the user grabs the resize bars. case WM_ENTERSIZEMOVE: m_paused = true; m_resizing = true; m_timer.Stop(); return 0; // WM_EXITSIZEMOVE is sent when the user releases the resize bars. // Here we reset everything based on the new window dimensions. case WM_EXITSIZEMOVE: m_paused = false; m_resizing = false; m_timer.Start(); m_graphicsManager->Resize(); return 0; // WM_DESTROY is sent when the window is being destroyed. case WM_DESTROY: PostQuitMessage(0); return 0; // The WM_MENUCHAR message is sent when a menu is active and the user presses // a key that does not correspond to any mnemonic or accelerator key. case WM_MENUCHAR: // Don't beep when we alt-enter. return MAKELRESULT(0, MNC_CLOSE); // Catch this message so to prevent the window from becoming too small. case WM_GETMINMAXINFO: ((MINMAXINFO*)lParam)->ptMinTrackSize.x = 200; ((MINMAXINFO*)lParam)->ptMinTrackSize.y = 200; return 0; case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN: OnMouseDown(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); return 0; case WM_LBUTTONUP: case WM_MBUTTONUP: case WM_RBUTTONUP: OnMouseUp(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); return 0; case WM_MOUSEMOVE: OnMouseMove(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); return 0; case WM_KEYUP: case WM_SYSKEYUP: if (wParam == VK_ESCAPE) { PostQuitMessage(0); } else { OnKeyUp(wParam, lParam, m_timer); } return 0; case WM_KEYDOWN: case WM_SYSKEYDOWN: OnKeyDown(wParam, lParam, m_timer); OnKeyDown(wParam, lParam, m_timer); return 0; case WM_MOUSEWHEEL: { OnMouseWheel(wParam, lParam, hwnd); } return 0; } return DefWindowProc(hwnd, msg, wParam, lParam); } GameEngine::CEGame& GameEngine::CEGame::Get() { assert(g_pGame != nullptr); return *g_pGame; } //TODO: In editor mode instead of call Run, call every function from graphicsManager separately and use connect QT method to bind it with playground uint32_t GameEngine::CEGame::Run() { MSG msg = {0}; m_timer.Reset(); while (msg.message != WM_QUIT) { // If there are Window messages then process them. if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } // Otherwise, do animation/game stuff. else { m_timer.Update(); if (!m_paused) { CalculateFPS(true); m_graphicsManager->Update(m_timer); m_graphicsManager->Render(m_timer); } else { Sleep(100); } } } return (int)msg.wParam; } std::shared_ptr<GameEngine::CEConsole> GameEngine::CEGame::GetConsole() { return m_console; } void GameEngine::CEGame::CreateMainWindow(const std::wstring& windowName, int width, int height) { m_window = std::make_shared<CEWindowInstance>(windowName, m_hInstance, width, height); m_window->Create(); } void ConceptEngineFramework::Game::CEGame::CreateEditorWindow(const std::wstring& windowName, HWND hwnd, int width, int height) { m_window = std::make_shared<CEWindowInstance>(windowName, hwnd, width, height); } void GameEngine::CEGame::CreateGraphicsManager(Graphics::API graphicsAPI) { switch (graphicsAPI) { case Graphics::API::DirectX12_API: m_graphicsManager = std::make_shared<CEDX12ManagerInstance>(m_window.get()); break; case Graphics::API::Vulkan_API: m_graphicsManager = std::make_shared<CEVManagerInstance>(); break; case Graphics::API::OpenGL_API: m_graphicsManager = std::make_shared<CEOGLManagerInstance>(); break; default: m_graphicsManager = std::make_shared<CEDX12ManagerInstance>(m_window.get()); break; } m_graphicsManager->InitPlayground(m_playground); m_graphicsManager->Create(); } void ConceptEngineFramework::Game::CEGame::CreateEditorGraphicsManager(Graphics::API graphicsAPI) { switch (graphicsAPI) { case Graphics::API::DirectX12_API: m_graphicsManager = std::make_shared<CEDX12ManagerInstance>(m_window.get()); break; case Graphics::API::Vulkan_API: m_graphicsManager = std::make_shared<CEVManagerInstance>(); break; case Graphics::API::OpenGL_API: m_graphicsManager = std::make_shared<CEOGLManagerInstance>(); break; default: m_graphicsManager = std::make_shared<CEDX12ManagerInstance>(m_window.get()); break; } m_graphicsManager->InitPlayground(m_playground); m_graphicsManager->Create(); } void GameEngine::CEGame::CreateConsole(const std::wstring& windowName) { m_console = std::make_shared<CEConsoleInstance>(windowName); m_console->Create(); }
30.154897
148
0.694667
Ludaxord
c079906b878af68e36583ff66537acf054543149
956
cpp
C++
torch/csrc/distributed/c10d/logging.cpp
ljhOfGithub/pytorch
c568f7b16f2a98d72ff5b7c6c6161b67b2c27514
[ "Intel" ]
2
2020-03-13T06:57:49.000Z
2020-05-17T04:18:14.000Z
torch/csrc/distributed/c10d/logging.cpp
ellhe-blaster/pytorch
e5282c3cb8bf6ad8c5161f9d0cc271edb9abed25
[ "Intel" ]
1
2019-07-23T15:23:32.000Z
2019-07-23T15:32:23.000Z
torch/csrc/distributed/c10d/logging.cpp
ellhe-blaster/pytorch
e5282c3cb8bf6ad8c5161f9d0cc271edb9abed25
[ "Intel" ]
2
2019-07-23T14:37:31.000Z
2019-07-23T14:47:13.000Z
// Copyright (c) Meta Platforms, Inc. and its affiliates. // All rights reserved. // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include <c10d/logging.h> #include <c10d/debug.h> namespace c10d { namespace detail { bool isLogLevelEnabled(LogLevel level) noexcept { // c10 logger does not support debug and trace levels. In order to map higher // levels we adjust our ordinal value. int level_int = static_cast<int>(level) - 2; if (level_int >= 0) { return FLAGS_caffe2_log_level <= level_int; } // Debug and trace levels are only enabled when c10 log level is set to INFO. if (FLAGS_caffe2_log_level != 0) { return false; } if (level_int == -1) { return debug_level() != DebugLevel::Off; } if (level_int == -2) { return debug_level() == DebugLevel::Detail; } return false; } } // namespace detail } // namespace c10d
23.9
79
0.688285
ljhOfGithub
c07cae9204e813066bd15ab25d27470cdc4a1a8f
14,576
hpp
C++
include/drone.hpp
KPO-2020-2021/zad5_1-kgliwinski
0bd90e1e065f32363c77ad02e217406487850a99
[ "Unlicense" ]
null
null
null
include/drone.hpp
KPO-2020-2021/zad5_1-kgliwinski
0bd90e1e065f32363c77ad02e217406487850a99
[ "Unlicense" ]
null
null
null
include/drone.hpp
KPO-2020-2021/zad5_1-kgliwinski
0bd90e1e065f32363c77ad02e217406487850a99
[ "Unlicense" ]
null
null
null
#pragma once #include "prism.hpp" #include "cuboid.hpp" #include "lacze_do_gnuplota.hpp" #include <unistd.h> #include <vector> /*! * \file drone.hpp * * \brief Plik zawiera definicję klasy reprezentujacej drona, * budowanie i przemieszczanie go */ /*! * \class Drone * \brief Opisuje drona o prostopadlosciennym korpusie i 4 rotorach */ class Drone { private: /*! * \brief Zmienna reprezentujaca polozenie drona (dokladnie * polozenie punktu centralnego prostopadloscianu body) */ Vector3D drone_pos; /*! * \brief Zmienna reprezentujaca zwrot drona. * Reprezentowana przez jednostkowy Vector, * nie dopuszcza sie zwrotu pionowego. */ Vector3D drone_orient; /*! * \brief Zmienna reprezentujaca zwrot drona jako kat w stopniach. */ double drone_angle; /*! * \brief Tablica graniastoslupow szesciokatnych, * reprezentujaca rotory drona */ Prism rotors[4]; /*! * \brief Prostopadloscian reprezentujacy korpus drona */ Cuboid body; public: /*! * \brief Konstruktor bezparametryczny klasy Drone. * Powstaly dron jest skonstruowany z bezparametrycznych * prostopadloscianu (body) oraz rotorow przeskalowanych * 10-krotnie (aby sie poprawnie wyswietlal) w poziomie i * 5-krotnie w pionie (aby zachowac pewna poprawna skale) * \post Inicjalizuje podstawowego drona */ Drone(); /*! * \brief Metoda uzywana przy konstruowania drona * Ustawia rotory w ten sposob, ze srodek ich dolnej * podstawy jest w tym samym punkcie co wierzcholki * gornej podstawy body * \post Zmienia pozycje rotorow = *this */ void set_rotors_in_place(); /*! * \brief Przesuwa drona o zadany wektor w 3D * \param[in] trans - Vector3D * \param[out] translated - Dron po operacji przesuniecia */ Drone translation(Vector3D const &tran) const; /*! * \brief Metoda uzywana przy konstruowania drona * przesuwa drona w ten sposob, ze Vector3D * centre prostopadloscianu body pokrywa sie * z Vector3D pos * \returns translated - przesuniety dron */ Drone translation_to_pos() const; /*! * \brief Metoda obracajaca dron o zadany kat w 3D wokol srodka figury * \param[in] mat - macierz obrotu * \param[out] rotated - dron po przeprowadzonej rotacji */ Drone rotation_around_cen(const Matrix3D &mat) const; /*! * \brief Metoda skalujaca wszystkie elementy drona przez skale kazdego elementu * \param[out] scaled - dron po operacji skalowania */ Drone scale_dro() const; /*! * \brief Przeciazenie operatora == dla klasy Drone * \param[in] dro - porownywany dron * \retval false - nie sa rowne, * \retval true - sa rowne */ bool operator==(const Drone &dro) const; /*! * \brief Metoda ustawiajaca drone_pos * \pre Pozycja drona musi znajdowac sie nad plaszcyzna. * Punktem referencji jest srodek prostopadloscianu body, wiec * aby dron nie zapadal sie w podloze, minimalna wspolrzedna z polozenia * nie moze nigdy byc mniejsza od polowy wysokosci prostopadloscianu * \param[in] pos - wektor pozycji * \post Ustawia pozycje drona (zadana przez uzytkownika) * \retval false - jesli wprowadzona pozycja jest bledna * \retval true - jesli jest prawidlowa */ bool set_drone_pos(Vector3D const &pos); /*! * \brief Metoda wypisuje na standardowym wyjsciu pozycje drona (bez wysokosci) */ void print_drone_pos() const; /*! * \brief Metoda ustawiajaca skale wszystkich elementow drona * \param[in] bod - skala korpusu * \param[in] rot - skala rotorow * \post Ustawia skale korpusa i rotorow */ void set_scale_all(Vector3D const &bod, Vector3D const &rot); /*! * \brief Metoda zwracajaca wszystkie elementy drona do odpowiednich zmiennych * \param[in] b - tu zwrocone bedzie body * \param[in] rot - tu zostana zwrocone odpowiednio rotory * \param[in] p - wektor pozycji * \post Zwraca odpowiednio pola klasy Drone */ void get_dro(Cuboid &b, Prism (&rot)[4], Vector3D &p) const; /*! * \brief Metoda sprawdzajaca budowe drona * \retval true - dron odpowiednio zbudowany * \retval false - dron blednie zbudowany */ bool check_dro() const; /*! * \brief Metoda zwracajaca orientacje drona * \return res - Zwracana orientacja */ Vector3D get_orien() const; /*! * \brief Metoda sprawdzajaca orientacje drona * Vector3D dron_orien musi byc jednostkowy, oraz miec skladowa z=0 * \retval true - odpowiednia orientacja * \retval false - bledna orientacja */ bool check_orien() const; /*! * \brief Metoda ustawiajaca nazwy plikow do zapisu dla drona * \param[in] bod - tablica nazw plikow odpowiednio 0-sample_name, 1-final_name; * zawierajacych dane do korpusu drona * \param[in] rots - analogiczna tablica co bod, dla rotorow drona * \post Zmienia obiekt, przypisuje mu odpowiednie parametry */ void setup_filenames(std::string const (&bod)[2], std::string const (&rots)[4][2]); /*! * \brief Metoda ustawiajaca nazwy plikow w laczy do gnuplota (nazwy final!) * \param[in] Lacze - lacze do ktorego wpisane zostana nazwy * \pre Metoda wymaga zainicjowanych nazw elementow drona * \post Zmienia lacze, przypisuje mu odpowiednie parametry */ bool set_filenames_gnuplot(PzG::LaczeDoGNUPlota &Lacze) const; /*! * \brief Metoda zwracajaca nazwy plikow do zapisu dla drona * \param[in] bod - tablica nazw plikow odpowiednio 0-sample_name, 1-final_name; * do ktorych zwracane sa nazwy * \param[in] rots - analogiczna tablica co bod, dla rotorow drona * \return przypisuje argumentom odpowiednie wartosci */ void get_filenames(std::string (&bod)[2], std::string (&rots)[4][2]) const; /*! * \brief Metoda rysujaca drona w gnuplocie. Przeznaczona do testow * \post Wyswietla okienko gnuplota z wyrysowanym dronem */ void Print_to_gnuplot_drone() const; /*! * \brief Metoda zapisujaca parametry drona do plikow (do plikow final kazdego z elementow) * \post Aktualizuje pliki z danymi */ void Print_to_files_drone() const; /*! * \brief Metoda animujaca obrot rotorow i zapisujaca to w plikach. * Metoda sluzy jako metoda pomocnicza, przy kazdej animacji (translacji czy * rotacji drona) rotory sie niezaleznie obracaja. Ta metoda to umozliwia. * \pre Pliki musza byc odpowiednio skonfigurowane * \post Rotory sa obracane o kat 1 stopnia, zmieniany jest obiekt drona * efekt rotacji zapisywnay jest w plikach */ void Rotors_rotation_animation(); /*! * \brief Metoda animujaca obrot drona i wyrysowujaca calosc w gnuplocie * \pre Lacze musi byc odpowiednio skonfigurowane * \param[in] Lacze - aktywne lacze do gnuplota * \param[in] angle - kat obrotu w stopniach, obrot wykonuje sie wylacznie wokol osi z * \post W oknie gnuplota wykonuje sie animacja obrotu drona */ void Drone_rotation_animation(PzG::LaczeDoGNUPlota Lacze, double const &angle); /*! * \brief Metoda przygotowujaca sciezke drona z uzyciem std::vector<> * \pre Lacze musi byc odpowiednio skonfigurowane. Wektor translacji * musi miec zerowa wpolrzedna z * \param[in] tran - wektor translacji * \param[in] path - std::vector<> do ktorego zapisywana jest sciezka * \post W oknie gnuplota wyrysowuje sie sciezka drona * \retval true - jesli jest odpowiednio skonfigurowane lacze * \retval false - w przeciwnym wypadku */ bool Drone_make_path( Vector3D const &tran, std::vector<Vector3D> &path); /*! * \brief Metoda zapisujaca sciezke do pliku oraz do lacza * \param[in] path - std::vector<> z ktorego wypisywana jest sciezka * \param[in] name - nazwa pliku do zapisu * \param[in] Lacze - lacze do gnuplota * \post W podanym pliku zapisuje sie sciezka, jest rysowana w gnuplocie * \retval true - jesli zapis sie powiedzie * \retval false - w przeciwnym wypadku */ bool Drone_path_to_file(std::vector<Vector3D> &path, std::string const &name, PzG::LaczeDoGNUPlota &Lacze); /*! * \brief Oczyszcza plik ze sciezka * \param[in] name - nazwa pliku ze sciezka * \retval true - jesli operacja sie powiedzie * \retval false - w przeciwnym wypadku */ bool Drone_path_clear(std::string const &name); /*! * \brief Metoda animujaca translacje drona i wyrysowujaca calosc w gnuplocie * \pre Lacze musi byc odpowiednio skonfigurowane * \param[in] Lacze - aktywne lacze do gnuplota * \param[in] tran - wektor translacji * \post W oknie gnuplota wykonuje sie animacja translacji drona */ void Drone_translation_animation(PzG::LaczeDoGNUPlota &Lacze, Vector3D const &tran); /*! * \brief Metoda zamieniajaca drona na tego z pliku sample * \pre PLiki musza byc odpowiednio skonfigurowane * \param[in] angle - jesli dron roboczy jest obrocony o pewien kat, nalezy * podac ten kat w metodzie * \post Zamienia drona na tego o wzorcowych wymiarach */ void Drone_change_to_sample(double const &angle); /*! * \brief Metoda wczytywania odpowiednich wierzcholkow z pliku wzorcowego * zgodnie z zaproponowanym sposobem w zadaniu dron. * Przypisuje wczytane wierzcholki do elementow drona. * \param[out] dro - wczytwany dron */ Drone Drone_From_Sample() const; /*! * \brief Metoda obliczajaca i przeprowadzajaca caly ruch drona * (obrot o kat i przelot z zadania 5.1) * \pre Lacze musi byc odpowiednio skonfigurowane * \param[in] angle - kat w stopniach * \param[in] len - dlugosc przelotu * \param[in] Lacze - aktywne lacze do gnuplota * \post W oknie gnuplota wykonuje sie animacja ruchu drona * \retval true - jesli operacja sie powiedzie * \retval false - w przeciwnym wypadku */ bool Drone_basic_motion(double const &angle, double const &len, PzG::LaczeDoGNUPlota &Lacze); /*! * \brief Metoda robiaca "oblot" drona wokol punktu (z modyfikacji) * \pre Lacze musi byc odpowiednio skonfigurowane * \param[in] radius - promien okregu * \param[in] Lacze - aktywne lacze do gnuplota * \post W oknie gnuplota wykonuje sie animacja ruchu drona * \retval true - jesli operacja sie powiedzie * \retval false - w przeciwnym wypadku */ bool Drone_roundabout(double const &radius, PzG::LaczeDoGNUPlota &Lacze); /*! * \brief Metoda przygotowujaca sciezke drona z uzyciem std::vector<> do roundabout * \pre Lacze musi byc odpowiednio skonfigurowane. Promien musi byc dodatni * \param[in] radius - promien okregu * \param[in] path - std::vector<> do ktorego zapisywana jest sciezka * \post W oknie gnuplota wyrysowuje sie sciezka drona * \retval true - jesli jest odpowiednio skonfigurowane lacze * \retval false - w przeciwnym wypadku */ bool Drone_make_path_roundabout(double const &radius, std::vector<Vector3D> &path); };
46.868167
176
0.525796
KPO-2020-2021
c07cd1d2f1f988efc4c9d5488d644eba2c3ed223
908
cpp
C++
Spectro.Arduino/ColorAnimator.cpp
SKKbySSK/Spectro
3f89838321b07e061575b995c46a154df3b50be3
[ "MIT" ]
null
null
null
Spectro.Arduino/ColorAnimator.cpp
SKKbySSK/Spectro
3f89838321b07e061575b995c46a154df3b50be3
[ "MIT" ]
null
null
null
Spectro.Arduino/ColorAnimator.cpp
SKKbySSK/Spectro
3f89838321b07e061575b995c46a154df3b50be3
[ "MIT" ]
null
null
null
#include "Arduino.h" #ifndef __COLOR__ #define __COLOR__ #include "Color.cpp" #endif extern unsigned long timer0_millis; class ColorAnimator { private: int time; float durationMs; unsigned long offset, position; int dr, dg, db, r, g, b; Color color, from, to; public: float Progress; ColorAnimator(Color from, Color to, float durationMs) { this->from = from; this->to = to; this->durationMs = durationMs; } void Start() { offset = millis(); position = 0; Progress = 0; color = from; } Color Update() { position = millis() - offset; Progress = position / durationMs; Progress = min(1, Progress); dr = to.r - from.r; dg = to.g - from.g; db = to.b - from.b; r = from.r + (int)(dr * Progress); g = from.g + (int)(dg * Progress); b = from.b + (int)(db * Progress); color = Color(r, g, b); return color; } };
18.530612
57
0.594714
SKKbySSK
c07e0d23bcf83823c2e2554635644f1701758d8c
2,325
cpp
C++
Hypodermic.Tests/RegistrationTests.cpp
KirillShirkunov/Hypodermic
2c5466ae092dd16f3b55a385856a9ddf3215a5f6
[ "MIT" ]
419
2015-01-01T18:43:59.000Z
2022-03-21T08:33:56.000Z
Hypodermic.Tests/RegistrationTests.cpp
KirillShirkunov/Hypodermic
2c5466ae092dd16f3b55a385856a9ddf3215a5f6
[ "MIT" ]
39
2015-02-12T10:34:18.000Z
2021-09-22T12:01:24.000Z
Hypodermic.Tests/RegistrationTests.cpp
KirillShirkunov/Hypodermic
2c5466ae092dd16f3b55a385856a9ddf3215a5f6
[ "MIT" ]
91
2015-02-03T04:50:46.000Z
2022-03-24T07:31:48.000Z
#include "stdafx.h" #include "Hypodermic/ContainerBuilder.h" #include "TestingTypes.h" namespace Hypodermic { namespace Testing { BOOST_AUTO_TEST_SUITE(RegistrationTests) BOOST_AUTO_TEST_CASE(should_call_activation_handler_everytime_an_instance_is_activated_through_resolution) { // Arrange ContainerBuilder builder; std::vector< std::shared_ptr< DefaultConstructible1 > > activatedInstances; // Act builder.registerType< DefaultConstructible1 >().onActivated([&activatedInstances](ComponentContext&, const std::shared_ptr< DefaultConstructible1 >& instance) { activatedInstances.push_back(instance); }); auto container = builder.build(); // Assert auto instance1 = container->resolve< DefaultConstructible1 >(); BOOST_CHECK(instance1 != nullptr); auto instance2 = container->resolve< DefaultConstructible1 >(); BOOST_CHECK(instance2 != nullptr); BOOST_CHECK(instance1 != instance2); BOOST_REQUIRE_EQUAL(activatedInstances.size(), 2u); BOOST_CHECK(instance1 == activatedInstances[0]); BOOST_CHECK(instance2 == activatedInstances[1]); } BOOST_AUTO_TEST_CASE(should_call_activation_handler_only_once_for_single_instance_mode) { // Arrange ContainerBuilder builder; std::vector< std::shared_ptr< DefaultConstructible1 > > activatedInstances; // Act builder.registerType< DefaultConstructible1 >() .singleInstance() .onActivated([&activatedInstances](ComponentContext&, const std::shared_ptr< DefaultConstructible1 >& instance) { activatedInstances.push_back(instance); }); auto container = builder.build(); // Assert auto instance1 = container->resolve< DefaultConstructible1 >(); BOOST_CHECK(instance1 != nullptr); auto instance2 = container->resolve< DefaultConstructible1 >(); BOOST_CHECK(instance2 != nullptr); BOOST_CHECK(instance1 == instance2); BOOST_REQUIRE_EQUAL(activatedInstances.size(), 1u); BOOST_CHECK(instance1 == activatedInstances[0]); } BOOST_AUTO_TEST_SUITE_END() } // namespace Testing } // namespace Hypodermic
30.194805
166
0.669677
KirillShirkunov
c07e324e1581990bbd78a66114c6b67e8f88d4ea
2,096
hpp
C++
src/mpi/channel_base.hpp
angainor/oomph
67a3a680cb3d68e4b7a71e6e1745e7a98076c44a
[ "BSD-3-Clause" ]
null
null
null
src/mpi/channel_base.hpp
angainor/oomph
67a3a680cb3d68e4b7a71e6e1745e7a98076c44a
[ "BSD-3-Clause" ]
6
2021-11-11T07:40:55.000Z
2022-01-11T09:26:19.000Z
src/mpi/channel_base.hpp
angainor/oomph
67a3a680cb3d68e4b7a71e6e1745e7a98076c44a
[ "BSD-3-Clause" ]
2
2021-09-03T20:26:46.000Z
2021-11-10T09:20:12.000Z
/* * ghex-org * * Copyright (c) 2014-2021, ETH Zurich * All rights reserved. * * Please, refer to the LICENSE file in the root directory. * SPDX-License-Identifier: BSD-3-Clause */ #pragma once #include <oomph/util/mpi_error.hpp> #include "./context.hpp" namespace oomph { class channel_base { protected: using heap_type = context_impl::heap_type; using pointer = heap_type::pointer; using handle_type = typename pointer::handle_type; using key_type = typename handle_type::key_type; using flag_basic_type = key_type; using flag_type = flag_basic_type volatile; protected: //heap_type& m_heap; std::size_t m_size; std::size_t m_T_size; std::size_t m_levels; std::size_t m_capacity; communicator::rank_type m_remote_rank; communicator::tag_type m_tag; bool m_connected = false; MPI_Request m_init_req; public: channel_base(/*heap_type& h,*/ std::size_t size, std::size_t T_size, communicator::rank_type remote_rank, communicator::tag_type tag, std::size_t levels) //: m_heap{h} : m_size{size} , m_T_size{T_size} , m_levels{levels} , m_capacity{levels} , m_remote_rank{remote_rank} , m_tag{tag} { } void connect() { OOMPH_CHECK_MPI_RESULT(MPI_Wait(&m_init_req, MPI_STATUS_IGNORE)); m_connected = true; } protected: // index of flag in buffer (in units of flag_basic_type) std::size_t flag_offset() const noexcept { return (m_size * m_T_size + 2 * sizeof(flag_basic_type) - 1) / sizeof(flag_basic_type) - 1; } // number of elements of type T (including padding) std::size_t buffer_size() const noexcept { return ((flag_offset() + 1) * sizeof(flag_basic_type) + m_T_size - 1) / m_T_size; } // pointer to flag location for a given buffer void* flag_ptr(void* ptr) const noexcept { return (void*)((char*)ptr + flag_offset() * sizeof(flag_basic_type)); } }; } // namespace oomph
27.578947
99
0.636927
angainor
c08275c8eab4ac156ab4cdaff119ebce6773abc6
1,554
hpp
C++
menoh/composite_backend/backend/generic/operator/identity.hpp
xeddmc/menoh
c00e8d5c2e9f46d7228b2f8130ae0d5254005ca1
[ "MIT" ]
284
2018-06-21T02:00:08.000Z
2021-11-22T07:50:22.000Z
menoh/composite_backend/backend/generic/operator/identity.hpp
xeddmc/menoh
c00e8d5c2e9f46d7228b2f8130ae0d5254005ca1
[ "MIT" ]
174
2018-06-21T06:01:57.000Z
2020-12-28T06:26:55.000Z
menoh/composite_backend/backend/generic/operator/identity.hpp
xeddmc/menoh
c00e8d5c2e9f46d7228b2f8130ae0d5254005ca1
[ "MIT" ]
33
2018-06-21T04:19:17.000Z
2020-05-08T12:51:55.000Z
#ifndef MENOH_IMPL_COMPOSITE_BACKEND_BACKEND_GENERIC_OPERATOR_IDENTITY_HPP #define MENOH_IMPL_COMPOSITE_BACKEND_BACKEND_GENERIC_OPERATOR_IDENTITY_HPP #include <algorithm> #include <menoh/array.hpp> #include <menoh/composite_backend/procedure.hpp> namespace menoh_impl { namespace composite_backend { namespace generic_backend { inline procedure make_identity(node const& /*node*/, std::vector<array> const& input_list, std::vector<array> const& output_list) { assert(input_list.size() == 1); assert(output_list.size() == 1); auto procedure = [input = input_list.at(0), output = output_list.at(0)]() { for(decltype(total_size(input)) i = 0; i < total_size(input); ++i) { fat(output, i) = fat(input, i); std::copy(static_cast<char*>(input.data()), static_cast<char*>(input.data()) + total_size(input) * get_size_in_bytes(input.dtype()), static_cast<char*>(output.data())); } }; return procedure; } } // namespace generic_backend } // namespace composite_backend } // namespace menoh_impl #endif // MENOH_IMPL_COMPOSITE_BACKEND_BACKEND_GENERIC_OPERATOR_IDENTITY_HPP
38.85
76
0.530888
xeddmc
c08386a52f78739a01a120394aa9317dae7e20ed
37,370
cpp
C++
Plugins/agsblend/AGSBlend.cpp
rofl0r/ags
23fcd2bef1c9b0ef61d849b0f78a2b4f5e9b712d
[ "Artistic-2.0" ]
2
2020-06-26T11:40:27.000Z
2021-06-14T15:58:09.000Z
Plugins/agsblend/AGSBlend.cpp
rofl0r/ags
23fcd2bef1c9b0ef61d849b0f78a2b4f5e9b712d
[ "Artistic-2.0" ]
null
null
null
Plugins/agsblend/AGSBlend.cpp
rofl0r/ags
23fcd2bef1c9b0ef61d849b0f78a2b4f5e9b712d
[ "Artistic-2.0" ]
null
null
null
/*********************************************************** * AGSBlend * * * * Author: Steven Poulton * * * * Date: 09/01/2011 * * * * Description: An AGS Plugin to allow true Alpha Blending * * * ***********************************************************/ #pragma region Defines_and_Includes #define MIN_EDITOR_VERSION 1 #define MIN_ENGINE_VERSION 3 #ifdef WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif #include <stdlib.h> #include <stdio.h> #include <math.h> #if !defined(BUILTIN_PLUGINS) #define THIS_IS_THE_PLUGIN #endif #include "../../Common/agsplugin.h" #if defined(BUILTIN_PLUGINS) namespace agsblend { #endif typedef unsigned char uint8; #define DEFAULT_RGB_R_SHIFT_32 16 #define DEFAULT_RGB_G_SHIFT_32 8 #define DEFAULT_RGB_B_SHIFT_32 0 #define DEFAULT_RGB_A_SHIFT_32 24 #if !defined(WINDOWS_VERSION) #define min(x,y) (((x) < (y)) ? (x) : (y)) #define max(x,y) (((x) > (y)) ? (x) : (y)) #endif #define abs(a) ((a)<0 ? -(a) : (a)) #define ChannelBlend_Normal(B,L) ((uint8)(B)) #define ChannelBlend_Lighten(B,L) ((uint8)((L > B) ? L:B)) #define ChannelBlend_Darken(B,L) ((uint8)((L > B) ? B:L)) #define ChannelBlend_Multiply(B,L) ((uint8)((B * L) / 255)) #define ChannelBlend_Average(B,L) ((uint8)((B + L) / 2)) #define ChannelBlend_Add(B,L) ((uint8)(min(255, (B + L)))) #define ChannelBlend_Subtract(B,L) ((uint8)((B + L < 255) ? 0:(B + L - 255))) #define ChannelBlend_Difference(B,L) ((uint8)(abs(B - L))) #define ChannelBlend_Negation(B,L) ((uint8)(255 - abs(255 - B - L))) #define ChannelBlend_Screen(B,L) ((uint8)(255 - (((255 - B) * (255 - L)) >> 8))) #define ChannelBlend_Exclusion(B,L) ((uint8)(B + L - 2 * B * L / 255)) #define ChannelBlend_Overlay(B,L) ((uint8)((L < 128) ? (2 * B * L / 255):(255 - 2 * (255 - B) * (255 - L) / 255))) #define ChannelBlend_SoftLight(B,L) ((uint8)((L < 128)?(2*((B>>1)+64))*((float)L/255):(255-(2*(255-((B>>1)+64))*(float)(255-L)/255)))) #define ChannelBlend_HardLight(B,L) (ChannelBlend_Overlay(L,B)) #define ChannelBlend_ColorDodge(B,L) ((uint8)((L == 255) ? L:min(255, ((B << 8 ) / (255 - L))))) #define ChannelBlend_ColorBurn(B,L) ((uint8)((L == 0) ? L:max(0, (255 - ((255 - B) << 8 ) / L)))) #define ChannelBlend_LinearDodge(B,L)(ChannelBlend_Add(B,L)) #define ChannelBlend_LinearBurn(B,L) (ChannelBlend_Subtract(B,L)) #define ChannelBlend_LinearLight(B,L)((uint8)(L < 128)?ChannelBlend_LinearBurn(B,(2 * L)):ChannelBlend_LinearDodge(B,(2 * (L - 128)))) #define ChannelBlend_VividLight(B,L) ((uint8)(L < 128)?ChannelBlend_ColorBurn(B,(2 * L)):ChannelBlend_ColorDodge(B,(2 * (L - 128)))) #define ChannelBlend_PinLight(B,L) ((uint8)(L < 128)?ChannelBlend_Darken(B,(2 * L)):ChannelBlend_Lighten(B,(2 * (L - 128)))) #define ChannelBlend_HardMix(B,L) ((uint8)((ChannelBlend_VividLight(B,L) < 128) ? 0:255)) #define ChannelBlend_Reflect(B,L) ((uint8)((L == 255) ? L:min(255, (B * B / (255 - L))))) #define ChannelBlend_Glow(B,L) (ChannelBlend_Reflect(L,B)) #define ChannelBlend_Phoenix(B,L) ((uint8)(min(B,L) - max(B,L) + 255)) #define ChannelBlend_Alpha(B,L,O) ((uint8)(O * B + (1 - O) * L)) #define ChannelBlend_AlphaF(B,L,F,O) (ChannelBlend_Alpha(F(B,L),B,O)) #pragma endregion #if defined(WINDOWS_VERSION) // The standard Windows DLL entry point BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } #endif //define engine IAGSEngine *engine; #pragma region Color_Functions int getr32(int c) { return ((c >> DEFAULT_RGB_R_SHIFT_32) & 0xFF); } int getg32 (int c) { return ((c >> DEFAULT_RGB_G_SHIFT_32) & 0xFF); } int getb32 (int c) { return ((c >> DEFAULT_RGB_B_SHIFT_32) & 0xFF); } int geta32 (int c) { return ((c >> DEFAULT_RGB_A_SHIFT_32) & 0xFF); } int makeacol32 (int r, int g, int b, int a) { return ((r << DEFAULT_RGB_R_SHIFT_32) | (g << DEFAULT_RGB_G_SHIFT_32) | (b << DEFAULT_RGB_B_SHIFT_32) | (a << DEFAULT_RGB_A_SHIFT_32)); } #pragma endregion #pragma region Pixel32_Definition struct Pixel32{ public: Pixel32(); ~Pixel32() {} int GetColorAsInt(); int Red; int Green; int Blue; int Alpha; }; Pixel32::Pixel32() { Red = 0; Blue = 0; Green = 0; Alpha = 0; } int Pixel32::GetColorAsInt() { return makeacol32(Red,Green,Blue,Alpha); } #pragma endregion /// <summary> /// Gets the alpha value at coords x,y /// </summary> int GetAlpha(int sprite, int x, int y){ BITMAP *engineSprite = engine->GetSpriteGraphic(sprite); unsigned char **charbuffer = engine->GetRawBitmapSurface (engineSprite); unsigned int **longbuffer = (unsigned int**)charbuffer; int alpha = geta32(longbuffer[y][x]); engine->ReleaseBitmapSurface (engineSprite); return alpha; } /// <summary> /// Sets the alpha value at coords x,y /// </summary> int PutAlpha(int sprite, int x, int y, int alpha){ BITMAP *engineSprite = engine->GetSpriteGraphic(sprite); unsigned char **charbuffer = engine->GetRawBitmapSurface (engineSprite); unsigned int **longbuffer = (unsigned int**)charbuffer; int r = getr32(longbuffer[y][x]); int g = getg32(longbuffer[y][x]); int b = getb32(longbuffer[y][x]); longbuffer[y][x] = makeacol32(r,g,b,alpha); engine->ReleaseBitmapSurface (engineSprite); return alpha; } /// <summary> /// Translates index from a 2D array to a 1D array /// </summary> int xytolocale(int x, int y, int width){ return (y * width + x); } int HighPass(int sprite, int threshold){ BITMAP* src = engine->GetSpriteGraphic(sprite); long srcWidth, srcHeight; engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, NULL); unsigned char **srccharbuffer = engine->GetRawBitmapSurface (src); unsigned int **srclongbuffer = (unsigned int**)srccharbuffer; for (int y = 0; y<srcHeight; y++){ for (int x = 0; x<srcWidth; x++){ int srcr = getb32(srclongbuffer[y][x]); int srcg = getg32(srclongbuffer[y][x]); int srcb = getr32(srclongbuffer[y][x]); int tempmaxim = max(srcr, srcg); int maxim = max(tempmaxim, srcb); int tempmin = min( srcr, srcg); int minim = min( srcb, tempmin); int light = (maxim + minim) /2 ; if (light < threshold) srclongbuffer[y][x] = makeacol32(0,0,0,0); } } return 0; } int Blur (int sprite, int radius) { BITMAP* src = engine->GetSpriteGraphic(sprite); long srcWidth, srcHeight; engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, NULL); unsigned char **srccharbuffer = engine->GetRawBitmapSurface (src); unsigned int **srclongbuffer = (unsigned int**)srccharbuffer; int negrad = -1 * radius; //use a 1Dimensional array since the array is on the free store, not the stack Pixel32 * Pixels = new Pixel32[(srcWidth + (radius * 2)) * (srcHeight + (radius * 2))]; // this defines a copy of the individual channels in class form. Pixel32 * Dest = new Pixel32[(srcWidth + (radius * 2)) * (srcHeight + (radius * 2))]; // this is the destination sprite. both have a border all the way round equal to the radius for the blurring. Pixel32 * Temp = new Pixel32[(srcWidth + (radius * 2)) * (srcHeight + (radius * 2))]; int arraywidth = srcWidth + (radius * 2); //define the array width since its used many times in the algorithm for (int y = 0; y<srcHeight; y++){ //copy the sprite to the Pixels class array for (int x = 0; x<srcWidth; x++){ int locale = xytolocale(x + radius, y + radius, arraywidth); Pixels[locale].Red = getr32(srclongbuffer[y][x]); Pixels[locale].Green = getg32(srclongbuffer[y][x]); Pixels[locale].Blue = getb32(srclongbuffer[y][x]); Pixels[locale].Alpha = geta32(srclongbuffer[y][x]); } } int numofpixels = (radius * 2 + 1); for (int y = 0; y < srcHeight; y++) { int totalr = 0; int totalg = 0; int totalb = 0; int totala = 0; // Process entire window for first pixel for (int kx = negrad; kx <= radius; kx++){ int locale = xytolocale(kx + radius, y + radius, arraywidth); totala += Pixels[locale].Alpha; totalr += (Pixels[locale].Red * Pixels[locale].Alpha)/ 255; totalg += (Pixels[locale].Green * Pixels[locale].Alpha)/ 255; totalb += (Pixels[locale].Blue * Pixels[locale].Alpha)/ 255; } int locale = xytolocale(radius, y + radius, arraywidth); Temp[locale].Red = totalr / numofpixels; // take an average and assign it to the destination array Temp[locale].Green = totalg / numofpixels; Temp[locale].Blue = totalb / numofpixels; Temp[locale].Alpha = totala / numofpixels; // Subsequent pixels just update window total for (int x = 1; x < srcWidth; x++) { // Subtract pixel leaving window int locale = xytolocale(x - 1, y + radius, arraywidth); totala -= Pixels[locale].Alpha; totalr -= (Pixels[locale].Red * Pixels[locale].Alpha)/ 255; totalg -= (Pixels[locale].Green * Pixels[locale].Alpha)/ 255; totalb -= (Pixels[locale].Blue * Pixels[locale].Alpha)/ 255; // Add pixel entering window locale = xytolocale(x + radius + radius, y + radius, arraywidth); totala += Pixels[locale].Alpha; totalr += (Pixels[locale].Red * Pixels[locale].Alpha)/ 255; totalg += (Pixels[locale].Green * Pixels[locale].Alpha)/ 255; totalb += (Pixels[locale].Blue * Pixels[locale].Alpha)/ 255; locale = xytolocale(x + radius, y + radius, arraywidth); Temp[locale].Red = totalr / numofpixels; // take an average and assign it to the destination array Temp[locale].Green = totalg / numofpixels; Temp[locale].Blue = totalb / numofpixels; Temp[locale].Alpha = totala / numofpixels; } } for (int x = 0; x < srcWidth; x++) { int totalr = 0; int totalg = 0; int totalb = 0; int totala = 0; // Process entire window for first pixel for (int ky = negrad; ky <= radius; ky++){ int locale = xytolocale(x + radius, ky + radius, arraywidth); totala += Temp[locale].Alpha; totalr += (Temp[locale].Red * Temp[locale].Alpha)/ 255; totalg += (Temp[locale].Green * Temp[locale].Alpha)/ 255; totalb += (Temp[locale].Blue * Temp[locale].Alpha)/ 255; } int locale = xytolocale(x + radius,radius, arraywidth); Dest[locale].Red = totalr / numofpixels; // take an average and assign it to the destination array Dest[locale].Green = totalg / numofpixels; Dest[locale].Blue = totalb / numofpixels; Dest[locale].Alpha = totala / numofpixels; // Subsequent pixels just update window total for (int y = 1; y < srcHeight; y++) { // Subtract pixel leaving window int locale = xytolocale(x + radius, y - 1, arraywidth); totala -= Temp[locale].Alpha; totalr -= (Temp[locale].Red * Temp[locale].Alpha)/ 255; totalg -= (Temp[locale].Green * Temp[locale].Alpha)/ 255; totalb -= (Temp[locale].Blue * Temp[locale].Alpha)/ 255; // Add pixel entering window locale = xytolocale(x + radius, y + radius + radius, arraywidth); totala += Temp[locale].Alpha; totalr += (Temp[locale].Red * Temp[locale].Alpha)/ 255; totalg += (Temp[locale].Green * Temp[locale].Alpha)/ 255; totalb += (Temp[locale].Blue * Temp[locale].Alpha)/ 255; locale = xytolocale(x + radius, y + radius, arraywidth); Dest[locale].Red = totalr / numofpixels; // take an average and assign it to the destination array Dest[locale].Green = totalg / numofpixels; Dest[locale].Blue = totalb / numofpixels; Dest[locale].Alpha = totala / numofpixels; } } for (int y = 0; y<srcHeight; y++){ for (int x = 0; x<srcWidth; x++){ int locale = xytolocale(x + radius, y + radius, arraywidth); srclongbuffer[y][x] = Dest[locale].GetColorAsInt(); //write the destination array to the main buffer } } delete [] Pixels; delete [] Dest; delete [] Temp; engine->ReleaseBitmapSurface(src); delete srclongbuffer; delete srccharbuffer; return 0; } int Clamp(int val, int min, int max){ if (val < min) return min; else if (val > max) return max; else return val; } int DrawSprite(int destination, int sprite, int x, int y, int DrawMode, int trans){ trans = 100 - trans; long srcWidth, srcHeight, destWidth, destHeight; BITMAP* src = engine->GetSpriteGraphic(sprite); BITMAP* dest = engine->GetSpriteGraphic(destination); engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, NULL); engine->GetBitmapDimensions(dest, &destWidth, &destHeight, NULL); if (x > destWidth || y > destHeight || x + srcWidth < 0 || y + srcHeight < 0) return 1; // offscreen unsigned char **srccharbuffer = engine->GetRawBitmapSurface (src); unsigned int **srclongbuffer = (unsigned int**)srccharbuffer; unsigned char **destcharbuffer = engine->GetRawBitmapSurface (dest); unsigned int **destlongbuffer = (unsigned int**)destcharbuffer; if (srcWidth + x > destWidth) srcWidth = destWidth - x - 1; if (srcHeight + y > destHeight) srcHeight = destHeight - y - 1; int destx, desty; int srcr, srcg, srcb, srca, destr, destg, destb, desta, finalr, finalg, finalb, finala; unsigned int col; int starty = 0; int startx = 0; if (x < 0) startx = -1 * x; if (y < 0) starty = -1 * y; int ycount = 0; int xcount = 0; for(ycount = starty; ycount<srcHeight; ycount ++){ for(xcount = startx; xcount<srcWidth; xcount ++){ destx = xcount + x; desty = ycount + y; srca = (geta32(srclongbuffer[ycount][xcount])); if (srca != 0) { srca = srca * trans / 100; srcr = getr32(srclongbuffer[ycount][xcount]); srcg = getg32(srclongbuffer[ycount][xcount]); srcb = getb32(srclongbuffer[ycount][xcount]); destr = getr32(destlongbuffer[desty][destx]); destg = getg32(destlongbuffer[desty][destx]); destb = getb32(destlongbuffer[desty][destx]); desta = geta32(destlongbuffer[desty][destx]); switch (DrawMode) { case 0: finalr = srcr; finalg = srcg; finalb = srcb; break; case 1: finalr = ChannelBlend_Lighten(srcr,destr); finalg = ChannelBlend_Lighten(srcg,destg); finalb = ChannelBlend_Lighten(srcb,destb); break; case 2: finalr = ChannelBlend_Darken(srcr,destr); finalg = ChannelBlend_Darken(srcg,destg); finalb = ChannelBlend_Darken(srcb,destb); break; case 3: finalr = ChannelBlend_Multiply(srcr,destr); finalg = ChannelBlend_Multiply(srcg,destg); finalb = ChannelBlend_Multiply(srcb,destb); break; case 4: finalr = ChannelBlend_Add(srcr,destr); finalg = ChannelBlend_Add(srcg,destg); finalb = ChannelBlend_Add(srcb,destb); break; case 5: finalr = ChannelBlend_Subtract(srcr,destr); finalg = ChannelBlend_Subtract(srcg,destg); finalb = ChannelBlend_Subtract(srcb,destb); break; case 6: finalr = ChannelBlend_Difference(srcr,destr); finalg = ChannelBlend_Difference(srcg,destg); finalb = ChannelBlend_Difference(srcb,destb); break; case 7: finalr = ChannelBlend_Negation(srcr,destr); finalg = ChannelBlend_Negation(srcg,destg); finalb = ChannelBlend_Negation(srcb,destb); break; case 8: finalr = ChannelBlend_Screen(srcr,destr); finalg = ChannelBlend_Screen(srcg,destg); finalb = ChannelBlend_Screen(srcb,destb); break; case 9: finalr = ChannelBlend_Exclusion(srcr,destr); finalg = ChannelBlend_Exclusion(srcg,destg); finalb = ChannelBlend_Exclusion(srcb,destb); break; case 10: finalr = ChannelBlend_Overlay(srcr,destr); finalg = ChannelBlend_Overlay(srcg,destg); finalb = ChannelBlend_Overlay(srcb,destb); break; case 11: finalr = ChannelBlend_SoftLight(srcr,destr); finalg = ChannelBlend_SoftLight(srcg,destg); finalb = ChannelBlend_SoftLight(srcb,destb); break; case 12: finalr = ChannelBlend_HardLight(srcr,destr); finalg = ChannelBlend_HardLight(srcg,destg); finalb = ChannelBlend_HardLight(srcb,destb); break; case 13: finalr = ChannelBlend_ColorDodge(srcr,destr); finalg = ChannelBlend_ColorDodge(srcg,destg); finalb = ChannelBlend_ColorDodge(srcb,destb); break; case 14: finalr = ChannelBlend_ColorBurn(srcr,destr); finalg = ChannelBlend_ColorBurn(srcg,destg); finalb = ChannelBlend_ColorBurn(srcb,destb); break; case 15: finalr = ChannelBlend_LinearDodge(srcr,destr); finalg = ChannelBlend_LinearDodge(srcg,destg); finalb = ChannelBlend_LinearDodge(srcb,destb); break; case 16: finalr = ChannelBlend_LinearBurn(srcr,destr); finalg = ChannelBlend_LinearBurn(srcg,destg); finalb = ChannelBlend_LinearBurn(srcb,destb); break; case 17: finalr = ChannelBlend_LinearLight(srcr,destr); finalg = ChannelBlend_LinearLight(srcg,destg); finalb = ChannelBlend_LinearLight(srcb,destb); break; case 18: finalr = ChannelBlend_VividLight(srcr,destr); finalg = ChannelBlend_VividLight(srcg,destg); finalb = ChannelBlend_VividLight(srcb,destb); break; case 19: finalr = ChannelBlend_PinLight(srcr,destr); finalg = ChannelBlend_PinLight(srcg,destg); finalb = ChannelBlend_PinLight(srcb,destb); break; case 20: finalr = ChannelBlend_HardMix(srcr,destr); finalg = ChannelBlend_HardMix(srcg,destg); finalb = ChannelBlend_HardMix(srcb,destb); break; case 21: finalr = ChannelBlend_Reflect(srcr,destr); finalg = ChannelBlend_Reflect(srcg,destg); finalb = ChannelBlend_Reflect(srcb,destb); break; case 22: finalr = ChannelBlend_Glow(srcr,destr); finalg = ChannelBlend_Glow(srcg,destg); finalb = ChannelBlend_Glow(srcb,destb); break; case 23: finalr = ChannelBlend_Phoenix(srcr,destr); finalg = ChannelBlend_Phoenix(srcg,destg); finalb = ChannelBlend_Phoenix(srcb,destb); break; } finala = 255-(255-srca)*(255-desta)/255; finalr = srca*finalr/finala + desta*destr*(255-srca)/finala/255; finalg = srca*finalg/finala + desta*destg*(255-srca)/finala/255; finalb = srca*finalb/finala + desta*destb*(255-srca)/finala/255; col = makeacol32(finalr, finalg, finalb, finala); destlongbuffer[desty][destx] = col; } } } engine->ReleaseBitmapSurface(src); engine->ReleaseBitmapSurface(dest); engine->NotifySpriteUpdated(destination); return 0; } int DrawAdd(int destination, int sprite, int x, int y, float scale){ long srcWidth, srcHeight, destWidth, destHeight; BITMAP* src = engine->GetSpriteGraphic(sprite); BITMAP* dest = engine->GetSpriteGraphic(destination); engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, NULL); engine->GetBitmapDimensions(dest, &destWidth, &destHeight, NULL); if (x > destWidth || y > destHeight) return 1; // offscreen unsigned char **srccharbuffer = engine->GetRawBitmapSurface (src); unsigned int **srclongbuffer = (unsigned int**)srccharbuffer; unsigned char **destcharbuffer = engine->GetRawBitmapSurface (dest); unsigned int **destlongbuffer = (unsigned int**)destcharbuffer; if (srcWidth + x > destWidth) srcWidth = destWidth - x - 1; if (srcHeight + y > destHeight) srcHeight = destHeight - y - 1; int destx, desty; int srcr, srcg, srcb, srca, destr, destg, destb, desta, finalr, finalg, finalb, finala; unsigned int col; int ycount = 0; int xcount = 0; int starty = 0; int startx = 0; if (x < 0) startx = -1 * x; if (y < 0) starty = -1 * y; for(ycount = starty; ycount<srcHeight; ycount ++){ for(xcount = startx; xcount<srcWidth; xcount ++){ destx = xcount + x; desty = ycount + y; srca = (geta32(srclongbuffer[ycount][xcount])); if (srca != 0) { srcr = getr32(srclongbuffer[ycount][xcount]) * srca / 255 * scale; srcg = getg32(srclongbuffer[ycount][xcount]) * srca / 255 * scale; srcb = getb32(srclongbuffer[ycount][xcount]) * srca / 255 * scale; desta = geta32(destlongbuffer[desty][destx]); if (desta == 0){ destr = 0; destg = 0; destb = 0; } else { destr = getr32(destlongbuffer[desty][destx]); destg = getg32(destlongbuffer[desty][destx]); destb = getb32(destlongbuffer[desty][destx]); } finala = 255-(255-srca)*(255-desta)/255; finalr = Clamp(srcr + destr, 0, 255); finalg = Clamp(srcg + destg, 0, 255); finalb = Clamp(srcb + destb, 0, 255); col = makeacol32(finalr, finalg, finalb, finala); destlongbuffer[desty][destx] = col; } } } engine->ReleaseBitmapSurface(src); engine->ReleaseBitmapSurface(dest); engine->NotifySpriteUpdated(destination); return 0; } int DrawAlpha(int destination, int sprite, int x, int y, int trans) { trans = 100 - trans; long srcWidth, srcHeight, destWidth, destHeight; BITMAP* src = engine->GetSpriteGraphic(sprite); BITMAP* dest = engine->GetSpriteGraphic(destination); engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, NULL); engine->GetBitmapDimensions(dest, &destWidth, &destHeight, NULL); if (x > destWidth || y > destHeight) return 1; // offscreen unsigned char **srccharbuffer = engine->GetRawBitmapSurface (src); unsigned int **srclongbuffer = (unsigned int**)srccharbuffer; unsigned char **destcharbuffer = engine->GetRawBitmapSurface (dest); unsigned int **destlongbuffer = (unsigned int**)destcharbuffer; if (srcWidth + x > destWidth) srcWidth = destWidth - x - 1; if (srcHeight + y > destHeight) srcHeight = destHeight - y - 1; int destx, desty; int srcr, srcg, srcb, srca, destr, destg, destb, desta, finalr, finalg, finalb, finala; int ycount = 0; int xcount = 0; int starty = 0; int startx = 0; if (x < 0) startx = -1 * x; if (y < 0) starty = -1 * y; for(ycount = starty; ycount<srcHeight; ycount ++){ for(xcount = startx; xcount<srcWidth; xcount ++){ destx = xcount + x; desty = ycount + y; srca = (geta32(srclongbuffer[ycount][xcount])) * trans / 100; if (srca != 0) { srcr = getr32(srclongbuffer[ycount][xcount]); srcg = getg32(srclongbuffer[ycount][xcount]); srcb = getb32(srclongbuffer[ycount][xcount]); destr = getr32(destlongbuffer[desty][destx]); destg = getg32(destlongbuffer[desty][destx]); destb = getb32(destlongbuffer[desty][destx]); desta = geta32(destlongbuffer[desty][destx]); finala = 255-(255-srca)*(255-desta)/255; finalr = srca*srcr/finala + desta*destr*(255-srca)/finala/255; finalg = srca*srcg/finala + desta*destg*(255-srca)/finala/255; finalb = srca*srcb/finala + desta*destb*(255-srca)/finala/255; destlongbuffer[desty][destx] = makeacol32(finalr, finalg, finalb, finala); } } } engine->ReleaseBitmapSurface(src); engine->ReleaseBitmapSurface(dest); engine->NotifySpriteUpdated(destination); return 0; } #if defined(WINDOWS_VERSION) //============================================================================== // ***** Design time ***** IAGSEditor *editor; // Editor interface const char *ourScriptHeader = "import int DrawAlpha(int destination, int sprite, int x, int y, int transparency);\r\n" "import int GetAlpha(int sprite, int x, int y);\r\n" "import int PutAlpha(int sprite, int x, int y, int alpha);\r\n" "import int Blur(int sprite, int radius);\r\n" "import int HighPass(int sprite, int threshold);\r\n" "import int DrawAdd(int destination, int sprite, int x, int y, float scale);\r\n" "import int DrawSprite(int destination, int sprite, int x, int y, int DrawMode, int trans);"; //------------------------------------------------------------------------------ LPCSTR AGS_GetPluginName() { return ("AGSBlend"); } //------------------------------------------------------------------------------ int AGS_EditorStartup(IAGSEditor *lpEditor) { // User has checked the plugin to use it in their game // If it's an earlier version than what we need, abort. if (lpEditor->version < MIN_EDITOR_VERSION) return (-1); editor = lpEditor; editor->RegisterScriptHeader(ourScriptHeader); // Return 0 to indicate success return (0); } //------------------------------------------------------------------------------ void AGS_EditorShutdown() { // User has un-checked the plugin from their game editor->UnregisterScriptHeader(ourScriptHeader); } //------------------------------------------------------------------------------ void AGS_EditorProperties(HWND parent) //*** optional *** { // User has chosen to view the Properties of the plugin // We could load up an options dialog or something here instead /* MessageBox(parent, L"AGSBlend v1.0 By Calin Leafshade", L"About", MB_OK | MB_ICONINFORMATION); */ } //------------------------------------------------------------------------------ int AGS_EditorSaveGame(char *buffer, int bufsize) //*** optional *** { // Called by the editor when the current game is saved to disk. // Plugin configuration can be stored in [buffer] (max [bufsize] bytes) // Return the amount of bytes written in the buffer return (0); } //------------------------------------------------------------------------------ void AGS_EditorLoadGame(char *buffer, int bufsize) //*** optional *** { // Called by the editor when a game is loaded from disk // Previous written data can be read from [buffer] (size [bufsize]). // Make a copy of the data, the buffer is freed after this function call. } //============================================================================== #endif // ***** Run time ***** // Engine interface //------------------------------------------------------------------------------ #define REGISTER(x) engine->RegisterScriptFunction(#x, (void *) (x)); #define STRINGIFY(s) STRINGIFY_X(s) #define STRINGIFY_X(s) #s void AGS_EngineStartup(IAGSEngine *lpEngine) { engine = lpEngine; // Make sure it's got the version with the features we need if (engine->version < MIN_ENGINE_VERSION) engine->AbortGame("Plugin needs engine version " STRINGIFY(MIN_ENGINE_VERSION) " or newer."); //register functions REGISTER(GetAlpha) REGISTER(PutAlpha) REGISTER(DrawAlpha) REGISTER(Blur) REGISTER(HighPass) REGISTER(DrawAdd) REGISTER(DrawSprite) } //------------------------------------------------------------------------------ void AGS_EngineShutdown() { // Called by the game engine just before it exits. // This gives you a chance to free any memory and do any cleanup // that you need to do before the engine shuts down. } //------------------------------------------------------------------------------ int AGS_EngineOnEvent(int event, int data) //*** optional *** { switch (event) { /* case AGSE_KEYPRESS: case AGSE_MOUSECLICK: case AGSE_POSTSCREENDRAW: case AGSE_PRESCREENDRAW: case AGSE_SAVEGAME: case AGSE_RESTOREGAME: case AGSE_PREGUIDRAW: case AGSE_LEAVEROOM: case AGSE_ENTERROOM: case AGSE_TRANSITIONIN: case AGSE_TRANSITIONOUT: case AGSE_FINALSCREENDRAW: case AGSE_TRANSLATETEXT: case AGSE_SCRIPTDEBUG: case AGSE_SPRITELOAD: case AGSE_PRERENDER: case AGSE_PRESAVEGAME: case AGSE_POSTRESTOREGAME: */ default: break; } // Return 1 to stop event from processing further (when needed) return (0); } //------------------------------------------------------------------------------ int AGS_EngineDebugHook(const char *scriptName, int lineNum, int reserved) //*** optional *** { // Can be used to debug scripts, see documentation return 0; } //------------------------------------------------------------------------------ void AGS_EngineInitGfx(const char *driverID, void *data) //*** optional *** { // This allows you to make changes to how the graphics driver starts up. // See documentation } //.............................................................................. #if defined(BUILTIN_PLUGINS) } #endif
35.288008
277
0.478245
rofl0r
c08409bca82ab6e9e3a44aa0af13ccc1e59356f1
1,468
cpp
C++
library/Components/Objects/Rulebase/src/Timebased_rules.cpp
NGliese/Embedded
589f55858b1f8b994347df3c0a2b2fcd4f9bd14e
[ "MIT" ]
null
null
null
library/Components/Objects/Rulebase/src/Timebased_rules.cpp
NGliese/Embedded
589f55858b1f8b994347df3c0a2b2fcd4f9bd14e
[ "MIT" ]
null
null
null
library/Components/Objects/Rulebase/src/Timebased_rules.cpp
NGliese/Embedded
589f55858b1f8b994347df3c0a2b2fcd4f9bd14e
[ "MIT" ]
null
null
null
/* * Timebased_rules.cpp * * Created on: Nov 16, 2021 * Author: nikolaj */ /***********************************************************************************************+ * \brief -- XX -- Library - CPP Source file * \par * \par @DETAILS * * * \li LIMITATION-TO-CLASS * \li LIMITATION-TO-CLASS * * \note ANY RELEVANT NOTES * * \file Timebased_rules.cpp * \author N.G Pedersen <nikolajgliese@tutanota.com> * \version 1.0 * \date 2021 * \copyright -- * * ***********************************************************************************************/ #include "../include/Timebased_rules.hpp" //#define DEBUG // default uncommeted #ifdef DEBUG static const char* LOG_TAG = "Timebased_rules"; #endif constexpr int NIGHT_TIME_START = 20; constexpr int NIGHT_TIME_END = 5; constexpr int VACATION_START = 4; constexpr int VACATION_END = 12; bool Timebased_rules::isItNight(void) { time_t now = time(0); struct tm tstruct; tstruct = *localtime(&now); if(tstruct.tm_hour >= NIGHT_TIME_START or tstruct.tm_hour <= NIGHT_TIME_END) { return true; } return false; } bool Timebased_rules::isItVacation(void) { time_t now = time(0); struct tm tstruct; tstruct = *localtime(&now); std::cout << " current day is : " << (int)tstruct.tm_mday << "\n"; if(tstruct.tm_mday >= VACATION_START and tstruct.tm_mday <= VACATION_END) { return true; } return false; }
21.275362
97
0.558583
NGliese
c0848274b608b3d75d61032d9eb6f302746143d7
1,576
hpp
C++
include/tensor_ops.hpp
jaistark/sp
911933c65f950e6bc51451840068ca9249554846
[ "BSD-2-Clause" ]
28
2015-03-04T08:34:40.000Z
2022-02-13T05:59:11.000Z
include/tensor_ops.hpp
jaistark/sp
911933c65f950e6bc51451840068ca9249554846
[ "BSD-2-Clause" ]
null
null
null
include/tensor_ops.hpp
jaistark/sp
911933c65f950e6bc51451840068ca9249554846
[ "BSD-2-Clause" ]
14
2015-03-04T08:34:42.000Z
2020-12-08T16:13:37.000Z
#ifndef _TENSOR_OPS_HPP_ #define _TENSOR_OPS_HPP_ #include "common.hpp" #include "network.hpp" #include "vector.hpp" #include <vector> // Routine to compute the second left eigenvector of the Markov Chain // induced by the stationary distribution. // // triples is the list of third order moments (must be symmetric) // counts is a counter such that counts[(u, v)] is the number of // third-order moments containing u and v // stationary_distrib is the multilinear PageRank vector // alpha is the teleportation parameter // max_iter is the maximum number of power iterations to run // tol is the relative error tolerance for stopping template <typename Scalar> Vector<Scalar> SecondLeftEvec(std::vector<Tuple>& triples, Counts& counts, Vector<Scalar>& stationary_distrib, Scalar alpha, int max_iter, double tol); // Find the multilinear PageRank vector. // We use the SS-HOPM by Kolda and Mayo to compute the vector. // // triples is the list of third order moments (must be symmetric) // counts is a counter such that counts[(u, v)] is the number of // third-order moments containing u and v // alpha is the teleportation parameter // gamma is the shift parameter for SS-HOPM // num_nodes is the number of nodes // max_iter is the maximum number of SS-HOPM iterations // tol is the relative error tolerance for stopping template <typename Scalar> Vector<Scalar> MPRVec(std::vector<Tuple>& triples, Counts& counts, Scalar alpha, Scalar gamma, int num_nodes, int max_iter, double tol); #endif // _TENSOR_OPS_HPP_
35.818182
74
0.738579
jaistark
c086fdd2f452273a9175890573d7378113667e7e
10,548
cpp
C++
deepracer_follow_the_leader_ws/build/deepracer_interfaces_pkg/rosidl_typesupport_c/deepracer_interfaces_pkg/srv/software_update_state_srv__type_support.cpp
amitjain-3/working_add
ddd3b10d854477e86bf7a8558b3d447ec03a8a5f
[ "Apache-2.0" ]
1
2022-03-11T20:15:27.000Z
2022-03-11T20:15:27.000Z
deepracer_follow_the_leader_ws/build/deepracer_interfaces_pkg/rosidl_typesupport_c/deepracer_interfaces_pkg/srv/software_update_state_srv__type_support.cpp
amitjain-3/working_add
ddd3b10d854477e86bf7a8558b3d447ec03a8a5f
[ "Apache-2.0" ]
null
null
null
deepracer_follow_the_leader_ws/build/deepracer_interfaces_pkg/rosidl_typesupport_c/deepracer_interfaces_pkg/srv/software_update_state_srv__type_support.cpp
amitjain-3/working_add
ddd3b10d854477e86bf7a8558b3d447ec03a8a5f
[ "Apache-2.0" ]
null
null
null
// generated from rosidl_typesupport_c/resource/idl__type_support.cpp.em // with input from deepracer_interfaces_pkg:srv/SoftwareUpdateStateSrv.idl // generated code does not contain a copyright notice #include "cstddef" #include "rosidl_runtime_c/message_type_support_struct.h" #include "deepracer_interfaces_pkg/msg/rosidl_typesupport_c__visibility_control.h" #include "deepracer_interfaces_pkg/srv/detail/software_update_state_srv__struct.h" #include "rosidl_typesupport_c/identifier.h" #include "rosidl_typesupport_c/message_type_support_dispatch.h" #include "rosidl_typesupport_c/type_support_map.h" #include "rosidl_typesupport_c/visibility_control.h" #include "rosidl_typesupport_interface/macros.h" namespace deepracer_interfaces_pkg { namespace srv { namespace rosidl_typesupport_c { typedef struct _SoftwareUpdateStateSrv_Request_type_support_ids_t { const char * typesupport_identifier[2]; } _SoftwareUpdateStateSrv_Request_type_support_ids_t; static const _SoftwareUpdateStateSrv_Request_type_support_ids_t _SoftwareUpdateStateSrv_Request_message_typesupport_ids = { { "rosidl_typesupport_fastrtps_c", // ::rosidl_typesupport_fastrtps_c::typesupport_identifier, "rosidl_typesupport_introspection_c", // ::rosidl_typesupport_introspection_c::typesupport_identifier, } }; typedef struct _SoftwareUpdateStateSrv_Request_type_support_symbol_names_t { const char * symbol_name[2]; } _SoftwareUpdateStateSrv_Request_type_support_symbol_names_t; #define STRINGIFY_(s) #s #define STRINGIFY(s) STRINGIFY_(s) static const _SoftwareUpdateStateSrv_Request_type_support_symbol_names_t _SoftwareUpdateStateSrv_Request_message_typesupport_symbol_names = { { STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_fastrtps_c, deepracer_interfaces_pkg, srv, SoftwareUpdateStateSrv_Request)), STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_introspection_c, deepracer_interfaces_pkg, srv, SoftwareUpdateStateSrv_Request)), } }; typedef struct _SoftwareUpdateStateSrv_Request_type_support_data_t { void * data[2]; } _SoftwareUpdateStateSrv_Request_type_support_data_t; static _SoftwareUpdateStateSrv_Request_type_support_data_t _SoftwareUpdateStateSrv_Request_message_typesupport_data = { { 0, // will store the shared library later 0, // will store the shared library later } }; static const type_support_map_t _SoftwareUpdateStateSrv_Request_message_typesupport_map = { 2, "deepracer_interfaces_pkg", &_SoftwareUpdateStateSrv_Request_message_typesupport_ids.typesupport_identifier[0], &_SoftwareUpdateStateSrv_Request_message_typesupport_symbol_names.symbol_name[0], &_SoftwareUpdateStateSrv_Request_message_typesupport_data.data[0], }; static const rosidl_message_type_support_t SoftwareUpdateStateSrv_Request_message_type_support_handle = { rosidl_typesupport_c__typesupport_identifier, reinterpret_cast<const type_support_map_t *>(&_SoftwareUpdateStateSrv_Request_message_typesupport_map), rosidl_typesupport_c__get_message_typesupport_handle_function, }; } // namespace rosidl_typesupport_c } // namespace srv } // namespace deepracer_interfaces_pkg #ifdef __cplusplus extern "C" { #endif ROSIDL_TYPESUPPORT_C_EXPORT_deepracer_interfaces_pkg const rosidl_message_type_support_t * ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_c, deepracer_interfaces_pkg, srv, SoftwareUpdateStateSrv_Request)() { return &::deepracer_interfaces_pkg::srv::rosidl_typesupport_c::SoftwareUpdateStateSrv_Request_message_type_support_handle; } #ifdef __cplusplus } #endif // already included above // #include "cstddef" // already included above // #include "rosidl_runtime_c/message_type_support_struct.h" // already included above // #include "deepracer_interfaces_pkg/msg/rosidl_typesupport_c__visibility_control.h" // already included above // #include "deepracer_interfaces_pkg/srv/detail/software_update_state_srv__struct.h" // already included above // #include "rosidl_typesupport_c/identifier.h" // already included above // #include "rosidl_typesupport_c/message_type_support_dispatch.h" // already included above // #include "rosidl_typesupport_c/type_support_map.h" // already included above // #include "rosidl_typesupport_c/visibility_control.h" // already included above // #include "rosidl_typesupport_interface/macros.h" namespace deepracer_interfaces_pkg { namespace srv { namespace rosidl_typesupport_c { typedef struct _SoftwareUpdateStateSrv_Response_type_support_ids_t { const char * typesupport_identifier[2]; } _SoftwareUpdateStateSrv_Response_type_support_ids_t; static const _SoftwareUpdateStateSrv_Response_type_support_ids_t _SoftwareUpdateStateSrv_Response_message_typesupport_ids = { { "rosidl_typesupport_fastrtps_c", // ::rosidl_typesupport_fastrtps_c::typesupport_identifier, "rosidl_typesupport_introspection_c", // ::rosidl_typesupport_introspection_c::typesupport_identifier, } }; typedef struct _SoftwareUpdateStateSrv_Response_type_support_symbol_names_t { const char * symbol_name[2]; } _SoftwareUpdateStateSrv_Response_type_support_symbol_names_t; #define STRINGIFY_(s) #s #define STRINGIFY(s) STRINGIFY_(s) static const _SoftwareUpdateStateSrv_Response_type_support_symbol_names_t _SoftwareUpdateStateSrv_Response_message_typesupport_symbol_names = { { STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_fastrtps_c, deepracer_interfaces_pkg, srv, SoftwareUpdateStateSrv_Response)), STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_introspection_c, deepracer_interfaces_pkg, srv, SoftwareUpdateStateSrv_Response)), } }; typedef struct _SoftwareUpdateStateSrv_Response_type_support_data_t { void * data[2]; } _SoftwareUpdateStateSrv_Response_type_support_data_t; static _SoftwareUpdateStateSrv_Response_type_support_data_t _SoftwareUpdateStateSrv_Response_message_typesupport_data = { { 0, // will store the shared library later 0, // will store the shared library later } }; static const type_support_map_t _SoftwareUpdateStateSrv_Response_message_typesupport_map = { 2, "deepracer_interfaces_pkg", &_SoftwareUpdateStateSrv_Response_message_typesupport_ids.typesupport_identifier[0], &_SoftwareUpdateStateSrv_Response_message_typesupport_symbol_names.symbol_name[0], &_SoftwareUpdateStateSrv_Response_message_typesupport_data.data[0], }; static const rosidl_message_type_support_t SoftwareUpdateStateSrv_Response_message_type_support_handle = { rosidl_typesupport_c__typesupport_identifier, reinterpret_cast<const type_support_map_t *>(&_SoftwareUpdateStateSrv_Response_message_typesupport_map), rosidl_typesupport_c__get_message_typesupport_handle_function, }; } // namespace rosidl_typesupport_c } // namespace srv } // namespace deepracer_interfaces_pkg #ifdef __cplusplus extern "C" { #endif ROSIDL_TYPESUPPORT_C_EXPORT_deepracer_interfaces_pkg const rosidl_message_type_support_t * ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_c, deepracer_interfaces_pkg, srv, SoftwareUpdateStateSrv_Response)() { return &::deepracer_interfaces_pkg::srv::rosidl_typesupport_c::SoftwareUpdateStateSrv_Response_message_type_support_handle; } #ifdef __cplusplus } #endif // already included above // #include "cstddef" #include "rosidl_runtime_c/service_type_support_struct.h" // already included above // #include "deepracer_interfaces_pkg/msg/rosidl_typesupport_c__visibility_control.h" // already included above // #include "rosidl_typesupport_c/identifier.h" #include "rosidl_typesupport_c/service_type_support_dispatch.h" // already included above // #include "rosidl_typesupport_c/type_support_map.h" // already included above // #include "rosidl_typesupport_interface/macros.h" namespace deepracer_interfaces_pkg { namespace srv { namespace rosidl_typesupport_c { typedef struct _SoftwareUpdateStateSrv_type_support_ids_t { const char * typesupport_identifier[2]; } _SoftwareUpdateStateSrv_type_support_ids_t; static const _SoftwareUpdateStateSrv_type_support_ids_t _SoftwareUpdateStateSrv_service_typesupport_ids = { { "rosidl_typesupport_fastrtps_c", // ::rosidl_typesupport_fastrtps_c::typesupport_identifier, "rosidl_typesupport_introspection_c", // ::rosidl_typesupport_introspection_c::typesupport_identifier, } }; typedef struct _SoftwareUpdateStateSrv_type_support_symbol_names_t { const char * symbol_name[2]; } _SoftwareUpdateStateSrv_type_support_symbol_names_t; #define STRINGIFY_(s) #s #define STRINGIFY(s) STRINGIFY_(s) static const _SoftwareUpdateStateSrv_type_support_symbol_names_t _SoftwareUpdateStateSrv_service_typesupport_symbol_names = { { STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME(rosidl_typesupport_fastrtps_c, deepracer_interfaces_pkg, srv, SoftwareUpdateStateSrv)), STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME(rosidl_typesupport_introspection_c, deepracer_interfaces_pkg, srv, SoftwareUpdateStateSrv)), } }; typedef struct _SoftwareUpdateStateSrv_type_support_data_t { void * data[2]; } _SoftwareUpdateStateSrv_type_support_data_t; static _SoftwareUpdateStateSrv_type_support_data_t _SoftwareUpdateStateSrv_service_typesupport_data = { { 0, // will store the shared library later 0, // will store the shared library later } }; static const type_support_map_t _SoftwareUpdateStateSrv_service_typesupport_map = { 2, "deepracer_interfaces_pkg", &_SoftwareUpdateStateSrv_service_typesupport_ids.typesupport_identifier[0], &_SoftwareUpdateStateSrv_service_typesupport_symbol_names.symbol_name[0], &_SoftwareUpdateStateSrv_service_typesupport_data.data[0], }; static const rosidl_service_type_support_t SoftwareUpdateStateSrv_service_type_support_handle = { rosidl_typesupport_c__typesupport_identifier, reinterpret_cast<const type_support_map_t *>(&_SoftwareUpdateStateSrv_service_typesupport_map), rosidl_typesupport_c__get_service_typesupport_handle_function, }; } // namespace rosidl_typesupport_c } // namespace srv } // namespace deepracer_interfaces_pkg #ifdef __cplusplus extern "C" { #endif ROSIDL_TYPESUPPORT_C_EXPORT_deepracer_interfaces_pkg const rosidl_service_type_support_t * ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME(rosidl_typesupport_c, deepracer_interfaces_pkg, srv, SoftwareUpdateStateSrv)() { return &::deepracer_interfaces_pkg::srv::rosidl_typesupport_c::SoftwareUpdateStateSrv_service_type_support_handle; } #ifdef __cplusplus } #endif
35.755932
165
0.85182
amitjain-3
c087746d79d1ba215d0149ff16973f0ead0a5dcd
5,378
cpp
C++
src/rviz/default_plugin/grid_cells_display.cpp
fftn/rviz
a9de85555b040f625b0bac5d7c3eba3be9e8fa42
[ "BSD-3-Clause-Clear" ]
null
null
null
src/rviz/default_plugin/grid_cells_display.cpp
fftn/rviz
a9de85555b040f625b0bac5d7c3eba3be9e8fa42
[ "BSD-3-Clause-Clear" ]
null
null
null
src/rviz/default_plugin/grid_cells_display.cpp
fftn/rviz
a9de85555b040f625b0bac5d7c3eba3be9e8fa42
[ "BSD-3-Clause-Clear" ]
null
null
null
/* * Copyright (c) 2008, Willow Garage, 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 the Willow Garage, 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. */ #include <boost/bind/bind.hpp> #include <OgreSceneNode.h> #include <OgreSceneManager.h> #include <OgreManualObject.h> #include <OgreBillboardSet.h> #include <rviz/frame_manager.h> #include <rviz/ogre_helpers/arrow.h> #include <rviz/ogre_helpers/point_cloud.h> #include <rviz/properties/color_property.h> #include <rviz/properties/float_property.h> #include <rviz/properties/parse_color.h> #include <rviz/validate_floats.h> #include <rviz/display_context.h> #include "grid_cells_display.h" namespace rviz { GridCellsDisplay::GridCellsDisplay() : MFDClass(), last_frame_count_(uint64_t(-1)) { color_property_ = new ColorProperty("Color", QColor(25, 255, 0), "Color of the grid cells.", this); alpha_property_ = new FloatProperty("Alpha", 1.0, "Amount of transparency to apply to the cells.", this, SLOT(updateAlpha())); alpha_property_->setMin(0); alpha_property_->setMax(1); } void GridCellsDisplay::onInitialize() { static int count = 0; std::stringstream ss; ss << "PolyLine" << count++; cloud_ = new PointCloud(); cloud_->setRenderMode(PointCloud::RM_TILES); cloud_->setCommonDirection(Ogre::Vector3::UNIT_Z); cloud_->setCommonUpVector(Ogre::Vector3::UNIT_Y); scene_node_->attachObject(cloud_); updateAlpha(); MFDClass::onInitialize(); } GridCellsDisplay::~GridCellsDisplay() { if (initialized()) { unsubscribe(); GridCellsDisplay::reset(); scene_node_->detachObject(cloud_); delete cloud_; } } void GridCellsDisplay::reset() { MFDClass::reset(); cloud_->clear(); } void GridCellsDisplay::updateAlpha() { cloud_->setAlpha(alpha_property_->getFloat()); context_->queueRender(); } bool validateFloats(const nav_msgs::GridCells& msg) { bool valid = true; valid = valid && validateFloats(msg.cell_width); valid = valid && validateFloats(msg.cell_height); valid = valid && validateFloats(msg.cells); return valid; } void GridCellsDisplay::processMessage(const nav_msgs::GridCells::ConstPtr& msg) { if (context_->getFrameCount() == last_frame_count_) return; last_frame_count_ = context_->getFrameCount(); cloud_->clear(); if (!validateFloats(*msg)) { setStatus(StatusProperty::Error, "Topic", "Message contained invalid floating point values (nans or infs)"); return; } Ogre::Vector3 position; Ogre::Quaternion orientation; if (!context_->getFrameManager()->getTransform(msg->header, position, orientation)) { ROS_DEBUG("Error transforming from frame '%s' to frame '%s'", msg->header.frame_id.c_str(), qPrintable(fixed_frame_)); } scene_node_->setPosition(position); scene_node_->setOrientation(orientation); if (msg->cell_width == 0) { setStatus(StatusProperty::Error, "Topic", "Cell width is zero, cells will be invisible."); } else if (msg->cell_height == 0) { setStatus(StatusProperty::Error, "Topic", "Cell height is zero, cells will be invisible."); } cloud_->setDimensions(msg->cell_width, msg->cell_height, 0.0); Ogre::ColourValue color_int = qtToOgre(color_property_->getColor()); uint32_t num_points = msg->cells.size(); typedef std::vector<PointCloud::Point> V_Point; V_Point points; points.resize(num_points); for (uint32_t i = 0; i < num_points; i++) { PointCloud::Point& current_point = points[i]; current_point.position.x = msg->cells[i].x; current_point.position.y = msg->cells[i].y; current_point.position.z = msg->cells[i].z; current_point.color = color_int; } cloud_->clear(); if (!points.empty()) { cloud_->addPoints(&points.front(), points.size()); } } } // namespace rviz #include <pluginlib/class_list_macros.hpp> PLUGINLIB_EXPORT_CLASS(rviz::GridCellsDisplay, rviz::Display)
31.450292
101
0.716623
fftn
c08eae1e1417ad9aae1fbf98d5d1fa66f71a47eb
2,862
cpp
C++
src/core/Game.cpp
tbsd/yet_another_roguelike
ed276351533f2be05f7cc04c03c215d841af5097
[ "MIT" ]
null
null
null
src/core/Game.cpp
tbsd/yet_another_roguelike
ed276351533f2be05f7cc04c03c215d841af5097
[ "MIT" ]
null
null
null
src/core/Game.cpp
tbsd/yet_another_roguelike
ed276351533f2be05f7cc04c03c215d841af5097
[ "MIT" ]
null
null
null
#include "Game.h" #include "Log.h" #include <mutex> #include <future> #include <chrono> #include "UserAction.h" #include "../component/Health.h" namespace tbsd { void Game::processAction(const Action& action) { switch (action.getType()) { case Action::Type::Connected: users.emplace_back(std::any_cast<CppServer::WS::WSSession*>(action.data.back())); { entityx::Entity playableChar = entities.create(); playableChar.assign<Position>(0, 0, 0); playableChar.assign<Health>(100); users.back().owned.push_back(playableChar); } break; case Action::Type::Disconnected: auto session = std::any_cast<CppServer::WS::WSSession*>(action.data.back()); users.erase( std::remove_if(users.begin(), users.end(), [&](User& u) {return u.session == session;}), users.end()); break; } } void Game::processCommand(ServerCommand command) { switch (command) { case Empty: break; case Invalid: default: Log::send("Invalid command", Log::Warning); } } void Game::mainLoop(std::function<void(void)> newActionsHandler) { std::string consoleInput; std::future<std::string> console = std::async([&]{return IO::getFromConsole();}); // Main game loop while (true) { // Process data from console if (console.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { consoleInput = console.get(); ServerCommand command = IO::parseCommand(consoleInput); if (command == Shutdown) return; else processCommand(command); console = std::async([&]{return IO::getFromConsole();}); } // Process data from server static std::mutex m; m.lock(); if (server.hasUserActions()) { auto action = server.getUserAction(); try { Action newAction(action->data); // TODO: thing of a better way of adding pointers // and not adding session where there no need for that newAction.data.emplace_back(action->session); actions.push(newAction); } catch (std::exception &ex) { Log::send(ex.what(), Log::Error); } m.unlock(); Log::send(action->data, Log::Received); server.send(*action); // echo } else m.unlock(); // processActions(); newActionsHandler(); } } void Game::decreaseTime(Unit amount) { // TODO: replace with a better solution. Create priority queue with random access? std::priority_queue<Action, std::vector<Action>, Action::Greater> decreased; while (!actions.empty()) { auto action = actions.top(); actions.pop(); action.time -= amount; decreased.push(action); } actions = decreased; } }
31.108696
100
0.592942
tbsd
6a4eff4c2b2c6aaf37fc5298c798321f5765d2c2
703
cpp
C++
src/utility/settings/BoundarySetting.cpp
Ozaq/ARTSS
32fc99623bf06db3ceb89fe20504867ccf28959d
[ "MIT" ]
null
null
null
src/utility/settings/BoundarySetting.cpp
Ozaq/ARTSS
32fc99623bf06db3ceb89fe20504867ccf28959d
[ "MIT" ]
null
null
null
src/utility/settings/BoundarySetting.cpp
Ozaq/ARTSS
32fc99623bf06db3ceb89fe20504867ccf28959d
[ "MIT" ]
null
null
null
/// \file BoundarySetting.cpp /// \brief Model of Boundaries in the XML /// \date Dec 01, 2021 /// \author von Mach /// \copyright <2015-2021> Forschungszentrum Juelich GmbH. All rights reserved. #include "BoundarySetting.h" namespace Settings { BoundarySetting::BoundarySetting(tinyxml2::XMLElement *xml_element) : field(xml_element->Attribute("field")), patch(xml_element->Attribute("patch")), type(xml_element->Attribute("type")), value(std::atof(xml_element->Attribute("value"))) { } #ifndef BENCHMARKING void BoundarySetting::print(spdlog::logger logger) const { logger.debug("field={} patch={} type={} value={}", field, patch, type, value); } #endif }
30.565217
82
0.687055
Ozaq
6a51653fdedf9b0120d0cba5bb13202186eec594
333
cpp
C++
dialogs/dialog-about.cpp
Intueor/PPK
afd1ddcb6214352b87097b58de0b9555a8a3f1b2
[ "Apache-2.0" ]
null
null
null
dialogs/dialog-about.cpp
Intueor/PPK
afd1ddcb6214352b87097b58de0b9555a8a3f1b2
[ "Apache-2.0" ]
null
null
null
dialogs/dialog-about.cpp
Intueor/PPK
afd1ddcb6214352b87097b58de0b9555a8a3f1b2
[ "Apache-2.0" ]
null
null
null
//== ВКЛЮЧЕНИЯ. #include "dialog-about.h" #include "ui_dialog-about.h" //== ФУНКЦИИ КЛАССОВ. //== Класс диалога "О программе". // Конструктор. DialogAbout::DialogAbout(QWidget *p_WidgetParent) : QDialog(p_WidgetParent), p_UI(new Ui::DialogAbout) { p_UI->setupUi(this); } // Деструктор. DialogAbout::~DialogAbout() { delete p_UI; }
27.75
127
0.714715
Intueor
6a55a46cc58954f0aa68d79792fa92fcbc3306ec
4,356
cxx
C++
src/qds/DispatchIO.cxx
XFone/exapi
05660e8b27dfa75aa0996342ee5b6b253b09c477
[ "Apache-2.0" ]
1
2020-04-11T06:06:40.000Z
2020-04-11T06:06:40.000Z
src/qds/DispatchIO.cxx
XFone/exapi
05660e8b27dfa75aa0996342ee5b6b253b09c477
[ "Apache-2.0" ]
null
null
null
src/qds/DispatchIO.cxx
XFone/exapi
05660e8b27dfa75aa0996342ee5b6b253b09c477
[ "Apache-2.0" ]
null
null
null
/* * $Id: $ * * System I/O dispatching implementation * * Copyright (c) 2014-2015 Zerone.IO (Shanghai). All rights reserved. * * $Log: $ * */ #include "Base.h" #include "Log.h" #include "Trace.h" #include "GlobalDefine.h" #include "DispatchIO.h" #include "algoapi/zmq/ZmqHelper.h" #include <string> using namespace std; using namespace ATS; #define USE_ZMQ_POLL 1 #define ZMQ_POLL_TIMEOUT 10 // 10ms DispatchIO::DispatchIO(void) : n_mq(0) { m_zmqctx = zmq_ctx_new(); zmq_ctx_set(m_zmqctx, ZMQ_MAX_SOCKETS, 128); } DispatchIO::~DispatchIO(void) { for (int i = 0; i < n_mq; i++) { delete a_mqs[i]; } zmq_ctx_term(m_zmqctx); // zmq_ctx_destroy(m_zmqctx); // deprecated } BaseZmqClient *DispatchIO::AssignSfHandler(SwordFishIntf *psf, BaseMsgDispatcher *dsp) { if (n_mq < (int)MAX_MQ_COUNT) { psf->SetContext(m_zmqctx); psf->SetUserParseFunc(dsp->GetMessageParser()); a_mqs[n_mq++] = new _MqDesc(psf, dsp, dsp); } return (BaseZmqClient *)psf; } BaseZmqClient *DispatchIO::AssignMqHandler(BaseZmqClient *pmq, IDispatcher *dsp) { if (n_mq < (int)MAX_MQ_COUNT) { pmq->SetContext(m_zmqctx); a_mqs[n_mq++] = new _MqDesc(pmq, dsp, NULL); } return pmq; } int DispatchIO::DispatchInfinitely(void *ctx, bool do_egress) { int i; #if USE_ZMQ_POLL int n_items = 0; zmq_pollitem_t poll_items[MAX_MQ_COUNT]; for (i = 0; i < n_mq && i < (int)MAX_MQ_COUNT; i++) { zmq_pollitem_t *pitem = &poll_items[i]; pitem->socket = a_mqs[i]->GetSocket(); pitem->fd = a_mqs[i]->GetFd(); pitem->events = ZMQ_POLLIN | ZMQ_POLLERR; pitem->revents = 0; n_items++; TRACE_THREAD(7, "poll_item { socket: 0x%x, fd: %d }", pitem->socket, pitem->fd); } LOGFILE(LOG_DEBUG, "ZMQ polling on %d items", n_items); #endif /* USE_ZMQ_POLL */ do { #if USE_ZMQ_POLL int rc = zmq_poll(poll_items, n_items, ZMQ_POLL_TIMEOUT); if (rc > 0) { // has events i = 0; TRACE_THREAD(8, "Got %d events", rc); while (i < n_items && rc > 0) { int revts = poll_items[i].revents; if (revts) { // this item got an event rc--; TRACE_THREAD(8, "ZMQ#%d polled!", i); if (revts & ZMQ_POLLIN) { onDispatch(a_mqs[i]); } if (revts & ZMQ_POLLERR) { LOGFILE(LOG_WARN, "socket %d has error", i); // TODO } } i++; } // while (i && rc) } else if (0 == rc) { // timeout // TODO --- // TRACE_THREAD(7, "timeout!"); } else { // -1 check errors int err = zmq_errno(); switch (err) { case EBADF: // fd or socket closed // TODO: reopen or re-initialize MQ LOGFILE(LOG_WARN, "zmq_poll got EBADF: %s", zmq_strerror(err)); break; case EINTR: // got SIGCHLD or SIGALRM // assert(0); LOGFILE(LOG_WARN, "got SIGCHLD or SIGALRM"); break; default: // what's up? LOGFILE(LOG_WARN, "zmq_poll got error: %s", zmq_strerror(err)); // assert(0); break; } } // if (rc) #else /* !USE_ZMQ_POLL */ for (i = 0; i < n_mq; i++) { onDispatch(&a_mqs[i]); } #endif /* USE_ZMQ_POLL */ if (do_egress) { ProcessEgress(); } } while (!g_is_exiting); return 0; } TDispResult DispatchIO::onDispatch(Object desc) { _MqDesc *mqd = (_MqDesc *)desc; TDispResult ret = DR_DROPPED; Object obj; if (NULL != (obj = mqd->doRecv())) { ret = mqd->doDispatch(obj); } else { TRACE_THREAD(7, "DispatchIO::onDispatch: unknown message"); } if (DR_SUCCESS != ret) { // TODO: to check status } if (DR_CONTINUE == ret) { // TODO: broadcast this message to all } return ret; }
24.066298
87
0.506198
XFone
6a58d45a9c342cf63c598464f6ba5fdcb4928274
3,494
cpp
C++
Unix/samples/Providers/Demo-i2/X_Halves_Class_Provider.cpp
Beguiled/omi
1c824681ee86f32314f430db972e5d3938f10fd4
[ "MIT" ]
165
2016-08-18T22:06:39.000Z
2019-05-05T11:09:37.000Z
Unix/samples/Providers/Demo-i2/X_Halves_Class_Provider.cpp
snchennapragada/omi
4fa565207d3445d1f44bfc7b890f9ea5ea7b41d0
[ "MIT" ]
409
2016-08-18T20:52:56.000Z
2019-05-06T10:03:11.000Z
Unix/samples/Providers/Demo-i2/X_Halves_Class_Provider.cpp
snchennapragada/omi
4fa565207d3445d1f44bfc7b890f9ea5ea7b41d0
[ "MIT" ]
72
2016-08-23T02:30:08.000Z
2019-04-30T22:57:03.000Z
/* **============================================================================== ** ** Copyright (c) Microsoft Corporation. All rights reserved. See file LICENSE ** for license information. ** **============================================================================== */ /* @migen@ */ #include <MI.h> #include "X_Halves_Class_Provider.h" MI_BEGIN_NAMESPACE X_SmallNumber_Class FillNumberByKey( Uint64 key); X_Halves_Class_Provider::X_Halves_Class_Provider( Module* module) : m_Module(module) { } X_Halves_Class_Provider::~X_Halves_Class_Provider() { } void X_Halves_Class_Provider::EnumerateInstances( Context& context, const String& nameSpace, const PropertySet& propertySet, bool keysOnly, const MI_Filter* filter) { context.Post(MI_RESULT_NOT_SUPPORTED); } void X_Halves_Class_Provider::GetInstance( Context& context, const String& nameSpace, const X_Halves_Class& instance_ref, const PropertySet& propertySet) { context.Post(MI_RESULT_NOT_SUPPORTED); } void X_Halves_Class_Provider::CreateInstance( Context& context, const String& nameSpace, const X_Halves_Class& new_instance) { context.Post(MI_RESULT_NOT_SUPPORTED); } void X_Halves_Class_Provider::ModifyInstance( Context& context, const String& nameSpace, const X_Halves_Class& new_instance, const PropertySet& propertySet) { context.Post(MI_RESULT_NOT_SUPPORTED); } void X_Halves_Class_Provider::DeleteInstance( Context& context, const String& nameSpace, const X_Halves_Class& instance_ref) { context.Post(MI_RESULT_NOT_SUPPORTED); } void X_Halves_Class_Provider::AssociatorInstances( Context& context, const String& nameSpace, const MI_Instance* instanceName, const String& resultClass, const String& role, const String& resultRole, const PropertySet& propertySet, bool keysOnly, const MI_Filter* filter) { if (!X_SmallNumber_IsA(instanceName)) { context.Post(MI_RESULT_FAILED); return ; } X_SmallNumber_Class number((const X_SmallNumber*)instanceName,true); if (!number.Number().exists) { // key is missing context.Post(MI_RESULT_FAILED); return ; } Uint64 num = number.Number().value; // check if we have smaller half if (num % 2 == 0 && (role.GetSize() == 0 || role == MI_T("number")) && // check role (resultRole.GetSize() == 0 || resultRole == MI_T("half")) // check result role ) { context.Post(FillNumberByKey(num / 2)); } // check if we have bigger half if (num * 2 < 10000 && (role.GetSize() == 0 || role == MI_T("half")) && // check role (resultRole.GetSize() == 0 || resultRole == MI_T("number")) // check result role ) { context.Post(FillNumberByKey(num * 2)); } context.Post(MI_RESULT_OK); } void X_Halves_Class_Provider::ReferenceInstances( Context& context, const String& nameSpace, const MI_Instance* instanceName, const String& role, const PropertySet& propertySet, bool keysOnly, const MI_Filter* filter) { context.Post(MI_RESULT_NOT_SUPPORTED); } MI_END_NAMESPACE MI_BEGIN_NAMESPACE void X_Halves_Class_Provider::Load( Context& context) { context.Post(MI_RESULT_OK); } void X_Halves_Class_Provider::Unload( Context& context) { context.Post(MI_RESULT_OK); } MI_END_NAMESPACE
23.449664
90
0.644533
Beguiled
6a5bc50b3d3d4a4110129e869e023df358f61a0a
3,545
hpp
C++
libcaf_core/caf/mixin/subscriber.hpp
mydatamodels/actor-framework
d8fe071c86137918dff57ea12fc7aa44e7f0190a
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
libcaf_core/caf/mixin/subscriber.hpp
mydatamodels/actor-framework
d8fe071c86137918dff57ea12fc7aa44e7f0190a
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
libcaf_core/caf/mixin/subscriber.hpp
mydatamodels/actor-framework
d8fe071c86137918dff57ea12fc7aa44e7f0190a
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <unordered_set> #include "caf/fwd.hpp" #include "caf/group.hpp" namespace caf::mixin { /// Marker for `subscriber`. struct subscriber_base {}; /// A `subscriber` is an actor that can subscribe /// to a `group` via `self->join(...)`. template <class Base, class Subtype> class subscriber : public Base, public subscriber_base { public: // -- member types ----------------------------------------------------------- /// Allows subtypes to refer mixed types with a simple name. using extended_base = subscriber; /// A container for storing subscribed groups. using subscriptions = std::unordered_set<group>; // -- constructors, destructors, and assignment operators -------------------- template <class... Ts> subscriber(actor_config& cfg, Ts&&... xs) : Base(cfg, std::forward<Ts>(xs)...) { if (cfg.groups != nullptr) for (auto& grp : *cfg.groups) join(grp); } // -- overridden functions of monitorable_actor ------------------------------ bool cleanup(error&& fail_state, execution_unit* ptr) override { auto me = this->ctrl(); for (auto& subscription : subscriptions_) subscription->unsubscribe(me); subscriptions_.clear(); return Base::cleanup(std::move(fail_state), ptr); } // -- group management ------------------------------------------------------- /// Causes this actor to subscribe to the group `what`. /// The group will be unsubscribed if the actor finishes execution. void join(const group& what) { CAF_LOG_TRACE(CAF_ARG(what)); if (what == invalid_group) return; if (what->subscribe(this->ctrl())) subscriptions_.emplace(what); } /// Causes this actor to leave the group `what`. void leave(const group& what) { CAF_LOG_TRACE(CAF_ARG(what)); if (subscriptions_.erase(what) > 0) what->unsubscribe(this->ctrl()); } /// Returns all subscribed groups. const subscriptions& joined_groups() const { return subscriptions_; } private: // -- data members ----------------------------------------------------------- /// Stores all subscribed groups. subscriptions subscriptions_; }; } // namespace caf
36.546392
80
0.472496
mydatamodels
6a5c9978d647b2abf2c1b08a4d22fca238db76dc
6,228
cpp
C++
src/dis6/LinearSegmentParameter.cpp
AlphaPixel/open-dis-cpp
90634cade32ac98e2108be8799bd2ec949c4337e
[ "BSD-2-Clause" ]
42
2017-02-22T07:23:06.000Z
2022-03-07T12:34:11.000Z
src/dis6/LinearSegmentParameter.cpp
AlphaPixel/open-dis-cpp
90634cade32ac98e2108be8799bd2ec949c4337e
[ "BSD-2-Clause" ]
62
2017-07-14T11:06:55.000Z
2022-01-22T02:32:45.000Z
src/dis6/LinearSegmentParameter.cpp
AlphaPixel/open-dis-cpp
90634cade32ac98e2108be8799bd2ec949c4337e
[ "BSD-2-Clause" ]
51
2017-08-10T16:44:32.000Z
2021-12-16T09:57:42.000Z
#include <dis6/LinearSegmentParameter.h> using namespace DIS; LinearSegmentParameter::LinearSegmentParameter(): _segmentNumber(0), _segmentAppearance(), _location(), _orientation(), _segmentLength(0), _segmentWidth(0), _segmentHeight(0), _segmentDepth(0), _pad1(0) { } LinearSegmentParameter::~LinearSegmentParameter() { } unsigned char LinearSegmentParameter::getSegmentNumber() const { return _segmentNumber; } void LinearSegmentParameter::setSegmentNumber(unsigned char pX) { _segmentNumber = pX; } SixByteChunk& LinearSegmentParameter::getSegmentAppearance() { return _segmentAppearance; } const SixByteChunk& LinearSegmentParameter::getSegmentAppearance() const { return _segmentAppearance; } void LinearSegmentParameter::setSegmentAppearance(const SixByteChunk &pX) { _segmentAppearance = pX; } Vector3Double& LinearSegmentParameter::getLocation() { return _location; } const Vector3Double& LinearSegmentParameter::getLocation() const { return _location; } void LinearSegmentParameter::setLocation(const Vector3Double &pX) { _location = pX; } Orientation& LinearSegmentParameter::getOrientation() { return _orientation; } const Orientation& LinearSegmentParameter::getOrientation() const { return _orientation; } void LinearSegmentParameter::setOrientation(const Orientation &pX) { _orientation = pX; } unsigned short LinearSegmentParameter::getSegmentLength() const { return _segmentLength; } void LinearSegmentParameter::setSegmentLength(unsigned short pX) { _segmentLength = pX; } unsigned short LinearSegmentParameter::getSegmentWidth() const { return _segmentWidth; } void LinearSegmentParameter::setSegmentWidth(unsigned short pX) { _segmentWidth = pX; } unsigned short LinearSegmentParameter::getSegmentHeight() const { return _segmentHeight; } void LinearSegmentParameter::setSegmentHeight(unsigned short pX) { _segmentHeight = pX; } unsigned short LinearSegmentParameter::getSegmentDepth() const { return _segmentDepth; } void LinearSegmentParameter::setSegmentDepth(unsigned short pX) { _segmentDepth = pX; } unsigned int LinearSegmentParameter::getPad1() const { return _pad1; } void LinearSegmentParameter::setPad1(unsigned int pX) { _pad1 = pX; } void LinearSegmentParameter::marshal(DataStream& dataStream) const { dataStream << _segmentNumber; _segmentAppearance.marshal(dataStream); _location.marshal(dataStream); _orientation.marshal(dataStream); dataStream << _segmentLength; dataStream << _segmentWidth; dataStream << _segmentHeight; dataStream << _segmentDepth; dataStream << _pad1; } void LinearSegmentParameter::unmarshal(DataStream& dataStream) { dataStream >> _segmentNumber; _segmentAppearance.unmarshal(dataStream); _location.unmarshal(dataStream); _orientation.unmarshal(dataStream); dataStream >> _segmentLength; dataStream >> _segmentWidth; dataStream >> _segmentHeight; dataStream >> _segmentDepth; dataStream >> _pad1; } bool LinearSegmentParameter::operator ==(const LinearSegmentParameter& rhs) const { bool ivarsEqual = true; if( ! (_segmentNumber == rhs._segmentNumber) ) ivarsEqual = false; if( ! (_segmentAppearance == rhs._segmentAppearance) ) ivarsEqual = false; if( ! (_location == rhs._location) ) ivarsEqual = false; if( ! (_orientation == rhs._orientation) ) ivarsEqual = false; if( ! (_segmentLength == rhs._segmentLength) ) ivarsEqual = false; if( ! (_segmentWidth == rhs._segmentWidth) ) ivarsEqual = false; if( ! (_segmentHeight == rhs._segmentHeight) ) ivarsEqual = false; if( ! (_segmentDepth == rhs._segmentDepth) ) ivarsEqual = false; if( ! (_pad1 == rhs._pad1) ) ivarsEqual = false; return ivarsEqual; } int LinearSegmentParameter::getMarshalledSize() const { int marshalSize = 0; marshalSize = marshalSize + 1; // _segmentNumber marshalSize = marshalSize + _segmentAppearance.getMarshalledSize(); // _segmentAppearance marshalSize = marshalSize + _location.getMarshalledSize(); // _location marshalSize = marshalSize + _orientation.getMarshalledSize(); // _orientation marshalSize = marshalSize + 2; // _segmentLength marshalSize = marshalSize + 2; // _segmentWidth marshalSize = marshalSize + 2; // _segmentHeight marshalSize = marshalSize + 2; // _segmentDepth marshalSize = marshalSize + 4; // _pad1 return marshalSize; } // Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // 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.
28.568807
93
0.745665
AlphaPixel
6a5ca6c9fede4f97106d6204d89b025f2bf8bb80
946
hpp
C++
src/recording/encoders/encoder.hpp
mightybruno/KShare
c1124354be9c8bb5c1931e37e19391f0b6c4389f
[ "MIT" ]
213
2017-04-23T13:12:59.000Z
2022-01-18T09:03:45.000Z
src/recording/encoders/encoder.hpp
mightybruno/KShare
c1124354be9c8bb5c1931e37e19391f0b6c4389f
[ "MIT" ]
67
2017-04-29T21:49:36.000Z
2018-06-09T21:30:04.000Z
src/recording/encoders/encoder.hpp
mightybruno/KShare
c1124354be9c8bb5c1931e37e19391f0b6c4389f
[ "MIT" ]
38
2017-04-30T09:57:46.000Z
2022-01-15T20:22:52.000Z
#ifndef ENCODER_HPP #define ENCODER_HPP #include <QImage> #include <QSize> extern "C" { #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libswscale/swscale.h> } struct OutputStream { AVStream *st = NULL; AVCodecContext *enc = NULL; int64_t nextPts = 0; AVFrame *frame = NULL; SwsContext *sws = NULL; }; struct CodecSettings { int bitrate; int gopSize; int bFrames; int mbDecisions; QString h264Profile; int h264Crf; bool vp9Lossless; }; class Encoder { public: Encoder(QString &targetFile, QSize res, CodecSettings *settings = NULL); ~Encoder(); bool addFrame(QImage frm); bool isRunning(); bool end(); private: AVCodec *codec = NULL; OutputStream *out = new OutputStream; AVFormatContext *fc = NULL; bool success = false; bool ended = false; QSize size; void setFrameRGB(QImage img); }; #endif // ENCODER_HPP
16.892857
76
0.661734
mightybruno
6a5ffeba2a7390a709bcbe189929311afcbc831e
2,796
cpp
C++
test/Kin/features/main.cpp
v4hn/rai
0638426c2c4a240863de4f39778d48e48fd8f5d7
[ "MIT" ]
null
null
null
test/Kin/features/main.cpp
v4hn/rai
0638426c2c4a240863de4f39778d48e48fd8f5d7
[ "MIT" ]
null
null
null
test/Kin/features/main.cpp
v4hn/rai
0638426c2c4a240863de4f39778d48e48fd8f5d7
[ "MIT" ]
null
null
null
#include <Kin/F_qFeatures.h> #include <Kin/F_PairCollision.h> #include <Kin/TM_angVel.h> #include <Kin/F_dynamics.h> #include <Kin/F_pose.h> #include <Kin/F_contacts.h> #include <Kin/forceExchange.h> #include <iomanip> extern bool orsDrawWires; extern bool rai_Kin_frame_ignoreQuatNormalizationWarning; //=========================================================================== void testFeature() { rai::Configuration C; rai::Frame world(C), obj1(&world), obj2(&world); world.name = "world"; obj1.name = "obj1"; obj2.name = "obj2"; obj1.setRelativePosition({1.,1.,1.}); obj2.setRelativePosition({-1.,-1.,1.}); obj1.setShape(rai::ST_ssBox, ARR(1.,1.,1.,rnd.uni(.01, .3))); obj2.setShape(rai::ST_ssBox, ARR(1.,1.,1.,rnd.uni(.01, .3))); obj1.setColor({.5,.8,.5,.4}); obj2.setColor({.5,.5,.8,.4}); rai::Joint j1(obj1, rai::JT_free); rai::Joint j2(obj2, rai::JT_transXYPhi); rai::Inertia m1(obj1), m2(obj2); m1.defaultInertiaByShape(); m2.defaultInertiaByShape(); rai::ForceExchange con(obj1, obj2); C.setTimes(.1); rai::Configuration C1(C), C2(C); ConfigurationL Ktuple = {&C, &C1, &C2}; uint n=3*C.getJointStateDimension(); rai::Array<ptr<Feature>> F; F.append(make_shared<F_PairCollision>(C, "obj1", "obj2", F_PairCollision::_negScalar)); F.append(make_shared<F_PairCollision>(C, "obj1", "obj2", F_PairCollision::_vector)); F.append(make_shared<F_PairCollision>(C, "obj1", "obj2", F_PairCollision::_center)); F.append(make_shared<TM_LinAngVel>(C, "obj1")); F.append(make_shared<TM_LinAngVel>(C, "obj2")) -> order=2; F.append(make_shared<F_Pose>(C, "obj1")); F.append(make_shared<F_Pose>(C, "obj2")) -> order=1; F.append(make_shared<F_Pose>(C, "obj1")) -> order=2; F.append(symbols2feature(FS_poseRel, {"obj1", "obj2"}, C)) -> order=0; F.append(symbols2feature(FS_poseRel, {"obj1", "obj2"}, C)) -> order=1; F.append(symbols2feature(FS_poseRel, {"obj1", "obj2"}, C)) -> order=2; F.append(symbols2feature(FS_poseDiff, {"obj1", "obj2"}, C)) -> order=0; F.append(symbols2feature(FS_poseDiff, {"obj1", "obj2"}, C)) -> order=1; F.append(symbols2feature(FS_poseDiff, {"obj1", "obj2"}, C)) -> order=2; F.append(make_shared<F_NewtonEuler>(C, "obj1")); rai_Kin_frame_ignoreQuatNormalizationWarning=true; for(uint k=0;k<100;k++){ arr x = 5.*(rand(n)-.5); bool succ=true; for(ptr<Feature>& f: F){ cout <<k <<std::setw(30) <<f->shortTag(C) <<' '; succ &= checkJacobian(f->vf(Ktuple), x, 1e-5); } arr y; F.first()->__phi(y, NoArr, Ktuple); if(!succ) C2.watch(true); } } //=========================================================================== int MAIN(int argc, char** argv){ rai::initCmdLine(argc, argv); rnd.clockSeed(); testFeature(); return 0; }
30.391304
89
0.615165
v4hn
6a6280e6a0a226f8f19c557fcabea131e16c7514
306
cpp
C++
atcoder/abc/20/a.cpp
utgw/programming-contest
eb7f28ae913296c6f4f9a8136dca8bd321e01e79
[ "MIT" ]
null
null
null
atcoder/abc/20/a.cpp
utgw/programming-contest
eb7f28ae913296c6f4f9a8136dca8bd321e01e79
[ "MIT" ]
null
null
null
atcoder/abc/20/a.cpp
utgw/programming-contest
eb7f28ae913296c6f4f9a8136dca8bd321e01e79
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define FOR(i,m,n) for(int i=m;i<(n);i++) #define REP(i,n) FOR(i,0,n) #define ALL(x) (x).begin(),(x).end() using namespace std; typedef long long ll; int main(void){ int q; cin >> q; if (q == 1) cout << "ABC" << endl; else cout << "chokudai" << endl; return 0; }
18
41
0.558824
utgw
6a666d9c46fa549432d11c482f7bbb5085f48865
1,597
cc
C++
extensions/common/api/bluetooth/bluetooth_manifest_handler.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
extensions/common/api/bluetooth/bluetooth_manifest_handler.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
extensions/common/api/bluetooth/bluetooth_manifest_handler.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2014 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 "extensions/common/api/bluetooth/bluetooth_manifest_handler.h" #include "extensions/common/api/bluetooth/bluetooth_manifest_data.h" #include "extensions/common/api/bluetooth/bluetooth_manifest_permission.h" #include "extensions/common/extension.h" #include "extensions/common/manifest_constants.h" namespace extensions { BluetoothManifestHandler::BluetoothManifestHandler() {} BluetoothManifestHandler::~BluetoothManifestHandler() {} bool BluetoothManifestHandler::Parse(Extension* extension, base::string16* error) { const base::Value* bluetooth = NULL; CHECK(extension->manifest()->Get(manifest_keys::kBluetooth, &bluetooth)); std::unique_ptr<BluetoothManifestData> data = BluetoothManifestData::FromValue(*bluetooth, error); if (!data) return false; extension->SetManifestData(manifest_keys::kBluetooth, data.release()); return true; } ManifestPermission* BluetoothManifestHandler::CreatePermission() { return new BluetoothManifestPermission(); } ManifestPermission* BluetoothManifestHandler::CreateInitialRequiredPermission( const Extension* extension) { BluetoothManifestData* data = BluetoothManifestData::Get(extension); if (data) return data->permission()->Clone(); return NULL; } const std::vector<std::string> BluetoothManifestHandler::Keys() const { return SingleKey(manifest_keys::kBluetooth); } } // namespace extensions
33.270833
78
0.765185
google-ar
6a6685ac3f4a2ab572fdd930067ecdb1b9791836
5,364
cc
C++
onnxruntime/contrib_ops/cpu/bert/longformer_attention_base.cc
lchang20/onnxruntime
97b8f6f394ae02c73ed775f456fd85639c91ced1
[ "MIT" ]
6,036
2019-05-07T06:03:57.000Z
2022-03-31T17:59:54.000Z
onnxruntime/contrib_ops/cpu/bert/longformer_attention_base.cc
lchang20/onnxruntime
97b8f6f394ae02c73ed775f456fd85639c91ced1
[ "MIT" ]
5,730
2019-05-06T23:04:55.000Z
2022-03-31T23:55:56.000Z
onnxruntime/contrib_ops/cpu/bert/longformer_attention_base.cc
lchang20/onnxruntime
97b8f6f394ae02c73ed775f456fd85639c91ced1
[ "MIT" ]
1,566
2019-05-07T01:30:07.000Z
2022-03-31T17:06:50.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "longformer_attention_base.h" namespace onnxruntime { namespace contrib { Status LongformerAttentionBase::CheckInputs(const TensorShape& input_shape, const TensorShape& weights_shape, const TensorShape& bias_shape, const TensorShape& mask_shape, const TensorShape& global_weights_shape, const TensorShape& global_bias_shape, const TensorShape& global_shape) const { // Input shapes: // input : (batch_size, sequence_length, hidden_size) // weights : (hidden_size, 3 * hidden_size) // bias : (3 * hidden_size) // mask : (batch_size, sequence_length) // global_weights : (hidden_size, 3 * hidden_size) // global_bias : (3 * hidden_size) // global : (batch_size, sequence_length) const auto& dims = input_shape.GetDims(); if (dims.size() != 3) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'input' is expected to have 3 dimensions, got ", dims.size()); } int batch_size = static_cast<int>(dims[0]); int sequence_length = static_cast<int>(dims[1]); int hidden_size = static_cast<int>(dims[2]); if (sequence_length % (2 * window_) != 0) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'input' dimension 1 should be divisiable by 2W, where W is value of the window attribute."); } if (hidden_size % num_heads_ != 0) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'input' dimension 2 should be divisiable by value of the num_heads attribute."); } const auto& weights_dims = weights_shape.GetDims(); if (weights_dims.size() != 2) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'weights' is expected to have 2 dimensions, got ", weights_dims.size()); } if (weights_dims[0] != dims[2]) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'weights' dimension 0 should have same length as dimension 2 of input 0"); } if (weights_dims[1] != 3 * weights_dims[0]) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'weights' dimension 1 should be 3 times of dimension 0"); } const auto& bias_dims = bias_shape.GetDims(); if (bias_dims.size() != 1) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'bias' is expected to have 1 dimension, got ", bias_dims.size()); } if (bias_dims[0] != weights_dims[1]) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'bias' dimension 0 should have same length as dimension 1 of input 'weights'"); } const auto& mask_dims = mask_shape.GetDims(); if (mask_dims.size() == 2) { if (static_cast<int>(mask_dims[0]) != batch_size || static_cast<int>(mask_dims[1]) != sequence_length) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Inputs 'mask' shall have shape batch_size x sequence_length"); } } else { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'mask' is expected to have 2 dimensions, got ", mask_dims.size()); } const auto& global_weights_dims = global_weights_shape.GetDims(); if (global_weights_dims.size() != 2) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'global_weights' is expected to have 2 dimensions, got ", weights_dims.size()); } if (global_weights_dims[0] != dims[2]) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'global_weights' dimension 0 should have same length as dimension 2 of input 0"); } if (global_weights_dims[1] != 3 * global_weights_dims[0]) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'global_weights' dimension 1 should be 3 times of dimension 0"); } const auto& global_bias_dims = global_bias_shape.GetDims(); if (global_bias_dims.size() != 1) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'global_bias' is expected to have 1 dimension, got ", global_bias_dims.size()); } if (global_bias_dims[0] != global_weights_dims[1]) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'global_bias' dimension 0 should have same length as dimension 1 of input 'global_weights'"); } const auto& global_dims = global_shape.GetDims(); if (global_dims.size() == 2) { if (static_cast<int>(global_dims[0]) != batch_size || static_cast<int>(global_dims[1]) != sequence_length) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Inputs 'global' shall have shape batch_size x sequence_length"); } } else { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input 'global' is expected to have 2 dimensions, got ", global_dims.size()); } return Status::OK(); } } // namespace contrib } // namespace onnxruntime
47.052632
129
0.634787
lchang20
6a673688c8219042eb9dc1da3e7e81e903f7580d
494
hpp
C++
Client/includes/states/PauseState.hpp
LiardeauxQ/r-type
8a77164c276b2d5958cd3504a9ea34f1cf6823cf
[ "MIT" ]
2
2020-02-12T12:02:00.000Z
2020-12-23T15:31:59.000Z
Client/includes/states/PauseState.hpp
LiardeauxQ/r-type
8a77164c276b2d5958cd3504a9ea34f1cf6823cf
[ "MIT" ]
null
null
null
Client/includes/states/PauseState.hpp
LiardeauxQ/r-type
8a77164c276b2d5958cd3504a9ea34f1cf6823cf
[ "MIT" ]
2
2020-02-12T12:02:03.000Z
2020-12-23T15:32:55.000Z
/* ** EPITECH PROJECT, 2019 ** PauseState.hpp ** File description: ** MenuState header */ #ifndef PAUSESTATE_HPP #define PAUSESTATE_HPP #include "State.hpp" class PauseState : public State { public: PauseState(std::shared_ptr<GameData> gameData); ~PauseState(); void onStart(); void onStop(); void onPause(); void onResume(); Transition update(); Transition handleEvent(sf::Event &event); }; #endif /* !PAUSESTATE_HPP */
19
55
0.625506
LiardeauxQ
6a696e2bf6e8f99049f29cd32c6e2e6e620d9d5e
936
cpp
C++
source/loader/linux/driver_discovery_lin.cpp
bgoglin/level-zero
e36cbe25004642a0b0e8ed0670a03725caacd8ad
[ "MIT" ]
3
2021-04-30T13:57:15.000Z
2021-06-28T06:59:47.000Z
source/loader/linux/driver_discovery_lin.cpp
bgoglin/level-zero
e36cbe25004642a0b0e8ed0670a03725caacd8ad
[ "MIT" ]
null
null
null
source/loader/linux/driver_discovery_lin.cpp
bgoglin/level-zero
e36cbe25004642a0b0e8ed0670a03725caacd8ad
[ "MIT" ]
1
2021-07-06T04:42:48.000Z
2021-07-06T04:42:48.000Z
/* * * Copyright (C) 2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "source/loader/driver_discovery.h" #include "source/inc/ze_util.h" #include <iostream> #include <sstream> #include <string> namespace loader { static const char *knownDriverNames[] = { MAKE_LIBRARY_NAME("ze_intel_gpu", "1"), }; std::vector<DriverLibraryPath> discoverEnabledDrivers() { std::vector<DriverLibraryPath> enabledDrivers; const char *altDrivers = nullptr; // ZE_ENABLE_ALT_DRIVERS is for development/debug only altDrivers = getenv("ZE_ENABLE_ALT_DRIVERS"); if (altDrivers == nullptr) { for (auto path : knownDriverNames) { enabledDrivers.emplace_back(path); } } else { std::stringstream ss(altDrivers); while (ss.good()) { std::string substr; getline(ss, substr, ','); enabledDrivers.emplace_back(substr); } } return enabledDrivers; } } // namespace loader
21.272727
57
0.688034
bgoglin
6a69d71eca6c7d026d5b3d43c05b8d46ca13d94a
636
hpp
C++
include/Event.hpp
RPClab/Analysis
cca7d4d07ead111ac61caee31ebd3522c88bac96
[ "MIT" ]
null
null
null
include/Event.hpp
RPClab/Analysis
cca7d4d07ead111ac61caee31ebd3522c88bac96
[ "MIT" ]
1
2021-08-04T08:20:00.000Z
2021-08-04T08:20:00.000Z
include/Event.hpp
MaftyNaveyuErin/Analysis
1d1870befde835baf6efb4fcaec292ee536d13f8
[ "MIT" ]
2
2021-07-29T06:47:38.000Z
2021-08-04T09:17:02.000Z
#pragma once #include "Channel.hpp" #include "TObject.h" #include <string> #include <vector> class Event: public TObject { public: Event()=default; void addChannel(const Channel& ch); void clear(); double BoardID{0}; int EventNumber{0}; int Pattern{0}; int ChannelMask{0}; double EventSize{0}; double TriggerTimeTag{0}; double Period_ns{0.0}; std::string Model{""}; std::string FamilyCode{""}; std::vector<Channel> Channels; ClassDef(Event, 2); };
23.555556
53
0.512579
RPClab
6a6f09d56511d23170ba885239075452341f4c0f
4,040
cpp
C++
src/cat_sorting.cpp
prescott66/poedit
f52d76beff00198686b27996d5a11fa24252a173
[ "MIT" ]
null
null
null
src/cat_sorting.cpp
prescott66/poedit
f52d76beff00198686b27996d5a11fa24252a173
[ "MIT" ]
null
null
null
src/cat_sorting.cpp
prescott66/poedit
f52d76beff00198686b27996d5a11fa24252a173
[ "MIT" ]
null
null
null
/* * This file is part of Poedit (http://www.poedit.net) * * Copyright (C) 1999-2012 Vaclav Slavik * Copyright (C) 2005 Olivier Sannier * * 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 "cat_sorting.h" #include <wx/config.h> /*static*/ SortOrder SortOrder::Default() { SortOrder order; wxString by = wxConfig::Get()->Read(_T("/sort_by"), _T("file-order")); long untrans = wxConfig::Get()->Read(_T("/sort_untrans_first"), 1L); if ( by == _T("source") ) order.by = By_Source; else if ( by == _T("translation") ) order.by = By_Translation; else order.by = By_FileOrder; order.untransFirst = (untrans != 0); return order; } void SortOrder::Save() { wxString bystr; switch ( by ) { case By_FileOrder: bystr = _T("file-order"); break; case By_Source: bystr = _T("source"); break; case By_Translation: bystr = _T("translation"); break; } wxConfig::Get()->Write(_T("/sort_by"), bystr); wxConfig::Get()->Write(_T("/sort_untrans_first"), untransFirst); } bool CatalogItemsComparator::operator()(int i, int j) const { const CatalogItem& a = Item(i); const CatalogItem& b = Item(j); if ( m_order.untransFirst ) { if ( a.GetValidity() == CatalogItem::Val_Invalid && b.GetValidity() != CatalogItem::Val_Invalid ) return true; if ( a.GetValidity() != CatalogItem::Val_Invalid && b.GetValidity() == CatalogItem::Val_Invalid ) return false; if ( !a.IsTranslated() && b.IsTranslated() ) return true; if ( a.IsTranslated() && !b.IsTranslated() ) return false; if ( a.IsFuzzy() && !b.IsFuzzy() ) return true; if ( !a.IsFuzzy() && b.IsFuzzy() ) return false; } switch ( m_order.by ) { case SortOrder::By_FileOrder: { return i < j; } case SortOrder::By_Source: { int r = CompareStrings(a.GetString(), b.GetString()); if ( r != 0 ) return r < 0; break; } case SortOrder::By_Translation: { int r = CompareStrings(a.GetTranslation(), b.GetTranslation()); if ( r != 0 ) return r < 0; break; } } // As last resort, sort by position in file. Note that this means that // no two items are considered equal w.r.t. sort order; this ensures stable // ordering. return i < j; } int CatalogItemsComparator::CompareStrings(wxString a, wxString b) const { // TODO: * use ICU for correct ordering // * use natural sort (for numbers) // * use ICU for correct case insensitivity a.Replace(_T("&"), _T("")); a.Replace(_T("_"), _T("")); b.Replace(_T("&"), _T("")); b.Replace(_T("_"), _T("")); return a.CmpNoCase(b); }
28.857143
105
0.597277
prescott66
6a703a644c7e7c2d7131ba819df184ca9b00ed69
4,505
cpp
C++
src/Obq_LightSaturationFilter.cpp
madesjardins/Obq_Shaders
9b5df11d54fc08cf217631a4f655603313de8d77
[ "Unlicense", "MIT" ]
43
2016-01-17T01:57:48.000Z
2021-08-30T21:10:26.000Z
src/Obq_LightSaturationFilter.cpp
madesjardins/Obq_Shaders
9b5df11d54fc08cf217631a4f655603313de8d77
[ "Unlicense", "MIT" ]
11
2015-12-15T21:25:38.000Z
2021-01-14T22:58:40.000Z
src/Obq_LightSaturationFilter.cpp
madesjardins/Obq_Shaders
9b5df11d54fc08cf217631a4f655603313de8d77
[ "Unlicense", "MIT" ]
10
2015-12-03T22:32:59.000Z
2020-06-02T16:30:36.000Z
/* Obq_LightSaturationFilter : Send receive test. *------------------------------------------------------------------------ Copyright (c) 2012-2015 Marc-Antoine Desjardins, ObliqueFX (marcantoinedesjardins@gmail.com) 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. Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php *------------------------------------------------------------------------ */ #include "O_Common.h" //--------------- // Arnold thingy AI_SHADER_NODE_EXPORT_METHODS(ObqLightSaturationFilterMethod); //------------------- // Arnold enum params enum Obq_LightSaturationFilter_Params {p_mode, p_key, p_triggerValue, p_saturation, p_defaultSaturation}; enum Obq_LightSaturationFilter_Mode {SIMPLE, TRIGGER, ASVALUE}; static const char* Obq_LightSaturationFilter_ModeNames[] = { "Simple saturation modifier", "Use trigger message", "Use message as saturation", NULL }; // shader data struct // typedef struct { int mode; const char* key; float triggerValue; float saturation; float defaultSaturation; } ShaderData; //----------------------- // Arnold node parameters node_parameters { AiParameterENUM("mode", SIMPLE,Obq_LightSaturationFilter_ModeNames); AiParameterSTR("key", "O1"); AiParameterFLT("triggerValue", 1.0f); AiParameterFLT("saturation", 0.0f); AiParameterFLT("defaultSaturation", 1.0f); } //------------------ // Arnold initialize node_initialize { ShaderData *data = (ShaderData*) AiMalloc(sizeof(ShaderData)); data->mode = SIMPLE; data->key = "O1"; data->triggerValue = 1.0f; data->saturation = 0.0f; data->defaultSaturation = 1.0f; AiNodeSetLocalData (node, data); } //-------------- // Arnold update node_update { ShaderData *data = (ShaderData*) AiNodeGetLocalData(node); data->mode = AiNodeGetInt(node,"mode"); data->key = AiNodeGetStr(node,"key"); data->triggerValue = AiNodeGetFlt(node,"triggerValue"); data->saturation = minimax(0.0f,AiNodeGetFlt(node,"saturation"),1.0f); data->defaultSaturation = minimax(0.0f,AiNodeGetFlt(node,"defaultSaturation"),1.0f); } inline void saturateLiu(AtColor& liu, float saturation) { float oneMinusSaturation = 1.0f-saturation; float mixluminance = oneMinusSaturation*(0.2126f*liu.r + 0.7152f*liu.g + 0.0722f*liu.b); liu.r = mixluminance + saturation*liu.r; liu.g = mixluminance + saturation*liu.g; liu.b = mixluminance + saturation*liu.b; } //---------------- // Arnold evaluate shader_evaluate { ShaderData *data = (ShaderData*) AiNodeGetLocalData(node); // Unoccluded intensity float ret = -1.0f; if(data->mode == SIMPLE) { saturateLiu(sg->Liu,data->saturation); } else if(AiStateGetMsgFlt(data->key, &ret)) // a message exists { if(data->mode == TRIGGER && ret == data->triggerValue ) saturateLiu(sg->Liu,data->saturation); else if(data->mode == ASVALUE) saturateLiu(sg->Liu,minimax(0.0f,ret,1.0f)); else saturateLiu(sg->Liu,data->defaultSaturation); } else saturateLiu(sg->Liu,data->defaultSaturation); } //-------------- // Arnold finish node_finish { ShaderData *data = (ShaderData*) AiNodeGetLocalData(node); AiFree(data); } //node_loader //{ // if (i > 0) // return false; // // node->methods = ObqLightSaturationFilterMethod; // node->output_type = AI_TYPE_RGB; // node->name = "Obq_LightSaturationFilter"; // node->node_type = AI_NODE_SHADER; //#ifdef _WIN32 // strcpy_s(node->version, AI_VERSION); //#else // strcpy(node->version, AI_VERSION); //#endif // return true; //}
28.15625
105
0.692564
madesjardins
6a731d968ed5d8be887538dd0054220894a53008
2,354
cpp
C++
101908/B.cpp
julianferres/Codeforces
ac80292a4d53b8078fc1a85e91db353c489555d9
[ "MIT" ]
4
2020-01-31T15:49:25.000Z
2020-07-07T11:44:03.000Z
101908/B.cpp
julianferres/CodeForces
14e8369e82a2403094183d6f7824201f681c9f65
[ "MIT" ]
null
null
null
101908/B.cpp
julianferres/CodeForces
14e8369e82a2403094183d6f7824201f681c9f65
[ "MIT" ]
null
null
null
/* AUTHOR: julianferres */ #include <bits/stdc++.h> using namespace std; // neal Debugger template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; } template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { os << '{'; string sep; for (const T &x : v) os << sep << x, sep = ", "; return os << '}'; } void dbg_out() { cerr << endl; } template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); } #ifdef LOCAL #define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__) #else #define dbg(...) #endif typedef long long ll; typedef vector<ll> vi; typedef pair<ll,ll> ii; typedef vector<ii> vii; typedef vector<bool> vb; #define FIN ios::sync_with_stdio(0);cin.tie(0);cout.tie(0) #define forr(i, a, b) for(int i = (a); i < (int) (b); i++) #define forn(i, n) forr(i, 0, n) #define DBG(x) cerr << #x << " = " << (x) << endl #define RAYA cerr << "===============================" << endl #define pb push_back #define mp make_pair #define all(c) (c).begin(),(c).end() #define esta(x,c) ((c).find(x) != (c).end()) const int MOD = 1e9+7; // 998244353 const int MAXN = 2e5+5; const int GRUNDY_GRANDE = 1000; vector<vector<int>> grundy(105, vector<int>(105)); int mex(int r, int c){ unordered_set<int> mex_set; forn(i, r) mex_set.insert(grundy[i][c]); forn(i, c) mex_set.insert(grundy[r][i]); forr(i, 1, min(r, c)) //Diagonales mex_set.insert(grundy[r-i][c-i]); forn(i, GRUNDY_GRANDE + 1) if(!esta(i, mex_set)) return i; } int main(){ FIN; forn(i, 104){ grundy[i][0] = grundy[i][i] = grundy[0][i] = GRUNDY_GRANDE; } forr(i, 1, 101){ forr(j, 1, 101) if(i != j) grundy[i][j] = mex(i, j); } int n; cin >> n; int resultado_final = 0; forn(i, n){ int ri, ci; cin >> ri >> ci; if(grundy[ri][ci] == GRUNDY_GRANDE){ cout << "Y\n"; // YA directamente gana return 0; } resultado_final ^= grundy[ri][ci]; // Cada ficha juega individualmente } cout << (resultado_final ? "Y" : "N") << "\n"; return 0; }
30.973684
290
0.568819
julianferres
6a75d731e0a24deda022adeeec5ff7bb52df510e
10,192
cpp
C++
benchmarks/linux-sgx/sdk/protected_fs/sgx_tprotected_fs/file_other.cpp
vschiavoni/unine-twine
312d770585ea88c13ef135ef467fee779494fd90
[ "Apache-2.0" ]
20
2021-04-05T20:05:57.000Z
2022-02-19T18:48:52.000Z
benchmarks/linux-sgx/sdk/protected_fs/sgx_tprotected_fs/file_other.cpp
vschiavoni/unine-twine
312d770585ea88c13ef135ef467fee779494fd90
[ "Apache-2.0" ]
null
null
null
benchmarks/linux-sgx/sdk/protected_fs/sgx_tprotected_fs/file_other.cpp
vschiavoni/unine-twine
312d770585ea88c13ef135ef467fee779494fd90
[ "Apache-2.0" ]
4
2021-02-22T14:52:21.000Z
2022-01-10T16:58:39.000Z
/* * Copyright (C) 2011-2020 Intel Corporation. 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 Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "sgx_tprotected_fs.h" #include "sgx_tprotected_fs_t.h" #include "protected_fs_file.h" #include "benchmark_utils.h" #include <sgx_utils.h> //#include <sgx_trts.h> #include <errno.h> // this function returns 0 only if the specified file existed and it was actually deleted // before we do that, we try to see if the file contained a monotonic counter, and if it did, we delete it from the system int32_t protected_fs_file::remove(const char* filename) { sgx_status_t status; int32_t result32 = 0; /* void* file = NULL; int64_t real_file_size = 0; if (filename == NULL) return 1; meta_data_node_t* file_meta_data = NULL; meta_data_encrypted_t* encrypted_part_plain = NULL; // if we have a problem in any of the stages, we simply jump to the end and try to remove the file... do { status = u_sgxprotectedfs_check_if_file_exists(&result, filename); if (status != SGX_SUCCESS) break; if (result == 0) { errno = EINVAL; return 1; // no such file, or file locked so we can't delete it anyways } try { file_meta_data = new meta_data_node_t; encrypted_part_plain = new meta_data_encrypted_t; } catch (std::bad_alloc e) { break; } status = u_sgxprotectedfs_exclusive_file_open(&file, filename, 1, &real_file_size, &result32); if (status != SGX_SUCCESS || file == NULL) break; if (real_file_size == 0 || real_file_size % NODE_SIZE != 0) break; // empty file or not an SGX protected FS file // might be an SGX protected FS file status = u_sgxprotectedfs_fread_node(&result32, file, 0, (uint8_t*)file_meta_data, NODE_SIZE); if (status != SGX_SUCCESS || result32 != 0) break; if (file_meta_data->plain_part.major_version != SGX_FILE_MAJOR_VERSION) break; sgx_aes_gcm_128bit_key_t zero_key_id = {0}; sgx_aes_gcm_128bit_key_t key = {0}; if (consttime_memequal(&file_meta_data->plain_part.key_id, &zero_key_id, sizeof(sgx_aes_gcm_128bit_key_t)) == 1) break; // shared file - no monotonic counter sgx_key_request_t key_request = {0}; key_request.key_name = SGX_KEYSELECT_SEAL; key_request.key_policy = SGX_KEYPOLICY_MRENCLAVE; memcpy(&key_request.key_id, &file_meta_data->plain_part.key_id, sizeof(sgx_key_id_t)); status = sgx_get_key(&key_request, &key); if (status != SGX_SUCCESS) break; status = benchmark_sgx_rijndael128GCM_decrypt(&key, file_meta_data->encrypted_part, sizeof(meta_data_encrypted_blob_t), (uint8_t*)encrypted_part_plain, file_meta_data->plain_part.meta_data_iv, SGX_AESGCM_IV_SIZE, NULL, 0, &file_meta_data->plain_part.meta_data_gmac); if (status != SGX_SUCCESS) break; sgx_mc_uuid_t empty_mc_uuid = {0}; if (consttime_memequal(&empty_mc_uuid, &encrypted_part_plain->mc_uuid, sizeof(sgx_mc_uuid_t)) == 0) { status = sgx_destroy_monotonic_counter(&encrypted_part_plain->mc_uuid); if (status != SGX_SUCCESS) break; // monotonic counter was deleted, mission accomplished!! } } while (0); // cleanup if (file_meta_data != NULL) delete file_meta_data; if (encrypted_part_plain != NULL) { // scrub the encrypted part memset_s(encrypted_part_plain, sizeof(meta_data_encrypted_t), 0, sizeof(meta_data_encrypted_t)); delete encrypted_part_plain; } if (file != NULL) u_sgxprotectedfs_fclose(&result32, file); */ // do the actual file removal status = u_sgxprotectedfs_remove(&result32, filename); if (status != SGX_SUCCESS) { errno = status; return 1; } if (result32 != 0) { if (result32 == -1) // no external errno value errno = EPERM; else errno = result32; return 1; } return 0; } int64_t protected_fs_file::tell() { int64_t result; sgx_thread_mutex_lock(&mutex); if (file_status != SGX_FILE_STATUS_OK) { errno = EPERM; last_error = SGX_ERROR_FILE_BAD_STATUS; sgx_thread_mutex_unlock(&mutex); return -1; } result = offset; sgx_thread_mutex_unlock(&mutex); return result; } // we don't support sparse files, fseek beyond the current file size will fail int protected_fs_file::seek(int64_t new_offset, int origin) { sgx_thread_mutex_lock(&mutex); if (file_status != SGX_FILE_STATUS_OK) { last_error = SGX_ERROR_FILE_BAD_STATUS; sgx_thread_mutex_unlock(&mutex); return -1; } //if (open_mode.binary == 0 && origin != SEEK_SET && new_offset != 0) //{ // last_error = EINVAL; // sgx_thread_mutex_unlock(&mutex); // return -1; //} int result = -1; switch (origin) { case SEEK_SET: if (new_offset >= 0 && new_offset <= encrypted_part_plain.size) { offset = new_offset; result = 0; } break; case SEEK_CUR: if ((offset + new_offset) >= 0 && (offset + new_offset) <= encrypted_part_plain.size) { offset += new_offset; result = 0; } break; case SEEK_END: if (new_offset <= 0 && new_offset >= (0 - encrypted_part_plain.size)) { offset = encrypted_part_plain.size + new_offset; result = 0; } break; default: break; } if (result == 0) end_of_file = false; else last_error = EINVAL; sgx_thread_mutex_unlock(&mutex); return result; } uint32_t protected_fs_file::get_error() { uint32_t result = SGX_SUCCESS; sgx_thread_mutex_lock(&mutex); if (last_error != SGX_SUCCESS) result = last_error; else if (file_status != SGX_FILE_STATUS_OK) result = SGX_ERROR_FILE_BAD_STATUS; sgx_thread_mutex_unlock(&mutex); return result; } bool protected_fs_file::get_eof() { return end_of_file; } void protected_fs_file::clear_error() { sgx_thread_mutex_lock(&mutex); if (file_status == SGX_FILE_STATUS_NOT_INITIALIZED || file_status == SGX_FILE_STATUS_CLOSED || file_status == SGX_FILE_STATUS_CRYPTO_ERROR || file_status == SGX_FILE_STATUS_CORRUPTED || file_status == SGX_FILE_STATUS_MEMORY_CORRUPTED) // can't fix these... { sgx_thread_mutex_unlock(&mutex); return; } if (file_status == SGX_FILE_STATUS_FLUSH_ERROR) { if (internal_flush(/*false,*/ true) == true) file_status = SGX_FILE_STATUS_OK; } if (file_status == SGX_FILE_STATUS_WRITE_TO_DISK_FAILED) { if (write_all_changes_to_disk(true) == true) { need_writing = false; file_status = SGX_FILE_STATUS_OK; } } /* if (file_status == SGX_FILE_STATUS_WRITE_TO_DISK_FAILED_NEED_MC) { if (write_all_changes_to_disk(true) == true) { need_writing = false; file_status = SGX_FILE_STATUS_MC_NOT_INCREMENTED; // fall through...next 'if' should take care of this one } } if ((file_status == SGX_FILE_STATUS_MC_NOT_INCREMENTED) && (encrypted_part_plain.mc_value <= (UINT_MAX-2))) { uint32_t mc_value; sgx_status_t status = sgx_increment_monotonic_counter(&encrypted_part_plain.mc_uuid, &mc_value); if (status == SGX_SUCCESS) { assert(mc_value == encrypted_part_plain.mc_value); file_status = SGX_FILE_STATUS_OK; } else { last_error = status; } } */ if (file_status == SGX_FILE_STATUS_OK) { last_error = SGX_SUCCESS; end_of_file = false; } sgx_thread_mutex_unlock(&mutex); } // clears the cache with all the plain data that was in it // doesn't clear the meta-data and first node, which are part of the 'main' structure int32_t protected_fs_file::clear_cache() { sgx_thread_mutex_lock(&mutex); if (file_status != SGX_FILE_STATUS_OK) { sgx_thread_mutex_unlock(&mutex); clear_error(); // attempt to fix the file, will also flush it sgx_thread_mutex_lock(&mutex); } else // file_status == SGX_FILE_STATUS_OK { internal_flush(/*false,*/ true); } if (file_status != SGX_FILE_STATUS_OK) // clearing the cache might lead to losing un-saved data { sgx_thread_mutex_unlock(&mutex); return 1; } while (cache.size() > 0) { void* data = cache.get_last(); assert(data != NULL); assert(((file_data_node_t*)data)->need_writing == false); // need_writing is in the same offset in both node types // for production - if (data == NULL || ((file_data_node_t*)data)->need_writing == true) { sgx_thread_mutex_unlock(&mutex); return 1; } cache.remove_last(); // before deleting the memory, need to scrub the plain secrets if (((file_data_node_t*)data)->type == FILE_DATA_NODE_TYPE) // type is in the same offset in both node types { file_data_node_t* file_data_node = (file_data_node_t*)data; memset_s(&file_data_node->plain, sizeof(data_node_t), 0, sizeof(data_node_t)); delete file_data_node; } else { file_mht_node_t* file_mht_node = (file_mht_node_t*)data; memset_s(&file_mht_node->plain, sizeof(mht_node_t), 0, sizeof(mht_node_t)); delete file_mht_node; } } sgx_thread_mutex_unlock(&mutex); return 0; }
25.672544
122
0.718407
vschiavoni
6a7603159561fc5925dc445ca2c478acdab8a413
7,805
cpp
C++
generator/osm_source.cpp
KAMiKAZOW/omim
560c1edf10c46bd2e6bc4d466bf6c65b92538b4a
[ "Apache-2.0" ]
7
2020-12-20T23:21:10.000Z
2020-12-23T23:38:58.000Z
generator/osm_source.cpp
mbrukman/omim
d22fe2b6e0beee697f096e931df97a64f9db9dc1
[ "Apache-2.0" ]
1
2020-06-18T11:19:43.000Z
2020-06-18T11:19:43.000Z
generator/osm_source.cpp
mbrukman/omim
d22fe2b6e0beee697f096e931df97a64f9db9dc1
[ "Apache-2.0" ]
null
null
null
#include "generator/osm_source.hpp" #include "generator/intermediate_data.hpp" #include "generator/intermediate_elements.hpp" #include "generator/osm_element.hpp" #include "generator/towns_dumper.hpp" #include "generator/translator_factory.hpp" #include "platform/platform.hpp" #include "geometry/mercator.hpp" #include "geometry/tree4d.hpp" #include "base/assert.hpp" #include "base/stl_helpers.hpp" #include "base/file_name_utils.hpp" #include <fstream> #include <memory> #include <set> #include "defines.hpp" using namespace std; namespace generator { // SourceReader ------------------------------------------------------------------------------------ SourceReader::SourceReader() : m_file(unique_ptr<istream, Deleter>(&cin, Deleter(false))) { LOG_SHORT(LINFO, ("Reading OSM data from stdin")); } SourceReader::SourceReader(string const & filename) : m_file(unique_ptr<istream, Deleter>(new ifstream(filename), Deleter())) { CHECK(static_cast<ifstream *>(m_file.get())->is_open(), ("Can't open file:", filename)); LOG_SHORT(LINFO, ("Reading OSM data from", filename)); } SourceReader::SourceReader(istringstream & stream) : m_file(unique_ptr<istream, Deleter>(&stream, Deleter(false))) { LOG_SHORT(LINFO, ("Reading OSM data from memory")); } uint64_t SourceReader::Read(char * buffer, uint64_t bufferSize) { m_file->read(buffer, bufferSize); return m_file->gcount(); } // Functions --------------------------------------------------------------------------------------- void AddElementToCache(cache::IntermediateDataWriter & cache, OsmElement & element) { switch (element.m_type) { case OsmElement::EntityType::Node: { auto const pt = mercator::FromLatLon(element.m_lat, element.m_lon); cache.AddNode(element.m_id, pt.y, pt.x); break; } case OsmElement::EntityType::Way: { // Store way. WayElement way(element.m_id); for (uint64_t nd : element.Nodes()) way.m_nodes.push_back(nd); if (way.IsValid()) cache.AddWay(element.m_id, way); break; } case OsmElement::EntityType::Relation: { // store relation RelationElement relation; for (auto const & member : element.Members()) { switch (member.m_type) { case OsmElement::EntityType::Node: relation.m_nodes.emplace_back(member.m_ref, string(member.m_role)); break; case OsmElement::EntityType::Way: relation.m_ways.emplace_back(member.m_ref, string(member.m_role)); break; case OsmElement::EntityType::Relation: relation.m_relations.emplace_back(member.m_ref, string(member.m_role)); break; default: break; } } for (auto const & tag : element.Tags()) relation.m_tags.emplace(tag.m_key, tag.m_value); if (relation.IsValid()) cache.AddRelation(element.m_id, relation); break; } default: break; } } void BuildIntermediateDataFromXML(SourceReader & stream, cache::IntermediateDataWriter & cache, TownsDumper & towns) { ProcessorOsmElementsFromXml processorOsmElementsFromXml(stream); OsmElement element; while (processorOsmElementsFromXml.TryRead(element)) { towns.CheckElement(element); AddElementToCache(cache, element); } } void ProcessOsmElementsFromXML(SourceReader & stream, function<void(OsmElement *)> processor) { ProcessorOsmElementsFromXml processorOsmElementsFromXml(stream); OsmElement element; while (processorOsmElementsFromXml.TryRead(element)) processor(&element); } void BuildIntermediateDataFromO5M(SourceReader & stream, cache::IntermediateDataWriter & cache, TownsDumper & towns) { auto processor = [&](OsmElement * element) { towns.CheckElement(*element); AddElementToCache(cache, *element); }; // Use only this function here, look into ProcessOsmElementsFromO5M // for more details. ProcessOsmElementsFromO5M(stream, processor); } void ProcessOsmElementsFromO5M(SourceReader & stream, function<void(OsmElement *)> processor) { ProcessorOsmElementsFromO5M processorOsmElementsFromO5M(stream); OsmElement element; while (processorOsmElementsFromO5M.TryRead(element)) processor(&element); } ProcessorOsmElementsFromO5M::ProcessorOsmElementsFromO5M(SourceReader & stream) : m_stream(stream) , m_dataset([&](uint8_t * buffer, size_t size) { return m_stream.Read(reinterpret_cast<char *>(buffer), size); }) , m_pos(m_dataset.begin()) { } bool ProcessorOsmElementsFromO5M::TryRead(OsmElement & element) { if (m_pos == m_dataset.end()) return false; using Type = osm::O5MSource::EntityType; auto const translate = [](Type t) -> OsmElement::EntityType { switch (t) { case Type::Node: return OsmElement::EntityType::Node; case Type::Way: return OsmElement::EntityType::Way; case Type::Relation: return OsmElement::EntityType::Relation; default: return OsmElement::EntityType::Unknown; } }; element = {}; // Be careful, we could call Nodes(), Members(), Tags() from O5MSource::Entity // only once (!). Because these functions read data from file simultaneously with // iterating in loop. Furthermore, into Tags() method calls Nodes.Skip() and Members.Skip(), // thus first call of Nodes (Members) after Tags() will not return any results. // So don not reorder the "for" loops (!). auto const entity = *m_pos; element.m_id = entity.id; switch (entity.type) { case Type::Node: { element.m_type = OsmElement::EntityType::Node; element.m_lat = entity.lat; element.m_lon = entity.lon; break; } case Type::Way: { element.m_type = OsmElement::EntityType::Way; for (uint64_t nd : entity.Nodes()) element.AddNd(nd); break; } case Type::Relation: { element.m_type = OsmElement::EntityType::Relation; for (auto const & member : entity.Members()) element.AddMember(member.ref, translate(member.type), member.role); break; } default: break; } for (auto const & tag : entity.Tags()) element.AddTag(tag.key, tag.value); ++m_pos; return true; } ProcessorOsmElementsFromXml::ProcessorOsmElementsFromXml(SourceReader & stream) : m_xmlSource([&, this](auto * element) { m_queue.emplace(*element); }) , m_parser(stream, m_xmlSource) { } bool ProcessorOsmElementsFromXml::TryReadFromQueue(OsmElement & element) { if (m_queue.empty()) return false; element = m_queue.front(); m_queue.pop(); return true; } bool ProcessorOsmElementsFromXml::TryRead(OsmElement & element) { do { if (TryReadFromQueue(element)) return true; } while (m_parser.Read()); return TryReadFromQueue(element); } /////////////////////////////////////////////////////////////////////////////////////////////////// // Generate functions implementations. /////////////////////////////////////////////////////////////////////////////////////////////////// bool GenerateIntermediateData(feature::GenerateInfo & info) { auto nodes = cache::CreatePointStorageWriter(info.m_nodeStorageType, info.GetCacheFileName(NODES_FILE)); cache::IntermediateDataWriter cache(*nodes, info); TownsDumper towns; SourceReader reader = info.m_osmFileName.empty() ? SourceReader() : SourceReader(info.m_osmFileName); LOG(LINFO, ("Data source:", info.m_osmFileName)); switch (info.m_osmFileType) { case feature::GenerateInfo::OsmSourceType::XML: BuildIntermediateDataFromXML(reader, cache, towns); break; case feature::GenerateInfo::OsmSourceType::O5M: BuildIntermediateDataFromO5M(reader, cache, towns); break; } cache.SaveIndex(); towns.Dump(info.GetIntermediateFileName(TOWNS_FILE)); LOG(LINFO, ("Added points count =", nodes->GetNumProcessedPoints())); return true; } } // namespace generator
28.589744
103
0.671365
KAMiKAZOW
6a78c619673b421223e3f24633a39ea63ad7f4c9
77
cpp
C++
src/core/menu/tabs/rage.cpp
luk1337/gamesneeze
9b85e177d5af9a1bd30a296172c4d80f91966966
[ "MIT" ]
1
2021-02-10T00:33:31.000Z
2021-02-10T00:33:31.000Z
src/core/menu/tabs/rage.cpp
luk1337/gamesneeze
9b85e177d5af9a1bd30a296172c4d80f91966966
[ "MIT" ]
null
null
null
src/core/menu/tabs/rage.cpp
luk1337/gamesneeze
9b85e177d5af9a1bd30a296172c4d80f91966966
[ "MIT" ]
null
null
null
#include "../menu.hpp" void Menu::drawRageTab() { ImGui::Text("Rage"); }
15.4
26
0.597403
luk1337
6a799b9f4c39aa781dfb7f22331f53657dfa4b64
5,442
cc
C++
INET_EC/visualizer/transportlayer/TransportConnectionOsgVisualizer.cc
LarryNguyen/ECSim-
0d3f848642e49845ed7e4c7b97dd16bd3d65ede5
[ "Apache-2.0" ]
12
2020-11-30T08:04:23.000Z
2022-03-23T11:49:26.000Z
INET_EC/visualizer/transportlayer/TransportConnectionOsgVisualizer.cc
LarryNguyen/ECSim-
0d3f848642e49845ed7e4c7b97dd16bd3d65ede5
[ "Apache-2.0" ]
1
2021-01-26T10:49:56.000Z
2021-01-31T16:58:52.000Z
INET_EC/visualizer/transportlayer/TransportConnectionOsgVisualizer.cc
LarryNguyen/ECSim-
0d3f848642e49845ed7e4c7b97dd16bd3d65ede5
[ "Apache-2.0" ]
8
2021-03-15T02:05:51.000Z
2022-03-21T13:14:02.000Z
// // Copyright (C) OpenSim Ltd. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program; if not, see <http://www.gnu.org/licenses/>. // #include "inet/common/ModuleAccess.h" #include "inet/common/OSGUtils.h" #include "inet/visualizer/transportlayer/TransportConnectionOsgVisualizer.h" namespace inet { namespace visualizer { Define_Module(TransportConnectionOsgVisualizer); #ifdef WITH_OSG TransportConnectionOsgVisualizer::TransportConnectionOsgVisualization::TransportConnectionOsgVisualization(osg::Node *sourceNode, osg::Node *destinationNode, int sourceModuleId, int destinationModuleId, int count) : TransportConnectionVisualization(sourceModuleId, destinationModuleId, count), sourceNode(sourceNode), destinationNode(destinationNode) { } void TransportConnectionOsgVisualizer::initialize(int stage) { TransportConnectionVisualizerBase::initialize(stage); if (!hasGUI()) return; if (stage == INITSTAGE_LOCAL) { networkNodeVisualizer = getModuleFromPar<NetworkNodeOsgVisualizer>(par("networkNodeVisualizerModule"), this); } } osg::Node *TransportConnectionOsgVisualizer::createConnectionEndNode(tcp::TCPConnection *tcpConnection) const { auto path = resolveResourcePath((std::string(icon) + ".png").c_str()); auto image = inet::osg::createImage(path.c_str()); auto texture = new osg::Texture2D(); texture->setImage(image); auto geometry = osg::createTexturedQuadGeometry(osg::Vec3(-image->s() / 2, 0.0, 0.0), osg::Vec3(image->s(), 0.0, 0.0), osg::Vec3(0.0, image->t(), 0.0), 0.0, 0.0, 1.0, 1.0); auto stateSet = geometry->getOrCreateStateSet(); stateSet->setTextureAttributeAndModes(0, texture); stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON); stateSet->setMode(GL_BLEND, osg::StateAttribute::ON); stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF); stateSet->setRenderingHint(osg::StateSet::TRANSPARENT_BIN); auto color = iconColorSet.getColor(connectionVisualizations.size()); auto colorArray = new osg::Vec4Array(); colorArray->push_back(osg::Vec4((double)color.red / 255.0, (double)color.green / 255.0, (double)color.blue / 255.0, 1)); geometry->setColorArray(colorArray, osg::Array::BIND_OVERALL); auto geode = new osg::Geode(); geode->addDrawable(geometry); return geode; } const TransportConnectionVisualizerBase::TransportConnectionVisualization *TransportConnectionOsgVisualizer::createConnectionVisualization(cModule *source, cModule *destination, tcp::TCPConnection *tcpConnection) const { auto sourceNode = createConnectionEndNode(tcpConnection); auto destinationNode = createConnectionEndNode(tcpConnection); return new TransportConnectionOsgVisualization(sourceNode, destinationNode, source->getId(), destination->getId(), 1); } void TransportConnectionOsgVisualizer::addConnectionVisualization(const TransportConnectionVisualization *connectionVisualization) { TransportConnectionVisualizerBase::addConnectionVisualization(connectionVisualization); auto connectionOsgVisualization = static_cast<const TransportConnectionOsgVisualization *>(connectionVisualization); auto sourceModule = getSimulation()->getModule(connectionVisualization->sourceModuleId); auto sourceVisualization = networkNodeVisualizer->getNetworkNodeVisualization(getContainingNode(sourceModule)); sourceVisualization->addAnnotation(connectionOsgVisualization->sourceNode, osg::Vec3d(0, 0, 32), 0); // TODO: size auto destinationModule = getSimulation()->getModule(connectionVisualization->destinationModuleId); auto destinationVisualization = networkNodeVisualizer->getNetworkNodeVisualization(getContainingNode(destinationModule)); destinationVisualization->addAnnotation(connectionOsgVisualization->destinationNode, osg::Vec3d(0, 0, 32), 0); // TODO: size } void TransportConnectionOsgVisualizer::removeConnectionVisualization(const TransportConnectionVisualization *connectionVisualization) { TransportConnectionVisualizerBase::removeConnectionVisualization(connectionVisualization); auto connectionOsgVisualization = static_cast<const TransportConnectionOsgVisualization *>(connectionVisualization); auto sourceModule = getSimulation()->getModule(connectionVisualization->sourceModuleId); auto sourceVisualization = networkNodeVisualizer->getNetworkNodeVisualization(getContainingNode(sourceModule)); sourceVisualization->removeAnnotation(connectionOsgVisualization->sourceNode); auto destinationModule = getSimulation()->getModule(connectionVisualization->destinationModuleId); auto destinationVisualization = networkNodeVisualizer->getNetworkNodeVisualization(getContainingNode(destinationModule)); destinationVisualization->removeAnnotation(connectionOsgVisualization->destinationNode); } #endif // ifdef WITH_OSG } // namespace visualizer } // namespace inet
51.828571
218
0.789967
LarryNguyen