lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
C++
lib/src/Core/AnimatedEntity.cpp
emilhornlund/DV1537Project-AlienAdventure
b370e49d259ee722edd6f39c979824280522076a
#include <Core/AnimatedEntity.hpp> #include <Core/Animation.hpp> #include <SFML/Graphics/RenderStates.hpp> #include <SFML/Graphics/RenderTarget.hpp> CGL::AnimatedEntity::AnimatedEntity(const bool paused) : m_animation(nullptr), m_currentFrame(0), m_isPaused(paused) {} CGL::AnimatedEntity::~AnimatedEntity() = default; void CGL::AnimatedEntity::setAnimation(const CGL::Animation &animation) { this->m_animation = &animation; this->setTexture(*this->m_animation->getSpriteSheet()); this->m_currentFrame = 0; this->setFrame(this->m_currentFrame); } void CGL::AnimatedEntity::play() { this->m_isPaused = false; } void CGL::AnimatedEntity::play(const CGL::Animation &animation) { if (this->getAnimation() != &animation) this->setAnimation(animation); this->play(); } void CGL::AnimatedEntity::pause() { this->m_isPaused = true; } void CGL::AnimatedEntity::stop() { this->m_isPaused = true; this->m_currentFrame = 0; this->setFrame(this->m_currentFrame); } const CGL::Animation *CGL::AnimatedEntity::getAnimation() const { return this->m_animation; } const sf::FloatRect CGL::AnimatedEntity::getLocalBounds() const { const auto& rect = this->m_animation->getFrame(this->m_currentFrame); return sf::FloatRect(0.f, 0.f, std::abs(rect.width), std::abs(rect.height)); } const sf::FloatRect CGL::AnimatedEntity::getGlobalBounds() const { return this->getTransform().transformRect(this->getLocalBounds()); } bool CGL::AnimatedEntity::isPlaying() const { return !this->m_isPaused; } void CGL::AnimatedEntity::setFrame(std::size_t newFrame, bool resetTime) { if (this->m_animation) { sf::IntRect rect = this->m_animation->getFrame(newFrame); this->m_vertices[0].position = sf::Vector2f(0.f, 0.f); this->m_vertices[1].position = sf::Vector2f(0.f, static_cast<float>(rect.height)); this->m_vertices[2].position = sf::Vector2f(static_cast<float>(rect.width), static_cast<float>(rect.height)); this->m_vertices[3].position = sf::Vector2f(static_cast<float>(rect.width), 0.f); float left = static_cast<float>(rect.left) + 0.0001f; float right = left + static_cast<float>(rect.width); float top = static_cast<float>(rect.top); float bottom = top + static_cast<float>(rect.height); this->m_vertices[0].texCoords = sf::Vector2f(left, top); this->m_vertices[1].texCoords = sf::Vector2f(left, bottom); this->m_vertices[2].texCoords = sf::Vector2f(right, bottom); this->m_vertices[3].texCoords = sf::Vector2f(right, top); } if (resetTime) { this->m_currentTime = sf::Time::Zero; } } void CGL::AnimatedEntity::update(sf::Time deltaTime) { if (!this->m_isPaused && this->m_animation) { this->m_currentTime += deltaTime; if (this->m_currentTime >= this->m_animation->getFrameTime()) { this->m_currentTime = sf::microseconds(this->m_currentTime.asMicroseconds() % this->m_animation->getFrameTime().asMicroseconds()); if (this->m_currentFrame + 1 < this->m_animation->getSize()) { this->m_currentFrame++; } else { this->m_currentFrame = 0; if (!this->m_animation->isLooped()) { m_isPaused = true; } } this->setFrame(this->m_currentFrame, false); } } } void CGL::AnimatedEntity::setColor(const sf::Color &color) { this->m_vertices[0].color = color; this->m_vertices[1].color = color; this->m_vertices[2].color = color; this->m_vertices[3].color = color; } void CGL::AnimatedEntity::draw(sf::RenderTarget &target, sf::RenderStates states) const { if (this->m_animation) { states.transform *= getTransform(); states.texture = &this->getTexture(); target.draw(this->m_vertices, 4, sf::Quads, states); } }
#include <Core/AnimatedEntity.hpp> #include <Core/Animation.hpp> #include <SFML/Graphics/RenderStates.hpp> #include <SFML/Graphics/RenderTarget.hpp> CGL::AnimatedEntity::AnimatedEntity(const bool paused) : m_animation(nullptr), m_currentFrame(0), m_isPaused(paused) {} CGL::AnimatedEntity::~AnimatedEntity() = default; void CGL::AnimatedEntity::setAnimation(const CGL::Animation &animation) { this->m_animation = &animation; this->setTexture(*this->m_animation->getSpriteSheet()); this->m_currentFrame = 0; this->setFrame(this->m_currentFrame); } void CGL::AnimatedEntity::play() { this->m_isPaused = false; } void CGL::AnimatedEntity::play(const CGL::Animation &animation) { if (this->getAnimation() != &animation) this->setAnimation(animation); this->play(); } void CGL::AnimatedEntity::pause() { this->m_isPaused = true; } void CGL::AnimatedEntity::stop() { this->m_isPaused = true; this->m_currentFrame = 0; this->setFrame(this->m_currentFrame); } const CGL::Animation *CGL::AnimatedEntity::getAnimation() const { return this->m_animation; } const sf::FloatRect CGL::AnimatedEntity::getLocalBounds() const { const auto& rect = this->m_animation->getFrame(this->m_currentFrame); return sf::FloatRect(0.f, 0.f, std::abs(rect.width), std::abs(rect.height)); } const sf::FloatRect CGL::AnimatedEntity::getGlobalBounds() const { return this->getTransform().transformRect(this->getLocalBounds()); } bool CGL::AnimatedEntity::isPlaying() const { return !this->m_isPaused; } void CGL::AnimatedEntity::setFrame(std::size_t newFrame, bool resetTime) { if (this->m_animation) { sf::IntRect rect = this->m_animation->getFrame(newFrame); this->m_vertices[0].position = sf::Vector2f(0.f, 0.f); this->m_vertices[1].position = sf::Vector2f(0.f, static_cast<float>(rect.height)); this->m_vertices[2].position = sf::Vector2f(static_cast<float>(rect.width), static_cast<float>(rect.height)); this->m_vertices[3].position = sf::Vector2f(static_cast<float>(rect.width), 0.f); float left = static_cast<floa
void CGL::AnimatedEntity::update(sf::Time deltaTime) { if (!this->m_isPaused && this->m_animation) { this->m_currentTime += deltaTime; if (this->m_currentTime >= this->m_animation->getFrameTime()) { this->m_currentTime = sf::microseconds(this->m_currentTime.asMicroseconds() % this->m_animation->getFrameTime().asMicroseconds()); if (this->m_currentFrame + 1 < this->m_animation->getSize()) { this->m_currentFrame++; } else { this->m_currentFrame = 0; if (!this->m_animation->isLooped()) { m_isPaused = true; } } this->setFrame(this->m_currentFrame, false); } } } void CGL::AnimatedEntity::setColor(const sf::Color &color) { this->m_vertices[0].color = color; this->m_vertices[1].color = color; this->m_vertices[2].color = color; this->m_vertices[3].color = color; } void CGL::AnimatedEntity::draw(sf::RenderTarget &target, sf::RenderStates states) const { if (this->m_animation) { states.transform *= getTransform(); states.texture = &this->getTexture(); target.draw(this->m_vertices, 4, sf::Quads, states); } }
t>(rect.left) + 0.0001f; float right = left + static_cast<float>(rect.width); float top = static_cast<float>(rect.top); float bottom = top + static_cast<float>(rect.height); this->m_vertices[0].texCoords = sf::Vector2f(left, top); this->m_vertices[1].texCoords = sf::Vector2f(left, bottom); this->m_vertices[2].texCoords = sf::Vector2f(right, bottom); this->m_vertices[3].texCoords = sf::Vector2f(right, top); } if (resetTime) { this->m_currentTime = sf::Time::Zero; } }
function_block-function_prefixed
[ { "content": " class Animation {\n\n private:\n\n sf::Time m_frameTime;\n\n\n\n bool m_isLooped;\n\n\n\n std::vector<sf::IntRect> m_frames;\n\n\n\n const sf::Texture *m_texture;\n\n\n\n Animation(const Animation &original);\n\n\n\n Animation &operator=(const Anima...
C++
NNet/ModelIO/NNetModelImporter.cpp
pk1954/solutions
02cd67fc1e6299e9fe56ce04dce2515d6f30df92
#include "stdafx.h" #include <filesystem> #include <assert.h> #include "ERRHNDL.H" #include "SignalFactory.h" #include "SignalGenerator.h" #include "UPSigGenList.h" #include "Knot.h" #include "Neuron.h" #include "InputConnector.h" #include "OutputConnector.h" #include "MonitorData.h" #include "NobException.h" #include "NNetWrapperHelpers.h" #include "NNetParameters.h" #include "InputLine.h" #include "OutputLine.h" #include "IoLine.h" #include "win32_script.h" #include "win32_thread.h" #include "NNetModelStorage.h" #include "NNetModelImporter.h" #include "ImportTermination.h" #include "WrapCreateNob.h" #include "WrapVoltage.h" #include "WrapperBase.h" using std::filesystem::exists; using std::make_unique; using std::to_wstring; using std::bit_cast; class WrapProtocol : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { script.ScrReadString(L"version"); double dVersion = script.ScrReadFloat(); } }; class WrapDescription : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { wstring const wstrDescription { script.ScrReadString() }; GetWriterInterface().AddDescriptionLine(wstrDescription); } }; class WrapGlobalParameter : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { auto const param(static_cast<ParamType::Value>(script.ScrReadUint())); script.ScrReadSpecial(L'='); float const fValue { Cast2Float(script.ScrReadFloat()) }; GetWriterInterface().SetParam(param, fValue); } }; class WrapNrOfNobs : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { script.ScrReadSpecial(L'='); long lNrOfNobs { script.ScrReadLong() }; GetUPNobsRef().IncreaseSize(lNrOfNobs); } }; class WrapNobParameter : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { script.ScrReadString(L"InputLine"); NobId const id (script.ScrReadLong()); auto const param(static_cast< ParamType::Value >(script.ScrReadUint())); assert(param == ParamType::Value::pulseRate); script.ScrReadSpecial(L'='); Cast2Float(script.ScrReadFloat()); } }; class WrapTriggerSound : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { NobId const id { ScrReadNobId(script) }; Neuron * pNeuron { GetWriterInterface().GetNobPtr<Neuron *>(id) }; Hertz const freq { script.ScrReadUlong() }; script.ScrReadString(L"Hertz"); MilliSecs const msec { script.ScrReadUlong() }; script.ScrReadString(L"msec"); pNeuron->SetTriggerSound(SoundDescr{ true, freq, msec }); } }; class WrapNrOfTracks : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { unsigned int const uiNrOfTracks { script.ScrReadUint() }; for (unsigned int ui = 0; ui < uiNrOfTracks; ++ui) GetMonitorData().InsertTrack(TrackNr(0)); } }; class WrapSignal : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { MicroMeterCircle umCircle; TrackNr trackNr { ScrReadTrackNr(script) }; script.ScrReadString(L"source"); unsigned long ulSigSrc { script.ScrReadUlong() }; if (ulSigSrc == NNetModelStorage::SIGSRC_CIRCLE) { umCircle = ScrReadMicroMeterCircle(script); } else { throw ScriptErrorHandler::ScriptException(999, wstring(L"Signal source type must be 101")); } GetMonitorData().AddSignal(GetUPNobsRef(), trackNr, umCircle); } }; class WrapSetParam : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { NobId const id { ScrReadNobId(script) }; ParamType::Value const param { ScrReadParamType(script) }; float fVal { Cast2Float(script.ScrReadFloat()) }; if (InputConnector * pInpConn { GetWriterInterface().GetNobPtr<InputConnector *>(id) }) { pInpConn->Apply2All ( [param, fVal](IoLine & n) { auto & inputLine { static_cast<InputLine &>(n) }; inputLine.GetSigGen()->SetParam(param, fVal); } ); } else if ( InputLine * pInpNeuron { GetWriterInterface().GetNobPtr<InputLine*>(id) } ) { pInpNeuron->GetSigGen()->SetParam(param, fVal); } } }; class WrapSignalGenerator : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { NNetModelWriterInterface & nmwi { GetWriterInterface() }; wstring const name { script.ScrReadString() }; SigGenStaticData const sigGenData { ScrReadSigGenStaticData(script) }; SigGenId const sigGenId { nmwi.FindSigGen(name) }; if (nmwi.IsValid(sigGenId)) { SignalGenerator * pSigGen { nmwi.GetSigGen(sigGenId) }; pSigGen->SetStaticData(sigGenData); } else { UPSigGen upSigGen { move(nmwi.NewSigGen(name)) }; upSigGen->SetStaticData(sigGenData); nmwi.PushSigGen(move(upSigGen)); } } }; void NNetModelImporter::Initialize() { SymbolTable::ScrDefConst(L"circle", NNetModelStorage::SIGSRC_CIRCLE ); SymbolTable::ScrDefConst(L"Description", new WrapDescription (* this)); SymbolTable::ScrDefConst(L"Protocol", new WrapProtocol (* this)); SymbolTable::ScrDefConst(L"GlobalParameter", new WrapGlobalParameter(* this)); SymbolTable::ScrDefConst(L"NrOfNobs", new WrapNrOfNobs (* this)); SymbolTable::ScrDefConst(L"CreateNob", new WrapCreateNob (* this)); SymbolTable::ScrDefConst(L"NobParameter", new WrapNobParameter (* this)); SymbolTable::ScrDefConst(L"TriggerSound", new WrapTriggerSound (* this)); SymbolTable::ScrDefConst(L"NrOfTracks", new WrapNrOfTracks (* this)); SymbolTable::ScrDefConst(L"Signal", new WrapSignal (* this)); SymbolTable::ScrDefConst(L"SetParam", new WrapSetParam (* this)); SymbolTable::ScrDefConst(L"Voltage", new WrapVoltage (* this)); SymbolTable::ScrDefConst(L"SignalGenerator", new WrapSignalGenerator(* this)); NobType::Apply2All ( [](NobType const & type) { SymbolTable::ScrDefConst ( NobType::GetName(type.GetValue()), static_cast<unsigned long>(type.GetValue()) ); } ); SymbolTable::ScrDefConst(L"inputNeuron", static_cast<unsigned long>(NobType::Value::inputLine)); SymbolTable::ScrDefConst(L"outputNeuron", static_cast<unsigned long>(NobType::Value::outputLine)); ParamType::Apply2AllParameters ( [](ParamType::Value const & param) { SymbolTable::ScrDefConst ( ParamType::GetName(param), static_cast<unsigned long>(param) ); } ); } void NNetModelImporter::importModel() { ImportTermination::Result res; Script script; bool bSuccess { false }; if (! m_wstrFile2Read.empty()) { script.SetEcho(true); try { bSuccess = script.ScrProcess(m_wstrFile2Read); } catch (NobException const & e) { CheckImportedNobId(script, m_ImportedNMWI.GetUPNobs(), e.m_id); } } if (bSuccess) { m_ImportedNMWI.RemoveOrphans(); m_ImportedNMWI.SetModelFilePath(m_wstrFile2Read); m_ImportedNMWI.DescriptionComplete(); res = ImportTermination::Result::ok; } else { m_upImportedModel.release(); res = ImportTermination::Result::errorInFile; } m_upTermination->Reaction(res, m_wstrFile2Read); } void NNetModelImporter::CheckImportedNobId ( Script & script, UPNobList const & list, NobId const id ) { wstring const strNobId { to_wstring(id.GetValue()) }; if (IsUndefined(id)) { script.SetExpectedToken(L"NobId != NO_NOB"); throw ScriptErrorHandler::ScriptException(999, wstring(L"Invalid nob id: ") + strNobId); } else if (! list.IsValidNobId(id)) { script.SetExpectedToken(L"id < " + to_wstring(list.Size())); throw ScriptErrorHandler::ScriptException(999, wstring(L"Invalid nob id: ") + strNobId); } else if (! list.IsNobDefined(id)) { script.SetExpectedToken(L"Defined NobId"); throw ScriptErrorHandler::ScriptException(999, wstring(L"Nob is not defined: ") + strNobId); } }; static unsigned int __stdcall importModelThreadProc(void * data) { SetThreadDescription(GetCurrentThread(), L"ImportModel"); NNetModelImporter * pModelImporter { bit_cast<NNetModelImporter *>(data) }; pModelImporter->importModel(); return 0; } bool NNetModelImporter::Import ( wstring const & wstrPath, unique_ptr<ImportTermination> upTermination ) { if (wstrPath.empty()) return false; if (m_upImportedModel.get()) return false; if (! exists(wstrPath)) { upTermination->Reaction(ImportTermination::Result::fileNotFound, wstrPath); return false; } m_upTermination = move(upTermination); m_upImportedModel = make_unique<NNetModel>(); m_ImportedNMWI.SetModel(m_upImportedModel.get()); m_wstrFile2Read = wstrPath; Util::RunAsAsyncThread(importModelThreadProc, static_cast<void *>(this)); return true; } unique_ptr<NNetModel> NNetModelImporter::GetImportedModel() { return move(m_upImportedModel); }
#include "stdafx.h" #include <filesystem> #include <assert.h> #include "ERRHNDL.H" #include "SignalFactory.h" #include "SignalGenerator.h" #include "UPSigGenList.h" #include "Knot.h" #include "Neuron.h" #include "InputConnector.h" #include "OutputConnector.h" #include "MonitorData.h" #include "NobException.h" #include "NNetWrapperHelpers.h" #include "NNetParameters.h" #include "InputLine.h" #include "OutputLine.h" #include "IoLine.h" #include "win32_script.h" #include "win32_thread.h" #include "NNetModelStorage.h" #include "NNetModelImporter.h" #include "ImportTermination.h" #include "WrapCreateNob.h" #include "WrapVoltage.h" #include "WrapperBase.h" using std::filesystem::exists; using std::make_unique; using std::to_wstring; using std::bit_cast; class WrapProtocol : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { script.ScrReadString(L"version"); double dVersion = script.ScrReadFloat(); } }; class WrapDescription : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { wstring const wstrDescription { script.ScrReadString() }; GetWriterInterface().AddDescriptionLine(wstrDescription); } }; class WrapGlobalParameter : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { auto const param(static_cast<ParamType::Value>(script.ScrReadUint())); script.ScrReadSpecial(L'='); float const fValue { Cast2Float(script.ScrReadFloat()) }; GetWriterInterface().SetParam(param, fValue); } }; class WrapNrOfNobs : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { script.ScrReadSpecial(L'='); long lNrOfNobs { script.ScrReadLong() }; GetUPNobsRef().IncreaseSize(lNrOfNobs); } }; class WrapNobParameter : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { script.ScrReadString(L"InputLine"); NobId const id (script.ScrReadLong()); auto const param(static_cast< ParamType::Value >(script.ScrReadUint())); assert(param == ParamType::Value::pulseRate); script.ScrReadSpecial(L'='); Cast2Float(script.ScrReadFloat()); } }; class WrapTriggerSound : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { NobId const id { ScrReadNobId(script) }; Neuron * pNeuron { GetWriterInterface().GetNobPtr<Neuron *>(id) }; Hertz const freq { script.ScrReadUlong() }; script.ScrReadString(L"Hertz"); MilliSecs const msec { script.ScrReadUlong() }; script.ScrReadString(L"msec"); pNeuron->SetTriggerSound(SoundDescr{ true, freq, msec }); } }; class WrapNrOfTracks : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { unsigned int const uiNrOfTracks { script.ScrReadUint() }; for (unsigned int ui = 0; ui < uiNrOfTracks; ++ui) GetMonitorData().InsertTrack(TrackNr(0)); } }; class WrapSignal : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { MicroMeterCircle umCircle; TrackNr trackNr { ScrReadTrackNr(script) }; script.ScrReadString(L"source"); unsigned long ulSigSrc { script.ScrReadUlong() }; if (ulSigSrc == NNetModelStorage::SIGSRC_CIRCLE) { umCircle = ScrReadMicroMeterCircle(script); } else { throw ScriptErrorHandler::ScriptException(999, wstring(L"Signal source type must be 101")); } GetMonitorData().AddSignal(GetUPNobsRef(), trackNr, umCircle); } }; class WrapSetParam : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { NobId const id { ScrReadNobId(script) }; ParamType::Value const param { ScrReadParamType(script) }; float fVal { Cast2Float(script.ScrReadFloat()) }; if (InputConnector * pInpConn { GetWriterInterface().GetNobPtr<InputConnector *>(id) }) { pInpConn->Apply2All ( [param, fVal](IoLine & n) { auto & inputLine { static_cast<InputLine &>(n) }; inputLine.GetSigGen()->SetParam(param, fVal); } ); } else if ( InputLine * pInpNeuron { GetWriterInterface().GetNobPtr<InputLine*>(id) } ) { pInpNeuron->GetSigGen()->SetParam(param, fVal); } } }; class WrapSignalGenerator : public WrapperBase { public: using WrapperBase::WrapperBase; void operator() (Script & script) const final { NNetModelWriterInterface & nmwi { GetWriterInterface() }; wstring const name { script.ScrReadString() }; SigGenStaticData const sigGenData { ScrReadSigGenStaticData(script) }; SigGenId const sigGenId { nmwi.FindSigGen(name) }; if (nmwi.IsValid(sigGenId)) { SignalGenerator * pSigGen { nmwi.GetSigGen(sigGenId) }; pSigGen->SetStaticData(sigGenData); } else { UPSigGen upSigGen { move(nmwi.NewSigGen(name)) }; upSigGen->SetStaticData(sigGenData); nmwi.PushSigGen(move(upSigGen)); } } }; void NNetModelImporter::Initialize() { SymbolTable::ScrDefConst(L"circle", NNetModelStorage::SIGSRC_CIRCLE ); SymbolTable::ScrDefConst(L"Description", new WrapDescription (* this)); SymbolTable::ScrDefConst(L"Protocol", new WrapProtocol (* this)); SymbolTable::ScrDefConst(L"GlobalParameter", new WrapGlobalParameter(* this)); SymbolTable::ScrDefConst(L"NrOfNobs", new WrapNrOfNobs (* this)); SymbolTable::ScrDefConst(L"CreateNob", new WrapCreateNob (* this)); SymbolTable::ScrDefConst(L"NobParameter", new WrapNobParameter (* this)); SymbolTable::ScrDefConst(L"TriggerSound", new WrapTriggerSound (* this)); SymbolTable::ScrDefConst(L"NrOfTracks", new WrapNrOfTracks (* this)); SymbolTable::ScrDefConst(L"Signal", new WrapSignal (* this)); SymbolTable::ScrDefConst(L"SetParam", new WrapSetParam (* this)); SymbolTable::ScrDefConst(L"Voltage", new WrapVoltage (* this)); SymbolTable::ScrDefConst(L"SignalGenerator", new WrapSignalGenerator(* this)); NobType::Apply2All ( [](NobType const & type) { SymbolTable::ScrDefConst ( NobType::GetName(type.GetValue()), static_cast<unsigned long>(type.GetValue()) ); } ); SymbolTable::ScrDefConst(L"inputNeuron", static_cast<unsigned long>(NobType::Value::inputLine)); SymbolTable::ScrDefConst(L"outputNeuron", static_cast<unsigned long>(NobType::Value::outputLine)); ParamType::Apply2AllParameters ( [](ParamType::Value const & param) {
; } ); } void NNetModelImporter::importModel() { ImportTermination::Result res; Script script; bool bSuccess { false }; if (! m_wstrFile2Read.empty()) { script.SetEcho(true); try { bSuccess = script.ScrProcess(m_wstrFile2Read); } catch (NobException const & e) { CheckImportedNobId(script, m_ImportedNMWI.GetUPNobs(), e.m_id); } } if (bSuccess) { m_ImportedNMWI.RemoveOrphans(); m_ImportedNMWI.SetModelFilePath(m_wstrFile2Read); m_ImportedNMWI.DescriptionComplete(); res = ImportTermination::Result::ok; } else { m_upImportedModel.release(); res = ImportTermination::Result::errorInFile; } m_upTermination->Reaction(res, m_wstrFile2Read); } void NNetModelImporter::CheckImportedNobId ( Script & script, UPNobList const & list, NobId const id ) { wstring const strNobId { to_wstring(id.GetValue()) }; if (IsUndefined(id)) { script.SetExpectedToken(L"NobId != NO_NOB"); throw ScriptErrorHandler::ScriptException(999, wstring(L"Invalid nob id: ") + strNobId); } else if (! list.IsValidNobId(id)) { script.SetExpectedToken(L"id < " + to_wstring(list.Size())); throw ScriptErrorHandler::ScriptException(999, wstring(L"Invalid nob id: ") + strNobId); } else if (! list.IsNobDefined(id)) { script.SetExpectedToken(L"Defined NobId"); throw ScriptErrorHandler::ScriptException(999, wstring(L"Nob is not defined: ") + strNobId); } }; static unsigned int __stdcall importModelThreadProc(void * data) { SetThreadDescription(GetCurrentThread(), L"ImportModel"); NNetModelImporter * pModelImporter { bit_cast<NNetModelImporter *>(data) }; pModelImporter->importModel(); return 0; } bool NNetModelImporter::Import ( wstring const & wstrPath, unique_ptr<ImportTermination> upTermination ) { if (wstrPath.empty()) return false; if (m_upImportedModel.get()) return false; if (! exists(wstrPath)) { upTermination->Reaction(ImportTermination::Result::fileNotFound, wstrPath); return false; } m_upTermination = move(upTermination); m_upImportedModel = make_unique<NNetModel>(); m_ImportedNMWI.SetModel(m_upImportedModel.get()); m_wstrFile2Read = wstrPath; Util::RunAsAsyncThread(importModelThreadProc, static_cast<void *>(this)); return true; } unique_ptr<NNetModel> NNetModelImporter::GetImportedModel() { return move(m_upImportedModel); }
SymbolTable::ScrDefConst ( ParamType::GetName(param), static_cast<unsigned long>(param) )
call_expression
[ { "content": "class Neuron : public BaseKnot\n\n{\n\npublic:\n\n\tNeuron(MicroMeterPnt const &, NobType const = NobType::Value::neuron);\n\n\tNeuron(BaseKnot const &, NobType const = NobType::Value::neuron);\n\n\tNeuron(Neuron const &); // copy constructor\n\n\n\n\tNeuron & operator=(Neuron con...
C++
hpx/runtime/serialization/map.hpp
akemp/hpx
1ddf7282e322c30d82f2be044071aed14807ebe1
#ifndef HPX_SERIALIZATION_MAP_HPP #define HPX_SERIALIZATION_MAP_HPP #include <map> #include <boost/mpl/and.hpp> #include <boost/type_traits/remove_const.hpp> #include <boost/type_traits/add_reference.hpp> #include <hpx/runtime/serialization/input_archive.hpp> #include <hpx/runtime/serialization/output_archive.hpp> #include <hpx/traits/is_bitwise_serializable.hpp> namespace hpx { namespace traits { template <class Key, class Value> struct is_bitwise_serializable<std::pair<Key, Value> >: boost::mpl::and_< is_bitwise_serializable<Key>, is_bitwise_serializable<Value> > {}; } namespace serialization { namespace detail { template <class Key, class Value> void load_pair_impl(input_archive& ar, std::pair<Key, Value>& t, boost::mpl::false_) { ar >> const_cast< typename boost::add_reference< typename boost::remove_const<Key>::type >::type>(t.first); ar >> t.second; } template <class Key, class Value> void load_pair_impl(input_archive& ar, std::pair<Key, Value>& t, boost::mpl::true_) { if (!has_array_optimization(ar)) load_pair_impl(ar, t, boost::mpl::false_()); else load_binary(ar, &t, sizeof(std::pair<Key, Value>)); } template <class Key, class Value> void save_pair_impl(output_archive& ar, std::pair<Key, Value>& t, boost::mpl::false_) { ar << t.first; ar << t.second; } template <class Key, class Value> void save_pair_impl(output_archive& ar, std::pair<Key, Value>& t, boost::mpl::true_) { if (!has_array_optimization(ar)) save_pair_impl(ar, t, boost::mpl::false_()); else save_binary(ar, &t, sizeof(std::pair<Key, Value>)); } } template <class Key, class Value> void serialize(input_archive& ar, std::pair<Key, Value>& t, unsigned) { typedef std::pair<Key, Value> pair_type; typedef typename traits::is_bitwise_serializable<pair_type> optimized; detail::load_pair_impl(ar, t, optimized()); } template <class Key, class Value> void serialize(output_archive& ar, std::pair<Key, Value>& t, unsigned) { typedef std::pair<Key, Value> pair_type; typedef typename traits::is_bitwise_serializable<pair_type> optimized; detail::save_pair_impl(ar, t, optimized()); } template <class Key, class Value, class Comp, class Alloc> void serialize(input_archive& ar, std::map<Key, Value, Comp, Alloc>& t, unsigned) { typedef typename std::map<Key, Value, Comp, Alloc>::size_type size_type; typedef typename std::map<Key, Value, Comp, Alloc>::value_type value_type; size_type size; ar >> size; for (size_type i = 0; i < size; ++i) { value_type v; ar >> v; t.insert(t.end(), v); } } template <class Key, class Value, class Comp, class Alloc> void serialize(output_archive& ar, std::map<Key, Value, Comp, Alloc>& t, unsigned) { typedef typename std::map<Key, Value, Comp, Alloc>::value_type value_type; ar << t.size(); for(value_type& val : t) { ar << val; } } } } #endif
#ifndef HPX_SERIALIZATION_MAP_HPP #define HPX_SERIALIZATION_MAP_HPP #include <map> #include <boost/mpl/and.hpp> #include <boost/type_traits/remove_const.hpp> #include <boost/type_traits/add_reference.hpp> #include <hpx/runtime/serialization/input_archive.hpp> #include <hpx/runtime/serialization/output_archive.hpp> #include <hpx/traits/is_bitwise_serializable.hpp> namespace hpx { namespace traits { template <class Key, class Value> struct is_bitwise_serializable<std::pair<Key, Value> >: boost::mpl::and_< is_bitwise_serializable<Key>, is_bitwise_serializable<Value> > {}; } namespace serialization { namespace detail { template <class Key, class Value> void load_pair_impl(input_archive& ar, std::pair<Key, Value>& t, boost::mpl::false_) { ar >> const_cast< typename boost::add_reference< typename boost::remove_const<Key>::type >::type>(t.first); ar >> t.second; } template <class Key, class Value> void load_pair_impl(input_archive& ar, std::pair<Key, Value>& t, boost::mpl::true_) { if (!has_array_optimization(ar)) load_pair_impl(ar, t, boost::mpl::false_()); else load_binary(ar, &t, sizeof(std::pair<Key, Value>)); } template <class Key, class Value> void save_pair_impl(output_archive& ar, std::pair<Key, Value>& t, boost::mpl::false_) { ar << t.first; ar << t.second; } template <class Key, class Value> void save_pair_impl(output_archive& ar, std::pair<Key, Value>& t, boost::mpl::true_) {
} } template <class Key, class Value> void serialize(input_archive& ar, std::pair<Key, Value>& t, unsigned) { typedef std::pair<Key, Value> pair_type; typedef typename traits::is_bitwise_serializable<pair_type> optimized; detail::load_pair_impl(ar, t, optimized()); } template <class Key, class Value> void serialize(output_archive& ar, std::pair<Key, Value>& t, unsigned) { typedef std::pair<Key, Value> pair_type; typedef typename traits::is_bitwise_serializable<pair_type> optimized; detail::save_pair_impl(ar, t, optimized()); } template <class Key, class Value, class Comp, class Alloc> void serialize(input_archive& ar, std::map<Key, Value, Comp, Alloc>& t, unsigned) { typedef typename std::map<Key, Value, Comp, Alloc>::size_type size_type; typedef typename std::map<Key, Value, Comp, Alloc>::value_type value_type; size_type size; ar >> size; for (size_type i = 0; i < size; ++i) { value_type v; ar >> v; t.insert(t.end(), v); } } template <class Key, class Value, class Comp, class Alloc> void serialize(output_archive& ar, std::map<Key, Value, Comp, Alloc>& t, unsigned) { typedef typename std::map<Key, Value, Comp, Alloc>::value_type value_type; ar << t.size(); for(value_type& val : t) { ar << val; } } } } #endif
if (!has_array_optimization(ar)) save_pair_impl(ar, t, boost::mpl::false_()); else save_binary(ar, &t, sizeof(std::pair<Key, Value>));
if_condition
[ { "content": " class function<Sig, void, void>\n\n : public detail::basic_function<\n\n detail::function_vtable_ptr<Sig, void, void>\n\n , Sig\n\n >\n\n {\n\n typedef detail::function_vtable_ptr<Sig, void, void> vtable_ptr;\n\n typedef detail::basic_function<v...
C++
native-library/src/util_classes/accessor_base.hpp
AVSystem/Anjay-java
c8f8c5e0ac5a086db4ca183155eed07374fc6585
#pragma once #include "../jni_wrapper.hpp" #include <optional> #include <string> #include <type_traits> #include <unordered_map> #include "./exception.hpp" #include "./optional_tag.hpp" namespace utils { namespace detail { template <class T> struct dependent_false : std::false_type {}; template <typename T> struct ArrayTypeExtractor : std::false_type {}; template <typename T> struct ArrayTypeExtractor<T[]> { typedef T type; }; } template <typename Peer> class AccessorBase { protected: jni::JNIEnv &env_; jni::Global<jni::Object<Peer>> instance_; jni::Global<jni::Class<Peer>> class_; AccessorBase(AccessorBase &) = delete; AccessorBase &operator=(AccessorBase &) = delete; template <typename JType> auto get_impl(const char *field_name) { return instance_.Get(env_, class_.template GetField<JType>(env_, field_name)); } template <typename JType, typename T> void set_impl(const char *field_name, const T &value) { instance_.Set(env_, class_.template GetField<JType>(env_, field_name), value); } template <typename R, typename... Args> auto get_method_impl(jni::Method<Peer, R(Args...)> &&method) { return [&, method = std::move(method)](const Args &... args) { return instance_.Call(env_, method, args...); }; } template <typename R, typename... Args> static auto get_static_method_impl(jni::JNIEnv &env, jni::Local<jni::Class<Peer>> &&clazz, jni::StaticMethod<Peer, R(Args...)> &&method) { return [&, clazz = std::move(clazz), method = std::move(method)](const Args &... args) { return clazz.Call(env, method, args...); }; } public: explicit AccessorBase(jni::JNIEnv &env, const jni::Object<Peer> &instance) : env_(env), instance_(jni::NewGlobal(env, instance)), class_(jni::NewGlobal(env, jni::Class<Peer>::Find(env))) {} jni::JNIEnv &get_env() { return env_; } template <typename Signature> auto get_method(const char *name) { return get_method_impl( class_.template GetMethod<Signature>(env_, name)); } template <typename Signature> static auto get_static_method(jni::JNIEnv &env, const char *name) { auto clazz = jni::Class<Peer>::Find(env); auto method = clazz.template GetStaticMethod<Signature>(env, name); return get_static_method_impl(env, std::move(clazz), std::move(method)); } template <typename T> auto get_nullable_value(const char *field_name) { if constexpr (std::is_same<T, std::string>::value) { auto str = get_impl<jni::String>(field_name); if (!str.get()) { return std::optional<std::string>{}; } return std::optional<std::string>{ jni::Make<std::string>(env_, str) }; } else if constexpr (std::is_array<T>::value && std::is_arithmetic< typename detail::ArrayTypeExtractor< T>::type>::value) { using Item = typename detail::ArrayTypeExtractor<T>::type; using RetT = typename std::vector<Item>; auto arr = get_impl<jni::Array<Item>>(field_name); auto vec = jni::Make<RetT>(env_, arr); return std::optional<RetT>{ vec }; } else { static_assert(detail::dependent_false<T>::value, "Not implemented"); } } template <typename T> std::optional<T> get_optional_integer(const char *field_name) { auto value = get_optional_value<jni::IntegerTag>(field_name); if (!value) { return {}; } auto unboxed = jni::Unbox(get_env(), *value); T casted = static_cast<T>(unboxed); if (static_cast<int64_t>(casted) != static_cast<int64_t>(unboxed)) { avs_throw(IllegalArgumentException( env_, std::string{ field_name } + " field has value that is out of range " + std::to_string(std::numeric_limits<T>::min()) + " - " + std::to_string(std::numeric_limits<T>::max()))); } return std::make_optional(casted); } template <typename T> std::optional<std::vector<T>> get_optional_array(const char *field_name) { if constexpr (std::is_arithmetic<T>::value) { auto optional_value = get_impl<jni::Object<OptionalTag>>(field_name); auto accessor = AccessorBase<OptionalTag>{ env_, optional_value }; if (!accessor.template get_method<jni::jboolean()>("isPresent")()) { return {}; } auto object = accessor.template get_method<jni::Object<>()>("get")(); jni::Local<jni::Array<T>> casted{ env_, jni::Cast(env_, jni::Class<jni::ArrayTag<T>>::Find(env_), object) .release() }; std::vector<T> result = jni::Make<std::vector<T>>(env_, casted); return { result }; } else { static_assert(detail::dependent_false<T>::value, "Not implemented"); } } template <typename T> auto get_value(const char *field_name) { if constexpr (std::is_same<T, size_t>::value) { auto value = get_impl<jni::jlong>(field_name); if (value < 0) { avs_throw(IllegalArgumentException( env_, "size_t field " + std::string{ field_name } + " has value that is negative")); } else if (static_cast<uint64_t>(value) > std::numeric_limits<size_t>::max()) { avs_throw(IllegalArgumentException( env_, "size_t field " + std::string{ field_name } + " has value that is too large")); } return static_cast<size_t>(value); } else if constexpr (std::is_same<T, uint16_t>::value) { auto value = get_impl<jni::jint>(field_name); if (value < 0) { avs_throw(IllegalArgumentException( env_, "uint16_t field " + std::string{ field_name } + " has value that is negative")); } else if (static_cast<uint32_t>(value) > std::numeric_limits<uint16_t>::max()) { avs_throw(IllegalArgumentException( env_, "uint16_t field " + std::string{ field_name } + " has value that is too large")); } return static_cast<uint16_t>(value); } else if constexpr (std::is_same<T, bool>::value) { return static_cast<bool>(get_impl<jni::jboolean>(field_name)); } else if constexpr (std::is_same<T, char>::value) { auto value = get_impl<jni::jchar>(field_name); if (value > std::numeric_limits<char>::max()) { avs_throw(IllegalArgumentException( env_, "char field " + std::string{ field_name } + " has value that is too large")); } else if (value < std::numeric_limits<char>::min()) { avs_throw(IllegalArgumentException( env_, "char field " + std::string{ field_name } + " has value that is negative")); } return static_cast<char>(value); } else { return get_impl<T>(field_name); } } template <typename T> auto get_optional_value(const char *field_name) { auto optional_value = get_impl<jni::Object<OptionalTag>>(field_name); auto accessor = AccessorBase<OptionalTag>{ env_, optional_value }; if (!accessor.template get_method<jni::jboolean()>("isPresent")()) { return std::optional<jni::Local<jni::Object<T>>>{}; } auto value = accessor.template get_method<jni::Object<>()>("get")(); auto casted = jni::Cast(env_, jni::Class<T>::Find(env_), value); return std::make_optional(std::move(casted)); } template <typename JavaT, typename NativeT> auto get_enum_value(const char *field_name, const std::unordered_map<std::string, NativeT> &mapping) { struct Enum { static constexpr auto Name() { return "java/lang/Enum"; } }; auto field_value = get_value<jni::Object<JavaT>>(field_name); if (!jni::IsInstanceOf(env_, field_value.get(), *jni::Class<Enum>::Find(env_))) { avs_throw(ClassCastException(env_, "Field " + std::string{ field_name } + " is not a Java Enum")); } auto accessor = AccessorBase<JavaT>{ env_, field_value }; auto value = jni::Make<std::string>( env_, accessor.template get_method<jni::String()>("name")()); auto mapped_to = mapping.find(value); if (mapped_to == mapping.end()) { avs_throw(IllegalArgumentException(env_, "Unsupported enum value: " + value)); } return mapped_to->second; } template <typename T> void set_value(const char *field_name, const T &value) { if constexpr (std::is_same<T, int32_t>::value) { set_impl<jni::jint>(field_name, static_cast<jni::jint>(value)); } else if constexpr (std::is_same<T, int64_t>::value) { set_impl<jni::jlong>(field_name, static_cast<jni::jlong>(value)); } else if constexpr (std::is_same<T, bool>::value) { set_impl<jni::jboolean>(field_name, static_cast<jni::jboolean>(value)); } else if constexpr (std::is_same<T, float>::value) { set_impl<jni::jfloat>(field_name, value); } else if constexpr (std::is_same<T, double>::value) { set_impl<jni::jdouble>(field_name, value); } else if constexpr (std::is_same<T, std::string>::value) { set_impl<jni::String>(field_name, jni::Make<jni::String>(env_, value)); } else { set_impl<jni::Object<T>>(field_name, value.into_object(env_)); } } }; }
#pragma once #include "../jni_wrapper.hpp" #include <optional> #include <string> #include <type_traits> #include <unordered_map> #include "./exception.hpp" #include "./optional_tag.hpp" namespace utils { namespace detail { template <class T> struct dependent_false : std::false_type {}; template <typename T> struct ArrayTypeExtractor : std::false_type {}; template <typename T> struct ArrayTypeExtractor<T[]> { typedef T type; }; } template <typename Peer> class AccessorBase { protected: jni::JNIEnv &env_; jni::Global<jni::Object<Peer>> instance_; jni::Global<jni::Class<Peer>> class_; AccessorBase(AccessorBase &) = delete; AccessorBase &operator=(AccessorBase &) = delete; template <typename JType> auto get_impl(const char *field_name) { return instance_.Get(env_, class_.template GetField<JType>(env_, field_name)); } template <typename JType, typename T> void set_impl(const char *field_name, const T &value) { instance_.Set(env_, class_.template GetField<JType>(env_, field_name), value); } template <typename R, typename... Args> auto get_method_impl(jni::Method<Peer, R(Args...)> &&method) { return [&, method = std::move(method)](const Args &... args) { return instance_.Call(env_, method, args...); }; } template <typename R, typename... Args> static auto get_static_method_impl(jni::JNIEnv &env, jni::Local<jni::Class<Peer>> &&clazz, jni::StaticMethod<Peer, R(Args...)> &&method) { return [&, clazz = std::move(clazz), method = std::move(method)](const Args &... args) { return clazz.Call(env, method, args...); }; } public: explicit AccessorBase(jni::JNIEnv &env, const jni::Object<Peer> &instance) : env_(env), instance_(jni::NewGlobal(env, instance)), class_(jni::NewGlobal(env, jni::Class<Peer>::Find(env))) {} jni::JNIEnv &get_env() { return env_; } template <typename Signature> auto get_method(const char *name) { return get_method_impl( class_.template GetMethod<Signature>(env_, name)); } template <typename Signature> static auto get_static_method(jni::JNIEnv &env, const char *name) { auto clazz = jni::Class<Peer>::Find(env); auto method = clazz.template GetStaticMethod<Signature>(env, name); return get_static_method_impl(env, std::move(clazz), std::move(method)); } template <typename T> auto get_nullable_value(const char *field_name) { if constexpr (std::is_same<T, std::string>::value) { auto str = get_impl<jni::String>(field_name); if (!str.get()) { return std::optional<std::string>{}; } return std::optional<std::string>{ jni::Make<std::string>(env_, str) }; } else if constexpr (std::is_array<T>::value && std::is_arithmetic< typename detail::ArrayTypeExtractor< T>::type>::value) { using Item = typename detail::ArrayTypeExtractor<T>::type; using RetT = typename std::vector<Item>; auto arr = get_impl<jni::Array<Item>>(field_name); auto vec = jni::Make<RetT>(env_, arr); return std::optional<RetT>{ vec }; } else { static_assert(detail::dependent_false<T>::value, "Not implemented"); } } template <typename T> std::optional<T> get_optional_integer(const char *field_name) { auto value = get_optional_value<jni::IntegerTag>(field_name); if (!value) { return {}; } auto unboxed = jni::Unbox(get_env(), *value); T casted = static_cast<T>(unboxed); if (static_cast<int64_t>(casted) != static_cast<int64_t>(unboxed)) { avs_throw(IllegalArgumentException( env_, std::string{ field_name } + " field has value that is out of range " + std::to_string(std::numeric_limits<T>::min()) + " - " + std::to_string(std::numeric_limits<T>::max()))); } return std::make_optional(casted); } template <typename T>
template <typename T> auto get_value(const char *field_name) { if constexpr (std::is_same<T, size_t>::value) { auto value = get_impl<jni::jlong>(field_name); if (value < 0) { avs_throw(IllegalArgumentException( env_, "size_t field " + std::string{ field_name } + " has value that is negative")); } else if (static_cast<uint64_t>(value) > std::numeric_limits<size_t>::max()) { avs_throw(IllegalArgumentException( env_, "size_t field " + std::string{ field_name } + " has value that is too large")); } return static_cast<size_t>(value); } else if constexpr (std::is_same<T, uint16_t>::value) { auto value = get_impl<jni::jint>(field_name); if (value < 0) { avs_throw(IllegalArgumentException( env_, "uint16_t field " + std::string{ field_name } + " has value that is negative")); } else if (static_cast<uint32_t>(value) > std::numeric_limits<uint16_t>::max()) { avs_throw(IllegalArgumentException( env_, "uint16_t field " + std::string{ field_name } + " has value that is too large")); } return static_cast<uint16_t>(value); } else if constexpr (std::is_same<T, bool>::value) { return static_cast<bool>(get_impl<jni::jboolean>(field_name)); } else if constexpr (std::is_same<T, char>::value) { auto value = get_impl<jni::jchar>(field_name); if (value > std::numeric_limits<char>::max()) { avs_throw(IllegalArgumentException( env_, "char field " + std::string{ field_name } + " has value that is too large")); } else if (value < std::numeric_limits<char>::min()) { avs_throw(IllegalArgumentException( env_, "char field " + std::string{ field_name } + " has value that is negative")); } return static_cast<char>(value); } else { return get_impl<T>(field_name); } } template <typename T> auto get_optional_value(const char *field_name) { auto optional_value = get_impl<jni::Object<OptionalTag>>(field_name); auto accessor = AccessorBase<OptionalTag>{ env_, optional_value }; if (!accessor.template get_method<jni::jboolean()>("isPresent")()) { return std::optional<jni::Local<jni::Object<T>>>{}; } auto value = accessor.template get_method<jni::Object<>()>("get")(); auto casted = jni::Cast(env_, jni::Class<T>::Find(env_), value); return std::make_optional(std::move(casted)); } template <typename JavaT, typename NativeT> auto get_enum_value(const char *field_name, const std::unordered_map<std::string, NativeT> &mapping) { struct Enum { static constexpr auto Name() { return "java/lang/Enum"; } }; auto field_value = get_value<jni::Object<JavaT>>(field_name); if (!jni::IsInstanceOf(env_, field_value.get(), *jni::Class<Enum>::Find(env_))) { avs_throw(ClassCastException(env_, "Field " + std::string{ field_name } + " is not a Java Enum")); } auto accessor = AccessorBase<JavaT>{ env_, field_value }; auto value = jni::Make<std::string>( env_, accessor.template get_method<jni::String()>("name")()); auto mapped_to = mapping.find(value); if (mapped_to == mapping.end()) { avs_throw(IllegalArgumentException(env_, "Unsupported enum value: " + value)); } return mapped_to->second; } template <typename T> void set_value(const char *field_name, const T &value) { if constexpr (std::is_same<T, int32_t>::value) { set_impl<jni::jint>(field_name, static_cast<jni::jint>(value)); } else if constexpr (std::is_same<T, int64_t>::value) { set_impl<jni::jlong>(field_name, static_cast<jni::jlong>(value)); } else if constexpr (std::is_same<T, bool>::value) { set_impl<jni::jboolean>(field_name, static_cast<jni::jboolean>(value)); } else if constexpr (std::is_same<T, float>::value) { set_impl<jni::jfloat>(field_name, value); } else if constexpr (std::is_same<T, double>::value) { set_impl<jni::jdouble>(field_name, value); } else if constexpr (std::is_same<T, std::string>::value) { set_impl<jni::String>(field_name, jni::Make<jni::String>(env_, value)); } else { set_impl<jni::Object<T>>(field_name, value.into_object(env_)); } } }; }
std::optional<std::vector<T>> get_optional_array(const char *field_name) { if constexpr (std::is_arithmetic<T>::value) { auto optional_value = get_impl<jni::Object<OptionalTag>>(field_name); auto accessor = AccessorBase<OptionalTag>{ env_, optional_value }; if (!accessor.template get_method<jni::jboolean()>("isPresent")()) { return {}; } auto object = accessor.template get_method<jni::Object<>()>("get")(); jni::Local<jni::Array<T>> casted{ env_, jni::Cast(env_, jni::Class<jni::ArrayTag<T>>::Find(env_), object) .release() }; std::vector<T> result = jni::Make<std::vector<T>>(env_, casted); return { result }; } else { static_assert(detail::dependent_false<T>::value, "Not implemented"); } }
function_block-full_function
[ { "content": "struct ClassCastException : public jni::PendingJavaException {\n\n ClassCastException(JNIEnv &env, const char *str)\n\n : jni::PendingJavaException() {\n\n env.ThrowNew(env.FindClass(\"java/lang/ClassCastException\"), str);\n\n }\n\n\n\n ClassCastException(JNIEnv &env, c...
C++
tools/macpo/tests/integration-tests/itest_harness.cpp
roystgnr/perfexpert
a03b13db9ac83e992e1c5cc3b6e45e52c266fe30
#include <fcntl.h> #include <rose.h> #include <sys/types.h> #include <sys/wait.h> #include <cerrno> #include <fstream> #include <string> #include <vector> #include "generic_defs.h" #include "itest_harness.h" #include "minst.h" bool file_exists(const std::string& filename) { return access(filename.c_str(), F_OK) != -1; } std::string get_src_directory() { return std::string(getenv("srcdir")) + "/tests/integration-tests"; } std::string get_build_directory() { char result[1024]; ssize_t count = readlink("/proc/self/exe", result, 1024); std::string exe_path = std::string(result, (count > 0) ? count : 0); size_t found = exe_path.find_last_of("/"); return exe_path.substr(0, found); } std::string get_tests_directory() { return get_src_directory() + "/test-files"; } std::string instrument_and_link(std::string input_file, string_list_t* special_args, options_t& options) { assert(file_exists(input_file) == true); std::string output_file = std::tmpnam(NULL); string_list_t args; populate_args(args, input_file, output_file, special_args); print_args(args); int pid; switch ((pid = fork())) { default: siginfo_t siginfo; waitid(P_PID, pid, &siginfo, WEXITED | WSTOPPED); break; case 0: { SgProject* project = frontend(args); assert(midend(project, options) == true); assert(backend(project) == 0); delete project; exit(0); } break; case -1: const char* err_msg = strerror(errno); std::cerr << "Failed to spawn child process: " << err_msg << "." << std::endl; break; } return output_file; } bool verify_output(std::string& filename, std::string& binary) { std::string program_output = get_process_stderr(binary); std::string file_contents = get_file_contents(filename); #if 0 std::cout << "program output: " << program_output << std::endl; #endif string_list_t prog_line_list, file_line_list; split(program_output, '\n', prog_line_list); split(file_contents, '\n', file_line_list); size_t file_lines = file_line_list.size(); size_t prog_lines = prog_line_list.size(); if (file_lines == 0 && prog_lines == 0) { return true; } if (file_lines < prog_lines) { std::cout << "File contents smaller than program output: " << file_lines << " v/s " << prog_lines << "!" << std::endl; return false; } size_t ctr = 0; std::string expected_prefix = "[macpo-integration-test]:"; for (string_list_t::iterator it = prog_line_list.begin(); it != prog_line_list.end(); it++) { std::string prog_line = *it; if (prog_line.compare(0, expected_prefix.size(), expected_prefix) == 0) { string_list_t prog_field_list; split(prog_line, ':', prog_field_list); while (ctr < file_lines) { std::string file_line = file_line_list[ctr]; if (file_line.compare(0, expected_prefix.size(), expected_prefix) == 0) break; ctr += 1; } if (ctr == file_lines) { std::cout << "Expected output has fewer test strings than " "program output, was expecting: " << prog_line << std::endl; return false; } string_list_t file_field_list; std::string file_line = file_line_list[ctr]; split(file_line, ':', file_field_list); ctr += 1; size_t prog_fields = prog_field_list.size(); size_t file_fields = file_field_list.size(); assert(prog_fields >= 2); assert(file_fields >= 2); if (prog_fields != file_fields) { std::cout << "Field length mismatch between program output and " "expected output: " << prog_line << " v/s " << file_line << "!" << std::endl; return false; } for (int i = 1; i < prog_fields; i++) { if (prog_field_list[i] != file_field_list[i] && file_field_list[i] != "?") { std::cout << "Field mismatch between program output and " "expected output: " << prog_field_list[i] << " v/s " << file_field_list[i] << "!" << std::endl; return false; } } } } if (ctr >= file_lines || (ctr < file_lines && file_line_list[ctr].compare(0, expected_prefix.size(), expected_prefix) != 0)) { return true; } std::cout << "Remaining entries in expected output, starting with: " << file_line_list[ctr] << "!" << std::endl; return false; } static void print_args(const string_list_t& args) { std::cout << mprefix << "running command:"; for (string_list_t::const_iterator it = args.begin(); it != args.end(); it++) { const std::string& argument = *it; std::cout << " " << argument; } std::cout << std::endl; } static void populate_args(string_list_t& args, std::string& input_file, std::string& output_file, string_list_t* special_args) { args.push_back("cc"); args.push_back(input_file); args.push_back("-o"); args.push_back(output_file); args.push_back("-lstdc++"); std::string mock_include_path = get_src_directory() + "/../libmrt"; args.push_back("-I" + mock_include_path); args.push_back(get_build_directory() + "/mrt.o"); if (special_args) { args.insert(args.end(), special_args->begin(), special_args->end()); } } static std::string get_process_stderr(std::string& binary_name) { int err_pipe[2]; pipe(err_pipe); char arg0[1024]; snprintf(arg0, sizeof(arg0), "%s", binary_name.c_str()); char *args[] = { arg0, NULL }; switch (fork()) { case -1: return ""; case 0: close(err_pipe[0]); if (dup2(err_pipe[1], 1) < 0) { perror("Could not duplicate descriptor"); exit(-1); } if (dup2(err_pipe[1], 2) < 0) { perror("Could not duplicate descriptor"); exit(1); } if (execv(arg0, args) == -1) { std::cout << "Could not execute binary file: " << binary_name << std::endl; perror("execv"); exit(2); } close(err_pipe[1]); exit(0); } wait(NULL); fcntl(err_pipe[0], F_SETFL, O_NONBLOCK | O_ASYNC); const int kLength = 1024; char buffer[kLength]; std::string str_stderr; while (true) { ssize_t read_count = read(err_pipe[0], buffer, kLength-1); if (read_count <= 0 || read_count >= kLength) break; buffer[read_count] = 0; str_stderr += buffer; } close(err_pipe[0]); close(err_pipe[1]); return str_stderr; } static std::string get_file_contents(std::string& filename) { std::string line, contents; std::ifstream fileobj(filename.c_str()); if (fileobj.is_open()) { while (getline(fileobj, line)) contents += line + "\n"; fileobj.close(); } return contents; }
#include <fcntl.h> #include <rose.h> #include <sys/types.h> #include <sys/wait.h> #include <cerrno> #include <fstream> #include <string> #include <vector> #include "generic_defs.h" #include "itest_harness.h" #include "minst.h" bool file_exists(const std::string& filename) { return access(filename.c_str(), F_OK) != -1; } std::string get_src_directory() { return std::string(getenv("srcdir")) + "/tests/integration-tests"; } std::string get_build_directory() { char result[1024]; ssize_t count = readlink("/proc/self/exe", result, 1024); std::string exe_path = std::string(result, (count > 0) ? count : 0); size_t found = exe_path.find_last_of("/"); return exe_path.substr(0, found); } std::string get_tests_directory() { return get_src_directory() + "/test-files"; } std::string instrument_and_link(std::string input_file, string_list_t* special_args, options_t& options) { assert(file_exists(input_file) == true); std::string output_file = std::tmpnam(NULL); string_list_t args; populate_args(args, input_file, output_file, special_args); print_args(args); int pid; switch ((pid = fork())) { default: siginfo_t siginfo; waitid(P_PID, pid, &siginfo, WEXITED | WSTOPPED); break; case 0: { SgProject* project = frontend(args); assert(midend(project, options) == true); assert(backend(project) == 0); delete project; exit(0); } break; case -1: const char* err_msg = strerror(errno); std::cerr << "Failed to spawn child process: " << err_msg << "." << std::endl; break; } return output_file; } bool verify_output(std::string& filename, std::string& binary) { std::string program_output = get_process_stderr(binary); std::string file_contents = get_file_contents(filename); #if 0 std::cout << "program output: " << program_output << std::endl; #endif string_list_t prog_line_list, file_line_list; split(program_output, '\n', prog_line_list); split(file_contents, '\n', file_line_list); size_t file_lines = file_line_list.size(); size_t prog_lines = prog_line_list.size(); if (file_lines == 0 && prog_lines == 0) { return true; } if (file_lines < prog_lines) { std::cout << "File contents smaller than program output: " << file_lines << " v/s " << prog_lines << "!" << std::endl; return false; } size_t ctr = 0; std::string expected_prefix = "[macpo-integration-test]:"; for (string_list_t::iterator it = prog_line_list.begin(); it != prog_line_list.end(); it++) { std::string prog_line = *it; if (prog_line.compare(0, expected_prefix.size(), expected_prefix) == 0) { string_list_t prog_field_list; split(prog_line, ':', prog_field_list); while (ctr < file_lines) { std::string file_line = file_line_list[ctr]; if (file_line.compare(0, expected_prefix.size(), expected_prefix) == 0) break; ctr += 1; } if (ctr == file_lines) { std::cout << "Expected output has fewer test strings than " "program output, was expecting: " << prog_line << std::endl; return false; } string_list_t file_field_list; std::string file_line = file_line_list[ctr]; split(file_line, ':', file_field_list); ctr += 1; size_t prog_fields = prog_field_list.size(); size_t file_fields = file_field_list.size(); assert(prog_fields >= 2); assert(file_fields >= 2); if (prog_fields != file_fields) { std::cout << "Field length mismatch between program output and " "expected output: " << prog_line << " v/s " << file_line << "!" << std::endl; return false; } for (int i = 1; i < prog_fields; i++) { if (prog_field_list[i] != file_field_list[i] && file_field_list[i] != "?") { std::cout << "Field mismatch between program output and " "expected output: " << prog_field_list[i] << " v/s " << file_field_list[i] << "!" << std::endl; return false; } } } } if (ctr >= file_lines || (ctr < file_lines && file_line_list[ctr].compare(0, expected_prefix.size(), expected_prefix) != 0)) { return true; } std::cout << "Remaining entries in expected output, starting with: " << file_line_list[ctr] << "!" << std::endl; return false; } static void print_args(const string_list_t& args) { std::cout << mprefix << "running command:"; for (string_list_t::const_iterator it = args.begin(); it != args.end(); it++) { const std::string& argument = *it; std::cout << " " << argument; } std::cout << std::endl; } static void populate_args(string_list_t& args, std::string& in
.push_back("-o"); args.push_back(output_file); args.push_back("-lstdc++"); std::string mock_include_path = get_src_directory() + "/../libmrt"; args.push_back("-I" + mock_include_path); args.push_back(get_build_directory() + "/mrt.o"); if (special_args) { args.insert(args.end(), special_args->begin(), special_args->end()); } } static std::string get_process_stderr(std::string& binary_name) { int err_pipe[2]; pipe(err_pipe); char arg0[1024]; snprintf(arg0, sizeof(arg0), "%s", binary_name.c_str()); char *args[] = { arg0, NULL }; switch (fork()) { case -1: return ""; case 0: close(err_pipe[0]); if (dup2(err_pipe[1], 1) < 0) { perror("Could not duplicate descriptor"); exit(-1); } if (dup2(err_pipe[1], 2) < 0) { perror("Could not duplicate descriptor"); exit(1); } if (execv(arg0, args) == -1) { std::cout << "Could not execute binary file: " << binary_name << std::endl; perror("execv"); exit(2); } close(err_pipe[1]); exit(0); } wait(NULL); fcntl(err_pipe[0], F_SETFL, O_NONBLOCK | O_ASYNC); const int kLength = 1024; char buffer[kLength]; std::string str_stderr; while (true) { ssize_t read_count = read(err_pipe[0], buffer, kLength-1); if (read_count <= 0 || read_count >= kLength) break; buffer[read_count] = 0; str_stderr += buffer; } close(err_pipe[0]); close(err_pipe[1]); return str_stderr; } static std::string get_file_contents(std::string& filename) { std::string line, contents; std::ifstream fileobj(filename.c_str()); if (fileobj.is_open()) { while (getline(fileobj, line)) contents += line + "\n"; fileobj.close(); } return contents; }
put_file, std::string& output_file, string_list_t* special_args) { args.push_back("cc"); args.push_back(input_file); args
random
[ { "content": "class FooTest : public ::testing::TestWithParam<const char*> {\n\n // You can implement all the usual class fixture members here.\n\n};\n\n\n\n// Then, use the TEST_P macro to define as many parameterized tests\n\n// for this fixture as you want. The _P suffix is for \"parameterized\"\n\n// or \"...
C++
Common/Loader/ssloader_sspj.cpp
SpriteStudio/SpriteStudio6-SDK
f2ad84c8e3ca9d189904da9c3d1114bb4044eecb
#include "ssloader_sspj.h" #include "ssloader_ssae.h" #include "ssloader_ssce.h" #include "ssloader_ssee.h" #include "ssloader_ssqe.h" #include "ssstring_uty.h" #include "../Helper/DebugPrint.h" #include "sscharconverter.h" namespace spritestudio6 { SsString SsProject::getSsceBasepath(){ return getFullPath( m_proj_filepath , settings.cellMapBaseDirectory ); } SsString SsProject::getSsaeBasepath() { return getFullPath( m_proj_filepath , settings.animeBaseDirectory ); } SsString SsProject::getSseeBasepath() { return getFullPath( m_proj_filepath , settings.effectBaseDirectory); } SsString SsProject::getSsqeBasepath() { return getFullPath( m_proj_filepath , settings.animeBaseDirectory ); } SsString SsProject::getImageBasepath() { return getFullPath( m_proj_filepath , settings.imageBaseDirectory ); } SsProject::~SsProject() { for ( SsAnimePackListItr itr = animeList.begin() ; itr != animeList.end() ; itr ++ ) itr->reset(); animeList.clear(); for ( SsSsCellMapList::iterator itr = cellmapList.begin() ; itr != cellmapList.end() ; itr ++ ) itr->reset(); cellmapList.clear(); for ( SsEffectFileList::iterator itr = effectfileList.begin() ; itr != effectfileList.end() ; itr ++ ) itr->reset(); effectfileList.clear(); for ( SsSequencePackList::iterator itr = sequenceList.begin() ; itr != sequenceList.end() ; itr ++ ) itr->reset(); sequenceList.clear(); cellmapNames.clear(); animepackNames.clear(); effectFileNames.clear(); textureList.clear(); sequencepackNames.clear(); } SsAnimePack* SsProject::findAnimationPack( SsString& animePackName ) { SsAnimePack* anime; for ( SsAnimePackListItr itr = animeList.begin() ; itr != animeList.end() ; ++itr ) { anime = itr->get(); if ( anime->name == animePackName ) { return anime; } } return 0; } SsAnimation* SsProject::findAnimation( SsString& animePackName , SsString& AnimeName ) { SsAnimePack* p = findAnimationPack( animePackName ); if ( p ) { return p->findAnimation(AnimeName); } return 0; } SsEffectFile* SsProject::findEffect( SsString& effectName ) { SsEffectFile* effect; for ( SsEffectFileListItr itr = effectfileList.begin() ; itr != effectfileList.end() ; ++itr ) { effect = itr->get(); if ( effect->name == effectName ) { return effect; } } return 0; } SsSequencePack* SsProject::findSequencePack( SsString& sequencePackName ) { SsSequencePack* sequence; for ( SsSequencePackListItr itr = sequenceList.begin() ; itr != sequenceList.end() ; ++itr ) { sequence = itr->get(); if ( sequence->name == sequencePackName ) { return sequence; } } return 0; } SsSequence* SsProject::findSequence( SsString& sequencePackName , SsString& SequenceName ) { SsSequencePack* p = findSequencePack( sequencePackName ); if ( p ) { return p->findSequence(SequenceName); } return 0; } SsProject* ssloader_sspj::Load(const std::string& filename ) { libXML::XMLDocument xml; std::string filenameSSPJ = SsCharConverter::convert_path_string( filename ); if ( libXML::XML_SUCCESS == xml.LoadFile( filenameSSPJ.c_str() ) ) { SsXmlIArchiver ar( xml.GetDocument() , "SpriteStudioProject" ); SsProject* proj = new SsProject(); proj->__Serialize( &ar ); std::string project_filepath = path2dir( filename ); proj->setFilepath( project_filepath ); if ( checkFileVersion(proj->version, SPRITESTUDIO6_SSPJVERSION) == false ) { DEBUG_PRINTF("Project load error : %s", project_filepath.c_str()); DEBUG_PRINTF("sspj old version"); delete proj; return 0; } for ( size_t i = 0 ;i < proj->getAnimePackNum() ; i++ ) { SsString ssaepath = SsCharConverter::convert_path_string(proj->getAnimePackFilePath(i)); SsAnimePack* anime = ssloader_ssae::Load( ssaepath ); if ( ( anime ) && ( checkFileVersion(anime->version, SPRITESTUDIO6_SSAEVERSION) == true ) ) { proj->animeList.push_back( std::move( std::unique_ptr<SsAnimePack>( anime ) ) ); }else{ DEBUG_PRINTF( "Animation load error : %s" , ssaepath.c_str() ); DEBUG_PRINTF( "ssae old version" ); if ( anime ) delete anime; delete proj; return 0; } } std::map<std::string, std::string> textures; for ( size_t i = 0 ;i < proj->getCellMapNum() ; i++ ) { SsString sscepath = SsCharConverter::convert_path_string(proj->getCellMapFilePath(i)); SsCellMap* cell = ssloader_ssce::Load( sscepath ); cell->loadFilepath = proj->getCelMapFileOriginalPath(i); proj->cellmapList.push_back( std::move( std::unique_ptr<SsCellMap>( cell ) ) ); textures[cell->imagePath] = sscepath; } proj->textureList.clear(); for (auto i = textures.begin(); i != textures.end(); i++) { proj->textureList.push_back(i->first); } for ( size_t i = 0 ;i < proj->getEffectFileNum() ; i++ ) { SsString sscepath = SsCharConverter::convert_path_string(proj->getEffectFilePath(i)); SsEffectFile* efile = ssloader_ssee::Load( sscepath ); ssloader_ssee::loadPostProcessing( efile, proj ); proj->effectfileList.push_back( std::move( std::unique_ptr<SsEffectFile>( efile ) ) ); } for ( size_t i = 0 ;i < proj->getSequencePackNum() ; i++ ) { SsString ssqepath = SsCharConverter::convert_path_string(proj->getSequencePackFilePath(i)); SsSequencePack* sequence = ssloader_ssqe::Load( ssqepath ); if ( ( sequence ) && ( checkFileVersion( sequence->version, SPRITESTUDIO6_SSQEVERSION) == true ) ) { proj->sequenceList.push_back( std::move( std::unique_ptr<SsSequencePack>( sequence ) ) ); }else{ DEBUG_PRINTF( "Sequence load error : %s" , ssqepath.c_str() ); DEBUG_PRINTF( "ssqe old version" ); if ( sequence ) delete sequence; delete proj; return 0; } } return proj; } return 0; } SsCellMap* SsProject::findCellMap( SsString& str ) { for ( SsSsCellMapListItr itr = cellmapList.begin() ; itr != cellmapList.end() ; itr ++) { SsCellMap* cellmap = itr->get(); SsString _name = cellmap->loadFilepath; if ( _name == str ) { return cellmap; } } return 0; } }
#include "ssloader_sspj.h" #include "ssloader_ssae.h" #include "ssloader_ssce.h" #include "ssloader_ssee.h" #include "ssloader_ssqe.h" #include "ssstring_uty.h" #include "../Helper/DebugPrint.h" #include "sscharconverter.h" namespace spritestudio6 { SsString SsProject::getSsceBasepath(){ return getFullPath( m_proj_filepath , settings.cellMapBaseDirectory ); } SsString SsProject::getSsaeBasepath() { return getFullPath( m_proj_filepath , settings.animeBaseDirectory ); } SsString SsProject::getSseeBasepath() { return getFullPath( m_proj_filepath , settings.effectBaseDirectory); } SsString SsProject::getSsqeBasepath() { return get
rsion" ); if ( anime ) delete anime; delete proj; return 0; } } std::map<std::string, std::string> textures; for ( size_t i = 0 ;i < proj->getCellMapNum() ; i++ ) { SsString sscepath = SsCharConverter::convert_path_string(proj->getCellMapFilePath(i)); SsCellMap* cell = ssloader_ssce::Load( sscepath ); cell->loadFilepath = proj->getCelMapFileOriginalPath(i); proj->cellmapList.push_back( std::move( std::unique_ptr<SsCellMap>( cell ) ) ); textures[cell->imagePath] = sscepath; } proj->textureList.clear(); for (auto i = textures.begin(); i != textures.end(); i++) { proj->textureList.push_back(i->first); } for ( size_t i = 0 ;i < proj->getEffectFileNum() ; i++ ) { SsString sscepath = SsCharConverter::convert_path_string(proj->getEffectFilePath(i)); SsEffectFile* efile = ssloader_ssee::Load( sscepath ); ssloader_ssee::loadPostProcessing( efile, proj ); proj->effectfileList.push_back( std::move( std::unique_ptr<SsEffectFile>( efile ) ) ); } for ( size_t i = 0 ;i < proj->getSequencePackNum() ; i++ ) { SsString ssqepath = SsCharConverter::convert_path_string(proj->getSequencePackFilePath(i)); SsSequencePack* sequence = ssloader_ssqe::Load( ssqepath ); if ( ( sequence ) && ( checkFileVersion( sequence->version, SPRITESTUDIO6_SSQEVERSION) == true ) ) { proj->sequenceList.push_back( std::move( std::unique_ptr<SsSequencePack>( sequence ) ) ); }else{ DEBUG_PRINTF( "Sequence load error : %s" , ssqepath.c_str() ); DEBUG_PRINTF( "ssqe old version" ); if ( sequence ) delete sequence; delete proj; return 0; } } return proj; } return 0; } SsCellMap* SsProject::findCellMap( SsString& str ) { for ( SsSsCellMapListItr itr = cellmapList.begin() ; itr != cellmapList.end() ; itr ++) { SsCellMap* cellmap = itr->get(); SsString _name = cellmap->loadFilepath; if ( _name == str ) { return cellmap; } } return 0; } }
FullPath( m_proj_filepath , settings.animeBaseDirectory ); } SsString SsProject::getImageBasepath() { return getFullPath( m_proj_filepath , settings.imageBaseDirectory ); } SsProject::~SsProject() { for ( SsAnimePackListItr itr = animeList.begin() ; itr != animeList.end() ; itr ++ ) itr->reset(); animeList.clear(); for ( SsSsCellMapList::iterator itr = cellmapList.begin() ; itr != cellmapList.end() ; itr ++ ) itr->reset(); cellmapList.clear(); for ( SsEffectFileList::iterator itr = effectfileList.begin() ; itr != effectfileList.end() ; itr ++ ) itr->reset(); effectfileList.clear(); for ( SsSequencePackList::iterator itr = sequenceList.begin() ; itr != sequenceList.end() ; itr ++ ) itr->reset(); sequenceList.clear(); cellmapNames.clear(); animepackNames.clear(); effectFileNames.clear(); textureList.clear(); sequencepackNames.clear(); } SsAnimePack* SsProject::findAnimationPack( SsString& animePackName ) { SsAnimePack* anime; for ( SsAnimePackListItr itr = animeList.begin() ; itr != animeList.end() ; ++itr ) { anime = itr->get(); if ( anime->name == animePackName ) { return anime; } } return 0; } SsAnimation* SsProject::findAnimation( SsString& animePackName , SsString& AnimeName ) { SsAnimePack* p = findAnimationPack( animePackName ); if ( p ) { return p->findAnimation(AnimeName); } return 0; } SsEffectFile* SsProject::findEffect( SsString& effectName ) { SsEffectFile* effect; for ( SsEffectFileListItr itr = effectfileList.begin() ; itr != effectfileList.end() ; ++itr ) { effect = itr->get(); if ( effect->name == effectName ) { return effect; } } return 0; } SsSequencePack* SsProject::findSequencePack( SsString& sequencePackName ) { SsSequencePack* sequence; for ( SsSequencePackListItr itr = sequenceList.begin() ; itr != sequenceList.end() ; ++itr ) { sequence = itr->get(); if ( sequence->name == sequencePackName ) { return sequence; } } return 0; } SsSequence* SsProject::findSequence( SsString& sequencePackName , SsString& SequenceName ) { SsSequencePack* p = findSequencePack( sequencePackName ); if ( p ) { return p->findSequence(SequenceName); } return 0; } SsProject* ssloader_sspj::Load(const std::string& filename ) { libXML::XMLDocument xml; std::string filenameSSPJ = SsCharConverter::convert_path_string( filename ); if ( libXML::XML_SUCCESS == xml.LoadFile( filenameSSPJ.c_str() ) ) { SsXmlIArchiver ar( xml.GetDocument() , "SpriteStudioProject" ); SsProject* proj = new SsProject(); proj->__Serialize( &ar ); std::string project_filepath = path2dir( filename ); proj->setFilepath( project_filepath ); if ( checkFileVersion(proj->version, SPRITESTUDIO6_SSPJVERSION) == false ) { DEBUG_PRINTF("Project load error : %s", project_filepath.c_str()); DEBUG_PRINTF("sspj old version"); delete proj; return 0; } for ( size_t i = 0 ;i < proj->getAnimePackNum() ; i++ ) { SsString ssaepath = SsCharConverter::convert_path_string(proj->getAnimePackFilePath(i)); SsAnimePack* anime = ssloader_ssae::Load( ssaepath ); if ( ( anime ) && ( checkFileVersion(anime->version, SPRITESTUDIO6_SSAEVERSION) == true ) ) { proj->animeList.push_back( std::move( std::unique_ptr<SsAnimePack>( anime ) ) ); }else{ DEBUG_PRINTF( "Animation load error : %s" , ssaepath.c_str() ); DEBUG_PRINTF( "ssae old ve
random
[ { "content": "namespace spritestudio6\n\n{\n\n\n\n\n", "file_path": "Common/Animator/ssplayer_types.h", "rank": 0, "score": 87211.16099266979 }, { "content": "namespace spritestudio6\n\n{\n\n\n\n\tconstexpr auto __PI__ = (3.14159265358979323846f);\n\n\t// #define RadianToDegree(Radian) ((dou...
C++
lib/getTunViaUSocket.cpp
xywzwd/VT-Wireless
ec42e742e2be26310df4b25cef9cea873896890b
#include <stdio.h> #include <string.h> #include <signal.h> #include <stdlib.h> #include <sys/time.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/wait.h> #include <errno.h> #include <unistd.h> #include "crts/debug.h" #include "getTunViaUSocket.hpp" static int checkHaveRead(int fd, long sec, long usec) { fd_set rfds; struct timeval tv = { .tv_sec = sec, .tv_usec = usec }; int ret; FD_ZERO(&rfds); FD_SET(fd, &rfds); ret = select(fd+1, &rfds, 0, 0, &tv); if(ret > 0) return ret; if(ret == -1) ERROR("select(, fd=%d,,) failed", fd); else WARN("read timed out in %lu %sseconds", sec?sec:usec, sec?"":"micro "); return ret; } static inline int recvfd(int &socket) { struct msghdr msg = {0}; char m_buffer[256]; struct iovec io = { .iov_base = m_buffer, .iov_len = sizeof(m_buffer) }; msg.msg_iov = &io; msg.msg_iovlen = 1; char c_buffer[256]; msg.msg_control = c_buffer; msg.msg_controllen = sizeof(c_buffer); errno = 0; INFO("Calling recvmsg(fd=%d,,,)", socket); if(recvmsg(socket, &msg, 0) < 0) { close(socket); socket = -1; ERROR("Failed to receive file descriptor message"); return -1; } struct cmsghdr * cmsg = CMSG_FIRSTHDR(&msg); unsigned char * data = CMSG_DATA(cmsg); int fd = *((int*) data); INFO("Got from UNIX Socket TUN fd=%d", fd); close(socket); if((fd = dup2(fd, socket)) != socket) { ERROR("dup2() failed"); close(fd); socket = -1; return -1; } socket = -1; INFO("Got TUN duped to fd=%d", fd); return fd; } static inline char *getPathTo_CRTS_mkTUN(void) { const char *mkTUN = "crts_mkTUN"; const size_t addSuffixLen = strlen(mkTUN) + 1; const size_t inc = 128; size_t bufLen = 128; char *buf = (char *) malloc(bufLen); ASSERT(buf, "malloc() failed"); ssize_t rl = readlink("/proc/self/exe", buf, bufLen); ASSERT(rl > 0, "readlink(\"/proc/self/exe\",,) failed"); while( ((size_t) rl) + addSuffixLen >= bufLen) { DASSERT(bufLen < 1024*1024, ""); buf = (char *) realloc(buf, bufLen += inc); ASSERT(buf, "realloc() failed"); rl = readlink("/proc/self/exe", buf, bufLen); ASSERT(rl > 0, "readlink(\"/proc/self/exe\",,) failed"); } buf[rl] = '\0'; --rl; while(rl > 3 && buf[rl] != '/') --rl; ASSERT(buf[rl] == '/', ""); ++rl; strcpy(&buf[rl], mkTUN); return buf; } bool checkSubnetAddress(const char *subnet) { unsigned long val; size_t len = strlen(subnet); const char *s = subnet; if(len > 18 || len < 10) goto fail; if(subnet[len-3] != '/') goto fail; errno = 0; val = strtoul(&subnet[len-2], 0, 10); if(errno || val > 31 || val < 24) goto fail; for(int i=0; i<3; ++i) { val = strtoul(s, 0, 10); if(errno || val > 255) goto fail; while(*s && *s != '.') ++s; if(! *s) goto fail; ++s; } val = strtoul(s, 0, 10); if(errno || val > 255) goto fail; return false; fail: ERROR("\"%s\" is not a safe subnet address\n" "Try something like: \"10.0.0.0/24\"", subnet); return true; } int getTunViaUSocket(const char *subnet) { if(checkSubnetAddress(subnet)) return -1; INFO("Making TUN with subnet \"%s\"", subnet); int sv[2] = { -1, -1 }; int tunFd = -1; pid_t pid = -1; int status = 0; int ret; errno = 0; ret = socketpair(AF_UNIX, SOCK_DGRAM, 0, sv); if(ret) { ERROR("socketpair(AF_UNIX, SOCK_DGRAM, 0,) failed"); goto fail; } DASSERT(sv[0] > -1 && sv[1] > -1, ""); pid = fork(); if(pid < 0) { ERROR("fork() failed"); goto fail; } if(pid == 0) { close(sv[0]); errno = 0; if(1 != dup2(sv[1], 1)) { ERROR("dup2(fd=%d, 0) failed", sv[1]); exit(1); } char *mkTUN = getPathTo_CRTS_mkTUN(); execl(mkTUN, mkTUN, subnet, 0); ERROR("exec(\"%s\", \"%s\", 0) failed", mkTUN, subnet); exit(1); } close(sv[1]); sv[1] = -1; ret = waitpid(pid, &status, 0); if(ret == -1) { ERROR("waitpid(pid=%u,,) failed", pid); goto fail; } INFO("wait(pid=%u,,) returned status=%d", pid, status); if((ret = checkHaveRead(sv[0], 0, 100)) > 0) tunFd = recvfd(sv[0]); return tunFd; fail: if(pid != -1) kill(pid, SIGTERM); if(sv[0] > -1) close(sv[0]); if(sv[1] > -1) close(sv[0]); return -1; }
#include <stdio.h> #include <string.h> #include <signal.h> #include <stdlib.h> #include <sys/time.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/wait.h> #include <errno.h> #include <unistd.h> #include "crts/debug.h" #include "getTunViaUSocket.hpp" static int checkHaveRead(int fd, long sec, long usec) { fd_set rfds; struct timeval tv = { .tv_sec = sec, .tv_usec = usec }; int ret; FD_ZERO(&rfds); FD_SET(fd, &rfds); ret = select(fd+1, &rfds, 0, 0, &tv); if(ret > 0) return ret; if(ret == -1) ERROR("select(, fd=%d,,) failed", fd); else WARN("read timed out in %lu %sseconds", sec?sec:usec, sec?"":"micro "); return ret; } static inline int recvfd(int &socket) { struct msghdr msg = {0}; char m_buffer[256]; struct iovec io = { .iov_base = m_buffer, .iov_len = sizeof(m_buffer) }; msg.msg_iov = &io; msg.msg_iovlen = 1; char c_buffer[256]; msg.msg_control = c_buffer; msg.msg_controllen = sizeof(c_buffer); errno = 0; INFO("Calling recvmsg(fd=%d,,,)", socket); if(recvmsg(socket, &msg, 0) < 0) { close(socket); socket = -1; ERROR("Failed to receive file descriptor message"); return -1; } struct cmsghdr * cmsg = CMSG_FIRSTHDR(&msg); unsigned char * data = CMSG_DATA(cmsg
et); const char *s = subnet; if(len > 18 || len < 10) goto fail; if(subnet[len-3] != '/') goto fail; errno = 0; val = strtoul(&subnet[len-2], 0, 10); if(errno || val > 31 || val < 24) goto fail; for(int i=0; i<3; ++i) { val = strtoul(s, 0, 10); if(errno || val > 255) goto fail; while(*s && *s != '.') ++s; if(! *s) goto fail; ++s; } val = strtoul(s, 0, 10); if(errno || val > 255) goto fail; return false; fail: ERROR("\"%s\" is not a safe subnet address\n" "Try something like: \"10.0.0.0/24\"", subnet); return true; } int getTunViaUSocket(const char *subnet) { if(checkSubnetAddress(subnet)) return -1; INFO("Making TUN with subnet \"%s\"", subnet); int sv[2] = { -1, -1 }; int tunFd = -1; pid_t pid = -1; int status = 0; int ret; errno = 0; ret = socketpair(AF_UNIX, SOCK_DGRAM, 0, sv); if(ret) { ERROR("socketpair(AF_UNIX, SOCK_DGRAM, 0,) failed"); goto fail; } DASSERT(sv[0] > -1 && sv[1] > -1, ""); pid = fork(); if(pid < 0) { ERROR("fork() failed"); goto fail; } if(pid == 0) { close(sv[0]); errno = 0; if(1 != dup2(sv[1], 1)) { ERROR("dup2(fd=%d, 0) failed", sv[1]); exit(1); } char *mkTUN = getPathTo_CRTS_mkTUN(); execl(mkTUN, mkTUN, subnet, 0); ERROR("exec(\"%s\", \"%s\", 0) failed", mkTUN, subnet); exit(1); } close(sv[1]); sv[1] = -1; ret = waitpid(pid, &status, 0); if(ret == -1) { ERROR("waitpid(pid=%u,,) failed", pid); goto fail; } INFO("wait(pid=%u,,) returned status=%d", pid, status); if((ret = checkHaveRead(sv[0], 0, 100)) > 0) tunFd = recvfd(sv[0]); return tunFd; fail: if(pid != -1) kill(pid, SIGTERM); if(sv[0] > -1) close(sv[0]); if(sv[1] > -1) close(sv[0]); return -1; }
); int fd = *((int*) data); INFO("Got from UNIX Socket TUN fd=%d", fd); close(socket); if((fd = dup2(fd, socket)) != socket) { ERROR("dup2() failed"); close(fd); socket = -1; return -1; } socket = -1; INFO("Got TUN duped to fd=%d", fd); return fd; } static inline char *getPathTo_CRTS_mkTUN(void) { const char *mkTUN = "crts_mkTUN"; const size_t addSuffixLen = strlen(mkTUN) + 1; const size_t inc = 128; size_t bufLen = 128; char *buf = (char *) malloc(bufLen); ASSERT(buf, "malloc() failed"); ssize_t rl = readlink("/proc/self/exe", buf, bufLen); ASSERT(rl > 0, "readlink(\"/proc/self/exe\",,) failed"); while( ((size_t) rl) + addSuffixLen >= bufLen) { DASSERT(bufLen < 1024*1024, ""); buf = (char *) realloc(buf, bufLen += inc); ASSERT(buf, "realloc() failed"); rl = readlink("/proc/self/exe", buf, bufLen); ASSERT(rl > 0, "readlink(\"/proc/self/exe\",,) failed"); } buf[rl] = '\0'; --rl; while(rl > 3 && buf[rl] != '/') --rl; ASSERT(buf[rl] == '/', ""); ++rl; strcpy(&buf[rl], mkTUN); return buf; } bool checkSubnetAddress(const char *subnet) { unsigned long val; size_t len = strlen(subn
random
[ { "content": "// This is an internal data structure and not a user interface; hence\n\n// it's not called CRTSParameter.\n\nstruct Parameter\n\n{\n\n // called in CRTSController to set the value.\n\n std::function<bool (double)> set;\n\n\n\n // called in CRTSController to poll the value\n\n std::fun...
C++
iRODS/server/re/src/testMS.cpp
nesi/irods
49eeaf76305fc483f21b1bbfbdd77d540b59cfd2
#include "reGlobalsExtern.hpp" #include "reFuncDefs.hpp" #include "icatHighLevelRoutines.hpp" int print_hello( ruleExecInfo_t *rei ) { RE_TEST_MACRO( "Test for print_hello\n" ); fprintf( stdout, "Hello\n" ); _writeString( "stdout", "Hello\n", rei ); return 0; } int recover_print_hello( ruleExecInfo_t *rei ) { RE_TEST_MACRO( "\b\b\b\b\b \b\b\b\b\b" ); fprintf( stdout, "\b\b\b\b\b \b\b\b\b\b" ); return 0; } int print_doi( dataObjInfo_t *doi ) { if ( reTestFlag == COMMAND_TEST_1 ) { fprintf( stdout, " objPath = %s\n", doi->objPath ); fprintf( stdout, " rescName= %s\n", doi->rescName ); fprintf( stdout, " dataType= %s\n", doi->dataType ); fprintf( stdout, " dataSize= %lld\n", doi->dataSize ); } else if ( reTestFlag == HTML_TEST_1 ) { fprintf( stdout, " <UL>\n" ); fprintf( stdout, " <LI> objPath = %s\n", doi->objPath ); fprintf( stdout, " <LI> rescName= %s\n", doi->rescName ); fprintf( stdout, " <LI> dataType= %s\n", doi->dataType ); fprintf( stdout, " <LI> dataSize= %lld\n", doi->dataSize ); fprintf( stdout, " </UL>\n" ); } else { rodsLog( LOG_NOTICE, " objPath = %s\n", doi->objPath ); rodsLog( LOG_NOTICE, " rescName= %s\n", doi->rescName ); rodsLog( LOG_NOTICE, " dataType= %s\n", doi->dataType ); rodsLog( LOG_NOTICE, " dataSize= %lld\n", doi->dataSize ); } return 0; } int print_uoi( userInfo_t *uoi ) { if ( reTestFlag == COMMAND_TEST_1 ) { fprintf( stdout, " userName = %s\n", uoi->userName ); fprintf( stdout, " rodsZone= %s\n", uoi->rodsZone ); fprintf( stdout, " userType= %s\n", uoi->userType ); } else if ( reTestFlag == HTML_TEST_1 ) { fprintf( stdout, " <UL>\n" ); fprintf( stdout, " <LI> userName= %s\n", uoi->userName ); fprintf( stdout, " <LI> rodsZone= %s\n", uoi->rodsZone ); fprintf( stdout, " <LI> userType= %s\n", uoi->userType ); fprintf( stdout, " </UL>\n" ); } else { rodsLog( LOG_NOTICE, " userName= %s\n", uoi->userName ); rodsLog( LOG_NOTICE, " rodsZone= %s\n", uoi->rodsZone ); rodsLog( LOG_NOTICE, " userType= %s\n", uoi->userType ); } return 0; } int msiAW1( msParam_t* mPIn, msParam_t* mPOut2, ruleExecInfo_t* ) { char *In; In = ( char * ) mPIn->inOutStruct; rodsLog( LOG_NOTICE, "ALPHA: ------> In:%s\n", In ); mPOut2->type = strdup( STR_MS_T ); mPOut2->inOutStruct = strdup( "Microservice_1" ); return 0; } int msiCutBufferInHalf( msParam_t* mPIn, ruleExecInfo_t *rei ) { RE_TEST_MACRO( "Test for msiCutBufferInHalf\n" ); if ( mPIn == NULL || mPIn->inpOutBuf == NULL ) { rodsLog( LOG_ERROR, "msiCutBufferInHalf: input is NULL." ); return USER__NULL_INPUT_ERR; } mPIn->inpOutBuf->len = ( mPIn->inpOutBuf->len ) / 2; return 0; } int msiDoSomething( msParam_t *, msParam_t *outParam, ruleExecInfo_t * rei ) { keyValPair_t *myKeyVal; RE_TEST_MACRO( " Calling msiDoSomething" ) if ( rei == NULL || rei->rsComm == NULL ) { rodsLog( LOG_ERROR, "msiDoSomething: input rei or rsComm is NULL." ); return SYS_INTERNAL_NULL_INPUT_ERR; } myKeyVal = ( keyValPair_t* ) malloc( sizeof( keyValPair_t ) ); memset( myKeyVal, 0, sizeof( keyValPair_t ) ); outParam->type = strdup( KeyValPair_MS_T ); outParam->inOutStruct = ( void* ) myKeyVal; return 0; }
#include "reGlobalsExtern.hpp" #include "reFuncDefs.hpp" #include "icatHighLevelRoutines.hpp" int print_hello( ruleExecInfo_t *rei ) { RE_TEST_MACRO( "Test for print_hello\n" ); fprintf( stdout, "Hello\n" ); _writeString( "stdout", "Hello\n", rei ); return 0; } int recover_print_hello( ruleExecInfo_t *rei ) { RE_TEST_MACRO( "\b\b\b\b\b \b\b\b\b\b" ); fprintf( stdout, "\b\b\b\b\b \b\b\b\b\b" ); return 0; } int print_doi( dataObjInfo_t *doi ) { if ( reTestFlag == COMMAND_TEST_1 ) { fprintf( s
int print_uoi( userInfo_t *uoi ) { if ( reTestFlag == COMMAND_TEST_1 ) { fprintf( stdout, " userName = %s\n", uoi->userName ); fprintf( stdout, " rodsZone= %s\n", uoi->rodsZone ); fprintf( stdout, " userType= %s\n", uoi->userType ); } else if ( reTestFlag == HTML_TEST_1 ) { fprintf( stdout, " <UL>\n" ); fprintf( stdout, " <LI> userName= %s\n", uoi->userName ); fprintf( stdout, " <LI> rodsZone= %s\n", uoi->rodsZone ); fprintf( stdout, " <LI> userType= %s\n", uoi->userType ); fprintf( stdout, " </UL>\n" ); } else { rodsLog( LOG_NOTICE, " userName= %s\n", uoi->userName ); rodsLog( LOG_NOTICE, " rodsZone= %s\n", uoi->rodsZone ); rodsLog( LOG_NOTICE, " userType= %s\n", uoi->userType ); } return 0; } int msiAW1( msParam_t* mPIn, msParam_t* mPOut2, ruleExecInfo_t* ) { char *In; In = ( char * ) mPIn->inOutStruct; rodsLog( LOG_NOTICE, "ALPHA: ------> In:%s\n", In ); mPOut2->type = strdup( STR_MS_T ); mPOut2->inOutStruct = strdup( "Microservice_1" ); return 0; } int msiCutBufferInHalf( msParam_t* mPIn, ruleExecInfo_t *rei ) { RE_TEST_MACRO( "Test for msiCutBufferInHalf\n" ); if ( mPIn == NULL || mPIn->inpOutBuf == NULL ) { rodsLog( LOG_ERROR, "msiCutBufferInHalf: input is NULL." ); return USER__NULL_INPUT_ERR; } mPIn->inpOutBuf->len = ( mPIn->inpOutBuf->len ) / 2; return 0; } int msiDoSomething( msParam_t *, msParam_t *outParam, ruleExecInfo_t * rei ) { keyValPair_t *myKeyVal; RE_TEST_MACRO( " Calling msiDoSomething" ) if ( rei == NULL || rei->rsComm == NULL ) { rodsLog( LOG_ERROR, "msiDoSomething: input rei or rsComm is NULL." ); return SYS_INTERNAL_NULL_INPUT_ERR; } myKeyVal = ( keyValPair_t* ) malloc( sizeof( keyValPair_t ) ); memset( myKeyVal, 0, sizeof( keyValPair_t ) ); outParam->type = strdup( KeyValPair_MS_T ); outParam->inOutStruct = ( void* ) myKeyVal; return 0; }
tdout, " objPath = %s\n", doi->objPath ); fprintf( stdout, " rescName= %s\n", doi->rescName ); fprintf( stdout, " dataType= %s\n", doi->dataType ); fprintf( stdout, " dataSize= %lld\n", doi->dataSize ); } else if ( reTestFlag == HTML_TEST_1 ) { fprintf( stdout, " <UL>\n" ); fprintf( stdout, " <LI> objPath = %s\n", doi->objPath ); fprintf( stdout, " <LI> rescName= %s\n", doi->rescName ); fprintf( stdout, " <LI> dataType= %s\n", doi->dataType ); fprintf( stdout, " <LI> dataSize= %lld\n", doi->dataSize ); fprintf( stdout, " </UL>\n" ); } else { rodsLog( LOG_NOTICE, " objPath = %s\n", doi->objPath ); rodsLog( LOG_NOTICE, " rescName= %s\n", doi->rescName ); rodsLog( LOG_NOTICE, " dataType= %s\n", doi->dataType ); rodsLog( LOG_NOTICE, " dataSize= %lld\n", doi->dataSize ); } return 0; }
function_block-function_prefixed
[ { "content": " def test(self):\n\n self.rods_session.assert_icommand(\"icd\")\n\n self.rods_session.assert_icommand(\"irule -vF \" + rules30dir + rulefile,\n", "file_path": "tests/pydevtest/test_allrules.py", "rank": 0, "score": 117236.89308473901...
C++
src/ukf.cpp
lb5160482/Sensor-Fusion-Unscented-Kalman-Filter
4636755b6a5dcc25f181684796d3ade82cb943f9
#include "ukf.h" #include "Eigen/Dense" #include <iostream> using namespace std; using Eigen::MatrixXd; using Eigen::VectorXd; using std::vector; UKF::UKF() { is_initialized_ = false; use_laser_ = true; use_radar_ = true; x_ = VectorXd(5); x_pred = VectorXd(5); P_ = MatrixXd::Identity(5, 5); P_pred = MatrixXd(5, 5); std_a_ = 2; std_yawdd_ = 0.5; std_laspx_ = 0.15; std_laspy_ = 0.15; std_radr_ = 0.3; std_radphi_ = 0.03; std_radrd_ = 0.3; n_x_ = 5; n_aug_ = 7; n_z_radar_ = 3; n_z_lidar_ = 2; lambda_ = 3 - n_x_; weights_ = VectorXd(2 * n_aug_ + 1); weights_(0) = lambda_ / (lambda_ + n_aug_); for (int i = 1; i < 2 * n_aug_ + 1; ++i) { weights_(i) = 1 / (2 * (lambda_ + n_aug_)); } Xsig_pred_ = MatrixXd(n_x_, 2 * n_aug_ + 1); } UKF::~UKF() {} void UKF::ProcessMeasurement(MeasurementPackage meas_package) { if ((!use_laser_ && meas_package.sensor_type_ == MeasurementPackage::LASER) || (!use_radar_ && meas_package.sensor_type_ == MeasurementPackage::RADAR)) { return; } if (!is_initialized_) { x_.fill(0.0); if (meas_package.sensor_type_ == MeasurementPackage::LASER) { float px = meas_package.raw_measurements_(0); float py = meas_package.raw_measurements_(1); x_(0) = px; x_(1) = py; cout << "Initialization finished with Laser data!" << endl; } else { float rho = meas_package.raw_measurements_(0); float phi = meas_package.raw_measurements_(1); float px = cos(phi) * rho; float py = sin(phi) * rho; x_(0) = px; x_(1) = py; cout << "Initialization finished with Radar data!" << endl; } is_initialized_ = true; time_us_ = meas_package.timestamp_; return; } double dt = (meas_package.timestamp_ - time_us_) / 1000000.0; time_us_ = meas_package.timestamp_; Prediction(dt); if (meas_package.sensor_type_ == MeasurementPackage::RADAR) { UpdateRadar(meas_package); } else { UpdateLidar(meas_package); } } void UKF::Prediction(double dt) { MatrixXd sigAug = GenerateSigmaAug(); SigPrediction(sigAug, dt); MeanAndCovPrediction(); } void UKF::UpdateLidar(MeasurementPackage meas_package) { MatrixXd ZSig = MatrixXd(n_z_lidar_, 2 * n_aug_ + 1); VectorXd zPred = VectorXd(n_z_lidar_); MatrixXd S = MatrixXd(n_z_lidar_,n_z_lidar_); ZSig.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; ++i) { VectorXd xPred = Xsig_pred_.col(i); double px = xPred(0); double py = xPred(1); ZSig(0, i) = px; ZSig(1, i) = py; } zPred.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; ++i) { zPred += weights_(i) * ZSig.col(i); } MatrixXd R = MatrixXd(2, 2); R << std_laspx_ * std_laspx_, 0, 0, std_laspy_ * std_laspy_; S.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; ++i) { VectorXd diff = ZSig.col(i) - zPred; S += weights_(i) * diff * diff.transpose(); } S += R; MatrixXd Tc = MatrixXd(n_x_, n_z_lidar_); Tc.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; ++i) { VectorXd diffX = Xsig_pred_.col(i) - x_pred; while (diffX(3) < -M_PI) { diffX(3) += 2 * M_PI; } while (diffX(3) > M_PI) { diffX(3) -= 2 * M_PI; } VectorXd diffZ = ZSig.col(i) - zPred; Tc += weights_(i) * diffX * diffZ.transpose(); } MatrixXd K = Tc * S.inverse(); VectorXd diffZ = meas_package.raw_measurements_ - zPred; this->x_ = this->x_pred + K * diffZ; this->P_ = this->P_pred - K * S * K.transpose(); } void UKF::UpdateRadar(MeasurementPackage meas_package) { MatrixXd ZSig = MatrixXd(n_z_radar_, 2 * n_aug_ + 1); VectorXd zPred = VectorXd(n_z_radar_); MatrixXd S = MatrixXd(n_z_radar_,n_z_radar_); ZSig.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; ++i) { VectorXd xPred = Xsig_pred_.col(i); double px = xPred(0); double py = xPred(1); double v = xPred(2); double yaw = xPred(3); double c1 = sqrt(px * px + py * py); ZSig(0, i) = c1; ZSig(1, i) = atan2(py, px); ZSig(2, i) = (px * cos(yaw) * v + py * sin(yaw) * v) / c1; } zPred.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; ++i) { zPred += weights_(i) * ZSig.col(i); } MatrixXd R = MatrixXd(3, 3); R << std_radr_ * std_radr_, 0, 0, 0, std_radphi_ * std_radphi_, 0, 0, 0, std_radrd_ * std_radrd_ ; S.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; ++i) { VectorXd diff = ZSig.col(i) - zPred; while (diff(1) < -M_PI) { diff(1) += 2 * M_PI; } while (diff(1) > M_PI) { diff(1) -= 2 * M_PI; } S += weights_(i) * diff * diff.transpose(); } S += R; MatrixXd Tc = MatrixXd(n_x_, n_z_radar_); Tc.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; ++i) { VectorXd diffX = Xsig_pred_.col(i) - x_pred; while (diffX(3) < -M_PI) { diffX(3) += 2 * M_PI; } while (diffX(3) > M_PI) { diffX(3) -= 2 * M_PI; } VectorXd diffZ = ZSig.col(i) - zPred; while (diffZ(1) < -M_PI) { diffZ(1) += 2 * M_PI; } while (diffZ(1) > M_PI) { diffZ(1) -= 2 * M_PI; } Tc += weights_(i) * diffX * diffZ.transpose(); } MatrixXd K = Tc * S.inverse(); VectorXd diffZ = meas_package.raw_measurements_ - zPred; while (diffZ(1) < -M_PI) { diffZ(1) += 2 * M_PI; } while (diffZ(1) > M_PI) { diffZ(1) -= 2 * M_PI; } this->x_ = this->x_pred + K * diffZ; this->P_ = this->P_pred - K * S * K.transpose(); } MatrixXd UKF::GenerateSigmaAug() { VectorXd xAug = VectorXd(n_aug_); xAug.head(n_x_) = this->x_; xAug[5] = 0; xAug[6] = 0; MatrixXd PAug = MatrixXd::Zero(n_aug_, n_aug_); PAug.fill(0.0); PAug.topLeftCorner(n_x_, n_x_) = this->P_; PAug(5, 5) = std_a_ * std_a_; PAug(6, 6) = std_yawdd_ * std_yawdd_; MatrixXd xSigAUg = MatrixXd(n_aug_, 2 * n_aug_ + 1); MatrixXd sqrtPAug = PAug.llt().matrixL(); xSigAUg.col(0) = xAug; for (int i = 0; i < n_aug_; ++i) { xSigAUg.col(i + 1) = xAug + sqrt(lambda_ + n_aug_) * sqrtPAug.col(i); xSigAUg.col(i + 1 + n_aug_) = xAug - sqrt(lambda_ + n_aug_) * sqrtPAug.col(i); } return xSigAUg; } void UKF::SigPrediction(MatrixXd& sigAug, double dt) { for (int i = 0; i < 2 * n_aug_ + 1; ++i) { VectorXd xSigAug = sigAug.col(i); double px = xSigAug(0); double py = xSigAug(1); double v = xSigAug(2); double yaw = xSigAug(3); double yawRate = xSigAug(4); double aV = xSigAug(5); double aYaw = xSigAug(6); if (fabs(yawRate) < 0.001) { this->Xsig_pred_(0, i) = px + v * cos(yaw) * dt + 0.5 * pow(dt, 2) * cos(yaw) * aV; this->Xsig_pred_(1, i) = py + v * sin(yaw) * dt + 0.5 * pow(dt, 2) * sin(yaw) * aV; } else { this->Xsig_pred_(0, i) = px + v / yawRate * (sin(yaw + yawRate * dt) - sin(yaw)) + 0.5 * pow(dt, 2) * cos(yaw) * aV; this->Xsig_pred_(1, i) = py + v / yawRate * (-cos(yaw + yawRate * dt) + cos(yaw)) + 0.5 * pow(dt, 2) * sin(yaw) * aV; } this->Xsig_pred_(2, i) = v + dt * aV; this->Xsig_pred_(3, i) = yaw + yawRate * dt + 0.5 * pow(dt, 2) * aYaw; this->Xsig_pred_(4, i) = yawRate + dt * aYaw; } } void UKF::MeanAndCovPrediction() { this->x_pred.fill(0.0); this->P_pred.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; ++i) { this->x_pred += weights_(i) * Xsig_pred_.col(i); } for (int i = 0; i < 2 * n_aug_ + 1; ++i) { VectorXd diff = Xsig_pred_.col(i) - this->x_pred; while (diff(3) < -M_PI) { diff(3) += 2 * M_PI; } while (diff(3) > M_PI) { diff(3) -= 2 * M_PI; } this->P_pred += weights_(i) * diff * diff.transpose(); } }
#include "ukf.h" #include "Eigen/Dense" #include <iostream> using namespace std; using Eigen::MatrixXd; using Eigen::VectorXd; using std::vector; UKF::UKF() { is_initialized_ = false; use_laser_ = true; use_radar_ = true; x_ = VectorXd(5); x_pred = VectorXd(5); P_ = MatrixXd::Identity(5, 5); P_pred = MatrixXd(5, 5); std_a_ = 2; std_yawdd_ = 0.5; std_laspx_ = 0.15; std_laspy_ = 0.15; std_radr_ = 0.3; std_radphi_ = 0.03; std_radrd_ = 0.3; n_x_ = 5; n_aug_ = 7; n_z_radar_ = 3; n_z_lidar_ = 2; lambda_ = 3 - n_x_; weights_ = VectorXd(2 * n_aug_ + 1); weights_(0) = lambda_ / (lambda_ + n_aug_); for (int i = 1; i < 2 * n_aug_ + 1; ++i) { weights_(i) = 1 / (2 * (lambda_ + n_aug_)); } Xsig_pred_ = MatrixXd(n_x_, 2 * n_aug_ + 1); } UKF::~UKF() {} void UKF::ProcessMeasurement(MeasurementPackage meas_package) { if ((!use_laser_ && meas_package.sensor_type_ == MeasurementPackage::LASER) || (!use_radar_ && meas_package.sensor_type_ == MeasurementPackage::RADAR)) { return; } if (!is_initialized_) { x_.fill(0.0); if (meas_package.sensor_type_ == MeasurementPackage::LASER) { float px = meas_package.raw_measurements_(0); float py = meas_package.raw_measurements_(1); x_(0) = px; x_(1) = py; cout << "Initialization finished with Laser data!" << endl; } else { float rho = meas_package.raw_measurements_(0); float phi = meas_package.raw_measurements_(1); float px = cos(phi) * rho; float py = sin(phi) * rho; x_(0) = px; x_(1) = py; cout << "Initialization finished with Radar data!" << endl; } is_initialized_ = true; time_us_ = meas_package.timestamp_; return; } double dt = (meas_package.timestamp_ - time_us_) / 1000000.0; time_us_ = meas_package.timestamp_; Prediction(dt);
} void UKF::Prediction(double dt) { MatrixXd sigAug = GenerateSigmaAug(); SigPrediction(sigAug, dt); MeanAndCovPrediction(); } void UKF::UpdateLidar(MeasurementPackage meas_package) { MatrixXd ZSig = MatrixXd(n_z_lidar_, 2 * n_aug_ + 1); VectorXd zPred = VectorXd(n_z_lidar_); MatrixXd S = MatrixXd(n_z_lidar_,n_z_lidar_); ZSig.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; ++i) { VectorXd xPred = Xsig_pred_.col(i); double px = xPred(0); double py = xPred(1); ZSig(0, i) = px; ZSig(1, i) = py; } zPred.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; ++i) { zPred += weights_(i) * ZSig.col(i); } MatrixXd R = MatrixXd(2, 2); R << std_laspx_ * std_laspx_, 0, 0, std_laspy_ * std_laspy_; S.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; ++i) { VectorXd diff = ZSig.col(i) - zPred; S += weights_(i) * diff * diff.transpose(); } S += R; MatrixXd Tc = MatrixXd(n_x_, n_z_lidar_); Tc.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; ++i) { VectorXd diffX = Xsig_pred_.col(i) - x_pred; while (diffX(3) < -M_PI) { diffX(3) += 2 * M_PI; } while (diffX(3) > M_PI) { diffX(3) -= 2 * M_PI; } VectorXd diffZ = ZSig.col(i) - zPred; Tc += weights_(i) * diffX * diffZ.transpose(); } MatrixXd K = Tc * S.inverse(); VectorXd diffZ = meas_package.raw_measurements_ - zPred; this->x_ = this->x_pred + K * diffZ; this->P_ = this->P_pred - K * S * K.transpose(); } void UKF::UpdateRadar(MeasurementPackage meas_package) { MatrixXd ZSig = MatrixXd(n_z_radar_, 2 * n_aug_ + 1); VectorXd zPred = VectorXd(n_z_radar_); MatrixXd S = MatrixXd(n_z_radar_,n_z_radar_); ZSig.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; ++i) { VectorXd xPred = Xsig_pred_.col(i); double px = xPred(0); double py = xPred(1); double v = xPred(2); double yaw = xPred(3); double c1 = sqrt(px * px + py * py); ZSig(0, i) = c1; ZSig(1, i) = atan2(py, px); ZSig(2, i) = (px * cos(yaw) * v + py * sin(yaw) * v) / c1; } zPred.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; ++i) { zPred += weights_(i) * ZSig.col(i); } MatrixXd R = MatrixXd(3, 3); R << std_radr_ * std_radr_, 0, 0, 0, std_radphi_ * std_radphi_, 0, 0, 0, std_radrd_ * std_radrd_ ; S.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; ++i) { VectorXd diff = ZSig.col(i) - zPred; while (diff(1) < -M_PI) { diff(1) += 2 * M_PI; } while (diff(1) > M_PI) { diff(1) -= 2 * M_PI; } S += weights_(i) * diff * diff.transpose(); } S += R; MatrixXd Tc = MatrixXd(n_x_, n_z_radar_); Tc.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; ++i) { VectorXd diffX = Xsig_pred_.col(i) - x_pred; while (diffX(3) < -M_PI) { diffX(3) += 2 * M_PI; } while (diffX(3) > M_PI) { diffX(3) -= 2 * M_PI; } VectorXd diffZ = ZSig.col(i) - zPred; while (diffZ(1) < -M_PI) { diffZ(1) += 2 * M_PI; } while (diffZ(1) > M_PI) { diffZ(1) -= 2 * M_PI; } Tc += weights_(i) * diffX * diffZ.transpose(); } MatrixXd K = Tc * S.inverse(); VectorXd diffZ = meas_package.raw_measurements_ - zPred; while (diffZ(1) < -M_PI) { diffZ(1) += 2 * M_PI; } while (diffZ(1) > M_PI) { diffZ(1) -= 2 * M_PI; } this->x_ = this->x_pred + K * diffZ; this->P_ = this->P_pred - K * S * K.transpose(); } MatrixXd UKF::GenerateSigmaAug() { VectorXd xAug = VectorXd(n_aug_); xAug.head(n_x_) = this->x_; xAug[5] = 0; xAug[6] = 0; MatrixXd PAug = MatrixXd::Zero(n_aug_, n_aug_); PAug.fill(0.0); PAug.topLeftCorner(n_x_, n_x_) = this->P_; PAug(5, 5) = std_a_ * std_a_; PAug(6, 6) = std_yawdd_ * std_yawdd_; MatrixXd xSigAUg = MatrixXd(n_aug_, 2 * n_aug_ + 1); MatrixXd sqrtPAug = PAug.llt().matrixL(); xSigAUg.col(0) = xAug; for (int i = 0; i < n_aug_; ++i) { xSigAUg.col(i + 1) = xAug + sqrt(lambda_ + n_aug_) * sqrtPAug.col(i); xSigAUg.col(i + 1 + n_aug_) = xAug - sqrt(lambda_ + n_aug_) * sqrtPAug.col(i); } return xSigAUg; } void UKF::SigPrediction(MatrixXd& sigAug, double dt) { for (int i = 0; i < 2 * n_aug_ + 1; ++i) { VectorXd xSigAug = sigAug.col(i); double px = xSigAug(0); double py = xSigAug(1); double v = xSigAug(2); double yaw = xSigAug(3); double yawRate = xSigAug(4); double aV = xSigAug(5); double aYaw = xSigAug(6); if (fabs(yawRate) < 0.001) { this->Xsig_pred_(0, i) = px + v * cos(yaw) * dt + 0.5 * pow(dt, 2) * cos(yaw) * aV; this->Xsig_pred_(1, i) = py + v * sin(yaw) * dt + 0.5 * pow(dt, 2) * sin(yaw) * aV; } else { this->Xsig_pred_(0, i) = px + v / yawRate * (sin(yaw + yawRate * dt) - sin(yaw)) + 0.5 * pow(dt, 2) * cos(yaw) * aV; this->Xsig_pred_(1, i) = py + v / yawRate * (-cos(yaw + yawRate * dt) + cos(yaw)) + 0.5 * pow(dt, 2) * sin(yaw) * aV; } this->Xsig_pred_(2, i) = v + dt * aV; this->Xsig_pred_(3, i) = yaw + yawRate * dt + 0.5 * pow(dt, 2) * aYaw; this->Xsig_pred_(4, i) = yawRate + dt * aYaw; } } void UKF::MeanAndCovPrediction() { this->x_pred.fill(0.0); this->P_pred.fill(0.0); for (int i = 0; i < 2 * n_aug_ + 1; ++i) { this->x_pred += weights_(i) * Xsig_pred_.col(i); } for (int i = 0; i < 2 * n_aug_ + 1; ++i) { VectorXd diff = Xsig_pred_.col(i) - this->x_pred; while (diff(3) < -M_PI) { diff(3) += 2 * M_PI; } while (diff(3) > M_PI) { diff(3) -= 2 * M_PI; } this->P_pred += weights_(i) * diff * diff.transpose(); } }
if (meas_package.sensor_type_ == MeasurementPackage::RADAR) { UpdateRadar(meas_package); } else { UpdateLidar(meas_package); }
if_condition
[ { "content": "struct has_std_result_type {int a[2];};\n", "file_path": "src/Eigen/src/Core/util/Meta.h", "rank": 0, "score": 167285.48100387253 }, { "content": "struct has_none {int a[1];};\n", "file_path": "src/Eigen/src/Core/util/Meta.h", "rank": 1, "score": 117858.8414467264 ...
C++
wled00/7segmdisp.cpp
imeszaros/ledclock
e739b11608e52a1e2a3dc88c54dcc40dbc1e5793
#include "7segmdisp.h" static CRGB dummy; void LedBasedDisplay::setRowColor(uint8_t row, bool state, CRGB color) { for (uint8_t c = 0, n = columnCount(); c < n; ++c) { setLedColor(row, c, state, color); } } void LedBasedDisplay::setColumnColor(uint8_t column, bool state, CRGB color) { for (uint8_t r = 0, n = rowCount(); r < n; ++r) { setLedColor(r, column, state, color); } } void LedBasedDisplay::setColor(bool state, CRGB color) { for (uint8_t r = 0, rn = rowCount(); r < rn; ++r) { for (uint8_t c = 0, cn = columnCount(); c < cn; ++c) { setLedColor(r, c, state, color); } } } SevenSegmentDisplay::SevenSegmentDisplay(LedBasedDisplayOutput output, uint8_t ledsPerSegment): _output(output), _ledsPerSegment(ledsPerSegment), _value(_7SEG_SYM_EMPTY), _mode(LedBasedDisplayMode::SET_ALL_LEDS) { _offColors = (CRGB*) malloc(7 * _ledsPerSegment * sizeof(CRGB)); _onColors = (CRGB*) malloc(7 * _ledsPerSegment * sizeof(CRGB)); _indices = (uint8_t*) malloc(7 * _ledsPerSegment * sizeof(uint8_t)); _showZero = true; } SevenSegmentDisplay::~SevenSegmentDisplay() { delete _indices; delete _offColors; delete _onColors; } uint8_t SevenSegmentDisplay::rowCount() { return _ledsPerSegment * 2 + 3; } uint8_t SevenSegmentDisplay::columnCount() { return _ledsPerSegment + 2; } uint8_t SevenSegmentDisplay::internalIndex(uint8_t row, uint8_t column) { uint8_t lastRow = (_ledsPerSegment + 1) * 2; if (row < 0 || row > lastRow) { return _7SEG_INDEX_UNDEF; } uint8_t midRow = _ledsPerSegment + 1; bool top = row == 0; bool mid = row == midRow; bool bot = row == lastRow; if (top || mid || bot) { if (column >= 1 && column <= _ledsPerSegment) { if (top) { return _7SEG_IDX(_7SEG_SEG_A, column - 1); } else if (mid) { return _7SEG_IDX(_7SEG_SEG_G, column - 1); } else { return _7SEG_IDX(_7SEG_SEG_D, column - 1); } } } else if (column == 0) { if (row < midRow) { return _7SEG_IDX(_7SEG_SEG_F, row - 1); } else { return _7SEG_IDX(_7SEG_SEG_E, row - midRow - 1); } } else if (column == _ledsPerSegment + 1) { if (row < midRow) { return _7SEG_IDX(_7SEG_SEG_B, row - 1); } else { return _7SEG_IDX(_7SEG_SEG_C, row - midRow - 1); } } return _7SEG_INDEX_UNDEF; } uint8_t SevenSegmentDisplay::indexOfCoords(uint8_t row, uint8_t column) { uint8_t idx = internalIndex(row, column); return idx == _7SEG_INDEX_UNDEF ? idx : _indices[idx]; } Coords SevenSegmentDisplay::coordsOfIndex(uint16_t index) { Coords coords; for (int i = 0, n = 7 * _ledsPerSegment; i < n; ++i) { if (_indices[i] == index) { uint8_t seg = i / _ledsPerSegment; uint8_t idx = i % _ledsPerSegment; switch (seg) { case _7SEG_SEG_A: coords.row = 0; break; case _7SEG_SEG_B: case _7SEG_SEG_F: coords.row = idx + 1; break; case _7SEG_SEG_C: case _7SEG_SEG_E: coords.row = _ledsPerSegment + 1 + idx + 1; break; case _7SEG_SEG_D: coords.row = _ledsPerSegment + 1 + _ledsPerSegment + 1; break; case _7SEG_SEG_G: coords.row = _ledsPerSegment + 1; break; } switch (seg) { case _7SEG_SEG_A: case _7SEG_SEG_D: case _7SEG_SEG_G: coords.col = idx + 1; break; case _7SEG_SEG_B: case _7SEG_SEG_C: coords.col = _ledsPerSegment + 1; break; case _7SEG_SEG_E: case _7SEG_SEG_F: coords.col = 0; break; } return coords; } } return coords; } CRGB* SevenSegmentDisplay::getLedColor(uint8_t row, uint8_t column, bool state) { uint8_t idx = internalIndex(row, column); if (idx == _7SEG_INDEX_UNDEF) { return &dummy; } return &(state ? _onColors : _offColors)[idx]; } void SevenSegmentDisplay::setLedColor(uint8_t row, uint8_t column, bool state, CRGB color) { uint8_t idx = internalIndex(row, column); if (idx == _7SEG_INDEX_UNDEF) { return; } (state ? _onColors : _offColors)[idx] = color; } void SevenSegmentDisplay::update() { uint8_t mask = 0b00000001; for (uint8_t seg = _7SEG_SEG_A; seg <= _7SEG_SEG_G; ++seg) { bool on = _value & mask; if (_7SEG_MODE(_mode, on)) { for (uint8_t i = 0; i < _ledsPerSegment; ++i) { uint8_t segmIdx = _7SEG_IDX(seg, i); CRGB c = (on ? _onColors : _offColors)[segmIdx]; (*_output)(_indices[segmIdx], c.red, c.green, c.blue); } } mask <<= 1; } } void SevenSegmentDisplay::setMode(LedBasedDisplayMode mode) { _mode = mode; } void SevenSegmentDisplay::mapSegment(uint8_t seg, ...) { va_list ap; va_start(ap, seg); for (uint8_t i = 0; i < _ledsPerSegment; i++) { _indices[_7SEG_IDX(seg, i)] = va_arg(ap, int); } va_end(ap); } void SevenSegmentDisplay::setSymbol(uint8_t symbol) { _value = symbol; } void SevenSegmentDisplay::setDigit(uint8_t digit) { switch (digit) { case 0: if (_showZero) setSymbol(_7SEG_SYM_0); else setSymbol(_7SEG_SYM_EMPTY); break; case 1: setSymbol(_7SEG_SYM_1); break; case 2: setSymbol(_7SEG_SYM_2); break; case 3: setSymbol(_7SEG_SYM_3); break; case 4: setSymbol(_7SEG_SYM_4); break; case 5: setSymbol(_7SEG_SYM_5); break; case 6: setSymbol(_7SEG_SYM_6); break; case 7: setSymbol(_7SEG_SYM_7); break; case 8: setSymbol(_7SEG_SYM_8); break; case 9: setSymbol(_7SEG_SYM_9); break; default: setSymbol(_7SEG_SYM_EMPTY); } } void SevenSegmentDisplay::setCharacter(char charcter) { switch (charcter) { case 'a': case 'A': setSymbol(_7SEG_SYM_A); break; case 'b': case 'B': setSymbol(_7SEG_SYM_B); break; case 'c': case 'C': setSymbol(_7SEG_SYM_C); break; case 'd': case 'D': setSymbol(_7SEG_SYM_D); break; case 'e': case 'E': setSymbol(_7SEG_SYM_E); break; case 'f': case 'F': setSymbol(_7SEG_SYM_F); break; case 'g': case 'G': setSymbol(_7SEG_SYM_G); break; case 'h': case 'H': setSymbol(_7SEG_SYM_H); break; case 'i': case 'I': setSymbol(_7SEG_SYM_I); break; case 'j': case 'J': setSymbol(_7SEG_SYM_J); break; case 'k': case 'K': setSymbol(_7SEG_SYM_K); break; case 'l': case 'L': setSymbol(_7SEG_SYM_L); break; case 'm': case 'M': setSymbol(_7SEG_SYM_M); break; case 'n': case 'N': setSymbol(_7SEG_SYM_N); break; case 'o': case 'O': setSymbol(_7SEG_SYM_O); break; case 'p': case 'P': setSymbol(_7SEG_SYM_P); break; case 'q': case 'Q': setSymbol(_7SEG_SYM_Q); break; case 'r': case 'R': setSymbol(_7SEG_SYM_R); break; case 's': case 'S': setSymbol(_7SEG_SYM_S); break; case 't': case 'T': setSymbol(_7SEG_SYM_T); break; case 'u': case 'U': setSymbol(_7SEG_SYM_U); break; case 'v': case 'V': setSymbol(_7SEG_SYM_V); break; case 'w': case 'W': setSymbol(_7SEG_SYM_W); break; case 'x': case 'X': setSymbol(_7SEG_SYM_X); break; case 'y': case 'Y': setSymbol(_7SEG_SYM_Y); break; case 'z': case 'Z': setSymbol(_7SEG_SYM_Z); break; case '-': setSymbol(_7SEG_SYM_DASH); break; case '_': setSymbol(_7SEG_SYM_UNDERSCORE); break; case ' ': default: setSymbol(_7SEG_SYM_EMPTY); } } void SevenSegmentDisplay::setShowZero(boolean showZero) { _showZero = showZero; } SeparatorDisplay::SeparatorDisplay(LedBasedDisplayOutput output): _output(output), _ledCount(0), _mappings(NULL), _state(false), _mode(LedBasedDisplayMode::SET_ALL_LEDS) {} SeparatorDisplay::~SeparatorDisplay() { delete _mappings; } uint8_t SeparatorDisplay::rowCount() { uint8_t max = _mappings[0].row; for (uint8_t i = 1; i < _ledCount; ++i) { if (_mappings[i].row > max) { max = _mappings[i].row; } } return max + 1; } uint8_t SeparatorDisplay::columnCount() { uint8_t max = _mappings[0].column; for (uint8_t i = 1; i < _ledCount; ++i) { if (_mappings[i].column > max) { max = _mappings[i].column; } } return max + 1; } uint8_t SeparatorDisplay::indexOfCoords(uint8_t row, uint8_t column) { for (uint8_t i = 0; i < _ledCount; ++i) { if (_mappings[i].row == row && _mappings[i].column == column) { return _mappings[i].index; } } return _7SEG_INDEX_UNDEF; } Coords SeparatorDisplay::coordsOfIndex(uint16_t index) { for (uint8_t i = 0; i < _ledCount; ++i) { if (_mappings[i].index == index) { return Coords(_mappings[i].row, _mappings[i].column); } } return Coords(); } CRGB* SeparatorDisplay::getLedColor(uint8_t row, uint8_t column, bool state) { for (uint8_t i = 0; i < _ledCount; ++i) { if (_mappings[i].row == row && _mappings[i].column == column) { if (state) { return &_mappings[i].onColor; } else { return &_mappings[i].offColor; } } } return &dummy; } void SeparatorDisplay::setLedColor(uint8_t row, uint8_t column, bool state, CRGB color) { for (uint8_t i = 0; i < _ledCount; ++i) { if (_mappings[i].row == row && _mappings[i].column == column) { if (state) { _mappings[i].onColor = color; } else { _mappings[i].offColor = color; } } } } void SeparatorDisplay::update() { for (uint8_t i = 0; i < _ledCount; ++i) { if (_7SEG_MODE(_mode, _state)) { CRGB c = _state ? _mappings[i].onColor : _mappings[i].offColor; (*_output)(_mappings[i].index, c.red, c.green, c.blue); } } } void SeparatorDisplay::setMode(LedBasedDisplayMode mode) { _mode = mode; } void SeparatorDisplay::map(uint8_t ledCount, ...) { if (_mappings != NULL) { delete _mappings; } _ledCount = ledCount; _mappings = (struct _Mapping*) malloc(ledCount * sizeof(struct _Mapping)); va_list ap; va_start(ap, ledCount); for (uint8_t i = 0; i < ledCount; i++) { _mappings[i].row = va_arg(ap, int); _mappings[i].column = va_arg(ap, int); _mappings[i].index = va_arg(ap, int); } va_end(ap); } void SeparatorDisplay::setState(bool state) { _state = state; } LedBasedRowDisplay::LedBasedRowDisplay(uint8_t displayCount, ...): _displayCount(displayCount), _displays((LedBasedDisplay**) malloc(displayCount * sizeof(LedBasedDisplay*))) { va_list ap; va_start(ap, displayCount); for (uint8_t i = 0; i < displayCount; i++) { _displays[i] = va_arg(ap, LedBasedDisplay*); } va_end(ap); } LedBasedRowDisplay::~LedBasedRowDisplay() { delete _displays; } uint8_t LedBasedRowDisplay::rowCount() { uint8_t rowCount = 0; for (uint8_t i = 0; i < _displayCount; i++) { rowCount = max(rowCount, _displays[i]->rowCount()); } return rowCount; } uint8_t LedBasedRowDisplay::columnCount() { uint8_t columnCount = 0; for (uint8_t i = 0; i < _displayCount; i++) { columnCount += _displays[i]->columnCount(); } return columnCount; } uint8_t LedBasedRowDisplay::indexOfCoords(uint8_t row, uint8_t column) { uint8_t c = column; for (uint8_t i = 0; i < _displayCount; i++) { uint8_t cc = _displays[i]->columnCount(); if (_displays[i]->columnCount() - 1 < c) { c -= cc; } else { return _displays[i]->indexOfCoords(row, c); } } return _7SEG_INDEX_UNDEF; } Coords LedBasedRowDisplay::coordsOfIndex(uint16_t index) { uint8_t columnCount = 0; for (uint8_t i = 0; i < _displayCount; i++) { Coords coords = _displays[i]->coordsOfIndex(index); if (coords.isValid()) { coords.col += columnCount; return coords; } else { columnCount += _displays[i]->columnCount(); } } return Coords(); } CRGB* LedBasedRowDisplay::getLedColor(uint8_t row, uint8_t column, bool state) { uint8_t c = column; for (uint8_t i = 0; i < _displayCount; i++) { uint8_t cc = _displays[i]->columnCount(); if (_displays[i]->columnCount() - 1 < c) { c -= cc; } else { return _displays[i]->getLedColor(row, c, state); } } return &dummy; } void LedBasedRowDisplay::setLedColor(uint8_t row, uint8_t column, bool state, CRGB color) { uint8_t c = column; for (uint8_t i = 0; i < _displayCount; i++) { uint8_t cc = _displays[i]->columnCount(); if (cc - 1 < c) { c -= cc; } else { _displays[i]->setLedColor(row, c, state, color); return; } } } void LedBasedRowDisplay::update() { for (uint8_t i = 0; i < _displayCount; i++) { _displays[i]->update(); } } void LedBasedRowDisplay::setMode(LedBasedDisplayMode mode) { for (uint8_t i = 0; i < _displayCount; i++) { _displays[i]->setMode(mode); } }
#include "7segmdisp.h" static CRGB dummy; void LedBasedDisplay::setRowColor(uint8_t row, bool state, CRGB color) { for (uint8_t c = 0, n = columnCount(); c < n; ++c) { setLedColor(row, c, state, color); } } void LedBasedDisplay::setColumnColor(uint8_t column, bool state, CRGB color) { for (uint8_t r = 0, n = rowCount(); r < n; ++r) { setLedColor(r, column, state, color); } } void LedBasedDisplay::setColor(bool state, CRGB color) { for (uint8_t r = 0, rn = rowCount(); r < rn; ++r) { for (uint8_t c = 0, cn = columnCount(); c < cn; ++c) { setLedColor(r, c, state, color); } } }
SevenSegmentDisplay::~SevenSegmentDisplay() { delete _indices; delete _offColors; delete _onColors; } uint8_t SevenSegmentDisplay::rowCount() { return _ledsPerSegment * 2 + 3; } uint8_t SevenSegmentDisplay::columnCount() { return _ledsPerSegment + 2; } uint8_t SevenSegmentDisplay::internalIndex(uint8_t row, uint8_t column) { uint8_t lastRow = (_ledsPerSegment + 1) * 2; if (row < 0 || row > lastRow) { return _7SEG_INDEX_UNDEF; } uint8_t midRow = _ledsPerSegment + 1; bool top = row == 0; bool mid = row == midRow; bool bot = row == lastRow; if (top || mid || bot) { if (column >= 1 && column <= _ledsPerSegment) { if (top) { return _7SEG_IDX(_7SEG_SEG_A, column - 1); } else if (mid) { return _7SEG_IDX(_7SEG_SEG_G, column - 1); } else { return _7SEG_IDX(_7SEG_SEG_D, column - 1); } } } else if (column == 0) { if (row < midRow) { return _7SEG_IDX(_7SEG_SEG_F, row - 1); } else { return _7SEG_IDX(_7SEG_SEG_E, row - midRow - 1); } } else if (column == _ledsPerSegment + 1) { if (row < midRow) { return _7SEG_IDX(_7SEG_SEG_B, row - 1); } else { return _7SEG_IDX(_7SEG_SEG_C, row - midRow - 1); } } return _7SEG_INDEX_UNDEF; } uint8_t SevenSegmentDisplay::indexOfCoords(uint8_t row, uint8_t column) { uint8_t idx = internalIndex(row, column); return idx == _7SEG_INDEX_UNDEF ? idx : _indices[idx]; } Coords SevenSegmentDisplay::coordsOfIndex(uint16_t index) { Coords coords; for (int i = 0, n = 7 * _ledsPerSegment; i < n; ++i) { if (_indices[i] == index) { uint8_t seg = i / _ledsPerSegment; uint8_t idx = i % _ledsPerSegment; switch (seg) { case _7SEG_SEG_A: coords.row = 0; break; case _7SEG_SEG_B: case _7SEG_SEG_F: coords.row = idx + 1; break; case _7SEG_SEG_C: case _7SEG_SEG_E: coords.row = _ledsPerSegment + 1 + idx + 1; break; case _7SEG_SEG_D: coords.row = _ledsPerSegment + 1 + _ledsPerSegment + 1; break; case _7SEG_SEG_G: coords.row = _ledsPerSegment + 1; break; } switch (seg) { case _7SEG_SEG_A: case _7SEG_SEG_D: case _7SEG_SEG_G: coords.col = idx + 1; break; case _7SEG_SEG_B: case _7SEG_SEG_C: coords.col = _ledsPerSegment + 1; break; case _7SEG_SEG_E: case _7SEG_SEG_F: coords.col = 0; break; } return coords; } } return coords; } CRGB* SevenSegmentDisplay::getLedColor(uint8_t row, uint8_t column, bool state) { uint8_t idx = internalIndex(row, column); if (idx == _7SEG_INDEX_UNDEF) { return &dummy; } return &(state ? _onColors : _offColors)[idx]; } void SevenSegmentDisplay::setLedColor(uint8_t row, uint8_t column, bool state, CRGB color) { uint8_t idx = internalIndex(row, column); if (idx == _7SEG_INDEX_UNDEF) { return; } (state ? _onColors : _offColors)[idx] = color; } void SevenSegmentDisplay::update() { uint8_t mask = 0b00000001; for (uint8_t seg = _7SEG_SEG_A; seg <= _7SEG_SEG_G; ++seg) { bool on = _value & mask; if (_7SEG_MODE(_mode, on)) { for (uint8_t i = 0; i < _ledsPerSegment; ++i) { uint8_t segmIdx = _7SEG_IDX(seg, i); CRGB c = (on ? _onColors : _offColors)[segmIdx]; (*_output)(_indices[segmIdx], c.red, c.green, c.blue); } } mask <<= 1; } } void SevenSegmentDisplay::setMode(LedBasedDisplayMode mode) { _mode = mode; } void SevenSegmentDisplay::mapSegment(uint8_t seg, ...) { va_list ap; va_start(ap, seg); for (uint8_t i = 0; i < _ledsPerSegment; i++) { _indices[_7SEG_IDX(seg, i)] = va_arg(ap, int); } va_end(ap); } void SevenSegmentDisplay::setSymbol(uint8_t symbol) { _value = symbol; } void SevenSegmentDisplay::setDigit(uint8_t digit) { switch (digit) { case 0: if (_showZero) setSymbol(_7SEG_SYM_0); else setSymbol(_7SEG_SYM_EMPTY); break; case 1: setSymbol(_7SEG_SYM_1); break; case 2: setSymbol(_7SEG_SYM_2); break; case 3: setSymbol(_7SEG_SYM_3); break; case 4: setSymbol(_7SEG_SYM_4); break; case 5: setSymbol(_7SEG_SYM_5); break; case 6: setSymbol(_7SEG_SYM_6); break; case 7: setSymbol(_7SEG_SYM_7); break; case 8: setSymbol(_7SEG_SYM_8); break; case 9: setSymbol(_7SEG_SYM_9); break; default: setSymbol(_7SEG_SYM_EMPTY); } } void SevenSegmentDisplay::setCharacter(char charcter) { switch (charcter) { case 'a': case 'A': setSymbol(_7SEG_SYM_A); break; case 'b': case 'B': setSymbol(_7SEG_SYM_B); break; case 'c': case 'C': setSymbol(_7SEG_SYM_C); break; case 'd': case 'D': setSymbol(_7SEG_SYM_D); break; case 'e': case 'E': setSymbol(_7SEG_SYM_E); break; case 'f': case 'F': setSymbol(_7SEG_SYM_F); break; case 'g': case 'G': setSymbol(_7SEG_SYM_G); break; case 'h': case 'H': setSymbol(_7SEG_SYM_H); break; case 'i': case 'I': setSymbol(_7SEG_SYM_I); break; case 'j': case 'J': setSymbol(_7SEG_SYM_J); break; case 'k': case 'K': setSymbol(_7SEG_SYM_K); break; case 'l': case 'L': setSymbol(_7SEG_SYM_L); break; case 'm': case 'M': setSymbol(_7SEG_SYM_M); break; case 'n': case 'N': setSymbol(_7SEG_SYM_N); break; case 'o': case 'O': setSymbol(_7SEG_SYM_O); break; case 'p': case 'P': setSymbol(_7SEG_SYM_P); break; case 'q': case 'Q': setSymbol(_7SEG_SYM_Q); break; case 'r': case 'R': setSymbol(_7SEG_SYM_R); break; case 's': case 'S': setSymbol(_7SEG_SYM_S); break; case 't': case 'T': setSymbol(_7SEG_SYM_T); break; case 'u': case 'U': setSymbol(_7SEG_SYM_U); break; case 'v': case 'V': setSymbol(_7SEG_SYM_V); break; case 'w': case 'W': setSymbol(_7SEG_SYM_W); break; case 'x': case 'X': setSymbol(_7SEG_SYM_X); break; case 'y': case 'Y': setSymbol(_7SEG_SYM_Y); break; case 'z': case 'Z': setSymbol(_7SEG_SYM_Z); break; case '-': setSymbol(_7SEG_SYM_DASH); break; case '_': setSymbol(_7SEG_SYM_UNDERSCORE); break; case ' ': default: setSymbol(_7SEG_SYM_EMPTY); } } void SevenSegmentDisplay::setShowZero(boolean showZero) { _showZero = showZero; } SeparatorDisplay::SeparatorDisplay(LedBasedDisplayOutput output): _output(output), _ledCount(0), _mappings(NULL), _state(false), _mode(LedBasedDisplayMode::SET_ALL_LEDS) {} SeparatorDisplay::~SeparatorDisplay() { delete _mappings; } uint8_t SeparatorDisplay::rowCount() { uint8_t max = _mappings[0].row; for (uint8_t i = 1; i < _ledCount; ++i) { if (_mappings[i].row > max) { max = _mappings[i].row; } } return max + 1; } uint8_t SeparatorDisplay::columnCount() { uint8_t max = _mappings[0].column; for (uint8_t i = 1; i < _ledCount; ++i) { if (_mappings[i].column > max) { max = _mappings[i].column; } } return max + 1; } uint8_t SeparatorDisplay::indexOfCoords(uint8_t row, uint8_t column) { for (uint8_t i = 0; i < _ledCount; ++i) { if (_mappings[i].row == row && _mappings[i].column == column) { return _mappings[i].index; } } return _7SEG_INDEX_UNDEF; } Coords SeparatorDisplay::coordsOfIndex(uint16_t index) { for (uint8_t i = 0; i < _ledCount; ++i) { if (_mappings[i].index == index) { return Coords(_mappings[i].row, _mappings[i].column); } } return Coords(); } CRGB* SeparatorDisplay::getLedColor(uint8_t row, uint8_t column, bool state) { for (uint8_t i = 0; i < _ledCount; ++i) { if (_mappings[i].row == row && _mappings[i].column == column) { if (state) { return &_mappings[i].onColor; } else { return &_mappings[i].offColor; } } } return &dummy; } void SeparatorDisplay::setLedColor(uint8_t row, uint8_t column, bool state, CRGB color) { for (uint8_t i = 0; i < _ledCount; ++i) { if (_mappings[i].row == row && _mappings[i].column == column) { if (state) { _mappings[i].onColor = color; } else { _mappings[i].offColor = color; } } } } void SeparatorDisplay::update() { for (uint8_t i = 0; i < _ledCount; ++i) { if (_7SEG_MODE(_mode, _state)) { CRGB c = _state ? _mappings[i].onColor : _mappings[i].offColor; (*_output)(_mappings[i].index, c.red, c.green, c.blue); } } } void SeparatorDisplay::setMode(LedBasedDisplayMode mode) { _mode = mode; } void SeparatorDisplay::map(uint8_t ledCount, ...) { if (_mappings != NULL) { delete _mappings; } _ledCount = ledCount; _mappings = (struct _Mapping*) malloc(ledCount * sizeof(struct _Mapping)); va_list ap; va_start(ap, ledCount); for (uint8_t i = 0; i < ledCount; i++) { _mappings[i].row = va_arg(ap, int); _mappings[i].column = va_arg(ap, int); _mappings[i].index = va_arg(ap, int); } va_end(ap); } void SeparatorDisplay::setState(bool state) { _state = state; } LedBasedRowDisplay::LedBasedRowDisplay(uint8_t displayCount, ...): _displayCount(displayCount), _displays((LedBasedDisplay**) malloc(displayCount * sizeof(LedBasedDisplay*))) { va_list ap; va_start(ap, displayCount); for (uint8_t i = 0; i < displayCount; i++) { _displays[i] = va_arg(ap, LedBasedDisplay*); } va_end(ap); } LedBasedRowDisplay::~LedBasedRowDisplay() { delete _displays; } uint8_t LedBasedRowDisplay::rowCount() { uint8_t rowCount = 0; for (uint8_t i = 0; i < _displayCount; i++) { rowCount = max(rowCount, _displays[i]->rowCount()); } return rowCount; } uint8_t LedBasedRowDisplay::columnCount() { uint8_t columnCount = 0; for (uint8_t i = 0; i < _displayCount; i++) { columnCount += _displays[i]->columnCount(); } return columnCount; } uint8_t LedBasedRowDisplay::indexOfCoords(uint8_t row, uint8_t column) { uint8_t c = column; for (uint8_t i = 0; i < _displayCount; i++) { uint8_t cc = _displays[i]->columnCount(); if (_displays[i]->columnCount() - 1 < c) { c -= cc; } else { return _displays[i]->indexOfCoords(row, c); } } return _7SEG_INDEX_UNDEF; } Coords LedBasedRowDisplay::coordsOfIndex(uint16_t index) { uint8_t columnCount = 0; for (uint8_t i = 0; i < _displayCount; i++) { Coords coords = _displays[i]->coordsOfIndex(index); if (coords.isValid()) { coords.col += columnCount; return coords; } else { columnCount += _displays[i]->columnCount(); } } return Coords(); } CRGB* LedBasedRowDisplay::getLedColor(uint8_t row, uint8_t column, bool state) { uint8_t c = column; for (uint8_t i = 0; i < _displayCount; i++) { uint8_t cc = _displays[i]->columnCount(); if (_displays[i]->columnCount() - 1 < c) { c -= cc; } else { return _displays[i]->getLedColor(row, c, state); } } return &dummy; } void LedBasedRowDisplay::setLedColor(uint8_t row, uint8_t column, bool state, CRGB color) { uint8_t c = column; for (uint8_t i = 0; i < _displayCount; i++) { uint8_t cc = _displays[i]->columnCount(); if (cc - 1 < c) { c -= cc; } else { _displays[i]->setLedColor(row, c, state, color); return; } } } void LedBasedRowDisplay::update() { for (uint8_t i = 0; i < _displayCount; i++) { _displays[i]->update(); } } void LedBasedRowDisplay::setMode(LedBasedDisplayMode mode) { for (uint8_t i = 0; i < _displayCount; i++) { _displays[i]->setMode(mode); } }
SevenSegmentDisplay::SevenSegmentDisplay(LedBasedDisplayOutput output, uint8_t ledsPerSegment): _output(output), _ledsPerSegment(ledsPerSegment), _value(_7SEG_SYM_EMPTY), _mode(LedBasedDisplayMode::SET_ALL_LEDS) { _offColors = (CRGB*) malloc(7 * _ledsPerSegment * sizeof(CRGB)); _onColors = (CRGB*) malloc(7 * _ledsPerSegment * sizeof(CRGB)); _indices = (uint8_t*) malloc(7 * _ledsPerSegment * sizeof(uint8_t)); _showZero = true; }
function_block-full_function
[ { "content": "const _C = d.querySelector('.container'), N = 4;\n", "file_path": "wled00/data/index.js", "rank": 0, "score": 80796.51181418088 }, { "content": "struct Reader<VariantRef, void> : Reader<char*, void> {\n\n explicit Reader(VariantRef x) : Reader<char*, void>(x.as<const char*>())...
C++
lib/src/TypeRegistration.cpp
PrincetonUniversity/mcpib
72a6b7a04288b9707f20699dbbdcdb964a8ca379
#include "mcpib/TypeRegistration.hpp" #include "mcpib/TypeRegistry.hpp" #include "mcpib/WrapperError.hpp" namespace mcpib { void TypeRegistration::registerFromPython(std::unique_ptr<FromPythonFactory> factory) { for (auto const & existing : _from_python) { if (factory->name == existing->name) { return; } } _from_python.push_back(std::move(factory)); } std::unique_ptr<FromPythonConverter> TypeRegistration::lookupFromPython( PyPtr const & p, bool is_lvalue, bool is_pointer ) const { std::unique_ptr<FromPythonConverter> converter; for (auto iter = _from_python.rbegin(); iter != _from_python.rend(); ++iter) { if ((!is_lvalue || (**iter).is_lvalue) && (is_pointer || !(**iter).is_pointer)) { converter = (**iter).apply(p); if (converter) break; } } return converter; } void TypeRegistration::setValueToPython(std::unique_ptr<ToPythonConverter> converter) { _value_to_python = std::move(converter); } void TypeRegistration::setRefToPython(std::unique_ptr<ToPythonConverter> converter) { _ref_to_python = std::move(converter); } void TypeRegistration::setConstRefToPython(std::unique_ptr<ToPythonConverter> converter) { _const_ref_to_python = std::move(converter); } void TypeRegistration::setPointerToPython(std::unique_ptr<ToPythonConverter> converter) { _pointer_to_python = std::move(converter); } void TypeRegistration::setConstPointerToPython(std::unique_ptr<ToPythonConverter> converter) { _const_pointer_to_python = std::move(converter); } void TypeRegistration::_copyInto(TypeRegistration & other, TypeRegistry & registry) const { for (auto const & other_conv : _from_python) { other.registerFromPython(other_conv->clone(registry)); } if (_value_to_python) other.setValueToPython(_value_to_python->clone(registry)); if (_ref_to_python) other.setRefToPython(_ref_to_python->clone(registry)); if (_const_ref_to_python) other.setConstRefToPython(_const_ref_to_python->clone(registry)); if (_pointer_to_python) other.setPointerToPython(_pointer_to_python->clone(registry)); if (_const_pointer_to_python) other.setConstPointerToPython(_const_pointer_to_python->clone(registry)); for (auto const & pair : _derived) { other._derived[pair.first] = registry.require(pair.first); } } ToPythonConverter const & TypeRegistration::getValueToPython() const { if (!_value_to_python) { throw raiseToPythonError("No move/copy to-Python converter found"); } return *_value_to_python; } ToPythonConverter const & TypeRegistration::getRefToPython() const { if (!_ref_to_python) { throw raiseToPythonError("No reference to-Python converter found"); } return *_ref_to_python; } ToPythonConverter const & TypeRegistration::getConstRefToPython() const { if (!_const_ref_to_python) { throw raiseToPythonError("No const reference to-Python converter found"); } return *_const_ref_to_python; } ToPythonConverter const & TypeRegistration::getPointerToPython() const { if (_pointer_to_python) { return *_pointer_to_python; } else if (_ref_to_python) { return *_ref_to_python; } throw raiseToPythonError("No pointer to-Python converter found"); } ToPythonConverter const & TypeRegistration::getConstPointerToPython() const { if (_const_pointer_to_python) { return *_const_pointer_to_python; } else if (_const_ref_to_python) { return *_const_ref_to_python; } throw raiseToPythonError("No const pointer to-Python converter found"); } }
#include "mcpib/TypeRegistration.hpp" #include "mcpib/TypeRegistry.hpp" #include "mcpib/WrapperError.hpp" namespace mcpib { void TypeRegistration::registerFromPython(std::unique_ptr<FromPythonFactory> factory) { for (auto const & existing : _from_python) { if (factory->name == existing->name) { return; } } _from_python.push_back(std::move(factory)); } std::unique_ptr<FromPythonConverter> TypeRegistration::lookupFromPython( PyPtr const & p, bool is_lvalue, bool is_pointer ) const { std::unique_ptr<FromPythonConverter> converter; for (auto iter = _from_python.rbegin(); iter != _from_python.rend(); ++iter) { if ((!is_lvalue || (**iter).is_lvalue) && (is_pointer || !(**iter).is_pointer)) { converter = (**iter).apply(p); if (converter) break; } } return converter; } void TypeRegistration::setValueToPython(std::unique_ptr<ToPythonConverter> converter) { _value_to_python = std::move(converter); } void TypeRegistration::setRefToPython(std::unique_ptr<ToPythonConverter> converter) { _ref_to_python = std::move(converter); } void TypeRegistration::setConstRefToPython(std::unique_ptr<ToPythonConverter> converter) { _const_ref_to_python = std::move(converter); } void TypeRegistration::setPointerToPython(std::unique_ptr<ToPythonConverter> converter) { _pointer_to_python = std::move(converter); } void TypeRegistration::setConstPointerToPython(std::unique_ptr<ToPythonConverter> converter) { _const_pointer_to_python = std::move(converter); } void TypeRegistration::_copyInto(TypeRegistration & other, TypeRegistry & registry) const { for (auto const & other_conv : _from_python) { other.registerFromPython(other_conv->clone(registry)); } if (_value_to_python) other.setValueToPython(_value_to_python->clone(registry)); if (_ref_to_python) other.setRefToPython(_ref_to_python->clone(registry)); if (_const_ref_to_python) other.setConstRefToPython(_const_ref_to_python->clone(registry)); if (_pointer_to_python) other.setPointerToPython(_pointer_to_python->clone(registry)); if (_const_pointer_to_python) other.setConstPointerToPython(_const_pointer_to_python->clone(registry)); for (auto const & pair : _derived) { other._derived[pair.first] = registry.require(pair.first); } } ToPythonConverter const & TypeRegistration::getValueToPython() const { if (!_value_to_python) { throw raiseToPythonError("No move/copy to-Python converter found"); } return *_value_to_python; } ToPythonConverter const & TypeRegistration::getRefToPython() const { if (!_ref_to_python) { throw raiseToPythonError("No reference to-Python converter found"); } return *
}
_ref_to_python; } ToPythonConverter const & TypeRegistration::getConstRefToPython() const { if (!_const_ref_to_python) { throw raiseToPythonError("No const reference to-Python converter found"); } return *_const_ref_to_python; } ToPythonConverter const & TypeRegistration::getPointerToPython() const { if (_pointer_to_python) { return *_pointer_to_python; } else if (_ref_to_python) { return *_ref_to_python; } throw raiseToPythonError("No pointer to-Python converter found"); } ToPythonConverter const & TypeRegistration::getConstPointerToPython() const { if (_const_pointer_to_python) { return *_const_pointer_to_python; } else if (_const_ref_to_python) { return *_const_ref_to_python; } throw raiseToPythonError("No const pointer to-Python converter found"); }
random
[ { "content": "class ReturnConverter<void> {\n\npublic:\n\n\n\n explicit ReturnConverter(TypeRegistry &) {}\n\n\n\n template <typename ArgumentBuilder, typename ...Args>\n\n PyPtr apply(ArgumentBuilder builder, std::function<void(Args...)> const & function) const {\n\n callFunction(builder, funct...
C++
ecmascript/napi/test/jsi_test.cpp
openharmony-gitee-mirror/ark_js_runtime
b5ac878349b00b337c45f4702332c23aa82e1e28
#include <cstdint> #include <cstdio> #include <cstring> #include <iostream> #include <memory> #include "ark_js_runtime.h" #include "js_value.h" using OHOS::Ace::Framework::ArkJSRuntime; using OHOS::Ace::Framework::JsRuntime; using OHOS::Ace::Framework::JsValue; using OHOS::Ace::Framework::RegisterFunctionType; using std::shared_ptr; std::string GetLogContent(const shared_ptr<JsRuntime> &runtime, const std::vector<shared_ptr<JsValue>> &argument) { std::string context; for (const auto &value : argument) { context += value->ToString(runtime); } return context; } shared_ptr<JsValue> AppDebugLogPrint(const shared_ptr<JsRuntime> &runtime, const shared_ptr<JsValue> &, const std::vector<shared_ptr<JsValue>> &argument, int32_t) { std::string context = GetLogContent(runtime, argument); std::cout << context.c_str() << std::endl; return runtime->NewObject(); } shared_ptr<JsValue> Setter(const shared_ptr<JsRuntime> &runtime, const shared_ptr<JsValue> &, const std::vector<shared_ptr<JsValue>> &argument, int32_t) { std::string context = GetLogContent(runtime, argument); std::cout << context.c_str() << std::endl; return runtime->NewObject(); } shared_ptr<JsValue> Getter(const shared_ptr<JsRuntime> &runtime, const shared_ptr<JsValue> &, const std::vector<shared_ptr<JsValue>> &argument, int32_t) { std::string context = GetLogContent(runtime, argument); std::cout << "Getter" << std::endl; return runtime->NewObject(); } int PrintLog([[maybe_unused]] int id, [[maybe_unused]] int level, const char *tag, [[maybe_unused]] const char *fmt, const char *message) { std::cout << tag << "::" << message; return 0; } class TestRuntime { public: TestRuntime() { runtime_ = ArkJSRuntime::GetInstance(); runtime_->SetLogPrint(PrintLog); runtime_->Initialize(""); } ~TestRuntime() { runtime_->Reset(); } inline const shared_ptr<JsRuntime> &operator*() const { return runtime_; } inline const shared_ptr<JsRuntime> &operator->() const { return runtime_; } private: shared_ptr<JsRuntime> runtime_; }; int main() { TestRuntime runtime; RegisterFunctionType func = AppDebugLogPrint; shared_ptr<JsValue> global = runtime->GetGlobal(); shared_ptr<JsValue> logFunc = runtime->NewFunction(func); shared_ptr<JsValue> consoleObj = runtime->NewObject(); global->SetProperty(*runtime, "console", consoleObj); consoleObj->SetProperty(*runtime, "log", logFunc); consoleObj->SetProperty(*runtime, "info", logFunc); shared_ptr<JsValue> getSetTest = runtime->NewObject(); shared_ptr<JsValue> setter = runtime->NewFunction(Setter); shared_ptr<JsValue> getter = runtime->NewFunction(Getter); bool getset = getSetTest->SetAccessorProperty(*runtime, "GetSetTest", getter, setter); std::cout << "SetAccessorProperty result: " << getset << std::endl; global->SetProperty(*runtime, "GetSet", getSetTest); std::vector<shared_ptr<JsValue>> arguments; arguments.emplace_back(runtime->NewString("Hello world")); consoleObj = global->GetProperty(*runtime, "console"); logFunc = consoleObj->GetProperty(*runtime, "log"); shared_ptr<JsValue> testObj = logFunc->Call(*runtime, runtime->NewUndefined(), arguments, 1); shared_ptr<JsValue> testArrayValue = runtime->NewString("1"); shared_ptr<JsValue> testValue = runtime->NewArray(); testValue->SetProperty(*runtime, "0", testArrayValue); testValue->SetProperty(*runtime, "1", testArrayValue); std::cout << "GetProperty test: " << testValue->GetArrayLength(*runtime) << std::endl; testObj->SetProperty(*runtime, "test", testValue); shared_ptr<JsValue> result = testObj->GetProperty(*runtime, "test"); std::cout << "GetProperty test: " << result->IsArray(*runtime) << ";" << result->GetArrayLength(*runtime) << std::endl; std::vector<std::string> argument; runtime->ExecuteJsBin("native.aex"); return 0; }
#include <cstdint> #include <cstdio> #include <cstring> #include <iostream> #include <memory> #include "ark_js_runtime.h" #include "js_value.h" using OHOS::Ace::Framework::ArkJSRuntime; using OHOS::Ace::Framework::JsRuntime; using OHOS::Ace::Framework::JsValue; using OHOS::Ace::Framework::RegisterFunctionType; using std::shared_ptr; std::string GetLogContent(const shared_ptr<JsRuntime> &runtime, const std::vector<shared_ptr<JsValue>> &argument) { std::string context; for (const auto &value : argument) { context += value->ToString(runtime); } return context; } shared_ptr<JsValue> AppDebugLogPrint(const shared_ptr<JsRuntime> &runtime, const shared_ptr<JsValue> &, const std::vector<shared_ptr<JsValue>> &argument, int32_t) { std::string context = GetLogContent(runtime, argument); std::cout << context.c_str() << std::endl; return runtime->NewObject(); } shared_ptr<JsValue> Setter(const shared_ptr<JsRuntime> &runtime, const shared_ptr<JsValue> &, const std::vector<shared_ptr<JsValue>> &argument, int32_t) { std::string context = GetLogContent(runtime, argument); std::cout << context.c_str() << std::endl; return runtime->NewObject(); } shared_ptr<JsValue> Getter(const shared_ptr<JsRuntime> &runtime, const shared_ptr<JsValue> &, const std::vector<shared_ptr<JsValue>> &argument, int32_t) { std::string context = GetLogContent(runtime, argument); std::cout << "Getter" << std::endl; return runtime->NewObject(); } int PrintLog([[maybe_unused]] int id, [[maybe_unused]] int level, const char *tag, [[maybe_unused]] const char *fmt, const char *message) { std::cout << tag << "::" << message; return 0; } class TestRuntime { public: TestRuntime() { runtime_ = ArkJSRuntime::GetInstance(); runtime_->SetLogPrint(PrintLog); runtime_->Initialize(""); } ~TestRuntime() { runtime_->Reset(); } inline const shared_ptr<JsRuntime> &operator*() const { return runtime_; } inline const shared_ptr<JsRuntime> &operator->() const { return runtime_; } private: shared_ptr<JsRuntime> runtime_; };
int main() { TestRuntime runtime; RegisterFunctionType func = AppDebugLogPrint; shared_ptr<JsValue> global = runtime->GetGlobal(); shared_ptr<JsValue> logFunc = runtime->NewFunction(func); shared_ptr<JsValue> consoleObj = runtime->NewObject(); global->SetProperty(*runtime, "console", consoleObj); consoleObj->SetProperty(*runtime, "log", logFunc); consoleObj->SetProperty(*runtime, "info", logFunc); shared_ptr<JsValue> getSetTest = runtime->NewObject(); shared_ptr<JsValue> setter = runtime->NewFunction(Setter); shared_ptr<JsValue> getter = runtime->NewFunction(Getter); bool getset = getSetTest->SetAccessorProperty(*runtime, "GetSetTest", getter, setter); std::cout << "SetAccessorProperty result: " << getset << std::endl; global->SetProperty(*runtime, "GetSet", getSetTest); std::vector<shared_ptr<JsValue>> arguments; arguments.emplace_back(runtime->NewString("Hello world")); consoleObj = global->GetProperty(*runtime, "console"); logFunc = consoleObj->GetProperty(*runtime, "log"); shared_ptr<JsValue> testObj = logFunc->Call(*runtime, runtime->NewUndefined(), arguments, 1); shared_ptr<JsValue> testArrayValue = runtime->NewString("1"); shared_ptr<JsValue> testValue = runtime->NewArray(); testValue->SetProperty(*runtime, "0", testArrayValue); testValue->SetProperty(*runtime, "1", testArrayValue); std::cout << "GetProperty test: " << testValue->GetArrayLength(*runtime) << std::endl; testObj->SetProperty(*runtime, "test", testValue); shared_ptr<JsValue> result = testObj->GetProperty(*runtime, "test"); std::cout << "GetProperty test: " << result->IsArray(*runtime) << ";" << result->GetArrayLength(*runtime) << std::endl; std::vector<std::string> argument; runtime->ExecuteJsBin("native.aex"); return 0; }
function_block-full_function
[ { "content": "class JSTaggedValue : public coretypes::TaggedValue {\n\npublic:\n\n static JSTaggedValue Cast(ObjectHeader *object)\n\n {\n\n return JSTaggedValue(object);\n\n }\n\n\n\n JSTaggedValue(void *) = delete;\n\n\n\n constexpr JSTaggedValue() = default;\n\n constexpr explicit JS...
C++
sourceCode/dotNet4.6/ndp/fx/src/data/native/sni/include/sni_servicebindings.hpp
csoap/csoap.github.io
2a8db44eb63425deff147652b65c5912f065334e
#ifndef _SNI_SERVICE_BINDINGS_07_15_2009_ #define _SNI_SERVICE_BINDINGS_07_15_2009_ #include "sni_spn.hpp" class SNI_ServiceBindings { public: static DWORD SetHostNamesAndAcceptedSPNs(__in_ecount_opt(dwcAllowedSPNs) WCHAR **pwszAcceptedSPNs, DWORD dwcAcceptedSPNs); static DWORD SetClusterAddresses(__in ADDRINFOW *paiwClusterAddresses); static DWORD SetClusterNames(__in_z LPWSTR wszClusterHostName); static DWORD MatchSPN(__in_z LPWSTR wszClientSuppliedSPN, __out SNIAuthErrStates *pSSPIFailureState); static void Release(); #ifndef SNIX private: static volatile LONG s_lClusterAddressesInitialized; static bool s_fClusterHostNamesInitialized; static bool s_fWSAStarted; static struct in_addr *s_piaIPv4Address; static DWORD s_dwcIPv4Address; static struct in6_addr *s_pi6aIPv6Address; static DWORD s_dwcIPv6Address; static LPWSTR *s_pwszHostNames; static DWORD s_dwcHostNames; static LPWSTR *s_pwszSPN; static DWORD s_dwcSPN; static DWORD MatchHostOrIPv4Address(__in_z LPWSTR wszHost, __out SNIAuthErrStates *pSSPIFailureState); static DWORD MatchIPv6Address(__in_z LPWSTR wszHost, __out SNIAuthErrStates *pSSPIFailureState); static DWORD MatchApprovedList(__in_z LPWSTR wszSPN); static DWORD MatchAgainstNameList(__in_z LPWSTR wszHost); static DWORD MatchAgainstIpv4AddressList(__in PSOCKADDR_STORAGE psaIpv4Address); static DWORD MatchAgainstIpv6AddressList(__in PSOCKADDR_STORAGE psaIpv6Address); static DWORD InitializeWSA(); static DWORD GetBackConnectionHostNames(__deref_out __nullnullterminated WCHAR **pwszBackConnectionHostNames); static DWORD AllocAndSetHostname(COMPUTER_NAME_FORMAT NameType); static DWORD RepackSzIntoWsz(__in_z LPCSTR szMbcsString); static void ReleaseIPs(); static void ReleaseNames(); inline static void BidTraceAddedIPv4Address(__in struct in_addr *psin_addr); inline static void BidTraceAddedIPv6Address(__in struct in6_addr *psin6_addr); inline static bool IsIn4AddrLoopback(const PSOCKADDR_IN psaiAddress); inline static bool IsIn6AddrLoopback(const PSOCKADDR_IN6 psai6Address); #endif }; #endif
#ifndef _SNI_SERVICE_BINDINGS_07_15_2009_ #define _SNI_SERVICE_BINDINGS_07_15_2009_ #include "sni_spn.hpp" class SNI_ServiceBindings { public: static DWORD SetHostNamesAndAcceptedSPNs(__in_ecount_opt(dwcAllowedSPNs) WCHAR **pwszAcceptedSPNs, DWORD dwcAcceptedSPNs); static DWORD SetClusterAddresses(__in ADDRINFOW *paiwClusterAddresses); static DWORD SetClusterNames(__in_z LPWSTR wszClusterHostName); static DWORD MatchSPN(__in_z LPWSTR ws
stNames); static DWORD AllocAndSetHostname(COMPUTER_NAME_FORMAT NameType); static DWORD RepackSzIntoWsz(__in_z LPCSTR szMbcsString); static void ReleaseIPs(); static void ReleaseNames(); inline static void BidTraceAddedIPv4Address(__in struct in_addr *psin_addr); inline static void BidTraceAddedIPv6Address(__in struct in6_addr *psin6_addr); inline static bool IsIn4AddrLoopback(const PSOCKADDR_IN psaiAddress); inline static bool IsIn6AddrLoopback(const PSOCKADDR_IN6 psai6Address); #endif }; #endif
zClientSuppliedSPN, __out SNIAuthErrStates *pSSPIFailureState); static void Release(); #ifndef SNIX private: static volatile LONG s_lClusterAddressesInitialized; static bool s_fClusterHostNamesInitialized; static bool s_fWSAStarted; static struct in_addr *s_piaIPv4Address; static DWORD s_dwcIPv4Address; static struct in6_addr *s_pi6aIPv6Address; static DWORD s_dwcIPv6Address; static LPWSTR *s_pwszHostNames; static DWORD s_dwcHostNames; static LPWSTR *s_pwszSPN; static DWORD s_dwcSPN; static DWORD MatchHostOrIPv4Address(__in_z LPWSTR wszHost, __out SNIAuthErrStates *pSSPIFailureState); static DWORD MatchIPv6Address(__in_z LPWSTR wszHost, __out SNIAuthErrStates *pSSPIFailureState); static DWORD MatchApprovedList(__in_z LPWSTR wszSPN); static DWORD MatchAgainstNameList(__in_z LPWSTR wszHost); static DWORD MatchAgainstIpv4AddressList(__in PSOCKADDR_STORAGE psaIpv4Address); static DWORD MatchAgainstIpv6AddressList(__in PSOCKADDR_STORAGE psaIpv6Address); static DWORD InitializeWSA(); static DWORD GetBackConnectionHostNames(__deref_out __nullnullterminated WCHAR **pwszBackConnectionHo
random
[]
C++
src/red4ext/FlightSettings.cpp
jackhumbert/flight_control
02938f5a26b3a299ef3d9b9e4d40e9294872a7ee
#include "FlightSettings.hpp" #include "FlightModule.hpp" #include "Utils.hpp" #include "stdafx.hpp" namespace FlightSettings { RED4ext::TTypedClass<FlightSettings> cls("FlightSettings"); RED4ext::CClass *FlightSettings::GetNativeType() { return &cls; } RED4ext::HashMap<RED4ext::CName, float> floats; void GetFloat(RED4ext::IScriptable *aContext, RED4ext::CStackFrame *aFrame, float *aOut, int64_t a4) { RED4ext::CName name; RED4ext::GetParameter(aFrame, &name); aFrame->code++; if (aOut) { *aOut = *floats.Get(name); } } void SetFloat(RED4ext::IScriptable *aContext, RED4ext::CStackFrame *aFrame, void *aOut, int64_t a4) { RED4ext::CName name; float value; RED4ext::GetParameter(aFrame, &name); RED4ext::GetParameter(aFrame, &value); aFrame->code++; floats.InsertOrAssign(name, value); } bool Setup(RED4ext::CGameApplication *aApp) { auto allocator = new RED4ext::Memory::DefaultAllocator(); floats = RED4ext::HashMap<RED4ext::CName, float>(allocator); floats.Insert("airResistance", 0.001); floats.Insert("angularBrakeFactor", 10.0); floats.Insert("angularDampFactor", 3.0); floats.Insert("brakeFactor", 1.2); floats.Insert("brakeOffset", 0.0); floats.Insert("collisionRecoveryDelay", 0.8); floats.Insert("collisionRecoveryDuration", 0.8); floats.Insert("defaultHoverHeight", 3.50); floats.Insert("distance", 0.0); floats.Insert("distanceEase", 0.1); floats.Insert("fwtfCorrection", 0.0); floats.Insert("hoverClamp", 10.0); floats.Insert("hoverFactor", 20.0); floats.Insert("liftFactor", 8.0); floats.Insert("liftFactorDrone", 40.0); floats.Insert("lookAheadMax", 10.0); floats.Insert("lookAheadMin", 1.0); floats.Insert("maxHoverHeight", 7.0); floats.Insert("minHoverHeight", 1.0); floats.Insert("normalEase", 0.3); floats.Insert("pitchAeroCorrectionFactor", 0.25); floats.Insert("pitchCorrectionFactor", 3.0); floats.Insert("pitchDirectionalityFactor", 80.0); floats.Insert("pitchFactorDrone", 5.0); floats.Insert("pitchWithLift", 0.0); floats.Insert("pitchWithSurge", 0.0); floats.Insert("referenceZ", 0.0); floats.Insert("rollCorrectionFactor", 15.0); floats.Insert("rollFactorDrone", 12.0); floats.Insert("rollWithYaw", 0.15); floats.Insert("secondCounter", 0.0); floats.Insert("surgeFactor", 15.0); floats.Insert("surgeOffset", 0.5); floats.Insert("swayFactor", 5.0); floats.Insert("swayWithYaw", 0.5); floats.Insert("thrusterFactor", 0.05); floats.Insert("yawCorrectionFactor", 0.25); floats.Insert("yawD", 3.0); floats.Insert("yawDirectionalityFactor", 50.0); floats.Insert("yawFactor", 5.0); floats.Insert("yawFactorDrone", 5.0); return true; } struct FlightSettingsModule : FlightModule { void Load(const RED4ext::Sdk *aSdk, RED4ext::PluginHandle aHandle) { RED4ext::GameState runningState; runningState.OnEnter = nullptr; runningState.OnUpdate = &Setup; runningState.OnExit = nullptr; aSdk->gameStates->Add(aHandle, RED4ext::EGameStateType::Running, &runningState); } void RegisterTypes() { cls.flags = {.isNative = true}; RED4ext::CRTTISystem::Get()->RegisterType(&cls); } void PostRegisterTypes() { auto rtti = RED4ext::CRTTISystem::Get(); auto scriptable = rtti->GetClass("IScriptable"); cls.parent = scriptable; auto getFloat = RED4ext::CClassStaticFunction::Create(&cls, "GetFloat", "GetFloat", &GetFloat, {.isNative = true, .isStatic = true}); cls.RegisterFunction(getFloat); auto setFloat = RED4ext::CClassStaticFunction::Create(&cls, "SetFloat", "SetFloat", &SetFloat, {.isNative = true, .isStatic = true}); cls.RegisterFunction(setFloat); } }; REGISTER_FLIGHT_MODULE(FlightSettingsModule); }
#include "FlightSettings.hpp" #include "FlightModule.hpp" #include "Utils.hpp" #include "stdafx.hpp" namespace FlightSettings { RED4ext::TTypedClass<FlightSettings> cls("FlightSettings"); RED4ext::CClass *FlightSettings::GetNativeType() { return &cls; } RED4ext::HashMap<RED4ext::CName, float> floats; void GetFloat(RED4ext::IScriptable *aContext, RED4ext::CStackFrame *aFrame, float *aOut, int64_t a4) { RED4ext::CName name; RED4ext::GetParameter(aFrame, &name); aFrame->code++; if (aOut) { *aOut = *floats.Get(name); } } void SetFloat(RED4ext::IScriptable *aContext, RED4ext::CStackFrame *aFrame, void *aOut, int64_t a4) { RED4ext::CName name; float value; RED4ext::GetParameter(aFrame, &name); RED4ext::GetParameter(aFrame, &value); aFrame->code++; floats.InsertOrAssign(name, value); } bool Setup(RED4ext::CGameApplication *aApp) { auto allocator = new RED4ext::Memory::DefaultAllocator(); floats = RED4ext::HashMap<RED4ext::CName, float>(allocator); floats.Insert("airResistance", 0.001); floats.Insert("angularBrakeFactor", 10.0); floats.Insert("angularDampFactor", 3.0); floats.Insert("brakeFactor", 1.2); floats.Insert("brakeOffset", 0.0); floats.Insert("collisionRecoveryDelay", 0.8); floats.Insert("collisionRecoveryDuration", 0.8); floats.Insert("defaultHoverHeight", 3.50); floats.Insert("distance", 0.0); floats.Insert("distanceEase", 0.1); floats.Insert("fwtfCorrection", 0.0); floats.Insert("hoverClamp", 10.0); floats.Insert("hoverFactor", 20.0); floats.Insert("liftFactor", 8.0); floats.Insert("liftFactorDrone", 40.0); floats.Insert("lookAheadMax", 10.0); floats.Insert("lookAheadMin", 1.0); floats.Insert("maxHoverHeight", 7.0); floats.Insert("minHoverHeight", 1.0); floats.Insert("normalEase", 0.3); floats.Insert("pitchAeroCorrectionFactor", 0.25); floats.Insert("pitchCorrectionFactor", 3.0); floats.Insert("pitchDirectionalityFactor", 80.0); floats.Insert("pitchFactorDrone", 5.0); floats.Insert("pitchWithLift", 0.0); floats.Insert("pitchWithSurge", 0.0); floats.Insert("referenceZ", 0.0); floats.Insert("rollCorrectionFactor", 15.0); floats.Insert("rollFactorDrone", 12.0); floats.Insert("rollWithYaw", 0.15); floats.Insert("secondCounter", 0.0); floats.Insert("surgeFactor", 15.0); floats.Insert("surgeOffset", 0.5); floats.Insert("swayFactor", 5.0); floats.Insert("swayWithYaw", 0.5); floats.Insert("thrusterFactor", 0.05); floats.Insert("yawCorrectionFactor", 0.25); floats.Insert("yawD", 3.0); floats.Insert("yawDirectionalityFactor", 50.0); floats.Insert("yawFactor", 5.0); floats.Insert("yawF
auto setFloat = RED4ext::CClassStaticFunction::Create(&cls, "SetFloat", "SetFloat", &SetFloat, {.isNative = true, .isStatic = true}); cls.RegisterFunction(setFloat); } }; REGISTER_FLIGHT_MODULE(FlightSettingsModule); }
actorDrone", 5.0); return true; } struct FlightSettingsModule : FlightModule { void Load(const RED4ext::Sdk *aSdk, RED4ext::PluginHandle aHandle) { RED4ext::GameState runningState; runningState.OnEnter = nullptr; runningState.OnUpdate = &Setup; runningState.OnExit = nullptr; aSdk->gameStates->Add(aHandle, RED4ext::EGameStateType::Running, &runningState); } void RegisterTypes() { cls.flags = {.isNative = true}; RED4ext::CRTTISystem::Get()->RegisterType(&cls); } void PostRegisterTypes() { auto rtti = RED4ext::CRTTISystem::Get(); auto scriptable = rtti->GetClass("IScriptable"); cls.parent = scriptable; auto getFloat = RED4ext::CClassStaticFunction::Create(&cls, "GetFloat", "GetFloat", &GetFloat, {.isNative = true, .isStatic = true}); cls.RegisterFunction(getFloat);
random
[ { "content": " FMOD_DSP_ALLOC_FUNC alloc;\n", "file_path": "deps/fmod/include/fmod_dsp.h", "rank": 0, "score": 130866.68190463846 }, { "content": " FMOD_CODEC_ALLOC_FUNC alloc;\n", "file_path": "deps/fmod/include/fmod_codec.h", "rank": 1, "score": 130...
C++
diffkemp/simpll/Utils.cpp
tmalecova/diffkemp
226166cec9044ff23753e7d74b49d2272677c0d6
#include "Utils.h" #include "Config.h" #include <llvm/IR/Instructions.h> #include <llvm/IR/Module.h> #include <llvm/IR/Operator.h> #include <llvm/Support/LineIterator.h> #include <llvm/Support/MemoryBuffer.h> #include <llvm/Support/Path.h> #include <llvm/Support/raw_ostream.h> #include <set> #include <iostream> #include <llvm/IR/PassManager.h> #include <llvm/Passes/PassBuilder.h> #include <llvm/Transforms/Scalar/DCE.h> #include <llvm/Transforms/Scalar/NewGVN.h> #include <llvm/Transforms/Scalar/SimplifyCFG.h> #include <llvm/Transforms/Utils/Cloning.h> const Function *getCalledFunction(const Value *CalledValue) { const Function *fun = dyn_cast<Function>(CalledValue); if (!fun) { if (auto BitCast = dyn_cast<BitCastOperator>(CalledValue)) { fun = dyn_cast<Function>(BitCast->getOperand(0)); } } return fun; } std::string typeName(const Type *Type) { std::string result; raw_string_ostream rso(result); Type->print(rso); rso.str(); result.erase(std::remove(result.begin(), result.end(), ' '), result.end()); std::replace(result.begin(), result.end(), '(', '$'); std::replace(result.begin(), result.end(), ')', '$'); std::replace(result.begin(), result.end(), ',', '_'); return result; } void deleteAliasToFun(Module &Mod, Function *Fun) { std::vector<GlobalAlias *> toRemove; for (auto &alias : Mod.aliases()) { if (alias.getAliasee() == Fun) toRemove.push_back(&alias); } for (auto &alias : toRemove) { alias->replaceAllUsesWith(Fun); alias->eraseFromParent(); } } bool hasSuffix(std::string Name) { size_t dotPos = Name.find_last_of('.'); return dotPos != std::string::npos && Name.find_last_not_of("0123456789.") < dotPos; } std::string dropSuffix(std::string Name) { return Name.substr(0, Name.find_last_of('.')); } std::string joinPath(StringRef DirName, StringRef FileName) { return FileName.startswith(DirName) ? FileName.str() : DirName.str() + sys::path::get_separator().str() + FileName.str(); } std::string getFileForFun(Function *Fun) { if (auto *SubProgram = Fun->getSubprogram()) { if (auto *File = SubProgram->getFile()) return joinPath(File->getDirectory(), File->getFilename()); } return ""; } bool searchCallStackRec(Function *Src, Function *Dest, CallStack &callStack, std::set<Function *> &visited) { visited.insert(Src); for (auto &BB : *Src) { for (auto &Inst : BB) { std::vector<Function *> calledFuns; if (CallInst *Call = dyn_cast<CallInst>(&Inst)) { if (auto c = Call->getCalledFunction()) calledFuns.push_back(c); } for (auto &Op : Inst.operands()) { if (isa<Function>(Op)) calledFuns.push_back(dyn_cast<Function>(Op)); } for (Function *called : calledFuns) { if (called && visited.find(called) == visited.end()) { auto loc = Inst.getDebugLoc(); if (!loc) continue; callStack.push_back(CallInfo(called->getName().str(), getFileForFun(Src), loc.getLine())); if (called == Dest) return true; else { bool found = searchCallStackRec(called, Dest, callStack, visited); if (found) return true; else callStack.pop_back(); } } } } } return false; } CallStack getCallStack(Function &Src, Function &Dest) { CallStack callStack; std::set<Function *> visited; searchCallStackRec(&Src, &Dest, callStack, visited); return callStack; } bool hasSideEffect(const Function &Fun, std::set<const Function *> &Visited) { if (Fun.isDeclaration()) { return !(Fun.getIntrinsicID() == Intrinsic::dbg_declare || Fun.getIntrinsicID() == Intrinsic::dbg_value || Fun.getIntrinsicID() == Intrinsic::expect); } Visited.insert(&Fun); for (auto &BB : Fun) { for (auto &Inst : BB) { if (isa<StoreInst>(&Inst)) return true; if (auto Call = dyn_cast<CallInst>(&Inst)) { const Function *called = Call->getCalledFunction(); if (!called) return true; if (Visited.find(called) != Visited.end()) continue; if (hasSideEffect(*called, Visited)) return true; } } } return false; } bool hasSideEffect(const Function &Fun) { std::set<const Function *> visited; return hasSideEffect(Fun, visited); } bool isAllocFunction(const Function &Fun) { return Fun.getName() == "kzalloc" || Fun.getName() == "__kmalloc" || Fun.getName() == "kmalloc"; } std::string valueAsString(const Constant *Val) { if (auto *IntVal = dyn_cast<ConstantInt>(Val)) { return std::to_string(IntVal->getSExtValue()); } return ""; } StructType *getStructType(const Value *Value) { StructType *Type = nullptr; if (auto PtrTy = dyn_cast<PointerType>(Value->getType())) { if (auto *StructTy = dyn_cast<StructType>(PtrTy->getElementType())) { Type = StructTy; } else if (auto *BitCast = dyn_cast<BitCastInst>(Value)) { if (auto *SrcPtrTy = dyn_cast<PointerType>(BitCast->getSrcTy())) { if (auto *SrcStructTy = dyn_cast<StructType>(SrcPtrTy->getElementType())) Type = SrcStructTy; } } } else Type = dyn_cast<StructType>(Value->getType()); return Type; } void simplifyFunction(Function *Fun) { PassBuilder pb; FunctionPassManager fpm(false); FunctionAnalysisManager fam(false); pb.registerFunctionAnalyses(fam); fpm.addPass(SimplifyCFGPass {}); fpm.addPass(DCEPass {}); fpm.addPass(NewGVNPass {}); fpm.run(*Fun, fam); } AttributeList cleanAttributeList(AttributeList AL) { AttributeList NewAttrList; std::vector<AttributeList::AttrIndex> indices { AttributeList::FirstArgIndex, AttributeList::FunctionIndex, AttributeList::ReturnIndex }; for (AttributeList::AttrIndex i : indices) { AttributeSet AttrSet = AL.getAttributes(i); if (AttrSet.getNumAttributes() != 0) { AttrBuilder AB; for (const Attribute &A : AttrSet) AB.addAttribute(A); NewAttrList = NewAttrList.addAttributes( AL.getContext(), i, AB); } } return NewAttrList; } CallInst *findCallInst(const CallInst *Call, Function *Fun) { if (!Call) return nullptr; for (auto &BB : *Fun) { for (auto &Inst : BB) { if (&Inst == Call) return dyn_cast<CallInst>(&Inst); } } return nullptr; } std::string getSourceFilePath(DIScope *Scope) { return joinPath(Scope->getDirectory(), Scope->getFilename()); } bool isValidCharForIdentifier(char ch) { if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_') return true; else return false; } bool isValidCharForIdentifierStart(char ch) { if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || ch == '_') return true; else return false; } void findAndReplace(std::string &input, std::string find, std::string replace) { int position = 0; while ((position = input.find(find, position)) != std::string::npos) { input.replace(position, find.length(), replace); position += replace.length(); } }
#include "Utils.h" #include "Config.h" #include <llvm/IR/Instructions.h> #include <llvm/IR/Module.h> #include <llvm/IR/Operator.h> #include <llvm/Support/LineIterator.h> #include <llvm/Support/MemoryBuffer.h> #include <llvm/Support/Path.h> #include <llvm/Support/raw_ostream.h> #include <set> #include <iostream> #include <llvm/IR/PassManager.h> #include <llvm/Passes/PassBuilder.h> #include <llvm/Transforms/Scalar/DCE.h> #include <llvm/Transforms/Scalar/NewGVN.h> #include <llvm/Transforms/Scalar/SimplifyCFG.h> #include <llvm/Transforms/Utils/Cloning.h> const Function *getCalledFunction(const Value *CalledValue) { const Function *fun = dyn_cast<Function>(CalledValue); if (!fun) { if (auto BitCast = dyn_cast<BitCastOperator>(CalledValue)) { fun = dyn_cast<Function>(BitCast->getOperand(0)); } } return fun; } std::string typeName(const Type *Type) { std::string result; raw_string_ostream rso(result); Type->print(rso); rso.str(); result.erase(std::remove(result.begin(), result.end(), ' '), result.end()); std::replace(result.begin(), result.end(), '(', '$'); std::replace(result.begin(), result.end(), ')', '$'); std::replace(result.begin(), result.end(), ',', '_'); return result; } void deleteAliasToFun(Module &Mod, Function *Fun) { std::vector<GlobalAlias *> toRemove; for (auto &alias : Mod.aliases()) { if (alias.getAliasee() == Fun) toRemove.push_back(&alias); } for (auto &alias : toRemove) { alias->replaceAllUsesWith(Fun); alias->eraseFromParent(); } } bool hasSuffix(std::string Name) { size_t dotPos = Name.find_last_of('.'); return dotPos != std::string::npos && Name.find_last_not_of("0123456789.") < dotPos; } std::string dropSuffix(std::string Name) { return Name.substr(0, Name.find_last_of('.')); } std::string joinPath(StringRef DirName, StringRef FileName) { return FileName.startswith(DirName) ? FileName.str() : DirName.str() + sys::path::get_separator().str() + FileName.str(); } std::string getFileForFun(Function *Fun) { if (auto *SubProgram = Fun->getSubprogram()) { if (auto *File = SubProgram->getFile()) return joinPath(File->getDirectory(), File->getFilename()); } return ""; } bool searchCallStackRec(Function *Src, Function *Dest, CallStack &callStack, std::set<Function *> &visited) { visited.insert(Src); for (auto &BB : *Src) { for (auto &Inst : BB) { std::vector<Function *> calledFuns; if (CallInst *Call = dyn_cast<CallInst>(&Inst)) { if (auto c = Call->getCalledFunction()) calledFuns.push_back(c); } for (auto &Op : Inst.operands()) { if (isa<Function>(Op)) calledFuns.push_back(dyn_cast<Function>(Op)); } for (Function *called : calledFuns) { if (called && visited.find(called) == visited.end()) { auto loc = Inst.getDebugLoc(); if (!loc) continue; callStack.push_back(CallInfo(called->getName().str(), getFileForFun(Src), loc.getLine())); if (called == Dest) return true; else { bool found = searchCallStackRec(called, Dest, callStack, visited); if (found) return true; else callStack.pop_back(); } } } } } return false; } CallStack getCallStack(Function &Src, Function &Dest) { CallStack callStack; std::set<Function *> visited; searchCallStackRec(&Src, &Dest, callStack, visited); return callStack; } bool hasSideEffect(const Function &Fun, std::set<const Function *> &Visited) { if (Fun.isDeclaration()) { return !(Fun.getIntrinsicID() == Intrinsic::dbg_declare || Fun.getIntrinsicID() == Intrinsic::dbg_value || Fun.getIntrinsicID() == Intrinsic::expect); } Visited.insert(&Fun); for (auto &BB : Fun) { for (auto &Inst : BB) { if (isa<StoreInst>(&Inst)) return true; if (auto Call = dyn_cast<CallInst>(&Inst)) { const Function *called = Call->getCalledFunction(); if (!called) return true; if (Visited.find(called) != Visited.end()) continue; if (hasSideEffect(*called, Visited)) return true; } } } return false; } bool hasSideEffect(const Function &Fun) { std::set<const Function *> visited; return hasSideEffect(Fun, visited); } bool isAllocFunction(const Function &Fun) { return Fun.getName() == "kzalloc" || Fun.getName() == "__kmalloc" || Fun.getName() == "kmalloc"; } std::string valueAsString(const Constant *Val) { if (auto *IntVal = dyn_cast<ConstantInt>(Val)) { return std::to_string(IntVal->getSExtValue()); } return ""; } StructType *getStructType(const Value *Value) { StructType *Type = nullptr;
return Type; } void simplifyFunction(Function *Fun) { PassBuilder pb; FunctionPassManager fpm(false); FunctionAnalysisManager fam(false); pb.registerFunctionAnalyses(fam); fpm.addPass(SimplifyCFGPass {}); fpm.addPass(DCEPass {}); fpm.addPass(NewGVNPass {}); fpm.run(*Fun, fam); } AttributeList cleanAttributeList(AttributeList AL) { AttributeList NewAttrList; std::vector<AttributeList::AttrIndex> indices { AttributeList::FirstArgIndex, AttributeList::FunctionIndex, AttributeList::ReturnIndex }; for (AttributeList::AttrIndex i : indices) { AttributeSet AttrSet = AL.getAttributes(i); if (AttrSet.getNumAttributes() != 0) { AttrBuilder AB; for (const Attribute &A : AttrSet) AB.addAttribute(A); NewAttrList = NewAttrList.addAttributes( AL.getContext(), i, AB); } } return NewAttrList; } CallInst *findCallInst(const CallInst *Call, Function *Fun) { if (!Call) return nullptr; for (auto &BB : *Fun) { for (auto &Inst : BB) { if (&Inst == Call) return dyn_cast<CallInst>(&Inst); } } return nullptr; } std::string getSourceFilePath(DIScope *Scope) { return joinPath(Scope->getDirectory(), Scope->getFilename()); } bool isValidCharForIdentifier(char ch) { if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_') return true; else return false; } bool isValidCharForIdentifierStart(char ch) { if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || ch == '_') return true; else return false; } void findAndReplace(std::string &input, std::string find, std::string replace) { int position = 0; while ((position = input.find(find, position)) != std::string::npos) { input.replace(position, find.length(), replace); position += replace.length(); } }
if (auto PtrTy = dyn_cast<PointerType>(Value->getType())) { if (auto *StructTy = dyn_cast<StructType>(PtrTy->getElementType())) { Type = StructTy; } else if (auto *BitCast = dyn_cast<BitCastInst>(Value)) { if (auto *SrcPtrTy = dyn_cast<PointerType>(BitCast->getSrcTy())) { if (auto *SrcStructTy = dyn_cast<StructType>(SrcPtrTy->getElementType())) Type = SrcStructTy; } } } else Type = dyn_cast<StructType>(Value->getType());
if_condition
[ { "content": "class CalledFunctionsAnalysis\n\n : public AnalysisInfoMixin<CalledFunctionsAnalysis> {\n\n public:\n\n using Result = std::set<const Function *>;\n\n Result run(Module &Mod,\n\n AnalysisManager<Module, Function *> &mam,\n\n Function *Main);\n\n\n\n prote...
C++
src/EDepSimModuleBuilder.hh
andrewmogan/edep-sim
4e9923ccba8b2f65f47b72cbb41ed683f19f1123
#ifndef EDepSim_ModuleBuilder_hh_seen #define EDepSim_ModuleBuilder_hh_seen #include <sstream> #include <G4ThreeVector.hh> class G4LogicalVolume; #include "EDepSimBuilder.hh" #include "EDepSimComponentBuilder.hh" namespace EDepSim {class ModuleBuilder;} class EDepSim::ModuleBuilder : public EDepSim::Builder { public: ModuleBuilder(G4String n, EDepSim::UserDetectorConstruction* c) : EDepSim::Builder(n,c) {Init();}; ModuleBuilder(G4String n, EDepSim::Builder* p) : EDepSim::Builder(n,p) { Init();}; virtual ~ModuleBuilder(); virtual G4LogicalVolume *GetPiece(void); void SetWidth(double w) {fWidth = w;} double GetWidth(void) {return fWidth;} void SetHeight(double w) {fHeight = w;} double GetHeight(void) {return fHeight;} double GetLength(void) {return fLength;}; void ClearComponentList(void); void AddComponent(G4String m); void SetRepetitions(int r, int c); void SetModuleCompTrans(int m, int cPerM, int c, double transX, double transY); void SetTargetLength(double w) {fTargetLength = w;} double GetTargetLength(void) {return fTargetLength;} void SetFixLength(bool f) {fFixLength = f;} bool GetFixLength(void) {return fFixLength;} void SetXPosition(double x) {xPosition = x;} double GetXPosition() {return xPosition;} void SetYPosition(double y) {yPosition = y;} double GetYPosition() {return yPosition;} double GetXmaxTranslation() {return xmax;} double GetXminTranslation() {return xmin;} double GetYmaxTranslation() {return ymax;} double GetYminTranslation() {return ymin;} private: double fWidth; double fHeight; double fLength; double fTargetLength; bool fFixLength; double xPosition; double yPosition; std::pair<double, double> fPair; typedef std::vector<EDepSim::ComponentBuilder*> PartsList; PartsList* fPartsList; typedef std::vector<std::pair<double, double> > TransList; TransList* fTransList; G4double xmax, xmin, ymax, ymin; void Init(void); }; namespace EDepSim {class ModuleBuilderMessenger;} class EDepSim::ModuleBuilderMessenger: public EDepSim::BuilderMessenger { private: EDepSim::ModuleBuilder* fBuilder; G4UIcmdWithoutParameter* fClearCMD; G4UIcmdWithAString* fAddCMD; G4UIcommand* fRepeatCMD; G4UIcmdWithADoubleAndUnit* fWidthCMD; G4UIcmdWithADoubleAndUnit* fHeightCMD; public: ModuleBuilderMessenger(EDepSim::ModuleBuilder* c, const char* guide=NULL) : EDepSim::BuilderMessenger(c,guide), fBuilder(c) { fClearCMD = new G4UIcmdWithoutParameter(CommandName("clear"),this); fClearCMD->SetGuidance("Clear the component list for the FG tracker."); fAddCMD = new G4UIcmdWithAString(CommandName("add"),this); fAddCMD->SetGuidance("Add the named component to the module." " Components are added from upstream" " to downstream."); fAddCMD->SetParameterName("Component", false); fRepeatCMD = new G4UIcommand(CommandName("repeat"),this); fRepeatCMD->SetGuidance("Times to repeat the last components."); G4UIparameter* repParam = new G4UIparameter('i'); repParam->SetParameterName("Repetitions"); fRepeatCMD->SetParameter(repParam); G4UIparameter* cntParam = new G4UIparameter('i'); cntParam->SetParameterName("Count"); fRepeatCMD->SetParameter(cntParam); fWidthCMD = new G4UIcmdWithADoubleAndUnit(CommandName("width"),this); fWidthCMD->SetGuidance("Set the width of the module."); fWidthCMD->SetParameterName("Width",false); fWidthCMD->SetUnitCategory("Length"); fHeightCMD = new G4UIcmdWithADoubleAndUnit(CommandName("height"),this); fHeightCMD->SetGuidance("Set the height of the module."); fHeightCMD->SetParameterName("Height",false); fHeightCMD->SetUnitCategory("Length"); }; virtual ~ModuleBuilderMessenger() { delete fClearCMD; delete fAddCMD; delete fRepeatCMD; delete fWidthCMD; delete fHeightCMD; }; void SetNewValue(G4UIcommand *cmd, G4String val) { if (cmd==fClearCMD) { fBuilder->ClearComponentList(); } else if (cmd==fAddCMD) { fBuilder->AddComponent(val); } else if (cmd==fRepeatCMD) { int repetitions; int count = 1; std::istringstream inputs((char*)val.c_str()); inputs >> repetitions >> count; fBuilder->SetRepetitions(repetitions,count); } else if (cmd==fWidthCMD) { fBuilder->SetWidth(fWidthCMD->GetNewDoubleValue(val)); } else if (cmd==fHeightCMD) { fBuilder->SetHeight(fHeightCMD->GetNewDoubleValue(val)); } else { EDepSim::BuilderMessenger::SetNewValue(cmd,val); } }; }; #endif
#ifndef EDepSim_ModuleBuilder_hh_seen #define EDepSim_ModuleBuilder_hh_seen #include <sstream> #include <G4ThreeVector.hh> class G4LogicalVolume; #include "EDepSimBuilder.hh" #include "EDepSimComponentBuilder.hh" namespace EDepSim {class ModuleBuilder;} class EDepSim::ModuleBuilder : public EDepSim::Builder { public: ModuleBuilder(G4String n, EDepSim::UserDetectorConstruction* c) : EDepSim::Builder(n,c) {Init();}; ModuleBuilder(G4String n, EDepSim::Builder* p) : EDepSim::Builder(n,p) { Init();}; virtual ~ModuleBuilder(); virtual G4LogicalVolume *GetPiece(void); void SetWidth(double w) {fWidth = w;} double GetWidth(void) {return fWidth;} void SetHeight(double w) {fHeight = w;} double GetHeight(void) {return fHeight;} double GetLength(void) {return fLength;}; void ClearComponentList(void); void AddComponent(G4String m); void SetRepetitions(int r, int c); void SetModuleCompTrans(int m, int cPerM, int c, double transX, double transY); void SetTargetLength(double w) {fTargetLength = w;} double GetTargetLength(void) {return fTargetLength;} void SetFixLength(bool f) {fFixLength = f;} bool GetFixLength(void) {return fFixLength;} void SetXPosition(double x) {xPosition = x;} double GetXPosition() {return xPosition;} void SetYPosition(double y) {yPosition = y;} double GetYPosition() {return yPosition;} double GetXmaxTranslation() {return xmax;} double GetXminTranslation() {return xmin;} double GetYmaxTranslation() {return ymax;} double GetYminTranslation() {return ymin;} private: double fWidth; double fHeight; double fLength; double fTargetLength; bool fFixLength; double xPosition; double yPosition; std::pair<double, double> fPair; typedef std::vector<EDepSim::ComponentBuilder*> PartsList; PartsList* fPartsList; typedef std::vector<std::pair<double, double> > TransList; TransList* fTransList; G4double xmax, xmin, ymax, ymin; void Init(void); }; namespace EDepSim {class ModuleBuilderMessenger;} class EDepSim::ModuleBuilderMessenger: public EDepSim::BuilderMessenger { private: EDepSim::ModuleBuilder* fBuilder; G4UIcmdWithoutParameter* fClearCMD; G4UIcmdWithAString* fAddCMD; G4UIcommand* fRepeatCMD; G4UIcmdWithADoubleAndUnit* fWidthCMD; G4UIcmdWithADoubleAndUnit* fHeightCMD; public:
; virtual ~ModuleBuilderMessenger() { delete fClearCMD; delete fAddCMD; delete fRepeatCMD; delete fWidthCMD; delete fHeightCMD; }; void SetNewValue(G4UIcommand *cmd, G4String val) { if (cmd==fClearCMD) { fBuilder->ClearComponentList(); } else if (cmd==fAddCMD) { fBuilder->AddComponent(val); } else if (cmd==fRepeatCMD) { int repetitions; int count = 1; std::istringstream inputs((char*)val.c_str()); inputs >> repetitions >> count; fBuilder->SetRepetitions(repetitions,count); } else if (cmd==fWidthCMD) { fBuilder->SetWidth(fWidthCMD->GetNewDoubleValue(val)); } else if (cmd==fHeightCMD) { fBuilder->SetHeight(fHeightCMD->GetNewDoubleValue(val)); } else { EDepSim::BuilderMessenger::SetNewValue(cmd,val); } }; }; #endif
ModuleBuilderMessenger(EDepSim::ModuleBuilder* c, const char* guide=NULL) : EDepSim::BuilderMessenger(c,guide), fBuilder(c) { fClearCMD = new G4UIcmdWithoutParameter(CommandName("clear"),this); fClearCMD->SetGuidance("Clear the component list for the FG tracker."); fAddCMD = new G4UIcmdWithAString(CommandName("add"),this); fAddCMD->SetGuidance("Add the named component to the module." " Components are added from upstream" " to downstream."); fAddCMD->SetParameterName("Component", false); fRepeatCMD = new G4UIcommand(CommandName("repeat"),this); fRepeatCMD->SetGuidance("Times to repeat the last components."); G4UIparameter* repParam = new G4UIparameter('i'); repParam->SetParameterName("Repetitions"); fRepeatCMD->SetParameter(repParam); G4UIparameter* cntParam = new G4UIparameter('i'); cntParam->SetParameterName("Count"); fRepeatCMD->SetParameter(cntParam); fWidthCMD = new G4UIcmdWithADoubleAndUnit(CommandName("width"),this); fWidthCMD->SetGuidance("Set the width of the module."); fWidthCMD->SetParameterName("Width",false); fWidthCMD->SetUnitCategory("Length"); fHeightCMD = new G4UIcmdWithADoubleAndUnit(CommandName("height"),this); fHeightCMD->SetGuidance("Set the height of the module."); fHeightCMD->SetParameterName("Height",false); fHeightCMD->SetUnitCategory("Length"); }
function_block-full_function
[ { "content": "class EDepSim::DokeBirks : public G4VRestDiscreteProcess //class definition\n\n{\n\npublic:\n\n\n\n DokeBirks(const G4String& processName = \"Doke-Birks\",\n\n G4ProcessType type = fElectromagnetic);\n\n ~DokeBirks();\n\n\n\n /// Determine which particles this process sho...
C++
Classes/Bmob/baseobject/bmobobject.cpp
isuhao/RaidenFree
1811a79d6704fb58e2abc58fb3feaad79af33841
#include "bmobobject.h" #include "network/HttpClient.h" #include "network/HttpResponse.h" #include "../util/bmobstrutil.h" using namespace network; BmobObject::BmobObject(){ this->m_pSaveDelegate = NULL; this->m_pUpdateDelegate = NULL; this->m_pSaveDelegate = NULL; } BmobObject::BmobObject(string tableName){ this->m_tableName = tableName; this->m_pSaveDelegate = NULL; this->m_pUpdateDelegate = NULL; this->m_pSaveDelegate = NULL; } BmobObject::~BmobObject(){ } void BmobObject::save(BmobSaveDelegate* delegate){ if (!BmobSDKInit::isInitialize()) { return ; } _opType = HTTP_OP_Type::_bHTTP_SAVE; this->m_pSaveDelegate = delegate; this->m_url = BmobSDKInit::URL + m_tableName; this->send(); } void BmobObject::increment(string column,int value ){ } void BmobObject::setValue(string key,cocos2d::Ref *object){ this->enParamsToHttp(key,object); } void BmobObject::setValue(string key,__Array* array){ if (array == NULL || key.empty()) { return ; } __Dictionary* dict = __Dictionary::create(); string op = "AddUnique"; dict->setObject(__String::createWithFormat("%s",op.c_str()),"__op"); dict->setObject(array,"objects"); this->enParamsToHttp(key,dict); } void BmobObject::update(BmobUpdateDelegate* delegate){ this->update(this->getObjectId(),delegate); } void BmobObject::update(string objectId,BmobUpdateDelegate* delegate){ if (objectId.empty()) { return ; } _opType = HTTP_OP_Type::_bHTTP_UPDATE; this->m_pUpdateDelegate = delegate; this->m_url = BmobSDKInit::URL + m_tableName ; if (!objectId.empty()) { this->m_url += + "/" + objectId; } this->send(HttpRequest::Type::PUT); } void BmobObject::remove(string name){ if (name.empty()) { return ; } this->clear(); __Dictionary* pDict = __Dictionary::create(); __String* pValue2 = __String::create("Delete"); pDict->setObject(pValue2, "__op"); this->enParamsToHttp(name,pDict); } void BmobObject::removeAll(string name,__Array* array){ if (array == NULL) { return ; } __Dictionary* dict = __Dictionary::create(); string op = "Remove"; dict->setObject(__String::createWithFormat("%s",op.c_str()),"__op"); dict->setObject(array,"objects"); this->enParamsToHttp(name,dict); } void BmobObject::del(BmobDeleteDelegate* delegate){ _opType = HTTP_OP_Type::_bHTTP_DELETE; this->m_pDeleteDelegate = delegate; this->m_url = BmobSDKInit::URL + m_tableName + "/" + m_objectId; this->send(HttpRequest::Type::DELETE); } void BmobObject::del(string objectId,BmobDeleteDelegate* delegate){ this->m_objectId = objectId; this->del(delegate); } void BmobObject::add(string column,Ref* object){ if (object == NULL) { return ; } __Dictionary* dict = __Dictionary::create(); string op = "Add"; __Array* array = __Array::create(); array->addObject(object); dict->setObject(__String::createWithFormat("%s",op.c_str()),"__op"); dict->setObject(array,"objects"); this->enParamsToHttp(column,dict); } void BmobObject::add(string column,__Array* array){ if (column.empty() || array == NULL) { return ; } __Dictionary* dict = __Dictionary::create(); string op = "Add"; dict->setObject(__String::createWithFormat("%s",op.c_str()),"__op"); dict->setObject(array,"objects"); this->enParamsToHttp(column,dict); } void BmobObject::enParamsToHttp(string key,cocos2d::Ref *object){ this->m_mapData.insert(pair<string, Ref *>(key, object)); } Ref* BmobObject::getParams(string key){ std::map<string, Ref *>::iterator it = m_mapData.find(key); if (it!=m_mapData.end()) { return it->second; } return NULL; } void BmobObject::setHeader(vector<string> v){ this->m_header = v; } vector<string> BmobObject::getHeader(){ if (this->m_header.empty()) { vector<string> header_list; header_list.push_back("X-Bmob-Application-Id:"+BmobSDKInit::APP_ID); header_list.push_back("X-Bmob-REST-API-Key:"+BmobSDKInit::APP_KEY); header_list.push_back("Content-Type: application/json"); if (strcmp(m_tableName.c_str(),BmobSDKInit::USER_TABLE.c_str()) == 0) { if (!m_session.empty()) { string se = "X-Bmob-Session-Token:" + m_session; header_list.push_back(se); } } this->m_header = header_list; } return this->m_header; } void BmobObject::enJson(Json::Value* value){ BmobJsonUtil::dictionary2Json(value, &(this->m_mapData)); } void BmobObject::deJson(Json::Value* value){ this->clear(); BmobJsonUtil::json2Dictionary(value, &(this->m_mapData)); this->m_objectId = (*value)["objectId"].asString(); this->m_createdAt = (*value)["createdAt"].asString(); this->m_updatedAt = (*value)["updatedAt"].asString(); } void BmobObject::send(){ this->send(HttpRequest::Type::POST); } void BmobObject::send(HttpRequest::Type type){ HttpRequest* req = new HttpRequest; req->setUrl(this->m_url.c_str()); req->setResponseCallback(this, cocos2d::SEL_CallFuncND(&BmobObject::onHttpRequestCompleted)); req->setRequestType(type); req->setHeaders(getHeader()); Json::Value params; std::string data; this->enJson(&params); data = params.toStyledString(); req->setRequestData(data.c_str(), strlen(data.c_str())); cout<<"request data is:"<<data<<endl; HttpClient::getInstance()->setTimeoutForConnect(3000); HttpClient::getInstance()->setTimeoutForRead(3000); HttpClient::getInstance()->send(req); req->release(); } void BmobObject::onHttpRequestCompleted(cocos2d::Node *pSender,void *data){ HttpResponse *response = (HttpResponse *)data; if (!response->isSucceed()) { int errorCode = response->getResponseCode(); string errorInfo = response->getErrorBuffer(); switch(_opType){ case HTTP_OP_Type::_bHTTP_SAVE:{ if (m_pSaveDelegate != NULL) { this->m_pSaveDelegate->onSaveError(errorCode,errorInfo.c_str()); } }break; case HTTP_OP_Type::_bHTTP_UPDATE:{ if (m_pUpdateDelegate != NULL) { this->m_pUpdateDelegate->onUpdateError(errorCode,errorInfo.c_str()); } }break; case HTTP_OP_Type::_bHTTP_DELETE:{ if (m_pDeleteDelegate != NULL) { this->m_pDeleteDelegate->onDeleteError(errorCode,errorInfo.c_str()); } }break; case HTTP_OP_Type::_bHTTP_RESET:{ if (m_pResetDelegate != NULL) { this->m_pResetDelegate->onResetError(errorCode,errorInfo.c_str()); } }break; case HTTP_OP_Type::_bHTTP_REQUEST_CODE:{ if(m_pRequestSMSCodeDelegate != NULL){ this->m_pRequestSMSCodeDelegate->onRequestDone(errorCode,errorInfo.c_str()); } }break; case HTTP_OP_Type::_bHTTP_RESET_BY_CODE:{ if(m_pResetByMSMCodeDelegate != NULL){ this->m_pResetByMSMCodeDelegate->onResetDone(errorCode,errorInfo.c_str()); } }break; case HTTP_OP_Type::_bHTTP_EMAIL_VERIFY:{ if (m_pEmailVerifyDelegate != NULL) { this->m_pEmailVerifyDelegate->onEmailVerifyError(errorCode,errorInfo.c_str()); } }break; case HTTP_OP_Type::_bHTTP_LOGIN:{ if(m_pLoginDelegate != NULL){ this->m_pLoginDelegate->onLoginDone(errorCode,errorInfo.c_str()); } }break; default:break; } return; }else{ std::vector<char> *buffer = response->getResponseData(); std::string str((*buffer).begin(),(*buffer).end()); cout<<"request sucess "<<str<<endl; Json::Reader reader; Json::Value value; if (!reader.parse(str, value)) { }else{ switch(_opType){ case HTTP_OP_Type::_bHTTP_SAVE:{ if (strcmp(m_tableName.c_str(),BmobSDKInit::USER_TABLE.c_str()) == 0) { string objectId = value["objectId"].asString(); string session = value["sessionToken"].asString(); UserDefault::getInstance()->setStringForKey("user_id",objectId); UserDefault::getInstance()->setStringForKey("user_session",session); } if (m_pSaveDelegate != NULL) { this->m_pSaveDelegate->onSaveSucess(str.c_str()); } }break; case HTTP_OP_Type::_bHTTP_UPDATE:{ if (m_pUpdateDelegate != NULL) { this->m_pUpdateDelegate->onUpdateSucess(str.c_str()); } }break; case HTTP_OP_Type::_bHTTP_DELETE:{ if (m_pDeleteDelegate != NULL) { this->m_pDeleteDelegate->onDeleteSucess(str.c_str()); } }break; case HTTP_OP_Type::_bHTTP_RESET:{ if (m_pResetDelegate != NULL) { this->m_pResetDelegate->onResetSucess(str.c_str()); } }break; case HTTP_OP_Type::_bHTTP_REQUEST_CODE:{ if(m_pRequestSMSCodeDelegate != NULL){ this->m_pRequestSMSCodeDelegate->onRequestDone(200,str.c_str()); } }break; case HTTP_OP_Type::_bHTTP_RESET_BY_CODE:{ if(m_pResetByMSMCodeDelegate != NULL){ this->m_pResetByMSMCodeDelegate->onResetDone(200,str.c_str()); } }break; case HTTP_OP_Type::_bHTTP_EMAIL_VERIFY:{ if (m_pEmailVerifyDelegate != NULL) { this->m_pEmailVerifyDelegate->onEmailVerifySucess(str.c_str()); } }break; case HTTP_OP_Type::_bHTTP_LOGIN:{ if(m_pLoginDelegate != NULL){ this->m_pLoginDelegate->onLoginDone(200,str.c_str()); } }break; default:break; } } } }
#include "bmobobject.h" #include "network/HttpClient.h" #include "network/HttpResponse.h" #include "../util/bmobstrutil.h" using namespace network; BmobObject::BmobObject(){ this->m_pSaveDelegate = NULL; this->m_pUpdateDelegate = NULL; this->m_pSaveDelegate = NULL; } BmobObject::BmobObject(string tableName){ this->m_tableName = tableName; this->m_pSaveDelegate = NULL; this->m_pUpdateDelegate = NULL; this->m_pSaveDelegate = NULL; } BmobObject::~BmobObject(){ } void BmobObject::save(BmobSaveDelegate* delegate){ if (!BmobSDKInit::isInitialize()) { return ; } _opType = HTTP_OP_Type::_bHTTP_SAVE; this->m_pSaveDelegate = delegate; this->m_url = BmobSDKInit::URL + m_tableName; this->send(); } void BmobObject::increment(string column,int value ){ } void BmobObject::setValue(string key,cocos2d::Ref *object){ this->enParamsToHttp(key,object); } void BmobObject::setValue(string key,__Array* array){ if (array == NULL || key.empty()) { return ; } __Dictionary* dict = __Dictionary::create(); string op = "AddUnique"; dict->setObject(__String::createWithFormat("%s",op.c_str()),"__op"); dict->setObject(array,"objects"); this->enParamsToHttp(key,dict); } void BmobObject::update(BmobUpdateDelegate* delegate){ this->update(this->getObjectId(),delegate); } void BmobObject::update(string objectId,BmobUpdateDelegate* delegate){ if (objectId.empty()) { return ; } _opType = HTTP_OP_Type::_bHTTP_UPDATE; this->m_pUpdateDelegate = delegate; this->m_url = BmobSDKInit::URL + m_tableName ; if (!objectId.empty()) { this->m_url += + "/" + objectId; } this->send(HttpRequest::Type::PUT); } void BmobObject::remove(string name){ if (name.empty()) { return ; } this->clear(); __Dictionary* pDict = __Dictionary::create(); __String* pValue2 = __String::create("Delete"); pDict->setObject(pValue2, "__op"); this->enParamsToHttp(name,pDict); } void BmobObject::removeAll(string name,__Array* array){
y,"objects"); this->enParamsToHttp(name,dict); } void BmobObject::del(BmobDeleteDelegate* delegate){ _opType = HTTP_OP_Type::_bHTTP_DELETE; this->m_pDeleteDelegate = delegate; this->m_url = BmobSDKInit::URL + m_tableName + "/" + m_objectId; this->send(HttpRequest::Type::DELETE); } void BmobObject::del(string objectId,BmobDeleteDelegate* delegate){ this->m_objectId = objectId; this->del(delegate); } void BmobObject::add(string column,Ref* object){ if (object == NULL) { return ; } __Dictionary* dict = __Dictionary::create(); string op = "Add"; __Array* array = __Array::create(); array->addObject(object); dict->setObject(__String::createWithFormat("%s",op.c_str()),"__op"); dict->setObject(array,"objects"); this->enParamsToHttp(column,dict); } void BmobObject::add(string column,__Array* array){ if (column.empty() || array == NULL) { return ; } __Dictionary* dict = __Dictionary::create(); string op = "Add"; dict->setObject(__String::createWithFormat("%s",op.c_str()),"__op"); dict->setObject(array,"objects"); this->enParamsToHttp(column,dict); } void BmobObject::enParamsToHttp(string key,cocos2d::Ref *object){ this->m_mapData.insert(pair<string, Ref *>(key, object)); } Ref* BmobObject::getParams(string key){ std::map<string, Ref *>::iterator it = m_mapData.find(key); if (it!=m_mapData.end()) { return it->second; } return NULL; } void BmobObject::setHeader(vector<string> v){ this->m_header = v; } vector<string> BmobObject::getHeader(){ if (this->m_header.empty()) { vector<string> header_list; header_list.push_back("X-Bmob-Application-Id:"+BmobSDKInit::APP_ID); header_list.push_back("X-Bmob-REST-API-Key:"+BmobSDKInit::APP_KEY); header_list.push_back("Content-Type: application/json"); if (strcmp(m_tableName.c_str(),BmobSDKInit::USER_TABLE.c_str()) == 0) { if (!m_session.empty()) { string se = "X-Bmob-Session-Token:" + m_session; header_list.push_back(se); } } this->m_header = header_list; } return this->m_header; } void BmobObject::enJson(Json::Value* value){ BmobJsonUtil::dictionary2Json(value, &(this->m_mapData)); } void BmobObject::deJson(Json::Value* value){ this->clear(); BmobJsonUtil::json2Dictionary(value, &(this->m_mapData)); this->m_objectId = (*value)["objectId"].asString(); this->m_createdAt = (*value)["createdAt"].asString(); this->m_updatedAt = (*value)["updatedAt"].asString(); } void BmobObject::send(){ this->send(HttpRequest::Type::POST); } void BmobObject::send(HttpRequest::Type type){ HttpRequest* req = new HttpRequest; req->setUrl(this->m_url.c_str()); req->setResponseCallback(this, cocos2d::SEL_CallFuncND(&BmobObject::onHttpRequestCompleted)); req->setRequestType(type); req->setHeaders(getHeader()); Json::Value params; std::string data; this->enJson(&params); data = params.toStyledString(); req->setRequestData(data.c_str(), strlen(data.c_str())); cout<<"request data is:"<<data<<endl; HttpClient::getInstance()->setTimeoutForConnect(3000); HttpClient::getInstance()->setTimeoutForRead(3000); HttpClient::getInstance()->send(req); req->release(); } void BmobObject::onHttpRequestCompleted(cocos2d::Node *pSender,void *data){ HttpResponse *response = (HttpResponse *)data; if (!response->isSucceed()) { int errorCode = response->getResponseCode(); string errorInfo = response->getErrorBuffer(); switch(_opType){ case HTTP_OP_Type::_bHTTP_SAVE:{ if (m_pSaveDelegate != NULL) { this->m_pSaveDelegate->onSaveError(errorCode,errorInfo.c_str()); } }break; case HTTP_OP_Type::_bHTTP_UPDATE:{ if (m_pUpdateDelegate != NULL) { this->m_pUpdateDelegate->onUpdateError(errorCode,errorInfo.c_str()); } }break; case HTTP_OP_Type::_bHTTP_DELETE:{ if (m_pDeleteDelegate != NULL) { this->m_pDeleteDelegate->onDeleteError(errorCode,errorInfo.c_str()); } }break; case HTTP_OP_Type::_bHTTP_RESET:{ if (m_pResetDelegate != NULL) { this->m_pResetDelegate->onResetError(errorCode,errorInfo.c_str()); } }break; case HTTP_OP_Type::_bHTTP_REQUEST_CODE:{ if(m_pRequestSMSCodeDelegate != NULL){ this->m_pRequestSMSCodeDelegate->onRequestDone(errorCode,errorInfo.c_str()); } }break; case HTTP_OP_Type::_bHTTP_RESET_BY_CODE:{ if(m_pResetByMSMCodeDelegate != NULL){ this->m_pResetByMSMCodeDelegate->onResetDone(errorCode,errorInfo.c_str()); } }break; case HTTP_OP_Type::_bHTTP_EMAIL_VERIFY:{ if (m_pEmailVerifyDelegate != NULL) { this->m_pEmailVerifyDelegate->onEmailVerifyError(errorCode,errorInfo.c_str()); } }break; case HTTP_OP_Type::_bHTTP_LOGIN:{ if(m_pLoginDelegate != NULL){ this->m_pLoginDelegate->onLoginDone(errorCode,errorInfo.c_str()); } }break; default:break; } return; }else{ std::vector<char> *buffer = response->getResponseData(); std::string str((*buffer).begin(),(*buffer).end()); cout<<"request sucess "<<str<<endl; Json::Reader reader; Json::Value value; if (!reader.parse(str, value)) { }else{ switch(_opType){ case HTTP_OP_Type::_bHTTP_SAVE:{ if (strcmp(m_tableName.c_str(),BmobSDKInit::USER_TABLE.c_str()) == 0) { string objectId = value["objectId"].asString(); string session = value["sessionToken"].asString(); UserDefault::getInstance()->setStringForKey("user_id",objectId); UserDefault::getInstance()->setStringForKey("user_session",session); } if (m_pSaveDelegate != NULL) { this->m_pSaveDelegate->onSaveSucess(str.c_str()); } }break; case HTTP_OP_Type::_bHTTP_UPDATE:{ if (m_pUpdateDelegate != NULL) { this->m_pUpdateDelegate->onUpdateSucess(str.c_str()); } }break; case HTTP_OP_Type::_bHTTP_DELETE:{ if (m_pDeleteDelegate != NULL) { this->m_pDeleteDelegate->onDeleteSucess(str.c_str()); } }break; case HTTP_OP_Type::_bHTTP_RESET:{ if (m_pResetDelegate != NULL) { this->m_pResetDelegate->onResetSucess(str.c_str()); } }break; case HTTP_OP_Type::_bHTTP_REQUEST_CODE:{ if(m_pRequestSMSCodeDelegate != NULL){ this->m_pRequestSMSCodeDelegate->onRequestDone(200,str.c_str()); } }break; case HTTP_OP_Type::_bHTTP_RESET_BY_CODE:{ if(m_pResetByMSMCodeDelegate != NULL){ this->m_pResetByMSMCodeDelegate->onResetDone(200,str.c_str()); } }break; case HTTP_OP_Type::_bHTTP_EMAIL_VERIFY:{ if (m_pEmailVerifyDelegate != NULL) { this->m_pEmailVerifyDelegate->onEmailVerifySucess(str.c_str()); } }break; case HTTP_OP_Type::_bHTTP_LOGIN:{ if(m_pLoginDelegate != NULL){ this->m_pLoginDelegate->onLoginDone(200,str.c_str()); } }break; default:break; } } } }
if (array == NULL) { return ; } __Dictionary* dict = __Dictionary::create(); string op = "Remove"; dict->setObject(__String::createWithFormat("%s",op.c_str()),"__op"); dict->setObject(arra
function_block-random_span
[ { "content": "class DefaultValueArrayAllocator : public ValueArrayAllocator\n\n{\n\npublic: // overridden from ValueArrayAllocator\n\n virtual ~DefaultValueArrayAllocator()\n\n {\n\n }\n\n\n\n virtual ValueInternalArray *newArray()\n\n {\n\n return new ValueInternalArray();\n\n }\n\n\n\n virt...
C++
Raspberry Pi/build-GUI_app-Desktop-Debug/moc_writewindow.cpp
AnasKhedr/Smart-Home-2017
b847baa26fbd12b831e2f4325f74d0aa1a766dad
#include "../gui/writewindow.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'writewindow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.3.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_WriteWindow_t { QByteArrayData data[10]; char stringdata[213]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_WriteWindow_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_WriteWindow_t qt_meta_stringdata_WriteWindow = { { QT_MOC_LITERAL(0, 0, 11), QT_MOC_LITERAL(1, 12, 25), QT_MOC_LITERAL(2, 38, 0), QT_MOC_LITERAL(3, 39, 5), QT_MOC_LITERAL(4, 45, 28), QT_MOC_LITERAL(5, 74, 4), QT_MOC_LITERAL(6, 79, 38), QT_MOC_LITERAL(7, 118, 29), QT_MOC_LITERAL(8, 148, 32), QT_MOC_LITERAL(9, 181, 31) }, "WriteWindow\0on_dial_temp_valueChanged\0" "\0value\0on_spinBox_temp_valueChanged\0" "arg1\0on_horizontalSlider_light_valueChanged\0" "on_spinBox_light_valueChanged\0" "on_pushButton_send_light_clicked\0" "on_pushButton_send_temp_clicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_WriteWindow[] = { 7, 0, 0, 0, 6, 14, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 44, 2, 0x08 , 4, 1, 47, 2, 0x08 , 6, 1, 50, 2, 0x08 , 7, 1, 53, 2, 0x08 , 8, 0, 56, 2, 0x08 , 9, 0, 57, 2, 0x08 , QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 5, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 5, QMetaType::Void, QMetaType::Void, 0 }; void WriteWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { WriteWindow *_t = static_cast<WriteWindow *>(_o); switch (_id) { case 0: _t->on_dial_temp_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 1: _t->on_spinBox_temp_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 2: _t->on_horizontalSlider_light_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 3: _t->on_spinBox_light_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 4: _t->on_pushButton_send_light_clicked(); break; case 5: _t->on_pushButton_send_temp_clicked(); break; default: ; } } } const QMetaObject WriteWindow::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_WriteWindow.data, qt_meta_data_WriteWindow, qt_static_metacall, 0, 0} }; const QMetaObject *WriteWindow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *WriteWindow::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_WriteWindow.stringdata)) return static_cast<void*>(const_cast< WriteWindow*>(this)); return QDialog::qt_metacast(_clname); } int WriteWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 6) qt_static_metacall(this, _c, _id, _a); _id -= 6; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 6) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 6; } return _id; } QT_END_MOC_NAMESPACE
#include "../gui/writewindow.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'writewindow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.3.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_WriteWindow_t { QByteArrayData data[10]; char stringdata[213]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_
2), QT_MOC_LITERAL(9, 181, 31) }, "WriteWindow\0on_dial_temp_valueChanged\0" "\0value\0on_spinBox_temp_valueChanged\0" "arg1\0on_horizontalSlider_light_valueChanged\0" "on_spinBox_light_valueChanged\0" "on_pushButton_send_light_clicked\0" "on_pushButton_send_temp_clicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_WriteWindow[] = { 7, 0, 0, 0, 6, 14, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 44, 2, 0x08 , 4, 1, 47, 2, 0x08 , 6, 1, 50, 2, 0x08 , 7, 1, 53, 2, 0x08 , 8, 0, 56, 2, 0x08 , 9, 0, 57, 2, 0x08 , QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 5, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 5, QMetaType::Void, QMetaType::Void, 0 }; void WriteWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { WriteWindow *_t = static_cast<WriteWindow *>(_o); switch (_id) { case 0: _t->on_dial_temp_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 1: _t->on_spinBox_temp_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 2: _t->on_horizontalSlider_light_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 3: _t->on_spinBox_light_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 4: _t->on_pushButton_send_light_clicked(); break; case 5: _t->on_pushButton_send_temp_clicked(); break; default: ; } } } const QMetaObject WriteWindow::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_WriteWindow.data, qt_meta_data_WriteWindow, qt_static_metacall, 0, 0} }; const QMetaObject *WriteWindow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *WriteWindow::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_WriteWindow.stringdata)) return static_cast<void*>(const_cast< WriteWindow*>(this)); return QDialog::qt_metacast(_clname); } int WriteWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 6) qt_static_metacall(this, _c, _id, _a); _id -= 6; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 6) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 6; } return _id; } QT_END_MOC_NAMESPACE
ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_WriteWindow_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_WriteWindow_t qt_meta_stringdata_WriteWindow = { { QT_MOC_LITERAL(0, 0, 11), QT_MOC_LITERAL(1, 12, 25), QT_MOC_LITERAL(2, 38, 0), QT_MOC_LITERAL(3, 39, 5), QT_MOC_LITERAL(4, 45, 28), QT_MOC_LITERAL(5, 74, 4), QT_MOC_LITERAL(6, 79, 38), QT_MOC_LITERAL(7, 118, 29), QT_MOC_LITERAL(8, 148, 3
random
[ { "content": "struct qt_meta_stringdata_ReadWindow_t {\n\n QByteArrayData data[5];\n\n char stringdata[80];\n\n};\n\n#define QT_MOC_LITERAL(idx, ofs, len) \\\n\n Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \\\n\n qptrdiff(offsetof(qt_meta_stringdata_ReadWindow_t, stringdata) + ofs \...
C++
src/canoe/phrasetable_filter_joint.cc
nrc-cnrc/Portage-SMT-TAS
73f5a65de4adfa13008ea9a01758385c97526059
#include "phrasetable_filter_joint.h" #include "soft_filter_tm_visitor.h" #include "hard_filter_tm_visitor.h" #include "logging.h" using namespace Portage; Logging::logger ptLogger_filter_joint(Logging::getLogger("debug.canoe.phraseTable_filter_joint")); PhraseTableFilterJoint::PhraseTableFilterJoint(bool limitPhrases, VocabFilter &tgtVocab, const pruningStyle* const pruning_style, const string& pruningTypeStr, const vector<double>& forwardWeights, const vector<double>& transWeights, bool tm_hard_limit, bool appendJointCounts) : Parent(limitPhrases, tgtVocab, pruningTypeStr, appendJointCounts) , visitor(NULL) , tgtTable(NULL) , pruning_style(pruning_style) , online_filter_output(NULL) { assert(pruning_style); if (tm_hard_limit) { visitor = new Joint_Filtering::hardFilterTMVisitor(*this, log_almost_0, pruningTypeStr, forwardWeights, transWeights); } else { visitor = new Joint_Filtering::softFilterTMVisitor(*this, log_almost_0, pruningTypeStr); } assert(visitor); LOG_VERBOSE1(ptLogger_filter_joint, "Creating/Using PhraseTableFilterJoint %s mode", visitor->style.c_str()); } PhraseTableFilterJoint::~PhraseTableFilterJoint() { if (online_filter_output) delete online_filter_output; online_filter_output = NULL; if (visitor) delete visitor; visitor = NULL; if (tgtTable) delete tgtTable; tgtTable = NULL; } void PhraseTableFilterJoint::outputForOnlineProcessing(const string& filtered_TM_filename) { online_filter_output = new oSafeMagicStream(filtered_TM_filename); assert(online_filter_output); tgtTable = new TargetPhraseTable; assert(tgtTable); LOG_VERBOSE2(ptLogger_filter_joint, "Setting output for online processing: %s, %s", filtered_TM_filename.c_str(), pruning_style->description().c_str()); } float PhraseTableFilterJoint::convertFromRead(float value) const { return value; } float PhraseTableFilterJoint::convertToWrite(float value) const { return value; } void PhraseTableFilterJoint::filter(const string& filtered_TM_filename) { assert(visitor); assert(pruning_style); LOG_VERBOSE2(ptLogger_filter_joint, "Applying %s filter_joint to: %s, pruningStyle=%s, n=%d", visitor->style.c_str(), filtered_TM_filename.c_str(), pruning_style->description().c_str(), numTextTransModels); visitor->set(pruning_style, numTextTransModels); visitor->numKeptEntry = 0; textTable.traverse(*visitor); oSafeMagicStream multi(filtered_TM_filename); write(multi); fprintf(stderr, "There are %d entries left after applying %s filtering\n", visitor->numKeptEntry, visitor->style.c_str()); visitor->display(cerr); } Uint PhraseTableFilterJoint::processTargetPhraseTable(const string& src, Uint src_word_count, TargetPhraseTable* tgtTable) { assert(visitor); if (!tgtTable) return 0; if (!online_filter_output) return 0; assert(pruning_style); const Uint L = (*pruning_style)(src_word_count); LOG_VERBOSE3(ptLogger_filter_joint, "Online processing of one entry (%s) L=%d n=%d", visitor->style.c_str(), L, tgtTable->begin()->second.backward.size()); const Uint numBeforeFiltering(tgtTable->size()); visitor->set(L, tgtTable->begin()->second.backward.size()); (*visitor)(*tgtTable); write(*online_filter_output, src, *tgtTable); const Uint numKeptEntry(tgtTable->size()); tgtTable->clear(); return numBeforeFiltering - numKeptEntry; } TargetPhraseTable* PhraseTableFilterJoint::getTargetPhraseTable(PhraseTableEntry& entry, bool limitPhrases) { if (!online_filter_output || tgtVocab.getNumSourceSents() > 0) { return PhraseTable::getTargetPhraseTable(entry, limitPhrases); } else { assert(tgtTable); tgtTable->clear(); return tgtTable; } }
#include "phrasetable_filter_joint.h" #include "soft_filter_tm_visitor.h" #include "hard_filter_tm_visitor.h" #include "logging.h" using namespace Portage; Logging::logger ptLogger_filter_joint(Logging::getLogger("debug.canoe.phraseTable_filter_joint")); PhraseTableFilterJoint::PhraseTableFilterJoint(bool limitPhrases, VocabFilter &tgtVocab, const pruningStyle* const pruning_style, const string& pruningTypeStr, const vector<double>& forwardWeights, const vector<double>& transWeights, bool tm_hard_limit, bool appendJointCounts) : Parent(limitPhrases, tgtVocab, pruningTypeStr, appendJointCounts) , visitor(NULL) , tgtTable(NULL) , pruning_style(pruning_style) , online_filter_output(NULL) { assert(pruning_style); if (tm_hard_limit) { visitor = new Joint_Filtering::hardFilterTMVisitor(*this, log_almost_0, pruningTypeStr, forwardWeights, transWeights); } else { visitor = new Joint_Filtering::softFilterTMVisitor(*this, log_almost_0, pruningTypeStr); } assert(visitor); LOG_VERBOSE1(ptLogger_filter_joint, "Creating/Using PhraseTableFilterJoint %s mode", visitor->style.c_str()); } PhraseTableFilterJoint::~PhraseTableFilterJoint() { if (online_filter_output) delete online_filter_output; online_filter_output = NULL; if (visitor) delete visitor; visitor = NULL; if (tgtTable) delete tgtTable; tgtTable = NULL; } void PhraseTableFilterJoint::outputForOnlineProcessing(const string& filtered_TM_filename) { online_filter_output = new oSafeMagicStream(filtered_TM_filename); assert(online_filter_output); tgtTable = new TargetPhraseTable; assert(tgtTable); LOG_VERBOSE2(ptLogger_filter_joint, "Setting output for online processing: %s, %s", filtered_TM_filename.c_str(), pruning_style->description().c_str()); } float PhraseTableFilterJoint::convertFromRead(float value) const { return value; } float PhraseTableFilterJoint::convertToWrite(float value) const { return value; } void PhraseTableFilterJoint::filter(const string& filtered_TM_filename) { assert(visitor); assert(pruning_style); LOG_VERBOSE2(ptLogger_filter_joint, "Applying %s filter_joint to: %s, pruningStyle=%s, n=%d", visitor->style.c_str(), filtered_TM_filename.c_str(), pruning_style->description().c_str(), numTextTransModels); visitor->set(pruning_style, numTextTransModels); visitor->numKeptEntry = 0; textTable.traverse(*visitor); oSafeMagicStream multi(filtered_TM_filename); write(multi); fprintf(stderr, "There are %d entries left after applying %s filtering\n", visitor->numKeptEntry, visitor->style.c_str()); visitor->display(cerr); } Uint PhraseTableFilterJoint::processTargetPhraseTable(const string& src, Uint src_word_count, TargetPhraseTable* tgtTable) { assert(visitor); if (!tgtTable) return 0; if (!online_filter_output) return 0; assert(pruning_style); const Uint L = (*pruning_style)(src_word_count);
; const Uint numBeforeFiltering(tgtTable->size()); visitor->set(L, tgtTable->begin()->second.backward.size()); (*visitor)(*tgtTable); write(*online_filter_output, src, *tgtTable); const Uint numKeptEntry(tgtTable->size()); tgtTable->clear(); return numBeforeFiltering - numKeptEntry; } TargetPhraseTable* PhraseTableFilterJoint::getTargetPhraseTable(PhraseTableEntry& entry, bool limitPhrases) { if (!online_filter_output || tgtVocab.getNumSourceSents() > 0) { return PhraseTable::getTargetPhraseTable(entry, limitPhrases); } else { assert(tgtTable); tgtTable->clear(); return tgtTable; } }
LOG_VERBOSE3(ptLogger_filter_joint, "Online processing of one entry (%s) L=%d n=%d", visitor->style.c_str(), L, tgtTable->begin()->second.backward.size())
call_expression
[ { "content": "struct null_deleter\n\n{\n\n void operator()(T const *) const {}\n\n};\n\n\n\n\n\nptr_FF FeatureFunctionSet::create(const string& name,\n\n const string& arg,\n\n const char* fileff_prefix,\n\n boo...
C++
cpp/test/main.cc
yjhatfdu/zstd-codec
f3f52dd801df1ece0d6cdbc9445dcb2a00973e37
#include <algorithm> #include <cstdio> #include <fstream> #include <functional> #include <iterator> #include <iostream> #include <string> #include "zstd-codec.h" #include "zstd-dict.h" #include "zstd-stream.h" #define CATCH_CONFIG_MAIN #include "catch.hpp" class FileResource : public Resource<FILE> { public: FileResource(const std::string& path, const char* mode) : FileResource(path.c_str(), mode) { } FileResource(const char* path, const char* mode) : Resource(fopen(path, mode), fclose) { } }; static std::string fixturePath(const char* name) { static const std::string kFixturePath("test/fixtures"); return kFixturePath + "/" + name; } static std::string tempPath(const char* name) { static const std::string kTempPath("test/tmp"); return kTempPath + "/" + name; } static Vec<u8> loadFixture(const char* name) { const auto path = fixturePath(name); std::ifstream stream(path.c_str(), std::ios::in | std::ios::binary); return Vec<u8>((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>()); } TEST_CASE("Zstd-Dictionary-Interfaces", "[zstd][compress][decompress][dictionary]") { const auto dict_bytes = loadFixture("sample-dict"); const auto sample_books = loadFixture("sample-books.json"); const auto compression_level = 5; ZstdCompressionDict cdict(dict_bytes, compression_level); ZstdDecompressionDict ddict(dict_bytes); ZstdCodec codec; Vec<u8> compressed_bytes(codec.CompressBound(sample_books.size())); auto rc = codec.CompressUsingDict(compressed_bytes, sample_books, cdict); REQUIRE(rc >= 0); REQUIRE(rc < sample_books.size()); compressed_bytes.resize(rc); REQUIRE(codec.ContentSize(compressed_bytes) == sample_books.size()); Vec<u8> decompressed_bytes(sample_books.size() * 2); rc = codec.DecompressUsingDict(decompressed_bytes, compressed_bytes, ddict); REQUIRE(rc >= 0); REQUIRE(rc == sample_books.size()); decompressed_bytes.resize(rc); REQUIRE(decompressed_bytes == sample_books); rc = codec.Decompress(decompressed_bytes, compressed_bytes); REQUIRE(rc < 0); } TEST_CASE("Stream using dictionary", "[zstd][compress][decompress][dictionary][stream]") { const auto dict_bytes = loadFixture("sample-dict"); const auto sample_books = loadFixture("sample-books.json"); const auto compression_level = 5; ZstdCompressionDict cdict(dict_bytes, compression_level); ZstdDecompressionDict ddict(dict_bytes); Vec<u8> compressed_bytes; compressed_bytes.reserve(1 * 1024 * 1024); const auto append_bytes = [](Vec<u8>& dest, const Vec<u8>& src) { std::copy(std::begin(src), std::end(src), std::back_inserter(dest)); }; const StreamCallback cstream_callback = [&append_bytes, &compressed_bytes](const Vec<u8>& compressed) { append_bytes(compressed_bytes, compressed); }; ZstdCompressStream cstream; REQUIRE(cstream.Begin(cdict)); REQUIRE(cstream.Transform(sample_books, cstream_callback)); REQUIRE(cstream.End(cstream_callback)); REQUIRE(compressed_bytes.size() < sample_books.size()); Vec<u8> content_bytes; content_bytes.reserve(1 * 1024 * 1024); const StreamCallback dstream_callback = [&append_bytes, &content_bytes](const Vec<u8>& decompressed) { append_bytes(content_bytes, decompressed); }; ZstdDecompressStream dstream; REQUIRE(dstream.Begin(ddict)); REQUIRE(dstream.Transform(compressed_bytes, dstream_callback)); REQUIRE(dstream.End(dstream_callback)); REQUIRE(compressed_bytes.size() < content_bytes.size()); REQUIRE(content_bytes == sample_books); } TEST_CASE("ZstdCompressStream", "[zstd][compress][stream]") { const auto block_size = 1024; size_t read_size; Vec<u8> read_buff(block_size); Vec<u8> content_bytes; content_bytes.reserve(1 * 1024 * 1024); Vec<u8> result_bytes; result_bytes.reserve(1 * 1024 * 1024); const StreamCallback callback = [&result_bytes](const Vec<u8>& compressed) { std::copy(std::begin(compressed), std::end(compressed), std::back_inserter(result_bytes)); }; ZstdCompressStream stream; REQUIRE(stream.Begin(3)); FileResource bmp_file(fixturePath("dance_yorokobi_mai_man.bmp"), "rb"); while ((read_size = fread(&read_buff[0], 1, read_buff.size(), bmp_file.get()))) { read_buff.resize(read_size); REQUIRE(stream.Transform(read_buff, callback)); std::copy(std::begin(read_buff), std::end(read_buff), std::back_inserter(content_bytes)); read_buff.resize(read_buff.capacity()); } REQUIRE(stream.End(callback)); REQUIRE(result_bytes.size() < content_bytes.size()); bmp_file.Close(); ZstdCodec codec; Vec<u8> decompressed_bytes(content_bytes.size()); REQUIRE(codec.Decompress(decompressed_bytes, result_bytes) == content_bytes.size()); REQUIRE(decompressed_bytes == content_bytes); FileResource result_file(tempPath("dance_yorokobi_mai_man.bmp.zst"), "wb"); fwrite(&result_bytes[0], result_bytes.size(), 1, result_file.get()); result_file.Close(); } TEST_CASE("ZstdDecompressStream", "[zstd][decompress][stream]") { const auto block_size = 1024; size_t read_size; Vec<u8> read_buff(block_size); Vec<u8> compressed_bytes; compressed_bytes.reserve(1 * 1024 * 1024); Vec<u8> result_bytes; result_bytes.reserve(1 * 1024 * 1024); const StreamCallback callback = [&result_bytes](const Vec<u8>& decompressed) { std::copy(std::begin(decompressed), std::end(decompressed), std::back_inserter(result_bytes)); }; ZstdDecompressStream stream; REQUIRE(stream.Begin()); FileResource zst_file(fixturePath("dance_yorokobi_mai_woman.bmp.zst"), "rb"); while ((read_size = fread(&read_buff[0], 1, read_buff.size(), zst_file.get()))) { read_buff.resize(read_size); REQUIRE(stream.Transform(read_buff, callback)); std::copy(std::begin(read_buff), std::end(read_buff), std::back_inserter(compressed_bytes)); read_buff.resize(read_buff.capacity()); } REQUIRE(stream.End(callback)); REQUIRE(result_bytes.size() > compressed_bytes.size()); zst_file.Close(); ZstdCodec codec; const auto content_size = codec.ContentSize(compressed_bytes); REQUIRE(result_bytes.size() == content_size); Vec<u8> content_bytes(content_size); REQUIRE(codec.Decompress(content_bytes, compressed_bytes) == content_size); REQUIRE(content_bytes == result_bytes); FileResource result_file(tempPath("dance_yorokobi_mai_woman.bmp"), "wb"); fwrite(&result_bytes[0], result_bytes.size(), 1, result_file.get()); result_file.Close(); }
#include <algorithm> #include <cstdio> #include <fstream> #include <functional> #include <iterator> #include <iostream> #include <string> #include "zstd-codec.h" #include "zstd-dict.h" #include "zstd-stream.h" #define CATCH_CONFIG_MAIN #include "catch.hpp" class FileResource : public Resource<FILE> { public: FileResource(const std::string& path, const char* mode) : FileResource(path.c_str(), mode) { } FileResource(const char* path, const char* mode) : Resource(fopen(path, mode), fclose) { } }; static std::string fixturePath(const char* name) { static const std::string kFixturePath("test/fixtures"); return kFixturePath + "/" + name; } static std::string tempPath(const char* name) { static const std::string kTempPath("test/tmp"); return kTempPath + "/" + name; } static Vec<u8> loadFixture(const char* name) {
TEST_CASE("Zstd-Dictionary-Interfaces", "[zstd][compress][decompress][dictionary]") { const auto dict_bytes = loadFixture("sample-dict"); const auto sample_books = loadFixture("sample-books.json"); const auto compression_level = 5; ZstdCompressionDict cdict(dict_bytes, compression_level); ZstdDecompressionDict ddict(dict_bytes); ZstdCodec codec; Vec<u8> compressed_bytes(codec.CompressBound(sample_books.size())); auto rc = codec.CompressUsingDict(compressed_bytes, sample_books, cdict); REQUIRE(rc >= 0); REQUIRE(rc < sample_books.size()); compressed_bytes.resize(rc); REQUIRE(codec.ContentSize(compressed_bytes) == sample_books.size()); Vec<u8> decompressed_bytes(sample_books.size() * 2); rc = codec.DecompressUsingDict(decompressed_bytes, compressed_bytes, ddict); REQUIRE(rc >= 0); REQUIRE(rc == sample_books.size()); decompressed_bytes.resize(rc); REQUIRE(decompressed_bytes == sample_books); rc = codec.Decompress(decompressed_bytes, compressed_bytes); REQUIRE(rc < 0); } TEST_CASE("Stream using dictionary", "[zstd][compress][decompress][dictionary][stream]") { const auto dict_bytes = loadFixture("sample-dict"); const auto sample_books = loadFixture("sample-books.json"); const auto compression_level = 5; ZstdCompressionDict cdict(dict_bytes, compression_level); ZstdDecompressionDict ddict(dict_bytes); Vec<u8> compressed_bytes; compressed_bytes.reserve(1 * 1024 * 1024); const auto append_bytes = [](Vec<u8>& dest, const Vec<u8>& src) { std::copy(std::begin(src), std::end(src), std::back_inserter(dest)); }; const StreamCallback cstream_callback = [&append_bytes, &compressed_bytes](const Vec<u8>& compressed) { append_bytes(compressed_bytes, compressed); }; ZstdCompressStream cstream; REQUIRE(cstream.Begin(cdict)); REQUIRE(cstream.Transform(sample_books, cstream_callback)); REQUIRE(cstream.End(cstream_callback)); REQUIRE(compressed_bytes.size() < sample_books.size()); Vec<u8> content_bytes; content_bytes.reserve(1 * 1024 * 1024); const StreamCallback dstream_callback = [&append_bytes, &content_bytes](const Vec<u8>& decompressed) { append_bytes(content_bytes, decompressed); }; ZstdDecompressStream dstream; REQUIRE(dstream.Begin(ddict)); REQUIRE(dstream.Transform(compressed_bytes, dstream_callback)); REQUIRE(dstream.End(dstream_callback)); REQUIRE(compressed_bytes.size() < content_bytes.size()); REQUIRE(content_bytes == sample_books); } TEST_CASE("ZstdCompressStream", "[zstd][compress][stream]") { const auto block_size = 1024; size_t read_size; Vec<u8> read_buff(block_size); Vec<u8> content_bytes; content_bytes.reserve(1 * 1024 * 1024); Vec<u8> result_bytes; result_bytes.reserve(1 * 1024 * 1024); const StreamCallback callback = [&result_bytes](const Vec<u8>& compressed) { std::copy(std::begin(compressed), std::end(compressed), std::back_inserter(result_bytes)); }; ZstdCompressStream stream; REQUIRE(stream.Begin(3)); FileResource bmp_file(fixturePath("dance_yorokobi_mai_man.bmp"), "rb"); while ((read_size = fread(&read_buff[0], 1, read_buff.size(), bmp_file.get()))) { read_buff.resize(read_size); REQUIRE(stream.Transform(read_buff, callback)); std::copy(std::begin(read_buff), std::end(read_buff), std::back_inserter(content_bytes)); read_buff.resize(read_buff.capacity()); } REQUIRE(stream.End(callback)); REQUIRE(result_bytes.size() < content_bytes.size()); bmp_file.Close(); ZstdCodec codec; Vec<u8> decompressed_bytes(content_bytes.size()); REQUIRE(codec.Decompress(decompressed_bytes, result_bytes) == content_bytes.size()); REQUIRE(decompressed_bytes == content_bytes); FileResource result_file(tempPath("dance_yorokobi_mai_man.bmp.zst"), "wb"); fwrite(&result_bytes[0], result_bytes.size(), 1, result_file.get()); result_file.Close(); } TEST_CASE("ZstdDecompressStream", "[zstd][decompress][stream]") { const auto block_size = 1024; size_t read_size; Vec<u8> read_buff(block_size); Vec<u8> compressed_bytes; compressed_bytes.reserve(1 * 1024 * 1024); Vec<u8> result_bytes; result_bytes.reserve(1 * 1024 * 1024); const StreamCallback callback = [&result_bytes](const Vec<u8>& decompressed) { std::copy(std::begin(decompressed), std::end(decompressed), std::back_inserter(result_bytes)); }; ZstdDecompressStream stream; REQUIRE(stream.Begin()); FileResource zst_file(fixturePath("dance_yorokobi_mai_woman.bmp.zst"), "rb"); while ((read_size = fread(&read_buff[0], 1, read_buff.size(), zst_file.get()))) { read_buff.resize(read_size); REQUIRE(stream.Transform(read_buff, callback)); std::copy(std::begin(read_buff), std::end(read_buff), std::back_inserter(compressed_bytes)); read_buff.resize(read_buff.capacity()); } REQUIRE(stream.End(callback)); REQUIRE(result_bytes.size() > compressed_bytes.size()); zst_file.Close(); ZstdCodec codec; const auto content_size = codec.ContentSize(compressed_bytes); REQUIRE(result_bytes.size() == content_size); Vec<u8> content_bytes(content_size); REQUIRE(codec.Decompress(content_bytes, compressed_bytes) == content_size); REQUIRE(content_bytes == result_bytes); FileResource result_file(tempPath("dance_yorokobi_mai_woman.bmp"), "wb"); fwrite(&result_bytes[0], result_bytes.size(), 1, result_file.get()); result_file.Close(); }
const auto path = fixturePath(name); std::ifstream stream(path.c_str(), std::ios::in | std::ios::binary); return Vec<u8>((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>()); }
function_block-function_prefix_line
[ { "content": " class NamePattern : public Pattern {\n\n public:\n\n NamePattern( std::string const& name );\n\n virtual ~NamePattern();\n\n virtual bool matches( TestCaseInfo const& testCase ) const override;\n\n private:\n\n WildcardPattern m_wil...
C++
WebKit2-7604.1.38.0.7/WebKit2-7604.1.38.0.7/UIProcess/API/glib/WebKitWebResource.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
#include "config.h" #include "WebKitWebResource.h" #include "APIData.h" #include "WebFrameProxy.h" #include "WebKitURIRequest.h" #include "WebKitWebResourcePrivate.h" #include <glib/gi18n-lib.h> #include <wtf/glib/GRefPtr.h> #include <wtf/glib/WTFGType.h> #include <wtf/text/CString.h> using namespace WebKit; enum { SENT_REQUEST, RECEIVED_DATA, FINISHED, FAILED, FAILED_WITH_TLS_ERRORS, LAST_SIGNAL }; enum { PROP_0, PROP_URI, PROP_RESPONSE }; struct _WebKitWebResourcePrivate { RefPtr<WebFrameProxy> frame; CString uri; GRefPtr<WebKitURIResponse> response; bool isMainResource; }; WEBKIT_DEFINE_TYPE(WebKitWebResource, webkit_web_resource, G_TYPE_OBJECT) static guint signals[LAST_SIGNAL] = { 0, }; static void webkitWebResourceGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec) { WebKitWebResource* resource = WEBKIT_WEB_RESOURCE(object); switch (propId) { case PROP_URI: g_value_set_string(value, webkit_web_resource_get_uri(resource)); break; case PROP_RESPONSE: g_value_set_object(value, webkit_web_resource_get_response(resource)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); } } static void webkit_web_resource_class_init(WebKitWebResourceClass* resourceClass) { GObjectClass* objectClass = G_OBJECT_CLASS(resourceClass); objectClass->get_property = webkitWebResourceGetProperty; g_object_class_install_property(objectClass, PROP_URI, g_param_spec_string("uri", _("URI"), _("The current active URI of the resource"), 0, WEBKIT_PARAM_READABLE)); g_object_class_install_property(objectClass, PROP_RESPONSE, g_param_spec_object("response", _("Response"), _("The response of the resource"), WEBKIT_TYPE_URI_RESPONSE, WEBKIT_PARAM_READABLE)); signals[SENT_REQUEST] = g_signal_new( "sent-request", G_TYPE_FROM_CLASS(objectClass), G_SIGNAL_RUN_LAST, 0, nullptr, nullptr, g_cclosure_marshal_generic, G_TYPE_NONE, 2, WEBKIT_TYPE_URI_REQUEST, WEBKIT_TYPE_URI_RESPONSE); signals[RECEIVED_DATA] = g_signal_new( "received-data", G_TYPE_FROM_CLASS(objectClass), G_SIGNAL_RUN_LAST, 0, nullptr, nullptr, g_cclosure_marshal_generic, G_TYPE_NONE, 1, G_TYPE_UINT64); signals[FINISHED] = g_signal_new("finished", G_TYPE_FROM_CLASS(objectClass), G_SIGNAL_RUN_LAST, 0, 0, 0, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); signals[FAILED] = g_signal_new( "failed", G_TYPE_FROM_CLASS(objectClass), G_SIGNAL_RUN_LAST, 0, 0, 0, g_cclosure_marshal_VOID__BOXED, G_TYPE_NONE, 1, G_TYPE_ERROR | G_SIGNAL_TYPE_STATIC_SCOPE); signals[FAILED_WITH_TLS_ERRORS] = g_signal_new("failed-with-tls-errors", G_TYPE_FROM_CLASS(objectClass), G_SIGNAL_RUN_LAST, 0, nullptr, nullptr, g_cclosure_marshal_generic, G_TYPE_NONE, 2, G_TYPE_TLS_CERTIFICATE, G_TYPE_TLS_CERTIFICATE_FLAGS); } static void webkitWebResourceUpdateURI(WebKitWebResource* resource, const CString& requestURI) { if (resource->priv->uri == requestURI) return; resource->priv->uri = requestURI; g_object_notify(G_OBJECT(resource), "uri"); } WebKitWebResource* webkitWebResourceCreate(WebFrameProxy* frame, WebKitURIRequest* request, bool isMainResource) { ASSERT(frame); WebKitWebResource* resource = WEBKIT_WEB_RESOURCE(g_object_new(WEBKIT_TYPE_WEB_RESOURCE, NULL)); resource->priv->frame = frame; resource->priv->uri = webkit_uri_request_get_uri(request); resource->priv->isMainResource = isMainResource; return resource; } void webkitWebResourceSentRequest(WebKitWebResource* resource, WebKitURIRequest* request, WebKitURIResponse* redirectResponse) { webkitWebResourceUpdateURI(resource, webkit_uri_request_get_uri(request)); g_signal_emit(resource, signals[SENT_REQUEST], 0, request, redirectResponse); } void webkitWebResourceSetResponse(WebKitWebResource* resource, WebKitURIResponse* response) { resource->priv->response = response; g_object_notify(G_OBJECT(resource), "response"); } void webkitWebResourceNotifyProgress(WebKitWebResource* resource, guint64 bytesReceived) { g_signal_emit(resource, signals[RECEIVED_DATA], 0, bytesReceived); } void webkitWebResourceFinished(WebKitWebResource* resource) { g_signal_emit(resource, signals[FINISHED], 0, NULL); } void webkitWebResourceFailed(WebKitWebResource* resource, GError* error) { g_signal_emit(resource, signals[FAILED], 0, error); g_signal_emit(resource, signals[FINISHED], 0, NULL); } void webkitWebResourceFailedWithTLSErrors(WebKitWebResource* resource, GTlsCertificateFlags tlsErrors, GTlsCertificate* certificate) { g_signal_emit(resource, signals[FAILED_WITH_TLS_ERRORS], 0, certificate, tlsErrors); g_signal_emit(resource, signals[FINISHED], 0, nullptr); } WebFrameProxy* webkitWebResourceGetFrame(WebKitWebResource* resource) { return resource->priv->frame.get(); } const char* webkit_web_resource_get_uri(WebKitWebResource* resource) { g_return_val_if_fail(WEBKIT_IS_WEB_RESOURCE(resource), 0); return resource->priv->uri.data(); } WebKitURIResponse* webkit_web_resource_get_response(WebKitWebResource* resource) { g_return_val_if_fail(WEBKIT_IS_WEB_RESOURCE(resource), 0); return resource->priv->response.get(); } struct ResourceGetDataAsyncData { RefPtr<API::Data> webData; }; WEBKIT_DEFINE_ASYNC_DATA_STRUCT(ResourceGetDataAsyncData) static void resourceDataCallback(API::Data* wkData, GTask* task) { ResourceGetDataAsyncData* data = static_cast<ResourceGetDataAsyncData*>(g_task_get_task_data(task)); data->webData = wkData; g_task_return_boolean(task, TRUE); } void webkit_web_resource_get_data(WebKitWebResource* resource, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData) { g_return_if_fail(WEBKIT_IS_WEB_RESOURCE(resource)); GTask* task = g_task_new(resource, cancellable, callback, userData); g_task_set_task_data(task, createResourceGetDataAsyncData(), reinterpret_cast<GDestroyNotify>(destroyResourceGetDataAsyncData)); if (resource->priv->isMainResource) resource->priv->frame->getMainResourceData([task](API::Data* data, CallbackBase::Error) { resourceDataCallback(data, adoptGRef(task).get()); }); else { String url = String::fromUTF8(resource->priv->uri.data()); resource->priv->frame->getResourceData(API::URL::create(url).ptr(), [task](API::Data* data, CallbackBase::Error) { resourceDataCallback(data, adoptGRef(task).get()); }); } } guchar* webkit_web_resource_get_data_finish(WebKitWebResource* resource, GAsyncResult* result, gsize* length, GError** error) { g_return_val_if_fail(WEBKIT_IS_WEB_RESOURCE(resource), 0); g_return_val_if_fail(g_task_is_valid(result, resource), 0); GTask* task = G_TASK(result); if (!g_task_propagate_boolean(task, error)) return 0; ResourceGetDataAsyncData* data = static_cast<ResourceGetDataAsyncData*>(g_task_get_task_data(task)); if (length) *length = data->webData->size(); return static_cast<guchar*>(g_memdup(data->webData->bytes(), data->webData->size())); }
#include "config.h" #include "WebKitWebResource.h" #include "APIData.h" #include "WebFrameProxy.h" #include "WebKitURIRequest.h" #include "WebKitWebResourcePrivate.h" #include <glib/gi18n-lib.h> #include <wtf/glib/GRefPtr.h> #include <wtf/glib/WTFGType.h> #include <wtf/text/CString.h> using namespace WebKit; enum { SENT_REQUEST, RECEIVED_DATA, FINISHED, FAILED, FAILED_WITH_TLS_ERRORS, LAST_SIGNAL }; enum { PROP_0, PROP_URI, PROP_RESPONSE }; struct _WebKitWebResourcePrivate { RefPtr<WebFrameProxy> frame; CString uri; GRefPtr<WebKitURIResponse> response; bool isMainResource; }; WEBKIT_DEFINE_TYPE(WebKitWebResource, webkit_web_resource, G_TYPE_OBJECT) static guint signals[LAST_SIGNAL] = { 0, }; static void webkitWebResourceGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec) { WebKitWebResource* resource = WEBKIT_WEB_RESOURCE(object); switch (propId) { case PROP_URI: g_value_set_string(value, webkit_web_resource_get_uri(resource)); break; case PROP_RESPONSE: g_value_set_object(value, webkit_web_resource_get_response(resource)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec); } } static void webkit_web_resource_class_init(WebKitWebResourceClass* resourceClass) { GObjectClass* objectClass = G_OBJECT_CLASS(resourceClass); objectClass->get_property = webkitWebResourceGetProperty; g_object_class_install_property(objectClass, PROP_URI, g_param_spec_string("uri",
Errors(WebKitWebResource* resource, GTlsCertificateFlags tlsErrors, GTlsCertificate* certificate) { g_signal_emit(resource, signals[FAILED_WITH_TLS_ERRORS], 0, certificate, tlsErrors); g_signal_emit(resource, signals[FINISHED], 0, nullptr); } WebFrameProxy* webkitWebResourceGetFrame(WebKitWebResource* resource) { return resource->priv->frame.get(); } const char* webkit_web_resource_get_uri(WebKitWebResource* resource) { g_return_val_if_fail(WEBKIT_IS_WEB_RESOURCE(resource), 0); return resource->priv->uri.data(); } WebKitURIResponse* webkit_web_resource_get_response(WebKitWebResource* resource) { g_return_val_if_fail(WEBKIT_IS_WEB_RESOURCE(resource), 0); return resource->priv->response.get(); } struct ResourceGetDataAsyncData { RefPtr<API::Data> webData; }; WEBKIT_DEFINE_ASYNC_DATA_STRUCT(ResourceGetDataAsyncData) static void resourceDataCallback(API::Data* wkData, GTask* task) { ResourceGetDataAsyncData* data = static_cast<ResourceGetDataAsyncData*>(g_task_get_task_data(task)); data->webData = wkData; g_task_return_boolean(task, TRUE); } void webkit_web_resource_get_data(WebKitWebResource* resource, GCancellable* cancellable, GAsyncReadyCallback callback, gpointer userData) { g_return_if_fail(WEBKIT_IS_WEB_RESOURCE(resource)); GTask* task = g_task_new(resource, cancellable, callback, userData); g_task_set_task_data(task, createResourceGetDataAsyncData(), reinterpret_cast<GDestroyNotify>(destroyResourceGetDataAsyncData)); if (resource->priv->isMainResource) resource->priv->frame->getMainResourceData([task](API::Data* data, CallbackBase::Error) { resourceDataCallback(data, adoptGRef(task).get()); }); else { String url = String::fromUTF8(resource->priv->uri.data()); resource->priv->frame->getResourceData(API::URL::create(url).ptr(), [task](API::Data* data, CallbackBase::Error) { resourceDataCallback(data, adoptGRef(task).get()); }); } } guchar* webkit_web_resource_get_data_finish(WebKitWebResource* resource, GAsyncResult* result, gsize* length, GError** error) { g_return_val_if_fail(WEBKIT_IS_WEB_RESOURCE(resource), 0); g_return_val_if_fail(g_task_is_valid(result, resource), 0); GTask* task = G_TASK(result); if (!g_task_propagate_boolean(task, error)) return 0; ResourceGetDataAsyncData* data = static_cast<ResourceGetDataAsyncData*>(g_task_get_task_data(task)); if (length) *length = data->webData->size(); return static_cast<guchar*>(g_memdup(data->webData->bytes(), data->webData->size())); }
_("URI"), _("The current active URI of the resource"), 0, WEBKIT_PARAM_READABLE)); g_object_class_install_property(objectClass, PROP_RESPONSE, g_param_spec_object("response", _("Response"), _("The response of the resource"), WEBKIT_TYPE_URI_RESPONSE, WEBKIT_PARAM_READABLE)); signals[SENT_REQUEST] = g_signal_new( "sent-request", G_TYPE_FROM_CLASS(objectClass), G_SIGNAL_RUN_LAST, 0, nullptr, nullptr, g_cclosure_marshal_generic, G_TYPE_NONE, 2, WEBKIT_TYPE_URI_REQUEST, WEBKIT_TYPE_URI_RESPONSE); signals[RECEIVED_DATA] = g_signal_new( "received-data", G_TYPE_FROM_CLASS(objectClass), G_SIGNAL_RUN_LAST, 0, nullptr, nullptr, g_cclosure_marshal_generic, G_TYPE_NONE, 1, G_TYPE_UINT64); signals[FINISHED] = g_signal_new("finished", G_TYPE_FROM_CLASS(objectClass), G_SIGNAL_RUN_LAST, 0, 0, 0, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); signals[FAILED] = g_signal_new( "failed", G_TYPE_FROM_CLASS(objectClass), G_SIGNAL_RUN_LAST, 0, 0, 0, g_cclosure_marshal_VOID__BOXED, G_TYPE_NONE, 1, G_TYPE_ERROR | G_SIGNAL_TYPE_STATIC_SCOPE); signals[FAILED_WITH_TLS_ERRORS] = g_signal_new("failed-with-tls-errors", G_TYPE_FROM_CLASS(objectClass), G_SIGNAL_RUN_LAST, 0, nullptr, nullptr, g_cclosure_marshal_generic, G_TYPE_NONE, 2, G_TYPE_TLS_CERTIFICATE, G_TYPE_TLS_CERTIFICATE_FLAGS); } static void webkitWebResourceUpdateURI(WebKitWebResource* resource, const CString& requestURI) { if (resource->priv->uri == requestURI) return; resource->priv->uri = requestURI; g_object_notify(G_OBJECT(resource), "uri"); } WebKitWebResource* webkitWebResourceCreate(WebFrameProxy* frame, WebKitURIRequest* request, bool isMainResource) { ASSERT(frame); WebKitWebResource* resource = WEBKIT_WEB_RESOURCE(g_object_new(WEBKIT_TYPE_WEB_RESOURCE, NULL)); resource->priv->frame = frame; resource->priv->uri = webkit_uri_request_get_uri(request); resource->priv->isMainResource = isMainResource; return resource; } void webkitWebResourceSentRequest(WebKitWebResource* resource, WebKitURIRequest* request, WebKitURIResponse* redirectResponse) { webkitWebResourceUpdateURI(resource, webkit_uri_request_get_uri(request)); g_signal_emit(resource, signals[SENT_REQUEST], 0, request, redirectResponse); } void webkitWebResourceSetResponse(WebKitWebResource* resource, WebKitURIResponse* response) { resource->priv->response = response; g_object_notify(G_OBJECT(resource), "response"); } void webkitWebResourceNotifyProgress(WebKitWebResource* resource, guint64 bytesReceived) { g_signal_emit(resource, signals[RECEIVED_DATA], 0, bytesReceived); } void webkitWebResourceFinished(WebKitWebResource* resource) { g_signal_emit(resource, signals[FINISHED], 0, NULL); } void webkitWebResourceFailed(WebKitWebResource* resource, GError* error) { g_signal_emit(resource, signals[FAILED], 0, error); g_signal_emit(resource, signals[FINISHED], 0, NULL); } void webkitWebResourceFailedWithTLS
random
[ { "content": "struct external_constructor<value_t::object>\n\n{\n\n template<typename BasicJsonType>\n\n static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)\n\n {\n\n j.m_type = value_t::object;\n\n j.m_value = obj;\n\n j.assert_invariant();\n\n ...
C++
core/src/love/DrawDataFrame.hpp
castle-games/castle-client
7fb34759b164d8de1d83b43bc00ff200a5086e2e
#ifndef DrawDataFrame_hpp #define DrawDataFrame_hpp #define _USE_MATH_DEFINES #include <stdio.h> #include <functional> #include <memory> #include "GhostTypes.hpp" namespace love { class DrawData; struct DrawDataLayer; class DrawDataFrame { public: bool isLinked; PathDataList pathDataList; Bounds fillImageBounds; bool _graphicsNeedsReset = true; ToveGraphicsHolder *_graphics = NULL; DrawDataLayer *_parentLayer = NULL; image::ImageData *fillImageData = NULL; graphics::Image *fillImage = NULL; graphics::Canvas *pathsCanvas = NULL; std::optional<std::string> fillPng; std::optional<std::string> base64Png; inline static double nextRenderTime = 0; double lastRenderTime = 0; DrawDataFrame() = default; DrawDataFrame(bool isLinked_, DrawDataLayer *parentLayer_) : isLinked(isLinked_) , _parentLayer(parentLayer_) { fillImageBounds.maxX = 0; fillImageBounds.maxY = 0; fillImageBounds.minX = 0; fillImageBounds.minY = 0; } DrawDataFrame(const DrawDataFrame &other) = delete; ~DrawDataFrame() { releaseRenderData(); if (pathsCanvas) { pathsCanvas->release(); } } void releaseRenderData() { if (_graphics || fillImageData || fillImage) { std::printf("releasing %p\n", (void *)this); } if (_graphics) { delete _graphics; _graphics = nullptr; } if (fillImageData) { fillImageData->release(); fillImageData = nullptr; } if (fillImage) { fillImage->release(); fillImage = nullptr; } } void read(Archive::Reader &archive) { isLinked = archive.boolean("isLinked", false); archive.arr("pathDataList", [&]() { for (auto i = 0; i < archive.size(); i++) { std::shared_ptr<PathData> pathData = std::make_shared<PathData>(); archive.obj(i, *pathData); if (pathData->isValid()) { pathDataList.push_back(pathData); } } }); archive.obj("fillImageBounds", fillImageBounds); fillPng = archive.str("fillPng", ""); } void write(Archive::Writer &archive) { archive.boolean("isLinked", isLinked); archive.arr("pathDataList", [&]() { for (size_t i = 0; i < pathDataList.size(); i++) { if (pathDataList[i]->isValid()) { archive.obj(*pathDataList[i]); } } }); archive.obj("fillImageBounds", fillImageBounds); if (fillImageData) { love::filesystem::FileData *fileData = fillImageData->encode( love::image::FormatHandler::EncodedFormat::ENCODED_PNG, "Image.png", false); const char *fileDataString = (const char *)fileData->getData(); size_t fileDataSize = fileData->getSize(); size_t dstlen = 0; char *result = data::encode(data::ENCODE_BASE64, fileDataString, fileDataSize, dstlen, 0); archive.str("fillPng", std::string(result)); delete result; fileData->release(); } else if (fillPng && fillPng->length() > 0) { archive.str("fillPng", *fillPng); } } static graphics::Canvas *newCanvas(int width, int height); static love::image::ImageData *newImageData(graphics::Canvas *canvas); static void renderToCanvas(graphics::Canvas *canvas, const std::function<void()> &lambda); static std::string encodeBase64Png(love::image::ImageData *imageData); static std::string encodeBase64Png(graphics::Canvas *canvas); bool arePathDatasMergable(PathData pd1, PathData pd2); float round(float num, int numDecimalPlaces); std::vector<float> roundFloatArray(std::vector<float> a); void cleanUpPaths(); Bounds getPathDataBounds(std::optional<Bounds> bounds); Bounds getPathDataBoundsInPixelCoordinates(); Bounds getFillImageBoundsInPathCoordinates(); void resetGraphics(); ToveGraphicsHolder *graphics(); void render(); void renderFill(); std::optional<std::string> renderPreviewPng(int size); static graphics::Image *imageDataToImage(image::ImageData *); void resizeFillImageDataToPathBounds(); graphics::Image *getFillImage(); void updateFillImageWithFillImageData(); void compressFillCanvas(); bool floodFill(float x, float y, Colorf color); bool floodClear(float x, float y, float radius); void resetFill(); void updatePathsCanvas(); void deserializeFill(); image::ImageData *canvasToImageData(graphics::Canvas *canvas); DrawDataLayer *parentLayer() { return _parentLayer; } void setParentLayer(DrawDataLayer *l) { _parentLayer = l; } }; typedef std::string DrawDataLayerId; struct DrawDataLayer { std::string title; DrawDataLayerId id; bool isVisible = true; bool isBitmap = false; DrawData *_parent = NULL; std::vector<std::shared_ptr<DrawDataFrame>> frames; DrawDataLayer() = default; DrawDataLayer(std::string title_, DrawDataLayerId id_) : title(title_) , id(id_) { } void read(Archive::Reader &archive) { title = archive.str("title", ""); id = archive.str("id", ""); isVisible = archive.boolean("isVisible", true); isBitmap = archive.boolean("isBitmap", false); archive.arr("frames", [&]() { for (auto i = 0; i < archive.size(); i++) { auto frame = std::make_shared<DrawDataFrame>(); archive.obj(i, *frame); frames.push_back(std::move(frame)); } }); } void write(Archive::Writer &archive) { archive.str("title", title); archive.str("id", id); archive.boolean("isVisible", isVisible); archive.boolean("isBitmap", isBitmap); archive.arr("frames", [&]() { for (size_t i = 0; i < frames.size(); i++) { archive.obj(*frames[i]); } }); } DrawData *parent() { return _parent; } void setParent(DrawData *d) { _parent = d; for (auto &frame : frames) { frame->setParentLayer(this); } } }; } #endif
#ifndef DrawDataFrame_hpp #define DrawDataFrame_hpp #define _USE_MATH_DEFINES #include <stdio.h> #include <functional> #include <memory> #include "GhostTypes.hpp" namespace love { class DrawData; struct DrawDataLayer; class DrawDataFrame { public: bool isLinked; PathDataList pathDataList; Bounds fillImageBounds; bool _graphicsNeedsReset = true; ToveGraphicsHolder *_graphics = NULL; DrawDataLayer *_parentLayer = NULL; image::ImageData *fillImageData = NULL; graphics::Image *fillImage = NULL; graphics::Canvas *pathsCanvas = NULL; std::optional<std::string> fillPng; std::optional<std::string> base64Png; inline static double nextRenderTime = 0; double lastRenderTime = 0; DrawDataFrame() = default; DrawDataFrame(bool isLinked_, DrawDataLayer *parentLayer_) : isLinked(isLinked_) , _parentLayer(parentLayer_) { fillImageBounds.maxX = 0; fillImageBounds.maxY = 0; fillImageBounds.minX = 0; fillImageBounds.minY = 0; } DrawDataFrame(const DrawDataFrame &other) = delete; ~DrawDataFrame() { releaseRenderData(); if (pathsCanvas) { pathsCanvas->release(); } } void releaseRenderData() { if (_graphics || fillImageData || fillImage) { std::printf("releasing %p\n", (void *)this); } if (_graphics) { delete _graphics; _graphics = nullptr; } if (fillImageData) { fillImageData->release(); fillImageData = nullptr; } if (fillImage) { fillImage->release(); fillImage = nullptr; } } void read(Archive::Reader &archive) { isLinked = archive.boolean("isLinked", false); archive.arr("pathDataList", [&]() { for (auto i = 0; i < archive.size(); i++) { std::shared_ptr<PathData> pathData = std::make_shared<PathData>(); archive.obj(i, *pathData); if (pathData->isValid()) { pathDataList.push_back(pathData); } } }); archive.obj("fillImageBounds", fillImageBounds); fillPng = archive.str("fillPng", ""); } void write(Archive::Writer &archive) { archive.boolean("isLinked", isLinked); archive.arr("pathDataList", [&]() { for (size_t i = 0; i < pathDataList.size(); i++) { if (pathDataList[i]->isValid()) { archive.obj(*pathDataList[i]); } } }); archive.obj("fillImageBounds", fillImageBounds); if (fillImageData) {
const char *fileDataString = (const char *)fileData->getData(); size_t fileDataSize = fileData->getSize(); size_t dstlen = 0; char *result = data::encode(data::ENCODE_BASE64, fileDataString, fileDataSize, dstlen, 0); archive.str("fillPng", std::string(result)); delete result; fileData->release(); } else if (fillPng && fillPng->length() > 0) { archive.str("fillPng", *fillPng); } } static graphics::Canvas *newCanvas(int width, int height); static love::image::ImageData *newImageData(graphics::Canvas *canvas); static void renderToCanvas(graphics::Canvas *canvas, const std::function<void()> &lambda); static std::string encodeBase64Png(love::image::ImageData *imageData); static std::string encodeBase64Png(graphics::Canvas *canvas); bool arePathDatasMergable(PathData pd1, PathData pd2); float round(float num, int numDecimalPlaces); std::vector<float> roundFloatArray(std::vector<float> a); void cleanUpPaths(); Bounds getPathDataBounds(std::optional<Bounds> bounds); Bounds getPathDataBoundsInPixelCoordinates(); Bounds getFillImageBoundsInPathCoordinates(); void resetGraphics(); ToveGraphicsHolder *graphics(); void render(); void renderFill(); std::optional<std::string> renderPreviewPng(int size); static graphics::Image *imageDataToImage(image::ImageData *); void resizeFillImageDataToPathBounds(); graphics::Image *getFillImage(); void updateFillImageWithFillImageData(); void compressFillCanvas(); bool floodFill(float x, float y, Colorf color); bool floodClear(float x, float y, float radius); void resetFill(); void updatePathsCanvas(); void deserializeFill(); image::ImageData *canvasToImageData(graphics::Canvas *canvas); DrawDataLayer *parentLayer() { return _parentLayer; } void setParentLayer(DrawDataLayer *l) { _parentLayer = l; } }; typedef std::string DrawDataLayerId; struct DrawDataLayer { std::string title; DrawDataLayerId id; bool isVisible = true; bool isBitmap = false; DrawData *_parent = NULL; std::vector<std::shared_ptr<DrawDataFrame>> frames; DrawDataLayer() = default; DrawDataLayer(std::string title_, DrawDataLayerId id_) : title(title_) , id(id_) { } void read(Archive::Reader &archive) { title = archive.str("title", ""); id = archive.str("id", ""); isVisible = archive.boolean("isVisible", true); isBitmap = archive.boolean("isBitmap", false); archive.arr("frames", [&]() { for (auto i = 0; i < archive.size(); i++) { auto frame = std::make_shared<DrawDataFrame>(); archive.obj(i, *frame); frames.push_back(std::move(frame)); } }); } void write(Archive::Writer &archive) { archive.str("title", title); archive.str("id", id); archive.boolean("isVisible", isVisible); archive.boolean("isBitmap", isBitmap); archive.arr("frames", [&]() { for (size_t i = 0; i < frames.size(); i++) { archive.obj(*frames[i]); } }); } DrawData *parent() { return _parent; } void setParent(DrawData *d) { _parent = d; for (auto &frame : frames) { frame->setParentLayer(this); } } }; } #endif
love::filesystem::FileData *fileData = fillImageData->encode( love::image::FormatHandler::EncodedFormat::ENCODED_PNG, "Image.png", false);
assignment_statement
[]
C++
plugins/CleverbotPlugin/CleverbotPlugin/CleverbotPlugin.cpp
daemon/monkeybot
50bf65674daefa12bfc002771243360bb1d07481
#include "api/Api.h" #include "plugin/Plugin.h" #include "CleverbotHTTP.h" #include <algorithm> #include <future> #include <thread> #include <queue> #include <iostream> #include <string> #include <random> #include <atomic> #include <chrono> #include <curl/curl.h> namespace { const long Timeout = 12000; const ChatMessage::Type ChatType = ChatMessage::Type::Public; const int Channel = 2; const double BaseRespondChance = 0.1; } namespace Random { std::random_device dev; std::mt19937 gen(dev()); double GetReal() { std::uniform_real_distribution<double> dist(0, 1); return dist(gen); } } std::string strtolower(std::string str) { std::transform(str.begin(), str.end(), str.begin(), tolower); return str; } class CleverbotQueue { private: std::shared_ptr<CleverbotHTTP> m_Cleverbot; std::shared_ptr<std::thread> m_Thread; std::queue<std::string> m_Queue; std::mutex m_Mutex; api::Bot* m_Bot; std::atomic<bool> m_Running; ChatMessage::Type m_Type; int m_Channel; void StripEntities(std::string& str) { using namespace std; while (true) { size_t begin = str.find("&"); size_t end = str.find(";"); if (begin == string::npos || end == string::npos || begin >= end) return; str.erase(begin, end - begin + 1); } } bool Contains(std::string str, const std::string& find) { std::string find_lower = strtolower(find); str = strtolower(str); return str.find(find_lower) != std::string::npos; } std::string EraseName(std::string thought) { std::string bot_name = strtolower(m_Bot->GetName()); thought = strtolower(thought); if (thought.compare(bot_name) == 0) return thought; std::size_t pos = thought.find(bot_name); if (pos != std::string::npos) thought.erase(pos, bot_name.length()); if (thought.length() > pos && thought[pos] == ' ') thought.erase(pos, 1); return thought; } void HandleResponse(std::string response) { static const std::vector<std::string> filter = { "clever", "ios app" }; std::cout << "Response: " << response << std::endl; if (response.length() > 0) { if (response.at(0) == '*') response.insert(response.begin(), '.'); for (const std::string& str : filter) if (Contains(response, str)) return; StripEntities(response); std::string to_send; switch (m_Type) { case ChatMessage::Type::Channel: to_send = ";"; if (Channel > 1) to_send += std::to_string(m_Channel) + ";"; break; case ChatMessage::Type::Team: to_send = "'"; break; } to_send += response; m_Bot->SendMessage(to_send); } } void Run() { m_Running = true; while (m_Running) { if (!m_Cleverbot) m_Cleverbot = std::make_shared<CleverbotHTTP>(Timeout); m_Mutex.lock(); if (m_Queue.empty()) { m_Mutex.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); continue; } std::string thought = m_Queue.front(); m_Queue.pop(); m_Mutex.unlock(); thought = EraseName(thought); std::cout << "Thinking: " << thought << std::endl; std::future<std::string> future = std::async(std::launch::async, std::bind(&CleverbotHTTP::Think, m_Cleverbot.get(), thought)); if (future.wait_for(std::chrono::milliseconds(Timeout)) != std::future_status::ready) { std::cout << "Timeout." << std::endl; continue; } HandleResponse(future.get()); } } public: CleverbotQueue(api::Bot* bot, ChatMessage::Type type, int channel) : m_Bot(bot), m_Queue(), m_Mutex(), m_Type(type), m_Channel(channel) { m_Thread = std::make_shared<std::thread>(&CleverbotQueue::Run, this); } ~CleverbotQueue() { m_Running = false; m_Thread->join(); } void Enqueue(const std::string& str) { std::lock_guard<std::mutex> lock(m_Mutex); if (m_Queue.size() < 2) m_Queue.push(str); } }; class CleverbotPlugin : public Plugin { private: typedef std::chrono::system_clock::rep Timestamp; api::Bot* m_Bot; std::shared_ptr<CleverbotQueue> m_CBQ; bool m_LastReference; struct Message { std::string player; std::string message; Message(ChatMessage* mesg) : player(mesg->GetPlayer()), message(mesg->GetMessage()) { } }; struct StoredMessage { Message message; Timestamp timestamp; StoredMessage(ChatMessage* mesg, Timestamp timestamp) : message(mesg), timestamp(timestamp) { } }; typedef std::deque<StoredMessage> ChatQueue; ChatQueue m_ChatQueue; public: CleverbotPlugin(api::Bot* bot) : m_Bot(bot), m_LastReference(false) { } int OnCreate() { m_CBQ = std::make_shared<CleverbotQueue>(m_Bot, ChatType, Channel); std::string version = m_Bot->GetVersion().GetString(); std::cout << "Cleverbot loaded for monkeybot version " << version << std::endl; return 0; } Timestamp GetTime() const { using namespace std::chrono; auto duration = system_clock::now().time_since_epoch(); return duration_cast<milliseconds>(duration).count(); } int OnUpdate(unsigned long dt) { return 0; } int OnDestroy() { return 0; } void PurgeMessages() { const Timestamp AliveTime = 1000 * 60 * 3; const Timestamp timestamp = GetTime(); while (!m_ChatQueue.empty()) { StoredMessage message = m_ChatQueue.front(); if (timestamp - message.timestamp < AliveTime) break; m_ChatQueue.pop_front(); } } std::size_t GetReferenceCount() const { ChatQueue::const_iterator iter = m_ChatQueue.begin(); std::string name = strtolower(m_Bot->GetName()); std::size_t references = 0; while (iter != m_ChatQueue.end()) { std::string message = strtolower(iter->message.message); if (message.find(name) != std::string::npos) ++references; ++iter; } return references; } std::size_t GetChatterCount() const { std::size_t chatters = m_ChatQueue.size(); return chatters; } double GetRespondChance() const { std::size_t chatters = GetChatterCount(); if (chatters <= 1 || m_LastReference) return 1.0; std::size_t references = GetReferenceCount(); return BaseRespondChance + (1.0 / (chatters * 1.75)) + ((references / (double)chatters) * .50); } void OnChatMessage(ChatMessage* mesg) { using namespace std; if (mesg->GetType() != ChatType) return; if (ChatType == ChatMessage::Type::Channel && mesg->GetChannel() != Channel) return; if (mesg->GetPlayer().compare(m_Bot->GetName()) == 0) return; PurgeMessages(); string message = strtolower(mesg->GetMessage()); string name = strtolower(m_Bot->GetName()); double respond_chance = GetRespondChance(); bool contains_name = message.find(name) != string::npos; StoredMessage stored(mesg, GetTime()); bool push = m_ChatQueue.empty() || (!m_ChatQueue.empty() && m_ChatQueue.back().message.player.compare(mesg->GetPlayer()) != 0); if (push) m_ChatQueue.push_back(stored); std::cout << "Chatters: " << GetChatterCount() << " References: " << GetReferenceCount() << " Respond Chance: " << respond_chance << std::endl; if (contains_name || Random::GetReal() <= respond_chance) m_CBQ->Enqueue(mesg->GetMessage()); m_LastReference = contains_name; } }; extern "C" { PLUGIN_FUNC Plugin* CreatePlugin(api::Bot* bot) { curl_global_init(CURL_GLOBAL_ALL); return new CleverbotPlugin(bot); } PLUGIN_FUNC void DestroyPlugin(Plugin* plugin) { delete plugin; curl_global_cleanup(); } PLUGIN_FUNC const char* GetPluginName() { return "CleverbotPlugin"; } }
#include "api/Api.h" #include "plugin/Plugin.h" #include "CleverbotHTTP.h" #include <algorithm> #include <future> #include <thread> #include <queue> #include <iostream> #include <string> #include <random> #include <atomic> #include <chrono> #include <curl/curl.h> namespace { const long Timeout = 12000; const ChatMessage::Type ChatType = ChatMessage::Type::Public; const int Channel = 2; const double BaseRespondChance = 0.1; } namespace Random { std::random_device dev; std::mt19937 gen(dev()); double GetReal() { std::uniform_real_distribution<double> dist(0, 1); return dist(gen); } } std::string strtolower(std::string str) { std::transform(str.begin(), str.end(), str.begin(), tolower); return str; } class CleverbotQueue { private: std::shared_ptr<CleverbotHTTP> m_Cleverbot; std::shared_ptr<std::thread> m_Thread; std::queue<std::string> m_Queue; std::mutex m_Mutex; api::Bot* m_Bot; std::atomic<bool> m_Running; ChatMessage::Type m_Type; int m_Channel;
bool Contains(std::string str, const std::string& find) { std::string find_lower = strtolower(find); str = strtolower(str); return str.find(find_lower) != std::string::npos; } std::string EraseName(std::string thought) { std::string bot_name = strtolower(m_Bot->GetName()); thought = strtolower(thought); if (thought.compare(bot_name) == 0) return thought; std::size_t pos = thought.find(bot_name); if (pos != std::string::npos) thought.erase(pos, bot_name.length()); if (thought.length() > pos && thought[pos] == ' ') thought.erase(pos, 1); return thought; } void HandleResponse(std::string response) { static const std::vector<std::string> filter = { "clever", "ios app" }; std::cout << "Response: " << response << std::endl; if (response.length() > 0) { if (response.at(0) == '*') response.insert(response.begin(), '.'); for (const std::string& str : filter) if (Contains(response, str)) return; StripEntities(response); std::string to_send; switch (m_Type) { case ChatMessage::Type::Channel: to_send = ";"; if (Channel > 1) to_send += std::to_string(m_Channel) + ";"; break; case ChatMessage::Type::Team: to_send = "'"; break; } to_send += response; m_Bot->SendMessage(to_send); } } void Run() { m_Running = true; while (m_Running) { if (!m_Cleverbot) m_Cleverbot = std::make_shared<CleverbotHTTP>(Timeout); m_Mutex.lock(); if (m_Queue.empty()) { m_Mutex.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); continue; } std::string thought = m_Queue.front(); m_Queue.pop(); m_Mutex.unlock(); thought = EraseName(thought); std::cout << "Thinking: " << thought << std::endl; std::future<std::string> future = std::async(std::launch::async, std::bind(&CleverbotHTTP::Think, m_Cleverbot.get(), thought)); if (future.wait_for(std::chrono::milliseconds(Timeout)) != std::future_status::ready) { std::cout << "Timeout." << std::endl; continue; } HandleResponse(future.get()); } } public: CleverbotQueue(api::Bot* bot, ChatMessage::Type type, int channel) : m_Bot(bot), m_Queue(), m_Mutex(), m_Type(type), m_Channel(channel) { m_Thread = std::make_shared<std::thread>(&CleverbotQueue::Run, this); } ~CleverbotQueue() { m_Running = false; m_Thread->join(); } void Enqueue(const std::string& str) { std::lock_guard<std::mutex> lock(m_Mutex); if (m_Queue.size() < 2) m_Queue.push(str); } }; class CleverbotPlugin : public Plugin { private: typedef std::chrono::system_clock::rep Timestamp; api::Bot* m_Bot; std::shared_ptr<CleverbotQueue> m_CBQ; bool m_LastReference; struct Message { std::string player; std::string message; Message(ChatMessage* mesg) : player(mesg->GetPlayer()), message(mesg->GetMessage()) { } }; struct StoredMessage { Message message; Timestamp timestamp; StoredMessage(ChatMessage* mesg, Timestamp timestamp) : message(mesg), timestamp(timestamp) { } }; typedef std::deque<StoredMessage> ChatQueue; ChatQueue m_ChatQueue; public: CleverbotPlugin(api::Bot* bot) : m_Bot(bot), m_LastReference(false) { } int OnCreate() { m_CBQ = std::make_shared<CleverbotQueue>(m_Bot, ChatType, Channel); std::string version = m_Bot->GetVersion().GetString(); std::cout << "Cleverbot loaded for monkeybot version " << version << std::endl; return 0; } Timestamp GetTime() const { using namespace std::chrono; auto duration = system_clock::now().time_since_epoch(); return duration_cast<milliseconds>(duration).count(); } int OnUpdate(unsigned long dt) { return 0; } int OnDestroy() { return 0; } void PurgeMessages() { const Timestamp AliveTime = 1000 * 60 * 3; const Timestamp timestamp = GetTime(); while (!m_ChatQueue.empty()) { StoredMessage message = m_ChatQueue.front(); if (timestamp - message.timestamp < AliveTime) break; m_ChatQueue.pop_front(); } } std::size_t GetReferenceCount() const { ChatQueue::const_iterator iter = m_ChatQueue.begin(); std::string name = strtolower(m_Bot->GetName()); std::size_t references = 0; while (iter != m_ChatQueue.end()) { std::string message = strtolower(iter->message.message); if (message.find(name) != std::string::npos) ++references; ++iter; } return references; } std::size_t GetChatterCount() const { std::size_t chatters = m_ChatQueue.size(); return chatters; } double GetRespondChance() const { std::size_t chatters = GetChatterCount(); if (chatters <= 1 || m_LastReference) return 1.0; std::size_t references = GetReferenceCount(); return BaseRespondChance + (1.0 / (chatters * 1.75)) + ((references / (double)chatters) * .50); } void OnChatMessage(ChatMessage* mesg) { using namespace std; if (mesg->GetType() != ChatType) return; if (ChatType == ChatMessage::Type::Channel && mesg->GetChannel() != Channel) return; if (mesg->GetPlayer().compare(m_Bot->GetName()) == 0) return; PurgeMessages(); string message = strtolower(mesg->GetMessage()); string name = strtolower(m_Bot->GetName()); double respond_chance = GetRespondChance(); bool contains_name = message.find(name) != string::npos; StoredMessage stored(mesg, GetTime()); bool push = m_ChatQueue.empty() || (!m_ChatQueue.empty() && m_ChatQueue.back().message.player.compare(mesg->GetPlayer()) != 0); if (push) m_ChatQueue.push_back(stored); std::cout << "Chatters: " << GetChatterCount() << " References: " << GetReferenceCount() << " Respond Chance: " << respond_chance << std::endl; if (contains_name || Random::GetReal() <= respond_chance) m_CBQ->Enqueue(mesg->GetMessage()); m_LastReference = contains_name; } }; extern "C" { PLUGIN_FUNC Plugin* CreatePlugin(api::Bot* bot) { curl_global_init(CURL_GLOBAL_ALL); return new CleverbotPlugin(bot); } PLUGIN_FUNC void DestroyPlugin(Plugin* plugin) { delete plugin; curl_global_cleanup(); } PLUGIN_FUNC const char* GetPluginName() { return "CleverbotPlugin"; } }
void StripEntities(std::string& str) { using namespace std; while (true) { size_t begin = str.find("&"); size_t end = str.find(";"); if (begin == string::npos || end == string::npos || begin >= end) return; str.erase(begin, end - begin + 1); } }
function_block-full_function
[ { "content": "class int_generator {\n\n public:\n\n typedef typename concurrency::scoped_lock_type scoped_lock_type;\n\n typedef typename concurrency::mutex_type mutex_type;\n\n\n\n /// constructor\n\n //mac TODO: figure out if signed types present a range problem\n\n int_g...
C++
src/hdf5/DataTypeHDF5.cpp
balint42/nix
50f1de33b946b7b194c82fb0efd9b0cecba9ed54
#include <nix/hdf5/DataTypeHDF5.hpp> #include <stdexcept> #include <iostream> #include <cassert> namespace nix { namespace hdf5 { namespace h5x { DataType DataType::copy(hid_t source) { DataType hi_copy = H5Tcopy(source); hi_copy.check("Could not copy type"); return hi_copy; } DataType DataType::makeStrType(size_t size) { DataType str_type = H5Tcopy(H5T_C_S1); str_type.check("Could not create string type"); str_type.size(size); return str_type; } void DataType::size(size_t t) { HErr res = H5Tset_size(hid, t); res.check("DataType::size: Could not set size"); } size_t DataType::size() const { return H5Tget_size(hid); } bool DataType::isVariableString() const { HTri res = H5Tis_variable_str(hid); res.check("DataType::isVariableString(): H5Tis_variable_str failed"); return res.result(); } } h5x::DataType data_type_to_h5_filetype(DataType dtype) { switch (dtype) { case DataType::Bool: return h5x::DataType::copy(H5T_STD_B8LE); case DataType::Int8: return h5x::DataType::copy(H5T_STD_I8LE); case DataType::Int16: return h5x::DataType::copy(H5T_STD_I16LE); case DataType::Int32: return h5x::DataType::copy(H5T_STD_I32LE); case DataType::Int64: return h5x::DataType::copy(H5T_STD_I64LE); case DataType::UInt8: return h5x::DataType::copy(H5T_STD_U8LE); case DataType::UInt16: return h5x::DataType::copy(H5T_STD_U16LE); case DataType::UInt32: return h5x::DataType::copy(H5T_STD_U32LE); case DataType::UInt64: return h5x::DataType::copy(H5T_STD_U64LE); case DataType::Float: return h5x::DataType::copy(H5T_IEEE_F32LE); case DataType::Double: return h5x::DataType::copy(H5T_IEEE_F64LE); case DataType::String: return h5x::DataType::makeStrType(); case DataType::Opaque: return h5x::DataType::copy(H5T_NATIVE_OPAQUE); case DataType::Char: break; case DataType::Nothing: break; case DataType::Date: break; case DataType::DateTime: break; } throw std::invalid_argument("Unkown DataType"); } h5x::DataType data_type_to_h5_memtype(DataType dtype) { switch(dtype) { case DataType::Bool: return h5x::DataType::copy(H5T_NATIVE_B8); case DataType::Int8: return h5x::DataType::copy(H5T_NATIVE_INT8); case DataType::Int16: return h5x::DataType::copy(H5T_NATIVE_INT16); case DataType::Int32: return h5x::DataType::copy(H5T_NATIVE_INT32); case DataType::Int64: return h5x::DataType::copy(H5T_NATIVE_INT64); case DataType::UInt8: return h5x::DataType::copy(H5T_NATIVE_UINT8); case DataType::UInt16: return h5x::DataType::copy(H5T_NATIVE_UINT16); case DataType::UInt32: return h5x::DataType::copy(H5T_NATIVE_UINT32); case DataType::UInt64: return h5x::DataType::copy(H5T_NATIVE_UINT64); case DataType::Float: return h5x::DataType::copy(H5T_NATIVE_FLOAT); case DataType::Double: return h5x::DataType::copy(H5T_NATIVE_DOUBLE); case DataType::String: return h5x::DataType::makeStrType(); case DataType::Opaque: return h5x::DataType::copy(H5T_NATIVE_OPAQUE); case DataType::Char: break; case DataType::Nothing: break; case DataType::Date: break; case DataType::DateTime: break; } throw std::invalid_argument("DataType not handled!"); } #define NOT_IMPLEMENTED false DataType data_type_from_h5(H5T_class_t vclass, size_t vsize, H5T_sign_t vsign) { if (vclass == H5T_INTEGER) { switch (vsize) { case 1: return vsign == H5T_SGN_2 ? DataType::Int8 : DataType::UInt8; case 2: return vsign == H5T_SGN_2 ? DataType::Int16 : DataType::UInt16; case 4: return vsign == H5T_SGN_2 ? DataType::Int32 : DataType::UInt32; case 8: return vsign == H5T_SGN_2 ? DataType::Int64 : DataType::UInt64; } } else if (vclass == H5T_FLOAT) { return vsize == 8 ? DataType::Double : DataType::Float; } else if (vclass == H5T_STRING) { return DataType::String; } else if (vclass == H5T_BITFIELD) { switch (vsize) { case 1: return DataType::Bool; } } std::cerr << "FIXME: Not implemented " << vclass << " " << vsize << " " << vsign << " " << std::endl; assert(NOT_IMPLEMENTED); return DataType::Nothing; } } }
#include <nix/hdf5/DataTypeHDF5.hpp> #include <stdexcept> #include <iostream> #include <cassert> namespace nix { namespace hdf5 { namespace h5x { DataType DataType::copy(hid_t source) { DataType hi_copy = H5Tcopy(source); hi_copy.check("Could not copy type"); return hi_copy; } DataType DataType::makeStrType(size_t size) { DataType str_type = H5Tcopy(H5T_C_S1); str_type.check("Could not create string type"); str_type.size(size); return str_type; } void DataType::size(size_t t) { HErr res = H5Tset_size(hid, t); res.check("DataType::size: Could not set size"); } size_t DataType::size() const { return H5Tget_size(hid); } bool DataType::isVariableString() const { HTri res = H5Tis_variable_str(hid); res.check("DataType::isVariableString(): H5Tis_variable_str failed"); return res.result(); } } h5x::DataType data_type_to_h5_filetype(DataType dtype) { switch (dtype) { case DataType::Bool: return h5x::DataType::copy(H5T_STD_B8LE); case DataType::Int8: return h5x::DataType::copy(H5T_STD_I8LE); case DataType::Int16: return h5x::DataType::copy(H5T_STD_I16LE); case DataType::Int32: return h5x::DataType::copy(H5T_STD_I32LE); case DataType::Int64: return h5x::DataType::copy(H5T_STD_I64LE); case DataType::UInt8: return h5x::DataType::copy(H5T_STD_U8LE); case DataType::UInt16: return h5x::DataType::copy(H5T_STD_U16LE); case DataType::UInt32: return h5x::DataType::copy(H5T_STD_U32LE); case DataType::UInt64: return h5x::DataType::copy(H5T_STD_U64LE); case DataType::Float: return h5x::DataType::copy(H5T_IEEE_F32LE); case DataType::Double: return h5x::DataType::copy(H5T_IEEE_F64LE); case DataType::String: return h5x::DataType::makeStrType(); case DataType::Opaque: return h5x::DataType::copy(H5T_NATIVE_OPAQUE); case DataType::Char: break; case DataType::Nothing: break; case DataType::Date: break; case DataType::DateTime: break; } throw std::invalid_argument("Unkown DataType"); } h5x::DataType data_type_to_h5_memtype(DataType dtype) { switch(dtype) { case DataType::Bool: return h5x::DataType::copy(H5T_NATIVE_B8); case DataType::Int8: return h5x::DataType::copy(H5T_NATIVE_INT8); case DataType::Int16: return h5x::DataType::copy(H5T_NATIVE_INT16); case DataType::Int32: return h5x::DataType::copy(H5T_NATIVE_INT32); case DataType::Int64: return h5x::DataType::copy(H5T_NATIVE_INT64); case DataType::UInt8: return h5x::DataType::copy(H5T_NATIVE_UINT8); case DataType::UInt16: return h5x::DataType::copy(H5T_NATIVE_UINT16); case DataType::UInt32: return h5x::DataType::copy(H5T_NATIVE_UINT32); case DataType::UInt64: return h5x::DataType::copy(H5T_NATIVE_UINT64); case DataType::Float: return h5x::DataType::copy(H5T_NATIVE_FLOAT); case DataType::Double: return h5x::DataType::copy(H5T_NATIVE_DOUBLE); case DataType::String: return h5x::DataType::makeStrType(); case DataType::Opaque: return h5x::DataType::copy(H5T_NATIVE_OPAQUE); case DataType::Char: break; case DataType::Nothing: break; case DataType::Date: break; case DataType::DateTime: break; } throw std::invalid_argument("DataType not handled!"); } #define NOT_IMPLEMENTED false DataType data_type_from_h5(H5T_class_t vclass, size_t vsize, H5T_sign_t vsign) { if (vclass == H5T_INTEGER) { switch (vsize) { case 1: return vsign == H5T_SGN_2 ? DataType::Int8 : DataType::UInt8; case 2: return vsign == H5T_SGN_2 ? DataType::Int16 : DataType::UInt16; case 4: return vsign == H5T_SGN_2 ? DataType::Int32 : DataType::UInt32; case 8: return vsign == H5T_SGN_2 ? DataType::Int64 : DataType::UInt64; } } else if (vclass == H5T_FLOAT) { return vsize == 8 ? DataType::Double : DataType::Float; } else
std::cerr << "FIXME: Not implemented " << vclass << " " << vsize << " " << vsign << " " << std::endl; assert(NOT_IMPLEMENTED); return DataType::Nothing; } } }
if (vclass == H5T_STRING) { return DataType::String; } else if (vclass == H5T_BITFIELD) { switch (vsize) { case 1: return DataType::Bool; } }
if_condition
[ { "content": "struct to_data_type<bool> {\n\n static const bool is_valid = true;\n\n static const DataType value = DataType::Bool;\n\n};\n\n\n\n/**\n\n * @brief Determine if a type is a valid data type.\n\n */\n\ntemplate<>\n", "file_path": "include/nix/DataType.hpp", "rank": 0, "score": 18745...
C++
src/base/circlebuffer.cpp
aksenofo/sparrow
c0300700a023f374ebb8faa69bcefe261e99d9d5
#include "circlebuffer.h" namespace sparrow { CircularBuffer::CircularBuffer(uint32_t size) : m_size(size) { m_buffer.reset(new uint8_t[m_size]); m_head = m_tail = m_buffer.get(); m_state = m_size == 0 ? Full : Empty; } uint32_t CircularBuffer::WriteEnd(const void* ptr, uint32_t size) noexcept { assert(m_tail <= m_head); const uint8_t* curPtr = reinterpret_cast<const uint8_t*>(ptr); uint32_t canWrite = std::min(size, uint32_t(Eob() - m_head)); memcpy(m_head, curPtr, canWrite); size -= canWrite; m_head += canWrite; assert(m_head <= Eob()); if (m_head == Eob()) m_head = m_buffer.get(); m_state = m_head == m_tail ? Full : Unknown; return size; } uint32_t CircularBuffer::WriteBegin(const void* ptr, uint32_t size) noexcept { assert(m_tail > m_head); const uint8_t* curPtr = reinterpret_cast<const uint8_t*>(ptr); uint32_t canWrite = std::min(size, uint32_t(m_tail - m_head)); memcpy(m_head, curPtr, canWrite); size -= canWrite; m_head += canWrite; assert(m_head <= m_tail); m_state = m_head == m_tail ? Full : Unknown; return size; } uint32_t CircularBuffer::Put(const void* ptr, uint32_t size) noexcept { const uint8_t* curPtr = reinterpret_cast<const uint8_t*>(ptr); if (m_state == Full || size == 0) return 0; uint32_t sizeRest = size; if (m_tail <= m_head) { sizeRest = WriteEnd(ptr, size); curPtr += size - sizeRest; if (m_state == Full || sizeRest == 0) return size - sizeRest; } sizeRest = WriteBegin(curPtr, sizeRest); return size - sizeRest; } uint8_t CircularBuffer::Get() { uint8_t v; if (ConsumeSize() > 0) { v = *Ptr(); Consume(1); } else throw std::runtime_error("Not enough data in buffer."); return v; } void CircularBuffer::Reset() noexcept { m_head = m_tail = m_buffer.get(); m_state = m_size == 0 ? Full : Empty; } uint32_t CircularBuffer::ConsumeSize() noexcept { if (m_state == Empty) return 0; if (m_tail < m_head) return m_head - m_tail; else return Eob() - m_tail; } uint32_t CircularBuffer::PopulateSize() noexcept { if (IsFull()) return 0; if (m_head >= m_tail) return Eob() - m_head; else return m_tail - m_head; } void CircularBuffer::Populate(uint32_t size) noexcept { if (size == 0) return; assert(m_state != Full); if (m_tail <= m_head) { assert(m_head + size <= Eob()); m_head += size; } else { assert(m_head + size <= m_tail); m_head += size; } if (m_head == Eob()) m_head = m_buffer.get(); if (m_tail == m_head) m_state = Full; else m_state = Unknown; } void CircularBuffer::Consume(uint32_t size) noexcept { if (size == 0) return; assert(m_state != Empty); assert(m_tail + size <= Eob()); m_tail += size; if (m_tail == Eob()) m_tail = m_buffer.get(); if (m_tail == m_head) m_state = Empty; else m_state = Unknown; } uint32_t CircularBuffer::FilledSize() const noexcept { if (m_state == Full) return m_size; if (m_tail <= m_head) return m_head - m_tail; else return (Eob() - m_tail) + m_head - m_buffer.get(); } uint32_t CircularBuffer::Get(void* ptr, uint32_t size) noexcept { uint32_t ts1 = std::min(ConsumeSize(), size); if (ts1 == 0) return 0; memcpy(ptr, Ptr(), ts1); Consume(ts1); uint32_t ts2 = std::min(ConsumeSize(), size - ts1); if (ts2 == 0) return ts1; memcpy(reinterpret_cast<uint8_t*>(ptr) + ts1, Ptr(), ts2); Consume(ts2); return ts1 + ts2; } uint32_t CircularBuffer::PutLatecomer(uint32_t lateSize, const void* ptr, uint32_t size) noexcept { const uint8_t* point = static_cast<const uint8_t*>(ptr); if (IsEmpty() || size == 0) { return 0; } else if (m_head > m_tail) { uint8_t* stop = m_head - lateSize; uint8_t* start = stop - size; if (stop < m_tail) return 0; start = std::max(start, m_tail); if (start < m_buffer.get() + m_size) { memcpy(start, point, stop - start); return stop - start; } return 0; } else { uint32_t consumed = 0; uint32_t s1 = m_buffer.get() + m_size - m_tail; if (s1 < lateSize) lateSize -= s1; else { uint8_t* start = m_tail + lateSize; uint8_t* stop = std::min(m_buffer.get() + m_size, start + size); memcpy(start, point, stop - start); point += stop - start; consumed += stop - start; size -= stop - start; lateSize = 0; } uint32_t s2 = m_buffer.get() - m_head; if (s1 < lateSize) return consumed; else { uint8_t* start = m_buffer.get() + lateSize; uint8_t* stop = std::min(start + size, m_head); memcpy(start, point, stop - start); consumed += stop - start; } return consumed; } } uint32_t CircularBuffer::Blocks() const noexcept { if (m_state == Empty) { return 0; } if (m_tail < m_head) return 1; else return 2; } }
#include "circlebuffer.h" namespace sparrow { CircularBuffer::CircularBuffer(uint32_t size) : m_size(size) { m_buffer.reset(new uint8_t[m_size]); m_head = m_tail = m_buffer.get(); m_state = m_size == 0 ? Full : Empty; } uint32_t CircularBuffer::WriteEnd(const void* ptr, uint32_t size) noexcept { assert(m_tail <= m_head); const uint8_t* curPtr = reinterpret_cast<const uint8_t*>(ptr); uint32_t canWrite = std::min(size, uint32_t(Eob() - m_head)); memcpy(m_head, curPtr, canWrite); size -= canWrite; m_head += canWrite; assert(m_head <= Eob()); if (m_head == Eob()) m_head = m_buffer.get(); m_state = m_head == m_tail ? Full : Unknown; return size; } uint32_t CircularBuffer::WriteBegin(const void* ptr, uint32_t size) noexcept { assert(m_tail > m_head); const uint8_t* curPtr = reinterpret_cast<const uint8_t*>(ptr); uint32_t canWrite = std::min(size, uint32_t(m_tail - m_head)); memcpy(m_head, curPtr, canWrite); size -= canWrite; m_head += canWrite; assert(m_head <= m_tail); m_state = m_head == m_tail ? Full : Unknown; return size; } uint32_t CircularBuffer::Put(const void* ptr, uint32_t size) noexcept { const uint8_t* curPtr = reinterpret_cast<const uint8_t*>(ptr); if (m_state == Full || size == 0) return 0; uint32_t sizeRest = size; if (m_tail <= m_head) { sizeRest = WriteEnd(ptr, size); curPtr += size - sizeRest; if (m_state == Full || sizeRest == 0) return size - sizeRest; } sizeRest = WriteBegin(curPtr, sizeRest); return size - sizeRest; } uint8_t CircularBuffer::Get() { uint8_t v; if (ConsumeSize() > 0) { v = *Ptr(); Consume(1); } else throw std::runtime_error("Not enough data in buffer."); return v; } void CircularBuffer::Reset() noexcept { m_head = m_tail = m_buffer.get(); m_state = m_size == 0 ? Full : Empty; } uint32_t CircularBuffer::ConsumeSize() noexcept { if (m_state == Empty) return 0; if (m_tail < m_head) return m_head - m_tail; else return Eob() - m_tail; } uint32_t CircularBuffer::PopulateSize() noexcept { if (IsFull()) return 0; if (m_head >= m_tail) return Eob() - m_head; else return m_tail - m_head; } void CircularBuffer::Populate(uint32_t size) noexcept { if (size == 0) return; assert(m_state != Full); if (m_tail <= m_head) { assert(m_head + size <= Eob()); m_head += size; } else { assert(m_head + size <= m_tail); m_head += size; } if (m_head == Eob()) m_head = m_buffer.get(); if (m_tail == m_head) m_state = Full; else m_state = Unknown; } void CircularBuffer::Consume(uint32_t size) noexcept { if (size == 0) return; assert(m_state != Empty); assert(m_tail + size <= Eob()); m_tail += size; if (m_tail == Eob()) m_tail = m_buffer.get(); if (m_tail == m_head) m_state = Empty; else m_state = Unknown; } uint32_t CircularBuffer::FilledSize() const noexcept { if (m_state == Full) return m_size; if (m_tail <= m_head) return m_head - m_tail; else return (Eob() - m_tail) + m_head - m_buffer.get(); } uint32_t CircularBuffer::Get(void* ptr, uint32_t size) noexcept { uint32_t ts1 = std::min(ConsumeSize(), size); if (ts1 == 0) return 0; memcpy(ptr, Ptr(), ts1); Consume(ts1); uint32_t ts2 = std::min(ConsumeSize(), size - ts1); if (ts2 == 0) return ts1; memcpy(reinterpret_cast<uint8_t*>(ptr) + ts1, Ptr(), ts2); Consume(ts2); return ts1 + ts2; } uint32_t CircularBuffer::PutLatecomer(uint32_t lateSize, const void* ptr, uint32_t size) noexcept { const uint8_t* point = static_cast<const uint8_t*>(ptr); if (IsEmpty() || size == 0) { return 0; } else if (m_head > m_tail) { uint8_t* stop = m_head - lateSize; uint8_t* start = stop - size; if (stop < m_tail) return 0; start = std::max(start, m_tail); if (start < m_buffer.get() + m_size) { memcpy(start, point, stop - start); return stop - start; } return 0; } else { uint32_t consumed = 0; uint32_t s1 = m_buffer.get() + m_size - m_tail; if (s1 < lateSize) lateSize -= s1; else { uint8_t*
} uint32_t s2 = m_buffer.get() - m_head; if (s1 < lateSize) return consumed; else { uint8_t* start = m_buffer.get() + lateSize; uint8_t* stop = std::min(start + size, m_head); memcpy(start, point, stop - start); consumed += stop - start; } return consumed; } } uint32_t CircularBuffer::Blocks() const noexcept { if (m_state == Empty) { return 0; } if (m_tail < m_head) return 1; else return 2; } }
start = m_tail + lateSize; uint8_t* stop = std::min(m_buffer.get() + m_size, start + size); memcpy(start, point, stop - start); point += stop - start; consumed += stop - start; size -= stop - start; lateSize = 0;
random
[ { "content": "class Consumer\n\n{\n\npublic:\n\n Consumer() = default;\n\n COPYBLE_DEFAULT(Consumer);\n\n MOVEBLE_DEFAULT(Consumer);\n\n\n\n template<typename Func>\n\n uint32_t operator()(CircularBuffer& circularBuffer, Func fn)\n\n {\n\n uint32_t totallyConsumed = 0;\n\n while ...
C++
caffe2/operators/load_save_op_util.cc
wenhaopeter/read_pytorch_code
491f989cd918cf08874dd4f671fb7f0142a0bc4f
#include "caffe2/operators/load_save_op_util.h" namespace caffe2 { namespace load_save_op_util { std::string buildBlobNameFromDbKey( const std::string& dbKey, const std::string& strip_prefix, const std::string& add_prefix) { std::string key = dbKey.substr(0, dbKey.find(kChunkIdSeparator)); if (!strip_prefix.empty()) { auto match_pos = key.find(strip_prefix); if (match_pos != std::string::npos) { key = key.substr(match_pos + strip_prefix.size()); } } key = add_prefix + key; return key; } void ProcessBlob( Blob* blob, const BlobProto& proto, std::unordered_map<std::string, BlobState>* blob_states_ptr, const std::string& key, int* loaded_blobs) { auto& blob_states = *blob_states_ptr; if (blob_states.count(key) == 0) { blob->Reset(); } DeserializeBlob(proto, blob); if (proto.has_content_num_chunks()) { if (!blob_states.count(key)) { blob_states[key] = BlobState(proto.content_num_chunks()); } CAFFE_ENFORCE( blob_states[key] .seen_chunks_ids.insert(proto.content_chunk_id()) .second, "Chunk with the same id has occurred twice for: ", key); CAFFE_ENFORCE( proto.content_chunk_id() >= 0 && proto.content_chunk_id() < blob_states[key].total_size, "Chunk id has to be not less than 0 and " "less than content_num_chunks for key: ", key); blob_states[key].current_size++; CAFFE_ENFORCE( !blob_states[key].is_tensor, "Proto with content_chunks can not store tensor: ", key); CAFFE_ENFORCE( blob_states[key].current_size <= blob_states[key].total_size, "Found an extra part for an already filled blob: ", key); if (blob_states[key].current_size == blob_states[key].total_size) { (*loaded_blobs)++; } return; } if (!proto.has_tensor()) { CAFFE_ENFORCE(blob_states.count(key) == 0, "Blob duplicated: ", key); blob_states[key] = BlobState(); (*loaded_blobs)++; return; } CAFFE_ENFORCE(proto.has_tensor()); if (blob_states.count(key)) { CAFFE_ENFORCE(blob_states[key].is_tensor, "Must be tensor ", key); CAFFE_ENFORCE( blob_states[key].current_size < blob_states[key].total_size, "Found an extra part for an already filled tensor: ", key); CAFFE_ENFORCE( proto.tensor().has_segment(), "Partial tensor must have a segment: ", key); blob_states[key].current_size += proto.tensor().segment().end() - proto.tensor().segment().begin(); CAFFE_ENFORCE( blob_states[key].current_size <= blob_states[key].total_size, "Tensor parts are bigger than target size for tensor: ", key); } else { const auto& dims = proto.tensor().dims(); int64_t total_size = 1; for (const auto& dim : dims) { total_size *= dim; } auto current_size = total_size; if (proto.tensor().has_segment()) { current_size = proto.tensor().segment().end() - proto.tensor().segment().begin(); } blob_states[key] = BlobState(total_size, current_size, true ); } if (blob_states[key].current_size == blob_states[key].total_size) { (*loaded_blobs)++; } } void validateBlobStates( const std::unordered_map<std::string, BlobState>& blob_states) { for (const auto& iter : blob_states) { const BlobState& blob_state = iter.second; CAFFE_ENFORCE( blob_state.current_size == blob_state.total_size, "Data size mismatch for blob ", iter.first, ". Expected: ", blob_state.total_size, " Read: ", blob_state.current_size); } } } }
#include "caffe2/operators/load_save_op_util.h" namespace caffe2 { namespace load_save_op_util { std::string buildBlobNameFromDbKey( const std::string& dbKey, const std::string& strip_prefix, const std::string& add_prefix) { std::string key = dbKey.substr(0, dbKey.find(kChunkIdSeparator)); if (!strip_prefix.empty()) { auto match_pos = key.find(strip_prefix); if (match_pos != std::string::npos) { key = key.substr(match_pos + strip_prefix.size()); } } key = add_prefix + key; return key; } void ProcessBlob( Blob* blob, const BlobProto& proto, std::unordered_map<std::string, BlobState>* blob_states_ptr, const std::string& key, int* loaded_blobs) { auto& blob_states = *blob_states_ptr; if (blob_states.count(key) == 0) { blob->Reset(); } DeserializeBlob(proto, blob); if (proto.has_content_num_chunks()) { if (!blob_states.count(key)) { blob_states[key] = BlobState(proto.content_num_chunks()); } CAFFE_ENFORCE( blob_states[key] .seen_chunks_ids.insert(proto.content_chunk_id()) .second, "Chunk with the same id has occurred twice for: ", key); CAFFE_ENFORCE( proto.content_chunk_id() >= 0 && proto.content_chunk_id() < blob_states[key].total_size, "Chunk id has to be not less than 0 and " "less than content_num_chunks for key: ", key); blob_states[key].current_size++; CAFFE_ENFORCE( !blob_states[key].is_tensor, "Proto with content_chunks can not store tensor: ", key); CAFFE_ENFORCE( blob_states[key].current_size <= blob_states[key].total_size, "Found an extra part for an already filled blob: ", key); if (blob_states[key].current_size == blob_states[key].total_size) { (*loaded_blobs)++; } return; } if (!proto.has_tensor()) { CAFFE_ENFORCE(blob_states.count(key) == 0, "Blob duplicated: ", key); blob_states[key] = BlobState(); (*loaded_blobs)++; return; } CAFFE_ENFORCE(proto.has_tensor()); if (blob_states.count(key)) { CAFFE_ENFORCE(blob_states[key].is_tensor, "Must be tensor ", key);
; CAFFE_ENFORCE( proto.tensor().has_segment(), "Partial tensor must have a segment: ", key); blob_states[key].current_size += proto.tensor().segment().end() - proto.tensor().segment().begin(); CAFFE_ENFORCE( blob_states[key].current_size <= blob_states[key].total_size, "Tensor parts are bigger than target size for tensor: ", key); } else { const auto& dims = proto.tensor().dims(); int64_t total_size = 1; for (const auto& dim : dims) { total_size *= dim; } auto current_size = total_size; if (proto.tensor().has_segment()) { current_size = proto.tensor().segment().end() - proto.tensor().segment().begin(); } blob_states[key] = BlobState(total_size, current_size, true ); } if (blob_states[key].current_size == blob_states[key].total_size) { (*loaded_blobs)++; } } void validateBlobStates( const std::unordered_map<std::string, BlobState>& blob_states) { for (const auto& iter : blob_states) { const BlobState& blob_state = iter.second; CAFFE_ENFORCE( blob_state.current_size == blob_state.total_size, "Data size mismatch for blob ", iter.first, ". Expected: ", blob_state.total_size, " Read: ", blob_state.current_size); } } } }
CAFFE_ENFORCE( blob_states[key].current_size < blob_states[key].total_size, "Found an extra part for an already filled tensor: ", key)
call_expression
[ { "content": "class Int8GivenIntTensorFillOp final : public Operator<CPUContext> {\n\n public:\n\n template <class... Args>\n\n explicit Int8GivenIntTensorFillOp(Args&&... args)\n\n : Operator<CPUContext>(std::forward<Args>(args)...),\n\n scale_(this->template GetSingleArgument<float>(\"Y_scale\",...
C++
test/syscalls/linux/close_range.cc
neilalexander/gvisor
14807179c24110d46441efbf30cf375a22d04e57
#include <asm-generic/errno-base.h> #include <unistd.h> #include <vector> #include "gtest/gtest.h" #include "absl/base/macros.h" #include "test/util/file_descriptor.h" #include "test/util/posix_error.h" #include "test/util/temp_path.h" #include "test/util/test_util.h" namespace gvisor { namespace testing { namespace { #ifndef CLOSE_RANGE_UNSHARE #define CLOSE_RANGE_UNSHARE (1U << 1) #endif #ifndef CLOSE_RANGE_CLOEXEC #define CLOSE_RANGE_CLOEXEC (1U << 2) #endif #ifndef SYS_close_range #if defined(__x86_64__) || defined(__aarch64__) #define SYS_close_range 436 #else #error "Unknown architecture" #endif #endif int close_range(unsigned int first, unsigned int last, unsigned int flags) { return syscall(SYS_close_range, first, last, flags); } class CloseRangeTest : public ::testing::Test { public: void CreateFiles(int num_files) { file_names_.reserve(num_files); for (int i = 0; i < num_files; ++i) { file_names_.push_back(NewTempAbsPath()); int fd; ASSERT_THAT(fd = open(file_names_[i].c_str(), O_CREAT, 0644), SyscallSucceeds()); ASSERT_THAT(close(fd), SyscallSucceeds()); } } void OpenFilesRdwr() { fds_.clear(); fds_.reserve(file_names_.size()); for (std::string &file_name : file_names_) { int fd; ASSERT_THAT(fd = open(file_name.c_str(), O_RDWR), SyscallSucceeds()); fds_.push_back(fd); } } private: void TearDown() override { for (std::string &name : file_names_) { unlink(name.c_str()); } } protected: std::vector<std::string> file_names_; std::vector<unsigned int> fds_; }; TEST_F(CloseRangeTest, ContiguousRange) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = 0; CreateFiles(num_files_in_range); OpenFilesRdwr(); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallSucceeds()); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, PosixErrorIs(EBADF)); } } TEST_F(CloseRangeTest, RangeWithHoles) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = 0; CreateFiles(num_files_in_range); OpenFilesRdwr(); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } EXPECT_THAT(close(fds_[2]), SyscallSucceeds()); EXPECT_THAT(close(fds_[7]), SyscallSucceeds()); EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallSucceeds()); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, PosixErrorIs(EBADF)); } } TEST_F(CloseRangeTest, RangeInMiddleOfOpenFiles) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = 0; CreateFiles(num_files_in_range); OpenFilesRdwr(); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } size_t slice_start = 4; size_t slice_end = 7; EXPECT_THAT(close_range(fds_[slice_start], fds_[slice_end], flags), SyscallSucceeds()); for (int fd : std::vector(fds_.begin() + slice_start, fds_.begin() + slice_end + 1)) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, PosixErrorIs(EBADF)); } for (int fd : std::vector(fds_.begin(), fds_.begin() + slice_start)) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } for (int fd : std::vector(fds_.begin() + slice_end + 1, fds_.end())) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } } TEST_F(CloseRangeTest, SingleFile) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 1; unsigned int flags = 0; CreateFiles(num_files_in_range); OpenFilesRdwr(); auto ret = ReadAllFd(fds_[0]); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); EXPECT_THAT(close_range(fds_[0], fds_[0], flags), SyscallSucceeds()); ret = ReadAllFd(fds_[0]); EXPECT_THAT(ret, PosixErrorIs(EBADF)); } TEST_F(CloseRangeTest, CallCloseRangeTwice) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = 0; CreateFiles(num_files_in_range); OpenFilesRdwr(); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallSucceeds()); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, PosixErrorIs(EBADF)); } EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallSucceeds()); } TEST_F(CloseRangeTest, CloexecFlagTest) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = CLOSE_RANGE_CLOEXEC; CreateFiles(num_files_in_range); OpenFilesRdwr(); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallSucceeds()); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } } TEST_F(CloseRangeTest, UnshareFlagTest) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = CLOSE_RANGE_UNSHARE; CreateFiles(num_files_in_range); OpenFilesRdwr(); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallSucceeds()); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, PosixErrorIs(EBADF)); } } TEST_F(CloseRangeTest, UnshareFlagAndCloseRangeAtStart) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = CLOSE_RANGE_UNSHARE; CreateFiles(num_files_in_range); OpenFilesRdwr(); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } size_t range_split = 5; EXPECT_THAT(close_range(fds_[0], fds_[range_split - 1], flags), SyscallSucceeds()); for (int fd : std::vector(fds_.begin(), fds_.begin() + range_split)) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, PosixErrorIs(EBADF)); } for (int fd : std::vector(fds_.begin() + range_split, fds_.end())) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } } TEST_F(CloseRangeTest, UnshareFlagAndCloseRangeAtEnd) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = CLOSE_RANGE_UNSHARE; CreateFiles(num_files_in_range); OpenFilesRdwr(); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } size_t range_split = 5; EXPECT_THAT( close_range(fds_[range_split], fds_[num_files_in_range - 1], flags), SyscallSucceeds()); for (int fd : std::vector(fds_.begin(), fds_.begin() + range_split)) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } for (int fd : std::vector(fds_.begin() + range_split, fds_.end())) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, PosixErrorIs(EBADF)); } } TEST_F(CloseRangeTest, CloexecAndUnshareFlagTest) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = CLOSE_RANGE_CLOEXEC | CLOSE_RANGE_UNSHARE; CreateFiles(num_files_in_range); OpenFilesRdwr(); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallSucceeds()); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } } TEST_F(CloseRangeTest, RangeFirstGreaterThanLast) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = 0; CreateFiles(num_files_in_range); OpenFilesRdwr(); EXPECT_THAT(close_range(fds_[num_files_in_range - 1], fds_[0], flags), SyscallFailsWithErrno(EINVAL)); } TEST_F(CloseRangeTest, InvalidFlags) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; CreateFiles(num_files_in_range); OpenFilesRdwr(); unsigned int flags = CLOSE_RANGE_CLOEXEC | CLOSE_RANGE_UNSHARE | 0xF; EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallFailsWithErrno(EINVAL)); flags = 0xF0; EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallFailsWithErrno(EINVAL)); flags = CLOSE_RANGE_CLOEXEC | 0xF00; EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallFailsWithErrno(EINVAL)); } } } }
#include <asm-generic/errno-base.h> #include <unistd.h> #include <vector> #include "gtest/gtest.h" #include "absl/base/macros.h" #include "test/util/file_descriptor.h" #include "test/util/posix_error.h" #include "test/util/temp_path.h" #include "test/util/test_util.h" namespace gvisor { namespace testing { namespace { #ifndef CLOSE_RANGE_UNSHARE #define CLOSE_RANGE_UNSHARE (1U << 1) #endif #ifndef CLOSE_RANGE_CLOEXEC #define CLOSE_RANGE_CLOEXEC (1U << 2) #endif #ifndef SYS_close_range #if defined(__x86_64__) || defined(__aarch64__) #define SYS_close_range 436 #else #error "Unknown architecture" #endif #endif int close_range(unsigned int first, unsigned int last, unsigned int flags) { return syscall(SYS_close_range, first, last, flags); } class CloseRangeTest : public ::testing::Test { public: void CreateFiles(int num_files) { file_names_.reserve(num_files); for (int i = 0; i < num_files; ++i) { file_names_.push_back(NewTempAbsPath()); int fd; ASSERT_THAT(fd = open(file_names_[i].c_str(), O_CREAT, 0644), SyscallSucceeds()); ASSERT_THAT(close(fd), SyscallSucceeds()); } } void OpenFilesRdwr() { fds_.clear(); fds_.reserve(file_names_.size()); for (std::string &file_name : file_names_) { int fd; ASSERT_THAT(fd = open(file_name.c_str(), O_RDWR), SyscallSucceeds()); fds_.push_back(fd); } } private: void TearDown() override { for (std::string &name : file_names_) { unlink(name.c_str()); } } protected: std::vector<std::string> file_names_; std::vector<unsigned int> fds_; }; TEST_F(CloseRangeTest, ContiguousRange) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = 0; CreateFiles(num_files_in_range); OpenFilesRdwr(); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallSucceeds()); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, PosixErrorIs(EBADF)); } } TEST_F(CloseRangeTest, RangeWithHoles) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = 0; CreateFiles(num_files_in_range); OpenFilesRdwr(); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } EXPECT_THAT(close(fds_[2]), SyscallSucceeds()); EXPECT_THAT(close(fds_[7]), SyscallSucceeds()); EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallSucceeds()); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, PosixErrorIs(EBADF)); } } TEST_F(CloseRangeTest, RangeInMiddleOfOpenFiles) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = 0; CreateFiles(num_files_in_range); OpenFilesRdwr(); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } size_t slice_start = 4; size_t slice_end = 7; EXPECT_THAT(close_range(fds_[slice_start], fds_[slice_end], flags), SyscallSucceeds()); for (int fd : std::vector(fds_.begin() + slice_start, fds_.begin() + slice_end + 1)) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, PosixErrorIs(EBADF)); } for (int fd : std::vector(fds_.begin(), fds_.begin() + slice_start)) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } for (int fd : std::vector(fds_.begin() + slice_end + 1, fds_.end())) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } } TEST_F(CloseRangeTest, SingleFile) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 1; unsigned int flags = 0; CreateFiles(num_files_in_range); OpenFilesRdwr(); auto ret = ReadAllFd(fds_[0]); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); EXPECT_THAT(close_range(fds_[0], fds_[0], flags), SyscallSucceeds()); ret = ReadAllFd(fds_[0]); EXPECT_THAT(ret, PosixErrorIs(EBADF)); } TEST_F(CloseRangeTest, CallCloseRangeTwice) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = 0; CreateFiles(num_files_in_range); OpenFilesRdwr(); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallSucceeds()); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, PosixErrorIs(EBADF)); } EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallSucceeds()); } TEST_F(CloseRangeTest, CloexecFlagTest) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = CLOSE_RANGE_CLOEXEC; CreateFiles(num_files_in_range); OpenFilesRdwr(); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallSucceeds()); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } } TEST_F(CloseRangeTest, UnshareFlagTest) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = CLOSE_RANGE_UNSHARE; CreateFiles(num_files_in_range); OpenFilesRdwr(); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallSucceeds()); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, PosixErrorIs(EBADF)); } } TEST_F(CloseRangeTest, UnshareFlagAndCloseRangeAtStart) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = CLOSE_RANGE_UNSHARE; CreateFiles(num_files_in_range); OpenFilesRdwr(); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } size_t range_split = 5; EXPECT_THAT(close_range(fds_[0], fds_[range_split - 1], flags), SyscallSucceeds()); for (int fd : std::vector(fds_.begin(), fds_.begin() + range_split)) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, PosixErrorIs(EBADF)); } for (int fd : std::vector(fds_.begin() + range_split, fds_.end())) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } } TEST_F(CloseRangeTest, UnshareFlagAndCloseRangeAtEnd) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = CLOSE_RANGE_UNSHARE; CreateFiles(num_files_in_range); OpenFilesRdwr(); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } size_t range_split = 5; EXPECT_THAT( close_range(fds_[range_split], fds_[num_files_in_range - 1], flags), SyscallSucceeds()); for (int fd : std::vector(fds_.begin(), fds_.begin() + range_split)) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } for (int fd : std::vector(fds_.begin() + range_split, fds_.end())) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, PosixErrorIs(EBADF)); } }
TEST_F(CloseRangeTest, RangeFirstGreaterThanLast) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = 0; CreateFiles(num_files_in_range); OpenFilesRdwr(); EXPECT_THAT(close_range(fds_[num_files_in_range - 1], fds_[0], flags), SyscallFailsWithErrno(EINVAL)); } TEST_F(CloseRangeTest, InvalidFlags) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; CreateFiles(num_files_in_range); OpenFilesRdwr(); unsigned int flags = CLOSE_RANGE_CLOEXEC | CLOSE_RANGE_UNSHARE | 0xF; EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallFailsWithErrno(EINVAL)); flags = 0xF0; EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallFailsWithErrno(EINVAL)); flags = CLOSE_RANGE_CLOEXEC | 0xF00; EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallFailsWithErrno(EINVAL)); } } } }
TEST_F(CloseRangeTest, CloexecAndUnshareFlagTest) { SKIP_IF(!IsRunningOnGvisor() && close_range(1, 0, 0) < 0 && errno == ENOSYS); int num_files_in_range = 10; unsigned int flags = CLOSE_RANGE_CLOEXEC | CLOSE_RANGE_UNSHARE; CreateFiles(num_files_in_range); OpenFilesRdwr(); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } EXPECT_THAT(close_range(fds_[0], fds_[num_files_in_range - 1], flags), SyscallSucceeds()); for (int fd : fds_) { auto ret = ReadAllFd(fd); EXPECT_THAT(ret, IsPosixErrorOkMatcher()); } }
function_block-full_function
[ { "content": "class SpecificErrnoMatcher : public ::testing::MatcherInterface<int> {\n\n public:\n\n explicit SpecificErrnoMatcher(int const expected) : expected_(expected) {}\n\n\n\n bool MatchAndExplain(\n\n int const actual_errno,\n\n ::testing::MatchResultListener* const listener) const override...
C++
src/modules/Bots/playerbot/RandomPlayerbotFactory.cpp
YggDrazil/-MaNGOsZero0.20
6bc64bf5c42cbd1e491c28a4d7a2bf91051323fb
#include "Config/Config.h" #include "../botpch.h" #include "playerbot.h" #include "PlayerbotAIConfig.h" #include "PlayerbotFactory.h" #include "AccountMgr.h" #include "ObjectMgr.h" #include "DatabaseEnv.h" #include "PlayerbotAI.h" #include "Player.h" #include "RandomPlayerbotFactory.h" #include "SystemConfig.h" map<uint8, vector<uint8> > RandomPlayerbotFactory::availableRaces; RandomPlayerbotFactory::RandomPlayerbotFactory(uint32 accountId) : accountId(accountId) { availableRaces[CLASS_WARRIOR].push_back(RACE_HUMAN); availableRaces[CLASS_WARRIOR].push_back(RACE_NIGHTELF); availableRaces[CLASS_WARRIOR].push_back(RACE_GNOME); availableRaces[CLASS_WARRIOR].push_back(RACE_DWARF); availableRaces[CLASS_WARRIOR].push_back(RACE_ORC); availableRaces[CLASS_WARRIOR].push_back(RACE_UNDEAD); availableRaces[CLASS_WARRIOR].push_back(RACE_TAUREN); availableRaces[CLASS_WARRIOR].push_back(RACE_TROLL); availableRaces[CLASS_PALADIN].push_back(RACE_HUMAN); availableRaces[CLASS_PALADIN].push_back(RACE_DWARF); availableRaces[CLASS_ROGUE].push_back(RACE_HUMAN); availableRaces[CLASS_ROGUE].push_back(RACE_DWARF); availableRaces[CLASS_ROGUE].push_back(RACE_NIGHTELF); availableRaces[CLASS_ROGUE].push_back(RACE_GNOME); availableRaces[CLASS_ROGUE].push_back(RACE_ORC); availableRaces[CLASS_ROGUE].push_back(RACE_TROLL); availableRaces[CLASS_PRIEST].push_back(RACE_HUMAN); availableRaces[CLASS_PRIEST].push_back(RACE_DWARF); availableRaces[CLASS_PRIEST].push_back(RACE_NIGHTELF); availableRaces[CLASS_PRIEST].push_back(RACE_TROLL); availableRaces[CLASS_PRIEST].push_back(RACE_UNDEAD); availableRaces[CLASS_MAGE].push_back(RACE_HUMAN); availableRaces[CLASS_MAGE].push_back(RACE_GNOME); availableRaces[CLASS_MAGE].push_back(RACE_UNDEAD); availableRaces[CLASS_MAGE].push_back(RACE_TROLL); availableRaces[CLASS_WARLOCK].push_back(RACE_HUMAN); availableRaces[CLASS_WARLOCK].push_back(RACE_GNOME); availableRaces[CLASS_WARLOCK].push_back(RACE_UNDEAD); availableRaces[CLASS_WARLOCK].push_back(RACE_ORC); availableRaces[CLASS_SHAMAN].push_back(RACE_ORC); availableRaces[CLASS_SHAMAN].push_back(RACE_TAUREN); availableRaces[CLASS_SHAMAN].push_back(RACE_TROLL); availableRaces[CLASS_HUNTER].push_back(RACE_DWARF); availableRaces[CLASS_HUNTER].push_back(RACE_NIGHTELF); availableRaces[CLASS_HUNTER].push_back(RACE_ORC); availableRaces[CLASS_HUNTER].push_back(RACE_TAUREN); availableRaces[CLASS_HUNTER].push_back(RACE_TROLL); availableRaces[CLASS_DRUID].push_back(RACE_NIGHTELF); availableRaces[CLASS_DRUID].push_back(RACE_TAUREN); } bool RandomPlayerbotFactory::CreateRandomBot(uint8 cls) { sLog.outDetail("Creating new random bot for class %d", cls); uint8 gender = rand() % 2 ? GENDER_MALE : GENDER_FEMALE; uint8 race = availableRaces[cls][urand(0, availableRaces[cls].size() - 1)]; string name = CreateRandomBotName(); if (name.empty()) return false; uint8 skin = urand(0, 7); uint8 face = urand(0, 7); uint8 hairStyle = urand(0, 7); uint8 hairColor = urand(0, 7); uint8 facialHair = urand(0, 7); uint8 outfitId = 0; WorldSession* session = new WorldSession(accountId, NULL, SEC_PLAYER, 0, LOCALE_enUS); if (!session) { sLog.outError("Couldn't create session for random bot account %d", accountId); delete session; return false; } Player *player = new Player(session); if (!player->Create(sObjectMgr.GeneratePlayerLowGuid(), name, race, cls, gender, skin, face, hairStyle, hairColor, facialHair, outfitId)) { player->DeleteFromDB(player->GetObjectGuid(), accountId, true, true); delete session; delete player; sLog.outError("Unable to create random bot for account %d - name: \"%s\"; race: %u; class: %u; gender: %u; skin: %u; face: %u; hairStyle: %u; hairColor: %u; facialHair: %u; outfitId: %u", accountId, name.c_str(), race, cls, gender, skin, face, hairStyle, hairColor, facialHair, outfitId); return false; } player->setCinematic(2); player->SetAtLoginFlag(AT_LOGIN_NONE); player->SaveToDB(); sLog.outDetail("Random bot created for account %d - name: \"%s\"; race: %u; class: %u; gender: %u; skin: %u; face: %u; hairStyle: %u; hairColor: %u; facialHair: %u; outfitId: %u", accountId, name.c_str(), race, cls, gender, skin, face, hairStyle, hairColor, facialHair, outfitId); return true; } string RandomPlayerbotFactory::CreateRandomBotName() { QueryResult *result = CharacterDatabase.Query("SELECT MAX(name_id) FROM ai_playerbot_names"); if (!result) return ""; Field *fields = result->Fetch(); uint32 maxId = fields[0].GetUInt32(); delete result; uint32 id = urand(0, maxId); result = CharacterDatabase.PQuery("SELECT n.name FROM ai_playerbot_names n " "LEFT OUTER JOIN characters e ON e.name = n.name " "WHERE e.guid IS NULL AND n.name_id >= '%u' LIMIT 1", id); if (!result) { sLog.outError("No more names left for random bots"); return ""; } Field *nfields = result->Fetch(); string name = nfields[0].GetCppString(); delete result; return name; }
#include "Config/Config.h" #include "../botpch.h" #include "playerbot.h" #include "PlayerbotAIConfig.h" #include "PlayerbotFactory.h" #include "AccountMgr.h" #include "ObjectMgr.h" #include "DatabaseEnv.h" #include "PlayerbotAI.h" #include "Player.h" #include "RandomPlayerbotFactory.h" #include "SystemConfig.h" map<uint8, vector<uint8> > RandomPlayerbotFactory::availableRaces; RandomPlayerbotFactory::RandomPlayerbotFactory(uint32 accountId) : accountId(accountId) { availableRaces[CLASS_WARRIOR].push_back(RACE_HUMAN); availableRaces[CLASS_WARRIOR].push_back(RACE_NIGHTELF); availableRaces[CLASS_WARRIOR].push_back(RACE_GNOME); availableRaces[CLASS_WARRIOR].push_back(RACE_DWARF); availableRaces[CLASS_WARRIOR].push_back(RACE_ORC); availableRaces[CLASS_WARRIOR].push_back(RACE_UNDEAD); availableRaces[CLASS_WARRIOR].push_back(RACE_TAUREN); availableRaces[CLASS_WARRIOR].push_back(RACE_TROLL); availableRaces[CLASS_PALADIN].push_back(RACE_HUMAN); availableRaces[CLASS_PALADIN].push_back(RACE_DWARF); availableRaces[CLASS_ROGUE].push_back(RACE_HUMAN); availableRaces[CLASS_ROGUE].push_back(RACE_DWARF); availableRaces[CLASS_ROGUE].push_back(RACE_NIGHTELF); availableRaces[CLASS_ROGUE].push_back(RACE_GNOME); availableRaces[CLASS_ROGUE].push_back(RACE_ORC); availableRaces[CLASS_ROGUE].push_back(RACE_TROLL); availableRaces[CLASS_PRIEST].push_back(RACE_HUMAN); availableRaces[CLASS_PRIEST].push_back(RACE_DWARF); availableRaces[CLASS_PRIEST].push_back(RACE_NIGHTELF); availableRaces[CLASS_PRIEST].push_back(RACE_TROLL); availableRaces[CLASS_PRIEST].push_back(RACE_UNDEAD); availableRaces[CLASS_MAGE].push_back(RACE_HUMAN); availableRaces[CLASS_MAGE].push_back(RACE_GNOME); availableRaces[CLASS_MAGE].push_back(RACE_UNDEAD); availableRaces[CLASS_MAGE].push_back(RACE_TROLL); availableRaces[CLASS_WARLOCK].push_back(RACE_HUMAN); availableRaces[CLASS_WARLOCK].push_back(RACE_GNOME); availableRaces[CLASS_WARLOCK].push_back(RACE_UNDEAD); availableRaces[CLASS_WARLOCK].push_back(RACE_ORC); availableRaces[CLASS_SHAMAN].push_back(RACE_ORC); availableRaces[CLASS_SHAMAN].push_back(RACE_TAUREN); availableRaces[CLASS_SHAMAN].push_back(RACE_TROLL); availableRaces[CLASS_HUNTER].push_back(RACE_DWARF); availableRaces[CLASS_HUNTER].push_back(RACE_NIGHTELF); availableRaces[CLASS_HUNTER].push_back(RACE_ORC); availableRaces[CLASS_HUNTER].push_back(RACE_TAUREN); availableRaces[CLASS_HUNTER].push_back(RACE_TROLL); availableRaces[CLASS_DRUID].push_back(RACE_NIGHTELF); availableRaces[CLASS_DRUID].push_back(RACE_TAUREN); } bool RandomPlayerbotFactory::CreateRandomBot(uint8 cls) { sLog.outDetail("Creating new random bot for class %d", cls); uint8 gender = rand() % 2 ? GENDER_MALE : GENDER_FEMALE; uint8 race = availableRaces[cls][urand(0, availableRaces[cls].size() - 1)]; string name = CreateRandomBotName(); if (name.empty()) return false; uint8 skin = urand(0, 7); uint8 face = urand(0, 7); uint8 hairStyle = urand(0, 7); uint8 hairColor = urand(0, 7); uint8 facialHair = urand(0, 7); uint8 outfitId = 0; WorldSession* session = new WorldSession(accountId, NULL, SEC_PLAYER, 0, LOCALE_enUS); if (!session) { sLog.outError("Couldn't create session for random bot account %d", accountId); delete session; return false; } Player *player = new Player(session);
player->setCinematic(2); player->SetAtLoginFlag(AT_LOGIN_NONE); player->SaveToDB(); sLog.outDetail("Random bot created for account %d - name: \"%s\"; race: %u; class: %u; gender: %u; skin: %u; face: %u; hairStyle: %u; hairColor: %u; facialHair: %u; outfitId: %u", accountId, name.c_str(), race, cls, gender, skin, face, hairStyle, hairColor, facialHair, outfitId); return true; } string RandomPlayerbotFactory::CreateRandomBotName() { QueryResult *result = CharacterDatabase.Query("SELECT MAX(name_id) FROM ai_playerbot_names"); if (!result) return ""; Field *fields = result->Fetch(); uint32 maxId = fields[0].GetUInt32(); delete result; uint32 id = urand(0, maxId); result = CharacterDatabase.PQuery("SELECT n.name FROM ai_playerbot_names n " "LEFT OUTER JOIN characters e ON e.name = n.name " "WHERE e.guid IS NULL AND n.name_id >= '%u' LIMIT 1", id); if (!result) { sLog.outError("No more names left for random bots"); return ""; } Field *nfields = result->Fetch(); string name = nfields[0].GetCppString(); delete result; return name; }
if (!player->Create(sObjectMgr.GeneratePlayerLowGuid(), name, race, cls, gender, skin, face, hairStyle, hairColor, facialHair, outfitId)) { player->DeleteFromDB(player->GetObjectGuid(), accountId, true, true); delete session; delete player; sLog.outError("Unable to create random bot for account %d - name: \"%s\"; race: %u; class: %u; gender: %u; skin: %u; face: %u; hairStyle: %u; hairColor: %u; facialHair: %u; outfitId: %u", accountId, name.c_str(), race, cls, gender, skin, face, hairStyle, hairColor, facialHair, outfitId); return false; }
if_condition
[ { "content": "class Player;\n", "file_path": "src/modules/Bots/playerbot/RandomPlayerbotMgr.h", "rank": 0, "score": 310367.1292837344 }, { "content": "class Player;\n", "file_path": "src/modules/Bots/playerbot/RandomPlayerbotFactory.h", "rank": 1, "score": 310367.1292837344 }, ...
C++
examples/FloodPedestrian_2019/Flood_XML_inpGen/XML_inpGen/xmlGen.cpp
SahebSh/FLAMEGPU
c81323b68532a52756b96dbf55fd29416e642cc9
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <algorithm> double bed_data(double x_int, double y_int); #define SIZE 128 #define xmin 0 #define xmax 15 #define ymin 0 #define ymax 15 #define OFF 0 #define ON 1 int main() { FILE *fp = fopen("flood_init.xml", "w"); if (fp == NULL) { printf("Error opening file!\n"); exit(1); } int inDomain = 1; double dt_ped = 0.0f; double dt_flood = 0.0f; int auto_dt_on = OFF; int body_effect_on = OFF; int evacuation_on = OFF; int sandbagging_on = OFF; int pedestrians_population = 1000; float hero_percentage = 0.5; double FLOOD_START_TIME = 200; double DISCHARGE_PEAK_TIME = 400; double FLOOD_END_TIME = 600; double evacuation_start_time = 400; double sandbagging_start_time = 400; double sandbagging_end_time = 4200; double pickup_duration = 30; double drop_duration = 30; double DISCHARGE_INITIAL = 0.0f; double DISCHARGE_PEAK = 1.3f; double DISCHARGE_END = 0.0f; int INFLOW_BOUNDARY = 3; int BOUNDARY_EAST_STATUS = 2; int BOUNDARY_WEST_STATUS = 2; int BOUNDARY_NORTH_STATUS = 1; int BOUNDARY_SOUTH_STATUS = 2; double x1_boundary = 110; double x2_boundary = 190; double y1_boundary = 40; double y2_boundary = 120; double init_depth_boundary = 0.1; float sandbag_length = 0.50f; float sandbag_height = 0.10f; float sandbag_width = 0.25f; float dike_length = 120.0f; float dike_height = 0.5f; float dike_width = 3.0f; int evacuation_exit_number = 6; int pickup_point = 5; int drop_point = 7; double lx, ly; double dx, dy; int i, j; auto z0_int = new double[SIZE + 1][SIZE + 1](); auto x_int = new double[SIZE + 1](); auto y_int = new double[SIZE + 1](); auto z0 = new double[SIZE][SIZE](); auto x = new double[SIZE](); auto y = new double[SIZE](); double qx_initial = 0.0; double qy_initial = 0.0; lx = xmax - xmin; ly = ymax - ymin; dx = (double)lx / (double)SIZE; dy = (double)ly / (double)SIZE; FILE *fp2 = fopen("init_topo.txt", "w"); if (fp2 == NULL){ printf("Error opening file!\n"); exit(1); } fprintf(fp, "<states>\n"); fprintf(fp, "<itno>0</itno>\n"); fprintf(fp, " <environment>\n\n"); fprintf(fp, " <xmin>%d</xmin>\n", xmin); fprintf(fp, " <xmax>%d</xmax>\n", xmax); fprintf(fp, " <ymin>%d</ymin>\n", ymin); fprintf(fp, " <ymax>%d</ymax>\n\n", ymax); fprintf(fp, " <dt_ped>%f</dt_ped>\n", dt_ped); fprintf(fp, " <dt_flood>%f</dt_flood>\n\n", dt_flood); fprintf(fp, " <auto_dt_on>%d</auto_dt_on>\n", auto_dt_on); fprintf(fp, " <body_effect_on>%d</body_effect_on>\n", body_effect_on); fprintf(fp, " <evacuation_on>%d</evacuation_on>\n", evacuation_on); fprintf(fp, " <sandbagging_on>%d</sandbagging_on>\n\n", sandbagging_on); fprintf(fp, " <pedestrians_population>%d</pedestrians_population>\n", pedestrians_population); fprintf(fp, " <hero_percentage>%f</hero_percentage>\n\n", hero_percentage); fprintf(fp, " <FLOOD_START_TIME>%f</FLOOD_START_TIME>\n", FLOOD_START_TIME); fprintf(fp, " <DISCHARGE_PEAK_TIME>%f</DISCHARGE_PEAK_TIME>\n", DISCHARGE_PEAK_TIME); fprintf(fp, " <FLOOD_END_TIME>%f</FLOOD_END_TIME>\n", FLOOD_END_TIME); fprintf(fp, " <evacuation_start_time>%f</evacuation_start_time>\n", evacuation_start_time); fprintf(fp, " <sandbagging_start_time>%f</sandbagging_start_time>\n", sandbagging_start_time); fprintf(fp, " <sandbagging_end_time>%f</sandbagging_end_time>\n", sandbagging_end_time); fprintf(fp, " <pickup_duration>%f</pickup_duration>\n", pickup_duration); fprintf(fp, " <drop_duration>%f</drop_duration>\n\n", drop_duration); fprintf(fp, " <DISCHARGE_INITIAL>%f</DISCHARGE_INITIAL>\n", DISCHARGE_INITIAL); fprintf(fp, " <DISCHARGE_PEAK>%f</DISCHARGE_PEAK>\n", DISCHARGE_PEAK); fprintf(fp, " <DISCHARGE_END>%f</DISCHARGE_END>\n\n", DISCHARGE_END); fprintf(fp, " <INFLOW_BOUNDARY>%d</INFLOW_BOUNDARY>\n", INFLOW_BOUNDARY); fprintf(fp, " <BOUNDARY_EAST_STATUS>%d</BOUNDARY_EAST_STATUS>\n", BOUNDARY_EAST_STATUS); fprintf(fp, " <BOUNDARY_WEST_STATUS>%d</BOUNDARY_WEST_STATUS>\n", BOUNDARY_WEST_STATUS); fprintf(fp, " <BOUNDARY_NORTH_STATUS>%d</BOUNDARY_NORTH_STATUS>\n", BOUNDARY_NORTH_STATUS); fprintf(fp, " <BOUNDARY_SOUTH_STATUS>%d</BOUNDARY_SOUTH_STATUS>\n\n", BOUNDARY_SOUTH_STATUS); fprintf(fp, " <x1_boundary>%f</x1_boundary>\n", x1_boundary); fprintf(fp, " <x2_boundary>%f</x2_boundary>\n", x2_boundary); fprintf(fp, " <y1_boundary>%f</y1_boundary>\n", y1_boundary); fprintf(fp, " <y2_boundary>%f</y2_boundary>\n\n", y2_boundary); fprintf(fp, " <init_depth_boundary>%f</init_depth_boundary>\n\n", init_depth_boundary); fprintf(fp, " <sandbag_length>%f</sandbag_length>\n", sandbag_length); fprintf(fp, " <sandbag_height>%f</sandbag_height>\n", sandbag_height); fprintf(fp, " <sandbag_width>%f</sandbag_width>\n", sandbag_width); fprintf(fp, " <dike_length>%f</dike_length>\n", dike_length); fprintf(fp, " <dike_height>%f</dike_height>\n", dike_height); fprintf(fp, " <dike_width>%f</dike_width>\n\n", dike_width); fprintf(fp, " <evacuation_exit_number>%d</evacuation_exit_number>\n\n", evacuation_exit_number); fprintf(fp, " <pickup_point>%d</pickup_point>\n", pickup_point); fprintf(fp, " <drop_point>%d</drop_point>\n\n", drop_point); fprintf(fp, " </environment>\n\n"); for (i = 0; i < SIZE + 1; i++){ for (j = 0; j < SIZE + 1; j++){ x_int[i] = xmin + i * dx; y_int[j] = ymin + j * dy; z0_int[i][j] = bed_data((double)x_int[i], (double)y_int[j]); } } for (i = 0; i < SIZE; i++) for (j = 0; j< SIZE; j++) { { x[i] = 0.5 * (x_int[i] + x_int[i + 1]); y[j] = 0.5 * (y_int[j] + y_int[j + 1]); z0[i][j] = (z0_int[i][j] + z0_int[i + 1][j] + z0_int[i][j + 1] + z0_int[i + 1][j + 1]) / 4; fprintf(fp2, "%d\t\t %d\t\t %f \n", i, j, z0[i][j]); fprintf(fp, " <xagent>\n"); fprintf(fp, "\t<name>FloodCell</name>\n"); fprintf(fp, "\t<inDomain>%d</inDomain>\n", inDomain); fprintf(fp, "\t<x>%d</x>\n", i); fprintf(fp, "\t<y>%d</y>\n", j); fprintf(fp, "\t<z0>%f</z0>\n", z0[i][j]); fprintf(fp, " </xagent>\n"); } } fprintf(fp, "</states>"); fclose(fp); return 0; } double bed_data(double x_int, double y_int) { double zz; double flume_length = 1; double x1 = (xmax - flume_length) / 2 ; double x2 = (xmax + flume_length) / 2 ; if ((x_int <= x1) || (x_int >= x2)) zz = 10; else zz = 0; return zz; }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <algorithm> double bed_data(double x_int, double y_int); #define SIZE 128 #define xmin 0 #define xmax 15 #define ymin 0 #define ymax 15 #define OFF 0 #define ON 1 int main() { FILE *fp = fopen("flood_init.xml", "w"); if (fp == NULL) { printf("Error opening file!\n"); exit(1); } int inDomain = 1; double dt_ped = 0.0f; double dt_flood = 0.0f; int auto_dt_on = OFF; int body_effect_on = OFF; int evacuation_on = OFF; int sandbagging_on = OFF; int pedestrians_population = 1000; float hero_percentage = 0.5; double FLOOD_START_TIME = 200; double DISCHARGE_PEAK_TIME = 400; double FLOOD_END_TIME = 600; double evacuation_start_time = 400; double sandbagging_start_time = 400; double sandbagging_end_time = 4200; double pickup_duration = 30; double drop_duration = 30; double DISCHARGE_INITIAL = 0.0f; double DISCHARGE_PEAK = 1.3f; double DISCHARGE_END = 0.0f; int INFLOW_BOUNDARY = 3; int BOUNDARY_EAST_STATUS = 2; int BOUNDARY_WEST_STATUS = 2; int BOUNDARY_NORTH_STATUS = 1; int BOUNDARY_SOUTH_STATUS = 2; double x1_boundary = 110; double x2_boundary = 190; double y1_boundary = 40; double y2_boundary = 120; double init_depth_boundary = 0.1; float sandbag_length = 0.50f; float sandbag_height = 0.10f; float sandbag_width = 0.25f; float dike_length = 120.0f; float dike_height = 0.5f; float dike_width = 3.0f; int evacuation_exit_number = 6; int pickup_point = 5; int drop_point = 7; double lx, ly; double dx, dy; int i, j; auto z0_int = new double[SIZE + 1][SIZE + 1](); auto x_int = new double[SIZE + 1](); auto y_int = new double[SIZE + 1](); auto z0 = new double[SIZE][SIZE](); auto x = new double[SIZE](); auto y = new double[SIZE](); double qx_initial = 0.0; double qy_initial = 0.0; lx = xmax - xmin; ly = ymax - ymin; dx = (double)lx / (double)SIZE; dy = (double)ly / (double)SIZE; FILE *fp2 = fopen("init_topo.txt", "w"); if (fp2 == NULL){ printf("Error opening file!\n"); exit(1); } fprintf(fp, "<states>\n"); fprintf(fp, "<itno>0</itno>\n"); fprintf(fp, " <environment>\n\n"); fprintf(fp, " <xmin>%d</xmin>\n", xmin); fprintf(fp, " <xmax>%d</xmax>\n", xmax); fprintf(fp, " <ymin>%d</ymin>\n", ymin); fprintf(fp, " <ymax>%d</ymax>\n\n", ymax); fprintf(fp, " <dt_ped>%f</dt_ped>\n", dt_ped); fprintf(fp, " <dt_flood>%f</dt_flood>\n\n", dt_flood); fprintf(fp, " <auto_dt_on>%d</auto_dt_on>\n", auto_dt_on); fprintf(fp, " <body_effect_on>%d</body_effect_on>\n", body_effect_on); fprintf(fp, " <evacuation_on>%d</evacuation_on>\n", evacuation_on); fprintf(fp, " <sandbagging_on>%d</sandbagging_on>\n\n", sandbagging_on); fprintf(fp, " <pedestrians_population>%d</pedestrians_population>\n", pedestrians_population); fprintf(fp, " <hero_percentage>%f</hero_percentage>\n\n", hero_percentage); fprintf(fp, " <FLOOD_START_TIME>%f</FLOOD_START_TIME>\n", FLOOD_START_TIME); fprintf(fp, " <DISCHARGE_PEAK_TIME>%f</DISCHARGE_PEAK_TIME>\n", DISCHARGE_PEAK_TIME); fprintf(fp, " <FLOOD_END_TIME>%f</FLOOD_END_TIME>\n", FLOOD_END_TIME); fprintf(fp, " <evacuation_start_time>%f</evacuation_start_time>\n", evacuation_start_time); fprintf(fp, " <sandbagging_start_time>%f</sandbagging_start_time>\n", sandbagging_start_time); fprintf(fp, " <sandbagging_end_time>%f</sandbagging_end_time>\n", sandbagging_end_time); fprintf(fp, " <pickup_duration>%f</pickup_duration>\n", pickup_duration); fprintf(fp, " <drop_duration>%f</drop_duration>\n\n", drop_duration); fprintf(fp, " <DISCHARGE_INITIAL>%f</DISCHARGE_INITIAL>\n", DISCHARGE_INITIAL); fprintf(fp, " <DISCHARGE_PEAK>%f</DISCHARGE_PEAK>\n", DISCHARGE_PEAK); fprintf(fp, " <DISCHARGE_END>%f</DISCHARGE_END>\n\n", DISCHARGE_END); fprintf(fp, " <INFLOW_BOUNDARY>%d</INFLOW_BOUNDARY>\n", INFLOW_BOUNDARY); fprintf(fp, " <BOUNDARY_EAST_STATUS>%d</BOUNDARY_EAST_STATUS>\n", BOUNDARY_EAST_STATUS); fprintf(fp, " <BOUNDARY_WEST_STATUS>%d</BOUNDARY_WEST_STATUS>\n", BOUNDARY_WEST_STATUS); fprintf(fp, " <BOUNDARY_NORTH_STATUS>%d</BOUNDARY_NORTH_STATUS>\n", BOUNDARY_NORTH_STATUS); fprintf(fp, " <BOUNDARY_SOUTH_STATUS>%d</BOUNDARY_SOUTH_STATUS>\n\n", BOUNDARY_SOUTH_STATUS); fprintf(fp, " <x1_boundary>%f</x1_boundary>\n", x1_boundary); fprintf(fp, " <x2_boundary>%f</x2_boundary>\n", x2_boundary); fprintf(fp, " <y1_boundary>%f</y1_boundary>\n", y1_boundary); fprintf(fp, " <y2_boundary>%f</y2_boundary>\n\n", y2_boundary); fprintf(fp, " <init_depth_boundary>%f</init_depth_boundary>\n\n", init_depth_boundary); fprintf(fp, " <sandbag_length>%f</sandbag_length>\n", sandbag_length); fprintf(fp, " <sandbag_height>%f</sandbag_height>\n", sandbag_height); fprintf(fp, " <sandbag_width>%f</sandbag_width>\n", sandbag_width); fprintf(fp, " <dike_length>%f</dike_length>\n", dike_length); fprintf(fp, " <dike_height>%f</dike_height>\n", dike_height); fprintf(fp, " <dike_width>%f</dike_width>\n\n", dike_width); fprintf(fp, " <evacuation_exit_number>%d</evacuation_exit_number>\n\n", evacuation_exit_number); fprintf(fp, " <pickup_point>%d</pickup_point>\n", pickup_point); fprintf(fp, " <drop_point>%d</drop_point>\n\n", drop_point); fprintf(fp, " </environment>\n\n"); for (i = 0; i < SIZE + 1; i++){ for (j = 0; j < SIZE + 1; j++){ x_int[i] = xmin + i * dx; y_int[j] = ymin + j * dy; z0_int[i][j] = bed_data((double)x_int[i], (double)y_int[j]); } } for (i = 0; i < SIZE; i++) for (j = 0; j< SIZE; j++) { { x[i] = 0.5 * (x_int[i] + x_int[i + 1]); y[j] = 0.5 * (y_int[j] + y_int[j + 1]); z0[i][j] = (z0_int[i][j] + z0_int[i + 1][j] + z0_int[i][j + 1] + z0_int[i + 1][j + 1]) / 4; fprintf(fp2, "%d\t\t %d\t\t %f \n", i, j, z0[i][j]); fprintf(fp, " <xagent>\n"); fprintf(fp, "\t<name>FloodCell</name>\n"); fprintf(fp, "\t<inDomain>%d</inDomain>\n", inDomain); fprintf(fp, "\t<x>%d</x>\n", i); fprintf(fp, "\t<y>%d</y>\n", j); fprintf(fp, "\t<z0>%f</z0>\n", z0[i][j]); fprintf(fp, " </xagent>\n"); } } fprintf(fp, "</states>"); fclose(fp); return 0; } double bed_data(double x_int, double y_int) { double zz; double flume_length =
1; double x1 = (xmax - flume_length) / 2 ; double x2 = (xmax + flume_length) / 2 ; if ((x_int <= x1) || (x_int >= x2)) zz = 10; else zz = 0; return zz; }
function_block-function_prefixed
[ { "content": "class Double {\n\npublic:\n\n Double() {}\n\n Double(double d) : d_(d) {}\n\n Double(uint64_t u) : u_(u) {}\n\n\n\n double Value() const { return d_; }\n\n uint64_t Uint64Value() const { return u_; }\n\n\n\n double NextPositiveDouble() const {\n\n RAPIDJSON_ASSERT(!Sign())...
C++
LuaKitProject/src/Projects/jni/com_common_luakit_LuaHelper.cpp
williamwen1986/Luakit
2e113a3b429a8205cf8ac0dbc074480906b34384
#include <com_common_luakit_LuaHelper.h> #include "base/logging.h" #include "base/command_line.h" #include "base/memory/scoped_ptr.h" #include "common/business_main_delegate.h" #include "common/business_runtime.h" #include "base/android/base_jni_registrar.h" #include "base/android/jni_android.h" #include "JniEnvWrapper.h" #include "base/thread_task_runner_handle.h" #include "common/base_lambda_support.h" #include "tools/lua_helpers.h" #include "JniLuaConvertor.h" #ifdef __cplusplus extern "C" { #endif #include "lua.h" #include "lauxlib.h" JNIEXPORT void JNICALL Java_com_common_luakit_LuaHelper_startLuaKitNative (JNIEnv *env, jclass c, jobject context) { static bool hasStartLuakit = false; if (!hasStartLuakit) { base::android::InitApplicationContext(env, base::android::ScopedJavaLocalRef<jobject>(env, context)); LOG(ERROR) << "nativeNewObject support ... "; setXXTEAKeyAndSign("2dxLua", strlen("2dxLua"), "XXTEA", strlen("XXTEA")); BusinessMainDelegate* delegate(new BusinessMainDelegate()); BusinessRuntime* Business_runtime(BusinessRuntime::Create()); Business_runtime->Initialize(delegate); Business_runtime->Run(); } else { assert(0); } } void pushLuaModule(std::string moduleName) { lua_State * L = BusinessThread::GetCurrentThreadLuaState(); BEGIN_STACK_MODIFY(L) std::string lua = "TEM_OC_OBJECT = require('"+ moduleName +"')"; doString(L, lua.c_str()); lua_getglobal(L, "TEM_OC_OBJECT"); lua_pushnil(L); lua_setglobal(L, "TEM_OC_OBJECT"); END_STACK_MODIFY(L, 1) } JNIEXPORT jobject JNICALL Java_com_common_luakit_LuaHelper_callLuaFunction__Ljava_lang_String_2Ljava_lang_String_2 (JNIEnv *env, jclass, jstring moduleName, jstring methodName) { const char* module = env->GetStringUTFChars((jstring)moduleName, NULL); const char* method = env->GetStringUTFChars((jstring)methodName, NULL); lua_State * L = BusinessThread::GetCurrentThreadLuaState(); BEGIN_STACK_MODIFY(L) pushLuaModule(module); lua_pushstring(L, method); lua_rawget(L, -2); jobject ret = NULL; if (lua_isfunction(L, -1)) { int err = lua_pcall(L, 0, 1, 0); if (err != 0) { luaError(L,"callLuaFunction call error"); } else { ret = object_copyToJava(L, env,-1); } } else { luaError(L,"callLuaFunction call error no such function"); } END_STACK_MODIFY(L, 0) env->ReleaseStringUTFChars((jstring)moduleName, module); env->ReleaseStringUTFChars((jstring)methodName, method); return ret; } JNIEXPORT jobject JNICALL Java_com_common_luakit_LuaHelper_callLuaFunction__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_Object_2 (JNIEnv *env, jclass, jstring moduleName, jstring methodName,jobject p1) { const char* module = env->GetStringUTFChars((jstring)moduleName, NULL); const char* method = env->GetStringUTFChars((jstring)methodName, NULL); lua_State * L = BusinessThread::GetCurrentThreadLuaState(); BEGIN_STACK_MODIFY(L) pushLuaModule(module); lua_pushstring(L, method); lua_rawget(L, -2); jobject ret = NULL; if (lua_isfunction(L, -1)) { object_fromjava(L, env ,p1); int err = lua_pcall(L, 1, 1, 0); if (err != 0) { luaError(L,"callLuaFunction call error"); } else { ret = object_copyToJava(L, env,-1); } } else { luaError(L,"callLuaFunction call error no such function"); } END_STACK_MODIFY(L, 0) env->ReleaseStringUTFChars((jstring)moduleName, module); env->ReleaseStringUTFChars((jstring)methodName, method); return ret; } JNIEXPORT jobject JNICALL Java_com_common_luakit_LuaHelper_callLuaFunction__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_Object_2Ljava_lang_Object_2 (JNIEnv *env, jclass, jstring moduleName, jstring methodName,jobject p1, jobject p2) { const char* module = env->GetStringUTFChars((jstring)moduleName, NULL); const char* method = env->GetStringUTFChars((jstring)methodName, NULL); lua_State * L = BusinessThread::GetCurrentThreadLuaState(); BEGIN_STACK_MODIFY(L) pushLuaModule(module); lua_pushstring(L, method); lua_rawget(L, -2); jobject ret = NULL; if (lua_isfunction(L, -1)) { object_fromjava(L, env ,p1); object_fromjava(L, env ,p2); int err = lua_pcall(L, 2, 1, 0); if (err != 0) { luaError(L,"callLuaFunction call error"); } else { ret = object_copyToJava(L, env,-1); } } else { luaError(L,"callLuaFunction call error no such function"); } END_STACK_MODIFY(L, 0) env->ReleaseStringUTFChars((jstring)moduleName, module); env->ReleaseStringUTFChars((jstring)methodName, method); return ret; } JNIEXPORT jobject JNICALL Java_com_common_luakit_LuaHelper_callLuaFunction__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_Object_2 (JNIEnv *env, jclass, jstring moduleName, jstring methodName, jobject p1, jobject p2, jobject p3) { const char* module = env->GetStringUTFChars((jstring)moduleName, NULL); const char* method = env->GetStringUTFChars((jstring)methodName, NULL); lua_State * L = BusinessThread::GetCurrentThreadLuaState(); BEGIN_STACK_MODIFY(L) pushLuaModule(module); lua_pushstring(L, method); lua_rawget(L, -2); jobject ret = NULL; if (lua_isfunction(L, -1)) { object_fromjava(L, env ,p1); object_fromjava(L, env ,p2); object_fromjava(L, env ,p3); int err = lua_pcall(L, 3, 1, 0); if (err != 0) { luaError(L,"callLuaFunction call error"); } else { ret = object_copyToJava(L, env,-1); } } else { luaError(L,"callLuaFunction call error no such function"); } END_STACK_MODIFY(L, 0) env->ReleaseStringUTFChars((jstring)moduleName, module); env->ReleaseStringUTFChars((jstring)methodName, method); return ret; } JNIEXPORT jobject JNICALL Java_com_common_luakit_LuaHelper_callLuaFunction__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_Object_2 (JNIEnv *env, jclass, jstring moduleName, jstring methodName, jobject p1,jobject p2,jobject p3,jobject p4) { const char* module = env->GetStringUTFChars((jstring)moduleName, NULL); const char* method = env->GetStringUTFChars((jstring)methodName, NULL); lua_State * L = BusinessThread::GetCurrentThreadLuaState(); BEGIN_STACK_MODIFY(L) pushLuaModule(module); lua_pushstring(L, method); lua_rawget(L, -2); jobject ret = NULL; if (lua_isfunction(L, -1)) { object_fromjava(L, env ,p1); object_fromjava(L, env ,p2); object_fromjava(L, env ,p3); object_fromjava(L, env ,p4); int err = lua_pcall(L, 4, 1, 0); if (err != 0) { luaError(L,"callLuaFunction call error"); } else { ret = object_copyToJava(L, env,-1); } } else { luaError(L,"callLuaFunction call error no such function"); } END_STACK_MODIFY(L, 0) env->ReleaseStringUTFChars((jstring)moduleName, module); env->ReleaseStringUTFChars((jstring)methodName, method); return ret; } JNIEXPORT jobject JNICALL Java_com_common_luakit_LuaHelper_callLuaFunction__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_Object_2 (JNIEnv *env, jclass, jstring moduleName, jstring methodName,jobject p1,jobject p2,jobject p3,jobject p4,jobject p5) { const char* module = env->GetStringUTFChars((jstring)moduleName, NULL); const char* method = env->GetStringUTFChars((jstring)methodName, NULL); lua_State * L = BusinessThread::GetCurrentThreadLuaState(); BEGIN_STACK_MODIFY(L) pushLuaModule(module); lua_pushstring(L, method); lua_rawget(L, -2); jobject ret = NULL; if (lua_isfunction(L, -1)) { object_fromjava(L, env ,p1); object_fromjava(L, env ,p2); object_fromjava(L, env ,p3); object_fromjava(L, env ,p4); object_fromjava(L, env ,p5); int err = lua_pcall(L, 5, 1, 0); if (err != 0) { luaError(L,"callLuaFunction call error"); } else { ret = object_copyToJava(L, env,-1); } } else { luaError(L,"callLuaFunction call error no such function"); } END_STACK_MODIFY(L, 0) env->ReleaseStringUTFChars((jstring)moduleName, module); env->ReleaseStringUTFChars((jstring)methodName, method); return ret; } jint JNI_OnLoad(JavaVM* jvm, void* reserved) { JniEnvWrapper env(jvm); JNIEnv * envp = env; LOG(INFO) << "JNI_Onload start"; base::android::InitVM(jvm); if (!base::android::RegisterJni(env)) { LOG(ERROR)<<"base::android::RegisterJni(env) error"; return -1; } CommandLine::Init(0, nullptr); LOG(INFO) << "JNI_Onload end"; return JNI_VERSION_1_6; } #ifdef __cplusplus } #endif
#include <com_common_luakit_LuaHelper.h> #include "base/logging.h" #include "base/command_line.h" #include "base/memory/scoped_ptr.h" #include "common/business_main_delegate.h" #include "common/business_runtime.h" #include "base/android/base_jni_registrar.h" #include "base/android/jni_android.h" #include "JniEnvWrapper.h" #include "base/thread_task_runner_handle.h" #include "common/base_lambda_support.h" #include "tools/lua_helpers.h" #include "JniLuaConvertor.h" #ifdef __cplusplus extern "C" { #endif #include "lua.h" #include "lauxlib.h" JNIEXPORT void JNICALL Java_com_common_luakit_LuaHelper_startLuaKitNative (JNIEnv *env, jclass c, jobject context) { static bool hasStartLuakit = false; if (!hasStartLuakit) { base::android::InitApplicationContext(env, base::android::ScopedJavaLocalRef<jobject>(env, context)); LOG(ERROR) << "nativeNewObject support ... "; setXXTEAKeyAndSign("2dxLua", strlen("2dxLua"), "XXTEA", strlen("XXTEA")); BusinessMainDelegate* delegate(new BusinessMainDelegate()); BusinessRuntime* Business_runtime(BusinessRuntime::Create()); Business_runtime->Initialize(delegate); Business_runtime->Run(); } else { assert(0); } } void pushLuaModule(std::string moduleName) { lua_State * L = BusinessThread::GetCurrentThreadLuaState(); BEGIN_STACK_MODIFY(L) std::string lua = "TEM_OC_OBJECT = require('"+ moduleName +"')"; doString(L, lua.c_str()); lua_getglobal(L, "TEM_OC_OBJECT"); lua_pushnil(L); lua_setglobal(L, "TEM_OC_OBJECT"); END_STACK_MODIFY(L, 1) } JNIEXPORT jobject JNICALL Java_com_common_luakit_LuaHelper_callLuaFunction__Ljava_lang_String_2Ljava_lang_String_2 (JNIEnv *env, jclass, jstring moduleName, jstring methodName) { const char* module = env->GetStringUTFChars((jstring)moduleName, NULL); const char* method = env->GetStringUTFChars((jstring)methodName, NULL); lua_State * L = BusinessThread::GetCurrentThreadLuaState(); BEGIN_STACK_MODIFY(L) pushLuaModule(module); lua_pushstring(L, method); lua_rawget(L, -2); jobject ret = NULL; if (lua_isfunction(L, -1)) { int err = lua_pcall(L, 0, 1, 0); if (err != 0) { luaError(L,"callLuaFunction call error"); } else { ret = object_copyToJava(L, env,-1); } } else { luaError(L,"callLuaFunction call error no such function"); } END_STACK_MODIFY(L, 0) env->ReleaseStringUTFChars((jstring)moduleName, module); env->ReleaseStringUTFChars((jstring)methodName, method); return ret; } JNIEXPORT jobject JNICALL Java_com_common_luakit_LuaHelper_callLuaFunction__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_Object_2 (JNIEnv *env, jclass, jstring moduleName, jstring methodName,jobject p1) { const char* module = env->GetStringUTFChars((jstring)moduleName, NULL); const char* method = env->GetStringUTFChars((jstring)methodName, NULL); lua_State * L = BusinessThread::GetCurrentThreadLuaState(); BEGIN_STACK_MODIFY(L) pushLuaModule(module); lua_pushstring(L, method); lua_rawget(L, -2); jobject ret = NULL; if (lua_isfunction(L, -1)) { object_fromjava(L, env ,p1); int err = lua_pcall(L, 1, 1, 0); if (err != 0) { luaError(L,"callLuaFunction call error"); } else { ret = object_copyToJava(L, env,-1); } } else { luaError(L,"callLuaFunction call error no such function"); } END_STACK_MODIFY(L, 0) env->ReleaseStringUTFChars((jstring)moduleName, module); env->ReleaseStringUTFChars((jstring)methodName, method); return ret; } JNIEXPORT jobject JNICALL Java_com_common_luakit_LuaHelper_callLuaFunction__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_Object_2Ljava_lang_Object_2 (JNIEnv *env, jclass, jstring moduleName, jstring methodName,jobject p1, jobject p2) { const char* module = env->GetStringUTFChars((jstring)moduleName, NULL); const char* method = env->GetStringUTFChars((jstring)methodName, NULL); lua_State * L = BusinessThread::GetCurrentThreadLuaState(); BEGIN_STACK_MODIFY(L) pushLuaModule(module); lua_pushstring(L, method); lua_rawget(L, -2); jobject ret = NULL; if (lua_isfunction(L, -1)) { object_fromjava(L, env ,p1); object_fromjava(L, env ,p2); int err = lua_pcall(L, 2, 1, 0); if (err != 0) { luaError(L,"callLuaFunction call error"); } else { ret = object_copyToJava(L, env,-1); } } else { luaError(L,"callLuaFunction call error no such function"); } END_STACK_MODIFY(L, 0) env->ReleaseStringUTFChars((jstring)moduleName, module); env->ReleaseStringUTFChars((jstring)methodName, method); return ret; } JNIEXPORT jobject JNICALL Java_com_common_luakit_LuaHelper_callLuaFunction__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_Object_2 (JNIEnv *env, jclass, jstring moduleName, jstring methodName, jobject p1, jobject p2, jobject p3) { const char* module = env->GetStringUTFChars((jstring)moduleName, NULL); const char* method = env->GetStringUTFChars((jstring)methodName, NULL); lua_State * L = BusinessThread::GetCurrentThreadLuaState(); BEGIN_STACK_MODIFY(L) pushLuaModule(module); lua_pushstring(L, method); lua_rawget(L, -2); jobject ret = NULL; if (lua_isfunction(L, -1)) { object_fromjava(L, env ,p1); object_fromjava(L, env ,p2); object_fromjava(L, env ,p3); int err = lua_pcall(L, 3, 1, 0); if (err != 0) { luaError(L,"callLuaFunction call error"); } else { ret = object_copyToJava(L, env,-1); } } else { luaError(L,"callLuaFunction call error no such function"); } END_STACK_MODIFY(L, 0) env->ReleaseStringUTFChars((jstring)moduleName, module); env->ReleaseStringUTFChars((jstring)methodName, method); return ret; } JNIEXPORT jobject JNICALL Java_com_common_luakit_LuaHelper_callLuaFunction__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_Object_2 (JNIEnv *env, jclass, jstring moduleName, jstring methodName, jobject p1,jobject p2,jobject p3,jobject p4) { const char* module = env->GetStringUTFChars((jstring)moduleName, NULL); const char* method = env->GetStringUTFChars((jstring)methodName, NULL); lua_State * L = BusinessThread::GetCurrentThreadLuaState(); BEGIN_STACK_MODIFY(L) pushLuaModule(module); lua_pushstring(L, method); lua_rawget(L, -2); jobject ret = NULL; if (lua_isfunction(L, -1)) { object_fromjava(L, env ,p1); object_fromjava(L, env ,p2); object_fromjava(L, env ,p3); object_fromjava(L, env ,p4); int err = lua_pcall(L, 4, 1, 0); if (err != 0) { luaError(L,"callLuaFunction call error"); } else { ret = object_copyToJava(L, env,-1); } } else { luaError(L,"callLuaFunction call error no such function"); } END_STACK_MODIFY(L, 0) env->ReleaseStringUTFChars((jstring)moduleName, module); env->ReleaseStringUTFChars((jstring)methodName, method); return ret; } JNIEXPORT jobject JNICALL Java_com_common_luakit_LuaHelper_callLuaFunction__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_Object_2 (JNIEnv *env, jclass, jstring moduleName, jstring methodName,jobject p1,jobject p2,jobject p3,jobject p4,jobject p5) { const char* module = env->GetStringUTFChars((jstring)moduleName, NULL); const char* method = env->GetStringUTFChars((jstring)methodName, NULL); lua_State * L = BusinessThread::GetCurrentThreadLuaState(); BEGIN_STACK_MODIFY(L) pushLuaModule(module); lua_pushstring(L, method); lua_rawget(L, -2); jobject ret = NULL; if (lua_isfunction(L, -1)) { object_fromjava(L, env ,p1); object_fromjava(L, env ,p2); object_fromjava(L, env ,p3); object_fromjava(L, env ,p4); object_fromjava(L, env ,p5); int err = lua_pcall(L, 5, 1, 0); if (err != 0) { luaError(L,"callLuaFunction call error"); } else { ret = object_copyToJava(L, env,-1); } } else { luaError(L,"callLuaFunction call error no such function"); } END_STACK_MODIFY(L, 0) env->ReleaseStringUTFChars((jstring)moduleName, module); env->ReleaseStringUTFChars((jstring)methodName, method); return ret; } jint JNI_OnLoad(JavaVM* jvm, void* reserved) { JniEnvWrapper env(jvm); JNIEnv * envp = env; LOG(INFO) << "J
#ifdef __cplusplus } #endif
NI_Onload start"; base::android::InitVM(jvm); if (!base::android::RegisterJni(env)) { LOG(ERROR)<<"base::android::RegisterJni(env) error"; return -1; } CommandLine::Init(0, nullptr); LOG(INFO) << "JNI_Onload end"; return JNI_VERSION_1_6; }
function_block-function_prefixed
[ { "content": "struct BindState<Runnable, RunType, void(P1, P2, P3, P4, P5,\n\n P6)> : public BindStateBase {\n\n typedef Runnable RunnableType;\n\n typedef IsWeakMethod<HasIsMethodTag<Runnable>::value, P1> IsWeakCall;\n\n typedef Invoker<6, BindState, RunType> InvokerType;\n\n typedef typename InvokerTyp...
C++
xls/noc/config_ng/flattened_multi_dimensional_array_test.cc
felixzhuologist/xls
b6a4ec7190049002be1c0829d52b1d7767c88204
#include "xls/noc/config_ng/flattened_multi_dimensional_array.h" #include "gtest/gtest.h" namespace xls::noc { namespace { TEST(FlattenedMultiDimensionalArrayTest, GetElementCount) { FlattenedMultiDimensionalArray<int64_t> array({3, 4}); EXPECT_EQ(array.GetElementCount(), 12); FlattenedMultiDimensionalArray<int64_t> zero_array({}); EXPECT_EQ(zero_array.GetElementCount(), 1); } TEST(FlattenedMultiDimensionalArrayTest, iterators) { FlattenedMultiDimensionalArray<int64_t> array({3, 4}); int64_t count = 0; for (int64_t element : array) { element++; count++; } EXPECT_EQ(array.GetElementCount(), count); FlattenedMultiDimensionalArray<int64_t> zero_array({}); count = 0; for (int64_t element : zero_array) { element++; count++; } EXPECT_EQ(zero_array.GetElementCount(), count); } TEST(FlattenedMultiDimensionalArrayTest, GetDimensions) { FlattenedMultiDimensionalArray<int64_t> array({3, 4}); const DimensionBounds& dimensions = array.GetDimensions(); EXPECT_EQ(dimensions.GetDimensionCount(), 2); EXPECT_EQ(dimensions.GetDimensionBound(0), 3); EXPECT_EQ(dimensions.GetDimensionBound(1), 4); FlattenedMultiDimensionalArray<int64_t> zero_array({}); const DimensionBounds& zero_dimensions = zero_array.GetDimensions(); EXPECT_EQ(zero_dimensions.GetDimensionCount(), 0); } TEST(FlattenedMultiDimensionalArrayTest, SetValueCoordinate) { FlattenedMultiDimensionalArray<int64_t> array({2, 2}); for (int64_t dimension_1 = 0; dimension_1 < 2; dimension_1++) { for (int64_t dimension_0 = 0; dimension_0 < 2; dimension_0++) { array.SetValue({dimension_0, dimension_1}, 42); } } FlattenedMultiDimensionalArray<int64_t> zero_array({}); zero_array.SetValue({}, 42); } TEST(FlattenedMultiDimensionalArrayTest, SetValueIndex) { FlattenedMultiDimensionalArray<int64_t> array({2, 2}); for (int64_t count = 0; count < 4; count++) { array.SetValue(count, 42); } FlattenedMultiDimensionalArray<int64_t> zero_array({}); zero_array.SetValue(0, 42); } TEST(FlattenedMultiDimensionalArrayTest, GetValueCoordinate) { FlattenedMultiDimensionalArray<int64_t> array({2, 2}); int value = 0; for (int64_t dimension_1 = 0; dimension_1 < 2; dimension_1++) { for (int64_t dimension_0 = 0; dimension_0 < 2; dimension_0++) { array.SetValue({dimension_0, dimension_1}, value++); } } value = 0; for (int64_t dimension_1 = 0; dimension_1 < 2; dimension_1++) { for (int64_t dimension_0 = 0; dimension_0 < 2; dimension_0++) { int64_t result = array.GetValue({dimension_0, dimension_1}); EXPECT_EQ(result, value++); } } FlattenedMultiDimensionalArray<int64_t> zero_array({}); zero_array.SetValue({}, 42); int64_t result = zero_array.GetValue({}); EXPECT_EQ(result, 42); } TEST(FlattenedMultiDimensionalArrayTest, GetValueIndex) { FlattenedMultiDimensionalArray<int64_t> array({2, 2}); int value = 0; for (int64_t count = 0; count < 4; count++) { array.SetValue(count, value++); } value = 0; for (int64_t count = 0; count < 4; count++) { int64_t result = array.GetValue(count); EXPECT_EQ(result, value++); } FlattenedMultiDimensionalArray<int64_t> zero_array({}); zero_array.SetValue(0, 42); int64_t result = zero_array.GetValue(0); EXPECT_EQ(result, 42); } TEST(FlattenedMultiDimensionalArrayTest, GetCoordinateOfIndex) { FlattenedMultiDimensionalArray<int64_t> array({2, 3}); int64_t index = 0; for (int64_t i = 0; i < 3; i++) { for (int64_t j = 0; j < 2; j++) { Coordinate coordinate = array.GetCoordinateOfIndex(index).value(); EXPECT_EQ(coordinate.GetDimensionCount(), 2); EXPECT_EQ(coordinate.GetCoordinate(0), j); EXPECT_EQ(coordinate.GetCoordinate(1), i); index++; } } EXPECT_EQ(array.GetCoordinateOfIndex(index), absl::nullopt); FlattenedMultiDimensionalArray<int64_t> zero_array({}); Coordinate coordinate = zero_array.GetCoordinateOfIndex(0).value(); EXPECT_EQ(coordinate.GetDimensionCount(), 0); EXPECT_EQ(zero_array.GetCoordinateOfIndex(1), absl::nullopt); } TEST(FlattenedMultiDimensionalArrayIteratorTest, IsAtBoundsCheck) { using array_t = FlattenedMultiDimensionalArray<int64_t>; array_t array({2, 3}); array_t::DimensionalSpaceIterator iterator = array.GetDimensionalSpaceIterator({0, 1}); EXPECT_FALSE(iterator.IsAtBounds()); int64_t count = 0; while (!iterator.IsAtBounds()) { ++iterator; count++; } EXPECT_EQ(count, 6); array_t zero_array({}); array_t::DimensionalSpaceIterator zero_iterator = zero_array.GetDimensionalSpaceIterator({}); EXPECT_FALSE(zero_iterator.IsAtBounds()); count = 0; while (!zero_iterator.IsAtBounds()) { ++zero_iterator; count++; } EXPECT_EQ(count, 1); } TEST(FlattenedMultiDimensionalArrayIteratorTest, DistanceFromEnd) { using array_t = FlattenedMultiDimensionalArray<int64_t>; array_t array({2, 3}); array_t::DimensionalSpaceIterator iterator = array.GetDimensionalSpaceIterator({0, 1}); for (int64_t i = 0; i < 3; i++) { for (int64_t j = 0; j < 2; j++) { EXPECT_EQ(iterator.DistanceFromEnd(0), 2 - j); EXPECT_EQ(iterator.DistanceFromEnd(1), 3 - i); ++iterator; } } EXPECT_EQ(iterator.DistanceFromEnd(0), 0); EXPECT_EQ(iterator.DistanceFromEnd(1), 0); array_t zero_array({}); array_t::DimensionalSpaceIterator zero_iterator = zero_array.GetDimensionalSpaceIterator({}); EXPECT_EQ(zero_iterator.DistanceFromEnd(absl::nullopt), 1); ++zero_iterator; EXPECT_EQ(zero_iterator.DistanceFromEnd(absl::nullopt), 0); } TEST(FlattenedMultiDimensionalArrayIteratorTest, GetDimensions) { using array_t = FlattenedMultiDimensionalArray<int64_t>; array_t array({2, 3}); array_t::DimensionalSpaceIterator iterator = array.GetDimensionalSpaceIterator({0, 1}); EXPECT_EQ(iterator.GetDimensions(), array.GetDimensions()); array_t zero_array({}); array_t::DimensionalSpaceIterator zero_iterator = zero_array.GetDimensionalSpaceIterator({}); EXPECT_EQ(zero_iterator.GetDimensions(), zero_array.GetDimensions()); } TEST(FlattenedMultiDimensionalArrayIteratorTest, GetCoordinate) { using array_t = FlattenedMultiDimensionalArray<int64_t>; array_t array({2, 3}); array_t::DimensionalSpaceIterator iterator = array.GetDimensionalSpaceIterator({0, 1}); for (int64_t i = 0; i < 3; i++) { for (int64_t j = 0; j < 2; j++) { EXPECT_EQ(iterator.GetCoordinate(), Coordinate({j, i})); ++iterator; } } EXPECT_EQ(iterator.GetCoordinate(), absl::nullopt); array_t zero_array({}); array_t::DimensionalSpaceIterator zero_iterator = zero_array.GetDimensionalSpaceIterator({}); EXPECT_EQ(zero_iterator.GetCoordinate(), Coordinate({})); ++zero_iterator; EXPECT_EQ(zero_iterator.GetCoordinate(), absl::nullopt); } TEST(FlattenedMultiDimensionalArrayIteratorTest, EqualAndNotEqualOperator) { using array_t = FlattenedMultiDimensionalArray<int64_t>; array_t array({2, 3}); array_t::DimensionalSpaceIterator iterator0 = array.GetDimensionalSpaceIterator({0, 1}); array_t::DimensionalSpaceIterator iterator1 = array.GetDimensionalSpaceIterator({0, 1}); for (; !iterator0.IsAtBounds(); ++iterator0, ++iterator1) { EXPECT_TRUE(iterator0 == iterator1); EXPECT_FALSE(iterator0 != iterator1); } EXPECT_TRUE(iterator0 == iterator1); EXPECT_FALSE(iterator0 != iterator1); array_t zero_array({}); array_t::DimensionalSpaceIterator zero_iterator0 = zero_array.GetDimensionalSpaceIterator({}); array_t::DimensionalSpaceIterator zero_iterator1 = zero_array.GetDimensionalSpaceIterator({}); for (; !iterator0.IsAtBounds(); ++zero_iterator0, ++zero_iterator1) { EXPECT_TRUE(zero_iterator0 == zero_iterator1); EXPECT_FALSE(zero_iterator0 != zero_iterator1); } EXPECT_TRUE(zero_iterator0 == zero_iterator1); EXPECT_FALSE(zero_iterator0 != zero_iterator1); } TEST(FlattenedMultiDimensionalArrayIteratorTest, PostfixAddition) { using array_t = FlattenedMultiDimensionalArray<int64_t>; array_t array({2, 3}); array_t::DimensionalSpaceIterator iterator = array.GetDimensionalSpaceIterator({0, 1}); array_t::DimensionalSpaceIterator iterator_copy(iterator); array_t::DimensionalSpaceIterator iterator_postfix = iterator++; EXPECT_EQ(iterator_copy, iterator_postfix); EXPECT_NE(iterator, iterator_postfix); array_t zero_array({}); array_t::DimensionalSpaceIterator zero_iterator = zero_array.GetDimensionalSpaceIterator({}); array_t::DimensionalSpaceIterator zero_iterator_copy(zero_iterator); array_t::DimensionalSpaceIterator zero_iterator_postfix = zero_iterator++; EXPECT_EQ(zero_iterator_copy, zero_iterator_postfix); EXPECT_NE(zero_iterator, zero_iterator_postfix); } TEST(FlattenedMultiDimensionalArrayIteratorTest, ElementAccess) { using array_t = FlattenedMultiDimensionalArray<int64_t>; array_t array({2, 3}); array_t::DimensionalSpaceIterator iterator = array.GetDimensionalSpaceIterator({0, 1}); int64_t count = 0; while (!iterator.IsAtBounds()) { *iterator++ = count++; } for (int64_t index = 0; index < 6; index++) { EXPECT_EQ(array.GetValue(index), index); } array_t zero_array({}); array_t::DimensionalSpaceIterator zero_iterator = zero_array.GetDimensionalSpaceIterator({}); *zero_iterator++ = 42; EXPECT_EQ(zero_array.GetValue(0), 42); } } }
#include "xls/noc/config_ng/flattened_multi_dimensional_array.h" #include "gtest/gtest.h" namespace xls::noc { namespace { TEST(FlattenedMultiDimensionalArrayTest, GetElementCount) { FlattenedMultiDimensionalArray<int64_t> array({3, 4}); EXPECT_EQ(array.GetElementCount(), 12); FlattenedMultiDimensionalArray<int64_t> zero_array({}); EXPECT_EQ(zero_array.GetElementCount(), 1); } TEST(FlattenedMultiDimensionalArrayTest, iterators) { FlattenedMultiDimensionalArray<int64_t> array({3, 4}); int64_t count = 0; for (int64_t element : array) { element++; count++; } EXPECT_EQ(array.GetElementCount(), count); FlattenedMultiDimensionalArray<int64_t> zero_array({}); count = 0; for (int64_t element : zero_array) { element++; count++; } EXPECT_EQ(zero_array.GetElementCount(), count); } TEST(FlattenedMultiDimensionalArrayTest, GetDimensions) { FlattenedMultiDimensionalArray<int64_t> array({3, 4}); const DimensionBounds& dimensions = array.GetDimensions(); EXPECT_EQ(dimensions.GetDimensionCount(), 2); EXPECT_EQ(dimensions.GetDimensionBound(0), 3); EXPECT_EQ(dimensions.GetDimensionBound(1), 4); FlattenedMultiDimensionalArray<int64_t> zero_array({}); const DimensionBounds& zero_dimensions = zero_array.GetDimensions(); EXPECT_EQ(zero_dimensions.GetDimensionCount(), 0); } TEST(FlattenedMultiDimensionalArrayTest, SetValueCoordinate) { FlattenedMultiDimensionalArray<int64_t> array({2, 2}); for (int64_t dimension_1 = 0; dimension_1 < 2; dimension_1++) { for (int64_t dimension_0 = 0; dimension_0 < 2; dimension_0++) { array.SetValue({dimension_0, dimension_1}, 42); } } FlattenedMultiDimensionalArray<int64_t> zero_array({}); zero_array.SetValue({}, 42); } TEST(FlattenedMultiDimensionalArrayTest, SetValueIndex) { FlattenedMultiDimensionalArray<int64_t> array({2, 2}); for (int64_t count = 0; count < 4; count++) { array.SetValue(count, 42); } FlattenedMultiDimensionalArray<int64_t> zero_array({}); zero_array.SetValue(0, 42); } TEST(FlattenedMultiDimensionalArrayTest, GetValueCoordinate) { FlattenedMultiDimensionalArray<int64_t> array({2, 2}); int value = 0; for (int64_t dimension_1 = 0; dimension_1 < 2; dimension_1++) { for (int64_t dimension_0 = 0; dimension_0 < 2; dimension_0++) { array.SetValue({dimension_0, dimension_1}, value++); } } value = 0; for (int64_t dimension_1 = 0; dimension_1 < 2; dimension_1++) { for (int64_t dimension_0 = 0; dimension_0 < 2; dimension_0++) { int64_t result = array.GetValue({dimension_0, dimension_1}); EXPECT_EQ(result, value++); } } FlattenedMultiDimensionalArray<int64_t> zero_array({}); zero_array.SetValue({}, 42); int64_t result = zero_array.GetValue({}); EXPECT_EQ(result, 42); } TEST(FlattenedMultiDimensionalArrayTest, GetValueIndex) { FlattenedMultiDimensionalArray<int64_t> array({2, 2}); int value = 0; for (int64_t count = 0; count < 4; count++) { array.SetValue(count, value++); } value = 0; for (int64_t count = 0; count < 4; count++) { int64_t result = array.GetValue(count); EXPECT_EQ(result, value++); } FlattenedMultiDimensionalArray<int64_t> zero_array({}); zero_array.SetValue(0, 42); int64_t result = zero_array.GetValue(0); EXPECT_EQ(result, 42); } TEST(FlattenedMultiDimensionalArrayTest, GetCoordinateOfIndex) { FlattenedMultiDimensionalArray<int64_t> array({2, 3}); int64_t index = 0; for (int64_t i = 0; i < 3; i++) { for (int64_t j = 0; j < 2; j++) { Coordinate coordinate = array.GetCoordinateOfIndex(index).value(); EXPECT_EQ(coordinate.GetDimensionCount(), 2); EXPECT_EQ(coordinate.GetCoordinate(0), j); EXPECT_EQ(coordinate.GetCoordinate(1), i); index++; } } EXPECT_EQ(array.GetCoordinateOfIndex(index), absl::nullopt); FlattenedMultiDimensionalArray<int64_t> zero_array({}); Coordinate coordinate = zero_array.GetCoordinateOfIndex(0).value(); EXPECT_EQ(coordinate.GetDimensionCount(), 0); EXPECT_EQ(zero_array.GetCoordinateOfIndex(1), absl::nullopt); } TEST(FlattenedMultiDimensionalArrayIteratorTest, IsAtBoundsCheck) { using array_t = FlattenedMultiDimensionalArray<int64_t>; array_t array({2, 3}); array_t::DimensionalSpaceIterator iterator = array.GetDimensionalSpaceIterator({0, 1}); EXPECT_FALSE(iterator.IsAtBounds()); int64_t count = 0; while (!iterator.IsAtBounds()) { ++iterator; count++; } EXPECT_EQ(count, 6); array_t zero_array({}); array_t::DimensionalSpaceIterator zero_iterator = zero_array.GetDimensionalSpaceIterator({}); EXPECT_FALSE(zero_iterator.IsAtBounds()); count = 0; while (!zero_iterator.IsAtBounds()) { ++zero_iterator; count++; } EXPECT_EQ(count, 1); } TEST(FlattenedMultiDimensionalArrayIteratorTest, DistanceFromEnd) { using array_t = FlattenedMultiDimensionalArray<int64_t>; array_t array({2, 3}); array_t::DimensionalSpaceIterator iterator = array.GetDimensionalSpaceIterator({0, 1}); for (int64_t i = 0; i < 3; i++) { for (int64_t j = 0; j < 2; j++) { EXPECT_EQ(iterator.DistanceFromEnd(0), 2 - j); EXPECT_EQ(iterator.DistanceFromEnd(1), 3 - i); ++iterator; } } EXPECT_EQ(iterator.DistanceFromEnd(0), 0); EXPECT_EQ(iterator.DistanceFromEnd(1), 0); array_t zero_array({}); array_t::DimensionalSpaceIterator zero_iterator = zero_array.GetDimensionalSpaceIterator({}); EXPECT_EQ(zero_iterator.DistanceFromEnd(absl::nullopt), 1); ++zero_iterator; EXPECT_EQ(zero_iterator.DistanceFromEnd(absl::nullopt), 0); } TEST(FlattenedMultiDimensionalArrayIteratorTest, GetDimensions) { using array_t = FlattenedMultiDimensionalArray<int64_t>; array_t array({2, 3}); array_t::DimensionalSpaceIterator iterator = array.GetDimensionalSpaceIterator({0, 1}); EXPECT_EQ(iterator.GetDimensions(), array.GetDimensions()); array_t zero_array({}); array_t::DimensionalSpaceIterator zero_iterator = zero_array.GetDimensionalSpaceIterator({}); EXPECT_EQ(zero_iterator.GetDimensions(), zero_array.GetDimensions()); } TEST(FlattenedMultiDimensionalArrayIteratorTest, GetCoordinate) { using array_t = FlattenedMultiDimensionalArray<int64_t>; array_t array({2, 3}); array_t::DimensionalSpaceIterator iterator = array.GetDimensionalSpaceIterator({0, 1}); for (int64_t i = 0; i < 3; i++) { for (int64_t j = 0; j < 2; j++) { EXPECT_EQ(iterator.GetCoordinate(), Coordinate({j, i})); ++iterator; } } EXPECT_EQ(iterator.GetCoordinate(), absl::nullopt); array_t zero_array({}); array_t::DimensionalSpaceIterator zero_iterator = zero_array.GetDimensionalSpaceIterator({}); EXPECT_EQ(zero_iterator.GetCoordinate(), Coordinate({})); ++zero_iterator; EXPECT_EQ(zero_iterator.GetCoordinate(), absl::nullopt); } TEST(FlattenedMultiDimensionalArrayIteratorTest, EqualAndNotEqualOperator) { using array_t = FlattenedMultiDimensionalArray<int64_t>; array_t array({2, 3}); array_t::DimensionalSpaceIterator iterator0 = array.GetDimensionalSpaceIterator({0, 1}); array_t::DimensionalSpaceIterator iterator1 = array.GetDimensionalSpaceIterator({0, 1}); for (; !iterator0.IsAtBounds(); ++iterator0, ++iterator1) { EXPECT_TRUE(iterator0 == iterator1); EXPECT_FALSE(iterator0 != iterator1); } EXPECT_TRUE(iterator0 == iterator1); EXPECT_FALSE(iterator0 != iterator1); array_t zero_array({}); array_t::DimensionalSpaceIterator zero_iterator0 = zero_array.GetDimensionalSpaceIterator({}); array_t::DimensionalSpaceIterator zero_iterator1 = zero_array.GetDimensionalSpaceIterator({}); for (; !iterator0.IsAtBounds(); ++zero_iterator0, ++zero_iterator1) { EXPECT_TRUE(zero_iterator0 == zero_iterator1); EXPECT_FALSE(zero_iterator0 != zero_iterator1); } EXPECT_TRUE(zero_iterator0 == zero_iterator1); EXPECT_FALSE(zero_iterator0 != zero_iterator1); } TEST(FlattenedMultiDimensionalArrayIteratorTest, PostfixAddition) { using array_t = FlattenedMultiDimensionalArray<int64_t>; array_t array({2, 3}); array_t::DimensionalSpaceIterator iterator = array.GetDimensionalSpaceIterator({0, 1}); array_t::DimensionalSpaceIterator iterator_copy(iterator); array_t::DimensionalSpaceIterator iterator_postfix = iterator++; EXPECT_EQ(iterator_copy, iterator_postfix); EXPECT_NE(iterator, iterator_postfix); array_t zero_array({}); array_t::DimensionalSpaceIterator zero_iterat
PECT_EQ(zero_array.GetValue(0), 42); } } }
or = zero_array.GetDimensionalSpaceIterator({}); array_t::DimensionalSpaceIterator zero_iterator_copy(zero_iterator); array_t::DimensionalSpaceIterator zero_iterator_postfix = zero_iterator++; EXPECT_EQ(zero_iterator_copy, zero_iterator_postfix); EXPECT_NE(zero_iterator, zero_iterator_postfix); } TEST(FlattenedMultiDimensionalArrayIteratorTest, ElementAccess) { using array_t = FlattenedMultiDimensionalArray<int64_t>; array_t array({2, 3}); array_t::DimensionalSpaceIterator iterator = array.GetDimensionalSpaceIterator({0, 1}); int64_t count = 0; while (!iterator.IsAtBounds()) { *iterator++ = count++; } for (int64_t index = 0; index < 6; index++) { EXPECT_EQ(array.GetValue(index), index); } array_t zero_array({}); array_t::DimensionalSpaceIterator zero_iterator = zero_array.GetDimensionalSpaceIterator({}); *zero_iterator++ = 42; EX
random
[ { "content": "fn array_and_array(p: bits[2][5][4][42], q: bits[32], v: bits[2][5][4]) -> bits[2][5][4][42] {\n\n ret array_update.1: bits[2][5][4][42] = array_update(p, v, indices=[q], id=1)\n\n}\n\n)\";\n\n ParseFunctionAndCheckDump(input);\n\n}\n\n\n\nTEST(IrParserTest, DifferentWidthMultiplies) {\n\n std:...
C++
src/god_field.cpp
connorzl/geometry-central
99114ffaf3efb58c912f94402dd0426cbb17d3f1
#include "geometrycentral/god_field.h" GodField::GodField(HalfedgeMesh *m, Geometry<Euclidean>* g) : mesh(m), geom(g) { edgeVector = HalfedgeData<std::complex<double>>(mesh); r = HalfedgeData<std::complex<double>>(mesh); field = FaceData<std::complex<double>>(mesh); faceAreas = FaceData<double>(mesh); } void GodField::computeCrossField(EdgeData<double> &lengths, HalfedgeData<double> &angles) { std::cout << "Computing Smoothest Cross Field" << std::endl; edgeLengths = lengths; heAngles = angles; faceAreas = Operators::computeAreas(mesh, edgeLengths); setup(); Eigen::SparseMatrix<std::complex<double>> M = assembleM(); Eigen::SparseMatrix<std::complex<double>> A = assembleA(); A = A + 1e-8 * M; Eigen::MatrixXcd u = Eigen::MatrixXcd::Random(mesh->nFaces(),1); Eigen::MatrixXcd x; PositiveDefiniteSolver<std::complex<double>> s(A); for (int i = 0; i < nPowerIterations; i++) { Eigen::MatrixXcd rhs = M * u; x = s.solve(rhs); std::complex<double> norm2 = (x.transpose() * M * x)(0,0); u = x / sqrt(norm2); } FaceData<size_t> faceIndices = mesh->getFaceIndices(); for (FacePtr f : mesh->faces()) { std::complex<double> c = u(faceIndices[f],0); std::complex<double> val; if (std::abs(c) == 0) { val = 0; } else { val = c / std::abs(c); } field[f] = val; } std::cout << "Done!" << std::endl; } void GodField::setup() { for (FacePtr f : mesh->faces()) { HalfedgePtr he = f.halfedge(); double l_jl = edgeLengths[he.edge()]; double l_ij = edgeLengths[he.prev().edge()]; double theta_ijl = heAngles[he.next()]; Vector2 j = Vector2{0,0}; Vector2 l = Vector2{l_jl,0}; Vector2 i = Vector2{cos(theta_ijl) * l_ij, sin(theta_ijl) * l_ij}; Vector2 jl = l - j; Vector2 li = i - l; Vector2 ij = j - i; edgeVector[he] = std::complex<double>(jl.x,jl.y); edgeVector[he.next()] = std::complex<double>(li.x,li.y); edgeVector[he.prev()] = std::complex<double>(ij.x,ij.y); } for (VertexPtr v : mesh->vertices()) { for (HalfedgePtr he : v.outgoingHalfedges()) { if (he.edge().isBoundary()) { continue; } std::complex<double> theta_ij = edgeVector[he]; std::complex<double> theta_ji = edgeVector[he.twin()]; r[he] = std::pow((-theta_ij / theta_ji), 4); r[he] = r[he] / std::abs(r[he]); } } } Eigen::SparseMatrix<std::complex<double>> GodField::assembleM() { size_t n = mesh->nFaces(); Eigen::SparseMatrix<std::complex<double>> M(n,n); std::vector<Eigen::Triplet<std::complex<double>>> triplets; FaceData<size_t> faceIndices = mesh->getFaceIndices(); for (FacePtr f : mesh->faces()) { size_t i = faceIndices[f]; triplets.push_back(Eigen::Triplet<std::complex<double>>(i, i, faceAreas[f])); } M.setFromTriplets(triplets.begin(),triplets.end()); return M; } Eigen::SparseMatrix<std::complex<double>> GodField::assembleA() { size_t n = mesh->nFaces(); Eigen::SparseMatrix<std::complex<double>> A(n,n); std::vector<Eigen::Triplet<std::complex<double>>> triplets; FaceData<size_t> faceIndices = mesh->getFaceIndices(); for (FacePtr f : mesh->faces()) { size_t i = faceIndices[f]; HalfedgePtr he_ij = f.halfedge(); std::complex<double> r_ij, r_jk, r_ki; r_ij = r[he_ij]; r_jk = r[he_ij.next()]; r_ki = r[he_ij.prev()]; double sumWeight = 0; double weight; HalfedgePtr he = f.halfedge(); if (!he_ij.edge().isBoundary()) { weight = 1; sumWeight += weight; size_t i_ij = faceIndices[he_ij.twin().face()]; triplets.push_back(Eigen::Triplet<std::complex<double>>(i,i_ij,-weight * r_ij)); } if (!he_ij.next().edge().isBoundary()) { weight = 1; sumWeight += weight; size_t i_jk = faceIndices[he_ij.next().twin().face()]; triplets.push_back(Eigen::Triplet<std::complex<double>>(i,i_jk,-weight * r_jk)); } if (!he_ij.prev().edge().isBoundary()) { weight = 1; sumWeight += weight; size_t i_ki = faceIndices[he_ij.prev().twin().face()]; triplets.push_back(Eigen::Triplet<std::complex<double>>(i,i_ki,-weight * r_ki)); } triplets.push_back(Eigen::Triplet<std::complex<double>>(i, i, sumWeight)); } A.setFromTriplets(triplets.begin(),triplets.end()); return A; } size_t GodField::computeSingularities(VertexData<int> &singularities) { std::cout << "Computing Singularities..."; int total = 0; size_t numSingularities = 0; for (VertexPtr v : mesh->vertices()) { double angleSum = 0; if (v.isBoundary()) { singularities[v] = 0; continue; } for (HalfedgePtr he : v.outgoingHalfedges()) { std::complex<double> u_i = field[he.face()]; std::complex<double> u_j = field[he.twin().face()]; std::complex<double> r_ji = r[he]; angleSum += std::arg(u_i / (r_ji * u_j)); } double phi = (angleSum + 4*geom->angleDefect(v)) / (2.0 * M_PI); singularities[v] = std::round(phi); if (singularities[v] != 0) { numSingularities++; } total += singularities[v]; } std::cout << "Done! Singularities Index Sum: " << total << std::endl; return numSingularities; }
#include "geometrycentral/god_field.h" GodField::GodField(HalfedgeMesh *m, Geometry<Euclidean>* g) : mesh(m), geom(g) { edgeVector = HalfedgeData<std::complex<double>>(mesh); r = HalfedgeData<std::complex<double>>(mesh); field = FaceData<std::complex<double>>(mesh); faceAreas = FaceData<double>(mesh); }
void GodField::setup() { for (FacePtr f : mesh->faces()) { HalfedgePtr he = f.halfedge(); double l_jl = edgeLengths[he.edge()]; double l_ij = edgeLengths[he.prev().edge()]; double theta_ijl = heAngles[he.next()]; Vector2 j = Vector2{0,0}; Vector2 l = Vector2{l_jl,0}; Vector2 i = Vector2{cos(theta_ijl) * l_ij, sin(theta_ijl) * l_ij}; Vector2 jl = l - j; Vector2 li = i - l; Vector2 ij = j - i; edgeVector[he] = std::complex<double>(jl.x,jl.y); edgeVector[he.next()] = std::complex<double>(li.x,li.y); edgeVector[he.prev()] = std::complex<double>(ij.x,ij.y); } for (VertexPtr v : mesh->vertices()) { for (HalfedgePtr he : v.outgoingHalfedges()) { if (he.edge().isBoundary()) { continue; } std::complex<double> theta_ij = edgeVector[he]; std::complex<double> theta_ji = edgeVector[he.twin()]; r[he] = std::pow((-theta_ij / theta_ji), 4); r[he] = r[he] / std::abs(r[he]); } } } Eigen::SparseMatrix<std::complex<double>> GodField::assembleM() { size_t n = mesh->nFaces(); Eigen::SparseMatrix<std::complex<double>> M(n,n); std::vector<Eigen::Triplet<std::complex<double>>> triplets; FaceData<size_t> faceIndices = mesh->getFaceIndices(); for (FacePtr f : mesh->faces()) { size_t i = faceIndices[f]; triplets.push_back(Eigen::Triplet<std::complex<double>>(i, i, faceAreas[f])); } M.setFromTriplets(triplets.begin(),triplets.end()); return M; } Eigen::SparseMatrix<std::complex<double>> GodField::assembleA() { size_t n = mesh->nFaces(); Eigen::SparseMatrix<std::complex<double>> A(n,n); std::vector<Eigen::Triplet<std::complex<double>>> triplets; FaceData<size_t> faceIndices = mesh->getFaceIndices(); for (FacePtr f : mesh->faces()) { size_t i = faceIndices[f]; HalfedgePtr he_ij = f.halfedge(); std::complex<double> r_ij, r_jk, r_ki; r_ij = r[he_ij]; r_jk = r[he_ij.next()]; r_ki = r[he_ij.prev()]; double sumWeight = 0; double weight; HalfedgePtr he = f.halfedge(); if (!he_ij.edge().isBoundary()) { weight = 1; sumWeight += weight; size_t i_ij = faceIndices[he_ij.twin().face()]; triplets.push_back(Eigen::Triplet<std::complex<double>>(i,i_ij,-weight * r_ij)); } if (!he_ij.next().edge().isBoundary()) { weight = 1; sumWeight += weight; size_t i_jk = faceIndices[he_ij.next().twin().face()]; triplets.push_back(Eigen::Triplet<std::complex<double>>(i,i_jk,-weight * r_jk)); } if (!he_ij.prev().edge().isBoundary()) { weight = 1; sumWeight += weight; size_t i_ki = faceIndices[he_ij.prev().twin().face()]; triplets.push_back(Eigen::Triplet<std::complex<double>>(i,i_ki,-weight * r_ki)); } triplets.push_back(Eigen::Triplet<std::complex<double>>(i, i, sumWeight)); } A.setFromTriplets(triplets.begin(),triplets.end()); return A; } size_t GodField::computeSingularities(VertexData<int> &singularities) { std::cout << "Computing Singularities..."; int total = 0; size_t numSingularities = 0; for (VertexPtr v : mesh->vertices()) { double angleSum = 0; if (v.isBoundary()) { singularities[v] = 0; continue; } for (HalfedgePtr he : v.outgoingHalfedges()) { std::complex<double> u_i = field[he.face()]; std::complex<double> u_j = field[he.twin().face()]; std::complex<double> r_ji = r[he]; angleSum += std::arg(u_i / (r_ji * u_j)); } double phi = (angleSum + 4*geom->angleDefect(v)) / (2.0 * M_PI); singularities[v] = std::round(phi); if (singularities[v] != 0) { numSingularities++; } total += singularities[v]; } std::cout << "Done! Singularities Index Sum: " << total << std::endl; return numSingularities; }
void GodField::computeCrossField(EdgeData<double> &lengths, HalfedgeData<double> &angles) { std::cout << "Computing Smoothest Cross Field" << std::endl; edgeLengths = lengths; heAngles = angles; faceAreas = Operators::computeAreas(mesh, edgeLengths); setup(); Eigen::SparseMatrix<std::complex<double>> M = assembleM(); Eigen::SparseMatrix<std::complex<double>> A = assembleA(); A = A + 1e-8 * M; Eigen::MatrixXcd u = Eigen::MatrixXcd::Random(mesh->nFaces(),1); Eigen::MatrixXcd x; PositiveDefiniteSolver<std::complex<double>> s(A); for (int i = 0; i < nPowerIterations; i++) { Eigen::MatrixXcd rhs = M * u; x = s.solve(rhs); std::complex<double> norm2 = (x.transpose() * M * x)(0,0); u = x / sqrt(norm2); } FaceData<size_t> faceIndices = mesh->getFaceIndices(); for (FacePtr f : mesh->faces()) { std::complex<double> c = u(faceIndices[f],0); std::complex<double> val; if (std::abs(c) == 0) { val = 0; } else { val = c / std::abs(c); } field[f] = val; } std::cout << "Done!" << std::endl; }
function_block-full_function
[ { "content": "class GodField {\n\n public:\n\n GodField() {};\n\n GodField(HalfedgeMesh *m, Geometry<Euclidean> *geom);\n\n\n\n void computeCrossField(EdgeData<double> &lengths, HalfedgeData<double> &angles);\n\n size_t computeSingularities(VertexData<int> &singularities);\n\n\n\n...
C++
Src/Graphics/Camera.cpp
QuaternionMark/COMP371-FinalProject
ac750a5bb4896f4800d8fbc08fac9ef9a002ed44
#include <cmath> #include <stdexcept> #include "Camera.h" #include "../Math/MathUtil.h" Camera::Camera(int w, int h, float fov, float nearZ, float farZ, bool orthographic) { position = Vector3f(0.f, 0.f, 0.f); lookAt = Vector3f(0.f, 0.f, 1.f); upDir = Vector3f(0.f, 1.f, 0.f); viewMatrix = Matrix4x4f::constructViewMat(position, lookAt, upDir); xAngle = 0.f; yAngle = 0.f; yAngleLimit = 1.5f; tilt = 0.f; this->nearPlaneZ = nearZ; this->farPlaneZ = farZ; this->fov = fov; this->width = w; this->height = h; this->orthographicProj = orthographic; this->thirdPerson = false; this->thirdPersonRadius = 20.f; rotation = Matrix4x4f::identity; needsViewUpdate = true; needsProjUpdate = true; } Camera::Camera(int w, int h) : Camera(w, h, MathUtil::degToRad(70.f)) { } void Camera::addShader(Shader* shd) { shaders.push_back(shd); needsViewUpdate = true; needsProjUpdate = true; } Matrix4x4f Camera::getViewMatrix() const { return viewMatrix; } Matrix4x4f Camera::getProjectionMatrix() const { return projectionMatrix; } void Camera::update() { GLuint err = GL_NO_ERROR; err = glGetError(); if (err != GL_NO_ERROR) { throw std::runtime_error("Uncaught exception - Camera::update()."); } if (needsViewUpdate) { if (!thirdPerson) { rotation = Matrix4x4f::rotate(Vector3f(-yAngle, xAngle, tilt)); viewMatrix = Matrix4x4f::constructViewMat(position, rotation.transform(lookAt), rotation.transform(upDir)); } else { float cosXAngle = std::cos(xAngle); float cosYAngle = std::cos(yAngle); float sinXAngle = std::sin(xAngle); float sinYAngle = std::sin(yAngle); Vector3f thirdPersonPosition = position.subtract(Vector3f(thirdPersonRadius * cosYAngle * cosXAngle, thirdPersonRadius * sinYAngle, -thirdPersonRadius * cosYAngle * sinXAngle)); viewMatrix = Matrix4x4f::constructViewMat(thirdPersonPosition, position.subtract(thirdPersonPosition).normalize(), upDir); } for (int i = 0; i < (int)shaders.size(); i++) { shaders[i]->getMat4Uniform("viewMatrix")->setValue(viewMatrix); } needsViewUpdate = false; } if (needsProjUpdate) { if (!orthographicProj) { projectionMatrix = Matrix4x4f::constructPerspectiveMat(fov, getAspectRatio(), nearPlaneZ, farPlaneZ); } else { projectionMatrix = Matrix4x4f::constructOrthographicMat((float)width, (float)height, nearPlaneZ, farPlaneZ); } for (int i = 0; i < (int)shaders.size(); i++) { shaders[i]->getMat4Uniform("projectionMatrix")->setValue(projectionMatrix); } needsProjUpdate = false; } } Vector3f Camera::getPosition() const { return position; } void Camera::setPosition(const Vector3f& pos) { needsViewUpdate = true; position = pos; } void Camera::setTilt(float rad) { needsViewUpdate = !MathUtil::eqFloats(rad, tilt); tilt = rad; } void Camera::addAngle(float x, float y) { if (MathUtil::eqFloats(x, 0.f) && MathUtil::eqFloats(y, 0.f)) { return; } xAngle += x; yAngle -= y; if (yAngle < -yAngleLimit) { yAngle = -yAngleLimit; } else if (yAngle > yAngleLimit) { yAngle = yAngleLimit; } float PI_MUL_2 = MathUtil::PI * 2.f; if (xAngle > PI_MUL_2) { xAngle -= PI_MUL_2; } else if (xAngle < -PI_MUL_2) { xAngle += PI_MUL_2; } needsViewUpdate = true; } void Camera::resetAngle() { xAngle = 0.f; yAngle = 0.f; needsViewUpdate = true; } void Camera::setThirdPersonPerspective(bool bruh) { needsViewUpdate = bruh != thirdPerson; thirdPerson = bruh; } bool Camera::isThirdPerson() const { return thirdPerson; } void Camera::addFov(float deg) { fov += MathUtil::degToRad(deg); fov = MathUtil::clampFloat(fov, 0.1f, 2.9f); needsProjUpdate = true; } void Camera::setXYClippings(int w, int h) { if (width == w && height == h) { return; } this->width = w; this->height = h; needsProjUpdate = true; } void Camera::setZClippings(float nearZ, float farZ) { if (MathUtil::eqFloats(nearPlaneZ, nearZ) && MathUtil::eqFloats(farPlaneZ, farZ)) { return; } nearPlaneZ = nearZ; farPlaneZ = farZ; needsProjUpdate = true; } float Camera::getAspectRatio() const { return (float)width / height; } void Camera::setOrthographicProj(bool bruh) { needsProjUpdate = bruh != orthographicProj; orthographicProj = bruh; }
#include <cmath> #include <stdexcept> #include "Camera.h" #include "../Math/MathUtil.h" Camera::Camera(int w, int h, float fov, float nearZ, float farZ, bool orthographic) { position = Vector3f(0.f, 0.f, 0.f); lookAt = Vector3f(0.f, 0.f, 1.f); upDir = Vector3f(0.f, 1.f, 0.f); viewMatrix = Matrix4x4f::constructViewMat(position, lookAt, upDir); xAngle = 0.f; yAngle = 0.f; yAngleLimit = 1.5f; tilt = 0.f; this->nearPlaneZ = nearZ; this->farPlaneZ = farZ; this->fov = fov; this->width = w; this->height = h; this->orthographicProj = orthographic; this->thirdPerson = false; this->thirdPersonRadius = 20.f; rotation = Matrix4x4f::identity; needsViewUpdate = true; needsProjUpdate = true; } Camera::Camera(int w, int h) : Camera(w, h, MathUtil::degToRad(70.f)) { } void Camera::addShader(Shader* shd) { shaders.push_back(shd); needsViewUpdate = true; needsProjUpdate = true; } Matrix4x4f Camera::getViewMatrix() const { return viewMatrix; } Matrix4x4f Camera::getProjectionMatrix() const { return projectionMatrix; } void Camera::update() { GLuint err = GL_NO_ERROR; err = glGetError(); if (err != GL_NO_ERROR) { throw std::runtime_error("Uncaught exception - Camera::update()."); } if (needsViewUpdate) { if (!thirdPerson) { rotation = Matrix4x4f::rotate(Vector3f(-yAngle, xAngle, tilt)); viewMatrix = Matrix4x4f::constructViewMat(position, rotation.transform(lookAt), rotation.transform(upDir)); } else { float cosXAngle = std::cos(xAngle); float cosYAngle = std::cos(yAngle); float sinXAngle = std::sin(xAngle); float sinYAngle = std::sin(yAngle); Vector3f thirdPersonPosition =
; viewMatrix = Matrix4x4f::constructViewMat(thirdPersonPosition, position.subtract(thirdPersonPosition).normalize(), upDir); } for (int i = 0; i < (int)shaders.size(); i++) { shaders[i]->getMat4Uniform("viewMatrix")->setValue(viewMatrix); } needsViewUpdate = false; } if (needsProjUpdate) { if (!orthographicProj) { projectionMatrix = Matrix4x4f::constructPerspectiveMat(fov, getAspectRatio(), nearPlaneZ, farPlaneZ); } else { projectionMatrix = Matrix4x4f::constructOrthographicMat((float)width, (float)height, nearPlaneZ, farPlaneZ); } for (int i = 0; i < (int)shaders.size(); i++) { shaders[i]->getMat4Uniform("projectionMatrix")->setValue(projectionMatrix); } needsProjUpdate = false; } } Vector3f Camera::getPosition() const { return position; } void Camera::setPosition(const Vector3f& pos) { needsViewUpdate = true; position = pos; } void Camera::setTilt(float rad) { needsViewUpdate = !MathUtil::eqFloats(rad, tilt); tilt = rad; } void Camera::addAngle(float x, float y) { if (MathUtil::eqFloats(x, 0.f) && MathUtil::eqFloats(y, 0.f)) { return; } xAngle += x; yAngle -= y; if (yAngle < -yAngleLimit) { yAngle = -yAngleLimit; } else if (yAngle > yAngleLimit) { yAngle = yAngleLimit; } float PI_MUL_2 = MathUtil::PI * 2.f; if (xAngle > PI_MUL_2) { xAngle -= PI_MUL_2; } else if (xAngle < -PI_MUL_2) { xAngle += PI_MUL_2; } needsViewUpdate = true; } void Camera::resetAngle() { xAngle = 0.f; yAngle = 0.f; needsViewUpdate = true; } void Camera::setThirdPersonPerspective(bool bruh) { needsViewUpdate = bruh != thirdPerson; thirdPerson = bruh; } bool Camera::isThirdPerson() const { return thirdPerson; } void Camera::addFov(float deg) { fov += MathUtil::degToRad(deg); fov = MathUtil::clampFloat(fov, 0.1f, 2.9f); needsProjUpdate = true; } void Camera::setXYClippings(int w, int h) { if (width == w && height == h) { return; } this->width = w; this->height = h; needsProjUpdate = true; } void Camera::setZClippings(float nearZ, float farZ) { if (MathUtil::eqFloats(nearPlaneZ, nearZ) && MathUtil::eqFloats(farPlaneZ, farZ)) { return; } nearPlaneZ = nearZ; farPlaneZ = farZ; needsProjUpdate = true; } float Camera::getAspectRatio() const { return (float)width / height; } void Camera::setOrthographicProj(bool bruh) { needsProjUpdate = bruh != orthographicProj; orthographicProj = bruh; }
position.subtract(Vector3f(thirdPersonRadius * cosYAngle * cosXAngle, thirdPersonRadius * sinYAngle, -thirdPersonRadius * cosYAngle * sinXAngle))
call_expression
[ { "content": "struct NameCompare: std::binary_function <const char *, const char *, bool>\n\n{\n\n bool\n\n operator () (const char *x, const char *y) const\n\n {\n\n\treturn strcmp (x, y) < 0;\n\n }\n\n};\n\n\n\n\n\ntypedef Attribute* (*Constructor)();\n\ntypedef std::map <const char *, Constructor...
C++
StageProc2F64Neon.hpp
unevens/hiir
4589fedb4d08b899514cb605ccd7418bf262ab18
#if ! defined (hiir_StageProc2F64Neon_CODEHEADER_INCLUDED) #define hiir_StageProc2F64Neon_CODEHEADER_INCLUDED #include "hiir/StageDataNeonV2F64.h" namespace hiir { template <> inline void StageProc2F64Neon <1>::process_sample_pos (const int nbr_coefs, float64x2_t &spl_0, float64x2_t &spl_1, StageDataNeonV2F64 *stage_arr) { const int cnt = nbr_coefs + 2 - 1; const float64x2_t tmp_0 = vmlaq_f64 ( vld1q_f64 (stage_arr [cnt - 2]._mem ), spl_0 - vld1q_f64 (stage_arr [cnt ]._mem ), vld1q_f64 (stage_arr [cnt ]._coef) ); vst1q_f64 (stage_arr [cnt - 2]._mem, spl_0); vst1q_f64 (stage_arr [cnt - 1]._mem, spl_1); vst1q_f64 (stage_arr [cnt ]._mem, tmp_0); spl_0 = tmp_0; } template <> inline void StageProc2F64Neon <0>::process_sample_pos (const int nbr_coefs, float64x2_t &spl_0, float64x2_t &spl_1, StageDataNeonV2F64 *stage_arr) { const int cnt = nbr_coefs + 2; vst1q_f64 (stage_arr [cnt - 2]._mem, spl_0); vst1q_f64 (stage_arr [cnt - 1]._mem, spl_1); } template <int REMAINING> void StageProc2F64Neon <REMAINING>::process_sample_pos (const int nbr_coefs, float64x2_t &spl_0, float64x2_t &spl_1, StageDataNeonV2F64 *stage_arr) { const int cnt = nbr_coefs + 2 - REMAINING; const float64x2_t tmp_0 = vmlaq_f64 ( vld1q_f64 (stage_arr [cnt - 2]._mem ), spl_0 - vld1q_f64 (stage_arr [cnt ]._mem ), vld1q_f64 (stage_arr [cnt ]._coef) ); const float64x2_t tmp_1 = vmlaq_f64 ( vld1q_f64 (stage_arr [cnt - 1]._mem ), spl_1 - vld1q_f64 (stage_arr [cnt + 1]._mem ), vld1q_f64 (stage_arr [cnt + 1]._coef) ); vst1q_f64 (stage_arr [cnt - 2]._mem, spl_0); vst1q_f64 (stage_arr [cnt - 1]._mem, spl_1); spl_0 = tmp_0; spl_1 = tmp_1; StageProc2F64Neon <REMAINING - 2>::process_sample_pos ( nbr_coefs, spl_0, spl_1, stage_arr ); } template <> inline void StageProc2F64Neon <1>::process_sample_neg (const int nbr_coefs, float64x2_t &spl_0, float64x2_t &spl_1, StageDataNeonV2F64 *stage_arr) { const int cnt = nbr_coefs + 2 - 1; float64x2_t tmp_0 = spl_0; tmp_0 += vld1q_f64 (stage_arr [cnt ]._mem ); tmp_0 *= vld1q_f64 (stage_arr [cnt ]._coef); tmp_0 -= vld1q_f64 (stage_arr [cnt - 2]._mem ); vst1q_f64 (stage_arr [cnt - 2]._mem, spl_0); vst1q_f64 (stage_arr [cnt - 1]._mem, spl_1); vst1q_f64 (stage_arr [cnt ]._mem, tmp_0); spl_0 = tmp_0; } template <> inline void StageProc2F64Neon <0>::process_sample_neg (const int nbr_coefs, float64x2_t &spl_0, float64x2_t &spl_1, StageDataNeonV2F64 *stage_arr) { const int cnt = nbr_coefs + 2; vst1q_f64 (stage_arr [cnt - 2]._mem, spl_0); vst1q_f64 (stage_arr [cnt - 1]._mem, spl_1); } template <int REMAINING> void StageProc2F64Neon <REMAINING>::process_sample_neg (const int nbr_coefs, float64x2_t &spl_0, float64x2_t &spl_1, StageDataNeonV2F64 *stage_arr) { const int cnt = nbr_coefs + 2 - REMAINING; float64x2_t tmp_0 = spl_0; tmp_0 += vld1q_f64 (stage_arr [cnt ]._mem ); tmp_0 *= vld1q_f64 (stage_arr [cnt ]._coef); tmp_0 -= vld1q_f64 (stage_arr [cnt - 2]._mem ); float64x2_t tmp_1 = spl_1; tmp_1 += vld1q_f64 (stage_arr [cnt + 1]._mem ); tmp_1 *= vld1q_f64 (stage_arr [cnt + 1]._coef); tmp_1 -= vld1q_f64 (stage_arr [cnt - 1]._mem ); vst1q_f64 (stage_arr [cnt - 2]._mem, spl_0); vst1q_f64 (stage_arr [cnt - 1]._mem, spl_1); spl_0 = tmp_0; spl_1 = tmp_1; StageProc2F64Neon <REMAINING - 2>::process_sample_neg ( nbr_coefs, spl_0, spl_1, stage_arr ); } } #endif
#if ! defined (hiir_StageProc2F64Neon_CODEHEADER_INCLUDED) #define hiir_StageProc2F64Neon_CODEHEADER_INCLUDED #include "hiir/StageDataNeonV2F64.h" namespace hiir { template <> inline void StageProc2F64Neon <1>::process_sample_pos (const int nbr_coefs, float64x2_t &spl_0, float64x2_t &spl_1, St
aq_f64 ( vld1q_f64 (stage_arr [cnt - 2]._mem ), spl_0 - vld1q_f64 (stage_arr [cnt ]._mem ), vld1q_f64 (stage_arr [cnt ]._coef) ); const float64x2_t tmp_1 = vmlaq_f64 ( vld1q_f64 (stage_arr [cnt - 1]._mem ), spl_1 - vld1q_f64 (stage_arr [cnt + 1]._mem ), vld1q_f64 (stage_arr [cnt + 1]._coef) ); vst1q_f64 (stage_arr [cnt - 2]._mem, spl_0); vst1q_f64 (stage_arr [cnt - 1]._mem, spl_1); spl_0 = tmp_0; spl_1 = tmp_1; StageProc2F64Neon <REMAINING - 2>::process_sample_pos ( nbr_coefs, spl_0, spl_1, stage_arr ); } template <> inline void StageProc2F64Neon <1>::process_sample_neg (const int nbr_coefs, float64x2_t &spl_0, float64x2_t &spl_1, StageDataNeonV2F64 *stage_arr) { const int cnt = nbr_coefs + 2 - 1; float64x2_t tmp_0 = spl_0; tmp_0 += vld1q_f64 (stage_arr [cnt ]._mem ); tmp_0 *= vld1q_f64 (stage_arr [cnt ]._coef); tmp_0 -= vld1q_f64 (stage_arr [cnt - 2]._mem ); vst1q_f64 (stage_arr [cnt - 2]._mem, spl_0); vst1q_f64 (stage_arr [cnt - 1]._mem, spl_1); vst1q_f64 (stage_arr [cnt ]._mem, tmp_0); spl_0 = tmp_0; } template <> inline void StageProc2F64Neon <0>::process_sample_neg (const int nbr_coefs, float64x2_t &spl_0, float64x2_t &spl_1, StageDataNeonV2F64 *stage_arr) { const int cnt = nbr_coefs + 2; vst1q_f64 (stage_arr [cnt - 2]._mem, spl_0); vst1q_f64 (stage_arr [cnt - 1]._mem, spl_1); } template <int REMAINING> void StageProc2F64Neon <REMAINING>::process_sample_neg (const int nbr_coefs, float64x2_t &spl_0, float64x2_t &spl_1, StageDataNeonV2F64 *stage_arr) { const int cnt = nbr_coefs + 2 - REMAINING; float64x2_t tmp_0 = spl_0; tmp_0 += vld1q_f64 (stage_arr [cnt ]._mem ); tmp_0 *= vld1q_f64 (stage_arr [cnt ]._coef); tmp_0 -= vld1q_f64 (stage_arr [cnt - 2]._mem ); float64x2_t tmp_1 = spl_1; tmp_1 += vld1q_f64 (stage_arr [cnt + 1]._mem ); tmp_1 *= vld1q_f64 (stage_arr [cnt + 1]._coef); tmp_1 -= vld1q_f64 (stage_arr [cnt - 1]._mem ); vst1q_f64 (stage_arr [cnt - 2]._mem, spl_0); vst1q_f64 (stage_arr [cnt - 1]._mem, spl_1); spl_0 = tmp_0; spl_1 = tmp_1; StageProc2F64Neon <REMAINING - 2>::process_sample_neg ( nbr_coefs, spl_0, spl_1, stage_arr ); } } #endif
ageDataNeonV2F64 *stage_arr) { const int cnt = nbr_coefs + 2 - 1; const float64x2_t tmp_0 = vmlaq_f64 ( vld1q_f64 (stage_arr [cnt - 2]._mem ), spl_0 - vld1q_f64 (stage_arr [cnt ]._mem ), vld1q_f64 (stage_arr [cnt ]._coef) ); vst1q_f64 (stage_arr [cnt - 2]._mem, spl_0); vst1q_f64 (stage_arr [cnt - 1]._mem, spl_1); vst1q_f64 (stage_arr [cnt ]._mem, tmp_0); spl_0 = tmp_0; } template <> inline void StageProc2F64Neon <0>::process_sample_pos (const int nbr_coefs, float64x2_t &spl_0, float64x2_t &spl_1, StageDataNeonV2F64 *stage_arr) { const int cnt = nbr_coefs + 2; vst1q_f64 (stage_arr [cnt - 2]._mem, spl_0); vst1q_f64 (stage_arr [cnt - 1]._mem, spl_1); } template <int REMAINING> void StageProc2F64Neon <REMAINING>::process_sample_pos (const int nbr_coefs, float64x2_t &spl_0, float64x2_t &spl_1, StageDataNeonV2F64 *stage_arr) { const int cnt = nbr_coefs + 2 - REMAINING; const float64x2_t tmp_0 = vml
random
[ { "content": "class StageProc2F64Neon\n\n{\n\n\tstatic_assert (REMAINING >= 0, \"REMAINING must be >= 0.\");\n\n\n\n/*\\\\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/\n\n\n\npublic:\n\n\n\n\tstatic hiir_FORCEINLINE voi...
C++
dependencies/mountutils/src/linux/functions.cpp
runcitadel/imager
5519eec99a8003b4acb71cbfea507f384d4fb910
#include "../mountutils.hpp" #include <cerrno> #include <mntent.h> #include <sys/mount.h> #include <sys/stat.h> auto unmount_disk(const char *device_path) -> MOUNTUTILS_RESULT { const char *mount_path = nullptr; std::vector<std::string> mount_dirs = {}; struct stat stats; if (stat(device_path, &stats) != 0) { MountUtilsLog("Stat failed"); return MOUNTUTILS_ERROR_GENERAL; } else if (S_ISDIR(stats.st_mode)) { MountUtilsLog("Device is a directory"); return MOUNTUTILS_ERROR_INVALID_DRIVE; } struct mntent *mnt_p; struct mntent data; char mnt_buf[4096 + 1024]; FILE *proc_mounts; MountUtilsLog("Reading /proc/mounts"); proc_mounts = setmntent("/proc/mounts", "r"); if (proc_mounts == nullptr) { MountUtilsLog("Couldn't read /proc/mounts"); return MOUNTUTILS_ERROR_GENERAL; } while ((mnt_p = getmntent_r(proc_mounts, &data, mnt_buf, sizeof(mnt_buf))) != nullptr) { mount_path = mnt_p->mnt_fsname; if (strncmp(mount_path, device_path, strlen(device_path)) == 0) { MountUtilsLog("Mount point " + std::string(mount_path) + " belongs to drive " + std::string(device_path)); mount_dirs.emplace_back(mnt_p->mnt_dir); } } MountUtilsLog("Closing /proc/mounts"); endmntent(proc_mounts); size_t unmounts = 0; MOUNTUTILS_RESULT result_code = MOUNTUTILS_SUCCESS; for (const std::string& mount_dir : mount_dirs) { MountUtilsLog("Unmounting " + mount_dir + "..."); mount_path = mount_dir.c_str(); if (umount2(mount_path, MNT_EXPIRE) != 0) { MountUtilsLog("Unmount MNT_EXPIRE " + mount_dir + ": EAGAIN"); if (umount2(mount_path, MNT_EXPIRE) != 0) { MountUtilsLog("Unmount MNT_EXPIRE " + mount_dir + " failed: " + std::string(strerror(errno))); } else { MountUtilsLog("Unmount " + mount_dir + ": success"); unmounts++; continue; } } else { MountUtilsLog("Unmount " + mount_dir + ": success"); unmounts++; continue; } if (umount2(mount_path, MNT_DETACH) != 0) { MountUtilsLog("Unmount MNT_DETACH " + mount_dir + " failed: " + std::string(strerror(errno))); } else { MountUtilsLog("Unmount " + mount_dir + ": success"); unmounts++; continue; } if (umount2(mount_path, MNT_FORCE) != 0) { MountUtilsLog("Unmount MNT_FORCE " + mount_dir + " failed: " + std::string(strerror(errno))); } else { MountUtilsLog("Unmount " + mount_dir + ": success"); unmounts++; continue; } } return unmounts == mount_dirs.size() ? MOUNTUTILS_SUCCESS : MOUNTUTILS_ERROR_GENERAL; } auto eject_disk(const char *device) -> MOUNTUTILS_RESULT { return unmount_disk(device); }
#include "../mountutils.hpp" #include <cerrno> #include <mntent.h> #include <sys/mount.h> #include <sys/stat.h> auto unmount_disk(const char *device_path) -> MOUNTUTILS_RESULT { const char *mount_path = nullptr; std::vector<std::string> mount_dirs = {}; struct stat stats; if (stat(device_path, &stats) != 0) { MountUtilsLog("Stat fa
ts == nullptr) { MountUtilsLog("Couldn't read /proc/mounts"); return MOUNTUTILS_ERROR_GENERAL; } while ((mnt_p = getmntent_r(proc_mounts, &data, mnt_buf, sizeof(mnt_buf))) != nullptr) { mount_path = mnt_p->mnt_fsname; if (strncmp(mount_path, device_path, strlen(device_path)) == 0) { MountUtilsLog("Mount point " + std::string(mount_path) + " belongs to drive " + std::string(device_path)); mount_dirs.emplace_back(mnt_p->mnt_dir); } } MountUtilsLog("Closing /proc/mounts"); endmntent(proc_mounts); size_t unmounts = 0; MOUNTUTILS_RESULT result_code = MOUNTUTILS_SUCCESS; for (const std::string& mount_dir : mount_dirs) { MountUtilsLog("Unmounting " + mount_dir + "..."); mount_path = mount_dir.c_str(); if (umount2(mount_path, MNT_EXPIRE) != 0) { MountUtilsLog("Unmount MNT_EXPIRE " + mount_dir + ": EAGAIN"); if (umount2(mount_path, MNT_EXPIRE) != 0) { MountUtilsLog("Unmount MNT_EXPIRE " + mount_dir + " failed: " + std::string(strerror(errno))); } else { MountUtilsLog("Unmount " + mount_dir + ": success"); unmounts++; continue; } } else { MountUtilsLog("Unmount " + mount_dir + ": success"); unmounts++; continue; } if (umount2(mount_path, MNT_DETACH) != 0) { MountUtilsLog("Unmount MNT_DETACH " + mount_dir + " failed: " + std::string(strerror(errno))); } else { MountUtilsLog("Unmount " + mount_dir + ": success"); unmounts++; continue; } if (umount2(mount_path, MNT_FORCE) != 0) { MountUtilsLog("Unmount MNT_FORCE " + mount_dir + " failed: " + std::string(strerror(errno))); } else { MountUtilsLog("Unmount " + mount_dir + ": success"); unmounts++; continue; } } return unmounts == mount_dirs.size() ? MOUNTUTILS_SUCCESS : MOUNTUTILS_ERROR_GENERAL; } auto eject_disk(const char *device) -> MOUNTUTILS_RESULT { return unmount_disk(device); }
iled"); return MOUNTUTILS_ERROR_GENERAL; } else if (S_ISDIR(stats.st_mode)) { MountUtilsLog("Device is a directory"); return MOUNTUTILS_ERROR_INVALID_DRIVE; } struct mntent *mnt_p; struct mntent data; char mnt_buf[4096 + 1024]; FILE *proc_mounts; MountUtilsLog("Reading /proc/mounts"); proc_mounts = setmntent("/proc/mounts", "r"); if (proc_moun
random
[ { "content": "#define HAVE_STRUCT_STAT_ST_BLKSIZE 1\n", "file_path": "dependencies/libarchive-3.4.2/libarchive/config_freebsd.h", "rank": 0, "score": 121046.8140738607 }, { "content": "#define\tHAVE_STRUCT_STAT_ST_FLAGS 1\n", "file_path": "dependencies/libarchive-3.4.2/tar/config_freebsd...
C++
src/imageio/NumpyImageLoader.cpp
gao-duan/tev
4916200e2315f4fe3c22dfa1546faa085ea68a62
#include <tev/imageio/NumpyImageLoader.h> #include <tev/ThreadPool.h> #include <regex> using namespace Eigen; using namespace filesystem; using namespace std; TEV_NAMESPACE_BEGIN bool NumpyImageLoader::canLoadFile(std::istream& iStream) const { std::string header; std::getline(iStream, header); bool result = !!iStream && header.length() >= 10 && header.substr(1, 5) == "NUMPY" && (unsigned char)header[0] == (unsigned char)0x93; iStream.clear(); iStream.seekg(0); return result; } ImageData NumpyImageLoader::load(std::istream& iStream, const filesystem::path& path, const std::string& channelSelector) const { ImageData result; ThreadPool threadPool; Vector2i img_size; std::string header; std::getline(iStream, header); if (header.length() < 10 || header.substr(1, 5) != "NUMPY" || (unsigned char)header[0] != (unsigned char)0x93) { throw invalid_argument{ tfm::format("Invalid numpy image") }; } auto pos = header.find("descr"); if (pos == std::string::npos) { throw invalid_argument{ tfm::format("Numpy image cannot find `descr` in the header.") }; } pos += 9; bool littleEndian = (header[pos] == '<' || header[pos] == '|' ? true : false); if (!littleEndian) { throw invalid_argument{ tfm::format("Numpy image only supports little endian.") }; } char type = header[pos + 1]; int size = atoi(header.substr(pos + 2, 1).c_str()); if (type != 'f' && type != 'u' && size > 4) { throw invalid_argument{ tfm::format("Numpy image load error, type is neither `f` or `u`") }; } pos = header.find("fortran_order"); if (pos == std::string::npos) throw invalid_argument{ tfm::format("Numpy image load error, no order information") }; pos += 16; bool fortranOrder = header.substr(pos, 4) == "True" ? true : false; if (fortranOrder) throw invalid_argument{ tfm::format("Numpy image load error, only C order is supported now") }; auto offset = header.find("(") + 1; auto shapeString = header.substr(offset, header.find(")") - offset); std::regex regex("[0-9][0-9]*"); std::smatch match; std::vector<int> shape; while (std::regex_search(shapeString, match, regex)) { shape.push_back(std::stoi(match[0].str())); shapeString = match.suffix().str(); } int w = 0, h = 0, ch = 1; if (shape.size() < 2 || shape.size() > 4) { throw invalid_argument{ tfm::format("Numpy image load error, only supports numpy with shape length 2/3/4") }; } if (shape.size() == 2) { h = shape[0]; w = shape[1]; ch = 1; } else if (shape.size() == 3) { h = shape[0]; w = shape[1]; ch = shape[2]; } else if (shape.size() == 4) { h = shape[1]; w = shape[2]; ch = shape[3]; } if (ch > 4) throw invalid_argument{ tfm::format("Numpy image load error, only at most 4 channels is supported") }; img_size = Vector2i(w, h); std::vector<char> data; data.resize(w * h * ch * size); if (!iStream.read(data.data(), w * h * ch * size)) throw invalid_argument{ tfm::format("Numpy image load error, cannot read the data region") }; std::vector<float> float_data; float_data.resize(w * h * ch); if (type == 'f' && size == 4) { const float * new_data = reinterpret_cast<const float*>(data.data()); for (size_t i = 0; i < float_data.size(); ++i) { float_data[i] = new_data[i]; } } else if (type == 'f' && size == 2) { const ::half* new_data = reinterpret_cast<const ::half*>(data.data()); for (size_t i = 0; i < float_data.size(); ++i) { float_data[i] = float(new_data[i]); } } else if (type == 'u' && size == 1) { for (size_t i = 0; i < float_data.size(); ++i) { float_data[i] = float((unsigned char)(data[i])) / 255.0f; } } vector<Channel> channels = makeNChannels(ch, img_size); threadPool.parallelFor<DenseIndex>(0, img_size.y(), [&](DenseIndex y) { for (int x = 0; x < img_size.x(); ++x) { int baseIdx = (y * img_size.x() + x) * ch; for (int c = 0; c < ch; ++c) { float val = float_data[baseIdx + c]; channels[c].at({ x, y }) = val; } } }); vector<pair<size_t, size_t>> matches; for (size_t i = 0; i < channels.size(); ++i) { size_t matchId; if (matchesFuzzy(channels[i].name(), channelSelector, &matchId)) { matches.emplace_back(matchId, i); } } if (!channelSelector.empty()) { sort(begin(matches), end(matches)); } for (const auto& match : matches) { result.channels.emplace_back(move(channels[match.second])); } result.layers.emplace_back(""); return result; } TEV_NAMESPACE_END
#include <tev/imageio/NumpyImageLoader.h> #include <tev/ThreadPool.h> #include <regex> using namespace Eigen; using namespace filesystem; using namespace std; TEV_NAMESPACE_BEGIN bool NumpyImageLoader::canLoadFile(std::istream& iStream) const { std::string header; std::getline(iStream, header); bool result = !!iStream && header.length() >= 10 && header.substr(1, 5) == "NUMPY" && (unsigned char)header[0] == (unsigned char)0x93; iStream.clear(); iStream.seekg(0); return result; } ImageData NumpyImageLoader::load(std::istream& iStream, const filesystem::path& path, const std::string& channelSelector) const { ImageData result; ThreadPool threadPool; Vector2i img_size; std::string header; std::getline(iStream, header); if (header.length() < 10 || header.substr(1, 5) != "NUMPY" || (unsigned char)header[0] != (unsigned char)0x93) { throw invalid_argument{ tfm::format("Invalid numpy image") }; } auto pos = header.find("descr"); if (pos == std::string::npos) { throw invalid_argument{ tfm::format("Numpy image cannot find `descr` in the header.") }; } pos += 9; bool littleEndian = (header[pos] == '<' || header[pos] == '|' ? true : false); if (!littleEndian) { throw invalid_argument{ tfm::format("Numpy image only supports little endian.") }; } char type = header[pos + 1]; int size = atoi(header.substr(pos + 2, 1).c_str()); if (type != 'f' && type != 'u' && size > 4) { throw invalid_argument{ tfm::format("Numpy image load error, type is neither `f` or `u`") }; } pos = header.find("fortran_order"); if (pos == std::string::npos) throw invalid_argument{ tfm::format("Numpy image load error, no order information") }; pos += 16; bool fortranOrder = header.substr(pos, 4) == "True" ? true : false; if (fortranOrder) throw invalid_argument{ tfm::format("Numpy image load error, only C order is supported now") }; auto offset = header.find("(") + 1; auto shapeString = header.substr(offset, header.find(")") - offset); std::regex regex("[0-9][0-9]*"); std::smatch match; std::vector<int> shape; while (std::regex_search(shapeString, match, regex)) { shape.push_back(std::stoi(match[0].str())); shapeString = match.suffix().str(); } int w = 0, h = 0, ch = 1; if (shape.size() < 2 || shape.size() > 4) { throw invalid_argument{ tfm::format("Numpy image load error, only supports numpy with shape length 2/3/4") }; } if (shape.size() == 2) { h = shape[0]; w = shape[1]; ch = 1; } else if (shape.size() == 3) { h = shape[0]; w = shape[1]; ch = shape[2]; } else if (shape.size() == 4) { h = shape[1]; w = shape[2]; ch = shape[3]; } if (ch > 4) throw invalid_argument{ tfm::format("Numpy image load error, only at most 4 channels is supported") }; img_size = Vector2i(w, h); std::vector<char> data; data.resize(w * h * ch * size); if (!iStream.read(data.data(), w * h * ch * size)) throw invalid_argument{ tfm::format("Numpy image load error, cannot read the data region") }; std::vector<float> float_data; float_data.resize(w * h * ch); if (type == 'f' && size == 4) { const float * new_data = reinterpret_cast<const float*>(data.data()); for (size_t i = 0; i < float_data.size(); ++i) { float_data[i] = new_data[i]; } } else if (type == 'f' && size == 2) { const ::half* new_data = reinterpret_cast<const ::half*>(data.data()); for (size_t i = 0; i < float_data.size(); ++i) { float_data[i] = float(new_data[i]); } } else if (type == 'u' && size == 1) { for (size_t i = 0; i < float_data.size(); ++i) { float_data[i] = float((unsigned char)(data[i])) / 255.0f; } } vector<Channel> channels = makeNChannels(ch, img_size); threadPool.parallelFor<DenseIndex>(0, img_size.y(), [&](DenseIndex y) { for (int x = 0; x < img_size.x(); ++x) { int baseIdx = (y * img_size.x() + x) * ch; for (int c = 0; c < ch; ++c) { float val = float_data[baseIdx + c]; channels[c].at({ x, y }) = val; } } }); vector<pair<size_t, size_t>> matches; for (size_t i = 0; i < channels.size(); ++i) { size_t matchId; if (matchesFuzzy(channels[i].name(), channelSelector, &matchId)) { matches.emplace_back(matchId, i); } }
TEV_NAMESPACE_END
if (!channelSelector.empty()) { sort(begin(matches), end(matches)); } for (const auto& match : matches) { result.channels.emplace_back(move(channels[match.second])); } result.layers.emplace_back(""); return result; }
function_block-function_prefix_line
[ { "content": "class NumpyImageSaver : public TypedImageSaver<float> {\n\npublic:\n\n void save(std::ostream& oStream, const filesystem::path& path, const std::vector<float>& data, const Eigen::Vector2i& imageSize, int nChannels) const override;\n\n\n\n bool hasPremultipliedAlpha() const override {\n\n ...
C++
externals/mpir-3.0.0/tests/cxx/t-binary.cc
JaminChan/eos_win
c03e57151cfe152d0d3120abb13226f4df74f37e
#include <iostream> #include "mpir.h" #include "mpirxx.h" #include "gmp-impl.h" #include "tests.h" using namespace std; void check_mpz (void) { { mpz_class a(1), b(2); mpz_class c(a + b); ASSERT_ALWAYS(c == 3); } { mpz_class a(3), b(4); mpz_class c; c = a * b; ASSERT_ALWAYS(c == 12); } { mpz_class a(5), b(3); mpz_class c; c = a % b; ASSERT_ALWAYS(c == 2); } { mpz_class a(1); signed int b = 3; mpz_class c(a - b); ASSERT_ALWAYS(c == -2); } { mpz_class a(-8); unsigned int b = 2; mpz_class c; c = a / b; ASSERT_ALWAYS(c == -4); } { mpz_class a(2); double b = 3.0; mpz_class c(a + b); ASSERT_ALWAYS(c == 5); } { mpz_class a(4); mpz_class b; b = a + 0; ASSERT_ALWAYS(b == 4); } { mpz_class a(3); signed int b = 9; mpz_class c(b / a); ASSERT_ALWAYS(c == 3); } { mpz_class a(3), b(4); mpz_class c(a * (-b)); ASSERT_ALWAYS(c == -12); } { mpz_class a(3), b(2), c(1); mpz_class d; d = (a % b) + c; ASSERT_ALWAYS(d == 2); } { mpz_class a(-5); unsigned int b = 2; mpz_class c((-a) << b); ASSERT_ALWAYS(c == 20); } { mpz_class a(5), b(-4); signed int c = 3; mpz_class d; d = (a * b) >> c; ASSERT_ALWAYS(d == -3); } { mpz_class a(2), b(4); double c = 6; mpz_class d(c / (a - b)); ASSERT_ALWAYS(d == -3); } { mpz_class a(3), b(2); double c = 1; mpz_class d; d = c + (a + b); ASSERT_ALWAYS(d == 6); } { mpz_class a(3), b(5), c(7); mpz_class d; d = (a - b) * (-c); ASSERT_ALWAYS(d == 14); } } void check_mpq (void) { { mpq_class a(1, 2), b(3, 4); mpq_class c(a + b); ASSERT_ALWAYS(c == 1.25); } { mpq_class a(1, 2); signed int b = 3; mpq_class c(a - b); ASSERT_ALWAYS(c == -2.5); } { mpq_class a(1, 2); mpq_class b; b = a + 0; ASSERT_ALWAYS(b == 0.5); } { mpq_class a(2, 3); signed int b = 4; mpq_class c; c = b / a; ASSERT_ALWAYS(c == 6); } { mpq_class a(1, 2); mpz_class b(1); mpq_class c(a + b); ASSERT_ALWAYS(c == 1.5); } { mpq_class a(2, 3); mpz_class b(1); double c = 2.0; mpq_class d; d = a * (b + c); ASSERT_ALWAYS(d == 2); } { mpq_class a(2, 3); mpz_class b(4); mpq_class c(b / a); ASSERT_ALWAYS(c == 6); } { mpq_class a(2, 3); mpz_class b(1), c(4); mpq_class d; d = (b - c) * a; ASSERT_ALWAYS(d == -2); } { mpq_class a(1, 3), b(3, 4); mpq_class c; c = a * (-b); ASSERT_ALWAYS(c == -0.25); } { mpq_class a(1, 3), b(2, 3), c(1, 4); mpq_class d((a / b) + c); ASSERT_ALWAYS(d == 0.75); } { mpq_class a(3, 8); unsigned int b = 4; mpq_class c((-a) << b); ASSERT_ALWAYS(c == -6); } { mpq_class a(1, 2), b(1, 4); double c = 6.0; mpq_class d; d = c / (a + b); ASSERT_ALWAYS(d == 8); } { mpq_class a(1, 2), b(1, 4); mpz_class c(1); mpq_class d((a + b) - c); ASSERT_ALWAYS(d == -0.25); } { mpq_class a(1, 3), b(3, 2); mpz_class c(2), d(4); mpq_class e; e = (a * b) / (c - d); ASSERT_ALWAYS(e == -0.25); } { mpq_class a(1, 3), b(3, 4); mpz_class c(-3); mpq_class d(c * (a * b)); ASSERT_ALWAYS(d == -0.75); } { mpq_class a(1, 3), b(3, 5); mpz_class c(6); signed int d = 4; mpq_class e; e = (c % d) / (a * b); ASSERT_ALWAYS(e == 10); } { mpq_class a(1, 3), b(3, 4), c(2, 5); mpq_class d; d = (a * b) / (-c); ASSERT_ALWAYS(d == -0.625); } } void check_mpf (void) { { mpf_class a(1), b(2); mpf_class c(a + b); ASSERT_ALWAYS(c == 3); } { mpf_class a(1.5), b(6); mpf_class c; c = a / b; ASSERT_ALWAYS(c == 0.25); } { mpf_class a(1); signed int b = -2; mpf_class c(a - b); ASSERT_ALWAYS(c == 3); } { mpf_class a(2); mpf_class b; b = a + 0; ASSERT_ALWAYS(b == 2); } { mpf_class a(2); unsigned int b = 3; mpf_class c; c = b / a; ASSERT_ALWAYS(c == 1.5); } { mpf_class a(2); mpz_class b(3); mpf_class c(a - b); ASSERT_ALWAYS(c == -1); } { mpf_class a(3); mpz_class b(2), c(1); mpf_class d; d = a * (b + c); ASSERT_ALWAYS(d == 9); } { mpf_class a(6); mpq_class b(3, 4); mpf_class c(a * b); ASSERT_ALWAYS(c == 4.5); } { mpf_class a(2), b(-3); mpf_class c; c = a * (-b); ASSERT_ALWAYS(c == 6); } { mpf_class a(3), b(4), c(5); mpf_class d; d = (a / b) - c; ASSERT_ALWAYS(d == -4.25); } { mpf_class a(3); unsigned int b = 2; mpf_class c((-a) >> b); ASSERT_ALWAYS(c == -0.75); } { mpf_class a(2), b(3); double c = 5.0; mpf_class d; d = c / (a + b); ASSERT_ALWAYS(d == 1); } { mpf_class a(2), b(3); mpz_class c(4); mpf_class d; d = (a + b) * c; ASSERT_ALWAYS(d == 20); } { mpf_class a(2), b(3); mpq_class c(1, 2), d(1, 4); mpf_class e; e = (a * b) / (c + d); ASSERT_ALWAYS(e == 8); } { mpf_class a(1), b(2); mpq_class c(3); mpf_class d(c / (a + b)); ASSERT_ALWAYS(d == 1); } { mpf_class a(1); mpz_class b(2); mpq_class c(3, 4); mpf_class d; d = (-c) + (a + b); ASSERT_ALWAYS(d == 2.25); } { mpf_class a(1), b(2), c(3); mpf_class d; d = (a + b) * (-c); ASSERT_ALWAYS(d == -9); } } int main (void) { tests_start(); check_mpz(); check_mpq(); check_mpf(); tests_end(); return 0; }
#include <iostream> #include "mpir.h" #include "mpirxx.h" #include "gmp-impl.h" #include "tests.h" using namespace std; void check_mpz (void) { { mpz_class a(1), b(2); mpz_class c(a + b); ASSERT_ALWAYS(c == 3); } { mpz_class a(3), b(4); mpz_class c; c = a * b; ASSERT_ALWAYS(c == 12); } { mpz_class a(5), b(3); mpz_class c; c = a % b; ASSERT_ALWAYS(c == 2); } { mpz_class a(1); signed int b = 3; mpz_class c(a - b); ASSERT_ALWAYS(c == -2); } { mpz_class a(-8); unsigned int b = 2; mpz_class c; c = a / b; ASSERT_ALWAYS(c == -4); } { mpz_class a(2); double b = 3.0; mpz_class c(a + b); ASSERT_ALWAYS(c == 5); } { mpz_class a(4); mpz_class b; b = a + 0; ASSERT_ALWAYS(b == 4); } { mpz_class a(3); signed int b = 9; mpz_class c(b / a); ASSERT_ALWAYS(c == 3); } { mpz_class a(3), b(4); mpz_class c(a * (-b)); ASSERT_ALWAYS(c == -12); } { mpz_class a(3), b(2), c(1); mpz_class d; d = (a % b) + c; ASSERT_ALWAYS(d == 2); } { mpz_class a(-5); unsigned int b = 2; mpz_class c((-a) << b); ASSERT_ALWAYS(c == 20); } { mpz_class a(5), b(-4); signed int c = 3; mpz_class d; d = (a * b) >> c; ASSERT_ALWAYS(d == -3); } { mpz_class a(2), b(4); double c = 6; mpz_class d(c / (a - b)); ASSERT_ALWAYS(d == -3); } { mpz_class a(3), b(2); double c = 1; mpz_class d; d = c + (a + b); ASSERT_ALWAYS(d == 6); } { mpz_class a(3), b(5), c(7); mpz_class d; d = (a - b) * (-c); ASSERT_ALWAYS(d == 14); } } void check_mpq (void) { { mpq_class a(1, 2), b(3, 4); mpq_class c(a + b); ASSERT_ALWAYS(c == 1.25); } { mpq_class a(1, 2); signed int b = 3; mpq_class c(a - b); ASSERT_ALWAYS(c == -2.5); } { mpq_class a(1, 2); mpq_class b; b = a + 0; ASSERT_ALWA
2), b(1, 4); mpz_class c(1); mpq_class d((a + b) - c); ASSERT_ALWAYS(d == -0.25); } { mpq_class a(1, 3), b(3, 2); mpz_class c(2), d(4); mpq_class e; e = (a * b) / (c - d); ASSERT_ALWAYS(e == -0.25); } { mpq_class a(1, 3), b(3, 4); mpz_class c(-3); mpq_class d(c * (a * b)); ASSERT_ALWAYS(d == -0.75); } { mpq_class a(1, 3), b(3, 5); mpz_class c(6); signed int d = 4; mpq_class e; e = (c % d) / (a * b); ASSERT_ALWAYS(e == 10); } { mpq_class a(1, 3), b(3, 4), c(2, 5); mpq_class d; d = (a * b) / (-c); ASSERT_ALWAYS(d == -0.625); } } void check_mpf (void) { { mpf_class a(1), b(2); mpf_class c(a + b); ASSERT_ALWAYS(c == 3); } { mpf_class a(1.5), b(6); mpf_class c; c = a / b; ASSERT_ALWAYS(c == 0.25); } { mpf_class a(1); signed int b = -2; mpf_class c(a - b); ASSERT_ALWAYS(c == 3); } { mpf_class a(2); mpf_class b; b = a + 0; ASSERT_ALWAYS(b == 2); } { mpf_class a(2); unsigned int b = 3; mpf_class c; c = b / a; ASSERT_ALWAYS(c == 1.5); } { mpf_class a(2); mpz_class b(3); mpf_class c(a - b); ASSERT_ALWAYS(c == -1); } { mpf_class a(3); mpz_class b(2), c(1); mpf_class d; d = a * (b + c); ASSERT_ALWAYS(d == 9); } { mpf_class a(6); mpq_class b(3, 4); mpf_class c(a * b); ASSERT_ALWAYS(c == 4.5); } { mpf_class a(2), b(-3); mpf_class c; c = a * (-b); ASSERT_ALWAYS(c == 6); } { mpf_class a(3), b(4), c(5); mpf_class d; d = (a / b) - c; ASSERT_ALWAYS(d == -4.25); } { mpf_class a(3); unsigned int b = 2; mpf_class c((-a) >> b); ASSERT_ALWAYS(c == -0.75); } { mpf_class a(2), b(3); double c = 5.0; mpf_class d; d = c / (a + b); ASSERT_ALWAYS(d == 1); } { mpf_class a(2), b(3); mpz_class c(4); mpf_class d; d = (a + b) * c; ASSERT_ALWAYS(d == 20); } { mpf_class a(2), b(3); mpq_class c(1, 2), d(1, 4); mpf_class e; e = (a * b) / (c + d); ASSERT_ALWAYS(e == 8); } { mpf_class a(1), b(2); mpq_class c(3); mpf_class d(c / (a + b)); ASSERT_ALWAYS(d == 1); } { mpf_class a(1); mpz_class b(2); mpq_class c(3, 4); mpf_class d; d = (-c) + (a + b); ASSERT_ALWAYS(d == 2.25); } { mpf_class a(1), b(2), c(3); mpf_class d; d = (a + b) * (-c); ASSERT_ALWAYS(d == -9); } } int main (void) { tests_start(); check_mpz(); check_mpq(); check_mpf(); tests_end(); return 0; }
YS(b == 0.5); } { mpq_class a(2, 3); signed int b = 4; mpq_class c; c = b / a; ASSERT_ALWAYS(c == 6); } { mpq_class a(1, 2); mpz_class b(1); mpq_class c(a + b); ASSERT_ALWAYS(c == 1.5); } { mpq_class a(2, 3); mpz_class b(1); double c = 2.0; mpq_class d; d = a * (b + c); ASSERT_ALWAYS(d == 2); } { mpq_class a(2, 3); mpz_class b(4); mpq_class c(b / a); ASSERT_ALWAYS(c == 6); } { mpq_class a(2, 3); mpz_class b(1), c(4); mpq_class d; d = (b - c) * a; ASSERT_ALWAYS(d == -2); } { mpq_class a(1, 3), b(3, 4); mpq_class c; c = a * (-b); ASSERT_ALWAYS(c == -0.25); } { mpq_class a(1, 3), b(2, 3), c(1, 4); mpq_class d((a / b) + c); ASSERT_ALWAYS(d == 0.75); } { mpq_class a(3, 8); unsigned int b = 4; mpq_class c((-a) << b); ASSERT_ALWAYS(c == -6); } { mpq_class a(1, 2), b(1, 4); double c = 6.0; mpq_class d; d = c / (a + b); ASSERT_ALWAYS(d == 8); } { mpq_class a(1,
random
[]
C++
Classes/Scene/BattleMode/BattleScene.cpp
jimmyy512/LegendStory
d2b271023d02eab4f1b540a297d56eae5716bf1f
#include "scene/BattleMode/BattleScene.h" #include <sstream> #include "cocos-ext.h" #include "spine\spine-cocos2dx.h" #include "spine\spine.h" #include "Tools\AudioManagement.h" #include "UI\BattleMode\BattleHUDlayer.h" #include "Map\BattleMode\BattleMap.h" #include "Monster\BattleMode\BattleSoldierFactory.h" #include "Monster\BattleMode\SoldierAI.h" #include "Scene\DeveloperMenuScene.h" #include "ExtensionsAlgorithm.h" #include "DebugLayer.h" USING_NS_CC; USING_NS_CC_EXT; using namespace spine; using namespace cocos2d::experimental; NS_BATTLEMODE_BEGAN BattleScene* BattleScene::static_BattleScene = nullptr; cocos2d::Scene * BattleScene::createScene(int our, int enemy) { auto scene = Scene::createWithPhysics(); auto layer = BattleScene::create(our,enemy); scene->addChild(layer); return scene; } BattleScene* BattleScene::getBattleScene() { if (static_BattleScene == nullptr) return nullptr; else return static_BattleScene; } BattleScene::BattleScene() { this->_continuousClickCount=0; } BattleScene::~BattleScene() { NotificationCenter::getInstance()->removeAllObservers(this); AudioManagement::getInstance()->clearAudioManagement(); SoldierAI::getInstance()->clearData(); static_BattleScene = nullptr; } BattleScene* BattleScene::create(int our, int enemy) { BattleScene* _ptr = new (std::nothrow)BattleScene; if (_ptr && _ptr->init(our,enemy)) { _ptr->autorelease(); } else { CC_SAFE_DELETE(_ptr); } return _ptr; } bool BattleScene::init(int our, int enemy) { if (!Layer::init()) { return false; } static_BattleScene = this; visible = Director::getInstance()->getVisibleSize(); origin = Director::getInstance()->getVisibleOrigin(); NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(BattleScene::pauseBattleMapListenerCallBack), "PauseBattleMapListenerCallBack", NULL); NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(BattleScene::resumeBattleMapListenerCallBack), "ResumeBattleMapListenerCallBack", NULL); AudioManagement::getInstance()->play("music/battleMusic3.mp3", AudioManagement::AudioType::Music, true); auto battleMap = BattleMap::create("map/BattleMode/battleMap.png"); battleMap->setScale(0.8f); battleMap->setAnchorPoint(cocos2d::Vec2(0, 0)); battleMap->setPosition(cocos2d::Vec2(0, 0)); this->addChild(battleMap, 0, BattleMapTag); auto hudlayer = BattleMode::BattleHUDlayer::create(); this->addChild(hudlayer,1); this->m_ScaleOfScene = 1.0f; this->schedule([this](float dt) { SoldierAI::getInstance()->updateSoldierAI(); }, 0.7f, "SoldierAIUpdate"); this->schedule([this](float dt) { SoldierAI::getInstance()->updateBattleSoldier(); }, 0.2f, "BattleSoldierUpdate"); this->schedule([this](float dt) { SoldierAI::getInstance()->updateSoldierPosition(); }, 0.04f, "SoldierPositionupdate"); auto multiTouchListener = EventListenerTouchAllAtOnce::create(); multiTouchListener->onTouchesBegan = [&](std::vector<Touch*> touch, Event* event) { if (SoldierAI::getInstance()->getOurSoldierSelectedTotal() >= 1) { this->_continuousClickCount++; this->_currentClickTime = ExtensionsAlgorithm::getCurrentTime(); if (this->_currentClickTime -this->_prevClickTime < 10) { this->_continuousClickCount = 0; } if (this->_continuousClickCount >= 2 && this->_currentClickTime - this->_prevClickTime < 300 && touch.size()==1) { Vec2 battleMapAnchorPoint = BattleMap::getBattleMap()->getAnchorPoint(); Size battleMapSize = BattleMap::getBattleMap()->getBoundingBox().size; battleMapSize.width = battleMapSize.width*battleMapAnchorPoint.x; battleMapSize.height = battleMapSize.height*battleMapAnchorPoint.y; Vec2 touchOnBattleMap = touch[0]->getLocation() + (-BattleMap::getBattleMap()->getPosition()); touchOnBattleMap.x = touchOnBattleMap.x + battleMapSize.width; touchOnBattleMap.y = touchOnBattleMap.y + battleMapSize.height; SoldierAI::getInstance()->_structAICommand.AssignMoveCommand = true; AudioManagement::getInstance()->play("sound/assignPos.mp3", AudioManagement::AudioType::Sound, false); Sprite* targetFlag = (Sprite*)BattleMap::getBattleMap()->getChildByTag(BattleMap::TARGET_FLAG); targetFlag->setVisible(true); targetFlag->setPosition(touchOnBattleMap*(1 / BattleMap::getBattleMap()->getScale())); SoldierAI::getInstance()->updateSelectedLegionFlagTargetPosition(targetFlag->getPosition()); this->_continuousClickCount = 0; } this->_prevClickTime = this->_currentClickTime; } }; multiTouchListener->onTouchesMoved = [this](std::vector<Touch*> touches, Event* event) { BattleMap* battleMap = (BattleMap*)getChildByTag(BattleMapTag); if (touches.size() >= 2) { auto point1 = touches[0]->getLocation(); auto point2 = touches[1]->getLocation(); auto currDistance = point1.distance(point2); auto prevDistance = touches[0]->getPreviousLocation().distance(touches[1]->getPreviousLocation()); cocos2d::Vec2 touchWithOrginDef1 = point1 - mapCurrentPosition; cocos2d::Vec2 touchWithOrginDef2 = point2 - mapCurrentPosition; float touchWithOrginMidX = (touchWithOrginDef1.x + touchWithOrginDef2.x) / 2; float touchWithOrginMidY = (touchWithOrginDef1.y + touchWithOrginDef2.y) / 2; auto newAnchorX = touchWithOrginMidX / battleMap->getBoundingBox().size.width; auto newAnchorY = touchWithOrginMidY / battleMap->getBoundingBox().size.height; battleMap->setAnchorPoint(cocos2d::Vec2(newAnchorX, newAnchorY)); cocos2d::Vec2 mapNewPosition; mapNewPosition.x = (point2.x + point1.x) / 2; mapNewPosition.y = (point2.y + point1.y) / 2; if (currDistance > prevDistance) { m_ScaleOfScene += 0.01f; if (m_ScaleOfScene > 1.8f) m_ScaleOfScene = 1.8f; battleMap->setScale(m_ScaleOfScene); } else if (currDistance < prevDistance) { m_ScaleOfScene -= 0.01f; if (m_ScaleOfScene < 0.8f) m_ScaleOfScene = 0.8f; battleMap->setScale(m_ScaleOfScene); } Size battleMapOirginSize = battleMap->getBoundingBox().size; if (mapCurrentPosition.x > 0) { mapNewPosition.x -= mapCurrentPosition.x; } if (mapCurrentPosition.x < (-battleMapOirginSize.width) + visible.width) { mapNewPosition.x += (-battleMapOirginSize.width) + visible.width - mapCurrentPosition.x; } if (mapCurrentPosition.y > 0) { mapNewPosition.y -= mapCurrentPosition.y; } if (mapCurrentPosition.y < (-battleMapOirginSize.height) + visible.height) { mapNewPosition.y += (-battleMapOirginSize.height) + visible.height - mapCurrentPosition.y; } if (mapNewPosition != battleMap->getPosition()) { this->_continuousClickCount = 0; } battleMap->setPosition(mapNewPosition); mapCurrentPosition = cocos2d::Vec2(mapNewPosition.x, mapNewPosition.y)- cocos2d::Vec2(battleMapOirginSize.width * newAnchorX, battleMapOirginSize.height * newAnchorY); } else { Size battleMapOirginSize = battleMap->getBoundingBox().size; auto touch = touches[0]; auto currentPointToPreviousPointDistance = touch->getDelta(); auto pos = battleMap->getPosition() + currentPointToPreviousPointDistance; auto MaxMapPosX = battleMapOirginSize.width * battleMap->getAnchorPoint().x+origin.x; auto MaxMapPosY = battleMapOirginSize.height * battleMap->getAnchorPoint().y+origin.y; auto MinMapPosX = -battleMapOirginSize.width + visible.width + battleMapOirginSize.width * battleMap->getAnchorPoint().x+origin.x; auto MinMapPosY = -battleMapOirginSize.height + visible.height + battleMapOirginSize.height * battleMap->getAnchorPoint().y+origin.y; pos.x = MIN(pos.x, MaxMapPosX); pos.x = MAX(pos.x, MinMapPosX); pos.y = MIN(pos.y, MaxMapPosY); pos.y = MAX(pos.y, MinMapPosY); if (pos != battleMap->getPosition()) { this->_continuousClickCount = 0; } battleMap->setPosition(pos.x,pos.y); if (pos.x >= MaxMapPosX || pos.x <= MinMapPosX) { currentPointToPreviousPointDistance.x = 0; } if (pos.y >= MaxMapPosY || pos.y <= MinMapPosY) { currentPointToPreviousPointDistance.y = 0; } mapCurrentPosition += currentPointToPreviousPointDistance; } }; multiTouchListener->onTouchesEnded = [this](std::vector<Touch*> touches, Event* event) { }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(multiTouchListener, this); SoldierAI::getInstance()->generateOneLegion(1, 48, SoldierType::Musket, SoldierCamp::OurSoldier, battleMap, cocos2d::Vec2(250, 400)); SoldierAI::getInstance()->generateOneLegion(2, 48, SoldierType::ShieldSoldier, SoldierCamp::EnemySoldier, battleMap, cocos2d::Vec2(1500, 400)); SoldierAI::getInstance()->generateOneLegion(1, 48, SoldierType::Musket, SoldierCamp::OurSoldier, battleMap, cocos2d::Vec2(250, 200)); SoldierAI::getInstance()->generateOneLegion(2, 48, SoldierType::ShieldSoldier, SoldierCamp::EnemySoldier, battleMap, cocos2d::Vec2(1500, 200)); return true; } void BattleScene::pauseBattleMapListenerCallBack(Ref* ref) { auto battleMap = getChildByTag(BattleMapTag); Director::getInstance()->getEventDispatcher()->pauseEventListenersForTarget(battleMap, true); } void BattleScene::resumeBattleMapListenerCallBack(Ref* ref) { auto battleMap = getChildByTag(BattleMapTag); Director::getInstance()->getEventDispatcher()->resumeEventListenersForTarget(battleMap, true); } NS_BATTLEMODE_END
#include "scene/BattleMode/BattleScene.h" #include <sstream> #include "cocos-ext.h" #include "spine\spine-cocos2dx.h" #include "spine\spine.h" #include "Tools\AudioManagement.h" #include "UI\BattleMode\BattleHUDlayer.h" #include "Map\BattleMode\BattleMap.h" #include "Monster\BattleMode\BattleSoldierFactory.h" #include "Monster\BattleMode\SoldierAI.h" #include "Scene\DeveloperMenuScene.h" #include "ExtensionsAlgorithm.h" #include "DebugLayer.h" USING_NS_CC; USING_NS_CC_EXT; using namespace spine; using namespace cocos2d::experimental; NS_BATTLEMODE_BEGAN BattleScene* BattleScene::static_BattleScene = nullptr; cocos2d::Scene * BattleScene::createScene(int our, int enemy) { auto scene = Scene::createWithPhysics(); auto layer = BattleScene::create(our,enemy); scene->addChild(layer); return scene; } BattleScene* BattleScene::getBattleScene() { if (static_BattleScene == nullptr) return nullptr; else return static_BattleScene; } BattleScene::BattleScene() { this->_continuousClickCount=0; } BattleScene::~BattleScene() { NotificationCenter::getInstance()->removeAllObservers(this); AudioManagement::getInstance()->clearAudioManagement(); SoldierAI::getInstance()->clearData(); static_BattleScene = nullptr; } BattleScene* BattleScene::create(int our, int enemy) { BattleScene* _ptr = new (std::nothrow)BattleScene; if (_ptr && _ptr->init(our,enemy)) { _ptr->autorelease(); } else { CC_SAFE_DELETE(_ptr); } return _ptr; } bool BattleScene::init(int our, int enemy) { if (!Layer::init()) { return false; } static
irginSize.width * battleMap->getAnchorPoint().x+origin.x; auto MaxMapPosY = battleMapOirginSize.height * battleMap->getAnchorPoint().y+origin.y; auto MinMapPosX = -battleMapOirginSize.width + visible.width + battleMapOirginSize.width * battleMap->getAnchorPoint().x+origin.x; auto MinMapPosY = -battleMapOirginSize.height + visible.height + battleMapOirginSize.height * battleMap->getAnchorPoint().y+origin.y; pos.x = MIN(pos.x, MaxMapPosX); pos.x = MAX(pos.x, MinMapPosX); pos.y = MIN(pos.y, MaxMapPosY); pos.y = MAX(pos.y, MinMapPosY); if (pos != battleMap->getPosition()) { this->_continuousClickCount = 0; } battleMap->setPosition(pos.x,pos.y); if (pos.x >= MaxMapPosX || pos.x <= MinMapPosX) { currentPointToPreviousPointDistance.x = 0; } if (pos.y >= MaxMapPosY || pos.y <= MinMapPosY) { currentPointToPreviousPointDistance.y = 0; } mapCurrentPosition += currentPointToPreviousPointDistance; } }; multiTouchListener->onTouchesEnded = [this](std::vector<Touch*> touches, Event* event) { }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(multiTouchListener, this); SoldierAI::getInstance()->generateOneLegion(1, 48, SoldierType::Musket, SoldierCamp::OurSoldier, battleMap, cocos2d::Vec2(250, 400)); SoldierAI::getInstance()->generateOneLegion(2, 48, SoldierType::ShieldSoldier, SoldierCamp::EnemySoldier, battleMap, cocos2d::Vec2(1500, 400)); SoldierAI::getInstance()->generateOneLegion(1, 48, SoldierType::Musket, SoldierCamp::OurSoldier, battleMap, cocos2d::Vec2(250, 200)); SoldierAI::getInstance()->generateOneLegion(2, 48, SoldierType::ShieldSoldier, SoldierCamp::EnemySoldier, battleMap, cocos2d::Vec2(1500, 200)); return true; } void BattleScene::pauseBattleMapListenerCallBack(Ref* ref) { auto battleMap = getChildByTag(BattleMapTag); Director::getInstance()->getEventDispatcher()->pauseEventListenersForTarget(battleMap, true); } void BattleScene::resumeBattleMapListenerCallBack(Ref* ref) { auto battleMap = getChildByTag(BattleMapTag); Director::getInstance()->getEventDispatcher()->resumeEventListenersForTarget(battleMap, true); } NS_BATTLEMODE_END
_BattleScene = this; visible = Director::getInstance()->getVisibleSize(); origin = Director::getInstance()->getVisibleOrigin(); NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(BattleScene::pauseBattleMapListenerCallBack), "PauseBattleMapListenerCallBack", NULL); NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(BattleScene::resumeBattleMapListenerCallBack), "ResumeBattleMapListenerCallBack", NULL); AudioManagement::getInstance()->play("music/battleMusic3.mp3", AudioManagement::AudioType::Music, true); auto battleMap = BattleMap::create("map/BattleMode/battleMap.png"); battleMap->setScale(0.8f); battleMap->setAnchorPoint(cocos2d::Vec2(0, 0)); battleMap->setPosition(cocos2d::Vec2(0, 0)); this->addChild(battleMap, 0, BattleMapTag); auto hudlayer = BattleMode::BattleHUDlayer::create(); this->addChild(hudlayer,1); this->m_ScaleOfScene = 1.0f; this->schedule([this](float dt) { SoldierAI::getInstance()->updateSoldierAI(); }, 0.7f, "SoldierAIUpdate"); this->schedule([this](float dt) { SoldierAI::getInstance()->updateBattleSoldier(); }, 0.2f, "BattleSoldierUpdate"); this->schedule([this](float dt) { SoldierAI::getInstance()->updateSoldierPosition(); }, 0.04f, "SoldierPositionupdate"); auto multiTouchListener = EventListenerTouchAllAtOnce::create(); multiTouchListener->onTouchesBegan = [&](std::vector<Touch*> touch, Event* event) { if (SoldierAI::getInstance()->getOurSoldierSelectedTotal() >= 1) { this->_continuousClickCount++; this->_currentClickTime = ExtensionsAlgorithm::getCurrentTime(); if (this->_currentClickTime -this->_prevClickTime < 10) { this->_continuousClickCount = 0; } if (this->_continuousClickCount >= 2 && this->_currentClickTime - this->_prevClickTime < 300 && touch.size()==1) { Vec2 battleMapAnchorPoint = BattleMap::getBattleMap()->getAnchorPoint(); Size battleMapSize = BattleMap::getBattleMap()->getBoundingBox().size; battleMapSize.width = battleMapSize.width*battleMapAnchorPoint.x; battleMapSize.height = battleMapSize.height*battleMapAnchorPoint.y; Vec2 touchOnBattleMap = touch[0]->getLocation() + (-BattleMap::getBattleMap()->getPosition()); touchOnBattleMap.x = touchOnBattleMap.x + battleMapSize.width; touchOnBattleMap.y = touchOnBattleMap.y + battleMapSize.height; SoldierAI::getInstance()->_structAICommand.AssignMoveCommand = true; AudioManagement::getInstance()->play("sound/assignPos.mp3", AudioManagement::AudioType::Sound, false); Sprite* targetFlag = (Sprite*)BattleMap::getBattleMap()->getChildByTag(BattleMap::TARGET_FLAG); targetFlag->setVisible(true); targetFlag->setPosition(touchOnBattleMap*(1 / BattleMap::getBattleMap()->getScale())); SoldierAI::getInstance()->updateSelectedLegionFlagTargetPosition(targetFlag->getPosition()); this->_continuousClickCount = 0; } this->_prevClickTime = this->_currentClickTime; } }; multiTouchListener->onTouchesMoved = [this](std::vector<Touch*> touches, Event* event) { BattleMap* battleMap = (BattleMap*)getChildByTag(BattleMapTag); if (touches.size() >= 2) { auto point1 = touches[0]->getLocation(); auto point2 = touches[1]->getLocation(); auto currDistance = point1.distance(point2); auto prevDistance = touches[0]->getPreviousLocation().distance(touches[1]->getPreviousLocation()); cocos2d::Vec2 touchWithOrginDef1 = point1 - mapCurrentPosition; cocos2d::Vec2 touchWithOrginDef2 = point2 - mapCurrentPosition; float touchWithOrginMidX = (touchWithOrginDef1.x + touchWithOrginDef2.x) / 2; float touchWithOrginMidY = (touchWithOrginDef1.y + touchWithOrginDef2.y) / 2; auto newAnchorX = touchWithOrginMidX / battleMap->getBoundingBox().size.width; auto newAnchorY = touchWithOrginMidY / battleMap->getBoundingBox().size.height; battleMap->setAnchorPoint(cocos2d::Vec2(newAnchorX, newAnchorY)); cocos2d::Vec2 mapNewPosition; mapNewPosition.x = (point2.x + point1.x) / 2; mapNewPosition.y = (point2.y + point1.y) / 2; if (currDistance > prevDistance) { m_ScaleOfScene += 0.01f; if (m_ScaleOfScene > 1.8f) m_ScaleOfScene = 1.8f; battleMap->setScale(m_ScaleOfScene); } else if (currDistance < prevDistance) { m_ScaleOfScene -= 0.01f; if (m_ScaleOfScene < 0.8f) m_ScaleOfScene = 0.8f; battleMap->setScale(m_ScaleOfScene); } Size battleMapOirginSize = battleMap->getBoundingBox().size; if (mapCurrentPosition.x > 0) { mapNewPosition.x -= mapCurrentPosition.x; } if (mapCurrentPosition.x < (-battleMapOirginSize.width) + visible.width) { mapNewPosition.x += (-battleMapOirginSize.width) + visible.width - mapCurrentPosition.x; } if (mapCurrentPosition.y > 0) { mapNewPosition.y -= mapCurrentPosition.y; } if (mapCurrentPosition.y < (-battleMapOirginSize.height) + visible.height) { mapNewPosition.y += (-battleMapOirginSize.height) + visible.height - mapCurrentPosition.y; } if (mapNewPosition != battleMap->getPosition()) { this->_continuousClickCount = 0; } battleMap->setPosition(mapNewPosition); mapCurrentPosition = cocos2d::Vec2(mapNewPosition.x, mapNewPosition.y)- cocos2d::Vec2(battleMapOirginSize.width * newAnchorX, battleMapOirginSize.height * newAnchorY); } else { Size battleMapOirginSize = battleMap->getBoundingBox().size; auto touch = touches[0]; auto currentPointToPreviousPointDistance = touch->getDelta(); auto pos = battleMap->getPosition() + currentPointToPreviousPointDistance; auto MaxMapPosX = battleMapO
random
[ { "content": "#include \"cocos2d.h\"\n\n#include \"DefinitionBattleMode.h\"\n\n#include \"cocostudio\\CocoStudio.h\"\n\n#include \"ui/CocosGUI.h\"\n\nclass LoginScene : public cocos2d::Layer\n\n{\n\npublic:\n\n static cocos2d::Scene* createScene();\n\n virtual bool init();\n\n CREATE_FUNC(LoginScene);\...
C++
3rdParty/iresearch/utils/index-convert.cpp
sita1999/arangodb
6a4f462fa209010cd064f99e63d85ce1d432c500
#if defined(_MSC_VER) #pragma warning(disable: 4101) #pragma warning(disable: 4267) #endif #include <cmdline.h> #if defined(_MSC_VER) #pragma warning(default: 4267) #pragma warning(default: 4101) #endif #include "shared.hpp" #include "index-convert.hpp" #include "common.hpp" #include "formats/formats.hpp" #include "index/directory_reader.hpp" #include "index/index_writer.hpp" NS_LOCAL const std::string HELP = "help"; const std::string DIR_TYPE = "dir-type"; const std::string IN_DIR = "in"; const std::string OUT_DIR = "out"; const std::string OUT_FORMAT = "out-format"; const std::string FORMATS_DIR = "format-dir"; NS_END int convert( const std::string& in, const std::string& out, const std::string& dir_type, const std::string& format) { auto in_dir = create_directory(dir_type, in); if (!in_dir) { std::cerr << "Unable to create input directory directory of type '" << dir_type << "'" << std::endl; return 1; } auto out_dir = create_directory(dir_type, out); if (!out_dir) { std::cerr << "Unable to create input directory directory of type '" << dir_type << "'" << std::endl; return 1; } auto codec = irs::formats::get(format); if (!codec) { std::cerr << "Unable to load the specified format '" << dir_type << "'" << std::endl; return 1; } auto reader = irs::directory_reader::open(*in_dir); auto writer = irs::index_writer::make(*out_dir, codec, irs::OM_CREATE | irs::OM_APPEND); writer->import(*reader); writer->commit(); return 0; } int convert(const cmdline::parser& args) { if (!args.exist(IN_DIR) || !args.exist(OUT_DIR) || !args.exist(OUT_FORMAT)) { return 1; } const auto& in_path = args.get<std::string>(IN_DIR); if (in_path.empty()) { return 1; } const auto& out_path = args.get<std::string>(OUT_DIR); if (out_path.empty()) { return 1; } const auto& out_format = args.get<std::string>(OUT_FORMAT); const auto dir_type = args.exist(DIR_TYPE) ? args.get<std::string>(DIR_TYPE) : std::string("fs"); irs::formats::init(); if (args.exist(FORMATS_DIR)) { auto& formats_dir = args.get<std::string>(FORMATS_DIR); if (!formats_dir.empty()) { irs::formats::load_all(formats_dir); } } return convert(in_path, out_path, dir_type, out_format); } int convert(int argc, char* argv[]) { cmdline::parser cmdconv; cmdconv.add(HELP, '?', "Produce help message"); cmdconv.add<std::string>(IN_DIR, 0, "Path to input index directory", true); cmdconv.add<std::string>(OUT_DIR, 0, "Path to output index directory", true); cmdconv.add<std::string>(FORMATS_DIR, 0, "Plugin directory", false); cmdconv.add<std::string>(OUT_FORMAT, 0, "Output format", true); cmdconv.add<std::string>(DIR_TYPE, 0, "Directory type (fs|mmap)", false, std::string("fs")); cmdconv.parse(argc, argv); if (cmdconv.exist(HELP)) { std::cout << cmdconv.usage() << std::endl; return 0; } return convert(cmdconv); }
#if defined(_MSC_VER) #pragma warning(disable: 4101) #pragma warning(disable: 4267) #endif #include <cmdline.h> #if defined(_MSC_VER) #pragma warning(default: 4267) #pragma warning(default: 4101) #endif #include "shared.hpp" #include "index-convert.hpp" #include "common.hpp" #include "formats/formats.hpp" #include "index/directory_reader.hpp" #include "index/index_writer.hpp" NS_LOCAL const std::string HELP = "help"; const std::string DIR_TYPE = "dir-type"; const std::string IN_DIR = "in"; const std::string OUT_DIR = "out"; const std::string OUT_FORMAT = "out-format"; const std::string FORMATS_DIR = "format-dir";
int convert(const cmdline::parser& args) { if (!args.exist(IN_DIR) || !args.exist(OUT_DIR) || !args.exist(OUT_FORMAT)) { return 1; } const auto& in_path = args.get<std::string>(IN_DIR); if (in_path.empty()) { return 1; } const auto& out_path = args.get<std::string>(OUT_DIR); if (out_path.empty()) { return 1; } const auto& out_format = args.get<std::string>(OUT_FORMAT); const auto dir_type = args.exist(DIR_TYPE) ? args.get<std::string>(DIR_TYPE) : std::string("fs"); irs::formats::init(); if (args.exist(FORMATS_DIR)) { auto& formats_dir = args.get<std::string>(FORMATS_DIR); if (!formats_dir.empty()) { irs::formats::load_all(formats_dir); } } return convert(in_path, out_path, dir_type, out_format); } int convert(int argc, char* argv[]) { cmdline::parser cmdconv; cmdconv.add(HELP, '?', "Produce help message"); cmdconv.add<std::string>(IN_DIR, 0, "Path to input index directory", true); cmdconv.add<std::string>(OUT_DIR, 0, "Path to output index directory", true); cmdconv.add<std::string>(FORMATS_DIR, 0, "Plugin directory", false); cmdconv.add<std::string>(OUT_FORMAT, 0, "Output format", true); cmdconv.add<std::string>(DIR_TYPE, 0, "Directory type (fs|mmap)", false, std::string("fs")); cmdconv.parse(argc, argv); if (cmdconv.exist(HELP)) { std::cout << cmdconv.usage() << std::endl; return 0; } return convert(cmdconv); }
NS_END int convert( const std::string& in, const std::string& out, const std::string& dir_type, const std::string& format) { auto in_dir = create_directory(dir_type, in); if (!in_dir) { std::cerr << "Unable to create input directory directory of type '" << dir_type << "'" << std::endl; return 1; } auto out_dir = create_directory(dir_type, out); if (!out_dir) { std::cerr << "Unable to create input directory directory of type '" << dir_type << "'" << std::endl; return 1; } auto codec = irs::formats::get(format); if (!codec) { std::cerr << "Unable to load the specified format '" << dir_type << "'" << std::endl; return 1; } auto reader = irs::directory_reader::open(*in_dir); auto writer = irs::index_writer::make(*out_dir, codec, irs::OM_CREATE | irs::OM_APPEND); writer->import(*reader); writer->commit(); return 0; }
function_block-full_function
[]
C++
asw/xy_to_angle.cpp
aswdevz/asw
ba483a71742fefbe6aa886e0e6acf56f22f375fe
#include "stdafx.h" #include "asw.h" #include "xy_to_angle.h" #ifdef USE_ORIGINAL_DEADZONE_FUNCTION bool in_deadzone(short x, short y, int deadzone) { int x_percent = (int)(abs(x) / 327.67); int y_percent = (int)(abs(y) / 327.67); if ( sqrt(pow(x_percent, 2) + pow(y_percent, 2) ) <= deadzone) { return TRUE; } return FALSE; } #else bool in_deadzone(short x, short y, int deadzone) { double x_percent = abs(x) / 327.67; double y_percent = abs(y) / 327.67; if ( sqrt(pow(x_percent, 2) + pow(y_percent, 2) ) <= deadzone) { return TRUE; } return FALSE; } #endif double calculate_angle_from_x_y(short x, short y) { if (x == 0) { if (y >= 0) return 0.0; else return 180.0; } if (y == 0) { if (x >= 0) return 90.0; else return -90.0; } if (x > 0) { if (y > 0) { return (atan((double)x / (double)y) * 180.0 / M_PI); } if (y < 0) { return ((atan(-(double)y / (double)x) * 180.0 / M_PI) + 90.0); } } if (x < 0) { if (y > 0) { return ((-atan(-(double)x / (double)y)) * 180.0 / M_PI); } if (y < 0) { return ((-atan(-(double)y / -(double)x) * 180.0 / M_PI) - 90.0); } } return 0.0; } long angle_to_vjoy(double angle, int virtual_wheel_max_angle) { double max_angle = ((double)virtual_wheel_max_angle) / 2; double min_angle = -((double)virtual_wheel_max_angle) / 2; if (angle > max_angle) angle = max_angle; if (angle < min_angle) angle = min_angle; long finalvalue = (long)round(((angle + max_angle)*(32767.0 / ((double)virtual_wheel_max_angle)) + 1)); return finalvalue; } int check_if_rotated_past_180(double current, double last, int* rotations) { if (((current >= -180.0) && (current < 0.0)) && (current < (last - 180.0))) { *rotations = *rotations + 1; return 1; } if (((current <= 180.0) && (current > 0.0)) && (current > (last + 180.0))) { *rotations = *rotations - 1; return -1; } return 0; } int clip_angle_and_rotations(int virtual_wheel_max_angle, double* angle_in, int* rotations) { double right_lock = ((double)virtual_wheel_max_angle) / 2; double left_lock = -(((double)virtual_wheel_max_angle) / 2); int max_rotations = (int)((right_lock + 180.0) / 360.0); int min_rotations = (int)((left_lock - 180.0) / 360.0); double max_angle = right_lock - (360.0 * max_rotations); double min_angle = left_lock + (360.0 * (-min_rotations)); double angle = ((*angle_in) + (*rotations)*360.0); if (angle > ((double)virtual_wheel_max_angle) / 2) { angle = ((double)virtual_wheel_max_angle) / 2; *angle_in = max_angle; *rotations = max_rotations; } if (angle < (-((double)virtual_wheel_max_angle) / 2)) { angle = -(((double)virtual_wheel_max_angle) / 2); *angle_in = min_angle; *rotations = min_rotations; } return 0; } double calculate_real_angle(double current, int virtual_wheel_max_angle, int* rotations, int* steering_lock) { *steering_lock = 0; double angle = (current + (*rotations)*360.0); if (angle > ((double)virtual_wheel_max_angle) / 2) { angle = ((double)virtual_wheel_max_angle) / 2; *steering_lock = 1; } if (angle < (-((double)virtual_wheel_max_angle) / 2)) { angle = -(((double)virtual_wheel_max_angle) / 2); *steering_lock = -1; } return angle; } LONG invert_vjoy_axis_value(LONG value, int invert_axis) { if (invert_axis == 1) return 32769 - value; else return value; }
#include "stdafx.h" #include "asw.h" #include "xy_to_angle.h" #ifdef USE_ORIGINAL_DEADZONE_FUNCTION bool in_deadzone(short x, short y, int deadzone) { int x_percent = (int)(abs(x) / 327.67); int y_percent = (int)(abs(y) / 327.67); if ( sqrt(pow(x_percent, 2) + pow(y_percent, 2) ) <= deadzone) { return TRUE; } return FALSE; } #else bool in_deadzone(short x, short y, int deadzone) { double x_percent = abs(x) / 327.67; double y_percent = abs(y) / 327.67; if ( sqrt(pow(x_percent, 2) + pow(y_percent, 2) ) <= deadzone) { return TRUE; } return FALSE; } #endif double calculate_angle_from_x_y(short x, short y) { if (x == 0) { if (y >= 0) return 0.0; else return 180.0; } if (y == 0) { if (x >
uble)virtual_wheel_max_angle)) + 1)); return finalvalue; } int check_if_rotated_past_180(double current, double last, int* rotations) { if (((current >= -180.0) && (current < 0.0)) && (current < (last - 180.0))) { *rotations = *rotations + 1; return 1; } if (((current <= 180.0) && (current > 0.0)) && (current > (last + 180.0))) { *rotations = *rotations - 1; return -1; } return 0; } int clip_angle_and_rotations(int virtual_wheel_max_angle, double* angle_in, int* rotations) { double right_lock = ((double)virtual_wheel_max_angle) / 2; double left_lock = -(((double)virtual_wheel_max_angle) / 2); int max_rotations = (int)((right_lock + 180.0) / 360.0); int min_rotations = (int)((left_lock - 180.0) / 360.0); double max_angle = right_lock - (360.0 * max_rotations); double min_angle = left_lock + (360.0 * (-min_rotations)); double angle = ((*angle_in) + (*rotations)*360.0); if (angle > ((double)virtual_wheel_max_angle) / 2) { angle = ((double)virtual_wheel_max_angle) / 2; *angle_in = max_angle; *rotations = max_rotations; } if (angle < (-((double)virtual_wheel_max_angle) / 2)) { angle = -(((double)virtual_wheel_max_angle) / 2); *angle_in = min_angle; *rotations = min_rotations; } return 0; } double calculate_real_angle(double current, int virtual_wheel_max_angle, int* rotations, int* steering_lock) { *steering_lock = 0; double angle = (current + (*rotations)*360.0); if (angle > ((double)virtual_wheel_max_angle) / 2) { angle = ((double)virtual_wheel_max_angle) / 2; *steering_lock = 1; } if (angle < (-((double)virtual_wheel_max_angle) / 2)) { angle = -(((double)virtual_wheel_max_angle) / 2); *steering_lock = -1; } return angle; } LONG invert_vjoy_axis_value(LONG value, int invert_axis) { if (invert_axis == 1) return 32769 - value; else return value; }
= 0) return 90.0; else return -90.0; } if (x > 0) { if (y > 0) { return (atan((double)x / (double)y) * 180.0 / M_PI); } if (y < 0) { return ((atan(-(double)y / (double)x) * 180.0 / M_PI) + 90.0); } } if (x < 0) { if (y > 0) { return ((-atan(-(double)x / (double)y)) * 180.0 / M_PI); } if (y < 0) { return ((-atan(-(double)y / -(double)x) * 180.0 / M_PI) - 90.0); } } return 0.0; } long angle_to_vjoy(double angle, int virtual_wheel_max_angle) { double max_angle = ((double)virtual_wheel_max_angle) / 2; double min_angle = -((double)virtual_wheel_max_angle) / 2; if (angle > max_angle) angle = max_angle; if (angle < min_angle) angle = min_angle; long finalvalue = (long)round(((angle + max_angle)*(32767.0 / ((do
random
[ { "content": "\tint* thumbstick_deadzone;\n", "file_path": "asw/asw.h", "rank": 0, "score": 26571.359982119866 }, { "content": "bool in_deadzone(short x, short y, int deadzone);\n", "file_path": "asw/xy_to_angle.h", "rank": 1, "score": 26571.359982119866 }, { "content": "...
C++
thread_lib/main.cpp
fu4ck/linux_env_dev
8076ca56a2ec907dec0c952e6ed27b6e644c5ae1
#include <iostream> #include <unistd.h> #include <signal.h> #include <sys/types.h> #include <sys/epoll.h> #include <fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <assert.h> #include <sys/stat.h> #include <string> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <stdarg.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include "threadpool.h" #include "http_conn.h" #define MAX_FD 65535 #define MAX_EVENT_NUMBER 10000 extern int addfd(int epollfd, int fd, bool one_shot); extern int removefd(int epollfd, int fd); void addsig(int sig, void(handler)(int), bool restart=true) { struct sigaction sa; memset(&sa, '\0', sizeof(sa)); sa.sa_handler = handler; if(restart){ sa.sa_flags |= SA_RESTART; } sigfillset(&sa.sa_mask); assert(sigaction(sig, &sa, NULL)!=-1); } void show_error(int connfd, const char* info){ printf("%s", info); send(connfd, info, strlen(info), 0); close(connfd); } int main(int argc, char* argv[]) { if (argc<=2){ return 1; } const char* ip = argv[1]; int port = atoi(argv[2]); addsig(SIGPIPE, SIG_IGN); threadpool<http_conn>* pool = NULL; try{ pool = new threadpool<http_conn>; }catch (...){ return 1; } http_conn* users = new http_conn[MAX_FD]; assert(users); int user_count = 0; int listenfd = socket(PF_INET, SOCK_STREAM, 0); assert(listenfd >= 0); struct linger tmp = {1,0}; setsockopt(listenfd, SOL_SOCKET, SO_LINGER, &tmp, sizeof(tmp)); int ret =0 ; struct sockaddr_in address; bzero(&address,sizeof(address)); address.sin_family=AF_INET; inet_pton(AF_INET, ip, &address.sin_addr); address.sin_port = htons(port); ret = bind(listenfd, (struct sockaddr*)&address, sizeof(address)); assert(ret>=0); ret = listen(listenfd, 5); assert(ret>=0); epoll_event events[MAX_EVENT_NUMBER]; int epollfd = epoll_create(5); assert(epollfd!=-1); addfd(epollfd, listenfd, false); http_conn::m_epollfd = epollfd; while(true){ int number = epoll_wait(epollfd, events, MAX_EVENT_NUMBER, -1); if((number<0)&&(errno!=EINTR)){ break; } for(int i=0;i<number;i++){ int sockfd = events[i].data.fd; if(sockfd==listenfd){ struct sockaddr_in client_address; socklen_t client_addrlength = sizeof(client_address); int connfd = accept(listenfd, (struct sockaddr*)&client_address, &client_addrlength); if (connfd <0){ continue; } if(http_conn::m_user_count>=MAX_FD){ continue; } users[connfd].init(connfd, client_address); }else if(events[i].events&(EPOLLRDHUP|EPOLLHUP|EPOLLERR)){ users[sockfd].close_conn(); }else if(events[i].events&EPOLLIN){ if(users[sockfd].read()){ pool->append(users+sockfd); }else{ users[sockfd].close_conn(); } }else if(events[i].events&EPOLLOUT){ if(!users[sockfd].write()){ users[sockfd].close_conn(); } }else{ } } } close(epollfd); close(listenfd); delete []users; delete pool; return 0; }
#include <iostream> #include <unistd.h> #include <signal.h> #include <sys/types.h> #include <sys/epoll.h> #include <fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <assert.h> #include <sys/stat.h> #include <string> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <stdarg.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include "threadpool.h" #include "http_conn.h" #define MAX_FD 65535 #define MAX_EVENT_NUMBER 10000 extern int addfd(int epollfd, int fd, bool one_shot); extern int removefd(int epollfd, int fd); void addsig(int sig, void(handler)(int), bool restart=true) { struct sigaction sa; memset(&sa, '\0', sizeof(sa)); sa.sa_handler = handler; if(restart){ sa.sa_flags |= SA_RESTART; } sigfillset(&sa.sa_mask); assert(sigaction(sig, &sa, NULL)!=-1); } void show_error(int connfd, const char* info){ printf("%s", info); send(connfd, info, strlen(info), 0); close(connfd); } int main(int argc, char* argv[]) { if (argc<=2){ return 1; } const char* ip = argv[1]; int port = atoi(argv[2]); addsig(SIGPIPE, SIG_IGN); threadpool<http_conn>* pool = NULL; try{ pool = new threadpool<http_conn>; }catch (...){ return 1; } http_conn* users = new http_conn[MAX_FD]; assert(users); int user_count = 0; int listenfd = socket(PF_INET, SOCK_STREAM, 0); assert(listenfd >= 0); struct linger tmp = {1,0}; setsockopt(listenfd, SOL_SOCKET, SO_LINGER, &tmp, sizeof(tmp)); int ret =0 ; struct sockaddr_in address; bzero(&address,sizeof(address)); address.sin_family=AF_INET; inet_pton(AF_INET, ip, &address.sin_addr); address.sin_port = htons(port); ret = bind(listenfd, (struct sockaddr*)&address, sizeof(address)); assert(ret>=0); ret = listen(listenfd, 5); assert(ret>=0); epoll_event events[MAX_EVENT_NUMBER]; int epollfd = epoll_create(5); assert(epollfd!=-1); addfd(epollfd, listenfd, false); http_conn::m_epollfd = epollfd; while(true){ int number = epoll_wait(epollfd, events, MAX_EVENT_NUMBER, -1); if((number<0)&&(errno!=EINTR)){ break; } for(int i=0;i<number;i++){ int sockfd = events[i].data.fd; if(sockfd==listenfd){ struct sockaddr_in client_address; socklen_t client_addrlength = sizeof(client_address); int connfd = accept(listenfd, (struct sockaddr*)&client_address, &client_addrlength); if (connfd <0){ continue; } if(http_conn::m_user_count>=MAX_FD){ continue; } users[connfd].init(connfd, client_address); }else if(events[i].events&(EPOLLRDHUP|EPOLLHUP|EPOLLERR)){ users[sockfd].close_conn(); }else if(events[i].events&EPOLLIN){ if(users[sockfd].read()){ pool->append(users+sockfd); }else{ users[sockfd].close_conn(); } }
else if(events[i].events&EPOLLOUT){ if(!users[sockfd].write()){ users[sockfd].close_conn(); } }else{ } } } close(epollfd); close(listenfd); delete []users; delete pool; return 0; }
function_block-function_prefix_line
[ { "content": "char const* info_compiler = \"INFO\" \":\" \"compiler[\" COMPILER_ID \"]\";\n", "file_path": "thread_lib/cmake-build-debug/CMakeFiles/3.20.2/CompilerIdC/CMakeCCompilerId.c", "rank": 0, "score": 15856.93664216525 }, { "content": "char const* info_platform = \"INFO\" \":\" \"plat...
C++
cpp_analysis/bin/check_sizes.cpp
shahrukhqasim/HGCalML
2808564b31c89d9b7eb882734f6aebc6f35e94f3
#include "TString.h" #include "TFile.h" #include "TTree.h" #include <vector> #include <iostream> #include "TH1D.h" #include "TCanvas.h" void mergeOF(TH1D* h){ double lastb = h->GetBinContent(h->GetNbinsX()); h->SetBinContent(h->GetNbinsX(), lastb+h->GetBinContent(h->GetNbinsX()+1)); } int main(int argc, char* argv[]){ if(argc<2) return -1; TString infile = argv[1]; TFile f(infile, "READ"); TTree * tree = (TTree*) f.Get("Delphes"); if(!tree || tree->IsZombie()){ std::cerr << "tree has a problem" << std::endl; return -1; } std::vector<std::vector<float> > * rh_feat =0, * rh_truth = 0, *lc_feat = 0, * lc_truth=0; tree->SetBranchAddress("rechit_features",&rh_feat); tree->SetBranchAddress("rechit_simcluster_fractions",&rh_truth); tree->SetBranchAddress("layercluster_features",&lc_feat); tree->SetBranchAddress("layercluster_simcluster_fractions",&lc_truth); if(tree->GetEntries()<1){ std::cerr << "tree has 0 entries" <<std::endl; return -2; } tree->GetEntry(0); if(rh_feat->size()<1 || lc_feat->size()<1){ std::cerr << "first entry has zero rechits or layer cluster" <<std::endl; return -3; } std::cout << "rechit_features: " << rh_feat->at(0).size() << std::endl; std::cout << "layercluster_features: " << lc_feat->at(0).size() << std::endl; std::cout << "\ncomputing average/max rechits" << std::endl; TH1D nrechits("nrechits","nrechits",20,1000,10000); TH1D nlayerclusters("nlayerclusters","nlayerclusters",20,100,2000); TH1D rechit_energy("rechit_energy","rechit_energy",20,0,0.05); TH1D rechit_truthenergy("rechit_truthenergy","rechit_truthenergy",20,0,0.05); int max_nrechits=0, max_nlayerclusters=0, max_simclusters=0; float avg_nrechits=0, avg_nlayerclusters=0; const int nentries = tree->GetEntries(); for(int event=0;event<nentries;event++){ tree->GetEntry(event); const int nrh = rh_feat->size(); const int nlc = lc_feat->size(); int nsc = 0; if(rh_truth->size()>0) nsc=rh_truth->at(0).size(); if(max_nrechits<nrh) max_nrechits=nrh; if(max_nlayerclusters<nlc) max_nlayerclusters=nlc; if(max_simclusters<nsc) max_simclusters=nsc; avg_nrechits+=nrh; avg_nlayerclusters+=nlc; nrechits.Fill(nrh); nlayerclusters.Fill(nlc); for(size_t i=0;i<rh_feat->size();i++){ rechit_energy.Fill(rh_feat->at(i).at(0)); float truthsum = 0; for(size_t j=0;j<rh_truth->at(i).size();j++){ truthsum+=rh_truth->at(i).at(j); } if(truthsum>0) rechit_truthenergy.Fill(truthsum*rh_feat->at(i).at(0)); if(truthsum>0 && fabs(truthsum-1.)>0.0001) std::cout << "weird truthsum" << truthsum << std::endl; } } avg_nrechits/=(float)nentries; avg_nlayerclusters/=(float)nentries; std::cout << "max nrechits: " << max_nrechits << std::endl; std::cout << "max nlayerclusters: " << max_nlayerclusters << std::endl; std::cout << "max nsimclusters: " << max_simclusters << std::endl; std::cout << "average nrechits: " << avg_nrechits << std::endl; std::cout << "average nlayerclusters: " << avg_nlayerclusters << std::endl; mergeOF(&nrechits); mergeOF(&nlayerclusters); TCanvas cv; nrechits.Draw(); cv.Print("nrechits.pdf"); nlayerclusters.Draw(); cv.Print("nlayerclusters.pdf"); rechit_energy.Draw(); cv.Print("rechit_energy.pdf"); rechit_truthenergy.SetLineColor(kRed); rechit_truthenergy.Draw("same"); cv.Print("rechit_truthenergy.pdf"); return 0; }
#include "TString.h" #include "TFile.h" #include "TTree.h" #include <vector> #include <iostream> #include "TH1D.h" #include "TCanvas.h" void mergeOF(TH1D* h){ double lastb = h->GetBinContent(h->GetNbinsX()); h->SetBinContent(h->GetNbinsX(), lastb+h->GetBinContent(h->GetNbinsX()+1)); }
int main(int argc, char* argv[]){ if(argc<2) return -1; TString infile = argv[1]; TFile f(infile, "READ"); TTree * tree = (TTree*) f.Get("Delphes"); if(!tree || tree->IsZombie()){ std::cerr << "tree has a problem" << std::endl; return -1; } std::vector<std::vector<float> > * rh_feat =0, * rh_truth = 0, *lc_feat = 0, * lc_truth=0; tree->SetBranchAddress("rechit_features",&rh_feat); tree->SetBranchAddress("rechit_simcluster_fractions",&rh_truth); tree->SetBranchAddress("layercluster_features",&lc_feat); tree->SetBranchAddress("layercluster_simcluster_fractions",&lc_truth); if(tree->GetEntries()<1){ std::cerr << "tree has 0 entries" <<std::endl; return -2; } tree->GetEntry(0); if(rh_feat->size()<1 || lc_feat->size()<1){ std::cerr << "first entry has zero rechits or layer cluster" <<std::endl; return -3; } std::cout << "rechit_features: " << rh_feat->at(0).size() << std::endl; std::cout << "layercluster_features: " << lc_feat->at(0).size() << std::endl; std::cout << "\ncomputing average/max rechits" << std::endl; TH1D nrechits("nrechits","nrechits",20,1000,10000); TH1D nlayerclusters("nlayerclusters","nlayerclusters",20,100,2000); TH1D rechit_energy("rechit_energy","rechit_energy",20,0,0.05); TH1D rechit_truthenergy("rechit_truthenergy","rechit_truthenergy",20,0,0.05); int max_nrechits=0, max_nlayerclusters=0, max_simclusters=0; float avg_nrechits=0, avg_nlayerclusters=0; const int nentries = tree->GetEntries(); for(int event=0;event<nentries;event++){ tree->GetEntry(event); const int nrh = rh_feat->size(); const int nlc = lc_feat->size(); int nsc = 0; if(rh_truth->size()>0) nsc=rh_truth->at(0).size(); if(max_nrechits<nrh) max_nrechits=nrh; if(max_nlayerclusters<nlc) max_nlayerclusters=nlc; if(max_simclusters<nsc) max_simclusters=nsc; avg_nrechits+=nrh; avg_nlayerclusters+=nlc; nrechits.Fill(nrh); nlayerclusters.Fill(nlc); for(size_t i=0;i<rh_feat->size();i++){ rechit_energy.Fill(rh_feat->at(i).at(0)); float truthsum = 0; for(size_t j=0;j<rh_truth->at(i).size();j++){ truthsum+=rh_truth->at(i).at(j); } if(truthsum>0) rechit_truthenergy.Fill(truthsum*rh_feat->at(i).at(0)); if(truthsum>0 && fabs(truthsum-1.)>0.0001) std::cout << "weird truthsum" << truthsum << std::endl; } } avg_nrechits/=(float)nentries; avg_nlayerclusters/=(float)nentries; std::cout << "max nrechits: " << max_nrechits << std::endl; std::cout << "max nlayerclusters: " << max_nlayerclusters << std::endl; std::cout << "max nsimclusters: " << max_simclusters << std::endl; std::cout << "average nrechits: " << avg_nrechits << std::endl; std::cout << "average nlayerclusters: " << avg_nlayerclusters << std::endl; mergeOF(&nrechits); mergeOF(&nlayerclusters); TCanvas cv; nrechits.Draw(); cv.Print("nrechits.pdf"); nlayerclusters.Draw(); cv.Print("nlayerclusters.pdf"); rechit_energy.Draw(); cv.Print("rechit_energy.pdf"); rechit_truthenergy.SetLineColor(kRed); rechit_truthenergy.Draw("same"); cv.Print("rechit_truthenergy.pdf"); return 0; }
function_block-full_function
[ { "content": "//#define GOOGLE_CUDA 1\n\n\n\n#if GOOGLE_CUDA\n\n#define EIGEN_USE_GPU\n\n#define HANDLE_ERROR( err ) ( tensorflow::functor::HandleError( err, __FILE__, __LINE__ ) )\n\n\n\n#include \"slicing_knn_kernel.h\"\n\n#include \"helpers.h\"\n\n#include \"tensorflow/core/util/gpu_kernel_helper.h\"\n\n#inc...
C++
src/platform/threadmgr/ThreadManager.cpp
shorton3/dashingplatforms
f461c967827b92c8bcf872c365afa64e56871aba
#include <iostream> #include <sstream> #include <ace/Thread.h> #include "ThreadManager.h" #include "platform/logger/Logger.h" #include "platform/common/Defines.h" #define THREAD_FUNC_RETRY 5 #define THREAD_MONITOR_PERIOD 2 #define MONITOR_GROUP_ID 17239115 ThreadManager::ThreadsWaitingForRestartMap ThreadManager::restartMap_; ACE_Thread_Mutex ThreadManager::restartMapMutex_; bool ThreadManager::isInitialized_ = false; ACE_thread_t ThreadManager::createThread(ACE_THR_FUNC function, void *functionArgs, const char* threadName, bool shouldRestart, long threadFlags, long priority, int threadGroup, size_t stackSize) { ACE_thread_t threadId = 0; if (!isInitialized_) { isInitialized_ = true; ThreadManager::createThread((ACE_THR_FUNC)ThreadManager::startThreadMonitor, 0, "ThreadManagerMonitor", true, THR_NEW_LWP | THR_JOINABLE | THR_SCHED_DEFAULT, ACE_DEFAULT_THREAD_PRIORITY, MONITOR_GROUP_ID); } ostringstream ostr; ostr << "Received request to create thread (" << threadName << ")" << ends; STRACELOG(DEVELOPERLOG, THREADLOG, ostr.str().c_str()); ThreadParameters* threadParameters = new ThreadParameters(threadName, shouldRestart, function, functionArgs, threadFlags, priority, threadGroup, stackSize); if (ACE_Thread_Manager::instance()->spawn( (ACE_THR_FUNC)ThreadManager::runThread, (void*)threadParameters, threadFlags, &threadId, 0 , priority, threadGroup, 0 , stackSize) == ERROR) { ostringstream ostr; ostr << "Unable to spawn thread (" << threadName << ")" << ends; STRACELOG(ERRORLOG, THREADLOG, ostr.str().c_str()); return 0; } else { ostringstream ostr; ostr << "Successfully spawned thread (" << threadName << ") returning Thread Id (" << threadId << ")" << ends; STRACELOG(DEBUGLOG, THREADLOG, ostr.str().c_str()); } return threadId; } ACE_thread_t* ThreadManager::createThreadPool(size_t Nthreads, ACE_THR_FUNC function, void *functionArgs, const char* threadName, bool shouldRestart, long threadFlags, long priority, int threadGroup, size_t stackSize) { ACE_thread_t* threadIds = new ACE_thread_t[Nthreads]; size_t stackSizes[Nthreads]; memset(stackSizes, stackSize, Nthreads); if (!isInitialized_) { isInitialized_ = true; ThreadManager::createThread((ACE_THR_FUNC)ThreadManager::startThreadMonitor, 0, "ThreadManagerMonitor", true, THR_NEW_LWP | THR_JOINABLE | THR_SCHED_DEFAULT, ACE_DEFAULT_THREAD_PRIORITY, MONITOR_GROUP_ID); } ostringstream ostr; ostr << "Received request to create thread pool (" << threadName << ") with (" << Nthreads << ") threads" << ends; STRACELOG(DEVELOPERLOG, THREADLOG, ostr.str().c_str()); ThreadParameters* threadParameters = new ThreadParameters(threadName, shouldRestart, function, functionArgs, threadFlags, priority, threadGroup, stackSize); if (ACE_Thread_Manager::instance()->spawn_n( threadIds, Nthreads, (ACE_THR_FUNC)ThreadManager::runThread, (void*)threadParameters, threadFlags, priority, threadGroup, 0 , stackSizes, 0 ) == ERROR) { ostringstream ostr; ostr << "Unable to spawn thread pool (" << threadName << ")" << ends; STRACELOG(ERRORLOG, THREADLOG, ostr.str().c_str()); return 0; } else { ostringstream ostr; ostr << "Successfully spawned thread pool (" << threadName << ")" << ends; STRACELOG(DEBUGLOG, THREADLOG, ostr.str().c_str()); } return threadIds; } void ThreadManager::startThreadMonitor() { while (1) { ThreadManager::restartMapMutex_.acquire(); if (!ThreadManager::restartMap_.empty()) { ThreadsWaitingForRestartMap::iterator restartMapIterator; ThreadsWaitingForRestartMap::iterator endIterator; restartMapIterator = ThreadManager::restartMap_.begin(); endIterator = ThreadManager::restartMap_.end(); while (restartMapIterator != endIterator) { ThreadParameters* threadParms = (ThreadParameters*)restartMapIterator->second; ACE_thread_t newThreadId = ThreadManager::createThread(threadParms->function_, threadParms->functionArgs_, threadParms->threadName_.c_str(), threadParms->shouldRestart_, threadParms->threadFlags_, threadParms->priority_, threadParms->threadGroup_, threadParms->stackSize_); ostringstream ostr; ostr << "Thread (" << threadParms->threadName_ << ") restarted with new Thread Id (" << newThreadId << ")" << ends; STRACELOG(DEBUGLOG, THREADLOG, ostr.str().c_str()); ThreadManager::restartMap_.erase(restartMapIterator->first); restartMapIterator++; } } ThreadManager::restartMapMutex_.release(); sleep(THREAD_MONITOR_PERIOD); } } ThreadManager::~ThreadManager() { if ((threadParameters_) && (!threadParameters_->shouldRestart_)) { delete threadParameters_; } } void ThreadManager::apply(void) { if (threadParameters_->shouldRestart_) { ostringstream ostr; ostr << "Thread exit handler caught thread death for thread (" << threadParameters_->threadName_ << ") with Id (" << threadId_ << "). Attempting restart." << ends; STRACELOG(ERRORLOG, THREADLOG, ostr.str().c_str()); typedef pair<unsigned long, ThreadParameters*> ThreadRestartPair; ThreadRestartPair threadRestartPair(threadId_, threadParameters_); ThreadManager::restartMapMutex_.acquire(); pair<map<unsigned long, ThreadParameters*>::iterator, bool> pairIterator = ThreadManager::restartMap_.insert(threadRestartPair); if (!pairIterator.second) { ostringstream ostr; ostr << "Error queuing thread (" << threadParameters_->threadName_ << ") with Id (" << threadId_ << ") for restart. Thread will not be restarted." << ends; STRACELOG(ERRORLOG, THREADLOG, ostr.str().c_str()); } ThreadManager::restartMapMutex_.release(); } else { ostringstream ostr; ostr << "Thread exit handler caught thread death for (" << threadParameters_->threadName_ << ") with Id (" << threadId_ << ")" << ends; STRACELOG(WARNINGLOG, THREADLOG, ostr.str().c_str()); } } ThreadManager::ThreadManager(ThreadParameters& threadParameters) : threadParameters_(&threadParameters) { threadId_ = ACE_Thread::self(); } ThreadManager* ThreadManager::getInstance(ThreadParameters& threadParameters) { return new ThreadManager(threadParameters); } ACE_THR_FUNC_RETURN ThreadManager::runThread(ThreadParameters& threadParameters) { ACE_Thread_Manager::instance()->at_exit(ThreadManager::getInstance(threadParameters)); ostringstream ostr1; ostr1 << "Attached thread exit handler to thread (" << threadParameters.threadName_ << ") with Id (" << ACE_Thread::self() << ")" << ends; STRACELOG(DEVELOPERLOG, THREADLOG, ostr1.str().c_str()); try { (*threadParameters.function_) (threadParameters.functionArgs_); } catch (exception exc) { ostringstream ostr; ostr << "Caught Application Level Exception - " << exc.what() << ends; STRACELOG(ERRORLOG, THREADLOG, ostr.str().c_str()); } if (threadParameters.shouldRestart_) { int counter = 0; while (counter < THREAD_FUNC_RETRY) { ostringstream ostr2; ostr2 << "Thread function (" << threadParameters.threadName_ << ") with Id (" << ACE_Thread::self() << ") returned. Calling it again (count=" << counter << ")." << ends; STRACELOG(ERRORLOG, THREADLOG, ostr2.str().c_str()); try { (*threadParameters.function_) (threadParameters.functionArgs_); } catch (exception exc) { ostringstream ostr; ostr << "Caught Application Level Exception - " << exc.what() << ends; STRACELOG(ERRORLOG, THREADLOG, ostr.str().c_str()); } counter++; } ostringstream ostr2; ostr2 << "Thread function (" << threadParameters.threadName_ << ") with Id (" << ACE_Thread::self() << ") returned " << counter << " times. Giving up to let the thread get restarted" << ends; STRACELOG(ERRORLOG, THREADLOG, ostr2.str().c_str()); } else { ostringstream ostr2; ostr2 << "Thread function (" << threadParameters.threadName_ << ") with Id (" << ACE_Thread::self() << ") returned." << ends; STRACELOG(WARNINGLOG, THREADLOG, ostr2.str().c_str()); } return 0; }
#include <iostream> #include <sstream> #include <ace/Thread.h> #include "ThreadManager.h" #include "platform/logger/Logger.h" #include "platform/common/Defines.h" #define THREAD_FUNC_RETRY 5 #define THREAD_MONITOR_PERIOD 2 #define MONITOR_GROUP_ID 17239115 ThreadManager::ThreadsWaitingForRestartMap ThreadManager::restartMap_; ACE_Thread_Mutex ThreadManager::restartMapMutex_; bool ThreadManager::isInitialized_ = false; ACE_thread_t ThreadManager::createThread(ACE_THR_FUNC function, void *functionArgs, const char* threadName, bool shouldRestart, long threadFlags, long priority, int threadGroup, size_t stackSize) { ACE_thread_t threadId = 0; if (!isInitialized_) { isInitialized_ = true; ThreadManager::createThread((ACE_THR_FUNC)ThreadManager::startThreadMonitor, 0, "ThreadManagerMonitor", true, THR_NEW_LWP | THR_JOINABLE | THR_SCHED_DEFAULT, ACE_DEFAULT_THREAD_PRIORITY, MONITOR_GROUP_ID); } ostringstream ostr; ostr << "Received request to create thread (" << threadName << ")" << ends; STRACELOG(DEVELOPERLOG, THREADLOG, ostr.str().c_str()); ThreadParameters* threadParameters = new ThreadParameters(threadName, shouldRestart, function, functionArgs, threadFlags, priority, threadGroup, stackSize); if (ACE_Thread_Manager::instance()->spawn( (ACE_THR_FUNC)ThreadManager::runThread, (void*)threadParameters, threadFlags, &threadId, 0 , priority, threadGroup, 0 , stackSize) == ERROR) { ostringstream ostr; ostr << "Unable to spawn thread (" << threadName << ")" << ends; STRACELOG(ERRORLOG, THREADLOG, ostr.str().c_str()); return 0; } else { ostringstream ostr; ostr << "Successfully spawned thread (" << threadName << ") returning Thread Id (" << threadId << ")" << ends; STRACELOG(DEBUGLOG, THREADLOG, ostr.str().c_str()); } return threadId; } ACE_thread_t* ThreadManager::createThreadPool(size_t Nthreads, ACE_THR_FUNC function, void *functionArgs, const char* threadName, bool shouldRestart, long threadFlags, long priority, int threadGroup, size_t stackSize) { ACE_thread_t* threadIds = new ACE_thread_t[Nthreads]; size_t stackSizes[Nthreads]; memset(stackSizes, stackSize, Nthreads); if (!isInitialized_) { isInitialized_ = true; ThreadManager::createThread((ACE_THR_FUNC)ThreadManager::startThreadMonitor, 0, "ThreadManagerMonitor", true, THR_NEW_LWP | THR_JOINABLE | THR_SCHED_DEFAULT, ACE_DEFAULT_THREAD_PRIORITY, MONITOR_GROUP_ID); } ostringstream ostr; ostr << "Received request to create thread pool (" << threadName << ") with (" << Nthreads << ") threads" << ends; STRACELOG(DEVELOPERLOG, THREADLOG, ostr.str().c_str()); ThreadParameters* threadParameters = new ThreadParameters(threadName, shouldRestart, function, functionArgs, threadFlags, priority, threadGroup, stackSize); if (ACE_Thread_Manager::instance()->spawn_n( threadIds, Nthreads, (ACE_THR_FUNC)ThreadManager::runThread, (void*)threadParameters, threadFlags, priority, threadGroup, 0 , stackSizes, 0 ) == ERROR) { ostringstream ostr; ostr << "Unable to spawn thread pool (" << threadName << ")" << ends; STRACELOG(ERRORLOG, THREADLOG, ostr.str().c_str()); return 0; } else { ostringstream ostr; ostr << "Successfully spawned thread pool (" << threadName << ")" << ends; STRACELOG(DEBUGLOG, THREADLOG, ostr.str().c_str()); } return threadIds; } void ThreadManager::startThreadMonitor() { while (1) { ThreadManager::restartMapMutex_.acquire(); if (!ThreadManager::restartMap_.empty()) { ThreadsWaitingForRestartMap::iterator restartMapIterator; ThreadsWaitingForRestartMap::iterator endIterator; restartMapIterator = ThreadManager::restartMap_.begin(); endIterator = ThreadManager::restartMap_.end(); while (restartMapIterator != endIterator) { ThreadParameters* threadParms = (ThreadParameters*)restartMapIterator->second; ACE_thread_t newThreadId =
; ostringstream ostr; ostr << "Thread (" << threadParms->threadName_ << ") restarted with new Thread Id (" << newThreadId << ")" << ends; STRACELOG(DEBUGLOG, THREADLOG, ostr.str().c_str()); ThreadManager::restartMap_.erase(restartMapIterator->first); restartMapIterator++; } } ThreadManager::restartMapMutex_.release(); sleep(THREAD_MONITOR_PERIOD); } } ThreadManager::~ThreadManager() { if ((threadParameters_) && (!threadParameters_->shouldRestart_)) { delete threadParameters_; } } void ThreadManager::apply(void) { if (threadParameters_->shouldRestart_) { ostringstream ostr; ostr << "Thread exit handler caught thread death for thread (" << threadParameters_->threadName_ << ") with Id (" << threadId_ << "). Attempting restart." << ends; STRACELOG(ERRORLOG, THREADLOG, ostr.str().c_str()); typedef pair<unsigned long, ThreadParameters*> ThreadRestartPair; ThreadRestartPair threadRestartPair(threadId_, threadParameters_); ThreadManager::restartMapMutex_.acquire(); pair<map<unsigned long, ThreadParameters*>::iterator, bool> pairIterator = ThreadManager::restartMap_.insert(threadRestartPair); if (!pairIterator.second) { ostringstream ostr; ostr << "Error queuing thread (" << threadParameters_->threadName_ << ") with Id (" << threadId_ << ") for restart. Thread will not be restarted." << ends; STRACELOG(ERRORLOG, THREADLOG, ostr.str().c_str()); } ThreadManager::restartMapMutex_.release(); } else { ostringstream ostr; ostr << "Thread exit handler caught thread death for (" << threadParameters_->threadName_ << ") with Id (" << threadId_ << ")" << ends; STRACELOG(WARNINGLOG, THREADLOG, ostr.str().c_str()); } } ThreadManager::ThreadManager(ThreadParameters& threadParameters) : threadParameters_(&threadParameters) { threadId_ = ACE_Thread::self(); } ThreadManager* ThreadManager::getInstance(ThreadParameters& threadParameters) { return new ThreadManager(threadParameters); } ACE_THR_FUNC_RETURN ThreadManager::runThread(ThreadParameters& threadParameters) { ACE_Thread_Manager::instance()->at_exit(ThreadManager::getInstance(threadParameters)); ostringstream ostr1; ostr1 << "Attached thread exit handler to thread (" << threadParameters.threadName_ << ") with Id (" << ACE_Thread::self() << ")" << ends; STRACELOG(DEVELOPERLOG, THREADLOG, ostr1.str().c_str()); try { (*threadParameters.function_) (threadParameters.functionArgs_); } catch (exception exc) { ostringstream ostr; ostr << "Caught Application Level Exception - " << exc.what() << ends; STRACELOG(ERRORLOG, THREADLOG, ostr.str().c_str()); } if (threadParameters.shouldRestart_) { int counter = 0; while (counter < THREAD_FUNC_RETRY) { ostringstream ostr2; ostr2 << "Thread function (" << threadParameters.threadName_ << ") with Id (" << ACE_Thread::self() << ") returned. Calling it again (count=" << counter << ")." << ends; STRACELOG(ERRORLOG, THREADLOG, ostr2.str().c_str()); try { (*threadParameters.function_) (threadParameters.functionArgs_); } catch (exception exc) { ostringstream ostr; ostr << "Caught Application Level Exception - " << exc.what() << ends; STRACELOG(ERRORLOG, THREADLOG, ostr.str().c_str()); } counter++; } ostringstream ostr2; ostr2 << "Thread function (" << threadParameters.threadName_ << ") with Id (" << ACE_Thread::self() << ") returned " << counter << " times. Giving up to let the thread get restarted" << ends; STRACELOG(ERRORLOG, THREADLOG, ostr2.str().c_str()); } else { ostringstream ostr2; ostr2 << "Thread function (" << threadParameters.threadName_ << ") with Id (" << ACE_Thread::self() << ") returned." << ends; STRACELOG(WARNINGLOG, THREADLOG, ostr2.str().c_str()); } return 0; }
ThreadManager::createThread(threadParms->function_, threadParms->functionArgs_, threadParms->threadName_.c_str(), threadParms->shouldRestart_, threadParms->threadFlags_, threadParms->priority_, threadParms->threadGroup_, threadParms->stackSize_)
call_expression
[ { "content": "function with a return - the return value is simply ignored.\n\n(See ethel example below)\n\n\n\nAll the correct virtual function behavior is preserved. (see ricky\n\nexample below).\n\n\n\nIf you somehow try to create something in violation\n\nof the type system you will get a compile-time or tem...
C++
fboss/agent/state/tests/NeighborTests.cpp
dgrnbrg-meta/fboss
cde5aa021fbb28e08cc912a7c227e93ed3faefee
#include <fboss/agent/state/ArpResponseEntry.h> #include "fboss/agent/test/TestUtils.h" #include "fboss/agent/state/ArpEntry.h" #include "fboss/agent/state/NdpEntry.h" #include "fboss/agent/state/NeighborEntry.h" #include "fboss/agent/state/NeighborResponseTable.h" #include "fboss/agent/state/Vlan.h" #include <gtest/gtest.h> namespace { auto constexpr kState = "state"; } using namespace facebook::fboss; using folly::IPAddressV4; using folly::IPAddressV6; using folly::MacAddress; template <typename NeighborEntryT> void serializeTest(const NeighborEntryT& entry) { auto serialized = entry.toFollyDynamic(); auto entryBack = NeighborEntryT::fromFollyDynamic(serialized); EXPECT_EQ(entry, *entryBack); } TEST(ArpEntry, serialize) { auto entry = std::make_unique<ArpEntry>( IPAddressV4("192.168.0.1"), MacAddress("01:01:01:01:01:01"), PortDescriptor(PortID(1)), InterfaceID(10)); validateThriftyMigration(*entry); serializeTest(*entry); } TEST(NdpEntry, serialize) { auto entry = std::make_unique<NdpEntry>( IPAddressV6("2401:db00:21:70cb:face:0:96:0"), MacAddress("01:01:01:01:01:01"), PortDescriptor(PortID(10)), InterfaceID(10)); validateThriftyMigration(*entry); serializeTest(*entry); } TEST(ArpTable, serialize) { ArpTable table; table.addEntry( IPAddressV4("192.168.0.1"), MacAddress("01:01:01:01:01:01"), PortDescriptor(PortID(10)), InterfaceID(10), NeighborState::REACHABLE); table.addEntry( IPAddressV4("192.168.0.2"), MacAddress("01:01:01:01:01:02"), PortDescriptor(PortID(11)), InterfaceID(11), NeighborState::PENDING); validateThriftyMigration(table); serializeTest(table); } TEST(NdpTable, serialize) { NdpTable table; table.addEntry( IPAddressV6("2401:db00:21:70cb:face:0:96:0"), MacAddress("01:01:01:01:01:01"), PortDescriptor(PortID(10)), InterfaceID(10), NeighborState::REACHABLE); table.addEntry( IPAddressV6("2401:db00:21:70cb:face:0:96:1"), MacAddress("01:01:01:01:01:02"), PortDescriptor(PortID(11)), InterfaceID(11), NeighborState::PENDING); validateThriftyMigration(table); serializeTest(table); } TEST(NeighborResponseEntry, serialize) { auto entry = std::make_unique<ArpResponseEntry>( IPAddressV4("192.168.0.1"), MacAddress("01:01:01:01:01:01"), InterfaceID(0)); auto serialized = entry->toFollyDynamic(); auto entryBack = ArpResponseEntry::fromFollyDynamic(serialized); EXPECT_TRUE(*entry == *entryBack); } TEST(NeighborResponseTableTest, modify) { auto ip1 = IPAddressV4("192.168.0.1"), ip2 = IPAddressV4("192.168.0.2"); auto mac1 = MacAddress("01:01:01:01:01:01"), mac2 = MacAddress("01:01:01:01:01:02"); auto state = std::make_shared<SwitchState>(); auto vlan = std::make_shared<Vlan>(VlanID(2001), "vlan1"); auto arpResponseTable = std::make_shared<ArpResponseTable>(); arpResponseTable->setEntry(ip1, mac1, InterfaceID(0)); vlan->setArpResponseTable(arpResponseTable); state->getVlans()->addVlan(vlan); EXPECT_EQ(vlan.get(), vlan->modify(&state)); arpResponseTable = std::make_shared<ArpResponseTable>(); arpResponseTable->setEntry(ip2, mac2, InterfaceID(1)); vlan->setArpResponseTable(arpResponseTable); EXPECT_EQ(vlan.get(), vlan->modify(&state)); vlan->publish(); auto modifiedVlan = vlan->modify(&state); arpResponseTable = std::make_shared<ArpResponseTable>(); arpResponseTable->setEntry(ip1, mac1, InterfaceID(0)); EXPECT_DEATH(vlan->setArpResponseTable(arpResponseTable), "!isPublished"); modifiedVlan->setArpResponseTable(arpResponseTable); EXPECT_NE(vlan.get(), modifiedVlan); EXPECT_FALSE(vlan->getArpResponseTable()->getEntry(ip1) != nullptr); EXPECT_TRUE(vlan->getArpResponseTable()->getEntry(ip2) != nullptr); EXPECT_TRUE(modifiedVlan->getArpResponseTable()->getEntry(ip1) != nullptr); EXPECT_FALSE(modifiedVlan->getArpResponseTable()->getEntry(ip2) != nullptr); }
#include <fboss/agent/state/ArpResponseEntry.h> #include "fboss/agent/test/TestUtils.h" #include "fboss/agent/state/ArpEntry.h" #include "fboss/agent/state/NdpEntry.h" #include "fboss/agent/state/NeighborEntry.h" #include "fboss/agent/state/NeighborResponseTable.h" #include "fboss/agent/state/Vlan.h" #include <gtest/gtest.h> namespace { auto constexpr kState = "state"; } using namespace facebook::fboss; using folly::IPAddressV4; using folly::IPAddressV6; using folly::MacAddress; template <typename NeighborEntryT> void serializeTest(const NeighborEntryT& entry) { auto serialized = entry.toFollyDynamic(); auto entryBack = NeighborEntryT::fromFollyDynamic(serialized); EXPECT_EQ(entry, *entryBack); } TEST(ArpEntry, serialize) { auto entry = std::make_unique<ArpEntry>( IPAddressV4("192.168.0.1"), MacAddress("01:01:01:01:01:01"), PortDescriptor(PortID(1)), InterfaceID(10)); validateThriftyMigration(*entry); serializeTest(*entry); } TEST(NdpEntry, serialize) { auto entry = std::make_unique<NdpEntry>( IPAddressV6("2401:db00:21:70cb:face:0:96:0"), MacAddress("01:01:01:01:01:01"), PortDescriptor(PortID(10)), InterfaceID(10)); validateThriftyMigration(*entry); serializeTest(*entry); }
TEST(NdpTable, serialize) { NdpTable table; table.addEntry( IPAddressV6("2401:db00:21:70cb:face:0:96:0"), MacAddress("01:01:01:01:01:01"), PortDescriptor(PortID(10)), InterfaceID(10), NeighborState::REACHABLE); table.addEntry( IPAddressV6("2401:db00:21:70cb:face:0:96:1"), MacAddress("01:01:01:01:01:02"), PortDescriptor(PortID(11)), InterfaceID(11), NeighborState::PENDING); validateThriftyMigration(table); serializeTest(table); } TEST(NeighborResponseEntry, serialize) { auto entry = std::make_unique<ArpResponseEntry>( IPAddressV4("192.168.0.1"), MacAddress("01:01:01:01:01:01"), InterfaceID(0)); auto serialized = entry->toFollyDynamic(); auto entryBack = ArpResponseEntry::fromFollyDynamic(serialized); EXPECT_TRUE(*entry == *entryBack); } TEST(NeighborResponseTableTest, modify) { auto ip1 = IPAddressV4("192.168.0.1"), ip2 = IPAddressV4("192.168.0.2"); auto mac1 = MacAddress("01:01:01:01:01:01"), mac2 = MacAddress("01:01:01:01:01:02"); auto state = std::make_shared<SwitchState>(); auto vlan = std::make_shared<Vlan>(VlanID(2001), "vlan1"); auto arpResponseTable = std::make_shared<ArpResponseTable>(); arpResponseTable->setEntry(ip1, mac1, InterfaceID(0)); vlan->setArpResponseTable(arpResponseTable); state->getVlans()->addVlan(vlan); EXPECT_EQ(vlan.get(), vlan->modify(&state)); arpResponseTable = std::make_shared<ArpResponseTable>(); arpResponseTable->setEntry(ip2, mac2, InterfaceID(1)); vlan->setArpResponseTable(arpResponseTable); EXPECT_EQ(vlan.get(), vlan->modify(&state)); vlan->publish(); auto modifiedVlan = vlan->modify(&state); arpResponseTable = std::make_shared<ArpResponseTable>(); arpResponseTable->setEntry(ip1, mac1, InterfaceID(0)); EXPECT_DEATH(vlan->setArpResponseTable(arpResponseTable), "!isPublished"); modifiedVlan->setArpResponseTable(arpResponseTable); EXPECT_NE(vlan.get(), modifiedVlan); EXPECT_FALSE(vlan->getArpResponseTable()->getEntry(ip1) != nullptr); EXPECT_TRUE(vlan->getArpResponseTable()->getEntry(ip2) != nullptr); EXPECT_TRUE(modifiedVlan->getArpResponseTable()->getEntry(ip1) != nullptr); EXPECT_FALSE(modifiedVlan->getArpResponseTable()->getEntry(ip2) != nullptr); }
TEST(ArpTable, serialize) { ArpTable table; table.addEntry( IPAddressV4("192.168.0.1"), MacAddress("01:01:01:01:01:01"), PortDescriptor(PortID(10)), InterfaceID(10), NeighborState::REACHABLE); table.addEntry( IPAddressV4("192.168.0.2"), MacAddress("01:01:01:01:01:02"), PortDescriptor(PortID(11)), InterfaceID(11), NeighborState::PENDING); validateThriftyMigration(table); serializeTest(table); }
function_block-full_function
[ { "content": "class MacEntry\n\n : public ThriftyBaseT<state::MacEntryFields, MacEntry, MacEntryFields> {\n\n public:\n\n MacEntry(\n\n folly::MacAddress mac,\n\n PortDescriptor portDescr,\n\n std::optional<cfg::AclLookupClass> classID = std::nullopt,\n\n MacEntryType type = MacEntryType...
C++
src/hermite.cpp
azurite/AST-245-N-Body
cc3e3acd61f62415c1e5f40c8aba5b93703837fa
#include <iostream> #include <fstream> #include <chrono> #include <hermite.hpp> Hermite::Hermite() { t = .0; dt = 0.01; eps = 0.01; N = 0; filename = ""; lean = false; blockSize = 1; } void Hermite::enableLean() { if(!lean) lean = true; } void Hermite::disableLean() { if(lean) lean = false; } void Hermite::setBlockSize(int size) { if(size >= 1) { blockSize = size; } } void Hermite::setSoftening(double newEps) { eps = newEps; } void Hermite::integrate(double dt, int numSteps) { std::cout << "starting integration of: " << filename << std::endl; std::cout << "-------------------------------------------" << std::endl; std::cout << "N: " << N << std::endl; std::cout << "dt: " << dt << std::endl; std::cout << "softening: " << eps << std::endl; std::cout << "time interval: [0, " << (numSteps * dt) << "]" << std::endl; totalData = MatrixXd::Zero(3, (numSteps / blockSize + 1) * N); energy = VectorXd::Zero(numSteps); this->dt = dt; t = 0; auto start = std::chrono::high_resolution_clock::now(); for(int step = 0; step < numSteps; step++) { if(step % blockSize == 0) { totalData.block(0, (step / blockSize)*N, 3, N) = particles.block(1, 0, 3, N); } this->computeEnergy(step); this->step(); t += dt; } energy = (((energy(0) * VectorXd::Ones(numSteps)) - energy) / energy(0)).cwiseAbs(); auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> time = end - start; std::cout << "simulation time: " << time.count() << "s" << std::endl; std::cout << "-------------------------------------------" << std::endl; std::cout << std::endl; if(!lean) { std::ofstream file_pos(filename + ".output_pos.txt"); for(int i = 0; i < totalData.rows(); i++) { for(int j = 0; j < totalData.cols(); j++) { file_pos << totalData(i, j) << " "; } file_pos << std::endl; } } std::ofstream file_energy(filename + ".output_energy.txt"); for(int i = 0; i <= energy.size() - blockSize; i += blockSize) { file_energy << energy(i) << " "; } file_energy << std::endl; std::ofstream file_meta(filename + ".output_meta.txt"); file_meta << N << " " << dt << " " << (numSteps * dt) << " " << eps << std::endl; } void Hermite::computeEnergy(int step) { double etot = .0; double mi, mj, dx, dy, dz, vx, vy, vz; for(int i = 0; i < N; i++) { double subtract = .0; mi = particles(0, i); vx = particles(4, i); vy = particles(5, i); vz = particles(6, i); for(int j = 0; j < i; j++) { mj = particles(0, j); dx = particles(1, j) - particles(1, i); dy = particles(2, j) - particles(2, i); dz = particles(3, j) - particles(3, i); subtract += (mj / std::sqrt(dx*dx + dy*dy + dz*dz + eps*eps)); } etot += (mi * (0.5 * (vx*vx + vy*vy + vz*vz) - subtract)); } energy(step) = etot; } MatrixXd Hermite::computeForces(const MatrixXd mass, const MatrixXd pos, const MatrixXd vel) { double mi, mj, dx, dy, dz, dvx, dvy, dvz, sqrtInvDist, sqrtInvDist3, sqrtInvDist5, vdotr, ax, ay, az, jx, jy, jz; MatrixXd acc_and_jerk = MatrixXd::Zero(6, N); for(int i = 0; i < N; i++) { for(int j = i + 1; j < N; j++) { mj = mass(0, j); dx = pos(0, i) - pos(0, j); dy = pos(1, i) - pos(1, j); dz = pos(2, i) - pos(2, j); dvx = vel(0, i) - vel(0, j); dvy = vel(1, i) - vel(1, j); dvz = vel(2, i) - vel(2, j); sqrtInvDist = 1.0 / std::sqrt(dx * dx + dy * dy + dz * dz + eps * eps); sqrtInvDist3 = sqrtInvDist * sqrtInvDist * sqrtInvDist; sqrtInvDist5 = sqrtInvDist3 * sqrtInvDist * sqrtInvDist; vdotr = dvx * dx + dvy * dy + dvz * dz; ax = -mj * dx * sqrtInvDist3; ay = -mj * dy * sqrtInvDist3; az = -mj * dz * sqrtInvDist3; acc_and_jerk(0, i) += ax; acc_and_jerk(1, i) += ay; acc_and_jerk(2, i) += az; acc_and_jerk(0, j) -= ax; acc_and_jerk(1, j) -= ay; acc_and_jerk(2, j) -= az; jx = -mj * ((dvx * sqrtInvDist3) - (3 * vdotr * dx) * sqrtInvDist5); jy = -mj * ((dvy * sqrtInvDist3) - (3 * vdotr * dy) * sqrtInvDist5); jz = -mj * ((dvz * sqrtInvDist3) - (3 * vdotr * dz) * sqrtInvDist5); acc_and_jerk(3, i) += jx; acc_and_jerk(4, i) += jy; acc_and_jerk(5, i) += jz; acc_and_jerk(3, j) -= jx; acc_and_jerk(4, j) -= jy; acc_and_jerk(5, j) -= jz; } } return acc_and_jerk; } void Hermite::step() { MatrixXd masses = particles.topRows(1); x0 = particles.block(1, 0, 3, N); v0 = particles.block(4, 0, 3, N); MatrixXd acc_and_jerk0 = computeForces(masses, x0, v0); a0 = acc_and_jerk0.topRows(3); jerk0 = acc_and_jerk0.bottomRows(3); xp = (x0 + (v0 * dt) + (a0 * (0.5 * dt * dt)) + (jerk0 * (0.1667 * dt * dt * dt))); vp = (v0 + (a0 * dt) + (jerk0 * (0.5 * dt * dt))); MatrixXd acc_and_jerk1 = computeForces(masses, xp, vp); a1 = acc_and_jerk1.topRows(3); jerk1 = acc_and_jerk1.bottomRows(3); v1 = v0 + ((a0 + a1) * 0.5 * dt) + ((jerk0 - jerk1) * 0.0833 * dt * dt); x1 = x0 + ((v0 + v1) * 0.5 * dt) + ((a0 - a1) * 0.0833 * dt * dt); particles.block(1, 0, 3, N) = x1; particles.block(4, 0, 3, N) = v1; } bool Hermite::readData(const std::string &filename) { std::ifstream infile(filename); int numParticles, numGasParticles, numStarParticles; if(infile.is_open()) { infile >> numParticles >> numGasParticles >> numStarParticles; particles = Eigen::MatrixXd::Zero(HERMITE_DATA_ROWS, numParticles); N = numParticles; this->filename = filename; for(int i = 0; i < numParticles; i++) { infile >> particles(0, i); } for(int i = 0; i < numParticles; i++) { infile >> particles(1, i); } for(int i = 0; i < numParticles; i++) { infile >> particles(2, i); } for(int i = 0; i < numParticles; i++) { infile >> particles(3, i); } for(int i = 0; i < numParticles; i++) { infile >> particles(4, i); } for(int i = 0; i < numParticles; i++) { infile >> particles(5, i); } for(int i = 0; i < numParticles; i++) { infile >> particles(6, i); } infile >> eps; return true; } std::cout << "Hermite::readData(\"" << filename << "\") " << "could not read file" << std::endl; return false; } const Matrix<double, 3, Dynamic> &Hermite::data() { return totalData; }
#include <iostream> #include <fstream> #include <chrono> #include <hermite.hpp> Hermite::Hermite() { t = .0; dt = 0.01; eps = 0.01; N = 0; filename = ""; lean = false; blockSize = 1; } void Hermite::enableLean() { if(!lean) lean = true; } void Hermite::disableLean() { if(lean) lean = false; } void Hermite::setBlockSize(int size) { if(size >= 1) { blockSize = size; } } void Hermite::setSoftening(double newEps) { eps = newEps; } void Hermite::integrate(double dt, int numSteps) { std::cout << "starting integration of: " << filename << std::endl; std::cout << "-------------------------------------------" << std::endl; std::cout << "N: " << N << std::endl; std::cout << "dt: " << dt << std::endl; std::cout << "softening: " << eps << std::endl; std::cout << "time interval: [0, " << (numSteps * dt) << "]" << std::endl; totalData = MatrixXd::Zero(3, (numSteps / blockSize + 1) * N); energy = VectorXd::Zero(numSteps); this->dt = dt; t = 0; auto start = std::chrono::high_resolution_clock::now(); for(int step = 0; step < numSteps; step++) { if(step % blockSize == 0) { totalData.block(0, (step / blockSize)*N, 3, N) = particles.block(1, 0, 3, N); } this->computeEnergy(step); this->step(); t += dt; } energy = (((energy(0) * VectorXd::Ones(numSteps)) - energy) / energy(0)).cwiseAbs(); auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> time = end - start; std::cout << "simulation time: " << time.count() << "s" << std::endl; std::cout << "-------------------------------------------" << std::endl; std::cout << std::endl;
std::ofstream file_energy(filename + ".output_energy.txt"); for(int i = 0; i <= energy.size() - blockSize; i += blockSize) { file_energy << energy(i) << " "; } file_energy << std::endl; std::ofstream file_meta(filename + ".output_meta.txt"); file_meta << N << " " << dt << " " << (numSteps * dt) << " " << eps << std::endl; } void Hermite::computeEnergy(int step) { double etot = .0; double mi, mj, dx, dy, dz, vx, vy, vz; for(int i = 0; i < N; i++) { double subtract = .0; mi = particles(0, i); vx = particles(4, i); vy = particles(5, i); vz = particles(6, i); for(int j = 0; j < i; j++) { mj = particles(0, j); dx = particles(1, j) - particles(1, i); dy = particles(2, j) - particles(2, i); dz = particles(3, j) - particles(3, i); subtract += (mj / std::sqrt(dx*dx + dy*dy + dz*dz + eps*eps)); } etot += (mi * (0.5 * (vx*vx + vy*vy + vz*vz) - subtract)); } energy(step) = etot; } MatrixXd Hermite::computeForces(const MatrixXd mass, const MatrixXd pos, const MatrixXd vel) { double mi, mj, dx, dy, dz, dvx, dvy, dvz, sqrtInvDist, sqrtInvDist3, sqrtInvDist5, vdotr, ax, ay, az, jx, jy, jz; MatrixXd acc_and_jerk = MatrixXd::Zero(6, N); for(int i = 0; i < N; i++) { for(int j = i + 1; j < N; j++) { mj = mass(0, j); dx = pos(0, i) - pos(0, j); dy = pos(1, i) - pos(1, j); dz = pos(2, i) - pos(2, j); dvx = vel(0, i) - vel(0, j); dvy = vel(1, i) - vel(1, j); dvz = vel(2, i) - vel(2, j); sqrtInvDist = 1.0 / std::sqrt(dx * dx + dy * dy + dz * dz + eps * eps); sqrtInvDist3 = sqrtInvDist * sqrtInvDist * sqrtInvDist; sqrtInvDist5 = sqrtInvDist3 * sqrtInvDist * sqrtInvDist; vdotr = dvx * dx + dvy * dy + dvz * dz; ax = -mj * dx * sqrtInvDist3; ay = -mj * dy * sqrtInvDist3; az = -mj * dz * sqrtInvDist3; acc_and_jerk(0, i) += ax; acc_and_jerk(1, i) += ay; acc_and_jerk(2, i) += az; acc_and_jerk(0, j) -= ax; acc_and_jerk(1, j) -= ay; acc_and_jerk(2, j) -= az; jx = -mj * ((dvx * sqrtInvDist3) - (3 * vdotr * dx) * sqrtInvDist5); jy = -mj * ((dvy * sqrtInvDist3) - (3 * vdotr * dy) * sqrtInvDist5); jz = -mj * ((dvz * sqrtInvDist3) - (3 * vdotr * dz) * sqrtInvDist5); acc_and_jerk(3, i) += jx; acc_and_jerk(4, i) += jy; acc_and_jerk(5, i) += jz; acc_and_jerk(3, j) -= jx; acc_and_jerk(4, j) -= jy; acc_and_jerk(5, j) -= jz; } } return acc_and_jerk; } void Hermite::step() { MatrixXd masses = particles.topRows(1); x0 = particles.block(1, 0, 3, N); v0 = particles.block(4, 0, 3, N); MatrixXd acc_and_jerk0 = computeForces(masses, x0, v0); a0 = acc_and_jerk0.topRows(3); jerk0 = acc_and_jerk0.bottomRows(3); xp = (x0 + (v0 * dt) + (a0 * (0.5 * dt * dt)) + (jerk0 * (0.1667 * dt * dt * dt))); vp = (v0 + (a0 * dt) + (jerk0 * (0.5 * dt * dt))); MatrixXd acc_and_jerk1 = computeForces(masses, xp, vp); a1 = acc_and_jerk1.topRows(3); jerk1 = acc_and_jerk1.bottomRows(3); v1 = v0 + ((a0 + a1) * 0.5 * dt) + ((jerk0 - jerk1) * 0.0833 * dt * dt); x1 = x0 + ((v0 + v1) * 0.5 * dt) + ((a0 - a1) * 0.0833 * dt * dt); particles.block(1, 0, 3, N) = x1; particles.block(4, 0, 3, N) = v1; } bool Hermite::readData(const std::string &filename) { std::ifstream infile(filename); int numParticles, numGasParticles, numStarParticles; if(infile.is_open()) { infile >> numParticles >> numGasParticles >> numStarParticles; particles = Eigen::MatrixXd::Zero(HERMITE_DATA_ROWS, numParticles); N = numParticles; this->filename = filename; for(int i = 0; i < numParticles; i++) { infile >> particles(0, i); } for(int i = 0; i < numParticles; i++) { infile >> particles(1, i); } for(int i = 0; i < numParticles; i++) { infile >> particles(2, i); } for(int i = 0; i < numParticles; i++) { infile >> particles(3, i); } for(int i = 0; i < numParticles; i++) { infile >> particles(4, i); } for(int i = 0; i < numParticles; i++) { infile >> particles(5, i); } for(int i = 0; i < numParticles; i++) { infile >> particles(6, i); } infile >> eps; return true; } std::cout << "Hermite::readData(\"" << filename << "\") " << "could not read file" << std::endl; return false; } const Matrix<double, 3, Dynamic> &Hermite::data() { return totalData; }
if(!lean) { std::ofstream file_pos(filename + ".output_pos.txt"); for(int i = 0; i < totalData.rows(); i++) { for(int j = 0; j < totalData.cols(); j++) { file_pos << totalData(i, j) << " "; } file_pos << std::endl; } }
if_condition
[ { "content": " VectorXd energy;\n\n std::string filename;\n\n bool lean; // if set to true solver will not write position files because they can get quite large\n\n int blockSize;\n\n Matrix<double, 3, Dynamic> totalData; // positions of all particles over all time steps\n\n\n\n void computeEnergy(int ste...
C++
sandbox/rootfs.cc
Codu-LLC/sandbox
f78cb0fb8705904ffcda370f3395ca134d5fd87e
#include "debug.h" #include "rootfs.h" #include "sandbox.h" #include "util.h" #include <fcntl.h> #include <iostream> #include <sys/types.h> #include <sys/mount.h> #include <sys/stat.h> #include <unistd.h> int setup_rootfs(Sandbox *ptr) { if (mount(ptr->get_src_root_fs_dir().c_str(), ptr->get_target_root_fs_dir().c_str(), "", MS_BIND | MS_REC, NULL) == -1) { return -1; } if (mkdir((ptr->get_target_root_fs_dir() + "/sandbox").c_str(), 0777) == -1 && errno != EEXIST) { print_string(ptr->is_debug(), "Making a directory for sandbox failed"); return -1; } if (mount(ptr->get_sandbox_dir().c_str(), (ptr->get_target_root_fs_dir() + "/sandbox").c_str(), "", MS_BIND, NULL) == -1) { print_string(ptr->is_debug(), "Mounting the sandbox directory failed."); return -1; } if (chdir(ptr->get_target_root_fs_dir().c_str()) == -1) { print_string(ptr->is_debug(), "Changing directory to the target rootfs failed."); return -1; } if (mkdir("sandbox/put_old", 0777) == -1 && errno != EEXIST) { print_string(ptr->is_debug(), "Making a directory for put_old failed."); return -1; } if (pivot_root(".", "sandbox/put_old") == -1) { print_string(ptr->is_debug(), "Pivot root failed."); return -1; } if (mount("sandbox/put_old/dev", "dev", "", MS_BIND | MS_REC, NULL) == -1) { print_string(ptr->is_debug(), "Mounting /dev failed."); return -1; } if (mount("", "dev", "", MS_SLAVE | MS_REC, NULL) == -1) { print_string(ptr->is_debug(), "Mounting /dev failed."); return -1; } if (mount("sandbox/put_old/proc", "proc", "", MS_BIND | MS_REC, NULL) == -1) { print_string(ptr->is_debug(), "Mounting /proc failed."); return -1; } if (mount("", "proc", "", MS_SLAVE | MS_REC, NULL) == -1) { print_string(ptr->is_debug(), "Mounting /proc failed."); return -1; } if (mount("sandbox/put_old/sys", "sys", "", MS_BIND | MS_REC, NULL) == -1) { print_string(ptr->is_debug(), "Mounting /sys failed."); return -1; } if (mount("", "sys", "", MS_SLAVE | MS_REC, NULL) == -1) { print_string(ptr->is_debug(), "Mounting /sys failed."); return -1; } if (mount("sandbox/put_old/tmp", "tmp", "", MS_BIND | MS_REC, NULL) == -1) { print_string(ptr->is_debug(), "Mounting /tmp failed."); return -1; } if (umount2("sandbox/put_old", MNT_DETACH) == -1) { print_string(ptr->is_debug(), "Detaching old rootfs failed."); return -1; } if (remove("sandbox/put_old") == -1) { print_string(ptr->is_debug(), "Removing old rootfs failed."); return -1; } if (chdir("sandbox") == -1) { print_string(ptr->is_debug(), "Changing current directory to sandbox failed."); return -1; } int f = open("stat.txt", O_CREAT, 0777); if (f == -1) { print_string(ptr->is_debug(), "Creating stat file failed."); return -1; } close(f); return 0; }
#include "debug.h" #include "rootfs.h" #include "sandbox.h" #include "util.h" #include <fcntl.h> #include <iostream> #include <sys/types.h> #include <sys/mount.h> #include <sys/stat.h> #include <unistd.h> int setup_rootfs(Sandbox *ptr) { if (mount(ptr->get_src_root_fs_dir().c_str(), ptr->get_target_root_fs_dir().c_str(), "", MS_BIND | MS_REC, NULL) == -1) { return -1; } if (mkdir((ptr->get_target_root_fs_dir() + "/sandbox").c_str(), 0777) == -1 && errno != E
1; } if (umount2("sandbox/put_old", MNT_DETACH) == -1) { print_string(ptr->is_debug(), "Detaching old rootfs failed."); return -1; } if (remove("sandbox/put_old") == -1) { print_string(ptr->is_debug(), "Removing old rootfs failed."); return -1; } if (chdir("sandbox") == -1) { print_string(ptr->is_debug(), "Changing current directory to sandbox failed."); return -1; } int f = open("stat.txt", O_CREAT, 0777); if (f == -1) { print_string(ptr->is_debug(), "Creating stat file failed."); return -1; } close(f); return 0; }
EXIST) { print_string(ptr->is_debug(), "Making a directory for sandbox failed"); return -1; } if (mount(ptr->get_sandbox_dir().c_str(), (ptr->get_target_root_fs_dir() + "/sandbox").c_str(), "", MS_BIND, NULL) == -1) { print_string(ptr->is_debug(), "Mounting the sandbox directory failed."); return -1; } if (chdir(ptr->get_target_root_fs_dir().c_str()) == -1) { print_string(ptr->is_debug(), "Changing directory to the target rootfs failed."); return -1; } if (mkdir("sandbox/put_old", 0777) == -1 && errno != EEXIST) { print_string(ptr->is_debug(), "Making a directory for put_old failed."); return -1; } if (pivot_root(".", "sandbox/put_old") == -1) { print_string(ptr->is_debug(), "Pivot root failed."); return -1; } if (mount("sandbox/put_old/dev", "dev", "", MS_BIND | MS_REC, NULL) == -1) { print_string(ptr->is_debug(), "Mounting /dev failed."); return -1; } if (mount("", "dev", "", MS_SLAVE | MS_REC, NULL) == -1) { print_string(ptr->is_debug(), "Mounting /dev failed."); return -1; } if (mount("sandbox/put_old/proc", "proc", "", MS_BIND | MS_REC, NULL) == -1) { print_string(ptr->is_debug(), "Mounting /proc failed."); return -1; } if (mount("", "proc", "", MS_SLAVE | MS_REC, NULL) == -1) { print_string(ptr->is_debug(), "Mounting /proc failed."); return -1; } if (mount("sandbox/put_old/sys", "sys", "", MS_BIND | MS_REC, NULL) == -1) { print_string(ptr->is_debug(), "Mounting /sys failed."); return -1; } if (mount("", "sys", "", MS_SLAVE | MS_REC, NULL) == -1) { print_string(ptr->is_debug(), "Mounting /sys failed."); return -1; } if (mount("sandbox/put_old/tmp", "tmp", "", MS_BIND | MS_REC, NULL) == -1) { print_string(ptr->is_debug(), "Mounting /tmp failed."); return -
random
[ { "content": "//\n\n// Created by Eugene Junghyun Kim on 1/13/2021.\n\n//\n\n\n\n#include \"cgroup.h\"\n\n#include \"debug.h\"\n\n#include \"execution.h\"\n\n#include \"file.h\"\n\n#include \"limit.h\"\n\n#include <memory>\n\n#include <sched.h>\n\n#include <signal.h>\n\n#include <string>\n\n#include <sys/types....
C++
src/cpp/toHTML/toHTML.cpp
tmadden/asm-dom
5cc18c41ba0da8319280355260d96d58bf67d782
#include "toHTML.hpp" #include "../utils/utils.hpp" #include "../VNode/VNode.hpp" #include "../Config/Config.hpp" #include <emscripten/val.h> #include <unordered_map> #include <string> namespace asmdom { std::unordered_map<std::string, bool> containerElements { {"a", true}, {"defs", true}, {"glyph", true}, {"g", true}, {"marker", true}, {"mask", true}, {"missing-glyph", true}, {"pattern", true}, {"svg", true}, {"switch", true}, {"symbol", true}, {"text", true}, {"desc", true}, {"metadata", true}, {"title", true} }; std::unordered_map<std::string, bool> voidElements { {"area", true}, {"base", true}, {"br", true}, {"col", true}, {"embed", true}, {"hr", true}, {"img", true}, {"input", true}, {"keygen", true}, {"link", true}, {"meta", true}, {"param", true}, {"source", true}, {"track", true}, {"wbr", true} }; #ifndef ASMDOM_JS_SIDE std::unordered_map<std::string, bool> omitProps { {"attributes", true}, {"childElementCount", true}, {"children", true}, {"classList", true}, {"clientHeight", true}, {"clientLeft", true}, {"clientTop", true}, {"clientWidth", true}, {"currentStyle", true}, {"firstElementChild", true}, {"innerHTML", true}, {"lastElementChild", true}, {"nextElementSibling", true}, {"ongotpointercapture", true}, {"onlostpointercapture", true}, {"onwheel", true}, {"outerHTML", true}, {"previousElementSibling", true}, {"runtimeStyle", true}, {"scrollHeight", true}, {"scrollLeft", true}, {"scrollLeftMax", true}, {"scrollTop", true}, {"scrollTopMax", true}, {"scrollWidth", true}, {"tabStop", true}, {"tagName", true} }; #endif std::string encode(const std::string& data) { std::string encoded; size_t size = data.size(); encoded.reserve(size); for(size_t pos = 0; pos != size; ++pos) { switch(data[pos]) { case '&': encoded.append("&amp;"); break; case '\"': encoded.append("&quot;"); break; case '\'': encoded.append("&apos;"); break; case '<': encoded.append("&lt;"); break; case '>': encoded.append("&gt;"); break; case '`': encoded.append("&#96;"); break; default: encoded.append(&data[pos], 1); break; } } return encoded; }; void appendAttributes(const VNode* const vnode, std::string& html) { for (auto& it : vnode->data.attrs) { html.append(" " + it.first + "=\"" + encode(it.second) + "\""); } #ifdef ASMDOM_JS_SIDE html.append( wstring_to_utf8(emscripten::val::module_property("appendProps")(reinterpret_cast<std::uintptr_t>(vnode)).as<std::wstring>()) ); #else emscripten::val String = emscripten::val::global("String"); for (auto& it : vnode->data.props) { if (!omitProps[it.first]) { std::string key = it.first; std::transform(key.begin(), key.end(), key.begin(), ::tolower); html.append(" " + key + "=\"" + encode(String(it.second).as<std::string>()) + "\""); } } #endif }; void toHTML(const VNode* const vnode, std::string& html) { if (!vnode) return; if (vnode->hash & isText && !vnode->sel.empty()) { html.append(encode(vnode->sel)); } else if (vnode->hash & isComment) { html.append("<!--" + vnode->sel + "-->"); } else if (vnode->hash & isFragment) { for(Children::size_type i = 0; i != vnode->children.size(); ++i) { toHTML(vnode->children[i], html); } } else { bool isSvg = (vnode->hash & hasNS) && vnode->ns == "http://www.w3.org/2000/svg"; bool isSvgContainerElement = isSvg && containerElements[vnode->sel]; html.append("<" + vnode->sel); appendAttributes(vnode, html); if (isSvg && !isSvgContainerElement) { html.append(" /"); } html.append(">"); if ( isSvgContainerElement || (!isSvg && !voidElements[vnode->sel]) ) { #ifdef ASMDOM_JS_SIDE html.append( wstring_to_utf8(emscripten::val::module_property("insertInnerHTML")(reinterpret_cast<std::uintptr_t>(vnode)).as<std::wstring>()) ); #else if (vnode->data.props.count("innerHTML") != 0) { html.append(vnode->data.props.at("innerHTML").as<std::string>()); } else #endif for(Children::size_type i = 0; i != vnode->children.size(); ++i) { toHTML(vnode->children[i], html); } html.append("</" + vnode->sel + ">"); } } }; std::string toHTML(VNode* const vnode) { std::string html; vnode->normalize(); toHTML(vnode, html); #ifndef ASMDOM_JS_SIDE if (vnode && CLEAR_MEMORY) { deleteVNode(vnode); } #endif return html; }; }
#include "toHTML.hpp" #include "../utils/utils.hpp" #include "../VNode/VNode.hpp" #include "../Config/Config.hpp" #include <emscripten/val.h> #include <unordered_map> #include <string> namespace asmdom { std::unordered_map<std::string, bool> containerElements { {"a", true}, {"defs", true}, {"glyph", true}, {"g", true}, {"marker", true}, {"mask", true}, {"missing-glyph", true}, {"pattern", true}, {"svg", true}, {"switch", true}, {"symbol", true}, {"text", true}, {"desc", true}, {"metadata", true}, {"title", true} }; std::unordered_map<std::string, bool> voidElements { {"area", true}, {"base", true}, {"br", true}, {"col", true}, {"embed", true}, {"hr", true}, {"img", true}, {"input", true}, {"keygen", true}, {"link", true}, {"meta", true}, {"param", true}, {"source", true}, {"track", true}, {"wbr", true} }; #ifndef ASMDOM_JS_SIDE std::unordered_map<std::string, bool> omitProps { {"attributes", true}, {"childElementCount", true}, {"children", true}, {"classList", true}, {"clientHeight", true}, {"clientLeft", true}, {"clientTop", true}, {"clientWidth", true}, {"currentStyle", true}, {"firstElementChild", true}, {"innerHTML", true}, {"lastElementChild", true}, {"nextElementSibling", true}, {"ongotpointercapture", true}, {"onlostpointercapture", true}, {"onwheel", true}, {"outerHTML", true}, {"previousElementSibling", true}, {"runtimeStyle", true}, {"scrollHeight", true}, {"scrollLeft", true}, {"scrollLeftMax", true}, {"scrollTop", true}, {"scrollTopMax", true}, {"scrollWidth", true}, {"tabStop", true}, {"tagName", true} }; #endif std::string encode(const std::string& data) { std::string encoded; size_t size = data.size(); encoded.reserve(size); for(size_t pos = 0; pos != size; ++pos) { switch(data[pos]) { case '&': encoded.append("&amp;"); break; case '\"': encoded.append("&quot;"); break; case '\'': encoded.append("&apos;"); break; case '<': encoded.append("&lt;"); break; case '>': encoded.append("&gt;"); break; case '`': encoded.append("&#96;"); break; default: encoded.append(&data[pos], 1); break; } } return encoded; }; void appendAttributes(const VNode* const vnode, std::string& html) { for (auto& it : vnode->data.attrs) { html.append(" " + it.first + "=\"" + encode(it.second) + "\""); } #ifdef ASMDOM_JS_SIDE html.append( wstring_to_utf8(emscripten::val::module_property("appendProps")(reinterpret_cast<std::uintptr_t>(vnode)).as<std::wstring>()) ); #else emscripten::val String = emscripten::val::global("String"); for (auto& it : vnode->data.props) { if (!omitProps[it.first]) { std::string key = it.first; std::transform(key.begin(), key.end(), key.begin(), ::tolower); html.append(" " + key + "=\"" + encode(String(it.second).as<std::string>()) + "\""); } } #endif }; void toHTML(const VNode* const vnode, std::string& html) { if (!vnode) return; if (vnode->hash & isText && !vnode->sel.empty()) { html.append(encode(vnode->sel)); } else if (vnode->hash & isComment) { html.append("<!--" + vnode->sel + "-->"); } else if (vnode->hash & isFragment) { for(Children::size_type i = 0; i != vnode->children.size(); ++i) { toHTML(vnode->children[i], html); } } else { bool isSvg = (vnode->hash & hasNS) && vnode->ns == "http://www.w3.org/2000/svg"; bool isSvgContainerElement = isSvg && containerElements[vnode->sel]; html.append("<" + vnode->sel); appendAttributes(vnode, html); if (isSvg && !isSvgContainerElement) { html.append(" /"); } html.append(">"); if ( isSvgContainerElement || (!isSvg && !voidElements[vnode->sel]) ) { #ifdef ASMDOM_JS_SIDE
; #else if (vnode->data.props.count("innerHTML") != 0) { html.append(vnode->data.props.at("innerHTML").as<std::string>()); } else #endif for(Children::size_type i = 0; i != vnode->children.size(); ++i) { toHTML(vnode->children[i], html); } html.append("</" + vnode->sel + ">"); } } }; std::string toHTML(VNode* const vnode) { std::string html; vnode->normalize(); toHTML(vnode, html); #ifndef ASMDOM_JS_SIDE if (vnode && CLEAR_MEMORY) { deleteVNode(vnode); } #endif return html; }; }
html.append( wstring_to_utf8(emscripten::val::module_property("insertInnerHTML")(reinterpret_cast<std::uintptr_t>(vnode)).as<std::wstring>()) )
call_expression
[ { "content": "const getData = (Module, obj) => {\n\n let hasRaws = obj.raw !== undefined;\n\n let hasEvents = false;\n\n\n\n let ref;\n\n const attrs = new Module.MapStringString();\n\n const raw = obj.raw !== undefined ? obj.raw : {};\n\n const events = {};\n\n\n\n if (typeof obj.className === 'string')...
C++
lite/kernels/cuda/lookup_table_compute_test.cc
jameswu2014/Paddle-Lite
827e349ac8eb769a873fe9b3aa961af8b8b20a96
#include "lite/kernels/cuda/lookup_table_compute.h" #include <gtest/gtest.h> #include <cmath> #include <memory> #include <string> #include <utility> #include <vector> #include "lite/core/op_registry.h" namespace paddle { namespace lite { namespace kernels { namespace cuda { using Tensor = lite::Tensor; void LookupTableComputeRef(const operators::LookupTableParam& param) { auto* ids_t = param.Ids; auto* output_t = param.Out; int64_t padding_idx = param.padding_idx; auto* ids = ids_t->data<int64_t>(); int64_t ids_numel = ids_t->dims().production(); auto* table_t = param.W; int64_t row_number = table_t->dims()[0]; int64_t row_width = table_t->dims()[1]; auto* table = table_t->data<float>(); auto* output = output_t->mutable_data<float>(); memset(output, 0, output_t->dims().production() * sizeof(float)); for (int64_t i = 0; i < ids_numel; ++i) { if (padding_idx != -1 && ids[i] == padding_idx) { memset(output + i * row_width, 0, row_width * sizeof(float)); } else { CHECK_LT(ids[i], row_number); CHECK_GE(ids[i], 0); memcpy(output + i * row_width, table + ids[i] * row_width, row_width * sizeof(float)); } } } TEST(lookup_table_cuda, retrieve_op) { auto lookup_table = KernelRegistry::Global().Create<TARGET(kCUDA), PRECISION(kFloat)>( "lookup_table"); ASSERT_FALSE(lookup_table.empty()); ASSERT_TRUE(lookup_table.front()); } TEST(lookup_table_cuda, init) { LookupTableCompute lookup_table; ASSERT_EQ(lookup_table.precision(), PRECISION(kFloat)); ASSERT_EQ(lookup_table.target(), TARGET(kCUDA)); } TEST(lookup_table_cuda, compute) { LookupTableCompute lookup_table; std::unique_ptr<KernelContext> ctx(new KernelContext); auto& context = ctx->As<CUDAContext>(); operators::LookupTableParam param; Tensor w, ids, out; Tensor w_cpu, ids_cpu, out_cpu; Tensor w_ref, ids_ref, out_ref; int64_t padding_idx = 0; int vocab_size = 128; int emb_size = 64; int ids_h = 50; int ids_w = 30; auto w_dim = DDim({vocab_size, emb_size}); auto ids_dim = DDim({ids_h, ids_w}); auto out_dim = DDim({ids_h, ids_w, emb_size}); int w_num = w_dim.production(); int ids_num = ids_dim.production(); int out_num = out_dim.production(); w.Resize(w_dim); ids.Resize(ids_dim); out.Resize(out_dim); w_cpu.Resize(w_dim); ids_cpu.Resize(ids_dim); out_cpu.Resize(out_dim); w_ref.Resize(w_dim); ids_ref.Resize(ids_dim); out_ref.Resize(out_dim); auto* out_data = out.mutable_data<float>(TARGET(kCUDA)); auto* w_cpu_data = w_cpu.mutable_data<float>(); auto* ids_cpu_data = ids_cpu.mutable_data<int64_t>(); auto* out_cpu_data = out_cpu.mutable_data<float>(); auto* w_ref_data = w_ref.mutable_data<float>(); auto* ids_ref_data = ids_ref.mutable_data<int64_t>(); auto* out_ref_data = out_ref.mutable_data<float>(); for (int i = 0; i < w_num; i++) { w_cpu_data[i] = static_cast<float>(i + 1) / (w_num + 1); w_ref_data[i] = static_cast<float>(i + 1) / (w_num + 1); } for (int i = 0; i < ids_num; i++) { ids_cpu_data[i] = i % vocab_size; ids_ref_data[i] = i % vocab_size; } w.Assign<float, lite::DDim, TARGET(kCUDA)>(w_cpu_data, w_dim); ids.Assign<int64_t, lite::DDim, TARGET(kCUDA)>(ids_cpu_data, ids_dim); param.W = &w; param.Ids = &ids; param.Out = &out; param.padding_idx = padding_idx; lookup_table.SetParam(param); cudaStream_t stream; cudaStreamCreate(&stream); context.SetExecStream(stream); lookup_table.SetContext(std::move(ctx)); lookup_table.Launch(); cudaDeviceSynchronize(); CopySync<TARGET(kCUDA)>( out_cpu_data, out_data, sizeof(float) * out.numel(), IoDirection::DtoH); param.W = &w_ref; param.Ids = &ids_ref; param.Out = &out_ref; LookupTableComputeRef(param); for (int i = 0; i < out_num; i++) { EXPECT_NEAR(out_cpu_data[i], out_ref_data[i], 1e-5); } } } } } } USE_LITE_KERNEL(lookup_table, kCUDA, kFloat, kNCHW, def);
#include "lite/kernels/cuda/lookup_table_compute.h" #include <gtest/gtest.h> #include <cmath> #include <memory> #include <string> #include <utility> #include <vector> #include "lite/core/op_registry.h" namespace paddle { namespace lite { namespace kernels { namespace cuda { using Tensor = lite::Tensor;
TEST(lookup_table_cuda, retrieve_op) { auto lookup_table = KernelRegistry::Global().Create<TARGET(kCUDA), PRECISION(kFloat)>( "lookup_table"); ASSERT_FALSE(lookup_table.empty()); ASSERT_TRUE(lookup_table.front()); } TEST(lookup_table_cuda, init) { LookupTableCompute lookup_table; ASSERT_EQ(lookup_table.precision(), PRECISION(kFloat)); ASSERT_EQ(lookup_table.target(), TARGET(kCUDA)); } TEST(lookup_table_cuda, compute) { LookupTableCompute lookup_table; std::unique_ptr<KernelContext> ctx(new KernelContext); auto& context = ctx->As<CUDAContext>(); operators::LookupTableParam param; Tensor w, ids, out; Tensor w_cpu, ids_cpu, out_cpu; Tensor w_ref, ids_ref, out_ref; int64_t padding_idx = 0; int vocab_size = 128; int emb_size = 64; int ids_h = 50; int ids_w = 30; auto w_dim = DDim({vocab_size, emb_size}); auto ids_dim = DDim({ids_h, ids_w}); auto out_dim = DDim({ids_h, ids_w, emb_size}); int w_num = w_dim.production(); int ids_num = ids_dim.production(); int out_num = out_dim.production(); w.Resize(w_dim); ids.Resize(ids_dim); out.Resize(out_dim); w_cpu.Resize(w_dim); ids_cpu.Resize(ids_dim); out_cpu.Resize(out_dim); w_ref.Resize(w_dim); ids_ref.Resize(ids_dim); out_ref.Resize(out_dim); auto* out_data = out.mutable_data<float>(TARGET(kCUDA)); auto* w_cpu_data = w_cpu.mutable_data<float>(); auto* ids_cpu_data = ids_cpu.mutable_data<int64_t>(); auto* out_cpu_data = out_cpu.mutable_data<float>(); auto* w_ref_data = w_ref.mutable_data<float>(); auto* ids_ref_data = ids_ref.mutable_data<int64_t>(); auto* out_ref_data = out_ref.mutable_data<float>(); for (int i = 0; i < w_num; i++) { w_cpu_data[i] = static_cast<float>(i + 1) / (w_num + 1); w_ref_data[i] = static_cast<float>(i + 1) / (w_num + 1); } for (int i = 0; i < ids_num; i++) { ids_cpu_data[i] = i % vocab_size; ids_ref_data[i] = i % vocab_size; } w.Assign<float, lite::DDim, TARGET(kCUDA)>(w_cpu_data, w_dim); ids.Assign<int64_t, lite::DDim, TARGET(kCUDA)>(ids_cpu_data, ids_dim); param.W = &w; param.Ids = &ids; param.Out = &out; param.padding_idx = padding_idx; lookup_table.SetParam(param); cudaStream_t stream; cudaStreamCreate(&stream); context.SetExecStream(stream); lookup_table.SetContext(std::move(ctx)); lookup_table.Launch(); cudaDeviceSynchronize(); CopySync<TARGET(kCUDA)>( out_cpu_data, out_data, sizeof(float) * out.numel(), IoDirection::DtoH); param.W = &w_ref; param.Ids = &ids_ref; param.Out = &out_ref; LookupTableComputeRef(param); for (int i = 0; i < out_num; i++) { EXPECT_NEAR(out_cpu_data[i], out_ref_data[i], 1e-5); } } } } } } USE_LITE_KERNEL(lookup_table, kCUDA, kFloat, kNCHW, def);
void LookupTableComputeRef(const operators::LookupTableParam& param) { auto* ids_t = param.Ids; auto* output_t = param.Out; int64_t padding_idx = param.padding_idx; auto* ids = ids_t->data<int64_t>(); int64_t ids_numel = ids_t->dims().production(); auto* table_t = param.W; int64_t row_number = table_t->dims()[0]; int64_t row_width = table_t->dims()[1]; auto* table = table_t->data<float>(); auto* output = output_t->mutable_data<float>(); memset(output, 0, output_t->dims().production() * sizeof(float)); for (int64_t i = 0; i < ids_numel; ++i) { if (padding_idx != -1 && ids[i] == padding_idx) { memset(output + i * row_width, 0, row_width * sizeof(float)); } else { CHECK_LT(ids[i], row_number); CHECK_GE(ids[i], 0); memcpy(output + i * row_width, table + ids[i] * row_width, row_width * sizeof(float)); } } }
function_block-full_function
[ { "content": "namespace paddle {\n\nnamespace lite {\n\n\n\ntemplate <typename Dtype>\n\nvoid fill_tensor_host_const_impl(Dtype* dio, Dtype value, int64_t size) {\n\n for (int64_t i = 0; i < size; ++i) {\n\n dio[i] = value;\n\n }\n\n}\n\n/**\n\n * \\brief Fill the host tensor buffer with rand value.\n\n *...
C++
kt-nn/src/main/cpp/LayerImage.cpp
viveret/kotlin-tiny-dnn
0f33d497384fe14b34edaa705642d67a15fadc66
#include "pocketn2.h" extern "C" JNIEXPORT jlong JNICALL Java_com_viveret_tinydnn_data_graphics_LayerImage_jniConstructor( JNIEnv *env, jobject thiz, jlong width, jlong height, jlong depth, tiny_dnn::image_type format) { auto fn = [&]() { auto size = new shape3d(width, height, depth); return (jlong)(void*) new tiny_dnn::image<unsigned char>(*size, format); }; jlong ret; if (jniTryCatch(env, fn, ret)) { return ret; } else { return -1; } } extern "C" JNIEXPORT void JNICALL Java_com_viveret_tinydnn_data_graphics_LayerImage_jniResize(JNIEnv *env, jobject thiz, jlong handle, jlong width, jlong height) { auto fn = [&]() { ((tiny_dnn::image<unsigned char> *) handle)->resize(width, height); return true; }; jboolean ret; jniTryCatch(env, fn, ret); } extern "C" JNIEXPORT jbyteArray JNICALL Java_com_viveret_tinydnn_data_graphics_LayerImage_jniGetPixelData(JNIEnv *env, jobject thiz, jlong handle) { auto fn = [&]() { return ((tiny_dnn::image<unsigned char>*) handle)->data(); }; std::vector<unsigned char> ret; if (!jniTryCatch(env, fn, ret)) { ret = std::vector<unsigned char>(0); } jbyte* jbyteBuffer = new jbyte[ret.size()]; std::copy(ret.begin(), ret.end(), jbyteBuffer); jbyteArray ret2 = env->NewByteArray((jsize)ret.size()); env->SetByteArrayRegion(ret2, 0, (jsize)ret.size(), jbyteBuffer); return ret2; } extern "C" JNIEXPORT jint JNICALL Java_com_viveret_tinydnn_data_graphics_LayerImage_jniGetFormat(JNIEnv *env, jobject thiz, jlong handle) { auto fn = [&]() { return ((tiny_dnn::image<unsigned char> *) handle)->type(); }; tiny_dnn::image_type ret; if (jniTryCatch(env, fn, ret)) { return (jint) ret; } else { return -1; } } extern "C" JNIEXPORT jlong JNICALL Java_com_viveret_tinydnn_data_graphics_LayerImage_jniGetWidth(JNIEnv *env, jobject thiz, jlong handle) { auto fn = [&]() { return ((tiny_dnn::image<unsigned char> *) handle)->width(); }; jlong ret; if (jniTryCatch(env, fn, ret)) { return ret; } else { return -1; } } extern "C" JNIEXPORT jlong JNICALL Java_com_viveret_tinydnn_data_graphics_LayerImage_jniGetHeight(JNIEnv *env, jobject thiz, jlong handle) { auto fn = [&]() { return ((tiny_dnn::image<unsigned char> *) handle)->height(); }; jlong ret; if (jniTryCatch(env, fn, ret)) { return ret; } else { return -1; } } extern "C" JNIEXPORT jlong JNICALL Java_com_viveret_tinydnn_data_graphics_LayerImage_jniGetDepth(JNIEnv *env, jobject thiz, jlong handle) { auto fn = [&]() { return ((tiny_dnn::image<unsigned char> *) handle)->depth(); }; jlong ret; if (jniTryCatch(env, fn, ret)) { return ret; } else { return -1; } } extern "C" JNIEXPORT jboolean JNICALL Java_com_viveret_tinydnn_data_graphics_LayerImage_jniEmpty(JNIEnv *env, jobject thiz, jlong handle) { auto fn = [&]() { return ((tiny_dnn::image<unsigned char> *) handle)->empty(); }; jboolean ret; if (jniTryCatch(env, fn, ret)) { return ret; } else { return (jboolean) false; } }
#include "pocketn2.h" extern "C" JNIEXPORT jlong JNICALL Java_com_viveret_tinydnn_data_graphics_LayerImage_jniConstructor( JNIEnv *env, jobject thiz, jlong width, jlong height, jlong depth, tiny_dnn::image_type format) { auto fn = [&]() { auto size = new shape3d(width, height, depth); return (jlong)(void*) new tiny_dnn::image<unsigned char>(*size, format); }; jlong ret; if (jniTryCatch(env, fn, ret)) { return ret; } else { return -1; } } extern "C" JNIEXPORT void JNICALL Java_com_viveret_tinydnn_data_graphics_LayerImage_jniResize(JNIEnv *env, jobject thiz, jlong handle, jlong width, jlong height) { auto fn = [&]() { ((tiny_dnn::image<unsigned char> *) handle)->resize(width, height); return true; }; jboolean ret; jniTryCatch(env, fn, ret); } extern "C" JNIEXPORT jbyteArray JNICALL Java_com_viveret_tinydnn_data_graphics_LayerImage_jniGetPixelData(JNIEnv *env, jobject thiz, jlong handle) { auto fn = [&]() { return ((tiny_dnn::image<unsigned char>*) handle)->data(); }; std::vector<unsigned char> ret; if (!jniTryCatch(env, fn, ret))
r); return ret2; } extern "C" JNIEXPORT jint JNICALL Java_com_viveret_tinydnn_data_graphics_LayerImage_jniGetFormat(JNIEnv *env, jobject thiz, jlong handle) { auto fn = [&]() { return ((tiny_dnn::image<unsigned char> *) handle)->type(); }; tiny_dnn::image_type ret; if (jniTryCatch(env, fn, ret)) { return (jint) ret; } else { return -1; } } extern "C" JNIEXPORT jlong JNICALL Java_com_viveret_tinydnn_data_graphics_LayerImage_jniGetWidth(JNIEnv *env, jobject thiz, jlong handle) { auto fn = [&]() { return ((tiny_dnn::image<unsigned char> *) handle)->width(); }; jlong ret; if (jniTryCatch(env, fn, ret)) { return ret; } else { return -1; } } extern "C" JNIEXPORT jlong JNICALL Java_com_viveret_tinydnn_data_graphics_LayerImage_jniGetHeight(JNIEnv *env, jobject thiz, jlong handle) { auto fn = [&]() { return ((tiny_dnn::image<unsigned char> *) handle)->height(); }; jlong ret; if (jniTryCatch(env, fn, ret)) { return ret; } else { return -1; } } extern "C" JNIEXPORT jlong JNICALL Java_com_viveret_tinydnn_data_graphics_LayerImage_jniGetDepth(JNIEnv *env, jobject thiz, jlong handle) { auto fn = [&]() { return ((tiny_dnn::image<unsigned char> *) handle)->depth(); }; jlong ret; if (jniTryCatch(env, fn, ret)) { return ret; } else { return -1; } } extern "C" JNIEXPORT jboolean JNICALL Java_com_viveret_tinydnn_data_graphics_LayerImage_jniEmpty(JNIEnv *env, jobject thiz, jlong handle) { auto fn = [&]() { return ((tiny_dnn::image<unsigned char> *) handle)->empty(); }; jboolean ret; if (jniTryCatch(env, fn, ret)) { return ret; } else { return (jboolean) false; } }
{ ret = std::vector<unsigned char>(0); } jbyte* jbyteBuffer = new jbyte[ret.size()]; std::copy(ret.begin(), ret.end(), jbyteBuffer); jbyteArray ret2 = env->NewByteArray((jsize)ret.size()); env->SetByteArrayRegion(ret2, 0, (jsize)ret.size(), jbyteBuffe
function_block-random_span
[ { "content": "class GeneratePackageAction(val size: Int, val includeFitTo: Boolean, val path: String): ProjectAction {\n\n override val name: String = \"@Generate Package\"\n\n override fun doAction(project: NeuralNetProject): OnSelectedResult { return OnSelectedResult(true) }\n\n}", "file_path": "kt-...
C++
src/core-util/pipe.cpp
rocksat/mLib
1bd996008200b54d0984e957264e03faa24651d2
#ifdef _WIN32 #include <AccCtrl.h> #include <Aclapi.h> namespace ml { Pipe::Pipe() { m_handle = nullptr; } Pipe::~Pipe() { closePipe(); } void Pipe::closePipe() { if(m_handle != nullptr) { FlushFileBuffers(m_handle); DisconnectNamedPipe(m_handle); CloseHandle(m_handle); m_handle = nullptr; } } void Pipe::createPipe(const std::string &pipeName, bool block) { closePipe(); const UINT PipeBufferSize = 100000; DWORD dwRes; PSID pEveryoneSID = nullptr, pAdminSID = nullptr; PACL pACL = nullptr; PSECURITY_DESCRIPTOR pSD = nullptr; EXPLICIT_ACCESS ea[1]; SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY; SID_IDENTIFIER_AUTHORITY SIDAuthNT = SECURITY_NT_AUTHORITY; SECURITY_ATTRIBUTES attributes; HKEY hkSub = nullptr; BOOL success = AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pEveryoneSID); MLIB_ASSERT_STR(success != FALSE, "AllocateAndInitializeSid failed in Pipe::CreatePipe"); ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS)); ea[0].grfAccessPermissions = FILE_ALL_ACCESS; ea[0].grfAccessMode = SET_ACCESS; ea[0].grfInheritance= NO_INHERITANCE; ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID; ea[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; ea[0].Trustee.ptstrName = (LPTSTR) pEveryoneSID; dwRes = SetEntriesInAcl(1, ea, nullptr, &pACL); MLIB_ASSERT_STR(dwRes == ERROR_SUCCESS, "SetEntriesInAcl failed in Pipe::CreatePipe"); pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH); MLIB_ASSERT_STR(pSD != nullptr, "LocalAlloc failed in Pipe::CreatePipe"); success = InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION); MLIB_ASSERT_STR(success != FALSE, "InitializeSecurityDescriptor failed in Pipe::CreatePipe"); success = SetSecurityDescriptorDacl(pSD, TRUE, pACL, FALSE); MLIB_ASSERT_STR(success != FALSE, "SetSecurityDescriptorDacl failed in Pipe::CreatePipe"); attributes.nLength = sizeof(SECURITY_ATTRIBUTES); attributes.lpSecurityDescriptor = pSD; attributes.bInheritHandle = FALSE; std::string fullPipeName = std::string("\\\\.\\pipe\\") + pipeName; m_handle = CreateNamedPipeA( fullPipeName.c_str(), PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, PipeBufferSize, PipeBufferSize, NMPWAIT_USE_DEFAULT_WAIT, &attributes); MLIB_ASSERT_STR(m_handle != INVALID_HANDLE_VALUE, "CreateNamedPipe failed in Pipe::CreatePipe"); if(block) { std::cout << "Pipe created, waiting for connection" << std::endl; BOOL Connected = (ConnectNamedPipe(m_handle, nullptr) != 0); MLIB_ASSERT_STR(Connected != FALSE, "ConnectNamedPipe failed in Pipe::CreatePipe"); std::cout << "Connected" << std::endl; } else { } } void Pipe::connectToLocalPipe(const std::string &pipeName) { connectToPipe(std::string("\\\\.\\pipe\\") + pipeName); } void Pipe::connectToPipe(const std::string &pipeName) { closePipe(); bool done = false; while(!done) { m_handle = CreateFileA( pipeName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr); if(m_handle != INVALID_HANDLE_VALUE) { done = true; } Sleep(100); } DWORD mode = PIPE_READMODE_BYTE; BOOL success = SetNamedPipeHandleState( m_handle, &mode, nullptr, nullptr); MLIB_ASSERT_STR(success != FALSE, "SetNamedPipeHandleState failed in Pipe::ConnectToPipe"); } bool Pipe::messagePresent() { MLIB_ASSERT_STR(m_handle != nullptr, "Pipe invalid in Pipe::MessagePresent"); DWORD BytesReady = 0; DWORD BytesLeft = 0; BOOL success = PeekNamedPipe( m_handle, nullptr, 0, nullptr, &BytesReady, &BytesLeft); return (BytesReady > 0); } bool Pipe::readMessage(std::vector<BYTE> &Message) { MLIB_ASSERT_STR(m_handle != nullptr, "Pipe invalid in Pipe::ReadMessage"); DWORD BytesReady = 0; BOOL success = PeekNamedPipe( m_handle, nullptr, 0, nullptr, &BytesReady, nullptr); MLIB_ASSERT_STR(success != FALSE, "PeekNamedPipe failed in Pipe::ReadMessage"); Message.resize(BytesReady); if(BytesReady == 0) { return false; } DWORD BytesRead; success = ReadFile( m_handle, &Message[0], (DWORD)Message.size(), &BytesRead, nullptr); MLIB_ASSERT_STR(success != FALSE && BytesRead > 0, "ReadFile failed in Pipe::ReadMessage"); return true; } void Pipe::sendMessage(const std::vector<BYTE> &Message) { sendMessage(&Message[0], (UINT)Message.size()); } void Pipe::sendMessage(const std::string &message) { sendMessage((const BYTE *)message.c_str(), (UINT)message.size()); std::string endLine; endLine.push_back('\n'); sendMessage((const BYTE *)endLine.c_str(), 1); } void Pipe::sendMessage(const BYTE *Message, UINT MessageLength) { if(Message == nullptr || MessageLength == 0) return; MLIB_ASSERT_STR(m_handle != nullptr, "Pipe invalid in Pipe::SendMessage"); DWORD BytesWritten; BOOL success = WriteFile( m_handle, Message, MessageLength, &BytesWritten, nullptr); if (success == FALSE) MLIB_WARNING("WriteFile failed in Pipe::ReadMessage"); if (BytesWritten != MessageLength) MLIB_WARNING("WriteFile failed to send entire message in Pipe::ReadMessage"); } UINT Pipe::activeInstances() { MLIB_ASSERT_STR(m_handle != nullptr, "Pipe invalid in Pipe::ActiveInstances"); DWORD Instances; BOOL success = GetNamedPipeHandleState( m_handle, nullptr, &Instances, nullptr, nullptr, nullptr, 0); MLIB_ASSERT_STR(success != FALSE, "GetNamedPipeHandleState failed in Pipe::ActiveInstances"); return Instances; } std::string Pipe::userName() { MLIB_ASSERT_STR(m_handle != nullptr, "Pipe invalid in Pipe::UserName"); char buffer[512]; BOOL success = GetNamedPipeHandleStateA( m_handle, nullptr, nullptr, nullptr, nullptr, buffer, 512); MLIB_ASSERT_STR(success != FALSE, "GetNamedPipeHandleState failed in Pipe::UserName"); return std::string(buffer); } bool Pipe::valid() { return (m_handle != nullptr); } } #endif
#ifdef _WIN32 #include <AccCtrl.h> #include <Aclapi.h> namespace ml { Pipe::Pipe() { m_handle = nullptr; } Pipe::~Pipe() { closePipe(); } void Pipe::closePipe() { if(m_handle != nullptr) { FlushFileBuffers(m_handle); DisconnectNamedPipe(m_handle); CloseHandle(m_handle); m_handle = nullptr; } } void Pipe::createPipe(const std::string &pipeName, bool block) { closePipe(); const UINT PipeBufferSize = 100000; DWORD dwRes; PSID pEveryoneSID = nullptr, pAdminSID = nullptr; PACL pACL = nullptr; PSECURITY_DESCRIPTOR pSD = nullptr; EXPLICIT_ACCESS ea[1]; SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY; SID_IDENTIFIER_AUTHORITY SIDAuthNT = SECURITY_NT_AUTHORITY; SECURITY_ATTRIBUTES attributes; HKEY hkSub = nullptr; BOOL success = AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pEveryoneSID); MLIB_ASSERT_STR(success != FALSE, "AllocateAndInitializeSid failed in Pipe::CreatePipe"); ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS)); ea[0].grfAccessPermissions = FILE_ALL_ACCESS; ea[0].grfAccessMode = SET_ACCESS; ea[0].grfInheritance= NO_INHERITANCE; ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID; ea[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; ea[0].Trustee.ptstrName = (LPTSTR) pEveryoneSID; dwRes = SetEntriesInAcl(1, ea, nullptr, &pACL); MLIB_ASSERT_STR(dwRes == ERROR_SUCCESS, "SetEntriesInAcl failed in Pipe::CreatePipe"); pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH); MLIB_ASSERT_STR(pSD != nullptr, "LocalAlloc failed in Pipe::CreatePipe"); success = InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION); MLIB_ASSERT_STR(success != FALSE, "InitializeSecurityDescriptor failed in Pipe::CreatePipe"); success = SetSecurityDescriptorDacl(pSD, TRUE, pACL, FALSE); MLIB_ASSERT_STR(success != FALSE, "SetSecurityDescriptorDacl failed in Pipe::CreatePipe"); attributes.nLength = sizeof(SECURITY_ATTRIBUTES); attributes.lpSecurityDescriptor = pSD; attributes.bInheritHandle = FALSE; std::string fullPipeName = std::string("\\\\.\\pipe\\") + pipeName; m_handle = CreateNamedPipeA( fullPipeName.c_str(), PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, PipeBufferSize, PipeBufferSize, NMPWAIT_USE_DEFAULT_WAIT, &attributes); MLIB_ASSERT_STR(m_handle != INVALID_HANDLE_VALUE, "CreateNamedPipe failed in Pipe::CreatePipe"); if(block) { std::cout << "Pipe created, waiting for connection" << std::endl; BOOL Connected = (ConnectNamedPipe(m_handle, nullptr) != 0); MLIB_ASSERT_STR(Connected != FALSE, "ConnectNamedPipe failed in Pipe::CreatePipe"); std::cout << "Connected" << std::endl; } else { } } void Pipe::connectToLocalPipe(const std::string &pipeName) { connectToPipe(std::string("\\\\.\\pipe\\") + pipeName); } void Pipe::connectToPipe(const std::string &pipeName) { closePipe(); bool done = false; while(!done) { m_handle = CreateFileA( pipeName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr); if(m_handle != INVALID_HANDLE_VALUE) { done = true; } Sleep(100); } DWORD mode = PIPE_READMODE_BYTE; BOOL success = SetNamedPipeHandleState( m_handle, &mode, nullptr, nullptr); MLIB_ASSERT_STR(success != FALSE, "SetNamedPipeHandleState failed in Pipe::ConnectToPipe"); } bool Pipe::messagePresent() { MLIB_ASSERT_STR(m_handle != nullptr, "Pipe invali
m_handle, nullptr, 0, nullptr, &BytesReady, &BytesLeft); return (BytesReady > 0); } bool Pipe::readMessage(std::vector<BYTE> &Message) { MLIB_ASSERT_STR(m_handle != nullptr, "Pipe invalid in Pipe::ReadMessage"); DWORD BytesReady = 0; BOOL success = PeekNamedPipe( m_handle, nullptr, 0, nullptr, &BytesReady, nullptr); MLIB_ASSERT_STR(success != FALSE, "PeekNamedPipe failed in Pipe::ReadMessage"); Message.resize(BytesReady); if(BytesReady == 0) { return false; } DWORD BytesRead; success = ReadFile( m_handle, &Message[0], (DWORD)Message.size(), &BytesRead, nullptr); MLIB_ASSERT_STR(success != FALSE && BytesRead > 0, "ReadFile failed in Pipe::ReadMessage"); return true; } void Pipe::sendMessage(const std::vector<BYTE> &Message) { sendMessage(&Message[0], (UINT)Message.size()); } void Pipe::sendMessage(const std::string &message) { sendMessage((const BYTE *)message.c_str(), (UINT)message.size()); std::string endLine; endLine.push_back('\n'); sendMessage((const BYTE *)endLine.c_str(), 1); } void Pipe::sendMessage(const BYTE *Message, UINT MessageLength) { if(Message == nullptr || MessageLength == 0) return; MLIB_ASSERT_STR(m_handle != nullptr, "Pipe invalid in Pipe::SendMessage"); DWORD BytesWritten; BOOL success = WriteFile( m_handle, Message, MessageLength, &BytesWritten, nullptr); if (success == FALSE) MLIB_WARNING("WriteFile failed in Pipe::ReadMessage"); if (BytesWritten != MessageLength) MLIB_WARNING("WriteFile failed to send entire message in Pipe::ReadMessage"); } UINT Pipe::activeInstances() { MLIB_ASSERT_STR(m_handle != nullptr, "Pipe invalid in Pipe::ActiveInstances"); DWORD Instances; BOOL success = GetNamedPipeHandleState( m_handle, nullptr, &Instances, nullptr, nullptr, nullptr, 0); MLIB_ASSERT_STR(success != FALSE, "GetNamedPipeHandleState failed in Pipe::ActiveInstances"); return Instances; } std::string Pipe::userName() { MLIB_ASSERT_STR(m_handle != nullptr, "Pipe invalid in Pipe::UserName"); char buffer[512]; BOOL success = GetNamedPipeHandleStateA( m_handle, nullptr, nullptr, nullptr, nullptr, buffer, 512); MLIB_ASSERT_STR(success != FALSE, "GetNamedPipeHandleState failed in Pipe::UserName"); return std::string(buffer); } bool Pipe::valid() { return (m_handle != nullptr); } } #endif
d in Pipe::MessagePresent"); DWORD BytesReady = 0; DWORD BytesLeft = 0; BOOL success = PeekNamedPipe(
function_block-random_span
[ { "content": "class Pipe\n\n{\n\npublic:\n\n Pipe();\n\n ~Pipe();\n\n \n\n //\n\n // Connection\n\n //\n\n void closePipe();\n\n void createPipe(const std::string &pipeName, bool block);\n\n void connectToLocalPipe(const std::string &pipeName);\n\n void connectToPipe(const std::str...
C++
libcat/src/cat_storage_resmgr.cpp
shadow-paw/cat
975749c9d716687f1bd74c80d474fed6065768de
#include "cat_storage_resmgr.h" #include <new> #include <string.h> #include <png.h> using namespace cat; ResourceManager::ResourceManager(VFS* vfs) { m_contextready = false; m_vfs = vfs; } ResourceManager::~ResourceManager() { fini(); } bool ResourceManager::init() { return true; } void ResourceManager::fini() { context_lost(); m_shaders.clear(); m_texs.clear(); } void ResourceManager::context_lost() { if (!m_contextready) return; m_contextready = false; for (auto& it : m_shaders) { it.second.first.shader->fini(); } for (auto& it : m_texs) { it.second.first->release(); } } bool ResourceManager::context_restored() { if (m_contextready) return true; m_contextready = true; for (auto it: m_shaders) { reload_shader(&it.second.first, it.first); } for (auto it : m_texs) { reload_tex(it.second.first, it.first); } return true; } const Shader* ResourceManager::retain_shader(const std::string& name, const std::unordered_map<int, std::string>& uniforms, const std::unordered_map<int, std::string>& attrs) { Buffer buffer; auto cached = m_shaders.find(name); if (cached!=m_shaders.end()) { auto& pair = cached->second; pair.second ++; return pair.first.shader; } Shader* shader = new (std::nothrow) Shader(); if (!shader) return nullptr; if (m_contextready) { if (!m_vfs->read(name, &buffer)) return nullptr; if (!shader->init((const char*)buffer.ptr(), (const char*)buffer.ptr())) { delete shader; return nullptr; } shader->bind(); for (auto it : uniforms) { shader->bind_uniform(it.first, it.second.c_str()); } for (auto it : attrs) { shader->bind_attr(it.first, it.second.c_str()); } shader->unbind(); } m_shaders.emplace(name, std::make_pair(SHADER_DATA{ shader, uniforms, attrs }, 1)); return shader; } bool ResourceManager::reload_shader(SHADER_DATA* sd, const std::string& name) { std::string path(name); Buffer buffer; if (!m_vfs->read(path, &buffer)) return false; if (!sd->shader->init((const char*)buffer.ptr(), (const char*)buffer.ptr())) return false; sd->shader->bind(); for (auto it : sd->uniforms) { sd->shader->bind_uniform(it.first, it.second.c_str()); } for (auto it : sd->attrs) { sd->shader->bind_attr(it.first, it.second.c_str()); } sd->shader->unbind(); return true; } bool ResourceManager::release_shader(const std::string& name) { auto cached = m_shaders.find(name); if (cached == m_shaders.end()) return false; auto& pair = cached->second; pair.second --; if (pair.second == 0) { delete pair.first.shader; m_shaders.erase(name); } return true; } bool ResourceManager::release_shader(const Shader* shader) { if (shader == nullptr ) return false; for (auto it=m_shaders.begin(); it!=m_shaders.end(); ++it) { auto& pair = it->second; if (pair.first.shader != shader) continue; pair.second --; if (pair.second == 0) { delete pair.first.shader; m_shaders.erase(it); } return true; } return false; } const Texture* ResourceManager::retain_tex(const std::string& name) { Buffer buffer; auto cached = m_texs.find(name); if (cached!=m_texs.end()) { auto& pair = cached->second; pair.second ++; return pair.first; } Texture* tex = new (std::nothrow) Texture(); if (!tex) return nullptr; if (m_contextready) { if (!m_vfs->read(name, &buffer)) return nullptr; if (!load_tex_png(tex, buffer)) { delete tex; return nullptr; } } m_texs.emplace(name, std::make_pair(tex, 1)); return tex; } bool ResourceManager::reload_tex(Texture* tex, const std::string& name) { Buffer buffer; if (!m_vfs->read(name.c_str(), &buffer)) return false; return load_tex_png(tex, buffer); } bool ResourceManager::release_tex(const std::string& name) { auto cached = m_texs.find(name); if (cached == m_texs.end()) return false; auto& pair = cached->second; pair.second --; if (pair.second == 0) { delete pair.first; m_texs.erase(name); } return true; } bool ResourceManager::release_tex(const Texture* tex) { if (tex == nullptr ) return false; for (auto it=m_texs.begin(); it!=m_texs.end(); ++it) { auto& pair = it->second; if (pair.first != tex) continue; pair.second --; if (pair.second == 0) { delete pair.first; m_texs.erase(it); } return true; } return false; } const Buffer* ResourceManager::retain_raw(const std::string& name) { auto cached = m_raws.find(name); if (cached != m_raws.end()) { auto& pair = cached->second; pair.second++; return pair.first; } Buffer* buffer = new Buffer(); if (!m_vfs->read(name, buffer)) { delete buffer; return nullptr; } m_raws.emplace(name, std::make_pair(buffer, 1)); return buffer; } bool ResourceManager::release_raw(const std::string& name) { auto cached = m_raws.find(name); if (cached == m_raws.end()) return false; auto& pair = cached->second; pair.second--; if (pair.second == 0) { delete pair.first; m_raws.erase(name); } return true; } bool ResourceManager::release_raw(const Buffer* buffer) { if (buffer == nullptr) return false; for (auto it = m_raws.begin(); it != m_raws.end(); ++it) { auto& pair = it->second; if (pair.first != buffer) continue; pair.second--; if (pair.second == 0) { delete pair.first; m_raws.erase(it); } return true; } return false; } typedef struct { Buffer* buffer; size_t offset; } PNGBufferReader; void _png_read(png_structp png, png_bytep data, png_size_t size) { PNGBufferReader* br = (PNGBufferReader*) png_get_io_ptr(png); if ( br->offset + size <= br->buffer->size() ) { memcpy ( data, br->buffer->ptr() + br->offset, size ); br->offset += size; } } bool ResourceManager::load_tex_png(Texture* tex, Buffer& buf) { Texture::Format format; unsigned int width, height; uint8_t* pixel = nullptr; png_structp png = NULL; png_infop info = NULL; png_bytepp row_pointers; size_t row_bytes; PNGBufferReader bufreader; if (png_sig_cmp(buf.ptr(), 0, 8)) goto fail; png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (png == NULL) goto fail; info = png_create_info_struct(png); if (info == NULL) goto fail; if (setjmp(png_jmpbuf(png))) goto fail; bufreader.buffer = &buf; bufreader.offset = 8; png_set_read_fn(png, &bufreader, _png_read); png_set_sig_bytes(png, 8); png_read_png(png, info, PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING | PNG_TRANSFORM_EXPAND, NULL); switch ( png_get_color_type(png, info) ) { case PNG_COLOR_TYPE_RGBA: format = Texture::Format::RGBA; break; case PNG_COLOR_TYPE_RGB: format = Texture::Format::RGB; break; default: goto fail; } row_bytes = png_get_rowbytes(png, info); width = (unsigned int)png_get_image_width(png, info); height = (unsigned int)png_get_image_height(png, info); if (width > 4096 || height > 4096) goto fail; pixel = new (std::nothrow) uint8_t[row_bytes * height]; if (!pixel) goto fail; row_pointers = png_get_rows(png, info); for (unsigned int i = 0; i < height; i++) { memcpy( pixel + (row_bytes * (height-1-i)), row_pointers[i], row_bytes ); } png_destroy_read_struct(&png, &info, NULL); tex->update(format, (int)width, (int)height, pixel); delete pixel; return true; fail: png_destroy_read_struct(&png, &info, NULL); delete pixel; return false; }
#include "cat_storage_resmgr.h" #include <new> #include <string.h> #include <png.h> using namespace cat; ResourceManager::ResourceManager(VFS* vfs) { m_contextready = false; m_vfs = vfs; } ResourceManager::~ResourceManager() { fini(); } bool ResourceManager::init() { return true; } void ResourceManager::fini() { context_lost(); m_shaders.clear(); m_texs.clear(); } void ResourceManager::context_lost() { if (!m_contextready) return; m_contextready = false; for (auto& it : m_shaders) { it.second.first.shader->fini(); } for (auto& it : m_texs) { it.second.first->release(); } }
const Shader* ResourceManager::retain_shader(const std::string& name, const std::unordered_map<int, std::string>& uniforms, const std::unordered_map<int, std::string>& attrs) { Buffer buffer; auto cached = m_shaders.find(name); if (cached!=m_shaders.end()) { auto& pair = cached->second; pair.second ++; return pair.first.shader; } Shader* shader = new (std::nothrow) Shader(); if (!shader) return nullptr; if (m_contextready) { if (!m_vfs->read(name, &buffer)) return nullptr; if (!shader->init((const char*)buffer.ptr(), (const char*)buffer.ptr())) { delete shader; return nullptr; } shader->bind(); for (auto it : uniforms) { shader->bind_uniform(it.first, it.second.c_str()); } for (auto it : attrs) { shader->bind_attr(it.first, it.second.c_str()); } shader->unbind(); } m_shaders.emplace(name, std::make_pair(SHADER_DATA{ shader, uniforms, attrs }, 1)); return shader; } bool ResourceManager::reload_shader(SHADER_DATA* sd, const std::string& name) { std::string path(name); Buffer buffer; if (!m_vfs->read(path, &buffer)) return false; if (!sd->shader->init((const char*)buffer.ptr(), (const char*)buffer.ptr())) return false; sd->shader->bind(); for (auto it : sd->uniforms) { sd->shader->bind_uniform(it.first, it.second.c_str()); } for (auto it : sd->attrs) { sd->shader->bind_attr(it.first, it.second.c_str()); } sd->shader->unbind(); return true; } bool ResourceManager::release_shader(const std::string& name) { auto cached = m_shaders.find(name); if (cached == m_shaders.end()) return false; auto& pair = cached->second; pair.second --; if (pair.second == 0) { delete pair.first.shader; m_shaders.erase(name); } return true; } bool ResourceManager::release_shader(const Shader* shader) { if (shader == nullptr ) return false; for (auto it=m_shaders.begin(); it!=m_shaders.end(); ++it) { auto& pair = it->second; if (pair.first.shader != shader) continue; pair.second --; if (pair.second == 0) { delete pair.first.shader; m_shaders.erase(it); } return true; } return false; } const Texture* ResourceManager::retain_tex(const std::string& name) { Buffer buffer; auto cached = m_texs.find(name); if (cached!=m_texs.end()) { auto& pair = cached->second; pair.second ++; return pair.first; } Texture* tex = new (std::nothrow) Texture(); if (!tex) return nullptr; if (m_contextready) { if (!m_vfs->read(name, &buffer)) return nullptr; if (!load_tex_png(tex, buffer)) { delete tex; return nullptr; } } m_texs.emplace(name, std::make_pair(tex, 1)); return tex; } bool ResourceManager::reload_tex(Texture* tex, const std::string& name) { Buffer buffer; if (!m_vfs->read(name.c_str(), &buffer)) return false; return load_tex_png(tex, buffer); } bool ResourceManager::release_tex(const std::string& name) { auto cached = m_texs.find(name); if (cached == m_texs.end()) return false; auto& pair = cached->second; pair.second --; if (pair.second == 0) { delete pair.first; m_texs.erase(name); } return true; } bool ResourceManager::release_tex(const Texture* tex) { if (tex == nullptr ) return false; for (auto it=m_texs.begin(); it!=m_texs.end(); ++it) { auto& pair = it->second; if (pair.first != tex) continue; pair.second --; if (pair.second == 0) { delete pair.first; m_texs.erase(it); } return true; } return false; } const Buffer* ResourceManager::retain_raw(const std::string& name) { auto cached = m_raws.find(name); if (cached != m_raws.end()) { auto& pair = cached->second; pair.second++; return pair.first; } Buffer* buffer = new Buffer(); if (!m_vfs->read(name, buffer)) { delete buffer; return nullptr; } m_raws.emplace(name, std::make_pair(buffer, 1)); return buffer; } bool ResourceManager::release_raw(const std::string& name) { auto cached = m_raws.find(name); if (cached == m_raws.end()) return false; auto& pair = cached->second; pair.second--; if (pair.second == 0) { delete pair.first; m_raws.erase(name); } return true; } bool ResourceManager::release_raw(const Buffer* buffer) { if (buffer == nullptr) return false; for (auto it = m_raws.begin(); it != m_raws.end(); ++it) { auto& pair = it->second; if (pair.first != buffer) continue; pair.second--; if (pair.second == 0) { delete pair.first; m_raws.erase(it); } return true; } return false; } typedef struct { Buffer* buffer; size_t offset; } PNGBufferReader; void _png_read(png_structp png, png_bytep data, png_size_t size) { PNGBufferReader* br = (PNGBufferReader*) png_get_io_ptr(png); if ( br->offset + size <= br->buffer->size() ) { memcpy ( data, br->buffer->ptr() + br->offset, size ); br->offset += size; } } bool ResourceManager::load_tex_png(Texture* tex, Buffer& buf) { Texture::Format format; unsigned int width, height; uint8_t* pixel = nullptr; png_structp png = NULL; png_infop info = NULL; png_bytepp row_pointers; size_t row_bytes; PNGBufferReader bufreader; if (png_sig_cmp(buf.ptr(), 0, 8)) goto fail; png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (png == NULL) goto fail; info = png_create_info_struct(png); if (info == NULL) goto fail; if (setjmp(png_jmpbuf(png))) goto fail; bufreader.buffer = &buf; bufreader.offset = 8; png_set_read_fn(png, &bufreader, _png_read); png_set_sig_bytes(png, 8); png_read_png(png, info, PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING | PNG_TRANSFORM_EXPAND, NULL); switch ( png_get_color_type(png, info) ) { case PNG_COLOR_TYPE_RGBA: format = Texture::Format::RGBA; break; case PNG_COLOR_TYPE_RGB: format = Texture::Format::RGB; break; default: goto fail; } row_bytes = png_get_rowbytes(png, info); width = (unsigned int)png_get_image_width(png, info); height = (unsigned int)png_get_image_height(png, info); if (width > 4096 || height > 4096) goto fail; pixel = new (std::nothrow) uint8_t[row_bytes * height]; if (!pixel) goto fail; row_pointers = png_get_rows(png, info); for (unsigned int i = 0; i < height; i++) { memcpy( pixel + (row_bytes * (height-1-i)), row_pointers[i], row_bytes ); } png_destroy_read_struct(&png, &info, NULL); tex->update(format, (int)width, (int)height, pixel); delete pixel; return true; fail: png_destroy_read_struct(&png, &info, NULL); delete pixel; return false; }
bool ResourceManager::context_restored() { if (m_contextready) return true; m_contextready = true; for (auto it: m_shaders) { reload_shader(&it.second.first, it.first); } for (auto it : m_texs) { reload_tex(it.second.first, it.first); } return true; }
function_block-full_function
[ { "content": "namespace cat {\n\n// ----------------------------------------------------------------------------\n\n// UI Event\n\n// ----------------------------------------------------------------------------\n\nstruct TouchEvent {\n\n enum EventType { TouchDown, TouchUp, TouchMove, Scroll };\n\n EventT...
C++
examples/classes/slider/sliderx.cpp
pierrebestwork/owl642
3f4aa9ec0febc52acd3523f0b6ba063d5e388365
#include <owl/applicat.h> #include <owl/framewin.h> #include <owl/slider.h> #include <owl/gauge.h> #include <owl/static.h> using namespace owl; class TMainWindow : public TWindow { public: TMainWindow(); protected: virtual void SetupWindow(); void EvTimer(uint timerId); private: enum { IDC_THERMOSTAT = 201, IDC_HEATERTIME, IDC_OUTSIDETEMP, IDC_STATICTEMP, IDC_STATICTIME, IDC_STATICOTEMP, IDC_THERMOMETER, }; enum {IDT_REFRESH = 1}; double Temp; bool IsHeaterOn; TStatic TempStatic; TGauge ThermometerGauge; THSlider ThermostatSlider; TStatic HysteresisStatic; TVSlider HysteresisSlider; TStatic OutsideTempStatic; TVSlider OutsideTempSlider; void UpdateTemp(); void UpdateHysteresis(uint = 0); void UpdateOutsideTemp(uint = 0); void SimulateHeater(); DECLARE_RESPONSE_TABLE(TMainWindow); }; DEFINE_RESPONSE_TABLE1(TMainWindow, TWindow) EV_WM_TIMER, EV_CHILD_NOTIFY_ALL_CODES(IDC_HEATERTIME, UpdateHysteresis), EV_CHILD_NOTIFY_ALL_CODES(IDC_OUTSIDETEMP, UpdateOutsideTemp), END_RESPONSE_TABLE; TMainWindow::TMainWindow() : TWindow(0, 0, 0), Temp(40.0), IsHeaterOn(false), TempStatic(this, IDC_STATICTEMP, "", 110, 30, 160, 17, 0), ThermometerGauge(this, "%d\xB0", IDC_THERMOMETER, 70, 70, 240, 24, true, 2), ThermostatSlider(this, IDC_THERMOSTAT, 70, 110, 240, 40), HysteresisStatic(this, IDC_STATICTIME, "", 4, 10, 160, 17, 0), HysteresisSlider(this, IDC_HEATERTIME, 20, 30, 32, 160), OutsideTempStatic(this, IDC_STATICOTEMP, "", 216, 10, 160, 17, 0), OutsideTempSlider(this, IDC_OUTSIDETEMP, 330, 30, 32, 160) { MoveWindow(0, 0, 380, 200); SetBkgndColor(TColor::Sys3dFace); TempStatic.ModifyStyle(0, SS_CENTER); ThermostatSlider.ModifyStyle(0, TBS_AUTOTICKS); HysteresisStatic.ModifyStyle(0, SS_LEFT); HysteresisSlider.ModifyStyle(0, TBS_AUTOTICKS); OutsideTempStatic.ModifyStyle(0, SS_RIGHT); OutsideTempSlider.ModifyStyle(0, TBS_AUTOTICKS); } void TMainWindow::SetupWindow() { TWindow::SetupWindow(); ThermometerGauge.SetRange(40, 120); ThermometerGauge.SetValue(80); ThermostatSlider.SetRange(40, 120); ThermostatSlider.SetRuler(10, false); ThermostatSlider.SetPosition(80); HysteresisSlider.SetRange(0, 10); HysteresisSlider.SetRuler(5, false); HysteresisSlider.SetPosition(5); OutsideTempSlider.SetRange(20, 90); OutsideTempSlider.SetRuler(10, false); OutsideTempSlider.SetPosition(40); SetTimer(IDT_REFRESH, 1000); UpdateTemp(); UpdateHysteresis(); UpdateOutsideTemp(); } void TMainWindow::EvTimer(uint ) { SimulateHeater(); UpdateTemp(); } void TMainWindow::UpdateTemp() { std::ostringstream s; s << "Heater is " << (IsHeaterOn ? "on" : "off"); TempStatic.SetText(s.str()); ThermometerGauge.SetValue(static_cast<int>(Temp + 0.5)); } void TMainWindow::UpdateHysteresis(uint) { std::ostringstream s; s << HysteresisSlider.GetPosition() << "\xB0 hysteresis"; HysteresisStatic.SetText(s.str()); } void TMainWindow::UpdateOutsideTemp(uint) { std::ostringstream s; s << OutsideTempSlider.GetPosition() << "\xB0 outside"; OutsideTempStatic.SetText(s.str()); } void TMainWindow::SimulateHeater() { Temp += (IsHeaterOn ? 2.0 : 0.0) + (OutsideTempSlider.GetPosition() - Temp) / 40.0; int tempSetting = ThermostatSlider.GetPosition(); int hysteresis = HysteresisSlider.GetPosition(); double lowTriggerTemp = tempSetting - hysteresis; double highTriggerTemp = tempSetting + hysteresis; if (!IsHeaterOn && Temp <= lowTriggerTemp) IsHeaterOn = true; else if (IsHeaterOn && Temp >= highTriggerTemp) IsHeaterOn = false; } class THomeHeaterSimulator : public TApplication { public: THomeHeaterSimulator() : TApplication("Home Heater Simulator") {} protected: virtual void InitMainWindow() { TFrameWindow* frame = new TFrameWindow(0, GetName(), new TMainWindow, true); frame->ModifyStyle(WS_SIZEBOX | WS_MAXIMIZEBOX, 0); frame->EnableKBHandler(); SetMainWindow(frame); } }; int OwlMain(int, char* []) { THomeHeaterSimulator app; return app.Run(); }
#include <owl/applicat.h> #include <owl/framewin.h> #include <owl/slider.h> #include <owl/gauge.h> #include <owl/static.h> using namespace owl; class TMainWindow : public TWindow { public: TMainWindow(); protected: virtual void SetupWindow(); void EvTimer(uint timerId); private: enum { IDC_THERMOSTAT = 201, IDC_HEATERTIME, IDC_OUTSIDETEMP, IDC_STATICTEMP, IDC_STATICTIME, IDC_STATICOTEMP, IDC_THERMOMETER, }; enum {IDT_REFRESH = 1}; double Temp; bool IsHeaterOn; TStatic TempStatic; TGauge ThermometerGauge; THSlider ThermostatSlider; TStatic HysteresisStatic; TVSlider HysteresisSlider; TStatic OutsideTempStatic; TVSlider OutsideTempSlider; void UpdateTemp(); void UpdateHysteresis(uint = 0); void UpdateOutsideTemp(uint = 0); void SimulateHeater(); DECLARE_RESPONSE_TABLE(TMainWindow); }; DEFINE_RESPONSE_TABLE1(TMainWindow, TWindow) EV_WM_TIMER, EV_CHILD_NOTIFY_ALL_CODES(IDC_HEATERTIME, UpdateHysteresis), EV_CHILD_NOTIFY_ALL_CODES(IDC_OUTSIDETEMP, UpdateOutsideTemp), END_RESPONSE_TABLE; TMainWindow::TMainWindow() : TWindow(0, 0, 0), Temp(40.0), IsHeaterOn(false), TempStatic(this, IDC_STATICTEMP, "", 110, 30, 160, 17, 0), ThermometerGauge(this, "%d\xB0", IDC_THERMOMETER, 70, 70, 240, 24, true, 2), ThermostatSlider(this, IDC_THERMOSTAT, 70, 110, 240, 40), HysteresisStatic(this, IDC_STATICTIME, "", 4, 10, 160, 17, 0), HysteresisSlider(this, IDC_HEATERTIME, 20, 30, 32, 160), OutsideTempStatic(this, IDC_STATICOTEMP, "", 216, 10, 160, 17, 0), OutsideTempSlider(this, IDC_OUTSIDETEMP, 330, 30, 32, 160) { MoveWindow(0, 0, 380, 200); SetBkgndColor(TColor::Sys3dFace); TempStatic.ModifyStyle(0, SS_CENTER); ThermostatSlider.ModifyStyle(0, TBS_AUTOTICKS); HysteresisStatic.ModifyStyle(0, SS_LEFT); HysteresisSlider.ModifyStyle(0, TBS_AUTOTICKS); OutsideTempStatic.ModifyStyle(0, SS_RIGHT); OutsideTempSlider.ModifyStyle(0, TBS_AUTOTICKS); } void TMainWindow::SetupWindow() { TWindow::SetupWindow(); ThermometerGauge.SetRange(40, 120); ThermometerGauge.SetValue(80); ThermostatSlider.SetRange(40, 120); ThermostatSlider.SetRuler(10, false); ThermostatSlider.SetPosition(80); HysteresisSlider.SetRange(0, 10); HysteresisSlider.SetRuler(5, false); HysteresisSlider.SetPosition(5); OutsideTempSlider.SetRange(20, 90); OutsideTempSlider.SetRuler(10, false); OutsideTempSlider.SetPosition(40); SetTimer(IDT_REFRESH, 1000); UpdateTemp(); UpdateHysteresis(); UpdateOutsideTemp(); } void TMainWindow::EvTimer(uint ) { SimulateHeater(); UpdateTemp(); } void TMainWindow::UpdateTemp() { std::ostringstream s; s << "Heater is " << (IsHeaterOn ? "on" : "off"); TempStatic.SetText(s.str()); ThermometerGauge.SetValue(static_cast<int>(Temp + 0.5)); } void TMainWindow::UpdateHysteresis(uint) { std::ostringstream s; s << HysteresisSlider.GetPosition() << "\xB0 hysteresis"; HysteresisStatic.SetText(s.str()); } void TMainWindow::UpdateOutsideTemp(uint) { std::ostringstream s; s << OutsideTempSlider.GetPosition() << "\xB0 outside"; OutsideTempStatic.SetText(s.str()); } void TMainWindow::SimulateHeater() { Temp += (IsHeaterOn ? 2.0 : 0.0) + (OutsideTempSlider.GetPosition() - Temp) / 40.0; int tempSetting = ThermostatSlider.GetPosition(); int hysteresis = HysteresisSlider.GetPosition(); double lowTriggerTemp = tempSetting - hysteresis; double highTriggerTemp = tempSetting + hysteresis;
} class THomeHeaterSimulator : public TApplication { public: THomeHeaterSimulator() : TApplication("Home Heater Simulator") {} protected: virtual void InitMainWindow() { TFrameWindow* frame = new TFrameWindow(0, GetName(), new TMainWindow, true); frame->ModifyStyle(WS_SIZEBOX | WS_MAXIMIZEBOX, 0); frame->EnableKBHandler(); SetMainWindow(frame); } }; int OwlMain(int, char* []) { THomeHeaterSimulator app; return app.Run(); }
if (!IsHeaterOn && Temp <= lowTriggerTemp) IsHeaterOn = true; else if (IsHeaterOn && Temp >= highTriggerTemp) IsHeaterOn = false;
if_condition
[ { "content": "//----------------------------------------------------------------------------\n\nclass OWLEXTCLASS TNotebook : public virtual owl::TWindow {\n\n public:\n\n //--- redefined functions ---\n\n TNotebook(int tabloc = 0);\n\n ~TNotebook();\n\n void SetTabCnt(int tabcnt, int firsttab = 0,...
C++
src/plugins/lackman/packagesmodel.cpp
devel29a/leechcraft
faf5e856010fb785e4bbf3ce7b5c6a5c49f3239a
#include "packagesmodel.h" #include <QIcon> #include <QApplication> #include <util/util.h> #include "core.h" #include "storage.h" #include "pendingmanager.h" namespace LeechCraft { namespace LackMan { PackagesModel::PackagesModel (QObject *parent) : QAbstractItemModel (parent) { } int PackagesModel::columnCount (const QModelIndex&) const { return Columns::MaxColumn; } QVariant PackagesModel::headerData (int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Vertical) return QVariant (); if (role != Qt::DisplayRole) return QVariant (); switch (section) { case Columns::Inst: return tr ("I"); case Columns::Upd: return tr ("U"); case Columns::Name: return tr ("Name"); case Columns::Description: return tr ("Description"); case Columns::Version: return tr ("Version"); case Columns::Size: return tr ("Size"); default: return "unknown"; } } QVariant PackagesModel::data (const QModelIndex& index, int role) const { const auto& lpi = Packages_.at (index.row ()); const int col = index.column (); switch (role) { case Qt::DisplayRole: switch (col) { case Columns::Name: return lpi.Name_; case Columns::Description: return lpi.ShortDescription_; case Columns::Version: return lpi.Version_; case Columns::Size: { const auto size = Core::Instance ().GetStorage ()->GetPackageSize (lpi.PackageID_); return size > 0 ? Util::MakePrettySize (size) : tr ("unknown"); } default: return QVariant (); } case Qt::DecorationRole: return col != Columns::Name ? QVariant () : Core::Instance ().GetIconForLPI (lpi); case Qt::CheckStateRole: { auto pm = Core::Instance ().GetPendingManager (); switch (col) { case Columns::Inst: if (lpi.IsInstalled_) return pm->GetPendingRemove ().contains (lpi.PackageID_) ? Qt::Unchecked : Qt::Checked; else return pm->GetPendingInstall ().contains (lpi.PackageID_) ? Qt::Checked : Qt::Unchecked; case Columns::Upd: if (!lpi.HasNewVersion_) return {}; return pm->GetPendingUpdate ().contains (lpi.PackageID_) ? Qt::Checked : Qt::Unchecked; default: return {}; } } case PMRPackageID: return lpi.PackageID_; case PMRShortDescription: return lpi.ShortDescription_; case PMRLongDescription: return lpi.LongDescription_; case PMRTags: return lpi.Tags_; case PMRInstalled: return lpi.IsInstalled_; case PMRUpgradable: return lpi.HasNewVersion_; case PMRVersion: return lpi.Version_; case PMRThumbnails: case PMRScreenshots: { QStringList result; for (const auto& img : Core::Instance ().GetStorage ()->GetImages (lpi.Name_)) if (img.Type_ == (role == PMRThumbnails ? Image::TThumbnail : Image::TScreenshot)) result << img.URL_; return result; } case PMRSize: return Core::Instance ().GetStorage ()->GetPackageSize (lpi.PackageID_); default: return {}; } } bool PackagesModel::setData (const QModelIndex& index, const QVariant& value, int role) { if (role != Qt::CheckStateRole) return false; const auto& lpi = Packages_.at (index.row ()); const Qt::CheckState state = static_cast<Qt::CheckState> (value.toInt ()); switch (index.column ()) { case Columns::Inst: { const bool isNewState = (state == Qt::Checked && !lpi.IsInstalled_) || (state == Qt::Unchecked && lpi.IsInstalled_); Core::Instance ().GetPendingManager ()-> ToggleInstallRemove (lpi.PackageID_, isNewState, lpi.IsInstalled_); emit dataChanged (index, index); return true; } case Columns::Upd: Core::Instance ().GetPendingManager ()->ToggleUpdate (lpi.PackageID_, state == Qt::Checked); emit dataChanged (index, index); return true; default: return false; } } Qt::ItemFlags PackagesModel::flags (const QModelIndex& index) const { if (!index.isValid ()) return 0; auto flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable; const auto& lpi = Packages_.at (index.row ()); switch (index.column ()) { case Columns::Inst: flags |= Qt::ItemIsUserCheckable; break; case Columns::Upd: if (lpi.HasNewVersion_) flags |= Qt::ItemIsUserCheckable; break; } return flags; } QModelIndex PackagesModel::index (int row, int column, const QModelIndex& parent) const { if (!hasIndex (row, column, parent)) return QModelIndex (); return createIndex (row, column); } QModelIndex PackagesModel::parent (const QModelIndex&) const { return QModelIndex (); } int PackagesModel::rowCount (const QModelIndex& parent) const { return parent.isValid () ? 0 : Packages_.size (); } void PackagesModel::AddRow (const ListPackageInfo& lpi) { int size = Packages_.size (); beginInsertRows (QModelIndex (), size, size); Packages_ << lpi; endInsertRows (); } void PackagesModel::UpdateRow (const ListPackageInfo& lpi) { for (int i = 0, size = Packages_.size (); i < size; ++i) if (Packages_.at (i).Name_ == lpi.Name_) { Packages_ [i] = lpi; emit dataChanged (index (i, 0), index (i, columnCount () - 1)); break; } } void PackagesModel::RemovePackage (int packageId) { for (int i = 0, size = Packages_.size (); i < size; ++i) if (Packages_.at (i).PackageID_ == packageId) { beginRemoveRows (QModelIndex (), i, i); Packages_.removeAt (i); endRemoveRows (); break; } } ListPackageInfo PackagesModel::FindPackage (const QString& name) const { const auto pos = std::find_if (Packages_.begin (), Packages_.end (), [&name] (const auto& lpi) { return lpi.Name_ == name; }); return pos != Packages_.end () ? *pos : ListPackageInfo {}; } int PackagesModel::GetRow (int packageId) const { for (int i = 0, size = Packages_.size (); i < size; ++i) if (Packages_.at (i).PackageID_ == packageId) return i; return -1; } void PackagesModel::Clear () { beginResetModel (); Packages_.clear (); endResetModel (); } void PackagesModel::handlePackageInstallRemoveToggled (int id) { const auto row = GetRow (id); if (row == -1) { qWarning () << Q_FUNC_INFO << "unknown package ID" << id; return; } const auto& idx = index (row, Columns::Inst); emit dataChanged (idx, idx); } void PackagesModel::handlePackageUpdateToggled (int id) { const auto row = GetRow (id); if (row == -1) { qWarning () << Q_FUNC_INFO << "unknown package ID" << id; return; } const auto& idx = index (row, Columns::Upd); emit dataChanged (idx, idx); } } }
#include "packagesmodel.h" #include <QIcon> #include <QApplication> #include <util/util.h> #include "core.h" #include "storage.h" #include "pendingmanager.h" namespace LeechCraft { namespace LackMan { PackagesModel::PackagesModel (QObject *parent) : QAbstractItemModel (parent) { } int PackagesModel::columnCount (const QModelIndex&) const { return Columns::MaxColumn; } QVariant PackagesModel::headerData (int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Vertical) return QVariant (); if (role != Qt::DisplayRole) return QVariant (); switch (section) { case Columns::Inst: return tr ("I"); case Columns::Upd: return tr ("U"); case Columns::Name: return tr ("Name"); case Columns::Description: return tr ("Description"); case Columns::Version: return tr ("Version"); case Columns::Size: return tr ("Size"); default: return "unknown"; } } QVariant PackagesModel::data (const QModelIndex& index, int role) const { const auto& lpi = Packages_.at (index.row ()); const int col = index.column (); switch (role) { case Qt::DisplayRole: switch (col) { case Columns::Name: return lpi.Name_; case Columns::Description: return lpi.ShortDescription_; case Columns::Version: return lpi.Version_; case Columns::Size: { const auto size = Core::Instance ().GetStorage ()->GetPackageSize (lpi.PackageID_); return size > 0 ? Util::MakePrettySize (size) : tr ("unknown"); } default: return QVariant (); } case Qt::DecorationRole: return col != Columns::Name ? QVariant () : Core::Instance ().GetIconForLPI (lpi); case Qt::CheckStateRole: { auto pm = Core::Instance ().GetPendingManager (); switch (col) { case Columns::Inst: if (lpi.IsInstalled_) return pm->GetPendingRemove ().contains (lpi.PackageID_) ? Qt::Unchecked : Qt::Checked; else return pm->GetPendingInstall ().contains (lpi.PackageID_) ? Qt::Checked : Qt::Unchecked; case Columns::Upd: if (!lpi.HasNewVersion_) return {}; return pm->GetPendingUpdate ().contains (lpi.PackageID_) ? Qt::Checked : Qt::Unchecked; default: return {}; } } case PMRPackageID: return lpi.PackageID_; case PMRShortDescription: return lpi.ShortDescription_; case PMRLongDescription: return lpi.LongDescription_; case PMRTags: return lpi.Tags_; case PMRInstalled: return lpi.IsInstalled_; case PMRUpgradable: return lpi.HasNewVersion_; case PMRVersion: return lpi.Version_; case PMRThumbnails: case PMRScreenshots: { QStringList result; for (const auto& img : Core::Instance ().GetStorage ()->GetImages (lpi.Name_)) if (img.Type_ == (role == PMRThumbnails ? Image::TThumbnail : Image::TScreenshot)) result << img.URL_; return result; } case PMRSize: return Core::Instance ().GetStorage ()->GetPackageSize (lpi.PackageID_); default: return {}; } } bool PackagesModel::setData (const QModelIndex& index, const QVariant& value, int role) { if (role != Qt::CheckStateRole) return false; const auto& lpi = Packages_.at (index.row ()); const Qt::CheckState state = static_cast<Qt::CheckState> (value.toInt ()); switch (index.column ()) { case Columns::Inst: { const bool isNewState = (state == Qt::Checked && !lpi.IsInstalled_) || (state == Qt::Unchecked && lpi.IsInstalled_); Core::Instance ().GetPendingManager ()-> ToggleInstallRemove (lpi.PackageID_, isNewState, lpi.IsInstalled_); emit dataChanged (index, index); return true; } case Columns::Upd: Core::Instance ().GetPendingManager ()->ToggleUpdate (lpi.PackageID_, state == Qt::Checked); emit dataChanged (index, index); return true; default: return false; } } Qt::ItemFlags PackagesModel::flags (const QModelIndex& index) const { if (!index.isValid ()) return 0; auto flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable; const auto& lpi = Packages_.at (index.row ()); switch (index.column ()) { case Columns::Inst: flags |= Qt::ItemIsUserCheckable; break; case Columns::Upd: if (lpi.HasNewVersion_) flags |= Qt::ItemIsUserCheckable; break; } return flags; } QModelIndex PackagesModel::index (int row, int column, const QModelIndex& parent) const { if (!hasIndex (row, column, parent)) return QModelIndex (); return createIndex (row, column); } QModelIndex PackagesModel::parent (const QModelIndex&) const { return QModelIndex (); } int PackagesModel::rowCount (const QModelIndex& parent) const { return parent.isValid () ? 0 : Packages_.size (); } void PackagesModel::AddRow (const ListPackageInfo& lpi) { int size = Packages_.size (); beginInsertRows (QModelIndex (), size, size); Packages_ << lpi; endInsertRows (); } void PackagesModel::UpdateRow (const ListPackageInfo& lpi) { for (int i = 0, size = Packages_.size (); i < size; ++i) if (Packages_.at (i).Name_ == lpi.Name_) { Packages_ [i] = lpi; emit dataChanged (index (i, 0), index (i, columnCount () - 1)); break; } } void PackagesModel::RemovePackage (int packageId) { for (int i = 0, size = Packages_.size (); i < size; ++i) if (Packages_.at (i).PackageID_ == packageId) { beginRemoveRows (QModelIndex (), i, i); Packages_.removeAt (i); endRemoveRows (); break; } }
int PackagesModel::GetRow (int packageId) const { for (int i = 0, size = Packages_.size (); i < size; ++i) if (Packages_.at (i).PackageID_ == packageId) return i; return -1; } void PackagesModel::Clear () { beginResetModel (); Packages_.clear (); endResetModel (); } void PackagesModel::handlePackageInstallRemoveToggled (int id) { const auto row = GetRow (id); if (row == -1) { qWarning () << Q_FUNC_INFO << "unknown package ID" << id; return; } const auto& idx = index (row, Columns::Inst); emit dataChanged (idx, idx); } void PackagesModel::handlePackageUpdateToggled (int id) { const auto row = GetRow (id); if (row == -1) { qWarning () << Q_FUNC_INFO << "unknown package ID" << id; return; } const auto& idx = index (row, Columns::Upd); emit dataChanged (idx, idx); } } }
ListPackageInfo PackagesModel::FindPackage (const QString& name) const { const auto pos = std::find_if (Packages_.begin (), Packages_.end (), [&name] (const auto& lpi) { return lpi.Name_ == name; }); return pos != Packages_.end () ? *pos : ListPackageInfo {}; }
function_block-full_function
[ { "content": "\tconst struct\n\n\t{\n\n\t\ttemplate<typename Vec>\n\n\t\tauto operator() (Vec&& vec) const\n\n\t\t{\n\n\t\t\tusing std::begin;\n\n\t\t\tusing std::end;\n\n\t\t\tusing MP = typename Vec::value_type;\n\n\t\t\treturn std::accumulate (begin (vec), end (vec), Mzero<MP> (), &operator+<MP>);\n\n\t\t}\n...
C++
pxr/imaging/plugin/hdRpr/rifcpp/rifContext.cpp
MagisterDemens/RadeonProRenderUSD
51d3855b7c1a0cd8dafb5986d5ac4c6eb9df38e2
#include "rifContext.h" #include "rifError.h" #include "RadeonProRender_CL.h" #include "RadeonProRender_GL.h" #include "RadeonImageFilters_cl.h" #include "RadeonImageFilters_gl.h" #include "RadeonImageFilters_metal.h" #include "rprcpp/rprContext.h" #include "rprcpp/rprFramebufferGL.h" #include <vector> #include <cassert> #include <stdexcept> PXR_NAMESPACE_OPEN_SCOPE namespace rif { namespace { class ContextOpenCL final : public Context { public: explicit ContextOpenCL(rpr_context rprContext, std::string const& modelPath); ~ContextOpenCL() override = default; std::unique_ptr<Image> CreateImage(rpr::FrameBuffer* rprFrameBuffer) override; private: const rif_backend_api_type rifBackendApiType = RIF_BACKEND_API_OPENCL; }; class ContextMetal final : public Context { public: explicit ContextMetal(rpr_context rprContext, std::string const& modelPath); ~ContextMetal() override = default; std::unique_ptr<Image> CreateImage(rpr::FrameBuffer* rprFrameBuffer) override; private: const rif_backend_api_type rifBackendApiType = RIF_BACKEND_API_METAL; }; class ContextCPU final : public Context { public: explicit ContextCPU(rpr_context rprContext, std::string const& modelPath); ~ContextCPU() override = default; std::unique_ptr<Image> CreateImage(rpr::FrameBuffer* rprFrameBuffer) override; void UpdateInputImage(rpr::FrameBuffer* rprFrameBuffer, rif_image image) override; private: const rif_backend_api_type rifBackendApiType = RIF_BACKEND_API_OPENCL; }; std::vector<rpr_char> GetRprCachePath(rpr_context rprContext) { size_t length; rpr_status status = rprContextGetInfo(rprContext, RPR_CONTEXT_CACHE_PATH, sizeof(size_t), nullptr, &length); if (status != RPR_SUCCESS) { throw rif::Error(RPR_GET_ERROR_MESSAGE(status, "Failed to get cache path", rprContext)); } std::vector<rpr_char> path(length); status = rprContextGetInfo(rprContext, RPR_CONTEXT_CACHE_PATH, path.size(), &path[0], nullptr); if (status != RPR_SUCCESS) { throw rif::Error(RPR_GET_ERROR_MESSAGE(status, "Failed to get cache path", rprContext)); } return path; } rif_image_desc GetRifImageDesc(rpr::FrameBuffer* rprFrameBuffer) { auto rprDesc = rprFrameBuffer->GetDesc(); rif_image_desc imageDesc = {}; imageDesc.image_width = rprDesc.fb_width; imageDesc.image_height = rprDesc.fb_height; imageDesc.image_depth = 1; imageDesc.image_row_pitch = 0; imageDesc.image_slice_pitch = 0; imageDesc.num_components = 4; imageDesc.type = RIF_COMPONENT_TYPE_FLOAT32; return imageDesc; } ContextOpenCL::ContextOpenCL(rpr_context rprContext, std::string const& modelPath) : Context(modelPath) { int deviceCount = 0; RIF_ERROR_CHECK_THROW(rifGetDeviceCount(rifBackendApiType, &deviceCount), "Failed to query device count"); assert(deviceCount != 0); if (0 == deviceCount) throw rif::Error("No compatible devices."); rpr_cl_context clContext; rpr_status status = rprContextGetInfo(rprContext, RPR_CL_CONTEXT, sizeof(rpr_cl_context), &clContext, nullptr); if (status != RPR_SUCCESS) { throw rif::Error(RPR_GET_ERROR_MESSAGE(status, "Failed to query CL context", rprContext)); } rpr_cl_device clDevice; status = rprContextGetInfo(rprContext, RPR_CL_DEVICE, sizeof(rpr_cl_device), &clDevice, nullptr); if (status != RPR_SUCCESS) { throw rif::Error(RPR_GET_ERROR_MESSAGE(status, "Failed to query CL device", rprContext)); } rpr_cl_command_queue clCommandQueue; status = rprContextGetInfo(rprContext, RPR_CL_COMMAND_QUEUE, sizeof(rpr_cl_command_queue), &clCommandQueue, nullptr); if (status != RPR_SUCCESS) { throw rif::Error(RPR_GET_ERROR_MESSAGE(status, "Failed to query CL command queue", rprContext)); } std::vector<rpr_char> path = GetRprCachePath(rprContext); #ifndef __APPLE__ RIF_ERROR_CHECK_THROW(rifCreateContextFromOpenClContext(RIF_API_VERSION, clContext, clDevice, clCommandQueue, path.data(), &m_context), "Failed to create RIF context") #endif } std::unique_ptr<Image> ContextOpenCL::CreateImage(rpr::FrameBuffer* rprFrameBuffer) { if (!rprFrameBuffer) { return nullptr; } rif_image rifImage = nullptr; #ifndef __APPLE__ if (auto rprFrameBufferGL = dynamic_cast<rpr::FrameBufferGL*>(rprFrameBuffer)) { RIF_ERROR_CHECK_THROW(rifContextCreateImageFromOpenGlTexture(m_context, GL_TEXTURE_2D, 0, rprFrameBufferGL->GetGL(), &rifImage), "Failed to create RIF image from OpenGL texture") } else { rpr_cl_mem clMem = rprFrameBuffer->GetCLMem(); assert(clMem); if (!clMem) { RIF_THROW_ERROR_MSG("Failed to get rpr framebuffer cl_mem"); } auto rifImageDesc = GetRifImageDesc(rprFrameBuffer); RIF_ERROR_CHECK_THROW(rifContextCreateImageFromOpenClMemory(m_context, &rifImageDesc, clMem, false, &rifImage), "Failed to create RIF image from OpenCL memory"); } #endif return std::unique_ptr<Image>(new Image(rifImage)); } ContextCPU::ContextCPU(rpr_context rprContext, std::string const& modelPath) : Context(modelPath) { int deviceCount = 0; RIF_ERROR_CHECK_THROW(rifGetDeviceCount(rifBackendApiType, &deviceCount), "Failed to query device count"); assert(deviceCount != 0); if (0 == deviceCount) RIF_THROW_ERROR_MSG("No compatible devices"); std::vector<rpr_char> path = GetRprCachePath(rprContext); RIF_ERROR_CHECK_THROW(rifCreateContext(RIF_API_VERSION, rifBackendApiType, 0, path.data(), &m_context), "Failed to create RIF context") } std::unique_ptr<Image> ContextCPU::CreateImage(rpr::FrameBuffer* rprFrameBuffer) { if (!rprFrameBuffer) { return nullptr; } return Context::CreateImage(GetRifImageDesc(rprFrameBuffer)); } void ContextCPU::UpdateInputImage(rpr::FrameBuffer* rprFrameBuffer, rif_image image) { if (!rprFrameBuffer || !image) { return; } size_t sizeInBytes = 0; size_t retSize = 0; RIF_ERROR_CHECK_THROW(rifImageGetInfo(image, RIF_IMAGE_DATA_SIZEBYTE, sizeof(size_t), (void*)& sizeInBytes, &retSize), "Failed to get RIF image info"); size_t fbSize; rpr_status status = rprFrameBufferGetInfo(rprFrameBuffer->GetHandle(), RPR_FRAMEBUFFER_DATA, 0, NULL, &fbSize); if (status != RPR_SUCCESS) { throw rif::Error(RPR_GET_ERROR_MESSAGE(status, "Failed to query RPR_FRAMEBUFFER_DATA")); } assert(sizeInBytes == fbSize); if (sizeInBytes != fbSize) RIF_THROW_ERROR_MSG("Failed to match RIF image and frame buffer sizes"); void* imageData = nullptr; RIF_ERROR_CHECK_THROW(rifImageMap(image, RIF_IMAGE_MAP_WRITE, &imageData), "Failed to map RIF image"); auto rprStatus = rprFrameBufferGetInfo(rprFrameBuffer->GetHandle(), RPR_FRAMEBUFFER_DATA, fbSize, imageData, NULL); assert(RPR_SUCCESS == rprStatus); RIF_ERROR_CHECK_THROW(rifImageUnmap(image, imageData), "Failed to unmap RIF image"); if (RPR_SUCCESS != rprStatus) RIF_THROW_ERROR_MSG("Failed to get data from RPR frame buffer"); } rpr_int GpuDeviceIdUsed(rpr_creation_flags contextFlags) { #define GPU(x) RPR_CREATION_FLAGS_ENABLE_GPU##x std::vector<rpr_int> gpu_ids; gpu_ids.reserve(16); gpu_ids.push_back(GPU(0)); gpu_ids.push_back(GPU(1)); gpu_ids.push_back(GPU(2)); gpu_ids.push_back(GPU(3)); gpu_ids.push_back(GPU(4)); gpu_ids.push_back(GPU(5)); gpu_ids.push_back(GPU(6)); gpu_ids.push_back(GPU(7)); gpu_ids.push_back(GPU(8)); gpu_ids.push_back(GPU(9)); gpu_ids.push_back(GPU(10)); gpu_ids.push_back(GPU(11)); gpu_ids.push_back(GPU(12)); gpu_ids.push_back(GPU(13)); gpu_ids.push_back(GPU(14)); gpu_ids.push_back(GPU(15)); #undef GPU for (rpr_int i = 0; i < gpu_ids.size(); i++ ) { if ((contextFlags & gpu_ids[i]) != 0) return i; } return -1; } ContextMetal::ContextMetal(rpr_context rprContext, std::string const& modelPath) : Context(modelPath) { int deviceCount = 0; RIF_ERROR_CHECK_THROW(rifGetDeviceCount(rifBackendApiType, &deviceCount), "Failed to query device count"); assert(deviceCount != 0); if (0 == deviceCount) RIF_THROW_ERROR_MSG("No compatible devices"); rpr_creation_flags contextFlags = 0; rpr_status status = rprContextGetInfo(rprContext, RPR_CONTEXT_CREATION_FLAGS, sizeof(rpr_creation_flags), &contextFlags, nullptr); if (status != RPR_SUCCESS) { throw rif::Error(RPR_GET_ERROR_MESSAGE(status, "Failed to query RPR context creation flags")); } std::vector<rpr_char> path = GetRprCachePath(rprContext); RIF_ERROR_CHECK_THROW(rifCreateContext(RIF_API_VERSION, rifBackendApiType, GpuDeviceIdUsed(contextFlags), path.data(), &m_context), "Failed to create RIF context"); } std::unique_ptr<Image> ContextMetal::CreateImage(rpr::FrameBuffer* rprFrameBuffer) { if (!rprFrameBuffer) { return nullptr; } rif_image rifImage = nullptr; rpr_cl_mem clMem = rprFrameBuffer->GetCLMem(); assert(clMem); if (!clMem) RIF_THROW_ERROR_MSG("Failed to get frame buffer cl_mem"); rpr_image_format framebufferFormat; rpr_status status = rprFrameBufferGetInfo(rprFrameBuffer->GetHandle(), RPR_FRAMEBUFFER_FORMAT, sizeof(framebufferFormat), &framebufferFormat, nullptr); if (status != RPR_SUCCESS) { throw rif::Error(RPR_GET_ERROR_MESSAGE(status, "Failed to get framebuffer format")); } int bytesPerComponent = 1; if (framebufferFormat.type == RPR_COMPONENT_TYPE_FLOAT32) { bytesPerComponent = 4; } else if (framebufferFormat.type == RPR_COMPONENT_TYPE_FLOAT16) { bytesPerComponent = 2; } auto desc = GetRifImageDesc(rprFrameBuffer); rif_longlong size = desc.image_width * desc.image_height * framebufferFormat.num_components * bytesPerComponent; RIF_ERROR_CHECK_THROW(rifContextCreateImageFromMetalMemory(m_context, &desc, clMem, size, &rifImage), "Failed to create RIF image from metal memory"); return std::unique_ptr<Image>(new Image(rifImage)); } bool HasGpuContext(rpr_creation_flags contextFlags) { #define GPU(x) RPR_CREATION_FLAGS_ENABLE_GPU##x rpr_creation_flags gpuMask = GPU(0) | GPU(1) | GPU(2) | GPU(3) | GPU(4) | GPU(5) | GPU(6) | GPU(7) | GPU(8) | GPU(9) | GPU(10) | GPU(11) | GPU(12) | GPU(13) | GPU(14) | GPU(15); #undef GPU return (contextFlags & gpuMask) != 0; } } std::unique_ptr<Context> Context::Create(rpr::Context* rprContext, std::string const& modelPath) { if (!rprContext) { return nullptr; } rpr_creation_flags contextFlags = 0; if (RPR_ERROR_CHECK(rprContextGetInfo(rprContext->GetHandle(), RPR_CONTEXT_CREATION_FLAGS, sizeof(rpr_creation_flags), &contextFlags, nullptr), "Failed to query RPR context creation flags")) { return nullptr; } try { std::unique_ptr<Context> rifContext; if (contextFlags & RPR_CREATION_FLAGS_ENABLE_METAL) { rifContext.reset(new ContextMetal(rprContext->GetHandle(), modelPath)); } else if (HasGpuContext(contextFlags) && rprContext->GetActivePluginType() != rpr::PluginType::HYBRID) { rifContext.reset(new ContextOpenCL(rprContext->GetHandle(), modelPath)); } else { rifContext.reset(new ContextCPU(rprContext->GetHandle(), modelPath)); } RIF_ERROR_CHECK_THROW(rifContextCreateCommandQueue(rifContext->m_context, &rifContext->m_commandQueue), "Failed to create RIF command queue"); return rifContext; } catch (rif::Error const& e) { TF_RUNTIME_ERROR("Failed to create RIF context. RIF error: %s", e.what()); } return nullptr; } Context::Context(std::string const& modelPath) : m_modelPath(modelPath) { } Context::~Context() { if (m_commandQueue) { rifObjectDelete(m_commandQueue); } if (m_context) { rifObjectDelete(m_context); } } std::unique_ptr<Image> Context::CreateImage(rif_image_desc const& desc) { rif_image rifImage = nullptr; RIF_ERROR_CHECK_THROW(rifContextCreateImage(m_context, &desc, nullptr, &rifImage), "Failed to create RIF image"); return std::unique_ptr<Image>(new Image(rifImage)); } void Context::UpdateInputImage(rpr::FrameBuffer* rprFrameBuffer, rif_image image) { } void Context::AttachFilter(rif_image_filter filter, rif_image inputImage, rif_image outputImage) { RIF_ERROR_CHECK_THROW(rifCommandQueueAttachImageFilter(m_commandQueue, filter, inputImage, outputImage), "Failed to attach image filter to queue"); ++m_numAttachedFilters; } void Context::DetachFilter(rif_image_filter filter) { auto rifStatus = rifCommandQueueDetachImageFilter(m_commandQueue, filter); if (rifStatus == RIF_ERROR_INVALID_PARAMETER) { return; } RIF_ERROR_CHECK_THROW(rifStatus, "Failed to detach image filter from queue"); --m_numAttachedFilters; } rif_image_filter Context::CreateImageFilter(rif_image_filter_type type) { rif_image_filter outFilter = nullptr; RIF_ERROR_CHECK_THROW(rifContextCreateImageFilter(m_context, type, &outFilter), "Failed to create image filter"); return outFilter; } void Context::ExecuteCommandQueue() { if (!m_numAttachedFilters) { return; } RIF_ERROR_CHECK_THROW(rifContextExecuteCommandQueue(m_context, m_commandQueue, nullptr, nullptr, nullptr), "Failed to execute command queue"); RIF_ERROR_CHECK_THROW(rifSyncronizeQueue(m_commandQueue), "Failed to synchronize command queue"); } } PXR_NAMESPACE_CLOSE_SCOPE
#include "rifContext.h" #include "rifError.h" #include "RadeonProRender_CL.h" #include "RadeonProRender_GL.h" #include "RadeonImageFilters_cl.h" #include "RadeonImageFilters_gl.h" #include "RadeonImageFilters_metal.h" #include "rprcpp/rprContext.h" #include "rprcpp/rprFramebufferGL.h" #include <vector> #include <cassert> #include <stdexcept> PXR_NAMESPACE_OPEN_SCOPE namespace rif { namespace { class ContextOpenCL final : public Context { public: explicit ContextOpenCL(rpr_context rprContext, std::string const& modelPath); ~ContextOpenCL() override = default; std::unique_ptr<Image> CreateImage(rpr::FrameBuffer* rprFrameBuffer) override; private: const rif_backend_api_type rifBackendApiType = RIF_BACKEND_API_OPENCL; }; class ContextMetal final : public Context { public: explicit ContextMetal(rpr_context rprContext, std::string const& modelPath); ~ContextMetal() override = default; std::unique_ptr<Image> CreateImage(rpr::FrameBuffer* rprFrameBuffer) override; private: const rif_backend_api_type rifBackendApiType = RIF_BACKEND_API_METAL; }; class ContextCPU final : public Context { public: explicit ContextCPU(rpr_context rprContext, std::string const& modelPath); ~ContextCPU() override = default; std::unique_ptr<Image> CreateImage(rpr::FrameBuffer* rprFrameBuffer) override; void UpdateInputImage(rpr::FrameBuffer* rprFrameBuffer, rif_image image) override; private: const rif_backend_api_type rifBackendApiType = RIF_BACKEND_API_OPENCL; }; std::vector<rpr_char> GetRprCachePath(rpr_context rprContext) { size_t length; rpr_status status = rprContextGetInfo(rprContext, RPR_CONTEXT_CACHE_PATH, sizeof(size_t), nullptr, &length); if (status != RPR_SUCCESS) { throw rif::Error(RPR_GET_ERROR_MESSAGE(status, "Failed to get cache path", rprContext)); } std::vector<rpr_char> path(length); status = rprContextGetInfo(rprContext, RPR_CONTEXT_CACHE_PATH, path.size(), &path[0], nullptr); if (status != RPR_SUCCESS) { throw rif::Error(RPR_GET_ERROR_MESSAGE(status, "Failed to get cache path", rprContext)); } return path; } rif_image_desc GetRifImageDesc(rpr::FrameBuffer* rprFrameBuffer) { auto rprDesc = rprFrameBuffer->GetDesc(); rif_image_desc imageDesc = {}; imageDesc.image_width = rprDesc.fb_width; imageDesc.image_height = rprDesc.fb_height; imageDesc.image_depth = 1; imageDesc.image_row_pitch = 0; imageDesc.image_slice_pitch = 0; imageDesc.num_components = 4; imageDesc.type = RIF_COMPONENT_TYPE_FLOAT32; return imageDesc; } ContextOpenCL::ContextOpenCL(rpr_context rprContext, std::string const& modelPath) : Context(modelPath) { int deviceCount = 0; RIF_ERROR_CHECK_THROW(rifGetDeviceCount(rifBackendApiType, &deviceCount), "Failed to query device count"); assert(deviceCount != 0); if (0 == deviceCount) throw rif::Error("No compatible devices."); rpr_cl_context clContext; rpr_status status = rprContextGetInfo(rprContext, RPR_CL_CONTEXT, sizeof(rpr_cl_context), &clContext, nullptr); if (status != RPR_SUCCESS) { throw rif::Error(RPR_GET_ERROR_MESSAGE(status, "Failed to query CL context", rprContext)); } rpr_cl_device clDevice; status = rprContextGetInfo(rprContext, RPR_CL_DEVICE, sizeof(rpr_cl_device), &clDevice, nullptr); if (status != RPR_SUCCESS) { throw rif::Error(RPR_GET_ERROR_MESSAGE(status, "Failed to query CL device", rprContext)); } rpr_cl_command_queue clCommandQueue; status = rprContextGetInfo(rprContext, RPR_CL_COMMAND_QUEUE, sizeof(rpr_cl_command_queue), &clCommandQueue, nullptr); if (status != RPR_SUCCESS) { throw rif::Error(RPR_GET_ERROR_MESSAGE(status, "Failed to query CL command queue", rprContext)); } std::vector<rpr_char> path = GetRprCachePath(rprContext); #ifndef __APPLE__ RIF_ERROR_CHECK_THROW(rifCreateContextFromOpenClContext(RIF_API_VERSION, clContext, clDevice, clCommandQueue, path.data(), &m_context), "Failed to create RIF context") #endif } std::unique_ptr<Image> ContextOpenCL::CreateImage(rpr::FrameBuffer* rprFrameBuffer) { if (!rprFrameBuffer) { return nullptr; } rif_image rifImage = nullptr; #ifndef __APPLE__ if (auto rprFrameBufferGL = dynamic_cast<rpr::FrameBufferGL*>(rprFrameBuffer)) { RIF_ERROR_CHECK_THROW(rifContextCreateImageFromOpenGlTexture(m_context, GL_TEXTURE_2D, 0, rprFrameBufferGL->GetGL(), &rifImage), "Failed to create RIF image from OpenGL texture") } else { rpr_cl_mem clMem = rprFrameBuffer->GetCLMem(); assert(clMem); if (!clMem) { RIF_THROW_ERROR_MSG("Failed to get rpr framebuffer cl_mem"); } auto rifImageDesc = GetRifImageDesc(rprFrameBuffer); RIF_ERROR_CHECK_THROW(rifContextCreateImageFromOpenClMemory(m_context, &rifImageDesc, clMem, false, &rifImage), "Failed to create RIF image from OpenCL memory"); } #endif return std::unique_ptr<Image>(new Image(rifImage)); } ContextCPU::ContextCPU(rpr_context rprContext, std::string const& modelPath) : Context(modelPath) { int deviceCount = 0; RIF_ERROR_CHECK_THROW(rifGetDeviceCount(rifBackendApiType, &deviceCount), "Failed to query device count"); assert(deviceCount != 0); if (0 == deviceCount) RIF_THROW_ERROR_MSG("No compatible devices"); std::vector<rpr_char> path = GetRprCachePath(rprContext); RIF_ERROR_CHECK_THROW(rifCreateContext(RIF_API_VERSION, rifBackendApiType, 0, path.data(), &m_context), "Failed to create RIF context") } std::unique_ptr<Image> ContextCPU::CreateImage(rpr::FrameBuffer* rprFrameBuffer) { if (!rprFrameBuffer) { return nullptr; } return Context::CreateImage(GetRifImageDesc(rprFrameBuffer)); } void ContextCPU::UpdateInputImage(rpr::FrameBuffer* rprFrameBuffer, rif_image image) { if (!rprFrameBuffer || !image) { return; } size_t sizeInBytes = 0; size_t retSize = 0; RIF_ERROR_CHECK_THROW(rifImageGetInfo(image, RIF_IMAGE_DATA_SIZEBYTE, sizeof(size_t), (void*)& sizeInBytes, &retSize), "Failed to get RIF image info"); size_t fbSize; rpr_status status = rprFrameBufferGetInfo(rprFrameBuffer->GetHandle(), RPR_FRAMEBUFFER_DATA, 0, NULL, &fbSize); if (status != RPR_SUCCESS) { throw rif::Error(RPR_GET_ERROR_MESSAGE(status, "Failed to query RPR_FRAMEBUFFER_DATA")); } assert(sizeInBytes == fbSize); if (sizeInBytes != fbSize) RIF_THROW_ERROR_MSG("Failed to match RIF image and frame buffer sizes"); void* imageData = nullptr; RIF_ERROR_CHECK_THROW(rifImageMap(image, RIF_IMAGE_MAP_WRITE, &imageData), "Failed to map RIF image"); auto rprStatus = rprFrameBufferGetInfo(rprFrameBuffer->GetHandle(), RPR_FRAMEBUFFER_DATA, fbSize, imageData, NULL); assert(RPR_SUCCESS == rprStatus); RIF_ERROR_CHECK_THROW(rifImageUnmap(image, imageData), "Failed to unmap RIF image"); if (RPR_SUCCESS != rprStatus) RIF_THROW_ERROR_MSG("Failed to get data from RPR frame buffer"); } rpr_int GpuDeviceIdUsed(rpr_creation_flags contextFlags) { #define GPU(x) RPR_CREATION_FLAGS_ENABLE_GPU##x std::vector<rpr_int> gpu_ids; gpu_ids.reserve(16); gpu_ids.push_back(GPU(0)); gpu_ids.push_back(GPU(1)); gpu_ids.push_back(GPU(2)); gpu_ids.push_back(GPU(3)); gpu_ids.push_back(GPU(4)); gpu_ids.push_back(GPU(5)); gpu_ids.push_back(GPU(6)); gpu_ids.push_back(GPU(7)); gpu_ids.push_back(GPU(8)); gpu_ids.push_back(GPU(9)); gpu_ids.push_back(GPU(10)); gpu_ids.push_back(GPU(11)); gpu_ids.push_back(GPU(12)); gpu_ids.push_back(GPU(13)); gpu_ids.push_back(GPU(14)); gpu_ids.push_back(GPU(15)); #
ContextMetal::ContextMetal(rpr_context rprContext, std::string const& modelPath) : Context(modelPath) { int deviceCount = 0; RIF_ERROR_CHECK_THROW(rifGetDeviceCount(rifBackendApiType, &deviceCount), "Failed to query device count"); assert(deviceCount != 0); if (0 == deviceCount) RIF_THROW_ERROR_MSG("No compatible devices"); rpr_creation_flags contextFlags = 0; rpr_status status = rprContextGetInfo(rprContext, RPR_CONTEXT_CREATION_FLAGS, sizeof(rpr_creation_flags), &contextFlags, nullptr); if (status != RPR_SUCCESS) { throw rif::Error(RPR_GET_ERROR_MESSAGE(status, "Failed to query RPR context creation flags")); } std::vector<rpr_char> path = GetRprCachePath(rprContext); RIF_ERROR_CHECK_THROW(rifCreateContext(RIF_API_VERSION, rifBackendApiType, GpuDeviceIdUsed(contextFlags), path.data(), &m_context), "Failed to create RIF context"); } std::unique_ptr<Image> ContextMetal::CreateImage(rpr::FrameBuffer* rprFrameBuffer) { if (!rprFrameBuffer) { return nullptr; } rif_image rifImage = nullptr; rpr_cl_mem clMem = rprFrameBuffer->GetCLMem(); assert(clMem); if (!clMem) RIF_THROW_ERROR_MSG("Failed to get frame buffer cl_mem"); rpr_image_format framebufferFormat; rpr_status status = rprFrameBufferGetInfo(rprFrameBuffer->GetHandle(), RPR_FRAMEBUFFER_FORMAT, sizeof(framebufferFormat), &framebufferFormat, nullptr); if (status != RPR_SUCCESS) { throw rif::Error(RPR_GET_ERROR_MESSAGE(status, "Failed to get framebuffer format")); } int bytesPerComponent = 1; if (framebufferFormat.type == RPR_COMPONENT_TYPE_FLOAT32) { bytesPerComponent = 4; } else if (framebufferFormat.type == RPR_COMPONENT_TYPE_FLOAT16) { bytesPerComponent = 2; } auto desc = GetRifImageDesc(rprFrameBuffer); rif_longlong size = desc.image_width * desc.image_height * framebufferFormat.num_components * bytesPerComponent; RIF_ERROR_CHECK_THROW(rifContextCreateImageFromMetalMemory(m_context, &desc, clMem, size, &rifImage), "Failed to create RIF image from metal memory"); return std::unique_ptr<Image>(new Image(rifImage)); } bool HasGpuContext(rpr_creation_flags contextFlags) { #define GPU(x) RPR_CREATION_FLAGS_ENABLE_GPU##x rpr_creation_flags gpuMask = GPU(0) | GPU(1) | GPU(2) | GPU(3) | GPU(4) | GPU(5) | GPU(6) | GPU(7) | GPU(8) | GPU(9) | GPU(10) | GPU(11) | GPU(12) | GPU(13) | GPU(14) | GPU(15); #undef GPU return (contextFlags & gpuMask) != 0; } } std::unique_ptr<Context> Context::Create(rpr::Context* rprContext, std::string const& modelPath) { if (!rprContext) { return nullptr; } rpr_creation_flags contextFlags = 0; if (RPR_ERROR_CHECK(rprContextGetInfo(rprContext->GetHandle(), RPR_CONTEXT_CREATION_FLAGS, sizeof(rpr_creation_flags), &contextFlags, nullptr), "Failed to query RPR context creation flags")) { return nullptr; } try { std::unique_ptr<Context> rifContext; if (contextFlags & RPR_CREATION_FLAGS_ENABLE_METAL) { rifContext.reset(new ContextMetal(rprContext->GetHandle(), modelPath)); } else if (HasGpuContext(contextFlags) && rprContext->GetActivePluginType() != rpr::PluginType::HYBRID) { rifContext.reset(new ContextOpenCL(rprContext->GetHandle(), modelPath)); } else { rifContext.reset(new ContextCPU(rprContext->GetHandle(), modelPath)); } RIF_ERROR_CHECK_THROW(rifContextCreateCommandQueue(rifContext->m_context, &rifContext->m_commandQueue), "Failed to create RIF command queue"); return rifContext; } catch (rif::Error const& e) { TF_RUNTIME_ERROR("Failed to create RIF context. RIF error: %s", e.what()); } return nullptr; } Context::Context(std::string const& modelPath) : m_modelPath(modelPath) { } Context::~Context() { if (m_commandQueue) { rifObjectDelete(m_commandQueue); } if (m_context) { rifObjectDelete(m_context); } } std::unique_ptr<Image> Context::CreateImage(rif_image_desc const& desc) { rif_image rifImage = nullptr; RIF_ERROR_CHECK_THROW(rifContextCreateImage(m_context, &desc, nullptr, &rifImage), "Failed to create RIF image"); return std::unique_ptr<Image>(new Image(rifImage)); } void Context::UpdateInputImage(rpr::FrameBuffer* rprFrameBuffer, rif_image image) { } void Context::AttachFilter(rif_image_filter filter, rif_image inputImage, rif_image outputImage) { RIF_ERROR_CHECK_THROW(rifCommandQueueAttachImageFilter(m_commandQueue, filter, inputImage, outputImage), "Failed to attach image filter to queue"); ++m_numAttachedFilters; } void Context::DetachFilter(rif_image_filter filter) { auto rifStatus = rifCommandQueueDetachImageFilter(m_commandQueue, filter); if (rifStatus == RIF_ERROR_INVALID_PARAMETER) { return; } RIF_ERROR_CHECK_THROW(rifStatus, "Failed to detach image filter from queue"); --m_numAttachedFilters; } rif_image_filter Context::CreateImageFilter(rif_image_filter_type type) { rif_image_filter outFilter = nullptr; RIF_ERROR_CHECK_THROW(rifContextCreateImageFilter(m_context, type, &outFilter), "Failed to create image filter"); return outFilter; } void Context::ExecuteCommandQueue() { if (!m_numAttachedFilters) { return; } RIF_ERROR_CHECK_THROW(rifContextExecuteCommandQueue(m_context, m_commandQueue, nullptr, nullptr, nullptr), "Failed to execute command queue"); RIF_ERROR_CHECK_THROW(rifSyncronizeQueue(m_commandQueue), "Failed to synchronize command queue"); } } PXR_NAMESPACE_CLOSE_SCOPE
undef GPU for (rpr_int i = 0; i < gpu_ids.size(); i++ ) { if ((contextFlags & gpu_ids[i]) != 0) return i; } return -1; }
function_block-function_prefix_line
[ { "content": "class FrameBufferGL : public FrameBuffer {\n\npublic:\n\n FrameBufferGL(rpr_context context, rpr_uint width, rpr_uint height);\n\n FrameBufferGL(FrameBufferGL&& fb) noexcept;\n\n ~FrameBufferGL() override;\n\n\n\n FrameBufferGL const& operator=(FrameBufferGL&& fb) noexcept;\n\n\n\n ...
C++
Code/Framework/AzCore/AzCore/Math/TransformSerializer.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
#include <AzCore/Math/Transform.h> #include <AzCore/Math/TransformSerializer.h> namespace AZ { AZ_CLASS_ALLOCATOR_IMPL(JsonTransformSerializer, AZ::SystemAllocator, 0); JsonSerializationResult::Result JsonTransformSerializer::Load( void* outputValue, [[maybe_unused]] const Uuid& outputValueTypeId, const rapidjson::Value& inputValue, JsonDeserializerContext& context) { namespace JSR = JsonSerializationResult; if (azrtti_typeid<AZ::Transform>() != outputValueTypeId) { return context.Report( JSR::Tasks::ReadField, JSR::Outcomes::Unsupported, "Unable to deserialize Transform from json because the outputValueTypeId isn't a Transform type."); } AZ::Transform* transformInstance = reinterpret_cast<AZ::Transform*>(outputValue); AZ_Assert(transformInstance, "Output value for JsonTransformSerializer can't be null."); if (IsExplicitDefault(inputValue)) { *transformInstance = AZ::Transform::CreateIdentity(); return context.Report(JSR::Tasks::ReadField, JSR::Outcomes::DefaultsUsed, "Transform value set to identity."); } JSR::ResultCode result(JSR::Tasks::ReadField); { AZ::Vector3 translation = transformInstance->GetTranslation(); JSR::ResultCode loadResult = ContinueLoadingFromJsonObjectField( &translation, azrtti_typeid<decltype(translation)>(), inputValue, TranslationTag, context); result.Combine(loadResult); transformInstance->SetTranslation(translation); } { AZ::Quaternion rotation = transformInstance->GetRotation(); JSR::ResultCode loadResult = ContinueLoadingFromJsonObjectField(&rotation, azrtti_typeid<decltype(rotation)>(), inputValue, RotationTag, context); result.Combine(loadResult); transformInstance->SetRotation(rotation); } { float scale = transformInstance->GetUniformScale(); JSR::ResultCode loadResult = ContinueLoadingFromJsonObjectField(&scale, azrtti_typeid<decltype(scale)>(), inputValue, ScaleTag, context); result.Combine(loadResult); transformInstance->SetUniformScale(scale); } return context.Report( result, result.GetProcessing() != JSR::Processing::Halted ? "Successfully loaded Transform information." : "Failed to load Transform information."); } JsonSerializationResult::Result JsonTransformSerializer::Store( rapidjson::Value& outputValue, const void* inputValue, const void* defaultValue, [[maybe_unused]] const Uuid& valueTypeId, JsonSerializerContext& context) { namespace JSR = AZ::JsonSerializationResult; if (azrtti_typeid<AZ::Transform>() != valueTypeId) { return context.Report( JSR::Tasks::WriteValue, JSR::Outcomes::Unsupported, "Unable to Serialize Transform to json because the valueTypeId isn't a Transform type."); } const AZ::Transform* transformInstance = reinterpret_cast<const AZ::Transform*>(inputValue); AZ_Assert(transformInstance, "Input value for JsonTransformSerializer can't be null."); const AZ::Transform* defaultTransformInstance = reinterpret_cast<const AZ::Transform*>(defaultValue); JSR::ResultCode result(JSR::Tasks::WriteValue); { AZ::ScopedContextPath subPathName(context, TranslationTag); const AZ::Vector3 translation = transformInstance->GetTranslation(); const AZ::Vector3 defaultTranslation = defaultTransformInstance ? defaultTransformInstance->GetTranslation() : AZ::Vector3(); JSR::ResultCode storeResult = ContinueStoringToJsonObjectField( outputValue, TranslationTag, &translation, defaultTransformInstance ? &defaultTranslation : nullptr, azrtti_typeid<decltype(translation)>(), context); result.Combine(storeResult); } { AZ::ScopedContextPath subPathName(context, RotationTag); const AZ::Quaternion rotation = transformInstance->GetRotation(); const AZ::Quaternion defaultRotation = defaultTransformInstance ? defaultTransformInstance->GetRotation() : AZ::Quaternion(); JSR::ResultCode storeResult = ContinueStoringToJsonObjectField( outputValue, RotationTag, &rotation, defaultTransformInstance ? &defaultRotation : nullptr, azrtti_typeid<decltype(rotation)>(), context); result.Combine(storeResult); } { AZ::ScopedContextPath subPathName(context, ScaleTag); float scale = transformInstance->GetUniformScale(); float defaultScale = defaultTransformInstance ? defaultTransformInstance->GetUniformScale() : 0.0f; JSR::ResultCode storeResult = ContinueStoringToJsonObjectField( outputValue, ScaleTag, &scale, defaultTransformInstance ? &defaultScale : nullptr, azrtti_typeid<decltype(scale)>(), context); result.Combine(storeResult); } return context.Report( result, result.GetProcessing() != JSR::Processing::Halted ? "Successfully stored Transform information." : "Failed to store Transform information."); } auto JsonTransformSerializer::GetOperationsFlags() const -> OperationFlags { return OperationFlags::InitializeNewInstance; } }
#include <AzCore/Math/Transform.h> #include <AzCore/Math/TransformSerializer.h> namespace AZ { AZ_CLASS_ALLOCATOR_IMPL(JsonTransformSerializer, AZ::SystemAllocator, 0);
JsonSerializationResult::Result JsonTransformSerializer::Store( rapidjson::Value& outputValue, const void* inputValue, const void* defaultValue, [[maybe_unused]] const Uuid& valueTypeId, JsonSerializerContext& context) { namespace JSR = AZ::JsonSerializationResult; if (azrtti_typeid<AZ::Transform>() != valueTypeId) { return context.Report( JSR::Tasks::WriteValue, JSR::Outcomes::Unsupported, "Unable to Serialize Transform to json because the valueTypeId isn't a Transform type."); } const AZ::Transform* transformInstance = reinterpret_cast<const AZ::Transform*>(inputValue); AZ_Assert(transformInstance, "Input value for JsonTransformSerializer can't be null."); const AZ::Transform* defaultTransformInstance = reinterpret_cast<const AZ::Transform*>(defaultValue); JSR::ResultCode result(JSR::Tasks::WriteValue); { AZ::ScopedContextPath subPathName(context, TranslationTag); const AZ::Vector3 translation = transformInstance->GetTranslation(); const AZ::Vector3 defaultTranslation = defaultTransformInstance ? defaultTransformInstance->GetTranslation() : AZ::Vector3(); JSR::ResultCode storeResult = ContinueStoringToJsonObjectField( outputValue, TranslationTag, &translation, defaultTransformInstance ? &defaultTranslation : nullptr, azrtti_typeid<decltype(translation)>(), context); result.Combine(storeResult); } { AZ::ScopedContextPath subPathName(context, RotationTag); const AZ::Quaternion rotation = transformInstance->GetRotation(); const AZ::Quaternion defaultRotation = defaultTransformInstance ? defaultTransformInstance->GetRotation() : AZ::Quaternion(); JSR::ResultCode storeResult = ContinueStoringToJsonObjectField( outputValue, RotationTag, &rotation, defaultTransformInstance ? &defaultRotation : nullptr, azrtti_typeid<decltype(rotation)>(), context); result.Combine(storeResult); } { AZ::ScopedContextPath subPathName(context, ScaleTag); float scale = transformInstance->GetUniformScale(); float defaultScale = defaultTransformInstance ? defaultTransformInstance->GetUniformScale() : 0.0f; JSR::ResultCode storeResult = ContinueStoringToJsonObjectField( outputValue, ScaleTag, &scale, defaultTransformInstance ? &defaultScale : nullptr, azrtti_typeid<decltype(scale)>(), context); result.Combine(storeResult); } return context.Report( result, result.GetProcessing() != JSR::Processing::Halted ? "Successfully stored Transform information." : "Failed to store Transform information."); } auto JsonTransformSerializer::GetOperationsFlags() const -> OperationFlags { return OperationFlags::InitializeNewInstance; } }
JsonSerializationResult::Result JsonTransformSerializer::Load( void* outputValue, [[maybe_unused]] const Uuid& outputValueTypeId, const rapidjson::Value& inputValue, JsonDeserializerContext& context) { namespace JSR = JsonSerializationResult; if (azrtti_typeid<AZ::Transform>() != outputValueTypeId) { return context.Report( JSR::Tasks::ReadField, JSR::Outcomes::Unsupported, "Unable to deserialize Transform from json because the outputValueTypeId isn't a Transform type."); } AZ::Transform* transformInstance = reinterpret_cast<AZ::Transform*>(outputValue); AZ_Assert(transformInstance, "Output value for JsonTransformSerializer can't be null."); if (IsExplicitDefault(inputValue)) { *transformInstance = AZ::Transform::CreateIdentity(); return context.Report(JSR::Tasks::ReadField, JSR::Outcomes::DefaultsUsed, "Transform value set to identity."); } JSR::ResultCode result(JSR::Tasks::ReadField); { AZ::Vector3 translation = transformInstance->GetTranslation(); JSR::ResultCode loadResult = ContinueLoadingFromJsonObjectField( &translation, azrtti_typeid<decltype(translation)>(), inputValue, TranslationTag, context); result.Combine(loadResult); transformInstance->SetTranslation(translation); } { AZ::Quaternion rotation = transformInstance->GetRotation(); JSR::ResultCode loadResult = ContinueLoadingFromJsonObjectField(&rotation, azrtti_typeid<decltype(rotation)>(), inputValue, RotationTag, context); result.Combine(loadResult); transformInstance->SetRotation(rotation); } { float scale = transformInstance->GetUniformScale(); JSR::ResultCode loadResult = ContinueLoadingFromJsonObjectField(&scale, azrtti_typeid<decltype(scale)>(), inputValue, ScaleTag, context); result.Combine(loadResult); transformInstance->SetUniformScale(scale); } return context.Report( result, result.GetProcessing() != JSR::Processing::Halted ? "Successfully loaded Transform information." : "Failed to load Transform information."); }
function_block-full_function
[]
C++
widgets/mainwindow.cpp
AxelLeLouedec/Fitts
23ff29373f6e8cd3bdbe8eaf1f60c9c0808cf44b
#include "./widgets/mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) , m_settings(new QSettings("options.ini", QSettings::IniFormat)) { ui->setupUi(this); openHome(); } void MainWindow::onHomeEvent(int val, void *obj) { qDebug() << "[MainWindow] onHomeEvent"; switch(val) { case HOME_GAME_END: openResults((FittsModel *) obj); break; case HOME_OPEN_SETTINGS: openSettings(); break; case HOME_OPEN_RAPPEL: openReminder(); break; case HOME_EXIT_PRGM: qApp->exit(); break; default: break; } } void MainWindow::onSettingsEvent(int val, void *obj) { qDebug() << "[MainWindow] onSettingsEvent"; switch(val) { case SETTINGS_CLOSE: model = (FittsModel*) obj; qDebug() << model->nbCible; openHome(); break; default: break; } } void MainWindow::onReminderEvent(int val, void *obj) { qDebug() << "[MainWindow] onRappelEvent"; switch(val) { case REMINDER_CLOSE: openHome(); break; default: break; } } void MainWindow::onResultsEvent(int val) { qDebug() << "[MainWindow] onResultsEvent"; switch(val) { case RESULTS_RESTART: openHome(); break; case RESULTS_EXIT_PRGM: qApp->exit(); default: break; } } void MainWindow::openHome() { qDebug() << "Opening home"; home = new Home(model); connect(home, SIGNAL(onHomeEvent(int,void*)), this, SLOT(onHomeEvent(int,void*))); this->setCentralWidget(home); } void MainWindow::openResults(FittsModel *model) { qDebug() << "Opening results"; results = new Results(model); connect(results, SIGNAL(onResultsEvent(int)), this, SLOT(onResultsEvent(int))); this->setCentralWidget(results); } void MainWindow::openSettings() { qDebug() << "Opening settings"; settings = new Settings(model); connect(settings, SIGNAL(onSettingsEvent(int,void*)), this, SLOT(onSettingsEvent(int,void*))); this->setCentralWidget(settings); } void MainWindow::openReminder() { qDebug() << "Opening Reminder"; reminder = new Reminder(); connect(reminder, SIGNAL(onReminderEvent(int,void*)), this, SLOT(onReminderEvent(int,void*))); this->setCentralWidget(reminder); } MainWindow::~MainWindow() { delete ui; } void MainWindow::changeEvent(QEvent* event) { if (event->type() == QEvent::LanguageChange) { ui->retranslateUi(this); } QMainWindow::changeEvent(event); } void MainWindow::on_actionFran_ais_triggered() { m_settings->setValue("Language",1); updateLanguage(m_settings, &translator); } void MainWindow::on_actionEnglish_triggered() { m_settings->setValue("Language",2); updateLanguage(m_settings, &translator); } void MainWindow::on_actionQuitter_triggered() { qApp->exit(); }
#include "./widgets/mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) , m_settings(new QSettings("options.ini", QSettings::IniFormat)) { ui->setupUi(this); openHome(); } void MainWindow::onHomeEvent(int val, void *obj) { qDebug() << "[MainWindow] onHomeEvent"; switch(val) { case HOME_GAME_END: openResults((FittsModel *) obj); break; case HOME_OPEN_SETTINGS: openSettings(); break; case HOME_OPEN_RAPPEL: openReminder(); break; case HOME_EXIT_PRGM: qApp->exit(); break; default: break; } } void MainWindow::onSettingsEvent(int val, void *obj) { qDebug() << "[MainWindow] onSettingsEvent"; switch(val) { case SETTINGS_CLOSE: model = (FittsModel*) obj; qDebug() << model->nbCible; openHome(); break; default: break; } } void MainWindow::onReminderEvent(int val, void *obj) { qDebug() << "[MainWindow] onRappelEvent"; switch(val) { case REMINDER_CLOSE: openHome(); break; default: break; } } void MainWindow::onResultsEvent(int val) { qDebug() << "[MainWindow] onResultsEv
void MainWindow::openHome() { qDebug() << "Opening home"; home = new Home(model); connect(home, SIGNAL(onHomeEvent(int,void*)), this, SLOT(onHomeEvent(int,void*))); this->setCentralWidget(home); } void MainWindow::openResults(FittsModel *model) { qDebug() << "Opening results"; results = new Results(model); connect(results, SIGNAL(onResultsEvent(int)), this, SLOT(onResultsEvent(int))); this->setCentralWidget(results); } void MainWindow::openSettings() { qDebug() << "Opening settings"; settings = new Settings(model); connect(settings, SIGNAL(onSettingsEvent(int,void*)), this, SLOT(onSettingsEvent(int,void*))); this->setCentralWidget(settings); } void MainWindow::openReminder() { qDebug() << "Opening Reminder"; reminder = new Reminder(); connect(reminder, SIGNAL(onReminderEvent(int,void*)), this, SLOT(onReminderEvent(int,void*))); this->setCentralWidget(reminder); } MainWindow::~MainWindow() { delete ui; } void MainWindow::changeEvent(QEvent* event) { if (event->type() == QEvent::LanguageChange) { ui->retranslateUi(this); } QMainWindow::changeEvent(event); } void MainWindow::on_actionFran_ais_triggered() { m_settings->setValue("Language",1); updateLanguage(m_settings, &translator); } void MainWindow::on_actionEnglish_triggered() { m_settings->setValue("Language",2); updateLanguage(m_settings, &translator); } void MainWindow::on_actionQuitter_triggered() { qApp->exit(); }
ent"; switch(val) { case RESULTS_RESTART: openHome(); break; case RESULTS_EXIT_PRGM: qApp->exit(); default: break; } }
function_block-function_prefixed
[ { "content": "class FittsModel\n\n{\n\npublic:\n\n FittsModel();\n\n\n\n int cibleLeft = 10;\n\n int nbCible = 10;\n\n int minSize = 10;\n\n int maxSize = 150;\n\n\n\n double a = 0.20;\n\n double b = 0.10;\n\n\n\n double ecartType = 0;\n\n double erreurType = 0;\n\n double diffMoy ...
C++
tests/test_address.cc
wavesplatform/wavespp
9505613e01b19e5a73dfb90e9569323be98a3852
#include <cstring> #include <string> #include <iostream> #include <algorithm> #include "../src/address.hpp" #include "../src/utils.hpp" static constexpr auto PUBLIC_KEY_BIN_LEN = wavespp::public_key::PUBLIC_KEY_BIN_LEN; static int test_address_to_base58() { const std::string base58_address = "3MtBqEtkF8cYkNJv85QUS4wteNj48ZMAnt9"; const std::string bin_address = wavespp::utils::from_base58(base58_address); if (wavespp::utils::to_base58(bin_address) != base58_address) { fprintf(stderr, "wavespp::utils::to_base58/from_base58 results do not match\n"); return 1; } if (bin_address.size() != wavespp::address::ADDRESS_BIN_LEN) { fprintf(stderr, "bin_address.size() = %ld != ADDRESS_BIN_LEN\n", bin_address.size()); return 1; } unsigned char bin_uchar_address[wavespp::address::ADDRESS_BIN_LEN] = {0}; std::copy(bin_address.begin(), bin_address.end(), bin_uchar_address); wavespp::address address(bin_uchar_address); if (address.to_base58() != base58_address) { fprintf(stderr, "wavespp::address::to_base58() != %s\n", base58_address.c_str()); return 1; } return 0; } static int test_address_to_binary() { const char* address_base58 = "3Mv9XDntij4ZRE1XiNZed6J74rncBpiYNDV"; const auto expected_address_binary = wavespp::utils::from_base58(address_base58); wavespp::address address(address_base58); const auto address_binary = address.to_binary(); if (address_binary != expected_address_binary) { fprintf(stderr, "%s: binary address %s != expected_address_binary %s \n", __func__, address_binary.c_str(), expected_address_binary.c_str()); return 1; } return 0; } static int test_address_from_binary() { const char* address_base58 = "3Mv9XDntij4ZRE1XiNZed6J74rncBpiYNDV"; const auto expected_address_binary = wavespp::utils::from_base58(address_base58); const auto address = wavespp::address::FromBinary(expected_address_binary); const auto address_binary = address.to_binary(); if (address_binary != expected_address_binary) { fprintf(stderr, "%s: binary address %s != expected_address_binary %s \n", __func__, address_binary.c_str(), expected_address_binary.c_str()); return 1; } return 0; } static int test_address_from_unsigned_char() { printf("%s\n", __func__); const char* address_base58 = "3ND8YwWJ5XHhYNbLcWv9uZEqVboSU8iyMgu"; const auto expected_address_binary = wavespp::utils::from_base58(address_base58); const std::string input_public_key_str = "Do24gp5eC4HrN6XQkYh7FicnbHH3q7nEMnSUfn9Gundu"; const std::string input_public_key = wavespp::utils::from_base58(input_public_key_str); const unsigned char chain_id = 'T'; const unsigned char (&public_key)[PUBLIC_KEY_BIN_LEN] = reinterpret_cast<const unsigned char (&)[PUBLIC_KEY_BIN_LEN]>( *input_public_key.c_str()); wavespp::public_key sender_public_key(public_key); wavespp::address address(sender_public_key, chain_id); const auto address_binary = address.to_binary(); if (address_binary != expected_address_binary) { fprintf(stderr, "%s: binary address %s != expected_address_binary %s \n", __func__, address_binary.c_str(), expected_address_binary.c_str()); return 1; } printf("%s: address_binary: %s\n", __func__, wavespp::utils::to_base58(address_binary).c_str()); return 0; } int main(int argc, char const* argv[]) { int res = 0; do { if ((res = test_address_to_base58())) break; if ((res = test_address_to_binary())) break; if ((res = test_address_from_binary())) break; if ((res = test_address_from_unsigned_char())) break; } while (false); return res; }
#include <cstring> #include <string> #include <iostream> #include <algorithm> #include "../src/address.hpp" #include "../src/utils.hpp" static constexpr auto PUBLIC_KEY_BIN_LEN = wavespp::public_key::PUBLIC_KEY_BIN_LEN; static int test_address_to_base58() { const std::string base58_address = "3MtBqEtkF8cYkNJv85QUS4wteNj48ZMAnt9"; const std::string bin_address = wavespp::utils::from_base58(base58_address); if (wavespp::utils::to_base58(bin_address) != base58_address) { fprintf(stderr, "wavespp::utils::to_base58/from_base58 results do not match\n"); return 1; } if (bin_address.size() != wavespp::address::ADDRESS_BIN_LEN) { fprintf(stderr, "bin_address.size() = %ld != ADDRESS_BIN_LEN\n", bin_address.size()); return 1; } unsigned char bin_uchar_address[wavespp::address::ADDRESS_BIN_LEN] = {0}; std::copy(bin_address.begin(), bin_address.end(), bin_uchar_address); wavespp::address address(bin_uchar_address); if (address.to_base58() != base58_address) { fprintf(stderr, "wavespp::address::to_base58() != %s\n", base58_address.c_str()); return 1; } return 0; } static int test_address_to_binary() { const char* address_base58 = "3Mv9XDntij4ZRE1XiNZed6J74rncBpiYNDV"; const auto expected_address_binary = wavespp::utils::from_base58(address_base58); wavespp::address address(address_base58); const auto address_binary = address.to_binary(); if (address_binary != expected_address_binary) { fprintf(stderr, "%s: binary address %s != expected_address_binary %s \n", __func__, address_binary.c_str(), expected_address_binary.c_str()); return 1; } return 0; } static int test_address_from_binary() { const char* address_base58 = "3Mv9XDntij4ZRE1XiNZed6J74rncBpiYNDV"; const auto expected_address_binary = wavespp::utils::from_base58(address_base58); const auto address = wavespp::address::FromBinary(expected_address_binary); const auto address_binary = address.to_binary();
return 0; } static int test_address_from_unsigned_char() { printf("%s\n", __func__); const char* address_base58 = "3ND8YwWJ5XHhYNbLcWv9uZEqVboSU8iyMgu"; const auto expected_address_binary = wavespp::utils::from_base58(address_base58); const std::string input_public_key_str = "Do24gp5eC4HrN6XQkYh7FicnbHH3q7nEMnSUfn9Gundu"; const std::string input_public_key = wavespp::utils::from_base58(input_public_key_str); const unsigned char chain_id = 'T'; const unsigned char (&public_key)[PUBLIC_KEY_BIN_LEN] = reinterpret_cast<const unsigned char (&)[PUBLIC_KEY_BIN_LEN]>( *input_public_key.c_str()); wavespp::public_key sender_public_key(public_key); wavespp::address address(sender_public_key, chain_id); const auto address_binary = address.to_binary(); if (address_binary != expected_address_binary) { fprintf(stderr, "%s: binary address %s != expected_address_binary %s \n", __func__, address_binary.c_str(), expected_address_binary.c_str()); return 1; } printf("%s: address_binary: %s\n", __func__, wavespp::utils::to_base58(address_binary).c_str()); return 0; } int main(int argc, char const* argv[]) { int res = 0; do { if ((res = test_address_to_base58())) break; if ((res = test_address_to_binary())) break; if ((res = test_address_from_binary())) break; if ((res = test_address_from_unsigned_char())) break; } while (false); return res; }
if (address_binary != expected_address_binary) { fprintf(stderr, "%s: binary address %s != expected_address_binary %s \n", __func__, address_binary.c_str(), expected_address_binary.c_str()); return 1; }
if_condition
[ { "content": "struct address\n\n{\n\n // Length of an address in Base58 format.\n\n static const size_t ADDRESS_B58_LEN = 36;\n\n // Length of an address in binary format.\n\n static constexpr size_t ADDRESS_BIN_LEN = 26;\n\n\n\n address();\n\n address(const char* _str); // from base58\n\n ...
C++
xfa/src/fwl/src/basewidget/fwl_tooltipctrlimp.cpp
andoma/pdfium
6c0c0ce4b67502b89edf9c47c7e248328a8d8e9c
#include "xfa/src/foxitlib.h" #include "xfa/src/fwl/src/core/include/fwl_targetimp.h" #include "xfa/src/fwl/src/core/include/fwl_noteimp.h" #include "xfa/src/fwl/src/core/include/fwl_widgetimp.h" #include "xfa/src/fwl/src/core/include/fwl_panelimp.h" #include "xfa/src/fwl/src/core/include/fwl_formimp.h" #include "xfa/src/fwl/src/basewidget/include/fwl_tooltipctrlimp.h" IFWL_ToolTip* IFWL_ToolTip::Create(const CFWL_WidgetImpProperties& properties, IFWL_Widget* pOuter) { IFWL_ToolTip* pToolTip = new IFWL_ToolTip; CFWL_ToolTipImp* pToolTipImpl = new CFWL_ToolTipImp(properties, pOuter); pToolTip->SetImpl(pToolTipImpl); pToolTipImpl->SetInterface(pToolTip); return pToolTip; } FWL_ERR IFWL_ToolTip::SetAnchor(const CFX_RectF& rtAnchor) { return static_cast<CFWL_ToolTipImp*>(GetImpl())->SetAnchor(rtAnchor); } FWL_ERR IFWL_ToolTip::Show() { return static_cast<CFWL_ToolTipImp*>(GetImpl())->Show(); } FWL_ERR IFWL_ToolTip::Hide() { return static_cast<CFWL_ToolTipImp*>(GetImpl())->Hide(); } IFWL_ToolTip::IFWL_ToolTip() { } CFWL_ToolTipImp::CFWL_ToolTipImp(const CFWL_WidgetImpProperties& properties, IFWL_Widget* pOuter) : CFWL_FormImp(properties, pOuter), m_bBtnDown(FALSE), m_dwTTOStyles(FDE_TTOSTYLE_SingleLine), m_iTTOAlign(FDE_TTOALIGNMENT_Center), m_hTimerShow(NULL), m_hTimerHide(NULL), m_pTimer(NULL) { m_rtClient.Set(0, 0, 0, 0); m_rtCaption.Set(0, 0, 0, 0); m_rtAnchor.Set(0, 0, 0, 0); m_TimerShow.m_pToolTip = this; m_TimerHide.m_pToolTip = this; } CFWL_ToolTipImp::~CFWL_ToolTipImp() { if (m_pTimer) { delete m_pTimer; m_pTimer = NULL; } } FWL_ERR CFWL_ToolTipImp::GetClassName(CFX_WideString& wsClass) const { wsClass = FWL_CLASS_ToolTip; return FWL_ERR_Succeeded; } FX_DWORD CFWL_ToolTipImp::GetClassID() const { return FWL_CLASSHASH_ToolTip; } FWL_ERR CFWL_ToolTipImp::Initialize() { m_pProperties->m_dwStyles |= FWL_WGTSTYLE_Popup; m_pProperties->m_dwStyles &= ~FWL_WGTSTYLE_Child; if (CFWL_WidgetImp::Initialize() != FWL_ERR_Succeeded) return FWL_ERR_Indefinite; m_pDelegate = new CFWL_ToolTipImpDelegate(this); return FWL_ERR_Succeeded; } FWL_ERR CFWL_ToolTipImp::Finalize() { delete m_pDelegate; m_pDelegate = nullptr; return CFWL_WidgetImp::Finalize(); } FWL_ERR CFWL_ToolTipImp::GetWidgetRect(CFX_RectF& rect, FX_BOOL bAutoSize) { if (bAutoSize) { rect.Set(0, 0, 0, 0); if (m_pProperties->m_pThemeProvider == NULL) { m_pProperties->m_pThemeProvider = GetAvailableTheme(); } CFX_WideString wsCaption; IFWL_ToolTipDP* pData = static_cast<IFWL_ToolTipDP*>(m_pProperties->m_pDataProvider); if (pData) { pData->GetCaption(m_pInterface, wsCaption); } int32_t iLen = wsCaption.GetLength(); if (iLen > 0) { CFX_SizeF sz = CalcTextSize(wsCaption, m_pProperties->m_pThemeProvider); rect.Set(0, 0, sz.x, sz.y); rect.width += FWL_WGTCAPACITY_CXBorder * 25; rect.height += FWL_WGTCAPACITY_CYBorder * 8; } CFWL_WidgetImp::GetWidgetRect(rect, TRUE); } else { rect = m_pProperties->m_rtWidget; } return FWL_ERR_Succeeded; } FWL_ERR CFWL_ToolTipImp::Update() { if (IsLocked()) { return FWL_ERR_Indefinite; } if (!m_pProperties->m_pThemeProvider) { m_pProperties->m_pThemeProvider = GetAvailableTheme(); } UpdateTextOutStyles(); GetClientRect(m_rtClient); m_rtCaption = m_rtClient; return FWL_ERR_Succeeded; } FWL_ERR CFWL_ToolTipImp::GetClientRect(CFX_RectF& rect) { FX_FLOAT x = 0; FX_FLOAT y = 0; FX_FLOAT t = 0; IFWL_ThemeProvider* pTheme = m_pProperties->m_pThemeProvider; if (pTheme) { CFWL_ThemePart part; part.m_pWidget = m_pInterface; x = *static_cast<FX_FLOAT*>( pTheme->GetCapacity(&part, FWL_WGTCAPACITY_CXBorder)); y = *static_cast<FX_FLOAT*>( pTheme->GetCapacity(&part, FWL_WGTCAPACITY_CYBorder)); } rect = m_pProperties->m_rtWidget; rect.Offset(-rect.left, -rect.top); rect.Deflate(x, t, x, y); return FWL_ERR_Succeeded; } FWL_ERR CFWL_ToolTipImp::DrawWidget(CFX_Graphics* pGraphics, const CFX_Matrix* pMatrix) { IFWL_ToolTipTarget* toolTipTarget = CFWL_ToolTipContainer::getInstance()->GetCurrentToolTipTarget(); if (toolTipTarget && !toolTipTarget->UseDefaultTheme()) { return toolTipTarget->DrawToolTip(pGraphics, pMatrix, m_pInterface); } if (!pGraphics) return FWL_ERR_Indefinite; if (!m_pProperties->m_pThemeProvider) return FWL_ERR_Indefinite; IFWL_ThemeProvider* pTheme = m_pProperties->m_pThemeProvider; DrawBkground(pGraphics, pTheme, pMatrix); DrawText(pGraphics, pTheme, pMatrix); return FWL_ERR_Succeeded; } void CFWL_ToolTipImp::DrawBkground(CFX_Graphics* pGraphics, IFWL_ThemeProvider* pTheme, const CFX_Matrix* pMatrix) { CFWL_ThemeBackground param; param.m_pWidget = m_pInterface; param.m_iPart = FWL_PART_TTP_Background; param.m_dwStates = m_pProperties->m_dwStates; param.m_pGraphics = pGraphics; if (pMatrix) { param.m_matrix.Concat(*pMatrix); } param.m_rtPart = m_rtClient; if (m_pProperties->m_dwStates & FWL_WGTSTATE_Focused) { param.m_pData = &m_rtCaption; } pTheme->DrawBackground(&param); } void CFWL_ToolTipImp::DrawText(CFX_Graphics* pGraphics, IFWL_ThemeProvider* pTheme, const CFX_Matrix* pMatrix) { if (!m_pProperties->m_pDataProvider) return; CFX_WideString wsCaption; m_pProperties->m_pDataProvider->GetCaption(m_pInterface, wsCaption); if (wsCaption.IsEmpty()) { return; } CFWL_ThemeText param; param.m_pWidget = m_pInterface; param.m_iPart = FWL_PART_TTP_Caption; param.m_dwStates = m_pProperties->m_dwStates; param.m_pGraphics = pGraphics; if (pMatrix) { param.m_matrix.Concat(*pMatrix); } param.m_rtPart = m_rtCaption; param.m_wsText = wsCaption; param.m_dwTTOStyles = m_dwTTOStyles; param.m_iTTOAlign = m_iTTOAlign; pTheme->DrawText(&param); } void CFWL_ToolTipImp::UpdateTextOutStyles() { m_iTTOAlign = FDE_TTOALIGNMENT_Center; m_dwTTOStyles = FDE_TTOSTYLE_SingleLine; if (m_pProperties->m_dwStyleExes & FWL_WGTSTYLE_RTLReading) { m_dwTTOStyles |= FDE_TTOSTYLE_RTL; } if (m_pProperties->m_dwStyleExes & FWL_STYLEEXT_TTP_Multiline) { m_dwTTOStyles &= ~FDE_TTOSTYLE_SingleLine; } } FWL_ERR CFWL_ToolTipImp::SetAnchor(const CFX_RectF& rtAnchor) { m_rtAnchor = rtAnchor; return TRUE; } FWL_ERR CFWL_ToolTipImp::Show() { IFWL_ToolTipDP* pData = static_cast<IFWL_ToolTipDP*>(m_pProperties->m_pDataProvider); int32_t nInitDelay = pData->GetInitialDelay(m_pInterface); if ((m_pProperties->m_dwStates & FWL_WGTSTATE_Invisible)) { m_hTimerShow = FWL_StartTimer(&m_TimerShow, nInitDelay, FALSE); } return TRUE; } FWL_ERR CFWL_ToolTipImp::Hide() { SetStates(FWL_WGTSTATE_Invisible, TRUE); if (m_hTimerHide) { FWL_StopTimer(m_hTimerHide); m_hTimerHide = NULL; } if (m_hTimerShow) { FWL_StopTimer(m_hTimerShow); m_hTimerShow = NULL; } return TRUE; } FWL_ERR CFWL_ToolTipImp::SetStates(FX_DWORD dwStates, FX_BOOL bSet) { if ((dwStates & FWL_WGTSTATE_Invisible) && !bSet) { IFWL_ToolTipDP* pData = static_cast<IFWL_ToolTipDP*>(m_pProperties->m_pDataProvider); int32_t nAutoPopDelay = pData->GetAutoPopDelay(m_pInterface); m_hTimerHide = FWL_StartTimer(&m_TimerHide, nAutoPopDelay, FALSE); } return CFWL_WidgetImp::SetStates(dwStates, bSet); } void CFWL_ToolTipImp::RefreshToolTipPos() { if ((m_pProperties->m_dwStyleExes & FWL_STYLEEXT_TTP_NoAnchor) == 0) { CFX_RectF rtPopup; CFX_RectF rtWidget(m_pProperties->m_rtWidget); CFX_RectF rtAnchor(m_rtAnchor); rtPopup.Set(0, 0, 0, 0); FX_FLOAT fx = rtAnchor.Center().x + 20; FX_FLOAT fy = rtAnchor.Center().y + 20; rtPopup.Set(fx, fy, rtWidget.Width(), rtWidget.Height()); FX_FLOAT fScreenWidth = 0; FX_FLOAT fScreenHeight = 0; GetScreenSize(fScreenWidth, fScreenHeight); if (rtPopup.bottom() > fScreenHeight) { rtPopup.Offset(0, fScreenHeight - rtPopup.bottom()); } if (rtPopup.right() > fScreenWidth) { rtPopup.Offset(fScreenWidth - rtPopup.right(), 0); } if (rtPopup.left < 0) { rtPopup.Offset(0 - rtPopup.left, 0); } if (rtPopup.top < 0) { rtPopup.Offset(0, 0 - rtPopup.top); } SetWidgetRect(rtPopup); Update(); } } CFWL_ToolTipImp::CFWL_ToolTipTimer::CFWL_ToolTipTimer(CFWL_ToolTipImp* pToolTip) : m_pToolTip(pToolTip) {} int32_t CFWL_ToolTipImp::CFWL_ToolTipTimer::Run(FWL_HTIMER hTimer) { if (m_pToolTip->m_hTimerShow == hTimer && m_pToolTip->m_hTimerShow) { if (m_pToolTip->GetStates() & FWL_WGTSTATE_Invisible) { m_pToolTip->SetStates(FWL_WGTSTATE_Invisible, FALSE); m_pToolTip->RefreshToolTipPos(); FWL_StopTimer(m_pToolTip->m_hTimerShow); m_pToolTip->m_hTimerShow = NULL; return TRUE; } } if (m_pToolTip->m_hTimerHide == hTimer && m_pToolTip->m_hTimerHide) { m_pToolTip->SetStates(FWL_WGTSTATE_Invisible, TRUE); FWL_StopTimer(m_pToolTip->m_hTimerHide); m_pToolTip->m_hTimerHide = NULL; return TRUE; } return TRUE; } CFWL_ToolTipImpDelegate::CFWL_ToolTipImpDelegate(CFWL_ToolTipImp* pOwner) : m_pOwner(pOwner) {} int32_t CFWL_ToolTipImpDelegate::OnProcessMessage(CFWL_Message* pMessage) { return CFWL_WidgetImpDelegate::OnProcessMessage(pMessage); } FWL_ERR CFWL_ToolTipImpDelegate::OnProcessEvent(CFWL_Event* pEvent) { return FWL_ERR_Succeeded; } FWL_ERR CFWL_ToolTipImpDelegate::OnDrawWidget(CFX_Graphics* pGraphics, const CFX_Matrix* pMatrix) { return m_pOwner->DrawWidget(pGraphics, pMatrix); }
#include "xfa/src/foxitlib.h" #include "xfa/src/fwl/src/core/include/fwl_targetimp.h" #include "xfa/src/fwl/src/core/include/fwl_noteimp.h" #include "xfa/src/fwl/src/core/include/fwl_widgetimp.h" #include "xfa/src/fwl/src/core/include/fwl_panelimp.h" #include "xfa/src/fwl/src/core/include/fwl_formimp.h" #include "xfa/src/fwl/src/basewidget/include/fwl_tooltipctrlimp.h" IFWL_ToolTip* IFWL_ToolTip::Create(const CFWL_WidgetImpProperties& properties, IFWL_Widget* pOuter) { IFWL_ToolTip* pToolTip = new IFWL_ToolTip; CFWL_ToolTipImp* pToolTipImpl = new CFWL_ToolTipImp(properties, pOuter); pToolTip->SetImpl(pToolTipImpl); pToolTipImpl->SetInterface(pToolTip); return pToolTip; } FWL_ERR IFWL_ToolTip::SetAnchor(const CFX_RectF& rtAnchor) { return static_cast<CFWL_ToolTipImp*>(GetImpl())->SetAnchor(rtAnchor); } FWL_ERR IFWL_ToolTip::Show() { return static_cast<CFWL_ToolTipImp*>(GetImpl())->Show(); } FWL_ERR IFWL_ToolTip::Hide() { return static_cast<CFWL_ToolTipImp*>(GetImpl())->Hide(); } IFWL_ToolTip::IFWL_ToolTip() { } CFWL_ToolTipImp::CFWL_ToolTipImp(const CFWL_WidgetImpProperties& properties, IFWL_Widget* pOuter) : CFWL_FormImp(properties, pOuter), m_bBtnDown(FALSE), m_dwTTOStyles(FDE_TTOSTYLE_SingleLine), m_iTTOAlign(FDE_TTOALIGNMENT_Center), m_hTimerShow(NULL), m_hTimerHide(NULL), m_pTimer(NULL) { m_rtClient.Set(0, 0, 0, 0); m_rtCaption.Set(0, 0, 0, 0); m_rtAnchor.Set(0, 0, 0, 0); m_TimerShow.m_pToolTip = this; m_TimerHide.m_pToolTip = this; } CFWL_ToolTipImp::~CFWL_ToolTipImp() { if (m_pTimer) { delete m_pTimer; m_pTimer = NULL; } } FWL_ERR CFWL_ToolTipImp::GetClassName(CFX_WideString& wsClass) const { wsClass = FWL_CLASS_ToolTip; return FWL_ERR_Succeeded; } FX_DWORD CFWL_ToolTipImp::GetClassID() const { return FWL_CLASSHASH_ToolTip; } FWL_ERR CFWL_ToolTipImp::Initialize() { m_pProperties->m_dwStyles |= FWL_WGTSTYLE_Popup; m_pProperties->m_dwStyles &= ~FWL_WGTSTYLE_Child; if (CFWL_WidgetImp::Initialize() != FWL_ERR_Succeeded) return FWL_ERR_Indefinite; m_pDelegate = new CFWL_ToolTipImpDelegate(this); return FWL_ERR_Succeeded; } FWL_ERR CFWL_ToolTipImp::Finalize() { delete m_pDelegate; m_pDelegate = nullptr; return CFWL_WidgetImp::Finalize(); } FWL_ERR CFWL_ToolTipImp::GetWidgetRect(CFX_RectF& rect, FX_BOOL bAutoSize) { if (bAutoSize) { rect.Set(0, 0, 0, 0); if (m_pProperties->m_pThemeProvider == NULL) { m_pProperties->m_pThemeProvider = GetAvailableTheme(); } CFX_WideString wsCaption; IFWL_ToolTipDP* pData = static_cast<IFWL_ToolTipDP*>(m_pProperties->m_pDataProvider); if (pData) { pData->GetCaption(m_pInterface, wsCaption); } int32_t iLen = wsCaption.GetLength(); if (iLen > 0) { CFX_SizeF sz = CalcTextSize(wsCaption, m_pProperties->m_pThemeProvider); rect.Set(0, 0, sz.x, sz.y); rect.width += FWL_WGTCAPACITY_CXBorder * 25; rect.height += FWL_WGTCAPACITY_CYBorder * 8; } CFWL_WidgetImp::GetWidgetRect(rect, TRUE); } else { rect = m_pProperties->m_rtWidget; } return FWL_ERR_Succeeded; } FWL_ERR CFWL_ToolTipImp::Update() { if (IsLocked()) {
FWL_ERR CFWL_ToolTipImp::GetClientRect(CFX_RectF& rect) { FX_FLOAT x = 0; FX_FLOAT y = 0; FX_FLOAT t = 0; IFWL_ThemeProvider* pTheme = m_pProperties->m_pThemeProvider; if (pTheme) { CFWL_ThemePart part; part.m_pWidget = m_pInterface; x = *static_cast<FX_FLOAT*>( pTheme->GetCapacity(&part, FWL_WGTCAPACITY_CXBorder)); y = *static_cast<FX_FLOAT*>( pTheme->GetCapacity(&part, FWL_WGTCAPACITY_CYBorder)); } rect = m_pProperties->m_rtWidget; rect.Offset(-rect.left, -rect.top); rect.Deflate(x, t, x, y); return FWL_ERR_Succeeded; } FWL_ERR CFWL_ToolTipImp::DrawWidget(CFX_Graphics* pGraphics, const CFX_Matrix* pMatrix) { IFWL_ToolTipTarget* toolTipTarget = CFWL_ToolTipContainer::getInstance()->GetCurrentToolTipTarget(); if (toolTipTarget && !toolTipTarget->UseDefaultTheme()) { return toolTipTarget->DrawToolTip(pGraphics, pMatrix, m_pInterface); } if (!pGraphics) return FWL_ERR_Indefinite; if (!m_pProperties->m_pThemeProvider) return FWL_ERR_Indefinite; IFWL_ThemeProvider* pTheme = m_pProperties->m_pThemeProvider; DrawBkground(pGraphics, pTheme, pMatrix); DrawText(pGraphics, pTheme, pMatrix); return FWL_ERR_Succeeded; } void CFWL_ToolTipImp::DrawBkground(CFX_Graphics* pGraphics, IFWL_ThemeProvider* pTheme, const CFX_Matrix* pMatrix) { CFWL_ThemeBackground param; param.m_pWidget = m_pInterface; param.m_iPart = FWL_PART_TTP_Background; param.m_dwStates = m_pProperties->m_dwStates; param.m_pGraphics = pGraphics; if (pMatrix) { param.m_matrix.Concat(*pMatrix); } param.m_rtPart = m_rtClient; if (m_pProperties->m_dwStates & FWL_WGTSTATE_Focused) { param.m_pData = &m_rtCaption; } pTheme->DrawBackground(&param); } void CFWL_ToolTipImp::DrawText(CFX_Graphics* pGraphics, IFWL_ThemeProvider* pTheme, const CFX_Matrix* pMatrix) { if (!m_pProperties->m_pDataProvider) return; CFX_WideString wsCaption; m_pProperties->m_pDataProvider->GetCaption(m_pInterface, wsCaption); if (wsCaption.IsEmpty()) { return; } CFWL_ThemeText param; param.m_pWidget = m_pInterface; param.m_iPart = FWL_PART_TTP_Caption; param.m_dwStates = m_pProperties->m_dwStates; param.m_pGraphics = pGraphics; if (pMatrix) { param.m_matrix.Concat(*pMatrix); } param.m_rtPart = m_rtCaption; param.m_wsText = wsCaption; param.m_dwTTOStyles = m_dwTTOStyles; param.m_iTTOAlign = m_iTTOAlign; pTheme->DrawText(&param); } void CFWL_ToolTipImp::UpdateTextOutStyles() { m_iTTOAlign = FDE_TTOALIGNMENT_Center; m_dwTTOStyles = FDE_TTOSTYLE_SingleLine; if (m_pProperties->m_dwStyleExes & FWL_WGTSTYLE_RTLReading) { m_dwTTOStyles |= FDE_TTOSTYLE_RTL; } if (m_pProperties->m_dwStyleExes & FWL_STYLEEXT_TTP_Multiline) { m_dwTTOStyles &= ~FDE_TTOSTYLE_SingleLine; } } FWL_ERR CFWL_ToolTipImp::SetAnchor(const CFX_RectF& rtAnchor) { m_rtAnchor = rtAnchor; return TRUE; } FWL_ERR CFWL_ToolTipImp::Show() { IFWL_ToolTipDP* pData = static_cast<IFWL_ToolTipDP*>(m_pProperties->m_pDataProvider); int32_t nInitDelay = pData->GetInitialDelay(m_pInterface); if ((m_pProperties->m_dwStates & FWL_WGTSTATE_Invisible)) { m_hTimerShow = FWL_StartTimer(&m_TimerShow, nInitDelay, FALSE); } return TRUE; } FWL_ERR CFWL_ToolTipImp::Hide() { SetStates(FWL_WGTSTATE_Invisible, TRUE); if (m_hTimerHide) { FWL_StopTimer(m_hTimerHide); m_hTimerHide = NULL; } if (m_hTimerShow) { FWL_StopTimer(m_hTimerShow); m_hTimerShow = NULL; } return TRUE; } FWL_ERR CFWL_ToolTipImp::SetStates(FX_DWORD dwStates, FX_BOOL bSet) { if ((dwStates & FWL_WGTSTATE_Invisible) && !bSet) { IFWL_ToolTipDP* pData = static_cast<IFWL_ToolTipDP*>(m_pProperties->m_pDataProvider); int32_t nAutoPopDelay = pData->GetAutoPopDelay(m_pInterface); m_hTimerHide = FWL_StartTimer(&m_TimerHide, nAutoPopDelay, FALSE); } return CFWL_WidgetImp::SetStates(dwStates, bSet); } void CFWL_ToolTipImp::RefreshToolTipPos() { if ((m_pProperties->m_dwStyleExes & FWL_STYLEEXT_TTP_NoAnchor) == 0) { CFX_RectF rtPopup; CFX_RectF rtWidget(m_pProperties->m_rtWidget); CFX_RectF rtAnchor(m_rtAnchor); rtPopup.Set(0, 0, 0, 0); FX_FLOAT fx = rtAnchor.Center().x + 20; FX_FLOAT fy = rtAnchor.Center().y + 20; rtPopup.Set(fx, fy, rtWidget.Width(), rtWidget.Height()); FX_FLOAT fScreenWidth = 0; FX_FLOAT fScreenHeight = 0; GetScreenSize(fScreenWidth, fScreenHeight); if (rtPopup.bottom() > fScreenHeight) { rtPopup.Offset(0, fScreenHeight - rtPopup.bottom()); } if (rtPopup.right() > fScreenWidth) { rtPopup.Offset(fScreenWidth - rtPopup.right(), 0); } if (rtPopup.left < 0) { rtPopup.Offset(0 - rtPopup.left, 0); } if (rtPopup.top < 0) { rtPopup.Offset(0, 0 - rtPopup.top); } SetWidgetRect(rtPopup); Update(); } } CFWL_ToolTipImp::CFWL_ToolTipTimer::CFWL_ToolTipTimer(CFWL_ToolTipImp* pToolTip) : m_pToolTip(pToolTip) {} int32_t CFWL_ToolTipImp::CFWL_ToolTipTimer::Run(FWL_HTIMER hTimer) { if (m_pToolTip->m_hTimerShow == hTimer && m_pToolTip->m_hTimerShow) { if (m_pToolTip->GetStates() & FWL_WGTSTATE_Invisible) { m_pToolTip->SetStates(FWL_WGTSTATE_Invisible, FALSE); m_pToolTip->RefreshToolTipPos(); FWL_StopTimer(m_pToolTip->m_hTimerShow); m_pToolTip->m_hTimerShow = NULL; return TRUE; } } if (m_pToolTip->m_hTimerHide == hTimer && m_pToolTip->m_hTimerHide) { m_pToolTip->SetStates(FWL_WGTSTATE_Invisible, TRUE); FWL_StopTimer(m_pToolTip->m_hTimerHide); m_pToolTip->m_hTimerHide = NULL; return TRUE; } return TRUE; } CFWL_ToolTipImpDelegate::CFWL_ToolTipImpDelegate(CFWL_ToolTipImp* pOwner) : m_pOwner(pOwner) {} int32_t CFWL_ToolTipImpDelegate::OnProcessMessage(CFWL_Message* pMessage) { return CFWL_WidgetImpDelegate::OnProcessMessage(pMessage); } FWL_ERR CFWL_ToolTipImpDelegate::OnProcessEvent(CFWL_Event* pEvent) { return FWL_ERR_Succeeded; } FWL_ERR CFWL_ToolTipImpDelegate::OnDrawWidget(CFX_Graphics* pGraphics, const CFX_Matrix* pMatrix) { return m_pOwner->DrawWidget(pGraphics, pMatrix); }
return FWL_ERR_Indefinite; } if (!m_pProperties->m_pThemeProvider) { m_pProperties->m_pThemeProvider = GetAvailableTheme(); } UpdateTextOutStyles(); GetClientRect(m_rtClient); m_rtCaption = m_rtClient; return FWL_ERR_Succeeded; }
function_block-function_prefix_line
[ { "content": "class CLST_Rect : public CPDF_Rect {\n\n public:\n\n CLST_Rect() { left = top = right = bottom = 0.0f; }\n\n\n\n CLST_Rect(FX_FLOAT other_left,\n\n FX_FLOAT other_top,\n\n FX_FLOAT other_right,\n\n FX_FLOAT other_bottom) {\n\n left = other_left;\n\n top = o...
C++
qtmultimedia/tests/auto/unit/qmediaserviceprovider/tst_qmediaserviceprovider.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
#include <QtTest/QtTest> #include <QDebug> #include <QStringList> #include <private/qmediaserviceprovider_p.h> #include <qmediaserviceproviderplugin.h> #include <private/qmediapluginloader_p.h> #include <qmediaobject.h> #include <qmediaservice.h> #include <qmediaplayer.h> #include <qaudiorecorder.h> #include <qcamera.h> #include <qcamerainfo.h> QT_USE_NAMESPACE class MockMediaServiceProvider : public QMediaServiceProvider { QMediaService* requestService(const QByteArray &type, const QMediaServiceProviderHint &) { Q_UNUSED(type); return 0; } void releaseService(QMediaService *service) { Q_UNUSED(service); } }; class tst_QMediaServiceProvider : public QObject { Q_OBJECT public slots: void initTestCase(); private slots: void testDefaultProviderAvailable(); void testObtainService(); void testHasSupport(); void testSupportedMimeTypes(); void testProviderHints(); void testDefaultDevice(); void testAvailableDevices(); void testCameraInfo(); private: QObjectList plugins; }; void tst_QMediaServiceProvider::initTestCase() { QCoreApplication::setLibraryPaths(QStringList() << QCoreApplication::applicationDirPath()); } void tst_QMediaServiceProvider::testDefaultProviderAvailable() { QVERIFY(QMediaServiceProvider::defaultServiceProvider() != 0); } void tst_QMediaServiceProvider::testObtainService() { QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider(); if (provider == 0) QSKIP("No default provider"); QMediaService *service = 0; service = provider->requestService(Q_MEDIASERVICE_MEDIAPLAYER); QVERIFY(service != 0); provider->releaseService(service); } void tst_QMediaServiceProvider::testHasSupport() { MockMediaServiceProvider mockProvider; QCOMPARE(mockProvider.hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/ogv", QStringList()), QMultimedia::MaybeSupported); QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider(); if (provider == 0) QSKIP("No default provider"); QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/ogv", QStringList()), QMultimedia::MaybeSupported); QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "audio/ogg", QStringList()), QMultimedia::ProbablySupported); QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "audio/wav", QStringList()), QMultimedia::ProbablySupported); QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/avi", QStringList() << "mpeg4"), QMultimedia::MaybeSupported); QCOMPARE(provider->hasSupport(QByteArray("non existing service"), "video/ogv", QStringList()), QMultimedia::NotSupported); QCOMPARE(QMediaPlayer::hasSupport("video/ogv"), QMultimedia::MaybeSupported); QCOMPARE(QMediaPlayer::hasSupport("audio/ogg"), QMultimedia::ProbablySupported); QCOMPARE(QMediaPlayer::hasSupport("audio/wav"), QMultimedia::ProbablySupported); QCOMPARE(QMediaPlayer::hasSupport("audio/wav", QStringList(), QMediaPlayer::LowLatency), QMultimedia::ProbablySupported); QCOMPARE(QMediaPlayer::hasSupport("audio/ogg", QStringList(), QMediaPlayer::LowLatency), QMultimedia::ProbablySupported); QCOMPARE(QMediaPlayer::hasSupport("video/quicktime", QStringList(), QMediaPlayer::LowLatency), QMultimedia::MaybeSupported); QCOMPARE(QMediaPlayer::hasSupport("video/quicktime", QStringList(), QMediaPlayer::StreamPlayback), QMultimedia::ProbablySupported); QCOMPARE(QMediaPlayer::hasSupport("audio/wav", QStringList(), QMediaPlayer::StreamPlayback), QMultimedia::MaybeSupported); QMediaPlayer simplePlayer(0, QMediaPlayer::LowLatency); QCOMPARE(simplePlayer.service()->objectName(), QLatin1String("MockServicePlugin2")); QMediaPlayer mediaPlayer; QVERIFY(mediaPlayer.service()->objectName() != QLatin1String("MockServicePlugin2")); QMediaPlayer streamPlayer(0, QMediaPlayer::StreamPlayback); QCOMPARE(streamPlayer.service()->objectName(), QLatin1String("MockServicePlugin4")); } void tst_QMediaServiceProvider::testSupportedMimeTypes() { QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider(); if (provider == 0) QSKIP("No default provider"); QVERIFY(provider->supportedMimeTypes(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER)).contains("audio/ogg")); QVERIFY(!provider->supportedMimeTypes(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER)).contains("audio/mp3")); } void tst_QMediaServiceProvider::testProviderHints() { { QMediaServiceProviderHint hint; QVERIFY(hint.isNull()); QCOMPARE(hint.type(), QMediaServiceProviderHint::Null); QVERIFY(hint.device().isEmpty()); QCOMPARE(hint.cameraPosition(), QCamera::UnspecifiedPosition); QVERIFY(hint.mimeType().isEmpty()); QVERIFY(hint.codecs().isEmpty()); QCOMPARE(hint.features(), 0); } { QByteArray deviceName(QByteArray("testDevice")); QMediaServiceProviderHint hint(deviceName); QVERIFY(!hint.isNull()); QCOMPARE(hint.type(), QMediaServiceProviderHint::Device); QCOMPARE(hint.device(), deviceName); QCOMPARE(hint.cameraPosition(), QCamera::UnspecifiedPosition); QVERIFY(hint.mimeType().isEmpty()); QVERIFY(hint.codecs().isEmpty()); QCOMPARE(hint.features(), 0); } { QMediaServiceProviderHint hint(QCamera::FrontFace); QVERIFY(!hint.isNull()); QCOMPARE(hint.type(), QMediaServiceProviderHint::CameraPosition); QVERIFY(hint.device().isEmpty()); QCOMPARE(hint.cameraPosition(), QCamera::FrontFace); QVERIFY(hint.mimeType().isEmpty()); QVERIFY(hint.codecs().isEmpty()); QCOMPARE(hint.features(), 0); } { QMediaServiceProviderHint hint(QMediaServiceProviderHint::LowLatencyPlayback); QVERIFY(!hint.isNull()); QCOMPARE(hint.type(), QMediaServiceProviderHint::SupportedFeatures); QVERIFY(hint.device().isEmpty()); QCOMPARE(hint.cameraPosition(), QCamera::UnspecifiedPosition); QVERIFY(hint.mimeType().isEmpty()); QVERIFY(hint.codecs().isEmpty()); QCOMPARE(hint.features(), QMediaServiceProviderHint::LowLatencyPlayback); } { QMediaServiceProviderHint hint(QMediaServiceProviderHint::RecordingSupport); QVERIFY(!hint.isNull()); QCOMPARE(hint.type(), QMediaServiceProviderHint::SupportedFeatures); QVERIFY(hint.device().isEmpty()); QCOMPARE(hint.cameraPosition(), QCamera::UnspecifiedPosition); QVERIFY(hint.mimeType().isEmpty()); QVERIFY(hint.codecs().isEmpty()); QCOMPARE(hint.features(), QMediaServiceProviderHint::RecordingSupport); } { QString mimeType(QLatin1String("video/ogg")); QStringList codecs; codecs << "theora" << "vorbis"; QMediaServiceProviderHint hint(mimeType,codecs); QVERIFY(!hint.isNull()); QCOMPARE(hint.type(), QMediaServiceProviderHint::ContentType); QVERIFY(hint.device().isEmpty()); QCOMPARE(hint.cameraPosition(), QCamera::UnspecifiedPosition); QCOMPARE(hint.mimeType(), mimeType); QCOMPARE(hint.codecs(), codecs); QMediaServiceProviderHint hint2(hint); QVERIFY(!hint2.isNull()); QCOMPARE(hint2.type(), QMediaServiceProviderHint::ContentType); QVERIFY(hint2.device().isEmpty()); QCOMPARE(hint.cameraPosition(), QCamera::UnspecifiedPosition); QCOMPARE(hint2.mimeType(), mimeType); QCOMPARE(hint2.codecs(), codecs); QMediaServiceProviderHint hint3; QVERIFY(hint3.isNull()); hint3 = hint; QVERIFY(!hint3.isNull()); QCOMPARE(hint3.type(), QMediaServiceProviderHint::ContentType); QVERIFY(hint3.device().isEmpty()); QCOMPARE(hint.cameraPosition(), QCamera::UnspecifiedPosition); QCOMPARE(hint3.mimeType(), mimeType); QCOMPARE(hint3.codecs(), codecs); QCOMPARE(hint, hint2); QCOMPARE(hint3, hint2); QMediaServiceProviderHint hint4(mimeType,codecs); QCOMPARE(hint, hint4); QMediaServiceProviderHint hint5(mimeType,QStringList()); QVERIFY(hint != hint5); } } void tst_QMediaServiceProvider::testDefaultDevice() { QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider(); if (provider == 0) QSKIP("No default provider"); QCOMPARE(provider->defaultDevice(Q_MEDIASERVICE_AUDIOSOURCE), QByteArray("audiosource1")); QCOMPARE(provider->defaultDevice(Q_MEDIASERVICE_CAMERA), QByteArray("frontcamera")); } void tst_QMediaServiceProvider::testAvailableDevices() { QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider(); if (provider == 0) QSKIP("No default provider"); QList<QByteArray> devices = provider->devices(Q_MEDIASERVICE_AUDIOSOURCE); QCOMPARE(devices.count(), 2); QCOMPARE(devices.at(0), QByteArray("audiosource1")); QCOMPARE(devices.at(1), QByteArray("audiosource2")); devices = provider->devices(Q_MEDIASERVICE_CAMERA); QCOMPARE(devices.count(), 3); QCOMPARE(devices.at(0), QByteArray("frontcamera")); QCOMPARE(devices.at(1), QByteArray("backcamera")); QCOMPARE(devices.at(2), QByteArray("somecamera")); } void tst_QMediaServiceProvider::testCameraInfo() { QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider(); if (provider == 0) QSKIP("No default provider"); QCOMPARE(provider->cameraPosition("backcamera"), QCamera::BackFace); QCOMPARE(provider->cameraOrientation("backcamera"), 90); QCOMPARE(provider->cameraPosition("frontcamera"), QCamera::FrontFace); QCOMPARE(provider->cameraOrientation("frontcamera"), 270); QCOMPARE(provider->cameraPosition("somecamera"), QCamera::UnspecifiedPosition); QCOMPARE(provider->cameraOrientation("somecamera"), 0); { QCamera camera; QVERIFY(camera.service()); QCOMPARE(camera.service()->objectName(), QLatin1String("MockServicePlugin3")); } { QCamera camera(QCameraInfo::defaultCamera()); QVERIFY(camera.service()); QCOMPARE(camera.service()->objectName(), QLatin1String("MockServicePlugin3")); } { QCamera camera(QCameraInfo::availableCameras().at(0)); QVERIFY(camera.service()); QCOMPARE(camera.service()->objectName(), QLatin1String("MockServicePlugin3")); } { QCamera camera(QCameraInfo::availableCameras().at(1)); QVERIFY(camera.service()); QCOMPARE(camera.service()->objectName(), QLatin1String("MockServicePlugin5")); } { QCamera camera(QCameraInfo::availableCameras().at(2)); QVERIFY(camera.service()); QCOMPARE(camera.service()->objectName(), QLatin1String("MockServicePlugin5")); } { QCamera camera(QCamera::FrontFace); QVERIFY(camera.service()); QCOMPARE(camera.service()->objectName(), QLatin1String("MockServicePlugin3")); } { QCamera camera(QCamera::BackFace); QVERIFY(camera.service()); QCOMPARE(camera.service()->objectName(), QLatin1String("MockServicePlugin5")); } { QCamera camera(QCamera::UnspecifiedPosition); QVERIFY(camera.service()); QCOMPARE(camera.service()->objectName(), QLatin1String("MockServicePlugin3")); } } QTEST_MAIN(tst_QMediaServiceProvider) #include "tst_qmediaserviceprovider.moc"
#include <QtTest/QtTest> #include <QDebug> #include <QStringList> #include <private/qmediaserviceprovider_p.h> #include <qmediaserviceproviderplugin.h> #include <private/qmediapluginloader_p.h> #include <qmediaobject.h> #include <qmediaservice.h> #include <qmediaplayer.h> #include <qaudiorecorder.h> #include <qcamera.h> #include <qcamerainfo.h> QT_USE_NAMESPACE class MockMediaServiceProvider : public QMediaServiceProvider { QMediaService* requestService(const QByteArray &type, const QMediaServiceProviderHint &) { Q_UNUSED(type); return 0; } void releaseService(QMediaService *service) { Q_UNUSED(service); } }; class tst_QMediaServiceProvider : public QObject { Q_OBJECT public slots: void initTestCase(); private slots: void testDefaultProviderAvailable(); void testObtainService(); void testHasSupport(); void testSupportedMimeTypes(); void testProviderHints(); void testDefaultDevice(); void testAvailableDevices(); void testCameraInfo(); private: QObjectList plugins; }; void tst_QMediaServiceProvider::initTestCase() { QCoreApplication::setLibraryPaths(QStringList() << QCoreApplication::applicationDirPath()); } void tst_QMediaServiceProvider::testDefaultProviderAvailable() { QVERIFY(QMediaServiceProvider::defaultServiceProvider() != 0); } void tst_QMediaServiceProvider::testObtainService() { QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider(); if (provider == 0) QSKIP("No default provider"); QMediaService *service = 0; service = provider->requestService(Q_MEDIASERVICE_MEDIAPLAYER); QVERIFY(service != 0); provider->releaseService(service); } void tst_QMediaServiceProvider::testHasSupport() { MockMediaServiceProvider mockProvider; QCOMPARE(mockProvider.hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/ogv", QStringList()), QMultimedia::MaybeSupported); QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider(); if (provider == 0) QSKIP("No default provider"); QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/ogv", QStringList()), QMultimedia::MaybeSupported); QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "audio/ogg", QStringList()), QMultimedia::ProbablySupported); QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "audio/wav", QStringL
e(), QMediaServiceProviderHint::Device); QCOMPARE(hint.device(), deviceName); QCOMPARE(hint.cameraPosition(), QCamera::UnspecifiedPosition); QVERIFY(hint.mimeType().isEmpty()); QVERIFY(hint.codecs().isEmpty()); QCOMPARE(hint.features(), 0); } { QMediaServiceProviderHint hint(QCamera::FrontFace); QVERIFY(!hint.isNull()); QCOMPARE(hint.type(), QMediaServiceProviderHint::CameraPosition); QVERIFY(hint.device().isEmpty()); QCOMPARE(hint.cameraPosition(), QCamera::FrontFace); QVERIFY(hint.mimeType().isEmpty()); QVERIFY(hint.codecs().isEmpty()); QCOMPARE(hint.features(), 0); } { QMediaServiceProviderHint hint(QMediaServiceProviderHint::LowLatencyPlayback); QVERIFY(!hint.isNull()); QCOMPARE(hint.type(), QMediaServiceProviderHint::SupportedFeatures); QVERIFY(hint.device().isEmpty()); QCOMPARE(hint.cameraPosition(), QCamera::UnspecifiedPosition); QVERIFY(hint.mimeType().isEmpty()); QVERIFY(hint.codecs().isEmpty()); QCOMPARE(hint.features(), QMediaServiceProviderHint::LowLatencyPlayback); } { QMediaServiceProviderHint hint(QMediaServiceProviderHint::RecordingSupport); QVERIFY(!hint.isNull()); QCOMPARE(hint.type(), QMediaServiceProviderHint::SupportedFeatures); QVERIFY(hint.device().isEmpty()); QCOMPARE(hint.cameraPosition(), QCamera::UnspecifiedPosition); QVERIFY(hint.mimeType().isEmpty()); QVERIFY(hint.codecs().isEmpty()); QCOMPARE(hint.features(), QMediaServiceProviderHint::RecordingSupport); } { QString mimeType(QLatin1String("video/ogg")); QStringList codecs; codecs << "theora" << "vorbis"; QMediaServiceProviderHint hint(mimeType,codecs); QVERIFY(!hint.isNull()); QCOMPARE(hint.type(), QMediaServiceProviderHint::ContentType); QVERIFY(hint.device().isEmpty()); QCOMPARE(hint.cameraPosition(), QCamera::UnspecifiedPosition); QCOMPARE(hint.mimeType(), mimeType); QCOMPARE(hint.codecs(), codecs); QMediaServiceProviderHint hint2(hint); QVERIFY(!hint2.isNull()); QCOMPARE(hint2.type(), QMediaServiceProviderHint::ContentType); QVERIFY(hint2.device().isEmpty()); QCOMPARE(hint.cameraPosition(), QCamera::UnspecifiedPosition); QCOMPARE(hint2.mimeType(), mimeType); QCOMPARE(hint2.codecs(), codecs); QMediaServiceProviderHint hint3; QVERIFY(hint3.isNull()); hint3 = hint; QVERIFY(!hint3.isNull()); QCOMPARE(hint3.type(), QMediaServiceProviderHint::ContentType); QVERIFY(hint3.device().isEmpty()); QCOMPARE(hint.cameraPosition(), QCamera::UnspecifiedPosition); QCOMPARE(hint3.mimeType(), mimeType); QCOMPARE(hint3.codecs(), codecs); QCOMPARE(hint, hint2); QCOMPARE(hint3, hint2); QMediaServiceProviderHint hint4(mimeType,codecs); QCOMPARE(hint, hint4); QMediaServiceProviderHint hint5(mimeType,QStringList()); QVERIFY(hint != hint5); } } void tst_QMediaServiceProvider::testDefaultDevice() { QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider(); if (provider == 0) QSKIP("No default provider"); QCOMPARE(provider->defaultDevice(Q_MEDIASERVICE_AUDIOSOURCE), QByteArray("audiosource1")); QCOMPARE(provider->defaultDevice(Q_MEDIASERVICE_CAMERA), QByteArray("frontcamera")); } void tst_QMediaServiceProvider::testAvailableDevices() { QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider(); if (provider == 0) QSKIP("No default provider"); QList<QByteArray> devices = provider->devices(Q_MEDIASERVICE_AUDIOSOURCE); QCOMPARE(devices.count(), 2); QCOMPARE(devices.at(0), QByteArray("audiosource1")); QCOMPARE(devices.at(1), QByteArray("audiosource2")); devices = provider->devices(Q_MEDIASERVICE_CAMERA); QCOMPARE(devices.count(), 3); QCOMPARE(devices.at(0), QByteArray("frontcamera")); QCOMPARE(devices.at(1), QByteArray("backcamera")); QCOMPARE(devices.at(2), QByteArray("somecamera")); } void tst_QMediaServiceProvider::testCameraInfo() { QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider(); if (provider == 0) QSKIP("No default provider"); QCOMPARE(provider->cameraPosition("backcamera"), QCamera::BackFace); QCOMPARE(provider->cameraOrientation("backcamera"), 90); QCOMPARE(provider->cameraPosition("frontcamera"), QCamera::FrontFace); QCOMPARE(provider->cameraOrientation("frontcamera"), 270); QCOMPARE(provider->cameraPosition("somecamera"), QCamera::UnspecifiedPosition); QCOMPARE(provider->cameraOrientation("somecamera"), 0); { QCamera camera; QVERIFY(camera.service()); QCOMPARE(camera.service()->objectName(), QLatin1String("MockServicePlugin3")); } { QCamera camera(QCameraInfo::defaultCamera()); QVERIFY(camera.service()); QCOMPARE(camera.service()->objectName(), QLatin1String("MockServicePlugin3")); } { QCamera camera(QCameraInfo::availableCameras().at(0)); QVERIFY(camera.service()); QCOMPARE(camera.service()->objectName(), QLatin1String("MockServicePlugin3")); } { QCamera camera(QCameraInfo::availableCameras().at(1)); QVERIFY(camera.service()); QCOMPARE(camera.service()->objectName(), QLatin1String("MockServicePlugin5")); } { QCamera camera(QCameraInfo::availableCameras().at(2)); QVERIFY(camera.service()); QCOMPARE(camera.service()->objectName(), QLatin1String("MockServicePlugin5")); } { QCamera camera(QCamera::FrontFace); QVERIFY(camera.service()); QCOMPARE(camera.service()->objectName(), QLatin1String("MockServicePlugin3")); } { QCamera camera(QCamera::BackFace); QVERIFY(camera.service()); QCOMPARE(camera.service()->objectName(), QLatin1String("MockServicePlugin5")); } { QCamera camera(QCamera::UnspecifiedPosition); QVERIFY(camera.service()); QCOMPARE(camera.service()->objectName(), QLatin1String("MockServicePlugin3")); } } QTEST_MAIN(tst_QMediaServiceProvider) #include "tst_qmediaserviceprovider.moc"
ist()), QMultimedia::ProbablySupported); QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/avi", QStringList() << "mpeg4"), QMultimedia::MaybeSupported); QCOMPARE(provider->hasSupport(QByteArray("non existing service"), "video/ogv", QStringList()), QMultimedia::NotSupported); QCOMPARE(QMediaPlayer::hasSupport("video/ogv"), QMultimedia::MaybeSupported); QCOMPARE(QMediaPlayer::hasSupport("audio/ogg"), QMultimedia::ProbablySupported); QCOMPARE(QMediaPlayer::hasSupport("audio/wav"), QMultimedia::ProbablySupported); QCOMPARE(QMediaPlayer::hasSupport("audio/wav", QStringList(), QMediaPlayer::LowLatency), QMultimedia::ProbablySupported); QCOMPARE(QMediaPlayer::hasSupport("audio/ogg", QStringList(), QMediaPlayer::LowLatency), QMultimedia::ProbablySupported); QCOMPARE(QMediaPlayer::hasSupport("video/quicktime", QStringList(), QMediaPlayer::LowLatency), QMultimedia::MaybeSupported); QCOMPARE(QMediaPlayer::hasSupport("video/quicktime", QStringList(), QMediaPlayer::StreamPlayback), QMultimedia::ProbablySupported); QCOMPARE(QMediaPlayer::hasSupport("audio/wav", QStringList(), QMediaPlayer::StreamPlayback), QMultimedia::MaybeSupported); QMediaPlayer simplePlayer(0, QMediaPlayer::LowLatency); QCOMPARE(simplePlayer.service()->objectName(), QLatin1String("MockServicePlugin2")); QMediaPlayer mediaPlayer; QVERIFY(mediaPlayer.service()->objectName() != QLatin1String("MockServicePlugin2")); QMediaPlayer streamPlayer(0, QMediaPlayer::StreamPlayback); QCOMPARE(streamPlayer.service()->objectName(), QLatin1String("MockServicePlugin4")); } void tst_QMediaServiceProvider::testSupportedMimeTypes() { QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider(); if (provider == 0) QSKIP("No default provider"); QVERIFY(provider->supportedMimeTypes(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER)).contains("audio/ogg")); QVERIFY(!provider->supportedMimeTypes(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER)).contains("audio/mp3")); } void tst_QMediaServiceProvider::testProviderHints() { { QMediaServiceProviderHint hint; QVERIFY(hint.isNull()); QCOMPARE(hint.type(), QMediaServiceProviderHint::Null); QVERIFY(hint.device().isEmpty()); QCOMPARE(hint.cameraPosition(), QCamera::UnspecifiedPosition); QVERIFY(hint.mimeType().isEmpty()); QVERIFY(hint.codecs().isEmpty()); QCOMPARE(hint.features(), 0); } { QByteArray deviceName(QByteArray("testDevice")); QMediaServiceProviderHint hint(deviceName); QVERIFY(!hint.isNull()); QCOMPARE(hint.typ
random
[]
C++
main/svl/source/misc/sharecontrolfile.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
#include "precompiled_svl.hxx" #include <stdio.h> #include <com/sun/star/ucb/XSimpleFileAccess.hpp> #include <com/sun/star/ucb/XCommandEnvironment.hpp> #include <com/sun/star/ucb/XContent.hpp> #include <com/sun/star/ucb/InsertCommandArgument.hpp> #include <com/sun/star/ucb/InteractiveIOException.hpp> #include <com/sun/star/io/WrongFormatException.hpp> #include <osl/time.h> #include <osl/security.hxx> #include <osl/socket.hxx> #include <rtl/string.hxx> #include <rtl/ustring.hxx> #include <rtl/strbuf.hxx> #include <rtl/ustrbuf.hxx> #include <comphelper/processfactory.hxx> #include <ucbhelper/content.hxx> #include <tools/urlobj.hxx> #include <tools/stream.hxx> #include <unotools/bootstrap.hxx> #include <unotools/streamwrap.hxx> #include <unotools/useroptions.hxx> #include <svl/sharecontrolfile.hxx> using namespace ::com::sun::star; namespace svt { ShareControlFile::ShareControlFile( const ::rtl::OUString& aOrigURL, const uno::Reference< lang::XMultiServiceFactory >& xFactory ) : LockFileCommon( aOrigURL, xFactory, ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".~sharing." ) ) ) { OpenStream(); if ( !IsValid() ) throw io::NotConnectedException(); } ShareControlFile::~ShareControlFile() { try { Close(); } catch( uno::Exception& ) {} } void ShareControlFile::OpenStream() { if ( !m_xStream.is() && m_aURL.getLength() ) { uno::Reference< ucb::XCommandEnvironment > xDummyEnv; ::ucbhelper::Content aContent = ::ucbhelper::Content( m_aURL, xDummyEnv ); uno::Reference< ucb::XContentIdentifier > xContId( aContent.get().is() ? aContent.get()->getIdentifier() : 0 ); if ( !xContId.is() || !xContId->getContentProviderScheme().equals( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "file" ) ) ) ) throw io::IOException(); uno::Reference< io::XStream > xStream; try { xStream = aContent.openWriteableStreamNoLock(); } catch ( ucb::InteractiveIOException const & e ) { if ( e.Code == ucb::IOErrorCode_NOT_EXISTING ) { SvMemoryStream aStream(0,0); uno::Reference< io::XInputStream > xInput( new ::utl::OInputStreamWrapper( aStream ) ); ucb::InsertCommandArgument aInsertArg; aInsertArg.Data = xInput; aInsertArg.ReplaceExisting = sal_False; aContent.executeCommand( rtl::OUString::createFromAscii( "insert" ), uno::makeAny( aInsertArg ) ); try { aContent.setPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsHidden" ) ), uno::makeAny( sal_True ) ); } catch( uno::Exception& ) {} xStream = aContent.openWriteableStreamNoLock(); } else throw; } m_xSeekable.set( xStream, uno::UNO_QUERY_THROW ); m_xInputStream.set( xStream->getInputStream(), uno::UNO_QUERY_THROW ); m_xOutputStream.set( xStream->getOutputStream(), uno::UNO_QUERY_THROW ); m_xTruncate.set( m_xOutputStream, uno::UNO_QUERY_THROW ); m_xStream = xStream; } } void ShareControlFile::Close() { if ( m_xStream.is() ) { try { if ( m_xInputStream.is() ) m_xInputStream->closeInput(); if ( m_xOutputStream.is() ) m_xOutputStream->closeOutput(); } catch( uno::Exception& ) {} m_xStream = uno::Reference< io::XStream >(); m_xInputStream = uno::Reference< io::XInputStream >(); m_xOutputStream = uno::Reference< io::XOutputStream >(); m_xSeekable = uno::Reference< io::XSeekable >(); m_xTruncate = uno::Reference< io::XTruncate >(); m_aUsersData.realloc( 0 ); } } uno::Sequence< uno::Sequence< ::rtl::OUString > > ShareControlFile::GetUsersData() { ::osl::MutexGuard aGuard( m_aMutex ); if ( !IsValid() ) throw io::NotConnectedException(); if ( !m_aUsersData.getLength() ) { sal_Int64 nLength = m_xSeekable->getLength(); if ( nLength > SAL_MAX_INT32 ) throw uno::RuntimeException(); uno::Sequence< sal_Int8 > aBuffer( (sal_Int32)nLength ); m_xSeekable->seek( 0 ); sal_Int32 nRead = m_xInputStream->readBytes( aBuffer, (sal_Int32)nLength ); nLength -= nRead; while ( nLength > 0 ) { uno::Sequence< sal_Int8 > aTmpBuf( (sal_Int32)nLength ); nRead = m_xInputStream->readBytes( aTmpBuf, (sal_Int32)nLength ); if ( nRead > nLength ) throw uno::RuntimeException(); for ( sal_Int32 nInd = 0; nInd < nRead; nInd++ ) aBuffer[aBuffer.getLength() - (sal_Int32)nLength + nInd] = aTmpBuf[nInd]; nLength -= nRead; } m_aUsersData = ParseList( aBuffer ); } return m_aUsersData; } void ShareControlFile::SetUsersDataAndStore( const uno::Sequence< uno::Sequence< ::rtl::OUString > >& aUsersData ) { ::osl::MutexGuard aGuard( m_aMutex ); if ( !IsValid() ) throw io::NotConnectedException(); if ( !m_xTruncate.is() || !m_xOutputStream.is() || !m_xSeekable.is() ) throw uno::RuntimeException(); m_xTruncate->truncate(); m_xSeekable->seek( 0 ); ::rtl::OUStringBuffer aBuffer; for ( sal_Int32 nInd = 0; nInd < aUsersData.getLength(); nInd++ ) { if ( aUsersData[nInd].getLength() != SHARED_ENTRYSIZE ) throw lang::IllegalArgumentException(); for ( sal_Int32 nEntryInd = 0; nEntryInd < SHARED_ENTRYSIZE; nEntryInd++ ) { aBuffer.append( EscapeCharacters( aUsersData[nInd][nEntryInd] ) ); if ( nEntryInd < SHARED_ENTRYSIZE - 1 ) aBuffer.append( (sal_Unicode)',' ); else aBuffer.append( (sal_Unicode)';' ); } } ::rtl::OString aStringData( ::rtl::OUStringToOString( aBuffer.makeStringAndClear(), RTL_TEXTENCODING_UTF8 ) ); uno::Sequence< sal_Int8 > aData( (sal_Int8*)aStringData.getStr(), aStringData.getLength() ); m_xOutputStream->writeBytes( aData ); m_aUsersData = aUsersData; } uno::Sequence< ::rtl::OUString > ShareControlFile::InsertOwnEntry() { ::osl::MutexGuard aGuard( m_aMutex ); if ( !IsValid() ) throw io::NotConnectedException(); GetUsersData(); uno::Sequence< ::uno::Sequence< ::rtl::OUString > > aNewData( m_aUsersData.getLength() + 1 ); uno::Sequence< ::rtl::OUString > aNewEntry = GenerateOwnEntry(); sal_Bool bExists = sal_False; sal_Int32 nNewInd = 0; for ( sal_Int32 nInd = 0; nInd < m_aUsersData.getLength(); nInd++ ) { if ( m_aUsersData[nInd].getLength() == SHARED_ENTRYSIZE ) { if ( m_aUsersData[nInd][SHARED_LOCALHOST_ID] == aNewEntry[SHARED_LOCALHOST_ID] && m_aUsersData[nInd][SHARED_SYSUSERNAME_ID] == aNewEntry[SHARED_SYSUSERNAME_ID] && m_aUsersData[nInd][SHARED_USERURL_ID] == aNewEntry[SHARED_USERURL_ID] ) { if ( !bExists ) { aNewData[nNewInd] = aNewEntry; bExists = sal_True; } } else { aNewData[nNewInd] = m_aUsersData[nInd]; } nNewInd++; } } if ( !bExists ) aNewData[nNewInd++] = aNewEntry; aNewData.realloc( nNewInd ); SetUsersDataAndStore( aNewData ); return aNewEntry; } bool ShareControlFile::HasOwnEntry() { ::osl::MutexGuard aGuard( m_aMutex ); if ( !IsValid() ) { throw io::NotConnectedException(); } GetUsersData(); uno::Sequence< ::rtl::OUString > aEntry = GenerateOwnEntry(); for ( sal_Int32 nInd = 0; nInd < m_aUsersData.getLength(); ++nInd ) { if ( m_aUsersData[nInd].getLength() == SHARED_ENTRYSIZE && m_aUsersData[nInd][SHARED_LOCALHOST_ID] == aEntry[SHARED_LOCALHOST_ID] && m_aUsersData[nInd][SHARED_SYSUSERNAME_ID] == aEntry[SHARED_SYSUSERNAME_ID] && m_aUsersData[nInd][SHARED_USERURL_ID] == aEntry[SHARED_USERURL_ID] ) { return true; } } return false; } void ShareControlFile::RemoveEntry( const uno::Sequence< ::rtl::OUString >& aArgEntry ) { ::osl::MutexGuard aGuard( m_aMutex ); if ( !IsValid() ) throw io::NotConnectedException(); GetUsersData(); uno::Sequence< ::rtl::OUString > aEntry = aArgEntry; if ( aEntry.getLength() != SHARED_ENTRYSIZE ) aEntry = GenerateOwnEntry(); uno::Sequence< ::uno::Sequence< ::rtl::OUString > > aNewData( m_aUsersData.getLength() + 1 ); sal_Int32 nNewInd = 0; for ( sal_Int32 nInd = 0; nInd < m_aUsersData.getLength(); nInd++ ) { if ( m_aUsersData[nInd].getLength() == SHARED_ENTRYSIZE ) { if ( m_aUsersData[nInd][SHARED_LOCALHOST_ID] != aEntry[SHARED_LOCALHOST_ID] || m_aUsersData[nInd][SHARED_SYSUSERNAME_ID] != aEntry[SHARED_SYSUSERNAME_ID] || m_aUsersData[nInd][SHARED_USERURL_ID] != aEntry[SHARED_USERURL_ID] ) { aNewData[nNewInd] = m_aUsersData[nInd]; nNewInd++; } } } aNewData.realloc( nNewInd ); SetUsersDataAndStore( aNewData ); if ( !nNewInd ) { RemoveFile(); } } void ShareControlFile::RemoveFile() { ::osl::MutexGuard aGuard( m_aMutex ); if ( !IsValid() ) throw io::NotConnectedException(); Close(); uno::Reference< lang::XMultiServiceFactory > xFactory = ::comphelper::getProcessServiceFactory(); uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess > xSimpleFileAccess( xFactory->createInstance( ::rtl::OUString::createFromAscii("com.sun.star.ucb.SimpleFileAccess") ), uno::UNO_QUERY_THROW ); xSimpleFileAccess->kill( m_aURL ); } }
#include "precompiled_svl.hxx" #include <stdio.h> #include <com/sun/star/ucb/XSimpleFileAccess.hpp> #include <com/sun/star/ucb/XCommandEnvironment.hpp> #include <com/sun/star/ucb/XContent.hpp> #include <com/sun/star/ucb/InsertCommandArgument.hpp> #include <com/sun/star/ucb/InteractiveIOException.hpp> #include <com/sun/star/io/WrongFormatException.hpp> #include <osl/time.h> #include <osl/security.hxx> #include <osl/socket.hxx> #include <rtl/string.hxx> #include <rtl/ustring.hxx> #include <rtl/strbuf.hxx> #include <rtl/ustrbuf.hxx> #include <comphelper/processfactory.hxx> #include <ucbhelper/content.hxx> #include <tools/urlobj.hxx> #include <tools/stream.hxx> #include <unotools/bootstrap.hxx> #include <unotools/streamwrap.hxx> #include <unotools/useroptions.hxx> #include <svl/sharecontrolfile.hxx> using namespace ::com::sun::star; namespace svt { ShareControlFile::ShareControlFile( const ::rtl::OUString& aOrigURL, const uno::Reference< lang::XMultiServiceFactory >& xFactory ) : LockFileCommon( aOrigURL, xFactory, ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".~sharing." ) ) ) { OpenStream(); if ( !IsValid() ) throw io::NotConnectedException(); } ShareControlFile::~ShareControlFile() { try { Close(); } catch( uno::Exception& ) {} } void ShareControlFile::OpenStream() { if ( !m_xStream.is() && m_aURL.getLength() ) { uno::Reference< ucb::XCommandEnvironment > xDummyEnv; ::ucbhelper::Content aContent = ::ucbhelper::Content( m_aURL, xDummyEnv ); uno::Reference< ucb::XContentIdentifier > xContId( aContent.get().is() ? aContent.get()->getIdentifier() : 0 ); if ( !xContId.is() || !xContId->getContentProviderScheme().equals( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "file" ) ) ) ) throw io::IOException(); uno::Reference< io::XStream > xStream; try { xStream = aContent.openWriteableStreamNoLock(); } catch ( ucb::InteractiveIOException const & e ) { if ( e.Code == ucb::IOErrorCode_NOT_EXISTING ) { SvMemoryStream aStream(0,0); uno::Reference< io::XInputStream > xInput( new ::utl::OInputStreamWrapper( aStream ) ); ucb::InsertCommandArgument aInsertArg; aInsertArg.Data = xInput; aInsertArg.ReplaceExisting = sal_False; aContent.executeCommand( rtl::OUString::createFromAscii( "insert" ), uno::makeAny( aInsertArg ) ); try { aContent.setPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "IsHidden" ) ), uno::makeAny( sal_True ) ); } catch( uno::Exception& ) {} xStream = aContent.openWriteableStreamNoLock(); } else throw; } m_xSeekable.set( xStream, uno::UNO_QUERY_THROW ); m_xInputStream.set( xStream->getInputStream(), uno::UNO_QUERY_THROW ); m_xOutputStream.set( xStream->getOutputStream(), uno::UNO_QUERY_THROW ); m_xTruncate.set( m_xOutputStream, uno::UNO_QUERY_THROW ); m_xStream = xStream; } } void ShareControlFile::Close() { if ( m_xStream.is() ) { try { if ( m_xInputStream.is() ) m_xInputStream->closeInput(); if ( m_xOutputStream.is() ) m_xOutputStream->closeOutput(); } catch( uno::Exception& ) {} m_xStream = uno::Reference< io::XStream >(); m_xInputStream = uno::Reference< io::XInputStream >(); m_xOutputStream = uno::Reference< io::XOutputStream >(); m_xSeekable = uno::Reference< io::XSeekable >(); m_xTruncate = uno::Reference< io::XTruncate >(); m_aUsersData.realloc( 0 ); } } uno::Sequence< uno::Sequence< ::rtl::OUString > > ShareControlFile::GetUsersData() { ::osl::MutexGuard aGuard( m_aMutex ); if ( !IsValid() ) throw io::NotConnectedException(); if ( !m_aUsersData.getLength() ) { sal_Int64 nLength = m_xSeekable->getLength(); if ( nLength > SAL_MAX_INT32 ) throw uno::RuntimeException(); uno::Sequence< sal_Int8 > aBuffer( (sal_Int32)nLength ); m_xSeekable->seek( 0 ); sal_Int32 nRead = m_xInputStream->readBytes( aBuffer, (sal_Int32)nLength ); nLength -= nRead; while ( nLength > 0 ) { uno::Sequence< sal_Int8 > aTmpBuf( (sal_Int32)nLength ); nRead = m_xInputStream->readBytes( aTmpBuf, (sal_Int32)nLength ); if ( nRead > nLength ) throw uno::RuntimeException(); for ( sal_Int32 nInd = 0; nInd < nRead; nInd++ ) aBuffer[aBuffer.getLength() - (sal_Int32)nLength + nInd] = aTmpBuf[nInd]; nLength -= nRead; } m_aUsersData = ParseList( aBuffer ); } return m_aUsersData; } void ShareControlFile::SetUsersDataAndStore( const uno::Sequence< uno::Sequence< ::rtl::OUString > >& aUsersData ) { ::osl::MutexGuard aGuard( m_aMutex ); if ( !IsValid() ) throw io::NotConnectedException(); if ( !m_xTruncate.is() || !m_xOutputStream.is() || !m_xSeekable.is() ) throw uno::RuntimeException(); m_xTruncate->truncate(); m_xSeekable->seek( 0 ); ::rtl::OUStringBuffer aBuffer; for ( sal_Int32 nInd = 0; nInd < aUsersData.getLength(); nInd++ ) { if ( aUsersData[nInd].getLength() != SHARED_ENTRYSIZE ) throw lang::IllegalArgumentException(); for ( sal_Int32 nEntryInd = 0; nEntryInd < SHARED_ENTRYSIZE; nEntryInd++ ) { aBuffer.append( EscapeCharacters( aUsersData[nInd][nEntryInd] ) ); if ( nEntryInd < SHARED_ENTRYSIZE - 1 ) aBuffer.append( (sal_Unicode)',' ); else aBuffer.append( (sal_Unicode)';' ); } } ::rtl::OString aStringData( ::rtl::OUStringToOString( aBuffer.makeStringAndClear(), RTL_TEXTENCODING_UTF8 ) ); uno::Sequence< sal_Int8 > aData( (sal_Int8*)aStringData.getStr(), aStringData.getLength() ); m_xOutputStream->writeBytes( aData ); m_aUsersData = aUsersData; } uno::Sequence< ::rtl::OUString > ShareControlFile::InsertOwnEntry() { ::osl::MutexGuard aGuard( m_aMutex ); if ( !IsValid() ) throw io::NotConnectedException(); GetUsersData(); uno::Sequence< ::uno::Sequence< ::rtl::OUString > > aNewData( m_aUsersData.getLength() + 1 ); uno::Sequence< ::rtl::OUString > aNewEntry = GenerateOwnEntry(); sal_Bool bExists = sal_False; sal_Int32 nNewInd = 0; for ( sal_Int32 nInd = 0; nInd < m_aUsersData.getLength(); nInd++ ) { if ( m_aUsersData[nInd].getLength() == SHARED_ENTRYSIZE ) { if ( m_aUsersData[nInd][SHARED_LOCALHOST_ID] == aNewEntry[SHARED_LOCALHOST_ID] && m_aUsersData[nInd][SHARED_SYSUSERNAME_ID] == aNewEntry[SHARED_SYSUSERNAME_ID] && m_aUsersData[nInd][SHARED_USERURL_ID] == aNewEntry[SHARED_USERURL_ID] ) {
} else { aNewData[nNewInd] = m_aUsersData[nInd]; } nNewInd++; } } if ( !bExists ) aNewData[nNewInd++] = aNewEntry; aNewData.realloc( nNewInd ); SetUsersDataAndStore( aNewData ); return aNewEntry; } bool ShareControlFile::HasOwnEntry() { ::osl::MutexGuard aGuard( m_aMutex ); if ( !IsValid() ) { throw io::NotConnectedException(); } GetUsersData(); uno::Sequence< ::rtl::OUString > aEntry = GenerateOwnEntry(); for ( sal_Int32 nInd = 0; nInd < m_aUsersData.getLength(); ++nInd ) { if ( m_aUsersData[nInd].getLength() == SHARED_ENTRYSIZE && m_aUsersData[nInd][SHARED_LOCALHOST_ID] == aEntry[SHARED_LOCALHOST_ID] && m_aUsersData[nInd][SHARED_SYSUSERNAME_ID] == aEntry[SHARED_SYSUSERNAME_ID] && m_aUsersData[nInd][SHARED_USERURL_ID] == aEntry[SHARED_USERURL_ID] ) { return true; } } return false; } void ShareControlFile::RemoveEntry( const uno::Sequence< ::rtl::OUString >& aArgEntry ) { ::osl::MutexGuard aGuard( m_aMutex ); if ( !IsValid() ) throw io::NotConnectedException(); GetUsersData(); uno::Sequence< ::rtl::OUString > aEntry = aArgEntry; if ( aEntry.getLength() != SHARED_ENTRYSIZE ) aEntry = GenerateOwnEntry(); uno::Sequence< ::uno::Sequence< ::rtl::OUString > > aNewData( m_aUsersData.getLength() + 1 ); sal_Int32 nNewInd = 0; for ( sal_Int32 nInd = 0; nInd < m_aUsersData.getLength(); nInd++ ) { if ( m_aUsersData[nInd].getLength() == SHARED_ENTRYSIZE ) { if ( m_aUsersData[nInd][SHARED_LOCALHOST_ID] != aEntry[SHARED_LOCALHOST_ID] || m_aUsersData[nInd][SHARED_SYSUSERNAME_ID] != aEntry[SHARED_SYSUSERNAME_ID] || m_aUsersData[nInd][SHARED_USERURL_ID] != aEntry[SHARED_USERURL_ID] ) { aNewData[nNewInd] = m_aUsersData[nInd]; nNewInd++; } } } aNewData.realloc( nNewInd ); SetUsersDataAndStore( aNewData ); if ( !nNewInd ) { RemoveFile(); } } void ShareControlFile::RemoveFile() { ::osl::MutexGuard aGuard( m_aMutex ); if ( !IsValid() ) throw io::NotConnectedException(); Close(); uno::Reference< lang::XMultiServiceFactory > xFactory = ::comphelper::getProcessServiceFactory(); uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess > xSimpleFileAccess( xFactory->createInstance( ::rtl::OUString::createFromAscii("com.sun.star.ucb.SimpleFileAccess") ), uno::UNO_QUERY_THROW ); xSimpleFileAccess->kill( m_aURL ); } }
if ( !bExists ) { aNewData[nNewInd] = aNewEntry; bExists = sal_True; }
if_condition
[]
C++
tools/mesh_import/src/core/binary_exporter.cpp
ValtoForks/Terminus-Engine
0c7381af84736ec7b029977843590453cde64b1d
#include <binary_exporter.h> #include <assimp_importer.h> #include <filesystem.h> #include <timer.h> #include <iostream> namespace binary_exporter { void export_mesh(AssimpImportData* data, std::string output, Options options) { std::string meshOutputName = filesystem::get_filename(data->filename); auto mats = new TSM_Material_Json[data->header.material_count]; for (int i = 0; i < data->header.material_count; i++) { Json doc; String map = std::string(data->materials[i].albedo); if (map != "") { String name = filesystem::get_file_name_and_extention(map); String path_in_mat = "texture/"; path_in_mat += name; doc["diffuse_map"] = path_in_mat; String sourcePath = data->mesh_path; sourcePath += map; std::string dest_path = output; dest_path += "/"; dest_path += path_in_mat; filesystem::copy_file(sourcePath, dest_path); } else { Json diffuse_color; diffuse_color["r"] = 0.0f; diffuse_color["g"] = 0.0f; diffuse_color["b"] = 0.0f; diffuse_color["a"] = 1.0f; doc["diffuse_value"] = diffuse_color; } map = std::string(data->materials[i].normal); if (map != "") { String name = filesystem::get_file_name_and_extention(map); String path_in_mat = "texture/"; path_in_mat += name; doc["normal_map"] = path_in_mat; String sourcePath = data->mesh_path; sourcePath += map; std::string dest_path = output; dest_path += "/"; dest_path += path_in_mat; filesystem::copy_file(sourcePath, dest_path); } map = std::string(data->materials[i].metalness); if (data->materials[i].has_metalness) { String name = filesystem::get_file_name_and_extention(map); String path_in_mat = "texture/"; path_in_mat += name; doc["metalness_map"] = path_in_mat; String sourcePath = data->mesh_path; sourcePath += map; std::string dest_path = output; dest_path += "/"; dest_path += path_in_mat; filesystem::copy_file(sourcePath, dest_path); } else { doc["metalness_value"] = 0.5f; } map = std::string(data->materials[i].roughness); if (data->materials[i].has_roughness) { String name = filesystem::get_file_name_and_extention(map); String path_in_mat = "texture/"; path_in_mat += name; doc["roughness_map"] = path_in_mat; String sourcePath = data->mesh_path; sourcePath += map; std::string dest_path = output; dest_path += "/"; dest_path += path_in_mat; filesystem::copy_file(sourcePath, dest_path); } else { doc["roughness_value"] = 0.5f; } doc["backface_cull"] = true; std::string matPath = output; matPath += "/material/mat_"; matPath += data->materials[i].mesh_name; matPath += ".json"; String output_str = doc.dump(4); if (filesystem::write_begin(matPath)) { filesystem::write((void*)output_str.c_str(), output_str.size(), 1, 0); filesystem::write_end(); } String formattedString = "material/mat_"; formattedString += data->materials[i].mesh_name; formattedString += ".json\0"; strncpy(mats[i].material, formattedString.c_str(),50); } for (int i = 0; i < data->header.mesh_count; i++) { uint32_t idx = data->meshes[i].material_index; if (options.verbose) std::cout << "Mat Idx : " << std::to_string(idx) << std::endl; } std::string meshPath = output; meshPath += "/mesh/"; meshPath += meshOutputName; meshPath += "."; meshPath += ASSET_EXTENSION; if (filesystem::write_begin(meshPath)) { long Offset = 0; filesystem::write(&data->header, sizeof(TSM_FileHeader), 1, Offset); Offset += sizeof(TSM_FileHeader); filesystem::write(data->vertices, sizeof(TSM_Vertex), data->header.vertex_count, Offset); Offset += sizeof(TSM_Vertex) * data->header.vertex_count; filesystem::write(data->indices, sizeof(uint32_t), data->header.index_count, Offset); Offset += sizeof(uint32_t) * data->header.index_count; filesystem::write(data->meshes, sizeof(TSM_MeshHeader), data->header.mesh_count, Offset); Offset += sizeof(TSM_MeshHeader) * data->header.mesh_count; filesystem::write(mats, sizeof(TSM_Material_Json), data->header.material_count, Offset); filesystem::write_end(); } T_SAFE_DELETE_ARRAY(mats); T_SAFE_DELETE_ARRAY(data->vertices); T_SAFE_DELETE_ARRAY(data->indices); T_SAFE_DELETE_ARRAY(data->materials); T_SAFE_DELETE_ARRAY(data->meshes); T_SAFE_DELETE(data); } void export_mesh(std::string file, std::string output, Options options) { Timer timer; timer.start(); filesystem::create_directory(output); filesystem::create_directory(output + "/mesh"); filesystem::create_directory(output + "/material"); filesystem::create_directory(output + "/texture"); AssimpImportData* data = assimp_importer::import_mesh(file, options); export_mesh(data, output, options); timer.stop(); std::cout << "Finished exporting mesh in " << timer.elapsed_time_sec() << " second(s)." << std::endl; } }
#include <binary_exporter.h> #include <assimp_importer.h> #include <filesystem.h> #include <timer.h> #include <iostream> namespace binary_exporter { void export_mesh(AssimpImportData* data, std::string output, Options options) { std::string meshOutputName = filesystem::get_filename(data->filename); auto mats = new TSM_Material_Json[data->header.material_count]; for (int i = 0; i < data->header.material_count; i++) { Json doc; String map = std::string(data->materials[i].albedo); if (map != "") { String name = filesystem::get_file_name_and_extention(map); String path_in_mat = "texture/"; path_in_mat += name; doc["diffuse_map"] = path_in_mat; String sourcePath = data->mesh_path; sourcePath += map; std::string dest_path = output; dest_path += "/"; dest_path += path_in_mat; filesystem::copy_file(sourcePath, dest_path); } else { Json diffuse_color; diffuse_color["r"] = 0.0f; diffuse_color["g"] = 0.0f; diffuse_color["b"] = 0.0f; diffuse_color["a"] = 1.0f; doc["diffuse_value"] = diffuse_color; } map = std::string(data->materials[i].normal); if (map != "") { String name = filesystem::get_file_name_and_extention(map); String path_in_mat = "texture/"; path_in_mat += name; doc["normal_map"] = path_in_mat; String sourcePath = data->mesh_path; sourcePath += map; std::string dest_path = output; dest_path += "/"; dest_path += path_in_mat; filesystem::copy_file(sourcePath, dest_path); } map = std::string(data->materials[i].metalness); if (data->materials[i].has_metalness) { String name = filesystem::get_file_name_and_extention(map); String path_in_mat = "texture/"; path_in_mat += name; doc["metalness_map"] = path_in_mat; String sourcePath = data->mesh_path; sourcePath += map; std::string dest_path = output; dest_path += "/"; dest_path += path_in_mat; filesystem::copy_file(sourcePath, dest_path); } else { doc["metalness_value"] = 0.5f; } map = std::string(data->materials[i].roughness); if (data->materials[i].has_roughness) { String name = filesystem::get_file_name_and_extention(map); String path_in_mat = "texture/"; path_in_mat += name; doc["roughness_map"] = path_in_mat; String sourcePath = data->mesh_path; sourcePath += map;
string file, std::string output, Options options) { Timer timer; timer.start(); filesystem::create_directory(output); filesystem::create_directory(output + "/mesh"); filesystem::create_directory(output + "/material"); filesystem::create_directory(output + "/texture"); AssimpImportData* data = assimp_importer::import_mesh(file, options); export_mesh(data, output, options); timer.stop(); std::cout << "Finished exporting mesh in " << timer.elapsed_time_sec() << " second(s)." << std::endl; } }
std::string dest_path = output; dest_path += "/"; dest_path += path_in_mat; filesystem::copy_file(sourcePath, dest_path); } else { doc["roughness_value"] = 0.5f; } doc["backface_cull"] = true; std::string matPath = output; matPath += "/material/mat_"; matPath += data->materials[i].mesh_name; matPath += ".json"; String output_str = doc.dump(4); if (filesystem::write_begin(matPath)) { filesystem::write((void*)output_str.c_str(), output_str.size(), 1, 0); filesystem::write_end(); } String formattedString = "material/mat_"; formattedString += data->materials[i].mesh_name; formattedString += ".json\0"; strncpy(mats[i].material, formattedString.c_str(),50); } for (int i = 0; i < data->header.mesh_count; i++) { uint32_t idx = data->meshes[i].material_index; if (options.verbose) std::cout << "Mat Idx : " << std::to_string(idx) << std::endl; } std::string meshPath = output; meshPath += "/mesh/"; meshPath += meshOutputName; meshPath += "."; meshPath += ASSET_EXTENSION; if (filesystem::write_begin(meshPath)) { long Offset = 0; filesystem::write(&data->header, sizeof(TSM_FileHeader), 1, Offset); Offset += sizeof(TSM_FileHeader); filesystem::write(data->vertices, sizeof(TSM_Vertex), data->header.vertex_count, Offset); Offset += sizeof(TSM_Vertex) * data->header.vertex_count; filesystem::write(data->indices, sizeof(uint32_t), data->header.index_count, Offset); Offset += sizeof(uint32_t) * data->header.index_count; filesystem::write(data->meshes, sizeof(TSM_MeshHeader), data->header.mesh_count, Offset); Offset += sizeof(TSM_MeshHeader) * data->header.mesh_count; filesystem::write(mats, sizeof(TSM_Material_Json), data->header.material_count, Offset); filesystem::write_end(); } T_SAFE_DELETE_ARRAY(mats); T_SAFE_DELETE_ARRAY(data->vertices); T_SAFE_DELETE_ARRAY(data->indices); T_SAFE_DELETE_ARRAY(data->materials); T_SAFE_DELETE_ARRAY(data->meshes); T_SAFE_DELETE(data); } void export_mesh(std::
random
[ { "content": "using String = std::string;\n", "file_path": "tools/mesh_import/include/types.h", "rank": 0, "score": 120601.69996484136 }, { "content": "using Json = nlohmann::json;\n", "file_path": "tools/mesh_import/include/types.h", "rank": 1, "score": 120591.52757084777 }, ...
C++
src/EventTraceKit.Etw/EventSession.cpp
ljani/event-trace-kit
59a217fbaecfc87b3915e2494a8d25593d04ae99
#include "Descriptors.h" #include "TraceLog.h" #include "WatchDog.h" #include "InteropHelper.h" #include "etk/ITraceLog.h" #include "etk/ITraceProcessor.h" #include "etk/ITraceSession.h" #include <memory> #include <string> using namespace System; using namespace System::Collections::Generic; using namespace System::ComponentModel; using namespace System::Linq; using namespace System::Runtime::InteropServices; using namespace System::Threading::Tasks; using namespace EventTraceKit::Tracing; using msclr::interop::marshal_as; namespace msclr { namespace interop { static bool IsProviderBinary(String^ filePath) { return filePath->EndsWith(L".exe", StringComparison::OrdinalIgnoreCase) || filePath->EndsWith(L".dll", StringComparison::OrdinalIgnoreCase); } template<> inline etk::TraceProviderDescriptor marshal_as(EventProviderDescriptor^ const& provider) { etk::TraceProviderDescriptor native( marshal_as<GUID>(provider->Id), provider->Level, provider->MatchAnyKeyword, provider->MatchAllKeyword); native.IncludeSecurityId = provider->IncludeSecurityId; native.IncludeTerminalSessionId = provider->IncludeTerminalSessionId; native.IncludeStackTrace = provider->IncludeStackTrace; if (provider->ExecutableName) native.ExecutableName = marshal_as<std::wstring>(provider->ExecutableName); if (provider->ProcessIds) native.ProcessIds = marshal_as_vector(provider->ProcessIds); native.EventIdsFilterIn = provider->EventIdsFilterIn; if (provider->EventIds) native.EventIds = marshal_as_vector(provider->EventIds); native.StackWalkEventIdsFilterIn = provider->StackWalkEventIdsFilterIn; if (provider->StackWalkEventIds) native.StackWalkEventIds = marshal_as_vector(provider->StackWalkEventIds); native.FilterStackWalkLevelKeyword = provider->FilterStackWalkLevelKeyword; native.StackWalkFilterIn = provider->StackWalkFilterIn; native.StackWalkLevel = provider->StackWalkLevel; native.StackWalkMatchAnyKeyword = provider->StackWalkMatchAnyKeyword; native.StackWalkMatchAllKeyword = provider->StackWalkMatchAllKeyword; if (provider->Manifest) { auto manifest = marshal_as<std::wstring>(provider->Manifest); if (IsProviderBinary(provider->Manifest)) native.SetProviderBinary(manifest); else native.SetManifest(manifest); } return native; } } } namespace EventTraceKit::Tracing { public ref struct TraceStatistics { property unsigned NumberOfBuffers; property unsigned FreeBuffers; property unsigned EventsLost; property unsigned BuffersWritten; property unsigned LogBuffersLost; property unsigned RealTimeBuffersLost; property unsigned LoggerThreadId; }; public ref class EventSession : public System::IDisposable { public: EventSession(TraceProfileDescriptor^ profile, TraceLog^ traceLog); ~EventSession() { this->!EventSession(); } !EventSession(); void Start(); Task^ StartAsync(); void Stop(); void Flush(); TraceStatistics^ Query(); private: ref struct StartAsyncHelper { StartAsyncHelper(EventSession^ parent) : parent(parent) {} void Run() { parent->Start(); } EventSession^ parent; }; TraceProfileDescriptor^ profile; TraceLog^ traceLog; std::wstring* loggerName = nullptr; WatchDog^ watchDog; etk::ITraceSession* session = nullptr; etk::ITraceSession* kernelSession = nullptr; etk::ITraceProcessor* processor = nullptr; }; static std::wstring LoggerNameBase = L"EventTraceKit_54644792-9281-48E9-B69D-E82A86F98960"; static std::wstring CreateLoggerName() { int pid = System::Diagnostics::Process::GetCurrentProcess()->Id; return LoggerNameBase + L"_" + std::to_wstring(pid); } static etk::TraceProperties CreateTraceProperties(CollectorDescriptor^ profile) { etk::TraceProperties properties(marshal_as<GUID>(System::Guid::NewGuid())); if (profile->BufferSize.HasValue) properties.BufferSize = profile->BufferSize.Value; if (profile->MinimumBuffers.HasValue) properties.MinimumBuffers = profile->MinimumBuffers.Value; if (profile->MaximumBuffers.HasValue) properties.MaximumBuffers = profile->MaximumBuffers.Value; if (profile->LogFileName) properties.LogFileName = marshal_as<std::wstring>(profile->LogFileName); if (profile->FlushPeriod.HasValue) { properties.FlushPeriod = std::chrono::duration<unsigned, std::milli>( static_cast<unsigned>(profile->FlushPeriod.Value.TotalMilliseconds)); } return properties; } EventSession::EventSession(TraceProfileDescriptor^ profile, TraceLog^ traceLog) : profile(profile) , traceLog(traceLog) , loggerName(new std::wstring(CreateLoggerName())) { if (profile->Collectors->Count == 0) throw gcnew System::ArgumentException(L"profile"); if (!traceLog) throw gcnew System::ArgumentNullException(L"traceLog"); watchDog = gcnew WatchDog(marshal_as<String^>(*loggerName)); traceLog->UpdateTraceData(profile); for each (auto collector in profile->Collectors) { if (auto systemCollector = dynamic_cast<SystemCollectorDescriptor^>(collector)) { auto traceProperties = CreateTraceProperties(systemCollector); auto session = etk::CreateEtwTraceSession(L"NT Kernel Logger", traceProperties); session->SetKernelProviders(systemCollector->KernelFlags, true); this->kernelSession = session.release(); continue; } if (auto eventCollector = dynamic_cast<EventCollectorDescriptor^>(collector)) { auto traceProperties = CreateTraceProperties(eventCollector); auto session = etk::CreateEtwTraceSession(*loggerName, traceProperties); for each (auto provider in eventCollector->Providers) { auto nativeProvider = marshal_as<etk::TraceProviderDescriptor>(provider); session->AddProvider(nativeProvider); session->EnableProvider(nativeProvider.Id); } this->session = session.release(); continue; } } } EventSession::!EventSession() { Stop(); delete session; delete kernelSession; delete watchDog; delete loggerName; } void EventSession::Start() { watchDog->Start(); HRESULT hr; if (kernelSession) { hr = kernelSession->Start(); if (FAILED(hr)) throw gcnew Win32Exception(hr); } if (session) { hr = session->Start(); if (FAILED(hr)) { if (kernelSession) (void)kernelSession->Stop(); throw gcnew Win32Exception(hr); } } std::vector<std::wstring_view> loggerNames; if (session) loggerNames.push_back(*loggerName); if (kernelSession) loggerNames.push_back(L"NT Kernel Logger"); auto processor = etk::CreateEtwTraceProcessor(loggerNames); processor->SetEventSink(traceLog->Native()); this->processor = processor.release(); this->processor->StartProcessing(); auto logFileHeader = this->processor->GetLogFileHeader(); EventSessionInfo sessionInfo; sessionInfo.StartTime = logFileHeader->StartTime.QuadPart; sessionInfo.PerfFreq = logFileHeader->PerfFreq.QuadPart; sessionInfo.PointerSize = logFileHeader->PointerSize; traceLog->SetSessionInfo(sessionInfo); } Task^ EventSession::StartAsync() { return Task::Run(gcnew Action(this, &EventSession::Start)); } void EventSession::Stop() { if (!processor) return; processor->StopProcessing(); if (session) session->Stop(); if (kernelSession) kernelSession->Stop(); watchDog->Stop(); delete processor; processor = nullptr; } void EventSession::Flush() { if (!processor) return; if (session) session->Flush(); if (kernelSession) kernelSession->Flush(); } TraceStatistics^ EventSession::Query() { if (!session) return gcnew TraceStatistics(); etk::TraceStatistics nativeStats; session->Query(nativeStats); auto stats = gcnew TraceStatistics(); stats->NumberOfBuffers = nativeStats.NumberOfBuffers; stats->FreeBuffers = nativeStats.FreeBuffers; stats->EventsLost = nativeStats.EventsLost; stats->BuffersWritten = nativeStats.BuffersWritten; stats->LogBuffersLost = nativeStats.LogBuffersLost; stats->RealTimeBuffersLost = nativeStats.RealTimeBuffersLost; stats->LoggerThreadId = nativeStats.LoggerThreadId; return stats; } }
#include "Descriptors.h" #include "TraceLog.h" #include "WatchDog.h" #include "InteropHelper.h" #include "etk/ITraceLog.h" #include "etk/ITraceProcessor.h" #include "etk/ITraceSession.h" #include <memory> #include <string> using namespace System; using namespace System::Collections::Generic; using namespace System::ComponentModel; using namespace System::Linq; using namespace System::Runtime::InteropServices; using namespace System::Threading::Tasks; using namespace EventTraceKit::Tracing; using msclr::interop::marshal_as; namespace msclr { namespace interop { static bool IsPro
on* kernelSession = nullptr; etk::ITraceProcessor* processor = nullptr; }; static std::wstring LoggerNameBase = L"EventTraceKit_54644792-9281-48E9-B69D-E82A86F98960"; static std::wstring CreateLoggerName() { int pid = System::Diagnostics::Process::GetCurrentProcess()->Id; return LoggerNameBase + L"_" + std::to_wstring(pid); } static etk::TraceProperties CreateTraceProperties(CollectorDescriptor^ profile) { etk::TraceProperties properties(marshal_as<GUID>(System::Guid::NewGuid())); if (profile->BufferSize.HasValue) properties.BufferSize = profile->BufferSize.Value; if (profile->MinimumBuffers.HasValue) properties.MinimumBuffers = profile->MinimumBuffers.Value; if (profile->MaximumBuffers.HasValue) properties.MaximumBuffers = profile->MaximumBuffers.Value; if (profile->LogFileName) properties.LogFileName = marshal_as<std::wstring>(profile->LogFileName); if (profile->FlushPeriod.HasValue) { properties.FlushPeriod = std::chrono::duration<unsigned, std::milli>( static_cast<unsigned>(profile->FlushPeriod.Value.TotalMilliseconds)); } return properties; } EventSession::EventSession(TraceProfileDescriptor^ profile, TraceLog^ traceLog) : profile(profile) , traceLog(traceLog) , loggerName(new std::wstring(CreateLoggerName())) { if (profile->Collectors->Count == 0) throw gcnew System::ArgumentException(L"profile"); if (!traceLog) throw gcnew System::ArgumentNullException(L"traceLog"); watchDog = gcnew WatchDog(marshal_as<String^>(*loggerName)); traceLog->UpdateTraceData(profile); for each (auto collector in profile->Collectors) { if (auto systemCollector = dynamic_cast<SystemCollectorDescriptor^>(collector)) { auto traceProperties = CreateTraceProperties(systemCollector); auto session = etk::CreateEtwTraceSession(L"NT Kernel Logger", traceProperties); session->SetKernelProviders(systemCollector->KernelFlags, true); this->kernelSession = session.release(); continue; } if (auto eventCollector = dynamic_cast<EventCollectorDescriptor^>(collector)) { auto traceProperties = CreateTraceProperties(eventCollector); auto session = etk::CreateEtwTraceSession(*loggerName, traceProperties); for each (auto provider in eventCollector->Providers) { auto nativeProvider = marshal_as<etk::TraceProviderDescriptor>(provider); session->AddProvider(nativeProvider); session->EnableProvider(nativeProvider.Id); } this->session = session.release(); continue; } } } EventSession::!EventSession() { Stop(); delete session; delete kernelSession; delete watchDog; delete loggerName; } void EventSession::Start() { watchDog->Start(); HRESULT hr; if (kernelSession) { hr = kernelSession->Start(); if (FAILED(hr)) throw gcnew Win32Exception(hr); } if (session) { hr = session->Start(); if (FAILED(hr)) { if (kernelSession) (void)kernelSession->Stop(); throw gcnew Win32Exception(hr); } } std::vector<std::wstring_view> loggerNames; if (session) loggerNames.push_back(*loggerName); if (kernelSession) loggerNames.push_back(L"NT Kernel Logger"); auto processor = etk::CreateEtwTraceProcessor(loggerNames); processor->SetEventSink(traceLog->Native()); this->processor = processor.release(); this->processor->StartProcessing(); auto logFileHeader = this->processor->GetLogFileHeader(); EventSessionInfo sessionInfo; sessionInfo.StartTime = logFileHeader->StartTime.QuadPart; sessionInfo.PerfFreq = logFileHeader->PerfFreq.QuadPart; sessionInfo.PointerSize = logFileHeader->PointerSize; traceLog->SetSessionInfo(sessionInfo); } Task^ EventSession::StartAsync() { return Task::Run(gcnew Action(this, &EventSession::Start)); } void EventSession::Stop() { if (!processor) return; processor->StopProcessing(); if (session) session->Stop(); if (kernelSession) kernelSession->Stop(); watchDog->Stop(); delete processor; processor = nullptr; } void EventSession::Flush() { if (!processor) return; if (session) session->Flush(); if (kernelSession) kernelSession->Flush(); } TraceStatistics^ EventSession::Query() { if (!session) return gcnew TraceStatistics(); etk::TraceStatistics nativeStats; session->Query(nativeStats); auto stats = gcnew TraceStatistics(); stats->NumberOfBuffers = nativeStats.NumberOfBuffers; stats->FreeBuffers = nativeStats.FreeBuffers; stats->EventsLost = nativeStats.EventsLost; stats->BuffersWritten = nativeStats.BuffersWritten; stats->LogBuffersLost = nativeStats.LogBuffersLost; stats->RealTimeBuffersLost = nativeStats.RealTimeBuffersLost; stats->LoggerThreadId = nativeStats.LoggerThreadId; return stats; } }
viderBinary(String^ filePath) { return filePath->EndsWith(L".exe", StringComparison::OrdinalIgnoreCase) || filePath->EndsWith(L".dll", StringComparison::OrdinalIgnoreCase); } template<> inline etk::TraceProviderDescriptor marshal_as(EventProviderDescriptor^ const& provider) { etk::TraceProviderDescriptor native( marshal_as<GUID>(provider->Id), provider->Level, provider->MatchAnyKeyword, provider->MatchAllKeyword); native.IncludeSecurityId = provider->IncludeSecurityId; native.IncludeTerminalSessionId = provider->IncludeTerminalSessionId; native.IncludeStackTrace = provider->IncludeStackTrace; if (provider->ExecutableName) native.ExecutableName = marshal_as<std::wstring>(provider->ExecutableName); if (provider->ProcessIds) native.ProcessIds = marshal_as_vector(provider->ProcessIds); native.EventIdsFilterIn = provider->EventIdsFilterIn; if (provider->EventIds) native.EventIds = marshal_as_vector(provider->EventIds); native.StackWalkEventIdsFilterIn = provider->StackWalkEventIdsFilterIn; if (provider->StackWalkEventIds) native.StackWalkEventIds = marshal_as_vector(provider->StackWalkEventIds); native.FilterStackWalkLevelKeyword = provider->FilterStackWalkLevelKeyword; native.StackWalkFilterIn = provider->StackWalkFilterIn; native.StackWalkLevel = provider->StackWalkLevel; native.StackWalkMatchAnyKeyword = provider->StackWalkMatchAnyKeyword; native.StackWalkMatchAllKeyword = provider->StackWalkMatchAllKeyword; if (provider->Manifest) { auto manifest = marshal_as<std::wstring>(provider->Manifest); if (IsProviderBinary(provider->Manifest)) native.SetProviderBinary(manifest); else native.SetManifest(manifest); } return native; } } } namespace EventTraceKit::Tracing { public ref struct TraceStatistics { property unsigned NumberOfBuffers; property unsigned FreeBuffers; property unsigned EventsLost; property unsigned BuffersWritten; property unsigned LogBuffersLost; property unsigned RealTimeBuffersLost; property unsigned LoggerThreadId; }; public ref class EventSession : public System::IDisposable { public: EventSession(TraceProfileDescriptor^ profile, TraceLog^ traceLog); ~EventSession() { this->!EventSession(); } !EventSession(); void Start(); Task^ StartAsync(); void Stop(); void Flush(); TraceStatistics^ Query(); private: ref struct StartAsyncHelper { StartAsyncHelper(EventSession^ parent) : parent(parent) {} void Run() { parent->Start(); } EventSession^ parent; }; TraceProfileDescriptor^ profile; TraceLog^ traceLog; std::wstring* loggerName = nullptr; WatchDog^ watchDog; etk::ITraceSession* session = nullptr; etk::ITraceSessi
random
[ { "content": "namespace EventTraceKit.EventTracing.Schema\n\n{\n\n using System.Xml.Linq;\n\n using EventTraceKit.EventTracing.Schema.Base;\n\n\n\n public static class EventManifestSchema\n\n {\n\n public static readonly XNamespace Namespace =\n\n \"http://schemas.microsoft.com/win...
C++
export/windows/cpp/obj/src/haxe/Timer.cpp
TinyPlanetStudios/Project-Crash-Land
365f196be4212602d32251566f26b53fb70693f6
#include <hxcpp.h> #ifndef INCLUDED_haxe_Log #include <haxe/Log.h> #endif #ifndef INCLUDED_haxe_Timer #include <haxe/Timer.h> #endif #ifndef INCLUDED_openfl__legacy_Lib #include <openfl/_legacy/Lib.h> #endif namespace haxe{ void Timer_obj::__construct(Float time){ HX_STACK_FRAME("haxe.Timer","new",0x4136b0cf,"haxe.Timer.new","haxe/Timer.hx",210,0x1a690682) HX_STACK_THIS(this) HX_STACK_ARG(time,"time") HXLINE( 212) this->mTime = time; HXLINE( 213) ::haxe::Timer_obj::sRunningTimers->push(hx::ObjectPtr<OBJ_>(this)); HXLINE( 214) Float _hx_tmp = ::haxe::Timer_obj::getMS(); HXDLIN( 214) this->mFireAt = (_hx_tmp + this->mTime); HXLINE( 215) this->mRunning = true; } Dynamic Timer_obj::__CreateEmpty() { return new Timer_obj; } hx::ObjectPtr< Timer_obj > Timer_obj::__new(Float time) { hx::ObjectPtr< Timer_obj > _hx_result = new Timer_obj(); _hx_result->__construct(time); return _hx_result; } Dynamic Timer_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< Timer_obj > _hx_result = new Timer_obj(); _hx_result->__construct(inArgs[0]); return _hx_result; } HX_BEGIN_DEFAULT_FUNC(__default_run,Timer_obj) void _hx_run(){ HX_STACK_FRAME("haxe.Timer","__default_run",0xdc2b9b9c,"haxe.Timer.__default_run","haxe/Timer.hx",257,0x1a690682) HX_STACK_THIS(this) } HX_END_LOCAL_FUNC0((void)) HX_END_DEFAULT_FUNC void Timer_obj::stop(){ HX_STACK_FRAME("haxe.Timer","stop",0xd1fd70b3,"haxe.Timer.stop","haxe/Timer.hx",277,0x1a690682) HX_STACK_THIS(this) HXLINE( 277) Bool _hx_tmp = this->mRunning; HXDLIN( 277) if (_hx_tmp) { HXLINE( 279) this->mRunning = false; HXLINE( 281) { HXLINE( 281) HX_VARI( Int,_g1) = (int)0; HXDLIN( 281) HX_VARI( Int,_g) = ::haxe::Timer_obj::sRunningTimers->length; HXDLIN( 281) while((_g1 < _g)){ HXLINE( 281) HX_VARI( Int,i) = _g1++; HXLINE( 283) Bool _hx_tmp1 = hx::IsEq( ::haxe::Timer_obj::sRunningTimers->__get(i).StaticCast< ::haxe::Timer >(),hx::ObjectPtr<OBJ_>(this) ); HXDLIN( 283) if (_hx_tmp1) { HXLINE( 285) ::haxe::Timer_obj::sRunningTimers[i] = null(); HXLINE( 286) goto _hx_goto_0; } } _hx_goto_0:; } } } HX_DEFINE_DYNAMIC_FUNC0(Timer_obj,stop,(void)) void Timer_obj::_hx___check(Float inTime){ HX_STACK_FRAME("haxe.Timer","__check",0xb5623597,"haxe.Timer.__check","haxe/Timer.hx",299,0x1a690682) HX_STACK_THIS(this) HX_STACK_ARG(inTime,"inTime") HXLINE( 299) Bool _hx_tmp = (inTime >= this->mFireAt); HXDLIN( 299) if (_hx_tmp) { HXLINE( 301) hx::AddEq(this->mFireAt,this->mTime); HXLINE( 302) this->run(); } } HX_DEFINE_DYNAMIC_FUNC1(Timer_obj,_hx___check,(void)) ::Array< ::Dynamic> Timer_obj::sRunningTimers; ::haxe::Timer Timer_obj::delay( ::Dynamic f,Int time){ HX_BEGIN_LOCAL_FUNC_S2(hx::LocalFunc,_hx_Closure_0, ::Dynamic,f, ::haxe::Timer,t) HXARGC(0) void _hx_run(){ HX_STACK_FRAME("haxe.Timer","delay",0x3ed5f1b2,"haxe.Timer.delay","haxe/Timer.hx",224,0x1a690682) HXLINE( 226) t->stop(); HXLINE( 227) f(); } HX_END_LOCAL_FUNC0((void)) HX_STACK_FRAME("haxe.Timer","delay",0x3ed5f1b2,"haxe.Timer.delay","haxe/Timer.hx",220,0x1a690682) HX_STACK_ARG(f,"f") HX_STACK_ARG(time,"time") HXLINE( 222) HX_VARI( ::haxe::Timer,t) = ::haxe::Timer_obj::__new(time); HXLINE( 224) t->run = ::Dynamic(new _hx_Closure_0(f,t)); HXLINE( 231) return t; } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Timer_obj,delay,return ) Float Timer_obj::getMS(){ HX_STACK_FRAME("haxe.Timer","getMS",0xf90fafab,"haxe.Timer.getMS","haxe/Timer.hx",239,0x1a690682) HXLINE( 239) Float _hx_tmp = ( (Float)(::haxe::Timer_obj::lime_time_stamp()) ); HXDLIN( 239) return (_hx_tmp * ((Float)1000.0)); } STATIC_HX_DEFINE_DYNAMIC_FUNC0(Timer_obj,getMS,return ) ::Dynamic Timer_obj::measure( ::Dynamic f, ::Dynamic pos){ HX_STACK_FRAME("haxe.Timer","measure",0x42373f4d,"haxe.Timer.measure","haxe/Timer.hx",247,0x1a690682) HX_STACK_ARG(f,"f") HX_STACK_ARG(pos,"pos") HXLINE( 249) HX_VARI( Float,t0) = ::haxe::Timer_obj::stamp(); HXLINE( 250) HX_VARI( ::Dynamic,r) = f(); HXLINE( 251) Float _hx_tmp = ::haxe::Timer_obj::stamp(); HXDLIN( 251) ::haxe::Log_obj::trace(((_hx_tmp - t0) + HX_("s",73,00,00,00)),pos); HXLINE( 252) return r; } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Timer_obj,measure,return ) Float Timer_obj::stamp(){ HX_STACK_FRAME("haxe.Timer","stamp",0xebba8a32,"haxe.Timer.stamp","haxe/Timer.hx",267,0x1a690682) HXLINE( 267) return ( (Float)(::haxe::Timer_obj::lime_time_stamp()) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC0(Timer_obj,stamp,return ) void Timer_obj::_hx___checkTimers(){ HX_STACK_FRAME("haxe.Timer","__checkTimers",0xb7078205,"haxe.Timer.__checkTimers","haxe/Timer.hx",309,0x1a690682) HXLINE( 311) HX_VARI( Float,now) = ::haxe::Timer_obj::getMS(); HXLINE( 312) HX_VARI( Bool,foundNull) = false; HXLINE( 313) HX_VAR( ::haxe::Timer,timer); HXLINE( 315) { HXLINE( 315) HX_VARI( Int,_g1) = (int)0; HXDLIN( 315) HX_VARI( Int,_g) = ::haxe::Timer_obj::sRunningTimers->length; HXDLIN( 315) while((_g1 < _g)){ HXLINE( 315) HX_VARI( Int,i) = _g1++; HXLINE( 317) timer = ::haxe::Timer_obj::sRunningTimers->__get(i).StaticCast< ::haxe::Timer >(); HXLINE( 319) Bool _hx_tmp = hx::IsNotNull( timer ); HXDLIN( 319) if (_hx_tmp) { HXLINE( 321) timer->_hx___check(now); } HXLINE( 325) Bool _hx_tmp1 = !(foundNull); HXDLIN( 325) if (_hx_tmp1) { HXLINE( 325) foundNull = hx::IsNull( ::haxe::Timer_obj::sRunningTimers->__get(i).StaticCast< ::haxe::Timer >() ); } else { HXLINE( 325) foundNull = true; } } } HXLINE( 329) if (foundNull) { HX_BEGIN_LOCAL_FUNC_S0(hx::LocalFunc,_hx_Closure_0) HXARGC(1) Bool _hx_run( ::haxe::Timer val){ HX_STACK_FRAME("haxe.Timer","__checkTimers",0xb7078205,"haxe.Timer.__checkTimers","haxe/Timer.hx",331,0x1a690682) HX_STACK_ARG(val,"val") HXLINE( 331) return hx::IsNotNull( val ); } HX_END_LOCAL_FUNC1(return) HXLINE( 331) ::haxe::Timer_obj::sRunningTimers = ::haxe::Timer_obj::sRunningTimers->filter( ::Dynamic(new _hx_Closure_0())); } } STATIC_HX_DEFINE_DYNAMIC_FUNC0(Timer_obj,_hx___checkTimers,(void)) Float Timer_obj::_hx___nextWake(Float limit){ HX_STACK_FRAME("haxe.Timer","__nextWake",0x0e101148,"haxe.Timer.__nextWake","haxe/Timer.hx",339,0x1a690682) HX_STACK_ARG(limit,"limit") HXLINE( 341) HX_VARI( Float,now) = ::haxe::Timer_obj::getMS(); HXLINE( 342) HX_VAR( Float,sleep); HXLINE( 344) { HXLINE( 344) HX_VARI( Int,_g) = (int)0; HXDLIN( 344) HX_VARI( ::Array< ::Dynamic>,_g1) = ::haxe::Timer_obj::sRunningTimers; HXDLIN( 344) while((_g < _g1->length)){ HXLINE( 344) HX_VARI( ::haxe::Timer,timer) = _g1->__get(_g).StaticCast< ::haxe::Timer >(); HXDLIN( 344) ++_g; HXLINE( 346) Bool _hx_tmp = hx::IsNull( timer ); HXDLIN( 346) if (_hx_tmp) { HXLINE( 347) continue; } HXLINE( 349) sleep = (timer->mFireAt - now); HXLINE( 351) Bool _hx_tmp1 = (sleep < limit); HXDLIN( 351) if (_hx_tmp1) { HXLINE( 353) limit = sleep; HXLINE( 355) if ((sleep < (int)0)) { HXLINE( 357) return (int)0; } } } } HXLINE( 365) return (limit * ((Float)0.001)); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Timer_obj,_hx___nextWake,return ) ::Dynamic Timer_obj::lime_time_stamp; Timer_obj::Timer_obj() { run = new __default_run(this); } void Timer_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(Timer); HX_MARK_MEMBER_NAME(mTime,"mTime"); HX_MARK_MEMBER_NAME(mFireAt,"mFireAt"); HX_MARK_MEMBER_NAME(mRunning,"mRunning"); HX_MARK_MEMBER_NAME(run,"run"); HX_MARK_END_CLASS(); } void Timer_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(mTime,"mTime"); HX_VISIT_MEMBER_NAME(mFireAt,"mFireAt"); HX_VISIT_MEMBER_NAME(mRunning,"mRunning"); HX_VISIT_MEMBER_NAME(run,"run"); } hx::Val Timer_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"run") ) { return hx::Val( run); } break; case 4: if (HX_FIELD_EQ(inName,"stop") ) { return hx::Val( stop_dyn()); } break; case 5: if (HX_FIELD_EQ(inName,"mTime") ) { return hx::Val( mTime); } break; case 7: if (HX_FIELD_EQ(inName,"mFireAt") ) { return hx::Val( mFireAt); } if (HX_FIELD_EQ(inName,"__check") ) { return hx::Val( _hx___check_dyn()); } break; case 8: if (HX_FIELD_EQ(inName,"mRunning") ) { return hx::Val( mRunning); } } return super::__Field(inName,inCallProp); } bool Timer_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"delay") ) { outValue = delay_dyn(); return true; } if (HX_FIELD_EQ(inName,"getMS") ) { outValue = getMS_dyn(); return true; } if (HX_FIELD_EQ(inName,"stamp") ) { outValue = stamp_dyn(); return true; } break; case 7: if (HX_FIELD_EQ(inName,"measure") ) { outValue = measure_dyn(); return true; } break; case 10: if (HX_FIELD_EQ(inName,"__nextWake") ) { outValue = _hx___nextWake_dyn(); return true; } break; case 13: if (HX_FIELD_EQ(inName,"__checkTimers") ) { outValue = _hx___checkTimers_dyn(); return true; } break; case 14: if (HX_FIELD_EQ(inName,"sRunningTimers") ) { outValue = sRunningTimers; return true; } break; case 15: if (HX_FIELD_EQ(inName,"lime_time_stamp") ) { outValue = lime_time_stamp; return true; } } return false; } hx::Val Timer_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"run") ) { run=inValue.Cast< ::Dynamic >(); return inValue; } break; case 5: if (HX_FIELD_EQ(inName,"mTime") ) { mTime=inValue.Cast< Float >(); return inValue; } break; case 7: if (HX_FIELD_EQ(inName,"mFireAt") ) { mFireAt=inValue.Cast< Float >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"mRunning") ) { mRunning=inValue.Cast< Bool >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } bool Timer_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 14: if (HX_FIELD_EQ(inName,"sRunningTimers") ) { sRunningTimers=ioValue.Cast< ::Array< ::Dynamic> >(); return true; } break; case 15: if (HX_FIELD_EQ(inName,"lime_time_stamp") ) { lime_time_stamp=ioValue.Cast< ::Dynamic >(); return true; } } return false; } void Timer_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_HCSTRING("mTime","\x1a","\x33","\x83","\xfa")); outFields->push(HX_HCSTRING("mFireAt","\x96","\xea","\x58","\x72")); outFields->push(HX_HCSTRING("mRunning","\x12","\x2d","\x35","\x13")); super::__GetFields(outFields); }; #if HXCPP_SCRIPTABLE static hx::StorageInfo Timer_obj_sMemberStorageInfo[] = { {hx::fsFloat,(int)offsetof(Timer_obj,mTime),HX_HCSTRING("mTime","\x1a","\x33","\x83","\xfa")}, {hx::fsFloat,(int)offsetof(Timer_obj,mFireAt),HX_HCSTRING("mFireAt","\x96","\xea","\x58","\x72")}, {hx::fsBool,(int)offsetof(Timer_obj,mRunning),HX_HCSTRING("mRunning","\x12","\x2d","\x35","\x13")}, {hx::fsObject ,(int)offsetof(Timer_obj,run),HX_HCSTRING("run","\x4b","\xe7","\x56","\x00")}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo Timer_obj_sStaticStorageInfo[] = { {hx::fsObject ,(void *) &Timer_obj::sRunningTimers,HX_HCSTRING("sRunningTimers","\xfa","\xbb","\xcd","\xfe")}, {hx::fsObject ,(void *) &Timer_obj::lime_time_stamp,HX_HCSTRING("lime_time_stamp","\x3b","\x9f","\x6b","\x12")}, { hx::fsUnknown, 0, null()} }; #endif static ::String Timer_obj_sMemberFields[] = { HX_HCSTRING("mTime","\x1a","\x33","\x83","\xfa"), HX_HCSTRING("mFireAt","\x96","\xea","\x58","\x72"), HX_HCSTRING("mRunning","\x12","\x2d","\x35","\x13"), HX_HCSTRING("run","\x4b","\xe7","\x56","\x00"), HX_HCSTRING("stop","\x02","\xf0","\x5b","\x4c"), HX_HCSTRING("__check","\xa8","\xf1","\x14","\xb0"), ::String(null()) }; static void Timer_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(Timer_obj::__mClass,"__mClass"); HX_MARK_MEMBER_NAME(Timer_obj::sRunningTimers,"sRunningTimers"); HX_MARK_MEMBER_NAME(Timer_obj::lime_time_stamp,"lime_time_stamp"); }; #ifdef HXCPP_VISIT_ALLOCS static void Timer_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(Timer_obj::__mClass,"__mClass"); HX_VISIT_MEMBER_NAME(Timer_obj::sRunningTimers,"sRunningTimers"); HX_VISIT_MEMBER_NAME(Timer_obj::lime_time_stamp,"lime_time_stamp"); }; #endif hx::Class Timer_obj::__mClass; static ::String Timer_obj_sStaticFields[] = { HX_HCSTRING("sRunningTimers","\xfa","\xbb","\xcd","\xfe"), HX_HCSTRING("delay","\x83","\xd7","\x26","\xd7"), HX_HCSTRING("getMS","\x7c","\x95","\x60","\x91"), HX_HCSTRING("measure","\x5e","\xfb","\xe9","\x3c"), HX_HCSTRING("stamp","\x03","\x70","\x0b","\x84"), HX_HCSTRING("__checkTimers","\xd6","\x20","\x5c","\x49"), HX_HCSTRING("__nextWake","\xd7","\x75","\xf7","\x9d"), HX_HCSTRING("lime_time_stamp","\x3b","\x9f","\x6b","\x12"), ::String(null()) }; void Timer_obj::__register() { hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_HCSTRING("haxe.Timer","\x5d","\x9d","\x24","\x4b"); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &Timer_obj::__GetStatic; __mClass->mSetStaticField = &Timer_obj::__SetStatic; __mClass->mMarkFunc = Timer_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(Timer_obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(Timer_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< Timer_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = Timer_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = Timer_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = Timer_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } void Timer_obj::__boot() { { HX_STACK_FRAME("haxe.Timer","boot",0xc6bd04e3,"haxe.Timer.boot","haxe/Timer.hx",203,0x1a690682) HXLINE( 203) sRunningTimers = ::Array_obj< ::Dynamic>::__new(0); } { HX_STACK_FRAME("haxe.Timer","boot",0xc6bd04e3,"haxe.Timer.boot","haxe/Timer.hx",379,0x1a690682) HXLINE( 379) lime_time_stamp = ::openfl::_legacy::Lib_obj::load(HX_("lime-legacy",c1,7f,b9,87),HX_("lime_legacy_time_stamp",9d,85,d0,ec),(int)0); } } }
#include <hxcpp.h> #ifndef INCLUDED_haxe_Log #include <haxe/Log.h> #endif #ifndef INCLUDED_haxe_Timer #include <haxe/Timer.h> #endif #ifndef INCLUDED_openfl__legacy_Lib #include <openfl/_legacy/Lib.h> #endif namespace haxe{ void Timer_obj::__construct(Float time){ HX_STACK_FRAME("haxe.Timer","new",0x4136b0cf,"haxe.Timer.new","haxe/Timer.hx",210,0x1a690682) HX_STACK_THIS(this) HX_STACK_ARG(time,"time") HXLINE( 212) this->mTime = time; HXLINE( 213) ::haxe::Timer_obj::sRunningTimers->push(hx::ObjectPtr<OBJ_>(this)); HXLINE( 214) Float _hx_tmp = ::haxe::Timer_obj::getMS(); HXDLIN( 214) this->mFireAt = (_hx_tmp + this->mTime); HXLINE( 215) this->mRunning = true; } Dynamic Timer_obj::__CreateEmpty() { return new Timer_obj; } hx::ObjectPtr< Timer_obj > Timer_obj::__new(Float time) { hx::ObjectPtr< Timer_obj > _hx_result = new Timer_obj(); _hx_result->__construct(time); return _hx_result; } Dynamic Timer_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< Timer_obj > _hx_result = new Timer_obj(); _hx_result->__construct(inArgs[0]); return _hx_result; } HX_BEGIN_DEFAULT_FUNC(__default_run,Timer_obj) void _hx_run(){ HX_STACK_FRAME("haxe.Timer","__default_run",0xdc2b9b9c,"haxe.Timer.__default_run","haxe/Timer.hx",257,0x1a690682) HX_STACK_THIS(this) } HX_END_LOCAL_FUNC0((void)) HX_END_DEFAULT_FUNC void Timer_obj::stop(){ HX_STACK_FRAME("haxe.Timer","stop",0xd1fd70b3,"haxe.Timer.stop","haxe/Timer.hx",277,0x1a690682) HX_STACK_THIS(this) HXLINE( 277) Bool _hx_tmp = this->mRunning; HXDLIN( 277) if (_hx_tmp) { HXLINE( 279) this->mRunning = false; HXLINE( 281) { HXLINE( 281) HX_VARI( Int,_g1) = (int)0; HXDLIN( 281) HX_VARI( Int,_g) = ::haxe::Timer_obj::sRunningTimers->length; HXDLIN( 281) while((_g1 < _g)){ HXLINE( 281) HX_VARI( Int,i) = _g1++; HXLINE( 283) Bool _hx_tmp1 = hx::IsEq( ::haxe::Timer_obj::sRunningTimers->__get(i).StaticCast< ::haxe::Timer >(),hx::ObjectPtr<OBJ_>(this) ); HXDLIN( 283) if (_hx_tmp1) { HXLINE( 285) ::haxe::Timer_obj::sRunningTimers[i] = null(); HXLINE( 286) goto _hx_goto_0; } } _hx_goto_0:; } } } HX_DEFINE_DYNAMIC_FUNC0(Timer_obj,stop,(void)) void Timer_obj::_hx___check(Float inTime){ HX_STACK_FRAME("haxe.Timer","__check",0xb5623597,"haxe.Timer.__check","haxe/Timer.hx",299,0x1a690682) HX_STACK_THIS(this) HX_STACK_ARG(inTime,"inTime") HXLINE( 299) Bool _hx_tmp = (inTime >= this->mFireAt); HXDLIN( 299) if (_hx_tmp) { HXLINE( 301) hx::AddEq(this->mFireAt,this->mTime); HXLINE( 302) this->run(); } } HX_DEFINE_DYNAMIC_FUNC1(Timer_obj,_hx___check,(void)) ::Array< ::Dynamic> Timer_obj::sRunningTimers; ::haxe::Timer Timer_obj::delay( ::Dynamic f,Int time){ HX_BEGIN_LOCAL_FUNC_S2(hx::LocalFunc,_hx_Closure_0, ::Dynamic,f, ::haxe::Timer,t) HXARGC(0) void _hx_run(){ HX_STACK_FRAME("haxe.Timer","delay",0x3ed5f1b2,"haxe.Timer.delay","haxe/Timer.hx",224,0x1a690682) HXLINE( 226) t->stop(); HXLINE( 227) f(); } HX_END_LOCAL_FUNC0((void)) HX_STACK_FRAME("haxe.Timer","delay",0x3ed5f1b2,"haxe.Timer.delay","haxe/Timer.hx",220,0x1a690682) HX_STACK_ARG(f,"f") HX_STACK_ARG(time,"time") HXLINE( 222) HX_VARI( ::haxe::Timer,t) = ::haxe::Timer_obj::__new(time); HXLINE( 224) t->run = ::Dynamic(new _hx_Closure_0(f,t)); HXLINE( 231) return t; } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Timer_obj,delay,return ) Float Timer_obj::getMS(){ HX_STACK_FRAME("haxe.Timer","getMS",0xf90fafab,"haxe.Timer.getMS","haxe/Timer.hx",239,0x1a690682) HXLINE( 239) Float _hx_tmp = ( (Float)(::haxe::Timer_obj::lime_time_stamp()) ); HXDLIN( 239) return (_hx_tmp * ((Float)1000.0)); } STATIC_HX_DEFINE_DYNAMIC_FUNC0(Timer_obj,getMS,return ) ::Dynamic Timer_obj::measure( ::Dynamic f, ::Dynamic pos){ HX_STACK_FRAME("haxe.Timer","measure",0x42373f4d,"haxe.Timer.measure","haxe/Timer.hx",247,0x1a690682) HX_STACK_ARG(f,"f") HX_STACK_ARG(pos,"pos") HXLINE( 249) HX_VARI( Float,t0) = ::haxe::Timer_obj::stamp(); HXLINE( 250) HX_VARI( ::Dynamic,r) = f(); HXLINE( 251) Float _hx_tmp = ::haxe::Timer_obj::stamp(); HXDLIN( 251) ::haxe::Log_obj::trace(((_hx_tmp - t0) + HX_("s",73,00,00,00)),pos); HXLINE( 252) return r; } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Timer_obj,measure,return ) Float Timer_obj::stamp(){ HX_STACK_FRAME("haxe.Timer","stamp",0xebba8a32,"haxe.Timer.stamp","haxe/Timer.hx",267,0x1a690682) HXLINE( 267) return ( (Float)(::haxe::Timer_obj::lime_time_stamp()) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC0(Timer_obj,stamp,return ) void Timer_obj::_hx___checkTimers(){ HX_STACK_FRAME("haxe.Timer","__checkTimers",0xb7078205,"haxe.Timer.__checkTimers","haxe/Timer.hx",309,0x1a690682) HXLINE( 311) HX_VARI( Float,now) = ::haxe::Timer_obj::getMS(); HXLINE( 312) HX_VARI( Bool,foundNull) = false; HXLINE( 313) HX_VAR( ::haxe::Timer,timer); HXLINE( 315) { HXLINE( 315) HX_VARI( Int,_g1) = (int)0; HXDLIN( 315) HX_VARI( Int,_g) = ::haxe::Timer_obj::sRunningTimers->length; HXDLIN( 315) while((_g1 < _g)){ HXLINE( 315) HX_VARI( Int,i) = _g1++; HXLINE( 317) timer = ::haxe::Timer_obj::sRunningTimers->__get(i).StaticCast< ::haxe::Timer >(); HXLINE( 319) Bool _hx_tmp = hx::IsNotNull( timer ); HXDLIN( 319) if (_hx_tmp) { HXLINE( 321) timer->_hx___check(now); } HXLINE( 325) Bool _hx_tmp1 = !(foundNull); HXDLIN( 325) if (_hx_tmp1) { HXLINE( 325) foundNull = hx::IsNull( ::haxe::Timer_obj::sRunningTimers->__get(i).StaticCast< ::haxe::Timer >() ); } else { HXLINE( 325) foundNull = true; } } } HXLINE( 329) if (foundNull) { HX_BEGIN_LOCAL_FUNC_S0(hx::LocalFunc,_hx_Closure_0) HXARGC(1) Bool _hx_run( ::haxe::Timer val){ HX_STACK_FRAME("haxe.Timer","__checkTimers",0xb7078205,"haxe.Timer.__checkTimers","haxe/Timer.hx",331,0x1a690682) HX_STACK_ARG(val,"val") HXLINE( 331) return hx::IsNotNull( val ); } HX_END_LOCAL_FUNC1(return) HXLINE( 331) ::haxe::Timer_obj::sRunningTimers = ::haxe::Timer_obj::sRunningTimers->filter( ::Dynamic(new _hx_Closure_0())); } }
::Dynamic Timer_obj::lime_time_stamp; Timer_obj::Timer_obj() { run = new __default_run(this); } void Timer_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(Timer); HX_MARK_MEMBER_NAME(mTime,"mTime"); HX_MARK_MEMBER_NAME(mFireAt,"mFireAt"); HX_MARK_MEMBER_NAME(mRunning,"mRunning"); HX_MARK_MEMBER_NAME(run,"run"); HX_MARK_END_CLASS(); } void Timer_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(mTime,"mTime"); HX_VISIT_MEMBER_NAME(mFireAt,"mFireAt"); HX_VISIT_MEMBER_NAME(mRunning,"mRunning"); HX_VISIT_MEMBER_NAME(run,"run"); } hx::Val Timer_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"run") ) { return hx::Val( run); } break; case 4: if (HX_FIELD_EQ(inName,"stop") ) { return hx::Val( stop_dyn()); } break; case 5: if (HX_FIELD_EQ(inName,"mTime") ) { return hx::Val( mTime); } break; case 7: if (HX_FIELD_EQ(inName,"mFireAt") ) { return hx::Val( mFireAt); } if (HX_FIELD_EQ(inName,"__check") ) { return hx::Val( _hx___check_dyn()); } break; case 8: if (HX_FIELD_EQ(inName,"mRunning") ) { return hx::Val( mRunning); } } return super::__Field(inName,inCallProp); } bool Timer_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"delay") ) { outValue = delay_dyn(); return true; } if (HX_FIELD_EQ(inName,"getMS") ) { outValue = getMS_dyn(); return true; } if (HX_FIELD_EQ(inName,"stamp") ) { outValue = stamp_dyn(); return true; } break; case 7: if (HX_FIELD_EQ(inName,"measure") ) { outValue = measure_dyn(); return true; } break; case 10: if (HX_FIELD_EQ(inName,"__nextWake") ) { outValue = _hx___nextWake_dyn(); return true; } break; case 13: if (HX_FIELD_EQ(inName,"__checkTimers") ) { outValue = _hx___checkTimers_dyn(); return true; } break; case 14: if (HX_FIELD_EQ(inName,"sRunningTimers") ) { outValue = sRunningTimers; return true; } break; case 15: if (HX_FIELD_EQ(inName,"lime_time_stamp") ) { outValue = lime_time_stamp; return true; } } return false; } hx::Val Timer_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"run") ) { run=inValue.Cast< ::Dynamic >(); return inValue; } break; case 5: if (HX_FIELD_EQ(inName,"mTime") ) { mTime=inValue.Cast< Float >(); return inValue; } break; case 7: if (HX_FIELD_EQ(inName,"mFireAt") ) { mFireAt=inValue.Cast< Float >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"mRunning") ) { mRunning=inValue.Cast< Bool >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } bool Timer_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 14: if (HX_FIELD_EQ(inName,"sRunningTimers") ) { sRunningTimers=ioValue.Cast< ::Array< ::Dynamic> >(); return true; } break; case 15: if (HX_FIELD_EQ(inName,"lime_time_stamp") ) { lime_time_stamp=ioValue.Cast< ::Dynamic >(); return true; } } return false; } void Timer_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_HCSTRING("mTime","\x1a","\x33","\x83","\xfa")); outFields->push(HX_HCSTRING("mFireAt","\x96","\xea","\x58","\x72")); outFields->push(HX_HCSTRING("mRunning","\x12","\x2d","\x35","\x13")); super::__GetFields(outFields); }; #if HXCPP_SCRIPTABLE static hx::StorageInfo Timer_obj_sMemberStorageInfo[] = { {hx::fsFloat,(int)offsetof(Timer_obj,mTime),HX_HCSTRING("mTime","\x1a","\x33","\x83","\xfa")}, {hx::fsFloat,(int)offsetof(Timer_obj,mFireAt),HX_HCSTRING("mFireAt","\x96","\xea","\x58","\x72")}, {hx::fsBool,(int)offsetof(Timer_obj,mRunning),HX_HCSTRING("mRunning","\x12","\x2d","\x35","\x13")}, {hx::fsObject ,(int)offsetof(Timer_obj,run),HX_HCSTRING("run","\x4b","\xe7","\x56","\x00")}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo Timer_obj_sStaticStorageInfo[] = { {hx::fsObject ,(void *) &Timer_obj::sRunningTimers,HX_HCSTRING("sRunningTimers","\xfa","\xbb","\xcd","\xfe")}, {hx::fsObject ,(void *) &Timer_obj::lime_time_stamp,HX_HCSTRING("lime_time_stamp","\x3b","\x9f","\x6b","\x12")}, { hx::fsUnknown, 0, null()} }; #endif static ::String Timer_obj_sMemberFields[] = { HX_HCSTRING("mTime","\x1a","\x33","\x83","\xfa"), HX_HCSTRING("mFireAt","\x96","\xea","\x58","\x72"), HX_HCSTRING("mRunning","\x12","\x2d","\x35","\x13"), HX_HCSTRING("run","\x4b","\xe7","\x56","\x00"), HX_HCSTRING("stop","\x02","\xf0","\x5b","\x4c"), HX_HCSTRING("__check","\xa8","\xf1","\x14","\xb0"), ::String(null()) }; static void Timer_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(Timer_obj::__mClass,"__mClass"); HX_MARK_MEMBER_NAME(Timer_obj::sRunningTimers,"sRunningTimers"); HX_MARK_MEMBER_NAME(Timer_obj::lime_time_stamp,"lime_time_stamp"); }; #ifdef HXCPP_VISIT_ALLOCS static void Timer_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(Timer_obj::__mClass,"__mClass"); HX_VISIT_MEMBER_NAME(Timer_obj::sRunningTimers,"sRunningTimers"); HX_VISIT_MEMBER_NAME(Timer_obj::lime_time_stamp,"lime_time_stamp"); }; #endif hx::Class Timer_obj::__mClass; static ::String Timer_obj_sStaticFields[] = { HX_HCSTRING("sRunningTimers","\xfa","\xbb","\xcd","\xfe"), HX_HCSTRING("delay","\x83","\xd7","\x26","\xd7"), HX_HCSTRING("getMS","\x7c","\x95","\x60","\x91"), HX_HCSTRING("measure","\x5e","\xfb","\xe9","\x3c"), HX_HCSTRING("stamp","\x03","\x70","\x0b","\x84"), HX_HCSTRING("__checkTimers","\xd6","\x20","\x5c","\x49"), HX_HCSTRING("__nextWake","\xd7","\x75","\xf7","\x9d"), HX_HCSTRING("lime_time_stamp","\x3b","\x9f","\x6b","\x12"), ::String(null()) }; void Timer_obj::__register() { hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_HCSTRING("haxe.Timer","\x5d","\x9d","\x24","\x4b"); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &Timer_obj::__GetStatic; __mClass->mSetStaticField = &Timer_obj::__SetStatic; __mClass->mMarkFunc = Timer_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(Timer_obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(Timer_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< Timer_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = Timer_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = Timer_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = Timer_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } void Timer_obj::__boot() { { HX_STACK_FRAME("haxe.Timer","boot",0xc6bd04e3,"haxe.Timer.boot","haxe/Timer.hx",203,0x1a690682) HXLINE( 203) sRunningTimers = ::Array_obj< ::Dynamic>::__new(0); } { HX_STACK_FRAME("haxe.Timer","boot",0xc6bd04e3,"haxe.Timer.boot","haxe/Timer.hx",379,0x1a690682) HXLINE( 379) lime_time_stamp = ::openfl::_legacy::Lib_obj::load(HX_("lime-legacy",c1,7f,b9,87),HX_("lime_legacy_time_stamp",9d,85,d0,ec),(int)0); } } }
STATIC_HX_DEFINE_DYNAMIC_FUNC0(Timer_obj,_hx___checkTimers,(void)) Float Timer_obj::_hx___nextWake(Float limit){ HX_STACK_FRAME("haxe.Timer","__nextWake",0x0e101148,"haxe.Timer.__nextWake","haxe/Timer.hx",339,0x1a690682) HX_STACK_ARG(limit,"limit") HXLINE( 341) HX_VARI( Float,now) = ::haxe::Timer_obj::getMS(); HXLINE( 342) HX_VAR( Float,sleep); HXLINE( 344) { HXLINE( 344) HX_VARI( Int,_g) = (int)0; HXDLIN( 344) HX_VARI( ::Array< ::Dynamic>,_g1) = ::haxe::Timer_obj::sRunningTimers; HXDLIN( 344) while((_g < _g1->length)){ HXLINE( 344) HX_VARI( ::haxe::Timer,timer) = _g1->__get(_g).StaticCast< ::haxe::Timer >(); HXDLIN( 344) ++_g; HXLINE( 346) Bool _hx_tmp = hx::IsNull( timer ); HXDLIN( 346) if (_hx_tmp) { HXLINE( 347) continue; } HXLINE( 349) sleep = (timer->mFireAt - now); HXLINE( 351) Bool _hx_tmp1 = (sleep < limit); HXDLIN( 351) if (_hx_tmp1) { HXLINE( 353) limit = sleep; HXLINE( 355) if ((sleep < (int)0)) { HXLINE( 357) return (int)0; } } } } HXLINE( 365) return (limit * ((Float)0.001)); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Timer_obj,_hx___nextWake,return )
call_expression
[ { "content": "class HXCPP_CLASS_ATTRIBUTES Timer_obj : public hx::Object\n\n{\n\n\tpublic:\n\n\t\ttypedef hx::Object super;\n\n\t\ttypedef Timer_obj OBJ_;\n\n\t\tTimer_obj();\n\n\n\n\tpublic:\n\n\t\tvoid __construct(Float time);\n\n\t\tinline void *operator new(size_t inSize, bool inContainer=true,const char *i...
C++
include/external/urdl/istreambuf.hpp
Ptomaine/nstd
72daa4abab97dc82b407c774b00476459df0730b
#ifndef URDL_ISTREAMBUF_HPP #define URDL_ISTREAMBUF_HPP #include <streambuf> #include "detail/config.hpp" #include "option_set.hpp" #include "url.hpp" #include "detail/abi_prefix.hpp" namespace urdl { class istreambuf : public std::streambuf { public: URDL_DECL istreambuf(); URDL_DECL ~istreambuf(); template <typename Option> void set_option(const Option& option) { option_set options; options.set_option(option); set_options(options); } URDL_DECL void set_options(const option_set& options); template <typename Option> Option get_option() const { option_set options(get_options()); return options.get_option<Option>(); } URDL_DECL option_set get_options() const; URDL_DECL bool is_open() const; URDL_DECL istreambuf* open(const url& u); URDL_DECL istreambuf* close(); URDL_DECL const asio::error_code& puberror() const; URDL_DECL std::size_t open_timeout() const; URDL_DECL void open_timeout(std::size_t milliseconds); URDL_DECL std::size_t read_timeout() const; URDL_DECL void read_timeout(std::size_t milliseconds); URDL_DECL std::string content_type() const; URDL_DECL std::size_t content_length() const; URDL_DECL std::string headers() const; protected: URDL_DECL int_type underflow(); URDL_DECL virtual const asio::error_code& error() const; private: URDL_DECL void init_buffers(); struct body; body* body_; }; } #include "detail/abi_suffix.hpp" #if defined(URDL_HEADER_ONLY) # include "impl/istreambuf.ipp" #endif #endif
#ifndef URDL_ISTREAMBUF_HPP #define URDL_ISTREAMBUF_HPP #include <streambuf> #include "detail/config.hpp" #include "option_set.hpp" #include "url.hpp" #include "detail/abi_prefix.hpp" namespace urdl {
fix.hpp" #if defined(URDL_HEADER_ONLY) # include "impl/istreambuf.ipp" #endif #endif
class istreambuf : public std::streambuf { public: URDL_DECL istreambuf(); URDL_DECL ~istreambuf(); template <typename Option> void set_option(const Option& option) { option_set options; options.set_option(option); set_options(options); } URDL_DECL void set_options(const option_set& options); template <typename Option> Option get_option() const { option_set options(get_options()); return options.get_option<Option>(); } URDL_DECL option_set get_options() const; URDL_DECL bool is_open() const; URDL_DECL istreambuf* open(const url& u); URDL_DECL istreambuf* close(); URDL_DECL const asio::error_code& puberror() const; URDL_DECL std::size_t open_timeout() const; URDL_DECL void open_timeout(std::size_t milliseconds); URDL_DECL std::size_t read_timeout() const; URDL_DECL void read_timeout(std::size_t milliseconds); URDL_DECL std::string content_type() const; URDL_DECL std::size_t content_length() const; URDL_DECL std::string headers() const; protected: URDL_DECL int_type underflow(); URDL_DECL virtual const asio::error_code& error() const; private: URDL_DECL void init_buffers(); struct body; body* body_; }; } #include "detail/abi_suf
random
[ { "content": "*/\n\n\n\n#define URDL_HEADER_ONLY\n\n#define URDL_DISABLE_SSL\n\n#define ASIO_STANDALONE\n\n#define ASIO_HAS_STD_CHRONO\n\n\n\n#include \"external/asio/asio/include/asio.hpp\"\n\n#include \"external/urdl/http.hpp\"\n\n#include \"external/urdl/istream.hpp\"\n\n#include \"external/urdl/istreambuf.h...
C++
src/machine_learning/matrix_factorization.cpp
rafaelppires/rex
4d3c10ba4bde86365090b5c7c5e8de037a1fb885
#include "matrix_factorization.h" #include <utils/time_probe.h> #include <iostream> MatrixFactorizationModel::MatrixFactorizationModel(int rank) : rank_(rank) {} double MatrixFactorizationModel::predict(int user, int item) const { return weights_.predict(user, item); } double MatrixFactorizationModel::rmse(const TripletVector<uint8_t> &testset) { size_t count = 0; double sumofsquares = 0; for (auto &t : testset) { double diff = t.value() - predict(t.row(), t.col()); sumofsquares += diff * diff; ++count; } return sqrt(sumofsquares / count); } bool MatrixFactorizationModel::init_item(int item, const Sparse &column) { if (!weights_.has_item(item)) { find_space(0, item); weights_.items.col(item) = column; return true; } return false; } bool MatrixFactorizationModel::init_user(int user, const Sparse &column) { if (!weights_.has_user(user)) { find_space(user, 0); weights_.users.col(user) = column; return true; } return false; } Sparse MatrixFactorizationModel::zero_embedding() { Sparse ret; ret.reserve(rank_); ret.resize(rank_, 1); ret.col(0) = Eigen::MatrixXd::Zero(rank_, 1).sparseView(); return ret; } void MatrixFactorizationModel::make_compressed() { weights_.users.makeCompressed(); weights_.items.makeCompressed(); weights_.user_biases.makeCompressed(); weights_.item_biases.makeCompressed(); } void MatrixFactorizationModel::item_merge_column(Sparse &Y, const Sparse &Other) { sparse_matrix_outer_iterate(Other, [&](Sparse::InnerIterator it, int i) { int item = it.col(); if (!init_item(item, Other.col(item))) { Y.col(item) = (Y.col(item) + Other.col(item)) / 2.; } }); } void MatrixFactorizationModel::user_merge_column(Sparse &X, const Sparse &Other) { sparse_matrix_outer_iterate(Other, [&](Sparse::InnerIterator it, int i) { int user = it.col(); if (!init_user(user, Other.col(user))) { X.col(user) = (X.col(user) + Other.col(user)) / 2.; } }); } void MatrixFactorizationModel::merge_average( const MatrixFactorizationModel &m) { item_merge_column(weights_.items, m.weights_.items); item_merge_column(weights_.item_biases, m.weights_.item_biases); user_merge_column(weights_.users, m.weights_.users); user_merge_column(weights_.user_biases, m.weights_.user_biases); } void MatrixFactorizationModel::prep_toshare() { init_user(rank_, weights_.users.col(0)); weights_.users.col(rank_) = weights_.users.col(0); weights_.users.col(0) = Eigen::MatrixXd::Zero(rank_, 1).sparseView(); weights_.user_biases.coeffRef(0, rank_) = weights_.user_biases.coeff(0, 0); weights_.user_biases.coeffRef(0, 0) = 0; } std::set<int> MatrixFactorizationModel::metropolis_hastings( size_t my_degree, const DegreesAndModels &models, Sparse &factors, Sparse &biases, bool isusers) { std::set<int> ret; sparse_matrix_outer_iterate(factors, [&](Sparse::InnerIterator it, int i) { int index = it.col(); double sum_weights = 0; Sparse embedding(zero_embedding()), bias; bias.resize(1, 1); bias.coeffRef(0, 0) = 0; std::vector<size_t> degrees; for (const auto &model : models) { size_t degree = model.degree; const MatrixFactorizationModel &nmodel = model.model; if (isusers ? nmodel.weights_.has_user(index) : nmodel.weights_.has_item(index)) { double weight = 1. / (1 + std::max(my_degree, degree)); embedding.col(0) += weight * (isusers ? nmodel.weights_.users.col(index) : nmodel.weights_.items.col(index)); bias.coeffRef(0, 0) += weight * (isusers ? nmodel.weights_.user_biases.coeff(0, index) : nmodel.weights_.item_biases.coeff(0, index)); sum_weights += weight; degrees.emplace_back(degree); } } if (sum_weights > 1.0) { std::cerr << "my rank: " << rank_ << " idx: " << index << std::endl; std::cerr << "Sum of weights > 1: " << sum_weights << std::endl; std::cerr << my_degree << " (" << degrees.size() << ") - "; for (auto &d : degrees) std::cerr << d << " "; std::cerr << std::endl; abort(); } double my_weight = 1. - sum_weights; factors.col(index) *= my_weight; biases.coeffRef(0, index) *= my_weight; factors.col(index) += embedding.col(0); biases.coeffRef(0, index) += bias.coeff(0, 0); ret.insert(index); }); return ret; } std::set<int> MatrixFactorizationModel::metropolis_hastings_users( size_t my_degree, const DegreesAndModels &models) { return metropolis_hastings(my_degree, models, weights_.users, weights_.user_biases, true); } std::set<int> MatrixFactorizationModel::metropolis_hastings_items( size_t my_degree, const DegreesAndModels &models) { return metropolis_hastings(my_degree, models, weights_.items, weights_.item_biases, false); } std::pair<double, Sparse> MatrixFactorizationModel::combine_neighbors( bool isuser, int index, const DegreesAndModels &models) { struct Entry { Entry(unsigned d, Sparse c, double b) : degree(d), col(c), bias(b) {} unsigned degree; Sparse col; double bias; }; std::vector<Entry> embs; for (const auto &neigh : models) { const MatrixFactorizationModel &nmodel = neigh.model; if (isuser ? nmodel.weights_.has_user(index) : nmodel.weights_.has_item(index)) { embs.emplace_back( neigh.degree, isuser ? nmodel.weights_.users.col(index) : nmodel.weights_.items.col(index), isuser ? nmodel.weights_.user_biases.coeff(0, index) : nmodel.weights_.item_biases.coeff(0, index)); } } Sparse embedd(zero_embedding()); double sum_of_inverses = 0, bias = 0; for (const auto &e : embs) sum_of_inverses += 1.0 / e.degree; for (const auto &e : embs) { double w = (1.0 / (1 + e.degree * (sum_of_inverses - 1.0 / e.degree))); embedd.col(0) += w * e.col; bias += w * e.bias; } return std::make_pair(bias, embedd); } void MatrixFactorizationModel::combine_neighbors_embeddings( bool isuser, const DegreesAndModels &models, std::set<int> &exclude_list) { for (const auto &neigh : models) { sparse_matrix_outer_iterate( isuser ? neigh.model.weights_.users : neigh.model.weights_.items, [&](Sparse::InnerIterator it, int i) { int index = it.col(); if (exclude_list.insert(index).second) { auto combined = combine_neighbors(isuser, index, models); if (isuser) { init_user(index, combined.second); weights_.user_biases.coeffRef(0, index) = combined.first; } else { init_item(index, combined.second); weights_.item_biases.coeffRef(0, index) = combined.first; } } }); } } void MatrixFactorizationModel::combine_neighbors_users( const DegreesAndModels &models, std::set<int> &exclude_list) { combine_neighbors_embeddings(true, models, exclude_list); } void MatrixFactorizationModel::combine_neighbors_items( const DegreesAndModels &models, std::set<int> &exclude_list) { combine_neighbors_embeddings(false, models, exclude_list); } void MatrixFactorizationModel::merge_weighted(size_t my_degree, const DegreesAndModels &models) { std::set<int> users_done = metropolis_hastings_users(my_degree, models), items_done = metropolis_hastings_items(my_degree, models); combine_neighbors_users(models, users_done); combine_neighbors_items(models, items_done); } void MatrixFactorizationModel::find_space(int user, int item, const Sparse &col, double b) { auto &Y = weights_.items, &B = weights_.item_biases; auto &X = weights_.users, &A = weights_.user_biases; if (item >= Y.cols()) { Y.conservativeResize(rank_, item + 1); B.conservativeResize(1, item + 1); if (col.outerSize() > 0) Y.col(item) = col; if (b > 0) B.coeffRef(0, item) = b; } if (user >= X.cols()) { X.conservativeResize(rank_, user + 1); A.conservativeResize(1, user + 1); if (col.outerSize() > 0) X.col(user) = col; if (b > 0) A.coeffRef(0, user) = b; } } size_t MatrixFactorizationModel::estimate_serial_size() const { return sizeof(rank_) + weights_.estimate_serial_size(); } void MatrixFactorizationModel::serialize_append( std::vector<uint8_t> &out) const { const uint8_t *rptr = reinterpret_cast<const uint8_t *>(&rank_); out.insert(out.end(), rptr, rptr + sizeof(rank_)); weights_.serialize_append(out); } size_t MatrixFactorizationModel::deserialize(const std::vector<uint8_t> &data, size_t offset) { rank_ = *reinterpret_cast<const int *>(&data[offset]); return weights_.deserialize(data, offset + sizeof(rank_)); } HyperMFSGD::HyperMFSGD(int r, double lr, double rp, double ib, double ifact) : rank(r), learning_rate(lr), regularization_param(rp), init_factor(ifact), init_bias(ib) { #if 0 init_column_ = Sparse(Dense::Constant(r, 1, ifact).sparseView()); #else TripletVector<double> column; for (int i = 0; i < r; ++i) { column.emplace_back(i, 0, ifact * double(rand() % 10000) / 10000); } Sparse m(r, 1); m.setFromTriplets(column.begin(), column.end()); init_column_ = m; #endif } MFSGD::MFSGD(HyperMFSGD h) : hyper_(h), model_(h.rank), weights_(model_.weights_) {} double MFSGD::train(int user, int item, double value) { auto &Y = weights_.items, &B = weights_.item_biases; auto &X = weights_.users, &A = weights_.user_biases; double lambda = hyper_.regularization_param, eta = hyper_.learning_rate; #if 1 double err = value - model_.predict(user, item), step = eta * err, mult = 1 - eta * lambda; Y.col(item) = mult * Y.col(item) + step * X.col(user); B.coeffRef(0, item) += step; X.col(user) = mult * X.col(user) + step * Y.col(item); A.coeffRef(0, user) += step; #else double err = value - model_.predict(user, item); B.coeffRef(0, item) += eta * (err - lambda * B.coeffRef(0, item)); A.coeffRef(0, user) += eta * (err - lambda * A.coeffRef(0, user)); X.col(user) += eta * (err * Y.col(item) - lambda * X.col(user)); Y.col(item) += eta * (err * X.col(user) - lambda * Y.col(item)); #endif return err * err; } void MatrixFactorizationModel::get_factors(int user, int item) { }
#include "matrix_factorization.h" #include <utils/time_probe.h> #include <iostream> MatrixFactorizationModel::MatrixFactorizationModel(int rank) : rank_(rank) {} double MatrixFactorizationModel::predict(int user, int item) const { return weights_.predict(user, item); } double MatrixFactorizationModel::rmse(const TripletVector<uint8_t> &testset) { size_t count = 0; double sumofsquares = 0; for (auto &t : testset) { double diff = t.value() - predict(t.row(), t.col()); sumofsquares += diff * diff; ++count; } return sqrt(sumofsquares / count); } bool MatrixFactorizationModel::init_item(int item, const Sparse &column) { if (!weights_.has_item(item)) { find_space(0, item); weights_.items.col(item) = column; return true; } return false; } bool MatrixFactorizationModel::init_user(int user, const Sparse &column) { if (!weights_.has_user(user)) { find_space(user, 0); weights_.users.col(user) = column; return true; } return false; } Sparse MatrixFactorizationModel::zero_embedding() { Sparse ret; ret.reserve(rank_); ret.resize(rank_, 1); ret.col(0) = Eigen::MatrixXd::Zero(rank_, 1).sparseView(); return ret; } void MatrixFactorizationModel::make_compressed() { weights_.users.makeCompressed(); weights_.items.makeCompressed(); weights_.user_biases.makeCompressed(); weights_.item_biases.makeCompressed(); } void MatrixFactorizationModel::item_merge_column(Sparse &Y, const Sparse &Other) { sparse_matrix_outer_iterate(Other, [&](Sparse::InnerIterator it, int i) { int item = it.col(); if (!init_item(item, Other.col(item))) { Y.col(item) = (Y.col(item) + Other.col(item)) / 2.; } }); } void MatrixFactorizationModel::user_merge_column(Sparse &X, const Sparse &Other) { sparse_matrix_outer_iterate(Other, [&](Sparse::InnerIterator it, int i) { int user = it.col(); if (!init_user(user, Other.col(user))) { X.col(user) = (X.col(user) + Other.col(user)) / 2.; } }); } void MatrixFactorizationModel::merge_average( const MatrixFactorizationModel &m) { item_merge_column(weights_.items, m.weights_.items); item_merge_column(weights_.item_biases, m.weights_.item_biases); user_merge_column(weights_.users, m.weights_.users); user_merge_column(weights_.user_biases, m.weights_.user_biases); } void MatrixFactorizationModel::prep_toshare() { init_user(rank_, weights_.users.col(0)); weights_.users.col(rank_) = weights_.users.col(0); weights_.users.col(0) = Eigen::MatrixXd::Zero(rank_, 1).sparseView(); weights_.user_biases.coeffRef(0, rank_) = weights_.user_biases.coeff(0, 0); weights_.user_biases.coeffRef(0, 0) = 0; } std::set<int> MatrixFactorizationModel::metropolis_hastings( size_t my_degree, const DegreesAndModels &models, Sparse &factors, Sparse &biases, bool isusers) { std::set<int> ret; sparse_matrix_outer_iterate(factors, [&](Sparse::InnerIterator it, int i) { int index = it.col(); double sum_weights = 0; Sparse embedding(zero_embedding()), bias; bias.resize(1, 1); bias.coeffRef(0, 0) = 0; std::vector<size_t> degrees; for (const auto &model : models) { size_t degree = model.degree; const MatrixFactorizationModel &nmodel = model.model; if (isusers ? nmodel.weights_.has_user(index) : nmodel.weights_.has_item(index)) { double weight = 1. / (1 + std::max(my_degree, degree)); embedding.col(0) += weight * (isusers ? nmodel.weights_.users.col(index) : nmodel.weights_.items.col(index)); bias.coeffRef(0, 0) += weight * (isusers ? nmodel.weights_.user_biases.coeff(0, index) : nmodel.weights_.item_biases.coeff(0, index)); sum_weights += weight; degrees.emplace_back(degree); } } if (sum_weights > 1.0) { std::cerr << "my rank: " << rank_ << " idx: " << index << std::endl; std::cerr << "Sum of weights > 1: " << sum_weights << std::endl; std::cerr << my_degree << " (" << degrees.size() << ") - "; for (auto &d : degrees) std::cerr << d << " "; std::cerr << std::endl; abort(); } double my_weight = 1. - sum_weights; factors.col(index) *= my_weight; biase
rank_) + weights_.estimate_serial_size(); } void MatrixFactorizationModel::serialize_append( std::vector<uint8_t> &out) const { const uint8_t *rptr = reinterpret_cast<const uint8_t *>(&rank_); out.insert(out.end(), rptr, rptr + sizeof(rank_)); weights_.serialize_append(out); } size_t MatrixFactorizationModel::deserialize(const std::vector<uint8_t> &data, size_t offset) { rank_ = *reinterpret_cast<const int *>(&data[offset]); return weights_.deserialize(data, offset + sizeof(rank_)); } HyperMFSGD::HyperMFSGD(int r, double lr, double rp, double ib, double ifact) : rank(r), learning_rate(lr), regularization_param(rp), init_factor(ifact), init_bias(ib) { #if 0 init_column_ = Sparse(Dense::Constant(r, 1, ifact).sparseView()); #else TripletVector<double> column; for (int i = 0; i < r; ++i) { column.emplace_back(i, 0, ifact * double(rand() % 10000) / 10000); } Sparse m(r, 1); m.setFromTriplets(column.begin(), column.end()); init_column_ = m; #endif } MFSGD::MFSGD(HyperMFSGD h) : hyper_(h), model_(h.rank), weights_(model_.weights_) {} double MFSGD::train(int user, int item, double value) { auto &Y = weights_.items, &B = weights_.item_biases; auto &X = weights_.users, &A = weights_.user_biases; double lambda = hyper_.regularization_param, eta = hyper_.learning_rate; #if 1 double err = value - model_.predict(user, item), step = eta * err, mult = 1 - eta * lambda; Y.col(item) = mult * Y.col(item) + step * X.col(user); B.coeffRef(0, item) += step; X.col(user) = mult * X.col(user) + step * Y.col(item); A.coeffRef(0, user) += step; #else double err = value - model_.predict(user, item); B.coeffRef(0, item) += eta * (err - lambda * B.coeffRef(0, item)); A.coeffRef(0, user) += eta * (err - lambda * A.coeffRef(0, user)); X.col(user) += eta * (err * Y.col(item) - lambda * X.col(user)); Y.col(item) += eta * (err * X.col(user) - lambda * Y.col(item)); #endif return err * err; } void MatrixFactorizationModel::get_factors(int user, int item) { }
s.coeffRef(0, index) *= my_weight; factors.col(index) += embedding.col(0); biases.coeffRef(0, index) += bias.coeff(0, 0); ret.insert(index); }); return ret; } std::set<int> MatrixFactorizationModel::metropolis_hastings_users( size_t my_degree, const DegreesAndModels &models) { return metropolis_hastings(my_degree, models, weights_.users, weights_.user_biases, true); } std::set<int> MatrixFactorizationModel::metropolis_hastings_items( size_t my_degree, const DegreesAndModels &models) { return metropolis_hastings(my_degree, models, weights_.items, weights_.item_biases, false); } std::pair<double, Sparse> MatrixFactorizationModel::combine_neighbors( bool isuser, int index, const DegreesAndModels &models) { struct Entry { Entry(unsigned d, Sparse c, double b) : degree(d), col(c), bias(b) {} unsigned degree; Sparse col; double bias; }; std::vector<Entry> embs; for (const auto &neigh : models) { const MatrixFactorizationModel &nmodel = neigh.model; if (isuser ? nmodel.weights_.has_user(index) : nmodel.weights_.has_item(index)) { embs.emplace_back( neigh.degree, isuser ? nmodel.weights_.users.col(index) : nmodel.weights_.items.col(index), isuser ? nmodel.weights_.user_biases.coeff(0, index) : nmodel.weights_.item_biases.coeff(0, index)); } } Sparse embedd(zero_embedding()); double sum_of_inverses = 0, bias = 0; for (const auto &e : embs) sum_of_inverses += 1.0 / e.degree; for (const auto &e : embs) { double w = (1.0 / (1 + e.degree * (sum_of_inverses - 1.0 / e.degree))); embedd.col(0) += w * e.col; bias += w * e.bias; } return std::make_pair(bias, embedd); } void MatrixFactorizationModel::combine_neighbors_embeddings( bool isuser, const DegreesAndModels &models, std::set<int> &exclude_list) { for (const auto &neigh : models) { sparse_matrix_outer_iterate( isuser ? neigh.model.weights_.users : neigh.model.weights_.items, [&](Sparse::InnerIterator it, int i) { int index = it.col(); if (exclude_list.insert(index).second) { auto combined = combine_neighbors(isuser, index, models); if (isuser) { init_user(index, combined.second); weights_.user_biases.coeffRef(0, index) = combined.first; } else { init_item(index, combined.second); weights_.item_biases.coeffRef(0, index) = combined.first; } } }); } } void MatrixFactorizationModel::combine_neighbors_users( const DegreesAndModels &models, std::set<int> &exclude_list) { combine_neighbors_embeddings(true, models, exclude_list); } void MatrixFactorizationModel::combine_neighbors_items( const DegreesAndModels &models, std::set<int> &exclude_list) { combine_neighbors_embeddings(false, models, exclude_list); } void MatrixFactorizationModel::merge_weighted(size_t my_degree, const DegreesAndModels &models) { std::set<int> users_done = metropolis_hastings_users(my_degree, models), items_done = metropolis_hastings_items(my_degree, models); combine_neighbors_users(models, users_done); combine_neighbors_items(models, items_done); } void MatrixFactorizationModel::find_space(int user, int item, const Sparse &col, double b) { auto &Y = weights_.items, &B = weights_.item_biases; auto &X = weights_.users, &A = weights_.user_biases; if (item >= Y.cols()) { Y.conservativeResize(rank_, item + 1); B.conservativeResize(1, item + 1); if (col.outerSize() > 0) Y.col(item) = col; if (b > 0) B.coeffRef(0, item) = b; } if (user >= X.cols()) { X.conservativeResize(rank_, user + 1); A.conservativeResize(1, user + 1); if (col.outerSize() > 0) X.col(user) = col; if (b > 0) A.coeffRef(0, user) = b; } } size_t MatrixFactorizationModel::estimate_serial_size() const { return sizeof(
random
[ { "content": "class meta_sqrt<Y, InfX, SupX, true> { public: enum { ret = (SupX*SupX <= Y) ? SupX : InfX }; };\n\n\n\n\n\n/** \\internal Computes the least common multiple of two positive integer A and B\n\n * at compile-time. It implements a naive algorithm testing all multiples of A.\n\n * It thus works be...
C++
vtkMAF/Testing/vtkMAFVolumeResampleTest.cpp
FusionBox2/MAF2
b576955f4f6b954467021f12baedfebcaf79a382
#include <cppunit/config/SourcePrefix.h> #include "vtkMAFVolumeResampleTest.h" #include "vtkMAFSmartPointer.h" #include "vtkMAFVolumeResample.h" #include "vtkDataSet.h" #include "vtkStructuredPoints.h" #include "vtkRectilinearGridReader.h" #include "vtkRectilinearGrid.h" #include "vtkDataArray.h" #include "vtkPointData.h" #include "vtkDataSetWriter.h" using namespace std; void vtkMAFVolumeResampleTest::TestResample() { const char *inFileName = "volumeRG_dim_10_10_10_bounds_1_10_1_10_1_10.vtk"; const char *outVTKFileName= "resampled_volumeRG_dim_10_10_10_bounds_1_10_1_10_1_10.vtk"; TestResampleInternal(inFileName, outVTKFileName ); inFileName = "volumeRG_dim_10_10_10_bounds_m5_5_m5_5_m5_5.vtk"; outVTKFileName= "resampled_volumeRG_dim_10_10_10_bounds_m5_5_m5_5_m5_5.vtk"; TestResampleInternal(inFileName, outVTKFileName ); } void vtkMAFVolumeResampleTest::TestResampleInternal( const char *inFileName , const char *outVTKFileName ) { std::string absPathFilename=MAF_DATA_ROOT; absPathFilename += "/Test_VolumeResample/"; absPathFilename.append(inFileName); vtkRectilinearGridReader *reader = vtkRectilinearGridReader::New(); reader->SetFileName(absPathFilename.c_str()); reader->Update(); double inputDataSpacing[3]; vtkRectilinearGrid *rg = reader->GetOutput(); inputDataSpacing[0] = rg->GetXCoordinates()->GetComponent(1,0)-rg->GetXCoordinates()->GetComponent(0,0); inputDataSpacing[1] = rg->GetYCoordinates()->GetComponent(1,0)-rg->GetYCoordinates()->GetComponent(0,0); inputDataSpacing[2] = rg->GetZCoordinates()->GetComponent(1,0)-rg->GetZCoordinates()->GetComponent(0,0); PrintDouble3(cout, inputDataSpacing, "inputDataSpacing"); double inputDataOrigin[3]; inputDataOrigin[0] = rg->GetXCoordinates()->GetComponent(0,0); inputDataOrigin[1] = rg->GetYCoordinates()->GetComponent(0,0); inputDataOrigin[2] = rg->GetZCoordinates()->GetComponent(0,0); PrintDouble3(cout, inputDataOrigin, "inputDataOrigin"); vtkMAFVolumeResample *resample = vtkMAFVolumeResample::New(); resample->SetZeroValue(0); resample->SetInput(reader->GetOutput()); resample->SetVolumeOrigin(inputDataOrigin); PrintDouble3(cout, inputDataOrigin, "inputDataOrigin"); vtkTransform *transform = vtkTransform::New(); transform->Identity(); transform->Update(); double xAxis[3] = {0,0,0}; for (int i = 0; i < 3; i++) { xAxis[i] = transform->GetMatrix()->GetElement(i, 0); } resample->SetVolumeAxisX(xAxis); PrintDouble3(cout, xAxis, "xAxis"); double yAxis[3] = {0,0,0}; for (int i = 0; i < 3; i++) { yAxis[i] = transform->GetMatrix()->GetElement(i, 1); } resample->SetVolumeAxisY(yAxis); PrintDouble3(cout, yAxis, "yAxis"); double sr[2]; rg->GetScalarRange(sr); double w = sr[1] - sr[0]; double l = (sr[1] + sr[0]) * 0.5; resample->SetWindow(w); resample->SetLevel(l); resample->AutoSpacingOff(); vtkStructuredPoints *outputSP = vtkStructuredPoints::New(); outputSP->SetSource(NULL); outputSP->SetOrigin(inputDataOrigin); outputSP->SetSpacing(inputDataSpacing); outputSP->SetScalarType(rg->GetPointData()->GetScalars()->GetDataType()); double resamplingBoxBounds[6]; rg->GetBounds(resamplingBoxBounds); int outputSPExtent[6]; outputSPExtent[0] = 0; outputSPExtent[1] = (resamplingBoxBounds[1] - resamplingBoxBounds[0]) / inputDataSpacing[0]; outputSPExtent[2] = 0; outputSPExtent[3] = (resamplingBoxBounds[3] - resamplingBoxBounds[2]) / inputDataSpacing[1]; outputSPExtent[4] = 0; outputSPExtent[5] = (resamplingBoxBounds[5] - resamplingBoxBounds[4]) / inputDataSpacing[2]; outputSP->SetExtent(outputSPExtent); outputSP->SetUpdateExtent(outputSPExtent); outputSP->Modified(); resample->SetOutput(outputSP); resample->Update(); double inBounds[6] = {0,0,0}; rg->GetBounds(inBounds); double checkBounds[6]; outputSP->GetBounds(checkBounds); CPPUNIT_ASSERT(checkBounds[0]==inBounds[0] && checkBounds[1]==inBounds[1] && checkBounds[2]==inBounds[2]); CPPUNIT_ASSERT(checkBounds[3]==inBounds[3] && checkBounds[4]==inBounds[4] && checkBounds[5]==inBounds[5]); WriteVTKDatasetToFile(outputSP, outVTKFileName); reader->Delete(); resample->Delete(); outputSP->Delete(); transform->Delete(); } void vtkMAFVolumeResampleTest::WriteVTKDatasetToFile( vtkDataSet * outputVolumeVTKData, const char *outputFilename ) { vtkMAFSmartPointer<vtkDataSetWriter> writer; writer->SetInput(outputVolumeVTKData); string fullPathOutputFilename; fullPathOutputFilename.append(MAF_DATA_ROOT); fullPathOutputFilename.append("/Test_VolumeResample/"); fullPathOutputFilename.append(outputFilename); cout << fullPathOutputFilename; writer->SetFileName(fullPathOutputFilename.c_str()); writer->SetFileTypeToASCII(); writer->Write(); } void vtkMAFVolumeResampleTest::PrintDouble6( ostream& os, double array[6], const char *logMessage ) { if (logMessage) os << logMessage << std::endl; os << "xmin, xmax [" << array[0] << " , " << array[1] << "]" << std::endl; os << "ymin, ymax [" << array[2] << " , " << array[3] << "]" << std::endl; os << "zmin, zmax [" << array[4] << " , " << array[5] << "]" << std::endl; os << std::endl; } void vtkMAFVolumeResampleTest::PrintDouble3( ostream& os, double array[3], const char *logMessage ) { if (logMessage) os << logMessage << " [" << array[0] << " , " << array[1] << " , " << array[2] << " ]" << std::endl; os << std::endl; } void vtkMAFVolumeResampleTest::PrintInt3( ostream& os, int array[3], const char *logMessage ) { if (logMessage) os << logMessage << " [" << array[0] << " , " << array[1] << " , " << array[2] << " ]" << std::endl; os << std::endl; } void vtkMAFVolumeResampleTest::TestSetGetVolumeOrigin() { double volumeOrigin[3] = {1,2,3}; vtkMAFVolumeResample *resample = vtkMAFVolumeResample::New(); resample->SetVolumeOrigin(volumeOrigin); double checkVolumeOrigin[3] = {1,2,3}; resample->GetVolumeOrigin(checkVolumeOrigin); for (int i = 0; i < 3; i++) { CPPUNIT_ASSERT(checkVolumeOrigin[i] == volumeOrigin[i]); } resample->Delete(); } void vtkMAFVolumeResampleTest::TestSetGetVolumeAxisX() { double volumeAxisX[3] = {0,0,1}; vtkMAFVolumeResample *resample = vtkMAFVolumeResample::New(); resample->SetVolumeAxisX(volumeAxisX); double checkVolumeAxisX[3] = {0,0,1}; resample->GetVolumeAxisX(checkVolumeAxisX); for (int i = 0; i < 3; i++) { CPPUNIT_ASSERT(checkVolumeAxisX[i] == volumeAxisX[i]); } resample->Delete(); } void vtkMAFVolumeResampleTest::TestSetGetVolumeAxisY() { double volumeAxisY[3] = {0,0,1}; vtkMAFVolumeResample *resample = vtkMAFVolumeResample::New(); resample->SetVolumeAxisY(volumeAxisY); double checkVolumeAxisY[3] = {0,0,1}; resample->GetVolumeAxisY(checkVolumeAxisY); for (int i = 0; i < 3; i++) { CPPUNIT_ASSERT(checkVolumeAxisY[i] == volumeAxisY[i]); } resample->Delete(); } void vtkMAFVolumeResampleTest::TestSetGetWindow() { double window = 10; vtkMAFVolumeResample *resample = vtkMAFVolumeResample::New(); resample->SetWindow(window); double checkWindow = 10; resample->GetWindow(); CPPUNIT_ASSERT(checkWindow == window); resample->Delete(); } void vtkMAFVolumeResampleTest::TestSetGetLevel() { double level = 10; vtkMAFVolumeResample *resample = vtkMAFVolumeResample::New(); resample->SetLevel(level); double checkLevel = 10; resample->GetLevel(); CPPUNIT_ASSERT(checkLevel == level); resample->Delete(); }
#include <cppunit/config/SourcePrefix.h> #include "vtkMAFVolumeResampleTest.h" #include "vtkMAFSmartPointer.h" #include "vtkMAFVolumeResample.h" #include "vtkDataSet.h" #include "vtkStructuredPoints.h" #include "vtkRectilinearGridReader.h" #include "vtkRectilinearGrid.h" #include "vtkDataArray.h" #include "vtkPointData.h" #include "vtkDataSetWriter.h" using namespace std; void vtkMAFVolumeResampleTest::TestResample() { const char *inFileName = "volumeRG_dim_10_10_10_bounds_1_10_1_10_1_10.vtk"; const char *outVTKFileName= "resampled_volumeRG_dim_10_10_10_bounds_1_10_1_10_1_10.vtk"; TestResampleInternal(inFileName, outVTKFileName ); inFileName = "volumeRG_dim_10_10_10_bounds_m5_5_m5_5_m5_5.vtk"; outVTKFileName= "resampled_volumeRG_dim_10_10_10_bounds_m5_5_m5_5_m5_5.vtk"; TestResampleInternal(inFileName, outVTKFileName ); } void vtkMAFVolumeResampleTest::TestResampleInternal( const char *inFileName , const char *outVTKFileName ) { std::string absPathFilename=MAF_DATA_ROOT; absPathFilename += "/Test_VolumeResample/"; absPathFilename.append(inFileName); vtkRectilinearGridReader *reader = vtkRectilinearGridReader::New(); reader->SetFileName(absPathFilename.c_str()); reader->Update(); double inputDataSpacing[3]; vtkRectilinearGrid *rg = reader->GetOutput(); inputDataSpacing[0] = rg->GetXCoordinates()->GetComponent(1,0)-rg->GetXCoordinates()->GetComponent(0,0); inputDataSpacing[1] = rg->GetYCoordinates()->GetComponent(1,0)-rg->GetYCoordinates()->GetComponent(0,0); inputDataSpacing[2] = rg->GetZCoordinates()->GetComponent(1,0)-rg->GetZCoordinates()->GetComponent(0,0); PrintDouble3(cout, inputDataSpacing, "inputDataSpacing"); double inputDataOrigin[3]; inputDataOrigin[0] = rg->GetXCoordinates()->GetComponent(0,0); inputDataOrigin[1] = rg->GetYCoordinates()->GetComponent(0,0); inputDataOrigin[2] = rg->GetZCoordinates()->GetComponent(0,0); PrintDouble3(cout, inputDataOrigin, "inputDataOrigin"); vtkMAFVolumeResample *resample = vtkMAFVolumeResample::New(); resample->SetZeroValue(0); resample->SetInput(reader->GetOutput()); resample->SetVolumeOrigin(inputDataOrigin); PrintDouble3(cout, inputDataOrigin, "inputDataOrigin"); vtkTransform *transform = vtkTransform::New(); transform->Identity(); transform->Update(); double xAxis[3] = {0,0,0}; for (int i = 0; i < 3; i++) { xAxis[i] = transform->GetMatrix()->GetElement(i, 0); } resample->SetVolumeAxisX(xAxis); PrintDouble3(cout, xAxis, "xAxis"); double yAxis[3] = {0,0,0}; for (int i = 0; i < 3; i++) { yAxis[i] = transform->GetMatrix()->GetElement(i, 1); } resample->SetVolumeAxisY(yAxis); PrintDouble3(cout, yAxis, "yAxis"); double sr[2]; rg->GetScalarRange(sr); double w = sr[1] - sr[0]; double l = (sr[1] + sr[0]) * 0.5; resample->SetWindow(w); resample->SetLevel(l); resample->AutoSpacingOff(); vtkStructuredPoints *outputSP = vtkStructuredPoints::New(); outputSP->SetSource(NULL); outputSP->SetOrigin(inputDataOrigin); outputSP->SetSpacing(inputDataSpacing); outputSP->SetScalarType(rg->GetPointData()->GetScalars()->GetDataType()); double resamplingBoxBounds[6]; rg->GetBounds(resamplingBoxBounds); int outputSPExtent[6]; outputSPExtent[0] = 0; outputSPExtent[1] = (resamplingBoxBounds[1] - resamplingBoxBounds[0]) / inputDataSpacing[0]; outputSPExtent[2] = 0; outputSPExtent[3] = (resamplingBoxBounds[3] - resamplingBoxBounds[2]) / inputDataSpacing[1]; outputSPExtent[4] = 0; outputSPExtent[5] = (resamplingBoxBounds[5] - resamplingBoxBounds[4]) / inputDataSpacing[2]; outputSP->SetExtent(outputSPExtent); outputSP->SetUpdateExtent(outputSPExtent); outputSP->Modified(); resample->SetOutput(outputSP); resample->Update(); double inBounds[6] = {0,0,0}; rg->GetBounds(inBounds); double checkBounds[6]; outputSP->GetBounds(checkBounds); CPPUNIT_ASSERT(checkBounds[0]==inBounds[0] && checkBounds[1]==inBounds[1] && checkBounds[2]==inBounds[2]); CPPUNIT_ASSERT(checkBounds[3]==inBounds[3] && checkBounds[4]==inBounds[4] && checkBounds[5]==inBounds[5]); WriteVTKDatasetToFile(outputSP, outVTKFileName); reader->Delete(); resample->Delete(); outputSP->Delete(); transform->Delete(); } void vtkMAFVolumeResampleTest::WriteVTKDatasetToFile( vtkDataSet * outputVolumeVTKData, const char *outputFilename ) { vtkMAFSmartPointer<vtkDataSetWriter> writer; writer->SetInput(outputVolumeVTKData); string fullPathOutputFilename; fullPathOutputFilename.append(MAF_DATA_ROOT); fullPathOutputFilename.append("/Test_VolumeResample/"); fullPathOutputFilename.append(outputFilename); cout << fullPathOutputFilename; writer->SetFileName(fullPathOutputFilename.c_str()); writer->SetFileTypeToASCII(); writer->Write(); } void vtkMAFVolumeResampleTest::PrintDouble6( ostream& os, double array[6], const char *logMessage ) { if (logMessage) os << logMessage << std::endl; os << "xmin, xmax [" << array[0] << " , " << array[1] << "]" << std::endl; os << "ymin, ymax [" << array[2] << " , " << array[3] << "]" << std::endl; os << "zmin, zmax [" << array[4] << " , " << array[5] << "]" << std::endl; os << std::endl; } void vtkMAFVolumeResampleTest::PrintDouble3( ostream& os, double array[3], const char *logMessage ) { if (logMessage) os << logMessage << " [" << array[0] << " , " << array[1] << " , " << array[2] << " ]" << std::endl; os << std::endl; } void vtkMAFVolumeResampleTest::PrintInt3( ostream& os, int array[3], const char *logMessage ) { if (logMessage) os << logMessage << " [" << array[0] << " , " << array[1] << " , " << array[2] << " ]" << std::endl; os << std::endl; } void vtkMAFVolumeResampleTest::TestSetGetVolumeOrigin() { double volumeOrigin[3] = {1,2,3}; vtkMAFVolumeResample *resample = vtkMAFVolumeResample::New(); resample->SetVolumeOrigin(volumeOrigin); double checkVolum
== volumeOrigin[i]); } resample->Delete(); } void vtkMAFVolumeResampleTest::TestSetGetVolumeAxisX() { double volumeAxisX[3] = {0,0,1}; vtkMAFVolumeResample *resample = vtkMAFVolumeResample::New(); resample->SetVolumeAxisX(volumeAxisX); double checkVolumeAxisX[3] = {0,0,1}; resample->GetVolumeAxisX(checkVolumeAxisX); for (int i = 0; i < 3; i++) { CPPUNIT_ASSERT(checkVolumeAxisX[i] == volumeAxisX[i]); } resample->Delete(); } void vtkMAFVolumeResampleTest::TestSetGetVolumeAxisY() { double volumeAxisY[3] = {0,0,1}; vtkMAFVolumeResample *resample = vtkMAFVolumeResample::New(); resample->SetVolumeAxisY(volumeAxisY); double checkVolumeAxisY[3] = {0,0,1}; resample->GetVolumeAxisY(checkVolumeAxisY); for (int i = 0; i < 3; i++) { CPPUNIT_ASSERT(checkVolumeAxisY[i] == volumeAxisY[i]); } resample->Delete(); } void vtkMAFVolumeResampleTest::TestSetGetWindow() { double window = 10; vtkMAFVolumeResample *resample = vtkMAFVolumeResample::New(); resample->SetWindow(window); double checkWindow = 10; resample->GetWindow(); CPPUNIT_ASSERT(checkWindow == window); resample->Delete(); } void vtkMAFVolumeResampleTest::TestSetGetLevel() { double level = 10; vtkMAFVolumeResample *resample = vtkMAFVolumeResample::New(); resample->SetLevel(level); double checkLevel = 10; resample->GetLevel(); CPPUNIT_ASSERT(checkLevel == level); resample->Delete(); }
eOrigin[3] = {1,2,3}; resample->GetVolumeOrigin(checkVolumeOrigin); for (int i = 0; i < 3; i++) { CPPUNIT_ASSERT(checkVolumeOrigin[i]
function_block-random_span
[ { "content": "class vtkTransform;\n", "file_path": "Interaction/mafCameraTransform.h", "rank": 0, "score": 127481.85520661279 }, { "content": "class vtkTransform;\n", "file_path": "Testing/Base/mafTransformFrameTest.h", "rank": 1, "score": 124946.89338589914 }, { "content...
C++
Libraries/VtkVgQtSceneUtil/vtkVgCoordinateTransform.cxx
PinkDiamond1/vivia
70f7fbed4b33b14d34de35c69b2b14df3514d720
#include "vtkVgCoordinateTransform.h" #include <vtkVgAdapt.h> #include <vtkMatrix4x4.h> #include <vtkObjectFactory.h> #include <vgl/vgl_homg_point_2d.h> #include <vgl/algo/vgl_h_matrix_2d.h> #include <vgl/algo/vgl_h_matrix_2d_compute_linear.h> vtkStandardNewMacro(vtkVgCoordinateTransform); vtkVgCoordinateTransform::vtkVgCoordinateTransform() { } vtkVgCoordinateTransform::~vtkVgCoordinateTransform() { } void vtkVgCoordinateTransform::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } void vtkVgCoordinateTransform::SetFromPoints(double pt1[], double pt2[], double pt3[], double pt4[]) { this->FromPoint[0][0] = pt1[0]; this->FromPoint[0][1] = pt1[1]; this->FromPoint[1][0] = pt2[0]; this->FromPoint[1][1] = pt2[1]; this->FromPoint[2][0] = pt3[0]; this->FromPoint[2][1] = pt3[1]; this->FromPoint[3][0] = pt4[0]; this->FromPoint[3][1] = pt4[1]; } void vtkVgCoordinateTransform::SetFromPoints(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { this->FromPoint[0][0] = x1; this->FromPoint[0][1] = y1; this->FromPoint[1][0] = x2; this->FromPoint[1][1] = y2; this->FromPoint[2][0] = x3; this->FromPoint[2][1] = y3; this->FromPoint[3][0] = x4; this->FromPoint[3][1] = y4; } void vtkVgCoordinateTransform::SetToPoints(double pt1[], double pt2[], double pt3[], double pt4[]) { this->ToPoint[0][0] = pt1[0]; this->ToPoint[0][1] = pt1[1]; this->ToPoint[1][0] = pt2[0]; this->ToPoint[1][1] = pt2[1]; this->ToPoint[2][0] = pt3[0]; this->ToPoint[2][1] = pt3[1]; this->ToPoint[3][0] = pt4[0]; this->ToPoint[3][1] = pt4[1]; } void vtkVgCoordinateTransform::SetToPoints(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { this->ToPoint[0][0] = x1; this->ToPoint[0][1] = y1; this->ToPoint[1][0] = x2; this->ToPoint[1][1] = y2; this->ToPoint[2][0] = x3; this->ToPoint[2][1] = y3; this->ToPoint[3][0] = x4; this->ToPoint[3][1] = y4; } vtkSmartPointer<vtkMatrix4x4> vtkVgCoordinateTransform::GetHomographyMatrix() { std::vector<vgl_homg_point_2d<double> > fromPoints; std::vector<vgl_homg_point_2d<double> > toPoints; for (int i = 0; i < 4; ++i) { vgl_homg_point_2d<double> vglPt2d(this->FromPoint[i][0], this->FromPoint[i][1], 1); fromPoints.push_back(vglPt2d); } for (int i = 0; i < 4; ++i) { vgl_homg_point_2d<double> vglPt2d(this->ToPoint[i][0], this->ToPoint[i][1], 1); toPoints.push_back(vglPt2d); } vgl_h_matrix_2d_compute_linear algo; vgl_h_matrix_2d<double> homography; bool success = algo.compute(fromPoints, toPoints, homography); if (success) { return vtkVgAdapt(homography.get_matrix()); } else { return 0; } }
#include "vtkVgCoordinateTransform.h" #include <vtkVgAdapt.h> #include <vtkMatrix4x4.h> #include <vtkObjectFactory.h> #include <vgl/vgl_homg_point_2d.h> #include <vgl/algo/vgl_h_matrix_2d.h> #include <vgl/algo/vgl_h_matrix_2d_compute_linear.h> vtkStandardNewMacro(vtkVgCoordinateTransform); vtkVgCoordinateTransform::vtkVgCoordinateTransform() { } vtkVgCoordinateTransform::~vtkVgCoordinateTransform() { } void vtkVgCoordinateTransform::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } void vtkVgCoordinateTransform::SetFromPoints(double pt1[], double pt2[], double pt3[], double pt4[]) { this->FromPoint[0][0] = pt1[0]; this->FromPoint[0][1] = pt1[1]; this->FromPoint[1][0] = pt2[0]; this->FromPoint[1][1] = pt2[1]; this->FromPoint[2][0] = pt3[0]; this->FromPoint[2][1] = pt3[1]; this->FromPoint[3][0] = pt4[0]; this->FromPoint[3][1] = pt4[1]; } void vtkVgCoordinateTransform::SetFromPoints(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) { this->FromPoint[0][0] = x1; this->FromPoint[0][1] = y1; this->FromPoint[1][0] = x2; this->FromPoint[1][1] = y2; this->FromPoint[2][0] = x3; this->FromPoint[2][1] = y3; this->FromPoint[3][0] = x4; this->FromPoint[3][1] = y4; } void vtkVgCoordinateTransform::SetToPoints(double pt1[], double pt2[], double pt3[], double pt4[]) { this->ToPoint[0][0] = pt1[0]; this->ToPoint[0][1] = pt1[1]; this->ToPoint[1][0] = pt2[0]; this->ToPoint[1][1] = pt2[1]; this->ToPoint[2][0] = pt3[0]; this->ToPoint[2][1] = pt3[1]; this->ToPoint[3][0] = pt4[0]; this->ToPoint[3][1] = pt4[1]; } void vtkVgCoordinateTransform::SetToPoints(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) {
vtkSmartPointer<vtkMatrix4x4> vtkVgCoordinateTransform::GetHomographyMatrix() { std::vector<vgl_homg_point_2d<double> > fromPoints; std::vector<vgl_homg_point_2d<double> > toPoints; for (int i = 0; i < 4; ++i) { vgl_homg_point_2d<double> vglPt2d(this->FromPoint[i][0], this->FromPoint[i][1], 1); fromPoints.push_back(vglPt2d); } for (int i = 0; i < 4; ++i) { vgl_homg_point_2d<double> vglPt2d(this->ToPoint[i][0], this->ToPoint[i][1], 1); toPoints.push_back(vglPt2d); } vgl_h_matrix_2d_compute_linear algo; vgl_h_matrix_2d<double> homography; bool success = algo.compute(fromPoints, toPoints, homography); if (success) { return vtkVgAdapt(homography.get_matrix()); } else { return 0; } }
this->ToPoint[0][0] = x1; this->ToPoint[0][1] = y1; this->ToPoint[1][0] = x2; this->ToPoint[1][1] = y2; this->ToPoint[2][0] = x3; this->ToPoint[2][1] = y3; this->ToPoint[3][0] = x4; this->ToPoint[3][1] = y4; }
function_block-function_prefix_line
[ { "content": "class QT_TESTINGSUPPORT_EXPORT pqQteDoubleSliderEventPlayer :\n\n public pqWidgetEventPlayer\n\n{\n\n Q_OBJECT\n\n\n\npublic:\n\n pqQteDoubleSliderEventPlayer(QObject* p = 0);\n\n\n\n bool playEvent(QObject* Object, const QString& Command, const QString& Arguments, bool& Error);\n\n\n\nprivate...
C++
kraken/resources/home/dnanexus/jellyfish-1.1.11/jellyfish/stats_main_cmdline.hpp
transcript/DNAnexus_apps
12c2ba6f57b805a9fcf6e1da4f9d64394ef72256
#ifndef __STATS_ARGS_HPP__ #define __STATS_ARGS_HPP__ #include <jellyfish/yaggo.hpp> class stats_args { public: bool recompute_flag; uint64_t lower_count_arg; bool lower_count_given; uint64_t upper_count_arg; bool upper_count_given; bool verbose_flag; const char * output_arg; bool output_given; const char * db_arg; enum { USAGE_OPT = 1000, FULL_HELP_OPT }; stats_args() : recompute_flag(false), lower_count_arg(), lower_count_given(false), upper_count_arg(), upper_count_given(false), verbose_flag(false), output_arg(""), output_given(false) { } stats_args(int argc, char* argv[]) : recompute_flag(false), lower_count_arg(), lower_count_given(false), upper_count_arg(), upper_count_given(false), verbose_flag(false), output_arg(""), output_given(false) { parse(argc, argv); } void parse(int argc, char* argv[]) { static struct option long_options[] = { {"recompute", 0, 0, 'r'}, {"lower-count", 1, 0, 'L'}, {"upper-count", 1, 0, 'U'}, {"verbose", 0, 0, 'v'}, {"output", 1, 0, 'o'}, {"help", 0, 0, 'h'}, {"full-help", 0, 0, FULL_HELP_OPT}, {"usage", 0, 0, USAGE_OPT}, {"version", 0, 0, 'V'}, {0, 0, 0, 0} }; static const char *short_options = "hVrL:U:vo:"; std::string err; #define CHECK_ERR(type,val,which) if(!err.empty()) { std::cerr << "Invalid " #type " '" << val << "' for [" which "]: " << err << "\n"; exit(1); } while(true) { int index = -1; int c = getopt_long(argc, argv, short_options, long_options, &index); if(c == -1) break; switch(c) { case ':': std::cerr << "Missing required argument for " << (index == -1 ? std::string(1, (char)optopt) : std::string(long_options[index].name)) << std::endl; exit(1); case 'h': std::cout << usage() << "\n\n" << help() << std::endl; exit(0); case USAGE_OPT: std::cout << usage() << "\nUse --help for more information." << std::endl; exit(0); case 'V': print_version(); exit(0); case '?': std::cerr << "Use --usage or --help for some help\n"; exit(1); case FULL_HELP_OPT: std::cout << usage() << "\n\n" << help() << "\n\n" << hidden() << std::endl; exit(0); case 'r': recompute_flag = true; break; case 'L': lower_count_given = true; lower_count_arg = yaggo::conv_uint<uint64_t>((const char *)optarg, err, false); CHECK_ERR(uint64_t, optarg, "-L, --lower-count=uint64") break; case 'U': upper_count_given = true; upper_count_arg = yaggo::conv_uint<uint64_t>((const char *)optarg, err, false); CHECK_ERR(uint64_t, optarg, "-U, --upper-count=uint64") break; case 'v': verbose_flag = true; break; case 'o': output_given = true; output_arg = optarg; break; } } if(argc - optind != 1) error("Requires exactly 1 argument."); db_arg = argv[optind]; ++optind; } #define stats_args_USAGE "Usage: jellyfish stats [options] db:path" const char * usage() const { return stats_args_USAGE; } void error(const char *msg) { std::cerr << "Error: " << msg << "\n" << usage() << "\nUse --help for more information" << std::endl; exit(1); } #define stats_args_HELP "Statistics\n\nDisplay some statistics about the k-mers in the hash:\n" \ "\n" \ "Unique: Number of k-mers which occur only once.\n" \ "Distinct: Number of k-mers, not counting multiplicity.\n" \ "Total: Number of k-mers, including multiplicity.\n" \ "Max_count: Maximum number of occurrence of a k-mer.\n\n" \ "Options (default value in (), *required):\n" \ " -L, --lower-count=uint64 Don't consider k-mer with count < lower-count\n" \ " -U, --upper-count=uint64 Don't consider k-mer with count > upper-count\n" \ " -v, --verbose Verbose (false)\n" \ " -o, --output=string Output file\n" \ " --usage Usage\n" \ " -h, --help This message\n" \ " --full-help Detailed help\n" \ " -V, --version Version" const char * help() const { return stats_args_HELP; } #define stats_args_HIDDEN "Hidden options:\n" \ " -r, --recompute Recompute (false)" const char * hidden() const { return stats_args_HIDDEN; } void print_version(std::ostream &os = std::cout) const { #ifndef PACKAGE_VERSION #define PACKAGE_VERSION "0.0.0" #endif os << PACKAGE_VERSION << "\n"; } void dump(std::ostream &os = std::cout) { os << "recompute_flag:" << recompute_flag << "\n"; os << "lower_count_given:" << lower_count_given << " lower_count_arg:" << lower_count_arg << "\n"; os << "upper_count_given:" << upper_count_given << " upper_count_arg:" << upper_count_arg << "\n"; os << "verbose_flag:" << verbose_flag << "\n"; os << "output_given:" << output_given << " output_arg:" << output_arg << "\n"; os << "db_arg:" << db_arg << "\n"; } private: }; #endif
#ifndef __STATS_ARGS_HPP__ #define __STATS_ARGS_HPP__ #include <jellyfish/yaggo.hpp> class stats_args { public: bool recompute_flag; uint64_t lower_count_arg; bool lower_count_given; uint64_t upper_count_arg; bool upper_count_given; bool verbose_flag; const char * output_arg; bool output_given; const char * db_arg; enum { USAGE_OPT = 1000, FULL_HELP_OPT }; stats_args() : recompute_flag(false), lower_count_arg(), lower_count_given(false), upper_count_arg(), upper_count_given(false), verbose_flag(false), output_arg(""), output_given(false) { } stats_args(int argc, char* argv[]) : recompute_flag(false), lower_count_arg(), lower_count_given(false), upper_count_arg(), upper_count_given(false), verbose_flag(false), output_arg(""), output_given(false) { parse(argc, argv); } void parse(int argc, char* argv[]) { static struct option long_options[] = { {"recompute", 0, 0, 'r'}, {"lower-count", 1, 0, 'L'}, {"upper-count", 1, 0, 'U'}, {"verbose", 0, 0, 'v'}, {"output", 1, 0, 'o'}, {"help", 0, 0, 'h'}, {"full-help", 0, 0, FULL_HELP_OPT}, {"usage", 0, 0, USAGE_OPT}, {"version", 0, 0, 'V'}, {0, 0, 0, 0} }; static const char *short_options = "hVrL:U:vo:"; std::string err; #define CHECK_ERR(type,val,which) if(!err.empty()) { std::cerr << "Invalid " #type " '" << val << "' for [" which "]: " << err << "\n"; exit(1); } while(true) { int index = -1; int c = getopt_long(argc, argv, short_options, long_options, &index); if(c == -1) break; switch(c) { case ':': std::cerr << "Missing required argument for " << (index == -1 ? std::string(1, (char)optopt) : std::string(long_options[index].name)) << std::endl; exit(1); case 'h': std::cout << usage() << "\n\n" << help() << std::endl; exit(0); case USAGE_OPT: std::cout << usage() << "\nUse --help for more information." << std::endl; exit(0); case 'V': print_version(); exit(0); case '?': std::cerr << "Use --usage or --help for some help\n"; exit(1); case FULL_HELP_OPT: std::cout << usage() << "\n\n" << help() << "\n\n" << hidden() << std::endl; exit(0); case 'r': recompute_flag = true; break; case 'L': lower_count_given = true; lower_count_arg = yaggo::conv_uint<uint64_t>((const char *)optarg, err, false); CHECK_ERR(uint64_t, optarg, "-L, --lower-count=uint64") break; case 'U': upper_count_given = true; upper_count_arg = yaggo::conv_uint<uint64_t>((const char *)optarg, err, false); CHECK_ERR(uint64_t, optarg, "-U, --upper-count=uint64") break; case 'v': verbose_flag = true; break; case 'o': output_given = true; output_arg = optarg; break; } } if(argc - optind != 1) error("Requires exactly 1 argument."); db_arg = argv[optind]; ++optind; } #define stats_args_USAGE "Usage: jellyfish stats [options] db:path" const char * usage() const { return stats_args_USAGE; } void error(const char *msg) { std::cerr << "Error: " << msg << "\n" << usage() << "\nUse --help for more information" << std::endl; exit(1); } #define stats_args_HELP "Statistics\n\nDisplay some statistics about the k-mers in the hash:\n" \ "\n" \ "Unique: Number of k-mers which occur only once.\n" \ "Distinct: Number of k-mers, not counting multiplicity.\n" \ "Total: Number of k-mers, including multiplicity.\n" \ "Max_count: Maximum number of occurrence of a k-mer.\n\n" \ "Options (default value in (), *required):\n" \ " -L, --lower-count=uint64 Don't consider k-mer with count < lower-count\n" \ " -U, --upper-count=uint64 Don't consider k-mer with count > upper-count\n" \ " -v, --verbose Verbose (false)\n" \ " -o, --output=string Output file\n" \ " --usage Usage\n" \ " -h, --help This message\n" \ " --full-help Detailed help\n" \ " -V, --version Version" const char * help() const { return stats_args_HELP; } #define stats_args_HIDDEN "Hidden options:\n" \ " -r, --recompute Recompute (false)" const char * hidden() const { return stats_args_HIDDEN; } void print_version(std::ostream &os = std::cout) const { #ifndef PACKAGE_VERSION #define PACKAGE_VERSION "0.0.0" #endif os << PACKAGE_VERSION << "\n"; }
private: }; #endif
void dump(std::ostream &os = std::cout) { os << "recompute_flag:" << recompute_flag << "\n"; os << "lower_count_given:" << lower_count_given << " lower_count_arg:" << lower_count_arg << "\n"; os << "upper_count_given:" << upper_count_given << " upper_count_arg:" << upper_count_arg << "\n"; os << "verbose_flag:" << verbose_flag << "\n"; os << "output_given:" << output_given << " output_arg:" << output_arg << "\n"; os << "db_arg:" << db_arg << "\n"; }
function_block-full_function
[ { "content": "struct tuple_size<GTEST_1_TUPLE_(T)> { static const int value = 1; };\n\n\n\ntemplate <GTEST_2_TYPENAMES_(T)>\n", "file_path": "kraken/resources/home/dnanexus/jellyfish-1.1.11/unit_tests/gtest/include/gtest/internal/gtest-tuple.h", "rank": 0, "score": 416406.8253525696 }, { "co...
C++
sources/dansandu/ballotin/logging.cpp
dansandu/ballotin
e92aac53153ca85759bc412a86937b28c5dbfc4c
#include "dansandu/ballotin/logging.hpp" #include "dansandu/ballotin/date_time.hpp" #include "dansandu/ballotin/exception.hpp" #include "dansandu/ballotin/file_system.hpp" #include "dansandu/ballotin/string.hpp" #include <algorithm> #include <fstream> using dansandu::ballotin::date_time::getDateTime; using dansandu::ballotin::file_system::writeToStandardError; using dansandu::ballotin::file_system::writeToStandardOutput; namespace dansandu::ballotin::logging { Logger& Logger::globalInstance() { static auto logger = Logger{}; return logger; } Logger::Logger() : level_{Level::debug} { } void Logger::addHandler(std::string name, const Level level, std::function<void(const LogEntry&)> handler) { const auto lock = std::lock_guard<std::mutex>{mutex_}; if (std::find_if(handlers_.cbegin(), handlers_.cend(), [&name](const auto& handler) { return handler.name == name; }) == handlers_.cend()) { handlers_.push_back({std::move(name), level, std::move(handler)}); } else { THROW(std::logic_error, "the handler named '", name, "' is already registered"); } } void Logger::removeHandler(const std::string_view name) { const auto lock = std::lock_guard<std::mutex>{mutex_}; if (const auto position = std::find_if(handlers_.cbegin(), handlers_.cend(), [name](const auto& handler) { return handler.name == name; }); position != handlers_.cend()) { handlers_.erase(position); } } void Logger::setLevel(const Level level) { level_.store(level); } Level Logger::getLevel() const { return level_.load(); } void Logger::log(const Level level, const char* const function, const char* const file, const int line, const std::string_view message) const { if (level <= getLevel()) { const auto timestamp = getDateTime(); const auto logEntry = LogEntry{timestamp, level, std::this_thread::get_id(), function, file, line, message}; const auto lock = std::lock_guard<std::mutex>{mutex_}; for (const auto& handler : handlers_) { if (logEntry.level <= handler.level) { handler.callback(logEntry); } } } } void Logger::log(const Level level, const char* const function, const char* const file, const int line, const std::function<std::string()>& messageSupplier) const { if (level <= getLevel()) { const auto timestamp = getDateTime(); const auto message = messageSupplier(); const auto logEntry = LogEntry{timestamp, level, std::this_thread::get_id(), function, file, line, message}; const auto lock = std::lock_guard<std::mutex>{mutex_}; for (const auto& handler : handlers_) { if (logEntry.level <= handler.level) { handler.callback(logEntry); } } } } void standardOutputHandler(const LogEntry& logEntry) { auto stream = std::stringstream{}; stream << logEntry.timestamp << " " << levelToString(logEntry.level) << " " << logEntry.threadId << " " << logEntry.file << ":" << logEntry.line << " " << logEntry.message << std::endl; const auto string = stream.str(); if (logEntry.level <= Level::warn) { writeToStandardOutput(string); } else { writeToStandardError(string); } } struct UnitTestsHandlerImplementation { static void deleter(void* pointer) { delete static_cast<UnitTestsHandlerImplementation*>(pointer); } UnitTestsHandlerImplementation(const char* const filePath) : logFile{filePath, std::ios_base::out | std::ios_base::app} { } std::ofstream logFile; std::mutex mutex; }; UnitTestsHandler::UnitTestsHandler(const char* const filePath) : implementation_{new UnitTestsHandlerImplementation{filePath}, UnitTestsHandlerImplementation::deleter} { } void UnitTestsHandler::operator()(const LogEntry& logEntry) { auto stream = std::stringstream{}; stream << logEntry.timestamp << " " << levelToString(logEntry.level) << " " << logEntry.threadId << " " << logEntry.file << ":" << logEntry.line << " " << logEntry.message << std::endl; const auto casted = static_cast<UnitTestsHandlerImplementation*>(implementation_.get()); const auto lock = std::lock_guard<std::mutex>{casted->mutex}; casted->logFile << stream.rdbuf(); } }
#include "dansandu/ballotin/logging.hpp" #include "dansandu/ballotin/date_time.hpp" #include "dansandu/ballotin/exception.hpp" #include "dansandu/ballotin/file_system.hpp" #include "dansandu/ballotin/string.hpp" #include <algorithm> #include <fstream> using dansandu::ballotin::date_time::getDateTime; using dansandu::ballotin::file_system::writeToStandardError; using dansandu::ballotin::file_system::writeToStandardOutput; namespace dansandu::ballotin::logging { Logger& Logger::globalInstance() { static auto logger = Logger{}; return logger; } Logger::Logger() : level_{Level::debug} { } void Logger::addHandler(std::string name, const Level level, std::function<void(const LogEntry&)> handler) { const auto lock = std::lock_guard<std::mutex>{mutex_}; if (std::find_if(handlers_.cbegin(), handlers_.cend(), [&name](const auto& handler) { return handler.name == name; }) == handlers_.cend()) { handlers_.push_back({std::move(name), level, std::move(handler)}); } else { THROW(std::logic_error, "the handler named '", name, "' is already registered"); } } void Logger::removeHandler(const std::string_view name) { const auto lock = std::lock_guard<std::mutex>{mutex_}; if (const auto position = std::find_if(handlers_.cbegin(), handlers_.cend(), [name](const auto& handler) { return handler.name == name; }); position != handlers_.cend()) { handlers_.erase(position); } } void Logger::setLevel(const Level level) { level_.store(level); } Level Logger::getLevel() const { return level_.load(); } void Logger::log(const Level level, const char* const function, const char* const file, const int line, const std::string_view message) const { if (level <= getLevel()) { const auto timestamp = getDateTime(); const auto logEntry = LogEntry{timestamp, level, std::this_thread::get_id(), function, file, line, message}; const auto lock = std::lock_guard<std::mutex>{mutex_}; for (const auto& handler : handlers_) { if (logEntry.level <= handler.level) { handler.callback(logEntry); } } } }
void standardOutputHandler(const LogEntry& logEntry) { auto stream = std::stringstream{}; stream << logEntry.timestamp << " " << levelToString(logEntry.level) << " " << logEntry.threadId << " " << logEntry.file << ":" << logEntry.line << " " << logEntry.message << std::endl; const auto string = stream.str(); if (logEntry.level <= Level::warn) { writeToStandardOutput(string); } else { writeToStandardError(string); } } struct UnitTestsHandlerImplementation { static void deleter(void* pointer) { delete static_cast<UnitTestsHandlerImplementation*>(pointer); } UnitTestsHandlerImplementation(const char* const filePath) : logFile{filePath, std::ios_base::out | std::ios_base::app} { } std::ofstream logFile; std::mutex mutex; }; UnitTestsHandler::UnitTestsHandler(const char* const filePath) : implementation_{new UnitTestsHandlerImplementation{filePath}, UnitTestsHandlerImplementation::deleter} { } void UnitTestsHandler::operator()(const LogEntry& logEntry) { auto stream = std::stringstream{}; stream << logEntry.timestamp << " " << levelToString(logEntry.level) << " " << logEntry.threadId << " " << logEntry.file << ":" << logEntry.line << " " << logEntry.message << std::endl; const auto casted = static_cast<UnitTestsHandlerImplementation*>(implementation_.get()); const auto lock = std::lock_guard<std::mutex>{casted->mutex}; casted->logFile << stream.rdbuf(); } }
void Logger::log(const Level level, const char* const function, const char* const file, const int line, const std::function<std::string()>& messageSupplier) const { if (level <= getLevel()) { const auto timestamp = getDateTime(); const auto message = messageSupplier(); const auto logEntry = LogEntry{timestamp, level, std::this_thread::get_id(), function, file, line, message}; const auto lock = std::lock_guard<std::mutex>{mutex_}; for (const auto& handler : handlers_) { if (logEntry.level <= handler.level) { handler.callback(logEntry); } } } }
function_block-full_function
[ { "content": "enum class Level\n\n{\n\n none,\n\n error,\n\n warn,\n\n info,\n\n debug\n\n};\n\n\n\nconstexpr bool operator<(const Level left, const Level right)\n\n{\n\n return static_cast<int>(left) < static_cast<int>(right);\n\n}\n\n\n\nconstexpr bool operator>(const Level left, const Level...
C++
external/opengl/libagl2/src/texture.cpp
gordonjohnpatrick/XobotOS
888ed3b8cc8d8e0a54b1858bfa5a3572545f4d2f
#include "gles2context.h" #define API_ENTRY #define CALL_GL_API(NAME,...) LOGD("?"#NAME); assert(0); #define CALL_GL_API_RETURN(NAME,...) LOGD("?"#NAME); assert(0); return 0; static inline GGLTexture * AllocTexture() { GGLTexture * tex = (GGLTexture *)calloc(1, sizeof(GGLTexture)); tex->minFilter = GGLTexture::GGL_LINEAR; tex->magFilter = GGLTexture::GGL_LINEAR; return tex; } void GLES2Context::InitializeTextures() { tex.textures = std::map<GLuint, GGLTexture *>(); tex.tex2D = AllocTexture(); tex.textures[GL_TEXTURE_2D] = tex.tex2D; tex.texCube = AllocTexture(); tex.textures[GL_TEXTURE_CUBE_MAP] = tex.texCube; for (unsigned i = 0; i < GGL_MAXCOMBINEDTEXTUREIMAGEUNITS; i++) { tex.tmus[i] = NULL; tex.sampler2tmu[i] = NULL; } tex.active = 0; tex.free = max(GL_TEXTURE_2D, GL_TEXTURE_CUBE_MAP) + 1; tex.tex2D->format = GGL_PIXEL_FORMAT_RGBA_8888; tex.tex2D->type = GL_TEXTURE_2D; tex.tex2D->levelCount = 1; tex.tex2D->wrapS = tex.tex2D->wrapT = GGLTexture::GGL_REPEAT; tex.tex2D->minFilter = tex.tex2D->magFilter = GGLTexture::GGL_NEAREST; tex.tex2D->width = tex.tex2D->height = 1; tex.tex2D->levels = malloc(4); *(unsigned *)tex.tex2D->levels = 0xff000000; tex.texCube->format = GGL_PIXEL_FORMAT_RGBA_8888; tex.texCube->type = GL_TEXTURE_CUBE_MAP; tex.texCube->levelCount = 1; tex.texCube->wrapS = tex.texCube->wrapT = GGLTexture::GGL_REPEAT; tex.texCube->minFilter = tex.texCube->magFilter = GGLTexture::GGL_NEAREST; tex.texCube->width = tex.texCube->height = 1; tex.texCube->levels = malloc(4 * 6); static unsigned texels [6] = {0xff0000ff, 0xff00ff00, 0xffff0000, 0xff00ffff, 0xffffff00, 0xffff00ff }; memcpy(tex.texCube->levels, texels, sizeof texels); tex.unpack = 4; } void GLES2Context::TextureState::UpdateSampler(GGLInterface * iface, unsigned tmu) { for (unsigned i = 0; i < GGL_MAXCOMBINEDTEXTUREIMAGEUNITS; i++) if (tmu == sampler2tmu[i]) iface->SetSampler(iface, i, tmus[tmu]); } void GLES2Context::UninitializeTextures() { for (std::map<GLuint, GGLTexture *>::iterator it = tex.textures.begin(); it != tex.textures.end(); it++) { if (!it->second) continue; free(it->second->levels); free(it->second); } } static inline void GetFormatAndBytesPerPixel(const GLenum format, unsigned * bytesPerPixel, GGLPixelFormat * texFormat) { switch (format) { case GL_ALPHA: *texFormat = GGL_PIXEL_FORMAT_A_8; *bytesPerPixel = 1; break; case GL_LUMINANCE: *texFormat = GGL_PIXEL_FORMAT_L_8; *bytesPerPixel = 1; break; case GL_LUMINANCE_ALPHA: *texFormat = GGL_PIXEL_FORMAT_LA_88; *bytesPerPixel = 2; break; case GL_RGB: *texFormat = GGL_PIXEL_FORMAT_RGB_888; *bytesPerPixel = 3; break; case GL_RGBA: *texFormat = GGL_PIXEL_FORMAT_RGBA_8888; *bytesPerPixel = 4; break; case GL_UNSIGNED_SHORT_5_6_5: *texFormat = GGL_PIXEL_FORMAT_RGB_565; *bytesPerPixel = 2; break; default: assert(0); return; } } static inline void CopyTexture(char * dst, const char * src, const unsigned bytesPerPixel, const unsigned sx, const unsigned sy, const unsigned sw, const unsigned dx, const unsigned dy, const unsigned dw, const unsigned w, const unsigned h) { const unsigned bpp = bytesPerPixel; if (dw == sw && dw == w && sx == 0 && dx == 0) memcpy(dst + dy * dw * bpp, src + sy * sw * bpp, w * h * bpp); else for (unsigned y = 0; y < h; y++) memcpy(dst + ((dy + y) * dw + dx) * bpp, src + ((sy + y) * sw + sx) * bpp, w * bpp); } void glActiveTexture(GLenum texture) { GLES2_GET_CONST_CONTEXT(ctx); unsigned index = texture - GL_TEXTURE0; assert(NELEM(ctx->tex.tmus) > index); ctx->tex.active = index; } void glBindTexture(GLenum target, GLuint texture) { GLES2_GET_CONST_CONTEXT(ctx); std::map<GLuint, GGLTexture *>::iterator it = ctx->tex.textures.find(texture); GGLTexture * tex = NULL; if (it != ctx->tex.textures.end()) { tex = it->second; if (!tex) { tex = AllocTexture(); tex->type = target; it->second = tex; } assert(target == tex->type); } else if (0 == texture) { if (GL_TEXTURE_2D == target) { tex = ctx->tex.tex2D; } else if (GL_TEXTURE_CUBE_MAP == target) { tex = ctx->tex.texCube; } else assert(0); } else { if (texture <= ctx->tex.free) ctx->tex.free = texture + 1; tex = AllocTexture(); tex->type = target; ctx->tex.textures[texture] = tex; } ctx->tex.tmus[ctx->tex.active] = tex; ctx->tex.UpdateSampler(ctx->iface, ctx->tex.active); } void API_ENTRY(glCompressedTexImage2D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid* data) { CALL_GL_API(glCompressedTexImage2D, target, level, internalformat, width, height, border, imageSize, data); } void API_ENTRY(glCompressedTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid* data) { CALL_GL_API(glCompressedTexSubImage2D, target, level, xoffset, yoffset, width, height, format, imageSize, data); } void glCopyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border) { GLES2_GET_CONST_CONTEXT(ctx); assert(0 == border); assert(0 == level); unsigned bytesPerPixel = 0; GGLPixelFormat texFormat = GGL_PIXEL_FORMAT_UNKNOWN; GetFormatAndBytesPerPixel(internalformat, &bytesPerPixel, &texFormat); assert(texFormat == ctx->rasterizer.frameSurface.format); unsigned offset = 0, size = width * height * bytesPerPixel, totalSize = size; assert(ctx->tex.tmus[ctx->tex.active]); assert(y + height <= ctx->rasterizer.frameSurface.height); assert(x + width <= ctx->rasterizer.frameSurface.width); GGLTexture & tex = *ctx->tex.tmus[ctx->tex.active]; tex.width = width; tex.height = height; tex.levelCount = 1; tex.format = texFormat; switch (target) { case GL_TEXTURE_2D: tex.levels = realloc(tex.levels, totalSize); CopyTexture((char *)tex.levels, (const char *)ctx->rasterizer.frameSurface.data, bytesPerPixel, x, y, ctx->rasterizer.frameSurface.width, 0, 0, width, width, height); break; default: assert(0); return; } ctx->tex.UpdateSampler(ctx->iface, ctx->tex.active); } void glCopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height) { GLES2_GET_CONST_CONTEXT(ctx); assert(0 == level); unsigned bytesPerPixel = 4; unsigned offset = 0, size = width * height * bytesPerPixel, totalSize = size; assert(ctx->tex.tmus[ctx->tex.active]); GGLTexture & tex = *ctx->tex.tmus[ctx->tex.active]; assert(tex.format == ctx->rasterizer.frameSurface.format); assert(GGL_PIXEL_FORMAT_RGBA_8888 == tex.format); const unsigned srcWidth = ctx->rasterizer.frameSurface.width; const unsigned srcHeight = ctx->rasterizer.frameSurface.height; assert(x >= 0 && y >= 0); assert(xoffset >= 0 && yoffset >= 0); assert(x + width <= srcWidth); assert(y + height <= srcHeight); assert(xoffset + width <= tex.width); assert(yoffset + height <= tex.height); switch (target) { case GL_TEXTURE_2D: CopyTexture((char *)tex.levels, (const char *)ctx->rasterizer.frameSurface.data, bytesPerPixel, x, y, srcWidth, xoffset, yoffset, tex.width, width, height); break; default: assert(0); return; } ctx->tex.UpdateSampler(ctx->iface, ctx->tex.active); } void glDeleteTextures(GLsizei n, const GLuint* textures) { GLES2_GET_CONST_CONTEXT(ctx); for (unsigned i = 0; i < n; i++) { std::map<GLuint, GGLTexture *>::iterator it = ctx->tex.textures.find(textures[i]); if (it == ctx->tex.textures.end()) continue; ctx->tex.free = min(ctx->tex.free, textures[i]); for (unsigned i = 0; i < GGL_MAXCOMBINEDTEXTUREIMAGEUNITS; i++) if (ctx->tex.tmus[i] == it->second) { if (GL_TEXTURE_2D == it->second->type) ctx->tex.tmus[i] = ctx->tex.tex2D; else if (GL_TEXTURE_CUBE_MAP == it->second->type) ctx->tex.tmus[i] = ctx->tex.texCube; else assert(0); ctx->tex.UpdateSampler(ctx->iface, i); } if (it->second) { free(it->second->levels); free(it->second); } ctx->tex.textures.erase(it); } } void glGenTextures(GLsizei n, GLuint* textures) { GLES2_GET_CONST_CONTEXT(ctx); for (unsigned i = 0; i < n; i++) { textures[i] = 0; for (ctx->tex.free; ctx->tex.free < 0xffffffffu; ctx->tex.free++) if (ctx->tex.textures.find(ctx->tex.free) == ctx->tex.textures.end()) { ctx->tex.textures[ctx->tex.free] = NULL; textures[i] = ctx->tex.free; ctx->tex.free++; break; } assert(textures[i]); } } void API_ENTRY(glGetTexParameterfv)(GLenum target, GLenum pname, GLfloat* params) { CALL_GL_API(glGetTexParameterfv, target, pname, params); } void API_ENTRY(glGetTexParameteriv)(GLenum target, GLenum pname, GLint* params) { CALL_GL_API(glGetTexParameteriv, target, pname, params); } GLboolean glIsTexture(GLuint texture) { GLES2_GET_CONST_CONTEXT(ctx); if (ctx->tex.textures.find(texture) == ctx->tex.textures.end()) return GL_FALSE; else return GL_TRUE; } void glPixelStorei(GLenum pname, GLint param) { GLES2_GET_CONST_CONTEXT(ctx); assert(GL_UNPACK_ALIGNMENT == pname); assert(1 == param || 2 == param || 4 == param || 8 == param); ctx->tex.unpack = param; } void glTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* pixels) { GLES2_GET_CONST_CONTEXT(ctx); switch (type) { case GL_UNSIGNED_BYTE: break; case GL_UNSIGNED_SHORT_5_6_5: internalformat = format = GL_UNSIGNED_SHORT_5_6_5; assert(4 == ctx->tex.unpack); break; default: assert(0); } assert(internalformat == format); assert(0 == border); if (0 != level) { LOGD("agl2: glTexImage2D level=%d", level); return; } unsigned bytesPerPixel = 0; GGLPixelFormat texFormat = GGL_PIXEL_FORMAT_UNKNOWN; GetFormatAndBytesPerPixel(format, &bytesPerPixel, &texFormat); assert(texFormat && bytesPerPixel); unsigned offset = 0, size = width * height * bytesPerPixel, totalSize = size; assert(ctx->tex.tmus[ctx->tex.active]); GGLTexture & tex = *ctx->tex.tmus[ctx->tex.active]; tex.width = width; tex.height = height; tex.levelCount = 1; tex.format = texFormat; switch (target) { case GL_TEXTURE_2D: assert(GL_TEXTURE_2D == ctx->tex.tmus[ctx->tex.active]->type); offset = 0; break; break; case GL_TEXTURE_CUBE_MAP_POSITIVE_X: case GL_TEXTURE_CUBE_MAP_NEGATIVE_X: case GL_TEXTURE_CUBE_MAP_POSITIVE_Y: case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: case GL_TEXTURE_CUBE_MAP_POSITIVE_Z: case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: assert(GL_TEXTURE_CUBE_MAP == ctx->tex.tmus[ctx->tex.active]->type); assert(width == height); offset = (target - GL_TEXTURE_CUBE_MAP_POSITIVE_X) * size; totalSize = 6 * size; break; default: assert(0); return; } tex.levels = realloc(tex.levels, totalSize); if (pixels) CopyTexture((char *)tex.levels, (const char *)pixels, bytesPerPixel, 0, 0, width, 0, 0, width, width, height); ctx->tex.UpdateSampler(ctx->iface, ctx->tex.active); } void glTexParameterf(GLenum target, GLenum pname, GLfloat param) { glTexParameteri(target, pname, param); } void API_ENTRY(glTexParameterfv)(GLenum target, GLenum pname, const GLfloat* params) { CALL_GL_API(glTexParameterfv, target, pname, params); } void glTexParameteri(GLenum target, GLenum pname, GLint param) { GLES2_GET_CONST_CONTEXT(ctx); assert(ctx->tex.tmus[ctx->tex.active]); assert(target == ctx->tex.tmus[ctx->tex.active]->type); GGLTexture & tex = *ctx->tex.tmus[ctx->tex.active]; switch (pname) { case GL_TEXTURE_WRAP_S: case GL_TEXTURE_WRAP_T: GGLTexture::GGLTextureWrap wrap; switch (param) { case GL_REPEAT: wrap = GGLTexture::GGL_REPEAT; break; case GL_CLAMP_TO_EDGE: wrap = GGLTexture::GGL_CLAMP_TO_EDGE; break; case GL_MIRRORED_REPEAT: wrap = GGLTexture::GGL_MIRRORED_REPEAT; break; default: assert(0); return; } if (GL_TEXTURE_WRAP_S == pname) tex.wrapS = wrap; else tex.wrapT = wrap; break; case GL_TEXTURE_MIN_FILTER: switch (param) { case GL_NEAREST: tex.minFilter = GGLTexture::GGL_NEAREST; break; case GL_LINEAR: tex.minFilter = GGLTexture::GGL_LINEAR; break; case GL_NEAREST_MIPMAP_NEAREST: break; case GL_NEAREST_MIPMAP_LINEAR: break; case GL_LINEAR_MIPMAP_NEAREST: break; case GL_LINEAR_MIPMAP_LINEAR: break; default: assert(0); return; } break; case GL_TEXTURE_MAG_FILTER: switch (param) { case GL_NEAREST: tex.minFilter = GGLTexture::GGL_NEAREST; break; case GL_LINEAR: tex.minFilter = GGLTexture::GGL_LINEAR; break; default: assert(0); return; } break; default: assert(0); return; } if (tex.magFilter != tex.minFilter) tex.magFilter = tex.minFilter = GGLTexture::GGL_LINEAR; ctx->tex.UpdateSampler(ctx->iface, ctx->tex.active); } void API_ENTRY(glTexParameteriv)(GLenum target, GLenum pname, const GLint* params) { CALL_GL_API(glTexParameteriv, target, pname, params); } void glTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid* pixels) { GLES2_GET_CONST_CONTEXT(ctx); assert(0 == level); assert(target == ctx->tex.tmus[ctx->tex.active]->type); switch (type) { case GL_UNSIGNED_BYTE: break; case GL_UNSIGNED_SHORT_5_6_5: format = GL_UNSIGNED_SHORT_5_6_5; assert(4 == ctx->tex.unpack); break; default: assert(0); } GGLTexture & tex = *ctx->tex.tmus[ctx->tex.active]; GGLPixelFormat texFormat = GGL_PIXEL_FORMAT_UNKNOWN; unsigned bytesPerPixel = 0; GetFormatAndBytesPerPixel(format, &bytesPerPixel, &texFormat); assert(texFormat == tex.format); assert(GL_UNSIGNED_BYTE == type); switch (target) { case GL_TEXTURE_2D: CopyTexture((char *)tex.levels, (const char *)pixels, bytesPerPixel, 0, 0, width, xoffset, yoffset, tex.width, width, height); break; default: assert(0); } ctx->tex.UpdateSampler(ctx->iface, ctx->tex.active); }
#include "gles2context.h" #define API_ENTRY #define CALL_GL_API(NAME,...) LOGD("?"#NAME); assert(0); #define CALL_GL_API_RETURN(NAME,...) LOGD("?"#NAME); assert(0); return 0;
void GLES2Context::InitializeTextures() { tex.textures = std::map<GLuint, GGLTexture *>(); tex.tex2D = AllocTexture(); tex.textures[GL_TEXTURE_2D] = tex.tex2D; tex.texCube = AllocTexture(); tex.textures[GL_TEXTURE_CUBE_MAP] = tex.texCube; for (unsigned i = 0; i < GGL_MAXCOMBINEDTEXTUREIMAGEUNITS; i++) { tex.tmus[i] = NULL; tex.sampler2tmu[i] = NULL; } tex.active = 0; tex.free = max(GL_TEXTURE_2D, GL_TEXTURE_CUBE_MAP) + 1; tex.tex2D->format = GGL_PIXEL_FORMAT_RGBA_8888; tex.tex2D->type = GL_TEXTURE_2D; tex.tex2D->levelCount = 1; tex.tex2D->wrapS = tex.tex2D->wrapT = GGLTexture::GGL_REPEAT; tex.tex2D->minFilter = tex.tex2D->magFilter = GGLTexture::GGL_NEAREST; tex.tex2D->width = tex.tex2D->height = 1; tex.tex2D->levels = malloc(4); *(unsigned *)tex.tex2D->levels = 0xff000000; tex.texCube->format = GGL_PIXEL_FORMAT_RGBA_8888; tex.texCube->type = GL_TEXTURE_CUBE_MAP; tex.texCube->levelCount = 1; tex.texCube->wrapS = tex.texCube->wrapT = GGLTexture::GGL_REPEAT; tex.texCube->minFilter = tex.texCube->magFilter = GGLTexture::GGL_NEAREST; tex.texCube->width = tex.texCube->height = 1; tex.texCube->levels = malloc(4 * 6); static unsigned texels [6] = {0xff0000ff, 0xff00ff00, 0xffff0000, 0xff00ffff, 0xffffff00, 0xffff00ff }; memcpy(tex.texCube->levels, texels, sizeof texels); tex.unpack = 4; } void GLES2Context::TextureState::UpdateSampler(GGLInterface * iface, unsigned tmu) { for (unsigned i = 0; i < GGL_MAXCOMBINEDTEXTUREIMAGEUNITS; i++) if (tmu == sampler2tmu[i]) iface->SetSampler(iface, i, tmus[tmu]); } void GLES2Context::UninitializeTextures() { for (std::map<GLuint, GGLTexture *>::iterator it = tex.textures.begin(); it != tex.textures.end(); it++) { if (!it->second) continue; free(it->second->levels); free(it->second); } } static inline void GetFormatAndBytesPerPixel(const GLenum format, unsigned * bytesPerPixel, GGLPixelFormat * texFormat) { switch (format) { case GL_ALPHA: *texFormat = GGL_PIXEL_FORMAT_A_8; *bytesPerPixel = 1; break; case GL_LUMINANCE: *texFormat = GGL_PIXEL_FORMAT_L_8; *bytesPerPixel = 1; break; case GL_LUMINANCE_ALPHA: *texFormat = GGL_PIXEL_FORMAT_LA_88; *bytesPerPixel = 2; break; case GL_RGB: *texFormat = GGL_PIXEL_FORMAT_RGB_888; *bytesPerPixel = 3; break; case GL_RGBA: *texFormat = GGL_PIXEL_FORMAT_RGBA_8888; *bytesPerPixel = 4; break; case GL_UNSIGNED_SHORT_5_6_5: *texFormat = GGL_PIXEL_FORMAT_RGB_565; *bytesPerPixel = 2; break; default: assert(0); return; } } static inline void CopyTexture(char * dst, const char * src, const unsigned bytesPerPixel, const unsigned sx, const unsigned sy, const unsigned sw, const unsigned dx, const unsigned dy, const unsigned dw, const unsigned w, const unsigned h) { const unsigned bpp = bytesPerPixel; if (dw == sw && dw == w && sx == 0 && dx == 0) memcpy(dst + dy * dw * bpp, src + sy * sw * bpp, w * h * bpp); else for (unsigned y = 0; y < h; y++) memcpy(dst + ((dy + y) * dw + dx) * bpp, src + ((sy + y) * sw + sx) * bpp, w * bpp); } void glActiveTexture(GLenum texture) { GLES2_GET_CONST_CONTEXT(ctx); unsigned index = texture - GL_TEXTURE0; assert(NELEM(ctx->tex.tmus) > index); ctx->tex.active = index; } void glBindTexture(GLenum target, GLuint texture) { GLES2_GET_CONST_CONTEXT(ctx); std::map<GLuint, GGLTexture *>::iterator it = ctx->tex.textures.find(texture); GGLTexture * tex = NULL; if (it != ctx->tex.textures.end()) { tex = it->second; if (!tex) { tex = AllocTexture(); tex->type = target; it->second = tex; } assert(target == tex->type); } else if (0 == texture) { if (GL_TEXTURE_2D == target) { tex = ctx->tex.tex2D; } else if (GL_TEXTURE_CUBE_MAP == target) { tex = ctx->tex.texCube; } else assert(0); } else { if (texture <= ctx->tex.free) ctx->tex.free = texture + 1; tex = AllocTexture(); tex->type = target; ctx->tex.textures[texture] = tex; } ctx->tex.tmus[ctx->tex.active] = tex; ctx->tex.UpdateSampler(ctx->iface, ctx->tex.active); } void API_ENTRY(glCompressedTexImage2D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid* data) { CALL_GL_API(glCompressedTexImage2D, target, level, internalformat, width, height, border, imageSize, data); } void API_ENTRY(glCompressedTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid* data) { CALL_GL_API(glCompressedTexSubImage2D, target, level, xoffset, yoffset, width, height, format, imageSize, data); } void glCopyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border) { GLES2_GET_CONST_CONTEXT(ctx); assert(0 == border); assert(0 == level); unsigned bytesPerPixel = 0; GGLPixelFormat texFormat = GGL_PIXEL_FORMAT_UNKNOWN; GetFormatAndBytesPerPixel(internalformat, &bytesPerPixel, &texFormat); assert(texFormat == ctx->rasterizer.frameSurface.format); unsigned offset = 0, size = width * height * bytesPerPixel, totalSize = size; assert(ctx->tex.tmus[ctx->tex.active]); assert(y + height <= ctx->rasterizer.frameSurface.height); assert(x + width <= ctx->rasterizer.frameSurface.width); GGLTexture & tex = *ctx->tex.tmus[ctx->tex.active]; tex.width = width; tex.height = height; tex.levelCount = 1; tex.format = texFormat; switch (target) { case GL_TEXTURE_2D: tex.levels = realloc(tex.levels, totalSize); CopyTexture((char *)tex.levels, (const char *)ctx->rasterizer.frameSurface.data, bytesPerPixel, x, y, ctx->rasterizer.frameSurface.width, 0, 0, width, width, height); break; default: assert(0); return; } ctx->tex.UpdateSampler(ctx->iface, ctx->tex.active); } void glCopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height) { GLES2_GET_CONST_CONTEXT(ctx); assert(0 == level); unsigned bytesPerPixel = 4; unsigned offset = 0, size = width * height * bytesPerPixel, totalSize = size; assert(ctx->tex.tmus[ctx->tex.active]); GGLTexture & tex = *ctx->tex.tmus[ctx->tex.active]; assert(tex.format == ctx->rasterizer.frameSurface.format); assert(GGL_PIXEL_FORMAT_RGBA_8888 == tex.format); const unsigned srcWidth = ctx->rasterizer.frameSurface.width; const unsigned srcHeight = ctx->rasterizer.frameSurface.height; assert(x >= 0 && y >= 0); assert(xoffset >= 0 && yoffset >= 0); assert(x + width <= srcWidth); assert(y + height <= srcHeight); assert(xoffset + width <= tex.width); assert(yoffset + height <= tex.height); switch (target) { case GL_TEXTURE_2D: CopyTexture((char *)tex.levels, (const char *)ctx->rasterizer.frameSurface.data, bytesPerPixel, x, y, srcWidth, xoffset, yoffset, tex.width, width, height); break; default: assert(0); return; } ctx->tex.UpdateSampler(ctx->iface, ctx->tex.active); } void glDeleteTextures(GLsizei n, const GLuint* textures) { GLES2_GET_CONST_CONTEXT(ctx); for (unsigned i = 0; i < n; i++) { std::map<GLuint, GGLTexture *>::iterator it = ctx->tex.textures.find(textures[i]); if (it == ctx->tex.textures.end()) continue; ctx->tex.free = min(ctx->tex.free, textures[i]); for (unsigned i = 0; i < GGL_MAXCOMBINEDTEXTUREIMAGEUNITS; i++) if (ctx->tex.tmus[i] == it->second) { if (GL_TEXTURE_2D == it->second->type) ctx->tex.tmus[i] = ctx->tex.tex2D; else if (GL_TEXTURE_CUBE_MAP == it->second->type) ctx->tex.tmus[i] = ctx->tex.texCube; else assert(0); ctx->tex.UpdateSampler(ctx->iface, i); } if (it->second) { free(it->second->levels); free(it->second); } ctx->tex.textures.erase(it); } } void glGenTextures(GLsizei n, GLuint* textures) { GLES2_GET_CONST_CONTEXT(ctx); for (unsigned i = 0; i < n; i++) { textures[i] = 0; for (ctx->tex.free; ctx->tex.free < 0xffffffffu; ctx->tex.free++) if (ctx->tex.textures.find(ctx->tex.free) == ctx->tex.textures.end()) { ctx->tex.textures[ctx->tex.free] = NULL; textures[i] = ctx->tex.free; ctx->tex.free++; break; } assert(textures[i]); } } void API_ENTRY(glGetTexParameterfv)(GLenum target, GLenum pname, GLfloat* params) { CALL_GL_API(glGetTexParameterfv, target, pname, params); } void API_ENTRY(glGetTexParameteriv)(GLenum target, GLenum pname, GLint* params) { CALL_GL_API(glGetTexParameteriv, target, pname, params); } GLboolean glIsTexture(GLuint texture) { GLES2_GET_CONST_CONTEXT(ctx); if (ctx->tex.textures.find(texture) == ctx->tex.textures.end()) return GL_FALSE; else return GL_TRUE; } void glPixelStorei(GLenum pname, GLint param) { GLES2_GET_CONST_CONTEXT(ctx); assert(GL_UNPACK_ALIGNMENT == pname); assert(1 == param || 2 == param || 4 == param || 8 == param); ctx->tex.unpack = param; } void glTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* pixels) { GLES2_GET_CONST_CONTEXT(ctx); switch (type) { case GL_UNSIGNED_BYTE: break; case GL_UNSIGNED_SHORT_5_6_5: internalformat = format = GL_UNSIGNED_SHORT_5_6_5; assert(4 == ctx->tex.unpack); break; default: assert(0); } assert(internalformat == format); assert(0 == border); if (0 != level) { LOGD("agl2: glTexImage2D level=%d", level); return; } unsigned bytesPerPixel = 0; GGLPixelFormat texFormat = GGL_PIXEL_FORMAT_UNKNOWN; GetFormatAndBytesPerPixel(format, &bytesPerPixel, &texFormat); assert(texFormat && bytesPerPixel); unsigned offset = 0, size = width * height * bytesPerPixel, totalSize = size; assert(ctx->tex.tmus[ctx->tex.active]); GGLTexture & tex = *ctx->tex.tmus[ctx->tex.active]; tex.width = width; tex.height = height; tex.levelCount = 1; tex.format = texFormat; switch (target) { case GL_TEXTURE_2D: assert(GL_TEXTURE_2D == ctx->tex.tmus[ctx->tex.active]->type); offset = 0; break; break; case GL_TEXTURE_CUBE_MAP_POSITIVE_X: case GL_TEXTURE_CUBE_MAP_NEGATIVE_X: case GL_TEXTURE_CUBE_MAP_POSITIVE_Y: case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: case GL_TEXTURE_CUBE_MAP_POSITIVE_Z: case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: assert(GL_TEXTURE_CUBE_MAP == ctx->tex.tmus[ctx->tex.active]->type); assert(width == height); offset = (target - GL_TEXTURE_CUBE_MAP_POSITIVE_X) * size; totalSize = 6 * size; break; default: assert(0); return; } tex.levels = realloc(tex.levels, totalSize); if (pixels) CopyTexture((char *)tex.levels, (const char *)pixels, bytesPerPixel, 0, 0, width, 0, 0, width, width, height); ctx->tex.UpdateSampler(ctx->iface, ctx->tex.active); } void glTexParameterf(GLenum target, GLenum pname, GLfloat param) { glTexParameteri(target, pname, param); } void API_ENTRY(glTexParameterfv)(GLenum target, GLenum pname, const GLfloat* params) { CALL_GL_API(glTexParameterfv, target, pname, params); } void glTexParameteri(GLenum target, GLenum pname, GLint param) { GLES2_GET_CONST_CONTEXT(ctx); assert(ctx->tex.tmus[ctx->tex.active]); assert(target == ctx->tex.tmus[ctx->tex.active]->type); GGLTexture & tex = *ctx->tex.tmus[ctx->tex.active]; switch (pname) { case GL_TEXTURE_WRAP_S: case GL_TEXTURE_WRAP_T: GGLTexture::GGLTextureWrap wrap; switch (param) { case GL_REPEAT: wrap = GGLTexture::GGL_REPEAT; break; case GL_CLAMP_TO_EDGE: wrap = GGLTexture::GGL_CLAMP_TO_EDGE; break; case GL_MIRRORED_REPEAT: wrap = GGLTexture::GGL_MIRRORED_REPEAT; break; default: assert(0); return; } if (GL_TEXTURE_WRAP_S == pname) tex.wrapS = wrap; else tex.wrapT = wrap; break; case GL_TEXTURE_MIN_FILTER: switch (param) { case GL_NEAREST: tex.minFilter = GGLTexture::GGL_NEAREST; break; case GL_LINEAR: tex.minFilter = GGLTexture::GGL_LINEAR; break; case GL_NEAREST_MIPMAP_NEAREST: break; case GL_NEAREST_MIPMAP_LINEAR: break; case GL_LINEAR_MIPMAP_NEAREST: break; case GL_LINEAR_MIPMAP_LINEAR: break; default: assert(0); return; } break; case GL_TEXTURE_MAG_FILTER: switch (param) { case GL_NEAREST: tex.minFilter = GGLTexture::GGL_NEAREST; break; case GL_LINEAR: tex.minFilter = GGLTexture::GGL_LINEAR; break; default: assert(0); return; } break; default: assert(0); return; } if (tex.magFilter != tex.minFilter) tex.magFilter = tex.minFilter = GGLTexture::GGL_LINEAR; ctx->tex.UpdateSampler(ctx->iface, ctx->tex.active); } void API_ENTRY(glTexParameteriv)(GLenum target, GLenum pname, const GLint* params) { CALL_GL_API(glTexParameteriv, target, pname, params); } void glTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid* pixels) { GLES2_GET_CONST_CONTEXT(ctx); assert(0 == level); assert(target == ctx->tex.tmus[ctx->tex.active]->type); switch (type) { case GL_UNSIGNED_BYTE: break; case GL_UNSIGNED_SHORT_5_6_5: format = GL_UNSIGNED_SHORT_5_6_5; assert(4 == ctx->tex.unpack); break; default: assert(0); } GGLTexture & tex = *ctx->tex.tmus[ctx->tex.active]; GGLPixelFormat texFormat = GGL_PIXEL_FORMAT_UNKNOWN; unsigned bytesPerPixel = 0; GetFormatAndBytesPerPixel(format, &bytesPerPixel, &texFormat); assert(texFormat == tex.format); assert(GL_UNSIGNED_BYTE == type); switch (target) { case GL_TEXTURE_2D: CopyTexture((char *)tex.levels, (const char *)pixels, bytesPerPixel, 0, 0, width, xoffset, yoffset, tex.width, width, height); break; default: assert(0); } ctx->tex.UpdateSampler(ctx->iface, ctx->tex.active); }
static inline GGLTexture * AllocTexture() { GGLTexture * tex = (GGLTexture *)calloc(1, sizeof(GGLTexture)); tex->minFilter = GGLTexture::GGL_LINEAR; tex->magFilter = GGLTexture::GGL_LINEAR; return tex; }
function_block-full_function
[]
C++
activemq-cpp/src/test/activemq/core/ConnectionAuditTest.cpp
novomatic-tech/activemq-cpp
d6f76ede90d21b7ee2f0b5d4648e440e66d63003
#include "ConnectionAuditTest.h" #include <activemq/core/ConnectionAudit.h> #include <activemq/core/Dispatcher.h> #include <activemq/core/ActiveMQMessageAudit.h> #include <activemq/util/IdGenerator.h> #include <activemq/commands/Message.h> #include <activemq/commands/ActiveMQDestination.h> #include <activemq/commands/ActiveMQQueue.h> #include <decaf/util/ArrayList.h> using namespace std; using namespace activemq; using namespace activemq::core; using namespace activemq::commands; using namespace activemq::util; using namespace decaf; using namespace decaf::lang; using namespace decaf::util; namespace { class MyDispatcher : public Dispatcher { public: virtual ~MyDispatcher() {} virtual void dispatch(const Pointer<commands::MessageDispatch>& message) { } virtual int getHashCode() const { return 1; } }; } ConnectionAuditTest::ConnectionAuditTest() { } ConnectionAuditTest::~ConnectionAuditTest() { } void ConnectionAuditTest::testConstructor1() { ConnectionAudit audit; CPPUNIT_ASSERT(audit.isCheckForDuplicates()); CPPUNIT_ASSERT(audit.getAuditDepth() == ActiveMQMessageAudit::DEFAULT_WINDOW_SIZE); CPPUNIT_ASSERT(audit.getAuditMaximumProducerNumber() == ActiveMQMessageAudit::MAXIMUM_PRODUCER_COUNT); } void ConnectionAuditTest::testConstructor2() { ConnectionAudit audit(100, 200); CPPUNIT_ASSERT(audit.isCheckForDuplicates()); CPPUNIT_ASSERT(audit.getAuditDepth() == 100); CPPUNIT_ASSERT(audit.getAuditMaximumProducerNumber() == 200); } void ConnectionAuditTest::testIsDuplicate() { int count = 10000; ConnectionAudit audit; ArrayList<Pointer<MessageId> > list; Pointer<MyDispatcher> dispatcher(new MyDispatcher); Pointer<ProducerId> pid(new ProducerId); pid->setConnectionId("test"); pid->setSessionId(0); pid->setValue(1); Pointer<Message> message(new Message()); for (int i = 0; i < count; i++) { Pointer<ActiveMQDestination> destination(new ActiveMQQueue("TEST.QUEUE")); message->setDestination(destination); Pointer<MessageId> id(new MessageId); id->setProducerId(pid); id->setProducerSequenceId(i); list.add(id); message->setMessageId(id); CPPUNIT_ASSERT(!audit.isDuplicate(dispatcher.get(), message)); } int index = list.size() -1 -audit.getAuditDepth(); for (; index < list.size(); index++) { Pointer<MessageId> id = list.get(index); message->setMessageId(id); CPPUNIT_ASSERT_MESSAGE(std::string() + "duplicate msg:" + id->toString(), audit.isDuplicate(dispatcher.get(), message)); } } void ConnectionAuditTest::testRollbackDuplicate() { int count = 10000; ConnectionAudit audit; ArrayList<Pointer<MessageId> > list; Pointer<MyDispatcher> dispatcher(new MyDispatcher); Pointer<ProducerId> pid(new ProducerId); pid->setConnectionId("test"); pid->setSessionId(0); pid->setValue(1); Pointer<ActiveMQDestination> destination(new ActiveMQQueue("TEST.QUEUE")); Pointer<Message> message(new Message()); message->setDestination(destination); for (int i = 0; i < count; i++) { Pointer<MessageId> id(new MessageId); id->setProducerId(pid); id->setProducerSequenceId(i); list.add(id); message->setMessageId(id); CPPUNIT_ASSERT(!audit.isDuplicate(dispatcher.get(), message)); } int index = list.size() -1 -audit.getAuditDepth(); for (; index < list.size(); index++) { Pointer<MessageId> id = list.get(index); message->setMessageId(id); CPPUNIT_ASSERT_MESSAGE(std::string() + "duplicate msg:" + id->toString(), audit.isDuplicate(dispatcher.get(), message)); audit.rollbackDuplicate(dispatcher.get(), message); CPPUNIT_ASSERT_MESSAGE(std::string() + "duplicate msg:" + id->toString(), !audit.isDuplicate(dispatcher.get(), message)); } }
#include "ConnectionAuditTest.h" #include <activemq/core/ConnectionAudit.h> #include <activemq/core/Dispatcher.h> #include <activemq/core/ActiveMQMessageAudit.h> #include <activemq/util/IdGenerator.h> #include <activemq/commands/Message.h> #include <activemq/commands/ActiveMQDestination.h> #include <activemq/commands/ActiveMQQueue.h> #include <decaf/util/ArrayList.h> using namespace std; using namespace activemq; using namespace activemq::core; using namespace activemq::commands; using namespace activemq::util; using namespace decaf; using namespace decaf::lang; using namespace decaf::util; namespace { class MyDispatcher : public Dispatcher { public: virtual ~MyDispatcher() {} virtual void dispatch(const Pointer<commands::MessageDispatch>& message) { } virtual int getHashCode() const { return 1; } }; } ConnectionAuditTest::ConnectionAuditTest() { } ConnectionAuditTest::~ConnectionAuditTest() { } void ConnectionAuditTest::testConstructor1() { ConnectionAudit audit; CPPUNIT_ASSERT(audit.isCheckForDuplicates()); CPPUNIT_ASSERT(audit.getAuditDepth() == ActiveMQMessageAudit::DEFAULT_WINDOW_SIZE); CPPUNIT_ASSERT(audit.getAuditMaximumProd
eId> id(new MessageId); id->setProducerId(pid); id->setProducerSequenceId(i); list.add(id); message->setMessageId(id); CPPUNIT_ASSERT(!audit.isDuplicate(dispatcher.get(), message)); } int index = list.size() -1 -audit.getAuditDepth(); for (; index < list.size(); index++) { Pointer<MessageId> id = list.get(index); message->setMessageId(id); CPPUNIT_ASSERT_MESSAGE(std::string() + "duplicate msg:" + id->toString(), audit.isDuplicate(dispatcher.get(), message)); } } void ConnectionAuditTest::testRollbackDuplicate() { int count = 10000; ConnectionAudit audit; ArrayList<Pointer<MessageId> > list; Pointer<MyDispatcher> dispatcher(new MyDispatcher); Pointer<ProducerId> pid(new ProducerId); pid->setConnectionId("test"); pid->setSessionId(0); pid->setValue(1); Pointer<ActiveMQDestination> destination(new ActiveMQQueue("TEST.QUEUE")); Pointer<Message> message(new Message()); message->setDestination(destination); for (int i = 0; i < count; i++) { Pointer<MessageId> id(new MessageId); id->setProducerId(pid); id->setProducerSequenceId(i); list.add(id); message->setMessageId(id); CPPUNIT_ASSERT(!audit.isDuplicate(dispatcher.get(), message)); } int index = list.size() -1 -audit.getAuditDepth(); for (; index < list.size(); index++) { Pointer<MessageId> id = list.get(index); message->setMessageId(id); CPPUNIT_ASSERT_MESSAGE(std::string() + "duplicate msg:" + id->toString(), audit.isDuplicate(dispatcher.get(), message)); audit.rollbackDuplicate(dispatcher.get(), message); CPPUNIT_ASSERT_MESSAGE(std::string() + "duplicate msg:" + id->toString(), !audit.isDuplicate(dispatcher.get(), message)); } }
ucerNumber() == ActiveMQMessageAudit::MAXIMUM_PRODUCER_COUNT); } void ConnectionAuditTest::testConstructor2() { ConnectionAudit audit(100, 200); CPPUNIT_ASSERT(audit.isCheckForDuplicates()); CPPUNIT_ASSERT(audit.getAuditDepth() == 100); CPPUNIT_ASSERT(audit.getAuditMaximumProducerNumber() == 200); } void ConnectionAuditTest::testIsDuplicate() { int count = 10000; ConnectionAudit audit; ArrayList<Pointer<MessageId> > list; Pointer<MyDispatcher> dispatcher(new MyDispatcher); Pointer<ProducerId> pid(new ProducerId); pid->setConnectionId("test"); pid->setSessionId(0); pid->setValue(1); Pointer<Message> message(new Message()); for (int i = 0; i < count; i++) { Pointer<ActiveMQDestination> destination(new ActiveMQQueue("TEST.QUEUE")); message->setDestination(destination); Pointer<Messag
random
[ { "content": " class DECAF_API Reader: public virtual decaf::io::Closeable, public virtual decaf::lang::Readable {\n\n private:\n\n\n\n Reader(const Reader&);\n\n Reader& operator=(const Reader&);\n\n\n\n protected:\n\n\n\n Reader();\n\n\n\n public:\n\n\n\n virtual ~Reade...
C++
PlayTools/mainwindow.cpp
memorywalker/playtools
39441f3df16484a0784a5cc3b62c57af049fdc52
#include "mainwindow.h" #include "firewallrules.h" #include "ui_mainwindow.h" #include <Windows.h> #include "AutoMate.h" #include <QDebug> #include <QHotkey> #include <QSound> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) , m_nLuckwheelInteval(4000) { ui->setupUi(this); m_AutoMate = new AutoMate(); m_AutoMate->SetWindow(this); m_GtaProcessPath = "I:\\SteamLibrary\\steamapps\\common\\Grand Theft Auto V\\GTA5.exe"; m_firewallRules.SetActionListener(this); InitUI(); } MainWindow::~MainWindow() { for (size_t i = 0; i < FunctionType_Max; i++) { delete m_FuncHotkeys[i]; m_FuncHotkeys[i] = nullptr; } delete ui; } void MainWindow::InitUI() { QString strluckyWheelInteval = ui->lineEditLuckyWheelInteval->text(); m_nLuckwheelInteval = strluckyWheelInteval.toInt(); BindHotKeys(); } void MainWindow::PlaySoundPrompt() { QSound::play("c:/Windows/media/tada.wav"); } void MainWindow::BindHotKeys() { for (size_t i = 0; i < FunctionType_Max; i++) { m_FuncHotkeys[i] = new QHotkey(this); } QString strKey = ui->lineEditSolo->text().trimmed().toLower(); m_FuncHotkeys[FunctionType_Solo]->setShortcut(QKeySequence(strKey), true); QMetaObject::Connection conn = QObject::connect(m_FuncHotkeys[FunctionType_Solo], &QHotkey::activated, this, &MainWindow::on_soloButton_clicked); Q_ASSERT(conn); strKey = ui->lineEditDisconnectProcess->text().trimmed().toLower(); m_FuncHotkeys[FunctionType_Disconnect]->setShortcut(QKeySequence(strKey), true); conn = QObject::connect(m_FuncHotkeys[FunctionType_Disconnect], &QHotkey::activated, this, &MainWindow::on_disconnectProcessButton_clicked); Q_ASSERT(conn); strKey = ui->lineEditFingerPrint->text().trimmed().toLower(); m_FuncHotkeys[FunctionType_Finger]->setShortcut(QKeySequence(strKey), true); conn = QObject::connect(m_FuncHotkeys[FunctionType_Finger], &QHotkey::activated, this, &MainWindow::on_fingerPrintButton_clicked); Q_ASSERT(conn); strKey = ui->lineEditLuckyWheel->text().trimmed().toLower(); m_FuncHotkeys[FunctionType_Lucky]->setShortcut(QKeySequence(strKey), true); conn = QObject::connect(m_FuncHotkeys[FunctionType_Lucky], &QHotkey::activated, this, &MainWindow::on_luckyWheelButton_clicked); Q_ASSERT(conn); strKey = ui->lineEditDoomsDayII->text().trimmed().toLower(); m_FuncHotkeys[FunctionType_DoomsDayII]->setShortcut(QKeySequence(strKey), true); conn = QObject::connect(m_FuncHotkeys[FunctionType_DoomsDayII], &QHotkey::activated, this, &MainWindow::on_doomsDay2Button_clicked); Q_ASSERT(conn); strKey = ui->lineEditDoomsDayIII->text().trimmed().toLower(); m_FuncHotkeys[FunctionType_DoomsDayIII]->setShortcut(QKeySequence(strKey), true); conn = QObject::connect(m_FuncHotkeys[FunctionType_DoomsDayIII], &QHotkey::activated, this, &MainWindow::on_doomsDay3Button_clicked); Q_ASSERT(conn); strKey = ui->lineEditSnack->text().trimmed().toLower(); m_FuncHotkeys[FunctionType_Snack]->setShortcut(QKeySequence(strKey), true); conn = QObject::connect(m_FuncHotkeys[FunctionType_Snack], &QHotkey::activated, this, &MainWindow::on_snackButton_clicked); Q_ASSERT(conn); strKey = ui->lineEditArmor->text().trimmed().toLower(); m_FuncHotkeys[FunctionType_Armor]->setShortcut(QKeySequence(strKey), true); conn = QObject::connect(m_FuncHotkeys[FunctionType_Armor], &QHotkey::activated, this, &MainWindow::on_amorButton_clicked); Q_ASSERT(conn); } void MainWindow::UnBindHotKeys() { bool bRet = QObject::disconnect(m_FuncHotkeys[FunctionType_Solo], &QHotkey::activated, this, &MainWindow::on_soloButton_clicked); bRet &= QObject::disconnect(m_FuncHotkeys[FunctionType_Disconnect], &QHotkey::activated, this, &MainWindow::on_disconnectProcessButton_clicked); bRet &= QObject::disconnect(m_FuncHotkeys[FunctionType_Finger], &QHotkey::activated, this, &MainWindow::on_fingerPrintButton_clicked); bRet &= QObject::disconnect(m_FuncHotkeys[FunctionType_Lucky], &QHotkey::activated, this, &MainWindow::on_luckyWheelButton_clicked); bRet &= QObject::disconnect(m_FuncHotkeys[FunctionType_DoomsDayII], &QHotkey::activated, this, &MainWindow::on_doomsDay2Button_clicked); bRet &= QObject::disconnect(m_FuncHotkeys[FunctionType_DoomsDayIII], &QHotkey::activated, this, &MainWindow::on_doomsDay3Button_clicked); bRet &= QObject::disconnect(m_FuncHotkeys[FunctionType_Snack], &QHotkey::activated, this, &MainWindow::on_snackButton_clicked); bRet &= QObject::disconnect(m_FuncHotkeys[FunctionType_Armor], &QHotkey::activated, this, &MainWindow::on_amorButton_clicked); for (size_t i = 0; i < FunctionType_Max; i++) { delete m_FuncHotkeys[i]; m_FuncHotkeys[i] = nullptr; } } void MainWindow::OnActionDone(QString& strOut) { ui->labelPrompt->setText(strOut); PlaySoundPrompt(); } void MainWindow::closeEvent(QCloseEvent* e) { m_firewallRules.StopProcessOffine(); m_firewallRules.StopSinglePublicSession(); } void MainWindow::on_snackButton_clicked() { PlaySoundPrompt(); if (m_AutoMate) { m_AutoMate->SendSnackCmd(); } } void MainWindow::on_amorButton_clicked() { PlaySoundPrompt(); if (m_AutoMate) { m_AutoMate->SendArmorCmd(); } } void MainWindow::on_soloButton_clicked() { PlaySoundPrompt(); static bool switchOn = false; if (!switchOn) { m_firewallRules.StartSinglePublicSession(); } else { m_firewallRules.StopSinglePublicSession(); } switchOn = !switchOn; if (switchOn) { ui->soloButton->setStyleSheet("background-color: rgb(255, 0, 0)"); } else { ui->soloButton->setStyleSheet("background-color: rgb(23, 135, 6)"); } } void MainWindow::on_disconnectProcessButton_clicked() { PlaySoundPrompt(); static bool switchOn = false; if (!switchOn) { m_firewallRules.StartProcessOffline(m_GtaProcessPath); } else { m_firewallRules.StopProcessOffine(); } switchOn = !switchOn; if (switchOn) { ui->disconnectProcessButton->setStyleSheet("background-color: rgb(255, 0, 0)"); } else { ui->disconnectProcessButton->setStyleSheet("background-color: rgb(23, 135, 6)"); } } void MainWindow::on_fingerPrintButton_clicked() { PlaySoundPrompt(); } void MainWindow::on_luckyWheelButton_clicked() { PlaySoundPrompt(); if (m_AutoMate) { m_AutoMate->SendLuckyWheelCmd(m_nLuckwheelInteval); } } void MainWindow::on_doomsDay2Button_clicked() { PlaySoundPrompt(); if (m_AutoMate) { m_AutoMate->SendDoomsDayIICmd(); } } void MainWindow::on_doomsDay3Button_clicked() { PlaySoundPrompt(); if (m_AutoMate) { m_AutoMate->SendDoomsDayIIICmd(); } } void MainWindow::on_lineEditLuckyWheelInteval_textChanged(const QString &arg1) { QString strluckyWheelInteval = ui->lineEditLuckyWheelInteval->text(); m_nLuckwheelInteval = strluckyWheelInteval.toInt(); } void MainWindow::on_pushButtonSave_clicked() { UnBindHotKeys(); BindHotKeys(); }
#include "mainwindow.h" #include "firewallrules.h" #include "ui_mainwindow.h" #include <Windows.h> #include "AutoMate.h" #include <QDebug> #include <QHotkey> #include <QSound> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) , m_nLuckwheelInteval(4000) { ui->setupUi(this); m_AutoMate = new AutoMate(); m_AutoMate->SetWindow(this); m_GtaProcessPath = "I:\\SteamLibrary\\steamapps\\common\\Grand Theft Auto V\\GTA5.exe"; m_firewallRules.SetActionListener(this); InitUI(); } MainWindow::~MainWindow() { for (size_t i = 0; i < FunctionType_Max; i++) { delete m_FuncHotkeys[i]; m_FuncHotkeys[i] = nullptr; } delete ui; } void MainWindow::InitUI() { QString strluckyWheelInteval = ui->lineEditLuckyWheelInteval->text(); m_nLuckwheelInteval = strluckyWheelInteval.toInt(); BindHotKeys(); } void MainWindow::PlaySoundPrompt() { QSound::play("c:/Windows/media/tada.wav"); } void MainWindow::BindHotKeys() { for (size_t i = 0; i < FunctionType_Max; i++) { m_FuncHotkeys[i] = new QHotkey(this); } QString strKey = ui->lineEditSolo->text().trimmed().toLower(); m_FuncHotkeys[FunctionType_Solo]->setShortcut(QKeySequence(strKey), true); QMetaObject::Connection conn = QObject::connect(m_FuncHotkeys[FunctionType_Solo], &QHotkey::activated, this, &MainWindow::on_soloButton_clicked); Q_ASSERT(conn); strKey = ui->lineEditDisconnectProcess->text().trimmed().toLower(); m_FuncHotkeys[FunctionType_Disconnect]->setShortcut(QKeySequence(strKey), true); conn = QObject::connect(m_FuncHotkeys[FunctionType_Disconnect], &QHotkey::activated, this, &MainWindow::on_disconnectProcessButton_clicked); Q_ASSERT(conn); strKey = ui->lineEditFingerPrint->text().trimmed().toLower(); m
m_firewallRules.StartProcessOffline(m_GtaProcessPath); } else { m_firewallRules.StopProcessOffine(); } switchOn = !switchOn; if (switchOn) { ui->disconnectProcessButton->setStyleSheet("background-color: rgb(255, 0, 0)"); } else { ui->disconnectProcessButton->setStyleSheet("background-color: rgb(23, 135, 6)"); } } void MainWindow::on_fingerPrintButton_clicked() { PlaySoundPrompt(); } void MainWindow::on_luckyWheelButton_clicked() { PlaySoundPrompt(); if (m_AutoMate) { m_AutoMate->SendLuckyWheelCmd(m_nLuckwheelInteval); } } void MainWindow::on_doomsDay2Button_clicked() { PlaySoundPrompt(); if (m_AutoMate) { m_AutoMate->SendDoomsDayIICmd(); } } void MainWindow::on_doomsDay3Button_clicked() { PlaySoundPrompt(); if (m_AutoMate) { m_AutoMate->SendDoomsDayIIICmd(); } } void MainWindow::on_lineEditLuckyWheelInteval_textChanged(const QString &arg1) { QString strluckyWheelInteval = ui->lineEditLuckyWheelInteval->text(); m_nLuckwheelInteval = strluckyWheelInteval.toInt(); } void MainWindow::on_pushButtonSave_clicked() { UnBindHotKeys(); BindHotKeys(); }
_FuncHotkeys[FunctionType_Finger]->setShortcut(QKeySequence(strKey), true); conn = QObject::connect(m_FuncHotkeys[FunctionType_Finger], &QHotkey::activated, this, &MainWindow::on_fingerPrintButton_clicked); Q_ASSERT(conn); strKey = ui->lineEditLuckyWheel->text().trimmed().toLower(); m_FuncHotkeys[FunctionType_Lucky]->setShortcut(QKeySequence(strKey), true); conn = QObject::connect(m_FuncHotkeys[FunctionType_Lucky], &QHotkey::activated, this, &MainWindow::on_luckyWheelButton_clicked); Q_ASSERT(conn); strKey = ui->lineEditDoomsDayII->text().trimmed().toLower(); m_FuncHotkeys[FunctionType_DoomsDayII]->setShortcut(QKeySequence(strKey), true); conn = QObject::connect(m_FuncHotkeys[FunctionType_DoomsDayII], &QHotkey::activated, this, &MainWindow::on_doomsDay2Button_clicked); Q_ASSERT(conn); strKey = ui->lineEditDoomsDayIII->text().trimmed().toLower(); m_FuncHotkeys[FunctionType_DoomsDayIII]->setShortcut(QKeySequence(strKey), true); conn = QObject::connect(m_FuncHotkeys[FunctionType_DoomsDayIII], &QHotkey::activated, this, &MainWindow::on_doomsDay3Button_clicked); Q_ASSERT(conn); strKey = ui->lineEditSnack->text().trimmed().toLower(); m_FuncHotkeys[FunctionType_Snack]->setShortcut(QKeySequence(strKey), true); conn = QObject::connect(m_FuncHotkeys[FunctionType_Snack], &QHotkey::activated, this, &MainWindow::on_snackButton_clicked); Q_ASSERT(conn); strKey = ui->lineEditArmor->text().trimmed().toLower(); m_FuncHotkeys[FunctionType_Armor]->setShortcut(QKeySequence(strKey), true); conn = QObject::connect(m_FuncHotkeys[FunctionType_Armor], &QHotkey::activated, this, &MainWindow::on_amorButton_clicked); Q_ASSERT(conn); } void MainWindow::UnBindHotKeys() { bool bRet = QObject::disconnect(m_FuncHotkeys[FunctionType_Solo], &QHotkey::activated, this, &MainWindow::on_soloButton_clicked); bRet &= QObject::disconnect(m_FuncHotkeys[FunctionType_Disconnect], &QHotkey::activated, this, &MainWindow::on_disconnectProcessButton_clicked); bRet &= QObject::disconnect(m_FuncHotkeys[FunctionType_Finger], &QHotkey::activated, this, &MainWindow::on_fingerPrintButton_clicked); bRet &= QObject::disconnect(m_FuncHotkeys[FunctionType_Lucky], &QHotkey::activated, this, &MainWindow::on_luckyWheelButton_clicked); bRet &= QObject::disconnect(m_FuncHotkeys[FunctionType_DoomsDayII], &QHotkey::activated, this, &MainWindow::on_doomsDay2Button_clicked); bRet &= QObject::disconnect(m_FuncHotkeys[FunctionType_DoomsDayIII], &QHotkey::activated, this, &MainWindow::on_doomsDay3Button_clicked); bRet &= QObject::disconnect(m_FuncHotkeys[FunctionType_Snack], &QHotkey::activated, this, &MainWindow::on_snackButton_clicked); bRet &= QObject::disconnect(m_FuncHotkeys[FunctionType_Armor], &QHotkey::activated, this, &MainWindow::on_amorButton_clicked); for (size_t i = 0; i < FunctionType_Max; i++) { delete m_FuncHotkeys[i]; m_FuncHotkeys[i] = nullptr; } } void MainWindow::OnActionDone(QString& strOut) { ui->labelPrompt->setText(strOut); PlaySoundPrompt(); } void MainWindow::closeEvent(QCloseEvent* e) { m_firewallRules.StopProcessOffine(); m_firewallRules.StopSinglePublicSession(); } void MainWindow::on_snackButton_clicked() { PlaySoundPrompt(); if (m_AutoMate) { m_AutoMate->SendSnackCmd(); } } void MainWindow::on_amorButton_clicked() { PlaySoundPrompt(); if (m_AutoMate) { m_AutoMate->SendArmorCmd(); } } void MainWindow::on_soloButton_clicked() { PlaySoundPrompt(); static bool switchOn = false; if (!switchOn) { m_firewallRules.StartSinglePublicSession(); } else { m_firewallRules.StopSinglePublicSession(); } switchOn = !switchOn; if (switchOn) { ui->soloButton->setStyleSheet("background-color: rgb(255, 0, 0)"); } else { ui->soloButton->setStyleSheet("background-color: rgb(23, 135, 6)"); } } void MainWindow::on_disconnectProcessButton_clicked() { PlaySoundPrompt(); static bool switchOn = false; if (!switchOn) {
random
[ { "content": "class AutoMate\n\n{\n\npublic:\n\n\tAutoMate();\n\n\t~AutoMate();\n\n\n\n\tvoid SetWindow(QObject* qObj);\n\n\n\n\tvoid SendTestCommand();\n\n\n\n\tvoid SendSnackCmd();\n\n\tvoid SendArmorCmd();\n\n\tvoid SendDoomsDayIICmd();\n\n\tvoid SendDoomsDayIIICmd();\n\n\tvoid SendLuckyWheelCmd(int millisec...
C++
fltl/include/mpl/Static.hpp
iambrosie/Grail-Plus
e102de735e86df241e4311394190ad39181f073b
#ifndef FLTL_STATIC_HPP_ #define FLTL_STATIC_HPP_ #include <new> namespace fltl { namespace mpl { namespace detail { template <typename T> class StaticValue { public: inline static T &default_value(void) throw() { static T val; static bool is_initialized(false); if(!is_initialized) { is_initialized = true; new (&val) T; } return val; } }; template <typename T> class StaticValue<T *> { public: inline static T *&default_value(void) throw() { static T *val(0); return val; } }; template <> class StaticValue<char> { public: inline static char &default_value(void) throw() { static char val('\0'); return val; } }; template <> class StaticValue<unsigned char> { public: inline static unsigned char &default_value(void) throw() { static unsigned char val(0U); return val; } }; template <> class StaticValue<short> { public: inline static short &default_value(void) throw() { static short val(0); return val; } }; template <> class StaticValue<unsigned short> { public: inline static unsigned short &default_value(void) throw() { static unsigned short val(0U); return val; } }; template <> class StaticValue<int> { public: inline static int &default_value(void) throw() { static int val(0); return val; } }; template <> class StaticValue<unsigned> { public: inline static unsigned &default_value(void) throw() { static unsigned val(0U); return val; } }; template <> class StaticValue<long> { public: inline static long &default_value(void) throw() { static long val(0L); return val; } }; template <> class StaticValue<unsigned long> { public: inline static unsigned long &default_value(void) throw() { static unsigned long val(0UL); return val; } }; template <> class StaticValue<float> { public: inline static float &default_value(void) throw() { static float val(0.0); return val; } }; template <> class StaticValue<double> { public: inline static double &default_value(void) throw() { static double val(0.0); return val; } }; } template <typename T> class Static { public: static const T &VALUE; }; template <typename T> const T &Static<T>::VALUE(detail::StaticValue<T>::default_value()); }} #endif
#ifndef FLTL_STATIC_HPP_ #define FLTL_STATIC_HPP_ #include <new> namespace fltl { namespace mpl { namespace detail { template <typename T> class StaticValue { public: inline static T &default_value(void) throw() { static T val; static bool is_initialized(false); if(!is_initialized) { is_initialized = true; new (&val) T; } return val; } }; template <typename T> class StaticValue<T *> {
taticValue<unsigned short> { public: inline static unsigned short &default_value(void) throw() { static unsigned short val(0U); return val; } }; template <> class StaticValue<int> { public: inline static int &default_value(void) throw() { static int val(0); return val; } }; template <> class StaticValue<unsigned> { public: inline static unsigned &default_value(void) throw() { static unsigned val(0U); return val; } }; template <> class StaticValue<long> { public: inline static long &default_value(void) throw() { static long val(0L); return val; } }; template <> class StaticValue<unsigned long> { public: inline static unsigned long &default_value(void) throw() { static unsigned long val(0UL); return val; } }; template <> class StaticValue<float> { public: inline static float &default_value(void) throw() { static float val(0.0); return val; } }; template <> class StaticValue<double> { public: inline static double &default_value(void) throw() { static double val(0.0); return val; } }; } template <typename T> class Static { public: static const T &VALUE; }; template <typename T> const T &Static<T>::VALUE(detail::StaticValue<T>::default_value()); }} #endif
public: inline static T *&default_value(void) throw() { static T *val(0); return val; } }; template <> class StaticValue<char> { public: inline static char &default_value(void) throw() { static char val('\0'); return val; } }; template <> class StaticValue<unsigned char> { public: inline static unsigned char &default_value(void) throw() { static unsigned char val(0U); return val; } }; template <> class StaticValue<short> { public: inline static short &default_value(void) throw() { static short val(0); return val; } }; template <> class S
random
[ { "content": " class IfTrue<true,ThenT,ElseT> {\n\n public:\n\n typedef ThenT type;\n\n };\n\n\n\n template <typename T0, typename T2, typename ThenT, typename ElseT>\n", "file_path": "fltl/include/mpl/If.hpp", "rank": 1, "score": 226457.0076507059 }, { "content": " cla...
C++
src/chwSurfaceTweak.cpp
bradleyhenke/chwtools
733e346b4dc6452954b6ba19899d2ccf0a0cd79f
#include "chwSurfaceTweak.h" const MTypeId chwSurfaceTweak::typeId( 0x89007 ); const MString chwSurfaceTweak::typeName( "chwSurfaceTweak" ); MObject chwSurfaceTweak::aInVert; MObject chwSurfaceTweak::aFalloffMode; MObject chwSurfaceTweak::aFalloffCurve; MObject chwSurfaceTweak::aFalloffRadius; MObject chwSurfaceTweak::aRelativeMatrix; MObject chwSurfaceTweak::aDeformMatrix; MObject chwSurfaceTweak::aOutTranslate; MObject chwSurfaceTweak::aOutTranslateX; MObject chwSurfaceTweak::aOutTranslateY; MObject chwSurfaceTweak::aOutTranslateZ; MObject chwSurfaceTweak::aOutRotate; MObject chwSurfaceTweak::aOutRotateX; MObject chwSurfaceTweak::aOutRotateY; MObject chwSurfaceTweak::aOutRotateZ; chwSurfaceTweak::chwSurfaceTweak() { m_data = new chwSurfaceTweakData; } chwSurfaceTweak::~chwSurfaceTweak() { delete m_data; } void* chwSurfaceTweak::creator(){ return new chwSurfaceTweak(); } MStatus chwSurfaceTweak::initialize() { MFnNumericAttribute nAttr; MFnEnumAttribute eAttr; MFnMatrixAttribute mAttr; MRampAttribute rAttr; MFnUnitAttribute uAttr; aInVert = nAttr.create( "vertex", "v", MFnNumericData::kLong ); nAttr.setKeyable(true); nAttr.setStorable(true); nAttr.setMin(0); nAttr.setDefault(0); nAttr.setReadable(true); nAttr.setWritable(true); addAttribute(aInVert); aFalloffMode = eAttr.create( "falloffMode", "fom" ); eAttr.addField( "Volume", 0); eAttr.setKeyable(true); eAttr.setStorable(true); eAttr.setReadable(true); eAttr.setWritable(true); eAttr.setDefault(0); addAttribute(aFalloffMode); aFalloffRadius = nAttr.create( "falloffRadius", "for", MFnNumericData::kFloat, 1.0 ); nAttr.setWritable(true); nAttr.setStorable(true); nAttr.setKeyable (true); nAttr.setConnectable(true); nAttr.setMin(0.0); nAttr.setDefault(1.0); addAttribute(aFalloffRadius); aFalloffCurve = rAttr.createCurveRamp("falloffCurve", "foc"); addAttribute(aFalloffCurve); aRelativeMatrix = mAttr.create( "relativeMatrix", "rm" ); mAttr.setConnectable(true); addAttribute(aRelativeMatrix); aDeformMatrix = mAttr.create( "deformMatrix", "dm" ); mAttr.setConnectable(true); addAttribute(aDeformMatrix); aOutTranslateX = nAttr.create( "outTranslateX", "ostx", MFnNumericData::kDouble, 0.0 ); aOutTranslateY = nAttr.create( "outTranslateY", "osty", MFnNumericData::kDouble, 0.0 ); aOutTranslateZ = nAttr.create( "outTranslateZ", "ostz", MFnNumericData::kDouble, 0.0 ); aOutTranslate = nAttr.create( "outTranslate", "os", aOutTranslateX, aOutTranslateY, aOutTranslateZ ); addAttribute(aOutTranslate); aOutRotateX = uAttr.create( "outRotateX", "osrx", MFnUnitAttribute::kAngle, 0.0 ); aOutRotateY = uAttr.create( "outRotateY", "osry", MFnUnitAttribute::kAngle, 0.0 ); aOutRotateZ = uAttr.create( "outRotateZ", "osrz", MFnUnitAttribute::kAngle, 0.0 ); aOutRotate = nAttr.create( "outRotate", "osr", aOutRotateX, aOutRotateY, aOutRotateZ ); addAttribute(aOutRotate); attributeAffects( chwSurfaceTweak::aInVert, chwSurfaceTweak::aOutTranslate ); attributeAffects( chwSurfaceTweak::aInVert, chwSurfaceTweak::aOutRotate ); attributeAffects( chwSurfaceTweak::inputGeom, chwSurfaceTweak::aOutTranslate ); attributeAffects( chwSurfaceTweak::inputGeom, chwSurfaceTweak::aOutRotate ); attributeAffects( chwSurfaceTweak::aRelativeMatrix, chwSurfaceTweak::outputGeom ); attributeAffects( chwSurfaceTweak::aDeformMatrix, chwSurfaceTweak::outputGeom ); attributeAffects( chwSurfaceTweak::aFalloffMode, chwSurfaceTweak::outputGeom ); attributeAffects( chwSurfaceTweak::aFalloffCurve, chwSurfaceTweak::outputGeom ); attributeAffects( chwSurfaceTweak::aFalloffRadius, chwSurfaceTweak::outputGeom ); MGlobal::executeCommand( "makePaintable -attrType \"multiFloat\" -sm \"deformer\" \"chwSurfaceTweak\" \"weights\";" ); return MStatus::kSuccess; } MStatus chwSurfaceTweak::compute(const MPlug& plug, MDataBlock& data) { MStatus status; MObject thisNode = this->thisMObject(); m_data->m_env = data.inputValue(envelope).asFloat(); m_data->m_vert = data.inputValue( aInVert ).asInt(); if (plug == aOutTranslate || plug == aOutRotate || plug.parent() == aOutTranslate || plug.parent() == aOutRotate ) { MDataHandle outTranslateHnd = data.outputValue( aOutTranslate ); MDataHandle outRotateHnd = data.outputValue( aOutRotate ); MPlug inPlug(thisNode,input); inPlug.selectAncestorLogicalIndex(0,input); MDataHandle hInput = data.inputValue(inPlug, &status); CHECK_MSTATUS_AND_RETURN_IT(status); MDataHandle hGeom = hInput.child(inputGeom); MObject mesh = hGeom.asMesh(); if (!mesh.isNull()) { MFnMesh meshFn(mesh, &status); CHECK_MSTATUS_AND_RETURN_IT(status); m_data->m_numverts = meshFn.numVertices(); status = meshFn.getPoints(m_data->m_points, MSpace::kWorld); CHECK_MSTATUS_AND_RETURN_IT(status); status = meshFn.getVertexNormals(false, m_data->m_normals, MSpace::kWorld); CHECK_MSTATUS_AND_RETURN_IT(status); int prev; MItMeshVertex iter(mesh); iter.setIndex(m_data->m_vert, prev); iter.getConnectedVertices(m_data->m_conids); if (m_data->m_conids.length() > 1) { m_data->m_aimvert = m_data->m_conids[0]; m_data->m_upvert = m_data->m_conids[1]; } else { return MStatus::kFailure; } if (m_data->m_vert < m_data->m_numverts) { MMatrix m; MVector vx, vy, vz; MPoint outTranslate; double outRotate[3]; vx = m_data->m_normals[m_data->m_vert]; vy = (m_data->m_points[m_data->m_upvert] - m_data->m_points[m_data->m_vert]).normal(); vz = (vx ^ vy).normal(); vy = (vx ^ vz).normal(); m[0][0] = vx[0]; m[0][1] = vx[1]; m[0][2] = vx[2]; m[0][3] = 0.f; m[1][0] = vy[0]; m[1][1] = vy[1]; m[1][2] = vy[2]; m[1][3] = 0.f; m[2][0] = vz[0]; m[2][1] = vz[1]; m[2][2] = vz[2]; m[2][3] = 0.f; m[3][0] = m_data->m_points[m_data->m_vert][0]; m[3][1] = m_data->m_points[m_data->m_vert][1]; m[3][2] = m_data->m_points[m_data->m_vert][2]; m[3][3] = 1.f; MTransformationMatrix outMatrix(m); MTransformationMatrix::RotationOrder order; outMatrix.getRotation(outRotate, order, MSpace::kWorld); outTranslate = outMatrix.getTranslation(MSpace::kWorld); outRotateHnd.set3Double(outRotate[0], outRotate[1], outRotate[2]); outTranslateHnd.set3Double(outTranslate[0],outTranslate[1],outTranslate[2]); } else { outTranslateHnd.set(0.0, 0.0, 0.0); outRotateHnd.set(0.0, 0.0, 0.0); } } outTranslateHnd.setClean(); outRotateHnd.setClean(); } else if (plug.attribute() == outputGeom) { unsigned int index = plug.logicalIndex(); MPlug inPlug(thisNode,input); inPlug.selectAncestorLogicalIndex(index,input); MDataHandle hInput = data.inputValue(inPlug); MDataHandle hGeom = hInput.child(inputGeom); m_data->m_localToWorldMatrix = hGeom.geometryTransformMatrix(); MDataHandle hOutput = data.outputValue(plug); hOutput.copy(hGeom); MObject mesh = hGeom.asMesh(); if (!mesh.isNull()) { if (m_data->m_env > 0.0) { m_data->m_falloffMode = data.inputValue( aFalloffMode ).asShort(); m_data->m_falloffRadius = data.inputValue( aFalloffRadius ).asFloat(); m_data->m_falloffCurve = MRampAttribute(thisNode, aFalloffCurve, &status); m_data->m_relativeMatrix = data.inputValue( aRelativeMatrix ).asMatrix(); m_data->m_deformMatrix = data.inputValue( aDeformMatrix ).asMatrix(); m_data->m_relativeInverseMatrix = m_data->m_relativeMatrix.inverse(); m_data->m_localToWorldMatrixInverse = m_data->m_localToWorldMatrix.inverse(); MTransformationMatrix defMat(m_data->m_relativeMatrix); m_data->m_relativeMatrixTranslate = defMat.translation(MSpace::kWorld); MFnMesh meshFn(mesh, &status); CHECK_MSTATUS_AND_RETURN_IT(status); m_data->m_numverts = meshFn.numVertices(); status = meshFn.getPoints(m_data->m_points, MSpace::kWorld); CHECK_MSTATUS_AND_RETURN_IT(status); m_data->m_weights.setLength(m_data->m_numverts); for (unsigned int idx=0; idx < m_data->m_numverts; idx++) { m_data->m_weights[idx]= weightValue(data,index,idx); } ThreadedDeform td; td.data = m_data; parallel_for( blocked_range<int>( 0, m_data->m_numverts ), td ); status = meshFn.setPoints(m_data->m_points, MSpace::kWorld); } } } data.setClean(plug); return status; } MStatus chwSurfaceTweak::postConstructor_initialise_ramp_curve( MObject &rampObj, int index, float position, float value, int interpolation) { MStatus status; MObject thisNode = this->thisMObject(); MPlug rampPlug( thisNode, rampObj ); MPlug elementPlug = rampPlug.elementByLogicalIndex( index, &status ); MPlug positionPlug = elementPlug.child(0, &status); status = positionPlug.setFloat(position); MPlug valuePlug = elementPlug.child(1); status = valuePlug.setFloat(value); MPlug interpPlug = elementPlug.child(2); interpPlug.setInt(interpolation); return MS::kSuccess; } void chwSurfaceTweak::postConstructor() { MStatus status; status = postConstructor_initialise_ramp_curve( aFalloffCurve, 0, 0.0f, 1.0f, 2 ); CHECK_MSTATUS(status); status = postConstructor_initialise_ramp_curve( aFalloffCurve, 1, 1.0f, 0.0f, 2 ); CHECK_MSTATUS(status); }
#include "chwSurfaceTweak.h" const MTypeId chwSurfaceTweak::typeId( 0x89007 ); const MString chwSurfaceTweak::typeName( "chwSurfaceTweak" ); MObject chwSurfaceTweak::aInVert; MObject chwSurfaceTweak::aFalloffMode; MObject chwSurfaceTweak::aFalloffCurve; MObject chwSurfaceTweak::aFalloffRadius; MObject chwSurfaceTweak::aRelativeMatrix; MObject chwSurfaceTweak::aDeformMatrix; MObject chwSurfaceTweak::aOutTranslate; MObject chwSurfaceTweak::aOutTranslateX; MObject chwSurfaceTweak::aOutTranslateY; MObject chwSurfaceTweak::aOutTranslateZ; MObject chwSurfaceTweak::aOutRotate; MObject chwSurfaceTweak::aOutRotateX; MObject chwSurfaceTweak::aOutRotateY; MObject chwSurfaceTweak::aOutRotateZ; chwSurfaceTweak::chwSurfaceTweak() { m_data = new chwSurfaceTweakData; } chwSurfaceTweak::~chwSurfaceTweak() { delete m_data; } void* chwSurfaceTweak::creator(){ return new chwSurfaceTweak(); } MStatus chwSurfaceTweak::initialize() { MFnNumericAttribute nAttr; MFnEnumAttribute eAttr; MFnMatrixAttribute mAttr; MRampAttribute rAttr; MFnUnitAttribute uAttr; aInVert = nAttr.create( "vertex", "v", MFnNumericData::kLong ); nAttr.setKeyable(true); nAttr.setStorable(true); nAttr.setMin(0); nAttr.setDefault(0); nAttr.setReadable(true); nAttr.setWritable(true); addAttribute(aInVert); aFalloffMode = eAttr.create( "falloffMode", "fom" ); eAttr.addField( "Volume", 0); eAttr.setKeyable(true); eAttr.setStorable(true); eAttr.setReadable(true); eAttr.setWritable(true); eAttr.setDefault(0); addAttribute(aFalloffMode); aFalloffRadius = nAttr.create( "falloffRadius", "for", MFnNumericData::kFloat, 1.0 ); nAttr.setWritable(true); nAttr.setStorable(true); nAttr.setKeyable (true); nAttr.setConnectable(true); nAttr.setMin(0.0); nAttr.setDefault(1.0); addAttribute(aFalloffRadius); aFalloffCurve = rAttr.createCurveRamp("falloffCurve", "foc"); addAttribute(aFalloffCurve); aRelativeMatrix = mAttr.create( "relativeMatrix", "rm" ); mAttr.setConnectable(true); addAttribute(aRelativeMatrix); aDeformMatrix = mAttr.create( "deformMatrix", "dm" ); mAttr.setConnectable(true); addAttribute(aDeformMatrix); aOutTranslateX = nAttr.create( "outTranslateX", "ostx", MFnNumericData::kDouble, 0.0 ); aOutTranslateY = nAttr.create( "outTranslateY", "osty", MFnNumericData::kDouble, 0.0 ); aOutTranslateZ = nAttr.create( "outTranslateZ", "ostz", MFnNumericData::kDouble, 0.0 ); aOutTranslate = nAttr.create( "outTranslate", "os", aOutTranslateX, aOutTranslateY, aOutTranslateZ ); addAttribute(aOutTranslate); aOutRotateX = uAttr.create( "outRotateX", "osrx", MFnUnitAttribute::kAngle, 0.0 ); aOutRotateY = uAttr.create( "outRotateY", "osry", MFnUnitAttribute::kAngle, 0.0 ); aOutRotateZ = uAttr.create( "outRotateZ", "osrz", MFnUnitAttribute::kAngle, 0.0 ); aOutRotate = nAttr.create( "outRotate", "osr", aOutRotateX, aOutRotateY, aOutRotateZ ); addAttribute(aOutRotate); attributeAffects( chwSurfaceTweak::aInVert, chwSurfaceTweak::aOutTranslate ); attributeAffects( chwSurfaceTweak::aInVert, chwSurfaceTweak::aOutRotate ); attributeAffects( chwSurfaceTweak::inputGeom, chwSurfaceTweak::aOutTranslate ); attributeAffects( chwSurfaceTweak::inputGeom, chwSurfaceTweak::aOutRotate ); attributeAffects( chwSurfaceTweak::aRelativeMatrix, chwSurfaceTweak::outputGeom ); attributeAffects( chwSurfaceTweak::aDeformMatrix, chwSurfaceTweak::outputGeom ); attributeAffects( chwSurfaceTweak::aFalloffMode, chwSurfaceTweak::outputGeom ); attributeAffects( chwSurfaceTweak::aFalloffCurve, chwSurfaceTweak::outputGeom ); attributeAffects( chwSurfaceTweak::aFalloffRadius, chwSurfaceTweak::outputGeom ); MGlobal::executeCommand( "makePaintable -attrType \"multiFloat\" -sm \"deformer\" \"chwSurfaceTweak\" \"weights\";" ); return MStatus::kSuccess; } MStatus chwSurfaceTweak::compute(const MPlug& plug, MDataBlock& data) { MStatus status; MObject thisNode = this->thisMObject(); m_data->m_env = data.inputValue(envelope).asFloat(); m_data->m_vert = data.inputValue( aInVert ).asInt(); if (plug == aOutTranslate || plug == aOutRotate || plug.parent() == aOutTranslate || plug.parent() == aOutRotate ) { MDataHandle outTranslateHnd = data.outputValue( aOutTranslate ); MDataHandle outRotateHnd = data.outputValue( aOutRotate ); MPlug inPlug(thisNode,input); inPlug.selectAncestorLogicalIndex(0,input); MDataHandle hInput = data.inputValue(inPlug, &status); CHECK_MSTATUS_AND_RETURN_IT(status); MDataHandle hGeom = hInput.child(inputGeom); MObject mesh = hGeom.asMesh(); if (!mesh.isNull()) { MFnMesh meshFn(mesh, &status); CHECK_MSTATUS_AND_RETURN_IT(status); m_data->m_numverts = meshFn.numVertices(); status = meshFn.getPoints(m_data->m_points, MSpace::kWorld); CHECK_MSTATUS_AND_RETURN_IT(status); status = meshFn.getVertexNormals(false, m_data->m_normals, MSpace::kWorld); CHECK_MSTATUS_AND_RETURN_IT(status); int prev; MItMeshVertex iter(mesh); iter.setIndex(m_data->m_vert, prev); iter.getConnectedVertices(m_data->m_conids); if (m_data->m_conids.length() > 1) { m_data->m_aimvert = m_data->m_conids[0]; m_data->m_upvert = m_data->m_conids[1]; } else { return MStatus::kFailure; } if (m_data->m_vert < m_data->m_numverts) { MMatrix m; MVector vx, vy, vz; MPoint outTranslate; double outRotate[3]; vx = m_data->m_normals[m_data->m_vert]; vy = (m_data->m_points[m_data->m_upvert] - m_data->m_points[m_data->m_vert]).normal(); vz = (vx ^ vy).normal(); vy = (vx ^ vz).normal(); m[0][0] = vx[0]; m[0][1] = vx[1]; m[0][2] = vx[2]; m[0][3] = 0.f; m[1][0] = vy[0]; m[1][1] = vy[1]; m[1][2] = vy[2]; m[1][3] = 0.f; m[2][0] = vz[0]; m[2][1] = vz[1]; m[2][2] = vz[2]; m[2][3] = 0.f; m[3][0] = m_data->m_points[m_data->m_vert][0]; m[3][1] = m_data->m_points[m_data->m_vert][1]; m[3][2] = m_data->m_points[m_data->m_vert][2]; m[3][3] = 1.f; MTransformationMatrix outMatrix(m); MTransformationMatrix::RotationOrder order; outMatrix.getRotation(outRotate, order, MSpace::kWorld); outTranslate = outMatrix.getTranslation(MSpace::kWorld); outRotateHnd.set3Double(outRotate[0], outRotate[1], outRotate[2]); outTranslateHnd.set3Double(outTranslate[0],outTranslate[1],outTranslate[2]); } else { outTranslateHnd.set(0.0, 0.0, 0.0); outRotateHnd.set(0.0, 0.0, 0.0); } } outTranslateHnd.setClean(); outRotateHnd.setClean(); } else if (plug.attribute() == outputGeom) { unsigned int index = plug.logicalIndex(); MPlug inPlug(thisNode,input); inPlug.selectAncestorLogicalIndex(index,input); MDataHandle hInput = data.inputValue(inPlug); MDataHandle hGeom = hInput.child(inputGeom); m_data->m_localToWorldMatrix = hGeom.geometryTransformMatrix(); MDataHandle hOutput = data.outputValue(plug); hOutput.copy(hGeom); MObject mesh = hGeom.asMesh(); if (!mesh.isNull()) { if (m_data->m_env > 0.0) { m_data->m_falloffMode = data.inputValue( aFalloffMode ).asShort(); m_data->m_falloffRadius = data.inputValue( aFalloffRadius ).asFloat(); m_data->m_falloffCurve = MRampAttribute(thisNode, aFalloffCurve, &status); m_data->m_relativeMatrix = data.inputValue( aRelativeMatrix ).asMatrix(); m_data->m_deformMatrix = data.inputValue( aDeformMatrix ).asMatrix(); m_data->m_relativeInverseMatrix = m_data->m_relativeMatrix.inverse(); m_data->m_localToWorldMatrixInverse = m_data->m_localToWorldMatrix.inverse(); MTransformationMatrix defMat(m_data->m_relativeMatrix); m_data->m_relativeMatrixTranslate = defMat.translation(MSpace::kWorld); MFnMesh meshFn(mesh, &status); CHECK_MSTATUS_AND_RETURN_IT(status); m_data->m_numverts = meshFn.numVertices(); status = meshFn.getPoints(m_data->m_points, MSpace::kWorld); CHECK_MSTATUS_AND_RETURN_IT(status); m_data->m_weights.setLength(m_data->m_numverts); for (unsigned int idx=0; idx < m_data->m_numverts; idx++) { m_data->m_weights[idx]= weightValue(data,index,idx); } ThreadedDeform td; td.data = m_data; parallel_for( blocked_range<int>( 0, m_data->m_numverts ), td ); status = meshFn.setPoints(m_data->m_points, MSpace::kWorld); } } } data.setClean(plug); return status; }
void chwSurfaceTweak::postConstructor() { MStatus status; status = postConstructor_initialise_ramp_curve( aFalloffCurve, 0, 0.0f, 1.0f, 2 ); CHECK_MSTATUS(status); status = postConstructor_initialise_ramp_curve( aFalloffCurve, 1, 1.0f, 0.0f, 2 ); CHECK_MSTATUS(status); }
MStatus chwSurfaceTweak::postConstructor_initialise_ramp_curve( MObject &rampObj, int index, float position, float value, int interpolation) { MStatus status; MObject thisNode = this->thisMObject(); MPlug rampPlug( thisNode, rampObj ); MPlug elementPlug = rampPlug.elementByLogicalIndex( index, &status ); MPlug positionPlug = elementPlug.child(0, &status); status = positionPlug.setFloat(position); MPlug valuePlug = elementPlug.child(1); status = valuePlug.setFloat(value); MPlug interpPlug = elementPlug.child(2); interpPlug.setInt(interpolation); return MS::kSuccess; }
function_block-full_function
[ { "content": "class chwVertexBindData\n\n{\n\n\tpublic:\n\n\t\tMPointArray\t\tm_drvpoints;\n\n\t\tMPointArray\t\tm_defpoints;\n\n\t\tMFloatArray\t\tm_weights;\n\n\t\tMIntArray\t\tm_mapping;\n\n\t\tMMatrix\t\t\tm_localToWorldMatrix;\n\n\t\tfloat\t\t\tm_cutoffDistance;\n\n\t\tfloat\t\t\tm_searchDistance;\n\n};\n\...
C++
src/transpiler/transpiler.cpp
GeminiLab/afbd
6855eedd6e3b1309adea2071074d0ce0003e6079
#include <transpiler/transpiler.h> #include <llvm/IR/TypeBuilder.h> #include <queue> #include <set> #include <sstream> #include <iostream> using namespace std; using namespace afbd; void print_common_header(fstream &fs) { } shared_ptr<set<shared_ptr<Instruction>>> get_all_instrs(shared_ptr<Instruction> root) { auto _instrs = make_shared<set<shared_ptr<Instruction>>>(); queue<shared_ptr<Instruction>> _instr_to_visit; _instrs->insert(root); _instr_to_visit.push(root); while (!_instr_to_visit.empty()) { auto u = _instr_to_visit.front(); _instr_to_visit.pop(); for (auto& e: *u->succs()) { auto nx = e.first; if (_instrs->find(nx) == _instrs->end()) { _instrs->insert(nx); _instr_to_visit.push(nx); } } } return _instrs; } llvm::Function *Transpiler::transpile_process(shared_ptr<Process> proc) { std::ostringstream ss; ss << "process_" << rand() << "_" << time(nullptr); auto process = llvm::Function::Create( process_type, llvm::GlobalValue::LinkageTypes::ExternalLinkage, ss.str(), m ); llvm::IRBuilder<> builder(context); auto bbEntry = llvm::BasicBlock::Create(context, "", process); auto bbLoop = llvm::BasicBlock::Create(context, "", process); llvm::BasicBlock* bbEnd; if (proc->type() == ProcessType::Always) { bbEnd = bbLoop; } else { bbEnd = llvm::BasicBlock::Create(context, "", process); } builder.SetInsertPoint(bbEntry); auto sim = process->arg_begin(); map<shared_ptr<Var>, llvm::Value*> varAddr; for (auto &v: *var_id) { varAddr[v.first] = builder.CreateInBoundsGEP(sim, llvm::ArrayRef<llvm::Value*> { builder.getInt32(0), builder.getInt32(v.second) }); } function<llvm::Value*(shared_ptr<Expr>)> eval = [&](shared_ptr<Expr> expr) -> llvm::Value* { auto type = expr->type(); if (type == ExprType::VAR) { return builder.CreateLoad(varAddr[expr->as_var()]); } else if (type == ExprType::CONSTANT) { return builder.getInt32(expr->as_constant()->value()); } else { if (type == ExprType::NOT) { return builder.CreateNot(eval(expr->get_operand(0))); } else if (type == ExprType::REDUCE_BOOL) { return builder.CreateIntCast(eval(expr->get_operand(0)), builder.getInt32Ty(), false); } else if (type == ExprType::COND) { return builder.CreateSelect(eval(expr->get_operand(0)), eval(expr->get_operand(1)), eval(expr->get_operand(2))); } else { auto opl = eval(expr->get_operand(0)); auto opr = eval(expr->get_operand(1)); switch (type) { case ExprType::ADD: return builder.CreateAdd(opl, opr); case ExprType::SUB: return builder.CreateSub(opl, opr); case ExprType::MUL: return builder.CreateMul(opl, opr); case ExprType::DIV: return builder.CreateUDiv(opl, opr); case ExprType::MOD: return builder.CreateURem(opl, opr); case ExprType::EQ: return builder.CreateICmpEQ(opl, opr); case ExprType::NE: return builder.CreateICmpNE(opl, opr); case ExprType::GT: return builder.CreateICmpUGT(opl, opr); case ExprType::GE: return builder.CreateICmpUGE(opl, opr); case ExprType::LT: return builder.CreateICmpULT(opl, opr); case ExprType::LE: return builder.CreateICmpULE(opl, opr); case ExprType::AND: return builder.CreateAnd(opl, opr); case ExprType::OR: return builder.CreateOr(opl, opr); case ExprType::XOR: return builder.CreateXor(opl, opr); case ExprType::SHL: return builder.CreateShl(opl, opr); case ExprType::LSHR: return builder.CreateLShr(opl, opr); case ExprType::ASHR: return builder.CreateAShr(opl, opr); } } } }; function<llvm::Value*(llvm::Value*, int32_t)> shrink_to_width = [&](llvm::Value *v, int32_t width) -> llvm::Value* { return builder.CreateAnd(v, builder.getInt32((uint32_t)((1ull << width) - 1))); }; auto instrs = get_all_instrs(proc->begin()); map<shared_ptr<Instruction>, llvm::BasicBlock*> instr_bb; for (auto &x: *instrs) { instr_bb[x] = llvm::BasicBlock::Create(context, "", process); } builder.CreateBr(bbLoop); builder.SetInsertPoint(bbLoop); builder.CreateBr(instr_bb[proc->begin()]); for (auto &x: *instrs) { builder.SetInsertPoint(instr_bb[x]); auto type = x->type(); auto instr_delay = x->delay(); auto has_delay = instr_delay >= 0; instr_delay = has_delay ? instr_delay : 0; if (type == InstructionType::Delay) { if (instr_delay > 0) { builder.CreateCall(delay, llvm::ArrayRef<llvm::Value*> { builder.getInt32(instr_delay) }); } } else if (type == InstructionType::Trigger) { if (x->triggers()->size() > 0) { builder.CreateCall(prepare_wait); for (auto &w: *x->triggers()) { builder.CreateCall( add_wait, llvm::ArrayRef<llvm::Value*> { builder.getInt32(var_id->at(w.first)), builder.getInt32((int32_t)w.second), } ); } builder.CreateCall(do_wait); } } else { auto assign_type = x->assign_type(); auto dst = x->dst()->as_var(); if (assign_type == AssignType::Blocking) { if (has_delay) { auto temp = builder.CreateAlloca(builder.getInt32Ty()); builder.CreateStore(shrink_to_width(eval(x->expr()), dst->bit()), temp); if (instr_delay == 0) { builder.CreateCall(delay_for_explicit_zero_delay); } else { builder.CreateCall(delay, llvm::ArrayRef<llvm::Value*> { builder.getInt32(instr_delay) }); } builder.CreateCall( update, llvm::ArrayRef<llvm::Value*> { varAddr[x->dst()->as_var()], builder.CreateLoad(temp), builder.getInt32(var_id->at(dst)), } ); } else { builder.CreateCall( update, llvm::ArrayRef<llvm::Value*> { varAddr[x->dst()->as_var()], shrink_to_width(eval(x->expr()), dst->bit()), builder.getInt32(var_id->at(dst)), } ); } } else { builder.CreateCall( delayed_nonblocking_assign_update, llvm::ArrayRef<llvm::Value*> { varAddr[x->dst()->as_var()], shrink_to_width(eval(x->expr()), dst->bit()), builder.getInt32(var_id->at(dst)), builder.getInt32(instr_delay), } ); } } auto bbcd = llvm::BasicBlock::Create(context, "", process); builder.CreateBr(bbcd); builder.SetInsertPoint(bbcd); bool end = false; for (auto &s: *x->succs()) { auto instr = s.first; auto cond = s.second; if (cond == nullptr) { builder.CreateBr(instr_bb[instr]); end = true; break; } else { bbcd = llvm::BasicBlock::Create(context, "", process); builder.CreateCondBr(eval(cond), instr_bb[instr], bbcd); builder.SetInsertPoint(bbcd); } } if (!end) builder.CreateBr(bbEnd); } if (bbEnd != bbLoop) { builder.SetInsertPoint(bbEnd); builder.CreateCall(process_end); builder.CreateRetVoid(); } return process; } void Transpiler::load_static_functions() { auto voidTy = llvm::TypeBuilder<void, false>::get(context); auto tickTy = llvm::TypeBuilder<int32_t, false>::get(context); auto valTy = llvm::TypeBuilder<int32_t, false>::get(context); auto valPtrTy = valTy->getPointerTo(); auto varIdTy = llvm::TypeBuilder<int32_t, false>::get(context); auto edgeTy = llvm::TypeBuilder<int32_t, false>::get(context); process_type = llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type *>{sim_type->getPointerTo()}, false ); set_var_count = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type *>{varIdTy}, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "set_var_count", m ); push_process = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type *>{process_type->getPointerTo(), sim_type->getPointerTo()}, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "push_process", m ); process_end = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type *>{}, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "process_end", m ); reset = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type *>{}, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "reset", m ); delay = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type*> { tickTy }, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "delay", m ); delay_for_explicit_zero_delay = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type *>{}, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "delay_for_explicit_zero_delay", m ); delay_for_nonblocking_assign_update = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type*> { tickTy }, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "delay_for_nonblocking_assign_update", m ); delayed_nonblocking_assign_update = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type*> { valPtrTy, valTy, varIdTy, tickTy }, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "delayed_nonblocking_assign_update", m ); prepare_wait = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type *>{}, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "prepare_wait", m ); add_wait = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type *>{ varIdTy, edgeTy }, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "add_wait", m ); do_wait = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type *>{}, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "do_wait", m ); update = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type*> { valPtrTy, valTy, varIdTy }, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "update", m ); } llvm::Module *Transpiler::transpile(shared_ptr<Module> module, shared_ptr<fstream> fs) { auto simName = "sim_" + module->name(); m = new llvm::Module("sim_" + simName, context); llvm::IRBuilder<> builder(context); print_common_header(*fs); var_id = make_shared<map<shared_ptr<Var>, int>>(); *fs << "struct " << simName << " {" << endl; vector<llvm::Type *> member; for (auto &var: *module->vars()) { (*var_id)[var] = member.size(); member.push_back(builder.getInt32Ty()); *fs << "int " << *var->name() << ";" << endl; } *fs << "};" << endl; sim_type = llvm::StructType::create(context, llvm::ArrayRef<llvm::Type *>(member), simName); auto initializer = llvm::Function::Create( llvm::FunctionType::get(builder.getVoidTy(), llvm::ArrayRef<llvm::Type *>{sim_type->getPointerTo()}, false), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "initialize_sim", m ); *fs << "extern \"C\" void initialize_sim(" << simName << "*);" << endl; load_static_functions(); auto bb = llvm::BasicBlock::Create(context, "", initializer); builder.SetInsertPoint(bb); initializer->arg_begin()->setName("s"); builder.CreateCall(set_var_count, llvm::ArrayRef<llvm::Value*> { builder.getInt32(module->vars()->size()) }); for (auto &proc: *module->procs()) { builder.CreateCall(push_process, llvm::ArrayRef<llvm::Value*> { transpile_process(proc), initializer->arg_begin() }); } builder.CreateRetVoid(); fs->close(); return m; }
#include <transpiler/transpiler.h> #include <llvm/IR/TypeBuilder.h> #include <queue> #include <set> #include <sstream> #include <iostream> using namespace std; using namespace afbd; void print_common_header(fstream &fs) { } shared_ptr<set<shared_ptr<Instruction>>> get_all_instrs(shared_ptr<Instruction> root) { auto _instrs = make_shared<set<shared_ptr<Instruction>>>(); queue<shared_ptr<Instruction>> _instr_to_visit; _instrs->insert(root); _instr_to_visit.push(root); while (!_instr_to_visit.empty()) { auto u = _instr_to_visit.front(); _instr_to_visit.pop(); for (auto& e: *u->succs()) { auto nx = e.first; if (_instrs->find(nx) == _instrs->end()) { _instrs->insert(nx); _instr_to_visit.push(nx); } } } return _instrs; } llvm::Function *Transpiler::transpile_process(shared_ptr<Process> proc) { std::ostringstream ss; ss << "process_" << rand() << "_" << time(nullptr); auto process = llvm::Function::Create( process_type, llvm::GlobalValue::LinkageTypes::ExternalLinkage, ss.str(), m ); llvm::IRBuilder<> builder(context); auto bbEntry = llvm::BasicBlock::Create(context, "", process); auto bbLoop = llvm::BasicBlock::Create(context, "", process); llvm::BasicBlock* bbEnd; if (proc->type() == ProcessType::Always) { bbEnd = bbLoop; } else { bbEnd = llvm::BasicBlock::Create(context, "", process); } builder.SetInsertPoint(bbEntry); auto sim = process->arg_begin(); map<shared_ptr<Var>, llvm::Value*> varAddr; for (auto &v: *var_id) { varAddr[v.first] = builder.CreateInBoundsGEP(sim, llvm::ArrayRef<llvm::Value*> { builder.getInt32(0), builder.getInt32(v.second) }); } function<llvm::Value*(shared_ptr<Expr>)> eval = [&](shared_ptr<Expr> expr) -> llvm::Value* { auto type = expr->type(); if (type == ExprType::VAR) { return builder.CreateLoad(varAddr[expr->as_var()]); } else if (type == ExprType::CONSTANT) { return builder.getInt32(expr->as_constant()->value()); } else { if (type == ExprType::NOT) { return builder.CreateNot(eval(expr->get_operand(0))); } else if (type == ExprType::REDUCE_BOOL) { return builder.CreateIntCast(eval(expr->get_operand(0)), builder.getInt32Ty(), false); } else if (type == ExprType::COND) { return builder.CreateSelect(eval(expr->get_operand(0)), eval(expr->get_operand(1)), eval(expr->get_operand(2))); } else { auto opl = eval(expr->get_operand(0)); auto opr = eval(expr->get_operand(1)); switch (type) { case ExprType::ADD: return builder.CreateAdd(opl, opr); case ExprType::SUB: return builder.CreateSub(opl, opr); case ExprType::MUL: return builder.CreateMul(opl, opr); case ExprType::DIV: return builder.CreateUDiv(opl, opr); case ExprType::MOD: return builder.CreateURem(opl, opr); case ExprType::EQ: return builder.CreateICmpEQ(opl, opr); case ExprType::NE: return builder.CreateICmpNE(opl, opr); case ExprType::GT: return builder.CreateICmpUGT(opl, opr); case ExprType::GE: return builder.CreateICmpUGE(opl, opr); case ExprType::LT: return builder.CreateICmpULT(opl, opr); case ExprType::LE: return builder.CreateICmpULE(opl, opr); case ExprType::AND: return builder.CreateAnd(opl, opr); case ExprType::OR: return builder.CreateOr(opl, opr); case ExprType::XOR: return builder.CreateXor(opl, opr); case ExprType::SHL: return builder.CreateShl(opl, opr); case ExprType::LSHR: return builder.CreateLShr(opl, opr); case ExprType::ASHR: return builder.CreateAShr(opl, opr); } } } }; function<llvm::Value*(llvm::Value*, int32_t)> shrink_to_width = [&](llvm::Value *v, int32_t width) -> llvm::Value* { return builder.CreateAnd(v, builder.getInt32((uint32_t)((1ull << width) - 1))); }; auto instrs = get_all_instrs(proc->begin()); map<shared_ptr<Instruction>, llvm::BasicBlock*> instr_bb; for (auto &x: *instrs) { instr_bb[x] = llvm::BasicBlock::Create(context, "", process); } builder.CreateBr(bbLoop); builder.SetInsertPoint(bbLoop); builder.CreateBr(instr_bb[proc->begin()]); for (auto &x: *instrs) { builder.SetInsertPoint(instr_bb[x]); auto type = x->type(); auto instr_delay = x->delay(); auto has_delay = instr_delay >= 0; instr_delay = has_delay ? instr_delay : 0; if (type == InstructionType::Delay) { if (instr_delay > 0) { builder.CreateCall(delay, llvm::ArrayRef<llvm::Value*> { builder.getInt32(instr_delay) }); } } else if (type == InstructionType::Trigger) { if
process_type = llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type *>{sim_type->getPointerTo()}, false ); set_var_count = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type *>{varIdTy}, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "set_var_count", m ); push_process = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type *>{process_type->getPointerTo(), sim_type->getPointerTo()}, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "push_process", m ); process_end = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type *>{}, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "process_end", m ); reset = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type *>{}, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "reset", m ); delay = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type*> { tickTy }, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "delay", m ); delay_for_explicit_zero_delay = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type *>{}, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "delay_for_explicit_zero_delay", m ); delay_for_nonblocking_assign_update = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type*> { tickTy }, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "delay_for_nonblocking_assign_update", m ); delayed_nonblocking_assign_update = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type*> { valPtrTy, valTy, varIdTy, tickTy }, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "delayed_nonblocking_assign_update", m ); prepare_wait = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type *>{}, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "prepare_wait", m ); add_wait = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type *>{ varIdTy, edgeTy }, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "add_wait", m ); do_wait = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type *>{}, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "do_wait", m ); update = llvm::Function::Create( llvm::FunctionType::get( voidTy, llvm::ArrayRef<llvm::Type*> { valPtrTy, valTy, varIdTy }, false ), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "update", m ); } llvm::Module *Transpiler::transpile(shared_ptr<Module> module, shared_ptr<fstream> fs) { auto simName = "sim_" + module->name(); m = new llvm::Module("sim_" + simName, context); llvm::IRBuilder<> builder(context); print_common_header(*fs); var_id = make_shared<map<shared_ptr<Var>, int>>(); *fs << "struct " << simName << " {" << endl; vector<llvm::Type *> member; for (auto &var: *module->vars()) { (*var_id)[var] = member.size(); member.push_back(builder.getInt32Ty()); *fs << "int " << *var->name() << ";" << endl; } *fs << "};" << endl; sim_type = llvm::StructType::create(context, llvm::ArrayRef<llvm::Type *>(member), simName); auto initializer = llvm::Function::Create( llvm::FunctionType::get(builder.getVoidTy(), llvm::ArrayRef<llvm::Type *>{sim_type->getPointerTo()}, false), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "initialize_sim", m ); *fs << "extern \"C\" void initialize_sim(" << simName << "*);" << endl; load_static_functions(); auto bb = llvm::BasicBlock::Create(context, "", initializer); builder.SetInsertPoint(bb); initializer->arg_begin()->setName("s"); builder.CreateCall(set_var_count, llvm::ArrayRef<llvm::Value*> { builder.getInt32(module->vars()->size()) }); for (auto &proc: *module->procs()) { builder.CreateCall(push_process, llvm::ArrayRef<llvm::Value*> { transpile_process(proc), initializer->arg_begin() }); } builder.CreateRetVoid(); fs->close(); return m; }
(x->triggers()->size() > 0) { builder.CreateCall(prepare_wait); for (auto &w: *x->triggers()) { builder.CreateCall( add_wait, llvm::ArrayRef<llvm::Value*> { builder.getInt32(var_id->at(w.first)), builder.getInt32((int32_t)w.second), } ); } builder.CreateCall(do_wait); } } else { auto assign_type = x->assign_type(); auto dst = x->dst()->as_var(); if (assign_type == AssignType::Blocking) { if (has_delay) { auto temp = builder.CreateAlloca(builder.getInt32Ty()); builder.CreateStore(shrink_to_width(eval(x->expr()), dst->bit()), temp); if (instr_delay == 0) { builder.CreateCall(delay_for_explicit_zero_delay); } else { builder.CreateCall(delay, llvm::ArrayRef<llvm::Value*> { builder.getInt32(instr_delay) }); } builder.CreateCall( update, llvm::ArrayRef<llvm::Value*> { varAddr[x->dst()->as_var()], builder.CreateLoad(temp), builder.getInt32(var_id->at(dst)), } ); } else { builder.CreateCall( update, llvm::ArrayRef<llvm::Value*> { varAddr[x->dst()->as_var()], shrink_to_width(eval(x->expr()), dst->bit()), builder.getInt32(var_id->at(dst)), } ); } } else { builder.CreateCall( delayed_nonblocking_assign_update, llvm::ArrayRef<llvm::Value*> { varAddr[x->dst()->as_var()], shrink_to_width(eval(x->expr()), dst->bit()), builder.getInt32(var_id->at(dst)), builder.getInt32(instr_delay), } ); } } auto bbcd = llvm::BasicBlock::Create(context, "", process); builder.CreateBr(bbcd); builder.SetInsertPoint(bbcd); bool end = false; for (auto &s: *x->succs()) { auto instr = s.first; auto cond = s.second; if (cond == nullptr) { builder.CreateBr(instr_bb[instr]); end = true; break; } else { bbcd = llvm::BasicBlock::Create(context, "", process); builder.CreateCondBr(eval(cond), instr_bb[instr], bbcd); builder.SetInsertPoint(bbcd); } } if (!end) builder.CreateBr(bbEnd); } if (bbEnd != bbLoop) { builder.SetInsertPoint(bbEnd); builder.CreateCall(process_end); builder.CreateRetVoid(); } return process; } void Transpiler::load_static_functions() { auto voidTy = llvm::TypeBuilder<void, false>::get(context); auto tickTy = llvm::TypeBuilder<int32_t, false>::get(context); auto valTy = llvm::TypeBuilder<int32_t, false>::get(context); auto valPtrTy = valTy->getPointerTo(); auto varIdTy = llvm::TypeBuilder<int32_t, false>::get(context); auto edgeTy = llvm::TypeBuilder<int32_t, false>::get(context);
random
[ { "content": "class SigSet<T, typename std::enable_if<!std::is_pointer<T>::value>::type> : public SigSet<T, std::less<T>> {};\n\ntemplate<typename T>\n\nusing sort_by_name_id_guard = typename std::enable_if<std::is_same<T,RTLIL::Cell*>::value>::type;\n\ntemplate<typename T>\n", "file_path": "3rd/yosys/inclu...
C++
Editor/HairParticleWindow.cpp
mewbak/WickedEngine
572bc7836fa14793b1c3b3b4733ddc61f1da5887
#include "stdafx.h" #include "HairParticleWindow.h" using namespace std; using namespace wiECS; using namespace wiScene; HairParticleWindow::HairParticleWindow(wiGUI* gui) : GUI(gui) { assert(GUI && "Invalid GUI!"); float screenW = (float)wiRenderer::GetDevice()->GetScreenWidth(); float screenH = (float)wiRenderer::GetDevice()->GetScreenHeight(); hairWindow = new wiWindow(GUI, "Hair Particle System Window"); hairWindow->SetSize(XMFLOAT2(800, 600)); GUI->AddWidget(hairWindow); float x = 150; float y = 20; float step = 35; addButton = new wiButton("Add Hair Particle System"); addButton->SetPos(XMFLOAT2(x, y += step)); addButton->SetSize(XMFLOAT2(200, 30)); addButton->OnClick([&](wiEventArgs args) { Scene& scene = wiScene::GetScene(); scene.Entity_CreateHair("editorHair"); }); addButton->SetTooltip("Add new hair particle system."); hairWindow->AddWidget(addButton); meshComboBox = new wiComboBox("Mesh: "); meshComboBox->SetSize(XMFLOAT2(300, 25)); meshComboBox->SetPos(XMFLOAT2(x, y += step)); meshComboBox->SetEnabled(false); meshComboBox->OnSelect([&](wiEventArgs args) { auto hair = GetHair(); if (hair != nullptr) { if (args.iValue == 0) { hair->meshID = INVALID_ENTITY; } else { Scene& scene = wiScene::GetScene(); hair->meshID = scene.meshes.GetEntity(args.iValue - 1); } } }); meshComboBox->SetTooltip("Choose a mesh where hair will grow from..."); hairWindow->AddWidget(meshComboBox); countSlider = new wiSlider(0, 100000, 1000, 100000, "Strand Count: "); countSlider->SetSize(XMFLOAT2(360, 30)); countSlider->SetPos(XMFLOAT2(x, y += step * 2)); countSlider->OnSlide([&](wiEventArgs args) { auto hair = GetHair(); if (hair != nullptr) { hair->strandCount = (uint32_t)args.iValue; } }); countSlider->SetEnabled(false); countSlider->SetTooltip("Set hair strand count"); hairWindow->AddWidget(countSlider); lengthSlider = new wiSlider(0, 4, 1, 100000, "Particle Length: "); lengthSlider->SetSize(XMFLOAT2(360, 30)); lengthSlider->SetPos(XMFLOAT2(x, y += step)); lengthSlider->OnSlide([&](wiEventArgs args) { auto hair = GetHair(); if (hair != nullptr) { hair->length = args.fValue; } }); lengthSlider->SetEnabled(false); lengthSlider->SetTooltip("Set hair strand length"); hairWindow->AddWidget(lengthSlider); stiffnessSlider = new wiSlider(0, 20, 5, 100000, "Particle Stiffness: "); stiffnessSlider->SetSize(XMFLOAT2(360, 30)); stiffnessSlider->SetPos(XMFLOAT2(x, y += step * 2)); stiffnessSlider->OnSlide([&](wiEventArgs args) { auto hair = GetHair(); if (hair != nullptr) { hair->stiffness = args.fValue; } }); stiffnessSlider->SetEnabled(false); stiffnessSlider->SetTooltip("Set hair strand stiffness, how much it tries to get back to rest position."); hairWindow->AddWidget(stiffnessSlider); randomnessSlider = new wiSlider(0, 1, 0.2f, 100000, "Particle Randomness: "); randomnessSlider->SetSize(XMFLOAT2(360, 30)); randomnessSlider->SetPos(XMFLOAT2(x, y += step)); randomnessSlider->OnSlide([&](wiEventArgs args) { auto hair = GetHair(); if (hair != nullptr) { hair->randomness = args.fValue; } }); randomnessSlider->SetEnabled(false); randomnessSlider->SetTooltip("Set hair length randomization factor. This will affect randomness of hair lengths."); hairWindow->AddWidget(randomnessSlider); segmentcountSlider = new wiSlider(1, 10, 1, 9, "Segment Count: "); segmentcountSlider->SetSize(XMFLOAT2(360, 30)); segmentcountSlider->SetPos(XMFLOAT2(x, y += step)); segmentcountSlider->OnSlide([&](wiEventArgs args) { auto hair = GetHair(); if (hair != nullptr) { hair->segmentCount = (uint32_t)args.iValue; } }); segmentcountSlider->SetEnabled(false); segmentcountSlider->SetTooltip("Set hair strand segment count. This will affect simulation quality and performance."); hairWindow->AddWidget(segmentcountSlider); randomSeedSlider = new wiSlider(1, 12345, 1, 12344, "Random seed: "); randomSeedSlider->SetSize(XMFLOAT2(360, 30)); randomSeedSlider->SetPos(XMFLOAT2(x, y += step)); randomSeedSlider->OnSlide([&](wiEventArgs args) { auto hair = GetHair(); if (hair != nullptr) { hair->randomSeed = (uint32_t)args.iValue; } }); randomSeedSlider->SetEnabled(false); randomSeedSlider->SetTooltip("Set hair system-wide random seed value. This will affect hair patch placement randomization."); hairWindow->AddWidget(randomSeedSlider); viewDistanceSlider = new wiSlider(0, 1000, 100, 10000, "View distance: "); viewDistanceSlider->SetSize(XMFLOAT2(360, 30)); viewDistanceSlider->SetPos(XMFLOAT2(x, y += step)); viewDistanceSlider->OnSlide([&](wiEventArgs args) { auto hair = GetHair(); if (hair != nullptr) { hair->viewDistance = args.fValue; } }); viewDistanceSlider->SetEnabled(false); viewDistanceSlider->SetTooltip("Set view distance. After this, particles will be faded out."); hairWindow->AddWidget(viewDistanceSlider); hairWindow->Translate(XMFLOAT3(200, 50, 0)); hairWindow->SetVisible(false); SetEntity(entity); } HairParticleWindow::~HairParticleWindow() { hairWindow->RemoveWidgets(true); GUI->RemoveWidget(hairWindow); SAFE_DELETE(hairWindow); } void HairParticleWindow::SetEntity(Entity entity) { this->entity = entity; auto hair = GetHair(); if (hair != nullptr) { lengthSlider->SetValue(hair->length); stiffnessSlider->SetValue(hair->stiffness); randomnessSlider->SetValue(hair->randomness); countSlider->SetValue((float)hair->strandCount); segmentcountSlider->SetValue((float)hair->segmentCount); randomSeedSlider->SetValue((float)hair->randomSeed); viewDistanceSlider->SetValue(hair->viewDistance); } else { } } wiHairParticle* HairParticleWindow::GetHair() { if (entity == INVALID_ENTITY) { return nullptr; } Scene& scene = wiScene::GetScene(); wiHairParticle* hair = scene.hairs.GetComponent(entity); return hair; } void HairParticleWindow::UpdateData() { auto emitter = GetHair(); if (emitter == nullptr) { return; } Scene& scene = wiScene::GetScene(); meshComboBox->ClearItems(); meshComboBox->AddItem("NO MESH"); for (size_t i = 0; i < scene.meshes.GetCount(); ++i) { Entity entity = scene.meshes.GetEntity(i); const NameComponent& name = *scene.names.GetComponent(entity); meshComboBox->AddItem(name.name); if (emitter->meshID == entity) { meshComboBox->SetSelected((int)i + 1); } } }
#include "stdafx.h" #include "HairParticleWindow.h" using namespace std; using namespace wiECS; using namespace wiScene; HairParticleWindow::HairParticleWindow(wiGUI* gui) : GUI(gui) { assert(GUI && "Invalid GUI!"); float screenW = (float)wiRenderer::GetDevice()->GetScreenWidth(); float screenH = (float)wiRenderer::GetDevice()->GetScreenHeight(); hairWindow = new wiWindow(GUI, "Hair Particle System Window"); hairWindow->SetSize(XMFLOAT2(800, 600)); GUI->AddWidget(hairWindow); float x = 150; float y = 20; float step = 35; addButton = new wiButton("Add Hair Particle System"); addButton->SetPos(XMFLOAT2(x, y += step)); addButton->SetSize(XMFLOAT2(200, 30));
; addButton->SetTooltip("Add new hair particle system."); hairWindow->AddWidget(addButton); meshComboBox = new wiComboBox("Mesh: "); meshComboBox->SetSize(XMFLOAT2(300, 25)); meshComboBox->SetPos(XMFLOAT2(x, y += step)); meshComboBox->SetEnabled(false); meshComboBox->OnSelect([&](wiEventArgs args) { auto hair = GetHair(); if (hair != nullptr) { if (args.iValue == 0) { hair->meshID = INVALID_ENTITY; } else { Scene& scene = wiScene::GetScene(); hair->meshID = scene.meshes.GetEntity(args.iValue - 1); } } }); meshComboBox->SetTooltip("Choose a mesh where hair will grow from..."); hairWindow->AddWidget(meshComboBox); countSlider = new wiSlider(0, 100000, 1000, 100000, "Strand Count: "); countSlider->SetSize(XMFLOAT2(360, 30)); countSlider->SetPos(XMFLOAT2(x, y += step * 2)); countSlider->OnSlide([&](wiEventArgs args) { auto hair = GetHair(); if (hair != nullptr) { hair->strandCount = (uint32_t)args.iValue; } }); countSlider->SetEnabled(false); countSlider->SetTooltip("Set hair strand count"); hairWindow->AddWidget(countSlider); lengthSlider = new wiSlider(0, 4, 1, 100000, "Particle Length: "); lengthSlider->SetSize(XMFLOAT2(360, 30)); lengthSlider->SetPos(XMFLOAT2(x, y += step)); lengthSlider->OnSlide([&](wiEventArgs args) { auto hair = GetHair(); if (hair != nullptr) { hair->length = args.fValue; } }); lengthSlider->SetEnabled(false); lengthSlider->SetTooltip("Set hair strand length"); hairWindow->AddWidget(lengthSlider); stiffnessSlider = new wiSlider(0, 20, 5, 100000, "Particle Stiffness: "); stiffnessSlider->SetSize(XMFLOAT2(360, 30)); stiffnessSlider->SetPos(XMFLOAT2(x, y += step * 2)); stiffnessSlider->OnSlide([&](wiEventArgs args) { auto hair = GetHair(); if (hair != nullptr) { hair->stiffness = args.fValue; } }); stiffnessSlider->SetEnabled(false); stiffnessSlider->SetTooltip("Set hair strand stiffness, how much it tries to get back to rest position."); hairWindow->AddWidget(stiffnessSlider); randomnessSlider = new wiSlider(0, 1, 0.2f, 100000, "Particle Randomness: "); randomnessSlider->SetSize(XMFLOAT2(360, 30)); randomnessSlider->SetPos(XMFLOAT2(x, y += step)); randomnessSlider->OnSlide([&](wiEventArgs args) { auto hair = GetHair(); if (hair != nullptr) { hair->randomness = args.fValue; } }); randomnessSlider->SetEnabled(false); randomnessSlider->SetTooltip("Set hair length randomization factor. This will affect randomness of hair lengths."); hairWindow->AddWidget(randomnessSlider); segmentcountSlider = new wiSlider(1, 10, 1, 9, "Segment Count: "); segmentcountSlider->SetSize(XMFLOAT2(360, 30)); segmentcountSlider->SetPos(XMFLOAT2(x, y += step)); segmentcountSlider->OnSlide([&](wiEventArgs args) { auto hair = GetHair(); if (hair != nullptr) { hair->segmentCount = (uint32_t)args.iValue; } }); segmentcountSlider->SetEnabled(false); segmentcountSlider->SetTooltip("Set hair strand segment count. This will affect simulation quality and performance."); hairWindow->AddWidget(segmentcountSlider); randomSeedSlider = new wiSlider(1, 12345, 1, 12344, "Random seed: "); randomSeedSlider->SetSize(XMFLOAT2(360, 30)); randomSeedSlider->SetPos(XMFLOAT2(x, y += step)); randomSeedSlider->OnSlide([&](wiEventArgs args) { auto hair = GetHair(); if (hair != nullptr) { hair->randomSeed = (uint32_t)args.iValue; } }); randomSeedSlider->SetEnabled(false); randomSeedSlider->SetTooltip("Set hair system-wide random seed value. This will affect hair patch placement randomization."); hairWindow->AddWidget(randomSeedSlider); viewDistanceSlider = new wiSlider(0, 1000, 100, 10000, "View distance: "); viewDistanceSlider->SetSize(XMFLOAT2(360, 30)); viewDistanceSlider->SetPos(XMFLOAT2(x, y += step)); viewDistanceSlider->OnSlide([&](wiEventArgs args) { auto hair = GetHair(); if (hair != nullptr) { hair->viewDistance = args.fValue; } }); viewDistanceSlider->SetEnabled(false); viewDistanceSlider->SetTooltip("Set view distance. After this, particles will be faded out."); hairWindow->AddWidget(viewDistanceSlider); hairWindow->Translate(XMFLOAT3(200, 50, 0)); hairWindow->SetVisible(false); SetEntity(entity); } HairParticleWindow::~HairParticleWindow() { hairWindow->RemoveWidgets(true); GUI->RemoveWidget(hairWindow); SAFE_DELETE(hairWindow); } void HairParticleWindow::SetEntity(Entity entity) { this->entity = entity; auto hair = GetHair(); if (hair != nullptr) { lengthSlider->SetValue(hair->length); stiffnessSlider->SetValue(hair->stiffness); randomnessSlider->SetValue(hair->randomness); countSlider->SetValue((float)hair->strandCount); segmentcountSlider->SetValue((float)hair->segmentCount); randomSeedSlider->SetValue((float)hair->randomSeed); viewDistanceSlider->SetValue(hair->viewDistance); } else { } } wiHairParticle* HairParticleWindow::GetHair() { if (entity == INVALID_ENTITY) { return nullptr; } Scene& scene = wiScene::GetScene(); wiHairParticle* hair = scene.hairs.GetComponent(entity); return hair; } void HairParticleWindow::UpdateData() { auto emitter = GetHair(); if (emitter == nullptr) { return; } Scene& scene = wiScene::GetScene(); meshComboBox->ClearItems(); meshComboBox->AddItem("NO MESH"); for (size_t i = 0; i < scene.meshes.GetCount(); ++i) { Entity entity = scene.meshes.GetEntity(i); const NameComponent& name = *scene.names.GetComponent(entity); meshComboBox->AddItem(name.name); if (emitter->meshID == entity) { meshComboBox->SetSelected((int)i + 1); } } }
addButton->OnClick([&](wiEventArgs args) { Scene& scene = wiScene::GetScene(); scene.Entity_CreateHair("editorHair"); })
call_expression
[ { "content": "class wiGUI;\n", "file_path": "Editor/HairParticleWindow.h", "rank": 0, "score": 231629.97973045165 }, { "content": "class HairParticleWindow\n\n{\n\npublic:\n\n\tHairParticleWindow(wiGUI* gui);\n\n\t~HairParticleWindow();\n\n\n\n\twiECS::Entity entity;\n\n\tvoid SetEntity(wiEC...
C++
libmarch/include/march/python/wrapper_core.hpp
j8xixo12/solvcon
a8bf3a54d4b1ed91d292e0cdbcb6f2710d33d99a
#pragma once #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <utility> #include <memory> #include <vector> #include <algorithm> #include <cstring> #include "march.hpp" #include "march/python/WrapBase.hpp" namespace march { namespace python { class MARCH_PYTHON_WRAPPER_VISIBILITY WrapBuffer : public WrapBase< WrapBuffer, Buffer, std::shared_ptr<Buffer> > { friend base_type; WrapBuffer(pybind11::module & mod, const char * pyname, const char * clsdoc) : base_type(mod, pyname, clsdoc) { } }; class MARCH_PYTHON_WRAPPER_VISIBILITY WrapLookupTableCore : public WrapBase< WrapLookupTableCore, LookupTableCore > { friend base_type; WrapLookupTableCore(pybind11::module & mod, const char * pyname, const char * clsdoc) : base_type(mod, pyname, clsdoc) { namespace py = pybind11; (*this) .init() .def_property_readonly("nghost", &LookupTableCore::nghost) .def_property_readonly("nbody", &LookupTableCore::nbody) .def_property_readonly("ncolumn", &LookupTableCore::ncolumn) .array_readwrite() .array_readonly() .pickle() .address() .def("__getattr__", [](LookupTableCore & tbl, py::object key) { return py::object(Table(tbl).full().attr(key)); }) .def_property_readonly("_nda", [](LookupTableCore & tbl) { return Table(tbl).full(); }) ; } wrapper_type & init() { namespace py = pybind11; return def(py::init([](py::args args, py::kwargs kwargs) { std::vector<index_type> dims(args.size()-1); index_type nghost = args[0].cast<index_type>(); index_type nbody = args[1].cast<index_type>(); dims[0] = nghost + nbody; for (size_t it=1; it<dims.size(); ++it) { dims[it] = args[it+1].cast<index_type>(); } PyArray_Descr * descr = nullptr; if (kwargs && kwargs.contains("dtype")) { PyArray_DescrConverter(py::object(kwargs["dtype"]).ptr(), &descr); } if (nullptr == descr) { descr = PyArray_DescrFromType(NPY_INT); } DataTypeId dtid = static_cast<DataTypeId>(descr->type_num); Py_DECREF(descr); LookupTableCore table(nghost, nbody, dims, dtid); std::string creation("empty"); if (kwargs && kwargs.contains("creation")) { creation = kwargs["creation"].cast<std::string>(); } if ("zeros" == creation) { memset(table.buffer()->template data<char>(), 0, table.buffer()->nbyte()); } else if ("empty" == creation) { } else { throw py::value_error("invalid creation type"); } return table; })); } wrapper_type & array_readwrite() { namespace py = pybind11; return def_property( "F", [](LookupTableCore & tbl) { return Table(tbl).full(); }, [](LookupTableCore & tbl, py::array src) { Table::CopyInto(Table(tbl).full(), src); }, "Full array.") .def_property( "G", [](LookupTableCore & tbl) { return Table(tbl).ghost(); }, [](LookupTableCore & tbl, py::array src) { if (tbl.nghost()) { Table::CopyInto(Table(tbl).ghost(), src); } else { throw py::index_error("ghost is zero"); } }, "Ghost-part array.") .def_property( "B", [](LookupTableCore & tbl) { return Table(tbl).body(); }, [](LookupTableCore & tbl, py::array src) { Table::CopyInto(Table(tbl).body(), src); }, "Body-part array.") ; } wrapper_type & array_readonly() { return def_property_readonly( "_ghostpart", [](LookupTableCore & tbl) { return Table(tbl).ghost(); }, "Ghost-part array without setter.") .def_property_readonly( "_bodypart", [](LookupTableCore & tbl) { return Table(tbl).body(); }, "Body-part array without setter.") ; } wrapper_type & pickle() { namespace py = pybind11; return def(py::pickle( [](LookupTableCore & tbl){ return py::make_tuple(tbl.nghost(), tbl.nbody(), tbl.dims(), (long)tbl.datatypeid(), Table(tbl).full()); }, [](py::tuple tpl){ if (tpl.size() != 5) { throw std::runtime_error("Invalid state for Table (LookupTableCore)!"); } index_type nghost = tpl[0].cast<index_type>(); index_type nbody = tpl[1].cast<index_type>(); std::vector<index_type> dims = tpl[2].cast<std::vector<index_type>>(); DataTypeId datatypeid = static_cast<DataTypeId>(tpl[3].cast<long>()); py::array src = tpl[4].cast<py::array>(); LookupTableCore tbl(nghost, nbody, dims, datatypeid); Table::CopyInto(Table(tbl).full(), src); return tbl; } )); } wrapper_type & address() { return def_property_readonly( "offset", [](LookupTableCore & tbl) { return tbl.nghost() * tbl.ncolumn(); }, "Element offset from the head of the ndarray to where the body starts.") .def_property_readonly( "_ghostaddr", [](LookupTableCore & tbl) { return (Py_intptr_t) Table::BYTES(Table(tbl).full()); }) .def_property_readonly( "_bodyaddr", [](LookupTableCore & tbl) { return (Py_intptr_t) Table::BYTES(Table(tbl).body()); }) ; } }; template< size_t NDIM > class MARCH_PYTHON_WRAPPER_VISIBILITY WrapVector : public WrapBase< WrapVector<NDIM>, Vector<NDIM> > { using base_type = WrapBase< WrapVector<NDIM>, Vector<NDIM> >; using wrapper_type = typename base_type::wrapper_type; using wrapped_type = typename base_type::wrapped_type; friend base_type; WrapVector(pybind11::module & mod, const char * pyname, const char * clsdoc) : base_type(mod, pyname, clsdoc) { namespace py = pybind11; wrapped_type dummy; #define MARCH_PYBIND_VECTOR_SCALAR_OP(PYNAME, CXXOP) \ .def("__i" #PYNAME "__", [](wrapped_type & self, real_type v) { self CXXOP v; return self; }) \ .def("__" #PYNAME "__", [](wrapped_type & self, real_type v) { auto ret(self); ret CXXOP v; return ret; }) #define MARCH_PYBIND_VECTOR_VECTOR_OP(PYNAME, CXXOP) \ .def("__i" #PYNAME "__", [](wrapped_type & self, wrapped_type const & v) { self CXXOP v; return self; }) \ .def("__" #PYNAME "__", [](wrapped_type & self, wrapped_type const & v) { auto ret(self); ret CXXOP v; return ret; }) (*this) .def(py::init([]() { return wrapped_type(); })) .def(py::init([](wrapped_type & other) { return wrapped_type(other); })) .add_element_init(dummy) .def("repr", &wrapped_type::repr, py::arg("indent")=0, py::arg("precision")=0) .def("__repr__", [](wrapped_type & self){ return self.repr(); }) .def("__eq__", &wrapped_type::operator==) .def( "__hash__", [](wrapped_type const & self) { py::list tmp; for (size_t it=0; it<self.size(); ++it) { tmp.append(self[it]); } return py::hash(tmp); } ) .def("is_close_to", &wrapped_type::is_close_to) .def("__len__", &wrapped_type::size) .def( "__getitem__", [](wrapped_type & self, index_type i) { return self.at(i); }, py::return_value_policy::copy ) .def( "__setitem__", [](wrapped_type & self, index_type i, real_type v) { self.at(i) = v; } ) MARCH_PYBIND_VECTOR_VECTOR_OP(add, +=) MARCH_PYBIND_VECTOR_VECTOR_OP(sub, -=) MARCH_PYBIND_VECTOR_SCALAR_OP(add, +=) MARCH_PYBIND_VECTOR_SCALAR_OP(sub, -=) MARCH_PYBIND_VECTOR_SCALAR_OP(mul, *=) MARCH_PYBIND_VECTOR_SCALAR_OP(div, /=) MARCH_PYBIND_VECTOR_SCALAR_OP(truediv, /=) ; #undef MARCH_PYBIND_VECTOR_SCALAR_OP #undef MARCH_PYBIND_VECTOR_VECTOR_OP } wrapper_type & add_element_init(Vector<3> const &) { namespace py = pybind11; (*this) .def(py::init([](real_type v0, real_type v1, real_type v2) { return wrapped_type(v0, v1, v2); })) ; return *this; } wrapper_type & add_element_init(Vector<2> const &) { namespace py = pybind11; (*this) .def(py::init([](real_type v0, real_type v1) { return wrapped_type(v0, v1); })) ; return *this; } }; } }
#pragma once #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <utility> #include <memory> #include <vector> #include <algorithm> #include <cstring> #include "march.hpp" #include "march/python/WrapBase.hpp" namespace march { namespace python { class MARCH_PYTHON_WRAPPER_VISIBILITY WrapBuffer : public WrapBase< WrapBuffer, Buffer, std::shared_ptr<Buffer> > { friend base_type; WrapBuffer(pybind11::module & mod, const char * pyname, const char * clsdoc) : base_type(mod, pyname, clsdoc) { } }; class MARCH_PYTHON_WRAPPER_VISIBILITY WrapLookupTableCore : public WrapBase< WrapLookupTableCore, LookupTableCore > { friend base_type; WrapLookupTableCore(pybind11::module & mod, const char * pyname, const char * clsdoc) : base_type(mod, pyname, clsdoc) { namespace py = pybind11; (*this) .init() .def_property_readonly("nghost", &LookupTableCore::nghost) .def_property_readonly("nbody", &LookupTableCore::nbody) .def_property_readonly("ncolumn", &LookupTableCore::ncolumn) .array_readwrite() .array_readonly() .pickle() .address() .def("__getattr__", [](LookupTableCore & tbl, py::object key) { return py::object(Table(tbl).full().attr(key)); }) .def_property_readonly("_nda", [](LookupTableCore & tbl) { return Table(tbl).full(); }) ; } wrapper_type & init() { namespace py = pybind11; return def(py::init([](py::args args, py::kwargs kwargs) { std::vector<index_type> dims(args.size()-1); index_type nghost = args[0].cast<index_type>(); index_type nbody = args[1].cast<index_type>(); dims[0] = nghost + nbody; for (size_t it=1; it<dims.size(); ++it) { dims[it] = args[it+1].cast<index_type>(); } PyArray_Descr * descr = nullptr; if (kwargs && kwargs.contains("dtype")) { PyArray_DescrConverter(py::object(kwargs["dtype"]).ptr(), &descr); } if (nullptr == descr) { descr = PyArray_DescrFromType(NPY_INT); } DataTypeId dtid = static_cast<DataTypeId>(descr->type_num); Py_DECREF(descr); LookupTableCore table(nghost, nbody, dims, dtid); std::string creation("empty"); if (kwargs && kwargs.contains("creation")) { creation = kwargs["creation"].cast<std::string>(); } if ("zeros" == creation) { memset(table.buffer()->template data<char>(), 0, table.buffer()->nbyte()); } else if ("empty" == creation) { } else { throw py::value_error("invalid creation type"); } return table; })); } wrapper_type & array_readwrite() { namespace py = pybind11; return def_property( "F", [](LookupTableCore & tbl) { return Table(tbl).full(); }, [](LookupTableCore & tbl, py::array src) { Table::CopyInto(Table(tbl).full(), src); }, "Full array.") .def_property( "G", [](LookupTableCore & tbl) { return Table(tbl).ghost(); }, [](LookupTableCore & tbl, py::array src) {
}, "Ghost-part array.") .def_property( "B", [](LookupTableCore & tbl) { return Table(tbl).body(); }, [](LookupTableCore & tbl, py::array src) { Table::CopyInto(Table(tbl).body(), src); }, "Body-part array.") ; } wrapper_type & array_readonly() { return def_property_readonly( "_ghostpart", [](LookupTableCore & tbl) { return Table(tbl).ghost(); }, "Ghost-part array without setter.") .def_property_readonly( "_bodypart", [](LookupTableCore & tbl) { return Table(tbl).body(); }, "Body-part array without setter.") ; } wrapper_type & pickle() { namespace py = pybind11; return def(py::pickle( [](LookupTableCore & tbl){ return py::make_tuple(tbl.nghost(), tbl.nbody(), tbl.dims(), (long)tbl.datatypeid(), Table(tbl).full()); }, [](py::tuple tpl){ if (tpl.size() != 5) { throw std::runtime_error("Invalid state for Table (LookupTableCore)!"); } index_type nghost = tpl[0].cast<index_type>(); index_type nbody = tpl[1].cast<index_type>(); std::vector<index_type> dims = tpl[2].cast<std::vector<index_type>>(); DataTypeId datatypeid = static_cast<DataTypeId>(tpl[3].cast<long>()); py::array src = tpl[4].cast<py::array>(); LookupTableCore tbl(nghost, nbody, dims, datatypeid); Table::CopyInto(Table(tbl).full(), src); return tbl; } )); } wrapper_type & address() { return def_property_readonly( "offset", [](LookupTableCore & tbl) { return tbl.nghost() * tbl.ncolumn(); }, "Element offset from the head of the ndarray to where the body starts.") .def_property_readonly( "_ghostaddr", [](LookupTableCore & tbl) { return (Py_intptr_t) Table::BYTES(Table(tbl).full()); }) .def_property_readonly( "_bodyaddr", [](LookupTableCore & tbl) { return (Py_intptr_t) Table::BYTES(Table(tbl).body()); }) ; } }; template< size_t NDIM > class MARCH_PYTHON_WRAPPER_VISIBILITY WrapVector : public WrapBase< WrapVector<NDIM>, Vector<NDIM> > { using base_type = WrapBase< WrapVector<NDIM>, Vector<NDIM> >; using wrapper_type = typename base_type::wrapper_type; using wrapped_type = typename base_type::wrapped_type; friend base_type; WrapVector(pybind11::module & mod, const char * pyname, const char * clsdoc) : base_type(mod, pyname, clsdoc) { namespace py = pybind11; wrapped_type dummy; #define MARCH_PYBIND_VECTOR_SCALAR_OP(PYNAME, CXXOP) \ .def("__i" #PYNAME "__", [](wrapped_type & self, real_type v) { self CXXOP v; return self; }) \ .def("__" #PYNAME "__", [](wrapped_type & self, real_type v) { auto ret(self); ret CXXOP v; return ret; }) #define MARCH_PYBIND_VECTOR_VECTOR_OP(PYNAME, CXXOP) \ .def("__i" #PYNAME "__", [](wrapped_type & self, wrapped_type const & v) { self CXXOP v; return self; }) \ .def("__" #PYNAME "__", [](wrapped_type & self, wrapped_type const & v) { auto ret(self); ret CXXOP v; return ret; }) (*this) .def(py::init([]() { return wrapped_type(); })) .def(py::init([](wrapped_type & other) { return wrapped_type(other); })) .add_element_init(dummy) .def("repr", &wrapped_type::repr, py::arg("indent")=0, py::arg("precision")=0) .def("__repr__", [](wrapped_type & self){ return self.repr(); }) .def("__eq__", &wrapped_type::operator==) .def( "__hash__", [](wrapped_type const & self) { py::list tmp; for (size_t it=0; it<self.size(); ++it) { tmp.append(self[it]); } return py::hash(tmp); } ) .def("is_close_to", &wrapped_type::is_close_to) .def("__len__", &wrapped_type::size) .def( "__getitem__", [](wrapped_type & self, index_type i) { return self.at(i); }, py::return_value_policy::copy ) .def( "__setitem__", [](wrapped_type & self, index_type i, real_type v) { self.at(i) = v; } ) MARCH_PYBIND_VECTOR_VECTOR_OP(add, +=) MARCH_PYBIND_VECTOR_VECTOR_OP(sub, -=) MARCH_PYBIND_VECTOR_SCALAR_OP(add, +=) MARCH_PYBIND_VECTOR_SCALAR_OP(sub, -=) MARCH_PYBIND_VECTOR_SCALAR_OP(mul, *=) MARCH_PYBIND_VECTOR_SCALAR_OP(div, /=) MARCH_PYBIND_VECTOR_SCALAR_OP(truediv, /=) ; #undef MARCH_PYBIND_VECTOR_SCALAR_OP #undef MARCH_PYBIND_VECTOR_VECTOR_OP } wrapper_type & add_element_init(Vector<3> const &) { namespace py = pybind11; (*this) .def(py::init([](real_type v0, real_type v1, real_type v2) { return wrapped_type(v0, v1, v2); })) ; return *this; } wrapper_type & add_element_init(Vector<2> const &) { namespace py = pybind11; (*this) .def(py::init([](real_type v0, real_type v1) { return wrapped_type(v0, v1); })) ; return *this; } }; } }
if (tbl.nghost()) { Table::CopyInto(Table(tbl).ghost(), src); } else { throw py::index_error("ghost is zero"); }
if_condition
[ { "content": "class LookupTable<ElemType, 0>: public LookupTableCore\n\n{\n\n\n\npublic:\n\n\n\n using elem_type = ElemType;\n\n\n\n typedef elem_type (&row_type);\n\n typedef const elem_type (&const_row_type);\n\n\n\n LookupTable() {}\n\n\n\n LookupTable(index_type nghost, index_type nbody)\n\n ...
C++
cpp/mindalpha/dense_tensor.cpp
mindalpha/MindAlpha
5b6fe017a37238884a6e963fd6b0a1492938e186
#include <string.h> #include <json11.hpp> #include <mindalpha/dense_tensor.h> #include <mindalpha/file_utils.h> #include <mindalpha/tensor_utils.h> namespace mindalpha { void DenseTensor::Init(std::function<void()> cb) { PSMessage req = std::make_shared<Message>(); json11::Json json = json11::Json::object { { "command", "DenseInit" }, { "meta", GetMeta() }, }; req->GetMessageMeta().SetReceiver(ServerGroup); req->GetMessageMeta().SetBody(json.dump()); agent_->BroadcastRequest(req, [cb](PSMessage req, std::vector<PSMessage> ress) { cb(); }); } void DenseTensor::Dispose(std::function<void()> cb) { PSMessage req = std::make_shared<Message>(); json11::Json json = json11::Json::object { { "command", "DenseDispose" }, { "name", GetMeta().GetName() }, }; req->GetMessageMeta().SetReceiver(ServerGroup); req->GetMessageMeta().SetBody(json.dump()); agent_->BroadcastRequest(req, [cb](PSMessage req, std::vector<PSMessage> ress) { cb(); }); } void DenseTensor::Push(SmartArray<uint8_t> in, std::function<void()> cb, bool is_value, bool is_state) { const size_t name_hash = GetMeta().GetNameHash(); const size_t item_size = DataTypeToSize(GetMeta().GetDataType()); const size_t slice_items = SliceElements(is_state ? GetMeta().GetStateShape() : GetMeta().GetDataShape()); const size_t slice_length = item_size * slice_items; const int num_parts = GetMeta().GetPartitionCount(); json11::Json json = json11::Json::object { { "command", "DensePush" }, { "name", GetMeta().GetName() }, { "is_value", is_value }, { "is_state", is_state }, }; std::string command = json.dump(); std::vector<PSMessage> reqs; reqs.reserve(num_parts); for (int k = 0; k < num_parts; k++) { PSMessage req = std::make_shared<Message>(); req->GetMessageMeta().SetReceiver(ServerRankToNodeId(k)); req->GetMessageMeta().SetBody(command); size_t begin = 0; size_t end = 0; GetMeta().ComputePartitionShapesWithHash(name_hash, k, begin, end, nullptr, nullptr); begin *= slice_length; end *= slice_length; SmartArray<uint8_t> k_in = in.Slice(begin, end); req->AddTypedSlice(k_in, GetMeta().GetDataType()); reqs.push_back(req); } agent_->SendAllRequests(std::move(reqs), [cb](std::vector<PSMessage> reqs, std::vector<PSMessage> ress) { cb(); }); } void DenseTensor::Pull(std::function<void(SmartArray<uint8_t> out)> cb, bool is_state) { json11::Json json = json11::Json::object { { "command", "DensePull" }, { "name", GetMeta().GetName() }, { "is_state", is_state }, }; PSMessage req = std::make_shared<Message>(); req->GetMessageMeta().SetReceiver(ServerGroup); req->GetMessageMeta().SetBody(json.dump()); agent_->BroadcastRequest(req, [this, cb, is_state](PSMessage req, std::vector<PSMessage> ress) { const size_t name_hash = GetMeta().GetNameHash(); const size_t item_size = DataTypeToSize(GetMeta().GetDataType()); const size_t slice_items = SliceElements(is_state ? GetMeta().GetStateShape() : GetMeta().GetDataShape()); const size_t slice_length = item_size * slice_items; const size_t total_items = TotalElements(is_state ? GetMeta().GetStateShape() : GetMeta().GetDataShape()); const size_t total_length = item_size * total_items; const int num_parts = GetMeta().GetPartitionCount(); SmartArray<uint8_t> out(total_length); for (int k = 0; k < num_parts; k++) { PSMessage res = ress.at(k); SmartArray<uint8_t> k_out = res->GetTypedSlice(0, GetMeta().GetDataType()); const int sender = res->GetMessageMeta().GetSender(); const int rank = NodeIdToRank(sender); size_t begin = 0; size_t end = 0; GetMeta().ComputePartitionShapesWithHash(name_hash, rank, begin, end, nullptr, nullptr); begin *= slice_length; end *= slice_length; memcpy(out.data() + begin, k_out.data(), end - begin); } cb(out); }); } void DenseTensor::PushMeta(const DenseTensorMeta& meta, std::function<void()> cb) { PSMessage req = std::make_shared<Message>(); json11::Json json = json11::Json::object { { "command", "DensePushMeta" }, { "name", GetMeta().GetName() }, { "meta", meta }, }; req->GetMessageMeta().SetReceiver(ServerGroup); req->GetMessageMeta().SetBody(json.dump()); agent_->BroadcastRequest(req, [cb](PSMessage req, std::vector<PSMessage> ress) { cb(); }); } void DenseTensor::PullMeta(std::function<void (DenseTensorMeta meta)> cb) { PSMessage req = std::make_shared<Message>(); json11::Json json = json11::Json::object { { "command", "DensePullMeta" }, { "name", GetMeta().GetName() }, }; req->GetMessageMeta().SetReceiver(ServerGroup); req->GetMessageMeta().SetBody(json.dump()); agent_->BroadcastRequest(req, [this, cb](PSMessage req, std::vector<PSMessage> ress) { for (size_t k = 0; k < ress.size(); k++) { const std::string& body1 = ress.at(0)->GetMessageMeta().GetBody(); const std::string& body2 = ress.at(k)->GetMessageMeta().GetBody(); if (body1 != body2) { const int nodeId1 = ress.at(0)->GetMessageMeta().GetSender(); const int nodeId2 = ress.at(k)->GetMessageMeta().GetSender(); std::string serr; serr.append("Meta of dense tensor '"); serr.append(GetMeta().GetName()); serr.append("' on node "); serr.append(NodeIdToString(nodeId1)); serr.append(" and "); serr.append(NodeIdToString(nodeId2)); serr.append(" mismatch.\n\n"); serr.append(GetStackTrace()); spdlog::error(serr); throw std::runtime_error(serr); } } const std::string& body = ress.at(0)->GetMessageMeta().GetBody(); DenseTensorMeta meta = DenseTensorMeta::FromJsonString(body); cb(std::move(meta)); }); } void DenseTensor::Load(const std::string& dir_path, std::function<void()> cb, bool keep_meta) { std::string meta_path = GetDenseMetaPath(dir_path); std::string str = StreamReadAll(meta_path); DenseTensorMeta meta = DenseTensorMeta::FromJsonString(str); if (!meta.IsCompatible(meta_)) { std::string serr; serr.append("Incompatible meta detected in '"); serr.append(meta_path); serr.append("', can not load dense tensor '"); serr.append(GetMeta().GetName()); serr.append("'.\n\n"); serr.append(GetStackTrace()); spdlog::error(serr); throw std::runtime_error(serr); } auto push_data_and_state = [this, dir_path, cb] { if (agent_->GetAgentRank() != 0) { cb(); return; } const size_t item_size = DataTypeToSize(GetMeta().GetDataType()); const size_t total_items = TotalElements(GetMeta().GetDataShape()); const size_t total_length = item_size * total_items; SmartArray<uint8_t> data(total_length); std::string data_path = GetDenseDataPath(dir_path); if (!data.empty() && LoadAsSArray(data_path, &data) < 0) { std::string serr; serr.append("Fail to load data file of dense tensor '"); serr.append(GetMeta().GetName()); serr.append("' from '"); serr.append(data_path); serr.append("'.\n\n"); serr.append(GetStackTrace()); spdlog::error(serr); throw std::runtime_error(serr); } Push(data, [this, dir_path, cb] { if (GetMeta().GetStateShape().empty()) { cb(); return; } const size_t item_size = DataTypeToSize(GetMeta().GetDataType()); const size_t total_items = TotalElements(GetMeta().GetStateShape()); const size_t total_length = item_size * total_items; SmartArray<uint8_t> state(total_length); std::string state_path = GetDenseStatePath(dir_path); if (!state.empty() && LoadAsSArray(state_path, &state) < 0) { std::string serr; serr.append("Fail to load state file of dense tensor '"); serr.append(GetMeta().GetName()); serr.append("' from '"); serr.append(state_path); serr.append("'.\n\n"); serr.append(GetStackTrace()); spdlog::error(serr); throw std::runtime_error(serr); } Push(state, [cb] { cb(); }, false, true); }, true, false); }; if (!keep_meta) { GetMeta().SetInitializerByData(meta.GetInitializerAsData()); GetMeta().SetUpdaterByData(meta.GetUpdaterAsData()); } if (keep_meta || agent_->GetAgentRank() != 0) push_data_and_state(); else { meta.SetName(GetMeta().GetName()); meta.SetPartitionCount(agent_->GetServerCount()); PushMeta(meta, push_data_and_state); } } void DenseTensor::Save(const std::string& dir_path, std::function<void()> cb) { PullMeta([this, dir_path, cb](DenseTensorMeta meta) { std::string meta_path = GetDenseMetaPath(dir_path); std::string str = meta.ToJsonString(); EnsureLocalDirectory(dir_path); StreamWriteAll(meta_path, str); Pull([this, dir_path, cb](SmartArray<uint8_t> data) { std::string data_path = GetDenseDataPath(dir_path); if (!data.empty() && SaveAsSArray(data_path, data) < 0) { std::string serr; serr.append("Fail to save data file of dense tensor "); serr.append(GetMeta().GetName()); serr.append("' to '"); serr.append(data_path); serr.append("'.\n\n"); serr.append(GetStackTrace()); spdlog::error(serr); throw std::runtime_error(serr); } Pull([this, dir_path, cb](SmartArray<uint8_t> state) { std::string state_path = GetDenseStatePath(dir_path); if (!state.empty() && SaveAsSArray(state_path, state) < 0) { std::string serr; serr.append("Fail to save state file of dense tensor '"); serr.append(GetMeta().GetName()); serr.append("' to '"); serr.append(state_path); serr.append("'.\n\n"); serr.append(GetStackTrace()); spdlog::error(serr); throw std::runtime_error(serr); } cb(); }, true); }, false); }); } std::string DenseTensor::GetDenseMetaPath(const std::string& dir_path) const { std::string file_name = fmt::format("{}__dense_meta.json", GetMeta().GetName()); std::string file_path = JoinPath(dir_path, file_name); return file_path; } std::string DenseTensor::GetDenseDataPath(const std::string& dir_path) const { std::string file_name = fmt::format("{}__dense_data.dat", GetMeta().GetName()); std::string file_path = JoinPath(dir_path, file_name); return file_path; } std::string DenseTensor::GetDenseStatePath(const std::string& dir_path) const { std::string file_name = fmt::format("{}__dense_state.dat", GetMeta().GetName()); std::string file_path = JoinPath(dir_path, file_name); return file_path; } }
#include <string.h> #include <json11.hpp> #include <mindalpha/dense_tensor.h> #include <mindalpha/file_utils.h> #include <mindalpha/tensor_utils.h> namespace mindalpha { void DenseTensor::Init(std::function<void()> cb) { PSMessage req = std::make_shared<Message>(); json11::Json json = json11::Json::object { { "command", "DenseInit" }, { "meta", GetMeta() }, }; req->GetMessageMeta().SetReceiver(ServerGroup); req->GetMessageMeta().SetBody(json.dump()); agent_->BroadcastRequest(req, [cb](PSMessage req, std::vector<PSMessage> ress) { cb(); }); } void DenseTensor::Dispose(std::function<void()> cb) { PSMessage req = std::make_shared<Message>(); json11::Json json = json11::Json::object { { "command", "DenseDispose" }, { "name", GetMeta().GetName() }, }; req->GetMessageMeta().SetReceiver(ServerGroup); req->GetMessageMeta().SetBody(json.dump()); agent_->BroadcastRequest(req, [cb](PSMessage req, std::vector<PSMessage> ress) { cb(); }); } void DenseTensor::Push(SmartArray<uint8_t> in, std::function<void()> cb, bool is_value, bool is_state) { const size_t name_hash = GetMeta().GetNameHash(); const size_t item_size = DataTypeToSize(GetMeta().GetDataType()); const size_t slice_items = SliceElements(is_state ? GetMeta().GetStateShape() : GetMeta().GetDataShape()); const size_t slice_length = item_size * slice_items; const int num_parts = GetMeta().GetPartitionCount(); json11::Json json = json11::Json::object { { "command", "DensePush" }, { "name", GetMeta().GetName() }, { "is_value", is_value }, { "is_state", is_state }, }; std::string command = json.dump(); std::vector<PSMessage> reqs; reqs.reserve(num_parts); for (int k = 0; k < num_parts; k++) { PSMessage req = std::make_shared<Message>(); req->GetMessageMeta().SetReceiver(ServerRankToNodeId(k)); req->GetMessageMeta().SetBody(command); size_t begin = 0; size_t end = 0; GetMeta().ComputePartitionShapesWithHash(name_hash, k, begin, end, nullptr, nullptr); begin *= slice_length; end *= slice_length; SmartArray<uint8_t> k_in = in.Slice(begin, end); req->AddTypedSlice(k_in, GetMeta().GetDataType()); reqs.push_back(req); } agent_->SendAllRequests(std::move(reqs), [cb](std::vector<PSMessage> reqs, std::vector<PSMessage> ress) { cb(); }); } void DenseTensor::Pull(std::function<void(SmartArray<uint8_t> out)> cb, bool is_state) { json11::Json json = json11::Json::object { { "command", "DensePull" }, { "name", GetMeta().GetName() }, { "is_state", is_state }, }; PSMessage req = std::make_shared<Message>(); req->GetMessageMeta().SetReceiver(ServerGroup); req->GetMessageMeta().SetBody(json.dump()); agent_->BroadcastRequest(req, [this, cb, is_state](PSMessage req, std::vector<PSMessage> ress) { const size_t name_hash = GetMeta().GetNameHash(); const size_t item_size = DataTypeToSize(GetMeta().GetDataType()); const size_t slice_items = SliceElements(is_state ? GetMeta().GetStateShape() : GetMeta().GetDataShape()); const size_t slice_length = item_size * slice_items; const size_t total_items = TotalElements(is_state ? GetMeta().GetStateShape() : GetMeta().GetDataShape()); const size_t total_length = item_size * total_items; const int num_parts = GetMeta().GetPartitionCount(); SmartArray<uint8_t> out(total_length); for (int k = 0; k < num_parts; k++) { PSMessage res = ress.at(k); SmartArray<uint8_t> k_out = res->GetTypedSlice(0, GetMeta().GetDataType()); const int sender = res->GetMessageMeta().GetSender(); const int rank = NodeIdToRank(sender); size_t begin = 0; size_t end = 0; GetMeta().ComputePartitionShapesWithHash(name_hash, rank, begin, end, nullptr, nullptr); begin *= slice_length; end *= slice_length; memcpy(out.data() + begin, k_out.data(), end - begin); } cb(out); }); } void DenseTensor::PushMeta(const DenseTensorMeta& meta, std::function<void()> cb) { PSMessage req = std::make_shared<Message>(); json11::Json json = json11::Json::object { { "command", "DensePushMeta" }, { "name", GetMeta().GetName() }, { "meta", meta }, }; req->GetMessageMeta().SetReceiver(ServerGroup); req->GetMessageMeta().SetBody(json.dump()); agent_->BroadcastRequest(req, [cb](PSMessage req, std::vector<PSMessage> ress) { cb(); }); } void DenseTensor::PullMeta(std::function<void (DenseTensorMeta meta)> cb) { PSMessage req = std::make_shared<Message>(); json11::Json json = json11::Json::object { { "command", "DensePullMeta" }, { "name", GetMeta().GetName() }, }; req->GetMessageMeta().SetReceiver(ServerGroup); req->GetMessageMeta().SetBody(json.dump()); agent_->BroadcastRequest(req, [this, cb](PSMessage req, std::vector<PSMessage> ress) { for (size_t k = 0; k < ress.size(); k++) { const std::string& body1 = ress.at(0)->GetMessageMeta().GetBody(); const std::string& body2 = ress.at(k)->GetMessageMeta().GetBody(); if (body1 != body2) { const int nodeId1 = ress.at(0)->GetMessageMeta().GetSender(); const int nodeId2 = ress.at(k)->GetMessageMeta().GetSender(); std::string serr; serr.append("Meta of dense tensor '"); serr.append(GetMeta().GetName()); serr.append("' on node "); serr.append(NodeIdToString(nodeId1)); serr.append(" and "); serr.append(NodeIdToString(nodeId2)); serr.append(" mismatch.\n\n"); serr.append(GetStackTrace()); spdlog::error(serr); throw std::runtime_error(serr); } } const std::string& body = ress.at(0)->GetMessageMeta().GetBody(); DenseTensorMeta meta = DenseTensorMeta::FromJsonString(body); cb(std::move(meta)); }); } void DenseTensor::Load(const std::string& dir_path, std::function<void()> cb, bool keep_meta) { std::string meta_path = GetDenseMetaPath(dir_path); std::string str = StreamReadAll(meta_path); DenseTensorMeta meta = DenseTensorMeta::FromJsonString(str); if (!meta.IsCompatible(meta_)) { std::string serr; serr.append("Incompatible meta detected in '"); serr.append(meta_path); serr.append("', can not load dense tensor '"); serr.append(GetMeta().GetName()); serr.append("'.\n\n"); serr.append(GetStackTrace()); spdlog::error(serr); throw std::runtime_error(serr); } auto push_data_and_state = [this, dir_path, cb] { if (agent_->GetAgentRank() != 0) { cb(); return; } const size_t item_size = DataTypeToSize(GetMeta().GetDataType()); const size_t total_items = TotalElements(GetMeta().GetDataShape()); const size_t total_length = item_size * total_items; SmartArray<uint8_t> data(total_length); std::string data_path = GetDenseDataPath(dir_path); if (!data.empty() && LoadAsSArray(data_path, &data) < 0) { std::string serr; serr.append("Fail to load data file of dense tensor '"); serr.append(GetMeta().GetName()); serr.append("' from '"); serr.append(data_path); serr.append("'.\n\n"); serr.append(GetStackTrace()); spdlog::error(serr); throw std::runtime_error(serr); } Push(data, [this, dir_path, cb] { if (GetMeta().GetStateShape().empty()) { cb(); return; } const size_t item_size = DataTypeToSize(GetMeta().GetDataType()); const size_t total_items = TotalElements(GetMeta().GetStateShape()); const size_t total_length = item_size * total_items; SmartArray<uint8_t> state(total_length); std::string state_path = GetDenseStatePath(dir_path); if (!state.empty() && LoadAsSArray(state_path, &state) < 0) { std::string serr; serr.append("Fail to load state file of dense tensor '"); serr.append(GetMeta().GetName()); serr.append("' from '"); serr.append(state_path); serr.append("'.\n\n"); serr.append(GetStackTrace()); spdlog::error(serr); throw std::runtime_error(serr); } Push(state, [cb] { cb(); }, false, true); }, true, false); }; if (!keep_meta) { GetMeta().SetInitializerByData(meta.GetInitializerAsData()); GetMeta().SetUpdaterByData(meta.GetUpdaterAsData()); }
} void DenseTensor::Save(const std::string& dir_path, std::function<void()> cb) { PullMeta([this, dir_path, cb](DenseTensorMeta meta) { std::string meta_path = GetDenseMetaPath(dir_path); std::string str = meta.ToJsonString(); EnsureLocalDirectory(dir_path); StreamWriteAll(meta_path, str); Pull([this, dir_path, cb](SmartArray<uint8_t> data) { std::string data_path = GetDenseDataPath(dir_path); if (!data.empty() && SaveAsSArray(data_path, data) < 0) { std::string serr; serr.append("Fail to save data file of dense tensor "); serr.append(GetMeta().GetName()); serr.append("' to '"); serr.append(data_path); serr.append("'.\n\n"); serr.append(GetStackTrace()); spdlog::error(serr); throw std::runtime_error(serr); } Pull([this, dir_path, cb](SmartArray<uint8_t> state) { std::string state_path = GetDenseStatePath(dir_path); if (!state.empty() && SaveAsSArray(state_path, state) < 0) { std::string serr; serr.append("Fail to save state file of dense tensor '"); serr.append(GetMeta().GetName()); serr.append("' to '"); serr.append(state_path); serr.append("'.\n\n"); serr.append(GetStackTrace()); spdlog::error(serr); throw std::runtime_error(serr); } cb(); }, true); }, false); }); } std::string DenseTensor::GetDenseMetaPath(const std::string& dir_path) const { std::string file_name = fmt::format("{}__dense_meta.json", GetMeta().GetName()); std::string file_path = JoinPath(dir_path, file_name); return file_path; } std::string DenseTensor::GetDenseDataPath(const std::string& dir_path) const { std::string file_name = fmt::format("{}__dense_data.dat", GetMeta().GetName()); std::string file_path = JoinPath(dir_path, file_name); return file_path; } std::string DenseTensor::GetDenseStatePath(const std::string& dir_path) const { std::string file_name = fmt::format("{}__dense_state.dat", GetMeta().GetName()); std::string file_path = JoinPath(dir_path, file_name); return file_path; } }
if (keep_meta || agent_->GetAgentRank() != 0) push_data_and_state(); else { meta.SetName(GetMeta().GetName()); meta.SetPartitionCount(agent_->GetServerCount()); PushMeta(meta, push_data_and_state); }
if_condition
[ { "content": "class DenseTensorMeta\n\n{\n\npublic:\n\n const std::string& GetName() const { return name_; }\n\n void SetName(std::string value) { name_ = std::move(value); }\n\n\n\n DataType GetDataType() const { return data_type_; }\n\n void SetDataType(DataType value) { data_type_ = value; }\n\n\...
C++
chrome/browser/ui/views/tabs/color_picker_view.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
#include "chrome/browser/ui/views/tabs/color_picker_view.h" #include <memory> #include <vector> #include "base/bind.h" #include "base/callback.h" #include "base/containers/span.h" #include "chrome/browser/themes/theme_properties.h" #include "chrome/browser/ui/tabs/tab_group_theme.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "components/tab_groups/tab_group_color.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/pointer/touch_ui_controller.h" #include "ui/base/theme_provider.h" #include "ui/gfx/animation/tween.h" #include "ui/gfx/canvas.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/favicon_size.h" #include "ui/views/border.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/highlight_path_generator.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/flex_layout.h" #include "ui/views/layout/flex_layout_types.h" #include "ui/views/view_class_properties.h" namespace { class ColorPickerHighlightPathGenerator : public views::HighlightPathGenerator { public: ColorPickerHighlightPathGenerator() = default; SkPath GetHighlightPath(const views::View* view) override { gfx::RectF bounds(view->GetContentsBounds()); bounds.Inset(gfx::Insets(-2.0f)); const gfx::PointF center = bounds.CenterPoint(); return SkPath().addCircle(center.x(), center.y(), bounds.width() / 2.0f); } private: DISALLOW_COPY_AND_ASSIGN(ColorPickerHighlightPathGenerator); }; } class ColorPickerElementView : public views::Button, public views::ButtonListener { public: ColorPickerElementView( base::RepeatingCallback<void(ColorPickerElementView*)> selected_callback, const views::BubbleDialogDelegateView* bubble_view, tab_groups::TabGroupColorId color_id, base::string16 color_name) : Button(this), selected_callback_(std::move(selected_callback)), bubble_view_(bubble_view), color_id_(color_id), color_name_(color_name) { DCHECK(selected_callback_); SetAccessibleName(color_name); SetFocusForPlatform(); SetInstallFocusRingOnFocus(true); views::HighlightPathGenerator::Install( this, std::make_unique<ColorPickerHighlightPathGenerator>()); const int padding = ChromeLayoutProvider::Get()->GetDistanceMetric( views::DISTANCE_RELATED_BUTTON_HORIZONTAL) / 2; gfx::Insets insets = ui::TouchUiController::Get()->touch_ui() ? gfx::Insets(padding * 2) : gfx::Insets(padding); SetBorder(views::CreateEmptyBorder(insets)); SetInkDropMode(InkDropMode::OFF); set_animate_on_state_change(true); } void SetSelected(bool selected) { if (selected_ == selected) return; selected_ = selected; SchedulePaint(); } bool selected() const { return selected_; } bool IsGroupFocusTraversable() const override { return false; } views::View* GetSelectedViewForGroup(int group) override { DCHECK(parent()); return parent()->GetSelectedViewForGroup(group); } void GetAccessibleNodeData(ui::AXNodeData* node_data) override { views::Button::GetAccessibleNodeData(node_data); node_data->role = ax::mojom::Role::kRadioButton; node_data->SetCheckedState(selected() ? ax::mojom::CheckedState::kTrue : ax::mojom::CheckedState::kFalse); } base::string16 GetTooltipText(const gfx::Point& p) const override { return color_name_; } gfx::Size CalculatePreferredSize() const override { const gfx::Insets insets = GetInsets(); const int circle_size = ui::TouchUiController::Get()->touch_ui() ? 3 * gfx::kFaviconSize / 2 : gfx::kFaviconSize; gfx::Size size(circle_size, circle_size); size.Enlarge(insets.width(), insets.height()); return size; } int GetHeightForWidth(int width) const override { return width; } void PaintButtonContents(gfx::Canvas* canvas) override { gfx::RectF bounds(GetContentsBounds()); DCHECK_EQ(bounds.width(), bounds.height()); const SkColor color = GetThemeProvider()->GetColor(GetTabGroupDialogColorId(color_id_)); cc::PaintFlags flags; flags.setStyle(cc::PaintFlags::kFill_Style); flags.setColor(color); flags.setAntiAlias(true); canvas->DrawCircle(bounds.CenterPoint(), bounds.width() / 2.0f, flags); PaintSelectionIndicator(canvas); } void ButtonPressed(Button* sender, const ui::Event& event) override { DCHECK_EQ(this, sender); if (!selected_) { selected_ = true; SchedulePaint(); selected_callback_.Run(this); } } private: void PaintSelectionIndicator(gfx::Canvas* canvas) { if (!selected_) { return; } constexpr float kInset = 3.0f; constexpr float kThickness = 2.0f; cc::PaintFlags flags; flags.setStyle(cc::PaintFlags::kStroke_Style); flags.setStrokeWidth(kThickness); flags.setAntiAlias(true); flags.setColor(bubble_view_->color()); gfx::RectF indicator_bounds(GetContentsBounds()); indicator_bounds.Inset(gfx::InsetsF(kInset)); DCHECK(!indicator_bounds.size().IsEmpty()); canvas->DrawCircle(indicator_bounds.CenterPoint(), indicator_bounds.width() / 2.0f, flags); } const base::RepeatingCallback<void(ColorPickerElementView*)> selected_callback_; const views::BubbleDialogDelegateView* bubble_view_; const tab_groups::TabGroupColorId color_id_; const base::string16 color_name_; bool selected_ = false; }; ColorPickerView::ColorPickerView( const views::BubbleDialogDelegateView* bubble_view, const TabGroupEditorBubbleView::Colors& colors, tab_groups::TabGroupColorId initial_color_id, ColorSelectedCallback callback) : callback_(std::move(callback)) { DCHECK(!colors.empty()); elements_.reserve(colors.size()); for (const auto& color : colors) { elements_.push_back(AddChildView(std::make_unique<ColorPickerElementView>( base::Bind(&ColorPickerView::OnColorSelected, base::Unretained(this)), bubble_view, color.first, color.second))); if (initial_color_id == color.first) elements_.back()->SetSelected(true); } gfx::Insets child_insets = elements_[0]->GetInsets(); SetProperty(views::kInternalPaddingKey, gfx::Insets(0, child_insets.left(), 0, child_insets.right())); SetFocusBehavior(views::View::FocusBehavior::NEVER); for (View* view : elements_) { view->SetGroup(0); } auto* layout = SetLayoutManager(std::make_unique<views::FlexLayout>()); layout->SetOrientation(views::LayoutOrientation::kHorizontal) .SetDefault( views::kFlexBehaviorKey, views::FlexSpecification(views::MinimumFlexSizeRule::kPreferred, views::MaximumFlexSizeRule::kUnbounded) .WithAlignment(views::LayoutAlignment::kCenter) .WithWeight(1)); } ColorPickerView::~ColorPickerView() { RemoveAllChildViews(true); } base::Optional<int> ColorPickerView::GetSelectedElement() const { for (size_t i = 0; i < elements_.size(); ++i) { if (elements_[i]->selected()) return static_cast<int>(i); } return base::nullopt; } views::View* ColorPickerView::GetSelectedViewForGroup(int group) { for (ColorPickerElementView* element : elements_) { if (element->selected()) return element; } return nullptr; } views::Button* ColorPickerView::GetElementAtIndexForTesting(int index) { DCHECK_GE(index, 0); DCHECK_LT(index, static_cast<int>(elements_.size())); return elements_[index]; } void ColorPickerView::OnColorSelected(ColorPickerElementView* element) { for (ColorPickerElementView* other_element : elements_) { if (other_element != element) other_element->SetSelected(false); } if (callback_) callback_.Run(); }
#include "chrome/browser/ui/views/tabs/color_picker_view.h" #include <memory> #include <vector> #include "base/bind.h" #include "base/callback.h" #include "base/containers/span.h" #include "chrome/browser/themes/theme_properties.h" #include "chrome/browser/ui/tabs/tab_group_theme.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "components/tab_groups/tab_group_color.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/pointer/touch_ui_controller.h" #include "ui/base/theme_provider.h" #include "ui/gfx/animation/tween.h" #include "ui/gfx/canvas.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/favicon_size.h" #include "ui/views/border.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/highlight_path_generator.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/flex_layout.h" #include "ui/views/layout/flex_layout_types.h" #include "ui/views/view_class_properties.h" namespace { class ColorPickerHighlightPathGenerator : public views::HighlightPathGenerator { public: ColorPickerHighlightPathGenerator() = default; SkPath GetHighlightPath(const views::View* view) override { gfx::RectF bounds(view->GetContentsBounds()); bounds.Inset(gfx::Insets(-2.0f)); const gfx::PointF center = bounds.CenterPoint(); return SkPath().addCircle(center.x(), center.y(), bounds.width() / 2.0f); } private: DISALLOW_COPY_AND_ASSIGN(ColorPickerHighlightPathGenerator); }; } class ColorPickerElementView : public views::Button, public views::ButtonListener { public: ColorPickerElementView( base::RepeatingCallback<void(ColorPickerElementView*)> selected_callback, const views::BubbleDialogDelegateView* bubble_view, tab_groups::TabGroupColorId color_id, base::string16 color_name) : Button(this), selected_callback_(std::move(selected_callback)), bubble_view_(bubble_view), color_id_(color_id), color_name_(color_name) { DCHECK(selected_callback_); SetAccessibleName(color_name); SetFocusForPlatform(); SetInstallFocusRingOnFocus(true); views::HighlightPathGenerator::Install( this, std::make_unique<ColorPickerHighlightPathGenerator>()); const int padding = ChromeLayoutProvider::Get()->GetDistanceMetric( views::DISTANCE_RELATED_BUTTON_HORIZONTAL) / 2; gfx::Insets insets = ui::TouchUiController::Get()->touch_ui() ? gfx::Insets(padding * 2) : gfx::Insets(padding); SetBorder(views::CreateEmptyBorder(insets)); SetInkDropMode(InkDropMode::OFF); set_animate_on_state_change(true); } void SetSelected(bool selected) { if (selected_ == selected) return; selected_ = selected; SchedulePaint(); } bool selected() const { return selected_; } bool IsGroupFocusTraversable() const override { return false; } views::View* GetSelectedViewForGroup(int group) override { DCHECK(parent()); return parent()->GetSelectedViewForGroup(group); } void GetAccessibleNodeData(ui::AXNodeData* node_data) override { views::Button::GetAccessibleNodeData(node_data); node_data->role = ax::mojom::Role::kRadioButton; node_data->SetCheckedState(selected() ? ax::mojom::CheckedState::kTrue : ax::mojom::CheckedState::kFalse); } base::string16 GetTooltipText(const gfx::Point& p) const override { return color_name_; } gfx::Size CalculatePreferredSize() const override { const gfx::Insets insets = GetInsets(); const int circle_size = ui::TouchUiController::Get()->touch_ui() ? 3 * gfx::kFaviconSize / 2 : gfx::kFaviconSize; gfx::Size size(circle_size, circle_size); size.Enlarge(insets.width(), insets.height()); return size; } int GetHeightForWidth(int width) const override { return width; } void PaintButtonContents(gfx::Canvas* canvas) override { gfx::RectF bounds(GetContentsBounds()); DCHECK_EQ(bounds.width(), bounds.height()); const SkColor color = GetThemeProvider()->GetColor(GetTabGroupDialogColorId(color_id_)); cc::PaintFlags flags; flags.setStyle(cc::PaintFlags::kFil
void ButtonPressed(Button* sender, const ui::Event& event) override { DCHECK_EQ(this, sender); if (!selected_) { selected_ = true; SchedulePaint(); selected_callback_.Run(this); } } private: void PaintSelectionIndicator(gfx::Canvas* canvas) { if (!selected_) { return; } constexpr float kInset = 3.0f; constexpr float kThickness = 2.0f; cc::PaintFlags flags; flags.setStyle(cc::PaintFlags::kStroke_Style); flags.setStrokeWidth(kThickness); flags.setAntiAlias(true); flags.setColor(bubble_view_->color()); gfx::RectF indicator_bounds(GetContentsBounds()); indicator_bounds.Inset(gfx::InsetsF(kInset)); DCHECK(!indicator_bounds.size().IsEmpty()); canvas->DrawCircle(indicator_bounds.CenterPoint(), indicator_bounds.width() / 2.0f, flags); } const base::RepeatingCallback<void(ColorPickerElementView*)> selected_callback_; const views::BubbleDialogDelegateView* bubble_view_; const tab_groups::TabGroupColorId color_id_; const base::string16 color_name_; bool selected_ = false; }; ColorPickerView::ColorPickerView( const views::BubbleDialogDelegateView* bubble_view, const TabGroupEditorBubbleView::Colors& colors, tab_groups::TabGroupColorId initial_color_id, ColorSelectedCallback callback) : callback_(std::move(callback)) { DCHECK(!colors.empty()); elements_.reserve(colors.size()); for (const auto& color : colors) { elements_.push_back(AddChildView(std::make_unique<ColorPickerElementView>( base::Bind(&ColorPickerView::OnColorSelected, base::Unretained(this)), bubble_view, color.first, color.second))); if (initial_color_id == color.first) elements_.back()->SetSelected(true); } gfx::Insets child_insets = elements_[0]->GetInsets(); SetProperty(views::kInternalPaddingKey, gfx::Insets(0, child_insets.left(), 0, child_insets.right())); SetFocusBehavior(views::View::FocusBehavior::NEVER); for (View* view : elements_) { view->SetGroup(0); } auto* layout = SetLayoutManager(std::make_unique<views::FlexLayout>()); layout->SetOrientation(views::LayoutOrientation::kHorizontal) .SetDefault( views::kFlexBehaviorKey, views::FlexSpecification(views::MinimumFlexSizeRule::kPreferred, views::MaximumFlexSizeRule::kUnbounded) .WithAlignment(views::LayoutAlignment::kCenter) .WithWeight(1)); } ColorPickerView::~ColorPickerView() { RemoveAllChildViews(true); } base::Optional<int> ColorPickerView::GetSelectedElement() const { for (size_t i = 0; i < elements_.size(); ++i) { if (elements_[i]->selected()) return static_cast<int>(i); } return base::nullopt; } views::View* ColorPickerView::GetSelectedViewForGroup(int group) { for (ColorPickerElementView* element : elements_) { if (element->selected()) return element; } return nullptr; } views::Button* ColorPickerView::GetElementAtIndexForTesting(int index) { DCHECK_GE(index, 0); DCHECK_LT(index, static_cast<int>(elements_.size())); return elements_[index]; } void ColorPickerView::OnColorSelected(ColorPickerElementView* element) { for (ColorPickerElementView* other_element : elements_) { if (other_element != element) other_element->SetSelected(false); } if (callback_) callback_.Run(); }
l_Style); flags.setColor(color); flags.setAntiAlias(true); canvas->DrawCircle(bounds.CenterPoint(), bounds.width() / 2.0f, flags); PaintSelectionIndicator(canvas); }
function_block-function_prefixed
[]
C++
src/libmv/simple_pipeline/camera_intrinsics.cc
Matthias-Fauconneau/libmv
531c79bf95fddaaa70707d1abcd4fdafda16bbf0
#include "libmv/simple_pipeline/camera_intrinsics.h" #include "libmv/numeric/levenberg_marquardt.h" namespace libmv { struct Offset { signed char ix,iy; unsigned char fx,fy; }; CameraIntrinsics::CameraIntrinsics() : K_(Mat3::Identity()), image_width_(0), image_height_(0), k1_(0), k2_(0), k3_(0), p1_(0), p2_(0), distort_(0), undistort_(0) {} CameraIntrinsics::~CameraIntrinsics() { if(distort_) delete[] distort_; if(undistort_) delete[] undistort_; } void CameraIntrinsics::SetK(const Mat3 new_k) { K_ = new_k; FreeLookupGrid(); } void CameraIntrinsics::SetFocalLength(double focal_x, double focal_y) { K_(0, 0) = focal_x; K_(1, 1) = focal_y; FreeLookupGrid(); } void CameraIntrinsics::SetPrincipalPoint(double cx, double cy) { K_(0, 2) = cx; K_(1, 2) = cy; FreeLookupGrid(); } void CameraIntrinsics::SetImageSize(int width, int height) { image_width_ = width; image_height_ = height; FreeLookupGrid(); } void CameraIntrinsics::SetRadialDistortion(double k1, double k2, double k3) { k1_ = k1; k2_ = k2; k3_ = k3; FreeLookupGrid(); } void CameraIntrinsics::SetTangentialDistortion(double p1, double p2) { p1_ = p1; p2_ = p2; FreeLookupGrid(); } void CameraIntrinsics::ApplyIntrinsics(double normalized_x, double normalized_y, double *image_x, double *image_y) const { double x = normalized_x; double y = normalized_y; double r2 = x*x + y*y; double r4 = r2 * r2; double r6 = r4 * r2; double r_coeff = (1 + k1_*r2 + k2_*r4 + k3_*r6); double xd = x * r_coeff + 2*p1_*x*y + p2_*(r2 + 2*x*x); double yd = y * r_coeff + 2*p2_*x*y + p1_*(r2 + 2*y*y); *image_x = focal_length_x() * xd + principal_point_x(); *image_y = focal_length_y() * yd + principal_point_y(); } struct InvertIntrinsicsCostFunction { public: typedef Vec2 FMatrixType; typedef Vec2 XMatrixType; InvertIntrinsicsCostFunction(const CameraIntrinsics &intrinsics, double image_x, double image_y) : intrinsics(intrinsics), x(image_x), y(image_y) {} Vec2 operator()(const Vec2 &u) const { double xx, yy; intrinsics.ApplyIntrinsics(u(0), u(1), &xx, &yy); Vec2 fx; fx << (xx - x), (yy - y); return fx; } const CameraIntrinsics &intrinsics; double x, y; }; void CameraIntrinsics::InvertIntrinsics(double image_x, double image_y, double *normalized_x, double *normalized_y) const { Vec2 normalized; normalized(0) = (image_x - principal_point_x()) / focal_length_x(); normalized(1) = (image_y - principal_point_y()) / focal_length_y(); typedef LevenbergMarquardt<InvertIntrinsicsCostFunction> Solver; InvertIntrinsicsCostFunction intrinsics_cost(*this, image_x, image_y); Solver::SolverParameters params; Solver solver(intrinsics_cost); solver.minimize(params, &normalized); *normalized_x = normalized(0); *normalized_y = normalized(1); } template<typename WarpFunction> void CameraIntrinsics::ComputeLookupGrid(Offset* grid, int width, int height) { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { double warp_x, warp_y; WarpFunction(this,x,y,&warp_x,&warp_y); int ix = int(warp_x), iy = int(warp_y); int fx = round((warp_x-ix)*256), fy = round((warp_y-iy)*256); if(fx == 256) { fx=0; ix++; } if(fy == 256) { fy=0; iy++; } if( ix < 0 ) { ix = 0, fx = 0; } if( iy < 0 ) { iy = 0, fy = 0; } if( ix >= width-2 ) ix = width-2; if( iy >= height-2 ) iy = height-2; Offset offset = { ix-x, iy-y, fx, fy }; grid[y*width+x] = offset; } } } template<typename T,int N> static void Warp(const Offset* grid, const T* src, T* dst, int width, int height) { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { Offset offset = grid[y*width+x]; const T* s = &src[((y+offset.iy)*width+(x+offset.ix))*N]; for (int i = 0; i < N; i++) { dst[(y*width+x)*N+i] = ((s[ i] * (256-offset.fx) + s[ N+i] * offset.fx) * (256-offset.fy) +(s[width*N+i] * (256-offset.fx) + s[width*N+N+i] * offset.fx) * offset.fy) / (256*256); } } } } void CameraIntrinsics::FreeLookupGrid() { if(distort_) delete distort_, distort_=0; if(undistort_) delete undistort_, undistort_=0; } struct ApplyIntrinsicsFunction { ApplyIntrinsicsFunction(CameraIntrinsics* intrinsics, double x, double y, double *warp_x, double *warp_y) { intrinsics->ApplyIntrinsics( (x-intrinsics->principal_point_x())/intrinsics->focal_length_x(), (y-intrinsics->principal_point_y())/intrinsics->focal_length_y(), warp_x, warp_y); } }; struct InvertIntrinsicsFunction { InvertIntrinsicsFunction(CameraIntrinsics* intrinsics, double x, double y, double *warp_x, double *warp_y) { intrinsics->InvertIntrinsics(x,y,warp_x,warp_y); *warp_x = *warp_x*intrinsics->focal_length_x()+intrinsics->principal_point_x(); *warp_y = *warp_y*intrinsics->focal_length_y()+intrinsics->principal_point_y(); } }; void CameraIntrinsics::Distort(const float* src, float* dst, int width, int height, int channels) { if(!distort_) { distort_ = new Offset[width*height]; ComputeLookupGrid<InvertIntrinsicsFunction>(distort_,width,height); } if(channels==1) Warp<float,1>(distort_,src,dst,width,height); else if(channels==2) Warp<float,2>(distort_,src,dst,width,height); else if(channels==3) Warp<float,3>(distort_,src,dst,width,height); else if(channels==4) Warp<float,4>(distort_,src,dst,width,height); } void CameraIntrinsics::Distort(const unsigned char* src, unsigned char* dst, int width, int height, int channels) { if(!distort_) { distort_ = new Offset[width*height]; ComputeLookupGrid<InvertIntrinsicsFunction>(distort_,width,height); } if(channels==1) Warp<unsigned char,1>(distort_,src,dst,width,height); else if(channels==2) Warp<unsigned char,2>(distort_,src,dst,width,height); else if(channels==3) Warp<unsigned char,3>(distort_,src,dst,width,height); else if(channels==4) Warp<unsigned char,4>(distort_,src,dst,width,height); } void CameraIntrinsics::Undistort(const float* src, float* dst, int width, int height, int channels) { if(!undistort_) { undistort_ = new Offset[width*height]; ComputeLookupGrid<ApplyIntrinsicsFunction>(undistort_,width,height); } if(channels==1) Warp<float,1>(undistort_,src,dst,width,height); else if(channels==2) Warp<float,2>(undistort_,src,dst,width,height); else if(channels==3) Warp<float,3>(undistort_,src,dst,width,height); else if(channels==4) Warp<float,4>(undistort_,src,dst,width,height); } void CameraIntrinsics::Undistort(const unsigned char* src, unsigned char* dst, int width, int height, int channels) { if(!undistort_) { undistort_ = new Offset[width*height]; ComputeLookupGrid<ApplyIntrinsicsFunction>(undistort_,width,height); } if(channels==1) Warp<unsigned char,1>(undistort_,src,dst,width,height); else if(channels==2) Warp<unsigned char,2>(undistort_,src,dst,width,height); else if(channels==3) Warp<unsigned char,3>(undistort_,src,dst,width,height); else if(channels==4) Warp<unsigned char,4>(undistort_,src,dst,width,height); } }
#include "libmv/simple_pipeline/camera_intrinsics.h" #include "libmv/numeric/levenberg_marquardt.h" namespace libmv { struct Offset { signed char ix,iy; unsigned char fx,fy; }; CameraIntrinsics::CameraIntrinsics() : K_(Mat3::Identity()), image_width_(0), image_height_(0), k1_(0), k2_(0), k3_(0), p1_(0), p2_(0), distort_(0), undistort_(0) {} CameraIntrinsics::~CameraIntrinsics() { if(distort_) delete[] distort_; if(undistort_) delete[] undistort_; } void CameraIntrinsics::SetK(const Mat3 new_k) { K_ = new_k; FreeLookupGrid(); } void CameraIntrinsics::SetFocalLength(double focal_x, double focal_y) { K_(0, 0) = focal_x; K_(1, 1) = focal_y; FreeLookupGrid(); } void CameraIntrinsics::SetPrincipalPoint(double cx, double cy) { K_(0, 2) = cx; K_(1, 2) = cy; FreeLookupGrid(); } void CameraIntrinsics::SetImageSize(int width, int height) { image_width_ = width; image_height_ = height; FreeLookupGrid(); } void CameraIntrinsics::SetRadialDistortion(double k1, double k2, double k3) { k1_ = k1; k2_ = k2; k3_ = k3; FreeLookupGrid(); } void CameraIntrinsics::SetTangentialDistortion(double p1, double p2) { p1_ = p1; p2_ = p2; FreeLookupGrid(); } void CameraIntrinsics::ApplyIntrinsics(double normalized_x, double normalized_y, double *image_x, double *image_y) const { double x = normalized_x; double y = normalized_y; double r2 = x*x + y*y; double r4 = r2 * r2; double r6 = r4 * r2; double r_coeff = (1 + k1_*r2 + k2_*r4 + k3_*r6); double xd = x * r_coeff + 2*p1_*x*y + p2_*(r2 + 2*x*x); double yd = y * r_coeff + 2*p2_*x*y + p1_*(r2 + 2*y*y); *image_x = focal_length_x() * xd + principal_point_x(); *image_y = focal_length_y() * yd + principal_point_y(); } struct InvertIntrinsicsCostFunction { public: typedef Vec2 FMatrixType; typedef Vec2 XMatrixType; InvertIntrinsicsCostFunction(const CameraIntrinsics &intrinsics, double image_x, double image_y) : intrinsics(intrinsics), x(image_x), y(image_y) {} Vec2 operator()(const Vec2 &u) const { double xx, yy; intrinsics.ApplyIntrinsics(u(0), u(1), &xx, &yy); Vec2 fx; fx << (xx - x), (yy - y); return fx; } const CameraIntrinsics &intrinsics; double x, y; }; void CameraIntrinsics::InvertIntrinsics(double image_x, double image_y, double *normalized_x, double *normalized_y) const { Vec2 normalized; normalized(0) = (image_x - principal_point_x()) / focal_length_x(); normalized(1) = (image_y - principal_point_y()) / focal_length_y(); typedef LevenbergMarquardt<InvertIntrinsicsCostFunction> Solver; InvertIntrinsicsCostFunction intrinsics_cost(*this, image_x, image_y); Solver::SolverParameters params; Solver solver(intrinsics_cost); solver.minimize(params, &normalized); *normalized_x = normalized(0); *normalized_y = normalized(1); } template<typename WarpFunction> void CameraIntrinsics::ComputeLookupGrid(Offset* grid, int width, int height) { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { double warp_x, warp_y; WarpFunction(this,x,y,&warp_x,&warp_y); int ix = int(warp_x), iy = int(warp_y); int fx = round((warp_x-ix)*256), fy = round((warp_y-iy)*256); if(fx == 256) { fx=0; ix++; } if(fy == 256) { fy=0; iy++; } if( ix < 0 ) { ix = 0, fx = 0; } if( iy < 0 ) { iy = 0, fy = 0; } if( ix >= width-2 ) ix = width-2; if( iy >= height-2 ) iy = height-2; Offset offset = { ix-x, iy-y, fx, fy }; grid[y*width+x] = offset; } } } template<typename T,int N> static void Warp(const Offset* grid, const T* src, T* dst, int width, int height) { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { Offset offset = grid[y*width+x]; const T* s = &src[((y+offset.iy)*width+(x+offset.ix))*N]; for (in
(undistort_,src,dst,width,height); } }
t i = 0; i < N; i++) { dst[(y*width+x)*N+i] = ((s[ i] * (256-offset.fx) + s[ N+i] * offset.fx) * (256-offset.fy) +(s[width*N+i] * (256-offset.fx) + s[width*N+N+i] * offset.fx) * offset.fy) / (256*256); } } } } void CameraIntrinsics::FreeLookupGrid() { if(distort_) delete distort_, distort_=0; if(undistort_) delete undistort_, undistort_=0; } struct ApplyIntrinsicsFunction { ApplyIntrinsicsFunction(CameraIntrinsics* intrinsics, double x, double y, double *warp_x, double *warp_y) { intrinsics->ApplyIntrinsics( (x-intrinsics->principal_point_x())/intrinsics->focal_length_x(), (y-intrinsics->principal_point_y())/intrinsics->focal_length_y(), warp_x, warp_y); } }; struct InvertIntrinsicsFunction { InvertIntrinsicsFunction(CameraIntrinsics* intrinsics, double x, double y, double *warp_x, double *warp_y) { intrinsics->InvertIntrinsics(x,y,warp_x,warp_y); *warp_x = *warp_x*intrinsics->focal_length_x()+intrinsics->principal_point_x(); *warp_y = *warp_y*intrinsics->focal_length_y()+intrinsics->principal_point_y(); } }; void CameraIntrinsics::Distort(const float* src, float* dst, int width, int height, int channels) { if(!distort_) { distort_ = new Offset[width*height]; ComputeLookupGrid<InvertIntrinsicsFunction>(distort_,width,height); } if(channels==1) Warp<float,1>(distort_,src,dst,width,height); else if(channels==2) Warp<float,2>(distort_,src,dst,width,height); else if(channels==3) Warp<float,3>(distort_,src,dst,width,height); else if(channels==4) Warp<float,4>(distort_,src,dst,width,height); } void CameraIntrinsics::Distort(const unsigned char* src, unsigned char* dst, int width, int height, int channels) { if(!distort_) { distort_ = new Offset[width*height]; ComputeLookupGrid<InvertIntrinsicsFunction>(distort_,width,height); } if(channels==1) Warp<unsigned char,1>(distort_,src,dst,width,height); else if(channels==2) Warp<unsigned char,2>(distort_,src,dst,width,height); else if(channels==3) Warp<unsigned char,3>(distort_,src,dst,width,height); else if(channels==4) Warp<unsigned char,4>(distort_,src,dst,width,height); } void CameraIntrinsics::Undistort(const float* src, float* dst, int width, int height, int channels) { if(!undistort_) { undistort_ = new Offset[width*height]; ComputeLookupGrid<ApplyIntrinsicsFunction>(undistort_,width,height); } if(channels==1) Warp<float,1>(undistort_,src,dst,width,height); else if(channels==2) Warp<float,2>(undistort_,src,dst,width,height); else if(channels==3) Warp<float,3>(undistort_,src,dst,width,height); else if(channels==4) Warp<float,4>(undistort_,src,dst,width,height); } void CameraIntrinsics::Undistort(const unsigned char* src, unsigned char* dst, int width, int height, int channels) { if(!undistort_) { undistort_ = new Offset[width*height]; ComputeLookupGrid<ApplyIntrinsicsFunction>(undistort_,width,height); } if(channels==1) Warp<unsigned char,1>(undistort_,src,dst,width,height); else if(channels==2) Warp<unsigned char,2>(undistort_,src,dst,width,height); else if(channels==3) Warp<unsigned char,3>(undistort_,src,dst,width,height); else if(channels==4) Warp<unsigned char,4>
random
[ { "content": "struct tuple_size<GTEST_2_TUPLE_(T)> { static const int value = 2; };\n\n\n\ntemplate <GTEST_3_TYPENAMES_(T)>\n", "file_path": "src/third_party/gtest/include/gtest/internal/gtest-tuple.h", "rank": 1, "score": 343036.2119991771 }, { "content": "struct tuple_size<GTEST_0_TUPLE_(T...
C++
tests/experimental/strong_type/strong_type.t.cpp
tobanteAudio/taetl
0aa6365aa156b297745f395882ff366a8626e5e0
#include "etl/experimental/strong_type/strong_type.hpp" #include "etl/cstdint.hpp" #include "etl/type_traits.hpp" #include "testing/testing.hpp" using namespace etl::experimental; template <typename T> constexpr auto test() -> bool { { using Kilogram = strong_type<T, struct Kilogram_tag>; auto kilo = Kilogram {}; kilo = Kilogram { 0 }; assert((kilo.raw_value() == T { 0 })); } { using Kilo = strong_type<T, struct Kilo_tag>; assert((sizeof(Kilo) == sizeof(typename Kilo::value_type))); assert((etl::is_constructible_v<Kilo>)); assert((etl::is_trivially_constructible_v<Kilo>)); assert((etl::is_nothrow_constructible_v<Kilo>)); assert((etl::is_destructible_v<Kilo>)); assert((etl::is_trivially_destructible_v<Kilo>)); assert((etl::is_nothrow_destructible_v<Kilo>)); assert((etl::is_assignable_v<Kilo, Kilo>)); assert((etl::is_trivially_assignable_v<Kilo, Kilo>)); assert((etl::is_nothrow_assignable_v<Kilo, Kilo>)); assert((etl::is_copy_constructible_v<Kilo>)); assert((etl::is_trivially_copy_constructible_v<Kilo>)); assert((etl::is_nothrow_copy_constructible_v<Kilo>)); assert((etl::is_copy_assignable_v<Kilo>)); assert((etl::is_trivially_copy_assignable_v<Kilo>)); assert((etl::is_nothrow_copy_assignable_v<Kilo>)); assert((etl::is_move_constructible_v<Kilo>)); assert((etl::is_trivially_move_constructible_v<Kilo>)); assert((etl::is_nothrow_move_constructible_v<Kilo>)); assert((etl::is_move_assignable_v<Kilo>)); assert((etl::is_trivially_move_assignable_v<Kilo>)); assert((etl::is_nothrow_move_assignable_v<Kilo>)); assert((etl::is_swappable_v<Kilo>)); assert((etl::is_nothrow_swappable_v<Kilo>)); assert((!etl::has_virtual_destructor_v<Kilo>)); } { using Kilo = strong_type<T, struct Kilo_tag, skill::addable>; auto const lhs = Kilo(1); auto const rhs = Kilo(2); auto const sum = lhs + rhs; assert((sum.raw_value() == T(3))); } { using Kilo = strong_type<T, struct Kilo_tag, skill::subtractable>; auto const lhs = Kilo(2); auto const rhs = Kilo(1); auto const sum = lhs - rhs; assert((sum.raw_value() == T(1))); } { using Kilo = strong_type<T, struct Kilo_tag, skill::multipliable>; auto const lhs = Kilo(2); auto const rhs = Kilo(2); auto const sum = lhs * rhs; assert((sum.raw_value() == T(4))); } { using Kilo = strong_type<T, struct Kilo_tag, skill::divisible>; auto const lhs = Kilo(2); auto const rhs = Kilo(2); auto const sum = lhs / rhs; assert((sum.raw_value() == T(1))); } { using Hertz = strong_type<T, struct Hertz_tag, skill::comparable>; auto const lhs = Hertz { typename Hertz::value_type(44) }; auto const rhs = Hertz { typename Hertz::value_type(48) }; assert((lhs.raw_value() == typename Hertz::value_type(44))); assert((rhs.raw_value() == typename Hertz::value_type(48))); assert((lhs < rhs)); assert((!(lhs > rhs))); assert((lhs <= rhs)); assert((!(lhs >= rhs))); assert((lhs != rhs)); assert((!(lhs == rhs))); } return true; } constexpr auto test_all() -> bool { assert(test<etl::uint8_t>()); assert(test<etl::int8_t>()); assert(test<etl::uint16_t>()); assert(test<etl::int16_t>()); assert(test<etl::uint32_t>()); assert(test<etl::int32_t>()); assert(test<etl::uint64_t>()); assert(test<etl::int64_t>()); assert(test<float>()); assert(test<double>()); assert(test<long double>()); return true; } auto main() -> int { assert(test_all()); static_assert(test_all()); return 0; }
#include "etl/experimental/strong_type/strong_type.hpp" #include "etl/cstdint.hpp" #include "etl/type_traits.hpp" #include "testing/testing.hpp" using namespace etl::experimental; template <typename T> constexpr auto test() -> bool { { using Kilogram = strong_type<T, struct Kilogram_tag>; auto kilo = Kilogram {}; kilo = Kilogram { 0 }; assert((kilo.raw_value() == T { 0 })); } { using Kilo = strong_type<T, struct Kilo_tag>; assert((sizeof(Kilo) == sizeof(typename Kilo::value_type))); assert((etl:
to const sum = lhs / rhs; assert((sum.raw_value() == T(1))); } { using Hertz = strong_type<T, struct Hertz_tag, skill::comparable>; auto const lhs = Hertz { typename Hertz::value_type(44) }; auto const rhs = Hertz { typename Hertz::value_type(48) }; assert((lhs.raw_value() == typename Hertz::value_type(44))); assert((rhs.raw_value() == typename Hertz::value_type(48))); assert((lhs < rhs)); assert((!(lhs > rhs))); assert((lhs <= rhs)); assert((!(lhs >= rhs))); assert((lhs != rhs)); assert((!(lhs == rhs))); } return true; } constexpr auto test_all() -> bool { assert(test<etl::uint8_t>()); assert(test<etl::int8_t>()); assert(test<etl::uint16_t>()); assert(test<etl::int16_t>()); assert(test<etl::uint32_t>()); assert(test<etl::int32_t>()); assert(test<etl::uint64_t>()); assert(test<etl::int64_t>()); assert(test<float>()); assert(test<double>()); assert(test<long double>()); return true; } auto main() -> int { assert(test_all()); static_assert(test_all()); return 0; }
:is_constructible_v<Kilo>)); assert((etl::is_trivially_constructible_v<Kilo>)); assert((etl::is_nothrow_constructible_v<Kilo>)); assert((etl::is_destructible_v<Kilo>)); assert((etl::is_trivially_destructible_v<Kilo>)); assert((etl::is_nothrow_destructible_v<Kilo>)); assert((etl::is_assignable_v<Kilo, Kilo>)); assert((etl::is_trivially_assignable_v<Kilo, Kilo>)); assert((etl::is_nothrow_assignable_v<Kilo, Kilo>)); assert((etl::is_copy_constructible_v<Kilo>)); assert((etl::is_trivially_copy_constructible_v<Kilo>)); assert((etl::is_nothrow_copy_constructible_v<Kilo>)); assert((etl::is_copy_assignable_v<Kilo>)); assert((etl::is_trivially_copy_assignable_v<Kilo>)); assert((etl::is_nothrow_copy_assignable_v<Kilo>)); assert((etl::is_move_constructible_v<Kilo>)); assert((etl::is_trivially_move_constructible_v<Kilo>)); assert((etl::is_nothrow_move_constructible_v<Kilo>)); assert((etl::is_move_assignable_v<Kilo>)); assert((etl::is_trivially_move_assignable_v<Kilo>)); assert((etl::is_nothrow_move_assignable_v<Kilo>)); assert((etl::is_swappable_v<Kilo>)); assert((etl::is_nothrow_swappable_v<Kilo>)); assert((!etl::has_virtual_destructor_v<Kilo>)); } { using Kilo = strong_type<T, struct Kilo_tag, skill::addable>; auto const lhs = Kilo(1); auto const rhs = Kilo(2); auto const sum = lhs + rhs; assert((sum.raw_value() == T(3))); } { using Kilo = strong_type<T, struct Kilo_tag, skill::subtractable>; auto const lhs = Kilo(2); auto const rhs = Kilo(1); auto const sum = lhs - rhs; assert((sum.raw_value() == T(1))); } { using Kilo = strong_type<T, struct Kilo_tag, skill::multipliable>; auto const lhs = Kilo(2); auto const rhs = Kilo(2); auto const sum = lhs * rhs; assert((sum.raw_value() == T(4))); } { using Kilo = strong_type<T, struct Kilo_tag, skill::divisible>; auto const lhs = Kilo(2); auto const rhs = Kilo(2); au
function_block-random_span
[ { "content": "struct auto_reg {\n\n explicit auto_reg(name_and_tags const& sp, test_func_t func)\n\n {\n\n current_session().add_test(sp, func);\n\n }\n\n};\n\n\n\n} // namespace etl::test\n\n\n\n#endif // ETL_EXPERIMENTAL_TESTING_SESSION_HPP\n", "file_path": "etl/experimental/testing/sessio...
C++
tests/benchmark/src/UAutomizerFileReader-test.cpp
typesAreSpaces/AXDInterpolator
e0759c806480ff54b7a4f878e007b534a71dad44
#include "UAutomizerFileReader.h" void UAutomizerFileReader::testAXDInterpolator() const { TEMP_FILE_SETUP; BENCHMARK_COMMAND( z3::solver tseitin_solver(ctx, "QF_AUFLIA"); tseitin_solver.add(z3::mk_and(part_a)); tseitin_solver.add(z3::mk_and(part_b)); axdinterpolator_file << tseitin_solver.to_smt2(); axdinterpolator_file.close();, sprintf(exec_command, "./../../bin/axd_interpolator QF_LIA %s %u 1000000;", file_for_implementation.c_str(), curr_solver);, #if REPORT_BAD_CASES if(ret != 0 && ret != 152){ char complain_command[1000]; sprintf( complain_command, "echo File: \"%s\" Solver Code: \"%u\" Sample Id: %d Exit Code: %d >> /home/jose/bad_cases.txt", file_for_implementation.c_str(), curr_solver, 500 - num_samples, ret); system(complain_command); system(("mv " + file_for_implementation + " ~/" + file_for_implementation + std::to_string(500 - num_samples)).c_str()); } #endif sprintf(log_command, "echo File: \"%s\" Solver Code: \"%u\" Exit Code: %d >> \"%s\"", file_for_implementation.c_str(), curr_solver, ret, file_statistics); ); system(("rm -rf " + temp_file).c_str()); } void UAutomizerFileReader::testOtherSolvers() { switch(curr_solver){ case Z3: { TEMP_FILE_SETUP; BENCHMARK_COMMAND( z3::solver tseitin_solver(ctx, "QF_AUFLIA"); tseitin_solver.add(z3::mk_and(part_a)); tseitin_solver.add(z3::mk_and(part_b)); axdinterpolator_file << "(set-option :produce-interpolants true)" << std::endl; axdinterpolator_file << "(set-logic QF_AUFLIA)" << std::endl; axdinterpolator_file << nameAssertionsZ3(tseitin_solver.to_smt2()); axdinterpolator_file << "(get-interpolant part_a part_b)" << std::endl; axdinterpolator_file.close();, std::string temp_file_name = "z3_inter_temp_" + current_file; sprintf(exec_command, "./../../bin/z3 %s > %s;", file_for_implementation.c_str(), temp_file_name.c_str());, std::ifstream result(temp_file_name.c_str()); std::string line(""); std::string interpolant_from_file(""); std::getline(result, line); if(line == "unsat"){ std::getline(result, line); interpolant_from_file += tseitin_solver.to_smt2_decls_only(); interpolant_from_file += "(assert (and true\n"; while(std::getline(result, line)) interpolant_from_file += line + "\n"; interpolant_from_file += ")\n"; interpolant_from_file += "(check-sat)\n"; system(("rm -rf " + temp_file_name).c_str()); z3::solver z3_interpolant_parser(ctx, "QF_AUFLIA"); z3_interpolant_parser.from_string(interpolant_from_file.c_str()); auto const & interpolant_result = z3_interpolant_parser.assertions(); std::cout << interpolant_result << std::endl; sprintf(log_command, "echo File: \"%s\" Solver Code: \"%u\" Exit Code: %d >> \"%s\"", file_for_implementation.c_str(), 3, ret, file_statistics); } else{ system(("rm -rf " + temp_file_name).c_str()); sprintf(log_command, "echo File: \"%s\" Solver Code: \"%u\" Exit Code: %d >> \"%s\"", file_for_implementation.c_str(), 3, 1, file_statistics); } ); system(("rm -rf " + temp_file).c_str()); } return; case MATHSAT: { TEMP_FILE_SETUP; BENCHMARK_COMMAND( z3::solver tseitin_solver(ctx, "QF_AUFLIA"); tseitin_solver.add(z3::mk_and(part_a)); tseitin_solver.add(z3::mk_and(part_b)); axdinterpolator_file << "(set-option :produce-interpolants true)" << std::endl; axdinterpolator_file << nameAssertionsMathsat(tseitin_solver.to_smt2()); axdinterpolator_file << "(get-interpolant (part_a))" << std::endl; axdinterpolator_file.close();, std::string temp_file_name = "mathsat_inter_temp_" + current_file; sprintf(exec_command, "./../../bin/mathsat %s > %s;", file_for_implementation.c_str(), temp_file_name.c_str());, std::ifstream result(temp_file_name.c_str()); std::string line(""); std::string interpolant_from_file(""); std::getline(result, line); if(line == "unsat"){ interpolant_from_file += tseitin_solver.to_smt2_decls_only(); interpolant_from_file += "(assert (and true\n"; std::string _interpolant_result = ""; while(std::getline(result, line)) _interpolant_result += line + "\n"; if(_interpolant_result.find("build ie-local interpolant") != std::string::npos){ system(("rm -rf " + temp_file_name).c_str()); sprintf(log_command, "echo File: \"%s\" Solver Code: \"%u\" Exit Code: %d >> \"%s\"", file_for_implementation.c_str(), 4, 1, file_statistics); } else { interpolant_from_file += _interpolant_result; interpolant_from_file += "))\n"; interpolant_from_file += "(check-sat)\n"; system(("rm -rf " + temp_file_name).c_str()); z3::solver mathsat_interpolant_parser(ctx, "QF_AUFLIA"); mathsat_interpolant_parser.from_string(interpolant_from_file.c_str()); auto const & interpolant_result = mathsat_interpolant_parser.assertions(); std::cout << interpolant_result << std::endl; sprintf(log_command, "echo File: \"%s\" Solver Code: \"%u\" Exit Code: %d >> \"%s\"", file_for_implementation.c_str(), 4, ret, file_statistics); } } else{ system(("rm -rf " + temp_file_name).c_str()); sprintf(log_command, "echo File: \"%s\" Solver Code: \"%u\" Exit Code: %d >> \"%s\"", file_for_implementation.c_str(), 4, 1, file_statistics); } ); system(("rm -rf " + temp_file).c_str()); } return; case SMTINTERPOL: { TEMP_FILE_SETUP; BENCHMARK_COMMAND( z3::solver tseitin_solver(ctx, "QF_AUFLIA"); tseitin_solver.add(z3::mk_and(part_a)); tseitin_solver.add(z3::mk_and(part_b)); axdinterpolator_file << "(set-option :print-success false)\n" << "(set-option :produce-interpolants true)" << std::endl; axdinterpolator_file << "(set-logic QF_AUFLIA)" << std::endl; axdinterpolator_file << nameAssertionsZ3(tseitin_solver.to_smt2()); axdinterpolator_file << "(get-interpolants part_a part_b)" << std::endl; axdinterpolator_file.close();, std::string temp_file_name = "smtinterpol_inter_temp_" + current_file; sprintf(exec_command, "java -jar ./../../bin/smtinterpol-2.5-663-gf15aa217.jar -w %s > %s", file_for_implementation.c_str(), temp_file_name.c_str());, std::ifstream result(temp_file_name.c_str()); std::string line(""); std::string interpolant_from_file(""); std::getline(result, line); if(line == "unsat"){ interpolant_from_file += tseitin_solver.to_smt2_decls_only(); interpolant_from_file += "(assert \n"; std::getline(result, line); interpolant_from_file += line.erase(0, 1) + "\n"; interpolant_from_file.erase(interpolant_from_file.size() - 2, 2); interpolant_from_file += ")\n"; interpolant_from_file += "(check-sat)\n"; system(("rm -rf " + temp_file_name).c_str()); z3::solver smtinterpol_interpolant_parser(ctx, "QF_AUFLIA"); smtinterpol_interpolant_parser.from_string(interpolant_from_file.c_str()); auto const & interpolant_result = smtinterpol_interpolant_parser.assertions(); std::cerr << interpolant_result << std::endl; sprintf(log_command, "echo File: \"%s\" Solver Code: \"%u\" Exit Code: %d >> \"%s\"", file_for_implementation.c_str(), 5, ret, file_statistics); } else{ system(("rm -rf " + temp_file_name).c_str()); sprintf(log_command, "echo File: \"%s\" Solver Code: \"%u\" Exit Code: %d >> \"%s\"", file_for_implementation.c_str(), 5, 1, file_statistics); } ); system(("rm -rf " + temp_file).c_str()); } return; } }
#include "UAutomizerFileReader.h" void UAutomizerFileReader::testAXDInterpolator() const { TEMP_FILE_SETUP; BENCHMARK_COMMAND( z3::solver tseitin_solver(ctx, "QF_AUFLIA"); tseitin_solver.add(z3::mk_and(part_a)); tseitin_solver.add(z3::mk_and(part_b)); axdinterpolator_file << tseitin_solver.to_smt2(); axdinterpolator_file.close();, sprintf(exec_command, "./../../bin/axd_interpolator QF_LIA %s %u 1000000;", file_for_implementation.c_str(), curr_solver);, #if REPORT_BAD_CASES if(ret != 0 && ret != 152){ char complain_command[1000]; sprintf( complain_command, "echo File: \"%s\" Solver Code: \"%u\" Sample Id: %d Exit Code: %d >> /home/jose/bad_cases.txt", file_for_implementation.c_str(), curr_solver, 500 - num_samples, ret); system(complain_command); system(("mv " + file_for_implementation + " ~/" + file_for_implementation + std::to_string(500 - num_samples)).c_str()); } #endif sprintf(log_command, "echo File: \"%s\" Solver Code: \"%u\" Exit Code: %d >> \"%s\"", file_for_implementation.c_str(), curr_solver, ret, file_statistics); ); system(("rm -rf " + temp_file).c_str()); } void UAutomizerFileReader::testOtherSolvers() { switch(curr_solver){ case Z3: { TEMP_FILE_SETUP; BENCHMARK_COMMAND( z3::solver tseitin_solver(ctx, "QF_AUFLIA"); tseitin_solver.add(z3::mk_and(part_a)); tseitin_solver.add(z3::mk_and(part_b)); axdinterpolator_file << "(set-option :produce-interpolants true)" << std::endl; axdinterpolator_file << "(set-logic QF_AUFLIA)" << std::endl; axdinterpolator_file << nameAssertionsZ3(tseitin_solver.to_smt2()); axdinterpolator_file << "(get-interpolant part_a part_b)" << std::endl; axdinterpolator_file.close();, std::string temp_file_name = "z3_inter_temp_" + current_file; sprintf(exec_command, "./../../bin/z3 %s > %s;", file_for_implementation.c_str(), temp_file_name.c_str());, std::ifstream result(temp_file_name.c_str()); std::string line(""); std::string interpolant_from_file(""); std::getline(result, line); if(line == "unsat"){ std::getline(result, line); interpolant_from_file += tseitin_solver.to_smt2_decls_only(); interpolant_from_file += "(assert (and true\n"; while(std::getline(result, line)) interpolant_from_file += line + "\n"; interpolant_from_file += ")\n"; interpolant_from_file += "(check-sat)\n"; system(("rm -rf " + temp_file_name).c_str()); z3::solver z3_interpolant_parser(ctx, "QF_AUFLIA"); z3_interpolant_parser.from_string(interpolant_from_file.c_str()); auto const & interpolant_result = z3_interpolant_parser.assertions(); std::cout << interpolant_result << std::endl; sprintf(log_command, "echo File: \"%s\" Solver Code: \"%u\" Exit Code: %d >> \"%s\"", file_for_implementation.c_str(), 3, ret, file_statistics); } else{ system(("rm -rf " + temp_file_name).c_str()); sprintf(log_command, "echo File: \"%s\" Solver Code: \"%u\" Exit Code: %d >> \"%s\"", file_for_implementation.c_str(), 3, 1, file_statistics); } ); system(("rm -rf " + temp_file).c_str()); } return; case MATHSAT: { TEMP_FILE_SETUP; BENCHMARK_COMMAND( z3::solver tseitin_solver(ctx, "QF_AUFLIA"); tseitin_solver.add(z3::mk_and(part_a)); tseitin_solver.add(z3::mk_and(part_b)); axdinterpolator_file << "(set-option :produce-interpolants true)" << std::endl; axdinterpolator_file << nameAssertionsMathsat(tseitin_solver.to_smt2()); axdinterpolator_file << "(get-interpolant (part_a))" << std::endl; axdinterpolator_file.close();, std::string temp_file_name = "mathsat_inter_temp_" + current_file; sprintf(exec_command, "./../../bin/mathsat %s > %s;", file_for_implementation.c_str(), temp_file_name.c_str());, std::ifstream result(temp_file_name.c_str()); std::string line(""); std::string interpolant_from_file(""); std::getline(result, line); if(line == "unsat"){ interpolant_from_file += tseitin_solver.to_smt2_decls_only(); interpolant_from_file += "(assert (and true\n"; std::string _interpolant_result = ""; while(std::getline(result, line)) _interpolant_result += line + "\n"; if(_interpolant_result.find("build ie-local interpolant") != std::string::npos){ system(("rm -rf " + temp_file_name).c_str()); sprintf(log_command, "echo File: \"%s\" Solver Code: \"%u\" Exit Code: %d >> \"%s\"", file_for_implementation.c_str(), 4, 1, file_statistics); } else { interpolant_from_file += _interpolant_result; interpolant_from_file += "))\n"; interpolant_from_file += "(check-sat)\n"; system(("rm -rf " + temp_file_name).c_str()); z3::solver mathsat_interpolant_parser(ctx, "QF_AUFLIA"); mathsat_interpolant_parser.from_string(interpolant_from_file.c_str()); auto const & interpolant_result = mathsat_interpolant_parser.assertions(); std::cout << interpolant_result << std::endl; sprintf(log_command, "echo File: \"%s\" Solver Code: \"%u\" Exit Code: %d >> \"%s\"", file_for_implementation.c_str(), 4, ret, file_statistics); } } else{ system(("rm -rf " + temp_file_name).c_str()); sprintf(log_command, "echo File: \"%s\" Solver Code: \"%u\" Exit Code: %d >> \"%s\"", file_for_implementation.c_str(), 4, 1, file_statistics); } ); system(("rm -rf " + temp_file).c_str()); } return; case SMTINTERPOL: { TEMP_FILE_SETUP; BENCHMARK_COMMAND( z3::solver tseitin_solver(ctx, "QF_AUFLIA"); tseitin_solver.add(z3::mk_and(part_a)); tseitin_solver.add(z3::mk_and(part_b)); axdinterpolator_file << "(set-option :print-success false)\n" << "(set-option :produce-interpolants true)" << std::endl; axdinterpolator_file << "(set-logic QF_AUFLIA)" << std::endl; axdinterpolator_file << nameAssertionsZ3(tseitin_solver.to_smt2()); axdinterpolator_file << "(get-interpolants part_a part_b)" << std::endl; axdinterpolator_file.close();, std::string temp_file_name = "smtinterpol_inter_temp_" + current_file; sprintf(exec_command, "java -jar ./../../bin/smtinterpol-2.5-663-gf15aa217.jar -w %s > %s", file_for_implementation.c_str(), temp_file_name.c_str());, std::ifstream result(temp_file_name.c_str()); std::string line(""); std::string interpolant_from_file(""); std::getline(result, line); if(line == "unsat"){ interpolant_from_file += tseitin_solver.to_smt2_decls_only(); interpolant_from_file += "(assert \n"; std::getline(result, line); interpolant_from_file += line.erase(0, 1) + "\n"; interpolant_from_file.erase(interpolant_from_file.size() - 2, 2);
interpolant_from_file += ")\n"; interpolant_from_file += "(check-sat)\n"; system(("rm -rf " + temp_file_name).c_str()); z3::solver smtinterpol_interpolant_parser(ctx, "QF_AUFLIA"); smtinterpol_interpolant_parser.from_string(interpolant_from_file.c_str()); auto const & interpolant_result = smtinterpol_interpolant_parser.assertions(); std::cerr << interpolant_result << std::endl; sprintf(log_command, "echo File: \"%s\" Solver Code: \"%u\" Exit Code: %d >> \"%s\"", file_for_implementation.c_str(), 5, ret, file_statistics); } else{ system(("rm -rf " + temp_file_name).c_str()); sprintf(log_command, "echo File: \"%s\" Solver Code: \"%u\" Exit Code: %d >> \"%s\"", file_for_implementation.c_str(), 5, 1, file_statistics); } ); system(("rm -rf " + temp_file).c_str()); } return; } }
function_block-function_prefix_line
[ { "content": "enum SMT_SOLVER { Z3, MATHSAT, SMTINTERPOL };\n\n\n", "file_path": "tests/benchmark/include/UAutomizerFileReader.h", "rank": 0, "score": 219527.99814903465 }, { "content": "enum BENCHMARK_EXIT_CODE { SUCCESS, FAILED, TIMEOUT };\n", "file_path": "tests/benchmark/include/UAut...
C++
problemes/probleme1xx/probleme185.cpp
ZongoForSpeed/ProjectEuler
2e2d45f984d48a1da8275886c976f909a0de94ce
#include "problemes.h" #include "arithmetique.h" #include <fstream> typedef unsigned long long nombre; typedef std::vector<nombre> vecteur; typedef std::pair<std::string, unsigned short> paire; typedef std::vector<paire> ensemble; namespace { template<typename Iterator> bool cherche_solution(Iterator debut, Iterator fin, std::vector<std::set<char>> &solutions) { if (debut == fin) { for (const auto &s: solutions) if (s.size() != 1) return false; return true; } for (const auto &s: solutions) if (s.empty()) return false; auto essai = *debut; std::set<size_t> test; for (size_t n = 0; n < solutions.size(); ++n) test.insert(n); for (size_t n = 0; n < solutions.size(); ++n) { auto s = solutions[n]; if (solutions[n].size() == 1) { if (*solutions[n].begin() == essai.first[n]) { essai.second--; test.erase(n); } } if (s.find(essai.first[n]) == s.end()) { test.erase(n); } } if (test.size() < essai.second) return false; if (essai.second == 0) { for (size_t n: test) { solutions[n].erase(essai.first[n]); } return cherche_solution(++debut, fin, solutions); } else { std::vector<bool> combinaison(test.size(), true); for (size_t n = 0; n < essai.second; ++n) combinaison.at(n) = false; do { auto s = solutions; bool suivant = false; size_t position = 0; for (size_t n: test) { if (combinaison[position]) s[n].erase(essai.first[n]); else if (s[n].find(essai.first[n]) == s[n].end()) { suivant = true; break; } else s[n] = {essai.first[n]}; ++position; } if (suivant) continue; if (cherche_solution(std::next(debut), fin, s)) { std::swap(s, solutions); return true; } } while (std::next_permutation(combinaison.begin(), combinaison.end())); return false; } } } ENREGISTRER_PROBLEME(185, "Number Mind") { std::ifstream ifs("data/p185_number_mind.txt"); ensemble essais; size_t taille = 0; std::string pattern, correct, ignore; while (ifs >> pattern >> correct >> ignore) { taille = pattern.size(); essais.emplace_back(pattern, correct[1] - '0'); } std::set<char> chiffres{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; std::vector<std::set<char>> solutions; for (size_t n = 0; n < taille; ++n) solutions.push_back(chiffres); cherche_solution(essais.begin(), essais.end(), solutions); std::ostringstream oss; for (const auto &s: solutions) oss << *s.begin(); return oss.str(); }
#include "problemes.h" #include "arithmetique.h" #include <fstream> typedef unsigned long long nombre; typedef std::vector<nombre> vecteur; typedef std::pair<std::string, unsigned short> paire; typedef std::vector<paire> ensemble; namespace { template<typename Iterator> bool cherche_solution(Iterator debut, Iterator fin, std::vector<std::set<char>> &solutions) { if (debut == fin) { for (const auto &s: solutions) if (s.size() != 1) return false; return true; } for (const auto &s: solutions) if (s.empty()) return false; auto essai = *debut; std::set<size_t> test; for (size_t n = 0; n < solutions.size(); ++n) test.insert(n); for (size_t n = 0; n < solutions.size(); ++n) { auto s = solutions[n]; if (solutions[n].size() == 1) { if (*solutions[n].begin() == essai.first[n]) { essai.second--; test.erase(n); } }
} ENREGISTRER_PROBLEME(185, "Number Mind") { std::ifstream ifs("data/p185_number_mind.txt"); ensemble essais; size_t taille = 0; std::string pattern, correct, ignore; while (ifs >> pattern >> correct >> ignore) { taille = pattern.size(); essais.emplace_back(pattern, correct[1] - '0'); } std::set<char> chiffres{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; std::vector<std::set<char>> solutions; for (size_t n = 0; n < taille; ++n) solutions.push_back(chiffres); cherche_solution(essais.begin(), essais.end(), solutions); std::ostringstream oss; for (const auto &s: solutions) oss << *s.begin(); return oss.str(); }
if (s.find(essai.first[n]) == s.end()) { test.erase(n); } } if (test.size() < essai.second) return false; if (essai.second == 0) { for (size_t n: test) { solutions[n].erase(essai.first[n]); } return cherche_solution(++debut, fin, solutions); } else { std::vector<bool> combinaison(test.size(), true); for (size_t n = 0; n < essai.second; ++n) combinaison.at(n) = false; do { auto s = solutions; bool suivant = false; size_t position = 0; for (size_t n: test) { if (combinaison[position]) s[n].erase(essai.first[n]); else if (s[n].find(essai.first[n]) == s[n].end()) { suivant = true; break; } else s[n] = {essai.first[n]}; ++position; } if (suivant) continue; if (cherche_solution(std::next(debut), fin, s)) { std::swap(s, solutions); return true; } } while (std::next_permutation(combinaison.begin(), combinaison.end())); return false; } }
function_block-function_prefix_line
[ { "content": " class numeric_limits<mpz_nombre> : public numeric_limits<long long> {\n\n public:\n\n static constexpr int digits = INT_MAX;\n\n static constexpr int digits10 = INT_MAX;\n\n\n\n static mpz_nombre max() {\n\n return mpz_nombre::puissance(2, digits);\n\n ...
C++
include/zisa/memory/array_view_impl.hpp
1uc/ZisaMemory
9d9689e46e63629f842b04765bc322f32d91758e
#ifndef ARRAY_VIEW_IMPL_HPP #define ARRAY_VIEW_IMPL_HPP namespace zisa { template <class T> auto raw_ptr(T *a) -> decltype(a) { return a; } template <class T, class Indexing> array_view_base<T, Indexing>::array_view_base(array_view_base::shape_type shape, T *ptr, device_type mem_location) : _shape(shape), _ptr(ptr), _mem_location(mem_location) {} template <class T, class Indexing> typename array_view_base<T, Indexing>::size_type array_view_base<T, Indexing>::size() const { return product(_shape); } template <class T, class Indexing> const typename array_view_base<T, Indexing>::shape_type & array_view_base<T, Indexing>::shape() const { return _shape; } template <class T, class Indexing> typename array_view_base<T, Indexing>::size_type array_view_base<T, Indexing>::shape(array_view_base::size_type i) const { return _shape(i); } template <class T, class Indexing> device_type memory_location(const array_view_base<T, Indexing> &view) { return view.memory_location(); } template <class T, int n_dims, template <int> class Indexing> array_view<T, n_dims, Indexing>::array_view(const shape_t<n_dims> &shape, T *ptr, device_type mem_location) : super(shape, ptr, mem_location) {} template <class T, int n_dims, template <int> class Indexing> template <class Array, class Shape> array_view<T, n_dims, Indexing>::array_view( array_base<T, Indexing<n_dims>, Array, Shape> &other) : array_view(zisa::shape(other), zisa::raw_ptr(other), zisa::memory_location(other)) {} template <class T, int n_dims, template <int> class Indexing> array_view<T, n_dims, Indexing>::array_view(std::vector<T> &v) : array_view(shape_t<1>{v.size()}, v.data(), device_type::cpu) {} template <class T, int n_dims, template <int> class Indexing> T *array_view<T, n_dims, Indexing>::raw() const { return this->_ptr; } template <class T, int n_dims, template <int> class Indexing> T &array_view<T, n_dims, Indexing>::operator[](array_view::size_type i) const { return this->_ptr[i]; } template <class T, int n_dims, template <int> class Indexing> template <class... Ints> T &array_view<T, n_dims, Indexing>::operator()(Ints... ints) const { auto l = Indexing<n_dims>::linear_index(this->shape(), integer_cast<size_type>(ints)...); return (*this)[l]; } template <class T, int n_dims, template <int> class Indexing> T *array_view<T, n_dims, Indexing>::begin() const { return this->_ptr; } template <class T, int n_dims, template <int> class Indexing> T *array_view<T, n_dims, Indexing>::end() const { return this->_ptr + this->size(); } template <class T, int n_dims, template <int> class Indexing> T const *array_view<T, n_dims, Indexing>::cbegin() const { return this->_ptr; } template <class T, int n_dims, template <int> class Indexing> T const *array_view<T, n_dims, Indexing>::cend() const { return this->_ptr + this->size(); } template <class T, int n_dims, template <int> class Indexing> void array_view<T, n_dims, Indexing>::copy_data( const array_view<T, n_dims, Indexing> &other) const { copy_data(array_const_view<T, n_dims, Indexing>(other)); } template <class T, int n_dims, template <int> class Indexing> void array_view<T, n_dims, Indexing>::copy_data( const array_const_view<T, n_dims, Indexing> &other) const { assert((*this).shape() == other.shape()); LOG_ERR_IF(this->memory_location() == device_type::cuda, "Implement this."); if (other.raw() != (*this).raw()) { std::copy(other.begin(), other.end(), (*this).begin()); } } } #endif
#ifndef ARRAY_VIEW_IMPL_HPP #define ARRAY_VIEW_IMPL_HPP namespace zisa { template <class T> auto raw_ptr(T *a) -> decltype(a) { return a; } template <class T, class Indexing> array_view_base<T, Indexing>::array_view_base(array_view_base::shape_type shape, T *ptr, device_type mem_location) : _shape(shape), _ptr(ptr), _mem_location(mem_location) {} template <class T, class Indexing> typename array_view_base<T, Indexing>::size_type array_view_base<T, Indexing>::size() const { return product(_shape); } template <class T, class Indexing> const typename array_view_base<T, Indexing>::shape_type & array_view_base<T, Indexing>::shape() const { return _shape; } template <class T, class Indexing> typename array_view_base<T, Indexing>::size_type array_view_base<T, Indexing>::shape(array_view_base::size_type i) const { return _shape(i); } template <class T, class Indexing> device_type memory_location(const array_view_base<T, Indexing> &view) { return view.memory_location(); } template <class T, int n_dims, template <int> class Indexing> array_view<T, n_dims, Indexing>::array_view(const shape_t<n_dims> &shape, T *ptr, device_type mem_location) : super(shape, ptr, mem_location) {} template <class T, int n_dims, template <int> class Indexing> template <class Array, class Shape> array_view<T, n_dims, Indexing>::array_view( array_base<T, Indexing<n_dims>, Array, Shape> &other) : array_view(zisa::shape(other), zisa::raw_ptr(other), zisa::memory_location(other)) {} template <class T, int n_dims, template <int> class Indexing> array_view<T, n_dims, Indexing>::array_view(std::vector<T> &v) : array_view(shape_t<1>{v.size()}, v.data(), device_type::cpu) {} template <class T, int n_dims, template <int> class Indexing> T *array_view<T, n_dims, Indexing>::raw() const { return this->_ptr; } template <class T, int n_dim
int n_dims, template <int> class Indexing> T const *array_view<T, n_dims, Indexing>::cbegin() const { return this->_ptr; } template <class T, int n_dims, template <int> class Indexing> T const *array_view<T, n_dims, Indexing>::cend() const { return this->_ptr + this->size(); } template <class T, int n_dims, template <int> class Indexing> void array_view<T, n_dims, Indexing>::copy_data( const array_view<T, n_dims, Indexing> &other) const { copy_data(array_const_view<T, n_dims, Indexing>(other)); } template <class T, int n_dims, template <int> class Indexing> void array_view<T, n_dims, Indexing>::copy_data( const array_const_view<T, n_dims, Indexing> &other) const { assert((*this).shape() == other.shape()); LOG_ERR_IF(this->memory_location() == device_type::cuda, "Implement this."); if (other.raw() != (*this).raw()) { std::copy(other.begin(), other.end(), (*this).begin()); } } } #endif
s, template <int> class Indexing> T &array_view<T, n_dims, Indexing>::operator[](array_view::size_type i) const { return this->_ptr[i]; } template <class T, int n_dims, template <int> class Indexing> template <class... Ints> T &array_view<T, n_dims, Indexing>::operator()(Ints... ints) const { auto l = Indexing<n_dims>::linear_index(this->shape(), integer_cast<size_type>(ints)...); return (*this)[l]; } template <class T, int n_dims, template <int> class Indexing> T *array_view<T, n_dims, Indexing>::begin() const { return this->_ptr; } template <class T, int n_dims, template <int> class Indexing> T *array_view<T, n_dims, Indexing>::end() const { return this->_ptr + this->size(); } template <class T,
random
[ { "content": "class array_const_view : public array_view_base<const T, Indexing<n_dims>> {\n\n\n\nprivate:\n\n using super = array_view_base<const T, Indexing<n_dims>>;\n\n using size_type = typename super::size_type;\n\n\n\npublic:\n\n ANY_DEVICE_INLINE\n\n array_const_view(const shape_t<n_dims> &shape,\n\...
C++
src/developer/debug/unwinder/dwarf_cfi.cc
lalrochhara/fuchsia
f56c62fa108cfd72b8034eeddb4e403f1f69fdbd
#include "src/developer/debug/unwinder/dwarf_cfi.h" #include <algorithm> #include <cinttypes> #include <cstdint> #include <map> #include <string> #include "src/developer/debug/unwinder/dwarf_cfi_parser.h" #include "third_party/crashpad/third_party/glibc/elf/elf.h" namespace unwinder { namespace { struct DwarfCie { uint64_t code_alignment_factor = 0; int64_t data_alignment_factor = 0; RegisterID return_address_register; bool fde_have_augmentation_data = false; uint8_t fde_address_encoding = 0xFF; uint64_t instructions_begin = 0; uint64_t instructions_end = 0; }; struct DwarfFde { uint64_t pc_begin = 0; uint64_t pc_end = 0; uint64_t instructions_begin = 0; uint64_t instructions_end = 0; }; [[nodiscard]] Error DecodeTableEntrySize(uint8_t table_enc, uint64_t& res) { if (table_enc == 0xFF) { return Error("no binary search table"); } if ((table_enc & 0xF0) != 0x30) { return Error("invalid table_enc"); } switch (table_enc & 0x0F) { case 0x02: case 0x0A: res = 4; return Success(); case 0x03: case 0x0B: res = 8; return Success(); case 0x04: case 0x0C: res = 16; return Success(); default: return Error("unsupported table_enc: %#x", table_enc); } } [[nodiscard]] Error DecodeLength(Memory* memory, uint64_t& ptr, uint64_t& length) { uint32_t short_length; if (auto err = memory->Read(ptr, short_length); err.has_err()) { return err; } if (short_length == 0) { return Error("not a valid CIE/FDE"); } if (short_length == 0xFFFFFFFF) { if (auto err = memory->Read(ptr, length); err.has_err()) { return err; } } else { length = short_length; } return Success(); } [[nodiscard]] Error DecodeCIE(Memory* memory, uint64_t cie_ptr, DwarfCie& cie) { uint64_t length; if (auto err = DecodeLength(memory, cie_ptr, length); err.has_err()) { return err; } cie.instructions_end = cie_ptr + length; uint32_t cie_id; if (auto err = memory->Read(cie_ptr, cie_id); err.has_err()) { return err; } if (cie_id) { return Error("not a valid CIE"); } uint8_t version; if (auto err = memory->Read(cie_ptr, version); err.has_err()) { return err; } if (version != 1) { return Error("unsupported CIE version: %d", version); } std::string augmentation_string; while (true) { char ch; if (auto err = memory->Read(cie_ptr, ch); err.has_err()) { return err; } if (ch) { augmentation_string.push_back(ch); } else { break; } } if (auto err = memory->ReadULEB128(cie_ptr, cie.code_alignment_factor); err.has_err()) { return err; } if (auto err = memory->ReadSLEB128(cie_ptr, cie.data_alignment_factor); err.has_err()) { return err; } if (auto err = memory->Read(cie_ptr, cie.return_address_register); err.has_err()) { return err; } if (augmentation_string.empty()) { cie.instructions_begin = cie_ptr; cie.fde_have_augmentation_data = false; } else { if (augmentation_string[0] != 'z') { return Error("invalid augmentation string: %s", augmentation_string.c_str()); } uint64_t augmentation_length; if (auto err = memory->ReadULEB128(cie_ptr, augmentation_length); err.has_err()) { return err; } cie.instructions_begin = cie_ptr + augmentation_length; cie.fde_have_augmentation_data = true; for (char ch : augmentation_string) { switch (ch) { case 'L': uint8_t lsda_encoding; if (auto err = memory->Read(cie_ptr, lsda_encoding); err.has_err()) { return err; } break; case 'P': uint8_t enc; if (auto err = memory->Read(cie_ptr, enc); err.has_err()) { return err; } uint64_t personality; if (auto err = memory->ReadEncoded(cie_ptr, personality, enc, 0); err.has_err()) { return err; } break; case 'R': if (auto err = memory->Read(cie_ptr, cie.fde_address_encoding); err.has_err()) { return err; } break; } } } return Success(); } [[nodiscard]] Error DecodeFDE(Memory* memory, uint64_t fde_ptr, DwarfFde& fde, DwarfCie& cie) { uint64_t length; if (auto err = DecodeLength(memory, fde_ptr, length); err.has_err()) { return err; } fde.instructions_end = fde_ptr + length; uint32_t cie_offset; if (auto err = memory->Read(fde_ptr, cie_offset); err.has_err()) { return err; } if (auto err = DecodeCIE(memory, fde_ptr - 4 - cie_offset, cie); err.has_err()) { return err; } if (auto err = memory->ReadEncoded(fde_ptr, fde.pc_begin, cie.fde_address_encoding); err.has_err()) { return err; } if (auto err = memory->ReadEncoded(fde_ptr, fde.pc_end, cie.fde_address_encoding & 0x0F); err.has_err()) { return err; } fde.pc_end += fde.pc_begin; if (cie.fde_have_augmentation_data) { uint64_t augmentation_length; if (auto err = memory->ReadULEB128(fde_ptr, augmentation_length); err.has_err()) { return err; } fde_ptr += augmentation_length; } fde.instructions_begin = fde_ptr; return Success(); } } Error DwarfCfi::Load(Memory* elf, uint64_t elf_ptr) { Elf64_Ehdr ehdr; if (auto err = elf->Read(+elf_ptr, ehdr); err.has_err()) { return err; } if (strncmp(reinterpret_cast<const char*>(ehdr.e_ident), ELFMAG, SELFMAG) != 0) { return Error("not an ELF image"); } eh_frame_hdr_ptr_ = 0; pc_begin_ = -1; pc_end_ = 0; for (uint64_t i = 0; i < ehdr.e_phnum; i++) { Elf64_Phdr phdr; if (auto err = elf->Read(elf_ptr + ehdr.e_phoff + ehdr.e_phentsize * i, phdr); err.has_err()) { return err; } if (phdr.p_type == PT_GNU_EH_FRAME) { eh_frame_hdr_ptr_ = elf_ptr + phdr.p_vaddr; } else if (phdr.p_type == PT_LOAD && phdr.p_flags & PF_X) { pc_begin_ = std::min(pc_begin_, elf_ptr + phdr.p_vaddr); pc_end_ = std::max(pc_end_, elf_ptr + phdr.p_vaddr + phdr.p_memsz); } } if (!eh_frame_hdr_ptr_) { return Error("no PT_GNU_EH_FRAME segment"); } auto p = eh_frame_hdr_ptr_; uint8_t version; if (auto err = elf->Read(p, version); err.has_err()) { return err; } if (version != 1) { return Error("unknown eh_frame_hdr version %d", version); } uint8_t eh_frame_ptr_enc; uint8_t fde_count_enc; uint64_t eh_frame_ptr; if (auto err = elf->Read<uint8_t>(p, eh_frame_ptr_enc); err.has_err()) { return err; } if (auto err = elf->Read<uint8_t>(p, fde_count_enc); err.has_err()) { return err; } if (auto err = elf->Read<uint8_t>(p, table_enc_); err.has_err()) { return err; } if (auto err = DecodeTableEntrySize(table_enc_, table_entry_size_); err.has_err()) { return err; } if (auto err = elf->ReadEncoded(p, eh_frame_ptr, eh_frame_ptr_enc, eh_frame_hdr_ptr_); err.has_err()) { return err; } if (auto err = elf->ReadEncoded(p, fde_count_, fde_count_enc, eh_frame_hdr_ptr_); err.has_err()) { return err; } table_ptr_ = p; if (fde_count_ == 0) { return Error("empty binary search table"); } elf_ = elf; return Success(); } Error DwarfCfi::Step(Memory* stack, const Registers& current, Registers& next) { uint64_t pc; if (auto err = current.GetPC(pc); err.has_err()) { return err; } if (pc < pc_begin_ || pc >= pc_end_) { return Error("pc %#" PRIx64 " is outside of the executable area", pc); } uint64_t low = 0; uint64_t high = fde_count_; while (low + 1 < high) { uint64_t mid = (low + high) / 2; uint64_t addr = table_ptr_ + mid * table_entry_size_; uint64_t mid_pc; if (auto err = elf_->ReadEncoded(addr, mid_pc, table_enc_, eh_frame_hdr_ptr_); err.has_err()) { return err; } if (pc < mid_pc) { high = mid; } else { low = mid; } } uint64_t addr = table_ptr_ + low * table_entry_size_ + table_entry_size_ / 2; uint64_t fde_ptr; if (auto err = elf_->ReadEncoded(addr, fde_ptr, table_enc_, eh_frame_hdr_ptr_); err.has_err()) { return err; } DwarfCie cie; DwarfFde fde; if (auto err = DecodeFDE(elf_, fde_ptr, fde, cie); err.has_err()) { return err; } if (pc < fde.pc_begin || pc >= fde.pc_end) { return Error("cannot find FDE for pc %#" PRIx64, pc); } DwarfCfiParser cfi_parser(current.arch()); if (auto err = cfi_parser.ParseInstructions(elf_, cie.code_alignment_factor, cie.data_alignment_factor, cie.instructions_begin, cie.instructions_end, -1); err.has_err()) { return err; } cfi_parser.Snapshot(); if (auto err = cfi_parser.ParseInstructions(elf_, cie.code_alignment_factor, cie.data_alignment_factor, fde.instructions_begin, fde.instructions_end, pc - fde.pc_begin); err.has_err()) { return err; } if (auto err = cfi_parser.Step(stack, cie.return_address_register, current, next); err.has_err()) { return err; } return Success(); } }
#include "src/developer/debug/unwinder/dwarf_cfi.h" #include <algorithm> #include <cinttypes> #include <cstdint> #include <map> #include <string> #include "src/developer/debug/unwinder/dwarf_cfi_parser.h" #include "third_party/crashpad/third_party/glibc/elf/elf.h" namespace unwinder { namespace { struct DwarfCie { uint64_t code_alignment_factor = 0; int64_t data_alignment_factor = 0; RegisterID return_address_register; bool fde_have_augmentation_data = false; uint8_t fde_address_encoding = 0xFF; uint64_t instructions_begin = 0; uint64_t instructions_end = 0; }; struct DwarfFde { uint64_t pc_begin = 0; uint64_t pc_end = 0; uint64_t instructions_begin = 0; uint64_t instructions_end = 0; }; [[nodiscard]] Error DecodeTableEntrySize(uint8_t table_enc, uint64_t& res) { if (table_enc == 0xFF) { return Error("no binary search table"); } if ((table_enc & 0xF0) != 0x30) { return Error("invalid table_enc"); } switch (table_enc & 0x0F) { case 0x02: case 0x0A: res = 4; return Success(); case 0x03: case 0x0B: res = 8; return Success(); case 0x04: case 0x0C: res = 16; return Success(); default: return Error("unsupported table_enc: %#x", table_enc); } } [[nodiscard]] Error DecodeLength(Memory* memory, uint64_t& ptr, uint64_t& length) { uint32_t short_length; if (auto err = memory->Read(ptr, short_length); err.has_err()) { return err; } if (short_length == 0) { return Error("not a valid CIE/FDE"); } if (short_length == 0xFFFFFFFF) { if (auto err = memory->Read(ptr, length); err.has_err()) { return err; } } else { length = short_length; } return Success(); } [[nodiscard]] Error DecodeCIE(Memory* memory, uint64_t cie_ptr, DwarfCie& cie) { uint64_t length; if (auto err = DecodeLength(memory, cie_ptr, length); err.has_err()) { return err; } cie.instructions_end = cie_ptr + length; uint32_t cie_id; if (auto err = memory->Read(cie_ptr, cie_id); err.has_err()) { return err; } if (cie_id) { return Error("not a valid CIE"); } uint8_t version; if (auto err = memory->Read(cie_ptr, version); err.has_err()) { return err; } if (version != 1) { return Error("unsupported CIE version: %d", version); } std::string augmentation_string; while (true) { char ch; if (auto err = memory->Read(cie_ptr, ch); err.has_err()) { return err; } if (ch) { augmentation_string.push_back(ch); } else { break; } } if (auto err = memory->ReadULEB128(cie_ptr, cie.code_alignment_factor); err.has_err()) { return err; } if (auto err = memory->ReadSLEB128(cie_ptr, cie.data_alignment_factor); err.has_err()) { return err; } if (auto err = memory->Read(cie_ptr, cie.return_address_register); err.has_err()) { return err; } if (augmentation_string.empty()) { cie.instructions_begin = cie_ptr; cie.fde_have_augmentation_data = false; } else { if (augmentation_string[0] != 'z') { return Error("invalid augmentation string: %s", augmentation_string.c_str()); } uint64_t augmentation_length; if (auto err = memory->ReadULEB128(cie_ptr, augmentation_length); err.has_err()) { return err; } cie.instructions_begin = cie_ptr + augmentation_length; cie.fde_have_augmentation_data = true; for (char ch : augmentation_string) { switch (ch) { case 'L': uint8_t lsda_encoding; if (auto err = memory->Read(cie_ptr, lsda_encoding); err.has_err()) { return err; } break; case 'P': uint8_t enc; if (auto err = memory->Read(cie_ptr, enc); err.has_err()) { return err; } uint64_t personality; if (auto err = memory->ReadEncoded(cie_ptr, personality, enc, 0); err.has_err()) { return err; } break; case 'R': if (auto err = memory->Read(cie_ptr, cie.fde_address_encoding); err.has_err()) { return err; } break; } } } return Success(); } [[nodiscard]] Error DecodeFDE(Memory* memory, uint64_t fde_ptr, DwarfFde& fde, DwarfCie& cie) { uint64_t length; if (auto err = DecodeLength(memory, fde_ptr, length); err.has_err()) { return err; } fde.instructions_end = fde_ptr + length; uint32_t cie_offset; if (auto err = memory->Read(fde_ptr, cie_offset); err.has_err()) { return err; } if (auto err = DecodeCIE(memory, fde_ptr - 4 - cie_offset, cie); err.has_err()) { return err; } if (auto err = memory->ReadEncoded(fde_ptr, fde.pc_begin, cie.fde_address_encoding); err.has_err()) { return err; } if (auto err = memory->ReadEncoded(fde_ptr, fde.pc_end, cie.fde_address_encoding & 0x0F); err.has_err()) { return err; } fde.pc_end += fde.pc_begin; if (cie.fde_have_augmentation_data) { uint64_t augmentation_length; if (auto err = memory->ReadULEB128(fde_ptr, augmentation_length); err.has_err()) { return err; } fde_ptr += augmentation_length; } fde.instructions_begin = fde_ptr; return Success(); } } Error DwarfCfi::Load(Memory* elf, uint64_t elf_ptr) { Elf64_Ehdr ehdr; if (auto err = elf->Read(+elf_ptr, ehdr); err.has_err()) { return err; } if (strncmp(reinterpret_cast<const char*>(ehdr.e_ident), ELFMAG, SELFMAG) != 0) { return Error("not an ELF image"); } eh_frame_hdr_ptr_ = 0; pc_begin_ = -1; pc_end_ = 0; for (uint64_t i = 0; i < ehdr.e_phnum; i++) { Elf64_Phdr phdr; if (auto err = elf->Read(elf_ptr + ehdr.e_phoff + ehdr.e_phentsize * i, phdr); err.has_err()) { return err; } if (phdr.p_type == PT_GNU_EH_FRAME) { eh_frame_hdr_ptr_ = elf_ptr + phdr.p_vaddr; } else if (phdr.p_type == PT_LOAD && phdr.p_flags & PF_X) { pc_begin_ = std::min(pc_begin_, elf_ptr + phdr.p_vaddr); pc_end_ = std::max(pc_end_, elf_ptr + phdr.p_vaddr + phdr.p_memsz); } } if (!eh_frame_hdr_ptr_) { return Error("no PT_GNU_EH_FRAME segment"); } auto p = eh_frame_hdr_ptr_; uint8_t version; if (auto err = elf->Read(p, version); err.has_err()) { return err; } if (version != 1) { return Error("unknown eh_frame_hdr version %d", version); } uint8_t eh_frame_ptr_enc; uint8_t fde_count_enc; uint64_t eh_frame_ptr; if (auto err = elf->Read<uint8_t>(p, eh_frame_ptr_enc); err.has_err()) { return err; } if (auto err = elf->Read<uint8_t>(p, fde_count_enc); err.has_err()) { return err; } if (auto err = elf->Read<uint8_t>(p, table_enc_); err.has_err()) { return err; } if (auto err = DecodeTableEntrySize(table_enc_, table_entry_size_); err.has_err()) { return err; } if (auto err = elf->ReadEncoded(p, eh_frame_ptr, eh_frame_ptr_enc, eh_frame_hdr_ptr_); err.has_err()) { return err; } if (auto err = elf->ReadEncoded(p, fde_count_, fde_count_enc, eh_frame_hdr_ptr_); err.has_err()) { return err; } table_ptr_ = p; if (fde_count_ == 0) { return Error("empty binary search table"); } elf_ = elf; return Success(); } Error DwarfCfi::Step(Memory* stack, const Registers& current, Registers& next) { uint64_t pc; if (auto err = current.GetPC(pc); err.has_err()) { return err; } if (pc < pc_begin_ || pc >= pc_end_) { return Error("pc %#" PRIx64 " is outside of the executable area", pc); } uint64_t low = 0; uint64_t high = fde_count_; while (low + 1 < high) { uint64_t mid = (low + high) / 2; uint64_t addr = table_ptr_ + mid * table_entry_size_; uint64_t mid_pc; if (auto err = elf_->ReadEncoded(addr, mid_pc, table_enc_, eh_frame_hdr_ptr_); err.has_err()) { return err; } if (pc < mid_pc) { high = mid; } else { low = mid; } } uint64_t addr = table_ptr_ + low * table_entry_size_ + table_entry_size_ / 2; uint64_t fde_ptr; if (auto err = elf_->ReadEncoded(addr, fde_ptr, table_enc_, eh_frame_hdr_ptr_); err.has_err()) { return err; } DwarfCie cie; DwarfFde fde; if (auto err = DecodeFDE(elf_, fde_ptr, fde, cie); err.has_err()) { return err; } if (pc < fde.pc_begin || pc >= fde.pc_end) { return Error("cannot find FDE for pc %#" PRIx64, pc); } DwarfCfiParser cfi_parser(current.arch());
cfi_parser.Snapshot(); if (auto err = cfi_parser.ParseInstructions(elf_, cie.code_alignment_factor, cie.data_alignment_factor, fde.instructions_begin, fde.instructions_end, pc - fde.pc_begin); err.has_err()) { return err; } if (auto err = cfi_parser.Step(stack, cie.return_address_register, current, next); err.has_err()) { return err; } return Success(); } }
if (auto err = cfi_parser.ParseInstructions(elf_, cie.code_alignment_factor, cie.data_alignment_factor, cie.instructions_begin, cie.instructions_end, -1); err.has_err()) { return err; }
if_condition
[]
C++
Code/trunk/cpp/Geometry/CartesianMesh/CartesianMesh_base.hh
jlconlin/PhDThesis
8e704613721a800ce1c59576e94f40fa6f7cd986
#ifndef CARTESIANMESH_BASE_HH #define CARTESIANMESH_BASE_HH #include <boost/ptr_container/ptr_vector.hpp> #include "Types.hh" #include "Dimension.hh" #include "GeomId.hh" #include "MeshTraits.hh" #include "Assert.hh" #include "GeometricElementConcept.hh" using boost::ptr_vector; template<typename dimension_type, typename geom_elem> inline typename CartesianMesh<dimension_type>::SizeType numCentering(const CartesianMesh<dimension_type>& mesh); template<typename dimension_type> class CartesianMesh_base : public MeshTraits<dimension_type>, boost::noncopyable { private: BOOST_CLASS_REQUIRE(dimension_type, , DimensionConcept); public: typedef dimension_type DimensionType; typedef MeshTraits<DimensionType> Base; public: typename Base::LengthType length() const { return mLength; } typename Base::SizeType numZones() const { return mZones.size() + numGhostZones(); } typename Base::SizeType numNodes() const { return mNodes.size() + numGhostNodes(); } typename Base::SizeType numCorners() const { return mCorners.size() + numGhostCorners(); } typename Base::SizeType numGhostZones() const { if(mGhostZones == 0) return 0; else return mGhostZones->size(); } typename Base::SizeType numGhostNodes() const { if(mGhostNodes == 0) return 0; else return mGhostNodes->size(); } typename Base::SizeType numGhostCorners() const { if(mGhostCorners == 0) return 0; else return mGhostCorners->size(); } typename Base::ZoneIterator zoneBegin() { return typename Base::ZoneIterator( mZones, mZones.begin() ); } typename Base::ZoneIterator zoneEnd() { return typename Base::ZoneIterator( mZones, mZones.end() ); } typename Base::const_ZoneIterator zoneBegin() const { return typename Base::const_ZoneIterator( mZones, mZones.begin() ); } typename Base::const_ZoneIterator zoneEnd() const { return typename Base::const_ZoneIterator(mZones, mZones.end()); } typename Base::NodeIterator nodeBegin() { return typename Base::NodeIterator( mNodes, mNodes.begin() ); } typename Base::NodeIterator nodeEnd() { return typename Base::NodeIterator( mNodes, mNodes.end() ); } typename Base::const_NodeIterator nodeBegin() const { return typename Base::const_NodeIterator( mNodes, mNodes.begin() ); } typename Base::const_NodeIterator nodeEnd() const { return typename Base::const_NodeIterator( mNodes, mNodes.end() ); } typename Base::CornerIterator cornerBegin() { return typename Base::CornerIterator( mCorners, mCorners.begin() ); } typename Base::CornerIterator cornerEnd() { return typename Base::CornerIterator( mCorners, mCorners.end() ); } typename Base::const_CornerIterator cornerBegin() const { return typename Base::const_CornerIterator( mCorners, mCorners.begin() ); } typename Base::const_CornerIterator cornerEnd() const { return typename Base::const_CornerIterator( mCorners, mCorners.end() ); } typename Base::reverse_ZoneIterator zoneRBegin() { return typename Base::reverse_ZoneIterator( zoneEnd() ); } typename Base::reverse_ZoneIterator zoneREnd() { return typename Base::reverse_ZoneIterator( zoneBegin() ); } typename Base::const_reverse_ZoneIterator zoneRBegin() const { return typename Base::const_reverse_ZoneIterator( zoneEnd() ); } typename Base::const_reverse_ZoneIterator zoneREnd() const { return typename Base::const_reverse_ZoneIterator( zoneBegin() ); } typename Base::reverse_NodeIterator nodeRBegin() { return typename Base::reverse_NodeIterator( nodeEnd() ); } typename Base::reverse_NodeIterator nodeREnd() { return typename Base::reverse_NodeIterator( nodeBegin() ); } typename Base::const_reverse_NodeIterator nodeRBegin() const { return typename Base::const_reverse_NodeIterator( nodeEnd() ); } typename Base::const_reverse_NodeIterator nodeREnd() const { return typename Base::const_reverse_NodeIterator( nodeBegin() ); } typename Base::reverse_CornerIterator cornerRBegin() { return typename Base::reverse_CornerIterator( cornerEnd() ); } typename Base::reverse_CornerIterator cornerREnd() { return typename Base::reverse_CornerIterator( cornerBegin() ); } typename Base::const_reverse_CornerIterator cornerRBegin() const { return typename Base::const_reverse_CornerIterator( cornerEnd() ); } typename Base::const_reverse_CornerIterator cornerREnd() const { return typename Base::const_reverse_CornerIterator( cornerBegin() ); } protected: CartesianMesh_base(typename Base::LengthType length_in, typename Base::SizeType num_zones, typename Base::SizeType num_nodes, typename Base::SizeType num_corners, typename Base::SizeType num_ghost_zones, typename Base::SizeType num_ghost_nodes, typename Base::SizeType num_ghost_corners) : mLength(length_in), mZones(num_zones), mNodes(num_nodes), mCorners(num_corners), mGhostZones(0), mGhostNodes(0), mGhostCorners(0) { if(num_ghost_zones != 0) { mGhostZones = new ptr_vector<typename Base::GhostZone>(num_ghost_zones); } if(num_ghost_nodes != 0) { mGhostNodes = new ptr_vector<typename Base::GhostNode>(num_ghost_nodes); } if(num_ghost_corners != 0) { mGhostCorners = new ptr_vector<typename Base::GhostCorner>(num_ghost_corners); } } ~CartesianMesh_base() { if(mGhostZones != 0) { delete mGhostZones; } if(mGhostNodes != 0) { delete mGhostNodes; } if(mGhostCorners != 0) { delete mGhostCorners; } } typename Base::LengthType mLength; ptr_vector<typename Base::Zone> mZones; ptr_vector<typename Base::Node> mNodes; ptr_vector<typename Base::Corner> mCorners; ptr_vector<typename Base::GhostZone>* mGhostZones; ptr_vector<typename Base::GhostNode>* mGhostNodes; ptr_vector<typename Base::GhostCorner>* mGhostCorners; private: CartesianMesh_base(); }; template<typename dimension_type> class CartesianMesh : CartesianMesh_base<dimension_type>, boost::noncopyable { private: CartesianMesh(); }; #endif
#ifndef CARTESIANMESH_BASE_HH #define CARTESIANMESH_BASE_HH #include <boost/ptr_container/ptr_vector.hpp> #include "Types.hh" #include "Dimension.hh" #include "GeomId.hh" #include "MeshTraits.hh" #include "Assert.hh" #include "GeometricElementConcept.hh" using boost::ptr_vector; template<typename dimension_type, typename geom_elem> inline typename CartesianMesh<dimension_type>::SizeType numCentering(const CartesianMesh<dimension_type>& mesh); template<typename dimension_type> class CartesianMesh_base : public MeshTraits<dimension_type>, boost::noncopyable { private: BOOST_CLASS_REQUIRE(dimension_type, , DimensionConcept); public: typedef dimension_type DimensionType; typedef MeshTraits<DimensionType> Base; public: typename Base::LengthType length() const { return mLength; } typename Base::SizeType numZones() const { return mZones.size() + numGhostZones(); } typename Base::SizeType numNodes() const { return mNodes.size() + numGhostNodes(); } typename Base::SizeType numCorners() const { return mCorners.size() + numGhostCorners(); } typename Base::SizeType numGhostZones() const { if(mGhostZones == 0) return 0; else return mGhostZones->size(); } typename Base::SizeType numGhostNodes() const { if(mGhostNodes == 0) return 0; else return mGhostNodes->size(); } typename Base::SizeType numGhostCorners() const { if(mGhostCorners == 0)
typename Base::const_NodeIterator nodeEnd() const { return typename Base::const_NodeIterator( mNodes, mNodes.end() ); } typename Base::CornerIterator cornerBegin() { return typename Base::CornerIterator( mCorners, mCorners.begin() ); } typename Base::CornerIterator cornerEnd() { return typename Base::CornerIterator( mCorners, mCorners.end() ); } typename Base::const_CornerIterator cornerBegin() const { return typename Base::const_CornerIterator( mCorners, mCorners.begin() ); } typename Base::const_CornerIterator cornerEnd() const { return typename Base::const_CornerIterator( mCorners, mCorners.end() ); } typename Base::reverse_ZoneIterator zoneRBegin() { return typename Base::reverse_ZoneIterator( zoneEnd() ); } typename Base::reverse_ZoneIterator zoneREnd() { return typename Base::reverse_ZoneIterator( zoneBegin() ); } typename Base::const_reverse_ZoneIterator zoneRBegin() const { return typename Base::const_reverse_ZoneIterator( zoneEnd() ); } typename Base::const_reverse_ZoneIterator zoneREnd() const { return typename Base::const_reverse_ZoneIterator( zoneBegin() ); } typename Base::reverse_NodeIterator nodeRBegin() { return typename Base::reverse_NodeIterator( nodeEnd() ); } typename Base::reverse_NodeIterator nodeREnd() { return typename Base::reverse_NodeIterator( nodeBegin() ); } typename Base::const_reverse_NodeIterator nodeRBegin() const { return typename Base::const_reverse_NodeIterator( nodeEnd() ); } typename Base::const_reverse_NodeIterator nodeREnd() const { return typename Base::const_reverse_NodeIterator( nodeBegin() ); } typename Base::reverse_CornerIterator cornerRBegin() { return typename Base::reverse_CornerIterator( cornerEnd() ); } typename Base::reverse_CornerIterator cornerREnd() { return typename Base::reverse_CornerIterator( cornerBegin() ); } typename Base::const_reverse_CornerIterator cornerRBegin() const { return typename Base::const_reverse_CornerIterator( cornerEnd() ); } typename Base::const_reverse_CornerIterator cornerREnd() const { return typename Base::const_reverse_CornerIterator( cornerBegin() ); } protected: CartesianMesh_base(typename Base::LengthType length_in, typename Base::SizeType num_zones, typename Base::SizeType num_nodes, typename Base::SizeType num_corners, typename Base::SizeType num_ghost_zones, typename Base::SizeType num_ghost_nodes, typename Base::SizeType num_ghost_corners) : mLength(length_in), mZones(num_zones), mNodes(num_nodes), mCorners(num_corners), mGhostZones(0), mGhostNodes(0), mGhostCorners(0) { if(num_ghost_zones != 0) { mGhostZones = new ptr_vector<typename Base::GhostZone>(num_ghost_zones); } if(num_ghost_nodes != 0) { mGhostNodes = new ptr_vector<typename Base::GhostNode>(num_ghost_nodes); } if(num_ghost_corners != 0) { mGhostCorners = new ptr_vector<typename Base::GhostCorner>(num_ghost_corners); } } ~CartesianMesh_base() { if(mGhostZones != 0) { delete mGhostZones; } if(mGhostNodes != 0) { delete mGhostNodes; } if(mGhostCorners != 0) { delete mGhostCorners; } } typename Base::LengthType mLength; ptr_vector<typename Base::Zone> mZones; ptr_vector<typename Base::Node> mNodes; ptr_vector<typename Base::Corner> mCorners; ptr_vector<typename Base::GhostZone>* mGhostZones; ptr_vector<typename Base::GhostNode>* mGhostNodes; ptr_vector<typename Base::GhostCorner>* mGhostCorners; private: CartesianMesh_base(); }; template<typename dimension_type> class CartesianMesh : CartesianMesh_base<dimension_type>, boost::noncopyable { private: CartesianMesh(); }; #endif
return 0; else return mGhostCorners->size(); } typename Base::ZoneIterator zoneBegin() { return typename Base::ZoneIterator( mZones, mZones.begin() ); } typename Base::ZoneIterator zoneEnd() { return typename Base::ZoneIterator( mZones, mZones.end() ); } typename Base::const_ZoneIterator zoneBegin() const { return typename Base::const_ZoneIterator( mZones, mZones.begin() ); } typename Base::const_ZoneIterator zoneEnd() const { return typename Base::const_ZoneIterator(mZones, mZones.end()); } typename Base::NodeIterator nodeBegin() { return typename Base::NodeIterator( mNodes, mNodes.begin() ); } typename Base::NodeIterator nodeEnd() { return typename Base::NodeIterator( mNodes, mNodes.end() ); } typename Base::const_NodeIterator nodeBegin() const { return typename Base::const_NodeIterator( mNodes, mNodes.begin() ); }
random
[ { "content": "class MeshBaseException : public ExceptionBase\n\n{\n\npublic:\n\n /// Imports the \\c LineNumType from the \\c ExceptionBase base class.\n\n\ttypedef ExceptionBase::LineNumType LineNumType;\n\n\n\n\t/*! \\brief Constructor. Takes in the line number and filename where the exception \n\n\t * ...
C++
OpenSees/SRC/element/PFEMElement/TclModelBuilder_addPFEMElement.cpp
kuanshi/ductile-fracture
ccb350564df54f5c5ec3a079100effe261b46650
#include "TclModelBuilder_addPFEMElement.h" #include "PFEMElement2D.h" #include "PFEMElement2DFIC.h" #include "PFEMElement2DCompressible.h" #include "PFEMElement2DBubble.h" #include "PFEMElement2Dmini.h" #include "PFEMElement3D.h" #include <cstring> #include <string> int TclModelBuilder_addPFEMElement2D(ClientData clientData, Tcl_Interp *interp, int argc, TCL_Char **argv, Domain *theDomain, TclModelBuilder *theBuilder) { if(argc < 11) { opserr << "Invalid #args: want element PFEMElement2D tag"; opserr << "nd1 nd2 nd3 type rho mu b1 b2 <thickness kappa>\n"; return TCL_ERROR; } int loc = 2; int tag; if(Tcl_GetInt(interp, argv[loc], &tag) != TCL_OK) { opserr<< "WARNING invalid tag "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } loc++; int nd1; if(Tcl_GetInt(interp, argv[loc], &nd1) != TCL_OK) { opserr<< "WARNING invalid nd1 "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } loc++; int nd2; if(Tcl_GetInt(interp, argv[loc], &nd2) != TCL_OK) { opserr<< "WARNING invalid nd2 "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } loc++; int nd3; if(Tcl_GetInt(interp, argv[loc], &nd3) != TCL_OK) { opserr<< "WARNING invalid nd3 "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } loc++; int type = -1; if(strcmp(argv[loc], "FIC")==0 || strcmp(argv[loc], "fic")==0 || strcmp(argv[loc], "Fic")==0) { type = 0; } else if(strcmp(argv[loc], "quasi-incompressible")==0 || strcmp(argv[loc], "Quasi-Incompressible")==0) { type = 1; } else if(strcmp(argv[loc], "bubble")==0 || strcmp(argv[loc], "Bubble")==0) { type = 2; } else if(strcmp(argv[loc], "mini")==0 || strcmp(argv[loc], "Mini")==0) { type = 3; } else { opserr<<"WARNNG: unknown type for PFEMElement2D \n"; return TCL_ERROR; } loc++; double rho; if(Tcl_GetDouble(interp, argv[loc], &rho) != TCL_OK) { opserr<< "WARNING invalid rho "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } loc++; double mu; if(Tcl_GetDouble(interp, argv[loc], &mu) != TCL_OK) { opserr<< "WARNING invalid mu "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } loc++; double b1; if(Tcl_GetDouble(interp, argv[loc], &b1) != TCL_OK) { opserr<< "WARNING invalid b1 "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } loc++; double b2; if(Tcl_GetDouble(interp, argv[loc], &b2) != TCL_OK) { opserr<< "WARNING invalid b2 "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } loc++; double thickness = 1.0; if(argc > loc) { if(Tcl_GetDouble(interp, argv[loc], &thickness) != TCL_OK) { opserr<< "WARNING invalid thickness "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } } loc++; double kappa = 2.2e9; if(argc > loc) { if(Tcl_GetDouble(interp, argv[loc], &kappa) != TCL_OK) { opserr<< "WARNING invalid kappa "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } } loc++; int lumped = 0; if(argc > loc) { if(Tcl_GetInt(interp, argv[loc], &lumped) != TCL_OK) { opserr<< "WARNING invalid lumped "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } } loc++; int checkJ = 0; if(argc > loc) { if(Tcl_GetInt(interp, argv[loc], &checkJ) != TCL_OK) { opserr<< "WARNING invalid checkJ "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } } loc++; Element* ele = 0; if(type == 0) { ele = new PFEMElement2DFIC(tag,nd1,nd2,nd3,rho,mu,b1,b2,thickness); } else if(type == 1) { ele = new PFEMElement2DCompressible(tag,nd1,nd2,nd3,rho,mu,b1,b2,thickness,kappa); } else if(type == 2) { ele = new PFEMElement2DBubble(tag,nd1,nd2,nd3,rho,mu,b1,b2,thickness,kappa); } else if(type == 3) { ele = new PFEMElement2Dmini(tag,nd1,nd2,nd3,rho,mu,b1,b2,thickness,kappa,lumped,checkJ); } if (ele == 0) { opserr << "WARNING ran out of memory creating element\n"; opserr << "element: " << tag << endln; return TCL_ERROR; } if (theDomain->addElement(ele) == false) { opserr << "WARNING failed to add element to the domain\n"; opserr << "element: " << tag << endln; delete ele; return TCL_ERROR; } return TCL_OK; } int TclModelBuilder_addPFEMElement3D(ClientData clientData, Tcl_Interp *interp, int argc, TCL_Char **argv, Domain *theDomain, TclModelBuilder *theBuilder) { if(argc < 13) { opserr << "Invalid #args: want element PFEMElement3D "; opserr << "tag nd1 nd2 nd3 nd4 type rho mu b1 b2 b3 <kappa lumped checkJ>\n"; return TCL_ERROR; } int loc = 2; int tag; if(Tcl_GetInt(interp, argv[loc], &tag) != TCL_OK) { opserr<< "WARNING invalid tag "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; int nd1; if(Tcl_GetInt(interp, argv[loc], &nd1) != TCL_OK) { opserr<< "WARNING invalid nd1 "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; int nd2; if(Tcl_GetInt(interp, argv[loc], &nd2) != TCL_OK) { opserr<< "WARNING invalid nd2 "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; int nd3; if(Tcl_GetInt(interp, argv[loc], &nd3) != TCL_OK) { opserr<< "WARNING invalid nd3 "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; int nd4; if(Tcl_GetInt(interp, argv[loc], &nd4) != TCL_OK) { opserr<< "WARNING invalid nd4 "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; std::string type = argv[loc]; loc++; double rho; if(Tcl_GetDouble(interp, argv[loc], &rho) != TCL_OK) { opserr<< "WARNING invalid rho "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; double mu; if(Tcl_GetDouble(interp, argv[loc], &mu) != TCL_OK) { opserr<< "WARNING invalid mu "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; double b1; if(Tcl_GetDouble(interp, argv[loc], &b1) != TCL_OK) { opserr<< "WARNING invalid b1 "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; double b2; if(Tcl_GetDouble(interp, argv[loc], &b2) != TCL_OK) { opserr<< "WARNING invalid b2 "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; double b3; if(Tcl_GetDouble(interp, argv[loc], &b3) != TCL_OK) { opserr<< "WARNING invalid b3 "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; double kappa = 2.2e9; if(argc > loc) { if(Tcl_GetDouble(interp, argv[loc], &kappa) != TCL_OK) { opserr<<"WARNING invalid kappa "<<argv[loc]<<": element PFEMElement3D\n"; return TCL_ERROR; } loc++; } int lumped = 0; if(argc > loc) { if(Tcl_GetInt(interp, argv[loc], &lumped) != TCL_OK) { opserr<<"WARNING invalid lumped "<<argv[loc]<<": element PFEMElement3D\n"; return TCL_ERROR; } loc++; } int check = 0; if(argc > loc) { if(Tcl_GetInt(interp, argv[loc], &check) != TCL_OK) { opserr<<"WARNING invalid check "<<argv[loc]<<": element PFEMElement3D\n"; return TCL_ERROR; } loc++; } Element* ele = 0; if(type == "pressuregradient" || type == "PressureGradient") { ele = new PFEMElement3D(tag,nd1,nd2,nd3,nd4,rho,mu,b1,b2,b3); } else { opserr<<"element PFEMElement3D type "<<type.c_str()<<" is not known\n"; return TCL_ERROR; } if (ele == 0) { opserr << "WARNING ran out of memory creating element\n"; opserr << "element: " << tag << endln; return TCL_ERROR; } if (theDomain->addElement(ele) == false) { opserr << "WARNING failed to add element to the domain\n"; opserr << "element: " << tag << endln; delete ele; return TCL_ERROR; } return TCL_OK; }
#include "TclModelBuilder_addPFEMElement.h" #include "PFEMElement2D.h" #include "PFEMElement2DFIC.h" #include "PFEMElement2DCompressible.h" #include "PFEMElement2DBubble.h" #include "PFEMElement2Dmini.h" #include "PFEMElement3D.h" #include <cstring> #include <string>
int TclModelBuilder_addPFEMElement3D(ClientData clientData, Tcl_Interp *interp, int argc, TCL_Char **argv, Domain *theDomain, TclModelBuilder *theBuilder) { if(argc < 13) { opserr << "Invalid #args: want element PFEMElement3D "; opserr << "tag nd1 nd2 nd3 nd4 type rho mu b1 b2 b3 <kappa lumped checkJ>\n"; return TCL_ERROR; } int loc = 2; int tag; if(Tcl_GetInt(interp, argv[loc], &tag) != TCL_OK) { opserr<< "WARNING invalid tag "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; int nd1; if(Tcl_GetInt(interp, argv[loc], &nd1) != TCL_OK) { opserr<< "WARNING invalid nd1 "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; int nd2; if(Tcl_GetInt(interp, argv[loc], &nd2) != TCL_OK) { opserr<< "WARNING invalid nd2 "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; int nd3; if(Tcl_GetInt(interp, argv[loc], &nd3) != TCL_OK) { opserr<< "WARNING invalid nd3 "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; int nd4; if(Tcl_GetInt(interp, argv[loc], &nd4) != TCL_OK) { opserr<< "WARNING invalid nd4 "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; std::string type = argv[loc]; loc++; double rho; if(Tcl_GetDouble(interp, argv[loc], &rho) != TCL_OK) { opserr<< "WARNING invalid rho "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; double mu; if(Tcl_GetDouble(interp, argv[loc], &mu) != TCL_OK) { opserr<< "WARNING invalid mu "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; double b1; if(Tcl_GetDouble(interp, argv[loc], &b1) != TCL_OK) { opserr<< "WARNING invalid b1 "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; double b2; if(Tcl_GetDouble(interp, argv[loc], &b2) != TCL_OK) { opserr<< "WARNING invalid b2 "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; double b3; if(Tcl_GetDouble(interp, argv[loc], &b3) != TCL_OK) { opserr<< "WARNING invalid b3 "<< argv[loc] << ": element PFEMElement3D\n"; return TCL_ERROR; } loc++; double kappa = 2.2e9; if(argc > loc) { if(Tcl_GetDouble(interp, argv[loc], &kappa) != TCL_OK) { opserr<<"WARNING invalid kappa "<<argv[loc]<<": element PFEMElement3D\n"; return TCL_ERROR; } loc++; } int lumped = 0; if(argc > loc) { if(Tcl_GetInt(interp, argv[loc], &lumped) != TCL_OK) { opserr<<"WARNING invalid lumped "<<argv[loc]<<": element PFEMElement3D\n"; return TCL_ERROR; } loc++; } int check = 0; if(argc > loc) { if(Tcl_GetInt(interp, argv[loc], &check) != TCL_OK) { opserr<<"WARNING invalid check "<<argv[loc]<<": element PFEMElement3D\n"; return TCL_ERROR; } loc++; } Element* ele = 0; if(type == "pressuregradient" || type == "PressureGradient") { ele = new PFEMElement3D(tag,nd1,nd2,nd3,nd4,rho,mu,b1,b2,b3); } else { opserr<<"element PFEMElement3D type "<<type.c_str()<<" is not known\n"; return TCL_ERROR; } if (ele == 0) { opserr << "WARNING ran out of memory creating element\n"; opserr << "element: " << tag << endln; return TCL_ERROR; } if (theDomain->addElement(ele) == false) { opserr << "WARNING failed to add element to the domain\n"; opserr << "element: " << tag << endln; delete ele; return TCL_ERROR; } return TCL_OK; }
int TclModelBuilder_addPFEMElement2D(ClientData clientData, Tcl_Interp *interp, int argc, TCL_Char **argv, Domain *theDomain, TclModelBuilder *theBuilder) { if(argc < 11) { opserr << "Invalid #args: want element PFEMElement2D tag"; opserr << "nd1 nd2 nd3 type rho mu b1 b2 <thickness kappa>\n"; return TCL_ERROR; } int loc = 2; int tag; if(Tcl_GetInt(interp, argv[loc], &tag) != TCL_OK) { opserr<< "WARNING invalid tag "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } loc++; int nd1; if(Tcl_GetInt(interp, argv[loc], &nd1) != TCL_OK) { opserr<< "WARNING invalid nd1 "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } loc++; int nd2; if(Tcl_GetInt(interp, argv[loc], &nd2) != TCL_OK) { opserr<< "WARNING invalid nd2 "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } loc++; int nd3; if(Tcl_GetInt(interp, argv[loc], &nd3) != TCL_OK) { opserr<< "WARNING invalid nd3 "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } loc++; int type = -1; if(strcmp(argv[loc], "FIC")==0 || strcmp(argv[loc], "fic")==0 || strcmp(argv[loc], "Fic")==0) { type = 0; } else if(strcmp(argv[loc], "quasi-incompressible")==0 || strcmp(argv[loc], "Quasi-Incompressible")==0) { type = 1; } else if(strcmp(argv[loc], "bubble")==0 || strcmp(argv[loc], "Bubble")==0) { type = 2; } else if(strcmp(argv[loc], "mini")==0 || strcmp(argv[loc], "Mini")==0) { type = 3; } else { opserr<<"WARNNG: unknown type for PFEMElement2D \n"; return TCL_ERROR; } loc++; double rho; if(Tcl_GetDouble(interp, argv[loc], &rho) != TCL_OK) { opserr<< "WARNING invalid rho "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } loc++; double mu; if(Tcl_GetDouble(interp, argv[loc], &mu) != TCL_OK) { opserr<< "WARNING invalid mu "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } loc++; double b1; if(Tcl_GetDouble(interp, argv[loc], &b1) != TCL_OK) { opserr<< "WARNING invalid b1 "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } loc++; double b2; if(Tcl_GetDouble(interp, argv[loc], &b2) != TCL_OK) { opserr<< "WARNING invalid b2 "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } loc++; double thickness = 1.0; if(argc > loc) { if(Tcl_GetDouble(interp, argv[loc], &thickness) != TCL_OK) { opserr<< "WARNING invalid thickness "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } } loc++; double kappa = 2.2e9; if(argc > loc) { if(Tcl_GetDouble(interp, argv[loc], &kappa) != TCL_OK) { opserr<< "WARNING invalid kappa "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } } loc++; int lumped = 0; if(argc > loc) { if(Tcl_GetInt(interp, argv[loc], &lumped) != TCL_OK) { opserr<< "WARNING invalid lumped "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } } loc++; int checkJ = 0; if(argc > loc) { if(Tcl_GetInt(interp, argv[loc], &checkJ) != TCL_OK) { opserr<< "WARNING invalid checkJ "<< argv[loc] << ": element PFEMElement2D\n"; return TCL_ERROR; } } loc++; Element* ele = 0; if(type == 0) { ele = new PFEMElement2DFIC(tag,nd1,nd2,nd3,rho,mu,b1,b2,thickness); } else if(type == 1) { ele = new PFEMElement2DCompressible(tag,nd1,nd2,nd3,rho,mu,b1,b2,thickness,kappa); } else if(type == 2) { ele = new PFEMElement2DBubble(tag,nd1,nd2,nd3,rho,mu,b1,b2,thickness,kappa); } else if(type == 3) { ele = new PFEMElement2Dmini(tag,nd1,nd2,nd3,rho,mu,b1,b2,thickness,kappa,lumped,checkJ); } if (ele == 0) { opserr << "WARNING ran out of memory creating element\n"; opserr << "element: " << tag << endln; return TCL_ERROR; } if (theDomain->addElement(ele) == false) { opserr << "WARNING failed to add element to the domain\n"; opserr << "element: " << tag << endln; delete ele; return TCL_ERROR; } return TCL_OK; }
function_block-full_function
[ { "content": " CONST char *string;\t\t/* Last string passed to Tcl_RegExpExec. */\n", "file_path": "OpenSees/SRC/tcl/include/tclRegexp.h", "rank": 0, "score": 183596.33256221714 }, { "content": " public TypedIOPort string;\n", "file_path": "OpenSees/SRC/java/kepler/opensees/StringT...
C++
OpenTES4/bsa.cpp
Cyril-Meyer/OpenTES4Oblivion
dc2791a5a7ea911d0960d79ce0b9445fcbe329ee
#include "bsa.h" BSA::BSA() {} void BSA::summary() { std::cout << "header" << std::endl; std::cout << this->header.fileId << std::endl; std::cout << this->header.version << std::endl; std::cout << this->header.offset << std::endl; std::cout << this->header.archiveFlags << std::endl; std::cout << this->header.folderCount << std::endl; std::cout << this->header.fileCount << std::endl; std::cout << this->header.totalFolderNameLength << std::endl; std::cout << this->header.totalFileNameLength << std::endl; std::cout << this->header.fileFlags << std::endl; std::cout << "folderRecords" << std::endl; for (std::size_t i = 0; i < this->header.folderCount; ++i) { std::cout << this->folderRecords[i].nameHash << std::endl; std::cout << this->folderRecords[i].count << std::endl; std::cout << this->folderRecords[i].offset << std::endl; } std::cout << "fileRecordBlocks" << std::endl; std::bitset<32> archiveFlags(this->header.archiveFlags); for (std::size_t i = 0; i < this->fileRecordBlocks.size(); ++i) { if (archiveFlags.test(0)) { std::cout << this->fileRecordBlocks[i].name.data << std::endl; } for (std::size_t j = 0; j < this->fileRecordBlocks[i].fileRecords.size(); ++j) { std::cout << " " << this->fileRecordBlocks[i].fileRecords[j].nameHash << std::endl; std::cout << " " << this->fileRecordBlocks[i].fileRecords[j].size << std::endl; std::cout << " " << this->fileRecordBlocks[i].fileRecords[j].offset << std::endl; } } std::cout << "fileNameBlock" << std::endl; if (archiveFlags.test(1)) { for (std::size_t i = 0; i < this->header.fileCount; i++) { std::cout << this->fileNameBlock.fileNames[i].data << std::endl; } } } std::istream& operator>>(std::istream& is, BSA& bsa) { auto read = [](std::istream& is, void* dataptr, uint64_t datasize) { is.read(reinterpret_cast<char*>(dataptr), datasize); }; read(is, &bsa.header.fileId, sizeof(bsa.header.fileId)); read(is, &bsa.header.version, sizeof(bsa.header.version)); read(is, &bsa.header.offset, sizeof(bsa.header.offset)); read(is, &bsa.header.archiveFlags, sizeof(bsa.header.archiveFlags)); read(is, &bsa.header.folderCount, sizeof(bsa.header.folderCount)); read(is, &bsa.header.fileCount, sizeof(bsa.header.fileCount)); read(is, &bsa.header.totalFolderNameLength, sizeof(bsa.header.totalFolderNameLength)); read(is, &bsa.header.totalFileNameLength, sizeof(bsa.header.totalFileNameLength)); read(is, &bsa.header.fileFlags, sizeof(bsa.header.fileFlags)); std::bitset<32> archiveFlags(bsa.header.archiveFlags); for (std::size_t i = 0; i < bsa.header.folderCount; ++i) { BSA::FolderRecord fr; read(is, &fr.nameHash, sizeof(fr.nameHash)); read(is, &fr.count, sizeof(fr.count)); read(is, &fr.offset, sizeof(fr.offset)); bsa.folderRecords.push_back(fr); } uint32_t frfc = 0; for (std::size_t i = 0; i < bsa.header.folderCount; ++i) { frfc += bsa.folderRecords[i].count; } if (frfc != bsa.header.fileCount) { std::cout << "ERROR : fileCount and folderRecord number of files " "doesn't match" << std::endl; return is; } for (uint32_t i = 0; i < bsa.header.folderCount; ++i) { BSA::FileRecordBlocks frb; BSA::BZString bzs; if (archiveFlags.test(0)) { read(is, &bzs.length, sizeof(bzs.length)); bzs.data = new char[bzs.length]; read(is, bzs.data, bzs.length); if (bzs.data[bzs.length - 1] != '\0') { std::cout << "ERROR : invalid bzstring" << std::endl; return is; } } else { bzs.length = 0; bzs.data = nullptr; } frb.name = bzs; for (uint32_t j = 0; j < bsa.folderRecords[i].count; ++j) { BSA::FileRecord fr; read(is, &fr.nameHash, sizeof(fr.nameHash)); read(is, &fr.size, sizeof(fr.size)); read(is, &fr.offset, sizeof(fr.offset)); frb.fileRecords.push_back(fr); } bsa.fileRecordBlocks.push_back(frb); } if (archiveFlags.test(1)) { std::string tmpstr; for (uint32_t i = 0; i < bsa.header.fileCount; i++) { getline(is, tmpstr, '\0'); BSA::ZString zs; zs.data = new char[tmpstr.length()]; for (std::size_t j = 0; j <= tmpstr.length(); j++) { zs.data[j] = tmpstr[j]; } bsa.fileNameBlock.fileNames.push_back(zs); } } if (archiveFlags.test(1)) { std::size_t frbfrs = 0; for (std::size_t i = 0; i < bsa.fileRecordBlocks.size(); ++i) frbfrs += bsa.fileRecordBlocks.at(i).fileRecords.size(); if (frbfrs != bsa.fileNameBlock.fileNames.size()) { std::cout << "ERROR : fileRecords and fileNameBlock number of " "files doesn't match" << std::endl; return is; } } if (archiveFlags.test(1)) { std::size_t c = 0; for (std::size_t i = 0; i < bsa.fileRecordBlocks.size(); ++i) { for (std::size_t j = 0; j < bsa.fileRecordBlocks.at(i).fileRecords.size(); ++j) { bsa.fileRecordBlocks.at(i).fileRecords.at(j).filename = &bsa.fileNameBlock.fileNames.at(c); c++; } } } return is; }
#include "bsa.h" BSA::BSA() {} void BSA::summary() { std::cout << "header" << std::endl; std::cout << this->header.fileId << std::endl; std::cout << this->header.version << std::endl; std::cout << this->header.offset << std::endl; std::cout << this->header.archiveFlags << std::endl; std::cout << this->header.folderCount << std::endl; std::cout << this->header.fileCount << std::endl; std::cout << this->header.totalFolderNameLength << std::endl; std::cout << this->header.totalFileNameLength << std::endl; std::cout << this->header.fileFlags << std::endl; std::cout << "folderRecords" << std::endl; for (std::size_t i = 0; i < this->header.folderCount; ++i) { std::cout << this->folderRecords[i].nameHash << std::endl; std::cout << this->folderRecords[i].count << std::endl; std::cout << this->folderRecords[i].offset << std::endl; } std::cout << "fileRecordBlocks" << std::endl; std::bitset<32> archiveFlags(this->header.archiveFlags); for (std::size_t i = 0; i < this->fileRecordBlocks.size(); ++i) { if (archiveFlags.test(0)) { std::cout << this->fileRecordBlocks[i].name.data << std::endl; } for (std::size_t j = 0; j < this->fileRecordBlocks[i].fileRecords.size(); ++j) { std::cout << " " << this->fileRecordBlocks[i].fileRecords[j].nameHash << std::endl; std::cout << " " << this->fileRecordBlocks[i].fileRecords[j].size << std::endl; std::cout << " " << this->fileRecordBlocks[i].fileRecords[j].offset << std::endl; } } std::cout << "fileNameBlock" << std::endl; if (archiveFlags.test(1)) { for (std::size_t i = 0; i < this->header.fileCount; i++) { std::cout << this->fileNameBlock.fileNames[i].data << std::endl; } } } std::istream& operator>>(std::istream& is, BSA& bsa) { auto read = [](std::istream& is, void* dataptr, uint64_t datasize) { is.read(reinterpret_cast<char*>(dataptr), datasize); }; read(is, &bsa.header.fileId, sizeof(bsa.header.fileId)); read(is, &bsa.header.version, sizeof(bsa.header.version)); read(is, &bsa.header.offset, sizeof(bsa.header.offset)); read(is, &bsa.header.archiveFlags, sizeof(bsa.header.archiveFlags)); read(is, &bsa.header.folderCount, sizeof(bsa.header.folderCount)); read(is, &bsa.header.fileCount, sizeof(bsa.header.fileCount)); read(is, &bsa.header.totalFolderNameLength, sizeof(bsa.header.totalFolderNameLength)); read(is, &bsa.header.totalFileNameLength, sizeof(bsa.header.totalFileNameLength)); read(is, &bsa.header.fileFlags, sizeof(bsa.header.fileFlags)); std::bitset<32> archiveFlags(bsa.header.archiveFlags); for (std::size_t i = 0; i < bsa.header.folderCount; ++i) { BSA::FolderRecord fr; read(is, &fr.nameHash, sizeof(fr.nameHash)); read(is, &fr.count, sizeof(fr.count)); read(is, &fr.offset, sizeof(fr.offset)); bsa.folderRecords.push_back(fr); } uint32_t frfc = 0; for (std::size_t i = 0; i < bsa.header.folderCount; ++i) { frfc += bsa.folderRecords[i].count; } if (frfc != bsa.header.fileCount) { std::cout << "ERROR : fileCount and folderRecord number of files " "doesn't match" << std::endl; return is; } for (uint32_t i = 0; i < bsa.header.folderCount; ++i) { BSA::FileRecordBlocks frb; BSA::BZString bzs;
frb.name = bzs; for (uint32_t j = 0; j < bsa.folderRecords[i].count; ++j) { BSA::FileRecord fr; read(is, &fr.nameHash, sizeof(fr.nameHash)); read(is, &fr.size, sizeof(fr.size)); read(is, &fr.offset, sizeof(fr.offset)); frb.fileRecords.push_back(fr); } bsa.fileRecordBlocks.push_back(frb); } if (archiveFlags.test(1)) { std::string tmpstr; for (uint32_t i = 0; i < bsa.header.fileCount; i++) { getline(is, tmpstr, '\0'); BSA::ZString zs; zs.data = new char[tmpstr.length()]; for (std::size_t j = 0; j <= tmpstr.length(); j++) { zs.data[j] = tmpstr[j]; } bsa.fileNameBlock.fileNames.push_back(zs); } } if (archiveFlags.test(1)) { std::size_t frbfrs = 0; for (std::size_t i = 0; i < bsa.fileRecordBlocks.size(); ++i) frbfrs += bsa.fileRecordBlocks.at(i).fileRecords.size(); if (frbfrs != bsa.fileNameBlock.fileNames.size()) { std::cout << "ERROR : fileRecords and fileNameBlock number of " "files doesn't match" << std::endl; return is; } } if (archiveFlags.test(1)) { std::size_t c = 0; for (std::size_t i = 0; i < bsa.fileRecordBlocks.size(); ++i) { for (std::size_t j = 0; j < bsa.fileRecordBlocks.at(i).fileRecords.size(); ++j) { bsa.fileRecordBlocks.at(i).fileRecords.at(j).filename = &bsa.fileNameBlock.fileNames.at(c); c++; } } } return is; }
if (archiveFlags.test(0)) { read(is, &bzs.length, sizeof(bzs.length)); bzs.data = new char[bzs.length]; read(is, bzs.data, bzs.length); if (bzs.data[bzs.length - 1] != '\0') { std::cout << "ERROR : invalid bzstring" << std::endl; return is; } } else { bzs.length = 0; bzs.data = nullptr; }
if_condition
[ { "content": " def read(self):\n\n # open file\n\n file = open(self.filename, 'rb')\n\n # read file header\n\n self.header = {\n\n \"fileId\": str(file.read(4)),\n\n \"version\": bytes_to_int(file.read(4)),\n\n \"offset\": bytes_to_int(file.read(4)...
C++
libuuidpp/libuuidpp.hpp
dagronf/UUID_Wrapper
6ad8e7390d200bb96ef3e6e815650c2d5a2f886c
#pragma once #include <uuid/uuid.h> #include <string> #include <array> #ifndef __APPLE__ #include <string.h> typedef char __uuid_string_t[37]; typedef __uuid_string_t uuid_string_t; #endif static_assert(16 == sizeof(uuid_t), "uuid_t is of unexpected size"); static_assert(37 == sizeof(uuid_string_t), "Unexpected uuid_string_t size"); #include <type_traits> template<typename E> struct enable_bitmask_operators{ static const bool enable=false; }; template<typename E> typename std::enable_if<enable_bitmask_operators<E>::enable,E>::type operator|(E lhs,E rhs){ typedef typename std::underlying_type<E>::type underlying; return static_cast<E>( static_cast<underlying>(lhs) | static_cast<underlying>(rhs)); } template<typename E> typename std::enable_if<enable_bitmask_operators<E>::enable,E>::type operator&(E lhs,E rhs){ typedef typename std::underlying_type<E>::type underlying; return static_cast<E>( static_cast<underlying>(lhs) & static_cast<underlying>(rhs)); } namespace libuuidpp { namespace exception { struct invalid_uuid: public std::runtime_error { invalid_uuid(const char* guid) : std::runtime_error(std::string("libuuidpp exception: invalid guid '") + guid + "'") {} }; }; class uuid { public: static const uuid nil; typedef std::array<unsigned char, sizeof(uuid_t)> binary; inline static uuid random() { return uuid(libuuidpp::uuid::Random); } inline static bool is_valid(const char* uuidString) { uuid_t tmp; return internal_create(uuidString, tmp); } inline static bool is_valid(const std::string& uuidString) { return is_valid(uuidString.c_str()); } inline uuid() { internal_set(libuuidpp::uuid::Nil); } inline uuid(const uuid_t& rawValue) { ::uuid_copy(_rawuuid, rawValue); } inline uuid(const binary& data) { set(data); } inline uuid(const char* guidString) { if (!set(guidString)) { throw exception::invalid_uuid((guidString != NULL) ? guidString : "NULL"); } } inline uuid(const std::string& guidString) : uuid(guidString.c_str()) { } inline uuid(const uuid& right) { ::uuid_copy(_rawuuid, right._rawuuid); } inline bool set(const char* uuidString) { return internal_create(uuidString, _rawuuid); } inline bool set(const std::string& guidString) { return set(guidString.c_str()); } inline void set(const binary& data) { memcpy(_rawuuid, data.data(), data.size()); } inline void set_random() { ::uuid_generate_random(_rawuuid); } inline void set_nil() { ::uuid_clear(_rawuuid); } std::size_t hash() const; inline bool is_nil() const { return ::uuid_is_null(_rawuuid); } inline bool operator!=(const uuid& right) const { return ::uuid_compare(_rawuuid, right._rawuuid) != 0; } inline bool operator==(const uuid& right) const { return ::uuid_compare(_rawuuid, right._rawuuid) == 0; } inline bool operator<(const uuid& right) const { return ::uuid_compare(_rawuuid, right._rawuuid) < 0; } inline bool operator>(const uuid& right) const { return ::uuid_compare(_rawuuid, right._rawuuid) > 0; } enum class formatting { standard = 0, lowercase = 1 << 0, brackets = 1 << 1 }; std::string string(formatting format = formatting::standard) const; inline uuid::binary data() const { uuid::binary tmp; ::memcpy(tmp.data(), _rawuuid, sizeof(uuid_t)); return tmp; } private: typedef enum CreationState { Nil = 0, Random = 1 } CreationState; static const size_t STR_GUID_LEN = sizeof(uuid_string_t); static const size_t MS_GUID_LEN = STR_GUID_LEN + 1; inline static uuid internal_create(uuid::CreationState creation = uuid::Nil) { return uuid(creation); } inline static bool is_microsoft_formatted(const char* guid) { return ((::strnlen(guid, MS_GUID_LEN + 2) == MS_GUID_LEN) && guid[0] == '{' && guid[STR_GUID_LEN] == '}'); } static bool internal_microsoft_create(const char* uuidString, uuid_t& result); inline static bool internal_uuid_create(const char* uuidString, uuid_t& result) { return (::uuid_parse(uuidString, result) == 0); } static bool internal_create(const char* uuidString, uuid_t& result); inline void internal_set(CreationState creation = uuid::Nil) { (creation == uuid::Random) ? set_random() : set_nil(); } inline uuid(CreationState creation) { internal_set(creation); } ::uuid_t _rawuuid; }; }; namespace std { template<> struct hash<libuuidpp::uuid> { std::size_t operator()(libuuidpp::uuid const& s) const noexcept { return s.hash(); } }; } template<> struct enable_bitmask_operators<libuuidpp::uuid::formatting> { static const bool enable=true; }; namespace libuuidpp { const uuid uuid::nil = uuid::internal_create(libuuidpp::uuid::Nil); std::string uuid::string(libuuidpp::uuid::formatting format) const { std::string result; result.reserve(MS_GUID_LEN); uuid_string_t strVal; bool isBracketed = (format & formatting::brackets) == formatting::brackets; bool isLowercased = (format & formatting::lowercase) == formatting::lowercase; if (isBracketed) { result += "{"; } if (isLowercased) { ::uuid_unparse_lower(_rawuuid, strVal); } else { ::uuid_unparse_upper(_rawuuid, strVal); } result += std::string(strVal); if (isBracketed) { result += "}"; } return result; } std::size_t uuid::hash() const { #if INTPTR_MAX == INT64_MAX static const std::uint64_t FNV_offset_basis = 14695981039346656037UL; static const std::uint64_t FNV_prime = 1099511628211; #elif INTPTR_MAX == INT32_MAX static const std::uint32_t FNV_offset_basis = 2166136261; static const std::uint32_t FNV_prime = 16777619; #else #error Not a supported architecture (32bit or 64bit) #endif std::size_t result = FNV_offset_basis; for (std::size_t offset = 0; offset < sizeof(uuid_t); offset++) { result ^= _rawuuid[offset]; result *= FNV_prime; } return result; } bool uuid::internal_create(const char* uuidString, uuid_t& result) { if (uuidString != nullptr) { if (internal_microsoft_create(uuidString, result)) { return true; } else if (internal_uuid_create(uuidString, result)) { return true; } } ::uuid_clear(result); return false; } bool uuid::internal_microsoft_create(const char* uuidString, uuid_t& result) { if (is_microsoft_formatted(uuidString)) { char temp[STR_GUID_LEN]; ::memset(temp, 0, STR_GUID_LEN); ::memcpy(temp, uuidString+1, STR_GUID_LEN - 1); if (::uuid_parse(temp, result) != 0) { return false; } return true; } return false; } };
#pragma once #include <uuid/uuid.h> #include <string> #include <array> #ifndef __APPLE__ #include <string.h> typedef char __uuid_string_t[37]; typedef __uuid_string_t uuid_string_t; #endif static_assert(16 == sizeof(uuid_t), "uuid_t is of unexpected size"); static_assert(37 == sizeof(uuid_string_t), "Unexpected uuid_string_t size"); #include <type_traits> template<typename E> struct enable_bitmask_operators{ static const bool enable=false; }; template<typename E> typename std::enable_if<enable_bitmask_operators<E>::enable,E>::type operator|(E lhs,E rhs){ typedef typename std::underlying_type<E>::type underlying; return static_cast<E>( static_cast<underlying>(lhs) | static_cast<underlying>(rhs)); } template<typename E> typename std::enable_if<enable_bitmask_operators<E>::enable,E>::type operator&(E lhs,E rhs){ typedef typename std::underlying_type<E>::type underlying; return static_cast<E>( static_cast<underlying>(lhs) & static_cast<underlying>(rhs)); } namespace libuuidpp { namespace exception { struct invalid_uuid: public std::runtime_error { invalid_uuid(const char* guid) : std::runtime_error(std::string("libuuidpp exception: invalid guid '") + guid + "'") {} }; }; class uuid { public: static const uuid nil; typedef std::array<unsigned char, sizeof(uuid_t)> binary; inline static uuid random() { return uuid(libuuidpp::uuid::Random); } inline static bool is_valid(const char* uuidString) { uuid_t tmp; return internal_create(uuidString, tmp); } inline static bool is_valid(const std::string& uuidString) { return is_valid(uuidString.c_str()); } inline uuid() { internal_set(libuuidpp::uuid::Nil); } inline uuid(const uuid_t& rawValue) { ::uuid_copy(_rawuuid, rawValue); } inline uuid(const binary& data) { set(data); } inline uuid(const char* guidString) { if (!set(guidString)) { throw exception::invalid_uuid((guidString != NULL) ? guidString : "NULL"); } } inline uuid(const std::string& guidString) : uuid(guidString.c_str()) { } inline uuid(const uuid& right) { ::uuid_copy(_rawuuid, right._rawuuid); } inline bool set(const char* uuidString) { return internal_create(uuidString, _rawuuid); } inline bool set(const std::string& guidString) { return set(guidString.c_str()); } inline void set(const binary& data) { memcpy(_rawuuid, data.data(), data.size()); } inline void set_random() { ::uuid_generate_random(_rawuuid); } inline void set_nil() { ::uuid_clear(_rawuuid); } std::size_t hash() const; inline bool is_nil() const { return ::uuid_is_null(_rawuuid); } inline bool operator!=(const uuid& right) const { return ::uuid_compare(_rawuuid, right._rawuuid) != 0; } inline bool operator==(const uuid& right) const { return ::uuid_compare(_rawuuid, right._rawuuid) == 0; } inline bool operator<(const uuid& right) const { return ::uuid_compare(_rawuuid, right._rawuuid) < 0; } inline bool operator>(const uuid& right) const { return ::uuid_compare(_rawuuid, right._rawuuid) > 0; } enum class formatting { standard = 0, lowercase = 1 << 0, brackets = 1 << 1 }; std::string string(formatting format = formatting::standard) const; inline uuid::binary data() const { uuid::binary tmp; ::memcpy(tmp.data(), _rawuuid, sizeof(uuid_t)); return tmp; } private: typedef enum CreationState { Nil = 0, Random = 1 } CreationState; static const size_t STR_GUID_LEN = sizeof(uuid_string_t); static const size_t MS_GUID_LEN = STR_GUID_LEN + 1; inline static uuid internal_create(uuid::CreationState creation = uuid::Nil) { return uuid(creation); } inline static bool is_microsoft_formatted(const char* guid) { return ((::strnlen(guid, MS_GUID_LEN + 2) == MS_GUID_LEN) && guid[0] == '{' && guid[STR_GUID_LEN] == '}'); } static bool internal_microsoft_create(const char* uuidString, uuid_t& result); inline static bool internal_uuid_create(const char* uuidString, uuid_t& result) { return (::uuid_parse(uuidString, result) == 0); } static bool internal_create(const char* uuidString, uuid_t& result); inline void internal_set(CreationState creation = uuid::Nil) { (creation == uuid::Random) ? set_random() : set_nil(); } inline uuid(CreationState creation) { internal_set(creation); } ::uuid_t _rawuuid; }; }; namespace std { template<> struct hash<libuuidpp::uuid> { std::size_t operator()(libuuidpp::uuid const& s) const noexcept { return s.hash(); } }; } template<> struct enable_bitmask_operators<libuuidpp::uuid::formatting> { static const bool enable=true; }; namespace libuuidpp { const uuid uuid::nil = uuid::internal_create(libuuidpp::uuid::Nil); std::string uuid::string(libuuidpp::uuid::formatting format) const { std::string result; result.reserve(MS_GUID_LEN); uuid_string_t strVal; bool isBracketed = (format & formatting::brackets) == formatting::brackets; bool isLowercased = (format & formatting::lowercase) == formatting::lowercase; if (isBracketed) { result += "{"; } if (isLowercased) { ::uuid_unparse_lower(_rawuuid, strVal); } else { ::uuid_unparse_upper(_rawuuid, strVal); } result += std::string(strVal); if (isBracketed) { result += "}"; } return result; } std::size_t uuid::hash() const { #if INTPTR_MAX == INT64_MAX static const std::uint64_t FNV_offset_basis = 14695981039346656037UL; static const std::uint64_t FNV_prime = 1099511628211; #elif INTPTR_MAX == INT32_MAX static const std::uint32_t FNV_offset_basis = 2166136261; static const std::uint32_t FNV_prime = 16777619; #else #error Not a supported architecture (32bit or 64bit) #endif std::size_t result = FNV_offset_basis; for (std::size_t offset = 0; offset < sizeof(uuid_t); offset++) { result ^= _rawuuid[offset]; result *= FNV_prime; } return result; } bool uuid::internal_create(const char* uuidString, uuid_t& result) { if (uuidStrin
bool uuid::internal_microsoft_create(const char* uuidString, uuid_t& result) { if (is_microsoft_formatted(uuidString)) { char temp[STR_GUID_LEN]; ::memset(temp, 0, STR_GUID_LEN); ::memcpy(temp, uuidString+1, STR_GUID_LEN - 1); if (::uuid_parse(temp, result) != 0) { return false; } return true; } return false; } };
g != nullptr) { if (internal_microsoft_create(uuidString, result)) { return true; } else if (internal_uuid_create(uuidString, result)) { return true; } } ::uuid_clear(result); return false; }
function_block-function_prefixed
[ { "content": "# libuuidpp - A lightweight C++ UUID class.\n\n\n\nA lightweight C++ class wrapper around the `libuuid` library.\n\n\n\n## Features\n\n\n\n* Compatible with std containers such as `std::vector`, `std::set`, `std::map` etc.\n\n* Handles upper and lower case uuids.\n\n* Automatically handles Microso...
C++
Base/QTGUI/qSlicerExtensionsManagerDialog.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
#include <QPushButton> #include "qSlicerApplication.h" #include "qSlicerExtensionsManagerDialog.h" #include "qSlicerExtensionsManagerModel.h" #include "qSlicerSettingsExtensionsPanel.h" #include "ui_qSlicerExtensionsManagerDialog.h" class qSlicerExtensionsManagerDialogPrivate: public Ui_qSlicerExtensionsManagerDialog { Q_DECLARE_PUBLIC(qSlicerExtensionsManagerDialog); protected: qSlicerExtensionsManagerDialog* const q_ptr; public: qSlicerExtensionsManagerDialogPrivate(qSlicerExtensionsManagerDialog& object); void init(); bool RestartRequested; QStringList PreviousModulesAdditionalPaths; QStringList PreviousExtensionsScheduledForUninstall; QVariantMap PreviousExtensionsScheduledForUpdate; }; qSlicerExtensionsManagerDialogPrivate::qSlicerExtensionsManagerDialogPrivate(qSlicerExtensionsManagerDialog& object) :q_ptr(&object) { } void qSlicerExtensionsManagerDialogPrivate::init() { Q_Q(qSlicerExtensionsManagerDialog); this->setupUi(q); QPushButton * restartButton = this->ButtonBox->button(QDialogButtonBox::Ok); restartButton->setText("Restart"); q->setRestartRequested(false); QSettings * settings = qSlicerCoreApplication::application()->revisionUserSettings(); this->PreviousModulesAdditionalPaths = settings->value("Modules/AdditionalPaths").toStringList(); this->PreviousExtensionsScheduledForUninstall = settings->value("Extensions/ScheduledForUninstall").toStringList(); this->PreviousExtensionsScheduledForUpdate = settings->value("Extensions/ScheduledForUpdate").toMap(); qSlicerSettingsExtensionsPanel * extensionsPanel = qobject_cast<qSlicerSettingsExtensionsPanel*>( qSlicerApplication::application()->settingsDialog()->panel("Extensions")); Q_ASSERT(extensionsPanel); if (extensionsPanel) { QObject::connect(extensionsPanel, SIGNAL(extensionsServerUrlChanged(QString)), this->ExtensionsManagerWidget, SLOT(refreshInstallWidget())); } } qSlicerExtensionsManagerDialog::qSlicerExtensionsManagerDialog(QWidget *_parent) : Superclass(_parent) , d_ptr(new qSlicerExtensionsManagerDialogPrivate(*this)) { Q_D(qSlicerExtensionsManagerDialog); d->init(); } qSlicerExtensionsManagerDialog::~qSlicerExtensionsManagerDialog() { } qSlicerExtensionsManagerModel* qSlicerExtensionsManagerDialog::extensionsManagerModel()const { Q_D(const qSlicerExtensionsManagerDialog); return d->ExtensionsManagerWidget->extensionsManagerModel(); } void qSlicerExtensionsManagerDialog::setExtensionsManagerModel(qSlicerExtensionsManagerModel* model) { Q_D(qSlicerExtensionsManagerDialog); if (this->extensionsManagerModel() == model) { return; } disconnect(this, SLOT(onModelUpdated())); d->ExtensionsManagerWidget->setExtensionsManagerModel(model); if (model) { this->onModelUpdated(); connect(model, SIGNAL(modelUpdated()), this, SLOT(onModelUpdated())); connect(model, SIGNAL(extensionInstalled(QString)), this, SLOT(onModelUpdated())); connect(model, SIGNAL(extensionScheduledForUninstall(QString)), this, SLOT(onModelUpdated())); connect(model, SIGNAL(extensionCancelledScheduleForUninstall(QString)), this, SLOT(onModelUpdated())); connect(model, SIGNAL(extensionScheduledForUpdate(QString)), this, SLOT(onModelUpdated())); connect(model, SIGNAL(extensionCancelledScheduleForUpdate(QString)), this, SLOT(onModelUpdated())); connect(model, SIGNAL(extensionEnabledChanged(QString,bool)), this, SLOT(onModelUpdated())); } } bool qSlicerExtensionsManagerDialog::restartRequested()const { Q_D(const qSlicerExtensionsManagerDialog); return d->RestartRequested; } void qSlicerExtensionsManagerDialog::setRestartRequested(bool value) { Q_D(qSlicerExtensionsManagerDialog); d->RestartRequested = value; d->RestartRequestedLabel->setVisible(value); d->ButtonBox->button(QDialogButtonBox::Ok)->setEnabled(value); } void qSlicerExtensionsManagerDialog::onModelUpdated() { Q_D(qSlicerExtensionsManagerDialog); Q_ASSERT(this->extensionsManagerModel()); bool shouldRestart = false; qSlicerCoreApplication * coreApp = qSlicerCoreApplication::application(); if (d->PreviousModulesAdditionalPaths != coreApp->revisionUserSettings()->value("Modules/AdditionalPaths").toStringList() || d->PreviousExtensionsScheduledForUninstall != coreApp->revisionUserSettings()->value("Extensions/ScheduledForUninstall").toStringList() || d->PreviousExtensionsScheduledForUpdate != coreApp->revisionUserSettings()->value("Extensions/ScheduledForUpdate").toMap()) { shouldRestart = true; } this->setRestartRequested(shouldRestart); }
#include <QPushButton> #include "qSlicerApplication.h" #include "qSlicerExtensionsManagerDialog.h" #include "qSlicerExtensionsManagerModel.h" #include "qSlicerSettingsExtensionsPanel.h" #include "ui_qSlicerExtensionsManagerDialog.h" class qSlicerExtensionsManagerDialogPrivate: public Ui_qSlicerExtensionsManagerDialog { Q_DECLARE_PUBLIC(qSlicerExtensionsManagerDialog); protected: qSlicerExtensionsManagerDialog* const q_ptr; public: qSlicerExtensionsManagerDialogPrivate(qSlicerExtensionsManagerDialog& object); void init(); bool RestartRequested; QStringList PreviousModulesAdditionalPaths; QStringList PreviousExtensionsScheduledForUninstall; QVariantMap PreviousExtensionsScheduledForUpdate; }; qSlicerExtensionsManagerDialogPrivate::qSlicerExtensionsManagerDialogPrivate(qSlicerExtensionsManagerDialog& object) :q_ptr(&object) { } void qSlicerExtensionsManagerDialogPrivate::init() { Q_Q(qSlicerExtensionsManagerDialog); this->setupUi(q); QPushButton * restartButton = this->ButtonBox->button(QDialogButtonBox::Ok); restartButton->setText("Restart"); q->setRestartRequested(false); QSettings * settings = qSlicerCoreApplication::application(
lication * coreApp = qSlicerCoreApplication::application(); if (d->PreviousModulesAdditionalPaths != coreApp->revisionUserSettings()->value("Modules/AdditionalPaths").toStringList() || d->PreviousExtensionsScheduledForUninstall != coreApp->revisionUserSettings()->value("Extensions/ScheduledForUninstall").toStringList() || d->PreviousExtensionsScheduledForUpdate != coreApp->revisionUserSettings()->value("Extensions/ScheduledForUpdate").toMap()) { shouldRestart = true; } this->setRestartRequested(shouldRestart); }
)->revisionUserSettings(); this->PreviousModulesAdditionalPaths = settings->value("Modules/AdditionalPaths").toStringList(); this->PreviousExtensionsScheduledForUninstall = settings->value("Extensions/ScheduledForUninstall").toStringList(); this->PreviousExtensionsScheduledForUpdate = settings->value("Extensions/ScheduledForUpdate").toMap(); qSlicerSettingsExtensionsPanel * extensionsPanel = qobject_cast<qSlicerSettingsExtensionsPanel*>( qSlicerApplication::application()->settingsDialog()->panel("Extensions")); Q_ASSERT(extensionsPanel); if (extensionsPanel) { QObject::connect(extensionsPanel, SIGNAL(extensionsServerUrlChanged(QString)), this->ExtensionsManagerWidget, SLOT(refreshInstallWidget())); } } qSlicerExtensionsManagerDialog::qSlicerExtensionsManagerDialog(QWidget *_parent) : Superclass(_parent) , d_ptr(new qSlicerExtensionsManagerDialogPrivate(*this)) { Q_D(qSlicerExtensionsManagerDialog); d->init(); } qSlicerExtensionsManagerDialog::~qSlicerExtensionsManagerDialog() { } qSlicerExtensionsManagerModel* qSlicerExtensionsManagerDialog::extensionsManagerModel()const { Q_D(const qSlicerExtensionsManagerDialog); return d->ExtensionsManagerWidget->extensionsManagerModel(); } void qSlicerExtensionsManagerDialog::setExtensionsManagerModel(qSlicerExtensionsManagerModel* model) { Q_D(qSlicerExtensionsManagerDialog); if (this->extensionsManagerModel() == model) { return; } disconnect(this, SLOT(onModelUpdated())); d->ExtensionsManagerWidget->setExtensionsManagerModel(model); if (model) { this->onModelUpdated(); connect(model, SIGNAL(modelUpdated()), this, SLOT(onModelUpdated())); connect(model, SIGNAL(extensionInstalled(QString)), this, SLOT(onModelUpdated())); connect(model, SIGNAL(extensionScheduledForUninstall(QString)), this, SLOT(onModelUpdated())); connect(model, SIGNAL(extensionCancelledScheduleForUninstall(QString)), this, SLOT(onModelUpdated())); connect(model, SIGNAL(extensionScheduledForUpdate(QString)), this, SLOT(onModelUpdated())); connect(model, SIGNAL(extensionCancelledScheduleForUpdate(QString)), this, SLOT(onModelUpdated())); connect(model, SIGNAL(extensionEnabledChanged(QString,bool)), this, SLOT(onModelUpdated())); } } bool qSlicerExtensionsManagerDialog::restartRequested()const { Q_D(const qSlicerExtensionsManagerDialog); return d->RestartRequested; } void qSlicerExtensionsManagerDialog::setRestartRequested(bool value) { Q_D(qSlicerExtensionsManagerDialog); d->RestartRequested = value; d->RestartRequestedLabel->setVisible(value); d->ButtonBox->button(QDialogButtonBox::Ok)->setEnabled(value); } void qSlicerExtensionsManagerDialog::onModelUpdated() { Q_D(qSlicerExtensionsManagerDialog); Q_ASSERT(this->extensionsManagerModel()); bool shouldRestart = false; qSlicerCoreApp
random
[ { "content": "class DiffusionTensor3DTransform : public Object\n\n{\n\npublic:\n\n typedef TData DataType;\n\n typedef double TransformType;\n\n typedef DiffusionTensor3DTransform Self;\n\n typedef Point<TransformType, 3> PointT...
C++
main/sw/source/ui/docvw/SidebarTxtControlAcc.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
#include "precompiled_sw.hxx" #include <SidebarTxtControlAcc.hxx> #include <SidebarTxtControl.hxx> #include <svl/brdcst.hxx> #include <toolkit/awt/vclxaccessiblecomponent.hxx> #include <editeng/unoedsrc.hxx> #include <editeng/unoforou.hxx> #include <editeng/unoviwou.hxx> #include <editeng/unoedhlp.hxx> #include <svx/AccessibleTextHelper.hxx> #include <editeng/outliner.hxx> namespace css = ::com::sun::star; namespace sw { namespace sidebarwindows { class SidebarTextEditSource : public SvxEditSource, public SfxBroadcaster { public: SidebarTextEditSource( SidebarTxtControl& rSidebarTxtControl ); virtual ~SidebarTextEditSource(); virtual SvxEditSource* Clone() const; virtual SvxTextForwarder* GetTextForwarder(); virtual SvxViewForwarder* GetViewForwarder(); virtual SvxEditViewForwarder* GetEditViewForwarder( sal_Bool bCreate = sal_False ); virtual void UpdateData(); virtual SfxBroadcaster& GetBroadcaster() const; DECL_LINK( NotifyHdl, EENotify* ); private: SidebarTxtControl& mrSidebarTxtControl; SvxOutlinerForwarder mTextForwarder; SvxDrawOutlinerViewForwarder mViewForwarder; }; SidebarTextEditSource::SidebarTextEditSource( SidebarTxtControl& rSidebarTxtControl ) : SvxEditSource() , mrSidebarTxtControl( rSidebarTxtControl ) , mTextForwarder( *(rSidebarTxtControl.GetTextView()->GetOutliner()), sal_False ) , mViewForwarder( *(rSidebarTxtControl.GetTextView()) ) { if ( mrSidebarTxtControl.GetTextView() ) { mrSidebarTxtControl.GetTextView()->GetOutliner()->SetNotifyHdl( LINK(this, SidebarTextEditSource, NotifyHdl) ); } } SidebarTextEditSource::~SidebarTextEditSource() { if ( mrSidebarTxtControl.GetTextView() ) { mrSidebarTxtControl.GetTextView()->GetOutliner()->SetNotifyHdl( Link() ); } } SvxEditSource* SidebarTextEditSource::Clone() const { return new SidebarTextEditSource( mrSidebarTxtControl ); } SvxTextForwarder* SidebarTextEditSource::GetTextForwarder() { return &mTextForwarder; } SvxViewForwarder* SidebarTextEditSource::GetViewForwarder() { return &mViewForwarder; } SvxEditViewForwarder* SidebarTextEditSource::GetEditViewForwarder( sal_Bool ) { return &mViewForwarder; } void SidebarTextEditSource::UpdateData() { } SfxBroadcaster& SidebarTextEditSource::GetBroadcaster() const { return *( const_cast< SidebarTextEditSource* > (this) ); } IMPL_LINK(SidebarTextEditSource, NotifyHdl, EENotify*, pNotify) { if ( pNotify ) { ::std::auto_ptr< SfxHint > aHint( SvxEditSourceHelper::EENotification2Hint( pNotify ) ); if( aHint.get() ) { Broadcast( *aHint.get() ); } } return 0; } class SidebarTxtControlAccessibleContext : public VCLXAccessibleComponent { public: explicit SidebarTxtControlAccessibleContext( SidebarTxtControl& rSidebarTxtControl ); virtual ~SidebarTxtControlAccessibleContext(); virtual sal_Int32 SAL_CALL getAccessibleChildCount() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); using WeakAggComponentImplHelperBase::addEventListener; using WeakAggComponentImplHelperBase::removeEventListener; virtual void SAL_CALL addEventListener ( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleEventListener >& xListener) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener ( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleEventListener >& xListener) throw (::com::sun::star::uno::RuntimeException); protected: virtual void ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent ); private: SidebarTxtControl& mrSidebarTxtControl; ::accessibility::AccessibleTextHelper* mpAccessibleTextHelper; ::vos::OMutex maMutex; void defunc(); }; SidebarTxtControlAccessibleContext::SidebarTxtControlAccessibleContext( SidebarTxtControl& rSidebarTxtControl ) : VCLXAccessibleComponent( rSidebarTxtControl.GetWindowPeer() ) , mrSidebarTxtControl( rSidebarTxtControl ) , mpAccessibleTextHelper( 0 ) , maMutex() { ::std::auto_ptr<SvxEditSource> pEditSource( new SidebarTextEditSource( mrSidebarTxtControl ) ); mpAccessibleTextHelper = new ::accessibility::AccessibleTextHelper( pEditSource ); mpAccessibleTextHelper->SetEventSource( mrSidebarTxtControl.GetWindowPeer() ); } SidebarTxtControlAccessibleContext::~SidebarTxtControlAccessibleContext() { defunc(); } void SidebarTxtControlAccessibleContext::defunc() { delete mpAccessibleTextHelper; mpAccessibleTextHelper = 0; } sal_Int32 SAL_CALL SidebarTxtControlAccessibleContext::getAccessibleChildCount() throw (::com::sun::star::uno::RuntimeException) { vos::OGuard aGuard( maMutex ); sal_Int32 nChildCount( 0 ); if ( mpAccessibleTextHelper ) { nChildCount = mpAccessibleTextHelper->GetChildCount(); } return nChildCount; } css::uno::Reference< css::accessibility::XAccessible > SAL_CALL SidebarTxtControlAccessibleContext::getAccessibleChild( sal_Int32 i ) throw ( css::lang::IndexOutOfBoundsException, css::uno::RuntimeException ) { vos::OGuard aGuard( maMutex ); css::uno::Reference< css::accessibility::XAccessible > xChild; if ( mpAccessibleTextHelper ) { xChild = mpAccessibleTextHelper->GetChild( i ); } return xChild; } void SAL_CALL SidebarTxtControlAccessibleContext::addEventListener ( const css::uno::Reference< css::accessibility::XAccessibleEventListener >& xListener) throw (css::uno::RuntimeException) { vos::OGuard aGuard( maMutex ); if ( mpAccessibleTextHelper ) { mpAccessibleTextHelper->AddEventListener(xListener); } } void SAL_CALL SidebarTxtControlAccessibleContext::removeEventListener ( const css::uno::Reference< css::accessibility::XAccessibleEventListener >& xListener) throw (css::uno::RuntimeException) { vos::OGuard aGuard( maMutex ); if ( mpAccessibleTextHelper ) { mpAccessibleTextHelper->RemoveEventListener(xListener); } } void SidebarTxtControlAccessibleContext::ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent ) { if ( mpAccessibleTextHelper ) { switch ( rVclWindowEvent.GetId() ) { case VCLEVENT_OBJECT_DYING: { defunc(); } break; case VCLEVENT_WINDOW_GETFOCUS: case VCLEVENT_CONTROL_GETFOCUS: { mpAccessibleTextHelper->SetFocus( sal_True ); } break; case VCLEVENT_WINDOW_LOSEFOCUS: case VCLEVENT_CONTROL_LOSEFOCUS: { mpAccessibleTextHelper->SetFocus( sal_False ); } break; } } VCLXAccessibleComponent::ProcessWindowEvent( rVclWindowEvent ); } SidebarTxtControlAccessible::SidebarTxtControlAccessible( SidebarTxtControl& rSidebarTxtControl ) : VCLXWindow() , mrSidebarTxtControl( rSidebarTxtControl ) { SetWindow( &mrSidebarTxtControl ); } SidebarTxtControlAccessible::~SidebarTxtControlAccessible() { } css::uno::Reference< css::accessibility::XAccessibleContext > SidebarTxtControlAccessible::CreateAccessibleContext() { SidebarTxtControlAccessibleContext* pAccContext( new SidebarTxtControlAccessibleContext( mrSidebarTxtControl ) ); css::uno::Reference< css::accessibility::XAccessibleContext > xAcc( pAccContext ); return xAcc; } } }
#include "precompiled_sw.hxx" #include <SidebarTxtControlAcc.hxx> #include <SidebarTxtControl.hxx> #include <svl/brdcst.hxx> #include <toolkit/awt/vclxaccessiblecomponent.hxx> #include <editeng/unoedsrc.hxx> #include <editeng/unoforou.hxx> #include <editeng/unoviwou.hxx> #include <editeng/unoedhlp.hxx> #include <svx/AccessibleTextHelper.hxx> #include <editeng/outliner.hxx> namespace css = ::com::sun::star; namespace sw { namespace sidebarwindows { class SidebarTextEditSource : public SvxEditSource, public SfxBroadcaster { public: SidebarTextEditSource( SidebarTxtControl& rSidebarTxtControl ); virtual ~SidebarTextEditSource(); virtual SvxEditSource* Clone() const; virtual SvxTextForwarder* GetTextForwarder(); virtual SvxViewForwarder* GetViewForwarder(); virtual SvxEditViewForwarder* GetEditViewForwarder( sal_Bool bCreate = sal_False ); virtual void UpdateData(); virtual SfxBroadcaster& GetBroadcaster() const; DECL_LINK( NotifyHdl, EENotify* ); private: SidebarTxtControl& mrSidebarTxtControl; SvxOutlinerForwarder mTextForwarder; SvxDrawOutlinerViewForwarder mViewForwarder; }; SidebarTextEditSource::SidebarTextEditSource( SidebarTxtControl& rSidebarTxtControl ) : SvxEditSource() , mrSidebarTxtControl( rSidebarTxtControl ) , mTextForwarder( *(rSidebarTxtControl.GetTextView()->GetOutliner()), sal_False ) , mViewForwarder( *(rSidebarTxtControl.GetTextView()) ) {
} SidebarTextEditSource::~SidebarTextEditSource() { if ( mrSidebarTxtControl.GetTextView() ) { mrSidebarTxtControl.GetTextView()->GetOutliner()->SetNotifyHdl( Link() ); } } SvxEditSource* SidebarTextEditSource::Clone() const { return new SidebarTextEditSource( mrSidebarTxtControl ); } SvxTextForwarder* SidebarTextEditSource::GetTextForwarder() { return &mTextForwarder; } SvxViewForwarder* SidebarTextEditSource::GetViewForwarder() { return &mViewForwarder; } SvxEditViewForwarder* SidebarTextEditSource::GetEditViewForwarder( sal_Bool ) { return &mViewForwarder; } void SidebarTextEditSource::UpdateData() { } SfxBroadcaster& SidebarTextEditSource::GetBroadcaster() const { return *( const_cast< SidebarTextEditSource* > (this) ); } IMPL_LINK(SidebarTextEditSource, NotifyHdl, EENotify*, pNotify) { if ( pNotify ) { ::std::auto_ptr< SfxHint > aHint( SvxEditSourceHelper::EENotification2Hint( pNotify ) ); if( aHint.get() ) { Broadcast( *aHint.get() ); } } return 0; } class SidebarTxtControlAccessibleContext : public VCLXAccessibleComponent { public: explicit SidebarTxtControlAccessibleContext( SidebarTxtControl& rSidebarTxtControl ); virtual ~SidebarTxtControlAccessibleContext(); virtual sal_Int32 SAL_CALL getAccessibleChildCount() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); using WeakAggComponentImplHelperBase::addEventListener; using WeakAggComponentImplHelperBase::removeEventListener; virtual void SAL_CALL addEventListener ( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleEventListener >& xListener) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener ( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleEventListener >& xListener) throw (::com::sun::star::uno::RuntimeException); protected: virtual void ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent ); private: SidebarTxtControl& mrSidebarTxtControl; ::accessibility::AccessibleTextHelper* mpAccessibleTextHelper; ::vos::OMutex maMutex; void defunc(); }; SidebarTxtControlAccessibleContext::SidebarTxtControlAccessibleContext( SidebarTxtControl& rSidebarTxtControl ) : VCLXAccessibleComponent( rSidebarTxtControl.GetWindowPeer() ) , mrSidebarTxtControl( rSidebarTxtControl ) , mpAccessibleTextHelper( 0 ) , maMutex() { ::std::auto_ptr<SvxEditSource> pEditSource( new SidebarTextEditSource( mrSidebarTxtControl ) ); mpAccessibleTextHelper = new ::accessibility::AccessibleTextHelper( pEditSource ); mpAccessibleTextHelper->SetEventSource( mrSidebarTxtControl.GetWindowPeer() ); } SidebarTxtControlAccessibleContext::~SidebarTxtControlAccessibleContext() { defunc(); } void SidebarTxtControlAccessibleContext::defunc() { delete mpAccessibleTextHelper; mpAccessibleTextHelper = 0; } sal_Int32 SAL_CALL SidebarTxtControlAccessibleContext::getAccessibleChildCount() throw (::com::sun::star::uno::RuntimeException) { vos::OGuard aGuard( maMutex ); sal_Int32 nChildCount( 0 ); if ( mpAccessibleTextHelper ) { nChildCount = mpAccessibleTextHelper->GetChildCount(); } return nChildCount; } css::uno::Reference< css::accessibility::XAccessible > SAL_CALL SidebarTxtControlAccessibleContext::getAccessibleChild( sal_Int32 i ) throw ( css::lang::IndexOutOfBoundsException, css::uno::RuntimeException ) { vos::OGuard aGuard( maMutex ); css::uno::Reference< css::accessibility::XAccessible > xChild; if ( mpAccessibleTextHelper ) { xChild = mpAccessibleTextHelper->GetChild( i ); } return xChild; } void SAL_CALL SidebarTxtControlAccessibleContext::addEventListener ( const css::uno::Reference< css::accessibility::XAccessibleEventListener >& xListener) throw (css::uno::RuntimeException) { vos::OGuard aGuard( maMutex ); if ( mpAccessibleTextHelper ) { mpAccessibleTextHelper->AddEventListener(xListener); } } void SAL_CALL SidebarTxtControlAccessibleContext::removeEventListener ( const css::uno::Reference< css::accessibility::XAccessibleEventListener >& xListener) throw (css::uno::RuntimeException) { vos::OGuard aGuard( maMutex ); if ( mpAccessibleTextHelper ) { mpAccessibleTextHelper->RemoveEventListener(xListener); } } void SidebarTxtControlAccessibleContext::ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent ) { if ( mpAccessibleTextHelper ) { switch ( rVclWindowEvent.GetId() ) { case VCLEVENT_OBJECT_DYING: { defunc(); } break; case VCLEVENT_WINDOW_GETFOCUS: case VCLEVENT_CONTROL_GETFOCUS: { mpAccessibleTextHelper->SetFocus( sal_True ); } break; case VCLEVENT_WINDOW_LOSEFOCUS: case VCLEVENT_CONTROL_LOSEFOCUS: { mpAccessibleTextHelper->SetFocus( sal_False ); } break; } } VCLXAccessibleComponent::ProcessWindowEvent( rVclWindowEvent ); } SidebarTxtControlAccessible::SidebarTxtControlAccessible( SidebarTxtControl& rSidebarTxtControl ) : VCLXWindow() , mrSidebarTxtControl( rSidebarTxtControl ) { SetWindow( &mrSidebarTxtControl ); } SidebarTxtControlAccessible::~SidebarTxtControlAccessible() { } css::uno::Reference< css::accessibility::XAccessibleContext > SidebarTxtControlAccessible::CreateAccessibleContext() { SidebarTxtControlAccessibleContext* pAccContext( new SidebarTxtControlAccessibleContext( mrSidebarTxtControl ) ); css::uno::Reference< css::accessibility::XAccessibleContext > xAcc( pAccContext ); return xAcc; } } }
if ( mrSidebarTxtControl.GetTextView() ) { mrSidebarTxtControl.GetTextView()->GetOutliner()->SetNotifyHdl( LINK(this, SidebarTextEditSource, NotifyHdl) ); }
if_condition
[]
C++
Operations/albaOpExporterAnsysCommon.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
#include "albaDefines.h" #include "albaOpExporterAnsysCommon.h" #include "albaOpImporterAnsysCommon.h" #include "albaDecl.h" #include "albaGUI.h" #include "albaSmartPointer.h" #include "albaTagItem.h" #include "albaTagArray.h" #include "albaVME.h" #include "albaVMEMesh.h" #include "albaVMEMeshAnsysTextExporter.h" #include "albaAbsMatrixPipe.h" #include <iostream> #include <fstream> #include "vtkALBASmartPointer.h" #include "vtkUnstructuredGrid.h" #include "vtkCellArray.h" #include "vtkDoubleArray.h" #include "vtkIntArray.h" #include "vtkPointData.h" #include "vtkCellData.h" #include "vtkFieldData.h" #include "vtkTransform.h" #include "vtkTransformFilter.h" #include <vcl_string.h> #include <vcl_fstream.h> #include <vcl_sstream.h> #include <vcl_map.h> #include <vcl_vector.h> #include "wx/stdpaths.h" albaCxxAbstractTypeMacro(albaOpExporterAnsysCommon); albaOpExporterAnsysCommon::albaOpExporterAnsysCommon(const wxString &label) : albaOpExporterFEMCommon(label) { m_AnsysOutputFileNameFullPath = ""; } albaOpExporterAnsysCommon::~albaOpExporterAnsysCommon() { } void albaOpExporterAnsysCommon::OpRun() { Init(); CreateGui(); } void albaOpExporterAnsysCommon::OnOK() { albaString wildcard = GetWildcard(); m_AnsysOutputFileNameFullPath = ""; wxString f; f = albaGetSaveFile("",wildcard).c_str(); if(!f.IsEmpty()) { m_AnsysOutputFileNameFullPath = f; Write(); } } void albaOpExporterAnsysCommon::OpStop(int result) { HideGui(); albaEventMacro(albaEvent(this,result)); } void albaOpExporterAnsysCommon::Init() { albaVMEMesh *input = albaVMEMesh::SafeDownCast(m_Input); assert(input); vtkUnstructuredGrid *inputUGrid = input->GetUnstructuredGridOutput()->GetUnstructuredGridData(); if(inputUGrid != NULL) { m_TotalElements = inputUGrid->GetNumberOfPoints(); m_TotalElements += inputUGrid->GetNumberOfCells(); vtkDataArray *materialsIDArray = NULL; materialsIDArray = inputUGrid->GetCellData()->GetArray("EX"); if (materialsIDArray != NULL) { m_TotalElements += materialsIDArray->GetNumberOfTuples(); } } } int albaOpExporterAnsysCommon::compareElem(const void *p1, const void *p2) { ExportElement *a, *b; a = (ExportElement *)p1; b = (ExportElement *)p2; double result; result = a->elementType - b->elementType; if (result < 0) return -1; else if (result > 0) return 1; else { result = a->matID - b->matID; if (result < 0) return -1; else if (result > 0) return 1; else { result = a->elementID - b->elementID; if (result < 0) return -1; else if (result > 0) return 1; else assert(0); } } } ExportElement *albaOpExporterAnsysCommon::CreateExportElements(albaVMEMesh * input, int rowsNumber, vtkUnstructuredGrid * inputUGrid, FILE * file) { vtkIntArray *elementIdArray = input->GetElementsIDArray(); vtkIntArray *nodesIDArray = input->GetNodesIDArray(); vtkIntArray *typeArray = input->GetElementsTypeArray(); vtkIntArray *realArray = input->GetElementsRealArray(); ExportElement *exportVector = new ExportElement[rowsNumber]; int currType=-1; for (int rowID = 0 ; rowID < rowsNumber ; rowID++) { exportVector[rowID].elementID = elementIdArray ? elementIdArray->GetValue(rowID) : rowID+1; exportVector[rowID].matID = GetMatIdArray() ? GetMatIdArray()[rowID] : 1; exportVector[rowID].elementType = typeArray ? typeArray->GetValue(rowID) : 1; exportVector[rowID].elementReal = realArray ? realArray->GetValue(rowID) : 1; exportVector[rowID].cellID=rowID; } qsort(exportVector, rowsNumber, sizeof(ExportElement), compareElem); for (int rowID = 0 ; rowID < rowsNumber ; rowID++) { if(currType != exportVector[rowID].elementType) { int mode; vtkCell *currentCell = inputUGrid->GetCell(exportVector[rowID].cellID); vtkIdList *idList = currentCell->GetPointIds(); int cellNpoints=currentCell->GetNumberOfPoints(); switch (cellNpoints) { case 4: mode = 285; break; case 8: mode = 45; break; case 10: mode = 187; break; case 20: mode = 186; break; default: mode = -1; break; } currType = exportVector[rowID].elementType; fprintf(file,"ET,%d,%d\n", currType, mode); } } return exportVector; }
#include "albaDefines.h" #include "albaOpExporterAnsysCommon.h" #include "albaOpImporterAnsysCommon.h" #include "albaDecl.h" #include "albaGUI.h" #include "albaSmartPointer.h" #include "albaTagItem.h" #include "albaTagArray.h" #include "albaVME.h" #include "albaVMEMesh.h" #include "albaVMEMeshAnsysTextExporter.h" #include "albaAbsMatrixPipe.h" #include <iostream> #include <fstream> #include "vtkALBASmartPointer.h" #include "vtkUnstructuredGrid.h" #include "vtkCellArray.h" #include "vtkDoubleArray.h" #include "vtkIntArray.h" #include "vtkPointData.h" #include "vtkCellData.h" #include "vtkFieldData.h" #include "vtkTransform.h" #include "vtkTransformFilter.h" #include <vcl_string.h> #include <vcl_fstream.h> #include <vcl_sstream.h> #include <vcl_map.h> #include <vcl_vector.h> #include "wx/stdpaths.h" albaCxxAbstractTypeMacro(albaOpExporterAnsysCommon); albaOpExporterAnsysCommon::albaOpExporterAnsysCommon(const wxString &label) : albaOpExporterFEMCommon(label) { m_AnsysOutputFileNameFullPath = ""; } albaOpExporterAnsysCommon::~albaOpExporterAnsysCommon() { } void albaOpExporterAnsysCommon::OpRun() { Init(); CreateGui(); } void albaOpExporterAnsysCommon::OnOK() { albaString wildcard = GetWildcard(); m_AnsysOutputFileNameFullPath = ""; wxString f; f = albaGetSaveFile("",wildcard).c_str(); if(!f.IsEmpty()) { m_AnsysOutputFileNameFullPath = f; Write(); } } void albaOpExporterAnsysCommon::OpStop(int result) { HideGui(); albaEventMacro(albaEvent(this,result)); } void albaOpExporterAnsysCommon::Init() { albaVMEMesh *input = albaVMEMesh::SafeDownCast(m_Input); assert(input); vtkUnstructuredGrid *inputUGrid = input->GetUnstructuredGridOutput()->GetUnstructuredGridData(); if(inputUGrid != NULL) { m_TotalElements = inputUGrid->GetNumberOfPoints(); m_TotalElements += inputUGrid->GetNumberOfCells(); vtkDataArray *materialsIDArray = NULL; materialsIDArray = inputUGrid->GetCellData()->GetArray("EX"); if (materialsIDArray != NULL) { m_TotalElements += materialsIDArray->GetNumberOfTuples(); } } } int albaOpExporterAnsysCommon::compareElem(const void *p1, const void *p2) { ExportElement *a, *b; a = (ExportElement *)p1; b = (ExportElement *)p2; double result; result = a->elementType - b->elementType; if (result < 0) return -1; else if (result > 0) return 1; else { result = a->matID - b->matID;
} } ExportElement *albaOpExporterAnsysCommon::CreateExportElements(albaVMEMesh * input, int rowsNumber, vtkUnstructuredGrid * inputUGrid, FILE * file) { vtkIntArray *elementIdArray = input->GetElementsIDArray(); vtkIntArray *nodesIDArray = input->GetNodesIDArray(); vtkIntArray *typeArray = input->GetElementsTypeArray(); vtkIntArray *realArray = input->GetElementsRealArray(); ExportElement *exportVector = new ExportElement[rowsNumber]; int currType=-1; for (int rowID = 0 ; rowID < rowsNumber ; rowID++) { exportVector[rowID].elementID = elementIdArray ? elementIdArray->GetValue(rowID) : rowID+1; exportVector[rowID].matID = GetMatIdArray() ? GetMatIdArray()[rowID] : 1; exportVector[rowID].elementType = typeArray ? typeArray->GetValue(rowID) : 1; exportVector[rowID].elementReal = realArray ? realArray->GetValue(rowID) : 1; exportVector[rowID].cellID=rowID; } qsort(exportVector, rowsNumber, sizeof(ExportElement), compareElem); for (int rowID = 0 ; rowID < rowsNumber ; rowID++) { if(currType != exportVector[rowID].elementType) { int mode; vtkCell *currentCell = inputUGrid->GetCell(exportVector[rowID].cellID); vtkIdList *idList = currentCell->GetPointIds(); int cellNpoints=currentCell->GetNumberOfPoints(); switch (cellNpoints) { case 4: mode = 285; break; case 8: mode = 45; break; case 10: mode = 187; break; case 20: mode = 186; break; default: mode = -1; break; } currType = exportVector[rowID].elementType; fprintf(file,"ET,%d,%d\n", currType, mode); } } return exportVector; }
if (result < 0) return -1; else if (result > 0) return 1; else { result = a->elementID - b->elementID; if (result < 0) return -1; else if (result > 0) return 1; else assert(0); }
if_condition
[ { "content": " function is of type void *, and returns NULL.\n\n Otherwise the type is void which is correct for WIN32\n\n and SPROC\n\n*/ \n\n#ifdef CMAKE_USE_SPROC_INIT\n\ntypedef int mmuThreadProcessIDType;\n\n#endif\n\n\n\n\n\n#ifdef CMAKE_USE_PTHREADS_INIT\n\ntypedef void *(*mmuInternalThreadFunctionTy...
C++
src/test_suites/oclc/oclc_miscellaneous_vector_functions/src/vec_step.cpp
intel/cassian
8e9594f053f9b9464066c8002297346580e4aa2a
#include <algorithm> #include <cassian/catch2_utils/catch2_utils.hpp> #include <cassian/cli/cli.hpp> #include <cassian/runtime/openclc_type_tuples.hpp> #include <cassian/runtime/runtime.hpp> #include <cassian/test_harness/test_harness.hpp> #include <cassian/utility/metaprogramming.hpp> #include <cassian/utility/utility.hpp> #include <catch2/catch.hpp> #include <cstddef> #include <numeric> #include <string> #include <test_config.hpp> #include <vector> namespace ca = cassian; namespace { template <typename T> int get_reference() { using data_host_type = typename T::host_type; if constexpr (ca::is_vector_v<data_host_type>) { return data_host_type::size_in_memory; } return 1; } template <typename T> std::string get_build_options() { const std::string clc_data_type = T::device_type; std::string build_options = " -D DATA_TYPE=" + clc_data_type; return build_options; } ca::Kernel create_kernel(const std::string &path, const std::string &name, const std::string &build_options, cassian::Runtime *runtime, const std::string &program_type) { const std::string source = ca::load_text_file(ca::get_asset(path)); return runtime->create_kernel(name, source, build_options, program_type); } std::vector<int> generate_input(const size_t elements) { std::vector<int> input(elements); std::iota(input.begin(), input.end(), 0); return input; } template <typename T> std::vector<int> run_data_type_kernel(const cassian::Kernel &kernel, const size_t global_work_size, const std::vector<T> &input, cassian::Runtime *runtime) { std::vector<ca::Buffer> buffers; ca::Buffer input_buffer = runtime->create_buffer(sizeof(T) * input.size()); runtime->write_buffer_from_vector(input_buffer, input); buffers.push_back(input_buffer); ca::Buffer output_buffer = runtime->create_buffer(sizeof(int) * global_work_size); buffers.push_back(output_buffer); runtime->set_kernel_argument(kernel, 0, input_buffer); runtime->set_kernel_argument(kernel, 1, output_buffer); runtime->run_kernel(kernel, global_work_size); std::vector<int> output = runtime->read_buffer_to_vector<int>(output_buffer); for (auto &buffer : buffers) { runtime->release_buffer(buffer); } return output; } template <typename T> std::vector<int> run_pure_type_kernel(const cassian::Kernel &kernel, const size_t global_work_size, cassian::Runtime *runtime) { std::vector<ca::Buffer> buffers; ca::Buffer output_buffer = runtime->create_buffer(sizeof(int) * global_work_size); buffers.push_back(output_buffer); runtime->set_kernel_argument(kernel, 0, output_buffer); runtime->run_kernel(kernel, global_work_size); std::vector<int> output = runtime->read_buffer_to_vector<int>(output_buffer); for (auto &buffer : buffers) { runtime->release_buffer(buffer); } return output; } using GentypeTypes = ca::TupleConcat<ca::ScalarTypes, ca::VectorTypes>::type; template <typename T> std::string test_name() { return std::string(T::type_name); } TEMPLATE_LIST_TEST_CASE_CUSTOM_NAME("vec_step_data_type", "", GentypeTypes, test_name<TestType>) { const TestConfig &config = get_test_config(); ca::Requirements requirements; requirements.arithmetic_type<typename TestType::scalar_type>(); if (ca::should_skip_test(requirements, *config.runtime())) { return; } ca::Runtime *runtime = config.runtime(); const std::string program_type = config.program_type(); const size_t global_work_size = config.work_size(); using data_host_type = typename TestType::host_type; const std::vector<data_host_type> input(global_work_size, data_host_type(123)); const std::string build_options = get_build_options<TestType>(); ca::Kernel kernel = create_kernel("kernels/oclc_miscellaneous_vector_functions/vec_step.cl", "test_data_type", build_options, runtime, program_type); const std::vector<int> output = run_data_type_kernel(kernel, global_work_size, input, runtime); runtime->release_kernel(kernel); const std::vector<int> reference = std::vector<int>(global_work_size, get_reference<TestType>()); REQUIRE_THAT(output, Catch::Equals(reference)); } TEMPLATE_LIST_TEST_CASE_CUSTOM_NAME("vec_step_pure_type", "", GentypeTypes, test_name<TestType>) { const TestConfig &config = get_test_config(); ca::Requirements requirements; requirements.arithmetic_type<typename TestType::scalar_type>(); if (ca::should_skip_test(requirements, *config.runtime())) { return; } ca::Runtime *runtime = config.runtime(); const std::string program_type = config.program_type(); const size_t global_work_size = config.work_size(); const std::string build_options = get_build_options<TestType>(); ca::Kernel kernel = create_kernel("kernels/oclc_miscellaneous_vector_functions/vec_step.cl", "test_pure_type", build_options, runtime, program_type); using data_host_type = typename TestType::host_type; const std::vector<int> output = run_pure_type_kernel<data_host_type>(kernel, global_work_size, runtime); runtime->release_kernel(kernel); const std::vector<int> reference = std::vector<int>(global_work_size, get_reference<TestType>()); REQUIRE_THAT(output, Catch::Equals(reference)); } }
#include <algorithm> #include <cassian/catch2_utils/catch2_utils.hpp> #include <cassian/cli/cli.hpp> #include <cassian/runtime/openclc_type_tuples.hpp> #include <cassian/runtime/runtime.hpp> #include <cassian/test_harness/test_harness.hpp> #include <cassian/utility/metaprogramming.hpp> #include <cassian/utility/utility.hpp> #include <catch2/catch.hpp> #include <cstddef> #include <numeric> #include <string> #include <test_config.hpp> #include <vector> namespace ca = cassian; namespace { template <typename T>
template <typename T> std::string get_build_options() { const std::string clc_data_type = T::device_type; std::string build_options = " -D DATA_TYPE=" + clc_data_type; return build_options; } ca::Kernel create_kernel(const std::string &path, const std::string &name, const std::string &build_options, cassian::Runtime *runtime, const std::string &program_type) { const std::string source = ca::load_text_file(ca::get_asset(path)); return runtime->create_kernel(name, source, build_options, program_type); } std::vector<int> generate_input(const size_t elements) { std::vector<int> input(elements); std::iota(input.begin(), input.end(), 0); return input; } template <typename T> std::vector<int> run_data_type_kernel(const cassian::Kernel &kernel, const size_t global_work_size, const std::vector<T> &input, cassian::Runtime *runtime) { std::vector<ca::Buffer> buffers; ca::Buffer input_buffer = runtime->create_buffer(sizeof(T) * input.size()); runtime->write_buffer_from_vector(input_buffer, input); buffers.push_back(input_buffer); ca::Buffer output_buffer = runtime->create_buffer(sizeof(int) * global_work_size); buffers.push_back(output_buffer); runtime->set_kernel_argument(kernel, 0, input_buffer); runtime->set_kernel_argument(kernel, 1, output_buffer); runtime->run_kernel(kernel, global_work_size); std::vector<int> output = runtime->read_buffer_to_vector<int>(output_buffer); for (auto &buffer : buffers) { runtime->release_buffer(buffer); } return output; } template <typename T> std::vector<int> run_pure_type_kernel(const cassian::Kernel &kernel, const size_t global_work_size, cassian::Runtime *runtime) { std::vector<ca::Buffer> buffers; ca::Buffer output_buffer = runtime->create_buffer(sizeof(int) * global_work_size); buffers.push_back(output_buffer); runtime->set_kernel_argument(kernel, 0, output_buffer); runtime->run_kernel(kernel, global_work_size); std::vector<int> output = runtime->read_buffer_to_vector<int>(output_buffer); for (auto &buffer : buffers) { runtime->release_buffer(buffer); } return output; } using GentypeTypes = ca::TupleConcat<ca::ScalarTypes, ca::VectorTypes>::type; template <typename T> std::string test_name() { return std::string(T::type_name); } TEMPLATE_LIST_TEST_CASE_CUSTOM_NAME("vec_step_data_type", "", GentypeTypes, test_name<TestType>) { const TestConfig &config = get_test_config(); ca::Requirements requirements; requirements.arithmetic_type<typename TestType::scalar_type>(); if (ca::should_skip_test(requirements, *config.runtime())) { return; } ca::Runtime *runtime = config.runtime(); const std::string program_type = config.program_type(); const size_t global_work_size = config.work_size(); using data_host_type = typename TestType::host_type; const std::vector<data_host_type> input(global_work_size, data_host_type(123)); const std::string build_options = get_build_options<TestType>(); ca::Kernel kernel = create_kernel("kernels/oclc_miscellaneous_vector_functions/vec_step.cl", "test_data_type", build_options, runtime, program_type); const std::vector<int> output = run_data_type_kernel(kernel, global_work_size, input, runtime); runtime->release_kernel(kernel); const std::vector<int> reference = std::vector<int>(global_work_size, get_reference<TestType>()); REQUIRE_THAT(output, Catch::Equals(reference)); } TEMPLATE_LIST_TEST_CASE_CUSTOM_NAME("vec_step_pure_type", "", GentypeTypes, test_name<TestType>) { const TestConfig &config = get_test_config(); ca::Requirements requirements; requirements.arithmetic_type<typename TestType::scalar_type>(); if (ca::should_skip_test(requirements, *config.runtime())) { return; } ca::Runtime *runtime = config.runtime(); const std::string program_type = config.program_type(); const size_t global_work_size = config.work_size(); const std::string build_options = get_build_options<TestType>(); ca::Kernel kernel = create_kernel("kernels/oclc_miscellaneous_vector_functions/vec_step.cl", "test_pure_type", build_options, runtime, program_type); using data_host_type = typename TestType::host_type; const std::vector<int> output = run_pure_type_kernel<data_host_type>(kernel, global_work_size, runtime); runtime->release_kernel(kernel); const std::vector<int> reference = std::vector<int>(global_work_size, get_reference<TestType>()); REQUIRE_THAT(output, Catch::Equals(reference)); } }
int get_reference() { using data_host_type = typename T::host_type; if constexpr (ca::is_vector_v<data_host_type>) { return data_host_type::size_in_memory; } return 1; }
function_block-full_function
[ { "content": "/*\n\n * Copyright (C) 2021 Intel Corporation\n\n *\n\n * SPDX-License-Identifier: MIT\n\n *\n\n */\n\n\n\n#ifndef CASSIAN_VECTOR_VECTOR_HPP\n\n#define CASSIAN_VECTOR_VECTOR_HPP\n\n\n\n#include <algorithm>\n\n#include <array>\n\n#include <cstddef>\n\n#include <functional>\n\n#include <initializer_...
C++
Sankore-3.1/src/gui/UBDownloadWidget.cpp
eaglezzb/rsdc
cce881f6542ff206bf286cf798c8ec8da3b51d50
#include <QDebug> #include <QHeaderView> #include <QStyleOptionProgressBarV2> #include <QApplication> #include "UBDownloadWidget.h" #include "globals/UBGlobals.h" #include "core/UBApplication.h" #include "core/memcheck.h" UBDownloadWidget::UBDownloadWidget(QWidget *parent, const char *name):QWidget(parent) , mpLayout(NULL) , mpBttnLayout(NULL) , mpTree(NULL) , mpCancelBttn(NULL) , mpItem(NULL) { setObjectName(name); setWindowTitle(tr("Downloading files")); SET_STYLE_SHEET(); resize(400, 300); mpLayout = new QVBoxLayout(this); setLayout(mpLayout); mpTree = new QTreeWidget(this); mpTree->setRootIsDecorated(false); mpTree->setColumnCount(2); mpTree->header()->setStretchLastSection(false); mpTree->header()->setResizeMode(eItemColumn_Desc, QHeaderView::Stretch); mpTree->header()->setResizeMode(eItemColumn_Close, QHeaderView::Custom); mpTree->resizeColumnToContents(eItemColumn_Close); mpTree->header()->close(); mpLayout->addWidget(mpTree, 1); mpBttnLayout = new QHBoxLayout(); mpBttnLayout->addStretch(1); mpCancelBttn = new QPushButton(tr("Cancel"), this); mpCancelBttn->setObjectName("DockPaletteWidgetButton"); mpBttnLayout->addWidget(mpCancelBttn, 0); mpLayout->addLayout(mpBttnLayout); connect(UBDownloadManager::downloadManager(), SIGNAL(fileAddedToDownload()), this, SLOT(onFileAddedToDownload())); connect(UBDownloadManager::downloadManager(), SIGNAL(downloadUpdated(int,qint64,qint64)), this, SLOT(onDownloadUpdated(int,qint64,qint64))); connect(UBDownloadManager::downloadManager(), SIGNAL(downloadFinished(int)), this, SLOT(onDownloadFinished(int))); connect(mpCancelBttn, SIGNAL(clicked()), this, SLOT(onCancelClicked())); connect(mpTree, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(onItemClicked(QTreeWidgetItem*,int))); } UBDownloadWidget::~UBDownloadWidget() { if(NULL != mpCancelBttn) { delete mpCancelBttn; mpCancelBttn = NULL; } if(NULL != mpTree) { delete mpTree; mpTree = NULL; } if(NULL != mpBttnLayout) { delete mpBttnLayout; mpBttnLayout = NULL; } if(NULL != mpLayout) { delete mpLayout; mpLayout = NULL; } } void UBDownloadWidget::onFileAddedToDownload() { if(NULL != mpTree) { mpTree->clear(); addCurrentDownloads(); addPendingDownloads(); } } void UBDownloadWidget::addCurrentDownloads() { QVector<sDownloadFileDesc> actualDL = UBDownloadManager::downloadManager()->currentDownloads(); qDebug() << "Actual downloads size: " << actualDL.size(); for(int i=0; i<actualDL.size();i++) { mpItem = new QTreeWidgetItem(mpTree); mpItem->setText(eItemColumn_Desc, actualDL.at(i).name); mpItem->setData(eItemColumn_Desc, Qt::UserRole, QVariant(actualDL.at(i).id)); mpItem->setIcon(eItemColumn_Close, QIcon(":images/close.svg")); mpTree->addTopLevelItem(mpItem); mpItem = new QTreeWidgetItem(mpTree); mpItem->setData(eItemColumn_Desc, Qt::UserRole, actualDL.at(i).currentSize); mpItem->setData(eItemColumn_Desc, Qt::UserRole + 1, actualDL.at(i).totalSize); mpItem->setData(eItemColumn_Desc, Qt::UserRole + 2, actualDL.at(i).id); mpTree->addTopLevelItem(mpItem); mpTree->setItemDelegateForRow(((i+1)*2)-1, &mProgressBarDelegate); } } void UBDownloadWidget::addPendingDownloads() { QVector<sDownloadFileDesc> pendingDL = UBDownloadManager::downloadManager()->pendingDownloads(); for(int i=0; i<pendingDL.size(); i++) { mpItem = new QTreeWidgetItem(mpTree); mpItem->setText(eItemColumn_Desc, pendingDL.at(i).name); mpItem->setData(eItemColumn_Desc, Qt::UserRole, QVariant(pendingDL.at(i).id)); mpTree->addTopLevelItem(mpItem); } } void UBDownloadWidget::onDownloadUpdated(int id, qint64 crnt, qint64 total) { if(NULL != mpTree) { QAbstractItemModel* model = mpTree->model(); if(NULL != model) { for(int i=0; i< model->rowCount(); i++) { QModelIndex currentIndex = model->index(i, eItemColumn_Desc); if(id == currentIndex.data(Qt::UserRole + 2)) { model->setData(currentIndex, crnt, Qt::UserRole); model->setData(currentIndex, total, Qt::UserRole + 1); break; } } } } } void UBDownloadWidget::onDownloadFinished(int id) { Q_UNUSED(id); onFileAddedToDownload(); } void UBDownloadWidget::onCancelClicked() { UBDownloadManager::downloadManager()->cancelDownloads(); } void UBDownloadWidget::onItemClicked(QTreeWidgetItem *pItem, int col) { if( eItemColumn_Close == col && "" != pItem->text(eItemColumn_Desc)){ UBDownloadManager::downloadManager()->cancelDownload(pItem->data(eItemColumn_Desc, Qt::UserRole).toInt()); } } UBDownloadProgressDelegate::UBDownloadProgressDelegate(QObject *parent):QItemDelegate(parent) { } void UBDownloadProgressDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionProgressBarV2 opt; opt.rect = option.rect; opt.minimum = 0; opt.maximum = index.data(Qt::UserRole + 1).toInt(); opt.progress = index.data(Qt::UserRole).toInt(); if(0 == index.column()){ QApplication::style()->drawControl(QStyle::CE_ProgressBar, &opt, painter, 0); } }
#include <QDebug> #include <QHeaderView> #include <QStyleOptionProgressBarV2> #include <QApplication> #include "UBDownloadWidget.h" #include "globals/UBGlobals.h" #include "core/UBApplication.h" #include "core/memcheck.h" UBDownloadWidget::UBDownloadWidget(QWidget *parent, const char *name):QWidget(parent) , mpLayout(NULL) , mpBttnLayout(NULL) , mpTree(NULL) , mpCancelBttn(NULL) , mpItem(NULL) { setObjectName(name); setWindowTitle(tr("Downloading files")); SET_STYLE_SHEET(); resize(400, 300); mpLayout = new QVBoxLayout(this); setLayout(mpLayout); mpTree = new QTreeWidget(this); mpTree->setRootIsDecorated(false); mpTree->setColumnCount(2); mpTree->header()->setStretchLastSection(false); mpTree->header()->setResizeMode(eItemColumn_Desc, QHeaderView::Stretch); mpTree->header()->setResizeMode(eItemColumn_Close, QHeaderView::Custom); mpTree->resizeColumnToContents(eItemColumn_Close); mpTree->header()->close(); mpLayout->addWidget(mpTree, 1); mpBttnLayout = new QHBoxLayout(); mpBttnLayout->addStretch(1); mpCancelBttn = new QPushButton(tr
n_Desc, Qt::UserRole, QVariant(actualDL.at(i).id)); mpItem->setIcon(eItemColumn_Close, QIcon(":images/close.svg")); mpTree->addTopLevelItem(mpItem); mpItem = new QTreeWidgetItem(mpTree); mpItem->setData(eItemColumn_Desc, Qt::UserRole, actualDL.at(i).currentSize); mpItem->setData(eItemColumn_Desc, Qt::UserRole + 1, actualDL.at(i).totalSize); mpItem->setData(eItemColumn_Desc, Qt::UserRole + 2, actualDL.at(i).id); mpTree->addTopLevelItem(mpItem); mpTree->setItemDelegateForRow(((i+1)*2)-1, &mProgressBarDelegate); } } void UBDownloadWidget::addPendingDownloads() { QVector<sDownloadFileDesc> pendingDL = UBDownloadManager::downloadManager()->pendingDownloads(); for(int i=0; i<pendingDL.size(); i++) { mpItem = new QTreeWidgetItem(mpTree); mpItem->setText(eItemColumn_Desc, pendingDL.at(i).name); mpItem->setData(eItemColumn_Desc, Qt::UserRole, QVariant(pendingDL.at(i).id)); mpTree->addTopLevelItem(mpItem); } } void UBDownloadWidget::onDownloadUpdated(int id, qint64 crnt, qint64 total) { if(NULL != mpTree) { QAbstractItemModel* model = mpTree->model(); if(NULL != model) { for(int i=0; i< model->rowCount(); i++) { QModelIndex currentIndex = model->index(i, eItemColumn_Desc); if(id == currentIndex.data(Qt::UserRole + 2)) { model->setData(currentIndex, crnt, Qt::UserRole); model->setData(currentIndex, total, Qt::UserRole + 1); break; } } } } } void UBDownloadWidget::onDownloadFinished(int id) { Q_UNUSED(id); onFileAddedToDownload(); } void UBDownloadWidget::onCancelClicked() { UBDownloadManager::downloadManager()->cancelDownloads(); } void UBDownloadWidget::onItemClicked(QTreeWidgetItem *pItem, int col) { if( eItemColumn_Close == col && "" != pItem->text(eItemColumn_Desc)){ UBDownloadManager::downloadManager()->cancelDownload(pItem->data(eItemColumn_Desc, Qt::UserRole).toInt()); } } UBDownloadProgressDelegate::UBDownloadProgressDelegate(QObject *parent):QItemDelegate(parent) { } void UBDownloadProgressDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionProgressBarV2 opt; opt.rect = option.rect; opt.minimum = 0; opt.maximum = index.data(Qt::UserRole + 1).toInt(); opt.progress = index.data(Qt::UserRole).toInt(); if(0 == index.column()){ QApplication::style()->drawControl(QStyle::CE_ProgressBar, &opt, painter, 0); } }
("Cancel"), this); mpCancelBttn->setObjectName("DockPaletteWidgetButton"); mpBttnLayout->addWidget(mpCancelBttn, 0); mpLayout->addLayout(mpBttnLayout); connect(UBDownloadManager::downloadManager(), SIGNAL(fileAddedToDownload()), this, SLOT(onFileAddedToDownload())); connect(UBDownloadManager::downloadManager(), SIGNAL(downloadUpdated(int,qint64,qint64)), this, SLOT(onDownloadUpdated(int,qint64,qint64))); connect(UBDownloadManager::downloadManager(), SIGNAL(downloadFinished(int)), this, SLOT(onDownloadFinished(int))); connect(mpCancelBttn, SIGNAL(clicked()), this, SLOT(onCancelClicked())); connect(mpTree, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(onItemClicked(QTreeWidgetItem*,int))); } UBDownloadWidget::~UBDownloadWidget() { if(NULL != mpCancelBttn) { delete mpCancelBttn; mpCancelBttn = NULL; } if(NULL != mpTree) { delete mpTree; mpTree = NULL; } if(NULL != mpBttnLayout) { delete mpBttnLayout; mpBttnLayout = NULL; } if(NULL != mpLayout) { delete mpLayout; mpLayout = NULL; } } void UBDownloadWidget::onFileAddedToDownload() { if(NULL != mpTree) { mpTree->clear(); addCurrentDownloads(); addPendingDownloads(); } } void UBDownloadWidget::addCurrentDownloads() { QVector<sDownloadFileDesc> actualDL = UBDownloadManager::downloadManager()->currentDownloads(); qDebug() << "Actual downloads size: " << actualDL.size(); for(int i=0; i<actualDL.size();i++) { mpItem = new QTreeWidgetItem(mpTree); mpItem->setText(eItemColumn_Desc, actualDL.at(i).name); mpItem->setData(eItemColum
random
[ { "content": "\t\tSSL_CIPHER *new_cipher;\n", "file_path": "Sankore-ThirdParty/openssl/0.9.8i/include/openssl/ssl3.h", "rank": 0, "score": 129144.86743968823 }, { "content": "X509V3_EXT_NEW ext_new;\n", "file_path": "Sankore-ThirdParty/openssl/0.9.8i/include/openssl/x509v3.h", "rank"...
C++
libs/semanticsearch/src/semanticsearch/query/query_executor.cpp
devjsc/ledger
5681480faf6e2aeee577f149c17745d6ab4d4ab3
#include "semanticsearch/query/query_executor.hpp" #include <cassert> namespace fetch { namespace semanticsearch { QueryExecutor::QueryExecutor(SharedSemanticSearchModule instance, ErrorTracker &error_tracker) : error_tracker_(error_tracker) , semantic_search_module_{std::move(instance)} {} void QueryExecutor::Execute(Query const &query, Agent agent) { agent_ = std::move(agent); error_tracker_.SetSource(query.source, query.filename); if (query.statements.empty()) { return; } for (auto const &stmt : query.statements) { switch (stmt[0].properties) { case QueryInstruction::PROP_CTX_MODEL: ExecuteDefine(stmt); break; case QueryInstruction::PROP_CTX_SET: ExecuteSet(stmt); break; case QueryInstruction::PROP_CTX_STORE: ExecuteStore(stmt); break; default: error_tracker_.RaiseRuntimeError("Unknown statement type.", stmt[0].token); return; } if (error_tracker_.HasErrors()) { break; } } } QueryExecutor::Vocabulary QueryExecutor::GetInstance(std::string const &name) { assert(context_.Has(name)); return context_.Get(name); } void QueryExecutor::ExecuteStore(CompiledStatement const &stmt) { using Type = QueryInstruction::Type; if (stmt[1].type != Type::IDENTIFIER) { error_tracker_.RaiseSyntaxError("Expected variable name.", stmt[1].token); return; } auto name = static_cast<std::string>(stmt[1].token); if (!context_.Has(name)) { error_tracker_.RaiseSyntaxError("Vairable not defined", stmt[1].token); return; } auto obj = context_.Get(name); auto model_name = context_.GetModelName(name); if (!semantic_search_module_->HasModel(model_name)) { error_tracker_.RaiseSyntaxError("Could not find model '" + model_name + "'", stmt[1].token); return; } auto model = semantic_search_module_->GetModel(model_name); if (model == nullptr) { error_tracker_.RaiseInternalError("Model '" + model_name + "' is null.", stmt[1].token); return; } model->VisitSubmodelsWithVocabulary( [this, stmt](std::string, std::string mname, Vocabulary obj) { auto model = semantic_search_module_->GetModel(mname); if (model == nullptr) { error_tracker_.RaiseSyntaxError("Could not find model '" + mname + "'", stmt[1].token); return; } SemanticPosition position = model->Reduce(obj); assert(semantic_search_module_->advertisement_register() != nullptr); semantic_search_module_->advertisement_register()->AdvertiseAgent(agent_->id, mname, position); agent_->RegisterVocabularyLocation(mname, position); }, obj); } void QueryExecutor::ExecuteSet(CompiledStatement const &stmt) { using Type = QueryInstruction::Type; std::size_t i = 3; if (stmt.size() < i) { error_tracker_.RaiseSyntaxError("Set statment has incorrect syntax.", stmt[0].token); return; } if (stmt[1].type != Type::IDENTIFIER) { error_tracker_.RaiseSyntaxError("Expected variable name.", stmt[1].token); return; } if (stmt[2].type != Type::IDENTIFIER) { error_tracker_.RaiseSyntaxError("Expected variable type.", stmt[2].token); return; } std::vector<QueryVariant> stack; std::vector<Vocabulary> scope_objects; Vocabulary last; int scope_depth = 0; QueryVariant object_name = NewQueryVariant(static_cast<std::string>(stmt[1].token), TYPE_KEY, stmt[1].token); stack.push_back(object_name); QueryVariant model_name = NewQueryVariant(static_cast<std::string>(stmt[2].token), TYPE_KEY, stmt[2].token); stack.push_back(model_name); while (i < stmt.size()) { auto x = stmt[i]; switch (x.type) { case Type::PUSH_SCOPE: { ++scope_depth; auto obj = VocabularyInstance::New<PropertyMap>({}); scope_objects.push_back(obj); break; } case Type::POP_SCOPE: --scope_depth; last = scope_objects.back(); scope_objects.pop_back(); { QueryVariant s = NewQueryVariant(last, TYPE_INSTANCE, x.token); stack.push_back(s); } break; case Type::ATTRIBUTE: { auto value = stack.back(); stack.pop_back(); auto key = stack.back(); stack.pop_back(); auto object = scope_objects.back(); assert(object != nullptr); std::string name = static_cast<std::string>(key->As<Token>()); switch (value->type()) { case TYPE_INTEGER: object->Insert(name, VocabularyInstance::New<Int>(value->As<Int>())); break; case TYPE_FLOAT: object->Insert(name, VocabularyInstance::New<Float>(value->As<Float>())); break; case TYPE_STRING: object->Insert(name, VocabularyInstance::New<String>(value->As<String>())); break; case TYPE_INSTANCE: object->Insert(name, value->As<Vocabulary>()); break; default: break; } } break; case Type::SEPARATOR: break; case Type::IDENTIFIER: { auto obj = context_.Get(static_cast<std::string>( x.token)); QueryVariant ele = NewQueryVariant(obj, TYPE_INSTANCE, x.token); stack.push_back(ele); break; } case Type::FLOAT: { QueryVariant ele = NewQueryVariant(Float(x.token.AsFloat()), TYPE_FLOAT, x.token); stack.push_back(ele); break; } case Type::INTEGER: { QueryVariant ele = NewQueryVariant(Int(atol(std::string(x.token).c_str())), TYPE_INTEGER, x.token); stack.push_back(ele); break; } case Type::STRING: { std::string str = static_cast<std::string>(x.token.SubArray(1, x.token.size() - 2)); QueryVariant ele = NewQueryVariant(str, TYPE_STRING, x.token); stack.push_back(ele); break; } case Type::OBJECT_KEY: { QueryVariant ele = NewQueryVariant(x.token, TYPE_KEY, x.token); stack.push_back(ele); break; } default: break; } ++i; } if (static_cast<bool>(last)) { auto value = stack.back(); stack.pop_back(); auto model_var = stack.back(); stack.pop_back(); auto key = stack.back(); stack.pop_back(); auto name_of_model = model_var->As<std::string>(); auto model = semantic_search_module_->GetModel(name_of_model); if (model == nullptr) { error_tracker_.RaiseRuntimeError("Could not find model '" + name_of_model + "'.", stmt[stmt.size() - 1].token); return; } if (!model->Validate(last)) { error_tracker_.RaiseRuntimeError("Instance does not match model requirements.", stmt[stmt.size() - 1].token); return; } context_.Set(key->As<std::string>(), last, name_of_model); } else { error_tracker_.RaiseRuntimeError( "No object instance was created, only declared. This is not supported yet.", stmt[stmt.size() - 1].token); return; } } void QueryExecutor::ExecuteDefine(CompiledStatement const &stmt) { std::size_t i = 1; stack_.clear(); std::vector<ModelInterfaceBuilder> scope_models; ModelInterfaceBuilder last; int scope_depth = 0; using Type = QueryInstruction::Type; while (i < stmt.size()) { auto x = stmt[i]; switch (x.type) { case Type::PUSH_SCOPE: ++scope_depth; scope_models.push_back(semantic_search_module_->NewProxy()); break; case Type::POP_SCOPE: --scope_depth; last = scope_models.back(); scope_models.pop_back(); { QueryVariant s = NewQueryVariant(last.model(), TYPE_MODEL, x.token); stack_.push_back(s); } break; case Type::ATTRIBUTE: { QueryVariant value = stack_.back(); stack_.pop_back(); QueryVariant key = stack_.back(); stack_.pop_back(); auto model = scope_models.back(); if (TypeMismatch<ModelField>(value, x.token)) { return; } if (TypeMismatch<Token>(key, x.token)) { return; } if (value->As<ModelField>() == nullptr) { error_tracker_.RaiseInternalError("Attribute value is null.", x.token); break; } if (model.model() == nullptr) { error_tracker_.RaiseInternalError("Model is null.", x.token); break; } model.Field(static_cast<std::string>(key->As<Token>()), value->As<ModelField>()); } break; case Type::SEPARATOR: break; case Type::IDENTIFIER: if (scope_depth == 0) { QueryVariant ele = NewQueryVariant(x.token, TYPE_KEY, x.token); stack_.push_back(ele); } else { auto field_name = static_cast<std::string>(x.token); if (!semantic_search_module_->HasField(field_name)) { error_tracker_.RaiseRuntimeError( "Could not find field: " + static_cast<std::string>(x.token), x.token); return; } QueryVariant ele = NewQueryVariant(semantic_search_module_->GetField(field_name), TYPE_MODEL, x.token); stack_.push_back(ele); } break; case Type::FLOAT: { QueryVariant ele = NewQueryVariant(x.token.AsFloat(), TYPE_FLOAT, x.token); stack_.push_back(ele); break; } case Type::INTEGER: { QueryVariant ele = NewQueryVariant(Int(atol(std::string(x.token).c_str())), TYPE_INTEGER, x.token); stack_.push_back(ele); break; } case Type::STRING: { std::string str = static_cast<std::string>(x.token.SubArray(1, x.token.size() - 2)); QueryVariant ele = NewQueryVariant(str, TYPE_STRING, x.token); stack_.push_back(ele); break; } case Type::OBJECT_KEY: { QueryVariant ele = NewQueryVariant(x.token, TYPE_KEY, x.token); stack_.push_back(ele); break; } case Type::FUNCTION: { QueryVariant ele = NewQueryVariant(x.token, TYPE_FUNCTION_NAME, x.token); stack_.push_back(ele); break; } case Type::EXECUTE_CALL: { if (stack_.empty()) { std::cerr << "INTERNAL ERROR!" << std::endl; exit(-1); } std::vector<void const *> args; std::vector<std::type_index> arg_signature; uint64_t n = stack_.size() - 1; while ((n != 0) && (stack_[n]->type() != TYPE_FUNCTION_NAME)) { auto arg = stack_[n]; args.push_back(arg->data()); arg_signature.push_back(arg->type_index()); --n; } std::reverse(args.begin(), args.end()); std::reverse(arg_signature.begin(), arg_signature.end()); if (TypeMismatch<Token>(stack_[n], stack_[n]->token())) { return; } auto function_name = static_cast<std::string>(stack_[n]->As<Token>()); if (!semantic_search_module_->HasFunction(function_name)) { error_tracker_.RaiseRuntimeError("Function '" + function_name + "' does not exist.", stack_[n]->token()); return; } auto & function = (*semantic_search_module_)[function_name]; std::type_index ret_type = function.return_type(); if (!function.ValidateSignature(ret_type, arg_signature)) { error_tracker_.RaiseRuntimeError( "Call to '" + function_name + "' does not match signature.", stack_[n]->token()); return; } QueryVariant ret; try { ret = function(args); } catch (std::runtime_error const &e) { error_tracker_.RaiseRuntimeError(e.what(), stack_[n]->token()); return; } for (std::size_t j = 0; j < args.size(); ++j) { stack_.pop_back(); } stack_.pop_back(); stack_.push_back(ret); break; } default: std::cout << "'" << x.token << "' - TODO IMPLEMENT " << std::endl; break; } ++i; } if (bool(last)) { auto value = stack_.back(); stack_.pop_back(); auto key = stack_.back(); stack_.pop_back(); semantic_search_module_->AddModel(static_cast<std::string>(key->As<Token>()), last.model()); } else { std::cout << "NOT READY: " << last.model() << std::endl; } } } }
#include "semanticsearch/query/query_executor.hpp" #include <cassert> namespace fetch { namespace semanticsearch { QueryExecutor::QueryExecutor(SharedSemanticSearchModule instance, ErrorTracker &error_tracker) : error_tracker_(error_tracker) , semantic_search_module_{std::move(instance)} {} void QueryExecutor::Execute(Query const &query, Agent agent) { agent_ = std::move(agent); error_tracker_.SetSource(query.source, query.filename); if (query.statements.empty()) { return; } for (auto const &stmt : query.statements) { switch (stmt[0].properties) { case QueryInstruction::PROP_CTX_MODEL: ExecuteDefine(stmt); break; case QueryInstruction::PROP_CTX_SET: ExecuteSet(stmt); break; case QueryInstruction::PROP_CTX_STORE: ExecuteStore(stmt); break; default: error_tracker_.RaiseRuntimeError("Unknown statement type.", stmt[0].token); return; } if (error_tracker_.HasErrors()) { break; } } } QueryExecutor::Vocabulary QueryExecutor::GetInstance(std::string const &name) { assert(context_.Has(name)); return context_.Get(name); } void QueryExecutor::ExecuteStore(CompiledStatement const &stmt) { using Type = QueryInstruction::Type; if (stmt[1].type != Type::IDENTIFIER) { error_tracker_.RaiseSyntaxError("Expected variable name.", stmt[1].token); return; } auto name = static_cast<std::string>(stmt[1].token); if (!context_.Has(name)) { error_tracker_.RaiseSyntaxError("Vairable not defined", stmt[1].token); return; } auto obj = context_.Get(name); auto model_name = context_.GetModelName(name); if (!semantic_search_module_->HasModel(model_name)) { error_tracker_.RaiseSyntaxError("Could not find model '" + model_name + "'", stmt[1].token); return; } auto model = semantic_search_module_->GetModel(model_name); if (model == nullptr) { error_tracker_.RaiseInternalError("Model '" + model_name + "' is null.", stmt[1].token); return; }
; } void QueryExecutor::ExecuteSet(CompiledStatement const &stmt) { using Type = QueryInstruction::Type; std::size_t i = 3; if (stmt.size() < i) { error_tracker_.RaiseSyntaxError("Set statment has incorrect syntax.", stmt[0].token); return; } if (stmt[1].type != Type::IDENTIFIER) { error_tracker_.RaiseSyntaxError("Expected variable name.", stmt[1].token); return; } if (stmt[2].type != Type::IDENTIFIER) { error_tracker_.RaiseSyntaxError("Expected variable type.", stmt[2].token); return; } std::vector<QueryVariant> stack; std::vector<Vocabulary> scope_objects; Vocabulary last; int scope_depth = 0; QueryVariant object_name = NewQueryVariant(static_cast<std::string>(stmt[1].token), TYPE_KEY, stmt[1].token); stack.push_back(object_name); QueryVariant model_name = NewQueryVariant(static_cast<std::string>(stmt[2].token), TYPE_KEY, stmt[2].token); stack.push_back(model_name); while (i < stmt.size()) { auto x = stmt[i]; switch (x.type) { case Type::PUSH_SCOPE: { ++scope_depth; auto obj = VocabularyInstance::New<PropertyMap>({}); scope_objects.push_back(obj); break; } case Type::POP_SCOPE: --scope_depth; last = scope_objects.back(); scope_objects.pop_back(); { QueryVariant s = NewQueryVariant(last, TYPE_INSTANCE, x.token); stack.push_back(s); } break; case Type::ATTRIBUTE: { auto value = stack.back(); stack.pop_back(); auto key = stack.back(); stack.pop_back(); auto object = scope_objects.back(); assert(object != nullptr); std::string name = static_cast<std::string>(key->As<Token>()); switch (value->type()) { case TYPE_INTEGER: object->Insert(name, VocabularyInstance::New<Int>(value->As<Int>())); break; case TYPE_FLOAT: object->Insert(name, VocabularyInstance::New<Float>(value->As<Float>())); break; case TYPE_STRING: object->Insert(name, VocabularyInstance::New<String>(value->As<String>())); break; case TYPE_INSTANCE: object->Insert(name, value->As<Vocabulary>()); break; default: break; } } break; case Type::SEPARATOR: break; case Type::IDENTIFIER: { auto obj = context_.Get(static_cast<std::string>( x.token)); QueryVariant ele = NewQueryVariant(obj, TYPE_INSTANCE, x.token); stack.push_back(ele); break; } case Type::FLOAT: { QueryVariant ele = NewQueryVariant(Float(x.token.AsFloat()), TYPE_FLOAT, x.token); stack.push_back(ele); break; } case Type::INTEGER: { QueryVariant ele = NewQueryVariant(Int(atol(std::string(x.token).c_str())), TYPE_INTEGER, x.token); stack.push_back(ele); break; } case Type::STRING: { std::string str = static_cast<std::string>(x.token.SubArray(1, x.token.size() - 2)); QueryVariant ele = NewQueryVariant(str, TYPE_STRING, x.token); stack.push_back(ele); break; } case Type::OBJECT_KEY: { QueryVariant ele = NewQueryVariant(x.token, TYPE_KEY, x.token); stack.push_back(ele); break; } default: break; } ++i; } if (static_cast<bool>(last)) { auto value = stack.back(); stack.pop_back(); auto model_var = stack.back(); stack.pop_back(); auto key = stack.back(); stack.pop_back(); auto name_of_model = model_var->As<std::string>(); auto model = semantic_search_module_->GetModel(name_of_model); if (model == nullptr) { error_tracker_.RaiseRuntimeError("Could not find model '" + name_of_model + "'.", stmt[stmt.size() - 1].token); return; } if (!model->Validate(last)) { error_tracker_.RaiseRuntimeError("Instance does not match model requirements.", stmt[stmt.size() - 1].token); return; } context_.Set(key->As<std::string>(), last, name_of_model); } else { error_tracker_.RaiseRuntimeError( "No object instance was created, only declared. This is not supported yet.", stmt[stmt.size() - 1].token); return; } } void QueryExecutor::ExecuteDefine(CompiledStatement const &stmt) { std::size_t i = 1; stack_.clear(); std::vector<ModelInterfaceBuilder> scope_models; ModelInterfaceBuilder last; int scope_depth = 0; using Type = QueryInstruction::Type; while (i < stmt.size()) { auto x = stmt[i]; switch (x.type) { case Type::PUSH_SCOPE: ++scope_depth; scope_models.push_back(semantic_search_module_->NewProxy()); break; case Type::POP_SCOPE: --scope_depth; last = scope_models.back(); scope_models.pop_back(); { QueryVariant s = NewQueryVariant(last.model(), TYPE_MODEL, x.token); stack_.push_back(s); } break; case Type::ATTRIBUTE: { QueryVariant value = stack_.back(); stack_.pop_back(); QueryVariant key = stack_.back(); stack_.pop_back(); auto model = scope_models.back(); if (TypeMismatch<ModelField>(value, x.token)) { return; } if (TypeMismatch<Token>(key, x.token)) { return; } if (value->As<ModelField>() == nullptr) { error_tracker_.RaiseInternalError("Attribute value is null.", x.token); break; } if (model.model() == nullptr) { error_tracker_.RaiseInternalError("Model is null.", x.token); break; } model.Field(static_cast<std::string>(key->As<Token>()), value->As<ModelField>()); } break; case Type::SEPARATOR: break; case Type::IDENTIFIER: if (scope_depth == 0) { QueryVariant ele = NewQueryVariant(x.token, TYPE_KEY, x.token); stack_.push_back(ele); } else { auto field_name = static_cast<std::string>(x.token); if (!semantic_search_module_->HasField(field_name)) { error_tracker_.RaiseRuntimeError( "Could not find field: " + static_cast<std::string>(x.token), x.token); return; } QueryVariant ele = NewQueryVariant(semantic_search_module_->GetField(field_name), TYPE_MODEL, x.token); stack_.push_back(ele); } break; case Type::FLOAT: { QueryVariant ele = NewQueryVariant(x.token.AsFloat(), TYPE_FLOAT, x.token); stack_.push_back(ele); break; } case Type::INTEGER: { QueryVariant ele = NewQueryVariant(Int(atol(std::string(x.token).c_str())), TYPE_INTEGER, x.token); stack_.push_back(ele); break; } case Type::STRING: { std::string str = static_cast<std::string>(x.token.SubArray(1, x.token.size() - 2)); QueryVariant ele = NewQueryVariant(str, TYPE_STRING, x.token); stack_.push_back(ele); break; } case Type::OBJECT_KEY: { QueryVariant ele = NewQueryVariant(x.token, TYPE_KEY, x.token); stack_.push_back(ele); break; } case Type::FUNCTION: { QueryVariant ele = NewQueryVariant(x.token, TYPE_FUNCTION_NAME, x.token); stack_.push_back(ele); break; } case Type::EXECUTE_CALL: { if (stack_.empty()) { std::cerr << "INTERNAL ERROR!" << std::endl; exit(-1); } std::vector<void const *> args; std::vector<std::type_index> arg_signature; uint64_t n = stack_.size() - 1; while ((n != 0) && (stack_[n]->type() != TYPE_FUNCTION_NAME)) { auto arg = stack_[n]; args.push_back(arg->data()); arg_signature.push_back(arg->type_index()); --n; } std::reverse(args.begin(), args.end()); std::reverse(arg_signature.begin(), arg_signature.end()); if (TypeMismatch<Token>(stack_[n], stack_[n]->token())) { return; } auto function_name = static_cast<std::string>(stack_[n]->As<Token>()); if (!semantic_search_module_->HasFunction(function_name)) { error_tracker_.RaiseRuntimeError("Function '" + function_name + "' does not exist.", stack_[n]->token()); return; } auto & function = (*semantic_search_module_)[function_name]; std::type_index ret_type = function.return_type(); if (!function.ValidateSignature(ret_type, arg_signature)) { error_tracker_.RaiseRuntimeError( "Call to '" + function_name + "' does not match signature.", stack_[n]->token()); return; } QueryVariant ret; try { ret = function(args); } catch (std::runtime_error const &e) { error_tracker_.RaiseRuntimeError(e.what(), stack_[n]->token()); return; } for (std::size_t j = 0; j < args.size(); ++j) { stack_.pop_back(); } stack_.pop_back(); stack_.push_back(ret); break; } default: std::cout << "'" << x.token << "' - TODO IMPLEMENT " << std::endl; break; } ++i; } if (bool(last)) { auto value = stack_.back(); stack_.pop_back(); auto key = stack_.back(); stack_.pop_back(); semantic_search_module_->AddModel(static_cast<std::string>(key->As<Token>()), last.model()); } else { std::cout << "NOT READY: " << last.model() << std::endl; } } } }
model->VisitSubmodelsWithVocabulary( [this, stmt](std::string, std::string mname, Vocabulary obj) { auto model = semantic_search_module_->GetModel(mname); if (model == nullptr) { error_tracker_.RaiseSyntaxError("Could not find model '" + mname + "'", stmt[1].token); return; } SemanticPosition position = model->Reduce(obj); assert(semantic_search_module_->advertisement_register() != nullptr); semantic_search_module_->advertisement_register()->AdvertiseAgent(agent_->id, mname, position); agent_->RegisterVocabularyLocation(mname, position); }, obj)
call_expression
[ { "content": " enum class Type\n\n {\n\n UNKNOWN = 0,\n\n SET_CONTEXT,\n\n PUSH_SCOPE,\n\n POP_SCOPE,\n\n\n\n FUNCTION = 50,\n\n EXECUTE_CALL,\n\n\n\n // Operators come first and are ordered according to precendence\n\n // That is: DO not change the order unless you intensionally\n\n ...
C++
ipc/src/client_endpoint_com.cpp
tyoma/micro-profiler
32f6981c643b93997752d414f631fd6684772b28
#include <ipc/endpoint.h> #include <atlbase.h> #include <common/module.h> #include <common/string.h> #include <ipc/com/init.h> #include <functional> using namespace std; namespace micro_profiler { namespace ipc { namespace com { class inbound_stream : public ISequentialStream { public: inbound_stream(channel &underlying); ~inbound_stream(); STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject); STDMETHODIMP_(ULONG) AddRef(); STDMETHODIMP_(ULONG) Release(); STDMETHODIMP Read(void *, ULONG, ULONG *); STDMETHODIMP Write(const void *message, ULONG size, ULONG *written); private: unsigned _references; channel &_underlying; }; class client_session : public channel { public: client_session(const char *destination_endpoint_id, channel &inbound); virtual void disconnect() throw(); virtual void message(const_byte_range payload); private: static shared_ptr<void> create_activation_context(); static shared_ptr<void> lock_activation_context(const shared_ptr<void> &ctx); private: channel &_inbound; com_initialize _com_initialize; CComPtr<ISequentialStream> _stream; DWORD _sink_cookie; }; inbound_stream::inbound_stream(channel &underlying) : _references(0), _underlying(underlying) { } inbound_stream::~inbound_stream() { _underlying.disconnect(); } STDMETHODIMP inbound_stream::QueryInterface(REFIID riid, void **object) { if (IID_IUnknown != riid && IID_ISequentialStream != riid) return E_NOINTERFACE; *object = (ISequentialStream *)this; AddRef(); return S_OK; } STDMETHODIMP_(ULONG) inbound_stream::AddRef() { return ++_references; } STDMETHODIMP_(ULONG) inbound_stream::Release() { unsigned int r = --_references; if (!r) delete this; return r; } STDMETHODIMP inbound_stream::Read(void *, ULONG, ULONG *) { return E_NOTIMPL; } STDMETHODIMP inbound_stream::Write(const void *buffer, ULONG size, ULONG * ) { return _underlying.message(const_byte_range(static_cast<const byte *>(buffer), size)), S_OK; } client_session::client_session(const char *destination_endpoint_id, channel &inbound) : _inbound(inbound) { shared_ptr<void> ctx = create_activation_context(); shared_ptr<void> ctx_lock = lock_activation_context(ctx); const guid_t id = from_string(destination_endpoint_id); CComPtr<inbound_stream> sink(new inbound_stream(inbound)); if (S_OK != _stream.CoCreateInstance(id, NULL, CLSCTX_LOCAL_SERVER)) throw connection_refused(destination_endpoint_id); CComQIPtr<IConnectionPoint>(_stream)->Advise(sink, &_sink_cookie); } void client_session::disconnect() throw() { } void client_session::message(const_byte_range payload) { ULONG written; _stream->Write(payload.begin(), static_cast<ULONG>(payload.length()), &written); } shared_ptr<void> client_session::create_activation_context() { ACTCTX ctx = { sizeof(ACTCTX), }; HMODULE hmodule = (HMODULE)get_module_info((void *)&create_activation_context).base; ctx.hModule = hmodule; ctx.lpResourceName = ISOLATIONAWARE_MANIFEST_RESOURCE_ID; ctx.dwFlags = ACTCTX_FLAG_HMODULE_VALID | ACTCTX_FLAG_RESOURCE_NAME_VALID; HANDLE hcontext = ::CreateActCtx(&ctx); return INVALID_HANDLE_VALUE == hcontext ? shared_ptr<void>() : shared_ptr<void>(hcontext, &::ReleaseActCtx); } shared_ptr<void> client_session::lock_activation_context(const shared_ptr<void> &ctx) { ULONG_PTR cookie; return ctx && ::ActivateActCtx(ctx.get(), &cookie) ? shared_ptr<void>(reinterpret_cast<void*>(cookie), bind(&::DeactivateActCtx, 0, cookie)) : shared_ptr<void>(); } channel_ptr_t connect_client(const char *destination_endpoint_id, channel &inbound) { return channel_ptr_t(new client_session(destination_endpoint_id, inbound)); } } } }
#include <ipc/endpoint.h> #include <atlbase.h> #include <common/module.h> #include <common/string.h> #include <ipc/com/init.h> #include <functional> using namespace std; namespace micro_profiler { namespace ipc { namespace com { class inbound_stream : public ISequentialStream { public: inbound_stream(channel &underlying); ~inbound_stream(); STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject); STDMETHODIMP_(ULONG) AddRef(); STDMETHODIMP_(ULONG) Release(); STDMETHODIMP Read(void *, ULONG, ULONG *); STDMETHODIMP Write(const void *message, ULONG size, ULONG *written); private: unsigned _references; channel &_underlying; }; class client_session : public channel { public: client_session(const char *destination_endpoint_id, channel &inbound); virtual void disconnect() throw(); virtual void message(const_byte_range payload); private: static shared_ptr<void> create_activation_context(); static shared_ptr<void> lock_activation_context(const shared_ptr<void> &ctx); private: channel &_inbound; com_initialize _com_initialize; CComPtr<ISequentialStream> _stream; DWORD _sink_cookie; }; inbound_stream::inbound_stream(channel &underlying) : _references(0), _underlying(underlying) { } inbound_stream::~inbound_stream() { _underlying.disconnect(); } STDMETHODIMP inbound_stream::QueryInterface(REFIID riid, void **object) { if (IID_IUnknown != riid && IID_ISequentialStream != riid) return E_NOINTERFACE; *object = (ISequentialStream *)this; AddRef(); return S_OK; } STDMETHODIMP_(ULONG) inbound_stream::AddRef() { return ++_references; } STDMETHODIMP_(ULONG) inbound_stream::Release() { unsigned int r = --_references; if (!r) delete this; return r; } STDMETHODIMP inbound_stream::Read(void *, ULONG, ULONG *) { return E_NOTIMPL; } STDMETHODIMP inbound_stream::Write(const void *buffer, ULONG size, ULONG * ) { return _underlying.message(const_byte_range(static_cast<const byte *>(buffer), size)), S_OK; } client_session::client_session(const char *destination_endpoint_id, channel &inbound) : _inbound(inbound) { shared_ptr<void> ctx = create_activation_context(); shared_ptr<void> ctx_lock = lock_activation_context(ctx); const guid_t id = from_string(destination_endpoint_id); CComPtr<inbound_stream> sink(new inbound_stream(inbound)); if (S_OK != _stream.CoCreateInstance(id, NULL, CLSCTX_LOCAL_SERVER)) throw connection_refused(destination_endpoint_id); CComQIPtr<IConnectionPoint>(_stream)->Advise(sink, &_sink_cookie); } void client_session::disconnect() throw() { } void client_session::message(const_byte_range payload) { ULONG written; _stream->Write(payload.begin(), static_cast<ULONG>(payload.length()), &written); } shared_ptr<void> client_session::create_activation_context() { ACTCTX ctx = { sizeof(ACTCTX), }; HMODULE hmodule = (HMODULE)get_module_info((void *)&create_activation_context).base; ctx.hModule = hmodule; ctx.lpResourceName = ISOLATIONAWARE_MANIFEST_RESOURCE_ID; ctx.dwFlags = ACTCTX_FLAG_HMODULE_VALID | ACTCTX_FLAG_RESOURCE_NAME_VALID; HANDLE hcontext = ::CreateActCtx(&ctx); return INVALID_HANDLE_VALUE == hcontext ? shared_ptr<void>() : shared_ptr<void>(hcontext, &::ReleaseActCtx); }
channel_ptr_t connect_client(const char *destination_endpoint_id, channel &inbound) { return channel_ptr_t(new client_session(destination_endpoint_id, inbound)); } } } }
shared_ptr<void> client_session::lock_activation_context(const shared_ptr<void> &ctx) { ULONG_PTR cookie; return ctx && ::ActivateActCtx(ctx.get(), &cookie) ? shared_ptr<void>(reinterpret_cast<void*>(cookie), bind(&::DeactivateActCtx, 0, cookie)) : shared_ptr<void>(); }
function_block-full_function
[ { "content": "\t\t\tclass session : public ISequentialStream, public IConnectionPoint, public /*outbound*/ ipc::channel,\n\n\t\t\t\tpublic CComObjectRoot\n\n\t\t\t{\n\n\t\t\tpublic:\n\n\t\t\t\tBEGIN_COM_MAP(session)\n\n\t\t\t\t\tCOM_INTERFACE_ENTRY(ISequentialStream)\n\n\t\t\t\t\tCOM_INTERFACE_ENTRY(IConnection...
C++
test/ese/src/devlibtest/stat/statunit/movingavg.cxx
ScriptBox99/Extensible-Storage-Engine
3bcf428c8a041733043e18fd9ae55cffeba307b2
#include "statunittest.hxx" #include "stat.hxx" class MovingAverageTest : public UNITTEST { private: static MovingAverageTest s_instance; protected: MovingAverageTest() {} public: ~MovingAverageTest() {} public: const char * SzName() const; const char * SzDescription() const; bool FRunUnderESE98() const; bool FRunUnderESENT() const; bool FRunUnderESE97() const; ERR ErrTest(); }; MovingAverageTest MovingAverageTest::s_instance; const char * MovingAverageTest::SzName() const { return "MovingAverage"; }; const char * MovingAverageTest::SzDescription() const { return "Tests the statistic libraries' moving average support."; } bool MovingAverageTest::FRunUnderESE98() const { return true; } bool MovingAverageTest::FRunUnderESENT() const { return true; } bool MovingAverageTest::FRunUnderESE97() const { return true; } ERR MovingAverageTest::ErrTest() { wprintf( L"\tTesting Moving Average support ...\n"); #define TestTest( ftest ) if ( !(ftest) ) \ { \ wprintf(L" [line=%d] Test( %S ) failed w/ %d\n", __LINE__, #ftest, (DWORD)(ftest) ); \ STATAssertSz( fFalse, "HaltTest" ); \ } printf( "\tSingle-sample moving average...\n" ); CMovingAverage< ULONG, 1 > avgOneSample( 10 ); TestTest( 10 == avgOneSample.GetLastSample() ); TestTest( 10 == avgOneSample.GetAverage() ); avgOneSample.AddSample( 12 ); TestTest( 12 == avgOneSample.GetLastSample() ); TestTest( 12 == avgOneSample.GetAverage() ); avgOneSample.AddSample( 15 ); TestTest( 15 == avgOneSample.GetLastSample() ); TestTest( 15 == avgOneSample.GetAverage() ); avgOneSample.Reset( 20 ); TestTest( 20 == avgOneSample.GetLastSample() ); TestTest( 20 == avgOneSample.GetAverage() ); avgOneSample.AddSample( 30 ); TestTest( 30 == avgOneSample.GetLastSample() ); TestTest( 30 == avgOneSample.GetAverage() ); avgOneSample.AddSample( 5 ); TestTest( 5 == avgOneSample.GetLastSample() ); TestTest( 5 == avgOneSample.GetAverage() ); printf( "\tTwo-sample moving average...\n" ); CMovingAverage< LONG, 2 > avgTwoSamples( 100 ); TestTest( 100 == avgTwoSamples.GetLastSample() ); TestTest( 100 == avgTwoSamples.GetAverage() ); avgTwoSamples.AddSample( 50 ); TestTest( 50 == avgTwoSamples.GetLastSample() ); TestTest( 75 == avgTwoSamples.GetAverage() ); avgTwoSamples.AddSample( 10 ); TestTest( 10 == avgTwoSamples.GetLastSample() ); TestTest( 30 == avgTwoSamples.GetAverage() ); avgTwoSamples.AddSample( 60 ); TestTest( 60 == avgTwoSamples.GetLastSample() ); TestTest( 35 == avgTwoSamples.GetAverage() ); avgTwoSamples.AddSample( 80 ); TestTest( 80 == avgTwoSamples.GetLastSample() ); TestTest( 70 == avgTwoSamples.GetAverage() ); avgTwoSamples.AddSample( -30 ); TestTest( -30 == avgTwoSamples.GetLastSample() ); TestTest( 25 == avgTwoSamples.GetAverage() ); avgTwoSamples.AddSample( -10 ); TestTest( -10 == avgTwoSamples.GetLastSample() ); TestTest( -20 == avgTwoSamples.GetAverage() ); avgTwoSamples.AddSample( 110 ); TestTest( 110 == avgTwoSamples.GetLastSample() ); TestTest( 50 == avgTwoSamples.GetAverage() ); avgTwoSamples.Reset( -30 ); TestTest( -30 == avgTwoSamples.GetLastSample() ); TestTest( -30 == avgTwoSamples.GetAverage() ); avgTwoSamples.AddSample( -40 ); TestTest( -40 == avgTwoSamples.GetLastSample() ); TestTest( -35 == avgTwoSamples.GetAverage() ); avgTwoSamples.AddSample( 240 ); TestTest( 240 == avgTwoSamples.GetLastSample() ); TestTest( 100 == avgTwoSamples.GetAverage() ); avgTwoSamples.AddSample( 60 ); TestTest( 60 == avgTwoSamples.GetLastSample() ); TestTest( 150 == avgTwoSamples.GetAverage() ); printf( "\tFive-sample moving average...\n" ); CMovingAverage< INT, 5 > avgFiveSamples( -1000 ); TestTest( -1000 == avgFiveSamples.GetLastSample() ); TestTest( -1000 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 0 ); TestTest( 0 == avgFiveSamples.GetLastSample() ); TestTest( -800 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 500 ); TestTest( 500 == avgFiveSamples.GetLastSample() ); TestTest( -500 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 5000 ); TestTest( 5000 == avgFiveSamples.GetLastSample() ); TestTest( 700 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( -10000 ); TestTest( -10000 == avgFiveSamples.GetLastSample() ); TestTest( -1100 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 1000 ); TestTest( 1000 == avgFiveSamples.GetLastSample() ); TestTest( -700 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 10000 ); TestTest( 10000 == avgFiveSamples.GetLastSample() ); TestTest( 1300 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 5000 ); TestTest( 5000 == avgFiveSamples.GetLastSample() ); TestTest( 2200 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( -100000 ); TestTest( -100000 == avgFiveSamples.GetLastSample() ); TestTest( -18800 == avgFiveSamples.GetAverage() ); avgFiveSamples.Reset( -10000 ); TestTest( -10000 == avgFiveSamples.GetLastSample() ); TestTest( -10000 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 0 ); TestTest( 0 == avgFiveSamples.GetLastSample() ); TestTest( -8000 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 0 ); TestTest( 0 == avgFiveSamples.GetLastSample() ); TestTest( -6000 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 0 ); TestTest( 0 == avgFiveSamples.GetLastSample() ); TestTest( -4000 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 0 ); TestTest( 0 == avgFiveSamples.GetLastSample() ); TestTest( -2000 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 0 ); TestTest( 0 == avgFiveSamples.GetLastSample() ); TestTest( 0 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 10000 ); TestTest( 10000 == avgFiveSamples.GetLastSample() ); TestTest( 2000 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 1000 ); TestTest( 1000 == avgFiveSamples.GetLastSample() ); TestTest( 2200 == avgFiveSamples.GetAverage() ); return JET_errSuccess; }
#include "statunittest.hxx" #include "stat.hxx" class MovingAverageTest : public UNITTEST { private: static MovingAverageTest s_instance; protected: MovingAverageTest() {} public: ~MovingAverageTest() {} public: const char * SzName() const; const char * SzDescription() const; bool FRunUnderESE98() const; bool FRunUnderESENT() const; bool FRunUnderESE97() const; ERR ErrTest(); }; MovingAverageTest MovingAverageTest::s_instance; const char * MovingAverageTest::SzName() const { return "MovingAverage"; }; const char * MovingAverageTest::SzDescription() const { return "Tests the statistic libraries' moving average support."; } bool MovingAverageTest::FRunUnderESE98() const { return true; } bool MovingAverageTest::FRunUnderESENT() const { return true; } bool MovingAverageTest::FRunUnderESE97() const { return true; } ERR MovingAverageTest::ErrTest() { wprintf( L"\tTesting Moving Average support ...\n"); #define TestTest( ftest ) if ( !(ftest) ) \ { \ wprintf(L" [line=%d] Test( %S ) failed w/ %d\n", __LINE__, #ftest, (DWORD)(ftest) ); \ STATAssertSz( fFalse, "HaltTest" ); \ } printf( "\tSingle-sample moving average...\n" ); CMovingAverage< ULONG, 1 > avgOneSample( 10 ); TestTest( 10 == avgOneSample.GetLastSample() ); TestTest( 10 == avgOneSample.GetAverage() ); avgOneSample.AddSample( 12 ); TestTest( 12 == avgOneSample.GetLastSample() ); TestTest( 12 == avgOneSample.GetAverage() ); avgOneSample.AddSample( 15 ); TestTest( 15 == avgOneSample.GetLastSample() ); TestTest( 15 == avgOneSample.GetAverage() ); avgOneSample.Reset( 20 ); TestTest( 20 == avgOneSample.GetLastSample() ); TestTest( 20 == avgOneSample.GetAverage() ); avgOneSample.AddSample( 30 ); TestTest( 30 == avgOneSample.GetLastSample() ); TestTest( 30 == avgOneSample.GetAverage() ); avgOneSample.AddSample( 5 ); TestTest( 5 == avgOneSample.GetLastSample() ); TestTest( 5 == avgOneSample.GetAverage() ); printf( "\tTwo-sample moving average...\n" ); CMovingAverage< LONG, 2 > avgTwoSamples( 100 ); TestTest( 100 == avgTwoSamples.GetLastSample() ); TestTest( 100 == avgTwoSamples.GetAverage() ); avgTwoSamples.AddSample( 50 ); TestTest( 50 == avgTwoSamples.GetLastSample() ); TestTest( 75 == avgTwoSamples.GetAverag
e() ); avgTwoSamples.AddSample( 10 ); TestTest( 10 == avgTwoSamples.GetLastSample() ); TestTest( 30 == avgTwoSamples.GetAverage() ); avgTwoSamples.AddSample( 60 ); TestTest( 60 == avgTwoSamples.GetLastSample() ); TestTest( 35 == avgTwoSamples.GetAverage() ); avgTwoSamples.AddSample( 80 ); TestTest( 80 == avgTwoSamples.GetLastSample() ); TestTest( 70 == avgTwoSamples.GetAverage() ); avgTwoSamples.AddSample( -30 ); TestTest( -30 == avgTwoSamples.GetLastSample() ); TestTest( 25 == avgTwoSamples.GetAverage() ); avgTwoSamples.AddSample( -10 ); TestTest( -10 == avgTwoSamples.GetLastSample() ); TestTest( -20 == avgTwoSamples.GetAverage() ); avgTwoSamples.AddSample( 110 ); TestTest( 110 == avgTwoSamples.GetLastSample() ); TestTest( 50 == avgTwoSamples.GetAverage() ); avgTwoSamples.Reset( -30 ); TestTest( -30 == avgTwoSamples.GetLastSample() ); TestTest( -30 == avgTwoSamples.GetAverage() ); avgTwoSamples.AddSample( -40 ); TestTest( -40 == avgTwoSamples.GetLastSample() ); TestTest( -35 == avgTwoSamples.GetAverage() ); avgTwoSamples.AddSample( 240 ); TestTest( 240 == avgTwoSamples.GetLastSample() ); TestTest( 100 == avgTwoSamples.GetAverage() ); avgTwoSamples.AddSample( 60 ); TestTest( 60 == avgTwoSamples.GetLastSample() ); TestTest( 150 == avgTwoSamples.GetAverage() ); printf( "\tFive-sample moving average...\n" ); CMovingAverage< INT, 5 > avgFiveSamples( -1000 ); TestTest( -1000 == avgFiveSamples.GetLastSample() ); TestTest( -1000 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 0 ); TestTest( 0 == avgFiveSamples.GetLastSample() ); TestTest( -800 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 500 ); TestTest( 500 == avgFiveSamples.GetLastSample() ); TestTest( -500 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 5000 ); TestTest( 5000 == avgFiveSamples.GetLastSample() ); TestTest( 700 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( -10000 ); TestTest( -10000 == avgFiveSamples.GetLastSample() ); TestTest( -1100 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 1000 ); TestTest( 1000 == avgFiveSamples.GetLastSample() ); TestTest( -700 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 10000 ); TestTest( 10000 == avgFiveSamples.GetLastSample() ); TestTest( 1300 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 5000 ); TestTest( 5000 == avgFiveSamples.GetLastSample() ); TestTest( 2200 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( -100000 ); TestTest( -100000 == avgFiveSamples.GetLastSample() ); TestTest( -18800 == avgFiveSamples.GetAverage() ); avgFiveSamples.Reset( -10000 ); TestTest( -10000 == avgFiveSamples.GetLastSample() ); TestTest( -10000 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 0 ); TestTest( 0 == avgFiveSamples.GetLastSample() ); TestTest( -8000 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 0 ); TestTest( 0 == avgFiveSamples.GetLastSample() ); TestTest( -6000 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 0 ); TestTest( 0 == avgFiveSamples.GetLastSample() ); TestTest( -4000 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 0 ); TestTest( 0 == avgFiveSamples.GetLastSample() ); TestTest( -2000 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 0 ); TestTest( 0 == avgFiveSamples.GetLastSample() ); TestTest( 0 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 10000 ); TestTest( 10000 == avgFiveSamples.GetLastSample() ); TestTest( 2000 == avgFiveSamples.GetAverage() ); avgFiveSamples.AddSample( 1000 ); TestTest( 1000 == avgFiveSamples.GetLastSample() ); TestTest( 2200 == avgFiveSamples.GetAverage() ); return JET_errSuccess; }
function_block-function_prefixed
[]
C++
app/DiskFSTree.cpp
Toysoft/ciderpress
640959dad551ba75a48bd3c49629579730ead351
#include "StdAfx.h" #include "DiskFSTree.h" #include "ChooseAddTargetDialog.h" #include "../reformat/Charset.h" using namespace DiskImgLib; bool DiskFSTree::BuildTree(DiskFS* pDiskFS, CTreeCtrl* pTree) { ASSERT(pDiskFS != NULL); ASSERT(pTree != NULL); pTree->SetImageList(&fTreeImageList, TVSIL_NORMAL); return AddDiskFS(pTree, TVI_ROOT, pDiskFS, 1); } bool DiskFSTree::AddDiskFS(CTreeCtrl* pTree, HTREEITEM parent, DiskImgLib::DiskFS* pDiskFS, int depth) { const DiskFS::SubVolume* pSubVol; TargetData* pTarget; HTREEITEM hLocalRoot; TVITEM tvi; TVINSERTSTRUCT tvins; pTarget = AllocTargetData(); pTarget->kind = kTargetDiskFS; pTarget->pDiskFS = pDiskFS; pTarget->pFile = NULL; tvi.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM; CString volumeId(Charset::ConvertMORToUNI(pDiskFS->GetVolumeID())); int index = fStringHolder.Add(volumeId); tvi.pszText = (LPWSTR)(LPCWSTR) fStringHolder.GetAt(index); tvi.cchTextMax = 0; if (pDiskFS->GetReadWriteSupported() && !pDiskFS->GetFSDamaged()) { tvi.iImage = kTreeImageHardDriveRW; pTarget->selectable = true; } else { tvi.iImage = kTreeImageHardDriveRO; pTarget->selectable = false; } tvi.iSelectedImage = tvi.iImage; tvi.lParam = (LPARAM) pTarget; tvins.item = tvi; tvins.hInsertAfter = parent; tvins.hParent = parent; hLocalRoot = pTree->InsertItem(&tvins); if (hLocalRoot == NULL) { LOGW("Tree root InsertItem failed"); return false; } pSubVol = pDiskFS->GetNextSubVolume(NULL); while (pSubVol != NULL) { if (!AddDiskFS(pTree, hLocalRoot, pSubVol->GetDiskFS(), depth+1)) return false; pSubVol = pDiskFS->GetNextSubVolume(pSubVol); } if (fIncludeSubdirs && pDiskFS->GetReadWriteSupported() && !pDiskFS->GetFSDamaged()) { AddSubdir(pTree, hLocalRoot, pDiskFS, NULL, depth); } if (fExpandDepth == -1 || depth <= fExpandDepth) pTree->Expand(hLocalRoot, TVE_EXPAND); if (parent == TVI_ROOT) { pTree->Select(hLocalRoot, TVGN_CARET); } return true; } DiskImgLib::A2File* DiskFSTree::AddSubdir(CTreeCtrl* pTree, HTREEITEM parent, DiskImgLib::DiskFS* pDiskFS, DiskImgLib::A2File* pParentFile, int depth) { A2File* pFile; TargetData* pTarget; HTREEITEM hLocalRoot; TVITEM tvi; TVINSERTSTRUCT tvins; pFile = pDiskFS->GetNextFile(pParentFile); if (pFile == NULL && pParentFile == NULL) { return NULL; } if (pParentFile == NULL) { if (pFile->IsVolumeDirectory()) { pParentFile = pFile; pFile = pDiskFS->GetNextFile(pFile); } hLocalRoot = parent; } else { pTarget = AllocTargetData(); pTarget->kind = kTargetSubdir; pTarget->selectable = true; pTarget->pDiskFS = pDiskFS; pTarget->pFile = pParentFile; tvi.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM; CString fileNameW(pParentFile->GetFileName()); int index = fStringHolder.Add(fileNameW); tvi.pszText = (LPWSTR)(LPCWSTR) fStringHolder.GetAt(index); tvi.cchTextMax = 0; tvi.iImage = kTreeImageFolderClosed; tvi.iSelectedImage = kTreeImageFolderOpen; tvi.lParam = (LPARAM) pTarget; tvins.item = tvi; tvins.hInsertAfter = parent; tvins.hParent = parent; hLocalRoot = pTree->InsertItem(&tvins); if (hLocalRoot == NULL) { LOGW("Tree insert '%ls' failed", tvi.pszText); return NULL; } } while (pFile != NULL) { if (pFile->IsDirectory()) { ASSERT(!pFile->IsVolumeDirectory()); if (pFile->GetParent() == pParentFile) { pFile = AddSubdir(pTree, hLocalRoot, pDiskFS, pFile, depth+1); if (pFile == NULL) break; } else { break; } } else { pFile = pDiskFS->GetNextFile(pFile); } } if (fExpandDepth == -1 || depth <= fExpandDepth) pTree->Expand(hLocalRoot, TVE_EXPAND); return pFile; } DiskFSTree::TargetData* DiskFSTree::AllocTargetData(void) { TargetData* pNew = new TargetData; if (pNew == NULL) return NULL; pNew->pNext = fpTargetData; fpTargetData = pNew; return pNew; } void DiskFSTree::FreeAllTargetData(void) { TargetData* pTarget; TargetData* pNext; pTarget = fpTargetData; while (pTarget != NULL) { pNext = pTarget->pNext; delete pTarget; pTarget = pNext; } fpTargetData = NULL; }
#include "StdAfx.h" #include "DiskFSTree.h" #include "ChooseAddTargetDialog.h" #include "../reformat/Charset.h" using namespace DiskImgLib; bool DiskFSTree::BuildTree(DiskFS* pDiskFS, CTreeCtrl* pTree) { ASSERT(pDiskFS != NULL); ASSERT(pTree != NULL); pTree->SetImageList(&fTreeImageList, TVSIL_NORMAL); return AddDiskFS(pTree, TVI_ROOT, pDiskFS, 1); } bool DiskFSTree::AddDiskFS(CTreeCtrl* pTree, HTREEITEM parent, DiskImgLib::DiskFS* pDiskFS, int depth) { const DiskFS::SubVolume* pSubVol; TargetData* pTarget; HTREEITEM hLocalRoot; TVITEM tvi; TVINSERTSTRUCT tvins; pTarget = AllocTargetData(); pTarget->kind = kTargetDiskFS; pTarget->pDiskFS = pDiskFS; pTarget->pFile = NULL; tvi.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM; CString volumeId(Charset::ConvertMORToUNI(pDiskFS->GetVolumeID())); int index = fStringHolder.Add(volumeId); tvi.pszText = (LPWSTR)(LPCWSTR) fStringHolder.GetAt(index); tvi.cchTextMax = 0; if (pDiskFS->GetReadWriteSupported() && !pDiskFS->GetFSDamaged()) { tvi.iImage = kTreeImageHardDriveRW; pTarget->selectable = true; } else { tvi.iImage = kTreeImageHardDriveRO; pTarget->selectable = false; } tvi.iSelectedImage = tvi.iImage; tvi.lParam = (LPARAM) pTarget; tvins.item = tvi; tvins.hInsertAfter = parent; tvins.hParent = parent; hLocalRoot = pTree->InsertItem(&tvins); if (hLocalRoot == NULL) { LOGW("Tree root InsertItem failed"); return false; } pSubVol = pDiskFS->GetNextSubVolume(NULL); while (pSubVol != NULL) { if (!AddDiskFS(pTree, hLocalRoot, pSubVol->GetDiskFS(), depth+1)) return false; pSubVol = pDiskFS->GetNextSubVolume(pSubVol); } if (fIncludeSubdirs && pDiskFS->GetReadWriteSupported() && !pDiskFS->GetFSDamaged()) { AddSubdir(pTree, hLocalRoot, pDiskFS, NULL, depth); } if (fExpandDepth == -1 || depth <= fExpandDepth) pTree->Expand(hLocalRoot, TVE_EXPAND); if (parent == TVI_ROOT) { pTree->Select(hLocalRoot, TVGN_CARET); } return true; } DiskImgLib::A2File* DiskFSTree::AddSubdir(CTreeCtrl* pTree, HTREEITEM parent, DiskImgLib::DiskFS* pDiskFS, DiskImgLib::A2File* pParentFile, int depth) { A2File* pFile; TargetData* pTarget; HTREEITEM hLocalRoot; TVITEM tvi; TVINSERTSTRUCT tvins; pFile = pDiskFS->GetNextFile(pParentFile); if (pFile == NULL && pParentFile == NULL) { return NULL; } if (pParentFile == NULL) { if (pFile->IsVolumeDirectory()) { pParentFile = pFile; pFile = pDiskFS->GetNextFile(pFile); } hLocalRoot = parent; } else { pTarget = AllocTargetData(); pTarget->kind = kTargetSubdir; pTarget->selectable = true; pTarget->pDiskFS = pDiskFS; pTarget->pFile = pParentFile; tvi.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM; CString fileNameW(pParentFile->GetFileName()); int index = fStringHolder.Add(fileNameW); tvi.pszText = (LPWSTR)(LPCWSTR) fStringHolder.GetAt(index); tvi.cchTextMax = 0; tvi.iImage = kTreeImageFolderClosed; tvi.iSelectedImage = kTreeImageFolderOpen; tvi.lParam = (LPARAM) pTarget; tvins.item = tvi; tvins.hInsertAfter = parent; tvins.hParent = parent; hLocalRoot = pTree->InsertItem(&tvins); if (hLocalRoot == NULL) { LOGW("Tree insert '%ls' failed", tvi.pszText); return NULL; } } while (pFile != NULL) { if (pFile->IsDirectory()) { ASSERT(!pFile->IsVolumeDirectory()); if (pFile->GetParent() == pParentFile) { pFile = AddSubdir(pTree, hLocalRoot, pDiskFS, pFile, depth+1); if (pFile == NULL) break; } else { break; } } else { pFile = pDiskFS->GetNextFile(pFile); } } if (fExpandDepth == -1 || depth <= fExpandDepth) pTree->Expand(hLocalRoot, TVE_EXPAND); return pFile; }
void DiskFSTree::FreeAllTargetData(void) { TargetData* pTarget; TargetData* pNext; pTarget = fpTargetData; while (pTarget != NULL) { pNext = pTarget->pNext; delete pTarget; pTarget = pNext; } fpTargetData = NULL; }
DiskFSTree::TargetData* DiskFSTree::AllocTargetData(void) { TargetData* pNew = new TargetData; if (pNew == NULL) return NULL; pNew->pNext = fpTargetData; fpTargetData = pNew; return pNew; }
function_block-full_function
[ { "content": " uch depth[2*L_CODES+1];\n", "file_path": "zlib/deflate.h", "rank": 0, "score": 93639.98853513303 }, { "content": " uInt insert; /* bytes at end of window left to insert */\n", "file_path": "zlib/deflate.h", "rank": 1, "score": 93630.98532131276 }, ...
C++
include/dll/datasets/imagenet.hpp
jw-j/dll
2a72ec0a5c8d52de5565eb5075bc44f078955fca
#pragma once #include <vector> #include <unordered_map> #include <utility> #include <string> #include <dirent.h> #include <opencv2/highgui/highgui.hpp> namespace dll { namespace imagenet { inline void read_files(std::vector<std::pair<size_t, size_t>>& files, std::unordered_map<size_t, float>& label_map, const std::string& file_path){ files.reserve(1200000); struct dirent* entry; auto dir = opendir(file_path.c_str()); while ((entry = readdir(dir))) { std::string file_name(entry->d_name); if (file_name.find("n") != 0) { continue; } std::string label_name(file_name.begin() + 1, file_name.end()); size_t label = std::atoi(label_name.c_str()); auto l = label_map.size(); label_map[label] = l; struct dirent* sub_entry; auto sub_dir = opendir((file_path + "/" + file_name).c_str()); while ((sub_entry = readdir(sub_dir))) { std::string image_name(sub_entry->d_name); if (image_name.find("n") != 0){ continue; } std::string image_number(image_name.begin() + image_name.find('_') + 1, image_name.end() - 5); size_t image = std::atoi(image_number.c_str()); files.emplace_back(label, image); } } } struct image_iterator : std::iterator< std::input_iterator_tag, etl::fast_dyn_matrix<float, 3, 256, 256>, ptrdiff_t, etl::fast_dyn_matrix<float, 3, 256, 256>*, etl::fast_dyn_matrix<float, 3, 256, 256>& > { using value_type = etl::fast_dyn_matrix<float, 3, 256, 256>; std::string imagenet_path; std::shared_ptr<std::vector<std::pair<size_t, size_t>>> files; std::shared_ptr<std::unordered_map<size_t, float>> labels; size_t index; image_iterator(const std::string& imagenet_path, std::shared_ptr<std::vector<std::pair<size_t, size_t>>> files, std::shared_ptr<std::unordered_map<size_t, float>> labels, size_t index) : imagenet_path(imagenet_path), files(files), labels(labels), index(index) { } image_iterator(image_iterator&& rhs) = default; image_iterator(const image_iterator& rhs) = default; image_iterator& operator=(image_iterator&& rhs) = default; image_iterator& operator=(const image_iterator& rhs) = default; image_iterator& operator++(){ ++index; return *this; } image_iterator operator++(int){ cpp_unreachable("Should never be called"); return *this; } value_type operator*() { auto& image_file = (*files)[index]; auto label = std::string("/n") + (image_file.first < 10000000 ? "0" : "") + std::to_string(image_file.first); auto image_path = std::string(imagenet_path) + "/train" + label + label + "_" + std::to_string(image_file.second) + ".JPEG"; auto mat = cv::imread(image_path.c_str(), cv::IMREAD_ANYCOLOR | cv::IMREAD_ANYDEPTH); value_type image; if (!mat.data || mat.empty()) { std::cerr << "ERROR: Failed to read image: " << image_path << std::endl; image = 0; return image; } if (mat.cols != 256 || mat.rows != 256) { std::cerr << "ERROR: Image of invalid size: " << image_path << std::endl; image = 0; return image; } if (cpp_likely(mat.channels() == 3)) { for (size_t x = 0; x < 256; ++x) { for (size_t y = 0; y < 256; ++y) { auto pixel = mat.at<cv::Vec3b>(y, x); image(0, x, y) = pixel.val[0]; image(1, x, y) = pixel.val[1]; image(2, x, y) = pixel.val[2]; } } } else { for (size_t x = 0; x < 256; ++x) { for (size_t y = 0; y < 256; ++y) { image(0, x, y) = mat.at<unsigned char>(y, x); } } image(1) = 0; image(2) = 0; } return image; } bool operator==(const image_iterator& rhs) const { return index == rhs.index; } bool operator!=(const image_iterator& rhs) const { return index != rhs.index; } }; struct label_iterator : std::iterator< std::input_iterator_tag, float, ptrdiff_t, float*, float& > { std::shared_ptr<std::vector<std::pair<size_t, size_t>>> files; std::shared_ptr<std::unordered_map<size_t, float>> labels; size_t index; label_iterator(std::shared_ptr<std::vector<std::pair<size_t, size_t>>> files, std::shared_ptr<std::unordered_map<size_t, float>> labels, size_t index) : files(files), labels(labels), index(index) { } label_iterator(const label_iterator& rhs) = default; label_iterator(label_iterator&& rhs) = default; label_iterator& operator=(const label_iterator& rhs) = default; label_iterator& operator=(label_iterator&& rhs) = default; label_iterator& operator++(){ ++index; return *this; } label_iterator operator++(int){ auto it = *this; ++index; return it; } float operator*() const { return (*labels)[(*files)[index].first]; } bool operator==(const label_iterator& rhs) const { return index == rhs.index; } bool operator!=(const label_iterator& rhs) const { return index != rhs.index; } }; } template<typename... Parameters> auto make_imagenet_dataset(const std::string& folder, Parameters&&... ){ auto train_files = std::make_shared<std::vector<std::pair<size_t, size_t>>>(); auto labels = std::make_shared<std::unordered_map<size_t, float>>(); imagenet::read_files(*train_files, *labels, std::string(folder) + "train"); std::random_device rd; std::default_random_engine engine(rd()); std::shuffle(train_files->begin(), train_files->end(), engine); imagenet::image_iterator iit(folder, train_files, labels, 0); imagenet::image_iterator iend(folder, train_files, labels, train_files->size()); imagenet::label_iterator lit(train_files, labels, 0); imagenet::label_iterator lend(train_files, labels, train_files->size()); return make_dataset_holder( make_generator(iit, iend, lit, lend, train_files->size(), 1000, dll::outmemory_data_generator_desc<Parameters..., dll::categorical>{}), make_generator(iit, iend, lit, lend, train_files->size(), 1000, dll::outmemory_data_generator_desc<Parameters..., dll::categorical>{})); } }
#pragma once #include <vector> #include <unordered_map> #include <utility> #include <string> #include <dirent.h> #include <opencv2/highgui/highgui.hpp> namespace dll { namespace imagenet { inline void read_files(std::vector<std::pair<size_t, size_t>>& files, std::unordered_map<size_t, float>& label_map, const std::string& file_path){ files.reserve(1200000); struct dirent* entry; auto dir = opendir(file_path.c_str()); while ((entry = readdir(dir))) { std::string file_name(entry->d_name); if (file_name.find("n") != 0) { continue; } std::string label_name(file_name.begin() + 1, file_name.end()); size_t label = std::atoi(label_name.c_str()); auto l = label_map.size(); label_map[label] = l; struct dirent* sub_entry; auto sub_dir = opendir((file_path + "/" + file_name).c_str()); while ((sub_entry = readdir(sub_dir))) { std::string image_name(sub_entry->d_name); if (image_name.find("n") != 0){ continue; } std::string image_number(image_name.begin() + image_name.find('_') + 1, image_name.end() - 5); size_t image = std::atoi(image_number.c_str()); files.emplace_back(label, image); } } } struct image_iterator : std::iterator< std::input_iterator_tag, etl::fast_dyn_matrix<float, 3, 256, 256>, ptrdiff_t, etl::fast_dyn_matrix<float, 3, 256, 256>*, etl::fast_dyn_matrix<float, 3, 256, 256>& > { using value_type = etl::fast_dyn_matrix<float, 3, 256, 256>; std::string imagenet_path; std::shared_ptr<std::vector<std::pair<size_t, size_t>>> files; std::shared_ptr<std::unordered_map<size_t, float>> labels; size_t index; image_iterator(const std::string& imagenet_path, std::shared_ptr<std::vector<std::pair<size_t, size_t>>> files, std::shared_ptr<std::unordered_map<size_t, float>> labels, size_t index) : imagenet_path(imagenet_path), files(files), labels(labels), index(index) { } image_iterator(image_iterator&& rhs) = default; image_iterator(const image_iterator& rhs) = default; image_iterator& operator=(image_iterator&& rhs) = default; image_iterator& operator=(const image_iterator& rhs) = default; image_iterator& operator++(){ ++index; return *this; } image_iterator operator++(int){ cpp_unreachable("Should never be called"); return *this; } value_type operator*() { auto& image_file = (*files)[index]; auto label = std::string("/n") + (image_file.first < 10000000 ? "0" : "") + std::to_string(image_file.first); auto image_path = std::string(imagenet_path) + "/train" + label + label + "_" + std::to_string(image_file.second) + ".JPEG"; auto mat = cv::imread(image_path.c_str(), cv::IMREAD_ANYCOLOR | cv::IMREAD_ANYDEPTH); value_type image; if (!mat.data || mat.empty()) { std::cerr << "ERROR: Failed to read image: " << image_path << std::endl; image = 0; return image; } if (mat.cols != 256 || mat.rows != 256) { std::cerr << "ERROR: Image of invalid size: " << image_path << std::endl; image = 0; return image; } if (cpp_likely(mat.channels() == 3)) { for (size_t x = 0; x < 256; ++x) { for (size_t y = 0; y < 256; ++y) { auto pixel = mat.at<cv::Vec3b>(y, x); image(0, x, y) = pixel.val[0]; image(1, x, y) = pixel.val[1]; image(2, x, y) = pixel.val[2]; } } } else { for (size_t x = 0; x < 256; ++x) { for (size_t y = 0; y < 256; ++y) { image(0, x, y) = mat.at<unsigned char>(y, x); } } image(1) = 0; image(2) = 0; } return image; } bool operator==(const image_iterator& rhs) const { return index == rhs.index; } bool operator!=(const image_iterator& rhs) const { return index != rhs.index; } }; struct label_iterator : std::iterator< std::input_iterator_tag, float, ptrdiff_t, float*, float& > { std::shared_ptr<std::vector<std::pair<size_t, size_t>>> files; std::shared_ptr<std::unordered_map<size_t, float>> labels; size_t index; label_iterator(std::shared_ptr<std::vector<std::pair<size_t, size_t>>> files, s
l_iterator&& rhs) = default; label_iterator& operator++(){ ++index; return *this; } label_iterator operator++(int){ auto it = *this; ++index; return it; } float operator*() const { return (*labels)[(*files)[index].first]; } bool operator==(const label_iterator& rhs) const { return index == rhs.index; } bool operator!=(const label_iterator& rhs) const { return index != rhs.index; } }; } template<typename... Parameters> auto make_imagenet_dataset(const std::string& folder, Parameters&&... ){ auto train_files = std::make_shared<std::vector<std::pair<size_t, size_t>>>(); auto labels = std::make_shared<std::unordered_map<size_t, float>>(); imagenet::read_files(*train_files, *labels, std::string(folder) + "train"); std::random_device rd; std::default_random_engine engine(rd()); std::shuffle(train_files->begin(), train_files->end(), engine); imagenet::image_iterator iit(folder, train_files, labels, 0); imagenet::image_iterator iend(folder, train_files, labels, train_files->size()); imagenet::label_iterator lit(train_files, labels, 0); imagenet::label_iterator lend(train_files, labels, train_files->size()); return make_dataset_holder( make_generator(iit, iend, lit, lend, train_files->size(), 1000, dll::outmemory_data_generator_desc<Parameters..., dll::categorical>{}), make_generator(iit, iend, lit, lend, train_files->size(), 1000, dll::outmemory_data_generator_desc<Parameters..., dll::categorical>{})); } }
td::shared_ptr<std::unordered_map<size_t, float>> labels, size_t index) : files(files), labels(labels), index(index) { } label_iterator(const label_iterator& rhs) = default; label_iterator(label_iterator&& rhs) = default; label_iterator& operator=(const label_iterator& rhs) = default; label_iterator& operator=(labe
random
[ { "content": "struct random_crop : value_pair_conf_elt<random_crop_id, size_t, X, Y> {};\n\n\n\n/*!\n\n * \\brief Elastic distortion\n\n */\n\ntemplate <size_t C, size_t K = 9>\n", "file_path": "include/dll/base_conf.hpp", "rank": 0, "score": 284440.7828568713 }, { "content": "struct convert...
C++
torch/csrc/jit/testing/module_differ.cpp
aaditya-panik/pytorch
731c8255b7e8ed5435bfa09c7e0ad5f60bcc91d4
#include <torch/csrc/jit/testing/module_differ.h> #include <torch/csrc/jit/mobile/interpreter.h> #include <iostream> #include <sstream> #include <string> #include <unordered_map> #include <vector> namespace torch { namespace jit { template <typename It> bool ivalueListEquals( It lbegin, It lend, It rbegin, It rend, bool print, int print_indent) { int i = 0; const std::string indent(print_indent, '\t'); for (; lbegin != lend && rbegin != rend; ++lbegin, ++rbegin, ++i) { if (!ivalueEquals(*lbegin, *rbegin, print, print_indent + 1)) { std::cout << indent << "list element differs at position " << i << std::endl; return false; } } return true; } bool ivalueEquals( const IValue& lhs, const IValue& rhs, bool print, int print_indent) { const std::string indent(print_indent, '\t'); if (lhs.tagKind() != rhs.tagKind()) { if (print) { std::cout << indent << "lhs is type: " << lhs.tagKind() << "rhs is type: " << rhs.tagKind() << std::endl; } return false; } if (lhs.isCapsule()) { return true; } if (lhs.isDouble() || lhs.isComplexDouble() || lhs.isInt() || lhs.isBool() || lhs.isString() || lhs.isDevice() || lhs.isCapsule() || lhs.isRRef() || lhs.isEnum() || lhs.isIntList() || lhs.isDoubleList() || lhs.isBoolList() || lhs.isNone()) { if (lhs != rhs) { if (print) { std::cout << indent << "lhs is " << lhs << " || rhs is " << rhs << std::endl; } return false; } return true; } if (lhs.isTensor()) { const auto& lt = lhs.toTensor(); const auto& rt = rhs.toTensor(); std::stringstream lsize; std::stringstream rsize; for (const auto x : lt.sizes()) { lsize << x << ","; } for (const auto x : rt.sizes()) { rsize << x << ","; } if (lsize.str() != lsize.str()) { if (print) { std::cout << indent << "left tensor is of shape " << lsize.str() << "but right tensor is of shape " << rsize.str() << std::endl; } return false; } if (lt.allclose(rt)) { return true; } else { if (print) { std::cout << indent << "rhs and lhs has are not close" << std::endl; } return false; } } if (lhs.isGenericDict()) { const auto& ldict = lhs.toGenericDict(); const auto& rdict = rhs.toGenericDict(); if (ldict.size() != rdict.size()) { if (print) { std::cout << indent << "lhs and rhs are dicts of different sizes: " << ldict.size() << " vs. " << rdict.size() << std::endl; } return false; } for (const auto& kv : ldict) { auto rhs_iter = rdict.find(kv.key()); if (rhs_iter == rdict.end()) { if (print) { std::cout << indent << "rhs missing key: " << kv.key() << std::endl; } } if (!ivalueEquals( kv.value(), rhs_iter->value(), print, print_indent + 1)) { if (print) { std::cout << indent << "for key: " << kv.key() << " value differs." << std::endl; } return false; } } return true; } else if (lhs.isTensorList() || lhs.isList()) { const auto& vec = lhs.toList(); const auto& rvec = rhs.toList(); return ivalueListEquals( vec.begin(), vec.end(), rvec.begin(), rvec.end(), print, print_indent); } else if (lhs.isTuple()) { const auto vec = lhs.toTuple()->elements(); const auto rvec = rhs.toTuple()->elements(); return ivalueListEquals( vec.begin(), vec.end(), rvec.begin(), rvec.end(), print, print_indent); } else if (lhs.isObject()) { auto lobj = lhs.toObject(); auto robj = rhs.toObject(); auto ltype = lobj->type(); auto rtype = robj->type(); if (ltype->name() != rtype->name()) { if (print) { std::cerr << indent << "left object is of type: " << ltype->name()->qualifiedName() << " but right obj is of type: " << rtype->name()->qualifiedName() << std::endl; } return false; } auto getstate = ltype->findMethod("__getstate__"); if (getstate != nullptr) { return ivalueEquals( (*getstate)({lobj}), (*getstate)({robj}), print, print_indent + 1); } for (int i = 0; i < ltype->numAttributes(); i++) { if (!ivalueEquals( lobj->getSlot(i), robj->getSlot(i), print, print_indent + 1)) { std::cout << "attribute differs at position " << i << std::endl; return false; } } return true; } std::cerr << " I am here and should not be: " << rhs.tagKind() << std::endl; return false; } template <typename T, typename COMP, typename PRINTER> bool vectorEqual( const std::vector<T>& lhs, const std::vector<T>& rhs, bool print, COMP comparator, PRINTER printer) { if (lhs.size() != rhs.size()) { if (print) { std::cout << "lhs and rhs has different size: " << lhs.size() << "vs. " << rhs.size() << std::endl; } return false; } for (int i = 0; i < lhs.size(); i++) { if (!comparator(lhs[i], rhs[i])) { if (print) { std::cout << i << "th element of lhs and rhs differs \n lhs is " << printer(lhs[i]) << " rhs is " << printer(rhs[i]) << std::endl; } return false; } } return true; } bool moduleFunctionEquals( const mobile::Function& lhs, const mobile::Function& rhs, bool print) { const auto* lhs_code = lhs.get_code().get(); const auto* rhs_code = rhs.get_code().get(); if (print) { std::cout << "> Diffing instructions..." << std::endl; } auto ins_equal = [](Instruction lins, Instruction rins) -> bool { return (lins.op == rins.op && lins.N == rins.N && lins.X == rins.X); }; auto id = [](auto ins) { return ins; }; if (vectorEqual( lhs_code->instructions_, rhs_code->instructions_, true, ins_equal, id)) { std::cout << " pass." << std::endl; } else { std::cout << " fail." << std::endl; return false; } if (print) { std::cout << "> Diffing constants..." << std::endl; } if (ivalueListEquals( lhs_code->constants_.begin(), lhs_code->constants_.end(), rhs_code->constants_.begin(), rhs_code->constants_.end(), true, 2)) { std::cout << " pass" << std::endl; } else { std::cout << " fail" << std::endl; return false; } if (print) { std::cout << "> Diffing operators ..." << std::endl; } auto equals = [](auto op1, auto op2) -> bool { return op1 == op2; }; if (vectorEqual(lhs_code->op_names_, rhs_code->op_names_, true, equals, id)) { std::cout << " pass." << std::endl; } else { std::cout << " fail." << std::endl; return false; } if (lhs_code->register_size_ != rhs_code->register_size_) { std::cout << "Register size differs: " << lhs_code->register_size_ << " vs. " << rhs_code->register_size_ << std::endl; return false; } if (print) { std::cout << "> Diffing debug handles..." << std::endl; } if (vectorEqual( lhs_code->debug_handles_, rhs_code->debug_handles_, true, equals, id)) { std::cout << " pass." << std::endl; } else { std::cout << " fail." << std::endl; return false; } auto type_eq = [](auto t1, auto t2) { return t1->str() == t2->str(); }; auto type_print = [](auto t1) { return t1->str(); }; if (print) { std::cout << "> Diffing types..." << std::endl; } if (vectorEqual( lhs_code->types_, rhs_code->types_, true, type_eq, type_print)) { std::cout << " pass." << std::endl; } else { std::cout << " fail." << std::endl; return false; } if (print) { std::cout << "> Diffing schema..." << std::endl; } if (toString(lhs.getSchema()) == toString(rhs.getSchema())) { std::cout << " pass." << std::endl; } else { std::cout << " lhs is " << lhs.getSchema() << std::endl; std::cout << " rhs is " << rhs.getSchema() << std::endl; std::cout << " fail." << std::endl; return false; } return true; } bool moduleEquals(const mobile::Module& lhs, const mobile::Module& rhs) { std::unordered_map<std::string, const mobile::Function*> lhs_name_to_func; std::unordered_map<std::string, const mobile::Function*> rhs_name_to_func; for (const auto& func : lhs.compilation_unit().methods()) { lhs_name_to_func[func->name()] = func.get(); } for (const auto& func : rhs.compilation_unit().methods()) { rhs_name_to_func[func->name()] = func.get(); } for (const auto& name_func : lhs_name_to_func) { auto rhs_func = rhs_name_to_func.find(name_func.first); if (rhs_func == rhs_name_to_func.end()) { std::cout << "Method with name: " << name_func.first << " only exists in lhs"; } std::cout << "comparing method with name " << name_func.first << std::endl; if (moduleFunctionEquals(*name_func.second, *rhs_func->second, true)) { std::cout << "pass" << std::endl; } else { std::cout << "fail" << std::endl; return false; } } std::cout << "Diffing m._ivalue()..." << std::endl; if (ivalueEquals(lhs._ivalue(), rhs._ivalue(), true, 0)) { std::cout << " pass." << std::endl; } else { std::cout << " fail." << std::endl; return false; } return true; } } }
#include <torch/csrc/jit/testing/module_differ.h> #include <torch/csrc/jit/mobile/interpreter.h> #include <iostream> #include <sstream> #include <string> #include <unordered_map> #include <vector> namespace torch { namespace jit { template <typename It> bool ivalueListEquals( It lbegin, It lend, It rbegin, It rend, bool print, int print_indent) { int i = 0; const std::string indent(print_indent, '\t'); for (; lbegin != lend && rbegin != rend; ++lbegin, ++rbegin, ++i) { if (!ivalueEquals(*lbegin, *rbegin, print, print_indent + 1)) { std::cout << indent << "list element differs at position " << i << std::endl; return false; } } return true; } bool ivalueEquals( const IValue& lhs, const IValue& rhs, bool print, int print_indent) { const std::string indent(print_indent, '\t'); if (lhs.tagKind() != rhs.tagKind()) { if (print) { std::cout << indent << "lhs is type: " << lhs.tagKind() << "rhs is type: " << rhs.tagKind() << std::endl; } return false; } if (lhs.isCapsule()) { return true; } if (lhs.isDouble() || lhs.isComplexDouble() || lhs.isInt() || lhs.isBool() || lhs.isString() || lhs.isDevice() || lhs.isCapsule() || lhs.isRRef() || lhs.isEnum() || lhs.isIntList() || lhs.isDoubleList() || lhs.isBoolList() || lhs.isNone()) { if (lhs != rhs) { if (print) { std::cout << indent << "lhs is " << lhs << " || rhs is " << rhs << std::endl; } return false; } return true; } if (lhs.isTensor()) { const auto& lt = lhs.toTensor(); const auto& rt = rhs.toTensor(); std::stringstream lsize; std::stringstream rsize; for (const auto x : lt.sizes()) { lsize << x << ","; } for (const auto x : rt.sizes()) { rsize << x << ","; } if (lsize.str() != lsize.str()) { if (print) { std::cout << indent << "left tensor is of shape " << lsize.str() << "but right tensor is of shape " << rsize.str() << std::endl; } return false; } if (lt.allclose(rt)) { return true; } else { if (print) { std::cout << indent << "rhs and lhs has are not close" << std::endl; } return false; } } if (lhs.isGenericDict()) { const auto& ldict = lhs.toGenericDict(); const auto& rdict = rhs.toGenericDict(); if (ldict.size() != rdict.size()) { if (print) { std::cout << indent << "lhs and rhs are dicts of different sizes: " << ldict.size() << " vs. " << rdict.size() << std::endl; } return false; } for (const auto& kv : ldict) { auto rhs_iter = rdict.find(kv.key()); if (rhs_iter == rdict.end()) { if (print) { std::cout << indent << "rhs missing key: " << kv.key() << std::endl; } } if (!ivalueEquals( kv.value(), rhs_iter->value(), print, print_indent + 1)) { if (print) { std::cout << indent << "for key: " << kv.key() << " value differs." << std::endl; } return false; } } return true; } else if (lhs.isTensorList() || lhs.isList()) { const auto& vec = lhs.toList(); const auto& rvec = rhs.toList(); return ivalueListEquals( vec.begin(), vec.end(), rvec.begin(), rvec.end(), print, print_indent); } else if (lhs.isTuple()) { const auto vec = lhs.toTuple()->elements(); const auto rvec = rhs.toTuple()->elements(); return ivalueListEquals( vec.begin(), vec.end(), rvec.begin(), rvec.end(), print, print_indent); } else if (lhs.isObject()) { auto lobj = lhs.toObject(); auto robj = rhs.toObject(); auto ltype = lobj->type(); auto rtype = robj->type(); if (ltype->name() != rtype->name()) { if (print) { std::cerr << indent << "left object is of type: " << ltype->name()->qualifiedName() << " but right obj is of type: " << rtype->name()->qualifiedName() << std::endl; } return false; } auto getstate = ltype->findMethod("__getstate__"); if (getstate != nullptr) { return ivalueEquals( (*getstate)({lobj}), (*getstate)({robj}), print, print_indent + 1); } for (int i = 0; i < ltype->numAttributes(); i++) { if (!ivalueEquals( lobj->getSlot(i), robj->getSlot(i), print, print_indent + 1)) { std::cout << "attribute differs at position " << i << std::endl; return false; } } return true; } std::cerr << " I am here and should not be: " << rhs.tagKind() << std::endl; return false; } template <typename T, typename COMP, typename PRINTER> bool vectorEqual( const std::vector<T>& lhs, const std::vector<T>& rhs, bool print, COMP comparator, PRINTER printer) { if (lhs.size() != rhs.size()) { if (print) { std::cout << "lhs and rhs has different size: " << lhs.size() << "vs. " << rhs.size() << std::endl; } return false; } for (int i = 0; i < lhs.size(); i++) { if (!comparator(lhs[i], rhs[i])) { if (print) { std::cout << i << "th element of lhs and rhs differs \n lhs is " << printer(lhs[i]) << " rhs is " << printer(rhs[i]) << std::endl; } return false; } } return true; } bool moduleFunctionEquals( const mobile::Function& lhs, const mobile::Function& rhs, bool print) { const auto* lhs_code = lhs.get_code().get(); const auto* rhs_code = rhs.get_code().get(); if (print) { std::cout << "> Diffing instructions..." << std::endl; } auto ins_equal = [](Instruction lins, Instruction rins) -> bool { return (lins.op == rins.op && lins.N == rins.N && lins.X == rins.X); }; auto id = [](auto ins) { return ins; }; if (vectorEqual( lhs_code->instructions_, rhs_code->instructions_, true, ins_equal, id)) { std::cout << " pass." << std::endl; } else { std::cout << " fail." << std::endl; return false; } if (print) { std::cout << "> Diffing constants..." << std::endl; } if (ivalueListEquals( lhs_code->constants_.begin(), lhs_code->constants_.end(), rhs_code->constants_.begin(), rhs_code->constants_.end(), true, 2)) { std::cout << " pass" << std::endl; } else { std::cout << " fail" << std::endl; return false; } if (print) { std::cout << "> Diffing operators ..." << std::endl; } auto equals = [](auto op1, auto op2) -> bool { return op1 == op2; }; if (vectorEqual(lhs_code->op_names_, rhs_code->op_names_, true, equals, id)) { std::cout << " pass." << std::endl; } else { std::cout << " fail." << std::endl; return false; } if (lhs_code->register_size_ != rhs_code->register_size_) { std::cout << "Register size differs: " << lhs_code->register_size_ << " vs. " << rhs_code->register_size_ << std::endl; return false; } if (print) { std::cout << "> Diffing debug handles..." << std::endl; } if (
) { std::cout << " pass." << std::endl; } else { std::cout << " fail." << std::endl; return false; } auto type_eq = [](auto t1, auto t2) { return t1->str() == t2->str(); }; auto type_print = [](auto t1) { return t1->str(); }; if (print) { std::cout << "> Diffing types..." << std::endl; } if (vectorEqual( lhs_code->types_, rhs_code->types_, true, type_eq, type_print)) { std::cout << " pass." << std::endl; } else { std::cout << " fail." << std::endl; return false; } if (print) { std::cout << "> Diffing schema..." << std::endl; } if (toString(lhs.getSchema()) == toString(rhs.getSchema())) { std::cout << " pass." << std::endl; } else { std::cout << " lhs is " << lhs.getSchema() << std::endl; std::cout << " rhs is " << rhs.getSchema() << std::endl; std::cout << " fail." << std::endl; return false; } return true; } bool moduleEquals(const mobile::Module& lhs, const mobile::Module& rhs) { std::unordered_map<std::string, const mobile::Function*> lhs_name_to_func; std::unordered_map<std::string, const mobile::Function*> rhs_name_to_func; for (const auto& func : lhs.compilation_unit().methods()) { lhs_name_to_func[func->name()] = func.get(); } for (const auto& func : rhs.compilation_unit().methods()) { rhs_name_to_func[func->name()] = func.get(); } for (const auto& name_func : lhs_name_to_func) { auto rhs_func = rhs_name_to_func.find(name_func.first); if (rhs_func == rhs_name_to_func.end()) { std::cout << "Method with name: " << name_func.first << " only exists in lhs"; } std::cout << "comparing method with name " << name_func.first << std::endl; if (moduleFunctionEquals(*name_func.second, *rhs_func->second, true)) { std::cout << "pass" << std::endl; } else { std::cout << "fail" << std::endl; return false; } } std::cout << "Diffing m._ivalue()..." << std::endl; if (ivalueEquals(lhs._ivalue(), rhs._ivalue(), true, 0)) { std::cout << " pass." << std::endl; } else { std::cout << " fail." << std::endl; return false; } return true; } } }
vectorEqual( lhs_code->debug_handles_, rhs_code->debug_handles_, true, equals, id)
call_expression
[]