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
d324cc28afd9df66043c6afaeb549d176758f8d4
749
cpp
C++
source/aufgabe_12.cpp
SVincent/programmiersprachen-aufgabenblatt-3.
4eeeec3973999e0bf57c81e7ae681930e259aa6b
[ "MIT" ]
null
null
null
source/aufgabe_12.cpp
SVincent/programmiersprachen-aufgabenblatt-3.
4eeeec3973999e0bf57c81e7ae681930e259aa6b
[ "MIT" ]
null
null
null
source/aufgabe_12.cpp
SVincent/programmiersprachen-aufgabenblatt-3.
4eeeec3973999e0bf57c81e7ae681930e259aa6b
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_RUNNER #include "catch.hpp" #include <cmath> #include <vector> #include <iostream> #include <algorithm> //std::all_of std::vector<int> v_1 {1,2,3,4,5,6,7,8,9}; std::vector<int> v_2 {9,8,7,6,5,4,3,2,1}; std::vector<int> v_3(9); bool equals_10 (int i) { return i == 10 ; } TEST_CASE ("equals 10 test" "[transform]") { REQUIRE(std::all_of(v_3.begin(), v_3.end(), equals_10)); } int main(int argc, char* argv[]) { //addition lambda function auto addition = [](int x, int y) -> int {return x + y;}; //iteratively uses addition over v_1 and v_2 and stores results in v_3 std::transform (v_1.begin(), v_1.end(), v_2.begin(), v_3.begin(), addition); return Catch::Session().run(argc, argv); }
25.827586
80
0.634179
SVincent
d325d86cd9e250577d210401b46c9d40d31cbe3f
11,994
hpp
C++
Source/AllProjects/GraphicUtils/CIDGraphDev/CIDGraphDev_Pen.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
216
2019-03-09T06:41:28.000Z
2022-02-25T16:27:19.000Z
Source/AllProjects/GraphicUtils/CIDGraphDev/CIDGraphDev_Pen.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
9
2020-09-27T08:00:52.000Z
2021-07-02T14:27:31.000Z
Source/AllProjects/GraphicUtils/CIDGraphDev/CIDGraphDev_Pen.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
29
2019-03-09T10:12:24.000Z
2021-03-03T22:25:29.000Z
// // FILE NAME: CIDGraphDev_Pen.hpp // // AUTHOR: Dean Roddey // // CREATED: 05/24/2002 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements the pen classes. Pens represent GUI objects // that can be used to draw lines of varying widths and styles. It has // attributes such as mix mode, style, end join, etc... The base class is // TGUIPen, which allows code to accept different types of pens // polymorphically, while maintaining simpler interfaces for creating // each type of pen. // // We also define the TPenJanitor class, which will apply a pen to a // graphic device on a scoped basis, which is how they almost always are // applied, returning the original pen upon exit from the scope. It a very // simple class, so we don't bother making it a TObject derivative. // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) // --------------------------------------------------------------------------- // CLASS: TGUIPen // PREFIX: gpen // --------------------------------------------------------------------------- class CIDGRDEVEXP TGUIPen : public TObject { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TGUIPen(const TGUIPen&) = delete; ~TGUIPen(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TGUIPen& operator=(const TGUIPen&) = delete; // ------------------------------------------------------------------- // Public, non-virtual methods // ------------------------------------------------------------------- tCIDLib::TBoolean bSetOnDevice() const; tCIDLib::TBoolean bSetOnDevice ( const tCIDLib::TBoolean bToSet ); tCIDGraphDev::TPenHandle hpenThis() const; tCIDLib::TVoid Unset ( TGraphDrawDev& gdevTarget , tCIDGraphDev::TPenHandle hpenToPutBack ); protected : // ------------------------------------------------------------------- // Hidden constructors // ------------------------------------------------------------------- TGUIPen(); // ------------------------------------------------------------------- // Protected, virtual methods // ------------------------------------------------------------------- virtual tCIDGraphDev::TPenHandle hpenCreatePen() const = 0; private : // ------------------------------------------------------------------- // Private data members // // m_bSetOnDevice // We keep up with whether we are currently set on a device, // so that we can catch errors of double sets or unsets when // we aren't set. // // m_hpenThis // The handle to the pen. We fault it in upon first use. The // derived class creates it, and we store it. // ------------------------------------------------------------------- tCIDLib::TBoolean m_bSetOnDevice; mutable tCIDGraphDev::TPenHandle m_hpenThis; // ------------------------------------------------------------------- // Magic macros // ------------------------------------------------------------------- RTTIDefs(TGUIPen,TObject) NulObject(TGUIPen) }; // --------------------------------------------------------------------------- // CLASS: TCosmeticPen // PREFIX: gpen // --------------------------------------------------------------------------- class CIDGRDEVEXP TCosmeticPen : public TGUIPen { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TCosmeticPen ( const TRGBClr& rgbClr , const tCIDGraphDev::ELineStyles eStyle = tCIDGraphDev::ELineStyles::Solid ); TCosmeticPen(const TCosmeticPen&) = delete; ~TCosmeticPen(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TCosmeticPen& operator=(const TCosmeticPen&) = delete; protected : // ------------------------------------------------------------------- // Protected, inherited methods // ------------------------------------------------------------------- tCIDGraphDev::TPenHandle hpenCreatePen() const override; private : // ------------------------------------------------------------------- // Private data members // // m_eStyle // The line style, i.e. dashed, dotted, etc... // // m_rgbClr // The color used as the line color for this pen. // ------------------------------------------------------------------- tCIDGraphDev::ELineStyles m_eStyle; TRGBClr m_rgbClr; // ------------------------------------------------------------------- // Magic macros // ------------------------------------------------------------------- RTTIDefs(TCosmeticPen,TGUIPen) }; // --------------------------------------------------------------------------- // CLASS: TGeomPen // PREFIX: gpen // --------------------------------------------------------------------------- class CIDGRDEVEXP TGeomPen : public TGUIPen { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TGeomPen ( const TRGBClr& rgbClr , const tCIDLib::TCard4 c4Width ); TGeomPen ( const TRGBClr& rgbClr , const tCIDLib::TCard4 c4Width , const tCIDGraphDev::ELineEnds eEndType , const tCIDGraphDev::ELineJoins eJoinType , const tCIDGraphDev::ELineStyles eStyle ); TGeomPen ( const TRGBClr& rgbClr , const tCIDLib::TCard4 c4Width , const tCIDGraphDev::ELineEnds eEndType , const tCIDGraphDev::ELineJoins eJoinType , const tCIDGraphDev::EPatterns ePattern ); TGeomPen(const TGeomPen&) = delete; ~TGeomPen(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TGeomPen& operator=(const TGeomPen&) = delete; protected : // ------------------------------------------------------------------- // Protected, inherited methods // ------------------------------------------------------------------- tCIDGraphDev::TPenHandle hpenCreatePen() const override; private : // ------------------------------------------------------------------- // Private data members // // m_c4Width // The width in logical units of the line // // m_eEndType // m_eJoinType // Controls the way that lines butt together and how the end // caps are drawn. // // m_eStyle // Controls the style, e.g. dotted, dashed, etc... Note that // the 'alternate' scheme is not legal for geometric pens and // and will cause an error. // // m_rgbClr // The color used as the fill color in this pen. // ------------------------------------------------------------------- tCIDLib::TCard4 m_c4Width; tCIDGraphDev::ELineEnds m_eEndType; tCIDGraphDev::ELineJoins m_eJoinType; tCIDGraphDev::EPatterns m_ePattern; tCIDGraphDev::ELineStyles m_eStyle; TRGBClr m_rgbClr; // ------------------------------------------------------------------- // Magic macros // ------------------------------------------------------------------- RTTIDefs(TGeomPen,TGUIPen) }; // --------------------------------------------------------------------------- // CLASS: TNullPen // PREFIX: gpen // --------------------------------------------------------------------------- class CIDGRDEVEXP TNullPen : public TGUIPen { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TNullPen(); TNullPen(const TNullPen&) = delete; ~TNullPen(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TNullPen& operator=(const TNullPen&) = delete; protected : // ------------------------------------------------------------------- // Protected, inherited methods // ------------------------------------------------------------------- tCIDGraphDev::TPenHandle hpenCreatePen() const override; private : // ------------------------------------------------------------------- // Magic macros // ------------------------------------------------------------------- RTTIDefs(TNullPen,TGUIPen) }; // --------------------------------------------------------------------------- // CLASS: TPenJanitor // PREFIX: jan // --------------------------------------------------------------------------- class CIDGRDEVEXP TPenJanitor { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TPenJanitor() = delete; TPenJanitor ( TGraphDrawDev* const pgdevTarget , TGUIPen* const pgpenToSet ); TPenJanitor(const TPenJanitor&) = delete; ~TPenJanitor(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TPenJanitor& operator=(const TPenJanitor&) = delete; private : // ------------------------------------------------------------------- // Private data members // // m_hpenRestore // The old pen we must restore. // // m_pgdevTarget // The graphics device we put the pen on and must restore the // old pen to. // // m_pgpenSet // The pen that we set and must remove on destruction. // ------------------------------------------------------------------- tCIDGraphDev::TPenHandle m_hpenRestore; TGraphDrawDev* m_pgdevTarget; TGUIPen* m_pgpenSet; }; #pragma CIDLIB_POPPACK
34.073864
89
0.348007
MarkStega
d33848efb19800a4efabce491b8f0fbfae0714d6
1,696
cpp
C++
src/exercises/binary-watch/main.cpp
j-haj/interview-prep
7d9f0ca4c321cf1d2393aea17bcd375119005e5d
[ "MIT" ]
null
null
null
src/exercises/binary-watch/main.cpp
j-haj/interview-prep
7d9f0ca4c321cf1d2393aea17bcd375119005e5d
[ "MIT" ]
null
null
null
src/exercises/binary-watch/main.cpp
j-haj/interview-prep
7d9f0ca4c321cf1d2393aea17bcd375119005e5d
[ "MIT" ]
null
null
null
#include <cctype> #include <iostream> #include <sstream> #include <string> #include <unordered_set> #include <vector> std::size_t to_time(const std::unordered_set<std::size_t>& times) { std::size_t t = 0; for (const auto x : times) t += (1 << x); return t; } std::string construct_time(const std::size_t hour, const std::size_t minute) { std::stringstream ss; ss << hour << ":" << (minute > 9 ? "" : "0") << minute; return ss.str(); } void recursive_searcher(std::size_t n, std::size_t current, std::unordered_set<std::size_t>& hours, std::unordered_set<std::size_t>& minutes, std::unordered_set<std::string>& results) { if (current <= 0) { if ((hours.size() + minutes.size()) != n) return; auto hour = to_time(hours); auto minute = to_time(minutes); if (hour > 12 || minute >= 60) return; results.insert(construct_time(hour, minute)); return; } // outer loop handles hours for (std::size_t i = 0; i < 4; ++i) { // inner loop handles minutes for (std::size_t j = 0; j < 6; ++j) { hours.insert(i); recursive_searcher(n, current - 1, hours, minutes, results); minutes.insert(j); recursive_searcher(n, current - 1, hours, minutes, results); hours.erase(i); recursive_searcher(n, current - 1, hours, minutes, results); minutes.erase(j); } } } int main() { int n = 3; std::unordered_set<std::size_t> hours; std::unordered_set<std::size_t> minutes; std::unordered_set<std::string> results; recursive_searcher(n, n, hours, minutes, results); for (const auto& s : results) std::cout << s << std::endl; return 0; }
30.285714
78
0.607311
j-haj
d34f7f52b6c1b693dfc524ac3bd62468c2b03483
1,506
cpp
C++
gwen/UnitTest/CollapsibleList.cpp
Oipo/GWork
3dd70c090bf8708dd3e7b9cfbcb67163bb7166db
[ "MIT" ]
null
null
null
gwen/UnitTest/CollapsibleList.cpp
Oipo/GWork
3dd70c090bf8708dd3e7b9cfbcb67163bb7166db
[ "MIT" ]
null
null
null
gwen/UnitTest/CollapsibleList.cpp
Oipo/GWork
3dd70c090bf8708dd3e7b9cfbcb67163bb7166db
[ "MIT" ]
null
null
null
#include "Gwen/UnitTest/UnitTest.h" #include "Gwen/Controls/CollapsibleList.h" using namespace Gwen; class CollapsibleList : public GUnit { public: GWEN_CONTROL_INLINE(CollapsibleList, GUnit) { Gwen::Controls::CollapsibleList* pControl = new Gwen::Controls::CollapsibleList(this); pControl->SetSize(100, 200); pControl->SetPos(10, 10); { Gwen::Controls::CollapsibleCategory* cat = pControl->Add("Category One"); cat->Add("Hello"); cat->Add("Two"); cat->Add("Three"); cat->Add("Four"); } { Gwen::Controls::CollapsibleCategory* cat = pControl->Add("Shopping"); cat->Add("Special"); cat->Add("Two Noses"); cat->Add("Orange ears"); cat->Add("Beer"); cat->Add("Three Eyes"); cat->Add("Special"); cat->Add("Two Noses"); cat->Add("Orange ears"); cat->Add("Beer"); cat->Add("Three Eyes"); cat->Add("Special"); cat->Add("Two Noses"); cat->Add("Orange ears"); cat->Add("Beer"); cat->Add("Three Eyes"); } { Gwen::Controls::CollapsibleCategory* cat = pControl->Add("Category One"); cat->Add("Hello"); cat->Add("Two"); cat->Add("Three"); cat->Add("Four"); } } }; DEFINE_UNIT_TEST(CollapsibleList, "CollapsibleList");
28.961538
94
0.505976
Oipo
d35043f8eeccf4d7510ddc2e72560e3ea156e92d
782
cpp
C++
simple/simple.cpp
zyxeeker/detours-cmake
1a20ef565d48e695e191a18f2e53111fbb6f32fc
[ "MIT" ]
11
2019-05-23T02:16:40.000Z
2021-07-07T06:26:05.000Z
simple/simple.cpp
zyxeeker/detours-cmake
1a20ef565d48e695e191a18f2e53111fbb6f32fc
[ "MIT" ]
null
null
null
simple/simple.cpp
zyxeeker/detours-cmake
1a20ef565d48e695e191a18f2e53111fbb6f32fc
[ "MIT" ]
6
2019-05-25T11:37:17.000Z
2021-11-22T09:53:42.000Z
#include <stdio.h> #include <Windows.h> #include <detours.h> static auto real_Beep = ::Beep; //------------------------------------------------------------------------- static BOOL WINAPI my_Beep(DWORD dwFreq, DWORD dwDuration) { printf("Beep(%u, %u)\n", dwFreq, dwDuration); return real_Beep(dwFreq, dwDuration); } //------------------------------------------------------------------------- int main() { DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach(&(PVOID&)real_Beep, my_Beep); auto error = DetourTransactionCommit(); ::Beep(200, 1000); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourDetach(&(PVOID&)real_Beep, my_Beep); error = DetourTransactionCommit(); return 0; }
26.066667
75
0.560102
zyxeeker
d3559f9b694414dbe02d9dcc1f1f7d33d314d150
706
cpp
C++
ConsoleEngine/SceneManager.cpp
jsutas999/ConsoleGameEngine
e2a911ece15cac67b7b7070ead5965b2f194f19f
[ "MIT" ]
null
null
null
ConsoleEngine/SceneManager.cpp
jsutas999/ConsoleGameEngine
e2a911ece15cac67b7b7070ead5965b2f194f19f
[ "MIT" ]
null
null
null
ConsoleEngine/SceneManager.cpp
jsutas999/ConsoleGameEngine
e2a911ece15cac67b7b7070ead5965b2f194f19f
[ "MIT" ]
null
null
null
#include "SceneManager.h" #include "Logger.h" SceneManager* SceneManager::singelton; SceneManager * SceneManager::getInstance() { return singelton; } void SceneManager::LoadNextScene(Scene * scene) { levels.push_back(scene); scene->Initialize(); } void SceneManager::LoadPreviesScene() { Scene* t = levels.back(); delete t; levels.pop_back(); } Scene * SceneManager::getCurrentScene() { return levels.back(); } SceneManager::SceneManager() { if (singelton == NULL) { singelton = this; } } SceneManager::~SceneManager() { while (!levels.empty()) { levels.back()->Deconstruct(); delete levels.back(); levels.pop_back(); } Logger::getInstance()->AddMsg("ALL SCENES CLEARED"); }
14.708333
53
0.694051
jsutas999
d35790d3f9ed6661a504f79739710963a74127d1
4,429
cpp
C++
OpenGeo3D/DlgNewGridLOD.cpp
rocky-iheg-china/OpenGeo3D
fd6a5a523ef40f6d81637fd64a18405aa8a4f164
[ "MIT" ]
1
2020-11-12T06:35:24.000Z
2020-11-12T06:35:24.000Z
OpenGeo3D/DlgNewGridLOD.cpp
rocky-iheg-china/OpenGeo3D
fd6a5a523ef40f6d81637fd64a18405aa8a4f164
[ "MIT" ]
null
null
null
OpenGeo3D/DlgNewGridLOD.cpp
rocky-iheg-china/OpenGeo3D
fd6a5a523ef40f6d81637fd64a18405aa8a4f164
[ "MIT" ]
null
null
null
#include "DlgNewGridLOD.h" #include "Strings.h" DlgNewGridLOD::DlgNewGridLOD(wxWindow* parent, int level) : wxDialog(parent, wxID_ANY, wxEmptyString) { level_ = level; parentSizeX_ = parentSizeY_ = parentSizeZ_ = 1; wxString title = wxString::Format(wxS("%s - %d"), Strings::TitleOfMenuItemAppendGridLOD(), level_); SetTitle(title); wxFlexGridSizer* sizer = new wxFlexGridSizer(4, 4, wxSize(2, 4)); sizer->Add(new wxStaticText(this, wxID_ANY, wxEmptyString)); sizer->Add(new wxStaticText(this, wxID_ANY, Strings::LabelOfX()), wxSizerFlags().CenterHorizontal()); sizer->Add(new wxStaticText(this, wxID_ANY, Strings::LabelOfY()), wxSizerFlags().CenterHorizontal()); sizer->Add(new wxStaticText(this, wxID_ANY, Strings::LabelOfZ()), wxSizerFlags().CenterHorizontal()); ctrlSizeX_ = new wxTextCtrl(this, wxID_ANY); ctrlSizeY_ = new wxTextCtrl(this, wxID_ANY); ctrlSizeZ_ = new wxTextCtrl(this, wxID_ANY); sizer->Add(new wxStaticText(this, wxID_ANY, Strings::LabelOfGridCellSize())); sizer->Add(ctrlSizeX_); sizer->Add(ctrlSizeY_); sizer->Add(ctrlSizeZ_); ctrlScaleX_ = new wxSpinCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS | wxSP_WRAP | wxALIGN_RIGHT, 1, 4, 2); ctrlScaleY_ = new wxSpinCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS | wxSP_WRAP | wxALIGN_RIGHT, 1, 4, 2); ctrlScaleZ_ = new wxSpinCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS | wxSP_WRAP | wxALIGN_RIGHT, 1, 4, 2); sizer->Add(new wxStaticText(this, wxID_ANY, Strings::LabelOfGridCellScale())); sizer->Add(ctrlScaleX_); sizer->Add(ctrlScaleY_); sizer->Add(ctrlScaleZ_); if (level_ == 0) { ctrlScaleX_->SetValue(1); ctrlScaleY_->SetValue(1); ctrlScaleZ_->SetValue(1); ctrlScaleX_->Disable(); ctrlScaleY_->Disable(); ctrlScaleZ_->Disable(); } else { ctrlSizeX_->SetEditable(false); ctrlSizeY_->SetEditable(false); ctrlSizeZ_->SetEditable(false); } ctrlScaleX_->Bind(wxEVT_SPINCTRL, &DlgNewGridLOD::OnSetScaleX, this); ctrlScaleY_->Bind(wxEVT_SPINCTRL, &DlgNewGridLOD::OnSetScaleY, this); ctrlScaleZ_->Bind(wxEVT_SPINCTRL, &DlgNewGridLOD::OnSetScaleZ, this); wxSizer* btnSizer = wxDialog::CreateSeparatedButtonSizer(wxOK | wxCANCEL); Bind(wxEVT_COMMAND_BUTTON_CLICKED, &DlgNewGridLOD::OnButtonOK, this, wxID_OK); wxBoxSizer* mainSizer = new wxBoxSizer(wxVERTICAL); mainSizer->Add(sizer, wxSizerFlags(1).Expand().Border(wxALL, 10)); mainSizer->Add(new wxStaticText(this, wxID_ANY, Strings::TipOfGridLODAndCellScale()), wxSizerFlags().Expand().Border(wxLEFT | wxRIGHT | wxBOTTOM, 10)); mainSizer->Add(btnSizer, wxSizerFlags(0).Expand().Border(wxLEFT | wxRIGHT | wxBOTTOM, 10)); SetSizerAndFit(mainSizer); } DlgNewGridLOD::~DlgNewGridLOD() { } void DlgNewGridLOD::SetParentLevelCellSize(double x, double y, double z) { parentSizeX_ = x; parentSizeY_ = y; parentSizeZ_ = z; int scaleX, scaleY, scaleZ; GetCellScale(scaleX, scaleY, scaleZ); ctrlSizeX_->SetValue(wxString::FromDouble(x / scaleX, 6)); ctrlSizeY_->SetValue(wxString::FromDouble(y / scaleY, 6)); ctrlSizeZ_->SetValue(wxString::FromDouble(z / scaleZ, 6)); } void DlgNewGridLOD::OnSetScaleX(wxSpinEvent& evt) { int scale = ctrlScaleX_->GetValue(); ctrlSizeX_->SetValue(wxString::FromDouble(parentSizeX_ / scale, 6)); } void DlgNewGridLOD::OnSetScaleY(wxSpinEvent& evt) { int scale = ctrlScaleY_->GetValue(); ctrlSizeY_->SetValue(wxString::FromDouble(parentSizeY_ / scale, 6)); } void DlgNewGridLOD::OnSetScaleZ(wxSpinEvent& evt) { int scale = ctrlScaleZ_->GetValue(); ctrlSizeZ_->SetValue(wxString::FromDouble(parentSizeZ_ / scale, 6)); } bool DlgNewGridLOD::GetCellScale(int& x, int& y, int& z) const { x = ctrlScaleX_->GetValue(); y = ctrlScaleY_->GetValue(); z = ctrlScaleZ_->GetValue(); return true; } bool DlgNewGridLOD::GetCellSize(double& x, double& y, double& z) const { if (!ctrlSizeX_->GetValue().ToCDouble(&x)) { return false; } if (!ctrlSizeY_->GetValue().ToCDouble(&y)) { return false; } if (!ctrlSizeZ_->GetValue().ToCDouble(&z)) { return false; } return true; } void DlgNewGridLOD::OnButtonOK(wxCommandEvent& event) { double sizeX, sizeY, sizeZ; if (!GetCellSize(sizeX, sizeY, sizeZ) || sizeX <= ZERO_ERROR || sizeY <= ZERO_ERROR || sizeZ <= ZERO_ERROR) { wxMessageBox(Strings::TipOfInvalidGridCellSize(), Strings::AppName(), wxICON_ERROR); return; } EndModal(wxID_OK); }
39.19469
152
0.743057
rocky-iheg-china
d357d54a83f217e4984eda1b13e0abdf0a63778e
856
cpp
C++
code-forces/632 Div 2/B.cpp
ErickJoestar/competitive-programming
76afb766dbc18e16315559c863fbff19a955a569
[ "MIT" ]
1
2020-04-23T00:35:38.000Z
2020-04-23T00:35:38.000Z
code-forces/632 Div 2/B.cpp
ErickJoestar/competitive-programming
76afb766dbc18e16315559c863fbff19a955a569
[ "MIT" ]
null
null
null
code-forces/632 Div 2/B.cpp
ErickJoestar/competitive-programming
76afb766dbc18e16315559c863fbff19a955a569
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define ENDL '\n' #define pb push_back #define F first #define S second #define deb(u) cout << #u ": " << (u) << endl; #define lli long long #define pii pair<int, int> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t, n; cin >> t; while (t--) { cin >> n; vector<int> a(n), b(n); bool pos = false, neg = false; bool ok = true; for (int i(0); i < n; i++) cin >> a[i]; for (int i(0); i < n; i++) cin >> b[i]; for (int i(0); i < n; i++) { if (a[i] > b[i] && !neg) ok = false; if (a[i] < b[i] && !pos) ok = false; if (a[i] == -1) neg = true; if (a[i] == 1) pos = true; } if (ok) cout << "YES" << ENDL; else cout << "NO" << ENDL; } return 0; }
18.608696
46
0.454439
ErickJoestar
d357e3ce33bc4da1450d9d601de07ae7b1cd9776
2,962
cpp
C++
examples/danmaku/entities/healthbar.cpp
hirusora/abcg
69ffb7a2981c868e08a5df76c502069b1f12d329
[ "MIT" ]
null
null
null
examples/danmaku/entities/healthbar.cpp
hirusora/abcg
69ffb7a2981c868e08a5df76c502069b1f12d329
[ "MIT" ]
null
null
null
examples/danmaku/entities/healthbar.cpp
hirusora/abcg
69ffb7a2981c868e08a5df76c502069b1f12d329
[ "MIT" ]
null
null
null
#include "healthbar.hpp" #include <cppitertools/itertools.hpp> #include <glm/gtx/rotate_vector.hpp> void HealthBar::initializeGL(GLuint program) { terminateGL(); m_program = program; m_rotationLoc = abcg::glGetUniformLocation(m_program, "rotation"); m_scaleLoc = abcg::glGetUniformLocation(m_program, "scale"); m_translationLoc = abcg::glGetUniformLocation(m_program, "translation"); const auto height{0.02f}; m_scale = glm::vec2(1.0f, 1.0f); m_translation = glm::vec2{0.0f, 1.0f - height}; // Create health bar rectangle std::array<glm::vec2, 4> positions{ glm::vec2{-1.0f, height}, glm::vec2{1.0f, height}, glm::vec2{-1.0f, -height}, glm::vec2{1.0f, -height}}; std::array<glm::vec4, 4> colors{m_color, m_color, m_color, m_color}; // Generate VBOs abcg::glGenBuffers(1, &m_vboVertices); abcg::glBindBuffer(GL_ARRAY_BUFFER, m_vboVertices); abcg::glBufferData(GL_ARRAY_BUFFER, sizeof(positions), positions.data(), GL_STATIC_DRAW); abcg::glBindBuffer(GL_ARRAY_BUFFER, 0); abcg::glGenBuffers(1, &m_vboColors); abcg::glBindBuffer(GL_ARRAY_BUFFER, m_vboColors); abcg::glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors.data(), GL_STATIC_DRAW); abcg::glBindBuffer(GL_ARRAY_BUFFER, 0); // Get location of attributes in the program const GLint positionAttribute{ abcg::glGetAttribLocation(m_program, "inPosition")}; const GLint colorAttribute{abcg::glGetAttribLocation(m_program, "inColor")}; // Create VAO abcg::glGenVertexArrays(1, &m_vao); // Bind vertex attributes to current VAO abcg::glBindVertexArray(m_vao); abcg::glEnableVertexAttribArray(positionAttribute); abcg::glBindBuffer(GL_ARRAY_BUFFER, m_vboVertices); abcg::glVertexAttribPointer(positionAttribute, 2, GL_FLOAT, GL_FALSE, 0, nullptr); abcg::glEnableVertexAttribArray(colorAttribute); abcg::glBindBuffer(GL_ARRAY_BUFFER, m_vboColors); abcg::glVertexAttribPointer(colorAttribute, 4, GL_FLOAT, GL_FALSE, 0, nullptr); abcg::glBindBuffer(GL_ARRAY_BUFFER, 0); // End of binding to current VAO abcg::glBindVertexArray(0); } void HealthBar::paintGL(const GameData &gameData) { if (gameData.m_state != State::Playing) return; abcg::glUseProgram(m_program); abcg::glBindVertexArray(m_vao); abcg::glUniform1f(m_rotationLoc, m_rotation); abcg::glUniform2f(m_scaleLoc, m_scale.x, m_scale.y); abcg::glUniform2f(m_translationLoc, m_translation.x, m_translation.y); abcg::glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); abcg::glBindVertexArray(0); abcg::glUseProgram(0); } void HealthBar::terminateGL() { abcg::glDeleteBuffers(1, &m_vboVertices); abcg::glDeleteBuffers(1, &m_vboColors); abcg::glDeleteVertexArrays(1, &m_vao); } void HealthBar::update(Enemy &enemy, const GameData &gameData) { if (gameData.m_state != State::Playing) return; m_scale.x = enemy.m_hp / enemy.m_maxHP; }
32.549451
78
0.714382
hirusora
d35b84519e9343fd8b14072fbea0f30ad4a7f237
1,853
cpp
C++
MergedSortedArray.cpp
sachanakshat/Competitive_Practice
63170d87398bf5bd163febecdcfef8db21c632c7
[ "MIT" ]
null
null
null
MergedSortedArray.cpp
sachanakshat/Competitive_Practice
63170d87398bf5bd163febecdcfef8db21c632c7
[ "MIT" ]
null
null
null
MergedSortedArray.cpp
sachanakshat/Competitive_Practice
63170d87398bf5bd163febecdcfef8db21c632c7
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> #include <chrono> #include<bits/stdc++.h> using namespace std; using namespace std::chrono; class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { int * merged = (int*)malloc(sizeof(int)*(m+n)); int i=0, j=0, k=0; i=m-1, j=n-1, k=m+n-1; while(i>=0 && j>=0) { if(nums1[i] > nums2[j]) nums1[k--] = nums1[i--]; else nums1[k--] = nums2[j--]; } while(i>=0) nums1[k--] = nums1[i--]; while(j>=0) nums1[k--] = nums2[j--]; // while(i<m && j<n) // { // if(nums1[i] < nums2[j]) // merged[k++] = nums1[i++]; // else // merged[k++] = nums2[j++]; // } // while(i<m) // merged[k++] = nums1[i++]; // while(j<n) // merged[k++] = nums2[j++]; //I tried both space separated form and this kind of format. Nothing works! // for(k=0; k<m+n-1; k++) // { // nums1[k] = merged[k]; // } cout<<"["; for(k=0; k<m+n-1; k++) cout<<nums1[k]<<","; cout<<nums1[k]<<"]"; } }; int main() { auto start = high_resolution_clock::now(); // int a[10] = {15,45,32,41,65,12,95,23,25,65}; vector<int> arr{1,1,1,2,2}; // vector<int> arr{2,4,1,5,3}; vector<int> nums1{1,2,3,0,0,0}; vector<int> nums2{2,5,6}; Solution obj; obj.merge(nums1, 3, nums2, 3); auto stop = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start); cout <<"\nExecution time: "<<duration.count() <<" microseconds"<<endl; return 0; }
23.455696
83
0.444145
sachanakshat
d35b9b3d4fcf7e87e05f76f62f83413c0da88874
2,735
cpp
C++
src/ThreadPool.cpp
NivenT/jubilant-funicular
a8f11df59afb4668601ad3359ff28530a59ce5d0
[ "MIT" ]
3
2018-03-19T19:27:05.000Z
2019-09-27T06:41:56.000Z
src/ThreadPool.cpp
NivenT/jubilant-funicular
a8f11df59afb4668601ad3359ff28530a59ce5d0
[ "MIT" ]
null
null
null
src/ThreadPool.cpp
NivenT/jubilant-funicular
a8f11df59afb4668601ad3359ff28530a59ce5d0
[ "MIT" ]
1
2021-02-05T10:29:08.000Z
2021-02-05T10:29:08.000Z
#include "nta/ThreadPool.h" namespace nta { namespace utils { ThreadPool::ThreadPool(size_t num_threads) : m_workers(num_threads), m_kill(false), m_available(num_threads) { m_dispatch_thread = std::thread([this]{ dispatcher(); }); for (size_t id = 0; id < num_threads; id++) { m_workers[id].t = std::thread([this, id]{ worker_func(id); }); } } bool ThreadPool::allWorkFinished() { for (size_t i = 0; i < m_workers.size(); i++) { if (!m_workers[i].free) return false; } return m_funcs.empty(); } size_t ThreadPool::getAvailableWorker() { m_available.wait(); for (size_t i = 0; i < m_workers.size(); i++) { if (m_workers[i].free) { m_workers[i].free = false; return i; } } // Should never get here } void ThreadPool::dispatcher() { /// \todo Can I reorganize to replace with a while(!kill)? while (true) { m_scheduled.wait(); if (m_kill) break; size_t id = getAvailableWorker(); m_empty.m.lock(); m_workers[id].thunk = m_funcs.front(); m_funcs.pop(); m_empty.m.unlock(); m_workers[id].task.signal(); } // Notify workers to die for (auto& w : m_workers) { w.task.signal(); } } void ThreadPool::worker_func(size_t wid) { auto& me = m_workers[wid]; while (true) { me.task.wait(); if (m_kill) break; me.thunk(); me.free = true; m_available.signal(); m_empty.m.lock(); m_empty.cv.notify_all(); m_empty.m.unlock(); } } void ThreadPool::schedule(const Thunk& thunk) { m_empty.m.lock(); m_funcs.push(thunk); m_empty.m.unlock(); m_scheduled.signal(); } void ThreadPool::wait() { std::lock_guard<std::mutex> lg(m_empty.m); m_empty.cv.wait(m_empty.m, [this]{return allWorkFinished();}); } ThreadPool::~ThreadPool() { wait(); m_kill = true; // make sure everyone gets the kill notification m_scheduled.signal(); m_dispatch_thread.join(); for (auto& w : m_workers) { w.t.join(); } m_workers.clear(); } } }
31.436782
91
0.453382
NivenT
d35c14337a803b2cf5a42b8919db93371a132bbe
7,874
cpp
C++
BelaWarpDetect/Library/MatchSyllables.cpp
nathanntg/bela-warp-detect
5d82eeedaab855ab3f31d3b9da3f946043d70b91
[ "MIT" ]
null
null
null
BelaWarpDetect/Library/MatchSyllables.cpp
nathanntg/bela-warp-detect
5d82eeedaab855ab3f31d3b9da3f946043d70b91
[ "MIT" ]
null
null
null
BelaWarpDetect/Library/MatchSyllables.cpp
nathanntg/bela-warp-detect
5d82eeedaab855ab3f31d3b9da3f946043d70b91
[ "MIT" ]
null
null
null
// // MatchSyllables.cpp // BelaWarpDetect // // Created by Nathan Perkins on 1/20/18. // Copyright © 2018 Nathan Perkins. All rights reserved. // #include "MatchSyllables.hpp" #include "LoadAudio.hpp" #include "ManagedMemory.hpp" #include <cmath> MatchSyllables::MatchSyllables(float sample_rate) : _sample_rate(sample_rate), _stft(_window_length, _window_stride, _buffer_length), _idx_lo(_stft.ConvertFrequencyToIndex(_freq_lo, _sample_rate)), _idx_hi(_stft.ConvertFrequencyToIndex(_freq_hi, _sample_rate)), _features(_stft.GetLengthPower()) { _stft.SetWindowHanning(); } MatchSyllables::~MatchSyllables() { } void MatchSyllables::SetCallbackMatch(void (*cb)(size_t, float, int)) { _cb_match = cb; } void MatchSyllables::SetCallbackColumn(void (*cb)(std::vector<float>, std::vector<int>)) { _cb_column = cb; } bool MatchSyllables::_ReadFeatures(std::vector<float> &features) { if (!_stft.ReadPower(features)) { return false; } // log? if (_log_power) { // potentially only calculate log within indices of interest for (auto it = features.begin(); it != features.end(); ++it) { *it = log(1.f + *it); } } return true; } int MatchSyllables::AddSyllable(const std::vector<float> &audio, float threshold, float constrain_length) { // clear STFT _stft.Clear(); // write values if (!_stft.WriteValues(audio)) { return -1; } // zero pad to edge _stft.ZeroPadToEdge(); // template for syllable std::vector<std::vector<float>> tmpl; // read in template std::vector<float> col; while (_ReadFeatures(col)) { tmpl.push_back(std::vector<float>(col.begin() + _idx_lo, col.begin() + _idx_hi)); } // add at end size_t index = _next_index++; _dtms.emplace_back(index, tmpl, threshold, constrain_length * static_cast<float>(tmpl.size())); return static_cast<int>(index); } int MatchSyllables::AddSyllable(const std::string file, float threshold, float constrain_length) { // can not add syllables after initialization if (_initialized) { return -1; } std::vector<float> audio; float sample_rate; // load audio if (!LoadAudio(file, audio, sample_rate)) { return -1; } if (sample_rate != _sample_rate) { return -1; } return AddSyllable(audio, threshold, constrain_length); } int MatchSyllables::AddSpectrogram(const std::vector<std::vector<float>> &spect, float threshold, float constrain_length) { // invalid feature length if ((_idx_hi - _idx_lo) != spect[0].size()) { return -1; } // add at end size_t index = _next_index++; _dtms.emplace_back(index, spect, threshold, constrain_length * static_cast<float>(spect.size())); return static_cast<int>(index); } int MatchSyllables::AddSpectrogram(const float *spect, size_t length, size_t features, float threshold, float constrain_length) { // invalid feature length if ((_idx_hi - _idx_lo) != features) { return -1; } // add at end size_t index = _next_index++; _dtms.emplace_back(index, spect, length, features, threshold, constrain_length * static_cast<float>(length)); return static_cast<int>(index); } int MatchSyllables::AddSpectrogram(const std::string file, float threshold, float constrain_length) { FILE *fh; fh = fopen(file.c_str(), "r"); if (!fh) { return -1; } // obtain file size: fseek(fh, 0, SEEK_END); size_t file_length = ftell(fh); rewind(fh); // calculate size size_t features = _idx_hi - _idx_lo; size_t length = file_length / sizeof(float) / features; size_t total = features * length; if (file_length != total * sizeof(float)) { return -1; } // read file ManagedMemory<float> buffer(total); if (total != fread(static_cast<void *>(buffer.ptr()), sizeof(float), total, fh)) { return -1; } // close file fclose(fh); // add at end size_t index = _next_index++; _dtms.emplace_back(index, buffer.ptr(), length, features, threshold, constrain_length * static_cast<float>(length)); return static_cast<int>(index); } bool MatchSyllables::Initialize() { if (_initialized) { return false; } if (_dtms.empty()) { return false; } // set initialize _initialized = true; // reset Reset(); return true; } void MatchSyllables::Reset() { if (_initialized) { // clear circular buffer _stft.Clear(); // flush matches for (auto it = _dtms.begin(); it != _dtms.end(); ++it) { it->dtm.Reset(); it->last_score = 0.f; } } } bool MatchSyllables::IngestAudio(const float *audio, const unsigned int len, const unsigned int stride) { if (!_initialized) { return false; } // ingest values if (!_stft.WriteValues(audio, len, stride)) { return false; } return true; } bool MatchSyllables::IngestAudio(const std::vector<float> &audio) { if (!_initialized) { return false; } // ingest values if (!_stft.WriteValues(audio)) { return false; } return true; } bool MatchSyllables::MatchOnce(float *score, int *len) { // enough data to read features? if (!_ReadFeatures(_features)) { return false; } for (auto it = _dtms.begin(); it != _dtms.end(); ++it) { struct dtm_out out = it->dtm.IngestFeatureVector(&_features[_idx_lo]); // was last time point below theshold, below length constraint and a local minimum? if (it->last_score >= it->threshold && fabs(static_cast<float>(it->last_len)) < it-> threshold_length && out.normalized_score < it->last_score) { // ALTERNATIVE: //if (out.score >= _dtms[i].threshold && abs((float)out.len_diff) < _dtms[i].length) { //} // call match callback if (_cb_match) { // trigger callback _cb_match(it->index, it->last_score, it->last_len); } // reset DTM? OR reset all? it->dtm.Reset(); // zero out score to prevent double trigger out.normalized_score = 0.f; } // populate arguments if (score) { score[it->index] = out.normalized_score; } if (len) { len[it->index] = out.len_diff; } // store last it->last_score = out.normalized_score; it->last_len = out.len_diff; } // call at end of each column if (_cb_column) { std::vector<float> scores = std::vector<float>(_next_index); std::vector<int> lengths = std::vector<int>(_next_index); for (auto it = _dtms.begin(); it != _dtms.end(); ++it) { scores[it->index] = it->last_score; lengths[it->index] = it->last_len; } _cb_column(scores, lengths); } return true; } void MatchSyllables::PerformMatching() { while (MatchOnce(NULL, NULL)); } bool MatchSyllables::ZeroPadAndFetch(std::vector<float> &scores, std::vector<int> &lengths) { if (!_initialized) { return false; } // zero pad to edge _stft.ZeroPadToEdge(); // perform matching PerformMatching(); // resize returns scores.resize(_next_index); lengths.resize(_next_index); // fill last score and last length for (auto it = _dtms.begin(); it != _dtms.end(); ++it) { scores[it->index] = it->last_score; lengths[it->index] = it->last_len; } return true; }
26.246667
153
0.595631
nathanntg
d35c2f82b8a2b3190b518095af162b8d5b2ce259
1,341
cpp
C++
net/tests/testUri.cpp
frankencode/fluxkit
0436454f0791d8fddf8e0adc383ef7c54080245d
[ "BSD-3-Clause" ]
3
2016-02-10T04:58:32.000Z
2020-09-15T06:39:43.000Z
net/tests/testUri.cpp
frankencode/fluxkit
0436454f0791d8fddf8e0adc383ef7c54080245d
[ "BSD-3-Clause" ]
null
null
null
net/tests/testUri.cpp
frankencode/fluxkit
0436454f0791d8fddf8e0adc383ef7c54080245d
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2007-2015 Frank Mertens. * * Use of this source is governed by a BSD-style license that can be * found in the LICENSE file. * */ #include <flux/testing/TestSuite> #include <flux/stdio> #include <flux/net/Uri> using namespace flux; using namespace flux::testing; using namespace flux::net; class BreakDownUri: public TestCase { void run() { Ref<Uri> uri = Uri::create("http://john@example.com:8000/%7ejohn/123.php?say=hello#part1"); fout("uri->scheme() = \"%%\"\n") << uri->scheme(); fout("uri->userInfo() = \"%%\"\n") << uri->userInfo(); fout("uri->host() = \"%%\"\n") << uri->host(); fout("uri->port() = %%\n") << uri->port(); fout("uri->path() = \"%%\"\n") << uri->path(); fout("uri->query() = \"%%\"\n") << uri->query(); fout("uri->fragment() = \"%%\"\n") << uri->fragment(); FLUX_VERIFY(uri->scheme() == "http"); FLUX_VERIFY(uri->userInfo() == "john"); FLUX_VERIFY(uri->host() == "example.com"); FLUX_VERIFY(uri->port() == 8000); FLUX_VERIFY(uri->path() == "/~john/123.php"); FLUX_VERIFY(uri->query() == "say=hello"); FLUX_VERIFY(uri->fragment() == "part1"); } }; int main(int argc, char** argv) { FLUX_TESTSUITE_ADD(BreakDownUri); return testSuite()->run(argc, argv); }
30.477273
99
0.555556
frankencode
c9655d31784f81f45226d9347f7b0bd63bad7271
1,346
cpp
C++
236.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
236.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
236.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ull = uint64_t; using ll = int64_t; using ld = long double; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<ii> vii; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: bool preorderSearch(vector<TreeNode *>& path, TreeNode *root, TreeNode *node) { path.push_back(root); if (root->val == node->val) return true; if (root->left && preorderSearch(path, root->left, node)) return true; if (root->right && preorderSearch(path, root->right, node)) return true; path.pop_back(); return false; } vector<TreeNode *> findNodePath(TreeNode *root, TreeNode *node) { vector<TreeNode *> path; preorderSearch(path, root, node); return path; } TreeNode* lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) { vector<TreeNode *> p_path = findNodePath(root, p); vector<TreeNode *> q_path = findNodePath(root, q); for (int i = 1; i < min(p_path.size(), q_path.size()); ++i) if (p_path[i] != q_path[i]) return p_path[i - 1]; return p_path[min(p_path.size(), q_path.size()) - 1]; } };
29.26087
83
0.590639
Alex-Amber
c96575a1dd12f0deebc138859705bcf032489318
16,916
cpp
C++
qtdomterm/backend.cpp
lws-team/DomTerm
b5410508e1531ef0ef43bc389cb90132cf87f1ba
[ "BSD-3-Clause" ]
1
2022-02-16T21:33:42.000Z
2022-02-16T21:33:42.000Z
qtdomterm/backend.cpp
lws-team/DomTerm
b5410508e1531ef0ef43bc389cb90132cf87f1ba
[ "BSD-3-Clause" ]
null
null
null
qtdomterm/backend.cpp
lws-team/DomTerm
b5410508e1531ef0ef43bc389cb90132cf87f1ba
[ "BSD-3-Clause" ]
3
2017-10-25T05:45:43.000Z
2022-02-16T21:33:43.000Z
/* This file is part of QtDomTerm. It is derived from Session.cpp, which is part of Konsole. Copyright (C) 2016 by Per Bothner <per@bothner.com> Copyright (C) 2006-2007 by Robert Knight <robertknight@gmail.com> Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de> Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <termios.h> #include <QDir> #include <QUrl> #include <QRegExp> #include <QtDebug> #include <QDesktopServices> #include <QTimer> #include <QFileSystemWatcher> #include "backend.h" #include "Pty.h" #include "kptyprocess.h" #include "browserapplication.h" #include "webview.h" Backend::Backend(QSharedDataPointer<ProcessOptions> processOptions, QObject *parent) : QObject(parent), _processOptions(processOptions), _shellProcess(0), _wantedClose(false) { addDomtermVersion("QtDomTerm"); _shellProcess = new Konsole::Pty(); connect(_shellProcess,SIGNAL(receivedData(const char *,int)),this, SLOT(onReceiveBlock(const char *,int)) ); #if 0 connect( _emulation,SIGNAL(sendData(const char *,int)),_shellProcess, SLOT(sendData(const char *,int)) ); connect( _emulation,SIGNAL(lockPtyRequest(bool)),_shellProcess,SLOT(lockPty(bool)) ); connect( _emulation,SIGNAL(useUtf8Request(bool)),_shellProcess,SLOT(setUtf8Mode(bool)) ); #endif connect( _shellProcess,SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(done(int)) ); } KPtyDevice *Backend::pty() const { return _shellProcess->pty(); } Backend::~Backend() { delete _shellProcess; } /** Encode an arbitrary sequence of bytes as an ASCII string. * This is used because QWebChannel doesn't have a way to transmit * data except as strings or JSON-encoded strings. * We restrict the encoding to ASCII (i.e. codes less then 128) * to avoid excess bytes if the result is UTF-8-encoded. * * The encoding optimizes UTF-8 data, with the following byte values: * 0-3: 1st byte of a 2-byte sequence encoding an arbitrary 8-bit byte. * 4-7: 1st byte of a 2-byte sequence encoding a 2-byte UTF8 Latin-1 character. * 8-13: mean the same ASCII control character * 14: special case for ESC * 15: followed by 2 more bytes encodes a 2-byte UTF8 sequence. * bytes 16-31: 1st byte of a 3-byte sequence encoding a 3-byte UTF8 sequence. * 32-127: mean the same ASCII printable character * The only times we generate extra bytes for a valid UTF8 sequence * if for code-points 0-7, 14-26, 28-31, 0x100-0x7ff. * A byte that is not part of a valid UTF9 sequence may need 2 bytes. * (A character whose encoding is partial, may also need extra bytes.) */ static QString encodeAsAscii(const char * buf, int len) { QString str; const unsigned char *ptr = (const unsigned char *) buf; const unsigned char *end = ptr + len; while (ptr < end) { unsigned char ch = *ptr++; if (ch >= 32 || (ch >= 8 && ch <= 13)) { // Characters in the printable ascii range plus "standard C" // control characters are encoded as-is str.append(QChar(ch)); } else if (ch == 27) { // Special case for ESC, encoded as '\016' str.append(QChar(14)); } else if ((ch & 0xD0) == 0xC0 && end - ptr >= 1 && (ptr[0] & 0xC0) == 0x80) { // Optimization of 2-byte UTF-8 sequence if ((ch & 0x1C) == 0) { // If Latin-1 encode 110000aa,10bbbbbb as 1aa,0BBBBBBB // where BBBBBBB=48+bbbbbb str.append(4 + QChar(ch & 3)); } else { // Else encode 110aaaaa,10bbbbbb as '\017',00AAAAA,0BBBBBBB // where AAAAAA=48+aaaaa;BBBBBBB=48+bbbbbb str.append(QChar(15)); str.append(QChar(48 + (ch & 0x3F))); } str.append(QChar(48 + (*ptr++ & 0x3F))); } else if ((ch & 0xF0) == 0xE0 && end - ptr >= 2 && (ptr[0] & 0xC0) == 0x80 && (ptr[1] & 0xC0) == 0x80) { // Optimization of 3-byte UTF-8 sequence // encode 1110aaaa,10bbbbbb,10cccccc as AAAA,0BBBBBBB,0CCCCCCC // where AAAA=16+aaaa;BBBBBBB=48+bbbbbb;CCCCCCC=48+cccccc str.append(QChar(16 + (ch & 0xF))); str.append(QChar(48 + (*ptr++ & 0x3F))); str.append(QChar(48 + (*ptr++ & 0x3F))); } else { // The fall-back case - use 2 bytes for 1: // encode aabbbbbb as 000000aa,0BBBBBBB, where BBBBBBB=48+bbbbbb str.append(QChar((ch >> 6) & 3)); str.append(QChar(48 + (ch & 0x3F))); } } return str; } void Backend::onReceiveBlock( const char * buf, int len ) { emit writeEncoded(len, encodeAsAscii(buf, len)); } QString Backend::program() const { return _processOptions->program; } QStringList Backend::arguments() const { return _processOptions->arguments; } QStringList Backend::environment() const { return _processOptions->environment; } QString Backend::initialWorkingDirectory() const { return _processOptions->workdir; } void Backend::setInputMode(char mode) { emit writeInputMode((int) mode); } void Backend::setSessionName(const QString& name) { _nameTitle = name; } void Backend::requestHtmlData() { emit writeOperatingSystemControl(102, ""); } void Backend::requestChangeCaret(bool set) { emit writeSetCaretStyle(set ? 1 : 5); } void Backend::loadSessionName() { emit writeOperatingSystemControl(30, _nameTitle); } void Backend::loadStylesheet(const QString& stylesheet, const QString& name) { emit writeOperatingSystemControl(96, toJsonQuoted(name)+","+toJsonQuoted(stylesheet)); } void Backend::reloadStylesheet() { QString name = QString::fromLatin1("preferences"); QString stylesheetFilename = BrowserApplication::instance()->stylesheetFilename(); QString stylesheetExtraRules = BrowserApplication::instance()->stylesheetRules(); QString contents; if (! stylesheetFilename.isEmpty()) { QFile file(stylesheetFilename); if (file.open(QFile::ReadOnly | QFile::Text)) { QTextStream text(&file); contents = text.readAll(); } } contents += stylesheetExtraRules; if (! contents.isEmpty() || _stylesheetLoaded) { loadStylesheet(contents, name); } _stylesheetLoaded = ! contents.isEmpty(); } void Backend::run() { reloadStylesheet(); loadSessionName(); connect(BrowserApplication::instance()->fileSystemWatcher(), &QFileSystemWatcher::fileChanged, this, &Backend::reloadStylesheet); connect(BrowserApplication::instance(), &BrowserApplication::reloadStyleSheet, this, &Backend::reloadStylesheet); _shellProcess->setWorkingDirectory(initialWorkingDirectory()); QStringList env = environment(); env += "TERM=xterm-256color"; env += "COLORTERM=truecolor"; const char *ttyName = pty()->ttyName(); QString domtermVar = "DOMTERM="; domtermVar += domtermVersion(); domtermVar += ";tty="; domtermVar += ttyName; env += domtermVar; QString exec = program(); /* if we do all the checking if this shell exists then we use it ;) * Dont know about the arguments though.. maybe youll need some more checking im not sure * However this works on Arch and FreeBSD now. */ int result = _shellProcess->start(exec, arguments(), env, 0, false); if (result < 0) { qDebug() << "CRASHED! result: " << result; return; } emit started(); } void Backend::setUserTitle(int /*what*/, const QString & /*caption*/) { #if 0 //set to true if anything is actually changed (eg. old _nameTitle != new _nameTitle ) bool modified = false; // (btw: what=0 changes _userTitle and icon, what=1 only icon, what=2 only _userTitle if ((what == 0) || (what == 2)) { _isTitleChanged = true; if ( _userTitle != caption ) { _userTitle = caption; modified = true; } } if ((what == 0) || (what == 1)) { _isTitleChanged = true; if ( _iconText != caption ) { _iconText = caption; modified = true; } } if (what == 11) { QString colorString = caption.section(';',0,0); //qDebug() << __FILE__ << __LINE__ << ": setting background colour to " << colorString; QColor backColor = QColor(colorString); if (backColor.isValid()) { // change color via \033]11;Color\007 if (backColor != _modifiedBackground) { _modifiedBackground = backColor; // bail out here until the code to connect the terminal display // to the changeBackgroundColor() signal has been written // and tested - just so we don't forget to do this. Q_ASSERT( 0 ); emit changeBackgroundColorRequest(backColor); } } } if (what == 30) { _isTitleChanged = true; if ( _nameTitle != caption ) { setTitle(Session::NameRole,caption); return; } } if (what == 31) { QString cwd=caption; cwd=cwd.replace( QRegExp("^~"), QDir::homePath() ); emit openUrlRequest(cwd); } // change icon via \033]32;Icon\007 if (what == 32) { _isTitleChanged = true; if ( _iconName != caption ) { _iconName = caption; modified = true; } } if (what == 50) { emit profileChangeCommandReceived(caption); return; } if ( modified ) { emit titleChanged(); } #endif } QString Backend::userTitle() const { return _userTitle; } bool Backend::isCanonicalMode() { struct ::termios ttmode; pty()->tcGetAttr(&ttmode); return (ttmode.c_lflag & ICANON) != 0; } bool Backend::isEchoingMode() { struct ::termios ttmode; pty()->tcGetAttr(&ttmode); return (ttmode.c_lflag & ECHO) != 0; } bool Backend::sendSignal(int signal) { int result = ::kill(_shellProcess->pid(),signal); if ( result == 0 ) { _shellProcess->waitForFinished(); return true; } else return false; } void Backend::close() { _wantedClose = true; if (!_shellProcess->isRunning() || !sendSignal(SIGHUP)) { // Forced close. QTimer::singleShot(1, this, SIGNAL(finished())); } } void Backend::done(int exitStatus) { QString message; if (!_wantedClose || exitStatus != 0) { if (_shellProcess->exitStatus() == QProcess::NormalExit) { message.sprintf("Session '%s' exited with status %d.", _nameTitle.toUtf8().data(), exitStatus); } else { message.sprintf("Session '%s' crashed.", _nameTitle.toUtf8().data()); } } if ( !_wantedClose && _shellProcess->exitStatus() != QProcess::NormalExit ) message.sprintf("Session '%s' exited unexpectedly.", _nameTitle.toUtf8().data()); else emit finished(); } void Backend::processInputCharacters(const QString &text) { QByteArray data = text.toUtf8(); _shellProcess->sendData(data.constData(), data.length()); } void Backend::reportEvent(const QString &name, const QString &data) { //fprintf(stderr, "reportEvent called name %s data %s canon:%d\n", name.toUtf8().constData(), data.toUtf8().constData(), (int) isCanonicalMode()); fflush(stderr); if (name=="KEY") { int q = data.indexOf('"'); QString kstr = parseSimpleJsonString(data, q, data.length()); int kstr0 = kstr.length() != 1 ? -1 : kstr[0].unicode(); if (isCanonicalMode() && kstr0 != 3 && kstr0 != 4 && kstr0 != 26) { emit writeOperatingSystemControl(isEchoingMode() ? 74 : 73, data); } else processInputCharacters(kstr); } else if (name=="WS") { QStringList words = data.split(QRegExp("\\s+")); setWindowSize(words[0].toInt(), words[1].toInt(), (int) words[2].toFloat(), (int) words[3].toFloat()); } else if (name=="VERSION") { addDomtermVersion(data); } else if (name=="ALINK") { QUrl url = parseSimpleJsonString(data, 0, data.length()); QDesktopServices::openUrl(url); } else if (name=="SESSION-NAME") { setSessionName(parseSimpleJsonString(data, 0, data.length())); } else if (name=="INPUT-MODE-CHANGED") { if (data.length() == 3) webView()->inputModeChanged(data[1].cell()); } else if (name=="GET-HTML") { int q = data.indexOf('"'); QString html = parseSimpleJsonString(data, q, data.length()); //fprintf(stderr, "reporttEvent name %s data %s canon:%d\n", name.toUtf8().constData(), data.toUtf8().constData(), (int) isCanonicalMode()); fflush(stderr); _savedHtml = html; } else { // unknown } } void Backend::log(const QString& message) { if (false) { //message = toJsonQuoted(message); fprintf(stderr, "log called %s\n", message.toUtf8().constData()); fflush(stderr); } } void Backend::setWindowSize(int nrows, int ncols, int /*pixw*/, int /*pixh*/) { _shellProcess->setWindowSize(nrows, ncols); } void Backend::addDomtermVersion(const QString &info) { if (_domtermVersion.isEmpty()) _domtermVersion = info; else { _domtermVersion += ';'; _domtermVersion += info; } } QString Backend::parseSimpleJsonString(QString str, int start, int end) { QString buf; QChar ch0 = 0; int i = start; for (;;) { if (i >= end) return "<error>"; ch0 = str[i++]; if (ch0 == '"' || ch0 == '\'') break; //if (! Character.isWhitespace(ch0)) // return "<error>"; } for (; i < end; ) { QChar ch = str[i++]; if (ch == ch0) { break; } if (ch == '\\') { if (i == end) return "<error>"; ch = str[i++]; switch (ch.unicode()) { case 'b': ch = '\b'; break; case 'f': ch = '\f'; break; case 't': ch = '\t'; break; case 'n': ch = '\n'; break; case 'r': ch = '\r'; break; case '\\': case '\'': case '\"': break; case 'u': if (i + 4 > end) return "<error>"; ch = 0; for (int j = 0; j < 4; j++) { int cd = str[i++].unicode(); int d = cd >= '0' && cd <= '9' ? (char) cd - '0' : cd >= 'a' && cd <= 'f' ? (char) cd - 'a' + 10 : cd >= 'A' && cd <= 'F' ? (char) cd - 'A' + 10 : -1; if (d < 0) return "<error>"; ch = (QChar) ((ch.unicode() << 4) + d); } } } buf += ch; } return buf; } QString Backend::toJsonQuoted(QString str) { QString buf; int len = str.length(); buf += '\"'; for (int i = 0; i < len; i++) { QChar qch = str[i]; int ch = qch.unicode(); if (ch == '\n') buf += "\\n"; else if (ch == '\r') buf += "\\r"; else if (ch == '\t') buf += "\\t"; else if (ch == '\b') buf += "\\b"; else if (ch < ' ' || ch >= 127) { buf += "\\u"; QString hex = QString::number(ch, 16); int slen = hex.length(); if (slen == 1) buf += "000"; else if (slen == 2) buf += "00"; else if (slen == 3) buf += "0"; buf += hex; } else { if (ch == '\"' || ch == '\\') buf += '\\'; buf += qch; } } buf += '\"'; return buf; } ProcessOptions* Backend::processOptions() { return _processOptions.data(); }
30.756364
170
0.569106
lws-team
c965cc0e17a7575f5e481174b1d7c35cbbabfa47
6,945
hpp
C++
test/gaussian_filter/gaussian_filter_test_suite.hpp
aeolusbot-tommyliu/fl
a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02
[ "MIT" ]
17
2015-07-03T06:53:05.000Z
2021-05-15T20:55:12.000Z
test/gaussian_filter/gaussian_filter_test_suite.hpp
aeolusbot-tommyliu/fl
a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02
[ "MIT" ]
3
2015-02-20T12:48:17.000Z
2019-12-18T08:45:13.000Z
test/gaussian_filter/gaussian_filter_test_suite.hpp
aeolusbot-tommyliu/fl
a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02
[ "MIT" ]
15
2015-02-20T11:34:14.000Z
2021-05-15T20:55:13.000Z
/* * This is part of the fl library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2015 Max Planck Society, * Autonomous Motion Department, * Institute for Intelligent Systems * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file gaussian_filter_test_suite.hpp * \date June 2015 * \author Jan Issac (jan.issac@gmail.com) */ #pragma once #include <gtest/gtest.h> #include "../typecast.hpp" #include <Eigen/Dense> #include <cmath> #include <iostream> #include <fl/util/profiling.hpp> #include <fl/util/math/linear_algebra.hpp> #include <fl/filter/filter_interface.hpp> #include <fl/model/transition/linear_transition.hpp> #include <fl/model/sensor/linear_gaussian_sensor.hpp> #include <fl/model/sensor/linear_decorrelated_gaussian_sensor.hpp> template <typename TestType> class GaussianFilterTest : public ::testing::Test { protected: typedef typename TestType::Parameter Configuration; enum: signed int { StateDim = Configuration::StateDim, InputDim = Configuration::InputDim, ObsrvDim = Configuration::ObsrvDim, StateSize = fl::TestSize<StateDim, TestType>::Value, InputSize = fl::TestSize<InputDim, TestType>::Value, ObsrvSize = fl::TestSize<ObsrvDim, TestType>::Value, FilterIterations = Configuration::Iterations }; enum ModelSetup { Random, Identity }; typedef Eigen::Matrix<fl::Real, StateSize, 1> State; typedef Eigen::Matrix<fl::Real, InputSize, 1> Input; typedef Eigen::Matrix<fl::Real, ObsrvSize, 1> Obsrv; GaussianFilterTest() : predict_steps_(30), predict_update_steps_(FilterIterations) { } struct ModelFactory { // Sizes will be 1 of the test type is static and it will fall back to // -1 for dynamic size tests. This may be used as an expansion factor // using fl::ExpandSizes<MySize, Sizes>::Value. If Sizes is equal to 1 // (Static) then ExpandSizes will simply multiply MySizes by 1 and // everything is defined statically. On the other hand, if the Sizes // is -1, fl::ExpandSizes will fallback to -1 indicating that the test // type is dynamic. enum : signed int { Sizes = fl::TestSize<1, TestType>::Value }; typedef fl::LinearTransition< State, Input > LinearTransition; typedef fl::LinearGaussianSensor< Obsrv, State > LinearObservation; LinearTransition create_linear_state_model() { auto model = LinearTransition(StateDim, InputDim); auto A = model.create_dynamics_matrix(); auto Q = model.create_noise_matrix(); switch (setup) { case Random: A.setRandom(); Q.setRandom(); break; case Identity: A.setIdentity(); Q.setIdentity(); break; } model.dynamics_matrix(A); model.noise_matrix(Q); return model; } LinearObservation create_sensor() { auto model = LinearObservation(ObsrvDim, StateDim); auto H = model.create_sensor_matrix(); auto R = model.create_noise_matrix(); switch (setup) { case Random: H.setRandom(); R.setRandom(); break; case Identity: H.setIdentity(); R.setIdentity(); break; } model.sensor_matrix(H); model.noise_matrix(R); return model; } ModelSetup setup; }; typedef typename Configuration::template FilterDefinition< ModelFactory >::Type Filter; Filter create_filter(ModelSetup setup = Identity) const { return Configuration::create_filter(ModelFactory{setup}); } typename fl::Traits<Filter>::Input zero_input(const Filter& filter) { return fl::Traits<Filter>::Input::Zero( filter.transition().input_dimension()); } typename fl::Traits<Filter>::Obsrv rand_obsrv(const Filter& filter) { return fl::Traits<Filter>::Obsrv::Random( filter.sensor().obsrv_dimension()); } protected: int predict_steps_; int predict_update_steps_; }; TYPED_TEST_CASE_P(GaussianFilterTest); //TYPED_TEST_P(GaussianFilterTest, init_predict) //{ // typedef TestFixture This; // auto filter = This::create_filter(); // auto belief = filter.create_belief(); // EXPECT_TRUE(belief.mean().isZero()); // EXPECT_TRUE(belief.covariance().isIdentity()); // std::cout << filter.name() << std::endl; // std::cout << filter.description() << std::endl; // filter.predict(belief, This::zero_input(), belief); // auto Q = filter.transition().noise_covariance(); // EXPECT_TRUE(belief.mean().isZero()); // EXPECT_TRUE(fl::are_similar(belief.covariance(), 2. * Q)); //} TYPED_TEST_P(GaussianFilterTest, predict_then_update) { typedef TestFixture This; auto filter = This::create_filter(This::Identity); PV(filter.name()); auto belief = filter.create_belief(); EXPECT_TRUE(belief.covariance().ldlt().isPositive()); for (int i = 0; i < This::predict_update_steps_; ++i) { PF(i); // PV(belief.mean()); // PV(belief.covariance()); filter.predict(belief, This::zero_input(filter), belief); // if (!belief.covariance().ldlt().isPositive()) // { // PV(belief.mean()); // PV(belief.covariance()); // } ASSERT_TRUE(belief.covariance().ldlt().isPositive()); filter.update(belief, This::rand_obsrv(filter), belief); // if (!belief.covariance().ldlt().isPositive()) // { // PV(belief.mean()); // PV(belief.covariance()); // } ASSERT_TRUE(belief.covariance().ldlt().isPositive()); } PV(belief.mean()); PV(belief.covariance()); } TYPED_TEST_P(GaussianFilterTest, predict_loop) { typedef TestFixture This; auto filter = This::create_filter(This::Identity); auto belief = filter.create_belief(); EXPECT_TRUE(belief.covariance().ldlt().isPositive()); for (int i = 0; i < This::predict_steps_; ++i) { filter.predict(belief, This::zero_input(filter), belief); } EXPECT_TRUE(belief.covariance().ldlt().isPositive()); } REGISTER_TYPED_TEST_CASE_P(GaussianFilterTest, //init_predict, predict_then_update, predict_loop);
26.207547
79
0.600144
aeolusbot-tommyliu
c966fa1aaf20bbd198cf9580ac433d7e613ddb30
2,330
cpp
C++
src/main.cpp
gmoehler/ledpoi
d1294b172b7069f62119c310399d80500402d882
[ "MIT" ]
null
null
null
src/main.cpp
gmoehler/ledpoi
d1294b172b7069f62119c310399d80500402d882
[ "MIT" ]
75
2017-05-28T23:39:33.000Z
2019-05-09T06:18:44.000Z
src/main.cpp
gmoehler/ledpoi
d1294b172b7069f62119c310399d80500402d882
[ "MIT" ]
null
null
null
#include "ledpoi.h" #include "ledpoi_utils.h" #include "soc/soc.h" #include "soc/rtc_cntl_reg.h" #include "dispatch/dispatchTask.h" #include "display/displayTask.h" #include "player/playerTask.h" #include "uart/uartTask.h" #include "ui/button.h" // #include "selftest/selftestTask.h" // unless defined differently below this is the default log level #define DEFAULT_LOG_LEVEL ESP_LOG_INFO void logging_setup(){ esp_log_level_set(MAIN_T, ESP_LOG_DEBUG); // main program task esp_log_level_set(DSPCH_T, ESP_LOG_DEBUG); // dispatch task esp_log_level_set(DISP_T, DEFAULT_LOG_LEVEL); // display task esp_log_level_set(UART_T, DEFAULT_LOG_LEVEL); // uart task esp_log_level_set(PLAY_T, ESP_LOG_DEBUG); // play task esp_log_level_set(SPIF_T, DEFAULT_LOG_LEVEL); // spiffs task // esp_log_level_set(SELF_T, DEFAULT_LOG_LEVEL); // selftest task esp_log_level_set(BUT_T, DEFAULT_LOG_LEVEL); // button task esp_log_level_set(EXPL_T, DEFAULT_LOG_LEVEL); // example task esp_log_level_set(SPIFF_A, DEFAULT_LOG_LEVEL); // play spiffs action esp_log_level_set(NOACT_A, DEFAULT_LOG_LEVEL); // void ("no") action esp_log_level_set(ANIM_A, DEFAULT_LOG_LEVEL); // animation action esp_log_level_set(TIMER, DEFAULT_LOG_LEVEL); // timer util esp_log_level_set(POICMD, DEFAULT_LOG_LEVEL); // poi command util esp_log_level_set(INTS, DEFAULT_LOG_LEVEL); // interaction state esp_log_level_set(SPIF_U, DEFAULT_LOG_LEVEL); // spiffs utils // esp_log_level_set(SELF_H, DEFAULT_LOG_LEVEL); // selftest helper } void disableBrownOut() { WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); } void setup() { disableBrownOut(); // uart_setup(); // first one because this sets serial baudrate logging_setup(); // setup tasks and queues with sizes button_setup(); dispatch_setup(10); display_setup(10); player_setup(5); // start tasks with prios button_start(8); dispatch_start(7); player_start(4); display_start(9); sendRawToDispatch({ANIMATE, RAINBOW, 1, 5, 0, 100}, MAIN_T); sendRawToDispatch({SHOW_RGB, 0, 0, 0, 2, 254}, MAIN_T); // black // waiting for button interaction } // everything works with tasks, we dont need the loop... void loop(){ delay(100000); // snow white sleep }
32.361111
74
0.718455
gmoehler
c96a0c35aa9c48b3dd71e1ee452a550c06f988bc
8,426
hpp
C++
include/nodes/internal/Export.hpp
clouddon/nodeeditor
fda93f9b75012d420e087a6b1aae50061ba47947
[ "BSD-3-Clause" ]
null
null
null
include/nodes/internal/Export.hpp
clouddon/nodeeditor
fda93f9b75012d420e087a6b1aae50061ba47947
[ "BSD-3-Clause" ]
null
null
null
include/nodes/internal/Export.hpp
clouddon/nodeeditor
fda93f9b75012d420e087a6b1aae50061ba47947
[ "BSD-3-Clause" ]
null
null
null
#pragma once #if \ defined (__CYGWIN__) || \ defined (__CYGWIN32__) # define NODE_EDITOR_PLATFORM "Cygwin" # define NODE_EDITOR_PLATFORM_CYGWIN # define NODE_EDITOR_PLATFORM_UNIX # define NODE_EDITOR_PLATFORM_WINDOWS #elif \ defined (_WIN16) || \ defined (_WIN32) || \ defined (_WIN64) || \ defined (__WIN32__) || \ defined (__TOS_WIN__) || \ defined (__WINDOWS__) # define NODE_EDITOR_PLATFORM "Windows" # define NODE_EDITOR_PLATFORM_WINDOWS #elif \ defined (macintosh) || \ defined (Macintosh) || \ defined (__TOS_MACOS__) || \ (defined (__APPLE__) && defined (__MACH__)) # define NODE_EDITOR_PLATFORM "Mac" # define NODE_EDITOR_PLATFORM_MAC # define NODE_EDITOR_PLATFORM_UNIX #elif \ defined (linux) || \ defined (__linux) || \ defined (__linux__) || \ defined (__TOS_LINUX__) # define NODE_EDITOR_PLATFORM "Linux" # define NODE_EDITOR_PLATFORM_LINUX # define NODE_EDITOR_PLATFORM_UNIX #elif \ defined (__FreeBSD__) || \ defined (__OpenBSD__) || \ defined (__NetBSD__) || \ defined (__bsdi__) || \ defined (__DragonFly__) # define NODE_EDITOR_PLATFORM "BSD" # define NODE_EDITOR_PLATFORM_BSD # define NODE_EDITOR_PLATFORM_UNIX #elif \ defined (sun) || \ defined (__sun) # define NODE_EDITOR_PLATFORM "Solaris" # define NODE_EDITOR_PLATFORM_SOLARIS # define NODE_EDITOR_PLATFORM_UNIX #elif \ defined (_AIX) || \ defined (__TOS_AIX__) # define NODE_EDITOR_PLATFORM "AIX" # define NODE_EDITOR_PLATFORM_AIX # define NODE_EDITOR_PLATFORM_UNIX #elif \ defined (hpux) || \ defined (_hpux) || \ defined (__hpux) # define NODE_EDITOR_PLATFORM "HPUX" # define NODE_EDITOR_PLATFORM_HPUX # define NODE_EDITOR_PLATFORM_UNIX #elif \ defined (__QNX__) # define NODE_EDITOR_PLATFORM "QNX" # define NODE_EDITOR_PLATFORM_QNX # define NODE_EDITOR_PLATFORM_UNIX #elif \ defined (unix) || \ defined (__unix) || \ defined (__unix__) # define NODE_EDITOR_PLATFORM "Unix" # define NODE_EDITOR_PLATFORM_UNIX #endif #ifndef NODE_EDITOR_PLATFORM # error "Current platform is not supported." #endif #if \ defined (__MINGW32__) || \ defined (__MINGW64__) # define NODE_EDITOR_COMPILER "MinGW" # define NODE_EDITOR_COMPILER_MINGW #elif \ defined (__GNUC__) # define NODE_EDITOR_COMPILER "GNU" # define NODE_EDITOR_COMPILER_GNU # define NODE_EDITOR_COMPILER_GNU_VERSION_MAJOR __GNUC__ # define NODE_EDITOR_COMPILER_GNU_VERSION_MINOR __GNUC_MINOR__ # define NODE_EDITOR_COMPILER_GNU_VERSION_PATCH __GNUC_PATCHLEVEL__ #elif \ defined (__clang__) # define NODE_EDITOR_COMPILER "Clang" # define NODE_EDITOR_COMPILER_CLANG #elif \ defined (_MSC_VER) # define NODE_EDITOR_COMPILER "Microsoft Visual C++" # define NODE_EDITOR_COMPILER_MICROSOFT #elif \ defined (__BORLANDC__) # define NODE_EDITOR_COMPILER "Borland C++ Builder" # define NODE_EDITOR_COMPILER_BORLAND #elif \ defined (__CODEGEARC__) # define NODE_EDITOR_COMPILER "CodeGear C++ Builder" # define NODE_EDITOR_COMPILER_CODEGEAR #elif \ defined (__INTEL_COMPILER) || \ defined (__ICL) # define NODE_EDITOR_COMPILER "Intel C++" # define NODE_EDITOR_COMPILER_INTEL #elif \ defined (__xlC__) || \ defined (__IBMCPP__) # define NODE_EDITOR_COMPILER "IBM XL C++" # define NODE_EDITOR_COMPILER_IBM #elif \ defined (__HP_aCC) # define NODE_EDITOR_COMPILER "HP aC++" # define NODE_EDITOR_COMPILER_HP #elif \ defined (__WATCOMC__) # define NODE_EDITOR_COMPILER "Watcom C++" # define NODE_EDITOR_COMPILER_WATCOM #endif #ifndef NODE_EDITOR_COMPILER # error "Current compiler is not supported." #endif #ifdef NODE_EDITOR_PLATFORM_WINDOWS # define NODE_EDITOR_EXPORT __declspec(dllexport) # define NODE_EDITOR_IMPORT __declspec(dllimport) # define NODE_EDITOR_LOCAL #elif \ NODE_EDITOR_COMPILER_GNU_VERSION_MAJOR >= 4 || \ defined (NODE_EDITOR_COMPILER_CLANG) # define NODE_EDITOR_EXPORT __attribute__((visibility("default"))) # define NODE_EDITOR_IMPORT __attribute__((visibility("default"))) # define NODE_EDITOR_LOCAL __attribute__((visibility("hidden"))) #else # define NODE_EDITOR_EXPORT # define NODE_EDITOR_IMPORT # define NODE_EDITOR_LOCAL #endif #ifdef __cplusplus # define NODE_EDITOR_DEMANGLED extern "C" #else # define NODE_EDITOR_DEMANGLED #endif #if defined (NODE_EDITOR_SHARED) && !defined (NODE_EDITOR_STATIC) # ifdef NODE_EDITOR_EXPORTS # define NODE_EDITOR_PUBLIC NODE_EDITOR_EXPORT # else # define NODE_EDITOR_PUBLIC NODE_EDITOR_IMPORT # endif # define NODE_EDITOR_PRIVATE NODE_EDITOR_LOCAL #elif !defined (NODE_EDITOR_SHARED) && defined (NODE_EDITOR_STATIC) # define NODE_EDITOR_PUBLIC # define NODE_EDITOR_PRIVATE #elif defined (NODE_EDITOR_SHARED) && defined (NODE_EDITOR_STATIC) # ifdef NODE_EDITOR_EXPORTS # error "Cannot build as shared and static simultaneously." # else # error "Cannot link against shared and static simultaneously." # endif #else # ifdef NODE_EDITOR_EXPORTS # error "Choose whether to build as shared or static." # else # error "Choose whether to link against shared or static." # endif #endif #include <functional> #include <memory> #include <utility> #include <QtGlobal> #include <QString> #include <QtCore/QUuid> #include <QtCore/QVariant> namespace Qt { namespace detail { #if (!defined(_MSC_VER) && (__cplusplus < 201300)) || \ ( defined(_MSC_VER) && (_MSC_VER < 1800)) //_MSC_VER == 1800 is Visual Studio 2013, which is already somewhat C++14 compilant, // and it has make_unique in it's standard library implementation template<typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } #else template<typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) { return std::make_unique<T>(std::forward<Args>(args)...); } #endif } } namespace std { #if (QT_VERSION < QT_VERSION_CHECK(5, 14, 0)) template<> struct hash<QString> { inline std::size_t operator()(QString const &s) const { return qHash(s); } }; #endif template<> struct hash<QUuid> { inline std::size_t operator()(QUuid const& uid) const { return qHash(uid); } }; }
36.008547
87
0.545099
clouddon
c9771ac657028531efbc20c9b837eebb10ef5c52
26,073
cpp
C++
YorozuyaGSLib/source/CMonsterSkillDetail.cpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
YorozuyaGSLib/source/CMonsterSkillDetail.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
YorozuyaGSLib/source/CMonsterSkillDetail.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
#include <CMonsterSkillDetail.hpp> #include <common/ATFCore.hpp> START_ATF_NAMESPACE namespace Detail { Info::CMonsterSkillctor_CMonsterSkill2_ptr CMonsterSkillctor_CMonsterSkill2_next(nullptr); Info::CMonsterSkillctor_CMonsterSkill2_clbk CMonsterSkillctor_CMonsterSkill2_user(nullptr); Info::CMonsterSkillCopy4_ptr CMonsterSkillCopy4_next(nullptr); Info::CMonsterSkillCopy4_clbk CMonsterSkillCopy4_user(nullptr); Info::CMonsterSkillGetAccumulationCount6_ptr CMonsterSkillGetAccumulationCount6_next(nullptr); Info::CMonsterSkillGetAccumulationCount6_clbk CMonsterSkillGetAccumulationCount6_user(nullptr); Info::CMonsterSkillGetAttackDist8_ptr CMonsterSkillGetAttackDist8_next(nullptr); Info::CMonsterSkillGetAttackDist8_clbk CMonsterSkillGetAttackDist8_user(nullptr); Info::CMonsterSkillGetBeforeTime10_ptr CMonsterSkillGetBeforeTime10_next(nullptr); Info::CMonsterSkillGetBeforeTime10_clbk CMonsterSkillGetBeforeTime10_user(nullptr); Info::CMonsterSkillGetDstCaseType12_ptr CMonsterSkillGetDstCaseType12_next(nullptr); Info::CMonsterSkillGetDstCaseType12_clbk CMonsterSkillGetDstCaseType12_user(nullptr); Info::CMonsterSkillGetElement14_ptr CMonsterSkillGetElement14_next(nullptr); Info::CMonsterSkillGetElement14_clbk CMonsterSkillGetElement14_user(nullptr); Info::CMonsterSkillGetExceptMotive16_ptr CMonsterSkillGetExceptMotive16_next(nullptr); Info::CMonsterSkillGetExceptMotive16_clbk CMonsterSkillGetExceptMotive16_user(nullptr); Info::CMonsterSkillGetExceptMotiveValue18_ptr CMonsterSkillGetExceptMotiveValue18_next(nullptr); Info::CMonsterSkillGetExceptMotiveValue18_clbk CMonsterSkillGetExceptMotiveValue18_user(nullptr); Info::CMonsterSkillGetFld20_ptr CMonsterSkillGetFld20_next(nullptr); Info::CMonsterSkillGetFld20_clbk CMonsterSkillGetFld20_user(nullptr); Info::CMonsterSkillGetMaxDmg22_ptr CMonsterSkillGetMaxDmg22_next(nullptr); Info::CMonsterSkillGetMaxDmg22_clbk CMonsterSkillGetMaxDmg22_user(nullptr); Info::CMonsterSkillGetMaxProb24_ptr CMonsterSkillGetMaxProb24_next(nullptr); Info::CMonsterSkillGetMaxProb24_clbk CMonsterSkillGetMaxProb24_user(nullptr); Info::CMonsterSkillGetMinDmg26_ptr CMonsterSkillGetMinDmg26_next(nullptr); Info::CMonsterSkillGetMinDmg26_clbk CMonsterSkillGetMinDmg26_user(nullptr); Info::CMonsterSkillGetMinProb28_ptr CMonsterSkillGetMinProb28_next(nullptr); Info::CMonsterSkillGetMinProb28_clbk CMonsterSkillGetMinProb28_user(nullptr); Info::CMonsterSkillGetMotive30_ptr CMonsterSkillGetMotive30_next(nullptr); Info::CMonsterSkillGetMotive30_clbk CMonsterSkillGetMotive30_user(nullptr); Info::CMonsterSkillGetMotiveValue32_ptr CMonsterSkillGetMotiveValue32_next(nullptr); Info::CMonsterSkillGetMotiveValue32_clbk CMonsterSkillGetMotiveValue32_user(nullptr); Info::CMonsterSkillGetNextActionDelayTime34_ptr CMonsterSkillGetNextActionDelayTime34_next(nullptr); Info::CMonsterSkillGetNextActionDelayTime34_clbk CMonsterSkillGetNextActionDelayTime34_user(nullptr); Info::CMonsterSkillGetSFLv36_ptr CMonsterSkillGetSFLv36_next(nullptr); Info::CMonsterSkillGetSFLv36_clbk CMonsterSkillGetSFLv36_user(nullptr); Info::CMonsterSkillGetSPActionProbability38_ptr CMonsterSkillGetSPActionProbability38_next(nullptr); Info::CMonsterSkillGetSPActionProbability38_clbk CMonsterSkillGetSPActionProbability38_user(nullptr); Info::CMonsterSkillGetSPLimitCount40_ptr CMonsterSkillGetSPLimitCount40_next(nullptr); Info::CMonsterSkillGetSPLimitCount40_clbk CMonsterSkillGetSPLimitCount40_user(nullptr); Info::CMonsterSkillGetType42_ptr CMonsterSkillGetType42_next(nullptr); Info::CMonsterSkillGetType42_clbk CMonsterSkillGetType42_user(nullptr); Info::CMonsterSkillGetUseType44_ptr CMonsterSkillGetUseType44_next(nullptr); Info::CMonsterSkillGetUseType44_clbk CMonsterSkillGetUseType44_user(nullptr); Info::CMonsterSkillInit46_ptr CMonsterSkillInit46_next(nullptr); Info::CMonsterSkillInit46_clbk CMonsterSkillInit46_user(nullptr); Info::CMonsterSkillIsAttackAble48_ptr CMonsterSkillIsAttackAble48_next(nullptr); Info::CMonsterSkillIsAttackAble48_clbk CMonsterSkillIsAttackAble48_user(nullptr); Info::CMonsterSkillIsExit50_ptr CMonsterSkillIsExit50_next(nullptr); Info::CMonsterSkillIsExit50_clbk CMonsterSkillIsExit50_user(nullptr); Info::CMonsterSkillNextPass52_ptr CMonsterSkillNextPass52_next(nullptr); Info::CMonsterSkillNextPass52_clbk CMonsterSkillNextPass52_user(nullptr); Info::CMonsterSkillSetAccumulationCountAdd54_ptr CMonsterSkillSetAccumulationCountAdd54_next(nullptr); Info::CMonsterSkillSetAccumulationCountAdd54_clbk CMonsterSkillSetAccumulationCountAdd54_user(nullptr); Info::CMonsterSkillSetForce56_ptr CMonsterSkillSetForce56_next(nullptr); Info::CMonsterSkillSetForce56_clbk CMonsterSkillSetForce56_user(nullptr); Info::CMonsterSkillSetGen58_ptr CMonsterSkillSetGen58_next(nullptr); Info::CMonsterSkillSetGen58_clbk CMonsterSkillSetGen58_user(nullptr); Info::CMonsterSkillSetSkill60_ptr CMonsterSkillSetSkill60_next(nullptr); Info::CMonsterSkillSetSkill60_clbk CMonsterSkillSetSkill60_user(nullptr); Info::CMonsterSkillUse62_ptr CMonsterSkillUse62_next(nullptr); Info::CMonsterSkillUse62_clbk CMonsterSkillUse62_user(nullptr); Info::CMonsterSkilldtor_CMonsterSkill64_ptr CMonsterSkilldtor_CMonsterSkill64_next(nullptr); Info::CMonsterSkilldtor_CMonsterSkill64_clbk CMonsterSkilldtor_CMonsterSkill64_user(nullptr); void CMonsterSkillctor_CMonsterSkill2_wrapper(struct CMonsterSkill* _this) { CMonsterSkillctor_CMonsterSkill2_user(_this, CMonsterSkillctor_CMonsterSkill2_next); }; void CMonsterSkillCopy4_wrapper(struct CMonsterSkill* _this, struct CMonsterSkill* Cls) { CMonsterSkillCopy4_user(_this, Cls, CMonsterSkillCopy4_next); }; int CMonsterSkillGetAccumulationCount6_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetAccumulationCount6_user(_this, CMonsterSkillGetAccumulationCount6_next); }; float CMonsterSkillGetAttackDist8_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetAttackDist8_user(_this, CMonsterSkillGetAttackDist8_next); }; unsigned int CMonsterSkillGetBeforeTime10_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetBeforeTime10_user(_this, CMonsterSkillGetBeforeTime10_next); }; int CMonsterSkillGetDstCaseType12_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetDstCaseType12_user(_this, CMonsterSkillGetDstCaseType12_next); }; int CMonsterSkillGetElement14_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetElement14_user(_this, CMonsterSkillGetElement14_next); }; int CMonsterSkillGetExceptMotive16_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetExceptMotive16_user(_this, CMonsterSkillGetExceptMotive16_next); }; int CMonsterSkillGetExceptMotiveValue18_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetExceptMotiveValue18_user(_this, CMonsterSkillGetExceptMotiveValue18_next); }; struct _base_fld* CMonsterSkillGetFld20_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetFld20_user(_this, CMonsterSkillGetFld20_next); }; int CMonsterSkillGetMaxDmg22_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetMaxDmg22_user(_this, CMonsterSkillGetMaxDmg22_next); }; int CMonsterSkillGetMaxProb24_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetMaxProb24_user(_this, CMonsterSkillGetMaxProb24_next); }; int CMonsterSkillGetMinDmg26_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetMinDmg26_user(_this, CMonsterSkillGetMinDmg26_next); }; int CMonsterSkillGetMinProb28_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetMinProb28_user(_this, CMonsterSkillGetMinProb28_next); }; int CMonsterSkillGetMotive30_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetMotive30_user(_this, CMonsterSkillGetMotive30_next); }; int CMonsterSkillGetMotiveValue32_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetMotiveValue32_user(_this, CMonsterSkillGetMotiveValue32_next); }; unsigned int CMonsterSkillGetNextActionDelayTime34_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetNextActionDelayTime34_user(_this, CMonsterSkillGetNextActionDelayTime34_next); }; int CMonsterSkillGetSFLv36_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetSFLv36_user(_this, CMonsterSkillGetSFLv36_next); }; int CMonsterSkillGetSPActionProbability38_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetSPActionProbability38_user(_this, CMonsterSkillGetSPActionProbability38_next); }; int CMonsterSkillGetSPLimitCount40_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetSPLimitCount40_user(_this, CMonsterSkillGetSPLimitCount40_next); }; int CMonsterSkillGetType42_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetType42_user(_this, CMonsterSkillGetType42_next); }; int CMonsterSkillGetUseType44_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillGetUseType44_user(_this, CMonsterSkillGetUseType44_next); }; void CMonsterSkillInit46_wrapper(struct CMonsterSkill* _this) { CMonsterSkillInit46_user(_this, CMonsterSkillInit46_next); }; bool CMonsterSkillIsAttackAble48_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillIsAttackAble48_user(_this, CMonsterSkillIsAttackAble48_next); }; bool CMonsterSkillIsExit50_wrapper(struct CMonsterSkill* _this) { return CMonsterSkillIsExit50_user(_this, CMonsterSkillIsExit50_next); }; void CMonsterSkillNextPass52_wrapper(struct CMonsterSkill* _this) { CMonsterSkillNextPass52_user(_this, CMonsterSkillNextPass52_next); }; void CMonsterSkillSetAccumulationCountAdd54_wrapper(struct CMonsterSkill* _this, int nTempAccumulationCount) { CMonsterSkillSetAccumulationCountAdd54_user(_this, nTempAccumulationCount, CMonsterSkillSetAccumulationCountAdd54_next); }; int CMonsterSkillSetForce56_wrapper(struct CMonsterSkill* _this, struct _monster_fld* pMonsterFld, struct _monster_sp_fld* pSPCont, int nSFLv, struct _force_fld* pForceFld, unsigned int dwDelayTime, float fAttackDist, unsigned int dwCastDelay, int nMotive, int nMotiveValue, int skillDestType) { return CMonsterSkillSetForce56_user(_this, pMonsterFld, pSPCont, nSFLv, pForceFld, dwDelayTime, fAttackDist, dwCastDelay, nMotive, nMotiveValue, skillDestType, CMonsterSkillSetForce56_next); }; int CMonsterSkillSetGen58_wrapper(struct CMonsterSkill* _this, struct _monster_fld* pMonsterFld, int nSFLv, unsigned int dwDelayTime, float fAttackDist, unsigned int dwCastDelay) { return CMonsterSkillSetGen58_user(_this, pMonsterFld, nSFLv, dwDelayTime, fAttackDist, dwCastDelay, CMonsterSkillSetGen58_next); }; int CMonsterSkillSetSkill60_wrapper(struct CMonsterSkill* _this, struct _monster_fld* pMonsterFld, struct _monster_sp_fld* pSPCont, int nSFLv, int nEffectType, struct _skill_fld* pSkillFld, unsigned int dwDelayTime, float fAttackDist, unsigned int dwCastDelay, int nMotive, int nMotiveValue, int skillDestType) { return CMonsterSkillSetSkill60_user(_this, pMonsterFld, pSPCont, nSFLv, nEffectType, pSkillFld, dwDelayTime, fAttackDist, dwCastDelay, nMotive, nMotiveValue, skillDestType, CMonsterSkillSetSkill60_next); }; int CMonsterSkillUse62_wrapper(struct CMonsterSkill* _this, unsigned int dwUsedTime, bool bCount) { return CMonsterSkillUse62_user(_this, dwUsedTime, bCount, CMonsterSkillUse62_next); }; void CMonsterSkilldtor_CMonsterSkill64_wrapper(struct CMonsterSkill* _this) { CMonsterSkilldtor_CMonsterSkill64_user(_this, CMonsterSkilldtor_CMonsterSkill64_next); }; ::std::array<hook_record, 32> CMonsterSkill_functions = { _hook_record { (LPVOID)0x14014b5a0L, (LPVOID *)&CMonsterSkillctor_CMonsterSkill2_user, (LPVOID *)&CMonsterSkillctor_CMonsterSkill2_next, (LPVOID)cast_pointer_function(CMonsterSkillctor_CMonsterSkill2_wrapper), (LPVOID)cast_pointer_function((void(CMonsterSkill::*)())&CMonsterSkill::ctor_CMonsterSkill) }, _hook_record { (LPVOID)0x140156140L, (LPVOID *)&CMonsterSkillCopy4_user, (LPVOID *)&CMonsterSkillCopy4_next, (LPVOID)cast_pointer_function(CMonsterSkillCopy4_wrapper), (LPVOID)cast_pointer_function((void(CMonsterSkill::*)(struct CMonsterSkill*))&CMonsterSkill::Copy) }, _hook_record { (LPVOID)0x140155730L, (LPVOID *)&CMonsterSkillGetAccumulationCount6_user, (LPVOID *)&CMonsterSkillGetAccumulationCount6_next, (LPVOID)cast_pointer_function(CMonsterSkillGetAccumulationCount6_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)())&CMonsterSkill::GetAccumulationCount) }, _hook_record { (LPVOID)0x1401556f0L, (LPVOID *)&CMonsterSkillGetAttackDist8_user, (LPVOID *)&CMonsterSkillGetAttackDist8_next, (LPVOID)cast_pointer_function(CMonsterSkillGetAttackDist8_wrapper), (LPVOID)cast_pointer_function((float(CMonsterSkill::*)())&CMonsterSkill::GetAttackDist) }, _hook_record { (LPVOID)0x140155870L, (LPVOID *)&CMonsterSkillGetBeforeTime10_user, (LPVOID *)&CMonsterSkillGetBeforeTime10_next, (LPVOID)cast_pointer_function(CMonsterSkillGetBeforeTime10_wrapper), (LPVOID)cast_pointer_function((unsigned int(CMonsterSkill::*)())&CMonsterSkill::GetBeforeTime) }, _hook_record { (LPVOID)0x140155850L, (LPVOID *)&CMonsterSkillGetDstCaseType12_user, (LPVOID *)&CMonsterSkillGetDstCaseType12_next, (LPVOID)cast_pointer_function(CMonsterSkillGetDstCaseType12_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)())&CMonsterSkill::GetDstCaseType) }, _hook_record { (LPVOID)0x14014f7e0L, (LPVOID *)&CMonsterSkillGetElement14_user, (LPVOID *)&CMonsterSkillGetElement14_next, (LPVOID)cast_pointer_function(CMonsterSkillGetElement14_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)())&CMonsterSkill::GetElement) }, _hook_record { (LPVOID)0x1401557d0L, (LPVOID *)&CMonsterSkillGetExceptMotive16_user, (LPVOID *)&CMonsterSkillGetExceptMotive16_next, (LPVOID)cast_pointer_function(CMonsterSkillGetExceptMotive16_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)())&CMonsterSkill::GetExceptMotive) }, _hook_record { (LPVOID)0x140155810L, (LPVOID *)&CMonsterSkillGetExceptMotiveValue18_user, (LPVOID *)&CMonsterSkillGetExceptMotiveValue18_next, (LPVOID)cast_pointer_function(CMonsterSkillGetExceptMotiveValue18_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)())&CMonsterSkill::GetExceptMotiveValue) }, _hook_record { (LPVOID)0x14014dd80L, (LPVOID *)&CMonsterSkillGetFld20_user, (LPVOID *)&CMonsterSkillGetFld20_next, (LPVOID)cast_pointer_function(CMonsterSkillGetFld20_wrapper), (LPVOID)cast_pointer_function((struct _base_fld*(CMonsterSkill::*)())&CMonsterSkill::GetFld) }, _hook_record { (LPVOID)0x14014f820L, (LPVOID *)&CMonsterSkillGetMaxDmg22_user, (LPVOID *)&CMonsterSkillGetMaxDmg22_next, (LPVOID)cast_pointer_function(CMonsterSkillGetMaxDmg22_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)())&CMonsterSkill::GetMaxDmg) }, _hook_record { (LPVOID)0x14014f860L, (LPVOID *)&CMonsterSkillGetMaxProb24_user, (LPVOID *)&CMonsterSkillGetMaxProb24_next, (LPVOID)cast_pointer_function(CMonsterSkillGetMaxProb24_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)())&CMonsterSkill::GetMaxProb) }, _hook_record { (LPVOID)0x14014f800L, (LPVOID *)&CMonsterSkillGetMinDmg26_user, (LPVOID *)&CMonsterSkillGetMinDmg26_next, (LPVOID)cast_pointer_function(CMonsterSkillGetMinDmg26_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)())&CMonsterSkill::GetMinDmg) }, _hook_record { (LPVOID)0x14014f840L, (LPVOID *)&CMonsterSkillGetMinProb28_user, (LPVOID *)&CMonsterSkillGetMinProb28_next, (LPVOID)cast_pointer_function(CMonsterSkillGetMinProb28_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)())&CMonsterSkill::GetMinProb) }, _hook_record { (LPVOID)0x1401556b0L, (LPVOID *)&CMonsterSkillGetMotive30_user, (LPVOID *)&CMonsterSkillGetMotive30_next, (LPVOID)cast_pointer_function(CMonsterSkillGetMotive30_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)())&CMonsterSkill::GetMotive) }, _hook_record { (LPVOID)0x140155690L, (LPVOID *)&CMonsterSkillGetMotiveValue32_user, (LPVOID *)&CMonsterSkillGetMotiveValue32_next, (LPVOID)cast_pointer_function(CMonsterSkillGetMotiveValue32_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)())&CMonsterSkill::GetMotiveValue) }, _hook_record { (LPVOID)0x14014c2e0L, (LPVOID *)&CMonsterSkillGetNextActionDelayTime34_user, (LPVOID *)&CMonsterSkillGetNextActionDelayTime34_next, (LPVOID)cast_pointer_function(CMonsterSkillGetNextActionDelayTime34_wrapper), (LPVOID)cast_pointer_function((unsigned int(CMonsterSkill::*)())&CMonsterSkill::GetNextActionDelayTime) }, _hook_record { (LPVOID)0x14014dda0L, (LPVOID *)&CMonsterSkillGetSFLv36_user, (LPVOID *)&CMonsterSkillGetSFLv36_next, (LPVOID)cast_pointer_function(CMonsterSkillGetSFLv36_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)())&CMonsterSkill::GetSFLv) }, _hook_record { (LPVOID)0x140155790L, (LPVOID *)&CMonsterSkillGetSPActionProbability38_user, (LPVOID *)&CMonsterSkillGetSPActionProbability38_next, (LPVOID)cast_pointer_function(CMonsterSkillGetSPActionProbability38_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)())&CMonsterSkill::GetSPActionProbability) }, _hook_record { (LPVOID)0x140155750L, (LPVOID *)&CMonsterSkillGetSPLimitCount40_user, (LPVOID *)&CMonsterSkillGetSPLimitCount40_next, (LPVOID)cast_pointer_function(CMonsterSkillGetSPLimitCount40_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)())&CMonsterSkill::GetSPLimitCount) }, _hook_record { (LPVOID)0x14014c2c0L, (LPVOID *)&CMonsterSkillGetType42_user, (LPVOID *)&CMonsterSkillGetType42_next, (LPVOID)cast_pointer_function(CMonsterSkillGetType42_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)())&CMonsterSkill::GetType) }, _hook_record { (LPVOID)0x14014dd60L, (LPVOID *)&CMonsterSkillGetUseType44_user, (LPVOID *)&CMonsterSkillGetUseType44_next, (LPVOID)cast_pointer_function(CMonsterSkillGetUseType44_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)())&CMonsterSkill::GetUseType) }, _hook_record { (LPVOID)0x140156030L, (LPVOID *)&CMonsterSkillInit46_user, (LPVOID *)&CMonsterSkillInit46_next, (LPVOID)cast_pointer_function(CMonsterSkillInit46_wrapper), (LPVOID)cast_pointer_function((void(CMonsterSkill::*)())&CMonsterSkill::Init) }, _hook_record { (LPVOID)0x14014f880L, (LPVOID *)&CMonsterSkillIsAttackAble48_user, (LPVOID *)&CMonsterSkillIsAttackAble48_next, (LPVOID)cast_pointer_function(CMonsterSkillIsAttackAble48_wrapper), (LPVOID)cast_pointer_function((bool(CMonsterSkill::*)())&CMonsterSkill::IsAttackAble) }, _hook_record { (LPVOID)0x1401556d0L, (LPVOID *)&CMonsterSkillIsExit50_user, (LPVOID *)&CMonsterSkillIsExit50_next, (LPVOID)cast_pointer_function(CMonsterSkillIsExit50_wrapper), (LPVOID)cast_pointer_function((bool(CMonsterSkill::*)())&CMonsterSkill::IsExit) }, _hook_record { (LPVOID)0x140156980L, (LPVOID *)&CMonsterSkillNextPass52_user, (LPVOID *)&CMonsterSkillNextPass52_next, (LPVOID)cast_pointer_function(CMonsterSkillNextPass52_wrapper), (LPVOID)cast_pointer_function((void(CMonsterSkill::*)())&CMonsterSkill::NextPass) }, _hook_record { (LPVOID)0x140161500L, (LPVOID *)&CMonsterSkillSetAccumulationCountAdd54_user, (LPVOID *)&CMonsterSkillSetAccumulationCountAdd54_next, (LPVOID)cast_pointer_function(CMonsterSkillSetAccumulationCountAdd54_wrapper), (LPVOID)cast_pointer_function((void(CMonsterSkill::*)(int))&CMonsterSkill::SetAccumulationCountAdd) }, _hook_record { (LPVOID)0x140156700L, (LPVOID *)&CMonsterSkillSetForce56_user, (LPVOID *)&CMonsterSkillSetForce56_next, (LPVOID)cast_pointer_function(CMonsterSkillSetForce56_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)(struct _monster_fld*, struct _monster_sp_fld*, int, struct _force_fld*, unsigned int, float, unsigned int, int, int, int))&CMonsterSkill::SetForce) }, _hook_record { (LPVOID)0x1401562b0L, (LPVOID *)&CMonsterSkillSetGen58_user, (LPVOID *)&CMonsterSkillSetGen58_next, (LPVOID)cast_pointer_function(CMonsterSkillSetGen58_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)(struct _monster_fld*, int, unsigned int, float, unsigned int))&CMonsterSkill::SetGen) }, _hook_record { (LPVOID)0x1401564a0L, (LPVOID *)&CMonsterSkillSetSkill60_user, (LPVOID *)&CMonsterSkillSetSkill60_next, (LPVOID)cast_pointer_function(CMonsterSkillSetSkill60_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)(struct _monster_fld*, struct _monster_sp_fld*, int, int, struct _skill_fld*, unsigned int, float, unsigned int, int, int, int))&CMonsterSkill::SetSkill) }, _hook_record { (LPVOID)0x140156920L, (LPVOID *)&CMonsterSkillUse62_user, (LPVOID *)&CMonsterSkillUse62_next, (LPVOID)cast_pointer_function(CMonsterSkillUse62_wrapper), (LPVOID)cast_pointer_function((int(CMonsterSkill::*)(unsigned int, bool))&CMonsterSkill::Use) }, _hook_record { (LPVOID)0x14014b5f0L, (LPVOID *)&CMonsterSkilldtor_CMonsterSkill64_user, (LPVOID *)&CMonsterSkilldtor_CMonsterSkill64_next, (LPVOID)cast_pointer_function(CMonsterSkilldtor_CMonsterSkill64_wrapper), (LPVOID)cast_pointer_function((void(CMonsterSkill::*)())&CMonsterSkill::dtor_CMonsterSkill) }, }; }; // end namespace Detail END_ATF_NAMESPACE
55.950644
318
0.68615
lemkova
c97a10c7980e29f436ccf6c1cea11fe5c29318fb
7,167
cpp
C++
code/editors/xrECoreLite/EditObject.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
7
2018-03-27T12:36:07.000Z
2020-06-26T11:31:52.000Z
code/editors/xrECoreLite/EditObject.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
2
2018-05-26T23:17:14.000Z
2019-04-14T18:33:27.000Z
code/editors/xrECoreLite/EditObject.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
3
2020-06-26T11:41:44.000Z
2021-09-29T19:35:04.000Z
//---------------------------------------------------- // file: EditObject.cpp //---------------------------------------------------- #include "files_list.hpp" #pragma hdrstop #if defined (_MAX_EXPORT) #include "..\..\..\xrEngine\fmesh.h" #else #include "..\..\xrEngine\fmesh.h" #endif #include "EditObject.h" #include "EditMesh.h" #ifdef _EDITOR #include "motion.h" #include "bone.h" #include "ImageManager.h" #endif // mimimal bounding box size float g_MinBoxSize = 0.05f; #ifdef _EDITOR void CSurface::CreateImageData() { VERIFY(0 == m_ImageData); m_ImageData = xr_new<SSimpleImage>(); m_ImageData->name = m_Texture; m_ImageData->layers.push_back(U32Vec()); ImageLib.LoadTextureData(*m_ImageData->name, m_ImageData->layers.back(), m_ImageData->w, m_ImageData->h); } void CSurface::RemoveImageData() { xr_delete(m_ImageData); } #endif CEditableObject::CEditableObject(const char* name) { m_LibName = name; m_objectFlags.zero(); m_ObjectVersion = 0; #ifdef _EDITOR vs_SkeletonGeom = 0; #endif m_Box.invalidate(); m_LoadState.zero(); m_ActiveSMotion = 0; t_vPosition.set(0.f, 0.f, 0.f); t_vScale.set(1.f, 1.f, 1.f); t_vRotate.set(0.f, 0.f, 0.f); a_vPosition.set(0.f, 0.f, 0.f); a_vRotate.set(0.f, 0.f, 0.f); bOnModified = false; m_RefCount = 0; m_LODShader = 0; m_CreateName = "unknown"; m_CreateTime = 0; m_ModifName = "unknown"; m_ModifTime = 0; } CEditableObject::~CEditableObject() { ClearGeometry(); } //---------------------------------------------------- void CEditableObject::VerifyMeshNames() { int idx = 0; string1024 nm, pref; for (auto m_def = m_Meshes.begin(); m_def != m_Meshes.end(); ++m_def) { strcpy(pref, (*m_def)->m_Name.size() ? (*m_def)->m_Name.c_str() : "mesh"); _Trim(pref); strcpy(nm, pref); while (FindMeshByName(nm, *m_def)) sprintf(nm, "%s%2d", pref, ++idx); (*m_def)->SetName(nm); } } bool CEditableObject::ContainsMesh(const CEditableMesh* m) { VERIFY(m); for (auto m_def = m_Meshes.begin(); m_def != m_Meshes.end(); ++m_def) if (m == (*m_def)) return true; return false; } CEditableMesh* CEditableObject::FindMeshByName(const char* name, CEditableMesh* Ignore) { for (auto m = m_Meshes.begin(); m != m_Meshes.end(); ++m) if ((Ignore != (*m)) && (stricmp((*m)->Name().c_str(), name) == 0)) return (*m); return 0; } void CEditableObject::ClearGeometry() { #ifdef _EDITOR OnDeviceDestroy(); #endif if (!m_Meshes.empty()) for (auto m = m_Meshes.begin(); m != m_Meshes.end(); ++m) xr_delete(*m); if (!m_Surfaces.empty()) for (auto s_it = m_Surfaces.begin(); s_it != m_Surfaces.end(); ++s_it) xr_delete(*s_it); m_Meshes.clear(); m_Surfaces.clear(); #ifdef _EDITOR // bones for (BoneIt b_it = m_Bones.begin(); b_it != m_Bones.end(); b_it++)xr_delete(*b_it); m_Bones.clear(); // skeletal motions for (SMotionIt s_it = m_SMotions.begin(); s_it != m_SMotions.end(); s_it++) xr_delete(*s_it); m_SMotions.clear(); #endif m_ActiveSMotion = 0; } int CEditableObject::GetFaceCount() { int cnt = 0; for (auto m = m_Meshes.begin(); m != m_Meshes.end(); ++m) cnt += (*m)->GetFaceCount(); return cnt; } int CEditableObject::GetSurfFaceCount(const char* surf_name) { int cnt = 0; CSurface* surf = FindSurfaceByName(surf_name); for (auto m = m_Meshes.begin(); m != m_Meshes.end(); ++m) cnt += (*m)->GetSurfFaceCount(surf); return cnt; } int CEditableObject::GetVertexCount() { int cnt = 0; for (auto m = m_Meshes.begin(); m != m_Meshes.end(); ++m) cnt += (*m)->GetVertexCount(); return cnt; } void CEditableObject::UpdateBox() { VERIFY(!m_Meshes.empty()); auto m = m_Meshes.begin(); m_Box.invalidate(); for (; m != m_Meshes.end(); ++m) { Fbox meshbox; (*m)->GetBox(meshbox); for (int i = 0; i < 8; ++i) { Fvector pt; meshbox.getpoint(i, pt); m_Box.modify(pt); } } } //---------------------------------------------------- void CEditableObject::RemoveMesh(CEditableMesh* mesh) { auto m_it = std::find(m_Meshes.begin(), m_Meshes.end(), mesh); VERIFY(m_it != m_Meshes.end()); m_Meshes.erase(m_it); xr_delete(mesh); } void CEditableObject::TranslateToWorld(const Fmatrix& parent) { for (auto m = m_Meshes.begin(); m != m_Meshes.end(); ++m) (*m)->Transform(parent); #ifdef _EDITOR OnDeviceDestroy(); #endif UpdateBox(); } CSurface* CEditableObject::FindSurfaceByName(const char* surf_name, int* s_id) { for (auto s_it = m_Surfaces.begin(); s_it != m_Surfaces.end(); ++s_it) if (stricmp((*s_it)->_Name(), surf_name) == 0) { if (s_id) *s_id = s_it - m_Surfaces.begin(); return *s_it; } return 0; } LPCSTR CEditableObject::GenerateSurfaceName(const char* base_name) { static string1024 nm; strcpy(nm, base_name); if (FindSurfaceByName(nm)) { DWORD idx = 0; do { sprintf(nm, "%s_%d", base_name, idx); ++idx; } while (FindSurfaceByName(nm)); } return nm; } bool CEditableObject::VerifyBoneParts() { std::vector<u8> b_use(BoneCount(), 0); for (auto bp_it = m_BoneParts.begin(); bp_it != m_BoneParts.end(); ++bp_it) for (int i = 0; i<int(bp_it->bones.size()); ++i) { int idx = FindBoneByNameIdx(bp_it->bones[i].c_str()); if (idx == -1) { bp_it->bones.erase(bp_it->bones.begin() + i); --i; } else { b_use[idx]++; } } for (auto u_it = b_use.begin(); u_it != b_use.end(); ++u_it) if (*u_it != 1) return false; return true; } void CEditableObject::PrepareOGFDesc(ogf_desc& desc) { string512 tmp; desc.source_file = m_LibName.c_str(); desc.create_name = m_CreateName.c_str(); desc.create_time = m_CreateTime; desc.modif_name = m_ModifName.c_str(); desc.modif_time = m_ModifTime; desc.build_name = xr_strconcat(tmp, "\\\\", Core.CompName, "\\", Core.UserName); ctime(&desc.build_time); } void CEditableObject::SetVersionToCurrent(BOOL bCreate, BOOL bModif) { string512 tmp; if (bCreate) { m_CreateName = xr_strconcat(tmp, "\\\\", Core.CompName, "\\", Core.UserName); m_CreateTime = time(NULL); } if (bModif) { m_ModifName = xr_strconcat(tmp, "\\\\", Core.CompName, "\\", Core.UserName); m_ModifTime = time(NULL); } } void CEditableObject::GetFaceWorld(const Fmatrix& parent, CEditableMesh* M, int idx, Fvector* verts) { const Fvector* PT[3]; M->GetFacePT(idx, PT); parent.transform_tiny(verts[0], *PT[0]); parent.transform_tiny(verts[1], *PT[1]); parent.transform_tiny(verts[2], *PT[2]); } void CEditableObject::Optimize() { for (auto m_def = m_Meshes.begin(); m_def != m_Meshes.end(); ++m_def) { (*m_def)->OptimizeMesh(false); (*m_def)->RebuildVMaps(); } } bool CEditableObject::Validate() { bool bRes = true; for (auto s_it = m_Surfaces.begin(); s_it != m_Surfaces.end(); ++s_it) if (false == (*s_it)->Validate()) { Msg("!Invalid surface found: Object [%s], Surface [%s].", GetName(), (*s_it)->_Name()); bRes = false; } for (auto m_def = m_Meshes.begin(); m_def != m_Meshes.end(); ++m_def) if (false == (*m_def)->Validate()) { Msg("!Invalid mesh found: Object [%s], Mesh [%s].", m_LibName.c_str(), (*m_def)->Name().c_str()); bRes = false; } return bRes; } //----------------------------------------------------------------------------
21.267062
106
0.625785
Rikoshet-234
c97aab1a63d144d7077a8d5dba1951be32af82e4
1,465
cpp
C++
lucida/imagematching/template/IMSClient.cpp
bnsblue/lucida
b3810caf5d8ab1d3494c56fd0c01eca38185002b
[ "BSD-3-Clause" ]
3,483
2015-01-09T03:23:46.000Z
2015-12-13T03:00:51.000Z
lucida/imagematching/template/IMSClient.cpp
bnsblue/lucida
b3810caf5d8ab1d3494c56fd0c01eca38185002b
[ "BSD-3-Clause" ]
50
2015-03-07T00:03:13.000Z
2015-06-30T06:07:45.000Z
lucida/imagematching/template/IMSClient.cpp
bnsblue/lucida
b3810caf5d8ab1d3494c56fd0c01eca38185002b
[ "BSD-3-Clause" ]
495
2015-03-11T17:39:54.000Z
2015-12-20T16:26:43.000Z
/* * * */ #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <thrift/protocol/TBinaryProtocol.h> #include <thrift/transport/TSocket.h> #include <thrift/transport/TTransportUtils.h> #include "gen-cpp/ImageMatchingService.h" using namespace std; using namespace apache::thrift; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; int main(int argc, char** argv) { int port = 9082; string imagePath; if (argv[1]) { port = atoi(argv[1]); } else { cout << "Using default port for imm..." << endl; } if(argv[2]) { imagePath = argv[2]; } else { cerr << "Usage: ./client <imm_port> <path_to_image>" << endl; return -1; } boost::shared_ptr<TTransport> socket(new TSocket("localhost", port)); boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket)); boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport)); ImageMatchingServiceClient client(protocol); struct timeval tv1, tv2; try{ ifstream fin(imagePath.c_str(), ios::binary); ostringstream ostrm; ostrm << fin.rdbuf(); string image(ostrm.str()); if (!fin) cerr << "Could not open the file!" << endl; transport->open(); string response; client.match_img(response, image); cout << "client sent the image successfully..." << endl; cout << response << endl; transport->close(); }catch(TException &tx){ cout << "ERROR: " << tx.what() << endl; } return 0; }
22.538462
73
0.682594
bnsblue
c97d8854211c8f4d5dd6bbbf18f79f0e49674088
1,979
hpp
C++
include/trial/online/interim/comoment.hpp
breese/trial.online
d28f8025082682ce10d9eb97c63ed0d4e62c7511
[ "BSL-1.0" ]
6
2017-11-19T15:12:33.000Z
2021-12-18T08:21:45.000Z
include/trial/online/interim/comoment.hpp
breese/trial.online
d28f8025082682ce10d9eb97c63ed0d4e62c7511
[ "BSL-1.0" ]
1
2019-02-20T11:28:49.000Z
2019-02-20T11:28:49.000Z
include/trial/online/interim/comoment.hpp
breese/trial.online
d28f8025082682ce10d9eb97c63ed0d4e62c7511
[ "BSL-1.0" ]
2
2019-02-19T16:00:03.000Z
2020-10-29T08:26:44.000Z
#ifndef TRIAL_ONLINE_INTERIM_COMOMENT_HPP #define TRIAL_ONLINE_INTERIM_COMOMENT_HPP /////////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2019 Bjorn Reese <breese@users.sourceforge.net> // // 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 <trial/online/cumulative/comoment.hpp> namespace trial { namespace online { namespace interim { template <typename T, std::size_t Window, online::with Moment> class basic_comoment; //! @brief Sliding-window covariance estimator template <typename T, std::size_t Window> class basic_comoment<T, Window, with::variance> { static_assert(std::is_floating_point<T>::value, "T must be an floating-point type"); public: using value_type = T; using size_type = std::size_t; //! @brief Resets filter. void clear() noexcept; //! @brief Appends data point. void push(value_type first, value_type second) noexcept; //! @brief Returns maximum window size. size_type capacity() const noexcept; //! @brief Returns current window size. size_type size() const noexcept; //! @brief Returns true if window is empty. bool empty() const noexcept; //! @brief Returns true if window is full. bool full() const noexcept; //! @brief Returns covariance. value_type variance() const noexcept; protected: cumulative::basic_comoment<value_type, with::variance> active; cumulative::basic_comoment<value_type, with::variance> passive; }; // Convenience template <typename T, std::size_t Window> using covariance = basic_comoment<T, Window, with::variance>; } // namespace interim } // namespace online } // namespace trial #include <trial/online/interim/detail/comoment.ipp> #endif // TRIAL_ONLINE_INTERIM_COMOMENT_HPP
26.386667
88
0.664982
breese
c98b38ae62cf86d46a78ecd36c5e844aff855886
2,999
hpp
C++
libformula/Headers/formula/Term.hpp
purefunsolutions/ember-plus
d022732f2533ad697238c6b5210d7fc3eb231bfc
[ "BSL-1.0" ]
78
2015-07-31T14:46:38.000Z
2022-03-28T09:28:28.000Z
libformula/Headers/formula/Term.hpp
purefunsolutions/ember-plus
d022732f2533ad697238c6b5210d7fc3eb231bfc
[ "BSL-1.0" ]
81
2015-08-03T07:58:19.000Z
2022-02-28T16:21:19.000Z
libformula/Headers/formula/Term.hpp
purefunsolutions/ember-plus
d022732f2533ad697238c6b5210d7fc3eb231bfc
[ "BSL-1.0" ]
49
2015-08-03T12:53:10.000Z
2022-03-17T17:25:49.000Z
/* Copyright (C) 2012-2016 Lawo GmbH (http://www.lawo.com). Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef __LIBFORMULA_TERM_HPP #define __LIBFORMULA_TERM_HPP #include "CodeEmitter.hpp" #include "ErrorStack.hpp" #include "Scanner.hpp" #include "Parser.hpp" #include "util/CodeInterpreter.hpp" #include <memory> namespace libformula { /** * Represents a mathematical expression, which is constructed from * a provided string. * @note The template parameter must be a class implementing the * CodeEmitter interface. Additionaly, it must provided * a templated function with the following name and * signature: * template<typename DestType> * DestType compute(DestType); */ template<typename CodeEmitterType> class Term { public: /** * Initializes a new term by parsing and compiling the provided * term string. * @param first Points to the first item in the buffer containing * the term to compile. * @param last Points to the first item beyond the buffer. * @param error A pointer to the error stack which collects errors * that occur during scanning or parsing the term. */ template<typename InputIterator> Term(InputIterator first, InputIterator last, ErrorStack* error); /** * Computes the term and returns the result. * @param value The value to use for the '$' symbol. * @return Returns the result of the computation. */ template<typename ValueType> ValueType compute(ValueType value) const; private: std::shared_ptr<CodeEmitterType> m_emitter; }; /************************************************************************** * Inline implementation * **************************************************************************/ template<typename CodeEmitterType> template<typename InputIterator> inline Term<CodeEmitterType>::Term(InputIterator first, InputIterator last, ErrorStack* error) : m_emitter(std::make_shared<CodeEmitterType>()) { auto const scanner = Scanner<InputIterator>(first, last, error); if (error->empty()) { auto emitter = m_emitter.get(); auto const parser = Parser<InputIterator>(scanner, emitter, error); } } template<typename CodeEmitterType> template<typename ValueType> ValueType Term<CodeEmitterType>::compute(ValueType value) const { auto const result = m_emitter->compute(value); return result; } typedef Term<util::CodeInterpreter> CompiledTerm; } #endif // __LIBFORMULA_TERM_HPP
35.282353
98
0.591531
purefunsolutions
c98c55131a7aa847d5e003069bac8848e151e740
3,187
inl
C++
include/equal/factory/dat.inl
equal-games/equal
acaf0d456d7b996dd2a6bc23150cd45ddf618296
[ "BSD-2-Clause", "Apache-2.0" ]
7
2019-08-07T21:27:27.000Z
2020-11-27T16:33:16.000Z
include/equal/factory/dat.inl
equal-games/equal
acaf0d456d7b996dd2a6bc23150cd45ddf618296
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
include/equal/factory/dat.inl
equal-games/equal
acaf0d456d7b996dd2a6bc23150cd45ddf618296
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Equal Games * 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 <equal/world/data.hpp> /** * @brief A custom serialize methods for boost::serialization */ namespace boost::serialization { /** * @ingroup factories * @brief Serialize method for eq::Position */ template <class Archive> void serialize(Archive &ar, eq::Position &data, const unsigned int version) { ar &data.x; ar &data.y; } /** * @ingroup factories * @brief Serialize method for eq::Size */ template <class Archive> void serialize(Archive &ar, eq::Size &data, const unsigned int version) { ar &data.x; ar &data.y; } /** * @ingroup factories * @brief Serialize method for eq::World */ template <class Archive> void serialize(Archive &ar, eq::World &data, const unsigned int version) { ar &data.tile_size; ar &data.tileset_size; ar &data.chunk_size; ar &data.tilesets; ar &data.chunks; ar &data.floors; ar &data.tiles; ar &data.things; } /** * @ingroup factories * @brief Serialize method for eq::Chunk */ template <class Archive> void serialize(Archive &ar, eq::Chunk &data, const unsigned int version) { ar &data.position; } /** * @ingroup factories * @brief Serialize method for eq::Floor */ template <class Archive> void serialize(Archive &ar, eq::Floor &data, const unsigned int version) { ar &data.chunk; ar &data.number; } /** * @ingroup factories * @brief Serialize method for eq::Tile */ template <class Archive> void serialize(Archive &ar, eq::Tile &data, const unsigned int version) { ar &data.floor; ar &data.position; ar &data.flags; } /** * @ingroup factories * @brief Serialize method for eq::Thing */ template <class Archive> void serialize(Archive &ar, eq::Thing &data, const unsigned int version) { ar &data.tile; ar &data.id; ar &data.type; } /** * @ingroup factories * @brief Serialize method for eq::ResourceDAT */ template <class Archive> void serialize(Archive &ar, eq::ResourceDAT &data, const unsigned int version) { ar &data.textures; ar &data.fonts; } /** * @ingroup factories * @brief Serialize method for eq::FontDAT */ template <class Archive> void serialize(Archive &ar, eq::FontDAT &data, const unsigned int version) { ar &data.name; ar &data.compressed; ar &data.buffer; } /** * @ingroup factories * @brief Serialize method for eq::TextureDAT */ template <class Archive> void serialize(Archive &ar, eq::TextureDAT &data, const unsigned int version) { ar &data.name; ar &data.first_id; ar &data.width; ar &data.height; ar &data.depth; ar &data.pitch; ar &data.format; ar &data.compressed; ar &data.buffer; } } // namespace boost::serialization
23.433824
80
0.698149
equal-games
c99a62b4a49898f32e0998ac3464ceb35711b7ff
3,094
cpp
C++
constraintsolver/src/types/Clause.cpp
hendrik-skubch/alica-supplementary
de6d48cc6b8144bdc7bf03373ae04212b1f545bc
[ "MIT" ]
1
2018-12-28T12:06:45.000Z
2018-12-28T12:06:45.000Z
constraintsolver/src/types/Clause.cpp
hendrik-skubch/alica-supplementary
de6d48cc6b8144bdc7bf03373ae04212b1f545bc
[ "MIT" ]
12
2018-05-28T05:27:04.000Z
2021-11-23T07:52:35.000Z
constraintsolver/src/types/Clause.cpp
hendrik-skubch/alica-supplementary
de6d48cc6b8144bdc7bf03373ae04212b1f545bc
[ "MIT" ]
3
2019-03-27T01:05:10.000Z
2020-07-23T19:11:09.000Z
/* * Clause.cpp * * Created on: Dec 4, 2014 * Author: Philipp */ #include "types/Clause.h" #include "types/Lit.h" #include "types/Var.h" #include "types/Watcher.h" #include <iostream> namespace alica { namespace reasoner { namespace cnsat { Clause::Clause() { activity = 0; satisfied = false; isFinished = false; isTautologic = false; watcher = std::make_shared<std::vector<Watcher*>>(2); literals = std::make_shared<std::vector<shared_ptr<Lit>>>(); } Clause::~Clause() { for (Watcher* w : *watcher) { // w->lit->var->watchList // TODO delete w; } } void Clause::addChecked(std::shared_ptr<Lit> l) { bool found = false; if (l->isTemporary) { for (int i = 0; i < static_cast<int>(literals->size()); ++i) { if (literals->at(i)->isTemporary && l->_atom == literals->at(i)->_atom) { found = true; break; } } if (!found) { literals->push_back(l); } return; } for (int i = 0; i < static_cast<int>(literals->size()); ++i) { if (l->_atom == literals->at(i)->_atom) { found = true; if (l->sign != literals->at(i)->sign) { isTautologic = true; literals->clear(); } break; } } if (!found) { literals->push_back(l); } return; } std::shared_ptr<Clause> Clause::clone() { std::shared_ptr<Clause> clone = std::make_shared<Clause>(); // clone->literals->insert(clone->literals->end(), literals->begin(), literals->end()); *clone->literals = *literals; // clone->literals = make_shared<vector<shared_ptr<Lit>>>(); // for (shared_ptr<Lit> l : *literals) { // clone->literals->push_back(l); // } clone->isFinished = isFinished; clone->isTautologic = isTautologic; return clone; } void Clause::add(std::shared_ptr<Lit> l) { literals->push_back(l); } int Clause::avgActivity() { int ret = 0; for (std::shared_ptr<Lit> l : *literals) { ret += l->var->activity; } return ret / literals->size(); } bool Clause::checkSatisfied() { for (std::shared_ptr<Lit> l : *literals) { if (l->var->assignment == l->sign) { return true; } } return false; } bool Clause::compareTo(std::shared_ptr<Clause> ep1, std::shared_ptr<Clause> ep2) { return ep1->activity > ep2->activity; } void Clause::print() { for (std::shared_ptr<Lit> l : *literals) { if (l->sign == Assignment::FALSE) { cout << "-"; } if (l->sign == Assignment::TRUE) { cout << "+"; } if (l->sign == Assignment::UNASSIGNED) { cout << "#"; } cout << l->var->index; if ((watcher->at(0) && watcher->at(0)->lit == l) || (watcher->at(1) && watcher->at(1)->lit == l)) { cout << "w"; } cout << " "; } cout << endl; } } /* namespace cnsat */ } /* namespace reasoner */ } /* namespace alica */
22.42029
107
0.519716
hendrik-skubch
c99e31234951a1cd8a5128cee47273d49aa3c9ef
5,574
cc
C++
lib/asan/asan_malloc_win.cc
Inventor1938/compiler_rt
71f55845f157d285d27bbc5e5c53ff145847d9b4
[ "MIT" ]
8,865
2017-03-13T03:27:32.000Z
2022-03-31T12:57:44.000Z
atlas-aapt/external/compiler-rt/lib/asan/asan_malloc_win.cc
gdongxie/atlas
602b3295716ef405574033759ab0238c7ee34527
[ "Apache-2.0" ]
359
2017-03-13T06:37:22.000Z
2022-01-27T14:31:43.000Z
atlas-aapt/external/compiler-rt/lib/asan/asan_malloc_win.cc
gdongxie/atlas
602b3295716ef405574033759ab0238c7ee34527
[ "Apache-2.0" ]
1,709
2017-03-13T02:29:13.000Z
2022-03-31T12:57:48.000Z
//===-- asan_malloc_win.cc ------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of AddressSanitizer, an address sanity checker. // // Windows-specific malloc interception. //===----------------------------------------------------------------------===// #include "sanitizer_common/sanitizer_platform.h" #if SANITIZER_WINDOWS #include "asan_allocator.h" #include "asan_interceptors.h" #include "asan_internal.h" #include "asan_stack.h" #include "interception/interception.h" #include <stddef.h> using namespace __asan; // NOLINT // MT: Simply defining functions with the same signature in *.obj // files overrides the standard functions in the CRT. // MD: Memory allocation functions are defined in the CRT .dll, // so we have to intercept them before they are called for the first time. #if ASAN_DYNAMIC # define ALLOCATION_FUNCTION_ATTRIBUTE #else # define ALLOCATION_FUNCTION_ATTRIBUTE SANITIZER_INTERFACE_ATTRIBUTE #endif extern "C" { ALLOCATION_FUNCTION_ATTRIBUTE void free(void *ptr) { GET_STACK_TRACE_FREE; return asan_free(ptr, &stack, FROM_MALLOC); } ALLOCATION_FUNCTION_ATTRIBUTE void _free_dbg(void *ptr, int) { free(ptr); } ALLOCATION_FUNCTION_ATTRIBUTE void cfree(void *ptr) { CHECK(!"cfree() should not be used on Windows"); } ALLOCATION_FUNCTION_ATTRIBUTE void *malloc(size_t size) { GET_STACK_TRACE_MALLOC; return asan_malloc(size, &stack); } ALLOCATION_FUNCTION_ATTRIBUTE void *_malloc_dbg(size_t size, int, const char *, int) { return malloc(size); } ALLOCATION_FUNCTION_ATTRIBUTE void *calloc(size_t nmemb, size_t size) { GET_STACK_TRACE_MALLOC; return asan_calloc(nmemb, size, &stack); } ALLOCATION_FUNCTION_ATTRIBUTE void *_calloc_dbg(size_t nmemb, size_t size, int, const char *, int) { return calloc(nmemb, size); } ALLOCATION_FUNCTION_ATTRIBUTE void *_calloc_impl(size_t nmemb, size_t size, int *errno_tmp) { return calloc(nmemb, size); } ALLOCATION_FUNCTION_ATTRIBUTE void *realloc(void *ptr, size_t size) { GET_STACK_TRACE_MALLOC; return asan_realloc(ptr, size, &stack); } ALLOCATION_FUNCTION_ATTRIBUTE void *_realloc_dbg(void *ptr, size_t size, int) { CHECK(!"_realloc_dbg should not exist!"); return 0; } ALLOCATION_FUNCTION_ATTRIBUTE void *_recalloc(void *p, size_t n, size_t elem_size) { if (!p) return calloc(n, elem_size); const size_t size = n * elem_size; if (elem_size != 0 && size / elem_size != n) return 0; return realloc(p, size); } ALLOCATION_FUNCTION_ATTRIBUTE size_t _msize(void *ptr) { GET_CURRENT_PC_BP_SP; (void)sp; return asan_malloc_usable_size(ptr, pc, bp); } ALLOCATION_FUNCTION_ATTRIBUTE void *_expand(void *memblock, size_t size) { // _expand is used in realloc-like functions to resize the buffer if possible. // We don't want memory to stand still while resizing buffers, so return 0. return 0; } ALLOCATION_FUNCTION_ATTRIBUTE void *_expand_dbg(void *memblock, size_t size) { return _expand(memblock, size); } // TODO(timurrrr): Might want to add support for _aligned_* allocation // functions to detect a bit more bugs. Those functions seem to wrap malloc(). int _CrtDbgReport(int, const char*, int, const char*, const char*, ...) { ShowStatsAndAbort(); } int _CrtDbgReportW(int reportType, const wchar_t*, int, const wchar_t*, const wchar_t*, ...) { ShowStatsAndAbort(); } int _CrtSetReportMode(int, int) { return 0; } } // extern "C" namespace __asan { void ReplaceSystemMalloc() { #if defined(ASAN_DYNAMIC) // We don't check the result because CRT might not be used in the process. __interception::OverrideFunction("free", (uptr)free); __interception::OverrideFunction("malloc", (uptr)malloc); __interception::OverrideFunction("_malloc_crt", (uptr)malloc); __interception::OverrideFunction("calloc", (uptr)calloc); __interception::OverrideFunction("_calloc_crt", (uptr)calloc); __interception::OverrideFunction("realloc", (uptr)realloc); __interception::OverrideFunction("_realloc_crt", (uptr)realloc); __interception::OverrideFunction("_recalloc", (uptr)_recalloc); __interception::OverrideFunction("_recalloc_crt", (uptr)_recalloc); __interception::OverrideFunction("_msize", (uptr)_msize); __interception::OverrideFunction("_expand", (uptr)_expand); // Override different versions of 'operator new' and 'operator delete'. // No need to override the nothrow versions as they just wrap the throw // versions. // FIXME: Unfortunately, MSVC miscompiles the statements that take the // addresses of the array versions of these operators, // see https://connect.microsoft.com/VisualStudio/feedbackdetail/view/946992 // We might want to try to work around this by [inline] assembly or compiling // parts of the RTL with Clang. void *(*op_new)(size_t sz) = operator new; void (*op_delete)(void *p) = operator delete; void *(*op_array_new)(size_t sz) = operator new[]; void (*op_array_delete)(void *p) = operator delete[]; __interception::OverrideFunction("??2@YAPAXI@Z", (uptr)op_new); __interception::OverrideFunction("??3@YAXPAX@Z", (uptr)op_delete); __interception::OverrideFunction("??_U@YAPAXI@Z", (uptr)op_array_new); __interception::OverrideFunction("??_V@YAXPAX@Z", (uptr)op_array_delete); #endif } } // namespace __asan #endif // _WIN32
31.139665
80
0.712235
Inventor1938
c9a03be1325335a9eb5790139baf33c9e2663315
5,207
hpp
C++
thirdparty/taocppjson/include/tao/json/sax/from_value.hpp
liftchampion/nativejson-benchmark
6d575ffa4359a5c4230f74b07d994602a8016fb5
[ "MIT" ]
null
null
null
thirdparty/taocppjson/include/tao/json/sax/from_value.hpp
liftchampion/nativejson-benchmark
6d575ffa4359a5c4230f74b07d994602a8016fb5
[ "MIT" ]
null
null
null
thirdparty/taocppjson/include/tao/json/sax/from_value.hpp
liftchampion/nativejson-benchmark
6d575ffa4359a5c4230f74b07d994602a8016fb5
[ "MIT" ]
null
null
null
// Copyright (c) 2016-2017 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/json/ #ifndef TAOCPP_JSON_INCLUDE_SAX_FROM_VALUE_HPP #define TAOCPP_JSON_INCLUDE_SAX_FROM_VALUE_HPP #include <stdexcept> #include "../value.hpp" namespace tao { namespace json { namespace sax { // SAX producer to generate events from a JSON value template< template< typename... > class Traits, typename Consumer > void from_value( const basic_value< Traits >& v, Consumer& consumer ) { switch( v.type() ) { case type::UNINITIALIZED: throw std::logic_error( "unable to produce events from uninitialized values" ); case type::DISCARDED: throw std::logic_error( "unable to produce events from discarded values" ); case type::NULL_: consumer.null(); return; case type::BOOLEAN: consumer.boolean( v.unsafe_get_boolean() ); return; case type::SIGNED: consumer.number( v.unsafe_get_signed() ); return; case type::UNSIGNED: consumer.number( v.unsafe_get_unsigned() ); return; case type::DOUBLE: consumer.number( v.unsafe_get_double() ); return; case type::STRING: consumer.string( v.unsafe_get_string() ); return; case type::ARRAY: consumer.begin_array(); for( const auto& e : v.unsafe_get_array() ) { sax::from_value( e, consumer ); consumer.element(); } consumer.end_array(); return; case type::OBJECT: consumer.begin_object(); for( const auto& e : v.unsafe_get_object() ) { consumer.key( e.first ); sax::from_value( e.second, consumer ); consumer.member(); } consumer.end_object(); return; case type::RAW_PTR: if( const basic_value< Traits >* p = v.unsafe_get_raw_ptr() ) { sax::from_value( *p, consumer ); } else { consumer.null(); } return; } throw std::logic_error( "invalid value for tao::json::type" ); // LCOV_EXCL_LINE } // SAX producer to generate events from an rvalue JSON value // note: strings from the source might be moved in the consumer template< template< typename... > class Traits, typename Consumer > void from_value( basic_value< Traits >&& v, Consumer& consumer ) { switch( v.type() ) { case type::UNINITIALIZED: throw std::logic_error( "unable to produce events from uninitialized values" ); case type::DISCARDED: throw std::logic_error( "unable to produce events from discarded values" ); case type::NULL_: consumer.null(); return; case type::BOOLEAN: consumer.boolean( v.unsafe_get_boolean() ); return; case type::SIGNED: consumer.number( v.unsafe_get_signed() ); return; case type::UNSIGNED: consumer.number( v.unsafe_get_unsigned() ); return; case type::DOUBLE: consumer.number( v.unsafe_get_double() ); return; case type::STRING: consumer.string( std::move( v.unsafe_get_string() ) ); return; case type::ARRAY: consumer.begin_array(); for( auto&& e : v.unsafe_get_array() ) { sax::from_value( std::move( e ), consumer ); consumer.element(); } consumer.end_array(); return; case type::OBJECT: consumer.begin_object(); for( auto&& e : v.unsafe_get_object() ) { consumer.key( std::move( e.first ) ); sax::from_value( std::move( e.second ), consumer ); consumer.member(); } consumer.end_object(); return; case type::RAW_PTR: if( const basic_value< Traits >* p = v.unsafe_get_raw_ptr() ) { sax::from_value( *p, consumer ); } else { consumer.null(); } return; } throw std::logic_error( "invalid value for tao::json::type" ); // LCOV_EXCL_LINE } } // sax } // json } // tao #endif
38.007299
97
0.467256
liftchampion
c9a880b97b52efd83273551e225ade48ffe9e286
1,871
hpp
C++
io/private/tty_color_t.hpp
Better-Idea/Mix-C
71f34a5fc8c17a516cf99bc397289d046364a82e
[ "Apache-2.0" ]
41
2019-09-24T02:17:34.000Z
2022-01-18T03:14:46.000Z
io/private/tty_color_t.hpp
Better-Idea/Mix-C
71f34a5fc8c17a516cf99bc397289d046364a82e
[ "Apache-2.0" ]
2
2019-11-04T09:01:40.000Z
2020-06-23T03:03:38.000Z
io/private/tty_color_t.hpp
Better-Idea/Mix-C
71f34a5fc8c17a516cf99bc397289d046364a82e
[ "Apache-2.0" ]
8
2019-09-24T02:17:35.000Z
2021-09-11T00:21:03.000Z
#ifndef xpack_io_private_tty_color_t #define xpack_io_private_tty_color_t #pragma push_macro("xuser") #undef xuser #define xuser mixc::io_private_tty_color_t::inc #include"define/base_type.hpp" #include"macro/xexport.hpp" #pragma pop_macro("xuser") namespace mixc::io_private_tty_color_t::origin{ enum class tty_color_t : u08 { black, red, green, yellow, blue, magenta, cyan, white, gray, light_red, light_green, light_yellow, light_blue, light_magenta, light_cyan, light_gray, }; namespace tty_color{ constexpr tty_color_t black = tty_color_t::black; constexpr tty_color_t red = tty_color_t::red; constexpr tty_color_t green = tty_color_t::green; constexpr tty_color_t yellow = tty_color_t::yellow; constexpr tty_color_t blue = tty_color_t::blue; constexpr tty_color_t magenta = tty_color_t::magenta; constexpr tty_color_t cyan = tty_color_t::cyan; constexpr tty_color_t white = tty_color_t::white; constexpr tty_color_t gray = tty_color_t::gray; constexpr tty_color_t light_red = tty_color_t::light_red; constexpr tty_color_t light_green = tty_color_t::light_green; constexpr tty_color_t light_yellow = tty_color_t::light_yellow; constexpr tty_color_t light_blue = tty_color_t::light_blue; constexpr tty_color_t light_magenta = tty_color_t::light_magenta; constexpr tty_color_t light_cyan = tty_color_t::light_cyan; constexpr tty_color_t light_gray = tty_color_t::light_gray; } } #endif xexport_space(mixc::io_private_tty_color_t::origin)
35.980769
77
0.634955
Better-Idea
c9a8ced0f3090311fb3399a3d77bb40804d6f7f1
615
cpp
C++
docs/atl/codesnippet/CPP/catllist-class_13.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
965
2017-06-25T23:57:11.000Z
2022-03-31T14:17:32.000Z
docs/atl/codesnippet/CPP/catllist-class_13.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
3,272
2017-06-24T00:26:34.000Z
2022-03-31T22:14:07.000Z
docs/atl/codesnippet/CPP/catllist-class_13.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
951
2017-06-25T12:36:14.000Z
2022-03-26T22:49:06.000Z
// Define the integer list CAtlList<int> myList; // Populate the list myList.AddTail(1); myList.AddTail(2); myList.AddTail(3); myList.AddTail(4); // Confirm not empty ATLASSERT(myList.IsEmpty() == false); // Remove the tail element myList.RemoveTailNoReturn(); // Confirm not empty ATLASSERT(myList.IsEmpty() == false); // Remove the head element myList.RemoveHeadNoReturn(); // Confirm not empty ATLASSERT(myList.IsEmpty() == false); // Remove all remaining elements myList.RemoveAll(); // Confirm empty ATLASSERT(myList.IsEmpty() == true);
21.206897
42
0.652033
bobbrow
c9acad7ea1d0289d4da1fe0af97b10b2885003f7
4,376
cpp
C++
src/update.cpp
fatorius/Capizero
2aace7c314df37a7a1c437eb2e66571ed1a89aa5
[ "MIT" ]
null
null
null
src/update.cpp
fatorius/Capizero
2aace7c314df37a7a1c437eb2e66571ed1a89aa5
[ "MIT" ]
null
null
null
src/update.cpp
fatorius/Capizero
2aace7c314df37a7a1c437eb2e66571ed1a89aa5
[ "MIT" ]
null
null
null
#include "include.h" #include "update.h" #include "bitboard.h" #include "hash.h" #include "attacks.h" #include "init.h" int reverse_square[2] = {-8,8}; game* g; void update_piece(const int s,const int p,const int start,const int dest){ bit_units[s] &= not_mask[start]; bit_units[s] |= mask[dest]; bit_all = bit_units[0] | bit_units[1]; add_key(s,p,start); add_key(s,p,dest); board[dest] = p; board[start] = EMPTY; bit_pieces[s][p] &= not_mask[start]; bit_pieces[s][p] |= mask[dest]; } void add_piece(const int s,const int p,const int sq){ board[sq] = p; add_key(s,p,sq); bit_units[s] |= mask[sq]; bit_pieces[s][p] |= mask[sq]; bit_all = bit_units[0] | bit_units[1]; } void remove_piece(const int s,const int p,const int sq){ add_key(s,p,sq); board[sq] = EMPTY; bit_units[s] &= not_mask[sq]; bit_pieces[s][p] &= not_mask[sq]; bit_all = bit_units[0] | bit_units[1]; } int make_move(const int start, const int dest){ if (abs(start - dest) == 2 && board[start] == K) { if (attack(xside, start)) return false; if (dest == G1) { if (attack(xside, F1)) return false; update_piece(side, R, H1, F1); } else if (dest == C1) { if (attack(xside, D1)) return false; update_piece(side, R, A1, D1); } else if (dest == G8) { if (attack(xside, F8)) return false; update_piece(side, R, H8, F8); } else if (dest == C8) { if (attack(xside, D8)) return false; update_piece(side, R, A8, D8); } } g = & game_list[hply]; g -> start = start; g -> dest = dest; g -> capture = board[dest]; g -> castle = castle; g -> fifty = fifty; g -> hash = currentkey; g -> lock = currentlock; g -> castle = castle; castle &= castle_mask[start] & castle_mask[dest]; ply++; hply++; fifty++; if (board[start] == P) { fifty = 0; if (board[dest] == EMPTY && col[start] != col[dest]) { remove_piece(xside, P, dest + reverse_square[side]); } } if (board[dest] < 6) { fifty = 0; remove_piece(xside, board[dest], dest); } if (board[start] == P && (row[dest] == 0 || row[dest] == 7)) { remove_piece(side, P, start); add_piece(side, Q, dest); g -> promote = Q; } else { g -> promote = 0; update_piece(side, board[start], start, dest); } side ^= 1; xside ^= 1; if (attack(side, next_bit(bit_pieces[xside][K]))) { take_back(); return false; } return true; } void take_back(){ side ^= 1; xside ^= 1; ply--; hply--; game * m = & game_list[hply]; int start = m -> start; int dest = m -> dest; castle = m -> castle; fifty = m -> fifty; if (board[dest] == P && m -> capture == EMPTY && col[start] != col[dest]) { add_piece(xside, P, dest + reverse_square[side]); } if (m -> promote == Q) { add_piece(side, P, start); remove_piece(side, board[dest], dest); } else { update_piece(side, board[dest], dest, start); } if (m -> capture != EMPTY) { add_piece(xside, m -> capture, dest); } if (abs(start - dest) == 2 && board[start] == K) { if (dest == G1){ update_piece(side, R, F1, H1); } else if (dest == C1){ update_piece(side, R, D1, A1); } else if (dest == G8){ update_piece(side, R, F8, H8); } else if (dest == C8){ update_piece(side, R, D8, A8); } } } int make_recapture(const int from, const int to){ game_list[hply].start = from; game_list[hply].dest = to; game_list[hply].capture = board[to]; ++ply; ++hply; remove_piece(xside,board[to],to); update_piece(side,board[from],from,to); side ^= 1; xside ^= 1; if (attack(side, next_bit(bit_pieces[xside][K]))){ unmake_recapture(); return false; } return true; } void unmake_recapture(){ side ^= 1; xside ^= 1; --ply; --hply; update_piece(side,board[game_list[hply].dest], game_list[hply].dest, game_list[hply].start); add_piece(xside, game_list[hply].capture, game_list[hply].dest); }
24.311111
96
0.527422
fatorius
c9ad1b44df2191a3fbbff1177b7183a434aa2abc
5,473
cpp
C++
catboost/private/libs/algo/approx_calcer/eval_additive_metric_with_leaves.cpp
SaiAyachit/catboost
876d831d1a6c9fb7caa6f24e70058580f09b5c6c
[ "Apache-2.0" ]
4
2020-06-24T06:07:52.000Z
2021-04-16T22:58:09.000Z
catboost/private/libs/algo/approx_calcer/eval_additive_metric_with_leaves.cpp
TakeOver/stochasticrank
45f9c701785bb952c59c704a2bfe878d5cbb01e4
[ "Apache-2.0" ]
null
null
null
catboost/private/libs/algo/approx_calcer/eval_additive_metric_with_leaves.cpp
TakeOver/stochasticrank
45f9c701785bb952c59c704a2bfe878d5cbb01e4
[ "Apache-2.0" ]
1
2020-10-17T09:28:08.000Z
2020-10-17T09:28:08.000Z
#include "eval_additive_metric_with_leaves.h" #include <catboost/libs/helpers/exception.h> #include <catboost/libs/helpers/vector_helpers.h> #include <library/cpp/fast_exp/fast_exp.h> #include <util/generic/algorithm.h> #include <util/generic/utility.h> #include <util/generic/vector.h> #include <util/generic/xrange.h> static int GetBlockSize( bool isObjectwise, TConstArrayRef<TQueryInfo> queriesInfo, int idx, int nextIdx ) { if (isObjectwise) { return nextIdx - idx; } return queriesInfo[nextIdx - 1].End - queriesInfo[idx].Begin; } static int GetNextIdx( bool isObjectwise, TConstArrayRef<TQueryInfo> queriesInfo, int lastIdx, int maxApproxBlockSize, int idx ) { if (isObjectwise) { return Min<int>(idx + maxApproxBlockSize, lastIdx); } int objectsCount = 0; while (idx < lastIdx) { objectsCount += queriesInfo[idx].GetSize(); if (objectsCount > maxApproxBlockSize) { return idx; } idx += 1; } return idx; } TMetricHolder EvalErrorsWithLeaves( const TConstArrayRef<TConstArrayRef<double>> approx, const TConstArrayRef<TConstArrayRef<double>> leafDelta, TConstArrayRef<TIndexType> indices, bool isExpApprox, TConstArrayRef<float> target, TConstArrayRef<float> weight, TConstArrayRef<TQueryInfo> queriesInfo, const IMetric& error, NPar::TLocalExecutor* localExecutor ) { CB_ENSURE(error.IsAdditiveMetric(), "EvalErrorsWithLeaves is not implemented for non-additive metric " + error.GetDescription()); const auto approxDimension = approx.size(); TVector<TVector<double>> localLeafDelta; ResizeRank2(approxDimension, leafDelta[0].size(), localLeafDelta); AssignRank2(leafDelta, &localLeafDelta); if (isExpApprox) { for (auto& deltaDimension : localLeafDelta) { FastExpInplace(deltaDimension.data(), deltaDimension.size()); } } NPar::TLocalExecutor sequentialExecutor; const auto evalMetric = [&] (int from, int to) { // objects or queries TVector<TConstArrayRef<double>> approxBlock(approxDimension, TArrayRef<double>{}); const bool isObjectwise = error.GetErrorType() == EErrorType::PerObjectError; CB_ENSURE(isObjectwise || !queriesInfo.empty(), "Need queries to evaluate metric " + error.GetDescription()); int maxApproxBlockSize = 4096; if (!isObjectwise) { const auto maxQuerySize = MaxElementBy( queriesInfo.begin() + from, queriesInfo.begin() + to, [] (const auto& query) { return query.GetSize(); })->GetSize(); maxApproxBlockSize = Max<int>(maxApproxBlockSize, maxQuerySize); } TVector<TVector<double>> approxDeltaBlock; ResizeRank2(approxDimension, maxApproxBlockSize, approxDeltaBlock); TVector<TQueryInfo> localQueriesInfo(queriesInfo.begin(), queriesInfo.end()); TMetricHolder result; for (int idx = from; idx < to; /*see below*/) { const int nextIdx = GetNextIdx(isObjectwise, queriesInfo, to, maxApproxBlockSize, idx); const int approxBlockSize = GetBlockSize(isObjectwise, queriesInfo, idx, nextIdx); const int approxBlockStart = isObjectwise ? idx : queriesInfo[idx].Begin; for (auto dimensionIdx : xrange(approxDimension)) { const auto approxDimension = MakeArrayRef(approxDeltaBlock[dimensionIdx]); const auto deltaDimension = MakeArrayRef(localLeafDelta[dimensionIdx]); for (auto jdx : xrange(approxBlockSize)) { approxDimension[jdx] = deltaDimension[indices[approxBlockStart + jdx]]; } } for (auto dimensionIdx : xrange(approxDimension)) { approxBlock[dimensionIdx] = MakeArrayRef(approx[dimensionIdx].data() + approxBlockStart, approxBlockSize); } const auto targetBlock = MakeArrayRef(target.data() + approxBlockStart, approxBlockSize); const auto weightBlock = weight.empty() ? TArrayRef<float>{} : MakeArrayRef(weight.data() + approxBlockStart, approxBlockSize); auto queriesInfoBlock = TArrayRef<TQueryInfo>{}; if (!isObjectwise) { queriesInfoBlock = MakeArrayRef(localQueriesInfo.data() + idx, nextIdx - idx); for (auto& query : queriesInfoBlock) { query.Begin -= approxBlockStart; query.End -= approxBlockStart; } } const auto blockResult = EvalErrors( approxBlock, To2DConstArrayRef<double>(approxDeltaBlock), isExpApprox, targetBlock, weightBlock, queriesInfoBlock, error, &sequentialExecutor); result.Add(blockResult); idx = nextIdx; } return result; }; int begin = 0; int end; if (error.GetErrorType() == EErrorType::PerObjectError) { end = target.size(); Y_VERIFY(end <= approx[0].ysize()); } else { Y_VERIFY(error.GetErrorType() == EErrorType::QuerywiseError || error.GetErrorType() == EErrorType::PairwiseError); end = queriesInfo.size(); } return ParallelEvalMetric(evalMetric, GetMinBlockSize(end - begin), begin, end, *localExecutor); }
37.744828
133
0.636762
SaiAyachit
c9ade46a2116d05e7760a7b522ba7358ecae51f3
4,261
cpp
C++
assignments/a6-transform/unique.cpp
habmc/animation-toolkit
7abce87dbe7c5dfe392a168e47f22596b7a9a7b0
[ "MIT" ]
null
null
null
assignments/a6-transform/unique.cpp
habmc/animation-toolkit
7abce87dbe7c5dfe392a168e47f22596b7a9a7b0
[ "MIT" ]
null
null
null
assignments/a6-transform/unique.cpp
habmc/animation-toolkit
7abce87dbe7c5dfe392a168e47f22596b7a9a7b0
[ "MIT" ]
null
null
null
#include "atkui/framework.h" #include "atk/toolkit.h" using namespace atk; using glm::quat; using glm::vec3; class Unique : public atkui::Framework { public: Unique() : atkui::Framework(atkui::Perspective) {} virtual ~Unique() {} virtual void setup() { lookAt(vec3(-20, 50, -700), vec3(0)); float spacing = 40; for (int i = 0; i < 10; i++) { Skeleton _tentacle; Joint *root = new Joint("hip"); root->setLocalTranslation(vec3(spacing * i - 200, 50, -i * spacing)); _tentacle.addJoint(root); Joint *joint1 = new Joint("right knee"); joint1->setLocalTranslation(vec3(-20, -20, 0)); _tentacle.addJoint(joint1, root); Joint *joint10 = new Joint("right ankle"); joint10->setLocalTranslation(vec3(0, -30, 0)); _tentacle.addJoint(joint10, joint1); Joint *joint2 = new Joint("left knee"); joint2->setLocalTranslation(vec3(20, -20, 0)); _tentacle.addJoint(joint2, root); Joint *joint20 = new Joint("left ankle"); joint20->setLocalTranslation(vec3(0, -30, 0)); _tentacle.addJoint(joint20, joint2); Joint *joint3 = new Joint("sternum"); joint3->setLocalTranslation(vec3(0, 40, 0)); _tentacle.addJoint(joint3, root); Joint *joint4 = new Joint("head"); joint4->setLocalTranslation(vec3(0, 25, 0)); _tentacle.addJoint(joint4, joint3); Joint *joint5 = new Joint("left shoulder"); joint5->setLocalTranslation(vec3(-20, 5, 0)); _tentacle.addJoint(joint5, joint3); Joint *joint50 = new Joint("left elbow"); joint50->setLocalTranslation(vec3(-10, -20, 0)); _tentacle.addJoint(joint50, joint5); Joint *joint6 = new Joint("right shoulder"); joint6->setLocalTranslation(vec3(20, 5, 0)); _tentacle.addJoint(joint6, joint3); Joint *joint60 = new Joint("right elbow"); joint60->setLocalTranslation(vec3(10, -20, 0)); _tentacle.addJoint(joint60, joint6); _tentacle.fk(); // compute local2global transforms _tentacles.push_back(_tentacle); } } virtual void scene() { push(); scale(vec3(10)); vec3 d10 = vec3(-10, 0, -30); quat R10 = glm::angleAxis(0.f, vec3(1, 0, 0)); Transform F10(R10, d10); // transform from frame 1 to world transform(F10); setColor(discoPallet[rand() % 5]); drawCube(vec3(0), vec3(2.5, 5, 5)); pop(); for (int j = 0; j < 10; j++) { Skeleton _tentacle = _tentacles[j]; int numJoints = _tentacle.getNumJoints(); setColor(pallet[j % 5]); for (int i = 0; i < numJoints; i++) { _tentacle.fk(); _tentacle.getByID(7)->setLocalRotation(glm::angleAxis((sin(elapsedTime()) * 25.0f), vec3(0, 1, 0))); _tentacle.getByID(9)->setLocalRotation(glm::angleAxis((sin(elapsedTime()) * 25.0f), vec3(0, 1, 0))); Joint *joint = _tentacle.getByID(i); if (joint->getParent() == 0) { continue; } Joint *parent = joint->getParent(); vec3 globalParentPos = parent->getGlobalTranslation(); vec3 globalPos = joint->getGlobalTranslation(); drawEllipsoid(globalParentPos, globalPos, 7); } } } protected: std::vector<Skeleton> _tentacles; std::vector<vec3> pallet = { vec3(0, 165, 227) / 255.0f, vec3(141, 215, 191) / 255.0f, vec3(255, 150, 197) / 255.0f, vec3(255, 87, 104) / 255.0f, vec3(255, 162, 58) / 255.0f}; std::vector<vec3> discoPallet = { vec3(15, 192, 252) / 255.0f, vec3(123, 29, 175) / 255.0f, vec3(255, 47, 185) / 255.0f, vec3(212, 255, 71) / 255.0f, vec3(27, 54, 73) / 255.0f}; }; int main(int argc, char **argv) { Unique viewer; viewer.run(); }
34.362903
116
0.526402
habmc
c9b7441dcbfdd37824f3fffd8d001badf441802c
843
cpp
C++
base/static_resource_test.cpp
hjinlin/toft
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
[ "BSD-3-Clause" ]
264
2015-01-03T11:50:17.000Z
2022-03-17T02:38:34.000Z
base/static_resource_test.cpp
hjinlin/toft
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
[ "BSD-3-Clause" ]
12
2015-04-27T15:17:34.000Z
2021-05-01T04:31:18.000Z
base/static_resource_test.cpp
hjinlin/toft
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
[ "BSD-3-Clause" ]
128
2015-02-07T18:13:10.000Z
2022-02-21T14:24:14.000Z
// Copyright (c) 2011, The Toft Authors. // All rights reserved. // // Author: CHEN Feng <chen3feng@gmail.com> // Created: 09/30/11 // Description: static resource test #include "toft/base/static_resource.h" #include "toft/base/static_resource_test_data.h" #include "thirdparty/gtest/gtest.h" namespace toft { static const char RESOURCE_test[] = "hello"; TEST(StaticResource, Test) { StringPiece resource = TOFT_STATIC_RESOURCE(test); EXPECT_STREQ(RESOURCE_test, resource.data()); } TEST(StaticResource, Package) { const StaticResourcePackage& package = TOFT_STATIC_RESOURCE_PACKAGE(toft_base_static_resource_test_data); StringPiece data; ASSERT_TRUE(package.Find("static_resource.testdata", &data)); EXPECT_EQ("hello, blade!\n", data); ASSERT_FALSE(package.Find("wtf", &data)); } } // namespace toft
25.545455
74
0.733096
hjinlin
c9ba7748536a88bdcd54e2c575160c31d8cd2144
145
cc
C++
build/x86/python/m5/internal/BasicRouter_vector.i_init.cc
billionshang/gem5
18cc4294f32315595f865d07d1f33434e92b06b2
[ "BSD-3-Clause" ]
null
null
null
build/x86/python/m5/internal/BasicRouter_vector.i_init.cc
billionshang/gem5
18cc4294f32315595f865d07d1f33434e92b06b2
[ "BSD-3-Clause" ]
1
2020-08-20T05:53:30.000Z
2020-08-20T05:53:30.000Z
build/X86_MESI_Two_Level/python/m5/internal/BasicRouter_vector.i_init.cc
hoho20000000/gem5-fy
b59f6feed22896d6752331652c4d8a41a4ca4435
[ "BSD-3-Clause" ]
null
null
null
#include "sim/init.hh" extern "C" { void init_BasicRouter_vector(); } EmbeddedSwig embed_swig_BasicRouter_vector(init_BasicRouter_vector);
18.125
68
0.786207
billionshang
c9bc14cb506ec90cd7b3348b232da1de4d188142
3,216
cpp
C++
noisy_circles/src/ofApp.cpp
c-c-c/gold-creative-coding
d7ccb5d5f706caafed27050a4c3a514c56a8230e
[ "MIT" ]
1
2020-04-25T06:34:59.000Z
2020-04-25T06:34:59.000Z
noisy_circles/src/ofApp.cpp
c-c-c/gold-creative-coding-1
d7ccb5d5f706caafed27050a4c3a514c56a8230e
[ "MIT" ]
null
null
null
noisy_circles/src/ofApp.cpp
c-c-c/gold-creative-coding-1
d7ccb5d5f706caafed27050a4c3a514c56a8230e
[ "MIT" ]
null
null
null
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofBackground(255); ofSetBackgroundAuto(false); totalRays = 20; stepSize = 200; radius = 300; angleStep = TWO_PI/totalRays; sunLocX = ofGetWidth()/2; sunLocY = ofGetHeight()/2; ofSetCircleResolution(60); for(int i=0 ; i < totalRays ; i++) { noiseSeeds.push_back(ofRandom(10000)); } ofNoFill(); } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ ofSetColor(0, 30); if(mouseX != 0 || mouseY != 0) { sunLocX += (mouseX-sunLocX) * 0.01; sunLocY += (mouseY-sunLocY) * 0.01; } ofTranslate(sunLocX, sunLocY); ofScale(0.6, 0.6); ofBeginShape(); float noiseRadius; ofPoint pointLocation; noiseRadius = (ofNoise(noiseSeeds[totalRays-1]) * stepSize) + radius; pointLocation.x = noiseRadius * cos(angleStep*(totalRays-1)); pointLocation.y = noiseRadius * sin(angleStep*(totalRays-1)); ofCurveVertex(pointLocation); for(int i=0 ; i<totalRays+1 ; i++) { if(i == totalRays) { noiseRadius = (ofNoise(noiseSeeds[0]) * stepSize) + radius; } else { noiseRadius = (ofNoise(noiseSeeds[i]) * stepSize) + radius; } pointLocation.x = noiseRadius * cos(angleStep*i); pointLocation.y = noiseRadius * sin(angleStep*i); ofCurveVertex(pointLocation); noiseSeeds[i] += 0.01; } noiseRadius = (ofNoise(noiseSeeds[noiseSeeds.size()]) * stepSize) + radius; pointLocation.x = noiseRadius * cos(angleStep*(noiseSeeds.size())); pointLocation.y = noiseRadius * sin(angleStep*(noiseSeeds.size())); ofCurveVertex(pointLocation); ofEndShape(); // ofSetColor(255, 215, 13); // ofDrawCircle(0, 0, 300); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
25.125
79
0.439366
c-c-c
c9c28ee01b835ed81984137a1913dbfd8ee0849f
4,736
hh
C++
core/transformation/TransformationFunctionArgs.hh
gnafit/gna
c1a58dac11783342c97a2da1b19c97b85bce0394
[ "MIT" ]
5
2019-10-14T01:06:57.000Z
2021-02-02T16:33:06.000Z
core/transformation/TransformationFunctionArgs.hh
gnafit/gna
c1a58dac11783342c97a2da1b19c97b85bce0394
[ "MIT" ]
null
null
null
core/transformation/TransformationFunctionArgs.hh
gnafit/gna
c1a58dac11783342c97a2da1b19c97b85bce0394
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include "Args.hh" #include "Rets.hh" #include "Ints.hh" #include "Atypes.hh" #include "Rtypes.hh" #include "Itypes.hh" namespace ParametrizedTypes{ class ParametrizedBase; } namespace TransformationTypes { template<typename FloatType,typename SizeType> class GPUFunctionArgsT; template<typename SourceType,typename SinkType> class EntryT; /** * @brief Transformation Function arguments. * * FunctionArgs instance is pased to the Function and contains the necessary data: * - inputs; * - outputs; * - internal storage. * * Inputs are available read-only. * * @author Maxim Gonchar * @date 07.2018 */ template<typename SourceFloatType, typename SinkFloatType> class FunctionArgsT { public: using EntryType = EntryT<SourceFloatType,SinkFloatType>; using FunctionArgsType = FunctionArgsT<SourceFloatType,SinkFloatType>; using GPUFunctionArgsType = GPUFunctionArgsT<SourceFloatType, size_t>; using GPUFunctionArgsPtr = std::unique_ptr<GPUFunctionArgsType>; using ArgsType = ArgsT<SourceFloatType,SinkFloatType>; using RetsType = RetsT<SourceFloatType,SinkFloatType>; using IntsType = IntsT<SourceFloatType,SinkFloatType>; FunctionArgsT(EntryType* e) : args(e), rets(e), ints(e), m_entry(e) { } ///< Constructor. FunctionArgsT(const FunctionArgsType& other) : FunctionArgsT(other.m_entry) { } ///< Copy constructor. ~FunctionArgsT(); ArgsType args; ///< arguments, or transformation inputs (read-only) RetsType rets; ///< return values, or transformation outputs (writable) IntsType ints; ///< preallocated data arrays for the transformation's internal usage (writable) #ifdef GNA_CUDA_SUPPORT GPUFunctionArgsPtr gpu=nullptr; ///< GPU function arguments void requireGPU(); ///< Initialize GPU function arguments #endif void updateTypes(); ///< Update arguments and types size_t getMapping(size_t input){ return m_entry->mapping[input]; } void readVariables(ParametrizedTypes::ParametrizedBase* parbase); /// Read variables from ParametrizedBase instance void readVariables(); /// Read variables from previous ParametrizedBase instance private: EntryType *m_entry=nullptr; ///< Entry instance to access Sinks. ParametrizedTypes::ParametrizedBase* m_parbase=nullptr; ///< Access to the relevant ParametrizedBase instance }; /** * @brief Transformation TypesFunction arguments. * * TypesFunctionArgs instance is pased to the typesFunction and contains the necessary data types: * - inputs' data types; * - outputs' data types; * - internal storages' data types. * * The input data types are available read-only. * * @author Maxim Gonchar * @date 07.2018 */ template<typename SourceFloatType, typename SinkFloatType> struct TypesFunctionArgsT { using EntryType = EntryT<SourceFloatType,SinkFloatType>; using Atypes = AtypesT<SourceFloatType,SinkFloatType>; using Rtypes = RtypesT<SourceFloatType,SinkFloatType>; using Itypes = ItypesT<SourceFloatType,SinkFloatType>; TypesFunctionArgsT(EntryType* e) : args(e), rets(e), ints(e) { } ///< Constructor. Atypes args; ///< arguments'/inputs' data types (read-only) Rtypes rets; ///< return values'/outputs' data types (writable) Itypes ints; ///< preallocated storage's data types (writable) }; /** * @brief Transformation StorageTypesFunction arguments. * * TypesFunctionArgs instance is pased to the typesFunction and contains the necessary data types: * - inputs' data types; * - outputs' data types; * - internal storages' data types. * * The input and output data types are available read-only. The StorageTypesFunction may only create * and modify the information about the internal storage requirements. * * @author Maxim Gonchar * @date 07.2018 */ template<typename SourceFloatType, typename SinkFloatType> struct StorageTypesFunctionArgsT { using TypesFunctionArgsType = TypesFunctionArgsT<SourceFloatType,SinkFloatType>; StorageTypesFunctionArgsT(TypesFunctionArgsType& fargs) : args(fargs.args), rets(fargs.rets), ints(fargs.ints) { } ///< Constructor. AtypesT<SourceFloatType,SinkFloatType>& args; ///< arguments'/inputs' data types (read-only) const RtypesT<SourceFloatType,SinkFloatType>& rets; ///< return values'/outputs' data types (read-only) ItypesT<SourceFloatType,SinkFloatType>& ints; ///< preallocated storage's data types (writable) }; }
39.798319
137
0.697846
gnafit
c9c52249096143bb02479851000731440129fcb4
7,430
cpp
C++
src/test/lang/ast/sigs/function_signatures_test.cpp
ludkinm/stan
c318114f875266f22c98cf0bebfff928653727cb
[ "CC-BY-3.0", "BSD-3-Clause" ]
null
null
null
src/test/lang/ast/sigs/function_signatures_test.cpp
ludkinm/stan
c318114f875266f22c98cf0bebfff928653727cb
[ "CC-BY-3.0", "BSD-3-Clause" ]
null
null
null
src/test/lang/ast/sigs/function_signatures_test.cpp
ludkinm/stan
c318114f875266f22c98cf0bebfff928653727cb
[ "CC-BY-3.0", "BSD-3-Clause" ]
null
null
null
#include <stan/lang/ast_def.cpp> #include <gtest/gtest.h> #include <cmath> #include <sstream> #include <string> #include <set> #include <vector> using stan::lang::bare_array_type; using stan::lang::bare_expr_type; using stan::lang::double_type; using stan::lang::expression; using stan::lang::function_signatures; using stan::lang::ill_formed_type; using stan::lang::int_type; using stan::lang::matrix_type; using stan::lang::row_vector_type; using stan::lang::vector_type; using stan::lang::void_type; using std::vector; std::vector<bare_expr_type> bare_expr_type_vec() { return std::vector<bare_expr_type>(); } std::vector<bare_expr_type> bare_expr_type_vec(const bare_expr_type& t1) { std::vector<bare_expr_type> etv; etv.push_back(t1); return etv; } std::vector<bare_expr_type> bare_expr_type_vec(const bare_expr_type& t1, const bare_expr_type& t2) { std::vector<bare_expr_type> etv; etv.push_back(t1); etv.push_back(t2); return etv; } std::vector<bare_expr_type> bare_expr_type_vec(const bare_expr_type& t1, const bare_expr_type& t2, const bare_expr_type& t3) { std::vector<bare_expr_type> etv; etv.push_back(t1); etv.push_back(t2); etv.push_back(t3); return etv; } TEST(lang_ast, function_signatures_log_sum_exp_1) { stan::lang::function_signatures& fs = stan::lang::function_signatures::instance(); std::stringstream error_msgs; EXPECT_EQ( bare_expr_type(double_type()), fs.get_result_type("log_sum_exp", bare_expr_type_vec(bare_array_type(double_type(), 1)), error_msgs)); } TEST(lang_ast, function_signatures_log_sum_exp_2) { stan::lang::function_signatures& fs = stan::lang::function_signatures::instance(); std::stringstream error_msgs; EXPECT_EQ(bare_expr_type(double_type()), fs.get_result_type( "log_sum_exp", bare_expr_type_vec(bare_expr_type(vector_type())), error_msgs)); } TEST(lang_ast, function_signatures_log_sum_exp_3) { stan::lang::function_signatures& fs = stan::lang::function_signatures::instance(); std::stringstream error_msgs; EXPECT_EQ( bare_expr_type(double_type()), fs.get_result_type("log_sum_exp", bare_expr_type_vec(bare_expr_type(row_vector_type())), error_msgs)); } TEST(lang_ast, function_signatures_log_sum_exp_4) { stan::lang::function_signatures& fs = stan::lang::function_signatures::instance(); std::stringstream error_msgs; EXPECT_EQ(bare_expr_type(double_type()), fs.get_result_type( "log_sum_exp", bare_expr_type_vec(bare_expr_type(matrix_type())), error_msgs)); } TEST(lang_ast, function_signatures_log_sum_exp_binary) { stan::lang::function_signatures& fs = stan::lang::function_signatures::instance(); std::stringstream error_msgs; EXPECT_EQ( bare_expr_type(double_type()), fs.get_result_type("log_sum_exp", bare_expr_type_vec(bare_expr_type(double_type()), bare_expr_type(double_type())), error_msgs)); } TEST(lang_ast, function_signatures_unary_vectorized_trunc_0) { stan::lang::function_signatures& fs = stan::lang::function_signatures::instance(); std::stringstream error_msgs; EXPECT_EQ(bare_expr_type(double_type()), fs.get_result_type("trunc", bare_expr_type_vec(double_type()), error_msgs)); } TEST(lang_ast, function_signatures_unary_vectorized_trunc_1) { stan::lang::function_signatures& fs = stan::lang::function_signatures::instance(); std::stringstream error_msgs; EXPECT_EQ(bare_expr_type(bare_array_type(double_type())), fs.get_result_type( "trunc", bare_expr_type_vec(bare_array_type(double_type())), error_msgs)); } TEST(lang_ast, function_signatures_unary_vectorized_trunc_8) { stan::lang::function_signatures& fs = stan::lang::function_signatures::instance(); std::stringstream error_msgs; EXPECT_EQ(bare_expr_type(bare_array_type(double_type(), 8)), fs.get_result_type( "trunc", bare_expr_type_vec(bare_array_type(double_type(), 8)), error_msgs)); } TEST(lang_ast, function_signatures_multi_normal_0) { stan::lang::function_signatures& fs = stan::lang::function_signatures::instance(); std::stringstream error_msgs; EXPECT_EQ( bare_expr_type(double_type()), fs.get_result_type( "multi_normal_log", bare_expr_type_vec(bare_array_type(vector_type()), bare_array_type(vector_type()), matrix_type()), error_msgs)); } TEST(lang_ast, function_signatures_multi_normal_cholesky_0) { stan::lang::function_signatures& fs = stan::lang::function_signatures::instance(); std::stringstream error_msgs; EXPECT_EQ( bare_expr_type(double_type()), fs.get_result_type( "multi_normal_cholesky_log", bare_expr_type_vec(bare_array_type(vector_type()), bare_array_type(vector_type()), matrix_type()), error_msgs)); } TEST(lang_ast, function_signatures_multi_normal_cholesky_1) { stan::lang::function_signatures& fs = stan::lang::function_signatures::instance(); std::stringstream error_msgs; EXPECT_EQ( bare_expr_type(double_type()), fs.get_result_type("multi_normal_cholesky_log", bare_expr_type_vec(bare_array_type(vector_type()), vector_type(), matrix_type()), error_msgs)); } TEST(lang_ast, function_signatures_add) { stan::lang::function_signatures& fs = stan::lang::function_signatures::instance(); std::stringstream error_msgs; EXPECT_EQ(bare_expr_type(double_type()), fs.get_result_type( "sqrt", bare_expr_type_vec(bare_expr_type(double_type())), error_msgs)); EXPECT_EQ(bare_expr_type(), fs.get_result_type("foo__", bare_expr_type_vec(), error_msgs)); EXPECT_EQ(bare_expr_type(), fs.get_result_type( "foo__", bare_expr_type_vec(bare_expr_type(double_type())), error_msgs)); // these next two conflict fs.add("bar__", bare_expr_type(double_type()), bare_expr_type(int_type()), bare_expr_type(double_type())); fs.add("bar__", bare_expr_type(double_type()), bare_expr_type(double_type()), bare_expr_type(int_type())); EXPECT_EQ(bare_expr_type(), fs.get_result_type("bar__", bare_expr_type_vec(bare_expr_type(int_type()), bare_expr_type(int_type())), error_msgs)); // after this, should be resolvable fs.add("bar__", bare_expr_type(int_type()), bare_expr_type(int_type()), bare_expr_type(int_type())); EXPECT_EQ(bare_expr_type(int_type()), fs.get_result_type("bar__", bare_expr_type_vec(bare_expr_type(int_type()), bare_expr_type(int_type())), error_msgs)); }
36.243902
80
0.646433
ludkinm
c9c5b730197b4f6f9e7e5653359ad7a3d30b83ec
1,756
cpp
C++
ui/src/gtk3/application.cpp
Berrysoft/XamlCpp
cc7da0cf83892ceb88926292b7c90b9f8da6128d
[ "MIT" ]
27
2020-01-02T07:40:57.000Z
2022-03-09T14:43:56.000Z
ui/src/gtk3/application.cpp
Berrysoft/XamlCpp
cc7da0cf83892ceb88926292b7c90b9f8da6128d
[ "MIT" ]
null
null
null
ui/src/gtk3/application.cpp
Berrysoft/XamlCpp
cc7da0cf83892ceb88926292b7c90b9f8da6128d
[ "MIT" ]
3
2020-05-21T07:02:08.000Z
2021-07-01T00:56:38.000Z
#include <gtk/gtk.h> #include <nowide/cstdlib.hpp> #include <shared/application.hpp> #include <xaml/ui/application.h> using namespace std; xaml_result xaml_application_impl::init(int argc, char** argv) noexcept { m_native_impl.m_outer = this; XAML_RETURN_IF_FAILED(xaml_event_new(&m_activate)); m_native_app.reset(gtk_application_new(nullptr, G_APPLICATION_FLAGS_NONE)); g_signal_connect(m_native_app.get(), "activate", G_CALLBACK(xaml_application_impl::on_activate_event), this); XAML_RETURN_IF_FAILED(xaml_vector_new(&m_cmd_lines)); for (int i = 0; i < argc; i++) { xaml_ptr<xaml_string> arg; XAML_RETURN_IF_FAILED(xaml_string_new_view(argv[i], &arg)); XAML_RETURN_IF_FAILED(m_cmd_lines->append(arg)); } return XAML_S_OK; } xaml_result xaml_application_impl::run(int* pres) noexcept { m_quit_value = g_application_run(G_APPLICATION(m_native_app.get()), 0, nullptr); *pres = m_quit_value; return XAML_S_OK; } xaml_result xaml_application_impl::quit(int value) noexcept { m_quit_value = value; g_application_quit(G_APPLICATION(m_native_app.get())); return XAML_S_OK; } xaml_result xaml_application_impl::get_theme(xaml_application_theme* ptheme) noexcept { char* theme_buffer = nowide::getenv("GTK_THEME"); string_view theme = theme_buffer ? theme_buffer : string_view{}; *ptheme = theme.ends_with(":dark") ? xaml_application_theme_dark : xaml_application_theme_light; return XAML_S_OK; } void xaml_application_impl::on_activate_event(GApplication*, xaml_application_impl* self) noexcept { xaml_ptr<xaml_event_args> args; XAML_ASSERT_SUCCEEDED(xaml_event_args_empty(&args)); XAML_ASSERT_SUCCEEDED(self->m_activate->invoke(self, args)); }
33.769231
113
0.753986
Berrysoft
c9c67a756ef95067ee069b6015d0a7eec895d146
3,247
cpp
C++
common/ffsutils.cpp
ISpillMyDrink/UEFITool
a4430e24e05154c1e9c9023f4ab487acd7310ca4
[ "BSD-2-Clause" ]
null
null
null
common/ffsutils.cpp
ISpillMyDrink/UEFITool
a4430e24e05154c1e9c9023f4ab487acd7310ca4
[ "BSD-2-Clause" ]
null
null
null
common/ffsutils.cpp
ISpillMyDrink/UEFITool
a4430e24e05154c1e9c9023f4ab487acd7310ca4
[ "BSD-2-Clause" ]
null
null
null
/* ffsutils.cpp Copyright (c) 2019, LongSoft. All rights reserved. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. */ #include "ffsutils.h" #include "utility.h" #include "ffs.h" namespace FfsUtils { USTATUS findFileRecursive(TreeModel *model, const UModelIndex index, const UString & hexPattern, const UINT8 mode, std::set<std::pair<UModelIndex, UModelIndex> > & files) { if (!index.isValid()) return U_SUCCESS; if (hexPattern.isEmpty()) return U_INVALID_PARAMETER; const char *hexPatternRaw = hexPattern.toLocal8Bit(); std::vector<UINT8> pattern, patternMask; if (!makePattern(hexPatternRaw, pattern, patternMask)) return U_INVALID_PARAMETER; // Check for "all substrings" pattern size_t count = 0; for (size_t i = 0; i < patternMask.size(); i++) if (patternMask[i] == 0) count++; if (count == patternMask.size()) return U_SUCCESS; bool hasChildren = (model->rowCount(index) > 0); for (int i = 0; i < model->rowCount(index); i++) { #if ((QT_VERSION_MAJOR == 5) && (QT_VERSION_MINOR < 6)) || (QT_VERSION_MAJOR < 5) findFileRecursive(model, index.child(i, index.column()), hexPattern, mode, files); #else findFileRecursive(model, index.model()->index(i, index.column(), index), hexPattern, mode, files); #endif } UByteArray data; if (hasChildren) { if (mode == SEARCH_MODE_HEADER) data = model->header(index); else if (mode == SEARCH_MODE_ALL) data = model->header(index) + model->body(index); } else { if (mode == SEARCH_MODE_HEADER) data = model->header(index); else if (mode == SEARCH_MODE_BODY) data = model->body(index); else data = model->header(index) + model->body(index); } const UINT8 *rawData = reinterpret_cast<const UINT8 *>(data.constData()); INTN offset = findPattern(pattern.data(), patternMask.data(), pattern.size(), rawData, data.size(), 0); // For patterns that cross header|body boundary, skip patterns entirely located in body, since // children search above has already found them. if (hasChildren && mode == SEARCH_MODE_ALL && offset >= model->header(index).size()) { offset = -1; } if (offset >= 0) { if (model->type(index) != Types::File) { UModelIndex ffs = model->findParentOfType(index, Types::File); if (model->type(index) == Types::Section && model->subtype(index) == EFI_SECTION_FREEFORM_SUBTYPE_GUID) files.insert(std::pair<UModelIndex, UModelIndex>(ffs, index)); else files.insert(std::pair<UModelIndex, UModelIndex>(ffs, UModelIndex())); } else { files.insert(std::pair<UModelIndex, UModelIndex>(index, UModelIndex())); } } return U_SUCCESS; } };
34.542553
170
0.642747
ISpillMyDrink
c9c7dc4290dab1e13270eb07feecd6dd4f90f5f8
1,022
cpp
C++
Advanced-Concepts/lambdas/properties/properties.cpp
Zayk01/Cplusplus-Concepts
cbe81abcd0776d7b331ab5e7dd8993926551cf87
[ "MIT" ]
null
null
null
Advanced-Concepts/lambdas/properties/properties.cpp
Zayk01/Cplusplus-Concepts
cbe81abcd0776d7b331ab5e7dd8993926551cf87
[ "MIT" ]
null
null
null
Advanced-Concepts/lambdas/properties/properties.cpp
Zayk01/Cplusplus-Concepts
cbe81abcd0776d7b331ab5e7dd8993926551cf87
[ "MIT" ]
null
null
null
#include <iostream> #include <list> #include <cassert> #include "propierties.hpp" using namespace std; int main() { /*Initializing variables in capture*/ auto mylambda = [c=list<int>{4,2}](){ //lambda for(auto v : c) cout << v ; }; mylambda(); // Output: 42 auto obj = variables_in_capture{}; //lambda as class obj(); // Output: 42 /*Mutating lambda member variables*/ auto by_value=[]() { auto v = 7; auto lambda = [v]() mutable { cout << v << " "; ++v; }; lambda(); //Output: 7 local v=8 lambda(); //Output: 8 local v=9 cout << v; //v=7 }; auto by_reference=[]() { auto v = 7; auto lambda = [&v]() { cout << v << " "; ++v; }; lambda(); //Output: 7 v:8 lambda(); //Output: 8 v:9 cout << v; //v:9 }; by_value(); //Output: 7,8,7 by_reference(); //Output: 7,8,9 return 0; }
18.925926
61
0.453033
Zayk01
c9c875b0dadba5adabd3b22688881c7105aef4bb
531
hpp
C++
commonFunctions.hpp
noah1510/modwo_leaves
a99c46268b89fda5c8b764aacdd3ad38dcfb19fe
[ "MIT" ]
null
null
null
commonFunctions.hpp
noah1510/modwo_leaves
a99c46268b89fda5c8b764aacdd3ad38dcfb19fe
[ "MIT" ]
null
null
null
commonFunctions.hpp
noah1510/modwo_leaves
a99c46268b89fda5c8b764aacdd3ad38dcfb19fe
[ "MIT" ]
null
null
null
// // commonFunctions.hpp // modwo_leaves // // Created by Tobias Höpp on 10.10.18. // Copyright © 2018 Tobias Höpp. All rights reserved. // #ifndef commonFunctions_hpp #define commonFunctions_hpp #include <stdio.h> #endif /* commonFunctions_hpp */ using namespace std; float durchschnitt(float* arr, int* laenge); float standartabweichung(float* arr, int laenge); //ggf. ebenfalls durchschnitt übergeben für bessere performance? int ableitung(float* arr, int laenge, float* result); float bfrequenz(float* arr, int laenge);
27.947368
114
0.753296
noah1510
c9d3b7e1fc79309ec11e2620ad2182f0fd8079c4
1,493
cpp
C++
bindings/ATL/pgelib2015/PGEFile/PGEFile/PGELevelData.cpp
ds-sloth/PGE-File-Library-STL
ed6dcae410bad6376e21fd5213d6952bdf7ae7cd
[ "MIT" ]
1
2018-09-02T09:51:31.000Z
2018-09-02T09:51:31.000Z
bindings/ATL/pgelib2015/PGEFile/PGEFile/PGELevelData.cpp
ds-sloth/PGE-File-Library-STL
ed6dcae410bad6376e21fd5213d6952bdf7ae7cd
[ "MIT" ]
4
2017-08-06T13:52:15.000Z
2021-07-21T04:32:15.000Z
bindings/ATL/pgelib2015/PGEFile/PGEFile/PGELevelData.cpp
ds-sloth/PGE-File-Library-STL
ed6dcae410bad6376e21fd5213d6952bdf7ae7cd
[ "MIT" ]
6
2017-03-23T15:26:06.000Z
2021-07-21T04:26:27.000Z
// PGELevelData.cpp: Implementierung von CPGELevelData #include "stdafx.h" #include "PGELevelData.h" // CPGELevelData STDMETHODIMP CPGELevelData::get_Stars(LONG* pVal) { *pVal = m_stars; return S_OK; } STDMETHODIMP CPGELevelData::put_Stars(LONG newVal) { m_stars = newVal; return S_OK; } STDMETHODIMP CPGELevelData::get_LevelName(BSTR* pVal) { return m_levelName.CopyTo(pVal); } STDMETHODIMP CPGELevelData::put_LevelName(BSTR newVal) { return m_levelName.AssignBSTR(newVal); } STDMETHODIMP CPGELevelData::get_Blocks(IPGELevelBlocks** pVal) { return m_blocks.CopyTo(pVal); } STDMETHODIMP CPGELevelData::get_BGOs(IPGELevelBGOs** pVal) { return m_bgos.CopyTo(pVal); } STDMETHODIMP CPGELevelData::get_Sections(IPGELevelSections** pVal) { return m_sections.CopyTo(pVal); } STDMETHODIMP CPGELevelData::get_PlayerPoints(IPGELevelPlayerPoints** pVal) { return m_player_points.CopyTo(pVal); } STDMETHODIMP CPGELevelData::get_NPCs(IPGELevelNPCs** pVal) { return m_npcs.CopyTo(pVal); } STDMETHODIMP CPGELevelData::get_Warps(IPGELevelWarps** pVal) { return m_warps.CopyTo(pVal); } STDMETHODIMP CPGELevelData::get_Events(IPGELevelEvents** pVal) { return m_events.CopyTo(pVal); } STDMETHODIMP CPGELevelData::get_PhysicalEnvironments(IPGELevelPhysicalEnvironments** pVal) { return m_physical_environments.CopyTo(pVal); } STDMETHODIMP CPGELevelData::get_Layers(IPGELevelLayers** pVal) { return m_layers.CopyTo(pVal); }
16.775281
90
0.758205
ds-sloth
c9d62922280e5c7e5df95c116ae667ac432052bb
3,894
hpp
C++
include/glw/Mesh.hpp
jarrettchisholm/glr
79a57b12e26fe84595e833cace3528cb9c82bc20
[ "WTFPL" ]
11
2015-08-19T23:15:41.000Z
2018-05-15T21:53:28.000Z
include/glw/Mesh.hpp
jarrettchisholm/glr
79a57b12e26fe84595e833cace3528cb9c82bc20
[ "WTFPL" ]
2
2015-05-21T06:37:24.000Z
2015-05-23T05:37:16.000Z
include/glw/Mesh.hpp
jarrettchisholm/glr
79a57b12e26fe84595e833cace3528cb9c82bc20
[ "WTFPL" ]
5
2016-10-31T08:02:15.000Z
2018-08-24T07:40:23.000Z
#ifndef MESH_H_ #define MESH_H_ #include <vector> #include <atomic> #include <GL/glew.h> #include <assimp/cimport.h> #include <assimp/scene.h> #include <assimp/postprocess.h> #include "IMesh.hpp" #include "shaders/IShaderProgram.hpp" namespace glr { namespace glw { class IOpenGlDevice; /** * A class that contains mesh data, and can load this data into OpenGL, as well as render that data * once it has been transferred. */ class Mesh : public IMesh { public: /** * Basic constructor. The creator of the Mesh will have to set the data, and then call * 'allocateVideoMemory()' and 'pushToVideoMemory()' before this mesh will render properly. */ Mesh(IOpenGlDevice* openGlDevice, std::string name); /** * Standard constructor. * * @param initialize If true, will initialize all of the resources required for this mesh. Otherwise, it will * just create the mesh and return it (without initializing it). */ Mesh(IOpenGlDevice* openGlDevice, std::string name, std::vector< glm::vec3 > vertices, std::vector< glm::vec3 > normals, std::vector< glm::vec2 > textureCoordinates, std::vector< glm::vec4 > colors, std::vector< VertexBoneData > vertexBoneData, BoneData boneData, bool initialize = true ); /** * Standard constructor. * * This type of Mesh does not have any bone data set by default. * * @param initialize If true, will initialize all of the resources required for this mesh. Otherwise, it will * just create the mesh and return it (without initializing it). */ Mesh(IOpenGlDevice* openGlDevice, std::string name, std::vector< glm::vec3 > vertices, std::vector< glm::vec3 > normals, std::vector< glm::vec2 > textureCoordinates, std::vector< glm::vec4 > colors, bool initialize = true ); virtual ~Mesh(); virtual void render(); virtual BoneData& getBoneData(); virtual void allocateVideoMemory(); virtual void pushToVideoMemory(); virtual void pullFromVideoMemory(); virtual void freeVideoMemory(); virtual bool isVideoMemoryAllocated() const; virtual void loadLocalData(); virtual void freeLocalData(); virtual bool isLocalDataLoaded() const; virtual bool isDirty() const; virtual const std::string& getName() const; void setName(std::string name); void setVertices(std::vector< glm::vec3 > vertices); void setNormals(std::vector< glm::vec3 > normals); void setTextureCoordinates(std::vector< glm::vec2 > textureCoordinates); void setColors(std::vector< glm::vec4 > colors); void setVertexBoneData(std::vector< VertexBoneData > vertexBoneData); std::vector< glm::vec3 >& getVertices(); std::vector< glm::vec3 >& getNormals(); std::vector< glm::vec2 >& getTextureCoordinates(); std::vector< glm::vec4 >& getColors(); std::vector< VertexBoneData >& getVertexBoneData(); virtual void serialize(const std::string& filename); virtual void serialize(serialize::TextOutArchive& outArchive); virtual void deserialize(const std::string& filename); virtual void deserialize(serialize::TextInArchive& inArchive); protected: IOpenGlDevice* openGlDevice_; std::string name_; std::vector< glm::vec3 > vertices_; std::vector< glm::vec3 > normals_; std::vector< glm::vec2 > textureCoordinates_; std::vector< glm::vec4 > colors_; std::vector< VertexBoneData > vertexBoneData_; BoneData boneData_; glm::detail::uint32 vaoId_; glm::detail::uint32 vboIds_[5]; std::atomic<bool> isLocalDataLoaded_; std::atomic<bool> isVideoMemoryAllocated_; std::atomic<bool> isDirty_; glm::detail::uint32 currentNumberOfVertices_ = 0; glm::detail::uint32 currentVerticesSpaceAllocated_ = 0; std::string textureFileName_; private: /** * Required by serialization. */ Mesh(); friend class boost::serialization::access; template<class Archive> void inline serialize(Archive& ar, const unsigned int version); }; } } #include "Mesh.inl" #endif /* MESH_H_ */
26.489796
111
0.724448
jarrettchisholm
c9df8e869ae2ae7d357ee40f634e6e3e72d70df5
1,985
cpp
C++
src/viewer.cpp
cfsd/cfsd18-visualization
e43d20d4b5312ef5e39b92184e0bb2b9476bda42
[ "BSD-3-Clause" ]
null
null
null
src/viewer.cpp
cfsd/cfsd18-visualization
e43d20d4b5312ef5e39b92184e0bb2b9476bda42
[ "BSD-3-Clause" ]
1
2018-10-20T12:08:52.000Z
2018-10-20T12:08:52.000Z
src/viewer.cpp
cfsd/cfsd18-visualization
e43d20d4b5312ef5e39b92184e0bb2b9476bda42
[ "BSD-3-Clause" ]
null
null
null
#include "viewer.hpp" #include <pangolin/pangolin.h> Viewer::Viewer(std::map<std::string,std::string> commandlineArgs, Drawer &drawer) : m_drawer(drawer){ std::cout << commandlineArgs.count("cid") << std::endl; } void Viewer::Run(){ pangolin::CreateWindowAndBind("Path Viewer",1024,768); // 3D Mouse handler requires depth testing to be enabled glEnable(GL_DEPTH_TEST); // Issue specific OpenGl we might need glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); pangolin::CreatePanel("menu").SetBounds(0.0,1.0,0.0,pangolin::Attach::Pix(175)); pangolin::Var<bool> menuShowAttention("menu.ShowAttention",true,true); pangolin::Var<bool> menuShowDetectCones("menu.ShowDetectCones",true,true); pangolin::Var<bool> menuShowSurfaces("menu.ShowSurfaces",true,true); pangolin::Var<bool> menuShowAimpoint("menu.ShowAimPoint",true,true); pangolin::Var<bool> menuExit("menu.Exit",false,false); pangolin::OpenGlRenderState s_cam( pangolin::ProjectionMatrix(1024,768,2000,2000,512,389,0.1,1000), pangolin::ModelViewLookAt(0,-10,10, 0,0,0,1.0,0.0, 0.0) ); pangolin::View& d_cam = pangolin::CreateDisplay() .SetBounds(0.0, 1.0, pangolin::Attach::Pix(175), 1.0, -1024.0f/768.0f) .SetHandler(new pangolin::Handler3D(s_cam)); pangolin::OpenGlMatrix Twc; Twc.SetIdentity(); while(1){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); d_cam.Activate(s_cam); glClearColor(1.0f,1.0f,1.0f,1.0f); //m_drawer.drawCurrentCar(Twc); if(menuShowAttention) m_drawer.drawAttention(); if(menuShowDetectCones) m_drawer.drawDetectCone(); if(menuShowSurfaces) m_drawer.drawSurfaces(true,true); if(menuShowAimpoint) m_drawer.drawAimPoint(); pangolin::FinishFrame(); if(menuExit) break; } }
32.540984
84
0.648866
cfsd
c9dfd52eb5bdae300acc4d132908d29af3244d68
385
hxx
C++
incl/Handler.hxx
TumbleOwlee/win-rearrange-cxx
b72b15c3c555b6b1afea4478c973c151107cd67a
[ "MIT" ]
1
2021-11-13T00:05:19.000Z
2021-11-13T00:05:19.000Z
incl/Handler.hxx
TumbleOwlee/win-rearrange-cxx
b72b15c3c555b6b1afea4478c973c151107cd67a
[ "MIT" ]
null
null
null
incl/Handler.hxx
TumbleOwlee/win-rearrange-cxx
b72b15c3c555b6b1afea4478c973c151107cd67a
[ "MIT" ]
null
null
null
#ifndef HXX_HANDLER #define HXX_HANDLER #include "Config.hxx" #include "Command.hxx" #include <atomic> #include <thread> class Handler { public: Handler(Config& config); void start(); void stop(); private: std::atomic_bool m_stop; Config& m_config; std::unique_ptr<std::thread> m_thread; std::vector<Command*> m_commands; void run(); }; #endif
13.275862
42
0.664935
TumbleOwlee
5187140d94d0aa3938739fec2d7897157e236a0b
9,857
cpp
C++
src/ImGui/imgui_impl_gateware.cpp
dgramirez/vkPortfolio
a26fea81a640477437ec74ca0ce28e1848d3ecf0
[ "MIT" ]
null
null
null
src/ImGui/imgui_impl_gateware.cpp
dgramirez/vkPortfolio
a26fea81a640477437ec74ca0ce28e1848d3ecf0
[ "MIT" ]
null
null
null
src/ImGui/imgui_impl_gateware.cpp
dgramirez/vkPortfolio
a26fea81a640477437ec74ca0ce28e1848d3ecf0
[ "MIT" ]
null
null
null
// dear imgui: Platform Binding for Gateware (64 bit applications only) // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // Implemented features: // [X] Just the Base Stuff // [ ] Works just as well with Linux // [ ] Works just as well with Mac #include "imgui.h" #include "imgui_impl_gateware.h" #include "Gateware.h" // Gateware Data static GW::SYSTEM::GWindow g_GWindow; static GW::INPUT::GBufferedInput g_GBufferedInput; static GW::CORE::GEventReceiver g_GBIReceiver; static GW::INPUT::GInput g_GInput; static unsigned long long g_Time = 0; static unsigned long long g_TicksPerSecond = 0; static ImGuiMouseCursor g_LastMouseCursor = ImGuiMouseCursor_COUNT; static bool g_HasGamepad = false; static bool g_WantUpdateHasGamepad = true; //Helper Functions void AddCharacter(const uint32_t& _data); //Functions bool ImGui_ImplGateware_Init(void* gwindow) { g_GWindow = *(static_cast<GW::SYSTEM::GWindow*>(gwindow)); //Setup back-end capabilities flag ImGuiIO& io = ImGui::GetIO(); io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) io.BackendPlatformName = "imgui_impl_gateware"; //Get Width and Heigh uint32_t w, h; g_GWindow.GetClientWidth(w); g_GWindow.GetClientHeight(h); io.DisplaySize = ImVec2((float)w, (float)h); // Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array that we will update during the application lifetime. io.KeyMap[ImGuiKey_Tab] = G_KEY_TAB; io.KeyMap[ImGuiKey_LeftArrow] = G_KEY_LEFT; io.KeyMap[ImGuiKey_RightArrow] = G_KEY_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = G_KEY_UP; io.KeyMap[ImGuiKey_DownArrow] = G_KEY_DOWN; io.KeyMap[ImGuiKey_PageUp] = G_KEY_PAGEUP; io.KeyMap[ImGuiKey_PageDown] = G_KEY_PAGEDOWN; io.KeyMap[ImGuiKey_Home] = G_KEY_HOME; io.KeyMap[ImGuiKey_End] = G_KEY_END; io.KeyMap[ImGuiKey_Insert] = G_KEY_INSERT; io.KeyMap[ImGuiKey_Delete] = G_KEY_DELETE; io.KeyMap[ImGuiKey_Backspace] = G_KEY_BACKSPACE; io.KeyMap[ImGuiKey_Space] = G_KEY_SPACE; io.KeyMap[ImGuiKey_Enter] = G_KEY_ENTER; io.KeyMap[ImGuiKey_Escape] = G_KEY_ESCAPE; io.KeyMap[ImGuiKey_KeyPadEnter] = G_KEY_NUMPAD_PLUS; io.KeyMap[ImGuiKey_A] = G_KEY_A; io.KeyMap[ImGuiKey_C] = G_KEY_C; io.KeyMap[ImGuiKey_V] = G_KEY_V; io.KeyMap[ImGuiKey_X] = G_KEY_X; io.KeyMap[ImGuiKey_Y] = G_KEY_Y; io.KeyMap[ImGuiKey_Z] = G_KEY_Z; #if _WIN32 GW::SYSTEM::UNIVERSAL_WINDOW_HANDLE uwh; g_GWindow.GetWindowHandle(uwh); io.ImeWindowHandle = uwh.window; #endif //Create Callback for GBufferedInput g_GInput.Create(g_GWindow); g_GBufferedInput.Create(g_GWindow); g_GBIReceiver.Create(g_GBufferedInput, [&]() { //GEvent Setup [Getting Events] GW::GEvent gEvent; g_GBIReceiver.Pop(gEvent); //Reading GWindow's Events & Data GW::INPUT::GBufferedInput::Events Event; GW::INPUT::GBufferedInput::EVENT_DATA EventData; gEvent.Read(Event, EventData); //Do Events bool isFocus; g_GWindow.IsFocus(isFocus); if (isFocus) { switch (Event) { case GW::INPUT::GBufferedInput::Events::KEYPRESSED: if (EventData.data < 256) io.KeysDown[EventData.data] = 1; io.KeyCtrl = io.KeysDown[G_KEY_CONTROL]; io.KeyShift = io.KeysDown[G_KEY_LEFTSHIFT] || io.KeysDown[G_KEY_RIGHTSHIFT]; io.KeyAlt = io.KeysDown[G_KEY_LEFTALT] || io.KeysDown[G_KEY_RIGHTALT]; AddCharacter(EventData.data); break; case GW::INPUT::GBufferedInput::Events::KEYRELEASED: if (EventData.data < 256) io.KeysDown[EventData.data] = 0; io.KeyCtrl = io.KeysDown[G_KEY_CONTROL]; io.KeyShift = io.KeysDown[G_KEY_LEFTSHIFT] || io.KeysDown[G_KEY_RIGHTSHIFT]; io.KeyAlt = io.KeysDown[G_KEY_LEFTALT] || io.KeysDown[G_KEY_RIGHTALT]; break; case GW::INPUT::GBufferedInput::Events::BUTTONPRESSED: if (EventData.data == G_BUTTON_LEFT) io.MouseDown[0] = true; if (EventData.data == G_BUTTON_RIGHT) io.MouseDown[1] = true; if (EventData.data == G_BUTTON_MIDDLE) io.MouseDown[2] = true; break; case GW::INPUT::GBufferedInput::Events::BUTTONRELEASED: if (EventData.data == G_BUTTON_LEFT) io.MouseDown[0] = false; if (EventData.data == G_BUTTON_RIGHT) io.MouseDown[1] = false; if (EventData.data == G_BUTTON_MIDDLE) io.MouseDown[2] = false; break; case GW::INPUT::GBufferedInput::Events::MOUSESCROLL: if (EventData.data == G_MOUSE_SCROLL_UP) io.MouseWheel += 1; else io.MouseWheel -= 1; break; } } }); return true; } IMGUI_IMPL_API void ImGui_ImplGateware_Shutdown() { g_GBIReceiver = nullptr; g_GBufferedInput = nullptr; g_GWindow = nullptr; } IMGUI_IMPL_API void ImGui_ImplGateware_NewFrame(const float& dt) { ImGuiIO& io = ImGui::GetIO(); IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer back-end. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame()."); // Setup display size (every frame to accommodate for window resizing) uint32_t w, h; g_GWindow.GetClientWidth(w); g_GWindow.GetClientHeight(h); io.DisplaySize = ImVec2((float)w, (float)h); // Setup time step io.DeltaTime = dt; // Update OS Mouse Position bool isFocus; g_GWindow.IsFocus(isFocus); if (isFocus) g_GInput.GetMousePosition(io.MousePos.x, io.MousePos.y); } void AddCharacter(const uint32_t& _data) { ImGuiIO& io = ImGui::GetIO(); uint32_t capital = 32 * io.KeyShift; switch (_data) { case G_KEY_A: io.AddInputCharacter('a' ^ capital); break; case G_KEY_B: io.AddInputCharacter('b' ^ capital); break; case G_KEY_C: io.AddInputCharacter('c' ^ capital); break; case G_KEY_D: io.AddInputCharacter('d' ^ capital); break; case G_KEY_E: io.AddInputCharacter('e' ^ capital); break; case G_KEY_F: io.AddInputCharacter('f' ^ capital); break; case G_KEY_G: io.AddInputCharacter('g' ^ capital); break; case G_KEY_H: io.AddInputCharacter('h' ^ capital); break; case G_KEY_I: io.AddInputCharacter('i' ^ capital); break; case G_KEY_J: io.AddInputCharacter('j' ^ capital); break; case G_KEY_K: io.AddInputCharacter('k' ^ capital); break; case G_KEY_L: io.AddInputCharacter('l' ^ capital); break; case G_KEY_M: io.AddInputCharacter('m' ^ capital); break; case G_KEY_N: io.AddInputCharacter('n' ^ capital); break; case G_KEY_O: io.AddInputCharacter('o' ^ capital); break; case G_KEY_P: io.AddInputCharacter('p' ^ capital); break; case G_KEY_Q: io.AddInputCharacter('q' ^ capital); break; case G_KEY_R: io.AddInputCharacter('r' ^ capital); break; case G_KEY_S: io.AddInputCharacter('s' ^ capital); break; case G_KEY_T: io.AddInputCharacter('t' ^ capital); break; case G_KEY_U: io.AddInputCharacter('u' ^ capital); break; case G_KEY_V: io.AddInputCharacter('v' ^ capital); break; case G_KEY_W: io.AddInputCharacter('w' ^ capital); break; case G_KEY_X: io.AddInputCharacter('x' ^ capital); break; case G_KEY_Y: io.AddInputCharacter('y' ^ capital); break; case G_KEY_Z: io.AddInputCharacter('z' ^ capital); break; case G_KEY_0: if (capital) io.AddInputCharacter(')'); else io.AddInputCharacter('0'); break; case G_KEY_1: if (capital) io.AddInputCharacter('!'); else io.AddInputCharacter('1'); break; case G_KEY_2: if (capital) io.AddInputCharacter('@'); else io.AddInputCharacter('2'); break; case G_KEY_3: if (capital) io.AddInputCharacter('#'); else io.AddInputCharacter('3'); break; case G_KEY_4: if (capital) io.AddInputCharacter('$'); else io.AddInputCharacter('4'); break; case G_KEY_5: if (capital) io.AddInputCharacter('%'); else io.AddInputCharacter('5'); break; case G_KEY_6: if (capital) io.AddInputCharacter('^'); else io.AddInputCharacter('6'); break; case G_KEY_7: if (capital) io.AddInputCharacter('&'); else io.AddInputCharacter('7'); break; case G_KEY_8: if (capital) io.AddInputCharacter('*'); else io.AddInputCharacter('8'); break; case G_KEY_9: if (capital) io.AddInputCharacter('('); else io.AddInputCharacter('9'); break; case G_KEY_ADD: io.AddInputCharacter('+'); break; case G_KEY_MULTIPLY: io.AddInputCharacter('*'); break; case G_KEY_DIVIDE: io.AddInputCharacter('/'); break; case G_KEY_MINUS: if (capital) io.AddInputCharacter('_'); else io.AddInputCharacter('-'); break; case G_KEY_EQUALS: if (capital) io.AddInputCharacter('+'); else io.AddInputCharacter('='); break; case G_KEY_BRACKET_OPEN: if (capital) io.AddInputCharacter('{'); else io.AddInputCharacter('['); break; case G_KEY_BRACKET_CLOSE: if (capital) io.AddInputCharacter('}'); else io.AddInputCharacter(']'); break; case G_KEY_COLON: if (capital) io.AddInputCharacter(':'); else io.AddInputCharacter(';'); break; case G_KEY_QUOTE: if (capital) io.AddInputCharacter('"'); else io.AddInputCharacter('\''); break; case G_KEY_TILDE: if (capital) io.AddInputCharacter('~'); else io.AddInputCharacter('`'); break; case G_KEY_BACKSLASH: if (capital) io.AddInputCharacter('|'); else io.AddInputCharacter('\\'); break; case G_KEY_COMMA: if (capital) io.AddInputCharacter('<'); else io.AddInputCharacter(','); break; case G_KEY_PERIOD: if (capital) io.AddInputCharacter('>'); else io.AddInputCharacter('.'); break; case G_KEY_FOWARDSLASH: if (capital) io.AddInputCharacter('?'); else io.AddInputCharacter('/'); break; case G_KEY_SPACE: io.AddInputCharacter(' '); break; case G_KEY_NUMPAD_MINUS: io.AddInputCharacter('-'); break; case G_KEY_NUMPAD_PLUS: io.AddInputCharacter('+'); break; } }
25.470284
189
0.703967
dgramirez
518d7cbea2bd353743e8337d63f38c3ef6a7c1e8
181
hh
C++
parser/parser.hh
jez/ragel-bison-parser-sandbox
6663d1887472eda9569d507356e26c30d2c25d8a
[ "BlueOak-1.0.0" ]
2
2020-09-12T15:45:26.000Z
2021-11-01T19:21:23.000Z
parser/parser.hh
jez/ragel-bison-parser-sandbox
6663d1887472eda9569d507356e26c30d2c25d8a
[ "BlueOak-1.0.0" ]
null
null
null
parser/parser.hh
jez/ragel-bison-parser-sandbox
6663d1887472eda9569d507356e26c30d2c25d8a
[ "BlueOak-1.0.0" ]
1
2021-07-18T22:52:05.000Z
2021-07-18T22:52:05.000Z
#pragma once #include "parser/driver.hh" #include "parser/parser_impl.h" namespace sandbox::parser { std::unique_ptr<Node> parse(std::string_view source, bool trace = false); }
16.454545
73
0.740331
jez
51903a1fa5d660f3f9a470bcba3008aa9ce4dcd0
1,374
cpp
C++
src/services/robot_config.cpp
simwijs/naoqi_driver
89b00459dc517f8564b1d7092eb36a3fc68a7096
[ "Apache-2.0" ]
null
null
null
src/services/robot_config.cpp
simwijs/naoqi_driver
89b00459dc517f8564b1d7092eb36a3fc68a7096
[ "Apache-2.0" ]
null
null
null
src/services/robot_config.cpp
simwijs/naoqi_driver
89b00459dc517f8564b1d7092eb36a3fc68a7096
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2015 Aldebaran * * 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 "robot_config.hpp" #include "../helpers/driver_helpers.hpp" namespace naoqi { namespace service { RobotConfigService::RobotConfigService( const std::string& name, const std::string& topic, const qi::SessionPtr& session ) : name_(name), topic_(topic), session_(session) {} void RobotConfigService::reset( rclcpp::Node* node ) { service_ = node->create_service<naoqi_bridge_msgs::srv::GetRobotInfo>( topic_, std::bind(&RobotConfigService::callback, this, std::placeholders::_1, std::placeholders::_2)); } void RobotConfigService::callback( const std::shared_ptr<naoqi_bridge_msgs::srv::GetRobotInfo::Request> req, std::shared_ptr<naoqi_bridge_msgs::srv::GetRobotInfo::Response> resp ) { resp->info = helpers::driver::getRobotInfo(session_); } } }
29.234043
179
0.740175
simwijs
51951edf6e30ed37fee4dc85551a612e15b2eee8
1,475
cpp
C++
0898-Leftmost One/0898-Leftmost One.cpp
akekho/LintCode
2d31f1ec092d89e70d5059c7fb2df2ee03da5981
[ "MIT" ]
77
2017-12-30T13:33:37.000Z
2022-01-16T23:47:08.000Z
0801-0900/0898-Leftmost One/0898-Leftmost One.cpp
jxhangithub/LintCode-1
a8aecc65c47a944e9debad1971a7bc6b8776e48b
[ "MIT" ]
1
2018-05-14T14:15:40.000Z
2018-05-14T14:15:40.000Z
0801-0900/0898-Leftmost One/0898-Leftmost One.cpp
jxhangithub/LintCode-1
a8aecc65c47a944e9debad1971a7bc6b8776e48b
[ "MIT" ]
39
2017-12-07T14:36:25.000Z
2022-03-10T23:05:37.000Z
class Solution { public: /** * @param arr: The 2-dimension array * @return: Return the column the leftmost one is located */ int getColumn(vector<vector<int>> &arr) { // Write your code here int m = arr.size(); int n = arr[0].size(); int left = n; for (int i = 0; i < m; ++i) { int start = 0, end = n - 1; while (start < end) { int mid = start + (end - start) / 2; if (arr[i][mid]) { end = mid; } else { start = mid + 1; } } if (arr[i][start]) { left = min(left, start); } } return left; } }; class Solution { public: /** * @param arr: The 2-dimension array * @return: Return the column the leftmost one is located */ int getColumn(vector<vector<int>> &arr) { // Write your code here int m = arr.size(); int n = arr[0].size(); int left = n; for (int j = 0; j < n; ++j) { if (arr[0][j]) { left = j; break; } } for (int i = 1; i < m; ++i) { if (arr[i][left] == 0) { continue; } while (left > 0 && arr[i][left - 1] == 1) { --left; } } return left; } };
24.583333
61
0.372203
akekho
5199e8dc83a51e34d03d96bbc4471ee82918843d
1,891
cpp
C++
src/chapter2_windowCreation.cpp
dokipen3d/OpenGLTutorial
31d7a67dc01079a2fb395b3c236f3e8d97b53c19
[ "BSL-1.0" ]
null
null
null
src/chapter2_windowCreation.cpp
dokipen3d/OpenGLTutorial
31d7a67dc01079a2fb395b3c236f3e8d97b53c19
[ "BSL-1.0" ]
null
null
null
src/chapter2_windowCreation.cpp
dokipen3d/OpenGLTutorial
31d7a67dc01079a2fb395b3c236f3e8d97b53c19
[ "BSL-1.0" ]
null
null
null
#include <array> #include <chrono> // current time #include <cmath> // sin & cos #include <cstdlib> // for std::exit() #include <fmt/core.h> // for fmt::print(). implements c++20 std::format // this is really important to make sure that glbindings does not clash with // glfw's opengl includes. otherwise we get ambigous overloads. #define GLFW_INCLUDE_NONE #include <GLFW/glfw3.h> #include <glbinding/gl/gl.h> #include <glbinding/glbinding.h> using namespace gl; using namespace std::chrono; int main() { auto startTime = system_clock::now(); const auto windowPtr = []() { if (!glfwInit()) { fmt::print("glfw didnt initialize!\n"); std::exit(EXIT_FAILURE); } glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, 1); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5); auto windowPtr = glfwCreateWindow( 1600, 900, "Chapter 2 - Window Creation", nullptr, nullptr); if (!windowPtr) { fmt::print("window doesn't exist\n"); glfwTerminate(); std::exit(EXIT_FAILURE); } glfwSetWindowPos(windowPtr, 520, 180); glfwMakeContextCurrent(windowPtr); glbinding::initialize(glfwGetProcAddress, false); return windowPtr; }(); std::array<GLfloat, 4> clearColour; while (!glfwWindowShouldClose(windowPtr)) { auto currentTime = duration<float>(system_clock::now() - startTime).count(); clearColour = {std::sin(currentTime) * 0.5f + 0.5f, std::cos(currentTime) * 0.5f + 0.5f, 0.2f, 1.0f}; glClearBufferfv(GL_COLOR, 0, clearColour.data()); glfwSwapBuffers(windowPtr); glfwPollEvents(); } glfwTerminate(); }
28.223881
76
0.626653
dokipen3d
519d6f863ce4ecaf9653f25466d6e310c8f6ee6c
6,808
cpp
C++
src/ppu.cpp
hyprd/ouri
701b3c0f536d999fb88695ac8a1631bc595fd402
[ "MIT" ]
null
null
null
src/ppu.cpp
hyprd/ouri
701b3c0f536d999fb88695ac8a1631bc595fd402
[ "MIT" ]
null
null
null
src/ppu.cpp
hyprd/ouri
701b3c0f536d999fb88695ac8a1631bc595fd402
[ "MIT" ]
null
null
null
#include "ppu.h" #include "helpers.h" PPU::PPU(MMU* mmu) { _mmu = mmu; LCDControl = _mmu->ReadMemory(0xFF40); LCDStatus = _mmu->ReadMemory(0xFF41); // SDL window = SDL_CreateWindow("ouri", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 160, 144, 0); renderer = SDL_CreateRenderer(window, -1, 0); texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB4444, SDL_TEXTUREACCESS_STREAMING, 160, 144); // LCDC enabledWindowBackground = false; // LCDC.0 enabledSprites = false; // LCDC.1 spriteHeight = 8; // LCDC.2 tilemapAreaBackground = 0; // LCDC.3 tileAddressingMode = false; // LCDC.4 enabledWindow = false; // LCDC.5 tilemapAreaWindow = 0; // LCDC.6 enabledLCD = false; // LCDC.7 currentScanline = 0; tileSize = 16; } PPU::~PPU() { SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); } void PPU::Update() { UpdateLCDC(); LoadPalettes(); UpdateRenderer(); // RenderBackground(); RenderSprites(); IncrementScanline(); } inline void PPU::IncrementScanline() { _mmu->SetMemory(0xFF44, _mmu->ReadMemory(0xFF44) + 1); } inline void PPU::UpdateRenderer() { SDL_UpdateTexture(texture, NULL, pixels, 2 * GB_WIDTH); SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); } uint8_t PPU::GetColour(int8_t colourValue, uint16_t palette) { uint8_t pal = _mmu->ReadMemory(palette); int upper = 0, lower = 0; // Bit 7 - 6 - Color for index 3 // Bit 5 - 4 - Color for index 2 // Bit 3 - 2 - Color for index 1 // Bit 1 - 0 - Color for index 0 switch(colourValue) { case 0: upper = 1; lower = 0; break; case 1: upper = 3; lower = 2; break; case 2: upper = 5; lower = 4; break; case 3: upper = 7; lower = 6; break; } // return colour from the palette // order -> [upper colour, lower colour] return ((pal >> upper) << 0x01 | (pal >> lower)); } inline void PPU::UpdateLCDC() { // LCDC functions LCDControl = _mmu->ReadMemory(0xFF40); enabledWindowBackground = LCDControl.test(0) ? true : false; enabledSprites = LCDControl.test(1) ? true : false; LCDControl.test(2) ? spriteHeight = 16 : spriteHeight = 8; tilemapAreaBackground = LCDControl.test(3) ? 0x9C00 : 0x9800; tileAddressingMode = LCDControl.test(4) ? true : false; enabledWindow = LCDControl.test(5) ? true : false; tilemapAreaWindow = LCDControl.test(6) ? 0x9800: 0x9C00; enabledLCD = LCDControl.test(7) ? true : false; } inline void PPU::LoadPalettes() { if(enabledWindowBackground) { std::bitset<8> BGP = _mmu->ReadMemory(0xFF47); backgroundPalette[0] = FormByte(BGP[0], BGP[1]); backgroundPalette[1] = FormByte(BGP[2], BGP[3]); backgroundPalette[2] = FormByte(BGP[4], BGP[5]); backgroundPalette[3] = FormByte(BGP[6], BGP[7]); } if(enabledSprites) { std::bitset<8> OBP0 = _mmu->ReadMemory(0xFF48); std::bitset<8> OBP1 = _mmu->ReadMemory(0xFF49); // lowest 2 bits are ignored as index 0 is transparent spritePaletteZero[1] = FormByte(OBP0[2], OBP0[3]); spritePaletteZero[2] = FormByte(OBP0[4], OBP0[5]); spritePaletteZero[3] = FormByte(OBP0[6], OBP0[7]); spritePaletteOne[1] = FormByte(OBP1[2], OBP1[3]); spritePaletteOne[2] = FormByte(OBP1[4], OBP1[5]); spritePaletteOne[3] = FormByte(OBP1[6], OBP1[7]); } } void PPU::RenderBackground() { currentScanline = _mmu->ReadMemory(0xFF44); if(currentScanline >= 144) return; uint16_t tileData = tileAddressingMode ? 0x8000 : 0x8800; uint8_t SCY = _mmu->ReadMemory(0xFF42); uint8_t SCX = _mmu->ReadMemory(0xFF43); uint8_t y = SCY + currentScanline; uint16_t row = static_cast<uint8_t>(y * 32); for(int pixel = 0; pixel < GB_WIDTH; pixel++) { uint8_t x = SCX + pixel; uint16_t col = x / 8; uint16_t address = tilemapAreaBackground + row + col; int16_t tileNumber; uint16_t tileAddress; if(tileAddressingMode) { tileNumber = static_cast<int8_t>(_mmu->ReadMemory(address)); tileAddress = tileData + ((tileNumber + signedOffset) * tileSize); } else { tileNumber = _mmu->ReadMemory(_mmu->ReadMemory(address)); tileAddress = tileData + (tileNumber * tileSize); } uint16_t addr = ((y % 8) * 2) + tileAddress; uint8_t upper = _mmu->ReadMemory(addr); uint8_t lower = _mmu->ReadMemory(addr + 1); uint8_t colourBit = ~((x % 8) - 7); uint8_t colourValue = (lower >> colourBit) << 0x01 | (upper >> colourBit) & 0x01; std::cout << "Colour value: " << std::bitset<8>(+colourValue) << std::endl; uint8_t colour = backgroundPalette[colourValue]; // std::cout << +colour << std::endl; //std::cout << std::hex << +colour << std::endl; pixels[x + (currentScanline * GB_WIDTH)] = colour; } } void PPU::RenderSprites() { uint16_t tilemap = 0x8000; // always 0x8000 for sprite rendering currentScanline = _mmu->ReadMemory(0xFF44); for(int oam = 0xFE00; oam < 0xFE9F; oam += 4) { uint8_t SY = _mmu->ReadMemory(oam); uint8_t SX = _mmu->ReadMemory(oam + 1); uint8_t index = _mmu->ReadMemory(oam + 2); std::bitset<8> attributes = _mmu->ReadMemory(oam + 3); uint16_t palette = attributes.test(4) ? 0xFF49 : 0xFF48; bool flipX = attributes.test(5); bool flipY = attributes.test(6); if(currentScanline < (SY + spriteHeight) && currentScanline >= SY) { uint16_t renderLine = flipY ? ~((currentScanline - SY) - spriteHeight) * 2 : (currentScanline - SY) * 2; uint8_t upper = _mmu->ReadMemory(tilemap + (index * tileSize) + renderLine); uint8_t lower= _mmu->ReadMemory(tilemap + (index * tileSize) + renderLine + 1); for(int tilepixel = 7; tilepixel >= 0; tilepixel--) { uint8_t pixel = ~(tilepixel) + 7 + SX; if(pixel < GB_WIDTH && currentScanline < 144) { // not in vblank int pos = flipX ? ~(tilepixel - 7) : tilepixel; uint8_t colourValue = (lower >> pos) << 0x01 | (upper >> pos) & 0x01; uint8_t colour = GetColour(colourValue, palette); //std::cout << colour << std::endl; pixels[pixel + (currentScanline * GB_WIDTH)] = colour; } } } } }
38.247191
116
0.584313
hyprd
519f5289a31077c5a9427b556642dc995416a9c4
9,244
cpp
C++
src/read_buffer.cpp
skovaka/nanopore_aligner
0ebd606d941db0bb82f14c17b453f27269a38716
[ "MIT" ]
null
null
null
src/read_buffer.cpp
skovaka/nanopore_aligner
0ebd606d941db0bb82f14c17b453f27269a38716
[ "MIT" ]
null
null
null
src/read_buffer.cpp
skovaka/nanopore_aligner
0ebd606d941db0bb82f14c17b453f27269a38716
[ "MIT" ]
null
null
null
/* MIT License * * Copyright (c) 2018 Sam Kovaka <skovaka@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "read_buffer.hpp" ReadBuffer::Params ReadBuffer::PRMS = { num_channels : 512, bp_per_sec : 450, sample_rate : 4000, chunk_time : 1.0, max_chunks : 1000000, }; const std::string Paf::PAF_TAGS[] = { "mt", //MAP_TIME "wt", //WAIT_TIME "qt", //QUEUE_TIME "rt", //RECEIVE_TIME "ch", //CHANNEL "ej", //UNBLOCK "st", //START_TIME "mx", //IN_SCAN "tr", //TOP_RATIO "mr", //MEAN_RATIO "en", //ENDED "kp", //KEEP "dl", //DELAY "sc", //SEED_CLUSTER "ce" //CONFIDENT_EVENT }; Paf::Paf() : is_mapped_(false), ended_(false), rd_name_(""), rf_name_(""), rd_st_(0), rd_en_(0), rd_len_(0), rf_st_(0), rf_en_(0), rf_len_(0), fwd_(false), matches_(0) {} Paf::Paf(const std::string &rd_name, u16 channel, u64 start_sample) : is_mapped_(false), ended_(false), rd_name_(rd_name), rf_name_(""), rd_st_(0), rd_en_(0), rd_len_(0), rf_st_(0), rf_en_(0), rf_len_(0), fwd_(false), matches_(0) { set_int(Tag::CHANNEL, channel); set_int(Tag::READ_START, start_sample); } bool Paf::is_mapped() const { return is_mapped_; } bool Paf::is_ended() const { return ended_; } void Paf::print_paf() const { std::cout << rd_name_ << "\t" << rd_len_ << "\t"; if (is_mapped_) { std::cout << rd_st_ << "\t" << rd_en_ << "\t" << (fwd_ ? '+' : '-') << "\t" << rf_name_ << "\t" << rf_len_ << "\t" << rf_st_ << "\t" << rf_en_ << "\t" << matches_ << "\t" << (rf_en_ - rf_st_ + 1) << "\t" << 255; } else { std::cout << "*" << "\t" << "*" << "\t" << "*" << "\t" << "*" << "\t" << "*" << "\t" << "*" << "\t" << "*" << "\t" << "*" << "\t" << "*" << "\t" << "255"; } for (auto t : int_tags_) { std::cout << std::fixed << "\t" << PAF_TAGS[t.first] << ":i:" << t.second; } for (auto t : float_tags_) { std::cout << std::fixed << "\t" << PAF_TAGS[t.first] << ":f:" << t.second; } for (auto t : str_tags_) { std::cout << "\t" << PAF_TAGS[t.first] << ":Z:" << t.second; } std::cout << "\n"; } void Paf::set_read_len(u64 rd_len) { rd_len_ = rd_len; } void Paf::set_ended() { ended_ = true; //set_int(Tag::ENDED, 1); } void Paf::set_mapped(u64 rd_st, u64 rd_en, std::string rf_name, u64 rf_st, u64 rf_en, u64 rf_len, bool fwd, u16 matches) { is_mapped_ = true; rd_st_ = rd_st; rd_en_ = rd_en; rf_name_ = rf_name; rf_st_ = rf_st; rf_en_ = rf_en; rf_len_ = rf_len; fwd_ = fwd; matches_ = matches; } void Paf::set_int(Tag t, int v) { int_tags_.emplace_back(t, v); } void Paf::set_float(Tag t, float v) { float_tags_.emplace_back(t, v); } void Paf::set_str(Tag t, std::string v) { str_tags_.emplace_back(t, v); } ReadBuffer::ReadBuffer() { chunk_count_ = 0; } //TODO: eliminate swap from mapper, rely on automatic move constructor void ReadBuffer::swap(ReadBuffer &r) { //std::swap(source_, r.source_); std::swap(channel_idx_, r.channel_idx_); std::swap(id_, r.id_); std::swap(number_, r.number_); std::swap(start_sample_, r.start_sample_); std::swap(raw_len_, r.raw_len_); std::swap(full_signal_, r.full_signal_); std::swap(chunk_, r.chunk_); std::swap(chunk_count_, r.chunk_count_); std::swap(chunk_processed_, r.chunk_processed_); std::swap(loc_, r.loc_); } void ReadBuffer::clear() { raw_len_ = 0; full_signal_.clear(); chunk_.clear(); chunk_count_ = 0; loc_ = Paf(); } ReadBuffer::ReadBuffer(const hdf5_tools::File &file, const std::string &raw_path, const std::string &ch_path) { for (auto a : file.get_attr_map(raw_path)) { if (a.first == "read_id") { id_ = a.second; } else if (a.first == "read_number") { number_ = atoi(a.second.c_str()); } else if (a.first == "start_time") { start_sample_ = atoi(a.second.c_str()); } } float cal_digit = 1, cal_range = 1, cal_offset = 0; for (auto a : file.get_attr_map(ch_path)) { if (a.first == "channel_number") { channel_idx_ = atoi(a.second.c_str()) - 1; } else if (a.first == "digitisation") { cal_digit = atof(a.second.c_str()); } else if (a.first == "range") { cal_range = atof(a.second.c_str()); } else if (a.first == "offset") { cal_offset = atof(a.second.c_str()); } } std::string sig_path = raw_path + "/Signal"; std::vector<i16> int_data; file.read(sig_path, int_data); chunk_count_ = (int_data.size() / PRMS.chunk_len()) + (int_data.size() % PRMS.chunk_len() != 0); if (chunk_count_ > PRMS.max_chunks) { chunk_count_ = PRMS.max_chunks; int_data.resize(chunk_count_ * PRMS.chunk_len()); } //full_signal_.reserve(int_data.size()); //full_signal_.assign(int_data.begin(), int_data.end()); for (u16 raw : int_data) { float calibrated = cal_range * (raw + cal_offset) / cal_digit; full_signal_.push_back(calibrated); } loc_ = Paf(id_, get_channel(), start_sample_); set_raw_len(full_signal_.size()); } ReadBuffer::ReadBuffer(Chunk &first_chunk) : //source_(Source::LIVE), channel_idx_(first_chunk.get_channel_idx()), id_(first_chunk.get_id()), number_(first_chunk.get_number()), start_sample_(first_chunk.get_start()), chunk_count_(1), chunk_processed_(false), loc_(id_, channel_idx_+1, start_sample_) { //loc_.set_int(Paf::Tag::RECEIVE_TIME, PARAMS.get_time());//TODO: FIX set_raw_len(first_chunk.size()); first_chunk.pop(chunk_); } void ReadBuffer::set_raw_len(u64 raw_len) { raw_len_ = raw_len; loc_.set_read_len(raw_len_ * PRMS.bp_per_samp()); } bool ReadBuffer::add_chunk(Chunk &c) { if (!chunk_processed_ || channel_idx_ != c.get_channel_idx() || number_ != c.get_number()) return false; chunk_processed_ = false; chunk_count_++; set_raw_len(raw_len_+c.size()); c.pop(chunk_); return true; } bool ReadBuffer::empty() const { return full_signal_.empty() && chunk_.empty(); } u16 ReadBuffer::get_channel() const { return channel_idx_+1; } u16 ReadBuffer::get_channel_idx() const { return channel_idx_; } bool ReadBuffer::chunks_maxed() const { return chunk_count_ >= PRMS.max_chunks; } u32 ReadBuffer::chunk_count() const { return chunk_count_; //full_signal_.size() / PRMS.chunk_len(); } Chunk ReadBuffer::get_chunk(u32 i) const { u32 st = i * PRMS.chunk_len(), ln = PRMS.chunk_len(); if (st > full_signal_.size()) { //return Chunk(); st = full_signal_.size(); } if (st+ln > full_signal_.size()) { ln = full_signal_.size() - st; } return Chunk(id_, get_channel(), number_, start_sample_+st, full_signal_, st, ln); } u32 ReadBuffer::get_chunks(std::vector<Chunk> &chunk_queue, bool real_start, u32 offs) const { u32 count = 0; u16 l = PRMS.chunk_len(); float start = real_start ? start_sample_ : 0; for (u32 i = offs; i+l <= full_signal_.size() && count < PRMS.max_chunks; i += l) { chunk_queue.emplace_back(id_, get_channel(), number_, start+i, full_signal_, i, l); count++; } return count; } bool operator< (const ReadBuffer &r1, const ReadBuffer &r2) { return r1.start_sample_ < r2.start_sample_; } u64 ReadBuffer::get_duration() const { return raw_len_; } u64 ReadBuffer::get_start() const { return start_sample_; } u64 ReadBuffer::get_end() const { return start_sample_ + raw_len_; }
26.563218
100
0.582432
skovaka
51a602bf0f8a0e7de444810c4bf3e6bccf2ffd3d
1,590
cpp
C++
inkcpp/string_table.cpp
2shady4u/inkcpp
3b1a90336ba56ed7dcac8c51f9860c93be358fe0
[ "MIT" ]
null
null
null
inkcpp/string_table.cpp
2shady4u/inkcpp
3b1a90336ba56ed7dcac8c51f9860c93be358fe0
[ "MIT" ]
null
null
null
inkcpp/string_table.cpp
2shady4u/inkcpp
3b1a90336ba56ed7dcac8c51f9860c93be358fe0
[ "MIT" ]
null
null
null
#include "string_table.h" namespace ink::runtime::internal { string_table::~string_table() { // Delete all allocated strings for (auto iter = _table.begin(); iter != _table.end(); ++iter) delete[] iter.key(); _table.clear(); } char* string_table::create(size_t length) { // allocate the string char* data = new char[length]; if (data == nullptr) return nullptr; // Add to the tree bool success = _table.insert(data, true); // TODO: Should it start as used? assert(success, "Duplicate string pointer in the string_table. How is that possible?"); if (!success) { delete[] data; return nullptr; } // Return allocated string return data; } void string_table::clear_usage() { // Clear usages for (auto iter = _table.begin(); iter != _table.end(); ++iter) iter.val() = false; } void string_table::mark_used(const char* string) { auto iter = _table.find(string); if (iter == _table.end()) return; // assert?? // set used flag *iter = true; } void string_table::gc() { // begin at the start auto iter = _table.begin(); const char* last = nullptr; while (iter != _table.end()) { // If the string is not used if (!*iter) { // Delete it delete[] iter.key(); _table.erase(iter); // Re-establish iterator at last position // TODO: BAD. We need inline delete that doesn't invalidate pointers if (last == nullptr) iter = _table.begin(); else { iter = _table.find(last); iter++; } continue; } // Next last = iter.key(); iter++; } } }
19.156627
89
0.61195
2shady4u
51a971772986f04f1c8657f45616104fedcb58a9
36,042
hpp
C++
lib/sept/Data.hpp
vdods/sept
08ee1faf1af4feb0dc440a3002eb8cc52681f946
[ "Apache-2.0" ]
null
null
null
lib/sept/Data.hpp
vdods/sept
08ee1faf1af4feb0dc440a3002eb8cc52681f946
[ "Apache-2.0" ]
null
null
null
lib/sept/Data.hpp
vdods/sept
08ee1faf1af4feb0dc440a3002eb8cc52681f946
[ "Apache-2.0" ]
null
null
null
// 2020.03.13 - Victor Dods #pragma once #include <any> #include <cassert> #include <exception> #include <functional> #include <iostream> #include <lvd/hash.hpp> #include <lvd/OstreamDelegate.hpp> #include <lvd/StaticAssociation_t.hpp> #include "sept/core.hpp" #include "sept/DataPrintCtx.hpp" #include "sept/RefTerm.hpp" #include <typeindex> #include <type_traits> // This template metafunction should be present in std::, but isn't. There is a private // implementation of it in the std implementation. template <typename T_> struct is_in_place_type : std::false_type { }; // Template specialization to make the metafunction return true for std::in_place_type_t<T_>. template <typename T_> struct is_in_place_type<std::in_place_type_t<T_>> : std::true_type { }; // Convenience alias for is_in_place_type<T_>::value. template <typename T_> inline constexpr bool is_in_place_type_v = is_in_place_type<T_>::value; namespace sept { // This is necessary to get the operator<< based printing of sept::Data to work. using lvd::operator<<; // Forward declaration of the type-specified Data. template <typename T_> class Data_t; // Forward declaration of print_data, with necessary forward declaration of Data. class Data; class DataPrintCtx; void print_data (std::ostream &out, DataPrintCtx &ctx, Data const &data); Data element_of_data (Data const &container, Data const &param); Data construct_inhabitant_of_data (Data const &type_data, Data const &argument_data); // Data is the fundamental unit of currency in sept; this is how each data node is represented in C++. // TODO: Should this be called Data or Node? Or what? // TODO: Maybe inherit std::any privately class Data : public std::any { public: // These are the same constructors std::any has, with the exception of the default constructor. // It should be impossible to create a Data without a value. Data () = delete; Data (Data const &other) : std::any(static_cast<std::any const &>(other)) { } Data (Data &&other) noexcept : std::any(std::move(static_cast<std::any &&>(other))) { } template < typename ValueType_, typename U_ = std::decay_t<ValueType_>, typename = std::enable_if_t< !std::is_base_of_v<Data,U_> && !is_in_place_type_v<ValueType_> && std::is_copy_constructible_v<U_> > > Data (ValueType_ &&value) : std::any(std::forward<ValueType_>(value)) { } template < typename ValueType_, typename... Args_, typename U_ = std::decay_t<ValueType_>, typename = std::enable_if_t< std::is_constructible_v<U_,Args_...> && std::is_copy_constructible_v<U_> // This one doesn't make sense, it should allow move-construction too. > > explicit Data (std::in_place_type_t<ValueType_>, Args_&&... args) : std::any(std::in_place_type_t<ValueType_>(), std::forward<Args_>(args)...) { } template < typename ValueType_, typename I_, typename... Args_, typename U_ = std::decay_t<ValueType_>, typename = std::enable_if_t< std::is_constructible_v<U_,std::initializer_list<I_>&, Args_...> && std::is_copy_constructible_v<U_> // Also not 100% sure about this one. > > explicit Data (std::in_place_type_t<ValueType_>, std::initializer_list<I_> il, Args_&&... args) : std::any(std::in_place_type_t<ValueType_>(), il, std::forward<Args_>(args)...) { } // These are the same operator= overloads as std::any has. Data &operator = (Data const &other) { std::any::operator=(static_cast<std::any const &>(other)); return *this; } Data &operator = (Data &&other) noexcept { std::any::operator=(std::move(static_cast<std::any &&>(other))); return *this; } template < typename ValueType_, typename U_ = std::decay_t<ValueType_>, typename = std::enable_if_t< !std::is_base_of_v<Data,U_> && // TODO: Change to "is subclass of Data" std::is_copy_constructible_v<U_> > > Data &operator = (ValueType_ &&value) { std::any::operator=(std::move(value)); return *this; } // Override std::any::has_value in order to deref first. bool has_value () const { return deref().raw__has_value(); } // Override std::any::type in order to deref first. std::type_info const &type () const { return deref().raw__type(); } // This calls std::any::has_value bool raw__has_value () const { return std::any::has_value(); } // { return static_cast<std::any const &>(*this).has_value(); } // This calls std::any::type std::type_info const &raw__type () const { return std::any::type(); } // { return static_cast<std::any const &>(*this).type(); } // This dereferences all wrapped RefTerm_c levels. I.e. if this data is RefTerm_c, then it will call // deref() on it and return. Otherwise it will return *this. Data const &deref () const & { return is_ref() ? deref_once().deref() : *this; } // This dereferences all wrapped RefTerm_c levels. I.e. if this data is RefTerm_c, then it will call // deref() on it and return. Otherwise it will return *this. Data &deref () & { return is_ref() ? deref_once().deref() : *this; } // This dereferences all wrapped RefTerm_c levels. I.e. if this data is RefTerm_c, then it will call // deref() on it and return. Otherwise it will return *this. Data move_deref () && { return is_ref() ? std::move(*this).move_deref_once().move_deref() : std::move(*this); } // For determining if this Data contains a RefTerm_c value. bool is_ref () const noexcept { return raw__can_cast<RefTerm_c>(); } // For accessing the underlying RefTerm_c, if is_ref() returns true. Otherwise will throw. RefTerm_c const &as_ref () const & { return raw__cast<RefTerm_c const &>(); } // For accessing the underlying RefTerm_c, if is_ref() returns true. Otherwise will throw. RefTerm_c &as_ref () & { return raw__cast<RefTerm_c &>(); } // For accessing the underlying RefTerm_c, if is_ref() returns true. Otherwise will throw. RefTerm_c move_as_ref () && { return std::move(*this).raw__move_cast<RefTerm_c>(); } private: // Returns the referenced_data if this data is RefTerm_c (recursively). Otherwise will throw. Data const &deref_once () const &; // Returns the referenced_data if this data is RefTerm_c (recursively). Otherwise will throw. Data &deref_once () &; // Returns the moved referenced_data if this data is RefTerm_c (recursively). Otherwise will throw. Data move_deref_once () &&; public: // // Cast methods (which implicitly and automatically dereference. // // Returns true iff the given std::any_cast<T_> would succeed (this uses the pointer-semantic version of std::any_cast). // T_ should not be a reference type. It automatically handles dereferencing if this data is RefTerm_c. template <typename T_> bool can_cast () const noexcept { static_assert(!std::is_reference_v<T_>, "T_ must not be a reference type"); return deref().raw__can_cast<T_>(); } // Returns true iff the given std::any_cast<T_> would succeed (this uses the pointer-semantic version of std::any_cast) // T_ should not be a reference type. It automatically handles dereferencing if this data is RefTerm_c. template <typename T_> bool can_cast () noexcept { static_assert(!std::is_reference_v<T_>, "T_ must not be a reference type"); return deref().raw__can_cast<T_>(); } // // Returns true iff the given std::any_cast<T_> would succeed (this uses the pointer-semantic version of std::any_cast) // // T_ should not be a reference type. It automatically handles dereferencing if this data is RefTerm_c. // template <typename T_> // bool can_cast () && noexcept { // static_assert(!std::is_reference_v<T_>, "T_ must not be a reference type"); // // Not 100% sure if this can_cast version is necessary or even correct. // return deref().raw__can_cast<T_>(); // } // Essentially performs std::any_cast<T_> on this object, except with nicer syntax. // It automatically handles dereferencing if this data is RefTerm_c. // TODO: Maybe use std::decay_t and then return `std::decay_t<T_> const &` template <typename T_> T_ cast () const & { return deref().raw__cast<T_>(); } // Essentially performs std::any_cast<T_> on this object, except with nicer syntax. // It automatically handles dereferencing if this data is RefTerm_c. // TODO: Maybe use std::decay_t and then return `std::decay_t<T_> &` template <typename T_> T_ cast () & { return deref().raw__cast<T_>(); } // Essentially performs std::any_cast<T_> on this object, except with nicer syntax. // It automatically handles dereferencing if this data is RefTerm_c. // TODO: Maybe use std::decay_t and then return `std::decay_t<T_> &&` template <typename T_> T_ move_cast () && { return std::move(*this).move_deref().raw__move_cast<T_>(); } // Essentially performs std::any_cast<T_ const *> on this object, except with nicer syntax. // It automatically handles dereferencing if this data is RefTerm_c. template <typename T_> T_ const *ptr_cast () const { return deref().raw__ptr_cast<T_>(); } // Essentially performs std::any_cast<T_ *> on this object, except with nicer syntax. // It automatically handles dereferencing if this data is RefTerm_c. template <typename T_> T_ *ptr_cast () { return deref().raw__ptr_cast<T_>(); } // This is a run-time type assertion that this Data actually holds T_. This call then just type-casts this // to the more-specific type Data_t<T_> const &. template <typename T_> Data_t<T_> const &as () const & { return deref().raw__as<T_>(); } // This is a run-time type assertion that this Data actually holds T_. This call then just type-casts this // to the more-specific type Data_t<T_> &. template <typename T_> Data_t<T_> &as () & { return deref().raw__as<T_>(); } // // This is a run-time type assertion that this Data actually holds T_. This call then just type-casts this // // to the more-specific type Data_t<T_> &&. // template <typename T_> // Data_t<T_> &&move_as () && { // return move_deref().raw__move_as<T_>(); // } // // Original "raw" versions of can_cast, cast, as -- these don't automatically dereference RefTerm_c. // // Returns true iff the given std::any_cast<T_> would succeed (this uses the pointer-semantic version of std::any_cast) template <typename T_> bool raw__can_cast () const noexcept { return std::any_cast<T_>(static_cast<std::any const *>(this)) != nullptr; } // Returns true iff the given std::any_cast<T_> would succeed (this uses the pointer-semantic version of std::any_cast) template <typename T_> bool raw__can_cast () noexcept { return std::any_cast<T_>(static_cast<std::any *>(this)) != nullptr; } // // Returns true iff the given std::any_cast<T_> would succeed (this uses the pointer-semantic version of std::any_cast) // template <typename T_> // bool raw__can_cast () && noexcept { // // Not 100% sure if this raw__can_cast version is necessary or even correct. // return std::any_cast<T_>(static_cast<std::any *>(this)) != nullptr; // } // Essentially performs std::any_cast<T_> on this object, except with nicer syntax. template <typename T_> T_ raw__cast () const & { return std::any_cast<T_>(static_cast<std::any const &>(*this)); } // Essentially performs std::any_cast<T_> on this object, except with nicer syntax. template <typename T_> T_ raw__cast () & { return std::any_cast<T_>(static_cast<std::any &>(*this)); } // Essentially performs std::any_cast<T_> on this object, except with nicer syntax. template <typename T_> T_ raw__move_cast () && { return std::move(std::any_cast<T_ &>(static_cast<std::any &>(*this))); } // Performs std::any_cast<T_ const> (using the pointer-semantic version) on this // object, except with nicer syntax. template <typename T_> T_ const *raw__ptr_cast () const { return std::any_cast<T_ const>(static_cast<std::any const *>(this)); } // Performs std::any_cast<T_ const> (using the pointer-semantic version) on this // object, except with nicer syntax. template <typename T_> T_ *raw__ptr_cast () { return std::any_cast<T_>(static_cast<std::any *>(this)); } // This is a run-time type assertion that this Data actually holds T_. This call then just type-casts this // to the more-specific type Data_t<T_> const &. template <typename T_> Data_t<T_> const &raw__as () const & { std::any_cast<T_>(static_cast<std::any const &>(*this)); // This will throw std::bad_any_cast if the cast is invalid. return static_cast<Data_t<T_> const &>(*this); } // This is a run-time type assertion that this Data actually holds T_. This call then just type-casts this // to the more-specific type Data_t<T_> &. template <typename T_> Data_t<T_> &raw__as () & { std::any_cast<T_>(static_cast<std::any &>(*this)); // This will throw std::bad_any_cast if the cast is invalid. return static_cast<Data_t<T_>&>(*this); } // // This is a run-time type assertion that this Data actually holds T_. This call then just type-casts this // // to the more-specific type Data_t<T_> &&. // // TODO: Figure out if this is right (it's probably not) // template <typename T_> // Data_t<T_> &&raw__move_as () && { // std::any_cast<T_>(static_cast<std::any &&>(*this)); // This will throw std::bad_any_cast if the cast is invalid. // return static_cast<Data_t<T_>&&>(*this); // } // Convenient way to get an overload for operator<< on std::ostream. operator lvd::OstreamDelegate () const; // // Data model methods // TODO: Potentially include things like abstract_type(), serialize(), etc. // // This calls construct_inhabitant_of(*this, argument) Data operator() (Data const &argument) const { return construct_inhabitant_of_data(*this, argument); } // This calls element_of_data(*this, param). Data operator[] (Data const &param) const { return element_of_data(*this, param); } }; // TODO: Implement specialization for std::swap(Data &, Data &) // This is analogous to std::make_any<T_> template <typename T_, typename... Args_> Data make_data (Args_&&... args) { return Data(std::in_place_type_t<T_>(), std::forward<Args_>(args)...); } // // Template methods from RefTerm_c that must be after the definition of Data // template <typename T_> bool RefTerm_c::can_cast () const { return referenced_data().can_cast<T_>(); } template <typename T_> bool RefTerm_c::can_cast () { return referenced_data().can_cast<T_>(); } template <typename T_> T_ RefTerm_c::cast () const { return referenced_data().cast<T_>(); } template <typename T_> T_ RefTerm_c::cast () { return referenced_data().cast<T_>(); } // // StaticAssociation_t for Data::operator lvd::OstreamDelegate // using DataPrintFunction = std::function<void(std::ostream &, DataPrintCtx &, Data const &)>; using DataPrintFunctionMap = std::unordered_map<std::type_index,DataPrintFunction>; LVD_STATIC_ASSOCIATION_DEFINE(_Data_Print, DataPrintFunctionMap) #define SEPT__REGISTER__PRINT__GIVE_ID(Type, unique_id) \ LVD_STATIC_ASSOCIATION_REGISTER( \ _Data_Print, \ unique_id, \ std::type_index(typeid(Type)), \ [](std::ostream &out, DataPrintCtx &ctx, Data const &value_data){ \ auto const &value = value_data.cast<Type const &>(); \ print(out, ctx, value); \ } \ ) #define SEPT__REGISTER__PRINT(Type) \ SEPT__REGISTER__PRINT__GIVE_ID(Type, Type) void print_data (std::ostream &out, DataPrintCtx &ctx, Data const &data); // Fallback default for printing. template <typename T_> void print (std::ostream &out, DataPrintCtx &ctx, T_ const &value) { out << value; } // // StaticAssociation_t for Data::operator lvd::OstreamDelegate // using DataHashFunction = std::function<size_t(Data const &)>; using DataHashFunctionMap = std::unordered_map<std::type_index,DataHashFunction>; LVD_STATIC_ASSOCIATION_DEFINE(_Data_Hash, DataHashFunctionMap) #define SEPT__REGISTER__HASH__GIVE_ID(Type, unique_id) \ LVD_STATIC_ASSOCIATION_REGISTER( \ _Data_Hash, \ unique_id, \ std::type_index(typeid(Type)), \ [](Data const &value_data) -> size_t { \ auto const &value = value_data.cast<Type const &>(); \ return std::hash<Type>()(value); \ } \ ) #define SEPT__REGISTER__HASH(Type) \ SEPT__REGISTER__HASH__GIVE_ID(Type, Type) size_t hash_data (Data const &data); // // StaticAssociation_t for eq_data // using DataPredicateUnary = std::function<bool(Data const &)>; using DataPredicateBinary = std::function<bool(Data const &, Data const &)>; using DataEqPredicateMap = std::unordered_map<std::type_index,DataPredicateBinary>; LVD_STATIC_ASSOCIATION_DEFINE(_Data_Eq, DataEqPredicateMap) #define SEPT__REGISTER__EQ__GIVE_ID(Type, unique_id) \ LVD_STATIC_ASSOCIATION_REGISTER( \ _Data_Eq, \ unique_id, \ std::type_index(typeid(Type)), \ [](Data const &lhs, Data const &rhs){ \ return lhs.cast<Type const &>() == rhs.cast<Type const &>(); \ } \ ) #define SEPT__REGISTER__EQ(Type) \ SEPT__REGISTER__EQ__GIVE_ID(Type, Type) // Only allow definitions of equality where the data are the same type. This means that for values of // different types to be equal (i.e. different int sizes), their conversion has to be explicit. bool eq_data (Data const &lhs, Data const &rhs); // TODO: Maybe use an explicitly named equals function instead, otherwise the fact that type can be converted into // Data greatly interferes with finding legitimately missing overloads for operator== for specific types. inline bool operator == (Data const &lhs, Data const &rhs) { return eq_data(lhs, rhs); } // TODO: Maybe use an explicitly named not_equals function instead inline bool operator != (Data const &lhs, Data const &rhs) { return !eq_data(lhs, rhs); } // // StaticAssociation_t for abstract_type_of_data -- abstract_type_of_data(x) should return the most-specific // type that x belongs to. // using DataFunction = std::function<Data(Data const &)>; using DataAbstractTypeOfEvaluatorMap = std::unordered_map<std::type_index,DataFunction>; LVD_STATIC_ASSOCIATION_DEFINE(_Data_AbstractTypeOf, DataAbstractTypeOfEvaluatorMap) #define SEPT__REGISTER__ABSTRACT_TYPE_OF__GIVE_ID__EVALUATOR(Value, unique_id, evaluator) \ LVD_STATIC_ASSOCIATION_REGISTER( \ _Data_AbstractTypeOf, \ unique_id, \ std::type_index(typeid(Value)), \ evaluator \ ) #define SEPT__REGISTER__ABSTRACT_TYPE_OF__EVALUATOR(Value, evaluator) \ SEPT__REGISTER__ABSTRACT_TYPE_OF__GIVE_ID__EVALUATOR(Value, Value, evaluator) #define SEPT__REGISTER__ABSTRACT_TYPE_OF__GIVE_ID__EVALUATOR_BODY(Value, unique_id, evaluator_body) \ SEPT__REGISTER__ABSTRACT_TYPE_OF__GIVE_ID__EVALUATOR( \ Value, \ unique_id, \ [](Data const &value_data)->Data{ \ auto const &value = value_data.cast<Value const &>(); \ std::ignore = value; \ evaluator_body \ } \ ) #define SEPT__REGISTER__ABSTRACT_TYPE_OF__GIVE_ID(Value, unique_id) \ SEPT__REGISTER__ABSTRACT_TYPE_OF__GIVE_ID__EVALUATOR_BODY(Value, unique_id, return abstract_type_of(value);) #define SEPT__REGISTER__ABSTRACT_TYPE_OF(Value) \ SEPT__REGISTER__ABSTRACT_TYPE_OF__GIVE_ID__EVALUATOR_BODY(Value, Value, return abstract_type_of(value);) Data abstract_type_of_data (Data const &value_data); // // StaticAssociation_t for inhabits_data -- inhabits_data(x, T) means "x inhabits T [as an abstract type]". // Note that this isn't the same as "abstract_type_of_data(x) == T", since in general x could inhabit // many different, overlapping abstract types. // struct TypeIndexPair { std::type_index m_value_ti; std::type_index m_type_ti; TypeIndexPair (std::type_index value_ti, std::type_index type_ti) : m_value_ti(value_ti) , m_type_ti(type_ti) { } bool operator == (TypeIndexPair const &other) const { return m_value_ti == other.m_value_ti && m_type_ti == other.m_type_ti; } }; } // end namespace sept // This has to go before std::unordered_map<TypeIndexPair,...> namespace std { // Template specialization to define std::hash<sept::TypeIndexPair>. template <> struct hash<sept::TypeIndexPair> { size_t operator () (sept::TypeIndexPair const &k) const { return lvd::hash(k.m_value_ti, k.m_type_ti); } }; } // end namespace std namespace sept { using DataInhabitsPredicateMap = std::unordered_map<TypeIndexPair,DataPredicateBinary>; LVD_STATIC_ASSOCIATION_DEFINE(_Data_Inhabits, DataInhabitsPredicateMap) #define SEPT__REGISTER__INHABITS__GIVE_ID__EVALUATOR(Value, Type, unique_id, evaluator) \ LVD_STATIC_ASSOCIATION_REGISTER( \ _Data_Inhabits, \ unique_id, \ TypeIndexPair{std::type_index(typeid(Value)), std::type_index(typeid(Type))}, \ evaluator \ ) #define SEPT__REGISTER__INHABITS__EVALUATOR(Value, Type, evaluator) \ SEPT__REGISTER__INHABITS__GIVE_ID__EVALUATOR(Value, Type, __##Value##___##Type##__, evaluator) // NONDATA indicates that the parameter of inhabits_data will be converted to the given ParamType, // e.g. as in `bool inhabits (uint32_t const &, Uint32 const &)`. #define SEPT__REGISTER__INHABITS__GIVE_ID__NONDATA(Value, Type, unique_id) \ SEPT__REGISTER__INHABITS__GIVE_ID__EVALUATOR( \ Value, \ Type, \ unique_id, \ [](Data const &value_data, Data const &type_data) -> bool { \ auto const &value = value_data.cast<Value const &>(); \ static_assert(!std::is_same_v<Type,Data>); \ auto const &type = type_data.cast<Type const &>(); \ std::ignore = value; \ std::ignore = type; \ return inhabits(value, type); \ } \ ) // DATA indicates that the value parameter of inhabits_data will not be converted, and will be passed as Data, // e.g. as in `bool inhabits (Data const &, Uint32 const &)`. #define SEPT__REGISTER__INHABITS__GIVE_ID__DATA(Value, Type, unique_id) \ SEPT__REGISTER__INHABITS__GIVE_ID__EVALUATOR( \ Value, \ Type, \ unique_id, \ [](Data const &value_data, Data const &type_data) -> bool { \ auto const &type = type_data.cast<Type const &>(); \ std::ignore = type; \ static_assert(std::is_same_v<Value,Data>); \ return inhabits(value_data, type); \ } \ ) // NONDATA indicates that the parameter of inhabits_data will be converted to the given ParamType, // e.g. as in `bool inhabits (uint32_t const &, Uint32 const &)`. #define SEPT__REGISTER__INHABITS__NONDATA(Value, Type) \ SEPT__REGISTER__INHABITS__GIVE_ID__NONDATA(Value, Type, __##Value##___##Type##__) // DATA indicates that the parameter of element_of_data will not be converted, and will be passed as Data, // e.g. as in `bool inhabits (Data const &, Uint32 const &)`. #define SEPT__REGISTER__INHABITS__DATA(Value, Type) \ SEPT__REGISTER__INHABITS__GIVE_ID__DATA(Value, Type, __##Value##___##Type##__) // This one causes inhabits_data(value, type) (where decltype(value) == Value and decltype(type) == Type) // to always return true (i.e. it doesn't depend on the content of value, only its type, i.e. Value). #define SEPT__REGISTER__INHABITS__NONDATA__UNCONDITIONAL(Value, Type) \ SEPT__REGISTER__INHABITS__EVALUATOR(Value, Type, DataPredicateBinary{nullptr}) bool inhabits_data (Data const &value_data, Data const &type_data); // // StaticAssociation_t for compare_data -- compare_data(lhs, rhs) should return: // - A negative value if lhs < rhs // - 0 if lhs == rhs // - A positive value if lhs > rhs // // TODO: Change this into TotalOrder, and also implement PartialOrder // using CompareFunction = std::function<int(Data const &,Data const &)>; using DataCompareEvaluatorMap = std::unordered_map<TypeIndexPair,CompareFunction>; LVD_STATIC_ASSOCIATION_DEFINE(_Data_Compare, DataCompareEvaluatorMap) #define SEPT__REGISTER__COMPARE__GIVE_ID__EVALUATOR(Lhs, Rhs, unique_id, evaluator) \ LVD_STATIC_ASSOCIATION_REGISTER( \ _Data_Compare, \ unique_id, \ TypeIndexPair{std::type_index(typeid(Lhs)), std::type_index(typeid(Rhs))}, \ evaluator \ ) #define SEPT__REGISTER__COMPARE__EVALUATOR(Lhs, Rhs, evaluator) \ SEPT__REGISTER__COMPARE__GIVE_ID__EVALUATOR(Lhs, Rhs, __##Lhs##___##Rhs##__, evaluator) #define SEPT__REGISTER__COMPARE__GIVE_ID__SINGLETON(Type, unique_id) \ SEPT__REGISTER__COMPARE__GIVE_ID__EVALUATOR(Type, Type, unique_id, nullptr) #define SEPT__REGISTER__COMPARE__SINGLETON(Type) \ SEPT__REGISTER__COMPARE__GIVE_ID__EVALUATOR(Type, Type, Type, nullptr) #define SEPT__REGISTER__COMPARE__GIVE_ID(Lhs, Rhs, unique_id) \ SEPT__REGISTER__COMPARE__GIVE_ID__EVALUATOR( \ Lhs, \ Rhs, \ unique_id, \ [](Data const &lhs_data, Data const &rhs_data)->int{ \ return compare(lhs_data.cast<Lhs const &>(), rhs_data.cast<Rhs const &>()); \ } \ ) #define SEPT__REGISTER__COMPARE(Lhs, Rhs) \ SEPT__REGISTER__COMPARE__GIVE_ID(Lhs, Rhs, __##Lhs##___##Rhs##__) int compare_data (Data const &lhs, Data const &rhs); // // StaticAssociation_t for serialize_data // using SerializeProcedure = std::function<void(Data const &value, std::ostream &out)>; using DataSerializeProcedureMap = std::unordered_map<std::type_index,SerializeProcedure>; LVD_STATIC_ASSOCIATION_DEFINE(_Data_Serialize, DataSerializeProcedureMap) #define SEPT__REGISTER_SERIALIZE__GIVE_ID__EVALUATOR(Type, unique_id, evaluator) \ LVD_STATIC_ASSOCIATION_REGISTER( \ _Data_Serialize, \ unique_id, \ std::type_index(typeid(Type)), \ evaluator \ ) #define SEPT__REGISTER__SERIALIZE__EVALUATOR(Type, evaluator) \ SEPT__REGISTER_SERIALIZE__GIVE_ID__EVALUATOR(Type, __##Lhs##___##Rhs##__, evaluator) #define SEPT__REGISTER__SERIALIZE__GIVE_ID(Type, unique_id) \ SEPT__REGISTER_SERIALIZE__GIVE_ID__EVALUATOR( \ Type, \ unique_id, \ [](Data const &value_data, std::ostream &out){ \ Type const &value = value_data.cast<Type const &>(); \ std::ignore = value; \ serialize(value, out); \ } \ ) #define SEPT__REGISTER__SERIALIZE(Type) \ SEPT__REGISTER__SERIALIZE__GIVE_ID(Type, Type) void serialize_data (Data const &value, std::ostream &out); // This causes anything but an explicit Data to be passed into serialize_data. template <typename T_> void serialize_data (T_ const &, std::ostream &) = delete; // // StaticAssociation_t for deserialize_data // using DeserializeProcedure = std::function<Data(Data &&type, std::istream &in)>; using DataDeserializeProcedureMap = std::unordered_map<std::type_index,DeserializeProcedure>; LVD_STATIC_ASSOCIATION_DEFINE(DeserializeData, DataDeserializeProcedureMap) #define SEPT__REGISTER__DESERIALIZE__GIVE_ID__EVALUATOR(Type, unique_id, evaluator) \ LVD_STATIC_ASSOCIATION_REGISTER( \ DeserializeData, \ unique_id, \ std::type_index(typeid(Type)), \ evaluator \ ) #define SEPT__REGISTER__DESERIALIZE__EVALUATOR(Type, evaluator) \ SEPT__REGISTER__DESERIALIZE__GIVE_ID__EVALUATOR(Type, Type, evaluator) #define SEPT__REGISTER__DESERIALIZE__GIVE_ID__POD(Value, Type, unique_id) \ SEPT__REGISTER__DESERIALIZE__GIVE_ID__EVALUATOR( \ Type, \ unique_id, \ [](Data &&abstract_type, std::istream &in) -> Data { \ return SerializationForPOD<Value>::deserialize_value(in); \ } \ ) #define SEPT__REGISTER__DESERIALIZE__POD(Value, Type) \ SEPT__REGISTER__DESERIALIZE__GIVE_ID__POD(Value, Type, Type) // TODO: Maybe define a template that is specialized for each type, similar to SerializationForPOD #define SEPT__REGISTER__DESERIALIZE(Type, evaluator_body) \ SEPT__REGISTER__DESERIALIZE__EVALUATOR( \ Type, \ [](Data &&abstract_type, std::istream &in) -> Data { evaluator_body } \ ) Data deserialize_data (std::istream &in); // // StaticAssociation_t for element_of_data // using ElementOfDataFunction = std::function<Data(Data const &container_data, Data const &param_data)>; using DataElementOfFunctionMap = std::unordered_map<TypeIndexPair,ElementOfDataFunction>; LVD_STATIC_ASSOCIATION_DEFINE(ElementOfData, DataElementOfFunctionMap) #define SEPT__REGISTER__ELEMENT_OF__GIVE_ID__EVALUATOR(ContainerType, ParamType, unique_id, evaluator) \ LVD_STATIC_ASSOCIATION_REGISTER( \ ElementOfData, \ unique_id, \ TypeIndexPair{std::type_index(typeid(ContainerType)), std::type_index(typeid(ParamType))}, \ evaluator \ ) #define SEPT__REGISTER__ELEMENT_OF__EVALUATOR(ContainerType, ParamType, evaluator) \ SEPT__REGISTER__ELEMENT_OF__GIVE_ID__EVALUATOR(ContainerType, ParamType, __##ContainerType##___##ParamType##__, evaluator) // NONDATA indicates that the parameter of element_of_data will be converted to the given ParamType, // e.g. as in `Data element_of (ArrayTerm_c const &a, uint32_t index)`. #define SEPT__REGISTER__ELEMENT_OF__GIVE_ID__NONDATA(ContainerType, ParamType, unique_id) \ SEPT__REGISTER__ELEMENT_OF__GIVE_ID__EVALUATOR( \ ContainerType, \ ParamType, \ unique_id, \ [](Data const &container_data, Data const &param_data) -> Data { \ auto const &container = container_data.cast<ContainerType const &>(); \ static_assert(!std::is_same_v<ParamType,Data>); \ auto const &param = param_data.cast<ParamType const &>(); \ std::ignore = container; \ std::ignore = param; \ return element_of(container, param); \ } \ ) // DATA indicates that the parameter of element_of_data will not be converted, and will be passed as Data, // e.g. as in `Data element_of (OrderedMapTerm_c const &m, Data const &key)`. #define SEPT__REGISTER__ELEMENT_OF__GIVE_ID__DATA(ContainerType, ParamType, unique_id) \ SEPT__REGISTER__ELEMENT_OF__GIVE_ID__EVALUATOR( \ ContainerType, \ ParamType, \ unique_id, \ [](Data const &container_data, Data const &param_data) -> Data { \ auto const &container = container_data.cast<ContainerType const &>(); \ std::ignore = container; \ static_assert(std::is_same_v<ParamType,Data>); \ return element_of(container, param_data); \ } \ ) // NONDATA indicates that the parameter of element_of_data will be converted to the given ParamType, // e.g. as in `Data element_of (ArrayTerm_c const &a, uint32_t index)`. #define SEPT__REGISTER__ELEMENT_OF__NONDATA(ContainerType, ParamType) \ SEPT__REGISTER__ELEMENT_OF__GIVE_ID__NONDATA(ContainerType, ParamType, __##ContainerType##___##ParamType##__) // DATA indicates that the parameter of element_of_data will not be converted, and will be passed as Data, // e.g. as in `Data element_of (OrderedMapTerm_c const &m, Data const &key)`. #define SEPT__REGISTER__ELEMENT_OF__DATA(ContainerType, ParamType) \ SEPT__REGISTER__ELEMENT_OF__GIVE_ID__DATA(ContainerType, ParamType, __##ContainerType##___##ParamType##__) Data element_of_data (Data const &container_data, Data const &param_data); // // StaticAssociation_t for construct_inhabitant_of_data -- for using the operator() syntax // using ConstructInhabitantEvaluator = std::function<Data(Data const &type, Data const &argument)>; using DataConstructInhabitantOfEvaluatorMap = std::unordered_map<TypeIndexPair,ConstructInhabitantEvaluator>; LVD_STATIC_ASSOCIATION_DEFINE(_Data_ConstructInhabitantOf, DataConstructInhabitantOfEvaluatorMap) #define SEPT__REGISTER__CONSTRUCT_INHABITANT_OF__GIVE_ID__EVALUATOR(Type, Argument, unique_id, evaluator) \ LVD_STATIC_ASSOCIATION_REGISTER( \ _Data_ConstructInhabitantOf, \ unique_id, \ TypeIndexPair{std::type_index(typeid(Type)), std::type_index(typeid(Argument))}, \ evaluator \ ) #define SEPT__REGISTER__CONSTRUCT_INHABITANT_OF__EVALUATOR(Type, Argument, evaluator) \ SEPT__REGISTER__CONSTRUCT_INHABITANT_OF__GIVE_ID__EVALUATOR(Type, Argument, __##Type##___##Argument##__, evaluator) #define SEPT__REGISTER__CONSTRUCT_INHABITANT_OF__GIVE_ID__EVALUATOR_BODY(Type, Argument, unique_id, evaluator_body) \ SEPT__REGISTER__CONSTRUCT_INHABITANT_OF__GIVE_ID__EVALUATOR( \ Type, \ Argument, \ unique_id, \ [](Data const &type_data, Data const &argument_data) -> Data{ \ auto const &type = type_data.cast<Type const &>(); \ auto const &argument = argument_data.cast<Argument const &>(); \ std::ignore = type; \ std::ignore = argument; \ evaluator_body \ } \ ) #define SEPT__REGISTER__CONSTRUCT_INHABITANT_OF__GIVE_ID(Type, Argument, unique_id) \ SEPT__REGISTER__CONSTRUCT_INHABITANT_OF__GIVE_ID__EVALUATOR_BODY(Type, Argument, unique_id, return type(argument);) #define SEPT__REGISTER__CONSTRUCT_INHABITANT_OF(Type, Argument) \ SEPT__REGISTER__CONSTRUCT_INHABITANT_OF__GIVE_ID__EVALUATOR_BODY(Type, Argument, __##Type##___##Argument##__, return type(argument);) // TODO: Need to make a version of this that accepts Data, just like SEPT__REGISTER__ELEMENT_OF__DATA etc #define SEPT__REGISTER__CONSTRUCT_INHABITANT_OF__GIVE_ID__ABSTRACT_TYPE(Type, Argument, unique_id) \ SEPT__REGISTER__CONSTRUCT_INHABITANT_OF__GIVE_ID__EVALUATOR(Type, Argument, unique_id, nullptr) #define SEPT__REGISTER__CONSTRUCT_INHABITANT_OF__ABSTRACT_TYPE(Type, Argument) \ SEPT__REGISTER__CONSTRUCT_INHABITANT_OF__GIVE_ID__EVALUATOR(Type, Argument, __##Type##___##Argument##__, nullptr) Data construct_inhabitant_of_data (Data const &type_data, Data const &argument_data); // // Other stuff // // Determines set membership. Doesn't have to be defined for all possible containers. // TODO: Provide overloads for all the various Data_t<T_> types, so that more compile-time stuff can be done. bool is_member (Data const &value, Data const &container); // Produces the element type of an Array_c*. Might be used for other types in the future as well. // TODO: Provide overloads for all the various Data_t<T_> types, so that more compile-time stuff can be done. Data element_type_of (Data const &array_type); Data element_type_of (Data &&array_type); Data domain_of (Data const &ordered_map_type); Data domain_of (Data &&ordered_map_type); Data codomain_of (Data const &ordered_map_type); Data codomain_of (Data &&ordered_map_type); } // end namespace sept namespace std { // template <typename Key_> struct hash; // Template specialization to define std::hash<sept::Data>. template <> struct hash<sept::Data> { size_t operator () (sept::Data const &data) const; }; // Overload to define std::swap for sept::Data. NOTE/TODO: Figure out if this causes a problem // with Data_t<A> being swappable with Data_t<B>. Maybe use an std::enable_if? inline void swap (sept::Data &lhs, sept::Data &rhs) noexcept { assert(false && "just testing to see if this is ever called -- maybe it shouldn't be (see comments)"); swap(static_cast<any&>(lhs), static_cast<any&>(rhs)); } } // end namespace std
43.060932
137
0.698518
vdods
51aa22d8c28a360f3287d63dd61d0bf7575a9208
4,506
cpp
C++
Samples/Win7Samples/winbase/storage/EhStorEnumerator/EhStorEnumerator2/LocalCertStoreImp.cpp
windows-development/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/Win7Samples/winbase/storage/EhStorEnumerator/EhStorEnumerator2/LocalCertStoreImp.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
null
null
null
Samples/Win7Samples/winbase/storage/EhStorEnumerator/EhStorEnumerator2/LocalCertStoreImp.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.000Z
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved #include "StdAfx.h" #include "LocalCertStoreImp.h" CLocalCertStoreImp::CLocalCertStoreImp(void) { m_hCertStoreHandle = NULL; } CLocalCertStoreImp::~CLocalCertStoreImp(void) { if (m_hCertStoreHandle) { CertCloseStore(m_hCertStoreHandle, 0); m_hCertStoreHandle = NULL; } } HRESULT CLocalCertStoreImp::OpenSystemStore(SYSTEM_STORE_NAMES nStore) { LPTSTR szSubsystemProtocol; switch (nStore) { case SYSTEM_STORE_CA: szSubsystemProtocol = _T("CA"); break; case SYSTEM_STORE_MY: szSubsystemProtocol = _T("MY"); break; case SYSTEM_STORE_ROOT: szSubsystemProtocol = _T("ROOT"); break; case SYSTEM_STORE_SPC: szSubsystemProtocol = _T("SPC"); break; default: return FALSE; } m_hCertStoreHandle = ::CertOpenSystemStore(NULL, szSubsystemProtocol); return (m_hCertStoreHandle) ? S_OK : HRESULT_FROM_WIN32(GetLastError()); } HRESULT CLocalCertStoreImp::GetDecodedCertName(PCERT_NAME_BLOB pCertName, DWORD dwStrType, LPTSTR szCertName, ULONG nBufferMax) { DWORD dwDataLength = 0; PWCHAR pString = NULL; HRESULT hr = S_OK; if (pCertName == NULL) { return E_INVALIDARG; } // find the length first dwDataLength = ::CertNameToStr(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, pCertName, dwStrType, NULL, 0); if (dwDataLength == 0) { return E_FAIL; } pString = new WCHAR[dwDataLength]; if (pString == NULL) { return E_OUTOFMEMORY; } CertNameToStr(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, pCertName, dwStrType, pString, dwDataLength); StringCbCopy(szCertName, nBufferMax, pString); // perform cleanup delete[] pString; pString = NULL; return hr; } HRESULT CLocalCertStoreImp::GetCertificatesList(CCertificate *&parCertificates, DWORD &nCertificatesCnt) { HRESULT hr = S_OK; PCCERT_CONTEXT pCertContext = NULL; DWORD nCertIndex = 0; // cert store must be opened first... if (m_hCertStoreHandle == NULL) { return E_UNEXPECTED; } // pass 1, get certificates count nCertificatesCnt = 0; while(pCertContext = ::CertEnumCertificatesInStore(m_hCertStoreHandle, pCertContext)) { nCertificatesCnt ++; } pCertContext = NULL; parCertificates = new CCertificate[nCertificatesCnt]; while(pCertContext = ::CertEnumCertificatesInStore(m_hCertStoreHandle, pCertContext)) { TCHAR szStringBuf[256]; CCertificate &certificate = parCertificates[nCertIndex++]; hr = GetDecodedCertName( &pCertContext->pCertInfo->Issuer, CERT_X500_NAME_STR | CERT_NAME_STR_REVERSE_FLAG | CERT_NAME_STR_NO_QUOTING_FLAG, szStringBuf, _countof(szStringBuf)); if (SUCCEEDED(hr)) { certificate.set_Issuer(szStringBuf); } hr = GetDecodedCertName( &pCertContext->pCertInfo->Subject, CERT_X500_NAME_STR | CERT_NAME_STR_REVERSE_FLAG | CERT_NAME_STR_NO_QUOTING_FLAG, szStringBuf, _countof(szStringBuf)); if (SUCCEEDED(hr)) { certificate.set_Subject(szStringBuf); // copy encoded certificate blob to byte array certificate.set_EncodedData(pCertContext->pbCertEncoded, pCertContext->cbCertEncoded); certificate.set_Version(pCertContext->pCertInfo->dwVersion); } } return hr; } HRESULT CLocalCertStoreImp::AddCertificate(CCertificate &certificate) { HRESULT hr = S_OK; DWORD nCertEncodedSize = 0; // cert store must be opened first... if (m_hCertStoreHandle == NULL) { return E_UNEXPECTED; } if (CertAddEncodedCertificateToStore( m_hCertStoreHandle, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, certificate.get_EncodedData(nCertEncodedSize), nCertEncodedSize, CERT_STORE_ADD_NEW, NULL) == FALSE) { hr = HRESULT_FROM_WIN32(GetLastError()); } return hr; }
28.339623
128
0.648247
windows-development
51b398064863748ee5808273d91e4f83d884fcc2
3,406
cpp
C++
tests/HttpURL.cpp
Good-Pudge/OkHttpFork
b179350d6262f281c1c27d69d944c62f536fe1ba
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
10
2019-02-21T06:21:48.000Z
2022-02-22T08:01:24.000Z
tests/HttpURL.cpp
Good-Pudge/OkHttpFork
b179350d6262f281c1c27d69d944c62f536fe1ba
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
2
2018-02-04T20:16:46.000Z
2018-02-04T20:19:00.000Z
tests/HttpURL.cpp
Good-Pudge/OkHttpFork
b179350d6262f281c1c27d69d944c62f536fe1ba
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
10
2018-10-15T10:17:00.000Z
2022-02-17T02:28:51.000Z
#include <catch.hpp> #include "util/ExceptionCatch.hpp" #include <ohf/HttpURL.hpp> using namespace ohf; TEST_CASE("HttpURL") { REQUIRE(HttpURL::defaultPort("http") == 80); REQUIRE(HttpURL::defaultPort("https") == 443); REQUIRE(HttpURL::decode("Hello%2C%20world%21") == "Hello, world!"); REQUIRE_THROWS_CODE(HttpURL::decode("%ZZ"), Exception::Code::INVALID_URI_HEX_CODE); REQUIRE(HttpURL("example.com:214").url() == "http://example.com:214/"); REQUIRE(HttpURL("example.com/#FrAgMeNt").url() == "http://example.com/#FrAgMeNt"); REQUIRE(HttpURL("example.com/?q=123&land=en-US&empty").url() == "http://example.com/?empty&land=en-US&q=123"); REQUIRE_THROWS_CODE(HttpURL("example.com?q=123"), Exception::Code::INVALID_URI); REQUIRE_THROWS_CODE(HttpURL("example.com#123"), Exception::Code::INVALID_URI); REQUIRE_THROWS_CODE(HttpURL("/?q=123"), Exception::Code::HOST_IS_EMPTY); REQUIRE_THROWS_CODE(HttpURL("example.com:INVALID"), Exception::Code::INVALID_PORT); REQUIRE_THROWS_CODE(HttpURL("example.com/?q=123=321"), Exception::Code::INVALID_QUERY_PARAMETER); HttpURL::Builder builder; SECTION("Builder") { builder .scheme("ftp") .host("example.com") .port(1234) .addPathSegments("/foo/bar") .setPathSegment(0, "wow") .setPathSegment(2, "oh/") .removePathSegment(1) .query("q=123&hello=world&empty_parameter") .setQueryParameter("unused", "parameter") .setQueryParameter("q", "321") .removeQueryParameter("unused") .fragment("some_fragment") .pathSuffix(false); REQUIRE_THROWS_CODE(builder.query("q=123=321"), Exception::Code::INVALID_QUERY_PARAMETER); } HttpURL url = builder.build(); REQUIRE(url.scheme() == "ftp"); REQUIRE(url.host() == "example.com"); REQUIRE(url.port() == 1234); REQUIRE_FALSE(url.pathSuffix()); REQUIRE(url.encodedPath() == "/wow/oh"); REQUIRE(url.pathSegments()[0] == "wow"); REQUIRE(url.pathSegments()[1] == "oh"); REQUIRE(url.pathSize() == 7); auto segments = url.encodedPathSegments(); REQUIRE(segments[0] == "wow"); REQUIRE(segments[1] == "oh"); REQUIRE(url.query() == "empty_parameter&hello=world&q=321"); REQUIRE(url.queryParameter("q") == "321"); REQUIRE(url.queryParameterName(0) == "empty_parameter"); auto query = url.queryMap(); REQUIRE(query["empty_parameter"].empty()); REQUIRE(query["hello"] == "world"); REQUIRE(query["q"] == "321"); REQUIRE_THROWS_CODE(url.queryParameterName(3), Exception::Code::OUT_OF_RANGE); REQUIRE(url.queryParameterValue(0).empty()); REQUIRE_THROWS_CODE(url.queryParameterValue(3), Exception::Code::OUT_OF_RANGE); REQUIRE(url.queryParameterNames()[0] == "empty_parameter"); REQUIRE(url.querySize() == 33); REQUIRE(url.fragment() == "some_fragment"); REQUIRE_FALSE(url.isHttps()); std::ostringstream oss; oss << url; REQUIRE(oss.str() == "ftp://example.com:1234/wow/oh?empty_parameter&hello=world&q=321#some_fragment"); url = HttpURL::Builder() .host("example.com") .addPathSegments("path/") .build(); REQUIRE(url.url() == "http://example.com/path/"); REQUIRE(url.encodedQuery().empty()); }
40.070588
114
0.627422
Good-Pudge
51b3a6d2ebf4456f7f27f5e333e72cf2bf2de5a0
3,916
cpp
C++
libcaf_core/test/actor_factory.cpp
v2nero/actor-framework
c2f811809143d32c598471a20363238b0882a761
[ "BSL-1.0", "BSD-3-Clause" ]
1
2021-03-06T19:51:07.000Z
2021-03-06T19:51:07.000Z
libcaf_core/test/actor_factory.cpp
Boubou818/actor-framework
da90ef78b26da5d225f039072e616da415c48494
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
libcaf_core/test/actor_factory.cpp
Boubou818/actor-framework
da90ef78b26da5d225f039072e616da415c48494
[ "BSL-1.0", "BSD-3-Clause" ]
1
2021-02-19T11:25:15.000Z
2021-02-19T11:25:15.000Z
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "caf/config.hpp" #define CAF_SUITE actor_factory #include "caf/test/unit_test.hpp" #include "caf/all.hpp" #include "caf/actor_registry.hpp" using namespace caf; using std::endl; namespace { using down_atom = atom_constant<atom("down")>; struct fixture { actor_system_config cfg; void test_spawn(message args, bool expect_fail = false) { actor_system system{cfg}; scoped_actor self{system}; CAF_MESSAGE("set aut"); strong_actor_ptr res; std::set<std::string> ifs; scoped_execution_unit context{&system}; actor_config actor_cfg{&context}; auto aut = system.spawn<actor>("test_actor", std::move(args)); if (expect_fail) { CAF_REQUIRE(!aut); return; } CAF_REQUIRE(aut); self->wait_for(*aut); CAF_MESSAGE("aut done"); } }; struct test_actor_no_args : event_based_actor { using event_based_actor::event_based_actor; }; struct test_actor_one_arg : event_based_actor { test_actor_one_arg(actor_config& conf, int value) : event_based_actor(conf) { CAF_CHECK_EQUAL(value, 42); } }; } // namespace <anonymous> CAF_TEST_FIXTURE_SCOPE(add_actor_type_tests, fixture) CAF_TEST(fun_no_args) { auto test_actor_one_arg = [] { CAF_MESSAGE("inside test_actor"); }; cfg.add_actor_type("test_actor", test_actor_one_arg); test_spawn(make_message()); CAF_MESSAGE("test_spawn done"); } CAF_TEST(fun_no_args_selfptr) { auto test_actor_one_arg = [](event_based_actor*) { CAF_MESSAGE("inside test_actor"); }; cfg.add_actor_type("test_actor", test_actor_one_arg); test_spawn(make_message()); } CAF_TEST(fun_one_arg) { auto test_actor_one_arg = [](int i) { CAF_CHECK_EQUAL(i, 42); }; cfg.add_actor_type("test_actor", test_actor_one_arg); test_spawn(make_message(42)); } CAF_TEST(fun_one_arg_selfptr) { auto test_actor_one_arg = [](event_based_actor*, int i) { CAF_CHECK_EQUAL(i, 42); }; cfg.add_actor_type("test_actor", test_actor_one_arg); test_spawn(make_message(42)); } CAF_TEST(class_no_arg_invalid) { cfg.add_actor_type<test_actor_no_args>("test_actor"); test_spawn(make_message(42), true); } CAF_TEST(class_no_arg_valid) { cfg.add_actor_type<test_actor_no_args>("test_actor"); test_spawn(make_message()); } CAF_TEST(class_one_arg_invalid) { cfg.add_actor_type<test_actor_one_arg, const int&>("test_actor"); test_spawn(make_message(), true); } CAF_TEST(class_one_arg_valid) { cfg.add_actor_type<test_actor_one_arg, const int&>("test_actor"); test_spawn(make_message(42)); } CAF_TEST_FIXTURE_SCOPE_END()
31.328
80
0.569969
v2nero
51b7752ec44b728ca36f0e7c54e6ee04b018660b
8,216
cpp
C++
src/opbox/common/OpRegistry.cpp
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-01-25T21:21:07.000Z
2021-04-29T17:24:00.000Z
src/opbox/common/OpRegistry.cpp
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
8
2018-10-09T14:35:30.000Z
2020-09-30T20:09:42.000Z
src/opbox/common/OpRegistry.cpp
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-04-23T19:01:36.000Z
2021-05-11T07:44:55.000Z
// Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. #include <iostream> #include <chrono> #include <thread> #include <sstream> #include <map> #include "faodel-common/Debug.hh" #include "opbox/common/OpRegistry.hh" using namespace std; namespace opbox { OpRegistry::OpRegistry() : finalized(false) { mutex = faodel::GenerateMutex(); } /** * @brief Signify that work has been completed and that all known ops should be discarded */ void OpRegistry::Finish(){ F_ASSERT(finalized, "Finish attempted on OpRegistry when it has not been started"); mutex->Lock(); //Get rid of all post ops known_ops_post.clear(); op_names_post.clear(); mutex->Unlock(); //Get rid of all pre ops known_ops_pre.clear(); op_names_pre.clear(); finalized=false; } /** * @brief Register a function for creating a particular op * @param[in] op_id The unique id for the op (a compile-time hash of its name) * @param[in] op_name The unique string name of the op * @param[in] func A function for creating the new op * @return void * * The RegisterOp function is used to register a lambda for creating a new * Op associated with a particular ID. A user should define a meaningful * name for the op (op_name) and use a compile-time hash of the name to * uniquely identify the Op. This function will exit if the given op_id * matches a previously registered op (it assumes there is a hash collision). * * It is expected that most users will use the RegisterOp template to * register functions, as id/name fields can be cumbersome. eg, use: * opbox::RegisterOp<OpMyBigStateMachine>(); * * Ops can be registered at any point in time, but there is a performance * advantage to registering them before the bootstrap::Start() phase takes * place (ie, it avoids a mutex). */ void OpRegistry::RegisterOp(int op_id, string op_name, fn_OpCreate_t func){ //Note: user specifies op_id and op_name because if we create a dummy // op at this point, it's possible something in the ctor won't // be ready. //See if in pre-finalized set auto search = known_ops_pre.find(op_id); if (search != known_ops_pre.end()){ std::cout <<"Error: duplicate register of same Op function. Could be a hash collision or duplicates. Name is: "<<op_name<<endl; std::cout <<" All known ops:\n" << str(1,3) <<endl; exit(-1); } if(!finalized){ known_ops_pre[op_id] = func; op_names_pre[op_id] = op_name; } else { //We're currently running. Must also search the post section mutex->Lock(); search = known_ops_post.find(op_id); if(search != known_ops_post.end()){ std::cout <<"Error: duplicate register of same Op function. Could be a hash collision or duplicates. Name is: "<<op_name<<endl; std::cout <<" All known ops:\n" << str(1,3) <<endl; exit(-1); } known_ops_post[op_id] = func; op_names_post[op_id] = op_name; mutex->Unlock(); } } /** * @brief Convert a registered op id number to a name * @param[in] op_id The ID of the op * @retval NAME The name of the registered op * @retval "" ID was not registered */ string OpRegistry::GetOpName(int op_id) const { auto search1 = op_names_pre.find(op_id); if(search1 != op_names_pre.end()) { return search1->second; } string result; mutex->ReaderLock(); auto search2 = op_names_post.find(op_id); if(search2 != op_names_post.end()) { result = search2->second; } mutex->Unlock(); return result; } /** * @brief Remove an Op from service * @param[in] op_id The op id to remove * @param[in] ignore_lock_warning Ignore check to see if attempting to deregister a pre op when finalized * * TODO: Ops that were registered before bootstrap was started emit a warning */ void OpRegistry::DeregisterOp(int op_id, bool ignore_lock_warning){ auto search1 = known_ops_pre.find(op_id); if(search1 != known_ops_pre.end()){ if(finalized && !ignore_lock_warning){ //TODO: we should really shut down more gracefully. However, OpRegistry doesn't // reset finalized until it is shut down, which usually happens after the // user shuts down. std::cout <<"Warning:: Deregistering pre-finalized op while in finalized state\n"; exit(0); } known_ops_pre.erase(search1); auto search1b = op_names_pre.find(op_id); if(search1b != op_names_pre.end()) op_names_pre.erase(search1b); return; } mutex->Lock(); auto search2 = known_ops_post.find(op_id); if(search2 != known_ops_post.end()){ known_ops_post.erase(search2); auto search2b = op_names_post.find(op_id); if(search2b != op_names_post.end()) op_names_post.erase(search2b); mutex->Unlock(); return; } mutex->Unlock(); cout <<"Error: Deregister op "<<op_id<<" did not find requested op to deregister\n"; } /** * @brief Creates a new Op for the given op id * @param[in] op_id Unique id for op (usually a compile-time hash of the op name) * @retval OP* A pointer to the newly-create Op * @retval nullptr The op was not found in the list */ Op * OpRegistry::CreateOp(unsigned int op_id){ //Search 1: do a lockless search on the pre-finalize ops auto search1 = known_ops_pre.find(op_id); if(search1 != known_ops_pre.end()){ return search1->second(); } //Search 2: do a locked search on the post-finalize ops mutex->Lock(); auto search2 = known_ops_post.find(op_id); if(search2 != known_ops_post.end()){ Op *res = search2->second(); mutex->Unlock(); return res; } mutex->Unlock(); return nullptr; } /** * @brief Process a request from Whookie to get status information * * @param[in] args The map of k/v parameters the user sent in this request * @param[in] results The stringstream to write results to */ void OpRegistry::HandleWhookieStatus( const std::map<std::string,std::string> &args, std::stringstream &results) { faodel::ReplyStream rs(args, "OpBox OpRegistry Status", &results); whookieInfo(rs); rs.Finish(); } /** * @brief Append information about the reqistry to a whookie replystream * * @param[in] rs The replystream that output should be written to */ void OpRegistry::whookieInfo(faodel::ReplyStream &rs) { rs.tableBegin("OpRegistry"); rs.tableTop({"Parameter","Setting"}); rs.tableRow({"Finalized:", (finalized)?"True":"False"}); rs.tableRow({"Pre-Finalized Entries:", to_string(op_names_pre.size())}); rs.tableRow({"Post-Finalized Entries:", to_string(op_names_post.size())}); rs.tableEnd(); rs.tableBegin("Operations Registered before OpBox Start()\n"); rs.tableTop({"Name","Hash(name)"}); for(auto &id_name : op_names_pre){ rs.tableRow( { id_name.second, to_string(id_name.first) } ); } rs.tableEnd(); rs.tableBegin("Operations Registered after OpBox Start()\n"); rs.tableTop({"Name","Hash(name)"}); mutex->ReaderLock(); for(auto &id_name : op_names_post){ rs.tableRow( { id_name.second, to_string(id_name.first) } ); } rs.tableEnd(); mutex->Unlock(); } /** * @brief Dump information about a component (and its internal components) * * @param[in] ss The stringstream to append this component's information to * @param[in] depth How many layers deeper into the component we should go * @param[in] indent How many spaces to indent this component */ void OpRegistry::sstr(std::stringstream &ss, int depth, int indent) const { if(depth<0) return; ss << string(indent,' ') << "[OpRegistry]" << " PreInitOps: "<< known_ops_pre.size() << " PostInitOps: "<< known_ops_post.size() << endl; if(depth>0){ indent++; for(auto x : known_ops_pre){ Op *op = x.second(); ss<< string(indent,' ') << "["<<hex<<x.first<<"] "<<op->getOpName()<<endl; delete op; } mutex->Lock(); for(auto x : known_ops_post){ Op *op = x.second(); ss<< string(indent,' ') << "["<<hex<<x.first<<"] "<<op->getOpName()<<endl; delete op; } mutex->Unlock(); } } } // namespace opbox
30.887218
133
0.67186
faodel
51bc4bce65562e10f228ba9b2adc9415fc24eff5
609
cpp
C++
URI/1012.cpp
JovemPedr0/LP1
d1e1a6df95812cab1dca3b981273c9557557572e
[ "MIT" ]
null
null
null
URI/1012.cpp
JovemPedr0/LP1
d1e1a6df95812cab1dca3b981273c9557557572e
[ "MIT" ]
null
null
null
URI/1012.cpp
JovemPedr0/LP1
d1e1a6df95812cab1dca3b981273c9557557572e
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> #define PI 3.14159 using namespace std; int main() { double ladoA, ladoB, ladoC; cin >> ladoA >> ladoB >> ladoC; cout << "TRIANGULO: " << fixed << setprecision(3) << (ladoA*ladoC) / 2 << endl; cout << "CIRCULO: " << fixed << setprecision(3) << PI * (ladoC * ladoC) << endl; cout << "TRAPEZIO: " << fixed << setprecision(3) << ((ladoA + ladoB) * ladoC)/ 2 << endl; cout << "QUADRADO: " << fixed << setprecision (3) << ladoB*ladoB << endl; cout << "RETANGULO: " << fixed << setprecision(3) << ladoA * ladoB << endl; return 0; }
25.375
93
0.563218
JovemPedr0
51cf74e598561b6c220a361e65bc84f3dad1b27f
20,185
hpp
C++
toolkits/graphical_models/factors/factor_graph.hpp
coreyp1/graphlab
637be90021c5f83ab7833ca15c48e76039057969
[ "ECL-2.0", "Apache-2.0" ]
8
2017-11-19T11:46:55.000Z
2021-07-08T22:45:55.000Z
toolkits/graphical_models/factors/factor_graph.hpp
coreyp1/graphlab
637be90021c5f83ab7833ca15c48e76039057969
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
toolkits/graphical_models/factors/factor_graph.hpp
coreyp1/graphlab
637be90021c5f83ab7833ca15c48e76039057969
[ "ECL-2.0", "Apache-2.0" ]
7
2015-12-15T12:12:23.000Z
2019-10-16T16:48:40.000Z
/** * Software submitted by * Systems & Technology Research / Vision Systems Inc., 2013 * * Approved for public release; distribution is unlimited. [DISTAR Case #21428] * * 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. * * For more about this software visit: * * http://www.graphlab.ml.cmu.edu * */ #ifndef VSI_FACTOR_GRAPH_HPP #define VSI_FACTOR_GRAPH_HPP #include <cassert> #include <iostream> #include <fstream> #include <sstream> #include <set> #include <map> //#include <graphlab/engine/engine_includes.hpp> #include <graphlab/graph/graph_includes.hpp> #include <graphlab/serialization/serialization_includes.hpp> #include <graphlab/vertex_program/vertex_program_includes.hpp> #include "table_factor.hpp" #include "bp_graph_data.h" //#include <graphlab/macros_def.hpp> namespace belief_prop { /** * Defines a factor_graph; i.e., a bipartite graph whose verticies can * be divide into two disjoint sets: a set of variables V and a set of * factors F. Undirected edges connect factors to variables. An edge * exists between f and v if v is a member of the factor's domain. * * A variable specifies a unary discrete probabiltiy mass function over * a set of labels. A variable's PMF is assumed to be defined by a * dense_table in which each label has a corresponding probability. * * A factor specifies a discrete joint probability mass function over * a set of variables. The n-D PMF is defined by either a dense_table * or a sparse_table. The values in the table are stored such that the * first variable added to the domain iterates the fastest. * * The typical usasge of this interface would consist of 1) adding a set * of variables by using add_variable(), 2) defining the prior distribution * over each variable by using one of the prior related methods (such as * set_prior_for_variable() ), 3) adding a set of factors by using * add_factor(), 4) constructing the distributed graph using make_bp_graph(), * 5) running belief propagation on the distributed graph to propagate the * evidence across the graph (outside the scope of this interface), and * 6) loading the results using pull_beliefs_for_variables(). * * The resulting belief for a variable can be queried using * belief_for_variable().logP() (once the evidence has been propagated * across the distributed graph and the results pulled back into the * factor_graph using pull_beliefs_for_variables() ). * * \author Scott Richardson 10/2012 * */ // NOTE a variable has a domain that spans only itself. a factor has // a domain that spans its neighboring variables template<size_t MAX_DIM> class factor_graph { typedef typename graph_type<MAX_DIM>::type graph_type_t; typedef vertex_data<MAX_DIM> vertex_data_t; typedef edge_data<MAX_DIM> edge_data_t; // dense_table is used to define the distributions over variables. // *this shouldnt need to know specifically about sparse_table typedef graphlab::dense_table<MAX_DIM> dense_table_t; typedef graphlab::table_base<MAX_DIM> table_base_t; typedef graphlab::table_factor<MAX_DIM> factor_type; typedef graphlab::discrete_variable variable_type; // variable related methods public: factor_graph() : _unique_var_id(0) { } public: /** Add a new discrete variable to the factor graph */ // TODO rename to create_variable() variable_type add_variable(const size_t n_labels, const std::string& default_var_name="") { size_t id = _unique_var_id++; // assert that the id can be used to index into _factors DCHECK_EQ(id, num_factors()); // Only store the variable in the local variable map if the variable (key) // does not exist in the graph (map) already // var_map_const_iter_type it = _var_map.find(var_name); // if(it != _var_map.end()) { // std::cout << "WARNING: variable already exists for that name" << std::endl; // return it->second; // } // Create a new variable variable_type variable(id, n_labels); std::string var_name(default_var_name); if(var_name.empty()) { std::stringstream ss; ss << id; var_name = ss.str(); } // Save the factor to the factor graph vertex_data_t vert = add_vertex(variable, var_name); logstream(LOG_INFO) << "var_id=" << id << " description='" << vert.name << "'" << std::endl; return variable; } /** * Direct access to the variable's belief distribution. * useful for initialization */ dense_table_t& belief_for_variable(const variable_type& var) { DCHECK_LT(var.id(), num_factors()); // NOTE the variable's prior distribution is always dense dense_table_t* belief = dynamic_cast<dense_table_t*>(factors()[var.id()].belief.table()); DCHECK_NE(belief, NULL); return *belief; } dense_table_t& belief_for_var(const variable_type& var) { return belief_for_variable(var); } /** * Direct access to the variable's belief distribution. */ const dense_table_t& belief_for_variable(const variable_type& var) const { DCHECK_LT(var.id(), num_factors()); // NOTE the variable's prior distribution is always dense dense_table_t const *const belief = dynamic_cast<dense_table_t const *const>( factors()[var.id()].belief.table()); DCHECK_NE(belief, NULL); return *belief; } const dense_table_t& belief_for_var(const variable_type& var) const { return belief_for_variable(var); } /** * Direct access to the variable's prior distribution. * useful for initialization */ dense_table_t& prior_for_variable(const variable_type& var) { DCHECK_LT(var.id(), num_factors()); // NOTE the variable's prior distribution is always dense dense_table_t* potential = dynamic_cast<dense_table_t*>(factors()[var.id()].potential.table()); DCHECK_NE(potential, NULL); return *potential; } /** * Direct access to the variable's prior distribution. */ const dense_table_t& prior_for_variable(const variable_type& var) const { DCHECK_LT(var.id(), num_factors()); // NOTE the variable's prior distribution is always dense dense_table_t const *const potential = dynamic_cast<dense_table_t const *const>(factors()[var.id()].potential.table()); DCHECK_NE(potential, NULL); return *potential; } // TODO rename to stage_prior_for_variable, etc. void set_prior_for_variable(const variable_type& var, const std::vector<double>& data) { DCHECK_LT(var.id(), num_factors()); factor_type& potential = factors()[var.id()].potential; // NOTE the variable's prior distribution is always dense dense_table_t* table = dynamic_cast<dense_table_t* >(potential.table()); DCHECK_NE(table, NULL); *table = dense_table_t(table->domain(), data); } void set_belief_for_variable(const variable_type& var, const std::vector<double>& data) { DCHECK_LT(var.id(), num_factors()); factor_type& belief = factors()[var.id()].belief; // NOTE the variable's prior distribution is always dense dense_table_t* table = dynamic_cast<dense_table_t* >(belief.table()); DCHECK_NE(table, NULL); *table = dense_table_t(table->domain(), data); } void set_prior_for_variable(const variable_type& var, const dense_table_t& table) { DCHECK_LT(var.id(), num_factors()); factors()[var.id()].potential = factor_type(factor_type::DENSE_TABLE, table); } void set_belief_for_variable(const variable_type& var, const dense_table_t& table) { DCHECK_LT(var.id(), num_factors()); factors()[var.id()].belief = factor_type(factor_type::DENSE_TABLE, table); } variable_type get_variable(const size_t id) { DCHECK_LT(id, num_factors()); DCHECK_EQ(factors()[id].potential.table()->ndims(), 1); return factors()[id].potential.table()->var(0); } private: // REVIEW prevent a variable from being double added const vertex_data_t& add_vertex(const variable_type &variable, const std::string& var_name) { // assert that the id can be used to index into _factors DCHECK_EQ(variable.id(), num_factors()); // Define a unary factor (the concept not the class) over the var to // support a prior. // NOTE the variable's prior distribution is always dense factor_type prior(factor_type::DENSE_TABLE, dense_table_t(variable)); // using shift normalization, this is equivalent to uniform() prior.table()->zero(); // NOTE the variable's prior distribution is always dense factor_type belief(factor_type::DENSE_TABLE, dense_table_t(variable)); // using shift normalization, this is equivalent to uniform() belief.table()->zero(); // assert that prior and belief have the same domain //ASSERT_TRUE(belief.domain() == prior.domain()); // catalog the variable and associated metadata vertex_data_t vertex(prior, belief, true, var_name); _factors.push_back(vertex); //ASSERT_EQ(_factors[variable.id()].belief, vertex.belief); //ASSERT_EQ(_factors[variable.id()].potential, vertex.potential); return _factors.back(); } factor_type uniform_factor_from_factor(const factor_type& factor) { factor_type belief = factor; // using shift normalization, this is equivalent to uniform() belief.table()->zero(); return belief; } // factor related methods public: /** Add a new discrete factor to the factor graph */ // REVIEW prevent a factor from being double added void add_factor(const table_base_t& factor, const std::string& default_factor_name = "") { size_t id = _unique_var_id++; DCHECK_NE(factor.ndims(), 0); // assert that the id can be used to index into _factors DCHECK_EQ(id, num_factors()); std::string factor_name; if(default_factor_name.empty()) { std::stringstream ss; ss << id; factor_name = ss.str(); } else { factor_name = default_factor_name; } // assert all variables have already been added to the graph logstream(LOG_INFO) << "ndims=" << factor.ndims() << " id=" << id << " description='" << factor_name << "'" << std::endl; for(size_t i = 0; i < factor.ndims(); ++i) { logstream(LOG_INFO) << " factor.var(" << i << ").id()=" << factor.var(i).id() << std::endl; DCHECK_LT(factor.var(i).id(), num_factors()); DCHECK_EQ(factor.var(i).id(), get_variable(factor.var(i).id()).id()); } factor_type node(factor); factor_type uniform = uniform_factor_from_factor(node); vertex_data_t vertex(node, uniform, false, factor_name); _factors.push_back(vertex); //ASSERT_EQ(_factors[id], vertex); } // utils public: size_t num_factors() const { return factors().size(); } // FIXME O(n) size_t num_variables() const { size_t ndims = 0; for(typename std::vector<vertex_data_t >::const_iterator factor = factors().begin(); factor != factors().end(); ++factor) { // any vertex that has a domain with only a single dimension is a variable ... if(factor->potential.table()->ndims() == 1) { ndims++; } } return ndims; } const std::string& name(const size_t id) const { DCHECK_LT(id, num_factors()); return factors()[id].name; } /** * write a dot file which can be loaded into graphviz */ void save_graph_summary(const std::string& filename) { DCHECK_EQ(_unique_var_id, num_factors()); std::ofstream fout(filename.c_str()); if(fout.is_open() == false) { std::cerr << "ERROR: " << filename << " not opened." << std::endl; return; } fout << "graph G {" << std::endl; fout << "layout=sfdp;" << std::endl; fout << "overlap=false;" << std::endl; //fout << "sccmap;" << std::endl; fout << "K=2;" << std::endl; //fout << "clusterrank=local;" << std::endl; // Iterate all the factors and all the edges. NOTE all variables are also factors typename std::vector<vertex_data_t >::const_iterator factor; size_t factor_idx = 0; for(factor = factors().begin(); factor != factors().end(); ++factor_idx, ++factor) { //fout << "subgraph cluster_" << factor_idx << " {" << std::endl; //fout << "color=none;" << std::endl; // Iterate edges for a factor for(size_t i = 0; i < factor->potential.table()->ndims(); ++i) { variable_type variable = factor->potential.table()->var(i); // all variables are also factors, dont link a variable to itself if(variable.id() == factor_idx) continue; fout << "\"" << factor->name << " {" << factor_idx << "}" << "\" -- \"" << name(variable.id()) << "{" << variable.id() << "}" << "\";" << std::endl; } //fout << "}" << std::endl; } fout << "}" << std::endl; } // end of save_graph_summary /** * Construct a belief propagation graph from a factor graph */ // NOTE could rewrite this function to construct the graph in parallel using // the graphlab::distributed_control obj // TODO rename to finalize_distributed_graph() // REVIEW because bound, damping and regularization are now an attribute of a // factor, perhaps they should be set in add_factor() void make_bp_graph(graph_type_t& graph, double bound, double damping, double regularization=0.0) { DCHECK_NE(num_factors(), 0); DCHECK_EQ(_unique_var_id, num_factors()); // TODO clear the graph graphlab::timer timer; if (graph.dc().procid() == 0) { // Add all the factors and all the edges. NOTE all variables are also factors typename std::vector<vertex_data_t >::iterator factor = factors().begin(); typename std::vector<vertex_data_t >::const_iterator end = factors().end(); size_t factor_idx = 0; for( ; factor != end; ++factor_idx, ++factor) { // Add the factor to the graph factor->BOUND = bound; factor->DAMPING = damping; factor->REGULARIZATION = regularization; graph.add_vertex(factor_idx, *factor); // TODO does the order in which i add variables and factors matter? // Attach all the edges for(size_t i = 0; i < factor->potential.table()->ndims(); ++i) { variable_type variable = factor->potential.table()->var(i); // all variables are also factors, dont link a variable to itself if(variable.id() == factor_idx) continue; // NOTE from graph::add_edge() - An edge can only be added if both the // source and target vertex id's are already in the graph. Duplicate // edges are not supported and may result in undefined behavior // NOTE messages are always dense dense_table_t msg(variable); msg.zero(); // using shift normalization, this is equivalent to uniform() graph.add_edge(factor_idx, variable.id(), edge_data_t(msg)); } } graph.dc().cout() << "Loading graph. Finished in " << timer.current_time() << std::endl; } timer.start(); graph.finalize(); graph.dc().cout() << "Finalizing graph. Finished in " << timer.current_time() << std::endl; graph.dc().cout() << "================ " << "Graph statistics on proc " << graph.dc().procid() << " of " << graph.dc().numprocs() << " ===============" << "\n Num vertices: " << graph.num_vertices() << "\n Num edges: " << graph.num_edges() << "\n Num replica: " << graph.num_replicas() << "\n Replica to vertex ratio: " << float(graph.num_replicas())/graph.num_vertices() << "\n --------------------------------------------" << "\n Num local own vertices: " << graph.num_local_own_vertices() << "\n Num local vertices: " << graph.num_local_vertices() << "\n Replica to own ratio: " << (float)graph.num_local_vertices()/graph.num_local_own_vertices() << "\n Num local edges: " << graph.num_local_edges() //<< "\n Begin edge id: " << graph.global_eid(0) << "\n Edge balance ratio: " << float(graph.num_local_edges())/graph.num_edges() << std::endl; } // end of make_bp_graph /** * Update the value of the variables' beliefs given the propegated * graphlab distributed-graph. */ // TODO rename to pull_beliefs void pull_beliefs_for_variables(graph_type_t& graph) { typedef dense_table_t const *const const_ptr; // aggregate (reduce) the variable verticies into a vector aggregate_vertex_data agg = graph.template map_reduce_vertices<aggregate_vertex_data>( aggregate_vertex_data() ); // wow for(unsigned i=0; i < agg.size(); ++i) { const vertex_data_t& ovdata = agg.agg[i]; DCHECK_EQ(ovdata.belief.table()->ndims(), 1); const_ptr other = dynamic_cast<const_ptr>(ovdata.belief.table()); if(other == NULL) { std::cout << "ERROR: std::bad_cast" << std::endl; // REVIEW should probably raise an exception ASSERT_TRUE(false); } vertex_data_t& vdata = factors()[other->args().var(0).id()]; DCHECK_EQ(vdata.belief.table()->ndims(), 1); const_ptr tbl = dynamic_cast<const_ptr>(vdata.belief.table()); if(tbl == NULL) { std::cout << "ERROR: std::bad_cast" << std::endl; // REVIEW should probably raise an exception ASSERT_TRUE(false); } ASSERT_EQ(tbl->args().var(0).id(), other->args().var(0).id()); vdata.belief = ovdata.belief; } } private: struct aggregate_vertex_data { std::vector<vertex_data_t> agg; aggregate_vertex_data() { } aggregate_vertex_data operator()(const typename graph_type_t::vertex_type& vertex) { const vertex_data_t& ovdata = vertex.data(); aggregate_vertex_data out; // variables are always dense and 1D, although not all 1D vertices are variables... if(ovdata.isVariable == true) { out.agg.push_back(ovdata); } return out; } aggregate_vertex_data& operator+=(const aggregate_vertex_data& other) { agg.insert(agg.end(), other.agg.begin(), other.agg.end()); return *this; } unsigned size() { return agg.size(); } void save(graphlab::oarchive& arc) const { arc << agg; } void load(graphlab::iarchive& arc) { arc >> agg; } }; public: void print_variable(const variable_type& var, const std::vector<double>& labels, std::ostream& out = std::cout) { const dense_table_t& table = belief_for_variable(var); DCHECK_EQ(table.size(), labels.size()); //std::ios::fmtflags f(out.flags()); // i cant believe this is how you do this out << "var_" << var.id() << ": " << factors()[var.id()].name << std::endl; out << std::setw(8) << "index" << std::setw(16) << "logP" << std::setw(16) << "label" << std::endl; size_t end = table.size(); for(size_t i=0; i < end; ++i) { out << std::setw(8) << i << std::setw(16) << table.logP(i) << std::setw(16) << labels[i] << std::endl; } //out.flags(f); } // accessors private: const std::vector<vertex_data_t>& factors() const { return _factors; } std::vector<vertex_data_t>& factors() { return _factors; } private: // NOTE if ever multithreaded, this requires atomic access size_t _unique_var_id; // REVIEW deep-copying data into std::vectors is slow std::vector<vertex_data_t > _factors; }; } // end of namespace belief_prop //#include <graphlab/macros_undef.hpp> #endif // VSI_FACTOR_GRAPH_HPP
35.226876
103
0.650879
coreyp1
51d1d70790c93f46bfa0fc6a1130c74d67f5695a
8,105
hpp
C++
hipcub/include/hipcub/backend/rocprim/grid/grid_queue.hpp
ROCmMathLibrariesBot/hipCUB
003a5b2b791dc01e88d0c0caaaf1de9ae53ad638
[ "BSD-3-Clause" ]
36
2019-05-14T09:27:57.000Z
2022-03-03T09:19:11.000Z
hipcub/include/hipcub/backend/rocprim/grid/grid_queue.hpp
ROCmMathLibrariesBot/hipCUB
003a5b2b791dc01e88d0c0caaaf1de9ae53ad638
[ "BSD-3-Clause" ]
70
2019-05-06T23:07:53.000Z
2022-03-17T08:24:22.000Z
hipcub/include/hipcub/backend/rocprim/grid/grid_queue.hpp
ROCmMathLibrariesBot/hipCUB
003a5b2b791dc01e88d0c0caaaf1de9ae53ad638
[ "BSD-3-Clause" ]
25
2019-05-03T19:45:13.000Z
2022-03-31T08:14:38.000Z
/****************************************************************************** * Copyright (c) 2011, Duane Merrill. All rights reserved. * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. * Modifications Copyright (c) 2021, Advanced Micro Devices, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION 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. * ******************************************************************************/ #ifndef HIPCUB_ROCPRIM_GRID_GRID_QUEUE_HPP_ #define HIPCUB_ROCPRIM_GRID_GRID_QUEUE_HPP_ #include <type_traits> #include "../../../config.hpp" BEGIN_HIPCUB_NAMESPACE /** * \addtogroup GridModule * @{ */ /** * \brief GridQueue is a descriptor utility for dynamic queue management. * * \par Overview * GridQueue descriptors provides abstractions for "filling" or * "draining" globally-shared vectors. * * \par * A "filling" GridQueue works by atomically-adding to a zero-initialized counter, * returning a unique offset for the calling thread to write its items. * The GridQueue maintains the total "fill-size". The fill counter must be reset * using GridQueue::ResetFill by the host or kernel instance prior to the kernel instance that * will be filling. * * \par * Similarly, a "draining" GridQueue works by works by atomically-incrementing a * zero-initialized counter, returning a unique offset for the calling thread to * read its items. Threads can safely drain until the array's logical fill-size is * exceeded. The drain counter must be reset using GridQueue::ResetDrain or * GridQueue::FillAndResetDrain by the host or kernel instance prior to the kernel instance that * will be filling. (For dynamic work distribution of existing data, the corresponding fill-size * is simply the number of elements in the array.) * * \par * Iterative work management can be implemented simply with a pair of flip-flopping * work buffers, each with an associated set of fill and drain GridQueue descriptors. * * \tparam OffsetT Signed integer type for global offsets */ template <typename OffsetT> class GridQueue { private: /// Counter indices enum { FILL = 0, DRAIN = 1, }; /// Pair of counters OffsetT *d_counters; public: /// Returns the device allocation size in bytes needed to construct a GridQueue instance __host__ __device__ __forceinline__ static size_t AllocationSize() { return sizeof(OffsetT) * 2; } /// Constructs an invalid GridQueue descriptor __host__ __device__ __forceinline__ GridQueue() : d_counters(NULL) {} /// Constructs a GridQueue descriptor around the device storage allocation __host__ __device__ __forceinline__ GridQueue( void *d_storage) ///< Device allocation to back the GridQueue. Must be at least as big as <tt>AllocationSize()</tt>. : d_counters((OffsetT*) d_storage) {} /// This operation sets the fill-size and resets the drain counter, preparing the GridQueue for draining in the next kernel instance. To be called by the host or by a kernel prior to that which will be draining. HIPCUB_DEVICE hipError_t FillAndResetDrain( OffsetT fill_size, hipStream_t stream = 0) { hipError_t result = hipErrorUnknown; (void)stream; d_counters[FILL] = fill_size; d_counters[DRAIN] = 0; result = hipSuccess; return result; } HIPCUB_HOST hipError_t FillAndResetDrain( OffsetT fill_size, hipStream_t stream = 0) { hipError_t result = hipErrorUnknown; OffsetT counters[2]; counters[FILL] = fill_size; counters[DRAIN] = 0; result = CubDebug(hipMemcpyAsync(d_counters, counters, sizeof(OffsetT) * 2, hipMemcpyHostToDevice, stream)); return result; } /// This operation resets the drain so that it may advance to meet the existing fill-size. To be called by the host or by a kernel prior to that which will be draining. HIPCUB_DEVICE hipError_t ResetDrain(hipStream_t stream = 0) { hipError_t result = hipErrorUnknown; (void)stream; d_counters[DRAIN] = 0; result = hipSuccess; return result; } HIPCUB_HOST hipError_t ResetDrain(hipStream_t stream = 0) { hipError_t result = hipErrorUnknown; result = CubDebug(hipMemsetAsync(d_counters + DRAIN, 0, sizeof(OffsetT), stream)); return result; } /// This operation resets the fill counter. To be called by the host or by a kernel prior to that which will be filling. HIPCUB_DEVICE hipError_t ResetFill(hipStream_t stream = 0) { hipError_t result = hipErrorUnknown; (void)stream; d_counters[FILL] = 0; result = hipSuccess; return result; } HIPCUB_HOST hipError_t ResetFill(hipStream_t stream = 0) { hipError_t result = hipErrorUnknown; result = CubDebug(hipMemsetAsync(d_counters + FILL, 0, sizeof(OffsetT), stream)); return result; } /// Returns the fill-size established by the parent or by the previous kernel. HIPCUB_DEVICE hipError_t FillSize( OffsetT &fill_size, hipStream_t stream = 0) { hipError_t result = hipErrorUnknown; (void)stream; fill_size = d_counters[FILL]; result = hipSuccess; return result; } HIPCUB_HOST hipError_t FillSize( OffsetT &fill_size, hipStream_t stream = 0) { hipError_t result = hipErrorUnknown; result = CubDebug(hipMemcpyAsync(&fill_size, d_counters + FILL, sizeof(OffsetT), hipMemcpyDeviceToHost, stream)); return result; } /// Drain \p num_items from the queue. Returns offset from which to read items. To be called from hip kernel. HIPCUB_DEVICE OffsetT Drain(OffsetT num_items) { return atomicAdd(d_counters + DRAIN, num_items); } /// Fill \p num_items into the queue. Returns offset from which to write items. To be called from hip kernel. HIPCUB_DEVICE OffsetT Fill(OffsetT num_items) { return atomicAdd(d_counters + FILL, num_items); } }; #ifndef DOXYGEN_SHOULD_SKIP_THIS // Do not document /** * Reset grid queue (call with 1 block of 1 thread) */ template <typename OffsetT> __global__ void FillAndResetDrainKernel( GridQueue<OffsetT> grid_queue, OffsetT num_items) { grid_queue.FillAndResetDrain(num_items); } #endif // DOXYGEN_SHOULD_SKIP_THIS /** @} */ // end group GridModule END_HIPCUB_NAMESPACE #endif // HIPCUB_ROCPRIM_GRID_GRID_QUEUE_HPP_
34.34322
216
0.68723
ROCmMathLibrariesBot
51d23d123984af1afa6c2678ee5cbe8c25b0f6bf
1,225
cpp
C++
codeforces/977D - Divide by three, multiply by two.cpp
Dijkstraido-2/online-judge
31844cd8fbd5038cc5ebc6337d68229cef133a30
[ "MIT" ]
1
2018-12-25T23:55:19.000Z
2018-12-25T23:55:19.000Z
codeforces/977D - Divide by three, multiply by two.cpp
Dijkstraido-2/online-judge
31844cd8fbd5038cc5ebc6337d68229cef133a30
[ "MIT" ]
null
null
null
codeforces/977D - Divide by three, multiply by two.cpp
Dijkstraido-2/online-judge
31844cd8fbd5038cc5ebc6337d68229cef133a30
[ "MIT" ]
null
null
null
//============================================================================ // Problem : 977D - Divide by three, multiply by two // Category : Topsort //============================================================================ #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<ll> vl; typedef vector<int> vi; typedef vector<vi> vvi; vl v; vi color,sorted; vvi g; int n; void dfs(int v) { color[v] = 1; for(int u : g[v]) if(!color[u]) dfs(u); sorted.push_back(v); } void topsort() { color = vi(n, 0); sorted.clear(); for(int i = 0; i < n; i++) if(!color[i]) dfs(i); reverse(sorted.begin(), sorted.end()); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); while(cin >> n) { v = vl(n); for(int i = 0; i < n; i++) cin >> v[i]; g = vvi(n); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) if(i != j && (v[i]*2 == v[j] || (v[i]%3 == 0 && v[i]/3 == v[j]))) g[i].push_back(j); topsort(); for(int i = 0; i < n; i++) cout << v[sorted[i]] << " \n"[i==n-1]; } return 0; }
22.685185
81
0.395102
Dijkstraido-2
51d5556f4c4bf4e9cdcd4ef4a4df5a3d933c111a
3,029
cpp
C++
XJ Contests/2020/10.31/independent/independent.cpp
jinzhengyu1212/Clovers
0efbb0d87b5c035e548103409c67914a1f776752
[ "MIT" ]
null
null
null
XJ Contests/2020/10.31/independent/independent.cpp
jinzhengyu1212/Clovers
0efbb0d87b5c035e548103409c67914a1f776752
[ "MIT" ]
null
null
null
XJ Contests/2020/10.31/independent/independent.cpp
jinzhengyu1212/Clovers
0efbb0d87b5c035e548103409c67914a1f776752
[ "MIT" ]
null
null
null
/* the vast starry sky, bright for those who chase the light. */ #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> pii; #define mk make_pair const int inf=(int)1e9; const ll INF=(ll)5e18; const int MOD=998244353; int add(int x,int y){x+=y; return x>=MOD ? x-MOD : x;} int sub(int x,int y){x-=y; return x<0 ? x+MOD : x;} #define mul(x,y) (ll)(x)*(y)%MOD int qpow(int x,int y){int ret=1; while(y){if(y&1) ret=mul(ret,x); x=mul(x,x); y>>=1;} return ret;} void checkmin(int &x,int y){if(x>y) x=y;} void checkmax(int &x,int y){if(x<y) x=y;} void checkmin(ll &x,ll y){if(x>y) x=y;} void checkmax(ll &x,ll y){if(x<y) x=y;} #define out(x) cerr<<#x<<'='<<x<<' ' #define outln(x) cerr<<#x<<'='<<x<<endl #define Sz(x) (int)(x).size() inline int read(){ int x=0,f=1; char c=getchar(); while(c>'9'||c<'0'){if(c=='-') f=-1; c=getchar();} while(c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar(); return x*f; } const int N=300005; int n,k,fa[N],son[N],dep[N]; vector<int> v[N]; struct node{ int x,maxx; }; vector<node> dp[N]; int id[N],mxdep[N]; void dfs1(int u){ mxdep[u]=dep[u]; for(auto to : v[u]){ dep[to]=dep[u]+1; dfs1(to); checkmax(mxdep[u],mxdep[to]+1); if(mxdep[son[u]]<mxdep[to]) son[u]=to; } } int T[N]; void dfs2(int u){ int szu=0; if(son[u]){ dfs2(son[u]),id[u]=id[son[u]]; szu=Sz(dp[id[u]]); int tt=dp[id[u]][szu-1].maxx; if(szu>k) checkmax(tt,dp[id[u]][szu-k-1].maxx+1); dp[id[u]].push_back({tt,tt}); } else dp[id[u]].push_back({1,1}); szu++; for(auto to : v[u]){ if(to==son[u]) continue; dfs2(to); dp[id[to]].push_back({0,0}); for(int i=0;i<Sz(dp[id[to]]);i++){ T[i]=1; int tmp=max(i,k+1-i),szto=Sz(dp[id[to]]); if(tmp<Sz(dp[id[u]])) checkmax(T[i],dp[id[to]][szto-i-1].x+dp[id[u]][szu-tmp-1].maxx); else checkmax(T[i],dp[id[to]][szto-i-1].x); if(tmp<Sz(dp[id[to]])) checkmax(T[i],dp[id[u]][szu-i-1].x+dp[id[to]][szto-tmp-1].maxx); else checkmax(T[i],dp[id[u]][szu-i-1].x); } for(int i=0;i<Sz(dp[id[to]]);i++) dp[id[u]][szu-i-1].x=T[i]; for(int i=Sz(dp[id[to]])-1;i>=0;i--){ int tmp=szu-i-1; checkmax(dp[id[u]][tmp].maxx,dp[id[u]][tmp].x); if(tmp) checkmax(dp[id[u]][tmp].maxx,dp[id[u]][tmp-1].maxx); } dp[id[to]].clear(); } //outln(u); //for(auto to : dp[id[u]]) cout<<to.x<<" "<<to.maxx<<endl; } int main() { n=read(); k=read()-1; for(int i=1;i<=n;i++) dp[i].clear(); for(int i=2;i<=n;i++){ fa[i]=read()+1; v[fa[i]].push_back(i); } if(k==0){ printf("%d\n",n); return 0; } for(int i=1;i<=n;i++) id[i]=i; dfs1(1); dfs2(1); int ans=1; for(int i=0;i<Sz(dp[id[1]]);i++) checkmax(ans,dp[id[1]][i].x); cout<<ans<<endl; return 0; }
28.308411
98
0.493232
jinzhengyu1212
51d77d223f36b8d56658c52a25c8d7a260728653
5,949
cpp
C++
src/examples/meshviewer/util/frustumhelpers.cpp
bfierz/vcl
6ef8d446b6a2f46543a5b3f9f76cad0d8f691969
[ "MIT" ]
15
2015-05-15T09:14:42.000Z
2022-02-20T13:00:17.000Z
src/examples/meshviewer/util/frustumhelpers.cpp
bfierz/vcl
6ef8d446b6a2f46543a5b3f9f76cad0d8f691969
[ "MIT" ]
54
2015-05-14T09:21:51.000Z
2021-05-28T06:09:06.000Z
src/examples/meshviewer/util/frustumhelpers.cpp
bfierz/vcl
6ef8d446b6a2f46543a5b3f9f76cad0d8f691969
[ "MIT" ]
4
2017-04-18T06:16:42.000Z
2021-07-16T08:00:12.000Z
/* * This file is part of the Visual Computing Library (VCL) release under the * MIT license. * * Copyright (c) 2015 Basil Fierz * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "frustumhelpers.h" // VCL #include <vcl/geometry/marchingcubestables.h> namespace Vcl { namespace Util { Eigen::Vector4f computeFrustumSize(const Eigen::Vector4f& frustum) { // tan(fov / 2) float scale = frustum.x(); float ratio = frustum.y(); float near_dist = frustum.z(); float far_dist = frustum.w(); float near_half_height = scale * near_dist; float near_half_width = near_half_height * ratio; float far_half_height = scale * far_dist; float far_half_width = far_half_height * ratio; return { near_half_width, near_half_height, far_half_width, far_half_height }; } Eigen::Vector3f intersectRayPlane(const Eigen::Vector3f& p0, const Eigen::Vector3f& dir, const Eigen::Vector4f& plane) { Eigen::Vector3f N = plane.segment<3>(0); float d = plane.w(); // Point on plane Eigen::Vector3f P = d * N; float t = (P - p0).dot(N) / dir.dot(N); return p0 + t * dir; } // https://de.wikipedia.org/wiki/Hessesche_Normalform#Abstand_2 float computePlaneVertexDistance(const Eigen::Vector4f& eq, const Eigen::Vector3f& v) { Eigen::Vector3f N = eq.segment<3>(0); float d = eq.w(); // Distance point-plane float dist = v.dot(N) - d; return dist; } void computePlaneFrustumIntersection(const Eigen::Vector4f& plane, const Eigen::Matrix4f& View, const Eigen::Vector4f& Frustum, std::vector<Eigen::Vector3f>& vertices) { Eigen::Vector3f N = plane.segment<3>(0); float d = plane.w(); // Point on plane Eigen::Vector3f P = d * N; // Transform the plane normal to the view-space P = (View * Eigen::Vector4f(P.x(), P.y(), P.z(), 1)).segment<3>(0); N = View.block<3, 3>(0, 0) * N; d = P.dot(N); Eigen::Vector4f transformed_plane{ N.x(), N.y(), N.z(), d }; // Compute the rays of the frustum from camera point into screen Eigen::Vector4f frustum_size = computeFrustumSize(Frustum); // Computed frustum points Eigen::Vector3f fc[8]; // Points of the near plane Eigen::Vector3f point_on_near = Eigen::Vector3f(0, 0, -Frustum.z()); fc[0] = point_on_near + Eigen::Vector3f(1, 0, 0) * frustum_size.x() - Eigen::Vector3f(0, 1, 0) * frustum_size.y(); fc[1] = point_on_near - Eigen::Vector3f(1, 0, 0) * frustum_size.x() - Eigen::Vector3f(0, 1, 0) * frustum_size.y(); fc[2] = point_on_near - Eigen::Vector3f(1, 0, 0) * frustum_size.x() + Eigen::Vector3f(0, 1, 0) * frustum_size.y(); fc[3] = point_on_near + Eigen::Vector3f(1, 0, 0) * frustum_size.x() + Eigen::Vector3f(0, 1, 0) * frustum_size.y(); // Distance of near plane float dn0 = computePlaneVertexDistance(transformed_plane, fc[0]); float dn1 = computePlaneVertexDistance(transformed_plane, fc[1]); float dn2 = computePlaneVertexDistance(transformed_plane, fc[2]); float dn3 = computePlaneVertexDistance(transformed_plane, fc[3]); // Points of the far plane Eigen::Vector3f point_on_far = Eigen::Vector3f(0, 0, -Frustum.w()); fc[4] = point_on_far + Eigen::Vector3f(1, 0, 0) * frustum_size.z() - Eigen::Vector3f(0, 1, 0) * frustum_size.w(); fc[5] = point_on_far - Eigen::Vector3f(1, 0, 0) * frustum_size.z() - Eigen::Vector3f(0, 1, 0) * frustum_size.w(); fc[6] = point_on_far - Eigen::Vector3f(1, 0, 0) * frustum_size.z() + Eigen::Vector3f(0, 1, 0) * frustum_size.w(); fc[7] = point_on_far + Eigen::Vector3f(1, 0, 0) * frustum_size.z() + Eigen::Vector3f(0, 1, 0) * frustum_size.w(); // Distance of far plane float df0 = computePlaneVertexDistance(transformed_plane, fc[4]); float df1 = computePlaneVertexDistance(transformed_plane, fc[5]); float df2 = computePlaneVertexDistance(transformed_plane, fc[6]); float df3 = computePlaneVertexDistance(transformed_plane, fc[7]); // Compute MC table index int num_tri_idx = ((df3 >= 0) << 7) | ((df2 >= 0) << 6) | ((df1 >= 0) << 5) | ((df0 >= 0) << 4) | ((dn3 >= 0) << 3) | ((dn2 >= 0) << 2) | ((dn1 >= 0) << 1) | ((dn0 >= 0) << 0); // How many triangles are we generating int num_tris = Vcl::Geometry::caseToNumPolys[num_tri_idx]; // List of triangles auto tris = (Eigen::Vector4i*)Vcl::Geometry::edgeVertexList + (5 * num_tri_idx); // Prepare storage vertices.reserve(vertices.size() + 15); for (int t = 0; t < num_tris; t++) { const auto& tri = tris[t]; for (int i = 0; i < 3; i++) { if (tri(i) < 4) { vertices.emplace_back(intersectRayPlane(fc[tri(i)], (fc[(tri(i) + 1) % 4] - fc[tri(i)]).normalized(), transformed_plane)); } else if (tri(i) < 8) { vertices.emplace_back(intersectRayPlane(fc[tri(i)], (fc[4 + (tri(i) + 1) % 4] - fc[tri(i)]).normalized(), transformed_plane)); } else { vertices.emplace_back(intersectRayPlane(fc[tri(i) - 4], (fc[tri(i) - 8] - fc[tri(i) - 4]).normalized(), transformed_plane)); } } } } }}
39.397351
168
0.673727
bfierz
51da91a4d2a4c7189a93f2a223108ff034bea36b
2,083
cpp
C++
problem1.cpp
NIKU-SINGH/Project-Euler
8398878a7ee5182cdd6e57ce2be8310ef2efdbef
[ "MIT" ]
null
null
null
problem1.cpp
NIKU-SINGH/Project-Euler
8398878a7ee5182cdd6e57ce2be8310ef2efdbef
[ "MIT" ]
null
null
null
problem1.cpp
NIKU-SINGH/Project-Euler
8398878a7ee5182cdd6e57ce2be8310ef2efdbef
[ "MIT" ]
null
null
null
/* *************************************QUESTION 1 ********************************************* If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ************************************************************************************************* */ //header files #include<iostream> using namespace std; //main function int main(){ int testcase; cin>>testcase; //loop to run for different test case for(int i=0;i<testcase;i++) { //Input of nunber upto which multiple needs to be calculated int n; cin>>n; //long long int because number gets large so it can store large number long long int MultiOfThree, MultiOfFive , MultiOfFifteen, SumOfMultiple=0; /* one of the approach can be that we though all numbers and check whether its is a multiple of five or three and then add. But that approach is time consuming . so in order to reduce time a new approach is required. that is we add multiples of three and five and subtract multiples of fifteen. by this we avoid checking each number. */ //To calculate how many mutiples are there of Three below n MultiOfThree = (n-1)/3; //To calculate how many mutiples are five of Three below n MultiOfFive = (n-1)/5; //To calculate how many mutiples are there of fifteen below n MultiOfFifteen = (n-1)/15; //together adding the sum of all multiple of 3,5 and subtracting 15 /*We Know sum of 3+6+9+12+....99 can be re written as ----> 3*(1 + 2 + 3 + 4 + ....33) 5 + 10 + 15 + 20 .... 95 -----> 5 * ( 1 + 2 + 3 + 4 +....19) 15 + 30 + 45 + ......90 ------> 15 * ( 1 + 2 +3 ...6) and we know sum of n Natural numbers is ---->[n*(n+1)/2] so applying that */ SumOfMultiple = (3*(MultiOfThree*(MultiOfThree+1)/2)) + (5*(MultiOfFive*(MultiOfFive+1)/2)) - (15*(MultiOfFifteen*(MultiOfFifteen+1)/2)); cout<<SumOfMultiple<<endl; } return 0; }
31.560606
140
0.576572
NIKU-SINGH
51e645b79043292d9853c5709bb7c91881da6daf
948
cpp
C++
.LHP/.Lop11/.T.Hung/GG_3/1197/1197/1197.cpp
sxweetlollipop2912/MaCode
661d77a2096e4d772fda2b6a7f80c84113b2cde9
[ "MIT" ]
null
null
null
.LHP/.Lop11/.T.Hung/GG_3/1197/1197/1197.cpp
sxweetlollipop2912/MaCode
661d77a2096e4d772fda2b6a7f80c84113b2cde9
[ "MIT" ]
null
null
null
.LHP/.Lop11/.T.Hung/GG_3/1197/1197/1197.cpp
sxweetlollipop2912/MaCode
661d77a2096e4d772fda2b6a7f80c84113b2cde9
[ "MIT" ]
null
null
null
// AC UVa #include <iostream> #include <algorithm> #include <cstdio> #pragma warning(disable:4996) #define maxN 30001 typedef int maxn; maxn n, m, par[maxN], size[maxN]; maxn Root(maxn x) { while (x != par[x]) x = par[x]; return x; } void Union(maxn x, maxn y) { x = Root(x), y = Root(y); if (x == y) return; if (size[x] > size[y]) par[y] = x, size[x] += size[y]; else par[x] = y, size[y] += size[x]; } void Prepare() { std::cin >> m; for (maxn i = 0; i < n; i++) par[i] = i, size[i] = 1; for (maxn i = 0; i < m; i++) { maxn cnt; std::cin >> cnt; if (!cnt) continue; maxn a; std::cin >> a; while (--cnt) { maxn x; std::cin >> x; Union(a, x); } } } void Process() { std::cout << size[Root(0)] << '\n'; } int main() { //freopen("1197.inp", "r", stdin); //freopen("1197.out", "w", stdout); std::ios_base::sync_with_stdio(0); std::cin.tie(0); while (std::cin >> n && n) { Prepare(); Process(); } }
15.290323
55
0.533755
sxweetlollipop2912
51ea02da102966e792a40a67debb6c6e7cb5ea29
14,531
hpp
C++
libs/storage/include/storage/new_versioned_random_access_stack.hpp
jinmannwong/ledger
f3b129c127e107603e08bb192eb695d23eb17dbc
[ "Apache-2.0" ]
null
null
null
libs/storage/include/storage/new_versioned_random_access_stack.hpp
jinmannwong/ledger
f3b129c127e107603e08bb192eb695d23eb17dbc
[ "Apache-2.0" ]
null
null
null
libs/storage/include/storage/new_versioned_random_access_stack.hpp
jinmannwong/ledger
f3b129c127e107603e08bb192eb695d23eb17dbc
[ "Apache-2.0" ]
2
2019-11-13T10:55:24.000Z
2019-11-13T11:37:09.000Z
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // 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. // //------------------------------------------------------------------------------ // // RANDOM ACCESS STACK // // ┌──────┬───────────┬───────────┬───────────┬───────────┐ // │ │ │ │ │ │ // │HEADER│ OBJECT │ OBJECT │ OBJECT │ OBJECT │ // │ │ │ │ │ │...... // │ │ │ │ │ │ // └──────┴───────────┴───────────┴───────────┴───────────┘ // │ ▲ // │ │ // │ │ // ▼ │ // ┌──────┬──────┬──────┬──────┬──────┐ // │ │ │ │ │ │ // ......│ PUSH │ POP │ SWAP │BKMARK│ PUSH │ HISTORY // │ │ │ │ │ │ // └──────┴──────┴──────┴──────┴──────┘ #include "storage/cached_random_access_stack.hpp" #include "storage/key.hpp" #include "storage/random_access_stack.hpp" #include "storage/storage_exception.hpp" #include "storage/variant_stack.hpp" #include "core/byte_array/encoders.hpp" #include <cstring> namespace fetch { namespace storage { // defined in key.hpp using DefaultKey = Key<256>; /** * This header is at the beginning of the main RAS and keeps track of the final bookmark in the * history stack */ struct NewBookmarkHeader { uint64_t header; uint64_t bookmark; // aim to remove this. }; /** * NewVersionedRandomAccessStack implements a random access stack that can revert to a previous * state. It does this by having a random access stack, and also keeping a stack recording all of * the state-changing operations made to the stack (in the history). The user can place bookmarks * which allow reverting the stack to it's state at that point in time. * * The history is a variant stack so as to allow different operations to be saved. However note that * the stack itself has elements of constant width, so no dynamically allocated memory. * */ template <typename T, typename S = RandomAccessStack<T, NewBookmarkHeader>> class NewVersionedRandomAccessStack { private: using stack_type = S; using header_extra_type = uint64_t; using header_type = NewBookmarkHeader; static constexpr char const *LOGGING_NAME = "NewVersionedRandomAccessStack"; /** * To be pushed onto the history stack as a variant. * * Represents a 'bookmark' that users can revert to. */ struct HistoryBookmark { HistoryBookmark() { // Clear the whole structure (including padded regions) are zeroed memset(this, 0, sizeof(decltype(*this))); } HistoryBookmark(uint64_t val, DefaultKey const &key_in) { // Clear the whole structure (including padded regions) are zeroed memset(this, 0, sizeof(decltype(*this))); bookmark = val; key = key_in; } enum { value = 0 }; uint64_t bookmark = 0; // Internal index DefaultKey key{}; // User supplied key }; /** * To be pushed onto the history stack as a variant. * * Represents a swap on the main stack, holds the information about which elements were swapped */ struct HistorySwap { HistorySwap() { // Clear the whole structure (including padded regions) are zeroed memset(this, 0, sizeof(decltype(*this))); } HistorySwap(uint64_t i_, uint64_t j_) { // Clear the whole structure (including padded regions) are zeroed memset(this, 0, sizeof(decltype(*this))); i = i_; j = j_; } enum { value = 1 }; uint64_t i = 0; uint64_t j = 0; }; /** * To be pushed onto the history stack as a variant. * * Represents a pop on the main stack, holds the popped element T from the main stack */ struct HistoryPop { HistoryPop() { // Clear the whole structure (including padded regions) are zeroed memset(this, 0, sizeof(decltype(*this))); } explicit HistoryPop(T const &d) { // Clear the whole structure (including padded regions) are zeroed memset(this, 0, sizeof(decltype(*this))); data = d; } enum { value = 2 }; T data{}; }; /** * To be pushed onto the history stack as a variant. * * Represents a push on the main stack, doesn't need any meta data since when reverting the * history this corresponds to a pop */ struct HistoryPush { HistoryPush() { // Clear the whole structure (including padded regions) are zeroed memset(this, 0, sizeof(decltype(*this))); } enum { value = 3 }; }; /** * To be pushed onto the history stack as a variant. * * Represents setting the history at a specific index. * * @param: i The index * @param: d The item * */ struct HistorySet { HistorySet() { // Clear the whole structure (including padded regions) are zeroed memset(this, 0, sizeof(decltype(*this))); } HistorySet(uint64_t i_, T const &d) { // Clear the whole structure (including padded regions) are zeroed memset(this, 0, sizeof(decltype(*this))); i = i_; data = d; } enum { value = 4 }; uint64_t i = 0; T data; }; /** * Represents a change to the header of the main stack, for example when changing the * 'extra' data that can be stored there. */ struct HistoryHeader { HistoryHeader() { // Clear the whole structure (including padded regions) are zeroed memset(this, 0, sizeof(decltype(*this))); } HistoryHeader(uint64_t d) { // Clear the whole structure (including padded regions) are zeroed memset(this, 0, sizeof(decltype(*this))); data = d; } enum { value = 5 }; uint64_t data = 0; }; public: using type = T; using event_handler_type = std::function<void()>; NewVersionedRandomAccessStack() { stack_.OnFileLoaded([this]() { SignalFileLoaded(); }); stack_.OnBeforeFlush([this]() { SignalBeforeFlush(); }); } ~NewVersionedRandomAccessStack() { stack_.ClearEventHandlers(); } void ClearEventHandlers() { on_file_loaded_ = nullptr; on_before_flush_ = nullptr; } void OnFileLoaded(event_handler_type const &f) { on_file_loaded_ = f; } void OnBeforeFlush(event_handler_type const &f) { on_before_flush_ = f; } void SignalFileLoaded() { if (on_file_loaded_) { on_file_loaded_(); } } void SignalBeforeFlush() { if (on_before_flush_) { on_before_flush_(); } } /** * Indicate whether the stack is writing directly to disk or caching writes. * * @return: Whether the stack is written straight to disk. */ static constexpr bool DirectWrite() { return stack_type::DirectWrite(); } void Load(std::string const &filename, std::string const &history, bool const &create_if_not_exist = true) { stack_.Load(filename, create_if_not_exist); history_.Load(history, create_if_not_exist); hash_history_.Load("hash_history_" + history, create_if_not_exist); internal_bookmark_index_ = stack_.header_extra().bookmark; } void New(std::string const &filename, std::string const &history) { stack_.New(filename); history_.New(history); hash_history_.New("hash_history_" + history); internal_bookmark_index_ = stack_.header_extra().bookmark; } void Clear() { stack_.Clear(); history_.Clear(); hash_history_.Clear(); internal_bookmark_index_ = stack_.header_extra().bookmark; } type Get(std::size_t i) const { type object; stack_.Get(i, object); return object; } void Get(std::size_t i, type &object) const { stack_.Get(i, object); } void Set(std::size_t i, type const &object) { type old_data; stack_.Get(i, old_data); history_.Push(HistorySet{i, old_data}, HistorySet::value); stack_.Set(i, object); } uint64_t Push(type const &object) { history_.Push(HistoryPush{}, HistoryPush::value); return stack_.Push(object); } void Pop() { type old_data = stack_.Top(); history_.Push(HistoryPop{old_data}, HistoryPop::value); stack_.Pop(); } type Top() const { return stack_.Top(); } void Swap(std::size_t i, std::size_t j) { history_.Push(HistorySwap{i, j}, HistorySwap::value); stack_.Swap(i, j); } void SetExtraHeader(header_extra_type const &b) { header_type h = stack_.header_extra(); history_.Push(HistoryHeader{h.header}, HistoryHeader::value); h.header = b; stack_.SetExtraHeader(h); } header_extra_type const &header_extra() const { return stack_.header_extra().header; } uint64_t Commit(DefaultKey const &key) { // The flush here is vitally important since we must ensure the all flush handlers successfully // execute. Failure to do this results in an incorrectly ordered difference / history stack // which in turn means that the state can not be reverted Flush(false); // Create a bookmark with our key, push it to the history stack HistoryBookmark history_bookmark{internal_bookmark_index_, key}; history_.Push(history_bookmark, HistoryBookmark::value); hash_history_.Push(history_bookmark); // Update our header with this information (the bookmark index) header_type h = stack_.header_extra(); h.bookmark = internal_bookmark_index_; stack_.SetExtraHeader(h); internal_bookmark_index_++; // Optionally flush since this is a checkpoint Flush(false); return internal_bookmark_index_ - 1; } bool HashExists(DefaultKey const &key) const { if (hash_history_.empty()) { FETCH_LOG_DEBUG(LOGGING_NAME, "Attempted to find if hash exists, but history is empty!"); return false; } uint64_t hash_history_size = hash_history_.size(); HistoryBookmark book; for (std::size_t i = 0; i < hash_history_size; ++i) { uint64_t reverse_index = hash_history_size - i - 1; hash_history_.Get(reverse_index, book); if (book.key == key) { return true; } } return false; } /** * Revert the main stack to the point at bookmark b by continually popping off changes from the * history, inspecting their type, and applying a revert with that change. Unsafe if the key * doesn't exist! * * @param: b The bookmark to revert to * */ void RevertToHash(DefaultKey const &key) { bool bookmark_found = false; while (!bookmark_found) { if (history_.empty()) { throw StorageException( "Attempt to revert to key failed, leaving stack in undefined state."); } // Find the type of the top of the history uint64_t t = history_.Type(); switch (t) { case HistoryBookmark::value: bookmark_found = RevertBookmark(key); break; case HistorySwap::value: RevertSwap(); break; case HistoryPop::value: RevertPop(); break; case HistoryPush::value: RevertPush(); break; case HistorySet::value: RevertSet(); break; case HistoryHeader::value: RevertHeader(); break; default: throw StorageException("Undefined type found when reverting in versioned history"); } } } void Flush(bool lazy = true) { // Note that the variant stack (history) does not need flushing stack_.Flush(lazy); history_.Flush(lazy); hash_history_.Flush(lazy); } std::size_t size() const { return stack_.size(); } std::size_t empty() const { return stack_.empty(); } bool is_open() const { return stack_.is_open(); } private: VariantStack history_; RandomAccessStack<HistoryBookmark> hash_history_; uint64_t internal_bookmark_index_{0}; event_handler_type on_file_loaded_; event_handler_type on_before_flush_; stack_type stack_; bool RevertBookmark(DefaultKey const &key_to_compare) { // Get bookmark from history HistoryBookmark book; history_.Top(book); internal_bookmark_index_ = book.bookmark; // Update header header_type h = stack_.header_extra(); h.bookmark = internal_bookmark_index_; stack_.SetExtraHeader(h); // If we are reverting to a state, we want this bookmark to stay - this // will make reverting to the same hash twice in a row valid. if (!(key_to_compare == book.key)) { history_.Pop(); // Sanity check, the hash history matches if (!(hash_history_.Top().key == book.key) || hash_history_.size() == 0) { FETCH_LOG_ERROR(LOGGING_NAME, "Hash history top does not match bookmark being removed!"); } hash_history_.Pop(); } return key_to_compare == book.key; } void RevertSwap() { HistorySwap swap; history_.Top(swap); stack_.Swap(swap.i, swap.j); history_.Pop(); } void RevertPop() { HistoryPop pop; history_.Top(pop); stack_.Push(pop.data); history_.Pop(); } void RevertPush() { HistoryPush push; history_.Top(push); stack_.Pop(); history_.Pop(); } void RevertSet() { HistorySet set; history_.Top(set); stack_.Set(set.i, set.data); history_.Pop(); } void RevertHeader() { HistoryHeader header; history_.Top(header); header_type h = stack_.header_extra(); h.header = header.data; stack_.SetExtraHeader(h); assert(this->header_extra() == h.header); history_.Pop(); } }; } // namespace storage } // namespace fetch
23.743464
100
0.607391
jinmannwong
51eb7bfaeb0ddf9336b9baae2b09ba4fdff19670
1,840
hpp
C++
source/mapManager/IconManager.hpp
mvxxx/MarsCombat
c4d10da7cf9bf8a71e00f64e5e364a358b477b15
[ "MIT" ]
1
2019-08-25T10:36:16.000Z
2019-08-25T10:36:16.000Z
source/mapManager/IconManager.hpp
mvxxx/MarsCombat
c4d10da7cf9bf8a71e00f64e5e364a358b477b15
[ "MIT" ]
null
null
null
source/mapManager/IconManager.hpp
mvxxx/MarsCombat
c4d10da7cf9bf8a71e00f64e5e364a358b477b15
[ "MIT" ]
null
null
null
/* mvxxx 2019 https://github.com/mvxxx */ #pragma once #include "../../external/SFML/include/SFML/System/Vector2.hpp" #include "../../external/SFML/include/SFML/System/Clock.hpp" #include "../entities/icon/Icon.hpp" #include "../Utilities.hpp" #include <map> #include <queue> #include <memory> class IconManager { /* ===Objects=== */ public: enum class bonus_t { ammo_machine_gun, ammo_rocket_launcher, ammo_laser, health_lite, health_medium, health_ultra }; protected: private: //possible positions of icons std::map<std::pair<int,int>,std::pair<bonus_t,std::shared_ptr<Icon>>> availablePositions; //used for spawns icons sf::Clock timer; //requests for spawn icons std::queue<sf::Vector2i> requests; mv::Cache<sf::Texture> iconTextures; /* ===Methods=== */ public: /** * @brief classic ctor * @param positions - available positions for icons' spawn (with given type) */ explicit IconManager(const std::vector<std::pair<bonus_t ,sf::Vector2i>>& positions); /** * @brief manages icons, spawns them, control timer */ void update(); /** * @brief looking for icon which is touched by entity * @param unitPos - unit position of considered entity * @return pointer to touched icon | if entity doesn't touch anything, then nullptr */ std::shared_ptr<Icon> getTouchedIcon(const sf::Vector2i& unitPos); /** * @brief creates vector of pointers to icon * @return vector of shared pointer to icon * @info used for renderer */ std::vector<std::shared_ptr<mv::Entity>> getIconsContainer(); /** * @brief getter for cache * @return cache of icon textures */ mv::Cache<sf::Texture>& getIconTextures(); protected: private: };
22.716049
93
0.638043
mvxxx
51ed57c484971273d03d5922c5500ecb9a8b7939
577
cpp
C++
2019/NyariDuitTerooz/H.cpp
comtran/ideafuse
c0b057aea23e0b2205cc4bfe0726c47802cf47b9
[ "MIT" ]
5
2018-05-06T07:51:08.000Z
2018-05-22T00:18:08.000Z
2019/NyariDuitTerooz/H.cpp
comtran/ideafuse
c0b057aea23e0b2205cc4bfe0726c47802cf47b9
[ "MIT" ]
1
2018-05-16T11:19:58.000Z
2018-05-16T11:19:58.000Z
2019/NyariDuitTerooz/H.cpp
comtran/ideafuse
c0b057aea23e0b2205cc4bfe0726c47802cf47b9
[ "MIT" ]
2
2018-05-06T11:32:26.000Z
2018-05-07T10:10:01.000Z
#include<bits/stdc++.h> using namespace std; #define ll long long struct point{ int x,y; }; ll sqr(int a){ return a*a; } ll countDist(point A, point B){ return ceil(hypot(A.x-B.x, A.y-B.y)); } int main (){ int t; cin>>t; for (int xx=1;xx<=t;xx++){ point pusat; int R; cin>>pusat.x>>pusat.y>>R; int n;cin>>n; vector<point> immo; for (int i=1;i<=n;i++){ point tmp; cin>>tmp.x>>tmp.y; immo.push_back(tmp); } long long ans=0; for (int i=0;i<n;i++){ ans+=max((ll)0, countDist(immo[i],pusat)-R); } cout<<"Case #"<<xx<<": "<<ans<<endl; } }
14.794872
47
0.563258
comtran
51f3156ac9044ea6a7f2cdd9159a6f4ff479b858
447
cpp
C++
Problems/0067. Add Binary.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
Problems/0067. Add Binary.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
Problems/0067. Add Binary.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
class Solution { public: string addBinary(string a, string b) { string ans{}; int i = a.length()-1, j = b.length()-1, carry{}; while(i>=0 or j>=0 or carry){ int sum = carry; if(i>=0) sum += a[i--] - '0'; if(j>=0) sum += b[j--] - '0'; ans += char(sum%2 + '0'); carry =sum /2; } reverse(begin(ans), end(ans)); return ans; } };
26.294118
56
0.409396
KrKush23
51f3b338064a90e7b7fd411f964d08ce72f4441e
15,148
cc
C++
deploy/lite/src/main.cc
Amanda-Barbara/PaddleDetection
65ac13074eaaa2447c644a2df71969d8a3dd1fae
[ "Apache-2.0" ]
1
2022-03-30T02:39:57.000Z
2022-03-30T02:39:57.000Z
deploy/lite/src/main.cc
Amanda-Barbara/PaddleDetection
65ac13074eaaa2447c644a2df71969d8a3dd1fae
[ "Apache-2.0" ]
null
null
null
deploy/lite/src/main.cc
Amanda-Barbara/PaddleDetection
65ac13074eaaa2447c644a2df71969d8a3dd1fae
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <math.h> #include <stdarg.h> #include <sys/stat.h> #include <sys/types.h> #include <algorithm> #include <iostream> #include <numeric> #include <string> #include <vector> #include "include/config_parser.h" #include "include/keypoint_detector.h" #include "include/object_detector.h" #include "include/preprocess_op.h" #include "json/json.h" Json::Value RT_Config; void PrintBenchmarkLog(std::vector<double> det_time, int img_num) { std::cout << "----------------------- Config info -----------------------" << std::endl; std::cout << "num_threads: " << RT_Config["cpu_threads"].as<int>() << std::endl; std::cout << "----------------------- Data info -----------------------" << std::endl; std::cout << "batch_size_det: " << RT_Config["batch_size_det"].as<int>() << std::endl; std::cout << "----------------------- Model info -----------------------" << std::endl; RT_Config["model_dir_det"].as<std::string>().erase( RT_Config["model_dir_det"].as<std::string>().find_last_not_of("/") + 1); std::cout << "detection model_name: " << RT_Config["model_dir_det"].as<std::string>() << std::endl; std::cout << "----------------------- Perf info ------------------------" << std::endl; std::cout << "Total number of predicted data: " << img_num << " and total time spent(ms): " << std::accumulate(det_time.begin(), det_time.end(), 0.) << std::endl; img_num = std::max(1, img_num); std::cout << "preproce_time(ms): " << det_time[0] / img_num << ", inference_time(ms): " << det_time[1] / img_num << ", postprocess_time(ms): " << det_time[2] / img_num << std::endl; } void PrintKptsBenchmarkLog(std::vector<double> det_time, int img_num) { std::cout << "----------------------- Data info -----------------------" << std::endl; std::cout << "batch_size_keypoint: " << RT_Config["batch_size_keypoint"].as<int>() << std::endl; std::cout << "----------------------- Model info -----------------------" << std::endl; RT_Config["model_dir_keypoint"].as<std::string>().erase( RT_Config["model_dir_keypoint"].as<std::string>().find_last_not_of("/") + 1); std::cout << "keypoint model_name: " << RT_Config["model_dir_keypoint"].as<std::string>() << std::endl; std::cout << "----------------------- Perf info ------------------------" << std::endl; std::cout << "Total number of predicted data: " << img_num << " and total time spent(ms): " << std::accumulate(det_time.begin(), det_time.end(), 0.) << std::endl; img_num = std::max(1, img_num); std::cout << "Average time cost per person:" << std::endl << "preproce_time(ms): " << det_time[0] / img_num << ", inference_time(ms): " << det_time[1] / img_num << ", postprocess_time(ms): " << det_time[2] / img_num << std::endl; } void PrintTotalIimeLog(double det_time, double keypoint_time, double crop_time) { std::cout << "----------------------- Time info ------------------------" << std::endl; std::cout << "Total Pipeline time(ms) per image: " << det_time + keypoint_time + crop_time << std::endl; std::cout << "Average det time(ms) per image: " << det_time << ", average keypoint time(ms) per image: " << keypoint_time << ", average crop time(ms) per image: " << crop_time << std::endl; } static std::string DirName(const std::string& filepath) { auto pos = filepath.rfind(OS_PATH_SEP); if (pos == std::string::npos) { return ""; } return filepath.substr(0, pos); } static bool PathExists(const std::string& path) { struct stat buffer; return (stat(path.c_str(), &buffer) == 0); } static void MkDir(const std::string& path) { if (PathExists(path)) return; int ret = 0; ret = mkdir(path.c_str(), 0755); if (ret != 0) { std::string path_error(path); path_error += " mkdir failed!"; throw std::runtime_error(path_error); } } static void MkDirs(const std::string& path) { if (path.empty()) return; if (PathExists(path)) return; MkDirs(DirName(path)); MkDir(path); } void PredictImage(const std::vector<std::string> all_img_paths, const int batch_size_det, const double threshold_det, const bool run_benchmark, PaddleDetection::ObjectDetector* det, PaddleDetection::KeyPointDetector* keypoint, const std::string& output_dir = "output") { std::vector<double> det_t = {0, 0, 0}; int steps = ceil(static_cast<float>(all_img_paths.size()) / batch_size_det); int kpts_imgs = 0; std::vector<double> keypoint_t = {0, 0, 0}; double midtimecost = 0; for (int idx = 0; idx < steps; idx++) { std::vector<cv::Mat> batch_imgs; int left_image_cnt = all_img_paths.size() - idx * batch_size_det; if (left_image_cnt > batch_size_det) { left_image_cnt = batch_size_det; } for (int bs = 0; bs < left_image_cnt; bs++) { std::string image_file_path = all_img_paths.at(idx * batch_size_det + bs); cv::Mat im = cv::imread(image_file_path, 1); batch_imgs.insert(batch_imgs.end(), im); } // Store all detected result std::vector<PaddleDetection::ObjectResult> result; std::vector<int> bbox_num; std::vector<double> det_times; // Store keypoint results std::vector<PaddleDetection::KeyPointResult> result_kpts; std::vector<cv::Mat> imgs_kpts; std::vector<std::vector<float>> center_bs; std::vector<std::vector<float>> scale_bs; std::vector<int> colormap_kpts = PaddleDetection::GenerateColorMap(20); bool is_rbox = false; if (run_benchmark) { det->Predict( batch_imgs, threshold_det, 50, 50, &result, &bbox_num, &det_times); } else { det->Predict( batch_imgs, threshold_det, 0, 1, &result, &bbox_num, &det_times); } // get labels and colormap auto labels = det->GetLabelList(); auto colormap = PaddleDetection::GenerateColorMap(labels.size()); int item_start_idx = 0; for (int i = 0; i < left_image_cnt; i++) { cv::Mat im = batch_imgs[i]; std::vector<PaddleDetection::ObjectResult> im_result; int detect_num = 0; for (int j = 0; j < bbox_num[i]; j++) { PaddleDetection::ObjectResult item = result[item_start_idx + j]; if (item.confidence < threshold_det || item.class_id == -1) { continue; } detect_num += 1; im_result.push_back(item); if (item.rect.size() > 6) { is_rbox = true; printf("class=%d confidence=%.4f rect=[%d %d %d %d %d %d %d %d]\n", item.class_id, item.confidence, item.rect[0], item.rect[1], item.rect[2], item.rect[3], item.rect[4], item.rect[5], item.rect[6], item.rect[7]); } else { printf("class=%d confidence=%.4f rect=[%d %d %d %d]\n", item.class_id, item.confidence, item.rect[0], item.rect[1], item.rect[2], item.rect[3]); } } std::cout << all_img_paths.at(idx * batch_size_det + i) << " The number of detected box: " << detect_num << std::endl; item_start_idx = item_start_idx + bbox_num[i]; std::vector<int> compression_params; compression_params.push_back(cv::IMWRITE_JPEG_QUALITY); compression_params.push_back(95); std::string output_path(output_dir); if (output_dir.rfind(OS_PATH_SEP) != output_dir.size() - 1) { output_path += OS_PATH_SEP; } std::string image_file_path = all_img_paths.at(idx * batch_size_det + i); if (keypoint) { int imsize = im_result.size(); for (int i = 0; i < imsize; i++) { auto keypoint_start_time = std::chrono::steady_clock::now(); auto item = im_result[i]; cv::Mat crop_img; std::vector<double> keypoint_times; std::vector<int> rect = { item.rect[0], item.rect[1], item.rect[2], item.rect[3]}; std::vector<float> center; std::vector<float> scale; if (item.class_id == 0) { PaddleDetection::CropImg(im, crop_img, rect, center, scale); center_bs.emplace_back(center); scale_bs.emplace_back(scale); imgs_kpts.emplace_back(crop_img); kpts_imgs += 1; } auto keypoint_crop_time = std::chrono::steady_clock::now(); std::chrono::duration<float> midtimediff = keypoint_crop_time - keypoint_start_time; midtimecost += static_cast<double>(midtimediff.count() * 1000); if (imgs_kpts.size() == RT_Config["batch_size_keypoint"].as<int>() || ((i == imsize - 1) && !imgs_kpts.empty())) { if (run_benchmark) { keypoint->Predict(imgs_kpts, center_bs, scale_bs, 10, 10, &result_kpts, &keypoint_times); } else { keypoint->Predict(imgs_kpts, center_bs, scale_bs, 0, 1, &result_kpts, &keypoint_times); } imgs_kpts.clear(); center_bs.clear(); scale_bs.clear(); keypoint_t[0] += keypoint_times[0]; keypoint_t[1] += keypoint_times[1]; keypoint_t[2] += keypoint_times[2]; } } std::string kpts_savepath = output_path + "keypoint_" + image_file_path.substr(image_file_path.find_last_of('/') + 1); cv::Mat kpts_vis_img = VisualizeKptsResult( im, result_kpts, colormap_kpts, keypoint->get_threshold()); cv::imwrite(kpts_savepath, kpts_vis_img, compression_params); printf("Visualized output saved as %s\n", kpts_savepath.c_str()); } else { // Visualization result cv::Mat vis_img = PaddleDetection::VisualizeResult( im, im_result, labels, colormap, is_rbox); std::string det_savepath = output_path + "result_" + image_file_path.substr(image_file_path.find_last_of('/') + 1); cv::imwrite(det_savepath, vis_img, compression_params); printf("Visualized output saved as %s\n", det_savepath.c_str()); } } det_t[0] += det_times[0]; det_t[1] += det_times[1]; det_t[2] += det_times[2]; } PrintBenchmarkLog(det_t, all_img_paths.size()); if (keypoint) { PrintKptsBenchmarkLog(keypoint_t, kpts_imgs); PrintTotalIimeLog( (det_t[0] + det_t[1] + det_t[2]) / all_img_paths.size(), (keypoint_t[0] + keypoint_t[1] + keypoint_t[2]) / all_img_paths.size(), midtimecost / all_img_paths.size()); } } int main(int argc, char** argv) { std::cout << "Usage: " << argv[0] << " [config_path] [image_dir](option)\n"; if (argc < 2) { std::cout << "Usage: ./main det_runtime_config.json" << std::endl; return -1; } std::string config_path = argv[1]; std::string img_path = ""; if (argc >= 3) { img_path = argv[2]; } // Parsing command-line PaddleDetection::load_jsonf(config_path, RT_Config); if (RT_Config["model_dir_det"].as<std::string>().empty()) { std::cout << "Please set [model_det_dir] in " << config_path << std::endl; return -1; } if (RT_Config["image_file"].as<std::string>().empty() && RT_Config["image_dir"].as<std::string>().empty() && img_path.empty()) { std::cout << "Please set [image_file] or [image_dir] in " << config_path << " Or use command: <" << argv[0] << " [image_dir]>" << std::endl; return -1; } if (!img_path.empty()) { std::cout << "Use image_dir in command line overide the path in config file" << std::endl; RT_Config["image_dir"] = img_path; RT_Config["image_file"] = ""; } // Load model and create a object detector PaddleDetection::ObjectDetector det( RT_Config["model_dir_det"].as<std::string>(), RT_Config["cpu_threads"].as<int>(), RT_Config["batch_size_det"].as<int>()); PaddleDetection::KeyPointDetector* keypoint = nullptr; if (!RT_Config["model_dir_keypoint"].as<std::string>().empty()) { keypoint = new PaddleDetection::KeyPointDetector( RT_Config["model_dir_keypoint"].as<std::string>(), RT_Config["cpu_threads"].as<int>(), RT_Config["batch_size_keypoint"].as<int>(), RT_Config["use_dark_decode"].as<bool>()); RT_Config["batch_size_det"] = 1; printf( "batchsize of detection forced to be 1 while keypoint model is not " "empty()"); } // Do inference on input image if (!RT_Config["image_file"].as<std::string>().empty() || !RT_Config["image_dir"].as<std::string>().empty()) { if (!PathExists(RT_Config["output_dir"].as<std::string>())) { MkDirs(RT_Config["output_dir"].as<std::string>()); } std::vector<std::string> all_img_paths; std::vector<cv::String> cv_all_img_paths; if (!RT_Config["image_file"].as<std::string>().empty()) { all_img_paths.push_back(RT_Config["image_file"].as<std::string>()); if (RT_Config["batch_size_det"].as<int>() > 1) { std::cout << "batch_size_det should be 1, when set `image_file`." << std::endl; return -1; } } else { cv::glob(RT_Config["image_dir"].as<std::string>(), cv_all_img_paths); for (const auto& img_path : cv_all_img_paths) { all_img_paths.push_back(img_path); } } PredictImage(all_img_paths, RT_Config["batch_size_det"].as<int>(), RT_Config["threshold_det"].as<float>(), RT_Config["run_benchmark"].as<bool>(), &det, keypoint, RT_Config["output_dir"].as<std::string>()); } delete keypoint; keypoint = nullptr; return 0; }
38.940874
80
0.561526
Amanda-Barbara
51f4cc0526fbcb205b07a4b94fc3b6456e5d265b
677
cpp
C++
SW/src/encoder_implementation/encoder_implementation.cpp
chris3069/BLDC_Project
69f6b7ed810d091dd430d93554056e34af130d2d
[ "BSL-1.0" ]
null
null
null
SW/src/encoder_implementation/encoder_implementation.cpp
chris3069/BLDC_Project
69f6b7ed810d091dd430d93554056e34af130d2d
[ "BSL-1.0" ]
null
null
null
SW/src/encoder_implementation/encoder_implementation.cpp
chris3069/BLDC_Project
69f6b7ed810d091dd430d93554056e34af130d2d
[ "BSL-1.0" ]
null
null
null
#include "encoder_implementation.hpp" #include "Encoder.h" Encoder Speed_encoder(12, 13); #define SPEED_DECREASE 0.1 float getTargetSpeed(void) { static int32_t old_target_speed = INT32_MIN; static int32_t new_target_speed = INT32_MAX; new_target_speed = Speed_encoder.read(); if (new_target_speed != old_target_speed) { old_target_speed = new_target_speed; Serial.println(new_target_speed); } return (float)new_target_speed*SPEED_DECREASE; } void reset_target_speed (void) { digitalWrite(INH, false); const int32_t target_speed = 0; Speed_encoder.write(target_speed); Serial.println("Reset Button Ṕressed -> Reset Motor Control"); }
20.515152
64
0.753323
chris3069
51f58251753c81f2410de48c0ccda831b6db8174
3,431
cpp
C++
data/appGPU/vec_add.cpp
leios/thesis
0fdbfdc9b42a967a9b3492be4ab788bdf76d4ce5
[ "MIT" ]
9
2019-02-12T02:41:25.000Z
2021-03-03T09:46:28.000Z
data/appGPU/vec_add.cpp
leios/thesis
0fdbfdc9b42a967a9b3492be4ab788bdf76d4ce5
[ "MIT" ]
1
2019-02-07T08:22:21.000Z
2019-02-07T08:22:21.000Z
data/appGPU/vec_add.cpp
leios/thesis
0fdbfdc9b42a967a9b3492be4ab788bdf76d4ce5
[ "MIT" ]
1
2019-02-07T08:07:50.000Z
2019-02-07T08:07:50.000Z
#define __CL_ENABLE_EXCEPTIONS #include <CL/cl.hpp> #include <iostream> #include <vector> #include <math.h> // OpenCL kernel const char *kernelSource = "\n" \ "#pragma OPENCL EXTENSION cl_khr_fp64 : enable \n" \ "__kernel void vecAdd( __global double *a, \n" \ " __global double *b, \n" \ " __global double *c, \n" \ " const unsigned int n){ \n" \ " \n" \ " // Global Tread ID \n" \ " int id = get_global_id(0); \n" \ " \n" \ " // Remain in boundaries \n" \ " if (id < n){ \n" \ " c[id] = a[id] + b[id]; \n" \ " } \n" \ "} \n"; int main(){ unsigned int n = 1024; double *h_a, *h_b, *h_c; h_a = new double[n]; h_b = new double[n]; h_c = new double[n]; for (size_t i = 0; i < n; ++i){ h_a[i] = 1; h_b[i] = 1; } cl::Buffer d_a, d_b, d_c; cl_int err = CL_SUCCESS; try{ std::vector<cl::Platform> platforms; cl::Platform::get(&platforms); if(platforms.size() == 0){ std::cout << "Platforms size is 0\n"; return -1; } cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[0])(), 0 }; cl::Context context(CL_DEVICE_TYPE_GPU, properties); std::vector<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>(); cl::CommandQueue queue(context, devices[0], 0, &err); d_a = cl::Buffer(context, CL_MEM_READ_ONLY, n*sizeof(double)); d_b = cl::Buffer(context, CL_MEM_READ_ONLY, n*sizeof(double)); d_c = cl::Buffer(context, CL_MEM_WRITE_ONLY, n*sizeof(double)); queue.enqueueWriteBuffer(d_a, CL_TRUE, 0, n*sizeof(double), h_a); queue.enqueueWriteBuffer(d_b, CL_TRUE, 0, n*sizeof(double), h_b); cl::Program::Sources source(1, std::make_pair(kernelSource,strlen(kernelSource))); cl::Program program_ = cl::Program(context, source); program_.build(devices); cl::Kernel kernel(program_, "vecAdd", &err); kernel.setArg(0, d_a); kernel.setArg(1, d_b); kernel.setArg(2, d_c); kernel.setArg(3, n); cl::NDRange localSize(64); cl::NDRange globalSize((int)(ceil(n/(float)64)*64)); cl::Event event; queue.enqueueNDRangeKernel( kernel, cl::NullRange, globalSize, localSize, NULL, &event ); event.wait(); queue.enqueueReadBuffer(d_c, CL_TRUE, 0, n*sizeof(double), h_c); } catch(cl::Error err){ std::cerr << "ERROR: " << err.what() << "(" << err.err() << ")\n"; } // Check to make sure everything works for (size_t i = 0; i < n; ++i){ if (h_c[i] != h_a[i] + h_b[i]){ std::cout << "Yo. You failed. What a loser! Ha\n"; exit(1); } } std::cout << "You passed the test, congratulations!\n"; delete(h_a); delete(h_b); delete(h_c); }
30.633929
80
0.473623
leios
51f74b000cd428bd613964fd6bb8d0ef38e21e3b
5,227
cpp
C++
firmware/src/Tool.cpp
galacticstudios/Logic-Meter
17009d23a09ba12975af055a031fe84b317a8cc7
[ "MIT" ]
41
2021-01-23T00:40:56.000Z
2022-01-14T12:34:33.000Z
firmware/src/Tool.cpp
galacticstudios/Logic-Meter
17009d23a09ba12975af055a031fe84b317a8cc7
[ "MIT" ]
3
2021-01-28T17:07:40.000Z
2021-07-01T11:41:19.000Z
firmware/src/Tool.cpp
galacticstudios/Logic-Meter
17009d23a09ba12975af055a031fe84b317a8cc7
[ "MIT" ]
3
2021-01-28T17:16:45.000Z
2021-01-29T01:59:49.000Z
/* * File: Tool.cpp * Author: Bob * * Created on April 24, 2020, 11:26 AM */ #include <string> #include "Tool.h" #include "Display.h" #include "Menu.h" #include "Utility.h" #include "Pane.h" static const MenuItem helpMenuItems[5] = { MenuItem(), MenuItem(), MenuItem(), MenuItem(), MenuItem("Done", MenuType::ParentMenu, NULL, CB(&Tool::ExitHelp))}; const Menu helpMenu(helpMenuItems); Tool::Tool(const char *title, Pane *pane, const Menu &menu, const Help &help) : _title(title), _pane(pane), _menu(menu), _requestDeactivate(false), _menuStackPointer(0), _help(help), _inHelp(false) { _requestDeactivate = false; display.SetTitle(_title); SetStatusText(""); display.SetMenu(_menu); display.SetPane(*_pane); _menuStackPointer = 0; _menuStack[0] = &_menu; } Tool::~Tool() { if (_inHelp) ExitHelp(); display.ClearPane(); delete _pane; PrimaryD0_InputEnable(); PrimaryD11_InputEnable(); PrimaryF4_InputEnable(); Aux1D1_InputEnable(); Aux1D9_InputEnable(); Aux1D10_InputEnable(); Aux1F5_InputEnable(); Aux2D4_InputEnable(); Aux2D5_InputEnable(); Aux2F0_InputEnable(); Aux2F1_InputEnable(); } void Tool::SetStatusText(const char *text) { display.SetStatus(text); } // Button index = 1..5 void Tool::OnButtonPressed(int buttonIndex) { const Menu *currentMenu = _menuStack[_menuStackPointer]; // If the Help button was pressed if (buttonIndex >= countof(currentMenu->MenuItems())) { if (_inHelp) { // Simulate pressing the "Done" button buttonIndex = 4; } // Else (help screen is not currently displayed) else { _menuStack[++_menuStackPointer] = &helpMenu; display.SetMenu(*_menuStack[_menuStackPointer]); EnterHelp(); return; } } const MenuItem &selectedItem = currentMenu->MenuItems()[buttonIndex]; switch (selectedItem.NextMenuType()) { case NoChange : break; case ChildMenu : _menuStack[++_menuStackPointer] = selectedItem.NextMenu(); break; case SiblingMenu : _menuStack[_menuStackPointer] = selectedItem.NextMenu(); break; case ParentMenu : ASSERT(_menuStackPointer != 0); --_menuStackPointer; break; } if (_menuStack[_menuStackPointer] != currentMenu) display.SetMenu(*_menuStack[_menuStackPointer]); selectedItem.Execute(this); } void Tool::PopMenu() { ASSERT(_menuStackPointer != 0); --_menuStackPointer; display.SetMenu(*_menuStack[_menuStackPointer]); } void Tool::EnterHelp() { static laString *newline; static uint32_t lineWidth; if (newline == NULL) { newline = laString_New(NULL); *newline = laString_CreateFromCharBuffer("\n", &RegularFont); lineWidth = laWidget_GetWidth((laWidget *) HelpTextWidget); laMargin margin; laWidget_GetMargin((laWidget *) HelpTextWidget, &margin); lineWidth -= margin.left + margin.right; } GetPane()->SetVisible(false); _inHelp = true; // Assemble the help text std::string text; if (_help.Primary()) { text = text + std::string("P: ") + _help.Primary() + "\n"; } else text = text + "P: Unused\n"; if (_help.Aux1()) { text = text + "A: " + _help.Aux1() + "\n"; } else text = text + "A: Unused\n"; if (_help.Aux2()) { text = text + "B: " + _help.Aux2() + "\n"; } else text = text + "B: Unused\n"; text = text + "\n" + _help.Text(); // Wrap the text. laString s = laString_CreateFromUTF8Buffer(text.c_str(), &RegularFont); uint32_t len = laString_Length(&s); uint32_t lastWordStartIndex = 0, lastWordStartX = 0; uint32_t x = 0; // Go through all the characters in the string for (uint32_t charIndex = 0; charIndex < len; ++charIndex) { GFXU_CHAR ch = laString_CharAt(&s, charIndex); uint32_t charWidth = laString_GetCharWidth(&s, charIndex); if (ch == '\n') { lastWordStartIndex = charIndex + 1; lastWordStartX = 0; x = 0; } else if (ch == ' ') { lastWordStartIndex = charIndex + 1; x += charWidth; lastWordStartX = x; } else if (x + charWidth >= lineWidth) { // Replace the last word break with a newline laString_Remove(&s, lastWordStartIndex - 1, 1); laString_Insert(&s, newline, lastWordStartIndex - 1); x = x - lastWordStartX + charWidth; lastWordStartX = 0; } else x += charWidth; } laLabelWidget_SetText(HelpTextWidget, s); laString_Destroy(&s); laWidget_SetVisible(HelpPanel, LA_TRUE); } void Tool::ExitHelp() { laWidget_SetVisible(HelpPanel, LA_FALSE); GetPane()->SetVisible(true); _inHelp = false; }
24.890476
79
0.577004
galacticstudios
51fd0f7ed401e2716bc0176983cf6e8639df6233
773
cpp
C++
src/strategy/triggers/ChatCommandTrigger.cpp
htc16/mod-playerbots
2307e3f980035a244bfb4fedefda5bc55903d470
[ "MIT" ]
12
2022-03-23T05:14:53.000Z
2022-03-30T12:12:58.000Z
src/strategy/triggers/ChatCommandTrigger.cpp
htc16/mod-playerbots
2307e3f980035a244bfb4fedefda5bc55903d470
[ "MIT" ]
24
2022-03-23T13:56:37.000Z
2022-03-31T18:23:32.000Z
src/strategy/triggers/ChatCommandTrigger.cpp
htc16/mod-playerbots
2307e3f980035a244bfb4fedefda5bc55903d470
[ "MIT" ]
3
2022-03-24T21:47:10.000Z
2022-03-31T06:21:46.000Z
/* * Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license, you may redistribute it and/or modify it under version 2 of the License, or (at your option), any later version. */ #include "ChatCommandTrigger.h" #include "Playerbots.h" ChatCommandTrigger::ChatCommandTrigger(PlayerbotAI* botAI, std::string const command) : Trigger(botAI, command), triggered(false), owner(nullptr) { } void ChatCommandTrigger::ExternalEvent(std::string const paramName, Player* eventPlayer) { param = paramName; owner = eventPlayer; triggered = true; } Event ChatCommandTrigger::Check() { if (!triggered) return Event(); return Event(getName(), param, owner); } void ChatCommandTrigger::Reset() { triggered = false; }
24.935484
205
0.719276
htc16
a404aac37dea850bc05b125aa2f4f6286d35f679
4,991
hpp
C++
include/r3d/vec.hpp
AlexandruIca/R3D
d0088f7fcc8756f529e07ca99e26f880e9210f40
[ "Unlicense" ]
null
null
null
include/r3d/vec.hpp
AlexandruIca/R3D
d0088f7fcc8756f529e07ca99e26f880e9210f40
[ "Unlicense" ]
null
null
null
include/r3d/vec.hpp
AlexandruIca/R3D
d0088f7fcc8756f529e07ca99e26f880e9210f40
[ "Unlicense" ]
null
null
null
#ifndef R3D_VEC_HPP #define R3D_VEC_HPP #pragma once #include <algorithm> #include <array> #include <cmath> #include <cstddef> #include <functional> #include <iostream> #include <numeric> #include <type_traits> #include "r3d/impl/assert.hpp" #include "r3d/matrix.hpp" namespace r3d { namespace impl { template<typename T, std::size_t N> struct vec { static_assert(std::is_arithmetic_v<T>, "`r3d::vec` can only accept arithmetic types"); static_assert(N >= 1, "`r3d::vec` needs to have size at least 1"); private: std::array<T, N> m_data; public: vec(vec const&) noexcept = default; vec(vec&&) noexcept = default; ~vec() noexcept = default; explicit vec(std::array<T, N> const& init) : m_data{ init } { } explicit vec(T const& val) { m_data.fill(val); } vec() : vec(0) { } auto operator=(vec const&) noexcept -> vec& = default; auto operator=(vec&&) noexcept -> vec& = default; [[nodiscard]] constexpr auto size() const noexcept -> std::size_t { return N; } [[nodiscard]] auto operator==(vec const& other) const noexcept -> bool { return m_data == other.m_data; } [[nodiscard]] auto operator!=(vec const& other) const noexcept -> bool { return !(m_data == other.m_data); } [[nodiscard]] auto operator+(vec const& other) const noexcept -> vec { vec tmp{ 0 }; std::transform(m_data.begin(), m_data.end(), other.m_data.begin(), tmp.m_data.begin(), std::plus<>{}); return tmp; } [[nodiscard]] auto operator-(vec const& other) const noexcept -> vec { vec tmp{ 0 }; std::transform(m_data.begin(), m_data.end(), other.m_data.begin(), tmp.m_data.begin(), std::minus<>{}); return tmp; } [[nodiscard]] auto operator+(T const val) const noexcept -> vec { vec result{ *this }; for(T& t : result.m_data) { t += val; } return result; } [[nodiscard]] auto operator-(T const val) const noexcept -> vec { vec result{ *this }; for(T& t : result.m_data) { t -= val; } return result; } [[nodiscard]] auto operator*(T const val) const noexcept -> vec { vec result{ *this }; for(T& t : result.m_data) { t *= val; } return result; } [[nodiscard]] auto operator/(T const val) const noexcept -> vec { vec result{ *this }; for(T& t : result.m_data) { t /= val; } return result; } [[nodiscard]] auto operator[](int const index) noexcept -> T& { ASSERT(index >= 0); ASSERT(static_cast<std::size_t>(index) < N); return m_data[static_cast<std::size_t>(index)]; } [[nodiscard]] auto operator[](int const index) const noexcept -> T const& { ASSERT(index >= 0); ASSERT(static_cast<std::size_t>(index) < N); return m_data[static_cast<std::size_t>(index)]; } [[nodiscard]] auto operator[](std::size_t const index) noexcept -> T& { ASSERT(index < N); return m_data[index]; } [[nodiscard]] auto operator[](std::size_t const index) const noexcept -> T const& { ASSERT(index < N); return m_data[index]; } [[nodiscard]] auto length() const noexcept -> float { return std::sqrt(std::accumulate( m_data.begin(), m_data.end(), T{ 0 }, [](T const sum, T const val) -> T { return sum + val * val; })); } auto normalize() noexcept -> void { float const len = this->length(); for(T& num : m_data) { num /= len; } } }; } // namespace impl using vec2i = impl::vec<int, 2>; using vec3f = impl::vec<float, 3>; using vec4f = impl::vec<float, 4>; using triangle = std::array<vec3f, 3>; template<typename T, std::size_t N> [[nodiscard]] auto cross(impl::vec<T, N> const& v1, impl::vec<T, N> const& v2) -> impl::vec<T, N> { impl::vec<T, N> result{ 0 }; constexpr int x = 0; constexpr int y = 1; constexpr int z = 2; result[x] = v1[y] * v2[z] - v1[z] * v2[y]; result[y] = v1[z] * v2[x] - v1[x] * v2[z]; result[z] = v1[x] * v2[y] - v1[y] * v2[x]; return result; } template<typename T, std::size_t N> [[nodiscard]] auto dot(impl::vec<T, N> const& v1, impl::vec<T, N> const& v2) -> T { T result{ 0 }; for(std::size_t i = 0; i < N; ++i) { result += v1[i] * v2[i]; } return result; } namespace operators { [[nodiscard]] auto operator*(vec3f const& v, mat4f const& m) -> vec3f; template<typename T, std::size_t N> auto operator<<(std::ostream& os, impl::vec<T, N> const& v) -> std::ostream& { os << '('; os << v[0]; for(std::size_t i = 1; i < N; ++i) { os << ", " << v[i]; } os << ')'; return os; } } // namespace operators } // namespace r3d #endif // !R3D_VEC_HPP
22.894495
114
0.549389
AlexandruIca
a4088ed8e162da1f4e883f5419e30707e1cb4ef5
2,950
cpp
C++
src/unix/unix_address.cpp
PeterStoytchev/sockpp
c4507c2c49176c08a489750082a4bfed9ddff878
[ "BSD-3-Clause" ]
447
2018-02-22T21:38:51.000Z
2022-03-25T02:35:20.000Z
src/unix/unix_address.cpp
PeterStoytchev/sockpp
c4507c2c49176c08a489750082a4bfed9ddff878
[ "BSD-3-Clause" ]
60
2017-05-03T20:22:55.000Z
2022-02-19T23:56:57.000Z
src/unix/unix_address.cpp
PeterStoytchev/sockpp
c4507c2c49176c08a489750082a4bfed9ddff878
[ "BSD-3-Clause" ]
95
2018-10-04T10:17:20.000Z
2022-03-22T08:04:40.000Z
// unix_address.cpp // // -------------------------------------------------------------------------- // This file is part of the "sockpp" C++ socket library. // // Copyright (c) 2014-2017 Frank Pagliughi // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -------------------------------------------------------------------------- #include "sockpp/unix_address.h" #include <cstring> #include <stdexcept> using namespace std; namespace sockpp { ///////////////////////////////////////////////////////////////////////////// constexpr sa_family_t unix_address::ADDRESS_FAMILY; constexpr size_t unix_address::MAX_PATH_NAME; // -------------------------------------------------------------------------- unix_address::unix_address(const string& path) { addr_.sun_family = ADDRESS_FAMILY; ::strncpy(addr_.sun_path, path.c_str(), MAX_PATH_NAME); } unix_address::unix_address(const sockaddr& addr) { auto domain = addr.sa_family; if (domain != AF_UNIX) throw std::invalid_argument("Not a UNIX-domain address"); // TODO: We should check the path, or at least see that it has // proper NUL termination. std::memcpy(&addr_, &addr, sizeof(sockaddr)); } // -------------------------------------------------------------------------- ostream& operator<<(ostream& os, const unix_address& addr) { os << "unix:" << addr.path(); return os; } ///////////////////////////////////////////////////////////////////////////// // End namespace sockpp }
36.875
77
0.631525
PeterStoytchev
a408a7da5c26ff6276fc84264245d030b9fb760b
5,195
hpp
C++
test/unit/memory/compress_store/compress_store_test.hpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
340
2020-09-16T21:12:48.000Z
2022-03-28T15:40:33.000Z
test/unit/memory/compress_store/compress_store_test.hpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
383
2020-09-17T06:56:35.000Z
2022-03-13T15:58:53.000Z
test/unit/memory/compress_store/compress_store_test.hpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
28
2021-02-27T23:11:23.000Z
2022-03-25T12:31:29.000Z
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #include "test.hpp" #include <eve/function/compress_store.hpp> #include <algorithm> #include <array> #include <random> template <typename T, typename L, typename C> void ignore_test(T x, L m, C c) { using e_t = eve::element_type_t<T>; using arr = std::array<e_t, T::size()>; // gcc bug workaround arr x_arr; eve::store(x, x_arr.data()); arr expected; expected.fill(e_t{0}); std::int8_t f_i = c.offset(eve::as(x)); std::int8_t l_i = f_i + c.count(eve::as(x)); std::int8_t o = f_i; for (std::int8_t i = f_i; i != l_i; ++i) { if (!m.get(i)) continue; expected[o++] = x_arr[i]; } alignas(sizeof(arr)) arr actual; actual.fill(e_t{0}); e_t* out = eve::unsafe(eve::compress_store[c])(x, m, actual.begin()); TTS_EQUAL((out - actual.begin()), o); TTS_EQUAL(T(expected.begin()), T(actual.begin())); using ap_t = eve::aligned_ptr<e_t, eve::cardinal_t<T>>; actual.fill(e_t{0}); out = eve::unsafe(eve::compress_store[c])(x, m, ap_t{actual.begin()}); TTS_EQUAL((out - actual.begin()), o); TTS_EQUAL(T(expected.begin()), T(actual.begin())); } template <typename T, typename L> void all_ignore_tests(T x, L m) { if (x.size() < 16) { for (std::int8_t i = 0; i != x.size() + 1; ++i) { for (std::int8_t j = 0; j <= x.size() - i; ++j) { ignore_test(x, m, eve::ignore_extrema{i, j}); } } } else { for (std::int8_t i = 0; i != x.size() + 1; ++i) { ignore_test(x, m, eve::ignore_first(i)); ignore_test(x, m, eve::ignore_last(i)); } } } template < typename L, typename T> void precise_tests(T x) { using e_t = eve::element_type_t<T>; // ignore all { e_t data; eve::unsafe(eve::compress_store[eve::ignore_all])(x, L{}, &data + 1); eve::safe(eve::compress_store[eve::ignore_all])(x, L{}, &data + 1); } // writing exactly, e_t data[2] = { e_t{0}, e_t{5}} ; L mask{false}; mask.set(T::size() - 1, true); eve::safe(eve::compress_store)(x, mask, &data[0]); TTS_EQUAL(data[0], x.back()); TTS_EQUAL(data[1], e_t{5}); // unsafe with ignore still acts as safe data[0] = e_t{0}; eve::unsafe(eve::compress_store[eve::ignore_first(0)])(x, mask, &data[0]); TTS_EQUAL(data[0], x.back()); TTS_EQUAL(data[1], e_t{5}); } template <bool all_options, typename T, typename L> void one_test(T x, L m) { using e_t = eve::element_type_t<T>; using arr = std::array<e_t, T::size()>; arr expected; expected.fill(e_t{0}); std::int8_t o = 0; for (std::int8_t i = 0; i != T::size(); ++i) { if (!m.get(i)) continue; expected[o++] = x.get(i); } alignas(sizeof(arr)) arr actual; actual.fill(e_t{0}); e_t* out = eve::unsafe(eve::compress_store)(x, m, actual.begin()); TTS_EQUAL((out - actual.begin()), o); // No guarantees past the out std::copy(&expected[o], expected.end(), &actual[o]); TTS_EQUAL(T(expected.begin()), T(actual.begin())); // Same check for aligned if constexpr (all_options) { using ap_t = eve::aligned_ptr<e_t, eve::cardinal_t<T>>; actual.fill(e_t{0}); out = eve::unsafe(eve::compress_store)(x, m, ap_t{actual.begin()}); TTS_EQUAL((out - actual.begin()), o); std::copy(&expected[o], expected.end(), &actual[o]); TTS_EQUAL(T(expected.begin()), T(actual.begin())); } if constexpr (all_options) { all_ignore_tests(x, m); } } template <typename L, typename T> void go_through_everything(T x) { L m(false); auto test = [&](auto& self, std::size_t i) mutable { if (i == T::size()) { one_test<false>(x, m); return; }; self(self, i + 1); m.set(i, true); self(self, i + 1); }; test(test, 0); } template<typename L, typename T> void smaller_test_v(T x) { if constexpr ( eve::current_api == eve::avx512 && (eve::has_aggregated_abi_v<T> || eve::has_aggregated_abi_v<L>)) { TTS_PASS("aggregated on avx512"); return; } else { // even elements { L m {false}; for( std::ptrdiff_t i = 0; i < T::size(); i += 2 ) { m.set(i, true); one_test<true>(x, m); } } // all/none { one_test<true>(x, L {true}); one_test<true>(x, L {false}); } // bunch of randoms { constexpr auto seed = sizeof(eve::element_type_t<L>) + sizeof(eve::element_type_t<T>) + T::size(); std::mt19937 g(seed); std::uniform_int_distribution<short> d(0, 1); auto random_l = [&]() mutable { L m {false}; for( int i = 0; i != L::size(); ++i ) { m.set(i, d(g) == 1); } return m; }; for( int i = 0; i < 100; ++i ) { one_test<false>(x, random_l()); } } // precise precise_tests<L>(x); } } template <typename L, typename T> void all_tests_for_v(T x) { if constexpr (T::size() <= 8) { go_through_everything<L>(x); } smaller_test_v<L>(x); }
23.830275
115
0.553224
the-moisrex
a40b0b55b871bd1a19d2c6d06b91debcf207a5da
1,735
cpp
C++
src/framework/core/consoleapplication.cpp
Sposito/otclient
d3e12b5d44a3f801b0b24fcf25dfd811929e6ba4
[ "MIT" ]
518
2015-01-10T18:09:26.000Z
2022-03-27T11:41:33.000Z
src/framework/core/consoleapplication.cpp
Sposito/otclient
d3e12b5d44a3f801b0b24fcf25dfd811929e6ba4
[ "MIT" ]
504
2015-01-01T17:34:59.000Z
2022-03-25T18:27:37.000Z
src/framework/core/consoleapplication.cpp
Sposito/otclient
d3e12b5d44a3f801b0b24fcf25dfd811929e6ba4
[ "MIT" ]
545
2015-01-08T09:37:10.000Z
2022-03-05T00:57:50.000Z
/* * Copyright (c) 2010-2013 OTClient <https://github.com/edubart/otclient> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "consoleapplication.h" #include <framework/core/clock.h> #include <framework/luaengine/luainterface.h> #ifdef FW_NET #include <framework/net/connection.h> #endif ConsoleApplication g_app; void ConsoleApplication::run() { m_running = true; // run the first poll poll(); // first clock update g_clock.update(); g_lua.callGlobalField("g_app", "onRun"); while(!m_stopping) { poll(); stdext::millisleep(1); g_clock.update(); m_frameCounter.update(); } m_stopping = false; m_running = false; }
30.982143
80
0.722767
Sposito
a40ea043937a71c3496977854ea34d34215ec0c0
85
cpp
C++
src/GUI/Crxtterm.cpp
ArashMassoudieh/GIFMod_
1fa9eda21fab870fc3baf56462f79eb800d5154f
[ "MIT" ]
5
2017-11-20T19:32:27.000Z
2018-08-28T06:08:45.000Z
src/GUI/Crxtterm.cpp
ArashMassoudieh/GIFMod_
1fa9eda21fab870fc3baf56462f79eb800d5154f
[ "MIT" ]
1
2017-07-04T05:40:30.000Z
2017-07-04T05:43:37.000Z
src/GUI/Crxtterm.cpp
ArashMassoudieh/GIFMod_
1fa9eda21fab870fc3baf56462f79eb800d5154f
[ "MIT" ]
2
2017-11-09T22:00:45.000Z
2018-08-30T10:56:08.000Z
#include "Crxtterm.h" Crxtterm::Crxtterm(void) { } Crxtterm::~Crxtterm(void) { }
7.083333
25
0.658824
ArashMassoudieh
a411e3309af0d56a0b9aa08a3bf7a3c6130b7ba1
3,207
cpp
C++
demo/opengl/ex/fog/fog_opengl.cpp
fox000002/ulib-win
628c4a0b8193d1ad771aa85598776ff42a45f913
[ "Apache-2.0" ]
4
2016-09-07T07:02:52.000Z
2019-06-22T08:55:53.000Z
demo/opengl/ex/fog/fog_opengl.cpp
fox000002/ulib-win
628c4a0b8193d1ad771aa85598776ff42a45f913
[ "Apache-2.0" ]
null
null
null
demo/opengl/ex/fog/fog_opengl.cpp
fox000002/ulib-win
628c4a0b8193d1ad771aa85598776ff42a45f913
[ "Apache-2.0" ]
3
2019-06-22T16:00:39.000Z
2022-03-09T13:46:27.000Z
#include "resource.h" #include <windows.h> #include <tchar.h> #include <cstdio> #include <cstring> #include <cstdlib> #include <GL/gl.h> #include <GL/glu.h> #include "ugldialog.h" #include "udlgapp.h" #include "uglut.h" GLint fogMode; void renderSphere (GLfloat x, GLfloat y, GLfloat z) { glPushMatrix(); glTranslatef (x, y, z); //glutSolidSphere(0.4, 16, 16); //Quadrics are part of glu library that make parameterized shapes GLUquadricObj *qobj; qobj = gluNewQuadric(); gluQuadricDrawStyle(qobj, GLU_FILL); // rotate the wire sphere so it's vertically // oriented //::glRotatef( 90.0f, 1.0f, 0.0f, 0.0f ); glColor3f( 1.0f, 0.0f, 0.0f ); gluSphere( qobj, 0.5, 20, 10); glPopMatrix(); } // using huys::UGLDialog; class MyGLDialog : public UGLDialog { public: MyGLDialog(HINSTANCE hInst, UINT nID) : UGLDialog(hInst, nID) {} BOOL initGL() { RECT rc; ::GetClientRect(m_hDlg, &rc); int w = rc.right-rc.left; int h = rc.bottom-rc.top; glViewport(0, 0, (GLsizei) w, (GLsizei) h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (w <= h) glOrtho (-2.5, 2.5, -2.5*(GLfloat)h/(GLfloat)w, 2.5*(GLfloat)h/(GLfloat)w, -10.0, 10.0); else glOrtho (-2.5*(GLfloat)w/(GLfloat)h, 2.5*(GLfloat)w/(GLfloat)h, -2.5, 2.5, -10.0, 10.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity (); GLfloat position[] = { 0.5, 0.5, 3.0, 0.0 }; glEnable(GL_DEPTH_TEST); glLightfv(GL_LIGHT0, GL_POSITION, position); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); { GLfloat mat[3] = {0.1745, 0.01175, 0.01175}; glMaterialfv (GL_FRONT, GL_AMBIENT, mat); mat[0] = 0.61424; mat[1] = 0.04136; mat[2] = 0.04136; glMaterialfv (GL_FRONT, GL_DIFFUSE, mat); mat[0] = 0.727811; mat[1] = 0.626959; mat[2] = 0.626959; glMaterialfv (GL_FRONT, GL_SPECULAR, mat); glMaterialf (GL_FRONT, GL_SHININESS, 0.6*128.0); } glEnable(GL_FOG); { GLfloat fogColor[4] = {0.5, 0.5, 0.5, 1.0}; fogMode = GL_EXP; glFogi (GL_FOG_MODE, fogMode); glFogfv (GL_FOG_COLOR, fogColor); glFogf (GL_FOG_DENSITY, 0.35); glHint (GL_FOG_HINT, GL_DONT_CARE); glFogf (GL_FOG_START, 1.0); glFogf (GL_FOG_END, 5.0); } glClearColor(0.5, 0.5, 0.5, 1.0); /* fog color */ return TRUE; } virtual BOOL animate() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); renderSphere (-2., -0.5, -1.0); renderSphere (-1., -0.5, -2.0); renderSphere (0., -0.5, -3.0); renderSphere (1., -0.5, -4.0); renderSphere (2., -0.5, -5.0); glFlush(); return TRUE; } virtual BOOL onChar(WPARAM wParam, LPARAM lParam) { switch (wParam) { case VK_ESCAPE: return UGLDialog::onCancel(); default: return UGLDialog::onChar(wParam, lParam); } } }; UDLGAPP_T(MyGLDialog, IDD_TEST);
25.862903
69
0.553165
fox000002
a412e29bbb4ae08fa09446111ab81014177fb322
2,551
hpp
C++
openstudiocore/src/model/ComponentWatcher_Impl.hpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
openstudiocore/src/model/ComponentWatcher_Impl.hpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
openstudiocore/src/model/ComponentWatcher_Impl.hpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2014, Alliance for Sustainable Energy. * All rights reserved. * * This library 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 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 * Lesser 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #ifndef MODEL_COMPONENTWATCHER_IMPL_HPP #define MODEL_COMPONENTWATCHER_IMPL_HPP #include "ModelAPI.hpp" #include "ModelObject.hpp" #include "ComponentData.hpp" #include "../utilities/core/Logger.hpp" #include <QObject> namespace openstudio { namespace model { class ComponentWatcher; namespace detail { class MODEL_API ComponentWatcher_Impl : public QObject, public std::enable_shared_from_this<ComponentWatcher_Impl> { Q_OBJECT; public: /** @name Constructors and Destructors */ //@{ ComponentWatcher_Impl(ComponentData& componentData); virtual ~ComponentWatcher_Impl() {} //@} /** @name Getters */ //@{ ComponentWatcher componentWatcher() const; ComponentData componentData() const; //@} signals: void obsolete(const ComponentWatcher& watcher); public slots: void dataChange(); void nameChange(); void componentDataChange(); void relationshipChange(int index,Handle newHandle,Handle oldHandle); void objectRemove(const Handle& handleOfRemovedObject); void objectAdd(const WorkspaceObject& addedObject); private: ComponentData m_componentData; std::vector<ModelObject> m_componentObjects; void mf_changeComponentVersion(); void mf_refreshComponentContents(bool logWarnings); void mf_removeComponent(); REGISTER_LOGGER("openstudio.model.ComponentWatcher"); }; } // detail } // model } // openstudio #endif // MODEL_COMPONENTWATCHER_IMPL_HPP
27.138298
119
0.668757
zhouchong90
a417542621bb6fe4bda712805ceaa87da3ddeea7
5,891
cpp
C++
test/test_arch_bsf.cpp
OscarAC/cpp-utils
b15e2ab6aebd149fb9d9a774f0a912adfd462126
[ "MIT" ]
1
2019-11-07T09:31:03.000Z
2019-11-07T09:31:03.000Z
test/test_arch_bsf.cpp
OscarAC/cpp-utils
b15e2ab6aebd149fb9d9a774f0a912adfd462126
[ "MIT" ]
null
null
null
test/test_arch_bsf.cpp
OscarAC/cpp-utils
b15e2ab6aebd149fb9d9a774f0a912adfd462126
[ "MIT" ]
null
null
null
// <util/test/test_arch_bsf.hpp> // 5/24/2015 - File Creation // Copyright(c) 2015-present, Oscar A. Carrera. // Distributed under the MIT License (http://opensource.org/licenses/MIT) #include <util/test.hpp> #include <util/arch.hpp> using namespace util; void test_bsf_32() { ASSERT_EQUAL(arch::bsf(0b00000000000000000000000000000000), -1); ASSERT_EQUAL(arch::bsf(0b00000000000000000000000000000001), 0); ASSERT_EQUAL(arch::bsf(0b00000000000000000000000000000010), 1); ASSERT_EQUAL(arch::bsf(0b00000000000000000000000000000100), 2); ASSERT_EQUAL(arch::bsf(0b00000000000000000000000000001000), 3); ASSERT_EQUAL(arch::bsf(0b00000000000000000000000000010000), 4); ASSERT_EQUAL(arch::bsf(0b00000000000000000000000000100000), 5); ASSERT_EQUAL(arch::bsf(0b00000000000000000000000001000000), 6); ASSERT_EQUAL(arch::bsf(0b00000000000000000000000010000000), 7); ASSERT_EQUAL(arch::bsf(0b00000000000000000000000100000000), 8); ASSERT_EQUAL(arch::bsf(0b00000000000000000000001000000000), 9); ASSERT_EQUAL(arch::bsf(0b00000000000000000000010000000000), 10); ASSERT_EQUAL(arch::bsf(0b00000000000000000000100000000000), 11); ASSERT_EQUAL(arch::bsf(0b00000000000000000001000000000000), 12); ASSERT_EQUAL(arch::bsf(0b00000000000000000010000000000000), 13); ASSERT_EQUAL(arch::bsf(0b00000000000000000100000000000000), 14); ASSERT_EQUAL(arch::bsf(0b00000000000000001000000000000000), 15); ASSERT_EQUAL(arch::bsf(0b00000000000000010000000000000000), 16); ASSERT_EQUAL(arch::bsf(0b00000000000000100000000000000000), 17); ASSERT_EQUAL(arch::bsf(0b00000000000001000000000000000000), 18); ASSERT_EQUAL(arch::bsf(0b00000000000010000000000000000000), 19); ASSERT_EQUAL(arch::bsf(0b00000000000100000000000000000000), 20); ASSERT_EQUAL(arch::bsf(0b00000000001000000000000000000000), 21); ASSERT_EQUAL(arch::bsf(0b00000000010000000000000000000000), 22); ASSERT_EQUAL(arch::bsf(0b00000000100000000000000000000000), 23); ASSERT_EQUAL(arch::bsf(0b00000001000000000000000000000000), 24); ASSERT_EQUAL(arch::bsf(0b00000010000000000000000000000000), 25); ASSERT_EQUAL(arch::bsf(0b00000100000000000000000000000000), 26); ASSERT_EQUAL(arch::bsf(0b00001000000000000000000000000000), 27); ASSERT_EQUAL(arch::bsf(0b00010000000000000000000000000000), 28); ASSERT_EQUAL(arch::bsf(0b00100000000000000000000000000000), 29); ASSERT_EQUAL(arch::bsf(0b01000000000000000000000000000000), 30); ASSERT_EQUAL(arch::bsf(0b10000000000000000000000000000000), 31); } void test_bsf_64() { ASSERT_EQUAL(arch::bsf(0b0000000000000000000000000000000100000000000000000000000000000000), 32); ASSERT_EQUAL(arch::bsf(0b0000000000000000000000000000001000000000000000000000000000000000), 33); ASSERT_EQUAL(arch::bsf(0b0000000000000000000000000000010000000000000000000000000000000000), 34); ASSERT_EQUAL(arch::bsf(0b0000000000000000000000000000100000000000000000000000000000000000), 35); ASSERT_EQUAL(arch::bsf(0b0000000000000000000000000001000000000000000000000000000000000000), 36); ASSERT_EQUAL(arch::bsf(0b0000000000000000000000000010000000000000000000000000000000000000), 37); ASSERT_EQUAL(arch::bsf(0b0000000000000000000000000100000000000000000000000000000000000000), 38); ASSERT_EQUAL(arch::bsf(0b0000000000000000000000001000000000000000000000000000000000000000), 39); ASSERT_EQUAL(arch::bsf(0b0000000000000000000000010000000000000000000000000000000000000000), 40); ASSERT_EQUAL(arch::bsf(0b0000000000000000000000100000000000000000000000000000000000000000), 41); ASSERT_EQUAL(arch::bsf(0b0000000000000000000001000000000000000000000000000000000000000000), 42); ASSERT_EQUAL(arch::bsf(0b0000000000000000000010000000000000000000000000000000000000000000), 43); ASSERT_EQUAL(arch::bsf(0b0000000000000000000100000000000000000000000000000000000000000000), 44); ASSERT_EQUAL(arch::bsf(0b0000000000000000001000000000000000000000000000000000000000000000), 45); ASSERT_EQUAL(arch::bsf(0b0000000000000000010000000000000000000000000000000000000000000000), 46); ASSERT_EQUAL(arch::bsf(0b0000000000000000100000000000000000000000000000000000000000000000), 47); ASSERT_EQUAL(arch::bsf(0b0000000000000001000000000000000000000000000000000000000000000000), 48); ASSERT_EQUAL(arch::bsf(0b0000000000000010000000000000000000000000000000000000000000000000), 49); ASSERT_EQUAL(arch::bsf(0b0000000000000100000000000000000000000000000000000000000000000000), 50); ASSERT_EQUAL(arch::bsf(0b0000000000001000000000000000000000000000000000000000000000000000), 51); ASSERT_EQUAL(arch::bsf(0b0000000000010000000000000000000000000000000000000000000000000000), 52); ASSERT_EQUAL(arch::bsf(0b0000000000100000000000000000000000000000000000000000000000000000), 53); ASSERT_EQUAL(arch::bsf(0b0000000001000000000000000000000000000000000000000000000000000000), 54); ASSERT_EQUAL(arch::bsf(0b0000000010000000000000000000000000000000000000000000000000000000), 55); ASSERT_EQUAL(arch::bsf(0b0000000100000000000000000000000000000000000000000000000000000000), 56); ASSERT_EQUAL(arch::bsf(0b0000001000000000000000000000000000000000000000000000000000000000), 57); ASSERT_EQUAL(arch::bsf(0b0000010000000000000000000000000000000000000000000000000000000000), 58); ASSERT_EQUAL(arch::bsf(0b0000100000000000000000000000000000000000000000000000000000000000), 59); ASSERT_EQUAL(arch::bsf(0b0001000000000000000000000000000000000000000000000000000000000000), 60); ASSERT_EQUAL(arch::bsf(0b0010000000000000000000000000000000000000000000000000000000000000), 61); ASSERT_EQUAL(arch::bsf(0b0100000000000000000000000000000000000000000000000000000000000000), 62); ASSERT_EQUAL(arch::bsf(0b1000000000000000000000000000000000000000000000000000000000000000), 63); } int main(int, char **) { test_bsf_32(); test_bsf_64(); return 0; }
64.032609
100
0.82312
OscarAC
a41ad44b3145566b8078947684223d430f7f5a34
1,913
cpp
C++
libs/libc/source/locale/setlocale.cpp
zhiayang/nx
0d9da881f67ec351244abd72e1f3884816b48f5b
[ "Apache-2.0" ]
16
2019-03-14T19:45:02.000Z
2022-02-06T19:18:08.000Z
libs/libc/source/locale/setlocale.cpp
zhiayang/nx
0d9da881f67ec351244abd72e1f3884816b48f5b
[ "Apache-2.0" ]
1
2020-05-08T08:40:02.000Z
2020-05-08T13:27:59.000Z
libs/libc/source/locale/setlocale.cpp
zhiayang/nx
0d9da881f67ec351244abd72e1f3884816b48f5b
[ "Apache-2.0" ]
2
2021-01-16T20:42:05.000Z
2021-12-01T23:37:18.000Z
/******************************************************************************* Copyright(C) Jonas 'Sortie' Termansen 2012, 2014. This file is part of the Sortix C Library. The Sortix C Library 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 3 of the License, or (at your option) any later version. The Sortix C 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the Sortix C Library. If not, see <http://www.gnu.org/licenses/>. locale/setlocale.cpp Set program locale. *******************************************************************************/ #include "../../include/locale.h" #include "../../include/stdlib.h" #include "../../include/string.h" static char* current_locales[LC_NUM_CATEGORIES] = { NULL }; extern "C" char* setlocale(int category, const char* locale) { if ( category < 0 || LC_ALL < category ) return (char*) NULL; char* new_strings[LC_NUM_CATEGORIES]; int from = category != LC_ALL ? category : 0; int to = category != LC_ALL ? category : LC_NUM_CATEGORIES - 1; if(!locale) return current_locales[to] ? current_locales[to] : (char*) "C"; for(int i = from; i <= to; i++) { if(!(new_strings[i] = strdup(locale))) { for(int n = from; n < i; n++) free(new_strings[n]); return NULL; } } // pthread_mutex_lock(&locale_lock); for(int i = from; i <= to; i++) { free(current_locales[i]); current_locales[i] = new_strings[i]; } // pthread_mutex_unlock(&locale_lock); return (char*) locale; }
30.365079
80
0.62781
zhiayang
a41dc4075f077257657668f3c287c231522dfcf2
2,123
hpp
C++
libraries/io_manager/public/IOManager.hpp
jcelerier/scop_vulkan
9b91c0ccd5027c9641ccacfb5043bb1bc2f51ad0
[ "MIT" ]
132
2021-04-04T21:19:46.000Z
2022-03-13T13:47:00.000Z
libraries/io_manager/public/IOManager.hpp
jcelerier/scop_vulkan
9b91c0ccd5027c9641ccacfb5043bb1bc2f51ad0
[ "MIT" ]
null
null
null
libraries/io_manager/public/IOManager.hpp
jcelerier/scop_vulkan
9b91c0ccd5027c9641ccacfb5043bb1bc2f51ad0
[ "MIT" ]
7
2021-04-04T21:19:48.000Z
2021-04-09T09:16:34.000Z
#ifndef SCOP_VULKAN_IOMANAGER_HPP #define SCOP_VULKAN_IOMANAGER_HPP #include <array> #include <vector> #include <string> #include <cstdint> #define GLFW_INCLUDE_VULKAN #include "GLFW/glfw3.h" #include "glm/glm.hpp" #include "IOManagerWindowCreationOption.hpp" #include "IOEvents.hpp" class IOManager final { public: IOManager(); ~IOManager(); IOManager(IOManager const &src) = delete; IOManager &operator=(IOManager const &rhs) = delete; IOManager(IOManager &&src) = delete; IOManager &operator=(IOManager &&rhs) = delete; // Constants static constexpr uint16_t const KEYS_BUFF_SIZE = 1024; static constexpr uint16_t const MOUSE_KEYS_BUFF_SIZE = 32; // Window related void createWindow(IOManagerWindowCreationOption &&opts); [[nodiscard]] GLFWwindow *getWindow() const; void deleteWindow(); [[nodiscard]] bool wasResized(); void toggleFullscreen(); [[nodiscard]] bool shouldClose() const; void triggerClose() const; void toggleMouseExclusive(); void toggleMouseVisibility(); [[nodiscard]] bool isMouseExclusive() const; [[nodiscard]] float getWindowRatio() const; [[nodiscard]] glm::ivec2 getWindowSize() const; [[nodiscard]] glm::ivec2 getFramebufferSize() const; // Keyboard / Mouse Input related [[nodiscard]] IOEvents getEvents() const; void resetMouseScroll(); // Vulkan related VkSurfaceKHR createVulkanSurface(VkInstance instance); [[nodiscard]] static std::vector<char const *> getRequiredInstanceExtension(); private: // Input std::array<uint8_t, KEYS_BUFF_SIZE> _keys{}; std::array<uint8_t, MOUSE_KEYS_BUFF_SIZE> _mouse_button{}; glm::vec2 _mouse_position{}; float _mouse_scroll{}; // Window related GLFWwindow *_win{}; bool _fullscreen{}; bool _resized{}; glm::ivec2 _win_size{}; glm::ivec2 _framebuffer_size{}; bool _mouse_exclusive{}; bool _cursor_hidden_on_window{}; // Callbacks inline void _initCallbacks(); // Mouse inline void _apply_mouse_visibility() const; }; #endif // SCOP_VULKAN_IOMANAGER_HPP
26.873418
62
0.701366
jcelerier
a4221cc112f1165aaa847f09da68d362a2efa77b
812
hpp
C++
Tetris/OpenGL/src/Logger/Logger.hpp
mhalittokluoglu/Games
bffc51ad04630eaff29c8c03508c9431ebb24c9b
[ "MIT" ]
null
null
null
Tetris/OpenGL/src/Logger/Logger.hpp
mhalittokluoglu/Games
bffc51ad04630eaff29c8c03508c9431ebb24c9b
[ "MIT" ]
null
null
null
Tetris/OpenGL/src/Logger/Logger.hpp
mhalittokluoglu/Games
bffc51ad04630eaff29c8c03508c9431ebb24c9b
[ "MIT" ]
null
null
null
#ifndef _LOGGER_HPP_ #define _LOGGER_HPP_ #define LOG_DEBUG(...) Logger::LogDebug(__VA_ARGS__) #define LOG_WARNING(...) Logger::LogWarning(__VA_ARGS__) #define LOG_ERROR(...) Logger::LogError(__VA_ARGS__) #define LOG_FATAL(...) Logger::LogFatal(__VA_ARGS__) #ifdef LINUX_SYSTEM #include "Linux/UDPClientConnection.hpp" #endif #ifdef WINDOWS_SYSTEM #include "Windows/UDPClientConnection.hpp" #endif class Logger { public: static void InitLogger(const char *ipAddres, uint64_t portNumber); static void LogDebug(const char *data, ...); static void LogWarning(const char *data, ...); static void LogError(const char *data, ...); static void LogFatal(const char *data, ...); private: static std::string GetTime(); static UDPClientConnection *m_Connection; }; #endif
26.193548
70
0.720443
mhalittokluoglu
a42562bd78b433b548aec42351e561e15fff87b3
3,654
cpp
C++
snippets/data_types/data_types.cpp
unnamedk/moderncpp
cdaf4c05ec5330df2a2fb45829a6f87e735a8744
[ "MIT" ]
null
null
null
snippets/data_types/data_types.cpp
unnamedk/moderncpp
cdaf4c05ec5330df2a2fb45829a6f87e735a8744
[ "MIT" ]
null
null
null
snippets/data_types/data_types.cpp
unnamedk/moderncpp
cdaf4c05ec5330df2a2fb45829a6f87e735a8744
[ "MIT" ]
null
null
null
#include <bitset> #include <iostream> #include <cstdint> auto get_bits(auto v) { return std::bitset<sizeof(v)*8>(*reinterpret_cast<unsigned long long*>(&v)); } int main() { // Basic types bool a = true; std::cout << "bool a: " << a << std::endl; std::cout << "sizeof(a): " << sizeof(a) << " bytes" << std::endl; std::cout << get_bits(a) << std::endl; std::cout << std::endl; int b = 25; std::cout << "int b: " << b << std::endl; std::cout << "sizeof(b): " << sizeof(b) << " bytes" << std::endl; std::cout << get_bits(b) << std::endl; std::cout << std::endl; double c = 1.34; std::cout << "double c: " << c << std::endl; std::cout << "sizeof(c): " << sizeof(c) << " bytes" << std::endl; std::cout << get_bits(c) << std::endl; std::cout << std::endl; char d = 'g'; std::cout << "char d: " << d << std::endl; std::cout << "sizeof(d): " << sizeof(d) << " bytes" << std::endl; std::cout << get_bits(d) << std::endl; std::cout << std::endl; // Integer implicit precision long g = 25; std::cout << "long g: " << g << std::endl; std::cout << "sizeof(g): " << sizeof(g) << " bytes" << std::endl; std::cout << get_bits(g) << std::endl; std::cout << std::endl; long long h = 8271; std::cout << "long long h: " << h << std::endl; std::cout << "sizeof(h): " << sizeof(h) << " bytes" << std::endl; std::cout << get_bits(h) << std::endl; std::cout << std::endl; // Unsigned integer - implicit precision unsigned long i = 987312; std::cout << "unsigned long i: " << i << std::endl; std::cout << "sizeof(i): " << sizeof(i) << " bytes" << std::endl; std::cout << get_bits(i) << std::endl; std::cout << std::endl; unsigned long long j = 4398271; std::cout << "unsigned long long j: " << j << std::endl; std::cout << "sizeof(j): " << sizeof(j) << " bytes" << std::endl; std::cout << get_bits(j) << std::endl; std::cout << std::endl; // Integer explicit precision int8_t k = 25; std::cout << "int8_t k: " << k << std::endl; std::cout << "sizeof(k): " << sizeof(k) << " bytes" << std::endl; std::cout << get_bits(k) << std::endl; std::cout << std::endl; int64_t l = 542; std::cout << "int64_t l: " << l << std::endl; std::cout << "sizeof(l): " << sizeof(l) << " bytes" << std::endl; std::cout << get_bits(l) << std::endl; std::cout << std::endl; // Unsigned integer explicit precision uint8_t m = 54; std::cout << "uint8_t m: " << m << std::endl; std::cout << "sizeof(m): " << sizeof(m) << " bytes" << std::endl; std::cout << get_bits(m) << std::endl; std::cout << std::endl; uint64_t n = 76354346; std::cout << "uint64_t n: " << n << std::endl; std::cout << "sizeof(n): " << sizeof(n) << " bytes" << std::endl; std::cout << get_bits(n) << std::endl; std::cout << std::endl; // Floating point precision float o = 25.54; std::cout << "float o: " << o << std::endl; std::cout << "sizeof(o): " << sizeof(o) << " bytes" << std::endl; std::cout << get_bits(o) << std::endl; std::cout << std::endl; long double p = 987312.325; std::cout << "long double p: " << p << std::endl; std::cout << "sizeof(p): " << sizeof(p) << " bytes" << std::endl; std::cout << get_bits(p) << std::endl; std::cout << std::endl; // Char unsigned char q = 'c'; std::cout << "unsigned char m: " << q << std::endl; std::cout << "sizeof(q): " << sizeof(q) << " bytes" << std::endl; std::cout << get_bits(q) << std::endl; std::cout << std::endl; return 0; }
33.833333
80
0.510126
unnamedk
a43514ee39a11fcd95e7a9c3c6c7f136c655e752
6,350
cpp
C++
src/StringConverters.cpp
ComicSansMS/GhulbusVulkan
b24ffb892a7573c957aed443a3fbd7ec281556e7
[ "MIT" ]
null
null
null
src/StringConverters.cpp
ComicSansMS/GhulbusVulkan
b24ffb892a7573c957aed443a3fbd7ec281556e7
[ "MIT" ]
null
null
null
src/StringConverters.cpp
ComicSansMS/GhulbusVulkan
b24ffb892a7573c957aed443a3fbd7ec281556e7
[ "MIT" ]
null
null
null
#include <gbVk/StringConverters.hpp> #include <ostream> namespace GHULBUS_VULKAN_NAMESPACE { char const* to_string(VkResult r) { #define GHULBUS_VULKAN_VKRESULT_PRINT_CASE(ec) case ec: return #ec switch(r) { default: return "Unknown"; GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_SUCCESS); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_NOT_READY); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_TIMEOUT); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_EVENT_SET); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_EVENT_RESET); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_INCOMPLETE); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_OUT_OF_HOST_MEMORY); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_OUT_OF_DEVICE_MEMORY); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_INITIALIZATION_FAILED); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_DEVICE_LOST); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_MEMORY_MAP_FAILED); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_LAYER_NOT_PRESENT); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_EXTENSION_NOT_PRESENT); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_FEATURE_NOT_PRESENT); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_INCOMPATIBLE_DRIVER); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_TOO_MANY_OBJECTS); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_FORMAT_NOT_SUPPORTED); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_FRAGMENTED_POOL); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_SURFACE_LOST_KHR); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_NATIVE_WINDOW_IN_USE_KHR); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_SUBOPTIMAL_KHR); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_OUT_OF_DATE_KHR); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_INCOMPATIBLE_DISPLAY_KHR); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_VALIDATION_FAILED_EXT); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_INVALID_SHADER_NV); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_OUT_OF_POOL_MEMORY_KHR); GHULBUS_VULKAN_VKRESULT_PRINT_CASE(VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR); } #undef GHULBUS_VULKAN_VKRESULT_PRINT_CASE } char const* to_string(VkPhysicalDeviceType t) { switch(t) { default: return "Unknown"; case VK_PHYSICAL_DEVICE_TYPE_OTHER: return "Other"; case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return "Integrated GPU"; case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return "Discrete GPU"; case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return "Virtual GPU"; case VK_PHYSICAL_DEVICE_TYPE_CPU: return "CPU"; } } std::string to_string(VkQueueFlags flags) { std::string ret; if(flags & VK_QUEUE_GRAPHICS_BIT) { ret += "Graphics "; } if(flags & VK_QUEUE_COMPUTE_BIT) { ret += "Compute "; } if(flags & VK_QUEUE_TRANSFER_BIT) { ret += "Transfer "; } if(flags & VK_QUEUE_SPARSE_BINDING_BIT) { ret += "Sparse_Binding "; } if(!ret.empty()) { ret.pop_back(); } return ret; } std::string memory_type_properties_to_string(uint32_t propertyFlags) { std::string ret; if(propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { ret += "Device_Local "; } if(propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) { ret += "Host_Visible "; } if(propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) { ret += "Host_Coherent "; } if(propertyFlags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) { ret += "Host_Cached "; } if(propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) { ret += "Lazy "; } if(!ret.empty()) { ret.pop_back(); } return ret; } std::string memory_heap_properties_to_string(uint32_t propertyFlags) { std::string ret; if(propertyFlags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) { ret += "Device_Local "; } if(!ret.empty()) { ret.pop_back(); } return ret; } std::string memory_size_to_string(VkDeviceSize size) { if(size > (1 << 30)) { return std::to_string(size >> 30u) + " GB"; } else if(size > (1 << 20)) { return std::to_string(size >> 20u) + " MB"; } else if(size > (1 << 10)) { return std::to_string(size >> 10u) + " KB"; } return std::to_string(size) + " byte" + ((size == 1) ? "" : "s"); } std::string version_to_string(uint32_t v) { return std::to_string(VK_VERSION_MAJOR(v)) + "." + std::to_string(VK_VERSION_MINOR(v)) + "." + std::to_string(VK_VERSION_PATCH(v)); } std::string uuid_to_string(uint8_t uuid[VK_UUID_SIZE]) { std::string res; res.reserve(36); auto to_char = [](int i) -> char { return (i <= 9) ? static_cast<char>('0' + i) : static_cast<char>('a' + (i-10)); }; for(int i = 0; i < VK_UUID_SIZE; ++i) { auto const hi = (uuid[i] >> 4) & 0x0F; auto const lo = uuid[i] & 0x0F; res.push_back(to_char(hi)); res.push_back(to_char(lo)); if (i == 3 || i == 5 || i == 7 || i == 9) { res.push_back('-'); } } return res; } } std::ostream& operator<<(std::ostream& os, VkResult r) { os << GHULBUS_VULKAN_NAMESPACE::to_string(r) << " (" << static_cast<int>(r) << ")"; return os; } std::ostream& operator<<(std::ostream& os, VkPhysicalDeviceType t) { return os << GHULBUS_VULKAN_NAMESPACE::to_string(t); } std::ostream& operator<<(std::ostream& os, VkLayerProperties const& lp) { os << lp.layerName << '\n' << " Spec V-" << VK_VERSION_MAJOR(lp.specVersion) << "." << VK_VERSION_MINOR(lp.specVersion) << "." << VK_VERSION_PATCH(lp.specVersion) << " Impl V-" << VK_VERSION_MAJOR(lp.implementationVersion) << "." << VK_VERSION_MINOR(lp.implementationVersion) << "." << VK_VERSION_PATCH(lp.implementationVersion) << "\n " << lp.description; return os; } std::ostream& operator<<(std::ostream& os, VkExtensionProperties const& ep) { os << ep.extensionName << " V-" << VK_VERSION_MAJOR(ep.specVersion) << "." << VK_VERSION_MINOR(ep.specVersion) << "." << VK_VERSION_PATCH(ep.specVersion); return os; }
34.324324
90
0.662205
ComicSansMS
bf9cf97872940a999f4d17b943e5e8b65a731b6d
1,819
cpp
C++
src/test/p0554.cpp
RodrigoHolztrattner/fixed_point
7fe8b459f63760a747cbcca244c002d62bf896a5
[ "BSL-1.0" ]
239
2016-03-01T12:01:21.000Z
2022-03-16T22:57:15.000Z
src/test/p0554.cpp
RodrigoHolztrattner/fixed_point
7fe8b459f63760a747cbcca244c002d62bf896a5
[ "BSL-1.0" ]
117
2015-09-12T05:35:23.000Z
2018-07-06T23:28:32.000Z
src/test/p0554.cpp
RodrigoHolztrattner/fixed_point
7fe8b459f63760a747cbcca244c002d62bf896a5
[ "BSL-1.0" ]
38
2016-03-02T17:59:24.000Z
2021-02-05T14:56:50.000Z
// Copyright John McFarlane 2015 - 2016. // 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 <sg14/auxiliary/elastic_fixed_point.h> namespace { using sg14::fixed_point; using sg14::_impl::identical; namespace bare_metal { // sample 1 - bare-metal fixed-point arithmetic constexpr auto a = (int8_t)(7.f * 8); // the value 7 stored in a byte with 3 fractional bits constexpr auto b = (int8_t)(3.125f * 16); // the value 3.125 stored in a byte with 4 fractional bits constexpr auto c = a * b; // the value 21.875 stored in an `int` with 7 fractional bits constexpr auto d = (float)c / 128; // 21.875f static_assert(identical(d, 21.875f), "position_paper test failed"); } namespace type_safe { // sample 2 - type-safe fixed-point arithmetic constexpr auto a = fixed_point<int8_t, -3>(7.f); // the value 7 stored in a byte with 3 fractional bits constexpr auto b = fixed_point<int8_t, -4>(3.125f); // the value 3.125 stored in a byte with 4 fractional bits constexpr auto c = a * b; // the value 21.875 stored in an `int` with 7 fractional bits constexpr auto d = (float)c; // 21.875f static_assert(identical(d, 21.875f), "position_paper test failed"); } namespace division { using sg14::elastic_fixed_point; constexpr elastic_fixed_point<1, 6> numerator = 0.5, denominator = 1.0; constexpr auto quotient = numerator / denominator; static_assert(identical(quotient, elastic_fixed_point<7, 7>{.5}), "position_paper test failed"); } }
47.868421
122
0.625618
RodrigoHolztrattner
bf9ed77a5181f53bb1a1209e59aa53b812798fa9
3,007
cpp
C++
src/AssetLoading/fontasset.cpp
egomeh/floaty-boaty-go-go
a011db6f1f8712bf3caa85becc1fd83ac5bf1996
[ "MIT" ]
2
2018-01-12T10:26:07.000Z
2018-02-02T19:03:00.000Z
src/AssetLoading/fontasset.cpp
egomeh/floaty-boaty-go-go
a011db6f1f8712bf3caa85becc1fd83ac5bf1996
[ "MIT" ]
null
null
null
src/AssetLoading/fontasset.cpp
egomeh/floaty-boaty-go-go
a011db6f1f8712bf3caa85becc1fd83ac5bf1996
[ "MIT" ]
null
null
null
#include "fontasset.hpp" #include "serialization/jsonserializer.hpp" #include "graphics/font.hpp" #include "graphics/graphicsutils.hpp" #include <algorithm> #include <vector> #include "util.hpp" Font *FontAssetFactory::GetAsset(const std::string &name) { if (m_LoadedAssets.count(name)) { return m_LoadedAssets[name].get(); } std::shared_ptr<Font> font = std::make_shared<Font>(); m_LoadedAssets.insert(std::make_pair(name, font)); RefreshAsset(name); return font.get(); } void FontAssetFactory::RefreshAsset(const std::string &name) { auto asset = m_LoadedAssets.find(name); if (asset == m_LoadedAssets.end()) { return; } nlohmann::json &fontAsset = (*m_AssetSubMap)[name]; std::string path = fontAsset["path"]; if (m_AssetDependencyTracker) { m_AssetDependencyTracker->InsertDependency<Font>(name, path); } std::vector<uint8_t> rawFontData; m_ResourceLoader->LoadFileContent(path, rawFontData); asset->second.get()->SetRawFontData(rawFontData); } FontTexture *FontTextureAssetFactory::GetAsset(const std::string &name) { if (m_LoadedAssets.count(name)) { return m_LoadedAssets[name].get(); } std::shared_ptr<FontTexture> texture = std::make_shared<FontTexture>(); m_LoadedAssets.insert(std::make_pair(name, texture)); RefreshAsset(name); return texture.get(); } void FontTextureAssetFactory::RefreshAsset(const std::string &name) { auto asset = m_LoadedAssets.find(name); if (asset == m_LoadedAssets.end()) { return; } nlohmann::json &fontTextureAsset = (*m_AssetSubMap)[name]; std::string path = fontTextureAsset["path"]; // If asset dependency tracker is present, add file dependency if (m_AssetDependencyTracker) { m_AssetDependencyTracker->InsertDependency<FontTexture>(path, name); } std::string serializedFontTexture = m_ResourceLoader->LoadFileAsText(path); nlohmann::json fontTextureJson; try { fontTextureJson = nlohmann::json::parse(serializedFontTexture); } catch (std::exception &ex) { DebugLog(ex.what()); return; } unsigned int size = fontTextureJson["size"]; std::string ttfSource = fontTextureJson["source"]; float fontSize = 16.f; if (fontTextureJson.count("fontsize") != 0) { fontSize = fontTextureJson["fontsize"]; } // Insert a dependency on the ttf source if (m_AssetDependencyTracker) { AssetIdentifier fontSourceIdentifier(GetTypeID<Font>(), ttfSource); m_AssetDependencyTracker->InsertDependency<FontTexture>(name, fontSourceIdentifier); } Font *ttf = m_AssetDatabase->RequestAsset<Font>(ttfSource); if (!ttf) { DebugLog("Source ttf not found"); return; } FontTexture *storedTexture = (*asset).second.get(); storedTexture->GenerateFontTexture(ttf, size, fontSize, FontTextureType::Raster); }
22.954198
92
0.669105
egomeh
bfacaf2e70f02d341600e34476e4f0ee2f01def3
7,055
cpp
C++
Luci-Engine/src/Platform/OpenGL/OpenGLFramebuffer.cpp
JordyAaldering/Game-Engine
b1a77e85073f98360931f7a94cdf05d93cb38339
[ "MIT" ]
null
null
null
Luci-Engine/src/Platform/OpenGL/OpenGLFramebuffer.cpp
JordyAaldering/Game-Engine
b1a77e85073f98360931f7a94cdf05d93cb38339
[ "MIT" ]
null
null
null
Luci-Engine/src/Platform/OpenGL/OpenGLFramebuffer.cpp
JordyAaldering/Game-Engine
b1a77e85073f98360931f7a94cdf05d93cb38339
[ "MIT" ]
null
null
null
#include "lucipch.h" #include "Platform/OpenGL/OpenGLFramebuffer.h" #include <glad/glad.h> namespace Luci { namespace Utils { static bool IsDepthFormat(FramebufferTextureFormat format) { switch (format) { case FramebufferTextureFormat::DEPTH24STENCIL8: return true; } return false; } static GLenum TextureTarget(bool multisampled) { return multisampled ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D; } static void CreateTextures(bool multisampled, uint32_t* outId, uint32_t count) { glCreateTextures(TextureTarget(multisampled), count, outId); } static void BindTexture(bool multisampled, uint32_t id) { glBindTexture(TextureTarget(multisampled), id); } static void AttachColorTexture(uint32_t id, int samples, GLenum internalFormat, GLenum format, uint32_t width, uint32_t height, int index) { bool multisampled = samples > 1; if (multisampled) { glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, samples, format, width, height, GL_FALSE); } else { glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + index, TextureTarget(multisampled), id, 0); } static void AttachDepthTexture(uint32_t id, int samples, GLenum format, GLenum attachmentType, uint32_t width, uint32_t height) { bool multisampled = samples > 1; if (multisampled) { glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, samples, format, width, height, GL_FALSE); } else { glTexStorage2D(GL_TEXTURE_2D, 1, format, width, height); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } glFramebufferTexture2D(GL_FRAMEBUFFER, attachmentType, TextureTarget(multisampled), id, 0); } static GLenum TextureFormatToGL(FramebufferTextureFormat format) { switch (format) { case FramebufferTextureFormat::RGBA8: return GL_RGBA8; case FramebufferTextureFormat::RED_INTEGER: return GL_RED_INTEGER; } LUCI_CORE_ASSERT(false, "Texture format not implemented"); return 0; } } OpenGLFramebuffer::OpenGLFramebuffer(const FramebufferSpecification& specification) : m_Specification(specification) { for (auto format : m_Specification.Attachments.Attachments) { if (!Utils::IsDepthFormat(format.TextureFormat)) { m_ColorAttachmentSpecifications.emplace_back(format); } else { m_DepthAttachmentSpecification = format; } } Invalidate(); } OpenGLFramebuffer::~OpenGLFramebuffer() { glDeleteFramebuffers(1, &m_RendererID); glDeleteTextures(m_ColorAttachments.size(), m_ColorAttachments.data()); glDeleteTextures(1, &m_DepthAttachment); } void OpenGLFramebuffer::Invalidate() { if (m_RendererID) { glDeleteFramebuffers(1, &m_RendererID); glDeleteTextures(m_ColorAttachments.size(), m_ColorAttachments.data()); glDeleteTextures(1, &m_DepthAttachment); m_ColorAttachments.clear(); m_DepthAttachment = 0; } glCreateFramebuffers(1, &m_RendererID); glBindFramebuffer(GL_FRAMEBUFFER, m_RendererID); bool multisampled = m_Specification.Samples > 1; // attachmens if (m_ColorAttachmentSpecifications.size()) { m_ColorAttachments.resize(m_ColorAttachmentSpecifications.size()); Utils::CreateTextures(multisampled, m_ColorAttachments.data(), m_ColorAttachments.size()); for (size_t i = 0; i < m_ColorAttachments.size(); i++) { Utils::BindTexture(multisampled, m_ColorAttachments[i]); switch (m_ColorAttachmentSpecifications[i].TextureFormat) { case FramebufferTextureFormat::RGBA8: Utils::AttachColorTexture(m_ColorAttachments[i], m_Specification.Samples, GL_RGBA8, GL_RGBA, m_Specification.Width, m_Specification.Height, i); break; case FramebufferTextureFormat::RED_INTEGER: Utils::AttachColorTexture(m_ColorAttachments[i], m_Specification.Samples, GL_R32I, GL_RED_INTEGER, m_Specification.Width, m_Specification.Height, i); break; } } } if (m_DepthAttachmentSpecification.TextureFormat != FramebufferTextureFormat::None) { Utils::CreateTextures(multisampled, &m_DepthAttachment, 1); Utils::BindTexture(multisampled, m_DepthAttachment); switch (m_DepthAttachmentSpecification.TextureFormat) { case FramebufferTextureFormat::DEPTH24STENCIL8: Utils::AttachDepthTexture(m_DepthAttachment, m_Specification.Samples, GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL_ATTACHMENT, m_Specification.Width, m_Specification.Height); break; } } if (m_ColorAttachments.size() > 1) { LUCI_CORE_ASSERT(m_ColorAttachments.size() <= 4, "Max 4 attachments supported"); GLenum buffers[4] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 }; glDrawBuffers(m_ColorAttachments.size(), buffers); } else if (m_ColorAttachments.empty()) { // only depth pass glDrawBuffer(GL_NONE); } LUCI_CORE_ASSERT(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, "Framebuffer is incomplete."); glBindFramebuffer(GL_FRAMEBUFFER, 0); } void OpenGLFramebuffer::Resize(uint32_t width, uint32_t height) { static const uint32_t MaxFramebufferSize = 8192; if (width == 0 || height == 0 || width > MaxFramebufferSize || height > MaxFramebufferSize) { LUCI_CORE_WARN("Attempted to resize framebuffer to invalid size ({0}, {1}).", width, height); return; } m_Specification.Width = width; m_Specification.Height = height; Invalidate(); } int OpenGLFramebuffer::ReadPixel(uint32_t attachmentIndex, int x, int y) { LUCI_CORE_ASSERT(attachmentIndex < m_ColorAttachments.size(), "Attachment index out of bounds"); glReadBuffer(GL_COLOR_ATTACHMENT0 + attachmentIndex); int pixelData; glReadPixels(x, y, 1, 1, GL_RED_INTEGER, GL_INT, &pixelData); return pixelData; } void OpenGLFramebuffer::ClearAttachment(uint32_t attachmentIndex, int value) { LUCI_CORE_ASSERT(attachmentIndex < m_ColorAttachments.size(), "Attachment index out of bounds"); auto& spec = m_ColorAttachmentSpecifications[attachmentIndex]; glClearTexImage(m_ColorAttachments[attachmentIndex], 0, Utils::TextureFormatToGL(spec.TextureFormat), GL_INT, &value); } void OpenGLFramebuffer::Bind() { glBindFramebuffer(GL_FRAMEBUFFER, m_RendererID); glViewport(0, 0, m_Specification.Width, m_Specification.Height); } void OpenGLFramebuffer::Unbind() { glBindFramebuffer(GL_FRAMEBUFFER, 0); } }
35.452261
171
0.765556
JordyAaldering
bfadc078da8c5f30a2949d64dd67471270914b62
1,140
hpp
C++
Sandbox/VirtualCallTest.hpp
delahee/enjmin
5d982da486ad0565fcda38939212e6745bdf3e3f
[ "MIT" ]
null
null
null
Sandbox/VirtualCallTest.hpp
delahee/enjmin
5d982da486ad0565fcda38939212e6745bdf3e3f
[ "MIT" ]
null
null
null
Sandbox/VirtualCallTest.hpp
delahee/enjmin
5d982da486ad0565fcda38939212e6745bdf3e3f
[ "MIT" ]
null
null
null
#pragma once #include <cctype> #include <cstdlib> class VirtualCallTest { public: static volatile double accum; static void flushCache(); }; class A { public: virtual void doSomething(); }; class B : public A { public: virtual void doSomething() override; }; class CC : public B { public: virtual void doSomething() override; }; class D : public CC { public: virtual void doSomething() override; }; class E : public D { public: virtual void doSomething() override; }; class F : public E { public: virtual void doSomething() override ; }; class G : public F { public: virtual void doSomething() override; }; class H : public G { public: virtual void doSomething() override; }; class AA { public: void doSomething(); }; class AAA { public: inline void doSomething() { VirtualCallTest::accum += Dice::randF(); VirtualCallTest::accum += Dice::randF(); VirtualCallTest::accum += Dice::randF(); VirtualCallTest::accum += Dice::randF(); VirtualCallTest::accum += Dice::randF(); VirtualCallTest::accum += Dice::randF(); VirtualCallTest::accum += Dice::randF(); VirtualCallTest::accum += Dice::randF(); } };
16.285714
42
0.685965
delahee
bfb6a789000e7dfac6acea58ecd0f15df4dd937f
7,067
hpp
C++
tests/include/testing_sycsrmv.hpp
amd/aocl-sparse
7eab271fee498af0cae9e336a74ef479dac6e781
[ "MIT" ]
11
2020-07-11T16:27:05.000Z
2022-01-11T11:50:59.000Z
tests/include/testing_sycsrmv.hpp
amd/aocl-sparse
7eab271fee498af0cae9e336a74ef479dac6e781
[ "MIT" ]
1
2020-11-12T17:45:29.000Z
2020-11-12T17:45:29.000Z
tests/include/testing_sycsrmv.hpp
amd/aocl-sparse
7eab271fee498af0cae9e336a74ef479dac6e781
[ "MIT" ]
8
2020-07-07T10:00:52.000Z
2022-01-12T15:35:17.000Z
/* ************************************************************************ * Copyright (c) 2020 Advanced Micro Devices, Inc. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * ************************************************************************ */ #pragma once #ifndef TESTING_SYCSRMV_HPP #define TESTING_SYCSRMV_HPP #include "aoclsparse.hpp" #include "aoclsparse_flops.hpp" #include "aoclsparse_gbyte.hpp" #include "aoclsparse_arguments.hpp" #include "aoclsparse_init.hpp" #include "aoclsparse_test.hpp" #include "aoclsparse_check.hpp" #include "aoclsparse_utility.hpp" #include "aoclsparse_random.hpp" /* ==================================================================================== */ /*! \brief Test function for symmetric CSR SPMV */ // Reads General/Symmetric sparse matrices in matrix market format // Invokes aoclsparse_csrmv with descr set to symmetric/general according to input // Verifies againts reference output, captures time, displays gflops , bandwidth template <typename T> void testing_sycsrmv(const Arguments& arg) { aoclsparse_int M = arg.M; aoclsparse_int N = arg.N; aoclsparse_int nnz_gen = arg.nnz; aoclsparse_int nnz = arg.nnz; aoclsparse_operation trans = arg.transA; aoclsparse_index_base base = arg.baseA; aoclsparse_matrix_init mat = arg.matrix; std::string filename = arg.filename; bool issymm; T h_alpha = static_cast<T>(arg.alpha); T h_beta = static_cast<T>(arg.beta); // Create matrix descriptor aoclsparse_local_mat_descr descr; // Set matrix index base CHECK_AOCLSPARSE_ERROR(aoclsparse_set_mat_index_base(descr, base)); // Create matrix descriptor aoclsparse_local_mat_descr rdescr; // Set matrix index base CHECK_AOCLSPARSE_ERROR(aoclsparse_set_mat_index_base(rdescr, base)); // Allocate memory for matrix std::vector<aoclsparse_int> hcsr_row_ptr; std::vector<aoclsparse_int> hcsr_col_ind; std::vector<T> hcsr_val; std::vector<aoclsparse_int> csr_row_ptr; std::vector<aoclsparse_int> csr_col_ind; std::vector<T> csr_val; aoclsparse_seedrand(); #if 0 // Print aoclsparse version int ver; aoclsparse_get_version(&ver); std::cout << "aocl-sparse version: " << ver / 100000 << "." << ver / 100 % 1000 << "." << ver % 100 << std::endl; #endif // Sample matrix aoclsparse_init_csr_matrix(hcsr_row_ptr, hcsr_col_ind, hcsr_val, M, N, nnz_gen, base, mat, filename.c_str(), issymm, true); aoclsparse_init_csr_matrix(csr_row_ptr, csr_col_ind, csr_val, M, N, nnz, base, mat, filename.c_str(), issymm, false); if(issymm == true) aoclsparse_set_mat_type(descr , aoclsparse_matrix_type_symmetric); else aoclsparse_set_mat_type(descr , aoclsparse_matrix_type_general); // Allocate memory for vectors std::vector<T> hx(N); std::vector<T> hy(M); std::vector<T> hy_gold(M); // Initialize data aoclsparse_init<T>(hx, 1, N, 1); aoclsparse_init<T>(hy, 1, M, 1); hy_gold = hy; if(arg.unit_check) { CHECK_AOCLSPARSE_ERROR(aoclsparse_csrmv(trans, &h_alpha, M, N, nnz, csr_val.data(), csr_col_ind.data(), csr_row_ptr.data(), descr, hx.data(), &h_beta, hy.data())); // Reference SPMV CSR implementation for(int i = 0; i < M; i++) { T result = 0.0; for(int j = hcsr_row_ptr[i]-base ; j < hcsr_row_ptr[i+1]-base ; j++) { result += h_alpha * hcsr_val[j] * hx[hcsr_col_ind[j] - base]; } hy_gold[i] = (h_beta * hy_gold[i]) + result; } near_check_general<T>(1, M, 1, hy_gold.data(), hy.data()); } int number_hot_calls = arg.iters; double cpu_time_used = DBL_MAX; // Performance run for(int iter = 0; iter < number_hot_calls; ++iter) { double cpu_time_start = aoclsparse_clock(); CHECK_AOCLSPARSE_ERROR(aoclsparse_csrmv(trans, &h_alpha, M, N, nnz, csr_val.data(), csr_col_ind.data(), csr_row_ptr.data(), descr, hx.data(), &h_beta, hy.data())); cpu_time_used = aoclsparse_clock_min_diff(cpu_time_used , cpu_time_start ); } double cpu_gflops = spmv_gflop_count<T>(M, nnz_gen, h_beta != static_cast<T>(0)) / cpu_time_used ; double cpu_gbyte = csrmv_gbyte_count<T>(M, N, nnz_gen, h_beta != static_cast<T>(0)) / cpu_time_used ; std::cout.precision(2); std::cout.setf(std::ios::fixed); std::cout.setf(std::ios::left); std::cout << std::setw(12) << "M" << std::setw(12) << "N" << std::setw(12) << "nnz" << std::setw(12) << "alpha" << std::setw(12) << "beta" << std::setw(12) << "GFlop/s" << std::setw(12) << "GB/s" << std::setw(12) << "msec" << std::setw(12) << "iter" << std::setw(12) << "verified" << std::endl; std::cout << std::setw(12) << M << std::setw(12) << N << std::setw(12) << nnz << std::setw(12) << h_alpha << std::setw(12) << h_beta << std::setw(12) << cpu_gflops << std::setw(12) << cpu_gbyte << std::setw(12) << cpu_time_used * 1e3 << std::setw(12) << number_hot_calls << std::setw(12) << (arg.unit_check ? "yes" : "no") << std::endl; } #endif // TESTING_SYCSRMV_HPP
35.512563
92
0.568558
amd
bfb86331d9750a2ff4d05c305913fa9eaa453e91
2,685
cpp
C++
cpp/1339.maximum-product-of-splitted-binary-tree.cpp
vermouth1992/Leetcode
0d7dda52b12f9e01d88fc279243742cd8b4bcfd1
[ "MIT" ]
null
null
null
cpp/1339.maximum-product-of-splitted-binary-tree.cpp
vermouth1992/Leetcode
0d7dda52b12f9e01d88fc279243742cd8b4bcfd1
[ "MIT" ]
null
null
null
cpp/1339.maximum-product-of-splitted-binary-tree.cpp
vermouth1992/Leetcode
0d7dda52b12f9e01d88fc279243742cd8b4bcfd1
[ "MIT" ]
null
null
null
/* * @lc app=leetcode id=1339 lang=cpp * * [1339] Maximum Product of Splitted Binary Tree * * https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/description/ * * algorithms * Medium (38.64%) * Total Accepted: 44.8K * Total Submissions: 106.2K * Testcase Example: '[1,2,3,4,5,6]' * * Given the root of a binary tree, split the binary tree into two subtrees by * removing one edge such that the product of the sums of the subtrees is * maximized. * * Return the maximum product of the sums of the two subtrees. Since the answer * may be too large, return it modulo 10^9 + 7. * * Note that you need to maximize the answer before taking the mod and not * after taking it. * * * Example 1: * * * Input: root = [1,2,3,4,5,6] * Output: 110 * Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. * Their product is 110 (11*10) * * * Example 2: * * * Input: root = [1,null,2,3,4,null,null,5,6] * Output: 90 * Explanation: Remove the red edge and get 2 binary trees with sum 15 and * 6.Their product is 90 (15*6) * * * Example 3: * * * Input: root = [2,3,9,10,7,8,6,5,4,11,1] * Output: 1025 * * * Example 4: * * * Input: root = [1,1] * Output: 1 * * * * Constraints: * * * The number of nodes in the tree is in the range [2, 5 * 10^4]. * 1 <= Node.val <= 10^4 * * */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ #include "common.hpp" class Solution { public: int maxProduct(TreeNode* root) { // compute the sum of each subtree and store in an array std::vector<long long> subtree_sum; long long total = this->compute_sum_subtree(root, subtree_sum); long long max_product = -1; for (auto& num : subtree_sum) { long long prod = (total - num) * num; if (prod > max_product) max_product = prod; } return max_product % (int) (1e9 + 7); } private: long long compute_sum_subtree(TreeNode* root, std::vector<long long> &subtree_sum) { if (root == nullptr) return 0; long long left_sum = this->compute_sum_subtree(root->left, subtree_sum); long long right_sum = this->compute_sum_subtree(root->right, subtree_sum); long long sum = left_sum + right_sum + root->val; subtree_sum.push_back(sum); return sum; } };
25.817308
93
0.614898
vermouth1992
bfb9e2b3194b153c9a2a2a9ee23fee18e5442c9d
2,634
hpp
C++
ThemeSelector.hpp
Nukem9/IDASkins
989690fffe8a7df78dc08f927cf8120f58bbfd58
[ "MIT" ]
37
2015-05-25T19:14:01.000Z
2021-11-18T14:05:11.000Z
ThemeSelector.hpp
nihilus/ida-skins
ee881f39798e8cfc2908246ccd150cb5b6702f5f
[ "MIT" ]
5
2015-08-27T15:10:25.000Z
2017-06-02T01:28:13.000Z
ThemeSelector.hpp
nihilus/ida-skins
ee881f39798e8cfc2908246ccd150cb5b6702f5f
[ "MIT" ]
7
2015-06-02T16:50:01.000Z
2020-09-04T20:36:40.000Z
/** * The MIT License (MIT) * * Copyright (c) 2014 athre0z * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef THEMESELECTOR_HPP #define THEMESELECTOR_HPP #include "ui_ThemeSelector.h" #include "ThemeManifest.hpp" #include <memory> #include <QDir> // ========================================================================= // // [ThemeSelector] // // ========================================================================= // /** * @brief Theme selection dialog. */ class ThemeSelector : public QDialog { Q_OBJECT typedef std::vector<std::pair<QDir, std::unique_ptr<ThemeManifest>>> ThemeList; Ui::ThemeSelector m_widgets; std::unique_ptr<ThemeList> m_curThemeList; QPixmap m_curPreviewImage; public: /** * @brief Constructor. * @param parent (Optional) If non-null, the parent. */ explicit ThemeSelector(QWidget *parent = nullptr); /** * @brief Refreshes the dialog. */ void refresh(); /** * @brief Gets selected theme directory * @return The selected theme directory or @c nullptr if none selected. */ const QDir *selectedThemeDir(); protected slots: /** * @brief Slot emitted when a theme was selected. */ void themeSelected(); public slots: void resizeEvent(QResizeEvent *event) override; private: /** * @brief Updates the preview image or removes it if none set. */ void updatePreview(); }; // ========================================================================= // #endif
33.341772
83
0.623766
Nukem9
bfbe6120946be0de6c788ed6f40c00001d0405ac
2,016
hpp
C++
src/CreateSearchFile.hpp
zhongguotu/ecs289c-precimonious
2c33f99eef616de9ffa5edc4c6e37ff09760ce6b
[ "BSD-3-Clause" ]
null
null
null
src/CreateSearchFile.hpp
zhongguotu/ecs289c-precimonious
2c33f99eef616de9ffa5edc4c6e37ff09760ce6b
[ "BSD-3-Clause" ]
null
null
null
src/CreateSearchFile.hpp
zhongguotu/ecs289c-precimonious
2c33f99eef616de9ffa5edc4c6e37ff09760ce6b
[ "BSD-3-Clause" ]
null
null
null
#ifndef CREATE_SEARCH_FILE_GUARD #define CREATE_SEARCH_FILE_GUARD 1 #include <llvm/Pass.h> #include <llvm/Instructions.h> #include <llvm/Support/CommandLine.h> #include <map> #include <set> #include <vector> namespace llvm { class GlobalVariable; class raw_fd_ostream; class Type; class Value; } using namespace std; using namespace llvm; extern cl::opt<string> ExcludedFunctionsFileName; extern cl::opt<string> IncludedFunctionsFileName; extern cl::opt<string> IncludedGlobalVarsFileName; extern cl::opt<string> ExcludedLocalVarsFileName; extern cl::opt<bool> ListOperators; extern cl::opt<bool> ListFunctions; extern cl::opt<bool> OnlyScalars; extern cl::opt<bool> OnlyArrays; extern cl::opt<string> FileName; class CreateSearchFile : public ModulePass { public: CreateSearchFile() : ModulePass(ID) {} virtual bool runOnModule(Module &module); virtual void getAnalysisUsage(AnalysisUsage &AU) const; static char ID; // Pass identification, replacement for typeid private: bool doInitialization(Module &); void runOnFunction(Function &function, raw_fd_ostream &outfile); void findFunctionCalls(Function &function, raw_fd_ostream &outfile); void findGlobalVariables(Module &module, raw_fd_ostream &outfile); void findLocalVariables(Function &function, raw_fd_ostream &outfile); void findOperators(Function &function, raw_fd_ostream &outfile); string findOperandName(Value *value); void printGlobal(raw_fd_ostream &outfile, string name, Type *type); void printLocal(Function &function, raw_fd_ostream &outfile, string name, Type *type); void printOperator(Function &function, raw_fd_ostream &outfile, Instruction &op, vector<string> &operands); set<string> excludedFunctions; set<string> includedFunctions; set<string> includedGlobalVars; set<string> excludedLocalVars; set<string> functionCalls; set<string> globalVars; set<string> localVars; map<Value*, string> allocaToVars; bool first; }; #endif // CREATE_SEARCH_FILE_GUARD
23.717647
109
0.771329
zhongguotu
bfc47c96ced3da4c85b6b2954c81c84e6377537d
866
hpp
C++
iRODS/server/core/include/resource.hpp
PlantandFoodResearch/irods
9dfe7ffe5aa0760b7493bd9392ea1270df9335d4
[ "BSD-3-Clause" ]
null
null
null
iRODS/server/core/include/resource.hpp
PlantandFoodResearch/irods
9dfe7ffe5aa0760b7493bd9392ea1270df9335d4
[ "BSD-3-Clause" ]
null
null
null
iRODS/server/core/include/resource.hpp
PlantandFoodResearch/irods
9dfe7ffe5aa0760b7493bd9392ea1270df9335d4
[ "BSD-3-Clause" ]
null
null
null
/*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ /* resource.h - header file for resource.c */ #ifndef RESOURCE_HPP #define RESOURCE_HPP #include "rods.hpp" #include "initServer.hpp" #include "objInfo.hpp" #include "dataObjInpOut.hpp" #include "ruleExecSubmit.hpp" #include "rcGlobalExtern.hpp" #include "rsGlobalExtern.hpp" #include "reIn2p3SysRule.hpp" #include "reSysDataObjOpr.hpp" /* definition for the flag in queRescGrp and queResc */ #define BOTTOM_FLAG 0 #define TOP_FLAG 1 #define BY_TYPE_FLAG 2 #define MAX_ELAPSE_TIME 1800 /* max time in seconds above which the load * info is considered to be out of date */ extern "C" { int getMultiCopyPerResc( rsComm_t* ); // JMC - backport 4556 } #endif /* RESOURCE_H */
23.405405
79
0.711316
PlantandFoodResearch
bfc4abaa31eee5eac5cc38472e04f16dd7071ceb
10,837
cpp
C++
seeksv/process_bwasw.cpp
qiukunlong/seeksv
d73d5fb329857d78bc76d6380f5d74318a24039a
[ "Apache-2.0" ]
16
2017-04-30T11:54:23.000Z
2022-02-23T07:57:31.000Z
seeksv/process_bwasw.cpp
qkl871118/seeksv
d73d5fb329857d78bc76d6380f5d74318a24039a
[ "Apache-2.0" ]
4
2017-09-11T02:03:33.000Z
2020-10-12T11:53:15.000Z
seeksv/process_bwasw.cpp
qkl871118/seeksv
d73d5fb329857d78bc76d6380f5d74318a24039a
[ "Apache-2.0" ]
3
2016-10-08T01:35:25.000Z
2016-11-07T09:34:54.000Z
#include "process_bwasw.h" #include "clip_reads.h" #include "getsv.h" void FindJunction(string file, int min_mapQ, multimap<Junction, OtherInfo> &junction2other) //void FindJunction(string file, int min_mapQ) { samfile_t *samfin; bam1_t *b; char in_mode[5], *fn_list = 0; in_mode[0] = 'r'; if (file.rfind(".bam") == file.size() - 4) { //if in_mode[1] == 'b', it will read a bam file in_mode[1] = 'b'; } if ((samfin = samopen(file.c_str(), in_mode, fn_list)) == 0) { cerr << "[main_samview] fail to open file for reading." << endl; exit(1); } if (samfin->header == 0) { cerr << "[main_samview] fail to read the header." << endl; exit(1); } b = bam_init1(); int ret = 0; g_min_mapQ = min_mapQ; string chr, read_id, left_seq, right_seq, left_qual, right_qual; int pos, left_seq_len, right_seq_len, map_len_in_ref; char clipped_side, strand; vector<pair<int, char> > cigar_vec; //GenerateCigar(b, map_len_in_ref) map<string, Alignment> read_id2align; map<string, Alignment>::iterator read_id2align_it; //read a line of the bam file, if the line is without soft-clipping read, ignore it while ((ret = samread(samfin, b) >= 0)) { // when read failed continue if (__g_skip_aln(samfin->header, b)) continue; //if the reads is unmap if (b->core.flag & BAM_FUNMAP) continue; int op1 = bam1_cigar(b)[0] & BAM_CIGAR_MASK, op2 = bam1_cigar(b)[b->core.n_cigar - 1] & BAM_CIGAR_MASK; if (op1 == BAM_CHARD_CLIP || op2 == BAM_CHARD_CLIP || (op1 == BAM_CSOFT_CLIP && op2 == BAM_CSOFT_CLIP) || (op1 == BAM_CMATCH && op2 == BAM_CMATCH) || b->core.flag & BAM_FDUP) continue; cigar_vec = GenerateCigar(b, map_len_in_ref); if (op1 == BAM_CSOFT_CLIP) { clipped_side = '5'; left_seq_len = (bam1_cigar(b)[0] >> BAM_CIGAR_SHIFT); right_seq_len = b->core.l_qseq - left_seq_len; pos = b->core.pos + 1; } else //op2 == BAM_CSOFT_CLIP { clipped_side = '3'; right_seq_len = (bam1_cigar(b)[b->core.n_cigar - 1] >> BAM_CIGAR_SHIFT); left_seq_len = b->core.l_qseq - right_seq_len; pos = b->core.pos + map_len_in_ref; } //bam1_strand(b) == 0 means strand is '+' bam1_strand(b) ? strand = '-' : strand = '+'; chr = samfin->header->target_name[b->core.tid]; GetSeq(b, 0, left_seq_len, right_seq_len, left_seq, left_qual, right_seq, right_qual, read_id); Alignment alignment, up_alignment, down_alignment; if (clipped_side == '5') { alignment.set_value(chr, pos, left_seq, left_qual, right_seq, right_qual, cigar_vec, '5', strand); } else { alignment.set_value(chr, pos, left_seq, left_qual, right_seq, right_qual, cigar_vec, '3', strand); } read_id2align_it = read_id2align.find(read_id); if (read_id2align_it != read_id2align.end()) { int microhomology_length = -1; if (read_id2align_it->second.strand == strand && read_id2align_it->second.clipped_side != clipped_side || read_id2align_it->second.strand != strand && read_id2align_it->second.clipped_side == clipped_side) { Junction junction; SeqInfo up_seq_info, down_seq_info; if (read_id2align_it->second.strand == strand && read_id2align_it->second.clipped_side != clipped_side) { switch(read_id2align_it->second.clipped_side) { case '5': up_alignment = alignment; down_alignment = read_id2align_it->second; break; case '3': up_alignment = read_id2align_it->second; down_alignment = alignment; break; } if (up_alignment.left_seq.length() >= down_alignment.left_seq.length()) { microhomology_length = up_alignment.left_seq.length() - down_alignment.left_seq.length(); junction.set_value(up_alignment.chr, up_alignment.pos - microhomology_length, '+', down_alignment.chr, down_alignment.pos, '+'); cigar_vec = up_alignment.cigar_vec; MinusCigarRight(cigar_vec, microhomology_length); up_seq_info.set_value(down_alignment.left_seq, cigar_vec, 0, 0, 0, 2); down_seq_info.set_value(down_alignment.right_seq, down_alignment.cigar_vec, 0, 0, 1, 2); // cerr << up_alignment.chr << '\t' << up_alignment.pos - microhomology_length << '\t' << '+' << '\t' // << down_alignment.chr << '\t' << down_alignment.pos << '\t' << '+' << '\t' << microhomology_length << '\t' << read_id << endl; } else { microhomology_length = 0; junction.set_value(up_alignment.chr, up_alignment.pos, '+', down_alignment.chr, down_alignment.pos, '+'); up_seq_info.set_value(down_alignment.left_seq, up_alignment.cigar_vec, 0, down_alignment.left_seq.length() - up_alignment.left_seq.length(), 0, 2); down_seq_info.set_value(down_alignment.right_seq, down_alignment.cigar_vec, 0, 0, 1, 2); // cerr << up_alignment.chr << '\t' << up_alignment.pos << '\t' << '+' << '\t' // << down_alignment.chr << '\t' << down_alignment.pos << '\t' << '+' << '\t' << microhomology_length << '\t' << read_id << endl; } } else if (read_id2align_it->second.strand != strand && read_id2align_it->second.clipped_side == clipped_side) { if (make_pair(read_id2align_it->second.chr, read_id2align_it->second.pos) < make_pair(chr, pos)) { up_alignment = read_id2align_it->second; down_alignment = alignment; } else { up_alignment = alignment; down_alignment = read_id2align_it->second; } if (clipped_side == '5') { if (up_alignment.right_seq.length() >= down_alignment.left_seq.length()) { microhomology_length = up_alignment.right_seq.length() - down_alignment.left_seq.length(); junction.set_value(up_alignment.chr, up_alignment.pos, '-', down_alignment.chr, down_alignment.pos + microhomology_length, '+'); GetReverseComplementSeq(up_alignment.left_seq); GetReverseComplementSeq(up_alignment.right_seq); cigar_vec = down_alignment.cigar_vec; AddCigarLeft(cigar_vec, microhomology_length); up_seq_info.set_value(up_alignment.right_seq, up_alignment.cigar_vec, 0, 0, 0, 2); down_seq_info.set_value(up_alignment.left_seq, cigar_vec, 0, 0, 1, 2); //cerr << up_alignment.chr << '\t' << up_alignment.pos << '\t' << '-' << '\t' //<< down_alignment.chr << '\t' << down_alignment.pos + microhomology_length << '\t' << '+' << '\t' << microhomology_length << '\t' << read_id << endl; } else { microhomology_length = 0; junction.set_value(up_alignment.chr, up_alignment.pos, '-', down_alignment.chr, down_alignment.pos, '+'); up_seq_info.set_value(down_alignment.left_seq, up_alignment.cigar_vec, 0, down_alignment.left_seq.length() - up_alignment.right_seq.length(), 0, 2); down_seq_info.set_value(down_alignment.right_seq, down_alignment.cigar_vec, 0, 0, 1, 2); //cerr << up_alignment.chr << '\t' << up_alignment.pos << '\t' << '-' << '\t' //<< down_alignment.chr << '\t' << down_alignment.pos << '\t' << '+' << '\t' << microhomology_length << '\t' << read_id << endl; } } else { if (up_alignment.left_seq.length() >= down_alignment.right_seq.length()) { microhomology_length = up_alignment.left_seq.length() - down_alignment.right_seq.length(); junction.set_value(up_alignment.chr, up_alignment.pos - microhomology_length, '+', down_alignment.chr, down_alignment.pos, '-'); GetReverseComplementSeq(down_alignment.left_seq); GetReverseComplementSeq(down_alignment.right_seq); cigar_vec = up_alignment.cigar_vec; MinusCigarRight(cigar_vec, microhomology_length); up_seq_info.set_value(down_alignment.right_seq, cigar_vec, 0, 0, 0, 2); down_seq_info.set_value(down_alignment.left_seq, down_alignment.cigar_vec, 0, 0, 1, 2); //cerr << up_alignment.chr << '\t' << up_alignment.pos - microhomology_length << '\t' << '+' << '\t' // << down_alignment.chr << '\t' << down_alignment.pos << '\t' << '-' << '\t' << microhomology_length << '\t' << read_id << endl; } else { microhomology_length = 0; junction.set_value(up_alignment.chr, up_alignment.pos, '+', down_alignment.chr, down_alignment.pos, '-'); up_seq_info.set_value(up_alignment.left_seq, up_alignment.cigar_vec, 0, 0, 0, 2); down_seq_info.set_value(up_alignment.right_seq, down_alignment.cigar_vec, down_alignment.right_seq.length() - up_alignment.left_seq.length(), 0, 1, 2); // cerr << up_alignment.chr << '\t' << up_alignment.pos << '\t' << '+' << '\t' // << down_alignment.chr << '\t' << down_alignment.pos << '\t' << '-' << '\t' << microhomology_length << '\t' << read_id << endl; } } } multimap<Junction, OtherInfo>::iterator junction2other_it = junction2other.find(junction); if (junction2other_it == junction2other.end()) { OtherInfo other_info(up_seq_info, down_seq_info, microhomology_length, 0); junction2other.insert(make_pair(junction, other_info)); } else { int up_seq_len1 = junction2other_it->second.up_seq_info.seq.length(); int down_seq_len1 = junction2other_it->second.down_seq_info.seq.length(); int up_seq_len2 = up_seq_info.seq.length(); int down_seq_len2 = down_seq_info.seq.length(); if (up_seq_len1 != up_seq_len2 || down_seq_len1 != down_seq_len2) { junction2other_it->second.down_seq_info.support_read_no++; } } read_id2align.erase(read_id); } } else { read_id2align.insert(make_pair(read_id, alignment)); } } } //int main(int argc, char *argv[]) //{ // string file = argv[1]; // multimap<Junction, OtherInfo> junction2other; // FindJunction(file, 1, junction2other); // multimap<Junction, OtherInfo>::iterator junction2other_it = junction2other.begin(); // while (junction2other_it != junction2other.end()) // { // cout << junction2other_it->first.up_chr << '\t' << junction2other_it->first.up_pos << '\t' << junction2other_it->first.up_strand << '\t' // << junction2other_it->first.down_chr << '\t' << junction2other_it->first.down_pos << '\t' << junction2other_it->first.down_strand << '\t' // << junction2other_it->second.down_seq_info.support_read_no << '\t' << junction2other_it->second.microhomology_length << '\t'; // for (int i = 0; i < junction2other_it->second.up_seq_info.cigar_vec.size(); i++) // cout << junction2other_it->second.up_seq_info.cigar_vec[i].first << junction2other_it->second.up_seq_info.cigar_vec[i].second; // cout << '\t'; // for (int i = 0; i < junction2other_it->second.down_seq_info.cigar_vec.size(); i++) // cout << junction2other_it->second.down_seq_info.cigar_vec[i].first << junction2other_it->second.down_seq_info.cigar_vec[i].second; // cout << '\t' << junction2other_it->second.up_seq_info.seq << '\t' << junction2other_it->second.down_seq_info.seq << endl; // ++junction2other_it; // } // return 0; //}
43.003968
208
0.666236
qiukunlong
bfc6ac5bd91640e7f7369d81db078a5c4c657648
2,349
cpp
C++
DailySummary/二叉搜索树的操作集.cpp
hao14293/2021-Postgraduate-408
70e1c40e6bcf0c5afe4a4638a7c168069d9c8319
[ "MIT" ]
950
2020-02-21T02:39:18.000Z
2022-03-31T07:27:36.000Z
DailySummary/二叉搜索树的操作集.cpp
RestmeF/2021-Postgraduate-408
70e1c40e6bcf0c5afe4a4638a7c168069d9c8319
[ "MIT" ]
6
2020-04-03T13:08:47.000Z
2022-03-07T08:54:56.000Z
DailySummary/二叉搜索树的操作集.cpp
RestmeF/2021-Postgraduate-408
70e1c40e6bcf0c5afe4a4638a7c168069d9c8319
[ "MIT" ]
131
2020-02-22T15:35:59.000Z
2022-03-21T04:23:57.000Z
#include <stdio.h> #include <stdlib.h> typedef int ElementType; typedef struct TNode *Position; typedef Position BinTree; struct TNode{ ElementType Data; BinTree Left; BinTree Right; }; BinTree Insert(BinTree BST, ElementType X); BinTree Delete(BinTree BST, ElementType X); Position Find(BinTree BST, ElementType X); Position FindMin(BinTree BST); Position FindMax(BinTree BST); int main() { BinTree BST, MinP, MaxP, Tmp; ElementType X; int N, i; BST = NULL; scanf("%d", &N); for (i = 0; i<N; i++) { scanf("%d", &X); BST = Insert(BST, X); } MinP = FindMin(BST); MaxP = FindMax(BST); scanf("%d", &N); for (i = 0; i<N; i++) { scanf("%d", &X); Tmp = Find(BST, X); if (Tmp == NULL) printf("%d is not found\n", X); else { printf("%d is found\n", Tmp->Data); if (Tmp == MinP) printf("%d is the smallest key\n", Tmp->Data); if (Tmp == MaxP) printf("%d is the largest key\n", Tmp->Data); } } scanf("%d", &N); for (i = 0; i<N; i++) { scanf("%d", &X); BST = Delete(BST, X); } return 0; } BinTree Insert(BinTree BST, ElementType X) { if (!BST) { BST = (BinTree)malloc(sizeof(struct TNode)); BST->Data = X; BST->Left = BST->Right = NULL; } else if (X < BST->Data) BST->Left = Insert(BST->Left, X); else if (X > BST->Data) BST->Right = Insert(BST->Right, X); return BST; } BinTree Delete(BinTree BST, ElementType X) { BinTree Temp; if (!BST) printf("Not Found\n"); else if (X < BST->Data) BST->Left = Delete(BST->Left, X); else if (X > BST->Data) BST->Right = Delete(BST->Right, X); else { if (BST->Left && BST->Right) //有两个子结点,用右子节点最大代替。 { Temp = FindMin(BST->Right); BST->Data = Temp->Data; BST->Right = Delete(BST->Right, Temp->Data); } else //有一个子结点或没有。 { Temp = BST; if (BST->Left) //只有左子结点; BST = BST->Left; else //只有右子结点; BST = BST->Right; free(Temp); } } return BST; } Position Find(BinTree BST, ElementType X) { if (!BST) return NULL; if (X < BST->Data) return(Find(BST->Left, X)); else if (X > BST->Data) return(Find(BST->Right, X)); else return BST; } Position FindMin(BinTree BST) { if (!BST) return NULL; if (!BST->Left) return BST; else return FindMin(BST->Left); } Position FindMax(BinTree BST) { if (!BST) return NULL; if (!BST->Right) return BST; else return FindMax(BST->Right); }
17.661654
66
0.601533
hao14293
bfc8d1f99a41d8500720652835d1e7e0a98d51d0
780
hh
C++
PyInputReader/JoyPoller.hh
BeTeK/PyXinputReader
734e5647efedb87435a71af94cb5ba1e5bd44d4b
[ "BSD-3-Clause" ]
null
null
null
PyInputReader/JoyPoller.hh
BeTeK/PyXinputReader
734e5647efedb87435a71af94cb5ba1e5bd44d4b
[ "BSD-3-Clause" ]
null
null
null
PyInputReader/JoyPoller.hh
BeTeK/PyXinputReader
734e5647efedb87435a71af94cb5ba1e5bd44d4b
[ "BSD-3-Clause" ]
null
null
null
#ifndef JOY_POLLER_HH #define JOY_POLLER_HH #include "WindowsHandler.hh" #include "Joystick.hh" #include "JoyState.hh" #include <dinput.h> #include <vector> class JoyPoller { public: virtual ~JoyPoller(); JoyPoller() = delete; JoyPoller(WindowsHandler& pWinHanler); JoyPoller& operator=(const JoyPoller& pRight) = delete; JoyPoller(const JoyPoller& pRight) = delete; const std::vector<JoyState>& poll(); const std::vector<JoyState>& getStates(); void rescan(); private: WindowsHandler& mWinHandler; static BOOL CALLBACK EnumJoysticksCallback(const DIDEVICEINSTANCE* pdidInstance, VOID* pContext); std::vector<Joystick::JoystickPtr> mJoyLst; std::vector<JoyState> mJoyStates; LPDIRECTINPUT8 mDI; }; #endif // !JOY_POLLER_HH
21.666667
99
0.723077
BeTeK