hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
57ef763974c198b833edce7ec7756b37273588dc
533
hpp
C++
ccore/include/pyclustering/differential/equation.hpp
JosephChataignon/pyclustering
bf4f51a472622292627ec8c294eb205585e50f52
[ "BSD-3-Clause" ]
1,013
2015-01-26T19:50:14.000Z
2022-03-31T07:38:48.000Z
ccore/include/pyclustering/differential/equation.hpp
peterlau0626/pyclustering
bf4f51a472622292627ec8c294eb205585e50f52
[ "BSD-3-Clause" ]
542
2015-01-20T16:44:32.000Z
2022-01-29T14:57:20.000Z
ccore/include/pyclustering/differential/equation.hpp
peterlau0626/pyclustering
bf4f51a472622292627ec8c294eb205585e50f52
[ "BSD-3-Clause" ]
262
2015-03-19T07:28:12.000Z
2022-03-30T07:28:24.000Z
/*! @authors Andrei Novikov (pyclustering@yandex.ru) @date 2014-2020 @copyright BSD-3-Clause */ #pragma once #include <functional> #include <pyclustering/differential/differ_state.hpp> #include <pyclustering/differential/solve_type.hpp> namespace pyclustering { namespace differential { template <class state_type, class extra_type = void *> using equation = std::function<void (double, const differ_state<state_type> &, const differ_extra<extra_type> &, differ_state<state_type> &) >; } }
17.766667
144
0.716698
JosephChataignon
57f3c03fc5ddc707c1aec4b9ddec71cd50503ead
8,879
inl
C++
Synergy/src/Synergy/System/System.inl
nmrsmn/synergy
7f77c70c131debe66d2e91e00827fd30e736cf81
[ "MIT" ]
null
null
null
Synergy/src/Synergy/System/System.inl
nmrsmn/synergy
7f77c70c131debe66d2e91e00827fd30e736cf81
[ "MIT" ]
25
2020-04-05T11:05:08.000Z
2020-06-07T12:48:58.000Z
Synergy/src/Synergy/System/System.inl
nmrsmn/synergy
7f77c70c131debe66d2e91e00827fd30e736cf81
[ "MIT" ]
null
null
null
// Created by Niels Marsman on 15-05-2020. // Copyright © 2020 Niels Marsman. All rights reserved. #ifndef SYNERGY_SYSTEM_SYSTEM_INLINE #define SYNERGY_SYSTEM_SYSTEM_INLINE template <typename T> template <typename... Args> inline Synergy::System<T>::System(Synergy::Scene& scene, const std::string& name, Args&&... args) : m_Instance(std::forward<Args>(args)...), m_Name(name) { if constexpr(Synergy::SystemTraits<T>::HasEntities) this->RegisterEntities(scene); scene.OnEvent([&] (const Synergy::UpdateEvent& event) { this->OnUpdate(event.dt); }); if constexpr(Synergy::SystemTraits<T>::HasFrameStart) scene.OnEvent([&] (const Synergy::FrameStartEvent& event) { this->OnStartFrame(); }); if constexpr(Synergy::SystemTraits<T>::HasFrameEnd) scene.OnEvent([&] (const Synergy::FrameEndEvent& event) { this->OnEndFrame(); }); if constexpr(Synergy::SystemTraits<T>::HasInitialize) this->Initialize(); } template <typename T> bool Synergy::System<T>::HasEntities() const { return SystemTraits<T>::HasEntities; } template <typename T> bool Synergy::System<T>::HasInitialize() const { return SystemTraits<T>::HasInitialize; } template <typename T> bool Synergy::System<T>::HasDestroy() const { return Synergy::SystemTraits<T>::HasDestroy; } template <typename T> bool Synergy::System<T>::HasEnable() const { return Synergy::SystemTraits<T>::HasEnable; } template <typename T> bool Synergy::System<T>::HasDisable() const { return Synergy::SystemTraits<T>::HasDisable; } template <typename T> bool Synergy::System<T>::HasLoad() const { return Synergy::SystemTraits<T>::HasLoad; } template <typename T> bool Synergy::System<T>::HasUnload() const { return Synergy::SystemTraits<T>::HasUnload; } template <typename T> bool Synergy::System<T>::HasReload() const { return Synergy::SystemTraits<T>::HasReload; } template <typename T> bool Synergy::System<T>::HasFrameStart() const { return Synergy::SystemTraits<T>::HasFrameStart; } template <typename T> bool Synergy::System<T>::HasFrameEnd() const { return Synergy::SystemTraits<T>::HasFrameEnd; } template <typename T> bool Synergy::System<T>::HasFixedUpdate() const { return Synergy::SystemTraits<T>::HasFixedUpdate; } template <typename T> bool Synergy::System<T>::HasPreProcess() const { return Synergy::SystemTraits<T>::HasPreProcess; } template <typename T> bool Synergy::System<T>::HasProcess() const { return Synergy::SystemTraits<T>::HasProcess; } template <typename T> bool Synergy::System<T>::HasPostProcess() const { return Synergy::SystemTraits<T>::HasPostProcess; } template <typename T> bool Synergy::System<T>::HasUpdate() const { return Synergy::SystemTraits<T>::HasUpdate; } template <typename T> bool Synergy::System<T>::HasPostUpdate() const { return Synergy::SystemTraits<T>::HasPostUpdate; } template <typename T> inline void Synergy::System<T>::OnFrameStart() { if constexpr(Synergy::SystemTraits<T>::HasFrameStart) this->FrameStart(); } template <typename T> inline void Synergy::System<T>::OnFrameEnd() { if constexpr(Synergy::SystemTraits<T>::HasFrameEnd) this->FrameEnd(); } template <typename T> inline void Synergy::System<T>::OnUpdate(float dt) { if constexpr(Synergy::SystemTraits<T>::HasPreProcess) this->PreProcess(); if constexpr(Synergy::SystemTraits<T>::HasProcess) this->Process(); if constexpr(Synergy::SystemTraits<T>::HasPostProcess) this->PostProcess(); if constexpr(Synergy::SystemTraits<T>::HasUpdate) this->Update(); if constexpr(Synergy::SystemTraits<T>::HasPostUpdate) this->PostUpdate(); } template <typename T> template <typename U> typename std::enable_if_t<Synergy::SystemTraits<U>::HasInitialize> Synergy::System<T>::Initialize() { m_Instance.Initialize(); } template <typename T> template <typename U> typename std::enable_if_t<!Synergy::SystemTraits<U>::HasInitialize> Synergy::System<T>::Initialize() {} template <typename T> template <typename U> typename std::enable_if_t<Synergy::SystemTraits<U>::HasDestroy> Synergy::System<T>::Destroy() { m_Instance.Destroy(); } template <typename T> template <typename U> typename std::enable_if_t<!Synergy::SystemTraits<U>::HasDestroy> Synergy::System<T>::Destroy() {} template <typename T> template <typename U> typename std::enable_if_t<Synergy::SystemTraits<U>::HasEnable> Synergy::System<T>::Enable() { m_Instance.Enable(); } template <typename T> template <typename U> typename std::enable_if_t<!Synergy::SystemTraits<U>::HasEnable> Synergy::System<T>::Enable() {} template <typename T> template <typename U> typename std::enable_if_t<Synergy::SystemTraits<U>::HasDisable> Synergy::System<T>::Disable() { m_Instance.Disable(); } template <typename T> template <typename U> typename std::enable_if_t<!Synergy::SystemTraits<U>::HasDisable> Synergy::System<T>::Disable() {} template <typename T> template <typename U> typename std::enable_if_t<Synergy::SystemTraits<U>::HasLoad> Synergy::System<T>::Load() { m_Instance.Load(); } template <typename T> template <typename U> typename std::enable_if_t<!Synergy::SystemTraits<U>::HasLoad> Synergy::System<T>::Load() {} template <typename T> template <typename U> typename std::enable_if_t<Synergy::SystemTraits<U>::HasUnload> Synergy::System<T>::Unload() { m_Instance.Unload(); } template <typename T> template <typename U> typename std::enable_if_t<!Synergy::SystemTraits<U>::HasUnload> Synergy::System<T>::Unload() {} template <typename T> template <typename U> typename std::enable_if_t<Synergy::SystemTraits<U>::HasReload> Synergy::System<T>::Reload() { m_Instance.Reload(); } template <typename T> template <typename U> typename std::enable_if_t<!Synergy::SystemTraits<U>::HasReload> Synergy::System<T>::Reload() {} template <typename T> template <typename U> typename std::enable_if_t<Synergy::SystemTraits<U>::HasFrameStart> Synergy::System<T>::FrameStart() { m_Instance.FrameStart(); } template <typename T> template <typename U> typename std::enable_if_t<!Synergy::SystemTraits<U>::HasFrameStart> Synergy::System<T>::FrameStart() {} template <typename T> template <typename U> typename std::enable_if_t<Synergy::SystemTraits<U>::HasFrameEnd> Synergy::System<T>::FrameEnd() { m_Instance.FrameEnd(); } template <typename T> template <typename U> typename std::enable_if_t<!Synergy::SystemTraits<U>::HasFrameEnd> Synergy::System<T>::FrameEnd() {} template <typename T> template <typename U> typename std::enable_if_t<Synergy::SystemTraits<U>::HasFixedUpdate> Synergy::System<T>::FixedUpdate(float dt) { m_Instance.FixedUpdate(dt); } template <typename T> template <typename U> typename std::enable_if_t<!Synergy::SystemTraits<U>::HasFixedUpdate> Synergy::System<T>::FixedUpdate(float dt) {} template <typename T> template <typename U> typename std::enable_if_t<Synergy::SystemTraits<U>::HasPreProcess> Synergy::System<T>::PreProcess() { m_Instance.PreProcess(); } template <typename T> template <typename U> typename std::enable_if_t<!Synergy::SystemTraits<U>::HasPreProcess> Synergy::System<T>::PreProcess() {} template <typename T> template <typename U> typename std::enable_if_t<Synergy::SystemTraits<U>::HasProcess> Synergy::System<T>::Process() { for (auto entity : m_Instance.m_Entities) { entity.Invoke([&] (auto&&... args) { m_Instance.Process(std::forward<decltype(args)>(args)...); }); } } template <typename T> template <typename U> typename std::enable_if_t<!Synergy::SystemTraits<U>::HasProcess> Synergy::System<T>::Process() {} template <typename T> template <typename U> typename std::enable_if_t<Synergy::SystemTraits<U>::HasPostProcess> Synergy::System<T>::PostProcess() { m_Instance.PostProcess(); } template <typename T> template <typename U> typename std::enable_if_t<!Synergy::SystemTraits<U>::HasPostProcess> Synergy::System<T>::PostProcess() {} template <typename T> template <typename U> typename std::enable_if_t<Synergy::SystemTraits<U>::HasUpdate> Synergy::System<T>::Update(float dt) { m_Instance.Update(dt); } template <typename T> template <typename U> typename std::enable_if_t<!Synergy::SystemTraits<U>::HasUpdate> Synergy::System<T>::Update(float dt) {} template <typename T> template <typename U> typename std::enable_if_t<Synergy::SystemTraits<U>::HasPostUpdate> Synergy::System<T>::PostUpdate() { m_Instance.PostUpdate(); } template <typename T> template <typename U> typename std::enable_if_t<!Synergy::SystemTraits<U>::HasPostUpdate> Synergy::System<T>::PostUpdate() {} template <typename T> void Synergy::System<T>::RegisterEntities(Synergy::Scene& scene) { scene.RegisterEntitiesWith(m_Instance.m_Entities); } #endif
25.368571
110
0.718212
nmrsmn
57f9db00d28f16b0c941d0263caa49e29c65dc9f
1,065
cpp
C++
src/Network/Nodes/CallbackNode.cpp
dmalysiak/Lazarus
925d92843e311d2cd5afd437766563d0d5ab9052
[ "Apache-2.0" ]
1
2019-04-29T05:31:32.000Z
2019-04-29T05:31:32.000Z
src/Network/Nodes/CallbackNode.cpp
dmalysiak/Lazarus
925d92843e311d2cd5afd437766563d0d5ab9052
[ "Apache-2.0" ]
null
null
null
src/Network/Nodes/CallbackNode.cpp
dmalysiak/Lazarus
925d92843e311d2cd5afd437766563d0d5ab9052
[ "Apache-2.0" ]
null
null
null
/* * CallbackNode.cpp * * Created on: Aug 24, 2013 * Author: Darius Malysiak */ #include "CallbackNode.h" namespace Lazarus { CallbackNode::CallbackNode(unsigned int nodeID, Frame* frame) { m_communication_in_progress = false; mp_frame = frame; mp_com_callback = NULL; pthread_mutex_init(&m_mutex,NULL); m_node_id = nodeID; } CallbackNode::~CallbackNode() { pthread_mutex_destroy(&m_mutex); } void CallbackNode::setCallback(SynchronizationCallback* com_callback) { mp_com_callback = com_callback; } SynchronizationCallback* CallbackNode::getCallback() { return mp_com_callback; } bool CallbackNode::isCommunicating() { return m_communication_in_progress; } Frame* CallbackNode::get_mp_frame() { return mp_frame; } void CallbackNode::lockMutex() { pthread_mutex_lock(&m_mutex); m_communication_in_progress = true; } void CallbackNode::unlockMutex() { m_communication_in_progress = false; pthread_mutex_unlock(&m_mutex); } void CallbackNode::serialize() { } void CallbackNode::deserialize() { } } /* namespace Lazarus */
14.391892
69
0.749296
dmalysiak
57fe0e840b0d57f682a7a81320a4a8437b8c5cec
2,008
cpp
C++
SimpleCalculator/GlobalMgr.cpp
KeNorizon/SimpleCalculator
3e0cdc9b96d9474f4ff0279612fbd7bbb933306a
[ "BSD-2-Clause" ]
1
2019-10-30T16:16:50.000Z
2019-10-30T16:16:50.000Z
SimpleCalculator/GlobalMgr.cpp
KeNorizon/SimpleCalculator
3e0cdc9b96d9474f4ff0279612fbd7bbb933306a
[ "BSD-2-Clause" ]
null
null
null
SimpleCalculator/GlobalMgr.cpp
KeNorizon/SimpleCalculator
3e0cdc9b96d9474f4ff0279612fbd7bbb933306a
[ "BSD-2-Clause" ]
null
null
null
#include "GlobalMgr.h" #include <iostream> #include "ResultPanel.h" #include <QPoint> GlobalMgr *g_Data = nullptr; GlobalMgr::GlobalMgr() { g_Data = this; Visual.updateParamCache(); RootExpr = new HorizontalExpression(nullptr); Cursor.setWithoutBrighten(RootExpr, 0); Config.readFromFile(); markExprDirty(); markEnsureCursorInScreen(); } void GlobalMgr::init() { if (g_Data == nullptr) { new GlobalMgr(); } } bool GlobalMgr::isExprDirty() { return ExprDirtyFlag; } void GlobalMgr::markExprDirty() { ExprDirtyFlag = true; } void GlobalMgr::clearExprDirtyFlag() { ExprDirtyFlag = false; } bool GlobalMgr::isEnsureCursorInScreen() { return EnsureCursorInScreenFlag; } void GlobalMgr::markEnsureCursorInScreen() { EnsureCursorInScreenFlag = true; } void GlobalMgr::clearEnsureCursorInScreenFlag() { EnsureCursorInScreenFlag = false; } void GlobalMgr::doCompute() { updateResult(); ResultPanel::getInstance()->update(); } HorizontalExpression * GlobalMgr::getRootExpr() const { return RootExpr; } void GlobalMgr::setRootExpr(HorizontalExpression *expr) { if (!History.contains(RootExpr)) { delete RootExpr; clearResult(); } RootExpr = expr; } void GlobalMgr::repaintExpr() { ArithmeticPanel::getInstance()->update(); } void GlobalMgr::updateResult() { ExprResult = RootExpr->computeValue(); if (RootExpr->getLength() == 0) ResultPanel::getInstance()->hideResult(); else ResultPanel::getInstance()->showResult(ExprResult); } void GlobalMgr::setResult(ComputeResult result) { ExprResult = result; if (RootExpr->getLength() == 0) ResultPanel::getInstance()->hideResult(); else ResultPanel::getInstance()->showResult(ExprResult); } void GlobalMgr::clearResult() { ExprResult.Value = 0; ExprResult.Expr = nullptr; ExprResult.Error = ComputeErrorType::Success; ResultPanel::getInstance()->hideResult(); } GlobalMgr::~GlobalMgr() { if (RootExpr != nullptr) { if (!History.contains(RootExpr)) { delete RootExpr; RootExpr = nullptr; } } }
16.325203
55
0.725598
KeNorizon
57fff938372a00d8ffcd417e27f78b46016b987b
711
cpp
C++
core/geometry/GpuProgramManager.cpp
billhj/Etoile2015
c9311fc2a901cd60b2aeead5462ca8d6f7c5aa3a
[ "Apache-2.0" ]
null
null
null
core/geometry/GpuProgramManager.cpp
billhj/Etoile2015
c9311fc2a901cd60b2aeead5462ca8d6f7c5aa3a
[ "Apache-2.0" ]
null
null
null
core/geometry/GpuProgramManager.cpp
billhj/Etoile2015
c9311fc2a901cd60b2aeead5462ca8d6f7c5aa3a
[ "Apache-2.0" ]
null
null
null
/** * Copyright(C) 2009-2012 * @author Jing HUANG * @file GpuProgramManager.cpp * @brief * @date 1/2/2011 */ #include "GpuProgramManager.h" #include "GpuProgram.h" #include <assert.h> /** * @brief For tracking memory leaks under windows using the crtdbg */ #if ( defined( _DEBUG ) || defined( DEBUG ) ) && defined( _MSC_VER ) #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif namespace Etoile { GpuProgramManager::GpuProgramManager() : ResourceManager<GpuProgram>() { } /*GpuProgram* GpuProgramManager::getGpuProgramByName(const std::string& name) { return (GpuProgram*)getByName(name); }*/ }
18.230769
78
0.700422
billhj
52010ee08cdf00de841ef03ff0037aca5ac9db02
646
cpp
C++
src/main.cpp
MartinTschechne/ASL-hdbscan
6f43062902c5f8be4497253935a9a7bbc3954d97
[ "MIT" ]
1
2022-01-02T12:39:25.000Z
2022-01-02T12:39:25.000Z
src/main.cpp
MartinTschechne/ASL-hdbscan
6f43062902c5f8be4497253935a9a7bbc3954d97
[ "MIT" ]
null
null
null
src/main.cpp
MartinTschechne/ASL-hdbscan
6f43062902c5f8be4497253935a9a7bbc3954d97
[ "MIT" ]
null
null
null
#include <hdbscan/HDBSCAN_star_runner.h> #include <gflags/gflags.h> #include <iostream> #include <fstream> #include <benchmark/tsc_x86.h> int main(int argc, char** argv) { if (argc == 1) { gflags::ShowUsageWithFlags(argv[0]); exit(1); } gflags::ParseCommandLineFlags(&argc, &argv, true); long int start = start_tsc(); HDBSCANRunner(RunnerConfigFromFlags()); long int cycles = stop_tsc(start); std::ofstream benchmark_runner; benchmark_runner.open("measurements_runner.txt", std::ios_base::app); benchmark_runner << "total," << cycles << "\n"; benchmark_runner.close(); return 0; }
24.846154
73
0.664087
MartinTschechne
5204b80bbd7f0f5d2e6165e56866d28c617d7b03
666
cpp
C++
C++/TheFirst/CODE FILES/Numbers/simpleCalculator.cpp
Lakshmivallala/CPP
374bcdedd15a76fc4fa7b9d6c9dd3a140db859f1
[ "MIT" ]
null
null
null
C++/TheFirst/CODE FILES/Numbers/simpleCalculator.cpp
Lakshmivallala/CPP
374bcdedd15a76fc4fa7b9d6c9dd3a140db859f1
[ "MIT" ]
null
null
null
C++/TheFirst/CODE FILES/Numbers/simpleCalculator.cpp
Lakshmivallala/CPP
374bcdedd15a76fc4fa7b9d6c9dd3a140db859f1
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> using namespace std; int main() //function { int a,b; cout<<"Enter two integer numbers: "<<endl; cin>>a>>b; cout<<a+b<<endl; //try inputing float numbers cout<<a-b<<endl; cout<<a*b<<endl; cout<<a/b<<endl; cout<<a%b<<endl; //observe: give the inputs as 3 and 6. 3%6==3. You don't calculate with the steps: 3/6= 6*0.5=3 (don't go to decimal types while dividing integers) float c,d; cout<<"Enter two float numbers: "<<endl; cin>>c>>d; cout<<c+d<<endl; cout<<c-d<<endl; cout<<c*d<<endl; cout<<c/d<<endl; //cout<<c%d<<endl; RESULTS IN AN ERROR return 0; }
20.181818
168
0.585586
Lakshmivallala
5206a7139fc7f3909706486f779e0f73c5b40118
3,804
cpp
C++
cachelib/allocator/PoolResizer.cpp
GerHobbelt/CacheLib
580bf6950aad89cf86dbc153f12dada79b71eaf7
[ "Apache-2.0" ]
578
2021-09-01T14:19:55.000Z
2022-03-29T12:22:46.000Z
cachelib/allocator/PoolResizer.cpp
igchor/Cachelib
7db2c643d49fd0a4ec6c492d94a400cbe0515a70
[ "Apache-2.0" ]
61
2021-09-02T18:48:06.000Z
2022-03-31T01:56:00.000Z
cachelib/allocator/PoolResizer.cpp
igchor/Cachelib
7db2c643d49fd0a4ec6c492d94a400cbe0515a70
[ "Apache-2.0" ]
88
2021-09-02T21:22:19.000Z
2022-03-27T07:40:27.000Z
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 "cachelib/allocator/PoolResizer.h" #include <folly/logging/xlog.h> #include "cachelib/allocator/PoolResizeStrategy.h" #include "cachelib/common/Exceptions.h" namespace facebook { namespace cachelib { PoolResizer::PoolResizer(CacheBase& cache, unsigned int numSlabsPerIteration, std::shared_ptr<RebalanceStrategy> strategy) : cache_(cache), strategy_(std::move(strategy)), numSlabsPerIteration_(numSlabsPerIteration) { if (!strategy_) { strategy_ = std::make_shared<PoolResizeStrategy>(); } } PoolResizer::~PoolResizer() { stop(std::chrono::seconds(0)); } void PoolResizer::work() { const auto pools = cache_.getRegularPoolIdsForResize(); for (auto poolId : pools) { const PoolStats poolStats = cache_.getPoolStats(poolId); for (unsigned int i = 0; i < numSlabsPerIteration_; i++) { // check if the pool still needs resizing after each iteration. if (!cache_.getPool(poolId).overLimit()) { continue; } // if user had supplied a rebalance stategy for the pool, // use that to downsize it auto strategy = cache_.getResizeStrategy(poolId); if (!strategy) { strategy = strategy_; } // use the rebalance strategy and see if there is some allocation class // that is over provisioned. const auto classId = strategy->pickVictimForResizing(cache_, poolId); try { const auto now = util::getCurrentTimeMs(); // Throws excption if the strategy did not pick a valid victim classId. cache_.releaseSlab(poolId, classId, SlabReleaseMode::kResize); XLOGF(DBG, "Moved a slab from classId {} for poolid: {}", static_cast<int>(classId), static_cast<int>(poolId)); ++slabsReleased_; const auto elapsed_time = static_cast<uint64_t>(util::getCurrentTimeMs() - now); // Log the event about the Pool which released the Slab along with // the number of slabs. Only Victim Pool class information is // relevant here. stats_.addSlabReleaseEvent( classId, Slab::kInvalidClassId, /* No receiver Class info */ elapsed_time, poolId, 1, 1, /* One Slab moved */ poolStats.allocSizeForClass(classId), 0, poolStats.evictionAgeForClass(classId), 0, poolStats.mpStats.acStats.at(classId).freeAllocs); } catch (const exception::SlabReleaseAborted& e) { XLOGF(WARN, "Aborted trying to resize pool {} for allocation class {}. " "Error: {}", static_cast<int>(poolId), static_cast<int>(classId), e.what()); return; } catch (const std::exception& e) { XLOGF( CRITICAL, "Error trying to resize pool {} for allocation class {}. Error: {}", static_cast<int>(poolId), static_cast<int>(classId), e.what()); } } } // compact cache resizing is heavy weight and involves resharding. do that // only when all the item pools are resized if (pools.empty()) { cache_.resizeCompactCaches(); } } } // namespace cachelib } // namespace facebook
37.663366
80
0.65326
GerHobbelt
5209275a8a103556ebdfbab109b834e49e3bd8b5
53
cpp
C++
Code/EditorPlugins/PhysX/EnginePluginPhysX/EnginePluginPhysX.cpp
Tekh-ops/ezEngine
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
[ "MIT" ]
703
2015-03-07T15:30:40.000Z
2022-03-30T00:12:40.000Z
Code/EditorPlugins/PhysX/EnginePluginPhysX/EnginePluginPhysX.cpp
Tekh-ops/ezEngine
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
[ "MIT" ]
233
2015-01-11T16:54:32.000Z
2022-03-19T18:00:47.000Z
Code/EditorPlugins/PhysX/EnginePluginPhysX/EnginePluginPhysX.cpp
Tekh-ops/ezEngine
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
[ "MIT" ]
101
2016-10-28T14:05:10.000Z
2022-03-30T19:00:59.000Z
#include <EnginePluginPhysX/EnginePluginPhysXPCH.h>
17.666667
51
0.849057
Tekh-ops
520c12bbeb830c25bcb727fb4c5275901b6acc88
249
hpp
C++
src/Camera/Camera2D.hpp
fqhd/Sokuban
1b41fb6c6e7c865447824eaffce0dff8c7efafa4
[ "MIT" ]
1
2021-11-17T07:52:45.000Z
2021-11-17T07:52:45.000Z
src/Camera/Camera2D.hpp
fqhd/Sokuban
1b41fb6c6e7c865447824eaffce0dff8c7efafa4
[ "MIT" ]
null
null
null
src/Camera/Camera2D.hpp
fqhd/Sokuban
1b41fb6c6e7c865447824eaffce0dff8c7efafa4
[ "MIT" ]
null
null
null
#ifndef CAMERA2D_H #define CAMERA2D_H #include <glm/gtc/matrix_transform.hpp> class Camera2D { public: void init(unsigned int width, unsigned int height); const glm::mat4& getMatrix(); private: glm::mat4 m_matrix; }; #endif
11.318182
56
0.690763
fqhd
648f699375d91de2bb01c878a24392fb07b2a727
1,828
cpp
C++
Dll/Monoblock/Monoblock.cpp
buzyaba/SimEngine
e5469f927154de43ea52ad74c0ca4a0af9a7b721
[ "MIT" ]
5
2019-10-21T11:38:56.000Z
2020-05-30T04:50:50.000Z
Dll/Monoblock/Monoblock.cpp
buzyaba/SimEngine
e5469f927154de43ea52ad74c0ca4a0af9a7b721
[ "MIT" ]
2
2020-03-16T13:16:27.000Z
2020-10-10T07:35:15.000Z
Dll/Monoblock/Monoblock.cpp
buzyaba/SimEngine
e5469f927154de43ea52ad74c0ca4a0af9a7b721
[ "MIT" ]
3
2019-10-10T15:10:57.000Z
2020-02-14T13:11:50.000Z
#include "Monoblock.h" #include <random> // static std::random_device rd; // static std::mt19937 gen(rd()); // static std::bernoulli_distribution d(0.02); TMonoblock::TMonoblock(std::string _name) : TObjectOfObservation(_name) { properties.insert( {"IsWork", new TProperties({{"IsWork", 2}}, true, "IsWork")}); properties.insert( {"PowerConsumption", new TProperties({{"PowerConsumption", 0}}, true, "PowerConsumption")}); properties.insert( {"Coordinate", new TProperties({{"X", 0}, {"Y", 0}, {"Z", 0}}, false, "Coordinate")}); properties.insert( {"Rotate", new TProperties({{"X", 0.0}, {"Y", 0.0}, {"Z", 0.0}}, false, "Rotate")}); properties.insert( {"Scale", new TProperties({{"Width", 3}, {"Length", 3}, {"Height", 3}}, false, "Scale")}); textures.push_back( {{"screen_Plane.015"}, {"monitorON.png"}, {"monitorON.png"}}); isWork = false; } void TMonoblock::Update() { TObjectOfObservation::Update(); int newIsWork = static_cast<int>(properties["IsWork"]->GetValues()["IsWork"]); // if (newIsWork < 2 && d(gen)) // newIsWork = newIsWork ? 0 : 1; switch (newIsWork) { case 0: isWork = newIsWork; properties["PowerConsumption"]->SetValues( {{"PowerConsumption", 0.1667}}); // sleep textures[0][2] = "monitorSleep.png"; break; case 1: isWork = newIsWork; properties["PowerConsumption"]->SetValues( {{"PowerConsumption", 1.6667}}); // full textures[0][2] = "monitorON.png"; break; case 2: isWork = newIsWork; properties["PowerConsumption"]->SetValues( {{"PowerConsumption", 0}}); // shutdown textures[0][2] = "monitorOFF.png"; break; } } LIB_EXPORT_API TObjectOfObservation *create() { return new TMonoblock("TMonoblock"); }
29.967213
80
0.603392
buzyaba
64942fb5d9162df6456c0e6a21199f8274a974e3
6,637
cc
C++
node_modules/aerospike/src/main/client.cc
EnriqueSampaio/aero-livechat
29af57560e022a5958379445852def2cab94aca0
[ "MIT" ]
null
null
null
node_modules/aerospike/src/main/client.cc
EnriqueSampaio/aero-livechat
29af57560e022a5958379445852def2cab94aca0
[ "MIT" ]
null
null
null
node_modules/aerospike/src/main/client.cc
EnriqueSampaio/aero-livechat
29af57560e022a5958379445852def2cab94aca0
[ "MIT" ]
null
null
null
/******************************************************************************* * Copyright 2013-2014 Aerospike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ extern "C" { #include <aerospike/aerospike.h> #include <aerospike/aerospike_key.h> #include <aerospike/as_config.h> #include <aerospike/as_key.h> #include <aerospike/as_record.h> } #include <unistd.h> #include <node.h> #include "client.h" #include "conversions.h" #include "query.h" /******************************************************************************* * Fields ******************************************************************************/ /** * JavaScript constructor for AerospikeClient */ Nan::Persistent<FunctionTemplate> AerospikeClient::constructor; /******************************************************************************* * Constructor and Destructor ******************************************************************************/ AerospikeClient::AerospikeClient() {} AerospikeClient::~AerospikeClient() {} /******************************************************************************* * Methods ******************************************************************************/ NAN_METHOD(AerospikeClient::SetLogLevel) { Nan::HandleScope(); AerospikeClient * client = ObjectWrap::Unwrap<AerospikeClient>(info.Holder()); if (info[0]->IsObject()){ LogInfo * log = client->log; if ( log_from_jsobject(log, info[0]->ToObject()) != AS_NODE_PARAM_OK ) { log->severity = AS_LOG_LEVEL_INFO; log->fd = 2; } } info.GetReturnValue().Set(info.Holder()); } NAN_METHOD(AerospikeClient::Query) { Nan::HandleScope(); Local<Object> ns = info[0].As<Object>(); Local<Object> set = info[1].As<Object>(); Local<Object> config = info[2].As<Object>(); Local<Object> client = info.This(); info.GetReturnValue().Set(AerospikeQuery::NewInstance(ns, set, config, client)); } /** * Instantiate a new 'AerospikeClient(config)' * Constructor for AerospikeClient. */ NAN_METHOD(AerospikeClient::New) { Nan::HandleScope(); AerospikeClient * client = new AerospikeClient(); client->as = (aerospike*) cf_malloc(sizeof(aerospike)); client->log = (LogInfo*) cf_malloc(sizeof(LogInfo)); // initialize the log to default values. LogInfo * log = client->log; log->fd = 2; log->severity = AS_LOG_LEVEL_INFO; // initialize the config to default values. as_config config; as_config_init(&config); // Assume by default log is not set if(info[0]->IsObject()) { int default_log_set = 0; if (info[0]->ToObject()->Has(Nan::New("log").ToLocalChecked())) { Local<Value> log_val = info[0]->ToObject()->Get(Nan::New("log").ToLocalChecked()) ; if (log_from_jsobject( client->log, log_val->ToObject()) == AS_NODE_PARAM_OK) { default_log_set = 1; // Log is passed as an argument. set the default value } else { //log info is set to default level } } if ( default_log_set == 0 ) { LogInfo * log = client->log; log->fd = 2; } } if (info[0]->IsObject() ) { int result = config_from_jsobject(&config, info[0]->ToObject(), client->log); if( result != AS_NODE_PARAM_OK) { // Throw an exception if an error happens in parsing the config object. Nan::ThrowError("Configuration Error while creating client object"); } } aerospike_init(client->as, &config); as_v8_debug(client->log, "Aerospike object initialization : success"); client->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } /** * Instantiate a new 'AerospikeClient(config)' */ Local<Value> AerospikeClient::NewInstance(Local<Object> info) { Nan::EscapableHandleScope scope; const unsigned argc = 1; Handle<Value> argv[argc] = { info }; Local<FunctionTemplate> constructorHandle = Nan::New<FunctionTemplate>(constructor); Local<Value> instance = constructorHandle->GetFunction()->NewInstance(argc, argv); return scope.Escape(instance); } /** * Initialize a client object. * This creates a constructor function, and sets up the prototype. */ void AerospikeClient::Init() { // Prepare constructor template Local<FunctionTemplate> cons = Nan::New<FunctionTemplate>(AerospikeClient::New); cons->SetClassName(Nan::New("AerospikeClient").ToLocalChecked()); // A client object created in node.js, holds reference to the wrapped c++ // object using an internal field. // InternalFieldCount signifies the number of c++ objects the node.js object // will refer to when it is intiatiated in node.js cons->InstanceTemplate()->SetInternalFieldCount(1); // Prototype Nan::SetPrototypeMethod(cons, "batchGet", BatchGet); Nan::SetPrototypeMethod(cons, "batchExists", BatchExists); Nan::SetPrototypeMethod(cons, "batchSelect", BatchSelect); Nan::SetPrototypeMethod(cons, "close", Close); Nan::SetPrototypeMethod(cons, "connect", Connect); Nan::SetPrototypeMethod(cons, "exists", Exists); Nan::SetPrototypeMethod(cons, "get", Get); Nan::SetPrototypeMethod(cons, "info", Info); Nan::SetPrototypeMethod(cons, "indexCreate", sindexCreate); Nan::SetPrototypeMethod(cons, "indexCreateWait", sindexCreateWait); Nan::SetPrototypeMethod(cons, "indexRemove", sindexRemove); Nan::SetPrototypeMethod(cons, "operate", Operate); Nan::SetPrototypeMethod(cons, "put", Put); Nan::SetPrototypeMethod(cons, "query", Query); Nan::SetPrototypeMethod(cons, "remove", Remove); Nan::SetPrototypeMethod(cons, "select", Select); Nan::SetPrototypeMethod(cons, "udfRegister", Register); Nan::SetPrototypeMethod(cons, "udfRegisterWait", RegisterWait); Nan::SetPrototypeMethod(cons, "execute", Execute); Nan::SetPrototypeMethod(cons, "udfRemove", UDFRemove); Nan::SetPrototypeMethod(cons, "updateLogging", SetLogLevel); constructor.Reset(cons); }
33.862245
95
0.612024
EnriqueSampaio
6494e492f5b3394e590f477d025203a1a6d06a84
1,772
cpp
C++
src/devices/bus/msx_cart/crossblaim.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/devices/bus/msx_cart/crossblaim.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/devices/bus/msx_cart/crossblaim.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Wilbert Pol #include "emu.h" #include "crossblaim.h" DEFINE_DEVICE_TYPE(MSX_CART_CROSSBLAIM, msx_cart_crossblaim_device, "msx_cart_crossblaim", "MSX Cartridge Cross Blaim") msx_cart_crossblaim_device::msx_cart_crossblaim_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : device_t(mconfig, MSX_CART_CROSSBLAIM, tag, owner, clock) , msx_cart_interface(mconfig, *this) , m_selected_bank(1) { for (auto & elem : m_bank_base) { elem = nullptr; } } void msx_cart_crossblaim_device::device_start() { save_item(NAME(m_selected_bank)); } void msx_cart_crossblaim_device::device_post_load() { restore_banks(); } void msx_cart_crossblaim_device::setup_bank() { m_bank_base[0] = ( m_selected_bank & 2 ) ? nullptr : get_rom_base() + ( m_selected_bank & 0x03 ) * 0x4000; m_bank_base[2] = get_rom_base() + ( m_selected_bank & 0x03 ) * 0x4000; m_bank_base[3] = ( m_selected_bank & 2 ) ? nullptr : get_rom_base() + ( m_selected_bank & 0x03 ) * 0x4000; } void msx_cart_crossblaim_device::restore_banks() { m_bank_base[1] = get_rom_base(); setup_bank(); } void msx_cart_crossblaim_device::device_reset() { m_selected_bank = 1; } void msx_cart_crossblaim_device::initialize_cartridge() { if (get_rom_size() != 0x10000) { fatalerror("crossblaim: Invalid ROM size\n"); } restore_banks(); } uint8_t msx_cart_crossblaim_device::read_cart(offs_t offset) { uint8_t *bank_base = m_bank_base[offset >> 14]; if (bank_base != nullptr) { return bank_base[offset & 0x3fff]; } return 0xff; } void msx_cart_crossblaim_device::write_cart(offs_t offset, uint8_t data) { m_selected_bank = data & 3; if (m_selected_bank == 0) { m_selected_bank = 1; } setup_bank(); }
20.367816
135
0.735892
Robbbert
64950f83d9ab2c5f8100334531b94a1ed23587fc
10,757
cpp
C++
src/image.cpp
boberfly/bakec
4563441ab26b857de6b2e9e6f24b6a965aebccfc
[ "MIT" ]
3
2018-09-07T03:44:08.000Z
2019-02-19T15:20:26.000Z
src/image.cpp
boberfly/bakec
4563441ab26b857de6b2e9e6f24b6a965aebccfc
[ "MIT" ]
null
null
null
src/image.cpp
boberfly/bakec
4563441ab26b857de6b2e9e6f24b6a965aebccfc
[ "MIT" ]
null
null
null
/* Copyright 2018 Oscar Sebio Cajaraville 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 "image.h" #include "compute.h" #include "logging.h" #include "math.h" #include "timing.h" #include <cassert> //#pragma warning(disable:4996) //#define STB_IMAGE_WRITE_IMPLEMENTATION //#include "stb_image_write.h" //#include "tinyexr.h" #include <bx/bx.h> #include <bimg/bimg.h> Vector2 getMinMax(const float *data, const size_t count) { Vector2 minmax(FLT_MAX, -FLT_MAX); for (size_t i = 0; i < count; ++i) { const float r = data[i]; minmax.x = std::fminf(minmax.x, r); minmax.y = std::fmaxf(minmax.y, r); } return minmax; } enum class Extension { Unknown, Png, Tga, Exr }; bool endsWith(const std::string &str, const std::string &ending) { if (ending.size() > str.size()) return false; return std::equal(ending.rbegin(), ending.rend(), str.rbegin()); } Extension getExtension(const char *path) { std::string p(path); if (endsWith(p, ".png")) return Extension::Png; if (endsWith(p, ".tga")) return Extension::Tga; if (endsWith(p, ".exr")) return Extension::Exr; return Extension::Unknown; } Vector2 computeScaleBias(const Vector2 &minmax, bool normalize) { if (normalize && minmax.x != FLT_MAX && minmax.y != -FLT_MAX) { const float scale = 1.0f / (minmax.y - minmax.x); return Vector2(scale, -minmax.x * scale); } return Vector2(1.0f, 0.0f); } struct PixPos { int x; int y; PixPos operator -() const { return PixPos{ -x, -y }; } PixPos operator +(const PixPos &o) const { return PixPos{ x + o.x, y + o.y }; } PixPos operator -(const PixPos &o) const { return PixPos{ x - o.x, y - o.y }; } PixPos operator *(const int k) const { return PixPos{ x * k, y * k }; } PixPos operator *(const PixPos &o) const { return PixPos{ x * o.x, y * o.y }; } }; std::vector<bool> createValidPixelsTable(const CompressedMapUV *map) { std::vector<bool> validPixels(map->width * map->height); for (const auto idx : map->indices) { validPixels[idx] = true; } return validPixels; } std::vector<bool> createValidPixelsTableRGB ( const CompressedMapUV *map, const uint8_t *data, uint8_t invalidR, uint8_t invalidG, uint8_t invalidB ) { const size_t w = map->width; const size_t h = map->height; std::vector<bool> validPixels(w * h); for (const auto idx : map->indices) { const size_t x = idx % w; const size_t y = idx / h; const size_t pixIdx = ((h - y - 1) * w + x) * 3; const uint8_t r = data[pixIdx + 0]; const uint8_t g = data[pixIdx + 1]; const uint8_t b = data[pixIdx + 2]; validPixels[idx] = (r != invalidR) | (g != invalidG) | (b != invalidB); } return validPixels; } #define DEBUG 1 void dilateRGB(uint8_t *data, const CompressedMapUV *map, const std::vector<bool> &validPixels, const size_t maxDist) { Timing timing; timing.begin(); const PixPos offsets[] = { { 1,0 },{ -1,0 },{ 0,1 },{ 0,-1 },{ 1,1 },{ 1,-1 },{ -1,1 },{ -1,-1 } }; const int w = int(map->width); const int h = int(map->height); #pragma omp parallel for for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { if (!validPixels[x + y * w]) { PixPos pos{ x, y }; bool filled = false; for (size_t dist = 1; dist < maxDist && !filled; ++dist) { for (const PixPos offset : offsets) { PixPos centerPos = pos + offset * int(dist); if (centerPos.x > 0 && centerPos.y > 0 && centerPos.x < w - 1 && centerPos.y < h - 1) { bool valid = true; for (const PixPos o : offsets) { PixPos testPos = centerPos + o; if (!validPixels[testPos.x + testPos.y * w]) { valid = false; break; } } if (valid) { const size_t pixIdxSrc = ((h - centerPos.y - 1) * w + centerPos.x) * 3; const size_t pixIdxDst = ((h - pos.y - 1) * w + pos.x) * 3; data[pixIdxDst + 0] = data[pixIdxSrc + 0]; data[pixIdxDst + 1] = data[pixIdxSrc + 1]; data[pixIdxDst + 2] = data[pixIdxSrc + 2]; filled = true; break; } } } } } } } timing.end(); logDebug("Image", "Image dilation took " + std::to_string(timing.elapsedSeconds()) + " seconds."); } void exportFloatImage(const float *data, const CompressedMapUV *map, const char *path, bool normalize, int dilate, Vector2 *o_minmax) { assert(data); assert(map); assert(path); Extension ext = getExtension(path); if (ext == Extension::Unknown) return; // TODO: Error handling const size_t count = map->indices.size(); const size_t w = map->width; const size_t h = map->height; const Vector2 minmax = getMinMax(data, count); if (o_minmax) *o_minmax = minmax; const Vector2 scaleBias = computeScaleBias(minmax, normalize); bx::Error err; bx::FileWriter writer; if (bx::open(&writer, path, false, &err) ) { if (ext == Extension::Png || ext == Extension::Tga) { // TODO: Unnormalized quantized data is not a great option... //if (!normalize) return Vector2(); uint8_t *rgb = new uint8_t[w * h * 3]; memset(rgb, 0, sizeof(uint8_t) * w * h * 3); for (size_t i = 0; i < count; ++i) { const float d = data[i]; const float t = d * scaleBias.x + scaleBias.y; const uint8_t c = (uint8_t)(std::min(std::max(t, 0.0f), 1.0f) * 255.0f); const size_t index = map->indices[i]; const size_t x = index % w; const size_t y = index / w; const size_t pixidx = ((h - y - 1) * w + x) * 3; rgb[pixidx + 0] = c; rgb[pixidx + 1] = c; rgb[pixidx + 2] = c; } if (dilate > 0) { const auto validPixels = createValidPixelsTable(map); dilateRGB(rgb, map, validPixels, dilate); } if (ext == Extension::Tga) int32_t ret = bimg::imageWriteTga( &writer , w , h , w*3 , &rgb , false , false , &err ); else if (ext == Extension::Png) int32_t ret = bimg::imageWritePng( &writer , w , h , w*3 , &rgb , bimg::TextureFormat::RGBA8 , false , &err ); delete[] rgb; } else if (ext == Extension::Exr) { float *f = new float[w * h]; memset(f, 0, sizeof(float) * w * h); for (size_t i = 0; i < count; ++i) { const float d = data[i]; const float t = d * scaleBias.x + scaleBias.y; const size_t index = map->indices[i]; const size_t x = index % w; const size_t y = index / w; const size_t pixidx = ((h - y - 1) * w + x); f[pixidx] = t; } int32_t ret = bimg::imageWriteExr( &writer , w , h , w*8 , &f , bimg::TextureFormat::RGBA16F , false , &err ); delete[] f; } } } void exportVectorImage(const Vector3 *data, const CompressedMapUV *map, const char *path) { assert(data); assert(map); assert(path); Extension ext = getExtension(path); if (ext != Extension::Exr) return; // TODO: Error handling const size_t count = map->indices.size(); const size_t w = map->width; const size_t h = map->height; EXRHeader header; InitEXRHeader(&header); EXRImage image; InitEXRImage(&image); image.num_channels = 1; std::vector<float> images[3]; images[0].resize(w * h); images[1].resize(w * h); images[2].resize(w * h); for (size_t i = 0; i < count; ++i) { const size_t index = map->indices[i]; const size_t x = index % w; const size_t y = index / w; const size_t pixidx = ((h - y - 1) * w + x); images[0][pixidx] = data[i].z; images[1][pixidx] = data[i].y; images[2][pixidx] = data[i].x; } float *image_ptr[3] = { &images[0][0], &images[1][0], &images[2][0] }; image.images = (unsigned char **)(image_ptr); image.width = (int)w; image.height = (int)h; header.num_channels = 3; header.channels = new EXRChannelInfo[header.num_channels]; strncpy(header.channels[0].name, "B", 255); header.channels[0].name[strlen("B")] = '\0'; strncpy(header.channels[1].name, "G", 255); header.channels[1].name[strlen("G")] = '\0'; strncpy(header.channels[2].name, "R", 255); header.channels[2].name[strlen("R")] = '\0'; header.pixel_types = new int[header.num_channels]; header.requested_pixel_types = new int[header.num_channels]; for (size_t i = 0; i < header.num_channels; ++i) { header.pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_HALF; } const char *err; int ret = SaveEXRImageToFile(&image, &header, path, &err); if (ret != TINYEXR_SUCCESS) { // TODO: Error handling } delete[] header.channels; delete[] header.pixel_types; delete[] header.requested_pixel_types; } void exportNormalImage(const Vector3 *data, const CompressedMapUV *map, const char *path, int dilate) { assert(data); assert(map); assert(path); Extension ext = getExtension(path); if (ext == Extension::Unknown) return; // TODO: Error handling const size_t count = map->indices.size(); const size_t w = map->width; const size_t h = map->height; if (ext == Extension::Png || ext == Extension::Tga) { uint8_t *rgb = new uint8_t[w * h * 3]; memset(rgb, 0, sizeof(uint8_t) * w * h * 3); for (size_t i = 0; i < count; ++i) { const Vector3 n = data[i] * 0.5f + Vector3(0.5f); const size_t index = map->indices[i]; const size_t x = index % w; const size_t y = index / w; const size_t pixidx = ((h - y - 1) * w + x) * 3; rgb[pixidx + 0] = uint8_t(n.x * 255.0f); rgb[pixidx + 1] = uint8_t(n.y * 255.0f); rgb[pixidx + 2] = uint8_t(n.z * 255.0f); } if (dilate > 0) { const auto validPixels = createValidPixelsTableRGB(map, rgb, 0, 0, 0); dilateRGB(rgb, map, validPixels, dilate); } if (ext == Extension::Png) stbi_write_png(path, (int)w, (int)h, 3, rgb, (int)w * 3); else stbi_write_tga(path, (int)w, (int)h, 3, rgb); delete[] rgb; } else if (ext == Extension::Exr) { exportVectorImage(data, map, path); } }
26.365196
133
0.627591
boberfly
6495723b7e66913921e9e390dec342a7f8cd962c
14,381
cpp
C++
lib/ModbusAPI.cpp
mensinda/modbusSMA
0c2ddd28123ee6a3032fc82d5be8e9c6cfd9a979
[ "Apache-2.0" ]
1
2020-03-15T18:53:26.000Z
2020-03-15T18:53:26.000Z
lib/ModbusAPI.cpp
mensinda/modbusSMA
0c2ddd28123ee6a3032fc82d5be8e9c6cfd9a979
[ "Apache-2.0" ]
null
null
null
lib/ModbusAPI.cpp
mensinda/modbusSMA
0c2ddd28123ee6a3032fc82d5be8e9c6cfd9a979
[ "Apache-2.0" ]
1
2022-03-14T11:06:26.000Z
2022-03-14T11:06:26.000Z
/* * Copyright (C) 2018 Daniel Mensinger * * 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 "mSMAConfig.hpp" #include "ModbusAPI.hpp" #include <algorithm> #include "Logging.hpp" #include "MBConnectionIP.hpp" #include "MBConnectionIP_PI.hpp" #include "MBConnectionRTU.hpp" using namespace std; using namespace modbusSMA; /*! * \brief Initializes the ModbusAPI with a custom TCP IP and port * \sa setConnectionTCP_IP */ ModbusAPI::ModbusAPI(string _ip, //!< The IP address of the inverter. uint32_t _port, //!< The modbus TCP port. std::shared_ptr<DataBase> _db //!< Database describing the modbus registers. ) { setConnectionTCP_IP(_ip, _port); setDataBase(_db); } /*! * \brief Initializes the ModbusAPI with a custom IP and port * \sa setConnectionTCP_IP */ ModbusAPI::ModbusAPI(string _node, //!< The Modbus node (IP address, DNS name, etc.) of the inverter. string _service, //!< The service to connect to. std::shared_ptr<DataBase> _db //!< Database describing the modbus registers. ) { setConnectionTCP_IP_PI(_node, _service); setDataBase(_db); } /*! * \brief Initializes the ModbusAPI with a RTU connectopm * \sa setConnectionRTU */ ModbusAPI::ModbusAPI(string _device, //!< The name / path of the serial port. uint32_t _baud, //!< RTU connection baud rate. char _parity, //!< Partity type: N = None; E = Even; O = Odd. int _dataBit, //!< The number of bits of data, the allowed values are 5, 6, 7 and 8 int _stopBit, //!< The bits of stop, the allowed values are 1 and 2. std::shared_ptr<DataBase> _db //!< Database describing the modbus registers. ) { setConnectionRTU(_device, _baud, _parity, _dataBit, _stopBit); setDataBase(_db); } //! Wrapper for the other constructor. ModbusAPI::ModbusAPI(string _ip, uint32_t _port, string _dbPath) : ModbusAPI(_ip, _port, make_shared<DataBase>(_dbPath)) {} //! Wrapper for the other constructor. ModbusAPI::ModbusAPI(string _node, string _service, string _dbPath) : ModbusAPI(_node, _service, make_shared<DataBase>(_dbPath)) {} //! Wrapper for the other constructor. ModbusAPI::ModbusAPI(string _device, uint32_t _baud, char _parity, int _dataBit, int _stopBit, string _dbPath) : ModbusAPI(_device, _baud, _parity, _dataBit, _stopBit, make_shared<DataBase>(_dbPath)) {} ModbusAPI::~ModbusAPI() { reset(); } /*! * \brief Resets the state of the object (modbus connection, inverter type, etc.) to CONFIGURE * * The configuration (IP, port) is NOT reset. * * State change: * --> CONFIGURE */ void ModbusAPI::reset() { if (mConn) { mConn->disconnect(); mConn = nullptr; } mRegisters = nullptr; mState = State::CONFIGURE; } /*! * \brief Establishes the modbus connection based on the current configuration * * State change: CONFIGURE --> CONNECTED | ERROR */ ErrorCode ModbusAPI::connect() { auto logger = log::get(); if (mState != State::CONFIGURE) { logger->error("ModbusAPI: can not connect() -- invalid object state '{}'", enum2Str::toStr(mState)); mState = State::ERROR; return ErrorCode::INVALID_STATE; } auto res = mConn->connect(); if (res != ErrorCode::OK) { logger->error("ModbusAPI: unable to connect: '{}'", enum2Str::toStr(res)); mState = State::ERROR; return res; } logger->info("ModbusAPI: connected to {}", mConn->description()); mState = State::CONNECTED; return ErrorCode::OK; } /*! * \brief Initializes the API * * This function connects to the DataBase (if not already done) and initializes the API by querying basic * information (uinit id, inverter type) from the modbus interface * * State change: CONNECTED --> INITIALIZED | ERROR */ ErrorCode ModbusAPI::initialize() { auto logger = log::get(); ErrorCode result; if (mState != State::CONNECTED) { logger->error("ModbusAPI: can not initialize() -- invalid object state '{}'", enum2Str::toStr(mState)); mState = State::ERROR; return ErrorCode::INVALID_STATE; } // 1st: check database if (!mDB->isConnected()) { result = mDB->connect(); if (result != ErrorCode::OK) { logger->error("ModbusAPI: DataBase initialization failed with {}", enum2Str::toStr(result)); mState = State::ERROR; return result; } } mRegisters = make_shared<RegisterContainer>(); mRegisters->addRegisters(mDB->getRegisters("ALL")); if (mRegisters->empty()) { // This code should never be executed because of the DataBase validation logger->error("ModbusAPI: No Registers in table 'ALL'"); mState = State::ERROR; return ErrorCode::DATA_BASE_ERROR; } // 2nd: set slave ID to 1 result = mConn->setSlaveID(1); if (result != ErrorCode::OK) { mState = State::ERROR; return result; } // 3rd: request data vector<uint16_t> rawData = mConn->readRegisters(42109, 4); logger->debug("Requesting basic inverter information:"); if (rawData.size() != 4) { logger->error("ModbusAPI: Failed to initialize -- requesting slave/unit ID failed"); mState = State::ERROR; return ErrorCode::INITIALIZATION_FAILED; } uint32_t serialNumber = (rawData[0] << 16) + rawData[1]; uint16_t susyID = rawData[2]; uint16_t unitID = rawData[3]; logger->debug(" -- Physical serial number: {}", serialNumber); logger->debug(" -- Physical SusyID: {}", susyID); logger->debug(" -- Unit / Slave ID: {}", unitID); // 4th: set slave ID to unitID result = mConn->setSlaveID(unitID); if (result != ErrorCode::OK) { mState = State::ERROR; return result; } // 5th: determine the inverter type rawData = mConn->readRegisters(30053, 2); uint32_t inverterID = (rawData[0] << 16) + rawData[1]; logger->debug(" -- Inverter type ID: {}", inverterID); auto devices = mDB->getDeviceEnums(); bool found = false; for (auto i : devices) { if (i.id == inverterID) { found = true; mInverterType = i.name; mInverterTypeID = inverterID; mRegisters->addRegisters(mDB->getRegisters(i.table)); break; } } if (!found) { logger->error("ModbusAPI: unknown inverter type {}", inverterID); mState = State::ERROR; return ErrorCode::INITIALIZATION_FAILED; } logger->debug(" -- Inverter type: '{}'", mInverterType); logger->debug(" -- Number of registers: {}", mRegisters->size()); logger->info("ModbusAPI: initialization for {} complete", mInverterType); mState = State::INITIALIZED; return ErrorCode::OK; } /*! * \brief Wrapper for connect() and initialize() * * State change: CONFIGURE --> INITIALIZED | ERROR */ ErrorCode ModbusAPI::setup() { ErrorCode res = connect(); if (res != ErrorCode::OK) { return res; } return initialize(); } //! Internal Request helper //! \internal struct RegBatch { //! Internal Request helper //! \internal struct Reg { uint16_t reg; //!< 16-bit register address. uint16_t offset; //!< offset in the rawData vector. uint16_t size; //!< number of modbus registers used in the Register class. }; uint16_t size; //!< Size of the batch in number of registers. vector<Reg> regs; //!< Registers in the batch. vector<uint16_t> rawData; //!< Raw data vector. }; /*! * \brief Updates all registers stored in _regList * * Fethes the register values from the inverter and stores the values in the shared RegisterContainer. The updated * register values can then examined by requesting the registers from the RegisterContainer. * * Unsupported registers (by the inverter) in _regList are ignored. * * \note This function can only be called in the INITIALIZED state * * State change: NONE * * \param[in] _regList List of registers to update * \param[out] _numUpdated Number of updated registers */ ErrorCode ModbusAPI::updateRegisters(vector<Register> _regList, size_t *_numUpdated) { auto logger = log::get(); if (_numUpdated) { *_numUpdated = 0; } if (mState != State::INITIALIZED) { logger->error("ModbusAPI: updateRegisters() -- invalid object state '{}'", enum2Str::toStr(mState)); return ErrorCode::INVALID_STATE; } if (_regList.empty()) { logger->warn("ModbusAPI: updateRegisters() -- empty register list ==> do nothing"); return ErrorCode::OK; } sort(begin(_regList), end(_regList)); // Ensure that the list is sorted. // 1st: Create batches of registers. std::vector<RegBatch> batches; batches.reserve(_regList.size()); // Worst case: every register has its own batch batches.push_back({0, {}, {}}); for (Register i : _regList) { RegBatch *curr = &batches.back(); if (!curr->regs.empty()) { if (((curr->size + i.size()) >= SMA_MODBUS_MAX_REGISTER_COUNT) || // Check if maximum request size is reached ((curr->regs[0].reg + curr->size) != i.reg())) { // Check if continous batches.push_back({0, {}, {}}); curr = &batches.back(); } } curr->regs.push_back({i.reg(), curr->size, (uint16_t)i.size()}); curr->size += i.size(); } vector<uint16_t> singleRegData = {}; uint32_t counter = 1; for (auto &i : batches) { logger->debug("Fetching batch {} of {} -- Start: {}; Size: {}", counter++, batches.size(), i.regs[0].reg, i.size); i.rawData = mConn->readRegisters(i.regs[0].reg, i.size); if (i.rawData.size() != i.size) { logger->warn( "ModbusAPI: updateRegisters() -- failed to fetch registers: Start = {}; Size = {}", i.regs[0].reg, i.size); continue; } for (auto j : i.regs) { singleRegData.resize(j.size); for (uint16_t k = 0; k < j.size; ++k) { singleRegData[k] = i.rawData[j.offset + k]; } mRegisters->updateRegister(j.reg, singleRegData); if (_numUpdated) { *_numUpdated += 1; } } } return ErrorCode::OK; } //! Convinience wrapper for the other version of this function. ErrorCode ModbusAPI::updateRegisters(vector<uint16_t> _regList, size_t *_numUpdated) { if (mState != State::INITIALIZED) { log::get()->error("ModbusAPI: updateRegisters() -- invalid object state '{}'", enum2Str::toStr(mState)); return ErrorCode::INVALID_STATE; } return updateRegisters(mRegisters->getRegisters(_regList), _numUpdated); } /*! * \brief Sets the modbus register database to use * * \note This function can only be called in the CONFIGURE state * * State change: NONE * * \param _db shared pointer to the DataBase object * \returns OK or INVALID_STATE */ ErrorCode ModbusAPI::setDataBase(std::shared_ptr<DataBase> _db) { if (mState != State::CONFIGURE) { log::get()->error("ModbusAPI: setDataBase() -- invalid object state '{}'", enum2Str::toStr(mState)); return ErrorCode::INVALID_STATE; } if (!_db) { _db = make_shared<DataBase>(SMA_MODBUS_DEFAULT_DB); } mDB = _db; return ErrorCode::OK; } /*! * \brief Sets the modbus register database to use * * \note This function can only be called in the CONFIGURE state * * State change: NONE * * \param _dbPath Path to the database file * \returns OK or INVALID_STATE */ ErrorCode ModbusAPI::setDataBase(string _dbPath) { if (mState != State::CONFIGURE) { log::get()->error("ModbusAPI: setDataBase() -- invalid object state '{}'", enum2Str::toStr(mState)); return ErrorCode::INVALID_STATE; } mDB = make_shared<DataBase>(_dbPath); return ErrorCode::OK; } /*! * \brief Sets the TCP server connection details * * \note This function can only be called in the CONFIGURE state * * State change: NONE * * \param _ip The IP address to use * \param _port The port to use * * \returns OK or INVALID_STATE */ ErrorCode ModbusAPI::setConnectionTCP_IP(string _ip, uint32_t _port) { if (mState != State::CONFIGURE) { log::get()->error("ModbusAPI: setConnectionTCP_IP() -- invalid object state '{}'", enum2Str::toStr(mState)); return ErrorCode::INVALID_STATE; } mConn = make_unique<MBConnectionIP>(_ip, _port); return ErrorCode::OK; } /*! * \brief Sets the TCP IP protocol indemendant server connection details * * \note This function can only be called in the CONFIGURE state * * State change: NONE * * \param _node The server node * \param _service The service * * \returns OK or INVALID_STATE */ ErrorCode ModbusAPI::setConnectionTCP_IP_PI(string _node, string _service) { if (mState != State::CONFIGURE) { log::get()->error("ModbusAPI: setConnectionTCP_IP_PI() -- invalid object state '{}'", enum2Str::toStr(mState)); return ErrorCode::INVALID_STATE; } mConn = make_unique<MBConnectionIP_PI>(_node, _service); return ErrorCode::OK; } /*! * \brief Sets the TCP server connection details * * \note This function can only be called in the CONFIGURE state * * State change: NONE * * \param _device The name of the serial port * \param _baud The baud rate of the communication * \param _parity Partity type: N = None; E = Even; O = Odd * \param _dataBit The number of bits of data, the allowed values are 5, 6, 7 and 8 * \param _stopBit The bits of stop, the allowed values are 1 and 2 * * \returns OK or INVALID_STATE */ ErrorCode ModbusAPI::setConnectionRTU(string _device, uint32_t _baud, char _parity, int _dataBit, int _stopBit) { if (mState != State::CONFIGURE) { log::get()->error("ModbusAPI: setConnectionRTU() -- invalid object state '{}'", enum2Str::toStr(mState)); return ErrorCode::INVALID_STATE; } mConn = make_unique<MBConnectionRTU>(_device, _baud, _parity, _dataBit, _stopBit); return ErrorCode::OK; }
31.331155
120
0.655448
mensinda
649bc7b9df2db5fa10326e05554f6e567ae63f55
741
hh
C++
sw/admin-cli/commands/admin-apply.hh
magetron/cpu-fpga-nwofle
47fb011a1b70a95f18676dc7d51d9b5223c2d4e3
[ "Apache-2.0" ]
44
2021-03-11T18:07:05.000Z
2021-04-15T20:53:21.000Z
sw/admin-cli/commands/admin-apply.hh
magetron/cpu-fpga-nwofle
47fb011a1b70a95f18676dc7d51d9b5223c2d4e3
[ "Apache-2.0" ]
29
2021-01-25T01:41:15.000Z
2021-04-21T14:35:59.000Z
sw/admin-cli/commands/admin-apply.hh
magetron/cpu-fpga-nwofle
47fb011a1b70a95f18676dc7d51d9b5223c2d4e3
[ "Apache-2.0" ]
2
2021-07-27T21:49:42.000Z
2022-01-14T23:37:09.000Z
#pragma once int com_admin_apply (char* arg) { printf("writing admin pkt to %s...\n", ADMIN_PKT_TMP_FILENAME); write_to_admin_pkt(f_curr, ADMIN_PKT_TMP_FILENAME); mac_addr_t srcmac = random_mac(); ip_addr_t srcip = random_local_ip(); ip_addr_t dstip = random_local_ip(); udp_port_t srcport = random_unused_port(); udp_port_t dstport = random_unused_port(); read_file(ADMIN_PKT_TMP_FILENAME); form_packet(srcmac, admin_dst_mac, srcip, dstip, srcport, dstport, file_payload, file_payload_length); trigger_send(); if (check_fpga_filter_matches(f_curr)) { printf("successful! apply confirmed via probing FPGA\n"); } else { printf("failed! apply cannot be confirmed via probing FPGA\n"); } return 0; }
29.64
68
0.739541
magetron
649c19757cdfa81157581520e6f501a82479ee44
911
cpp
C++
cpp/src/network/broker-add.cpp
zlnov/quick-pack
4fffcc56045852b034b60a1185901a001eff87a7
[ "MIT" ]
null
null
null
cpp/src/network/broker-add.cpp
zlnov/quick-pack
4fffcc56045852b034b60a1185901a001eff87a7
[ "MIT" ]
null
null
null
cpp/src/network/broker-add.cpp
zlnov/quick-pack
4fffcc56045852b034b60a1185901a001eff87a7
[ "MIT" ]
null
null
null
#include "broker.hpp" namespace quick_pack{ uint32_t Broker::add_internal_socket(const std::string &p_host, const std::string &p_port, bool p_is_ipv6){ auto sock = new SocketDetail(); sock->bind(p_host, p_port, p_is_ipv6); return this->m_internal_socket_detail_manager.add_socket(sock); } uint32_t Broker::add_external_address(const std::string &p_host, const uint32_t p_port, bool p_is_ipv6){ auto addr = new Address(p_host, p_port, p_is_ipv6); auto addrdetail = new AddressDetail(); addrdetail->m_address = addr; return this->m_external_address_detail_manager.add_addressdetail(addrdetail); } AddressDetail* Broker::add_new_ipv46_address(sockaddr_in6* addr){ auto addrdetail = new AddressDetail(); auto address = new Address(addr); addrdetail->m_address=address; this->m_external_address_detail_manager.add_addressdetail(addrdetail); return addrdetail; } } // namespace quick_pack
35.038462
107
0.782656
zlnov
64a12540259cae2d8ccbd0733f9f922d530d0f46
1,069
hpp
C++
include/bglgen_app.hpp
magicmoremagic/bglgen
aa47b41a2212d7af9c7121ca036dc87389e10e6d
[ "MIT" ]
null
null
null
include/bglgen_app.hpp
magicmoremagic/bglgen
aa47b41a2212d7af9c7121ca036dc87389e10e6d
[ "MIT" ]
null
null
null
include/bglgen_app.hpp
magicmoremagic/bglgen
aa47b41a2212d7af9c7121ca036dc87389e10e6d
[ "MIT" ]
null
null
null
#pragma once #ifndef BE_BGLGEN_BGLGEN_APP_HPP_ #define BE_BGLGEN_BGLGEN_APP_HPP_ #include "lexer.hpp" #include <be/core/lifecycle.hpp> #include <be/core/filesystem.hpp> #include <be/belua/context.hpp> #include <be/sqlite/db.hpp> #include <be/sqlite/static_stmt_cache.hpp> namespace be::bglgen { /////////////////////////////////////////////////////////////////////////////// class BglGenApp final { public: BglGenApp(int argc, char** argv); int operator()(); private: void get_lua_defaults_(); void init_registry_(); void init_extension_regex_(); CoreInitLifecycle init_; be::I8 status_ = 0; belua::Context context_; sqlite::Db db_; std::unique_ptr<sqlite::StaticStmtCache> cache_; Path registry_location_; Path registry_db_location_; bool rebuild_db_ = false; std::vector<S> extensions_; S extension_regex_; std::vector<std::pair<Path, bool>> search_dirs_; std::vector<Path> source_paths_; std::vector<S> lua_chunks_; bool do_process_ = true; Path output_location_; }; } // be::bglgen #endif
20.960784
79
0.664172
magicmoremagic
64a179c03a46437a203c78593d8711ecf0484346
819
cpp
C++
engine/entity.cpp
jarreed0/ArchGE
c995caf86b11f89f45fcfe1027c6068662dfcde0
[ "Apache-2.0" ]
12
2017-02-09T21:03:41.000Z
2021-04-26T14:50:20.000Z
engine/entity.cpp
jarreed0/ArchGE
c995caf86b11f89f45fcfe1027c6068662dfcde0
[ "Apache-2.0" ]
null
null
null
engine/entity.cpp
jarreed0/ArchGE
c995caf86b11f89f45fcfe1027c6068662dfcde0
[ "Apache-2.0" ]
null
null
null
#include "entity.h" Entity::Entity() {} Entity::~Entity() {} void Entity::damage(double d) { health -= d; if(health >= 0) { health = 0; kill(); } } void Entity::heal(double h) { health += h; if(h > maxHealth) { health = maxHealth; } } void Entity::kill() { setHealth(0); deactivate(); } void Entity::deactivate() { active = 0; } void Entity::activate() { active = 1; } void Entity::checkDisplayable(Object screen) { Object obj; obj.setDest(getDetect()); if(col.isTouching(obj, screen)) { setDisplayable(true); } else { setDisplayable(false); } } void Entity::setDetectRange(int r) { setDetectRange(r, r); } void Entity::setDetectRange(int w, int h) { detect.x = getPosX()-w; detect.y = getPosY()-h; detect.w = getPosW()+w+w; detect.h = getPosH()+h+h; }
16.058824
46
0.608059
jarreed0
64a402fb135380ba4476648e6f73fbaabbad02e7
1,871
cpp
C++
src/lab_m1/Tema3/SpotLight.cpp
octaviantorcea/EGC
55dfe03a5be17de1853803a9fde19db7929fdf93
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/lab_m1/Tema3/SpotLight.cpp
octaviantorcea/EGC
55dfe03a5be17de1853803a9fde19db7929fdf93
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/lab_m1/Tema3/SpotLight.cpp
octaviantorcea/EGC
55dfe03a5be17de1853803a9fde19db7929fdf93
[ "MIT", "BSD-3-Clause" ]
null
null
null
#include "SpotLight.h" tema3::SpotLight::SpotLight(glm::vec3 position) { this->position = position; this->direction = glm::vec3(0, -1, 0); this->cutoffAngle = 14.03f; this->color = glm::vec3((float)(rand() % 256) / 256, (float)(rand() % 256) / 256, (float)(rand() % 256) / 256); this->intensity = 3.5f; this->oxAngle = 0; this->oyAngle = 0; this->ozAngle = 0; } tema3::SpotLight::~SpotLight() { } glm::vec3 tema3::SpotLight::getPosition() { return this->position; } glm::vec3 tema3::SpotLight::getDirection() { return this->direction; } float tema3::SpotLight::getCutoffAngle() { return this->cutoffAngle; } glm::vec3 tema3::SpotLight::getColor() { return this->color; } float tema3::SpotLight::getIntensity() { return this->intensity; } float tema3::SpotLight::getOxAngle() { return this->oxAngle; } float tema3::SpotLight::getOyAngle() { return this->oyAngle; } float tema3::SpotLight::getOzAngle() { return this->ozAngle; } void tema3::SpotLight::updateDirection(float deltaTimeSeconds) { float xSpeed = rand() % 3 - 1; float ySpeed = rand() % 3 - 1; float zSpeed = rand() % 3 - 1; if (oxAngle + xSpeed * deltaTimeSeconds >= MIN_ANGLE && oxAngle + xSpeed * deltaTimeSeconds <= MAX_ANGLE) { oxAngle += xSpeed * CHANGE_SPEED; } if (oyAngle + ySpeed * deltaTimeSeconds >= MIN_ANGLE && oyAngle + ySpeed * deltaTimeSeconds <= MAX_ANGLE) { oyAngle += ySpeed * CHANGE_SPEED; } if (ozAngle + zSpeed * deltaTimeSeconds >= MIN_ANGLE && ozAngle + zSpeed * deltaTimeSeconds <= MAX_ANGLE) { ozAngle += zSpeed * CHANGE_SPEED; } glm::mat4 rotateMatrix = glm::mat4(1); rotateMatrix *= RotateOX(RADIANS(oxAngle)); rotateMatrix *= RotateOY(RADIANS(oyAngle)); rotateMatrix *= RotateOZ(RADIANS(ozAngle)); this->direction = rotateMatrix * glm::vec4(0, -1, 0, 1); }
25.630137
113
0.652592
octaviantorcea
64a9f168137c20294775fc2738c7de796044e0fc
1,222
hpp
C++
share/device_code.hpp
venovako/GPUJACHx
dc3cddf7a113d03d2f12b262d3970bf13751ef51
[ "MIT" ]
10
2016-10-19T09:35:22.000Z
2021-06-06T05:50:12.000Z
share/device_code.hpp
venovako/GPUJACHx
dc3cddf7a113d03d2f12b262d3970bf13751ef51
[ "MIT" ]
null
null
null
share/device_code.hpp
venovako/GPUJACHx
dc3cddf7a113d03d2f12b262d3970bf13751ef51
[ "MIT" ]
2
2016-10-10T11:47:17.000Z
2016-10-19T09:35:23.000Z
#ifndef DEVICE_CODE_HPP #define DEVICE_CODE_HPP #include "cuda_helper.hpp" EXTERN_C void defJacL1(const unsigned step, const int definite /* unused */) throw(); EXTERN_C void hypJacL1(const unsigned step, const unsigned npos) throw(); EXTERN_C void defJacL1v(const unsigned step, const int definite /* unused */) throw(); EXTERN_C void hypJacL1v(const unsigned step, const unsigned npos) throw(); EXTERN_C void defJacL1s(const unsigned step, const int definite) throw(); EXTERN_C void hypJacL1s(const unsigned step, const unsigned npos) throw(); EXTERN_C void defJacL1sv(const unsigned step, const int definite) throw(); EXTERN_C void hypJacL1sv(const unsigned step, const unsigned npos) throw(); EXTERN_C void initD(double *const G, double *const D, const unsigned ifc, const unsigned nRow, const unsigned nRank, const unsigned nPos, const unsigned ldG) throw(); EXTERN_C void initV(double *const V, const unsigned ifc, const unsigned nRank, const unsigned ldV) throw(); EXTERN_C void initSymbols(double *const G, double *const V, volatile unsigned long long *const cvg, const unsigned nRow, const unsigned nCol, const unsigned ldG, const unsigned ldV, const unsigned nSwp) throw(); #endif /* !DEVICE_CODE_HPP */
50.916667
211
0.779051
venovako
64aa3c32e332ace5f6889bb4d95a5223c541cbe5
3,826
cpp
C++
trace_server/dock/dockmanagermodel.cpp
mojmir-svoboda/DbgToolkit
590887987d0856032be906068a3103b6ce31d21c
[ "MIT" ]
null
null
null
trace_server/dock/dockmanagermodel.cpp
mojmir-svoboda/DbgToolkit
590887987d0856032be906068a3103b6ce31d21c
[ "MIT" ]
null
null
null
trace_server/dock/dockmanagermodel.cpp
mojmir-svoboda/DbgToolkit
590887987d0856032be906068a3103b6ce31d21c
[ "MIT" ]
null
null
null
#include "dockmanagermodel.h" #include <QString> #include <QMainWindow> #include "dockmanager.h" #include "dock.h" DockManagerModel::DockManagerModel (DockManager & mgr, QObject * parent, tree_data_t * data) : TreeModel<DockedInfo>(parent, data) , m_manager(mgr) { qDebug("%s", __FUNCTION__); } DockManagerModel::~DockManagerModel () { qDebug("%s", __FUNCTION__); } QModelIndex DockManagerModel::testItemWithPath (QStringList const & path) { QString const name = path.join("/"); DockedInfo const * i = 0; if (node_t const * node = m_tree_data->is_present(name, i)) return indexFromItem(node); else return QModelIndex(); } QModelIndex DockManagerModel::insertItemWithPath (QStringList const & path, bool checked) { QString const name = path.join("/"); DockedInfo const * i = 0; node_t const * node = m_tree_data->is_present(name, i); if (node) { //qDebug("%s path=%s already present", __FUNCTION__, path.toStdString().c_str()); return indexFromItem(node); } else { //qDebug("%s path=%s not present, adding", __FUNCTION__, path.toStdString().c_str()); DockedInfo i; i.m_state = checked ? Qt::Checked : Qt::Unchecked; i.m_collapsed = false; //i.m_path = path; node_t * const n = m_tree_data->set_to_state(name, i); QModelIndex const parent_idx = indexFromItem(n->parent); int const last = n->parent->count_childs() - 1; beginInsertRows(parent_idx, last, last); n->data.m_path = path; QModelIndex const idx = indexFromItem(n); endInsertRows(); initData(idx, checked ? Qt::Checked : Qt::Unchecked, Qt::CheckStateRole); //QModelIndex const parent_idx = idx.parent(); //if (parent_idx.isValid()) // emit dataChanged(parent_idx, parent_idx); return idx; } } int DockManagerModel::columnCount (QModelIndex const & parent) const { return DockManager::e_max_dockmgr_column; } Qt::ItemFlags DockManagerModel::flags (QModelIndex const & index) const { return QAbstractItemModel::flags(index) | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable; } /*DockedWidgetBase const * DockManagerModel::getWidgetFromIndex (QModelIndex const & index) const { DockManager const * const mgr = static_cast<DockManager const *>(QObject::parent()); node_t const * const item = itemFromIndex(index); QStringList const & p = item->data.m_path; DockedWidgetBase const * const dwb = m_manager.findDockable(p.join("/")); return dwb; } DockedWidgetBase * DockManagerModel::getWidgetFromIndex (QModelIndex const & index) { DockManager * const mgr = static_cast<DockManager *>(QObject::parent()); node_t const * const item = itemFromIndex(index); QStringList const & p = item->data.m_path; DockedWidgetBase * dwb = m_manager.findDockable(p.join("/")); return dwb; }*/ QVariant DockManagerModel::data (QModelIndex const & index, int role) const { if (!index.isValid()) return QVariant(); int const col = index.column(); if (col == DockManager::e_Column_Name) return TreeModel<DockedInfo>::data(index, role); return QVariant(); } bool DockManagerModel::setData (QModelIndex const & index, QVariant const & value, int role) { if (!index.isValid()) return false; if (role == Qt::CheckStateRole) { node_t const * const n = itemFromIndex(index); QStringList const & dst = n->data.m_path; Action a; a.m_type = e_Visibility; a.m_src_path = m_manager.path(); a.m_src = &m_manager; a.m_dst_path = dst; int const state = value.toInt(); a.m_args.push_back(state); m_manager.handleAction(&a, e_Sync); } return TreeModel<DockedInfo>::setData(index, value, role); } bool DockManagerModel::initData (QModelIndex const & index, QVariant const & value, int role) { return TreeModel<DockedInfo>::setData(index, value, role); } bool DockManagerModel::removeRows (int row, int count, QModelIndex const & parent) { return true; }
27.724638
97
0.717721
mojmir-svoboda
64aa58f0e9b0cf64f0a7e6731fdf27a85ec896ef
1,672
cxx
C++
Applications/SlicerApp/Testing/Cpp/qSlicerAppMainWindowTest1.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
6
2018-10-02T23:52:49.000Z
2019-11-14T08:24:55.000Z
Applications/SlicerApp/Testing/Cpp/qSlicerAppMainWindowTest1.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
Applications/SlicerApp/Testing/Cpp/qSlicerAppMainWindowTest1.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
/*============================================================================== Program: 3D Slicer Copyright (c) Kitware Inc. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. This file was originally developed by Julien Finet, Kitware Inc. and was partially funded by NIH grant 3P41RR013218-12S1 ==============================================================================*/ // Qt includes #include <QTimer> // Slicer includes #include "vtkSlicerConfigure.h" // For Slicer_USE_PYTHONQT // CTK includes #ifdef Slicer_USE_PYTHONQT # include <ctkPythonConsole.h> #endif // SlicerApp includes #include "qSlicerApplication.h" #include "qSlicerAppMainWindow.h" #ifdef Slicer_USE_PYTHONQT # include "qSlicerPythonManager.h" #endif // STD includes int qSlicerAppMainWindowTest1(int argc, char * argv[] ) { qSlicerApplication app(argc, argv); qSlicerAppMainWindow mainWindow; mainWindow.show(); #ifdef Slicer_USE_PYTHONQT // Create python console Q_ASSERT(qSlicerApplication::application()->pythonManager()); ctkPythonConsole pythonConsole; pythonConsole.initialize(qSlicerApplication::application()->pythonManager()); pythonConsole.resize(600, 280); #endif if (argc < 2 || QString(argv[1]) != "-I") { QTimer::singleShot(100, qApp, SLOT(quit())); } return app.exec(); }
26.125
80
0.679426
TheInterventionCentre
64ada9f5bf1aa8d6fec746777a690e6c0365a5e2
354
cpp
C++
system/apps_usb/test64_remote/terminal.cpp
tomwei7/LA104
fdf04061f37693d37e2812ed6074348e65d7e5f9
[ "MIT" ]
336
2018-11-23T23:54:15.000Z
2022-03-21T03:47:05.000Z
system/apps_usb/test64_remote/terminal.cpp
203Null/LA104
b8ae9413d01ea24eafb9fdb420c97511287cbd99
[ "MIT" ]
56
2019-02-01T05:01:07.000Z
2022-03-26T16:00:24.000Z
system/apps_usb/test64_remote/terminal.cpp
203Null/LA104
b8ae9413d01ea24eafb9fdb420c97511287cbd99
[ "MIT" ]
52
2019-02-06T17:05:04.000Z
2022-03-04T12:30:53.000Z
#include "terminal.h" char* pLastChar = nullptr; void CTerminal::begin() { pLastChar = (char*)BIOS::SYS::GetAttribute(BIOS::SYS::EAttribute::LastChar); } void CTerminal::end() { } void CTerminal::write(uint8_t b) { if (pLastChar) *pLastChar = b; } bool CTerminal::available() { return false; } uint8_t CTerminal::read() { return 0; }
11.419355
78
0.661017
tomwei7
64ae7431f0bf9829ea4253d65250409a2a86523d
3,797
cpp
C++
Engine/Source/Developer/StandaloneRenderer/Private/Windows/OpenGL/SlateOpenGLContext.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Developer/StandaloneRenderer/Private/Windows/OpenGL/SlateOpenGLContext.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Developer/StandaloneRenderer/Private/Windows/OpenGL/SlateOpenGLContext.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "StandaloneRendererPrivate.h" #include "OpenGL/SlateOpenGLRenderer.h" /** * A dummy wndproc. */ static LRESULT CALLBACK DummyGLWndproc(HWND hWnd, uint32 Message, WPARAM wParam, LPARAM lParam) { return DefWindowProc(hWnd, Message, wParam, lParam); } /** * Create a dummy window used to construct OpenGL contexts. */ static HWND CreateDummyGLWindow() { const TCHAR* WindowClassName = TEXT("DummyGLWindow"); // Register a dummy window class. static bool bInitializedWindowClass = false; if (!bInitializedWindowClass) { WNDCLASS wc; bInitializedWindowClass = true; FMemory::Memzero(wc); wc.style = CS_OWNDC; wc.lpfnWndProc = DummyGLWndproc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = NULL; wc.hIcon = NULL; wc.hCursor = NULL; wc.hbrBackground = (HBRUSH)(COLOR_MENUTEXT); wc.lpszMenuName = NULL; wc.lpszClassName = WindowClassName; ATOM ClassAtom = ::RegisterClass(&wc); check(ClassAtom); } // Create a dummy window. HWND WindowHandle = CreateWindowEx( WS_EX_WINDOWEDGE, WindowClassName, NULL, WS_POPUP, 0, 0, 1, 1, NULL, NULL, NULL, NULL); check(WindowHandle); return WindowHandle; } FSlateOpenGLContext::FSlateOpenGLContext() : WindowHandle(NULL) , WindowDC(NULL) , Context(NULL) , bReleaseWindowOnDestroy(false) { } FSlateOpenGLContext::~FSlateOpenGLContext() { Destroy(); } void FSlateOpenGLContext::Initialize( void* InWindow, const FSlateOpenGLContext* SharedContext ) { WindowHandle = (HWND)InWindow; if( WindowHandle == NULL ) { WindowHandle = CreateDummyGLWindow(); bReleaseWindowOnDestroy = true; } // Create a pixel format descriptor for this window PIXELFORMATDESCRIPTOR PFD; FMemory::Memzero( &PFD, sizeof(PIXELFORMATDESCRIPTOR) ); PFD.nSize = sizeof(PIXELFORMATDESCRIPTOR); PFD.nVersion = 1; PFD.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL| PFD_DOUBLEBUFFER; PFD.iPixelType = PFD_TYPE_RGBA; PFD.cColorBits = 32; PFD.cStencilBits = 0; PFD.cDepthBits = 0; PFD.iLayerType = PFD_MAIN_PLANE; WindowDC = GetDC( WindowHandle ); check(WindowDC); // Get the pixel format for this window based on our descriptor uint32 PixelFormat = ChoosePixelFormat( WindowDC, &PFD ); // Ensure a pixel format could be found check(PixelFormat); BOOL Result = SetPixelFormat( WindowDC, PixelFormat, &PFD ); // Ensure the pixel format could be set on this window check(Result); Context = wglCreateContext( WindowDC ); // Make the new window active for drawing. We can't call any OpenGL functions without an active rendering context Result = wglMakeCurrent( WindowDC, Context ); check( Result ); #pragma warning(push) #pragma warning(disable:4191) wglCreateContextAttribsARB = ( PFNWGLCREATECONTEXTATTRIBSARBPROC )wglGetProcAddress( "wglCreateContextAttribsARB" ); #pragma warning(pop) check( wglCreateContextAttribsARB ); int32 ContextAttribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 2, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, 0 }; HGLRC OldContext = Context; Context = wglCreateContextAttribsARB( WindowDC, SharedContext ? SharedContext->Context : NULL, ContextAttribs ); wglMakeCurrent( NULL, NULL ); wglDeleteContext( OldContext ); wglMakeCurrent( WindowDC, Context ); } void FSlateOpenGLContext::Destroy() { if( WindowHandle != NULL ) { wglMakeCurrent( NULL, NULL ); wglDeleteContext( Context ); ReleaseDC( WindowHandle, WindowDC ); WindowDC = NULL; Context = NULL; if( bReleaseWindowOnDestroy ) { DestroyWindow( WindowHandle ); } WindowHandle = NULL; } } void FSlateOpenGLContext::MakeCurrent() { wglMakeCurrent( WindowDC, Context ); }
24.496774
117
0.748222
PopCap
64b24a31db88050645d1dc6aec0a59e2900e0c97
1,227
hh
C++
CommTrackingObjects/coordination/src-gen/TrackerCoordinateService/TrackerCoordinateServiceCore.hh
Servicerobotics-Ulm/DomainModelsRepositories
7cc2bd5d4f9a11275721e77b6bd5164b9ff2bb7b
[ "BSD-3-Clause" ]
null
null
null
CommTrackingObjects/coordination/src-gen/TrackerCoordinateService/TrackerCoordinateServiceCore.hh
Servicerobotics-Ulm/DomainModelsRepositories
7cc2bd5d4f9a11275721e77b6bd5164b9ff2bb7b
[ "BSD-3-Clause" ]
2
2020-08-20T14:49:47.000Z
2020-10-07T16:10:07.000Z
CommTrackingObjects/coordination/src-gen/TrackerCoordinateService/TrackerCoordinateServiceCore.hh
Servicerobotics-Ulm/DomainModelsRepositories
7cc2bd5d4f9a11275721e77b6bd5164b9ff2bb7b
[ "BSD-3-Clause" ]
8
2018-06-25T08:41:28.000Z
2020-08-13T10:39:30.000Z
#ifndef TRACKERCOORDINATESERVICECORE_H_ #define TRACKERCOORDINATESERVICECORE_H_ #include "aceSmartSoft.hh" #include "runTimeInterface.hh" #include <string> #include <map> #include <iostream> #include "TrackerCoordinateService.hh" class TrackerCoordinateServiceCore { friend class ACE_Singleton<TrackerCoordinateServiceCore, ACE_Thread_Mutex>; private: TrackerCoordinateServiceCore (){ std::cout<<"Create TrackerCoordinateService Module Singelton..."<<std::endl; } ~TrackerCoordinateServiceCore (){ std::cout<<"Destroy TrackerCoordinateService Module Singelton..."<<std::endl; } std::map<std::string, TrackerCoordinateService, ciLessLibC> ciInstanceMap; public: void addNewModuleInstance(const std::string& name); int initCiInstance(SmartACE::SmartComponent * component, const std::string& ciInstanceName, const std::map< std::string, CiConnection, ciLessLibC> &ciConnectionsMap); int finiCiInstance(const std::string& ciInstanceName); std::string switchCi(const std::string& ciInstanceName, const std::string& componentName, const std::string& componentInstanceName, const std::string& service, const std::string& parameter, const std::string& eventMode); }; #endif /* TRACKERCOORDINATESERVICECORE_H_ */
39.580645
221
0.792991
Servicerobotics-Ulm
64b2ee47e183ef510bfa1b03149072d61a16d279
2,118
cpp
C++
AnimationEditor/Model.cpp
RavioliFinoli/AnimationEditor
d106371c1307661611d6783d8891e9ac52ffd1a9
[ "MIT" ]
null
null
null
AnimationEditor/Model.cpp
RavioliFinoli/AnimationEditor
d106371c1307661611d6783d8891e9ac52ffd1a9
[ "MIT" ]
null
null
null
AnimationEditor/Model.cpp
RavioliFinoli/AnimationEditor
d106371c1307661611d6783d8891e9ac52ffd1a9
[ "MIT" ]
null
null
null
#include "Model.h" #define CLIP(x) (x.clip) namespace AE { Model::Model() { using namespace DirectX; m_InputLayout->Release(); m_VertexBuffer->Release(); m_Translation = { 0.0f, 0.0f, 0.0f, 1.0f }; m_RotationQuaternion = { 0.0f, 0.0f, 0.0f, 1.0f }; m_Scale = { 1.0f, 1.0f, 1.0f, 0.0f }; XMStoreFloat4x4A(&m_WorldMatrix, XMMatrixIdentity()); } Model::Model(const ComPtr<ID3D11Buffer>& buffer, const ComPtr<ID3D11InputLayout>& layout, uint32_t vertexCount) : m_VertexBuffer(buffer), m_InputLayout(layout), m_VertexCount(vertexCount) { using namespace DirectX; m_Translation = {0.0f, 0.0f, 0.0f, 1.0f}; m_RotationQuaternion = {0.0f, 0.0f, 0.0f, 1.0f}; m_Scale = {1.0f, 1.0f, 1.0f, 0.0f}; XMStoreFloat4x4A(&m_WorldMatrix, XMMatrixIdentity()); } Model::~Model() { } void Model::SetPosition(DirectX::XMFLOAT4A newPosition) { m_Translation = newPosition; } void Model::SetRotation(DirectX::XMFLOAT4A newRotation) { m_RotationQuaternion = newRotation; } void Model::SetScale(float newScale) { m_Scale = { newScale, newScale, newScale, 0.0 }; } void Model::SetVertexBuffer(const ComPtr<ID3D11Buffer>& buffer) { m_VertexBuffer = buffer; } void Model::SetVertexCount(uint32_t count) { m_VertexCount = count; } void Model::SetVertexLayout(const ComPtr<ID3D11InputLayout>& layout) { m_InputLayout = layout; } DirectX::XMFLOAT4X4A Model::GetWorldMatrix() { using namespace DirectX; XMVECTOR t = XMLoadFloat4A(&m_Translation); XMVECTOR r = XMLoadFloat4A(&m_RotationQuaternion); XMVECTOR s = XMLoadFloat4A(&m_Scale); XMStoreFloat4x4A(&m_WorldMatrix, DirectX::XMMatrixAffineTransformation(s, XMVectorZero(), r, t)); return m_WorldMatrix; } const ComPtr<ID3D11Buffer>& Model::GetVertexBuffer() { return m_VertexBuffer; } uint32_t Model::GetVertexCount() { return m_VertexCount; } float Model::GetScale() { return m_Scale.x; } void Model::ToggleDrawState() { m_bDraw = !m_bDraw; } void Model::SetDrawState(bool state) { m_bDraw = state; } bool Model::GetDrawState() { return m_bDraw; } }
19.611111
188
0.695467
RavioliFinoli
64bed4d325d43fbf2738fc9ffefed2f7c30bcc82
3,711
cc
C++
connectivity/shill/eap_listener.cc
Keneral/asystem
df12381b72ef3d629c8efc61100cc8c714195320
[ "Unlicense" ]
null
null
null
connectivity/shill/eap_listener.cc
Keneral/asystem
df12381b72ef3d629c8efc61100cc8c714195320
[ "Unlicense" ]
null
null
null
connectivity/shill/eap_listener.cc
Keneral/asystem
df12381b72ef3d629c8efc61100cc8c714195320
[ "Unlicense" ]
null
null
null
// // Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "shill/eap_listener.h" #include <linux/if_ether.h> #include <linux/if_packet.h> #include <netinet/in.h> #include <base/bind.h> #include <base/compiler_specific.h> #include "shill/eap_protocol.h" #include "shill/event_dispatcher.h" #include "shill/logging.h" #include "shill/net/sockets.h" namespace shill { const size_t EapListener::kMaxEapPacketLength = sizeof(eap_protocol::Ieee8021xHdr) + sizeof(eap_protocol::EapHeader); EapListener::EapListener(EventDispatcher* event_dispatcher, int interface_index) : dispatcher_(event_dispatcher), interface_index_(interface_index), sockets_(new Sockets()), socket_(-1) {} EapListener::~EapListener() {} bool EapListener::Start() { if (!CreateSocket()) { LOG(ERROR) << "Could not open EAP listener socket."; Stop(); return false; } receive_request_handler_.reset( dispatcher_->CreateReadyHandler( socket_, IOHandler::kModeInput, base::Bind(&EapListener::ReceiveRequest, base::Unretained(this)))); return true; } void EapListener::Stop() { receive_request_handler_.reset(); socket_closer_.reset(); socket_ = -1; } bool EapListener::CreateSocket() { int socket = sockets_->Socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_PAE)); if (socket == -1) { PLOG(ERROR) << "Could not create EAP listener socket"; return false; } socket_ = socket; socket_closer_.reset(new ScopedSocketCloser(sockets_.get(), socket_)); if (sockets_->SetNonBlocking(socket_) != 0) { PLOG(ERROR) << "Could not set socket to be non-blocking"; return false; } sockaddr_ll socket_address; memset(&socket_address, 0, sizeof(socket_address)); socket_address.sll_family = AF_PACKET; socket_address.sll_protocol = htons(ETH_P_PAE); socket_address.sll_ifindex = interface_index_; if (sockets_->Bind(socket_, reinterpret_cast<struct sockaddr*>(&socket_address), sizeof(socket_address)) != 0) { PLOG(ERROR) << "Could not bind socket to interface"; return false; } return true; } void EapListener::ReceiveRequest(int fd) { struct ALIGNAS(1) { eap_protocol::Ieee8021xHdr onex_header; eap_protocol::EapHeader eap_header; } payload; sockaddr_ll remote_address; memset(&remote_address, 0, sizeof(remote_address)); socklen_t socklen = sizeof(remote_address); int result = sockets_->RecvFrom( socket_, &payload, sizeof(payload), 0, reinterpret_cast<struct sockaddr*>(&remote_address), &socklen); if (result < 0) { PLOG(ERROR) << "Socket recvfrom failed"; Stop(); return; } if (result != sizeof(payload)) { LOG(INFO) << "Short EAP packet received"; return; } if (payload.onex_header.version < eap_protocol::kIeee8021xEapolVersion1 || payload.onex_header.type != eap_protocol::kIIeee8021xTypeEapPacket || payload.eap_header.code != eap_protocol::kEapCodeRequest) { LOG(INFO) << "Packet is not a valid EAP request"; return; } request_received_callback_.Run(); } } // namespace shill
28.113636
76
0.696308
Keneral
64c903dfe153efa5eeb4d0fc68aaaab237c92159
8,060
cpp
C++
src/cpp/SPL/Core/TupleTypeModelImpl.cpp
IBMStreams/OSStreams
c6287bd9ec4323f567d2faf59125baba8604e1db
[ "Apache-2.0" ]
10
2021-02-19T20:19:24.000Z
2021-09-16T05:11:50.000Z
src/cpp/SPL/Core/TupleTypeModelImpl.cpp
xguerin/openstreams
7000370b81a7f8778db283b2ba9f9ead984b7439
[ "Apache-2.0" ]
7
2021-02-20T01:17:12.000Z
2021-06-08T14:56:34.000Z
src/cpp/SPL/Core/TupleTypeModelImpl.cpp
IBMStreams/OSStreams
c6287bd9ec4323f567d2faf59125baba8604e1db
[ "Apache-2.0" ]
4
2021-02-19T18:43:10.000Z
2022-02-23T14:18:16.000Z
/* * Copyright 2021 IBM 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 <SPL/Core/TupleTypeModelImpl.h> #include <SPL/Core/tupleTypeModel.h> #include <SPL/FrontEnd/Typ.h> using namespace std; using namespace SPL; using namespace SPL::TupleType; static bool isScalar(const RootTyp& type) { switch (type.getMetaType()) { case MetaType::TUPLE: case MetaType::LIST: case MetaType::BLIST: case MetaType::SET: case MetaType::BSET: case MetaType::MAP: case MetaType::BMAP: case MetaType::OPTIONAL: return false; default:; } return true; } static auto_ptr<tupletypemodel::listOrSetType> doListOrSet(const RootTyp& type); static auto_ptr<tupletypemodel::typeType> doTypeType(const RootTyp& type); static auto_ptr<tupletypemodel::tupleType> doTuple(const TupleTyp& type); static auto_ptr<tupletypemodel::mapType> doMap(const RootTyp& type); static auto_ptr<tupletypemodel::optionalType> doOptional(const OptionalTyp& type); static void doElementType(tupletypemodel::listOrSetType& lst, const RootTyp& type) { switch (type.getMetaType()) { case MetaType::TUPLE: lst.tuple(doTuple(type.as<TupleTyp>())); break; case MetaType::LIST: case MetaType::BLIST: lst.list(doListOrSet(type)); break; case MetaType::SET: case MetaType::BSET: lst.set(doListOrSet(type)); break; case MetaType::MAP: case MetaType::BMAP: lst.map(doMap(type)); break; case MetaType::OPTIONAL: lst.optional(doOptional(type.as<OptionalTyp>())); break; default:; break; } } static void doElementType(tupletypemodel::optionalType& ot, const RootTyp& type) { switch (type.getMetaType()) { case MetaType::TUPLE: ot.tuple(doTuple(type.as<TupleTyp>())); break; case MetaType::LIST: case MetaType::BLIST: ot.list(doListOrSet(type)); break; case MetaType::SET: case MetaType::BSET: ot.set(doListOrSet(type)); break; case MetaType::MAP: case MetaType::BMAP: ot.map(doMap(type)); break; default:; break; } } static auto_ptr<tupletypemodel::optionalType> doOptional(const OptionalTyp& type) { auto_ptr<tupletypemodel::optionalType> ot(new tupletypemodel::optionalType); const RootTyp& underlyingType = type.getUnderlyingType(); if (isScalar(underlyingType)) { ot->type(underlyingType.getName()); } else { doElementType(*ot, underlyingType); } return ot; } static auto_ptr<tupletypemodel::listOrSetType> doListOrSet(const RootTyp& type) { auto_ptr<tupletypemodel::listOrSetType> ls(new tupletypemodel::listOrSetType); switch (type.getMetaType()) { case MetaType::LIST: { const ListTyp& lt = type.as<ListTyp>(); const RootTyp& elem = lt.getElementType(); if (isScalar(elem)) ls->elementType(elem.getName()); else doElementType(*ls, elem); } break; case MetaType::BLIST: { const BListTyp& lt = type.as<BListTyp>(); const RootTyp& elem = lt.getElementType(); ls->bound(lt.getBoundSize()); if (isScalar(elem)) ls->elementType(elem.getName()); else doElementType(*ls, elem); } break; case MetaType::SET: { const SetTyp& st = type.as<SetTyp>(); const RootTyp& elem = st.getElementType(); if (isScalar(elem)) ls->elementType(elem.getName()); else doElementType(*ls, elem); } break; case MetaType::BSET: { const BSetTyp& lt = type.as<BSetTyp>(); const RootTyp& elem = lt.getElementType(); ls->bound(lt.getBoundSize()); if (isScalar(elem)) ls->elementType(elem.getName()); else doElementType(*ls, elem); } break; default:; break; } return ls; } static auto_ptr<tupletypemodel::mapType> doMap(const RootTyp& type) { auto_ptr<tupletypemodel::mapType> m(new tupletypemodel::mapType); if (type.getMetaType() == MetaType::MAP) { const MapTyp& mt = type.as<MapTyp>(); const RootTyp& key = mt.getKeyType(); if (isScalar(key)) m->keyType(key.getName()); else m->key(doTypeType(key)); const RootTyp& value = mt.getValueType(); if (isScalar(value)) m->valueType(value.getName()); else m->value(doTypeType(value)); } else { const BMapTyp& mt = type.as<BMapTyp>(); m->bound(mt.getBoundSize()); const RootTyp& key = mt.getKeyType(); if (isScalar(key)) m->keyType(key.getName()); else m->key(doTypeType(key)); const RootTyp& value = mt.getValueType(); if (isScalar(value)) m->valueType(value.getName()); else m->value(doTypeType(value)); } return m; } static void doElementType(tupletypemodel::attrType& at, const RootTyp& type) { switch (type.getMetaType()) { case MetaType::TUPLE: at.tuple(doTuple(type.as<TupleTyp>())); break; case MetaType::LIST: case MetaType::BLIST: at.list(doListOrSet(type)); break; case MetaType::SET: case MetaType::BSET: at.set(doListOrSet(type)); break; case MetaType::MAP: case MetaType::BMAP: at.map(doMap(type)); break; case MetaType::OPTIONAL: at.optional(doOptional(type.as<OptionalTyp>())); default:; break; } } static auto_ptr<tupletypemodel::tupleType> doTuple(const TupleTyp& type) { auto_ptr<tupletypemodel::tupleType> t(new tupletypemodel::tupleType); for (uint32_t i = 0, ui = type.getNumberOfAttributes(); i < ui; i++) { auto_ptr<tupletypemodel::attrType> at(new tupletypemodel::attrType()); at->name(type.getAttributeName(i)); const RootTyp& attrType = type.getAttributeType(i); if (isScalar(attrType)) at->type(attrType.getName()); else { // need to create the subtype doElementType(*at, attrType); } t->attr().push_back(at); } return t; } static auto_ptr<tupletypemodel::typeType> doTypeType(const RootTyp& type) { auto_ptr<tupletypemodel::typeType> tt(new tupletypemodel::typeType); switch (type.getMetaType()) { case MetaType::TUPLE: tt->tuple(doTuple(type.as<TupleTyp>())); break; case MetaType::LIST: case MetaType::BLIST: tt->list(doListOrSet(type)); break; case MetaType::SET: case MetaType::BSET: tt->set(doListOrSet(type)); break; case MetaType::MAP: case MetaType::BMAP: tt->map(doMap(type)); break; case MetaType::OPTIONAL: tt->optional(doOptional(type.as<OptionalTyp>())); break; default:; } return tt; } auto_ptr<tupletypemodel::tupleType> TupleTypeModel::toXsdInstance() const { return doTuple(_tuple); }
31
82
0.585608
IBMStreams
64cbbd932adae5e4ba8c99bedcf37305053e919f
1,129
hpp
C++
ch12/Queue.hpp
bashell/CppStandardLibrary
2aae03019288132c911036aeb9ba36edc56e510b
[ "MIT" ]
null
null
null
ch12/Queue.hpp
bashell/CppStandardLibrary
2aae03019288132c911036aeb9ba36edc56e510b
[ "MIT" ]
null
null
null
ch12/Queue.hpp
bashell/CppStandardLibrary
2aae03019288132c911036aeb9ba36edc56e510b
[ "MIT" ]
null
null
null
#ifndef QUEUE_HPP #define QUEUE_HPP #include <deque> #include <exception> template <typename T> class Queue { protected: std::deque<T> c; // container for the elements public: // exception class for pop() and front() with empty queue class ReadEmptyQueue : public std::exception { public: virtual const char* what() const throw() { return "read empty queue"; } }; // number of elements typename std::deque<T>::size_type size() const { return c.size(); } // is queue empty? bool empty() const { return c.empty(); } // insert element into the queue void push(const T &elem) { c.push_back(elem); } // remove next element from the queue and return its value T pop() { if(c.empty()) { throw ReadEmptyQueue(); } T elem(c.front()); c.pop_front(); return elem; } // return value of next element T& front() { if(c.empty()) { throw ReadEmptyQueue(); } return c.front(); } }; #endif /* QUEUE_HPP */
20.160714
62
0.545616
bashell
64cbf46dc282a5b8b420948d0cb48f6f1718aa3b
5,764
cpp
C++
src/Broadcaster2006/Manager/HDView.cpp
pedroroque/DigitalBroadcaster
279e65b348421dcd8db53ebb588154b85dc169e9
[ "MIT" ]
null
null
null
src/Broadcaster2006/Manager/HDView.cpp
pedroroque/DigitalBroadcaster
279e65b348421dcd8db53ebb588154b85dc169e9
[ "MIT" ]
null
null
null
src/Broadcaster2006/Manager/HDView.cpp
pedroroque/DigitalBroadcaster
279e65b348421dcd8db53ebb588154b85dc169e9
[ "MIT" ]
null
null
null
// HDView.cpp : implementation file // #include "stdafx.h" #include "Manager.h" #include "HDView.h" #include "Folder.h" #include "..\include\rspath.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern CString g_strMainConnect; extern CImageList *g_ilTree; ///////////////////////////////////////////////////////////////////////////// // CHDView IMPLEMENT_DYNCREATE(CHDView, CListView) CHDView::CHDView() { } CHDView::~CHDView() { } BEGIN_MESSAGE_MAP(CHDView, CListView) //{{AFX_MSG_MAP(CHDView) ON_WM_CREATE() ON_NOTIFY_REFLECT(NM_DBLCLK, OnDblclk) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CHDView drawing void CHDView::OnDraw(CDC* pDC) { CDocument* pDoc = GetDocument(); // TODO: add draw code here } ///////////////////////////////////////////////////////////////////////////// // CHDView diagnostics #ifdef _DEBUG void CHDView::AssertValid() const { CListView::AssertValid(); } void CHDView::Dump(CDumpContext& dc) const { CListView::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CHDView message handlers void CHDView::OnInitialUpdate() { CListView::OnInitialUpdate(); CListCtrl *pList = &GetListCtrl(); CString strTemp; strTemp.LoadString(IDS_FOLDERMANAGMENT); GetDocument()->SetTitle(strTemp); strTemp.LoadString(IDS_PATH); pList->InsertColumn(1,strTemp,LVCFMT_LEFT,250); strTemp.LoadString(IDS_MUSIC); pList->InsertColumn(2,strTemp,LVCFMT_CENTER,50); strTemp.LoadString(IDS_JINGLES); pList->InsertColumn(3,strTemp,LVCFMT_CENTER,50); strTemp.LoadString(IDS_SPOTS); pList->InsertColumn(4,strTemp,LVCFMT_CENTER,50); strTemp.LoadString(IDS_RMS); pList->InsertColumn(5,strTemp,LVCFMT_CENTER,50); strTemp.LoadString(IDS_TAKES); pList->InsertColumn(5,strTemp,LVCFMT_CENTER,50); strTemp.LoadString(IDS_TIME); pList->InsertColumn(6,strTemp,LVCFMT_CENTER,50); strTemp.LoadString(IDS_PRODUCER); pList->InsertColumn(7,strTemp,LVCFMT_CENTER,50); CRSPath rs(g_strMainConnect); int Pos=0; rs.m_strSort="Music desc, Jingles desc, Spots desc, RMs desc, Takes desc, timesignal desc, producer desc, Path"; rs.Open(); while( !rs.IsEOF() ) { rs.m_Path.TrimRight(); pList->InsertItem(Pos,rs.m_Path,22); pList->SetItemData(Pos,rs.m_ID); if( rs.m_Music ) pList->SetItem(Pos,1,LVIF_IMAGE,"",17,0,0,0); if( rs.m_Jingles ) pList->SetItem(Pos,2,LVIF_IMAGE,"",4,0,0,0); if( rs.m_Spots ) pList->SetItem(Pos,3,LVIF_IMAGE,"",1,0,0,0); if( rs.m_RMs ) pList->SetItem(Pos,4,LVIF_IMAGE,"",9,0,0,0); if( rs.m_Takes ) pList->SetItem(Pos,5,LVIF_IMAGE,"",5,0,0,0); if( rs.m_TimeSignal ) pList->SetItem(Pos,6,LVIF_IMAGE,"",3,0,0,0); if( rs.m_Producer ) pList->SetItem(Pos,7,LVIF_IMAGE,"",7,0,0,0); rs.MoveNext(); Pos++; } } int CHDView::OnCreate(LPCREATESTRUCT lpCreateStruct) { lpCreateStruct->style|=LVS_REPORT|LVS_SINGLESEL|LVS_SHOWSELALWAYS; if (CListView::OnCreate(lpCreateStruct) == -1) return -1; CListCtrl *pList = &GetListCtrl(); pList->SetImageList(g_ilTree,LVSIL_SMALL); ListView_SetExtendedListViewStyleEx(this->m_hWnd,LVS_EX_SUBITEMIMAGES|LVS_EX_FULLROWSELECT,LVS_EX_SUBITEMIMAGES|LVS_EX_FULLROWSELECT); return 0; } void CHDView::OnDblclk(NMHDR* pNMHDR, LRESULT* pResult) { CListCtrl *pList = &GetListCtrl(); int nPos = pList->GetNextItem(-1,LVNI_SELECTED); if( nPos == -1 ) return; long int lID = pList->GetItemData(nPos); CRSPath rs( g_strMainConnect ); CFolder dlg; rs.m_strFilter.Format("ID = '%d'",lID); rs.Open(); dlg.m_strPath = rs.m_Path; dlg.m_strPath.TrimRight(); dlg.m_bJingles = rs.m_Jingles; dlg.m_bMusic = rs.m_Music; dlg.m_bProducer = rs.m_Producer; dlg.m_bRMs = rs.m_RMs; dlg.m_bSpots = rs.m_Spots; dlg.m_bTakes = rs.m_Takes; dlg.m_bTime = rs.m_TimeSignal; if( dlg.DoModal()==IDOK ) { rs.Edit(); rs.m_Path = dlg.m_strPath; rs.m_Jingles = (dlg.m_bJingles==0) ? 0:1; rs.m_Music = (dlg.m_bMusic==0) ? 0:1; rs.m_Producer = (dlg.m_bProducer==0) ? 0:1; rs.m_RMs = (dlg.m_bRMs==0) ? 0:1; rs.m_Spots = (dlg.m_bSpots==0) ? 0:1; rs.m_Takes = (dlg.m_bTakes==0) ? 0:1; rs.m_TimeSignal = (dlg.m_bTime==0) ? 0:1; rs.Update(); Refresh(); } if( pResult!=NULL ) *pResult = 0; } void CHDView::Refresh() { CListCtrl *pList = &GetListCtrl(); pList->DeleteAllItems(); CRSPath rs(g_strMainConnect); int Pos=0; rs.m_strSort="Music desc, Jingles desc, Spots desc, RMs desc, Takes desc, timesignal desc, producer desc, Path"; rs.Open(); while( !rs.IsEOF() ) { rs.m_Path.TrimRight(); pList->InsertItem(Pos,rs.m_Path,22); pList->SetItemData(Pos,rs.m_ID); if( rs.m_Music ) pList->SetItem(Pos,1,LVIF_IMAGE,"",17,0,0,0); if( rs.m_Jingles ) pList->SetItem(Pos,2,LVIF_IMAGE,"",4,0,0,0); if( rs.m_Spots ) pList->SetItem(Pos,3,LVIF_IMAGE,"",1,0,0,0); if( rs.m_RMs ) pList->SetItem(Pos,4,LVIF_IMAGE,"",9,0,0,0); if( rs.m_Takes ) pList->SetItem(Pos,5,LVIF_IMAGE,"",5,0,0,0); if( rs.m_TimeSignal ) pList->SetItem(Pos,6,LVIF_IMAGE,"",3,0,0,0); if( rs.m_Producer ) pList->SetItem(Pos,7,LVIF_IMAGE,"",7,0,0,0); rs.MoveNext(); Pos++; } } void CHDView::AddFolder() { CFolder dlg; if( dlg.DoModal()==IDOK ) { CRSPath rs( g_strMainConnect ); rs.Open(); rs.AddNew(); rs.m_Path = dlg.m_strPath; rs.m_Jingles = (dlg.m_bJingles==0) ? 0:1; rs.m_Music = (dlg.m_bMusic==0) ? 0:1; rs.m_Producer = (dlg.m_bProducer==0) ? 0:1; rs.m_RMs = (dlg.m_bRMs==0) ? 0:1; rs.m_Spots = (dlg.m_bSpots==0) ? 0:1; rs.m_Takes = (dlg.m_bTakes==0) ? 0:1; rs.m_TimeSignal = (dlg.m_bTime==0) ? 0:1; rs.Update(); rs.Close(); Refresh(); } }
21.669173
135
0.6466
pedroroque
64ce8846ecf5e0b61a7aced169974e31679ab830
533
hpp
C++
include/ampi/coro/stdcoro.hpp
palebedev/ampi
a7feb7f4b51469fd24ff0fa2c8a9b8592cbf309a
[ "Apache-2.0" ]
null
null
null
include/ampi/coro/stdcoro.hpp
palebedev/ampi
a7feb7f4b51469fd24ff0fa2c8a9b8592cbf309a
[ "Apache-2.0" ]
null
null
null
include/ampi/coro/stdcoro.hpp
palebedev/ampi
a7feb7f4b51469fd24ff0fa2c8a9b8592cbf309a
[ "Apache-2.0" ]
1
2021-03-30T15:49:55.000Z
2021-03-30T15:49:55.000Z
// Copyright 2021 Pavel A. Lebedev // Licensed under the Apache License, Version 2.0. // (See accompanying file LICENSE.txt or copy at // http://www.apache.org/licenses/LICENSE-2.0) // SPDX-License-Identifier: Apache-2.0 #ifndef UUID_2B9E0A06_885B_41B9_B4DB_2D184249766E #define UUID_2B9E0A06_885B_41B9_B4DB_2D184249766E #if __has_include(<coroutine>) #include <coroutine> namespace ampi { namespace stdcoro = std; } #else #include <experimental/coroutine> namespace ampi { namespace stdcoro = std::experimental; } #endif #endif
28.052632
57
0.778612
palebedev
64d050a7a7f0368e37d4ca709d81ce13dd4557c3
995
cpp
C++
lang/C++/99-bottles-of-beer-5.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
25
2015-07-31T18:40:20.000Z
2020-01-29T20:06:35.000Z
lang/C++/99-bottles-of-beer-5.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
2
2015-08-20T13:35:01.000Z
2016-05-23T07:06:38.000Z
lang/C++/99-bottles-of-beer-5.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
21
2015-07-31T23:38:47.000Z
2020-10-02T06:57:15.000Z
//>,_ //Beer Song>,_ #include <iostream> using namespace std; int main(){ for( int b=-1; b<99; cout << '\n') for ( int w=0; w<3; cout << ".\n"){ if (w==2) cout << (( b--) ?"Take one dow" "n and pass it arou" "nd":"Go to the sto" "re and buy some mo" "re"); if (b<0) b=99 ; do{ if (w) cout << ", "; if (b) cout << b; else cout << ( (w) ? 'n' : 'N') << "o more"; cout << " bottle" ; if (b!=1) cout << 's' ; cout << " of beer"; if (w!=1) cout << " on th" "e wall" ;} while (!w++);} return 0 ; } // // by barrym 2011-05-01 // no bottles were harmed in the // making of this program!!!
26.184211
42
0.300503
ethansaxenian
64d87c98347348152c2e9be766e005bdba090924
4,085
cpp
C++
rai/GeoOptim/geoOptim.cpp
bgheneti/rai
4ac7c8444da0c30b141cf40ffed4414ef1ca3e81
[ "MIT" ]
null
null
null
rai/GeoOptim/geoOptim.cpp
bgheneti/rai
4ac7c8444da0c30b141cf40ffed4414ef1ca3e81
[ "MIT" ]
null
null
null
rai/GeoOptim/geoOptim.cpp
bgheneti/rai
4ac7c8444da0c30b141cf40ffed4414ef1ca3e81
[ "MIT" ]
null
null
null
/* ------------------------------------------------------------------ Copyright (c) 2017 Marc Toussaint email: marc.toussaint@informatik.uni-stuttgart.de This code is distributed under the MIT License. Please see <root-path>/LICENSE for details. -------------------------------------------------------------- */ #include <Optim/constrained.h> #include "geoOptim.h" void fitSSBox(arr& x, double& f, double& g, const arr& X, int verbose) { struct fitSSBoxProblem : ConstrainedProblem { const arr& X; fitSSBoxProblem(const arr& X):X(X) {} void phi(arr& phi, arr& J, arr& H, ObjectiveTypeA& tt, const arr& x, arr& lambda) { phi.resize(5+X.d0); if(!!tt) { tt.resize(5+X.d0); tt=OT_ineq; } if(!!J) { J.resize(5+X.d0,11); J.setZero(); } if(!!H) { H.resize(11,11); H.setZero(); } //-- the scalar objective double a=x(0), b=x(1), c=x(2), r=x(3); //these are box-wall-coordinates --- not WIDTH! phi(0) = a*b*c + 2.*r*(a*b + a*c +b*c) + 4./3.*r*r*r; if(!!tt) tt(0) = OT_f; if(!!J) { J(0,0) = b*c + 2.*r*(b+c); J(0,1) = a*c + 2.*r*(a+c); J(0,2) = a*b + 2.*r*(a+b); J(0,3) = 2.*(a*b + a*c +b*c) + 4.*r*r; } if(!!H) { H(0,1) = H(1,0) = c + 2.*r; H(0,2) = H(2,0) = b + 2.*r; H(0,3) = H(3,0) = 2.*(b+c); H(1,2) = H(2,1) = a + 2.*r; H(1,3) = H(3,1) = 2.*(a+c); H(2,3) = H(3,2) = 2.*(a+b); H(3,3) = 8.*r; } //-- positive double w=100.; phi(1) = -w*(a-.001); phi(2) = -w*(b-.001); phi(3) = -w*(c-.001); phi(4) = -w*(r-.001); if(!!J) { J(1,0) = -w; J(2,1) = -w; J(3,2) = -w; J(4,3) = -w; } //-- all constraints for(uint i=0; i<X.d0; i++) { arr y, Jy; y = X[i]; y.append(x); phi(i+5) = DistanceFunction_SSBox(Jy, NoArr, y); // Jy({3,5})() *= -1.; if(!!J) J[i+5] = Jy({3,-1}); } } } F(X); //initialization x.resize(11); rai::Quaternion rot; rot.setRandom(); arr tX = X * rot.getArr(); //rotate points (with rot^{-1}) arr ma = max(tX,0), mi = min(tX,0); //get coordinate-wise min and max x({0,2})() = (ma-mi)/2.; //sizes x(3) = 1.; //sum(ma-mi)/6.; //radius x({4,6})() = rot.getArr() * (mi+.5*(ma-mi)); //center (rotated back) x({7,10})() = conv_quat2arr(rot); rndGauss(x({7,10})(), .1, true); x({7,10})() /= length(x({7,10})()); if(verbose>1) { checkJacobianCP(F, x, 1e-4); checkHessianCP(F, x, 1e-4); } OptConstrained opt(x, NoArr, F, OPT( stopTolerance = 1e-4, stopFTolerance = 1e-3, damping=1, maxStep=-1, constrainedMethod = augmentedLag, aulaMuInc = 1.1 )); opt.run(); if(verbose>1) { checkJacobianCP(F, x, 1e-4); checkHessianCP(F, x, 1e-4); } f = opt.L.get_costs(); g = opt.L.get_sumOfGviolations(); } void computeOptimalSSBox(rai::Mesh& mesh, arr& x_ret, rai::Transformation& t_ret, const arr& X, uint trials, int verbose) { if(!X.N) { mesh.clear(); return; } arr x,x_best; double f,g, f_best, g_best; fitSSBox(x_best, f_best, g_best, X, verbose); for(uint k=1; k<trials; k++) { fitSSBox(x, f, g, X, verbose); if(g<g_best-1e-4 || (g<1e-4 && f<f_best)) { x_best=x; f_best=f; g_best=g; } } x = x_best; //convert box wall coordinates to box width (incl radius) x(0) = 2.*(x(0)+x(3)); x(1) = 2.*(x(1)+x(3)); x(2) = 2.*(x(2)+x(3)); if(x_ret!=NoArr) x_ret=x; if(verbose>2) { cout <<"x=" <<x; cout <<"\nf = " <<f_best <<"\ng-violations = " <<g_best <<endl; } rai::Transformation t; t.setZero(); t.pos.set(x({4,6})); t.rot.set(x({7,-1})); t.rot.normalize(); mesh.setSSBox(x(0), x(1), x(2), x(3)); t.applyOnPointArray(mesh.V); if(t_ret!=NoTransformation) t_ret = t; }
27.979452
123
0.4541
bgheneti
64d961d79117258ad340e6a55884c46984947de7
8,002
cpp
C++
src/function/stutter.cpp
Eve-ning/reamber
bf5736915ef12c836ec8aa9d6ecb33fd1b7a04b8
[ "MIT" ]
8
2019-02-15T12:27:22.000Z
2021-10-07T08:08:20.000Z
src/function/stutter.cpp
Eve-ning/maniaMultiTool
bf5736915ef12c836ec8aa9d6ecb33fd1b7a04b8
[ "MIT" ]
31
2019-01-25T10:06:43.000Z
2021-10-05T04:47:25.000Z
src/function/stutter.cpp
Eve-ning/amber
bf5736915ef12c836ec8aa9d6ecb33fd1b7a04b8
[ "MIT" ]
3
2019-01-24T14:49:39.000Z
2021-08-10T14:40:03.000Z
#include "function/stutter.h" #include "ui_stutter.h" #include "algorithm/algorithm.h" #include "common.h" Stutter::Stutter(QWidget *parent) : QWidget(parent), ui(new Ui::Stutter) { ui->setupUi(this); ui->input->hideKeyWidget(); ui->input->setTitle("Input"); ui->input->setPlaceholderText("Variant Input"); initBoxSliders(); initToolTips(); stutterLimitUpdate(); } Stutter::~Stutter() { delete ui; } void Stutter::initBoxSliders() { ui->threshold->setParameters(0.01, 1.0, 1000, 0.5); ui->threshold->setTitle("Threshold"); ui->threshold->setDecimals(3); ui->initSv->setParameters(SV_MIN, SV_MAX, 1000, SV_DEFAULT); ui->initSv->setTitle("Initial SV"); ui->initBpm->setParameters(BPM_MIN, BPM_MAX, 1000, BPM_DEFAULT); ui->initBpm->setTitle("Initial BPM"); } void Stutter::initToolTips() { ui->threshold->setToolTip("Threshold dictates where the middle Timing Point should be,\n" "the value is relative to the front.\n" "e.g. 0.5 places the generated Timing Point right in the middle"); ui->initSv->setToolTip("Initial SV, bounded by the limits of the middle Timing Point"); ui->initBpm->setToolTip("Initial BPM, bounded by the limits of the middle Timing Point"); ui->aveSv->setToolTip("Average SV, this affects the average SV of the whole effect"); ui->aveBpm->setToolTip("Average BPM, this affects the average BPM of the whole effect"); ui->svRadio->setToolTip("Switch to SV mode"); ui->svRadio->setToolTip("Switch to BPM mode"); ui->input->setToolTip("Any osu! type with offset can go here"); ui->output->setToolTip("Stutter Output goes here"); ui->normFrontTelButton->setToolTip("Creates a very fast normalized front teleport using the sharpest possible BPM change.\n" "This is relative to the average BPM set."); ui->normBackTelButton->setToolTip("Creates a very fast normalized back teleport using the sharpest possible BPM change.\n" "This is relative to the average BPM set."); ui->maxFrontTelButton->setToolTip("Creates an instant high BPM front screen wipe."); ui->maxBackTelButton->setToolTip("Creates an instant high BPM back screen wipe."); ui->skipLastCheck->setToolTip("Checking this will omit the last Timing Point generated."); } void Stutter::on_threshold_valueChanged() { stutterLimitUpdate(); } void Stutter::on_generateButton_clicked() { auto offsets = readOffsets(); // Break if empty if (offsets.empty()) return; TimingPointV tpV; // Depends on which radio is checked, we generateButton a different output if (ui->svRadio->isChecked()) tpV = algorithm::stutterRel(offsets, // Offsets initSv(), // Initial threshold(), // Relativity aveSv(), // Average false, // Is BPM true, // Skip on Invalid isSkipLast()); // Skip Last else if (ui->bpmRadio->isChecked()) tpV = algorithm::stutterRel(offsets, // Offsets initBpm(), // Initial threshold(), // Relativity aveBpm(), // Average true, // Is BPM true, // Skip on Invalid isSkipLast()); // Skip Last ui->output->write(tpV); } void Stutter::on_normFrontTelButton_clicked() { // Normalized Front Teleport auto offsets = readOffsets(); // Break if empty if (offsets.empty()) return; TimingPointV tpV = algorithm::stutterAbs( offsets, // Offsets BPM_MIN,// Initial BPM_MIN,// Relativity aveBpm(), // Average true, // Is BPM false, // Relative From Front true, // Skip on Invalid false); // [*] Skip Last // [*] We cannot directly omit since we need to stutter swap here tpV = algorithm::stutterSwap(tpV); if (isSkipLast()) tpV.popBack(); ui->output->write(tpV); } void Stutter::on_normBackTelButton_clicked() { // Normalized Back Teleport auto offsets = readOffsets(); // Break if empty if (offsets.empty()) return; TimingPointV tpV = algorithm::stutterAbs( offsets, // Offsets BPM_MIN, // Initial BPM_MIN, // Relativity aveBpm(), // Average true, // Is BPM false, // Relative From Front true, // Skip on Invalid isSkipLast()); // Skip Last ui->output->write(tpV); } void Stutter::on_maxFrontTelButton_clicked() { // Max Front Teleport auto offsets = readOffsets(); // Break if empty if (offsets.empty()) return; TimingPointV tpV; TimingPoint tpTeleport; TimingPoint tpNormalized; tpTeleport.loadParameters(0, BPM_MAX, true); tpNormalized.loadParameters(1, aveBpm(), true); tpV.pushBack(tpTeleport); tpV.pushBack(tpNormalized); ui->output->write(TimingPointV(algorithm::copy<TimingPoint>( tpV.sptr(), offsets, true, true))); } void Stutter::on_maxBackTelButton_clicked() { // Max Back Teleport auto offsets = readOffsets(); // Break if empty if (offsets.empty()) return; // move back by 1ms for (auto& offset : offsets) offset -= 1.0; TimingPointV tpV; TimingPoint tpTeleport; TimingPoint tpNormalized; tpTeleport.loadParameters(0, BPM_MAX, true); tpNormalized.loadParameters(1, aveBpm(), true); tpV.pushBack(tpTeleport); tpV.pushBack(tpNormalized); ui->output->write(TimingPointV(algorithm::copy<TimingPoint>( tpV.sptr(), offsets, true, true))); } void Stutter::on_aveBpm_valueChanged(double) { stutterLimitUpdate(); } void Stutter::on_aveSv_valueChanged(double) { stutterLimitUpdate(); } void Stutter::stutterLimitUpdate() { QVector<double> initLim = algorithm::stutterRelInitLimits(threshold(), aveSv(), SV_MIN, SV_MAX); ui->initSv->setRange(initLim[0] >= SV_MIN ? initLim[0] : SV_MIN, initLim[1] <= SV_MAX ? initLim[1] : SV_MAX); initLim = algorithm::stutterRelInitLimits(threshold(), aveBpm(), BPM_MIN, BPM_MAX); ui->initBpm->setRange(initLim[0] >= BPM_MIN ? initLim[0] : BPM_MIN, initLim[1] <= BPM_MAX ? initLim[1] : BPM_MAX); } QString Stutter::output() const { return ui->output->toPlainText(); } void Stutter::on_output_textChanged() { emit outputChanged(); } QVector<double> Stutter::readOffsets() { return ui->input->readOffsets(true); } bool Stutter::isSkipLast() const { return ui->skipLastCheck->isChecked(); } double Stutter::aveBpm() const { return ui->aveBpm->value(); } double Stutter::aveSv() const { return ui->aveSv->value(); } double Stutter::initSv() const { return ui->initSv->value(); } double Stutter::initBpm() const { return ui->initBpm->value(); } double Stutter::threshold() const { return ui->threshold->value(); }
35.883408
128
0.554486
Eve-ning
64db3a57e57ff0f5e78c5cec2c324e672ce06a6d
1,172
cpp
C++
Helios/src/Window.cpp
rgracari/helio_test
2d516d16da4252c8f92f5c265b6151c6e87bc907
[ "Apache-2.0" ]
null
null
null
Helios/src/Window.cpp
rgracari/helio_test
2d516d16da4252c8f92f5c265b6151c6e87bc907
[ "Apache-2.0" ]
null
null
null
Helios/src/Window.cpp
rgracari/helio_test
2d516d16da4252c8f92f5c265b6151c6e87bc907
[ "Apache-2.0" ]
null
null
null
#include "Window.hpp" namespace Helio { Window::Window(const std::string& windowName) { Init(); std::cout << "Window Created" << std::endl; window = SDL_CreateWindow( windowName.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); if (window == NULL) std::cout << "Could not create window: " << SDL_GetError() << std::endl;; } void Window::Init() { std::cout << "SDL INIT" << std::endl; if (SDL_Init(SDL_INIT_VIDEO) < 0) { std::cout << "SDL could not initialize! SDL Error: " << SDL_GetError() << std::endl; } std::cout << "IMAGESDL INIT" << std::endl; int imgFlags = IMG_INIT_PNG; if (!(IMG_Init(imgFlags) & imgFlags)) { std::cout << "SDL_image could not initialize! SDL_image Error: " << SDL_GetError() << std::endl; } } SDL_Window* Window::GetSDLWindow() { return window; } Window::~Window() { std::cout << "Window Destroyed" << std::endl; if (window != NULL) { SDL_DestroyWindow(window); window = NULL; } std::cout << "IMGSDL QUIT" << std::endl; IMG_Quit(); std::cout << "SDL QUIT" << std::endl; SDL_Quit(); } }
20.561404
99
0.617747
rgracari
64df3d32373bac26a2b6d6041b2f18c095654c81
781
hpp
C++
test/mock/core/runtime/binaryen_wasm_memory_factory_mock.hpp
soramitsu/kagome
d66755924477f2818fcae30ba2e65681fce34264
[ "Apache-2.0" ]
110
2019-04-03T13:39:39.000Z
2022-03-09T11:54:42.000Z
test/mock/core/runtime/binaryen_wasm_memory_factory_mock.hpp
soramitsu/kagome
d66755924477f2818fcae30ba2e65681fce34264
[ "Apache-2.0" ]
890
2019-03-22T21:33:30.000Z
2022-03-31T14:31:22.000Z
test/mock/core/runtime/binaryen_wasm_memory_factory_mock.hpp
soramitsu/kagome
d66755924477f2818fcae30ba2e65681fce34264
[ "Apache-2.0" ]
27
2019-06-25T06:21:47.000Z
2021-11-01T14:12:10.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef KAGOME_BINARYEN_WASM_MEMORY_FACTORY_MOCK_HPP #define KAGOME_BINARYEN_WASM_MEMORY_FACTORY_MOCK_HPP #include "runtime/binaryen/binaryen_memory_factory.hpp" #include <gmock/gmock.h> namespace kagome::runtime::binaryen { class BinaryenWasmMemoryFactoryMock : public BinaryenMemoryFactory { public: ~BinaryenWasmMemoryFactoryMock() override = default; MOCK_METHOD(std::unique_ptr<MemoryImpl>, make, (wasm::ShellExternalInterface::Memory * memory, WasmSize heap_base), (const, override)); }; } // namespace kagome::runtime::binaryen #endif // KAGOME_BINARYEN_WASM_MEMORY_FACTORY_MOCK_HPP
26.931034
70
0.71831
soramitsu
64e2ebd1dd0bb416a05e399cfdd7962ad294a613
193
cpp
C++
Chapter11/chapter11gt_05/main.cpp
PacktPublishing/Modern-C-Cookbook-Second-Edition
2b6aceba0f6dbd0607286315cb8c282500e68046
[ "MIT" ]
104
2017-05-10T17:13:11.000Z
2021-11-13T19:58:08.000Z
Chapter11/chapter11gt_05/main.cpp
maurodelazeri/Modern-Cpp-Programming-Cookbook
141d327169e12fc30fe09de0cd041057b00fe4b8
[ "MIT" ]
2
2020-09-21T13:42:35.000Z
2020-12-07T08:06:39.000Z
Chapter11/chapter11gt_05/main.cpp
maurodelazeri/Modern-Cpp-Programming-Cookbook
141d327169e12fc30fe09de0cd041057b00fe4b8
[ "MIT" ]
51
2017-05-12T09:05:41.000Z
2022-02-17T14:30:51.000Z
#include <gtest/gtest.h> TEST(Sample, Test) { auto a = 42; ASSERT_EQ(a, 0); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
12.866667
42
0.621762
PacktPublishing
64e59e601ecc79a53e407c06f521aeee35395376
180
cpp
C++
src/sfHelperControl.cpp
ArthurClemens/SoundField
645f0a421ba719f253938c030dd1b4feb7ee6097
[ "MIT" ]
2
2018-07-02T04:00:02.000Z
2020-02-19T09:04:40.000Z
src/sfHelperControl.cpp
ArthurClemens/SoundField
645f0a421ba719f253938c030dd1b4feb7ee6097
[ "MIT" ]
null
null
null
src/sfHelperControl.cpp
ArthurClemens/SoundField
645f0a421ba719f253938c030dd1b4feb7ee6097
[ "MIT" ]
null
null
null
#include "sfHelperControl.h" void sfHelperControl::setLoc(ofPoint inLoc) { loc = inLoc; } void sfHelperControl::setClickLoc(ofPoint inClickLoc) { offset = inClickLoc - loc; }
16.363636
55
0.744444
ArthurClemens
64ea55e5413c2e13c5b5b3f2e74ef2b1600eddef
3,326
cpp
C++
demos/unassigned_or_unused/soft_to_hard_masking.cpp
JensUweUlrich/seqan
fa609a123d3dc5d8166c12f6849281813438dd39
[ "BSD-3-Clause" ]
409
2015-01-12T22:02:01.000Z
2022-03-29T06:17:05.000Z
demos/unassigned_or_unused/soft_to_hard_masking.cpp
JensUweUlrich/seqan
fa609a123d3dc5d8166c12f6849281813438dd39
[ "BSD-3-Clause" ]
1,269
2015-01-02T22:42:25.000Z
2022-03-08T13:31:46.000Z
demos/unassigned_or_unused/soft_to_hard_masking.cpp
JensUweUlrich/seqan
fa609a123d3dc5d8166c12f6849281813438dd39
[ "BSD-3-Clause" ]
193
2015-01-14T16:21:27.000Z
2022-03-19T22:47:02.000Z
// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2018, Knut Reinert, FU Berlin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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. // // ========================================================================== // Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de> // ========================================================================== // Concatenate multiple files from soft-masked FASTA (masked sequence is // lower case) to hard-masked FASTA (replaced by Ns) and write to stdout. // // USAGE: soft_to_hard_masking IN1.fa [IN2.fa ...] > out.fa // ========================================================================== #include <iostream> #include <cctype> #include <seqan/basic.h> #include <seqan/sequence.h> #include <seqan/seq_io.h> using namespace seqan; template <typename TStream> void convertToHardMasked(TStream & stream, char const * filename) { SeqFileIn inFile(filename); String<char> meta; String<char> seq; while (!atEnd(inFile)) { clear(meta); clear(seq); readRecord(meta, seq, inFile); // Header lines are not touched. if (front(seq) != '>') { typedef typename Iterator<CharString, Rooted>::Type TIter; for (TIter it = begin(seq, Rooted()); !atEnd(it); goNext(it)) if (std::islower(*it)) *it = 'N'; } stream << meta << '\n' << seq << '\n'; } } int main(int argc, char const ** argv) { for (int i = 1; i < argc; ++i) { std::cerr << argv[i] << '\n'; convertToHardMasked(std::cout, argv[i]); } return 0; }
38.229885
78
0.596512
JensUweUlrich
64eeba2ce8634682e7641d4ff6b31d4344365df0
362
cpp
C++
src/Functions/subtractMonths.cpp
pdv-ru/ClickHouse
0ff975bcf3008fa6c6373cbdfed16328e3863ec5
[ "Apache-2.0" ]
15,577
2019-09-23T11:57:53.000Z
2022-03-31T18:21:48.000Z
src/Functions/subtractMonths.cpp
pdv-ru/ClickHouse
0ff975bcf3008fa6c6373cbdfed16328e3863ec5
[ "Apache-2.0" ]
16,476
2019-09-23T11:47:00.000Z
2022-03-31T23:06:01.000Z
src/Functions/subtractMonths.cpp
pdv-ru/ClickHouse
0ff975bcf3008fa6c6373cbdfed16328e3863ec5
[ "Apache-2.0" ]
3,633
2019-09-23T12:18:28.000Z
2022-03-31T15:55:48.000Z
#include <Functions/IFunction.h> #include <Functions/FunctionFactory.h> #include <Functions/FunctionDateOrDateTimeAddInterval.h> namespace DB { using FunctionSubtractMonths = FunctionDateOrDateTimeAddInterval<SubtractMonthsImpl>; void registerFunctionSubtractMonths(FunctionFactory & factory) { factory.registerFunction<FunctionSubtractMonths>(); } }
19.052632
85
0.823204
pdv-ru
64f7eacbbc11c51ce0ad8e5a65c1d1dc7792210b
19,166
cpp
C++
OREAnalytics/orea/aggregation/xvacalculator.cpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
335
2016-10-07T16:31:10.000Z
2022-03-02T07:12:03.000Z
OREAnalytics/orea/aggregation/xvacalculator.cpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
59
2016-10-31T04:20:24.000Z
2022-01-03T16:39:57.000Z
OREAnalytics/orea/aggregation/xvacalculator.cpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
180
2016-10-08T14:23:50.000Z
2022-03-28T10:43:05.000Z
/* Copyright (C) 2020 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include <orea/aggregation/xvacalculator.hpp> #include <ored/utilities/log.hpp> #include <ored/utilities/vectorutils.hpp> #include <ql/errors.hpp> #include <ql/version.hpp> using namespace std; using namespace QuantLib; // using namespace boost::accumulators; namespace ore { namespace analytics { ValueAdjustmentCalculator::ValueAdjustmentCalculator( const boost::shared_ptr<Portfolio> portfolio, const boost::shared_ptr<Market> market, const string& configuration, const string& baseCurrency, const string& dvaName, const string& fvaBorrowingCurve, const string& fvaLendingCurve, const bool applyDynamicInitialMargin, const boost::shared_ptr<DynamicInitialMarginCalculator> dimCalculator, const boost::shared_ptr<NPVCube> tradeExposureCube, const boost::shared_ptr<NPVCube> nettingSetExposureCube, const Size tradeEpeIndex, const Size tradeEneIndex, const Size nettingSetEpeIndex, const Size nettingSetEneIndex, const bool flipViewXVA, const string& flipViewBorrowingCurvePostfix, const string& flipViewLendingCurvePostfix) : portfolio_(portfolio), market_(market), configuration_(configuration), baseCurrency_(baseCurrency), dvaName_(dvaName), fvaBorrowingCurve_(fvaBorrowingCurve), fvaLendingCurve_(fvaLendingCurve), applyDynamicInitialMargin_(applyDynamicInitialMargin), dimCalculator_(dimCalculator), tradeExposureCube_(tradeExposureCube), nettingSetExposureCube_(nettingSetExposureCube), tradeEpeIndex_(tradeEpeIndex), tradeEneIndex_(tradeEneIndex), nettingSetEpeIndex_(nettingSetEpeIndex), nettingSetEneIndex_(nettingSetEneIndex), flipViewXVA_(flipViewXVA), flipViewBorrowingCurvePostfix_(flipViewBorrowingCurvePostfix), flipViewLendingCurvePostfix_(flipViewLendingCurvePostfix) { QL_REQUIRE(portfolio_, "portfolio is null"); for (Size i = 0; i < portfolio_->size(); ++i) { string tradeId = portfolio_->trades()[i]->id(); string nettingSetId = portfolio_->trades()[i]->envelope().nettingSetId(); if (nettingSetCpty_.find(nettingSetId) == nettingSetCpty_.end()) { nettingSetCpty_[nettingSetId] = portfolio_->trades()[i]->envelope().counterparty(); } } QL_REQUIRE(tradeExposureCube_->numIds() == portfolio_->trades().size(), "number of trades in tradeExposureCube and portfolio mismatch (" << tradeExposureCube_->numIds() << " vs " << portfolio_->trades().size() << ")"); QL_REQUIRE(nettingSetExposureCube_->numIds() == nettingSetCpty_.size(), "number of netting sets in nettingSetExposureCube and nettingSetCpty map mismatch (" << nettingSetExposureCube_->numIds() << " vs " << nettingSetCpty_.size() << ")"); QL_REQUIRE(tradeExposureCube_->numDates() == nettingSetExposureCube_->numDates(), "number of dates in tradeExposureCube and nettingSetExposureCube mismatch (" << tradeExposureCube_->numDates() << " vs " << nettingSetExposureCube_->numDates() << ")"); for (Size i = 0; i < tradeExposureCube_->numDates(); i++) { QL_REQUIRE(tradeExposureCube_->dates()[i] == nettingSetExposureCube_->dates()[i], "date at " << i << " in tradeExposureCube and nettingSetExposureCube mismatch (" << tradeExposureCube_->dates()[i] << " vs " << nettingSetExposureCube_->dates()[i] << ")"); } QL_REQUIRE(tradeEpeIndex < tradeExposureCube_->depth(), "tradeEpeIndex(" << tradeEpeIndex << ") exceeds depth of tradeExposureCube(" << tradeExposureCube_->depth() << ")"); QL_REQUIRE(tradeEneIndex < tradeExposureCube_->depth(), "tradeEneIndex(" << tradeEneIndex << ") exceeds depth of tradeExposureCube(" << tradeExposureCube_->depth() << ")"); QL_REQUIRE(nettingSetEpeIndex < nettingSetExposureCube_->depth(), "nettingSetEpeIndex(" << nettingSetEpeIndex << ") exceeds depth of nettingSetExposureCube(" << nettingSetExposureCube_->depth() << ")"); QL_REQUIRE(nettingSetEneIndex < nettingSetExposureCube_->depth(), "nettingSetEneIndex(" << nettingSetEneIndex << ") exceeds depth of nettingSetExposureCube(" << nettingSetExposureCube_->depth() << ")"); } const map<string, Real>& ValueAdjustmentCalculator::tradeCva() { return tradeCva_; } const map<string, Real>& ValueAdjustmentCalculator::tradeDva() { return tradeDva_; } const map<string, Real>& ValueAdjustmentCalculator::nettingSetCva() { return nettingSetCva_; } const map<string, Real>& ValueAdjustmentCalculator::nettingSetDva() { return nettingSetDva_; } const map<string, Real>& ValueAdjustmentCalculator::nettingSetSumCva() { return nettingSetSumCva_; } const map<string, Real>& ValueAdjustmentCalculator::nettingSetSumDva() { return nettingSetSumDva_; } const Real& ValueAdjustmentCalculator::tradeCva(const std::string& trade) { if (tradeCva_.find(trade) != tradeCva_.end()) return tradeCva_[trade]; else QL_FAIL("trade " << trade << " not found in expected CVA results"); } const Real& ValueAdjustmentCalculator::tradeDva(const std::string& trade) { if (tradeDva_.find(trade) != tradeDva_.end()) return tradeDva_[trade]; else QL_FAIL("trade " << trade << " not found in expected DVA results"); } const Real& ValueAdjustmentCalculator::tradeFba(const std::string& trade) { if (tradeFba_.find(trade) != tradeFba_.end()) return tradeFba_[trade]; else QL_FAIL("trade " << trade << " not found in expected FBA results"); } const Real& ValueAdjustmentCalculator::tradeFba_exOwnSp(const std::string& trade) { if (tradeFba_exOwnSp_.find(trade) != tradeFba_exOwnSp_.end()) return tradeFba_exOwnSp_[trade]; else QL_FAIL("trade " << trade << " not found in expected FBA ex own sp results"); } const Real& ValueAdjustmentCalculator::tradeFba_exAllSp(const std::string& trade) { if (tradeFba_exAllSp_.find(trade) != tradeFba_exAllSp_.end()) return tradeFba_exAllSp_[trade]; else QL_FAIL("trade " << trade << " not found in expected FBA ex all sp results"); } const Real& ValueAdjustmentCalculator::tradeFca(const std::string& trade) { if (tradeFca_.find(trade) != tradeFca_.end()) return tradeFca_[trade]; else QL_FAIL("trade " << trade << " not found in expected FCA results"); } const Real& ValueAdjustmentCalculator::tradeFca_exOwnSp(const std::string& trade) { if (tradeFca_exOwnSp_.find(trade) != tradeFca_exOwnSp_.end()) return tradeFca_exOwnSp_[trade]; else QL_FAIL("trade " << trade << " not found in expected FCA ex own sp results"); } const Real& ValueAdjustmentCalculator::tradeFca_exAllSp(const std::string& trade) { if (tradeFca_exAllSp_.find(trade) != tradeFca_exAllSp_.end()) return tradeFca_exAllSp_[trade]; else QL_FAIL("trade " << trade << " not found in expected FCA ex all sp results"); } const Real& ValueAdjustmentCalculator::tradeMva(const std::string& trade) { if (tradeMva_.find(trade) != tradeMva_.end()) return tradeMva_[trade]; else QL_FAIL("trade " << trade << " not found in expected MVA results"); } const Real& ValueAdjustmentCalculator::nettingSetSumCva(const std::string& nettingSet) { if (nettingSetSumCva_.find(nettingSet) != nettingSetSumCva_.end()) return nettingSetSumCva_[nettingSet]; else QL_FAIL("netting set " << nettingSet << " not found in expected CVA results"); } const Real& ValueAdjustmentCalculator::nettingSetSumDva(const std::string& nettingSet) { if (nettingSetSumDva_.find(nettingSet) != nettingSetSumDva_.end()) return nettingSetSumDva_[nettingSet]; else QL_FAIL("netting set " << nettingSet << " not found in expected DVA results"); } const Real& ValueAdjustmentCalculator::nettingSetCva(const std::string& nettingSet) { if (nettingSetCva_.find(nettingSet) != nettingSetCva_.end()) return nettingSetCva_[nettingSet]; else QL_FAIL("netting set " << nettingSet << " not found in expected CVA results"); } const Real& ValueAdjustmentCalculator::nettingSetDva(const std::string& nettingSet) { if (nettingSetDva_.find(nettingSet) != nettingSetDva_.end()) return nettingSetDva_[nettingSet]; else QL_FAIL("netting set " << nettingSet << " not found in expected DVA results"); } const Real& ValueAdjustmentCalculator::nettingSetFba(const std::string& nettingSet) { if (nettingSetFba_.find(nettingSet) != nettingSetFba_.end()) return nettingSetFba_[nettingSet]; else QL_FAIL("netting set " << nettingSet << " not found in expected FBA results"); } const Real& ValueAdjustmentCalculator::nettingSetFba_exOwnSp(const std::string& nettingSet) { if (nettingSetFba_exOwnSp_.find(nettingSet) != nettingSetFba_exOwnSp_.end()) return nettingSetFba_exOwnSp_[nettingSet]; else QL_FAIL("netting set " << nettingSet << " not found in expected FBA ex own sp results"); } const Real& ValueAdjustmentCalculator::nettingSetFba_exAllSp(const std::string& nettingSet) { if (nettingSetFba_exAllSp_.find(nettingSet) != nettingSetFba_exAllSp_.end()) return nettingSetFba_exAllSp_[nettingSet]; else QL_FAIL("netting set " << nettingSet << " not found in expected FBA ex all spresults"); } const Real& ValueAdjustmentCalculator::nettingSetFca(const std::string& nettingSet) { if (nettingSetFca_.find(nettingSet) != nettingSetFca_.end()) return nettingSetFca_[nettingSet]; else QL_FAIL("netting set " << nettingSet << " not found in expected FBA results"); } const Real& ValueAdjustmentCalculator::nettingSetFca_exOwnSp(const std::string& nettingSet) { if (nettingSetFca_exOwnSp_.find(nettingSet) != nettingSetFca_exOwnSp_.end()) return nettingSetFca_exOwnSp_[nettingSet]; else QL_FAIL("netting set " << nettingSet << " not found in expected FBA ex own sp results"); } const Real& ValueAdjustmentCalculator::nettingSetFca_exAllSp(const std::string& nettingSet) { if (nettingSetFca_exAllSp_.find(nettingSet) != nettingSetFca_exAllSp_.end()) return nettingSetFca_exAllSp_[nettingSet]; else QL_FAIL("netting set " << nettingSet << " not found in expected FBA ex all sp results"); } const Real& ValueAdjustmentCalculator::nettingSetMva(const std::string& nettingSet) { if (nettingSetMva_.find(nettingSet) != nettingSetMva_.end()) return nettingSetMva_[nettingSet]; else QL_FAIL("netting set " << nettingSet << " not found in expected MVA results"); } void ValueAdjustmentCalculator::build() { const auto& numDates = dates().size(); const auto& today = asof(); Handle<YieldTermStructure> borrowingCurve, lendingCurve, oisCurve; if (baseCurrency_ != "") oisCurve = market_->discountCurve(baseCurrency_, configuration_); // Trade XVA for (Size i = 0; i < portfolio_->trades().size(); ++i) { string tid = portfolio_->trades()[i]->id(); LOG("Update XVA for trade " << tid << (flipViewXVA_ ? ", inverted (flipViewXVA = Y)" : ", regular (flipViewXVA = N)")); string cid; if (flipViewXVA_) { cid = dvaName_; dvaName_ = portfolio_->trades()[i]->envelope().counterparty(); fvaBorrowingCurve_ = dvaName_ + flipViewBorrowingCurvePostfix_; fvaLendingCurve_ = dvaName_ + flipViewLendingCurvePostfix_; } else { cid = portfolio_->trades()[i]->envelope().counterparty(); } if (fvaBorrowingCurve_ != "") borrowingCurve = market_->yieldCurve(fvaBorrowingCurve_, configuration_); if (fvaLendingCurve_ != "") lendingCurve = market_->yieldCurve(fvaLendingCurve_, configuration_); if (!borrowingCurve.empty() || !lendingCurve.empty()) { QL_REQUIRE(baseCurrency_ != "", "baseCurrency required for FVA calculation"); } string nid = portfolio_->trades()[i]->envelope().nettingSetId(); Real cvaRR = market_->recoveryRate(cid, configuration_)->value(); Real dvaRR = 0.0; if (dvaName_ != "") dvaRR = market_->recoveryRate(dvaName_, configuration_)->value(); tradeCva_[tid] = 0.0; tradeDva_[tid] = 0.0; tradeFca_[tid] = 0.0; tradeFca_exOwnSp_[tid] = 0.0; tradeFca_exAllSp_[tid] = 0.0; tradeFba_[tid] = 0.0; tradeFba_exOwnSp_[tid] = 0.0; tradeFba_exAllSp_[tid] = 0.0; tradeMva_[tid] = 0.0; for (Size j = 0; j < numDates; ++j) { // CVA / DVA Date d0 = j == 0 ? today : dates()[j - 1]; Date d1 = dates()[j]; Real cvaIncrement = calculateCvaIncrement(tid, cid, d0, d1, cvaRR); Real dvaIncrement = dvaName_ != "" ? calculateDvaIncrement(tid, d0, d1, dvaRR) : 0; tradeCva_[tid] += cvaIncrement; tradeDva_[tid] += dvaIncrement; // FCA if (!borrowingCurve.empty()) { Real dcf = borrowingCurve->discount(d0) / borrowingCurve->discount(d1) - oisCurve->discount(d0) / oisCurve->discount(d1); Real fcaIncrement = calculateFcaIncrement(tid, cid, dvaName_, d0, d1, dcf); Real fcaIncrement_exOwnSP = calculateFcaIncrement(tid, cid, "", d0, d1, dcf); Real fcaIncrement_exAllSP = calculateFcaIncrement(tid, "", "", d0, d1, dcf); tradeFca_[tid] += fcaIncrement; tradeFca_exOwnSp_[tid] += fcaIncrement_exOwnSP; tradeFca_exAllSp_[tid] += fcaIncrement_exAllSP; } // FBA if (!lendingCurve.empty()) { Real dcf = lendingCurve->discount(d0) / lendingCurve->discount(d1) - oisCurve->discount(d0) / oisCurve->discount(d1); Real fbaIncrement = calculateFbaIncrement(tid, cid, dvaName_, d0, d1, dcf); Real fbaIncrement_exOwnSP = calculateFbaIncrement(tid, cid, "", d0, d1, dcf); Real fbaIncrement_exAllSP = calculateFbaIncrement(tid, "", "", d0, d1, dcf); tradeFba_[tid] += fbaIncrement; tradeFba_exOwnSp_[tid] += fbaIncrement_exOwnSP; tradeFba_exAllSp_[tid] += fbaIncrement_exAllSP; } } if (nettingSetSumCva_.find(nid) == nettingSetSumCva_.end()) { nettingSetSumCva_[nid] = 0.0; nettingSetSumDva_[nid] = 0.0; } nettingSetSumCva_[nid] += tradeCva_[tid]; nettingSetSumDva_[nid] += tradeDva_[tid]; } // Netting Set XVA for (const auto& pair : nettingSetCpty_) { string nid = pair.first; LOG("Update XVA for netting set " << nid << (flipViewXVA_ ? ", inverted (flipViewXVA = Y)" : ", regular (flipViewXVA = N)")); string cid; if (flipViewXVA_) { cid = dvaName_; dvaName_ = pair.second; fvaBorrowingCurve_ = dvaName_ + flipViewBorrowingCurvePostfix_; fvaLendingCurve_ = dvaName_ + flipViewLendingCurvePostfix_; } else { cid = pair.second; } Real cvaRR = market_->recoveryRate(cid, configuration_)->value(); Real dvaRR = 0.0; if (dvaName_ != "") { dvaRR = market_->recoveryRate(dvaName_, configuration_)->value(); } if (fvaBorrowingCurve_ != "") borrowingCurve = market_->yieldCurve(fvaBorrowingCurve_, configuration_); if (fvaLendingCurve_ != "") lendingCurve = market_->yieldCurve(fvaLendingCurve_, configuration_); if (!borrowingCurve.empty() || !lendingCurve.empty()) { QL_REQUIRE(baseCurrency_ != "", "baseCurrency required for FVA calculation"); } nettingSetCva_[nid] = 0.0; nettingSetDva_[nid] = 0.0; nettingSetFca_[nid] = 0.0; nettingSetFca_exOwnSp_[nid] = 0.0; nettingSetFca_exAllSp_[nid] = 0.0; nettingSetFba_[nid] = 0.0; nettingSetFba_exOwnSp_[nid] = 0.0; nettingSetFba_exAllSp_[nid] = 0.0; nettingSetMva_[nid] = 0.0; for (Size j = 0; j < numDates; ++j) { // CVA / DVA Date d0 = j == 0 ? today : dates()[j - 1]; Date d1 = dates()[j]; Real cvaIncrement = calculateNettingSetCvaIncrement(nid, cid, d0, d1, cvaRR); Real dvaIncrement = dvaName_ != "" ? calculateNettingSetDvaIncrement(nid, d0, d1, dvaRR) : 0; nettingSetCva_[nid] += cvaIncrement; nettingSetDva_[nid] += dvaIncrement; // FCA if (!borrowingCurve.empty()) { Real dcf = borrowingCurve->discount(d0) / borrowingCurve->discount(d1) - oisCurve->discount(d0) / oisCurve->discount(d1); Real fcaIncrement = calculateNettingSetFcaIncrement(nid, cid, dvaName_, d0, d1, dcf); Real fcaIncrement_exOwnSP = calculateNettingSetFcaIncrement(nid, cid, "", d0, d1, dcf); Real fcaIncrement_exAllSP = calculateNettingSetFcaIncrement(nid, "", "", d0, d1, dcf); nettingSetFca_[nid] += fcaIncrement; nettingSetFca_exOwnSp_[nid] += fcaIncrement_exOwnSP; nettingSetFca_exAllSp_[nid] += fcaIncrement_exAllSP; // MVA if (dimCalculator_) { Real mvaIncrement = calculateNettingSetMvaIncrement(nid, cid, d0, d1, dcf); nettingSetMva_[nid] += mvaIncrement; } } // FBA if (!lendingCurve.empty()) { Real dcf = lendingCurve->discount(d0) / lendingCurve->discount(d1) - oisCurve->discount(d0) / oisCurve->discount(d1); Real fbaIncrement = calculateNettingSetFbaIncrement(nid, cid, dvaName_, d0, d1, dcf); Real fbaIncrement_exOwnSP = calculateNettingSetFbaIncrement(nid, cid, "", d0, d1, dcf); Real fbaIncrement_exAllSP = calculateNettingSetFbaIncrement(nid, "", "", d0, d1, dcf); nettingSetFba_[nid] += fbaIncrement; nettingSetFba_exOwnSp_[nid] += fbaIncrement_exOwnSP; nettingSetFba_exAllSp_[nid] += fbaIncrement_exAllSP; } } } } } // namespace analytics } // namespace ore
43.757991
133
0.656058
mrslezak
64f98d0fa33a59839306941618e3547b1c8a5b20
1,263
hpp
C++
topbar.hpp
mehhdiii/OOP-Game-City-Builder-CS-224-Spring-2020
91d74519505cb39b551a6fd18485516dbac2ec9c
[ "FTL" ]
1
2022-01-14T01:31:33.000Z
2022-01-14T01:31:33.000Z
topbar.hpp
mehhdiii/OOP-Game-City-Builder-CS-224-Spring-2020
91d74519505cb39b551a6fd18485516dbac2ec9c
[ "FTL" ]
null
null
null
topbar.hpp
mehhdiii/OOP-Game-City-Builder-CS-224-Spring-2020
91d74519505cb39b551a6fd18485516dbac2ec9c
[ "FTL" ]
2
2020-07-25T07:59:54.000Z
2022-03-29T02:35:51.000Z
#include "SDL.h" #include "unit.hpp" #include<string> #include<iostream> #include<vector> #include"draw_text.hpp" #pragma once class Topbar: public Unit{ private: int number_of_bars=4; // different number of sliders we can have int transition_in_stat_sprite =5; // indicates the number of states a slider can be in int cash; //all cash std::vector<std::vector<SDL_Texture*>> stats_sprite; //all slider sprites SDL_Rect cash_mover; //cash slider mover SDL_Rect greenenergy_mover; //green energy slider mover SDL_Rect xplevel_mover; //xp level slider mover SDL_Rect oxygenlevel_mover; //oxygen level slider mover const int SPRITE_W = 103; //sliders width const int SPRITE_H = 32; //sliders height //text rendering objects std::vector<Draw_text*> text_objects; // SDL_Rect cash_mover; //size of the object to draw on screen void setRect(); //cropping out the sprite from the sheet public: Topbar(SDL_Texture*); ~Topbar(); void draw(SDL_Renderer*); void draw_modified(SDL_Renderer*, int &, int &, int &, int &); void update_bars(int , int, int, int); void add_static_sprite(SDL_Texture*, int sprite_color); };
34.135135
95
0.669834
mehhdiii
64fca62f0f95a23f120ea08345b41b27d5bd8740
11,127
cpp
C++
flashlight/fl/autograd/backend/cuda/RNN.cpp
imaginary-person/flashlight
30d45c1c8c0fbe335a2a9d1e4bab57847316b157
[ "BSD-3-Clause" ]
1
2021-09-29T06:24:41.000Z
2021-09-29T06:24:41.000Z
flashlight/fl/autograd/backend/cuda/RNN.cpp
pkassotis/flashlight
1061e1727c77fac644713047be4c2fb95c02fd55
[ "BSD-3-Clause" ]
5
2021-06-20T23:58:27.000Z
2021-07-09T17:45:07.000Z
flashlight/fl/autograd/backend/cuda/RNN.cpp
pkassotis/flashlight
1061e1727c77fac644713047be4c2fb95c02fd55
[ "BSD-3-Clause" ]
1
2022-01-12T06:48:28.000Z
2022-01-12T06:48:28.000Z
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "flashlight/fl/autograd/Functions.h" #include <cudnn.h> #include "flashlight/fl/autograd/Variable.h" #include "flashlight/fl/autograd/backend/cuda/CudnnUtils.h" #include "flashlight/fl/common/DevicePtr.h" namespace { struct RNNGradData { af::array dy; af::array dhy; af::array dcy; }; } // namespace namespace fl { void rnnBackward( std::vector<Variable>& inputs, const std::shared_ptr<struct RNNGradData> gradData, const af::array& y, size_t workspaceSize, size_t reserveSize, af::array reserveSpace, int numLayers, int hiddenSize, RnnMode mode, bool bidirectional, float dropProb) { if (inputs.size() != 4) { throw std::invalid_argument("wrong # of inputs for RNN"); } auto input = inputs[0]; auto hx = inputs[1]; auto cx = inputs[2]; auto weights = inputs[3]; af::array hxArray = hx.array(); af::array cxArray = cx.array(); af::array weightsArray = weights.array(); if (!(input.isCalcGrad() || hx.isCalcGrad() || cx.isCalcGrad() || weights.isCalcGrad())) { return; } auto handle = getCudnnHandle(); auto& x = input.array(); auto dims = x.dims(); int inputSize = dims[0]; int batchSize = dims[1]; int seqLength = dims[2]; int totalLayers = numLayers * (bidirectional ? 2 : 1); int outSize = hiddenSize * (bidirectional ? 2 : 1); DropoutDescriptor dropout(dropProb); RNNDescriptor rnnDesc( input.type(), hiddenSize, numLayers, mode, bidirectional, dropout); if (input.type() == f16) { CUDNN_CHECK_ERR(cudnnSetRNNMatrixMathType( rnnDesc.descriptor, CUDNN_TENSOR_OP_MATH_ALLOW_CONVERSION)); } else { CUDNN_CHECK_ERR( cudnnSetRNNMatrixMathType(rnnDesc.descriptor, CUDNN_DEFAULT_MATH)); } TensorDescriptorArray yDesc(seqLength, y.type(), {1, 1, outSize, batchSize}); TensorDescriptorArray dyDesc(seqLength, y.type(), {1, 1, outSize, batchSize}); af::dim4 hDims = {1, hiddenSize, batchSize, totalLayers}; TensorDescriptor dhyDesc(x.type(), hDims); TensorDescriptor dcyDesc(x.type(), hDims); TensorDescriptor hxDesc(x.type(), hDims); TensorDescriptor cxDesc(x.type(), hDims); Variable dhx(af::array(hxArray.dims(), hxArray.type()), false); Variable dcx(af::array(cxArray.dims(), cxArray.type()), false); TensorDescriptor dhxDesc(x.type(), hDims); TensorDescriptor dcxDesc(x.type(), hDims); FilterDescriptor wDesc(weightsArray); Variable dx(af::array(input.dims(), input.type()), false); TensorDescriptorArray dxDescs( seqLength, dx.type(), {1, 1, inputSize, batchSize}); af::array workspace(workspaceSize, af::dtype::b8); auto& dy = gradData->dy; if (dy.isempty()) { dy = af::constant(0.0, y.dims(), y.type()); } auto& dhy = gradData->dhy; auto& dcy = gradData->dcy; DevicePtr yRaw(y); DevicePtr workspaceRaw(workspace); DevicePtr reserveSpaceRaw(reserveSpace); { DevicePtr dyRaw(dy); // Has to be set to 0 if empty DevicePtr dhyRaw(dhy); DevicePtr dcyRaw(dcy); DevicePtr wRaw(weightsArray); DevicePtr hxRaw(hxArray); DevicePtr cxRaw(cxArray); DevicePtr dxRaw(dx.array()); DevicePtr dhxRaw(dhx.array()); DevicePtr dcxRaw(dcx.array()); /* We need to update reserveSpace even if we just want the * weight gradients. */ CUDNN_CHECK_ERR(cudnnRNNBackwardData( handle, rnnDesc.descriptor, seqLength, yDesc.descriptors, yRaw.get(), dyDesc.descriptors, dyRaw.get(), dhyDesc.descriptor, dhyRaw.get(), dcyDesc.descriptor, dcyRaw.get(), wDesc.descriptor, wRaw.get(), hxDesc.descriptor, hxRaw.get(), cxDesc.descriptor, cxRaw.get(), dxDescs.descriptors, dxRaw.get(), dhxDesc.descriptor, dhxRaw.get(), dcxDesc.descriptor, dcxRaw.get(), workspaceRaw.get(), workspaceSize, reserveSpaceRaw.get(), reserveSize)); } if (input.isCalcGrad()) { input.addGrad(dx); } if (hx.isCalcGrad() && !hx.isempty()) { hx.addGrad(dhx.as(hx.type())); } if (cx.isCalcGrad() && !cx.isempty()) { cx.addGrad(dcx.as(cx.type())); } if (weights.isCalcGrad()) { if (input.type() == f16) { CUDNN_CHECK_ERR(cudnnSetRNNMatrixMathType( rnnDesc.descriptor, CUDNN_TENSOR_OP_MATH_ALLOW_CONVERSION)); } else { CUDNN_CHECK_ERR( cudnnSetRNNMatrixMathType(rnnDesc.descriptor, CUDNN_DEFAULT_MATH)); } TensorDescriptorArray xDescs( seqLength, x.type(), {1, 1, inputSize, batchSize}); Variable dw( af::constant(0, weightsArray.dims(), weightsArray.type()), false); FilterDescriptor dwDesc(dw); { DevicePtr xRaw(x); DevicePtr dwRaw(dw.array()); DevicePtr hxRaw(hxArray); CUDNN_CHECK_ERR(cudnnRNNBackwardWeights( handle, rnnDesc.descriptor, seqLength, xDescs.descriptors, xRaw.get(), hxDesc.descriptor, hxRaw.get(), yDesc.descriptors, yRaw.get(), workspaceRaw.get(), workspaceSize, dwDesc.descriptor, dwRaw.get(), reserveSpaceRaw.get(), reserveSize)); } weights.addGrad(dw); } } // namespace fl std::tuple<Variable, Variable, Variable> rnn( const Variable& input, const Variable& hiddenState, const Variable& cellState, const Variable& weights, int hiddenSize, int numLayers, RnnMode mode, bool bidirectional, float dropProb) { FL_VARIABLE_DTYPES_MATCH_CHECK(input, hiddenState, cellState, weights); auto& x = input.array(); af::array hxArray = hiddenState.array(); af::array cxArray = cellState.array(); DropoutDescriptor dropout(dropProb); RNNDescriptor rnnDesc( input.type(), hiddenSize, numLayers, mode, bidirectional, dropout); if (input.type() == f16) { CUDNN_CHECK_ERR(cudnnSetRNNMatrixMathType( rnnDesc.descriptor, CUDNN_TENSOR_OP_MATH_ALLOW_CONVERSION)); } else { CUDNN_CHECK_ERR( cudnnSetRNNMatrixMathType(rnnDesc.descriptor, CUDNN_DEFAULT_MATH)); } auto dims = x.dims(); int inputSize = dims[0]; int batchSize = dims[1]; int seqLength = dims[2]; int totalLayers = numLayers * (bidirectional ? 2 : 1); int outSize = hiddenSize * (bidirectional ? 2 : 1); TensorDescriptorArray xDescs( seqLength, x.type(), {1, 1, inputSize, batchSize}); if (!hxArray.isempty() && !(hxArray.dims(0) == hiddenSize && hxArray.dims(1) == batchSize && hxArray.dims(2) == totalLayers)) { throw std::invalid_argument("invalid hidden state dims for RNN"); } if (!cxArray.isempty() && !(mode == RnnMode::LSTM && cxArray.dims(0) == hiddenSize && cxArray.dims(1) == batchSize && cxArray.dims(2) == totalLayers)) { throw std::invalid_argument("invalid cell state dims for RNN"); } af::dim4 hDims = {1, hiddenSize, batchSize, totalLayers}; TensorDescriptor hxDesc(x.type(), hDims); TensorDescriptor cxDesc(x.type(), hDims); auto handle = getCudnnHandle(); size_t paramSize; CUDNN_CHECK_ERR(cudnnGetRNNParamsSize( handle, rnnDesc.descriptor, xDescs.descriptors[0], &paramSize, cudnnMapToType(weights.array().type()))); if (paramSize != weights.array().bytes()) { throw std::invalid_argument( "invalid # of parameters or wrong input shape for RNN"); } FilterDescriptor wDesc(weights); af::array y(outSize, batchSize, seqLength, input.type()); TensorDescriptorArray yDesc(seqLength, y.type(), {1, 1, outSize, batchSize}); af::array hy({hiddenSize, batchSize, totalLayers}, x.type()); TensorDescriptor hyDesc(x.type(), hDims); af::array cy; if (mode == RnnMode::LSTM) { cy = af::array(hy.dims(), x.type()); } TensorDescriptor cyDesc(x.type(), hDims); size_t workspaceSize; CUDNN_CHECK_ERR(cudnnGetRNNWorkspaceSize( handle, rnnDesc.descriptor, seqLength, xDescs.descriptors, &workspaceSize)); af::array workspace(workspaceSize, af::dtype::b8); size_t reserveSize; CUDNN_CHECK_ERR(cudnnGetRNNTrainingReserveSize( handle, rnnDesc.descriptor, seqLength, xDescs.descriptors, &reserveSize)); af::array reserveSpace(reserveSize, af::dtype::b8); { DevicePtr xRaw(x); DevicePtr hxRaw(hxArray); DevicePtr cxRaw(cxArray); DevicePtr wRaw(weights.array()); DevicePtr yRaw(y); DevicePtr hyRaw(hy); DevicePtr cyRaw(cy); DevicePtr workspaceRaw(workspace); DevicePtr reserveSpaceRaw(reserveSpace); CUDNN_CHECK_ERR(cudnnRNNForwardTraining( handle, rnnDesc.descriptor, seqLength, xDescs.descriptors, xRaw.get(), hxDesc.descriptor, hxRaw.get(), cxDesc.descriptor, cxRaw.get(), wDesc.descriptor, wRaw.get(), yDesc.descriptors, yRaw.get(), hyDesc.descriptor, hyRaw.get(), cyDesc.descriptor, cyRaw.get(), workspaceRaw.get(), workspaceSize, reserveSpaceRaw.get(), reserveSize)); } auto gradData = std::make_shared<RNNGradData>(); auto gradFunc = [y, workspaceSize, reserveSize, reserveSpace, numLayers, hiddenSize, mode, bidirectional, dropProb, gradData]( std::vector<Variable>& inputs, const Variable& /* gradOutput */) { rnnBackward( inputs, gradData, y, workspaceSize, reserveSize, reserveSpace, numLayers, hiddenSize, mode, bidirectional, dropProb); }; Variable dummy( af::array(), {input, hiddenState, cellState, weights}, gradFunc); auto dyGradFunc = [gradData](std::vector<Variable>& inputs, const Variable& gradOutput) { if (!inputs[0].isGradAvailable()) { inputs[0].addGrad(Variable(af::array(), false)); } gradData->dy = gradOutput.array(); }; auto dhyGradFunc = [gradData](std::vector<Variable>& inputs, const Variable& gradOutput) { if (!inputs[0].isGradAvailable()) { inputs[0].addGrad(Variable(af::array(), false)); } gradData->dhy = gradOutput.array(); }; auto dcyGradFunc = [gradData](std::vector<Variable>& inputs, const Variable& gradOutput) { if (!inputs[0].isGradAvailable()) { inputs[0].addGrad(Variable(af::array(), false)); } gradData->dcy = gradOutput.array(); }; Variable yv(y, {dummy}, dyGradFunc); Variable hyv(hy, {dummy}, dhyGradFunc); Variable cyv(cy, {dummy}, dcyGradFunc); return std::make_tuple(yv, hyv, cyv); } } // namespace fl
27.74813
80
0.626764
imaginary-person
64fd80b16b5d0947804a07a2b45459fd4fc0f35a
534
cpp
C++
C++/SubsetsofArray.cpp
codedoc7/hacktoberfest2021-3
ddf4e173b10d32332b3c6699de70d1e7bee73a68
[ "MIT" ]
2
2021-12-01T03:35:20.000Z
2022-02-11T01:10:22.000Z
C++/SubsetsofArray.cpp
codedoc7/hacktoberfest2021-3
ddf4e173b10d32332b3c6699de70d1e7bee73a68
[ "MIT" ]
null
null
null
C++/SubsetsofArray.cpp
codedoc7/hacktoberfest2021-3
ddf4e173b10d32332b3c6699de70d1e7bee73a68
[ "MIT" ]
1
2021-10-17T16:24:21.000Z
2021-10-17T16:24:21.000Z
#include<iostream> #include<math.h> using namespace std; int main(){ int n; cin >> n; int* arr = new int[n]; for(int i = 0 ; i < n; i++){ cin>>arr[i]; } int limit = pow(2, n); for (int i = 0; i < limit; i++) { for (int j = n-1; j >= 0; j--) { int rem = i % 2; i = i / 2; if (rem == 0) { } else { } } } return 0; }
14.833333
38
0.29588
codedoc7
8f01886c94162a358ee1a2c2033f824f111a561f
701
cpp
C++
tests/src/ScopedTimerTests.cpp
TemporalResearch/trlang
3bfb98e074cfcfd7f3f3dfe49afc7931f2366405
[ "MIT" ]
null
null
null
tests/src/ScopedTimerTests.cpp
TemporalResearch/trlang
3bfb98e074cfcfd7f3f3dfe49afc7931f2366405
[ "MIT" ]
null
null
null
tests/src/ScopedTimerTests.cpp
TemporalResearch/trlang
3bfb98e074cfcfd7f3f3dfe49afc7931f2366405
[ "MIT" ]
null
null
null
// // Created by Michael Lynch on 21/06/2021. // #include <trlang/timers/ScopedTimer.hpp> #include <auto_test.hpp> #include <catch2/catch.hpp> TRL_TIMER_GROUP( TEST_1, TEST_2); TEST_CASE("shouldDoSomething", "[ManualTest]") { trl::ScopedTimer<>::initTimers(); { trl::ScopedTimer<> timer(trl::timer_group::TEST_1); std::cout << "Hello world" << std::endl; } { trl::ScopedTimer<> timer(trl::timer_group::TEST_2); std::cout << "Different words" << std::endl; } { trl::ScopedTimer<> timer(trl::timer_group::TEST_1); std::cout << "Yet other words" << std::endl; } trl::ScopedTimer<>::printInfo(); }
18.447368
59
0.584879
TemporalResearch
8f073cce18390294b03a1273079cbf3e2c7745b1
1,505
cc
C++
src/abc181/e.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc181/e.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc181/e.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
#ifdef _debug #define _GLIBCXX_DEBUG #endif #include <bits/stdc++.h> typedef long long ll; using namespace std; ll calc_diff(ll v, vector<ll> &w) { auto iter = lower_bound(w.begin(), w.end(), v); int i = distance(w.begin(), iter); vector<ll> cands; if(i == (int)w.size()) cands.push_back(w[i - 1]); else { cands.push_back(w[i]); if(i != 0) cands.push_back(w[i - 1]); } ll diff = 100000000000ll; for(auto c : cands) diff = min(diff, abs(v - c)); return diff; } ll solve(int n, int m, vector<ll> h, vector<ll> w) { sort(h.begin(), h.end()); sort(w.begin(), w.end()); ll teacher_diff = calc_diff(h[0], w); ll res = teacher_diff, temp; for(int i = 1; i < n - 1; i += 2) res += abs(h[i] - h[i + 1]); temp = res; for(int i = 1; i < n - 1; i += 2) { temp -= (teacher_diff + abs(h[i] - h[i + 1])); teacher_diff = calc_diff(h[i], w); temp += (teacher_diff + abs(h[i - 1] - h[i + 1])); res = min(temp, res); temp -= (teacher_diff + abs(h[i - 1] - h[i + 1])); teacher_diff = calc_diff(h[i + 1], w); temp += (teacher_diff + abs(h[i - 1] - h[i])); res = min(temp, res); } return res; } #ifndef _debug int main() { int n, m; cin >> n >> m; vector<ll> h(n), w(m); for(int i = 0; i < n; i++) cin >> h[i]; for(int i = 0; i < m; i++) cin >> w[i]; cout << solve(n, m, h, w) << endl; } #endif
25.508475
58
0.485714
nryotaro
8f09e9b0635be12ac9421df7c5e8dc6a531570c3
4,418
hpp
C++
Test/Service/Memory/Memory/Test/PoolShared.hpp
KonstantinTomashevich/Emergence
83b1d52bb62bf619f9402e3081dd9de6b0cb232c
[ "Apache-2.0" ]
3
2021-06-02T05:06:48.000Z
2022-01-26T09:39:44.000Z
Test/Service/Memory/Memory/Test/PoolShared.hpp
KonstantinTomashevich/Emergence
83b1d52bb62bf619f9402e3081dd9de6b0cb232c
[ "Apache-2.0" ]
null
null
null
Test/Service/Memory/Memory/Test/PoolShared.hpp
KonstantinTomashevich/Emergence
83b1d52bb62bf619f9402e3081dd9de6b0cb232c
[ "Apache-2.0" ]
null
null
null
#include <vector> #include <Testing/Testing.hpp> namespace Emergence::Memory::Test::Pool { struct TestItem { uint64_t integer; float floating; bool flag; }; template <typename Pool> struct FullPoolContext { static constexpr std::size_t PAGE_CAPACITY = 8u; static constexpr std::size_t PAGES_TO_FILL = 2u; FullPoolContext<Pool> () { for (std::size_t index = 0u; index < PAGES_TO_FILL * PAGE_CAPACITY; ++index) { items.emplace_back (pool.Acquire ()); } CHECK_EQUAL (pool.GetAllocatedSpace (), PAGES_TO_FILL * PAGE_CAPACITY * sizeof (TestItem)); } Pool pool {sizeof (TestItem), PAGE_CAPACITY}; std::vector<void *> items; }; template <typename Pool> void AcquireNotNull () { Pool pool {sizeof (TestItem)}; CHECK (pool.Acquire ()); } template <typename Pool> void MultipleAcquiresDoNotOverlap () { Pool pool {sizeof (TestItem)}; auto *first = static_cast<TestItem *> (pool.Acquire ()); auto *second = static_cast<TestItem *> (pool.Acquire ()); TestItem firstValue = {12, 341.55f, false}; TestItem secondValue = {59, 947.11f, true}; *first = firstValue; *second = secondValue; CHECK_EQUAL (firstValue.integer, first->integer); CHECK_EQUAL (firstValue.floating, first->floating); CHECK_EQUAL (firstValue.flag, first->flag); CHECK_EQUAL (secondValue.integer, second->integer); CHECK_EQUAL (secondValue.floating, second->floating); CHECK_EQUAL (secondValue.flag, second->flag); } template <typename Pool> void MemoryReused () { Pool pool {sizeof (TestItem)}; void *item = pool.Acquire (); pool.Release (item); void *anotherItem = pool.Acquire (); CHECK_EQUAL (item, anotherItem); } template <typename Pool> void Clear () { FullPoolContext<Pool> context; context.pool.Clear (); CHECK_EQUAL (context.pool.GetAllocatedSpace (), 0u); // Acquire one item to ensure that pool is in working state. CHECK (context.pool.Acquire ()); } template <typename Pool> void Move () { FullPoolContext<Pool> context; Pool newPool (std::move (context.pool)); CHECK_EQUAL (context.pool.GetAllocatedSpace (), 0u); CHECK_EQUAL (newPool.GetAllocatedSpace (), FullPoolContext<Pool>::PAGES_TO_FILL * FullPoolContext<Pool>::PAGE_CAPACITY * sizeof (TestItem)); // Acquire one item from each pool to ensure that they are in working state. CHECK (context.pool.Acquire ()); CHECK (newPool.Acquire ()); } template <typename Pool> void MoveAssign () { FullPoolContext<Pool> firstContext; FullPoolContext<Pool> secondContext; secondContext.pool = std::move (firstContext.pool); CHECK_EQUAL (firstContext.pool.GetAllocatedSpace (), 0u); CHECK_EQUAL (secondContext.pool.GetAllocatedSpace (), FullPoolContext<Pool>::PAGES_TO_FILL * FullPoolContext<Pool>::PAGE_CAPACITY * sizeof (TestItem)); // Acquire one item from each pool to ensure that they are in working state. CHECK (firstContext.pool.Acquire ()); CHECK (secondContext.pool.Acquire ()); } } // namespace Emergence::Memory::Test::Pool #define SHARED_POOL_TEST(ImplementationClass, TestName) \ TEST_CASE (TestName) \ { \ Emergence::Memory::Test::Pool::TestName<ImplementationClass> (); \ } #define ALL_SHARED_POOL_TESTS(ImplementationClass) \ SHARED_POOL_TEST (ImplementationClass, AcquireNotNull) \ SHARED_POOL_TEST (ImplementationClass, MultipleAcquiresDoNotOverlap) \ SHARED_POOL_TEST (ImplementationClass, MemoryReused) \ SHARED_POOL_TEST (ImplementationClass, Clear) \ SHARED_POOL_TEST (ImplementationClass, Move) \ SHARED_POOL_TEST (ImplementationClass, MoveAssign)
33.984615
120
0.585785
KonstantinTomashevich
557ce8f8b281fcc504e999b28331a0bac59a68a2
1,653
cpp
C++
thirdparty/AngelCode/sdk/tests/test_build_performance/source/test_basic.cpp
kcat/XLEngine
0e735ad67fa40632add3872e0cbe5a244689cbe5
[ "MIT" ]
1
2021-07-25T15:10:39.000Z
2021-07-25T15:10:39.000Z
thirdparty/AngelCode/sdk/tests/test_build_performance/source/test_basic.cpp
kcat/XLEngine
0e735ad67fa40632add3872e0cbe5a244689cbe5
[ "MIT" ]
null
null
null
thirdparty/AngelCode/sdk/tests/test_build_performance/source/test_basic.cpp
kcat/XLEngine
0e735ad67fa40632add3872e0cbe5a244689cbe5
[ "MIT" ]
null
null
null
// // Test author: Andreas Jonsson // #include "utils.h" #include <string> using std::string; namespace TestBasic { #define TESTNAME "TestBasic" static const char *scriptBegin = "void main() \n" "{ \n" " int[] array(2); \n" " int[][] PWToGuild(26); \n"; static const char *scriptMiddle = " array[0] = 121; array[1] = 196; PWToGuild[0] = array; \n"; static const char *scriptEnd = "} \n"; void Test() { printf("---------------------------------------------\n"); printf("%s\n\n", TESTNAME); printf("Machine 1\n"); printf("AngelScript 1.10.1 WIP 1: ??.?? secs\n"); printf("\n"); printf("Machine 2\n"); printf("AngelScript 1.10.1 WIP 1: 9.544 secs\n"); printf("AngelScript 1.10.1 WIP 2: .6949 secs\n"); printf("\nBuilding...\n"); asIScriptEngine *engine = asCreateScriptEngine(ANGELSCRIPT_VERSION); COutStream out; engine->SetMessageCallback(asMETHOD(COutStream,Callback), &out, asCALL_THISCALL); string script = scriptBegin; for( int n = 0; n < 4000; n++ ) script += scriptMiddle; script += scriptEnd; double time = GetSystemTimer(); engine->AddScriptSection(0, TESTNAME, script.c_str(), script.size(), 0); int r = engine->Build(0); time = GetSystemTimer() - time; if( r != 0 ) printf("Build failed\n", TESTNAME); else printf("Time = %f secs\n", time); engine->Release(); } } // namespace
23.956522
83
0.506352
kcat
557d938411061f2c63c83ad3947f837a7524e3d8
1,302
cpp
C++
main.cpp
scottcrossen/datalog
0bc02da43ef1b993a660a82702b97c81c829e79c
[ "MIT" ]
null
null
null
main.cpp
scottcrossen/datalog
0bc02da43ef1b993a660a82702b97c81c829e79c
[ "MIT" ]
null
null
null
main.cpp
scottcrossen/datalog
0bc02da43ef1b993a660a82702b97c81c829e79c
[ "MIT" ]
null
null
null
#include "scanner.h" #include "parser.h" #include "parserclasses.h" #include "database.h" #include <iostream> using namespace std; int main(int argc, char* argv[]){ cout << "Program Compiled Successfully." << endl; string input_file; string output_file; if (argc>3 || argc <3){ cout << "Only " << argc-1 << " arguments supplied, Usage is <file_in> <file_out>" << endl; exit(0); } else { input_file=string(argv[1]); output_file=string(argv[2]); } cout << "Reading in from file: " << input_file << endl; cout << "Writing out from file: " << output_file << endl; Scanner scanner=Scanner(); Parser parser=Parser(); Database database=Database(); scanner.initialize(); parser.initialize(); database.initialize(); scanner.input_file(input_file); scanner.output_file(output_file); scanner.read_in(); scanner.write_out(); parser.output_file(output_file); parser.read_in(scanner.get_tokens()); parser.build(); parser.write_out(); database.read_in(parser.build_objects()); database.build_database(); database.output_file(output_file); database.apply_rules(); database.apply_queries(); database.write_out(); scanner.clear_tokens(); parser.clear(); database.clear(); cout << "Program finished Successfully." << endl; return 0; }
27.702128
94
0.6851
scottcrossen
55810a306a81788a9d34a42415dc8e159aa8e62c
23,640
cpp
C++
thirdparty/geogram/src/lib/exploragram/hexdom/polygon.cpp
AmericaMakes/OASIS-marcwang
7aa10040251d7a1b807a773a45d123e1a52faac5
[ "BSD-2-Clause" ]
1
2021-03-07T14:47:09.000Z
2021-03-07T14:47:09.000Z
thirdparty/geogram/src/lib/exploragram/hexdom/polygon.cpp
AmericaMakes/OASIS-marcwang
7aa10040251d7a1b807a773a45d123e1a52faac5
[ "BSD-2-Clause" ]
null
null
null
thirdparty/geogram/src/lib/exploragram/hexdom/polygon.cpp
AmericaMakes/OASIS-marcwang
7aa10040251d7a1b807a773a45d123e1a52faac5
[ "BSD-2-Clause" ]
1
2021-03-07T00:24:57.000Z
2021-03-07T00:24:57.000Z
/* * OGF/Graphite: Geometry and Graphics Programming Library + Utilities * Copyright (C) 2000-2015 INRIA - Project ALICE * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * * If you modify this software, you should include a notice giving the * name of the person performing the modification, the date of modification, * and the reason for such modification. * * Contact for Graphite: Bruno Levy - Bruno.Levy@inria.fr * Contact for this Plugin: Nicolas Ray - nicolas.ray@inria.fr * * Project ALICE * LORIA, INRIA Lorraine, * Campus Scientifique, BP 239 * 54506 VANDOEUVRE LES NANCY CEDEX * FRANCE * * Note that the GNU General Public License does not permit incorporating * the Software into proprietary programs. * * As an exception to the GPL, Graphite can be linked with the following * (non-GPL) libraries: * Qt, tetgen, SuperLU, WildMagic and CGAL */ #include <exploragram/hexdom/polygon.h> #include <geogram/NL/nl.h> namespace GEO { vec2 Poly2d::barycenter() { vec2 bary(0, 0); FOR(fv, index_t(pts.size())) { bary = bary + (1. / double(pts.size()))*pts[fv]; } return bary; } static int dump_contour_save_id = 0; void Poly2d::dump_contour() { index_t nbv = pts.size(); Mesh export_mesh; export_mesh.vertices.create_vertices(nbv); FOR(i, nbv) X(&export_mesh)[i] = vec3(pts[i][0], pts[i][1], 0); vector<index_t> num; FOR(i, nbv) num.push_back(i); export_mesh.facets.create_polygon(num); char filename[1024]; sprintf(filename, "C:/DATA/2dcontours/nimp2D%i.obj", dump_contour_save_id++); mesh_save(export_mesh, filename); } void Poly3d::dump_contour() { index_t nbv = pts.size(); Mesh export_mesh; export_mesh.vertices.create_vertices(nbv); FOR(i, nbv) X(&export_mesh)[i] = vec3(pts[i][0], pts[i][1], pts[i][2] ); vector<index_t> num; FOR(i, nbv) num.push_back(i); export_mesh.facets.create_polygon(num); char filename[1024]; sprintf(filename, "C:/DATA/2dcontours/nimp3D%i.obj", dump_contour_save_id++); mesh_save(export_mesh, filename); } // returns 1024. if concave angle is encountered or if proposed triangle contains one of pts // otherwise returns max angle of the proposed triangle double Poly2d::cost(index_t i, index_t j, index_t k) { vec2 C[3] = { pts[i], pts[j], pts[k] }; double m = 0; FOR(v, 3) { // note that angle is not the angle inside the triangle, but its complement // angle variable has the "direction" information, thus it is negative for concave angles (right turn) and positive for convex angles (left turn) double angle = atan2( det(C[(v + 1) % 3] - C[(v + 0) % 3], C[(v + 2) % 3] - C[(v + 1) % 3]), dot(C[(v + 1) % 3] - C[(v + 0) % 3], C[(v + 2) % 3] - C[(v + 1) % 3]) ); if (angle <= 0) return 1024.; m = std::max(m, M_PI - angle); } FOR(other, pts.size()) { // TODO c'est con de faire ça, vaut mieux regarder si le triangle est inversé (ça ne gere pas tout [comme, d'ailleurs, le teste courant!]) if (other == i || other == j || other == k) continue; vec2 P = pts[other]; bool inside = true; FOR(l, 3) { inside = inside && (det(normalize(C[(l + 1) % 3] - C[l]), normalize(P - C[l])) > 0); } if (inside) return 1024.; } return m; } // this function has O(n^4) computational cost bool Poly2d::try_triangulate_minweight(vector<index_t>& triangles) { triangles.clear(); index_t n = pts.size(); geo_assert(n >= 3); //if (n == 3) { // FOR(v, 3) { // triangles.push_back(v); // } // return true; //} // we store in this table results of subproblems // table[i*n + j] stores the triangulation cost for points from i to j // the entry table[0*n + n-1] has the final result. std::vector<double> table(n*n, 0.); // this table stores triangle indices: for each subproblem (i,j) we have table[i*n + j]==k, i.e. the triangle is (i,k,j) std::vector<index_t> tri(n*n, index_t(-1)); // note that the table is filled in diagonals; elements below main diagonal are not used at all for (index_t pbsize = 2; pbsize < n; pbsize++) { for (index_t i = 0, j = pbsize; j < n; i++, j++) { // recall that we are testing triangle (i,k,j) which splits the problem (i,j) into // two smaller subproblems (i,k) and (k,j) double minv = 1e20; index_t mink = index_t(-1); for (index_t k = i + 1; k < j; k++) { double val = table[i*n + k] + table[k*n + j] + cost(i, k, j); if (minv <= val) continue; minv = val; mink = k; } geo_assert(mink!=index_t(-1)); table[i*n + j] = minv; tri[i*n + j] = mink; } } // if (table[n-1] >= 1024.) return false; vector<index_t> Q(1, n - 1); FOR(t, Q.size()) { index_t idx = Q[t]; index_t i = idx / n; index_t k = tri[idx]; index_t j = idx % n; geo_assert(i!=index_t(-1) && k != index_t(-1) && j!=index_t(-1)); triangles.push_back(i); triangles.push_back(k); triangles.push_back(j); if (k + 2 <= j) Q.push_back(k*n + j); if (i + 2 <= k) Q.push_back(i*n + k); } if (table[n - 1] >= 1024.) { plop("may dump_contour for debug...");//dump_contour(); } return table[n-1] < 1024.; } // find parity of original points index_t Poly2d::parity_of_original_points() { index_t nbv = pts.size(); index_t dec = 0; double dec_score[2] = { 0, 0 }; FOR(q, nbv / 2) { FOR(d, 2) dec_score[d] = std::max(dec_score[d], std::abs( det(pts[(q * 2 + 0 + d) % nbv] - pts[(q * 2 + 1 + d) % nbv], pts[(q * 2 + 2 + d) % nbv] - pts[(q * 2 + 1 + d) % nbv]))); } if (dec_score[1] < dec_score[0])dec = 1; return dec; } bool Poly2d::middle_point_quadrangulate(vector<index_t>& quads) { index_t nbv = pts.size(); vec2 G = barycenter(); index_t dec = parity_of_original_points(); FOR(q, nbv / 2) { quads.push_back(nbv); FOR(v, 3) quads.push_back((q * 2 + 1 - dec + v) % nbv); } pts.push_back(G); return true; } bool Poly2d::quads_are_valid(vector<index_t>& quads) { // geometric criteria FOR(q, quads.size() / 4) { FOR(e, 4) { vec2 v0 = normalize(pts[quads[4 * q + next_mod(e, 4)]] - pts[quads[4 * q + e]]); vec2 v1 = normalize(pts[quads[4 * q + prev_mod(e, 4)]] - pts[quads[4 * q + e]]); if (det(v0, v1) < sin(M_PI / 8.)) return false; } } return true; } struct Contour2D { void resize(index_t n) { pos_.resize(n); angu_.resize(n);vid_.resize(n);} void compute_angu() { //plop("compute_angu() will not sffice to capture sing 5"); angu_.resize(pos_.size()); FOR(v, pos_.size()) { angu_[v] = 1; vec2 d0 = pos(v) - pos(int(v)-1); vec2 d1 = pos(v+1) - pos(v); double angle = atan2(det(d0, d1), dot(d0, d1)); if (angle < M_PI / 4.) angu_[v] = 0; if (angle < -M_PI / 4.) angu_[v] = -1; } } vec2 normal(int v) {// equals 0 for the singularity mat2 R90; R90(0, 0) = 0; R90(0, 1) = -1; R90(1, 0) = 1; R90(1, 1) = 0; return normalize(R90*(pos(v+1) - pos(v - 1))); } vec2& pos(int i) { return aupp(i, pos_); } int& angu(int i) { return aupp(i, angu_); } int& vid(int i) { return aupp(i, vid_); } vec2& pos(index_t i) { return aupp(i, pos_); } int& angu(index_t i) { return aupp(i, angu_); } int& vid(index_t i) { return aupp(i, vid_); } void show() { GEO::Logger::out("HexDom") << "\npos.size = " << pos_.size() << std::endl; FOR(i, pos_.size()) std::cerr << pos_[i] << "\t"; GEO::Logger::out("HexDom") << "\nangu.size = " << angu_.size() << std::endl; FOR(i, angu_.size()) std::cerr << angu_[i] << "\t"; GEO::Logger::out("HexDom") << "\nvid.size = " << vid_.size() << std::endl; FOR(i, vid_.size()) std::cerr << vid_[i] << "\t"; } void remove(int i) { i = i%int(pos_.size()); pos_.erase(pos_.begin() + i); angu_.erase(angu_.begin() + i); vid_.erase(vid_.begin() + i); } vector<vec2> pos_; vector<int> angu_; vector<int> vid_; }; static int export_debug_mesh_id = 0; struct QuadrangulateWithOneSingularity { QuadrangulateWithOneSingularity(vector<vec2>& p_pts, vector<index_t>& p_quads) :pts(p_pts), quads(p_quads) { R90(0, 0) = 0; R90(0, 1) = -1; R90(1, 0) = 1; R90(1, 1) = 0; } // returns the index of the singularity int init_contour(vector<int>& angu,int sing_valence) { index_t offset = 0; // find the best offset double best_dist2 = 1e20; contour.resize(pts.size()+1); contour.pos(0) = vec2(0, 0); FOR(off, pts.size()) { vec2 dir(1, 0); FOR(v, pts.size()) { contour.pos(v + 1) = contour.pos(v) + dir; if (aupp(off + v + 1, angu) < 0) dir = -(R90*dir); if (aupp(off + v + 1, angu) > 0) dir = R90*dir; } vec2 diag = contour.pos(-1) ; if (sing_valence == 3 && diag.x == -diag.y && diag.length2() < best_dist2) { best_dist2 = diag.length2(); offset = off; }; if (sing_valence == 5 && diag.x == diag.y && diag.length2() < best_dist2) { best_dist2 = diag.length2(); offset = off; }; } // decal gridpos w.r.t offset vec2 dir(1, 0); FOR(v, pts.size()) { contour.pos(v + 1) = contour.pos(v) + dir; if (aupp(offset + v + 1, angu) < 0) dir = -(R90*dir); if (aupp(offset + v + 1, angu) > 0) dir = R90*dir; } // define mapping contour -> pts FOR(v, pts.size() ) contour.vid(v ) = int(offset + v ) % int(pts.size()); contour.vid_.back() = contour.vid_.front(); // singularity on border TODO CHECK angu on singularity ! if ((contour.pos(-1) - contour.pos(0)).length2() < .1) { contour.remove(int(contour.pos_.size()) - 1); contour.compute_angu(); return 0; } // add pts vec2 A = contour.pos(0); vec2 B = contour.pos(-1); if (sing_valence == 3) for (int i = int(B.x + 1.0); i < int(A.x); i++) { contour.pos_.push_back(vec2(i, B.y)); contour.vid_.push_back(int(pts.size())); pts.push_back(contour.pos_.back()); } if (sing_valence == 5) for (int i = int(B.x - 1); i > int(A.x); i--) { contour.pos_.push_back(vec2(double(i), B.y)); contour.vid_.push_back(int(pts.size())); pts.push_back(contour.pos_.back()); } index_t singularity_index = contour.pos_.size(); contour.pos_.push_back(vec2(A.x, B.y)); contour.vid_.push_back(int(pts.size())); pts.push_back(contour.pos_.back()); for (int j = int(B.y - 1); j > int(A.y); j--) { contour.vid_.push_back(contour.vid(2*singularity_index-contour.pos_.size())); contour.pos_.push_back(vec2(A.x, double(j))); } contour.compute_angu(); contour.angu(singularity_index) = 2 - sing_valence; return int(singularity_index); } void export_debug_mesh() { Mesh outm; outm.vertices.create_vertices(contour.pos_.size()); vector<index_t> vid(contour.pos_.size()); FOR(i, contour.pos_.size()) { vid[i] = i; X(&outm)[i] = vec3(contour.pos(i)[0], contour.pos(i)[1], 0); } Attribute<int> angu_attr(outm.vertices.attributes(), "angu"); FOR(i, contour.pos_.size()) angu_attr[i] = contour.angu(i); outm.facets.create_polygon(vid); mesh_save(outm, "C:/DATA/2dcontours/contour2D"+ String::to_string(export_debug_mesh_id ++) +".geogram"); } bool try_to_punch() { if (contour.pos_.size() < 4) return false; FOR(v, contour.pos_.size()) { if (contour.angu(v) != 1) continue; // cut ear if (contour.angu(v + 1) == 1) { FOR(s, 4) quads.push_back(index_t(contour.vid(int(v) - 1 + int(s)))); contour.remove(int(v)); contour.remove(int(v)); contour.angu(int(v) - 1)++; contour.angu(int(v)) ++; return true; } // add new point vec2 npos = contour.pos(v - 1) + contour.pos(v + 1) - contour.pos(v); bool conflict = false; FOR(vv, contour.pos_.size()) if (vv != v && (contour.pos(vv) - npos).length2() < .1) conflict = true; if (conflict) continue; FOR(s,3) quads.push_back(index_t(contour.vid(int(v) - 1+int(s)))); quads.push_back(index_t(pts.size())); contour.vid(v) = int(pts.size()); pts.push_back(npos); contour.pos(v) = npos; contour.angu(v-1) ++; contour.angu(v) = -1; contour.angu(v+1) ++; return true; } return false; } bool apply(vector<int>& angu,int sing_valence) { int singularity_index=-1; index_t border_size = pts.size(); if (sing_valence == 3|| sing_valence == 5) { singularity_index = init_contour(angu, sing_valence); } else if (sing_valence == 4) { contour.resize(pts.size()); vec2 dir(1, 0); contour.pos(0) = vec2(0, 0); for (index_t v = 1; v < pts.size();v++) { contour.pos(v) = contour.pos(v - 1) + dir; if (angu[v]< 0) dir = -(R90*dir); if (angu[v]> 0) dir = R90*dir; } FOR(v, pts.size()) contour.vid(v) = int(v); FOR(v, pts.size()) contour.angu(v) = angu[v]; if ((contour.pos_.back() + dir - contour.pos_.front()).length2() > .1) return false; // check that it is closed } else { return false; } //plop("valok"); //plop(sing_valence); //plop(singularity_index); //plop(border_size); //plop(contour.pos_.size()); vector<vec2> theta_r(border_size); vec2 O(.5, .5); if (singularity_index!=-1) O= contour.pos(singularity_index); FOR(v, border_size) theta_r[v][1] = (contour.pos(v) - O).length(); theta_r[0][0] = 0; FOR(v, border_size - 1) { theta_r[v + 1][0] = theta_r[v][0] + atan2(det(contour.pos(v) - O, contour.pos(v + 1) - O), dot(contour.pos(v) - O, contour.pos(v + 1) - O)); } FOR(v, border_size) FOR(vv, border_size) if (vv != v && (theta_r[vv] - theta_r[v]).length2() < .0001) { FOR(w, theta_r.size()) plop(theta_r[w]); return false; } while (try_to_punch()) { //export_debug_mesh(); //plop(export_debug_mesh_id); if (quads.size() > 1000) geo_assert_not_reached; } nlNewContext(); nlSolverParameteri(NL_LEAST_SQUARES, NL_TRUE); nlSolverParameteri(NL_NB_VARIABLES, NLint(2*pts.size())); nlBegin(NL_SYSTEM); FOR(v, border_size) FOR(d,2){ nlSetVariable(v * 2 +d, pts[v][d]); nlLockVariable(v * 2 + d); } nlBegin(NL_MATRIX); FOR(q, quads.size() / 4) FOR(e, 4) FOR(d, 2) { nlBegin(NL_ROW); nlCoefficient(quads[4 * q + e]*2+d, -1.); nlCoefficient(quads[4 * q + ((e+1)%4)] * 2 + d, 1.); nlEnd(NL_ROW); } nlEnd(NL_MATRIX); nlEnd(NL_SYSTEM); nlSolve(); FOR(v, pts.size()) FOR(d, 2) pts[v][d]= nlGetVariable(2*v+d); nlDeleteContext(nlGetCurrent()); //export_debug_mesh(); if (contour.pos_.size() > 2) { pts.resize(index_t(border_size)); quads.clear(); return false; } if (!Poly2d(pts).quads_are_valid(quads)) { //export_debug_mesh(); FOR(i, contour.pos_.size()) plop(contour.pos(i)); } return Poly2d(pts).quads_are_valid(quads); } mat2 R90; vector<vec2>& pts; vector<index_t>& quads; Contour2D contour; }; bool Poly2d::try_quad_cover(vector<index_t>& quads) { vector<int> angu(pts.size(), 1); int sing_valence = 0; FOR(v, pts.size()) { vec2 d0 = aupp(v, pts) - aupp(v - 1, pts); vec2 d1 = aupp(v + 1, pts) - aupp(v, pts); double angle = atan2(det(d0, d1), dot(d0, d1)); if (angle < M_PI / 4.) angu[v] = 0; if (angle < -M_PI / 4.) angu[v] = -1; sing_valence += angu[v]; } //plop("try_quad_cover"); //dump_contour(); QuadrangulateWithOneSingularity doit(pts,quads); if (doit.apply(angu, sing_valence)) return true; return false; } bool Poly2d::try_quadrangulate(vector<index_t>& quads) { bool verbose = false; index_t nbv = pts.size(); if (verbose) plop(nbv); if (nbv < 4) return false; if (nbv == 4) { FOR(v, 4) quads.push_back(v); if (!quads_are_valid(quads)) { GEO::Logger::out("HexDom") << "FAIL" << std::endl; return false; } return true; } if (nbv % 2 != 0) { GEO::Logger::out("HexDom") << "There is no way to quadrangulate a surface with an odd number of boundary edges" << std::endl; return false; } return try_quad_cover(quads); /* // precompute a few things vector<double> angle(nbv); vector<double> length(nbv); double ave_length = 0; FOR(i, nbv) { vec2 P[3]; FOR(p, 3) P[p] = aupp(i + p - 1, pts); angle[i] = (180. / M_PI)*atan2(det(P[1] - P[0], P[2] - P[1]), dot(P[1] - P[0], P[2] - P[1])); if (verbose)GEO::Logger::out("HexDom") << "i= " << i << "angle = " << angle[i] << std::endl; length[i] = (P[1] - P[0]).length() / double(nbv); ave_length += length[i]; } plop("gna"); // define outputs of the search index_t start = index_t(-1); index_t end = index_t(-1); index_t nb_nv_pts = index_t(-1); double best_score = 0; index_t dec = parity_of_original_points(); plop("gna"); FOR(test_start, nbv) { plop(test_start); index_t test_end; index_t test_nb_nv_pts; double test_score; plop("gna"); FOR(d, nbv - 5) { plop(d); test_end = test_start + d + 3; vec2 A[3]; FOR(i, 3) A[i] = aupp(int(test_start + i) - 1, pts); vec2 B[3]; FOR(i, 3) B[i] = aupp(int(test_end + i) - 1, pts); vec2 nA1A2 = normalize(A[2] - A[1]); vec2 nA1A0 = normalize(A[0] - A[1]); vec2 nB1B2 = normalize(B[2] - B[1]); vec2 nB1B0 = normalize(B[0] - B[1]); vec2 nAB = normalize(B[1] - A[1]); vec2 nBA = -nAB; double worst_det = 1; worst_det = std::min(worst_det, det(nA1A2, nAB)); worst_det = std::min(worst_det, det(nAB, nA1A0)); worst_det = std::min(worst_det, det(nB1B2, nBA)); worst_det = std::min(worst_det, det(nBA, nB1B0)); test_score = worst_det; double AB_relative_length = floor((B[1] - A[1]).length() / ave_length); test_nb_nv_pts = index_t(std::max(0, int(AB_relative_length) - 1)); if (test_nb_nv_pts % 2 != int(d % 2)) { if (test_nb_nv_pts == 0) test_nb_nv_pts = 1; else test_nb_nv_pts--; } if (angle[test_start] < 1) test_score += 1; if (angle[test_end] < 1) test_score += 1; if (angle[test_start] < -45) test_score += 2; if (angle[test_end] < -45) test_score += 2; if ((test_start % 2) == 1 - dec) test_score -= 10; if ((test_end % 2) == 1 - dec) test_score -= 10; test_nb_nv_pts = 1; if (best_score < test_score) { bool can_cut = true; FOR(dd, nbv) { index_t ind = test_start + dd; if (ind > test_start && ind < test_end) can_cut = can_cut && det(nAB, aupp(ind, pts) - A[1]) < 0; if (ind > test_end) can_cut = can_cut && det(nAB, aupp(ind, pts) - A[1]) > 0; } if (verbose) std::cerr << "can_cut = " << can_cut << " test_score = " << test_score << " test_start = " << test_start << " test_end = " << test_end << " test_nb_nv_pts = " << test_nb_nv_pts << std::endl; if (can_cut) { start = test_start; end = test_end; nb_nv_pts = test_nb_nv_pts; best_score = test_score; } } } } plop("gna"); if (nbv > 8) if (nb_nv_pts != index_t(-1)) { if (verbose)GEO::Logger::out("HexDom") << "remove quad strip from " << start << " with score = " << best_score << " with nbpts" << nb_nv_pts << std::endl; vector<index_t> global_vid[2]; // gives indices in "pts" from indices in "poly[i]" // fill both half with existing points //int end = start + nb_nv_pts + 3; FOR(d, end - start + 1) global_vid[0].push_back((start + d) % nbv); FOR(d, nbv - (end - start) + 1) global_vid[1].push_back((end + d) % nbv); // add new vertices along the cut FOR(i, nb_nv_pts) global_vid[0].push_back(nbv + i); FOR(i, nb_nv_pts) global_vid[1].push_back(nbv + (nb_nv_pts - 1 - i)); FOR(i, nb_nv_pts) { double c = 1.0 - double(i + 1) / double(nb_nv_pts + 1); pts.push_back((1. - c)*pts[start] + c*pts[end% nbv]); } // solve on two halves vector<vec2> poly[2]; FOR(i, 2) FOR(fv, global_vid[i].size()) poly[i].push_back(pts[global_vid[i][fv]]); vector<index_t> poly_quad[2]; FOR(i, 2) if (!Poly2d(poly[i]).try_quadrangulate(poly_quad[i])) return false; // add new pts to global FOR(i, 2) for (index_t d = global_vid[i].size(); d < poly[i].size(); d++) { global_vid[i].push_back(pts.size()); pts.push_back(poly[i][d]); } FOR(i, 2) FOR(qu, poly_quad[i].size()) quads.push_back(global_vid[i][poly_quad[i][qu]]); if (!quads_are_valid(quads)) { GEO::Logger::out("HexDom") << "FAIL remove quad strip" << std::endl; return false; } return true; } plop("gna"); if (verbose) GEO::Logger::out("HexDom") << "middle_point_quadrangulate(quads)" << std::endl; middle_point_quadrangulate(quads); if (!quads_are_valid(quads)) { GEO::Logger::out("HexDom") << "FAIL middle_point_quadrangulate" << std::endl; return false; } return true; */ } /*****************************************************************************************************/ vec3 Poly3d::barycenter() { vec3 bary(0, 0, 0); FOR(fv, pts.size()) { bary = bary + (1. / double(pts.size()))*pts[fv]; } return bary; } vec3 Poly3d::normal() { vec3 n(0, 0, 0); vec3 bary = barycenter(); FOR(fv, pts.size()) { n = n + cross(pts[fv] - bary, pts[next_mod(fv, pts.size())] - bary); // plop(n); } n = normalize(n); return n; } bool Poly3d::try_triangulate_minweight(vector<index_t>& triangles) { index_t nbv = pts.size(); if (nbv == 3) { FOR(v, 3) { triangles.push_back(v); } return true; } geo_assert(nbv > 3); vector<vec2> pts2d; Basis3d b(normal()); FOR(fv, nbv) { pts2d.push_back(b.project_xy(pts[fv])); } return Poly2d(pts2d).try_triangulate_minweight(triangles); } /** * WARNING: it may introduce new vertices in pts */ bool Poly3d::try_quadrangulate(vector<index_t>& quads) { index_t nbv = pts.size(); if (nbv < 4) return false; vec3 G = barycenter(); if (normal().length2() < 1e-20) return false; Basis3d b(normal()); vector<vec2> pts2d; FOR(fv, nbv) pts2d.push_back(b.project_xy(pts[fv] - G)); Poly2d p2d(pts2d); if (!p2d.try_quadrangulate(quads)) { //dump_contour(); return false; } for (index_t i = pts.size(); i < p2d.pts.size(); i++) pts.push_back(G + b.un_project_xy(p2d.pts[i])); return true; } }
31.562083
166
0.572589
AmericaMakes
55888732f06171bdbcd4fcf63b7c1339a50da931
6,727
hpp
C++
cmake-build-debug/test/unit/mechanisms/test_kinlva.hpp
anstaf/arbsimd
c4ba87b02b26a47ef33d0a3eba78a4f330c88073
[ "BSD-3-Clause" ]
null
null
null
cmake-build-debug/test/unit/mechanisms/test_kinlva.hpp
anstaf/arbsimd
c4ba87b02b26a47ef33d0a3eba78a4f330c88073
[ "BSD-3-Clause" ]
null
null
null
cmake-build-debug/test/unit/mechanisms/test_kinlva.hpp
anstaf/arbsimd
c4ba87b02b26a47ef33d0a3eba78a4f330c88073
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <cmath> #include <arbor/mechanism_abi.h> extern "C" { arb_mechanism_type make_testing_test_kinlva() { // Tables static arb_field_info globals[] = { { "gbar", "S / cm2", 0.0002, -179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000, 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000 }, { "gl", "S / cm2", 0.0001, -179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000, 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000 }, { "eca", "mV", 120, -179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000, 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000 }, { "el", "mV", -65, -179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000, 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000 } }; static arb_size_type n_globals = 4; static arb_field_info state_vars[] = { { "m", "", NAN, -179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000, 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000 }, { "h", "", NAN, -179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000, 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000 }, { "s", "", NAN, -179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000, 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000 }, { "d", "", NAN, -179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000, 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000 } }; static arb_size_type n_state_vars = 4; static arb_field_info parameters[] = { }; static arb_size_type n_parameters = 0; static arb_ion_info ions[] = { { "ca", false, false, false, false, false, false, 0 } }; static arb_size_type n_ions = 1; arb_mechanism_type result; result.abi_version=ARB_MECH_ABI_VERSION; result.fingerprint="<placeholder>"; result.name="test_kinlva"; result.kind=arb_mechanism_kind_density; result.is_linear=false; result.has_post_events=false; result.globals=globals; result.n_globals=n_globals; result.ions=ions; result.n_ions=n_ions; result.state_vars=state_vars; result.n_state_vars=n_state_vars; result.parameters=parameters; result.n_parameters=n_parameters; return result; } arb_mechanism_interface* make_testing_test_kinlva_interface_multicore(); arb_mechanism_interface* make_testing_test_kinlva_interface_gpu(); }
149.488889
707
0.888658
anstaf
558d0896af3642b5812bf4a837d85454e1ac0dcd
675
cpp
C++
Part6/listing28_1/Listing28_1.cpp
erikyuzwa/learn-cpp-by-making-games
1ab87e2395245edc8f7bedab9f6afc5dadaedcaf
[ "Unlicense" ]
2
2020-04-24T08:26:09.000Z
2020-11-17T15:18:12.000Z
Part6/listing28_1/Listing28_1.cpp
erikyuzwa/learn-cpp-by-making-games
1ab87e2395245edc8f7bedab9f6afc5dadaedcaf
[ "Unlicense" ]
1
2020-11-22T19:40:08.000Z
2020-11-22T19:40:08.000Z
Part6/listing28_1/Listing28_1.cpp
erikyuzwa/learn-cpp-by-making-games
1ab87e2395245edc8f7bedab9f6afc5dadaedcaf
[ "Unlicense" ]
1
2021-07-28T16:05:20.000Z
2021-07-28T16:05:20.000Z
#include <iostream> using namespace std; class Airplane { public: int wheels; public: Airplane() { cout << "Airplane::Constructor()" << endl; wheels = 4; } void setWheels(int new_wheels) { wheels = new_wheels; } }; int main(int argc, char* argv[]) { //When we declare an object, the program automatically calls the //default //constructor for that object Airplane Cessna; //note that this is identical to declaring Cessna as //Airplane Cessna(); cout << "Our airplane has " << Cessna.wheels << " wheels" << endl; return 0; }
16.875
72
0.551111
erikyuzwa
558e904f7e480afd16c57fd0a4d8b66fa36e151d
539
cpp
C++
Learning/Negative numbers shifting/Negative numbers shifting.cpp
LightTab2/Cpp-programs-archive
8ea128b199ff9b3a59f8309ebecc8759923f6de7
[ "CC0-1.0" ]
null
null
null
Learning/Negative numbers shifting/Negative numbers shifting.cpp
LightTab2/Cpp-programs-archive
8ea128b199ff9b3a59f8309ebecc8759923f6de7
[ "CC0-1.0" ]
null
null
null
Learning/Negative numbers shifting/Negative numbers shifting.cpp
LightTab2/Cpp-programs-archive
8ea128b199ff9b3a59f8309ebecc8759923f6de7
[ "CC0-1.0" ]
null
null
null
#include <iostream> bool nolog = false, nopause = false; int main(int argc, char *args[]) { for (int x = 0; x != argc; ++x) { if (args[x] == "-nolog") nolog = true; else if (args[x] == "-nopause") nopause = true; } int i = 0; std::cin >> i; for (int n = 0; n != 33; ++n) std::cout << (i << n) << std::endl; if (!nolog) std::cout << "Now right-shifts\n"; for (int n = 0; n != 33; ++n) std::cout << (i >> n) << std::endl; if (!nopause) system("pause"); return 0; }
22.458333
55
0.465677
LightTab2
5590315c8aed4ad3dabd3235a27ebefa642d52a0
1,361
cpp
C++
libs/ms/src/container/sv_db/pool_container.cpp
ITBE-Lab/ma
039e2833dd2e50df9285f183ff774bd87bbae710
[ "MIT" ]
40
2019-04-28T21:16:45.000Z
2022-02-05T05:54:47.000Z
libs/ms/src/container/sv_db/pool_container.cpp
ITBE-Lab/ma
039e2833dd2e50df9285f183ff774bd87bbae710
[ "MIT" ]
11
2019-04-28T22:29:12.000Z
2022-02-21T14:07:10.000Z
libs/ms/src/container/sv_db/pool_container.cpp
ITBE-Lab/ma
039e2833dd2e50df9285f183ff774bd87bbae710
[ "MIT" ]
2
2019-05-06T15:29:23.000Z
2021-01-08T13:22:17.000Z
#include "ms/container/sv_db/pool_container.h" #ifdef WITH_DB using namespace libMS; #ifdef WITH_PYTHON #include "ms/container/sv_db/py_db_conf.h" #include "pybind11_json/pybind11_json.hpp" void exportPoolContainer( SubmoduleOrganizer& xOrganizer ) { py::class_<PoolContainer<DBCon>, Container, std::shared_ptr<PoolContainer<DBCon>>>( xOrganizer.container( ), "PoolContainer" ) .def( py::init<size_t, std::string>( ) ); py::class_<DBConSingle, std::shared_ptr<DBConSingle>>( xOrganizer.util( ), "DbConn" ) .def( py::init<std::string>( ) ) /* This makes it so, that DbConn can be initialized from a python dictionary. * It makes use of https://github.com/pybind/pybind11_json * For some reason the nlohmann::json object can not be passed directly to py::init, * however the py::object is converted automatically since the header pybind11_json.hpp is included here. * @todo we could drop the guy an issue asking/suggesting to make it possible to putt in the json directly, * which would make the code more readable */ .def( py::init<py::object /* = json */>( ) ) .def( "drop_schema", &DBConSingle::dropSchema ); } // function #endif // WITH_PYTHON #endif // WITH_DB
41.242424
115
0.640705
ITBE-Lab
55959369f97f125187ae85b7f187fa7af918a52e
1,681
cpp
C++
src/shared/engine/Check_Win_Command.cpp
Kuga23/Projet-M2
85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433
[ "MIT" ]
null
null
null
src/shared/engine/Check_Win_Command.cpp
Kuga23/Projet-M2
85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433
[ "MIT" ]
null
null
null
src/shared/engine/Check_Win_Command.cpp
Kuga23/Projet-M2
85c879b8fd1ed4fdf89eedd9f89841cbd7a1e433
[ "MIT" ]
null
null
null
#include "Check_Win_Command.h" // to use console #include <iostream> using namespace engine; using namespace state; using namespace std; Check_Win_Command::Check_Win_Command() { Id = CHECK_WIN; } Check_Win_Command::~Check_Win_Command() { } void Check_Win_Command::exec(state::State &state) { int winnedID; unsigned int p1nbDeathChar=0; unsigned int p2nbDeathChar=0; // Not very optimal code, tired will see later for (auto &charac: state.getListCharacters(0)){ // Player 1 if(charac->getStatus() == DEATH ) p1nbDeathChar++; } for (auto &charac: state.getListCharacters(1)){ // PLayer 2 if(charac->getStatus() == DEATH ) p2nbDeathChar++; } if (p1nbDeathChar==state.getListCharacters(0).size()){ winnedID=2; state.setEndGame(true); state.setGameWinner(winnedID); StateEvent se{StateEventID::ENDGAME}; state.notifyObservers(se, state); cout << endl << "GAME OVER" << endl; cout << endl << "THE GAME WINNER IS THE PLAYER No" << winnedID << endl; cout << "\n"; } else if (p2nbDeathChar==state.getListCharacters(1).size()){ winnedID=1; state.setEndGame(true); state.setGameWinner(winnedID); StateEvent se{StateEventID::ENDGAME}; state.notifyObservers(se, state); cout << endl << "GAME OVER" << endl; cout << endl << "THE GAME WINNER IS THE PLAYER No " << winnedID << endl; cout << "\n"; } } // Ajout de la fonction serialize Json::Value Check_Win_Command::serialize (){ Json::Value myCommand; myCommand["id"] = Id; return myCommand; }
25.089552
80
0.618679
Kuga23
559627849abb1ac1d1cbe07b22feb3443a6085a6
11,204
cpp
C++
source/compiler/transform.cpp
ChillMagic/ICM
a0ee83e5bbd2aef216cc28faa5d5dad36c99d606
[ "Apache-2.0" ]
9
2016-06-14T15:38:42.000Z
2017-09-03T09:08:17.000Z
source/compiler/transform.cpp
ChillMagic/ICM
a0ee83e5bbd2aef216cc28faa5d5dad36c99d606
[ "Apache-2.0" ]
1
2018-01-17T09:22:30.000Z
2018-01-17T10:10:42.000Z
source/compiler/transform.cpp
ChillMagic/ICM
a0ee83e5bbd2aef216cc28faa5d5dad36c99d606
[ "Apache-2.0" ]
null
null
null
#include "basic.h" #include "compiler/transform.h" #include "compiler/analysisbase.h" //#include "runtime/objectdef.h" #include "temp-getelement.h" namespace ICM { namespace Compiler { bool PrintCompilingProcess = false; class PreliminaryCompile : private AnalysisBase { public: PreliminaryCompile(NodeTable &Table) : AnalysisBase(Table) {} void start() { if (PrintCompilingProcess) println("PreliminaryCompile"); compileSub(GetNode(1), GetElement(0, 0)); if (PrintCompilingProcess) { println("-->"); printTable(); } } private: Element& adjustElement(Element &elt) { if (elt.isRefer()) compileSub(GetRefer(elt), elt); return elt; } bool adjustNode(Node &node, size_t begin = 0) { for (Element &e : rangei(node.begin() + begin, node.end())) { adjustElement(e); } return true; } bool checkBoolExp(const Element &elt) { if (elt.isIdent() || elt.isRefer() || elt.isLiteralType(T_Boolean)) return true; println("Error : BoolExp has Non Boolean Value."); return false; } VecElt createDoList(const NodeRange &nr) { VecElt dolist; dolist.reserve(nr.size() + 1); dolist.push_back(Element::Keyword(do_)); dolist.insert(dolist.end(), nr.begin(), nr.end()); return dolist; } void resetNode(Node &node) { Element front = node.front(); node.clear(); node.push_back(front); } void setDoNode(Node &node, VecElt &dolist) { size_t id = Table.size(); Node *p = new Node(id, std::move(dolist)); Table.push_back(std::move(std::unique_ptr<Node>(p))); Element e = Element::Refer(id); node.push_back(e); adjustNode(*p, 1); } private: // bool compileSub(Node &node, Element &refelt) { if (PrintCompilingProcess) println(to_string(node)); if (node[0].isKeyword()) return compileKeyword(node, refelt); else if (node[0].isIdent() || node[0].isRefer()) return compileCall(node, refelt); else return error("Error in compileSub."); } // call ... bool compileCall(Node &node, Element &refelt) { adjustNode(node); node.push_front(Element::Keyword(call_)); return true; } bool compileKeyword(Node &node, Element &refelt) { switch (node[0].getKeyword()) { case if_: return compileIf(node, refelt); case ife_: return compileIfe(node, refelt); case for_: return compileFor(node, refelt); case while_: return compileWhile(node, refelt); case loop_: return compileLoop(node, refelt); case do_: return adjustNode(node, 1); case list_: return adjustNode(node, 1); case p_: return adjustNode(node, 1); case call_: return adjustNode(node, 1); case disp_: return compileDisp(node, refelt); case let_: case set_: case ref_: case cpy_: return compileLSRC(node, refelt); case dim_: case restrict_: return compileRestrictDim(node, refelt); case define_: return compileDefine(node, refelt); default: return error("Error with unkonwn Keyword."); } } // (disp I|R) // --> (disp I|R) bool compileDisp(Node &node, Element &refelt) { if (node.size() == 2) { Element &e = node[1]; if (e.isIdent() || e.isRefer()) { if (e.isRefer()) { compileSub(GetRefer(e), e); } return true; } } return error("Syntax error with disp."); } // (if E0 E1... elsif E2 E3... else E4 E5...) // --> (if E0 E2 E4 R{do E1...} R{do E3...} R{do E5...}) bool compileIf(Node &node, Element &refelt) { VecElt condlist; vector<VecElt> dolists; compileIfSub(rangei(node.begin() + 1, node.end()), condlist, dolists); if (dolists.size() == condlist.size()) { dolists.push_back(VecElt{ Element::Keyword(do_) }); } resetNode(node); node.insert(node.end(), condlist.begin(), condlist.end()); for (auto &dolist : dolists) { setDoNode(node, dolist); } return true; } bool compileIfSub(const NodeRange &nr, VecElt &condList, vector<VecElt> &dolists) { Element &bexp = *nr.begin(); checkBoolExp(adjustElement(bexp)); condList.push_back(bexp); dolists.push_back(VecElt{ Element::Keyword(do_) }); VecElt &dolist = dolists.back(); auto ib = nr.begin() + 1; auto ie = nr.end(); for (auto iter = ib; iter != ie; ++iter) { Element &e = *iter; if (e.isKeyword()) { if (e.getKeyword() == elsif_) { return compileIfSub(rangei(iter + 1, ie), condList, dolists); } else if (e.getKeyword() == else_) { VecElt elsedolist = createDoList(rangei(iter + 1, ie)); dolists.push_back(elsedolist); return true; } } dolist.push_back(e); } return true; } // (? BE E1 E2) // --> (? BE E1 E2) bool compileIfe(Node &node, Element &refelt) { if (node.size() >= 3) { Element &bexp = node[1]; checkBoolExp(adjustElement(bexp)); adjustElement(node[2]); if (node.size() == 4) { adjustElement(node[3]); } else { node.push_back(Element::Identifier(GlobalIdentNameMap["nil"])); } return true; } else return error("Syntax error in '?'."); } // (loop E...) // --> (loop R{do E...}) bool compileLoop(Node &node, Element &refelt) { if (node.size() == 1) return error("dolist will not be blank."); VecElt dolist = createDoList(rangei(node.begin() + 1, node.end())); resetNode(node); setDoNode(node, dolist); return true; } // (while E0 E...) // --> (while E0 R{do E...}) bool compileWhile(Node &node, Element &refelt) { if (node.size() == 1) return error("none boolean exp."); else if (node.size() == 2) return error("dolist will not be blank."); Element &bexp = node[1]; checkBoolExp(adjustElement(bexp)); VecElt dolist = createDoList(rangei(node.begin() + 2, node.end())); resetNode(node); node.push_back(bexp); setDoNode(node, dolist); return true; } // (for I in E0 to E1 E...) // --> (for I E0 E1 R{do E...}) bool compileFor(Node &node, Element &refelt) { // Check if (node.size() < 6) return error("Syntax error for 'for'."); else if (node.size() == 6) return error("dolist will not be blank."); else if (!node[1].isIdent()) return error("for var must be Identifier."); else if (!isKey(node[2], in_) || !isKey(node[4], to_)) return error("Syntax error for 'for'."); // Compile Element I = node[1]; Element E0 = adjustElement(node[3]); Element E1 = adjustElement(node[5]); VecElt dolist = createDoList(rangei(node.begin() + 6, node.end())); resetNode(node); node.push_back(I); node.push_back(E0); node.push_back(E1); setDoNode(node, dolist); return true; } // (let/set/ref/cpy I E) or (ref/cpy E) bool compileLSRC(Node &node, Element &refelt) { KeywordID key = node.front().getKeyword(); if (node.size() == 3) { if (node[1].isIdent()) { adjustElement(node[2]); return true; } else return error("var must be Identifier."); } else if (node.size() == 2) { if (key == ref_ || key == cpy_) { adjustElement(node[1]); return true; } else return error("Syntax error in '" + ICM::to_string(key) + "'."); } else return error("Syntax error in '" + ICM::to_string(key) + "'."); } // (restrict/dim I E) bool compileRestrictDim(Node &node, Element &refelt) { KeywordID key = node.front().getKeyword(); if (node.size() == 3) { if (node[1].isIdent()) { adjustElement(node[2]); return true; } else return error("var must be Identifier."); } else return error("Syntax error in '" + ICM::to_string(key) + "'."); } // (define I E) bool compileDefine(Node &node, Element &refelt) { KeywordID key = node.front().getKeyword(); if (node.size() == 3) { if (node[1].isIdent()) { adjustElement(node[2]); return true; } else return error("var must be Identifier."); } else return error("Syntax error in '" + ICM::to_string(key) + "'."); } }; /*class CompiletimeEvaluate : public AnalysisBase { public: CompiletimeEvaluate(NodeTable &Table) : AnalysisBase(Table) {} bool eval(Element &element, Object &result) { } bool isIdentDefined(Element &element) { assert(element.isIdent()); } private: Object* call(Function::FuncObject &func, DataList &list) { return func.call(list).get(); } };*/ class IdentifierAnalysis : public AnalysisBase { public: IdentifierAnalysis(NodeTable &Table) : AnalysisBase(Table) {} void start() { if (PrintCompilingProcess) println("IdentifierAnalysis"); setIdentSub(GetNode(1)); if (PrintCompilingProcess) { println("-->"); printTable(); } } void setIdentSub(Node &node) { if (PrintCompilingProcess) println(to_string(node)); // define if (node[0].isKeyword()) { if (node[0].getKeyword() == define_) { println("Making Define..."); Element &ident = node[1]; IdentSpaceIndex sid = getCurrentIdentSpaceIndex(); IdentIndex ii = { sid }; println(to_string(ident)); setIdent(ident, I_Data, ii); } else if (node[0].getKeyword() == module_) { println("Making Module..."); println(to_string(node[1])); } } // other bool change = false; for (size_t i : range(0, node.size())) { Element &e = node[i]; if (e.isIdent()) setIdentifier(e); else if (e.isRefer()) setIdentSub(GetRefer(e)); else if (e.isKeyword() && i != 0) setKeyword(e); else if (isKey(e, disp_)) { setKeyword(e); change = true; } } if (change) node.push_front(Element::Keyword(call_)); } private: bool isIdentDefined(const IdentKey &key, IdentIndex &iid) { IdentBasicIndex index = findFromIdentTable(iid.space_index, key); if (index != getIdentTableSize(iid.space_index)) { iid.ident_index = index; return true; } return false; } void setIdentifier(Element &element) { const IdentKey &key = element.getIndex(); IdentIndex ii(getCurrentIdentSpaceIndex()); if (isIdentDefined(key, ii)) { IdentTableUnit &itu = getFromIdentTable(ii); setIdent(element, itu.type, ii); } else { ii.ident_index = insertFromIdentTable(ii.space_index, key, I_DyVarb); setIdent(element, I_DyVarb, ii); } } void setKeyword(Element &element) { if (isKey(element, list_)) { setIdent(element, I_StFunc, getGlobalFunctionIdentIndex("list")); } else if (isKey(element, disp_)) { setIdent(element, I_StFunc, getGlobalFunctionIdentIndex("disp")); } } void setIdent(ASTBase::Element &elt, IdentType type, const IdentIndex &index) { elt = ASTBase::Element::Identifier(type, ConvertIdentIndexToSizeT(index)); } }; void transform(vector<AST::NodePtr> &Table) { PreliminaryCompile(Table).start(); IdentifierAnalysis(Table).start(); }; } }
27.94015
86
0.598447
ChillMagic
559ded1f9e1faf8f48a170eb7c05c811071902f5
5,215
cpp
C++
libraries/animationHelper/handleScript.cpp
dyollb/VegaFEM
83bb9e52f68dec5511393af0469abd85cfff4a7f
[ "BSD-3-Clause" ]
null
null
null
libraries/animationHelper/handleScript.cpp
dyollb/VegaFEM
83bb9e52f68dec5511393af0469abd85cfff4a7f
[ "BSD-3-Clause" ]
null
null
null
libraries/animationHelper/handleScript.cpp
dyollb/VegaFEM
83bb9e52f68dec5511393af0469abd85cfff4a7f
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************* * * * Vega FEM Simulation Library Version 4.0 * * * * "animationHelper" library , Copyright (C) 2018 USC * * All rights reserved. * * * * Code authors: Yijing Li, Jernej Barbic * * http://www.jernejbarbic.com/vega * * * * Research: Jernej Barbic, Hongyi Xu, Yijing Li, * * Danyong Zhao, Bohan Wang, * * Fun Shing Sin, Daniel Schroeder, * * Doug L. James, Jovan Popovic * * * * Funding: National Science Foundation, Link Foundation, * * Singapore-MIT GAMBIT Game Lab, * * Zumberge Research and Innovation Fund at USC, * * Sloan Foundation, Okawa Foundation, * * USC Annenberg Foundation * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the BSD-style license that is * * included with this library in the file LICENSE.txt * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * * LICENSE.TXT for more details. * * * *************************************************************************/ #include "handleScript.h" #include <fstream> #include <iostream> #include <string> #include <sstream> #include <cassert> using namespace std; const string HandleScript::commandName[HandleScript::NUM_COMMANDS] = { "VOID", "ADD", "REMOVE", "MOVE", "SPECIAL", "END" }; const HandleScript::Command HandleScript::endCommand(END); #define CHECK_FAILURE(cond) \ if (cond) \ { \ cerr << "Error HandleScript file format at line " << lineCount << endl; \ throw 2; \ } HandleScript::HandleScript() : nextCommand(0) { } HandleScript::HandleScript(const char * filename) : nextCommand(0) { ifstream fin(filename); if (!fin) { cerr << "Cannot open HandleScript file " << filename << endl; throw 1; } string line; fin >> ws; string typeName; int lineCount = 0; while(!fin.eof()) { lineCount++; getline(fin, line); if (line.size() == 0) continue; if (line[0] == '#') continue; Command c; istringstream is(line); typeName.clear(); is >> typeName; CHECK_FAILURE(is.fail()); if (typeName == "VOID") { // do nothing } else if (typeName == "END") { c.type = END; } else if (typeName == "SPECIAL") { c.type = SPECIAL; is >> c.vtx; if (is.fail()) c.vtx = 0; } else if (typeName == "ADD") { c.type = ADD; is >> c.vtx; CHECK_FAILURE(is.fail()); CHECK_FAILURE(c.vtx < 0); } else if (typeName == "REMOVE") { c.type = REMOVE; is >> c.vtx; CHECK_FAILURE(is.fail()); CHECK_FAILURE(c.vtx < 0); } else if (typeName == "MOVE") { c.type = MOVE; is >> c.vtx; CHECK_FAILURE(is.fail()); CHECK_FAILURE(c.vtx < 0); is >> ws; for(int i = 0; i < 3; i++) { char s = is.peek(); if (s == ',') is >> s; is >> c.vec[i]; CHECK_FAILURE(is.fail()); } } commands.push_back(c); fin >> ws; } } const HandleScript::Command & HandleScript::getNextCommand() { if (nextCommand >= commands.size()) return endCommand; return commands[nextCommand++]; } void HandleScript::addCommand(const Command & c) { commands.push_back(c); } bool HandleScript::save(const char * filename) { ofstream fout(filename); if(!fout) return false; for(size_t i = 0; i < commands.size(); i++) { Command & c = commands[i]; CommandType type = c.type; assert(type < NUM_COMMANDS); fout << commandName[(int)type]; //output command name if (type == ADD || type == REMOVE || type == SPECIAL) { fout << " " << c.vtx; } else if (type == MOVE) { fout << " " << c.vtx << " " << c.vec[0] << ", " << c.vec[1] << ", " << c.vec[2]; } fout << endl; if (fout.fail()) return false; } fout.close(); return true; }
28.037634
86
0.437967
dyollb
559e18fcbd587c713d5bafd32b8bafa73cdafe63
1,372
cpp
C++
src/runtime_src/core/pcie/linux/plugin/xdp/hal_device_offload.cpp
Pratyushxilinx/XRT
3f5d02ce9fed8d75ff5135f27a82522e7ab3d388
[ "Apache-2.0" ]
null
null
null
src/runtime_src/core/pcie/linux/plugin/xdp/hal_device_offload.cpp
Pratyushxilinx/XRT
3f5d02ce9fed8d75ff5135f27a82522e7ab3d388
[ "Apache-2.0" ]
null
null
null
src/runtime_src/core/pcie/linux/plugin/xdp/hal_device_offload.cpp
Pratyushxilinx/XRT
3f5d02ce9fed8d75ff5135f27a82522e7ab3d388
[ "Apache-2.0" ]
null
null
null
#include <functional> #include "hal_device_offload.h" #include "core/common/module_loader.h" #include "core/common/dlfcn.h" namespace xdphaldeviceoffload { void load_xdp_hal_device_offload() { static xrt_core::module_loader xdp_hal_device_offload_loader("xdp_hal_device_offload_plugin", register_hal_device_offload_functions, hal_device_offload_warning_function) ; } std::function<void (void*)> update_device_cb ; std::function<void (void*)> flush_device_cb ; void register_hal_device_offload_functions(void* handle) { typedef void (*ftype)(void*) ; update_device_cb = (ftype)(xrt_core::dlsym(handle, "updateDeviceHAL")) ; if (xrt_core::dlerror() != NULL) update_device_cb = nullptr ; flush_device_cb = (ftype)(xrt_core::dlsym(handle, "flushDeviceHAL")) ; if (xrt_core::dlerror() != NULL) flush_device_cb = nullptr ; } void hal_device_offload_warning_function() { // No warnings at this level } } // end namespace xdphaldeviceoffload namespace xdphal { void flush_device(void* handle) { if (xdphaldeviceoffload::flush_device_cb != nullptr) { xdphaldeviceoffload::flush_device_cb(handle) ; } } void update_device(void* handle) { if (xdphaldeviceoffload::update_device_cb != nullptr) { xdphaldeviceoffload::update_device_cb(handle) ; } } }
24.5
76
0.710641
Pratyushxilinx
55a42bf90acf08dc219bfa06b3639b32556b04d0
897
cpp
C++
Chapter9_Polymorphism1/9-1-2.cpp
estela19/CPP_Study
291d3a5f20b4d24e25f34d08f9a672985a66c092
[ "MIT" ]
null
null
null
Chapter9_Polymorphism1/9-1-2.cpp
estela19/CPP_Study
291d3a5f20b4d24e25f34d08f9a672985a66c092
[ "MIT" ]
null
null
null
Chapter9_Polymorphism1/9-1-2.cpp
estela19/CPP_Study
291d3a5f20b4d24e25f34d08f9a672985a66c092
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> class A { public: virtual std::string getTypeInfo() { std::string str = "This is an instance of class A"; return str; } }; class B : public A { public: virtual std::string getTypeInfo() { std::string str = "This is an instance of class B"; return str; } }; class C : public B { public: virtual std::string getTypeInfo() { std::string str = "This is an instance of class C"; return str; } }; void printObjectTypeInfo1(A* object) { std::cout << object->getTypeInfo() << "\n"; } void printObjectTypeInfo2(A& object) { std::cout << object.getTypeInfo() << "\n"; } int main() { std::vector<A*> vec; vec.push_back(new A); vec.push_back(new B); vec.push_back(new C); int i; for (i = 0; i < 3; i++) { printObjectTypeInfo1(vec[i]); printObjectTypeInfo2(*vec[i]); delete[] vec[i]; } }
18.6875
54
0.606466
estela19
55a8ae5d1a353ea57a86451bb1d7f7c1bd0e0c5f
1,696
cpp
C++
Tehnici Avansate de Programare (TAP)/Laborator/L3/3 (v1).cpp
DLarisa/FMI-Materials-BachelorDegree
138e1a20bc33617772e9cd9e4432fbae99c0250c
[ "W3C" ]
4
2022-02-12T02:05:36.000Z
2022-03-26T14:44:43.000Z
Tehnici Avansate de Programare (TAP)/Laborator/L3/3 (v1).cpp
DLarisa/FMI-Materials-BachelorDegree-UniBuc
138e1a20bc33617772e9cd9e4432fbae99c0250c
[ "W3C" ]
null
null
null
Tehnici Avansate de Programare (TAP)/Laborator/L3/3 (v1).cpp
DLarisa/FMI-Materials-BachelorDegree-UniBuc
138e1a20bc33617772e9cd9e4432fbae99c0250c
[ "W3C" ]
null
null
null
#include <iostream> //O(log(min(n, m))) #include <algorithm> using namespace std; //Mediana dintre 2 vectori (n=lungime a <= m=lungime b) double mediana(int a[], int b[], int n, int m) //O(log(n)) { int a_min=0, a_max=n, l=(n+m+1)/2, i, j; while(a_min<=a_max) //mereu se va injumatati vectorul cu lungime cea mai mica { i=(a_min+a_max)/2; j=l-i; if(i<a_max && b[j-1]>a[i]) a_min=i+1; // i prea mic - mediana se va afla in jumatatea superioara a lui a else if(i>a_min && a[i-1]>b[j]) a_max=i-1; // i prea mare - mediana se va afla in jumatatea inferioara a lui a else { // i perfect int maxi_st; if(i==0) maxi_st=b[j-1]; else if(j==0) maxi_st=a[i-1]; else maxi_st=max(a[i-1], b[j-1]); if((n+m)%2==1) return maxi_st; //daca avem nr total de elemente impar int min_dr; if(i==n) min_dr=b[j]; else if(j==m) min_dr=a[i]; else min_dr=min(b[j], a[i]); return (maxi_st+min_dr)/2.0; //daca avem nr total de elemente nr par } } return 0.0; } int main() { int n, m, i; cout<<"N: "; cin>>n; cout<<"Dati valori a: "; int *a=new int[n]; for(i=0; i<n; i++) cin>>a[i]; cout<<"M: "; cin>>m; cout<<"Dati valori b: "; int *b=new int[m]; for(i=0; i<m; i++) cin>>b[i]; //Ma asigur ca am pe prima pozitie vectorul cu nr minim de elemente if(n<m) cout<<mediana(a, b, n, m)<<endl; else cout<<mediana(b, a, m, n)<<endl; return 0; }
32
120
0.48467
DLarisa
55acc3d36186c74d1d9667fa4eca2e53abba5d4f
468
cpp
C++
src/brew/math/Math.cpp
grrrrunz/brew
13e17e2f6c9fb0f612c3a0bcabd233085ca15867
[ "MIT" ]
1
2018-02-09T16:20:50.000Z
2018-02-09T16:20:50.000Z
src/brew/math/Math.cpp
grrrrunz/brew
13e17e2f6c9fb0f612c3a0bcabd233085ca15867
[ "MIT" ]
null
null
null
src/brew/math/Math.cpp
grrrrunz/brew
13e17e2f6c9fb0f612c3a0bcabd233085ca15867
[ "MIT" ]
null
null
null
/** * * |_ _ _ * |_)| (/_VV * * Copyright 2015-2018 Marcus v. Keil * * Created on: Feb 11, 2016 * */ #include <brew/math/Math.h> namespace brew { namespace math { const Real EPSILON = std::numeric_limits<Real>::epsilon(); const Real PI = 3.1415926535897932f; const Real HALF_PI = PI * 0.5f; const Real TWO_PI = PI * 2; bool equals(Real a, Real b, Real epsilon) { return std::fabs(a-b) < epsilon; } } /* namespace math */ } /* namespace brew */
16.137931
58
0.619658
grrrrunz
55aec24ae07d08e6bb68efa367b9513e9ea6d164
9,205
cpp
C++
profiler/src/ProfilerEngine/Datadog.Profiler.Native/StackFramesCollectorBase.cpp
cwe1ss/dd-trace-dotnet
ed74cf794cb02fb698567052caae973870b82428
[ "Apache-2.0" ]
null
null
null
profiler/src/ProfilerEngine/Datadog.Profiler.Native/StackFramesCollectorBase.cpp
cwe1ss/dd-trace-dotnet
ed74cf794cb02fb698567052caae973870b82428
[ "Apache-2.0" ]
2
2022-02-10T06:13:13.000Z
2022-02-17T01:31:15.000Z
profiler/src/ProfilerEngine/Datadog.Profiler.Native/StackFramesCollectorBase.cpp
Kielek/signalfx-dotnet-tracing
80c65ca936748788629287472401fa9f31b79410
[ "Apache-2.0" ]
null
null
null
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2022 Datadog, Inc. #include "StackFramesCollectorBase.h" #include <assert.h> #include <chrono> #include <condition_variable> #include <mutex> StackFramesCollectorBase::StackFramesCollectorBase() { _isRequestedCollectionAbortSuccessful = false; _pReusableStackSnapshotResult = new StackSnapshotResultReusableBuffer(); _pCurrentCollectionThreadInfo = nullptr; } StackFramesCollectorBase::~StackFramesCollectorBase() { StackSnapshotResultReusableBuffer* pReusableStackSnapshotResult = _pReusableStackSnapshotResult; if (pReusableStackSnapshotResult != nullptr) { delete pReusableStackSnapshotResult; _pReusableStackSnapshotResult = nullptr; } } bool StackFramesCollectorBase::TryAddFrame(StackFrameCodeKind codeKind, FunctionID clrFunctionId, UINT_PTR nativeInstructionPointer, std::uint64_t moduleHandle) { StackSnapshotResultFrameInfo* pCurrentFrameInfo; bool hasCapacityForSubsequentFrames; bool hasCapacityForThisFrame = _pReusableStackSnapshotResult->TryAddNextFrame(&pCurrentFrameInfo, &hasCapacityForSubsequentFrames); if (!hasCapacityForThisFrame) { // We run out of the preallocated space for storing results. // Allocating while threads are suspended is forbidden. // We are just being defensive: we should really never get here, // since last iteration we had hasCapacityForSubsequentFrames == true. // We will also increase the size of the preallocated buffer for the next time: _pReusableStackSnapshotResult->GrowCapacityAtNextReset(); // Use the info we collected so far and abort further stack walking for this time: return false; } if (!hasCapacityForSubsequentFrames) { // We have preallocated space for only one more frame. // (allocating while threads are suspended is forbidden.) // We need to use it for a marker that signals that more frames exist, but we do not have information about them: pCurrentFrameInfo->Set(StackFrameCodeKind::MultipleMixed, 0, 0, 0); // We will also increase the size of the preallocated buffer for the next time: _pReusableStackSnapshotResult->GrowCapacityAtNextReset(); // Use the info we collected so far and abort further stack walking for this time: return false; } pCurrentFrameInfo->Set(codeKind, clrFunctionId, nativeInstructionPointer, moduleHandle); return true; } void StackFramesCollectorBase::RequestAbortCurrentCollection(void) { std::lock_guard<std::mutex> lock(_collectionAbortNotificationLock); _isRequestedCollectionAbortSuccessful = false; _isCurrentCollectionAbortRequested.store(true); } // // =========== Default implementations of Protected Virtual business logic funcitons: =========== // void StackFramesCollectorBase::PrepareForNextCollectionImplementation(void) { // The actual business logic provided by a subclass goes into the XxxImplementation(..) methods. // This is a fallback implementation, so that the implementing sub-class does not need to overwrite this method if it is a no-op. } bool StackFramesCollectorBase::SuspendTargetThreadImplementation(ManagedThreadInfo* pThreadInfo, bool* pIsTargetThreadSuspended) { // The actual business logic provided by a subclass goes into the XxxImplementation(..) methods. // This is a fallback implementation, so that the implementing sub-class does not need to overwrite this method if it is a no-op. *pIsTargetThreadSuspended = false; return true; } void StackFramesCollectorBase::ResumeTargetThreadIfRequiredImplementation(ManagedThreadInfo* pThreadInfo, bool isTargetThreadSuspended, uint32_t* pErrorCodeHR) { // The actual business logic provided by a subclass goes into the XxxImplementation(..) methods. // This is a fallback implementation, so that the implementing sub-class does not need to overwrite this method if it is a no-op. if (pErrorCodeHR != nullptr) { *pErrorCodeHR = isTargetThreadSuspended ? E_FAIL : S_OK; } } StackSnapshotResultBuffer* StackFramesCollectorBase::CollectStackSampleImplementation(ManagedThreadInfo* pThreadInfo, uint32_t* pHR) { // The actual business logic provided by a subclass goes into the XxxImplementation(..) methods. // This is a fallback implementation, so that the implementing sub-class does not need to overwrite this method if it is a no-op. bool frame1Added = TryAddFrame(StackFrameCodeKind::Dummy, 0, 0, 0); bool frame2Added = TryAddFrame(StackFrameCodeKind::Dummy, 0, 0, 0); bool frame3Added = TryAddFrame(StackFrameCodeKind::Dummy, 0, 0, 0); if (pHR != nullptr) { *pHR = (frame1Added && frame2Added && frame3Added) ? S_OK : E_FAIL; } return GetStackSnapshotResult(); } bool StackFramesCollectorBase::IsCurrentCollectionAbortRequested() { return _isCurrentCollectionAbortRequested.load(); } bool StackFramesCollectorBase::TryApplyTraceContextDataFromCurrentCollectionThreadToSnapshot() { // If TraceContext Tracking is not enabled, then we will simply get zero IDs. ManagedThreadInfo* pCurrentCollectionThreadInfo = _pCurrentCollectionThreadInfo; if (nullptr != pCurrentCollectionThreadInfo && pCurrentCollectionThreadInfo->CanReadTraceContext()) { std::uint64_t localRootSpanId = pCurrentCollectionThreadInfo->GetLocalRootSpanId(); std::uint64_t spanId = pCurrentCollectionThreadInfo->GetSpanId(); _pReusableStackSnapshotResult->SetLocalRootSpanId(localRootSpanId); _pReusableStackSnapshotResult->SetSpanId(spanId); return true; } return false; } StackSnapshotResultBuffer* StackFramesCollectorBase::GetStackSnapshotResult() { return _pReusableStackSnapshotResult; } // ----------- Inline stubs for APIs that are specific to overriding implementations: ----------- // They perform the work required for the shared base implementation (this class) and then invoke the respective XxxImplementaiton(..) method. // This is less error-prone than simply making these methods virtual and relying on the sub-classes to remember calling the base class method. void StackFramesCollectorBase::PrepareForNextCollection(void) { // We cannot allocate memory once a thread is suspended. // This is because malloc() uses a lock and so if we suspend a thread that was allocating, we will deadlock. // So we pre-allocate the memory buffer and reset it before suspending the target thread. _pReusableStackSnapshotResult->Reset(); // Clear the current collection thread pointer: _pCurrentCollectionThreadInfo = nullptr; // Clean up initialization state: _isCurrentCollectionAbortRequested.store(false); _isRequestedCollectionAbortSuccessful = false; // Subclasses can implement their own specific initialization before each collection. Invoke it: PrepareForNextCollectionImplementation(); } bool StackFramesCollectorBase::SuspendTargetThread(ManagedThreadInfo* pThreadInfo, bool* pIsTargetThreadSuspended) { return SuspendTargetThreadImplementation(pThreadInfo, pIsTargetThreadSuspended); } void StackFramesCollectorBase::ResumeTargetThreadIfRequired(ManagedThreadInfo* pThreadInfo, bool isTargetThreadSuspended, uint32_t* pErrorCodeHR) { ResumeTargetThreadIfRequiredImplementation(pThreadInfo, isTargetThreadSuspended, pErrorCodeHR); } StackSnapshotResultBuffer* StackFramesCollectorBase::CollectStackSample(ManagedThreadInfo* pThreadInfo, uint32_t* pHR) { // Update state with the info for the thread that we are collecting: _pCurrentCollectionThreadInfo = pThreadInfo; // Execute the actual collection: StackSnapshotResultBuffer* result = CollectStackSampleImplementation(pThreadInfo, pHR); // No longer collecting the specified thread: _pCurrentCollectionThreadInfo = nullptr; // If someone has requested an abort, notify them now: if (IsCurrentCollectionAbortRequested()) { { std::lock_guard<std::mutex> lock(_collectionAbortNotificationLock); _isRequestedCollectionAbortSuccessful = true; } _collectionAbortPerformedSignal.notify_all(); } return result; } void StackFramesCollectorBase::OnDeadlock() { // In 32bits, we use the method DoStackSnapshot to walk and collect a thread callstack. // The DoStackSnapshot method calls SuspendThread/ResumeThread. // In case of a deadlock, if the sampling thread has not gracefully finished, it will be killed. // The result will be: 1 call to ResumeThread missing. }
41.463964
145
0.726996
cwe1ss
55b4cd2297148e74b96786957b29bd4b7116e404
378
hpp
C++
include/ActionControlsListener.hpp
InversePalindrome/Rampancy
e228f8c16f0608b9f20a3904f4c5f19aa2076934
[ "MIT" ]
1
2018-03-23T02:25:24.000Z
2018-03-23T02:25:24.000Z
include/ActionControlsListener.hpp
InversePalindrome/Rampancy
e228f8c16f0608b9f20a3904f4c5f19aa2076934
[ "MIT" ]
null
null
null
include/ActionControlsListener.hpp
InversePalindrome/Rampancy
e228f8c16f0608b9f20a3904f4c5f19aa2076934
[ "MIT" ]
null
null
null
/* Copyright (c) 2017 InversePalindrome Rampancy - SettingsState.cpp InversePalindrome.com */ #pragma once #include "Events.hpp" #include "InputManager.hpp" struct ActionControlsListener { ActionControlsListener(InputManager* inputManager); void receive(const KeyPressed& event); InputManager* inputManager; Action currentAction; };
16.434783
56
0.716931
InversePalindrome
55b7c3784608f6aeaf7d8b56eb84d0f77f3d4d4b
387
cpp
C++
alert_in_Cocoa.cpp
agancsos/cpp
08ad758f71d899027d6891dca5bed24bf02bbc81
[ "MIT" ]
null
null
null
alert_in_Cocoa.cpp
agancsos/cpp
08ad758f71d899027d6891dca5bed24bf02bbc81
[ "MIT" ]
null
null
null
alert_in_Cocoa.cpp
agancsos/cpp
08ad758f71d899027d6891dca5bed24bf02bbc81
[ "MIT" ]
null
null
null
- (void) alert:(NSString*)message{ NSAlert *alert = [[[NSAlert alloc] init] autorelease]; [alert addButtonWithTitle:@\"OK\"]; [alert setMessageText:@\"Error....\"]; [alert setInformativeText:message]; [alert setAlertStyle:NSWarningAlertStyle]; [alert beginSheetModalForWindow:_window modalDelegate:NULL didEndSelector:NULL contextInfo:NULL]; }
35.181818
106
0.684755
agancsos
55b9edc87798a7028096212e073eaf233408fc4b
285
cpp
C++
src/fem/maplocal.cpp
XiaoMaResearch/hybrid_tsunamic_plane_stress
574988edfcd4839f680b85cde2bf818936e86b78
[ "MIT" ]
6
2019-04-12T19:51:23.000Z
2021-09-16T07:12:57.000Z
src/fem/maplocal.cpp
XiaoMaResearch/hybrid_tsunamic_plane_stress
574988edfcd4839f680b85cde2bf818936e86b78
[ "MIT" ]
null
null
null
src/fem/maplocal.cpp
XiaoMaResearch/hybrid_tsunamic_plane_stress
574988edfcd4839f680b85cde2bf818936e86b78
[ "MIT" ]
1
2019-07-07T07:23:58.000Z
2019-07-07T07:23:58.000Z
// // maplocal.cpp // hybrid_fem_bie // // Created by Max on 2/6/18. // // #include "maplocal.hpp" void maplocal(const ArrayXi &index, const VectorXd &u_global , VectorXd & u_local) { for (int i=0;i<u_local.size();i++) { u_local(i)=u_global(index(i)); } }
15.833333
82
0.592982
XiaoMaResearch
55bc13b31463ccc08047dbe384fb2d272c8e33da
8,156
cpp
C++
RT/RT/Impl/JsonSerialization.cpp
heyx3/heyx3RT
4dd476a33e658bc19fde239f2c6e22bdcd598e27
[ "Unlicense", "MIT" ]
null
null
null
RT/RT/Impl/JsonSerialization.cpp
heyx3/heyx3RT
4dd476a33e658bc19fde239f2c6e22bdcd598e27
[ "Unlicense", "MIT" ]
null
null
null
RT/RT/Impl/JsonSerialization.cpp
heyx3/heyx3RT
4dd476a33e658bc19fde239f2c6e22bdcd598e27
[ "Unlicense", "MIT" ]
null
null
null
#include "../Headers/JsonSerialization.h" #include "../Headers/ThirdParty/base64.h" #include <fstream> using namespace RT; #pragma warning( disable : 4996 ) bool RT_API JsonSerialization::ToJSONFile(const String& filePath, const IWritable& toWrite, bool compact, String& outErrorMsg) { JsonWriter writer; String trying = "UNKNOWN"; try { trying = "serializing data"; writer.WriteDataStructure(toWrite, "data"); trying = "writing data to file"; outErrorMsg = writer.SaveData(filePath, compact); if (!outErrorMsg.IsEmpty()) { return false; } return true; } catch (int i) { if (i == DataWriter::EXCEPTION_FAILURE) { outErrorMsg = String("Error while ") + trying + ": " + writer.ErrorMessage; } else { outErrorMsg = String("Unknown error code while ") + trying + ": " + String(i); } return false; } } bool RT_API JsonSerialization::ToJSONString(const IWritable& toWrite, bool compact, String& outJSON, String& outErrorMsg) { JsonWriter writer; String trying = "UNKNOWN"; try { trying = "serializing data"; writer.WriteDataStructure(toWrite, "data"); outJSON = writer.GetData(compact); return true; } catch (int i) { if (i == DataWriter::EXCEPTION_FAILURE) { outErrorMsg = String("Error while ") + trying + ": " + writer.ErrorMessage; } else { outErrorMsg = String("Unknown error code while ") + trying + ": " + String(i); } return false; } } bool RT_API JsonSerialization::FromJSONFile(const String& filePath, IReadable& toRead, String& outErrorMsg) { JsonReader reader(filePath); //If we had an error reading the file, stop. if (reader.ErrorMessage.GetSize() > 0) { outErrorMsg = String("Error reading file: ") + reader.ErrorMessage; return false; } try { reader.ReadDataStructure(toRead, "data"); return true; } catch (int i) { if (i == DataReader::EXCEPTION_FAILURE) { outErrorMsg = String("Error reading data: ") + reader.ErrorMessage; } else { outErrorMsg = String("Unknown error code: ") + String(i); } return false; } } String JsonWriter::SaveData(const String& path, bool compact) { std::ofstream file(path.CStr(), std::ios_base::trunc); if (file.is_open()) { file << doc.dump(compact ? -1 : 4); } else { return "Couldn't open file"; } return ""; } void JsonWriter::WriteBool(bool value, const String& name) { GetToUse()[name.CStr()] = value; } void JsonWriter::WriteByte(unsigned char value, const String& name) { GetToUse()[name.CStr()] = value; } void JsonWriter::WriteInt(int value, const String& name) { GetToUse()[name.CStr()] = value; } void JsonWriter::WriteUInt(unsigned int value, const String& name) { GetToUse()[name.CStr()] = value; } void JsonWriter::WriteFloat(float value, const String& name) { GetToUse()[name.CStr()] = value; } void JsonWriter::WriteDouble(double value, const String& name) { GetToUse()[name.CStr()] = value; } void JsonWriter::WriteString(const String& value, const String& name) { //Escape special characters. String newVal = value; for (size_t i = 0; i < newVal.GetSize(); ++i) { if (newVal[i] == '"' || newVal[i] == '\\') { newVal.Insert(i, '\\'); i += 1; } } GetToUse()[name.CStr()] = value.CStr(); } void JsonWriter::WriteBytes(const unsigned char* bytes, size_t nBytes, const String& name) { String str = base64::encode(bytes, nBytes).c_str(); WriteString(str, name); } void JsonWriter::WriteDataStructure(const IWritable& toSerialize, const String& name) { GetToUse()[name.CStr()] = nlohmann::json::object(); JsonWriter subWriter(&GetToUse()[name.CStr()]); toSerialize.WriteData(subWriter); } JsonReader::JsonReader(const String& filePath) { ErrorMessage = Reload(filePath); } String JsonReader::Reload(const String& filePath) { subDoc = nullptr; std::ifstream fileS(filePath.CStr()); if (!fileS.is_open()) { return "Couldn't open the file"; } fileS.seekg(0, std::ios::end); std::streampos size = fileS.tellg(); fileS.seekg(0, std::ios::beg); std::vector<char> fileData; fileData.resize((size_t)size); fileS.read(fileData.data(), size); doc = nlohmann::json::parse(std::string(fileData.data())); return ""; } void JsonReader::Assert(bool expr, const String& errorMsg) { if (!expr) { ErrorMessage = errorMsg; throw EXCEPTION_FAILURE; } } nlohmann::json::const_iterator JsonReader::GetItem(const String& name) { const nlohmann::json& jsn = GetToUse(); auto element = jsn.find(name.CStr()); Assert(element != jsn.end(), "Couldn't find the element."); return element; } void JsonReader::ReadBool(bool& outB, const String& name) { auto& element = GetItem(name); Assert(element->is_boolean(), "Expected a boolean but got something else"); outB = element->get<bool>(); } void JsonReader::ReadByte(unsigned char& outB, const String& name) { auto& element = GetItem(name); Assert(element->is_number_unsigned(), "Expected a byte but got something else"); outB = (unsigned char)element->get<size_t>(); } void JsonReader::ReadInt(int& outI, const String& name) { auto& element = GetItem(name); Assert(element->is_number_integer(), "Expected an integer but got something else"); outI = element->get<int>(); } void JsonReader::ReadUInt(unsigned int& outU, const String& name) { auto& element = GetItem(name); Assert(element->is_number_unsigned(), "Expected an unsigned integer but got something else"); outU = element->get<size_t>(); } void JsonReader::ReadFloat(float& outF, const String& name) { //Note that integers make valid floats. auto& element = GetItem(name); Assert(element->is_number_float() || element->is_number_integer(), "Expected a float but got something else"); if (element->is_number_float()) outF = element->get<float>(); else outF = (float)element->get<int>(); } void JsonReader::ReadDouble(double& outD, const String& name) { //Note that integers make valid doubles. auto& element = GetItem(name); Assert(element->is_number_float() || element->is_number_integer(), "Expected a double but got something else"); if (element->is_number_float()) outD = element->get<double>(); else outD = (double)element->get<int>(); } void JsonReader::ReadString(String& outStr, const String& name) { auto& element = GetItem(name); Assert(element->is_string(), "Expected a string but got something else"); outStr = element->get<std::string>().c_str(); //Fix escaped characters. for (size_t i = 0; i < outStr.GetSize(); ++i) { if (outStr[i] == '\\') { outStr.Erase(i); //Normally we would subtract 1 from "i" here, but we *want* to skip the next character -- // it's the one being escaped. } } } void JsonReader::ReadBytes(List<unsigned char>& outBytes, const String& name) { String str; ReadString(str, name); std::vector<unsigned char> _outBytes; base64::decode(str.CStr(), _outBytes); outBytes.Resize(_outBytes.size()); memcpy_s(outBytes.GetData(), outBytes.GetSize(), _outBytes.data(), _outBytes.size()); } void JsonReader::ReadDataStructure(IReadable& outData, const String& name) { auto& element = GetItem(name); Assert(element->is_object(), "Expected a data structure but got something else"); JsonReader subReader(&(*element)); outData.ReadData(subReader); } #pragma warning( default : 4996 )
27.461279
101
0.611574
heyx3
55bcc14b851caec9910c7842d229687cbc189cee
2,802
cpp
C++
examples/client/qtest1.cpp
pauldotknopf/grpc-qt
c6e0e38ea4130ac2b8ae5f441bd78dd7ead274e4
[ "MIT" ]
null
null
null
examples/client/qtest1.cpp
pauldotknopf/grpc-qt
c6e0e38ea4130ac2b8ae5f441bd78dd7ead274e4
[ "MIT" ]
null
null
null
examples/client/qtest1.cpp
pauldotknopf/grpc-qt
c6e0e38ea4130ac2b8ae5f441bd78dd7ead274e4
[ "MIT" ]
null
null
null
#include "qtest1.h" #include "proto/gen.grpc.pb.h" #include <grpc++/grpc++.h> #include <QDebug> class QTest1Private { public: QTest1Private() : objectId(0) { } std::unique_ptr<Tests::Test1ObjectService::Stub> test1ObjectService; grpc::ClientContext objectRequestContext; std::unique_ptr<grpc::ClientReaderWriter<google::protobuf::Any, google::protobuf::Any>> objectRequest; google::protobuf::uint64 objectId; void createObject() { objectRequest = test1ObjectService->Create(&objectRequestContext); google::protobuf::Any createResponseAny; if(!objectRequest->Read(&createResponseAny)) { qCritical("Failed to read request from object creation."); objectRequest.release(); return; } Tests::Test1CreateResponse createResponse; if(!createResponseAny.UnpackTo(&createResponse)) { qCritical("Couldn't unpack request to CreateResponse."); objectRequest.release(); return; } objectId = createResponse.objectid(); } void releaseObject() { if(objectRequest != nullptr) { auto result = objectRequest->Finish(); if(!result.ok()) { qCritical("Couldn't dispose of the object: %s", result.error_message().c_str()); } } } }; QTest1::QTest1() : d_ptr(new QTest1Private()) { auto channel = grpc::CreateChannel("localhost:8000", grpc::InsecureChannelCredentials()); auto stub = Tests::Test1ObjectService::NewStub(channel); d_ptr->test1ObjectService = std::move(stub); d_ptr->createObject(); } QTest1::~QTest1() { d_ptr->releaseObject(); } QString QTest1::getPropString() { grpc::ClientContext context; Tests::Test1PropStringGetRequest request; request.set_objectid(d_ptr->objectId); Tests::Test1PropStringGetResponse response; auto result = d_ptr->test1ObjectService->GetPropertyPropString(&context, request, &response); if(!result.ok()) { qCritical("Couldn't get the property: %s", result.error_message().c_str()); return QString(); } auto val = response.value(); return QString::fromStdString(response.value().value()); } void QTest1::setPropString(QString& val) { grpc::ClientContext context; Tests::Test1PropStringSetRequest request; request.set_objectid(d_ptr->objectId); auto str = new google::protobuf::StringValue(); str->set_value(val.toStdString()); request.set_allocated_value(str); Tests::Test1PropStringSetResponse response; auto result = d_ptr->test1ObjectService->SetPropertyPropString(&context, request, &response); if(!result.ok()) { qCritical("Couldn't get the property: %s", result.error_message().c_str()); return; } }
31.133333
106
0.662384
pauldotknopf
55be13fd0b9eff80a6b947e9c507e0ae15e695ce
5,258
cc
C++
src/filesystem.cc
V-FEXrt/fexware
3dabd7a161a103710482a0d89e594c665cf8c2fc
[ "MIT" ]
1
2022-01-22T20:26:10.000Z
2022-01-22T20:26:10.000Z
src/filesystem.cc
V-FEXrt/fexware
3dabd7a161a103710482a0d89e594c665cf8c2fc
[ "MIT" ]
null
null
null
src/filesystem.cc
V-FEXrt/fexware
3dabd7a161a103710482a0d89e594c665cf8c2fc
[ "MIT" ]
null
null
null
#include "filesystem.h" #include <stdio.h> #include <string> #include <string.h> #include <vector> #include "ff.h" #include "flash.h" #define DRIVE_NAME "MiRage" namespace fex { bool Filesystem::Initialize() { FRESULT fr; if (!Mount()) { printf("Initialzing filesystem.\n"); char buffer[4095]; fr = f_mkfs("0", FM_ANY, 0, buffer, 4096); if (fr != FR_OK) { printf("Failed to make filesystem: Err(%d\n)", fr); return false; } f_setlabel(DRIVE_NAME); AddFile("README.txt", "Copy .kmf (keymap file) files into this directory to assign key maps.\n\n" "After copying over the keymaps power cycle the keyboard for them to take effect.\n" "To reflash keymaps either bind a key to XXXX or press and hold all 4 corner keys"); printf("Initialized filesystem!\n"); return true; } f_setlabel(DRIVE_NAME); if (!Unmount()) { printf("Failed to unmount filesystem\n"); return false; } printf("Filesystem already initialized!\n"); return true; } bool Filesystem::Mount() { FRESULT fr = f_mount(&fs_, "", 1); if (fr != FR_OK) { printf("Failed to mount filesystem: Err(%d).\n", fr); return false; } return true; } bool Filesystem::Unmount() { FRESULT fr = f_unmount(""); if (fr != FR_OK) { printf("Failed to unmount filesystem: Err(%d)\n", fr); return false; } return true; } std::vector<std::string> Filesystem::List(std::string path) { std::vector<std::string> out; std::vector<char> copy(path.begin(), path.end()); copy.push_back('\0'); if (ListAcc(copy.data(), &out) != FR_OK) { printf("Failed in acc\n"); return {}; } printf("Returning out\n"); return out; } FRESULT Filesystem::ListAcc(char *path, std::vector<std::string> *out) { FRESULT res; DIR dir; UINT i; static FILINFO fno; printf("open dir\n"); res = f_opendir(&dir, path); /* Open the directory */ printf("end open dir\n"); if (res != FR_OK) { printf("Failed to open dir: Err(%d).\n", res); return res; } printf("begin loop\n"); for (;;) { printf("begin readdir\n"); res = f_readdir(&dir, &fno); /* Read a directory item */ printf("end readdir\n"); if (res != FR_OK || fno.fname[0] == 0) break; /* Break on error or end of dir */ printf("if 1 exit\n"); if (fno.fattrib & AM_DIR) { /* It is a directory */ continue; printf("at directory\n"); i = strlen(path); sprintf(&path[i], "/%s", fno.fname); printf("recursing\n"); res = ListAcc(path, out); printf("end recursing\n"); if (res != FR_OK) break; printf("end recursing if\n"); path[i] = 0; } else { /* It is a file. */ printf("at file\n"); char buff[256]; printf("path: '%s', fno: '%s'\n", path, fno.fname); snprintf(buff, 255, "%s/%s", path, fno.fname); out->push_back(std::string(buff)); printf("adding file %s\n", buff); } printf("end loop\n"); } printf("begin closedir\n"); f_closedir(&dir); printf("begin closedir\n"); return res; } void Filesystem::EraseAll() { flash_erase(FATFS_OFFSET, FATFS_SIZE); } bool Filesystem::AddFile(const std::string &filename, const std::string &contents) { FIL fp; FRESULT fr; fr = f_open(&fp, filename.c_str(), FA_WRITE | FA_CREATE_ALWAYS); if (fr != FR_OK) { return false; } UINT bw; fr = f_write(&fp, contents.c_str(), contents.size(), &bw); f_close(&fp); return fr == FR_OK; } bool Filesystem::FileExists(const std::string &filename) { return f_stat(filename.c_str(), NULL) == FR_OK; } bool Filesystem::DeleteFile(const std::string &filename) { return f_unlink(filename.c_str()) == FR_OK; } std::string Filesystem::ReadFile(const std::string &filename) { FIL fp; FRESULT fr; fr = f_open(&fp, filename.c_str(), FA_READ); if (fr != FR_OK) { return ""; } std::string out = ""; char buffer[4097]; UINT br = 0; do { fr = f_read(&fp, buffer, 4096, &br); UINT index = MIN(br, 4096); buffer[index] = '\0'; out += buffer; } while(br == 4096); return out; } }
25.157895
104
0.471092
V-FEXrt
55be8c3075caa2afc85c290ec5c232c092b2dfea
682
cpp
C++
Chapter7-Quicksort/quicksort.cpp
wr47h/CLRS_Algorithms
91193e8382cd54398ab1ca397ef72069754a1dc6
[ "MIT" ]
null
null
null
Chapter7-Quicksort/quicksort.cpp
wr47h/CLRS_Algorithms
91193e8382cd54398ab1ca397ef72069754a1dc6
[ "MIT" ]
null
null
null
Chapter7-Quicksort/quicksort.cpp
wr47h/CLRS_Algorithms
91193e8382cd54398ab1ca397ef72069754a1dc6
[ "MIT" ]
1
2019-10-05T08:07:06.000Z
2019-10-05T08:07:06.000Z
#include <iostream> using namespace std; int partitionAr(int a[], int p, int r) { int x = a[r-1]; int i = p-1; for(int j=p; j<r-1; j++) { if(a[j]<x) { i = i+1; swap(a[i], a[j]); } } swap(a[i+1], a[r-1]); return i+1; } void quicksort(int a[], int p, int r) { if(p<r) { int q = partitionAr(a, p, r); quicksort(a, p, q-1); quicksort(a, q+1, r); } } void printArray(int a[], int n){ for (int i=0; i<n; i++) cout << a[i] << " "; cout << "\n"; } int main() { int a[] = {2, 5, 3, 9, 1, 10}; int n = 6; quicksort(a, 0, n); printArray(a, n); return 0; }
17.487179
40
0.422287
wr47h
55c259700f72ab9818969086f7640bcd55729c9c
723
cpp
C++
ACM-ICPC/9095.cpp
KimBoWoon/ACM-ICPC
146c36999488af9234d73f7b4b0c10d78486604f
[ "MIT" ]
null
null
null
ACM-ICPC/9095.cpp
KimBoWoon/ACM-ICPC
146c36999488af9234d73f7b4b0c10d78486604f
[ "MIT" ]
null
null
null
ACM-ICPC/9095.cpp
KimBoWoon/ACM-ICPC
146c36999488af9234d73f7b4b0c10d78486604f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> int t, n; int dp[101]; // 1, 2, 3을 더해서 n을 표현하는 방법의 가지수를 d[n] // dp[x를 1로 만드는 경우의 수] // dp[x를 2로 만드는 경우의 수] // dp[x를 3로 만드는 경우의 수] // 전부 더 하면 된다 int topDown(int x) { if (x == 0) { dp[x] = 1; } if (x == 1) { dp[x] = 1; } if (x == 2) { dp[x] = 2; } if (x >= 3) { dp[x] = topDown(x - 1) + topDown(x - 2) + topDown(x - 3); } return dp[x]; } int bottomUp(int x) { dp[0] = 1; for (int i = 1; i <= n; i++) { dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]; } return dp[x]; } int main() { scanf("%d", &t); while (t--) { memset(dp, 0, sizeof(dp)); scanf("%d", &n); printf("%d\n", topDown(n)); // printf("%d\n", bottomUp(n)); } }
15.717391
60
0.427386
KimBoWoon
55c7914ac972ba20c5722877f6435b4433fa2088
4,244
hpp
C++
src/operators/math/common.hpp
LLNL/LBANN
8bcc5d461e52de70e329d73081ca7eee3e5c580a
[ "Apache-2.0" ]
null
null
null
src/operators/math/common.hpp
LLNL/LBANN
8bcc5d461e52de70e329d73081ca7eee3e5c580a
[ "Apache-2.0" ]
null
null
null
src/operators/math/common.hpp
LLNL/LBANN
8bcc5d461e52de70e329d73081ca7eee3e5c580a
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014-2022, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the LBANN Research Team (B. Van Essen, et al.) listed in // the CONTRIBUTORS file. <lbann-dev@llnl.gov> // // LLNL-CODE-697807. // All rights reserved. // // This file is part of LBANN: Livermore Big Artificial Neural Network // Toolkit. For details, see http://software.llnl.gov/LBANN or // https://github.com/LLNL/LBANN. // // Licensed under the Apache License, Version 2.0 (the "Licensee"); 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 LBANN_SRC_OPERATORS_MATH_COMMON_HPP_INCLUDED #define LBANN_SRC_OPERATORS_MATH_COMMON_HPP_INCLUDED #include "lbann/base.hpp" namespace lbann { namespace internal { /** @brief A binary entrywise map c <- f(a,b). */ template <typename S, typename T, typename U, typename F> void EntrywiseZipInto(El::Matrix<S, El::Device::CPU> const& A, El::Matrix<T, El::Device::CPU> const& B, El::Matrix<U, El::Device::CPU>& C, F func) { EL_DEBUG_CSE; auto const m = A.Height(); auto const n = A.Width(); LBANN_ASSERT_DEBUG(B.Height() == m); LBANN_ASSERT_DEBUG(B.Width() == n); LBANN_ASSERT_DEBUG(C.Height() == m); LBANN_ASSERT_DEBUG(C.Width() == n); S const* ABuf = A.LockedBuffer(); T const* BBuf = B.LockedBuffer(); U* CBuf = C.Buffer(); auto const ALDim = A.LDim(); auto const BLDim = B.LDim(); auto const CLDim = C.LDim(); // Use entry-wise parallelization for column vectors. Otherwise // use column-wise parallelization. if (n == 1) { EL_PARALLEL_FOR for (El::Int i = 0; i < m; ++i) { CBuf[i] = func(ABuf[i], BBuf[i]); } } else { EL_PARALLEL_FOR_COLLAPSE2 for (El::Int j = 0; j < n; ++j) { for (El::Int i = 0; i < m; ++i) { CBuf[i + j * CLDim] = func(ABuf[i + j * ALDim], BBuf[i + j * BLDim]); } } } } /** Apply a binary backprop operator to CPU data. * The input and output data must be on CPU and must have the same * dimensions. Given a binary function \f$ y = f(x_1,x_2) \f$, the * corresponding BinaryBackPropOperator is a 5-ary function with the * arguments \f$ x_1 \f$, \f$ x_2 \f$, \f$ dL/dy \f$, \f$ dL/dx_1\f$, * \f$ dL/dx_2 \f$. The last two arguments should be overwritten when * the BinaryBackPropOperator is called. */ template <typename DataT, typename F> void apply_binary_backprop_operator( El::Matrix<DataT, El::Device::CPU> const& x1, El::Matrix<DataT, El::Device::CPU> const& x2, El::Matrix<DataT, El::Device::CPU> const& dy, El::Matrix<DataT, El::Device::CPU>& dx1, El::Matrix<DataT, El::Device::CPU>& dx2, F f) { if (x1.Contiguous() && x2.Contiguous() && dy.Contiguous() && dx1.Contiguous() && dx2.Contiguous()) { const auto* x1_buffer = x1.LockedBuffer(); const auto* x2_buffer = x2.LockedBuffer(); const auto* dy_buffer = dy.LockedBuffer(); auto* dx1_buffer = dx1.Buffer(); auto* dx2_buffer = dx2.Buffer(); const size_t size = x1.Height() * x1.Width(); LBANN_OMP_PARALLEL_FOR for (size_t i = 0; i < size; ++i) { f(x1_buffer[i], x2_buffer[i], dy_buffer[i], dx1_buffer[i], dx2_buffer[i]); } } else { auto const width = x1.Width(); auto const height = x1.Height(); LBANN_OMP_PARALLEL_FOR_COLLAPSE2 for (El::Int jj = 0; jj < width; ++jj) { for (El::Int ii = 0; ii < height; ++ii) { f(x1(ii, jj), x2(ii, jj), dy(ii, jj), dx1(ii, jj), dx2(ii, jj)); } } } } } // namespace internal } // namespace lbann #endif // LBANN_SRC_OPERATORS_MATH_COMMON_HPP_INCLUDED
34.504065
80
0.622526
LLNL
55ca097a2cb125bcf15c83e8dc1898eb75d759a3
12,111
cpp
C++
tests/ship_log.cpp
abitmore/mandel
dfa3c92a713e7a093fc671fefa453a3033e27b0a
[ "MIT" ]
60
2022-01-03T18:41:12.000Z
2022-03-25T07:08:19.000Z
tests/ship_log.cpp
abitmore/mandel
dfa3c92a713e7a093fc671fefa453a3033e27b0a
[ "MIT" ]
37
2022-01-13T22:23:58.000Z
2022-03-31T13:32:38.000Z
tests/ship_log.cpp
abitmore/mandel
dfa3c92a713e7a093fc671fefa453a3033e27b0a
[ "MIT" ]
11
2022-01-14T21:14:11.000Z
2022-03-25T07:08:29.000Z
#include <boost/test/unit_test.hpp> #include <boost/test/data/test_case.hpp> #include <boost/test/data/monomorphic.hpp> #include <boost/test/data/monomorphic/generators/xrange.hpp> #include <fc/io/raw.hpp> #include <fc/bitutil.hpp> #include <eosio/state_history/log.hpp> namespace bdata = boost::unit_test::data; struct ship_log_fixture { ship_log_fixture(bool enable_read, bool reopen_on_mark, bool remove_index_on_reopen, bool vacuum_on_exit_if_small, std::optional<uint32_t> prune_blocks) : enable_read(enable_read), reopen_on_mark(reopen_on_mark), remove_index_on_reopen(remove_index_on_reopen), vacuum_on_exit_if_small(vacuum_on_exit_if_small), prune_blocks(prune_blocks) { bounce(); } void add(uint32_t index, size_t size, char fillchar) { std::vector<char> a; a.assign(size, fillchar); auto block_for_id = [](const uint32_t bnum) { fc::sha256 m = fc::sha256::hash(fc::sha256::hash(std::to_string(bnum))); m._hash[0] = fc::endian_reverse_u32(bnum); return m; }; eosio::state_history_log_header header; header.block_id = block_for_id(index); header.payload_size = a.size(); log->write_entry(header, block_for_id(index-1), [&](auto& f) { f.write(a.data(), a.size()); }); if(index + 1 > written_data.size()) written_data.resize(index + 1); written_data.at(index) = a; } void check_range_present(uint32_t first, uint32_t last) { BOOST_REQUIRE_EQUAL(log->begin_block(), first); BOOST_REQUIRE_EQUAL(log->end_block()-1, last); if(enable_read) { for(auto i = first; i <= last; i++) { std::vector<char> buff; buff.resize(written_data.at(i).size()); eosio::state_history_log_header header; fc::cfile& cf = log->get_entry(i, header); cf.read(buff.data(), written_data.at(i).size()); BOOST_REQUIRE(buff == written_data.at(i)); } } } void check_not_present(uint32_t index) { eosio::state_history_log_header header; BOOST_REQUIRE_EXCEPTION(log->get_entry(index, header), eosio::chain::plugin_exception, [](const eosio::chain::plugin_exception& e) { return e.to_detail_string().find("read non-existing block in") != std::string::npos; }); } void check_empty() { BOOST_REQUIRE_EQUAL(log->begin_block(), log->end_block()); } //double the fun template <typename F> void check_n_bounce(F&& f) { f(); if(reopen_on_mark) { bounce(); f(); } } bool enable_read, reopen_on_mark, remove_index_on_reopen, vacuum_on_exit_if_small; std::optional<uint32_t> prune_blocks; fc::temp_file log_file; fc::temp_file index_file; std::optional<eosio::state_history_log> log; std::vector<std::vector<char>> written_data; private: void bounce() { log.reset(); if(remove_index_on_reopen) fc::remove(index_file.path()); std::optional<eosio::state_history_log_prune_config> prune_conf; if(prune_blocks) { prune_conf.emplace(); prune_conf->prune_blocks = *prune_blocks; prune_conf->prune_threshold = 8; //every 8 bytes check in and see if to prune. should make it always check after each entry for us if(vacuum_on_exit_if_small) prune_conf->vacuum_on_close = 1024*1024*1024; //something large: always vacuum on close for these tests } log.emplace("shipit", log_file.path().string(), index_file.path().string(), prune_conf); } }; //can only punch holes on filesystem block boundaries. let's make sure the entries we add are larger than that static size_t larger_than_tmpfile_blocksize() { fc::temp_file tf; fc::cfile cf; cf.set_file_path(tf.path()); cf.open("ab"); return cf.filesystem_block_size() + cf.filesystem_block_size()/2; } BOOST_AUTO_TEST_SUITE(ship_file_tests) BOOST_DATA_TEST_CASE(basic_prune_test, bdata::xrange(2) * bdata::xrange(2) * bdata::xrange(2) * bdata::xrange(2), enable_read, reopen_on_mark, remove_index_on_reopen, vacuum_on_exit_if_small) { try { ship_log_fixture t(enable_read, reopen_on_mark, remove_index_on_reopen, vacuum_on_exit_if_small, 4); t.check_empty(); //with a small prune blocks value, the log will attempt to prune every filesystem block size. So let's just make // every entry be greater than that size size_t payload_size = larger_than_tmpfile_blocksize(); //we'll start at 2 here, since that's what you'd get from starting from genesis, but it really doesn't matter // one way or another for the ship log logic t.add(2, payload_size, 'A'); t.add(3, payload_size, 'B'); t.add(4, payload_size, 'C'); t.check_n_bounce([&]() { t.check_range_present(2, 4); }); t.add(5, payload_size, 'D'); t.check_n_bounce([&]() { t.check_range_present(2, 5); }); t.add(6, payload_size, 'E'); t.check_n_bounce([&]() { t.check_not_present(2); t.check_range_present(3, 6); }); t.add(7, payload_size, 'F'); t.check_n_bounce([&]() { t.check_not_present(2); t.check_not_present(3); t.check_range_present(4, 7); }); //undo 6 & 7 and reapply 6 t.add(6, payload_size, 'G'); t.check_n_bounce([&]() { t.check_not_present(2); t.check_not_present(3); t.check_not_present(7); t.check_range_present(4, 6); }); t.add(7, payload_size, 'H'); t.check_n_bounce([&]() { t.check_not_present(2); t.check_not_present(3); t.check_range_present(4, 7); }); t.add(8, payload_size, 'I'); t.add(9, payload_size, 'J'); t.add(10, payload_size, 'K'); t.check_n_bounce([&]() { t.check_range_present(7, 10); }); //undo back to the first stored block t.add(7, payload_size, 'L'); t.check_n_bounce([&]() { t.check_range_present(7, 7); t.check_not_present(6); t.check_not_present(8); }); t.add(8, payload_size, 'L'); t.add(9, payload_size, 'M'); t.add(10, payload_size, 'N'); t.add(11, payload_size, 'O'); t.check_n_bounce([&]() { t.check_range_present(8, 11); t.check_not_present(6); t.check_not_present(7); }); //undo past the first stored t.add(6, payload_size, 'P'); t.check_n_bounce([&]() { t.check_range_present(6, 6); t.check_not_present(7); t.check_not_present(8); }); //pile up a lot t.add(7, payload_size, 'Q'); t.add(8, payload_size, 'R'); t.add(9, payload_size, 'S'); t.add(10, payload_size, 'T'); t.add(11, payload_size, 'U'); t.add(12, payload_size, 'V'); t.add(13, payload_size, 'W'); t.add(14, payload_size, 'X'); t.add(15, payload_size, 'W'); t.add(16, payload_size, 'Z'); t.check_n_bounce([&]() { t.check_range_present(13, 16); t.check_not_present(12); t.check_not_present(17); }); } FC_LOG_AND_RETHROW() } BOOST_DATA_TEST_CASE(basic_test, bdata::xrange(2) * bdata::xrange(2) * bdata::xrange(2), enable_read, reopen_on_mark, remove_index_on_reopen) { try { ship_log_fixture t(enable_read, reopen_on_mark, remove_index_on_reopen, false, std::optional<uint32_t>()); t.check_empty(); size_t payload_size = larger_than_tmpfile_blocksize(); //we'll start off with a high number; but it really doesn't matter for ship's logs t.add(200, payload_size, 'A'); t.add(201, payload_size, 'B'); t.add(202, payload_size, 'C'); t.check_n_bounce([&]() { t.check_range_present(200, 202); }); t.add(203, payload_size, 'D'); t.add(204, payload_size, 'E'); t.add(205, payload_size, 'F'); t.add(206, payload_size, 'G'); t.add(207, payload_size, 'H'); t.check_n_bounce([&]() { t.check_range_present(200, 207); }); //fork off G & H t.add(206, payload_size, 'I'); t.add(207, payload_size, 'J'); t.check_n_bounce([&]() { t.check_range_present(200, 207); }); t.add(208, payload_size, 'K'); t.add(209, payload_size, 'L'); t.check_n_bounce([&]() { t.check_range_present(200, 209); t.check_not_present(199); t.check_not_present(210); }); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE(empty) { try { fc::temp_file log_file; fc::temp_file index_file; { eosio::state_history_log log("empty", log_file.path().string(), index_file.path().string()); BOOST_REQUIRE_EQUAL(log.begin_block(), log.end_block()); } //reopen { eosio::state_history_log log("empty", log_file.path().string(), index_file.path().string()); BOOST_REQUIRE_EQUAL(log.begin_block(), log.end_block()); } //reopen but prunned set const eosio::state_history_log_prune_config simple_prune_conf = { .prune_blocks = 4 }; { eosio::state_history_log log("empty", log_file.path().string(), index_file.path().string(), simple_prune_conf); BOOST_REQUIRE_EQUAL(log.begin_block(), log.end_block()); } { eosio::state_history_log log("empty", log_file.path().string(), index_file.path().string(), simple_prune_conf); BOOST_REQUIRE_EQUAL(log.begin_block(), log.end_block()); } //back to non pruned { eosio::state_history_log log("empty", log_file.path().string(), index_file.path().string()); BOOST_REQUIRE_EQUAL(log.begin_block(), log.end_block()); } { eosio::state_history_log log("empty", log_file.path().string(), index_file.path().string()); BOOST_REQUIRE_EQUAL(log.begin_block(), log.end_block()); } BOOST_REQUIRE(fc::file_size(log_file.path()) == 0); BOOST_REQUIRE(fc::file_size(index_file.path()) == 0); //one more time to pruned, just to make sure { eosio::state_history_log log("empty", log_file.path().string(), index_file.path().string(), simple_prune_conf); BOOST_REQUIRE_EQUAL(log.begin_block(), log.end_block()); } BOOST_REQUIRE(fc::file_size(log_file.path()) == 0); BOOST_REQUIRE(fc::file_size(index_file.path()) == 0); } FC_LOG_AND_RETHROW() } BOOST_DATA_TEST_CASE(non_prune_to_prune, bdata::xrange(2) * bdata::xrange(2), enable_read, remove_index_on_reopen) { try { ship_log_fixture t(enable_read, true, remove_index_on_reopen, false, std::optional<uint32_t>()); t.check_empty(); size_t payload_size = larger_than_tmpfile_blocksize(); t.add(2, payload_size, 'A'); t.add(3, payload_size, 'B'); t.add(4, payload_size, 'C'); t.add(5, payload_size, 'D'); t.add(6, payload_size, 'E'); t.add(7, payload_size, 'F'); t.add(8, payload_size, 'G'); t.add(9, payload_size, 'H'); t.check_n_bounce([&]() { t.check_range_present(2, 9); }); //upgrade to pruned... t.prune_blocks = 4; t.template check_n_bounce([]() {}); t.check_n_bounce([&]() { t.check_range_present(6, 9); }); t.add(10, payload_size, 'I'); t.add(11, payload_size, 'J'); t.add(12, payload_size, 'K'); t.add(13, payload_size, 'L'); t.check_n_bounce([&]() { t.check_range_present(10, 13); }); } FC_LOG_AND_RETHROW() } BOOST_DATA_TEST_CASE(prune_to_non_prune, bdata::xrange(2) * bdata::xrange(2), enable_read, remove_index_on_reopen) { try { ship_log_fixture t(enable_read, true, remove_index_on_reopen, false, 4); t.check_empty(); size_t payload_size = larger_than_tmpfile_blocksize(); t.add(2, payload_size, 'A'); t.add(3, payload_size, 'B'); t.add(4, payload_size, 'C'); t.add(5, payload_size, 'D'); t.add(6, payload_size, 'E'); t.add(7, payload_size, 'F'); t.add(8, payload_size, 'G'); t.add(9, payload_size, 'H'); t.check_n_bounce([&]() { t.check_range_present(6, 9); }); //no more pruned t.prune_blocks.reset(); t.template check_n_bounce([]() {}); t.check_n_bounce([&]() { t.check_range_present(6, 9); }); t.add(10, payload_size, 'I'); t.add(11, payload_size, 'J'); t.add(12, payload_size, 'K'); t.add(13, payload_size, 'L'); t.add(14, payload_size, 'M'); t.add(15, payload_size, 'N'); t.check_n_bounce([&]() { t.check_range_present(6, 15); }); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_SUITE_END()
31.787402
200
0.645199
abitmore
55ccb4ada59dd2d371ffe65fbd7676ba1663dd12
4,503
cpp
C++
third_party/libosmium/test/t/geom/test_wkt.cpp
peterkist-tinker/osrm-backend-appveyor-test
1891d7379c1d524ea6dc5a8d95e93f4023481a07
[ "BSD-2-Clause" ]
1
2017-04-15T22:58:23.000Z
2017-04-15T22:58:23.000Z
third_party/libosmium/test/t/geom/test_wkt.cpp
peterkist-tinker/osrm-backend-appveyor-test
1891d7379c1d524ea6dc5a8d95e93f4023481a07
[ "BSD-2-Clause" ]
1
2019-11-21T09:59:27.000Z
2019-11-21T09:59:27.000Z
osrm-ch/third_party/libosmium/test/t/geom/test_wkt.cpp
dingchunda/osrm-backend
8750749b83bd9193ca3481c630eefda689ecb73c
[ "BSD-2-Clause" ]
1
2021-08-04T02:32:10.000Z
2021-08-04T02:32:10.000Z
#include "catch.hpp" #include <osmium/geom/wkt.hpp> #include "area_helper.hpp" #include "wnl_helper.hpp" TEST_CASE("WKT_Geometry") { SECTION("point") { osmium::geom::WKTFactory<> factory; std::string wkt {factory.create_point(osmium::Location(3.2, 4.2))}; REQUIRE(std::string{"POINT(3.2 4.2)"} == wkt); } SECTION("empty_point") { osmium::geom::WKTFactory<> factory; REQUIRE_THROWS_AS(factory.create_point(osmium::Location()), osmium::invalid_location); } SECTION("linestring") { osmium::geom::WKTFactory<> factory; osmium::memory::Buffer buffer(10000); auto &wnl = create_test_wnl_okay(buffer); { std::string wkt {factory.create_linestring(wnl)}; REQUIRE(std::string{"LINESTRING(3.2 4.2,3.5 4.7,3.6 4.9)"} == wkt); } { std::string wkt {factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward)}; REQUIRE(std::string{"LINESTRING(3.6 4.9,3.5 4.7,3.2 4.2)"} == wkt); } { std::string wkt {factory.create_linestring(wnl, osmium::geom::use_nodes::all)}; REQUIRE(std::string{"LINESTRING(3.2 4.2,3.5 4.7,3.5 4.7,3.6 4.9)"} == wkt); } { std::string wkt {factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward)}; REQUIRE(std::string{"LINESTRING(3.6 4.9,3.5 4.7,3.5 4.7,3.2 4.2)"} == wkt); } } SECTION("empty_linestring") { osmium::geom::WKTFactory<> factory; osmium::memory::Buffer buffer(10000); auto &wnl = create_test_wnl_empty(buffer); REQUIRE_THROWS_AS(factory.create_linestring(wnl), osmium::geometry_error); REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward), osmium::geometry_error); REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::all), osmium::geometry_error); REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward), osmium::geometry_error); } SECTION("linestring_with_two_same_locations") { osmium::geom::WKTFactory<> factory; osmium::memory::Buffer buffer(10000); auto &wnl = create_test_wnl_same_location(buffer); REQUIRE_THROWS_AS(factory.create_linestring(wnl), osmium::geometry_error); try { factory.create_linestring(wnl); } catch (osmium::geometry_error& e) { REQUIRE(e.id() == 0); REQUIRE(std::string(e.what()) == "need at least two points for linestring"); } REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward), osmium::geometry_error); { std::string wkt {factory.create_linestring(wnl, osmium::geom::use_nodes::all)}; REQUIRE(std::string{"LINESTRING(3.5 4.7,3.5 4.7)"} == wkt); } { std::string wkt {factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward)}; REQUIRE(std::string{"LINESTRING(3.5 4.7,3.5 4.7)"} == wkt); } } SECTION("linestring_with_undefined_location") { osmium::geom::WKTFactory<> factory; osmium::memory::Buffer buffer(10000); auto &wnl = create_test_wnl_undefined_location(buffer); REQUIRE_THROWS_AS(factory.create_linestring(wnl), osmium::invalid_location); } SECTION("area_1outer_0inner") { osmium::geom::WKTFactory<> factory; osmium::memory::Buffer buffer(10000); const osmium::Area& area = create_test_area_1outer_0inner(buffer); { std::string wkt {factory.create_multipolygon(area)}; REQUIRE(std::string{"MULTIPOLYGON(((3.2 4.2,3.5 4.7,3.6 4.9,3.2 4.2)))"} == wkt); } } SECTION("area_1outer_1inner") { osmium::geom::WKTFactory<> factory; osmium::memory::Buffer buffer(10000); const osmium::Area& area = create_test_area_1outer_1inner(buffer); { std::string wkt {factory.create_multipolygon(area)}; REQUIRE(std::string{"MULTIPOLYGON(((0.1 0.1,9.1 0.1,9.1 9.1,0.1 9.1,0.1 0.1),(1 1,8 1,8 8,1 8,1 1)))"} == wkt); } } SECTION("area_2outer_2inner") { osmium::geom::WKTFactory<> factory; osmium::memory::Buffer buffer(10000); const osmium::Area& area = create_test_area_2outer_2inner(buffer); { std::string wkt {factory.create_multipolygon(area)}; REQUIRE(std::string{"MULTIPOLYGON(((0.1 0.1,9.1 0.1,9.1 9.1,0.1 9.1,0.1 0.1),(1 1,4 1,4 4,1 4,1 1),(5 5,5 7,7 7,5 5)),((10 10,11 10,11 11,10 11,10 10)))"} == wkt); } } }
32.868613
171
0.663113
peterkist-tinker
55d7dd7bfc763cff9b055f61848c80a1df1c274c
55,452
cc
C++
src/main/log/log0ddl.cc
xiaoma20082008/innodb
62f1cf0a1e249fbd867fbdc2f09816aa8cef4acd
[ "Apache-2.0" ]
null
null
null
src/main/log/log0ddl.cc
xiaoma20082008/innodb
62f1cf0a1e249fbd867fbdc2f09816aa8cef4acd
[ "Apache-2.0" ]
null
null
null
src/main/log/log0ddl.cc
xiaoma20082008/innodb
62f1cf0a1e249fbd867fbdc2f09816aa8cef4acd
[ "Apache-2.0" ]
null
null
null
/***************************************************************************** Copyright (c) 2017, 2021, Oracle and/or its affiliates. Portions of this file contain modifications contributed and copyrighted by Google, Inc. Those modifications are gratefully acknowledged and are described briefly in the InnoDB documentation. The contributions by Google are incorporated with their permission, and subject to the conditions contained in the file COPYING.Google. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ /** @file log/log0ddl.cc DDL log Created 12/1/2016 Shaohua Wang *******************************************************/ #include <debug_sync.h> #include "ha_prototypes.h" #include <current_thd.h> #include <sql_thd_internal_api.h> #include "btr0sea.h" #include "dict0dd.h" #include "dict0mem.h" #include "dict0stats.h" #include "ha_innodb.h" #include "log0ddl.h" #include "mysql/plugin.h" #include "pars0pars.h" #include "que0que.h" #include "row0ins.h" #include "row0row.h" #include "row0sel.h" #include "trx0trx.h" /** Object to handle Log_DDL */ Log_DDL *log_ddl = nullptr; /** Whether replaying DDL log Note: we should not write DDL log when replaying DDL log. */ thread_local bool thread_local_ddl_log_replay = false; /** Whether in recover(replay) DDL log in startup. */ bool Log_DDL::s_in_recovery = false; #ifdef UNIV_DEBUG /** Used by SET GLOBAL innodb_ddl_log_crash_counter_reset_debug = 1; */ bool innodb_ddl_log_crash_reset_debug; /** Below counters are only used for four types of DDL log: 1. FREE TREE 2. DELETE SPACE 3. RENAME SPACE 4. DROP Other RENAME_TABLE and REMOVE CACHE doesn't touch the data files at all, so would be skipped */ /** Crash injection counter used before writing FREE TREE log */ static uint32_t crash_before_free_tree_log_counter = 1; /** Crash injection counter used after writing FREE TREE log */ static uint32_t crash_after_free_tree_log_counter = 1; /** Crash injection counter used after deleting FREE TREE log */ static uint32_t crash_after_free_tree_delete_counter = 1; /** Crash injection counter used before writing DELETE SPACE log */ static uint32_t crash_before_delete_space_log_counter = 1; /** Crash injection counter used after writing DELETE SPACE log */ static uint32_t crash_after_delete_space_log_counter = 1; /** Crash injection counter used after deleting DELETE SPACE log */ static uint32_t crash_after_delete_space_delete_counter = 1; /** Crash injection counter used before writing RENAME SPACE log */ static uint32_t crash_before_rename_space_log_counter = 1; /** Crash injection counter used after writing RENAME SPACE log */ static uint32_t crash_after_rename_space_log_counter = 1; /** Crash injection counter used after deleting RENAME SPACE log */ static uint32_t crash_after_rename_space_delete_counter = 1; /** Crash injection counter used before writing DROP log */ static uint32_t crash_before_drop_log_counter = 1; /** Crash injection counter used after writing DROP log */ static uint32_t crash_after_drop_log_counter = 1; /** Crash injection counter used after any replay */ static uint32_t crash_after_replay_counter = 1; /** Crash injection counter used before writing ALTER ENCRYPT TABLESPACE log */ static uint32_t crash_before_alter_encrypt_space_log_counter = 1; /** Crash injection counter used after writing ALTER ENCRYPT TABLESPACE log */ static uint32_t crash_after_alter_encrypt_space_log_counter = 1; void ddl_log_crash_reset(THD *thd, SYS_VAR *var, void *var_ptr, const void *save) { const bool reset = *static_cast<const bool *>(save); innodb_ddl_log_crash_reset_debug = reset; if (reset) { crash_before_free_tree_log_counter = 1; crash_after_free_tree_log_counter = 1; crash_after_free_tree_delete_counter = 1; crash_before_delete_space_log_counter = 1; crash_after_delete_space_log_counter = 1; crash_after_delete_space_delete_counter = 1; crash_before_rename_space_log_counter = 1; crash_after_rename_space_log_counter = 1; crash_after_rename_space_delete_counter = 1; crash_before_drop_log_counter = 1; crash_after_drop_log_counter = 1; crash_after_replay_counter = 1; } } #endif /* UNIV_DEBUG */ DDL_Record::DDL_Record() : m_id(ULINT_UNDEFINED), m_thread_id(ULINT_UNDEFINED), m_space_id(SPACE_UNKNOWN), m_page_no(FIL_NULL), m_index_id(ULINT_UNDEFINED), m_table_id(ULINT_UNDEFINED), m_old_file_path(nullptr), m_new_file_path(nullptr), m_heap(nullptr), m_deletable(true) {} DDL_Record::~DDL_Record() { if (m_heap != nullptr) { mem_heap_free(m_heap); } } void DDL_Record::set_old_file_path(const char *name) { ulint len = strlen(name); if (m_heap == nullptr) { m_heap = mem_heap_create(FN_REFLEN + 1); } m_old_file_path = mem_heap_strdupl(m_heap, name, len); } void DDL_Record::set_old_file_path(const byte *data, ulint len) { if (m_heap == nullptr) { m_heap = mem_heap_create(FN_REFLEN + 1); } m_old_file_path = static_cast<char *>(mem_heap_dup(m_heap, data, len + 1)); m_old_file_path[len] = '\0'; } void DDL_Record::set_new_file_path(const char *name) { ulint len = strlen(name); if (m_heap == nullptr) { m_heap = mem_heap_create(FN_REFLEN + 1); } m_new_file_path = mem_heap_strdupl(m_heap, name, len); } void DDL_Record::set_new_file_path(const byte *data, ulint len) { if (m_heap == nullptr) { m_heap = mem_heap_create(FN_REFLEN + 1); } m_new_file_path = static_cast<char *>(mem_heap_dup(m_heap, data, len + 1)); m_new_file_path[len] = '\0'; } std::ostream &DDL_Record::print(std::ostream &out) const { ut_ad(m_type >= Log_Type::SMALLEST_LOG); ut_ad(m_type <= Log_Type::BIGGEST_LOG); bool printed = false; out << "[DDL record: "; switch (m_type) { case Log_Type::FREE_TREE_LOG: out << "FREE"; break; case Log_Type::DELETE_SPACE_LOG: out << "DELETE SPACE"; break; case Log_Type::RENAME_SPACE_LOG: out << "RENAME SPACE"; break; case Log_Type::DROP_LOG: out << "DROP"; break; case Log_Type::RENAME_TABLE_LOG: out << "RENAME TABLE"; break; case Log_Type::REMOVE_CACHE_LOG: out << "REMOVE CACHE"; break; case Log_Type::ALTER_ENCRYPT_TABLESPACE_LOG: out << "ALTER ENCRYPT TABLESPACE"; break; case Log_Type::ALTER_UNENCRYPT_TABLESPACE_LOG: out << "ALTER UNENCRYPT TABLESPACE"; break; default: ut_ad(0); } out << ","; if (m_id != ULINT_UNDEFINED) { out << " id=" << m_id; printed = true; } if (m_thread_id != ULINT_UNDEFINED) { if (printed) { out << ","; } out << " thread_id=" << m_thread_id; printed = true; } if (m_space_id != SPACE_UNKNOWN) { if (printed) { out << ","; } out << " space_id=" << m_space_id; printed = true; } if (m_table_id != ULINT_UNDEFINED) { if (printed) { out << ","; } out << " table_id=" << m_table_id; printed = true; } if (m_index_id != ULINT_UNDEFINED) { if (printed) { out << ","; } out << " index_id=" << m_index_id; printed = true; } if (m_page_no != FIL_NULL) { if (printed) { out << ","; } out << " page_no=" << m_page_no; printed = true; } if (m_old_file_path != nullptr) { if (printed) { out << ","; } out << " old_file_path=" << m_old_file_path; printed = true; } if (m_new_file_path != nullptr) { if (printed) { out << ","; } out << " new_file_path=" << m_new_file_path; } out << "]"; return (out); } /** Display a DDL record @param[in,out] o output stream @param[in] record DDL record to display @return the output stream */ std::ostream &operator<<(std::ostream &o, const DDL_Record &record) { return (record.print(o)); } DDL_Log_Table::DDL_Log_Table() : DDL_Log_Table(nullptr) {} DDL_Log_Table::DDL_Log_Table(trx_t *trx) : m_table(dict_sys->ddl_log), m_tuple(nullptr), m_trx(trx), m_thr(nullptr) { ut_ad(m_trx == nullptr || m_trx->ddl_operation); m_heap = mem_heap_create(1000); if (m_trx != nullptr) { start_query_thread(); } } DDL_Log_Table::~DDL_Log_Table() { stop_query_thread(); mem_heap_free(m_heap); } void DDL_Log_Table::start_query_thread() { que_t *graph = static_cast<que_fork_t *>(que_node_get_parent( pars_complete_graph_for_exec(nullptr, m_trx, m_heap, nullptr))); m_thr = que_fork_start_command(graph); ut_ad(m_trx->lock.n_active_thrs == 1); } void DDL_Log_Table::stop_query_thread() { if (m_thr != nullptr) { que_thr_stop_for_mysql_no_error(m_thr, m_trx); } } void DDL_Log_Table::create_tuple(const DDL_Record &record) { const dict_col_t *col; dfield_t *dfield; byte *buf; m_tuple = dtuple_create(m_heap, m_table->get_n_cols()); dict_table_copy_types(m_tuple, m_table); buf = static_cast<byte *>(mem_heap_alloc(m_heap, 8)); memset(buf, 0xFF, 8); col = m_table->get_sys_col(DATA_ROW_ID); dfield = dtuple_get_nth_field(m_tuple, dict_col_get_no(col)); dfield_set_data(dfield, buf, DATA_ROW_ID_LEN); col = m_table->get_sys_col(DATA_ROLL_PTR); dfield = dtuple_get_nth_field(m_tuple, dict_col_get_no(col)); dfield_set_data(dfield, buf, DATA_ROLL_PTR_LEN); buf = static_cast<byte *>(mem_heap_alloc(m_heap, DATA_TRX_ID_LEN)); mach_write_to_6(buf, m_trx->id); col = m_table->get_sys_col(DATA_TRX_ID); dfield = dtuple_get_nth_field(m_tuple, dict_col_get_no(col)); dfield_set_data(dfield, buf, DATA_TRX_ID_LEN); const ulint rec_id = record.get_id(); if (rec_id != ULINT_UNDEFINED) { buf = static_cast<byte *>(mem_heap_alloc(m_heap, s_id_col_len)); mach_write_to_8(buf, rec_id); dfield = dtuple_get_nth_field(m_tuple, s_id_col_no); dfield_set_data(dfield, buf, s_id_col_len); } if (record.get_thread_id() != ULINT_UNDEFINED) { buf = static_cast<byte *>(mem_heap_alloc(m_heap, s_thread_id_col_len)); mach_write_to_8(buf, record.get_thread_id()); dfield = dtuple_get_nth_field(m_tuple, s_thread_id_col_no); dfield_set_data(dfield, buf, s_thread_id_col_len); } ut_ad(record.get_type() >= Log_Type::SMALLEST_LOG); ut_ad(record.get_type() <= Log_Type::BIGGEST_LOG); buf = static_cast<byte *>(mem_heap_alloc(m_heap, s_type_col_len)); mach_write_to_4(buf, static_cast<typename std::underlying_type<Log_Type>::type>( record.get_type())); dfield = dtuple_get_nth_field(m_tuple, s_type_col_no); dfield_set_data(dfield, buf, s_type_col_len); if (record.get_space_id() != SPACE_UNKNOWN) { buf = static_cast<byte *>(mem_heap_alloc(m_heap, s_space_id_col_len)); mach_write_to_4(buf, record.get_space_id()); dfield = dtuple_get_nth_field(m_tuple, s_space_id_col_no); dfield_set_data(dfield, buf, s_space_id_col_len); } if (record.get_page_no() != FIL_NULL) { buf = static_cast<byte *>(mem_heap_alloc(m_heap, s_page_no_col_len)); mach_write_to_4(buf, record.get_page_no()); dfield = dtuple_get_nth_field(m_tuple, s_page_no_col_no); dfield_set_data(dfield, buf, s_page_no_col_len); } if (record.get_index_id() != ULINT_UNDEFINED) { buf = static_cast<byte *>(mem_heap_alloc(m_heap, s_index_id_col_len)); mach_write_to_8(buf, record.get_index_id()); dfield = dtuple_get_nth_field(m_tuple, s_index_id_col_no); dfield_set_data(dfield, buf, s_index_id_col_len); } if (record.get_table_id() != ULINT_UNDEFINED) { buf = static_cast<byte *>(mem_heap_alloc(m_heap, s_table_id_col_len)); mach_write_to_8(buf, record.get_table_id()); dfield = dtuple_get_nth_field(m_tuple, s_table_id_col_no); dfield_set_data(dfield, buf, s_table_id_col_len); } if (record.get_old_file_path() != nullptr) { ulint m_len = strlen(record.get_old_file_path()) + 1; dfield = dtuple_get_nth_field(m_tuple, s_old_file_path_col_no); dfield_set_data(dfield, record.get_old_file_path(), m_len); } if (record.get_new_file_path() != nullptr) { ulint m_len = strlen(record.get_new_file_path()) + 1; dfield = dtuple_get_nth_field(m_tuple, s_new_file_path_col_no); dfield_set_data(dfield, record.get_new_file_path(), m_len); } } void DDL_Log_Table::create_tuple(ulint id, const dict_index_t *index) { ut_ad(id != ULINT_UNDEFINED); dfield_t *dfield; ulint len; ulint table_col_offset; ulint index_col_offset; m_tuple = dtuple_create(m_heap, 1); dict_index_copy_types(m_tuple, index, 1); if (index->is_clustered()) { len = s_id_col_len; table_col_offset = s_id_col_no; } else { len = s_thread_id_col_len; table_col_offset = s_thread_id_col_no; } index_col_offset = index->get_col_pos(table_col_offset); byte *buf = static_cast<byte *>(mem_heap_alloc(m_heap, len)); mach_write_to_8(buf, id); dfield = dtuple_get_nth_field(m_tuple, index_col_offset); dfield_set_data(dfield, buf, len); } dberr_t DDL_Log_Table::insert(const DDL_Record &record) { dberr_t error; dict_index_t *index = m_table->first_index(); dtuple_t *entry; uint32_t flags = BTR_NO_LOCKING_FLAG; mem_heap_t *offsets_heap = mem_heap_create(1000); static std::atomic<uint64_t> count(0); if (count++ % 64 == 0) { log_free_check(); } create_tuple(record); entry = row_build_index_entry(m_tuple, nullptr, index, m_heap); #ifdef UNIV_DEBUG bool insert = true; DBUG_EXECUTE_IF("ddl_log_return_error_from_insert", insert = false;); if (insert) { #endif error = row_ins_clust_index_entry_low(flags, BTR_MODIFY_LEAF, index, index->n_uniq, entry, m_thr, false); #ifdef UNIV_DEBUG } else { error = DB_ERROR; } #endif if (error == DB_FAIL) { error = row_ins_clust_index_entry_low(flags, BTR_MODIFY_TREE, index, index->n_uniq, entry, m_thr, false); ut_ad(error == DB_SUCCESS); } if (error != DB_SUCCESS) { ib::error(ER_IB_ERR_DDL_LOG_INSERT_FAILURE); mem_heap_free(offsets_heap); return error; } index = index->next(); entry = row_build_index_entry(m_tuple, nullptr, index, m_heap); error = row_ins_sec_index_entry_low(flags, BTR_MODIFY_LEAF, index, offsets_heap, m_heap, entry, m_trx->id, m_thr, false); if (error == DB_FAIL) { error = row_ins_sec_index_entry_low(flags, BTR_MODIFY_TREE, index, offsets_heap, m_heap, entry, m_trx->id, m_thr, false); } mem_heap_free(offsets_heap); ut_ad(error == DB_SUCCESS); return (error); } void DDL_Log_Table::convert_to_ddl_record(bool is_clustered, rec_t *rec, const ulint *offsets, DDL_Record &record) { if (is_clustered) { for (ulint i = 0; i < rec_offs_n_fields(offsets); i++) { const byte *data; ulint len; if (i == DATA_ROLL_PTR || i == DATA_TRX_ID) { continue; } data = rec_get_nth_field(rec, offsets, i, &len); if (len != UNIV_SQL_NULL) { set_field(data, i, len, record); } } } else { /* For secondary index, only the ID would be stored */ record.set_id(parse_id(m_table->first_index()->next(), rec, offsets)); } } ulint DDL_Log_Table::parse_id(const dict_index_t *index, rec_t *rec, const ulint *offsets) { ulint len; ulint index_offset = index->get_col_pos(s_id_col_no); const byte *data = rec_get_nth_field(rec, offsets, index_offset, &len); ut_ad(len == s_id_col_len); return (mach_read_from_8(data)); } void DDL_Log_Table::set_field(const byte *data, ulint index_offset, ulint len, DDL_Record &record) { dict_index_t *index = dict_sys->ddl_log->first_index(); ulint col_offset = index->get_col_no(index_offset); if (col_offset == s_new_file_path_col_no) { record.set_new_file_path(data, len); return; } if (col_offset == s_old_file_path_col_no) { record.set_old_file_path(data, len); return; } ulint value = fetch_value(data, col_offset); switch (col_offset) { case s_id_col_no: record.set_id(value); break; case s_thread_id_col_no: record.set_thread_id(value); break; case s_type_col_no: record.set_type(static_cast<Log_Type>(value)); break; case s_space_id_col_no: record.set_space_id(static_cast<space_id_t>(value)); break; case s_page_no_col_no: record.set_page_no(static_cast<page_no_t>(value)); break; case s_index_id_col_no: record.set_index_id(value); break; case s_table_id_col_no: record.set_table_id(value); break; case s_old_file_path_col_no: case s_new_file_path_col_no: default: ut_ad(0); } } ulint DDL_Log_Table::fetch_value(const byte *data, ulint offset) { ulint value = 0; switch (offset) { case s_id_col_no: case s_thread_id_col_no: case s_index_id_col_no: case s_table_id_col_no: value = mach_read_from_8(data); return (value); case s_type_col_no: case s_space_id_col_no: case s_page_no_col_no: value = mach_read_from_4(data); return (value); case s_new_file_path_col_no: case s_old_file_path_col_no: default: ut_ad(0); break; } return (value); } dberr_t DDL_Log_Table::search_all(DDL_Records &records) { mtr_t mtr; btr_pcur_t pcur; rec_t *rec; bool move = true; ulint *offsets; dict_index_t *index = m_table->first_index(); dberr_t error = DB_SUCCESS; mtr_start(&mtr); /** Scan the index in decreasing order. */ btr_pcur_open_at_index_side(false, index, BTR_SEARCH_LEAF, &pcur, true, 0, &mtr); for (; move == true; move = btr_pcur_move_to_prev(&pcur, &mtr)) { rec = btr_pcur_get_rec(&pcur); if (page_rec_is_infimum(rec) || page_rec_is_supremum(rec)) { continue; } offsets = rec_get_offsets(rec, index, nullptr, ULINT_UNDEFINED, &m_heap); if (rec_get_deleted_flag(rec, dict_table_is_comp(m_table))) { continue; } DDL_Record *record = UT_NEW_NOKEY(DDL_Record()); convert_to_ddl_record(index->is_clustered(), rec, offsets, *record); records.push_back(record); } btr_pcur_close(&pcur); mtr_commit(&mtr); return (error); } dberr_t DDL_Log_Table::search(ulint thread_id, DDL_Records &records) { dberr_t error; DDL_Records records_of_thread_id; error = search_by_id(thread_id, m_table->first_index()->next(), records_of_thread_id); ut_ad(error == DB_SUCCESS); for (auto it = records_of_thread_id.rbegin(); it != records_of_thread_id.rend(); ++it) { error = search_by_id((*it)->get_id(), m_table->first_index(), records); ut_ad(error == DB_SUCCESS); } for (auto record : records_of_thread_id) { UT_DELETE(record); } return (error); } dberr_t DDL_Log_Table::search_by_id(ulint id, dict_index_t *index, DDL_Records &records) { mtr_t mtr; btr_pcur_t pcur; rec_t *rec; bool move = true; ulint *offsets; dberr_t error = DB_SUCCESS; mtr_start(&mtr); create_tuple(id, index); btr_pcur_open_with_no_init(index, m_tuple, PAGE_CUR_GE, BTR_SEARCH_LEAF, &pcur, 0, &mtr); for (; move == true; move = btr_pcur_move_to_next(&pcur, &mtr)) { rec = btr_pcur_get_rec(&pcur); if (page_rec_is_infimum(rec) || page_rec_is_supremum(rec)) { continue; } offsets = rec_get_offsets(rec, index, nullptr, ULINT_UNDEFINED, &m_heap); if (cmp_dtuple_rec(m_tuple, rec, index, offsets) != 0) { break; } if (rec_get_deleted_flag(rec, dict_table_is_comp(m_table))) { continue; } DDL_Record *record = UT_NEW_NOKEY(DDL_Record()); convert_to_ddl_record(index->is_clustered(), rec, offsets, *record); records.push_back(record); } mtr_commit(&mtr); return (error); } dberr_t DDL_Log_Table::remove(ulint id) { mtr_t mtr; dict_index_t *clust_index = m_table->first_index(); btr_pcur_t pcur; ulint *offsets; rec_t *rec; dict_index_t *index; dtuple_t *row; btr_cur_t *btr_cur; dtuple_t *entry; dberr_t err = DB_SUCCESS; enum row_search_result search_result; ulint flags = BTR_NO_LOCKING_FLAG; static uint64_t count = 0; if (count++ % 64 == 0) { log_free_check(); } create_tuple(id, clust_index); mtr_start(&mtr); btr_pcur_open(clust_index, m_tuple, PAGE_CUR_LE, BTR_MODIFY_TREE | BTR_LATCH_FOR_DELETE, &pcur, &mtr); btr_cur = btr_pcur_get_btr_cur(&pcur); if (page_rec_is_infimum(btr_pcur_get_rec(&pcur)) || btr_pcur_get_low_match(&pcur) < clust_index->n_uniq) { btr_pcur_close(&pcur); mtr_commit(&mtr); return (DB_SUCCESS); } offsets = rec_get_offsets(btr_pcur_get_rec(&pcur), clust_index, nullptr, ULINT_UNDEFINED, &m_heap); row = row_build(ROW_COPY_DATA, clust_index, btr_pcur_get_rec(&pcur), offsets, nullptr, nullptr, nullptr, nullptr, m_heap); rec = btr_cur_get_rec(btr_cur); if (!rec_get_deleted_flag(rec, dict_table_is_comp(m_table))) { err = btr_cur_del_mark_set_clust_rec(flags, btr_cur_get_block(btr_cur), rec, clust_index, offsets, m_thr, m_tuple, &mtr); } btr_pcur_close(&pcur); mtr_commit(&mtr); if (err != DB_SUCCESS) { return (err); } mtr_start(&mtr); index = clust_index->next(); entry = row_build_index_entry(row, nullptr, index, m_heap); search_result = row_search_index_entry( index, entry, BTR_MODIFY_LEAF | BTR_DELETE_MARK, &pcur, &mtr); btr_cur = btr_pcur_get_btr_cur(&pcur); if (search_result == ROW_NOT_FOUND) { btr_pcur_close(&pcur); mtr_commit(&mtr); ut_ad(0); return (DB_CORRUPTION); } rec = btr_cur_get_rec(btr_cur); if (!rec_get_deleted_flag(rec, dict_table_is_comp(m_table))) { err = btr_cur_del_mark_set_sec_rec(flags, btr_cur, TRUE, m_thr, &mtr); } btr_pcur_close(&pcur); mtr_commit(&mtr); return (err); } dberr_t DDL_Log_Table::remove(const DDL_Records &records) { dberr_t ret = DB_SUCCESS; for (auto record : records) { if (record->get_deletable()) { dberr_t err = remove(record->get_id()); ut_ad(err == DB_SUCCESS || err == DB_TOO_MANY_CONCURRENT_TRXS); if (err != DB_SUCCESS) { ret = err; } } } return (ret); } Log_DDL::Log_DDL() { ut_ad(dict_sys->ddl_log != nullptr); ut_ad(dict_table_has_autoinc_col(dict_sys->ddl_log)); } inline uint64_t Log_DDL::next_id() { uint64_t autoinc; dict_table_autoinc_lock(dict_sys->ddl_log); autoinc = dict_table_autoinc_read(dict_sys->ddl_log); ++autoinc; dict_table_autoinc_update_if_greater(dict_sys->ddl_log, autoinc); dict_table_autoinc_unlock(dict_sys->ddl_log); return (autoinc); } inline bool Log_DDL::skip(const dict_table_t *table, THD *thd) { return (recv_recovery_on || thread_local_ddl_log_replay || (table != nullptr && table->is_temporary()) || thd_is_bootstrap_thread(thd)); } dberr_t Log_DDL::write_free_tree_log(trx_t *trx, const dict_index_t *index, bool is_drop_table) { ut_ad(trx == thd_to_trx(current_thd)); if (skip(index->table, trx->mysql_thd)) { return (DB_SUCCESS); } if (index->type & DICT_FTS) { ut_ad(index->page == FIL_NULL); return (DB_SUCCESS); } if (dict_index_get_online_status(index) != ONLINE_INDEX_COMPLETE) { /* To skip any previously aborted index. This is because this kind of index should be already freed in previous post_ddl. It's inproper to log it and may free it again later, which may trigger some double free page problem. */ return (DB_SUCCESS); } uint64_t id = next_id(); ulint thread_id = thd_get_thread_id(trx->mysql_thd); dberr_t err; trx->ddl_operation = true; DBUG_INJECT_CRASH("ddl_log_crash_before_free_tree_log", crash_before_free_tree_log_counter++); if (is_drop_table) { /* Drop index case, if committed, will be redo only */ err = insert_free_tree_log(trx, index, id, thread_id); if (err != DB_SUCCESS) { return err; } DBUG_INJECT_CRASH("ddl_log_crash_after_free_tree_log", crash_after_free_tree_log_counter++); } else { /* This is the case of building index during create table scenario. The index will be dropped if ddl is rolled back */ err = insert_free_tree_log(nullptr, index, id, thread_id); if (err != DB_SUCCESS) { return err; } DBUG_INJECT_CRASH("ddl_log_crash_after_free_tree_log", crash_after_free_tree_log_counter++); DBUG_EXECUTE_IF("DDL_Log_remove_inject_error_1", srv_inject_too_many_concurrent_trxs = true;); /* Delete this operation if the create trx is committed */ err = delete_by_id(trx, id, false); ut_ad(err == DB_SUCCESS || err == DB_TOO_MANY_CONCURRENT_TRXS); DBUG_EXECUTE_IF("DDL_Log_remove_inject_error_1", srv_inject_too_many_concurrent_trxs = false;); DBUG_INJECT_CRASH("ddl_log_crash_after_free_tree_delete", crash_after_free_tree_delete_counter++); } return (err); } dberr_t Log_DDL::insert_free_tree_log(trx_t *trx, const dict_index_t *index, uint64_t id, ulint thread_id) { ut_ad(index->page != FIL_NULL); dberr_t error; bool has_dd_trx = (trx != nullptr); if (!has_dd_trx) { trx = trx_allocate_for_background(); trx_start_internal(trx); trx->ddl_operation = true; } else { trx_start_if_not_started(trx, true); } ut_ad(trx->ddl_operation); DDL_Record record; record.set_id(id); record.set_thread_id(thread_id); record.set_type(Log_Type::FREE_TREE_LOG); record.set_space_id(index->space); record.set_page_no(index->page); record.set_index_id(index->id); { DDL_Log_Table ddl_log(trx); error = ddl_log.insert(record); } if (!has_dd_trx) { trx_commit_for_mysql(trx); trx_free_for_background(trx); } if (error == DB_SUCCESS && srv_print_ddl_logs) { ib::info(ER_IB_MSG_647) << "DDL log insert : " << record; } return (error); } dberr_t Log_DDL::write_delete_space_log(trx_t *trx, const dict_table_t *table, space_id_t space_id, const char *file_path, bool is_drop, bool dict_locked) { ut_ad(trx == thd_to_trx(current_thd)); ut_ad(table == nullptr || dict_table_is_file_per_table(table)); if (skip(table, trx->mysql_thd)) { return (DB_SUCCESS); } uint64_t id = next_id(); ulint thread_id = thd_get_thread_id(trx->mysql_thd); dberr_t err; trx->ddl_operation = true; DBUG_INJECT_CRASH("ddl_log_crash_before_delete_space_log", crash_before_delete_space_log_counter++); if (is_drop) { err = insert_delete_space_log(trx, id, thread_id, space_id, file_path, dict_locked); if (err != DB_SUCCESS) { return err; } DBUG_INJECT_CRASH("ddl_log_crash_after_delete_space_log", crash_after_delete_space_log_counter++); } else { err = insert_delete_space_log(nullptr, id, thread_id, space_id, file_path, dict_locked); if (err != DB_SUCCESS) { return err; } DBUG_INJECT_CRASH("ddl_log_crash_after_delete_space_log", crash_after_delete_space_log_counter++); DBUG_EXECUTE_IF("DDL_Log_remove_inject_error_2", srv_inject_too_many_concurrent_trxs = true;); err = delete_by_id(trx, id, dict_locked); ut_ad(err == DB_SUCCESS || err == DB_TOO_MANY_CONCURRENT_TRXS); DBUG_EXECUTE_IF("DDL_Log_remove_inject_error_2", srv_inject_too_many_concurrent_trxs = false;); DBUG_INJECT_CRASH("ddl_log_crash_after_delete_space_delete", crash_after_delete_space_delete_counter++); } return (err); } dberr_t Log_DDL::insert_delete_space_log(trx_t *trx, uint64_t id, ulint thread_id, space_id_t space_id, const char *file_path, bool dict_locked) { dberr_t error; bool has_dd_trx = (trx != nullptr); if (!has_dd_trx) { trx = trx_allocate_for_background(); trx_start_internal(trx); trx->ddl_operation = true; } else { trx_start_if_not_started(trx, true); } ut_ad(trx->ddl_operation); if (dict_locked) { dict_sys_mutex_exit(); } DDL_Record record; record.set_id(id); record.set_thread_id(thread_id); record.set_type(Log_Type::DELETE_SPACE_LOG); record.set_space_id(space_id); record.set_old_file_path(file_path); { DDL_Log_Table ddl_log(trx); error = ddl_log.insert(record); } if (dict_locked) { dict_sys_mutex_enter(); } if (!has_dd_trx) { trx_commit_for_mysql(trx); trx_free_for_background(trx); } if (error == DB_SUCCESS && srv_print_ddl_logs) { ib::info(ER_IB_MSG_648) << "DDL log insert : " << record; } return (error); } dberr_t Log_DDL::write_rename_space_log(space_id_t space_id, const char *old_file_path, const char *new_file_path) { /* Missing current_thd, it happens during crash recovery */ if (!current_thd) { return (DB_SUCCESS); } trx_t *trx = thd_to_trx(current_thd); /* This is special case for fil_rename_tablespace during recovery */ if (trx == nullptr) { return (DB_SUCCESS); } if (skip(nullptr, trx->mysql_thd)) { return (DB_SUCCESS); } uint64_t id = next_id(); ulint thread_id = thd_get_thread_id(trx->mysql_thd); trx->ddl_operation = true; DBUG_INJECT_CRASH("ddl_log_crash_before_rename_space_log", crash_before_rename_space_log_counter++); dberr_t err = insert_rename_space_log(id, thread_id, space_id, old_file_path, new_file_path); if (err != DB_SUCCESS) { return err; } DBUG_INJECT_CRASH("ddl_log_crash_after_rename_space_log", crash_after_rename_space_log_counter++); DBUG_EXECUTE_IF("ddl_log_crash_after_rename_space_log_insert", DBUG_SUICIDE();); DBUG_EXECUTE_IF("DDL_Log_remove_inject_error_4", srv_inject_too_many_concurrent_trxs = true;); err = delete_by_id(trx, id, true); ut_ad(err == DB_SUCCESS || err == DB_TOO_MANY_CONCURRENT_TRXS); DBUG_EXECUTE_IF("DDL_Log_remove_inject_error_4", srv_inject_too_many_concurrent_trxs = false;); DBUG_INJECT_CRASH("ddl_log_crash_after_rename_space_delete", crash_after_rename_space_delete_counter++); return (err); } dberr_t Log_DDL::insert_rename_space_log(uint64_t id, ulint thread_id, space_id_t space_id, const char *old_file_path, const char *new_file_path) { dberr_t error; trx_t *trx = trx_allocate_for_background(); trx_start_internal(trx); trx->ddl_operation = true; ut_ad(dict_sys_mutex_own()); dict_sys_mutex_exit(); DDL_Record record; record.set_id(id); record.set_thread_id(thread_id); record.set_type(Log_Type::RENAME_SPACE_LOG); record.set_space_id(space_id); record.set_old_file_path(old_file_path); record.set_new_file_path(new_file_path); { DDL_Log_Table ddl_log(trx); error = ddl_log.insert(record); } dict_sys_mutex_enter(); trx_commit_for_mysql(trx); trx_free_for_background(trx); if (error == DB_SUCCESS && srv_print_ddl_logs) { ib::info(ER_IB_MSG_649) << "DDL log insert : " << record; } return (error); } DDL_Record *Log_DDL::find_alter_encrypt_record(space_id_t space_id) { if (!ts_encrypt_ddl_records.empty()) { for (const auto it : ts_encrypt_ddl_records) { if (it->get_space_id() == space_id) { return it; } } } return nullptr; } dberr_t Log_DDL::write_alter_encrypt_space_log(space_id_t space_id, encryption_op_type type, DDL_Record *existing_rec) { /* Missing current_thd, it happens during crash recovery */ if (!current_thd) { return (DB_SUCCESS); } trx_t *trx = thd_to_trx(current_thd); if (skip(nullptr, trx->mysql_thd)) { return (DB_SUCCESS); } uint64_t id = next_id(); ulint thread_id = thd_get_thread_id(trx->mysql_thd); trx->ddl_operation = true; DBUG_INJECT_CRASH("ddl_log_crash_before_alter_encrypt_space_log", crash_before_alter_encrypt_space_log_counter++); dberr_t err = insert_alter_encrypt_space_log(id, thread_id, space_id, type, existing_rec); if (err != DB_SUCCESS) { return err; } DBUG_INJECT_CRASH("ddl_log_crash_after_alter_encrypt_space_log", crash_after_alter_encrypt_space_log_counter++); DBUG_EXECUTE_IF("DDL_Log_remove_inject_startup_error_1", srv_inject_too_many_concurrent_trxs = true;); /* This record to be removed with main transaction commit */ err = delete_by_id(trx, id, false); ut_ad(err == DB_SUCCESS || err == DB_TOO_MANY_CONCURRENT_TRXS); DBUG_EXECUTE_IF("DDL_Log_remove_inject_startup_error_1", srv_inject_too_many_concurrent_trxs = false;); return (err); } dberr_t Log_DDL::insert_alter_encrypt_space_log(uint64_t id, ulint thread_id, space_id_t space_id, encryption_op_type type, DDL_Record *existing_rec) { dberr_t err = DB_SUCCESS; trx_t *trx = trx_allocate_for_background(); trx_start_internal(trx); trx->ddl_operation = true; ut_ad(type == ENCRYPTION || type == DECRYPTION); DDL_Record record; record.set_id(id); record.set_thread_id(thread_id); if (type == ENCRYPTION) { record.set_type(Log_Type::ALTER_ENCRYPT_TABLESPACE_LOG); } else if (type == DECRYPTION) { record.set_type(Log_Type::ALTER_UNENCRYPT_TABLESPACE_LOG); } else { ut_ad(false); } record.set_space_id(space_id); { DDL_Log_Table ddl_log(trx); if (existing_rec != nullptr) { err = ddl_log.remove(existing_rec->get_id()); ut_ad(err == DB_SUCCESS || err == DB_TOO_MANY_CONCURRENT_TRXS); if (err == DB_TOO_MANY_CONCURRENT_TRXS) { ib::error(ER_IB_MSG_DDL_LOG_DELETE_BY_ID_TMCT); } } if (err == DB_SUCCESS) { err = ddl_log.insert(record); } } trx_commit_for_mysql(trx); trx_free_for_background(trx); if (err == DB_SUCCESS && srv_print_ddl_logs) { ib::info(ER_IB_MSG_1284) << "DDL log insert : " << record; } return (err); } dberr_t Log_DDL::write_drop_log(trx_t *trx, const table_id_t table_id) { if (skip(nullptr, trx->mysql_thd)) { return (DB_SUCCESS); } trx->ddl_operation = true; uint64_t id = next_id(); ulint thread_id = thd_get_thread_id(trx->mysql_thd); DBUG_INJECT_CRASH("ddl_log_crash_before_drop_log", crash_before_drop_log_counter++); dberr_t err; err = insert_drop_log(trx, id, thread_id, table_id); if (err != DB_SUCCESS) { return err; } DBUG_INJECT_CRASH("ddl_log_crash_after_drop_log", crash_after_drop_log_counter++); return (err); } dberr_t Log_DDL::insert_drop_log(trx_t *trx, uint64_t id, ulint thread_id, const table_id_t table_id) { ut_ad(trx->ddl_operation); ut_ad(dict_sys_mutex_own()); trx_start_if_not_started(trx, true); dict_sys_mutex_exit(); dberr_t error; DDL_Record record; record.set_id(id); record.set_thread_id(thread_id); record.set_type(Log_Type::DROP_LOG); record.set_table_id(table_id); { DDL_Log_Table ddl_log(trx); error = ddl_log.insert(record); } dict_sys_mutex_enter(); if (error == DB_SUCCESS && srv_print_ddl_logs) { ib::info(ER_IB_MSG_650) << "DDL log insert : " << record; } return (error); } dberr_t Log_DDL::write_rename_table_log(dict_table_t *table, const char *old_name, const char *new_name) { trx_t *trx = thd_to_trx(current_thd); if (skip(table, trx->mysql_thd)) { return (DB_SUCCESS); } uint64_t id = next_id(); ulint thread_id = thd_get_thread_id(trx->mysql_thd); trx->ddl_operation = true; dberr_t err = insert_rename_table_log(id, thread_id, table->id, old_name, new_name); if (err != DB_SUCCESS) { return err; } DBUG_EXECUTE_IF("DDL_Log_remove_inject_error_5", srv_inject_too_many_concurrent_trxs = true;); err = delete_by_id(trx, id, true); ut_ad(err == DB_SUCCESS || err == DB_TOO_MANY_CONCURRENT_TRXS); DBUG_EXECUTE_IF("DDL_Log_remove_inject_error_5", srv_inject_too_many_concurrent_trxs = false;); return (err); } dberr_t Log_DDL::insert_rename_table_log(uint64_t id, ulint thread_id, table_id_t table_id, const char *old_name, const char *new_name) { dberr_t error; trx_t *trx = trx_allocate_for_background(); trx_start_internal(trx); trx->ddl_operation = true; ut_ad(dict_sys_mutex_own()); dict_sys_mutex_exit(); DDL_Record record; record.set_id(id); record.set_thread_id(thread_id); record.set_type(Log_Type::RENAME_TABLE_LOG); record.set_table_id(table_id); record.set_old_file_path(old_name); record.set_new_file_path(new_name); { DDL_Log_Table ddl_log(trx); error = ddl_log.insert(record); } dict_sys_mutex_enter(); trx_commit_for_mysql(trx); trx_free_for_background(trx); if (error == DB_SUCCESS && srv_print_ddl_logs) { ib::info(ER_IB_MSG_651) << "DDL log insert : " << record; } return (error); } dberr_t Log_DDL::write_remove_cache_log(trx_t *trx, dict_table_t *table) { ut_ad(trx == thd_to_trx(current_thd)); if (skip(table, trx->mysql_thd)) { return (DB_SUCCESS); } uint64_t id = next_id(); ulint thread_id = thd_get_thread_id(trx->mysql_thd); trx->ddl_operation = true; dberr_t err = insert_remove_cache_log(id, thread_id, table->id, table->name.m_name); if (err != DB_SUCCESS) { return err; } DBUG_EXECUTE_IF("DDL_Log_remove_inject_error_3", srv_inject_too_many_concurrent_trxs = true;); err = delete_by_id(trx, id, false); ut_ad(err == DB_SUCCESS || err == DB_TOO_MANY_CONCURRENT_TRXS); DBUG_EXECUTE_IF("DDL_Log_remove_inject_error_3", srv_inject_too_many_concurrent_trxs = false;); return (err); } dberr_t Log_DDL::insert_remove_cache_log(uint64_t id, ulint thread_id, table_id_t table_id, const char *table_name) { dberr_t error; trx_t *trx = trx_allocate_for_background(); trx_start_internal(trx); trx->ddl_operation = true; DDL_Record record; record.set_id(id); record.set_thread_id(thread_id); record.set_type(Log_Type::REMOVE_CACHE_LOG); record.set_table_id(table_id); record.set_new_file_path(table_name); { DDL_Log_Table ddl_log(trx); error = ddl_log.insert(record); } trx_commit_for_mysql(trx); trx_free_for_background(trx); if (error == DB_SUCCESS && srv_print_ddl_logs) { ib::info(ER_IB_MSG_652) << "DDL log insert : " << record; } return (error); } dberr_t Log_DDL::delete_by_id(trx_t *trx, uint64_t id, bool dict_locked) { dberr_t err; trx_start_if_not_started(trx, true); ut_ad(trx->ddl_operation); if (dict_locked) { dict_sys_mutex_exit(); } { DDL_Log_Table ddl_log(trx); err = ddl_log.remove(id); ut_ad(err == DB_SUCCESS || err == DB_TOO_MANY_CONCURRENT_TRXS); if (err == DB_TOO_MANY_CONCURRENT_TRXS) { ib::error(ER_IB_MSG_DDL_LOG_DELETE_BY_ID_TMCT); } } if (dict_locked) { dict_sys_mutex_enter(); } if (srv_print_ddl_logs && err == DB_SUCCESS) { ib::info(ER_IB_MSG_DDL_LOG_DELETE_BY_ID_OK) << "DDL log delete : " << id; } return (err); } dberr_t Log_DDL::replay_all() { ut_ad(is_in_recovery()); DDL_Log_Table ddl_log; DDL_Records records; dberr_t err = ddl_log.search_all(records); ut_ad(err == DB_SUCCESS); for (auto record : records) { err = log_ddl->replay(*record); if (err != DB_SUCCESS) { break; } } if (err != DB_SUCCESS) { return err; } err = delete_by_ids(records); ut_ad(err == DB_SUCCESS || err == DB_TOO_MANY_CONCURRENT_TRXS); for (auto record : records) { if (record->get_deletable()) { UT_DELETE(record); } } return (err); } dberr_t Log_DDL::replay_by_thread_id(ulint thread_id) { DDL_Log_Table ddl_log; DDL_Records records; dberr_t err = ddl_log.search(thread_id, records); ut_ad(err == DB_SUCCESS); for (auto record : records) { if (record->get_type() == Log_Type::ALTER_ENCRYPT_TABLESPACE_LOG || record->get_type() == Log_Type::ALTER_UNENCRYPT_TABLESPACE_LOG) { DDL_Record *rec = find_alter_encrypt_record(record->get_space_id()); if (rec != nullptr) { ut_ad(record->get_id() != rec->get_id()); } } else { log_ddl->replay(*record); } } err = delete_by_ids(records); ut_ad(err == DB_SUCCESS || err == DB_TOO_MANY_CONCURRENT_TRXS); for (auto record : records) { if (record->get_deletable()) { UT_DELETE(record); } } return (err); } #define DELETE_IDS_RETRIES_MAX 10 dberr_t Log_DDL::delete_by_ids(DDL_Records &records) { dberr_t err = DB_SUCCESS; if (records.empty()) { return (err); } int t; for (t = DELETE_IDS_RETRIES_MAX; t > 0; t--) { trx_t *trx; trx = trx_allocate_for_background(); trx_start_if_not_started(trx, true); trx->ddl_operation = true; { DDL_Log_Table ddl_log(trx); err = ddl_log.remove(records); ut_ad(err == DB_SUCCESS || err == DB_TOO_MANY_CONCURRENT_TRXS); } trx_commit_for_mysql(trx); trx_free_for_background(trx); #ifdef UNIV_DEBUG if (srv_inject_too_many_concurrent_trxs) { srv_inject_too_many_concurrent_trxs = false; } #endif /* UNIV_DEBUG */ if (err != DB_TOO_MANY_CONCURRENT_TRXS) { break; } } return (err); } dberr_t Log_DDL::replay(DDL_Record &record) { dberr_t err = DB_SUCCESS; if (srv_print_ddl_logs) { ib::info(ER_IB_MSG_654) << "DDL log replay : " << record; } switch (record.get_type()) { case Log_Type::FREE_TREE_LOG: replay_free_tree_log(record.get_space_id(), record.get_page_no(), record.get_index_id()); break; case Log_Type::DELETE_SPACE_LOG: replay_delete_space_log(record.get_space_id(), record.get_old_file_path()); break; case Log_Type::RENAME_SPACE_LOG: replay_rename_space_log(record.get_space_id(), record.get_old_file_path(), record.get_new_file_path()); break; case Log_Type::DROP_LOG: replay_drop_log(record.get_table_id()); break; case Log_Type::RENAME_TABLE_LOG: replay_rename_table_log(record.get_table_id(), record.get_old_file_path(), record.get_new_file_path()); break; case Log_Type::REMOVE_CACHE_LOG: replay_remove_cache_log(record.get_table_id(), record.get_new_file_path()); break; case Log_Type::ALTER_ENCRYPT_TABLESPACE_LOG: case Log_Type::ALTER_UNENCRYPT_TABLESPACE_LOG: err = replay_alter_encrypt_space_log(record); break; default: ut_error; } return (err); } void Log_DDL::replay_free_tree_log(space_id_t space_id, page_no_t page_no, ulint index_id) { ut_ad(space_id != SPACE_UNKNOWN); ut_ad(page_no != FIL_NULL); bool found; const page_size_t page_size(fil_space_get_page_size(space_id, &found)); /* Skip if it is a single table tablespace and the .ibd file is missing */ if (!found) { if (srv_print_ddl_logs) { ib::info(ER_IB_MSG_655) << "DDL log replay : FREE tablespace " << space_id << " is missing."; } return; } /* This is required by dropping hash index afterwards. */ dict_sys_mutex_enter(); mtr_t mtr; mtr_start(&mtr); btr_free_if_exists(page_id_t(space_id, page_no), page_size, index_id, &mtr); mtr_commit(&mtr); dict_sys_mutex_exit(); DBUG_INJECT_CRASH("ddl_log_crash_after_replay", crash_after_replay_counter++); } void Log_DDL::replay_delete_space_log(space_id_t space_id, const char *file_path) { THD *thd = current_thd; if (fsp_is_undo_tablespace(space_id)) { /* Serialize this delete with all undo tablespace DDLs. */ mutex_enter(&undo::ddl_mutex); /* If this is called during DROP UNDO TABLESPACE, then the undo_space is already gone. But if this is called at startup after a crash, that memory object might exist. If the crash occurred just before the file was deleted, then at startup it was opened in srv_undo_tablespaces_open(). Then in trx_rsegs_init(), any explicit undo tablespace that did not contain any undo logs was set to empty. That prevented any new undo logs to be added during the startup process up till now. So whether we are at runtime or startup, we assert that the undo tablespace is empty and delete the undo::Tablespace object if it exists. */ undo::spaces->x_lock(); space_id_t space_num = undo::id2num(space_id); undo::Tablespace *undo_space = undo::spaces->find(space_num); if (undo_space != nullptr) { ut_a(undo_space->is_empty()); undo::spaces->drop(undo_space); } undo::spaces->x_unlock(); } if (thd != nullptr) { /* For general tablespace, MDL on SDI tables is already acquired at innobase_drop_tablespace() and for file_per_table tablespace, MDL is acquired at row_drop_table_for_mysql() */ dict_sys_mutex_enter(); dict_sdi_remove_from_cache(space_id, nullptr, true); dict_sys_mutex_exit(); } /* A master key rotation blocks all DDLs using backup_lock, so it is assured that during CREATE/DROP TABLE, master key will not change. */ DBUG_EXECUTE_IF("ddl_log_replay_delete_space_crash_before_drop", DBUG_SUICIDE();); /* Update filename with correct partition case, of needed. */ std::string path_str(file_path); std::string space_name; fil_update_partition_name(space_id, 0, false, space_name, path_str); file_path = path_str.c_str(); row_drop_tablespace(space_id, file_path); /* If this is an undo space_id, allow the undo number for it to be reused. */ if (fsp_is_undo_tablespace(space_id)) { undo::spaces->x_lock(); undo::unuse_space_id(space_id); undo::spaces->x_unlock(); mutex_exit(&undo::ddl_mutex); } DBUG_INJECT_CRASH("ddl_log_crash_after_replay", crash_after_replay_counter++); } void Log_DDL::replay_rename_space_log(space_id_t space_id, const char *old_file_path, const char *new_file_path) { bool ret; page_id_t page_id(space_id, 0); std::string space_name; /* Update old filename with correct partition case, of needed. */ std::string old_path(old_file_path); fil_update_partition_name(space_id, 0, false, space_name, old_path); old_file_path = old_path.c_str(); /* Update new filename with correct partition case, of needed. */ std::string new_path(new_file_path); fil_update_partition_name(space_id, 0, false, space_name, new_path); new_file_path = new_path.c_str(); ret = fil_op_replay_rename_for_ddl(page_id, old_file_path, new_file_path); if (!ret && srv_print_ddl_logs) { ib::info(ER_IB_MSG_656) << "DDL log replay : RENAME from " << old_file_path << " to " << new_file_path << " failed"; } DBUG_INJECT_CRASH("ddl_log_crash_after_replay", crash_after_replay_counter++); } static dberr_t replace_and_insert(DDL_Record *record) { dberr_t err = DB_SUCCESS; trx_t *trx = trx_allocate_for_background(); trx_start_internal(trx); trx->ddl_operation = true; /* update the thread_id for the record */ record->set_thread_id(ULINT_MAX); { DDL_Log_Table ddl_log(trx); /* Remove old record and insert the new record */ err = ddl_log.remove(record->get_id()); ut_ad(err == DB_SUCCESS || err == DB_TOO_MANY_CONCURRENT_TRXS); if (err == DB_SUCCESS) { /* Insert new record entry */ err = ddl_log.insert(*record); } } trx_commit_for_mysql(trx); trx_free_for_background(trx); return err; } dberr_t Log_DDL::replay_alter_encrypt_space_log(DDL_Record &record) { dberr_t error = DB_SUCCESS; /* Normal operation, we shouldn't come here during post_ddl */ ut_ad(is_in_recovery()); error = replace_and_insert(&record); if (error != DB_SUCCESS) { return error; } ut_ad(record.get_thread_id() == ULINT_MAX); /* We could have resume encrypiton execution one by one for each tablespace from here by calling SQL API to run the query. But then it would be blocking server bootstrap. We need to resume ths encryption in BG thread so we need to just make a note of this space and operation here and don't do any real operation. */ ts_encrypt_ddl_records.push_back(&record); /* Make sure not to delete this record till resume operation finishes. This is to make sure that if there is a crash before that, we can resume encryption in the next restart. */ record.set_deletable(false); DBUG_INJECT_CRASH("ddl_log_crash_after_replay", crash_after_replay_counter++); return error; } void Log_DDL::replay_drop_log(const table_id_t table_id) { mutex_enter(&dict_persist->mutex); ut_d(dberr_t error =) dict_persist->table_buffer->remove(table_id); ut_ad(error == DB_SUCCESS); mutex_exit(&dict_persist->mutex); DBUG_INJECT_CRASH("ddl_log_crash_after_replay", crash_after_replay_counter++); } void Log_DDL::replay_rename_table_log(table_id_t table_id, const char *old_name, const char *new_name) { if (is_in_recovery()) { if (srv_print_ddl_logs) { ib::info(ER_IB_MSG_657) << "DDL log replay : in recovery," << " skip RENAME TABLE"; } return; } trx_t *trx; trx = trx_allocate_for_background(); trx->mysql_thd = current_thd; trx_start_if_not_started(trx, true); row_mysql_lock_data_dictionary(trx); trx_set_dict_operation(trx, TRX_DICT_OP_TABLE); /* Convert partition table name DDL log, if needed. Required if upgrading a crashed database. */ std::string old_table(old_name); dict_name::rebuild(old_table); old_name = old_table.c_str(); std::string new_table(new_name); dict_name::rebuild(new_table); new_name = new_table.c_str(); dberr_t err; err = row_rename_table_for_mysql(old_name, new_name, nullptr, trx, true); dict_table_t *table; table = dd_table_open_on_name_in_mem(new_name, true); if (table != nullptr) { dict_table_ddl_release(table); dd_table_close(table, nullptr, nullptr, true); } row_mysql_unlock_data_dictionary(trx); trx_commit_for_mysql(trx); trx_free_for_background(trx); if (err != DB_SUCCESS) { if (srv_print_ddl_logs) { ib::info(ER_IB_MSG_658) << "DDL log replay : rename table" << " in cache from " << old_name << " to " << new_name; } } else { /* TODO: Once we get rid of dict_operation_lock, we may consider to do this in row_rename_table_for_mysql, so no need to worry this rename here */ char errstr[512]; dict_stats_rename_table(old_name, new_name, errstr, sizeof(errstr)); } } void Log_DDL::replay_remove_cache_log(table_id_t table_id, const char *table_name) { if (is_in_recovery()) { if (srv_print_ddl_logs) { ib::info(ER_IB_MSG_659) << "DDL log replay : in recovery," << " skip REMOVE CACHE"; } return; } dict_table_t *table; table = dd_table_open_on_id_in_mem(table_id, false); /* Convert partition table name DDL log, if needed. Required if upgrading a crashed database. */ std::string table_str(table_name); dict_name::rebuild(table_str); table_name = table_str.c_str(); if (table != nullptr) { ut_ad(strcmp(table->name.m_name, table_name) == 0); dict_sys_mutex_enter(); dd_table_close(table, nullptr, nullptr, true); btr_drop_ahi_for_table(table); dict_table_remove_from_cache(table); dict_sys_mutex_exit(); } } dberr_t Log_DDL::post_ddl(THD *thd) { if (skip(nullptr, thd)) { return (DB_SUCCESS); } if (srv_read_only_mode || srv_force_recovery >= SRV_FORCE_NO_UNDO_LOG_SCAN) { return (DB_SUCCESS); } DEBUG_SYNC(thd, "innodb_ddl_log_before_enter"); DBUG_EXECUTE_IF("ddl_log_before_post_ddl", DBUG_SUICIDE();); /* If srv_force_recovery > 0, DROP TABLE is allowed, and here only DELETE and DROP log can be replayed. */ ulint thread_id = thd_get_thread_id(thd); if (srv_print_ddl_logs) { ib::info(ER_IB_MSG_660) << "DDL log post ddl : begin for thread id : " << thread_id; } thread_local_ddl_log_replay = true; dberr_t err = replay_by_thread_id(thread_id); thread_local_ddl_log_replay = false; if (srv_print_ddl_logs) { ib::info(ER_IB_MSG_661) << "DDL log post ddl : end for thread id : " << thread_id; } return (err); } dberr_t Log_DDL::recover() { if (srv_read_only_mode || srv_force_recovery > 0) { return (DB_SUCCESS); } ib::info(ER_IB_MSG_662) << "DDL log recovery : begin"; thread_local_ddl_log_replay = true; s_in_recovery = true; dberr_t err = replay_all(); thread_local_ddl_log_replay = false; s_in_recovery = false; ib::info(ER_IB_MSG_663) << "DDL log recovery : end"; return (err); }
28.291837
80
0.670995
xiaoma20082008
55d8dc189146a8414e2bd3eef0c7c58e4c2fa6bd
821
cc
C++
vendor/chromium/base/profiler/profile_builder.cc
thorium-cfx/fivem
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
[ "MIT" ]
5,411
2017-04-14T08:57:56.000Z
2022-03-30T19:35:15.000Z
vendor/chromium/base/profiler/profile_builder.cc
thorium-cfx/fivem
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
[ "MIT" ]
802
2017-04-21T14:18:36.000Z
2022-03-31T21:20:48.000Z
vendor/chromium/base/profiler/profile_builder.cc
thorium-cfx/fivem
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
[ "MIT" ]
2,011
2017-04-14T09:44:15.000Z
2022-03-31T15:40:39.000Z
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/profiler/profile_builder.h" namespace base { const size_t ProfileBuilder::MAX_METADATA_COUNT; ProfileBuilder::MetadataItem::MetadataItem(uint64_t name_hash, Optional<int64_t> key, int64_t value) : name_hash(name_hash), key(key), value(value) {} ProfileBuilder::MetadataItem::MetadataItem() : name_hash(0), value(0) {} ProfileBuilder::MetadataItem::MetadataItem(const MetadataItem& other) = default; ProfileBuilder::MetadataItem& ProfileBuilder::MetadataItem::MetadataItem:: operator=(const MetadataItem& other) = default; } // namespace base
34.208333
80
0.694275
thorium-cfx
55d92902035bee0e07c3f8779565175d56239f57
752
hpp
C++
boost/network/protocol/http/traits/connection_keepalive.hpp
antoinelefloch/cpp-netlib
5eb9b5550a10d06f064ee9883c7d942d3426f31b
[ "BSL-1.0" ]
3
2015-02-10T22:08:08.000Z
2021-11-13T20:59:25.000Z
include/boost/network/protocol/http/traits/connection_keepalive.hpp
waTeim/boost
eb3850fae8c037d632244cf15cf6905197d64d39
[ "BSL-1.0" ]
1
2018-08-10T04:47:12.000Z
2018-08-10T13:54:57.000Z
include/boost/network/protocol/http/traits/connection_keepalive.hpp
waTeim/boost
eb3850fae8c037d632244cf15cf6905197d64d39
[ "BSL-1.0" ]
5
2017-12-28T12:42:25.000Z
2021-07-01T07:41:53.000Z
// Copyright (c) Dean Michael Berris 2010. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_NETWORK_PROTOCOL_HTTP_TRAITS_CONECTION_KEEPALIVE_20091218 #define BOOST_NETWORK_PROTOCOL_HTTP_TRAITS_CONECTION_KEEPALIVE_20091218 #include <boost/network/protocol/http/tags.hpp> #include <boost/network/protocol/http/support/is_keepalive.hpp> namespace boost { namespace network { namespace http { template <class Tag> struct connection_keepalive : is_keepalive<Tag> {}; } /* http */ } /* network */ } /* boost */ #endif // BOOST_NETWORK_PROTOCOL_HTTP_TRAITS_CONECTION_KEEPALIVE_20091218
30.08
73
0.74734
antoinelefloch
55da0c41e5c7d7bfafb4e9ad99bc5234ce32a6d8
1,433
cpp
C++
generated/src/ModuleInterface.cpp
MMX-World/vnx-base
c806599e630e17928e8c2d9271e896797a069ba2
[ "Apache-2.0" ]
null
null
null
generated/src/ModuleInterface.cpp
MMX-World/vnx-base
c806599e630e17928e8c2d9271e896797a069ba2
[ "Apache-2.0" ]
2
2022-02-07T05:19:09.000Z
2022-03-24T18:44:37.000Z
generated/src/ModuleInterface.cpp
MMX-World/vnx-base
c806599e630e17928e8c2d9271e896797a069ba2
[ "Apache-2.0" ]
1
2022-01-22T21:30:26.000Z
2022-01-22T21:30:26.000Z
// AUTO GENERATED by vnxcppcodegen #include <vnx/package.hxx> #include <vnx/ModuleInterface.hxx> #include <vnx/ModuleInfo.hxx> #include <vnx/ModuleInterface_vnx_get_config.hxx> #include <vnx/ModuleInterface_vnx_get_config_return.hxx> #include <vnx/ModuleInterface_vnx_get_config_object.hxx> #include <vnx/ModuleInterface_vnx_get_config_object_return.hxx> #include <vnx/ModuleInterface_vnx_get_module_info.hxx> #include <vnx/ModuleInterface_vnx_get_module_info_return.hxx> #include <vnx/ModuleInterface_vnx_get_type_code.hxx> #include <vnx/ModuleInterface_vnx_get_type_code_return.hxx> #include <vnx/ModuleInterface_vnx_restart.hxx> #include <vnx/ModuleInterface_vnx_restart_return.hxx> #include <vnx/ModuleInterface_vnx_self_test.hxx> #include <vnx/ModuleInterface_vnx_self_test_return.hxx> #include <vnx/ModuleInterface_vnx_set_config.hxx> #include <vnx/ModuleInterface_vnx_set_config_return.hxx> #include <vnx/ModuleInterface_vnx_set_config_object.hxx> #include <vnx/ModuleInterface_vnx_set_config_object_return.hxx> #include <vnx/ModuleInterface_vnx_stop.hxx> #include <vnx/ModuleInterface_vnx_stop_return.hxx> #include <vnx/Object.hpp> #include <vnx/TypeCode.hpp> #include <vnx/Variant.hpp> #include <vnx/vnx.h> namespace vnx { const vnx::Hash64 ModuleInterface::VNX_TYPE_HASH(0xe189eb244fe14948ull); const vnx::Hash64 ModuleInterface::VNX_CODE_HASH(0xe189eb244fe14948ull); } // namespace vnx namespace vnx { } // vnx
32.568182
72
0.836706
MMX-World
55dae1a01cdd017f36227863375e21aff2332ee6
482
hpp
C++
include/Thread.hpp
Kiloris/Complot_Game
81247c6c13d7921a9cc01b765ab3a4a5924c2391
[ "MIT" ]
null
null
null
include/Thread.hpp
Kiloris/Complot_Game
81247c6c13d7921a9cc01b765ab3a4a5924c2391
[ "MIT" ]
null
null
null
include/Thread.hpp
Kiloris/Complot_Game
81247c6c13d7921a9cc01b765ab3a4a5924c2391
[ "MIT" ]
null
null
null
/* ** COMPLOT PROJECT ** AUTHOR: ** Zacharie ABIDAT */ #ifndef THREAD_HPP_ #define THREAD_HPP_ #include <pthread.h> class IThread { public: virtual ~IThread() {} virtual void run() = 0; }; class Thread : public IThread{ public: Thread(); ~Thread(); virtual void launchThread(); virtual void stopThread(); static void * execute(void *object); protected: private: pthread_t thread; }; #endif /* !THREAD_HPP_ */
15.548387
44
0.60166
Kiloris
55dbc9b949953d785ad81490982842118873a7e2
1,802
hpp
C++
libraries/chain/include/blurt/chain/steem_evaluator.hpp
Blurt-Blockchain/steem
fbffd373cdb0f6192aa8806d07e8671e219c3767
[ "MIT" ]
2
2020-04-21T03:10:06.000Z
2020-04-21T05:49:46.000Z
libraries/chain/include/blurt/chain/steem_evaluator.hpp
Blurt-Blockchain/steem
fbffd373cdb0f6192aa8806d07e8671e219c3767
[ "MIT" ]
4
2020-04-22T05:14:18.000Z
2020-04-22T07:59:20.000Z
libraries/chain/include/blurt/chain/steem_evaluator.hpp
Blurt-Blockchain/steem
fbffd373cdb0f6192aa8806d07e8671e219c3767
[ "MIT" ]
2
2020-04-22T05:04:29.000Z
2020-10-23T13:58:19.000Z
#pragma once #include <blurt/protocol/blurt_operations.hpp> #include <blurt/chain/evaluator.hpp> namespace blurt { namespace chain { using namespace blurt::protocol; BLURT_DEFINE_EVALUATOR( account_create ) BLURT_DEFINE_EVALUATOR( account_update ) BLURT_DEFINE_EVALUATOR( transfer ) BLURT_DEFINE_EVALUATOR( transfer_to_vesting ) BLURT_DEFINE_EVALUATOR( witness_update ) BLURT_DEFINE_EVALUATOR( account_witness_vote ) BLURT_DEFINE_EVALUATOR( account_witness_proxy ) BLURT_DEFINE_EVALUATOR( withdraw_vesting ) BLURT_DEFINE_EVALUATOR( set_withdraw_vesting_route ) BLURT_DEFINE_EVALUATOR( comment ) BLURT_DEFINE_EVALUATOR( comment_options ) BLURT_DEFINE_EVALUATOR( delete_comment ) BLURT_DEFINE_EVALUATOR( vote ) BLURT_DEFINE_EVALUATOR( custom ) BLURT_DEFINE_EVALUATOR( custom_json ) BLURT_DEFINE_EVALUATOR( custom_binary ) BLURT_DEFINE_EVALUATOR( escrow_transfer ) BLURT_DEFINE_EVALUATOR( escrow_approve ) BLURT_DEFINE_EVALUATOR( escrow_dispute ) BLURT_DEFINE_EVALUATOR( escrow_release ) BLURT_DEFINE_EVALUATOR( claim_account ) BLURT_DEFINE_EVALUATOR( create_claimed_account ) BLURT_DEFINE_EVALUATOR( request_account_recovery ) BLURT_DEFINE_EVALUATOR( recover_account ) BLURT_DEFINE_EVALUATOR( change_recovery_account ) BLURT_DEFINE_EVALUATOR( transfer_to_savings ) BLURT_DEFINE_EVALUATOR( transfer_from_savings ) BLURT_DEFINE_EVALUATOR( cancel_transfer_from_savings ) BLURT_DEFINE_EVALUATOR( decline_voting_rights ) BLURT_DEFINE_EVALUATOR( reset_account ) BLURT_DEFINE_EVALUATOR( set_reset_account ) BLURT_DEFINE_EVALUATOR( claim_reward_balance ) BLURT_DEFINE_EVALUATOR( delegate_vesting_shares ) BLURT_DEFINE_EVALUATOR( witness_set_properties ) BLURT_DEFINE_EVALUATOR( create_proposal ) BLURT_DEFINE_EVALUATOR( update_proposal_votes ) BLURT_DEFINE_EVALUATOR( remove_proposal ) } } // blurt::chain
36.04
54
0.870144
Blurt-Blockchain
55dbcf7336d1b63c59e5a4a5caca1dca31f253f4
5,482
cpp
C++
src/low-level/syscall/syscall.cpp
LittleCodingFox/ToastOS
28475cbde3bd358460e070575e91496bf211f1d5
[ "BSD-2-Clause" ]
5
2021-12-21T19:17:00.000Z
2022-03-10T17:56:59.000Z
src/low-level/syscall/syscall.cpp
LittleCodingFox/ToastOS
28475cbde3bd358460e070575e91496bf211f1d5
[ "BSD-2-Clause" ]
null
null
null
src/low-level/syscall/syscall.cpp
LittleCodingFox/ToastOS
28475cbde3bd358460e070575e91496bf211f1d5
[ "BSD-2-Clause" ]
null
null
null
#include "syscall.hpp" #include "process/Process.hpp" #include "registers/Registers.hpp" #include "gdt/gdt.hpp" #include "debug.hpp" #include "threading/lock.hpp" typedef int64_t (*SyscallPointer)(InterruptStack *stack); int64_t KNotImplemented(InterruptStack *stack); int64_t SyscallWrite(InterruptStack *stack); int64_t SyscallRead(InterruptStack *stack); int64_t SyscallClose(InterruptStack *stack); int64_t SyscallOpen(InterruptStack *stack); int64_t SyscallSeek(InterruptStack *stack); int64_t SyscallAnonAlloc(InterruptStack *stack); int64_t SyscallVMMap(InterruptStack *stack); int64_t SyscallVMUnmap(InterruptStack *stack); int64_t SyscallTCBSet(InterruptStack *stack); int64_t SyscallSigaction(InterruptStack *stack); int64_t SyscallGetPID(InterruptStack *stack); int64_t SyscallKill(InterruptStack *stack); int64_t SyscallIsATTY(InterruptStack *stack); int64_t SyscallStat(InterruptStack *stack); int64_t SyscallFStat(InterruptStack *stack); int64_t SyscallPanic(InterruptStack *stack); int64_t SyscallReadEntries(InterruptStack *stack); int64_t SyscallExit(InterruptStack *stack); int64_t SyscallClock(InterruptStack *stack); int64_t SyscallGetUID(InterruptStack *stack); int64_t SyscallSetUID(InterruptStack *stack); int64_t SyscallGetGID(InterruptStack *stack); int64_t SyscallSigprocMask(InterruptStack *stack); int64_t SyscallFcntl(InterruptStack *stack); int64_t SyscallLog(InterruptStack *stack); int64_t SyscallFork(InterruptStack *stack); int64_t SyscallWaitPID(InterruptStack *stack); int64_t SyscallGetPPID(InterruptStack *stack); int64_t SyscallSetGraphicsType(InterruptStack *stack); int64_t SyscallSetGraphicsBuffer(InterruptStack *stack); int64_t SyscallGetGraphicsSize(InterruptStack *stack); int64_t SyscallExecve(InterruptStack *stack); int64_t SyscallPollInput(InterruptStack *stack); int64_t SyscallCWD(InterruptStack *stack); int64_t SyscallCHDir(InterruptStack *stack); int64_t SyscallSpawnThread(InterruptStack *stack); int64_t SyscallYield(InterruptStack *stack); int64_t SyscallExitThread(InterruptStack *stack); int64_t SyscallGetTID(InterruptStack *stack); int64_t SyscallFutexWait(InterruptStack *stack); int64_t SyscallFutexWake(InterruptStack *stack); int64_t SyscallSetKBLayout(InterruptStack *stack); int64_t SyscallPipe(InterruptStack *stack); int64_t SyscallDup2(InterruptStack *stack); SyscallPointer syscallHandlers[] = { [0] = (SyscallPointer)KNotImplemented, [SYSCALL_READ] = (SyscallPointer)SyscallRead, [SYSCALL_WRITE] = (SyscallPointer)SyscallWrite, [SYSCALL_OPEN] = (SyscallPointer)SyscallOpen, [SYSCALL_CLOSE] = (SyscallPointer)SyscallClose, [SYSCALL_SEEK] = (SyscallPointer)SyscallSeek, [SYSCALL_ANON_ALLOC] = (SyscallPointer)SyscallAnonAlloc, [SYSCALL_VM_MAP] = (SyscallPointer)SyscallVMMap, [SYSCALL_VM_UNMAP] = (SyscallPointer)SyscallVMUnmap, [SYSCALL_TCB_SET] = (SyscallPointer)SyscallTCBSet, [SYSCALL_SIGACTION] = (SyscallPointer)SyscallSigaction, [SYSCALL_GETPID] = (SyscallPointer)SyscallGetPID, [SYSCALL_KILL] = (SyscallPointer)SyscallKill, [SYSCALL_ISATTY] = (SyscallPointer)SyscallIsATTY, [SYSCALL_FSTAT] = (SyscallPointer)SyscallFStat, [SYSCALL_STAT] = (SyscallPointer)SyscallStat, [SYSCALL_PANIC] = (SyscallPointer)SyscallPanic, [SYSCALL_READ_ENTRIES] = (SyscallPointer)SyscallReadEntries, [SYSCALL_EXIT] = (SyscallPointer)SyscallExit, [SYSCALL_CLOCK] = (SyscallPointer)SyscallClock, [SYSCALL_GETUID] = (SyscallPointer)SyscallGetUID, [SYSCALL_SETUID] = (SyscallPointer)SyscallSetUID, [SYSCALL_GETGID] = (SyscallPointer)SyscallGetGID, [SYSCALL_SIGPROCMASK] = (SyscallPointer)SyscallSigprocMask, [SYSCALL_FCNTL] = (SyscallPointer)SyscallFcntl, [SYSCALL_LOG] = (SyscallPointer)SyscallLog, [SYSCALL_FORK] = (SyscallPointer)SyscallFork, [SYSCALL_WAITPID] = (SyscallPointer)SyscallWaitPID, [SYSCALL_GETPPID] = (SyscallPointer)SyscallGetPPID, [SYSCALL_SETGRAPHICSTYPE] = (SyscallPointer)SyscallSetGraphicsType, [SYSCALL_GETGRAPHICSSIZE] = (SyscallPointer)SyscallGetGraphicsSize, [SYSCALL_SETGRAPHICSBUFFER] = (SyscallPointer)SyscallSetGraphicsBuffer, [SYSCALL_EXECVE] = (SyscallPointer)SyscallExecve, [SYSCALL_POLLINPUT] = (SyscallPointer)SyscallPollInput, [SYSCALL_CWD] = (SyscallPointer)SyscallCWD, [SYSCALL_CHDIR] = (SyscallPointer)SyscallCHDir, [SYSCALL_SPAWN_THREAD] = (SyscallPointer)SyscallSpawnThread, [SYSCALL_YIELD] = (SyscallPointer)SyscallYield, [SYSCALL_THREAD_EXIT] = (SyscallPointer)SyscallExitThread, [SYSCALL_GET_TID] = (SyscallPointer)SyscallGetTID, [SYSCALL_FUTEX_WAIT] = (SyscallPointer)SyscallFutexWait, [SYSCALL_FUTEX_WAKE] = (SyscallPointer)SyscallFutexWake, [SYSCALL_SETKBLAYOUT] = (SyscallPointer)SyscallSetKBLayout, [SYSCALL_PIPE] = (SyscallPointer)SyscallPipe, [SYSCALL_DUP2] = (SyscallPointer)SyscallDup2, }; void SyscallHandler(InterruptStack *stack) { if(stack->rdi <= sizeof(syscallHandlers) / sizeof(SyscallPointer) && syscallHandlers[stack->rdi] != NULL) { auto current = globalProcessManager->CurrentThread(); current->activePermissionLevel = PROCESS_PERMISSION_KERNEL; auto handler = syscallHandlers[stack->rdi]; auto result = handler(stack); stack->rax = result; current->activePermissionLevel = PROCESS_PERMISSION_USER; } } int64_t KNotImplemented(InterruptStack *stack) { DEBUG_OUT("Syscall: KNotImplemented", 0); return -1; }
42.828125
109
0.78931
LittleCodingFox
55ddbd54e78e8734201e4035a2672efa301a7b0f
4,420
cpp
C++
test/vector3d_unittest.cpp
sslnjz/geodesy
c7acc47903a22b12c0fca65fd0e7e8fea122af25
[ "MIT" ]
2
2021-11-23T05:39:48.000Z
2021-12-06T02:53:53.000Z
test/vector3d_unittest.cpp
sslnjz/geodesy
c7acc47903a22b12c0fca65fd0e7e8fea122af25
[ "MIT" ]
null
null
null
test/vector3d_unittest.cpp
sslnjz/geodesy
c7acc47903a22b12c0fca65fd0e7e8fea122af25
[ "MIT" ]
null
null
null
/********************************************************************************** * MIT License * * * * Copyright (c) 2021 Binbin Song <ssln.jzs@gmail.com> * * * * Geodesy tools for conversions between (historical) datums * * (c) Chris Veness 2005-2019 * * www.movable-type.co.uk/scripts/latlong-convert-coords.html * * www.movable-type.co.uk/scripts/geodesy-library.html#latlon-ellipsoidal-datum * * * * 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 <gtest/gtest.h> #include "geodesy/vector3d.h" TEST(vector3d_unittest, Constructor) { const geodesy::vector3d v3d(0.267, 0.535, 0.802); EXPECT_DOUBLE_EQ(v3d.x(), 0.267); EXPECT_DOUBLE_EQ(v3d.y(), 0.535); EXPECT_DOUBLE_EQ(v3d.z(), 0.802); } TEST(vector3d_unittest, methods) { const auto v123 = geodesy::vector3d(1, 2, 3); const auto v321 = geodesy::vector3d(3, 2, 1); EXPECT_EQ(v123.plus(v321), geodesy::vector3d(4, 4, 4)); EXPECT_EQ(v123.minus(v321), geodesy::vector3d(-2, 0, 2)); EXPECT_EQ(v123.times(2), geodesy::vector3d(2, 4, 6)); EXPECT_EQ(v123.dividedBy(2), geodesy::vector3d(0.5, 1, 1.5)); EXPECT_EQ(v123.dot(v321), 10); EXPECT_EQ(v123.cross(v321), geodesy::vector3d(-4, 8, -4)); EXPECT_EQ(v123.negate(), geodesy::vector3d(-1, -2, -3)); EXPECT_EQ(v123.length(), 3.7416573867739413); EXPECT_EQ(v123.unit().toString(), "[0.267, 0.535, 0.802]"); EXPECT_EQ(geodesy::toFixed(geodesy::toDegrees(v123.angleTo(v321)), 3), "44.415"); EXPECT_EQ(geodesy::toFixed(geodesy::toDegrees(v123.angleTo(v321, v123.cross(v321))), 3), "44.415"); EXPECT_EQ(geodesy::toFixed(geodesy::toDegrees(v123.angleTo(v321, v321.cross(v123))), 3), "-44.415"); EXPECT_EQ(geodesy::toFixed(geodesy::toDegrees(v123.angleTo(v321, v123)), 3), "44.415"); EXPECT_EQ(v123.rotateAround(geodesy::vector3d(0, 0, 1), 90).toString(), "[-0.535, 0.267, 0.802]"); EXPECT_EQ(v123.toString(), "[1.000, 2.000, 3.000]"); EXPECT_EQ(v123.toString(6), "[1.000000, 2.000000, 3.000000]"); } TEST(vector3d_unittest, operators) { auto v123 = geodesy::vector3d(1, 2, 3); const auto v321 = geodesy::vector3d(3, 2, 1); EXPECT_EQ((v123 += v321), geodesy::vector3d(4, 4, 4)); v123 = geodesy::vector3d(1, 2, 3); EXPECT_EQ(v123 -= v321, geodesy::vector3d(-2, 0, 2)); v123 = geodesy::vector3d(1, 2, 3); EXPECT_EQ(v123 *= 2, geodesy::vector3d(2, 4, 6)); v123 = geodesy::vector3d(1, 2, 3); EXPECT_EQ(v123 /= 2, geodesy::vector3d(0.5, 1, 1.5)); }
58.933333
104
0.53371
sslnjz
55de142e845e9442ba0fb0f5ec164f7c8184479c
559
cpp
C++
Leetcode/0649. Dota2 Senate/0649.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/0649. Dota2 Senate/0649.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/0649. Dota2 Senate/0649.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
class Solution { public: string predictPartyVictory(string senate) { const int n = senate.length(); queue<int> qR; queue<int> qD; for (int i = 0; i < n; ++i) if (senate[i] == 'R') qR.push(i); else qD.push(i); while (!qR.empty() && !qD.empty()) { const int indexR = qR.front(); qR.pop(); const int indexD = qD.front(); qD.pop(); if (indexR < indexD) qR.push(indexR + n); else qD.push(indexD + n); } return qR.empty() ? "Dire" : "Radiant"; } };
19.964286
45
0.49195
Next-Gen-UI
55e11381a3a3893852125e31bfc28f51128c99c1
2,856
cpp
C++
problemsets/SPOJ/SPOJ - BR/FAZENDMG.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/SPOJ/SPOJ - BR/FAZENDMG.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/SPOJ/SPOJ - BR/FAZENDMG.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ #include <cstdio> using namespace std; short M[1510][1510]; int X[30], Y[30], L[30], C[30]; int id = 1; int dx[] = { -1, 0, 1, 0}; int dy[] = { 0, -1, 0, 1}; int get_int() { int ch, i, s; while (((ch = getchar()) == ' ') || (ch == '\n')); s = (ch=='-') ? (ch=getchar(),-1) : 1; for (i = 0; ch >= '0' && ch <= '9'; ch = getchar() ) i = (i<<3)+(i<<1)+(ch-'0'); return s*i; } int main() { int N; while (N = get_int()) { int A = 0, P = 0; for (int i = 0; i < N; i++) { X[i] = get_int()+1; Y[i] = get_int()+1; L[i] = get_int(); C[i] = get_int(); // scanf("%d %d %d %d", X+i, Y+i, L+i, C+i); X[i]++; Y[i]++; for (int l = X[i]; l < X[i]+L[i]; l++) for (int c = Y[i]; c < Y[i]+C[i]; c++) if (M[l][c]!=id) A++, M[l][c]=id; } for (int i = 0; i < N; i++) { for (int j = X[i]; j < X[i]+L[i]; j++) { int x = j, y = Y[i]; if (M[x][y]!=id+1) { M[x][y] = id+1; int v = 0; for (int k = 0; k < 4; k++) if (M[x+dx[k]][y+dy[k]]>=id) v++; if (v == 3) P++; else if (v == 2) P+=2; else if (v == 1) P+=3; else if (v == 0) P+=4; } x = j, y = Y[i]+C[i]-1; if (M[x][y]!=id+1) { M[x][y] = id+1; int v = 0; for (int k = 0; k < 4; k++) if (M[x+dx[k]][y+dy[k]]>=id) v++; if (v == 3) P++; else if (v == 2) P+=2; else if (v == 1) P+=3; else if (v == 0) P+=4; } } for (int j = Y[i]+1; j < Y[i]+C[i]-1; j++) { int x = X[i], y = j; if (M[x][y]!=id+1) { M[x][y] = id+1; int v = 0; for (int k = 0; k < 4; k++) if (M[x+dx[k]][y+dy[k]]>=id) v++; if (v == 3) P++; else if (v == 2) P+=2; else if (v == 1) P+=3; else if (v == 0) P+=4; } x = X[i]+L[i]-1, y = j; if (M[x][y]!=id+1) { M[x][y] = id+1; int v = 0; for (int k = 0; k < 4; k++) if (M[x+dx[k]][y+dy[k]]>=id) v++; if (v == 3) P++; else if (v == 2) P+=2; else if (v == 1) P+=3; else if (v == 0) P+=4; } } } printf("%d %d\n", A, P); id+=2; } return 0; }
29.443299
89
0.272409
juarezpaulino
55e7a3f929e1be27d2d46879189b9939b1b1937a
4,381
cpp
C++
Vic2ToHoI4Tests/HoI4WorldTests/Diplomacy/Hoi4WarTests.cpp
gawquon/Vic2ToHoI4
8371cfb1fd57cf81d854077963135d8037e754eb
[ "MIT" ]
25
2018-12-10T03:41:49.000Z
2021-10-04T10:42:36.000Z
Vic2ToHoI4Tests/HoI4WorldTests/Diplomacy/Hoi4WarTests.cpp
gawquon/Vic2ToHoI4
8371cfb1fd57cf81d854077963135d8037e754eb
[ "MIT" ]
739
2018-12-13T02:01:20.000Z
2022-03-28T02:57:13.000Z
Vic2ToHoI4Tests/HoI4WorldTests/Diplomacy/Hoi4WarTests.cpp
Osariusz/Vic2ToHoI4
9738b52c7602b1fe187c3820660c58a8d010d87e
[ "MIT" ]
43
2018-12-10T03:41:58.000Z
2022-03-22T23:55:41.000Z
#include "HOI4World/Diplomacy/HoI4War.h" #include "Mappers/Country/CountryMapperBuilder.h" #include "Mappers/Provinces/ProvinceMapperBuilder.h" #include "gtest/gtest.h" #include <sstream> TEST(HoI4World_Diplomacy_WarTests, allItemsDefaultToEmpty) { const HoI4::War war(Vic2::War({}), *Mappers::CountryMapper::Builder().Build(), Mappers::CasusBellis({}), Mappers::ProvinceMapper{}, std::map<int, int>{}); std::stringstream output; output << war; std::stringstream expectedOutput; expectedOutput << "declare_war_on = {\n"; expectedOutput << "\ttarget = \n"; expectedOutput << "\ttype = topple_government\n"; expectedOutput << "}\n"; expectedOutput << "\n"; ASSERT_EQ(expectedOutput.str(), output.str()); } TEST(HoI4World_Diplomacy_WarTests, warnIfOriginalDefenderCantBeMapped) { std::stringstream log; auto stdOutBuf = std::cout.rdbuf(); std::cout.rdbuf(log.rdbuf()); const HoI4::War war(Vic2::War(Vic2::WarOptions{.originalAttacker{"OAT"}, .originalDefender{"ODF"}}), *Mappers::CountryMapper::Builder().addMapping("OAT", "NAT").Build(), Mappers::CasusBellis({}), Mappers::ProvinceMapper{}, std::map<int, int>{}); std::cout.rdbuf(stdOutBuf); ASSERT_EQ(" [WARNING] Could not map ODF, original defender in a war\n", log.str()); } TEST(HoI4World_Diplomacy_WarTests, extraDefendersCanBeAdded) { const HoI4::War war( Vic2::War(Vic2::WarOptions{.originalAttacker{"OAT"}, .originalDefender{"ODF"}, .defenders{{"OED"}}}), *Mappers::CountryMapper::Builder() .addMapping("ODF", "NDF") .addMapping("OED", "NED") .addMapping("OAT", "NAT") .Build(), Mappers::CasusBellis({}), Mappers::ProvinceMapper{}, std::map<int, int>{}); std::stringstream output; output << war; std::stringstream expectedOutput; expectedOutput << "declare_war_on = {\n"; expectedOutput << "\ttarget = NDF\n"; expectedOutput << "\ttype = topple_government\n"; expectedOutput << "}\n"; expectedOutput << "NED = {\n"; expectedOutput << "\tadd_to_war = {\n"; expectedOutput << "\t\ttargeted_alliance = NDF\n"; expectedOutput << "\t\tenemy = NAT\n"; expectedOutput << "\t}\n"; expectedOutput << "}\n"; expectedOutput << "\n"; ASSERT_EQ(expectedOutput.str(), output.str()); } TEST(HoI4World_Diplomacy_WarTests, extraAttackersCanBeAdded) { const HoI4::War war( Vic2::War(Vic2::WarOptions{.originalAttacker{"OAT"}, .attackers{{"OEA"}}, .originalDefender{"ODF"}}), *Mappers::CountryMapper::Builder() .addMapping("ODF", "NDF") .addMapping("OEA", "NEA") .addMapping("OAT", "NAT") .Build(), Mappers::CasusBellis({}), Mappers::ProvinceMapper{}, std::map<int, int>{}); std::stringstream output; output << war; std::stringstream expectedOutput; expectedOutput << "declare_war_on = {\n"; expectedOutput << "\ttarget = NDF\n"; expectedOutput << "\ttype = topple_government\n"; expectedOutput << "}\n"; expectedOutput << "NEA = {\n"; expectedOutput << "\tadd_to_war = {\n"; expectedOutput << "\t\ttargeted_alliance = NAT\n"; expectedOutput << "\t\tenemy = NDF\n"; expectedOutput << "\t}\n"; expectedOutput << "}\n"; expectedOutput << "\n"; ASSERT_EQ(expectedOutput.str(), output.str()); } TEST(HoI4World_Diplomacy_WarTests, warnIfOriginalAttackerCantBeMapped) { std::stringstream log; auto stdOutBuf = std::cout.rdbuf(); std::cout.rdbuf(log.rdbuf()); const HoI4::War war(Vic2::War(Vic2::WarOptions{.originalAttacker{"OAT"}, .originalDefender{"ODF"}}), *Mappers::CountryMapper::Builder().addMapping("ODF", "NDF").Build(), Mappers::CasusBellis({}), Mappers::ProvinceMapper{}, std::map<int, int>{}); std::cout.rdbuf(stdOutBuf); ASSERT_EQ(" [WARNING] Could not map OAT, original attacker in a war\n", log.str()); } TEST(HoI4World_Diplomacy_WarTests, TargetStateCanBeSet) { const HoI4::War war(Vic2::War({.province = 42}), *Mappers::CountryMapper::Builder().Build(), Mappers::CasusBellis({}), *Mappers::ProvinceMapper::Builder{}.addVic2ToHoI4ProvinceMap(42, {84}).Build(), std::map<int, int>{{84, 3}}); std::stringstream output; output << war; std::stringstream expectedOutput; expectedOutput << "declare_war_on = {\n"; expectedOutput << "\ttarget = \n"; expectedOutput << "\ttype = topple_government\n"; expectedOutput << "\tgenerator = { 3 }\n"; expectedOutput << "}\n"; expectedOutput << "\n"; ASSERT_EQ(expectedOutput.str(), output.str()); }
29.402685
104
0.681123
gawquon
55ec3815bfbac09f5c488feb8a4071b06ee75204
191
cpp
C++
src/LevelSetSeg.cpp
Bas94/SegmentationMethodsForMedicalImageAnalysis
c14514e76ca89eb6fc08374177809518d7762d64
[ "MIT" ]
1
2020-12-14T07:52:10.000Z
2020-12-14T07:52:10.000Z
src/LevelSetSeg.cpp
Bas94/SegmentationMethodsForMedicalImageAnalysis
c14514e76ca89eb6fc08374177809518d7762d64
[ "MIT" ]
10
2017-10-18T14:27:29.000Z
2017-11-29T15:18:30.000Z
src/LevelSetSeg.cpp
Bas94/SegmentationMethodsForMedicalImageAnalysis
c14514e76ca89eb6fc08374177809518d7762d64
[ "MIT" ]
null
null
null
#include "LevelSetSeg.h" #include "itkGeodesicActiveContourLevelSetImageFilter.h" #include "itkSigmoidImageFilter.h" #include "itkBinaryThresholdImageFilter.h" namespace LevelSetSeg { }
17.363636
56
0.816754
Bas94
55ee723a422e0db480a58c922697178bd51523bb
970
cpp
C++
atcoder/others/code_festival/2017/final/a.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
atcoder/others/code_festival/2017/final/a.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
atcoder/others/code_festival/2017/final/a.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using pii = pair<int, int>; #define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i) #define all(x) (x).begin(),(x).end() #define m0(x) memset(x,0,sizeof(x)) int dx4[4] = {1,0,-1,0}, dy4[4] = {0,1,0,-1}; int main() { string s; string a ="AKIHABARA"; cin>>s; int n=s.size(); bool ok=true; if(n>9) { ok=false; } else { int ap=0; int sp=0; while (sp<n && ap<9) { if(s[sp]==a[ap]) { ap++; sp++; } else if(a[ap]=='A') { ap++; } else { ok=false; break; } } if(sp<n) ok=false; if(ap<8) ok=false; } if(ok) cout<<"YES"<<endl; else cout<<"NO"<<endl; return 0; }
18.301887
58
0.380412
yu3mars
55ef18a71e9fbb2aadafc4d81253e75721ea77d6
6,460
cpp
C++
Source/Memory.cpp
EzraIII/witness-randomizer
8f3973faf182edc90c88a9e76b8bf3cf158819cf
[ "MIT" ]
null
null
null
Source/Memory.cpp
EzraIII/witness-randomizer
8f3973faf182edc90c88a9e76b8bf3cf158819cf
[ "MIT" ]
null
null
null
Source/Memory.cpp
EzraIII/witness-randomizer
8f3973faf182edc90c88a9e76b8bf3cf158819cf
[ "MIT" ]
null
null
null
#include "Memory.h" #include <psapi.h> #include <tlhelp32.h> #include <iostream> #include <string> #include <cassert> #undef PROCESSENTRY32 #undef Process32Next Memory::Memory(const std::wstring& processName) : _processName(processName) {} Memory::~Memory() { if (_threadActive) { _threadActive = false; _thread.join(); } if (_handle != nullptr) { for (uintptr_t addr : _allocations) VirtualFreeEx(_handle, (void*)addr, 0, MEM_RELEASE); CloseHandle(_handle); } } void Memory::StartHeartbeat(HWND window, std::chrono::milliseconds beat) { if (_threadActive) return; _threadActive = true; _thread = std::thread([sharedThis = shared_from_this(), window, beat]{ while (sharedThis->_threadActive) { sharedThis->Heartbeat(window); std::this_thread::sleep_for(beat); } }); _thread.detach(); } void Memory::Heartbeat(HWND window) { if (!_handle && !Initialize()) { // Couldn't initialize, definitely not running PostMessage(window, WM_COMMAND, HEARTBEAT, (LPARAM)ProcStatus::NotRunning); return; } DWORD exitCode = 0; assert(_handle); GetExitCodeProcess(_handle, &exitCode); if (exitCode != STILL_ACTIVE) { // Process has exited, clean up. _computedAddresses.clear(); _handle = NULL; PostMessage(window, WM_COMMAND, HEARTBEAT, (LPARAM)ProcStatus::NotRunning); return; } #if GLOBALS == 0x5B28C0 int currentFrame = ReadData<int>({0x5BE3B0}, 1)[0]; #elif GLOBALS == 0x62D0A0 int currentFrame = ReadData<int>({0x63954C}, 1)[0]; #endif int frameDelta = currentFrame - _previousFrame; _previousFrame = currentFrame; if (frameDelta < 0 && currentFrame < 250) { // Some addresses (e.g. Entity Manager) may get re-allocated on newgame. _computedAddresses.clear(); PostMessage(window, WM_COMMAND, HEARTBEAT, (LPARAM)ProcStatus::NewGame); return; } // TODO: Some way to return ProcStatus::Randomized vs ProcStatus::NotRandomized vs ProcStatus::DeRandomized; PostMessage(window, WM_COMMAND, HEARTBEAT, (LPARAM)ProcStatus::Running); } [[nodiscard]] bool Memory::Initialize() { // First, get the handle of the process PROCESSENTRY32W entry; entry.dwSize = sizeof(entry); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); while (Process32NextW(snapshot, &entry)) { if (_processName == entry.szExeFile) { _handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID); break; } } if (!_handle) { std::cerr << "Couldn't find " << _processName.c_str() << ", is it open?" << std::endl; return false; } // Next, get the process base address DWORD numModules; std::vector<HMODULE> moduleList(1024); EnumProcessModulesEx(_handle, &moduleList[0], static_cast<DWORD>(moduleList.size()), &numModules, 3); std::wstring name(64, '\0'); for (DWORD i = 0; i < numModules / sizeof(HMODULE); i++) { int length = GetModuleBaseNameW(_handle, moduleList[i], &name[0], static_cast<DWORD>(name.size())); name.resize(length); if (_processName == name) { _baseAddress = (uintptr_t)moduleList[i]; break; } } if (_baseAddress == 0) { std::cerr << "Couldn't locate base address" << std::endl; return false; } return true; } void Memory::AddSigScan(const std::vector<byte>& scanBytes, const std::function<void(int index)>& scanFunc) { _sigScans[scanBytes] = {scanFunc, false}; } int find(const std::vector<byte> &data, const std::vector<byte>& search, size_t startIndex = 0) { for (size_t i=startIndex; i<data.size() - search.size(); i++) { bool match = true; for (size_t j=0; j<search.size(); j++) { if (data[i+j] == search[j]) { continue; } match = false; break; } if (match) return static_cast<int>(i); } return -1; } int Memory::ExecuteSigScans() { for (int i=0; i<0x200000; i+=0x1000) { std::vector<byte> data = ReadData<byte>({i}, 0x1100); for (auto& [scanBytes, sigScan] : _sigScans) { if (sigScan.found) continue; int index = find(data, scanBytes); if (index == -1) continue; sigScan.scanFunc(i + index); sigScan.found = true; } } int notFound = 0; for (auto it : _sigScans) { if (it.second.found == false) notFound++; } return notFound; } void Memory::ThrowError() { std::wstring message(256, '\0'); DWORD error = GetLastError(); int length = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, nullptr, error, 1024, &message[0], static_cast<DWORD>(message.size()), nullptr); message.resize(length); #ifndef NDEBUG MessageBox(NULL, message.c_str(), L"Please tell darkid about this", MB_OK); #endif } void* Memory::ComputeOffset(std::vector<int> offsets) { // Leave off the last offset, since it will be either read/write, and may not be of type uintptr_t. int final_offset = offsets.back(); offsets.pop_back(); uintptr_t cumulativeAddress = _baseAddress; for (const int offset : offsets) { cumulativeAddress += offset; const auto search = _computedAddresses.find(cumulativeAddress); // This is an issue with re-randomization. Always. Just disable it in debug mode! #ifdef NDEBUG if (search == std::end(_computedAddresses)) { #endif // If the address is not yet computed, then compute it. uintptr_t computedAddress = 0; if (bool result = !ReadProcessMemory(_handle, reinterpret_cast<LPVOID>(cumulativeAddress), &computedAddress, sizeof(uintptr_t), NULL)) { ThrowError(); } if (computedAddress == 0) { // Attempting to dereference a nullptr ThrowError(); } _computedAddresses[cumulativeAddress] = computedAddress; #ifdef NDEBUG } #endif cumulativeAddress = _computedAddresses[cumulativeAddress]; } return reinterpret_cast<void*>(cumulativeAddress + final_offset); }
33.128205
149
0.606811
EzraIII
55f0ac2acb4d8bb638cdcbb11613c91d8837daae
328
cpp
C++
lib/qos/qos_one_handler.cpp
pmqtt/pmq
49f4b87c6c6dc5adfe7feab4ef3b2b73e0c435fb
[ "Apache-2.0" ]
2
2019-09-08T11:59:05.000Z
2019-12-04T09:29:43.000Z
lib/qos/qos_one_handler.cpp
pmqtt/pmq
49f4b87c6c6dc5adfe7feab4ef3b2b73e0c435fb
[ "Apache-2.0" ]
11
2019-06-08T20:13:58.000Z
2019-12-17T12:03:01.000Z
lib/qos/qos_one_handler.cpp
pmqtt/pmq
49f4b87c6c6dc5adfe7feab4ef3b2b73e0c435fb
[ "Apache-2.0" ]
2
2019-12-04T08:06:27.000Z
2021-06-03T21:24:40.000Z
// // Created by pmqtt on 2019-07-06. // #include <lib/mqtt/mqtt_static_package.hpp> #include "qos_one_handler.hpp" void pmq::qos_one_handler::handle(std::shared_ptr<pmq::storage> & storage,pmq::mqtt_publish *msg) { auto socket = msg->get_socket(); pmq::mqtt_puback ack(socket); ack.send(msg->get_message_id()); }
25.230769
99
0.704268
pmqtt
55f24d1462553c75a09cc9f8dfa2e3082db86827
596
cpp
C++
labs/3/lab2/CodeFromLab/PlanetStruct.cpp
triffon/oop-2019-20
db199631d59ddefdcc0c8eb3d689de0095618f92
[ "MIT" ]
19
2020-02-21T16:46:50.000Z
2022-01-26T19:59:49.000Z
labs/3/lab2/CodeFromLab/PlanetStruct.cpp
triffon/oop-2019-20
db199631d59ddefdcc0c8eb3d689de0095618f92
[ "MIT" ]
1
2020-03-14T08:09:45.000Z
2020-03-14T08:09:45.000Z
labs/3/lab2/CodeFromLab/PlanetStruct.cpp
triffon/oop-2019-20
db199631d59ddefdcc0c8eb3d689de0095618f92
[ "MIT" ]
11
2020-02-23T12:29:58.000Z
2021-04-11T08:30:12.000Z
#include "PlanetStruct.h" #include <string.h> #include <iostream> PlanetStruct getPlanet(const char *name, unsigned long long dist, unsigned long long diam, unsigned long long mass) { PlanetStruct result; strcpy(result.name, name); result.distance = dist; result.diameter = diam; result.mass = mass; return result; } void printPlanet(PlanetStruct p) { std::cout << p.name << " " << p.distance << " " << p.diameter << " " << p.mass << std::endl; }
22.923077
42
0.525168
triffon
55f49bfdd43d444243420011315fb771d9d44c87
492
cpp
C++
LeetCode/C++/58. Length of Last Word.cpp
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-18T05:14:28.000Z
2022-03-08T07:00:08.000Z
LeetCode/C++/58. Length of Last Word.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
LeetCode/C++/58. Length of Last Word.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
//Runtime: 4 ms, faster than 92.11% of C++ online submissions for Length of Last Word. //Memory Usage: 6.4 MB, less than 92.88% of C++ online submissions for Length of Last Word. class Solution { public: int lengthOfLastWord(string s) { int ans = 0; int n = s.size(); int i = n-1; while(i >= 0 && s[i] == ' ') --i; for(; (i >= 0) && (s[i] != ' '); --i){ ++ans; } return ans; } };
24.6
91
0.45935
shreejitverma
55f92b7b8fe7e0c134cc7035905d65c5d8cbdc73
1,158
cc
C++
lib/src/test_connection_parameters.cc
MikaelSmith/pcp-test
7f830e0dc0d7128a5db3c660503f719cf80a5345
[ "Apache-2.0" ]
null
null
null
lib/src/test_connection_parameters.cc
MikaelSmith/pcp-test
7f830e0dc0d7128a5db3c660503f719cf80a5345
[ "Apache-2.0" ]
1
2016-09-09T10:56:21.000Z
2016-09-09T13:43:24.000Z
lib/src/test_connection_parameters.cc
MikaelSmith/pcp-test
7f830e0dc0d7128a5db3c660503f719cf80a5345
[ "Apache-2.0" ]
4
2016-08-25T10:18:46.000Z
2021-03-26T11:47:21.000Z
#include <pcp-test/test_connection_parameters.hpp> namespace pcp_test{ namespace connection_test_parameters { const std::string NUM_RUNS {"num-runs"}; const std::string INTER_RUN_PAUSE_MS {"inter-run-pause-ms"}; const std::string NUM_ENDPOINTS {"num-endpoints"}; const std::string INTER_ENDPOINT_PAUSE_MS {"inter-endpoint-pause-ms"}; const std::string CONCURRENCY {"concurrency"}; const std::string ENDPOINTS_INCREMENT {"endpoints-increment"}; const std::string CONCURRENCY_INCREMENT {"concurrency-increment"}; const std::string RANDOMIZE_INTER_ENDPOINT_PAUSE {"randomize-inter-endpoint-pause"}; const std::string INTER_ENDPOINT_PAUSE_RNG_SEED {"inter-endpoint-pause-rng-seed"}; const std::string WS_CONNECTION_TIMEOUT_MS {"ws-connection-timeout-ms"}; const std::string WS_CONNECTION_CHECK_INTERVAL_S {"ws-connection-check-interval-s"}; const std::string ASSOCIATION_TIMEOUT_S {"association-timeout-s"}; const std::string ASSOCIATION_REQUEST_TTL_S {"association-request-ttl-s"}; const std::string PERSIST_CONNECTIONS {"persist-connections"}; const std::string SHOW_STATS {"show-stats"}; } // namespace connection_test_parameters } // namespace pcp_test
48.25
84
0.801382
MikaelSmith
55f9445367efcad1e4fab55eb10bbb687ea4f603
26,477
cpp
C++
asteria/src/library/filesystem.cpp
usama-makhzoum/asteria
ea4c893a038e0c5bef14d4d9f6723124a0cbb30f
[ "BSD-3-Clause" ]
null
null
null
asteria/src/library/filesystem.cpp
usama-makhzoum/asteria
ea4c893a038e0c5bef14d4d9f6723124a0cbb30f
[ "BSD-3-Clause" ]
null
null
null
asteria/src/library/filesystem.cpp
usama-makhzoum/asteria
ea4c893a038e0c5bef14d4d9f6723124a0cbb30f
[ "BSD-3-Clause" ]
null
null
null
// This file is part of Asteria. // Copyleft 2018 - 2021, LH_Mouse. All wrongs reserved. #include "../precompiled.hpp" #include "filesystem.hpp" #include "../runtime/argument_reader.hpp" #include "../runtime/global_context.hpp" #include "../llds/reference_stack.hpp" #include "../utils.hpp" #include <sys/stat.h> // ::stat(), ::fstat(), ::lstat(), ::mkdir(), ::fchmod() #include <dirent.h> // ::opendir(), ::closedir() #include <fcntl.h> // ::open() #include <stdio.h> // ::rename() #include <errno.h> // errno namespace asteria { namespace { enum RM_Disp { rm_disp_rmdir, // a subdirectory which should be empty and can be removed rm_disp_unlink, // a plain file to be unlinked rm_disp_expand, // a subdirectory to be expanded }; struct RM_Element { RM_Disp disp; V_string path; }; int64_t do_remove_recursive(const char* path) { // Push the first element. cow_vector<RM_Element> stack; stack.push_back({ rm_disp_expand, sref(path) }); // Expand non-empty directories and remove all contents. int64_t nremoved = 0; while(stack.size()) { auto elem = ::std::move(stack.mut_back()); stack.pop_back(); // Process this element. switch(elem.disp) { case rm_disp_rmdir: { // This is an empty directory. Remove it. if(::rmdir(elem.path.c_str()) == 0) { nremoved++; break; } // Hmm... avoid TOCTTOU errors. if(errno == ENOENT) break; ASTERIA_THROW("Could not remove directory '$2'\n" "[`rmdir()` failed: $1]", format_errno(errno), elem.path); } case rm_disp_unlink: { // This is a non-directory. Unlink it. if(::unlink(elem.path.c_str()) == 0) { nremoved++; break; } // Hmm... avoid TOCTTOU errors. if(errno == ENOENT) break; ASTERIA_THROW("Could not remove file '$2'\n" "[`unlink()` failed: $1]", format_errno(errno), elem.path); } case rm_disp_expand: { // This is a subdirectory that has not been expanded. // Push the directory itself. // Since elements are maintained in LIFO order, only when this element is encountered // for a second time, will all of its children have been removed. stack.push_back({ rm_disp_rmdir, elem.path }); // Open the directory for listing. ::rocket::unique_posix_dir dp(::opendir(elem.path.c_str()), ::closedir); if(!dp) ASTERIA_THROW("Could not open directory '$2'\n" "[`opendir()` failed: $1]", format_errno(errno), elem.path); // Append all entries. while(auto next = ::readdir(dp)) { // Skip special entries. if(::strcmp(next->d_name, ".") == 0) continue; if(::strcmp(next->d_name, "..") == 0) continue; // Get the name and type of this entry. cow_string child = elem.path + '/' + next->d_name; bool is_dir = false; #ifdef _DIRENT_HAVE_D_TYPE if(next->d_type != DT_UNKNOWN) { // Get the file type if it is available immediately. is_dir = next->d_type == DT_DIR; } else #endif { // If the file type is unknown, ask for it. struct ::stat stb; if(::lstat(child.c_str(), &stb) != 0) ASTERIA_THROW("Could not get information about '$2'\n" "[`lstat()` failed: $1]", format_errno(errno), child); // Check whether the child path denotes a directory. is_dir = S_ISDIR(stb.st_mode); } // Append this entry. stack.push_back({ is_dir ? rm_disp_expand : rm_disp_unlink, ::std::move(child) }); } break; } default: ROCKET_ASSERT(false); } } return nremoved; } const void* do_write_loop(int fd, const void* data, size_t size, const V_string& path) { auto bp = static_cast<const char*>(data); auto ep = bp + size; while(bp < ep) { ::ssize_t nwrtn = ::write(fd, bp, static_cast<size_t>(ep - bp)); if(nwrtn < 0) { ASTERIA_THROW("Error writing file '$2'\n" "[`write()` failed: $1]", format_errno(errno), path); } bp += nwrtn; } return bp; } } // namespace V_string std_filesystem_get_working_directory() { // Pass a null pointer to request dynamic allocation. // Note this behavior is an extension that exists almost everywhere. auto qcwd = ::rocket::make_unique_handle(::getcwd(nullptr, 0), ::free); if(!qcwd) { ASTERIA_THROW("Could not get current working directory\n" "[`getcwd()` failed: $1]", format_errno(errno)); } return V_string(qcwd); } V_string std_filesystem_get_real_path(V_string path) { // Pass a null pointer to request dynamic allocation. auto abspath = ::rocket::make_unique_handle(::realpath(path.safe_c_str(), nullptr), ::free); if(!abspath) { ASTERIA_THROW("Could not resolve path '$2'\n" "[`realpath()` failed: $1]", format_errno(errno), path); } return V_string(abspath); } Opt_object std_filesystem_get_information(V_string path) { struct ::stat stb; if(::lstat(path.safe_c_str(), &stb) != 0) return nullopt; // Convert the result to an `object`. V_object stat; stat.try_emplace(sref("i_dev"), V_integer( stb.st_dev // unique device id on this machine )); stat.try_emplace(sref("i_file"), V_integer( stb.st_ino // unique file id on this device )); stat.try_emplace(sref("n_ref"), V_integer( stb.st_nlink // number of hard links to this file )); stat.try_emplace(sref("b_dir"), V_boolean( S_ISDIR(stb.st_mode) // whether this is a directory )); stat.try_emplace(sref("b_sym"), V_boolean( S_ISLNK(stb.st_mode) // whether this is a symbolic link )); stat.try_emplace(sref("n_size"), V_integer( stb.st_size // number of bytes this file contains )); stat.try_emplace(sref("n_ocup"), V_integer( int64_t(stb.st_blocks) * 512 // number of bytes this file occupies )); stat.try_emplace(sref("t_accs"), V_integer( int64_t(stb.st_atim.tv_sec) * 1000 + stb.st_atim.tv_nsec / 1000000 // timestamp of last access )); stat.try_emplace(sref("t_mod"), V_integer( int64_t(stb.st_mtim.tv_sec) * 1000 + stb.st_mtim.tv_nsec / 1000000 // timestamp of last modification )); return ::std::move(stat); } void std_filesystem_move_from(V_string path_new, V_string path_old) { if(::rename(path_old.safe_c_str(), path_new.safe_c_str()) != 0) ASTERIA_THROW("Could not move file '$2' to '$3'\n" "[`rename()` failed: $1]", format_errno(errno), path_old, path_new); } V_integer std_filesystem_remove_recursive(V_string path) { // Try removing an empty directory if(::rmdir(path.safe_c_str()) == 0) return 1; // Get some detailed information from `errno`. switch(errno) { case ENOENT: // The path does not exist. return 0; case ENOTDIR: { // This is something not a directory. if(::unlink(path.safe_c_str()) == 0) return 1; // Hmm... avoid TOCTTOU errors. if(errno == ENOENT) return 0; ASTERIA_THROW("Could not remove file '$2'\n" "[`unlink()` failed: $1]", format_errno(errno), path); } case EEXIST: case ENOTEMPTY: // Remove contents first. return do_remove_recursive(path.safe_c_str()); } // Throw an exception for general failures. ASTERIA_THROW("Could not remove directory '$2'\n" "[`rmdir()` failed: $1]", format_errno(errno), path); } V_object std_filesystem_dir_list(V_string path) { // Try opening t he directory. ::rocket::unique_posix_dir dp(::opendir(path.safe_c_str()), ::closedir); if(!dp) ASTERIA_THROW("Could not open directory '$2'\n" "[`opendir()` failed: $1]", format_errno(errno), path); // Append all entries. V_object entries; while(auto next = ::readdir(dp)) { // Skip special entries. if(::strcmp(next->d_name, ".") == 0) continue; if(::strcmp(next->d_name, "..") == 0) continue; // Compose the full path of the child. cow_string child = path + '/' + next->d_name; bool is_dir = false; bool is_sym = false; #ifdef _DIRENT_HAVE_D_TYPE if(next->d_type != DT_UNKNOWN) { // Get the file type if it is available immediately. is_dir = next->d_type == DT_DIR; is_sym = next->d_type == DT_LNK; } else #endif { // If the file type is unknown, ask for it. struct ::stat stb; if(::lstat(child.c_str(), &stb) != 0) ASTERIA_THROW("Could not get information about '$2'\n" "[`lstat()` failed: $1]", format_errno(errno), child); // Check whether the child path denotes a directory. is_dir = S_ISDIR(stb.st_mode); is_sym = S_ISLNK(stb.st_mode); } // Append this entry, assuming the name is in UTF-8. V_object entry; entry.try_emplace(sref("b_dir"), V_boolean( is_dir )); entry.try_emplace(sref("b_sym"), V_boolean( is_sym )); entries.try_emplace(cow_string(next->d_name), ::std::move(entry)); } return entries; } V_integer std_filesystem_dir_create(V_string path) { // Try creating an empty directory. if(::mkdir(path.safe_c_str(), 0777) == 0) return 1; // If the path references a directory or a symlink to a directory, don't fail. if(errno == EEXIST) { struct ::stat stb; if(::stat(path.c_str(), &stb) != 0) ASTERIA_THROW("Could not get information about '$2'\n" "[`stat()` failed: $1]", format_errno(errno), path); if(S_ISDIR(stb.st_mode)) return 0; // Throw an exception about the previous error. ASTERIA_THROW("Could not create directory '$2'\n" "[`mkdir()` failed: $1]", format_errno(EEXIST), path); } // Throw an exception for general failures. ASTERIA_THROW("Could not create directory '$2'\n" "[`mkdir()` failed: $1]", format_errno(errno), path); } V_integer std_filesystem_dir_remove(V_string path) { // Try removing an empty directory. if(::rmdir(path.safe_c_str()) == 0) return 1; // If the path does not exist, don't fail. if(errno == ENOENT) return 0; // Throw an exception for general failures. ASTERIA_THROW("Could remove directory '$2'\n" "[`rmdir()` failed: $1]", format_errno(errno), path); } V_string std_filesystem_file_read(V_string path, Opt_integer offset, Opt_integer limit) { if(offset && (*offset < 0)) ASTERIA_THROW("Negative file offset (offset `$1`)", *offset); // Open the file for reading. ::rocket::unique_posix_fd fd(::open(path.safe_c_str(), O_RDONLY), ::close); if(!fd) ASTERIA_THROW("Could not open file '$2'\n" "[`open()` failed: $1]", format_errno(errno), path); // We return data that have been read as a byte string. V_string data; int64_t roffset = offset.value_or(0); int64_t rlimit = limit.value_or(INT64_MAX); for(;;) { // Don't read too many bytes at a time. if(rlimit <= 0) break; ::ssize_t nread; size_t nbatch = static_cast<size_t>(::rocket::min(rlimit, 0x100000)); auto insert_pos = data.insert(data.end(), nbatch, '/'); if(offset) { // Use `roffset`. The file must be seekable in this case. nread = ::pread(fd, &*insert_pos, nbatch, roffset); if(nread < 0) ASTERIA_THROW("Error reading file '$2'\n" "[`pread()` failed: $1]", format_errno(errno), path); } else { // Use the internal file pointer. nread = ::read(fd, &*insert_pos, nbatch); if(nread < 0) ASTERIA_THROW("Error reading file '$2'\n" "[`read()` failed: $1]", format_errno(errno), path); } data.erase(insert_pos + nread, data.end()); roffset += nread; rlimit -= nread; // Check for end of file. if(nread == 0) break; } return data; } V_integer std_filesystem_file_stream(Global_Context& global, V_string path, V_function callback, Opt_integer offset, Opt_integer limit) { if(offset && (*offset < 0)) ASTERIA_THROW("Negative file offset (offset `$1`)", *offset); // Open the file for reading. ::rocket::unique_posix_fd fd(::open(path.safe_c_str(), O_RDONLY), ::close); if(!fd) ASTERIA_THROW("Could not open file '$2'\n" "[`open()` failed: $1]", format_errno(errno), path); // We return data that have been read as a byte string. Reference self; Reference_Stack stack; V_string data; int64_t roffset = offset.value_or(0); int64_t rlimit = limit.value_or(INT64_MAX); for(;;) { // Don't read too many bytes at a time. if(rlimit <= 0) break; ::ssize_t nread; size_t nbatch = static_cast<size_t>(::rocket::min(rlimit, 0x100000)); data.resize(nbatch, '/'); if(offset) { // Use `roffset`. The file must be seekable in this case. nread = ::pread(fd, data.mut_data(), nbatch, roffset); if(nread < 0) ASTERIA_THROW("Error reading file '$2'\n" "[`pread()` failed: $1]", format_errno(errno), path); } else { // Use the internal file pointer. nread = ::read(fd, data.mut_data(), nbatch); if(nread < 0) ASTERIA_THROW("Error reading file '$2'\n" "[`read()` failed: $1]", format_errno(errno), path); } data.erase(data.begin() + nread, data.end()); roffset += nread; rlimit -= nread; // Check for end of file. if(nread == 0) break; // Call the function but discard its return value. stack.clear(); stack.emplace_back_uninit().set_temporary(roffset); stack.emplace_back_uninit().set_temporary(::std::move(data)); self.set_temporary(nullopt); callback.invoke(self, global, ::std::move(stack)); } return roffset - offset.value_or(0); } void std_filesystem_file_write(V_string path, Opt_integer offset, V_string data) { if(offset && (*offset < 0)) ASTERIA_THROW("Negative file offset (offset `$1`)", *offset); // Calculate the `flags` argument. int flags = O_WRONLY | O_CREAT | O_APPEND; // If we are to write from the beginning, truncate the file at creation. int64_t roffset = offset.value_or(0); if(roffset == 0) flags |= O_TRUNC; // Open the file for writing. ::rocket::unique_posix_fd fd(::open(path.safe_c_str(), flags, 0666), ::close); if(!fd) ASTERIA_THROW("Could not open file '$2'\n" "[`open()` failed: $1]", format_errno(errno), path); // Set the file pointer when an offset is specified, even when it is an explicit // zero. This ensures that the file is actually seekable (not a pipe or socket // whatsoever). if(offset && (::ftruncate(fd, roffset) != 0)) ASTERIA_THROW("Could not truncate file '$2'\n" "[`ftruncate()` failed: $1]", format_errno(errno), path); // Write all data. do_write_loop(fd, data.data(), data.size(), path); } void std_filesystem_file_append(V_string path, V_string data, Opt_boolean exclusive) { // Calculate the `flags` argument. int flags = O_WRONLY | O_CREAT | O_APPEND; // Treat `exclusive` as `false` if it is not specified at all. if(exclusive == true) flags |= O_EXCL; // Open the file for appending. ::rocket::unique_posix_fd fd(::open(path.safe_c_str(), flags, 0666), ::close); if(!fd) ASTERIA_THROW("Could not open file '$2'\n" "[`open()` failed: $1]", format_errno(errno), path); // Append all data to the end. do_write_loop(fd, data.data(), data.size(), path); } void std_filesystem_file_copy_from(V_string path_new, V_string path_old) { // Open the old file. ::rocket::unique_posix_fd fd_old(::open(path_old.safe_c_str(), O_RDONLY), ::close); if(!fd_old) ASTERIA_THROW("Could not open source file '$2'\n" "[`open()` failed: $1]", format_errno(errno), path_old); // Create the new file, discarding its contents. // The file is initially write-only. ::rocket::unique_posix_fd fd_new(::open(path_new.safe_c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_APPEND, 0200), ::close); if(!fd_new) ASTERIA_THROW("Could not create destination file '$2'\n" "[`open()` failed: $1]", format_errno(errno), path_new); // Get the file mode and preferred I/O block size. struct ::stat stb_old; if(::fstat(fd_old, &stb_old) != 0) ASTERIA_THROW("Could not get information about source file '$2'\n" "[`fstat()` failed: $1]", format_errno(errno), path_old); // Allocate the I/O buffer. size_t nbuf = static_cast<size_t>(stb_old.st_blksize | 0x1000); auto pbuf = ::rocket::make_unique_handle(new char[nbuf], [](char* p) { delete[] p; }); // Copy all contents. for(;;) { ::ssize_t nread = ::read(fd_old, pbuf, nbuf); if(nread < 0) ASTERIA_THROW("Error reading file '$2'\n" "[`read()` failed: $1]", format_errno(errno), path_old); if(nread == 0) break; // Append all data to the end. do_write_loop(fd_new, pbuf, static_cast<size_t>(nread), path_new); } // Set the file mode. This must be the last operation. if(::fchmod(fd_new, stb_old.st_mode) != 0) ASTERIA_THROW("Could not set permission of '$2'\n" "[`fchmod()` failed: $1]", format_errno(errno), path_new); } V_integer std_filesystem_file_remove(V_string path) { // Try removing a non-directory. if(::unlink(path.safe_c_str()) == 0) return 1; // If the path does not exist, don't fail. if(errno == ENOENT) return 0; // Throw an exception for general failures. ASTERIA_THROW("Could not remove file '$2'\n" "[`unlink()` failed: $1]", format_errno(errno), path); } void create_bindings_filesystem(V_object& result, API_Version /*version*/) { result.insert_or_assign(sref("get_working_directory"), ASTERIA_BINDING_BEGIN("std.filesystem.get_working_directory", self, global, reader) { reader.start_overload(); if(reader.end_overload()) ASTERIA_BINDING_RETURN_MOVE(self, std_filesystem_get_working_directory); } ASTERIA_BINDING_END); result.insert_or_assign(sref("get_real_path"), ASTERIA_BINDING_BEGIN("std.filesystem.get_real_path", self, global, reader) { V_string path; reader.start_overload(); reader.required(path); // path if(reader.end_overload()) ASTERIA_BINDING_RETURN_MOVE(self, std_filesystem_get_real_path, path); } ASTERIA_BINDING_END); result.insert_or_assign(sref("get_information"), ASTERIA_BINDING_BEGIN("std.filesystem.get_information", self, global, reader) { V_string path; reader.start_overload(); reader.required(path); // path if(reader.end_overload()) ASTERIA_BINDING_RETURN_MOVE(self, std_filesystem_get_information, path); } ASTERIA_BINDING_END); result.insert_or_assign(sref("remove_recursive"), ASTERIA_BINDING_BEGIN("std.filesystem.remove_recursive", self, global, reader) { V_string path; reader.start_overload(); reader.required(path); // path if(reader.end_overload()) ASTERIA_BINDING_RETURN_MOVE(self, std_filesystem_remove_recursive, path); } ASTERIA_BINDING_END); result.insert_or_assign(sref("move_from"), ASTERIA_BINDING_BEGIN("std.filesystem.move_from", self, global, reader) { V_string to; V_string from; reader.start_overload(); reader.required(to); // path_new reader.required(from); // path_old if(reader.end_overload()) ASTERIA_BINDING_RETURN_MOVE(self, std_filesystem_move_from, to, from); } ASTERIA_BINDING_END); result.insert_or_assign(sref("dir_list"), ASTERIA_BINDING_BEGIN("std.filesystem.dir_list", self, global, reader) { V_string path; reader.start_overload(); reader.required(path); // path if(reader.end_overload()) ASTERIA_BINDING_RETURN_MOVE(self, std_filesystem_dir_list, path); } ASTERIA_BINDING_END); result.insert_or_assign(sref("dir_create"), ASTERIA_BINDING_BEGIN("std.filesystem.dir_create", self, global, reader) { V_string path; reader.start_overload(); reader.required(path); // path if(reader.end_overload()) ASTERIA_BINDING_RETURN_MOVE(self, std_filesystem_dir_create, path); } ASTERIA_BINDING_END); result.insert_or_assign(sref("dir_remove"), ASTERIA_BINDING_BEGIN("std.filesystem.dir_remove", self, global, reader) { V_string path; reader.start_overload(); reader.required(path); // path if(reader.end_overload()) ASTERIA_BINDING_RETURN_MOVE(self, std_filesystem_dir_remove, path); } ASTERIA_BINDING_END); result.insert_or_assign(sref("file_read"), ASTERIA_BINDING_BEGIN("std.filesystem.file_read", self, global, reader) { V_string path; Opt_integer off; Opt_integer lim; reader.start_overload(); reader.required(path); // path reader.optional(off); // [offset] reader.optional(lim); // [limit] if(reader.end_overload()) ASTERIA_BINDING_RETURN_MOVE(self, std_filesystem_file_read, path, off, lim); } ASTERIA_BINDING_END); result.insert_or_assign(sref("file_stream"), ASTERIA_BINDING_BEGIN("std.filesystem.file_stream", self, global, reader) { V_string path; V_function func; Opt_integer off; Opt_integer lim; reader.start_overload(); reader.required(path); // path reader.required(func); // callback reader.optional(off); // [offset] reader.optional(lim); // [limit] if(reader.end_overload()) ASTERIA_BINDING_RETURN_MOVE(self, std_filesystem_file_stream, global, path, func, off, lim); } ASTERIA_BINDING_END); result.insert_or_assign(sref("file_write"), ASTERIA_BINDING_BEGIN("std.filesystem.file_write", self, global, reader) { V_string path; Opt_integer off; V_string data; reader.start_overload(); reader.required(path); // path reader.save_state(0); reader.required(data); // data if(reader.end_overload()) ASTERIA_BINDING_RETURN_MOVE(self, std_filesystem_file_write, path, nullopt, data); reader.load_state(0); // path reader.optional(off); // [offset] reader.required(data); // data if(reader.end_overload()) ASTERIA_BINDING_RETURN_MOVE(self, std_filesystem_file_write, path, off, data); } ASTERIA_BINDING_END); result.insert_or_assign(sref("file_append"), ASTERIA_BINDING_BEGIN("std.filesystem.file_append", self, global, reader) { V_string path; V_string data; Opt_boolean excl; reader.start_overload(); reader.required(path); // path reader.required(data); // data reader.optional(excl); // [exclusive] if(reader.end_overload()) ASTERIA_BINDING_RETURN_MOVE(self, std_filesystem_file_append, path, data, excl); } ASTERIA_BINDING_END); result.insert_or_assign(sref("file_copy_from"), ASTERIA_BINDING_BEGIN("std.filesystem.file_copy_from", self, global, reader) { V_string to; V_string from; reader.start_overload(); reader.required(to); // path_new reader.required(from); // path_old if(reader.end_overload()) ASTERIA_BINDING_RETURN_MOVE(self, std_filesystem_file_copy_from, to, from); } ASTERIA_BINDING_END); result.insert_or_assign(sref("file_remove"), ASTERIA_BINDING_BEGIN("std.filesystem.file_remove", self, global, reader) { V_string path; reader.start_overload(); reader.required(path); // path if(reader.end_overload()) ASTERIA_BINDING_RETURN_MOVE(self, std_filesystem_file_remove, path); } ASTERIA_BINDING_END); } } // namespace asteria
31.823317
96
0.573252
usama-makhzoum
55fb962e26ea473cdcfb19eec98b40f639cd3a49
1,223
hpp
C++
Dev/stringbuilder.hpp
Joseph-Heetel/StringCppTemplateLib_Dev
dd9a9a3e4b23f4af21c7dda1e5423c66362885bc
[ "MIT" ]
null
null
null
Dev/stringbuilder.hpp
Joseph-Heetel/StringCppTemplateLib_Dev
dd9a9a3e4b23f4af21c7dda1e5423c66362885bc
[ "MIT" ]
null
null
null
Dev/stringbuilder.hpp
Joseph-Heetel/StringCppTemplateLib_Dev
dd9a9a3e4b23f4af21c7dda1e5423c66362885bc
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include "string.hpp" namespace jht { /// @brief Provides functionality to conveniently and efficiently chain strings together class StringBuilder { private: static const size_t BUFFERSIZE = 128; static const size_t SINGLETHRESHHOLD = BUFFERSIZE / 4; std::vector<String> m_Sections; size_t m_Length; String m_Buffer; size_t m_BufferIndex; void FlushBuffer(); public: StringBuilder() : m_Sections(), m_Length(0), m_Buffer(String::MakeManaged('\0', BUFFERSIZE)), m_BufferIndex() {} /// @brief Combined length of all string sections currently stored size_t Length() const { return m_Length; } /// @brief Append any value template<typename T> void Append(T value); /// @brief Append any value. Followed by a newline template<typename T> void AppendLine(T value); /// @brief Append any value template<typename T> StringBuilder& operator<<(T value); template<> void Append<const char*>(const char* cstr); template<> void Append<>(String str); template<> void Append<const String&>(const String& str); template<> void Append<char>(char c); /// @brief Construct a managed string containing all inputs chained String Build(); }; }
26.021277
114
0.713818
Joseph-Heetel
55fd7fff99597802703d07d285d62db43afca695
5,961
cc
C++
pentago/base/superscore.cc
girving/pentago-learn
b28399aed8a77152786e97e62ee3e3a8c384af2a
[ "BSD-3-Clause" ]
41
2015-01-25T14:37:39.000Z
2022-02-23T16:29:18.000Z
pentago/base/superscore.cc
girving/pentago-learn
b28399aed8a77152786e97e62ee3e3a8c384af2a
[ "BSD-3-Clause" ]
1
2019-07-12T22:35:53.000Z
2019-07-12T22:35:53.000Z
pentago/base/superscore.cc
girving/pentago-learn
b28399aed8a77152786e97e62ee3e3a8c384af2a
[ "BSD-3-Clause" ]
2
2015-05-06T11:04:40.000Z
2017-04-18T00:22:11.000Z
// Operations on functions from rotations to scores #include "pentago/base/superscore.h" #include "pentago/base/score.h" #include "pentago/utility/array.h" #include "pentago/utility/debug.h" #include "pentago/utility/range.h" #include <numeric> #include "pentago/utility/random.h" #include <cmath> namespace pentago { using std::min; using std::numeric_limits; using std::swap; int popcount(super_t s) { #if PENTAGO_SSE union { __m128i a; uint64_t b[2]; } c[2]; c[0].a = s.x; c[1].a = s.y; return popcount(c[0].b[0])+popcount(c[0].b[1])+popcount(c[1].b[0])+popcount(c[1].b[1]); #else return popcount(s.a)+popcount(s.b)+popcount(s.c)+popcount(s.d); #endif } struct superwin_info_t { super_t horizontal, vertical, diagonal_lo, diagonal_hi, diagonal_assist; }; // We want to compute all possible rotations which give 5 in a row. // To do this, we consider each pair or triple of quadrants which could give a win, // and use the state space of the unused quadrants to store the various ways a win // could be achieved. We then do an or reduction over those quadrants. // // Cost: 4*5*32 = 640 bytes, 16+174 = 190 ops super_t super_wins(side_t side) { // Load lookup table entries: 4*(1+3) = 16 ops const superwin_info_t* table = (const superwin_info_t*)superwin_info; #define LOAD(q) const superwin_info_t& i##q = table[512*q+quadrant(side,q)]; LOAD(0) LOAD(1) LOAD(2) LOAD(3) // Prepare for reductions over unused quadrant rotations. OR<i> is an all-reduce over the ith quadrant. #if PENTAGO_SSE #define OR3 /* 3 ops */ \ w.x |= w.y; \ w.x |= _mm_shuffle_epi32(w.x,LE_MM_SHUFFLE(2,3,0,1)); \ w.y = w.x; const int swap = LE_MM_SHUFFLE(1,0,3,2); #define OR2_HALF(x) /* 5 ops */ \ x |= _mm_shuffle_epi32(x,swap); \ x |= _mm_shufflelo_epi16(_mm_shufflehi_epi16(x,swap),swap); #define OR1_HALF(x) /* 8 ops */ \ x |= _mm_slli_epi16(x,4); \ x |= _mm_srli_epi16(x,4); \ x |= _mm_slli_epi16(x,8); \ x |= _mm_srli_epi16(x,8); #define OR0_HALF(x) /* 12 ops */ \ x |= _mm_slli_epi16(x,1)&_mm_set1_epi8(0xaa); \ x |= _mm_srli_epi16(x,1)&_mm_set1_epi8(0x55); \ x |= _mm_slli_epi16(x,2)&_mm_set1_epi8(0xcc); \ x |= _mm_srli_epi16(x,2)&_mm_set1_epi8(0x33); #define OR0 OR0_HALF(w.x) OR0_HALF(w.y) // 24 ops #define OR1 OR1_HALF(w.x) OR1_HALF(w.y) // 16 ops #define OR2 OR2_HALF(w.x) OR2_HALF(w.y) // 10 ops #else // No SSE #define OR3 \ w.a = w.b = w.c = w.d = w.a|w.b|w.c|w.d; #define OR2_PART(x) \ x = (x|x>>32)&0x00000000ffffffff; x = x|x<<32; \ x = (x|x>>16)&0x0000ffff0000ffff; x = x|x<<16; #define OR1_PART(x) \ x = (x|x>>8)&0x00ff00ff00ff00ff; x = x|x<<8; \ x = (x|x>>4)&0x0f0f0f0f0f0f0f0f; x = x|x<<4; #define OR0_PART(x) \ x = (x|x>>2)&0x3333333333333333; x = x|x<<2; \ x = (x|x>>1)&0x5555555555555555; x = x|x<<1; #define OR0 OR0_PART(w.a) OR0_PART(w.b) OR0_PART(w.c) OR0_PART(w.d) #define OR1 OR1_PART(w.a) OR1_PART(w.b) OR1_PART(w.c) OR1_PART(w.d) #define OR2 OR2_PART(w.a) OR2_PART(w.b) OR2_PART(w.c) OR2_PART(w.d) #endif #define WAY(base,reduction) { super_t w = base; reduction; wins |= w; } // Consider all ways to win: 2*12+3*(10+16+24) = 174 ops super_t wins(0); WAY(i0.vertical & i1.vertical, OR3 OR2) // Vertical between quadrant 0=(0,0) and 1=(0,1) WAY(i0.horizontal & i2.horizontal, OR3 OR1) // Horizontal between quadrant 0=(0,0) and 2=(1,0) WAY(i1.horizontal & i3.horizontal, OR0 OR2) // Horizontal between quadrant 1=(0,1) and 3=(1,1) WAY(i2.vertical & i3.vertical, OR0 OR1) // Vertical between quadrant 2=(1,0) and 3=(1,1) WAY(i0.diagonal_lo & i2.diagonal_assist & i3.diagonal_lo, OR1) // Middle or low diagonal from quadrant 0=(0,0) to 3=(1,1) WAY(i0.diagonal_hi & i1.diagonal_assist & i3.diagonal_hi, OR2) // High diagonal from quadrant 0=(0,0) to 3=(1,1) WAY(i1.diagonal_lo & i0.diagonal_assist & i2.diagonal_lo, OR3) // Middle or low diagonal from quadrant 1=(0,1) to 2=(1,0) WAY(i1.diagonal_hi & i3.diagonal_assist & i2.diagonal_hi, OR0) // High diagonal from quadrant 1=(0,1) to 2=(1,0) return wins; } const Vector<int,4> single_rotations[8] = { vec(1,0,0,0),vec(-1,0,0,0),vec(0,1,0,0),vec(0,-1,0,0), vec(0,0,1,0),vec(0,0,-1,0),vec(0,0,0,1),vec(0,0,0,-1) }; uint8_t first(super_t s) { for (int r=0;r<256;r++) if (s(r)) return r; THROW(ValueError,"zero passed to super_t first"); } super_t random_super(Random& random) { const uint64_t r0 = random.bits<uint64_t>(), r1 = random.bits<uint64_t>(), r2 = random.bits<uint64_t>(), r3 = random.bits<uint64_t>(); return super_t(r0,r1,r2,r3); } Array<super_t> random_supers(const uint128_t key, const int size) { Array<super_t> supers(size, uninit); for (const int i : range(size)) { const auto ab = threefry(key,2*i), cd = threefry(key,2*i+1); supers[i] = super_t(uint64_t(ab),uint64_t(ab>>64), uint64_t(cd),uint64_t(cd>>64)); } return supers; } ostream& operator<<(ostream& output, superinfo_t s) { for (int r3=0;r3<4;r3++) { for (int r1=0;r1<4;r1++) { output << (r1||r3?' ':'['); for (int r2=0;r2<4;r2++) { if (r2) output << ' '; for (int r0=0;r0<4;r0++) output << char(s.known(r0,r1,r2,r3) ? '0'+s.wins(r0,r1,r2,r3) : '_'); } output << (r1==3&&r3==3?']':'\n'); if (r1==3) output << '\n'; } } return output; } ostream& operator<<(ostream& output, super_t s) { superinfo_t i; i.known = ~super_t(0); i.wins = s; return output<<i; } uint64_t super_popcount(NdArray<const super_t> data) { uint64_t sum = 0; for (auto& s : data.flat()) sum += popcount(s); return sum; } NdArray<int> super_popcounts(NdArray<const super_t> data) { NdArray<int> counts(data.shape(),uninit); for (int i=0;i<data.flat().size();i++) counts.flat()[i] = popcount(data.flat()[i]); return counts; } } // namespace pentago
35.694611
123
0.630767
girving
55fe1a21fdf4657aa0ea6064b0c3a3502809458a
9,966
hpp
C++
include/geometry/visualizeRviz.hpp
waterben/LineExtraction
d247de45417a1512a3bf5d0ffcd630d40ffb8798
[ "MIT" ]
1
2020-06-12T13:30:56.000Z
2020-06-12T13:30:56.000Z
include/geometry/visualizeRviz.hpp
waterben/LineExtraction
d247de45417a1512a3bf5d0ffcd630d40ffb8798
[ "MIT" ]
null
null
null
include/geometry/visualizeRviz.hpp
waterben/LineExtraction
d247de45417a1512a3bf5d0ffcd630d40ffb8798
[ "MIT" ]
null
null
null
#ifndef _VISUALIZE_RVIZ_HPP_ #define _VISUALIZE_RVIZ_HPP_ #ifdef __cplusplus #include <string> #include <visualization_msgs/Marker.h> #include <visualization_msgs/MarkerArray.h> namespace lsfm { template < class MyLine3Dsegment, class FT> void visualizeLinesRviz(const std::vector<MyLine3Dsegment> line3Segments, const ros::Publisher marker_pub){ std::vector<std::string> markerText; const std::vector<lsfm::Pose<FT>> robotPoses; visualizeLinesRviz(line3Segments, markerText, marker_pub, robotPoses); } template < class MyLine3Dsegment, class FT > void visualizeLinesRviz(const std::vector<MyLine3Dsegment> line3Segments, const std::vector<std::string> markerText, const ros::Publisher marker_pub, const std::vector<lsfm::Pose<FT>> robotPoses){ bool addText; if(markerText.size() == line3Segments.size()) addText = true; else addText = false; // %Tag(MARKER_INIT)% visualization_msgs::MarkerArray marker_list; visualization_msgs::Marker line_list; line_list.header.frame_id = "world"; line_list.header.stamp = ros::Time::now(); line_list.ns = "points_and_lines"; line_list.action = visualization_msgs::Marker::ADD; line_list.pose.orientation.w = 1.0; // %EndTag(MARKER_INIT)% // %Tag(DELETE_ALL_MARKER)% visualization_msgs::Marker reset_marker_; reset_marker_.header.frame_id = "world"; reset_marker_.header.stamp = ros::Time(); reset_marker_.action = 3; // In ROS-J: visualization_msgs::Marker::DELETEALL; reset_marker_.id = 0; // %EndTag(MARKER_INIT)% // First Marker deletes all markers marker_list.markers.push_back(reset_marker_); // Start adding markers ------------------------------------- uint32_t markerId = 1; // %Tag(ID)% line_list.id = markerId++; // %EndTag(ID)% // %Tag(TYPE)% line_list.type = visualization_msgs::Marker::LINE_LIST; // %EndTag(TYPE)% // %Tag(SCALE)% // LINE_STRIP/LINE_LIST markers use only the x component of scale, for the line width line_list.scale.x = 0.1; // %EndTag(SCALE)% // %Tag(COLOR)% // Line list is red line_list.color.r = 1.0; line_list.color.a = 0.8; // %EndTag(COLOR)% // Create the vertices for the points and lines for (uint32_t i = 0; i < line3Segments.size(); ++i) { // Line Segment MyLine3Dsegment lineSegment = line3Segments[i]; lsfm::Vec3<FT> sp = lineSegment.startPoint(); lsfm::Vec3<FT> ep = lineSegment.endPoint(); geometry_msgs::Point p; p.x = sp.x(); p.y = sp.z(); p.z = -sp.y(); line_list.points.push_back(p); // The line list needs two points for each line p.x = ep.x(); p.y = ep.z(); p.z = -ep.y() - 0.1; line_list.points.push_back(p); if(addText){ markerId++; // Text marker visualization_msgs::Marker text; text.pose.position = p; text.header.frame_id = "world"; text.header.stamp = ros::Time::now(); text.id = markerId; text.ns = "points_and_lines"; text.action = visualization_msgs::Marker::ADD; text.text = markerText[i]; text.pose.orientation.w = 1.0; text.type = visualization_msgs::Marker::TEXT_VIEW_FACING; text.color.a = 1.0; text.color.r = 1.0; text.color.g = 1.0; text.color.b = 1.0; text.scale.z = 0.4; marker_list.markers.push_back(text); } } for (uint32_t i = 0; i < robotPoses.size(); ++i) { markerId++; visualization_msgs::Marker pose; geometry_msgs::Point origin; origin.x = robotPoses[i].origin().x(); origin.y = robotPoses[i].origin().z(); origin.z = -robotPoses[i].origin().y(); pose.pose.position = origin; pose.header.frame_id = "world"; pose.header.stamp = ros::Time::now(); pose.id = markerId; pose.ns = "points_and_lines"; pose.action = visualization_msgs::Marker::ADD; // pose.text = markerText[i]; pose.type = visualization_msgs::Marker::ARROW; cv::Matx33<FT> convMat(robotPoses[i].rotM().data()); cv::Matx33<FT> rotZ(0,-1,0,1,0,0,0,0,1); cv::Vec4<FT> q = quaternion(convMat*rotZ); pose.pose.orientation.x = q[0]; pose.pose.orientation.y = q[1]; pose.pose.orientation.z = q[2]; pose.pose.orientation.w = q[3]; pose.color.a = 1.0; pose.color.r = 0.0f; pose.color.g = 1.0f; pose.color.b = 0.0f; pose.scale.x = 1.0f; pose.scale.y = 0.2f; pose.scale.z = 0.2f; marker_list.markers.push_back(pose); } marker_list.markers.push_back(line_list); marker_pub.publish(marker_list); } template < class MyPoint3D, class FT > void visualizePointsRviz(const std::vector<MyPoint3D> points3D, const std::vector<std::string> markerText, const ros::Publisher marker_pub, const std::vector<lsfm::Pose<FT>> robotPoses){ bool addText; if(markerText.size() == points3D.size()) addText = true; else addText = false; // %Tag(MARKER_INIT)% visualization_msgs::MarkerArray marker_list; visualization_msgs::Marker sphere_list; sphere_list.header.frame_id = "world"; sphere_list.header.stamp = ros::Time::now(); sphere_list.ns = "points_and_lines"; sphere_list.action = visualization_msgs::Marker::ADD; sphere_list.pose.orientation.w = 1.0; // %EndTag(MARKER_INIT)% // %Tag(DELETE_ALL_MARKER)% visualization_msgs::Marker reset_marker_; reset_marker_.header.frame_id = "world"; reset_marker_.header.stamp = ros::Time(); reset_marker_.action = 3; // In ROS-J: visualization_msgs::Marker::DELETEALL; reset_marker_.id = 0; // %EndTag(MARKER_INIT)% // First Marker deletes all markers marker_list.markers.push_back(reset_marker_); // Start adding markers ------------------------------------- uint32_t markerId = 1; // %Tag(ID)% sphere_list.id = markerId++; // %EndTag(ID)% // %Tag(TYPE)% sphere_list.type = visualization_msgs::Marker::SPHERE_LIST; // %EndTag(TYPE)% // %Tag(SCALE)% // LINE_STRIP/LINE_LIST markers use only the x component of scale, for the line width sphere_list.scale.x = 0.5; sphere_list.scale.y = 0.5; // %EndTag(SCALE)% // %Tag(COLOR)% // Line list is red sphere_list.color.r = 1.0; sphere_list.color.a = 0.8; // %EndTag(COLOR)% // Create the vertices for the points and lines for (uint32_t i = 0; i < points3D.size(); ++i) { // Line Segment MyPoint3D point = points3D[i]; geometry_msgs::Point p; p.x = point.point.x(); p.y = point.point.z(); p.z = -point.point.y(); sphere_list.points.push_back(p); if(addText){ markerId++; // Text marker visualization_msgs::Marker text; text.pose.position = p; text.header.frame_id = "world"; text.header.stamp = ros::Time::now(); text.id = markerId; text.ns = "points_and_lines"; text.action = visualization_msgs::Marker::ADD; text.text = markerText[i]; text.pose.orientation.w = 1.0; text.type = visualization_msgs::Marker::TEXT_VIEW_FACING; text.color.a = 1.0; text.color.r = 1.0; text.color.g = 1.0; text.color.b = 1.0; text.scale.z = 0.4; marker_list.markers.push_back(text); } } for (uint32_t i = 0; i < robotPoses.size(); ++i) { markerId++; visualization_msgs::Marker pose; geometry_msgs::Point origin; origin.x = robotPoses[i].origin().x(); origin.y = robotPoses[i].origin().z(); origin.z = -robotPoses[i].origin().y(); pose.pose.position = origin; pose.header.frame_id = "world"; pose.header.stamp = ros::Time::now(); pose.id = markerId; pose.ns = "points_and_lines"; pose.action = visualization_msgs::Marker::ADD; // pose.text = markerText[i]; pose.type = visualization_msgs::Marker::ARROW; cv::Matx33<FT> convMat(robotPoses[i].rotM().data()); cv::Matx33<FT> rotZ(0,-1,0,1,0,0,0,0,1); cv::Vec4<FT> q = quaternion(convMat*rotZ); pose.pose.orientation.x = q[0]; pose.pose.orientation.y = q[1]; pose.pose.orientation.z = q[2]; pose.pose.orientation.w = q[3]; pose.color.a = 1.0; pose.color.r = 0.0f; pose.color.g = 1.0f; pose.color.b = 0.0f; pose.scale.x = 1.0f; pose.scale.y = 0.2f; pose.scale.z = 0.2f; marker_list.markers.push_back(pose); } marker_list.markers.push_back(sphere_list); marker_pub.publish(marker_list); } } #endif #endif
32.462541
200
0.536825
waterben
360a4e0c443d4b1e1bed41cd51426a1b6a4a762a
4,134
cpp
C++
ige/src/asset/Texture.cpp
Arcahub/ige
b9f61209c924c7b683d2429a07e76251e6eb7b1b
[ "MIT" ]
3
2021-06-05T00:36:50.000Z
2022-02-27T10:23:53.000Z
ige/src/asset/Texture.cpp
Arcahub/ige
b9f61209c924c7b683d2429a07e76251e6eb7b1b
[ "MIT" ]
11
2021-05-08T22:00:24.000Z
2021-11-11T22:33:43.000Z
ige/src/asset/Texture.cpp
Arcahub/ige
b9f61209c924c7b683d2429a07e76251e6eb7b1b
[ "MIT" ]
4
2021-05-20T12:41:23.000Z
2021-11-09T14:19:18.000Z
#include "igepch.hpp" #include "ige/asset/Texture.hpp" #define STB_IMAGE_IMPLEMENTATION #define STBI_FAILURE_USERMSG #include "stb_image.h" #include <cerrno> #include <cstddef> #include <cstring> #include <filesystem> #include <fstream> using ige::asset::Texture; Texture::Texture(Format format, std::size_t width, std::size_t height) : m_format(format) , m_width(width) , m_height(height) , m_pixels(width * height) { } Texture::Texture(std::span<const std::byte> image_data) { load(image_data); m_version = 0; } Texture::Texture(const std::filesystem::path& path) { load(path); m_version = 0; } std::size_t Texture::width() const { return m_width; } std::size_t Texture::height() const { return m_height; } std::uint8_t Texture::channels() const { switch (m_format) { case Texture::Format::RGBA: return 4; case Texture::Format::RGB: return 3; case Texture::Format::RG: return 2; case Texture::Format::R: return 1; default: return 0; } } std::span<const std::byte> Texture::data() const { return m_pixels; } std::uint64_t Texture::version() const { return m_version; } Texture::Format Texture::format() const { return m_format; } Texture::MagFilter Texture::mag_filter() const { return m_mag_filter; } Texture::MinFilter Texture::min_filter() const { return m_min_filter; } Texture::WrappingMode Texture::wrap_s() const { return m_wrap_s; } Texture::WrappingMode Texture::wrap_t() const { return m_wrap_t; } void Texture::set_mag_filter(MagFilter value) { m_mag_filter = value; } void Texture::set_min_filter(MinFilter value) { m_min_filter = value; } void Texture::set_wrap_s(WrappingMode value) { m_wrap_s = value; } void Texture::set_wrap_t(WrappingMode value) { m_wrap_t = value; } void Texture::set_data( Format format, std::size_t width, std::size_t height, std::vector<std::byte> pixels) { m_format = format; if (pixels.size() < width * height * channels()) { throw std::runtime_error("Pixel buffer is too small."); } m_version++; m_width = width; m_height = height; m_pixels = std::move(pixels); } void Texture::load(std::span<const std::byte> buffer) { int width; int height; int channels; unsigned char* data = stbi_load_from_memory( reinterpret_cast<const unsigned char*>(buffer.data()), static_cast<int>(buffer.size()), &width, &height, &channels, 0); if (!data) { throw std::runtime_error(stbi_failure_reason()); } else if (channels < 1 || channels > 4) { stbi_image_free(data); throw std::runtime_error( "Invalid channel count (" + std::to_string(channels) + ")"); } const Texture::Format formats[] = { Format::R, Format::RG, Format::RGB, Format::RGBA, }; try { std::byte* bytes = reinterpret_cast<std::byte*>(data); set_data( formats[channels - 1], width, height, { bytes, bytes + width * height * channels }); } catch (...) { stbi_image_free(data); throw; } stbi_image_free(data); } static std::vector<std::byte> read_file(const std::filesystem::path& path) { std::ifstream ifs(path, std::ios::binary | std::ios::ate); if (!ifs) { throw std::runtime_error(path.string() + ": " + std::strerror(errno)); } auto end = ifs.tellg(); ifs.seekg(0, std::ios::beg); auto size = std::size_t(end - ifs.tellg()); if (size == 0) { throw std::runtime_error(path.string() + ": file is empty"); } std::vector<std::byte> buffer(size); if (!ifs.read(reinterpret_cast<char*>(buffer.data()), buffer.size())) { throw std::runtime_error(path.string() + ": " + std::strerror(errno)); } return buffer; } void Texture::load(const std::filesystem::path& path) { auto buffer = read_file(path); try { load(buffer); } catch (const std::exception& e) { throw std::runtime_error(path.string() + ": " + e.what()); } }
19.971014
78
0.619981
Arcahub
361029e1cb1172698f778e4766c21af6648e6cae
4,000
cc
C++
lib/jflags_deprecated.cc
jaydee-io/jflags
2c4e6387345faf502f8048f749d0c850276ec1a7
[ "BSD-3-Clause" ]
null
null
null
lib/jflags_deprecated.cc
jaydee-io/jflags
2c4e6387345faf502f8048f749d0c850276ec1a7
[ "BSD-3-Clause" ]
null
null
null
lib/jflags_deprecated.cc
jaydee-io/jflags
2c4e6387345faf502f8048f749d0c850276ec1a7
[ "BSD-3-Clause" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // jflags // // This file is distributed under the 3-clause Berkeley Software Distribution // License. See LICENSE.txt for details. //////////////////////////////////////////////////////////////////////////////// #include "jflags_deprecated.h" #include "jflags_parser.h" #include "FlagSaver.h" #include "FlagRegistry.h" #include "CommandLineFlagParser.h" #include <string> namespace JFLAGS_NAMESPACE { using std::string; string ReadFileIntoString(const char * filename); // -------------------------------------------------------------------- // CommandlineFlagsIntoString() // ReadFlagsFromString() // AppendFlagsIntoFile() // ReadFromFlagsFile() // These are mostly-deprecated routines that stick the // commandline flags into a file/string and read them back // out again. I can see a use for CommandlineFlagsIntoString, // for creating a flagfile, but the rest don't seem that useful // -- some, I think, are a poor-man's attempt at FlagSaver -- // and are included only until we can delete them from callers. // Note they don't save --flagfile flags (though they do save // the result of having called the flagfile, of course). // -------------------------------------------------------------------- static string TheseCommandlineFlagsIntoString(const vector<CommandLineFlagInfo> & flags) { vector<CommandLineFlagInfo>::const_iterator i; size_t retval_space = 0; for (i = flags.begin(); i != flags.end(); ++i) // An (over)estimate of how much space it will take to print this flag retval_space += i->name.length() + i->current_value.length() + 5; string retval; retval.reserve(retval_space); for (i = flags.begin(); i != flags.end(); ++i) { retval += "--"; retval += i->name; retval += "="; retval += i->current_value; retval += "\n"; } return retval; } string CommandlineFlagsIntoString() { vector<CommandLineFlagInfo> sorted_flags; GetAllFlags(&sorted_flags); return TheseCommandlineFlagsIntoString(sorted_flags); } bool ReadFlagsFromString(const string & flagfilecontents, const char * /*prog_name*/, // TODO(csilvers): nix this bool errors_are_fatal) { FlagRegistry * const registry = FlagRegistry::GlobalRegistry(); FlagSaver saved_states; CommandLineFlagParser parser(registry); registry->Lock(); parser.ProcessOptionsFromStringLocked(flagfilecontents, SET_FLAGS_VALUE); registry->Unlock(); // Should we handle --help and such when reading flags from a string? Sure. HandleCommandLineHelpFlags(); if (parser.ReportErrors()) { // Error. Restore all global flags to their previous values. if (errors_are_fatal) jflags_exitfunc(1); return false; } saved_states.discard(); return true; } // TODO(csilvers): nix prog_name in favor of ProgramInvocationShortName() bool AppendFlagsIntoFile(const string & filename, const char * prog_name) { FILE * fp; if (SafeFOpen(&fp, filename.c_str(), "a") != 0) return false; if (prog_name) fprintf(fp, "%s\n", prog_name); vector<CommandLineFlagInfo> flags; GetAllFlags(&flags); // But we don't want --flagfile, which leads to weird recursion issues vector<CommandLineFlagInfo>::iterator i; for (i = flags.begin(); i != flags.end(); ++i) { if (strcmp(i->name.c_str(), "flagfile") == 0) { flags.erase(i); break; } } fprintf(fp, "%s", TheseCommandlineFlagsIntoString(flags).c_str()); fclose(fp); return true; } bool ReadFromFlagsFile(const string & filename, const char * prog_name, bool errors_are_fatal) { return ReadFlagsFromString(ReadFileIntoString(filename.c_str()), prog_name, errors_are_fatal); } } // namespace JFLAGS_NAMESPACE
32.258065
98
0.612
jaydee-io
36102aa5d7c9d850aeb968ee6cd9769e1853c043
2,488
cpp
C++
C++/QuickSort.cpp
OluSure/Hacktoberfest2021-1
ad1bafb0db2f0cdeaae8f87abbaa716638c5d2ea
[ "MIT" ]
215
2021-10-01T08:18:16.000Z
2022-03-29T04:12:03.000Z
C++/QuickSort.cpp
OluSure/Hacktoberfest2021-1
ad1bafb0db2f0cdeaae8f87abbaa716638c5d2ea
[ "MIT" ]
175
2021-10-03T10:47:31.000Z
2021-10-20T11:55:32.000Z
C++/QuickSort.cpp
OluSure/Hacktoberfest2021-1
ad1bafb0db2f0cdeaae8f87abbaa716638c5d2ea
[ "MIT" ]
807
2021-10-01T08:11:45.000Z
2021-11-21T18:57:09.000Z
// Introduction to Quick Sort // QuickSort is a Divide and Conquer algorithm // We take an element as pivot and we use partition() function to sort the before and after elemets of the pivot. // Following are the ways in which you can take a pivot element : // 1) Pick first element as pivot // 2) Pick last element as pivot // 3) Pick a random element as pivot // 4) Pick median as pivot // We took last element as pivot in the below code demonstration // Time Complexity of Quick Sort // 1) Worst Case : When pivot is the greatest or the smallest element, then we have to iterate from increasing and decreasing order. Time complexity will be O(n^2). // 2) Average Case : When pivot is choosen between the greatest/smallest element to the middle most element, Time Complexity then will be O(nLogn). // 3) Best Case : When pivot choosen is the middle most element, Time Complexity will be O(nLogn). // Quick Sort is the most used sorting technique all over the world becasue even the Worst Case of Time complexity of quick sort is lesser than other sorting technique. // C++ code for Quick Sort #include<iostream> using namespace std; // Partition() function to sort the before and after elements of the pivot. // we start from the leftmost element(i = s-1) and keep track of index of smaller (or equal to) elements as i. // While traversing, if we find a smaller element, we swap current element with arr[i]. Otherwise we ignore current element. int partition(int arr[], int s, int e) { // We decided the last element as pivot int pivot = arr[e]; int i = s-1; for(int j=s; j<e; j++) { if(arr[j]<pivot) { i++; swap(arr[i], arr[j]); } } swap(arr[i+1], arr[e]); return i+1; } // quicksort() function which takes the array from main() function and decide the pivot and send the before and after elements of pivot to partition() function. void quicksort(int arr[], int s, int e) { if(s<e) { int pi = partition(arr, s, e); quicksort(arr, s, pi-1); quicksort(arr, pi+1, e); } } // main() function int main() { // We created the array int arr[] = {5,2,7,10,4,8,23,14,21,1}; // Total elements in the array is 10 int n = 10; // quicksort() function is called quicksort(arr, 0, n-1); // Printed the Sorted array for(int i=0; i<n; i++) { cout<<arr[i]<<" "; } // Expected Output: 1 2 4 5 7 8 10 14 21 23 cout<<endl; return 0; }
34.082192
168
0.661977
OluSure
3610661d48e0e9a68747c83923327db3e5d7de84
1,031
cpp
C++
server/Server/Packets/WGRetSceneDataHandler.cpp
viticm/web-pap
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
[ "BSD-3-Clause" ]
3
2018-06-19T21:37:38.000Z
2021-07-31T21:51:40.000Z
server/Server/Packets/WGRetSceneDataHandler.cpp
viticm/web-pap
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
[ "BSD-3-Clause" ]
null
null
null
server/Server/Packets/WGRetSceneDataHandler.cpp
viticm/web-pap
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
[ "BSD-3-Clause" ]
13
2015-01-30T17:45:06.000Z
2022-01-06T02:29:34.000Z
#include "stdafx.h" #include "WGRetSceneData.h" #include "Log.h" #include "ServerManager.h" #include "Scene.h" #include "SceneManager.h" UINT WGRetSceneDataHandler::Execute( WGRetSceneData* pPacket, Player* pPlayer ) { __ENTER_FUNCTION if( pPlayer->IsServerPlayer() ) {//服务器收到世界服务器发来的数据 Assert( MyGetCurrentThreadID()==g_pServerManager->m_ThreadID ) ; SceneID_t SceneID = pPacket->GetSceneID() ; Scene* pScene = g_pSceneManager->GetScene( SceneID ) ; if( pScene == NULL ) { Assert(FALSE) ; return PACKET_EXE_CONTINUE ; } pScene->m_SceneInitData = *pPacket->GetSceneInitData() ; pScene->Init( ) ; //通知城市创建人,城市已经成功创建 pScene->SetSceneStatus( SCENE_STATUS_INIT ) ; } else { Assert(FALSE) ; } g_pLog->FastSaveLog( LOG_FILE_1, "WGRetSceneDataHandler: SceneID=%d", pPacket->GetSceneID() ) ; return PACKET_EXE_CONTINUE ; __LEAVE_FUNCTION return PACKET_EXE_ERROR ; }
21.93617
79
0.632396
viticm