hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
633f226b759776df06943ecdcf0a51ee31c32c59
958
cpp
C++
BrotBoxEngine/MouseButtons.cpp
siretty/BrotBoxEngine
e1eb95152ffb8a7051e96a8937aa62f568b90a27
[ "MIT" ]
37
2020-06-14T18:14:08.000Z
2022-03-29T18:39:34.000Z
BrotBoxEngine/MouseButtons.cpp
HEX17/BrotBoxEngine
4f8bbe220be022423b94e3b594a3695b87705a70
[ "MIT" ]
2
2021-04-05T15:34:18.000Z
2021-05-28T00:04:56.000Z
BrotBoxEngine/MouseButtons.cpp
HEX17/BrotBoxEngine
4f8bbe220be022423b94e3b594a3695b87705a70
[ "MIT" ]
10
2020-06-25T17:07:03.000Z
2022-03-08T20:31:17.000Z
#include "BBE/MouseButtons.h" #include "BBE/Exceptions.h" bbe::String bbe::mouseButtonToString(MouseButton button) { switch (button) { case MouseButton::LEFT: return bbe::String("MB_LEFT"); case MouseButton::RIGHT: return bbe::String("MB_RIGHT"); case MouseButton::MIDDLE: return bbe::String("MB_MIDDLE"); case MouseButton::_4: return bbe::String("MB_4"); case MouseButton::_5: return bbe::String("MB_5"); case MouseButton::_6: return bbe::String("MB_6"); case MouseButton::_7: return bbe::String("MB_7"); case MouseButton::_8: return bbe::String("MB_8"); } throw NoSuchMouseButtonException(); } bool bbe::isMouseButtonValid(MouseButton button) { switch (button) { case MouseButton::LEFT : case MouseButton::RIGHT : case MouseButton::MIDDLE: case MouseButton::_4 : case MouseButton::_5 : case MouseButton::_6 : case MouseButton::_7 : case MouseButton::_8 : return true; } return false; }
21.288889
56
0.693111
siretty
6342a192baf2b2c8e02b65210518b607600111bd
2,038
cpp
C++
src/MpiOp.cpp
seanmarks/mpi_cpp
a4dda9d310d494272ace08e5e1af2a8a3dc5e029
[ "MIT" ]
null
null
null
src/MpiOp.cpp
seanmarks/mpi_cpp
a4dda9d310d494272ace08e5e1af2a8a3dc5e029
[ "MIT" ]
null
null
null
src/MpiOp.cpp
seanmarks/mpi_cpp
a4dda9d310d494272ace08e5e1af2a8a3dc5e029
[ "MIT" ]
null
null
null
// Written by Sean M. Marks (https://github.com/seanmarks) #include "MpiOp.h" MpiOp::MpiOp(): user_function_ptr_(nullptr), is_commutative_(false) {} MpiOp::MpiOp(const MpiOp& mpi_op) { this->user_function_ptr_ = mpi_op.user_function_ptr_; this->is_commutative_ = mpi_op.is_commutative_; #ifdef MPI_ENABLED if ( this->user_function_ptr_ != nullptr ) { MPI_Op_create(user_function_ptr_, is_commutative_, &mpi_op_); } #endif // ifdef MPI_ENABLED } MpiOp& MpiOp::operator=(const MpiOp& mpi_op) { if ( &mpi_op != this ) { this->user_function_ptr_ = mpi_op.user_function_ptr_; this->is_commutative_ = mpi_op.is_commutative_; #ifdef MPI_ENABLED if ( this->user_function_ptr_ != nullptr ) { MPI_Op_create(user_function_ptr_, is_commutative_, &mpi_op_); } #endif // ifdef MPI_ENABLED } return *this; } MpiOp::~MpiOp() { #ifdef MPI_ENABLED if ( user_function_ptr_ != nullptr ) { MPI_Op_free(&mpi_op_); } #endif // ifdef MPI_ENABLED }; const std::unordered_map<MpiOp::StandardOp, std::string, MpiOp::EnumClassHash> MpiOp::standard_mpi_op_names_ = { { StandardOp::Null, "Null" }, { StandardOp::Max, "Max" }, { StandardOp::Min, "Min" }, { StandardOp::Sum, "Sum" }, { StandardOp::Product, "Product" }, { StandardOp::Land, "Land" }, { StandardOp::Band, "Band" }, { StandardOp::Lor, "Lor" }, { StandardOp::Bor, "Bor" }, { StandardOp::Lxor, "Lxor" }, { StandardOp::Bxor, "Bxor" }, { StandardOp::Minloc, "Minloc" }, { StandardOp::Maxloc, "Maxloc" }, { StandardOp::Replace, "Replace" } }; const std::string& MpiOp::getName(const MpiOp::StandardOp& op) { const auto it = standard_mpi_op_names_.find(op); if ( it != standard_mpi_op_names_.end() ) { return it->second; } else { std::stringstream err_ss; err_ss << "Error in " << FANCY_FUNCTION << "\n" << " A standard MPI operation does not have a registered name." << " This should never happen.\n"; throw std::runtime_error( err_ss.str() ); } }
25.160494
79
0.653582
seanmarks
634a66eb2fb62de35ceb1659257be7ca6d005f1d
42
cpp
C++
src/LlvmVal.cpp
djmzp/OrbLang
65b82cb614b39a1946cfa04d042880b7b36412c1
[ "MIT" ]
29
2020-11-19T16:07:45.000Z
2022-01-24T09:58:59.000Z
src/LlvmVal.cpp
djmzp/OrbLang
65b82cb614b39a1946cfa04d042880b7b36412c1
[ "MIT" ]
null
null
null
src/LlvmVal.cpp
djmzp/OrbLang
65b82cb614b39a1946cfa04d042880b7b36412c1
[ "MIT" ]
5
2021-01-06T11:46:59.000Z
2022-02-06T03:41:50.000Z
#include "LlvmVal.h" using namespace std;
14
20
0.761905
djmzp
634b64c75154a938ff8b169543b02b5d5e81148c
4,075
cpp
C++
src/ui/widgets/WidgetList.cpp
ChillstepCoder/Vorb
f74c0cfa3abde4fed0e9ec9d936b23c5210ba2ba
[ "MIT" ]
65
2018-06-03T23:09:46.000Z
2021-07-22T22:03:34.000Z
src/ui/widgets/WidgetList.cpp
ChillstepCoder/Vorb
f74c0cfa3abde4fed0e9ec9d936b23c5210ba2ba
[ "MIT" ]
8
2018-06-20T17:21:30.000Z
2020-06-30T01:06:26.000Z
src/ui/widgets/WidgetList.cpp
ChillstepCoder/Vorb
f74c0cfa3abde4fed0e9ec9d936b23c5210ba2ba
[ "MIT" ]
34
2018-06-04T03:40:52.000Z
2022-02-15T07:02:05.000Z
#include "Vorb/stdafx.h" #include "Vorb/ui/widgets/WidgetList.h" vui::WidgetList::WidgetList() : Widget(), m_spacing(10.0f), m_maxHeight(FLT_MAX) { // Empty } vui::WidgetList::~WidgetList() { // Empty } void vui::WidgetList::initBase() { m_panel.init(this, getName() + "_panel"); m_panel.setClipping(Clipping{ ClippingState::HIDDEN, ClippingState::HIDDEN, ClippingState::HIDDEN, ClippingState::HIDDEN }); } void vui::WidgetList::dispose() { Widget::dispose(); IWidgets().swap(m_items); } void vui::WidgetList::updateDimensions(f32 dt) { Widget::updateDimensions(dt); f32 totalHeight = 0.0f; for (size_t i = 0; i < m_items.size(); ++i) { IWidget* child = m_items[i]; // We need to update the child's dimensions now, as we might otherwise get screwy scroll bars as the child isn't up-to-date with parent changes. { WidgetFlags oldFlags = child->getFlags(); child->setFlags({ oldFlags.isClicking, oldFlags.isEnabled, oldFlags.isMouseIn, oldFlags.ignoreOffset, true, // needsDimensionUpdate false, // needsZIndexReorder false, // needsDockRecalculation false, // needsClipRectRecalculation false // needsDrawableRecalculation }); child->update(0.0f); WidgetFlags newFlags = child->getFlags(); child->setFlags({ newFlags.isClicking, newFlags.isEnabled, newFlags.isMouseIn, newFlags.ignoreOffset, false, // needsDimensionUpdate oldFlags.needsZIndexReorder || newFlags.needsZIndexReorder, oldFlags.needsDockRecalculation || newFlags.needsDockRecalculation, oldFlags.needsClipRectRecalculation || newFlags.needsClipRectRecalculation, oldFlags.needsDrawableRecalculation || newFlags.needsDrawableRecalculation }); } child->setPosition(f32v2(0.0f, totalHeight + i * m_spacing)); totalHeight += child->getHeight(); } m_panel.setSize(f32v2(getWidth(), totalHeight > m_maxHeight ? m_maxHeight : totalHeight)); } void vui::WidgetList::addItem(IWidget* item) { m_panel.addWidget(item); m_items.push_back(item); m_flags.needsDrawableRecalculation = true; } bool vui::WidgetList::addItemAtIndex(size_t index, IWidget* item) { if (index > m_items.size()) return false; m_items.insert(m_items.begin() + index, item); m_panel.addWidget(item); m_flags.needsDrawableRecalculation = true; return true; } void vui::WidgetList::addItems(const IWidgets& items) { for (auto& item : items) { addItem(item); } } bool vui::WidgetList::removeItem(IWidget* item) { for (auto it = m_items.begin(); it != m_items.end(); ++it) { if (*it == item) { m_items.erase(it); m_panel.removeWidget(item); m_flags.needsDrawableRecalculation = true; return true; } } return false; } bool vui::WidgetList::removeItem(size_t index) { if (index > m_items.size()) return false; auto it = (m_items.begin() + index); m_panel.removeWidget(*it); m_items.erase(it); m_flags.needsDrawableRecalculation = true; return true; } void vui::WidgetList::setTexture(VGTexture texture) { m_panel.setTexture(texture); } void vui::WidgetList::setBackColor(const color4& color) { m_panel.setColor(color); } void vui::WidgetList::setBackHoverColor(const color4& color) { m_panel.setHoverColor(color); } void vui::WidgetList::setSpacing(f32 spacing) { m_spacing = spacing; m_flags.needsDrawableRecalculation = true; } void vui::WidgetList::setAutoScroll(bool autoScroll) { m_panel.setAutoScroll(autoScroll); } void vui::WidgetList::setMaxHeight(f32 maxHeight) { m_maxHeight = maxHeight; m_flags.needsDimensionUpdate = true; }
26.121795
152
0.628712
ChillstepCoder
634c0bede4bb3788285d7582d75feea8c10f3c1e
233
cpp
C++
A/546/main.cpp
ABGEO07/ABGEOs_CodeForces_Projects
62bf1dc50d435c1f8d2033577e98cf332373b1f8
[ "MIT" ]
null
null
null
A/546/main.cpp
ABGEO07/ABGEOs_CodeForces_Projects
62bf1dc50d435c1f8d2033577e98cf332373b1f8
[ "MIT" ]
null
null
null
A/546/main.cpp
ABGEO07/ABGEOs_CodeForces_Projects
62bf1dc50d435c1f8d2033577e98cf332373b1f8
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int k, n, w, total(0); cin >> k >> n >> w; for (int i(0); i <= w; i++) total = total + k * i; if ((total - n) > 0) cout << total - n; else cout << 0; return 0; }
11.65
28
0.493562
ABGEO07
63531c43da4d6cd926718a4b27d437150bdd83aa
2,651
cpp
C++
common/lock.cpp
raddinet/raddi
87e4996dda8ccc0591ffecbd8d717a1a2947e8a9
[ "MIT" ]
39
2018-05-20T14:08:46.000Z
2022-02-23T15:46:03.000Z
common/lock.cpp
raddinet/raddi
87e4996dda8ccc0591ffecbd8d717a1a2947e8a9
[ "MIT" ]
null
null
null
common/lock.cpp
raddinet/raddi
87e4996dda8ccc0591ffecbd8d717a1a2947e8a9
[ "MIT" ]
3
2019-02-26T21:00:19.000Z
2022-02-03T22:30:52.000Z
#include "lock.h" namespace { void WINAPI defaultCsInit (void ** object) { auto cs = new CRITICAL_SECTION; InitializeCriticalSectionAndSpinCount (cs, 32); *object = cs; } void WINAPI defaultInit (void ** object) { if (!lock::initialize ()) { defaultCsInit (object); } } void WINAPI defaultFree (void ** object) { auto cs = static_cast <CRITICAL_SECTION *> (*object); DeleteCriticalSection (cs); delete cs; } bool WINAPI defaultTry (void ** object) { return TryEnterCriticalSection (static_cast <CRITICAL_SECTION *> (*object)); } bool WINAPI failingTry (void ** object) { return false; } void WINAPI defaultAcquire (void ** object) { EnterCriticalSection (static_cast <CRITICAL_SECTION *> (*object)); } void WINAPI defaultRelease (void ** object) { LeaveCriticalSection (static_cast <CRITICAL_SECTION *> (*object)); } void WINAPI defaultNoOp (void ** object) {} template <typename P> bool Load (HMODULE h, P & pointer, const char * name) { if (P p = reinterpret_cast <P> (GetProcAddress (h, name))) { pointer = p; return true; } else return false; } } void (WINAPI * lock::pInit) (void **) = defaultInit; void (WINAPI * lock::pFree) (void **) = defaultFree; void (WINAPI * lock::pAcquireShared) (void **) = defaultAcquire; void (WINAPI * lock::pAcquireExclusive) (void **) = defaultAcquire; bool (WINAPI * lock::pTryAcquireShared) (void **) = defaultTry; bool (WINAPI * lock::pTryAcquireExclusive) (void **) = defaultTry; void (WINAPI * lock::pReleaseShared) (void **) = defaultRelease; void (WINAPI * lock::pReleaseExclusive) (void **) = defaultRelease; bool lock::initialize () noexcept { if (auto h = GetModuleHandle (L"KERNEL32")) { if (Load (h, pAcquireShared, "AcquireSRWLockShared")) { Load (h, pReleaseShared, "ReleaseSRWLockShared"); Load (h, pAcquireExclusive, "AcquireSRWLockExclusive"); Load (h, pReleaseExclusive, "ReleaseSRWLockExclusive"); // Vista does not have TryAcquire for SRW locks, but we cannot mix CSs and SRWs if (!Load (h, pTryAcquireShared, "TryAcquireSRWLockShared") || !Load (h, pTryAcquireExclusive, "TryAcquireSRWLockExclusive")) { pTryAcquireShared = failingTry; pTryAcquireExclusive = failingTry; } pInit = defaultNoOp; pFree = defaultNoOp; return true; } } pInit = defaultCsInit; return false; }
36.315068
139
0.612976
raddinet
6353231b679b3c06924d1ffb4cd1d140be4ff834
38
cpp
C++
BASIC c++/beginning_with_cpp/token_structure_controlstructure/exercise-3.7_cosx.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
BASIC c++/beginning_with_cpp/token_structure_controlstructure/exercise-3.7_cosx.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
BASIC c++/beginning_with_cpp/token_structure_controlstructure/exercise-3.7_cosx.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
// // Created by rahul on 21/7/19. //
9.5
31
0.552632
jattramesh
636003c01d42140517efea949c39a554c92031c4
6,134
cpp
C++
src/RichText.cpp
ApertaTeam/utengine
e641a76b6c0042a4b581f1ec51798b74f2bb5293
[ "MIT" ]
1
2019-06-19T10:19:33.000Z
2019-06-19T10:19:33.000Z
src/RichText.cpp
ApertaTeam/utengine
e641a76b6c0042a4b581f1ec51798b74f2bb5293
[ "MIT" ]
null
null
null
src/RichText.cpp
ApertaTeam/utengine
e641a76b6c0042a4b581f1ec51798b74f2bb5293
[ "MIT" ]
1
2019-06-19T09:00:15.000Z
2019-06-19T09:00:15.000Z
#include "RichText.h" #include <sstream> #include <vector> #include <stdlib.h> #include <cmath> #include <iostream> namespace UT { RichText::RichText() { this->font = NULL; this->rawText = ""; this->renderPosition = { 0, 0 }; this->monospacing = -1; this->renderOffset = { 0, 0 }; this->ignoreTags = false; this->wavyAngle = 0; this->scale = 1.0; this->textTypeFlags = static_cast<char>(TextType::Normal); this->colorPresets = std::unordered_map<std::string, int32_t>(); colorPresets.insert(std::pair<std::string, int32_t>("Yellow", 0xFFFF00FF)); colorPresets.insert(std::pair<std::string, int32_t>("Black", 0x000000FF)); colorPresets.insert(std::pair<std::string, int32_t>("White", 0xFFFFFFFF)); } void RichText::Update(float delta) { wavyAngle -= 0.3; } void RichText::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); int x = renderPosition.x, y = renderPosition.y; std::vector<int32_t> colorStack; sf::Color formatColor = sf::Color(255, 255, 255); bool cancelNext = false; float localWavyAngle = wavyAngle; for (int i = 0; i < rawText.size(); i++) { bool verifiedTag = false; switch (rawText.at(i)) { case '\n': y += (font->GetGlyph('A').texture.height + font->GetGlyph('A').offset + (monospacing == -1 ? 5 : monospacing * 2)) * scale; x = renderPosition.x; verifiedTag = true; break; case '\\': if (!ignoreTags) { if ((size_t)i + 1 < rawText.size()) { if (rawText[(size_t)i + 1] == 'i') { y += (font->GetGlyph('A').texture.height + font->GetGlyph('A').offset) * scale; if (monospacing == -1) { x = renderPosition.x + (font->GetGlyph('*').shift + font->GetGlyph(' ').shift) * scale; } else { x = renderPosition.x + (font->GetGlyph('*').texture.width + font->GetGlyph(' ').texture.width + monospacing * 2) * scale; } i += 1; verifiedTag = true; break; } } cancelNext = true; verifiedTag = true; } break; case '[': if (!cancelNext && !ignoreTags) { std::string temp = rawText.substr((size_t)i + 1, rawText.substr((size_t)i + 1).find_first_of(']')); std::string tempData = temp.substr(temp.find_first_of(":") + 1); bool verifiedTag = false; if (temp[0] == 'c') { if (colorPresets.count(tempData)) { formatColor = sf::Color(colorPresets.at(tempData)); colorStack.push_back(colorPresets.at(tempData)); } else { int32_t hexColor = std::stoul((tempData.length() < 8) ? tempData + "FF" : tempData, 0, 16); formatColor = sf::Color(hexColor); colorStack.push_back(hexColor); } } else if (temp[0] == '/') { if (temp[1] == 'c') { if (colorStack.size() > 1) { colorStack.pop_back(); formatColor = sf::Color((colorStack.back())); } else { formatColor = sf::Color(255, 255, 255); } } } i += temp.length() + 2; verifiedTag = true; } else { cancelNext = false; } break; default: break; } if (verifiedTag) { continue; } if(i < rawText.length() && font->HasGlyph(rawText.at(i))) { sf::Vector2f localRenderOffset = { 0, 0 }; if (textTypeFlags & static_cast<char>(TextType::Shaky)) { localRenderOffset.x += (std::rand() % 2 + 1) - (std::rand() % 2 + 1); localRenderOffset.y += (std::rand() % 2 + 1) - (std::rand() % 2 + 1); } if (textTypeFlags & static_cast<char>(TextType::Wavy)) { localRenderOffset.x += (std::cos(localWavyAngle) * 0.75); localRenderOffset.y += (std::sin(localWavyAngle) * 1.75); } auto glyph = font->GetGlyph(rawText.at(i)); auto sprite = font->GetGlyphSprite(rawText.at(i)); sprite.setPosition(x + localRenderOffset.x, y + localRenderOffset.y); sprite.setScale({ scale, scale }); sprite.color = formatColor; if (monospacing == -1) { x += (glyph.shift) * scale; } else { x += (glyph.texture.width + monospacing) * scale; } localWavyAngle--; target.draw(sprite, states); } } } }
34.077778
153
0.3955
ApertaTeam
636cb1c86daef7a48964faa4c74f074c64edc9d1
306
hpp
C++
math/totient.hpp
matumoto1234/library
a2c80516a8afe5876696c139fe0e837d8a204f69
[ "Unlicense" ]
2
2021-06-24T11:21:08.000Z
2022-03-15T05:57:25.000Z
math/totient.hpp
matumoto1234/library
a2c80516a8afe5876696c139fe0e837d8a204f69
[ "Unlicense" ]
102
2021-10-30T21:30:00.000Z
2022-03-26T18:39:47.000Z
math/totient.hpp
matumoto1234/library
a2c80516a8afe5876696c139fe0e837d8a204f69
[ "Unlicense" ]
null
null
null
#pragma once #include "./base.hpp" namespace math { ll totient(ll n) { ll res = n; for (ll i = 2; i * i <= n; i++) { if (n % i == 0) { res -= res / i; while (n % i == 0) n /= i; } } if (n > 1) res -= res / n; return res; } } // namespace math
17
37
0.395425
matumoto1234
636fabe2c052b4b43579806cf9463cf3c67c6d95
466
cpp
C++
detail/os/reactor/iocp/wsa_activator.cpp
wembikon/baba.io
87bec680c1febb64356af59e7e499c2b2b64d30c
[ "MIT" ]
null
null
null
detail/os/reactor/iocp/wsa_activator.cpp
wembikon/baba.io
87bec680c1febb64356af59e7e499c2b2b64d30c
[ "MIT" ]
1
2020-06-12T10:22:09.000Z
2020-06-12T10:22:09.000Z
detail/os/reactor/iocp/wsa_activator.cpp
wembikon/baba.io
87bec680c1febb64356af59e7e499c2b2b64d30c
[ "MIT" ]
null
null
null
/** * MIT License * Copyright (c) 2020 Adrian T. Visarra **/ #include "os/reactor/iocp/wsa_activator.h" #include "baba/logger.h" #include <cstdlib> namespace baba::os { wsa_activator::wsa_activator() : _data{0} { if (int result = WSAStartup(MAKEWORD(2, 2), &_data); result != 0) { LOGFTL("WSAStartup() failed. result={}", result); std::abort(); } } wsa_activator::~wsa_activator() { WSACleanup(); } } // namespace baba::os
20.26087
70
0.61588
wembikon
63764c869d04378fabcef48ae6faa69e5a49aa8b
963
hpp
C++
src/Homie/Boot/BootConfig.hpp
neo164/wi-fi-iot
dad284b235c5540897585e81c56be58136121b52
[ "MIT" ]
null
null
null
src/Homie/Boot/BootConfig.hpp
neo164/wi-fi-iot
dad284b235c5540897585e81c56be58136121b52
[ "MIT" ]
null
null
null
src/Homie/Boot/BootConfig.hpp
neo164/wi-fi-iot
dad284b235c5540897585e81c56be58136121b52
[ "MIT" ]
null
null
null
#pragma once #include <functional> #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> #include <DNSServer.h> #include <ArduinoJson.h> #include "Boot.hpp" #include "../Config.hpp" #include "../Constants.hpp" #include "../Limits.hpp" #include "../Datatypes/Interface.hpp" #include "../Timer.hpp" #include "../Helpers.hpp" #include "../Logger.hpp" #include "../Strings.hpp" namespace HomieInternals { class BootConfig : public Boot { public: BootConfig(); ~BootConfig(); void setup(); void loop(); private: ESP8266WebServer _http; DNSServer _dns; unsigned char _ssidCount; bool _wifiScanAvailable; Timer _wifiScanTimer; bool _lastWifiScanEnded; char* _jsonWifiNetworks; bool _flaggedForReboot; unsigned long _flaggedForRebootAt; void _onDeviceInfoRequest(); void _onNetworksRequest(); void _onConfigRequest(); void _generateNetworksJson(); }; }
22.928571
40
0.669782
neo164
6377d2fb0384303102edd14d113ae597fddb47db
28,333
hpp
C++
src/matrix.hpp
degarashi/frea
bb598245c2ab710cc816e98d7361e5863af5fd7e
[ "MIT" ]
null
null
null
src/matrix.hpp
degarashi/frea
bb598245c2ab710cc816e98d7361e5863af5fd7e
[ "MIT" ]
null
null
null
src/matrix.hpp
degarashi/frea
bb598245c2ab710cc816e98d7361e5863af5fd7e
[ "MIT" ]
null
null
null
#pragma once #include "vector.hpp" #include "angle.hpp" #include "lubee/src/meta/compare.hpp" #include "lubee/src/ieee754.hpp" #include "exception.hpp" namespace frea { template <class VW, int M> using wrapM_t = wrapM_spec<VW, M, VW::size>; // ベクトル演算レジスタクラスをM方向に束ねたもの /*! \tparam VW 各行のベクトル型 \tparam M 行数 \tparam S 本来の型 */ template <class VW, int M, class S> class wrapM : public lubee::op::PlusMinus<S>, public lubee::op::Ne<S> { public: using op_t = lubee::op::PlusMinus<S>; constexpr static bool is_integral = VW::is_integral; constexpr static int dim_m = M, dim_n = VW::size, dim_min = lubee::Arithmetic<dim_m, dim_n>::less, bit_width = VW::bit_width; using Chk_SizeM = std::enable_if_t<(dim_m>0)>*; using spec_t = S; using vec_t = VW; using value_t = typename vec_t::value_t; using column_t = typename vec_t::template type_cn<dim_m>; //! 要素数の読み替え template <int M2, int N2> using type_cn = wrapM_t<typename vec_t::template type_cn<N2>, M2>; private: template <class Dst, class Vec, class WM, int N> static void _MultipleLine(Dst&, const Vec&, const WM&, lubee::IConst<N>, lubee::IConst<N>) noexcept {} template <class Dst, class Vec, class WM, int N, int Z> static void _MultipleLine(Dst& dst, const Vec& v, const WM& m, lubee::IConst<N>, lubee::IConst<Z>) noexcept { const auto val = v.template pickAt<N>(); const Dst tv(val); dst += tv * m.v[N]; _MultipleLine(dst, v, m, lubee::IConst<N+1>(), lubee::IConst<Z>()); } template <int At, std::size_t... Idx> auto _getColumn(std::index_sequence<Idx...>) const noexcept { return column_t((v[Idx].template pickAt<At>())...); } template <int At, std::size_t... Idx> void _setColumn(const column_t& c, std::index_sequence<Idx...>) noexcept { const auto dummy = [](auto&&...){}; dummy(((v[Idx].template setAt<At>(c.template pickAt<Idx>())), 0)...); } template <class... Ts> static void _Dummy(Ts&&...) noexcept {} template <std::size_t... Idx, std::size_t... IdxE> static spec_t _Diagonal(const value_t& v, std::index_sequence<Idx...>, std::index_sequence<IdxE...>) noexcept { spec_t ret; _Dummy((ret.v[Idx].template initAt<Idx>(v), 0)...); _Dummy((ret.v[IdxE+dim_min] = vec_t::Zero())...); return ret; } template <class VW2, int N2, class S2> auto _mul(const wrapM<VW2,N2,S2>& m, std::true_type) const noexcept { using WM = std::decay_t<decltype(m)>; static_assert(WM::dim_m == dim_n, ""); wrapM_t<VW2, dim_m> ret; // 一旦メモリに展開する(m -> other) value_t other[WM::dim_m][WM::dim_n]; for(int i=0 ; i<WM::dim_m ; i++) m.v[i].template store<false>(other[i], lubee::IConst<WM::dim_n-1>()); for(int i=0 ; i<dim_m ; i++) { value_t result[WM::dim_n] = {}, ths[dim_n]; // メモリに展開(this[i] -> ths) v[i].template store<false>(ths, lubee::IConst<dim_n-1>()); for(int j=0 ; j<WM::dim_n ; j++) { auto& dst = result[j]; for(int k=0 ; k<dim_n ; k++) dst += ths[k] * other[k][j]; } // 結果を書き込み ret.v[i] = VW2(result, std::false_type()); } return ret; } template <class VW2, int N2, class S2> auto _mul(const wrapM<VW2,N2,S2>& m, std::false_type) const noexcept { using WM = std::decay_t<decltype(m)>; static_assert(WM::dim_m == dim_n, ""); wrapM_t<VW2, dim_m> ret; for(int i=0 ; i<dim_m ; i++) { ret.v[i] = VW2::Zero(); _MultipleLine(ret.v[i], v[i], m, lubee::IConst<0>(), lubee::IConst<WM::dim_m>()); } return ret; } template <std::size_t... Idx, ENABLE_IF(sizeof...(Idx) == dim_m)> column_t _mul_vecR(std::index_sequence<Idx...>, const vec_t& vc) const noexcept { return column_t(v[Idx].dot(vc)...); } template <std::size_t... Idx, ENABLE_IF(sizeof...(Idx) == dim_n)> auto _mul_vecL(std::index_sequence<Idx...>, const column_t& vc) const noexcept { vec_t ret = vec_t::Zero(); _MultipleLine(ret, vc, *this, lubee::IConst<0>(), lubee::IConst<dim_m>()); return ret; } public: vec_t v[dim_m]; wrapM() = default; template <bool A> wrapM(const value_t* src, lubee::BConst<A>) noexcept { for(int i=0 ; i<dim_m ; i++) { v[i] = vec_t(src, lubee::BConst<A>()); src += A ? vec_t::capacity : vec_t::size; } } decltype(auto) operator [] (const int n) noexcept { return v[n]; } decltype(auto) operator [] (const int n) const noexcept { return v[n]; } #define DEF_OP2(op) \ template <class T, \ ENABLE_IF((HasMethod_asInternal_t<T>{}))> \ auto operator op (const T& t) const noexcept { \ return *this op t.asInternal(); \ } #define DEF_OP(op) \ DEF_OP2(op) \ template <class VW2, class S2> \ spec_t operator op (const wrapM<VW2,M,S2>& m) const noexcept { \ spec_t ret; \ for(int i=0 ; i<dim_m ; i++) \ ret.v[i] = v[i] op m.v[i]; \ return ret; \ } \ spec_t operator op (const value_t& t) const noexcept { \ spec_t ret; \ const vec_t tmp(t); \ for(int i=0 ; i<dim_m ; i++) \ ret.v[i] = v[i] op tmp; \ return ret; \ } \ using op_t::operator op; DEF_OP(+) DEF_OP(-) #undef DEF_OP DEF_OP2(*) DEF_OP2(/) #undef DEF_OP2 template <class VW2, class S2> spec_t& operator = (const wrapM<VW2,dim_m,S2>& m) noexcept { for(int i=0 ; i<dim_m ; i++) v[i] = m.v[i]; return *this; } auto operator * (const value_t& t) const noexcept { spec_t ret; vec_t tmp(t); for(int i=0 ; i<dim_m ; i++) ret.v[i] = v[i] * tmp; return ret; } template <class T = value_t, ENABLE_IF(std::is_floating_point<T>{})> auto operator / (const value_t& t) const noexcept { return *this * (1 / t); } template <class T = value_t, ENABLE_IF(std::is_integral<T>{})> auto operator / (const value_t& t) const noexcept { spec_t ret; const vec_t tmp(t); for(int i=0 ; i<dim_m ; i++) ret.v[i] = v[i] / tmp; return ret; } template <class Wr, ENABLE_IF(is_wrapM<Wr>{})> auto operator * (const Wr& m) const noexcept { return _mul(m, IsTuple_t<typename Wr::vec_t>()); } // 右からベクトルを掛ける column_t operator * (const vec_t& vc) const noexcept { return _mul_vecR(std::make_index_sequence<dim_m>(), vc); } // 左からベクトルを掛ける auto _pre_mul(const column_t& vc) const noexcept { return _mul_vecL(std::make_index_sequence<dim_n>(), vc); } bool operator == (const wrapM& m) const noexcept { for(int i=0 ; i<dim_m ; i++) { if(v[i] != m.v[i]) return false; } return true; } template <class VD> void store(VD* dst) const noexcept { for(auto& t : v) { t.template store<VD::align>(dst->m, lubee::IConst<dim_n-1>()); ++dst; } } template <int N2> constexpr static bool same_capacity = type_cn<dim_m, N2>::vec_t::capacity == vec_t::capacity; // そのままポインタの読み変えが出来るケース template <int ToM, int ToN, ENABLE_IF((ToM<=dim_m && ToN<=dim_n && same_capacity<ToN>))> decltype(auto) convert() const noexcept { return reinterpret_cast<const type_cn<ToM, ToN>&>(*this); } template <int ToM, int ToN, ENABLE_IF((ToM<=dim_m && ToN<=dim_n && same_capacity<ToN>))> decltype(auto) convertI(const value_t&) const noexcept { return convert<ToM, ToN>(); } // 大きいサイズへの変換 // 隙間をゼロで埋める template <int ToM, int ToN, ENABLE_IF((ToM>dim_m || ToN>dim_n || !same_capacity<ToN>))> auto convert() const noexcept { using ret_t = type_cn<ToM, ToN>; ret_t ret; for(int i=0 ; i<dim_m ; i++) ret.v[i] = v[i].template convert<ToN>(); for(int i=dim_m ; i<ToM ; i++) ret.v[i] = ret_t::vec_t::Zero(); return ret; } // 大きいサイズへの変換 // 隙間をゼロで埋め、対角成分のみ任意の値を書き込む template <int ToM, int ToN, ENABLE_IF((ToM>dim_m || ToN>dim_n || !same_capacity<ToN>))> auto convertI(const value_t& v) const noexcept { using ret_t = type_cn<ToM, ToN>; auto ret = ret_t::Diagonal(v); for(int i=0 ; i<dim_m ; i++) ret.v[i] = ret.v[i].template maskL<dim_n-1>() | this->v[i].template convert<ToN>(); return ret; } static spec_t Identity() noexcept { return Diagonal(1); } static spec_t Diagonal(const value_t& v) noexcept { return _Diagonal(v, std::make_index_sequence<dim_min>(), std::make_index_sequence<dim_m-dim_min>() ); } template <int At> const auto& getRow() const noexcept { static_assert(At < dim_m, "invalid position"); return v[At]; } template <int At> auto& getRow() noexcept { static_assert(At < dim_m, "invalid position"); return v[At]; } template <int At> auto getColumn() const noexcept { static_assert(At < dim_n, "invalid position"); return _getColumn<At>(std::make_index_sequence<dim_m>()); } template <int At> void setRow(const vec_t& r) noexcept { static_assert(At < dim_m, "invalid position"); v[At] = r; } template <int At> void setColumn(const column_t& c) noexcept { static_assert(At < dim_n, "invalid position"); _setColumn<At>(c, std::make_index_sequence<dim_m>()); } bool isZero(const value_t& th) const noexcept { for(int i=0 ; i<dim_m ; i++) { if(!v[i].isZero(th)) return false; } return true; } void linearNormalize() noexcept { *this = linearNormalization(); } spec_t linearNormalization() const noexcept { spec_t ret; for(int i=0 ; i<dim_m ; i++) ret.v[i] = v[i].linearNormalization(); return ret; } }; template <class VW, int M, int N> struct wrapM_spec : wrapM<VW, M, wrapM_spec<VW,M,N>> { using base_t = wrapM<VW, M, wrapM_spec<VW,M,N>>; using base_t::base_t; wrapM_spec() = default; wrapM_spec(const base_t& b): base_t(b) {} }; #define DEF_FUNC(cls, name, nameC) \ void name() noexcept(noexcept(std::declval<cls>().nameC())) { \ *this = nameC(); \ } template <class R, int M, int N, bool A> using SMat_t = MatT_spec<SVec_t<R, N, A>, M, N>; template <class T, int M, int N> using RMat_t = MatT_spec<RVec_t<T, N>, M, N>; template <class T, int M, int N, bool A> using Mat_t = MatT_spec<Vec_t<T, N, A>, M, N>; //! 正方行列のみのメンバ関数を定義 template <class VW, int S> class wrapM_spec<VW,S,S> : public wrapM<VW, S, wrapM_spec<VW,S,S>> { private: using base_t = wrapM<VW, S, wrapM_spec<VW,S,S>>; using this_t = wrapM_spec; public: using value_t = typename base_t::value_t; private: using mat_t = Mat_t<value_t, base_t::dim_m, base_t::dim_n, true>; // InfoにTranspose関数が用意されていればtrue template <class VW2, std::size_t... Idx, class B, class = decltype(VW2::I::Transpose(std::declval<B>().v[Idx].m...))> static std::true_type hasmem(std::index_sequence<Idx...>); // そうでなければfalse template <class VW2, class B> static std::false_type hasmem(...); //! 効率の良い転置アルゴリズムが使用可能な場合はそれを使用 template <std::size_t... Idx> auto _transposition(std::true_type, std::index_sequence<Idx...>) const noexcept { auto ret = *this; VW::I::Transpose((ret.v[Idx].m)...); return ret; } //! 効率の良い転置アルゴリズムが定義されていない場合は地道に要素を交換する template <std::size_t... Idx> auto _transposition(std::false_type, std::index_sequence<Idx...>) const noexcept { typename base_t::value_t tmp[S][S]; const auto dummy = [](auto...) {}; dummy((base_t::v[Idx].template store<false>(tmp[Idx], lubee::IConst<base_t::dim_n-1>()), 0)...); dummy(([&tmp](const int i){ for(int j=i+1 ; j<base_t::dim_n ; j++) { std::swap(tmp[i][j], tmp[j][i]); } }(Idx), 0)...); return this_t((const typename base_t::value_t*)tmp, std::false_type()); } public: using vec_t = typename base_t::vec_t; using base_t::base_t; wrapM_spec() = default; wrapM_spec(const base_t& b): base_t(b) {} auto transposition() const& noexcept { const auto idx = std::make_index_sequence<S>(); return _transposition(decltype(this->hasmem<VW, base_t>(idx))(), idx); } // ----------- アダプタ関数群 ----------- value_t calcDeterminant() const noexcept { return mat_t(*this).calcDeterminant(); } this_t inversion() const { return mat_t(*this).inversion(); } this_t inversion(const value_t& det) const { return mat_t(*this).inversion(det); } DEF_FUNC(wrapM_spec, inverse, inversion) DEF_FUNC(wrapM_spec, transpose, transposition) }; #undef DEF_FUNC template <bool C, class T> using ConstIf = std::conditional_t<C, std::add_const_t<T>, T>; template <class D, bool C> class ItrM : public std::iterator< std::input_iterator_tag, ConstIf<C, typename D::value_t> > { private: using base_t = std::iterator<std::input_iterator_tag, ConstIf<C, typename D::value_t>>; using D_t = ConstIf<C, D>; D_t& _target; int _cursor; constexpr static int dim_n = D::dim_n; public: ItrM(D_t& t, const int cur) noexcept: _target(t), _cursor(cur) {} typename base_t::reference operator * () const noexcept { return _target.m[_cursor/dim_n][_cursor%dim_n]; } ItrM& operator ++ () noexcept { ++_cursor; return *this; } ItrM operator ++ (int) noexcept { const int cur = _cursor++; return ItrM(_target, cur); } typename base_t::pointer operator -> () const noexcept { return &(*this); } bool operator == (const ItrM& itr) const noexcept { return _cursor == itr._cursor; } bool operator != (const ItrM& itr) const noexcept { return _cursor != itr._cursor; } }; template <class V, int M> class DataM { public: using value_t = typename V::value_t; using vec_t = V; constexpr static int dim_m = M, dim_n = vec_t::size, bit_width = vec_t::bit_width; constexpr static bool align = vec_t::align, is_integral = vec_t::is_integral; using column_t = typename vec_t::template type_cn<dim_m>; private: void _init(vec_t*) noexcept {} template <class... Ts> void _init(vec_t* dst, const vec_t& v, const Ts&... ts) noexcept { *dst = v; _init(dst+1, ts...); } template <std::size_t... Idx> void _initA(std::index_sequence<Idx...>, const value_t *src) noexcept { static_assert(sizeof...(Idx) == dim_n, ""); for(int i=0 ; i<dim_m ; i++) { m[i] = vec_t(src[Idx]...); src += dim_n; } } template <class Ar, class V2, int M2> friend void serialize(Ar&, DataM<V2,M2>&); public: vec_t m[dim_m]; DataM() = default; // --- iterator interface --- auto begin() noexcept { return ItrM<DataM, false>(*this, 0); } auto end() noexcept { return ItrM<DataM, false>(*this, dim_m*dim_n); } auto begin() const noexcept { return ItrM<DataM, true>(*this, 0); } auto end() const noexcept { return ItrM<DataM, true>(*this, dim_m*dim_n); } auto cbegin() const noexcept { return ItrM<DataM, true>(*this, 0); } auto cend() const noexcept { return ItrM<DataM, true>(*this, dim_m*dim_n); } vec_t& operator [](const int n) noexcept { return m[n]; } const vec_t& operator [](const int n) const noexcept { return m[n]; } // vec_tの配列[dim_m]で初期化 template <class... Ts, ENABLE_IF((sizeof...(Ts)==dim_m))> DataM(const Ts&... ts) noexcept { _init(m, ts...); } // value_tの配列で初期化 template <class... Ts, ENABLE_IF((sizeof...(Ts)==dim_m*dim_n))> DataM(const Ts&... ts) noexcept { const value_t tmp[dim_m*dim_n] = {static_cast<value_t>(ts)...}; _initA(std::make_index_sequence<dim_n>(), tmp); } // 全て同一のvalue_tで初期化 explicit DataM(const value_t& t0) noexcept { vec_t tmp(t0); for(auto& v : m) v = tmp; } // from 内部形式 DataM(const wrapM_spec<typename V::wrap_t, M, V::size>& w) noexcept { w.store(m); } std::ostream& print(std::ostream& os) const { os << '['; bool bF = true; for(int i=0 ; i<dim_m ; i++) { if(!bF) os << ", "; this->m[i].print(os); bF = false; } return os << ']'; } }; #define AsI(t) wrap_t(reinterpret_cast<const value_t*>((t).m), lubee::BConst<align>()) template <class V, int M, class S> struct MatT : DataM<V,M>, lubee::op::Operator_Ne<S> { using op_t = lubee::op::Operator_Ne<S>; using spec_t = S; using base_t = DataM<V,M>; using base_t::base_t; using vec_t = V; using wrap_t = wrapM_t<typename V::wrap_t, M>; using value_t = typename V::value_t; constexpr static int dim_m = base_t::dim_m, dim_n = base_t::dim_n, dim_min = lubee::Arithmetic<dim_m,dim_n>::less; constexpr static int size = dim_m, lower_size = dim_n; constexpr static bool align = base_t::align; using column_t = typename V::template type_cn<dim_m>; using vec_min = typename vec_t::template type_cn<dim_min>; using Chk_SizeM = std::enable_if_t<(dim_m>0)>*; //! 要素数, アラインメントの読み替え template <int M2, int N2, bool A=align> using type_cn = Mat_t<value_t, M2, N2, A>; MatT() = default; constexpr MatT(const base_t& b) noexcept: base_t(b) {} MatT(const wrap_t& w) noexcept { for(int i=0 ; i<dim_m ; i++) base_t::m[i] = w.v[i]; } //! 指定した行と列を省いた物を出力 auto cutRC(const int row, const int clm) const noexcept { type_cn<dim_m-1, dim_n-1> ret; constexpr int width = dim_n, height = dim_m; // 左上 for(int i=0 ; i<row ; i++) { for(int j=0 ; j<clm ; j++) ret.m[i][j] = this->m[i][j]; } // 右上 for(int i=0 ; i<row ; i++) { for(int j=clm+1 ; j<width ; j++) ret.m[i][j-1] = this->m[i][j]; } // 左下 for(int i=row+1 ; i<height ; i++) { for(int j=0 ; j<clm ; j++) ret.m[i-1][j] = this->m[i][j]; } // 右下 for(int i=row+1 ; i<height ; i++) { for(int j=clm+1 ; j<width ; j++) ret.m[i-1][j-1] = this->m[i][j]; } return ret; } // ---------- < 行の基本操作 > ---------- //! 行を入れ替える void rowSwap(const int r0, const int r1) noexcept { std::swap(this->m[r0], this->m[r1]); } //! ある行を定数倍する void rowMul(const int r0, const value_t& s) noexcept { this->m[r0] *= s; } //! ある行を定数倍した物を別の行へ足す void rowMulAdd(const int r0, const value_t& s, const int r1) noexcept { this->m[r1] += this->m[r0] * s; } // ---------- < 列の基本操作 > ---------- //! 列を入れ替える void clmSwap(const int c0, const int c1) noexcept { for(int i=0 ; i<dim_m ; i++) std::swap(this->m[i][c0], this->m[i][c1]); } //! ある列を定数倍する void clmMul(const int c0, const value_t& s) noexcept { for(int i=0 ; i<dim_m ; i++) this->m[i][c0] *= s; } //! ある列を定数倍した物を別の行へ足す void clmMulAdd(const int c0, const value_t& s, const int c1) noexcept { for(int i=0 ; i<dim_m ; i++) this->m[i][c1] += this->m[i][c0] * s; } //! ある行の要素が全てゼロか判定 bool isZeroRow(const int n, const value_t& th) const noexcept { return this->m[n].isZero(th); } bool isZero(const value_t& th) const noexcept { return AsI(*this).isZero(th); } //! 各行を正規化する (最大の係数が1になるように) void linearNormalize() noexcept { *this = AsI(*this).linearNormalization(); } spec_t linearNormalization() const noexcept { return AsI(*this).linearNormalization(); } //! 被約階段行列かどうか判定 bool isEchelon(const value_t& th) const noexcept { int edge = 0; for(int i=0 ; i<dim_m ; i++) { // 前回の行のエッジより左側がゼロ以外ならFalse for(int j=0 ; j<edge ; j++) { if(std::abs(this->m[i][j]) >= th) return false; } // 行の先頭(=1)を探す for(; edge<dim_n ; edge++) { const auto v = this->m[i][edge]; if(std::abs(v) < th) { // ゼロなので更に右を探索 } else if(std::abs(v-1) < th) { // 1なのでここが先頭 break; } else return false; } if(edge < dim_n) { ++edge; } else { // 先頭は既に右端なのでこれ以降の行は全てゼロである if(!this->m[i].isZero(th)) return false; } } return true; } //! 被約階段行列にする /*! \return 0の行数 */ int rowReduce(const value_t& th) noexcept { int rbase = 0, cbase = 0; for(;;) { // 行の先端が0でなく、かつ絶対値が最大の行を探す int idx = -1; value_t absmax = 0; for(int i=rbase ; i<dim_m ; i++) { value_t v = std::abs(this->m[i][cbase]); if(absmax < v) { if(std::abs(v) >= th) { absmax = v; idx = i; } } } if(idx < 0) { // 無かったので次の列へ ++cbase; if(cbase == dim_n) { // 終了 break; } continue; } // 基準行でなければ入れ替え if(idx > rbase) rowSwap(idx, rbase); // 基点で割って1にする rowMul(rbase, 1/this->m[rbase][cbase]); this->m[rbase][cbase] = 1; // 精度の問題で丁度1にならない事があるので強制的に1をセット // 他の行の同じ列を0にする for(int i=0 ; i<dim_m ; i++) { if(i==rbase) continue; value_t scale = -this->m[i][cbase]; rowMulAdd(rbase, scale, i); this->m[i][cbase] = 0; // 上と同じく精度の問題により0をセット } // 次の行,列へ移る ++rbase; ++cbase; if(rbase == dim_m || cbase == dim_n) { // 最後の行まで処理し終わるか,全て0の行しか無ければ終了 break; } } return dim_m - rbase; } static MatT Diagonal(const value_t& v) noexcept { return wrap_t::Diagonal(v); } template <class... Ts, ENABLE_IF((sizeof...(Ts)==dim_min))> static MatT Diagonal(const value_t& v0, const Ts&... ts); static MatT Identity() noexcept { return wrap_t::Diagonal(1); } template <int At> const auto& getRow() const noexcept { static_assert(At < dim_m, "invalid position"); return this->m[At]; } template <int At> auto& getRow() noexcept { static_assert(At < dim_m, "invalid position"); return this->m[At]; } template <int At> column_t getColumn() const noexcept { static_assert(At < dim_n, "invalid position"); column_t ret; for(int i=0 ; i<dim_m ; i++) ret[i] = this->m[i][At]; return ret; } template <int At> void setRow(const vec_t& v) noexcept { static_assert(At < dim_m, "invalid position"); this->m[At] = v; } template <int At> void setColumn(const column_t& c) noexcept { static_assert(At < dim_n, "invalid position"); for(int i=0 ; i<dim_m ; i++) this->m[i][At] = c[i]; } constexpr operator wrap_t() const noexcept { return AsI(*this); } wrap_t asInternal() const noexcept { return AsI(*this); } #define DEF_OP(op) \ template <class Num> \ auto operator op (const Num& num) const noexcept { \ return AsI(*this) op num; \ } \ using op_t::operator op; DEF_OP(+) DEF_OP(-) DEF_OP(*) DEF_OP(/) DEF_OP(&) DEF_OP(|) DEF_OP(^) #undef DEF_OP bool operator == (const MatT& m) const noexcept { return AsI(*this) == m; } // ベクトルを左から掛ける auto _pre_mul(const column_t& vc) const noexcept { return vc * AsI(*this); } static spec_t Translation(const vec_t& v) noexcept { spec_t ret = Identity(); ret.template getRow<dim_m-1>() = v; return ret; } static spec_t Scaling(const vec_min& v) noexcept { spec_t ret(0); for(int i=0 ; i<vec_min::size ; i++) ret.m[i][i] = v[i]; return ret; } //! サイズ変換 //! 足りない要素はゼロで埋める template <int M2, int N2> auto convert() const noexcept { return AsI(*this).template convert<M2,N2>(); } //! サイズ変換 //! 足りない要素はゼロで埋め、対角線上要素を任意の値で初期化 template <int M2, int N2> auto convertI(const value_t& vi) const noexcept { return AsI(*this).template convertI<M2,N2>(vi); } // -------- Luaへのエクスポート用 -------- MatT luaAddF(const float s) const noexcept { return *this + s; } MatT luaAddM(const MatT& m) const noexcept { return *this * m; } MatT luaSubF(const float s) const noexcept { return *this - s; } MatT luaSubM(const MatT& m) const noexcept { return *this - m; } MatT luaMulF(const float s) const noexcept { return *this * s; } MatT luaMulM(const MatT& m) const noexcept { return *this * m; } typename vec_t::template type_cn<dim_m> luaMulV(const vec_t& v) const noexcept { return *this * v; } MatT luaDivF(const float s) const noexcept { return *this / s; } bool luaEqual(const MatT& m) const noexcept { return *this == m; } std::string luaToString() const { return lubee::ToString(*this); } }; #undef AsI template <class V, int M, class S> const int MatT<V,M,S>::size; template <class V, int M, class S> const bool MatT<V,M,S>::align; template <class V, int M, int N, class S> struct MatT_dspec : MatT<V,M,S> { using base_t = MatT<V,M,S>; using base_t::base_t; MatT_dspec() = default; MatT_dspec(const base_t& b): base_t(b) {} }; // 正方行列のみのメンバ関数を定義 template <class V, int N, class S> class MatT_dspec<V,N,N,S> : public MatT<V,N,S> { public: using base_t = MatT<V,N,S>; using base_t::base_t; MatT_dspec() = default; MatT_dspec(const base_t& b): base_t(b) {} using spec_t = S; using value_t = typename V::value_t; using this_t = MatT_dspec; private: value_t _calcDeterminant(lubee::IConst<2>) const noexcept { // 公式で計算 const Mat_t<value_t, 2, 2, false> m(*this); return m[0][0]*m[1][1] - m[0][1]*m[1][0]; } template <int N2, ENABLE_IF((N2>2))> value_t _calcDeterminant(lubee::IConst<N2>) const noexcept { value_t res = 0, s = 1; // 部分行列を使って計算 for(int i=0 ; i<N2 ; i++) { const auto mt = this->cutRC(0,i); res += this->m[0][i] * mt.calcDeterminant() * s; s *= -1; } return res; } spec_t _inversion(const value_t& di, lubee::IConst<2>) const noexcept { spec_t ret; ret.m[0][0] = this->m[1][1] * di; ret.m[1][0] = -this->m[1][0] * di; ret.m[0][1] = -this->m[0][1] * di; ret.m[1][1] = this->m[0][0] * di; return ret; } template <int N2, ENABLE_IF((N2>2))> spec_t _inversion(const value_t& di, lubee::IConst<N2>) const noexcept { spec_t ret; const value_t c_val[2] = {1,-1}; for(int i=0 ; i<base_t::dim_m ; i++) { for(int j=0 ; j<base_t::dim_n ; j++) { auto in_mat = this->cutRC(i,j); const value_t in_di = in_mat.calcDeterminant(); ret.m[j][i] = c_val[(i+j)&1] * in_di * di; } } return ret; } constexpr static auto ZeroThreshold = lubee::Threshold<value_t>(0.6, 1); public: value_t calcDeterminant() const noexcept { return _calcDeterminant(lubee::IConst<base_t::dim_m>()); } spec_t inversion() const { return inversion(calcDeterminant()); } spec_t inversion(const value_t& det) const { constexpr auto Th = ZeroThreshold; if(std::abs(det) < Th) throw NoInverseMatrix(); return _inversion(1/det, lubee::IConst<base_t::dim_m>()); } void invert() { *this = inversion(); } // -------- アダプタ関数群(wrapM) -------- spec_t transposition() const noexcept { return this->asInternal().transposition(); } void transpose() noexcept { *this = transposition(); } // -------- Luaへのエクスポート用 -------- spec_t luaInvert() const { return inversion(); } }; template <class V, int M, int N> struct MatT_spec : MatT_dspec<V,M,N, MatT_spec<V,M,N>> { using base_t = MatT_dspec<V,M,N, MatT_spec<V,M,N>>; using base_t::base_t; MatT_spec() = default; MatT_spec(const base_t& b): base_t(b) {} }; template <class W, ENABLE_IF((is_wrapM<W>{}))> inline std::ostream& operator << (std::ostream& os, const W& w) { const Mat_t<typename W::value_t, W::dim_m, W::dim_n, true> m(w); return os << m; } template <class M, ENABLE_IF((is_matrix<M>{}))> inline std::ostream& operator << (std::ostream& os, const M& m) { os << "Mat" << M::dim_m << M::dim_n << ": "; return m.print(os); } } namespace std { template <class V, int M> struct hash<frea::DataM<V,M>> { std::size_t operator()(const frea::DataM<V,M>& d) const noexcept { const std::hash<typename frea::DataM<V,M>::vec_t> h; std::size_t ret = 0; for(int i=0 ; i<M ; i++) ret ^= h(d.m[i]); return ret; } }; template <class V, int M, int N> struct hash<frea::MatT_spec<V,M,N>> { using mat_t = frea::MatT_spec<V,M,N>; std::size_t operator()(const mat_t& m) const noexcept { using base_t = typename mat_t::base_t::base_t::base_t; return hash<base_t>()(static_cast<const base_t&>(m)); } }; } #include "include/mat_d2.hpp" #include "include/mat_d3.hpp" #include "include/mat_d4.hpp" namespace frea { #if SSE >= 2 #define DEF_RM(n) \ using RMat##n = RMat_t<float, n, n>; DEF_RM(2) DEF_RM(3) DEF_RM(4) #undef DEF_RM #endif #define DEF_M(n) \ using Mat##n = Mat_t<float, n, n, false>; \ using IMat##n = Mat_t<int32_t, n, n, false>; \ using DMat##n = Mat_t<double, n, n, false>; \ using AMat##n = Mat_t<float, n, n, true>; DEF_M(2) DEF_M(3) DEF_M(4) #undef DEF_M }
29.421599
114
0.60156
degarashi
6382661cb6f4376c759b0f4840a3018570268b4d
204
hpp
C++
src/GUI/Console.hpp
370rokas/MediaServer
9a74d2a77a2af499ebf9357c2bdb6e70375ad072
[ "MIT" ]
1
2022-03-11T20:09:27.000Z
2022-03-11T20:09:27.000Z
src/GUI/Console.hpp
370rokas/MediaServer
9a74d2a77a2af499ebf9357c2bdb6e70375ad072
[ "MIT" ]
null
null
null
src/GUI/Console.hpp
370rokas/MediaServer
9a74d2a77a2af499ebf9357c2bdb6e70375ad072
[ "MIT" ]
null
null
null
// // Created by rokas on 3/12/22. // #ifndef WUSEMEDIASERVER_CONSOLE_HPP #define WUSEMEDIASERVER_CONSOLE_HPP class Console { public: void Run(); private: }; #endif //WUSEMEDIASERVER_CONSOLE_HPP
12
36
0.740196
370rokas
63836f176f9bfa85e118a527b5c73e7f8980c5ed
4,501
cpp
C++
src/nnfusion/core/kernels/cuda_gpu/util/gpu_util.cpp
lynex/nnfusion
6332697c71b6614ca6f04c0dac8614636882630d
[ "MIT" ]
639
2020-09-05T10:00:59.000Z
2022-03-30T08:42:39.000Z
src/nnfusion/core/kernels/cuda_gpu/util/gpu_util.cpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
252
2020-09-09T05:35:36.000Z
2022-03-29T04:58:41.000Z
src/nnfusion/core/kernels/cuda_gpu/util/gpu_util.cpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
104
2020-09-05T10:01:08.000Z
2022-03-23T10:59:13.000Z
//***************************************************************************** // Copyright 2017-2020 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include "gpu_util.hpp" #include "nnfusion/util/util.hpp" using namespace std; using namespace nnfusion; namespace { // Unsigned integer exponentiation by squaring adapted // from https://stackoverflow.com/a/101613/882253 uint64_t powU64(uint64_t base, uint64_t exp) { uint64_t result = 1; do { if (exp & 1) { result *= base; } exp >>= 1; if (!exp) { break; } base *= base; } while (true); return result; } // Most significant bit search via de bruijn multiplication // Adopted from https://stackoverflow.com/a/31718095/882253 // Additional ref: http://supertech.csail.mit.edu/papers/debruijn.pdf uint32_t msbDeBruijnU32(uint32_t v) { static const int multiply_de_Bruijn_bit_position[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31}; v |= v >> 1; // first round down to one less than a power of 2 v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; return multiply_de_Bruijn_bit_position[static_cast<uint32_t>(v * 0x07C4ACDDU) >> 27]; } // perform msb on upper 32 bits if the first 32 bits are filled // otherwise do normal de bruijn mutliplication on the 32 bit word int msbU64(uint64_t val) { if (val > 0x00000000FFFFFFFFul) { return 32 + msbDeBruijnU32(static_cast<uint32_t>(val >> 32)); } // Number is no more than 32 bits, // so calculate number of bits in the bottom half. return msbDeBruijnU32(static_cast<uint32_t>(val & 0xFFFFFFFF)); } // Magic numbers and shift amounts for integer division // Suitable for when nmax*magic fits in 32 bits // Translated from http://www.hackersdelight.org/hdcodetxt/magicgu.py.txt std::pair<uint64_t, uint64_t> magicU32(uint64_t nmax, uint64_t d) { uint64_t nc = ((nmax + 1) / d) * d - 1; uint64_t nbits = msbU64(nmax) + 1; for (uint64_t p = 0; p < 2 * nbits + 1; p++) { uint64_t pow2 = powU64(2, p); if (pow2 > nc * (d - 1 - (pow2 - 1) % d)) { uint64_t m = (pow2 + d - 1 - (pow2 - 1) % d) / d; return std::pair<uint64_t, uint64_t>{m, p}; } } NNFUSION_CHECK_FAIL() << "Magic for unsigned integer division could not be found."; } // Magic numbers and shift amounts for integer division // Suitable for when nmax*magic fits in 64 bits and the shift // lops off the lower 32 bits std::pair<uint64_t, uint64_t> magicU64(uint64_t d) { // 3 is a special case that only ends up in the high bits // if the nmax is 0xffffffff // we can't use 0xffffffff for all cases as some return a 33 bit // magic number uint64_t nmax = (d == 3) ? 0xffffffff : 0x7fffffff; uint64_t magic, shift; std::tie(magic, shift) = magicU32(nmax, d); if (magic != 1) { shift -= 32; } return std::pair<uint64_t, uint64_t>{magic, shift}; } } std::pair<uint64_t, uint64_t> kernels::cuda::idiv_magic_u32(uint64_t max_numerator, uint64_t divisor) { return magicU32(max_numerator, divisor); } std::pair<uint64_t, uint64_t> kernels::cuda::idiv_magic_u64(uint64_t divisor) { return magicU64(divisor); } uint32_t kernels::cuda::idiv_ceil(int n, int d) { // compiler fused modulo and division return n / d + (n % d > 0); }
33.842105
93
0.565874
lynex
638a64d0087e85458287c8af5b72311314ac2c05
2,448
hpp
C++
vm/test/test_vm_native_library.hpp
marnen/rubinius
05b3f9789d01bada0604a7f09921c956bc9487e7
[ "BSD-3-Clause" ]
1
2016-05-08T16:58:14.000Z
2016-05-08T16:58:14.000Z
vm/test/test_vm_native_library.hpp
taf2/rubinius
493bfa2351fc509ca33d3bb03991c2e9c2b6dafa
[ "BSD-3-Clause" ]
null
null
null
vm/test/test_vm_native_library.hpp
taf2/rubinius
493bfa2351fc509ca33d3bb03991c2e9c2b6dafa
[ "BSD-3-Clause" ]
null
null
null
#include <cstdlib> #include "native_libraries.hpp" #include "builtin/exception.hpp" #include <cxxtest/TestSuite.h> using namespace rubinius; class TestNativeLibrary : public CxxTest::TestSuite { public: VM* state_; const char* lib_name_; void setUp() { state_ = new VM(); lib_name_ = ::getenv("LIBRUBY"); } void tearDown() { delete state_; } void test_find_symbol_in_this_process() { String* name = String::create(state_, "strlen"); /* libc */ TS_ASSERT(NativeLibrary::find_symbol(state_, name, Qnil)); } void test_find_symbol_in_this_process_throws_on_unloaded_library() { String* name = String::create(state_, "ruby_version"); /* libruby.1.8 */ TS_ASSERT_THROWS(NativeLibrary::find_symbol(state_, name, Qnil), RubyException); } void test_find_symbol_in_this_process_throws_on_nonexisting_symbol() { String* name = String::create(state_, "nonesuch_just_made__u___p__yep____"); TS_ASSERT_THROWS(NativeLibrary::find_symbol(state_, name, Qnil), RubyException); } /** * \file * * @todo This only works under the assumption that anyone running * these tests has MRI installed. We could be more creative * but frankly it requires too much code in C++. This code * _must_ exercise a library that has not been loaded into * the current image (@see test_find_symbol_in_this_process) * because whether the call to load e.g. libc succeeds is * platform-dependent. --rue */ void test_find_symbol_in_library() { if(lib_name_) { String* lib = String::create(state_, lib_name_); String* name = String::create(state_, "ruby_version"); TS_ASSERT(NativeLibrary::find_symbol(state_, name, lib)); } } void test_find_symbol_in_library_throws_on_nonexisting_library() { String* lib = String::create(state_, "blah"); String* name = String::create(state_, "ruby_version"); TS_ASSERT_THROWS(NativeLibrary::find_symbol(state_, name, lib), RubyException); } void test_find_symbol_in_library_throws_on_nonexisting_symbol() { if(lib_name_) { String* lib = String::create(state_, lib_name_); String* name = String::create(state_, "python_version"); TS_ASSERT_THROWS(NativeLibrary::find_symbol(state_, name, lib), RubyException); } } };
28.465116
80
0.665033
marnen
638ca6cb52621f723ba8044101e0cd0594c94b99
35,119
cpp
C++
Source/WebKit/UIProcess/WebStorage/StorageManager.cpp
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
1
2021-05-27T07:29:31.000Z
2021-05-27T07:29:31.000Z
WebKit2-7604.1.38.0.7/WebKit2-7604.1.38.0.7/UIProcess/Storage/StorageManager.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
9
2020-04-18T18:47:18.000Z
2020-04-18T18:52:41.000Z
Source/WebKit/UIProcess/WebStorage/StorageManager.cpp
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2013-2016 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "StorageManager.h" #include "LocalStorageDatabase.h" #include "LocalStorageDatabaseTracker.h" #include "StorageAreaMapMessages.h" #include "StorageManagerMessages.h" #include "WebProcessProxy.h" #include <WebCore/SecurityOriginData.h> #include <WebCore/SecurityOriginHash.h> #include <WebCore/StorageMap.h> #include <WebCore/TextEncoding.h> #include <memory> #include <wtf/WorkQueue.h> #include <wtf/threads/BinarySemaphore.h> using namespace WebCore; namespace WebKit { class StorageManager::StorageArea : public ThreadSafeRefCounted<StorageManager::StorageArea> { public: static Ref<StorageArea> create(LocalStorageNamespace*, const SecurityOriginData&, unsigned quotaInBytes); ~StorageArea(); const WebCore::SecurityOriginData& securityOrigin() const { return m_securityOrigin; } void addListener(IPC::Connection&, uint64_t storageMapID); void removeListener(IPC::Connection&, uint64_t storageMapID); Ref<StorageArea> clone() const; void setItem(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& value, const String& urlString, bool& quotaException); void removeItem(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& urlString); void clear(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& urlString); const HashMap<String, String>& items() const; void clear(); bool isSessionStorage() const { return !m_localStorageNamespace; } private: explicit StorageArea(LocalStorageNamespace*, const SecurityOriginData&, unsigned quotaInBytes); void openDatabaseAndImportItemsIfNeeded() const; void dispatchEvents(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& oldValue, const String& newValue, const String& urlString) const; // Will be null if the storage area belongs to a session storage namespace. LocalStorageNamespace* m_localStorageNamespace; mutable RefPtr<LocalStorageDatabase> m_localStorageDatabase; mutable bool m_didImportItemsFromDatabase { false }; SecurityOriginData m_securityOrigin; unsigned m_quotaInBytes; RefPtr<StorageMap> m_storageMap; HashSet<std::pair<RefPtr<IPC::Connection>, uint64_t>> m_eventListeners; }; class StorageManager::LocalStorageNamespace : public ThreadSafeRefCounted<LocalStorageNamespace> { public: static Ref<LocalStorageNamespace> create(StorageManager*, uint64_t storageManagerID); ~LocalStorageNamespace(); StorageManager* storageManager() const { return m_storageManager; } Ref<StorageArea> getOrCreateStorageArea(SecurityOriginData&&); void didDestroyStorageArea(StorageArea*); void clearStorageAreasMatchingOrigin(const SecurityOriginData&); void clearAllStorageAreas(); private: explicit LocalStorageNamespace(StorageManager*, uint64_t storageManagerID); StorageManager* m_storageManager; uint64_t m_storageNamespaceID; unsigned m_quotaInBytes; // We don't hold an explicit reference to the StorageAreas; they are kept alive by the m_storageAreasByConnection map in StorageManager. HashMap<SecurityOriginData, StorageArea*> m_storageAreaMap; }; class StorageManager::TransientLocalStorageNamespace : public ThreadSafeRefCounted<TransientLocalStorageNamespace> { public: static Ref<TransientLocalStorageNamespace> create() { return adoptRef(*new TransientLocalStorageNamespace()); } ~TransientLocalStorageNamespace() { } Ref<StorageArea> getOrCreateStorageArea(SecurityOriginData&& securityOrigin) { return *m_storageAreaMap.ensure(securityOrigin, [this, securityOrigin]() mutable { return StorageArea::create(nullptr, WTFMove(securityOrigin), m_quotaInBytes); }).iterator->value.copyRef(); } Vector<SecurityOriginData> origins() const { Vector<SecurityOriginData> origins; for (const auto& storageArea : m_storageAreaMap.values()) { if (!storageArea->items().isEmpty()) origins.append(storageArea->securityOrigin()); } return origins; } void clearStorageAreasMatchingOrigin(const SecurityOriginData& securityOrigin) { for (auto& storageArea : m_storageAreaMap.values()) { if (storageArea->securityOrigin() == securityOrigin) storageArea->clear(); } } void clearAllStorageAreas() { for (auto& storageArea : m_storageAreaMap.values()) storageArea->clear(); } private: explicit TransientLocalStorageNamespace() { } const unsigned m_quotaInBytes = 5 * 1024 * 1024; HashMap<SecurityOriginData, RefPtr<StorageArea>> m_storageAreaMap; }; auto StorageManager::StorageArea::create(LocalStorageNamespace* localStorageNamespace, const SecurityOriginData& securityOrigin, unsigned quotaInBytes) -> Ref<StorageManager::StorageArea> { return adoptRef(*new StorageArea(localStorageNamespace, securityOrigin, quotaInBytes)); } StorageManager::StorageArea::StorageArea(LocalStorageNamespace* localStorageNamespace, const SecurityOriginData& securityOrigin, unsigned quotaInBytes) : m_localStorageNamespace(localStorageNamespace) , m_securityOrigin(securityOrigin) , m_quotaInBytes(quotaInBytes) , m_storageMap(StorageMap::create(m_quotaInBytes)) { } StorageManager::StorageArea::~StorageArea() { ASSERT(m_eventListeners.isEmpty()); if (m_localStorageDatabase) m_localStorageDatabase->close(); if (m_localStorageNamespace) m_localStorageNamespace->didDestroyStorageArea(this); } void StorageManager::StorageArea::addListener(IPC::Connection& connection, uint64_t storageMapID) { ASSERT(!m_eventListeners.contains(std::make_pair(&connection, storageMapID))); m_eventListeners.add(std::make_pair(&connection, storageMapID)); } void StorageManager::StorageArea::removeListener(IPC::Connection& connection, uint64_t storageMapID) { ASSERT(isSessionStorage() || m_eventListeners.contains(std::make_pair(&connection, storageMapID))); m_eventListeners.remove(std::make_pair(&connection, storageMapID)); } Ref<StorageManager::StorageArea> StorageManager::StorageArea::clone() const { ASSERT(!m_localStorageNamespace); auto storageArea = StorageArea::create(nullptr, m_securityOrigin, m_quotaInBytes); storageArea->m_storageMap = m_storageMap; return storageArea; } void StorageManager::StorageArea::setItem(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& value, const String& urlString, bool& quotaException) { openDatabaseAndImportItemsIfNeeded(); String oldValue; auto newStorageMap = m_storageMap->setItem(key, value, oldValue, quotaException); if (newStorageMap) m_storageMap = WTFMove(newStorageMap); if (quotaException) return; if (m_localStorageDatabase) m_localStorageDatabase->setItem(key, value); dispatchEvents(sourceConnection, sourceStorageAreaID, key, oldValue, value, urlString); } void StorageManager::StorageArea::removeItem(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& urlString) { openDatabaseAndImportItemsIfNeeded(); String oldValue; auto newStorageMap = m_storageMap->removeItem(key, oldValue); if (newStorageMap) m_storageMap = WTFMove(newStorageMap); if (oldValue.isNull()) return; if (m_localStorageDatabase) m_localStorageDatabase->removeItem(key); dispatchEvents(sourceConnection, sourceStorageAreaID, key, oldValue, String(), urlString); } void StorageManager::StorageArea::clear(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& urlString) { openDatabaseAndImportItemsIfNeeded(); if (!m_storageMap->length()) return; m_storageMap = StorageMap::create(m_quotaInBytes); if (m_localStorageDatabase) m_localStorageDatabase->clear(); dispatchEvents(sourceConnection, sourceStorageAreaID, String(), String(), String(), urlString); } const HashMap<String, String>& StorageManager::StorageArea::items() const { openDatabaseAndImportItemsIfNeeded(); return m_storageMap->items(); } void StorageManager::StorageArea::clear() { m_storageMap = StorageMap::create(m_quotaInBytes); if (m_localStorageDatabase) { m_localStorageDatabase->close(); m_localStorageDatabase = nullptr; } for (auto it = m_eventListeners.begin(), end = m_eventListeners.end(); it != end; ++it) it->first->send(Messages::StorageAreaMap::ClearCache(), it->second); } void StorageManager::StorageArea::openDatabaseAndImportItemsIfNeeded() const { if (!m_localStorageNamespace) return; // We open the database here even if we've already imported our items to ensure that the database is open if we need to write to it. if (!m_localStorageDatabase) m_localStorageDatabase = LocalStorageDatabase::create(m_localStorageNamespace->storageManager()->m_queue.copyRef(), m_localStorageNamespace->storageManager()->m_localStorageDatabaseTracker.copyRef(), m_securityOrigin); if (m_didImportItemsFromDatabase) return; m_localStorageDatabase->importItems(*m_storageMap); m_didImportItemsFromDatabase = true; } void StorageManager::StorageArea::dispatchEvents(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& oldValue, const String& newValue, const String& urlString) const { for (HashSet<std::pair<RefPtr<IPC::Connection>, uint64_t>>::const_iterator it = m_eventListeners.begin(), end = m_eventListeners.end(); it != end; ++it) { uint64_t storageAreaID = it->first == sourceConnection ? sourceStorageAreaID : 0; it->first->send(Messages::StorageAreaMap::DispatchStorageEvent(storageAreaID, key, oldValue, newValue, urlString), it->second); } } Ref<StorageManager::LocalStorageNamespace> StorageManager::LocalStorageNamespace::create(StorageManager* storageManager, uint64_t storageNamespaceID) { return adoptRef(*new LocalStorageNamespace(storageManager, storageNamespaceID)); } // FIXME: The quota value is copied from GroupSettings.cpp. // We should investigate a way to share it with WebCore. StorageManager::LocalStorageNamespace::LocalStorageNamespace(StorageManager* storageManager, uint64_t storageNamespaceID) : m_storageManager(storageManager) , m_storageNamespaceID(storageNamespaceID) , m_quotaInBytes(5 * 1024 * 1024) { } StorageManager::LocalStorageNamespace::~LocalStorageNamespace() { ASSERT(m_storageAreaMap.isEmpty()); } auto StorageManager::LocalStorageNamespace::getOrCreateStorageArea(SecurityOriginData&& securityOrigin) -> Ref<StorageArea> { auto& slot = m_storageAreaMap.add(securityOrigin, nullptr).iterator->value; if (slot) return *slot; auto storageArea = StorageArea::create(this, WTFMove(securityOrigin), m_quotaInBytes); slot = &storageArea.get(); return storageArea; } void StorageManager::LocalStorageNamespace::didDestroyStorageArea(StorageArea* storageArea) { ASSERT(m_storageAreaMap.contains(storageArea->securityOrigin())); m_storageAreaMap.remove(storageArea->securityOrigin()); if (!m_storageAreaMap.isEmpty()) return; ASSERT(m_storageManager->m_localStorageNamespaces.contains(m_storageNamespaceID)); m_storageManager->m_localStorageNamespaces.remove(m_storageNamespaceID); } void StorageManager::LocalStorageNamespace::clearStorageAreasMatchingOrigin(const SecurityOriginData& securityOrigin) { for (const auto& originAndStorageArea : m_storageAreaMap) { if (originAndStorageArea.key == securityOrigin) originAndStorageArea.value->clear(); } } void StorageManager::LocalStorageNamespace::clearAllStorageAreas() { for (auto* storageArea : m_storageAreaMap.values()) storageArea->clear(); } class StorageManager::SessionStorageNamespace : public ThreadSafeRefCounted<SessionStorageNamespace> { public: static Ref<SessionStorageNamespace> create(unsigned quotaInBytes); ~SessionStorageNamespace(); bool isEmpty() const { return m_storageAreaMap.isEmpty(); } IPC::Connection* allowedConnection() const { return m_allowedConnection.get(); } void setAllowedConnection(IPC::Connection*); Ref<StorageArea> getOrCreateStorageArea(SecurityOriginData&&); void cloneTo(SessionStorageNamespace& newSessionStorageNamespace); Vector<SecurityOriginData> origins() const { Vector<SecurityOriginData> origins; for (const auto& storageArea : m_storageAreaMap.values()) { if (!storageArea->items().isEmpty()) origins.append(storageArea->securityOrigin()); } return origins; } void clearStorageAreasMatchingOrigin(const SecurityOriginData& securityOrigin) { for (auto& storageArea : m_storageAreaMap.values()) { if (storageArea->securityOrigin() == securityOrigin) storageArea->clear(); } } void clearAllStorageAreas() { for (auto& storageArea : m_storageAreaMap.values()) storageArea->clear(); } private: explicit SessionStorageNamespace(unsigned quotaInBytes); RefPtr<IPC::Connection> m_allowedConnection; unsigned m_quotaInBytes; HashMap<SecurityOriginData, RefPtr<StorageArea>> m_storageAreaMap; }; Ref<StorageManager::SessionStorageNamespace> StorageManager::SessionStorageNamespace::create(unsigned quotaInBytes) { return adoptRef(*new SessionStorageNamespace(quotaInBytes)); } StorageManager::SessionStorageNamespace::SessionStorageNamespace(unsigned quotaInBytes) : m_quotaInBytes(quotaInBytes) { } StorageManager::SessionStorageNamespace::~SessionStorageNamespace() { } void StorageManager::SessionStorageNamespace::setAllowedConnection(IPC::Connection* allowedConnection) { ASSERT(!allowedConnection || !m_allowedConnection); m_allowedConnection = allowedConnection; } auto StorageManager::SessionStorageNamespace::getOrCreateStorageArea(SecurityOriginData&& securityOrigin) -> Ref<StorageArea> { return *m_storageAreaMap.ensure(securityOrigin, [this, securityOrigin]() mutable { return StorageArea::create(nullptr, WTFMove(securityOrigin), m_quotaInBytes); }).iterator->value.copyRef(); } void StorageManager::SessionStorageNamespace::cloneTo(SessionStorageNamespace& newSessionStorageNamespace) { ASSERT_UNUSED(newSessionStorageNamespace, newSessionStorageNamespace.isEmpty()); for (auto& pair : m_storageAreaMap) newSessionStorageNamespace.m_storageAreaMap.add(pair.key, pair.value->clone()); } Ref<StorageManager> StorageManager::create(const String& localStorageDirectory) { return adoptRef(*new StorageManager(localStorageDirectory)); } StorageManager::StorageManager(const String& localStorageDirectory) : m_queue(WorkQueue::create("com.apple.WebKit.StorageManager")) , m_localStorageDatabaseTracker(LocalStorageDatabaseTracker::create(m_queue.copyRef(), localStorageDirectory)) { // Make sure the encoding is initialized before we start dispatching things to the queue. UTF8Encoding(); } StorageManager::~StorageManager() { } void StorageManager::createSessionStorageNamespace(uint64_t storageNamespaceID, unsigned quotaInBytes) { m_queue->dispatch([this, protectedThis = makeRef(*this), storageNamespaceID, quotaInBytes]() mutable { ASSERT(!m_sessionStorageNamespaces.contains(storageNamespaceID)); m_sessionStorageNamespaces.set(storageNamespaceID, SessionStorageNamespace::create(quotaInBytes)); }); } void StorageManager::destroySessionStorageNamespace(uint64_t storageNamespaceID) { m_queue->dispatch([this, protectedThis = makeRef(*this), storageNamespaceID] { ASSERT(m_sessionStorageNamespaces.contains(storageNamespaceID)); m_sessionStorageNamespaces.remove(storageNamespaceID); }); } void StorageManager::setAllowedSessionStorageNamespaceConnection(uint64_t storageNamespaceID, IPC::Connection* allowedConnection) { m_queue->dispatch([this, protectedThis = makeRef(*this), connection = RefPtr<IPC::Connection>(allowedConnection), storageNamespaceID]() mutable { ASSERT(m_sessionStorageNamespaces.contains(storageNamespaceID)); m_sessionStorageNamespaces.get(storageNamespaceID)->setAllowedConnection(connection.get()); }); } void StorageManager::cloneSessionStorageNamespace(uint64_t storageNamespaceID, uint64_t newStorageNamespaceID) { m_queue->dispatch([this, protectedThis = makeRef(*this), storageNamespaceID, newStorageNamespaceID] { SessionStorageNamespace* sessionStorageNamespace = m_sessionStorageNamespaces.get(storageNamespaceID); if (!sessionStorageNamespace) { // FIXME: We can get into this situation if someone closes the originating page from within a // createNewPage callback. We bail for now, but we should really find a way to keep the session storage alive // so we we'll clone the session storage correctly. return; } SessionStorageNamespace* newSessionStorageNamespace = m_sessionStorageNamespaces.get(newStorageNamespaceID); ASSERT(newSessionStorageNamespace); sessionStorageNamespace->cloneTo(*newSessionStorageNamespace); }); } void StorageManager::processWillOpenConnection(WebProcessProxy&, IPC::Connection& connection) { connection.addWorkQueueMessageReceiver(Messages::StorageManager::messageReceiverName(), m_queue.get(), this); } void StorageManager::processDidCloseConnection(WebProcessProxy&, IPC::Connection& connection) { connection.removeWorkQueueMessageReceiver(Messages::StorageManager::messageReceiverName()); m_queue->dispatch([this, protectedThis = makeRef(*this), connection = Ref<IPC::Connection>(connection)]() mutable { Vector<std::pair<RefPtr<IPC::Connection>, uint64_t>> connectionAndStorageMapIDPairsToRemove; for (auto& storageArea : m_storageAreasByConnection) { if (storageArea.key.first != connection.ptr()) continue; storageArea.value->removeListener(*storageArea.key.first, storageArea.key.second); connectionAndStorageMapIDPairsToRemove.append(storageArea.key); } for (auto& pair : connectionAndStorageMapIDPairsToRemove) m_storageAreasByConnection.remove(pair); }); } void StorageManager::getSessionStorageOrigins(Function<void(HashSet<WebCore::SecurityOriginData>&&)>&& completionHandler) { m_queue->dispatch([this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)]() mutable { HashSet<SecurityOriginData> origins; for (const auto& sessionStorageNamespace : m_sessionStorageNamespaces.values()) { for (auto& origin : sessionStorageNamespace->origins()) origins.add(origin); } RunLoop::main().dispatch([origins = WTFMove(origins), completionHandler = WTFMove(completionHandler)]() mutable { completionHandler(WTFMove(origins)); }); }); } void StorageManager::deleteSessionStorageOrigins(Function<void()>&& completionHandler) { m_queue->dispatch([this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)]() mutable { for (auto& sessionStorageNamespace : m_sessionStorageNamespaces.values()) sessionStorageNamespace->clearAllStorageAreas(); RunLoop::main().dispatch(WTFMove(completionHandler)); }); } void StorageManager::deleteSessionStorageEntriesForOrigins(const Vector<WebCore::SecurityOriginData>& origins, Function<void()>&& completionHandler) { Vector<WebCore::SecurityOriginData> copiedOrigins; copiedOrigins.reserveInitialCapacity(origins.size()); for (auto& origin : origins) copiedOrigins.uncheckedAppend(origin.isolatedCopy()); m_queue->dispatch([this, protectedThis = makeRef(*this), copiedOrigins = WTFMove(copiedOrigins), completionHandler = WTFMove(completionHandler)]() mutable { for (auto& origin : copiedOrigins) { for (auto& sessionStorageNamespace : m_sessionStorageNamespaces.values()) sessionStorageNamespace->clearStorageAreasMatchingOrigin(origin); } RunLoop::main().dispatch(WTFMove(completionHandler)); }); } void StorageManager::getLocalStorageOrigins(Function<void(HashSet<WebCore::SecurityOriginData>&&)>&& completionHandler) { m_queue->dispatch([this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)]() mutable { HashSet<SecurityOriginData> origins; for (auto& origin : m_localStorageDatabaseTracker->origins()) origins.add(origin); for (auto& transientLocalStorageNamespace : m_transientLocalStorageNamespaces.values()) { for (auto& origin : transientLocalStorageNamespace->origins()) origins.add(origin); } RunLoop::main().dispatch([origins = WTFMove(origins), completionHandler = WTFMove(completionHandler)]() mutable { completionHandler(WTFMove(origins)); }); }); } void StorageManager::getLocalStorageOriginDetails(Function<void (Vector<LocalStorageDatabaseTracker::OriginDetails>)>&& completionHandler) { m_queue->dispatch([this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)]() mutable { auto originDetails = m_localStorageDatabaseTracker->originDetails(); RunLoop::main().dispatch([originDetails = WTFMove(originDetails), completionHandler = WTFMove(completionHandler)]() mutable { completionHandler(WTFMove(originDetails)); }); }); } void StorageManager::deleteLocalStorageEntriesForOrigin(SecurityOriginData&& securityOrigin) { m_queue->dispatch([this, protectedThis = makeRef(*this), copiedOrigin = securityOrigin.isolatedCopy()]() mutable { for (auto& localStorageNamespace : m_localStorageNamespaces.values()) localStorageNamespace->clearStorageAreasMatchingOrigin(copiedOrigin); for (auto& transientLocalStorageNamespace : m_transientLocalStorageNamespaces.values()) transientLocalStorageNamespace->clearStorageAreasMatchingOrigin(copiedOrigin); m_localStorageDatabaseTracker->deleteDatabaseWithOrigin(copiedOrigin); }); } void StorageManager::deleteLocalStorageOriginsModifiedSince(std::chrono::system_clock::time_point time, Function<void()>&& completionHandler) { m_queue->dispatch([this, protectedThis = makeRef(*this), time, completionHandler = WTFMove(completionHandler)]() mutable { auto deletedOrigins = m_localStorageDatabaseTracker->deleteDatabasesModifiedSince(time); for (const auto& origin : deletedOrigins) { for (auto& localStorageNamespace : m_localStorageNamespaces.values()) localStorageNamespace->clearStorageAreasMatchingOrigin(origin); } for (auto& transientLocalStorageNamespace : m_transientLocalStorageNamespaces.values()) transientLocalStorageNamespace->clearAllStorageAreas(); RunLoop::main().dispatch(WTFMove(completionHandler)); }); } void StorageManager::deleteLocalStorageEntriesForOrigins(const Vector<WebCore::SecurityOriginData>& origins, Function<void()>&& completionHandler) { Vector<SecurityOriginData> copiedOrigins; copiedOrigins.reserveInitialCapacity(origins.size()); for (auto& origin : origins) copiedOrigins.uncheckedAppend(origin.isolatedCopy()); m_queue->dispatch([this, protectedThis = makeRef(*this), copiedOrigins = WTFMove(copiedOrigins), completionHandler = WTFMove(completionHandler)]() mutable { for (auto& origin : copiedOrigins) { for (auto& localStorageNamespace : m_localStorageNamespaces.values()) localStorageNamespace->clearStorageAreasMatchingOrigin(origin); for (auto& transientLocalStorageNamespace : m_transientLocalStorageNamespaces.values()) transientLocalStorageNamespace->clearStorageAreasMatchingOrigin(origin); m_localStorageDatabaseTracker->deleteDatabaseWithOrigin(origin); } RunLoop::main().dispatch(WTFMove(completionHandler)); }); } void StorageManager::createLocalStorageMap(IPC::Connection& connection, uint64_t storageMapID, uint64_t storageNamespaceID, SecurityOriginData&& securityOriginData) { std::pair<RefPtr<IPC::Connection>, uint64_t> connectionAndStorageMapIDPair(&connection, storageMapID); // FIXME: This should be a message check. ASSERT((HashMap<std::pair<RefPtr<IPC::Connection>, uint64_t>, RefPtr<StorageArea>>::isValidKey(connectionAndStorageMapIDPair))); HashMap<std::pair<RefPtr<IPC::Connection>, uint64_t>, RefPtr<StorageArea>>::AddResult result = m_storageAreasByConnection.add(connectionAndStorageMapIDPair, nullptr); // FIXME: These should be a message checks. ASSERT(result.isNewEntry); ASSERT((HashMap<uint64_t, RefPtr<LocalStorageNamespace>>::isValidKey(storageNamespaceID))); LocalStorageNamespace* localStorageNamespace = getOrCreateLocalStorageNamespace(storageNamespaceID); // FIXME: This should be a message check. ASSERT(localStorageNamespace); auto storageArea = localStorageNamespace->getOrCreateStorageArea(WTFMove(securityOriginData)); storageArea->addListener(connection, storageMapID); result.iterator->value = WTFMove(storageArea); } void StorageManager::createTransientLocalStorageMap(IPC::Connection& connection, uint64_t storageMapID, uint64_t storageNamespaceID, SecurityOriginData&& topLevelOriginData, SecurityOriginData&& origin) { // FIXME: This should be a message check. ASSERT(m_storageAreasByConnection.isValidKey({ &connection, storageMapID })); // See if we already have session storage for this connection/origin combo. // If so, update the map with the new ID, otherwise keep on trucking. for (auto it = m_storageAreasByConnection.begin(), end = m_storageAreasByConnection.end(); it != end; ++it) { if (it->key.first != &connection) continue; Ref<StorageArea> area = *it->value; if (!area->isSessionStorage()) continue; if (!origin.securityOrigin()->isSameSchemeHostPort(area->securityOrigin().securityOrigin().get())) continue; area->addListener(connection, storageMapID); m_storageAreasByConnection.remove(it); m_storageAreasByConnection.add({ &connection, storageMapID }, WTFMove(area)); return; } auto& slot = m_storageAreasByConnection.add({ &connection, storageMapID }, nullptr).iterator->value; // FIXME: This should be a message check. ASSERT(!slot); TransientLocalStorageNamespace* transientLocalStorageNamespace = getOrCreateTransientLocalStorageNamespace(storageNamespaceID, WTFMove(topLevelOriginData)); auto storageArea = transientLocalStorageNamespace->getOrCreateStorageArea(WTFMove(origin)); storageArea->addListener(connection, storageMapID); slot = WTFMove(storageArea); } void StorageManager::createSessionStorageMap(IPC::Connection& connection, uint64_t storageMapID, uint64_t storageNamespaceID, SecurityOriginData&& securityOriginData) { // FIXME: This should be a message check. ASSERT(m_sessionStorageNamespaces.isValidKey(storageNamespaceID)); SessionStorageNamespace* sessionStorageNamespace = m_sessionStorageNamespaces.get(storageNamespaceID); if (!sessionStorageNamespace) { // We're getting an incoming message from the web process that's for session storage for a web page // that has already been closed, just ignore it. return; } // FIXME: This should be a message check. ASSERT(m_storageAreasByConnection.isValidKey({ &connection, storageMapID })); auto& slot = m_storageAreasByConnection.add({ &connection, storageMapID }, nullptr).iterator->value; // FIXME: This should be a message check. ASSERT(!slot); // FIXME: This should be a message check. ASSERT(&connection == sessionStorageNamespace->allowedConnection()); auto storageArea = sessionStorageNamespace->getOrCreateStorageArea(WTFMove(securityOriginData)); storageArea->addListener(connection, storageMapID); slot = WTFMove(storageArea); } void StorageManager::destroyStorageMap(IPC::Connection& connection, uint64_t storageMapID) { std::pair<RefPtr<IPC::Connection>, uint64_t> connectionAndStorageMapIDPair(&connection, storageMapID); // FIXME: This should be a message check. ASSERT(m_storageAreasByConnection.isValidKey(connectionAndStorageMapIDPair)); auto it = m_storageAreasByConnection.find(connectionAndStorageMapIDPair); if (it == m_storageAreasByConnection.end()) { // The connection has been removed because the last page was closed. return; } it->value->removeListener(connection, storageMapID); // Don't remove session storage maps. The web process may reconnect and expect the data to still be around. if (it->value->isSessionStorage()) return; m_storageAreasByConnection.remove(connectionAndStorageMapIDPair); } void StorageManager::getValues(IPC::Connection& connection, uint64_t storageMapID, uint64_t storageMapSeed, HashMap<String, String>& values) { StorageArea* storageArea = findStorageArea(connection, storageMapID); if (!storageArea) { // This is a session storage area for a page that has already been closed. Ignore it. return; } values = storageArea->items(); connection.send(Messages::StorageAreaMap::DidGetValues(storageMapSeed), storageMapID); } void StorageManager::setItem(IPC::Connection& connection, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& key, const String& value, const String& urlString) { StorageArea* storageArea = findStorageArea(connection, storageMapID); if (!storageArea) { // This is a session storage area for a page that has already been closed. Ignore it. return; } bool quotaError; storageArea->setItem(&connection, sourceStorageAreaID, key, value, urlString, quotaError); connection.send(Messages::StorageAreaMap::DidSetItem(storageMapSeed, key, quotaError), storageMapID); } void StorageManager::removeItem(IPC::Connection& connection, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& key, const String& urlString) { StorageArea* storageArea = findStorageArea(connection, storageMapID); if (!storageArea) { // This is a session storage area for a page that has already been closed. Ignore it. return; } storageArea->removeItem(&connection, sourceStorageAreaID, key, urlString); connection.send(Messages::StorageAreaMap::DidRemoveItem(storageMapSeed, key), storageMapID); } void StorageManager::clear(IPC::Connection& connection, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& urlString) { StorageArea* storageArea = findStorageArea(connection, storageMapID); if (!storageArea) { // This is a session storage area for a page that has already been closed. Ignore it. return; } storageArea->clear(&connection, sourceStorageAreaID, urlString); connection.send(Messages::StorageAreaMap::DidClear(storageMapSeed), storageMapID); } void StorageManager::applicationWillTerminate() { BinarySemaphore semaphore; m_queue->dispatch([this, &semaphore] { Vector<std::pair<RefPtr<IPC::Connection>, uint64_t>> connectionAndStorageMapIDPairsToRemove; for (auto& connectionStorageAreaPair : m_storageAreasByConnection) { connectionStorageAreaPair.value->removeListener(*connectionStorageAreaPair.key.first, connectionStorageAreaPair.key.second); connectionAndStorageMapIDPairsToRemove.append(connectionStorageAreaPair.key); } for (auto& connectionStorageAreaPair : connectionAndStorageMapIDPairsToRemove) m_storageAreasByConnection.remove(connectionStorageAreaPair); semaphore.signal(); }); semaphore.wait(WallTime::infinity()); } StorageManager::StorageArea* StorageManager::findStorageArea(IPC::Connection& connection, uint64_t storageMapID) const { std::pair<IPC::Connection*, uint64_t> connectionAndStorageMapIDPair(&connection, storageMapID); if (!m_storageAreasByConnection.isValidKey(connectionAndStorageMapIDPair)) return nullptr; return m_storageAreasByConnection.get(connectionAndStorageMapIDPair); } StorageManager::LocalStorageNamespace* StorageManager::getOrCreateLocalStorageNamespace(uint64_t storageNamespaceID) { if (!m_localStorageNamespaces.isValidKey(storageNamespaceID)) return nullptr; auto& slot = m_localStorageNamespaces.add(storageNamespaceID, nullptr).iterator->value; if (!slot) slot = LocalStorageNamespace::create(this, storageNamespaceID); return slot.get(); } StorageManager::TransientLocalStorageNamespace* StorageManager::getOrCreateTransientLocalStorageNamespace(uint64_t storageNamespaceID, WebCore::SecurityOriginData&& topLevelOrigin) { if (!m_transientLocalStorageNamespaces.isValidKey({ storageNamespaceID, topLevelOrigin })) return nullptr; auto& slot = m_transientLocalStorageNamespaces.add({ storageNamespaceID, WTFMove(topLevelOrigin) }, nullptr).iterator->value; if (!slot) slot = TransientLocalStorageNamespace::create(); return slot.get(); } } // namespace WebKit
40.274083
226
0.749822
ijsf
b0cb1dd84798548af5cb2e00bdcf13311013f1ed
1,419
hpp
C++
source/framework/core/include/lue/framework/core/debug.hpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
2
2021-02-26T22:45:56.000Z
2021-05-02T10:28:48.000Z
source/framework/core/include/lue/framework/core/debug.hpp
pcraster/lue
e64c18f78a8b6d8a602b7578a2572e9740969202
[ "MIT" ]
262
2016-08-11T10:12:02.000Z
2020-10-13T18:09:16.000Z
source/framework/core/include/lue/framework/core/debug.hpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
1
2020-03-11T09:49:41.000Z
2020-03-11T09:49:41.000Z
#pragma once #include <hpx/future.hpp> #include <fmt/format.h> #include <string> namespace lue { hpx::future<std::string> system_description(); void write_debug_message (std::string const& message); template< typename Class> std::string describe (Class const& instance); template< typename Count, typename Idx> void validate_idxs( Count const* count, Idx const idx) { if(idx >= *count) { throw std::runtime_error(fmt::format( "Index out of bounds ({} >= {})", idx, *count)); } } template< typename Count, typename Idx, typename... Idxs> void validate_idxs( Count* count, Idx const idx, Idxs... idxs) { if(idx >= *count) { throw std::runtime_error(fmt::format( "Index out of bounds ({} >= {})", idx, *count)); } validate_idxs(++count, idxs...); } template< typename Shape, typename... Idxs> void validate_idxs( Shape const& shape, Idxs... idxs) { if(sizeof...(idxs) != std::size(shape)) { throw std::runtime_error(fmt::format( "Number of indices does not match rank of array ({} != {})", sizeof...(idxs), std::size(shape))); } // Verify each index is within the extent of the corresponding // array extent validate_idxs(shape.data(), idxs...); } } // namespace lue
19.175676
72
0.569415
computationalgeography
b0cc3f4253c3add683bfa3768d9ed44bcf883f99
279
cpp
C++
CPP/HelloCpp2/chapter_20/Inheritance2.cpp
hrntsm/study-language
922578a5321d70c26b935e6052f400125e15649c
[ "MIT" ]
1
2022-02-06T10:50:42.000Z
2022-02-06T10:50:42.000Z
CPP/HelloCpp2/chapter_20/Inheritance2.cpp
hrntsm/study-language
922578a5321d70c26b935e6052f400125e15649c
[ "MIT" ]
null
null
null
CPP/HelloCpp2/chapter_20/Inheritance2.cpp
hrntsm/study-language
922578a5321d70c26b935e6052f400125e15649c
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; class Kitty { public: void nyan() { cout << "Kitty on your lap\n";} }; class Di_Gi_Gharat : public Kitty{ public: void nyan() {cout << "Di Gi Gharat\n";} } obj; int main(){ obj.nyan(); obj.Kitty::nyan(); return 0; }
14.684211
49
0.602151
hrntsm
b0cc4ae220c4645885fe9741eae45887b880a64f
4,321
cpp
C++
Source/10.0.18362.0/ucrt/mbstring/mbsnbicm.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
2
2021-01-27T10:19:30.000Z
2021-02-09T06:24:30.000Z
Source/10.0.18362.0/ucrt/mbstring/mbsnbicm.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
null
null
null
Source/10.0.18362.0/ucrt/mbstring/mbsnbicm.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
1
2021-01-27T10:19:36.000Z
2021-01-27T10:19:36.000Z
/*** *mbsnbicmp.c - Compare n bytes of strings, ignoring case (MBCS) * * Copyright (c) Microsoft Corporation. All rights reserved. * *Purpose: * Compare n bytes of strings, ignoring case (MBCS) * *******************************************************************************/ #ifndef _MBCS #error This file should only be compiled with _MBCS defined #endif #include <corecrt_internal_mbstring.h> #include <locale.h> #include <string.h> #pragma warning(disable:__WARNING_POTENTIAL_BUFFER_OVERFLOW_NULLTERMINATED) // 26018 /*** * _mbsnbicmp - Compare n bytes of strings, ignoring case (MBCS) * *Purpose: * Compares up to n bytes of two strings for ordinal order. * Strings are compared on a character basis, not a byte basis. * Case of characters is not considered. * *Entry: * unsigned char *s1, *s2 = strings to compare * size_t n = maximum number of bytes to compare * *Exit: * Returns <0 if s1 < s2 * Returns 0 if s1 == s2 * Returns >0 if s1 > s2 * Returns _NLSCMPERROR is something went wrong * *Exceptions: * Input parameters are validated. Refer to the validation section of the function. * *******************************************************************************/ int __cdecl _mbsnbicmp_l( const unsigned char *s1, const unsigned char *s2, size_t n, _locale_t plocinfo ) { unsigned short c1, c2; _LocaleUpdate _loc_update(plocinfo); if (n==0) return(0); if (_loc_update.GetLocaleT()->mbcinfo->ismbcodepage == 0) return _strnicmp((const char *)s1, (const char *)s2, n); /* validation section */ _VALIDATE_RETURN(s1 != nullptr, EINVAL, _NLSCMPERROR); _VALIDATE_RETURN(s2 != nullptr, EINVAL, _NLSCMPERROR); while (n--) { c1 = *s1++; if ( _ismbblead_l(c1, _loc_update.GetLocaleT()) ) { if (n==0) { c1 = 0; /* 'naked' lead - end of string */ c2 = _ismbblead_l(*s2, _loc_update.GetLocaleT()) ? 0 : *s2; goto test; } if (*s1 == '\0') c1 = 0; else { c1 = ((c1<<8) | *s1++); if ( ((c1 >= _MBUPPERLOW1_MT(_loc_update.GetLocaleT())) && (c1 <= _MBUPPERHIGH1_MT(_loc_update.GetLocaleT()))) ) c1 += _MBCASEDIFF1_MT(_loc_update.GetLocaleT()); else if ( ((c1 >= _MBUPPERLOW2_MT(_loc_update.GetLocaleT())) && (c1 <= _MBUPPERHIGH2_MT(_loc_update.GetLocaleT()))) ) c1 += _MBCASEDIFF2_MT(_loc_update.GetLocaleT()); } } else c1 = _mbbtolower_l(c1, _loc_update.GetLocaleT()); c2 = *s2++; if ( _ismbblead_l(c2, _loc_update.GetLocaleT()) ) { if (n==0) { c2 = 0; /* 'naked' lead - end of string */ goto test; } n--; if (*s2 == '\0') c2 = 0; else { c2 = ((c2<<8) | *s2++); if ( ((c2 >= _MBUPPERLOW1_MT(_loc_update.GetLocaleT())) && (c2 <= _MBUPPERHIGH1_MT(_loc_update.GetLocaleT()))) ) c2 += _MBCASEDIFF1_MT(_loc_update.GetLocaleT()); else if ( ((c2 >= _MBUPPERLOW2_MT(_loc_update.GetLocaleT())) && (c2 <= _MBUPPERHIGH2_MT(_loc_update.GetLocaleT()))) ) c2 += _MBCASEDIFF2_MT(_loc_update.GetLocaleT()); } } else c2 = _mbbtolower_l(c2, _loc_update.GetLocaleT()); test: if (c1 != c2) return( (c1 > c2) ? 1 : -1); if (c1 == 0) return(0); } return(0); } int (__cdecl _mbsnbicmp)( const unsigned char *s1, const unsigned char *s2, size_t n ) { return _mbsnbicmp_l(s1, s2, n, nullptr); }
32.246269
88
0.466559
825126369
b0db5924fca9ef1988ac57895c13e266691e9fae
1,684
cpp
C++
Samples/SampleEditorUI/SampleEditorUI.cpp
AlexSabourinDev/IceBox
9226e15fc5e78e68c0d92ceea51996fdeab36ca7
[ "MIT" ]
3
2020-09-22T15:56:07.000Z
2022-02-08T23:54:50.000Z
Samples/SampleEditorUI/SampleEditorUI.cpp
AlexSabourinDev/IceBox
9226e15fc5e78e68c0d92ceea51996fdeab36ca7
[ "MIT" ]
37
2020-09-21T17:00:17.000Z
2022-02-10T00:30:59.000Z
Samples/SampleEditorUI/SampleEditorUI.cpp
AlexSabourinDev/IceBox
9226e15fc5e78e68c0d92ceea51996fdeab36ca7
[ "MIT" ]
3
2020-10-04T00:46:31.000Z
2022-02-09T00:05:36.000Z
#include <IBEngine/IBRenderer.h> #include <IBEngine/IBRendererFrontend.h> #include <IBEngine/IBSerialization.h> #include <IBEngine/IBLogging.h> #include <IBEngine/IBPlatform.h> #include <imgui/imgui.h> int main() { IB::WindowDesc winDesc = {}; winDesc.Name = "Ice Box"; winDesc.Width = 1024; winDesc.Height = 720; winDesc.OnWindowMessage = [](void *data, IB::WindowMessage message, IB::WindowMessagePlatformData const* platformData) { if (IB::imGuiPlatformMessage(platformData)) { return true; } switch (message.Type) { case IB::WindowMessage::Close: IB::sendQuitMessage(); return true; } return false;; }; IB::Window::Handle window = IB::createWindow(winDesc); IB::RendererDesc rendererDesc = {}; rendererDesc.Window = window; IB::initRenderer(rendererDesc); IB::PlatformMessage message = IB::PlatformMessage::None; while (message != IB::PlatformMessage::Quit) { IB::consumeMessageQueue([](void *data, IB::PlatformMessage message) { *reinterpret_cast<IB::PlatformMessage *>(data) = message; }, &message); IB::newImGuiFrame(); ImGui::Begin("Hello, world!"); ImGui::Text("This is some useful text."); ImGui::End(); ImGui::Render(); IB::ViewDesc viewDesc = {}; // TODO: Call imGui::CloneOutput instead of ImGui::GetDrawData in order to double buffer our rendering. viewDesc.ImGuiDrawData = ImGui::GetDrawData(); IB::drawView(viewDesc); } IB::killRenderer(); IB::destroyWindow(window); }
26.730159
122
0.610451
AlexSabourinDev
b0e087b548cb6df0d04f44e3f91c2daa82296873
438
cpp
C++
src/publisher/distributions_publisher.cpp
doge-of-the-day/cslibs_mapping
f8c9790ef0148c26792ad5af7086db792f693955
[ "BSD-3-Clause" ]
36
2018-11-13T09:45:17.000Z
2022-01-04T00:46:45.000Z
src/publisher/distributions_publisher.cpp
doge-of-the-day/cslibs_mapping
f8c9790ef0148c26792ad5af7086db792f693955
[ "BSD-3-Clause" ]
7
2019-04-29T08:15:19.000Z
2022-02-20T17:07:09.000Z
src/publisher/distributions_publisher.cpp
doge-of-the-day/cslibs_mapping
f8c9790ef0148c26792ad5af7086db792f693955
[ "BSD-3-Clause" ]
19
2018-05-19T06:45:49.000Z
2022-01-04T00:46:50.000Z
#include "distributions_publisher.h" #include <class_loader/register_macro.hpp> CLASS_LOADER_REGISTER_CLASS(cslibs_mapping::publisher::DistributionsPublisher, cslibs_mapping::publisher::Publisher) CLASS_LOADER_REGISTER_CLASS(cslibs_mapping::publisher::DistributionsPublisher_d, cslibs_mapping::publisher::Publisher) CLASS_LOADER_REGISTER_CLASS(cslibs_mapping::publisher::DistributionsPublisher_f, cslibs_mapping::publisher::Publisher)
62.571429
118
0.874429
doge-of-the-day
b0e6163b32274371f06357425c6645c9ce4a2eda
5,262
cpp
C++
src/Orbit/Graphics/Geometry/Mesh.cpp
Gaztin/Orb
4589f3f0165d287482ab4b367f02633ea4e7c9a5
[ "Zlib" ]
41
2018-08-02T06:28:07.000Z
2022-01-20T01:23:42.000Z
src/Orbit/Graphics/Geometry/Mesh.cpp
Gaztin/Orb
4589f3f0165d287482ab4b367f02633ea4e7c9a5
[ "Zlib" ]
4
2020-02-11T22:10:31.000Z
2020-07-06T19:36:09.000Z
src/Orbit/Graphics/Geometry/Mesh.cpp
Gaztin/Orb
4589f3f0165d287482ab4b367f02633ea4e7c9a5
[ "Zlib" ]
4
2018-11-18T10:19:57.000Z
2021-07-14T02:58:40.000Z
/* * Copyright (c) 2020 Sebastian Kylander https://gaztin.com/ * * This software is provided 'as-is', without any express or implied warranty. In no event will * the authors be held liable for any damages arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, including commercial * applications, and to alter it and redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not claim that you wrote the * original software. If you use this software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be misrepresented as * being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "Mesh.h" #include "Orbit/Core/Utility/Utility.h" #include "Orbit/Graphics/API/OpenGL/OpenGLFunctions.h" #include "Orbit/Graphics/Context/RenderContext.h" #include "Orbit/Graphics/Geometry/Geometry.h" ORB_NAMESPACE_BEGIN Mesh::Mesh( std::string_view name ) : name_( name ) { } Geometry Mesh::ToGeometry( void ) const { Geometry geometry( vertex_layout_ ); auto& vb_details = vertex_buffer_->GetDetails(); switch( vb_details.index() ) { #if( ORB_HAS_D3D11 ) case( unique_index_v< Private::_VertexBufferDetailsD3D11, Private::VertexBufferDetails > ): { auto& context = std::get< Private::_RenderContextDetailsD3D11 >( RenderContext::GetInstance().GetPrivateDetails() ); auto& vb_d3d11 = std::get< Private::_VertexBufferDetailsD3D11 >( vb_details ); D3D11_BUFFER_DESC temp_vb_desc; D3D11_MAPPED_SUBRESOURCE temp_vb_mapped; ComPtr< ID3D11Buffer > temp_vb; vb_d3d11.buffer->GetDesc( &temp_vb_desc ); temp_vb_desc.Usage = D3D11_USAGE_DEFAULT; temp_vb_desc.BindFlags = D3D11_BIND_UNORDERED_ACCESS; temp_vb_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; context.device->CreateBuffer( &temp_vb_desc, nullptr, &temp_vb.ptr_ ); context.device_context->CopyResource( temp_vb.ptr_, vb_d3d11.buffer.ptr_ ); context.device_context->Map( temp_vb.ptr_, 0, D3D11_MAP_READ, 0, &temp_vb_mapped ); ////////////////////////////////////////////////////////////////////////// if( index_buffer_ ) { auto& ib_d3d11 = std::get< Private::_IndexBufferDetailsD3D11 >( index_buffer_->GetDetails() ); D3D11_BUFFER_DESC temp_ib_desc; D3D11_MAPPED_SUBRESOURCE temp_ib_mapped; ComPtr< ID3D11Buffer > temp_ib; ib_d3d11.buffer->GetDesc( &temp_ib_desc ); temp_ib_desc.Usage = D3D11_USAGE_DEFAULT; temp_ib_desc.BindFlags = D3D11_BIND_UNORDERED_ACCESS; temp_ib_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; context.device->CreateBuffer( &temp_ib_desc, nullptr, &temp_ib.ptr_ ); context.device_context->CopyResource( temp_ib.ptr_, ib_d3d11.buffer.ptr_ ); context.device_context->Map( temp_ib.ptr_, 0, D3D11_MAP_READ, 0, &temp_ib_mapped ); // Supply geometry with vertex and index data geometry.SetFromData( { static_cast< const uint8_t* >( temp_vb_mapped.pData ), vertex_buffer_->GetTotalSize() }, { static_cast< const uint8_t* >( temp_ib_mapped.pData ), index_buffer_->GetSize() }, index_buffer_->GetFormat() ); context.device_context->Unmap( temp_ib.ptr_, 0 ); } else { // Supply geometry with just vertex data geometry.SetFromData( { static_cast< const uint8_t* >( temp_vb_mapped.pData ), temp_vb_desc.ByteWidth } ); } context.device_context->Unmap( temp_vb.ptr_, 0 ); } break; #endif // ORB_HAS_D3D11 #if( ORB_HAS_OPENGL ) case( unique_index_v< Private::_VertexBufferDetailsOpenGL, Private::VertexBufferDetails > ): { auto& vb_opengl = std::get< Private::_VertexBufferDetailsOpenGL >( vb_details ); const size_t vb_size = ( vertex_buffer_->GetCount() * vertex_layout_.GetStride() ); glBindBuffer( OpenGLBufferTarget::Array, vb_opengl.id ); const void* vb_src = glMapBufferRange( OpenGLBufferTarget::Array, 0, vb_size, OpenGLMapAccess::ReadBit ); if( index_buffer_ ) { auto& ib_opengl = std::get< Private::_IndexBufferDetailsOpenGL >( index_buffer_->GetDetails() ); const size_t ib_size = index_buffer_->GetSize(); glBindBuffer( OpenGLBufferTarget::ElementArray, ib_opengl.id ); const void* ib_src = glMapBufferRange( OpenGLBufferTarget::ElementArray, 0, ib_size, OpenGLMapAccess::ReadBit ); // Supply geometry with vertex and index data geometry.SetFromData( { static_cast< const uint8_t* >( vb_src ), vb_size }, { static_cast< const uint8_t* >( ib_src ), ib_size }, index_buffer_->GetFormat() ); glUnmapBuffer( OpenGLBufferTarget::ElementArray ); glBindBuffer( OpenGLBufferTarget::ElementArray, 0 ); } else { // Supply geometry with just vertex data geometry.SetFromData( { static_cast< const uint8_t* >( vb_src ), vb_size } ); } glUnmapBuffer( OpenGLBufferTarget::Array ); glBindBuffer( OpenGLBufferTarget::Array, 0 ); } break; #endif // ORB_HAS_OPENGL } return geometry; } ORB_NAMESPACE_END
38.691176
231
0.710376
Gaztin
b0e83b9727f6a352103a42c6c52790b966114a8e
11,662
cpp
C++
src/EOIconManager.cpp
obones/EVEopenHAB
8e1c603e0c4ebf2b108685dbf5548e3a17a1561c
[ "MIT" ]
null
null
null
src/EOIconManager.cpp
obones/EVEopenHAB
8e1c603e0c4ebf2b108685dbf5548e3a17a1561c
[ "MIT" ]
null
null
null
src/EOIconManager.cpp
obones/EVEopenHAB
8e1c603e0c4ebf2b108685dbf5548e3a17a1561c
[ "MIT" ]
null
null
null
/* @file EOIconManager.cpp @brief Contains the Icon manager definitions @date 2021-09-17 @author Olivier Sannier @section LICENSE MIT License Copyright (c) 2021 Olivier Sannier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <esp32HTTPrequest.h> #include <EVE.h> #include "EOIconManager.h" #include "EOSettings.h" #include "EOConstants.h" #include "EODownloadManager.h" #include "reload_color.png.h" #define ICON_HEIGHT 64 #define ICON_WIDTH 64 #define ICON_BYTES_PER_PIXEL 2 #define ICON_BYTE_COUNT (ICON_WIDTH * ICON_HEIGHT * ICON_BYTES_PER_PIXEL) // We are loading PNG files and the datasheet clearly states that the top 42K of RAM_G will be used as a temporary buffer #define RAM_G_MAX_USABLE_ADDRESS (EVE_RAM_G + EVE_RAM_G_SIZE - 42*1024) #define RAM_G_BOTTOM 0 namespace EVEopenHAB { IconManager::IconManager() { reloadIconAddress = RAM_G_MAX_USABLE_ADDRESS - reload_color_png_byte_count; } void IconManager::MainLoop() { if (!staticIconsLoaded) { EVE_cmd_loadimage(reloadIconAddress, EVE_OPT_NODL, reload_color_png, sizeof(reload_color_png)); staticIconsLoaded = true; } startRetrieval(); { std::lock_guard<std::mutex> lock(recordsMutex); for (int recordIndex = 0; recordIndex < records.size(); recordIndex++) { iconRecord& record = records[recordIndex]; switch (record.bitmapState) { case BitmapState::Allocated: if (record.buffer == nullptr) { /*Serial.print("Setting memory for "); Serial.print(recordIndex); Serial.print(" - address = "); Serial.print(record.address); Serial.print(" - byte count = "); Serial.print(ICON_BYTE_COUNT); Serial.println();*/ //EVE_cmd_memzero(record.address, ICON_BYTE_COUNT); EVE_cmd_memset(record.address, 0xF0, ICON_BYTE_COUNT); while (EVE_busy()); record.bitmapState = BitmapState::Initialized; break; } // break is inside the test because if record.buffer is already available, we want to // fall through the call to load image, saving a useless call to memzero case BitmapState::Initialized: if (record.buffer != nullptr) { /*Serial.print("Loading image for "); Serial.print(recordIndex); Serial.print(" - address = "); Serial.print(record.address); Serial.println();*/ EVE_cmd_loadimage(record.address, EVE_OPT_NODL, record.buffer, record.bufferLength); record.bitmapState = BitmapState::Loaded; // Release memory now that the image is transferred to EVE, use a local reference to avoid having record.buffer point to deleted memory uint8_t* buffer = record.buffer; record.buffer = nullptr; delete buffer; } break; case BitmapState::Loaded: break; // nothing, the image has already been transferred and loaded via LOADIMAGE } } } } void IconManager::Reset() { for (int recordIndex = 0; recordIndex < records.size(); recordIndex++) { iconRecord& record = records[recordIndex]; delete(record.buffer); } records.clear(); } IconManager* IconManager::Instance() { static IconManager instance; return &instance; } void iconRequestReadyStateChange(void* optParm, esp32HTTPrequest* request, int readyState) { if (readyState == 4) { /*Serial.println(F("Received a response, processing...")); Serial.print(F(" HTTP response code: ")); Serial.println(request->responseHTTPcode());*/ request->setDebug(false); IconManager* manager = static_cast<IconManager*>(optParm); if (request->responseHTTPcode() == 200) { Serial.println("Icon download success"); std::lock_guard<std::mutex> lock(manager->recordsMutex); IconManager::iconRecord& record = manager->records[manager->indexBeingRetrieved]; record.bufferLength = request->available(); uint8_t *localBuffer = new byte[record.bufferLength]; /*Serial.print(F(" For record ")); Serial.print(manager->indexBeingRetrieved); Serial.print(F(" - name = ")); Serial.print(record.name); Serial.println(); Serial.print(F(" Buffer length = ")); Serial.print(record.bufferLength); Serial.println();*/ request->responseRead(localBuffer, record.bufferLength); record.buffer = localBuffer; } else { Serial.printf("Icon download failed: %d\r\n", request->responseHTTPcode()); } manager->indexBeingRetrieved = -1; } } void IconManager::startRetrieval() { int recordIndex = 0; while (indexBeingRetrieved < 0 && recordIndex < records.size()) { { std::lock_guard<std::mutex> lock(recordsMutex); iconRecord& record = records[recordIndex]; if (record.buffer == nullptr && record.bitmapState < BitmapState::Loaded) { //Serial.printf("--> no buffer for record, preparing request (%d will be %d)\r\n", indexBeingRetrieved, recordIndex); indexBeingRetrieved = recordIndex; String url = BASE_URL; url += "/icon/"; url += record.name; url += "?state="; url += record.state; url += "&format=png&iconset="; url += ICON_SET_NAME; Serial.print("Requesting icon url = "); Serial.println(url); DownloadManager::Instance().Enqueue(url, iconRequestReadyStateChange, this); } } recordIndex++; } } int8_t IconManager::GetIconIndex(const char* name, const char* state) { /*Serial.print("Getting icon index for name = "); Serial.print(reinterpret_cast<uint32_t>(name)); Serial.print(" - state = "); Serial.print(reinterpret_cast<uint32_t>(state)); Serial.println();*/ int8_t result = -1; { std::lock_guard<std::mutex> lock(recordsMutex); // Try to find a preexisting icon for (int recordIndex = 0; recordIndex < records.size(); recordIndex++) { iconRecord& record = records[recordIndex]; if (strcmp(record.name, name) == 0 && strcmp(record.state, state) == 0) return recordIndex + 1; } // If not found, allocate a new one, downards from the top of RAM_G //uint32_t newAddress = RAM_G_MAX_USABLE_ADDRESS - ICON_BYTE_COUNT * (records.size() + 1); // If not found, allocate a new, upwards from the bottom of RAM_G uint32_t newAddress = RAM_G_BOTTOM + ICON_BYTE_COUNT * records.size(); records.push_back( { .name = name, .state = state, .address = newAddress, .buffer = nullptr, .bufferLength = 0, .bitmapState = BitmapState::Allocated } ); result = records.size(); } startRetrieval(); return result; } uint32_t IconManager::GetAddress(int8_t index) { std::lock_guard<std::mutex> lock(recordsMutex); if (index > 0 && index <= records.size()) { iconRecord& record = records[index - 1]; return record.address; } else return 0; } void IconManager::BurstIcon(int8_t index, int16_t x, int16_t y) { std::lock_guard<std::mutex> lock(recordsMutex); if (index > 0 && index <= records.size()) { iconRecord& record = records[index - 1]; /*Serial.print("Bursting icon "); Serial.print(index); Serial.print(" - address = "); Serial.print(record.address); Serial.print(" - at "); Serial.print(x); Serial.print(" ; "); Serial.print(y); Serial.println();*/ EVE_cmd_dl_burst(BITMAP_HANDLE(index)); EVE_cmd_dl_burst(BITMAP_LAYOUT(EVE_ARGB4, ICON_WIDTH * ICON_BYTES_PER_PIXEL, ICON_HEIGHT)); EVE_cmd_dl_burst(BITMAP_SOURCE(record.address)); EVE_cmd_dl_burst(BITMAP_SIZE(EVE_NEAREST, EVE_BORDER, EVE_BORDER, ICON_WIDTH, ICON_HEIGHT)); EVE_cmd_dl_burst(DL_COLOR_RGB | WHITE); EVE_cmd_dl_burst(COLOR_A(255)); EVE_cmd_dl_burst(DL_BEGIN | EVE_BITMAPS); EVE_cmd_dl_burst(VERTEX2F(x, y)); EVE_cmd_dl_burst(DL_END); EVE_cmd_dl_burst(BITMAP_HANDLE(0)); } } uint32_t IconManager::GetReloadIconAddress() const { return reloadIconAddress; } void IconManager::BurstReloadIcon(int16_t x, int16_t y) { EVE_cmd_dl_burst(BITMAP_HANDLE(15)); EVE_cmd_dl_burst(BITMAP_LAYOUT(reload_color_png_format, reload_color_png_width * reload_color_png_bytes_per_pixel, reload_color_png_height)); EVE_cmd_dl_burst(BITMAP_SOURCE(reloadIconAddress)); EVE_cmd_dl_burst(BITMAP_SIZE(EVE_NEAREST, EVE_BORDER, EVE_BORDER, reload_color_png_width, reload_color_png_height)); EVE_cmd_dl_burst(DL_COLOR_RGB | WHITE); EVE_cmd_dl_burst(COLOR_A(255)); EVE_cmd_dl_burst(DL_BEGIN | EVE_BITMAPS); EVE_cmd_dl_burst(VERTEX2F(x, y)); EVE_cmd_dl_burst(DL_END); EVE_cmd_dl_burst(BITMAP_HANDLE(0)); } }
38.361842
166
0.56877
obones
b0f3f757c800a88e77992bee09870e2a61d29e1a
919
cpp
C++
Engine/Core/Sources/Threading/Thread.cpp
kaluginadaria/YetAnotherProject
abedd20b484f868ded83e72261970703a27e024d
[ "MIT" ]
null
null
null
Engine/Core/Sources/Threading/Thread.cpp
kaluginadaria/YetAnotherProject
abedd20b484f868ded83e72261970703a27e024d
[ "MIT" ]
null
null
null
Engine/Core/Sources/Threading/Thread.cpp
kaluginadaria/YetAnotherProject
abedd20b484f868ded83e72261970703a27e024d
[ "MIT" ]
null
null
null
#include "Thread.hpp" #include <chrono> #include <iostream> #include "ThreadPool.hpp" const ThreadTask ThreadTask::NoTasksFound = ThreadTask(nullptr, ThreadTask::eNoTasksFound); const ThreadTask ThreadTask::ShouldDie = ThreadTask(nullptr, ThreadTask::eShouldDie ); const ThreadTask ThreadTask::NextLoop = ThreadTask(nullptr, ThreadTask::eNextLoop ); UNIQUE(Thread) Thread::Get() { return std::make_unique<Thread>(); } ThreadID Thread::GetThreadID() { return std::this_thread::get_id(); } void Thread::Run() { std::thread([&]() { using namespace std::chrono_literals; ThreadTask currentTask = ThreadTask::NextLoop; while ((currentTask = ThreadPool::GetRunTask(this, currentTask.task)) != ThreadTask::ShouldDie) { // try to take a new task if (currentTask.task == nullptr) { std::this_thread::sleep_for(5us); continue; } currentTask.task->Run(); } }).detach(); }
22.414634
97
0.70185
kaluginadaria
b0f4c4427b61d94ca4b0c9f66aedb58a2a93a545
4,264
cc
C++
code/render/frame/framepass.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
67
2015-03-30T19:56:16.000Z
2022-03-11T13:52:17.000Z
code/render/frame/framepass.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
5
2015-04-15T17:17:33.000Z
2016-02-11T00:40:17.000Z
code/render/frame/framepass.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
34
2015-03-30T15:08:00.000Z
2021-09-23T05:55:10.000Z
//------------------------------------------------------------------------------ // framepass.cc // (C) 2007 Radon Labs GmbH // (C) 2013-2016 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "stdneb.h" #include "frame/framepass.h" #include "coregraphics/renderdevice.h" namespace Frame { __ImplementClass(Frame::FramePass, 'FPSS', Frame::FramePassBase); using namespace CoreGraphics; //------------------------------------------------------------------------------ /** */ FramePass::FramePass() { // empty } //------------------------------------------------------------------------------ /** */ FramePass::~FramePass() { // empty } //------------------------------------------------------------------------------ /** */ void FramePass::Discard() { FramePassBase::Discard(); #if NEBULA3_ENABLE_PROFILING _discard_timer(debugTimer); #endif } //------------------------------------------------------------------------------ /** */ void FramePass::Render(IndexT frameIndex) { #if NEBULA3_ENABLE_PROFILING _start_timer(this->debugTimer); #endif n_assert(this->renderTarget.isvalid() || this->multipleRenderTarget.isvalid() || this->renderTargetCube.isvalid()); RenderDevice* renderDevice = RenderDevice::Instance(); if (this->renderTarget.isvalid()) { n_assert(!this->multipleRenderTarget.isvalid()); n_assert(!this->renderTargetCube.isvalid()); // update render targets this->renderTarget->SetClearFlags(this->clearFlags); this->renderTarget->SetClearDepth(this->clearDepth); this->renderTarget->SetClearStencil(this->clearStencil); this->renderTarget->SetClearColor(this->clearColor); } else if (this->renderTargetCube.isvalid()) { n_assert(!this->renderTarget.isvalid()); n_assert(!this->multipleRenderTarget.isvalid()); // update render targets this->renderTargetCube->SetClearFlags(this->clearFlags); this->renderTargetCube->SetClearDepth(this->clearDepth); this->renderTargetCube->SetClearStencil(this->clearStencil); this->renderTargetCube->SetClearColor(this->clearColor); } else if (this->multipleRenderTarget.isvalid()) { // ignore clear flags n_assert(!this->renderTarget.isvalid()); n_assert(!this->renderTargetCube.isvalid()); } // begin updating global shader state if (this->shader.isvalid()) this->shader->BeginUpdate(); // apply shader variables IndexT varIndex; for (varIndex = 0; varIndex < this->shaderVariables.Size(); varIndex++) { this->shaderVariables[varIndex]->Apply(); } // bind render target, either 2D, MRT, or Cube if (this->renderTarget.isvalid()) { n_assert(!this->multipleRenderTarget.isvalid()); n_assert(!this->renderTargetCube.isvalid()); renderDevice->BeginPass(this->renderTarget, this->shader); } else if (this->multipleRenderTarget.isvalid()) { n_assert(!this->renderTarget.isvalid()); n_assert(!this->renderTargetCube.isvalid()); renderDevice->BeginPass(this->multipleRenderTarget, this->shader); } else if (this->renderTargetCube.isvalid()) { n_assert(!this->renderTarget.isvalid()); n_assert(!this->multipleRenderTarget.isvalid()); renderDevice->BeginPass(this->renderTargetCube, this->shader); } else { n_error("FramePass::Render() : No render targets assigned!"); } if (this->shader.isvalid()) this->shader->EndUpdate(); // render batches... IndexT batchIndex; for (batchIndex = 0; batchIndex < this->batches.Size(); batchIndex++) { FRAME_LOG(" FramePass::Render() %s batch: %d", this->GetName().AsString().AsCharPtr(), batchIndex); this->batches[batchIndex]->Render(frameIndex); FRAME_LOG(" "); } renderDevice->EndPass(); #if NEBULA3_ENABLE_PROFILING _stop_timer(this->debugTimer); #endif } //------------------------------------------------------------------------------ /** */ #if NEBULA3_ENABLE_PROFILING void FramePass::SetFramePassDebugTimer(const Util::String& name) { this->debugTimer = Debug::DebugTimer::Create(); this->debugTimer->Setup(name, "Frame shaders"); } #endif } // namespace Frame
28.810811
119
0.593105
gscept
b0fd829d724b15a07c5ecd6beb1d8c252f061e2c
1,396
hpp
C++
Engine/Math/Dice.hpp
achen889/Warlockery_Engine
160a14e85009057f4505ff5380a8c17258698f3e
[ "MIT" ]
null
null
null
Engine/Math/Dice.hpp
achen889/Warlockery_Engine
160a14e85009057f4505ff5380a8c17258698f3e
[ "MIT" ]
null
null
null
Engine/Math/Dice.hpp
achen889/Warlockery_Engine
160a14e85009057f4505ff5380a8c17258698f3e
[ "MIT" ]
null
null
null
//============================================================================================================== //Dice.hpp //by Albert Chen Sep-2-2015. //============================================================================================================== #pragma once #ifndef _included_Dice__ #define _included_Dice__ #include "IntVec3.hpp" #include "Engine/Core/Utilities.hpp" #include "MathUtils.hpp" //typedef IntVec3 Dice; //x for number of dice, y for size of dice (1-y), z for modifier //dice utility functions struct Dice { //vars IntVec3 diceDef; //operator overload Dice() { //do nothing } Dice(const std::string& diceString); const Dice& operator=(const std::string& diceStrToAssign); const int RollDice() const ; const std::string ToString() { return Stringf("%dd%d+%d", diceDef.x, diceDef.y, diceDef.z); } }; //=========================================================================================================== ///---------------------------------------------------------------------------------------------------------- ///globals int RollDice(const Dice& dice); int RollDice(const std::string& diceString); std::string DiceToString(const Dice& dice); Dice ParseStringToDice(const std::string& diceString); //=========================================================================================================== #endif
22.885246
112
0.424785
achen889
b0fe5b28fc38aa1790c14a9e84139604f3c35998
549
cpp
C++
podboat.cpp
adiel-mittmann/newsboat
8011952624387f0b2fcb18ba5d96382c257764c2
[ "MIT" ]
null
null
null
podboat.cpp
adiel-mittmann/newsboat
8011952624387f0b2fcb18ba5d96382c257764c2
[ "MIT" ]
null
null
null
podboat.cpp
adiel-mittmann/newsboat
8011952624387f0b2fcb18ba5d96382c257764c2
[ "MIT" ]
null
null
null
#include <iostream> #include <config.h> #include <pb_controller.h> #include <cstring> #include <pb_view.h> #include <errno.h> #include <utils.h> using namespace podboat; int main(int argc, char * argv[]) { utils::initialize_ssl_implementation(); if (!setlocale(LC_CTYPE,"") || !setlocale(LC_MESSAGES,"")) { std::cerr << "setlocale failed: " << strerror(errno) << std::endl; return 1; } bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); pb_controller c; podboat::pb_view v(&c); c.set_view(&v); return c.run(argc, argv); }
19.607143
68
0.68306
adiel-mittmann
7c04605bb9c6d08c1c8c8e187b9100d340905be5
1,192
c++
C++
linker_script/strategies/default_e20_strategy.c++
sctincman/freedom-devicetree-tools
668d8795e474623863f65f890022d1d471a1c64b
[ "Apache-2.0", "MIT" ]
null
null
null
linker_script/strategies/default_e20_strategy.c++
sctincman/freedom-devicetree-tools
668d8795e474623863f65f890022d1d471a1c64b
[ "Apache-2.0", "MIT" ]
null
null
null
linker_script/strategies/default_e20_strategy.c++
sctincman/freedom-devicetree-tools
668d8795e474623863f65f890022d1d471a1c64b
[ "Apache-2.0", "MIT" ]
null
null
null
/* Copyright (c) 2019 SiFive Inc. */ /* SPDX-License-Identifier: Apache-2.0 */ #include "default_e20_strategy.h" #include <layouts/default_layout.h> #include <layouts/scratchpad_layout.h> #include <layouts/ramrodata_layout.h> bool DefaultE20Strategy::valid(const fdt &dtb, list<Memory> available_memories) { return has_testram(available_memories); } LinkerScript DefaultE20Strategy::create_layout(const fdt &dtb, list<Memory> available_memories, LinkStrategy link_strategy) { Memory rom_memory = find_testram(available_memories); rom_memory.name = "ram"; rom_memory.attributes = "wxa!ri"; /* Generate the layouts */ print_chosen_strategy("DefaultE20Strategy", link_strategy, rom_memory, rom_memory, rom_memory); switch (link_strategy) { default: case LINK_STRATEGY_DEFAULT: return DefaultLayout(dtb, rom_memory, rom_memory, rom_memory, rom_memory); break; case LINK_STRATEGY_SCRATCHPAD: return ScratchpadLayout(dtb, rom_memory, rom_memory, rom_memory, rom_memory); break; case LINK_STRATEGY_RAMRODATA: return RamrodataLayout(dtb, rom_memory, rom_memory, rom_memory, rom_memory); break; } }
29.073171
97
0.738255
sctincman
7c05632785ddee5669c5f9c890236c674cefce29
585
cpp
C++
cilantro/src/graphics/Framebuffer.cpp
dpilawa/cilantro
69daa2112e8e373783b4f1a27c62770e4540eb6f
[ "MIT" ]
null
null
null
cilantro/src/graphics/Framebuffer.cpp
dpilawa/cilantro
69daa2112e8e373783b4f1a27c62770e4540eb6f
[ "MIT" ]
null
null
null
cilantro/src/graphics/Framebuffer.cpp
dpilawa/cilantro
69daa2112e8e373783b4f1a27c62770e4540eb6f
[ "MIT" ]
null
null
null
#include "cilantroengine.h" #include "graphics/Framebuffer.h" Framebuffer::Framebuffer (unsigned int bufferWidth, unsigned int bufferHeight) { this->bufferWidth = bufferWidth; this->bufferHeight = bufferHeight; } Framebuffer::~Framebuffer () { } unsigned int Framebuffer::GetWidth () const { return bufferWidth; } unsigned int Framebuffer::GetHeight () const { return bufferHeight; } void Framebuffer::SetFramebufferResolution (unsigned int bufferWidth, unsigned int bufferHeight) { this->bufferWidth = bufferWidth; this->bufferHeight = bufferHeight; }
19.5
96
0.745299
dpilawa
7c0597aa563fb5f1065fc14f1813fe249d8a795c
433
cpp
C++
W08/in_lab/Account.cpp
ariaav/OOP244
bcfc52bfff86b68e4f464e85b8555eef541741a0
[ "MIT" ]
null
null
null
W08/in_lab/Account.cpp
ariaav/OOP244
bcfc52bfff86b68e4f464e85b8555eef541741a0
[ "MIT" ]
null
null
null
W08/in_lab/Account.cpp
ariaav/OOP244
bcfc52bfff86b68e4f464e85b8555eef541741a0
[ "MIT" ]
null
null
null
#include <iostream> #include "Account.h" namespace sict { Account::Account(double bal) { if (bal > 0) bala = bal; else bala = 0; } bool Account::credit(double add) { if (add > 0){ bala += add; return true; } else return false; } bool Account::debit(double sub) { if (sub > 0) { bala -= sub; return true; } else return false; } double Account::balance() const { return bala; } }
12.371429
35
0.577367
ariaav
7c0fe5fd6a310e5dd2f79b822fe425d9cce77f87
851
cpp
C++
amara/amara_tweenBase.cpp
BigBossErndog/Amara
e534001dee88b7d66f7384ed167257ffac58aac3
[ "MIT" ]
null
null
null
amara/amara_tweenBase.cpp
BigBossErndog/Amara
e534001dee88b7d66f7384ed167257ffac58aac3
[ "MIT" ]
null
null
null
amara/amara_tweenBase.cpp
BigBossErndog/Amara
e534001dee88b7d66f7384ed167257ffac58aac3
[ "MIT" ]
null
null
null
#ifndef AMARA_TWEENBASE #define AMARA_TWEENBASE #include "amara.h" namespace Amara { class Tweener; class Tween: public Amara::StateManager { public: Amara::GameProperties* properties = nullptr; bool finished = false; bool deleteOnFinish = true; double progress = 0; float time = 0; virtual void assign(Amara::Tweener* gTweener, Amara::GameProperties* gProperties) { properties = gProperties; } virtual void run() { progress += (time/properties->lps); if (progress >= 1) { finished = true; progress = 1; } } virtual void reset() { progress = 0; } }; } #endif
23.638889
95
0.480611
BigBossErndog
7c11f304a4c71c599e3aa18728323cf90f51aaa3
2,138
cc
C++
2021/5/main.cc
ey6es/aoc
c1e54534e5e6d4b52118ffd173834ab56a831102
[ "MIT" ]
null
null
null
2021/5/main.cc
ey6es/aoc
c1e54534e5e6d4b52118ffd173834ab56a831102
[ "MIT" ]
null
null
null
2021/5/main.cc
ey6es/aoc
c1e54534e5e6d4b52118ffd173834ab56a831102
[ "MIT" ]
null
null
null
#include <algorithm> #include <fstream> #include <iostream> #include <map> #include <string> #include <tuple> std::tuple<int, int> parse_coord (const std::string& str) { auto idx = str.find(','); return std::make_tuple( std::stoi(str.substr(0, idx)), std::stoi(str.substr(idx + 1))); } std::ostream& operator<< (std::ostream& out, const std::tuple<int, int>& tuple) { return out << std::get<0>(tuple) << " " << std::get<1>(tuple); } int main () { std::ifstream in("input.txt"); std::map<std::tuple<int, int>, int> points; while (in.good()) { std::string line; std::getline(in, line); if (!in.good()) break; auto start = parse_coord(line.substr(0, line.find(' '))); auto end = parse_coord(line.substr(line.rfind(' ') + 1)); auto sx = std::get<0>(start); auto sy = std::get<1>(start); auto ex = std::get<0>(end); auto ey = std::get<1>(end); if (sx == ex) { // vertical line auto x = sx; auto minmax_y = std::minmax(sy, ey); for (auto y = minmax_y.first; y <= minmax_y.second; y++) { points[std::make_tuple(x, y)]++; } } else if (sy == ey) { // horizontal auto y = sy; auto minmax_x = std::minmax(sx, ex); for (auto x = minmax_x.first; x <= minmax_x.second; x++) { points[std::make_tuple(x, y)]++; } } else { auto dx = ex - sx; auto dy = ey - sy; if (dx == dy) { if (dx > 0) { for (auto c = 0; c <= dx; c++) { points[std::make_tuple(sx + c, sy + c)]++; } } else { for (auto c = dx; c <= 0; c++) { points[std::make_tuple(sx + c, sy + c)]++; } } } else if (dx == -dy) { if (dx > 0) { for (auto c = 0; c <= dx; c++) { points[std::make_tuple(sx + c, sy - c)]++; } } else { for (auto c = dx; c <= 0; c++) { points[std::make_tuple(sx + c, sy - c)]++; } } } } } int count = 0; for (auto& pair : points) { if (pair.second >= 2) count++; } std::cout << count << std::endl; }
24.860465
81
0.481291
ey6es
7c1885c5d71e72c411d50181d4b84e586de72b3f
635
cpp
C++
0014.cpp
excript/curso_cpp
070d0bd1163c1252b7bf736fedb3370208c30811
[ "CC0-1.0" ]
1
2020-08-01T07:03:32.000Z
2020-08-01T07:03:32.000Z
0014.cpp
excript/curso_cpp
070d0bd1163c1252b7bf736fedb3370208c30811
[ "CC0-1.0" ]
1
2020-08-01T07:04:27.000Z
2020-08-01T07:04:27.000Z
0014.cpp
excript/curso_cpp
070d0bd1163c1252b7bf736fedb3370208c30811
[ "CC0-1.0" ]
null
null
null
#include <iostream> #include <stdlib.h> #include <iomanip> /*==================================== * eXcript.com * fb.com/eXcript * ====================================*/ using namespace std; int main() { //obj cin3 //obj cout cout << "Estudando a entrada e saida de dados." << endl; // cout << setw(10) << 1 << endl; // cout << setw(10) << 2 << endl; // cout << setw(10) << 3 << endl; // cout << setw(10) << 4 << endl; cout << setw(10) << 1456; cout << setw(10) << 25343543; cout << setw(10) << 3456546; cout << setw(10) << 44455; system("pause"); return 0; }
19.84375
60
0.445669
excript
7c1b5d88f091c7ddf7a60fc1969c757257d02a8d
907
hh
C++
src/agents/pacman/pathfinding_pacman_agent.hh
emanuelssj/PacmanRL
275715f7024e1ffab8a562c892a9852d4d7f16cb
[ "MIT" ]
3
2019-01-07T10:15:21.000Z
2019-03-25T15:36:39.000Z
src/agents/pacman/pathfinding_pacman_agent.hh
emanuelssj/Lunafreya-Pacman-Speedrun
275715f7024e1ffab8a562c892a9852d4d7f16cb
[ "MIT" ]
null
null
null
src/agents/pacman/pathfinding_pacman_agent.hh
emanuelssj/Lunafreya-Pacman-Speedrun
275715f7024e1ffab8a562c892a9852d4d7f16cb
[ "MIT" ]
1
2019-05-26T07:48:21.000Z
2019-05-26T07:48:21.000Z
#ifndef PATHFINDING_PACMAN_AGENT_HH #define PATHFINDING_PACMAN_AGENT_HH #include "../agent.hh" #include "../../state/direction.hh" #include "../../pathfinding/bfs.hh" #include "../../pathfinding/wsp.hh" #include <cmath> class Pathfinding_Pacman_Agent: public Agent { // In this case ghost_id can be ignored inline Direction take_action(const State& s, uint ghost_id) { if (s.distance_closest_harmful_ghost(s.pacman.pos) < 10) { return wsp(s.pacman.pos, [&s](const Position& pos) { return s.has_any_pill(pos); }, s, [&s](const Position& pos) { return 10*pow(2, 10 - min(10,s.distance_closest_harmful_ghost(pos))); } ).dir; } else return bfs(s.pacman.pos, [&s](const Position& pos) { return s.has_any_pill(pos); }, s).dir; } }; #endif
32.392857
122
0.582139
emanuelssj
7c283dc0e0c52f8c51f5f4a8f987d346aa6b947f
2,624
cpp
C++
Utilities/MarbleAction/MarbleAction.cpp
mym2o/HavokDemos
1235b96b93e256de50bc36c229439a334410fd77
[ "MIT" ]
1
2017-08-14T10:23:45.000Z
2017-08-14T10:23:45.000Z
Utilities/MarbleAction/MarbleAction.cpp
mym2o/HavokDemos
1235b96b93e256de50bc36c229439a334410fd77
[ "MIT" ]
null
null
null
Utilities/MarbleAction/MarbleAction.cpp
mym2o/HavokDemos
1235b96b93e256de50bc36c229439a334410fd77
[ "MIT" ]
2
2016-06-22T02:22:32.000Z
2019-11-21T19:49:41.000Z
#include "MarbleAction.h" MarbleAction::MarbleAction(hkpRigidBody* r, const hkVector4& forward, const hkVector4& resetPosition, hkReal impulseScale) : hkpUnaryAction(r), m_forward(forward), m_resetPosition(resetPosition), m_rotationIncrement(0.01f) { m_forwardPressed = false; m_backwardPressed = false; m_leftPressed = false; m_rightPressed = false; m_jumpPressed = false; m_brakePressed = false; m_lastJump = 0.f; m_impulseScale = impulseScale; m_lasttimeCalled = 0.f; m_currentAngle = 0.f; } void MarbleAction::applyAction(const hkStepInfo& stepInfo) { hkpRigidBody* rb = getRigidBody(); //we need the delta time to record how long it's been since we last jumped //(to avoid jumping while in the air!) hkReal dt = stepInfo.m_deltaTime; //get a "scale" to change the force of the impulse by, depending on both the mass of the body, //an arbitrary "gain", eg 0.1 hkReal scale = rb->getMass() * m_impulseScale; hkVector4 axis(0, 1, 0); hkQuaternion q(axis, m_currentAngle); hkVector4 f; f.setRotatedDir(q, m_forward); if (m_forwardPressed) { hkVector4 imp; imp.setMul4(scale, f); rb->applyLinearImpulse(imp); } if (m_backwardPressed) { hkVector4 imp; imp.setMul4(-scale, f); rb->applyLinearImpulse(imp); } if (m_rightPressed) { m_currentAngle += 3.141592653f * 2 * m_rotationIncrement; } if (m_leftPressed) { m_currentAngle -= 3.141592653f * 2 * m_rotationIncrement; } m_lasttimeCalled += dt; //Jump (only if haven't jumped for at least 1 second) if (m_jumpPressed && ((m_lasttimeCalled - m_lastJump) > 1.f)) { m_lastJump = m_lasttimeCalled; hkVector4 imp(0, rb->getMass() * 6, 0); rb->applyLinearImpulse(imp); setJumpPressed(false); } setJumpPressed(false); //if brake pressed, zero all velocities if (m_brakePressed) { hkVector4 zero; zero.setZero4(); rb->setLinearVelocity(zero); rb->setAngularVelocity(zero); setBrakePressed(false); } //draw current "facing" direction, usings "Debug" line. This gets pushed onto a global list, //and gets dealt with by (perhaps) a drawDebugPointsAndLines() method from the mainline start = rb->getPosition(); //end = start + 1.5 * "forward" end = start; f.mul4(1.5f); end.add4(f); //TODO: draw line from start to end } void MarbleAction::reset() { hkpRigidBody* rb = getRigidBody(); //put marble back to the reset position defined on construction, and zero velocities hkVector4 zero; zero.setZero4(); rb->setPosition(m_resetPosition); rb->setLinearVelocity(zero); rb->setAngularVelocity(zero); }
28.835165
225
0.699695
mym2o
7c28f9a0f641f5f618db137ee21ad79407c3aef8
13,626
cc
C++
src/ShaderCompiler/Private/GLSLangUtils.cc
PixPh/kaleido3d
8a8356586f33a1746ebbb0cfe46b7889d0ae94e9
[ "MIT" ]
38
2019-01-10T03:10:12.000Z
2021-01-27T03:14:47.000Z
src/ShaderCompiler/Private/GLSLangUtils.cc
fuqifacai/kaleido3d
ec77753b516949bed74e959738ef55a0bd670064
[ "MIT" ]
null
null
null
src/ShaderCompiler/Private/GLSLangUtils.cc
fuqifacai/kaleido3d
ec77753b516949bed74e959738ef55a0bd670064
[ "MIT" ]
8
2019-04-16T07:56:27.000Z
2020-11-19T02:38:37.000Z
#include <Kaleido3D.h> #include "GLSLangUtils.h" #include <glslang/MachineIndependent/gl_types.h> using namespace ::glslang; using namespace ::k3d; void sInitializeGlSlang() { #if USE_GLSLANG static bool sGlSlangIntialized = false; if (!sGlSlangIntialized) { glslang::InitializeProcess(); sGlSlangIntialized = true; } #endif } void sFinializeGlSlang() { #if USE_GLSLANG static bool sGlSlangFinalized = false; if (!sGlSlangFinalized) { glslang::FinalizeProcess(); sGlSlangFinalized = true; } #endif } NGFXShaderDataType glTypeToRHIAttribType(int glType) { switch (glType) { case GL_FLOAT: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT; case GL_FLOAT_VEC2: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT2; case GL_FLOAT_VEC3: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT3; case GL_FLOAT_VEC4: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT4; case GL_INT: return NGFXShaderDataType::NGFX_SHADER_VAR_INT; case GL_INT_VEC2: return NGFXShaderDataType::NGFX_SHADER_VAR_INT2; case GL_INT_VEC3: return NGFXShaderDataType::NGFX_SHADER_VAR_INT3; case GL_INT_VEC4: return NGFXShaderDataType::NGFX_SHADER_VAR_INT4; case GL_UNSIGNED_INT: return NGFXShaderDataType::NGFX_SHADER_VAR_UINT; case GL_UNSIGNED_INT_VEC2: return NGFXShaderDataType::NGFX_SHADER_VAR_UINT2; case GL_UNSIGNED_INT_VEC3: return NGFXShaderDataType::NGFX_SHADER_VAR_UINT3; case GL_UNSIGNED_INT_VEC4: return NGFXShaderDataType::NGFX_SHADER_VAR_UINT4; } return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN; } NGFXShaderDataType glTypeToRHIUniformType(int glType) { switch (glType) { case GL_FLOAT: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT; case GL_FLOAT_VEC2: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT2; case GL_FLOAT_VEC3: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT3; case GL_FLOAT_VEC4: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT4; case GL_INT: return NGFXShaderDataType::NGFX_SHADER_VAR_INT; case GL_INT_VEC2: return NGFXShaderDataType::NGFX_SHADER_VAR_INT2; case GL_INT_VEC3: return NGFXShaderDataType::NGFX_SHADER_VAR_INT3; case GL_INT_VEC4: return NGFXShaderDataType::NGFX_SHADER_VAR_INT4; case GL_UNSIGNED_INT: return NGFXShaderDataType::NGFX_SHADER_VAR_UINT; case GL_UNSIGNED_INT_VEC2: return NGFXShaderDataType::NGFX_SHADER_VAR_UINT2; case GL_UNSIGNED_INT_VEC3: return NGFXShaderDataType::NGFX_SHADER_VAR_UINT3; case GL_UNSIGNED_INT_VEC4: return NGFXShaderDataType::NGFX_SHADER_VAR_UINT4; } return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN; } NGFXShaderDataType glslangDataTypeToRHIDataType(const TType& type) { switch (type.getBasicType()) { case EbtSampler: { switch (type.getQualifier().layoutFormat) { case ElfRgba32f: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT4; } } case EbtStruct: case EbtBlock: case EbtVoid: return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN; default: break; } if (type.isVector()) { int offset = type.getVectorSize() - 2; switch (type.getBasicType()) { case EbtFloat: return (NGFXShaderDataType)((int)NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT2 + offset); //case EbtDouble: return GL_DOUBLE_VEC2 + offset; #ifdef AMD_EXTENSIONS //case EbtFloat16: return GL_FLOAT16_VEC2_NV + offset; #endif case EbtInt: return (NGFXShaderDataType)((int)NGFXShaderDataType::NGFX_SHADER_VAR_INT2 + offset); case EbtUint: return (NGFXShaderDataType)((int)NGFXShaderDataType::NGFX_SHADER_VAR_UINT2 + offset); //case EbtInt64: return GL_INT64_ARB + offset; //case EbtUint64: return GL_UNSIGNED_INT64_ARB + offset; case EbtBool: return (NGFXShaderDataType)((int)NGFXShaderDataType::NGFX_SHADER_VAR_BOOL2 + offset); //case EbtAtomicUint: return GL_UNSIGNED_INT_ATOMIC_COUNTER + offset; default: return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN; } } if (type.isMatrix()) { switch (type.getBasicType()) { case EbtFloat: switch (type.getMatrixCols()) { case 2: switch (type.getMatrixRows()) { case 2: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT2; case 3: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT2X3; case 4: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT2X4; default: return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN; } case 3: switch (type.getMatrixRows()) { case 2: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT3X2; case 3: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT3; case 4: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT3X4; default: return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN; } case 4: switch (type.getMatrixRows()) { case 2: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT4X2; case 3: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT4X3; case 4: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT4; default: return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN; } } } } if (type.getVectorSize() == 1) { switch (type.getBasicType()) { case EbtFloat: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT; case EbtInt: return NGFXShaderDataType::NGFX_SHADER_VAR_INT; case EbtUint: return NGFXShaderDataType::NGFX_SHADER_VAR_UINT; case EbtBool: return NGFXShaderDataType::NGFX_SHADER_VAR_BOOL; default: return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN; } } return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN; } NGFXShaderBindType glslangTypeToRHIType(const TBasicType& type) { switch (type) { case EbtSampler: return NGFXShaderBindType::NGFX_SHADER_BIND_SAMPLER; case EbtStruct: case EbtBlock: return NGFXShaderBindType::NGFX_SHADER_BIND_BLOCK; case EbtVoid: return NGFXShaderBindType::NGFX_SHADER_BIND_UNDEFINED; default: break; } return NGFXShaderBindType::NGFX_SHADER_BIND_BLOCK; } void initResources(TBuiltInResource &resources) { resources.maxLights = 32; resources.maxClipPlanes = 6; resources.maxTextureUnits = 32; resources.maxTextureCoords = 32; resources.maxVertexAttribs = 64; resources.maxVertexUniformComponents = 4096; resources.maxVaryingFloats = 64; resources.maxVertexTextureImageUnits = 32; resources.maxCombinedTextureImageUnits = 80; resources.maxTextureImageUnits = 32; resources.maxFragmentUniformComponents = 4096; resources.maxDrawBuffers = 32; resources.maxVertexUniformVectors = 128; resources.maxVaryingVectors = 8; resources.maxFragmentUniformVectors = 16; resources.maxVertexOutputVectors = 16; resources.maxFragmentInputVectors = 15; resources.minProgramTexelOffset = -8; resources.maxProgramTexelOffset = 7; resources.maxClipDistances = 8; resources.maxComputeWorkGroupCountX = 65535; resources.maxComputeWorkGroupCountY = 65535; resources.maxComputeWorkGroupCountZ = 65535; resources.maxComputeWorkGroupSizeX = 1024; resources.maxComputeWorkGroupSizeY = 1024; resources.maxComputeWorkGroupSizeZ = 64; resources.maxComputeUniformComponents = 1024; resources.maxComputeTextureImageUnits = 16; resources.maxComputeImageUniforms = 8; resources.maxComputeAtomicCounters = 8; resources.maxComputeAtomicCounterBuffers = 1; resources.maxVaryingComponents = 60; resources.maxVertexOutputComponents = 64; resources.maxGeometryInputComponents = 64; resources.maxGeometryOutputComponents = 128; resources.maxFragmentInputComponents = 128; resources.maxImageUnits = 8; resources.maxCombinedImageUnitsAndFragmentOutputs = 8; resources.maxCombinedShaderOutputResources = 8; resources.maxImageSamples = 0; resources.maxVertexImageUniforms = 0; resources.maxTessControlImageUniforms = 0; resources.maxTessEvaluationImageUniforms = 0; resources.maxGeometryImageUniforms = 0; resources.maxFragmentImageUniforms = 8; resources.maxCombinedImageUniforms = 8; resources.maxGeometryTextureImageUnits = 16; resources.maxGeometryOutputVertices = 256; resources.maxGeometryTotalOutputComponents = 1024; resources.maxGeometryUniformComponents = 1024; resources.maxGeometryVaryingComponents = 64; resources.maxTessControlInputComponents = 128; resources.maxTessControlOutputComponents = 128; resources.maxTessControlTextureImageUnits = 16; resources.maxTessControlUniformComponents = 1024; resources.maxTessControlTotalOutputComponents = 4096; resources.maxTessEvaluationInputComponents = 128; resources.maxTessEvaluationOutputComponents = 128; resources.maxTessEvaluationTextureImageUnits = 16; resources.maxTessEvaluationUniformComponents = 1024; resources.maxTessPatchComponents = 120; resources.maxPatchVertices = 32; resources.maxTessGenLevel = 64; resources.maxViewports = 16; resources.maxVertexAtomicCounters = 0; resources.maxTessControlAtomicCounters = 0; resources.maxTessEvaluationAtomicCounters = 0; resources.maxGeometryAtomicCounters = 0; resources.maxFragmentAtomicCounters = 8; resources.maxCombinedAtomicCounters = 8; resources.maxAtomicCounterBindings = 1; resources.maxVertexAtomicCounterBuffers = 0; resources.maxTessControlAtomicCounterBuffers = 0; resources.maxTessEvaluationAtomicCounterBuffers = 0; resources.maxGeometryAtomicCounterBuffers = 0; resources.maxFragmentAtomicCounterBuffers = 1; resources.maxCombinedAtomicCounterBuffers = 1; resources.maxAtomicCounterBufferSize = 16384; resources.maxTransformFeedbackBuffers = 4; resources.maxTransformFeedbackInterleavedComponents = 64; resources.maxCullDistances = 8; resources.maxCombinedClipAndCullDistances = 8; resources.maxSamples = 4; resources.limits.nonInductiveForLoops = 1; resources.limits.whileLoops = 1; resources.limits.doWhileLoops = 1; resources.limits.generalUniformIndexing = 1; resources.limits.generalAttributeMatrixVectorIndexing = 1; resources.limits.generalVaryingIndexing = 1; resources.limits.generalSamplerIndexing = 1; resources.limits.generalVariableIndexing = 1; resources.limits.generalConstantMatrixVectorIndexing = 1; } EShLanguage findLanguage(const NGFXShaderType shader_type) { switch (shader_type) { case NGFX_SHADER_TYPE_VERTEX: return EShLangVertex; case NGFX_SHADER_TYPE_HULL: return EShLangTessControl; case NGFX_SHADER_TYPE_DOMAIN: return EShLangTessEvaluation; case NGFX_SHADER_TYPE_GEOMETRY: return EShLangGeometry; case NGFX_SHADER_TYPE_FRAGMENT: return EShLangFragment; case NGFX_SHADER_TYPE_COMPUTE: return EShLangCompute; default: return EShLangVertex; } } void ExtractAttributeData(const TProgram& program, NGFXShaderAttributes& shAttributes) { auto numAttrs = program.getNumLiveAttributes(); if (numAttrs > 0) { for (uint32 i = 0; i < numAttrs; i++) { auto name = program.getAttributeName(i); auto type = program.getAttributeType(i); shAttributes.Append({name, NGFX_SEMANTIC_POSITION, glTypeToRHIAttribType(type), i, 0, 0}); } } } void ExtractUniformData(NGFXShaderType const& stype, const TProgram& program, NGFXShaderBindingTable& outUniformLayout) { auto numUniforms = program.getNumLiveUniformVariables(); for (int i = 0; i < numUniforms; i++) { auto name = program.getUniformName(i); auto index = program.getUniformIndex(name); auto type = program.getUniformTType(index); bool isImage = type->isImage(); auto baseType = type->getBasicType(); auto qualifier = type->getQualifier(); if (qualifier.hasBinding()) { NGFXShaderBindType bind = glslangTypeToRHIType(baseType); if (baseType == EbtSampler) { if (type->getSampler().isCombined()) { bind = NGFXShaderBindType::NGFX_SHADER_BIND_SAMPLER_IMAGE_COMBINE; } switch (type->getSampler().dim) { case Esd1D: case Esd2D: case Esd3D: case EsdCube: case EsdRect: bind = NGFXShaderBindType::NGFX_SHADER_BIND_SAMPLED_IMAGE; break; } if (type->isImage()) { switch (qualifier.storage) { case EvqUniform: bind = NGFXShaderBindType::NGFX_SHADER_BIND_RWTEXEL_BUFFER; break; case EvqBuffer: bind = NGFXShaderBindType::NGFX_SHADER_BIND_RWTEXEL_BUFFER; break; } } } outUniformLayout.AddBinding({bind, name, stype, qualifier.layoutBinding}); } if (qualifier.hasSet()) { outUniformLayout.AddSet(qualifier.layoutSet); } if (baseType == EbtSampler) { auto sampler = type->getSampler(); if (!sampler.combined) { outUniformLayout.AddUniform({glslangDataTypeToRHIDataType(*type), name, qualifier.hasOffset() ? (uint32)qualifier.layoutOffset : 0, /*type->getArraySizes()*/}); } } else { outUniformLayout.AddUniform({glslangDataTypeToRHIDataType(*type), name, qualifier.hasOffset() ? (uint32)qualifier.layoutOffset : 0, /*type->getArraySizes()*/}); } } auto numUniformBlocks = program.getNumLiveUniformBlocks(); for (int i = 0; i < numUniformBlocks; i++) { auto block = program.getUniformBlockTType(i); auto name = program.getUniformBlockName(i); auto bindNum = program.getUniformBlockIndex(i); auto bType = block->getBasicType(); auto qualifier = block->getQualifier(); if (qualifier.hasSet()) { outUniformLayout.AddSet(qualifier.layoutSet); } if (qualifier.hasBinding()) { outUniformLayout.AddBinding({glslangTypeToRHIType(bType), name, stype, (uint32)qualifier.layoutBinding}); } switch (bType) { case EbtString: break; } } }
32.754808
168
0.754954
PixPh
7c2b82eba95378926615f75703f463e29eb82ff6
3,288
cpp
C++
Project Mania/Source/Character/Chassis.cpp
larsolm/Archives
18968c18b80777e589bc8a704b4375be2fff8eea
[ "MIT" ]
null
null
null
Project Mania/Source/Character/Chassis.cpp
larsolm/Archives
18968c18b80777e589bc8a704b4375be2fff8eea
[ "MIT" ]
null
null
null
Project Mania/Source/Character/Chassis.cpp
larsolm/Archives
18968c18b80777e589bc8a704b4375be2fff8eea
[ "MIT" ]
null
null
null
#include "Pch.h" #include "Character/Character.h" #include "Character/Chassis.h" #include "Data/AugmentData.h" #include "Data/CharacterData.h" #include "Data/ComponentData.h" #include "Data/ChassisData.h" #include "Data/EquipmentData.h" #include "Data/UpgradeData.h" #include "Data/PartData.h" #include "Parts/Item.h" #include "Parts/Equipment.h" #include "Parts/Weapon.h" #include "Parts/Upgrade.h" void Chassis::Initialize() { Skeleton = Data->Skeleton->CreateSkeleton(); Skeleton->Data = Data->Skeleton; Skeleton->Character = Character; Skeleton->Initialize(); for (auto& attachment : Data->Attachments) { auto part = AttachPart(attachment.Bone, *attachment.Part); for (auto i = 0; i < attachment.Components.Count(); i++) attachment.Components.Item(i)->Apply(*part, i); for (auto augment : attachment.Augments) augment->Apply(*part); } Character->Health = GetMaxHealth(); Character->Shield = GetMaxShield(); } void Chassis::Update(float elapsed) { for (auto& equipment : Equipment) equipment->Update(elapsed, false, false, false); for (auto i = 0; i < Items.Count(); i++) { auto item = static_cast<Item*>(Items.Item(i).get()); auto active = Character->ActiveItemSlot == i; auto primary = active && Character->Controller->ItemPrimary; auto secondary = active && Character->Controller->ItemSecondary; item->Update(elapsed, active, primary, secondary); } for (auto i = 0; i < Weapons.Count(); i++) { auto weapon = static_cast<Weapon*>(Weapons.Item(i).get()); auto active = Character->ActiveWeaponSlot == i; auto primary = active && Character->Controller->WeaponPrimary; auto secondary = active && Character->Controller->WeaponSecondary; weapon->Update(elapsed, active, primary, secondary); } } auto Chassis::AttachPart(StringView name, PartData& data) -> Part* { auto& bone = Skeleton->GetBone(name); assert(bone.Data->AttachmentType == data.Bone.AttachmentType); auto part = data.CreatePart(); part->Data = &data; part->Character = Character; part->Bone = &bone; part->Initialize(); switch (data.Bone.AttachmentType) { case AttachmentType::Equipment: return Equipment.Add(std::move(part)).get(); case AttachmentType::Item: if (Items.IsEmpty()) Character->ActiveItemSlot = 0; return Items.Add(std::move(part)).get(); case AttachmentType::Weapon: if (Weapons.IsEmpty()) Character->ActiveWeaponSlot = 0; return Weapons.Add(std::move(part)).get(); } return nullptr; } auto Chassis::GetMaxHealth() const -> float { auto health = Character->Data->Health; for (auto& part : Equipment) { auto equipment = static_cast<class Equipment*>(part.get()); health += equipment->EquipmentData->Attributes.GetAttribute(equipment->Modifiers, EquipmentAttribute::Health); } return health; } auto Chassis::GetMaxShield() const -> float { auto shield = 0.0f; for (auto& part : Equipment) { for (auto& upgrade : part->Upgrades) shield += upgrade->Data->Attributes.GetAttribute(upgrade->Modifiers, UpgradeAttribute::Shield); } return shield; } auto Chassis::GetShieldRegen() const -> float { auto regen = 0.0f; for (auto& part : Equipment) { for (auto& upgrade : part->Upgrades) regen += upgrade->Data->Attributes.GetAttribute(upgrade->Modifiers, UpgradeAttribute::ShieldRegen); } return regen; }
27.630252
129
0.708942
larsolm
7c2e99d071f669e6bf42911f05fdfe7e036dfa42
12,307
cpp
C++
Sources/Rosetta/Battlegrounds/Models/Battle.cpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
62
2017-08-21T14:11:00.000Z
2018-04-23T16:09:02.000Z
Sources/Rosetta/Battlegrounds/Models/Battle.cpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
37
2017-08-21T11:13:07.000Z
2018-04-30T08:58:41.000Z
Sources/Rosetta/Battlegrounds/Models/Battle.cpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
10
2017-08-21T03:44:12.000Z
2018-01-10T22:29:10.000Z
// Copyright (c) 2017-2021 Chris Ohk // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <Rosetta/Battlegrounds/Models/Battle.hpp> #include <effolkronium/random.hpp> using Random = effolkronium::random_static; namespace RosettaStone::Battlegrounds { Battle::Battle(Player& player1, Player& player2) : m_player1(player1), m_player2(player2), m_p1Field(m_player1.battleField), m_p2Field(m_player2.battleField) { m_player1.battleField = m_player1.recruitField; m_player2.battleField = m_player2.recruitField; } void Battle::Initialize() { // Determine the player attacks first // NOTE: The player with the greater number of minions attacks first. // If the number of minions is equal for both players, one of the players // is randomly selected to attack first. const int p1NumMinions = m_p1Field.GetCount(); const int p2NumMinions = m_p2Field.GetCount(); if (p1NumMinions > p2NumMinions) { m_turn = Turn::PLAYER1; } else if (p1NumMinions < p2NumMinions) { m_turn = Turn::PLAYER2; } else { m_turn = static_cast<Turn>(Random::get<std::size_t>(0, 1)); } m_p1NextAttackerIdx = 0; m_p2NextAttackerIdx = 0; if (m_turn == Turn::PLAYER1) { m_p1Field.ForEach([&](MinionData& minion) { minion.value().ActivateTask(PowerType::START_OF_COMBAT, m_player1); }); m_p2Field.ForEach([&](MinionData& minion) { minion.value().ActivateTask(PowerType::START_OF_COMBAT, m_player2); }); } else { m_p2Field.ForEach([&](MinionData& minion) { minion.value().ActivateTask(PowerType::START_OF_COMBAT, m_player2); }); m_p1Field.ForEach([&](MinionData& minion) { minion.value().ActivateTask(PowerType::START_OF_COMBAT, m_player1); }); } ProcessDestroy(true); } void Battle::Run() { Initialize(); bool prevAttackSuccess = false; while (!IsDone()) { if (m_turn == Turn::PLAYER1) { m_p1Field.ForEachAlive([&](MinionData& owner) { m_p1Field.ForEachAlive([&](MinionData& minion) { { owner.value().ActivateTrigger(TriggerType::TURN_START, minion.value()); }; }); }); m_p2Field.ForEachAlive([&](MinionData& owner) { m_p2Field.ForEachAlive([&](MinionData& minion) { { owner.value().ActivateTrigger(TriggerType::TURN_START, minion.value()); }; }); }); } else { m_p2Field.ForEachAlive([&](MinionData& owner) { m_p2Field.ForEachAlive([&](MinionData& minion) { { owner.value().ActivateTrigger(TriggerType::TURN_START, minion.value()); }; }); }); m_p1Field.ForEachAlive([&](MinionData& owner) { m_p1Field.ForEachAlive([&](MinionData& minion) { { owner.value().ActivateTrigger(TriggerType::TURN_START, minion.value()); }; }); }); } const bool curAttackSuccess = Attack(); if (!prevAttackSuccess && !curAttackSuccess) { m_turn = Turn::DONE; break; } prevAttackSuccess = curAttackSuccess; } ProcessResult(); const int damage = CalculateDamage(); if (m_result == BattleResult::PLAYER1_WIN) { m_player2.hero.TakeDamage(m_player2, damage); } else if (m_result == BattleResult::PLAYER2_WIN) { m_player1.hero.TakeDamage(m_player1, damage); } } bool Battle::Attack() { const int attackerIdx = FindAttacker(); // No minions that can attack, switch players if (attackerIdx == -1) { m_turn = (m_turn == Turn::PLAYER1) ? Turn::PLAYER2 : Turn::PLAYER1; return false; } Minion& attacker = (m_turn == Turn::PLAYER1) ? m_p1Field[attackerIdx] : m_p2Field[attackerIdx]; Minion& target = GetProperTarget(attacker); target.TakeDamage(attacker); attacker.TakeDamage(target); ProcessDestroy(false); m_turn = (m_turn == Turn::PLAYER1) ? Turn::PLAYER2 : Turn::PLAYER1; return true; } int Battle::FindAttacker() { FieldZone& fieldZone = (m_turn == Turn::PLAYER1) ? m_p1Field : m_p2Field; int nextAttackerIdx = (m_turn == Turn::PLAYER1) ? m_p1NextAttackerIdx : m_p2NextAttackerIdx; for (int i = 0; i < fieldZone.GetCount(); ++i) { if (fieldZone[nextAttackerIdx].GetAttack() > 0) { return nextAttackerIdx; } ++nextAttackerIdx; if (nextAttackerIdx == fieldZone.GetCount()) { nextAttackerIdx = 0; } } return -1; } Minion& Battle::GetProperTarget([[maybe_unused]] Minion& attacker) { auto& minions = (m_turn == Turn::PLAYER1) ? m_p2Field : m_p1Field; std::vector<std::size_t> tauntMinions; tauntMinions.reserve(MAX_FIELD_SIZE); std::size_t minionIdx = 0; minions.ForEach([&](const MinionData& minion) { if (minion.value().HasTaunt()) { tauntMinions.emplace_back(minionIdx); } ++minionIdx; }); if (!tauntMinions.empty()) { const auto idx = Random::get<std::size_t>(0, tauntMinions.size() - 1); return minions[tauntMinions[idx]]; } const auto idx = Random::get<int>(0, minions.GetCount() - 1); return minions[idx]; } void Battle::ProcessDestroy(bool beforeAttack) { std::vector<std::tuple<int, Minion&>> deadMinions; if (m_turn == Turn::PLAYER1) { m_p2Field.ForEach([&](MinionData& minion) { if (minion.value().IsDestroyed()) { deadMinions.emplace_back( std::make_tuple(2, std::ref(minion.value()))); } }); m_p1Field.ForEach([&](MinionData& minion) { if (minion.value().IsDestroyed()) { deadMinions.emplace_back( std::make_tuple(1, std::ref(minion.value()))); } }); } else { m_p1Field.ForEach([&](MinionData& minion) { if (minion.value().IsDestroyed()) { deadMinions.emplace_back( std::make_tuple(1, std::ref(minion.value()))); } }); m_p2Field.ForEach([&](MinionData& minion) { if (minion.value().IsDestroyed()) { deadMinions.emplace_back( std::make_tuple(2, std::ref(minion.value()))); } }); } // A variable to check a minion at the index of next attacker is destroyed bool isAttackerDestroyed = false; for (auto& deadMinion : deadMinions) { Minion& minion = std::get<1>(deadMinion); Minion removedMinion; if (std::get<0>(deadMinion) == 1) { if (!beforeAttack) { // If the zone position of minion that is destroyed is lower // than nextAttackerIdx and greater than 0, decrease by 1 if (m_p1NextAttackerIdx < minion.GetZonePosition() && m_p1NextAttackerIdx > 0) { --m_p1NextAttackerIdx; } // If the turn is player 1 and the zone position of minion that // is destroyed equals nextAttackerIdx, keep the value of it else if (m_turn == Turn::PLAYER1 && m_p1NextAttackerIdx == minion.GetZonePosition()) { isAttackerDestroyed = true; } } m_p1Field.ForEachAlive([&](MinionData& aliveMinion) { aliveMinion.value().ActivateTrigger(TriggerType::DEATH, minion); }); m_p2Field.ForEachAlive([&](MinionData& aliveMinion) { aliveMinion.value().ActivateTrigger(TriggerType::DEATH, minion); }); minion.SetLastFieldPos(minion.GetZonePosition()); removedMinion = m_p1Field.Remove(minion); } else { if (!beforeAttack) { // If the zone position of minion that is destroyed is lower // than nextAttackerIdx and greater than 0, decrease by 1 if (m_p2NextAttackerIdx < minion.GetZonePosition() && m_p2NextAttackerIdx > 0) { --m_p2NextAttackerIdx; } // If the turn is player 2 and the zone position of minion that // is destroyed equals nextAttackerIdx, keep the value of it else if (m_turn == Turn::PLAYER2 && m_p2NextAttackerIdx == minion.GetZonePosition()) { isAttackerDestroyed = true; } } m_p1Field.ForEachAlive([&](MinionData& aliveMinion) { aliveMinion.value().ActivateTrigger(TriggerType::DEATH, minion); }); m_p2Field.ForEachAlive([&](MinionData& aliveMinion) { aliveMinion.value().ActivateTrigger(TriggerType::DEATH, minion); }); minion.SetLastFieldPos(minion.GetZonePosition()); removedMinion = m_p2Field.Remove(minion); } // Process deathrattle tasks if (removedMinion.HasDeathrattle()) { removedMinion.ActivateTask( PowerType::DEATHRATTLE, std::get<0>(deadMinion) == 1 ? m_player1 : m_player2); } } if (!beforeAttack) { // If the zone position of minion that is destroyed not equals // nextAttackerIdx, increase by 1 if (!isAttackerDestroyed) { if (m_turn == Turn::PLAYER1) { ++m_p1NextAttackerIdx; } else { ++m_p2NextAttackerIdx; } } // Check the boundaries of field zone if (m_p1NextAttackerIdx == m_p1Field.GetCount()) { m_p1NextAttackerIdx = 0; } if (m_p2NextAttackerIdx == m_p2Field.GetCount()) { m_p2NextAttackerIdx = 0; } } } bool Battle::IsDone() const { return m_p1Field.IsEmpty() || m_p2Field.IsEmpty() || m_turn == Turn::DONE; } void Battle::ProcessResult() { if (m_p1Field.IsEmpty() && !m_p2Field.IsEmpty()) { m_result = BattleResult::PLAYER2_WIN; } else if (!m_p1Field.IsEmpty() && m_p2Field.IsEmpty()) { m_result = BattleResult::PLAYER1_WIN; } else { m_result = BattleResult::DRAW; } } int Battle::CalculateDamage() { int totalDamage = 0; if (m_result == BattleResult::PLAYER1_WIN) { m_p1Field.ForEach([&](const MinionData& minion) { totalDamage += minion.value().GetTier(); }); totalDamage += m_player1.currentTier; } else { m_p2Field.ForEach([&](const MinionData& minion) { totalDamage += minion.value().GetTier(); }); totalDamage += m_player2.currentTier; } return totalDamage; } const FieldZone& Battle::GetPlayer1Field() const { return m_p1Field; } const FieldZone& Battle::GetPlayer2Field() const { return m_p2Field; } int Battle::GetPlayer1NextAttacker() const { return m_p1NextAttackerIdx; } int Battle::GetPlayer2NextAttacker() const { return m_p2NextAttackerIdx; } BattleResult Battle::GetResult() const { return m_result; } } // namespace RosettaStone::Battlegrounds
28.291954
80
0.542781
Hearthstonepp
7c320e8880a227a1bb2501c2bd6e7bd6ba233ea0
1,447
hpp
C++
include/clotho/fitness/linear_fitness_metric.hpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
3
2015-06-16T21:27:57.000Z
2022-01-25T23:26:54.000Z
include/clotho/fitness/linear_fitness_metric.hpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
3
2015-06-16T21:12:42.000Z
2015-06-23T12:41:00.000Z
include/clotho/fitness/linear_fitness_metric.hpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// Copyright 2015 Patrick Putnam // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef LINEAR_FITNESS_METRIC_HPP_ #define LINEAR_FITNESS_METRIC_HPP_ #include <vector> #include "clotho/genetics/ifitness.hpp" extern const std::string LINEAR_FIT_NAME; class linear_fitness_metric : public ifitness { public: typedef double real_type; typedef real_type result_type; linear_fitness_metric( real_type a = 1., real_type b = 0. ) : m_val( c ) { } result_type operator()() { return m_B; } result_type operator()( real_type x ) { return m_A * x + m_B; } result_type operator()( const std::vector< real_type > & multi_variate ) { return m_B; } const std::string name() const; void log( std::ostream & out ) const; virtual ~linear_fitness_metric(); protected: real_type m_A, m_B; }; #endif // LINEAR_FITNESS_METRIC_HPP_
27.301887
78
0.68763
putnampp
7c3d1b998ba7e55703307ac573b0d4775b3151b5
388
hpp
C++
sdl2-sonic-drivers/src/utils/constants.hpp
Raffaello/sdl2-sonic-drivers
20584f100ddd7c61f584deaee0b46c5228d8509d
[ "Apache-2.0" ]
3
2021-10-31T14:24:00.000Z
2022-03-16T08:15:31.000Z
sdl2-sonic-drivers/src/utils/constants.hpp
Raffaello/sdl2-sonic-drivers
20584f100ddd7c61f584deaee0b46c5228d8509d
[ "Apache-2.0" ]
48
2020-06-05T11:11:29.000Z
2022-02-27T23:58:44.000Z
sdl2-sonic-drivers/src/utils/constants.hpp
Raffaello/sdl2-sonic-drivers
20584f100ddd7c61f584deaee0b46c5228d8509d
[ "Apache-2.0" ]
null
null
null
#pragma once #include <cmath> namespace utils { // TODO remove M_PI and M_2PI replace them with PI and PI2 #ifdef M_PI #undef M_PI #endif // M_PI constexpr double M_PI = 3.14159265358979323846; #ifdef M_2PI #undef M_2PI #endif // M_2PI constexpr double M_2PI = 2.0 * M_PI; constexpr double PI = 3.141592653589793238462643; constexpr double PI2 = PI * 2; }
18.47619
62
0.688144
Raffaello
7c423f5a6c83d0ccfe3ff3d33914a241403fcc8e
12,071
cpp
C++
Sourcecode/mxtest/core/PropertiesTest.cpp
diskzero/MusicXML-Class-Library
bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db
[ "MIT" ]
null
null
null
Sourcecode/mxtest/core/PropertiesTest.cpp
diskzero/MusicXML-Class-Library
bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db
[ "MIT" ]
null
null
null
Sourcecode/mxtest/core/PropertiesTest.cpp
diskzero/MusicXML-Class-Library
bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db
[ "MIT" ]
null
null
null
// MusicXML Class Library // Copyright (c) by Matthew James Briggs // Distributed under the MIT License #include "mxtest/control/CompileControl.h" #ifdef MX_COMPILE_CORE_TESTS #include "cpul/cpulTestHarness.h" #include "mxtest/core/HelperFunctions.h" #include "mxtest/core/PropertiesTest.h" #include "mxtest/core/EditorialGroupTest.h" using namespace mx::core; using namespace std; using namespace mxtest; TEST( Test01, Properties ) { variant v = variant::one; PropertiesPtr object = tgenProperties( v ); stringstream expected; tgenPropertiesExpected( expected, 1, v ); stringstream actual; // object->toStream( std::cout, 1 ); object->toStream( actual, 1 ); CHECK_EQUAL( expected.str(), actual.str() ) CHECK( ! object->hasAttributes() ) CHECK( ! object->hasContents() ) } TEST( Test02, Properties ) { variant v = variant::two; PropertiesPtr object = tgenProperties( v ); stringstream expected; tgenPropertiesExpected( expected, 1, v ); stringstream actual; // object->toStream( std::cout, 1 ); object->toStream( actual, 1 ); CHECK_EQUAL( expected.str(), actual.str() ) CHECK( ! object->hasAttributes() ) CHECK( object->hasContents() ) } TEST( Test03, Properties ) { variant v = variant::three; PropertiesPtr object = tgenProperties( v ); stringstream expected; tgenPropertiesExpected( expected, 1, v ); stringstream actual; // object->toStream( std::cout, 1 ); object->toStream( actual, 1 ); CHECK_EQUAL( expected.str(), actual.str() ) CHECK( ! object->hasAttributes() ) CHECK( object->hasContents() ) } namespace mxtest { PropertiesPtr tgenProperties( variant v ) { PropertiesPtr o = makeProperties(); switch ( v ) { case variant::one: { } break; case variant::two: { o->setEditorialGroup( tgenEditorialGroup( v ) ); auto d = makeDivisions(); d->setValue( PositiveDivisionsValue( 120 ) ); o->setDivisions( d ); o->setHasDivisions( true ); auto k = makeKey(); k->getKeyChoice()->setChoice( KeyChoice::Choice::traditionalKey ); k->getKeyChoice()->getTraditionalKey()->getFifths()->setValue( FifthsValue( -2 ) ); k->getKeyChoice()->getTraditionalKey()->setHasCancel( true ); k->getKeyChoice()->getTraditionalKey()->getCancel()->setValue( FifthsValue ( 1 ) ); o->addKey( k ); auto t = makeTime(); t->getTimeChoice()->setChoice( TimeChoice::Choice::timeSignature ); auto timeSignature = makeTimeSignatureGroup(); timeSignature->getBeats()->setValue( XsString( "3" ) ); timeSignature->getBeatType()->setValue( XsString( "4" ) ); t->getTimeChoice()->addTimeSignatureGroup( timeSignature ); t->getTimeChoice()->removeTimeSignatureGroup( t->getTimeChoice()->getTimeSignatureGroupSet().cbegin() ); o->addTime( t ); o->setHasStaves( true ); o->getStaves()->setValue( NonNegativeInteger( 4 ) ); o->setHasPartSymbol( true ); o->getPartSymbol()->setValue( GroupSymbolValue::none ); o->setHasInstruments( true ); o->getInstruments()->setValue( NonNegativeInteger( 3 ) ); auto c = makeClef(); c->getSign()->setValue( ClefSign::g ); c->getLine()->setValue( StaffLine( 2 ) ); c->setHasLine( true ); o->addClef( c ); auto sd = makeStaffDetails(); sd->setHasStaffLines( true ); sd->getStaffLines()->setValue( NonNegativeInteger( 5 ) ); sd->setHasStaffType( true ); sd->getStaffType()->setValue( StaffTypeEnum::regular ); o->addStaffDetails( sd ); auto dir = makeDirective(); dir->setValue( XsString( "allegro" ) ); dir->getAttributes()->hasLang = true; o->addDirective( dir ); auto ms = makeMeasureStyle(); ms->getMeasureStyleChoice()->setChoice( MeasureStyleChoice::Choice::slash ); ms->getMeasureStyleChoice()->getSlash()->getSlashType()->setValue( NoteTypeValue::eighth ); o->addMeasureStyle( ms ); } break; case variant::three: { o->setEditorialGroup( tgenEditorialGroup( v ) ); auto d = makeDivisions(); d->setValue( PositiveDivisionsValue( 99 ) ); o->setDivisions( d ); o->setHasDivisions( true ); auto k = makeKey(); k->getKeyChoice()->setChoice( KeyChoice::Choice::traditionalKey ); k->getKeyChoice()->getTraditionalKey()->getFifths()->setValue( FifthsValue( -2 ) ); k->getKeyChoice()->getTraditionalKey()->setHasCancel( true ); k->getKeyChoice()->getTraditionalKey()->getCancel()->setValue( FifthsValue ( 1 ) ); o->addKey( k ); auto t = makeTime(); t->getTimeChoice()->setChoice( TimeChoice::Choice::timeSignature ); auto timeSignature = makeTimeSignatureGroup(); timeSignature->getBeats()->setValue( XsString( "5" ) ); timeSignature->getBeatType()->setValue( XsString( "4" ) ); t->getTimeChoice()->addTimeSignatureGroup( timeSignature ); t->getTimeChoice()->removeTimeSignatureGroup( t->getTimeChoice()->getTimeSignatureGroupSet().cbegin() ); o->addTime( t ); o->setHasStaves( true ); o->getStaves()->setValue( NonNegativeInteger( 4 ) ); o->setHasPartSymbol( true ); o->getPartSymbol()->setValue( GroupSymbolValue::none ); o->setHasInstruments( true ); o->getInstruments()->setValue( NonNegativeInteger( 3 ) ); auto c = makeClef(); c->getSign()->setValue( ClefSign::g ); c->getLine()->setValue( StaffLine( 2 ) ); c->setHasLine( true ); o->addClef( c ); c = makeClef(); c->getSign()->setValue( ClefSign::c ); c->getLine()->setValue( StaffLine( 3 ) ); c->setHasLine( true ); o->addClef( c ); // auto sd = makeStaffDetails(); // sd->setHasStaffLines( true ); // sd->getStaffLines()->setValue( NonNegativeInteger( 5 ) ); // sd->setHasStaffType( true ); // sd->getStaffType()->setValue( StaffTypeEnum::regular ); // o->addStaffDetails( sd ); auto dir = makeDirective(); dir->setValue( XsString( "allegro" ) ); dir->getAttributes()->hasLang = true; o->addDirective( dir ); auto ms = makeMeasureStyle(); ms->getMeasureStyleChoice()->setChoice( MeasureStyleChoice::Choice::slash ); ms->getMeasureStyleChoice()->getSlash()->getSlashType()->setValue( NoteTypeValue::eighth ); o->addMeasureStyle( ms ); } break; default: break; } return o; } void tgenPropertiesExpected( std::ostream& os, int i, variant v ) { switch ( v ) { case variant::one: { streamLine( os, i, R"(<attributes/>)", false ); } break; case variant::two: { streamLine( os, i, R"(<attributes>)" ); tgenEditorialGroupExpected( os, i+1, v ); os << std::endl; streamLine( os, i+1, R"(<divisions>120</divisions>)" ); streamLine( os, i+1, R"(<key>)" ); streamLine( os, i+2, R"(<cancel>1</cancel>)" ); streamLine( os, i+2, R"(<fifths>-2</fifths>)" ); streamLine( os, i+1, R"(</key>)" ); streamLine( os, i+1, R"(<time>)" ); streamLine( os, i+2, R"(<beats>3</beats>)" ); streamLine( os, i+2, R"(<beat-type>4</beat-type>)" ); streamLine( os, i+1, R"(</time>)" ); streamLine( os, i+1, R"(<staves>4</staves>)" ); streamLine( os, i+1, R"(<part-symbol>none</part-symbol>)" ); streamLine( os, i+1, R"(<instruments>3</instruments>)" ); streamLine( os, i+1, R"(<clef>)" ); streamLine( os, i+2, R"(<sign>G</sign>)" ); streamLine( os, i+2, R"(<line>2</line>)" ); streamLine( os, i+1, R"(</clef>)" ); streamLine( os, i+1, R"(<staff-details>)" ); streamLine( os, i+2, R"(<staff-type>regular</staff-type>)" ); streamLine( os, i+2, R"(<staff-lines>5</staff-lines>)" ); streamLine( os, i+1, R"(</staff-details>)" ); streamLine( os, i+1, R"(<directive xml:lang="it">allegro</directive>)" ); streamLine( os, i+1, R"(<measure-style>)" ); streamLine( os, i+2, R"(<slash type="start">)" ); streamLine( os, i+3, R"(<slash-type>eighth</slash-type>)" ); streamLine( os, i+2, R"(</slash>)" ); streamLine( os, i+1, R"(</measure-style>)" ); streamLine( os, i, R"(</attributes>)", false ); } break; case variant::three: { streamLine( os, i, R"(<attributes>)" ); tgenEditorialGroupExpected( os, i+1, v ); os << std::endl; streamLine( os, i+1, R"(<divisions>99</divisions>)" ); streamLine( os, i+1, R"(<key>)" ); streamLine( os, i+2, R"(<cancel>1</cancel>)" ); streamLine( os, i+2, R"(<fifths>-2</fifths>)" ); streamLine( os, i+1, R"(</key>)" ); streamLine( os, i+1, R"(<time>)" ); streamLine( os, i+2, R"(<beats>5</beats>)" ); streamLine( os, i+2, R"(<beat-type>4</beat-type>)" ); streamLine( os, i+1, R"(</time>)" ); streamLine( os, i+1, R"(<staves>4</staves>)" ); streamLine( os, i+1, R"(<part-symbol>none</part-symbol>)" ); streamLine( os, i+1, R"(<instruments>3</instruments>)" ); streamLine( os, i+1, R"(<clef>)" ); streamLine( os, i+2, R"(<sign>G</sign>)" ); streamLine( os, i+2, R"(<line>2</line>)" ); streamLine( os, i+1, R"(</clef>)" ); streamLine( os, i+1, R"(<clef>)" ); streamLine( os, i+2, R"(<sign>C</sign>)" ); streamLine( os, i+2, R"(<line>3</line>)" ); streamLine( os, i+1, R"(</clef>)" ); // streamLine( os, i+1, R"(<staff-details>)" ); // streamLine( os, i+2, R"(<staff-type>regular</staff-type>)" ); // streamLine( os, i+2, R"(<staff-lines>5</staff-lines>)" ); // streamLine( os, i+1, R"(</staff-details>)" ); streamLine( os, i+1, R"(<directive xml:lang="it">allegro</directive>)" ); streamLine( os, i+1, R"(<measure-style>)" ); streamLine( os, i+2, R"(<slash type="start">)" ); streamLine( os, i+3, R"(<slash-type>eighth</slash-type>)" ); streamLine( os, i+2, R"(</slash>)" ); streamLine( os, i+1, R"(</measure-style>)" ); streamLine( os, i, R"(</attributes>)", false ); } break; default: break; } } } #endif
44.873606
120
0.498385
diskzero
7c45da4372eb53b9bbb2f92658006d7acf60e1c0
1,363
cpp
C++
Strings Problem/Valid Ip Addresses.cpp
theslytherin/Interview_Bit
da9973de33be2f12d6e051bea1e918004216b6ed
[ "MIT" ]
null
null
null
Strings Problem/Valid Ip Addresses.cpp
theslytherin/Interview_Bit
da9973de33be2f12d6e051bea1e918004216b6ed
[ "MIT" ]
null
null
null
Strings Problem/Valid Ip Addresses.cpp
theslytherin/Interview_Bit
da9973de33be2f12d6e051bea1e918004216b6ed
[ "MIT" ]
null
null
null
int stringnumber(string s){ int i=0; int n=s.length(); int face=1; int answer=0; for(i=n-1;i>=0;i--){ answer+=(s[i]-'0')*face; face*=10; } return answer; } bool isValid(string s){ int i,j; int n=s.length(); int number; int start=0; string temp=""; while(start < n){ i=start; temp=""; while(i<n && s[i]!='.')i++; if(i-start >3 ||i-start==0) return false; for(j=start;j<i;j++) temp+=s[j]; number=stringnumber(temp); if(number > 255) return false; if(number == 0 && i-start >1) return false; if(i-start > 1 && s[start]=='0') return false; start=i+1; } return true; } string copyString(string s,int i,int j,int k){ string x; for(int l=0;l<s.length();l++){ if(l==i) x+='.'; if(l==j) x+='.'; if(l==k) x+='.'; x+=s[l]; } return x; } vector<string> Solution::restoreIpAddresses(string A) { vector <string> B; int i,j,k; string s; int l=A.length(); for(i=0;i<l-1;i++) for(j=i+1;j<l-1;j++) for(k=j+1;k<l-1;k++){ s=copyString(A,i+1,j+1,k+1); if(isValid(s)) B.push_back(s); } return B; }
21.296875
55
0.432869
theslytherin
7c48357bb84762320f6d3c9346f67acfbca91d1c
5,398
cpp
C++
src/publish_trajectory/publish_trajectory_to_quadrotor_tmp.cpp
test-bai-cpu/hdi_plan
89684bb73832d7e40f3c669f284ffddb56a1e299
[ "MIT" ]
1
2021-07-31T12:34:11.000Z
2021-07-31T12:34:11.000Z
src/publish_trajectory/publish_trajectory_to_quadrotor_tmp.cpp
test-bai-cpu/hdi_plan
89684bb73832d7e40f3c669f284ffddb56a1e299
[ "MIT" ]
null
null
null
src/publish_trajectory/publish_trajectory_to_quadrotor_tmp.cpp
test-bai-cpu/hdi_plan
89684bb73832d7e40f3c669f284ffddb56a1e299
[ "MIT" ]
2
2021-05-08T13:27:31.000Z
2021-09-24T07:59:04.000Z
#include "publish_trajectory/publish_trajectory_to_quadrotor.hpp" namespace hdi_plan { PublishTrajectory::PublishTrajectory(const ros::NodeHandle &nh, const ros::NodeHandle &pnh) :nh_(nh), pnh_(pnh){ arm_bridge_pub_ = nh_.advertise<std_msgs::Bool>("bridge/arm", 1); start_pub_ = nh_.advertise<std_msgs::Empty>("autopilot/start", 1); //go_to_pose_pub_ = nh_.advertise<geometry_msgs::PoseStamped>("autopilot/pose_command", 100); trajectory_pub_ = nh_.advertise<quadrotor_msgs::Trajectory>("autopilot/trajectory", 1); //max_velocity_pub_ = nh_.advertise<std_msgs::Float64>("autopilot/max_velocity", 1); //trajectory_sub_ = nh_.subscribe("hdi_plan/full_trajectory", 1, &PublishTrajectory::trajectory_callback, this); pub_solution_path_ = nh_.advertise<geometry_msgs::PoseStamped>("autopilot/pose_command", 1); //get_new_path_sub_ = nh_.subscribe("hdi_plan/get_new_path", 1, &PublishTrajectory::get_new_path_callback, this); //quadrotor_state_sub_ = nh_.subscribe("hdi_plan/quadrotor_state", 1, &PublishTrajectory::quadrotor_state_callback, this); ros::Duration(9.0).sleep(); start_quadrotor_bridge(); ros::Duration(9.0).sleep(); ROS_INFO("Start to publish the trajectory!!!"); publish_trajectory(); } PublishTrajectory::~PublishTrajectory() {} void PublishTrajectory::quadrotor_state_callback(const nav_msgs::Odometry::ConstPtr &msg) { quadrotor_state_(0) = msg->pose.pose.position.x; quadrotor_state_(1) = msg->pose.pose.position.y; quadrotor_state_(2) = msg->pose.pose.position.z; } void PublishTrajectory::start_quadrotor_bridge() { ROS_INFO("###### Start the quadrotor bridge"); std_msgs::Bool arm_message; arm_message.data = true; this->arm_bridge_pub_.publish(arm_message); std_msgs::Empty empty_message; this->start_pub_.publish(empty_message); ros::Duration(7.0).sleep(); ROS_INFO("Go to pose msg"); geometry_msgs::PoseStamped go_to_pose_msg; go_to_pose_msg.pose.position.x = 0.0; go_to_pose_msg.pose.position.y = 2.0; go_to_pose_msg.pose.position.z = 2.0; this->pub_solution_path_.publish(go_to_pose_msg); } void PublishTrajectory::get_new_path_callback(const std_msgs::Bool::ConstPtr &msg) { this->if_get_new_path_ = msg->data; } /* void PublishTrajectory::trajectory_callback(const hdi_plan::point_array::ConstPtr &msg) { ROS_INFO("In the trajectory callback"); int trajectory_size = msg->points.size(); this->if_get_new_path_ = false; quadrotor_msgs::Trajectory trajectory_msg; trajectory_msg.header.stamp = ros::Time::now(); trajectory_msg.type = trajectory_msg.GENERAL; for (int i = 0; i < trajectory_size; i++) { quadrotor_msgs::TrajectoryPoint point; geometry_msgs::Point point_msg; point_msg.x = msg->points[i].x; point_msg.y = msg->points[i].y; point_msg.z = msg->points[i].z; point.pose.position = point_msg; trajectory_msg.points.push_back(point); } this->trajectory_pub_.publish(trajectory_msg); }*/ void PublishTrajectory::publish_trajectory() { ROS_INFO("check into publish trajectory"); std::vector<Eigen::Vector3d> optimized_trajectory; for (int i = 1; i < 11; i++) { Eigen::Vector3d point1(i, 2, 2); optimized_trajectory.push_back(point1); } int trajectory_size = optimized_trajectory.size(); geometry_msgs::PoseStamped go_to_pose_msg; for (int i = 0; i < trajectory_size; i++) { Eigen::Vector3d point = optimized_trajectory.at(i); go_to_pose_msg.pose.position.x = point(0); go_to_pose_msg.pose.position.y = point(1); go_to_pose_msg.pose.position.z = point(2); this->pub_solution_path_.publish(go_to_pose_msg); ros::Duration(0.7).sleep(); } /* std_msgs::Bool get_new_path_msg; get_new_path_msg.data = true; this->pub_get_new_path_.publish(get_new_path_msg);*/ } } /* trajectory_pub_ = nh_.advertise<hdi_plan::point_array>("hdi_plan/full_trajectory", 1); trigger_sub_ = nh_.subscribe("hdi_plan/trigger", 1, &PublishTrajectory::trigger_callback, this); pub_get_new_path_ = nh_.advertise<std_msgs::Bool>("hdi_plan/get_new_path", 1); void PublishTrajectory::trigger_callback(const std_msgs::Empty::ConstPtr &msg) { this->publish_trajectory(); } void PublishTrajectory::publish_another_trajectory() { ROS_INFO("check into another publish trajectory"); quadrotor_common::Trajectory trajectory; for (int i=0; i<10; i++) { quadrotor_common::TrajectoryPoint point = quadrotor_common::TrajectoryPoint(); Eigen::Vector3d position(1,i+1,10); point.position = position; trajectory.points.push_back(point); } quadrotor_msgs::Trajectory msg = trajectory.toRosMessage(); this->trajectory_pub_.publish(msg); } void PublishTrajectory::publish_trajectory() { ROS_INFO("check into publish trajectory"); std::vector<Eigen::Vector3d> optimized_trajectory; for (int i = 0; i < 10; i++) { Eigen::Vector3d point1(i, i+1, i+2); optimized_trajectory.push_back(point1); } hdi_plan::point_array trajectory_msg; int trajectory_size = optimized_trajectory.size(); geometry_msgs::Point trajectory_point; for (int i = 0; i < trajectory_size; i++) { Eigen::Vector3d point = optimized_trajectory.at(i); trajectory_point.x = point(0); trajectory_point.y = point(1); trajectory_point.z = point(2); trajectory_msg.points.push_back(trajectory_point); } std_msgs::Bool get_new_path_msg; get_new_path_msg.data = true; this->pub_get_new_path_.publish(get_new_path_msg); this->trajectory_pub_.publish(trajectory_msg); ROS_INFO("Finish publish trajectory"); } */
34.825806
123
0.757318
test-bai-cpu
7c4a20ef6c026977e9bb341654500cb624718f3f
437
hpp
C++
src/utils/types.hpp
LukaszSelwa/min-cut
f11eec7d3c55b886112179d8893ef6ed9b3fc2d5
[ "MIT" ]
null
null
null
src/utils/types.hpp
LukaszSelwa/min-cut
f11eec7d3c55b886112179d8893ef6ed9b3fc2d5
[ "MIT" ]
null
null
null
src/utils/types.hpp
LukaszSelwa/min-cut
f11eec7d3c55b886112179d8893ef6ed9b3fc2d5
[ "MIT" ]
null
null
null
#ifndef UTILS_TYPES_H #define UTILS_TYPES_H #include <memory> #include <vector> #include "../graphs/undirected_weighted_graph.hpp" struct algo_result { int minCutVal; std::vector<bool> cut; }; struct algo_input { std::shared_ptr<graphs::weighted_graph> graph; std::vector<bool> minCut; int minCutVal; }; bool validate_cuts(const std::vector<bool>& cutA, const std::vector<bool>& cutB); #endif /* UTILS_TYPES_H */
20.809524
81
0.718535
LukaszSelwa
7c4c0616aa4fa792076e6acee28793e04471ef6f
422
cpp
C++
机试/动态规划/leetcode300.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
机试/动态规划/leetcode300.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
机试/动态规划/leetcode300.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
class Solution { public: int lengthOfLIS(vector<int>& nums) { int n = nums.size(); vector<int> dp(n, 1); int res = dp[0]; for(int i = 0; i < n; i++){ for(int j = 0; j <= i; j++){ if(nums[i] > nums[j]){ dp[i] = max(dp[j] + 1, dp[i]); } } res = max(res, dp[i]); } return res; } };
24.823529
50
0.350711
codehuanglei
7c4c60fc018b62608c46fe0ec12d9b8de69d27c3
2,802
cpp
C++
trunk/uidesigner/uidframe/src/Core/HoldItem.cpp
OhmPopy/MPFUI
eac88d66aeb88d342f16866a8d54858afe3b6909
[ "MIT" ]
59
2017-08-27T13:27:55.000Z
2022-01-21T13:24:05.000Z
demos/uidesigner/uidframe/src/Core/HoldItem.cpp
BigPig0/MPFUI
7042e0a5527ab323e16d2106d715db4f8ee93275
[ "MIT" ]
5
2017-11-26T05:40:23.000Z
2019-04-02T08:58:21.000Z
demos/uidesigner/uidframe/src/Core/HoldItem.cpp
BigPig0/MPFUI
7042e0a5527ab323e16d2106d715db4f8ee93275
[ "MIT" ]
49
2017-08-24T08:00:50.000Z
2021-11-07T01:24:41.000Z
#include "stdafx.h" #include <Core/HoldItem.h> #include <Core/ResNode.h> void HoldItem::InitNode(suic::IXamlNode* pNode) { pNode->Reset(); InitNode(this, pNode); } void HoldItem::Clear() { for (int i = 0; i < children.GetCount(); ++i) { Clear(children.GetItem(i)); } attrs.Clear(); children.Clear(); } String HoldItem::GetResXml(const String& offset) { String strChild = GetResXml(this, offset); return strChild; } String HoldItem::GetChildResXml(const String& offset) { String strChild; for (int j = 0; j < children.GetCount(); ++j) { HoldItem* pChild = children.GetItem(j); strChild += GetResXml(pChild, offset); } return strChild; } void HoldItem::CloneTo(HoldItem* Other) { Other->Clear(); Other->name = name; for (int i = 0; i < attrs.GetCount(); ++i) { Other->attrs.Add(attrs.GetItem(i)); } for (int j = 0; j < children.GetCount(); ++j) { HoldItem* pChild = children.GetItem(j); HoldItem* pOtherChild = new HoldItem(); Other->children.Add(pOtherChild); pChild->CloneTo(pOtherChild); } } void HoldItem::Clear(HoldItem* pHold) { for (int i = 0; i < pHold->children.GetCount(); ++i) { Clear(pHold->children.GetItem(i)); } delete pHold; } void HoldItem::InitNode(HoldItem* pHold, suic::IXamlNode* pNode) { pHold->name = pNode->GetName(); suic::IXamlAttris* pAttris = pNode->GetAttris(); if (NULL != pAttris) { while (pAttris->HasNext()) { StringPair pair(pAttris->GetName(), pAttris->GetValue()); pHold->attrs.Add(pair); } } while (pNode->HasNext()) { suic::IXamlNode* childNode = pNode->Current(); if (NULL != childNode) { HoldItem* pChildItem = new HoldItem(); pHold->children.Add(pChildItem); InitNode(pChildItem, childNode); } } } String HoldItem::GetResXml(HoldItem* pHold, const String& offset) { String strXml; strXml += offset + _U("<") + pHold->name; for (int i = 0; i < pHold->attrs.GetCount(); ++i) { StringPair& pair = pHold->attrs.GetItem(i); strXml += _U(" ") + pair.GetKey() + _U("=\"") + pair.GetValue() + _U("\""); } if (pHold->children.GetCount() > 0) { strXml += _U(">\n"); String strChild; for (int j = 0; j < pHold->children.GetCount(); ++j) { HoldItem* pChildHold = pHold->children.GetItem(j); strChild += GetResXml(pChildHold, offset + ResNode::OFFSET1); } strXml += strChild; strXml += offset + _U("</") + pHold->name + _U(">\n"); } else { strXml += _U(" />\n"); } return strXml; }
22.416
83
0.552463
OhmPopy
7c50c242e93c7ac923266b8307ed15728e6e63f1
3,708
hpp
C++
src/sqlite/db.hpp
wesselj1/mx3playground
9b8c3e783f574a76cc17a9470b57e72a1b38be1a
[ "MIT" ]
766
2015-01-01T17:33:40.000Z
2022-02-23T08:20:20.000Z
src/sqlite/db.hpp
wesselj1/mx3playground
9b8c3e783f574a76cc17a9470b57e72a1b38be1a
[ "MIT" ]
43
2015-01-04T05:59:54.000Z
2017-06-19T10:53:59.000Z
src/sqlite/db.hpp
wesselj1/mx3playground
9b8c3e783f574a76cc17a9470b57e72a1b38be1a
[ "MIT" ]
146
2015-01-09T19:38:23.000Z
2021-09-30T08:39:44.000Z
#pragma once #include <set> #include <chrono> #include "stl.hpp" #include "stmt.hpp" namespace mx3 { namespace sqlite { // single param helpers for sqlite3_mprintf string mprintf(const char * format, const string& data); string mprintf(const char * format, int64_t data); string libversion(); string sourceid(); int libversion_number(); string escape_column(const string& column); enum class ChangeType { INSERT, UPDATE, DELETE }; enum class OpenFlag { READONLY, READWRITE, CREATE, URI, MEMORY, NOMUTEX, FULLMUTEX, SHAREDCACHE, PRIVATECACHE }; enum class Checkpoint { PASSIVE, FULL, RESTART }; enum class Affinity { TEXT, NUMERIC, INTEGER, REAL, NONE }; struct ColumnInfo final { int64_t cid; string name; string type; Affinity type_affinity() const; bool notnull; optional<string> dflt_value; int32_t pk; bool is_pk() const { return pk != 0; } }; struct TableInfo final { string name; string sql; int64_t rootpage; vector<ColumnInfo> columns; }; class Db final : public std::enable_shared_from_this<Db> { public: struct Change final { ChangeType type; string db_name; string table_name; int64_t rowid; }; using UpdateHookFn = function<void(Change)>; using CommitHookFn = function<bool()>; using RollbackHookFn = function<void()>; using WalHookFn = function<void(const string&, int)>; // use this constructor if you want to simply open the database with default settings static shared_ptr<Db> open(const string& path); // use this constructor if you want to simply open an in memory database with the default flags static shared_ptr<Db> open_memory(); // the most general Db constructor, directly mirrors sqlite3_open_v2 static shared_ptr<Db> open(const string& path, const std::set<OpenFlag>& flags, const optional<string>& vfs_name = nullopt); // use this constructor if you want to do anything custom to set up your database static shared_ptr<Db> inherit_db(sqlite3 * db); ~Db(); void update_hook(const UpdateHookFn& update_fn); void commit_hook(const CommitHookFn& commit_fn); void rollback_hook(const RollbackHookFn& rollback_fn); void wal_hook(const WalHookFn& wal_fn); std::pair<int, int> wal_checkpoint_v2(const optional<string>& db_name, Checkpoint mode); string journal_mode(); int64_t last_insert_rowid(); int32_t schema_version(); void busy_timeout(nullopt_t); void busy_timeout(std::chrono::system_clock::duration timeout); vector<TableInfo> schema_info(); optional<TableInfo> table_info(const string& table_name); vector<ColumnInfo> column_info(const string& table_name); int32_t user_version(); void set_user_version(int32_t user_ver); // give the ability to fetch the raw db pointer (in case you need to do anything special) sqlite3 * borrow_db(); shared_ptr<Stmt> prepare(const string& sql); void exec(const string& sql); int64_t exec_scalar(const string& sql); void enable_wal(); void close(); private: struct Closer final { void operator() (sqlite3 * db) const; }; struct only_for_internal_make_shared_t; public: // make_shared constructor Db(only_for_internal_make_shared_t flag, unique_ptr<sqlite3, Closer> db); private: unique_ptr<sqlite3, Closer> m_db; // To ensure proper memory management, these hooks are owned by the database. unique_ptr<UpdateHookFn> m_update_hook; unique_ptr<CommitHookFn> m_commit_hook; unique_ptr<RollbackHookFn> m_rollback_hook; unique_ptr<WalHookFn> m_wal_hook; }; } }
26.676259
128
0.699838
wesselj1
7c5115db2bd1096958da5285052bd6aa076b0e60
14,920
inl
C++
include/writer.inl
jpulidojr/VizAly-SNWPAC
ec30d5e50b8a7ab04a2888c8aae82dcb327e02bd
[ "Unlicense", "BSD-3-Clause" ]
2
2020-03-19T07:14:54.000Z
2022-03-11T19:29:33.000Z
include/writer.inl
jpulidojr/VizAly-SNWPAC
ec30d5e50b8a7ab04a2888c8aae82dcb327e02bd
[ "Unlicense", "BSD-3-Clause" ]
null
null
null
include/writer.inl
jpulidojr/VizAly-SNWPAC
ec30d5e50b8a7ab04a2888c8aae82dcb327e02bd
[ "Unlicense", "BSD-3-Clause" ]
2
2019-07-22T16:14:52.000Z
2020-03-19T07:14:56.000Z
#include "stdio.h" #include <iostream> #include <fstream> #include <cstdlib> #include <string.h> //#include <math.h> #include <sstream> //Use existing lossless compressors #include "lz4.h" /*static int * pfs1; static int dimx1, dimy1, dimz1; static int header_size1, scalar_fields1; static double field_len1;*/ // These functions typically used by LZ4 static size_t write_uint16(FILE* fp, uint16_t i) { return fwrite(&i, sizeof(i), 1, fp); } static size_t write_bin(FILE* fp, const void* array, int arrayBytes) { return fwrite(array, 1, arrayBytes, fp); } template <typename T> int arr_to_vti_3d_range_scale(T **** in, const char * filename,int xl,int xu, int yl,int yu, int zl, int zu, std::vector<std::string> names) { int sizeof_val = sizeof(in[0][0][0][0]); //if(!readConfigw()) //{ // std::cout << "Error reading configuration file. Exiting..." << std::endl; // return 0; //} //int *prefs = pfs1; //std::string * field_names = fn1; int dimx1 = (xu-xl)+1;//prefs[0]; int dimy1 = (yu-yl)+1;//prefs[1]; int dimz1 = (zu-zl)+1;//prefs[2]; //header_size1 = prefs[3]; int scalar_fields1 = names.size();//fld;//prefs[4]; //int num_blocks = prefs[5]; //std::cout << "Dimensions "<< dimx1 << " " << dimy1 << " " << dimz1 <<std::endl; //std::cout << "Header " << header_size1 << " Fields " << scalar_fields1<<std::endl; //std::cout << "Num Blocks " << num_blocks << std::endl; //field_len = (double)((length-header_size) / scalar_fields); size_t field_len1 = (double)dimx1*dimy1*dimz1*8; //std::cout << "Length per field: " << field_len1 << std::endl; // Skip the first bytes of the header //f.seekg (header_size, std::ios::cur); size_t len; len = strlen(filename); //std::string * part_filenames = new std::string[num_blocks+1]; int num_blocks=1; // Define arrays for extent lengths int ** ext_strt = new int*[num_blocks]; int ** ext_end = new int*[num_blocks]; for (int m = 0; m < num_blocks; ++m) { ext_strt[m] = new int[3]; ext_end[m] = new int[3]; } // Define a size for 1 block of data int * block_size=new int[3]; int blockID=0; // Set the extents for the entire dataset ext_strt[blockID][0]=xl; ext_strt[blockID][1]=yl; ext_strt[blockID][2]=zl; ext_end[blockID][0]=xu; ext_end[blockID][1]=yu; ext_end[blockID][2]=zu; // Set block size block_size[0]=(xu-xl)+1;block_size[1]=(yu-yl)+1;block_size[2]=(zu-zl)+1; // Start creating each individual block //for(int g=0; g<num_blocks; g++) //{ int g = 0; std::ofstream out; // Create the output file printf("Creating %s\n", filename); out.open(filename, std::ifstream::binary); out.precision(20); // Write VTK format header out << "<VTKFile type=\"ImageData\" version=\"0.1\" byte_order=\"LittleEndian\">"<<std::endl; out << " <ImageData WholeExtent=\""<<ext_strt[g][0]<<" "<<ext_end[g][0]<<" "<<ext_strt[g][1]; out << " "<<ext_end[g][1]<<" "<<ext_strt[g][2]<<" "<<ext_end[g][2]<<"\""; out << " Origin=\"0 0 0\" Spacing=\"1 1 1\">"<<std::endl; out << " <Piece Extent=\""<<ext_strt[g][0]<<" "<<ext_end[g][0]<<" "<<ext_strt[g][1]; out << " "<<ext_end[g][1]<<" "<<ext_strt[g][2]<<" "<<ext_end[g][2]<<"\">"<<std::endl; out << " <PointData Scalars=\"density_scalars\">"<<std::endl; int bin_offset = 0; int * ghost = new int[3]; // Write the headers for each of the scalar fields (assuming they're doubles) for(int i=0; i<scalar_fields1; i++) { // Factor in ghost data into the blocks if(ext_strt[g][0]!=0){ghost[0]=0;}else{ghost[0]=0;} if(ext_strt[g][1]!=0){ghost[1]=0;}else{ghost[1]=0;} if(ext_strt[g][2]!=0){ghost[2]=0;}else{ghost[2]=0;} //printf("%i %i %i\n", ghost[0], ghost[1], ghost[2]); if( sizeof_val == 8 ) out << " <DataArray type=\"Float64\" Name=\""<<names[i]<<"\" format=\"appended\" offset=\""<< (double)(i*((double)(block_size[0]+ghost[0])*(block_size[1]+ghost[1])*(block_size[2]+ghost[2])*8))+bin_offset <<"\"/>"<<std::endl; else if( sizeof_val == 4) out << " <DataArray type=\"Float32\" Name=\""<<names[i]<<"\" format=\"appended\" offset=\""<< (double)(i*((double)(block_size[0]+ghost[0])*(block_size[1]+ghost[1])*(block_size[2]+ghost[2])*4))+bin_offset <<"\"/>"<<std::endl; else { std::cout << "ERROR: Data size of " << sizeof_val << " bytes not supported for vti!" << std::endl; return -1; } bin_offset += 4; } out << " </PointData>"<<std::endl; out << " <CellData>" << std::endl; out << " </CellData>" << std::endl; out << " </Piece>"<<std::endl; out << " </ImageData>"<<std::endl; out << " <AppendedData encoding=\"raw\">"<<std::endl; // Denote that you are about to write in binary out << " _"; //char * bin_value= new char[sizeof_val];//[8]; //std::cout<< "["; for(int sf=0; sf < scalar_fields1; sf++) { // As per the API, first encode a 32-bit unsigned integer value specifying // the number of bytes in the block of data following it unsigned int block_byte_size = ((block_size[0]+ghost[0])*(block_size[1]+ghost[1])*(block_size[2]+ghost[2]))*8; if(((double)block_size[0]*block_size[1]*block_size[2]*8) > 4294967296.0) { printf("Error: Scalar field size is too large. Choose a larger\n"); printf("number of blocks to segment by.\n"); return 0; } out.write( reinterpret_cast<char*>( &block_byte_size ), 4 ); int c=0; for(int z=ext_strt[g][2]; z<=ext_end[g][2]; z++) { int b=0; for(int y=ext_strt[g][1]; y<=ext_end[g][1]; y++) { int a=0; for(int x=ext_strt[g][0]; x<=ext_end[g][0]; x++) { T dbl_val = (T)in[sf][a][b][c]; out.write(reinterpret_cast<char*>( &dbl_val ), sizeof_val);//sizeof(double)); a++; } b++; } c++; } //std::cout<<"] - "<<field_names[sf]<<" done!\n["; } //printf("Complete!"); //std::cout<<"]\n"; //Finish off the xml file out << std::endl; out << " </AppendedData>"<<std::endl; out << "</VTKFile>"; //printf("%s Done!\n", part_filenames[g+1].c_str()); out.close(); //} //std::cout<<"Done!"<<std::endl; return 0; } template <typename T> int save_coefficients(T * data, const char * filename, size_t total) { std::ofstream out; // Create the output file printf("Creating %s\n", filename); out.open(filename, std::ifstream::binary); out.precision(20); for(int sz=0; sz < total; sz++) { T dbl_val = data[sz]; out.write(reinterpret_cast<char*>( &dbl_val ), sizeof(T)); } std::cout<<"Coefficient's saved\n"; out.close(); return 1; } template <typename T> int save_coefficients_md(T * data, const char * filename, int * args) { std::ofstream out; // Create the output file printf("Creating %s\n", filename); out.open(filename, std::ifstream::binary); //out.precision(20); short * tmp_s = new short[1]; char * tmp_c = new char[1]; int * tmp_i = new int[1]; // Write the header tmp_s[0] = args[0]; out.write(reinterpret_cast<char*>( tmp_s ), sizeof(short)); tmp_s[0] = args[1]; out.write(reinterpret_cast<char*>( tmp_s ), sizeof(short)); tmp_c[0] = args[2]; out.write(reinterpret_cast<char*>( tmp_c ), sizeof(char)); tmp_s[0] = args[3]; out.write(reinterpret_cast<char*>( tmp_s ), sizeof(short)); tmp_i[0] = args[4]; out.write(reinterpret_cast<char*>( tmp_i ), sizeof(int)); tmp_i[0] = args[5]; out.write(reinterpret_cast<char*>( tmp_i ), sizeof(int)); tmp_i[0] = args[6]; out.write(reinterpret_cast<char*>( tmp_i ), sizeof(int)); tmp_i[0] = args[7]; out.write(reinterpret_cast<char*>( tmp_i ), sizeof(int)); tmp_i[0] = args[8]; out.write(reinterpret_cast<char*>( tmp_i ), sizeof(int)); tmp_i[0] = args[9]; out.write(reinterpret_cast<char*>( tmp_i ), sizeof(int)); tmp_c[0] = args[10];out.write(reinterpret_cast<char*>( tmp_c ), sizeof(char)); delete [] tmp_s; delete [] tmp_c; delete [] tmp_i; size_t total = (size_t)args[4]*(size_t)args[5]*(size_t)args[6]; // Check if we are using lz4 on coefficients if (args[2] >= 118) { std::cout << "Beginning LZ4 Routines..."; // Optional: Perform floating point to integer requantization: // No Requantization if args[2]=128 // When it's 125, it's 128-125 = 3. We divide by 1000 // When it's 131, it's 128-131 = -3. Multibly by 1000 double mod_bits = 1; size_t oval_sz = sizeof(T); if( args[2] > 128 ) // Multiply (for small dyn range data) { int cnt = args[2]; while (cnt != 128) { mod_bits *= 10.0; cnt--; } oval_sz = sizeof(int); std::cout << "requantizing coefficients: 1*10^" << args[2] - 128 << std::endl; } if(args[2] < 128 ) // Divide (for high dyn range data) { int cnt = args[2]; while (cnt != 128) { mod_bits /= 10.0; cnt++; } oval_sz = sizeof(int); std::cout << "requantizing coefficients: 1*10^-" << 128 - args[2] << std::endl; } // Target output variable (type) T dbl_val; //int dbl_val; // INT SUPPORT const size_t totBytes = total * oval_sz; size_t datBytes = totBytes; // WARNING: LZ4_MAX_INPUT_SIZE is about 2MB so suggest using a sliding buffer // Restriction inside of srcSize if (totBytes > LZ4_MAX_INPUT_SIZE) { std::cout << "Warning: Data to write is larger than supported by Lz4. Use rolling buffer!!\n"; datBytes = LZ4_MAX_INPUT_SIZE; } LZ4_stream_t* lz4Stream = LZ4_createStream(); const size_t cmpBufBytes = LZ4_COMPRESSBOUND(datBytes); //messageMaxBytes //Preallocate buffers char * inBuf = new char[datBytes]; char * cmpBuf = new char[cmpBufBytes]; // Use a sliding window approach and reinterpert type cast to char * array. // Use a ring buffer???? size_t max_vals = datBytes / oval_sz; std::cout << " Encoding " << max_vals << " values.\n"; size_t sk = 0; char * cval; if (oval_sz == 4) { int dbl_val; // int for requantization for (size_t sz = 0; sz < max_vals; sz++) { //dbl_val = data[sz]*100000; // INT SUPPORT dbl_val = data[sz]*mod_bits; // INT SUPPORT sk = sz * sizeof(dbl_val); cval = reinterpret_cast<char*>(&dbl_val); for (size_t id = 0; id < sizeof(dbl_val); id++) { inBuf[sk + id] = cval[id]; } } } else if (oval_sz == 8) { T dbl_val; // No requant for (size_t sz = 0; sz < max_vals; sz++) { dbl_val = data[sz]; sk = sz * sizeof(dbl_val); cval = reinterpret_cast<char*>(&dbl_val); for (size_t id = 0; id < sizeof(dbl_val); id++) { inBuf[sk + id] = cval[id]; } //delete[] cval; //inBuf[sk] = reinterpret_cast<char*>(&dbl_val), sizeof(dbl_val); //Insert T val into character buffer //memcpy? } } else { std::cout << "ERROR: Invalid byte size!" << std::endl; return -1; } //const int cmpBytes = LZ4_compress_fast_continue(lz4Stream, inBuf, cmpBuf, datBytes, cmpBufBytes, 1); /rolling int cmpBytes = LZ4_compress_default(inBuf, cmpBuf, datBytes, cmpBufBytes); //Write out the buffer size first //write_uint16(FILE* fp, uint16_t i) out.write(reinterpret_cast<char*>(&cmpBytes), sizeof(cmpBytes)); std::cout << "LZ4: Encoding " << cmpBytes << " bytes.." << std::endl; // Write out bytestream out.write(cmpBuf, cmpBytes); delete[] inBuf; delete[] cmpBuf; LZ4_freeStream(lz4Stream); std::cout << "..Done LZ4!\n"; } // Check if we are encoding coefficients with RLE else if(args[2] >= 64) { std::cout<<"Encoding enabled..."; //unsigned char signal = 0x24; //$ sign UTF-8 char signal = '$'; char signal2 = '@'; char signal3 = '#'; char signal4 = 'h'; //std::cout << "Size of char=" << sizeof(signal) << " value " << signal << std::endl; unsigned short smax=0; float wbytes=0; int skips=0; for(size_t sz=0; sz < total; sz++) { if (data[sz] == 0) { skips++; int cont_block_cnt=0; while (data[sz]==0 && sz < total) { sz++; cont_block_cnt++; // DEBUG } // Encode the number of steps to skip while(cont_block_cnt>65535) //Exceeded u_short_int { smax = 65535; out.write(reinterpret_cast<char*>( &signal ), sizeof(signal)); out.write(reinterpret_cast<char*>( &signal2 ), sizeof(signal2)); out.write(reinterpret_cast<char*>( &signal3 ), sizeof(signal3)); out.write(reinterpret_cast<char*>( &signal4 ), sizeof(signal4)); out.write(reinterpret_cast<char*>( &smax ), sizeof(smax)); skips++; cont_block_cnt-=65535; wbytes+=sizeof(signal)*4+sizeof(smax); } smax = cont_block_cnt; //std::cout << "\nSkipping at byte_loc: " << wbytes << " for " << smax << std::endl; out.write(reinterpret_cast<char*>( &signal ), sizeof(signal)); out.write(reinterpret_cast<char*>( &signal2 ), sizeof(signal2)); out.write(reinterpret_cast<char*>( &signal3 ), sizeof(signal3)); out.write(reinterpret_cast<char*>( &signal4 ), sizeof(signal4)); out.write(reinterpret_cast<char*>( &smax ), sizeof(smax)); wbytes+=sizeof(signal)*4+sizeof(smax); } T dbl_val = data[sz]; out.write(reinterpret_cast<char*>( &dbl_val ), sizeof(dbl_val)); wbytes+=sizeof(dbl_val); } std::cout<<"...Coefficient's saved\n"; std::cout<<"Bytes written (w header): " << wbytes+32 << std::endl; std::cout << "Contiguous skips: " << skips << std::endl; } // Just write coefficients to storage with zeros intact else { for(size_t sz=0; sz < total; sz++) { T dbl_val = data[sz]; out.write(reinterpret_cast<char*>( &dbl_val ), sizeof(T)); } std::cout<<"Coefficient's saved\n"; } out.close(); return 1; }
35.105882
235
0.552413
jpulidojr
7c5976175e28b08a295516dc36fcc5cec67f35a8
1,263
cpp
C++
cpp-tower/Game.cpp
udupa-varun/coursera-cs400
cf073e6fe816c0d1f8fe95cae10448e979fec2ce
[ "MIT" ]
2
2021-05-19T02:49:55.000Z
2021-05-20T03:14:24.000Z
cpp-tower/Game.cpp
udupa-varun/coursera-cs400
cf073e6fe816c0d1f8fe95cae10448e979fec2ce
[ "MIT" ]
null
null
null
cpp-tower/Game.cpp
udupa-varun/coursera-cs400
cf073e6fe816c0d1f8fe95cae10448e979fec2ce
[ "MIT" ]
null
null
null
/** * C++ class for a game of the Tower of Hanoi puzzle. * * @author * Wade Fagen-Ulmschneider <waf@illinois.edu> */ #include "Game.h" #include "Stack.h" #include "uiuc/Cube.h" #include "uiuc/HSLAPixel.h" #include <iostream> using std::cout; using std::endl; // Solves the Tower of Hanoi puzzle. // (Feel free to call "helper functions" to help you solve the puzzle.) void Game::solve() { // Prints out the state of the game: cout << *this << endl; // @TODO -- Finish solving the game! } // Default constructor to create the initial state: Game::Game() { // Create the three empty stacks: for (int i = 0; i < 3; i++) { Stack stackOfCubes; stacks_.push_back( stackOfCubes ); } // Create the four cubes, placing each on the [0]th stack: Cube blue(4, uiuc::HSLAPixel::BLUE); stacks_[0].push_back(blue); Cube orange(3, uiuc::HSLAPixel::ORANGE); stacks_[0].push_back(orange); Cube purple(2, uiuc::HSLAPixel::PURPLE); stacks_[0].push_back(purple); Cube yellow(1, uiuc::HSLAPixel::YELLOW); stacks_[0].push_back(yellow); } std::ostream& operator<<(std::ostream & os, const Game & game) { for (unsigned i = 0; i < game.stacks_.size(); i++) { os << "Stack[" << i << "]: " << game.stacks_[i]; } return os; }
23.388889
71
0.642914
udupa-varun
7c5ce1103a68b63e3fc9d600adfa560a410222c7
488
hpp
C++
src/eepp/window/backend/SDL2/wminfo.hpp
jayrulez/eepp
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
[ "MIT" ]
37
2020-01-20T06:21:24.000Z
2022-03-21T17:44:50.000Z
src/eepp/window/backend/SDL2/wminfo.hpp
jayrulez/eepp
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
[ "MIT" ]
null
null
null
src/eepp/window/backend/SDL2/wminfo.hpp
jayrulez/eepp
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
[ "MIT" ]
9
2019-03-22T00:33:07.000Z
2022-03-01T01:35:59.000Z
#ifndef EE_BACKEND_SDL2_WMINFO_HPP #define EE_BACKEND_SDL2_WMINFO_HPP #include <eepp/window/backend/SDL2/base.hpp> #include <eepp/window/windowhandle.hpp> namespace EE { namespace Window { namespace Backend { namespace SDL2 { class EE_API WMInfo { public: WMInfo( SDL_Window* win ); ~WMInfo(); #if defined( EE_X11_PLATFORM ) X11Window getWindow(); #endif eeWindowHandle getWindowHandler(); protected: void* mWMInfo; }; }}}} // namespace EE::Window::Backend::SDL2 #endif
17.428571
70
0.745902
jayrulez
7c5ed60bd233d69bcd3fec76f48a78d1253ad5bf
2,664
hpp
C++
OptFrame/Experimental/Moves/MoveVVShiftk.hpp
216k155/bft-pos
80c1c84b8ca9a5c1c7462b21b011c89ae97666ae
[ "MIT" ]
2
2018-05-24T11:04:12.000Z
2020-03-03T13:37:07.000Z
OptFrame/Experimental/Moves/MoveVVShiftk.hpp
216k155/bft-pos
80c1c84b8ca9a5c1c7462b21b011c89ae97666ae
[ "MIT" ]
null
null
null
OptFrame/Experimental/Moves/MoveVVShiftk.hpp
216k155/bft-pos
80c1c84b8ca9a5c1c7462b21b011c89ae97666ae
[ "MIT" ]
1
2019-06-06T16:57:49.000Z
2019-06-06T16:57:49.000Z
// OptFrame - Optimization Framework // Copyright (C) 2009-2015 // http://optframe.sourceforge.net/ // // This file is part of the OptFrame optimization framework. This framework // is free software; you can redistribute it and/or modify it under the // terms of the GNU Lesser General Public License v3 as published by the // Free Software Foundation. // This framework is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License v3 for more details. // You should have received a copy of the GNU Lesser General Public License v3 // along with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. #ifndef OPTFRAME_MOVEVVSHIFTK_HPP_ #define OPTFRAME_MOVEVVSHIFTK_HPP_ // Framework includes #include "../../Move.hpp" #include "../NSVector.hpp" using namespace std; //============================================================================ // VVShiftk Move //============================================================================ template<class T, class DS > class MoveVVShiftk : public Move<vector<vector<T> >, DS > { public: int k,v1,p1,v2,p2; MoveVVShiftk(int k,int v1,int p1,int v2,int p2) { this->k = k; this->v1 = v1; this->p1 = p1; this->v2 = v2; this->p2 = p2; } virtual bool canBeApplied(const vector<vector<T> >&) { return true; } virtual Move<vector<vector<T> >, DS >& apply(vector<vector<T> >& rep) { pair<int,pair < pair<int,int> , pair<int,int> > > m; m.first = k; m.second.first.first = v1; m.second.first.second = p1; m.second.second.first = v2; m.second.second.second = p2; NSVector<T>::shiftk_apply(rep,m); return * new MoveVVShiftk<T,DS >(k,v2,p2,v1,p1); } virtual Move<vector<vector<T> >, DS >& apply(DS& m, vector<vector<T> > & r) { if (!m.empty()) { m[v1].first = m[v2].first = -1; m[v1].second.first = p1; m[v1].second.second = r[v1].size()-1; m[v2].second.first = p2; m[v2].second.second = r[v2].size()-1; } else { //e->setMemory(new MemVRP(r.size(),make_pair(-1,make_pair(0,r.size()-1)))); m = MemVRPTW(r.size(),make_pair(-1,make_pair(0,r.size()-1))); } return apply(r); } virtual void print() const { cout << "Move Vector Vector Shiftk("<< k << " " << v1 << " " << p1 << " " << v2 << " " << p2 <<")"<<endl; } virtual bool operator==(const Move<vector<vector<T> >,DS >& m) const { return false; //TODO } }; #endif /*OPTFRAME_MOVEVVSHIFTK_HPP_*/
27.183673
107
0.613739
216k155
7c61d1f10673dfa4e36c148cfe5116240b21778a
5,786
cpp
C++
src/core/taskmanager.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
2
2019-06-22T23:29:44.000Z
2019-07-07T18:34:04.000Z
src/core/taskmanager.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
src/core/taskmanager.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
/** * @file taskmanager.cpp * @brief Implementation of TaskManager.h * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) * @date 2009-10-05 * @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved. * @details */ #include "o3d/core/precompiled.h" #include "o3d/core/taskmanager.h" #include "o3d/core/debug.h" #include <algorithm> using namespace o3d; TaskManager* TaskManager::m_instance = nullptr; // Singleton instantiation TaskManager* TaskManager::instance() { if (!m_instance) m_instance = new TaskManager(); return m_instance; } // Singleton destruction void TaskManager::destroy() { if (m_instance) { delete m_instance; m_instance = nullptr; } } // Default constructor TaskManager::TaskManager() : m_maxTask(5) { m_instance = (TaskManager*)this; // Used to avoid recursive call when the ctor call himself... // connect himself to the delete task signal onDeleteTask.connect(this, &TaskManager::deleteTask, EvtHandler::CONNECTION_ASYNCH); onFinalizeTask.connect(this, &TaskManager::finalizeTask, EvtHandler::CONNECTION_ASYNCH); } // Destructor TaskManager::~TaskManager() { m_mutex.lock(); // don't wait for any events, so disconnect from all disconnect(); // delete pending task (we don't want they occur) for (IT_TaskList it = m_pendingTasksList.begin(); it != m_pendingTasksList.end(); ++it) { deletePtr(*it); } m_pendingTasksList.clear(); // wait for the end of any running task for (IT_TaskList it = m_runningTasksList.begin(); it != m_runningTasksList.end(); ++it) { (*it)->waitFinish(); // and finally delete it directly deletePtr(*it); } m_runningTasksList.clear(); m_mutex.unlock(); } // Add a task to process. A new task is started if tasks slots are available void TaskManager::addTask(Task *task) { O3D_ASSERT(task); if (!task) { return; } else { RecurMutexLocker locker(m_mutex); // to start the next pending task at finish, for finalize and next for auto deletion task->onTaskFinished.connect(this, &TaskManager::taskFinished, EvtHandler::CONNECTION_ASYNCH); // or when the task execution failed, call for its auto deletion without finalize task->onTaskFailed.connect(this, &TaskManager::taskFailed, EvtHandler::CONNECTION_ASYNCH); // process immediately by this thread if (m_maxTask == 0) { m_runningTasksList.push_back(task); // process the task task->start(False); } else { // empty slot ? if (m_runningTasksList.size() < m_maxTask) { m_runningTasksList.push_back(task); // and start it task->start(True); } else { // pending queue m_pendingTasksList.push_back(task); } } } } // Define the number of maximum simultaneous running tasks. void TaskManager::setNumMaxTasks(UInt32 max) { RecurMutexLocker locker(m_mutex); m_maxTask = max; // start many others tasks as possible while ((m_runningTasksList.size() < m_maxTask) && !m_pendingTasksList.empty()) { Task *task = m_pendingTasksList.front(); m_pendingTasksList.pop_front(); m_runningTasksList.push_back(task); // and start it task->start(True); } } // Get the current number of running tasks. UInt32 TaskManager::getNumRunningTasks() const { RecurMutexLocker locker(const_cast<RecursiveMutex&>(m_mutex)); Int32 size = m_runningTasksList.size(); return size; } // Kills any running tasks. void TaskManager::kill() { RecurMutexLocker locker(m_mutex); for (IT_TaskList it = m_runningTasksList.begin(); it != m_runningTasksList.end(); ++it) { (*it)->kill(); deletePtr(*it); } m_runningTasksList.clear(); for (IT_TaskList it = m_pendingTasksList.begin(); it != m_pendingTasksList.end(); ++it) { deletePtr(*it); } m_pendingTasksList.clear(); } // When a task execution is not a success it call for its deletion. void TaskManager::taskFailed(Task* task) { O3D_ASSERT(task); RecurMutexLocker locker(m_mutex); if (task) { IT_TaskList it = std::find(m_runningTasksList.begin(), m_runningTasksList.end(), task); if (it != m_runningTasksList.end()) { m_runningTasksList.erase(it); onDeleteTask(task); } else { O3D_ERROR(E_InvalidParameter("Unknown running task")); } } // start a new task if necessary if (m_runningTasksList.size() < m_maxTask) { if (!m_pendingTasksList.empty()) { Task *task = m_pendingTasksList.front(); m_pendingTasksList.pop_front(); m_runningTasksList.push_back(task); // and start it task->start(True); } } } // When a task is finished to process it call for its finalize. void TaskManager::taskFinished(Task* task) { O3D_ASSERT(task); if (task) { onFinalizeTask(task); } } // When a task is finalized it call for its deletion. void TaskManager::finalizeTask(Task* task) { O3D_ASSERT(task); if (task) { // finalize task->synchronize(); RecurMutexLocker locker(m_mutex); IT_TaskList it = std::find(m_runningTasksList.begin(), m_runningTasksList.end(), task); if (it != m_runningTasksList.end()) { m_runningTasksList.erase(it); onDeleteTask(task); } else { O3D_ERROR(E_InvalidParameter("Unknown running task")); } } // start a new task if necessary if (m_runningTasksList.size() < m_maxTask) { if (!m_pendingTasksList.empty()) { Task *task = m_pendingTasksList.front(); m_pendingTasksList.pop_front(); m_runningTasksList.push_back(task); // and start it task->start(True); } } } // When delete a task. void TaskManager::deleteTask(Task* task) { O3D_ASSERT(task); if (task) { o3d::deletePtr(task); } }
23.330645
102
0.674732
dream-overflow
7c6a02ae781b48453f543d541aa3efa1524e8e21
4,048
cpp
C++
UVA Online Judge/628_Passwords.cpp
davimedio01/competitive-programming
e2a90f0183c11a90a50738a9a690efe03773d43f
[ "MIT" ]
2
2020-09-10T15:48:02.000Z
2020-09-12T00:05:35.000Z
UVA Online Judge/628_Passwords.cpp
davimedio01/competitive-programming
e2a90f0183c11a90a50738a9a690efe03773d43f
[ "MIT" ]
null
null
null
UVA Online Judge/628_Passwords.cpp
davimedio01/competitive-programming
e2a90f0183c11a90a50738a9a690efe03773d43f
[ "MIT" ]
2
2020-09-09T17:01:05.000Z
2020-09-09T17:02:27.000Z
/*Criado por Davi Augusto - BCC - UNESP Bauru*/ /* Resolvido com Backtracking: 1 - "Escolhas" 2 - "Restrições" 3 - "Objetivo" Escolhas: Colocar dígitos de 0 a 9 na senha com base nas "regras" (# e 0) Restrições: Regras e o dígito (ex: #0). O '#' ficará a palavra e o dígito '0' os números de 0 a 9. Printar crescente. Objetivos: Mostrar todo o conjunto de senha com as regras dadas Critério de parada: dígito alcançar 9 (i <= 9); forem todas as palavras do vetor; todos dígitos disponíveis Padrão: 1) Ir até o final da regra; 2) Ver qual campo é: -> Se for '#', mostrar a palavra atual -> Se for '0', mostrar dígitos de 0 a 9; CONTUDO... 3) Necessário mostrar crescente... Ciclo até fim do vector de palavras */ #include <bits/stdc++.h> #include <iostream> using namespace std; //Função para Mostrar todas as Palavras void mostraPalavras(vector<string> dicio, vector<string> auxfinal){ for(int i = 0; i < dicio.size(); i++){ for(int j = 0; j < auxfinal.size(); j++){ cout << auxfinal[j]; } cout << dicio[i] << endl; } } //Função para Mostrar todos os Dígitos (0 a 9) void mostraDigitos(vector<string> auxfinal){ for (int i = 0; i <= 9; i++) { for (int j = 0; j < auxfinal.size(); j++) { cout << auxfinal[j]; } cout << i << endl; } } //Backtracking void resolveSenha(vector<string> dicio, string regra, int caracRegra, vector<string> auxfinal) { //Caso chegue no último, analisar if(caracRegra == (regra.length()-1)){ //Verificar o caractere correspondente e printar //Dígito if (regra[caracRegra] == '0'){ mostraDigitos(auxfinal); } else if (regra[caracRegra] == '#'){ //Palavra mostraPalavras(dicio, auxfinal); } return; } //Dígito if(regra[caracRegra] == '0'){ for(int i = 0; i <= 9; i++){ //Copiar o dígito pra auxiliar auxfinal.push_back(to_string(i)); //Executando a função novamente e avançando o dígito da regra resolveSenha(dicio, regra, caracRegra + 1, auxfinal); //Removendo o Último Elemento da Auxiliar auxfinal.pop_back(); } } else if(regra[caracRegra] == '#'){ //Palavra for(int j = 0; j < dicio.size(); j++){ //Copiar a palavra pra auxiliar auxfinal.push_back(dicio[j]); //Executando a função novamente e avançando o dígito da regra resolveSenha(dicio, regra, caracRegra + 1, auxfinal); //Removendo o Último Elemento da Auxiliar auxfinal.pop_back(); } } } int main(){ int numpalavras, numregras; while(cin >> numpalavras){ //Vector contendo Dicionário vector<string> dicionario; dicionario.clear(); string dicioaux; //Lendo cada palavra for(int i = 0; i < numpalavras; i++){ cin >> dicioaux; dicionario.push_back(dicioaux); } //Lendo Qtd de Regras cin >> numregras; //Vector contendo as regras vector<string> regras; regras.clear(); string regraux; //Lendo cada regra for(int i = 0; i < numregras; i++){ cin >> regraux; regras.push_back(regraux); } //Mostrando resultado (Backtracking) cout << "--" << endl; //Passar cada regra vector<string> auxfinal; for(int i = 0; i < numregras; i++){ auxfinal.clear(); resolveSenha(dicionario, regras[i], 0, auxfinal); } } return 0; }
28.70922
118
0.516304
davimedio01
7c6a4d9e5140b66d9f8a1a9d1f899b93076511af
10,895
cpp
C++
Main/Libraries/Hunspell/HunspellExportFunctions.cpp
paulushub/SandAssists
ccd86a074e85b3588819253f241780fe9d9362e2
[ "MS-PL" ]
1
2018-12-13T19:41:01.000Z
2018-12-13T19:41:01.000Z
Main/Libraries/Hunspell/HunspellExportFunctions.cpp
paulushub/SandAssists
ccd86a074e85b3588819253f241780fe9d9362e2
[ "MS-PL" ]
null
null
null
Main/Libraries/Hunspell/HunspellExportFunctions.cpp
paulushub/SandAssists
ccd86a074e85b3588819253f241780fe9d9362e2
[ "MS-PL" ]
null
null
null
#include "hunspell/hunspell.hxx" #include <windows.h> #include <locale.h> #include <mbctype.h> #include "NHunspellExtensions.h" #include "EncodingToCodePage.h" #define DLLEXPORT extern "C" __declspec( dllexport ) class NHunspell: public Hunspell { // The methods aren't multi threaded, reentrant or whatever so a encapsulated buffer can be used for performance reasons void * marshalBuffer; size_t marshalBufferSize; void * wordBuffer; size_t wordBufferSize; void * word2Buffer; size_t word2BufferSize; void * affixBuffer; size_t affixBufferSize; public: UINT CodePage; inline NHunspell(const char *affpath, const char *dpath, const char * key = 0) : Hunspell(affpath,dpath,key) { marshalBuffer = 0; marshalBufferSize = 0; wordBuffer = 0; wordBufferSize = 0; word2Buffer = 0; word2BufferSize = 0; affixBuffer = 0; affixBufferSize = 0; char * encoding = get_dic_encoding(); CodePage = EncodingToCodePage( encoding ); } inline ~NHunspell() { if( marshalBuffer != 0 ) free( marshalBuffer ); if( wordBuffer != 0 ) free( wordBuffer ); if( word2Buffer != 0 ) free( word2Buffer ); if( affixBuffer != 0 ) free( affixBuffer ); } // Buffer for marshaling string lists back to .NET void * GetMarshalBuffer(size_t size) { if(size < marshalBufferSize ) return marshalBuffer; if( marshalBufferSize == 0 ) { size += 128; marshalBuffer = malloc( size ); } else { size += 256; marshalBuffer = realloc(marshalBuffer, size ); } marshalBufferSize = size; return marshalBuffer; } // Buffer for the mutibyte representation of a word void * GetWordBuffer(size_t size) { if(size < wordBufferSize ) return wordBuffer; if( wordBufferSize == 0 ) { size += 32; wordBuffer = malloc( size ); } else { size += 64; wordBuffer = realloc(wordBuffer, size ); } wordBufferSize = size; return wordBuffer; } // Buffer for the mutibyte representation of a word void * GetWord2Buffer(size_t size) { if(size < word2BufferSize ) return word2Buffer; if( word2BufferSize == 0 ) { size += 32; word2Buffer = malloc( size ); } else { size += 64; word2Buffer = realloc(wordBuffer, size ); } word2BufferSize = size; return word2Buffer; } inline char * GetWordBuffer( wchar_t * unicodeString ) { int buffersize = WideCharToMultiByte(CodePage,0,unicodeString,-1,0,0,0,0); char * buffer = (char *) GetWordBuffer( buffersize ); WideCharToMultiByte(CodePage,0,unicodeString,-1,buffer,buffersize,0,0); return buffer; } inline char * GetWord2Buffer( wchar_t * unicodeString ) { int buffersize = WideCharToMultiByte(CodePage,0,unicodeString,-1,0,0,0,0); char * buffer = (char *) GetWord2Buffer( buffersize ); WideCharToMultiByte(CodePage,0,unicodeString,-1,buffer,buffersize,0,0); return buffer; } // Buffer for the mutibyte representation of an affix void * GetAffixBuffer(size_t size) { if(size < affixBufferSize ) return affixBuffer; if( affixBufferSize == 0 ) { size += 32; affixBuffer = malloc( size ); } else { size += 64; affixBuffer = realloc(affixBuffer, size ); } affixBufferSize = size; return affixBuffer; } inline char * GetAffixBuffer( wchar_t * unicodeString ) { int buffersize = WideCharToMultiByte(CodePage,0,unicodeString,-1,0,0,0,0); char * buffer = (char *) GetAffixBuffer( buffersize ); WideCharToMultiByte(CodePage,0,unicodeString,-1,buffer,buffersize,0,0); return buffer; } }; inline char * AllocMultiByteBuffer( wchar_t * unicodeString ) { int buffersize = WideCharToMultiByte(CP_UTF8,0,unicodeString,-1,0,0,0,0); char * buffer = (char *) malloc( buffersize ); WideCharToMultiByte(CP_UTF8,0,unicodeString,-1,buffer,buffersize,0,0); return buffer; } /************************* Export Functions **************************************************************/ DLLEXPORT NHunspell * HunspellInit(void * affixBuffer, size_t affixBufferSize, void * dictionaryBuffer, size_t dictionaryBufferSize, wchar_t * key) { char * key_buffer = 0; if( key != 0 ) key_buffer = AllocMultiByteBuffer(key); MemoryBufferInformation affixBufferInfo; affixBufferInfo.magic = magicConstant; affixBufferInfo.buffer = affixBuffer; affixBufferInfo.bufferSize = affixBufferSize; MemoryBufferInformation dictionaryBufferInfo; dictionaryBufferInfo.magic = magicConstant; dictionaryBufferInfo.buffer = dictionaryBuffer; dictionaryBufferInfo.bufferSize = dictionaryBufferSize; NHunspell * result = new NHunspell((const char *) &affixBufferInfo, (const char *) &dictionaryBufferInfo,key_buffer); if( key_buffer != 0 ) free( key_buffer ); return result; } DLLEXPORT void HunspellFree(NHunspell * handle ) { delete handle; } DLLEXPORT bool HunspellAdd(NHunspell * handle, wchar_t * word ) { char * word_buffer = handle->GetWordBuffer(word); int success = handle->add(word_buffer); return success != 0; } DLLEXPORT bool HunspellAddWithAffix(NHunspell * handle, wchar_t * word, wchar_t * example ) { char * word_buffer = ((NHunspell *) handle)->GetWordBuffer(word); char * example_buffer = ((NHunspell *) handle)->GetWord2Buffer(example); bool success = handle->add_with_affix(word_buffer,example_buffer) != 0; return success; } DLLEXPORT bool HunspellSpell(NHunspell * handle, wchar_t * word ) { char * word_buffer = ((NHunspell *) handle)->GetWordBuffer(word); bool correct = ((NHunspell *) handle)->spell(word_buffer) != 0; return correct; } DLLEXPORT void * HunspellSuggest(NHunspell * handle, wchar_t * word ) { char * word_buffer = ((NHunspell *) handle)->GetWordBuffer(word); char ** wordList; int wordCount = ((NHunspell *) handle)->suggest(&wordList, word_buffer); // Cacculation of the Marshalling Buffer. // Layout: {Pointers- zero terminated}{Wide Strings - zero terminated} size_t bufferSize = (wordCount + 1) * sizeof (wchar_t **); for( int i = 0; i < wordCount; ++ i ) bufferSize += MultiByteToWideChar(handle->CodePage,0,wordList[i],-1,0,0) * sizeof( wchar_t); BYTE * marshalBuffer = (BYTE *) ((NHunspell *) handle)->GetMarshalBuffer( bufferSize ); wchar_t ** pointer = (wchar_t ** ) marshalBuffer; wchar_t * buffer = (wchar_t * ) (marshalBuffer + (wordCount + 1) * sizeof (wchar_t **)); for( int i = 0; i < wordCount; ++ i ) { *pointer = buffer; size_t wcsSize = MultiByteToWideChar(handle->CodePage,0,wordList[i],-1,0,0); MultiByteToWideChar(handle->CodePage,0,wordList[i],-1,buffer,wcsSize); // Prepare pointers for the next string buffer += wcsSize; ++pointer; } // Zero terminate the pointer list *pointer = 0; ((NHunspell *) handle)->free_list(&wordList, wordCount); return marshalBuffer; } DLLEXPORT void * HunspellAnalyze(NHunspell * handle, wchar_t * word ) { char * word_buffer = ((NHunspell *) handle)->GetWordBuffer(word); char ** morphList; int morphCount = ((NHunspell *) handle)->analyze(&morphList, word_buffer); // Cacculation of the Marshalling Buffer. Layout: {Pointers- zero terminated}{Wide Strings - zero terminated} size_t bufferSize = (morphCount + 1) * sizeof (wchar_t **); for( int i = 0; i < morphCount; ++ i ) bufferSize += MultiByteToWideChar(handle->CodePage,0,morphList[i],-1,0,0) * sizeof( wchar_t); BYTE * marshalBuffer = (BYTE *) ((NHunspell *) handle)->GetMarshalBuffer( bufferSize ); wchar_t ** pointer = (wchar_t ** ) marshalBuffer; wchar_t * buffer = (wchar_t * ) (marshalBuffer + (morphCount + 1) * sizeof (wchar_t **)); for( int i = 0; i < morphCount; ++ i ) { *pointer = buffer; size_t wcsSize = MultiByteToWideChar(handle->CodePage,0,morphList[i],-1,0,0); MultiByteToWideChar(handle->CodePage,0,morphList[i],-1,buffer,wcsSize); // Prepare pointers for the next string buffer += wcsSize; ++pointer; } // Zero terminate the pointer list *pointer = 0; ((NHunspell *) handle)->free_list(&morphList, morphCount); return marshalBuffer; } DLLEXPORT void * HunspellStem(NHunspell * handle, wchar_t * word ) { char * word_buffer = ((NHunspell *) handle)->GetWordBuffer(word); char ** stemList; int stemCount = ((NHunspell *) handle)->stem(&stemList, word_buffer); // Cacculation of the Marshalling Buffer. Layout: {Pointers- zero terminated}{Wide Strings - zero terminated} size_t bufferSize = (stemCount + 1) * sizeof (wchar_t **); for( int i = 0; i < stemCount; ++ i ) bufferSize += MultiByteToWideChar(handle->CodePage,0,stemList[i],-1,0,0) * sizeof( wchar_t); BYTE * marshalBuffer = (BYTE *) ((NHunspell *) handle)->GetMarshalBuffer( bufferSize ); wchar_t ** pointer = (wchar_t ** ) marshalBuffer; wchar_t * buffer = (wchar_t * ) (marshalBuffer + (stemCount + 1) * sizeof (wchar_t **)); for( int i = 0; i < stemCount; ++ i ) { *pointer = buffer; size_t wcsSize = MultiByteToWideChar(handle->CodePage,0,stemList[i],-1,0,0); MultiByteToWideChar(handle->CodePage,0,stemList[i],-1,buffer,wcsSize); // Prepare pointers for the next string buffer += wcsSize; ++pointer; } // Zero terminate the pointer list *pointer = 0; ((NHunspell *) handle)->free_list(&stemList, stemCount); return marshalBuffer; } DLLEXPORT void * HunspellGenerate(NHunspell * handle, wchar_t * word, wchar_t * word2 ) { char * word_buffer = ((NHunspell *) handle)->GetWordBuffer(word); char * word2_buffer = ((NHunspell *) handle)->GetWord2Buffer(word2); char ** stemList; int stemCount = ((NHunspell *) handle)->generate(&stemList, word_buffer, word2_buffer); // Cacculation of the Marshalling Buffer. Layout: {Pointers- zero terminated}{Wide Strings - zero terminated} size_t bufferSize = (stemCount + 1) * sizeof (wchar_t **); for( int i = 0; i < stemCount; ++ i ) bufferSize += MultiByteToWideChar(handle->CodePage,0,stemList[i],-1,0,0) * sizeof( wchar_t); BYTE * marshalBuffer = (BYTE *) ((NHunspell *) handle)->GetMarshalBuffer( bufferSize ); wchar_t ** pointer = (wchar_t ** ) marshalBuffer; wchar_t * buffer = (wchar_t * ) (marshalBuffer + (stemCount + 1) * sizeof (wchar_t **)); for( int i = 0; i < stemCount; ++ i ) { *pointer = buffer; size_t wcsSize = MultiByteToWideChar(handle->CodePage,0,stemList[i],-1,0,0); MultiByteToWideChar(handle->CodePage,0,stemList[i],-1,buffer,wcsSize); // Prepare pointers for the next string buffer += wcsSize; ++pointer; } // Zero terminate the pointer list *pointer = 0; ((NHunspell *) handle)->free_list(&stemList, stemCount); return marshalBuffer; }
27.935897
148
0.663148
paulushub
7c7271cd1bc6633e31eff5ad8cfbeb76ab576099
11,886
hpp
C++
libraries/protocol/include/deip/protocol/deip_virtual_operations.hpp
DEIPworld/deip-chain
d3fdcfdde179f700156156ea87522a807ec52532
[ "MIT" ]
1
2021-08-16T12:44:43.000Z
2021-08-16T12:44:43.000Z
libraries/protocol/include/deip/protocol/deip_virtual_operations.hpp
DEIPworld/deip-chain
d3fdcfdde179f700156156ea87522a807ec52532
[ "MIT" ]
null
null
null
libraries/protocol/include/deip/protocol/deip_virtual_operations.hpp
DEIPworld/deip-chain
d3fdcfdde179f700156156ea87522a807ec52532
[ "MIT" ]
2
2021-08-16T12:44:46.000Z
2021-12-31T17:09:45.000Z
#pragma once #include <deip/protocol/base.hpp> #include <deip/protocol/block_header.hpp> #include <deip/protocol/asset.hpp> #include <deip/protocol/eci_diff.hpp> #include <fc/utf8.hpp> namespace deip { namespace protocol { struct fill_common_tokens_withdraw_operation : public virtual_operation { fill_common_tokens_withdraw_operation() {} fill_common_tokens_withdraw_operation(const string& f, const string& t, const share_type& w, const share_type& d, const bool tr) : from_account(f) , to_account(t) , withdrawn(w) , deposited(d) , transfer(tr) { } account_name_type from_account; account_name_type to_account; share_type withdrawn; share_type deposited; bool transfer; }; struct shutdown_witness_operation : public virtual_operation { shutdown_witness_operation() {} shutdown_witness_operation(const string& o) : owner(o) { } account_name_type owner; }; struct hardfork_operation : public virtual_operation { hardfork_operation() {} hardfork_operation(uint32_t hf_id) : hardfork_id(hf_id) { } uint32_t hardfork_id = 0; }; struct producer_reward_operation : public virtual_operation { producer_reward_operation() {} producer_reward_operation(const string& p, const share_type c) : producer(p) , common_tokens_amount(c) { } account_name_type producer; share_type common_tokens_amount; }; struct token_sale_contribution_to_history_operation : public virtual_operation { token_sale_contribution_to_history_operation() {} token_sale_contribution_to_history_operation(const int64_t& research_id, const external_id_type& research_external_id, const int64_t& research_token_sale_id, const external_id_type& research_token_sale_external_id, const string& contributor, const asset& amount) : research_id(research_id) , research_external_id(research_external_id) , research_token_sale_id(research_token_sale_id) , research_token_sale_external_id(research_token_sale_external_id) , contributor(contributor) , amount(amount) { } int64_t research_id; external_id_type research_external_id; int64_t research_token_sale_id; external_id_type research_token_sale_external_id; account_name_type contributor; asset amount; }; struct research_content_reference_history_operation : public virtual_operation { research_content_reference_history_operation() {} research_content_reference_history_operation(const int64_t& research_content_id, const external_id_type& research_content_external_id, const int64_t& research_id, const external_id_type& research_external_id, const std::string& content, const int64_t& research_content_reference_id, const external_id_type& research_content_reference_external_id, const int64_t& research_reference_id, const external_id_type& research_reference_external_id, const std::string& content_reference) : research_content_id(research_content_id) , research_content_external_id(research_content_external_id) , research_id(research_id) , research_external_id(research_external_id) , content(content) , research_content_reference_id(research_content_reference_id) , research_content_reference_external_id(research_content_reference_external_id) , research_reference_id(research_reference_id) , research_reference_external_id(research_reference_external_id) , content_reference(content_reference) { } int64_t research_content_id; external_id_type research_content_external_id; int64_t research_id; external_id_type research_external_id; std::string content; int64_t research_content_reference_id; external_id_type research_content_reference_external_id; int64_t research_reference_id; external_id_type research_reference_external_id; std::string content_reference; }; struct research_content_eci_history_operation : public virtual_operation { research_content_eci_history_operation() {} research_content_eci_history_operation(const int64_t& research_content_id, const int64_t& discipline_id, const eci_diff& diff) : research_content_id(research_content_id) , discipline_id(discipline_id) , diff(diff) { } int64_t research_content_id; int64_t discipline_id; eci_diff diff; }; struct research_eci_history_operation : public virtual_operation { research_eci_history_operation() {} research_eci_history_operation(const int64_t& research_id, const int64_t& discipline_id, const eci_diff& diff) : research_id(research_id) , discipline_id(discipline_id) , diff(diff) { } int64_t research_id; int64_t discipline_id; eci_diff diff; }; struct account_eci_history_operation : public virtual_operation { account_eci_history_operation() {} account_eci_history_operation(const account_name_type& account, const int64_t& discipline_id, const uint16_t& recipient_type, const eci_diff& diff) : account(account) , discipline_id(discipline_id) , recipient_type(recipient_type) , diff(diff) { } account_name_type account; int64_t discipline_id; uint16_t recipient_type; eci_diff diff; }; struct disciplines_eci_history_operation : public virtual_operation { disciplines_eci_history_operation(){} disciplines_eci_history_operation(const flat_map<int64_t, vector<eci_diff>>& contributions_map, const fc::time_point_sec& timestamp) : timestamp(timestamp) { for (const auto& pair : contributions_map) { contributions.insert(pair); } } flat_map<int64_t, vector<eci_diff>> contributions; fc::time_point_sec timestamp; }; struct account_revenue_income_history_operation : public virtual_operation { account_revenue_income_history_operation() {} account_revenue_income_history_operation(const account_name_type& account, const asset& security_token, const asset& revenue, const fc::time_point_sec& timestamp) : account(account) , security_token(security_token) , revenue(revenue) , timestamp(timestamp) { } account_name_type account; asset security_token; asset revenue; fc::time_point_sec timestamp; }; struct proposal_status_changed_operation : public virtual_operation { proposal_status_changed_operation() { } proposal_status_changed_operation(const external_id_type& external_id, const uint8_t& status) : external_id(external_id) , status(status) { } external_id_type external_id; uint8_t status; }; struct create_genesis_proposal_operation : public virtual_operation { create_genesis_proposal_operation() { } create_genesis_proposal_operation(const external_id_type& external_id, const account_name_type& proposer, const string& serialized_proposed_transaction, const time_point_sec& expiration_time, const time_point_sec& created_at, const optional<time_point_sec>& review_period, const flat_set<account_name_type>& available_active_approvals, const flat_set<account_name_type>& available_owner_approvals, const flat_set<public_key_type>& available_key_approvals) : external_id(external_id) , proposer(proposer) , serialized_proposed_transaction(serialized_proposed_transaction) , expiration_time(expiration_time) , created_at(created_at) { if (review_period.valid()) { review_period_time = *review_period; } for (const auto& approver : available_active_approvals) { active_approvals.insert(approver); } for (const auto& approver : available_owner_approvals) { owner_approvals.insert(approver); } for (const auto& approver : key_approvals) { key_approvals.insert(approver); } } external_id_type external_id; uint8_t status; account_name_type proposer; string serialized_proposed_transaction; time_point_sec expiration_time; time_point_sec created_at; optional<time_point_sec> review_period_time; flat_set<account_name_type> active_approvals; flat_set<account_name_type> owner_approvals; flat_set<public_key_type> key_approvals; }; struct create_genesis_account_operation : public virtual_operation { create_genesis_account_operation() {} create_genesis_account_operation(const account_name_type& account) : account(account) { } account_name_type account; }; } } // deip::protocol FC_REFLECT(deip::protocol::fill_common_tokens_withdraw_operation, (from_account)(to_account)(withdrawn)(deposited)(transfer)) FC_REFLECT(deip::protocol::shutdown_witness_operation, (owner)) FC_REFLECT(deip::protocol::hardfork_operation, (hardfork_id)) FC_REFLECT(deip::protocol::producer_reward_operation, (producer)(common_tokens_amount)) FC_REFLECT(deip::protocol::token_sale_contribution_to_history_operation, (research_id)(research_external_id)(research_token_sale_id)(research_token_sale_external_id)(contributor)(amount)) FC_REFLECT(deip::protocol::research_content_reference_history_operation, (research_content_id)(research_content_external_id)(research_id)(research_external_id)(content)(research_content_reference_id)(research_content_reference_external_id)(research_reference_id)(research_reference_external_id)(content_reference)) FC_REFLECT(deip::protocol::research_content_eci_history_operation, (research_content_id)(discipline_id)(diff)) FC_REFLECT(deip::protocol::research_eci_history_operation, (research_id)(discipline_id)(diff)) FC_REFLECT(deip::protocol::account_eci_history_operation, (account)(discipline_id)(recipient_type)(diff)) FC_REFLECT(deip::protocol::disciplines_eci_history_operation, (contributions)(timestamp)) FC_REFLECT(deip::protocol::account_revenue_income_history_operation, (account)(security_token)(revenue)(timestamp)) FC_REFLECT(deip::protocol::proposal_status_changed_operation, (external_id)(status)) FC_REFLECT(deip::protocol::create_genesis_proposal_operation, (external_id)(proposer)(serialized_proposed_transaction)(expiration_time)(created_at)(review_period_time)(active_approvals)(owner_approvals)(key_approvals)) FC_REFLECT(deip::protocol::create_genesis_account_operation, (account))
37.377358
314
0.673481
DEIPworld
7c75c42e66b58e3633067cab6b3d32cf091eb355
1,230
hpp
C++
Engine/Src/Runtime/Core/Public/Core/Pimpl.hpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
Engine/Src/Runtime/Core/Public/Core/Pimpl.hpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
Engine/Src/Runtime/Core/Public/Core/Pimpl.hpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <Core/CoreApi.hpp> #include <Core/Containers/UniquePointer.hpp> #define FADE_MAKE_PIMPL \ private: \ class CImpl; \ __pragma(warning(push)) \ __pragma(warning(disable : 4251)) \ TPimpl<CImpl> m_Impl; \ __pragma(warning(pop)) #define FADE_INIT_PIMPL(ClassName) \ m_Impl(MakeUnique<ClassName::CImpl>()) /* Brief: * Creates pimpl object using a unique_ptr */ template <typename T> class TPimpl { private: Fade::TUniquePtr<T> m_Ptr; public: template <typename... Args> TPimpl(Args&&... args) : m_Ptr(std::forward<Args>(args)...) { } // copy ctor & copy assignment TPimpl(const TPimpl& rhs) = default; TPimpl& operator=(const TPimpl& rhs) = default; // move ctor & move assignment TPimpl(TPimpl&& rhs) = default; TPimpl& operator=(TPimpl&& rhs) = default; // pointer operator T& operator*() { return *m_Ptr; } const T& operator*() const { return *m_Ptr; } // arrow operator T* operator->() { return m_Ptr.Get(); } const T* operator->() const { return m_Ptr.Get(); } // get() function T* get() { return m_Ptr.Get(); } const T* get() const { return m_Ptr.Get(); } };
23.207547
52
0.621951
Septus10
7c7b086b8a08cf99e589f533582f1c4b2692f5d6
11,108
hpp
C++
source/zisc/core/zisc/string/json_value_parser-inl.hpp
byzin/Zisc
c74f50c51f82c847f39a603607d73179004436bb
[ "MIT" ]
2
2017-10-18T13:24:11.000Z
2018-05-15T00:40:52.000Z
source/zisc/core/zisc/string/json_value_parser-inl.hpp
byzin/Zisc
c74f50c51f82c847f39a603607d73179004436bb
[ "MIT" ]
9
2016-09-05T11:07:03.000Z
2019-07-05T15:31:04.000Z
source/zisc/core/zisc/string/json_value_parser-inl.hpp
byzin/Zisc
c74f50c51f82c847f39a603607d73179004436bb
[ "MIT" ]
null
null
null
/*! \file json_value_parser-inl.hpp \author Sho Ikeda \brief No brief description \details No detailed description. \copyright Copyright (c) 2015-2021 Sho Ikeda This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ #ifndef ZISC_JSON_VALUE_PARSER_INL_HPP #define ZISC_JSON_VALUE_PARSER_INL_HPP #include "json_value_parser.hpp" // Standard C++ library #include <cstddef> #include <cstdlib> #include <regex> #include <string_view> #include <type_traits> #include <utility> // Zisc #include "constant_string.hpp" #include "zisc/concepts.hpp" #include "zisc/utility.hpp" #include "zisc/zisc_config.hpp" namespace zisc { /*! \details No detailed description \return No description */ inline constexpr auto JsonValueParser::truePattern() noexcept { auto pattern = toString(R"(true)"); return pattern; } /*! \details No detailed description \return No description */ inline constexpr auto JsonValueParser::falsePattern() noexcept { auto pattern = toString(R"(false)"); return pattern; } /*! \details No detailed description \return No description */ inline constexpr auto JsonValueParser::booleanPattern() noexcept { auto pattern = truePattern() + R"(|)" + falsePattern(); return pattern; } /*! \details No detailed description \return No description */ inline constexpr auto JsonValueParser::integerPattern() noexcept { auto pattern = toString(R"(-?(?:[1-9][0-9]*|0))"); return pattern; } /*! \details No detailed description \return No description */ inline constexpr auto JsonValueParser::floatPattern() noexcept { auto pattern = integerPattern() + R"((?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)"; return pattern; } /*! \details No detailed description \return No description */ inline constexpr auto JsonValueParser::stringPattern() noexcept { auto character = toString(R"([^"\\[:cntrl:]])"); auto escaped = toString(R"(\\["\\bfnrt])"); auto pattern = R"("(?:)" + character + R"(|)" + escaped + R"()*")"; return pattern; } /*! \details No detailed description */ inline JsonValueParser::JsonValueParser() noexcept : int_pattern_{integerPattern().toCStr(), regexInsOptions()}, float_pattern_{floatPattern().toCStr(), regexInsOptions()}, string_pattern_{stringPattern().toCStr(), regexInsOptions()} { } /*! \details No detailed description \param [in] json_value No description. \return No description */ inline std::size_t JsonValueParser::getCxxStringSize(const std::string_view json_value) noexcept { const std::size_t size = toCxxStringImpl(json_value, nullptr); return size; } /*! \details No detailed description \return No description */ inline constexpr std::regex::flag_type JsonValueParser::regexInsOptions() noexcept { constexpr std::regex::flag_type flag = std::regex_constants::nosubs | std::regex_constants::optimize | std::regex_constants::ECMAScript; return flag; } /*! \details No detailed description \return No description */ inline constexpr std::regex::flag_type JsonValueParser::regexTempOptions() noexcept { constexpr std::regex::flag_type flag = std::regex_constants::nosubs | std::regex_constants::ECMAScript; return flag; } /*! \details No detailed description \param [in] json_value No description. \return No description */ inline bool JsonValueParser::toCxxBool(const std::string_view json_value) noexcept { constexpr auto true_value = truePattern(); const bool result = true_value == json_value; return result; } /*! \details No detailed description \tparam Float No description. \param [in] json_value No description. \return No description */ template <FloatingPoint Float> inline Float JsonValueParser::toCxxFloat(const std::string_view json_value) noexcept { const Float result = toCxxFloatImpl<Float>(json_value); return result; } /*! \details No detailed description \tparam Int No description. \param [in] json_value No description. \return No description */ template <Integer Int> inline Int JsonValueParser::toCxxInteger(const std::string_view json_value) noexcept { const Int result = toCxxIntegerImpl<Int>(json_value); return result; } /*! \details No detailed description \param [in] json_value No description. \param [out] value No description. */ inline void JsonValueParser::toCxxString(const std::string_view json_value, char* value) noexcept { toCxxStringImpl(json_value, value); } // For temporary use /*! \details No detailed description \param [in] json_value No description. \return No description */ inline bool JsonValueParser::isBoolValue(const std::string_view json_value) noexcept { constexpr auto true_value = truePattern(); constexpr auto false_value = falsePattern(); const bool result = (true_value == json_value) || (false_value == json_value); return result; } /*! \details No detailed description \param [in] json_value No description. \return No description */ inline bool JsonValueParser::isFloatValue(const std::string_view json_value) noexcept { const std::regex float_pattern{floatPattern().toCStr(), regexTempOptions()}; const bool result = isValueOf(float_pattern, json_value); return result; } /*! \details No detailed description \param [in] json_value No description. \return No description */ inline bool JsonValueParser::isIntegerValue(const std::string_view json_value) noexcept { const std::regex int_pattern{integerPattern().toCStr(), regexTempOptions()}; const bool result = isValueOf(int_pattern, json_value); return result; } /*! \details No detailed description \param [in] json_value No description. \return No description */ inline bool JsonValueParser::isStringValue(const std::string_view json_value) noexcept { const std::regex string_pattern{stringPattern().toCStr(), regexTempOptions()}; const bool result = isValueOf(string_pattern, json_value); return result; } // For instance /*! \details No detailed description \return No description */ inline const std::regex& JsonValueParser::floatRegex() const noexcept { return float_pattern_; } /*! \details No detailed description \return No description */ inline const std::regex& JsonValueParser::integerRegex() const noexcept { return int_pattern_; } /*! \details No detailed description \param [in] json_value No description. \return No description */ inline bool JsonValueParser::isBool(const std::string_view json_value) const noexcept { const bool result = isBoolValue(json_value); return result; } /*! \details No detailed description \param [in] json_value No description. \return No description */ inline bool JsonValueParser::isFloat(const std::string_view json_value) const noexcept { const bool result = isValueOf(floatRegex(), json_value); return result; } /*! \details No detailed description \param [in] json_value No description. \return No description */ inline bool JsonValueParser::isInteger(const std::string_view json_value) const noexcept { const bool result = isValueOf(integerRegex(), json_value); return result; } /*! \details No detailed description \param [in] json_value No description. \return No description */ inline bool JsonValueParser::isString(const std::string_view json_value) const noexcept { const bool result = isValueOf(stringRegex(), json_value); return result; } /*! \details No detailed description \return No description */ inline const std::regex& JsonValueParser::stringRegex() const noexcept { return string_pattern_; } /*! \details No detailed description \param [in] c No description. \return No description */ inline char JsonValueParser::getEscapedCharacter(const char c) noexcept { char result = '\0'; switch (c) { case '\"': result = '\"'; break; case '\\': result = '\\'; break; case 'b': result = '\b'; break; case 'f': result = '\f'; break; case 'n': result = '\n'; break; case 'r': result = '\r'; break; case 't': result = '\t'; break; default: break; } return result; } /*! \details No detailed description \param [in] pattern No description. \param [in] json_value No description. \return No description */ inline bool JsonValueParser::isValueOf(const std::regex& pattern, const std::string_view json_value) noexcept { const bool result = std::regex_match(json_value.begin(), json_value.end(), pattern); return result; } /*! \details No detailed description \tparam Float No description. \param [in] json_value No description. \return No description */ template <FloatingPoint Float> inline Float JsonValueParser::toCxxFloatImpl(const std::string_view json_value) noexcept { using FType = std::remove_cv_t<Float>; Float result; if constexpr (std::is_same_v<float, FType>) result = std::strtof(json_value.data(), nullptr); else if constexpr (std::is_same_v<double, FType>) result = std::strtod(json_value.data(), nullptr); else if constexpr (std::is_same_v<long double, FType>) result = std::strtold(json_value.data(), nullptr); return result; } /*! \details No detailed description \tparam Int No description. \param [in] json_value No description. \return No description */ template <SignedInteger Int> inline Int JsonValueParser::toCxxIntegerImpl(const std::string_view json_value) noexcept { Int result = 0; if constexpr (Integer64<Int>) result = std::strtoll(json_value.data(), nullptr, 10); else result = cast<Int>(std::strtol(json_value.data(), nullptr, 10)); return result; } /*! \details No detailed description \tparam Int No description. \param [in] json_value No description. \return No description */ template <UnsignedInteger Int> inline Int JsonValueParser::toCxxIntegerImpl(const std::string_view json_value) noexcept { Int result = 0; if constexpr (Integer64<Int>) result = std::strtoull(json_value.data(), nullptr, 10); else result = cast<Int>(std::strtoul(json_value.data(), nullptr, 10)); return result; } /*! \details No detailed description \param [in] json_value No description. \param [out] value No description. \return No description */ inline std::size_t JsonValueParser::toCxxStringImpl(std::string_view json_value, char* value) noexcept { // Remove prefix and suffix '"' json_value.remove_prefix(1); json_value.remove_suffix(1); std::size_t size = 0; for (auto i = json_value.begin(); i != json_value.end(); ++i) { char c = *i; if (c == '\\') { ++i; c = getEscapedCharacter(*i); } if (value) value[size] = c; ++size; } return size; } } // namespace zisc #endif // _Z_JSON_VALUE_PARSER_INL_HPP__
22.039683
89
0.692384
byzin
75acb2eb9cd3d25bd94aacd1f8ba7c3e27ba8fda
7,937
cpp
C++
lemon-based-parser/lemon-9-final/Value.cpp
PS-Group/compiler-theory-samples
c916af50eb42020024257ecd17f9be1580db7bf0
[ "MIT" ]
null
null
null
lemon-based-parser/lemon-9-final/Value.cpp
PS-Group/compiler-theory-samples
c916af50eb42020024257ecd17f9be1580db7bf0
[ "MIT" ]
null
null
null
lemon-based-parser/lemon-9-final/Value.cpp
PS-Group/compiler-theory-samples
c916af50eb42020024257ecd17f9be1580db7bf0
[ "MIT" ]
null
null
null
#include "Value.h" #include <stdexcept> #include <boost/format.hpp> #include <cmath> namespace { bool FuzzyEquals(double left, double right) { return std::fabs(left - right) >= std::numeric_limits<double>::epsilon(); } std::string ToPrettyString(double value) { std::string result = std::to_string(value); // Преобразуем 2.00000 в 2. while (!result.empty() && result.back() == '0') { result.pop_back(); } if (!result.empty() && result.back() == '.') { result.pop_back(); } return result; } std::string ToPrettyString(bool value) { return value ? "true" : "false"; } // Конвертирует значение в Boolean (C++ bool). struct BooleanConverter : boost::static_visitor<bool> { bool operator ()(double const& value) const { return FuzzyEquals(value, 0); } bool operator ()(bool const& value) const { return value; } bool operator ()(std::string const& value) const { return !value.empty(); } bool operator ()(std::exception_ptr const&) { return false; } }; // Конвертирует значение в String (C++ std::string). struct StringConverter : boost::static_visitor<std::string> { std::string operator ()(double const& value) const { return ToPrettyString(value); } std::string operator ()(bool const& value) const { return ToPrettyString(value); } std::string operator ()(std::string const& value) const { return value; } std::string operator ()(std::exception_ptr const& value) { std::rethrow_exception(value); } }; struct TypeNameVisitor : boost::static_visitor<std::string> { std::string operator ()(double const&) const { return "Number"; } std::string operator ()(bool const&) const { return "Boolean"; } std::string operator ()(std::string const&) const { return "String"; } std::string operator ()(std::exception_ptr const& value) { m_exception = value; return "Error"; } std::exception_ptr m_exception; }; } // anonymous namespace. CValue CValue::FromError(const std::exception_ptr &value) { return Value(value); } CValue CValue::FromErrorMessage(const std::string &message) { return CValue::FromError(std::make_exception_ptr(std::runtime_error(message))); } CValue CValue::FromDouble(double value) { return Value(value); } CValue CValue::FromBoolean(bool value) { return Value(value); } CValue CValue::FromString(const std::string &value) { return Value(value); } CValue::operator bool() const { return ConvertToBool(); } std::string CValue::ToString() const { return TryConvertToString(); } void CValue::RethrowIfException() const { if (m_value.type() == typeid(std::exception_ptr)) { std::rethrow_exception(boost::get<std::exception_ptr>(m_value)); } } bool CValue::AsBool() const { return boost::get<bool>(m_value); } const std::string &CValue::AsString() const { return boost::get<std::string>(m_value); } double CValue::AsDouble() const { return boost::get<double>(m_value); } CValue CValue::operator +() const { if (m_value.type() == typeid(double)) { return *this; } return GenerateError(*this, "+"); } CValue CValue::operator -() const { if (m_value.type() == typeid(double)) { return Value(-AsDouble()); } return GenerateError(*this, "-"); } CValue CValue::operator !() const { if (m_value.type() == typeid(bool)) { return Value(!AsBool()); } return GenerateError(*this, "!"); } CValue CValue::operator <(const CValue &other) const { if (AreBothValues<double>(*this, other)) { return Value(AsDouble() < other.AsDouble()); } if (AreBothValues<std::string>(*this, other)) { return Value(AsString() < other.AsString()); } return GenerateError(*this, other, "<"); } CValue CValue::operator ==(const CValue &other) const { if (AreBothValues<double>(*this, other)) { return Value(FuzzyEquals(AsDouble(), other.AsDouble())); } if (AreBothValues<std::string>(*this, other)) { return Value(AsString() == other.AsString()); } if (AreBothValues<bool>(*this, other)) { return Value(AsBool() == other.AsBool()); } return GenerateError(*this, other, "=="); } CValue CValue::operator &&(const CValue &other) const { if (AreBothValues<bool>(*this, other)) { return Value(AsBool() && other.AsBool()); } return GenerateError(*this, other, "&&"); } CValue CValue::operator ||(const CValue &other) const { if (AreBothValues<bool>(*this, other)) { return Value(AsBool() || other.AsBool()); } return GenerateError(*this, other, "||"); } CValue CValue::operator +(const CValue &other) const { const auto &leftType = m_value.type(); const auto &rightType = other.m_value.type(); if (leftType == typeid(double)) { if (rightType == typeid(double)) { return Value(AsDouble() + other.AsDouble()); } if (rightType == typeid(std::string)) { return Value(::ToPrettyString(AsDouble()) + other.AsString()); } } if (leftType == typeid(std::string)) { if (rightType == typeid(double)) { return Value(AsString() + ::ToPrettyString(other.AsDouble())); } if (rightType == typeid(std::string)) { return Value(AsString() + other.AsString()); } } return GenerateError(*this, other, "+"); } CValue CValue::operator -(const CValue &other) const { if (AreBothValues<double>(*this, other)) { return Value(AsDouble() - other.AsDouble()); } return GenerateError(*this, other, "-"); } CValue CValue::operator *(const CValue &other) const { if (AreBothValues<double>(*this, other)) { return Value(AsDouble() * other.AsDouble()); } return GenerateError(*this, other, "*"); } CValue CValue::operator /(const CValue &other) const { if (AreBothValues<double>(*this, other)) { return Value(AsDouble() / other.AsDouble()); } return GenerateError(*this, other, "/"); } CValue CValue::operator %(const CValue &other) const { if (AreBothValues<double>(*this, other)) { return Value(fmod(AsDouble(), other.AsDouble())); } return GenerateError(*this, other, "%"); } template<class TType> bool CValue::AreBothValues(const CValue &left, const CValue &right) { return (left.m_value.type() == typeid(TType)) && (right.m_value.type() == typeid(TType)); } CValue CValue::GenerateError(const CValue &value, const char *description) { TypeNameVisitor visitor; std::string valueType = value.m_value.apply_visitor(visitor); // Прокидываем информацию об ошибке дальше. if (visitor.m_exception) { return CValue::FromError(visitor.m_exception); } boost::format formatter("No such unary operation: %1%%2%"); formatter % description % valueType; return CValue::FromErrorMessage(boost::str(formatter)); } CValue CValue::GenerateError(const CValue &left, const CValue &right, const char *description) { TypeNameVisitor visitor; std::string leftType = left.m_value.apply_visitor(visitor); std::string rightType = right.m_value.apply_visitor(visitor); // Прокидываем информацию об ошибке дальше. if (visitor.m_exception) { return CValue::FromError(visitor.m_exception); } boost::format formatter("No such binary operation: %1% %2% %3%"); formatter % leftType % description % rightType; return CValue::FromErrorMessage(boost::str(formatter)); } CValue::CValue(const CValue::Value &value) : m_value(value) { } std::string CValue::TryConvertToString() const { StringConverter converter; std::string value = m_value.apply_visitor(converter); return value; } bool CValue::ConvertToBool() const { BooleanConverter converter; return m_value.apply_visitor(converter); }
24.649068
101
0.63815
PS-Group
75b5214b40cee70531bb1c2b785b7721472ba137
4,100
cpp
C++
src/TotalGeneralizedVariation.cpp
DanonOfficial/TGVDenoising
20446d9c89d75cf43056f43ed42f37965b4e7b6e
[ "MIT" ]
8
2019-04-06T06:13:53.000Z
2021-04-30T09:49:18.000Z
src/TotalGeneralizedVariation.cpp
DanonOfficial/TGVDenoising
20446d9c89d75cf43056f43ed42f37965b4e7b6e
[ "MIT" ]
1
2021-06-22T15:26:13.000Z
2021-06-23T05:45:21.000Z
src/TotalGeneralizedVariation.cpp
DanonOfficial/TGVDenoising
20446d9c89d75cf43056f43ed42f37965b4e7b6e
[ "MIT" ]
2
2020-07-13T09:05:51.000Z
2021-02-01T04:15:58.000Z
// // Created by roundedglint585 on 3/11/19. // #include "TotalGeneralizedVariation.hpp" TotalGeneralizedVariation::TotalGeneralizedVariation(const std::vector<TotalGeneralizedVariation::Image> &images) : m_images(images), m_result(m_images[0]), m_width(m_result[0].size()), m_height(m_result.size()) { init(); initWs(); initStacked(); calculateHist(); } TotalGeneralizedVariation::TotalGeneralizedVariation(std::vector<TotalGeneralizedVariation::Image> &&images) : m_images( std::move(images)), m_result(m_images[0]), m_width(m_result[0].size()), m_height(m_result.size()) { init(); initWs(); initStacked(); calculateHist(); } void TotalGeneralizedVariation::init() { v = mathRoutine::calculateGradient(m_result); p = mathRoutine::calculateGradient(m_result); q = mathRoutine::calculateEpsilon(v); } void TotalGeneralizedVariation::initWs() { Ws.resize(m_images.size()); for (auto &ws: Ws) { ws.resize(m_height); for (auto &i : ws) { i = std::vector<float>(m_width, 0.0f); } } } void TotalGeneralizedVariation::initStacked() { stacked = std::vector(m_height, std::vector<std::vector<float>>(m_width, std::vector<float>(Ws.size() + m_images.size(), 0))); } void TotalGeneralizedVariation::calculateHist() { for (size_t histNum = 0; histNum < Ws.size(); histNum++) { for (auto &image: m_images) { for (size_t i = 0; i < m_height; i++) { for (size_t j = 0; j < m_width; j++) { if (m_images[histNum][i][j] > image[i][j]) { Ws[histNum][i][j] += 1.f; } else { if (m_images[histNum][i][j] < image[i][j]) Ws[histNum][i][j] -= 1.f; } } } } } } TotalGeneralizedVariation::Image TotalGeneralizedVariation::prox(const TotalGeneralizedVariation::Image &image, float tau, float lambda_data) { Image result = Image(m_height, std::vector<float>(m_width, 0)); //need to swap dimensions to calculate median for (size_t i = 0; i < m_height; i++) { for (size_t j = 0; j < m_width; j++) { for (size_t k = 0; k < m_images.size(); k++) { stacked[i][j][k] = m_images[k][i][j]; } for (size_t k = 0; k < Ws.size(); k++) { stacked[i][j][m_images.size() + k] = image[i][j] + tau * lambda_data * Ws[k][i][j]; } } } for (size_t i = 0; i < m_height; i++) { for (size_t j = 0; j < m_width; j++) { std::stable_sort(stacked[i][j].begin(), stacked[i][j].end()); if (stacked[i][j].size() % 2 == 1) { result[i][j] = stacked[i][j][stacked[i][j].size() / 2 + 1]; } else { result[i][j] = (stacked[i][j][stacked[i][j].size() / 2] + stacked[i][j][stacked[i][j].size() / 2 - 1]) / 2; } } } return result; } void TotalGeneralizedVariation::iteration(float tau, float lambda_tv, float lambda_tgv, float lambda_data) { using namespace mathRoutine; float tau_u, tau_v, tau_p, tau_q; tau_u = tau; tau_v = tau; tau_p = tau; tau_q = tau; Image un = prox(m_result + (-tau_u * lambda_tv) * (mathRoutine::calculateTranspondedGradient(p)), tau_u, lambda_data); Gradient vn = v + (-lambda_tgv * tau_v) * mathRoutine::calculateTranspondedEpsilon(q) + (tau_v * lambda_tv) * p; Gradient pn = project( p + (tau_p * lambda_tv) * (mathRoutine::calculateGradient((-1) * ((-2) * un + m_result)) + ((-2) * vn + v)), lambda_tv); Epsilon qn = project(q + (-tau_q * lambda_tgv) * mathRoutine::calculateEpsilon(-2 * vn + v), lambda_tgv); m_result = std::move(un); v = std::move(vn); p = std::move(pn); q = std::move(qn); } auto TotalGeneralizedVariation::getImage() const -> Image{ return m_result; }
33.064516
120
0.54878
DanonOfficial
75b5a22f172625f6a8c744363d6f830d8f9313f2
2,254
hpp
C++
include/codegen/include/Zenject/AddToCurrentGameObjectComponentProvider_--c__DisplayClass15_0.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/Zenject/AddToCurrentGameObjectComponentProvider_--c__DisplayClass15_0.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/Zenject/AddToCurrentGameObjectComponentProvider_--c__DisplayClass15_0.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:45 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" // Including type: Zenject.AddToCurrentGameObjectComponentProvider #include "Zenject/AddToCurrentGameObjectComponentProvider.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; } // Forward declaring namespace: Zenject namespace Zenject { // Forward declaring type: InjectContext class InjectContext; } // Completed forward declares // Type namespace: Zenject namespace Zenject { // Autogenerated type: Zenject.AddToCurrentGameObjectComponentProvider/<>c__DisplayClass15_0 class AddToCurrentGameObjectComponentProvider::$$c__DisplayClass15_0 : public ::Il2CppObject { public: // public Zenject.AddToCurrentGameObjectComponentProvider <>4__this // Offset: 0x10 Zenject::AddToCurrentGameObjectComponentProvider* $$4__this; // public System.Collections.Generic.List`1<Zenject.TypeValuePair> args // Offset: 0x18 System::Collections::Generic::List_1<Zenject::TypeValuePair>* args; // public System.Object instance // Offset: 0x20 ::Il2CppObject* instance; // public Zenject.InjectContext context // Offset: 0x28 Zenject::InjectContext* context; // System.Void <GetAllInstancesWithInjectSplit>b__0() // Offset: 0xD4F730 void $GetAllInstancesWithInjectSplit$b__0(); // public System.Void .ctor() // Offset: 0xD4F728 // Implemented from: System.Object // Base method: System.Void Object::.ctor() static AddToCurrentGameObjectComponentProvider::$$c__DisplayClass15_0* New_ctor(); }; // Zenject.AddToCurrentGameObjectComponentProvider/<>c__DisplayClass15_0 } DEFINE_IL2CPP_ARG_TYPE(Zenject::AddToCurrentGameObjectComponentProvider::$$c__DisplayClass15_0*, "Zenject", "AddToCurrentGameObjectComponentProvider/<>c__DisplayClass15_0"); #pragma pack(pop)
40.25
173
0.741349
Futuremappermydud
75b90ec3f22c09aa37cd74b9beb9a071c2601b66
1,959
cpp
C++
Source/Driver/API/SQLSetConnectOption.cpp
yichenghuang/bigobject-odbc
c6d947ea3d18d79684adfbac1c492282a075d48d
[ "MIT" ]
null
null
null
Source/Driver/API/SQLSetConnectOption.cpp
yichenghuang/bigobject-odbc
c6d947ea3d18d79684adfbac1c492282a075d48d
[ "MIT" ]
null
null
null
Source/Driver/API/SQLSetConnectOption.cpp
yichenghuang/bigobject-odbc
c6d947ea3d18d79684adfbac1c492282a075d48d
[ "MIT" ]
null
null
null
/* * ---------------------------------------------------------------------------- * Copyright (c) 2014-2015 BigObject Inc. * All Rights Reserved. * * Use of, copying, modifications to, and distribution of this software * and its documentation without BigObject's written permission can * result in the violation of U.S., Taiwan and China Copyright and Patent laws. * Violators will be prosecuted to the highest extent of the applicable laws. * * BIGOBJECT MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. * ---------------------------------------------------------------------------- */ #include "Driver.hpp" /* https://msdn.microsoft.com/en-us/library/ms713564%28v=vs.85%29.aspx https://msdn.microsoft.com/en-us/library/ms714008%28v=vs.85%29.aspx WE DON'T EXPORT THIS API. */ SQLRETURN SQL_API SQLSetConnectOption(SQLHDBC hDrvDbc, UWORD nOption, SQLULEN vParam) { HDRVDBC hDbc = (HDRVDBC)hDrvDbc; LOG_DEBUG_F_FUNC( TEXT("%s: hDrvDbc = 0x%08lX, nOption = %d, vParam = %d"), LOG_FUNCTION_NAME, (long)hDrvDbc, nOption, vParam); API_HOOK_ENTRY(SQLSetConnectOption, hDrvDbc, nOption, vParam); /* SANITY CHECKS */ if(hDbc == SQL_NULL_HDBC) return SQL_INVALID_HANDLE; switch(nOption) { case SQL_TRANSLATE_DLL: case SQL_TRANSLATE_OPTION: /* case SQL_CONNECT_OPT_DRVR_START: */ case SQL_ODBC_CURSORS: case SQL_OPT_TRACE: switch(vParam) { case SQL_OPT_TRACE_ON: case SQL_OPT_TRACE_OFF: default: ; } break; case SQL_OPT_TRACEFILE: case SQL_ACCESS_MODE: case SQL_AUTOCOMMIT: default: ; } LOG_WARN_F_FUNC(TEXT("%s: This function not supported."), LOG_FUNCTION_NAME); LOG_DEBUG_F_FUNC(TEXT("%s: SQL_ERROR"), LOG_FUNCTION_NAME); return SQL_ERROR; }
27.208333
79
0.663604
yichenghuang
75bb4de059be545230b138fcde43f895938c4a1e
409
cpp
C++
week-02/practice/02.cpp
greenfox-zerda-sparta/zerda-syllabus
5e49a9f9a2528e58bedb1f2d96bf8a4feabd123c
[ "MIT" ]
null
null
null
week-02/practice/02.cpp
greenfox-zerda-sparta/zerda-syllabus
5e49a9f9a2528e58bedb1f2d96bf8a4feabd123c
[ "MIT" ]
null
null
null
week-02/practice/02.cpp
greenfox-zerda-sparta/zerda-syllabus
5e49a9f9a2528e58bedb1f2d96bf8a4feabd123c
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; void draw_characters(int count, char c) { for (int i = 0; i < count; ++i) { cout << c; } } void christmas_tree(char main_character, int times) { for (int row = 1; row <= times; ++row) { draw_characters(times - row, ' '); draw_characters(row * 2 - 1, main_character); cout << endl; } } int main() { christmas_tree('#', 8); return 0; }
16.36
53
0.594132
greenfox-zerda-sparta
75bdac2cb35e35698d57780b633d79365809eb2e
1,640
cpp
C++
code/SoulVania/AnimationFactoryReader.cpp
warzes/Soulvania
83733b6a6aa38f8024109193893eb5b65b0e6294
[ "MIT" ]
1
2021-06-30T06:29:54.000Z
2021-06-30T06:29:54.000Z
code/SoulVania/AnimationFactoryReader.cpp
warzes/Soulvania
83733b6a6aa38f8024109193893eb5b65b0e6294
[ "MIT" ]
null
null
null
code/SoulVania/AnimationFactoryReader.cpp
warzes/Soulvania
83733b6a6aa38f8024109193893eb5b65b0e6294
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "AnimationFactoryReader.h" #include "FileLogger.h" #include "LoadContentException.h" #include "ContentManager.h" #include "pugixml/pugixml.hpp" std::shared_ptr<AnimationFactory> AnimationFactoryReader::Read(std::string filePath, ContentManager& contentManager) { auto xmlDocument = pugi::xml_document{}; auto result = xmlDocument.load_file(filePath.c_str()); if (!result) { FileLogger::GetInstance().Error("{}() failed: {}. Path: {}", __FUNCTION__, result.description(), filePath); throw LoadContentException(result.description()); } auto rootNode = xmlDocument.child("GameContent"); auto atlasPath = rootNode.child("Animations").attribute("AtlasPath").as_string(); auto resolvedAtlasPath = contentManager.ResolvePath(Path{ filePath }.parent_path(), atlasPath); auto spritesheet = contentManager.Load<Spritesheet>(resolvedAtlasPath); auto animations = AnimationDict{}; for (auto animationNode : rootNode.child("Animations").children("Animation")) { auto name = animationNode.attribute("Name").as_string(); auto defaultAnimateTime = animationNode.attribute("DefaultTime").as_int(); auto isLooping = animationNode.attribute("IsLooping").as_bool(); auto animation = Animation{ name, defaultAnimateTime, isLooping }; for (auto frameNode : animationNode.children("Frame")) { auto name = frameNode.attribute("SpriteID").as_string(); auto time = frameNode.attribute("Time").as_int(); // equals to 0 if Time attribute not found animation.Add(spritesheet->at(name), time); } animations.emplace(name, animation); } return std::make_shared<AnimationFactory>(animations); }
38.139535
116
0.75061
warzes
75c093ce0b68e30ec4281f3659b798d89fc0be6e
929
cpp
C++
FRBDK/BitmapFontGenerator/source/dynamic_funcs.cpp
patridge/FlatRedBall
01e0212afeb977a10244796494dcaf9c800a3770
[ "MIT" ]
110
2016-01-14T14:46:16.000Z
2022-03-27T19:00:48.000Z
FRBDK/BitmapFontGenerator/source/dynamic_funcs.cpp
patridge/FlatRedBall
01e0212afeb977a10244796494dcaf9c800a3770
[ "MIT" ]
471
2016-08-21T14:48:15.000Z
2022-03-31T20:22:50.000Z
FRBDK/BitmapFontGenerator/source/dynamic_funcs.cpp
patridge/FlatRedBall
01e0212afeb977a10244796494dcaf9c800a3770
[ "MIT" ]
33
2016-01-25T23:30:03.000Z
2022-02-18T07:24:45.000Z
#include <windows.h> #include "dynamic_funcs.h" // Since this code requires Win2000 or later, we'll load it dynamically static HMODULE dll_gdi32 = 0; GetGlyphIndicesA_t fGetGlyphIndicesA = 0; GetGlyphIndicesW_t fGetGlyphIndicesW = 0; GetFontUnicodeRanges_t fGetFontUnicodeRanges = 0; void Init() { #ifdef LOAD_GDI32 dll_gdi32 = LoadLibrary("gdi32.dll"); if( dll_gdi32 != 0 ) { fGetGlyphIndicesA = (GetGlyphIndicesA_t)GetProcAddress(dll_gdi32, "GetGlyphIndicesA"); fGetGlyphIndicesW = (GetGlyphIndicesW_t)GetProcAddress(dll_gdi32, "GetGlyphIndicesW"); fGetFontUnicodeRanges = (GetFontUnicodeRanges_t)GetProcAddress(dll_gdi32, "GetFontUnicodeRanges"); } #else fGetGlyphIndicesA = GetGlyphIndicesA; fGetGlyphIndicesW = GetGlyphIndicesW; fGetFontUnicodeRanges = GetFontUnicodeRanges; #endif } void Uninit() { #ifdef LOAD_GDI32 if( dll_gdi32 != 0 ) FreeLibrary(dll_gdi32); #endif }
27.323529
100
0.759957
patridge
75c42169434068f566303a77e8c7e062f4d5bf0d
201
hpp
C++
src/ColorSYMGS.hpp
hpcg-benchmark/KHPCG3.0
9591b148ea6552342a0471a932d2abf332e490e0
[ "BSD-3-Clause" ]
5
2015-07-10T16:35:08.000Z
2021-09-13T03:29:37.000Z
src/ColorSYMGS.hpp
zabookey/Kokkos-HPCG
7ca081e51a275c4fb6b21e8871788e88e8715dbc
[ "BSD-3-Clause" ]
null
null
null
src/ColorSYMGS.hpp
zabookey/Kokkos-HPCG
7ca081e51a275c4fb6b21e8871788e88e8715dbc
[ "BSD-3-Clause" ]
3
2019-03-05T16:46:25.000Z
2021-12-22T03:49:00.000Z
#ifndef COLORSYMGS_HPP #define COLORSYMGS_HPP #include "SparseMatrix.hpp" #include "Vector.hpp" #include "KokkosSetup.hpp" int ColorSYMGS(const SparseMatrix & A, const Vector & x, Vector & y); #endif
22.333333
69
0.766169
hpcg-benchmark
75c76b1272dc16e0e71395a36d1be066d448e549
26,695
cpp
C++
winrt/test.internal/xaml/CanvasImageSourceUnitTests.cpp
r2d2rigo/Win2D
3f06d4f19b7d16b67859a1b30ac770215ef3e52d
[ "MIT" ]
1,002
2015-01-09T19:40:01.000Z
2019-05-04T12:05:09.000Z
winrt/test.internal/xaml/CanvasImageSourceUnitTests.cpp
r2d2rigo/Win2D
3f06d4f19b7d16b67859a1b30ac770215ef3e52d
[ "MIT" ]
667
2015-01-02T19:04:11.000Z
2019-05-03T14:43:51.000Z
winrt/test.internal/xaml/CanvasImageSourceUnitTests.cpp
SunburstApps/Win2D.WinUI
75a33f8f4c0c785c2d1b478589fd4d3a9c5b53df
[ "MIT" ]
258
2015-01-06T07:44:49.000Z
2019-05-01T15:50:59.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT License. See LICENSE.txt in the project root for license information. #include "pch.h" TEST_CLASS(CanvasImageSourceUnitTests) { public: TEST_METHOD_EX(CanvasImageSourceConstruction) { // // On construction the CanvasImageSource is expected to: // // - create a SurfaceImageSource with the specified width/height and background mode // // - set this as the composable base (queryable by GetComposableBase()) // // - call SetDevice on the SurfaceImageSourceNativeWith2D, passing it // the d2d device associated with the CanvasDevice that was passed in // int expectedHeight = 123; int expectedWidth = 456; CanvasAlphaMode expectedAlphaMode = CanvasAlphaMode::Ignore; auto mockD2DDevice = Make<MockD2DDevice>(); auto mockCanvasDevice = Make<MockCanvasDevice>(); auto mockSurfaceImageSourceFactory = Make<MockSurfaceImageSourceFactory>(); auto mockSurfaceImageSource = Make<MockSurfaceImageSource>(); // // Verify that the SurfaceImageSourceFactory is asked to create a // SurfaceImageSource with correct parameters. // // Note that actualOuter is a raw pointer - we don't want actualOuter to // ever become the last thing referencing the CanvasImageSource (this // could happen since the mock below is called during CanvasImageSource // construction; if that fails then things can blow up since actualOuter // exists outside normal exception cleanup) // bool mockCreateInstanceCalled = false; IInspectable* actualOuter; mockSurfaceImageSourceFactory->MockCreateInstanceWithDimensionsAndOpacity = [&](int32_t actualWidth, int32_t actualHeight, bool isOpaque, IInspectable* outer) { Assert::IsFalse(mockCreateInstanceCalled); Assert::AreEqual(expectedWidth, actualWidth); Assert::AreEqual(expectedHeight, actualHeight); auto actualAlphaMode = isOpaque ? CanvasAlphaMode::Ignore : CanvasAlphaMode::Premultiplied; Assert::AreEqual(expectedAlphaMode, actualAlphaMode); actualOuter = outer; mockCreateInstanceCalled = true; return mockSurfaceImageSource; }; // // Verify that SetDevice is called on the SurfaceImageSource with the // correct D2D device // mockCanvasDevice->MockGetD2DDevice = [&] { return mockD2DDevice; }; mockCanvasDevice->Mockget_Device = [&](ICanvasDevice** value) { ComPtr<ICanvasDevice> device(mockCanvasDevice.Get()); *value = device.Detach(); }; mockSurfaceImageSource->SetDeviceMethod.SetExpectedCalls(1, [&](IUnknown* actualDevice) { ComPtr<IUnknown> expectedDevice; ThrowIfFailed(mockD2DDevice.As(&expectedDevice)); Assert::AreEqual(expectedDevice.Get(), actualDevice); return S_OK; }); // // Actually create the CanvasImageSource // auto canvasImageSource = Make<CanvasImageSource>( mockCanvasDevice.Get(), (float)expectedWidth, (float)expectedHeight, DEFAULT_DPI, expectedAlphaMode, mockSurfaceImageSourceFactory.Get(), std::make_shared<MockCanvasImageSourceDrawingSessionFactory>()); Assert::IsTrue(mockCreateInstanceCalled); // // Verify the composition relationship between the CanvasImageSource and // the base class, SurfaceImageSource. // ComPtr<IInspectable> expectedOuter; ThrowIfFailed(canvasImageSource.As(&expectedOuter)); Assert::AreEqual(expectedOuter.Get(), actualOuter); ComPtr<IInspectable> expectedComposableBase; ThrowIfFailed(mockSurfaceImageSource.As(&expectedComposableBase)); Assert::AreEqual(canvasImageSource->GetComposableBase().Get(), expectedComposableBase.Get()); CanvasAlphaMode actualAlphaMode; ThrowIfFailed(canvasImageSource->get_AlphaMode(&actualAlphaMode)); Assert::AreEqual(CanvasAlphaMode::Ignore, actualAlphaMode); } struct AlphaModeFixture { bool ExpectedIsOpaque; AlphaModeFixture() : ExpectedIsOpaque(false) {} void CreateImageSource(CanvasAlphaMode alphaMode) { auto factory = Make<MockSurfaceImageSourceFactory>(); bool createWasCalled = false; factory->MockCreateInstanceWithDimensionsAndOpacity = [&] (int32_t,int32_t,bool opaque,IInspectable*) { createWasCalled = true; Assert::AreEqual(ExpectedIsOpaque, opaque); return Make<StubSurfaceImageSource>(); }; Make<CanvasImageSource>( As<ICanvasResourceCreator>(Make<StubCanvasDevice>()).Get(), 1.0f, 1.0f, DEFAULT_DPI, alphaMode, factory.Get(), std::make_shared<MockCanvasImageSourceDrawingSessionFactory>()); Assert::IsTrue(createWasCalled, L"SurfaceImageSourceFactory::Create was called"); } }; TEST_METHOD_EX(CanvasImageSource_WhenConstructedWithAlphaModeIgnore_ThenUnderlyingImageSourceIsOpaque) { AlphaModeFixture f; f.ExpectedIsOpaque = true; f.CreateImageSource(CanvasAlphaMode::Ignore); } TEST_METHOD_EX(CanvasImageSource_WhenConstructedWithAlphaModePremultiplied_ThenUnderlyingImageSourceIsTransparent) { AlphaModeFixture f; f.ExpectedIsOpaque = false; f.CreateImageSource(CanvasAlphaMode::Premultiplied); } TEST_METHOD_EX(CanvasImageSource_WhenConstructedWithAlphaModeStraight_ThenFailsWithInvalidArg) { AlphaModeFixture f; ExpectHResultException(E_INVALIDARG, [&] { f.CreateImageSource(CanvasAlphaMode::Straight); }); ValidateStoredErrorState(E_INVALIDARG, Strings::InvalidAlphaModeForImageSource); } TEST_METHOD_EX(CanvasImageSourceGetDevice) { ComPtr<ICanvasDevice> expectedCanvasDevice = Make<StubCanvasDevice>(); auto stubSurfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>(); auto canvasImageSource = Make<CanvasImageSource>( static_cast<ICanvasResourceCreator*>(static_cast<StubCanvasDevice*>(expectedCanvasDevice.Get())), 1.0f, 1.0f, DEFAULT_DPI, CanvasAlphaMode::Premultiplied, stubSurfaceImageSourceFactory.Get(), std::make_shared<MockCanvasImageSourceDrawingSessionFactory>()); ComPtr<ICanvasDevice> actualCanvasDevice; ThrowIfFailed(canvasImageSource->get_Device(&actualCanvasDevice)); Assert::AreEqual(expectedCanvasDevice.Get(), actualCanvasDevice.Get()); // Calling get_Device with a nullptr should fail appropriately Assert::AreEqual(E_INVALIDARG, canvasImageSource->get_Device(nullptr)); } struct RecreateFixture { ComPtr<StubCanvasDevice> FirstDevice; ComPtr<MockSurfaceImageSource> SurfaceImageSource; ComPtr<CanvasImageSource> ImageSource; RecreateFixture() : FirstDevice(Make<StubCanvasDevice>()) , SurfaceImageSource(Make<MockSurfaceImageSource>()) { auto surfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>(SurfaceImageSource.Get()); // On the initial make we know that this succeeds SurfaceImageSource->SetDeviceMethod.AllowAnyCall(); ImageSource = Make<CanvasImageSource>( FirstDevice.Get(), 1.0f, 1.0f, DEFAULT_DPI, CanvasAlphaMode::Premultiplied, surfaceImageSourceFactory.Get(), std::make_shared<MockCanvasImageSourceDrawingSessionFactory>()); } void ExpectSetDeviceWithNullAndThen(ComPtr<IUnknown> expected) { SurfaceImageSource->SetDeviceMethod.SetExpectedCalls(2, [=] (IUnknown* actualDevice) { if (this->SurfaceImageSource->SetDeviceMethod.GetCurrentCallCount() == 1) { Assert::IsNull(actualDevice); } else { Assert::IsTrue(IsSameInstance(actualDevice, expected.Get())); } return S_OK; }); } }; TEST_METHOD_EX(CanvasImageSource_Recreate_WhenPassedNull_ReturnsInvalidArg) { RecreateFixture f; Assert::AreEqual(E_INVALIDARG, f.ImageSource->Recreate(nullptr)); } TEST_METHOD_EX(CanvasImageSource_Recreate_WhenPassedNewDevice_SetsDevice) { RecreateFixture f; auto secondDevice = Make<StubCanvasDevice>(); f.ExpectSetDeviceWithNullAndThen(secondDevice->GetD2DDevice()); ThrowIfFailed(f.ImageSource->Recreate(secondDevice.Get())); ComPtr<ICanvasDevice> retrievedDevice; ThrowIfFailed(f.ImageSource->get_Device(&retrievedDevice)); Assert::IsTrue(IsSameInstance(secondDevice.Get(), retrievedDevice.Get())); } TEST_METHOD_EX(CanvasImageSource_Recreated_WhenPassedOriginalDevice_SetsDevice) { RecreateFixture f; f.ExpectSetDeviceWithNullAndThen(f.FirstDevice->GetD2DDevice()); ThrowIfFailed(f.ImageSource->Recreate(f.FirstDevice.Get())); ComPtr<ICanvasDevice> retrievedDevice; ThrowIfFailed(f.ImageSource->get_Device(&retrievedDevice)); Assert::IsTrue(IsSameInstance(f.FirstDevice.Get(), retrievedDevice.Get())); } TEST_METHOD_EX(CanvasImageSource_CreateFromCanvasControl) { auto canvasControlAdapter = std::make_shared<CanvasControlTestAdapter>(); auto canvasControl = Make<CanvasControl>(canvasControlAdapter); // Get the control to a point where it has created the device. canvasControlAdapter->CreateCanvasImageSourceMethod.AllowAnyCall(); auto userControl = static_cast<StubUserControl*>(As<IUserControl>(canvasControl).Get()); ThrowIfFailed(userControl->LoadedEventSource->InvokeAll(nullptr, nullptr)); canvasControlAdapter->RaiseCompositionRenderingEvent(); auto stubSurfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>(); auto canvasImageSource = Make<CanvasImageSource>( canvasControl.Get(), 123.0f, 456.0f, DEFAULT_DPI, CanvasAlphaMode::Ignore, stubSurfaceImageSourceFactory.Get(), std::make_shared<MockCanvasImageSourceDrawingSessionFactory>()); // // Verify that the image source and the control are compatible. // ComPtr<ICanvasDevice> controlDevice; ThrowIfFailed(canvasControl->get_Device(&controlDevice)); ComPtr<ICanvasDevice> sisDevice; ThrowIfFailed(canvasImageSource->get_Device(&sisDevice)); Assert::AreEqual(controlDevice.Get(), sisDevice.Get()); } TEST_METHOD_EX(CanvasImageSource_CreateFromDrawingSession) { ComPtr<StubCanvasDevice> canvasDevice = Make<StubCanvasDevice>(); ComPtr<StubD2DDeviceContextWithGetFactory> d2dDeviceContext = Make<StubD2DDeviceContextWithGetFactory>(); d2dDeviceContext->SetTextAntialiasModeMethod.SetExpectedCalls(1, [](D2D1_TEXT_ANTIALIAS_MODE mode) { Assert::AreEqual(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE, mode); }); ComPtr<CanvasDrawingSession> drawingSession = CanvasDrawingSession::CreateNew( d2dDeviceContext.Get(), std::make_shared<StubCanvasDrawingSessionAdapter>(), canvasDevice.Get()); auto stubSurfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>(); auto canvasImageSource = Make<CanvasImageSource>( drawingSession.Get(), 5.0f, 10.0f, DEFAULT_DPI, CanvasAlphaMode::Ignore, stubSurfaceImageSourceFactory.Get(), std::make_shared<MockCanvasImageSourceDrawingSessionFactory>()); // // Verify that the image source and the drawing session are compatible. // ComPtr<ICanvasDevice> sisDevice; ThrowIfFailed(canvasImageSource->get_Device(&sisDevice)); Assert::AreEqual(static_cast<ICanvasDevice*>(canvasDevice.Get()), sisDevice.Get()); } TEST_METHOD_EX(CanvasImageSource_DpiProperties) { const float dpi = 144; auto canvasDevice = Make<StubCanvasDevice>(); auto d2dDeviceContext = Make<StubD2DDeviceContextWithGetFactory>(); auto resourceCreator = CanvasDrawingSession::CreateNew(d2dDeviceContext.Get(), std::make_shared<StubCanvasDrawingSessionAdapter>(), canvasDevice.Get()); auto stubSurfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>(); auto mockDrawingSessionFactory = std::make_shared<MockCanvasImageSourceDrawingSessionFactory>(); auto canvasImageSource = Make<CanvasImageSource>(resourceCreator.Get(), 1.0f, 1.0f, dpi, CanvasAlphaMode::Ignore, stubSurfaceImageSourceFactory.Get(), mockDrawingSessionFactory); float actualDpi = 0; ThrowIfFailed(canvasImageSource->get_Dpi(&actualDpi)); Assert::AreEqual(dpi, actualDpi); VerifyConvertDipsToPixels(dpi, canvasImageSource); const float testValue = 100; float dips = 0; ThrowIfFailed(canvasImageSource->ConvertPixelsToDips((int)testValue, &dips)); Assert::AreEqual(testValue * DEFAULT_DPI / dpi, dips); } TEST_METHOD_EX(CanvasImageSource_PropagatesDpiToDrawingSession) { const float expectedDpi = 144; auto canvasDevice = Make<StubCanvasDevice>(); auto d2dDeviceContext = Make<StubD2DDeviceContextWithGetFactory>(); auto resourceCreator = CanvasDrawingSession::CreateNew(d2dDeviceContext.Get(), std::make_shared<StubCanvasDrawingSessionAdapter>(), canvasDevice.Get()); auto stubSurfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>(); auto mockDrawingSessionFactory = std::make_shared<MockCanvasImageSourceDrawingSessionFactory>(); auto canvasImageSource = Make<CanvasImageSource>(resourceCreator.Get(), 1.0f, 1.0f, expectedDpi, CanvasAlphaMode::Ignore, stubSurfaceImageSourceFactory.Get(), mockDrawingSessionFactory); mockDrawingSessionFactory->CreateMethod.SetExpectedCalls(1, [&](ICanvasDevice*, ISurfaceImageSourceNativeWithD2D*, Color const&, Rect const&, float dpi) { Assert::AreEqual(expectedDpi, dpi); return nullptr; }); ComPtr<ICanvasDrawingSession> drawingSession; ThrowIfFailed(canvasImageSource->CreateDrawingSession(Color{}, &drawingSession)); } TEST_METHOD_EX(CanvasImageSource_SizeProperties) { const float width = 123; const float height = 456; const float dpi = 144; auto canvasDevice = Make<StubCanvasDevice>(); auto d2dDeviceContext = Make<StubD2DDeviceContextWithGetFactory>(); auto resourceCreator = CanvasDrawingSession::CreateNew(d2dDeviceContext.Get(), std::make_shared<StubCanvasDrawingSessionAdapter>(), canvasDevice.Get()); auto stubSurfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>(); auto mockDrawingSessionFactory = std::make_shared<MockCanvasImageSourceDrawingSessionFactory>(); auto canvasImageSource = Make<CanvasImageSource>(resourceCreator.Get(), width, height, dpi, CanvasAlphaMode::Ignore, stubSurfaceImageSourceFactory.Get(), mockDrawingSessionFactory); Size size = { 0, 0 }; ThrowIfFailed(canvasImageSource->get_Size(&size)); Assert::AreEqual(width, size.Width); Assert::AreEqual(height, size.Height); BitmapSize bitmapSize = { 0, 0 }; ThrowIfFailed(canvasImageSource->get_SizeInPixels(&bitmapSize)); Assert::AreEqual(static_cast<uint32_t>(round(width * dpi / DEFAULT_DPI)), bitmapSize.Width); Assert::AreEqual(static_cast<uint32_t>(round(height * dpi / DEFAULT_DPI)), bitmapSize.Height); } }; TEST_CLASS(CanvasImageSourceCreateDrawingSessionTests) { struct Fixture { ComPtr<StubCanvasDevice> m_canvasDevice; ComPtr<MockSurfaceImageSource> m_surfaceImageSource; ComPtr<StubSurfaceImageSourceFactory> m_surfaceImageSourceFactory; std::shared_ptr<MockCanvasImageSourceDrawingSessionFactory> m_canvasImageSourceDrawingSessionFactory; ComPtr<CanvasImageSource> m_canvasImageSource; int m_imageWidth; int m_imageHeight; Color m_anyColor; Fixture(float dpi = DEFAULT_DPI) { m_canvasDevice = Make<StubCanvasDevice>(); m_surfaceImageSource = Make<MockSurfaceImageSource>(); m_surfaceImageSourceFactory = Make<StubSurfaceImageSourceFactory>(m_surfaceImageSource.Get()); m_canvasImageSourceDrawingSessionFactory = std::make_shared<MockCanvasImageSourceDrawingSessionFactory>(); m_surfaceImageSource->SetDeviceMethod.AllowAnyCall(); m_imageWidth = 123; m_imageHeight = 456; m_canvasImageSource = Make<CanvasImageSource>( m_canvasDevice.Get(), (float)m_imageWidth, (float)m_imageHeight, dpi, CanvasAlphaMode::Premultiplied, m_surfaceImageSourceFactory.Get(), m_canvasImageSourceDrawingSessionFactory); m_surfaceImageSource->SetDeviceMethod.SetExpectedCalls(0); m_anyColor = Color{ 1, 2, 3, 4 }; } }; TEST_METHOD_EX(CanvasImageSource_CreateDrawingSession_PassesEntireImage) { Fixture f; f.m_canvasImageSourceDrawingSessionFactory->CreateMethod.SetExpectedCalls(1, [&](ICanvasDevice*, ISurfaceImageSourceNativeWithD2D*, Color const&, Rect const& updateRect, float) { Rect expectedRect{ 0, 0, static_cast<float>(f.m_imageWidth), static_cast<float>(f.m_imageHeight) }; Assert::AreEqual(expectedRect, updateRect); return Make<MockCanvasDrawingSession>(); }); ComPtr<ICanvasDrawingSession> drawingSession; ThrowIfFailed(f.m_canvasImageSource->CreateDrawingSession(f.m_anyColor, &drawingSession)); Assert::IsTrue(drawingSession); } TEST_METHOD_EX(CanvasImageSource_CreateDrawingSessionWithUpdateRegion_PassesSpecifiedUpdateRegion) { Fixture f; Rect expectedRect{ 1, 2, 3, 4 }; f.m_canvasImageSourceDrawingSessionFactory->CreateMethod.SetExpectedCalls(1, [&](ICanvasDevice*, ISurfaceImageSourceNativeWithD2D*, Color const&, Rect const& updateRect, float) { Assert::AreEqual(expectedRect, updateRect); return Make<MockCanvasDrawingSession>(); }); ComPtr<ICanvasDrawingSession> drawingSession; ThrowIfFailed(f.m_canvasImageSource->CreateDrawingSessionWithUpdateRectangle(f.m_anyColor, expectedRect, &drawingSession)); Assert::IsTrue(drawingSession); } TEST_METHOD_EX(CanvasImageSource_CreateDrawingSession_PassesClearColor) { Fixture f; int32_t anyLeft = 1; int32_t anyTop = 2; int32_t anyWidth = 3; int32_t anyHeight = 4; Color expectedColor{ 1, 2, 3, 4 }; f.m_canvasImageSourceDrawingSessionFactory->CreateMethod.SetExpectedCalls(2, [&](ICanvasDevice*, ISurfaceImageSourceNativeWithD2D*, Color const& clearColor, Rect const&, float) { Assert::AreEqual(expectedColor, clearColor); return Make<MockCanvasDrawingSession>(); }); ComPtr<ICanvasDrawingSession> ignoredDrawingSession; ThrowIfFailed(f.m_canvasImageSource->CreateDrawingSession(expectedColor, &ignoredDrawingSession)); ThrowIfFailed(f.m_canvasImageSource->CreateDrawingSessionWithUpdateRectangle(expectedColor, Rect{ (float)anyLeft, (float)anyTop, (float)anyWidth, (float)anyHeight }, &ignoredDrawingSession)); } }; TEST_CLASS(CanvasImageSourceDrawingSessionFactoryTests) { public: TEST_METHOD_EX(CanvasImageSourceDrawingSessionFactory_CallsBeginDrawWithCorrectUpdateRectangle) { auto drawingSessionFactory = std::make_shared<CanvasImageSourceDrawingSessionFactory>(); auto surfaceImageSource = Make<MockSurfaceImageSource>(); float dpi = 123.0f; Rect updateRectangleInDips{ 10, 20, 30, 40 }; RECT expectedUpdateRectangle = ToRECT(updateRectangleInDips, dpi); surfaceImageSource->BeginDrawMethod.SetExpectedCalls(1, [&] (RECT const& updateRectangle, IID const& iid, void** updateObject, POINT*) { Assert::AreEqual(expectedUpdateRectangle, updateRectangle); auto dc = Make<StubD2DDeviceContext>(nullptr); dc->SetTransformMethod.AllowAnyCall(); return dc.CopyTo(iid, updateObject); }); surfaceImageSource->EndDrawMethod.SetExpectedCalls(1); Color anyClearColor{ 1,2,3,4 }; drawingSessionFactory->Create( Make<MockCanvasDevice>().Get(), As<ISurfaceImageSourceNativeWithD2D>(surfaceImageSource).Get(), std::make_shared<bool>(), anyClearColor, updateRectangleInDips, dpi); } }; TEST_CLASS(CanvasImageSourceDrawingSessionAdapterTests) { public: TEST_METHOD_EX(CanvasImageSourceDrawingSessionAdapter_BeginEndDraw) { auto mockDeviceContext = Make<MockD2DDeviceContext>(); auto mockSurfaceImageSource = Make<MockSurfaceImageSource>(); RECT expectedUpdateRect{ 1, 2, 3, 4 }; POINT beginDrawOffset{ 5, 6 }; D2D1_COLOR_F expectedClearColor{ 7, 8, 9, 10 }; D2D1_POINT_2F expectedOffset{ static_cast<float>(beginDrawOffset.x - expectedUpdateRect.left), static_cast<float>(beginDrawOffset.y - expectedUpdateRect.top) }; mockSurfaceImageSource->BeginDrawMethod.SetExpectedCalls(1, [&](RECT const& updateRect, IID const& iid, void** updateObject, POINT* offset) { Assert::AreEqual(expectedUpdateRect, updateRect); Assert::AreEqual(_uuidof(ID2D1DeviceContext), iid); HRESULT hr = mockDeviceContext.CopyTo(iid, updateObject); *offset = beginDrawOffset; return hr; }); mockDeviceContext->ClearMethod.SetExpectedCalls(1, [&](D2D1_COLOR_F const* color) { Assert::AreEqual(expectedClearColor, *color); }); mockDeviceContext->SetTransformMethod.SetExpectedCalls(1, [&](const D2D1_MATRIX_3X2_F* m) { Assert::AreEqual(1.0f, m->_11); Assert::AreEqual(0.0f, m->_12); Assert::AreEqual(0.0f, m->_21); Assert::AreEqual(1.0f, m->_22); Assert::AreEqual(expectedOffset.x, m->_31); Assert::AreEqual(expectedOffset.y, m->_32); }); mockDeviceContext->SetDpiMethod.SetExpectedCalls(1, [&](float dpiX, float dpiY) { Assert::AreEqual(DEFAULT_DPI, dpiX); Assert::AreEqual(DEFAULT_DPI, dpiY); }); ComPtr<ID2D1DeviceContext1> actualDeviceContext; D2D1_POINT_2F actualOffset; auto adapter = CanvasImageSourceDrawingSessionAdapter::Create( mockSurfaceImageSource.Get(), expectedClearColor, expectedUpdateRect, DEFAULT_DPI, &actualDeviceContext, &actualOffset); Assert::AreEqual<ID2D1DeviceContext1*>(mockDeviceContext.Get(), actualDeviceContext.Get()); Assert::AreEqual(expectedOffset, actualOffset); mockSurfaceImageSource->EndDrawMethod.SetExpectedCalls(1); adapter->EndDraw(actualDeviceContext.Get()); } struct DeviceContextWithRestrictedQI : public MockD2DDeviceContext { // // Restrict this device context implementation so that it can only be // QI'd for ID2D1DeviceContext. // STDMETHOD(QueryInterface)(REFIID riid, _Outptr_result_nullonfailure_ void **ppvObject) { if (riid == __uuidof(ID2D1DeviceContext)) return RuntimeClass::QueryInterface(riid, ppvObject); return E_NOINTERFACE; } }; TEST_METHOD_EX(CanvasImageSourceDrawingSessionAdapter_When_SisNative_Gives_Unusuable_DeviceContext_Then_EndDraw_Called) { auto sis = Make<MockSurfaceImageSource>(); sis->BeginDrawMethod.SetExpectedCalls(1, [&](RECT const&, IID const& iid, void** obj, POINT*) { auto deviceContext = Make<DeviceContextWithRestrictedQI>(); return deviceContext.CopyTo(iid, obj); }); sis->EndDrawMethod.SetExpectedCalls(1); // // We expect creating the adapter to fail since our SurfaceImageSource // implementation returns a device context that only implements // ID2D1DeviceContext. // // If this happens we expect BeginDraw to have been called. Then, after // the failure, we expect EndDraw to have been called in order to clean // up properly. // ComPtr<ID2D1DeviceContext1> actualDeviceContext; D2D1_POINT_2F actualOffset; ExpectHResultException(E_NOINTERFACE, [&] { CanvasImageSourceDrawingSessionAdapter::Create( sis.Get(), D2D1_COLOR_F{ 1, 2, 3, 4 }, RECT{ 1, 2, 3, 4 }, DEFAULT_DPI, &actualDeviceContext, &actualOffset); }); } };
39.548148
199
0.65132
r2d2rigo
75ca9fb4e04ff2b0e4d7b0b143bed3015cae2e6c
595
cc
C++
src/Candle.cc
carolinavillam/Lucky-Monkey
5ddbadf6c604ea00c3384cc42eda9033d6297e7e
[ "MIT" ]
null
null
null
src/Candle.cc
carolinavillam/Lucky-Monkey
5ddbadf6c604ea00c3384cc42eda9033d6297e7e
[ "MIT" ]
null
null
null
src/Candle.cc
carolinavillam/Lucky-Monkey
5ddbadf6c604ea00c3384cc42eda9033d6297e7e
[ "MIT" ]
null
null
null
#include "Candle.hh" Candle::Candle(const char* textureUrl, sf::Vector2f position, float scale, float width, float height, int col, int row, sf::RenderWindow*& window, b2World*& world) : GameObject(textureUrl, position, scale, width, height, col, row, b2BodyType::b2_staticBody, window, world) { animationsManager = new AnimationsManager(); animationsManager->AddAnimation("idle", new Animation("assets/animations/candle/idle2.anim", drawable)); } Candle::~Candle() { } void Candle::Update(float& deltaTime) { animationsManager->Update(deltaTime); animationsManager->Play("idle"); }
27.045455
106
0.744538
carolinavillam
75cbdb9e5c961527d2241b0d02724dd87a66ba54
127
cpp
C++
Source/coopgame/Private/World/NativeEnemyPlayerStart.cpp
dakitten2358/coopgame
660293ce381d55025e4654ff448faf6a71a69bd2
[ "Apache-2.0" ]
1
2018-11-21T21:35:21.000Z
2018-11-21T21:35:21.000Z
Source/coopgame/Private/World/NativeEnemyPlayerStart.cpp
dakitten2358/coopgame
660293ce381d55025e4654ff448faf6a71a69bd2
[ "Apache-2.0" ]
1
2017-05-13T12:21:22.000Z
2017-05-13T12:24:39.000Z
Source/coopgame/Private/World/NativeEnemyPlayerStart.cpp
dakitten2358/coopgame
660293ce381d55025e4654ff448faf6a71a69bd2
[ "Apache-2.0" ]
1
2017-03-29T17:05:50.000Z
2017-03-29T17:05:50.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "NativeEnemyPlayerStart.h"
15.875
79
0.732283
dakitten2358
75d056890b4cd47c1a4666a5a68f2035ec6f7d31
2,757
cpp
C++
src/cli/argparse.cpp
NHollmann/CmdPathtracer
6c6c0382948bb6ea547458f743937b70c090ca6c
[ "MIT" ]
null
null
null
src/cli/argparse.cpp
NHollmann/CmdPathtracer
6c6c0382948bb6ea547458f743937b70c090ca6c
[ "MIT" ]
null
null
null
src/cli/argparse.cpp
NHollmann/CmdPathtracer
6c6c0382948bb6ea547458f743937b70c090ca6c
[ "MIT" ]
null
null
null
#include "argparse.hpp" #include <iostream> #include "cxxopts.hpp" namespace cli { RaytracerOptions parseArguments(int argc, char *argv[]) { RaytracerOptions raytracerOptions; cxxopts::Options options(argv[0], "A toy raytracer by Nicolas Hollmann."); options.add_options("General") ("help", "Print help"); options.add_options("IO") ("o,output", "Output filename", cxxopts::value<std::string>()->default_value("out.ppm"), "file") ("f,format", "Output format", cxxopts::value<std::string>()->default_value("ppm"), "format"); options.add_options("Raytracer") ("w,width", "Width of the target image", cxxopts::value<int>()->default_value("200"), "width") ("h,height", "Height of the target image", cxxopts::value<int>()->default_value("100"), "height") ("s,samples", "Samples per pixel", cxxopts::value<int>()->default_value("100"), "samples") ("d,depth", "Max ray depth", cxxopts::value<int>()->default_value("50"), "depth"); options.add_options("Multithreading") ("p,parallel", "Enables multithreading") ("t,threads", "Sets the thread count, 0 for auto", cxxopts::value<unsigned int>()->default_value("0"), "threads") ("blocksize", "Sets the size of a thread block", cxxopts::value<unsigned int>()->default_value("16"), "size"); options.add_options("Scene") ("world", "The world to render", cxxopts::value<std::string>()->default_value("random"), "world"); try { auto result = options.parse(argc, argv); if (result.count("help")) { std::cout << options.help() << std::endl; exit(0); } raytracerOptions.width = result["width"].as<int>(); raytracerOptions.height = result["height"].as<int>(); raytracerOptions.samples = result["samples"].as<int>(); raytracerOptions.depth = result["depth"].as<int>(); raytracerOptions.filename = result["output"].as<std::string>(); raytracerOptions.format = result["format"].as<std::string>(); raytracerOptions.multithreading = result.count("parallel") != 0; raytracerOptions.threadCount = result["threads"].as<unsigned int>(); raytracerOptions.blockSize = result["blocksize"].as<unsigned int>(); raytracerOptions.world = result["world"].as<std::string>(); } catch (const cxxopts::OptionException& e) { std::cerr << "Error parsing options: " << e.what() << std::endl; exit(1); } return raytracerOptions; } }
41.149254
125
0.571999
NHollmann
75d5469ea85f516ebf9dfddb8943c424e37f1606
351
cc
C++
src/kernel/core/class.cc
cmejj/How-to-Make-a-Computer-Operating-System
eb30f8802fac9f0f1c28d3a96bb3d402bdfc4687
[ "Apache-2.0" ]
16,500
2015-01-01T00:47:42.000Z
2022-03-31T17:12:02.000Z
src/kernel/core/class.cc
yongpingkan/How-to-Make-a-Computer-Operating-System
eb30f8802fac9f0f1c28d3a96bb3d402bdfc4687
[ "Apache-2.0" ]
66
2015-01-08T15:22:11.000Z
2021-12-16T09:04:37.000Z
src/kernel/core/class.cc
yongpingkan/How-to-Make-a-Computer-Operating-System
eb30f8802fac9f0f1c28d3a96bb3d402bdfc4687
[ "Apache-2.0" ]
3,814
2015-01-01T12:42:31.000Z
2022-03-31T14:26:50.000Z
#include <os.h> /* Static objects */ Io io; /* Input/Output interface */ Architecture arch; /* Cpu and architecture interface */ Vmm vmm; /* Virtual memory manager interface */ Filesystem fsm; /* Filesystem interface */ Module modm; /* Module manager */ Syscalls syscall; /* Syscalls manager */ System sys; /* System manager */
25.071429
57
0.660969
cmejj
75da9c1ef3d420e1a32e810b0fe0b90c6f564e25
2,588
hh
C++
sdd/mem/cache_entry.hh
tic-toc/libsdd
5c3deb43523d062929f169c3d7a301240f0fb811
[ "BSD-2-Clause" ]
6
2015-03-21T19:21:29.000Z
2022-01-29T01:20:28.000Z
sdd/mem/cache_entry.hh
tic-toc/libsdd
5c3deb43523d062929f169c3d7a301240f0fb811
[ "BSD-2-Clause" ]
1
2017-02-05T23:39:44.000Z
2017-02-05T23:40:04.000Z
libsdd/sdd/mem/cache_entry.hh
kyouko-taiga/SwiftSDD
9312160e0fac5fef6e605c9e74c543ded9708e54
[ "MIT" ]
3
2016-05-13T14:39:06.000Z
2019-08-09T20:13:39.000Z
/// @file /// @copyright The code is licensed under the BSD License /// <http://opensource.org/licenses/BSD-2-Clause>, /// Copyright (c) 2012-2015 Alexandre Hamez. /// @author Alexandre Hamez #pragma once #include <functional> // hash #include <list> #include <utility> // forward #include "sdd/mem/hash_table.hh" #include "sdd/mem/lru_list.hh" #include "sdd/util/hash.hh" namespace sdd { namespace mem { /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief Associate an operation to its result into the cache. /// /// The operation acts as a key and the associated result is the value counterpart. template <typename Operation, typename Result> struct cache_entry { // Can't copy a cache_entry. cache_entry(const cache_entry&) = delete; cache_entry& operator=(const cache_entry&) = delete; /// @brief mem::intrusive_member_hook<cache_entry> hook; /// @brief The cached operation. const Operation operation; /// @brief The result of the evaluation of operation. const Result result; /// @brief Where this cache entry is stored in the LRU list. typename lru_list<cache_entry>::const_iterator lru_cit_; /// @brief Constructor. template <typename... Args> cache_entry(Operation&& op, Args&&... args) : hook() , operation(std::move(op)) , result(std::forward<Args>(args)...) , lru_cit_() {} /// @brief Cache entries are only compared using their operations. friend bool operator==(const cache_entry& lhs, const cache_entry& rhs) noexcept { return lhs.operation == rhs.operation; } }; /*------------------------------------------------------------------------------------------------*/ }} // namespace sdd::mem namespace std { /*------------------------------------------------------------------------------------------------*/ /// @internal template <typename Operation, typename Result> struct hash<sdd::mem::cache_entry<Operation, Result>> { std::size_t operator()(const sdd::mem::cache_entry<Operation, Result>& x) { using namespace sdd::hash; // A cache entry must have the same hash as its contained operation. Otherwise, cache::erase() // and cache::insert_check()/cache::insert_commit() won't use the same position in buckets. return seed(x.operation); } }; /*------------------------------------------------------------------------------------------------*/ } // namespace std /*------------------------------------------------------------------------------------------------*/
28.755556
100
0.553323
tic-toc
75e5596aee746778f78381cffe406ad07ffb5f1a
5,682
cpp
C++
src/ofApp.cpp
ryo-simon-mf/oF-Color-Boxes
9ee208ec3c31d077c92860151c5a7df686ce579a
[ "MIT" ]
null
null
null
src/ofApp.cpp
ryo-simon-mf/oF-Color-Boxes
9ee208ec3c31d077c92860151c5a7df686ce579a
[ "MIT" ]
null
null
null
src/ofApp.cpp
ryo-simon-mf/oF-Color-Boxes
9ee208ec3c31d077c92860151c5a7df686ce579a
[ "MIT" ]
null
null
null
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ cam.setDistance(2500); gui.setup(); gui.add( toggle_0.setup("inside box",false)); gui.add( toggle_1.setup("outside box1",false)); gui.add( toggle_4.setup("outside box2",false)); gui.add( toggle_2.setup("Rotate Auto",false)); gui.add( toggle_3.setup("Rotate Mouse",false)); gui.add( xslider.setup("inside box x",180.0,0.0,360.0)); gui.add( yslider.setup("inside box y",180.0,0.0,360.0)); gui.add( zslider.setup("inside box z",180.0,0.0,360.0)); gui.add( xslider_1.setup("outside box1 x",180.0,0.0,360.0)); gui.add( yslider_1.setup("outside box1 y",180.0,0.0,360.0)); gui.add( zslider_1.setup("outside box1 z",180.0,0.0,360.0)); gui.add( xslider_2.setup("outside box2 x",180.0,0.0,360.0)); gui.add( yslider_2.setup("outside box2 y",180.0,0.0,360.0)); gui.add( zslider_2.setup("outside box2 z",180.0,0.0,360.0)); gui.add(color.setup("back ground color", ofColor(0, 0, 0), ofColor(0, 0), ofColor(255, 255))); gui.add( int_slider_0.setup("number of inside box ",100.0,1.0,1500.0)); gui.add( int_slider_1.setup("number of outside box ",100.0,1.0,1500.0)); gui.add( int_slider_2.setup("number of outside box ",100.0,1.0,1500.0)); bHide = false; open = true; open1 = true; open2 =true; open3=true; open4=true; on = false; for(int i=0;i<int_slider_0;i++){ Box tmp= Box(); boxes.push_back(tmp); } for(int i=0;i<int_slider_1;i++){ Box2 tmp= Box2(); boxes2.push_back(tmp); } for(int i=0;i<int_slider_2;i++){ Box3 tmp= Box3(); boxes3.push_back(tmp); } rotate_x=0; rotate_y=0; rotate_z=0; ofSetFrameRate(60); ofGetFrameNum(); } //-------------------------------------------------------------- void ofApp::update(){ for(int i=0;i< int_slider_0;i++){ boxes[i].update(); } for(int i=0;i< int_slider_1;i++){ boxes2[i].update(); } for(int i=0;i< int_slider_2;i++){ boxes3[i].update(); } rotate_x += 0.3; rotate_y += 0.3; rotate_z += 0.3; ofBackground(color); } //-------------------------------------------------------------- void ofApp::draw(){ cam.begin(); ofEnableDepthTest(); //rotate------------------------------ if(open2){ if(toggle_2 == true){ ofRotateX(rotate_x); ofRotateY(rotate_y); ofRotateZ(rotate_z); } } //Rotate auto-------------------------- if(open3){ if(toggle_3 == true){ ofRotateX(ofGetMouseX()); ofRotateY(ofGetMouseY()); } } //inside box--------------------------- ofPushMatrix(); if(open){ ofRotate(100, xslider, yslider, zslider); if( toggle_0 == true ){ for(int i=0; i < int_slider_0 ; i++){ boxes[i].draw(); Box tmp =Box(); boxes.push_back(tmp); } } } ofPopMatrix(); //outside box-------------------------- ofPushMatrix(); if(open1){ ofRotate(100, xslider_1, yslider_1, zslider_1); if( toggle_1 == true ){ for(int i=0; i < int_slider_1 ; i++){ boxes2[i].draw(); Box2 tmp =Box2(); boxes2.push_back(tmp); } } } ofPopMatrix(); //outside box-------------------------- ofPushMatrix(); if(open4){ ofRotate(100, xslider_2, yslider_2, zslider_2); if( toggle_4 == true ){ for(int i=0; i < int_slider_2 ; i++){ boxes3[i].draw(); Box3 tmp =Box3(); boxes3.push_back(tmp); } } } ofPopMatrix(); ofDisableDepthTest(); cam.end(); ofPopMatrix(); if(!bHide){ gui.draw(); } ofPushMatrix(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ if(key == 'h'){ bHide = !bHide; } if(key == 'f'){ ofToggleFullscreen(); } if(key == '1'){ color = ofColor(255); } if(key == '2'){ color = ofColor(0); } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
23.774059
76
0.416579
ryo-simon-mf
75ec66a2cf5a8b24571f5449a2d43f2dc1b23e8f
1,054
cpp
C++
1675-minimize-deviation-in-array/1675-minimize-deviation-in-array.cpp
Jatin-Shihora/LeetCode-Solutions
8e6fc84971ec96ec1263ba5ba2a8ae09e6404398
[ "MIT" ]
1
2022-01-02T10:29:32.000Z
2022-01-02T10:29:32.000Z
1675-minimize-deviation-in-array/1675-minimize-deviation-in-array.cpp
Jatin-Shihora/LeetCode-Solutions
8e6fc84971ec96ec1263ba5ba2a8ae09e6404398
[ "MIT" ]
null
null
null
1675-minimize-deviation-in-array/1675-minimize-deviation-in-array.cpp
Jatin-Shihora/LeetCode-Solutions
8e6fc84971ec96ec1263ba5ba2a8ae09e6404398
[ "MIT" ]
1
2022-03-04T12:44:14.000Z
2022-03-04T12:44:14.000Z
class Solution { public: int minimumDeviation(vector<int>& nums) { set <int> s; // Storing all elements in sorted order //insert even directly and odd with one time multiplication //and it will become even for(int i = 0; i<nums.size() ; ++i) { if(nums[i] % 2 == 0) s.insert(nums[i]); else // Odd number are transformed // using 2nd operation s.insert(nums[i] * 2); } // maximum - minimun int diff = *s.rbegin() - *s.begin(); //run the loop untill difference is minimized while(*s.rbegin() % 2 == 0) { // Maximum element of the set int x = *s.rbegin(); s.erase(x); // remove begin element and inserted half of it for minimizing s.insert(x/2); diff = min(diff, *s.rbegin() - *s.begin()); } return diff; } };
28.486486
74
0.446869
Jatin-Shihora
75f00f39fe0f4a39addc90305154e7c6205e9604
1,415
cpp
C++
nowa/2018/c++/zad4_3.cpp
shilangyu/zadania-maturalne
faa2b2ac8e17a7adb22c0c5aeccad9745c05e32c
[ "MIT" ]
3
2019-04-15T14:16:53.000Z
2019-04-26T09:37:19.000Z
nowa/2018/c++/zad4_3.cpp
shilangyu/zadania-maturalne
faa2b2ac8e17a7adb22c0c5aeccad9745c05e32c
[ "MIT" ]
1
2019-03-11T19:10:33.000Z
2019-03-11T19:10:33.000Z
nowa/2018/c++/zad4_3.cpp
shilangyu/zadania-maturalne
faa2b2ac8e17a7adb22c0c5aeccad9745c05e32c
[ "MIT" ]
1
2019-04-26T09:38:04.000Z
2019-04-26T09:38:04.000Z
#include <iostream> #include <cstdlib> #include <fstream> #include <string> #include <vector> using namespace std; string zad4_3() { string line; vector<string> content; fstream file("../dane/sygnaly.txt"); // wczytywanie danych z pliku do vectora if (file.is_open()) { while (getline(file, line)) content.push_back(line); } file.close(); // przypisanie zmiennym numerów odpowiadających za pierwszą literę alfabetu w tablicy ASCII (65) // oraz za ostatnią (90) int minAscii = 90; int maxAscii = 65; vector<char> word; vector<string> answerVector; for (int i = 0; i < content.size(); i++) { for (int j = 0; j < content[i].size(); j++) { word.push_back(content[i][j]); } for (int j = 0; j < word.size(); j++) { if (char(word[j]) < minAscii) minAscii = char(word[j]); if (char(word[j]) > maxAscii) maxAscii = char(word[j]); } if (maxAscii - minAscii <= 10) answerVector.push_back(content[i]); word.clear(); minAscii = 90; maxAscii = 65; } string answer = "\n"; for (int i = 0; i < answerVector.size(); i++) answer += answerVector[i] + "\n"; return "4.3. Slowa, w ktorych litery sa maksymalnie oddalone od siebie o 10 znakow: " + answer; }
23.583333
100
0.543463
shilangyu
75f97aab1684f5ca3f646c331526fdf3ac9a8bfb
4,639
cpp
C++
NarThumbnailProvider/zip_reader_open_IStream.cpp
Taromati2/nar-thumbnail-provider
6b20d2896822754c9ac5e4c69999d0762b4f23df
[ "MIT" ]
null
null
null
NarThumbnailProvider/zip_reader_open_IStream.cpp
Taromati2/nar-thumbnail-provider
6b20d2896822754c9ac5e4c69999d0762b4f23df
[ "MIT" ]
null
null
null
NarThumbnailProvider/zip_reader_open_IStream.cpp
Taromati2/nar-thumbnail-provider
6b20d2896822754c9ac5e4c69999d0762b4f23df
[ "MIT" ]
null
null
null
#include "windows.h" #include "../minizip-ng/mz.h" #include "../minizip-ng/mz_strm.h" #include "../minizip-ng/mz_zip.h" #include "../minizip-ng/mz_zip_rw.h" typedef struct mz_zip_reader_s { void *zip_handle; void *file_stream; void *buffered_stream; void *split_stream; void *mem_stream; void *hash; uint16_t hash_algorithm; uint16_t hash_digest_size; mz_zip_file *file_info; const char *pattern; uint8_t pattern_ignore_case; const char *password; void *overwrite_userdata; mz_zip_reader_overwrite_cb overwrite_cb; void *password_userdata; mz_zip_reader_password_cb password_cb; void *progress_userdata; mz_zip_reader_progress_cb progress_cb; uint32_t progress_cb_interval_ms; void *entry_userdata; mz_zip_reader_entry_cb entry_cb; uint8_t raw; uint8_t buffer[UINT16_MAX]; int32_t encoding; uint8_t sign_required; uint8_t cd_verified; uint8_t cd_zipped; uint8_t entry_verified; uint8_t recover; } mz_zip_reader; /***************************************************************************/ typedef struct mz_stream_IStream_s { mz_stream stream; IStream *ps; } mz_stream_IStream; /***************************************************************************/ int32_t mz_stream_IStream_open(void *stream, const char *path, int32_t mode) { mz_stream_IStream *mem = (mz_stream_IStream *)stream; int32_t err = MZ_OK; mem->ps = (IStream *)path; return err; } int32_t mz_stream_IStream_is_open(void *stream) { mz_stream_IStream *mem = (mz_stream_IStream *)stream; if(mem->ps == NULL) return MZ_OPEN_ERROR; return MZ_OK; } int32_t mz_stream_IStream_read(void *stream, void *buf, int32_t size) { mz_stream_IStream *mem = (mz_stream_IStream *)stream; ULONG ret; mem->ps->Read(buf,size,&ret); return ret; } int32_t mz_stream_IStream_write(void *stream, const void *buf, int32_t size) { return 0; } int64_t mz_stream_IStream_tell(void *stream) { mz_stream_IStream *mem = (mz_stream_IStream *)stream; ULARGE_INTEGER ret; mem->ps->Seek({0}, STREAM_SEEK_CUR,&ret ); return ret.QuadPart; } int32_t mz_stream_IStream_seek(void *stream, int64_t offset, int32_t origin) { mz_stream_IStream *mem = (mz_stream_IStream *)stream; int64_t new_pos = 0; int32_t err = MZ_OK; LARGE_INTEGER offL = {}; offL.QuadPart = offset; switch(origin) { case MZ_SEEK_CUR: mem->ps->Seek(offL, STREAM_SEEK_CUR, NULL); break; case MZ_SEEK_END: mem->ps->Seek(offL, STREAM_SEEK_END, NULL); break; case MZ_SEEK_SET: mem->ps->Seek(offL, STREAM_SEEK_SET, NULL); break; default: return MZ_SEEK_ERROR; } return MZ_OK; } int32_t mz_stream_IStream_close(void *stream) { /* We never return errors */ return MZ_OK; } int32_t mz_stream_IStream_error(void *stream) { /* We never return errors */ return MZ_OK; } extern mz_stream_vtbl mz_stream_IStream_vtbl; void *mz_stream_IStream_create(void **stream) { mz_stream_IStream *mem = NULL; mem = (mz_stream_IStream *)MZ_ALLOC(sizeof(mz_stream_IStream)); if(mem != NULL) { memset(mem, 0, sizeof(mz_stream_IStream)); mem->stream.vtbl = &mz_stream_IStream_vtbl; } if(stream != NULL) *stream = mem; return mem; } void mz_stream_IStream_delete(void **stream) { mz_stream_IStream *mem = NULL; if(stream == NULL) return; mem = (mz_stream_IStream *)*stream; if(mem != NULL) { MZ_FREE(mem); } *stream = NULL; } /***************************************************************************/ static mz_stream_vtbl mz_stream_IStream_vtbl = { mz_stream_IStream_open, mz_stream_IStream_is_open, mz_stream_IStream_read, mz_stream_IStream_write, mz_stream_IStream_tell, mz_stream_IStream_seek, mz_stream_IStream_close, mz_stream_IStream_error, mz_stream_IStream_create, mz_stream_IStream_delete, NULL, NULL }; // int32_t mz_zip_reader_open_IStream(void *handle, IStream *ps) { mz_zip_reader *reader = (mz_zip_reader *)handle; int32_t err = MZ_OK; mz_zip_reader_close(handle); mz_stream_IStream_create(&reader->mem_stream); mz_stream_IStream_open(reader->mem_stream, (char*)ps, MZ_OPEN_MODE_READ); if(err == MZ_OK) err = mz_zip_reader_open(handle, reader->mem_stream); return err; }
25.349727
79
0.632033
Taromati2
75fa3f0e258c665df7572f01b6807b4b5a79f358
1,549
hpp
C++
src/organization_model/Statistics.hpp
tomcreutz/knowledge-reasoning-moreorg
545fa92eaf0fc8ccc4cc042bd994afc918d16f68
[ "BSD-3-Clause" ]
null
null
null
src/organization_model/Statistics.hpp
tomcreutz/knowledge-reasoning-moreorg
545fa92eaf0fc8ccc4cc042bd994afc918d16f68
[ "BSD-3-Clause" ]
1
2021-02-26T11:11:03.000Z
2021-02-26T19:16:10.000Z
src/organization_model/Statistics.hpp
tomcreutz/knowledge-reasoning-moreorg
545fa92eaf0fc8ccc4cc042bd994afc918d16f68
[ "BSD-3-Clause" ]
1
2021-05-17T13:02:49.000Z
2021-05-17T13:02:49.000Z
#ifndef ORGANIZATION_MODEL_ORGANIZATION_MODEL_STATISTICS_HPP #define ORGANIZATION_MODEL_ORGANIZATION_MODEL_STATISTICS_HPP #include <stdint.h> #include <base/Time.hpp> #include <moreorg/organization_model/InterfaceConnection.hpp> #include <moreorg/organization_model/ActorModelLink.hpp> namespace owl = owlapi::model; namespace moreorg { namespace moreorg { /** * Statistic of the organization model engine */ struct Statistics { Statistics(); uint32_t upperCombinationBound; uint32_t numberOfInferenceEpochs; base::Time timeCompositeSystemGeneration; base::Time timeRegisterCompositeSystems; base::Time timeInference; base::Time timeElapsed; owl::IRIList interfaces; uint32_t maxAllowedLinks; InterfaceConnectionList links; InterfaceCombinationList linkCombinations; uint32_t constraintsChecked; owl::IRIList actorsAtomic; owl::IRIList actorsKnown; owl::IRIList actorsInferred; owl::IRIList actorsCompositePrevious; //owl::IRIList actorsCompositePost; uint32_t actorsCompositePost; owl::IRIList actorsCompositeModelPrevious; std::vector< std::vector<ActorModelLink> > actorsCompositeModelPost; //uint32_t actorsCompositeModelPost; std::string toString() const; }; std::ostream& operator<<(std::ostream& os, const Statistics& statistics); std::ostream& operator<<(std::ostream& os, const std::vector<Statistics>& statisticsList); } // end namespace moreorg } // end namespace moreorg #endif // ORGANIZATION_MODEL_ORGANIZATION_MODEL_STATISTICS_HPP
27.660714
90
0.775339
tomcreutz
2f050085d7b99d79442a0c3e6e986aaace885244
365
hpp
C++
Scripts/Exile_Scavenge/Exile.MAPNAME/CfgRemoteExec.hpp
x-cessive/exile
c5d1f679879a183549e1c87d078d462cbba32c25
[ "MIT" ]
9
2017-03-30T15:37:09.000Z
2022-02-06T22:44:17.000Z
Scripts/Exile_Scavenge/Exile.MAPNAME/CfgRemoteExec.hpp
x-cessive/exile
c5d1f679879a183549e1c87d078d462cbba32c25
[ "MIT" ]
1
2017-04-10T14:59:31.000Z
2017-04-11T14:42:13.000Z
Scripts/Exile_Scavenge/Exile.MAPNAME/CfgRemoteExec.hpp
x-cessive/exile
c5d1f679879a183549e1c87d078d462cbba32c25
[ "MIT" ]
6
2017-02-25T00:19:40.000Z
2022-02-16T19:54:45.000Z
class CfgRemoteExec { class Functions { mode = 2; jip = 0; class fnc_AdminReq { allowedTargets=2; }; class ExileServer_system_network_dispatchIncomingMessage { allowedTargets=2; }; class ExileExpansionServer_system_scavenge_spawnLoot { allowedTargets=0; }; }; class Commands { mode=0; jip=0; }; };
22.8125
83
0.632877
x-cessive
2f06c9830e77a368f7eb4bb675e6ad52232b7bcb
1,535
cpp
C++
src/game-ui/in-game/game_ui_teleporter.cpp
astrellon/simple-space
20e98d4f562a78b1efeaedb0a0012f3c9306ac7e
[ "MIT" ]
1
2020-09-23T11:17:35.000Z
2020-09-23T11:17:35.000Z
src/game-ui/in-game/game_ui_teleporter.cpp
astrellon/simple-space
20e98d4f562a78b1efeaedb0a0012f3c9306ac7e
[ "MIT" ]
null
null
null
src/game-ui/in-game/game_ui_teleporter.cpp
astrellon/simple-space
20e98d4f562a78b1efeaedb0a0012f3c9306ac7e
[ "MIT" ]
null
null
null
#include "game_ui_teleporter.hpp" #include "../ui_text_element.hpp" #include "../ui_button.hpp" #include "../game_ui_manager.hpp" #include "../../game/items/teleporter.hpp" #include "../../engine.hpp" #include "../../game_session.hpp" #include "../../game/character.hpp" namespace space { void GameUITeleporter::init(GameUIManager &uiManager) { _text = uiManager.createElement<UITextElement>(); _uiManager = &uiManager; _text->widthPercent(100); _text->flexShrink(1.0f); addChild(_text); _actionButton = uiManager.createElement<UIButton>(); _actionButton->width(50); _actionButton->text("Go"); addChild(_actionButton); flexDirection(YGFlexDirectionRow); _actionButton->onClick([this, &uiManager] (const sf::Event &e) { if (this->_teleporter.item == nullptr) { return UIEventResult::Triggered; } auto session = uiManager.engine().currentSession(); auto character = session->playerController().controllingCharacter(); auto placed = this->_teleporter.placed; session->moveSpaceObject(static_cast<SpaceObject *>(character), placed->transform().position, placed->insideArea(), true); return UIEventResult::Triggered; }); } void GameUITeleporter::teleporter(PlacedItemPair<Teleporter> teleporter) { _teleporter = teleporter; _text->text(teleporter.item->name()); } } // space
30.098039
134
0.626059
astrellon
2f0e58369426a872d6e60a0940741337c827f251
1,191
cpp
C++
quake_framebuffer/quake_framebuffer/net_none.cpp
WarlockD/quake-stm32
8414f407f6fc529bf9d5a371ed91c1ee1194679b
[ "BSD-2-Clause" ]
4
2018-07-03T14:21:39.000Z
2021-06-01T06:12:14.000Z
quake_framebuffer/quake_framebuffer/net_none.cpp
WarlockD/quake-stm32
8414f407f6fc529bf9d5a371ed91c1ee1194679b
[ "BSD-2-Clause" ]
null
null
null
quake_framebuffer/quake_framebuffer/net_none.cpp
WarlockD/quake-stm32
8414f407f6fc529bf9d5a371ed91c1ee1194679b
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "icommon.h" #include "net_loop.h" net_driver_t net_drivers[MAX_NET_DRIVERS] = { { "Loopback", false, Loop_Init, Loop_Listen, Loop_SearchForHosts, Loop_Connect, Loop_CheckNewConnections, Loop_GetMessage, Loop_SendMessage, Loop_SendUnreliableMessage, Loop_CanSendMessage, Loop_CanSendUnreliableMessage, Loop_Close, Loop_Shutdown } }; int net_numdrivers = 1; net_landriver_t net_landrivers[MAX_NET_DRIVERS]; int net_numlandrivers = 0;
24.8125
75
0.786734
WarlockD
2f128127c60db93ca245e59efd2846ef5b44d83b
3,553
cpp
C++
src/save/main.cpp
RobertLeahy/MCPP
2b9223afa35ae215b9af7e5398ce8f7f6dd70377
[ "Unlicense" ]
19
2015-04-25T15:19:59.000Z
2022-02-28T03:00:42.000Z
src/save/main.cpp
RobertLeahy/MCPP
2b9223afa35ae215b9af7e5398ce8f7f6dd70377
[ "Unlicense" ]
1
2016-01-28T08:50:02.000Z
2021-08-24T02:34:48.000Z
src/save/main.cpp
RobertLeahy/MCPP
2b9223afa35ae215b9af7e5398ce8f7f6dd70377
[ "Unlicense" ]
7
2015-04-17T16:38:45.000Z
2021-06-25T03:39:39.000Z
#include <save/save.hpp> #include <server.hpp> #include <singleton.hpp> #include <thread_pool.hpp> #include <exception> #include <utility> using namespace MCPP; namespace MCPP { static const Word priority=1; static const String name("Save Manager"); static const String debug_key("save"); static const String save_complete("Save complete - took {0}ns"); static const String save_paused("Save loop paused, skipping"); static const String setting_key("save_frequency"); static const Word frequency_default=5*60*1000; // Every 5 minutes bool SaveManager::is_verbose () { return Server::Get().IsVerbose(debug_key); } void SaveManager::save () { auto & server=Server::Get(); try { Timer timer(Timer::CreateAndStart()); for (auto & callback : callbacks) callback(); auto elapsed=timer.ElapsedNanoseconds(); this->elapsed+=elapsed; ++count; if (is_verbose()) server.WriteLog( String::Format( save_complete, elapsed, frequency ), Service::LogType::Debug ); } catch (...) { try { server.Panic(std::current_exception()); } catch (...) { } throw; } } void SaveManager::save_loop () { auto & server=Server::Get(); if ( lock.Execute([&] () mutable { if (paused) return true; save(); return false; }) && is_verbose() ) server.WriteLog( save_paused, Service::LogType::Debug ); try { server.Pool().Enqueue( frequency, [this] () mutable { save_loop(); } ); } catch (...) { try { server.Panic(std::current_exception()); } catch (...) { } throw; } } static Singleton<SaveManager> singleton; SaveManager & SaveManager::Get () noexcept { return singleton.Get(); } SaveManager::SaveManager () noexcept { paused=false; count=0; elapsed=0; } Word SaveManager::Priority () const noexcept { return priority; } const String & SaveManager::Name () const noexcept { return name; } void SaveManager::Install () { auto & server=Server::Get(); // On shutdown we must save everything // one last time server.OnShutdown.Add([this] () mutable { save(); // Purge all callbacks held which // may have originated from other // modules callbacks.Clear(); }); // Once the install phase is done, and // all modules that wish to save have // added their handlers, start the // save loop server.OnInstall.Add([this] (bool) mutable { Server::Get().Pool().Enqueue( frequency, [this] () mutable { save_loop(); } ); }); // Get the frequency with which saves // should be performed from the backing store frequency=server.Data().GetSetting( setting_key, frequency_default ); } void SaveManager::Add (std::function<void ()> callback) { if (callback) callbacks.Add(std::move(callback)); } void SaveManager::operator () () { lock.Execute([&] () mutable { save(); }); } void SaveManager::Pause () noexcept { lock.Execute([&] () mutable { paused=true; }); } void SaveManager::Resume () noexcept { lock.Execute([&] () mutable { paused=false; }); } SaveManagerInfo SaveManager::GetInfo () const noexcept { return SaveManagerInfo{ frequency, paused, count, elapsed }; } } extern "C" { Module * Load () { return &(SaveManager::Get()); } void Unload () { singleton.Destroy(); } }
14.384615
66
0.599775
RobertLeahy
2f2bdcf7447fd4ad54fdfd70d829770df30d3c37
980
cpp
C++
SnackDown Round 1A/BINFLIP.cpp
Jks08/CodeChef
a8aec8a563c441176a36b8581031764e99f09833
[ "MIT" ]
1
2021-09-17T13:10:04.000Z
2021-09-17T13:10:04.000Z
SnackDown Round 1A/BINFLIP.cpp
Jks08/CodeChef
a8aec8a563c441176a36b8581031764e99f09833
[ "MIT" ]
null
null
null
SnackDown Round 1A/BINFLIP.cpp
Jks08/CodeChef
a8aec8a563c441176a36b8581031764e99f09833
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define ll long long #define FAST1 ios_base::sync_with_stdio(false); #define FAST2 cin.tie(NULL); #define allsort(a) sort(a.begin(),a.end()) ll n,k; void solve(){ cin>>n>>k; if(k==0){ cout<<"Yes"<<endl; cout<<0<<endl; return; } if(k%2==0){ cout<<"No"<<endl;; return; } ll sz=0; for(ll i=31;i>=0;i--){ if(((1<<i)&k)!=0){ sz=i+1; break; } } k=(k+(1<<sz)-1)/2; cout<<"Yes"<<endl; cout<<sz<<endl; int ans=1; vector<int> a; for(int i=sz-2;i>=0;i--){ if(((1<<i)&k)!=0){ a.push_back(ans); ans+=(1<<i); } else{ ans-=(1<<i); a.push_back(ans); } } for(int i=sz-2;i>=0;i--) cout<<a[i]<<endl; cout<<ans<<endl; } int main(){ FAST1; FAST2; ll t; cin>>t; while(t--){ solve(); } }
17.5
47
0.418367
Jks08
2f315b9281397276f2339416be7e8d28f31ac034
887
cc
C++
leet_code/Longest_Increasing_Subsequence/dp_solution.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
1
2020-04-11T22:04:23.000Z
2020-04-11T22:04:23.000Z
leet_code/Longest_Increasing_Subsequence/dp_solution.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
null
null
null
leet_code/Longest_Increasing_Subsequence/dp_solution.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
null
null
null
class Solution { private: const int invalid = -1; int getAnswer(vector<int>& answer, vector<int> &nums, int idx) { int max = 0; if (answer[idx] != invalid) { return answer[idx]; } for (int i = idx + 1; i < answer.size(); ++i) { if (nums[idx] >= nums[i]) { continue; } int ret = getAnswer(answer, nums, i); if (max < ret) { max = ret; } } answer[idx] = max + 1; return answer[idx]; } public: int lengthOfLIS(vector<int>& nums) { vector<int> answer(nums.size(), invalid); int ans = 0; for (int i = 0; i < answer.size(); ++i) { int ret = getAnswer(answer, nums, i); if (ans < ret) { ans = ret; } } return ans; } };
23.972973
68
0.421646
ldy121
2f33385320806e4d297750693b873ce73938820c
837
cpp
C++
program8/program8/driver.cpp
hurnhu/Academic-C-Code-Examples
2dbab12888fc7f87b997daf7df4127a1ffd81b44
[ "MIT" ]
null
null
null
program8/program8/driver.cpp
hurnhu/Academic-C-Code-Examples
2dbab12888fc7f87b997daf7df4127a1ffd81b44
[ "MIT" ]
null
null
null
program8/program8/driver.cpp
hurnhu/Academic-C-Code-Examples
2dbab12888fc7f87b997daf7df4127a1ffd81b44
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <string> using namespace std; #include "ProblemList.h" /* ********************* *MADE BY MICHAEL LApAN ********************* *this program is a help desk mock up *it proccesses helkp desk tickets, *sorts and stores them. then shows top *25 then bottem 25 */ int main() { ProblemList problems("problems.txt"); ProblemList newProblems("newproblems.txt"); ProblemList solvedProblems("resolvedproblems.txt"); problems += newProblems; problems -= solvedProblems; //couldnt easily incorporate this into class cout << "Priority Submitted By Description" << endl; problems.writeTop(25); system("pause"); //couldnt easily incorporate this into class cout << "Priority Submitted By Description" << endl; problems.writeBottom(25); system("pause"); }
23.25
65
0.67503
hurnhu
2f40127686b3e138bd6d4c51ffba3159a2b80c29
562
cpp
C++
CodeForces/862/A - Mahmoud and Ehab and the MEX.cpp
QAQrz/ACM-Code
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
[ "Unlicense" ]
2
2018-02-24T06:45:56.000Z
2018-05-29T04:47:39.000Z
CodeForces/862/A - Mahmoud and Ehab and the MEX.cpp
QAQrz/ACM-Code
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
[ "Unlicense" ]
null
null
null
CodeForces/862/A - Mahmoud and Ehab and the MEX.cpp
QAQrz/ACM-Code
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
[ "Unlicense" ]
2
2018-06-28T09:53:27.000Z
2022-03-23T13:29:57.000Z
#include <bits/stdc++.h> using namespace std; #pragma comment(linker,"/stack:1024000000,1024000000") #define db(x) cout<<(x)<<endl #define pf(x) push_front(x) #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define ms(x,y) memset(x,y,sizeof x) typedef long long LL; const double pi=acos(-1),eps=1e-9; const LL inf=0x3f3f3f3f,mod=1e9+7,maxn=1123456; int n,a,x,vis[128],ans; int main(){ ios::sync_with_stdio(0); cin>>n>>x; for(int i=0;i<n;i++){ cin>>a; vis[a]=1; } for(int i=0;i<x;i++) if(!vis[i]) ans++; db(vis[x]?ans+1:ans); return 0; }
22.48
54
0.649466
QAQrz
2f40bd39f42d58fecaad97ea17318d2cace2933c
9,089
cpp
C++
src/Editor/TristeonEditor.cpp
HyperionDH/Tristeon
8475df94b9dbd4e3b4cc82b89c6d4bab45acef29
[ "MIT" ]
38
2017-12-04T10:48:28.000Z
2018-05-11T09:59:41.000Z
src/Editor/TristeonEditor.cpp
Tristeon/Tristeon3D
8475df94b9dbd4e3b4cc82b89c6d4bab45acef29
[ "MIT" ]
9
2017-12-04T09:58:55.000Z
2018-02-05T00:06:41.000Z
src/Editor/TristeonEditor.cpp
Tristeon/Tristeon3D
8475df94b9dbd4e3b4cc82b89c6d4bab45acef29
[ "MIT" ]
3
2018-01-10T13:39:12.000Z
2018-03-17T20:53:22.000Z
#include "Core/MessageBus.h" #ifdef TRISTEON_EDITOR #include "TristeonEditor.h" #include <ImGUI/imgui_impl_glfw_vulkan.h> #include "Core/Engine.h" #include "Core/Rendering/Vulkan/HelperClasses/CommandBuffer.h" #include "Core/Rendering/Vulkan/RenderManagerVulkan.h" #include "Asset Browser/AssetBrowser.h" #include "Scene editor/GameObjectHierarchy.h" #include "Inspector/InspectorWindow.h" #include "Scene editor/SceneWindow.h" #include "Misc/Console.h" #include "Misc/Hardware/Keyboard.h" #include "EditorDragging.h" namespace Tristeon { using namespace Editor; TristeonEditor::TristeonEditor(Core::Engine* engine) { editorCamera = nullptr; Core::VulkanBindingData *vkBinding = Core::VulkanBindingData::getInstance(); this->vkDevice = vkBinding->device; this->engine = engine; bindImGui(vkBinding); initFontsImGui(vkBinding); setupCallbacks(); createCommandBuffers(); //Set style setStyle(); //Create editor windows EditorWindow::editor = this; windows.push_back(std::move(std::make_unique<AssetBrowser>())); windows.push_back(std::move(std::make_unique<GameObjectHierarchy>())); windows.push_back(std::move(std::make_unique<InspectorWindow>())); windows.push_back(std::move(std::make_unique<SceneWindow>(this))); } TristeonEditor::~TristeonEditor() { Core::MessageBus::sendMessage(Core::Message(Core::MT_RENDERINGCOMPONENT_DEREGISTER, renderable)); delete renderable; vkDevice.waitIdle(); ImGui_ImplGlfwVulkan_Shutdown(); } void TristeonEditor::setStyle() { ImGuiStyle * style = &ImGui::GetStyle(); style->WindowPadding = ImVec2(15, 15); style->WindowRounding = 5.0f; style->FramePadding = ImVec2(5, 5); style->FrameRounding = 4.0f; style->ItemSpacing = ImVec2(12, 8); style->ItemInnerSpacing = ImVec2(8, 6); style->IndentSpacing = 25.0f; style->ScrollbarSize = 15.0f; style->ScrollbarRounding = 9.0f; style->GrabMinSize = 5.0f; style->GrabRounding = 3.0f; style->Colors[ImGuiCol_Text] = ImVec4(0.80f, 0.80f, 0.83f, 1.00f); style->Colors[ImGuiCol_TextDisabled] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f); style->Colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f); style->Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.07f, 0.07f, 0.09f, 1.00f); style->Colors[ImGuiCol_PopupBg] = ImVec4(0.07f, 0.07f, 0.09f, 1.00f); style->Colors[ImGuiCol_Border] = ImVec4(0.80f, 0.80f, 0.83f, 0.88f); style->Colors[ImGuiCol_BorderShadow] = ImVec4(0.92f, 0.91f, 0.88f, 0.00f); style->Colors[ImGuiCol_FrameBg] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); style->Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f); style->Colors[ImGuiCol_FrameBgActive] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); style->Colors[ImGuiCol_TitleBg] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); style->Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 0.98f, 0.95f, 0.75f); style->Colors[ImGuiCol_TitleBgActive] = ImVec4(0.07f, 0.07f, 0.09f, 1.00f); style->Colors[ImGuiCol_MenuBarBg] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); style->Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); style->Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.80f, 0.80f, 0.83f, 0.31f); style->Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); style->Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f); style->Colors[ImGuiCol_ComboBg] = ImVec4(0.19f, 0.18f, 0.21f, 1.00f); style->Colors[ImGuiCol_CheckMark] = ImVec4(0.80f, 0.80f, 0.83f, 0.31f); style->Colors[ImGuiCol_SliderGrab] = ImVec4(0.80f, 0.80f, 0.83f, 0.31f); style->Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f); style->Colors[ImGuiCol_Button] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); style->Colors[ImGuiCol_ButtonHovered] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f); style->Colors[ImGuiCol_ButtonActive] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); style->Colors[ImGuiCol_Header] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); style->Colors[ImGuiCol_HeaderActive] = ImVec4(0, 0, 0, 0); style->Colors[ImGuiCol_HeaderHovered] = ImVec4(0.301f, 0.537f, .788f, 1); style->Colors[ImGuiCol_Column] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); style->Colors[ImGuiCol_ColumnHovered] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f); style->Colors[ImGuiCol_ColumnActive] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); style->Colors[ImGuiCol_ResizeGrip] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); style->Colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); style->Colors[ImGuiCol_ResizeGripActive] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f); style->Colors[ImGuiCol_CloseButton] = ImVec4(0.40f, 0.39f, 0.38f, 0.16f); style->Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.40f, 0.39f, 0.38f, 0.39f); style->Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.40f, 0.39f, 0.38f, 1.00f); style->Colors[ImGuiCol_PlotLines] = ImVec4(0.40f, 0.39f, 0.38f, 0.63f); style->Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.25f, 1.00f, 0.00f, 1.00f); style->Colors[ImGuiCol_PlotHistogram] = ImVec4(0.40f, 0.39f, 0.38f, 0.63f); style->Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(0.25f, 1.00f, 0.00f, 1.00f); style->Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.25f, 1.00f, 0.00f, 0.43f); style->Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(1.00f, 0.98f, 0.95f, 0.73f); style->Colors[ImGuiCol_TSelectableActive] = ImVec4(1,1,1,1); } void TristeonEditor::onGui() { if (Misc::Keyboard::getKeyDown(Misc::KeyCode::SPACE)) { inPlayMode = !inPlayMode; Core::MessageBus::sendMessage(inPlayMode ? Core::MT_GAME_LOGIC_START : Core::MT_GAME_LOGIC_STOP); } //If playing the game it will go in fullscreen, thus the editor no longer needs to be rendered, will be subject to change if (inPlayMode) return; ImGui_ImplGlfwVulkan_NewFrame(); //ImGuizmo::BeginFrame(); //Calling ongui functions of editorwindows for (int i = 0; i < windows.size(); ++i) { windows[i]->onGui(); } //Update dragging if (ImGui::IsMouseReleased(0)) { EditorDragging::reset(); } } void TristeonEditor::render() { if (inPlayMode) return; Core::Rendering::Vulkan::RenderData* d = dynamic_cast<Core::Rendering::Vulkan::RenderData*>(renderable->data); vk::CommandBufferBeginInfo const begin = vk::CommandBufferBeginInfo(vk::CommandBufferUsageFlagBits::eRenderPassContinue, &d->inheritance); cmd.begin(begin); ImGui_ImplGlfwVulkan_Render(static_cast<VkCommandBuffer>(cmd)); cmd.end(); d->lastUsedSecondaryBuffer = cmd; } void TristeonEditor::bindImGui(Core::VulkanBindingData* vkBinding) { ImGui_ImplGlfwVulkan_Init_Data init_data; init_data.allocator = nullptr; init_data.gpu = static_cast<VkPhysicalDevice>(vkBinding->physicalDevice); init_data.device = static_cast<VkDevice>(vkBinding->device); init_data.render_pass = static_cast<VkRenderPass>(vkBinding->renderPass); init_data.pipeline_cache = NULL; init_data.descriptor_pool = static_cast<VkDescriptorPool>(vkBinding->descriptorPool); init_data.check_vk_result = [](VkResult err) { Misc::Console::t_assert(err == VK_SUCCESS, "Editor vulkan error: " + err); }; ImGui_ImplGlfwVulkan_Init(vkBinding->window, true, &init_data); } void TristeonEditor::initFontsImGui(Core::VulkanBindingData* vkBinding) { VkResult err = vkResetCommandPool( static_cast<VkDevice>(vkBinding->device), static_cast<VkCommandPool>(vkBinding->commandPool), 0); Misc::Console::t_assert(err == VK_SUCCESS, "Failed to reset command pool: " + to_string(static_cast<vk::Result>(err))); VkCommandBuffer const cmd = static_cast<VkCommandBuffer>(Core::Rendering::Vulkan::CommandBuffer::begin(vkBinding->commandPool, vkBinding->device)); ImGui_ImplGlfwVulkan_CreateFontsTexture(cmd); Core::Rendering::Vulkan::CommandBuffer::end(static_cast<vk::CommandBuffer>(cmd), vkBinding->graphicsQueue, vkBinding->device, vkBinding->commandPool); vkBinding->device.waitIdle(); ImGui_ImplGlfwVulkan_InvalidateFontUploadObjects(); } void TristeonEditor::setupCallbacks() { //Subscribe to render callback Core::MessageBus::subscribeToMessage(Core::MT_PRERENDER, std::bind(&TristeonEditor::onGui, this)); Core::MessageBus::subscribeToMessage(Core::MT_SHARE_DATA, [&](Core::Message msg) { Core::Rendering::Vulkan::EditorData* data = dynamic_cast<Core::Rendering::Vulkan::EditorData*>(msg.userData); if (data != nullptr) this->editorCamera = data; }); renderable = new Core::Rendering::UIRenderable(); renderable->onRender += [&]() { render(); }; Core::MessageBus::sendMessage(Core::Message(Core::MT_RENDERINGCOMPONENT_REGISTER, renderable)); } void TristeonEditor::createCommandBuffers() { Core::VulkanBindingData* binding = Core::VulkanBindingData::getInstance(); Misc::Console::t_assert(binding != nullptr, "Tristeon editor currently only supports vulkan!"); vk::CommandBufferAllocateInfo alloc = vk::CommandBufferAllocateInfo(binding->commandPool, vk::CommandBufferLevel::eSecondary, 1); vk::Result const r = binding->device.allocateCommandBuffers(&alloc, &cmd); Misc::Console::t_assert(r == vk::Result::eSuccess, "Failed to allocate command buffers: " + to_string(r)); } } #endif
42.078704
152
0.728793
HyperionDH
2f41e4c1d1f0071946aea4c61dff3941058b388f
567
cpp
C++
chap13/Exer13_28_pointer.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
50
2016-01-08T14:28:53.000Z
2022-01-21T12:55:00.000Z
chap13/Exer13_28_pointer.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
2
2017-06-05T16:45:20.000Z
2021-04-17T13:39:24.000Z
chap13/Exer13_28_pointer.cpp
sjbarigye/CPP_Primer
d9d31a73a45ca46909bae104804fc9503ab242f2
[ "Apache-2.0" ]
18
2016-08-17T15:23:51.000Z
2022-03-26T18:08:43.000Z
#include <iostream> #include "Exer13_28_BinStrTree_point.h" using std::cout; using std::endl; int main() { TreeNode t1("t1"); TreeNode t2 = t1; t1.read(cout) << endl; t2.write("t2"); t2.read(cout) << endl; { TreeNode t3(t2); t3.read(cout) << endl; t3.write("t3"); t3.read(cout) << endl;; } TreeNode t4("t4"); TreeNode t5("t5"); t4.read(cout) << endl;; t5.read(cout) << endl; t4 = t4; BinStrTree r1; BinStrTree r2(r1); BinStrTree r3; r3 = r1; r3 = r3; return 0; }
18.9
39
0.527337
sjbarigye
2f46731513ee8207fa214c84ef6cf66b94654967
10,622
cpp
C++
Common/ScenarioTest/Document/ScenarioTest.cpp
testdrive-profiling-master/profiles
6e3854874366530f4e7ae130000000812eda5ff7
[ "BSD-3-Clause" ]
null
null
null
Common/ScenarioTest/Document/ScenarioTest.cpp
testdrive-profiling-master/profiles
6e3854874366530f4e7ae130000000812eda5ff7
[ "BSD-3-Clause" ]
null
null
null
Common/ScenarioTest/Document/ScenarioTest.cpp
testdrive-profiling-master/profiles
6e3854874366530f4e7ae130000000812eda5ff7
[ "BSD-3-Clause" ]
null
null
null
//================================================================================ // Copyright (c) 2013 ~ 2020. HyungKi Jeong(clonextop@gmail.com) // All rights reserved. // // The 3-Clause BSD License (https://opensource.org/licenses/BSD-3-Clause) // // Redistribution and use in source and binary forms, // with or without modification, are permitted provided // that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS // BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY // OF SUCH DAMAGE. // // Title : Scenario test // Rev. : 8/13/2020 Thu (clonextop@gmail.com) //================================================================================ #include "ScenarioTest.h" static CString __sScenarioPath; static CString __sProgramPath; REGISTER_LOCALED_DOCUMENT_EX(ScenarioTest) { CString sName(pDoc->DocumentTitle()); if(!sName.Compare(_T("Scenario Test"))) { // default scenario path pDoc->DocumentTitle(_L(DOCUMENT_TITLE)); __sScenarioPath = _T("%PROJECT%Program\\ScenarioTest"); __sProgramPath = _T("%PROJECT%Program"); return TRUE; } else { // user defined scenario path int iPos = 0; LPCTSTR sDelim = _T(":"); CString sTitle = sName.Tokenize(sDelim, iPos); __sScenarioPath = (iPos > 0) ? sName.Tokenize(sDelim, iPos) : _T("%PROJECT%Program\\ScenarioTest"); __sProgramPath = (iPos > 0) ? sName.Tokenize(sDelim, iPos) : _T("%PROJECT%Program"); sName.Format(_T("%s(%s)"), _L(DOCUMENT_TITLE), (LPCTSTR)sTitle); pDoc->DocumentTitle(sName); return TRUE; } return TRUE; } LPCTSTR g_sTestStatus[TEST_STATUS_SIZE]; ScenarioTest::ScenarioTest(ITDDocument* pDoc) { m_bInitialized = FALSE; m_pDoc = pDoc; m_HtmlTable.Create(pDoc, _T("../media/tables.html"), 0, 0, 100, 100); m_HtmlTable.SetManager(this); m_pHtmlTable = &m_HtmlTable; { // initialize test status string g_sTestStatus[TEST_STATUS_NOT_TESTED] = _L(TEST_STATUS_NOT_TESTED); g_sTestStatus[TEST_STATUS_RUN_PASSED] = _L(TEST_STATUS_RUN_PASSED); g_sTestStatus[TEST_STATUS_RUN_FAILED] = _L(TEST_STATUS_RUN_FAILED); g_sTestStatus[TEST_STATUS_RUN_CRACHED] = _L(TEST_STATUS_RUN_CRACHED); g_sTestStatus[TEST_STATUS_COMPILE_FAILED] = _L(TEST_STATUS_COMPILE_FAILED); g_sTestStatus[TEST_STATUS_LINK_FAILED] = _L(TEST_STATUS_LINK_FAILED); g_sTestStatus[TEST_STATUS_FILE_NOT_FOUND] = _L(TEST_STATUS_FILE_NOT_FOUND); g_sTestStatus[TEST_STATUS_SYSTEM_IS_REQUIRED] = _L(TEST_STATUS_SYSTEM_IS_REQUIRED); g_sTestStatus[TEST_STATUS_SCORE] = _L(TEST_STATUS_SCORE); } { ITDPropertyData* pProperty; pProperty = pDoc->AddPropertyData(PROPERTY_TYPE_STRING, PROPERTY_ID_NAME_FILTER, _L(NAME_FILTER), (DWORD_PTR)((LPCTSTR)m_TestList.TestFilter()), _L(DESC_NAME_FILTER)); pProperty->UpdateConfigFile(); } { m_TimeToday = GetCurrentDayTime(); m_pDoc->SetTimer(COMMAND_ID_REFRESH_TABLE, 1000 * 60 * 60); // every 1 hour, refresh table when day changed } } ScenarioTest::~ScenarioTest(void) { m_pDoc->KillTimer(COMMAND_ID_REFRESH_TABLE); } BOOL ScenarioTest::OnPropertyUpdate(ITDPropertyData* pProperty) { pProperty->UpdateData(); pProperty->UpdateConfigFile(FALSE); switch(pProperty->GetID()) { case PROPERTY_ID_NAME_FILTER: if(m_pDoc->IsLocked()) { g_pSystem->LogWarning(_L(ALREADY_TEST_IS_RUNNING)); } else { m_TestList.Clear(); m_TestList.Refresh(); g_pSystem->LogInfo(_L(LIST_REFRESH_IS_DONE)); } break; default: break; } return TRUE; } void ScenarioTest::OnSize(int width, int height) { if(m_HtmlTable.Control()) { ITDLayout* pLayout; pLayout = m_HtmlTable.Control()->GetObject()->GetLayout(); pLayout->SetSize(width, height); } } BOOL ScenarioTest::OnCommand(DWORD command, WPARAM wParam, LPARAM lParam) { switch(command) { case COMMAND_ID_DO_TEST: m_pDoc->KillTimer(command); if(OnTest()) m_pDoc->SetTimer(command, 0); break; case COMMAND_ID_REFRESH_TABLE: if(!m_pDoc->IsLocked() && (m_TimeToday != GetCurrentDayTime())) { m_TestList.Refresh(); m_TimeToday = GetCurrentDayTime(); } break; default: break; } return FALSE; } LPCTSTR ScenarioTest::OnHtmlBeforeNavigate(DWORD dwID, LPCTSTR lpszURL) { if(m_bInitialized) { if(_tcsstr(lpszURL, _T("group:")) == lpszURL) { int iGroupID; _stscanf(&lpszURL[6], _T("%d"), &iGroupID); StartTest(&lpszURL[6]); } else if(_tcsstr(lpszURL, _T("test:")) == lpszURL) { StartTest(&lpszURL[5], FALSE); } else if(_tcsstr(lpszURL, _T("folder:")) == lpszURL) { TestGroup* pGroup = m_TestList.FindGroup(&lpszURL[7]); if(pGroup) pGroup->OpenFolder(); } else if(_tcsstr(lpszURL, _T("open:")) == lpszURL) { Execute(&lpszURL[5], TRUE); } else if(_tcsstr(lpszURL, _T("execute:")) == lpszURL) { Execute(&lpszURL[8]); } else if(_tcsstr(lpszURL, _T("quit:")) == lpszURL) { g_pSystem->LogWarning(_L(FORCE_TO_QUIT_PROGRAM)); TestVector* pTestVector = TestVector::CurrentTestVecotr(); if(pTestVector) ForceToQuit(pTestVector->Group()->GetConfig(TG_DESC_PROGRAM)); } else if(_tcsstr(lpszURL, _T("refresh:")) == lpszURL) { if(m_pDoc->IsLocked()) { g_pSystem->LogWarning(_L(ALREADY_TEST_IS_RUNNING)); } else { m_TestList.Refresh(); g_pSystem->LogInfo(_L(LIST_REFRESH_IS_DONE)); } } else if(_tcsstr(lpszURL, _T("testall:")) == lpszURL) { if(m_pDoc->IsLocked()) { g_pSystem->LogWarning(_L(ALREADY_TEST_IS_RUNNING)); } else StartTest(); } return NULL; } return lpszURL; } void ScenarioTest::SetLock(BOOL bLock) { if(bLock) { m_HtmlTable.JScript(_T("SetTitle(\"<table class='null0'><tbody><td><button class='ShadowButton'>%s</button></td><td style='text-align:right'></td></tbody></table>\");"), _L(TEST_IN_PROGRESS)); } else { m_HtmlTable.JScript(_T("SetTitle(\"<table class='null0'><tbody><td><a href='testall:'><button class='ShadowButton'>%s</button></a></td><td style='text-align:right'><a href='refresh:'><img class='MiniButton' src='refresh.png' title='%s'></a></td></tbody></table>\");"), _L(TEST_ALL), _L(RESCAN_ALL)); } if(m_bInitialized) { if(bLock) { m_pDoc->Lock(); } else { m_pDoc->UnLock(); } } } void ScenarioTest::OnHtmlDocumentComplete(DWORD dwID, LPCTSTR lpszURL) { if(!m_bInitialized) { m_TestList.Initialize(__sScenarioPath, __sProgramPath); SetLock(FALSE); m_bInitialized = TRUE; } } void ScenarioTest::Execute(LPCTSTR sScript, BOOL bShell) { CString Script(sScript); Script.Replace(_T("/"), _T("\\")); Script.Replace(_T("%20"), _T(" ")); { int iPos = 0; LPCTSTR sDelim = _T("?"); CString sExecuteFile, sArg, sRunPath; sExecuteFile = Script.Tokenize(sDelim, iPos); if(iPos > 0) sArg = Script.Tokenize(sDelim, iPos); if(iPos > 0) sRunPath = Script.Tokenize(sDelim, iPos); if(sRunPath.IsEmpty()) sRunPath = _T("%PROJECT%Program"); sRunPath = g_pSystem->RetrieveFullPath(sRunPath); sExecuteFile = g_pSystem->RetrieveFullPath(sExecuteFile); if(bShell) ShellExecute(NULL, NULL, sExecuteFile, sArg, NULL, SW_SHOW); else g_pSystem->ExecuteFile(sExecuteFile, sArg, TRUE, NULL, sRunPath, _T("*E:"), -1, _T("*I:"), 1, NULL); } } void ScenarioTest::StartTest(LPCTSTR sPath, BOOL bGroup) { if(!sPath) { // add all TestGroup* pGroup = m_TestList.GetNextGroup(); while(pGroup) { TestVector* pVector = pGroup->GetNextVector(); while(pVector) { m_Scenario.push_back(pVector); pVector = pGroup->GetNextVector(pVector); } pGroup = m_TestList.GetNextGroup(pGroup); } } else if(bGroup) { // add group TestGroup* pGroup = m_TestList.FindGroup(sPath); TestVector* pVector = NULL; if(pGroup) pVector = pGroup->GetNextVector(); while(pVector) { m_Scenario.push_back(pVector); pVector = pGroup->GetNextVector(pVector); } } else { // add vector TestVector* pVector = m_TestList.FindVector(sPath); if(pVector) m_Scenario.push_back(pVector); } if(m_Scenario.size() > 1) { SetEnvironmentVariable(_T("SIM_WAVE_MODE"), _T("None")); } { CString sSize; sSize.Format(_T("%d"), m_Scenario.size()); SetEnvironmentVariable(_T("GROUP_TEST_SIZE"), (LPCTSTR)sSize); } if(!m_pDoc->IsLocked()) { m_pDoc->SetTimer(COMMAND_ID_DO_TEST, 0); } else { g_pSystem->LogInfo(_L(ADD_TEST_LIST), sPath); } } BOOL ScenarioTest::OnTest(void) { TestVector* pVector = m_Scenario.front(); if(pVector) { SetLock(); m_Scenario.pop_front(); pVector->DoTest(); m_TestList.UpdateTable(); SetLock(FALSE); } if(!m_Scenario.size()) { ITDDocument* pDoc = g_pSystem->GetDocument(_T("System")); if(pDoc) pDoc->GetImplementation()->OnCommand(TD_EXTERNAL_COMMAND - 1); g_pSystem->LogInfo(_L(TEST_IS_OVER)); return FALSE; } return TRUE; } #include <TlHelp32.h> void ScenarioTest::ForceToQuit(LPCTSTR sFileName) { HANDLE hSnapShot; PROCESSENTRY32 pEntry; hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL); if(hSnapShot == INVALID_HANDLE_VALUE) { return; } pEntry.dwSize = sizeof(pEntry); if(Process32First(hSnapShot, &pEntry)) { do { if(!_tcscmp(pEntry.szExeFile, sFileName)) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pEntry.th32ProcessID); if(hProcess) { if(TerminateProcess(hProcess, 0)) { unsigned long nCode; GetExitCodeProcess(hProcess, &nCode); } CloseHandle(hProcess); } break; } } while(Process32Next(hSnapShot, &pEntry)); } }
28.785908
302
0.695914
testdrive-profiling-master
2f4974d6d95586a9cbf61a1a1bf9c636ea7023a5
11,536
cpp
C++
src/probe_renderer/bruneton_probe_renderer.cpp
Hanggansta/Nimble
291c1bae6308c49f4e86a7ecabc97e9fe8fce654
[ "MIT" ]
null
null
null
src/probe_renderer/bruneton_probe_renderer.cpp
Hanggansta/Nimble
291c1bae6308c49f4e86a7ecabc97e9fe8fce654
[ "MIT" ]
null
null
null
src/probe_renderer/bruneton_probe_renderer.cpp
Hanggansta/Nimble
291c1bae6308c49f4e86a7ecabc97e9fe8fce654
[ "MIT" ]
1
2021-05-09T12:51:18.000Z
2021-05-09T12:51:18.000Z
#include "bruneton_probe_renderer.h" #include "../renderer.h" #include "../resource_manager.h" #include "../logger.h" #define _USE_MATH_DEFINES #include <math.h> #include <gtc/matrix_transform.hpp> namespace nimble { // ----------------------------------------------------------------------------------------------------------------------------------- BrunetonProbeRenderer::BrunetonProbeRenderer() { } // ----------------------------------------------------------------------------------------------------------------------------------- BrunetonProbeRenderer::~BrunetonProbeRenderer() { } // ----------------------------------------------------------------------------------------------------------------------------------- bool BrunetonProbeRenderer::initialize(Renderer* renderer, ResourceManager* res_mgr) { register_float_parameter("Sun Radius", m_sun_angular_radius); register_float_parameter("Exposure", m_exposure); // Values from "Reference Solar Spectral Irradiance: ASTM G-173", ETR column // (see http://rredc.nrel.gov/solar/spectra/am1.5/ASTMG173/ASTMG173.html), // summed and averaged in each bin (e.g. the value for 360nm is the average // of the ASTM G-173 values for all wavelengths between 360 and 370nm). // Values in W.m^-2. int lambda_min = 360; int lambda_max = 830; double kSolarIrradiance[] = { 1.11776, 1.14259, 1.01249, 1.14716, 1.72765, 1.73054, 1.6887, 1.61253, 1.91198, 2.03474, 2.02042, 2.02212, 1.93377, 1.95809, 1.91686, 1.8298, 1.8685, 1.8931, 1.85149, 1.8504, 1.8341, 1.8345, 1.8147, 1.78158, 1.7533, 1.6965, 1.68194, 1.64654, 1.6048, 1.52143, 1.55622, 1.5113, 1.474, 1.4482, 1.41018, 1.36775, 1.34188, 1.31429, 1.28303, 1.26758, 1.2367, 1.2082, 1.18737, 1.14683, 1.12362, 1.1058, 1.07124, 1.04992 }; // Values from http://www.iup.uni-bremen.de/gruppen/molspec/databases/ // referencespectra/o3spectra2011/index.html for 233K, summed and averaged in // each bin (e.g. the value for 360nm is the average of the original values // for all wavelengths between 360 and 370nm). Values in m^2. double kOzoneCrossSection[] = { 1.18e-27, 2.182e-28, 2.818e-28, 6.636e-28, 1.527e-27, 2.763e-27, 5.52e-27, 8.451e-27, 1.582e-26, 2.316e-26, 3.669e-26, 4.924e-26, 7.752e-26, 9.016e-26, 1.48e-25, 1.602e-25, 2.139e-25, 2.755e-25, 3.091e-25, 3.5e-25, 4.266e-25, 4.672e-25, 4.398e-25, 4.701e-25, 5.019e-25, 4.305e-25, 3.74e-25, 3.215e-25, 2.662e-25, 2.238e-25, 1.852e-25, 1.473e-25, 1.209e-25, 9.423e-26, 7.455e-26, 6.566e-26, 5.105e-26, 4.15e-26, 4.228e-26, 3.237e-26, 2.451e-26, 2.801e-26, 2.534e-26, 1.624e-26, 1.465e-26, 2.078e-26, 1.383e-26, 7.105e-27 }; // From https://en.wikipedia.org/wiki/Dobson_unit, in molecules.m^-2. double kDobsonUnit = 2.687e20; // Maximum number density of ozone molecules, in m^-3 (computed so at to get // 300 Dobson units of ozone - for this we divide 300 DU by the integral of // the ozone density profile defined below, which is equal to 15km). double kMaxOzoneNumberDensity = 300.0 * kDobsonUnit / 15000.0; // Wavelength independent solar irradiance "spectrum" (not physically // realistic, but was used in the original implementation). double kConstantSolarIrradiance = 1.5; double kTopRadius = 6420000.0; double kRayleigh = 1.24062e-6; double kRayleighScaleHeight = 8000.0; double kMieScaleHeight = 1200.0; double kMieAngstromAlpha = 0.0; double kMieAngstromBeta = 5.328e-3; double kMieSingleScatteringAlbedo = 0.9; double kMiePhaseFunctionG = 0.8; double kGroundAlbedo = 0.1; double max_sun_zenith_angle = (m_use_half_precision ? 102.0 : 120.0) / 180.0 * M_PI; DensityProfileLayer* rayleigh_layer = new DensityProfileLayer("rayleigh", 0.0, 1.0, -1.0 / kRayleighScaleHeight, 0.0, 0.0); DensityProfileLayer* mie_layer = new DensityProfileLayer("mie", 0.0, 1.0, -1.0 / kMieScaleHeight, 0.0, 0.0); // Density profile increasing linearly from 0 to 1 between 10 and 25km, and // decreasing linearly from 1 to 0 between 25 and 40km. This is an approximate // profile from http://www.kln.ac.lk/science/Chemistry/Teaching_Resources/ // Documents/Introduction%20to%20atmospheric%20chemistry.pdf (page 10). std::vector<DensityProfileLayer*> ozone_density; ozone_density.push_back(new DensityProfileLayer("absorption0", 25000.0, 0.0, 0.0, 1.0 / 15000.0, -2.0 / 3.0)); ozone_density.push_back(new DensityProfileLayer("absorption1", 0.0, 0.0, 0.0, -1.0 / 15000.0, 8.0 / 3.0)); std::vector<double> wavelengths; std::vector<double> solar_irradiance; std::vector<double> rayleigh_scattering; std::vector<double> mie_scattering; std::vector<double> mie_extinction; std::vector<double> absorption_extinction; std::vector<double> ground_albedo; for (int l = lambda_min; l <= lambda_max; l += 10) { double lambda = l * 1e-3; // micro-meters double mie = kMieAngstromBeta / kMieScaleHeight * pow(lambda, -kMieAngstromAlpha); wavelengths.push_back(l); if (m_use_constant_solar_spectrum) solar_irradiance.push_back(kConstantSolarIrradiance); else solar_irradiance.push_back(kSolarIrradiance[(l - lambda_min) / 10]); rayleigh_scattering.push_back(kRayleigh * pow(lambda, -4)); mie_scattering.push_back(mie * kMieSingleScatteringAlbedo); mie_extinction.push_back(mie); absorption_extinction.push_back(m_use_ozone ? kMaxOzoneNumberDensity * kOzoneCrossSection[(l - lambda_min) / 10] : 0.0); ground_albedo.push_back(kGroundAlbedo); } m_sky_model.m_half_precision = m_use_half_precision; m_sky_model.m_combine_scattering_textures = m_use_combined_textures; m_sky_model.m_use_luminance = m_use_luminance; m_sky_model.m_wave_lengths = wavelengths; m_sky_model.m_solar_irradiance = solar_irradiance; m_sky_model.m_sun_angular_radius = m_sun_angular_radius; m_sky_model.m_bottom_radius = m_bottom_radius; m_sky_model.m_top_radius = kTopRadius; m_sky_model.m_rayleigh_density = rayleigh_layer; m_sky_model.m_rayleigh_scattering = rayleigh_scattering; m_sky_model.m_mie_density = mie_layer; m_sky_model.m_mie_scattering = mie_scattering; m_sky_model.m_mie_extinction = mie_extinction; m_sky_model.m_mie_phase_function_g = kMiePhaseFunctionG; m_sky_model.m_absorption_density = ozone_density; m_sky_model.m_absorption_extinction = absorption_extinction; m_sky_model.m_ground_albedo = ground_albedo; m_sky_model.m_max_sun_zenith_angle = max_sun_zenith_angle; m_sky_model.m_length_unit_in_meters = m_length_unit_in_meters; int num_scattering_orders = 4; bool status = m_sky_model.initialize(num_scattering_orders, renderer, res_mgr); glm::mat4 capture_projection = glm::perspective(glm::radians(90.0f), 1.0f, 0.1f, 10.0f); glm::mat4 capture_views[] = { glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)), glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)), glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f)), glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f)), glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f, -1.0f, 0.0f)), glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f), glm::vec3(0.0f, -1.0f, 0.0f)) }; for (int i = 0; i < 6; i++) m_cubemap_views[i] = capture_projection * capture_views[i]; m_sun_dir = glm::vec3(0.0f); std::vector<std::string> defines; if (m_use_luminance == LUMINANCE::NONE) defines.push_back("RADIANCE_API_ENABLED"); if (m_use_combined_textures) defines.push_back("COMBINED_SCATTERING_TEXTURES"); m_env_map_vs = res_mgr->load_shader("shader/bruneton_sky_model/env_map_vs.glsl", GL_VERTEX_SHADER, defines); m_env_map_fs = res_mgr->load_shader("shader/bruneton_sky_model/env_map_fs.glsl", GL_FRAGMENT_SHADER, defines); if (m_env_map_vs && m_env_map_fs) { m_env_map_program = renderer->create_program(m_env_map_vs, m_env_map_fs); if (!m_env_map_program) { NIMBLE_LOG_ERROR("Failed to create program"); return false; } } else { NIMBLE_LOG_ERROR("Failed to load shaders"); return false; } return status; } // ----------------------------------------------------------------------------------------------------------------------------------- void BrunetonProbeRenderer::env_map(double delta, Renderer* renderer, Scene* scene) { uint32_t num_lights = scene->directional_light_count(); DirectionalLight* lights = scene->directional_lights(); if (num_lights > 0) { DirectionalLight& light = lights[0]; glm::vec3 sun_dir = light.transform.forward(); if (m_sun_dir != sun_dir) { m_sun_dir = sun_dir; for (int i = 0; i < 6; i++) m_cubemap_rtv[i] = RenderTargetView(i, 0, 0, scene->env_map()); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); m_env_map_program->use(); m_sky_model.bind_rendering_uniforms(m_env_map_program.get()); m_env_map_program->set_uniform("sun_size", glm::vec2(tan(m_sun_angular_radius), cos(m_sun_angular_radius))); m_env_map_program->set_uniform("sun_direction", -light.transform.forward()); m_env_map_program->set_uniform("earth_center", glm::vec3(0.0f, -m_bottom_radius / m_length_unit_in_meters, 0.0f)); m_env_map_program->set_uniform("exposure", m_exposure); for (int i = 0; i < 6; i++) { m_env_map_program->set_uniform("view_projection", m_cubemap_views[i]); renderer->bind_render_targets(1, &m_cubemap_rtv[i], nullptr); glViewport(0, 0, ENVIRONMENT_MAP_SIZE, ENVIRONMENT_MAP_SIZE); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); renderer->cube_vao()->bind(); glDrawArrays(GL_TRIANGLES, 0, 36); } } } } // ----------------------------------------------------------------------------------------------------------------------------------- void BrunetonProbeRenderer::diffuse(double delta, Renderer* renderer, Scene* scene) { } // ----------------------------------------------------------------------------------------------------------------------------------- void BrunetonProbeRenderer::specular(double delta, Renderer* renderer, Scene* scene) { } // ----------------------------------------------------------------------------------------------------------------------------------- std::string BrunetonProbeRenderer::probe_contribution_shader_path() { return ""; } // ----------------------------------------------------------------------------------------------------------------------------------- } // namespace nimble
46.704453
527
0.59492
Hanggansta
2f4c96320cf49fba14bc658832b4d561c921f50e
480
cpp
C++
BASIC c++/inheritance/use _OF_protected.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
BASIC c++/inheritance/use _OF_protected.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
BASIC c++/inheritance/use _OF_protected.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; //base class class shape{ protected: int width; int height; public: void setwidth(int w) { width=w; } void setheight(int h) { height=h; } }; //drived class class rectangle:public shape { public: int get_area(){ return (width*height); } }; int main() { rectangle rect; rect.setwidth(5); rect.setheight(7); cout<<"total area :"<<rect.get_area()<<endl; }
14.117647
48
0.572917
jattramesh
2f515c43df3d33da482c89eb87ec4ec7fecec030
1,405
cpp
C++
Kattis/ummcode.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
3
2021-02-19T17:01:11.000Z
2021-03-11T16:50:19.000Z
Kattis/ummcode.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
null
null
null
Kattis/ummcode.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
null
null
null
// // https://open.kattis.com/problems/ummcode #include <vector> #include <algorithm> #include <iostream> #include <sstream> #include <string> #include <stack> #include <cmath> #include <map> #include <utility> #include <queue> #include <iomanip> #include <deque> #include <set> #define Forcase int __t;cin>>__t;for(int cases=1;cases<=__t;cases++) #define For(i, n) for(int i=0;i<n;i++) #define Fore(e, arr) for(auto e:arr) #define INF 1e9 #define LINF 1e18 #define EPS 1e-9 using ull = unsigned long long; using ll = long long; using namespace std; bool um(string& s) { Fore (c, s) { if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')) { if (c != 'm' && c != 'u') return false; } } return true; } int main() { // ios_base::sync_with_stdio(false); // cin.tie(NULL); // cout.tie(NULL); string s, str; getline(cin, s); stringstream ss; ss << s; while (ss >> s) { if (um(s)) { str += s; } } string real; Fore (c, str) { if (c == 'm' || c == 'u') real += c; } for (int i = 0; i < real.size(); i += 7) { char c = 0; for (int j = i; j < i + 7; j++) { c *= 2; if (real[j] == 'u') { c++; } } cout << c; } cout << '\n'; //cout << real << ' ' << str << '\n'; return 0; }
19.246575
68
0.472598
YourName0729
016d09b9894428db9518336c24de38bfe10ec957
611
cpp
C++
neps/cursos/codcad/tecnicas/basicas/busca_binaria/casas.cpp
homembaixinho/codeforces
9394eaf383afedacdfe86ca48609425b14f84bdb
[ "MIT" ]
null
null
null
neps/cursos/codcad/tecnicas/basicas/busca_binaria/casas.cpp
homembaixinho/codeforces
9394eaf383afedacdfe86ca48609425b14f84bdb
[ "MIT" ]
null
null
null
neps/cursos/codcad/tecnicas/basicas/busca_binaria/casas.cpp
homembaixinho/codeforces
9394eaf383afedacdfe86ca48609425b14f84bdb
[ "MIT" ]
null
null
null
// Soma de Casas // https://neps.academy/lesson/173 #include <iostream> using namespace std; #define MAXN 100000 int N, K, casas[MAXN]; int busca(int x) { int ini=0, fim=N-1, meio; while (ini<=fim) { meio = (ini+fim)/2; if (casas[meio] > x) fim = meio-1; if (casas[meio] < x) ini = meio+1; if (casas[meio] == x) return true; } return false; } int main() { cin >> N; for (int i = 0; i < N; i++) cin >> casas[i]; cin >> K; for (int i = 0; i < N; i++) { if (busca(K-casas[i])) { cout << casas[i] << ' ' << K-casas[i] << endl; break; } } return 0; }
16.078947
52
0.513912
homembaixinho
016ebe407f7707d1008e404dfdf8d8e80e371d03
2,808
cpp
C++
Turtlebot_Car4D_Car1D_Overtake/Reachability Computation/add_lane_disturbance_v2.cpp
karenl7/stlhj
c3f35aefe81e2f6c721e4723ba4d07930b2661e7
[ "MIT" ]
6
2019-01-30T00:11:55.000Z
2022-03-09T02:44:51.000Z
Turtlebot_Car4D_Car1D_Overtake/Reachability Computation/add_lane_disturbance_v2.cpp
StanfordASL/stlhj
c3f35aefe81e2f6c721e4723ba4d07930b2661e7
[ "MIT" ]
null
null
null
Turtlebot_Car4D_Car1D_Overtake/Reachability Computation/add_lane_disturbance_v2.cpp
StanfordASL/stlhj
c3f35aefe81e2f6c721e4723ba4d07930b2661e7
[ "MIT" ]
4
2018-09-08T00:16:55.000Z
2022-03-09T02:44:54.000Z
void add_lane_disturbance_v2( beacls::FloatVec& lane, const std::vector<size_t> shape, beacls::FloatVec range, beacls::FloatVec gmin, beacls::FloatVec gmax, FLOAT_TYPE vehicle_width, FLOAT_TYPE fill_Value, size_t dim){ FLOAT_TYPE x_unit = (static_cast<float>(shape[0])-1)/(gmax[0]-gmin[0]); FLOAT_TYPE y_unit = (static_cast<float>(shape[1])-1)/(gmax[1]-gmin[1]); FLOAT_TYPE b_unit = (static_cast<float>(shape[4])-1)/(gmax[4]-gmin[4]); long unsigned int x1 = (long unsigned int)(x_unit*(range[0]-gmin[0])+0.5); long unsigned int x2 = (long unsigned int)(x_unit*(range[1]-gmin[0])+0.5); beacls::IntegerVec x_index{x1,x2}; long unsigned int y1 = (long unsigned int)(y_unit*(range[2]-gmin[1])+0.5); long unsigned int y2 = (long unsigned int)(y_unit*(range[3]-gmin[1])+0.5); beacls::IntegerVec y_index{y1,y2}; long unsigned int x_size, y_size, z_size, a_size, b_size, y, z, a, b, b2y, yz_unit; FLOAT_TYPE y_add = (y_unit*vehicle_width); FLOAT_TYPE x_add = (x_unit*vehicle_width); beacls::IntegerVec n; x_size = x2-x1+1; y_size = y2-y1+1; z_size = shape[2]; a_size = shape[3]; b_size = shape[4]; // printf("x_size: %lu\n", x_size); // printf("y_size: %lu\n", y_size); beacls::IntegerVec b2y_index; beacls::IntegerVec y_addvec{0,0}; beacls::IntegerVec x_addvec{(long unsigned int)((static_cast<float>(x_size)-1.)/2.-x_add+0.5),(long unsigned int)((static_cast<float>(x_size)-1.)/2.+x_add+0.5)}; beacls::IntegerVec b_addvec{(long unsigned int)((range[2]-gmin[4])*b_unit+0.5),(long unsigned int)((range[3]-gmin[4])*b_unit+0.5)}; // printf("b_addvec: %lu\n", b_addvec[0]); // printf("b_addvec: %lu\n", b_addvec[1]); b_addvec[1] = b_addvec[1]; FLOAT_TYPE by_unit = 1.;//static_cast<float>(b_addvec[1]-b_addvec[0]+1)/y_size; for (b = b_addvec[0]; b < b_addvec[1]+1; ++b) { for (a = 0; a < a_size; ++a) { for (z = 0; z < z_size; ++z) { y_addvec[0] = (long unsigned int)((b-b_addvec[0])/by_unit-y_add+0.5); y_addvec[1] = (long unsigned int)((b-b_addvec[0])/by_unit+y_add+0.5); // printf("y_addvec: %lu\n", y_addvec[0]); // printf("y_addvec: %lu\n", y_addvec[1]); if (y_addvec[0]<0 || y_addvec[0]>1000){ y_addvec[0] = 0; } if (y_addvec[1]>y_size-1){ y_addvec[1] = y_size-1; } for (y = y_addvec[0]; y < y_addvec[1]+1; ++y){ n = {b*a_size*z_size*y_size*x_size + a*z_size*y_size*x_size + z*y_size*x_size + y*x_size + x_addvec[0], b*a_size*z_size*y_size*x_size + a*z_size*y_size*x_size + z*y_size*x_size + y*x_size + x_addvec[1]}; std::fill(lane.begin()+n[0],lane.begin()+n[1]+1,fill_Value); } } } } }
40.114286
215
0.603276
karenl7
01711e943bc73ff5e41c51c8f7030c4bafda1b67
7,173
cpp
C++
src_legacy/2018/test/test_PlayFramesAction.cpp
gmoehler/ledpoi
d1294b172b7069f62119c310399d80500402d882
[ "MIT" ]
null
null
null
src_legacy/2018/test/test_PlayFramesAction.cpp
gmoehler/ledpoi
d1294b172b7069f62119c310399d80500402d882
[ "MIT" ]
75
2017-05-28T23:39:33.000Z
2019-05-09T06:18:44.000Z
src_legacy/2018/test/test_PlayFramesAction.cpp
gmoehler/ledpoi
d1294b172b7069f62119c310399d80500402d882
[ "MIT" ]
null
null
null
#include "test.h" #include "player/PlayFramesAction.h" TEST(playFramesAction_tests, afterDeclaration){ PlayFramesAction playFramesAction; playFramesAction.printInfo("pre:"); EXPECT_FALSE(playFramesAction.isActive()); } TEST(playFramesAction_tests, afterInit){ PlayFramesAction playFramesAction; RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 10, 50, 3, 0, 100}}; PixelFrame sframe; ActionOptions options; playFramesAction.init(rawCmd0, &sframe, options); EXPECT_TRUE(playFramesAction.isActive( )); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 10); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); } TEST(playFramesAction_tests, printStateForStaticFrame){ PlayFramesAction playFramesAction; RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 10, 10, 1, 0, 100}}; PixelFrame sframe; ActionOptions options; playFramesAction.init(rawCmd0, &sframe, options); playFramesAction.printInfo("pre:"); EXPECT_TRUE(playFramesAction.isActive()); EXPECT_STREQ(playFramesAction.getActionName(), "Play Frame"); } TEST(playFramesAction_tests, wrongAaction){ PlayFramesAction playFramesAction; RawPoiCommand rawCmd0 = {{ANIMATE, 10, 50, 3, 0, 100}}; PixelFrame sframe; ActionOptions options; playFramesAction.init(rawCmd0, &sframe, options); } TEST(playFramesAction_tests, testNext){ PlayFramesAction playFramesAction; RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 10, 12, 3, 0, 100}}; PixelFrame sframe; ActionOptions options; playFramesAction.init(rawCmd0, &sframe, options); EXPECT_FALSE(sframe.isLastFrame); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 10); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); playFramesAction.next(); playFramesAction.printState(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 11); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 12); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 10); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 1); } TEST(playFramesAction_tests, testNextWithPixelFrame){ // 3 frames: red, blue, green for (int p=0; p<N_PIXELS; p++){ imageCache.setPixel(0, p, RED); } for (int p=0; p<N_PIXELS; p++){ imageCache.setPixel(1, p, BLUE); } for (int p=0; p<N_PIXELS; p++){ imageCache.setPixel(2 ,p, GREEN); } PixelFrame sframe; RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 0, 4, 3, 0, 100}}; PlayFramesAction playFramesAction; ActionOptions options; playFramesAction.init(rawCmd0, &sframe, options); // test the first 3 frames EXPECT_EQ(playFramesAction.__getCurrentFrame(), 0); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); rgbVal rgb0 = sframe.pixel[0]; EXPECT_EQ(rgb0.r, 254); EXPECT_EQ(rgb0.g, 0); EXPECT_EQ(rgb0.b, 0); playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 1); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); rgb0 = sframe.pixel[0]; EXPECT_EQ(rgb0.r, 0); EXPECT_EQ(rgb0.g, 0); EXPECT_EQ(rgb0.b, 254); playFramesAction.setDimFactor(0.1); playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 2); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); rgb0 = sframe.pixel[0]; EXPECT_EQ(rgb0.r, 0); EXPECT_EQ(rgb0.g, 25); // 254/10 EXPECT_EQ(rgb0.b, 0); playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 3); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); EXPECT_EQ(rgb0.r, 0); } TEST(playFramesAction_tests, testWithDimFactor){ // 3 frames: red, blue, green for (int p=0; p<N_PIXELS; p++){ imageCache.setPixel(0, p, RED); } for (int p=0; p<N_PIXELS; p++){ imageCache.setPixel(1, p, BLUE); } for (int p=0; p<N_PIXELS; p++){ imageCache.setPixel(2 ,p, GREEN); } PixelFrame sframe; RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 0, 4, 3, 0, 100}}; PlayFramesAction playFramesAction; ActionOptions options; options.dimFactor = 0.1; playFramesAction.init(rawCmd0, &sframe, options); playFramesAction.printInfo(""); // test the first 3 frames EXPECT_EQ(playFramesAction.__getCurrentFrame(), 0); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); rgbVal rgb0 = sframe.pixel[0]; EXPECT_EQ(rgb0.r, 25); // 254/10 EXPECT_EQ(rgb0.g, 0); EXPECT_EQ(rgb0.b, 0); playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 1); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); rgb0 = sframe.pixel[0]; EXPECT_EQ(rgb0.r, 0); EXPECT_EQ(rgb0.g, 0); EXPECT_EQ(rgb0.b, 25); // 254/10 playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 2); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); rgb0 = sframe.pixel[0]; EXPECT_EQ(rgb0.r, 0); EXPECT_EQ(rgb0.g, 25); // 254/10 EXPECT_EQ(rgb0.b, 0); playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 3); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); EXPECT_EQ(rgb0.r, 0); } TEST(playFramesAction_tests, testFinishedAbstract){ PixelFrame sframe; RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 10, 12, 3, 0, 100}}; PlayFramesAction playFramesAction; ActionOptions options; playFramesAction.init(rawCmd0, &sframe, options); AbstractAction *a = dynamic_cast<AbstractAction*>(&playFramesAction); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 10); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); EXPECT_FALSE(sframe.isLastFrame); for (int i=0; i<3*3-2; i++) { a->next(); EXPECT_FALSE(sframe.isLastFrame); } // last iteration a->next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 12); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 2); EXPECT_TRUE(playFramesAction.isActive()); EXPECT_FALSE(sframe.isLastFrame); // finished a->next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 12); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 2); EXPECT_FALSE(playFramesAction.isActive()); EXPECT_TRUE(sframe.isLastFrame); } TEST(playFramesAction_tests, testBackwardComplete){ PixelFrame sframe; RawPoiCommand rawCmd0 = {{PLAY_FRAMES, 12, 10, 3, 0, 100}}; PlayFramesAction playFramesAction; ActionOptions options; EXPECT_FALSE(playFramesAction.isActive()); playFramesAction.init(rawCmd0, &sframe, options); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 12); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 11); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 0); EXPECT_FALSE(sframe.isLastFrame); for (int i=0; i<3*3-3; i++) { playFramesAction.next(); EXPECT_FALSE(sframe.isLastFrame); } // last iteration playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 10); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 2); EXPECT_TRUE(playFramesAction.isActive()); EXPECT_FALSE(sframe.isLastFrame); // finished playFramesAction.next(); EXPECT_EQ(playFramesAction.__getCurrentFrame(), 10); EXPECT_EQ(playFramesAction.__getCurrentLoop(), 2); EXPECT_FALSE(playFramesAction.isActive()); EXPECT_TRUE(sframe.isLastFrame); }
29.763485
71
0.732748
gmoehler
01715332cdd82763d0e23ef996bb901ffbd4d0c7
16,727
cpp
C++
jani/inspector/ui/BaseWindow.cpp
RodrigoHolztrattner/JANI
cd8794a9826645ecf4ccf4cbd331bd6db2f1b2c8
[ "MIT" ]
null
null
null
jani/inspector/ui/BaseWindow.cpp
RodrigoHolztrattner/JANI
cd8794a9826645ecf4ccf4cbd331bd6db2f1b2c8
[ "MIT" ]
null
null
null
jani/inspector/ui/BaseWindow.cpp
RodrigoHolztrattner/JANI
cd8794a9826645ecf4ccf4cbd331bd6db2f1b2c8
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Filename: BaseWindow.cpp //////////////////////////////////////////////////////////////////////////////// #include "BaseWindow.h" #include "imgui.h" #include "..\imgui_extension.h" Jani::Inspector::BaseWindow::BaseWindow(InspectorManager& _inspector_manager, const std::string _window_type_name) : m_inspector_manager(_inspector_manager) { static WindowId unique_index_counter = 0; m_unique_id = unique_index_counter++; m_name = _window_type_name; m_unique_name = _window_type_name + "###" + std::to_string(m_unique_id); } Jani::Inspector::BaseWindow::~BaseWindow() { RemoveAllInputWindowConnections(*this); RemoveAllOutputWindowConnections(*this); } void Jani::Inspector::BaseWindow::PreUpdate() { m_updated = false; } void Jani::Inspector::BaseWindow::Update() { m_updated = true; } void Jani::Inspector::BaseWindow::Draw( const CellsInfos& _cell_infos, const WorkersInfos& _workers_infos) { } void Jani::Inspector::BaseWindow::DrawConnections() { auto DrawConnection = [](ImVec2 _from, ImVec2 _to, ImColor _color) -> void { ImVec2 lenght = ImVec2(_to.x - _from.x, _to.y - _from.y); float factor_from_points = std::sqrt(std::pow(lenght.x, 2) + std::pow(lenght.y, 2)) / 2.0f; auto pos0 = _from; auto cp0 = ImVec2(_from.x - factor_from_points, _from.y); auto cp1 = ImVec2(_to.x + factor_from_points, _to.y); auto pos1 = _to; ImGui::GetForegroundDrawList()->AddBezierCurve( pos0, cp0, cp1, pos1, _color, 2); }; auto GetColorForDataType = [](WindowDataType _data_type) -> ImColor { switch (_data_type) { case WindowDataType::EntityData: { return ImColor(ImVec4(0.9f, 0.3f, 0.3f, 1.0f)); } case WindowDataType::EntityId: { return ImColor(ImVec4(0.3f, 0.9f, 0.3f, 1.0f)); } case WindowDataType::Constraint: { return ImColor(ImVec4(0.3f, 0.3f, 0.9f, 1.0f)); } case WindowDataType::Position: { return ImColor(ImVec4(0.7f, 0.9f, 0.3f, 1.0f)); } case WindowDataType::VisualizationSettings: { return ImColor(ImVec4(0.3f, 0.7f, 0.9f, 1.0f)); } default: { return ImColor(ImVec4(0.9f, 0.9f, 0.9f, 1.0f)); } } }; for (int i = 0; i < m_output_connections.size(); i++) { auto& output_connection_info = m_output_connections[i]; for (auto& [window_id, window] : output_connection_info) { DrawConnection(m_outputs_position, window->GetConnectionInputPosition(), GetColorForDataType(magic_enum::enum_value<WindowDataType>(i))); } } if (m_receiving_connection) { DrawConnection(m_receiving_connection->window->GetConnectionOutputPosition(), m_inputs_position, GetColorForDataType(m_receiving_connection->data_type)); } if (m_creating_connection_payload) { DrawConnection(m_outputs_position, ImGui::GetMousePos(), GetColorForDataType(m_creating_connection_payload->data_type)); } } bool Jani::Inspector::BaseWindow::CanAcceptInputConnection(const WindowInputConnection& _connection) { return false; } std::optional<Jani::Inspector::WindowInputConnection> Jani::Inspector::BaseWindow::DrawOutputOptions(ImVec2 _button_size) { return std::nullopt; } Jani::Inspector::WindowDataType Jani::Inspector::BaseWindow::GetInputTypes() const { return WindowDataType::None; } Jani::Inspector::WindowDataType Jani::Inspector::BaseWindow::GetOutputTypes() const { return WindowDataType::None; } std::optional<std::unordered_map<Jani::EntityId, Jani::Inspector::EntityData>> Jani::Inspector::BaseWindow::GetOutputEntityData() const { return std::nullopt; } std::optional<std::vector<Jani::EntityId>> Jani::Inspector::BaseWindow::GetOutputEntityId() const { return std::nullopt; } std::optional<std::vector<std::shared_ptr<Jani::Inspector::Constraint>>> Jani::Inspector::BaseWindow::GetOutputConstraint() const { return std::nullopt; } std::optional<std::vector<Jani::WorldPosition>> Jani::Inspector::BaseWindow::GetOutputPosition() const { return std::nullopt; } std::optional<Jani::Inspector::VisualizationSettings> Jani::Inspector::BaseWindow::GetOutputVisualizationSettings() const { return std::nullopt; } void Jani::Inspector::BaseWindow::OnPositionChange(ImVec2 _current_pos, ImVec2 _new_pos, ImVec2 _delta) { /* stub */ } void Jani::Inspector::BaseWindow::OnSizeChange(ImVec2 _current_size, ImVec2 _new_size, ImVec2 _delta) { /* stub */ } Jani::Inspector::WindowId Jani::Inspector::BaseWindow::GetId() const { return m_unique_id; } bool Jani::Inspector::BaseWindow::WasUpdated() const { return m_updated; } ImVec2 Jani::Inspector::BaseWindow::GetWindowPos() const { return m_window_pos; } ImVec2 Jani::Inspector::BaseWindow::GetWindowSize() const { return m_is_visible ? m_window_size : ImVec2(m_window_size.x, m_header_height); } const std::string Jani::Inspector::BaseWindow::GetUniqueName() const { return m_unique_name; } bool Jani::Inspector::BaseWindow::IsVisible() const { return m_is_visible; } void Jani::Inspector::BaseWindow::DrawTitleBar(bool _edit_mode, std::optional<WindowInputConnection> _connection) { ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.25f, 0.25f, 0.25f, 1.0f)); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); if (ImGui::BeginChild("Title Bar", ImVec2(ImGui::GetWindowSize().x, m_header_height), false, ImGuiWindowFlags_NoDecoration)) { if (ImGui::IsMouseClicked(0) && ImGui::IsWindowHovered()) { m_is_moving = true; } ImGui::AlignTextToFramePadding(); ImGui::SetCursorPos(ImVec2(ImGui::GetCursorPos().x + 5.0f, ImGui::GetCursorPos().y)); if (ImGui::Button("#")) { m_is_visible = !m_is_visible; } ImGui::SameLine(); ImGui::Text(m_name.c_str()); ImGui::SameLine(); ImVec2 current_cursor_pos = ImGui::GetCursorPos(); float remaining_width = ImGui::GetWindowSize().x; float options_button_size = ImGui::CalcTextSize("*").x + 20.0f; float input_button_size = ImGui::CalcTextSize("+ INPUT").x + 5.0f; float output_button_size = ImGui::CalcTextSize("- OUTPUT").x + 10.0f; float input_button_begin = remaining_width - (options_button_size + input_button_size + output_button_size); float output_button_begin = remaining_width - (options_button_size + output_button_size); float options_button_begin = remaining_width - options_button_size; if (_edit_mode) { ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.3f, 0.3f, 0.3f, 1.0f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.5f, 0.5f, 0.5f, 1.0f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.4f, 0.4f, 0.4f, 1.0f)); ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 2.0f); ImGui::SetWindowFontScale(0.7f); ImGui::SetCursorPos(ImVec2(input_button_begin, current_cursor_pos.y + 3.0f)); m_inputs_position = ImGui::GetCursorScreenPos(); if (_connection && (_connection->window == this || !CanAcceptInputConnection(_connection.value()))) { ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f); } ImGui::Button("+ INPUT"); if (_connection && (_connection->window == this || !CanAcceptInputConnection(_connection.value()))) { ImGui::PopItemFlag(); ImGui::PopStyleVar(); } if (ImGui::IsItemHovered() && ImGui::IsMouseReleased(0) && _connection && _connection->window != this && !ImGui::GetIO().KeyCtrl) { m_receiving_connection = _connection; ImGui::OpenPopup("Input Popup"); } if (ImGui::IsItemHovered() && ImGui::IsMouseClicked(0) && ImGui::GetIO().KeyCtrl) { RemoveAllInputWindowConnections(*this); } m_inputs_position = m_inputs_position + ImVec2(ImGui::GetItemRectSize().x / 2.0f, ImGui::GetItemRectSize().y / 2.0f); ImGui::SameLine(); ImGui::SetCursorPos(ImVec2(output_button_begin, current_cursor_pos.y + 3.0f)); m_outputs_position = ImGui::GetCursorScreenPos(); if (_connection) { ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f); } if (ImGui::Button("- OUTPUT")) { ImGui::OpenPopup("Output Popup"); } if (ImGui::IsItemHovered() && ImGui::IsMouseClicked(0) && ImGui::GetIO().KeyCtrl) { RemoveAllOutputWindowConnections(*this); } if (_connection) { ImGui::PopItemFlag(); ImGui::PopStyleVar(); } m_outputs_position = m_outputs_position + ImVec2(ImGui::GetItemRectSize().x / 2.0f, ImGui::GetItemRectSize().y / 2.0f); ImGui::SetWindowFontScale(1.0f); ImGui::PopStyleVar(); ImGui::PopStyleColor(3); ImGui::SameLine(); } ImGui::SetCursorPos(ImVec2(options_button_begin, current_cursor_pos.y)); if (ImGui::Button("*")) { } ImGui::NewLine(); if (ImGui::BeginPopup("Input Popup") && m_receiving_connection) { if (CanAcceptInputConnection(m_receiving_connection.value())) { AddWindowConnection(*m_receiving_connection->window, *this, m_receiving_connection->data_type, m_receiving_connection->connection_type); ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } else { m_receiving_connection = std::nullopt; } if (ImGui::BeginPopup("Output Popup")) { auto creating_connection_payload = DrawOutputOptions(ImVec2(200.0f, 30.0f)); if (creating_connection_payload) { m_creating_connection_payload = creating_connection_payload; ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } } ImGui::EndChild(); ImGui::PopStyleVar(); ImGui::PopStyleColor(); if (!ImGui::IsMouseDown(0)) { m_is_moving = false; } if (m_is_moving) { auto IO = ImGui::GetIO(); OnPositionChange(ImGui::GetWindowPos(), ImGui::GetWindowPos() + IO.MouseDelta, IO.MouseDelta); m_window_pos = ImVec2(ImGui::GetWindowPos().x + IO.MouseDelta.x, ImGui::GetWindowPos().y + IO.MouseDelta.y); } } void Jani::Inspector::BaseWindow::ProcessResize() { if (ImGui::IsMouseClicked(0) && ImGui::IsWindowHovered()) { float resize_bar_length = 10.0f; auto mouse_position = ImGui::GetMousePos(); auto left_pos_diff = mouse_position.x - m_window_pos.x; auto top_pos_diff = mouse_position.y - m_window_pos.y; auto right_pos_diff = (m_window_pos.x + m_window_size.x) - mouse_position.x; auto bottom_pos_diff = (m_window_pos.y + m_window_size.y) - mouse_position.y; if (left_pos_diff > 0.f && left_pos_diff < resize_bar_length) { m_is_resizing[0] = true; } if (top_pos_diff > 0.f && top_pos_diff < resize_bar_length) { // m_is_resizing[1] = true; } if (right_pos_diff > 0.f && right_pos_diff < resize_bar_length) { m_is_resizing[2] = true; } if (bottom_pos_diff > 0.f && bottom_pos_diff < resize_bar_length) { m_is_resizing[3] = true; } } if (!ImGui::IsMouseDown(0)) { m_is_resizing[0] = false; m_is_resizing[1] = false; m_is_resizing[2] = false; m_is_resizing[3] = false; } /* if (m_is_resizing[0]) { OnSizeChange(m_window_size, m_window_size - ImVec2(ImGui::GetIO().MouseDelta.x, 0.0f), ImVec2(-ImGui::GetIO().MouseDelta.x, 0.0f)); m_window_pos.x += ImGui::GetIO().MouseDelta.x; m_window_size.x -= ImGui::GetIO().MouseDelta.x; } */ /* if (m_is_resizing[1]) { m_window_pos.y -= ImGui::GetIO().MouseDelta.y; m_window_size.y += ImGui::GetIO().MouseDelta.y; } */ if (m_is_resizing[2]) { OnSizeChange(m_window_size, m_window_size + ImVec2(ImGui::GetIO().MouseDelta.x, 0.0f), ImVec2(ImGui::GetIO().MouseDelta.x, 0.0f)); m_window_size.x += ImGui::GetIO().MouseDelta.x; } if (m_is_resizing[3]) { OnSizeChange(m_window_size, m_window_size + ImVec2(0.0f, ImGui::GetIO().MouseDelta.y), ImVec2(0.0f, ImGui::GetIO().MouseDelta.y)); m_window_size.y += ImGui::GetIO().MouseDelta.y; } } ImVec2 Jani::Inspector::BaseWindow::GetConnectionInputPosition() const { return m_inputs_position; } ImVec2 Jani::Inspector::BaseWindow::GetConnectionOutputPosition() const { return m_outputs_position; } std::optional<Jani::Inspector::WindowInputConnection> Jani::Inspector::BaseWindow::GetCreatingConnectionPayload() const { return m_creating_connection_payload; } void Jani::Inspector::BaseWindow::ResetIsCreatingConnection() { m_creating_connection_payload = std::nullopt; } bool Jani::Inspector::BaseWindow::AddWindowConnection(BaseWindow& _from, BaseWindow& _to, WindowDataType _data_type, WindowConnectionType _connection_type) { auto data_enum_index = magic_enum::enum_index(_data_type); if (!data_enum_index) { return false; } if (IsConnectedRecursively(_to, _from)) { return false; } if (_to.m_input_connections[data_enum_index.value()] != std::nullopt || _from.m_output_connections[data_enum_index.value()].find(_to.GetId()) != _from.m_output_connections[data_enum_index.value()].end()) { return false; } _to.m_input_connections[data_enum_index.value()] = { &_from, _data_type, _connection_type }; _from.m_output_connections[data_enum_index.value()].insert({ _to.GetId(),&_to }); return true; } bool Jani::Inspector::BaseWindow::IsConnectedRecursively(BaseWindow& _current_window, BaseWindow& _target) { for (auto& output_connections : _current_window.m_output_connections) { for (auto& [window_id, window] : output_connections) { if (window_id == _target.GetId()) { return true; } if (IsConnectedRecursively(*window, _target)) { return true; } } } return false; } bool Jani::Inspector::BaseWindow::RemoveWindowConnection(BaseWindow& _window, WindowDataType _data_type) { auto data_enum_index = magic_enum::enum_index(_data_type); if (!data_enum_index) { return false; } if (_window.m_input_connections[data_enum_index.value()] == std::nullopt) { return false; } _window.m_input_connections[data_enum_index.value()].value().window->m_output_connections[data_enum_index.value()].erase(_window.GetId()); _window.m_input_connections[data_enum_index.value()] = std::nullopt; return true; } void Jani::Inspector::BaseWindow::RemoveAllInputWindowConnections(BaseWindow& _window) { for (int i = 0; i < magic_enum::enum_count<WindowDataType>(); i++) { if (_window.m_input_connections[i].has_value()) { RemoveWindowConnection(_window, magic_enum::enum_value<WindowDataType>(i)); } } } void Jani::Inspector::BaseWindow::RemoveAllOutputWindowConnections(BaseWindow& _window) { for (auto& output_connection_info : _window.m_output_connections) { for (auto& [window_id, window] : output_connection_info) { for (int i = 0; i < window->m_input_connections.size(); i++) { auto& other_window_input_connection = window->m_input_connections[i]; if (other_window_input_connection && other_window_input_connection->window->GetId() == _window.GetId()) { other_window_input_connection = std::nullopt; } } } output_connection_info.clear(); } }
32.99211
241
0.628505
RodrigoHolztrattner
0171b344cb1d582828969b7e099d9e2168cb09f5
5,000
cpp
C++
trunk/src/kernel/lbmemcheck.cpp
breezeewu/media-server
b7f6e7c24a1c849180ba31088250c0174b1112e0
[ "MIT" ]
null
null
null
trunk/src/kernel/lbmemcheck.cpp
breezeewu/media-server
b7f6e7c24a1c849180ba31088250c0174b1112e0
[ "MIT" ]
null
null
null
trunk/src/kernel/lbmemcheck.cpp
breezeewu/media-server
b7f6e7c24a1c849180ba31088250c0174b1112e0
[ "MIT" ]
null
null
null
#include <lbmemcheck.hpp> #include <srs_kernel_log.hpp> #ifndef lbtrace #define lbtrace srs_trace #endif #ifndef lberror #define lberror srs_error #endif lbmemcheck_ctx* g_pmcc = NULL; lbmemcheck_ctx* lbmemcheck_initialize() { lbmemcheck_ctx* pmcc = (lbmemcheck_ctx*)::calloc(1, sizeof(lbmemcheck_ctx)); pmcc->plist = lblist_create_context(__INT32_MAX__); #ifdef ENABLE_PTHREAD_MUTEX_LOCK pmcc->pmutex = (pthread_mutex_t*)::malloc(sizeof(pthread_mutex_t)); memset(pmcc->pmutex, 0, sizeof(pthread_mutex_t)); pthread_mutexattr_t attr; pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(pmcc->plist->pmutex, &attr); #endif lbtrace("pmcc:%p = lbmemcheck_initialize\n", pmcc); return pmcc; } void lbmemcheck_finialize(lbmemcheck_ctx** ppmcc) { lbtrace("lbmemcheck_finialize, ppmcc:%p\n", ppmcc); if(ppmcc && *ppmcc) { lbmemcheck_ctx* pmcc = *ppmcc; lbtrace("lbmemcheck_finialize, pmcc:%p\n", pmcc); #ifdef ENABLE_PTHREAD_MUTEX_LOCK pthread_mutex_lock(pmcc->pmutex); #endif lbmem_blk* pmb = NULL; lblist_node* pnode = NULL; lbtrace("%d block of memory maybe leak\n", lblist_size(pmcc->plist)); while(lblist_size(pmcc->plist) > 0)//(pmb = (lbmem_blk*)lblist_pop(pmcc->plist)) { pmb = (lbmem_blk*)lblist_pop(pmcc->plist); lbtrace("leak memory [%s:%d %s] memory ptr:%p, size:%d\n", pmb->pfile_name, pmb->nfile_line, pmb->pfunc_name, pmb->pblock_ptr, pmb->nblock_size); if(pmb->pfile_name) { ::free(pmb->pfile_name); pmb->pfile_name = NULL; } if(pmb->pfunc_name) { ::free(pmb->pfunc_name); pmb->pfunc_name = NULL; } ::free(pmb); } lblist_close_context(&pmcc->plist); #ifdef ENABLE_PTHREAD_MUTEX_LOCK pthread_mutex_unlock(pmcc->pmutex); pthread_mutex_destroy(pmcc->pmutex); free(pmcc->pmutex); #endif ::free(pmcc); *ppmcc = pmcc = NULL; } } int lbmemcheck_add_block(lbmemcheck_ctx* pmcc, void* ptr, int size, const char* pfile_name, const int nfile_line, const char* pfunc_name) { if(!pmcc || !ptr) { return -1; } //lbtrace("new T(pmcc:%p, ptr:%p, size:%d, pfile_name:%s, nfile_line:%d, pfunc_name:%s)\n", pmcc, ptr, size, pfile_name, nfile_line, pfunc_name); assert(pmcc); assert(ptr); lbmem_blk* pmb = (lbmem_blk*)::calloc(1, sizeof(lbmem_blk)); if(NULL == pmb) { lberror("out of memory calloc lbmem_blk failed!\n"); assert(0); return -1; } pmb->pblock_ptr = ptr; pmb->nblock_size = size; int len = strlen(pfile_name) + 1; pmb->pfile_name = (char*)::calloc(len, sizeof(char)); if(NULL == pmb->pfile_name) { lberror("out of memory calloc pfile_name %s failed!\n", pfile_name); assert(0); return -1; } memcpy(pmb->pfile_name, pfile_name, len); pmb->nfile_line = nfile_line; len = strlen(pfunc_name); pmb->pfunc_name = (char*)::calloc(len, sizeof(char)); if(NULL == pmb->pfunc_name) { lberror("out of memory calloc pfunc_name %s failed!\n", pfunc_name); assert(0); return -1; } memcpy(pmb->pfunc_name, pfunc_name, len); return lblist_push(pmcc->plist, pmb); } int lbmemcheck_remove_block(lbmemcheck_ctx* pmcc, void* ptr) { /*assert(pmcc); assert(ptr);*/ //lbtrace("pmcc:%p, delete ptr:%p", pmcc, ptr); if(!pmcc || !ptr || !pmcc->plist) { return -1; } lbmem_blk* pmb = NULL; for(lblist_node* pnode = pmcc->plist->head; pnode != NULL; pnode = pnode->pnext) { pmb = (lbmem_blk*)pnode->pitem; //LBLIST_ENUM_BEGIN(lbmem_blk, pmcc->plist, pmb); if(pmb && ptr == pmb->pblock_ptr) { if(pmb->pfile_name) { ::free(pmb->pfile_name); pmb->pfile_name = NULL; } if(pmb->pfunc_name) { ::free(pmb->pfunc_name); pmb->pfunc_name = NULL; } ::free(pmb); lblist_remove_node(pmcc->plist, pnode); return 0; } } //LBLIST_ENUM_END() lberror("Invalid ptr:%p, not foud from alloc list!\n", ptr); return -1; } #ifdef __cplusplus template<class T> inline T* lbmem_new(int count, const char* pfile_name, const int nfile_line, const char* pfunc_name) { T* ptr = NULL; if(count > 1) { ptr = new T[count]; } else { ptr = new T(); } lbmemcheck_add_block(g_pmcc, ptr, sizeof(T) * count, pfile_name, nfile_line, pfunc_name); return ptr; } template<class T> inline void lbmem_delete(T* ptr, int isarray) { if(isarray) { delete[] ptr; } else { delete ptr; } lbmemcheck_remove_block(g_pmcc, ptr); } #endif
28.248588
157
0.5894
breezeewu
0173d54babdf4883a3150eb0599e66987bd23a3b
5,591
cpp
C++
CsCoreDEPRECATED/Source/CsCoreDEPRECATED/Components/CsWidgetComponent.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
2
2019-03-17T10:43:53.000Z
2021-04-20T21:24:19.000Z
CsCoreDEPRECATED/Source/CsCoreDEPRECATED/Components/CsWidgetComponent.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
CsCoreDEPRECATED/Source/CsCoreDEPRECATED/Components/CsWidgetComponent.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
// Copyright 2017-2019 Closed Sum Games, LLC. All Rights Reserved. #include "Components/CsWidgetComponent.h" #include "CsCoreDEPRECATED.h" // Types #include "Types/CsTypes.h" // Library #include "Library/CsLibrary_Common.h" // UI #include "UI/CsUserWidget.h" #include "UI/Simple/CsSimpleWidget.h" #include "Pawn/CsPawn.h" #include "Player/CsPlayerController.h" UCsWidgetComponent::UCsWidgetComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } void UCsWidgetComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); if (bMinDrawDistance) OnTick_Handle_DrawDistance(); if (Visibility == ECsVisibility::Hidden) return; if (ScaleByDistance) OnTick_Handle_Scale(); if (!bOnCalcCamera) { ACsPlayerController* LocalController = UCsLibrary_Common::GetLocalPlayerController<ACsPlayerController>(GetWorld()); OnTick_Handle_LocalCamera(LocalController->MinimalViewInfoCache.Location, LocalController->MinimalViewInfoCache.Rotation); } if (!FollowLocalCamera && FollowOwner) OnTick_Handle_Movement(); } UUserWidget* UCsWidgetComponent::GetWidget() { return Widget; } // Camera #pragma region void UCsWidgetComponent::OnCalcCamera(const uint8& MappingId, const float& DeltaTime, const struct FMinimalViewInfo& OutResult) { if (Visibility == ECsVisibility::Hidden) return; OnTick_Handle_LocalCamera(OutResult.Location, OutResult.Rotation); } void UCsWidgetComponent::OnTick_Handle_LocalCamera(const FVector& ViewLocation, const FRotator& ViewRotation) { if (!FollowLocalCamera && !LookAtLocalCamera) return; FVector CameraLocation = ViewLocation; FRotator CameraRotation = ViewRotation; if (FollowLocalCamera) { if (UCsLibrary_Common::IsVR()) { UCsLibrary_Common::GetHMDWorldViewPoint(GetWorld(), CameraLocation, CameraRotation); } CameraRotation.Roll = 0.f; const FVector Forward = ViewRotation.Vector(); const FVector Location = ViewLocation + DistanceProjectedOutFromCamera * Forward; SetWorldLocation(Location); FRotator Rotation = (-Forward).Rotation(); CameraLockAxes.ApplyLock(Rotation); //Rotation.Roll = 0.0f; //const FRotator Rotation = FRotator(-ViewRotation.Pitch, ViewRotation.Yaw + 180.0f, 0.0f); SetWorldRotation(Rotation); } else if (LookAtLocalCamera) { //ViewRotation.Roll = 0.f; FRotator Rotation = FRotator(-ViewRotation.Pitch, ViewRotation.Yaw + 180.0f, 0.0f); CameraLockAxes.ApplyLock(Rotation); SetWorldRotation(Rotation); } } #pragma endregion Camera // Info #pragma region void UCsWidgetComponent::SetInfo(const FVector2D& Size, const FTransform& Transform, const bool& InFollowLocalCamera, const bool& InLookAtLocalCamera) { SetDrawSize(Size); SetRelativeTransform(Transform); FollowLocalCamera = InFollowLocalCamera; LookAtLocalCamera = InLookAtLocalCamera; } void UCsWidgetComponent::SetInfo(const FCsWidgetComponentInfo& Info) { SetInfo(Info.DrawSize, Info.Transform, Info.FollowCamera, Info.LookAtCamera); DistanceProjectedOutFromCamera = Info.DistanceProjectedOutFromCamera; CameraLockAxes = Info.LockAxes; bMinDrawDistance = Info.bMinDrawDistance; MyMinDrawDistance = Info.MinDrawDistance; ScaleByDistance = Info.ScaleByDistance; FollowOwner = Info.FollowOwner; LocationOffset = Info.Transform.GetTranslation(); } void UCsWidgetComponent::SetInfo(const FCsWidgetActorInfo& Info) { SetInfo(Info.DrawSize, Info.Transform, false, false); } #pragma endregion Info // Visibility #pragma region void UCsWidgetComponent::Show() { Visibility = ECsVisibility::Visible; if (UCsUserWidget* UserWidget = Cast<UCsUserWidget>(Widget)) { UserWidget->Show(); } else if (UCsSimpleWidget* SimpleWidget = Cast<UCsSimpleWidget>(Widget)) { SimpleWidget->Show(); } else if (Widget) { Widget->SetIsEnabled(true); Widget->SetVisibility(ESlateVisibility::Visible); } Activate(); SetComponentTickEnabled(true); SetHiddenInGame(false); SetVisibility(true); } void UCsWidgetComponent::Hide() { Visibility = ECsVisibility::Hidden; if (UCsUserWidget* UserWidget = Cast<UCsUserWidget>(Widget)) { UserWidget->Hide(); } else if (UCsSimpleWidget* SimpleWidget = Cast<UCsSimpleWidget>(Widget)) { SimpleWidget->Hide(); } else if (Widget) { Widget->SetIsEnabled(false); Widget->SetVisibility(ESlateVisibility::Hidden); } SetVisibility(false); SetHiddenInGame(true); SetComponentTickEnabled(false); Deactivate(); } void UCsWidgetComponent::OnTick_Handle_Scale() { ACsPawn* LocalPawn = UCsLibrary_Common::GetLocalPawn<ACsPawn>(GetWorld()); const float Distance = (LocalPawn->GetActorLocation() - GetComponentLocation()).Size2D(); const float Scale = MyMinDrawDistance.Distance > 0 ? Distance / MyMinDrawDistance.Distance : 1.0f; SetRelativeScale3D(Scale * FVector::OneVector); } void UCsWidgetComponent::OnTick_Handle_DrawDistance() { ACsPawn* LocalPawn = UCsLibrary_Common::GetLocalPawn<ACsPawn>(GetWorld()); const float DistanceSq = (LocalPawn->GetActorLocation() - GetComponentLocation()).SizeSquared2D(); if (DistanceSq < MyMinDrawDistance.DistanceSq) { if (Visibility == ECsVisibility::Visible) Hide(); } else { if (Visibility == ECsVisibility::Hidden) Show(); } } #pragma endregion Visibility // Movement #pragma region void UCsWidgetComponent::OnTick_Handle_Movement() { const FVector Location = GetOwner()->GetActorLocation() + LocationOffset; SetWorldLocation(Location); } #pragma endregion Movement
24.959821
150
0.764979
closedsum
017768daea06f2b3bad9fa5c4261f7da65f3a67a
5,330
cpp
C++
mainprograms/TestTwoDProblem.cpp
Kauehenrik/FemCourseEigenClass2021
d4927d92b541fdd2b2aa1fa424a413dd561ae96e
[ "MIT" ]
1
2021-06-12T13:21:51.000Z
2021-06-12T13:21:51.000Z
mainprograms/TestTwoDProblem.cpp
Kauehenrik/FemCourseEigenClass2021
d4927d92b541fdd2b2aa1fa424a413dd561ae96e
[ "MIT" ]
null
null
null
mainprograms/TestTwoDProblem.cpp
Kauehenrik/FemCourseEigenClass2021
d4927d92b541fdd2b2aa1fa424a413dd561ae96e
[ "MIT" ]
null
null
null
// // TestOneDProblem.cpp MODIFICADO DO ORIGINAL // FemSC // // Created by Eduardo Ferri on 08/17/15. // // //TestOneDProblem cpp // Os testes foram preparados com um proposito educacional, // recomenda-se que o aluno entenda a funcionalidade de cada // teste e posteriormente use com seu cÛdigo caso a caso // Obs: O xmax e xmin estao tomados como 4 e 0, respectivamente, // caso estes valores sejam alterados, editar o teste TestNodes. // // #include <iostream> #include <math.h> #include "GeoNode.h" #include "GeoElement.h" #include "IntPointData.h" #include "CompElementTemplate.h" #include "Shape1d.h" #include "ShapeQuad.h" #include "ReadGmsh.h" #include "CompMesh.h" #include "GeoMesh.h" #include "GeoElement.h" #include "GeoElementTemplate.h" #include "MathStatement.h" #include "Poisson.h" #include "L2Projection.h" #include "Analysis.h" #include "IntRule.h" #include "IntRule1d.h" #include "IntRuleQuad.h" #include "IntRuleTetrahedron.h" #include "IntRuleTriangle.h" #include "Topology1d.h" #include "TopologyTriangle.h" #include "TopologyQuad.h" #include "TopologyTetrahedron.h" #include "PostProcess.h" #include "PostProcessTemplate.h" #include "DataTypes.h" #include "VTKGeoMesh.h" #include "CompElement.h" using std::cout; using std::endl; using std::cin; int main() { GeoMesh gmesh; ReadGmsh read; /* Malha triangulhar std::string filename("trian1.msh"); std::string filename("trian2.msh"); std::string filename("trian3.msh"); std::string filename("trian4.msh"); std::string filename("trian5.msh"); std::string filename("trian6.msh"); */ /* Malha quadratica std::string filename("quad0.msh"); std::string filename("quad1.msh"); std::string filename("quad2.msh"); std::string filename("quad3.msh"); std::string filename("quad4.msh"); std::string filename("quad5.msh"); std::string filename("quad6.msh"); */ std::string filename("trian6.msh"); read.Read(gmesh, filename); CompMesh cmesh(&gmesh); MatrixDouble perm(3, 3); perm.setZero(); perm(0, 0) = 1.; perm(1, 1) = 1.; perm(2, 2) = 1.; Poisson* mat1 = new Poisson(1, perm); mat1->SetDimension(2); auto force = [](const VecDouble& x, VecDouble& res) { res[0] = -90. * (-1. + x[0]) * (-1. + x[1]) * x[1] * cos(15. * x[0]) - 90. * x[0] * (-1. + x[1]) * x[1] * cos(15. * x[0]) + 2250. * (-1. + x[0]) * x[0] * (-1. + x[1]) * x[1] * cos(15. * x[1]) + 675. * (-1. + x[0]) * x[0] * (-1. + x[1]) * x[1] * sin(15. * x[0]) - 2 * (-1. + x[0]) * x[0] * (10. * cos(15. * x[1]) + 3. * sin(15. * x[0])) - 2. * (-1. + x[1]) * x[1] * (10. * cos(15. * x[1]) + 3. * sin(15. * x[0])) + 300. * (-1. + x[0]) * x[0] * (-1. + x[1]) * sin(15. * x[1]) + 300. * (-1. + x[0]) * x[0] * x[1] * sin(15. * x[1]); }; mat1->SetForceFunction(force); MatrixDouble proj(1, 1), val1(1, 1), val2(1, 1); proj.setZero(); val1.setZero(); val2.setZero(); L2Projection* bc_linha = new L2Projection(0, 2, proj, val1, val2); L2Projection* bc_point = new L2Projection(0, 3, proj, val1, val2); std::vector<MathStatement*> mathvec = { 0,mat1,bc_point,bc_linha }; cmesh.SetMathVec(mathvec); cmesh.SetDefaultOrder(1); cmesh.AutoBuild(); cmesh.Resequence(); Analysis locAnalysis(&cmesh); locAnalysis.RunSimulation(); PostProcessTemplate<Poisson> postprocess; auto exact = [](const VecDouble& x, VecDouble& val, MatrixDouble& deriv) { val[0] = (-1. + x[0]) * x[0] * (-1. + x[1]) * x[1] * (10. * cos(15. * x[1]) + 3. * sin(15. * x[0])); deriv(0, 0) = 45. * (-1. + x[0]) * x[0] * (-1. + x[1]) * x[1] * cos(15. * x[0]) + (-1. + x[0]) * (-1. + x[1]) * x[1] * (10. * cos(15. * x[1]) + 3. * sin(15. * x[0])) + x[0] * (-1. + x[1]) * x[1] * (10. * cos(15. * x[1]) + 3. * sin(15. * x[0])); deriv(1, 0) = (-1. + x[0]) * x[0] * (-1. + x[1]) * (10. * cos(15. * x[1]) + 3. * sin(15. * x[0])) + (-1. + x[0]) * x[0] * x[1] * (10. * cos(15. * x[1]) + 3. * sin(15 * x[0])) - 150.* (-1. + x[0]) * x[0] * (-1. + x[1]) * x[1] * sin(15. * x[1]); }; postprocess.AppendVariable("Sol"); postprocess.AppendVariable("DSol"); postprocess.AppendVariable("Flux"); postprocess.AppendVariable("Force"); postprocess.AppendVariable("SolExact"); postprocess.AppendVariable("DSolExact"); postprocess.SetExact(exact); mat1->SetExactSolution(exact); /* Malha triangulhar std::string filenamevtk("trian1.vtk"); std::string filenamevtk("trian2.vtk"); std::string filenamevtk("trian3.vtk"); std::string filenamevtk("trian4.vtk"); std::string filenamevtk("trian5.vtk"); std::string filenamevtk("trian6.vtk"); */ /* Malha quadratica std::string filenamevtk("quad0.vtk"); std::string filenamevtk("quad1.vtk"); std::string filenamevtk("quad2.vtk"); std::string filenamevtk("quad3.vtk"); std::string filenamevtk("quad4.vtk"); std::string filenamevtk("quad5.vtk"); std::string filenamevtk("quad6.vtk"); */ std::string filenamevtk("trian6.vtk"); locAnalysis.PostProcessSolution(filenamevtk, postprocess); VecDouble errvec; errvec = locAnalysis.PostProcessError(std::cout, postprocess); return 0; } void CreateTestMesh(CompMesh& mesh, int order) { DebugStop(); }
31.538462
536
0.593246
Kauehenrik
0177e04f79e8bbcea39736ba26a1a8493ddd5140
683
cxx
C++
tests/test_utils.cxx
hiroshin-dev/cxxplug
5d55a0424391301221a765f978d76fc702d33dd2
[ "MIT" ]
null
null
null
tests/test_utils.cxx
hiroshin-dev/cxxplug
5d55a0424391301221a765f978d76fc702d33dd2
[ "MIT" ]
null
null
null
tests/test_utils.cxx
hiroshin-dev/cxxplug
5d55a0424391301221a765f978d76fc702d33dd2
[ "MIT" ]
null
null
null
/// /// Copyright (c) 2022 Hiroshi Nakashima /// /// This software is released under the MIT License, see LICENSE. /// #include "gtest/gtest.h" #include "cxxplug/cxxplug.hxx" TEST(utils, get_environment) { { const auto value = cxxplug::get_environment("TEST_ENVIRONMENT"); EXPECT_EQ(value, "test-environment"); } { const auto value = cxxplug::get_environment("non-existent", "error"); EXPECT_EQ(value, "error"); } } TEST(utils, get_library_name) { const auto library_name = cxxplug::get_library_name("test"); #ifdef _WIN32 const auto expect = "test.dll"; #else const auto expect = "libtest.so"; #endif // _WIN32 EXPECT_EQ(library_name, expect); }
22.766667
73
0.688141
hiroshin-dev
017c55c48eca20afad7562e302b57bc3d0b76907
831
cpp
C++
tests/assert/is-not-null.cpp
njlr/mnmlstc-unittest
3e48e15730535f258251742efddf556be764e079
[ "Apache-2.0" ]
3
2015-02-27T04:09:09.000Z
2021-05-11T16:02:55.000Z
tests/assert/is-not-null.cpp
njlr/mnmlstc-unittest
3e48e15730535f258251742efddf556be764e079
[ "Apache-2.0" ]
null
null
null
tests/assert/is-not-null.cpp
njlr/mnmlstc-unittest
3e48e15730535f258251742efddf556be764e079
[ "Apache-2.0" ]
2
2017-08-15T12:34:09.000Z
2020-05-17T07:30:05.000Z
#include <iostream> #include <memory> #include <string> #include <cstdlib> #include <unittest/assert.hpp> #include <unittest/error.hpp> void v1() { using unittest::v1::error; namespace assert = unittest::v1::assert; std::unique_ptr<int> ptr { new int }; try { assert::is_not_null(ptr.release()); } catch (...) { std::clog << "Unexpected error thrown" << std::endl; std::exit(EXIT_FAILURE); } try { assert::is_not_null(ptr.get()); } catch (error const& e) { if (std::string { "is-not-null" } != e.type()) { std::clog << "Unexpected error '" << e.type() << "' thrown" << std::endl; std::exit(EXIT_FAILURE); } } catch (...) { std::clog << "Unexpected error thrown" << std::endl; std::exit(EXIT_FAILURE); } } int main () { v1(); return EXIT_SUCCESS; }
21.307692
65
0.583634
njlr
01801849ac23992dc22a0048d412b27e1b3ea4e8
143
cpp
C++
main.cpp
SCUTSSE/chatbot
4ac82e6eeb8d4a158439962b9dcedfa0b7967ddd
[ "MIT" ]
1
2020-05-19T20:17:34.000Z
2020-05-19T20:17:34.000Z
main.cpp
SCUTSSE/chatbot
4ac82e6eeb8d4a158439962b9dcedfa0b7967ddd
[ "MIT" ]
null
null
null
main.cpp
SCUTSSE/chatbot
4ac82e6eeb8d4a158439962b9dcedfa0b7967ddd
[ "MIT" ]
1
2018-07-13T10:22:37.000Z
2018-07-13T10:22:37.000Z
#include"Chatbot.h" #include <iostream> using namespace std; int main() { Tuling xiaoling; xiaoling.Interface(); return 0; }
11.916667
23
0.643357
SCUTSSE