hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
75a164d4007883829cd61f5607ef3becd3d494d6
724
cc
C++
steam/asyncjob.cc
TBK/argonx
0165caad474d83f020fe29d85e802fae9adecc23
[ "BSD-2-Clause" ]
22
2019-01-15T12:18:25.000Z
2022-03-24T03:39:59.000Z
steam/asyncjob.cc
TBK/argonx
0165caad474d83f020fe29d85e802fae9adecc23
[ "BSD-2-Clause" ]
3
2019-07-13T16:16:16.000Z
2020-07-30T10:07:30.000Z
steam/asyncjob.cc
TBK/argonx
0165caad474d83f020fe29d85e802fae9adecc23
[ "BSD-2-Clause" ]
2
2019-06-19T10:09:32.000Z
2020-06-29T15:16:58.000Z
#include <precompiled.hh> #include "asyncjob.hh" namespace Steam { static std::vector<AsyncJob> jobs; AsyncJob NewAsyncJob(AsyncJob::Callback callback) { auto jobId = JobManager::GetNextNonCallJobId(); auto r = AsyncJob{jobId, callback}; jobs.push_back(r); return r; } void RunAsyncJobs() { std::vector<decltype(jobs.begin())> toRemove; for (auto it = jobs.begin(); it != jobs.end(); ++it) { const auto j = *it; auto result = j.RunJob(); if (result == AsyncJob::Result::finish) { toRemove.push_back(it); } } // Now remove them from the jobs for (auto it : toRemove) { jobs.erase(it); } } } // namespace Steam
21.294118
58
0.589779
TBK
75a4cf4f88bead27d7ad6c09dcf664a02bf5e92c
1,459
hxx
C++
include/distant/wow/entities/detail/impl/player.hxx
Ostoic/distant_wow
d9ae4e6226c8d0981abc4dc3c941ea60d8e22e6b
[ "MIT" ]
1
2022-02-19T21:37:43.000Z
2022-02-19T21:37:43.000Z
include/distant/wow/entities/detail/impl/player.hxx
Ostoic/distant_wow
d9ae4e6226c8d0981abc4dc3c941ea60d8e22e6b
[ "MIT" ]
null
null
null
include/distant/wow/entities/detail/impl/player.hxx
Ostoic/distant_wow
d9ae4e6226c8d0981abc4dc3c941ea60d8e22e6b
[ "MIT" ]
1
2022-02-19T21:37:46.000Z
2022-02-19T21:37:46.000Z
#pragma once #include "../player.hpp" #include "../../../memory/operations.hpp" #include "../../../offsets.hpp" #include "../../../error/game_error.hpp" namespace distant::wow::entities::detail { template <> inline memory::address get_name_ptr<player>(wow::guid guid) { const auto mask = memory::read<wow::dword>(wow::offsets::name_cache::cache_base + wow::offsets::name_cache::player_name_mask); const auto base = memory::read<wow::dword>(wow::offsets::name_cache::cache_base + wow::offsets::name_cache::player_name_base); const auto short_guid = memory::address(guid.low & 0xFFFFFFFF); auto offset = 12 * (mask & short_guid); auto current = memory::read<memory::address>(base + offset + 8); offset = memory::read<wow::dword>(base + offset); if ((current & 0x1) == 0x1) throw error::memory_disparity("[entities::player::get_name_ptr()] Invalid name cache offset"); auto test_guid = memory::read<wow::dword>(current); while (test_guid != short_guid) { current = memory::read<memory::address>(current + offset + 4); if ((current & 0x1) == 0x1) throw error::memory_disparity("[entities::player::get_name_ptr()] Invalid name cache offset"); test_guid = memory::read<wow::dword>(current); } return current + wow::offsets::name_cache::player_name_string; } template <> inline std::string load_name<player>(const wow::guid guid) { return memory::read<std::string>(detail::get_name_ptr<player>(guid)); } }
32.422222
128
0.690199
Ostoic
b5a8a1ac3a4b8386793567fb5f5c8e3df08810e2
2,898
cpp
C++
SDK/ARKSurvivalEvolved_AnimNotify_PlayParticleEffect_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_AnimNotify_PlayParticleEffect_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_AnimNotify_PlayParticleEffect_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
// ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_AnimNotify_PlayParticleEffect_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function AnimNotify_PlayParticleEffect.AnimNotify_PlayParticleEffect_C.GetNotifyName // () // Parameters: // class FString ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm) class FString UAnimNotify_PlayParticleEffect_C::GetNotifyName() { static auto fn = UObject::FindObject<UFunction>("Function AnimNotify_PlayParticleEffect.AnimNotify_PlayParticleEffect_C.GetNotifyName"); UAnimNotify_PlayParticleEffect_C_GetNotifyName_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function AnimNotify_PlayParticleEffect.AnimNotify_PlayParticleEffect_C.Received_Notify // (NetRequest, Exec, Native, NetResponse, MulticastDelegate, Public, HasOutParms, HasDefaults, DLLImport, BlueprintPure) // Parameters: // class USkeletalMeshComponent** MeshComp (Parm, ZeroConstructor, IsPlainOldData) // class UAnimSequenceBase** Animation (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UAnimNotify_PlayParticleEffect_C::Received_Notify(class USkeletalMeshComponent** MeshComp, class UAnimSequenceBase** Animation) { static auto fn = UObject::FindObject<UFunction>("Function AnimNotify_PlayParticleEffect.AnimNotify_PlayParticleEffect_C.Received_Notify"); UAnimNotify_PlayParticleEffect_C_Received_Notify_Params params; params.MeshComp = MeshComp; params.Animation = Animation; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function AnimNotify_PlayParticleEffect.AnimNotify_PlayParticleEffect_C.ExecuteUbergraph_AnimNotify_PlayParticleEffect // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UAnimNotify_PlayParticleEffect_C::ExecuteUbergraph_AnimNotify_PlayParticleEffect(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function AnimNotify_PlayParticleEffect.AnimNotify_PlayParticleEffect_C.ExecuteUbergraph_AnimNotify_PlayParticleEffect"); UAnimNotify_PlayParticleEffect_C_ExecuteUbergraph_AnimNotify_PlayParticleEffect_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
33.310345
170
0.729124
2bite
b5b793b32977564b5d59ef6aae49482a58422ddf
641
cpp
C++
Projects/JogoKartas/src/main.cpp
0lilauro/PDSII
d9453ef7a053295b9ed9bc871a90e1952aa571ee
[ "MIT" ]
null
null
null
Projects/JogoKartas/src/main.cpp
0lilauro/PDSII
d9453ef7a053295b9ed9bc871a90e1952aa571ee
[ "MIT" ]
null
null
null
Projects/JogoKartas/src/main.cpp
0lilauro/PDSII
d9453ef7a053295b9ed9bc871a90e1952aa571ee
[ "MIT" ]
null
null
null
#include <iostream> #include "Partida.hpp" #include "Jogador.hpp" using namespace std; int main() { int numero_cartas_por_jogador; int numero_jogadores; cin >> numero_jogadores; cin >> numero_cartas_por_jogador; Partida *p = new Partida(numero_jogadores); string nomeJogador; int numero_pontos_carta; int i, j; string naipe; for(int i=0; i<numero_jogadores; i++) { cin >> nomeJogador; for(int j=0; j<numero_cartas_por_jogador; j++){ cin >> numero_pontos_carta; cin >> naipe; p->addJogadorCarta(nomeJogador, numero_pontos_carta, naipe); } } p->imprimeJogadoresOrdenados(); return 0; }
20.677419
66
0.694228
0lilauro
b5b9be3b4ed25510e205e3ddeb9281f1583c1547
95
cpp
C++
Exercise one: Toolchain/helloThreads/newfile.cpp
LilyOSullivan/CDDLabs
4f2c597b5d9429683b4f60ebd32bcd11a0f51829
[ "MIT" ]
null
null
null
Exercise one: Toolchain/helloThreads/newfile.cpp
LilyOSullivan/CDDLabs
4f2c597b5d9429683b4f60ebd32bcd11a0f51829
[ "MIT" ]
null
null
null
Exercise one: Toolchain/helloThreads/newfile.cpp
LilyOSullivan/CDDLabs
4f2c597b5d9429683b4f60ebd32bcd11a0f51829
[ "MIT" ]
null
null
null
#include <stdio.h> int main(void) { int i; for(i=0;i<10;i++) printf("%d",i); }
11.875
23
0.473684
LilyOSullivan
b5ba5a5e1c4328c3b399677985032754b2633537
153
cc
C++
src/circuit/cmt_circuit_builder.cc
hyraxZK/libpws
cc1b7dfdafb3d01b025cdb72ed83379d205a0147
[ "Apache-2.0" ]
null
null
null
src/circuit/cmt_circuit_builder.cc
hyraxZK/libpws
cc1b7dfdafb3d01b025cdb72ed83379d205a0147
[ "Apache-2.0" ]
null
null
null
src/circuit/cmt_circuit_builder.cc
hyraxZK/libpws
cc1b7dfdafb3d01b025cdb72ed83379d205a0147
[ "Apache-2.0" ]
1
2020-01-16T07:49:03.000Z
2020-01-16T07:49:03.000Z
#include "cmt_circuit_builder.hh" CMTCircuitBuilder:: ~CMTCircuitBuilder() { } void CMTCircuitBuilder:: destroyCircuit(CMTCircuit* c) { delete c; }
11.769231
33
0.751634
hyraxZK
b5bb4cbaceb3b6811cb0a48d68fbf3fec159f2f2
1,441
cpp
C++
recursion/NumberofIslands_200.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
recursion/NumberofIslands_200.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
recursion/NumberofIslands_200.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
/* *********************************************************************** > File Name: NumberofIslands_200.cpp > Author: zzy > Mail: [email protected] > Created Time: Thu 08 Aug 2019 11:22:34 AM CST ********************************************************************** */ #include <stdio.h> #include <vector> #include <string> #include <stdio.h> #include <climits> #include <gtest/gtest.h> using std::vector; using std::string; /* * 200. 岛屿数量 * * 给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。 * */ /* * 解法1;DFS 顺序遍历二维数组。如果是岛,把他周围的岛都变成水。 ++ * * * */ class Solution { public: void Flood(vector<vector<char>>& grid, int sr, int sc) { if (sr < 0 || sr >= (int)grid.size()) return; if (sc < 0 || sc >= (int)grid[0].size()) return; if (grid[sr][sc] == '0') return; grid[sr][sc] = '0'; Flood(grid, sr - 1, sc); Flood(grid, sr + 1, sc); Flood(grid, sr, sc + 1); Flood(grid, sr, sc - 1); } int numIslands(vector<vector<char>>& grid) { if (grid.empty()) return 0; int sr = grid.size(); int sc = grid[0].size(); int island_num = 0; for (int i = 0; i < sr; ++i) { for (int j = 0; j < sc; ++j) { if (grid[i][j] == '1') { ++ island_num; Flood(grid, i, j); } } } return island_num; } }; TEST(testCase,test0) { } int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc,argv); return RUN_ALL_TESTS(); }
19.472973
93
0.521166
obviouskkk
b5bcd2817b54740bef2b5cc8f67613308cb8ae5a
3,607
hpp
C++
inc/Hazen/FrictionMethods.hpp
barne856/Hazen
afac525caa8d5229d6ce21248027d680cc5a620d
[ "MIT" ]
null
null
null
inc/Hazen/FrictionMethods.hpp
barne856/Hazen
afac525caa8d5229d6ce21248027d680cc5a620d
[ "MIT" ]
null
null
null
inc/Hazen/FrictionMethods.hpp
barne856/Hazen
afac525caa8d5229d6ce21248027d680cc5a620d
[ "MIT" ]
null
null
null
#ifndef HAZEN_FRICTION_METHODS #define HAZEN_FRICTION_METHODS // HAZEN #include "Hazen/HydraulicShapes.hpp" namespace hazen { /** * @brief An Abstract Friction Method used to calculate head losses in the * Passage Hydraulic Link. */ class FrictionMethod { public: /** * @brief Compute the slope of the Energy Grade Line (EGL) at one point in * a Passage due to irreversible friction losses. * * @param shape The cross-sectional shape of the Passage. * @param Q The flow through the Passage. * @param depth The depth of flow in the Passage at the point of interest. * @return The slope of the EGL at the point of interest along the * Passage. */ virtual Angle friction_slope(HydraulicShape *shape, Flow Q, Length depth) = 0; }; /** * @brief An implementation of Manning's Equation to compute the slope of the * Energy Grade Line (EGL) in a Passage. * */ class ManningsFriction : public FrictionMethod { public: /** * @brief Construct a new Mannings Friction object. * * @param n Manning's n coefficient. */ ManningsFriction(Dimensionless n); /** * @brief An implementation of Manning's Equation to compute the slope of * the Energy Grade Line (EGL) in a Passage. * @param shape The cross-sectional shape of the Passage. * @param Q The flow through the Passage. * @param depth The depth of flow in the Passage at the calculation point. * @return The slope of the EGL at a point along the Passage. */ Angle friction_slope(HydraulicShape *shape, Flow Q, Length depth) override; private: Dimensionless n; /**< Manning's n coefficient used in Manning's Equation.*/ }; /** * @brief An implementation of the Hazen-Williams Equation to compute the * slope of the Energy Grade Line (EGL) in a Passage. * */ class HazenFriction : public FrictionMethod { public: /** * @brief Construct a new Hazen Friction object. * * @param C Hazen roughness coefficient. */ HazenFriction(Dimensionless C); /** * @brief An implementation of Hazen-Williams Equation to compute the slope * of the Energy Grade Line (EGL) in a Passage. * @param shape The cross-sectional shape of the Passage. * @param Q The flow through the Passage. * @param depth The depth of flow in the Passage at the calculation point. * @return double The slope of the EGL at a point along the Passage. */ Angle friction_slope(HydraulicShape *shape, Flow Q, Length depth) override; private: Dimensionless C; /**< C friction coefficient used in the Hazen-Williams Equation.*/ }; /** * @brief An implementation of the Darcy-Weisbach Equation to compute the * slope of the Energy Grade Line (EGL) in a Passage. * */ class DarcyFriction : public FrictionMethod { public: /** * @brief Construct a new Darcy Friction object * * @param eps Pipe roughness coefficient. * @param rho Fluid density. * @param mu Fluid dynamic viscosity. */ DarcyFriction(Length eps, Density rho, Dynamic_Viscosity mu); /** * @brief An implementation of Darcy-Weisbach Equation to compute the slope * of the Energy Grade Line (EGL) in a Passage. * @return The slope of the EGL at a point along the Passage. * */ Angle friction_slope(HydraulicShape *shape, Flow Q, Length depth) override; private: Length eps; /**< epsilon, pipe roughness coefficient used in the Darcy-Weisbach Equation. Dimension matches that of the Hydraulic Shape.*/ Density rho; /**< Density of the fluid.*/ Dynamic_Viscosity mu; /**< Dynamic Viscosity of the fluid.*/ }; } // namespace hazen #endif
31.365217
80
0.703077
barne856
b5befa808059182fe6ed1bf1e778c49c09380dcc
11,293
cpp
C++
Monarch-Connect/Nodeeditor/src/NodeGraphicsObject.cpp
Toms42/Monarch-Connect
3ec456c7812caccc9de4a7f99bd47a16316e7667
[ "MIT" ]
1
2019-02-19T19:33:00.000Z
2019-02-19T19:33:00.000Z
Monarch-Connect/Nodeeditor/src/NodeGraphicsObject.cpp
Toms42/Monarch-Connect
3ec456c7812caccc9de4a7f99bd47a16316e7667
[ "MIT" ]
5
2019-01-09T06:10:02.000Z
2019-02-02T06:31:31.000Z
Monarch-Connect/Nodeeditor/src/NodeGraphicsObject.cpp
Toms42/Monarch-Connect
3ec456c7812caccc9de4a7f99bd47a16316e7667
[ "MIT" ]
null
null
null
#include "NodeGraphicsObject.hpp" #include <cstdlib> #include <iostream> #include <QtWidgets/QGraphicsEffect> #include <QtWidgets/QtWidgets> #include "ConnectionGraphicsObject.hpp" #include "ConnectionState.hpp" #include "FlowScene.hpp" #include "NodePainter.hpp" #include "FlowSceneModel.hpp" #include "NodeConnectionInteraction.hpp" #include "NodeIndex.hpp" #include "StyleCollection.hpp" using QtNodes::ConnectionPolicy; using QtNodes::FlowScene; using QtNodes::Node; using QtNodes::NodeDataType; using QtNodes::NodeGeometry; using QtNodes::NodeGraphicsObject; using QtNodes::NodeIndex; using QtNodes::NodeState; using QtNodes::PortDirection; NodeGraphicsObject::NodeGraphicsObject(FlowScene& scene, NodeIndex const& node) : _scene(scene) , _nodeIndex(node) , _geometry(node, *this) , _state(node) , _locked(false) { _scene.addItem(this); setFlag(QGraphicsItem::ItemDoesntPropagateOpacityToChildren, true); setFlag(QGraphicsItem::ItemIsMovable, true); setFlag(QGraphicsItem::ItemIsFocusable, true); setFlag(QGraphicsItem::ItemIsSelectable, true); setFlag(QGraphicsItem::ItemSendsScenePositionChanges, true); setCacheMode(QGraphicsItem::DeviceCoordinateCache); auto const& nodeStyle = flowScene().model()->nodeStyle(index()); { auto effect = new QGraphicsDropShadowEffect; effect->setOffset(4, 4); effect->setBlurRadius(20); effect->setColor(nodeStyle.ShadowColor); setGraphicsEffect(effect); } setOpacity(nodeStyle.Opacity); setAcceptHoverEvents(true); setZValue(0.); embedQWidget(); // connect to the move signals auto onMoveSlot = [this] { // ask the model to move it if (!flowScene().model()->moveNode(index(), pos())) { // set the location back setPos(flowScene().model()->nodeLocation(index())); moveConnections(); } }; connect(this, &QGraphicsObject::xChanged, this, onMoveSlot); connect(this, &QGraphicsObject::yChanged, this, onMoveSlot); } NodeGraphicsObject::~NodeGraphicsObject() { // TODO I think it is dangerous - user have to delete widget if he allocated // it //if (_proxyWidget) { // delete _proxyWidget->widget(); //} // TODO here can be problem, when item have a parent, then parent remove item // when it will be removed _scene.removeItem(this); } NodeIndex NodeGraphicsObject::index() const { return _nodeIndex; } FlowScene& NodeGraphicsObject::flowScene() { return _scene; } FlowScene const& NodeGraphicsObject::flowScene() const { return _scene; } NodeGeometry& NodeGraphicsObject::geometry() { return _geometry; } NodeGeometry const& NodeGraphicsObject::geometry() const { return _geometry; } NodeState& NodeGraphicsObject::nodeState() { return _state; } NodeState const& NodeGraphicsObject::nodeState() const { return _state; } void NodeGraphicsObject::embedQWidget() { if (auto w = flowScene().model()->nodeWidget(index())) { _proxyWidget = new QGraphicsProxyWidget(this); _proxyWidget->setWidget(w); _proxyWidget->setPreferredWidth(5); geometry().recalculateSize(); _proxyWidget->setPos(geometry().widgetPosition()); update(); _proxyWidget->setOpacity(1.0); _proxyWidget->setFlag(QGraphicsItem::ItemIgnoresParentOpacity); } } QRectF NodeGraphicsObject::boundingRect() const { return geometry().boundingRect(); } void NodeGraphicsObject::moveConnections() const { for (PortDirection portType : { PortDirection::In, PortDirection::Out }) { auto const& connectionEntries = nodeState().getEntries(portType); for (auto const& connections : connectionEntries) { for (auto& con : connections) con->move(); } }; } void NodeGraphicsObject::reactToPossibleConnection(PortDirection reactingPortType, NodeDataType reactingDataType, QPointF const& scenePoint) { QTransform const t = sceneTransform(); QPointF p = t.inverted().map(scenePoint); geometry().setDraggingPosition(p); update(); _state.setReaction(NodeState::REACTING, reactingPortType, reactingDataType); } void NodeGraphicsObject::resetReactionToConnection() { _state.setReaction(NodeState::NOT_REACTING); update(); } void NodeGraphicsObject::lock(bool locked) { _locked = locked; setFlag(QGraphicsItem::ItemIsMovable, !locked); setFlag(QGraphicsItem::ItemIsFocusable, !locked); setFlag(QGraphicsItem::ItemIsSelectable, !locked); } void NodeGraphicsObject::paint(QPainter* painter, QStyleOptionGraphicsItem const* option, QWidget*) { painter->setClipRect(option->exposedRect); NodePainter::paint(painter, *this); } QVariant NodeGraphicsObject::itemChange(GraphicsItemChange change, const QVariant& value) { if (change == ItemPositionChange && scene()) { moveConnections(); } return QGraphicsItem::itemChange(change, value); } void NodeGraphicsObject::mousePressEvent(QGraphicsSceneMouseEvent* event) { if (_locked) return; // deselect all other items after this one is selected if (!isSelected() && !(event->modifiers() & Qt::ControlModifier)) { _scene.clearSelection(); } // if(isSelected()) // { // qDebug() << "selected"; // emit(selectionUpdated()); // } for (PortDirection portToCheck : { PortDirection::In, PortDirection::Out }) { // TODO do not pass sceneTransform PortIndex portIndex = geometry().checkHitScenePoint( portToCheck, event->scenePos(), sceneTransform()); if (portIndex != INVALID) { std::vector<ConnectionGraphicsObject*> connections = nodeState().connections(portToCheck, portIndex); // start dragging existing connection if (!connections.empty() && flowScene().model()->nodePortConnectionPolicy( index(), portIndex, portToCheck) == ConnectionPolicy::One) { Q_ASSERT(connections.size() == 1); auto con = *connections.begin(); // start connecting anew, except start with the port that this // connection was already connected to Q_ASSERT(_scene._temporaryConn == nullptr); if (portToCheck == PortDirection::In) { _scene._temporaryConn = new ConnectionGraphicsObject(con->node(PortDirection::Out), con->portIndex(PortDirection::Out), NodeIndex{}, INVALID, _scene); _scene._temporaryConn->geometry().setEndPoint(PortDirection::In, event->scenePos()); } else { _scene._temporaryConn = new ConnectionGraphicsObject(NodeIndex{}, INVALID, con->node(PortDirection::In), con->portIndex(PortDirection::In), _scene); _scene._temporaryConn->geometry().setEndPoint(PortDirection::Out, event->scenePos()); } _scene._temporaryConn->grabMouse(); // remove it flowScene().model()->removeConnection(con->node(PortDirection::Out), con->portIndex(PortDirection::Out), con->node(PortDirection::In), con->portIndex(PortDirection::In)); } else // initialize new Connection { if (portToCheck == PortDirection::In) { Q_ASSERT(_scene._temporaryConn == nullptr); _scene._temporaryConn = new ConnectionGraphicsObject( NodeIndex{}, INVALID, _nodeIndex, portIndex, _scene); _scene._temporaryConn->geometry().setEndPoint(PortDirection::Out, event->scenePos()); } else { Q_ASSERT(_scene._temporaryConn == nullptr); _scene._temporaryConn = new ConnectionGraphicsObject( _nodeIndex, portIndex, NodeIndex{}, INVALID, _scene); _scene._temporaryConn->geometry().setEndPoint(PortDirection::In, event->scenePos()); } _scene._temporaryConn->grabMouse(); } } } auto pos = event->pos(); if (flowScene().model()->nodeResizable(index()) && geometry().resizeRect().contains(QPoint(pos.x(), pos.y()))) { nodeState().setResizing(true); } } void NodeGraphicsObject::mouseMoveEvent(QGraphicsSceneMouseEvent* event) { if (nodeState().resizing()) { auto diff = event->pos() - event->lastPos(); if (auto w = flowScene().model()->nodeWidget(index())) { auto oldSize = w->size(); oldSize += QSize(diff.x(), diff.y()); w->setFixedSize(oldSize); // We have to recalculdate size before set widgetPosition in proxyWidget geometry().recalculateSize(); _proxyWidget->setMinimumSize(oldSize); _proxyWidget->setMaximumSize(oldSize); _proxyWidget->setPos(geometry().widgetPosition()); moveConnections(); event->accept(); } } else { QGraphicsObject::mouseMoveEvent(event); if (event->lastPos() != event->pos()) moveConnections(); event->ignore(); } // TODO I think we have to set scene rect not here, but in view // QRectF r = scene()->sceneRect(); // r = r.united(mapToScene(boundingRect()).boundingRect()); // scene()->setSceneRect(r); } void NodeGraphicsObject::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { nodeState().setResizing(false); QGraphicsObject::mouseReleaseEvent(event); // position connections precisely after fast node move moveConnections(); } void NodeGraphicsObject::hoverEnterEvent(QGraphicsSceneHoverEvent* event) { // bring all the colliding nodes to background QList<QGraphicsItem*> overlapItems = collidingItems(); for (QGraphicsItem* item : overlapItems) { if (item->zValue() > 0.0) { item->setZValue(0.0); } } // bring this node forward setZValue(1.0); geometry().setHovered(true); update(); flowScene().model()->nodeHovered(index(), event->screenPos(), true); event->accept(); } void NodeGraphicsObject::hoverLeaveEvent(QGraphicsSceneHoverEvent* event) { geometry().setHovered(false); update(); flowScene().model()->nodeHovered(index(), event->screenPos(), false); event->accept(); } void NodeGraphicsObject::hoverMoveEvent(QGraphicsSceneHoverEvent* event) { auto pos = event->pos(); if (flowScene().model()->nodeResizable(index()) && geometry().resizeRect().contains(QPoint(pos.x(), pos.y()))) { setCursor(QCursor(Qt::SizeFDiagCursor)); } else { setCursor(QCursor()); } event->accept(); } void NodeGraphicsObject::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) { QGraphicsItem::mouseDoubleClickEvent(event); flowScene().model()->nodeDoubleClicked(index(), event->screenPos()); } void NodeGraphicsObject::contextMenuEvent(QGraphicsSceneContextMenuEvent* event) { QGraphicsItem::contextMenuEvent(event); flowScene().model()->nodeContextMenu(index(), event->screenPos()); }
26.447307
81
0.647481
Toms42
b5c009d49c579ef5d675ef420b9f3b3af0f3da80
1,002
cpp
C++
src/CrashRptWrapper.cpp
nCine/ncParticleEditor
3e744feb2ece1ec395c02628773e212b18f01162
[ "MIT" ]
7
2019-06-07T07:50:59.000Z
2021-12-10T20:38:48.000Z
src/CrashRptWrapper.cpp
nCine/ncParticleEditor
3e744feb2ece1ec395c02628773e212b18f01162
[ "MIT" ]
null
null
null
src/CrashRptWrapper.cpp
nCine/ncParticleEditor
3e744feb2ece1ec395c02628773e212b18f01162
[ "MIT" ]
3
2019-12-08T11:32:15.000Z
2020-11-26T11:53:25.000Z
#include "CrashRpt.h" #include <stdio.h> #include <tchar.h> #include "CrashRptWrapper.h" int CrashRptWrapper::install() { CR_INSTALL_INFO info; memset(&info, 0, sizeof(CR_INSTALL_INFO)); info.cb = sizeof(CR_INSTALL_INFO); info.pszAppName = _T(CrashRptWrapper::appName); info.pszAppVersion = _T(CrashRptWrapper::appVersion); info.pszEmailSubject = _T(CrashRptWrapper::emailSubject); info.pszEmailTo = _T(CrashRptWrapper::emailTo); info.uPriorities[CR_SMAPI] = 3; // Try send report over Simple MAPI // Install all available exception handlers info.dwFlags |= CR_INST_ALL_POSSIBLE_HANDLERS; // Install crash reporting int nResult = crInstall(&info); if (nResult != 0) { // Something goes wrong. Get error message. TCHAR szErrorMsg[512] = _T(""); crGetLastErrorMsg(szErrorMsg, 512); _tprintf_s(_T("%s\n"), szErrorMsg); return 1; } return 0; } void CrashRptWrapper::uninstall() { crUninstall(); } void CrashRptWrapper::emulateCrash() { crEmulateCrash(CR_SEH_EXCEPTION); }
23.302326
68
0.736527
nCine
b5cbf26352660fff17e1cce2a2ddc092f152345d
1,244
cpp
C++
include/asioext/detail/impl/win_path.cpp
zweistein-frm2/asio-extensions
bafea77c48d674930405cb7f93bdfe65539abc39
[ "BSL-1.0" ]
17
2018-04-13T00:38:55.000Z
2022-01-21T08:38:36.000Z
include/asioext/detail/impl/win_path.cpp
zweistein-frm2/asio-extensions
bafea77c48d674930405cb7f93bdfe65539abc39
[ "BSL-1.0" ]
4
2017-03-16T03:34:38.000Z
2020-05-08T00:05:51.000Z
include/asioext/detail/impl/win_path.cpp
zweistein-frm2/asio-extensions
bafea77c48d674930405cb7f93bdfe65539abc39
[ "BSL-1.0" ]
5
2017-09-06T15:56:04.000Z
2021-09-14T07:38:02.000Z
/// @copyright Copyright (c) 2015 Tim Niederhausen ([email protected]) /// 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) #include "asioext/detail/win_path.hpp" #include "asioext/detail/error.hpp" #include <windows.h> ASIOEXT_NS_BEGIN namespace detail { win_path::win_path(const char* s, std::size_t len, error_code& ec) ASIOEXT_NOEXCEPT : heap_memory_(nullptr) { int new_length; if (len >= kMaxPath) { new_length = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0); heap_memory_ = new (std::nothrow) wchar_t[new_length + 1]; if (!heap_memory_) { ec = asio::error::no_memory; return; } new_length = ::MultiByteToWideChar(CP_UTF8, 0, s, len, heap_memory_, new_length); heap_memory_[new_length] = L'\0'; } else { new_length = ::MultiByteToWideChar(CP_UTF8, 0, s, len, buffer_, kMaxPath); buffer_[new_length] = L'\0'; } if (new_length != 0) { ec = error_code(); } else { ec.assign(::GetLastError(), asio::error::get_system_category()); } } win_path::~win_path() { delete[] heap_memory_; } } ASIOEXT_NS_END
25.387755
91
0.647106
zweistein-frm2
b5cd5ed893535932712ac661a6939930b707839c
12,034
cc
C++
xarm_api/src/xarm_core/instruction/uxbus_cmd.cc
stevewen/xarm_ros
93770d50faf83be627ad16c268c7477ba72187c5
[ "BSD-3-Clause" ]
null
null
null
xarm_api/src/xarm_core/instruction/uxbus_cmd.cc
stevewen/xarm_ros
93770d50faf83be627ad16c268c7477ba72187c5
[ "BSD-3-Clause" ]
null
null
null
xarm_api/src/xarm_core/instruction/uxbus_cmd.cc
stevewen/xarm_ros
93770d50faf83be627ad16c268c7477ba72187c5
[ "BSD-3-Clause" ]
null
null
null
/* Copyright 2017 UFACTORY Inc. All Rights Reserved. * * Software License Agreement (BSD License) * * Author: Jimy Zhang <[email protected]> ============================================================================*/ #include "xarm/instruction/uxbus_cmd.h" #include "xarm/instruction/servo3_config.h" #include "xarm/instruction/uxbus_cmd_config.h" UxbusCmd::UxbusCmd(void) {} UxbusCmd::~UxbusCmd(void) {} int UxbusCmd::check_xbus_prot(u8 *data, u8 funcode) { return -11; } int UxbusCmd::send_pend(u8 funcode, int num, int timeout, u8 *rx_data) { return -11; } int UxbusCmd::send_xbus(u8 funcode, u8 *txdata, int num) { return -11; } void UxbusCmd::close(void) {} int UxbusCmd::set_nu8(u8 funcode, u8 *datas, int num) { int ret = send_xbus(funcode, datas, num); if (ret != 0) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(funcode, 0, UXBUS_CONF::SET_TIMEOUT, NULL); return ret; } int UxbusCmd::get_nu8(u8 funcode, u8 num, u8 *rx_data) { int ret = send_xbus(funcode, 0, 0); if (ret != 0) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(funcode, num, UXBUS_CONF::GET_TIMEOUT, rx_data); return ret; } int UxbusCmd::get_nu16(u8 funcode, u8 num, u16 *rx_data) { u8 datas[num * 2]; int ret = send_xbus(funcode, 0, 0); if (ret != 0) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(funcode, num * 2, UXBUS_CONF::GET_TIMEOUT, datas); for (int i = 0; i < num; i++) rx_data[i] = bin8_to_16(&datas[i * 2]); return ret; } int UxbusCmd::set_nfp32(u8 funcode, fp32 *datas, u8 num) { u8 hexdata[num * 4] = {0}; nfp32_to_hex(datas, hexdata, num); int ret = send_xbus(funcode, hexdata, num * 4); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(funcode, 0, UXBUS_CONF::SET_TIMEOUT, NULL); return ret; } int UxbusCmd::get_nfp32(u8 funcode, u8 num, fp32 *rx_data) { u8 datas[num * 4] = {0}; int ret = send_xbus(funcode, 0, 0); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(funcode, num * 4, UXBUS_CONF::GET_TIMEOUT, datas); hex_to_nfp32(datas, rx_data, num); return ret; } int UxbusCmd::swop_nfp32(u8 funcode, fp32 tx_datas[], u8 txn, fp32 *rx_data, u8 rxn) { u8 hexdata[128] = {0}; nfp32_to_hex(tx_datas, hexdata, txn); int ret = send_xbus(funcode, hexdata, txn * 4); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(funcode, rxn * 4, UXBUS_CONF::GET_TIMEOUT, hexdata); hex_to_nfp32(hexdata, rx_data, rxn); return ret; } int UxbusCmd::is_nfp32(u8 funcode, fp32 datas[], u8 txn, int *value) { u8 hexdata[txn * 4] = {0}; nfp32_to_hex(datas, hexdata, txn); int ret = send_xbus(funcode, hexdata, txn * 4); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(funcode, 1, UXBUS_CONF::GET_TIMEOUT, hexdata); *value = hexdata[0]; return ret; } int UxbusCmd::get_version(u8 rx_data[40]) { return get_nu8(UXBUS_RG::GET_VERSION, 40, rx_data); } int UxbusCmd::motion_en(u8 id, u8 value) { u8 txdata[2]; txdata[0] = id; txdata[1] = value; int ret = set_nu8(UXBUS_RG::MOTION_EN, txdata, 2); return ret; } int UxbusCmd::set_state(u8 value) { u8 txdata[1]; txdata[0] = value; int ret = set_nu8(UXBUS_RG::SET_STATE, txdata, 1); return ret; } int UxbusCmd::get_state(u8 *rx_data) { int ret = get_nu8(UXBUS_RG::GET_STATE, 1, rx_data); return ret; } int UxbusCmd::get_cmdnum(u16 *rx_data) { int ret = get_nu16(UXBUS_RG::GET_CMDNUM, 1, rx_data); return ret; } int UxbusCmd::get_errcode(u8 *rx_data) { int ret = get_nu8(UXBUS_RG::GET_ERROR, 2, rx_data); return ret; } int UxbusCmd::clean_err(void) { u8 txdata[1]; txdata[0] = 0; int ret = set_nu8(UXBUS_RG::CLEAN_ERR, txdata, 0); return ret; } int UxbusCmd::clean_war(void) { u8 txdata[1]; txdata[0] = 0; int ret = set_nu8(UXBUS_RG::CLEAN_WAR, txdata, 0); return ret; } int UxbusCmd::set_brake(u8 axis, u8 en) { u8 txdata[2] = {0}; txdata[0] = axis; txdata[1] = en; int ret = set_nu8(UXBUS_RG::SET_BRAKE, txdata, 2); return ret; } int UxbusCmd::set_mode(u8 value) { u8 txdata[1]; txdata[0] = value; int ret = set_nu8(UXBUS_RG::SET_MODE, txdata, 1); return ret; } int UxbusCmd::move_line(fp32 mvpose[6], fp32 mvvelo, fp32 mvacc, fp32 mvtime) { int i; fp32 txdata[9] = {0}; for (i = 0; i < 6; i++) txdata[i] = mvpose[i]; txdata[6] = mvvelo; txdata[7] = mvacc; txdata[8] = mvtime; int ret = set_nfp32(UXBUS_RG::MOVE_LINE, txdata, 9); return ret; } int UxbusCmd::move_lineb(fp32 mvpose[6], fp32 mvvelo, fp32 mvacc, fp32 mvtime, fp32 mvradii) { int i; fp32 txdata[10] = {0}; for (i = 0; i < 6; i++) txdata[i] = mvpose[i]; txdata[6] = mvvelo; txdata[7] = mvacc; txdata[8] = mvtime; txdata[9] = mvradii; int ret = set_nfp32(UXBUS_RG::MOVE_LINEB, txdata, 10); return ret; } int UxbusCmd::move_joint(fp32 mvjoint[7], fp32 mvvelo, fp32 mvacc, fp32 mvtime) { int i; fp32 txdata[10] = {0}; for (i = 0; i < 7; i++) txdata[i] = mvjoint[i]; txdata[7] = mvvelo; txdata[8] = mvacc; txdata[9] = mvtime; int ret = set_nfp32(UXBUS_RG::MOVE_JOINT, txdata, 10); return ret; } int UxbusCmd::move_gohome(fp32 mvvelo, fp32 mvacc, fp32 mvtime) { fp32 txdata[3] = {0}; txdata[0] = mvvelo; txdata[1] = mvacc; txdata[2] = mvtime; int ret = set_nfp32(UXBUS_RG::MOVE_HOME, txdata, 3); return ret; } int UxbusCmd::move_servoj(fp32 mvjoint[7], fp32 mvvelo, fp32 mvacc, fp32 mvtime) { int i; fp32 txdata[10] = {0}; for (i = 0; i < 7; i++) txdata[i] = mvjoint[i]; txdata[7] = mvvelo; txdata[8] = mvacc; txdata[9] = mvtime; int ret = set_nfp32(UXBUS_RG::MOVE_SERVOJ, txdata, 10); return ret; } int UxbusCmd::sleep_instruction(fp32 sltime) { fp32 txdata[1] = {0}; txdata[0] = sltime; int ret = set_nfp32(UXBUS_RG::SLEEP_INSTT, txdata, 1); return ret; } int UxbusCmd::set_tcp_jerk(fp32 jerk) { fp32 txdata[1] = {0}; txdata[0] = jerk; int ret = set_nfp32(UXBUS_RG::SET_TCP_JERK, txdata, 1); return ret; } int UxbusCmd::set_tcp_maxacc(fp32 maxacc) { fp32 txdata[1] = {0}; txdata[0] = maxacc; int ret = set_nfp32(UXBUS_RG::SET_TCP_MAXACC, txdata, 1); return ret; } int UxbusCmd::set_joint_jerk(fp32 jerk) { fp32 txdata[1] = {0}; txdata[0] = jerk; int ret = set_nfp32(UXBUS_RG::SET_JOINT_JERK, txdata, 1); return ret; } int UxbusCmd::set_joint_maxacc(fp32 maxacc) { fp32 txdata[1] = {0}; txdata[0] = maxacc; int ret = set_nfp32(UXBUS_RG::SET_JOINT_MAXACC, txdata, 1); return ret; } int UxbusCmd::set_tcp_offset(fp32 pose_offset[6]) { return set_nfp32(UXBUS_RG::SET_TCP_OFFSET, pose_offset, 6); } int UxbusCmd::clean_conf() { return set_nu8(UXBUS_RG::CLEAN_CONF, 0, 0); } int UxbusCmd::save_conf() { return set_nu8(UXBUS_RG::SAVE_CONF, 0, 0); } int UxbusCmd::get_tcp_pose(fp32 pose[6]) { return get_nfp32(UXBUS_RG::GET_TCP_POSE, 6, pose); } int UxbusCmd::get_joint_pose(fp32 angles[7]) { return get_nfp32(UXBUS_RG::GET_JOINT_POS, 7, angles); } int UxbusCmd::get_ik(fp32 pose[6], fp32 angles[7]) { return swop_nfp32(UXBUS_RG::GET_IK, pose, 6, angles, 7); } int UxbusCmd::get_fk(fp32 angles[7], fp32 pose[6]) { return swop_nfp32(UXBUS_RG::GET_FK, angles, 7, pose, 6); } int UxbusCmd::is_joint_limit(fp32 joint[7], int *value) { return is_nfp32(UXBUS_RG::IS_JOINT_LIMIT, joint, 7, value); } int UxbusCmd::is_tcp_limit(fp32 pose[6], int *value) { return is_nfp32(UXBUS_RG::IS_TCP_LIMIT, pose, 6, value); } int UxbusCmd::gripper_addr_w16(u8 id, u16 addr, fp32 value) { u8 txdata[7]; txdata[0] = id; bin16_to_8(addr, &txdata[1]); fp32_to_hex(value, &txdata[3]); int ret = send_xbus(UXBUS_RG::GRIPP_W16B, txdata, 7); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(UXBUS_RG::GRIPP_W16B, 0, UXBUS_CONF::GET_TIMEOUT, NULL); return ret; } int UxbusCmd::gripper_addr_r16(u8 id, u16 addr, fp32 *value) { u8 txdata[3], rx_data[4]; txdata[0] = id; bin16_to_8(addr, &txdata[1]); int ret = send_xbus(UXBUS_RG::GRIPP_R16B, txdata, 3); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(UXBUS_RG::GRIPP_R16B, 4, UXBUS_CONF::GET_TIMEOUT, rx_data); *value = bin8_to_16(rx_data); return ret; } int UxbusCmd::gripper_addr_w32(u8 id, u16 addr, fp32 value) { u8 txdata[7]; txdata[0] = id; bin16_to_8(addr, &txdata[1]); fp32_to_hex(value, &txdata[3]); int ret = send_xbus(UXBUS_RG::GRIPP_W32B, txdata, 7); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(UXBUS_RG::GRIPP_W32B, 0, UXBUS_CONF::GET_TIMEOUT, NULL); return ret; } int UxbusCmd::gripper_addr_r32(u8 id, u16 addr, fp32 *value) { u8 txdata[3], rx_data[4]; txdata[0] = id; bin16_to_8(addr, &txdata[1]); int ret = send_xbus(UXBUS_RG::GRIPP_R32B, txdata, 3); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(UXBUS_RG::GRIPP_R32B, 4, UXBUS_CONF::GET_TIMEOUT, rx_data); *value = bin8_to_32(rx_data); return ret; } int UxbusCmd::gripper_set_en(u16 value) { return gripper_addr_w16(UXBUS_CONF::GRIPPER_ID, SERVO3_RG::CON_EN, value); } int UxbusCmd::gripper_set_mode(u16 value) { return gripper_addr_w16(UXBUS_CONF::GRIPPER_ID, SERVO3_RG::CON_MODE, value); } int UxbusCmd::gripper_set_zero() { return gripper_addr_w16(UXBUS_CONF::GRIPPER_ID, SERVO3_RG::MT_ZERO, 1); } int UxbusCmd::gripper_get_pos(fp32 *pulse) { return gripper_addr_r32(UXBUS_CONF::GRIPPER_ID, SERVO3_RG::CURR_POS, pulse); } int UxbusCmd::gripper_set_pos(fp32 pulse) { return gripper_addr_w32(UXBUS_CONF::GRIPPER_ID, SERVO3_RG::TAGET_POS, pulse); } int UxbusCmd::gripper_set_posspd(fp32 speed) { return gripper_addr_w16(UXBUS_CONF::GRIPPER_ID, SERVO3_RG::POS_SPD, speed); } int UxbusCmd::gripper_get_errcode(u8 rx_data[2]) { return get_nu8(UXBUS_RG::GPGET_ERR, 2, rx_data); } int UxbusCmd::gripper_clean_err() { return gripper_addr_w16(UXBUS_CONF::GRIPPER_ID, SERVO3_RG::RESET_ERR, 1); } int UxbusCmd::servo_set_zero(u8 id) { u8 txdata[1]; txdata[0] = id; int ret = set_nu8(UXBUS_RG::SERVO_ZERO, txdata, 1); return ret; } int UxbusCmd::servo_get_dbmsg(u8 rx_data[16]) { int ret = get_nu8(UXBUS_RG::SERVO_DBMSG, 16, rx_data); return ret; } int UxbusCmd::servo_addr_w16(u8 id, u16 addr, fp32 value) { u8 txdata[7]; txdata[0] = id; bin16_to_8(addr, &txdata[1]); fp32_to_hex(value, &txdata[3]); int ret = send_xbus(UXBUS_RG::SERVO_W16B, txdata, 7); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(UXBUS_RG::SERVO_W16B, 0, UXBUS_CONF::GET_TIMEOUT, NULL); return ret; } int UxbusCmd::servo_addr_r16(u8 id, u16 addr, fp32 *value) { u8 txdata[3], rx_data[4]; txdata[0] = id; bin16_to_8(addr, &txdata[1]); int ret = send_xbus(UXBUS_RG::SERVO_R16B, txdata, 3); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(UXBUS_RG::SERVO_R16B, 4, UXBUS_CONF::GET_TIMEOUT, rx_data); *value = bin8_to_16(rx_data); return ret; } int UxbusCmd::servo_addr_w32(u8 id, u16 addr, fp32 value) { u8 txdata[7]; txdata[0] = id; bin16_to_8(addr, &txdata[1]); fp32_to_hex(value, &txdata[3]); int ret = send_xbus(UXBUS_RG::SERVO_W32B, txdata, 7); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(UXBUS_RG::SERVO_W32B, 0, UXBUS_CONF::GET_TIMEOUT, NULL); return ret; } int UxbusCmd::servo_addr_r32(u8 id, u16 addr, fp32 *value) { u8 txdata[3], rx_data[4]; txdata[0] = id; bin16_to_8(addr, &txdata[1]); int ret = send_xbus(UXBUS_RG::SERVO_R32B, txdata, 3); if (0 != ret) return UXBUS_STATE::ERR_NOTTCP; ret = send_pend(UXBUS_RG::SERVO_R32B, 4, UXBUS_CONF::GET_TIMEOUT, rx_data); *value = bin8_to_32(rx_data); return ret; }
28.248826
80
0.650241
stevewen
b5cd79a05b721e64c5f9a08ccd37f1c95e5f6e76
3,585
cc
C++
crypto/uuid.cc
stablecc/scclib
cedcb3b37a814d3a393e128db7aa9753f518cbaf
[ "BSD-3-Clause" ]
null
null
null
crypto/uuid.cc
stablecc/scclib
cedcb3b37a814d3a393e128db7aa9753f518cbaf
[ "BSD-3-Clause" ]
10
2022-02-27T18:52:11.000Z
2022-03-21T14:11:35.000Z
crypto/uuid.cc
stablecc/scclib
cedcb3b37a814d3a393e128db7aa9753f518cbaf
[ "BSD-3-Clause" ]
null
null
null
/* BSD 3-Clause License Copyright (c) 2022, Stable Cloud Computing, Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <crypto/uuid.h> #include <ctype.h> #include <algorithm> #include <vector> #include <string> #include <sstream> #include <crypto/random.h> #include <encode/hex.h> using namespace scc::crypto; using scc::encode::Hex; std::ostream& operator <<(std::ostream& os, const Uuid& u) { return os.write(u.val().c_str(), u.val().size()); } void scc::crypto::PrintTo(const Uuid& u, std::ostream* os) { *os << u; } const std::string Uuid::zero = "00000000-0000-0000-0000-000000000000"; void Uuid::assign(const std::string& s) { std::stringstream str(s); std::string tok; std::vector<std::string> v; while (std::getline(str, tok, '-')) { v.push_back(tok); } if (v.size() != 5) { m_uuid = zero; return; } if (v[0].size() != 8) { m_uuid = zero; return; } if (v[1].size() != 4) { m_uuid = zero; return; } if (v[2].size() != 4) { m_uuid = zero; return; } if (v[3].size() != 4) { m_uuid = zero; return; } if (v[4].size() != 12) { m_uuid = zero; return; } for (auto& x : v) { for (auto b : x) { if ( ((b<'0')||(b>'9')) && ((b<'a')||(b>'f')) && ((b<'A')||(b>'F')) ) { m_uuid = zero; return; } } } // NOTE: does not check for binary requirements m_uuid = s; std::for_each(m_uuid.begin(), m_uuid.end(), [](char& c) { c = tolower(c); }); } std::string Uuid::generate() { std::vector<char> u(16); RandomEngine::rand_bytes(&u[0], 16); // set most significant bits of time_hi_and_version (octet 6) to 0100 (version) u[6] &= 0x4f; u[6] |= 0x40; // set most significant bits of clock_seq_hi_and_reserved (octet 8) to 01 u[8] &= 0x7f; u[8] |= 0x40; // emit hex HxHxHxHx-HxHx-HxHx-HxHx-HxHxHxHxHxHx std::stringstream uuid; typedef std::vector<char> CharVec; uuid << Hex::bin_to_hex(CharVec(&u[0], &u[4])); uuid << "-"; uuid << Hex::bin_to_hex(CharVec(&u[4], &u[6])); uuid << "-"; uuid << Hex::bin_to_hex(CharVec(&u[6], &u[8])); uuid << "-"; uuid << Hex::bin_to_hex(CharVec(&u[8], &u[10])); uuid << "-"; uuid << Hex::bin_to_hex(CharVec(&u[10], &u[16])); m_uuid = uuid.str(); return m_uuid; }
28.228346
80
0.67894
stablecc
b5cda330eefe38e66510d1bc15d4e51a916d1222
543
hpp
C++
liboh/include/oh/ProxyLightObject.hpp
princeofcode/sirikata
41d33a574934aea2d8a30ce3514509b7a4ec182e
[ "BSD-3-Clause" ]
1
2016-05-09T07:55:37.000Z
2016-05-09T07:55:37.000Z
liboh/include/oh/ProxyLightObject.hpp
princeofcode/sirikata
41d33a574934aea2d8a30ce3514509b7a4ec182e
[ "BSD-3-Clause" ]
null
null
null
liboh/include/oh/ProxyLightObject.hpp
princeofcode/sirikata
41d33a574934aea2d8a30ce3514509b7a4ec182e
[ "BSD-3-Clause" ]
null
null
null
#ifndef _SIRIKATA_PROXY_LIGHT_OBJECT_HPP_ #define _SIRIKATA_PROXY_LIGHT_OBJECT_HPP_ #include "LightListener.hpp" #include "ProxyPositionObject.hpp" namespace Sirikata { /** * This class represents a ProxyObject that holds a LightInfo */ class SIRIKATA_OH_EXPORT ProxyLightObject : public MarkovianProvider1<LightListenerPtr,LightInfo>, public ProxyPositionObject { public: ProxyLightObject():MarkovianProvider1<LightListenerPtr,LightInfo>(LightInfo()){} void update(const LightInfo &li) { notify(li); } }; } #endif
27.15
84
0.779006
princeofcode
b5cdb76ac53f7881584cc514459e4a5c2d0db674
3,520
cpp
C++
ThreadTaxi.cpp
MapleStoryGameHack/Deprecated-RwBox-Plus
df927665c316b43791c4b72e2ac8a00789d05877
[ "MIT" ]
1
2021-07-11T13:01:57.000Z
2021-07-11T13:01:57.000Z
ThreadTaxi.cpp
MapleStoryGameHack/Deprecated-RwBox-Plus
df927665c316b43791c4b72e2ac8a00789d05877
[ "MIT" ]
null
null
null
ThreadTaxi.cpp
MapleStoryGameHack/Deprecated-RwBox-Plus
df927665c316b43791c4b72e2ac8a00789d05877
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- #pragma hdrstop #include "Map.h"; #include "ThreadTaxi.h" #include "Pointer.h" #include "Function.h" #include "WindowHook.h" //--------------------------------------------------------------------------- TThreadTaxi* ThreadTaxi ; __fastcall TThreadTaxi::TThreadTaxi(bool CreateSuspended ,long sMap,long eMap , MLPROC proc) : TThread(CreateSuspended) { this->proc = proc; isRunning = true; this->sMap = sMap; this->eMap = eMap; } void __fastcall TThreadTaxi::Start() { } void __fastcall TThreadTaxi::TaxiGo(long sMap , long eMap) { this->sMap = sMap; this->eMap = eMap; status = TaxiStart; } TThreadTaxi::TaxiStatus TThreadTaxi::GetTaxiStatus() { return this->status; } void __fastcall TThreadTaxi::TaxiControl( long* & tmp) { long cmap = ReadPointer(MapBase,MapIDOffset); long hp; POINT pt; if( (*tmp) == sMap) // FirstTime { GetTeleportPoint(*tmp,*(tmp+1),pt); proc(1,*tmp,*(tmp+1)); TeleXY(true,pt.x,pt.y-5); tmp++; GetTeleportPoint(*tmp,*(tmp+1),pt); SetXY(true,pt.x,pt.y); Sleep(200); SendKey(hWndMS, VK_UP); while( *(DWORD*)PeopleBase != 0 && this->isRunning) { SetXY(true,pt.x,pt.y); SendKey(hWndMS, VK_UP); Sleep(100); } if(! this->isRunning) return; while( *(DWORD*)PeopleBase == 0 && this->isRunning) Sleep(100); if(! this->isRunning) return; if(*tmp != eMap) tmp++; Sleep(500); } else { GetTeleportPoint(*tmp,*(tmp+1),pt); proc(1,*tmp,*(tmp+1)); SetXY(true,pt.x,pt.y); Sleep(200); while( *(DWORD*)PeopleBase == 0 && this->isRunning) Sleep(100); if( cmap != *(tmp-1)) { delete tmp; sMap = cmap; tmp = SearchMapPath(sMap, eMap); Sleep(100); return; } SendKey(hWndMS, VK_UP); SetXY(true,pt.x,pt.y); Sleep(200); while( *(DWORD*)PeopleBase != 0 && this->isRunning) { SetXY(true,pt.x,pt.y); SendKey(hWndMS, VK_UP); Sleep(100); } if(! this->isRunning) return; while( *(DWORD*)PeopleBase == 0 && this->isRunning) Sleep(100); if(! this->isRunning) return; if(*tmp != eMap) tmp++; Sleep(500); } } void __fastcall TThreadTaxi::Execute() { proc(0,0,0); long *path = SearchMapPath(sMap, eMap); long *tmp = path; POINT pt; String name; status = TaxiStart; if( *tmp != eMap ) { while( *tmp != eMap && (status != TaxiStop && status != TaxiError ) && this->isRunning) { TaxiControl(tmp); } long cmap = ReadPointer(MapBase,MapIDOffset); if( *tmp == eMap && cmap != eMap ) { Sleep(700); SendKey(hWndMS, VK_UP); while( *(DWORD*)PeopleBase != 0 && this->isRunning) Sleep(100); while( *(DWORD*)PeopleBase == 0 && this->isRunning) Sleep(100); } } long cmap = ReadPointer(MapBase,MapIDOffset); if( cmap != eMap){ proc(-2,0,0); } Terminate(); } void __fastcall TThreadTaxi::Terminate() { proc(-1,0,0); this->isRunning = false; } void __fastcall TThreadTaxi::SetXY( bool s , int x, int y) { WritePointer(SystemBase,SpawnSwitchOffset,s); WritePointer(SystemBase,SpawnXOffset,x); WritePointer(SystemBase,SpawnYOffset,y); } void __fastcall TThreadTaxi::TeleXY( bool s , int x, int y) { WritePointer(PeopleBase,PeopleTeleX,x); WritePointer(PeopleBase,PeopleTeleY,y); WritePointer(PeopleBase,PeopleTeleSW,s); } #pragma package(smart_init)
21.728395
93
0.578977
MapleStoryGameHack
b5ce5589a216c73c7dcfc97d020e48d119c9b4cc
622
cc
C++
codeforces/1130/b.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
506
2018-08-22T10:30:38.000Z
2022-03-31T10:01:49.000Z
codeforces/1130/b.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
13
2019-08-07T18:31:18.000Z
2020-12-15T21:54:41.000Z
codeforces/1130/b.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
234
2018-08-06T17:11:41.000Z
2022-03-26T10:56:42.000Z
// https://codeforces.com/contest/1130/problem/B #include<bits/stdc++.h> using namespace std; using ll=long long; using vi=vector<ll>; using vvi=vector<vi>; int main(){ ios::sync_with_stdio(0); cin.tie(0); ll n; cin>>n; vvi a(n); for(ll i=0;i<2*n;i++){ ll x; cin>>x; x--; a[x].push_back(i); } ll x=0,y=0; ll k=0; for(ll i=0;i<n;i++){ ll p1=a[i][0]; ll p2=a[i][1]; if(llabs(p1-x)+llabs(p2-y)<=llabs(p2-x)+llabs(p1-y)){ k+=llabs(p1-x)+llabs(p2-y); x=p1; y=p2; }else{ k+=llabs(p1-y)+llabs(p2-x); x=p2; y=p1; } } cout<<k<<endl; }
17.277778
57
0.512862
Ashindustry007
b5d09e10d87dd250f44f3d9d73afb41ca07c0cb9
1,028
hpp
C++
Keys.hpp
dnasdw/ctrcdnfetch
f3a4dcfd5f6e615635e1acea8746cd67e5e83643
[ "MIT" ]
1
2020-10-26T17:13:32.000Z
2020-10-26T17:13:32.000Z
Keys.hpp
dnasdw/ctrcdnfetch
f3a4dcfd5f6e615635e1acea8746cd67e5e83643
[ "MIT" ]
null
null
null
Keys.hpp
dnasdw/ctrcdnfetch
f3a4dcfd5f6e615635e1acea8746cd67e5e83643
[ "MIT" ]
null
null
null
#ifndef __KEYS_HPP__ #define __KEYS_HPP__ #include "types.h" namespace NintendoData { namespace KeyUtils { namespace Storage { enum KeyType { KeyX, KeyY, KeyNormal }; void ReloadStorage(); const u8* GetKey(int keyslot, KeyType type = KeyX, bool retail = true); const u8* GetKeyX(int keyslot, bool retail = true) {return GetKey(keyslot, KeyX, retail);} const u8* GetKeyY(int keyslot, bool retail = true) {return GetKey(keyslot, KeyY, retail);} const u8* GetKeyNormal(int keyslot, bool retail = true) {return GetKey(keyslot, KeyNormal, retail);} } bool Scrambler(u8* outnormal, const u8* KeyX, const u8* KeyY); bool Scrambler(u8* outnormal, int keyslotX, const u8* keyY, bool retail = true) { return Scrambler(outnormal, Storage::GetKeyX(keyslotX, retail), keyY); } bool Scrambler(u8* outnormal, const u8* keyX, int keyslotY, bool retail = true) { return Scrambler(outnormal, keyX, Storage::GetKeyY(keyslotY, retail)); } void SeedKeyY(u8* keyY, const u8* seed); } } #endif
35.448276
103
0.703307
dnasdw
b5d1b131006a5d8e01b001fb277f2fd11aaf7080
1,411
cpp
C++
tests/module/object_test.cpp
mambaru/wfc
170bf87302487c0cedc40b47c84447a765894774
[ "MIT" ]
1
2018-10-18T10:15:53.000Z
2018-10-18T10:15:53.000Z
tests/module/object_test.cpp
mambaru/wfc
170bf87302487c0cedc40b47c84447a765894774
[ "MIT" ]
7
2019-12-04T23:36:03.000Z
2021-04-21T12:37:07.000Z
tests/module/object_test.cpp
mambaru/wfc
170bf87302487c0cedc40b47c84447a765894774
[ "MIT" ]
null
null
null
#define IOW_DISABLE_LOG #include <iow/logger.hpp> #include <wfc/domain_object.hpp> #include <wfc/module/instance.hpp> #include <wfc/module/singleton.hpp> #include <wfc/module/multiton.hpp> #include <fas/utility/ignore_args.hpp> struct itest: public wfc::iinterface { ~itest(){} }; struct options { int test = 33; }; struct options_json { JSON_NAME(test) typedef wfc::json::object< options, fas::type_list_n< wfc::json::member<n_test, options, int, &options::test> >::type > type; typedef typename type::serializer serializer; typedef typename type::member_list member_list; typedef typename type::target target; }; class test: public ::wfc::domain_object<itest, options> { }; JSON_NAME2(name_test, "test") class test_singleton : public ::wfc::singleton< name_test, ::wfc::instance<test>, options_json > {}; class test_multiton : public ::wfc::multiton< name_test, ::wfc::instance<test>, options_json > {}; template<typename T> int test_gen() { T t; t.create(nullptr); std::cout << "[" << t.interface_name() << "]" << std::endl; std::string genstr = t.generate(""); std::cout << genstr << std::endl; t.configure(genstr, nullptr); if (t.name()!="test") return 1; return 0; } int main() { options opt; opt.test=0; fas::ignore_arg(opt); int res = test_gen<test_singleton>(); res += test_gen<test_multiton>(); return res; }
18.565789
77
0.669029
mambaru
b5d417695dc6a5ef7d643a1cf3c2f9178f0f0f48
18,707
cpp
C++
gearoenix/render/graph/tree/gx-rnd-gr-tr-pbr.cpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
35
2018-01-07T02:34:38.000Z
2022-02-09T05:19:03.000Z
gearoenix/render/graph/tree/gx-rnd-gr-tr-pbr.cpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
111
2017-09-20T09:12:36.000Z
2020-12-27T12:52:03.000Z
gearoenix/render/graph/tree/gx-rnd-gr-tr-pbr.cpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
5
2020-02-11T11:17:37.000Z
2021-01-08T17:55:43.000Z
#include "gx-rnd-gr-tr-pbr.hpp" #include "../../../core/asset/gx-cr-asset-manager.hpp" #include "../../../core/sync/gx-cr-sync-kernel-workers.hpp" #include "../../../physics/gx-phs-engine.hpp" #include "../../../system/gx-sys-application.hpp" #include "../../camera/gx-rnd-cmr-perspective.hpp" #include "../../engine/gx-rnd-eng-engine.hpp" #include "../../light/gx-rnd-lt-cascade-info.hpp" #include "../../light/gx-rnd-lt-directional.hpp" #include "../../reflection/gx-rnd-rfl-runtime.hpp" #include "../../scene/gx-rnd-scn-manager.hpp" #include "../../skybox/gx-rnd-sky-cube.hpp" #include "../../skybox/gx-rnd-sky-equirectangular.hpp" #include "../../texture/gx-rnd-txt-target.hpp" #include "../node/gx-rnd-gr-nd-forward-pbr.hpp" #include "../node/gx-rnd-gr-nd-irradiance-convoluter.hpp" #include "../node/gx-rnd-gr-nd-mipmap-generator.hpp" #include "../node/gx-rnd-gr-nd-radiance-convoluter.hpp" #include "../node/gx-rnd-gr-nd-shadow-mapper.hpp" #include "../node/gx-rnd-gr-nd-skybox-cube.hpp" #include "../node/gx-rnd-gr-nd-skybox-equirectangular.hpp" #include "../node/gx-rnd-gr-nd-unlit.hpp" #define GX_START_TASKS \ unsigned int task_number = 0; \ const unsigned int kernels_count = e->get_kernels()->get_threads_count(); #define GX_DO_TASK(expr) \ { \ if (task_number == kernel_index) { \ expr; \ } \ task_number = (task_number + 1) % kernels_count; \ } void gearoenix::render::graph::tree::Pbr::CameraData::clear() noexcept { skyboxes.clear(); opaques.forward_pbr = nullptr; opaques.unlit = nullptr; transparencies.clear(); } void gearoenix::render::graph::tree::Pbr::update_camera( const scene::Scene* const scn, camera::Camera* const cam, graph::tree::Pbr::CameraData& camera_nodes) noexcept { camera_nodes.clear(); update_skyboxes(scn, cam, camera_nodes); update_opaque(cam->get_seen_static_opaque_meshes(), scn, cam, camera_nodes); update_opaque(cam->get_seen_dynamic_opaque_meshes(), scn, cam, camera_nodes); update_transparent(cam->get_seen_transparent_meshes(), scn, cam, camera_nodes); for (auto& c : cam->get_cascades()) { cascades.push_back(&c); } } void gearoenix::render::graph::tree::Pbr::update_skyboxes(const scene::Scene* const scn, const camera::Camera* const cam, CameraData& camera_nodes) noexcept { node::SkyboxCube* previous_cube = nullptr; node::SkyboxEquirectangular* previous_equirectangular = nullptr; for (const auto& id_skybox : scn->get_skyboxs()) { const auto* const sky = id_skybox.second.get(); if (!sky->get_enabled()) continue; switch (sky->get_skybox_type()) { case skybox::Type::Equirectangular: previous_cube = nullptr; if (previous_equirectangular == nullptr) { previous_equirectangular = skybox_equirectangular.get_next([this] { auto* const n = new node::SkyboxEquirectangular("pbr-sky-equ", e, GX_DEFAULT_IGNORED_END_CALLER); n->set_render_target(e->get_main_render_target().get()); return n; }); camera_nodes.skyboxes[sky->get_layer()].push_back(previous_equirectangular); } previous_equirectangular->update(); previous_equirectangular->set_camera(cam); previous_equirectangular->add_sky(reinterpret_cast<const skybox::Equirectangular*>(sky)); break; case skybox::Type::Cube: previous_equirectangular = nullptr; if (previous_cube == nullptr) { previous_cube = skybox_cube.get_next([this] { auto* const n = new node::SkyboxCube("pbr-sky-cube", e, GX_DEFAULT_IGNORED_END_CALLER); n->set_render_target(e->get_main_render_target().get()); return n; }); camera_nodes.skyboxes[sky->get_layer()].push_back(previous_cube); } previous_cube->update(); previous_cube->set_camera(cam); previous_cube->add_sky(reinterpret_cast<const skybox::Cube*>(sky)); break; default: GX_UNEXPECTED } } } void gearoenix::render::graph::tree::Pbr::update_runtime_reflection(const scene::Scene* const scn) noexcept { const auto& runtime_reflections = scn->get_runtime_reflections(); for (const auto& id_rtr : runtime_reflections) { auto* const rtr = id_rtr.second.get(); if (!rtr->get_enabled()) continue; switch (rtr->get_state()) { case reflection::Runtime::State::EnvironmentCubeRender: { if (rtr->get_state_environment_face() == 0) { runtime_reflections_data.emplace(rtr, RuntimeReflectionData(rtr->get_radiance_convoluters()[0].size())); } auto& rtr_nodes = runtime_reflections_data.find(rtr)->second; const auto& cam = rtr->get_cameras()[rtr->get_state_environment_face()]; auto& rtr_face_nodes = rtr_nodes.faces[rtr->get_state_environment_face()]; rtr_face_nodes.cam = cam.get(); update_camera(scn, rtr_face_nodes.cam, rtr_face_nodes.camera_data); break; } case reflection::Runtime::State::EnvironmentCubeMipMap: { auto& rtr_nodes = runtime_reflections_data.find(rtr)->second; rtr_nodes.environment_mipmap_generator = rtr->get_environment_mipmap_generator().get(); rtr_nodes.environment_mipmap_generator->update(); rtr_nodes.irradiance_mipmap_generator = rtr->get_irradiance_mipmap_generator().get(); rtr_nodes.irradiance_mipmap_generator->update(); break; } case reflection::Runtime::State::IrradianceFace: { const auto fi = rtr->get_state_irradiance_face(); auto& irradiance = runtime_reflections_data.find(rtr)->second.faces[fi].irradiance; irradiance = rtr->get_irradiance_convoluters()[fi].get(); irradiance->update(); break; } case reflection::Runtime::State::IrradianceMipMap: { auto& rtr_nodes = runtime_reflections_data.find(rtr)->second; rtr_nodes.irradiance_mipmap_generator = rtr->get_irradiance_mipmap_generator().get(); rtr_nodes.irradiance_mipmap_generator->update(); break; } case reflection::Runtime::State::RadianceFaceLevel: { auto& rtr_nodes = runtime_reflections_data.find(rtr)->second; const auto& radiances = rtr->get_radiance_convoluters(); const auto fi = rtr->get_state_radiance_face(); auto& rtr_face_nodes = rtr_nodes.faces[fi]; const auto& face_radiances = radiances[fi]; const auto li = rtr->get_state_radiance_level(); auto* const radiance = face_radiances[li].get(); rtr_face_nodes.radiances[li] = radiance; radiance->update(); break; } default: return; } } } void gearoenix::render::graph::tree::Pbr::update_opaque( const std::vector<std::tuple<double, material::Type, model::Model*, model::Mesh*>>& seen_meshes, const scene::Scene* const scn, const camera::Camera* const cam, CameraData& camera_nodes) noexcept { node::ForwardPbr* fwd = camera_nodes.opaques.forward_pbr; if (fwd == nullptr) { fwd = forward_pbr.get_next([this] { return new node::ForwardPbr("pbr-fwd-pbr", e, GX_DEFAULT_IGNORED_END_CALLER); }); fwd->update(); fwd->set_scene(scn); fwd->set_camera(cam); const auto& cs = cam->get_cascades(); for (auto& cascade : cs) { fwd->add_cascade(&cascade); } camera_nodes.opaques.forward_pbr = fwd; } node::Unlit* unl = camera_nodes.opaques.unlit; if (unl == nullptr) { unl = unlit.get_next([this] { return new node::Unlit("pbr-tree-unlit", e, GX_DEFAULT_IGNORED_END_CALLER); }); unl->update(); unl->set_camera(cam); camera_nodes.opaques.unlit = unl; } for (const auto& [dis, material_id, model_ptr, mesh_ptr] : seen_meshes) { switch (material_id) { case material::Type::Pbr: { fwd->add_mesh(std::make_pair(model_ptr, mesh_ptr)); break; } case material::Type::Unlit: { unl->add_mesh(std::make_pair(model_ptr, mesh_ptr)); break; } default: GX_UNEXPECTED } } } void gearoenix::render::graph::tree::Pbr::update_transparent( const std::vector<std::tuple<double, material::Type, model::Model*, model::Mesh*>>& seen_meshes, const scene::Scene* scn, const camera::Camera* cam, CameraData& camera_nodes) noexcept { const auto& cs = cam->get_cascades(); node::ForwardPbr* fwd = nullptr; node::Unlit* unl = nullptr; for (const auto& [dis, mat_type, mdl, msh] : seen_meshes) { switch (mat_type) { case material::Type::Pbr: { unl = nullptr; if (fwd == nullptr) { fwd = forward_pbr.get_next([this] { auto* const n = new node::ForwardPbr( "pbr-tree-pbr", e, core::sync::EndCaller<core::sync::EndCallerIgnore>([] {})); n->set_render_target(e->get_main_render_target().get()); return n; }); camera_nodes.transparencies.push_back(fwd); fwd->update(); fwd->set_scene(scn); fwd->set_camera(cam); for (auto& c : cs) { fwd->add_cascade(&c); } } fwd->add_mesh({ mdl, msh }); break; } case material::Type::Unlit: { fwd = nullptr; if (unl == nullptr) { unl = unlit.get_next([this] { auto* const n = new node::Unlit( "pbr-tree-unlit", e, core::sync::EndCaller<core::sync::EndCallerIgnore>([] {})); n->set_render_target(e->get_main_render_target().get()); return n; }); camera_nodes.transparencies.push_back(unl); unl->update(); unl->set_camera(cam); } unl->add_mesh({ mdl, msh }); break; } default: GX_UNEXPECTED } (void)dis; } } void gearoenix::render::graph::tree::Pbr::record_runtime_reflection( const scene::Scene* const scn, unsigned int& task_number, const unsigned int kernel_index, const unsigned int kernels_count) noexcept { const auto& runtime_reflections = scn->get_runtime_reflections(); for (const auto& id_rtr : runtime_reflections) { auto* const rtr = id_rtr.second.get(); if (!rtr->get_enabled()) continue; auto id_rtr_data = runtime_reflections_data.find(rtr); if (runtime_reflections_data.end() == id_rtr_data) continue; auto& runtime_reflection = id_rtr_data->second; switch (rtr->get_state()) { case reflection::Runtime::State::EnvironmentCubeRender: { const auto& face = runtime_reflection.faces[rtr->get_state_environment_face()]; for (const auto& skies : face.camera_data.skyboxes) { for (auto* const sky : skies.second) { GX_DO_TASK(sky->record_continuously(kernel_index)) } } const auto& opaques = face.camera_data.opaques; if (opaques.forward_pbr != nullptr) opaques.forward_pbr->record(kernel_index); if (opaques.unlit != nullptr) opaques.unlit->record(kernel_index); for (auto* const node : face.camera_data.transparencies) { GX_DO_TASK(node->record_continuously(kernel_index)) } break; } case reflection::Runtime::State::EnvironmentCubeMipMap: { GX_DO_TASK(runtime_reflection.environment_mipmap_generator->record_continuously(kernel_index)) break; } case reflection::Runtime::State::IrradianceFace: { GX_DO_TASK(runtime_reflection.faces[rtr->get_state_irradiance_face()].irradiance->record_continuously(kernel_index)) break; } case reflection::Runtime::State::IrradianceMipMap: { GX_DO_TASK(runtime_reflection.irradiance_mipmap_generator->record_continuously(kernel_index)) break; } case reflection::Runtime::State::RadianceFaceLevel: { GX_DO_TASK(runtime_reflection.faces[rtr->get_state_radiance_face()].radiances[rtr->get_state_radiance_level()]->record_continuously(kernel_index)) break; } default: return; } } } void gearoenix::render::graph::tree::Pbr::submit_camera_data(const CameraData& camera_data) const noexcept { for (const auto& skies : camera_data.skyboxes) for (auto* const sky : skies.second) sky->submit(); const auto& opaques = camera_data.opaques; if (opaques.forward_pbr != nullptr) opaques.forward_pbr->submit(); if (opaques.unlit != nullptr) opaques.unlit->submit(); for (auto* const node : camera_data.transparencies) node->submit(); } void gearoenix::render::graph::tree::Pbr::submit_runtime_reflections(const scene::Scene* const scn) noexcept { const auto& runtime_reflections = scn->get_runtime_reflections(); for (const auto& id_rtr : runtime_reflections) { auto* const rtr = id_rtr.second.get(); if (!rtr->get_enabled()) continue; auto id_rtr_data = runtime_reflections_data.find(rtr); if (runtime_reflections_data.end() != id_rtr_data) { auto& runtime_reflection = id_rtr_data->second; switch (rtr->get_state()) { case reflection::Runtime::State::EnvironmentCubeRender: submit_camera_data(runtime_reflection.faces[rtr->get_state_environment_face()].camera_data); break; case reflection::Runtime::State::EnvironmentCubeMipMap: runtime_reflection.environment_mipmap_generator->submit(); break; case reflection::Runtime::State::IrradianceFace: runtime_reflection.faces[rtr->get_state_irradiance_face()].irradiance->submit(); break; case reflection::Runtime::State::IrradianceMipMap: runtime_reflection.irradiance_mipmap_generator->submit(); break; case reflection::Runtime::State::RadianceFaceLevel: { auto* const radiance_node = runtime_reflection.faces[rtr->get_state_radiance_face()].radiances[rtr->get_state_radiance_level()]; if (nullptr != radiance_node) radiance_node->submit(); break; } default: break; } } rtr->update_state(); } } gearoenix::render::graph::tree::Pbr::Pbr(engine::Engine* const e, const core::sync::EndCaller<core::sync::EndCallerIgnore>&) noexcept : Tree(e) , in_weak_hardware(engine::Type::OpenGLES2 == e->get_engine_type()) { } gearoenix::render::graph::tree::Pbr::~Pbr() noexcept { GXLOGD("Pbr render tree deleted.") } void gearoenix::render::graph::tree::Pbr::update() noexcept { forward_pbr.refresh(); skybox_cube.refresh(); skybox_equirectangular.refresh(); unlit.refresh(); nodes.clear(); cascades.clear(); const auto& priorities_scenes = e->get_physics_engine()->get_sorted_scenes(); for (const auto& priority_scenes : priorities_scenes) { const double scene_priority = priority_scenes.first; auto& scene_priority_nodes = nodes[scene_priority]; const scene::Scene* const scn = priority_scenes.second.get(); auto& scene_nodes = scene_priority_nodes[scn]; update_runtime_reflection(scn); const auto& cameras = scn->get_cameras(); for (const auto& id_camera : cameras) { auto* const cam = id_camera.second.get(); const double camera_priority = cam->get_layer(); auto& camera_priority_nodes = scene_nodes.cameras[camera_priority]; CameraData& camera_nodes = camera_priority_nodes[cam]; update_camera(scn, cam, camera_nodes); } } } void gearoenix::render::graph::tree::Pbr::record(const unsigned int kernel_index) noexcept { GX_START_TASKS for (auto* const cas : cascades) { cas->record(kernel_index); } for (const auto& priority_scenes : nodes) { for ([[maybe_unused]] const auto& [scn, scene_data] : priority_scenes.second) { record_runtime_reflection(scn, task_number, kernel_index, kernels_count); for (const auto& priority_cameras : scene_data.cameras) { for (const auto& cam_camera_nodes : priority_cameras.second) { const CameraData& camera_nodes = cam_camera_nodes.second; for (const auto& skies : camera_nodes.skyboxes) for (auto* const sky : skies.second) GX_DO_TASK(sky->record_continuously(kernel_index)) const auto& opaques = camera_nodes.opaques; if (opaques.forward_pbr != nullptr) opaques.forward_pbr->record(kernel_index); if (opaques.unlit != nullptr) opaques.unlit->record(kernel_index); for (auto* const node : camera_nodes.transparencies) GX_DO_TASK(node->record_continuously(kernel_index)) } } } } } void gearoenix::render::graph::tree::Pbr::submit() noexcept { for (auto* cas : cascades) { cas->submit(); } for (auto& priority_scenes : nodes) { for (const auto& [scn, scene_data] : priority_scenes.second) { submit_runtime_reflections(scn); for ([[maybe_unused]] const auto& [priority, cameras] : scene_data.cameras) { for ([[maybe_unused]] const auto& [cam, camera_data] : cameras) { submit_camera_data(camera_data); } } } } }
41.943946
158
0.600043
Hossein-Noroozpour
b5e06ebbf8a12bc929daf4a1551f54864f3ecc8a
1,230
cpp
C++
Longest Subarray of 1's After Deleting One Element.cpp
PoojaRani24/Leetcode_Monthly_Challenge
9ad56cb332b33bf8ce1c4ef5e64f92a1599e598b
[ "MIT" ]
null
null
null
Longest Subarray of 1's After Deleting One Element.cpp
PoojaRani24/Leetcode_Monthly_Challenge
9ad56cb332b33bf8ce1c4ef5e64f92a1599e598b
[ "MIT" ]
null
null
null
Longest Subarray of 1's After Deleting One Element.cpp
PoojaRani24/Leetcode_Monthly_Challenge
9ad56cb332b33bf8ce1c4ef5e64f92a1599e598b
[ "MIT" ]
null
null
null
class Solution { public: int longestSubarray(vector<int>& nums) { vector<pair<int,int>>v; int count=0; for(int i=0;i<nums.size();){ if(nums[i]==0) i++; else{ int start=i; int c=0; while(i<nums.size() && nums[i]==1) { i++; c++; } v.push_back({start,i-1}); if(c>count) count=c; } } for(int i=0;i<v.size();i++) cout<<v[i].first<<" "<<v[i].second<<endl; if(v.size()==0) return 0; else if(v.size()==1){ if(v[0].second-v[0].first+1==nums.size()) return nums.size()-1; else return v[0].second-v[0].first+1; } else{ for(int i=0;i<v.size()-1;i++){ if(v[i+1].first-v[i].second>2)continue; else { if(v[i+1].second-v[i].first>count) count=v[i+1].second-v[i].first; } } return count; } //return 0; } };
26.73913
55
0.339837
PoojaRani24
b5e3847310e58f59993c42ded3f4625891223f52
1,062
cpp
C++
CsPlugin/Source/CsEditor/Public/DetailCustomizations/EnumStruct/Team/ECsTeamCustomization.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
2
2019-03-17T10:43:53.000Z
2021-04-20T21:24:19.000Z
CsPlugin/Source/CsEditor/Public/DetailCustomizations/EnumStruct/Team/ECsTeamCustomization.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
CsPlugin/Source/CsEditor/Public/DetailCustomizations/EnumStruct/Team/ECsTeamCustomization.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
// Copyright 2017-2021 Closed Sum Games, LLC. All Rights Reserved. #include "DetailCustomizations/EnumStruct/Team/ECsTeamCustomization.h" // Types #include "Team/CsTypes_Team.h" #define LOCTEXT_NAMESPACE "ECsTeamCustomization" #define EnumMapType EMCsTeam #define EnumType FECsTeam FECsTeamCustomization::FECsTeamCustomization() : Super() { Init<EnumMapType, EnumType>(); } TSharedRef<IPropertyTypeCustomization> FECsTeamCustomization::MakeInstance() { return MakeShareable(new FECsTeamCustomization); } void FECsTeamCustomization::SetPropertyHandles(TSharedRef<IPropertyHandle> StructPropertyHandle) { SetPropertyHandles_Internal<EnumType>(StructPropertyHandle); } void FECsTeamCustomization::SetEnumWithDisplayName(const FString& DisplayName) { SetEnumWithDisplayName_Internal<EnumMapType, EnumType>(DisplayName); } void FECsTeamCustomization::GetDisplayNamePropertyValue(FString& OutDisplayName) const { GetDisplayNamePropertyValue_Internal<EnumMapType, EnumType>(OutDisplayName); } #undef EnumMapType #undef EnumType #undef LOCTEXT_NAMESPACE
25.285714
96
0.834275
closedsum
b5e4860f8b8f0f766cdf780d3f4708b774d987ed
3,264
hpp
C++
include/Pomdog/Graphics/DepthStencilDescription.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
include/Pomdog/Graphics/DepthStencilDescription.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
include/Pomdog/Graphics/DepthStencilDescription.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2015 mogemimi. // Distributed under the MIT license. See LICENSE.md file for details. #ifndef POMDOG_DEPTHSTENCILDESCRIPTION_E14C5D77_HPP #define POMDOG_DEPTHSTENCILDESCRIPTION_E14C5D77_HPP #include "ComparisonFunction.hpp" #include "DepthStencilOperation.hpp" #include "Pomdog/Basic/Export.hpp" #include <cstdint> #include <limits> namespace Pomdog { struct POMDOG_EXPORT DepthStencilDescription { DepthStencilOperation ClockwiseFace; DepthStencilOperation CounterClockwiseFace; std::int32_t ReferenceStencil; std::uint32_t StencilMask; std::uint32_t StencilWriteMask; ComparisonFunction DepthBufferFunction; bool DepthBufferEnable; bool DepthBufferWriteEnable; bool StencilEnable; static DepthStencilDescription CreateDefault() { return CreateReadWriteDepth(); } static DepthStencilDescription CreateReadWriteDepth() { DepthStencilDescription desc; desc.DepthBufferEnable = true; desc.DepthBufferWriteEnable = true; desc.StencilEnable = false; desc.DepthBufferFunction = ComparisonFunction::LessEqual; desc.ReferenceStencil = 0; desc.StencilMask = std::numeric_limits<std::uint32_t>::max(); desc.StencilWriteMask = std::numeric_limits<std::uint32_t>::max(); DepthStencilOperation defaultOperation = { StencilOperation::Keep, StencilOperation::Keep, StencilOperation::Keep, ComparisonFunction::Always }; desc.ClockwiseFace = defaultOperation; desc.CounterClockwiseFace = defaultOperation; return desc; } static DepthStencilDescription CreateReadOnlyDepth() { DepthStencilDescription desc; desc.DepthBufferEnable = true; desc.DepthBufferWriteEnable = false; desc.StencilEnable = false; desc.DepthBufferFunction = ComparisonFunction::LessEqual; desc.ReferenceStencil = 0; desc.StencilMask = std::numeric_limits<std::uint32_t>::max(); desc.StencilWriteMask = std::numeric_limits<std::uint32_t>::max(); DepthStencilOperation defaultOperation = { StencilOperation::Keep, StencilOperation::Keep, StencilOperation::Keep, ComparisonFunction::Always }; desc.ClockwiseFace = defaultOperation; desc.CounterClockwiseFace = defaultOperation; return desc; } static DepthStencilDescription CreateNone() { DepthStencilDescription desc; desc.DepthBufferEnable = false; desc.DepthBufferWriteEnable = false; desc.StencilEnable = false; desc.DepthBufferFunction = ComparisonFunction::LessEqual; desc.ReferenceStencil = 0; desc.StencilMask = std::numeric_limits<std::uint32_t>::max(); desc.StencilWriteMask = std::numeric_limits<std::uint32_t>::max(); DepthStencilOperation defaultOperation = { StencilOperation::Keep, StencilOperation::Keep, StencilOperation::Keep, ComparisonFunction::Always }; desc.ClockwiseFace = defaultOperation; desc.CounterClockwiseFace = defaultOperation; return desc; } }; } // namespace Pomdog #endif // POMDOG_DEPTHSTENCILDESCRIPTION_E14C5D77_HPP
35.478261
74
0.704044
bis83
b5ece2947cc73f1bb321c8c8e02d09bc2888ca5f
1,916
cpp
C++
src/SolarChargeSystem/lib/SerialReceiver/SerialReceiver.cpp
jack96013/Solar-Charge-System
e64c5fece5bff9b7a7f1c7d9b92235ed9e391812
[ "MIT" ]
null
null
null
src/SolarChargeSystem/lib/SerialReceiver/SerialReceiver.cpp
jack96013/Solar-Charge-System
e64c5fece5bff9b7a7f1c7d9b92235ed9e391812
[ "MIT" ]
null
null
null
src/SolarChargeSystem/lib/SerialReceiver/SerialReceiver.cpp
jack96013/Solar-Charge-System
e64c5fece5bff9b7a7f1c7d9b92235ed9e391812
[ "MIT" ]
null
null
null
#include "SerialReceiver.h" SerialReceiver::SerialReceiver() { } void SerialReceiver::begin(Stream& serial,uint16_t bufferLength) { this->serial = &serial; receiveBufferLength = bufferLength; receiveBuffer.reserve(bufferLength + 1); //serial.println("Ready !"); } void SerialReceiver::run() { serialCheck(); } void SerialReceiver::serialCheck() { bool receiveFinishFlag = false; while (serial->available()) { // 一個字節一個字節地讀,下一句是讀到的放入字符串數組中組成一個完成的數據包 char incomingByte = serial->read(); // 緩衝區已滿 if (receiveBuffer.length() >= receiveBufferLength) { receiveBuffer = ""; } receiveBuffer += (char)incomingByte; // 將字元一個個串接 if (incomingByte == SM_ENDMARK) { receiveFinishFlag = true; break; } } if (receiveFinishFlag) { if (receiveBuffer.length() > 0) { // remove /r /n removeLineEnding(receiveBuffer); #ifdef SM_DEBUG serial->println(receiveBuffer); #endif onReceiveCallbackInvoke(); } receiveBuffer = ""; } } // Remove Line Ending void SerialReceiver::removeLineEnding(String &str) { // Remove \n \r if (str.endsWith("\n")) str.remove(str.length() - 1); ; if (str.endsWith("\r")) str.remove(str.length() - 1); } void SerialReceiver::onReceiveCallbackInvoke() { if (onReceiveCallback != nullptr) onReceiveCallback(onReceiveCallbackArg,receiveBuffer); } void SerialReceiver::setOnReceiveCallback(OnReceiveCallback callback,void* arg) { this->onReceiveCallback = callback; this->onReceiveCallbackArg = arg; } void SerialReceiver::clearBuffer() { receiveBuffer = ""; serial->flush(); } String* SerialReceiver::getBuffer() { return &receiveBuffer; }
20.602151
79
0.600731
jack96013
b5eec152c2d814fe6deada75cf753da496deb74c
362
cpp
C++
Source/MarchingCubes/MarchingCubesGameModeBase.cpp
Styvak/Marching-Cubes-UE4
2ef8266f0a63294fbd1789724281b4d87e9b8daa
[ "MIT" ]
2
2020-04-19T12:07:33.000Z
2020-05-15T21:17:48.000Z
Source/MarchingCubes/MarchingCubesGameModeBase.cpp
Styvak/Marching-Cubes-UE4
2ef8266f0a63294fbd1789724281b4d87e9b8daa
[ "MIT" ]
null
null
null
Source/MarchingCubes/MarchingCubesGameModeBase.cpp
Styvak/Marching-Cubes-UE4
2ef8266f0a63294fbd1789724281b4d87e9b8daa
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "MarchingCubesGameModeBase.h" #include "BlockManager.h" void AMarchingCubesGameModeBase::InitGame(const FString& MapName, const FString& Options, FString& ErrorMessage) { Super::InitGame(MapName, Options, ErrorMessage); BlockManager::GetInstance()->RegisterBlocks(); }
30.166667
112
0.792818
Styvak
b5f031cd0c6b4408ae9cc3709dfb9e10e6935c84
2,228
hpp
C++
combinator/aggregate.hpp
kindone/proptest
174981600571b75bbd9ed69f56453c9994d2878c
[ "MIT" ]
null
null
null
combinator/aggregate.hpp
kindone/proptest
174981600571b75bbd9ed69f56453c9994d2878c
[ "MIT" ]
null
null
null
combinator/aggregate.hpp
kindone/proptest
174981600571b75bbd9ed69f56453c9994d2878c
[ "MIT" ]
null
null
null
#pragma once #include "../Shrinkable.hpp" #include "../Random.hpp" #include "../GenBase.hpp" #include "../util/function_traits.hpp" #include "../util/std.hpp" #include "../generator/integral.hpp" /** * @file aggregate.hpp * @brief Generator combinator for aggregating sequencially generated values into a value with a generator generator */ namespace proptest { namespace util { template <typename T> Generator<T> aggregateImpl(GenFunction<T> gen1, function<GenFunction<T>(T&)> gen2gen, size_t minSize, size_t maxSize) { auto gen1Ptr = util::make_shared<decltype(gen1)>(gen1); auto gen2genPtr = util::make_shared<function<GenFunction<T>(const T&)>>( [gen2gen](const T& t) { return gen2gen(const_cast<T&>(t)); }); return interval<uint64_t>(minSize, maxSize).flatMap<T>([gen1Ptr, gen2genPtr](uint64_t& size) { return Generator<T>([gen1Ptr, gen2genPtr, size](Random& rand) { Shrinkable<T> shr = (*gen1Ptr)(rand); for (size_t i = 0; i < size; i++) shr = (*gen2genPtr)(shr.get())(rand); return shr; }); }); } } // namespace util /** * @ingroup Combinators * @brief Generator combinator for aggregating a value of type T from a generator generator * @tparam GEN1 Generator type of (Random&) -> Shrinkable<T> * @tparam GEN2GEN (T&) -> ((Random&) -> Shrinkable<T>) (Generator for T) * @param gen1 base generator for type T * @param gen2gen function that returns a generator for type T based on previously generated value of the same type * @param minSize minimum size of the aggregate steps * @param maxSize maximum size of the aggregate steps * @return last generated value of T throughout the aggregation */ template <typename GEN1, typename GEN2GEN> decltype(auto) aggregate(GEN1&& gen1, GEN2GEN&& gen2gen, size_t minSize, size_t maxSize) { using T = typename invoke_result_t<GEN1, Random&>::type; // get the T from shrinkable<T>(Random&) using RetType = invoke_result_t<GEN2GEN, T&>; // GEN2GEN's return type GenFunction<T> funcGen1 = gen1; function<RetType(T&)> funcGen2Gen = gen2gen; return util::aggregateImpl<T>(funcGen1, funcGen2Gen, minSize, maxSize); } } // namespace proptest
37.762712
117
0.686266
kindone
b5f3921e8c1e683e8363151dbf1fc343f6525cc2
502
cpp
C++
src/nimbro/motion/gait_engines/feed_gait/src/kinematics/feed_kinematics_base.cpp
ssr-yuki/humanoid_op_ros
e8be8c445ead8c0d470c7998fdc28446ca9eb47a
[ "BSD-3-Clause" ]
45
2015-11-04T01:29:12.000Z
2022-02-11T05:37:42.000Z
src/nimbro/motion/gait_engines/feed_gait/src/kinematics/feed_kinematics_base.cpp
ssr-yuki/humanoid_op_ros
e8be8c445ead8c0d470c7998fdc28446ca9eb47a
[ "BSD-3-Clause" ]
1
2016-08-10T04:00:32.000Z
2016-08-10T12:59:36.000Z
src/nimbro/motion/gait_engines/feed_gait/src/kinematics/feed_kinematics_base.cpp
ssr-yuki/humanoid_op_ros
e8be8c445ead8c0d470c7998fdc28446ca9eb47a
[ "BSD-3-Clause" ]
20
2016-03-05T14:28:45.000Z
2021-01-30T00:50:47.000Z
// Feedback gait kinematics base class // Author: Philipp Allgeuer <[email protected]> // Includes #include <feed_gait/kinematics/feed_kinematics_base.h> // Namespaces using namespace feed_gait; // // FeedKinematicsBase class // // Gait halt pose function: PoseCommand void FeedKinematicsBase::getHaltPose(PoseCommand& haltPose) const { // Calculate the required halt pose getHaltPose(haltPose.pos); getHaltPoseEffort(haltPose.effort); getHaltPoseSuppCoeff(haltPose.suppCoeff); } // EOF
22.818182
65
0.782869
ssr-yuki
b5f41904025ba35fbe68d8a502804c774be8181a
191
hpp
C++
src/AudioLib/EffectType.hpp
CircuitMess/JayD-Library
f90bbb72224681a972cd2b535f80925a3319e631
[ "MIT" ]
2
2021-08-19T17:23:46.000Z
2021-10-10T17:11:04.000Z
src/AudioLib/EffectType.hpp
CircuitMess/JayD-Library
f90bbb72224681a972cd2b535f80925a3319e631
[ "MIT" ]
null
null
null
src/AudioLib/EffectType.hpp
CircuitMess/JayD-Library
f90bbb72224681a972cd2b535f80925a3319e631
[ "MIT" ]
1
2021-11-21T16:02:06.000Z
2021-11-21T16:02:06.000Z
#ifndef JAYD_LIBRARY_EFFECTTYPE_HPP #define JAYD_LIBRARY_EFFECTTYPE_HPP enum EffectType { NONE, SPEED, LOWPASS, HIGHPASS, REVERB, BITCRUSHER, COUNT }; #endif //JAYD_LIBRARY_EFFECTTYPE_HPP
21.222222
58
0.82199
CircuitMess
b5f4e469e002fba53bf7f9bdfcccb3e86bcabefa
2,552
cpp
C++
uva/uva1588/main.cpp
oklen/my-soluation
56d6c32f0a328332b090f9d633365b75605f4616
[ "MIT" ]
null
null
null
uva/uva1588/main.cpp
oklen/my-soluation
56d6c32f0a328332b090f9d633365b75605f4616
[ "MIT" ]
null
null
null
uva/uva1588/main.cpp
oklen/my-soluation
56d6c32f0a328332b090f9d633365b75605f4616
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> using namespace std; constexpr int intsize = sizeof(int); int fillstr(char *ar) { int count = 0; char cache = getchar(); if(cache == EOF) exit(0); while(cache!='\n') { ar[count++] = cache; cache = getchar(); } return count; } int fillstrb(char *ar) { int count = 0; char cache = getchar(); if(cache == EOF) exit(0); while(cache!='\n') { if(cache=='1') ar[count++] = '2'; else ar[count++] = '1'; cache = getchar(); } return count; } int mycmp(char *a,char *b,int le) { int i =0; while (i<le) { if(*(a+i) == '2' && *(b+i) == '2') return 1; i++; } return 0; } int main() { char at[100]; char ag[100]; char *aa = at; char *ab = ag; int count = 0,aal,abl; memset(aa,0,100*sizeof(char)); memset(ab,0,100*sizeof(char)); while(!cin.eof()) { abl = fillstr(ab); aal = fillstr(aa); if(abl < aal) { char* cache = ab; ab = aa; aa = cache; int c = abl; abl = aal; aal = c; } int shift = 0,comparesize,apos; int min = abl+aal; while(++shift < aal+abl) { if(shift<aal) { comparesize = shift; apos = aal - shift; } else if (shift >abl) { comparesize = aal - shift + abl; apos = 0; } else { comparesize = aal; apos = 0; } // cout << shift <<"Compare:" // <<strndup(aa+apos,comparesize) << ":" << strndup(ab+(shift>aal?shift-aal:0),comparesize) // << endl; if(mycmp(aa+apos,ab+(shift>aal?shift-aal:0),comparesize) == 0) { if(shift < aal && min > abl+aal-shift) { min = abl+aal-shift; // cout << "1 cae" << endl; } else if(shift > abl && min > shift) { min = shift; // cout << "2 cae" << endl; } else if(shift <= abl && shift>=aal) { min = abl; // cout << "min" << endl; } } } cout << min << endl; } }
22
107
0.375
oklen
b5f673fb80ce02ef3b53323ff159b7c8e8907e38
1,197
cpp
C++
Records.cpp
pmwasson/LightCycle
42e9b7e0fe0e17ee231f43577b222288306be238
[ "MIT" ]
2
2019-12-07T19:37:31.000Z
2020-03-18T13:33:46.000Z
Records.cpp
pmwasson/LightCycle
42e9b7e0fe0e17ee231f43577b222288306be238
[ "MIT" ]
null
null
null
Records.cpp
pmwasson/LightCycle
42e9b7e0fe0e17ee231f43577b222288306be238
[ "MIT" ]
1
2020-06-30T15:46:03.000Z
2020-06-30T15:46:03.000Z
#include "Records.h" void Records::validate() { if (checksum != calcChecksum()) { edgeRaceMinutes = 99; edgeRaceSeconds = 0; edgeRaceSeed = 0xFADED; crazyCourierScore = 0; crazyCourierSeed = 0xDECAF; checksum = calcChecksum(); } } bool Records::setER(uint32_t seed, uint8_t minutes, uint8_t seconds) { if ((minutes < edgeRaceMinutes) || ((minutes == edgeRaceMinutes) && (seconds < edgeRaceSeconds))) { edgeRaceMinutes = minutes; edgeRaceSeconds = seconds; edgeRaceSeed = seed; checksum = calcChecksum(); return true; } else { return false; } } bool Records::setCC(uint32_t seed, uint16_t score) { if (score > crazyCourierScore) { crazyCourierScore = score; crazyCourierSeed = seed; checksum = calcChecksum(); return true; } else { return false; } } uint8_t Records::calcChecksum() { return 0x58 ^ edgeRaceMinutes ^ edgeRaceSeconds ^ edgeRaceSeed ^ (edgeRaceSeed >> 8) ^ (edgeRaceSeed >> 16) ^ crazyCourierScore ^ (crazyCourierScore >> 8) ^ crazyCourierSeed ^ (crazyCourierSeed >> 8) ^ (crazyCourierSeed >> 16); }
23.019231
101
0.619048
pmwasson
b5fd38e38aba66f3e4f63ed577a561d4dfae7516
3,079
cpp
C++
redis-cli/command.cpp
mobile-pos/amp
efe4eb4fda1e6f1ad2ee6113c3bf0a9a61068763
[ "MIT" ]
6
2020-09-12T08:16:46.000Z
2020-11-19T04:05:35.000Z
redis-cli/command.cpp
mobile-pos/amp
efe4eb4fda1e6f1ad2ee6113c3bf0a9a61068763
[ "MIT" ]
null
null
null
redis-cli/command.cpp
mobile-pos/amp
efe4eb4fda1e6f1ad2ee6113c3bf0a9a61068763
[ "MIT" ]
2
2020-12-11T02:27:56.000Z
2021-11-18T02:15:01.000Z
#include "command.h" using namespace Redis; Command::Command(QString commandName, QObject *parent) : QObject(parent), commandName(commandName) { arguments << commandName; } void Command::addArgument(QVariant argument) { arguments << argument; } void Command::addArgumentStrings(QStringList arguments) { foreach (QString argument, arguments) { addArgument(argument); } } QString Command::getCommandName() { return arguments[0].toString(); } QVariantList Command::getArguments() { return arguments; } Command* Command::HKEYS(QString key) { Command *command = new Command("HKEYS"); command->addArgument(key); return command; } Command *Command::Auth(QString auth) { Command *command = new Command("AUTH"); command->addArgument(auth); return command; } Command *Command::HGETALL(QString key) { Command *command = new Command("HGETALL"); command->addArgument(key); return command; } Command *Command::HGET(QString key, QString field) { Command *command = new Command("HGET"); command->addArgument(key); command->addArgument(field); return command; } Command *Command::HSET(QString key, QString field, QString value) { Command *command = new Command("HSET"); command->addArgument(key); command->addArgument(field); command->addArgument(value); return command; } Command *Command::HDEL(QString key, QString field) { Command *command = new Command("HDEL"); command->addArgument(key); command->addArgument(field); return command; } Command *Command::SET(QString key, QString value) { Command *command = new Command("SET"); command->addArgument(key); command->addArgument(value); return command; } Command *Command::GET(QString key) { Command *command = new Command("GET"); command->addArgument(key); return command; } Command *Command::DEL(QStringList keys) { Command *command = new Command("DEL"); command->addArgumentStrings(keys); return command; } Command *Command::EXPIRE(QString key, int seconds) { Command *command = new Command("EXPIRE"); command->addArgument(key); command->addArgument(seconds); return command; } Command *Command::KEYS(QString pattern) { Command *command = new Command("KEYS"); command->addArgument(pattern); return command; } Command *Command::LPUSH(QString key, QStringList values) { Command *command = new Command("LPUSH"); command->addArgument(key); command->addArgumentStrings(values); return command; } Command *Command::RPOP(QString key) { Command *command = new Command("RPOP"); command->addArgument(key); return command; } Command *Command::SUBSCRIBE(QStringList channels) { Command *command = new Command("SUBSCRIBE"); command->addArgumentStrings(channels); return command; } Command* Command::PUBLISH(QString channel, QString value) { Command *command = new Command("PUBLISH"); command->addArgument(channel); command->addArgument(value); return command; }
18.889571
73
0.683664
mobile-pos
bd0403e8ed23cf7df3d81530bfdbea5c6b1f7840
1,564
cpp
C++
tools/deps/MachoParser/src/MachoTools.cpp
streamwater/HookZz
b09b89ea520c442142bf93b32c1a92b082715d59
[ "Apache-2.0" ]
4
2019-04-23T14:44:50.000Z
2020-11-05T06:52:37.000Z
tools/deps/MachoParser/src/MachoTools.cpp
streamwater/HookZz
b09b89ea520c442142bf93b32c1a92b082715d59
[ "Apache-2.0" ]
null
null
null
tools/deps/MachoParser/src/MachoTools.cpp
streamwater/HookZz
b09b89ea520c442142bf93b32c1a92b082715d59
[ "Apache-2.0" ]
4
2019-04-23T08:26:33.000Z
2021-09-21T07:45:19.000Z
// Copyright 2017 jmpews // // 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 "MachoTools.h" #ifdef __cplusplus extern "C" { #endif #include "zzdeps/common/LEB128.h" #include "zzdeps/common/debugbreak.h" #include "zzdeps/darwin/memory-utils-darwin.h" #ifdef __cplusplus } #endif #include "parsers/ObjcRuntime.h" #include "zz.h" void PrintClassInfo(objc_class_info_t *objc_class_info) { if (!objc_class_info) return; Xinfo("Class Name: %s, Address: %p", objc_class_info->class_name, (zpointer)objc_class_info->class_vmaddr); objc_method_infos_t *objc_method_infos; objc_method_infos = &(objc_class_info->objc_method_infos); std::vector<objc_method_info_t *>::iterator iter; objc_method_info_t *objc_method_info; for (iter = objc_method_infos->begin(); iter != objc_method_infos->end(); iter++) { objc_method_info = (*iter); Xinfo("- %s, %p", objc_method_info->method_name, (zpointer)objc_method_info->method_vmaddr); } }
30.666667
78
0.698849
streamwater
bd0594d47c0c5ad4f3923d2845466807efb29609
707
cpp
C++
2nd/378_kth_smallest_element_in_a_sorted_matrix.cpp
buptlxb/leetcode
b641419de040801c4f54618d7ee26edcf10ee53c
[ "BSD-3-Clause" ]
null
null
null
2nd/378_kth_smallest_element_in_a_sorted_matrix.cpp
buptlxb/leetcode
b641419de040801c4f54618d7ee26edcf10ee53c
[ "BSD-3-Clause" ]
null
null
null
2nd/378_kth_smallest_element_in_a_sorted_matrix.cpp
buptlxb/leetcode
b641419de040801c4f54618d7ee26edcf10ee53c
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <algorithm> using namespace std; class Solution { public: int kthSmallest(vector<vector<int>>& matrix, int k) { if (matrix.empty()) return 0; int left = matrix[0][0], right = matrix.back().back(); while (left < right) { int cnt = 0; int mid = left + (right - left) / 2; for (int i = 0; i < matrix.size(); ++i) cnt += distance( matrix[i].begin(), upper_bound(matrix[i].begin(), matrix[i].end(), mid)); if (cnt < k) left = mid + 1; else right = mid; } return left; } }; int main(void) { return 0; }
23.566667
106
0.472419
buptlxb
bd07027f10655ddf7e7644cece5a940dd0649e0d
7,191
cpp
C++
ShaderGLLib/Material.cpp
EPAC-Saxon/advance-obj-JulienBaumgartner
884aaf5a960f4f9575b0e9028b3234eacbfbb75b
[ "MIT" ]
null
null
null
ShaderGLLib/Material.cpp
EPAC-Saxon/advance-obj-JulienBaumgartner
884aaf5a960f4f9575b0e9028b3234eacbfbb75b
[ "MIT" ]
null
null
null
ShaderGLLib/Material.cpp
EPAC-Saxon/advance-obj-JulienBaumgartner
884aaf5a960f4f9575b0e9028b3234eacbfbb75b
[ "MIT" ]
null
null
null
#include "Material.h" #include <iterator> #include <fstream> #include <sstream> namespace sgl { std::map<std::string, std::shared_ptr<Material>> LoadMaterialsFromMtl(std::string file) { std::map<std::string, std::shared_ptr<Material>> materials; std::ifstream ifs; ifs.open(file, std::ifstream::in); if (!ifs.is_open()) { throw std::runtime_error("Couldn't open file: " + file); } std::shared_ptr<Material> material; std::string name; while (!ifs.eof()) { std::string line = ""; if (!std::getline(ifs, line)) break; if (line.empty()) continue; std::istringstream iss(line); std::string dump; if (!(iss >> dump)) { throw std::runtime_error( "Error parsing file: " + file + " no token found."); } if (dump == "newmtl") { if (material != nullptr) { materials[name] = material; } if (!(iss >> name)) { throw std::runtime_error( "Error parsing file : " + file + " no name found in newmtl."); } material = std::make_shared<Material>(name); } else if (dump == "map_Ka") { std::string path; if (!(iss >> path)) { throw std::runtime_error( "Error parsing file : " + file + " no path found in map_Ka."); } material->SetAmbientTexture(std::make_shared<Texture>(path)); } else if (dump == "map_Kd") { std::string path; if (!(iss >> path)) { throw std::runtime_error( "Error parsing file : " + file + " no path found in map_Kd."); } material->SetDiffuseTexture(std::make_shared<Texture>(path)); } else if (dump == "map_norm") { std::string path; if (!(iss >> path)) { throw std::runtime_error( "Error parsing file : " + file + " no path found in map_norm."); } material->SetNormalTexture(std::make_shared<Texture>(path)); } else if (dump == "map_Pm") { std::string path; if (!(iss >> path)) { throw std::runtime_error( "Error parsing file : " + file + " no path found in map_Pm."); } material->SetMetallicTexture(std::make_shared<Texture>(path)); } else if (dump == "map_Pr") { std::string path; if (!(iss >> path)) { throw std::runtime_error( "Error parsing file : " + file + " no path found in map_Pr."); } material->SetRoughnessTexture(std::make_shared<Texture>(path)); } else if (dump == "d") { float alpha; if (!(iss >> alpha)) { throw std::runtime_error( "Error parsing file : " + file + " no value found in d."); } material->SetAlpha(alpha); } else if (dump == "illum") { float illum; if (!(iss >> illum)) { throw std::runtime_error( "Error parsing file : " + file + " no value found in illum."); } material->SetIllum(illum); } else if (dump == "Ka") { float v[3]; if (!(iss >> v[0])) { throw std::runtime_error( "Error parsing file : " + file + " no r found in Ka."); } if (!(iss >> v[1])) { throw std::runtime_error( "Error parsing file : " + file + " no g found in Ka."); } if (!(iss >> v[2])) { throw std::runtime_error( "Error parsing file : " + file + " no b found in Ka."); } material->CreateAmbientTexture(v); } else if (dump == "Kd") { float v[3]; if (!(iss >> v[0])) { throw std::runtime_error( "Error parsing file : " + file + " no r found in Kd."); } if (!(iss >> v[1])) { throw std::runtime_error( "Error parsing file : " + file + " no g found in Kd."); } if (!(iss >> v[2])) { throw std::runtime_error( "Error parsing file : " + file + " no b found in Kd."); } material->CreateDiffuseTexture(v); } else if (dump == "norm") { float v[3]; if (!(iss >> v[0])) { throw std::runtime_error( "Error parsing file : " + file + " no r found in norm."); } if (!(iss >> v[1])) { throw std::runtime_error( "Error parsing file : " + file + " no g found in norm."); } if (!(iss >> v[2])) { throw std::runtime_error( "Error parsing file : " + file + " no b found in norm."); } material->CreateNormalTexture(v); } else if (dump == "Pm") { float v; if (!(iss >> v)) { throw std::runtime_error( "Error parsing file : " + file + " no value found in Pm."); } material->CreateMetallicTexture(&v); } else if (dump == "Pr") { float v; if (!(iss >> v)) { throw std::runtime_error( "Error parsing file : " + file + " no value found in Pr."); } material->CreateRoughnessTexture(&v); } } materials[name] = material; return materials; } Material::Material(std::string name) : name_(name) { } void Material::SetAmbientTexture(std::shared_ptr<Texture> texture) { ambient_texture_ = texture; } void Material::SetDiffuseTexture(std::shared_ptr<Texture> texture) { diffuse_texture_ = texture; } void Material::SetNormalTexture(std::shared_ptr<Texture> texture) { normal_texture_ = texture; } void Material::SetMetallicTexture(std::shared_ptr<Texture> texture) { metallic_texture_ = texture; } void Material::SetRoughnessTexture(std::shared_ptr<Texture> texture) { roughness_texture_ = texture; } void Material::SetAlpha(float alpha) { alpha_ = alpha; } void Material::SetIllum(float illum) { illum_ = illum; } void Material::CreateAmbientTexture(void* data) { ambient_texture_ = std::make_shared<Texture>(std::pair(1,1), data, PixelElementSize::FLOAT, PixelStructure::RGB); } void Material::CreateDiffuseTexture(void* data) { diffuse_texture_ = std::make_shared<Texture>(std::pair(1, 1), data, PixelElementSize::FLOAT, PixelStructure::RGB); } void Material::CreateNormalTexture(void* data) { normal_texture_ = std::make_shared<Texture>(std::pair(1, 1), data, PixelElementSize::FLOAT, PixelStructure::RGB); } void Material::CreateMetallicTexture(void* data) { metallic_texture_ = std::make_shared<Texture>(std::pair(1, 1), data, PixelElementSize::FLOAT, PixelStructure::GREY); } void Material::CreateRoughnessTexture(void* data) { roughness_texture_ = std::make_shared<Texture>(std::pair(1, 1), data, PixelElementSize::FLOAT, PixelStructure::GREY); } void Material::AddTextures(TextureManager& texture_manager) { texture_manager.AddTexture(name_ + "Ambient", ambient_texture_); texture_manager.AddTexture(name_ + "Diffuse", diffuse_texture_); texture_manager.AddTexture(name_ + "Normal", normal_texture_); texture_manager.AddTexture(name_ + "Metallic", metallic_texture_); texture_manager.AddTexture(name_ + "Roughness", roughness_texture_); } std::vector<std::string> Material::GetTexturesName() { std::vector<std::string> names; names.push_back(name_ + "Ambient"); names.push_back(name_ + "Diffuse"); names.push_back(name_ + "Normal"); names.push_back(name_ + "Metallic"); names.push_back(name_ + "Roughness"); return names; } }
22.54232
119
0.590738
EPAC-Saxon
bd07c25d6feec31f895d37fbd5aa4cc862c65811
1,578
cpp
C++
ModernOpenGLUdemy/main.cpp
killerasus/ModernOpenGL
3bde26a468e945282cd0f8366939bd6c2730ab05
[ "MIT" ]
2
2019-10-16T00:05:57.000Z
2019-10-16T00:17:25.000Z
ModernOpenGLUdemy/main.cpp
killerasus/ModernOpenGL
3bde26a468e945282cd0f8366939bd6c2730ab05
[ "MIT" ]
null
null
null
ModernOpenGLUdemy/main.cpp
killerasus/ModernOpenGL
3bde26a468e945282cd0f8366939bd6c2730ab05
[ "MIT" ]
null
null
null
#include <iostream> #include <GL/glew.h> #include <GLFW/glfw3.h> const GLint WIDTH = 800, HEIGHT = 600; int main() { if (!glfwInit()) { std::cout << "GLFW initialization failed!" << std::endl; glfwTerminate(); return 1; } // Setup GLFW window properties // OpenGL version glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // Core profile - No backwards compatibility glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Allow forward compatibility glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); GLFWwindow* mainWindow = glfwCreateWindow(WIDTH, HEIGHT, "Test Window", nullptr, nullptr); if (mainWindow == nullptr) { std::cout << "GLFW window creation failed!" << std::endl; glfwTerminate(); return 1; } // Get buffer size information int bufferWidth = -1, bufferHeight = -1; glfwGetFramebufferSize(mainWindow, &bufferWidth, &bufferHeight); // Set context for GLEW to use glfwMakeContextCurrent(mainWindow); // Allow modern extension features glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { std::cout << "GLEW initialization failed!" << std::endl; glfwDestroyWindow(mainWindow); glfwTerminate(); return 1; } // Setup viewport size glViewport(0, 0, bufferWidth, bufferHeight); // Loop until window closed while (!glfwWindowShouldClose(mainWindow)) { // Get and handle user input events glfwPollEvents(); // Clear window glClearColor(1.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glfwSwapBuffers(mainWindow); } return 0; }
22.542857
91
0.720532
killerasus
bd0c7f26e20517c38fe3a380aa92afbc081f20d4
4,847
cpp
C++
src/api/API.cpp
myxor/ceema
e0a9f299fd488da38a9a1492502017995d59e183
[ "Apache-2.0" ]
19
2018-08-31T12:52:13.000Z
2021-08-11T18:05:42.000Z
src/api/API.cpp
myxor/ceema
e0a9f299fd488da38a9a1492502017995d59e183
[ "Apache-2.0" ]
4
2019-02-01T09:12:56.000Z
2022-01-14T21:36:17.000Z
src/api/API.cpp
myxor/ceema
e0a9f299fd488da38a9a1492502017995d59e183
[ "Apache-2.0" ]
5
2021-03-28T18:06:21.000Z
2022-01-13T17:46:12.000Z
/** * Copyright 2017 Harold Bruintjes * * 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 "API.h" #include "logging/logging.h" namespace ceema { API::API(HttpManager& manager) : m_manager(manager) { m_manager.set_cert(api_cert); } future<byte_vector> API::get(std::string const &url) { auto& client = m_manager.getFreeClient(); return client.get(url); } future<void> API::get(std::string const &url, IHttpTransfer* transfer) { auto& client = m_manager.getFreeClient(); return client.get(url, transfer); } future<byte_vector> API::post(std::string const &url, byte_vector const& data) { auto& client = m_manager.getFreeClient(); return client.post(url, data); } void API::postFile(std::string url, IHttpTransfer* transfer, std::string const& filename) { auto& client = m_manager.getFreeClient(); client.postFile(url, transfer, filename); } future<byte_vector> API::postFile(std::string url, byte_vector const& data, std::string const& filename) { auto& client = m_manager.getFreeClient(); return client.postFile(url, data, filename); } future<json> API::jsonGet(std::string const& url) { auto& client = m_manager.getFreeClient(); auto request_fut = client.get(url); auto json_fut = request_fut.next([](future<byte_vector> fut) { byte_vector data = fut.get(); return checkJSONResult(json::parse(data.begin(), data.end())); }); return json_fut; } future<json> API::jsonPost(std::string const& url, json request) { auto& client = m_manager.getFreeClient(); std::string jsonString = request.dump(); LOG_DBG("Submitting API request: " << request); auto request_fut = client.post(url, byte_vector(jsonString.begin(), jsonString.end())); auto json_fut = request_fut.next([](future<byte_vector> fut) { byte_vector data = fut.get(); return checkJSONResult(json::parse(data.begin(), data.end())); }); return json_fut; } json API::checkJSONResult(json data) { LOG_DBG("Got JSON data for API: " << data); if (data.count("success") && !data["success"].get<bool>()) { throw std::runtime_error(data["error"].get<std::string>().c_str()); } return data; } const char* API::api_cert = "-----BEGIN CERTIFICATE-----\n" "MIIEYTCCA0mgAwIBAgIJAM1DR/DBRFpQMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV\n" "BAYTAkNIMQswCQYDVQQIEwJaSDEPMA0GA1UEBxMGWnVyaWNoMRAwDgYDVQQKEwdU\n" "aHJlZW1hMQswCQYDVQQLEwJDQTETMBEGA1UEAxMKVGhyZWVtYSBDQTEcMBoGCSqG\n" "SIb3DQEJARYNY2FAdGhyZWVtYS5jaDAeFw0xMjExMTMxMTU4NThaFw0zMjExMDgx\n" "MTU4NThaMH0xCzAJBgNVBAYTAkNIMQswCQYDVQQIEwJaSDEPMA0GA1UEBxMGWnVy\n" "aWNoMRAwDgYDVQQKEwdUaHJlZW1hMQswCQYDVQQLEwJDQTETMBEGA1UEAxMKVGhy\n" "ZWVtYSBDQTEcMBoGCSqGSIb3DQEJARYNY2FAdGhyZWVtYS5jaDCCASIwDQYJKoZI\n" "hvcNAQEBBQADggEPADCCAQoCggEBAK8GdoT7IpNC3Dz7IUGYW9pOBwx+9EnDZrkN\n" "VD8l3KfBHjGTdi9gQ6Nh+mQ9/yQ8254T2big9p0hcn8kjgEQgJWHpNhYnOhy3i0j\n" "cmlzb1MF/deFjJVtuMP3tqTwiMavpweoa20lGDn/CLZodu0Ra8oL78b6FVztNkWg\n" "PdiWClMk0JPPMlfLEiK8hfHE+6mRVXmi12itK1semmwyHKdj9fG4X9+rQ2sKuLfe\n" "jx7uFxnAF+GivCuCo8xfOesLw72vx+W7mmdYshg/lXOcqvszQQ/LmFEVQYxNaeeV\n" "nPSAs+ht8vUPW4sX9IkXKVgBJd1R1isUpoF6dKlUexmvLxEyf5cCAwEAAaOB4zCB\n" "4DAdBgNVHQ4EFgQUw6LaC7+J62rKdaTA37kAYYUbrkgwgbAGA1UdIwSBqDCBpYAU\n" "w6LaC7+J62rKdaTA37kAYYUbrkihgYGkfzB9MQswCQYDVQQGEwJDSDELMAkGA1UE\n" "CBMCWkgxDzANBgNVBAcTBlp1cmljaDEQMA4GA1UEChMHVGhyZWVtYTELMAkGA1UE\n" "CxMCQ0ExEzARBgNVBAMTClRocmVlbWEgQ0ExHDAaBgkqhkiG9w0BCQEWDWNhQHRo\n" "cmVlbWEuY2iCCQDNQ0fwwURaUDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUA\n" "A4IBAQARHMyIHBDFul+hvjACt6r0EAHYwR9GQSghIQsfHt8cyVczmEnJH9hrvh9Q\n" "Vivm7mrfveihmNXAn4WlGwQ+ACuVtTLxw8ErbST7IMAOx9npHf/kngnZ4nSwURF9\n" "rCEyHq179pNXpOzZ257E5r0avMNNXXDwulw03iBE21ebd00pG11GVq/I26s+8Bjn\n" "DKRPquKrSO4/luEDvL4ngiQjZp32S9Z1K9sVOzqtQ7I9zzeUADm3aVa/Bpaw4iMR\n" "1SI7o9aJYiRi1gxYP2BUA1IFqr8NzyfGD7tRHdq7bZOxXAluv81dcbz0SBX8SgV1\n" "4HEKc6xMANnYs/aYKjvmP0VpOvRU\n" "-----END CERTIFICATE-----"; }
42.147826
110
0.706416
myxor
bd0e127ea93ad4b923f4790be65c14f7046fd2d5
4,668
cpp
C++
Visual Mercutio/zModelBP/PSS_RiskNewFileDlg.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
1
2022-01-31T06:24:24.000Z
2022-01-31T06:24:24.000Z
Visual Mercutio/zModelBP/PSS_RiskNewFileDlg.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-04-11T15:50:42.000Z
2021-06-05T08:23:04.000Z
Visual Mercutio/zModelBP/PSS_RiskNewFileDlg.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-01-08T00:55:18.000Z
2022-01-31T06:24:18.000Z
/**************************************************************************** * ==> PSS_RiskNewFileDlg --------------------------------------------------* **************************************************************************** * Description : Provides a create a new risk file dialog box * * Developer : Processsoft * ****************************************************************************/ #include "stdafx.h" #include "PSS_RiskNewFileDlg.h" // processsoft #include "zMediator\PSS_Application.h" #include "zBaseLib\PSS_File.h" #include "zBaseLib\PSS_TextFile.h" #include "zBaseLib\PSS_MsgBox.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif //--------------------------------------------------------------------------- // Message map //--------------------------------------------------------------------------- BEGIN_MESSAGE_MAP(PSS_RiskNewFileDlg, CDialog) //{{AFX_MSG_MAP(PSS_RiskNewFileDlg) ON_BN_CLICKED(IDC_DIRECTORY_SELECT, OnBnClickedDirectorySelect) ON_EN_CHANGE(IDC_FILENAME, OnEnChangeFileName) ON_EN_CHANGE(IDC_DIRECTORY, OnEnChangeDirectory) ON_BN_CLICKED(IDOK, OnBnClickedOk) //}}AFX_MSG_MAP END_MESSAGE_MAP() //--------------------------------------------------------------------------- // PSS_RiskNewFileDlg //--------------------------------------------------------------------------- PSS_RiskNewFileDlg::PSS_RiskNewFileDlg(const CString& extension, CWnd* pParent) : CDialog(PSS_RiskNewFileDlg::IDD, pParent), m_Extension(extension) {} //--------------------------------------------------------------------------- PSS_RiskNewFileDlg::~PSS_RiskNewFileDlg() {} //--------------------------------------------------------------------------- CString PSS_RiskNewFileDlg::GetDirectory() { return m_Directory; } //--------------------------------------------------------------------------- CString PSS_RiskNewFileDlg::GetFileName() { return m_FileName; } //--------------------------------------------------------------------------- void PSS_RiskNewFileDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(PSS_RiskNewFileDlg) DDX_Text (pDX, IDC_FILENAME, m_FileName); DDX_Text (pDX, IDC_DIRECTORY, m_Directory); DDX_Control(pDX, IDC_FILENAME, m_FileName_Ctrl); DDX_Control(pDX, IDC_DIRECTORY, m_Directory_Ctrl); DDX_Control(pDX, IDOK, m_OK_Ctrl); //}}AFX_DATA_MAP } //--------------------------------------------------------------------------- BOOL PSS_RiskNewFileDlg::OnInitDialog() { CDialog::OnInitDialog(); PSS_Application* pApplication = PSS_Application::Instance(); if (pApplication) { PSS_MainForm* pMainForm = pApplication->GetMainForm(); if (pMainForm) { m_Directory = pMainForm->GetApplicationDir() + g_RiskDirectory; m_Directory_Ctrl.SetWindowText(m_Directory); } } m_OK_Ctrl.EnableWindow(FALSE); return TRUE; } //--------------------------------------------------------------------------- void PSS_RiskNewFileDlg::OnBnClickedDirectorySelect() { CSHFileInfo fileInfo; fileInfo.m_strTitle = _T(m_Directory); if (fileInfo.BrowseForFolder(GetParent()) == IDOK) { m_Directory = fileInfo.m_strPath; m_Directory_Ctrl.SetWindowText(m_Directory); } } //--------------------------------------------------------------------------- void PSS_RiskNewFileDlg::OnEnChangeFileName() { m_FileName_Ctrl.GetWindowText(m_FileName); CheckUserEntry(); } //--------------------------------------------------------------------------- void PSS_RiskNewFileDlg::OnEnChangeDirectory() { m_Directory_Ctrl.GetWindowText(m_Directory); CheckUserEntry(); } //--------------------------------------------------------------------------- void PSS_RiskNewFileDlg::OnBnClickedOk() { PSS_File file; if (!file.Exist(m_Directory)) { PSS_MsgBox mBox; mBox.Show(IDS_BAD_DIRECTORY, MB_OK); return; } if (file.Exist(m_Directory + _T("\\") + m_FileName + m_Extension)) { PSS_MsgBox mBox; mBox.Show(IDS_RISK_FILE_ALREADY_EXIST, MB_OK); return; } OnOK(); } //--------------------------------------------------------------------------- void PSS_RiskNewFileDlg::CheckUserEntry() { if (!m_FileName.IsEmpty() && !m_Directory.IsEmpty()) m_OK_Ctrl.EnableWindow(TRUE); else m_OK_Ctrl.EnableWindow(FALSE); } //---------------------------------------------------------------------------
32.643357
81
0.477721
Jeanmilost
bd135eb20b929718d7642e8d65a5bd52e3093f55
438
cpp
C++
src/generate_ua_nodeset2.cpp
Jokymon/TinyModelCompiler
dd0251cd8c1915e5615f43348c03f4176d9e90af
[ "MIT" ]
1
2020-01-03T16:18:47.000Z
2020-01-03T16:18:47.000Z
src/generate_ua_nodeset2.cpp
Jokymon/TinyModelCompiler
dd0251cd8c1915e5615f43348c03f4176d9e90af
[ "MIT" ]
null
null
null
src/generate_ua_nodeset2.cpp
Jokymon/TinyModelCompiler
dd0251cd8c1915e5615f43348c03f4176d9e90af
[ "MIT" ]
1
2020-01-30T20:54:12.000Z
2020-01-30T20:54:12.000Z
#include "ua_nodeset2_generator.h" #include <CLI/CLI.hpp> #include <iostream> #include <string> int main(int argc, char **argv) { CLI::App app; std::string docname; app.add_option("docname", docname, "Path to the Opc.Ua.NodeSet2.xml input file") ->required(); CLI11_PARSE(app, argc, argv); ua_nodeset2_generator ns2gen; ns2gen.load_nodeset(docname); ns2gen.write_nodeset2_sources(); return 0; }
19.043478
84
0.680365
Jokymon
bd14c36f8c89d0bc09bbf909b0862b8d22e91b02
1,980
cpp
C++
src/vega/pathname.cpp
project-eutopia/vega
c7b536c5e949094a908fa8f378729dbffc657f4a
[ "MIT" ]
18
2018-01-23T12:28:13.000Z
2022-02-13T12:23:21.000Z
src/vega/pathname.cpp
project-eutopia/vega
c7b536c5e949094a908fa8f378729dbffc657f4a
[ "MIT" ]
2
2018-11-29T01:51:25.000Z
2022-03-22T14:14:22.000Z
src/vega/pathname.cpp
project-eutopia/vega
c7b536c5e949094a908fa8f378729dbffc657f4a
[ "MIT" ]
6
2019-02-01T09:54:44.000Z
2022-01-09T22:13:54.000Z
#include "vega/pathname.h" namespace vega { Pathname::Pathname() noexcept : full_name_(), last_slash_(std::string::npos), last_dot_(std::string::npos) {} Pathname::Pathname(const std::string& full_name) noexcept : full_name_(full_name), last_slash_(std::string::npos), last_dot_(std::string::npos) { precompute(); } Pathname::Pathname(const char* s) noexcept : full_name_(s), last_slash_(std::string::npos), last_dot_(std::string::npos) { precompute(); } void Pathname::precompute() { last_slash_ = full_name_.rfind('/'); last_dot_ = full_name_.rfind('.'); if (last_dot_ != std::string::npos) { if (last_slash_ == std::string::npos) { // If no folder in front, then leading dot is not preceding file name extension if (last_dot_ == 0) last_dot_ = std::string::npos; } else { if (last_slash_ + 1 >= last_dot_) last_dot_ = std::string::npos; } } } const std::string& Pathname::full_name() const { return full_name_; } Pathname::operator std::string() const { return full_name_; } std::string Pathname::extension() const { return last_dot_ == std::string::npos ? "" : full_name_.substr(last_dot_ + 1); } std::string Pathname::base_name() const { size_t start = last_slash_ == std::string::npos ? 0 : last_slash_ + 1; if (last_dot_ == std::string::npos) { return full_name_.substr(start); } else { return full_name_.substr(start, last_dot_-start); } } std::string Pathname::folder() const { return last_slash_ == std::string::npos ? "./" : full_name_.substr(0, last_slash_ + 1); } std::istream& operator>>(std::istream& is, Pathname& pathname) { is >> pathname.full_name_; pathname.precompute(); return is; } const Pathname operator+(const Pathname& lhs, const Pathname& rhs) { return Pathname(lhs.full_name() + rhs.full_name()); } }
26.052632
91
0.621717
project-eutopia
bd1545f163aa78bc26da6765ece2afb2198c552e
652
hpp
C++
src/Dispatcher.hpp
tblyons/goon
fd5fbdda14fe1b4869e365c7cebec2bcb7de06e3
[ "Unlicense" ]
1
2022-02-11T21:25:53.000Z
2022-02-11T21:25:53.000Z
apps/Goon/src/Dispatcher.hpp
tybl/tybl
cc74416d3d982177d46b89c0ca44f3a8e1cf00d6
[ "Unlicense" ]
15
2021-08-21T13:41:29.000Z
2022-03-08T14:13:43.000Z
apps/Goon/src/Dispatcher.hpp
tybl/tybl
cc74416d3d982177d46b89c0ca44f3a8e1cf00d6
[ "Unlicense" ]
null
null
null
// License: The Unlicense (https://unlicense.org) #ifndef GOON_DISPATCHER_HPP #define GOON_DISPATCHER_HPP #include <SDL2/SDL.h> #include <functional> #include <vector> struct Dispatcher { Dispatcher(void); bool KeepRunning(void) const; void ProcessEvents(void); void AddKeyboardListener(std::function<void(SDL_Keycode)> func); void AddWindowListener(std::function<void(SDL_WindowEvent)> func); private: void OptOutEvents(void); private: std::vector<std::function<void(SDL_Keycode)>> mKeyboardListeners; std::vector<std::function<void(SDL_WindowEvent)>> mWindowListeners; bool mKeepRunning; }; #endif // GOON_DISPATCHER_HPP
28.347826
70
0.760736
tblyons
bd18b866b9459091ef5ec62a3e6f9a2319c38bf5
1,127
cc
C++
src/02_management/12_move.cc
chanchann/lighao
5c06c4dfcf93b9dd59522971f9c939af128b9378
[ "MIT" ]
1
2021-01-18T02:37:03.000Z
2021-01-18T02:37:03.000Z
src/02_management/12_move.cc
chanchann/Thread
5c06c4dfcf93b9dd59522971f9c939af128b9378
[ "MIT" ]
null
null
null
src/02_management/12_move.cc
chanchann/Thread
5c06c4dfcf93b9dd59522971f9c939af128b9378
[ "MIT" ]
null
null
null
/* 下面实现一个为std::thread添加了析构行为的joining_thread TODO */ #include <iostream> #include <thread> class A { std::thread t; public: A() noexcept = default; template<typename T, typename... Ts> explicit A(T&& f, Ts&&... args) : t(std::forward<T>(f), std::forward<Ts>(args)...) {} explicit A(std::thread x) noexcept : t(std::move(x)) {} A(A&& rhs) noexcept : t(std::move(rhs.t)) {} A& operator=(A&& rhs) noexcept { if (joinable()) join(); t = std::move(rhs.t); return *this; } A& operator=(std::thread rhs) noexcept { if (joinable()) join(); t = std::move(rhs); return *this; } ~A() noexcept { if (joinable()) join(); } void swap(A&& rhs) noexcept { t.swap(rhs.t); } std::thread::id get_id() const noexcept { return t.get_id(); } bool joinable() const noexcept { return t.joinable(); } void join() { t.join(); } void detach() { t.detach(); } std::thread& as_thread() noexcept { return t; } const std::thread& as_thread() const noexcept { return t; } };
22.54
66
0.535936
chanchann
bd1939be39508ed63c7723040f71afabc12c94c6
7,116
hpp
C++
engine/alice/application.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
1
2020-04-14T13:55:16.000Z
2020-04-14T13:55:16.000Z
engine/alice/application.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
4
2020-09-25T22:34:29.000Z
2022-02-09T23:45:12.000Z
engine/alice/application.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
1
2020-07-02T11:51:17.000Z
2020-07-02T11:51:17.000Z
/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. */ #pragma once #include <atomic> #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "engine/alice/node.hpp" #include "engine/gems/serialization/json.hpp" #include "engine/gems/uuid/uuid.hpp" namespace isaac { namespace alice { class ApplicationJsonLoader; class Backend; // The basis of an Isaac application. An application normally contains many nodes which work // together to create complex behaviors. A node in turn contains multiple components which define // its functionality. Components can be configured via parameters, exchange data via messages, and // much more. // // Applications can be created as specified in a JSON object. They can also be built interactively // at runtime, however not all features are yet supported for this use case. // // If you want to create an application which parses basic parameters via the command line you // can use the //engine/alice/tools:parse_command_line. This is kept as a separate library to not // pollute the default compile object with static variable from gflags. // // The API of this class is still under development and should considered to be experimental. class Application { public: // Creates a new application Application(const ApplicationJsonLoader& loader); // Creates a new application with a random name Application(const std::vector<std::string> module_paths = {}, const std::string& asset_path = ""); // Creates a new application as specified in the given JSON object. Application(const nlohmann::json& json, const std::vector<std::string> module_paths = {}, const std::string& asset_path = ""); ~Application(); // A name for the app which stays the same over time const std::string& name() const { return name_; } // A unique identifier which is different for every running application const Uuid& uuid() const { return uuid_; } // Loads more configuration and nodes from a JSON file void loadFromFile(const std::string& json_file); // Loads more configuration and nodes from a JSON text string void loadFromText(const std::string& json_text); // Loads more configuration and nodes from a JSON object void load(const nlohmann::json& json); // Creates a new node with the given name Node* createNode(const std::string& name); Node* createMessageNode(const std::string& name); // Destroys the node with the given name and all its components void destroyNode(const std::string& name); // Finds a node by name. This function will return nullptr if no node with this name exists. Node* findNodeByName(const std::string& name) const; // Gets a node by name. This function will assert if no node with this name exists. Node* getNodeByName(const std::string& name) const; // Find all nodes which have a component of the given type template <typename T> std::vector<Node*> findNodesWithComponent() const { std::vector<Node*> result; for (Node* node : nodes()) { if (node->hasComponent<T>()) { result.push_back(node); } } return result; } // Find all components of the given type. This function is quite slow. template <typename T> std::vector<T*> findComponents() const { std::vector<T*> result; for (Node* node : nodes()) { const auto components = node->getComponents<T>(); result.insert(result.end(), components.begin(), components.end()); } return result; } // Finds a unique component of the given type. Returns null if none or multiple components of this // type where found. This function is quite slow. template <typename T> T* findComponent() const { T* pointer = nullptr; for (Node* node : nodes()) { if (T* component = node->getComponentOrNull<T>()) { if (pointer != nullptr) { return nullptr; } pointer = component; } } return pointer; } // @deprecated: Use `getNodeComponentOrNull` instead. // Find a component by name and type. `link` is given as "node_name/component_name" template <typename T> T* findComponentByName(const std::string& link) const { return dynamic_cast<T*>(findComponentByName(link)); } // Find a component by name. `link` is given as "node_name/component_name" Component* findComponentByName(const std::string& link) const; // Gets the component of given type in the node of given name. Asserts in case the node // does not exists, or if there are none or multiple components of the given type in the node. template <typename T> T* getNodeComponent(const std::string& node_name) const { return getNodeByName(node_name)->getComponent<T>(); } // Gets the component of given type in the node of given name. nullptr is returned in case the // node does not exist, or if there are none or multiple components of the given type in the node. template <typename T> T* getNodeComponentOrNull(const std::string& node_name) const { const Node* node = findNodeByName(node_name); if (node == nullptr) return nullptr; return node->getComponentOrNull<T>(); } // For a channel 'nodename/compname/tag', return the component and tag string std::tuple<Component*, std::string> getComponentAndTag(const std::string& channel); // Starts the app, waits for the given duration, then stops the app void startWaitStop(double duration); // Starts the app, waits for Ctrl+C, then stops the app void startWaitStop(); // Interrupts the application and stops it void interrupt(); // Starts the app void start(); // Srops the app void stop(); Backend* backend() const { return backend_.get(); } // Gets absolute filename for relative asset filename. Identity in case of absolute filename. std::string getAssetPath(const std::string& path = "") const; private: friend class Node; friend class Backend; // Gets all nodes std::vector<Node*> nodes() const; // Creates a new application from the given JSON object. void createApplication(const ApplicationJsonLoader& loader); // Creates more configuration and graph void createMore(const ApplicationJsonLoader& loader); std::string name_; Uuid uuid_; std::unique_ptr<Backend> backend_; std::atomic<bool> is_running_; // Filename to write out the application json std::string application_backup_; // Cache the application json while the app is loading to write out to file later nlohmann::json app_json_; // Filename to write out the configuration std::string config_backup_; // Filename to write out the performance report std::string performance_report_out_; // Base path to search assets for std::string asset_path_; }; } // namespace alice } // namespace isaac
36.870466
100
0.723159
stereoboy
bd1da0dfad056a510f059f4a7642bff52a7cf4e3
3,240
cpp
C++
tc 160+/MagicBoxes.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/MagicBoxes.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/MagicBoxes.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> using namespace std; /* NE RADI */ bool canMake[31][31][1<<15]; bool done[31][31][1<<15]; bool go(int x, int y, int mask) { assert(x>=0 && y>=0); if (mask == 0) return true; if (x > y) swap(x, y); if (done[x][y][mask]) return canMake[x][y][mask]; done[x][y][mask] = true; for (int i=15; i>0; --i) if (mask & (1<<(i-1))) { if (i > x) return (canMake[x][y][mask] = false); int left = (mask ^ (1<<(i-1))); if (left == 0) return canMake[x][y][mask] = true; for (int m1=0; m1<left; m1=(((~left | m1)+1)&left)) { int m2 = left^m1; assert((m1|m2) == left); assert((m1&m2) == 0); if (go(x-i, y, m1) && go(i, y-i, m2) || go(x-i, i, m1) && go(x, y-i, m2)) return (canMake[x][y][mask] = true); } if (go(x-i, y, left) || go(x-i, i, left)) return (canMake[x][y][mask] = true); break; } for (int i=1; i<16; ++i) if (mask & (1<<(i-1))) { int left = (mask ^ (1<<(i-1))); if (left == 0) return canMake[x][y][mask] = true; for (int m1=0; m1<left; m1=(((~left | m1)+1)&left)) { int m2 = left^m1; assert((m1|m2) == left); assert((m1&m2) == 0); if (go(x-i, y, m1) && go(i, y-i, m2) || go(x-i, i, m1) && go(x, y-i, m2)) return (canMake[x][y][mask] = true); } if (go(x-i, y, left) || go(x-i, i, left)) return (canMake[x][y][mask] = true); break; } return (canMake[x][y][mask] = false); } class MagicBoxes { public: int biggest(int x, int y) { memset(done, 0, sizeof done); for (int i=15; i>1; --i) if (go(x, y, (1<<i)-1)) return i; return 1; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 1; int Arg1 = 1; int Arg2 = 1; verify_case(0, Arg2, biggest(Arg0, Arg1)); } void test_case_1() { int Arg0 = 2; int Arg1 = 2; int Arg2 = 1; verify_case(1, Arg2, biggest(Arg0, Arg1)); } void test_case_2() { int Arg0 = 10; int Arg1 = 10; int Arg2 = 5; verify_case(2, Arg2, biggest(Arg0, Arg1)); } void test_case_3() { int Arg0 = 26; int Arg1 = 26; int Arg2 = 11; verify_case(3, Arg2, biggest(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { MagicBoxes ___test; ___test.run_test(3); } // END CUT HERE
27.931034
309
0.517901
ibudiselic
bd226bd072be31791ea4537446d0236960feab71
421
cpp
C++
Level-1/9. Recursion on the way up/Print_Permutations.cpp
anubhvshrma18/PepCoding
1d5ebd43e768ad923bf007c8dd584e217df1f017
[ "Apache-2.0" ]
22
2021-06-02T04:25:55.000Z
2022-01-30T06:25:07.000Z
Level-1/9. Recursion on the way up/Print_Permutations.cpp
amitdubey6261/PepCoding
1d5ebd43e768ad923bf007c8dd584e217df1f017
[ "Apache-2.0" ]
2
2021-10-17T19:26:10.000Z
2022-01-14T18:18:12.000Z
Level-1/9. Recursion on the way up/Print_Permutations.cpp
amitdubey6261/PepCoding
1d5ebd43e768ad923bf007c8dd584e217df1f017
[ "Apache-2.0" ]
8
2021-07-21T09:55:15.000Z
2022-01-31T10:32:51.000Z
#include <iostream> using namespace std; void printPermutations(string str, string asf){ // write your code here if(str.length()==0){ cout << asf << endl; } for(int i=0;i<str.length();i++){ swap(str[0],str[i]); string y=""; y+=str[0]; printPermutations(str.substr(1),asf+y); } } int main(){ string str; cin>>str; printPermutations(str,""); }
18.304348
47
0.539192
anubhvshrma18
bd2bc1ea4e7c4ac7babe7112e769ae65f6f92ed4
2,308
cpp
C++
core/utils/src/TimeTracker.cpp
nicsor/BreadCrumbs
9ee5111d87d7a71b0a3910c14c4751eb3f1635ab
[ "MIT" ]
null
null
null
core/utils/src/TimeTracker.cpp
nicsor/BreadCrumbs
9ee5111d87d7a71b0a3910c14c4751eb3f1635ab
[ "MIT" ]
null
null
null
core/utils/src/TimeTracker.cpp
nicsor/BreadCrumbs
9ee5111d87d7a71b0a3910c14c4751eb3f1635ab
[ "MIT" ]
null
null
null
/** * @file TimeTracker.cpp * * @author Nicolae Natea * Contact: [email protected] */ #include <cstdint> #include <map> #include <mutex> #include <core/util/TimeTracker.hpp> namespace core { namespace util { namespace { struct TimeInfo { uint64_t times_called; ///< Keep track of number of times a particular method was called. uint64_t total_time; ///< Keep track of total execution time for a particular method. }; /** Global map to keep track of method execution */ std::map<std::string, TimeInfo> tracked_time_info; /** Synchronization mutex for updating time */ std::mutex tracked_time_mutex; } TimeTracker::TimeTracker(const std::string &id) : m_id(id) { m_start = std::chrono::steady_clock::now(); } TimeTracker::~TimeTracker() { auto durationUs = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - m_start).count(); std::lock_guard<std::mutex> lock(tracked_time_mutex); auto item = tracked_time_info.find(m_id); if (item == tracked_time_info.end()) { tracked_time_info.insert({m_id, {1, (uint64_t)durationUs}}); } else { item->second.total_time += durationUs; ++item->second.times_called; } } void clearStatistics() { std::lock_guard<std::mutex> lock(tracked_time_mutex); tracked_time_info.clear(); } std::string getTimingStatistics() { std::string response; response.reserve(16 * 1024); for (auto &el : tracked_time_info) { auto &stats = el.second; response.append(el.first); response.append(": "); response.append(std::to_string(stats.total_time)); response.append("us, "); response.append(std::to_string(stats.times_called)); response.append(" times, "); response.append(std::to_string((double) stats.total_time / stats.times_called)); response.append("us average\n"); } return response; } } }
31.616438
137
0.557192
nicsor
bd2c0645a6e63bf2ac8123eac1c868a4125ee907
22,274
cpp
C++
src/level/lightingcalculator.cpp
alexeyden/whack
2bff3beb0afb8c5aaba996b2838d2f0b9797039c
[ "WTFPL" ]
null
null
null
src/level/lightingcalculator.cpp
alexeyden/whack
2bff3beb0afb8c5aaba996b2838d2f0b9797039c
[ "WTFPL" ]
null
null
null
src/level/lightingcalculator.cpp
alexeyden/whack
2bff3beb0afb8c5aaba996b2838d2f0b9797039c
[ "WTFPL" ]
null
null
null
#include "lightingcalculator.h" #include "entityvisualinfoextractor.h" #include "level.h" #include "util/math.h" #include "util/rect.h" void LightingCalculator::calculate() { preparePass(); calculatePass(); averagePass(); spritesPass(); } void LightingCalculator::preparePass() { for(unsigned i = 0; i < _level->sizeX(); i++) { for(unsigned j = 0; j < _level->sizeY(); j++) { auto& block = _level->block(i, j); memcpy(block.lightingTint.floor, ambientRGB, sizeof(uint32_t) * 3); memcpy(block.lightingTint.ceiling, ambientRGB, sizeof(uint32_t) * 3); memcpy(block.lightingTint.north_bot, ambientRGB, sizeof(uint32_t) * 3); memcpy(block.lightingTint.south_bot, ambientRGB, sizeof(uint32_t) * 3); memcpy(block.lightingTint.east_bot, ambientRGB, sizeof(uint32_t) * 3); memcpy(block.lightingTint.west_bot, ambientRGB, sizeof(uint32_t) * 3); memcpy(block.lightingTint.north_top, ambientRGB, sizeof(uint32_t) * 3); memcpy(block.lightingTint.south_top, ambientRGB, sizeof(uint32_t) * 3); memcpy(block.lightingTint.east_top, ambientRGB, sizeof(uint32_t) * 3); memcpy(block.lightingTint.west_top, ambientRGB, sizeof(uint32_t) * 3); } } for(VisualEntity* e : _level->entities()) { memcpy(e->lighting_tint, ambientRGB, sizeof(uint32_t) * 3); } } void LightingCalculator::calculatePass() { for(const auto& light : _level->lights()) { for(unsigned i = 0; i < _level->sizeX(); i++) { for(unsigned j = 0; j < _level->sizeY(); j++) { auto& block = _level->block(i, j); calcLight(light, block, i, j); } } } } void LightingCalculator::calcLight(const Light& light, Block& block, uint32_t x, uint32_t y) { EntityVisualInfoExtractor extr; vec3 light_p(light.x, light.y, light.z); Rect<float> rect_block(x, y, x + 1, y + 1); vec3 p = vec3(x + 0.5f, y + 0.5f, block.standHeightVisual() + 0.01f); if(hitsLight(light_p, p)) { bool has_entity = false; for(const auto& e : _level->entitiesAt(x, y)) { const auto& aabb = e->collisionAABB(); bool near_ground = fabs(e->z() - block.standHeightVisual()) < 1.0f; bool intersects = Rect<float>(aabb.x0, aabb.y0, aabb.x1, aabb.y1).intersects(rect_block); if(near_ground && intersects && extr.extract(e).type == EntityFactory::ET_DECOR) { has_entity = true; break; } } if(!has_entity) lightAdd(block.lightingTint.floor, light, (light_p - p).length()); } uint32_t (*sides_bot[4])[3] = { &block.lightingTint.north_bot, &block.lightingTint.south_bot, &block.lightingTint.west_bot, &block.lightingTint.east_bot }; uint32_t (*sides_top[4])[3] = { &block.lightingTint.north_top, &block.lightingTint.south_top, &block.lightingTint.west_top, &block.lightingTint.east_top }; vec3 points[4] = { vec3(x + 0.5f, y + 1.05f, 0), vec3(x + 0.5f, y - 0.05f, 0), vec3(x - 0.05f, y + 0.5f, 0), vec3(x + 1.05f, y + 0.5f, 0) }; for(int i = 0; i < 4; i++) { for(float j = 0.0f; j <= 20; j += 0.5f) { vec3 p = points[i]; p.z = std::min(block.standHeightVisual() * j / 20.0f, block.standHeightVisual() - 0.05f); if(hitsLight(light_p, p)) { lightAdd(*(sides_bot[i]), light, (light_p - p).length()); break; } } } if(block.notchHeight > 0) { p = vec3(x + 0.5f, y + 0.5f, block.notchHeight + block.notch - 0.05f); if(hitsLight(light_p, p)) { lightAdd(block.lightingTint.ceiling, light, (light_p - p).length()); } for(int i = 0; i < 4; i++) { for(float j = 0.0f; j <= 20.0f; j += 0.5f) { vec3 p = points[i]; p.z = std::max(std::min( block.notch + block.notchHeight + (block.height - (block.notch + block.notchHeight))*j / 20.0f, block.height - 0.5f ), block.notch + block.notchHeight + 0.05f); if(hitsLight(light_p, p)) { lightAdd(*(sides_top[i]), light, (light_p - p).length()); break; } } } } } bool LightingCalculator::hitsLight(const vec3& light, const vec3& point) { // EntityVisualInfoExtractor extr; vec3 ray = (light - point).normalize(); _caster.stop_target = light; const auto& result = _caster.cast(point, ray); if(result.block != nullptr) return false; /* if(result.entity != nullptr && extr.extract(result.entity).type == EntityFactory::ET_DECOR) { float t; return !rayAABBIntersect3D(point.x, point.y, point.z, ray.x, ray.y, ray.z, result.entity->collisionAABB(), &t); } */ return true; } void LightingCalculator::lightAdd(uint32_t (&color)[3], const Light& light, float distance) { if(light.type == LT_SUN) { color[0] = std::min<uint32_t>(uint32_t(color[0]) + light.red, 0xff); color[1] = std::min<uint32_t>(uint32_t(color[1]) + light.green, 0xff); color[2] = std::min<uint32_t>(uint32_t(color[2]) + light.blue, 0xff); } else { float k = std::max<float>(-distance * 1.0f/light.intensity + 1.0f, 0.0f); if(k > 0) { color[0] = std::min<uint32_t>(uint32_t(color[0] + light.red * k), 0xffu); color[1] = std::min<uint32_t>(uint32_t(color[1] + light.green * k), 0xffu); color[2] = std::min<uint32_t>(uint32_t(color[2] + light.blue * k), 0xffu); } } } void LightingCalculator::averagePass() { averageFloor(); //averageFloor(); averageNorthSouth(); averageEastWest(); } void LightingCalculator::averageFloor() { struct ColorU32 { uint32_t red; uint32_t green; uint32_t blue; }; ColorU32* temp = new ColorU32[_level->sizeX() * _level->sizeY()]; for(unsigned i = 0; i < _level->sizeX(); i++) { for(unsigned j = 0; j < _level->sizeY(); j++) { auto& block = _level->block(i, j); uint32_t tint[3]; tint[0] = block.lightingTint.floor[0]; tint[1] = block.lightingTint.floor[1]; tint[2] = block.lightingTint.floor[2]; unsigned average_n = 1; if(i > 0 && _level->block(i - 1, j).standHeight() == block.standHeight()) { tint[0] += _level->block(i - 1, j).lightingTint.floor[0]; tint[1] += _level->block(i - 1, j).lightingTint.floor[1]; tint[2] += _level->block(i - 1, j).lightingTint.floor[2]; average_n += 1; } if(j > 0 && _level->block(i, j-1).standHeight() == block.standHeight()) { tint[0] += _level->block(i, j-1).lightingTint.floor[0]; tint[1] += _level->block(i, j-1).lightingTint.floor[1]; tint[2] += _level->block(i, j-1).lightingTint.floor[2]; average_n += 1; } if(i < _level->sizeX()-1 && _level->block(i + 1, j).standHeight() == block.standHeight()) { tint[0] += _level->block(i + 1, j).lightingTint.floor[0]; tint[1] += _level->block(i + 1, j).lightingTint.floor[1]; tint[2] += _level->block(i + 1, j).lightingTint.floor[2]; average_n += 1; } if(j < _level->sizeY()-1 && _level->block(i, j+1).standHeight() == block.standHeight()) { tint[0] += _level->block(i, j+1).lightingTint.floor[0]; tint[1] += _level->block(i, j+1).lightingTint.floor[1]; tint[2] += _level->block(i, j+1).lightingTint.floor[2]; average_n += 1; } if(i > 0 && j > 0 && _level->block(i - 1, j-1).standHeight() == block.standHeight()) { tint[0] += _level->block(i - 1, j-1).lightingTint.floor[0]; tint[1] += _level->block(i - 1, j-1).lightingTint.floor[1]; tint[2] += _level->block(i - 1, j-1).lightingTint.floor[2]; average_n += 1; } if(i > 0 && j < _level->sizeY()-1 && _level->block(i - 1, j+1).standHeight() == block.standHeight()) { tint[0] += _level->block(i - 1, j+1).lightingTint.floor[0]; tint[1] += _level->block(i - 1, j+1).lightingTint.floor[1]; tint[2] += _level->block(i - 1, j+1).lightingTint.floor[2]; average_n += 1; } if(i < _level->sizeX()-1 && j > 0 && _level->block(i + 1, j-1).standHeight() == block.standHeight()) { tint[0] += _level->block(i + 1, j-1).lightingTint.floor[0]; tint[1] += _level->block(i + 1, j-1).lightingTint.floor[1]; tint[2] += _level->block(i + 1, j-1).lightingTint.floor[2]; average_n += 1; } if(i < _level->sizeX()-1 && j < _level->sizeY()-1 && _level->block(i + 1, j+1).standHeight() == block.standHeight()) { tint[0] += _level->block(i + 1, j+1).lightingTint.floor[0]; tint[1] += _level->block(i + 1, j+1).lightingTint.floor[1]; tint[2] += _level->block(i + 1, j+1).lightingTint.floor[2]; average_n += 1; } tint[0] = tint[0]/average_n; tint[1] = tint[1]/average_n; tint[2] = tint[2]/average_n; temp[i + j * _level->sizeX()] = ColorU32 { uint8_t(tint[0]), uint8_t(tint[1]), uint8_t(tint[2]) }; } } for(uint32_t i = 0; i < _level->sizeX(); i++) { for(uint32_t j = 0; j < _level->sizeY(); j++) { Block& block = _level->block(i, j); const ColorU32& color = temp[i + _level->sizeX() * j]; block.lightingTint.floor[0] = color.red; block.lightingTint.floor[1] = color.green; block.lightingTint.floor[2] = color.blue; } } delete [] temp; } void LightingCalculator::averageEastWest() { for(unsigned i = 0; i < _level->sizeX(); i++) { for(unsigned j = 0; j < _level->sizeY(); j++) { auto& block = _level->block(i, j); uint32_t tint_north_bot[3]; uint32_t tint_south_bot[3]; uint32_t tint_north_top[3]; uint32_t tint_south_top[3]; tint_north_bot[0] = block.lightingTint.north_bot[0]; tint_north_bot[1] = block.lightingTint.north_bot[1]; tint_north_bot[2] = block.lightingTint.north_bot[2]; tint_south_bot[0] = block.lightingTint.south_bot[0]; tint_south_bot[1] = block.lightingTint.south_bot[1]; tint_south_bot[2] = block.lightingTint.south_bot[2]; tint_north_top[0] = block.lightingTint.north_top[0]; tint_north_top[1] = block.lightingTint.north_top[1]; tint_north_top[2] = block.lightingTint.north_top[2]; tint_south_top[0] = block.lightingTint.south_top[0]; tint_south_top[1] = block.lightingTint.south_top[1]; tint_south_top[2] = block.lightingTint.south_top[2]; uint8_t average_n[4] = {1, 1, 1, 1}; const float height_diff = 3.0f; if(i > 0 && isBlockBottomVisible(i - 1, j, DIR_N) && fabs(_level->block(i - 1, j).height - block.height) < height_diff) { tint_north_bot[0] += _level->block(i - 1, j).lightingTint.north_bot[0]; tint_north_bot[1] += _level->block(i - 1, j).lightingTint.north_bot[1]; tint_north_bot[2] += _level->block(i - 1, j).lightingTint.north_bot[2]; average_n[0] += 1; } if(i > 0 && isBlockBottomVisible(i - 1, j, DIR_S) && fabs(_level->block(i - 1, j).height - block.height) < height_diff) { tint_south_bot[0] += _level->block(i - 1, j).lightingTint.south_bot[0]; tint_south_bot[1] += _level->block(i - 1, j).lightingTint.south_bot[1]; tint_south_bot[2] += _level->block(i - 1, j).lightingTint.south_bot[2]; average_n[1] += 1; } if(i < _level->sizeX()-1 && isBlockBottomVisible(i + 1, j, DIR_N) && fabs(_level->block(i + 1, j).height - block.height) < height_diff) { tint_north_bot[0] += _level->block(i + 1, j).lightingTint.north_bot[0]; tint_north_bot[1] += _level->block(i + 1, j).lightingTint.north_bot[1]; tint_north_bot[2] += _level->block(i + 1, j).lightingTint.north_bot[2]; average_n[0] += 1; } if(i < _level->sizeX()-1 && isBlockBottomVisible(i + 1, j, DIR_S) && fabs(_level->block(i + 1, j).height - block.height) < height_diff) { tint_south_bot[0] += _level->block(i + 1, j).lightingTint.south_bot[0]; tint_south_bot[1] += _level->block(i + 1, j).lightingTint.south_bot[1]; tint_south_bot[2] += _level->block(i + 1, j).lightingTint.south_bot[2]; average_n[1] += 1; } if(i > 0 && isBlockTopVisible(i - 1, j, DIR_N) && fabs(_level->block(i - 1, j).height - block.height) < height_diff) { const auto& b = _level->block(i - 1, j); const auto color_north = b.hasTop() ? b.lightingTint.north_top : b.lightingTint.north_bot; tint_north_top[0] += color_north[0]; tint_north_top[1] += color_north[1]; tint_north_top[2] += color_north[2]; average_n[2] += 1; } if(i > 0 && isBlockTopVisible(i - 1, j, DIR_S) && fabs(_level->block(i - 1, j).height - block.height) < height_diff) { const auto& b = _level->block(i - 1, j); const auto color_south = b.hasTop() ? b.lightingTint.south_top : b.lightingTint.south_bot; tint_south_top[0] += color_south[0]; tint_south_top[1] += color_south[1]; tint_south_top[2] += color_south[2]; average_n[3] += 1; } if(i < _level->sizeX()-1 && isBlockTopVisible(i + 1, j, DIR_N) && fabs(_level->block(i + 1, j).height - block.height) < height_diff) { const auto& b = _level->block(i + 1, j); const auto color_north = b.hasTop() ? b.lightingTint.north_top : b.lightingTint.north_bot; tint_north_top[0] += color_north[0]; tint_north_top[1] += color_north[1]; tint_north_top[2] += color_north[2]; average_n[2] += 1; } if(i < _level->sizeX()-1 && isBlockTopVisible(i + 1, j, DIR_S) && fabs(_level->block(i + 1, j).height - block.height) < height_diff) { const auto& b = _level->block(i + 1, j); const auto color_south = b.hasTop() ? b.lightingTint.south_top : b.lightingTint.south_bot; tint_south_top[0] += color_south[0]; tint_south_top[1] += color_south[1]; tint_south_top[2] += color_south[2]; average_n[3] += 1; } tint_north_bot[0] = tint_north_bot[0]/average_n[0]; tint_north_bot[1] = tint_north_bot[1]/average_n[0]; tint_north_bot[2] = tint_north_bot[2]/average_n[0]; tint_south_bot[0] = tint_south_bot[0]/average_n[1]; tint_south_bot[1] = tint_south_bot[1]/average_n[1]; tint_south_bot[2] = tint_south_bot[2]/average_n[1]; tint_north_top[0] = tint_north_top[0]/average_n[2]; tint_north_top[1] = tint_north_top[1]/average_n[2]; tint_north_top[2] = tint_north_top[2]/average_n[2]; tint_south_top[0] = tint_south_top[0]/average_n[3]; tint_south_top[1] = tint_south_top[1]/average_n[3]; tint_south_top[2] = tint_south_top[2]/average_n[3]; block.lightingTint.north_bot[0] = tint_north_bot[0]; block.lightingTint.north_bot[1] = tint_north_bot[1]; block.lightingTint.north_bot[2] = tint_north_bot[2]; block.lightingTint.south_bot[0] = tint_south_bot[0]; block.lightingTint.south_bot[1] = tint_south_bot[1]; block.lightingTint.south_bot[2] = tint_south_bot[2]; block.lightingTint.north_top[0] = tint_north_top[0]; block.lightingTint.north_top[1] = tint_north_top[1]; block.lightingTint.north_top[2] = tint_north_top[2]; block.lightingTint.south_top[0] = tint_south_top[0]; block.lightingTint.south_top[1] = tint_south_top[1]; block.lightingTint.south_top[2] = tint_south_top[2]; } } } bool LightingCalculator::isBlockBottomVisible(uint32_t x, uint32_t y, Dir dir) const { const Block& block = _level->block(x, y); bool vis_x0 = x > 0 && _level->block(x - 1, y).standHeightVisual() < block.standHeightVisual(); bool vis_x1 = x < _level->sizeX() - 1 && _level->block(x + 1, y).standHeightVisual() < block.standHeightVisual(); bool vis_y0 = y > 0 && _level->block(x, y - 1).standHeightVisual() < block.standHeightVisual(); bool vis_y1 = y < _level->sizeY() - 1 && _level->block(x, y + 1).standHeightVisual() < block.standHeightVisual(); return (dir == DIR_W && vis_x0) || (dir == DIR_E && vis_x1) || (dir == DIR_S && vis_y0) || (dir == DIR_N && vis_y1); } bool LightingCalculator::isBlockTopVisible(uint32_t x, uint32_t y, Dir dir) const { const Block& block = _level->block(x, y); if(!block.hasTop()) return isBlockBottomVisible(x, y, dir); auto side_visible = [&block](const Block& b) { if(!b.hasTop() && b.height > block.height) return false; if(b.hasTop() && b.notch + b.notchHeight < block.notch + block.notchHeight && b.height > block.height) return false; if(b.hasTop() && b.notch > block.height) return false; return true; }; bool vis_x0 = x > 0 && side_visible(_level->block(x - 1, y)); bool vis_x1 = x < _level->sizeX() - 1 && side_visible(_level->block(x + 1, y)); bool vis_y0 = y > 0 && side_visible(_level->block(x, y - 1)); bool vis_y1 = y < _level->sizeY() - 1 && side_visible(_level->block(x, y + 1)); return (dir == DIR_W && vis_x0) || (dir == DIR_E && vis_x1) || (dir == DIR_S && vis_y0) || (dir == DIR_N && vis_y1); } void LightingCalculator::averageNorthSouth() { for(size_t i = 0; i < _level->sizeX(); i++) { for(size_t j = 0; j < _level->sizeY(); j++) { auto& block = _level->block(i, j); uint32_t tint_west_bot[3]; uint32_t tint_east_bot[3]; uint32_t tint_west_top[3]; uint32_t tint_east_top[3]; tint_west_bot[0] = block.lightingTint.west_bot[0]; tint_west_bot[1] = block.lightingTint.west_bot[1]; tint_west_bot[2] = block.lightingTint.west_bot[2]; tint_east_bot[0] = block.lightingTint.east_bot[0]; tint_east_bot[1] = block.lightingTint.east_bot[1]; tint_east_bot[2] = block.lightingTint.east_bot[2]; tint_west_top[0] = block.lightingTint.west_top[0]; tint_west_top[1] = block.lightingTint.west_top[1]; tint_west_top[2] = block.lightingTint.west_top[2]; tint_east_top[0] = block.lightingTint.east_top[0]; tint_east_top[1] = block.lightingTint.east_top[1]; tint_east_top[2] = block.lightingTint.east_top[2]; uint8_t average_n[4] = {1, 1, 1, 1}; const float height_diff = 3.0f; if(j > 0 && isBlockBottomVisible(i, j - 1, DIR_W) && fabs(_level->block(i, j - 1).height - block.height) < height_diff) { tint_west_bot[0] += _level->block(i, j - 1).lightingTint.west_bot[0]; tint_west_bot[1] += _level->block(i, j - 1).lightingTint.west_bot[1]; tint_west_bot[2] += _level->block(i, j - 1).lightingTint.west_bot[2]; average_n[0] += 1; } if(j > 0 && isBlockBottomVisible(i, j - 1, DIR_E) && fabs(_level->block(i, j - 1).height - block.height) < height_diff) { tint_east_bot[0] += _level->block(i, j - 1).lightingTint.east_bot[0]; tint_east_bot[1] += _level->block(i, j - 1).lightingTint.east_bot[1]; tint_east_bot[2] += _level->block(i, j - 1).lightingTint.east_bot[2]; average_n[1] += 1; } if(j < _level->sizeX()-1 && isBlockBottomVisible(i, j + 1, DIR_W) && fabs(_level->block(i, j + 1).height - block.height) < height_diff) { tint_west_bot[0] += _level->block(i, j + 1).lightingTint.west_bot[0]; tint_west_bot[1] += _level->block(i, j + 1).lightingTint.west_bot[1]; tint_west_bot[2] += _level->block(i, j + 1).lightingTint.west_bot[2]; average_n[0] += 1; } if(j < _level->sizeX()-1 && isBlockBottomVisible(i, j + 1, DIR_E) && fabs(_level->block(i, j + 1).height - block.height) < height_diff) { tint_east_bot[0] += _level->block(i, j + 1).lightingTint.east_bot[0]; tint_east_bot[1] += _level->block(i, j + 1).lightingTint.east_bot[1]; tint_east_bot[2] += _level->block(i, j + 1).lightingTint.east_bot[2]; average_n[1] += 1; } if(j > 0 && isBlockTopVisible(i, j - 1, DIR_W) && fabs(_level->block(i, j - 1).height - block.height) < height_diff) { const auto& b = _level->block(i, j - 1); const auto color_west = b.hasTop() ? b.lightingTint.west_top : b.lightingTint.west_bot; tint_west_top[0] += color_west[0]; tint_west_top[1] += color_west[1]; tint_west_top[2] += color_west[2]; average_n[2] += 1; } if(j > 0 && isBlockTopVisible(i, j - 1, DIR_E) && fabs(_level->block(i, j - 1).height - block.height) < height_diff) { const auto& b = _level->block(i, j - 1); const auto color_east = b.hasTop() ? b.lightingTint.east_top : b.lightingTint.east_bot; tint_east_top[0] += color_east[0]; tint_east_top[1] += color_east[1]; tint_east_top[2] += color_east[2]; average_n[3] += 1; } if(j < _level->sizeX()-1 && isBlockTopVisible(i, j + 1, DIR_W) && fabs(_level->block(i, j + 1).height - block.height) < height_diff) { const auto& b = _level->block(i, j + 1); const auto color_west = b.hasTop() ? b.lightingTint.west_top : b.lightingTint.west_bot; tint_west_top[0] += color_west[0]; tint_west_top[1] += color_west[1]; tint_west_top[2] += color_west[2]; average_n[2] += 1; } if(j < _level->sizeX()-1 && isBlockTopVisible(i, j + 1, DIR_E) && fabs(_level->block(i, j + 1).height - block.height) < height_diff) { const auto& b = _level->block(i, j + 1); const auto color_east = b.hasTop() ? b.lightingTint.east_top : b.lightingTint.east_bot; tint_east_top[0] += color_east[0]; tint_east_top[1] += color_east[1]; tint_east_top[2] += color_east[2]; average_n[3] += 1; } tint_west_bot[0] = tint_west_bot[0]/average_n[0]; tint_west_bot[1] = tint_west_bot[1]/average_n[0]; tint_west_bot[2] = tint_west_bot[2]/average_n[0]; tint_east_bot[0] = tint_east_bot[0]/average_n[1]; tint_east_bot[1] = tint_east_bot[1]/average_n[1]; tint_east_bot[2] = tint_east_bot[2]/average_n[1]; tint_west_top[0] = tint_west_top[0]/average_n[2]; tint_west_top[1] = tint_west_top[1]/average_n[2]; tint_west_top[2] = tint_west_top[2]/average_n[2]; tint_east_top[0] = tint_east_top[0]/average_n[3]; tint_east_top[1] = tint_east_top[1]/average_n[3]; tint_east_top[2] = tint_east_top[2]/average_n[3]; block.lightingTint.west_bot[0] = tint_west_bot[0]; block.lightingTint.west_bot[1] = tint_west_bot[1]; block.lightingTint.west_bot[2] = tint_west_bot[2]; block.lightingTint.east_bot[0] = tint_east_bot[0]; block.lightingTint.east_bot[1] = tint_east_bot[1]; block.lightingTint.east_bot[2] = tint_east_bot[2]; block.lightingTint.west_top[0] = tint_west_top[0]; block.lightingTint.west_top[1] = tint_west_top[1]; block.lightingTint.west_top[2] = tint_west_top[2]; block.lightingTint.east_top[0] = tint_east_top[0]; block.lightingTint.east_top[1] = tint_east_top[1]; block.lightingTint.east_top[2] = tint_east_top[2]; } } } void LightingCalculator::spritesPass() { for(const auto& light : _level->lights()) { for(VisualEntity* e : _level->entities()) { if(e->lighting_static) { auto lp = vec3(light.x, light.y, light.z); auto ep = vec3(e->x(), e->y(), e->z() + e->visualHeight() / 2.0f); if(hitsLight(lp, ep)) { lightAdd(e->lighting_tint, light, (lp - ep).length()); } } } } }
35.355556
121
0.633923
alexeyden
bd2f24769b4675ea5eb988c7616f917e027b2783
8,612
hpp
C++
cc/include/bounding_eccentricities.hpp
parthmittal/graph-algorithms
10ebeead1b3fc1ad52f9f69a5bf42d90c5604508
[ "MIT" ]
null
null
null
cc/include/bounding_eccentricities.hpp
parthmittal/graph-algorithms
10ebeead1b3fc1ad52f9f69a5bf42d90c5604508
[ "MIT" ]
null
null
null
cc/include/bounding_eccentricities.hpp
parthmittal/graph-algorithms
10ebeead1b3fc1ad52f9f69a5bf42d90c5604508
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <iterator> #include <queue> #include <vector> #include <graph.hpp> #include <optparser.hpp> #ifndef __BOUNDING_ECCENTRICITY_HPP__ #define __BOUNDING_ECCENTRICITY_HPP__ namespace our { using namespace std; /* * An iterative bfs implementation that returns the distance vector from the * source. * Here graph_type can take up naive graph type and CRS type. */ template <typename graph_type> vector<int> ECCENTRICITY(const graph_type &G, int source, int N) { const int inf = 1e9; std::vector<int> dist(N, inf); std::vector<int> visited(N, false); dist[source] = 0; visited[source] = true; std::queue<int> q; // cerr << "Starting BFS from node : " << source << endl; q.push(source); while (!q.empty()) { int u = q.front(); q.pop(); for (auto &v : G[u]) { if (!visited[v]) { visited[v] = true; dist[v] = dist[u] + 1; q.push(v); } } } for (int i = 0; i < N; i++) { if (dist[i] >= inf) { dist[i] = -1; } } return dist; } /* * Function to prune the degree 1 nodes and create links to nodes that have * similar eccentricity * Returns the vector pruned where pruned[i] takes the following values: * -1 : if this node as well as its neighbours are not pruned * -2 : if the neighbours of this node are pruned * >= 0 : index of the node which is similar to this node */ template <typename graph_type> vector<int> pruning(const graph_type &G, int N, int &count) { std::vector<int> pruned(N, -1); count = 0; for (int i = 0; i < N; i++) { if (!G.in_LWCC(i)) continue; int degree = G[i].size(); int prunee = -1; for (int j = 0; j < degree; j++) { auto it = G[i].begin(); std::advance(it, j); int v = *it; // if degree of v is 1 and its neighbours haven't been pruned. if (G[v].size() == 1 && pruned[v] == -1) { if (prunee == -1) { prunee = v; // prune all but this one } else { pruned[v] = v; count++; pruned[prunee] = -2; // when the neighbours of prunee are pruned } } } } std::cerr << std::endl << "Number of nodes pruned: " << count << std::endl << std::endl; return pruned; } template <typename graph_type> int select_from(int STRATEGY, const vector<int> &is_candidate, const graph_type &G, const vector<int> &lower, const vector<int> &upper, const vector<int> &d, bool &high, int N) { int to_return; if (STRATEGY == 1) // select the node with largest upper - lower difference, // break ties with degree { int max_range = 0; for (int i = 0; i < N; i++) { if (is_candidate[i]) { int diff = upper[i] - lower[i]; if (diff > max_range) { to_return = i; max_range = diff; } else if (diff == max_range && G[i].size() > G[to_return].size()) { to_return = i; } } } } else if (STRATEGY == 2) // select node alternatively between max lower // bound and min upperbound, break ties with degree { int min_lower_bound = N, max_upper_bound = 0; for (int i = 0; i < N; i++) { if (is_candidate[i]) { min_lower_bound = std::min(min_lower_bound, lower[i]); max_upper_bound = std::max(max_upper_bound, upper[i]); } } // cerr << "MIN ECCENTRICITY LOWER BOUND " << min_lower_bound << endl; // cerr << "MAX ECCENTRICITY UPPER BOUND " << max_upper_bound << endl; int min_lower_node = -1, max_upper_node = -1; for (int i = 0; i < N; i++) { if (is_candidate[i]) { if (lower[i] == min_lower_bound && (min_lower_node == -1 || G[i].size() > G[min_lower_node].size())) { // cerr << endl << "Updating min_lower_node to " << i << // endl; min_lower_node = i; } // cerr << upper[i] << " "; if (upper[i] == max_upper_bound && (max_upper_node == -1 || G[i].size() > G[max_upper_node].size())) { // cerr << "Updating max_upper_node to " << i << endl; max_upper_node = i; } } } if (high) { high = false; to_return = min_lower_node; } else { high = true; to_return = max_upper_node; } } else if (STRATEGY == 3) // select node with the farthest distance from the // current node, break ties with degree { to_return = std::distance(d.begin(), std::max_element(d.begin(), d.end())); } // cerr << "NEXT NODE FOR BFS " << to_return << endl; return to_return; } template <typename graph_type> vector<int> bounding_eccentricities(const graph_type &G, int N, int STRATEGY, OptParser &parser) { int PRUNE = parser.checkIncluded("to_prune"); int prune_count = 0; std::vector<int> pruned; if (PRUNE) { pruned = pruning(G, N, prune_count); } int candidates = G.size_LWCC() - prune_count, current = -1; std::vector<int> is_candidate(N, true); std::vector<int> eccentricity(N, 0), ecc_lower(N, 0), ecc_upper(N, N); std::vector<int> d; bool high = true; int number_of_iterations = 0; while (candidates > 0) { // cout << "Number of candidates left " << candidates << endl; if (current == -1) // choose the node with max degree in the first iteration { current = 0; for (int i = 0; i < N; i++) { if (pruned[i] >= 0 || !G.in_LWCC(i)) { is_candidate[i] = false; ecc_lower[i] = N + 1; ecc_upper[i] = -1; continue; } if (G[i].size() > G[current].size()) { current = i; } } } else { current = select_from(STRATEGY, is_candidate, G, ecc_lower, ecc_upper, d, high, N); } // run a bfs fron the selected node d = ECCENTRICITY(G, current, N); // calculate eccentricity of current node eccentricity[current] = *std::max_element(d.begin(), d.end()); is_candidate[current] = false; candidates--; // update lower and upper bounds to connected nodes for (int i = 0; i < N; i++) { if (pruned[i] >= 0 || !G.in_LWCC(i) || d[i] == -1) continue; ecc_lower[i] = std::max( ecc_lower[i], std::max(eccentricity[current] - d[i], d[i])); ecc_upper[i] = std::min(ecc_upper[i], eccentricity[current] + d[i]); } // update candidate set for (int i = 0; i < N; i++) { if (!is_candidate[i] || !G.in_LWCC(i) || pruned[i] >= 0) continue; if (ecc_lower[i] == ecc_upper[i]) { is_candidate[i] = false; eccentricity[i] = ecc_lower[i]; ecc_lower[i] = N + 1; ecc_upper[i] = -1; candidates--; } } number_of_iterations++; #ifdef DEBUG std::cerr << "---------------------------------------------------------" << std::endl; std::cerr << "Performed BFS on " << current << std::endl; std::cerr << "ECCENTRICITY = " << eccentricity[current] << std::endl; std::cerr << "---------------------------------------------------------" << std::endl; #endif } if (PRUNE) { for (int i = 0; i < N; i++) { if (!G.in_LWCC(i)) continue; if (pruned[i] >= 0) eccentricity[i] = eccentricity[pruned[i]]; } } std::cerr << "Number of iterations performed : " << number_of_iterations << endl; return eccentricity; } } // namespace our #endif
32.996169
80
0.474686
parthmittal
bd36c9ba7242d8535dfaadecbaea76c9db574ee4
320
cpp
C++
test/t_0011.cpp
rayloyal/leetcode
79ded19bbb9f2d294b609f30bd3cbfe2cf8311a9
[ "MIT" ]
1
2022-03-02T14:19:55.000Z
2022-03-02T14:19:55.000Z
test/t_0011.cpp
rayloyal/leetcode
79ded19bbb9f2d294b609f30bd3cbfe2cf8311a9
[ "MIT" ]
null
null
null
test/t_0011.cpp
rayloyal/leetcode
79ded19bbb9f2d294b609f30bd3cbfe2cf8311a9
[ "MIT" ]
null
null
null
#include "q_0011.h" #include "gtest/gtest.h" using namespace std; using ::testing::Test; TEST(Q0011, EXAMPLE){ Solution solution; vector<int> height1 = {1, 8, 6, 2, 5, 4, 8, 3, 7}; ASSERT_EQ(solution.maxArea(height1), 49); vector<int> height2 = {1, 1}; ASSERT_EQ(solution.maxArea(height2), 1); }
20
54
0.640625
rayloyal
bd371762adb95fd0bdec8328c6e81eff72b7e664
547
cpp
C++
60 Must Solve List/Unique Email Addresses.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
14
2021-08-22T18:21:14.000Z
2022-03-08T12:04:23.000Z
60 Must Solve List/Unique Email Addresses.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
1
2021-10-17T18:47:17.000Z
2021-10-17T18:47:17.000Z
60 Must Solve List/Unique Email Addresses.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
5
2021-09-01T08:21:12.000Z
2022-03-09T12:13:39.000Z
// Hari class Solution { public: string ruler(string email){ string cleanMail; for(char c: email){ if(c == '+' || c == '@') break; if(c == '.') continue; cleanMail += c; } cleanMail += email.substr(email.find('@')); return cleanMail; } int numUniqueEmails(vector<string>& emails) { unordered_set<string> emailSet; for(auto &it: emails){ emailSet.insert(ruler(it)); } return emailSet.size(); } };
21.88
51
0.482633
Tiger-Team-01
bd38582b1dbd9cb4342900ad66bbde0535bb73ad
3,060
cpp
C++
lib/project_euler/0001-0050/Problem17.cpp
wtmitchell/project_euler
b0fd328af41901aa53f757f1dd84f44f71d7be44
[ "MIT" ]
2
2016-04-03T08:44:15.000Z
2018-10-05T02:12:19.000Z
lib/project_euler/0001-0050/Problem17.cpp
wtmitchell/challenge_problems
b0fd328af41901aa53f757f1dd84f44f71d7be44
[ "MIT" ]
null
null
null
lib/project_euler/0001-0050/Problem17.cpp
wtmitchell/challenge_problems
b0fd328af41901aa53f757f1dd84f44f71d7be44
[ "MIT" ]
null
null
null
//===-- project_euler/Problem17.cpp -----------------------------*- C++ -*-===// // // ProjectEuler.net solutions by Will Mitchell // // This file is distributed under the MIT License. See LICENSE for details. // //===----------------------------------------------------------------------===// /// /// \class project_euler::Problem17 /// \brief Number letter counts /// /// Question /// -------- /// If the numbers 1 to 5 are written out in words: one, two, three, four, five, /// then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. /// /// If all the numbers from 1 to 1000 (one thousand) inclusive were written out /// in words, how many letters would be used? /// /// NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and /// forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 /// letters. The use of "and" when writing out numbers is in compliance with /// British usage. /// /// Analysis /// -------- /// Observe that for this case, we have a lot of redundancies. For instance, /// one, two, ... ninety-nine will occur 10 total times. The word "and" will /// occur 99 times per group of one hundred above 100, for a total of 99*8 times /// Then "one hundred" occurs 100 times, "two hundred" occurs 100 times etc. //===----------------------------------------------------------------------===// #include "Problem17.h" #include <sstream> using std::stringstream; #include <string> using std::string; #include "number/Miscellaneous.h" using number::toEnglishString; using number::toEnglishStringUnder1000; string project_euler::Problem17::answer() { if (!solved) solve(); stringstream ss; ss << "The number of letters used to write 1 to 1000 with British usage is " << count; return ss.str(); } std::string project_euler::Problem17::description() const { return "Problem 17: Number letter counts"; } void project_euler::Problem17::solve() { count = bruteForce3(); solved = true; } unsigned long project_euler::Problem17::bruteForce(const unsigned long limit) const { unsigned long letters = 0; for (auto i = 1ul; i <= limit; ++i) letters += toEnglishString<unsigned long, false, true>(i).length(); return letters; } unsigned long project_euler::Problem17::bruteForce2() const { unsigned long letters = 0; for (auto i = 1u; i <= 999; ++i) letters += toEnglishStringUnder1000<false, true>(i).length(); letters += string("onethousand").length(); return letters; } unsigned long project_euler::Problem17::bruteForce3() const { unsigned long letters = 0; // one, two, ... ninety-nine occur ten times total for (auto i = 1u; i <= 99; ++i) letters += toEnglishStringUnder1000<false>(i).length(); letters *= 10; // All the "and" from British grammar letters += 3 * 99 * 9; // All the "one hundred", "two hundred", etc for (auto i = 1u; i <= 9; ++i) letters += 100 * toEnglishStringUnder1000<false>(i * 100).length(); // Finally one thousand is an odd-ball letters += string("onethousand").length(); return letters; }
29.708738
80
0.63268
wtmitchell
bd399cd1cda1969d2bd5786d2646317b001d54a8
1,247
cpp
C++
011/demo.cpp
jiejieTop/c-plus-plus
2f5832333eb2521e08aea430e65f003cdf4611a5
[ "Apache-2.0" ]
null
null
null
011/demo.cpp
jiejieTop/c-plus-plus
2f5832333eb2521e08aea430e65f003cdf4611a5
[ "Apache-2.0" ]
null
null
null
011/demo.cpp
jiejieTop/c-plus-plus
2f5832333eb2521e08aea430e65f003cdf4611a5
[ "Apache-2.0" ]
null
null
null
/* * @Author: jiejie * @Github: https://github.com/jiejieTop * @Date: 2020-03-21 15:55:37 * @LastEditTime: 2020-04-01 00:45:32 * @Description: the code belongs to jiejie, please keep the author information and source code according to the license. */ #include <string> #include <cstring> #include <iostream> #include <vector> class class_a { private: /* data */ int width, high; public: class_a(int _w, int _h); ~class_a(); void print_info(void); }; class class_b { private: /* data */ int number; class_a test_a; public: class_b(int _b, int _w, int _h); ~class_b(); void print_info(void); }; class_a::class_a(int _w, int _h):width(_w),high(_h) { }; class_a::~class_a() { }; class_b::class_b(int _b, int _w, int _h):number(_b), test_a(_w, _h) { }; class_b::~class_b() { }; void class_a::print_info(void) { std::cout << "class_a::width = " << this->width << std::endl; std::cout << "class_a::high = " << this->high << std::endl; } void class_b::print_info(void) { std::cout << "class_b::number = " << this->number << std::endl; this->test_a.print_info(); } int main(void) { using namespace std; class_b r2(20, 13, 14); r2.print_info(); return 0; }
15.78481
121
0.615076
jiejieTop
bd3fef6937348f5e42026b3f068ee912e83bceb5
1,006
cpp
C++
test/bubblesort.cpp
SherlockZhang3/MyCppTest
393b91270e1485a8e7ff78bd11d9b91c7af3a872
[ "Apache-2.0" ]
null
null
null
test/bubblesort.cpp
SherlockZhang3/MyCppTest
393b91270e1485a8e7ff78bd11d9b91c7af3a872
[ "Apache-2.0" ]
null
null
null
test/bubblesort.cpp
SherlockZhang3/MyCppTest
393b91270e1485a8e7ff78bd11d9b91c7af3a872
[ "Apache-2.0" ]
null
null
null
/*================================================================ * Copyright (c) 2022年 SherlockZhang. All rights reserved. * * 文件名称:bubblesort.cpp * 创 建 者:SherlockZhang * 邮 箱:[email protected] * 创建日期:2021年02月23日 * 描 述:冒泡排序,其实应该说是反冒泡排序,把最大的数沉到后方。 * #pragma once ================================================================*/ #include <iostream> #include "printarr.h" using namespace std; void BubbleSort(int sort[]) { int k = 0; for (int j = 9; j >= 0; j--) //第一轮,bsort[9]是最大的,接下来找第二大的放到bsort[8]里 { for (int i = 0; i < j; i++) //两两比较,把最大的数放到最后 { if (sort[i] > sort[i + 1]) { k = sort[i]; sort[i] = sort[i + 1]; sort[i + 1] = k; } } } } int main() { int sort_array[10] = {2, 4, 1, 5, 0, 8, 6, 9, 3, 7}; PrintArr(sort_array, "冒泡排序前数组sort_array为:"); BubbleSort(sort_array); PrintArr(sort_array, "冒泡排序后数组sort_array为:"); return 0; }
24.536585
71
0.457256
SherlockZhang3
bd49a473ba04607edf42d8ee0c3a946a6b35e102
2,740
cpp
C++
learncpp/ej6c6.cpp
ignaciop/c-varios
c8ef033485efd19a01fbc43658be36473eb1d08d
[ "MIT" ]
null
null
null
learncpp/ej6c6.cpp
ignaciop/c-varios
c8ef033485efd19a01fbc43658be36473eb1d08d
[ "MIT" ]
null
null
null
learncpp/ej6c6.cpp
ignaciop/c-varios
c8ef033485efd19a01fbc43658be36473eb1d08d
[ "MIT" ]
null
null
null
#include <iostream> #include <array> #include <ctime> #include <cstdlib> enum CardSuit { SUIT_CLUB, SUIT_DIAMOND, SUIT_HEART, SUIT_SPADE, MAX_SUITS }; enum CardRank { RANK_2, RANK_3, RANK_4, RANK_5, RANK_6, RANK_7, RANK_8, RANK_9, RANK_10, RANK_JACK, RANK_QUEEN, RANK_KING, RANK_ACE, MAX_RANKS }; struct Card { CardSuit suit; CardRank rank; }; void printCard(const Card &card) { switch (card.rank) { case RANK_2: std::cout << '2'; break; case RANK_3: std::cout << '3'; break; case RANK_4: std::cout << '4'; break; case RANK_5: std::cout << '5'; break; case RANK_6: std::cout << '6'; break; case RANK_7: std::cout << '7'; break; case RANK_8: std::cout << '8'; break; case RANK_9: std::cout << '9'; break; case RANK_10: std::cout << 'T'; break; case RANK_JACK: std::cout << 'J'; break; case RANK_QUEEN: std::cout << 'Q'; break; case RANK_KING: std::cout << 'K'; break; case RANK_ACE: std::cout << 'A'; break; case MAX_RANKS: std::cout << ' '; break; } switch (card.suit) { case SUIT_CLUB: std::cout << 'C'; break; case SUIT_DIAMOND: std::cout << 'D'; break; case SUIT_HEART: std::cout << 'H'; break; case SUIT_SPADE: std::cout << 'S'; break; case MAX_SUITS: std::cout << ' '; break; } } void printDeck(const std::array<Card, 52> &deck) { for (const auto &card : deck) { printCard(card); std::cout << ' '; } std::cout << '\n'; } void swapCard(Card &a, Card &b) { Card temp = a; a = b; b = temp; } int getRandomNumber(int min, int max) { static const double fraction = 1.0 / (static_cast<double>(RAND_MAX) + 1.0); return static_cast<int>(rand()*fraction*(max - min + 1) + min); } void shuffleDeck(std::array<Card, 52> &deck) { for (int index = 0; index < 52; ++index) { int swapIndex = getRandomNumber(0, 51); swapCard(deck[index], deck[swapIndex]); } } int getCardValue(Card &card) { switch (card.rank) { case RANK_2: return 2; break; case RANK_3: return 3; break; case RANK_4: return 4; break; case RANK_5: return 5; break; case RANK_6: return 6; break; case RANK_7: return 7; break; case RANK_8: return 8; break; case RANK_9: return 9; break; case RANK_10: return 10; break; case RANK_JACK: return 10; break; case RANK_QUEEN: return 10; break; case RANK_KING: return 10; break; case RANK_ACE: return 11; break; case MAX_RANKS: return 0; break; } return 0; } int main() { std::array<Card, 52> deck; int card = 0; for (int suit = 0; suit < MAX_SUITS; ++suit) { for (int rank = 0; rank < MAX_RANKS; ++rank) { deck[card].suit = static_cast<CardSuit>(suit); deck[card].rank = static_cast<CardRank>(rank); ++card; } } printDeck(deck); shuffleDeck(deck); printDeck(deck); return 0; }
20.916031
76
0.633212
ignaciop
bd4f382bb6fb76eb87a50d0974245357ea70e6ec
23,775
cpp
C++
ExploringScaleSymmetry/Chapter6/automata2D/Evolver.cpp
TGlad/ExploringScaleSymmetry
25b2dae0279a0ac26f6bae2277d3b76a1cda8b04
[ "MIT" ]
null
null
null
ExploringScaleSymmetry/Chapter6/automata2D/Evolver.cpp
TGlad/ExploringScaleSymmetry
25b2dae0279a0ac26f6bae2277d3b76a1cda8b04
[ "MIT" ]
null
null
null
ExploringScaleSymmetry/Chapter6/automata2D/Evolver.cpp
TGlad/ExploringScaleSymmetry
25b2dae0279a0ac26f6bae2277d3b76a1cda8b04
[ "MIT" ]
null
null
null
// Thomas Lowe, 2020. // Defines the evolution of the automaton. Typically a fixed function of the neighbouring cells. #include "evolver.h" #include "Image.h" #include <string.h> #include <algorithm> using namespace std; Evolver::Evolver(int depth) { this->depth = depth; bitmaps = new Image*[depth+1]; bitmapDuals = new Image*[depth+1]; for (int size = 2, i=1; i<=depth; size *= 2, i++) { bitmaps[i] = new Image(size+2, size+2); // store each pixel bitmaps[i]->clear(); bitmapDuals[i] = new Image(size+2, size+2); // store each pixel bitmapDuals[i]->clear(); } type = 1; reset(); } void Evolver::checkSiblings() { if (type == 10) // temporal coherence { int count = 0; for (int i = 0; i < 89; i++) count += siblingMasks[i] ? 1 : 0; if (count >= 45) { for (int i = 0; i < 89; i++) siblingMasks[i] = !siblingMasks[i]; count = 89 - count; } } } void Evolver::reset() { frame = 0; // type 3 for (int i = 0; i<1<<9; i++) siblingMasks[i] = random(-1.0, 1.0)>0; checkSiblings(); for (int i = 0; i<1<<4; i++) parentMasks[i] = random(-1.0, 1.0)>0; for (int i = 0; i<1<<4; i++) childMasks[i] = random(-1.0, 1.0)>0; for (int i = 0; i<32; i++) totalMasks[i] = random(-1.0, 1.0) > 0 ? 1 : 0; // type 6 for (int i = 0; i<6; i++) for (int j = 0; j<3; j++) for (int k = 0; k<3; k++) { parentsAdd[i][j][k] = random(-1.0, 1.0) > 0 ? 1 : 0; parentsRemove[i][j][k] = random(-1.0, 1.0) > 0 ? 1 : 0; } // type 7 for (int i = 0; i<1<<7; i++) octagonalMasks[i] = random(-1.0, 1.0)>0; randomise(); } bool Evolver::load(const char* fileName, int type) { this->type = type; ifstream fp(fileName, ios::in | ios::binary); if (!fp.is_open()) { printf("Cannot find file: %s\n", fileName); return false; } read(fp); fp.close(); return true; } void Evolver::randomiseMasks(const Evolver& master, float percentVariation) { type = master.type; float threshold = 1.0f - 2.0f*0.01f*percentVariation; for (int i = 0; i<1<<9; i++) { siblingMasks[i] = master.siblingMasks[i]; if (random(-1.0, 1.0) > threshold) siblingMasks[i] = !siblingMasks[i]; } checkSiblings(); for (int i = 0; i<1<<4; i++) { parentMasks[i] = master.parentMasks[i]; if (random(-1.0, 1.0) > threshold) parentMasks[i] = !parentMasks[i]; } for (int i = 0; i<1<<4; i++) { childMasks[i] = master.childMasks[i]; if (random(-1.0, 1.0) > threshold) childMasks[i] = !childMasks[i]; } frame = 0; for (int i = 0; i<32; i++) { totalMasks[i] = master.totalMasks[i]; if (random(-1.0, 1.0) > threshold) totalMasks[i] = 1-totalMasks[i]; } for (int i = 0; i<6; i++) for (int j = 0; j<3; j++) for (int k = 0; k<3; k++) { parentsAdd[i][j][k] = master.parentsAdd[i][j][k]; parentsRemove[i][j][k] = master.parentsRemove[i][j][k]; if (random(-1.0, 1.0) > threshold) parentsAdd[i][j][k] = !parentsAdd[i][j][k]; if (random(-1.0, 1.0) > threshold) parentsRemove[i][j][k] = !parentsRemove[i][j][k]; } for (int i = 0; i<1<<7; i++) { octagonalMasks[i] = master.octagonalMasks[i]; if (random(-1.0, 1.0) > threshold) octagonalMasks[i] = !octagonalMasks[i]; } } void Evolver::randomise(bool *starts) { // initialise the bitmaps to some random image: // This is a recursive process, generating the data procedurally as we go deeper in detail level. for (int level = 2; level<=depth; level++) { int size = 1<<level; if (level == 2 && starts) { int c = 0; for (int i = 0; i<size; i++) for (int j = 0; j<size; j++) bitmaps[level]->setPixel(i, j, starts[c++] ? 128 : 0); continue; } for (int i = 0; i<size; i++) for (int j = 0; j<size; j++) bitmaps[level]->setPixel(i, j, random(-1.0, 1.0) > (type == 7 ? 0.0f : 0.5f) ? 128 : 0); } } void Evolver::read(ifstream &fp) { switch(type) { case(1): for (int i = 0; i<16; i++) fp.read((char *)&totalMasks[i], sizeof(int)); break; case(2): for (int i = 0; i<17; i++) fp.read((char *)&totalMasks[i], sizeof(int)); break; case(3): for (int i = 0; i<1<<9; i++) fp.read((char *)&siblingMasks[i], sizeof(bool)); for (int i = 0; i<1<<4; i++) fp.read((char *)&parentMasks[i], sizeof(bool)); for (int i = 0; i<1<<4; i++) fp.read((char *)&childMasks[i], sizeof(bool)); break; case(4): for (int i = 0; i<33; i++) fp.read((char *)&totalMasks[i], sizeof(int)); break; case(5): for (int i = 0; i<164; i++) fp.read((char *)&siblingMasks[i], sizeof(int)); break; case(6): for (int i = 0; i<6; i++) for (int j = 0; j<3; j++) for (int k = 0; k<3; k++) { fp.read((char *)&parentsAdd[i][j][k], sizeof(bool)); fp.read((char *)&parentsRemove[i][j][k], sizeof(bool)); } break; case(7): for (int i = 0; i<1<<6; i++) fp.read((char *)&octagonalMasks[i], sizeof(bool)); break; case(8) : for (int i = 0; i<1 << 7; i++) fp.read((char *)&octagonalMasks[i], sizeof(bool)); break; case(9) : for (int i = 0; i<1 << 4; i++) fp.read((char *)&parentMasks[i], sizeof(bool)); break; case(10) : for (int i = 0; i<89; i++) fp.read((char *)&siblingMasks[i], sizeof(bool)); break; case(11) : for (int i = 0; i<100; i++) fp.read((char *)&siblingMasks[i], sizeof(bool)); break; default: return; } frame = 0; } void Evolver::write(ofstream &fp) { switch(type) { case(1): for (int i = 0; i<16; i++) fp.write((char *)&totalMasks[i], sizeof(int)); break; case(2): for (int i = 0; i<17; i++) fp.write((char *)&totalMasks[i], sizeof(int)); break; case(3): for (int i = 0; i<1<<9; i++) fp.write((char *)&siblingMasks[i], sizeof(bool)); for (int i = 0; i<1<<4; i++) fp.write((char *)&parentMasks[i], sizeof(bool)); for (int i = 0; i<1<<4; i++) fp.write((char *)&childMasks[i], sizeof(bool)); break; case(4): for (int i = 0; i<33; i++) fp.write((char *)&totalMasks[i], sizeof(int)); break; case(5): for (int i = 0; i<164; i++) fp.write((char *)&siblingMasks[i], sizeof(int)); break; case(6): for (int i = 0; i<6; i++) for (int j = 0; j<3; j++) for (int k = 0; k<3; k++) { fp.write((char *)&parentsAdd[i][j][k], sizeof(bool)); fp.write((char *)&parentsRemove[i][j][k], sizeof(bool)); } break; case(7): for (int i = 0; i<1<<6; i++) fp.write((char *)&octagonalMasks[i], sizeof(bool)); break; case(8) : for (int i = 0; i<1 << 7; i++) fp.write((char *)&octagonalMasks[i], sizeof(bool)); break; case(9) : for (int i = 0; i<1 << 4; i++) fp.write((char *)&parentMasks[i], sizeof(bool)); break; case(10) : for (int i = 0; i<89; i++) fp.write((char *)&siblingMasks[i], sizeof(bool)); break; case(11) : for (int i = 0; i<100; i++) fp.write((char *)&siblingMasks[i], sizeof(bool)); break; default: break; } } void Evolver::set(const Evolver& evolver) { type = evolver.type; for (int i = 0; i<1<<9; i++) siblingMasks[i] = evolver.siblingMasks[i]; for (int i = 0; i<1<<4; i++) parentMasks[i] = evolver.parentMasks[i]; for (int i = 0; i<1<<4; i++) childMasks[i] = evolver.childMasks[i]; frame = 0; for (int i = 0; i<32; i++) totalMasks[i] = evolver.totalMasks[i]; for (int i = 0; i<6; i++) for (int j = 0; j<3; j++) for (int k = 0; k<3; k++) { parentsAdd[i][j][k] = evolver.parentsAdd[i][j][k]; parentsRemove[i][j][k] = evolver.parentsRemove[i][j][k]; } for (int i = 0; i<1<<7; i++) octagonalMasks[i] = evolver.octagonalMasks[i]; } void Evolver::draw() { bitmaps[depth]->generateTexture(); bitmaps[depth]->draw(); } void Evolver::drawMask() { if (type == 9) { int level = 8; bitmapDuals[level]->generateTexture(); bitmapDuals[level]->draw(); } } bool Evolver::getNewValue(int level, int X, int Y) { int dirX = X%2 ? 1 : -1; int dirY = Y%2 ? 1 : -1; int xx = X-dirX; int pattern1 = 0; int pattern2 = 0; for (int x = 0; x<3; x++) { int yy = Y-dirY; for (int y = 0; y<3; y++) { if (bitmaps[level]->isSet(xx, yy)) { pattern1 += 1<<(x+3*y); pattern2 += 1<<(y+3*x); } yy += dirY; } xx += dirX; } if (!siblingMasks[min(pattern1, pattern2)]) return false; xx = X/2; pattern1 = 0; pattern2 = 0; if (level > 0) { for (int x = 0; x<2; x++) { int yy = Y/2; for (int y = 0; y<2; y++) { if (bitmaps[level-1]->isSet(xx, yy)) { pattern1 += 1<<(x+2*y); pattern2 += 1<<(y+2*x); } yy += dirY; } xx += dirX; } } if (parentMasks[min(pattern1, pattern2)]) // the min ensures we remain symettric return true; pattern1 = 0; pattern2 = 0; xx = X*2 + 1 - X%2; if (level+1 <= depth) { for (int x = 0; x<2; x++) { int yy = Y*2 + 1 - Y%2; for (int y = 0; y<2; y++) { if (bitmaps[level+1]->isSet(xx, yy)) { pattern1 += 1<<(x+2*y); pattern2 += 1<<(y+2*x); } yy += dirY; } xx += dirX; } } if (childMasks[min(pattern1, pattern2)]) return true; return false; } bool Evolver::checkAddRemove(int level, int X, int Y, bool addRemove[6][3][3], int i, bool flip) { int dirX = X%2 ? 1 : -1; int dirY = Y%2 ? 1 : -1; int xx = X/2 - dirX; for (int x = 0; x<3; x++, xx += dirX) { int yy = Y/2 - dirY; for (int y = 0; y<3; y++, yy += dirY) { if (x==1 && y==1) continue; // if ((addRemove == parentsRemove && x==2 && y==2) || (addRemove == parentsAdd && x==0 && y==0)) // continue; bool mask = flip ? addRemove[i][y][x] : addRemove[i][x][y]; if (bitmaps[level-1]->isSet(xx, yy) != mask) return false; } } return true; } bool Evolver::getNewValueParentsOnly(int level, int X, int Y) { ASSERT(level > 0); if (bitmaps[level - 1]->isSet(X / 2, Y / 2)) // then prepare to remove { for (int i = 0; i<6; i++) if (checkAddRemove(level, X, Y, parentsRemove, i, false) || checkAddRemove(level, X, Y, parentsRemove, i, true)) return false; return true; } else { for (int i = 0; i<6; i++) if (checkAddRemove(level, X, Y, parentsAdd, i, false) || checkAddRemove(level, X, Y, parentsAdd, i, true)) return true; return false; } } bool Evolver::getNewValue4Parents(int level, int X, int Y) { ASSERT(level > 0); int dirX = X % 2 ? 1 : -1; int dirY = Y % 2 ? 1 : -1; int xx = X / 2; int pattern1 = 0; int pattern2 = 0; if (level > 0) { for (int x = 0; x<2; x++) { int yy = Y / 2; for (int y = 0; y<2; y++) { if (bitmaps[level - 1]->isSet(xx, yy)) { pattern1 += 1 << (x + 2 * y); pattern2 += 1 << (y + 2 * x); } yy += dirY; } xx += dirX; } } return parentMasks[min(pattern1, pattern2)]; // the min ensures we remain symettric } bool Evolver::getNewValueParentsOctagonal2(Image* image, int X, int Y, bool flip, bool extended, int level) { int pattern1 = 0; int pattern2 = 0; int pattern3 = 0; int pattern4 = 0; for (int i = 0; i<3; i++) { for (int j = 0; j<2; j++) { int I; int J; if (!flip) { I = X + i; J = Y + j; } else { I = X + j; J = Y + i; } if (image->isSet(I, J)) { pattern1 += 1<<(i + 3*j); pattern2 += 1<<((2-i) + 3*j); pattern3 += 1<<(i + 3*(1-j)); pattern4 += 1<<((2-i) + 3*(1-j)); } } } if (extended) { int i = 1; for (int j = -1; j<=2; j+=3) { int I; int J; if (!flip) { I = X + i; J = Y + j; } else { I = X + j; J = Y + i; } I = clamped(I, 0, 1<<level); J = clamped(J, 0, 1<<level); if (image->isSet(I, J)) { pattern1 += j==-1 ? 64 : 128; pattern2 += j==-1 ? 64 : 128; pattern3 += j==-1 ? 128 : 64; pattern4 += j==-1 ? 128 : 64; } } int minPattern = min(pattern1, min(pattern2, min(pattern3, pattern4))); if (minPattern <= 127) return octagonalMasks[minPattern]; else return !octagonalMasks[255 - minPattern]; } return octagonalMasks[min(pattern1, min(pattern2, min(pattern3, pattern4)))]; } bool Evolver::getNewValue2(int level, int X, int Y) { int dirX = X % 2 ? 1 : -1; int dirY = Y % 2 ? 1 : -1; int xx = X - dirX; // First, num neighbours int pattern1 = 0; int pattern2 = 0; int numNeighbours = 0; bool centreSet = false; for (int x = 0; x<3; x++) { int yy = Y - dirY; for (int y = 0; y<3; y++) { if (bitmaps[level]->isSet(xx, yy)) { if (x == 1 && y == 1) centreSet = true; else numNeighbours++; } yy += dirY; } xx += dirX; } xx = X / 2; bool hasParent = level > 0 ? bitmaps[level - 1]->isSet(X / 2, Y / 2) : 0; int numChildren = 0; xx = X * 2 + 1 - X % 2; if (level + 1 <= depth) { for (int x = 0; x<2; x++) { int yy = Y * 2 + 1 - Y % 2; for (int y = 0; y<2; y++) { if (bitmaps[level + 1]->isSet(xx, yy)) numChildren++; yy += dirY; } xx += dirX; } } return siblingMasks[((numNeighbours + numChildren * 8) * 2 + (int)hasParent) * 2 + (int)centreSet]; } bool getVal(int numChildren, int numParents, int numNeighbours, bool centreSet, bool *siblingMasks) { int coherence = 1; // even if (numNeighbours > 8 - coherence) return true; if (numNeighbours < coherence) return false; if (numParents == 1 && numChildren > 4 - coherence) return true; if (numParents == 0 && numChildren < coherence) return false; int index = numNeighbours + numChildren * 9 + numParents * 45; if (!centreSet) return siblingMasks[index]; else return !siblingMasks[89 - index]; } bool getVal4(int numChildren, int numParents, int numNeighbours, bool centreSet, bool *siblingMasks) { int coherence = 1; // even if (numNeighbours > 8 - coherence) return true; if (numNeighbours < coherence) return false; if (numParents > 4-coherence && numChildren > 4 - coherence) return true; if (numParents < coherence && numChildren < coherence) return false; int index = numNeighbours + numChildren * 9 + numParents * 45; if (!centreSet) return siblingMasks[index]; else return !siblingMasks[224 - index]; } bool Evolver::getNewValueAllSymmetries(int level, int X, int Y) { int dirX = X % 2 ? 1 : -1; int dirY = Y % 2 ? 1 : -1; int xx = X - dirX; // First, num neighbours int numNeighbours = 0; bool centreSet = false; for (int x = 0; x<3; x++) { int yy = Y - dirY; for (int y = 0; y<3; y++) { if (bitmaps[level]->isSet(xx, yy, centreSet)) { if (x == 1 && y == 1) centreSet = true; else numNeighbours++; } yy += dirY; } xx += dirX; } xx = X / 2; bool hasParent = level > 0 ? bitmaps[level - 1]->isSet(X / 2, Y / 2) : centreSet; #define ONE_PARENT #if defined ONE_PARENT int numParents = hasParent ? 1 : 0; #else int numParents = 0; if (level > 0) { for (int x = 0; x<2; x++) { int yy = Y / 2; for (int y = 0; y<2; y++) { if (bitmaps[level - 1]->isSet(xx, yy)) numParents++; yy += dirY; } xx += dirX; } } #endif int numChildren = 0; xx = X * 2 + 1 - X % 2; if (level + 1 <= depth) { for (int x = 0; x < 2; x++) { int yy = Y * 2 + 1 - Y % 2; for (int y = 0; y < 2; y++) { if (bitmaps[level + 1]->isSet(xx, yy)) numChildren++; yy += dirY; } xx += dirX; } } else numChildren = centreSet ? 4 : 0; // or 3, 1 bool answer = getVal(numChildren, numParents, numNeighbours, centreSet, siblingMasks); /* bool answer2 = !getVal(4-numChildren, 1-numParents, 8-numNeighbours, !centreSet, siblingMasks); if (answer != answer2) { std::cout << "didn't work" << std::endl; }*/ return answer; } bool Evolver::getNewValueChapter6(int level, int X, int Y) { int dirX = X % 2 ? 1 : -1; int dirY = Y % 2 ? 1 : -1; int xx = X - dirX; // First, num neighbours int numNeighbours = 0; bool centreSet = false; for (int x = 0; x<3; x++) { int yy = Y - dirY; for (int y = 0; y<3; y++) { if (bitmaps[level]->isSet(xx, yy, centreSet)) { if (x == 1 && y == 1) centreSet = true; else numNeighbours++; } yy += dirY; } xx += dirX; } xx = X / 2; int numParents = 0; if (level > 0) { for (int x = 0; x < 2; x++) { int yy = Y / 2; for (int y = 0; y < 2; y++) { if (bitmaps[level - 1]->isSet(xx, yy)) numParents++; yy += dirY; } xx += dirX; } } else numParents = centreSet ? 4 : 0; int numChildren = 0; xx = X * 2 + 1 - X % 2; if (level + 1 <= depth) { for (int x = 0; x < 2; x++) { int yy = Y * 2 + 1 - Y % 2; for (int y = 0; y < 2; y++) { if (bitmaps[level + 1]->isSet(xx, yy)) numChildren++; yy += dirY; } xx += dirX; } } else numChildren = centreSet ? 4 : 0; int total = (numChildren + numParents)*9 + numNeighbours; int maxx = max(numParents, numChildren); int minx = min(numParents, numChildren); if (minx >= 3) return true; if (maxx <= 1) return false; if (numNeighbours > 6) return true; if (numNeighbours < 2) return false; if (!centreSet) return siblingMasks[total]; else return !siblingMasks[80 - total]; } bool Evolver::getNewValueSimple(int level, int X, int Y) { int dirX = X%2 ? 1 : -1; int dirY = Y%2 ? 1 : -1; int xx = X-dirX; // First, num neighbours int pattern1 = 0; int pattern2 = 0; int numNeighbours = 0; bool centreSet = false; for (int x = 0; x<3; x++) { int yy = Y-dirY; for (int y = 0; y<3; y++) { if (bitmaps[level]->isSet(xx, yy)) { if (type != 2 && x==1 && y==1) centreSet = true; else numNeighbours++; } yy += dirY; } xx += dirX; } xx = X/2; if (level > 0) { for (int x = 0; x<2; x++) { int yy = Y/2; for (int y = 0; y<2; y++) { if (bitmaps[level-1]->isSet(xx, yy)) numNeighbours++; yy += dirY; } xx += dirX; } } xx = X*2 + 1 - X%2; if (level+1 <= depth) { for (int x = 0; x<2; x++) { int yy = Y*2 + 1 - Y%2; for (int y = 0; y<2; y++) { if (bitmaps[level+1]->isSet(xx, yy)) numNeighbours++; yy += dirY; } xx += dirX; } } if (type == 4) return totalMasks[centreSet ? numNeighbours : numNeighbours + 16]!=0; else return totalMasks[numNeighbours]!=0; } void Evolver::update() { // This performs the covolution frame++; if (type == 6) { if (frame == 1) { for (int level = 3; level <= depth; level++) { int size = 1 << level; for (int i = 0; i<size; i++) { for (int j = 0; j<size; j++) { int& pixel = bitmaps[level]->pixel(i, j); pixel = getNewValueParentsOnly(level, i, j) ? 192 : 0; } } } } return; } if (type == 9) { if (frame == 1) { for (int level = 3; level <= depth; level++) { int size = 1 << level; for (int i = 0; i<size; i++) { for (int j = 0; j<size; j++) { int& pixel = bitmaps[level]->pixel(i, j); pixel = getNewValue4Parents(level, i, j) ? 192 : 0; } } } for (int i = 0; i < 256; i++) { for (int j = 0; j < 256; j++) { bitmapDuals[8]->setPixel(i, j, bitmaps[2]->isSet(i / 64, j / 64) ? 128 : 0); } } } return; } if (type == 7 || type == 8) { if (frame == 1) { bool extended = frame==8; for (int level = 3; level<=depth; level++) { Image* mapFrom = bitmaps[level-1]; Image* mapTo = bitmapDuals[level]; int size = 1<<level; for (int i = 0; i<size/2; i++) { for (int j = 0; j<size/2 + 1; j++) { int toX = i + j; int toY = size/2 - 1 + j-i; int& pixel = mapTo->pixel(toX, toY); pixel = getNewValueParentsOctagonal2(mapFrom, i-1, j-1, false, extended, level-1) ? 192 : 0; } } for (int i = 0; i<size/2 + 1; i++) { for (int j = 0; j<size/2; j++) { int toX = i + j; int toY = size/2 + j-i; int& pixel = mapTo->pixel(toX, toY); pixel = getNewValueParentsOctagonal2(mapFrom, i-1, j-1, true, extended, level-1) ? 192 : 0; } } mapFrom = mapTo; mapTo = bitmaps[level]; for (int i = 0; i<size; i++) { for (int j = 0; j<size; j++) { int& pixel = mapTo->pixel(i, j); int fromX = -1 + (1 + i+j)/2; int fromY = -1 + (size + j-i)/2; pixel = getNewValueParentsOctagonal2(mapFrom, fromX, fromY, ((i+j)%2)==1, extended, level) ? 192 : 0; } } } } return; } // I need to get the timing algorithm right here... int currentLevel = -1; for (int i = 0; i<depth && currentLevel==-1; i++) if ((1<<i) & frame) currentLevel = i; // should go 0,1,0,2,0,1,0,3,... currentLevel = depth - currentLevel; // so most common is the highest detail. if (currentLevel == 1) { currentLevel = depth; frame = 1; } ASSERT(currentLevel <= depth && currentLevel > 1); int size = 1<<currentLevel; if (type < 3 || type == 4) { for (int i = 0; i<size; i++) { for (int j = 0; j<size; j++) { int& pixel = bitmaps[currentLevel]->pixel(i, j); adjustPixel(pixel, getNewValueSimple(currentLevel, i, j)); } } } else if (type == 3) { for (int i = 0; i<size; i++) { for (int j = 0; j<size; j++) { int& pixel = bitmaps[currentLevel]->pixel(i, j); adjustPixel(pixel, getNewValue(currentLevel, i, j)); } } } else if (type == 5) { for (int i = 0; i<size; i++) { for (int j = 0; j<size; j++) { int& pixel = bitmaps[currentLevel]->pixel(i, j); adjustPixel(pixel, getNewValue2(currentLevel, i, j)); } } } else if (type == 10) { for (int i = 0; i<size; i++) { for (int j = 0; j<size; j++) { int& pixel = bitmaps[currentLevel]->pixel(i, j); adjustPixel(pixel, getNewValueAllSymmetries(currentLevel, i, j)); } } } else if (type == 11) { for (int i = 0; i<size; i++) { for (int j = 0; j<size; j++) { int& pixel = bitmaps[currentLevel]->pixel(i, j); adjustPixel(pixel, getNewValueChapter6(currentLevel, i, j)); } } } for (int i = 0; i<size; i++) for (int j = 0; j<size; j++) bitmaps[currentLevel]->pixel(i, j) >>= 1; }
23.400591
118
0.492492
TGlad
bd53af54ccd266c823556b38c6bb37d8d0bf6290
23,001
cpp
C++
ros/src/Mobile_Platform.cpp
norlab-ulaval/navtechradar
4d3ccd2558e79142d656a6c12cd826d9397b0f2d
[ "MIT" ]
2
2020-11-18T17:48:40.000Z
2021-01-12T14:15:17.000Z
ros/src/Mobile_Platform.cpp
norlab-ulaval/navtechradar
4d3ccd2558e79142d656a6c12cd826d9397b0f2d
[ "MIT" ]
null
null
null
ros/src/Mobile_Platform.cpp
norlab-ulaval/navtechradar
4d3ccd2558e79142d656a6c12cd826d9397b0f2d
[ "MIT" ]
1
2022-03-22T16:09:51.000Z
2022-03-22T16:09:51.000Z
/* Copyright 2016 Navtech Radar Limited This file is part of iasdk which is released under The MIT License (MIT). See file LICENSE.txt in project root or go to https://opensource.org/licenses/MIT for full license details. */ /* Node Description: Example Application: Moving Platform Data Processor + Visualizer This app will subscribe to the raw data and give a user-configurable way to process this data. Functionality can be switched on/off using the dynamic reconfigure rqt plugin. Functionality available: Thresholded pointcloud of raw data Image topic using object detection algorithms Grid lines */ #define AZIMUTH_AVERAGING false #include "radarclient.h" #include "nav_ross/nav_msg.h" #include <iostream> #include <string> #include <vector> #include <math.h> #include <cstdint> #include <functional> #include <chrono> #include <thread> #include <cmath> #include <ros/ros.h> #include <std_msgs/String.h> #include <dynamic_reconfigure/server.h> #include <dynamic_paramConfig.h> #include <std_msgs/String.h> #include <visualization_msgs/Marker.h> #include <visualization_msgs/MarkerArray.h> #include <pcl/point_cloud.h> #include <pcl_ros/point_cloud.h> #include <pcl/point_types.h> #include <pcl_conversions/pcl_conversions.h> #include <sensor_msgs/PointCloud2.h> #include <sensor_msgs/point_cloud2_iterator.h> #include <cv_bridge/cv_bridge.h> #include <image_transport/image_transport.h> #include <opencv2/opencv.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <sensor_msgs/LaserScan.h> #ifdef _WIN32 #include <winsock2.h> #pragma comment(lib, "Ws2_32.lib") #pragma comment(lib, "Rpcrt4.lib") #pragma comment(lib, "Iphlpapi.lib") #endif using namespace Navtech; using namespace cv; using namespace std; // DYNAMICALLY CONFIGURABLE PARAMETERS (on the parameter server) uint16_t threshold_value = 62; uint16_t dilation_value = 2; //Default Image Slider value uint16_t gaussian_value = 5; //Default Dilation filter size uint16_t maxangle = 35; uint16_t pcl_threshold_value=60; uint16_t grid_stepSize = 10; uint16_t grid_stepSize_m; uint16_t grid_width; uint16_t grid_height; uint8_t colormap = 10; uint16_t level_above_average=19; uint16_t adaptive_size=2; bool boundingboxes2 = false; bool pointcloud = false; bool LaserScan2 = false; bool MinAreaRect = false; bool radarimage=false; bool radarimageprocessing =false; bool grid = true; bool adaptive_threshold=false; bool longtermaverage = false; bool ThreeDScanApp; static bool Configuration_NOT_Set = 1; double grid_opacity = 0.5; // End of configurable Parameters uint16_t azimuths = 400; bool initialisedaverage; float range_res; float sin_values [405]={}; float cos_values [405]={}; float Phi = 0; float last_Phi=0; pcl::PointCloud<pcl::PointXYZI>::Ptr threeDPCL(new pcl::PointCloud<pcl::PointXYZI>); image_transport::Publisher CartesianPublisher; image_transport::Publisher FilteredPublisher; image_transport::Publisher BoxesPublisher; ros::Publisher LaserScanPublisher2; ros::Publisher PointcloudPublisher; ros::Publisher PointcloudPublisher3d; ros::Publisher MarkerPub; cv::Mat Long_Term_Average; // struct TimerROS // { // std::chrono::time_point<std::chrono::steady_clock>start,end; // std::chrono::duration<float>duration; // TimerROS() // { // start = std::chrono::high_resolution_clock::now(); // } // ~TimerROS() // { // end= std::chrono::high_resolution_clock::now(); // duration=end-start; // float ms = duration.count()*1000.0f; // std::cout<<"Timer took "<<ms<<"ms"<<endl; // } // }; void InitialiseParameters(float &range_res,uint16_t &azimuths) { if((ros::param::has("configuration_range_res")) && (ros::param::has("configuration_azimuths"))){ ros::param::getCached("configuration_range_res",range_res); int az_tmp; ros::param::get("/configuration_azimuths",az_tmp); azimuths = az_tmp; std::cout<<"\nRange Resolution Set from Parameter Server: "<<range_res<<"m\n"; std::cout<<"Number of Azimuths Set from Parameter Server: "<<az_tmp<<"\n"; for (int i=0;i<azimuths;i++){ float theta=(float)i*2*M_PI/azimuths; sin_values[i]=sin(theta); cos_values[i]=cos(theta); } for (int i=az_tmp;i<azimuths+5;i++){ float theta=(float)(i-azimuths)*2*M_PI/azimuths; sin_values[i]=sin(theta); cos_values[i]=cos(theta); } } else{ std::cout<<"\nConfiguration Settings not loaded from ros::param server..\nIf doing data playback, set parameters in server manually using ROS param CLI.\nParameters required are: configuration_range_res and configuration_azimuths\nExiting..."; } } void PublishPointcloud(cv_bridge::CvImagePtr &cv_polar_image, uint16_t &pcl_threshold_value, uint16_t &maxangle, float &range_res) { float theta; cv::Mat navigation_image = (cv_polar_image->image - (double)pcl_threshold_value) * 255.0 / (255.0 - pcl_threshold_value); pcl::PointCloud<pcl::PointXYZI>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZI>); for (int bearing = 0; bearing < cv_polar_image->image.rows; bearing++) { theta = ((float)(bearing) / cv_polar_image->image.rows) * 2 * M_PI; for (size_t ind =1; ind < cv_polar_image->image.cols; ind++) { pcl::PointXYZI p; if ((theta < maxangle * M_PI / 180) || (theta > 2 * M_PI - maxangle * M_PI / 180)) { //The coordinate of the point is taken from the depth map //Y and Z taken negative to immediately visualize the cloud in the right way p.x = range_res * ind * cos(theta); p.y = range_res * ind * sin(theta); //Coloring the point with the corrispondent point in the rectified image p.intensity = navigation_image.at<uchar>(bearing, ind); p.z = 0;//((float)p.intensity / 64);//0; // Uncomment to make height of pixel proportional to Radar cross sectional area ((float)p.intensity / 32); } //Insert point in the cloud, cutting the points that are too distant if (cv_polar_image->image.at<uchar>(bearing, ind) > pcl_threshold_value) cloud->points.push_back(p); } } cloud->width = (int)cloud->points.size(); cloud->height = 1; cloud->header.frame_id = "navtech"; pcl_conversions::toPCL(cv_polar_image->header.stamp,cloud->header.stamp);//pcl_conversions::toPCL(cv_polar_image->header.stamp,cloud->header.stamp); PointcloudPublisher.publish(cloud); } void PublishLaserScan2(cv::Mat &new_im2,float range_resolution, uint16_t range_bins, uint16_t ScanAzimuths, int radarbins,cv_bridge::CvImagePtr &cv_polar_image) { sensor_msgs::LaserScan scan2; scan2.angle_increment = 2 * M_PI / (float)ScanAzimuths; scan2.time_increment = 1 / ((float)4 * (float)ScanAzimuths); scan2.scan_time = 1 / (float)4; scan2.range_min = 0.0; scan2.range_max = 500.0; //Set MaxRange of Scan scan2.ranges.resize(ScanAzimuths); std::cout<<"\nrange_bins, radar_bins: "<<range_bins<<", "<<radarbins; for (int i = 0; i <ScanAzimuths; i++) //all azimuths { for (int j = 30; j < range_bins; j++) //bin ranges { if (j == range_bins - 2) { scan2.ranges[i] = (float)j * range_resolution*(float)range_bins/(float)radarbins; break; } if (new_im2.at<uchar>(i, j) == 0) //if no edge is at this location, carry on searching along azimuth { } else //else, an edge is there - assign edge value { scan2.ranges[i] = (float)j * range_resolution*(float)range_bins / (float)radarbins; break; } } } scan2.header.stamp=cv_polar_image->header.stamp;//cv_polar_image->header.stamp; scan2.header.frame_id = "navtech"; LaserScanPublisher2.publish(scan2); } // void PublishProcessedImage(cv_bridge::CvImagePtr &Input_cv_image){ // cv::Mat radar_image_polar_copy ; // Input_cv_image->image.copyTo(radar_image_polar_copy); // cv::Mat maskmat(Input_cv_image->image.size(),CV_8UC1); // uint16_t cartesian_rows = Input_cv_image->image.cols; // uint16_t cartesian_cols = Input_cv_image->image.cols; // cv::Mat radar_image_cart = cv::Mat::zeros(cartesian_rows, cartesian_cols, CV_8UC1); // cv::Point2f center((float)cartesian_cols / 2, (float)cartesian_rows / 2); // double maxRadius = min(center.y, center.x); // int flags = cv::INTER_LINEAR + cv::WARP_FILL_OUTLIERS; // if(radarimageprocessing){ // cv::GaussianBlur(radar_image_polar_copy, radar_image_polar_copy, cvSize(gaussian_value * 2 + 1, gaussian_value * 2 + 1), 0); // cv::Mat processed_im; // cv::threshold(radar_image_polar_copy, radar_image_polar_copy, threshold_value, 255, CV_THRESH_TOZERO); // cv::Canny(radar_image_polar_copy, radar_image_polar_copy, 50, 100); // cv::dilate(radar_image_polar_copy, radar_image_polar_copy, cv::getStructuringElement(cv::MORPH_RECT, cvSize(dilation_value + 1, dilation_value + 1))); // std::vector<std::vector<cv::Point>> contours; // cv::findContours(radar_image_polar_copy, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); //Save only outer contours // cv::drawContours(maskmat, contours, -1, 255, -1); // cv::warpPolar(maskmat, radar_image_cart, radar_image_cart.size(), center, maxRadius, flags + cv::WARP_INVERSE_MAP); // } // else{ // cv::warpPolar(radar_image_polar_copy, radar_image_cart, radar_image_cart.size(), center, maxRadius, flags + cv::WARP_INVERSE_MAP); // } // cv::rotate(radar_image_cart, radar_image_cart, cv::ROTATE_90_COUNTERCLOCKWISE); // cv::bitwise_not(radar_image_cart,radar_image_cart); // cv::Mat radar_image_color; // cv::applyColorMap(radar_image_cart, radar_image_color, colormap); // if (grid){ // cv::Mat radar_grid; // grid_width = radar_image_color.size().width; // grid_height = radar_image_color.size().height; // radar_image_color.copyTo(radar_grid); // int start_point_y = (grid_height / 2) % grid_stepSize_m; // int start_point_x = (grid_width / 2) % grid_stepSize_m; // for (int i = start_point_y; i < grid_height; i += grid_stepSize_m) // cv::line(radar_grid, Point(0, i), Point(grid_width, i), cv::Scalar(255, 255, 255)); // for (int i = start_point_x; i < grid_width; i += grid_stepSize_m) // cv::line(radar_grid, Point(i, 0), Point(i, grid_height), cv::Scalar(255, 255, 255)); // addWeighted(radar_image_color, grid_opacity, radar_grid, 1 - grid_opacity, 0.0, radar_image_color); // } // sensor_msgs::ImagePtr CartesianMsg = cv_bridge::CvImage(Input_cv_image->header, "rgb8", radar_image_color).toImageMsg(); // CartesianPublisher.publish(CartesianMsg); // } void FindEdges2(cv_bridge::CvImagePtr &inputImage,uint16_t &gaussian_value, cv::Mat &OutputMatImage, uint16_t &threshold_value, uint16_t &dilation_value,uint16_t maxangle) { cv::Mat radar_image_rcs; inputImage->image.copyTo(radar_image_rcs); if(adaptive_threshold){ cv::adaptiveThreshold(OutputMatImage,OutputMatImage,255,ADAPTIVE_THRESH_MEAN_C,THRESH_BINARY,adaptive_size*2+1,-(double)level_above_average); } cv::GaussianBlur(inputImage->image, inputImage->image, cvSize(gaussian_value * 2 + 1, gaussian_value * 2 + 1), 0); if(AZIMUTH_AVERAGING){ cv::Mat mean; cv::reduce(inputImage->image,mean,0,CV_REDUCE_AVG,CV_8UC1); inputImage->image.copyTo(OutputMatImage); for(int i=0;i<inputImage->image.rows;i++) { cv::Mat temp_im; cv::threshold(inputImage->image.row(i), inputImage->image.row(i), (int)mean.at<uchar>(0,i)+threshold_value, 255, CV_THRESH_TOZERO); inputImage->image.row(i).copyTo(OutputMatImage.row(i)); } } else { cv::threshold(inputImage->image, OutputMatImage, threshold_value, 255, CV_THRESH_TOZERO); } cv::vconcat(OutputMatImage,OutputMatImage.rowRange(0,5),OutputMatImage); uint16_t deltaRow = inputImage->image.rows/2 - std::round(((float)maxangle/360.0)*(inputImage->image.rows)); OutputMatImage.rowRange(inputImage->image.rows/2 - deltaRow,inputImage->image.rows/2 +deltaRow).setTo(0); cv::Canny(OutputMatImage, OutputMatImage, 50, 100); } void PublishBoundingBoxes(cv_bridge::CvImagePtr &cv_polar_image,cv::Mat &EdgesMat){ cv::dilate(EdgesMat, EdgesMat, cv::getStructuringElement(cv::MORPH_RECT, cvSize(dilation_value + 1, dilation_value + 1))); std::vector<std::vector<cv::Point>> contours; cv::findContours(EdgesMat, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); //Save only outer contours visualization_msgs::MarkerArray Marker_Array; Marker_Array.markers.resize(contours.size()); cv::Mat radar_image_rcs; cv_polar_image->image.copyTo(radar_image_rcs); //Draw Box Contours Round Features if (MinAreaRect) { geometry_msgs::Point p; p.z=0; for (unsigned int i = 0; i < contours.size(); i++) { Marker_Array.markers[i].header.frame_id = "navtech"; Marker_Array.markers[i].header.stamp = cv_polar_image->header.stamp;//cv_polar_image->header.stamp; Marker_Array.markers[i].action = visualization_msgs::Marker::ADD; Marker_Array.markers[i].type = visualization_msgs::Marker::LINE_STRIP; Marker_Array.markers[i].pose.orientation.w = 1.0; Marker_Array.markers[i].id = i; Marker_Array.markers[i].scale.x = .3; Marker_Array.markers[i].color.b = 0;//1.0; Marker_Array.markers[i].color.a = 1.0; Marker_Array.markers[i].lifetime=ros::Duration(.25); Mat maskmat(radar_image_rcs.size(),CV_8UC1); double minVal; double maxVal; Scalar mean; cv::Point p1,p2; drawContours(maskmat, contours, i, 255, -1); cv::minMaxLoc(radar_image_rcs, &minVal, &maxVal, &p1,&p2, maskmat); mean = cv::mean(radar_image_rcs, maskmat); if(mean[0]>127){mean[0]=127;} Marker_Array.markers[i].color.r = (127+mean[0])/255; Marker_Array.markers[i].color.g = (127-mean[0])/255; cv::RotatedRect rect = cv::minAreaRect(contours[i]); cv::Point2f points[4]; rect.points(points); p.z=1; for (unsigned int j = 0; j<4; j++) { p.y=points[j].x*sin(points[j].y*2*M_PI/(float)azimuths)*range_res; p.x=points[j].x*cos(points[j].y*2*M_PI/(float)azimuths)*range_res; Marker_Array.markers[i].points.push_back(p); } p.y=points[0].x*sin(points[0].y*2*M_PI/(float)azimuths)*range_res; p.x=points[0].x*cos(points[0].y*2*M_PI/(float)azimuths)*range_res; Marker_Array.markers[i].points.push_back(p); Marker_Array.markers.push_back(Marker_Array.markers[i]); } } else{ for (unsigned int i = 0; i < contours.size(); i++) { Marker_Array.markers[i].header.frame_id = "navtech"; Marker_Array.markers[i].header.stamp = cv_polar_image->header.stamp; Marker_Array.markers[i].action = visualization_msgs::Marker::ADD; Marker_Array.markers[i].pose.orientation.w = 1.0; Marker_Array.markers[i].id = i; Marker_Array.markers[i].type = visualization_msgs::Marker::LINE_LIST; Marker_Array.markers[i].scale.x = .2; Marker_Array.markers[i].scale.z = 1,0; Marker_Array.markers[i].color.b = 0;//1.0; Marker_Array.markers[i].color.a = 1.0; Marker_Array.markers[i].lifetime=ros::Duration(.25); std::vector<cv::Point> boundingContour; geometry_msgs::Point p; p.z=0; cv::Mat maskmat(radar_image_rcs.size(),CV_8UC1); double minVal; double maxVal; Scalar mean; cv::Point p1,p2; drawContours(maskmat, contours, i, 255, -1); cv::minMaxLoc(radar_image_rcs, &minVal, &maxVal, &p1,&p2, maskmat); mean = cv::mean(radar_image_rcs, maskmat); if(mean[0]>127){mean[0]=127;} if(mean[0]<50){mean[0]=50;} Marker_Array.markers[i].color.r = (mean[0]-50)/(127-50); Marker_Array.markers[i].color.g = 1.0-(mean[0]-50)/(127-50); for (int k=0;k<10;k++) { for (unsigned int j = 0; j<contours[i].size(); ++j) { p.y=(contours[i][j].x*sin_values[contours[i][j].y])*range_res; p.x=(contours[i][j].x*cos_values[contours[i][j].y])*range_res; Marker_Array.markers[i].points.push_back(p); if(j+1<contours[i].size()) { p.y=(contours[i][j+1].x*sin_values[contours[i][j+1].y])*range_res; p.x=(contours[i][j+1].x*cos_values[contours[i][j+1].y])*range_res; } else { p.y=(contours[i][0].x*sin_values[contours[i][0].y])*range_res; p.x=(contours[i][0].x*cos_values[contours[i][0].y])*range_res; } Marker_Array.markers[i].points.push_back(p); } p.z=p.z+.2; } Marker_Array.markers.push_back(Marker_Array.markers[i]); } } MarkerPub.publish(Marker_Array); } void createThreeDPointCloud(cv::Mat &edgesMatInput,float range_resolution, uint16_t range_bins,uint16_t scanAzimuths,cv_bridge::CvImagePtr &cv_polar_image,uint16_t &maxangle){ last_Phi=Phi; for (int i = 0; i <scanAzimuths; i++) //all azimuths { float theta = 2*M_PI* i/scanAzimuths; pcl::PointXYZI p; for (int j = 30; j < range_bins; j++) //bin ranges { if (edgesMatInput.at<uchar>(i, j) == 0) //if no edge is at this location, carry on searching along azimuth { } else //else, an edge is there - assign edge value { if ((theta < maxangle * M_PI / 180) || (theta > 2 * M_PI - maxangle * M_PI / 180)){ p.x =(float)j * range_resolution* cos(theta); p.y = (float)j * range_resolution* sin(theta) * cos(Phi*M_PI/180); p.z = (float)j * range_resolution* sin(theta) * sin(Phi*M_PI/180); //Coloring the point with the corrispondent point in the rectified image if (p.z>18){ p.intensity=255;} if (p.z<-2){ p.intensity=0;} p.intensity = (int)((p.z+2)*255)/20; threeDPCL->points.push_back(p); } break; } } } } void ParamCallback(nav_ross::dynamic_paramConfig &config, uint32_t level){ Phi = config.Phi; ThreeDScanApp = config.ThreeDScanApp; threshold_value = config.threshold_value; dilation_value = config.dilation_value; gaussian_value = config.gaussian_value; pcl_threshold_value = config.pcl_threshold_value; maxangle = config.maxangle; colormap = config.colormap; boundingboxes2 = config.boundingboxes2; MinAreaRect = config.MinAreaRect; longtermaverage = config.longtermaverage; LaserScan2 = config.LaserScan2_Map; pointcloud = config.pointcloud; radarimage=config.radarimage; radarimageprocessing=config.radarimageprocessing; grid = config.grid; adaptive_threshold=config.adaptive_threshold; level_above_average=config.level_above_average; adaptive_size=config.adaptive_size; if (grid == true){ grid_stepSize = config.grid_stepSize; grid_stepSize_m = grid_stepSize / (range_res * 2); grid_opacity = config.grid_opacity; } } void ChatterCallback(const sensor_msgs::ImageConstPtr &radar_image_polar) { // TimerROS ProcessingTime; cv_bridge::CvImagePtr cv_polar_image; cv_polar_image = cv_bridge::toCvCopy(radar_image_polar, sensor_msgs::image_encodings::MONO8); cv_polar_image->header.stamp=radar_image_polar->header.stamp; uint16_t bins = cv_polar_image->image.rows; //uint16_t azimuths = cv_polar_image->image.cols; rotate(cv_polar_image->image, cv_polar_image->image, cv::ROTATE_90_COUNTERCLOCKWISE); cv::normalize(cv_polar_image->image, cv_polar_image->image, 0, 255, NORM_MINMAX, CV_8UC1); cv::Mat edges_Mat; if (pointcloud == true){ PublishPointcloud(cv_polar_image,pcl_threshold_value,maxangle,range_res); } // if(radarimage){ // //if(initialisedaverage){ // // cv_polar_image->image = Long_Term_Average;} // PublishProcessedImage(cv_polar_image); // } if(longtermaverage){ if(initialisedaverage){ Long_Term_Average = .9*Long_Term_Average + .1*cv_polar_image->image; cv_polar_image->image = cv_polar_image->image-Long_Term_Average; } else{ Long_Term_Average = cv_polar_image->image; initialisedaverage=true; } } else{initialisedaverage=false;} if(boundingboxes2 || LaserScan2 || ThreeDScanApp){ FindEdges2(cv_polar_image,gaussian_value,edges_Mat,threshold_value,dilation_value,maxangle); } if (boundingboxes2 == true){ PublishBoundingBoxes(cv_polar_image,edges_Mat); } if (LaserScan2 == true){ PublishLaserScan2(edges_Mat, range_res, edges_Mat.cols, edges_Mat.rows, bins,cv_polar_image); } if(boundingboxes2 || LaserScan2){ sensor_msgs::ImagePtr FilteredMsg = cv_bridge::CvImage(cv_polar_image->header, "mono8", edges_Mat).toImageMsg(); FilteredPublisher.publish(FilteredMsg); } if(ThreeDScanApp){ if(Phi != last_Phi){ createThreeDPointCloud(edges_Mat,range_res,edges_Mat.cols,edges_Mat.rows,cv_polar_image,maxangle); } threeDPCL->width = (int)threeDPCL->points.size(); threeDPCL->height = 1; threeDPCL->header.frame_id = "navtech"; pcl_conversions::toPCL(cv_polar_image->header.stamp,threeDPCL->header.stamp);//pcl_conversions::toPCL(cv_polar_image->header.stamp,cloud->header.stamp); PointcloudPublisher3d.publish(threeDPCL); } } int main(int argc, char **argv) { ros::init(argc, argv, "Mapper_V2"); ROS_INFO("initialized = true"); ros::NodeHandle n; ros::NodeHandle n1; InitialiseParameters(range_res,azimuths); ros::Subscriber sub2; sub2 = n.subscribe("talker1/Navtech/Polar", 10, ChatterCallback); ROS_INFO("subscribed = true"); image_transport::ImageTransport it(n1); CartesianPublisher = it.advertise("Navtech/Cartesian1", 10); FilteredPublisher = it.advertise("Navtech/Filtered", 10); LaserScanPublisher2 = n1.advertise<sensor_msgs::LaserScan>("Navtech/scan3", 1); PointcloudPublisher = n1.advertise<sensor_msgs::PointCloud2>("Navtech/FilteredPointcloud", 1); PointcloudPublisher3d = n1.advertise<sensor_msgs::PointCloud2>("Navtech/3dPCL", 1); MarkerPub = n1.advertise<visualization_msgs::MarkerArray>("visualization_markers",100); dynamic_reconfigure::Server<nav_ross::dynamic_paramConfig> srv; dynamic_reconfigure::Server<nav_ross::dynamic_paramConfig>::CallbackType f; f = boost::bind(&ParamCallback, _1, _2); srv.setCallback(f); ros::spin(); ROS_INFO("spinning = true"); return 0; }
39.656897
245
0.677449
norlab-ulaval
bd5506aa474c31782c9b4bad560841be06bf25d2
52
cpp
C++
TRAVELLING SALESMAN PROBLEM/stdafx.cpp
Emperor86/racheal-folusho
b1ed0dbc71e7f696ade23c8042d17718ebd2fb2f
[ "MIT" ]
null
null
null
TRAVELLING SALESMAN PROBLEM/stdafx.cpp
Emperor86/racheal-folusho
b1ed0dbc71e7f696ade23c8042d17718ebd2fb2f
[ "MIT" ]
null
null
null
TRAVELLING SALESMAN PROBLEM/stdafx.cpp
Emperor86/racheal-folusho
b1ed0dbc71e7f696ade23c8042d17718ebd2fb2f
[ "MIT" ]
null
null
null
////For precompiled headers #include "stdafx.h"
13
28
0.673077
Emperor86
bd5561a3c355f33ea27f417e351e0457091c9bf9
2,047
cpp
C++
luogu/codes/P4783.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
1
2021-02-22T03:39:24.000Z
2021-02-22T03:39:24.000Z
luogu/codes/P4783.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
null
null
null
luogu/codes/P4783.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
null
null
null
/************************************************************* * > File Name : P4783.cpp * > Author : Tony * > Created Time : 2019/05/18 00:14:50 **************************************************************/ #include <bits/stdc++.h> using namespace std; typedef long long LL; const LL mod = 1e9 + 7; const int maxn = 410; long long a[maxn][maxn]; int n, is[maxn], js[maxn]; void exgcd(LL a, LL b, LL& d, LL& x, LL& y) { if (!b) { d = a; x = 1; y = 0; } else { exgcd(b, a % b, d, y, x); y -= x * (a / b); } } LL inv(LL a, LL n) { LL d, x, y; exgcd(a, n, d, x, y); return d == 1 ? (x + n) % n : -1; } void inv() { for (int k = 1; k <= n; ++k) { for (int i = k; i <= n; ++i) { for (int j = k; j <= n; ++j) { if (a[i][j]) { is[k] = i; js[k] = j; break; } } } for (int i = 1; i <= n; ++i) swap(a[k][i], a[is[k]][i]); for (int i = 1; i <= n; ++i) swap(a[i][k], a[i][js[k]]); if (!a[k][k]) { printf("No Solution\n"); exit(0); } a[k][k] = inv(a[k][k], mod); for (int j = 1; j <= n; ++j) if (j != k) (a[k][j] *= a[k][k]) %= mod; for (int i = 1; i <= n; ++i) if (i != k) for (int j = 1; j <= n; ++j) if (j != k) (a[i][j] += mod - a[i][k] * a[k][j] % mod) %= mod; for (int i = 1; i <= n; ++i) if (i != k) a[i][k] = (mod - a[i][k] * a[k][k] % mod) % mod; } for (int k = n; k; --k) { for (int i = 1; i <= n; ++i) swap(a[js[k]][i], a[k][i]); for (int i = 1; i <= n; ++i) swap(a[i][is[k]], a[i][k]); } } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { scanf("%lld", &a[i][j]); } } inv(); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { printf("%lld ", a[i][j]); } printf("\n"); } return 0; }
28.041096
78
0.31998
Tony031218
32e80c663cdd87684b96a42b9d99fb19fdf8e349
1,628
hpp
C++
mod/wrd/frame/thread.hpp
kniz/World
13b0c8c7fdc6280efcb2135dc3902754a34e6d06
[ "MIT" ]
1
2019-02-02T07:07:32.000Z
2019-02-02T07:07:32.000Z
mod/wrd/frame/thread.hpp
kniz/World
13b0c8c7fdc6280efcb2135dc3902754a34e6d06
[ "MIT" ]
25
2016-09-23T16:36:19.000Z
2019-02-12T14:14:32.000Z
mod/wrd/frame/thread.hpp
kniz/World
13b0c8c7fdc6280efcb2135dc3902754a34e6d06
[ "MIT" ]
null
null
null
#pragma once #include "../builtin/container/mgd/tarr.hpp" #include "../builtin/container/native/tnmap.hpp" #include "frame.hpp" namespace wrd { class slotLoader; typedef tnarr<frame> frames; class _wout thread : public node { WRD(CLASS(thread, node), FRIEND_VERIFY(defAssignExpr, isDefinable), FRIEND_VERIFY(defVarExpr, defineVariable)) friend class baseObj; // for frames. friend class mgdFunc; // for frames. friend class blockExpr; // for frames. friend class defVarExpr; // for frames friend class defAssignExpr; friend class assignExpr; friend class verifier; friend class returnExpr; friend class runExpr; friend class func; // for frames. private: thread(); thread(const node& root); public: const frames& getFrames() const WRD_UNCONST_FUNC(_getFrames()) const frame& getNowFrame() const WRD_UNCONST_FUNC(_getNowFrame()) static thread& get(); static const instancer& getInstancer(); // node: nbicontainer& subs() override; wbool canRun(const ucontainable& args) const override; str run(const ucontainable& args) override; void rel() override; /// @return slot instances loaded by internal system. /// you can cast these to 'slot' types. const nmap& getSlots() const; protected: frames& _getFrames(); frame& _getNowFrame(); private: static thread** _get(); private: frames _frames; str _root; }; }
25.4375
73
0.613022
kniz
32e83204e9a70e8224dd58e8583c3ed4be2e4923
5,823
cc
C++
log/checkpoint_sender.cc
QiumingLu/dawn
58ebdb0d5389f6e3244c91aa09f20a7a47ee8042
[ "BSD-3-Clause" ]
13
2016-12-02T17:00:39.000Z
2020-11-24T08:24:43.000Z
log/checkpoint_sender.cc
QiumingLu/dawn
58ebdb0d5389f6e3244c91aa09f20a7a47ee8042
[ "BSD-3-Clause" ]
1
2018-06-12T05:18:57.000Z
2018-06-12T09:31:05.000Z
log/checkpoint_sender.cc
QiumingLu/dawn
58ebdb0d5389f6e3244c91aa09f20a7a47ee8042
[ "BSD-3-Clause" ]
2
2018-02-01T04:17:38.000Z
2020-04-26T10:21:06.000Z
// Copyright (c) 2016 Mirants Lu. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "log/checkpoint_sender.h" #include <vector> #include "log/checkpoint_manager.h" #include "paxos/config.h" #include "skywalker/file.h" #include "skywalker/logging.h" namespace skywalker { CheckpointSender::CheckpointSender(Config* config, CheckpointManager* manager) : config_(config), manager_(manager), receiver_node_id_(0), sequence_id_(0), ack_sequence_id_(0), flag_(true) {} CheckpointSender::~CheckpointSender() {} bool CheckpointSender::SendCheckpoint(uint64_t node_id) { receiver_node_id_ = node_id; sequence_id_ = 0; ack_sequence_id_ = 0; flag_ = true; bool res = config_->GetCheckpoint()->LockCheckpoint(config_->GetGroupId()); if (res) { uint64_t instance_id = manager_->GetCheckpointInstanceId(); BeginToSend(instance_id); res = SendCheckpointFiles(instance_id); if (res) { EndToSend(instance_id); } else { LOG_ERROR("Group %u - send checkpoint failed.", config_->GetGroupId()); } config_->GetCheckpoint()->UnLockCheckpoint(config_->GetGroupId()); } else { LOG_WARN("Group %u - lock checkpoint failed.", config_->GetGroupId()); } return res; } void CheckpointSender::BeginToSend(uint64_t instance_id) { Content content; content.set_type(CHECKPOINT_MESSAGE); content.set_group_id(config_->GetGroupId()); CheckpointMessage* begin = content.mutable_checkpoint_msg(); begin->set_type(CHECKPOINT_BEGIN); begin->set_node_id(config_->GetNodeId()); begin->set_instance_id(instance_id); begin->set_sequence_id(sequence_id_++); config_->GetMessager()->SendMessage(receiver_node_id_, content); } bool CheckpointSender::SendCheckpointFiles(uint64_t instance_id) { bool res = true; std::string dir; std::vector<std::string> files; const std::vector<StateMachine*>& machines = config_->GetStateMachines(); for (auto& machine : machines) { files.clear(); res = config_->GetCheckpoint()->GetCheckpoint( config_->GetGroupId(), machine->machine_id(), &dir, &files); if (!res) { LOG_ERROR("Group %u - get checkpoint failed, the machine_id=%d.", config_->GetGroupId(), machine->machine_id()); return res; } if (dir.empty() || files.empty()) { continue; } if (dir[dir.size() - 1] != '/') { dir += '/'; } for (auto& file : files) { res = SendFile(instance_id, machine->machine_id(), dir, file); if (!res) { LOG_ERROR("Group %u - send file failed, the file=%s%s.", config_->GetGroupId(), dir.c_str(), file.c_str()); break; } } } return res; } bool CheckpointSender::SendFile(uint64_t instance_id, int machine_id, const std::string& dir, const std::string& file) { std::string fname = dir + file; SequentialFile* seq_file; Status s = FileManager::Instance()->NewSequentialFile(fname, &seq_file); if (!s.ok()) { LOG_ERROR("Group %u - %s", config_->GetGroupId(), s.ToString().c_str()); return false; } bool res = true; size_t offset = 0; Content content; content.set_type(CHECKPOINT_MESSAGE); content.set_group_id(config_->GetGroupId()); CheckpointMessage* msg = content.mutable_checkpoint_msg(); msg->set_type(CHECKPOINT_FILE); msg->set_node_id(config_->GetNodeId()); msg->set_instance_id(instance_id); msg->set_machine_id(machine_id); msg->set_file(file); while (res) { Slice fragmenet; s = seq_file->Read(kBufferSize, &fragmenet, buffer_); if (!s.ok()) { res = false; LOG_ERROR("Group %u - %s", config_->GetGroupId(), s.ToString().c_str()); break; } if (fragmenet.empty()) { break; } offset += fragmenet.size(); msg->set_sequence_id(sequence_id_++); msg->set_offset(offset); msg->set_data(fragmenet.data(), fragmenet.size()); config_->GetMessager()->SendMessage(receiver_node_id_, content); res = CheckReceive(); } delete seq_file; return res; } void CheckpointSender::EndToSend(uint64_t instance_id) { Content content; content.set_type(CHECKPOINT_MESSAGE); content.set_group_id(config_->GetGroupId()); CheckpointMessage* end = content.mutable_checkpoint_msg(); end->set_type(CHECKPOINT_END); end->set_node_id(config_->GetNodeId()); end->set_instance_id(instance_id); end->set_sequence_id(sequence_id_); config_->GetMessager()->SendMessage(receiver_node_id_, content); } void CheckpointSender::OnComfirmReceive(const CheckpointMessage& msg) { std::unique_lock<std::mutex> lock(mutex_); if (msg.node_id() == receiver_node_id_ && msg.sequence_id() == ack_sequence_id_) { ++ack_sequence_id_; flag_ = msg.flag(); cond_.notify_one(); } else { LOG_WARN( "Group %u - receive a confirm message, " "which node_id = %llu, sequence_id=%d, " "but my sender_node_id_=%llu, ack_sequence_id_=%d.", config_->GetGroupId(), (unsigned long long)msg.node_id(), msg.sequence_id(), (unsigned long long)receiver_node_id_, ack_sequence_id_); } } bool CheckpointSender::CheckReceive() { bool res = true; std::unique_lock<std::mutex> lock(mutex_); while (flag_ && (sequence_id_ > ack_sequence_id_ + 16)) { std::cv_status cs = cond_.wait_for(lock, std::chrono::microseconds(10 * 1000 * 1000)); if (cs == std::cv_status::timeout) { LOG_ERROR("Group %u - receive comfirm message timeout!", config_->GetGroupId()); break; } } if (!flag_) { LOG_ERROR("Group %u - error happen.", config_->GetGroupId()); res = false; } return res; } } // namespace skywalker
30.170984
78
0.660484
QiumingLu
32eb7af8480ec3cf7a6c4bbbd4a80d38ebd6377c
39,341
cpp
C++
src/script/lua_api/l_mapgen.cpp
crazyBaboon/MathWorlds
dd35e88e207a26be8632999ad09eeef81820343d
[ "CC-BY-4.0" ]
1
2018-03-01T13:03:01.000Z
2018-03-01T13:03:01.000Z
src/script/lua_api/l_mapgen.cpp
crazyBaboon/MathWorlds
dd35e88e207a26be8632999ad09eeef81820343d
[ "CC-BY-4.0" ]
null
null
null
src/script/lua_api/l_mapgen.cpp
crazyBaboon/MathWorlds
dd35e88e207a26be8632999ad09eeef81820343d
[ "CC-BY-4.0" ]
null
null
null
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "lua_api/l_mapgen.h" #include "lua_api/l_internal.h" #include "lua_api/l_vmanip.h" #include "common/c_converter.h" #include "common/c_content.h" #include "cpp_api/s_security.h" #include "util/serialize.h" #include "server.h" #include "environment.h" #include "emerge.h" #include "mg_biome.h" #include "mg_ore.h" #include "mg_decoration.h" #include "mg_schematic.h" #include "mapgen_v5.h" #include "mapgen_v7.h" #include "filesys.h" #include "settings.h" #include "log.h" struct EnumString ModApiMapgen::es_BiomeTerrainType[] = { {BIOMETYPE_NORMAL, "normal"}, {BIOMETYPE_LIQUID, "liquid"}, {BIOMETYPE_NETHER, "nether"}, {BIOMETYPE_AETHER, "aether"}, {BIOMETYPE_FLAT, "flat"}, {0, NULL}, }; struct EnumString ModApiMapgen::es_DecorationType[] = { {DECO_SIMPLE, "simple"}, {DECO_SCHEMATIC, "schematic"}, {DECO_LSYSTEM, "lsystem"}, {0, NULL}, }; struct EnumString ModApiMapgen::es_MapgenObject[] = { {MGOBJ_VMANIP, "voxelmanip"}, {MGOBJ_HEIGHTMAP, "heightmap"}, {MGOBJ_BIOMEMAP, "biomemap"}, {MGOBJ_HEATMAP, "heatmap"}, {MGOBJ_HUMIDMAP, "humiditymap"}, {MGOBJ_GENNOTIFY, "gennotify"}, {0, NULL}, }; struct EnumString ModApiMapgen::es_OreType[] = { {ORE_SCATTER, "scatter"}, {ORE_SHEET, "sheet"}, {ORE_PUFF, "puff"}, {ORE_BLOB, "blob"}, {ORE_VEIN, "vein"}, {0, NULL}, }; struct EnumString ModApiMapgen::es_Rotation[] = { {ROTATE_0, "0"}, {ROTATE_90, "90"}, {ROTATE_180, "180"}, {ROTATE_270, "270"}, {ROTATE_RAND, "random"}, {0, NULL}, }; struct EnumString ModApiMapgen::es_SchematicFormatType[] = { {SCHEM_FMT_HANDLE, "handle"}, {SCHEM_FMT_MTS, "mts"}, {SCHEM_FMT_LUA, "lua"}, {0, NULL}, }; ObjDef *get_objdef(lua_State *L, int index, ObjDefManager *objmgr); Biome *get_or_load_biome(lua_State *L, int index, BiomeManager *biomemgr); Biome *read_biome_def(lua_State *L, int index, INodeDefManager *ndef); size_t get_biome_list(lua_State *L, int index, BiomeManager *biomemgr, UNORDERED_SET<u8> *biome_id_list); Schematic *get_or_load_schematic(lua_State *L, int index, SchematicManager *schemmgr, StringMap *replace_names); Schematic *load_schematic(lua_State *L, int index, INodeDefManager *ndef, StringMap *replace_names); Schematic *load_schematic_from_def(lua_State *L, int index, INodeDefManager *ndef, StringMap *replace_names); bool read_schematic_def(lua_State *L, int index, Schematic *schem, std::vector<std::string> *names); bool read_deco_simple(lua_State *L, DecoSimple *deco); bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic *deco); /////////////////////////////////////////////////////////////////////////////// ObjDef *get_objdef(lua_State *L, int index, ObjDefManager *objmgr) { if (index < 0) index = lua_gettop(L) + 1 + index; // If a number, assume this is a handle to an object def if (lua_isnumber(L, index)) return objmgr->get(lua_tointeger(L, index)); // If a string, assume a name is given instead if (lua_isstring(L, index)) return objmgr->getByName(lua_tostring(L, index)); return NULL; } /////////////////////////////////////////////////////////////////////////////// Schematic *get_or_load_schematic(lua_State *L, int index, SchematicManager *schemmgr, StringMap *replace_names) { if (index < 0) index = lua_gettop(L) + 1 + index; Schematic *schem = (Schematic *)get_objdef(L, index, schemmgr); if (schem) return schem; schem = load_schematic(L, index, schemmgr->getNodeDef(), replace_names); if (!schem) return NULL; if (schemmgr->add(schem) == OBJDEF_INVALID_HANDLE) { delete schem; return NULL; } return schem; } Schematic *load_schematic(lua_State *L, int index, INodeDefManager *ndef, StringMap *replace_names) { if (index < 0) index = lua_gettop(L) + 1 + index; Schematic *schem = NULL; if (lua_istable(L, index)) { schem = load_schematic_from_def(L, index, ndef, replace_names); if (!schem) { delete schem; return NULL; } } else if (lua_isnumber(L, index)) { return NULL; } else if (lua_isstring(L, index)) { schem = SchematicManager::create(SCHEMATIC_NORMAL); std::string filepath = lua_tostring(L, index); if (!fs::IsPathAbsolute(filepath)) filepath = ModApiBase::getCurrentModPath(L) + DIR_DELIM + filepath; if (!schem->loadSchematicFromFile(filepath, ndef, replace_names)) { delete schem; return NULL; } } return schem; } Schematic *load_schematic_from_def(lua_State *L, int index, INodeDefManager *ndef, StringMap *replace_names) { Schematic *schem = SchematicManager::create(SCHEMATIC_NORMAL); if (!read_schematic_def(L, index, schem, &schem->m_nodenames)) { delete schem; return NULL; } size_t num_nodes = schem->m_nodenames.size(); schem->m_nnlistsizes.push_back(num_nodes); if (replace_names) { for (size_t i = 0; i != num_nodes; i++) { StringMap::iterator it = replace_names->find(schem->m_nodenames[i]); if (it != replace_names->end()) schem->m_nodenames[i] = it->second; } } if (ndef) ndef->pendNodeResolve(schem); return schem; } bool read_schematic_def(lua_State *L, int index, Schematic *schem, std::vector<std::string> *names) { if (!lua_istable(L, index)) return false; //// Get schematic size lua_getfield(L, index, "size"); v3s16 size = check_v3s16(L, -1); lua_pop(L, 1); schem->size = size; //// Get schematic data lua_getfield(L, index, "data"); luaL_checktype(L, -1, LUA_TTABLE); u32 numnodes = size.X * size.Y * size.Z; schem->schemdata = new MapNode[numnodes]; size_t names_base = names->size(); UNORDERED_MAP<std::string, content_t> name_id_map; u32 i = 0; for (lua_pushnil(L); lua_next(L, -2); i++, lua_pop(L, 1)) { if (i >= numnodes) continue; //// Read name std::string name; if (!getstringfield(L, -1, "name", name)) throw LuaError("Schematic data definition with missing name field"); //// Read param1/prob u8 param1; if (!getintfield(L, -1, "param1", param1) && !getintfield(L, -1, "prob", param1)) param1 = MTSCHEM_PROB_ALWAYS_OLD; //// Read param2 u8 param2 = getintfield_default(L, -1, "param2", 0); //// Find or add new nodename-to-ID mapping UNORDERED_MAP<std::string, content_t>::iterator it = name_id_map.find(name); content_t name_index; if (it != name_id_map.end()) { name_index = it->second; } else { name_index = names->size() - names_base; name_id_map[name] = name_index; names->push_back(name); } //// Perform probability/force_place fixup on param1 param1 >>= 1; if (getboolfield_default(L, -1, "force_place", false)) param1 |= MTSCHEM_FORCE_PLACE; //// Actually set the node in the schematic schem->schemdata[i] = MapNode(name_index, param1, param2); } if (i != numnodes) { errorstream << "read_schematic_def: incorrect number of " "nodes provided in raw schematic data (got " << i << ", expected " << numnodes << ")." << std::endl; return false; } //// Get Y-slice probability values (if present) schem->slice_probs = new u8[size.Y]; for (i = 0; i != (u32) size.Y; i++) schem->slice_probs[i] = MTSCHEM_PROB_ALWAYS; lua_getfield(L, index, "yslice_prob"); if (lua_istable(L, -1)) { for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) { u16 ypos; if (!getintfield(L, -1, "ypos", ypos) || (ypos >= size.Y) || !getintfield(L, -1, "prob", schem->slice_probs[ypos])) continue; schem->slice_probs[ypos] >>= 1; } } return true; } void read_schematic_replacements(lua_State *L, int index, StringMap *replace_names) { if (index < 0) index = lua_gettop(L) + 1 + index; lua_pushnil(L); while (lua_next(L, index)) { std::string replace_from; std::string replace_to; if (lua_istable(L, -1)) { // Old {{"x", "y"}, ...} format lua_rawgeti(L, -1, 1); if (!lua_isstring(L, -1)) throw LuaError("schematics: replace_from field is not a string"); replace_from = lua_tostring(L, -1); lua_pop(L, 1); lua_rawgeti(L, -1, 2); if (!lua_isstring(L, -1)) throw LuaError("schematics: replace_to field is not a string"); replace_to = lua_tostring(L, -1); lua_pop(L, 1); } else { // New {x = "y", ...} format if (!lua_isstring(L, -2)) throw LuaError("schematics: replace_from field is not a string"); replace_from = lua_tostring(L, -2); if (!lua_isstring(L, -1)) throw LuaError("schematics: replace_to field is not a string"); replace_to = lua_tostring(L, -1); } replace_names->insert(std::make_pair(replace_from, replace_to)); lua_pop(L, 1); } } /////////////////////////////////////////////////////////////////////////////// Biome *get_or_load_biome(lua_State *L, int index, BiomeManager *biomemgr) { if (index < 0) index = lua_gettop(L) + 1 + index; Biome *biome = (Biome *)get_objdef(L, index, biomemgr); if (biome) return biome; biome = read_biome_def(L, index, biomemgr->getNodeDef()); if (!biome) return NULL; if (biomemgr->add(biome) == OBJDEF_INVALID_HANDLE) { delete biome; return NULL; } return biome; } Biome *read_biome_def(lua_State *L, int index, INodeDefManager *ndef) { if (!lua_istable(L, index)) return NULL; BiomeType biometype = (BiomeType)getenumfield(L, index, "type", ModApiMapgen::es_BiomeTerrainType, BIOMETYPE_NORMAL); Biome *b = BiomeManager::create(biometype); b->name = getstringfield_default(L, index, "name", ""); b->depth_top = getintfield_default(L, index, "depth_top", 0); b->depth_filler = getintfield_default(L, index, "depth_filler", -31000); b->depth_water_top = getintfield_default(L, index, "depth_water_top", 0); b->depth_riverbed = getintfield_default(L, index, "depth_riverbed", 0); b->y_min = getintfield_default(L, index, "y_min", -31000); b->y_max = getintfield_default(L, index, "y_max", 31000); b->heat_point = getfloatfield_default(L, index, "heat_point", 0.f); b->humidity_point = getfloatfield_default(L, index, "humidity_point", 0.f); b->flags = 0; //reserved std::vector<std::string> &nn = b->m_nodenames; nn.push_back(getstringfield_default(L, index, "node_top", "")); nn.push_back(getstringfield_default(L, index, "node_filler", "")); nn.push_back(getstringfield_default(L, index, "node_stone", "")); nn.push_back(getstringfield_default(L, index, "node_water_top", "")); nn.push_back(getstringfield_default(L, index, "node_water", "")); nn.push_back(getstringfield_default(L, index, "node_river_water", "")); nn.push_back(getstringfield_default(L, index, "node_riverbed", "")); nn.push_back(getstringfield_default(L, index, "node_dust", "")); ndef->pendNodeResolve(b); return b; } size_t get_biome_list(lua_State *L, int index, BiomeManager *biomemgr, UNORDERED_SET<u8> *biome_id_list) { if (index < 0) index = lua_gettop(L) + 1 + index; if (lua_isnil(L, index)) return 0; bool is_single = true; if (lua_istable(L, index)) { lua_getfield(L, index, "name"); is_single = !lua_isnil(L, -1); lua_pop(L, 1); } if (is_single) { Biome *biome = get_or_load_biome(L, index, biomemgr); if (!biome) { infostream << "get_biome_list: failed to get biome '" << (lua_isstring(L, index) ? lua_tostring(L, index) : "") << "'." << std::endl; return 1; } biome_id_list->insert(biome->index); return 0; } // returns number of failed resolutions size_t fail_count = 0; size_t count = 0; for (lua_pushnil(L); lua_next(L, index); lua_pop(L, 1)) { count++; Biome *biome = get_or_load_biome(L, -1, biomemgr); if (!biome) { fail_count++; infostream << "get_biome_list: failed to get biome '" << (lua_isstring(L, -1) ? lua_tostring(L, -1) : "") << "'" << std::endl; continue; } biome_id_list->insert(biome->index); } return fail_count; } /////////////////////////////////////////////////////////////////////////////// // get_biome_id(biomename) // returns the biome id used in biomemap int ModApiMapgen::l_get_biome_id(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *biome_str = lua_tostring(L, 1); if (!biome_str) return 0; BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr; if (!bmgr) return 0; Biome *biome = (Biome *)bmgr->getByName(biome_str); if (!biome || biome->index == OBJDEF_INVALID_INDEX) return 0; lua_pushinteger(L, biome->index); return 1; } // get_mapgen_object(objectname) // returns the requested object used during map generation int ModApiMapgen::l_get_mapgen_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *mgobjstr = lua_tostring(L, 1); int mgobjint; if (!string_to_enum(es_MapgenObject, mgobjint, mgobjstr ? mgobjstr : "")) return 0; enum MapgenObject mgobj = (MapgenObject)mgobjint; EmergeManager *emerge = getServer(L)->getEmergeManager(); Mapgen *mg = emerge->getCurrentMapgen(); if (!mg) throw LuaError("Must only be called in a mapgen thread!"); size_t maplen = mg->csize.X * mg->csize.Z; switch (mgobj) { case MGOBJ_VMANIP: { MMVManip *vm = mg->vm; // VoxelManip object LuaVoxelManip *o = new LuaVoxelManip(vm, true); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, "VoxelManip"); lua_setmetatable(L, -2); // emerged min pos push_v3s16(L, vm->m_area.MinEdge); // emerged max pos push_v3s16(L, vm->m_area.MaxEdge); return 3; } case MGOBJ_HEIGHTMAP: { if (!mg->heightmap) return 0; lua_newtable(L); for (size_t i = 0; i != maplen; i++) { lua_pushinteger(L, mg->heightmap[i]); lua_rawseti(L, -2, i + 1); } return 1; } case MGOBJ_BIOMEMAP: { if (!mg->biomegen) return 0; lua_newtable(L); for (size_t i = 0; i != maplen; i++) { lua_pushinteger(L, mg->biomegen->biomemap[i]); lua_rawseti(L, -2, i + 1); } return 1; } case MGOBJ_HEATMAP: { if (!mg->biomegen || mg->biomegen->getType() != BIOMEGEN_ORIGINAL) return 0; BiomeGenOriginal *bg = (BiomeGenOriginal *)mg->biomegen; lua_newtable(L); for (size_t i = 0; i != maplen; i++) { lua_pushnumber(L, bg->heatmap[i]); lua_rawseti(L, -2, i + 1); } return 1; } case MGOBJ_HUMIDMAP: { if (!mg->biomegen || mg->biomegen->getType() != BIOMEGEN_ORIGINAL) return 0; BiomeGenOriginal *bg = (BiomeGenOriginal *)mg->biomegen; lua_newtable(L); for (size_t i = 0; i != maplen; i++) { lua_pushnumber(L, bg->humidmap[i]); lua_rawseti(L, -2, i + 1); } return 1; } case MGOBJ_GENNOTIFY: { std::map<std::string, std::vector<v3s16> >event_map; std::map<std::string, std::vector<v3s16> >::iterator it; mg->gennotify.getEvents(event_map); lua_newtable(L); for (it = event_map.begin(); it != event_map.end(); ++it) { lua_newtable(L); for (size_t j = 0; j != it->second.size(); j++) { push_v3s16(L, it->second[j]); lua_rawseti(L, -2, j + 1); } lua_setfield(L, -2, it->first.c_str()); } return 1; } } return 0; } int ModApiMapgen::l_get_mapgen_params(lua_State *L) { NO_MAP_LOCK_REQUIRED; log_deprecated(L, "get_mapgen_params is deprecated; " "use get_mapgen_setting instead"); std::string value; MapSettingsManager *settingsmgr = getServer(L)->getEmergeManager()->map_settings_mgr; lua_newtable(L); settingsmgr->getMapSetting("mg_name", &value); lua_pushstring(L, value.c_str()); lua_setfield(L, -2, "mgname"); settingsmgr->getMapSetting("seed", &value); std::istringstream ss(value); u64 seed; ss >> seed; lua_pushinteger(L, seed); lua_setfield(L, -2, "seed"); settingsmgr->getMapSetting("water_level", &value); lua_pushinteger(L, stoi(value, -32768, 32767)); lua_setfield(L, -2, "water_level"); settingsmgr->getMapSetting("chunksize", &value); lua_pushinteger(L, stoi(value, -32768, 32767)); lua_setfield(L, -2, "chunksize"); settingsmgr->getMapSetting("mg_flags", &value); lua_pushstring(L, value.c_str()); lua_setfield(L, -2, "flags"); return 1; } // set_mapgen_params(params) // set mapgen parameters int ModApiMapgen::l_set_mapgen_params(lua_State *L) { NO_MAP_LOCK_REQUIRED; log_deprecated(L, "set_mapgen_params is deprecated; " "use set_mapgen_setting instead"); if (!lua_istable(L, 1)) return 0; MapSettingsManager *settingsmgr = getServer(L)->getEmergeManager()->map_settings_mgr; lua_getfield(L, 1, "mgname"); if (lua_isstring(L, -1)) settingsmgr->setMapSetting("mg_name", lua_tostring(L, -1), true); lua_getfield(L, 1, "seed"); if (lua_isnumber(L, -1)) settingsmgr->setMapSetting("seed", lua_tostring(L, -1), true); lua_getfield(L, 1, "water_level"); if (lua_isnumber(L, -1)) settingsmgr->setMapSetting("water_level", lua_tostring(L, -1), true); lua_getfield(L, 1, "chunksize"); if (lua_isnumber(L, -1)) settingsmgr->setMapSetting("chunksize", lua_tostring(L, -1), true); warn_if_field_exists(L, 1, "flagmask", "Deprecated: flags field now includes unset flags."); lua_getfield(L, 1, "flags"); if (lua_isstring(L, -1)) settingsmgr->setMapSetting("mg_flags", lua_tostring(L, -1), true); return 0; } // get_mapgen_setting(name) int ModApiMapgen::l_get_mapgen_setting(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string value; MapSettingsManager *settingsmgr = getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); if (!settingsmgr->getMapSetting(name, &value)) return 0; lua_pushstring(L, value.c_str()); return 1; } // get_mapgen_setting_noiseparams(name) int ModApiMapgen::l_get_mapgen_setting_noiseparams(lua_State *L) { NO_MAP_LOCK_REQUIRED; NoiseParams np; MapSettingsManager *settingsmgr = getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); if (!settingsmgr->getMapSettingNoiseParams(name, &np)) return 0; push_noiseparams(L, &np); return 1; } // set_mapgen_setting(name, value, override_meta) // set mapgen config values int ModApiMapgen::l_set_mapgen_setting(lua_State *L) { NO_MAP_LOCK_REQUIRED; MapSettingsManager *settingsmgr = getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); const char *value = luaL_checkstring(L, 2); bool override_meta = lua_isboolean(L, 3) ? lua_toboolean(L, 3) : false; if (!settingsmgr->setMapSetting(name, value, override_meta)) { errorstream << "set_mapgen_setting: cannot set '" << name << "' after initialization" << std::endl; } return 0; } // set_mapgen_setting_noiseparams(name, noiseparams, set_default) // set mapgen config values for noise parameters int ModApiMapgen::l_set_mapgen_setting_noiseparams(lua_State *L) { NO_MAP_LOCK_REQUIRED; MapSettingsManager *settingsmgr = getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); NoiseParams np; if (!read_noiseparams(L, 2, &np)) { errorstream << "set_mapgen_setting_noiseparams: cannot set '" << name << "'; invalid noiseparams table" << std::endl; return 0; } bool override_meta = lua_isboolean(L, 3) ? lua_toboolean(L, 3) : false; if (!settingsmgr->setMapSettingNoiseParams(name, &np, override_meta)) { errorstream << "set_mapgen_setting_noiseparams: cannot set '" << name << "' after initialization" << std::endl; } return 0; } // set_noiseparams(name, noiseparams, set_default) // set global config values for noise parameters int ModApiMapgen::l_set_noiseparams(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *name = luaL_checkstring(L, 1); NoiseParams np; if (!read_noiseparams(L, 2, &np)) { errorstream << "set_noiseparams: cannot set '" << name << "'; invalid noiseparams table" << std::endl; return 0; } bool set_default = lua_isboolean(L, 3) ? lua_toboolean(L, 3) : true; g_settings->setNoiseParams(name, np, set_default); return 0; } // get_noiseparams(name) int ModApiMapgen::l_get_noiseparams(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string name = luaL_checkstring(L, 1); NoiseParams np; if (!g_settings->getNoiseParams(name, np)) return 0; push_noiseparams(L, &np); return 1; } // set_gen_notify(flags, {deco_id_table}) int ModApiMapgen::l_set_gen_notify(lua_State *L) { NO_MAP_LOCK_REQUIRED; u32 flags = 0, flagmask = 0; EmergeManager *emerge = getServer(L)->getEmergeManager(); if (read_flags(L, 1, flagdesc_gennotify, &flags, &flagmask)) { emerge->gen_notify_on &= ~flagmask; emerge->gen_notify_on |= flags; } if (lua_istable(L, 2)) { lua_pushnil(L); while (lua_next(L, 2)) { if (lua_isnumber(L, -1)) emerge->gen_notify_on_deco_ids.insert((u32)lua_tonumber(L, -1)); lua_pop(L, 1); } } return 0; } // get_gen_notify() int ModApiMapgen::l_get_gen_notify(lua_State *L) { NO_MAP_LOCK_REQUIRED; EmergeManager *emerge = getServer(L)->getEmergeManager(); push_flags_string(L, flagdesc_gennotify, emerge->gen_notify_on, emerge->gen_notify_on); lua_newtable(L); int i = 1; for (std::set<u32>::iterator it = emerge->gen_notify_on_deco_ids.begin(); it != emerge->gen_notify_on_deco_ids.end(); ++it) { lua_pushnumber(L, *it); lua_rawseti(L, -2, i); i++; } return 2; } // register_biome({lots of stuff}) int ModApiMapgen::l_register_biome(lua_State *L) { NO_MAP_LOCK_REQUIRED; int index = 1; luaL_checktype(L, index, LUA_TTABLE); INodeDefManager *ndef = getServer(L)->getNodeDefManager(); BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr; Biome *biome = read_biome_def(L, index, ndef); if (!biome) return 0; ObjDefHandle handle = bmgr->add(biome); if (handle == OBJDEF_INVALID_HANDLE) { delete biome; return 0; } lua_pushinteger(L, handle); return 1; } // register_decoration({lots of stuff}) int ModApiMapgen::l_register_decoration(lua_State *L) { NO_MAP_LOCK_REQUIRED; int index = 1; luaL_checktype(L, index, LUA_TTABLE); INodeDefManager *ndef = getServer(L)->getNodeDefManager(); DecorationManager *decomgr = getServer(L)->getEmergeManager()->decomgr; BiomeManager *biomemgr = getServer(L)->getEmergeManager()->biomemgr; SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr; enum DecorationType decotype = (DecorationType)getenumfield(L, index, "deco_type", es_DecorationType, -1); Decoration *deco = decomgr->create(decotype); if (!deco) { errorstream << "register_decoration: decoration placement type " << decotype << " not implemented" << std::endl; return 0; } deco->name = getstringfield_default(L, index, "name", ""); deco->fill_ratio = getfloatfield_default(L, index, "fill_ratio", 0.02); deco->y_min = getintfield_default(L, index, "y_min", -31000); deco->y_max = getintfield_default(L, index, "y_max", 31000); deco->nspawnby = getintfield_default(L, index, "num_spawn_by", -1); deco->sidelen = getintfield_default(L, index, "sidelen", 8); if (deco->sidelen <= 0) { errorstream << "register_decoration: sidelen must be " "greater than 0" << std::endl; delete deco; return 0; } //// Get node name(s) to place decoration on size_t nread = getstringlistfield(L, index, "place_on", &deco->m_nodenames); deco->m_nnlistsizes.push_back(nread); //// Get decoration flags getflagsfield(L, index, "flags", flagdesc_deco, &deco->flags, NULL); //// Get NoiseParams to define how decoration is placed lua_getfield(L, index, "noise_params"); if (read_noiseparams(L, -1, &deco->np)) deco->flags |= DECO_USE_NOISE; lua_pop(L, 1); //// Get biomes associated with this decoration (if any) lua_getfield(L, index, "biomes"); if (get_biome_list(L, -1, biomemgr, &deco->biomes)) infostream << "register_decoration: couldn't get all biomes " << std::endl; lua_pop(L, 1); //// Get node name(s) to 'spawn by' size_t nnames = getstringlistfield(L, index, "spawn_by", &deco->m_nodenames); deco->m_nnlistsizes.push_back(nnames); if (nnames == 0 && deco->nspawnby != -1) { errorstream << "register_decoration: no spawn_by nodes defined," " but num_spawn_by specified" << std::endl; } //// Handle decoration type-specific parameters bool success = false; switch (decotype) { case DECO_SIMPLE: success = read_deco_simple(L, (DecoSimple *)deco); break; case DECO_SCHEMATIC: success = read_deco_schematic(L, schemmgr, (DecoSchematic *)deco); break; case DECO_LSYSTEM: break; } if (!success) { delete deco; return 0; } ndef->pendNodeResolve(deco); ObjDefHandle handle = decomgr->add(deco); if (handle == OBJDEF_INVALID_HANDLE) { delete deco; return 0; } lua_pushinteger(L, handle); return 1; } bool read_deco_simple(lua_State *L, DecoSimple *deco) { int index = 1; int param2; deco->deco_height = getintfield_default(L, index, "height", 1); deco->deco_height_max = getintfield_default(L, index, "height_max", 0); if (deco->deco_height <= 0) { errorstream << "register_decoration: simple decoration height" " must be greater than 0" << std::endl; return false; } size_t nnames = getstringlistfield(L, index, "decoration", &deco->m_nodenames); deco->m_nnlistsizes.push_back(nnames); if (nnames == 0) { errorstream << "register_decoration: no decoration nodes " "defined" << std::endl; return false; } param2 = getintfield_default(L, index, "param2", 0); if ((param2 < 0) || (param2 > 255)) { errorstream << "register_decoration: param2 out of bounds (0-255)" << std::endl; return false; } deco->deco_param2 = (u8)param2; return true; } bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic *deco) { int index = 1; deco->rotation = (Rotation)getenumfield(L, index, "rotation", ModApiMapgen::es_Rotation, ROTATE_0); StringMap replace_names; lua_getfield(L, index, "replacements"); if (lua_istable(L, -1)) read_schematic_replacements(L, -1, &replace_names); lua_pop(L, 1); lua_getfield(L, index, "schematic"); Schematic *schem = get_or_load_schematic(L, -1, schemmgr, &replace_names); lua_pop(L, 1); deco->schematic = schem; return schem != NULL; } // register_ore({lots of stuff}) int ModApiMapgen::l_register_ore(lua_State *L) { NO_MAP_LOCK_REQUIRED; int index = 1; luaL_checktype(L, index, LUA_TTABLE); INodeDefManager *ndef = getServer(L)->getNodeDefManager(); BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr; OreManager *oremgr = getServer(L)->getEmergeManager()->oremgr; enum OreType oretype = (OreType)getenumfield(L, index, "ore_type", es_OreType, ORE_SCATTER); Ore *ore = oremgr->create(oretype); if (!ore) { errorstream << "register_ore: ore_type " << oretype << " not implemented\n"; return 0; } ore->name = getstringfield_default(L, index, "name", ""); ore->ore_param2 = (u8)getintfield_default(L, index, "ore_param2", 0); ore->clust_scarcity = getintfield_default(L, index, "clust_scarcity", 1); ore->clust_num_ores = getintfield_default(L, index, "clust_num_ores", 1); ore->clust_size = getintfield_default(L, index, "clust_size", 0); ore->noise = NULL; ore->flags = 0; //// Get noise_threshold warn_if_field_exists(L, index, "noise_threshhold", "Deprecated: new name is \"noise_threshold\"."); float nthresh; if (!getfloatfield(L, index, "noise_threshold", nthresh) && !getfloatfield(L, index, "noise_threshhold", nthresh)) nthresh = 0; ore->nthresh = nthresh; //// Get y_min/y_max warn_if_field_exists(L, index, "height_min", "Deprecated: new name is \"y_min\"."); warn_if_field_exists(L, index, "height_max", "Deprecated: new name is \"y_max\"."); int ymin, ymax; if (!getintfield(L, index, "y_min", ymin) && !getintfield(L, index, "height_min", ymin)) ymin = -31000; if (!getintfield(L, index, "y_max", ymax) && !getintfield(L, index, "height_max", ymax)) ymax = 31000; ore->y_min = ymin; ore->y_max = ymax; if (ore->clust_scarcity <= 0 || ore->clust_num_ores <= 0) { errorstream << "register_ore: clust_scarcity and clust_num_ores" "must be greater than 0" << std::endl; delete ore; return 0; } //// Get flags getflagsfield(L, index, "flags", flagdesc_ore, &ore->flags, NULL); //// Get biomes associated with this decoration (if any) lua_getfield(L, index, "biomes"); if (get_biome_list(L, -1, bmgr, &ore->biomes)) infostream << "register_ore: couldn't get all biomes " << std::endl; lua_pop(L, 1); //// Get noise parameters if needed lua_getfield(L, index, "noise_params"); if (read_noiseparams(L, -1, &ore->np)) { ore->flags |= OREFLAG_USE_NOISE; } else if (ore->NEEDS_NOISE) { errorstream << "register_ore: specified ore type requires valid " "noise parameters" << std::endl; delete ore; return 0; } lua_pop(L, 1); //// Get type-specific parameters switch (oretype) { case ORE_SHEET: { OreSheet *oresheet = (OreSheet *)ore; oresheet->column_height_min = getintfield_default(L, index, "column_height_min", 1); oresheet->column_height_max = getintfield_default(L, index, "column_height_max", ore->clust_size); oresheet->column_midpoint_factor = getfloatfield_default(L, index, "column_midpoint_factor", 0.5f); break; } case ORE_PUFF: { OrePuff *orepuff = (OrePuff *)ore; lua_getfield(L, index, "np_puff_top"); read_noiseparams(L, -1, &orepuff->np_puff_top); lua_pop(L, 1); lua_getfield(L, index, "np_puff_bottom"); read_noiseparams(L, -1, &orepuff->np_puff_bottom); lua_pop(L, 1); break; } case ORE_VEIN: { OreVein *orevein = (OreVein *)ore; orevein->random_factor = getfloatfield_default(L, index, "random_factor", 1.f); break; } default: break; } ObjDefHandle handle = oremgr->add(ore); if (handle == OBJDEF_INVALID_HANDLE) { delete ore; return 0; } ore->m_nodenames.push_back(getstringfield_default(L, index, "ore", "")); size_t nnames = getstringlistfield(L, index, "wherein", &ore->m_nodenames); ore->m_nnlistsizes.push_back(nnames); ndef->pendNodeResolve(ore); lua_pushinteger(L, handle); return 1; } // register_schematic({schematic}, replacements={}) int ModApiMapgen::l_register_schematic(lua_State *L) { NO_MAP_LOCK_REQUIRED; SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr; StringMap replace_names; if (lua_istable(L, 2)) read_schematic_replacements(L, 2, &replace_names); Schematic *schem = load_schematic(L, 1, schemmgr->getNodeDef(), &replace_names); if (!schem) return 0; ObjDefHandle handle = schemmgr->add(schem); if (handle == OBJDEF_INVALID_HANDLE) { delete schem; return 0; } lua_pushinteger(L, handle); return 1; } // clear_registered_biomes() int ModApiMapgen::l_clear_registered_biomes(lua_State *L) { NO_MAP_LOCK_REQUIRED; BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr; bmgr->clear(); return 0; } // clear_registered_decorations() int ModApiMapgen::l_clear_registered_decorations(lua_State *L) { NO_MAP_LOCK_REQUIRED; DecorationManager *dmgr = getServer(L)->getEmergeManager()->decomgr; dmgr->clear(); return 0; } // clear_registered_ores() int ModApiMapgen::l_clear_registered_ores(lua_State *L) { NO_MAP_LOCK_REQUIRED; OreManager *omgr = getServer(L)->getEmergeManager()->oremgr; omgr->clear(); return 0; } // clear_registered_schematics() int ModApiMapgen::l_clear_registered_schematics(lua_State *L) { NO_MAP_LOCK_REQUIRED; SchematicManager *smgr = getServer(L)->getEmergeManager()->schemmgr; smgr->clear(); return 0; } // generate_ores(vm, p1, p2, [ore_id]) int ModApiMapgen::l_generate_ores(lua_State *L) { NO_MAP_LOCK_REQUIRED; EmergeManager *emerge = getServer(L)->getEmergeManager(); Mapgen mg; mg.seed = emerge->mgparams->seed; mg.vm = LuaVoxelManip::checkobject(L, 1)->vm; mg.ndef = getServer(L)->getNodeDefManager(); v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : mg.vm->m_area.MinEdge + v3s16(1,1,1) * MAP_BLOCKSIZE; v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) : mg.vm->m_area.MaxEdge - v3s16(1,1,1) * MAP_BLOCKSIZE; sortBoxVerticies(pmin, pmax); u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed); emerge->oremgr->placeAllOres(&mg, blockseed, pmin, pmax); return 0; } // generate_decorations(vm, p1, p2, [deco_id]) int ModApiMapgen::l_generate_decorations(lua_State *L) { NO_MAP_LOCK_REQUIRED; EmergeManager *emerge = getServer(L)->getEmergeManager(); Mapgen mg; mg.seed = emerge->mgparams->seed; mg.vm = LuaVoxelManip::checkobject(L, 1)->vm; mg.ndef = getServer(L)->getNodeDefManager(); v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : mg.vm->m_area.MinEdge + v3s16(1,1,1) * MAP_BLOCKSIZE; v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) : mg.vm->m_area.MaxEdge - v3s16(1,1,1) * MAP_BLOCKSIZE; sortBoxVerticies(pmin, pmax); u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed); emerge->decomgr->placeAllDecos(&mg, blockseed, pmin, pmax); return 0; } // create_schematic(p1, p2, probability_list, filename, y_slice_prob_list) int ModApiMapgen::l_create_schematic(lua_State *L) { MAP_LOCK_REQUIRED; INodeDefManager *ndef = getServer(L)->getNodeDefManager(); const char *filename = luaL_checkstring(L, 4); CHECK_SECURE_PATH(L, filename, true); Map *map = &(getEnv(L)->getMap()); Schematic schem; v3s16 p1 = check_v3s16(L, 1); v3s16 p2 = check_v3s16(L, 2); sortBoxVerticies(p1, p2); std::vector<std::pair<v3s16, u8> > prob_list; if (lua_istable(L, 3)) { lua_pushnil(L); while (lua_next(L, 3)) { if (lua_istable(L, -1)) { lua_getfield(L, -1, "pos"); v3s16 pos = check_v3s16(L, -1); lua_pop(L, 1); u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS); prob_list.push_back(std::make_pair(pos, prob)); } lua_pop(L, 1); } } std::vector<std::pair<s16, u8> > slice_prob_list; if (lua_istable(L, 5)) { lua_pushnil(L); while (lua_next(L, 5)) { if (lua_istable(L, -1)) { s16 ypos = getintfield_default(L, -1, "ypos", 0); u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS); slice_prob_list.push_back(std::make_pair(ypos, prob)); } lua_pop(L, 1); } } if (!schem.getSchematicFromMap(map, p1, p2)) { errorstream << "create_schematic: failed to get schematic " "from map" << std::endl; return 0; } schem.applyProbabilities(p1, &prob_list, &slice_prob_list); schem.saveSchematicToFile(filename, ndef); actionstream << "create_schematic: saved schematic file '" << filename << "'." << std::endl; lua_pushboolean(L, true); return 1; } // place_schematic(p, schematic, rotation, replacement) int ModApiMapgen::l_place_schematic(lua_State *L) { MAP_LOCK_REQUIRED; GET_ENV_PTR; ServerMap *map = &(env->getServerMap()); SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr; //// Read position v3s16 p = check_v3s16(L, 1); //// Read rotation int rot = ROTATE_0; const char *enumstr = lua_tostring(L, 3); if (enumstr) string_to_enum(es_Rotation, rot, std::string(enumstr)); //// Read force placement bool force_placement = true; if (lua_isboolean(L, 5)) force_placement = lua_toboolean(L, 5); //// Read node replacements StringMap replace_names; if (lua_istable(L, 4)) read_schematic_replacements(L, 4, &replace_names); //// Read schematic Schematic *schem = get_or_load_schematic(L, 2, schemmgr, &replace_names); if (!schem) { errorstream << "place_schematic: failed to get schematic" << std::endl; return 0; } schem->placeOnMap(map, p, 0, (Rotation)rot, force_placement); lua_pushboolean(L, true); return 1; } int ModApiMapgen::l_place_schematic_on_vmanip(lua_State *L) { NO_MAP_LOCK_REQUIRED; SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr; //// Read VoxelManip object MMVManip *vm = LuaVoxelManip::checkobject(L, 1)->vm; //// Read position v3s16 p = check_v3s16(L, 2); //// Read rotation int rot = ROTATE_0; const char *enumstr = lua_tostring(L, 4); if (enumstr) string_to_enum(es_Rotation, rot, std::string(enumstr)); //// Read force placement bool force_placement = true; if (lua_isboolean(L, 6)) force_placement = lua_toboolean(L, 6); //// Read node replacements StringMap replace_names; if (lua_istable(L, 5)) read_schematic_replacements(L, 5, &replace_names); //// Read schematic Schematic *schem = get_or_load_schematic(L, 3, schemmgr, &replace_names); if (!schem) { errorstream << "place_schematic: failed to get schematic" << std::endl; return 0; } bool schematic_did_fit = schem->placeOnVManip( vm, p, 0, (Rotation)rot, force_placement); lua_pushboolean(L, schematic_did_fit); return 1; } // serialize_schematic(schematic, format, options={...}) int ModApiMapgen::l_serialize_schematic(lua_State *L) { NO_MAP_LOCK_REQUIRED; SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr; //// Read options bool use_comments = getboolfield_default(L, 3, "lua_use_comments", false); u32 indent_spaces = getintfield_default(L, 3, "lua_num_indent_spaces", 0); //// Get schematic bool was_loaded = false; Schematic *schem = (Schematic *)get_objdef(L, 1, schemmgr); if (!schem) { schem = load_schematic(L, 1, NULL, NULL); was_loaded = true; } if (!schem) { errorstream << "serialize_schematic: failed to get schematic" << std::endl; return 0; } //// Read format of definition to save as int schem_format = SCHEM_FMT_MTS; const char *enumstr = lua_tostring(L, 2); if (enumstr) string_to_enum(es_SchematicFormatType, schem_format, std::string(enumstr)); //// Serialize to binary string std::ostringstream os(std::ios_base::binary); switch (schem_format) { case SCHEM_FMT_MTS: schem->serializeToMts(&os, schem->m_nodenames); break; case SCHEM_FMT_LUA: schem->serializeToLua(&os, schem->m_nodenames, use_comments, indent_spaces); break; default: return 0; } if (was_loaded) delete schem; std::string ser = os.str(); lua_pushlstring(L, ser.c_str(), ser.length()); return 1; } void ModApiMapgen::Initialize(lua_State *L, int top) { API_FCT(get_biome_id); API_FCT(get_mapgen_object); API_FCT(get_mapgen_params); API_FCT(set_mapgen_params); API_FCT(get_mapgen_setting); API_FCT(set_mapgen_setting); API_FCT(get_mapgen_setting_noiseparams); API_FCT(set_mapgen_setting_noiseparams); API_FCT(set_noiseparams); API_FCT(get_noiseparams); API_FCT(set_gen_notify); API_FCT(get_gen_notify); API_FCT(register_biome); API_FCT(register_decoration); API_FCT(register_ore); API_FCT(register_schematic); API_FCT(clear_registered_biomes); API_FCT(clear_registered_decorations); API_FCT(clear_registered_ores); API_FCT(clear_registered_schematics); API_FCT(generate_ores); API_FCT(generate_decorations); API_FCT(create_schematic); API_FCT(place_schematic); API_FCT(place_schematic_on_vmanip); API_FCT(serialize_schematic); }
25.679504
88
0.689281
crazyBaboon
32f11db0729e90e6d3b0383560439ac40545ae4a
957
cpp
C++
GFG/All_Code/1.cpp
jnvshubham7/CPP_Programming
a17c4a42209556495302ca305b7c3026df064041
[ "Apache-2.0" ]
1
2021-12-22T12:37:36.000Z
2021-12-22T12:37:36.000Z
GFG/All_Code/1.cpp
jnvshubham7/CPP_Programming
a17c4a42209556495302ca305b7c3026df064041
[ "Apache-2.0" ]
null
null
null
GFG/All_Code/1.cpp
jnvshubham7/CPP_Programming
a17c4a42209556495302ca305b7c3026df064041
[ "Apache-2.0" ]
null
null
null
class Solution { public: // create isupper() function bool isupper(char c) { return c >= 'A' && c <= 'Z'; } string arrangeString(string str) { int sum=0; //store all capital letters in a vector and all integer in different vector vector<char> capital; vector<int> integer; for(int i=0;i<str.length();i++) { if(isupper(str[i])) { capital.push_back(str[i]); } else { integer.push_back(str[i]-'0'); } } sort(capital.begin(),capital.end()); //sum of all integer for(int i=0;i<integer.size();i++) { sum=sum+integer[i]; } //return all capital letters follwed by sum of all integer string ans=""; for(int i=0;i<capital.size();i++) { ans=ans+capital[i]; } ans=ans+to_string(sum); return ans; } };
17.4
83
0.486938
jnvshubham7
fd07203282a5ae22b4030a053f9cb7a812387b64
1,776
cpp
C++
Lab 1/Ch_02-SourceCode/first_last_lab1A.cpp
candr002/CS150
8270f60769fc8a9c18e5c5c46879b63663ba2117
[ "Unlicense" ]
null
null
null
Lab 1/Ch_02-SourceCode/first_last_lab1A.cpp
candr002/CS150
8270f60769fc8a9c18e5c5c46879b63663ba2117
[ "Unlicense" ]
null
null
null
Lab 1/Ch_02-SourceCode/first_last_lab1A.cpp
candr002/CS150
8270f60769fc8a9c18e5c5c46879b63663ba2117
[ "Unlicense" ]
null
null
null
/* ************************************************************* Programmer: your name goes here file: first_last_lab1A.cpp change this TA Name: ( put the name of your lab TA here ) TA Email: (find out your TAs email, and put it here) Given the length and width of a rectangle, this C++ program computes and outputs the perimeter and area of the rectangle. Modify this program to produce the required output as explained in the comments below. You will submit this program as part of your solution for lab 1. //********************************************************** */ #include <iostream> using namespace std; int main() { ///(1) Required "programmer info code" ///(2) declared. initialize these variables to zero! double length; double width; double area; double perimeter; cout << "\nProgram to compute and output the perimeter and " << "area of a rectangle.\n\n\n"; ///(3) ask the user for the length, using a cout statement ///(4) store input in variable, using a cin statement ///(5) do the same two steps for width. ///(7)calculations - all you need to do is UN-comment these two lines //perimeter = 2 * (length + width); //area = length * width; ///(8) output results cout << " Length = " << length << endl; cout << " Width = " << width << endl; cout << " Perimeter = " << perimeter << endl; cout << " Area = " << area << endl; cout<<"\n\n"; // comment out this line, and see what happens cout <<endl<<endl; // now comment out this one,.. what happens? ///(9) exit program return 0; }//========================end of main======================
30.101695
74
0.543356
candr002
fd0a0c8bc0a0a65f09217ac5ff7ebbd688911cd1
685
cpp
C++
engine/src/resources/text.cpp
gguedesaz/thunder
41fbd8393dc6974ae26e1d77d5f2f8f252e14b5c
[ "Apache-2.0" ]
null
null
null
engine/src/resources/text.cpp
gguedesaz/thunder
41fbd8393dc6974ae26e1d77d5f2f8f252e14b5c
[ "Apache-2.0" ]
null
null
null
engine/src/resources/text.cpp
gguedesaz/thunder
41fbd8393dc6974ae26e1d77d5f2f8f252e14b5c
[ "Apache-2.0" ]
null
null
null
#include "resources/text.h" #include <variant.h> #define DATA "Data" #include <log.h> class TextPrivate { public: ByteArray m_Data; }; Text::Text() : p_ptr(new TextPrivate) { } Text::~Text() { delete p_ptr; } void Text::loadUserData(const VariantMap &data) { auto it = data.find(DATA); if(it != data.end()) { p_ptr->m_Data = (*it).second.toByteArray(); } } char *Text::data() const { return reinterpret_cast<char *>(&p_ptr->m_Data[0]); } uint32_t Text::size() const { return p_ptr->m_Data.size(); } void Text::setSize(uint32_t size) { p_ptr->m_Data.resize(size); } string Text::text() { return string(data(), size()); }
15.222222
55
0.614599
gguedesaz
fd0a1148a9c5147f96bb3d20de84c538c1c85fb2
1,752
cpp
C++
src/tf.cpp
JeroenBongers96/suii_3d_vision_ros
82197531f44d58d2579cd2563757581aae91d021
[ "BSD-3-Clause" ]
null
null
null
src/tf.cpp
JeroenBongers96/suii_3d_vision_ros
82197531f44d58d2579cd2563757581aae91d021
[ "BSD-3-Clause" ]
null
null
null
src/tf.cpp
JeroenBongers96/suii_3d_vision_ros
82197531f44d58d2579cd2563757581aae91d021
[ "BSD-3-Clause" ]
1
2020-01-01T22:29:24.000Z
2020-01-01T22:29:24.000Z
#include "tf.h" Transformation::Transformation() { std::cout << "TRANSFORMATION CREATED" << std::endl; std::cout << "##############################" << std::endl; } tf_struct_data Transformation::getTf(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud) { //Calculate the TF from a given PCD pcl::MomentOfInertiaEstimation <pcl::PointXYZ> feature_extractor; feature_extractor.setInputCloud (cloud); feature_extractor.compute (); std::vector <float> moment_of_inertia; std::vector <float> eccentricity; Eigen::Matrix3f rotational_matrix_OBB; float major_value, middle_value, minor_value; Eigen::Vector3f major_vector, middle_vector, minor_vector; Eigen::Vector3f mass_center; feature_extractor.getMomentOfInertia (moment_of_inertia); feature_extractor.getEigenValues (major_value, middle_value, minor_value); feature_extractor.getEigenVectors (major_vector, middle_vector, minor_vector); feature_extractor.getMassCenter (mass_center); int scale = 8; pcl::PointXYZ center (mass_center (0), mass_center (1), mass_center (2)); pcl::PointXYZ x_axis ((major_vector (0) / scale) + mass_center (0), (major_vector (1) / scale) + mass_center (1), (major_vector (2) / scale) + mass_center (2)); pcl::PointXYZ y_axis ((middle_vector (0) / scale) + mass_center (0), (middle_vector (1) / scale) + mass_center (1), (middle_vector (2) / scale) + mass_center (2)); pcl::PointXYZ z_axis ((minor_vector (0) / scale) + mass_center (0), (minor_vector (1) / scale) + mass_center (1), (minor_vector (2) / scale) + mass_center (2)); tf_tf_data.center = center; tf_tf_data.x_axis = x_axis; tf_tf_data.y_axis = y_axis; tf_tf_data.z_axis = z_axis; return(tf_tf_data); }
39.818182
167
0.693493
JeroenBongers96
fd0c7f939264a99f958c88c75bf0b80b09fa9fe0
869
cpp
C++
01_Programming_Basics/01_Programming_Basics_with_C++/12_Nested_Loops_Lab/08_cookie_factory.cpp
Knightwalker/Knowledgebase
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
[ "MIT" ]
null
null
null
01_Programming_Basics/01_Programming_Basics_with_C++/12_Nested_Loops_Lab/08_cookie_factory.cpp
Knightwalker/Knowledgebase
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
[ "MIT" ]
null
null
null
01_Programming_Basics/01_Programming_Basics_with_C++/12_Nested_Loops_Lab/08_cookie_factory.cpp
Knightwalker/Knowledgebase
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main() { int n = 0; cin >> n; cin.ignore(); for(int i = 0; i < n; i++) { bool flour = false; bool eggs = false; bool sugar = false; while(true) { string products = ""; getline(cin, products); if(products == "flour") { flour = true; } else if(products == "eggs") { eggs = true; } else if(products == "sugar") { sugar = true; } else if(products == "Bake!") { if(flour == true && eggs == true && sugar == true) { cout << "Baking batch number " << i + 1 << "..." << endl; break; } else { cout << "The batter should contain flour, eggs and sugar!" << endl; continue; } } } } return 0; }
18.104167
77
0.443038
Knightwalker
fd11af26a355261c9fa59c2fa1a80e32ba376a7c
886
cpp
C++
src/main.cpp
LuisHsu/Assignment_4
1735738d3d523d9c3a007d9fb471f121071e75fe
[ "BSD-3-Clause" ]
null
null
null
src/main.cpp
LuisHsu/Assignment_4
1735738d3d523d9c3a007d9fb471f121071e75fe
[ "BSD-3-Clause" ]
null
null
null
src/main.cpp
LuisHsu/Assignment_4
1735738d3d523d9c3a007d9fb471f121071e75fe
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright 2020 Luis Hsu. All rights reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file. */ #include <exception> #include <iostream> #include <unistd.h> #include <termios.h> #include <SpiningCube.hpp> int main(int argc, char const *argv[]){ struct termios term; tcgetattr(STDIN_FILENO, &term); { struct termios rawterm = term; cfmakeraw(&rawterm); rawterm.c_oflag |= OPOST; rawterm.c_lflag |= ISIG; tcsetattr(STDIN_FILENO, TCSANOW, &rawterm); } try{ SpiningCube app; app.exec(); }catch(std::exception& err){ std::cerr << err.what() << std::endl; tcflush(STDIN_FILENO, TCIFLUSH); tcsetattr(STDIN_FILENO, TCSANOW, &term); return -1; } tcflush(STDIN_FILENO, TCIFLUSH); tcsetattr(STDIN_FILENO, TCSANOW, &term); return 0; }
23.945946
53
0.646727
LuisHsu
fd121f8e6cc0bc74c3e6252f16e0f94bff96cdaa
591
hpp
C++
src/frontend/internal/patch_args.hpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
14
2020-04-14T17:00:56.000Z
2021-08-30T08:29:26.000Z
src/frontend/internal/patch_args.hpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
27
2020-12-27T16:00:44.000Z
2021-08-01T13:12:14.000Z
src/frontend/internal/patch_args.hpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
1
2020-05-29T18:33:37.000Z
2020-05-29T18:33:37.000Z
#pragma once #include "frontend/diag.hpp" #include "frontend/source_table.hpp" #include "prog/program.hpp" #include <functional> namespace frontend::internal { using PatchDiagReportFunc = std::function<void(Diag)>; /* Patches all call expressions in the program to include any information that was not available * when the call expression was initialally created. One example of this are the optional argument * initializers. */ auto patchCallArgs( const prog::Program& prog, const SourceTable& srcTable, PatchDiagReportFunc reportDiag) -> void; } // namespace frontend::internal
31.105263
100
0.774958
BastianBlokland
fd15d303beaf57426353061df12517d496968fa8
1,569
cpp
C++
codeforces/A - Number of Apartments/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/A - Number of Apartments/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/A - Number of Apartments/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729# created: Mar/24/2021 19:41 * solution_verdict: Accepted language: GNU C++17 (64) * run_time: 31 ms memory_used: 0 KB * problem: https://codeforces.com/contest/1430/problem/A ****************************************************************************************/ #include<iostream> #include<vector> #include<cstring> #include<map> #include<bitset> #include<assert.h> #include<algorithm> #include<iomanip> #include<cmath> #include<set> #include<queue> #include<sstream> #include<unordered_map> #include<unordered_set> #include<chrono> #include<stack> #include<deque> #include<random> #define long long long using namespace std; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const int N=1000,inf=1e9,mod=998244353; int a[N+2],b[N+2],c[N+2]; int main() { ios_base::sync_with_stdio(0);cin.tie(0); memset(a,-1,sizeof a); for(int i=0;i<=1000;i++) { if(i*3>1000)break; for(int j=0;j<=1000;j++) { if(i*3+j*5>1000)break; for(int k=0;k<=1000;k++) { int id=i*3+j*5+k*7; if(id>1000)break; a[id]=i,b[id]=j,c[id]=k; } } } int t;cin>>t; while(t--) { int x;cin>>x; if(a[x]==-1)cout<<-1<<endl; else cout<<a[x]<<" "<<b[x]<<" "<<c[x]<<endl; } return 0; }
28.017857
111
0.472275
kzvd4729
fd1a6891a77eab53fe831499466f91e5161229d8
6,258
cpp
C++
src/WebinariaEditor/TimelineControl/OverlayControl.cpp
mkmpvtltd1/Webinaria
41d86467800adb48e77ab49b92891fae2a99bb77
[ "MIT" ]
5
2015-03-31T15:51:22.000Z
2022-03-10T07:01:56.000Z
src/WebinariaEditor/TimelineControl/OverlayControl.cpp
mkmpvtltd1/Webinaria
41d86467800adb48e77ab49b92891fae2a99bb77
[ "MIT" ]
null
null
null
src/WebinariaEditor/TimelineControl/OverlayControl.cpp
mkmpvtltd1/Webinaria
41d86467800adb48e77ab49b92891fae2a99bb77
[ "MIT" ]
null
null
null
#include "StdAfx.h" #include "OverlayControl.h" #include "OverlayElement.h" #include "utils.h" OverlayControl::OverlayControl() : activeOverlay(0) , hitTestAnchor(ohtNone) { memset(&clickAnchor, 0, sizeof(clickAnchor)); } OverlayControl::~OverlayControl() { } Overlay* OverlayControl::GetActiveOverlay() const { return activeOverlay; } void OverlayControl::SetActiveOverlay(Overlay *overlay) { activeOverlay = overlay; } void OverlayControl::ResetCursor() { UpdateCursor(ohtNone); } void OverlayControl::UpdateCursor(OverlayHitTest hitTest) { HCURSOR cursor; switch (hitTest) { case ohtNone: cursor = LoadCursor(0, IDC_ARROW); break; case ohtInside: cursor = LoadCursor(0, IDC_SIZEALL); break; case ohtLeftBorder: case ohtRightBorder: cursor = LoadCursor(0, IDC_SIZEWE); break; case ohtTopBorder: case ohtBottomBorder: cursor = LoadCursor(0, IDC_SIZENS); break; case ohtTopLeftCorner: case ohtBottomRightCorner: cursor = LoadCursor(0, IDC_SIZENWSE); break; case ohtTopRightCorner: case ohtBottomLeftCorner: cursor = LoadCursor(0, IDC_SIZENESW); break; default: cursor = LoadCursor(0, IDC_ARROW); break; } SetCursor(cursor); } void OverlayControl::ActivateElement(HWND hwnd, OverlayElement *element) { if (ActiveOverlay->ActiveElement != element) { ActiveOverlay->ActiveElement = element; RepaintAll(hwnd); // Repaint window, if selection changed (block activated or selection cleared). ActiveOverlayElementChanged(); } } void OverlayControl::RepaintAll(HWND hwnd) { InvalidateRect(hwnd, 0, FALSE); } void OverlayControl::Paint(HWND hwnd, HDC dc) { if (!ActiveOverlay) return; RECT rect; GetClientRect(hwnd, &rect); ActiveOverlay->Paint(dc, &rect); } void OverlayControl::MouseDown(HWND hwnd, WPARAM wParam, LPARAM lParam) { if (!ActiveOverlay) return; // Left or right button clicked -- select the element under cursor. RECT clipRect, clientRect; GetWindowRect(hwnd, &clipRect); GetClientRect(hwnd, &clientRect); // Save original mouse position. GetCursorPosition(hwnd, &clickAnchor); // Element could be activated only if no element active AND user doesn't click // within the active element. if (!ActiveOverlay->ActiveElement || !ActiveOverlay->HitTestElement(ActiveOverlay->ActiveElement, &clientRect, &clickAnchor, &hitTestAnchor)) { // Find overlay element under cursor. OverlayElement *element = ActiveOverlay->FindElementFromPoint(&clientRect, &clickAnchor, &hitTestAnchor); ActivateElement(hwnd, element); } if (!ActiveOverlay->ActiveElement) { ResetCursor(); } if (0 != (wParam & MK_LBUTTON)) { if (ActiveOverlay->ActiveElement) { ActiveOverlay->ActiveElement->GetRect(&clientRect, &elementRectAnchor); // Show that we're about to drag the object. UpdateCursor(hitTestAnchor); // Capture the mouse. SetCapture(hwnd); ClipCursor(&clipRect); } return; } if (0 != (wParam & MK_RBUTTON)) { // Show popup menu. POINT pt; GetCursorPos(&pt); __raise RightMouseButtonClicked(ActiveOverlay->ActiveElement, &pt); return; } } void OverlayControl::MouseUp(HWND hwnd, WPARAM wParam, LPARAM lParam) { if (!ActiveOverlay) return; // Release mouse. ClipCursor(0); ReleaseCapture(); ResetCursor(); } void OverlayControl::MouseMove(HWND hwnd, WPARAM wParam, LPARAM lParam) { if (!ActiveOverlay || !ActiveOverlay->ActiveElement) { ResetCursor(); return; } RECT clientRect; GetClientRect(hwnd, &clientRect); POINT pt; GetCursorPosition(hwnd, &pt); if (0 != (wParam & MK_LBUTTON)) { RECT elementRect; memmove(&elementRect, &elementRectAnchor, sizeof(elementRect)); int dx = pt.x - clickAnchor.x, dy = pt.y - clickAnchor.y; bool updateAnchors = false; // Move/drag element. if (0 != (hitTestAnchor & ohtLeftBorder)) { if (ohtInside != hitTestAnchor && dx > 0 && RectWidth(elementRect) - dx < OverlayElement::MinimalSize) dx = RectWidth(elementRect) - OverlayElement::MinimalSize; elementRect.left += dx; } if (0 != (hitTestAnchor & ohtRightBorder)) { if (ohtInside != hitTestAnchor && dx < 0 && RectWidth(elementRect) + dx < OverlayElement::MinimalSize) dx = OverlayElement::MinimalSize - RectWidth(elementRect); elementRect.right += dx; } if (0 != (hitTestAnchor & ohtTopBorder)) { if (ohtInside != hitTestAnchor && dy > 0 && RectHeight(elementRect) - dy < OverlayElement::MinimalSize) dy = RectHeight(elementRect) - OverlayElement::MinimalSize; elementRect.top += dy; } if (0 != (hitTestAnchor & ohtBottomBorder)) { if (ohtInside != hitTestAnchor && dy < 0 && RectHeight(elementRect) + dy < OverlayElement::MinimalSize) dy = OverlayElement::MinimalSize - RectHeight(elementRect); elementRect.bottom += dy; } // Check for sanity. if (elementRect.left < clientRect.left) { updateAnchors = true; OffsetRect(&elementRect, clientRect.left - elementRect.left, 0); } if (elementRect.right > clientRect.right) { updateAnchors = true; OffsetRect(&elementRect, clientRect.right - elementRect.right, 0); } if (elementRect.top < clientRect.top) { updateAnchors = true; OffsetRect(&elementRect, 0, clientRect.top - elementRect.top); } if (elementRect.bottom > clientRect.bottom) { updateAnchors = true; OffsetRect(&elementRect, 0, clientRect.bottom - elementRect.bottom); } if (updateAnchors) { memmove(&clickAnchor, &pt, sizeof(clickAnchor)); memmove(&elementRectAnchor, &elementRect, sizeof(elementRectAnchor)); } // Update element coordinates. ActiveOverlay->ActiveElement->SetRect(&clientRect, &elementRect); // Drag object under cursor. RepaintAll(hwnd); } else { // No mouse keys pressed -- change cursor accordingly to what's // visible on the screen. OverlayHitTest hitTest = ohtNone; OverlayElement *element = ActiveOverlay->ActiveElement; if (ActiveOverlay->ActiveElement && !ActiveOverlay->HitTestElement(ActiveOverlay->ActiveElement, &clientRect, &pt, &hitTest)) { element = ActiveOverlay->FindElementFromPoint(&clientRect, &pt, &hitTest); } if (0 != element && element == ActiveOverlay->ActiveElement && ohtInside != hitTest) UpdateCursor(hitTest); else ResetCursor(); } }
23.007353
107
0.71109
mkmpvtltd1
fd23938cbc9e14eab4be2683bbcd009f4bf8c631
15,242
cpp
C++
prototype/src/asf_meta/meta_ut1_table.cpp
glshort/MapReady
c9065400a64c87be46418ab32e3a251ca2f55fd5
[ "BSD-3-Clause" ]
3
2017-12-31T05:33:28.000Z
2021-07-28T01:51:22.000Z
prototype/src/asf_meta/meta_ut1_table.cpp
glshort/MapReady
c9065400a64c87be46418ab32e3a251ca2f55fd5
[ "BSD-3-Clause" ]
null
null
null
prototype/src/asf_meta/meta_ut1_table.cpp
glshort/MapReady
c9065400a64c87be46418ab32e3a251ca2f55fd5
[ "BSD-3-Clause" ]
7
2017-04-26T18:18:33.000Z
2020-05-15T08:01:09.000Z
/* Table prepared by script process_epoc.sh eopc01.1900-2006 on Tue Jun 20 10:53:11 AKDT 2006 Format: <UTC year> <TAI-UTC> <UT1-TAI> (DUT source) */ { 1972.00, 10, -10.04749},/*IERS*/ { 1972.10, 10, -10.16419},/*IERS*/ { 1972.20, 10, -10.28450},/*IERS*/ { 1972.30, 10, -10.41373},/*IERS*/ { 1972.40, 10, -10.54006},/*IERS*/ { 1972.50, 11, -10.64084},/*IERS*/ { 1972.60, 11, -10.73373},/*IERS*/ { 1972.70, 11, -10.83149},/*IERS*/ { 1972.80, 11, -10.94923},/*IERS*/ { 1972.90, 11, -11.06709},/*IERS*/ { 1973.00, 12, -11.18856},/*IERS*/ { 1973.10, 12, -11.30265},/*IERS*/ { 1973.20, 12, -11.42686},/*IERS*/ { 1973.30, 12, -11.55778},/*IERS*/ { 1973.40, 12, -11.67471},/*IERS*/ { 1973.50, 12, -11.77400},/*IERS*/ { 1973.60, 12, -11.86491},/*IERS*/ { 1973.70, 12, -11.96185},/*IERS*/ { 1973.80, 12, -12.07210},/*IERS*/ { 1973.90, 12, -12.19501},/*IERS*/ { 1974.00, 13, -12.29977},/*IERS*/ { 1974.10, 13, -12.39364},/*IERS*/ { 1974.20, 13, -12.50162},/*IERS*/ { 1974.30, 13, -12.61288},/*IERS*/ { 1974.40, 13, -12.72934},/*IERS*/ { 1974.50, 13, -12.81714},/*IERS*/ { 1974.60, 13, -12.88905},/*IERS*/ { 1974.70, 13, -12.97471},/*IERS*/ { 1974.80, 13, -13.08026},/*IERS*/ { 1974.90, 13, -13.19056},/*IERS*/ { 1975.00, 14, -13.29168},/*IERS*/ { 1975.10, 14, -13.39445},/*IERS*/ { 1975.20, 14, -13.49861},/*IERS*/ { 1975.30, 14, -13.61121},/*IERS*/ { 1975.40, 14, -13.71758},/*IERS*/ { 1975.50, 14, -13.80278},/*IERS*/ { 1975.60, 14, -13.86928},/*IERS*/ { 1975.70, 14, -13.95555},/*IERS*/ { 1975.80, 14, -14.05870},/*IERS*/ { 1975.90, 14, -14.17115},/*IERS*/ { 1976.00, 15, -14.27485},/*IERS*/ { 1976.10, 15, -14.37858},/*IERS*/ { 1976.20, 15, -14.48529},/*IERS*/ { 1976.30, 15, -14.60920},/*IERS*/ { 1976.40, 15, -14.72609},/*IERS*/ { 1976.50, 15, -14.81439},/*IERS*/ { 1976.60, 15, -14.90276},/*IERS*/ { 1976.70, 15, -14.99438},/*IERS*/ { 1976.80, 15, -15.11295},/*IERS*/ { 1976.90, 15, -15.22922},/*IERS*/ { 1977.00, 16, -15.33429},/*IERS*/ { 1977.10, 16, -15.43486},/*IERS*/ { 1977.20, 16, -15.53991},/*IERS*/ { 1977.30, 16, -15.65816},/*IERS*/ { 1977.40, 16, -15.76907},/*IERS*/ { 1977.50, 16, -15.85318},/*IERS*/ { 1977.60, 16, -15.92317},/*IERS*/ { 1977.70, 16, -16.00853},/*IERS*/ { 1977.80, 16, -16.11962},/*IERS*/ { 1977.90, 16, -16.23631},/*IERS*/ { 1978.00, 17, -16.35048},/*IERS*/ { 1978.10, 17, -16.46424},/*IERS*/ { 1978.20, 17, -16.59385},/*IERS*/ { 1978.30, 17, -16.71645},/*IERS*/ { 1978.40, 17, -16.83222},/*IERS*/ { 1978.50, 17, -16.92002},/*IERS*/ { 1978.60, 17, -16.98716},/*IERS*/ { 1978.70, 17, -17.07543},/*IERS*/ { 1978.80, 17, -17.18262},/*IERS*/ { 1978.90, 17, -17.29274},/*IERS*/ { 1979.00, 18, -17.40095},/*IERS*/ { 1979.10, 18, -17.51263},/*IERS*/ { 1979.20, 18, -17.61610},/*IERS*/ { 1979.30, 18, -17.73014},/*IERS*/ { 1979.40, 18, -17.84034},/*IERS*/ { 1979.50, 18, -17.92136},/*IERS*/ { 1979.60, 18, -17.99174},/*IERS*/ { 1979.70, 18, -18.07234},/*IERS*/ { 1979.80, 18, -18.16697},/*IERS*/ { 1979.90, 18, -18.26064},/*IERS*/ { 1980.00, 19, -18.35506},/*IERS*/ { 1980.10, 19, -18.44519},/*IERS*/ { 1980.20, 19, -18.53334},/*IERS*/ { 1980.30, 19, -18.63331},/*IERS*/ { 1980.40, 19, -18.72368},/*IERS*/ { 1980.50, 19, -18.79364},/*IERS*/ { 1980.60, 19, -18.85472},/*IERS*/ { 1980.70, 19, -18.92492},/*IERS*/ { 1980.80, 19, -19.01279},/*IERS*/ { 1980.90, 19, -19.10786},/*IERS*/ { 1981.00, 19, -19.19533},/*IERS*/ { 1981.10, 19, -19.27770},/*IERS*/ { 1981.20, 19, -19.37273},/*IERS*/ { 1981.30, 19, -19.46855},/*IERS*/ { 1981.40, 19, -19.55874},/*IERS*/ { 1981.50, 20, -19.63015},/*IERS*/ { 1981.60, 20, -19.68015},/*IERS*/ { 1981.70, 20, -19.73470},/*IERS*/ { 1981.80, 20, -19.81950},/*IERS*/ { 1981.90, 20, -19.90425},/*IERS*/ { 1982.00, 20, -19.98157},/*IERS*/ { 1982.10, 20, -20.05764},/*IERS*/ { 1982.20, 20, -20.14294},/*IERS*/ { 1982.30, 20, -20.23245},/*IERS*/ { 1982.40, 20, -20.32120},/*IERS*/ { 1982.50, 21, -20.39269},/*IERS*/ { 1982.60, 21, -20.44047},/*IERS*/ { 1982.70, 21, -20.51094},/*IERS*/ { 1982.80, 21, -20.59604},/*IERS*/ { 1982.90, 21, -20.67953},/*IERS*/ { 1983.00, 21, -20.77233},/*IERS*/ { 1983.10, 21, -20.87840},/*IERS*/ { 1983.20, 21, -20.98260},/*IERS*/ { 1983.30, 21, -21.08940},/*IERS*/ { 1983.40, 21, -21.18155},/*IERS*/ { 1983.50, 22, -21.25242},/*IERS*/ { 1983.60, 22, -21.30479},/*IERS*/ { 1983.70, 22, -21.37015},/*IERS*/ { 1983.80, 22, -21.44164},/*IERS*/ { 1983.90, 22, -21.52831},/*IERS*/ { 1984.00, 22, -21.60454},/*IERS*/ { 1984.10, 22, -21.66061},/*IERS*/ { 1984.20, 22, -21.72310},/*IERS*/ { 1984.30, 22, -21.79878},/*IERS*/ { 1984.40, 22, -21.86186},/*IERS*/ { 1984.50, 22, -21.90229},/*IERS*/ { 1984.60, 22, -21.93164},/*IERS*/ { 1984.70, 22, -21.97718},/*IERS*/ { 1984.80, 22, -22.03639},/*IERS*/ { 1984.90, 22, -22.10288},/*IERS*/ { 1985.00, 22, -22.15755},/*IERS*/ { 1985.10, 22, -22.21164},/*IERS*/ { 1985.20, 22, -22.27369},/*IERS*/ { 1985.30, 22, -22.34299},/*IERS*/ { 1985.40, 22, -22.40256},/*IERS*/ { 1985.50, 23, -22.45214},/*IERS*/ { 1985.60, 23, -22.47489},/*IERS*/ { 1985.70, 23, -22.50517},/*IERS*/ { 1985.80, 23, -22.56613},/*IERS*/ { 1985.90, 23, -22.63315},/*IERS*/ { 1986.00, 23, -22.68677},/*IERS*/ { 1986.10, 23, -22.74045},/*IERS*/ { 1986.20, 23, -22.79309},/*IERS*/ { 1986.30, 23, -22.84464},/*IERS*/ { 1986.40, 23, -22.90151},/*IERS*/ { 1986.50, 23, -22.93016},/*IERS*/ { 1986.60, 23, -22.95058},/*IERS*/ { 1986.70, 23, -22.98209},/*IERS*/ { 1986.80, 23, -23.03895},/*IERS*/ { 1986.90, 23, -23.08991},/*IERS*/ { 1987.00, 23, -23.13808},/*IERS*/ { 1987.10, 23, -23.18654},/*IERS*/ { 1987.20, 23, -23.24637},/*IERS*/ { 1987.30, 23, -23.30866},/*IERS*/ { 1987.40, 23, -23.36392},/*IERS*/ { 1987.50, 23, -23.39857},/*IERS*/ { 1987.60, 23, -23.41932},/*IERS*/ { 1987.70, 23, -23.45848},/*IERS*/ { 1987.80, 23, -23.51296},/*IERS*/ { 1987.90, 23, -23.57487},/*IERS*/ { 1988.00, 24, -23.63580},/*IERS*/ { 1988.10, 24, -23.68559},/*IERS*/ { 1988.20, 24, -23.75280},/*IERS*/ { 1988.30, 24, -23.82072},/*IERS*/ { 1988.40, 24, -23.87745},/*IERS*/ { 1988.50, 24, -23.91014},/*IERS*/ { 1988.60, 24, -23.93105},/*IERS*/ { 1988.70, 24, -23.95515},/*IERS*/ { 1988.80, 24, -24.00189},/*IERS*/ { 1988.90, 24, -24.06531},/*IERS*/ { 1989.00, 24, -24.11503},/*IERS*/ { 1989.10, 24, -24.16144},/*IERS*/ { 1989.20, 24, -24.21817},/*IERS*/ { 1989.30, 24, -24.27613},/*IERS*/ { 1989.40, 24, -24.33885},/*IERS*/ { 1989.50, 24, -24.38600},/*IERS*/ { 1989.60, 24, -24.42140},/*IERS*/ { 1989.70, 24, -24.46111},/*IERS*/ { 1989.80, 24, -24.52280},/*IERS*/ { 1989.90, 24, -24.60148},/*IERS*/ { 1990.00, 25, -24.67052},/*IERS*/ { 1990.10, 25, -24.73857},/*IERS*/ { 1990.20, 25, -24.82081},/*IERS*/ { 1990.30, 25, -24.90511},/*IERS*/ { 1990.40, 25, -24.97988},/*IERS*/ { 1990.50, 25, -25.04038},/*IERS*/ { 1990.60, 25, -25.08310},/*IERS*/ { 1990.70, 25, -25.14583},/*IERS*/ { 1990.80, 25, -25.22266},/*IERS*/ { 1990.90, 25, -25.30233},/*IERS*/ { 1991.00, 26, -25.38103},/*IERS*/ { 1991.10, 26, -25.46249},/*IERS*/ { 1991.20, 26, -25.54368},/*IERS*/ { 1991.30, 26, -25.63048},/*IERS*/ { 1991.40, 26, -25.71474},/*IERS*/ { 1991.50, 26, -25.77556},/*IERS*/ { 1991.60, 26, -25.82080},/*IERS*/ { 1991.70, 26, -25.88546},/*IERS*/ { 1991.80, 26, -25.95804},/*IERS*/ { 1991.90, 26, -26.03975},/*IERS*/ { 1992.00, 26, -26.12531},/*IERS*/ { 1992.10, 26, -26.21336},/*IERS*/ { 1992.20, 26, -26.30379},/*IERS*/ { 1992.30, 26, -26.41029},/*IERS*/ { 1992.40, 26, -26.49599},/*IERS*/ { 1992.50, 27, -26.55791},/*IERS*/ { 1992.60, 27, -26.61077},/*IERS*/ { 1992.70, 27, -26.67686},/*IERS*/ { 1992.80, 27, -26.75412},/*IERS*/ { 1992.90, 27, -26.84612},/*IERS*/ { 1993.00, 27, -26.93602},/*IERS*/ { 1993.10, 27, -27.02831},/*IERS*/ { 1993.20, 27, -27.12756},/*IERS*/ { 1993.30, 27, -27.22865},/*IERS*/ { 1993.40, 27, -27.32495},/*IERS*/ { 1993.50, 28, -27.40242},/*IERS*/ { 1993.60, 28, -27.46253},/*IERS*/ { 1993.70, 28, -27.53203},/*IERS*/ { 1993.80, 28, -27.62255},/*IERS*/ { 1993.90, 28, -27.71486},/*IERS*/ { 1994.00, 28, -27.79932},/*IERS*/ { 1994.10, 28, -27.88382},/*IERS*/ { 1994.20, 28, -27.97527},/*IERS*/ { 1994.30, 28, -28.06622},/*IERS*/ { 1994.40, 28, -28.15865},/*IERS*/ { 1994.50, 29, -28.21844},/*IERS*/ { 1994.60, 29, -28.26859},/*IERS*/ { 1994.70, 29, -28.33348},/*IERS*/ { 1994.80, 29, -28.42066},/*IERS*/ { 1994.90, 29, -28.50642},/*IERS*/ { 1995.00, 29, -28.60090},/*IERS*/ { 1995.10, 29, -28.69718},/*IERS*/ { 1995.20, 29, -28.79435},/*IERS*/ { 1995.30, 29, -28.89725},/*IERS*/ { 1995.40, 29, -28.99328},/*IERS*/ { 1995.50, 29, -29.06358},/*IERS*/ { 1995.60, 29, -29.11361},/*IERS*/ { 1995.70, 29, -29.18038},/*IERS*/ { 1995.80, 29, -29.26329},/*IERS*/ { 1995.90, 29, -29.35337},/*IERS*/ { 1996.00, 30, -29.44481},/*IERS*/ { 1996.10, 30, -29.51008},/*IERS*/ { 1996.20, 30, -29.59074},/*IERS*/ { 1996.30, 30, -29.67417},/*IERS*/ { 1996.40, 30, -29.75456},/*IERS*/ { 1996.50, 30, -29.81371},/*IERS*/ { 1996.60, 30, -29.85922},/*IERS*/ { 1996.70, 30, -29.90147},/*IERS*/ { 1996.80, 30, -29.97022},/*IERS*/ { 1996.90, 30, -30.04416},/*IERS*/ { 1997.00, 30, -30.10965},/*IERS*/ { 1997.10, 30, -30.17309},/*IERS*/ { 1997.20, 30, -30.24820},/*IERS*/ { 1997.30, 30, -30.33871},/*IERS*/ { 1997.40, 30, -30.41623},/*IERS*/ { 1997.50, 31, -30.47382},/*IERS*/ { 1997.60, 31, -30.51875},/*IERS*/ { 1997.70, 31, -30.57240},/*IERS*/ { 1997.80, 31, -30.64863},/*IERS*/ { 1997.90, 31, -30.72153},/*IERS*/ { 1998.00, 31, -30.78121},/*IERS*/ { 1998.10, 31, -30.84997},/*IERS*/ { 1998.20, 31, -30.92540},/*IERS*/ { 1998.30, 31, -30.99751},/*IERS*/ { 1998.40, 31, -31.06848},/*IERS*/ { 1998.50, 31, -31.10114},/*IERS*/ { 1998.60, 31, -31.11460},/*IERS*/ { 1998.70, 31, -31.14183},/*IERS*/ { 1998.80, 31, -31.18624},/*IERS*/ { 1998.90, 31, -31.24017},/*IERS*/ { 1999.00, 32, -31.28314},/*IERS*/ { 1999.10, 32, -31.32083},/*IERS*/ { 1999.20, 32, -31.36002},/*IERS*/ { 1999.30, 32, -31.41203},/*IERS*/ { 1999.40, 32, -31.45641},/*IERS*/ { 1999.50, 32, -31.48014},/*IERS*/ { 1999.60, 32, -31.49444},/*IERS*/ { 1999.70, 32, -31.51801},/*IERS*/ { 1999.80, 32, -31.54939},/*IERS*/ { 1999.90, 32, -31.60251},/*IERS*/ { 2000.00, 32, -31.64452},/*IERS*/ { 2000.10, 32, -31.67494},/*IERS*/ { 2000.20, 32, -31.71001},/*IERS*/ { 2000.30, 32, -31.74474},/*IERS*/ { 2000.40, 32, -31.78012},/*IERS*/ { 2000.50, 32, -31.79592},/*IERS*/ { 2000.60, 32, -31.80120},/*IERS*/ { 2000.70, 32, -31.81286},/*IERS*/ { 2000.80, 32, -31.84000},/*IERS*/ { 2000.90, 32, -31.87947},/*IERS*/ { 2001.00, 32, -31.90630},/*IERS*/ { 2001.10, 32, -31.92371},/*IERS*/ { 2001.20, 32, -31.96111},/*IERS*/ { 2001.30, 32, -31.99033},/*IERS*/ { 2001.40, 32, -32.02290},/*IERS*/ { 2001.50, 32, -32.02782},/*IERS*/ { 2001.60, 32, -32.02061},/*IERS*/ { 2001.70, 32, -32.03042},/*IERS*/ { 2001.80, 32, -32.05585},/*IERS*/ { 2001.90, 32, -32.08686},/*IERS*/ { 2002.00, 32, -32.11544},/*IERS*/ { 2002.10, 32, -32.14173},/*IERS*/ { 2002.20, 32, -32.17393},/*IERS*/ { 2002.30, 32, -32.20071},/*IERS*/ { 2002.40, 32, -32.23035},/*IERS*/ { 2002.50, 32, -32.22962},/*IERS*/ { 2002.60, 32, -32.22404},/*IERS*/ { 2002.70, 32, -32.23033},/*IERS*/ { 2002.80, 32, -32.24297},/*IERS*/ { 2002.90, 32, -32.26122},/*IERS*/ { 2003.00, 32, -32.28924},/*IERS*/ { 2003.10, 32, -32.30788},/*IERS*/ { 2003.20, 32, -32.32854},/*IERS*/ { 2003.30, 32, -32.35880},/*IERS*/ { 2003.40, 32, -32.37457},/*IERS*/ { 2003.50, 32, -32.36613},/*IERS*/ { 2003.60, 32, -32.35380},/*IERS*/ { 2003.70, 32, -32.35299},/*IERS*/ { 2003.80, 32, -32.36284},/*IERS*/ { 2003.90, 32, -32.38076},/*IERS*/ { 2004.00, 32, -32.38958},/*IERS*/ { 2004.10, 32, -32.40412},/*IERS*/ { 2004.20, 32, -32.42257},/*IERS*/ { 2004.30, 32, -32.45126},/*IERS*/ { 2004.40, 32, -32.46832},/*IERS*/ { 2004.50, 32, -32.46861},/*IERS*/ { 2004.60, 32, -32.45463},/*IERS*/ { 2004.70, 32, -32.45006},/*IERS*/ { 2004.80, 32, -32.46423},/*IERS*/ { 2004.90, 32, -32.48719},/*IERS*/ { 2005.00, 32, -32.50336},/*IERS*/ { 2005.10, 32, -32.52311},/*IERS*/ { 2005.20, 32, -32.56365},/*IERS*/ { 2005.30, 32, -32.58598},/*IERS*/ { 2005.40, 32, -32.61477},/*IERS*/ { 2005.50, 32, -32.61517},/*IERS*/ { 2005.60, 32, -32.60093},/*IERS*/ { 2005.70, 32, -32.60041},/*IERS*/ { 2005.80, 32, -32.61887},/*IERS*/ { 2005.90, 32, -32.64200},/*IERS*/ { 2006.00, 33, -32.66113},/*IERS*/ { 2006.10, 33, -32.68219},/*IERS*/ { 2006.20, 33, -32.71340},/*IERS*/ { 2006.30, 33, -32.74972},/*IERS*/ { 2006.40, 33, -32.81039},/*pred*/ { 2006.50, 33, -32.81648},/*pred*/ { 2006.60, 33, -32.80854},/*pred*/ { 2006.70, 33, -32.80703},/*pred*/ { 2006.80, 33, -32.82483},/*pred*/ { 2006.90, 33, -32.85479},/*pred*/ { 2007.00, 33, -32.88236},/*pred*/ { 2007.10, 33, -32.90476},/*pred*/ { 2007.20, 33, -32.93106},/*pred*/ { 2007.30, 33, -32.96344},/*pred*/ { 2007.40, 33, -32.98924},/*pred*/ { 2007.50, 33, -32.99547},/*pred*/ { 2007.60, 33, -32.98757},/*pred*/ { 2007.70, 33, -32.98595},/*pred*/ { 2007.80, 33, -33.00362},/*pred*/ { 2007.90, 33, -33.03355},/*pred*/ { 2008.00, 33, -33.06117},/*pred*/ { 2008.10, 33, -33.08358},/*pred*/ { 2008.20, 33, -33.10983},/*pred*/ { 2008.30, 33, -33.14220},/*pred*/ { 2008.40, 33, -33.16810},/*pred*/ { 2008.50, 33, -33.17446},/*pred*/ { 2008.60, 33, -33.16659},/*pred*/ { 2008.70, 33, -33.16486},/*pred*/ { 2008.80, 33, -33.18242},/*pred*/ { 2008.90, 33, -33.21232},/*pred*/ { 2009.00, 33, -33.23998},/*pred*/ { 2009.10, 33, -33.26302},/*pred*/ { 2009.20, 33, -33.28943},/*pred*/ { 2009.30, 33, -33.32183},/*pred*/ { 2009.40, 33, -33.34742},/*pred*/ { 2009.50, 33, -33.35336},/*pred*/ { 2009.60, 33, -33.34539},/*pred*/ { 2009.70, 33, -33.34399},/*pred*/ { 2009.80, 33, -33.36194},/*pred*/ { 2009.90, 33, -33.39192},/*pred*/ { 2010.00, 33, -33.41945},/*pred*/ { 2010.10, 33, -33.44184},/*pred*/ { 2010.20, 33, -33.46820},/*pred*/ { 2010.30, 33, -33.50059},/*pred*/ { 2010.40, 33, -33.52627},/*pred*/ { 2010.50, 33, -33.53235},/*pred*/ { 2010.60, 33, -33.52441},/*pred*/ { 2010.70, 33, -33.52291},/*pred*/ { 2010.80, 33, -33.54073},/*pred*/ { 2010.90, 33, -33.57069},/*pred*/ { 2011.00, 33, -33.59826},/*pred*/ { 2011.10, 33, -33.62066},/*pred*/ { 2011.20, 33, -33.64696},/*pred*/ { 2011.30, 33, -33.67935},/*pred*/ { 2011.40, 33, -33.70513},/*pred*/ { 2011.50, 33, -33.71134},/*pred*/ { 2011.60, 33, -33.70343},/*pred*/ { 2011.70, 33, -33.70183},/*pred*/ { 2011.80, 33, -33.71952},/*pred*/ { 2011.90, 33, -33.74945},/*pred*/ { 2012.00, 33, -33.77707},/*pred*/ { 2012.10, 33, -33.79948},/*pred*/ { 2012.20, 33, -33.82573},/*pred*/ { 2012.30, 33, -33.85810},/*pred*/ { 2012.40, 33, -33.88399},/*pred*/ { 2012.50, 33, -33.89034},/*pred*/ { 2012.60, 33, -33.88246},/*pred*/ { 2012.70, 33, -33.88075},/*pred*/ { 2012.80, 33, -33.89832},/*pred*/ { 2012.90, 33, -33.92822},/*pred*/ { 2013.00, 33, -33.95587},/*pred*/ { 2013.10, 33, -33.97892},/*pred*/ { 2013.20, 33, -34.00533},/*pred*/ { 2013.30, 33, -34.03773},/*pred*/ { 2013.40, 33, -34.06331},/*pred*/ { 2013.50, 33, -34.06923},/*pred*/ { 2013.60, 33, -34.06125},/*pred*/ { 2013.70, 33, -34.05987},/*pred*/ { 2013.80, 33, -34.07783},/*pred*/ { 2013.90, 33, -34.10782},/*pred*/ { 2014.00, 33, -34.13534},/*pred*/ { 2014.10, 33, -34.15774},/*pred*/ { 2014.20, 33, -34.18410},/*pred*/ { 2014.30, 33, -34.21649},/*pred*/ { 2014.40, 33, -34.24216},/*pred*/ { 2014.50, 33, -34.24822},/*pred*/ { 2014.60, 33, -34.24028},/*pred*/ { 2014.70, 33, -34.23879},/*pred*/ { 2014.80, 33, -34.25663},/*pred*/ { 2014.90, 33, -34.28659},/*pred*/ { 2015.00, 33, -34.31415},/*pred*/
34.719818
45
0.544286
glshort
fd2e91aee0cd8b477dfab122b7ad308982499973
3,178
cpp
C++
gueepo2D/engine/core/renderer/Renderer.cpp
guilhermepo2/gueepo2D
deb03ff39c871710c07d36c366b53b34dbfebf08
[ "MIT" ]
1
2022-02-03T19:24:47.000Z
2022-02-03T19:24:47.000Z
gueepo2D/engine/core/renderer/Renderer.cpp
guilhermepo2/gueepo2D
deb03ff39c871710c07d36c366b53b34dbfebf08
[ "MIT" ]
4
2021-10-30T19:03:07.000Z
2022-02-10T01:06:02.000Z
gueepo2D/engine/core/renderer/Renderer.cpp
guilhermepo2/gueepo2D
deb03ff39c871710c07d36c366b53b34dbfebf08
[ "MIT" ]
1
2021-10-01T03:08:21.000Z
2021-10-01T03:08:21.000Z
#include "gueepo2Dpch.h" #include "Renderer.h" #include "core/Containers/string.h" #include "core/filesystem/Filesystem.h" #include "core/renderer/OrtographicCamera.h" #include "core/Renderer/RendererAPI.h" #include "core/Renderer/Shader.h" #include "core/Renderer/SpriteBatcher.h" // Specific Renderer APIs #include "platform/OpenGL/OpenGLRendererAPI.h" namespace gueepo { static RendererAPI* s_RendererAPI = nullptr; static ShaderLibrary shaderLibrary; SpriteBatcher* Renderer::s_spriteBatcher = nullptr; SpriteBatcher* Renderer::s_uiBatcher; static RendererAPI* InitRendererAPI() { switch (RendererAPI::GetAPI()) { case RendererAPI::API::None: LOG_ERROR("RENDERER API 'NONE' NOT IMPLEMENTED!"); break; case RendererAPI::API::OpenGL: return new OpenGLRendererAPI(); break; case RendererAPI::API::DirectX: case RendererAPI::API::Vulkan: case RendererAPI::API::Metal: LOG_ERROR("RENDERER API NOT IMPLEMENTED!"); break; } return nullptr; } // ======================================================================== // ======================================================================== void Renderer::Initialize() { s_RendererAPI = InitRendererAPI(); s_spriteBatcher = new SpriteBatcher(); s_uiBatcher = new SpriteBatcher(); if (s_RendererAPI == nullptr) { LOG_ERROR("Error initializing Renderer API"); return; } // #todo: well, ideally we should have a default assets folder or some way that we know this is not going to break, lmao. // I think it makes sense that the renderer itself handles the shaders, not the batches... LOG_INFO("Verifying shaders folder..."); bool bShaderPathExists = gueepo::filesystem::DirectoryExists("./assets/shaders"); if (bShaderPathExists) { shaderLibrary.Load("sprite shader", "./assets/shaders/sprite.vertex", "./assets/shaders/sprite.fragment"); shaderLibrary.Load("font shader", "./assets/shaders/font.vertex", "./assets/shaders/font.fragment"); } else { LOG_ERROR("couldn't find path assets/shaders"); LOG_ERROR("there might be issues with the renderer!"); return; } s_spriteBatcher->Initialize(s_RendererAPI, shaderLibrary.Get("sprite shader")); s_uiBatcher->Initialize(s_RendererAPI, shaderLibrary.Get("font shader")); } void Renderer::Shutdown() { s_spriteBatcher->Shutdown(); s_uiBatcher->Shutdown(); delete s_spriteBatcher; delete s_uiBatcher; } void Renderer::Begin(const OrtographicCamera& camera) { s_RendererAPI->SetClearColor( camera.GetBackGroundColor().rgba[0], camera.GetBackGroundColor().rgba[1], camera.GetBackGroundColor().rgba[2], camera.GetBackGroundColor().rgba[3] ); s_RendererAPI->Clear(); s_spriteBatcher->Begin(camera); s_uiBatcher->Begin(camera); } void Renderer::End() { s_spriteBatcher->End(); s_uiBatcher->End(); } /* void Renderer::Submit(VertexArray* vertexArray, Shader* shader) { shader->Bind(); shader->SetMat4("u_ViewProjection", s_RenderData.ViewProjection); vertexArray->Bind(); s_RendererAPI->DrawIndexed(vertexArray); } */ void Renderer::SetUnpackAlignment(int value) { s_RendererAPI->SetUnpackAlignment(value); } }
27.877193
123
0.69163
guilhermepo2
fd3064ad9e0677815b06b9eb961cf0c0376d285c
295
hh
C++
events/NewPlayerEvent.hh
deb0ch/R-Type
8bb37cd5ec318efb97119afb87d4996f6bb7644e
[ "WTFPL" ]
5
2016-03-15T20:14:10.000Z
2020-10-30T23:56:24.000Z
events/NewPlayerEvent.hh
deb0ch/R-Type
8bb37cd5ec318efb97119afb87d4996f6bb7644e
[ "WTFPL" ]
3
2018-12-19T19:12:44.000Z
2020-04-02T13:07:00.000Z
events/NewPlayerEvent.hh
deb0ch/R-Type
8bb37cd5ec318efb97119afb87d4996f6bb7644e
[ "WTFPL" ]
2
2016-04-11T19:29:28.000Z
2021-11-26T20:53:22.000Z
#ifndef NEWPLAYEREVENT_H_ # define NEWPLAYEREVENT_H_ # include "AEvent.hh" class NewPlayerEvent : public AEvent { public: NewPlayerEvent(unsigned int hash); virtual ~NewPlayerEvent(); unsigned int getRemoteId() const; protected: unsigned int _hash; }; #endif /* !NEWPLAYEREVENT_H_ */
17.352941
36
0.752542
deb0ch
fd327d1641017eb8fd91a66d05ede5f755759d7a
10,510
cpp
C++
frenet_planner_ros/src/frenetROS_obst.cpp
anime-sh/frenet-gym
2f8f4aa5a3de8c0e63aee81b0891ea0cf16bc305
[ "MIT" ]
1
2021-12-10T11:40:12.000Z
2021-12-10T11:40:12.000Z
frenet_planner_ros/src/frenetROS_obst.cpp
anime-sh/frenet-gym
2f8f4aa5a3de8c0e63aee81b0891ea0cf16bc305
[ "MIT" ]
1
2021-05-29T09:12:19.000Z
2021-05-29T09:12:19.000Z
frenet_planner_ros/src/frenetROS_obst.cpp
anime-sh/frenet-gym
2f8f4aa5a3de8c0e63aee81b0891ea0cf16bc305
[ "MIT" ]
1
2020-09-17T14:30:44.000Z
2020-09-17T14:30:44.000Z
#include "../include/frenet_optimal_trajectory.hpp" #include <ros/ros.h> #include <geometry_msgs/Twist.h> #include <nav_msgs/Path.h> #include <tf/transform_datatypes.h> #include <utility> #include <ros/console.h> #include <std_msgs/String.h> #include <std_msgs/Float64.h> #include <thread> #include <chrono> namespace plt = matplotlibcpp; std_msgs::String path_id; vecD FrenetPath::get_x() { return x; } vecD FrenetPath::get_y() { return y; } vecD FrenetPath::get_d() { return d; } vecD FrenetPath::get_c() { return c; } vecD FrenetPath::get_s_d() { return s_d; } vecD FrenetPath::get_s() { return s; } vecD FrenetPath::get_d_d() { return d_d; } vecD FrenetPath::get_d_dd() { return d_dd; } vecD FrenetPath::get_yaw() { return yaw; } double FrenetPath::get_cf() { return cf; } void path_id_callback(const std_msgs::String msg) { path_id = msg; got_path = true; } void action_callback(const geometry_msgs::Twist::ConstPtr& msg) { twist = *msg; no_action = false; } void odom_callback(const nav_msgs::Odometry::ConstPtr& msg) { odom = *msg; //ROS_INFO("Odom Received"); } void global_callback(const nav_msgs::Path::ConstPtr& msg) { path = *msg; } double calc_dis(double x1, double y1, double x2, double y2) { return sqrt(pow((x1 - x2), 2) + pow((y1 - y2), 2)); } void find_nearest_in_global_path(vecD global_x, vecD global_y, double &min_x, double &min_y, double &min_dis, int &min_id, int flag, FrenetPath path) { double bot_x, bot_y; if(flag==0) { bot_x = odom.pose.pose.position.x; bot_y = odom.pose.pose.position.y; } else { bot_x = path.get_x()[1]; bot_y = path.get_y()[1]; } min_dis = FLT_MAX; for(int i = 0; i < global_x.size(); i++) { double dis = calc_dis(global_x[i], global_y[i], bot_x, bot_y); if(dis < min_dis) { min_dis = dis; min_x = global_x[i]; min_y = global_y[i]; min_id = i; } } } double calc_s(double ptx, double pty, vecD global_x, vecD global_y) { double s = 0; if(global_x[0] == ptx && global_y[0] == pty) return s; for(int i = 1; i < global_x.size(); i++) { double dis = calc_dis(global_x[i], global_y[i], global_x[i - 1], global_y[i - 1]); s = s + dis; if(global_x[i] == ptx && global_y[i] == pty) break; } return s; } double get_bot_yaw() { geometry_msgs::Pose p = odom.pose.pose; tf::Quaternion q(p.orientation.x, p.orientation.y, p.orientation.z, p.orientation.w); tf::Matrix3x3 m(q); double roll, pitch, yaw; m.getRPY(roll, pitch, yaw); return yaw; } vecD global_path_yaw(Spline2D csp, vecD gx, vecD gy) { vecD yaw; vecD t = csp.calc_s(gx, gy); for(int i = 0; i < t.size(); i++) { yaw.push_back(csp.calc_yaw(t[i])); } return yaw; } void initial_conditions_path(Spline2D csp, vecD global_x, vecD global_y, vecD ryaw, double &s0, double &c_speed, double &c_d, double &c_d_d, double &c_d_dd, double &bot_yaw, FrenetPath path) { // Approach 1 vecD k= path.get_c(); vecD d = path.get_d(); vecD s_d = path.get_s_d(); vecD d_d = path.get_d_d(); vecD d_dd = path.get_d_dd(); vecD s= path.get_s(); s0= s[1]; c_speed = s_d[1]; c_d = d[1]; c_d_d= d_d[1]; c_d_dd= 0; bot_yaw = get_bot_yaw(); } void initial_conditions_new(Spline2D csp, vecD global_x, vecD global_y, vecD ryaw, double &s0, double &c_speed, double &c_d, double &c_d_d, double &c_d_dd, double bot_yaw) { FrenetPath path; double vx = odom.twist.twist.linear.x; double vy = odom.twist.twist.linear.y; double v = sqrt(vx*vx + vy*vy); double min_x, min_y; int min_id; // getting d find_nearest_in_global_path(global_x, global_y, min_x, min_y, c_d, min_id, 0, path); // deciding the sign for d pair<double, double> vec1, vec2; vec1.first = odom.pose.pose.position.x - global_x[min_id]; vec1.second = odom.pose.pose.position.y - global_y[min_id]; vec2.first = global_x[min_id] - global_x[min_id + 1]; vec2.second = global_y[min_id] - global_y[min_id + 1]; double curl2D = vec1.first*vec2.second - vec2.first*vec1.second; if(curl2D < 0) c_d *= -1; s0 = calc_s(min_x, min_y, global_x, global_y); bot_yaw = get_bot_yaw(); vecD theta = global_path_yaw(csp, global_x, global_y); double g_path_yaw = theta[min_id]; double delta_theta = bot_yaw - g_path_yaw; c_d_d = v*sin(delta_theta);//Equation 5 double k_r = csp.calc_curvature(s0); c_speed = v*cos(delta_theta) / (1 - k_r*c_d); //s_dot (Equation 7) c_d_dd = 0; // For the time being. Need to be updated } void publishPath(nav_msgs::Path &path_msg, FrenetPath path, vecD rk, vecD ryaw, double &c_speed, double &c_d, double &c_d_d) { vecD x_vec = path.get_x(); vecD y_vec = path.get_y(); for(int i = 0; i < path.get_x().size(); i++) { geometry_msgs::PoseStamped loc; loc.pose.position.x = x_vec[i]; loc.pose.position.y = y_vec[i]; double delta_theta = atan(c_d_d / ((1 - rk[i]*c_d)*c_speed)); double yaw = delta_theta + ryaw[i]; tf::Quaternion q = tf::createQuaternionFromRPY(0, 0, yaw); // roll , pitch = 0 q.normalize(); quaternionTFToMsg(q, loc.pose.orientation); path_msg.poses.push_back(loc); } } int main(int argc, char **argv) { ros::init(argc, argv, "frenet_planner"); ros::NodeHandle n; ros::Publisher frenet_path = n.advertise<nav_msgs::Path>("/frenet_path", 1); ros::Publisher target_vel = n.advertise<geometry_msgs::Twist>("/cmd_vel", 10); //Publish velocity ros::Publisher cost_fp = n.advertise<std_msgs::Float64>("/cost_fp", 10); //cost publish ros::Subscriber global_sub = n.subscribe("/global_path", 100, global_callback); ros::Subscriber odom_sub = n.subscribe("/carla/ego_vehicle/odometry", 10, odom_callback); //different subscriber ros::Subscriber action_sub = n.subscribe("/action", 1000, action_callback); ros::Subscriber path_id_sub = n.subscribe("/path_id", 1000, path_id_callback); ROS_INFO("Getting params"); // get params n.getParam("/frenet_planner/path/max_speed", MAX_SPEED); n.getParam("/frenet_planner/path/max_accel", MAX_ACCEL); n.getParam("/frenet_planner/path/max_curvature", MAX_CURVATURE); n.getParam("/frenet_planner/path/max_road_width", MAX_ROAD_WIDTH); n.getParam("/frenet_planner/path/d_road_w", D_ROAD_W); n.getParam("/frenet_planner/path/dt", DT); n.getParam("/frenet_planner/path/maxt", MAXT); n.getParam("/frenet_planner/path/mint", MINT); n.getParam("/frenet_planner/path/target_speed", TARGET_SPEED); n.getParam("/frenet_planner/path/d_t_s", D_T_S); n.getParam("/frenet_planner/path/n_s_sample", N_S_SAMPLE); n.getParam("/frenet_planner/path/robot_radius", ROBOT_RADIUS); n.getParam("/frenet_planner/path/max_lat_vel", MAX_LAT_VEL); n.getParam("/frenet_planner/path/min_lat_vel", MIN_LAT_VEL); n.getParam("/frenet_planner/path/d_d_ns", D_D_NS); n.getParam("/frenet_planner/path/max_shift_d", MAX_SHIFT_D); n.getParam("/frenet_planner/cost/kj", KJ); n.getParam("/frenet_planner/cost/kt", KT); n.getParam("/frenet_planner/cost/kd", KD); n.getParam("/frenet_planner/cost/kd_v", KD_V); n.getParam("/frenet_planner/cost/klon", KLON); n.getParam("/frenet_planner/cost/klat", KLAT); vecD rx, ry, ryaw, rk; double ds = 0.1; //ds represents the step size for cubic_spline double bot_yaw; while(!got_path) { cout<<"No message received in path_id. Waiting for connection."<<endl<<flush; this_thread::sleep_for(chrono::seconds(1)); ros::spinOnce(); } //Global path is made using the waypoints cout<<"Path_id : "<<path_id.data<<endl; string id_path = path_id.data; n.getParam("/frenet_planner/waypoints/W_X_" + id_path, W_X); n.getParam("/frenet_planner/waypoints/W_Y_" + id_path, W_Y); cout<<"Got new waypoints."<<endl; Spline2D csp = calc_spline_course(W_X, W_Y, rx, ry, ryaw, rk, ds); cout<<"Updated global path."<<endl; got_path = false; FrenetPath path; FrenetPath lp; double s0, c_d, c_d_d, c_d_dd, c_speed ; int ctr=0; while(ros::ok()) { if(got_path) { while(path_id.data == "") { cout<<"No message received in path_id. Waiting for connection."<<endl<<flush; this_thread::sleep_for(chrono::seconds(1)); ros::spinOnce(); } cout<<"Path_id : "<<path_id.data<<endl; string id_path = path_id.data; n.getParam("/frenet_planner/waypoints/W_X_" + id_path, W_X); n.getParam("/frenet_planner/waypoints/W_Y_" + id_path, W_Y); cout<<"Got new waypoints."<<endl; csp = calc_spline_course(W_X, W_Y, rx, ry, ryaw, rk, ds); cout<<"Updated global path."<<endl; got_path = false; } //Specifing initial conditions for the frenet planner using odometry if(ctr%10 == 0 or path.get_c().size() == 0) { cout << "initial NEW STARTS"<< endl; initial_conditions_new(csp, rx, ry, ryaw, s0, c_speed, c_d, c_d_d, c_d_dd, bot_yaw); } else { cout << "initial PATH STARTS"<< endl; initial_conditions_path(csp, rx, ry, ryaw, s0, c_speed, c_d, c_d_d, c_d_dd, bot_yaw, path); } while(no_action) { cout<<"Action message not received."<<endl<<flush; this_thread::sleep_for(chrono::seconds(1)); ros::spinOnce(); } cout<<"Before calling frenet_optimal_planning: Action : \n"<<twist.linear.x<<"\n"<<twist.linear.y<<"\n"<<twist.linear.z<<"\n"<<twist.angular.x<<endl; path = frenet_optimal_planning(csp, s0, c_speed, c_d, c_d_d, c_d_dd, lp, bot_yaw); cout<<"After calling frenet_optimal_planning"<<endl; lp = path; nav_msgs::Path path_msg; nav_msgs::Path global_path_msg; // paths are published in map frame path_msg.header.frame_id = "map"; global_path_msg.header.frame_id = "map"; //Global path pushed into the message for(int i = 0; i < rx.size(); i++) { geometry_msgs::PoseStamped loc; loc.pose.position.x = rx[i]; loc.pose.position.y = ry[i]; global_path_msg.poses.push_back(loc); } if(false) { plt::ion(); plt::show(); plt::plot(lp.get_x(), lp.get_y()); plt::pause(0.001); plt::plot(rx,ry); plt::pause(0.001); } //Required tranformations on the Frenet path are made and pushed into message publishPath(path_msg, path, rk, ryaw, c_d, c_speed, c_d_d); //Next velocity along the path double bot_v = sqrt(pow(1 - rk[1]*c_d, 2)*pow(c_speed, 2) + pow(c_d_d, 2)); geometry_msgs::Twist vel; vel.linear.x = bot_v; vel.linear.y = 0; vel.linear.z = 0; std_msgs::Float64 cost; cost.data = path.get_cf(); cost_fp.publish(cost); frenet_path.publish(path_msg); //global_path.publish(global_path_msg); target_vel.publish(vel); printf("VEL. PUBLISHED = %lf \n", vel.linear.x); ctr++; ros::spinOnce(); } }
26.811224
190
0.677545
anime-sh
fd36ce26d4be3904e2ad166a033ca00fa1f33f78
2,812
hpp
C++
waterbox/ares64/ares/nall/emulation/21fx.hpp
Fortranm/BizHawk
8cb0ffb6f8964cc339bbe1784838918fb0aa7e27
[ "MIT" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
waterbox/ares64/ares/nall/emulation/21fx.hpp
Fortranm/BizHawk
8cb0ffb6f8964cc339bbe1784838918fb0aa7e27
[ "MIT" ]
296
2021-10-16T18:00:18.000Z
2022-03-31T12:09:00.000Z
waterbox/ares64/ares/nall/emulation/21fx.hpp
Fortranm/BizHawk
8cb0ffb6f8964cc339bbe1784838918fb0aa7e27
[ "MIT" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
#pragma once #include <nall/nall.hpp> #include <nall/serial.hpp> using namespace nall; struct FX { auto open(Arguments& arguments) -> bool; auto close() -> void; auto readable() -> bool; auto read() -> u8; auto writable() -> bool; auto write(u8 data) -> void; auto read(u32 offset, u32 length) -> vector<u8>; auto write(u32 offset, const void* buffer, u32 length) -> void; auto write(u32 offset, const vector<u8>& buffer) -> void { write(offset, buffer.data(), buffer.size()); } auto execute(u32 offset) -> void; auto read(u32 offset) -> u8; auto write(u32 offset, u8 data) -> void; serial device; }; inline auto FX::open(Arguments& arguments) -> bool { //device name override support string name; arguments.take("--device", name); if(!device.open(name)) { print("[21fx] error: unable to open hardware device\n"); return false; } //flush the device (to clear floating inputs) while(true) { while(readable()) read(); auto iplrom = read(0x2184, 122); auto sha256 = Hash::SHA256(iplrom).digest(); if(sha256 == "41b79712a4a2d16d39894ae1b38cde5c41dad22eadc560df631d39f13df1e4b9") break; } return true; } inline auto FX::close() -> void { device.close(); } inline auto FX::readable() -> bool { return device.readable(); } //1000ns delay avoids burning CPU core at 100%; does not slow down max transfer rate at all inline auto FX::read() -> u8 { while(!readable()) usleep(1000); u8 buffer[1] = {0}; device.read(buffer, 1); return buffer[0]; } inline auto FX::writable() -> bool { return device.writable(); } inline auto FX::write(u8 data) -> void { while(!writable()) usleep(1000); u8 buffer[1] = {data}; device.write(buffer, 1); } // inline auto FX::read(u32 offset, u32 length) -> vector<u8> { write(0x21); write(0x66); write(0x78); write(offset >> 16); write(offset >> 8); write(offset >> 0); write(0x01); write(length >> 8); write(length >> 0); write(0x00); vector<u8> buffer; while(length--) buffer.append(read()); return buffer; } inline auto FX::write(u32 offset, const void* data, u32 length) -> void { write(0x21); write(0x66); write(0x78); write(offset >> 16); write(offset >> 8); write(offset >> 0); write(0x01); write(length >> 8); write(length >> 0); write(0x01); auto buffer = (u8*)data; for(auto n : range(length)) write(buffer[n]); write(0x00); } inline auto FX::execute(u32 offset) -> void { write(0x21); write(0x66); write(0x78); write(offset >> 16); write(offset >> 8); write(offset >> 0); write(0x00); } // inline auto FX::read(u32 offset) -> u8 { auto buffer = read(offset, 1); return buffer[0]; } inline auto FX::write(u32 offset, u8 data) -> void { vector<u8> buffer = {data}; write(offset, buffer); }
21.79845
107
0.63478
Fortranm
fd3a945300df5ca2ac17b3e959d996cfd02d0c10
1,403
cpp
C++
LivestreamEx/SubProcessorDanmuDouyu.cpp
cnSchwarzer/LivestreamExtract
14aabf3c5bb728941c62e3871b9aa1f55d0390a5
[ "MIT" ]
8
2021-04-01T00:36:34.000Z
2021-06-13T15:58:17.000Z
LivestreamEx/SubProcessorDanmuDouyu.cpp
cnSchwarzer/LivestreamExtract
14aabf3c5bb728941c62e3871b9aa1f55d0390a5
[ "MIT" ]
null
null
null
LivestreamEx/SubProcessorDanmuDouyu.cpp
cnSchwarzer/LivestreamExtract
14aabf3c5bb728941c62e3871b9aa1f55d0390a5
[ "MIT" ]
2
2021-04-16T04:00:34.000Z
2021-08-30T03:06:47.000Z
#include "SubProcessorDanmuDouyu.h" #include <filesystem> #include <fstream> #include "../common.h" void SubProcessorDanmuDouyu::initialize(LivestreamDanmuDouyu* dm) { dm->onChatMessage([=](ChatMessage* msg) { danmu(reinterpret_cast<ChatMessageDouyu*>(msg)); }); } void SubProcessorDanmuDouyu::danmu(ChatMessageDouyu* msg) { if (!working) return; json::object_t m = json::object_t(); m["username"] = msg->username; m["content"] = msg->content; m["color"] = static_cast<int>(msg->color); m["level"] = msg->level; m["timestamp"] = msg->time; danmuJson.push_back(m); danmuCount++; //Backup every 50 danmu if (danmuCount % 50 == 0) { std::ofstream danmu(danmuFilePath); danmu << danmuJson.dump(4, ' ', false, nlohmann::detail::error_handler_t::ignore); danmu.close(); } } void SubProcessorDanmuDouyu::onSerialize(json& root) { root["danmu_file"] = std::filesystem::absolute(danmuFilePath).string(); } void SubProcessorDanmuDouyu::start(time_t timestamp) { danmuFilePath = outputFolder + "/output_danmu/" + std::to_string(timestamp) + ".json"; std::filesystem::create_directories(outputFolder + "/output_danmu"); working = true; } void SubProcessorDanmuDouyu::stop() { std::ofstream danmu(danmuFilePath); danmu << danmuJson.dump(4, ' ', false, nlohmann::detail::error_handler_t::ignore); danmu.close(); danmuCount = 0; danmuJson.clear(); working = false; }
23
87
0.703493
cnSchwarzer
fd3c63cfa74d73ef827df6b19f1dae409a9b6502
15,480
cpp
C++
uwsim_resources/uwsim_osgworks/src/osgwTools/TangentSpaceGeneratorDouble.cpp
epsilonorion/usv_lsa_sim_copy
d189f172dc1d265b7688c7dc8375a65ac4a9c048
[ "Apache-2.0" ]
1
2020-11-30T09:55:33.000Z
2020-11-30T09:55:33.000Z
uwsim_resources/uwsim_osgworks/src/osgwTools/TangentSpaceGeneratorDouble.cpp
epsilonorion/usv_lsa_sim_copy
d189f172dc1d265b7688c7dc8375a65ac4a9c048
[ "Apache-2.0" ]
null
null
null
uwsim_resources/uwsim_osgworks/src/osgwTools/TangentSpaceGeneratorDouble.cpp
epsilonorion/usv_lsa_sim_copy
d189f172dc1d265b7688c7dc8375a65ac4a9c048
[ "Apache-2.0" ]
2
2020-11-21T19:50:54.000Z
2020-12-27T09:35:29.000Z
/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * osgWorks is (C) Copyright 2009-2012 by Kenneth Mark Bryden * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ // This code was taken from OSG v2.8.5 and modified to use double precision. #include <osgwTools/TangentSpaceGeneratorDouble.h> #include <osgwTools/Version.h> #include <osg/Notify> #include <osg/io_utils> namespace osgwTools { TangentSpaceGeneratorDouble::TangentSpaceGeneratorDouble() : osg::Referenced(), T_(new osg::Vec4Array), B_(new osg::Vec4Array), N_(new osg::Vec4Array) { } TangentSpaceGeneratorDouble::TangentSpaceGeneratorDouble(const TangentSpaceGeneratorDouble &copy, const osg::CopyOp &copyop) : osg::Referenced(copy), T_(static_cast<osg::Vec4Array *>(copyop(copy.T_.get()))), B_(static_cast<osg::Vec4Array *>(copyop(copy.B_.get()))), N_(static_cast<osg::Vec4Array *>(copyop(copy.N_.get()))) { } void TangentSpaceGeneratorDouble::generate(osg::Geometry *geo, int normal_map_tex_unit) { #if( OSGWORKS_OSG_VERSION < 30108 ) // check to see if vertex attributes indices exists, if so expand them to remove them // This was removed from OSG 3.1.8 upwards if (geo->suitableForOptimization()) { // removing coord indices so we don't have to deal with them in the binormal code. osg::notify(osg::INFO)<<"TangentSpaceGeneratorDouble::generate(Geometry*,int): Removing attribute indices"<<std::endl; geo->copyToAndOptimize(*geo); } #endif const osg::Array *vx = geo->getVertexArray(); const osg::Array *nx = geo->getNormalArray(); const osg::Array *tx = geo->getTexCoordArray(normal_map_tex_unit); if (!vx || !tx) return; unsigned int vertex_count = vx->getNumElements(); if (geo->getVertexIndices() == NULL) { T_->assign(vertex_count, osg::Vec4()); B_->assign(vertex_count, osg::Vec4()); N_->assign(vertex_count, osg::Vec4()); } else { unsigned int index_count = geo->getVertexIndices()->getNumElements(); T_->assign(index_count, osg::Vec4()); B_->assign(index_count, osg::Vec4()); N_->assign(index_count, osg::Vec4()); indices_ = new osg::UIntArray(); unsigned int i; for (i=0;i<index_count;i++) { indices_->push_back(i); } } unsigned int i; // VC6 doesn't like for-scoped variables for (unsigned int pri=0; pri<geo->getNumPrimitiveSets(); ++pri) { osg::PrimitiveSet *pset = geo->getPrimitiveSet(pri); unsigned int N = pset->getNumIndices(); switch (pset->getMode()) { case osg::PrimitiveSet::TRIANGLES: for (i=0; i<N; i+=3) { compute(pset, vx, nx, tx, i, i+1, i+2); } break; case osg::PrimitiveSet::QUADS: for (i=0; i<N; i+=4) { compute(pset, vx, nx, tx, i, i+1, i+2); compute(pset, vx, nx, tx, i+2, i+3, i); } break; case osg::PrimitiveSet::TRIANGLE_STRIP: if (pset->getType() == osg::PrimitiveSet::DrawArrayLengthsPrimitiveType) { osg::DrawArrayLengths *dal = static_cast<osg::DrawArrayLengths *>(pset); unsigned int j = 0; for (osg::DrawArrayLengths::const_iterator pi=dal->begin(); pi!=dal->end(); ++pi) { unsigned int iN = static_cast<unsigned int>(*pi-2); for (i=0; i<iN; ++i, ++j) { if ((i%2) == 0) { compute(pset, vx, nx, tx, j, j+1, j+2); } else { compute(pset, vx, nx, tx, j+1, j, j+2); } } j += 2; } } else { for (i=0; i<N-2; ++i) { if ((i%2) == 0) { compute(pset, vx, nx, tx, i, i+1, i+2); } else { compute(pset, vx, nx, tx, i+1, i, i+2); } } } break; case osg::PrimitiveSet::TRIANGLE_FAN: if (pset->getType() == osg::PrimitiveSet::DrawArrayLengthsPrimitiveType) { osg::DrawArrayLengths *dal = static_cast<osg::DrawArrayLengths *>(pset); unsigned int j = 0; for (osg::DrawArrayLengths::const_iterator pi=dal->begin(); pi!=dal->end(); ++pi) { unsigned int iN = static_cast<unsigned int>(*pi-2); for (i=0; i<iN; ++i) { compute(pset, vx, nx, tx, 0, j+1, j+2); } j += 2; } } else { for (i=0; i<N-2; ++i) { compute(pset, vx, nx, tx, 0, i+1, i+2); } } break; case osg::PrimitiveSet::POINTS: case osg::PrimitiveSet::LINES: case osg::PrimitiveSet::LINE_STRIP: case osg::PrimitiveSet::LINE_LOOP: break; default: osg::notify(osg::WARN) << "Warning: TangentSpaceGeneratorDouble: unknown primitive mode " << pset->getMode() << "\n"; } } // normalize basis vectors and force the normal vector to match // the triangle normal's direction unsigned int attrib_count = vx->getNumElements(); if (geo->getVertexIndices() != NULL) { attrib_count = geo->getVertexIndices()->getNumElements(); } for (i=0; i<attrib_count; ++i) { osg::Vec4 &vT = (*T_)[i]; osg::Vec4 &vB = (*B_)[i]; osg::Vec4 &vN = (*N_)[i]; osg::Vec3d txN = osg::Vec3d(vT.x(), vT.y(), vT.z()) ^ osg::Vec3d(vB.x(), vB.y(), vB.z()); if (txN * osg::Vec3d(vN.x(), vN.y(), vN.z()) >= 0) { vN = osg::Vec4(txN, 0); } else { vN = osg::Vec4(-txN, 0); } vT.normalize(); vB.normalize(); vN.normalize(); } /* TO-DO: if indexed, compress the attributes to have only one * version of each (different indices for each one?) */ } void TangentSpaceGeneratorDouble::compute(osg::PrimitiveSet *pset, const osg::Array* vx, const osg::Array* nx, const osg::Array* tx, int iA, int iB, int iC) { iA = pset->index(iA); iB = pset->index(iB); iC = pset->index(iC); osg::Vec3d P1; osg::Vec3d P2; osg::Vec3d P3; int i; // VC6 doesn't like for-scoped variables switch (vx->getType()) { case osg::Array::Vec2ArrayType: for (i=0; i<2; ++i) { P1.ptr()[i] = static_cast<const osg::Vec2Array&>(*vx)[iA].ptr()[i]; P2.ptr()[i] = static_cast<const osg::Vec2Array&>(*vx)[iB].ptr()[i]; P3.ptr()[i] = static_cast<const osg::Vec2Array&>(*vx)[iC].ptr()[i]; } break; case osg::Array::Vec3ArrayType: P1 = static_cast<const osg::Vec3Array&>(*vx)[iA]; P2 = static_cast<const osg::Vec3Array&>(*vx)[iB]; P3 = static_cast<const osg::Vec3Array&>(*vx)[iC]; break; case osg::Array::Vec4ArrayType: for (i=0; i<3; ++i) { P1.ptr()[i] = static_cast<const osg::Vec4Array&>(*vx)[iA].ptr()[i]; P2.ptr()[i] = static_cast<const osg::Vec4Array&>(*vx)[iB].ptr()[i]; P3.ptr()[i] = static_cast<const osg::Vec4Array&>(*vx)[iC].ptr()[i]; } break; default: osg::notify(osg::WARN) << "Warning: TangentSpaceGeneratorDouble: vertex array must be Vec2Array, Vec3Array or Vec4Array" << std::endl; } osg::Vec3d N1; osg::Vec3d N2; osg::Vec3d N3; if(nx) { switch (nx->getType()) { case osg::Array::Vec2ArrayType: for (i=0; i<2; ++i) { N1.ptr()[i] = static_cast<const osg::Vec2Array&>(*nx)[iA].ptr()[i]; N2.ptr()[i] = static_cast<const osg::Vec2Array&>(*nx)[iB].ptr()[i]; N3.ptr()[i] = static_cast<const osg::Vec2Array&>(*nx)[iC].ptr()[i]; } break; case osg::Array::Vec3ArrayType: N1 = static_cast<const osg::Vec3Array&>(*nx)[iA]; N2 = static_cast<const osg::Vec3Array&>(*nx)[iB]; N3 = static_cast<const osg::Vec3Array&>(*nx)[iC]; break; case osg::Array::Vec4ArrayType: for (i=0; i<3; ++i) { N1.ptr()[i] = static_cast<const osg::Vec4Array&>(*nx)[iA].ptr()[i]; N2.ptr()[i] = static_cast<const osg::Vec4Array&>(*nx)[iB].ptr()[i]; N3.ptr()[i] = static_cast<const osg::Vec4Array&>(*nx)[iC].ptr()[i]; } break; default: osg::notify(osg::WARN) << "Warning: TangentSpaceGeneratorDouble: normal array must be Vec2Array, Vec3Array or Vec4Array" << std::endl; } } osg::Vec2d uv1; osg::Vec2d uv2; osg::Vec2d uv3; switch (tx->getType()) { case osg::Array::Vec2ArrayType: uv1 = static_cast<const osg::Vec2Array&>(*tx)[iA]; uv2 = static_cast<const osg::Vec2Array&>(*tx)[iB]; uv3 = static_cast<const osg::Vec2Array&>(*tx)[iC]; break; case osg::Array::Vec3ArrayType: for (i=0; i<2; ++i) { uv1.ptr()[i] = static_cast<const osg::Vec3Array&>(*tx)[iA].ptr()[i]; uv2.ptr()[i] = static_cast<const osg::Vec3Array&>(*tx)[iB].ptr()[i]; uv3.ptr()[i] = static_cast<const osg::Vec3Array&>(*tx)[iC].ptr()[i]; } break; case osg::Array::Vec4ArrayType: for (i=0; i<2; ++i) { uv1.ptr()[i] = static_cast<const osg::Vec4Array&>(*tx)[iA].ptr()[i]; uv2.ptr()[i] = static_cast<const osg::Vec4Array&>(*tx)[iB].ptr()[i]; uv3.ptr()[i] = static_cast<const osg::Vec4Array&>(*tx)[iC].ptr()[i]; } break; default: osg::notify(osg::WARN) << "Warning: TangentSpaceGeneratorDouble: texture coord array must be Vec2Array, Vec3Array or Vec4Array" << std::endl; } if(nx){ osg::Vec3d V, T1, T2, T3, B1, B2, B3; V = osg::Vec3d(P2.x() - P1.x(), uv2.x() - uv1.x(), uv2.y() - uv1.y()) ^ osg::Vec3d(P3.x() - P1.x(), uv3.x() - uv1.x(), uv3.y() - uv1.y()); if (V.x() != 0) { V.normalize(); T1.x() += -V.y() / V.x(); B1.x() += -V.z() / V.x(); T2.x() += -V.y() / V.x(); B2.x() += -V.z() / V.x(); T3.x() += -V.y() / V.x(); B3.x() += -V.z() / V.x(); } V = osg::Vec3d(P2.y() - P1.y(), uv2.x() - uv1.x(), uv2.y() - uv1.y()) ^ osg::Vec3d(P3.y() - P1.y(), uv3.x() - uv1.x(), uv3.y() - uv1.y()); if (V.x() != 0) { V.normalize(); T1.y() += -V.y() / V.x(); B1.y() += -V.z() / V.x(); T2.y() += -V.y() / V.x(); B2.y() += -V.z() / V.x(); T3.y() += -V.y() / V.x(); B3.y() += -V.z() / V.x(); } V = osg::Vec3d(P2.z() - P1.z(), uv2.x() - uv1.x(), uv2.y() - uv1.y()) ^ osg::Vec3d(P3.z() - P1.z(), uv3.x() - uv1.x(), uv3.y() - uv1.y()); if (V.x() != 0) { V.normalize(); T1.z() += -V.y() / V.x(); B1.z() += -V.z() / V.x(); T2.z() += -V.y() / V.x(); B2.z() += -V.z() / V.x(); T3.z() += -V.y() / V.x(); B3.z() += -V.z() / V.x(); } if( (T1.length() == 0) && (B1.length() == 0) && (T2.length() == 0) && (B2.length() == 0) && (T3.length() == 0) && (B3.length() == 0) ) { osg::notify( osg::WARN ) << "Bad tangent space." << std::endl; osg::notify( osg::WARN ) << " iA " << iA << " uv1 " << uv1 << std::endl; osg::notify( osg::WARN ) << " iB " << iB << " uv2 " << uv2 << std::endl; osg::notify( osg::WARN ) << " iC " << iC << " uv3 " << uv3 << std::endl; } osg::Vec3d tempvec; tempvec = N1 ^ T1; (*T_)[iA] = osg::Vec4(tempvec ^ N1, 0); tempvec = B1 ^ N1; (*B_)[iA] = osg::Vec4(N1 ^ tempvec, 0); tempvec = N2 ^ T2; (*T_)[iB] = osg::Vec4(tempvec ^ N2, 0); tempvec = B2 ^ N2; (*B_)[iB] = osg::Vec4(N2 ^ tempvec, 0); tempvec = N3 ^ T3; (*T_)[iC] = osg::Vec4(tempvec ^ N3, 0); tempvec = B3 ^ N3; (*B_)[iC] = osg::Vec4(N3 ^ tempvec, 0); (*N_)[iA] += osg::Vec4(N1, 0); (*N_)[iB] += osg::Vec4(N2, 0); (*N_)[iC] += osg::Vec4(N3, 0); } else{ osg::Vec3d face_normal = (P2 - P1) ^ (P3 - P1); osg::Vec3d V; V = osg::Vec3d(P2.x() - P1.x(), uv2.x() - uv1.x(), uv2.y() - uv1.y()) ^ osg::Vec3d(P3.x() - P1.x(), uv3.x() - uv1.x(), uv3.y() - uv1.y()); if (V.x() != 0) { V.normalize(); (*T_)[iA].x() += -V.y() / V.x(); (*B_)[iA].x() += -V.z() / V.x(); (*T_)[iB].x() += -V.y() / V.x(); (*B_)[iB].x() += -V.z() / V.x(); (*T_)[iC].x() += -V.y() / V.x(); (*B_)[iC].x() += -V.z() / V.x(); } V = osg::Vec3d(P2.y() - P1.y(), uv2.x() - uv1.x(), uv2.y() - uv1.y()) ^ osg::Vec3d(P3.y() - P1.y(), uv3.x() - uv1.x(), uv3.y() - uv1.y()); if (V.x() != 0) { V.normalize(); (*T_)[iA].y() += -V.y() / V.x(); (*B_)[iA].y() += -V.z() / V.x(); (*T_)[iB].y() += -V.y() / V.x(); (*B_)[iB].y() += -V.z() / V.x(); (*T_)[iC].y() += -V.y() / V.x(); (*B_)[iC].y() += -V.z() / V.x(); } V = osg::Vec3d(P2.z() - P1.z(), uv2.x() - uv1.x(), uv2.y() - uv1.y()) ^ osg::Vec3d(P3.z() - P1.z(), uv3.x() - uv1.x(), uv3.y() - uv1.y()); if (V.x() != 0) { V.normalize(); (*T_)[iA].z() += -V.y() / V.x(); (*B_)[iA].z() += -V.z() / V.x(); (*T_)[iB].z() += -V.y() / V.x(); (*B_)[iB].z() += -V.z() / V.x(); (*T_)[iC].z() += -V.y() / V.x(); (*B_)[iC].z() += -V.z() / V.x(); } (*N_)[iA] += osg::Vec4(face_normal, 0); (*N_)[iB] += osg::Vec4(face_normal, 0); (*N_)[iC] += osg::Vec4(face_normal, 0); } } // osgwTools }
37.033493
149
0.461693
epsilonorion
fd3d0a66668762df21be8791e950c82c515166d9
2,120
hpp
C++
Engine/Source/Core/Testing.hpp
AhsanSarwar45/Qombat-OLD
0247441cf4927733ef0786c6df9a087461b0260b
[ "Apache-2.0" ]
null
null
null
Engine/Source/Core/Testing.hpp
AhsanSarwar45/Qombat-OLD
0247441cf4927733ef0786c6df9a087461b0260b
[ "Apache-2.0" ]
null
null
null
Engine/Source/Core/Testing.hpp
AhsanSarwar45/Qombat-OLD
0247441cf4927733ef0786c6df9a087461b0260b
[ "Apache-2.0" ]
null
null
null
// #pragma once // #include "Core/Core.hpp" // #include "Core/Configuration/ConfigManager.hpp" // #include "Core/Memory/PoolAllocator.hpp" // #include "Core/Memory/StackAllocator.hpp" // #include "Utility/Hashing.hpp" // #include <Core/Configuration/Configuration.hpp> // namespace QMBT // { // class MemoryLogger // { // public: // static void Init() // { // CONFIG_GROUP("TestGroup", // CONFIG_INT(s_VerbosityLevel, "Verbosity Level", "Sets the Verbosity Level", 0, 3)) // } // //inline static std::shared_ptr<spdlog::logger>& Get() { return s_Logger; } // //inline static std::shared_ptr<spdlog::logger> s_Logger; // inline static int s_VerbosityLevel = 5; // inline static int s_Pattern = 3; // }; // struct TestingPools // { // char a = 'g'; // double b = 5; // int c; // }; // void TestHash() // { // StringHash hash = StringHash("Arhedzejtgfxryeuhtrjytdkytkytjtfxjtrfrdjtyk"); // StringHash hash1 = StringHash("Arhedzejtgfxryeuhtrjytdkytkytjtfxjtrfrdjtyj"); // StringHash hash2 = StringHash("Arhedzejtgfxryeuhtrjytdkytkytjtfxjtrfrdjtyk"); // LOG_CORE_INFO("test hash = {0}", hash); // LOG_CORE_INFO("test hash1 = {0}", hash1); // LOG_CORE_INFO("test hash2 = {0}", hash2); // } // void TestMemory() // { // // StackAllocator allocator = StackAllocator("Stack Allocator"); // // TestingPools* objects[10]; // // for (int i = 0; i < 8; ++i) // // { // // objects[i] = allocator.Allocate<TestingPools>(); // // objects[i]->a = 'a' + i; // // objects[i]->b = i; // // } // // for (int i = 0; i < 8; ++i) // // { // // LOG_CORE_INFO("Info {0}, {1}, {2}", objects[i]->a, objects[i]->b, objects[i]->c); // // } // // for (int i = 7; i >= 0; --i) // // { // // allocator.Deallocate<TestingPools>(objects[i]); // // } // } // void Test() // { // LOG_CORE_INFO("Initial Val: {0}", MemoryLogger::s_VerbosityLevel); // MemoryLogger::Init(); // ConfigManager::SetConfigInt("TestGroup", "Verbosity Level", 345); // LOG_CORE_INFO("Initial Val: {0}", MemoryLogger::s_VerbosityLevel); // } // } // namespace QMBT
27.179487
92
0.602358
AhsanSarwar45
fd42376fcd48f86a650efbef3d27f2221688aa60
882
cpp
C++
src/Przeszkoda_Prost.cpp
broszczakmateusz/Dron-poprawione
a7a3efc370e2ddf6110fd8e3672296cf32775dc2
[ "MIT" ]
null
null
null
src/Przeszkoda_Prost.cpp
broszczakmateusz/Dron-poprawione
a7a3efc370e2ddf6110fd8e3672296cf32775dc2
[ "MIT" ]
null
null
null
src/Przeszkoda_Prost.cpp
broszczakmateusz/Dron-poprawione
a7a3efc370e2ddf6110fd8e3672296cf32775dc2
[ "MIT" ]
null
null
null
// // Created by mati on 07.06.2020. // #include "Przeszkoda_Prost.h" Przeszkoda_Prost::Przeszkoda_Prost(std::shared_ptr<drawNS::Draw3DAPI> ptrApi, const SWektor<double,ROZMIAR> &sr) : Prostopadloscian(ptrApi, sr) { for (int i = 0; i<8; i++) { Wierzcholki[i] = Wierzcholki[i] /2; } SWektor<double,ROZMIAR> tmp; tmp = srodek - Wierzcholki[0]; r_przeszkoda = tmp.dlugosc(); } void Przeszkoda_Prost::Rysuj() { Prostopadloscian::Rysuj(); api->change_shape_color(id,"green"); api->redraw(); } bool Przeszkoda_Prost::czy_kolizja(const Dron_interfejs &D)const { double suma_r = r_przeszkoda + D.get_r(); SWektor<double,ROZMIAR> tmp; tmp = srodek - D.get_srodek(); if ( tmp.dlugosc() < suma_r) { std::cout<< "Nastapila kolizja z przeszkoada! Wstrzymano ruch."; return true; } else return false; }
26.727273
112
0.646259
broszczakmateusz
fd42e1fb90e15220993a425ab67d649d58b8b1e0
2,842
cpp
C++
Programiranje Test 2 - Fuzija (spajanje) 2 niza u jedan/main.cpp
owlCoder/C_Plus_Plus_Projects
d2c70411c9322c89a8d6158a144e161abce65735
[ "MIT" ]
null
null
null
Programiranje Test 2 - Fuzija (spajanje) 2 niza u jedan/main.cpp
owlCoder/C_Plus_Plus_Projects
d2c70411c9322c89a8d6158a144e161abce65735
[ "MIT" ]
null
null
null
Programiranje Test 2 - Fuzija (spajanje) 2 niza u jedan/main.cpp
owlCoder/C_Plus_Plus_Projects
d2c70411c9322c89a8d6158a144e161abce65735
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; #include "FUZIJA.hpp" #include "PRAVOUGAONIK.hpp" #include "TACKA.hpp" int main() { int na, nb, nc, i; { cout << "\n---------------------- <int> ----------------------\n"; cout << endl << "Unos dimenzije za prvi niz: "; cin >> na; int* a = new int [na]; cout << "Unos elemenata prvog niza: "; for (i = 0; i < na; i++) cin >> a[i]; cout << endl << "\nUnos dimenzije za drugi niz: "; cin >> nb; int* b = new int [nb]; cout << "Unos elemenata drugog niza: "; for (i = 0; i < nb; i++) cin >> b[i]; int* c; fuzija <int> (a, na, b, nb, c, nc); cout << endl << "Fuzija: \n"; for (i = 0; i < nc; i++) cout << " " << c[i]; delete [] a; delete [] b; delete [] c; cout << "\n---------------------- <int> ----------------------\n"; } { cout << "\n\n\n\n---------------------- <Tacka> --------------------\n"; cout << endl << "Unos dimenzije za prvi niz: "; cin >> na; Tacka* a = new Tacka [na]; cout << "Unos elemenata prvog niza: "; for (i = 0; i < na; i++) cin >> a[i]; cout << endl << "\nUnos dimenzije za drugi niz: "; cin >> nb; Tacka* b = new Tacka [nb]; cout << "Unos elemenata drugog niza: "; for (i = 0; i < nb; i++) cin >> b[i]; Tacka* c; fuzija <Tacka> (a, na, b, nb, c, nc); cout << endl << "Fuzija: \n"; for (i = 0; i < nc; i++) cout << " " << c[i]; delete [] a; delete [] b; delete [] c; cout << "\n---------------------- <Tacka> ---------------------\n"; } { cout << "\n\n\n\n----------------- <Pravougaonik> -----------------\n"; cout << endl << "Unos dimenzije za prvi niz: "; cin >> na; Pravougaonik* a = new Pravougaonik [na]; cout << "Unos elemenata prvog niza: "; for (i = 0; i < na; i++) cin >> a[i]; cout << endl << "\nUnos dimenzije za drugi niz: "; cin >> nb; Pravougaonik* b = new Pravougaonik [nb]; cout << "Unos elemenata drugog niza: "; for (i = 0; i < nb; i++) cin >> b[i]; Pravougaonik* c; fuzija <Pravougaonik> (a, na, b, nb, c, nc); cout << endl << "Fuzija: \n"; for (i = 0; i < nc; i++) cout << " " << c[i]; delete [] a; delete [] b; delete [] c; cout << "\n------------------- <Pravougaonik> -----------------\n"; } return 0; }
23.882353
81
0.354328
owlCoder
fd47f756c6468c0c78a994564c8a0efa229d2268
1,721
cpp
C++
gpmp2/obstacle/tests/testSelfCollision.cpp
Cryptum169/gpmp2
f361baac4917b9a4d1220411e9c69dc9f96f4277
[ "BSD-3-Clause" ]
null
null
null
gpmp2/obstacle/tests/testSelfCollision.cpp
Cryptum169/gpmp2
f361baac4917b9a4d1220411e9c69dc9f96f4277
[ "BSD-3-Clause" ]
null
null
null
gpmp2/obstacle/tests/testSelfCollision.cpp
Cryptum169/gpmp2
f361baac4917b9a4d1220411e9c69dc9f96f4277
[ "BSD-3-Clause" ]
null
null
null
/** * @file testSelfCollisionArm.cpp * @author Mustafa Mukadam **/ #include <CppUnitLite/TestHarness.h> #include <gtsam/base/Matrix.h> #include <gtsam/base/Testable.h> #include <gtsam/base/numericalDerivative.h> #include <gpmp2/obstacle/SelfCollisionArm.h> #include <iostream> #include <cmath> using namespace std; using namespace gtsam; using namespace gpmp2; /* ************************************************************************** */ TEST(SelfCollisionArm, error) { // 3 link arm Vector3 a(1, 1, 1), alpha(0, 0, 0), d(0, 0, 0); Arm abs_arm(3, a, alpha, d); BodySphereVector body_spheres; body_spheres.push_back(BodySphere(0, 0.1, Point3(-0.5, 0, 0))); body_spheres.push_back(BodySphere(1, 0.1, Point3(-0.5, 0, 0))); body_spheres.push_back(BodySphere(1, 0.1, Point3(0, 0, 0))); body_spheres.push_back(BodySphere(2, 0.1, Point3(0, 0, 0))); ArmModel arm(abs_arm, body_spheres); Matrix data(2, 4); // sphere A id, sphere B id, epsilon, sigma data << 0, 1, 2.0, 0.1, 2, 3, 5.0, 0.1; SelfCollisionArm factor = SelfCollisionArm(0, arm, data); Vector actual, expect; Matrix H_exp, H_act; Vector3 q; q = Vector3(0.0, M_PI/2.0, 0.0); actual = factor.evaluateError(q, H_act); expect = (Vector(2) << 1.4928932188134527, 4.2).finished(); H_exp = numericalDerivative11(std::function<Vector2(const Vector3&)>( boost::bind(&SelfCollisionArm::evaluateError, factor, _1, boost::none)), q, 1e-6); EXPECT(assert_equal(expect, actual, 1e-6)); EXPECT(assert_equal(H_exp, H_act, 1e-6)); } /* ************************************************************************** */ /* main function */ int main() { TestResult tr; return TestRegistry::runAllTests(tr); }
28.213115
86
0.617083
Cryptum169
fd57a84e742671ace2a25b648a9028b9f8e41bee
966
cpp
C++
library/source/operations_tests/pretty_print_tester.cpp
spiretrading/darcel
a9c32989ad9c1571edaa41c7c3a86b276b782c0d
[ "MIT" ]
null
null
null
library/source/operations_tests/pretty_print_tester.cpp
spiretrading/darcel
a9c32989ad9c1571edaa41c7c3a86b276b782c0d
[ "MIT" ]
null
null
null
library/source/operations_tests/pretty_print_tester.cpp
spiretrading/darcel
a9c32989ad9c1571edaa41c7c3a86b276b782c0d
[ "MIT" ]
1
2020-04-17T13:25:25.000Z
2020-04-17T13:25:25.000Z
#include <sstream> #include <catch.hpp> #include "darcel/operations/pretty_print.hpp" #include "darcel/syntax/literal_expression.hpp" using namespace darcel; using namespace std; TEST_CASE("test_pretty_print_let", "[pretty_print]") { SECTION("Int literal") { std::stringstream ss; auto l = std::make_unique<LiteralExpression>(Location::global(), Literal("123", IntegerDataType::get_instance())); pretty_print(*l, ss); REQUIRE(ss.str() == "123"); } SECTION("Bool literal") { std::stringstream ss; auto l = std::make_unique<LiteralExpression>(Location::global(), Literal("true", BoolDataType::get_instance())); pretty_print(*l, ss); REQUIRE(ss.str() == "true"); } SECTION("String literal") { std::stringstream ss; auto l = std::make_unique<LiteralExpression>(Location::global(), Literal("hello", TextDataType::get_instance())); pretty_print(*l, ss); REQUIRE(ss.str() == "\"hello\""); } }
30.1875
68
0.665631
spiretrading
fd5dc361bd3e018873745bd51d8606b01c09b3c9
1,179
cpp
C++
Source/Framework/Core/Scene/TeSceneActor.cpp
GameDevery/TweedeFrameworkRedux
69a28fe171db33d00066b97b9b6bf89f6ef3e3a4
[ "MIT" ]
14
2022-02-25T15:52:35.000Z
2022-03-30T18:44:29.000Z
Source/Framework/Core/Scene/TeSceneActor.cpp
GameDevery/TweedeFrameworkRedux
69a28fe171db33d00066b97b9b6bf89f6ef3e3a4
[ "MIT" ]
null
null
null
Source/Framework/Core/Scene/TeSceneActor.cpp
GameDevery/TweedeFrameworkRedux
69a28fe171db33d00066b97b9b6bf89f6ef3e3a4
[ "MIT" ]
1
2022-02-28T09:24:05.000Z
2022-02-28T09:24:05.000Z
#include "TeSceneActor.h" #include "Scene/TeSceneObject.h" namespace te { void SceneActor::SetTransform(const Transform& transform) { if (_mobility != ObjectMobility::Movable) return; _transform = transform; _markCoreDirty(ActorDirtyFlag::Transform); } void SceneActor::SetMobility(ObjectMobility mobility) { _mobility = mobility; _markCoreDirty(ActorDirtyFlag::Mobility); } void SceneActor::SetActive(bool active) { _active = active; _markCoreDirty(ActorDirtyFlag::Active); } void SceneActor::UpdateState(const SceneObject& so, bool force) { UINT32 curHash = so.GetTransformHash(); if (curHash != _hash || force) { SetTransform(so.GetTransform()); _hash = curHash; } if (so.GetActive() != _active || force) { SetActive(so.GetActive()); _markCoreDirty(ActorDirtyFlag::Active); } if (so.GetMobility() != _mobility || force) { SetMobility(so.GetMobility()); _markCoreDirty(ActorDirtyFlag::Mobility); } } }
24.061224
67
0.583545
GameDevery
fd5e29e923774d0d8c7fe8128735a10d11f28d8f
179
cpp
C++
MIDI Test/AppMisc.cpp
MiguelGuthridge/HDSQs-MIDI-Editor
a5d6a2ea84b5123fb8f1aa0921da0b04e6e6cc27
[ "MIT" ]
null
null
null
MIDI Test/AppMisc.cpp
MiguelGuthridge/HDSQs-MIDI-Editor
a5d6a2ea84b5123fb8f1aa0921da0b04e6e6cc27
[ "MIT" ]
1
2018-07-01T08:51:05.000Z
2018-08-18T10:40:53.000Z
MIDI Test/AppMisc.cpp
HDSQmid/HDSQs-MIDI-Editor
a5d6a2ea84b5123fb8f1aa0921da0b04e6e6cc27
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "AppMisc.h" #include "files.h" #include "settings.h" void quit() { if (settings->getSaveBackup()) { if (fileIsOpen()) fileClose(); } exit(0); }
13.769231
33
0.642458
MiguelGuthridge
5b76206abdec46b5dd34feea66c57283cbd1858b
1,132
cpp
C++
Number Theory/extendedgcd.cpp
MYK12397/Algorithmic-Techniques
36b42aec550fba9ff49a74a383f6e9729e63dbc8
[ "MIT" ]
null
null
null
Number Theory/extendedgcd.cpp
MYK12397/Algorithmic-Techniques
36b42aec550fba9ff49a74a383f6e9729e63dbc8
[ "MIT" ]
null
null
null
Number Theory/extendedgcd.cpp
MYK12397/Algorithmic-Techniques
36b42aec550fba9ff49a74a383f6e9729e63dbc8
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; #define ll long long #define pb push_back const int mod =(int)1e9+7; /*int d,x,y; void extendedeuclid(int a,int b){ if(b==0){ d=a; x=1; y=0; } else{ extendedeuclid(b,a%b); int tmp=x; x=y; y=temp-(a/b)*y; } }*/ class triplet{ public: ll gcd; ll x; ll y; }; triplet extengcd(ll a, ll b){ if(b==0){ triplet myans; myans.gcd=a; myans.x=1; myans.y=0; return myans; } triplet res= extengcd(b,a%b); triplet ans; ans.gcd=res.gcd; ans.x=res.y; ans.y= res.x-((a/b)*res.y); return ans; } ll inverse(ll a,ll m){ ll x= extengcd(a,m).x; return (x%m+m)%m; } int main() { ios::sync_with_stdio(false); cin.tie(0); int t; scanf("%d",&t); while(t--) { ll a,b,d; cin>>a>>b>>d; ll g= __gcd(a,b); a/=g; b/=g; d/=g; if(d%g){ cout<<0<<endl; continue; } if(d==0){ cout<<1<<endl; continue; } ll y1= ((d%a)*inverse(b,a))%a; ll fval=d/b; if(d<y1*b){ cout<<0<<endl; continue; } ll n= (fval-y1)/a; cout<<n+1<<endl;} return 0; }
12.863636
34
0.506184
MYK12397
5b82b197ef4d2597f7a753c6057aca16f4265913
9,710
hpp
C++
sources/include/vssetup.hpp
fstudio/clangbuilder
d7c9b108afbf7eba7e614ca9ffd3b88d0cd061de
[ "MIT" ]
106
2016-01-25T11:15:37.000Z
2022-01-12T23:57:02.000Z
sources/include/vssetup.hpp
fstudio/clangbuilder
d7c9b108afbf7eba7e614ca9ffd3b88d0cd061de
[ "MIT" ]
45
2016-02-19T03:26:54.000Z
2021-06-12T13:36:43.000Z
sources/include/vssetup.hpp
fstudio/clangbuilder
d7c9b108afbf7eba7e614ca9ffd3b88d0cd061de
[ "MIT" ]
19
2016-05-08T08:58:03.000Z
2021-06-04T09:39:42.000Z
/////// #ifndef CBUI_VSSETUP_HPP #define CBUI_VSSETUP_HPP #include <objbase.h> // Published by Visual Studio Setup team // Microsoft.VisualStudio.Setup.Configuration.Native #include "Setup.Configuration.h" #include "comutils.hpp" #include "systemtools.hpp" #include "vsinstance.hpp" #include <bela/strip.hpp> #include <bela/match.hpp> #include <bela/ascii.hpp> #include <bela/env.hpp> #include <cstdlib> #include <vector> #ifndef VSSetupConstants #define VSSetupConstants /* clang-format off */ const IID IID_ISetupConfiguration = { 0x42843719, 0xDB4C, 0x46C2, { 0x8E, 0x7C, 0x64, 0xF1, 0x81, 0x6E, 0xFD, 0x5B } }; const IID IID_ISetupConfiguration2 = { 0x26AAB78C, 0x4A60, 0x49D6, { 0xAF, 0x3B, 0x3C, 0x35, 0xBC, 0x93, 0x36, 0x5D } }; const IID IID_ISetupPackageReference = { 0xda8d8a16, 0xb2b6, 0x4487, { 0xa2, 0xf1, 0x59, 0x4c, 0xcc, 0xcd, 0x6b, 0xf5 } }; const IID IID_ISetupHelper = { 0x42b21b78, 0x6192, 0x463e, { 0x87, 0xbf, 0xd5, 0x77, 0x83, 0x8f, 0x1d, 0x5c } }; const IID IID_IEnumSetupInstances = { 0x6380BCFF, 0x41D3, 0x4B2E, { 0x8B, 0x2E, 0xBF, 0x8A, 0x68, 0x10, 0xC8, 0x48 } }; const IID IID_ISetupInstance2 = { 0x89143C9A, 0x05AF, 0x49B0, { 0xB7, 0x17, 0x72, 0xE2, 0x18, 0xA2, 0x18, 0x5C } }; const IID IID_ISetupInstance = { 0xB41463C3, 0x8866, 0x43B5, { 0xBC, 0x33, 0x2B, 0x06, 0x76, 0xF7, 0xF4, 0x2E } }; const CLSID CLSID_SetupConfiguration = { 0x177F0C4A, 0x1CD3, 0x4DE7, { 0xA3, 0x2C, 0x71, 0xDB, 0xBB, 0x9F, 0xA3, 0x6D } }; /* clang-format on */ #endif namespace clangbuilder { class VisualStudioNativeSearcher { public: VisualStudioNativeSearcher() : setupConfig(nullptr), setupConfig2(nullptr), setupHelper(nullptr) { Initialize(); } VisualStudioNativeSearcher(const VisualStudioNativeSearcher &) = delete; VisualStudioNativeSearcher &operator=(const VisualStudioNativeSearcher &) = delete; bool GetVSInstanceAll(std::vector<VSInstance> &instances); private: bool Initialize(); bool IsEWDKEnabled(); bool GetVSInstanceInfo(comptr<ISetupInstance2> inst, VSInstance &vsi); bool CheckInstalledComponent(comptr<ISetupPackageReference> package, bool &bWin10SDK, bool &bWin81SDK); comptr<ISetupConfiguration> setupConfig; comptr<ISetupConfiguration2> setupConfig2; comptr<ISetupHelper> setupHelper; bool initializationFailure{false}; }; // TODO initialize inline bool VisualStudioNativeSearcher::Initialize() { if (FAILED(setupConfig.CoCreateInstance(CLSID_SetupConfiguration, NULL, IID_ISetupConfiguration, CLSCTX_INPROC_SERVER)) || setupConfig == NULL) { initializationFailure = true; return false; } if (FAILED(setupConfig.QueryInterface(IID_ISetupConfiguration2, (void **)&setupConfig2)) || setupConfig2 == NULL) { initializationFailure = true; return false; } if (FAILED(setupConfig.QueryInterface(IID_ISetupHelper, (void **)&setupHelper)) || setupHelper == NULL) { initializationFailure = true; return false; } initializationFailure = false; return true; } inline bool VisualStudioNativeSearcher::IsEWDKEnabled() { return (bela::EqualsIgnoreCase(L"True", bela::GetEnv(L"EnterpriseWDK")) && bela::EqualsIgnoreCase(L"True", bela::GetEnv(L"DisableRegistryUse"))); } inline std::wstring LookupVCToolsetVersion(std::wstring_view vsdir) { auto vcfile = bela::StringCat(vsdir, L"/VC/Auxiliary/Build/Microsoft.VCToolsVersion.default.txt"); std::wstring ver; if (!clangbuilder::LookupVersionFromFile(vcfile, ver)) { return L""; } return std::wstring(bela::StripAsciiWhitespace(ver)); } inline bool VisualStudioNativeSearcher::CheckInstalledComponent(comptr<ISetupPackageReference> package, bool &bWin10SDK, bool &bWin81SDK) { constexpr const std::wstring_view Win10SDKComponent = L"Microsoft.VisualStudio.Component.Windows10SDK"; constexpr const std::wstring_view Win81SDKComponent = L"Microsoft.VisualStudio.Component.Windows81SDK"; constexpr const std::wstring_view ComponentType = L"Component"; bool ret = false; bWin10SDK = bWin81SDK = false; comstr bstrId; if (FAILED(package->GetId(&bstrId))) { return ret; } comstr bstrType; if (FAILED(package->GetType(&bstrType))) { return ret; } std::wstring_view id{bstrId}; std::wstring_view type{bstrType}; // Checks for any version of Win10 SDK. The version is appended at the end of // the // component name ex: Microsoft.VisualStudio.Component.Windows10SDK.10240 if (id.find(Win10SDKComponent) != std::wstring_view::npos && type.compare(ComponentType) == 0) { bWin10SDK = true; ret = true; } if (id.compare(Win81SDKComponent) == 0 && type.compare(ComponentType) == 0) { bWin81SDK = true; ret = true; } return ret; } inline bool VisualStudioNativeSearcher::GetVSInstanceInfo(comptr<ISetupInstance2> inst, VSInstance &vsi) { if (inst == nullptr) { return false; } comstr bstrId; if (FAILED(inst->GetInstanceId(&bstrId))) { return false; } vsi.InstanceId = std::wstring(bstrId); InstanceState state; if (FAILED(inst->GetState(&state))) { return false; } auto lcid = GetUserDefaultLCID(); comstr bstrName; if (SUCCEEDED(inst->GetDisplayName(lcid, &bstrName))) { vsi.DisplayName = std::wstring(bstrName); } comptr<ISetupInstanceCatalog> catalog; if (SUCCEEDED(inst->QueryInterface(__uuidof(ISetupInstanceCatalog), (void **)&catalog)) && catalog != nullptr) { variant_t vt; if (SUCCEEDED(catalog->IsPrerelease(&vt.boolVal))) { vsi.IsPrerelease = (vt.boolVal != VARIANT_FALSE); } } vsi.DisplayName.append(vsi.IsPrerelease ? L" (Preview)" : L" (Release)"); ULONGLONG ullVersion = 0; comstr bstrVersion; if (FAILED(inst->GetInstallationVersion(&bstrVersion))) { return false; } vsi.Version = std::wstring(bstrVersion); if (SUCCEEDED(setupHelper->ParseVersion(bstrVersion, &ullVersion))) { vsi.ullVersion = ullVersion; vsi.ullMainVersion = ullVersion >> 48; } // Reboot may have been required before the installation path was created. comstr bstrInstallationPath; if ((eLocal & state) == eLocal) { if (FAILED(inst->GetInstallationPath(&bstrInstallationPath))) { return false; } vsi.VSInstallLocation = std::wstring(bstrInstallationPath); } vsi.VCToolsetVersion = LookupVCToolsetVersion(vsi.VSInstallLocation); // Reboot may have been required before the product package was registered // (last). if ((eRegistered & state) == eRegistered) { comptr<ISetupPackageReference> product; if (FAILED(inst->GetProduct(&product)) || !product) { return false; } LPSAFEARRAY lpsaPackages; if (FAILED(inst->GetPackages(&lpsaPackages)) || lpsaPackages == NULL) { return false; } int lower = lpsaPackages->rgsabound[0].lLbound; int upper = lpsaPackages->rgsabound[0].cElements + lower; IUnknown **ppData = (IUnknown **)lpsaPackages->pvData; for (int i = lower; i < upper; i++) { comptr<ISetupPackageReference> package = NULL; if (FAILED(ppData[i]->QueryInterface(IID_ISetupPackageReference, (void **)&package)) || package == nullptr) { continue; } bool win10SDKInstalled = false; bool win81SDkInstalled = false; bool ret = CheckInstalledComponent(package, win10SDKInstalled, win81SDkInstalled); if (ret) { vsi.IsWin10SDKInstalled |= win10SDKInstalled; vsi.IsWin81SDKInstalled |= win81SDkInstalled; } } SafeArrayDestroy(lpsaPackages); } return true; } inline bool VisualStudioNativeSearcher::GetVSInstanceAll(std::vector<VSInstance> &instances) { if (initializationFailure) { return false; } if (IsEWDKEnabled()) { auto envWindowsSdkDir81 = bela::GetEnv(L"WindowsSdkDir_81"); auto envVSVersion = bela::GetEnv(L"VisualStudioVersion"); auto envVsInstallDir = bela::GetEnv(L"VSINSTALLDIR"); if (!envVSVersion.empty() && !envVsInstallDir.empty()) { // TODO allowed version VSInstance item; item.IsEnterpriseWDK = true; item.VSInstallLocation = envVsInstallDir; item.Version = envVSVersion; item.DisplayName = bela::StringCat(L"Visual Studio ", envVSVersion, L" (EnterpriseWDK)"); item.VCToolsetVersion = LookupVCToolsetVersion(item.VSInstallLocation); item.ullVersion = std::stoi(envVSVersion); item.IsWin10SDKInstalled = true; item.IsWin81SDKInstalled = !envWindowsSdkDir81.empty(); instances.emplace_back(std::move(item)); } } // resolve all instances. comptr<IEnumSetupInstances> es; if (FAILED(setupConfig2->EnumInstances((IEnumSetupInstances **)&es))) { return false; } comptr<ISetupInstance> instance; while (SUCCEEDED(es->Next(1, &instance, nullptr)) && instance) { comptr<ISetupInstance2> instance2 = nullptr; if (FAILED(instance->QueryInterface(IID_ISetupInstance2, (void **)&instance2)) || instance2 == nullptr) { instance = nullptr; continue; } VSInstance item; if (GetVSInstanceInfo(instance2, item)) { instances.push_back(std::move(item)); } instance = nullptr; ///////// query once } std::sort(instances.begin(), instances.end()); return true; } } // namespace clangbuilder #endif
33.253425
101
0.671473
fstudio
5b8f07fef557d377c9ae80e31bcf664e1304cb07
1,524
cc
C++
core/proc/colormap.cc
amyznikov/qlidarview
a9826233ca5c8246d4fcdf23e6265ad2dad8e0c0
[ "CC0-1.0" ]
null
null
null
core/proc/colormap.cc
amyznikov/qlidarview
a9826233ca5c8246d4fcdf23e6265ad2dad8e0c0
[ "CC0-1.0" ]
null
null
null
core/proc/colormap.cc
amyznikov/qlidarview
a9826233ca5c8246d4fcdf23e6265ad2dad8e0c0
[ "CC0-1.0" ]
null
null
null
/* * colormap.cc * * Created on: Mar 18, 2022 * Author: amyznikov */ #include "colormap.h" #include <core/ssprintf.h> #include <core/debug.h> template<> const c_enum_member * members_of<COLORMAP>() { static constexpr c_enum_member members[] = { { COLORMAP_NONE, "NONE", "" }, { COLORMAP_JET, "JET", "" }, { COLORMAP_RAINBOW, "RAINBOW", "" }, { COLORMAP_AUTUMN, "AUTUMN", "" }, { COLORMAP_BONE, "BONE", "" }, { COLORMAP_WINTER, "WINTER", "" }, { COLORMAP_OCEAN, "OCEAN", "" }, { COLORMAP_SUMMER, "SUMMER", "" }, { COLORMAP_SPRING, "SPRING", "" }, { COLORMAP_COOL, "COOL", "" }, { COLORMAP_HSV, "HSV", "" }, { COLORMAP_PINK, "PINK", "" }, { COLORMAP_HOT, "HOT", "" }, { COLORMAP_PARULA, "PARULA", "" }, { COLORMAP_MAGMA, "MAGMA", "" }, { COLORMAP_INFERNO, "INFERNO", "" }, { COLORMAP_PLASMA, "PLASMA", "" }, { COLORMAP_VIRIDIS, "VIRIDIS", "" }, { COLORMAP_CIVIDIS, "CIVIDIS", "" }, { COLORMAP_TWILIGHT, "TWILIGHT", "" }, { COLORMAP_TWILIGHT_SHIFTED, "TWILIGHT_SHIFTED", "" }, { COLORMAP_TURBO, "TURBO", "" }, #if HAVE_COLORMAP_DEEPGREEN { COLORMAP_DEEPGREEN, "DEEPGREEN", "" }, #endif // HAVE_COLORMAP_DEEPGREEN { COLORMAP_NONE, nullptr, nullptr }, }; return members; } bool apply_colormap(cv::InputArray src, cv::OutputArray dst, COLORMAP cmap) { if ( cmap != COLORMAP_NONE ) { cv::applyColorMap(src, dst, cmap); return true; } return false; }
26.736842
75
0.574147
amyznikov
5b8f8559c869a17c673745ebac36a905449aea72
2,286
cpp
C++
euler024.cpp
suihan74/ProjectEuler
0ccd2470206a606700ab5c2a7162b2a3d3de2f8d
[ "MIT" ]
null
null
null
euler024.cpp
suihan74/ProjectEuler
0ccd2470206a606700ab5c2a7162b2a3d3de2f8d
[ "MIT" ]
null
null
null
euler024.cpp
suihan74/ProjectEuler
0ccd2470206a606700ab5c2a7162b2a3d3de2f8d
[ "MIT" ]
null
null
null
/** * Problem 24 「辞書式順列」 * 順列とはモノの順番付きの並びのことである. たとえば, 3124は数 1, 2, 3, 4 の一つの順列である. * すべての順列を数の大小でまたは辞書式に並べたものを辞書順と呼ぶ. 0と1と2の順列を辞書順に並べると * * 012 021 102 120 201 210 * になる. * * 0,1,2,3,4,5,6,7,8,9からなる順列を辞書式に並べたときの100万番目はいくつか? */ #include <cmath> #include <cstdint> #include <iostream> #include <stdexcept> #include <utility> // 9,876,543,210 みたいな結果を取り得るので,32bitだと溢れる恐れがある using uInt = std::uint_fast64_t; /** * 階乗を計算 * 試行可能範囲の算出に利用(nPn = n!より) * @param n 階乗したい数 * @return n! */ constexpr uInt factorial(uInt n) { return n > 1 ? n * factorial(n - 1) : 1; } /** * 0~9の数字を一回ずつ使った順列のうち,index番目のものを取得する * @param INDEX 何番目の順列が欲しいか * @param used 0~9のうち現在試行で使用中の数字を記録するビット列 * @param dic_counter 現在何番目までの順列を生成したかを表すカウンタ * @param current この深度までに生成されてきた値 * @param depth 再帰の深さ * @return .first 生成した順列 * @return .second 生成した順列が辞書順で何番目のものか */ std::pair<uInt, uInt> make_permutation_recursive( const uInt INDEX, uInt used = 0, uInt dic_counter = 0, uInt current = 0, uInt depth = 0) { for (uInt i = 0; i < 10; i++) { const uInt MASK = 1 << i; if (used & MASK) { continue; } const uInt PERM = current + i * std::pow(10, 9 - depth); if (depth == 9) { return std::make_pair(PERM, dic_counter + 1); } else { used |= MASK; auto p = make_permutation_recursive(INDEX, used, dic_counter, PERM, depth + 1); if (p.second == INDEX) { return std::move(p); } dic_counter = p.second; used &= ~MASK; } } return std::make_pair(0, dic_counter); } /** * 引数の範囲をチェックし,pairで返ってくる試行結果の必要部分だけ返す * @param INDEX 何番目の順列が欲しいか * @return INDEX番目に見つけた順列 * @throw std::out_of_range INDEXが0または10!を超える場合,試行不可能なので例外送出 */ inline uInt make_permutation_at(const uInt INDEX) { constexpr uInt FACT10 = factorial(10); if (INDEX == 0) { throw std::out_of_range("make_permutation_at(0) is not allowed"); } if (INDEX > FACT10) { throw std::out_of_range("make_permutation_at(): exceeded the calculable range"); } return make_permutation_recursive(INDEX).first; } int main(void) { try { std::cout << "Euler024: " << make_permutation_at(1000000) << std::endl; return 0; } catch (std::exception& e) { std::cout << e.what() << std::endl; return 1; } }
24.319149
106
0.646107
suihan74
5b900ac68cd8d887d044cee6626cd7c2833be086
50
cpp
C++
src/core/ent/ent_base.cpp
KEGEStudios/Moon
0e6aa078c8bf876c60aafe875ef53217ebdc74f1
[ "MIT" ]
null
null
null
src/core/ent/ent_base.cpp
KEGEStudios/Moon
0e6aa078c8bf876c60aafe875ef53217ebdc74f1
[ "MIT" ]
null
null
null
src/core/ent/ent_base.cpp
KEGEStudios/Moon
0e6aa078c8bf876c60aafe875ef53217ebdc74f1
[ "MIT" ]
1
2021-02-21T08:26:40.000Z
2021-02-21T08:26:40.000Z
#include "../../../template/core/ent/ent_base.tpp"
50
50
0.66
KEGEStudios
5b98384836b1d7302b5f056232f0d8510c08b101
6,579
cpp
C++
flare/src/actor_collider.cpp
taehyub/flare_cpp
7731bc0bcf2ce721f103586a48f74aa5c12504e8
[ "MIT" ]
14
2019-04-29T15:17:24.000Z
2020-12-30T12:51:05.000Z
flare/src/actor_collider.cpp
taehyub/flare_cpp
7731bc0bcf2ce721f103586a48f74aa5c12504e8
[ "MIT" ]
null
null
null
flare/src/actor_collider.cpp
taehyub/flare_cpp
7731bc0bcf2ce721f103586a48f74aa5c12504e8
[ "MIT" ]
6
2019-04-29T15:17:25.000Z
2021-11-16T03:20:59.000Z
#include "flare/actor_collider.hpp" #include "flare/block_reader.hpp" using namespace flare; ActorCollider::ActorCollider(ComponentType type) : ActorNode(type), m_IsCollisionEnabled(true) {} void ActorCollider::copy(const ActorCollider* node, ActorArtboard* artboard) { Base::copy(node, artboard); m_IsCollisionEnabled = node->m_IsCollisionEnabled; } ActorCollider* ActorCollider::read(ActorArtboard* artboard, BlockReader* reader, ActorCollider* collider) { Base::read(artboard, reader, collider); collider->m_IsCollisionEnabled = reader->readUint8() == 1; return collider; } bool ActorCollider::isCollisionEnabled() const { return m_IsCollisionEnabled; } void ActorCollider::isCollisionEnabled(bool isIt) { if (m_IsCollisionEnabled != isIt) { m_IsCollisionEnabled = isIt; } } // Rectangle ActorColliderRectangle::ActorColliderRectangle() : ActorCollider(ComponentType::ColliderRectangle), m_Width(0.0f), m_Height(0.0f) { } ActorComponent* ActorColliderRectangle::makeInstance(ActorArtboard* artboard) const { ActorColliderRectangle* instanceProp = new ActorColliderRectangle(); instanceProp->copy(this, artboard); return instanceProp; } void ActorColliderRectangle::copy(const ActorColliderRectangle* collider, ActorArtboard* artboard) { Base::copy(collider, artboard); m_Width = collider->m_Width; m_Height = collider->m_Height; } ActorColliderRectangle* ActorColliderRectangle::read(ActorArtboard* artboard, BlockReader* reader, ActorColliderRectangle* collider) { if (collider == nullptr) { collider = new ActorColliderRectangle(); } Base::read(artboard, reader, collider); collider->m_Width = reader->readFloat32(); collider->m_Height = reader->readFloat32(); return collider; } float ActorColliderRectangle::width() const { return m_Width; } float ActorColliderRectangle::height() const { return m_Height; } // Triangle ActorColliderTriangle::ActorColliderTriangle() : ActorCollider(ComponentType::ColliderTriangle), m_Width(0.0f), m_Height(0.0f) { } ActorComponent* ActorColliderTriangle::makeInstance(ActorArtboard* artboard) const { ActorColliderTriangle* instanceProp = new ActorColliderTriangle(); instanceProp->copy(this, artboard); return instanceProp; } void ActorColliderTriangle::copy(const ActorColliderTriangle* collider, ActorArtboard* artboard) { Base::copy(collider, artboard); m_Width = collider->m_Width; m_Height = collider->m_Height; } ActorColliderTriangle* ActorColliderTriangle::read(ActorArtboard* artboard, BlockReader* reader, ActorColliderTriangle* collider) { if (collider == nullptr) { collider = new ActorColliderTriangle(); } Base::read(artboard, reader, collider); collider->m_Width = reader->readFloat32(); collider->m_Height = reader->readFloat32(); return collider; } float ActorColliderTriangle::width() const { return m_Width; } float ActorColliderTriangle::height() const { return m_Height; } // Circle ActorColliderCircle::ActorColliderCircle() : ActorCollider(ComponentType::ColliderCircle), m_Radius(0.0f) {} ActorComponent* ActorColliderCircle::makeInstance(ActorArtboard* artboard) const { ActorColliderCircle* instanceProp = new ActorColliderCircle(); instanceProp->copy(this, artboard); return instanceProp; } void ActorColliderCircle::copy(const ActorColliderCircle* collider, ActorArtboard* artboard) { Base::copy(collider, artboard); m_Radius = collider->m_Radius; } ActorColliderCircle* ActorColliderCircle::read(ActorArtboard* artboard, BlockReader* reader, ActorColliderCircle* collider) { if (collider == nullptr) { collider = new ActorColliderCircle(); } Base::read(artboard, reader, collider); collider->m_Radius = reader->readFloat32(); return collider; } float ActorColliderCircle::radius() const { return m_Radius; } // Polygon ActorColliderPolygon::ActorColliderPolygon() : ActorCollider(ComponentType::ColliderPolygon), m_IsInstance(false), m_ContourVertexCount(0), m_ContourVertices(nullptr) { } ActorColliderPolygon::~ActorColliderPolygon() { if (!m_IsInstance) { delete[] m_ContourVertices; } } ActorComponent* ActorColliderPolygon::makeInstance(ActorArtboard* artboard) const { ActorColliderPolygon* instanceProp = new ActorColliderPolygon(); instanceProp->copy(this, artboard); return instanceProp; } void ActorColliderPolygon::copy(const ActorColliderPolygon* collider, ActorArtboard* artboard) { Base::copy(collider, artboard); m_IsInstance = true; m_ContourVertexCount = collider->m_ContourVertexCount; m_ContourVertices = collider->m_ContourVertices; } ActorColliderPolygon* ActorColliderPolygon::read(ActorArtboard* artboard, BlockReader* reader, ActorColliderPolygon* collider) { if (collider == nullptr) { collider = new ActorColliderPolygon(); } Base::read(artboard, reader, collider); collider->m_ContourVertexCount = reader->readUint32(); collider->m_ContourVertices = new float[collider->m_ContourVertexCount * 2]; reader->readFloat32Array(collider->m_ContourVertices, collider->m_ContourVertexCount * 2); return collider; } float* ActorColliderPolygon::contourVertices() const { return m_ContourVertices; } unsigned int ActorColliderPolygon::contourVertexCount() const { return m_ContourVertexCount; } // Line ActorColliderLine::ActorColliderLine() : ActorCollider(ComponentType::ColliderLine), m_IsInstance(false), m_VertexCount(0), m_Vertices(nullptr) { } ActorColliderLine::~ActorColliderLine() { if (!m_IsInstance) { delete[] m_Vertices; } } ActorComponent* ActorColliderLine::makeInstance(ActorArtboard* artboard) const { ActorColliderLine* instanceProp = new ActorColliderLine(); instanceProp->copy(this, artboard); return instanceProp; } void ActorColliderLine::copy(const ActorColliderLine* collider, ActorArtboard* artboard) { Base::copy(collider, artboard); m_IsInstance = true; m_VertexCount = collider->m_VertexCount; m_Vertices = collider->m_Vertices; } ActorColliderLine* ActorColliderLine::read(ActorArtboard* artboard, BlockReader* reader, ActorColliderLine* collider) { if (collider == nullptr) { collider = new ActorColliderLine(); } Base::read(artboard, reader, collider); collider->m_VertexCount = reader->readUint32(); collider->m_Vertices = new float[collider->m_VertexCount * 2]; reader->readFloat32Array(collider->m_Vertices, collider->m_VertexCount * 2); return collider; } float* ActorColliderLine::vertices() const { return m_Vertices; } unsigned int ActorColliderLine::vertexCount() const { return m_VertexCount; }
27.18595
129
0.769114
taehyub
5b99ef0f9ac2f67da283fb104dd73369b7744dca
4,666
cpp
C++
src/MCP2515/MCP2515_Io.cpp
rotoye/107-Arduino-MCP2515
70e6e2ed6918a97b8d6c681c4f8d9f6d214557a9
[ "MIT" ]
40
2020-02-21T12:42:59.000Z
2022-03-27T09:25:45.000Z
src/MCP2515/MCP2515_Io.cpp
adityathakekar/107-Arduino-MCP2515
5a0ddf728a32067d8bc849b1377bce55c649ac8e
[ "MIT" ]
29
2020-02-21T12:43:01.000Z
2022-01-31T09:12:03.000Z
src/MCP2515/MCP2515_Io.cpp
adityathakekar/107-Arduino-MCP2515
5a0ddf728a32067d8bc849b1377bce55c649ac8e
[ "MIT" ]
14
2020-02-10T10:41:11.000Z
2022-01-27T11:26:52.000Z
/** * This software is distributed under the terms of the MIT License. * Copyright (c) 2020 LXRobotics. * Author: Alexander Entinger <[email protected]> * Contributors: https://github.com/107-systems/107-Arduino-MCP2515/graphs/contributors. */ /************************************************************************************** * INCLUDE **************************************************************************************/ #include "MCP2515_Io.h" #include <Arduino.h> #include <assert.h> /************************************************************************************** * NAMESPACE **************************************************************************************/ namespace MCP2515 { /************************************************************************************** * CONSTANTS **************************************************************************************/ static Instruction const TABLE_LOAD_TX_BUFFER[] = { Instruction::LOAD_TX0, Instruction::LOAD_TX1, Instruction::LOAD_TX2 }; static Instruction const TABLE_REQUEST_TO_SEND[] = { Instruction::RTS_TX0, Instruction::RTS_TX1, Instruction::RTS_TX2 }; static Instruction const TABLE_READ_RX_BUFFER[] = { Instruction::READ_RX0, Instruction::READ_RX1 }; /************************************************************************************** * CTOR/DTOR **************************************************************************************/ MCP2515_Io::MCP2515_Io(SpiSelectFunc select, SpiDeselectFunc deselect, SpiTransferFunc transfer) : _select{select} , _deselect{deselect} , _transfer{transfer} { } /************************************************************************************** * PUBLIC MEMBER FUNCTIONS **************************************************************************************/ void MCP2515_Io::reset() { uint8_t const instruction = static_cast<uint8_t>(Instruction::RESET); _select(); _transfer(instruction); _deselect(); delay(10); } uint8_t MCP2515_Io::status() { uint8_t const instruction = static_cast<uint8_t>(Instruction::READ_STATUS); _select(); _transfer(instruction); uint8_t const status = _transfer(0); _deselect(); return status; } uint8_t MCP2515_Io::readRegister(Register const reg) { uint8_t const instruction = static_cast<uint8_t>(Instruction::READ); uint8_t const reg_addr = static_cast<uint8_t>(reg); _select(); _transfer(instruction); _transfer(reg_addr); uint8_t const data = _transfer(0); _deselect(); return data; } void MCP2515_Io::writeRegister(Register const reg, uint8_t const data) { uint8_t const instruction = static_cast<uint8_t>(Instruction::WRITE); uint8_t const reg_addr = static_cast<uint8_t>(reg); _select(); _transfer(instruction); _transfer(reg_addr); _transfer(data); _deselect(); } void MCP2515_Io::modifyRegister(Register const reg, uint8_t const mask, uint8_t const data) { uint8_t const instruction = static_cast<uint8_t>(Instruction::BITMOD); uint8_t const reg_addr = static_cast<uint8_t>(reg); _select(); _transfer(instruction); _transfer(reg_addr); _transfer(mask); _transfer(data); _deselect(); } void MCP2515_Io::setBit(Register const reg, uint8_t const bit_pos) { assert(bit_pos < 8); uint8_t const bit_mask = (1<<bit_pos); modifyRegister(reg, bit_mask, bit_mask); } void MCP2515_Io::clrBit(Register const reg, uint8_t const bit_pos) { assert(bit_pos < 8); uint8_t const bit_mask = (1<<bit_pos); modifyRegister(reg, bit_mask, 0); } void MCP2515_Io::loadTxBuffer(TxB const txb, uint8_t const * tx_buf_data) { uint8_t const instruction = static_cast<uint8_t>(TABLE_LOAD_TX_BUFFER[static_cast<uint8_t>(txb)]); _select(); _transfer(instruction); for(uint8_t b = 0; b < TX_BUF_SIZE; b++) { _transfer(tx_buf_data[b]); } _deselect(); } void MCP2515_Io::requestTx(TxB const txb) { uint8_t const instruction = static_cast<uint8_t>(TABLE_REQUEST_TO_SEND[static_cast<uint8_t>(txb)]); _select(); _transfer(instruction); _deselect(); } void MCP2515_Io::readRxBuffer(RxB const rxb, uint8_t * rx_buf_data) { uint8_t const instruction = static_cast<uint8_t>(TABLE_READ_RX_BUFFER[static_cast<uint8_t>(rxb)]); _select(); _transfer(instruction); for(uint8_t b = 0; b < RX_BUF_SIZE; b++) { rx_buf_data[b] = _transfer(0); } _deselect(); } /************************************************************************************** * NAMESPACE **************************************************************************************/ } /* MCP2515 */
25.779006
101
0.55315
rotoye
5b9c4a0dc8f947495554e61d3041cd8ddbbd787b
1,394
cpp
C++
Library/Sources/Stroika/Foundation/Execution/Throw.cpp
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
28
2015-09-22T21:43:32.000Z
2022-02-28T01:35:01.000Z
Library/Sources/Stroika/Foundation/Execution/Throw.cpp
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
98
2015-01-22T03:21:27.000Z
2022-03-02T01:47:00.000Z
Library/Sources/Stroika/Foundation/Execution/Throw.cpp
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
4
2019-02-21T16:45:25.000Z
2022-02-18T13:40:04.000Z
/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #include "../StroikaPreComp.h" #include "../Characters/ToString.h" #include "Throw.h" #if qStroika_Foundation_Exection_Throw_TraceThrowpointBacktrace #include "../Characters/String.h" #include "../Debug/BackTrace.h" #endif using namespace Stroika::Foundation; using namespace Stroika::Foundation::Execution; /* ******************************************************************************** ******************** Execution::Private_::GetBT_s/GetBT_ws ********************* ******************************************************************************** */ #if qStroika_Foundation_Exection_Throw_TraceThrowpointBacktrace string Private_::GetBT_s () { // KISS, and don't use string if you don't want truncation wstring tmp = Debug::BackTrace::Capture (Debug::BackTrace::Options{1}); // skip this frame from stacktrace string result; for (wchar_t c : tmp) { result += static_cast<char> (c); } return result; } wstring Private_::GetBT_ws () { // no need to use Thread::SuppressInterruptionInContext since not using any Stroika code that can throw return Debug::BackTrace::Capture (Debug::BackTrace::Options{1}); // skip this frame from stacktrace } #endif string Private_::ToString_s (const type_info& s) { return Characters::ToString (s).AsNarrowSDKString (); }
30.977778
110
0.620516
SophistSolutions
5b9eb569192f78f7e0adfebb943a50c88bc92107
1,702
hpp
C++
PnC/WBC/ContactSpec.hpp
stevenjj/PnC
e1e417dbd507f174bb2661247cb4360b6ee0ada7
[ "MIT" ]
1
2020-05-04T22:36:54.000Z
2020-05-04T22:36:54.000Z
PnC/WBC/ContactSpec.hpp
stevenjj/PnC
e1e417dbd507f174bb2661247cb4360b6ee0ada7
[ "MIT" ]
null
null
null
PnC/WBC/ContactSpec.hpp
stevenjj/PnC
e1e417dbd507f174bb2661247cb4360b6ee0ada7
[ "MIT" ]
null
null
null
#pragma once #include <stdio.h> #include <Eigen/Dense> #include <iostream> #include <PnC/RobotSystem/RobotSystem.hpp> #include <Utils/IO/IOUtilities.hpp> #include <Utils/Math/MathUtilities.hpp> //! Contact Frame's z-axis should correspond normal vector to the ground class ContactSpec { public: ContactSpec(RobotSystem* _robot, const int& _dim) { robot_ = _robot; dim_contact_ = _dim; b_set_contact_ = false; idx_Fz_ = dim_contact_ - 1; Jc_ = Eigen::MatrixXd::Zero(dim_contact_, robot_->getNumDofs()); JcDotQdot_ = Eigen::VectorXd::Zero(dim_contact_); } virtual ~ContactSpec() {} void getContactJacobian(Eigen::MatrixXd& Jc) { Jc = Jc_; } void getJcDotQdot(Eigen::VectorXd& JcDotQdot) { JcDotQdot = JcDotQdot_; } int getDim() { return dim_contact_; } void unsetContact() { b_set_contact_ = false; } bool updateContactSpec() { _UpdateJc(); _UpdateJcDotQdot(); _UpdateUf(); _UpdateInequalityVector(); b_set_contact_ = true; return true; } virtual int getDimRFConstratint() { return Uf_.rows(); } void getRFConstraintMtx(Eigen::MatrixXd& Uf) { Uf = Uf_; } void getRFConstraintVec(Eigen::VectorXd& ieq_vec) { ieq_vec = ieq_vec_; } int getFzIndex() { return idx_Fz_; } protected: virtual bool _UpdateJc() = 0; virtual bool _UpdateJcDotQdot() = 0; virtual bool _UpdateUf() = 0; virtual bool _UpdateInequalityVector() = 0; RobotSystem* robot_; Eigen::MatrixXd Jc_; Eigen::VectorXd JcDotQdot_; int dim_contact_; int idx_Fz_; bool b_set_contact_; Eigen::MatrixXd Uf_; Eigen::VectorXd ieq_vec_; };
27.451613
77
0.660987
stevenjj
5ba086382b898b99ecc8f4a8a5ac12b215c57f8b
260
cpp
C++
YorozuyaGSLib/source/_trans_account_report_wrac.cpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
YorozuyaGSLib/source/_trans_account_report_wrac.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
YorozuyaGSLib/source/_trans_account_report_wrac.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
#include <_trans_account_report_wrac.hpp> START_ATF_NAMESPACE int _trans_account_report_wrac::size() { using org_ptr = int (WINAPIV*)(struct _trans_account_report_wrac*); return (org_ptr(0x140207e00L))(this); }; END_ATF_NAMESPACE
23.636364
75
0.723077
lemkova
5ba37dacd8ac2e0f53c23ec2003548bcf7360380
1,355
cpp
C++
snippets/cpp/VS_Snippets_CLR/FieldInfo_SetValue/CPP/fieldinfo_setvalue.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
2
2020-02-22T09:30:21.000Z
2021-08-02T23:44:31.000Z
snippets/cpp/VS_Snippets_CLR/FieldInfo_SetValue/CPP/fieldinfo_setvalue.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
555
2019-09-23T22:22:58.000Z
2021-07-15T18:51:12.000Z
snippets/cpp/VS_Snippets_CLR/FieldInfo_SetValue/CPP/fieldinfo_setvalue.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
3
2020-01-29T16:31:15.000Z
2021-08-24T07:00:15.000Z
// <Snippet1> using namespace System; using namespace System::Reflection; using namespace System::Globalization; public ref class Example { private: String^ myString; public: Example() { myString = "Old value"; } property String^ StringProperty { String^ get() { return myString; } } }; int main() { Example^ myObject = gcnew Example; Type^ myType = Example::typeid; FieldInfo^ myFieldInfo = myType->GetField( "myString", BindingFlags::NonPublic | BindingFlags::Instance); // Display the string before applying SetValue to the field. Console::WriteLine( "\nThe field value of myString is \"{0}\".", myFieldInfo->GetValue( myObject ) ); // Display the SetValue signature used to set the value of a field. Console::WriteLine( "Applying SetValue(Object, Object)." ); // Change the field value using the SetValue method. myFieldInfo->SetValue( myObject, "New value" ); // Display the string after applying SetValue to the field. Console::WriteLine( "The field value of mystring is \"{0}\".", myFieldInfo->GetValue(myObject)); } /* This code produces the following output: The field value of myString is "Old value". Applying SetValue(Object, Object). The field value of mystring is "New value". */ // </Snippet1>
26.057692
71
0.660517
BohdanMosiyuk
5ba9ee27894b541339d82be27aaa8d94b6c6dea3
4,015
cpp
C++
IHM/main.cpp
Petititi/imGraph
068890ffe2f8fa1fb51bc95b8d9296cc79737fac
[ "BSD-3-Clause" ]
2
2015-01-12T11:27:45.000Z
2015-03-25T18:24:38.000Z
IHM/main.cpp
Petititi/imGraph
068890ffe2f8fa1fb51bc95b8d9296cc79737fac
[ "BSD-3-Clause" ]
30
2015-01-07T11:59:07.000Z
2015-04-24T13:02:01.000Z
IHM/main.cpp
Petititi/imGraph
068890ffe2f8fa1fb51bc95b8d9296cc79737fac
[ "BSD-3-Clause" ]
1
2018-12-20T12:18:18.000Z
2018-12-20T12:18:18.000Z
#include "view/GraphicView.h" #ifdef _WIN32 #pragma warning(disable:4503)//deactivated globally (without push) #pragma warning(push) #pragma warning(disable:4996 4251 4244 4275 4800) #include "listOfBlocks.h" #endif #include <QApplication> #include "opencv2/features2d.hpp" #include "qtextstream.h" #ifdef _WIN32 #pragma warning(pop) #endif using namespace charliesoft; using namespace std; using namespace cv; int main(int argc, char* argv[]) { QApplication app(argc, argv); Window::getInstance()->show(); return app.exec(); } /*! \mainpage ImGraph * \section sec1 Dependencies <p>The project is primarily developed on Windows, but we seek to make ImGraph a cross-platform project. The majority of the code should already be compatible with Linux and macOS, but it has not been tested...<br/> We also use some of the c++11 improvement, so you will need at least visual studio 2013 or g++ (>=4.6). </p> \subsection OpenCV OpenCV is an image/video processing library which was designed for computational efficiency and with a strong focus on real-time applications. Written in optimized C/C++, the library can take advantage of multi-core processing.<br/> As the version 3.0 is still not fully functionnal, we use an intermediate version from git://code.opencv.org/opencv.git, with the SHA-1 revision : 9eca3ec8f651e55c25094e4e76446f4bd904826c.<br/> \subsection CMake Cmake is a cross-platform, open-source build system. You can <a href="http://www.cmake.org/cmake/resources/software.html">download Cmake here</a>. You can follow <a href="http://www.cmake.org/cmake-tutorial/">this tutorial</a> to understand the full potential of this program. \subsection QT Qt is a cross-platform application framework that is widely used for IHM that can be run on various software and hardware platforms with little or no change in the codebase, while having the power and speed of native applications. ImGraph was primarily developped with Qt 4.8.5 but was successfully compiled with Qt 5! \subsection Boost Boost is a set of libraries for the C++ programming language. Many of Boost's founders are on the C++ standards committee, and several Boost libraries have been accepted for incorporation into both Technical Report 1 and the C++11 standard<br/> We use the 1.55 version (some problem exist with 1.57), you can found some <a href="http://sourceforge.net/projects/boost/files/boost-binaries/1.55.0-build2/">prebuild binaries here</a>. \subsection InputLoader This is a private library used to easily load/store videos (from webcam, files or folder).\n You can <a href="https://synogsm.lsis.univ-tln.fr/indefero/index.php/p/inputloader/source/tree/master/">download it here</a> (using login "guest" and no passwd). You should build and install it before building ImGraph! \subsection subsection_doxygen Doxygen (optional) Doxygen is used to generate the documentation of imGraph by creating an additionnal cmake target named "doc". Once the documentation is generated, please refer to html/index.html in the BINARY folder. If Doxygen cannot be found, this step is ignored (documentation for imGraph is also available online <a href="http://imgraph.github.io">here</a>). \section section_installation Installation Once dependencies are installed and configured, run this cmake command from the destination folder to generate the project (for VS12 in this example) with <I>path_to_opencv</I>,<I>path_to_qt5</I>,<I>path_to_inputloader</I>,<I>path_to_boost</I> and <I>path_to_imgraph</I> corresponding to your setup: \code{.sh} cmake -G "Visual Studio 12 2013" -DOPENCV_DIR=path_to_opencv -DCMAKE_PREFIX_PATH="path_to_qt5;path_to_InputLoader" -DBOOST_ROOT=path_to_boost path_to_imGraph \endcode \section ProjectStruct Project Structure \subsection ProjectStruct_Sub1 Scheduling and synchronization If you need details about how the graph of the processes handle scheduling and synchronization, this page is for you: \ref ProcessGraph \subsection ProjectStruct_Sub2 Build a Node \subsection ProjectStruct_Sub3 IHM */
63.730159
347
0.789539
Petititi
5bab9522d2ee611b52682ac9f4f9c034da0c36c1
23,381
cpp
C++
util.cpp
sxyu/watplot
7ea4e40756a084d1a5c7c0cb46a3458220a09682
[ "Apache-2.0" ]
2
2019-03-15T00:31:39.000Z
2020-08-12T01:43:51.000Z
util.cpp
sxyu/watplot
7ea4e40756a084d1a5c7c0cb46a3458220a09682
[ "Apache-2.0" ]
1
2019-03-15T01:19:01.000Z
2019-03-15T02:05:06.000Z
util.cpp
sxyu/watplot
7ea4e40756a084d1a5c7c0cb46a3458220a09682
[ "Apache-2.0" ]
1
2021-10-11T09:10:35.000Z
2021-10-11T09:10:35.000Z
#include "stdafx.h" #include "util.hpp" namespace watplot { namespace util { /* from SO */ std::string random_string(std::string::size_type length) { static auto& chrs = "0123456789" "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; thread_local static std::mt19937 rg{ std::random_device{}() }; thread_local static std::uniform_int_distribution<std::string::size_type> pick(0, sizeof(chrs) - 2); std::string s; s.reserve(length); while (length--) s += chrs[pick(rg)]; return s; } std::string padleft(int x, int digs, char chr) { std::stringstream stm; stm << std::setw(digs) << std::setfill(chr) << x; return stm.str(); } std::vector<std::string> split(const std::string & string_in, char const * delimiters, bool ignore_empty, bool trim) { std::vector<std::string> out; size_t n_delim = strlen(delimiters); if (n_delim == 0) { out.push_back(string_in); return out; } size_t a = 0, b = string_in.find_first_of(delimiters); for (; b != std::string::npos; a = b + 1, b = string_in.find_first_of(delimiters, a)) { out.push_back(std::move(string_in.substr(a, b - a))); if (ignore_empty && out.back().empty()) out.pop_back(); else { if (trim) { util::trim(out.back()); } } } out.push_back(std::move(string_in.substr(a))); if (ignore_empty && out.back().empty()) out.pop_back(); else { if (trim) { util::trim(out.back()); } } return out; } std::vector<std::string> split(const char * string_in, char const * delimiters, bool ignore_empty, bool trim) { return split(std::string(string_in), delimiters, ignore_empty, trim); } // trim from start (in place) void ltrim(std::string & s, const std::string & chrs) { s.erase(0, s.find_first_not_of(chrs)); } // trim from end (in place) void rtrim(std::string & s, const std::string & chrs) { s.erase(s.find_last_not_of(chrs) + 1, std::string::npos); } // trim from both ends (in place) void trim(std::string & s, const std::string & chrs) { //std::cerr << s << " A\n"; ltrim(s, chrs); //std::cerr << s << " B\n"; rtrim(s, chrs); //std::cerr << s << "\n"; } void upper(std::string & s) { for (size_t i = 0; i < s.size(); ++i) s[i] = std::toupper(s[i]); } void lower(std::string & s) { for (size_t i = 0; i < s.size(); ++i) s[i] = std::tolower(s[i]); } static double _closest_brute(const std::vector<point_t>& points) { if (points.size() < 2) { return -1.0; } auto minDistance = std::abs(sqr_dist(points.at(0), points.at(1))); for (auto i = std::begin(points); i != (std::end(points) - 1); ++i) { for (auto j = i + 1; j < std::end(points); ++j) { auto newDistance = std::abs(sqr_dist(*i, *j)); if (newDistance < minDistance) { minDistance = newDistance; } } } return minDistance; } static double _closest_optimized(const std::vector<point_t>& xP, const std::vector<point_t>& yP) { if (xP.size() <= 3) { return _closest_brute(xP); } auto N = xP.size(); std::vector<point_t> xL(xP.begin(), xP.begin() + N / 2), xR(xP.begin() + N / 2, xP.end()), yL, yR, yS; auto xM = xP.at((N - 1) / 2).first; std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) { return p.first <= xM; }); std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) { return p.first > xM; }); auto p1 = _closest_optimized(xL, yL), p2 = _closest_optimized(xR, yR); double minPair = min(p1, p2); std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) { return (xM - p.first) * (xM - p.first) < minPair; }); double result = minPair; for (auto i = yS.begin(); i != (yS.end() - 1); ++i) { for (auto k = i + 1; k != yS.end() && ((k->second - i->second) < minPair); ++k) { result = min(sqr_dist(*k, *i), result); } } return result; } double sqr_norm(const point_t & a) { return a.first * a.first + a.second * a.second; } double sqr_dist(const point_t & a, const point_t & b) { return (b.first - a.first) * (b.first - a.first) + (b.second - a.second) * (b.second - a.second); } double closest_pair_dist(const std::vector<point_t>& points) { auto xP = points, yP = points; std::sort(std::begin(xP), std::end(xP)); std::sort(std::begin(yP), std::end(yP), [](const point_t& a, const point_t& b) { return a.second < b.second; }); return sqrt(_closest_optimized(xP, yP)); } void par_for(std::function<void(int, int)> f, int l, int r, int num_threads) { if (num_threads == -1) num_threads = std::thread::hardware_concurrency();; std::vector<std::thread> mgr; int step = (r - 1) / num_threads + 1; for (int i = 0; i < r; i += step) { mgr.emplace_back(f, i, min(i + step, r)); } for (auto & thd : mgr) thd.join(); } void par_foreach(std::function<void(int)> f, int l, int r, std::mutex * mtx, int num_threads) { if (num_threads == -1) num_threads = std::thread::hardware_concurrency();; std::vector<std::thread> mgr; int cnt = l; bool own_mtx = !mtx; if (own_mtx) mtx = new std::mutex(); for (int i = 0; i < num_threads; ++i) { mgr.emplace_back([&]() { while (true) { mtx->lock(); if (cnt >= r) { mtx->unlock(); break; } int j = cnt; ++cnt; mtx->unlock(); f(j); } }); } for (auto & thd : mgr) thd.join(); if (own_mtx) delete mtx; } double min_max_k_partition(std::vector<std::pair<double, int> > & x, int k, int s, Eigen::ArrayXi * out) { std::sort(x.begin(), x.end()); int n = static_cast<int>(x.size()); double l = 0.0, r = x[n - 1].first - x[0].first, m; int start, cnt; while (r - l > 1e-9) { m = (l + r) / 2.; // oracle start = 0; cnt = 1; for (int i = 1; i < n; ++i) { if (x[i].first - x[start].first > m || i - start >= s) { start = i; ++cnt; } } if (cnt <= k) r = m; else l = m; } if (out) { auto & o = *out; o.setZero(); m = r; start = 0; cnt = 1; for (int i = 1; i < n; ++i) { if (x[i].first - x[start].first > m || i - start >= s) { start = i; ++cnt; o[x[i].second] = 1; } } if (cnt < k) { // unlikely, but if happens, fix for (int i = 1; i < n; ++i) { if (o[x[i].second] == 0) { o[x[i].second] = 1; ++cnt; if (cnt >= k) break; } } } // prefix sum to index array for (int i = 1; i < n; ++i) { o[x[i].second] += o[x[i - 1].second]; } } return r; } double double_to_angle(double angle) { bool negative = (angle < 0.0); angle = abs(angle); double dd = floor(angle / 10000.0); angle -= 10000.0 * dd; double mm = floor(angle / 100.0); double ss = angle - 100.0 * mm; dd += mm / 60.0 + ss / 3600.0; if (negative) dd *= -1; return dd; } static const std::vector<std::array<double, 3>> VIRIDIS = { { 0.267004, 0.004874, 0.329415 }, { 0.268510, 0.009605, 0.335427 }, { 0.269944, 0.014625, 0.341379 }, { 0.271305, 0.019942, 0.347269 }, { 0.272594, 0.025563, 0.353093 }, { 0.273809, 0.031497, 0.358853 }, { 0.274952, 0.037752, 0.364543 }, { 0.276022, 0.044167, 0.370164 }, { 0.277018, 0.050344, 0.375715 }, { 0.277941, 0.056324, 0.381191 }, { 0.278791, 0.062145, 0.386592 }, { 0.279566, 0.067836, 0.391917 }, { 0.280267, 0.073417, 0.397163 }, { 0.280894, 0.078907, 0.402329 }, { 0.281446, 0.084320, 0.407414 }, { 0.281924, 0.089666, 0.412415 }, { 0.282327, 0.094955, 0.417331 }, { 0.282656, 0.100196, 0.422160 }, { 0.282910, 0.105393, 0.426902 }, { 0.283091, 0.110553, 0.431554 }, { 0.283197, 0.115680, 0.436115 }, { 0.283229, 0.120777, 0.440584 }, { 0.283187, 0.125848, 0.444960 }, { 0.283072, 0.130895, 0.449241 }, { 0.282884, 0.135920, 0.453427 }, { 0.282623, 0.140926, 0.457517 }, { 0.282290, 0.145912, 0.461510 }, { 0.281887, 0.150881, 0.465405 }, { 0.281412, 0.155834, 0.469201 }, { 0.280868, 0.160771, 0.472899 }, { 0.280255, 0.165693, 0.476498 }, { 0.279574, 0.170599, 0.479997 }, { 0.278826, 0.175490, 0.483397 }, { 0.278012, 0.180367, 0.486697 }, { 0.277134, 0.185228, 0.489898 }, { 0.276194, 0.190074, 0.493001 }, { 0.275191, 0.194905, 0.496005 }, { 0.274128, 0.199721, 0.498911 }, { 0.273006, 0.204520, 0.501721 }, { 0.271828, 0.209303, 0.504434 }, { 0.270595, 0.214069, 0.507052 }, { 0.269308, 0.218818, 0.509577 }, { 0.267968, 0.223549, 0.512008 }, { 0.266580, 0.228262, 0.514349 }, { 0.265145, 0.232956, 0.516599 }, { 0.263663, 0.237631, 0.518762 }, { 0.262138, 0.242286, 0.520837 }, { 0.260571, 0.246922, 0.522828 }, { 0.258965, 0.251537, 0.524736 }, { 0.257322, 0.256130, 0.526563 }, { 0.255645, 0.260703, 0.528312 }, { 0.253935, 0.265254, 0.529983 }, { 0.252194, 0.269783, 0.531579 }, { 0.250425, 0.274290, 0.533103 }, { 0.248629, 0.278775, 0.534556 }, { 0.246811, 0.283237, 0.535941 }, { 0.244972, 0.287675, 0.537260 }, { 0.243113, 0.292092, 0.538516 }, { 0.241237, 0.296485, 0.539709 }, { 0.239346, 0.300855, 0.540844 }, { 0.237441, 0.305202, 0.541921 }, { 0.235526, 0.309527, 0.542944 }, { 0.233603, 0.313828, 0.543914 }, { 0.231674, 0.318106, 0.544834 }, { 0.229739, 0.322361, 0.545706 }, { 0.227802, 0.326594, 0.546532 }, { 0.225863, 0.330805, 0.547314 }, { 0.223925, 0.334994, 0.548053 }, { 0.221989, 0.339161, 0.548752 }, { 0.220057, 0.343307, 0.549413 }, { 0.218130, 0.347432, 0.550038 }, { 0.216210, 0.351535, 0.550627 }, { 0.214298, 0.355619, 0.551184 }, { 0.212395, 0.359683, 0.551710 }, { 0.210503, 0.363727, 0.552206 }, { 0.208623, 0.367752, 0.552675 }, { 0.206756, 0.371758, 0.553117 }, { 0.204903, 0.375746, 0.553533 }, { 0.203063, 0.379716, 0.553925 }, { 0.201239, 0.383670, 0.554294 }, { 0.199430, 0.387607, 0.554642 }, { 0.197636, 0.391528, 0.554969 }, { 0.195860, 0.395433, 0.555276 }, { 0.194100, 0.399323, 0.555565 }, { 0.192357, 0.403199, 0.555836 }, { 0.190631, 0.407061, 0.556089 }, { 0.188923, 0.410910, 0.556326 }, { 0.187231, 0.414746, 0.556547 }, { 0.185556, 0.418570, 0.556753 }, { 0.183898, 0.422383, 0.556944 }, { 0.182256, 0.426184, 0.557120 }, { 0.180629, 0.429975, 0.557282 }, { 0.179019, 0.433756, 0.557430 }, { 0.177423, 0.437527, 0.557565 }, { 0.175841, 0.441290, 0.557685 }, { 0.174274, 0.445044, 0.557792 }, { 0.172719, 0.448791, 0.557885 }, { 0.171176, 0.452530, 0.557965 }, { 0.169646, 0.456262, 0.558030 }, { 0.168126, 0.459988, 0.558082 }, { 0.166617, 0.463708, 0.558119 }, { 0.165117, 0.467423, 0.558141 }, { 0.163625, 0.471133, 0.558148 }, { 0.162142, 0.474838, 0.558140 }, { 0.160665, 0.478540, 0.558115 }, { 0.159194, 0.482237, 0.558073 }, { 0.157729, 0.485932, 0.558013 }, { 0.156270, 0.489624, 0.557936 }, { 0.154815, 0.493313, 0.557840 }, { 0.153364, 0.497000, 0.557724 }, { 0.151918, 0.500685, 0.557587 }, { 0.150476, 0.504369, 0.557430 }, { 0.149039, 0.508051, 0.557250 }, { 0.147607, 0.511733, 0.557049 }, { 0.146180, 0.515413, 0.556823 }, { 0.144759, 0.519093, 0.556572 }, { 0.143343, 0.522773, 0.556295 }, { 0.141935, 0.526453, 0.555991 }, { 0.140536, 0.530132, 0.555659 }, { 0.139147, 0.533812, 0.555298 }, { 0.137770, 0.537492, 0.554906 }, { 0.136408, 0.541173, 0.554483 }, { 0.135066, 0.544853, 0.554029 }, { 0.133743, 0.548535, 0.553541 }, { 0.132444, 0.552216, 0.553018 }, { 0.131172, 0.555899, 0.552459 }, { 0.129933, 0.559582, 0.551864 }, { 0.128729, 0.563265, 0.551229 }, { 0.127568, 0.566949, 0.550556 }, { 0.126453, 0.570633, 0.549841 }, { 0.125394, 0.574318, 0.549086 }, { 0.124395, 0.578002, 0.548287 }, { 0.123463, 0.581687, 0.547445 }, { 0.122606, 0.585371, 0.546557 }, { 0.121831, 0.589055, 0.545623 }, { 0.121148, 0.592739, 0.544641 }, { 0.120565, 0.596422, 0.543611 }, { 0.120092, 0.600104, 0.542530 }, { 0.119738, 0.603785, 0.541400 }, { 0.119512, 0.607464, 0.540218 }, { 0.119423, 0.611141, 0.538982 }, { 0.119483, 0.614817, 0.537692 }, { 0.119699, 0.618490, 0.536347 }, { 0.120081, 0.622161, 0.534946 }, { 0.120638, 0.625828, 0.533488 }, { 0.121380, 0.629492, 0.531973 }, { 0.122312, 0.633153, 0.530398 }, { 0.123444, 0.636809, 0.528763 }, { 0.124780, 0.640461, 0.527068 }, { 0.126326, 0.644107, 0.525311 }, { 0.128087, 0.647749, 0.523491 }, { 0.130067, 0.651384, 0.521608 }, { 0.132268, 0.655014, 0.519661 }, { 0.134692, 0.658636, 0.517649 }, { 0.137339, 0.662252, 0.515571 }, { 0.140210, 0.665859, 0.513427 }, { 0.143303, 0.669459, 0.511215 }, { 0.146616, 0.673050, 0.508936 }, { 0.150148, 0.676631, 0.506589 }, { 0.153894, 0.680203, 0.504172 }, { 0.157851, 0.683765, 0.501686 }, { 0.162016, 0.687316, 0.499129 }, { 0.166383, 0.690856, 0.496502 }, { 0.170948, 0.694384, 0.493803 }, { 0.175707, 0.697900, 0.491033 }, { 0.180653, 0.701402, 0.488189 }, { 0.185783, 0.704891, 0.485273 }, { 0.191090, 0.708366, 0.482284 }, { 0.196571, 0.711827, 0.479221 }, { 0.202219, 0.715272, 0.476084 }, { 0.208030, 0.718701, 0.472873 }, { 0.214000, 0.722114, 0.469588 }, { 0.220124, 0.725509, 0.466226 }, { 0.226397, 0.728888, 0.462789 }, { 0.232815, 0.732247, 0.459277 }, { 0.239374, 0.735588, 0.455688 }, { 0.246070, 0.738910, 0.452024 }, { 0.252899, 0.742211, 0.448284 }, { 0.259857, 0.745492, 0.444467 }, { 0.266941, 0.748751, 0.440573 }, { 0.274149, 0.751988, 0.436601 }, { 0.281477, 0.755203, 0.432552 }, { 0.288921, 0.758394, 0.428426 }, { 0.296479, 0.761561, 0.424223 }, { 0.304148, 0.764704, 0.419943 }, { 0.311925, 0.767822, 0.415586 }, { 0.319809, 0.770914, 0.411152 }, { 0.327796, 0.773980, 0.406640 }, { 0.335885, 0.777018, 0.402049 }, { 0.344074, 0.780029, 0.397381 }, { 0.352360, 0.783011, 0.392636 }, { 0.360741, 0.785964, 0.387814 }, { 0.369214, 0.788888, 0.382914 }, { 0.377779, 0.791781, 0.377939 }, { 0.386433, 0.794644, 0.372886 }, { 0.395174, 0.797475, 0.367757 }, { 0.404001, 0.800275, 0.362552 }, { 0.412913, 0.803041, 0.357269 }, { 0.421908, 0.805774, 0.351910 }, { 0.430983, 0.808473, 0.346476 }, { 0.440137, 0.811138, 0.340967 }, { 0.449368, 0.813768, 0.335384 }, { 0.458674, 0.816363, 0.329727 }, { 0.468053, 0.818921, 0.323998 }, { 0.477504, 0.821444, 0.318195 }, { 0.487026, 0.823929, 0.312321 }, { 0.496615, 0.826376, 0.306377 }, { 0.506271, 0.828786, 0.300362 }, { 0.515992, 0.831158, 0.294279 }, { 0.525776, 0.833491, 0.288127 }, { 0.535621, 0.835785, 0.281908 }, { 0.545524, 0.838039, 0.275626 }, { 0.555484, 0.840254, 0.269281 }, { 0.565498, 0.842430, 0.262877 }, { 0.575563, 0.844566, 0.256415 }, { 0.585678, 0.846661, 0.249897 }, { 0.595839, 0.848717, 0.243329 }, { 0.606045, 0.850733, 0.236712 }, { 0.616293, 0.852709, 0.230052 }, { 0.626579, 0.854645, 0.223353 }, { 0.636902, 0.856542, 0.216620 }, { 0.647257, 0.858400, 0.209861 }, { 0.657642, 0.860219, 0.203082 }, { 0.668054, 0.861999, 0.196293 }, { 0.678489, 0.863742, 0.189503 }, { 0.688944, 0.865448, 0.182725 }, { 0.699415, 0.867117, 0.175971 }, { 0.709898, 0.868751, 0.169257 }, { 0.720391, 0.870350, 0.162603 }, { 0.730889, 0.871916, 0.156029 }, { 0.741388, 0.873449, 0.149561 }, { 0.751884, 0.874951, 0.143228 }, { 0.762373, 0.876424, 0.137064 }, { 0.772852, 0.877868, 0.131109 }, { 0.783315, 0.879285, 0.125405 }, { 0.793760, 0.880678, 0.120005 }, { 0.804182, 0.882046, 0.114965 }, { 0.814576, 0.883393, 0.110347 }, { 0.824940, 0.884720, 0.106217 }, { 0.835270, 0.886029, 0.102646 }, { 0.845561, 0.887322, 0.099702 }, { 0.855810, 0.888601, 0.097452 }, { 0.866013, 0.889868, 0.095953 }, { 0.876168, 0.891125, 0.095250 }, { 0.886271, 0.892374, 0.095374 }, { 0.896320, 0.893616, 0.096335 }, { 0.906311, 0.894855, 0.098125 }, { 0.916242, 0.896091, 0.100717 }, { 0.926106, 0.897330, 0.104071 }, { 0.935904, 0.898570, 0.108131 }, { 0.945636, 0.899815, 0.112838 }, { 0.955300, 0.901065, 0.118128 }, { 0.964894, 0.902323, 0.123941 }, { 0.974417, 0.903590, 0.130215 }, { 0.983868, 0.904867, 0.136897 }, { 0.993248, 0.906157, 0.143936 } }; void applyColorMap(const cv::Mat & gray, cv::Mat & color, bool reverse, int cmap_id) { if (cmap_id < 13) { cv::applyColorMap(gray, color, cmap_id); } else if (cmap_id == 14) { cv::cvtColor(gray, color, cv::COLOR_GRAY2BGR); } else if (cmap_id == 13) { color = cv::Mat(gray.cols, gray.rows, CV_8UC3); static double lut_r[256] = { -1 }; static double lut_g[256]; static double lut_b[256]; if (lut_r[0] == -1) { for (int i = 0; i < 256; i++) { lut_r[i] = VIRIDIS[i][0] * 255; lut_g[i] = VIRIDIS[i][1] * 255; lut_b[i] = VIRIDIS[i][2] * 255; } } cv::Mat p = gray.reshape(0, 1).clone(); cv::Mat c = color.reshape(0, 1).clone(); if (reverse) { for (int i = 0; i < p.cols; i++) { c.at<cv::Vec3b>(0, i)[0] = (uchar)lut_b[255 - p.at<uchar>(0, i)]; c.at<cv::Vec3b>(0, i)[1] = (uchar)lut_g[255 - p.at<uchar>(0, i)]; c.at<cv::Vec3b>(0, i)[2] = (uchar)lut_r[255 - p.at<uchar>(0, i)]; } } else { for (int i = 0; i < p.cols; i++) { c.at<cv::Vec3b>(0, i)[0] = (uchar)lut_b[p.at<uchar>(0, i)]; c.at<cv::Vec3b>(0, i)[1] = (uchar)lut_g[p.at<uchar>(0, i)]; c.at<cv::Vec3b>(0, i)[2] = (uchar)lut_r[p.at<uchar>(0, i)]; } } color = c.reshape(0, gray.rows); } } std::string round(double dbl, int digs) { std::stringstream sstm; sstm << std::fixed << std::setprecision(digs); sstm << dbl; return sstm.str(); } } }
40.451557
114
0.430948
sxyu
5baf3f3de9b3bed763c296869329f680406d4754
1,515
cpp
C++
main.cpp
nathanmullenax83/wordtab
9cc01f7cb23fd92e40595d00f9438f24cb160de3
[ "Unlicense" ]
null
null
null
main.cpp
nathanmullenax83/wordtab
9cc01f7cb23fd92e40595d00f9438f24cb160de3
[ "Unlicense" ]
null
null
null
main.cpp
nathanmullenax83/wordtab
9cc01f7cb23fd92e40595d00f9438f24cb160de3
[ "Unlicense" ]
null
null
null
#include <iostream> #include <string> #include <map> #include <cctype> #include "dictionary.tpp" #include "sequencer.tpp" #include "formatter.tpp" using std::cin, std::string; int main(int argc, char **argv) { Dictionary dict; Sequencer seq; Formatter console; vector<string> args = console.parse_args(argc, argv); // parse arguments if( args.size() == 6 && args[1]=="markov" ) { size_t prefix_length = console.parse<size_t>(args[2]); size_t suffix_length = console.parse<size_t>(args[3]); size_t model = seq.define_model( prefix_length, suffix_length ); if( args[4]=="text" ) { console.read( dict, seq, cin ); size_t length = console.parse<size_t>( args[5] ); console.print( dict.decode(seq.generate(model,length))); } else if( args[4]=="words") { console.read_chars( dict, seq, cin ); size_t length = console.parse<size_t>( args[5]); console.print( dict.decode(seq.generate(model,length)),80, ""); } } else if( args.size() == 5 && args[1]=="markov" ) { size_t prefix_length = console.parse<size_t>(args[2]); size_t suffix_length = console.parse<size_t>(args[3]); size_t model = seq.define_model( prefix_length, suffix_length ); console.read( dict, seq, cin ); if( args[4]=="table") { seq.dump(model); } } else { cout << "Didn't recognize:\n\n"; console.print(args); } }
31.5625
75
0.586139
nathanmullenax83
5bb5607042dbe003827d313edd7fc434327659be
82
cpp
C++
Adding Your Own Libraries/Functions.cpp
isaKarabocek/Cpp-Tutorials
94bceedae55cd1985f707c136d615e8da0fcc1e4
[ "Apache-2.0" ]
null
null
null
Adding Your Own Libraries/Functions.cpp
isaKarabocek/Cpp-Tutorials
94bceedae55cd1985f707c136d615e8da0fcc1e4
[ "Apache-2.0" ]
null
null
null
Adding Your Own Libraries/Functions.cpp
isaKarabocek/Cpp-Tutorials
94bceedae55cd1985f707c136d615e8da0fcc1e4
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include"Functions.h" int square(int x) { return x*x; }
11.714286
22
0.646341
isaKarabocek
5bb8a5945ba14a7383f73cae0edcf7d71c8776df
10,551
cc
C++
wrappers/7.0.0/vtkImageCursor3DWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/7.0.0/vtkImageCursor3DWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/7.0.0/vtkImageCursor3DWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkImageInPlaceFilterWrap.h" #include "vtkImageCursor3DWrap.h" #include "vtkObjectWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkImageCursor3DWrap::ptpl; VtkImageCursor3DWrap::VtkImageCursor3DWrap() { } VtkImageCursor3DWrap::VtkImageCursor3DWrap(vtkSmartPointer<vtkImageCursor3D> _native) { native = _native; } VtkImageCursor3DWrap::~VtkImageCursor3DWrap() { } void VtkImageCursor3DWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkImageCursor3D").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("ImageCursor3D").ToLocalChecked(), ConstructorGetter); } void VtkImageCursor3DWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkImageCursor3DWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkImageInPlaceFilterWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkImageInPlaceFilterWrap::ptpl)); tpl->SetClassName(Nan::New("VtkImageCursor3DWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "GetCursorPosition", GetCursorPosition); Nan::SetPrototypeMethod(tpl, "getCursorPosition", GetCursorPosition); Nan::SetPrototypeMethod(tpl, "GetCursorRadius", GetCursorRadius); Nan::SetPrototypeMethod(tpl, "getCursorRadius", GetCursorRadius); Nan::SetPrototypeMethod(tpl, "GetCursorValue", GetCursorValue); Nan::SetPrototypeMethod(tpl, "getCursorValue", GetCursorValue); Nan::SetPrototypeMethod(tpl, "IsA", IsA); Nan::SetPrototypeMethod(tpl, "isA", IsA); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetCursorPosition", SetCursorPosition); Nan::SetPrototypeMethod(tpl, "setCursorPosition", SetCursorPosition); Nan::SetPrototypeMethod(tpl, "SetCursorRadius", SetCursorRadius); Nan::SetPrototypeMethod(tpl, "setCursorRadius", SetCursorRadius); Nan::SetPrototypeMethod(tpl, "SetCursorValue", SetCursorValue); Nan::SetPrototypeMethod(tpl, "setCursorValue", SetCursorValue); #ifdef VTK_NODE_PLUS_VTKIMAGECURSOR3DWRAP_INITPTPL VTK_NODE_PLUS_VTKIMAGECURSOR3DWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkImageCursor3DWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkImageCursor3D> native = vtkSmartPointer<vtkImageCursor3D>::New(); VtkImageCursor3DWrap* obj = new VtkImageCursor3DWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkImageCursor3DWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageCursor3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageCursor3DWrap>(info.Holder()); vtkImageCursor3D *native = (vtkImageCursor3D *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetClassName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkImageCursor3DWrap::GetCursorPosition(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageCursor3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageCursor3DWrap>(info.Holder()); vtkImageCursor3D *native = (vtkImageCursor3D *)wrapper->native.GetPointer(); double const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetCursorPosition(); Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 3 * sizeof(double)); Local<v8::Float64Array> at = v8::Float64Array::New(ab, 0, 3); memcpy(ab->GetContents().Data(), r, 3 * sizeof(double)); info.GetReturnValue().Set(at); } void VtkImageCursor3DWrap::GetCursorRadius(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageCursor3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageCursor3DWrap>(info.Holder()); vtkImageCursor3D *native = (vtkImageCursor3D *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetCursorRadius(); info.GetReturnValue().Set(Nan::New(r)); } void VtkImageCursor3DWrap::GetCursorValue(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageCursor3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageCursor3DWrap>(info.Holder()); vtkImageCursor3D *native = (vtkImageCursor3D *)wrapper->native.GetPointer(); double r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetCursorValue(); info.GetReturnValue().Set(Nan::New(r)); } void VtkImageCursor3DWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageCursor3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageCursor3DWrap>(info.Holder()); vtkImageCursor3D *native = (vtkImageCursor3D *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); int r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->IsA( *a0 ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkImageCursor3DWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageCursor3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageCursor3DWrap>(info.Holder()); vtkImageCursor3D *native = (vtkImageCursor3D *)wrapper->native.GetPointer(); vtkImageCursor3D * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkImageCursor3DWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkImageCursor3DWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkImageCursor3DWrap *w = new VtkImageCursor3DWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkImageCursor3DWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageCursor3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageCursor3DWrap>(info.Holder()); vtkImageCursor3D *native = (vtkImageCursor3D *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0])) { VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject()); vtkImageCursor3D * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObject *) a0->native.GetPointer() ); VtkImageCursor3DWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkImageCursor3DWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkImageCursor3DWrap *w = new VtkImageCursor3DWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkImageCursor3DWrap::SetCursorPosition(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageCursor3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageCursor3DWrap>(info.Holder()); vtkImageCursor3D *native = (vtkImageCursor3D *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetCursorPosition( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetCursorPosition( b0 ); return; } else if(info.Length() > 0 && info[0]->IsNumber()) { if(info.Length() > 1 && info[1]->IsNumber()) { if(info.Length() > 2 && info[2]->IsNumber()) { if(info.Length() != 3) { Nan::ThrowError("Too many parameters."); return; } native->SetCursorPosition( info[0]->NumberValue(), info[1]->NumberValue(), info[2]->NumberValue() ); return; } } } Nan::ThrowError("Parameter mismatch"); } void VtkImageCursor3DWrap::SetCursorRadius(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageCursor3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageCursor3DWrap>(info.Holder()); vtkImageCursor3D *native = (vtkImageCursor3D *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetCursorRadius( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkImageCursor3DWrap::SetCursorValue(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageCursor3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageCursor3DWrap>(info.Holder()); vtkImageCursor3D *native = (vtkImageCursor3D *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsNumber()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetCursorValue( info[0]->NumberValue() ); return; } Nan::ThrowError("Parameter mismatch"); }
29.227147
102
0.70799
axkibe
5bb8f76b627d0d5a69010539e9b50349984c8b12
361
cpp
C++
GameEngine/Components/ScoreComponent/ScoreComponent.cpp
Stun3R/Epitech-R-Type
3d6ef3bd5a937f50de996de2395c43c5115f0776
[ "MIT" ]
null
null
null
GameEngine/Components/ScoreComponent/ScoreComponent.cpp
Stun3R/Epitech-R-Type
3d6ef3bd5a937f50de996de2395c43c5115f0776
[ "MIT" ]
null
null
null
GameEngine/Components/ScoreComponent/ScoreComponent.cpp
Stun3R/Epitech-R-Type
3d6ef3bd5a937f50de996de2395c43c5115f0776
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2021 ** R-TYPE ** File description: ** Created by stun3r, */ #include "ScoreComponent.hpp" ScoreComponent::ScoreComponent() : _score(0) { } int ScoreComponent::getScore() const { return _score; } void ScoreComponent::setScore(int mScore) { _score = mScore; } void ScoreComponent::addScore(int mScore) { _score = _score + mScore; }
13.37037
44
0.703601
Stun3R
5bb936ae52a8cc0af1be986419fc22bd73ed6445
349
hpp
C++
include/Application.hpp
sirnuke/haiku-scientific-calculator
36320a37f9201abf5e5364d40419b34045ff1d4e
[ "MIT" ]
null
null
null
include/Application.hpp
sirnuke/haiku-scientific-calculator
36320a37f9201abf5e5364d40419b34045ff1d4e
[ "MIT" ]
null
null
null
include/Application.hpp
sirnuke/haiku-scientific-calculator
36320a37f9201abf5e5364d40419b34045ff1d4e
[ "MIT" ]
null
null
null
// Haiku Scientific Calculator // Bryan DeGrendel (c) 2015 // // See LICENSE for licensing information. #ifndef ___APPLICATION_H___ #define ___APPLICATION_H___ #include <AppKit.h> class Window; class Application : public BApplication { public: Application(); void ReadyToRun(); private: Window *window; }; #endif // ___APPLICATION_H___
13.96
41
0.744986
sirnuke