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
0c962a18f8cfd517e942eea403312fa83f246c86
6,162
cpp
C++
QSynthesis/Frontend/Tabs/Tuning/Editor/Modules/FindReplaceDialog.cpp
SineStriker/QSynthesis-Old
7b96f2d1292a4a57de6e1c50d4df2a57bfe2bc5d
[ "MIT" ]
3
2021-12-08T05:30:52.000Z
2021-12-18T10:46:49.000Z
QSynthesis/Frontend/Tabs/Tuning/Editor/Modules/FindReplaceDialog.cpp
QSynthesis/QSynthesis-Old
7b96f2d1292a4a57de6e1c50d4df2a57bfe2bc5d
[ "MIT" ]
null
null
null
QSynthesis/Frontend/Tabs/Tuning/Editor/Modules/FindReplaceDialog.cpp
QSynthesis/QSynthesis-Old
7b96f2d1292a4a57de6e1c50d4df2a57bfe2bc5d
[ "MIT" ]
null
null
null
#include "FindReplaceDialog.h" FindReplaceDialog::FindReplaceDialog(QWidget *parent) : TransparentContainer(parent) { m_current = 0; m_total = 0; mainLayout = new QGridLayout(this); mainLayout->setVerticalSpacing(10); findEdit = new FixedLineEdit(); replaceEdit = new FixedLineEdit(); findEdit->setPlaceholderText(tr("Find")); replaceEdit->setPlaceholderText(tr("Replace")); findEdit->setClearButtonEnabled(true); replaceEdit->setClearButtonEnabled(true); btnCase = new TextButton("Aa"); btnWord = new TextButton("W"); btnReserve = new TextButton("AB"); btnCase->setToolTip(tr("Case sensitive")); btnWord->setToolTip(tr("Whole words only")); btnReserve->setToolTip(tr("Preserve case")); btnCase->setCheckable(true); btnWord->setCheckable(true); btnReserve->setCheckable(true); QSize btnSize1(30, 30); btnCase->setFixedSize(btnSize1); btnWord->setFixedSize(btnSize1); btnReserve->setFixedSize(btnSize1); QFrame *separator = new QFrame(); separator->setProperty("type", "finder-separator"); separator->setFrameStyle(QFrame::VLine); separator->setFrameShadow(QFrame::Plain); separator->setFixedWidth(1); lbResult = new QLabel(); lbResult->setMinimumWidth(100); lbResult->setProperty("type", "finder-result"); lbResult->setAlignment(Qt::AlignCenter); QSizeF padding(5, 5); QSizeF padding2(8, 8); QSize btnSize2(30, 30); btnPrev = new IconButton(padding); btnNext = new IconButton(padding); btnReplace = new IconButton(padding); btnReplaceAll = new IconButton(padding); btnClose = new IconButton(padding2); btnPrev->setIcon(":/images/arrow-left-line.svg"); btnNext->setIcon(":/images/arrow-right-line.svg"); btnReplace->setIcon(":/images/find-replace-line.svg"); btnReplaceAll->setIcon(":/images/file-search-line.svg"); btnClose->setIcon(":/images/close-line.svg"); btnPrev->setToolTip(tr("Previous occurrence")); btnNext->setToolTip(tr("Next occurrence")); btnReplace->setToolTip(tr("Replace")); btnReplaceAll->setToolTip(tr("Replace all")); btnNext->setFixedSize(btnSize2); btnPrev->setFixedSize(btnSize2); btnReplace->setFixedSize(btnSize2); btnReplaceAll->setFixedSize(btnSize2); btnClose->setFixedSize(btnSize2); setFocusPolicy(Qt::ClickFocus); findEdit->setFocusPolicy(Qt::ClickFocus); replaceEdit->setFocusPolicy(Qt::ClickFocus); installEventFilter(this); findEdit->installEventFilter(this); replaceEdit->installEventFilter(this); connect(btnCase, &TextButton::toggled, this, &FindReplaceDialog::handleCaseBtnToggled); connect(btnWord, &TextButton::toggled, this, &FindReplaceDialog::handleWordBtnToggled); connect(btnPrev, &IconButton::clicked, this, &FindReplaceDialog::handlePrevBtnClicked); connect(btnNext, &IconButton::clicked, this, &FindReplaceDialog::handleNextBtnClicked); connect(btnReplace, &IconButton::clicked, this, &FindReplaceDialog::handleReplaceBtnClicked); connect(btnReplaceAll, &IconButton::clicked, this, &FindReplaceDialog::handleReplaceAllBtnClicked); connect(findEdit, &FixedLineEdit::textChanged, this, &FindReplaceDialog::handleFindTextChanged); connect(btnClose, &IconButton::clicked, this, &FindReplaceDialog::handleCloseBtnClicked); mainLayout->addWidget(findEdit, 0, 0); mainLayout->addWidget(replaceEdit, 1, 0, 1, 2); mainLayout->addWidget(btnCase, 0, 1); mainLayout->addWidget(btnWord, 0, 2); mainLayout->addWidget(btnReserve, 1, 2); mainLayout->addWidget(separator, 0, 3, 2, 1); mainLayout->addWidget(lbResult, 0, 4); mainLayout->addWidget(btnPrev, 0, 5); mainLayout->addWidget(btnNext, 0, 6); mainLayout->addWidget(btnClose, 0, 7); mainLayout->addWidget(btnReplace, 1, 5); mainLayout->addWidget(btnReplaceAll, 1, 6); setLayout(mainLayout); updateCaption(); setMinimumWidth(500); } FindReplaceDialog::~FindReplaceDialog() { } bool FindReplaceDialog::matchCase() const { return btnCase->isChecked(); } bool FindReplaceDialog::matchWord() const { return btnWord->isChecked(); } bool FindReplaceDialog::preserveCase() const { return btnReserve->isChecked(); } QString FindReplaceDialog::findText() const { return findEdit->text(); } QString FindReplaceDialog::replaceText() const { return replaceEdit->text(); } int FindReplaceDialog::current() const { return m_current; } void FindReplaceDialog::setCurrent(int current) { m_current = current; updateCaption(); } int FindReplaceDialog::total() const { return m_total; } void FindReplaceDialog::setTotal(int total) { m_total = total; updateCaption(); } void FindReplaceDialog::setFindTextFocus() { findEdit->setFocus(); findEdit->selectAll(); } void FindReplaceDialog::updateCaption() { lbResult->setText(QString::number(m_current) + "/" + QString::number(m_total)); } void FindReplaceDialog::handleCaseBtnToggled(bool checked) { emit findStateChanged(); } void FindReplaceDialog::handleWordBtnToggled(bool checked) { emit findStateChanged(); } void FindReplaceDialog::handleReserveBtnToggled(bool checked) { } void FindReplaceDialog::handlePrevBtnClicked() { emit prevRequested(); } void FindReplaceDialog::handleNextBtnClicked() { emit nextRequested(); } void FindReplaceDialog::handleReplaceBtnClicked() { emit replaceRequested(); } void FindReplaceDialog::handleReplaceAllBtnClicked() { emit replaceAllRequested(); } void FindReplaceDialog::handleFindTextChanged(const QString &text) { emit findStateChanged(); } void FindReplaceDialog::handleCloseBtnClicked() { emit closeRequested(); } bool FindReplaceDialog::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); int key = keyEvent->key(); if (key == Qt::Key_Enter || key == Qt::Key_Return) { emit nextRequested(); return true; } } return TransparentContainer::eventFilter(obj, event); }
29.066038
100
0.708536
SineStriker
0c9be8bf8c8c8e849788107a267df066f7ee8212
228
hpp
C++
dynamic/wrappers/cell_based/FarhadifarForce2.cppwg.hpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
6
2017-02-04T16:10:53.000Z
2021-07-01T08:03:16.000Z
dynamic/wrappers/cell_based/FarhadifarForce2.cppwg.hpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
6
2017-06-22T08:50:41.000Z
2019-12-15T20:17:29.000Z
dynamic/wrappers/cell_based/FarhadifarForce2.cppwg.hpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
3
2017-05-15T21:33:58.000Z
2019-10-27T21:43:07.000Z
#ifndef FarhadifarForce2_hpp__pyplusplus_wrapper #define FarhadifarForce2_hpp__pyplusplus_wrapper namespace py = pybind11; void register_FarhadifarForce2_class(py::module &m); #endif // FarhadifarForce2_hpp__pyplusplus_wrapper
32.571429
52
0.877193
jmsgrogan
0ca65de3b6d4fe81148de61559e9529bc329a18f
10,630
cpp
C++
PosixTimespec_test/PosixTimespec_test.cpp
leighgarbs/toolbox
fd9ceada534916fa8987cfcb5220cece2188b304
[ "MIT" ]
null
null
null
PosixTimespec_test/PosixTimespec_test.cpp
leighgarbs/toolbox
fd9ceada534916fa8987cfcb5220cece2188b304
[ "MIT" ]
null
null
null
PosixTimespec_test/PosixTimespec_test.cpp
leighgarbs/toolbox
fd9ceada534916fa8987cfcb5220cece2188b304
[ "MIT" ]
null
null
null
#include <iostream> #include <time.h> #include <vector> #include "PosixTimespec_test.hpp" #include "PosixTimespec.hpp" #include "Test.hpp" #include "TestCases.hpp" #include "TestMacros.hpp" TEST_PROGRAM_MAIN(PosixTimespec_test); //============================================================================== void PosixTimespec_test::addTestCases() { ADD_TEST_CASE(Operators); } //============================================================================== void PosixTimespec_test::Operators::addTestCases() { ADD_TEST_CASE(Addition); ADD_TEST_CASE(Subtraction); ADD_TEST_CASE(GreaterThan); ADD_TEST_CASE(GreaterThanOrEqualTo); ADD_TEST_CASE(LessThan); ADD_TEST_CASE(LessThanOrEqualTo); } //============================================================================== void PosixTimespec_test::Operators::Addition::addTestCases() { ADD_TEST_CASE(Case1); ADD_TEST_CASE(Case2); ADD_TEST_CASE(Case3); ADD_TEST_CASE(Case4); } //============================================================================== void PosixTimespec_test::Operators::Subtraction::addTestCases() { ADD_TEST_CASE(Case1); ADD_TEST_CASE(Case2); ADD_TEST_CASE(Case3); ADD_TEST_CASE(Case4); } //============================================================================== void PosixTimespec_test::Operators::GreaterThan::addTestCases() { ADD_TEST_CASE(Case1); ADD_TEST_CASE(Case2); ADD_TEST_CASE(Case3); } //============================================================================== void PosixTimespec_test::Operators::GreaterThanOrEqualTo::addTestCases() { ADD_TEST_CASE(Case1); ADD_TEST_CASE(Case2); ADD_TEST_CASE(Case3); } //============================================================================== void PosixTimespec_test::Operators::LessThan::addTestCases() { ADD_TEST_CASE(Case1); ADD_TEST_CASE(Case2); ADD_TEST_CASE(Case3); } //============================================================================== void PosixTimespec_test::Operators::LessThanOrEqualTo::addTestCases() { ADD_TEST_CASE(Case1); ADD_TEST_CASE(Case2); ADD_TEST_CASE(Case3); } //============================================================================== Test::Result PosixTimespec_test::Operators::Addition::Case1::body() { return operatorTest(0, 0, 0, 1, 0, 1, ADDITION); } //============================================================================== Test::Result PosixTimespec_test::Operators::Addition::Case2::body() { return operatorTest( 2346, 999999999, 1000, 40, 3347, 39, ADDITION); } //============================================================================== Test::Result PosixTimespec_test::Operators::Addition::Case3::body() { return operatorTest(5, 0, 2, 500000000, 7, 500000000, ADDITION); } //============================================================================== Test::Result PosixTimespec_test::Operators::Addition::Case4::body() { return operatorTest(1, 250000000, 0, 750000000, 2, 0, ADDITION); } //============================================================================== Test::Result PosixTimespec_test::Operators::Subtraction::Case1::body() { return operatorTest( 0, 0, 0, 1, static_cast<time_t>(0) - 1, 999999999, SUBTRACTION); } //============================================================================== Test::Result PosixTimespec_test::Operators::Subtraction::Case2::body() { return operatorTest( 2346, 999999999, 1000, 40, 1346, 999999959, SUBTRACTION); } //============================================================================== Test::Result PosixTimespec_test::Operators::Subtraction::Case3::body() { return operatorTest( 5, 0, 2, 500000000, 2, 500000000, SUBTRACTION); } //============================================================================== Test::Result PosixTimespec_test::Operators::Subtraction::Case4::body() { return operatorTest( 1, 250000000, 0, 750000000, 0, 500000000, SUBTRACTION); } //============================================================================== Test::Result PosixTimespec_test::Operators::GreaterThan::Case1::body() { return operatorTest(1, 0, 0, 1, true, GREATER_THAN); } //============================================================================== Test::Result PosixTimespec_test::Operators::GreaterThan::Case2::body() { return operatorTest(1, 0, 1, 0, false, GREATER_THAN); } //============================================================================== Test::Result PosixTimespec_test::Operators::GreaterThan::Case3::body() { return operatorTest(0, 1, 1, 0, false, GREATER_THAN); } //============================================================================== Test::Result PosixTimespec_test::Operators::GreaterThanOrEqualTo::Case1::body() { return operatorTest(1, 0, 0, 1, true, GREATER_THAN_OR_EQUAL_TO); } //============================================================================== Test::Result PosixTimespec_test::Operators::GreaterThanOrEqualTo::Case2::body() { return operatorTest(1, 0, 1, 0, true, GREATER_THAN_OR_EQUAL_TO); } //============================================================================== Test::Result PosixTimespec_test::Operators::GreaterThanOrEqualTo::Case3::body() { return operatorTest(0, 1, 1, 0, false, GREATER_THAN_OR_EQUAL_TO); } //============================================================================== Test::Result PosixTimespec_test::Operators::LessThan::Case1::body() { return operatorTest(1, 0, 0, 1, false, LESS_THAN); } //============================================================================== Test::Result PosixTimespec_test::Operators::LessThan::Case2::body() { return operatorTest(1, 0, 1, 0, false, LESS_THAN); } //============================================================================== Test::Result PosixTimespec_test::Operators::LessThan::Case3::body() { return operatorTest(0, 1, 1, 0, true, LESS_THAN); } //============================================================================== Test::Result PosixTimespec_test::Operators::LessThanOrEqualTo::Case1::body() { return operatorTest(1, 0, 0, 1, false, LESS_THAN_OR_EQUAL_TO); } //============================================================================== Test::Result PosixTimespec_test::Operators::LessThanOrEqualTo::Case2::body() { return operatorTest(1, 0, 1, 0, true, LESS_THAN_OR_EQUAL_TO); } //============================================================================== Test::Result PosixTimespec_test::Operators::LessThanOrEqualTo::Case3::body() { return operatorTest(0, 1, 1, 0, true, LESS_THAN_OR_EQUAL_TO); } //============================================================================== Test::Result PosixTimespec_test::Operators::operatorTest( time_t lhs_tv_sec, long lhs_tv_nsec, time_t rhs_tv_sec, long rhs_tv_nsec, time_t result_tv_sec, long result_tv_nsec, ArithmeticOperation operation) { // Create representations in the basic POSIX timespec and PosixTimespec PosixTimespec lhs; lhs.tp.tv_sec = lhs_tv_sec; lhs.tp.tv_nsec = lhs_tv_nsec; timespec lhs_ts; lhs_ts.tv_sec = lhs_tv_sec; lhs_ts.tv_nsec = lhs_tv_nsec; // Create representations in the basic POSIX timespec and PosixTimespec PosixTimespec rhs; rhs.tp.tv_sec = rhs_tv_sec; rhs.tp.tv_nsec = rhs_tv_nsec; timespec rhs_ts; rhs_ts.tv_sec = rhs_tv_sec; rhs_ts.tv_nsec = rhs_tv_nsec; // Do three separate tests of each operator. One test uses a PosixTimespec // on both sides and the other two use a PosixTimespec on only one side. PosixTimespec result_bothsides; PosixTimespec result_lhs; PosixTimespec result_rhs; if (operation == ADDITION) { result_bothsides = lhs + rhs; result_lhs = lhs + rhs_ts; result_rhs = lhs_ts + rhs; } else if (operation == SUBTRACTION) { result_bothsides = lhs - rhs; result_lhs = lhs - rhs_ts; result_rhs = lhs_ts - rhs; } MUST_BE_TRUE(result_bothsides.tp.tv_sec == result_tv_sec); MUST_BE_TRUE(result_bothsides.tp.tv_nsec == result_tv_nsec); MUST_BE_TRUE(result_lhs.tp.tv_sec == result_tv_sec); MUST_BE_TRUE(result_lhs.tp.tv_nsec == result_tv_nsec); MUST_BE_TRUE(result_rhs.tp.tv_sec == result_tv_sec); MUST_BE_TRUE(result_rhs.tp.tv_nsec == result_tv_nsec); return Test::PASSED; } //============================================================================== Test::Result PosixTimespec_test::Operators::operatorTest( time_t lhs_tv_sec, long lhs_tv_nsec, time_t rhs_tv_sec, long rhs_tv_nsec, bool result, ComparisonOperation operation) { // Create representations in the basic POSIX timespec and PosixTimespec PosixTimespec lhs; lhs.tp.tv_sec = lhs_tv_sec; lhs.tp.tv_nsec = lhs_tv_nsec; timespec lhs_ts; lhs_ts.tv_sec = lhs_tv_sec; lhs_ts.tv_nsec = lhs_tv_nsec; // Create representations in the basic POSIX timespec and PosixTimespec PosixTimespec rhs; rhs.tp.tv_sec = rhs_tv_sec; rhs.tp.tv_nsec = rhs_tv_nsec; timespec rhs_ts; rhs_ts.tv_sec = rhs_tv_sec; rhs_ts.tv_nsec = rhs_tv_nsec; // Do three separate tests of each operator. One test uses a PosixTimespec // on both sides and the other two use a PosixTimespec on only one side. bool result_bothsides = false; bool result_lhs = false; bool result_rhs = false; if (operation == GREATER_THAN) { result_bothsides = lhs > rhs; result_lhs = lhs > rhs_ts; result_rhs = lhs_ts > rhs; } else if (operation == GREATER_THAN_OR_EQUAL_TO) { result_bothsides = lhs >= rhs; result_lhs = lhs >= rhs_ts; result_rhs = lhs_ts >= rhs; } else if (operation == LESS_THAN) { result_bothsides = lhs < rhs; result_lhs = lhs < rhs_ts; result_rhs = lhs_ts < rhs; } else if (operation == LESS_THAN_OR_EQUAL_TO) { result_bothsides = lhs <= rhs; result_lhs = lhs <= rhs_ts; result_rhs = lhs_ts <= rhs; } MUST_BE_TRUE(result_bothsides == result); MUST_BE_TRUE(result_lhs == result); MUST_BE_TRUE(result_rhs == result); return Test::PASSED; }
32.31003
80
0.522201
leighgarbs
0ca8efe7daa5a13ef26181e08cd52b5a23f304fb
10,393
cpp
C++
Source/IO/NCCheckpoint.cpp
etpalmer63/ERF
88a3969ae93aae5b9d1416217df9051da476114e
[ "BSD-3-Clause-LBNL" ]
null
null
null
Source/IO/NCCheckpoint.cpp
etpalmer63/ERF
88a3969ae93aae5b9d1416217df9051da476114e
[ "BSD-3-Clause-LBNL" ]
null
null
null
Source/IO/NCCheckpoint.cpp
etpalmer63/ERF
88a3969ae93aae5b9d1416217df9051da476114e
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include <ERF.H> #include <NCInterface.H> #include <AMReX_PlotFileUtil.H> using namespace amrex; void ERF::WriteNCCheckpointFile () const { // checkpoint file name, e.g., chk00010 const std::string& checkpointname = amrex::Concatenate(check_file,istep[0],5); amrex::Print() << "Writing NetCDF checkpoint " << checkpointname << "\n"; const int nlevels = finest_level+1; // ---- ParallelDescriptor::IOProcessor() creates the directories PreBuildDirectorHierarchy(checkpointname, "Level_", nlevels, true); // write Header file if (ParallelDescriptor::IOProcessor()) { std::string HeaderFileName(checkpointname + "/Header.nc"); auto ncf = ncutils::NCFile::create(HeaderFileName, NC_CLOBBER | NC_NETCDF4); const std::string ndim_name = "num_dimension"; const std::string nl_name = "finest_levels"; const std::string ng_name = "num_grids"; const std::string nvar_name = "num_vars"; const std::string ndt_name = "num_dt"; const std::string nstep_name = "num_istep"; const std::string ntime_name = "num_newtime"; const int ndt = dt.size(); const int nstep = istep.size(); const int ntime = t_new.size(); amrex::Vector<int> nbox(nlevels); amrex::Vector<std::string> nbox_name(nlevels); amrex::Vector<amrex::Vector<std::string> > lo_names(nlevels); amrex::Vector<amrex::Vector<std::string> > hi_names(nlevels); amrex::Vector<amrex::Vector<std::string> > typ_names(nlevels); for (auto lev{0}; lev <= finest_level; ++lev) { nbox[lev] = boxArray(lev).size(); nbox_name[lev] = "NBox_"+std::to_string(lev); for (int nb(0); nb < boxArray(lev).size(); ++nb) { lo_names[lev] .push_back("SmallEnd_"+std::to_string(lev)+"_"+std::to_string(nb)); hi_names[lev] .push_back("BigEnd_"+std::to_string(lev)+"_"+std::to_string(nb)); typ_names[lev].push_back("BoxType_"+std::to_string(lev)+"_"+std::to_string(nb)); } } ncf.enter_def_mode(); ncf.put_attr("title", "ERF NetCDF CheckPoint Header"); ncf.def_dim(ndim_name, AMREX_SPACEDIM); ncf.def_dim(nl_name, nlevels); ncf.def_dim(ndt_name, ndt); ncf.def_dim(nstep_name, nstep); ncf.def_dim(ntime_name, ntime); for (auto lev{0}; lev <= finest_level; ++lev) { ncf.def_dim(nbox_name[lev], nbox[lev]); for (int nb(0); nb < boxArray(lev).size(); ++nb) { ncf.def_var(lo_names[lev][nb], ncutils::NCDType::Int, {nbox_name[lev], ndim_name}); ncf.def_var(hi_names[lev][nb], ncutils::NCDType::Int, {nbox_name[lev], ndim_name}); ncf.def_var(typ_names[lev][nb], ncutils::NCDType::Int, {nbox_name[lev], ndim_name}); } } ncf.def_var("istep", ncutils::NCDType::Int, {nstep_name}); ncf.def_var("dt" , ncutils::NCDType::Real, {ndt_name} ); ncf.def_var("tnew" , ncutils::NCDType::Real, {ntime_name}); ncf.exit_def_mode(); // output headfile in NetCDF format ncf.var("istep").put(istep.data(), {0}, {static_cast<long unsigned int>(nstep)}); ncf.var("dt") .put(dt.data(), {0}, {static_cast<long unsigned int>(ndt)}); ncf.var("tnew") .put(t_new.data(), {0}, {static_cast<long unsigned int>(ntime)}); // ncf.var("nbox") .put(nbox.begin(), {0}, {nstep}); for (auto lev{0}; lev <= finest_level; ++lev) { auto box_array = boxArray(lev); for (int nb(0); nb < box_array.size(); ++nb) { long unsigned int nbb = static_cast<long unsigned int>(nb); auto box = box_array[nb]; ncf.var(lo_names[lev][nb] ).put(box.smallEnd().begin(), {nbb, 0}, {1, AMREX_SPACEDIM}); ncf.var(hi_names[lev][nb] ).put(box.bigEnd().begin() , {nbb, 0}, {1, AMREX_SPACEDIM}); ncf.var(typ_names[lev][nb]).put(box.type().begin() , {nbb, 0}, {1, AMREX_SPACEDIM}); } } } // write the MultiFab data to, e.g., chk00010/Level_0/ // Here we make copies of the MultiFab with no ghost cells for (int lev = 0; lev <= finest_level; ++lev) { MultiFab cons(grids[lev],dmap[lev],Cons::NumVars,0); MultiFab::Copy(cons,vars_new[lev][Vars::cons],0,0,NVAR,0); WriteNCMultiFab(cons, amrex::MultiFabFileFullPrefix(lev, checkpointname, "Level_", "Cell")); MultiFab xvel(convert(grids[lev],IntVect(1,0,0)),dmap[lev],1,0); MultiFab::Copy(xvel,vars_new[lev][Vars::xvel],0,0,1,0); WriteNCMultiFab(xvel, amrex::MultiFabFileFullPrefix(lev, checkpointname, "Level_", "XFace")); MultiFab yvel(convert(grids[lev],IntVect(0,1,0)),dmap[lev],1,0); MultiFab::Copy(yvel,vars_new[lev][Vars::yvel],0,0,1,0); WriteNCMultiFab(yvel, amrex::MultiFabFileFullPrefix(lev, checkpointname, "Level_", "YFace")); MultiFab zvel(convert(grids[lev],IntVect(0,0,1)),dmap[lev],1,0); MultiFab::Copy(zvel,vars_new[lev][Vars::zvel],0,0,1,0); WriteNCMultiFab(zvel, amrex::MultiFabFileFullPrefix(lev, checkpointname, "Level_", "ZFace")); } } // // read NetCDF checkpoint to restart ERF // void ERF::ReadNCCheckpointFile () { amrex::Print() << "Restart from checkpoint " << restart_chkfile << "\n"; // Header std::string HeaderFileName(restart_chkfile + "/Header.nc"); auto ncf = ncutils::NCFile::open(HeaderFileName, NC_CLOBBER | NC_NETCDF4); const std::string nl_name = "finest_levels"; const std::string ng_name = "num_grids"; const std::string nvar_name = "num_vars"; const std::string ndt_name = "num_dt"; const std::string nstep_name = "num_istep"; const std::string ntime_name = "num_newtime"; const int nvar = static_cast<int>(ncf.dim(nvar_name).len()); AMREX_ALWAYS_ASSERT(nvar == Cons::NumVars); const int ndt = static_cast<int>(ncf.dim(ndt_name).len()); const int nstep = static_cast<int>(ncf.dim(nstep_name).len()); const int ntime = static_cast<int>(ncf.dim(ntime_name).len()); // Assert we are reading in data with the same finest_level as we have AMREX_ALWAYS_ASSERT(finest_level == static_cast<int>(ncf.dim(nl_name).len())); // output headfile in NetCDF format ncf.var("istep").get(istep.data(), {0}, {static_cast<long unsigned int>(nstep)}); ncf.var("dt") .get(dt.data(), {0}, {static_cast<long unsigned int>(ndt)}); ncf.var("t_new").get(t_new.data(), {0}, {static_cast<long unsigned int>(ntime)}); int ngrow_state = ComputeGhostCells(solverChoice.spatial_order)+1; int ngrow_vels = ComputeGhostCells(solverChoice.spatial_order); for (int lev = 0; lev <= finest_level; ++lev) { int num_box = static_cast<int>(ncf.dim("Nbox_"+std::to_string(lev)).len()); // read in level 'lev' BoxArray from Header BoxArray ba; for (int nb(0); nb < num_box; ++nb) { amrex::IntVect lo(AMREX_SPACEDIM); amrex::IntVect hi(AMREX_SPACEDIM); amrex::IntVect typ(AMREX_SPACEDIM); auto lo_name = "SmallEnd_"+std::to_string(lev)+"_"+std::to_string(nb); auto hi_name = "BigEnd_"+std::to_string(lev)+"_"+std::to_string(nb); auto typ_name = "BoxType_"+std::to_string(lev)+"_"+std::to_string(nb); ncf.var(lo_name) .get(lo.begin(), {0}, {AMREX_SPACEDIM}); ncf.var(hi_name) .get(hi.begin(), {0}, {AMREX_SPACEDIM}); ncf.var(typ_name).get(typ.begin(),{0}, {AMREX_SPACEDIM}); amrex::Box box = amrex::Box(lo, hi, typ); ba.set(nb, box); } // ba.readFrom(is); // GotoNextLine(is); // create a distribution mapping DistributionMapping dm { ba, ParallelDescriptor::NProcs() }; // set BoxArray grids and DistributionMapping dmap in AMReX_AmrMesh.H class SetBoxArray(lev, ba); SetDistributionMap(lev, dm); // build MultiFab data int ncomp = Cons::NumVars; auto& lev_old = vars_old[lev]; auto& lev_new = vars_new[lev]; lev_new[Vars::cons].define(grids[lev], dmap[lev], ncomp, ngrow_state); lev_old[Vars::cons].define(grids[lev], dmap[lev], ncomp, ngrow_state); //!don: get the ghost cells right here lev_new[Vars::xvel].define(convert(grids[lev], IntVect(1,0,0)), dmap[lev], 1, ngrow_vels); lev_old[Vars::xvel].define(convert(grids[lev], IntVect(1,0,0)), dmap[lev], 1, ngrow_vels); lev_new[Vars::yvel].define(convert(grids[lev], IntVect(0,1,0)), dmap[lev], 1, ngrow_vels); lev_old[Vars::yvel].define(convert(grids[lev], IntVect(0,1,0)), dmap[lev], 1, ngrow_vels); lev_new[Vars::zvel].define(convert(grids[lev], IntVect(0,0,1)), dmap[lev], 1, ngrow_vels); lev_old[Vars::zvel].define(convert(grids[lev], IntVect(0,0,1)), dmap[lev], 1, ngrow_vels); } // read in the MultiFab data for (int lev = 0; lev <= finest_level; ++lev) { MultiFab cons(grids[lev],dmap[lev],Cons::NumVars,0); WriteNCMultiFab(cons, amrex::MultiFabFileFullPrefix(lev, restart_chkfile, "Level_", "Cell")); MultiFab::Copy(vars_new[lev][Vars::cons],cons,0,0,Cons::NumVars,0); MultiFab xvel(convert(grids[lev],IntVect(1,0,0)),dmap[lev],1,0); WriteNCMultiFab(xvel, amrex::MultiFabFileFullPrefix(lev, restart_chkfile, "Level_", "Cell")); MultiFab::Copy(vars_new[lev][Vars::xvel],xvel,0,0,1,0); MultiFab yvel(convert(grids[lev],IntVect(0,1,0)),dmap[lev],1,0); WriteNCMultiFab(yvel, amrex::MultiFabFileFullPrefix(lev, restart_chkfile, "Level_", "Cell")); MultiFab::Copy(vars_new[lev][Vars::yvel],yvel,0,0,1,0); MultiFab zvel(convert(grids[lev],IntVect(0,0,1)),dmap[lev],1,0); WriteNCMultiFab(zvel, amrex::MultiFabFileFullPrefix(lev, restart_chkfile, "Level_", "Cell")); MultiFab::Copy(vars_new[lev][Vars::zvel],zvel,0,0,1,0); // Copy from new into old just in case MultiFab::Copy(vars_old[lev][Vars::cons],vars_new[lev][Vars::cons],0,0,NVAR,0); MultiFab::Copy(vars_old[lev][Vars::xvel],vars_new[lev][Vars::xvel],0,0,1,0); MultiFab::Copy(vars_old[lev][Vars::yvel],vars_new[lev][Vars::yvel],0,0,1,0); MultiFab::Copy(vars_old[lev][Vars::zvel],vars_new[lev][Vars::zvel],0,0,1,0); } }
43.852321
101
0.620995
etpalmer63
0ca9e8d598056fbe8c5fe6853b7646c56cc9445d
1,034
cpp
C++
Source/NdiMediaEditor/Private/Factories/NdiMediaFinderFactoryNew.cpp
Twentystudios/NdiMedia
4cc842c11940fbd2062cb940cce1e49ff5bea453
[ "BSD-3-Clause" ]
101
2016-08-05T10:33:42.000Z
2022-03-11T13:10:28.000Z
Source/NdiMediaEditor/Private/Factories/NdiMediaFinderFactoryNew.cpp
Twentystudios/NdiMedia
4cc842c11940fbd2062cb940cce1e49ff5bea453
[ "BSD-3-Clause" ]
35
2016-10-03T14:35:25.000Z
2021-03-25T05:18:34.000Z
Source/NdiMediaEditor/Private/Factories/NdiMediaFinderFactoryNew.cpp
Twentystudios/NdiMedia
4cc842c11940fbd2062cb940cce1e49ff5bea453
[ "BSD-3-Clause" ]
34
2016-08-19T15:34:55.000Z
2021-12-08T14:42:33.000Z
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "NdiMediaFinderFactoryNew.h" #include "AssetTypeCategories.h" #include "NdiMediaFinder.h" /* UNdiMediaFinderFactoryNew structors *****************************************************************************/ UNdiMediaFinderFactoryNew::UNdiMediaFinderFactoryNew(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { SupportedClass = UNdiMediaFinder::StaticClass(); bCreateNew = true; bEditAfterNew = true; } /* UFactory overrides *****************************************************************************/ UObject* UNdiMediaFinderFactoryNew::FactoryCreateNew(UClass* InClass, UObject* InParent, FName InName, EObjectFlags Flags, UObject* Context, FFeedbackContext* Warn) { return NewObject<UNdiMediaFinder>(InParent, InClass, InName, Flags); } uint32 UNdiMediaFinderFactoryNew::GetMenuCategories() const { return EAssetTypeCategories::Media; } bool UNdiMediaFinderFactoryNew::ShouldShowInNewMenu() const { return true; }
25.85
164
0.678917
Twentystudios
0cacfb880c05969b886658d21854f8329e526d1f
6,263
hpp
C++
stock_dbf_reader/stock_reader/mysql.hpp
smartdata-x/MarketSys
b4f999fb80b8f2357b75694c2ca94d46190a55f7
[ "Apache-2.0" ]
null
null
null
stock_dbf_reader/stock_reader/mysql.hpp
smartdata-x/MarketSys
b4f999fb80b8f2357b75694c2ca94d46190a55f7
[ "Apache-2.0" ]
null
null
null
stock_dbf_reader/stock_reader/mysql.hpp
smartdata-x/MarketSys
b4f999fb80b8f2357b75694c2ca94d46190a55f7
[ "Apache-2.0" ]
3
2016-10-25T01:56:17.000Z
2019-06-24T04:45:06.000Z
#ifndef MYSQL_HPP_ #define MYSQL_HPP_ #include <cassert> #include <cstdint> #include <cstring> #include <mysql.h> #include <string> #include <tuple> #include <typeinfo> #include <utility> #include <vector> #include "inpub_binder.hpp" #include "mysql_exception.hpp" #include "mysql_prepared_statement.hpp" #include "output_binder.hpp" #include "common.h" #include "utils.hpp" class mysql { public: mysql(base_logic::ConnAddr& configInfo); ~mysql(); mysql(const mysql& rhs) = delete; mysql(mysql&& rhs) = delete; mysql& operator=(const mysql& rhs) = delete; mysql& operator=(mysql&& rhs) = delete; public: void OnDisconnec(); bool ConnectMySql(); bool Reconnect(); bool CheckConnected(); /** * Normal query. Results are stored in the given vector. * @param query The query to run. * @param results A vector of tuples to store the results in. * @param args Arguments to bind to the query. */ template <typename... InputArgs, typename... OutputArgs> void runQuery( std::vector<std::tuple<OutputArgs...>>* const results, const char* const query, // Args needs to be sent by reference, because the values need to be // nontemporary (that is, lvalues) so that their memory locations // can be bound to MySQL's prepared statement API const InputArgs& ... args); /** * Command that doesn't return results, like "USE yelp" or * "INSERT INTO user VALUES ('Brandon', 28)". * @param query The query to run. * @param args Arguments to bind to the query. * @return The number of affected rows. */ /// @{ template <typename... Args> my_ulonglong runCommand( const char* const command, // Args needs to be sent by reference, because the values need to be // nontemporary (that is, lvalues) so that their memory locations // can be bound to MySQL's prepared statement API const Args& ... args) const; my_ulonglong runCommand(const char* const command); /// @} /** * Prepare a statement for multiple executions with different bound * parameters. If you're running a one off query or statement, you * should use runQuery or runCommand instead. * @param query The query to prepare. * @return A prepared statement object. */ MySqlPreparedStatement prepareStatement(const char* statement) const; /** * Run the command version of a prepared statement. */ /// @{ template <typename... Args> my_ulonglong runCommand( const MySqlPreparedStatement& statement, const Args& ... args) const; // my_ulonglong runCommand(const MySqlPreparedStatement& statement); /// @} /** * Run the query version of a prepared statement. */ template <typename... InputArgs, typename... OutputArgs> void runQuery( std::vector<std::tuple<OutputArgs...>>* results, const MySqlPreparedStatement& statement, const InputArgs& ...) const; private: base_logic::ConnAddr& m_configInfo_; int m_iReconnectCount_ = 0; MYSQL* m_pConnection_; }; template <typename... Args> my_ulonglong mysql::runCommand( const char* const command, const Args& ... args ) const { MySqlPreparedStatement statement(prepareStatement(command)); return runCommand(statement, args...); } template <typename... Args> my_ulonglong mysql::runCommand( const MySqlPreparedStatement& statement, const Args& ... args ) const { // Commands (e.g. INSERTs or DELETEs) should always have this set to 0 if (0 != statement.getFieldCount()) { throw MySqlException("Tried to run query with runCommand"); } if (sizeof...(args) != statement.getParameterCount()) { std::string errorMessage; errorMessage += "Incorrect number of parameters; command required "; errorMessage += base_logic::Utils::convertString(statement.getParameterCount()); errorMessage += " but "; errorMessage += base_logic::Utils::convertString(sizeof...(args)); errorMessage += " parameters were provided."; throw MySqlException(errorMessage); } std::vector<MYSQL_BIND> bindParameters; bindParameters.resize(statement.getParameterCount()); bindInputs<Args...>(&bindParameters, args...); if (0 != mysql_stmt_bind_param( statement.statementHandle_, bindParameters.data()) ) { throw MySqlException(statement); } if (0 != mysql_stmt_execute(statement.statementHandle_)) { throw MySqlException(statement); } // If the user ran a SELECT statement or something else, at least warn them const auto affectedRows = mysql_stmt_affected_rows( statement.statementHandle_); if ((static_cast<decltype(affectedRows)>(-1)) == affectedRows) { throw MySqlException("Tried to run query with runCommand"); } return affectedRows; } template <typename... InputArgs, typename... OutputArgs> void mysql::runQuery( std::vector<std::tuple<OutputArgs...>>* const results, const char* const query, const InputArgs& ... args) { assert(nullptr != results); assert(nullptr != query); MySqlPreparedStatement statement(prepareStatement(query)); runQuery(results, statement, args...); } template <typename... InputArgs, typename... OutputArgs> void mysql::runQuery( std::vector<std::tuple<OutputArgs...>>* const results, const MySqlPreparedStatement& statement, const InputArgs& ... args ) const { assert(nullptr != results); // SELECTs should always return something. Commands (e.g. INSERTs or // DELETEs) should always have this set to 0. if (0 == statement.getFieldCount()) { throw MySqlException("Tried to run command with runQuery"); } // Bind the input parameters // Check that the parameter count is right if (sizeof...(InputArgs) != statement.getParameterCount()) { std::string errorMessage; errorMessage += "Incorrect number of input parameters; query required "; errorMessage += base_logic::Utils::convertString(statement.getParameterCount()); errorMessage += " but "; errorMessage += base_logic::Utils::convertString(sizeof...(args)); errorMessage += " parameters were provided."; throw MySqlException(errorMessage); } std::vector<MYSQL_BIND> inputBindParameters; inputBindParameters.resize(statement.getParameterCount()); bindInputs<InputArgs...>(&inputBindParameters, args...); if (0 != mysql_stmt_bind_param( statement.statementHandle_, inputBindParameters.data()) ) { throw MySqlException(statement); } setResults<OutputArgs...>(statement, results); } #endif // MYSQL_HPP_
29.82381
82
0.724254
smartdata-x
0caf9398d1c7d6488eb8bcf273e9469f33ce18a1
2,082
cc
C++
src/ctl3d.cc
snmsts/xyzzy
3291c7898d17f90b1a50c3de1aeb5f9a446d9061
[ "RSA-MD" ]
90
2015-01-13T13:36:13.000Z
2022-03-25T12:22:19.000Z
src/ctl3d.cc
wanabe/xyzzy
a43581d9a2033d5c43d99cccfecc8e90aa3915e1
[ "RSA-MD" ]
6
2015-09-07T17:03:43.000Z
2019-08-13T12:35:48.000Z
src/ctl3d.cc
wanabe/xyzzy
a43581d9a2033d5c43d99cccfecc8e90aa3915e1
[ "RSA-MD" ]
38
2015-02-21T13:42:59.000Z
2022-03-25T12:25:15.000Z
#include "stdafx.h" #include "sysdep.h" #include "ctl3d.h" #include "vfs.h" static Ctl3d ctl3d; Ctl3dState Ctl3d::state; Ctl3d::~Ctl3d () { if (state.registered && state.Unregister) (*state.Unregister)(state.hinst); if (state.hlib) FreeLibrary (state.hlib); } void Ctl3d::enable (HINSTANCE h) { if (sysdep.Win4p () || state.registered) return; if (!state.hlib) { state.hlib = WINFS::LoadLibrary ("ctl3d32.dll"); if (!state.hlib) return; state.Register = (BOOL (WINAPI *)(HINSTANCE)) GetProcAddress (state.hlib, "Ctl3dRegister"); state.Unregister = (BOOL (WINAPI *)(HINSTANCE)) GetProcAddress (state.hlib, "Ctl3dUnregister"); state.AutoSubclass = (BOOL (WINAPI *)(HINSTANCE)) GetProcAddress (state.hlib, "Ctl3dAutoSubclass"); state.UnAutoSubclass = (BOOL (WINAPI *)()) GetProcAddress (state.hlib, "Ctl3dUnAutoSubclass"); state.ColorChange = (BOOL (WINAPI *)()) GetProcAddress (state.hlib, "Ctl3dColorChange"); state.WinIniChange = (void (WINAPI *)()) GetProcAddress (state.hlib, "Ctl3dWinIniChange"); if (!state.Register || !state.Unregister || !state.AutoSubclass || !state.UnAutoSubclass || !state.ColorChange || !state.WinIniChange) { FreeLibrary (state.hlib); state.hlib = 0; return; } } if (state.Register && state.AutoSubclass) { state.hinst = h; (*state.Register)(state.hinst); (*state.AutoSubclass)(state.hinst); state.registered = 1; } } void Ctl3d::color_change () { if (state.registered && state.ColorChange) (*state.ColorChange)(); } void Ctl3d::ini_change () { if (state.registered && state.WinIniChange) (*state.WinIniChange)(); } Ctl3dThread::Ctl3dThread () { if (Ctl3d::state.registered && Ctl3d::state.AutoSubclass) (*Ctl3d::state.AutoSubclass)(Ctl3d::state.hinst); } Ctl3dThread::~Ctl3dThread () { if (Ctl3d::state.registered && Ctl3d::state.UnAutoSubclass) (*Ctl3d::state.UnAutoSubclass)(); }
24.785714
61
0.627281
snmsts
0cb0513f28bd47fae2000ccd5f98171296258825
13,736
cpp
C++
src/elektronika/about.cpp
aestesis/elektronika
870f72ca7f64942f8316b3cd8f733f43c7d2d117
[ "Apache-2.0" ]
14
2016-05-09T01:14:03.000Z
2021-10-12T21:41:02.000Z
src/elektronika/about.cpp
aestesis/elektronika
870f72ca7f64942f8316b3cd8f733f43c7d2d117
[ "Apache-2.0" ]
null
null
null
src/elektronika/about.cpp
aestesis/elektronika
870f72ca7f64942f8316b3cd8f733f43c7d2d117
[ "Apache-2.0" ]
6
2015-08-19T01:28:54.000Z
2020-10-25T05:17:08.000Z
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // ABOUT.CPP (c) YoY'00 WEB: www.aestesis.org // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <math.h> #include "about.h" #include "main.h" #include "resource.h" ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ACI Aabout::CI=ACI("Aabout", GUID(0x11111111,0x00000103), &Awindow::CI, 0, NULL); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class AaboutMenu : public Aobject { AOBJ AaboutMenu (char *name, class Aobject *L, int x, int y, int w, int h); virtual ~AaboutMenu (); virtual void paint (Abitmap *b); virtual bool mouse (int x, int y, int state, int event); void calculText (); int position; Afont *font; char str[8192][128]; int nbstr; }; ACI AaboutMenu::CI=ACI("AaboutMenu", GUID(0x11111111,0x00000114), &Aobject::CI, 0, NULL); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// AaboutMenu::AaboutMenu(char *name, Aobject *L, int x, int y, int w, int h) : Aobject(name, L, x, y, w, h) { state|=stateNOCONTEXT; position=0; font=alib.getFont(fontTERMINAL09); calculText(); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// AaboutMenu::~AaboutMenu() { } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool AaboutMenu::mouse(int x, int y, int state, int event) { switch(event) { case mouseWHEEL: position=maxi(mini(position-(getWindow()->mouseW>>5), nbstr-5), 0); return true; } return ((Aobject *)father)->mouse(x+pos.x, y+pos.y, state, event); } void AaboutMenu::calculText() { { Aresobj *text=resource.getObj(MAKEINTRESOURCE(TXT_LICENSEDEMO), "TXT"); char *txt=(char *)text->lock(); int size=text->getSize(); int p=0; nbstr=0; while(p<size) { int d=p; int w=4; char t[2]; int l=size-p; int pn=p; char s=0; int last; t[1]=0; while((p<size)&&(w<this->pos.w)) { last=p; s=t[0]=txt[p++]; switch(s) { case ' ': l=p-d; pn=p; w+=font->w>>1; break; case '\n': d=p; break; case '\r': l=p-d; pn=p; w=this->pos.w; break; default: w+=font->getWidth(t); break; } } if(!(p>=size)) p=pn; else l=p-d; if(l>0) { strncpy(str[nbstr], txt+d, l); str[nbstr++][l]=0; } else str[nbstr++][0]=0; } text->unlock(); delete(text); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AaboutMenu::paint(Abitmap *b) { b->boxfa(0, 0, pos.w-1, pos.h-1, 0xff000000, 0.9f); { int y=4; int p=position; int h=font->getHeight("A"); while(((y+h)<pos.h)&&(p<nbstr)) { font->set(b, 4, y, str[p], 0xffffaa00); p++; y+=h; } } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Aabout::Aabout(char *name, int x, int y, class MYwindow *myw) : Awindow(name, x, y, 400, 300) { this->myw=myw; bac=false; zorder(zorderTOP); back=new Abitmap(pos.w, pos.h); title=new Astatic("title", this, 0, 0, &resource.get(MAKEINTRESOURCE(PNG_ELEKTRONIKA), "PNG")); title->show(TRUE); buttonClose=new Abutton("close", this, 378, 6, 16, 16, &alibres.get(MAKEINTRESOURCE(117), "PNG")); buttonClose->setTooltips("close button"); buttonClose->show(TRUE); pal.ar=frand()*100.f; pal.ag=frand()*100.f; pal.ab=frand()*100.f; pal.dr=(frand()+0.1f)*0.1f; pal.dg=(frand()+0.1f)*0.1f; pal.db=(frand()+0.1f)*0.1f; pal.ar0=frand()*100.f; pal.ag0=frand()*100.f; pal.ab0=frand()*100.f; pal.dr0=(frand()+0.1f)*0.09f; pal.dg0=(frand()+0.1f)*0.09f; pal.db0=(frand()+0.1f)*0.09f; pal.ar1=frand()*100.f; pal.ag1=frand()*100.f; pal.ab1=frand()*100.f; pal.dr1=(frand()+0.1f)*0.03f; pal.dg1=(frand()+0.1f)*0.03f; pal.db1=(frand()+0.1f)*0.03f; pal.ar10=frand()*100.f; pal.ag10=frand()*100.f; pal.ab10=frand()*100.f; pal.dr10=(frand()+0.1f)*0.01f; pal.dg10=(frand()+0.1f)*0.01f; pal.db10=(frand()+0.1f)*0.01f; pal.n=1.f/(frand()*512.f+16.f); zyg.zz1=5.f/(frand()*pos.w*10.f+(float)pos.w); zyg.zz2=5.f/(frand()*pos.w*10.f+(float)pos.w); zyg.zz3=5.f/(frand()*pos.w*10.f+(float)pos.w); zyg.ax1=frand()*100.f; zyg.ay1=frand()*100.f; zyg.ax2=frand()*100.f; zyg.ay2=frand()*100.f; zyg.ax3=frand()*100.f; zyg.ay3=frand()*100.f; zyg.dx1=(frand()+0.1f)*0.03f; zyg.dy1=(frand()+0.1f)*0.03f; zyg.dx2=(frand()+0.1f)*0.03f; zyg.dy2=(frand()+0.1f)*0.03f; zyg.dx3=(frand()+0.1f)*0.03f; zyg.dy3=(frand()+0.1f)*0.03f; menu=new AaboutMenu("about menu", this, 10, pos.h-110, pos.w-20, 100); menu->show(TRUE); hlp=new Abutton("help", this, 306, 120, 80, 16, "HELP"); hlp->setTooltips("help file"); hlp->show(true); web=new Abutton("web", this, 306, 140, 80, 16, "WEB"); web->setTooltips("aestesis web site"); web->show(true); reg=new Abutton("reg", this, 306, 160, 80, 16, "DONATE"); reg->setTooltips("donate"); reg->show(true); timer(100); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Aabout::~Aabout() { timer(0); delete(hlp); delete(web); delete(reg); delete(back); delete(title); delete(buttonClose); delete(menu); back=NULL; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Aabout::mouse(int x, int y, int state, int event) { switch(event) { case mouseLDOWN: wx=pos.x; wy=pos.y; lx=pos.x+x; ly=pos.y+y; bac=TRUE; mouseCapture(TRUE); return TRUE; case mouseNORMAL: if((state&mouseL)&&bac) move(wx+(x+pos.x)-lx, wy+(y+pos.y)-ly); return TRUE; case mouseLUP: bac=FALSE; mouseCapture(FALSE); return TRUE; case mouseRDOWN: destroy(); return TRUE; } return FALSE; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Aabout::notify(Anode *o, int event, dword p) { switch(event) { case nyCLICK: if(o==buttonClose) { destroy(); } else if(o==hlp) { char help[1024]; GetModuleFileName(GetModuleHandle(null), help, sizeof(help)); if(help[0]) { char *s=strrchr(help, '\\'); if(s) *s=0; } strcat(help, "\\help\\elektronika.chm"); ShellExecute(getWindow()->hw, "open", help, NULL, NULL, SW_SHOWNORMAL); } else if(o==web) { ShellExecute(getWindow()->hw, "open", "http://www.aestesis.eu/", NULL, NULL, SW_SHOWNORMAL); //httpto("http://www.aestesis.org/"); } else if(o==reg) { ShellExecute(getWindow()->hw, "open", "http://aestesis.eu/", NULL, NULL, SW_SHOWNORMAL); //httpto("http://www.aestesis.org/aestesis/register.php"); } break; } return Aobject::notify(o, event , p); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Aabout::paint(Abitmap *b) { b->set(0, 0, back, bitmapDEFAULT, bitmapDEFAULT); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Aabout::pulse() { if(back) { int x,y,i; dword palette[8192]; { float ar=pal.ar; float ag=pal.ag; float ab=pal.ab; float dr=pal.dr*0.1f; float dg=pal.dg*0.1f; float db=pal.db*0.1f; float ar0=pal.ar0; float ag0=pal.ag0; float ab0=pal.ab0; float dr0=pal.dr0*0.1f; float dg0=pal.dg0*0.1f; float db0=pal.db0*0.1f; float ar1=pal.ar1; float ag1=pal.ag1; float ab1=pal.ab1; float dr1=pal.dr1*0.1f; float dg1=pal.dg1*0.1f; float db1=pal.db1*0.1f; float ar10=pal.ar10; float ag10=pal.ag10; float ab10=pal.ab10; float dr10=pal.dr10*0.1f; float dg10=pal.dg10*0.1f; float db10=pal.db10*0.1f; float n=pal.n*0.1f; for(i=0; i<8192; i++) { float m=(float)sin(PI*(float)i*n)*0.4999f+0.5f; float vb=(float)(sin(PI*(float)i*0.01f)*0.5f+0.5f); byte r=(byte)(vb*((1.f-m)*((float)sin(ar1)*sin(ar10)*127.9f+128.f)+m*((float)sin(ar)*sin(ar0)*127.9f+128.f)))&255; byte g=(byte)(vb*((1.f-m)*((float)sin(ag1)*sin(ag10)*127.9f+128.f)+m*((float)sin(ag)*sin(ag0)*127.9f+128.f)))&255; byte b=0;//(byte)(vb*((1.f-m)*((float)sin(ab1)*sin(ab10)*127.9f+128.f)+m*((float)sin(ab)*sin(ab0)*127.9f+128.f)))&255; palette[i]=color32(r, g, b, 255); ar+=dr; ag+=dg; ab+=db; ar0+=dr0; ag0+=dg0; ab0+=db0; ar1+=dr1; ag1+=dg1; ab1+=db1; ar10+=dr10; ag10+=dg10; ab10+=db10; } pal.ar+=pal.dr*10.f; pal.ag+=pal.dg*10.f; pal.ab+=pal.db*10.f; pal.ar0+=pal.dr0*10.f; pal.ag0+=pal.dg0*10.f; pal.ab0+=pal.db0*10.f; pal.ar1+=pal.dr1*10.f; pal.ag1+=pal.dg1*10.f; pal.ab1+=pal.db1*10.f; pal.ar10+=pal.dr10*10.f; pal.ag10+=pal.dg10*10.f; pal.ab10+=pal.db10*10.f; } { dword *d=back->body32; float xx1=(float)sin(zyg.ax1)*pos.w; float yy1=(float)sin(zyg.ay1)*pos.h; float xx2=(float)sin(zyg.ax2)*pos.w; float yy2=(float)sin(zyg.ay2)*pos.h; float xx3=(float)sin(zyg.ax2)*pos.w; float yy3=(float)sin(zyg.ay2)*pos.h; zyg.ax1+=zyg.dx1; zyg.ay1+=zyg.dy1; zyg.ax2+=zyg.dx2; zyg.ay2+=zyg.dy2; zyg.ax3+=zyg.dx3; zyg.ay3+=zyg.dy3; for(y=0; y<pos.h; y++) { float dy1=(float)y-yy1; float dy2=(float)y-yy2; float dy3=(float)y-yy3; dy1*=dy1; dy2*=dy2; dy3*=dy3; for(x=0; x<pos.w; x++) { float dx1=(float)x-xx1; float dx2=(float)x-xx2; float dx3=(float)x-xx3; *(d++)=palette[(int)(((float)sin(sqrt(dx1*dx1+dy1)*zyg.zz1) + (float)sin(sqrt(dx2*dx2+dy2)*zyg.zz2) + (float)sin(sqrt(dx2*dx2+dy2)*zyg.zz2) ) * (4095.f/3.f)+ 4096.f )]; } } } back->boxfa(0,0,pos.w-1,pos.h-1,0xffffaa00,0.5f); back->boxa(0,0,pos.w-1, pos.h-1,0xff000000,0.8f); back->boxa(1,1,pos.w-2, pos.h-2,0xff000000,0.8f); back->boxa(2,2,pos.w-3, pos.h-3,0xff000000,0.8f); back->boxa(3,3,pos.w-4, pos.h-4,0xff000000,0.8f); back->boxa(4,4,pos.w-5, pos.h-5,0xff000000,0.8f); back->boxa(5,5,pos.w-6, pos.h-6,0xff000000,0.8f); { Afont *font=alib.getFont(fontCONFIDENTIAL14); font->set(back, 10, 70, "live version " VERSION, 0xffffffff); font->set(back, 10, pos.h-136, "aestesis 1991,2009", 0xffffffff); font->set(back, 10, pos.h-176, "software developer YoY", 0xff000000); font->set(back, 10, pos.h-156, "(CC) RENAN JEGOUZO", 0xff808080); } repaint(); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
30.056893
174
0.39684
aestesis
0cb2df04b700296df273dae8ab674ba28ea8bd3d
8,791
cpp
C++
SystemInfo.cpp
knela96/Game-Engine
06659d933c4447bd8d6c8536af292825ce4c2ab1
[ "Unlicense" ]
1
2019-11-16T22:01:56.000Z
2019-11-16T22:01:56.000Z
SystemInfo.cpp
knela96/Game-Engine
06659d933c4447bd8d6c8536af292825ce4c2ab1
[ "Unlicense" ]
null
null
null
SystemInfo.cpp
knela96/Game-Engine
06659d933c4447bd8d6c8536af292825ce4c2ab1
[ "Unlicense" ]
null
null
null
#include"SystemInfo.h" namespace Engine { static sMStats MemoryStats_MMRG; void RecalculateMemStatisticsFromMMGR() { MemoryStats_MMRG = m_getMemoryStatistics(); } SystemInfo::SystemInfo() { mSoftware_Info.DetectSystemProperties(); mHardware_MemoryInfo.DetectSystemProperties(); mHardware_GPUInfo.DetectSystemProperties(); mHardware_CPUInfo.DetectSystemProperties(); } void SoftwareInfo::DetectSystemProperties() { mSoftware_CppVersion = ExtractCppVersion(__cplusplus); mSoftware_WindowsVersion = ExtractWindowsVersion(); mSoftware_SDLVersion = ExtractSDLVersion(); } const std::string SoftwareInfo::ExtractCppVersion(long int cppValue) { std::string tmp_cppVersion = "NULL: return value does not match with any C++ version!"; switch (cppValue) { case(199711L): tmp_cppVersion = "C++ 98 or C++03"; break; case(201103L): tmp_cppVersion = "C++11"; break; case(201402L): tmp_cppVersion = "C++14"; break; case(201703L): tmp_cppVersion = "C++17"; break; default: tmp_cppVersion = "NULL: return value does not match with any C++ version!"; break; } return tmp_cppVersion; } const std::string SoftwareInfo::ExtractWindowsVersion() { OSVERSIONINFOEX OS; ZeroMemory(&OS, sizeof(OSVERSIONINFOEX)); OS.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); GetVersionEx(&(OSVERSIONINFO&)OS); std::string ret = "Windows "; if (OS.dwMajorVersion == 10) ret += "10"; else if (OS.dwMajorVersion == 6) { if (OS.dwMinorVersion == 3) ret += "8.1"; else if (OS.dwMinorVersion == 2) ret += "8"; else if (OS.dwMinorVersion == 1) ret += "7"; else ret += "Vista"; } else if (OS.dwMajorVersion == 5) { if (OS.dwMinorVersion == 2) ret += "XP SP2"; else if (OS.dwMinorVersion == 1) ret += "XP"; else if (OS.dwMinorVersion == 0) ret += "2000"; } else if (OS.dwMajorVersion == 4 || OS.dwMajorVersion == 3) ret += "WinNT"; else ret = "WINDOWS VERSION NOT FOUND"; return ret; } const std::string SoftwareInfo::ExtractSDLVersion() { SDL_version linked; SDL_version compiled; SDL_VERSION(&compiled); SDL_GetVersion(&linked); std::string VersionString = "SDL Compiled Version " + std::to_string(compiled.major) + std::to_string(compiled.minor) + std::to_string(compiled.patch); VersionString += ("\nSDL Linked Version " + std::to_string(linked.major) + std::to_string(linked.minor) + std::to_string(linked.patch)); return VersionString; } const std::string SoftwareInfo::GetCppCompilerVersion() { return (std::to_string(_MSVC_LANG) + " (" + ExtractCppVersion(_MSVC_LANG) + ")"); } void MemoryHardware::DetectSystemProperties() { ExtractMemoryInfo(); RecalculateMemStatisticsFromMMGR(); } void MemoryHardware::ExtractMemoryInfo() const { MEMORYSTATUSEX tmpMemoryInfo; tmpMemoryInfo.dwLength = sizeof(MEMORYSTATUSEX); GlobalMemoryStatusEx(&tmpMemoryInfo); m_MemoryInfo = tmpMemoryInfo; m_MemoryInfo.dwLength = sizeof(MEMORYSTATUSEX); GetProcessMemoryInfo(GetCurrentProcess(), &m_ProcessMemCounters, sizeof(m_ProcessMemCounters)); mProcess_vMemUsed = m_ProcessMemCounters.PagefileUsage; mProcess_physMemUsed = m_ProcessMemCounters.WorkingSetSize; } void MemoryHardware::RecalculateRAMParameters() { DetectSystemProperties(); } //Getting Stats of Memory from MMRG const uint MemoryHardware::GetMemStatsFromMMGR_TotalReportedMemory() const { return MemoryStats_MMRG.totalReportedMemory; } const uint MemoryHardware::GetMemStatsFromMMGR_TotalActualMemory() const { return MemoryStats_MMRG.totalActualMemory; } const uint MemoryHardware::GetMemStatsFromMMGR_PeakReportedMemory() const { return MemoryStats_MMRG.peakReportedMemory; } const uint MemoryHardware::GetMemStatsFromMMGR_PeakActualMemory() const { return MemoryStats_MMRG.peakActualMemory; } const uint MemoryHardware::GetMemStatsFromMMGR_AccumulatedReportedMemory() const { return MemoryStats_MMRG.accumulatedReportedMemory; } const uint MemoryHardware::GetMemStatsFromMMGR_AccumulatedActualMemory() const { return MemoryStats_MMRG.accumulatedActualMemory; } const uint MemoryHardware::GetMemStatsFromMMGR_AccumulatedAllocUnitCount() const { return MemoryStats_MMRG.accumulatedAllocUnitCount; } const uint MemoryHardware::GetMemStatsFromMMGR_TotalAllocUnitCount() const { return MemoryStats_MMRG.totalAllocUnitCount; } const uint MemoryHardware::GetMemStatsFromMMGR_PeakAllocUnitCount() const { return MemoryStats_MMRG.peakAllocUnitCount; } void GPUHardware::DetectSystemProperties() { GetGPUTotalVRAM(); GetGPUCurrentVRAM(); GPUDetect_ExtractGPUInfo(); } const int GPUHardware::GetGPUTotalVRAM() { /*int tmp_GPUTotalVRAM = 0; glGetIntegerv(0x9048, &tmp_GPUTotalVRAM); m_GPUTotalVRAM = tmp_GPUTotalVRAM;*/ //return m_GPUTotalVRAM / KBTOMB; return m_PI_GPUDet_GPUInfo.mPI_GPUDet_TotalVRAM_MB; } const int GPUHardware::GetGPUCurrentVRAM() { int tmp_GPUCurrentVRAM = 0; glGetIntegerv(0x9049, &tmp_GPUCurrentVRAM); m_GPUCurrentVRAM = tmp_GPUCurrentVRAM; return tmp_GPUCurrentVRAM / KBTOMB; } void GPUHardware::GPUDetect_ExtractGPUInfo() const { GPUPrimaryInfo_IntelGPUDetect tmp; std::wstring tmp_GPUBrand_WString; if (getGraphicsDeviceInfo(&tmp.m_GPUVendor, &tmp.m_GPUID, &tmp_GPUBrand_WString, &tmp.mPI_GPUDet_TotalVRAM_Bytes, &tmp.mPI_GPUDet_VRAMUsage_Bytes, &tmp.mPI_GPUDet_CurrentVRAM_Bytes, &tmp.mPI_GPUDet_VRAMReserved_Bytes)) { //Converting the WSTRING variable into a std::string std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; tmp.m_GPUBrand = converter.to_bytes(tmp_GPUBrand_WString); //If you prefer that in a char[] variable type, use: //sprintf_s(char[], char[] size, "%S", tmp_GPUBrand_WString.c_str()); tmp.mPI_GPUDet_TotalVRAM_MB = tmp.mPI_GPUDet_TotalVRAM_Bytes / BTOMB; tmp.mPI_GPUDet_VRAMUsage_MB = tmp.mPI_GPUDet_VRAMUsage_Bytes / BTOMB; tmp.mPI_GPUDet_CurrentVRAM_MB = tmp.mPI_GPUDet_CurrentVRAM_Bytes / BTOMB; tmp.mPI_GPUDet_VRAMReserved_MB = tmp.mPI_GPUDet_VRAMReserved_Bytes / BTOMB; m_PI_GPUDet_GPUInfo = tmp; } } void ProcessorHardware::DetectSystemProperties() { GetCPUSystemInfo(); CheckForCPUInstructionsSet(); } void ProcessorHardware::GetCPUSystemInfo() { GetSystemInfo(&m_CpuSysInfo); m_CpuArchitecture = ExtractCPUArchitecture(m_CpuSysInfo); getCPUInfo(&m_CPUBrand, &m_CPUVendor); } const std::string ProcessorHardware::ExtractCPUArchitecture(SYSTEM_INFO& SystemInfo) { std::string ret = "Unknown Architecture"; switch (SystemInfo.wProcessorArchitecture) { case(PROCESSOR_ARCHITECTURE_AMD64): ret = "x64 (AMD or Intel)"; break; case(PROCESSOR_ARCHITECTURE_ARM): ret = "ARM"; break; case(PROCESSOR_ARCHITECTURE_ARM64): ret = "ARM64"; break; case(PROCESSOR_ARCHITECTURE_IA64): ret = "Intel Itanium-based"; break; case(PROCESSOR_ARCHITECTURE_INTEL): ret = "x86"; break; case(PROCESSOR_ARCHITECTURE_UNKNOWN): ret = "Unknown architecture"; break; default: ret = "Unknown architecture"; break; } return ret; } void ProcessorHardware::CheckForCPUInstructionsSet() { if (SDL_Has3DNow() == true) m_CPUInstructionSet.Available_3DNow = true; if (SDL_HasRDTSC() == true) m_CPUInstructionSet.RDTSC_Available = true; if (SDL_HasAltiVec() == true) m_CPUInstructionSet.AltiVec_Available = true; if (SDL_HasAVX() == true) m_CPUInstructionSet.AVX_Available = true; if (SDL_HasAVX2() == true) m_CPUInstructionSet.AVX2_Available = true; if (SDL_HasMMX() == true) m_CPUInstructionSet.MMX_Available = true; if (SDL_HasSSE() == true) m_CPUInstructionSet.SSE_Available = true; if (SDL_HasSSE2() == true) m_CPUInstructionSet.SSE2_Available = true; if (SDL_HasSSE3() == true) m_CPUInstructionSet.SSE3_Available = true; if (SDL_HasSSE41() == true) m_CPUInstructionSet.SSE41_Available = true; if (SDL_HasSSE42() == true) m_CPUInstructionSet.SSE42_Available = true; } const std::string ProcessorHardware::GetCPUInstructionSet() const { std::string ret = ""; InstructionsSet is = m_CPUInstructionSet; if (is.Available_3DNow == true) ret += "3DNOW, "; if (is.RDTSC_Available == true) ret += "RDTSC, "; if (is.AltiVec_Available == true) ret += "AltiVec, "; if (is.AVX_Available == true) ret += "AVX, "; if (is.AVX2_Available == true) ret += "AVX2, "; if (is.MMX_Available == true) ret += "MMX, "; if (is.SSE_Available == true) ret += "SSE, "; if (is.SSE2_Available == true) ret += "SSE2, "; if (is.SSE3_Available == true) ret += "SSE3, "; if (is.SSE41_Available == true) ret += "SSE41, "; if (is.SSE42_Available == true) ret += "SSE42, "; ret += '\n'; return ret; } }
27.216718
220
0.730747
knela96
0cb450c25568097ae662d51a102af867ce5a9270
902
cpp
C++
BkZOOLib/bkzoo/util/StringUtil.cpp
yoichibeer/BkZOO
3ec97b6d34d0815063ca9d829e452771327101ff
[ "MIT" ]
null
null
null
BkZOOLib/bkzoo/util/StringUtil.cpp
yoichibeer/BkZOO
3ec97b6d34d0815063ca9d829e452771327101ff
[ "MIT" ]
null
null
null
BkZOOLib/bkzoo/util/StringUtil.cpp
yoichibeer/BkZOO
3ec97b6d34d0815063ca9d829e452771327101ff
[ "MIT" ]
null
null
null
/* * BkZOO! * * Copyright 2011-2017 yoichibeer. * Released under the MIT license. */ #include "StringUtil.h" #include <sstream> #include <ctime> using namespace bkzoo; namespace bkzoo { namespace util { std::string stringFromTime() { const time_t now = time(nullptr); const struct tm *pnow = localtime(&now); const int year = pnow->tm_year + 1900; /* 1900 - */ const int month = pnow->tm_mon + 1; /* 0-11 */ const int day = pnow->tm_mday + 1; /* 0-30 */ const int hour = pnow->tm_hour; /* 0-23 */ const int min = pnow->tm_min; /* 0-59 */ const int sec = pnow->tm_sec; /* 0-59 */ std::ostringstream oss; oss << year << "." << month << "." << day << "." << hour << "." << min << "." << sec; return oss.str(); } } }
22.55
97
0.486696
yoichibeer
0cb9b423042546198ac82f0c23a68e8773e7a9cb
134
cpp
C++
WYMIANA - Zamiana miejsc/WYMIANA - Zamiana miejsc/main.cpp
wdsking/PolskiSpoj
aaa1128b0499f4e4e46405ff3ef2beec0127d0c0
[ "MIT" ]
null
null
null
WYMIANA - Zamiana miejsc/WYMIANA - Zamiana miejsc/main.cpp
wdsking/PolskiSpoj
aaa1128b0499f4e4e46405ff3ef2beec0127d0c0
[ "MIT" ]
null
null
null
WYMIANA - Zamiana miejsc/WYMIANA - Zamiana miejsc/main.cpp
wdsking/PolskiSpoj
aaa1128b0499f4e4e46405ff3ef2beec0127d0c0
[ "MIT" ]
2
2019-04-16T20:05:44.000Z
2020-11-15T11:44:30.000Z
#include<stdio.h> int main() { int x, y; scanf("%d %d", &x, &y); x += y; y = x - y; x -= y; printf("%d %d", x, y); return 0; }
11.166667
24
0.432836
wdsking
0cbbf656e6d6e3b7e62906f2259f976844885010
1,356
cpp
C++
include/MenuItemSDUpdater.cpp
beNative/M5Stack-Concepts
dfebc3d633bc4519021b15371e69c4a76e5cef65
[ "Apache-2.0" ]
null
null
null
include/MenuItemSDUpdater.cpp
beNative/M5Stack-Concepts
dfebc3d633bc4519021b15371e69c4a76e5cef65
[ "Apache-2.0" ]
null
null
null
include/MenuItemSDUpdater.cpp
beNative/M5Stack-Concepts
dfebc3d633bc4519021b15371e69c4a76e5cef65
[ "Apache-2.0" ]
1
2021-02-28T08:45:20.000Z
2021-02-28T08:45:20.000Z
#include "MenuItemSDUpdater.h" #include <M5StackUpdater.h> // https://github.com/tobozo/M5Stack-SD-Updater/ #include <SD.h> #undef min #include <algorithm> static SDUpdater sdUpdater; void MenuItemSDUpdater::onEnter() { if (!name.length()) { // SDのルートフォルダから *.bin ファイルを探す。 deleteItems(); SD.begin(); File root = SD.open("/"); File file = root.openNextFile(); MenuItemSDUpdater* mi; while (file) { if (!file.isDirectory()) { String name = file.name(); int idx = name.lastIndexOf('.'); String ext = name.substring(idx + 1); if (ext == "bin") { name = name.substring(1, idx); mi = new MenuItemSDUpdater(name, name); addItem(mi); } } file = root.openNextFile(); std::sort(Items.begin(), Items.end(), compareIgnoreCase); } root.close(); } else { // 選択されたbinファイルでupdateを実行する。 String bin = "/" + name + ".bin"; sdUpdater.updateFromFS(SD, bin); ESP.restart(); } MenuItem::onEnter(); } void MenuItemSDUpdater::onFocus() { String filename = "/jpg/" + name + ".jpg"; if (SD.exists(filename.c_str())) { M5.Lcd.drawJpgFile(SD, filename.c_str(), 200, 40); } } void MenuItemSDUpdater::onDefocus() { M5.Lcd.fillRect(200, 30, 120, 140, backgroundColor); } void MenuItemSDUpdater::onAfterDraw() { }
23.789474
78
0.601032
beNative
0cbcba69300f9ba57f4ccd06e03054f74079fc93
11,275
hpp
C++
libformula/Headers/formula/Scanner.hpp
purefunsolutions/ember-plus
d022732f2533ad697238c6b5210d7fc3eb231bfc
[ "BSL-1.0" ]
78
2015-07-31T14:46:38.000Z
2022-03-28T09:28:28.000Z
libformula/Headers/formula/Scanner.hpp
purefunsolutions/ember-plus
d022732f2533ad697238c6b5210d7fc3eb231bfc
[ "BSL-1.0" ]
81
2015-08-03T07:58:19.000Z
2022-02-28T16:21:19.000Z
libformula/Headers/formula/Scanner.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_SCANNER_HPP #define __LIBFORMULA_SCANNER_HPP #include <string> #include <cstring> #include "ErrorStack.hpp" #include "Symbol.hpp" namespace libformula { /** * The Scanner is iterating through the term string and identifies the single tokens which * are used for parsing in the second pass. */ template<typename InputIterator> class Scanner { typedef std::vector<Symbol<InputIterator> > SymbolContainerT; public: typedef typename SymbolContainerT::value_type value_type; typedef typename SymbolContainerT::size_type size_type; typedef typename SymbolContainerT::const_iterator const_iterator; typedef typename SymbolContainerT::reference reference; typedef typename SymbolContainerT::const_reference const_reference; typedef InputIterator input_type; /** * Initializes a new scanner which immediately scans the provided term. * @param first Pointer to the first character in the term buffer. * @param last Points to the first item beyond the term to scan. * @param error Pointer to the error stack, where all detected errors are logged. * @note Note that the provided buffer must exist as long as the scanner instance * is alive! */ Scanner(InputIterator first, InputIterator last, ErrorStack *error); /** * Returns the number of tokens identified and created by the scanner. */ size_type size() const; /** * Returns an iterator that points to the first symbol created by the scanner. * @return An iterator that points to the first symbol created by the scanner. */ const_iterator begin() const; /** * Returns the iterator that points to the first location beyond the symbol buffer. * @return The iterator that points to the first location beyond the symbol buffer. */ const_iterator end() const; private: /** * Inserts a symbol to the internal symbol buffer. * @param symbol The symbol to add. */ void push(const_reference symbol); /** * Scans a single character symbol and adds the identifies symbol into the buffer. * @param first Current character. * @param last End of the provided term string. * @param error Error stack. */ InputIterator scanSingleCharSymbol(InputIterator first, InputIterator last, ErrorStack *error); /** * Tries to identify a symbol that consists of several characters, like a number or a function call. * @param first Current character. * @param last End of the provided term string. * @param error Error stack. */ InputIterator scanMultiCharSymbol(InputIterator first, InputIterator last, ErrorStack *error); /** * Tries to match the current input to a function and inserts the symbol to the buffer. * @param first Current character. * @param last End of the provided term string. * @param error Error stack. */ InputIterator scanFunction(InputIterator first, InputIterator last, ErrorStack *error); /** * Parses a number. * @param first Current character. * @param last End of the provided term string. * @param error Error stack. */ InputIterator scanNumber(InputIterator first, InputIterator last, ErrorStack *error); private: SymbolContainerT m_symbols; }; /************************************************************************** * Inline implementation * **************************************************************************/ template<typename InputIterator> inline Scanner<InputIterator>::Scanner(InputIterator first, InputIterator last, ErrorStack *error) { while(first != last && isspace(*first)) ++first; for( ; first != last; ) { switch(*first) { case SymbolType::It: case SymbolType::Divide: case SymbolType::LParen: case SymbolType::Minus: case SymbolType::Modulo: case SymbolType::Multiply: case SymbolType::Plus: case SymbolType::Pow: case SymbolType::RParen: case SymbolType::Comma: first = scanSingleCharSymbol(first, last, error); break; default: first = scanMultiCharSymbol(first, last, error); break; } while(first != last && isspace(*first)) ++first; } push(value_type(SymbolType::EndOfFile, size(), last, last)); } template<typename InputIterator> inline typename Scanner<InputIterator>::size_type Scanner<InputIterator>::size() const { return m_symbols.size(); } template<typename InputIterator> inline typename Scanner<InputIterator>::const_iterator Scanner<InputIterator>::begin() const { return m_symbols.begin(); } template<typename InputIterator> inline typename Scanner<InputIterator>::const_iterator Scanner<InputIterator>::end() const { return m_symbols.end(); } template<typename InputIterator> inline InputIterator Scanner<InputIterator>::scanSingleCharSymbol(InputIterator first, InputIterator last, ErrorStack *error) { push(value_type(static_cast<SymbolType::_Domain>(*first), size(), first, first + 1)); return ++first; } template<typename InputIterator> inline InputIterator Scanner<InputIterator>::scanMultiCharSymbol(InputIterator first, InputIterator last, ErrorStack *error) { if (::isalpha(*first)) { return scanFunction(first, last, error); } else if (::isdigit(*first)) { return scanNumber(first, last, error); } else { error->push(ErrorType::UnknownToken, "Unknown token"); return last; } } template<typename InputIterator> inline InputIterator Scanner<InputIterator>::scanFunction(InputIterator first, InputIterator last, ErrorStack *error) { typedef typename std::iterator_traits<InputIterator>::value_type type; type buffer[32]; auto cursor = &buffer[0]; auto it = first; while(it != last && ::isalpha(*it)) { *cursor++ = ::tolower(*it++); } *cursor = 0; if (strncmp(buffer, "sqrt", 4) == 0) push(value_type(SymbolType::Sqrt, size(), first, it)); else if (strncmp(buffer, "log", 3) == 0) push(value_type(SymbolType::Log, size(), first, it)); else if (strncmp(buffer, "ln", 2) == 0) push(value_type(SymbolType::Ln, size(), first, it)); else if (strncmp(buffer, "round", 5) == 0) push(value_type(SymbolType::Round, size(), first, it)); else if (strncmp(buffer, "ceil", 4) == 0) push(value_type(SymbolType::Ceil, size(), first, it)); else if (strncmp(buffer, "int", 3) == 0) push(value_type(SymbolType::Int, size(), first, it)); else if (strncmp(buffer, "float", 5) == 0) push(value_type(SymbolType::Float, size(), first, it)); else if (strncmp(buffer, "exp", 3) == 0) push(value_type(SymbolType::Exp, size(), first, it)); else if (strncmp(buffer, "sinh", 4) == 0) push(value_type(SymbolType::Sinh, size(), first, it)); else if (strncmp(buffer, "sin", 3) == 0) push(value_type(SymbolType::Sin, size(), first, it)); else if (strncmp(buffer, "cosh", 4) == 0) push(value_type(SymbolType::Cosh, size(), first, it)); else if (strncmp(buffer, "cos", 3) == 0) push(value_type(SymbolType::Cos, size(), first, it)); else if (strncmp(buffer, "tanh", 4) == 0) push(value_type(SymbolType::Tanh, size(), first, it)); else if (strncmp(buffer, "tan", 3) == 0) push(value_type(SymbolType::Tan, size(), first, it)); else if (strncmp(buffer, "atan", 4) == 0) push(value_type(SymbolType::Atan, size(), first, it)); else if (strncmp(buffer, "acos", 4) == 0) push(value_type(SymbolType::Acos, size(), first, it)); else if (strncmp(buffer, "asin", 4) == 0) push(value_type(SymbolType::Asin, size(), first, it)); else if (strncmp(buffer, "pi", 2) == 0) push(value_type(SymbolType::Pi, size(), first, it)); else if (strncmp(buffer, "e", 1) == 0) push(value_type(SymbolType::E, size(), first, it)); else if (strncmp(buffer, "abs", 3) == 0) push(value_type(SymbolType::Abs, size(), first, it)); else if (strncmp(buffer, "sgn", 3) == 0) push(value_type(SymbolType::Sgn, size(), first, it)); else { error->push(ErrorType::UnknownFunction, buffer); return last; } return it; } template<typename InputIterator> inline InputIterator Scanner<InputIterator>::scanNumber(InputIterator first, InputIterator last, ErrorStack *error) { auto it = first; auto exponents = 0; auto operators = 0; auto dots = 0; while(it != last && exponents < 2 && operators < 2 && dots < 2) { if (*it == 'E' || *it == 'e') ++exponents; else if (dots > 0 && (*it == '+' || *it == '-')) ++operators; else if (*it == '.') ++dots; else if (::isdigit(*it) == 0) break; ++it; } auto const invalid = !(exponents < 2 && dots < 2 && operators < 2); if (invalid == false) { if (dots == 0 && exponents == 0 && operators == 0) { push(value_type(SymbolType::IntegerValue, size(), first, it)); } else { push(value_type(SymbolType::RealValue, size(), first, it)); } return it; } else { error->push(ErrorType::TokenIsNotAValidNumber, std::string(first, it)); return last; } } template<typename InputIterator> inline void Scanner<InputIterator>::push(const_reference symbol) { m_symbols.push_back(symbol); } } #endif // __LIBFORMULA_SCANNER_HPP
37.70903
129
0.555565
purefunsolutions
0cc1da7e2deb9cfc343c619d6ff1ea29c40318e2
10,464
tcc
C++
include/dart/packet/object.tcc
Cfretz244/libdart
987b01aa1f11455ac6aaf89f8e60825e92e6ec25
[ "Apache-2.0" ]
85
2019-05-09T19:12:25.000Z
2021-02-07T16:31:55.000Z
include/dart/packet/object.tcc
Cfretz244/libdart
987b01aa1f11455ac6aaf89f8e60825e92e6ec25
[ "Apache-2.0" ]
10
2019-05-09T22:37:27.000Z
2020-03-29T03:25:16.000Z
include/dart/packet/object.tcc
Cfretz244/libdart
987b01aa1f11455ac6aaf89f8e60825e92e6ec25
[ "Apache-2.0" ]
10
2019-05-11T08:05:10.000Z
2020-06-11T11:05:17.000Z
#ifndef DART_PACKET_OBJECT_H #define DART_PACKET_OBJECT_H /*----- Project Includes -----*/ #include "../common.h" /*----- Function Implementations -----*/ namespace dart { template <template <class> class RefCount> template <class... Args, class EnableIf> basic_packet<RefCount> basic_packet<RefCount>::make_object(Args&&... pairs) { return basic_heap<RefCount>::make_object(std::forward<Args>(pairs)...); } template <template <class> class RefCount> template <bool enabled, class EnableIf> basic_packet<RefCount> basic_packet<RefCount>::make_object(gsl::span<basic_heap<RefCount> const> pairs) { return basic_heap<RefCount>::make_object(pairs); } template <template <class> class RefCount> template <bool enabled, class EnableIf> basic_packet<RefCount> basic_packet<RefCount>::make_object(gsl::span<basic_buffer<RefCount> const> pairs) { return basic_heap<RefCount>::make_object(pairs); } template <template <class> class RefCount> template <bool enabled, class EnableIf> basic_packet<RefCount> basic_packet<RefCount>::make_object(gsl::span<basic_packet const> pairs) { return basic_heap<RefCount>::make_object(pairs); } template <template <class> class RefCount> template <class KeyType, class ValueType, class EnableIf> basic_packet<RefCount>& basic_packet<RefCount>::add_field(KeyType&& key, ValueType&& value) & { get_heap().add_field(std::forward<KeyType>(key), std::forward<ValueType>(value)); return *this; } template <template <class> class RefCount> template <class KeyType, class ValueType, class EnableIf> basic_packet<RefCount>&& basic_packet<RefCount>::add_field(KeyType&& key, ValueType&& value) && { add_field(std::forward<KeyType>(key), std::forward<ValueType>(value)); return std::move(*this); } template <template <class> class RefCount> template <bool enabled, class EnableIf> basic_packet<RefCount>& basic_packet<RefCount>::remove_field(shim::string_view key) & { erase(key); return *this; } template <template <class> class RefCount> template <bool enabled, class EnableIf> basic_packet<RefCount>&& basic_packet<RefCount>::remove_field(shim::string_view key) && { remove_field(key); return std::move(*this); } template <template <class> class RefCount> template <class KeyType, class EnableIf> basic_packet<RefCount>& basic_packet<RefCount>::remove_field(KeyType const& key) & { erase(key.strv()); return *this; } template <template <class> class RefCount> template <class KeyType, class EnableIf> basic_packet<RefCount>&& basic_packet<RefCount>::remove_field(KeyType const& key) && { remove_field(key); return std::move(*this); } template <template <class> class RefCount> template <class String, bool enabled, class EnableIf> auto basic_packet<RefCount>::erase(basic_string<String> const& key) -> iterator { return erase(key.strv()); } template <template <class> class RefCount> template <bool enabled, class EnableIf> auto basic_packet<RefCount>::erase(shim::string_view key) -> iterator { return get_heap().erase(key); } template <template <class> class RefCount> template <class... Args, class EnableIf> basic_packet<RefCount> basic_packet<RefCount>::inject(Args&&... pairs) const { return shim::visit([&] (auto& v) -> basic_packet { return v.inject(std::forward<Args>(pairs)...); }, impl); } template <template <class> class RefCount> template <bool enabled, class EnableIf> basic_packet<RefCount> basic_packet<RefCount>::inject(gsl::span<basic_heap<RefCount> const> pairs) const { return shim::visit([&] (auto& v) -> basic_packet { return v.inject(pairs); }, impl); } template <template <class> class RefCount> template <bool enabled, class EnableIf> basic_packet<RefCount> basic_packet<RefCount>::inject(gsl::span<basic_buffer<RefCount> const> pairs) const { return shim::visit([&] (auto& v) -> basic_packet { return v.inject(pairs); }, impl); } template <template <class> class RefCount> template <bool enabled, class EnableIf> basic_packet<RefCount> basic_packet<RefCount>::inject(gsl::span<basic_packet const> pairs) const { return shim::visit([&] (auto& v) -> basic_packet { return v.inject(pairs); }, impl); } template <template <class> class RefCount> template <bool enabled, class EnableIf> basic_packet<RefCount> basic_packet<RefCount>::project(std::initializer_list<shim::string_view> keys) const { return shim::visit([&] (auto& v) -> basic_packet { return v.project(keys); }, impl); } template <template <class> class RefCount> template <bool enabled, class EnableIf> basic_packet<RefCount> basic_packet<RefCount>::project(gsl::span<std::string const> keys) const { return shim::visit([&] (auto& v) -> basic_packet { return v.project(keys); }, impl); } template <template <class> class RefCount> template <bool enabled, class EnableIf> basic_packet<RefCount> basic_packet<RefCount>::project(gsl::span<shim::string_view const> keys) const { return shim::visit([&] (auto& v) -> basic_packet { return v.project(keys); }, impl); } template <template <class> class RefCount> template <class String> basic_packet<RefCount> basic_packet<RefCount>::operator [](basic_string<String> const& key) const& { return (*this)[key.strv()]; } template <template <class> class RefCount> template <class String, bool enabled, class EnableIf> basic_packet<RefCount>&& basic_packet<RefCount>::operator [](basic_string<String> const& key) && { return std::move(*this)[key.strv()]; } template <template <class> class RefCount> basic_packet<RefCount> basic_packet<RefCount>::operator [](shim::string_view key) const& { return get(key); } template <template <class> class RefCount> template <bool enabled, class EnableIf> basic_packet<RefCount>&& basic_packet<RefCount>::operator [](shim::string_view key) && { return std::move(*this).get(key); } template <template <class> class RefCount> template <class String> basic_packet<RefCount> basic_packet<RefCount>::get(basic_string<String> const& key) const& { return get(key.strv()); } template <template <class> class RefCount> template <class String, bool enabled, class EnableIf> basic_packet<RefCount>&& basic_packet<RefCount>::get(basic_string<String> const& key) && { return std::move(*this).get(key.strv()); } template <template <class> class RefCount> basic_packet<RefCount> basic_packet<RefCount>::get(shim::string_view key) const& { return shim::visit([&] (auto& v) -> basic_packet { return v.get(key); }, impl); } template <template <class> class RefCount> template <bool enabled, class EnableIf> basic_packet<RefCount>&& basic_packet<RefCount>::get(shim::string_view key) && { shim::visit([&] (auto& v) { v = std::move(v).get(key); }, impl); return std::move(*this); } template <template <class> class RefCount> template <class String, class T, class EnableIf> basic_packet<RefCount> basic_packet<RefCount>::get_or(basic_string<String> const& key, T&& opt) const { return get_or(key.strv(), std::forward<T>(opt)); } template <template <class> class RefCount> template <class T, class EnableIf> basic_packet<RefCount> basic_packet<RefCount>::get_or(shim::string_view key, T&& opt) const { if (is_object() && has_key(key)) return get(key); else return convert::cast<basic_packet>(std::forward<T>(opt)); } template <template <class> class RefCount> basic_packet<RefCount> basic_packet<RefCount>::get_nested(shim::string_view path, char separator) const { return shim::visit([&] (auto& v) -> basic_packet { return v.get_nested(path, separator); }, impl); } template <template <class> class RefCount> template <class String> basic_packet<RefCount> basic_packet<RefCount>::at(basic_string<String> const& key) const& { return at(key.strv()); } template <template <class> class RefCount> template <class String, bool enabled, class EnableIf> basic_packet<RefCount>&& basic_packet<RefCount>::at(basic_string<String> const& key) && { return std::move(*this).at(key.strv()); } template <template <class> class RefCount> basic_packet<RefCount> basic_packet<RefCount>::at(shim::string_view key) const& { return shim::visit([&] (auto& v) -> basic_packet { return v.at(key); }, impl); } template <template <class> class RefCount> template <bool enabled, class EnableIf> basic_packet<RefCount>&& basic_packet<RefCount>::at(shim::string_view key) && { shim::visit([&] (auto& v) { v = std::move(v).at(key); }, impl); return std::move(*this); } template <template <class> class RefCount> template <class String> auto basic_packet<RefCount>::find(basic_string<String> const& key) const -> iterator { return find(key.strv()); } template <template <class> class RefCount> auto basic_packet<RefCount>::find(shim::string_view key) const -> iterator { return shim::visit([&] (auto& v) -> iterator { return v.find(key); }, impl); } template <template <class> class RefCount> template <class String> auto basic_packet<RefCount>::find_key(basic_string<String> const& key) const -> iterator { return find_key(key.strv()); } template <template <class> class RefCount> auto basic_packet<RefCount>::find_key(shim::string_view key) const -> iterator { return shim::visit([&] (auto& v) -> iterator { return v.find_key(key); }, impl); } template <template <class> class RefCount> std::vector<basic_packet<RefCount>> basic_packet<RefCount>::keys() const { std::vector<basic_packet> packets; packets.reserve(size()); shim::visit([&] (auto& v) { for (auto& k : v.keys()) packets.push_back(std::move(k)); }, impl); return packets; } template <template <class> class RefCount> template <class String> bool basic_packet<RefCount>::has_key(basic_string<String> const& key) const { return has_key(key.strv()); } template <template <class> class RefCount> bool basic_packet<RefCount>::has_key(shim::string_view key) const { return shim::visit([&] (auto& v) { return v.has_key(key); }, impl); } template <template <class> class RefCount> template <class KeyType, class EnableIf> bool basic_packet<RefCount>::has_key(KeyType const& key) const { if (key.get_type() == type::string) return has_key(key.strv()); else return false; } } #endif
38.189781
111
0.702886
Cfretz244
0cce115e7afb2e0f655c679e6a034ad18d19933f
4,093
cpp
C++
Old/mp3streamer_Plugin/cmpegaudiostreamdecoder.cpp
Harteex/Tuniac
dac98a68c1b801b7fc82874aad16cc8adcabb606
[ "BSD-3-Clause" ]
3
2022-01-05T08:47:51.000Z
2022-01-06T12:42:18.000Z
Old/mp3streamer_Plugin/cmpegaudiostreamdecoder.cpp
Harteex/Tuniac
dac98a68c1b801b7fc82874aad16cc8adcabb606
[ "BSD-3-Clause" ]
null
null
null
Old/mp3streamer_Plugin/cmpegaudiostreamdecoder.cpp
Harteex/Tuniac
dac98a68c1b801b7fc82874aad16cc8adcabb606
[ "BSD-3-Clause" ]
1
2022-01-06T16:12:58.000Z
2022-01-06T16:12:58.000Z
/* * CMpegAudioDecoder.cpp * audioenginetest * * Created by Tony Million on 24/11/2009. * Copyright 2009 Tony Million. All rights reserved. * */ #include "generaldefs.h" #include "cmpegaudiostreamdecoder.h" #include "stdlib.h" #include "stdio.h" #include "mpegdecoder.h" #define FRAMES_FLAG 0x0001 #define BYTES_FLAG 0x0002 #define TOC_FLAG 0x0004 #define VBR_SCALE_FLAG 0x0008 void CMpegAudioDecoder::Destroy(void) { #ifdef DEBUG_DESTROY printf("CMpegAudioDecoder::Destroy(this) == %p\n", this); #endif delete this; } bool CMpegAudioDecoder::SetState(unsigned long State) { return(true); } bool CMpegAudioDecoder::GetLength(unsigned long * MS) { *MS = ((float)m_TotalSamples / ((float)m_SampleRate / 1000.0f)); return true; } bool CMpegAudioDecoder::SetPosition(unsigned long * MS) { return false; } bool CMpegAudioDecoder::GetFormat(unsigned long * SampleRate, unsigned long * Channels) { *SampleRate = m_SampleRate; *Channels = m_Channels; return true; } bool CMpegAudioDecoder::GetBuffer(float ** ppBuffer, unsigned long * NumSamples) { int ret = 0; while(true) { ret = decoder.syncNextFrame(); if(ret == decodeFrame_NeedMoreData) { uint32_t left = decoder.getBytesLeft(); uint32_t bytesthistime = MIN_MPEG_DATA_SIZE - left; memcpy(m_databuffer, m_databuffer + bytesthistime, left); unsigned __int64 bytesread; m_pSource->Read(bytesthistime, m_databuffer + left, &bytesread); if(bytesread < bytesthistime) decoder.setEndOfStream(); decoder.setData(m_databuffer, left + bytesread); } else if(ret == decodeFrame_Success) { // found our first frame! break; } else if((ret == decodeFrame_NotEnoughBRV) || (ret == decodeFrame_Xing) || ret == decodeFrame_NoFollowingHeader) { // also skip ID3 frames please // need to go around again or we're gonna 'whoop' continue; } else { // something else happened! return false; } } if((ret == decodeFrame_Success) || (ret == decodeFrame_Xing)) { // we got a frame - now lets decode it innit //memset(m_audiobuffer, 0, 4096 * 4); decoder.synthFrame(m_audiobuffer); *ppBuffer = m_audiobuffer; *NumSamples = 2304; return true; } return false; } bool CMpegAudioDecoder::Open(IAudioFileIO * pFileIO) { m_pSource = pFileIO; if(!m_pSource) return NULL; //Lets find a frame so we can get sample rate and channels! float * temp; unsigned long blah; if(GetBuffer(&temp, &blah)) { m_SampleRate = decoder.header.SampleRate; m_Channels = decoder.header.Channels; decoder.Reset(); } return true; } #include <math.h> void deemphasis5015(void) { int num_channels = 2; float frequency = 44100; short * outbuf; int numsamples[2]; double llastin[2], llastout[2]; int i, ch; /* this implements an attenuation treble shelving filter to undo the effect of pre-emphasis. The filter is of a recursive first order */ short lastin; double lastout; short *pmm; /* See deemphasis.gnuplot */ double V0 = 0.3365; double OMEGAG = (1./19e-6); double T = (1./frequency); double H0 = (V0-1.); double B = (V0*tan((OMEGAG * T)/2.0)); double a1 = ((B - 1.)/(B + 1.)); double b0 = (1.0 + (1.0 - a1) * H0/2.0); double b1 = (a1 + (a1 - 1.0) * H0/2.0); for (ch=0; ch< num_channels; ch++) { /* --------------------------------------------------------------------- * For 48Khz: a1=-0.659065 * b0= 0.449605 * b1=-0.108670 * For 44.1Khz: a1=-0.62786881719628784282 * b0= 0.45995451989513153057 * b1=-0.08782333709141937339 * For 32kHZ ? */ lastin = llastin [ch]; lastout = llastout [ch]; for (pmm = (short *)outbuf [ch], i=0; i < numsamples[0]; /* TODO: check for second channel */ i++) { lastout = *pmm * b0 + lastin * b1 - lastout * a1; lastin = *pmm; //*pmm++ = (lastout > 0.0) ? lastout + 0.5 : lastout - 0.5; *pmm++ = lastout; } // for (pmn = .. */ llastout [ch] = lastout; llastin [ch] = lastin; } // or (ch = .. */ }
21.542105
114
0.632299
Harteex
7b4c0900cccfce3a5c05032ae73783bab8cfe010
240
hpp
C++
CPP_US/src/Engine/Engine.hpp
Basher207/Unity-style-Cpp-engine
812b0be2c61aea828cfd8c6d6f06f2cf6e889661
[ "MIT" ]
null
null
null
CPP_US/src/Engine/Engine.hpp
Basher207/Unity-style-Cpp-engine
812b0be2c61aea828cfd8c6d6f06f2cf6e889661
[ "MIT" ]
null
null
null
CPP_US/src/Engine/Engine.hpp
Basher207/Unity-style-Cpp-engine
812b0be2c61aea828cfd8c6d6f06f2cf6e889661
[ "MIT" ]
null
null
null
#pragma once //Adds all the relevant headers. #include "GameObject.hpp" #include "Camera.hpp" #include "Input.hpp" #include "Math.hpp" #include "MeshRenderer.hpp" #include "MonoBehaviour.hpp" #include "Runner.hpp" #include "Transform.hpp"
20
32
0.75
Basher207
7b56a1a4f3b734e5ba6b1f56cf4886b0f9e95854
2,773
cpp
C++
Source/SnowClient.cpp
zcharli/snow-olsr
3617044d3ad1a0541b346669bce76702f71f4d0c
[ "MIT" ]
3
2018-08-08T22:31:52.000Z
2019-12-17T14:02:59.000Z
Source/SnowClient.cpp
zcharli/snow-olsr
3617044d3ad1a0541b346669bce76702f71f4d0c
[ "MIT" ]
null
null
null
Source/SnowClient.cpp
zcharli/snow-olsr
3617044d3ad1a0541b346669bce76702f71f4d0c
[ "MIT" ]
null
null
null
#include "Headers/SnowClient.h" #include "Headers/NetworkTrafficManager.h" /* Testing headers */ #include "Headers/HelloMessage.h" using namespace std; SnowClient::SnowClient() { //mSocketPtr = make_shared<WLAN>(INTERFACE_NAME); } SnowClient::~SnowClient() {} int SnowClient::start() { shared_ptr<NetworkTrafficManager> vNetworkManager = make_shared<NetworkTrafficManager>(INTERFACE_NAME); vNetworkManager->init(); RoutingProtocol::getInstance().setPersonalAddress(vNetworkManager->getPersonalAddress()); while (1) { shared_ptr<Packet> vPacket = vNetworkManager->getMessage(); if (vPacket != nullptr) { //std::cout << "First packet " << vPacket->getSource() << std::endl; if (vPacket->getSource()!= vNetworkManager->getPersonalAddress()) { #if verbose std::cout << "Malloc shared_ptr OLSR MESSAGE"<< std::endl; #endif shared_ptr<OLSRMessage> vMessage = make_shared<OLSRMessage>(vPacket); #if verbose std::cout << "OLSR Message is deserialized " << vPacket->getSource() << std::endl; #endif RoutingProtocol::getInstance().lockForUpdate(); if(RoutingProtocol::getInstance().updateState(vMessage).needsForwarding()) { vNetworkManager->sendMsg(vMessage); } RoutingProtocol::getInstance().unLockAfterUpdate(); } else { //std::cout << "Got a packet from my self lulz" << std::endl; } } } return 0; } // Code used to test deserialization and serialization // // std::shared_ptr<HelloMessage> msg = make_shared<HelloMessage>(); // HelloMessage::LinkMessage link; // link.linkCode = 255; // char a[] = {'1', '2', '3', '4', '5', '6'}; // MACAddress linkAddr(a); // link.neighborIfAddr.push_back(linkAddr); // msg->mLinkMessages.push_back(link); // msg->type = 1; // msg->htime = 255; // msg->willingness = 255; // msg->mMessageHeader.type = 1; // msg->mMessageHeader.vtime = 255; // msg->mMessageHeader.messageSize = 8080; // memcpy(msg->mMessageHeader.originatorAddress, vNetworkManager->getPersonalAddress().data, WLAN_ADDR_LEN); // // /msg.mMessageHeader.originatorAddress = vNetworkManager->getPersonalAddress().data; // msg->mMessageHeader.timeToLive = 255; // msg->mMessageHeader.hopCount = 255; // msg->mMessageHeader.messageSequenceNumber = 8080; // OLSRMessage omsg; // omsg.messages.push_back(msg); // char* serialized = omsg.serialize().getData(); // OLSRMessage dmsg(serialized);
37.986301
116
0.60476
zcharli
7b5a37d255cdd1fa127a2330b641b04937616e7e
6,515
cc
C++
src/output/L2_Error_Calculator.cc
pgmaginot/DARK_ARTS
f04b0a30dcac911ef06fe0916921020826f5c42b
[ "MIT" ]
null
null
null
src/output/L2_Error_Calculator.cc
pgmaginot/DARK_ARTS
f04b0a30dcac911ef06fe0916921020826f5c42b
[ "MIT" ]
null
null
null
src/output/L2_Error_Calculator.cc
pgmaginot/DARK_ARTS
f04b0a30dcac911ef06fe0916921020826f5c42b
[ "MIT" ]
null
null
null
/** @file L2_Error_Calculator.cc * @author pmaginot * @brief A class that numerically approximates the L2 spatial errors of Temperature, Intensity, and Angle Integrated Intensity for MMS problems */ #include "L2_Error_Calculator.h" // ########################################################## // Public functions // ########################################################## L2_Error_Calculator::L2_Error_Calculator(const Angular_Quadrature& angular_quadrature, const Fem_Quadrature& fem_quadrature, const Cell_Data& cell_data, const Input_Reader& input_reader) : m_n_dfem( fem_quadrature.get_number_of_interpolation_points() ) , m_n_cells( cell_data.get_total_number_of_cells() ), /// m_n_quad_pts(fem_quadrature.get_number_of_integration_points() ), m_n_quad_pts(fem_quadrature.get_number_of_source_points() ), m_cell_data( cell_data ), m_fem_quadrature( fem_quadrature ), m_analytic_temperature(input_reader) , m_analytic_intensity(input_reader, angular_quadrature) { /// old way // fem_quadrature.get_dfem_integration_points( m_integration_quadrature_pts ); // fem_quadrature.get_integration_weights( m_integration_quadrature_wts ); // fem_quadrature.get_dfem_at_integration_points( m_dfem_at_integration_pts ); /// more correct way fem_quadrature.get_source_points(m_integration_quadrature_pts); fem_quadrature.get_source_weights(m_integration_quadrature_wts); fem_quadrature.get_dfem_at_source_points(m_dfem_at_integration_pts); } double L2_Error_Calculator::calculate_l2_error(const double time_eval, const Intensity_Moment_Data& phi) const { /// only going to calculate the error in the scalar flux double err = 0.; Eigen::VectorXd num_soln = Eigen::VectorXd::Zero(m_n_dfem); for(int cell = 0 ; cell < m_n_cells ; cell++) { phi.get_cell_angle_integrated_intensity(cell,0,0 , num_soln); err += calculate_local_l2_error(num_soln , m_cell_data.get_cell_left_edge(cell) , m_cell_data.get_cell_width(cell) , time_eval , PHI ); } return sqrt(err); } double L2_Error_Calculator::calculate_l2_error(const double time_eval, const Temperature_Data& temperature) const { double err = 0.; Eigen::VectorXd num_soln = Eigen::VectorXd::Zero(m_n_dfem); for(int cell = 0 ; cell < m_n_cells ; cell++) { temperature.get_cell_temperature(cell,num_soln); err += calculate_local_l2_error(num_soln , m_cell_data.get_cell_left_edge(cell) , m_cell_data.get_cell_width(cell) , time_eval, TEMPERATURE ); } return sqrt(err); } double L2_Error_Calculator::calculate_cell_avg_error(const double time_eval, const Intensity_Moment_Data& phi) const { /// only going to calculate the error in the scalar flux double err = 0.; Eigen::VectorXd num_soln = Eigen::VectorXd::Zero(m_n_dfem); for(int cell = 0 ; cell < m_n_cells ; cell++) { phi.get_cell_angle_integrated_intensity(cell,0,0 , num_soln); err += calculate_local_cell_avg_error(num_soln , m_cell_data.get_cell_left_edge(cell) , m_cell_data.get_cell_width(cell) , time_eval, PHI ); } return sqrt(err); } double L2_Error_Calculator::calculate_cell_avg_error(const double time_eval, const Temperature_Data& temperature) const { double err = 0.; Eigen::VectorXd num_soln = Eigen::VectorXd::Zero(m_n_dfem); for(int cell = 0 ; cell < m_n_cells ; cell++) { temperature.get_cell_temperature(cell,num_soln); err += calculate_local_cell_avg_error(num_soln , m_cell_data.get_cell_left_edge(cell) , m_cell_data.get_cell_width(cell) , time_eval , TEMPERATURE ); } return sqrt(err); } double L2_Error_Calculator::calculate_local_l2_error( const Eigen::VectorXd& numeric_at_dfem, const double xL , const double dx , const double time , const Data_Type data ) const { double err = 0.; /// add in dx/2 contribution std::vector<double> numeric_soln; m_fem_quadrature.evaluate_variable_at_quadrature_pts(numeric_at_dfem , m_dfem_at_integration_pts , numeric_soln); double x_eval = 0.; double analytic_soln = 0.; for(int q = 0 ; q < m_n_quad_pts ; q++) { x_eval = xL + dx/2.*(1. + m_integration_quadrature_pts[q] ); switch(data) { case PHI: { analytic_soln = m_analytic_intensity.get_mms_phi(x_eval, time); break; } case TEMPERATURE: { analytic_soln = m_analytic_temperature.get_mms_temperature(x_eval, time); break; } default: { throw Dark_Arts_Exception(SUPPORT_OBJECT , "Trying to find the L2 error of a weird data type"); break; } } // err += m_integration_quadrature_wts[q]*( analytic_soln*analytic_soln - 2.*numeric_soln[q]*analytic_soln + numeric_soln[q]*numeric_soln[q] ); err += m_integration_quadrature_wts[q]*( analytic_soln - numeric_soln[q])*( analytic_soln - numeric_soln[q]) ; } err *= dx/2.; return err; } double L2_Error_Calculator::calculate_local_cell_avg_error( const Eigen::VectorXd& numeric_at_dfem , const double xL , const double dx , const double time, const Data_Type data ) const { double err = 0.; std::vector<double> numeric_soln; m_fem_quadrature.evaluate_variable_at_quadrature_pts(numeric_at_dfem , m_dfem_at_integration_pts , numeric_soln); double x_eval = 0.; double analytic_soln = 0.; double analytic_average = 0.; double numeric_average = 0.; for(int q = 0 ; q < m_n_quad_pts ; q++) { x_eval = xL + dx/2.*(1. + m_integration_quadrature_pts[q] ); switch(data) { case PHI: { analytic_soln = m_analytic_intensity.get_mms_phi(x_eval, time); break; } case TEMPERATURE: { analytic_soln = m_analytic_temperature.get_mms_temperature(x_eval, time); break; } default: { throw Dark_Arts_Exception(SUPPORT_OBJECT , "Trying to find the L2 error of a weird data type"); break; } } analytic_average += m_integration_quadrature_wts[q]* analytic_soln ; numeric_average += m_integration_quadrature_wts[q]*numeric_soln[q]; } analytic_average /= 2.; numeric_average /= 2.; // err = dx*(analytic_average*analytic_average - 2.*analytic_average*numeric_average + numeric_average*numeric_average); err = dx*(analytic_average-numeric_average)*(analytic_average-numeric_average) ; return err; }
36.396648
154
0.692556
pgmaginot
7b5cd1b1a1c5697011a60b990b9e544ec320d4db
1,080
cpp
C++
src/benchmarks/ShowHash.cpp
perara-public/map_benchmark
8efe2a5eab97449971733d71e2047c26537c6123
[ "MIT" ]
110
2019-02-19T05:20:55.000Z
2022-03-21T10:14:18.000Z
src/benchmarks/ShowHash.cpp
perara-public/map_benchmark
8efe2a5eab97449971733d71e2047c26537c6123
[ "MIT" ]
10
2019-02-27T09:41:39.000Z
2021-04-15T06:35:56.000Z
src/benchmarks/ShowHash.cpp
perara-public/map_benchmark
8efe2a5eab97449971733d71e2047c26537c6123
[ "MIT" ]
17
2019-02-26T12:12:43.000Z
2022-01-27T07:03:59.000Z
#include "Hash.h" #include "bench.h" #include "hex.h" #include <bitset> template <typename T> void showHash(T val) { auto sh = std::hash<T>{}(val); auto mh = Hash<T>{}(val); std::cerr << hex(val) << " -> " << hex(sh) << " " << hex(mh) << " " << std::bitset<sizeof(size_t) * 8>(mh) << std::endl; } template <typename T> void showHash(const char* title) { std::cerr << std::endl << title << std::endl; std::cerr << "input std::hash " << HashName << std::endl; for (T i = 0; i < 100; ++i) { showHash(i); } for (T i = 0; i < 10; ++i) { T s = ((0x23d7 + i) << (sizeof(T) * 4)) + 12; showHash(s); } // <= 0 so it works with int overflows for (uint64_t i = 1; i <= (std::numeric_limits<T>::max)() && i != 0; i *= 2) { showHash(static_cast<T>(i)); } for (uint64_t i = 1; i <= (std::numeric_limits<T>::max)() && i != 0; i *= 2) { showHash(static_cast<T>(i + 1)); } } BENCHMARK(ShowHash) { showHash<uint64_t>("uint64_t"); showHash<int32_t>("int32_t"); }
26.341463
124
0.498148
perara-public
7b5dfd74467b7861e4667f8720b7e389065afea4
1,351
cpp
C++
src/IO/Device/ControlBoard/CM730.cpp
NaokiTakahashi12/OpenHumanoidController
ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d
[ "MIT" ]
1
2019-09-23T06:21:47.000Z
2019-09-23T06:21:47.000Z
src/IO/Device/ControlBoard/CM730.cpp
NaokiTakahashi12/hc-early
ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d
[ "MIT" ]
12
2019-07-30T00:17:09.000Z
2019-12-09T23:00:43.000Z
src/IO/Device/ControlBoard/CM730.cpp
NaokiTakahashi12/OpenHumanoidController
ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d
[ "MIT" ]
null
null
null
/** * * @file CM730.cpp * @author Naoki Takahashi * **/ #include "CM730.hpp" #include "CM730ControlTable.hpp" namespace IO { namespace Device { namespace ControlBoard { CM730::CM730(RobotStatus::InformationPtr &robot_status_information_ptr) : SerialControlBoard(robot_status_information_ptr) { id(default_id); } CM730::CM730(const ID &new_id, RobotStatus::InformationPtr &robot_status_information_ptr) : SerialControlBoard(new_id, robot_status_information_ptr) { } CM730::~CM730() { } std::string CM730::get_key() { return "CM730"; } void CM730::enable_power(const bool &flag) { command_controller->set_packet(create_switch_power_packet(flag)); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } void CM730::ping() { command_controller->set_packet(Communicator::Protocols::DynamixelVersion1::create_ping_packet(id())); } Communicator::SerialFlowScheduler::SinglePacket CM730::create_switch_power_packet(const bool &flag) { const auto value = flag ? Communicator::Protocols::DynamixelVersion1::enable : Communicator::Protocols::DynamixelVersion1::disable; const auto packet = Communicator::Protocols::DynamixelVersion1::create_write_packet( id(), CM730ControlTable::dynamixel_power, value ); return packet; } } } }
25.018519
153
0.715766
NaokiTakahashi12
7b5faea800d72e0705163223c5391249b42e51d7
1,030
cpp
C++
src/ipc/mq_receiver.cpp
kreopt/dcm
d9eae08b5ff716d5eb3d97684aeddd9492d342b0
[ "MIT" ]
null
null
null
src/ipc/mq_receiver.cpp
kreopt/dcm
d9eae08b5ff716d5eb3d97684aeddd9492d342b0
[ "MIT" ]
null
null
null
src/ipc/mq_receiver.cpp
kreopt/dcm
d9eae08b5ff716d5eb3d97684aeddd9492d342b0
[ "MIT" ]
null
null
null
#include "mq_receiver.hpp" #include <boost/interprocess/ipc/message_queue.hpp> #include <thread> #include "core/message.hpp" namespace bip = boost::interprocess; dcm::ipc::mq::receiver::receiver(const std::string &_mbox) : mbox_(_mbox) { bip::message_queue::remove(_mbox.c_str()); mq_ = std::make_shared<bip::message_queue>(bip::create_only, mbox_.c_str(), MAX_MESSAGES, MAX_MESSAGE_SIZE); } dcm::ipc::mq::receiver::~receiver() { bip::message_queue::remove(mbox_.c_str()); } void dcm::ipc::mq::receiver::listen() { size_t recvd_size; uint priority; while (!stop_) { auto raw_msg = std::shared_ptr<char>(new char[MAX_MESSAGE_SIZE], [](char* _p){delete [] _p;}); mq_->receive(raw_msg.get(), MAX_MESSAGE_SIZE, recvd_size, priority); if (on_message){ dcm::message msg; interproc::buffer encoded(raw_msg.get(), recvd_size); msg.decode_header(encoded); on_message(std::move(msg)); } std::this_thread::yield(); } }
30.294118
112
0.645631
kreopt
7b6183048a03ea269bef1c4c6fb76adc6a32665a
7,386
cc
C++
ns-allinone-2.35/ns-2.35/emulate/ping_responder.cc
nitishk017/ns2project
f037b796ff10300ffe0422580be5855c37d0b140
[ "MIT" ]
1
2020-05-29T13:04:42.000Z
2020-05-29T13:04:42.000Z
ns-allinone-2.35/ns-2.35/emulate/ping_responder.cc
nitishk017/ns2project
f037b796ff10300ffe0422580be5855c37d0b140
[ "MIT" ]
1
2019-01-20T17:35:23.000Z
2019-01-22T21:41:38.000Z
ns-allinone-2.35/ns-2.35/emulate/ping_responder.cc
nitishk017/ns2project
f037b796ff10300ffe0422580be5855c37d0b140
[ "MIT" ]
1
2021-09-29T16:06:57.000Z
2021-09-29T16:06:57.000Z
/* * Copyright (c) 1998 Regents of the University of California. * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the Network Research * Group at Lawrence Berkeley National Laboratory. * 4. Neither the name of the University nor of the Laboratory may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint static const char rcsid[] = "@(#) $Header: /cvsroot/nsnam/ns-2/emulate/ping_responder.cc,v 1.8 2000/09/01 03:04:10 haoboy Exp $"; #endif #include <stdio.h> #include <sys/types.h> #include <netinet/in.h> #include <netinet/in_systm.h> #include <netinet/ip.h> #include <netinet/ip_icmp.h> #include <netinet/ip_icmp.h> #include <arpa/inet.h> #include "agent.h" #include "scheduler.h" #include "emulate/internet.h" // // ping_responder.cc -- this agent may be inserted into nse as // a real-world responder to ICMP ECHOREQUEST operations. It's // used to test emulation mode, mostly (and in particular the rt scheduler) // class PingResponder : public Agent { public: PingResponder() : Agent(PT_LIVE) { } void recv(Packet*, Handler*); protected: icmp* validate(int, ip*); void reflect(ip*); }; static class PingResponderClass : public TclClass { public: PingResponderClass() : TclClass("Agent/PingResponder") {} TclObject* create(int , const char*const*) { return (new PingResponder()); } } class_pingresponder; /* * receive an ICMP echo request packet from the simulator. * Actual IP packet is in the "data" portion of the packet, and * is assumed to start with the IP header */ void PingResponder::recv(Packet* pkt, Handler*) { hdr_cmn *ch = HDR_CMN(pkt); int psize = ch->size(); u_char* payload = pkt->accessdata(); if (payload == NULL) { fprintf(stderr, "%f: PingResponder(%s): recv NULL data area\n", Scheduler::instance().clock(), name()); Packet::free(pkt); return; } /* * assume here that the data area contains an IP header! */ icmp* icmph; if ((icmph = validate(psize, (ip*) payload)) == NULL) { Internet::print_ip((ip*) payload); Packet::free(pkt); return; } /* * tasks: change icmp type to echo-reply, recompute IP hdr cksum, * recompute ICMP cksum */ icmph->icmp_type = ICMP_ECHOREPLY; reflect((ip*) payload); // like kernel routine icmp_reflect() /* * set up simulator packet to go to the correct place */ Agent::initpkt(pkt); ch->size() = psize; // will have been overwrittin by initpkt target_->recv(pkt); return; } /* * check a bunch of stuff: * ip vers ok, ip hlen is 5, proto is icmp, len big enough, * not fragmented, cksum ok, saddr not mcast/bcast */ icmp* PingResponder::validate(int sz, ip* iph) { if (sz < 20) { fprintf(stderr, "%f: PingResponder(%s): sim pkt too small for base IP header(%d)\n", Scheduler::instance().clock(), name(), sz); return (NULL); } int ipver = (*((char*)iph) & 0xf0) >> 4; if (ipver != 4) { fprintf(stderr, "%f: PingResponder(%s): IP bad ver (%d)\n", Scheduler::instance().clock(), name(), ipver); return (NULL); } int iplen = ntohs(iph->ip_len); int iphlen = (*((char*)iph) & 0x0f) << 2; if (iplen < (iphlen + 8)) { fprintf(stderr, "%f: PingResponder(%s): IP dgram not long enough (len: %d)\n", Scheduler::instance().clock(), name(), iplen); return (NULL); } if (sz < iplen) { fprintf(stderr, "%f: PingResponder(%s): IP dgram not long enough (len: %d)\n", Scheduler::instance().clock(), name(), iplen); return (NULL); } if (iphlen != 20) { fprintf(stderr, "%f: PingResponder(%s): IP bad hlen (%d)\n", Scheduler::instance().clock(), name(), iphlen); return (NULL); } if (Internet::in_cksum((u_short*) iph, iphlen)) { fprintf(stderr, "%f: PingResponder(%s): IP bad cksum\n", Scheduler::instance().clock(), name()); return (NULL); } if (iph->ip_p != IPPROTO_ICMP) { fprintf(stderr, "%f: PingResponder(%s): not ICMP (proto: %d)\n", Scheduler::instance().clock(), name(), iph->ip_p); return (NULL); } if (iph->ip_off != 0) { fprintf(stderr, "%f: PingResponder(%s): fragment! (off: 0x%x)\n", Scheduler::instance().clock(), name(), ntohs(iph->ip_off)); return (NULL); } if (iph->ip_src.s_addr == 0xffffffff || iph->ip_src.s_addr == 0) { fprintf(stderr, "%f: PingResponder(%s): bad src addr (%s)\n", Scheduler::instance().clock(), name(), inet_ntoa(iph->ip_src)); return (NULL); } if (IN_MULTICAST(ntohl(iph->ip_src.s_addr))) { fprintf(stderr, "%f: PingResponder(%s): mcast src addr (%s)\n", Scheduler::instance().clock(), name(), inet_ntoa(iph->ip_src)); return (NULL); } icmp* icp = (icmp*) (iph + 1); if (Internet::in_cksum((u_short*) icp, iplen - iphlen) != 0) { fprintf(stderr, "%f: PingResponder(%s): bad ICMP cksum\n", Scheduler::instance().clock(), name()); return (NULL); } if (icp->icmp_type != ICMP_ECHO) { fprintf(stderr, "%f: PingResponder(%s): not echo request (%d)\n", Scheduler::instance().clock(), name(), icp->icmp_type); return (NULL); } if (icp->icmp_code != 0) { fprintf(stderr, "%f: PingResponder(%s): bad code (%d)\n", Scheduler::instance().clock(), name(), icp->icmp_code); return (NULL); } return (icp); } /* * reflect: fix up the IP and ICMP info to reflect the packet * back from where it came in real life * * this routine will just assume no IP options on the pkt */ void PingResponder::reflect(ip* iph) { in_addr daddr = iph->ip_dst; int iplen = ntohs(iph->ip_len); int iphlen = (*((char*)iph) & 0x0f) << 2; /* swap src and dest IP addresses on IP header */ iph->ip_dst = iph->ip_src; iph->ip_src = daddr; iph->ip_sum = 0; iph->ip_sum = Internet::in_cksum((u_short*) iph, iphlen); /* recompute the icmp cksum */ icmp* icp = (icmp*)(iph + 1); // just past standard IP header icp->icmp_cksum = 0; icp->icmp_cksum = Internet::in_cksum((u_short*)icp, iplen - iphlen); }
29.782258
105
0.668291
nitishk017
7b64e395000258c1f463ca0822ff1866a6897001
1,543
hpp
C++
src/GUI.hpp
kririae/Fluid-Visualization
fc3d6deceb2428479a4ec58d5dbe44dcfc1a204e
[ "MIT" ]
2
2022-01-22T09:44:10.000Z
2022-01-22T09:45:02.000Z
src/GUI.hpp
kririae/Fluid-Visualization
fc3d6deceb2428479a4ec58d5dbe44dcfc1a204e
[ "MIT" ]
null
null
null
src/GUI.hpp
kririae/Fluid-Visualization
fc3d6deceb2428479a4ec58d5dbe44dcfc1a204e
[ "MIT" ]
null
null
null
// // Created by kr2 on 12/24/21. // #ifndef FLUIDVISUALIZATION_SRC_GUI_HPP #define FLUIDVISUALIZATION_SRC_GUI_HPP #include "Particle.hpp" #include "Shader.hpp" #include "PBuffer.hpp" #include <functional> #include <memory> typedef unsigned int uint; struct GLFWwindow; class Solver; class OrbitCamera; class GUI { public: GUI(int WIDTH, int HEIGHT); GUI(const GUI &) = delete; GUI &operator=(const GUI &) = delete; virtual ~GUI() = default; virtual void mainLoop(const std::function<void()> &callback); protected: GLFWwindow *window{}; int width, height; }; class RTGUI : public GUI { // REAL-TIME GUI for Lagrange View stimulation(particles) public: RTGUI(int WIDTH, int HEIGHT); ~RTGUI() override = default; void setParticles(const PBuffer& _buffer); void setSolver(std::shared_ptr<Solver> _solver); void mainLoop(const std::function<void()> &callback) override; void del(); protected: PBuffer buffer; uint frame = 0; unsigned int VAO{}, VBO{}, EBO{}; std::unique_ptr<Shader> p_shader{}, m_shader{}; std::shared_ptr<hvector<vec3> > mesh; std::shared_ptr<hvector<uint> > indices; std::shared_ptr<Solver> solver; std::shared_ptr<OrbitCamera> camera; bool snapshot{false}; bool pause{false}; uint lastPauseFrame{}; float lastX; float lastY; bool firstMouse{false}; private: void renderParticles() const; void refreshFps() const; void processInput(); void saveParticles() const; void mouseCallback(double x, double y); }; #endif //FLUIDVISUALIZATION_SRC_GUI_HPP
20.851351
64
0.714193
kririae
7b66efcfc3e73148dc12bd31e7b6f173dcb25565
2,044
cpp
C++
lib/year2020/src/Day06Puzzle.cpp
MarkRDavison/AdventOfCode
640ae6de76709367be8dfeb86b9f1f7d21908946
[ "MIT" ]
null
null
null
lib/year2020/src/Day06Puzzle.cpp
MarkRDavison/AdventOfCode
640ae6de76709367be8dfeb86b9f1f7d21908946
[ "MIT" ]
null
null
null
lib/year2020/src/Day06Puzzle.cpp
MarkRDavison/AdventOfCode
640ae6de76709367be8dfeb86b9f1f7d21908946
[ "MIT" ]
null
null
null
#include <2020/Day06Puzzle.hpp> #include <zeno-engine/Utility/StringExtensions.hpp> #include <sstream> #include <fstream> #include <iostream> namespace TwentyTwenty { Day06Puzzle::Day06Puzzle() : core::PuzzleBase("Custom Customs", 2020, 6) { } void Day06Puzzle::initialise(const core::InitialisationInfo& _initialisationInfo) { setInputLines(ze::StringExtensions::splitStringByLines(ze::StringExtensions::loadFileToString(_initialisationInfo.parameters[0]))); } void Day06Puzzle::setInputLines(const std::vector<std::string>& _inputLines) { m_InputLines = std::vector<std::string>(_inputLines); } std::pair<std::string, std::string> Day06Puzzle::fastSolve() { const auto& parsed = parseInput(m_InputLines); auto part1 = doPart1(parsed); auto part2 = doPart2(parsed); return { part1, part2 }; } std::vector<Day06Puzzle::Questions> Day06Puzzle::parseInput(const std::vector<std::string>& _input) { std::vector<Day06Puzzle::Questions> parsed; parsed.emplace_back(); for (const auto& i : _input) { if (i.empty()) { parsed.emplace_back(); continue; } auto& current = parsed.back(); current.emplace_back(); auto& qset = current.back(); for (const char c : i) { qset.insert(c); } } return parsed; } std::string Day06Puzzle::doPart1(const std::vector<Questions>& _parsedInput) { int count = 0; for (const auto& input : _parsedInput) { std::set<char> uniqueAnswers; for (const auto& q : input) { for (const auto& answer : q) { uniqueAnswers.insert(answer); } } count += uniqueAnswers.size(); } return std::to_string(count);; } std::string Day06Puzzle::doPart2(const std::vector<Questions>& _parsedInput) { int count = 0; for (const auto& t : _parsedInput) { for (const auto& c : t[0]) { bool valid = true; for (unsigned i = 1; i < t.size(); ++i) { if (t[i].count(c) <= 0) { valid = false; break; } } if (valid) { count++; } } } return std::to_string(count);; } }
21.291667
133
0.651174
MarkRDavison
7b682cb7d26f3b1663ee009f32fa184373b8c59b
1,284
cpp
C++
2-Data_Structures_and_Libraries/2.3-Non_Linear_Data_Structures_with_Built-in_Libraries/2-C++_STL_set_(Java_TreeSet)/vitorvgc/00978.cpp
IFCE-CP/CP3-solutions
1abcabd9a06968184a55d3b0414637019014694c
[ "MIT" ]
1
2017-11-16T10:56:17.000Z
2017-11-16T10:56:17.000Z
2-Data_Structures_and_Libraries/2.3-Non_Linear_Data_Structures_with_Built-in_Libraries/2-C++_STL_set_(Java_TreeSet)/vitorvgc/00978.cpp
IFCE-CP/CP3-solutions
1abcabd9a06968184a55d3b0414637019014694c
[ "MIT" ]
null
null
null
2-Data_Structures_and_Libraries/2.3-Non_Linear_Data_Structures_with_Built-in_Libraries/2-C++_STL_set_(Java_TreeSet)/vitorvgc/00978.cpp
IFCE-CP/CP3-solutions
1abcabd9a06968184a55d3b0414637019014694c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void print(priority_queue<int> pq) { for(; !pq.empty(); pq.pop()) printf("%d\n", pq.top()); } int main() { int t; for(scanf("%d", &t); t--; ) { int b, sg, sb; priority_queue<int> pqg, pqb; scanf("%d %d %d", &b, &sg, &sb); for(int i = 0, x; i < sg; ++i) { scanf("%d", &x); pqg.push(x); } for(int i = 0, x; i < sb; ++i) { scanf("%d", &x); pqb.push(x); } while(!pqg.empty() && !pqb.empty()) { int n = min(b, (int)min(pqg.size(), pqb.size())); vector<int> surv; for(int i = 0; i < n; ++i) { int g = pqg.top(); pqg.pop(); int b = pqb.top(); pqb.pop(); surv.push_back(g-b); } for(auto x : surv) { if(x > 0) pqg.push(x); else if(x < 0) pqb.push(-x); } } if(pqg.empty() && pqb.empty()) printf("green and blue died\n"); else { printf("%s wins\n", !pqg.empty() ? "green" : "blue"); print(!pqg.empty() ? pqg : pqb); } if(t) printf("\n"); } return 0; }
24.692308
65
0.374611
IFCE-CP
7b68f7a35a39189548e2159af99658ae33d1ae8a
14,338
hpp
C++
include/gtest_mpi/gtest_mpi_internal.hpp
teonnik/gtest_mpi
9664675870b36d1be6af682e3d99e63dfb6a3ad7
[ "BSD-3-Clause" ]
4
2019-05-31T09:35:09.000Z
2021-08-08T03:59:49.000Z
include/gtest_mpi/gtest_mpi_internal.hpp
teonnik/gtest_mpi
9664675870b36d1be6af682e3d99e63dfb6a3ad7
[ "BSD-3-Clause" ]
1
2019-06-20T12:31:27.000Z
2019-06-20T12:31:27.000Z
include/gtest_mpi/gtest_mpi_internal.hpp
teonnik/gtest_mpi
9664675870b36d1be6af682e3d99e63dfb6a3ad7
[ "BSD-3-Clause" ]
2
2019-05-31T09:35:14.000Z
2019-06-14T14:16:43.000Z
// This project contains source code from the Googletest framework // obtained from https://github.com/google/googletest with the following // terms: // // Copyright 2005, Google 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 Google Inc. 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 // OWNER 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. // --------------------------------------------------------------------- // // Modifications and additions are published under the following terms: // // Copyright 2019, Simon Frasch // 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 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 // OWNER 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. // --------------------------------------------------------------------- #ifndef GUARD_GTEST_MPI_INTERNAL_HPP #define GUARD_GTEST_MPI_INTERNAL_HPP #include <gtest/gtest.h> #include <mpi.h> #include <unistd.h> #include <cstdarg> #include <string> namespace gtest_mpi { namespace { // no external linkage // Taken / modified from Googletest static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*"; static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*"; static const char kUniversalFilter[] = "*"; static const char kDefaultOutputFormat[] = "xml"; static const char kDefaultOutputFile[] = "test_detail"; static const char kTestShardIndex[] = "GTEST_SHARD_INDEX"; static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS"; static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE"; static const char kTypeParamLabel[] = "TypeParam"; static const char kValueParamLabel[] = "GetParam()"; // Taken / modified from Googletest enum GTestColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW }; // Taken / modified from Googletest static void PrintFullTestCommentIfPresent(const ::testing::TestInfo& test_info) { const char* const type_param = test_info.type_param(); const char* const value_param = test_info.value_param(); if (type_param != NULL || value_param != NULL) { printf(", where "); if (type_param != NULL) { printf("%s = %s", kTypeParamLabel, type_param); if (value_param != NULL) printf(" and "); } if (value_param != NULL) { printf("%s = %s", kValueParamLabel, value_param); } } } // Taken / modified from Googletest bool ShouldUseColor(bool stdout_is_tty) { using namespace ::testing; using namespace ::testing::internal; const char* const gtest_color = GTEST_FLAG(color).c_str(); if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) { #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW // On Windows the TERM variable is usually not set, but the // console there does support colors. return stdout_is_tty; #else // On non-Windows platforms, we rely on the TERM variable. const char* const term = getenv("TERM"); const bool term_supports_color = String::CStringEquals(term, "xterm") || String::CStringEquals(term, "xterm-color") || String::CStringEquals(term, "xterm-256color") || String::CStringEquals(term, "screen") || String::CStringEquals(term, "screen-256color") || String::CStringEquals(term, "tmux") || String::CStringEquals(term, "tmux-256color") || String::CStringEquals(term, "rxvt-unicode") || String::CStringEquals(term, "rxvt-unicode-256color") || String::CStringEquals(term, "linux") || String::CStringEquals(term, "cygwin"); return stdout_is_tty && term_supports_color; #endif // GTEST_OS_WINDOWS } return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || String::CaseInsensitiveCStringEquals(gtest_color, "true") || String::CaseInsensitiveCStringEquals(gtest_color, "t") || String::CStringEquals(gtest_color, "1"); // We take "yes", "true", "t", and "1" as meaning "yes". If the // value is neither one of these nor "auto", we treat it as "no" to // be conservative. } // Taken / modified from Googletest static const char* GetAnsiColorCode(GTestColor color) { switch (color) { case COLOR_RED: return "1"; case COLOR_GREEN: return "2"; case COLOR_YELLOW: return "3"; default: return NULL; }; } // Taken / modified from Googletest static void ColoredPrintf(GTestColor color, const char* fmt, ...) { va_list args; va_start(args, fmt); static const bool in_color_mode = ShouldUseColor(isatty(fileno(stdout)) != 0); const bool use_color = in_color_mode && (color != COLOR_DEFAULT); if (!use_color) { vprintf(fmt, args); va_end(args); return; } printf("\033[0;3%sm", GetAnsiColorCode(color)); vprintf(fmt, args); printf("\033[m"); // Resets the terminal to default. va_end(args); } // Taken / modified from Googletest ::testing::internal::Int32 Int32FromEnvOrDie(const char* var, ::testing::internal::Int32 default_val) { using namespace ::testing; using namespace ::testing::internal; const char* str_val = getenv(var); if (str_val == NULL) { return default_val; } Int32 result; if (!ParseInt32(Message() << "The value of environment variable " << var, str_val, &result)) { exit(EXIT_FAILURE); } return result; } // Taken / modified from Googletest static std::string FormatCountableNoun(int count, const char* singular_form, const char* plural_form) { using namespace ::testing; return internal::StreamableToString(count) + " " + (count == 1 ? singular_form : plural_form); } // Taken / modified from Googletest static std::string FormatTestCount(int test_count) { return FormatCountableNoun(test_count, "test", "tests"); } // Taken / modified from Googletest static std::string FormatTestCaseCount(int test_case_count) { return FormatCountableNoun(test_case_count, "test case", "test cases"); } // Taken / modified from Googletest static const char* TestPartResultTypeToString(::testing::TestPartResult::Type type) { switch (type) { case ::testing::TestPartResult::kSuccess: return "Success"; case ::testing::TestPartResult::kNonFatalFailure: case ::testing::TestPartResult::kFatalFailure: #ifdef _MSC_VER return "error: "; #else return "Failure\n"; #endif default: return "Unknown result type"; } } // Taken / modified from Googletest bool ShouldShard(const char* total_shards_env, const char* shard_index_env, bool in_subprocess_for_death_test) { using namespace ::testing; using namespace ::testing::internal; if (in_subprocess_for_death_test) { return false; } const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1); const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1); if (total_shards == -1 && shard_index == -1) { return false; } else if (total_shards == -1 && shard_index != -1) { const Message msg = Message() << "Invalid environment variables: you have " << kTestShardIndex << " = " << shard_index << ", but have left " << kTestTotalShards << " unset.\n"; ColoredPrintf(COLOR_RED, msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } else if (total_shards != -1 && shard_index == -1) { const Message msg = Message() << "Invalid environment variables: you have " << kTestTotalShards << " = " << total_shards << ", but have left " << kTestShardIndex << " unset.\n"; ColoredPrintf(COLOR_RED, msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } else if (shard_index < 0 || shard_index >= total_shards) { const Message msg = Message() << "Invalid environment variables: we require 0 <= " << kTestShardIndex << " < " << kTestTotalShards << ", but you have " << kTestShardIndex << "=" << shard_index << ", " << kTestTotalShards << "=" << total_shards << ".\n"; ColoredPrintf(COLOR_RED, msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } return total_shards > 1; } // info from TestInfo, which does not have a copy constructor struct TestInfoProperties { std::string name; std::string case_name; std::string type_param; std::string value_param; bool should_run; std::set<int> ranks; }; // Holds null terminated strings in a single vector, // which can be exchanged in a single MPI call class StringCollection { public: void Add(const char* s) { int size = 0; for (; *s != '\0'; ++s, ++size) { text.push_back(*s); } text.push_back('\0'); start_indices.push_back(prev_size); prev_size = size + 1; } // Sends content to requested rank void Send(MPI_Comm comm, int rank) const { MPI_Send(text.data(), text.size(), MPI_CHAR, rank, 0, comm); MPI_Send(start_indices.data(), start_indices.size(), MPI_INT, rank, 0, comm); } // Overrides content with data from requested rank void Recv(MPI_Comm comm, int rank) { MPI_Status status; int count = 0; // Recv text MPI_Probe(rank, 0, comm, &status); MPI_Get_count(&status, MPI_CHAR, &count); text.resize(count); MPI_Recv(text.data(), count, MPI_CHAR, rank, 0, comm, MPI_STATUS_IGNORE); // Recv sizes MPI_Probe(rank, 0, comm, &status); MPI_Get_count(&status, MPI_INT, &count); start_indices.resize(count); MPI_Recv(start_indices.data(), count, MPI_INT, rank, 0, comm, MPI_STATUS_IGNORE); } void Reset() { text.clear(); start_indices.clear(); prev_size = 0; } const char* get_str(const int id) const { return text.data() + start_indices[id]; } const std::size_t Size() const { return start_indices.size(); } private: int prev_size = 0; std::vector<char> text; std::vector<int> start_indices; }; // All info recuired to print a failed test result. // Includes functionality for MPI exchange struct TestPartResultCollection { // Sends content to requested rank void Send(MPI_Comm comm, int rank) { MPI_Send(types.data(), types.size(), MPI_INT, rank, 0, comm); MPI_Send(line_numbers.data(), line_numbers.size(), MPI_INT, rank, 0, comm); summaries.Send(comm, rank); messages.Send(comm, rank); file_names.Send(comm, rank); } // Overrides content with data from requested rank void Recv(MPI_Comm comm, int rank) { MPI_Status status; int count = 0; // Recv text MPI_Probe(rank, 0, comm, &status); MPI_Get_count(&status, MPI_INT, &count); types.resize(count); MPI_Recv(types.data(), count, MPI_INT, rank, 0, comm, MPI_STATUS_IGNORE); // Recv sizes MPI_Probe(rank, 0, comm, &status); MPI_Get_count(&status, MPI_INT, &count); line_numbers.resize(count); MPI_Recv(line_numbers.data(), count, MPI_INT, rank, 0, comm, MPI_STATUS_IGNORE); summaries.Recv(comm, rank); messages.Recv(comm, rank); file_names.Recv(comm, rank); } void Add(const ::testing::TestPartResult& result) { types.push_back(result.type()); line_numbers.push_back(result.line_number()); summaries.Add(result.summary()); messages.Add(result.message()); file_names.Add(result.file_name()); } void Reset() { types.clear(); line_numbers.clear(); summaries.Reset(); messages.Reset(); file_names.Reset(); } std::size_t Size() const { return types.size(); } std::vector<int> types; std::vector<int> line_numbers; StringCollection summaries; StringCollection messages; StringCollection file_names; }; } // anonymous namespace } // namespace gtest_mpi #endif
35.934837
99
0.683917
teonnik
7b6932c63e3cfd74c36943631fae9d1aa5f72988
330
cpp
C++
pointer_example_4.cpp
pervincaliskan/SampleCExamples
c8cfd0076e4fdcfecdd4a1e97c482a506f6cca02
[ "MIT" ]
2
2019-12-22T18:52:34.000Z
2021-10-18T18:35:22.000Z
pointer_example_4.cpp
pervincaliskan/SampleCExamples
c8cfd0076e4fdcfecdd4a1e97c482a506f6cca02
[ "MIT" ]
1
2022-01-18T17:21:26.000Z
2022-01-18T17:21:26.000Z
pointer_example_4.cpp
pervincaliskan/SampleCExamples
c8cfd0076e4fdcfecdd4a1e97c482a506f6cca02
[ "MIT" ]
null
null
null
#include<stdio.h> int main(){ int x = 6; int *xptr = &x;; xptr = &x; // xptr gostergesine x adli bellek hucresinin adresi atandi printf("x'in onceki degeri: %d\n", x); x = *xptr + 1; // xptr gostergesinin gosterdigi bellek hucresindeki deger 1 artirildi printf("x'in sonraki degeri: %d\n", x); return 0; }
17.368421
87
0.633333
pervincaliskan
7b6fd00fc4e231f30de15845796fba40b79f97b5
776
hpp
C++
src/home_screen.hpp
tomfleet/M5PaperUI
cad8ccbbdf2273865eb9cbec70f41f87eca3fadd
[ "Apache-2.0" ]
24
2021-02-25T21:17:22.000Z
2022-03-01T19:01:13.000Z
src/home_screen.hpp
sthagen/M5PaperUI
05025433054d4e59ce8ec01eecbe44ac074b08ec
[ "Apache-2.0" ]
null
null
null
src/home_screen.hpp
sthagen/M5PaperUI
05025433054d4e59ce8ec01eecbe44ac074b08ec
[ "Apache-2.0" ]
10
2021-02-27T21:26:46.000Z
2022-03-13T12:59:40.000Z
#pragma once #include <memory> #include "widgetlib.hpp" class HomeScreen : public Frame { public: using ptr_t = std::shared_ptr<HomeScreen>; HomeScreen(int16_t x, int16_t y, int16_t w, int16_t h); static ptr_t Create(int16_t x, int16_t y, int16_t w, int16_t h) { return std::make_shared<HomeScreen>(x, y, w, h); } /// Initializes all views that have been added to the frame. void Init(WidgetContext *) override; void Prepare(WidgetContext *) override; ScreenUpdateMode Draw() override; private: void CreateAppButton(int16_t x, int16_t y, const std::string &name, const uint8_t *icon, WButton::handler_fun_t fun); WIconButton::ptr_t paint_button_; WIconButton::ptr_t settings_button_; bool hs_initialized_ = false; };
25.866667
72
0.710052
tomfleet
7b700b53e635d656f15d42b7debe701c25e636ab
4,975
cpp
C++
FS_Utils.cpp
Lynnvon/UnrealUtils
2fe3b00ad8e0518a47a7f6415ebabe381923b74d
[ "MIT" ]
1
2020-05-19T08:40:40.000Z
2020-05-19T08:40:40.000Z
FS_Utils.cpp
Lynnvon/UnrealUtils
2fe3b00ad8e0518a47a7f6415ebabe381923b74d
[ "MIT" ]
null
null
null
FS_Utils.cpp
Lynnvon/UnrealUtils
2fe3b00ad8e0518a47a7f6415ebabe381923b74d
[ "MIT" ]
1
2020-05-19T08:40:44.000Z
2020-05-19T08:40:44.000Z
// Copyright Shinban.Inc /*! * file FS_Utils.cpp * * author Hailiang Feng * date 2019/09/06 12:09 * * */ #include "FS_Utils.h" #include "Kismet/KismetMathLibrary.h" #include "FlightSim.h" #include "Engine/Texture2D.h" //~~~ Image Wrapper ~~~ #include "ImageUtils.h" #include "IImageWrapper.h" #include "IImageWrapperModule.h" //~~~ Image Wrapper ~~~ EVisualHelmetDirection UFS_Utils::GetAxisHelmetDirection(float Val) { static bool bDone = false; EVisualHelmetDirection dir = EVisualHelmetDirection::None; if (Val <= 1 && Val>0) { if (bDone) return dir; bDone = true; if (UKismetMathLibrary::InRange_FloatFloat(Val,0.0f,0.37f,false,false)) { dir = EVisualHelmetDirection::Right; }else if (UKismetMathLibrary::InRange_FloatFloat(Val,0.37f,0.74f,false,false)) { dir = EVisualHelmetDirection::Down; }else if(UKismetMathLibrary::InRange_FloatFloat(Val,0.74f,0.99f,false,false)) { dir = EVisualHelmetDirection::Left; } else { dir = EVisualHelmetDirection::Up; } } else { if (bDone) { dir = EVisualHelmetDirection::Origin; } bDone = false; } return dir; } FVector UFS_Utils::GetVectorBetweenTwoPointByAlpha(const FVector& Start,const FVector& End,const FVector& alpha) { float _dis = FVector::Distance(Start,End); FVector _unitVector = GetUnitVector(Start,End); FVector returnVal = FVector(_unitVector.X* _dis * alpha.X,_unitVector.Y * _dis * alpha.Y,_unitVector.Z * _dis * alpha.Z) + Start; return returnVal; } FVector UFS_Utils::GetVectorBetweenTwoPointByAlpha(const FVector& Start, const FVector& End, float alpha) { float _dis = FVector::Distance(Start,End); FVector _unitVector = GetUnitVector(Start,End); FVector returnVal = FVector(_unitVector.X* _dis * alpha,_unitVector.Y * _dis * alpha,_unitVector.Z * _dis * alpha) + Start; return returnVal; } FVector UFS_Utils::GetVectorWithCurve(const FVector& target, const FVector& curve) { return FVector(target.X*curve.X,target.Y*curve.Y,target.Z*curve.Z); } FRotator UFS_Utils::GetRotatorBetweenTwoAngleByAlpha(const FRotator& Start,const FRotator& End,const FVector& alpha) { FRotator returnVal = FMath::Lerp(Start,End,alpha.X); return returnVal; } FRotator UFS_Utils::GetRotatorBetweenTwoAngleByAlpha(const FRotator& Start, const FRotator& End, float alpha) { FRotator returnVal = FMath::Lerp(Start,End,alpha); return returnVal; } FVector UFS_Utils::GetUnitVector(const FVector& Start,const FVector& End) { return (End - Start ).GetSafeNormal(); } FRotator UFS_Utils::FindLookAtRotation(const FVector& Start, const FVector& Target) { return MakeRotFromX(Target - Start); } FRotator UFS_Utils::MakeRotFromX(const FVector& X) { return FRotationMatrix::MakeFromX(X).Rotator(); } float UFS_Utils::GetVectorLength(FVector _vector) { return _vector.Size(); } FVector UFS_Utils::RotateVectorAroundAxis(FVector InVector, float Angle, FVector Axis) { return InVector.RotateAngleAxis(Angle,Axis); } void UFS_Utils::SetRelativeLocationSmooth(USceneComponent* target, FVector newLocation,float Delta, float Speed) { FVector TargetLocation = FMath::VInterpTo(target->RelativeLocation,newLocation,Delta,Speed); target->SetRelativeLocation(TargetLocation); } UTexture2D* UFS_Utils::LoadTexture2D_FromFile(const FString& FullFilePath, EImageFormat ImageFormat, bool& IsValid, int32& Width, int32& Height) { IsValid = false; UTexture2D* LoadedT2D = NULL; IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper")); TSharedPtr<IImageWrapper> ImageWrapper = ImageWrapperModule.CreateImageWrapper(ImageFormat); //Load From File TArray<uint8> RawFileData; if (!FFileHelper::LoadFileToArray(RawFileData, *FullFilePath)) return NULL; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //Create T2D! if (ImageWrapper.IsValid() && ImageWrapper->SetCompressed(RawFileData.GetData(), RawFileData.Num())) { const TArray<uint8>* UncompressedBGRA = NULL; if (ImageWrapper->GetRaw(ERGBFormat::BGRA, 8, UncompressedBGRA)) { LoadedT2D = UTexture2D::CreateTransient(ImageWrapper->GetWidth(), ImageWrapper->GetHeight(), PF_B8G8R8A8); //Valid? if(!LoadedT2D) return NULL; //~~~~~~~~~~~~~~ //Out! Width = ImageWrapper->GetWidth(); Height = ImageWrapper->GetHeight(); //Copy! void* TextureData = LoadedT2D->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE); FMemory::Memcpy(TextureData, UncompressedBGRA->GetData(), UncompressedBGRA->Num()); LoadedT2D->PlatformData->Mips[0].BulkData.Unlock(); //Update! LoadedT2D->UpdateResource(); } } // Success! IsValid = true; return LoadedT2D; } FString UFS_Utils::GetTerrainConfigSection(FString section) { FString val; if (!GConfig) return FString(); FString RegistrySection = "Terrain"; bool isSuccess = GConfig->GetString( *RegistrySection, (TEXT("%s"), *section), val, GGameIni ); if (isSuccess) { return val; } return FString(); }
25.911458
144
0.728643
Lynnvon
7b72a3fcfc5eb6d9f1efd70ac1028c7117a6d729
1,994
cpp
C++
src/gmail/drafts/DraftsDraftResource.cpp
Vadimatorik/googleQt
814ad6f695bb8e88d6a773e69fb8c188febaab00
[ "MIT" ]
24
2016-12-03T09:12:43.000Z
2022-03-29T19:51:48.000Z
src/gmail/drafts/DraftsDraftResource.cpp
Vadimatorik/googleQt
814ad6f695bb8e88d6a773e69fb8c188febaab00
[ "MIT" ]
4
2016-12-03T09:14:42.000Z
2022-03-29T22:02:21.000Z
src/gmail/drafts/DraftsDraftResource.cpp
Vadimatorik/googleQt
814ad6f695bb8e88d6a773e69fb8c188febaab00
[ "MIT" ]
7
2018-01-01T09:14:10.000Z
2022-03-29T21:50:11.000Z
/********************************************************** DO NOT EDIT This file was generated from stone specification "drafts" Part of "Ardi - the organizer" project. [email protected] www.prokarpaty.net ***********************************************************/ #include "gmail/drafts/DraftsDraftResource.h" using namespace googleQt; namespace googleQt{ namespace drafts{ ///DraftResource DraftResource::operator QJsonObject()const{ QJsonObject js; this->toJson(js); return js; } void DraftResource::toJson(QJsonObject& js)const{ if(!m_id.isEmpty()) js["id"] = QString(m_id); js["message"] = (QJsonObject)m_message; } void DraftResource::fromJson(const QJsonObject& js){ m_id = js["id"].toString(); m_message.fromJson(js["message"].toObject()); } QString DraftResource::toString(bool multiline)const { QJsonObject js; toJson(js); QJsonDocument doc(js); QString s(doc.toJson(multiline ? QJsonDocument::Indented : QJsonDocument::Compact)); return s; } std::unique_ptr<DraftResource> DraftResource::factory::create(const QByteArray& data) { QJsonDocument doc = QJsonDocument::fromJson(data); QJsonObject js = doc.object(); return create(js); } std::unique_ptr<DraftResource> DraftResource::factory::create(const QJsonObject& js) { std::unique_ptr<DraftResource> rv; rv = std::unique_ptr<DraftResource>(new DraftResource); rv->fromJson(js); return rv; } #ifdef API_QT_AUTOTEST std::unique_ptr<DraftResource> DraftResource::EXAMPLE(int context_index, int parent_context_index){ Q_UNUSED(context_index); Q_UNUSED(parent_context_index); static int example_idx = 0; example_idx++; std::unique_ptr<DraftResource> rv(new DraftResource); rv->m_id = ApiAutotest::INSTANCE().getId("drafts::DraftResource", example_idx); rv->m_message = *(messages::MessageResource::EXAMPLE(0, context_index).get()); return rv; } #endif //API_QT_AUTOTEST }//drafts }//googleQt
25.564103
99
0.674524
Vadimatorik
7b743bec1c240137fcf927b0b1bb703d3dd22fc7
3,320
cpp
C++
main.cpp
SirJonthe/VoxelRayTrace
1c38a522e9734fcbac1ceb9c85c475a6c4709103
[ "Zlib" ]
26
2015-03-25T21:31:01.000Z
2021-11-09T11:40:45.000Z
main.cpp
SirJonthe/VoxelRayTrace
1c38a522e9734fcbac1ceb9c85c475a6c4709103
[ "Zlib" ]
1
2018-11-23T03:52:38.000Z
2018-11-24T10:39:05.000Z
main.cpp
SirJonthe/VoxelRayTrace
1c38a522e9734fcbac1ceb9c85c475a6c4709103
[ "Zlib" ]
null
null
null
#include <iostream> //#include <omp.h> #include "PlatformSDL.h" #include "Camera.h" #include "Renderer.h" #include "RobotModel.h" #include "Math3d.h" // Rudimentary OpenMP support is commented out // see main(...) and Renderer::Render(...) // see included header files in main.cpp and Renderer.cpp int main(int argc, char **argv) { if (SDL_Init(SDL_INIT_VIDEO) == -1) { std::cout << "Could not init SDL" << std::endl; return 1; } //omp_set_num_threads(omp_get_num_procs); int w = 800; int h = 600; bool fs = false; if (argc > 1 && (argc-1)%2 == 0) { for (int i = 1; i < argc; i+=2) { if (strcmp(argv[i], "-w") == 0) { w = atoi(argv[i+1]); std::cout << "width set to " << w << " from argument " << argv[i+1] << std::endl; } else if (strcmp(argv[i], "-h") == 0) { h = atoi(argv[i+1]); std::cout << "height set to " << h << " from argument " << argv[i+1] << std::endl; } else if (strcmp(argv[i], "-fs") == 0) { fs = bool( atoi(argv[i+1]) ); std::cout << "fullscreen set to " << fs << " from argument " << argv[i+1] << std::endl; } else { std::cout << "Unknown argument: " << argv[i] << std::endl; } } } Renderer renderer; if (!renderer.Init(w, h, fs)) { std::cout << "Could not init video mode" << std::endl; SDL_Quit(); return 1; } SDL_WM_SetCaption("Voxel Ray Tracing", NULL); SDL_WM_GrabInput(SDL_GRAB_ON); SDL_ShowCursor(SDL_FALSE); std::cout << "Total voxel volume: " << sizeof(Robot) << ", in bytes " << sizeof(Robot)*sizeof(Voxel) << std::endl; SDL_Event event; Camera camera(w, h); camera.SetPosition(vec3_t(8.f, 8.f, 8.f)); bool quit = false; float left = 0.f; float right = 0.f; float forward = 0.f; float backward = 0.f; float up = 0.f; float down = 0.f; while (!quit) { while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_w: forward = 1.f; break; case SDLK_a: left = 1.f; break; case SDLK_s: backward = -1.f; break; case SDLK_d: right = -1.f; break; case SDLK_q: down = 1.f; break; case SDLK_e: up = -1.f; break; case SDLK_ESCAPE: quit = true; break; default: break; } break; case SDL_QUIT: quit = true; break; case SDL_KEYUP: switch (event.key.keysym.sym) { case SDLK_w: forward = 0.f; break; case SDLK_a: left = 0.f; break; case SDLK_s: backward = 0.f; break; case SDLK_d: right = 0.f; break; case SDLK_q: down = 0.f; break; case SDLK_e: up = 0.f; break; default: break; } break; case SDL_MOUSEMOTION: camera.Turn(-event.motion.xrel * 0.01f, 0.f); break; default: break; } } const vec3_t prevCam = camera.GetPosition(); camera.Move(forward + backward, left + right, down + up); for (int i = 0; i < 3; ++i) { if (camera.GetPosition()[i] < 0 || camera.GetPosition()[i] >= 16) { camera.SetPosition(prevCam); break; } } renderer.Render(camera, Robot, RobotDim); renderer.Refresh(); } renderer.CleanUp(); SDL_Quit(); return 0; }
23.055556
116
0.544578
SirJonthe
7b7f57bcdba784ba0df008ae1a3e72f043fb74df
7,210
cpp
C++
jack/example-clients/server_control.cpp
KimJeongYeon/jack2_android
4a8787be4306558cb52e5379466c0ed4cc67e788
[ "BSD-3-Clause-No-Nuclear-Warranty" ]
47
2015-01-04T21:47:07.000Z
2022-03-23T16:27:16.000Z
vendor/samsung/external/jack/example-clients/server_control.cpp
cesarmo759/android_kernel_samsung_msm8916
f19717ef6c984b64a75ea600a735dc937b127c25
[ "Apache-2.0" ]
3
2015-02-04T21:40:11.000Z
2019-09-16T19:53:51.000Z
jack/example-clients/server_control.cpp
KimJeongYeon/jack2_android
4a8787be4306558cb52e5379466c0ed4cc67e788
[ "BSD-3-Clause-No-Nuclear-Warranty" ]
7
2015-05-17T08:22:52.000Z
2021-08-07T22:36:17.000Z
/* Copyright (C) 2008 Grame This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdio.h> #include <errno.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <getopt.h> #include <jack/jack.h> #include <jack/control.h> static jackctl_driver_t * jackctl_server_get_driver(jackctl_server_t *server, const char *driver_name) { const JSList * node_ptr = jackctl_server_get_drivers_list(server); while (node_ptr) { if (strcmp(jackctl_driver_get_name((jackctl_driver_t *)node_ptr->data), driver_name) == 0) { return (jackctl_driver_t *)node_ptr->data; } node_ptr = jack_slist_next(node_ptr); } return NULL; } static jackctl_internal_t * jackctl_server_get_internal(jackctl_server_t *server, const char *internal_name) { const JSList * node_ptr = jackctl_server_get_internals_list(server); while (node_ptr) { if (strcmp(jackctl_internal_get_name((jackctl_internal_t *)node_ptr->data), internal_name) == 0) { return (jackctl_internal_t *)node_ptr->data; } node_ptr = jack_slist_next(node_ptr); } return NULL; } #if 0 static jackctl_parameter_t * jackctl_get_parameter( const JSList * parameters_list, const char * parameter_name) { while (parameters_list) { if (strcmp(jackctl_parameter_get_name((jackctl_parameter_t *)parameters_list->data), parameter_name) == 0) { return (jackctl_parameter_t *)parameters_list->data; } parameters_list = jack_slist_next(parameters_list); } return NULL; } #endif static void print_value(union jackctl_parameter_value value, jackctl_param_type_t type) { switch (type) { case JackParamInt: printf("parameter value = %d\n", value.i); break; case JackParamUInt: printf("parameter value = %u\n", value.ui); break; case JackParamChar: printf("parameter value = %c\n", value.c); break; case JackParamString: printf("parameter value = %s\n", value.str); break; case JackParamBool: printf("parameter value = %d\n", value.b); break; } } static void print_parameters(const JSList * node_ptr) { while (node_ptr != NULL) { jackctl_parameter_t * parameter = (jackctl_parameter_t *)node_ptr->data; printf("\nparameter name = %s\n", jackctl_parameter_get_name(parameter)); printf("parameter id = %c\n", jackctl_parameter_get_id(parameter)); printf("parameter short decs = %s\n", jackctl_parameter_get_short_description(parameter)); printf("parameter long decs = %s\n", jackctl_parameter_get_long_description(parameter)); print_value(jackctl_parameter_get_default_value(parameter), jackctl_parameter_get_type(parameter)); node_ptr = jack_slist_next(node_ptr); } } static void print_driver(jackctl_driver_t * driver) { printf("\n--------------------------\n"); printf("driver = %s\n", jackctl_driver_get_name(driver)); printf("-------------------------- \n"); print_parameters(jackctl_driver_get_parameters(driver)); } static void print_internal(jackctl_internal_t * internal) { printf("\n-------------------------- \n"); printf("internal = %s\n", jackctl_internal_get_name(internal)); printf("-------------------------- \n"); print_parameters(jackctl_internal_get_parameters(internal)); } static void usage() { fprintf (stderr, "\n" "usage: jack_server_control \n" " [ --driver OR -d driver_name ]\n" " [ --client OR -c client_name ]\n" ); } int main(int argc, char *argv[]) { jackctl_server_t * server; const JSList * parameters; const JSList * drivers; const JSList * internals; const JSList * node_ptr; jackctl_sigmask_t * sigmask; int opt, option_index; const char* driver_name = "dummy"; const char* client_name = "audioadapter"; const char *options = "d:c:"; struct option long_options[] = { {"driver", 1, 0, 'd'}, {"client", 1, 0, 'c'}, {0, 0, 0, 0} }; while ((opt = getopt_long (argc, argv, options, long_options, &option_index)) != -1) { switch (opt) { case 'd': driver_name = optarg; break; case 'c': client_name = optarg; break; default: usage(); exit(0); } } server = jackctl_server_create(NULL, NULL); parameters = jackctl_server_get_parameters(server); /* jackctl_parameter_t* param; union jackctl_parameter_value value; param = jackctl_get_parameter(parameters, "verbose"); if (param != NULL) { value.b = true; jackctl_parameter_set_value(param, &value); } */ printf("\n========================== \n"); printf("List of server parameters \n"); printf("========================== \n"); print_parameters(parameters); printf("\n========================== \n"); printf("List of drivers \n"); printf("========================== \n"); drivers = jackctl_server_get_drivers_list(server); node_ptr = drivers; while (node_ptr != NULL) { print_driver((jackctl_driver_t *)node_ptr->data); node_ptr = jack_slist_next(node_ptr); } printf("\n========================== \n"); printf("List of internal clients \n"); printf("========================== \n"); internals = jackctl_server_get_internals_list(server); node_ptr = internals; while (node_ptr != NULL) { print_internal((jackctl_internal_t *)node_ptr->data); node_ptr = jack_slist_next(node_ptr); } // No error checking in this simple example... jackctl_server_open(server, jackctl_server_get_driver(server, driver_name)); jackctl_server_start(server); jackctl_server_load_internal(server, jackctl_server_get_internal(server, client_name)); /* // Switch master test jackctl_driver_t* master; usleep(5000000); printf("jackctl_server_load_master\n"); master = jackctl_server_get_driver(server, "coreaudio"); jackctl_server_switch_master(server, master); usleep(5000000); printf("jackctl_server_load_master\n"); master = jackctl_server_get_driver(server, "dummy"); jackctl_server_switch_master(server, master); */ sigmask = jackctl_setup_signals(0); jackctl_wait_signals(sigmask); jackctl_server_stop(server); jackctl_server_close(server); jackctl_server_destroy(server); return 0; }
29.428571
114
0.639528
KimJeongYeon
7b8c29d6976b119fe36a5f69a133ccaaf05316aa
5,980
cpp
C++
MMOCoreORB/src/server/zone/managers/creature/SpawnAreaMap.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/src/server/zone/managers/creature/SpawnAreaMap.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/src/server/zone/managers/creature/SpawnAreaMap.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
/* * SpawnAreaMap.cpp * * Created on: 12/08/2011 * Author: TheAnswer */ #include "SpawnAreaMap.h" #include "server/zone/Zone.h" #include "server/zone/managers/object/ObjectManager.h" #include "server/zone/objects/area/areashapes/CircularAreaShape.h" #include "server/zone/objects/area/areashapes/RectangularAreaShape.h" #include "server/zone/objects/area/areashapes/RingAreaShape.h" void SpawnAreaMap::loadMap(Zone* z) { zone = z; String planetName = zone->getZoneName(); setLoggingName("SpawnAreaMap " + planetName); lua->init(); try { loadRegions(); } catch (Exception& e) { error(e.getMessage()); } lua->deinit(); lua = nullptr; } void SpawnAreaMap::loadRegions() { String planetName = zone->getZoneName(); lua->runFile("scripts/managers/spawn_manager/" + planetName + "_regions.lua"); LuaObject obj = lua->getGlobalObject(planetName + "_regions"); if (obj.isValidTable()) { info("loading spawn areas...", true); lua_State* s = obj.getLuaState(); for (int i = 1; i <= obj.getTableSize(); ++i) { lua_rawgeti(s, -1, i); LuaObject areaObj(s); if (areaObj.isValidTable()) { readAreaObject(areaObj); } areaObj.pop(); } } obj.pop(); for (int i = 0; i < size(); ++i) { SpawnArea* area = get(i); Locker locker(area); for (int j = 0; j < noSpawnAreas.size(); ++j) { SpawnArea* notHere = noSpawnAreas.get(j); if (area->intersectsWith(notHere)) { area->addNoSpawnArea(notHere); } } } } void SpawnAreaMap::readAreaObject(LuaObject& areaObj) { String name = areaObj.getStringAt(1); float x = areaObj.getFloatAt(2); float y = areaObj.getFloatAt(3); int tier = areaObj.getIntAt(5); if (tier == UNDEFINEDAREA) return; float radius = 0; float x2 = 0; float y2 = 0; float innerRadius = 0; float outerRadius = 0; LuaObject areaShapeObject = areaObj.getObjectAt(4); if (!areaShapeObject.isValidTable()) { error("Invalid area shape table for spawn region " + name); return; } int areaType = areaShapeObject.getIntAt(1); if (areaType == CIRCLE) { radius = areaShapeObject.getFloatAt(2); if (radius <= 0 && !(tier & WORLDSPAWNAREA)) { error("Invalid radius of " + String::valueOf(radius) + " must be > 0 for circular spawn region " + name); return; } } else if (areaType == RECTANGLE) { x2 = areaShapeObject.getFloatAt(2); y2 = areaShapeObject.getFloatAt(3); int rectWidth = x2 - x; int rectHeight = y2 - y; if (!(tier & WORLDSPAWNAREA) && (rectWidth <= 0 || rectHeight <= 0)) { error("Invalid corner coordinates for rectangular spawn region " + name + ", total height: " + String::valueOf(rectHeight) + ", total width: " + String::valueOf(rectWidth)); return; } } else if (areaType == RING) { innerRadius = areaShapeObject.getFloatAt(2); outerRadius = areaShapeObject.getFloatAt(3); if (!(tier & WORLDSPAWNAREA)) { if (innerRadius <= 0) { error("Invalid inner radius of " + String::valueOf(innerRadius) + " must be > 0 for ring spawn region " + name); return; } else if (outerRadius <= 0) { error("Invalid outer radius of " + String::valueOf(outerRadius) + " must be > 0 for ring spawn region " + name); return; } } } else { error("Invalid area type of " + String::valueOf(areaType) + " for spawn region " + name); return; } areaShapeObject.pop(); if (radius == 0 && x2 == 0 && y2 == 0 && innerRadius == 0 && outerRadius == 0) return; static const uint32 crc = STRING_HASHCODE("object/spawn_area.iff"); ManagedReference<SpawnArea*> area = dynamic_cast<SpawnArea*>(ObjectManager::instance()->createObject(crc, 0, "spawnareas")); if (area == nullptr) return; Locker objLocker(area); StringId nameID(zone->getZoneName() + "_region_names", name); area->setObjectName(nameID, false); if (areaType == RECTANGLE) { ManagedReference<RectangularAreaShape*> rectangularAreaShape = new RectangularAreaShape(); Locker shapeLocker(rectangularAreaShape); rectangularAreaShape->setDimensions(x, y, x2, y2); float centerX = x + ((x2 - x) / 2); float centerY = y + ((y2 - y) / 2); rectangularAreaShape->setAreaCenter(centerX, centerY); area->setAreaShape(rectangularAreaShape); } else if (areaType == CIRCLE) { ManagedReference<CircularAreaShape*> circularAreaShape = new CircularAreaShape(); Locker shapeLocker(circularAreaShape); circularAreaShape->setAreaCenter(x, y); if (radius > 0) circularAreaShape->setRadius(radius); else circularAreaShape->setRadius(zone->getBoundingRadius()); area->setAreaShape(circularAreaShape); } else if (areaType == RING) { ManagedReference<RingAreaShape*> ringAreaShape = new RingAreaShape(); Locker shapeLocker(ringAreaShape); ringAreaShape->setAreaCenter(x, y); ringAreaShape->setInnerRadius(innerRadius); ringAreaShape->setOuterRadius(outerRadius); area->setAreaShape(ringAreaShape); } area->setTier(tier); area->initializePosition(x, 0, y); if (tier & SPAWNAREA) { area->setMaxSpawnLimit(areaObj.getIntAt(7)); LuaObject spawnGroups = areaObj.getObjectAt(6); if (spawnGroups.isValidTable()) { Vector<uint32> groups; for (int i = 1; i <= spawnGroups.getTableSize(); i++) { groups.add(spawnGroups.getStringAt(i).hashCode()); } area->buildSpawnList(&groups); } spawnGroups.pop(); } if ((radius != -1) && !(tier & WORLDSPAWNAREA)) { zone->transferObject(area, -1, true); } else { if (tier & WORLDSPAWNAREA) { worldSpawnAreas.add(area); } area->setZone(zone); } area->updateToDatabase(); put(nameID.getStringID().hashCode(), area); if (tier & NOSPAWNAREA) { area->setNoSpawnArea(true); noSpawnAreas.add(area); } if (tier & NOBUILDZONEAREA) { area->setNoBuildArea(true); } } void SpawnAreaMap::unloadMap() { noSpawnAreas.removeAll(); worldSpawnAreas.removeAll(); for (int i = 0; i < size(); i++) { SpawnArea* area = get(i); if (area != nullptr) { Locker locker(area); area->destroyObjectFromWorld(false); } } removeAll(); }
25.232068
176
0.675585
V-Fib
7b92b68a537bf7fc0530c0f58ed4eead3c953bc6
3,896
cpp
C++
imove_peopleextractor/src/ImageProcessing/PeopleExtractor.cpp
fbredius/IMOVE
912b4d0696e88acfc0ce7bc556eecf8fc423c4d3
[ "MIT" ]
3
2018-04-24T10:04:37.000Z
2018-05-11T08:27:03.000Z
imove_peopleextractor/src/ImageProcessing/PeopleExtractor.cpp
fbredius/IMOVE
912b4d0696e88acfc0ce7bc556eecf8fc423c4d3
[ "MIT" ]
null
null
null
imove_peopleextractor/src/ImageProcessing/PeopleExtractor.cpp
fbredius/IMOVE
912b4d0696e88acfc0ce7bc556eecf8fc423c4d3
[ "MIT" ]
3
2018-05-16T08:44:19.000Z
2020-12-04T16:04:32.000Z
#include "PeopleExtractor.h" // PeopleExtractor::PeopleExtractor(const cv::Size& frame_size, float pixels_per_meter, float resolution_resize_height, const Boundary& boundary) { PeopleExtractor::PeopleExtractor(CameraConfiguration* camConfig) { // Get values from camera configuration frame_size = camConfig->getResolution(); float pixels_per_meter = camConfig->getMeter(); Boundary boundary = camConfig->getProjection().createReorientedTopLeftBoundary(); // Calculate resize ratio resize_ratio = 1; // Initialize empty frame frame = cv::Mat::zeros(frame_size.height, frame_size.width, CV_8UC1); // Initialize Detector detector = PeopleDetector(pixels_per_meter, camConfig->getMinBlobArea(), camConfig->getMinBlobDistance()); // Initialize projector boundary Boundary proj_bound = Boundary(Vector2(boundary.getUpperLeft().x, boundary.getUpperLeft().y), Vector2(boundary.getUpperRight().x, boundary.getUpperRight().y), Vector2(boundary.getLowerLeft().x, boundary.getLowerLeft().y), Vector2(boundary.getLowerRight().x, boundary.getLowerRight().y)); // Initialize Identifier identifier = PeopleIdentifier(proj_bound); } PeopleExtractor::~PeopleExtractor() {} const scene_interface::People PeopleExtractor::extractPeople(cv::Mat& new_frame) { // Convert frame to grayscale //cvtColor(new_frame, new_frame, CV_RGB2GRAY); // Downscale frame resize(new_frame, new_frame, frame_size); // Start working with new frame frame = new_frame; // Get a vector with every Person in the Scene, generated by the Identifier from the locations provided by the Detector std::vector<Vector2> locations = detector.detect(frame); std::vector<Person> people = identifier.match(locations); debug_frame = detector.getDisplayFrame(); // Rescale location of every person based on downscaling for (Person& p : people) { Vector2 location = p.getLocation(); //cv::putText(debug_frame, std::to_string(p.getId()), cv::Point(location.x, location.y), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(0, 0, 255)); p.setLocation(Vector2(location.x*resize_ratio,location.y*resize_ratio)); } // Convert people to Person class from scene interface scene_interface::People converted_people = convert(people); // Return all extracted people return converted_people; } const scene_interface::People PeopleExtractor::convert(std::vector<Person>& people) { scene_interface::People interface_people; for (Person person : people) { // Check person type scene_interface::Person::PersonType interface_person_type; switch (person.person_type) { case Person::PersonType::Bystander: interface_person_type = scene_interface::Person::PersonType::Bystander; break; case Person::PersonType::Participant: interface_person_type = scene_interface::Person::PersonType::Participant; break; case Person::PersonType::None: interface_person_type = scene_interface::Person::PersonType::None; break; } // Check movement type scene_interface::Person::MovementType interface_movement_type; switch (person.movement_type) { case Person::MovementType::StandingStill: interface_movement_type = scene_interface::Person::MovementType::StandingStill; break; case Person::MovementType::Moving: interface_movement_type = scene_interface::Person::MovementType::Moving; break; } Vector2 location = person.getLocation(); // Add converted person to interface_people interface_people.push_back(scene_interface::Person( person.getId(), scene_interface::Location( location.x, location.y ), interface_person_type, interface_movement_type )); } return interface_people; } const cv::Mat PeopleExtractor::getDebugFrame() const { return debug_frame; }
37.825243
147
0.728183
fbredius
7b9a3720b498e04ab54ebadc197a08c67a67d944
1,118
cpp
C++
src/reader.cpp
data-bridge/build
1bd37f7061d9bd5caf0c1bd9c5cbbd85c7a45486
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
src/reader.cpp
data-bridge/build
1bd37f7061d9bd5caf0c1bd9c5cbbd85c7a45486
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
src/reader.cpp
data-bridge/build
1bd37f7061d9bd5caf0c1bd9c5cbbd85c7a45486
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
/* Part of BridgeData. Copyright (C) 2016-17 by Soren Hein. See LICENSE and README. */ #include <iostream> #if defined(_WIN32) && defined(__MINGW32__) #include "mingw.thread.h" #else #include <thread> #endif #include "args.h" #include "Files.h" #include "AllStats.h" #include "dispatch.h" using namespace std; int main(int argc, char * argv[]) { Options options; readArgs(argc, argv, options); setTables(); Files files; files.set(options); vector<thread> thr(options.numThreads); vector<AllStats> allStatsList(options.numThreads); Timer timer; timer.start(); for (unsigned i = 0; i < options.numThreads; i++) thr[i] = thread(dispatch, i, ref(files), options, ref(allStatsList[i])); for (unsigned i = 0; i < options.numThreads; i++) thr[i].join(); mergeResults(allStatsList, options); printResults(allStatsList[0], options); if (options.solveFlag) files.writeDDInfo(BRIDGE_DD_INFO_SOLVE); if (options.traceFlag) files.writeDDInfo(BRIDGE_DD_INFO_TRACE); timer.stop(); cout << "Time spent overall (elapsed): " << timer.str(2) << "\n"; }
18.327869
76
0.67263
data-bridge
7b9e10ab1ad581b173f46315189e82526dcb0bdb
10,190
cpp
C++
tests/src/json_stream_reader_tests.cpp
Cebtenzzre/jsoncons
2301edbad93265a4f64c74609bc944cd279eb2a7
[ "BSL-1.0" ]
null
null
null
tests/src/json_stream_reader_tests.cpp
Cebtenzzre/jsoncons
2301edbad93265a4f64c74609bc944cd279eb2a7
[ "BSL-1.0" ]
null
null
null
tests/src/json_stream_reader_tests.cpp
Cebtenzzre/jsoncons
2301edbad93265a4f64c74609bc944cd279eb2a7
[ "BSL-1.0" ]
null
null
null
// Copyright 2018 Daniel Parker // Distributed under Boost license #include <catch/catch.hpp> #include <jsoncons/json.hpp> #include <jsoncons/json_serializer.hpp> #include <jsoncons/json_stream_reader.hpp> #include <sstream> #include <vector> #include <utility> #include <ctime> using namespace jsoncons; TEST_CASE("json_stream_reader string_value test") { std::string s = R"("Tom")"; std::istringstream is(s); json_stream_reader reader(is); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::string_value); CHECK(reader.current().as<std::string>() == std::string("Tom")); CHECK(reader.current().as<jsoncons::string_view>() == jsoncons::string_view("Tom")); reader.next(); CHECK(reader.done()); } TEST_CASE("json_stream_reader string_value as<int> test") { std::string s = R"("-100")"; std::istringstream is(s); json_stream_reader reader(is); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::string_value); CHECK(reader.current().as<int>() == -100); reader.next(); CHECK(reader.done()); } TEST_CASE("json_stream_reader string_value as<unsigned> test") { std::string s = R"("100")"; std::istringstream is(s); json_stream_reader reader(is); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::string_value); CHECK(reader.current().as<int>() == 100); CHECK(reader.current().as<unsigned>() == 100); reader.next(); CHECK(reader.done()); } TEST_CASE("json_stream_reader null_value test") { std::string s = "null"; std::istringstream is(s); json_stream_reader reader(is); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::null_value); reader.next(); CHECK(reader.done()); } TEST_CASE("json_stream_reader bool_value test") { std::string s = "false"; std::istringstream is(s); json_stream_reader reader(is); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::bool_value); reader.next(); CHECK(reader.done()); } TEST_CASE("json_stream_reader int64_value test") { std::string s = "-100"; std::istringstream is(s); json_stream_reader reader(is); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::int64_value); CHECK(reader.current().as<int>() == -100); reader.next(); CHECK(reader.done()); } TEST_CASE("json_stream_reader uint64_value test") { std::string s = "100"; std::istringstream is(s); json_stream_reader reader(is); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::uint64_value); CHECK(reader.current().as<int>() == 100); CHECK(reader.current().as<unsigned>() == 100); reader.next(); CHECK(reader.done()); } TEST_CASE("json_stream_reader bignum_value test") { std::string s = "-18446744073709551617"; std::istringstream is(s); json_stream_reader reader(is); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::bignum_value); reader.next(); CHECK(reader.done()); } TEST_CASE("json_stream_reader double_value test") { std::string s = "100.0"; std::istringstream is(s); json_stream_reader reader(is); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::double_value); reader.next(); CHECK(reader.done()); } TEST_CASE("json_stream_reader array_value test") { std::string s = R"( [ { "enrollmentNo" : 100, "firstName" : "Tom", "lastName" : "Cochrane", "mark" : 55 }, { "enrollmentNo" : 101, "firstName" : "Catherine", "lastName" : "Smith", "mark" : 95}, { "enrollmentNo" : 102, "firstName" : "William", "lastName" : "Skeleton", "mark" : 60 } ] )"; std::istringstream is(s); json_stream_reader reader(is); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::begin_array); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::begin_object); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::name); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::uint64_value); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::name); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::string_value); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::name); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::string_value); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::name); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::uint64_value); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::end_object); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::begin_object); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::name); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::uint64_value); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::name); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::string_value); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::name); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::string_value); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::name); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::uint64_value); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::end_object); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::begin_object); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::name); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::uint64_value); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::name); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::string_value); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::name); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::string_value); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::name); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::uint64_value); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::end_object); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::end_array); reader.next(); CHECK(reader.done()); } TEST_CASE("json_stream_reader object_value test") { std::string s = R"( { "enrollmentNo" : 100, "firstName" : "Tom", "lastName" : "Cochrane", "mark" : 55 }, { "enrollmentNo" : 101, "firstName" : "Catherine", "lastName" : "Smith", "mark" : 95}, { "enrollmentNo" : 102, "firstName" : "William", "lastName" : "Skeleton", "mark" : 60 } )"; std::istringstream is(s); json_stream_reader reader(is); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::begin_object); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::name); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::uint64_value); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::name); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::string_value); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::name); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::string_value); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::name); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::uint64_value); reader.next(); REQUIRE_FALSE(reader.done()); CHECK(reader.current().event_type() == stream_event_type::end_object); reader.next(); CHECK(reader.done()); }
30.972644
88
0.644259
Cebtenzzre
7ba2da4ac00956231e3ccac5506bdc31a1cce4f8
4,939
cc
C++
src/sdk/test/batch_muation_test.cc
cuisonghui/tera
99a3f16de13dd454a64d64e938fcfeb030674d5f
[ "Apache-2.0", "BSD-3-Clause" ]
2,003
2015-07-13T08:36:45.000Z
2022-03-26T02:10:07.000Z
src/sdk/test/batch_muation_test.cc
a1e2w3/tera
dbcd28af792d879d961bf9fc7eb60de81b437646
[ "Apache-2.0", "BSD-3-Clause" ]
981
2015-07-14T00:03:24.000Z
2021-05-10T09:50:01.000Z
src/sdk/test/batch_muation_test.cc
a1e2w3/tera
dbcd28af792d879d961bf9fc7eb60de81b437646
[ "Apache-2.0", "BSD-3-Clause" ]
461
2015-07-14T02:53:35.000Z
2022-03-10T10:31:49.000Z
// Copyright (c) 2015-2018, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: [email protected] #include <atomic> #include <iostream> #include <string> #include <thread> #include <memory> #include "gflags/gflags.h" #include "glog/logging.h" #include "gtest/gtest.h" #include "sdk/batch_mutation_impl.h" #include "tera.h" #include "sdk/sdk_task.h" #include "sdk/sdk_zk.h" #include "sdk/table_impl.h" #include "sdk/test/mock_table.h" #include "tera.h" DECLARE_string(tera_coord_type); namespace tera { class BatchMutationTest : public ::testing::Test { public: BatchMutationTest() : batch_mu_(NULL) { batch_mu_ = static_cast<BatchMutationImpl*>(OpenTable("batch_mu_test")->NewBatchMutation()); } virtual ~BatchMutationTest() {} std::shared_ptr<Table> OpenTable(const std::string& tablename) { FLAGS_tera_coord_type = "fake_zk"; std::shared_ptr<MockTable> table_(new MockTable(tablename, &thread_pool_)); return table_; } BatchMutationImpl* batch_mu_; common::ThreadPool thread_pool_; }; TEST_F(BatchMutationTest, Put0) { batch_mu_->Put("rowkey", "value", 12); batch_mu_->Put("rowkey", "value1", 22); EXPECT_EQ(batch_mu_->mu_map_.size(), 1); EXPECT_EQ(batch_mu_->GetRows().size(), 1); } TEST_F(BatchMutationTest, Put1) { batch_mu_->Put("rowkey", "value", 12); batch_mu_->Put("rowkey1", "value1", 22); EXPECT_EQ(batch_mu_->mu_map_.size(), 2); EXPECT_EQ(batch_mu_->GetRows().size(), 2); } TEST_F(BatchMutationTest, Put2) { batch_mu_->Put("rowkey", "cf", "qu", "value"); batch_mu_->Put("rowkey", "", "qu", "value"); batch_mu_->Put("rowkey2", "cf", "", "value"); batch_mu_->Put("rowkey3", "", "", "value"); batch_mu_->Put("rowkey4", "cf", "qu", "value", 0); batch_mu_->Put("rowkey5", "cf", "qu", "value", 1); batch_mu_->Put("rowkey6", "cf", "qu", "value", -1); EXPECT_EQ(batch_mu_->mu_map_.size(), 6); EXPECT_EQ(batch_mu_->GetRows().size(), 6); EXPECT_EQ(batch_mu_->mu_map_["rowkey"].size(), 2); EXPECT_EQ(batch_mu_->mu_map_["rowkey1"].size(), 0); } TEST_F(BatchMutationTest, OtherOps) { batch_mu_->Add("rowkey", "cf", "qu", 12); EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().type, RowMutation::kAdd); batch_mu_->PutIfAbsent("rowkey", "cf", "qu", "value"); EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().type, RowMutation::kPutIfAbsent); batch_mu_->Append("rowkey", "cf", "qu", "value"); EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().type, RowMutation::kAppend); batch_mu_->DeleteRow("rowkey"); EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().type, RowMutation::kDeleteRow); EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().timestamp, kLatestTimestamp); batch_mu_->DeleteFamily("rowkey", "cf"); EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().type, RowMutation::kDeleteFamily); EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().timestamp, kLatestTimestamp); batch_mu_->DeleteColumns("rowkey", "cf", "qu"); EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().type, RowMutation::kDeleteColumns); EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().timestamp, kLatestTimestamp); batch_mu_->DeleteColumn("rowkey", "cf", "qu", -1); EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().type, RowMutation::kDeleteColumn); EXPECT_EQ(batch_mu_->mu_map_["rowkey"].back().timestamp, kLatestTimestamp); const std::string& huge_str = std::string(1 + (32 << 20), 'h'); batch_mu_->Put(huge_str, "cf", "qu", "v"); EXPECT_EQ(batch_mu_->GetError().GetType(), ErrorCode::kBadParam); batch_mu_->Put("r", "cf", huge_str, "v"); EXPECT_EQ(batch_mu_->GetError().GetType(), ErrorCode::kBadParam); batch_mu_->Put("r", "cf", "qu", huge_str); EXPECT_EQ(batch_mu_->GetError().GetType(), ErrorCode::kBadParam); } void MockOpStatCallback(Table* table, SdkTask* task) { // Nothing to do } TEST_F(BatchMutationTest, RunCallback) { EXPECT_FALSE(batch_mu_->IsAsync()); std::shared_ptr<Table> table = OpenTable("test"); batch_mu_->Prepare(MockOpStatCallback); EXPECT_TRUE(batch_mu_->on_finish_callback_ != NULL); EXPECT_TRUE(batch_mu_->start_ts_ > 0); // set OpStatCallback batch_mu_->RunCallback(); EXPECT_TRUE(batch_mu_->finish_); EXPECT_TRUE(batch_mu_->IsFinished()); } TEST_F(BatchMutationTest, Size) { EXPECT_EQ(batch_mu_->Size(), 0); int64_t ts = -1; batch_mu_->Put("r", "cf", "qu", "v"); EXPECT_EQ(batch_mu_->Size(), 6 + sizeof(ts)); batch_mu_->Put("r", "cf", "qu", "v"); // only calc one rowkey EXPECT_EQ(batch_mu_->Size(), (6 + sizeof(ts)) * 2 - 1); batch_mu_->Put("R", "cf", "qu", "v"); EXPECT_EQ(batch_mu_->Size(), (6 + sizeof(ts)) * 3 - 1); } TEST_F(BatchMutationTest, GetMutation) { batch_mu_->Put("r", "cf", "qu", "v"); batch_mu_->Put("r", "cf", "qu1", "v"); batch_mu_->Put("r2", "cf", "qu", "v"); batch_mu_->Put("r3", "cf", "qu", "v"); EXPECT_EQ((batch_mu_->GetMutation("r", 1)).qualifier, "qu1"); } }
33.828767
96
0.678072
cuisonghui
7babe23056c9b996729ed10b7e0de941c3ebd3f5
3,523
cpp
C++
lib/ipv4addr.cpp
reroman/libreroarp
f269fda1260ff42f688258c95504ded318c5a3a8
[ "BSD-3-Clause" ]
null
null
null
lib/ipv4addr.cpp
reroman/libreroarp
f269fda1260ff42f688258c95504ded318c5a3a8
[ "BSD-3-Clause" ]
null
null
null
lib/ipv4addr.cpp
reroman/libreroarp
f269fda1260ff42f688258c95504ded318c5a3a8
[ "BSD-3-Clause" ]
null
null
null
#include <reroman/ipv4addr.hpp> #include <stdexcept> #include <system_error> #include <cerrno> #include <cstring> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <net/if.h> using namespace std; using namespace reroman; IPv4Addr::IPv4Addr( uint32_t addr ) noexcept : data( {addr} ){} IPv4Addr::IPv4Addr( string addr ) { setAddr( addr ); } IPv4Addr::IPv4Addr( struct in_addr addr ) noexcept : data( addr ){} IPv4Addr::IPv4Addr( const IPv4Addr &addr ) noexcept : data( addr.data ){} string IPv4Addr::toString( void ) const { char tmp[INET_ADDRSTRLEN]; inet_ntop( AF_INET, &data, tmp, INET_ADDRSTRLEN ); return string( tmp ); } bool IPv4Addr::isValidNetmask( void ) const noexcept { uint32_t a = ntohl( data.s_addr ); if( !a || (a & 0xff) >= 254 ) return false; a = ~a; uint32_t b = a + 1; return !( b & a ); } void IPv4Addr::setAddr( string addr ) { if( !inet_aton( addr.c_str(), &data ) ) throw invalid_argument( addr + " is not a valid IPv4 address" ); } IPv4Addr IPv4Addr::operator+( int n ) const { int64_t tmp = ntohl( data.s_addr ); tmp += n; if( tmp > 0xffffffff ) throw overflow_error( "IPv4 overflow" ); if( tmp < 0 ) throw underflow_error( "IPv4 underflow" ); return IPv4Addr( htonl( static_cast<uint32_t>(tmp) ) ); } IPv4Addr IPv4Addr::operator-( int n ) const { int64_t tmp = ntohl( data.s_addr ); tmp -= n; if( tmp > 0xffffffff ) throw overflow_error( "IPv4 overflow" ); if( tmp < 0 ) throw underflow_error( "IPv4 underflow" ); return IPv4Addr( htonl( static_cast<uint32_t>(tmp) ) ); } IPv4Addr& IPv4Addr::operator++( void ) { int64_t tmp = ntohl( data.s_addr ); tmp++; if( tmp > 0xffffffff ) throw overflow_error( "IPv4 overflow" ); data.s_addr = htonl( tmp ); return *this; } IPv4Addr IPv4Addr::operator++( int ) { IPv4Addr res( *this ); int64_t tmp = ntohl( data.s_addr ); tmp++; if( tmp > 0xffffffff ) throw overflow_error( "IPv4 overflow" ); data.s_addr = htonl( tmp ); return res; } IPv4Addr& IPv4Addr::operator--( void ) { int64_t tmp = ntohl( data.s_addr ); tmp--; if( tmp < 0 ) throw underflow_error( "IPv4 underflow" ); data.s_addr = htonl( tmp ); return *this; } IPv4Addr IPv4Addr::operator--( int ) { IPv4Addr res( *this ); int64_t tmp = ntohl( data.s_addr ); tmp--; if( tmp < 0 ) throw underflow_error( "IPv4 underflow" ); data.s_addr = htonl( tmp ); return res; } IPv4Addr IPv4Addr::getFromInterface( string ifname ) { int sockfd; struct ifreq nic; if( (sockfd = socket( AF_INET, SOCK_DGRAM, 0 )) < 0 ) throw system_error( errno, generic_category(), "socket" ); if( ifname.size() >= IFNAMSIZ ) ifname.resize( IFNAMSIZ - 1 ); strcpy( nic.ifr_name, ifname.c_str() ); if( ioctl( sockfd, SIOCGIFADDR, &nic ) < 0 ){ close( sockfd ); throw system_error( errno, generic_category(), ifname ); } IPv4Addr result( ((sockaddr_in*)&nic.ifr_addr)->sin_addr ); close( sockfd ); return result; } IPv4Addr IPv4Addr::getNmaskFromInterface( string ifname ) { int sockfd; struct ifreq nic; if( (sockfd = socket( AF_INET, SOCK_DGRAM, 0 )) < 0 ) throw system_error( errno, generic_category(), "socket" ); if( ifname.size() >= IFNAMSIZ ) ifname.resize( IFNAMSIZ - 1 ); strcpy( nic.ifr_name, ifname.c_str() ); if( ioctl( sockfd, SIOCGIFNETMASK, &nic ) < 0 ){ close( sockfd ); throw system_error( errno, generic_category(), ifname ); } IPv4Addr result( ((sockaddr_in*)&nic.ifr_netmask)->sin_addr ); close( sockfd ); return result; }
20.017045
66
0.665626
reroman
7bb4842f206386551cbb595198813881c22b5ce2
599
hpp
C++
Source/Ilum/Geometry/Mesh/Process/Parameterization.hpp
Chaf-Libraries/Ilum
83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8
[ "MIT" ]
11
2022-01-09T05:32:56.000Z
2022-03-28T06:35:16.000Z
Source/Ilum/Geometry/Mesh/Process/Parameterization.hpp
Chaf-Libraries/Ilum
83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8
[ "MIT" ]
null
null
null
Source/Ilum/Geometry/Mesh/Process/Parameterization.hpp
Chaf-Libraries/Ilum
83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8
[ "MIT" ]
1
2021-11-20T15:39:03.000Z
2021-11-20T15:39:03.000Z
#pragma once #include "IMeshProcess.hpp" namespace Ilum::geometry { class Parameterization : public IMeshProcess { public: enum class TutteWeightType { Uniform, Cotangent, ShapePreserving }; static std::pair<std::vector<Vertex>, std::vector<uint32_t>> MinimumSurface(const std::vector<Vertex> &in_vertices, const std::vector<uint32_t> &in_indices); static std::pair<std::vector<Vertex>, std::vector<uint32_t>> TutteParameterization(const std::vector<Vertex> &in_vertices, const std::vector<uint32_t> &in_indices, TutteWeightType weight_type); }; } // namespace Ilum::geometry
28.52381
194
0.752922
Chaf-Libraries
7bb8ee6ab7343c12d49cce4f1ddd761d109e8fab
687
hpp
C++
test/mock/core/runtime/core_factory_mock.hpp
igor-egorov/kagome
b2a77061791aa7c1eea174246ddc02ef5be1b605
[ "Apache-2.0" ]
null
null
null
test/mock/core/runtime/core_factory_mock.hpp
igor-egorov/kagome
b2a77061791aa7c1eea174246ddc02ef5be1b605
[ "Apache-2.0" ]
null
null
null
test/mock/core/runtime/core_factory_mock.hpp
igor-egorov/kagome
b2a77061791aa7c1eea174246ddc02ef5be1b605
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef KAGOME_CORE_FACTORY_MOCK_HPP #define KAGOME_CORE_FACTORY_MOCK_HPP #include "runtime/binaryen/core_factory.hpp" #include <gmock/gmock.h> namespace kagome::runtime::binaryen { class CoreFactoryMock : public CoreFactory { public: ~CoreFactoryMock() override = default; MOCK_METHOD2( createWithCode, std::unique_ptr<Core>( std::shared_ptr<RuntimeEnvironmentFactory> runtime_env_factory, std::shared_ptr<WasmProvider> wasm_provider)); }; } // namespace kagome::runtime::binaryen #endif // KAGOME_CORE_FACTORY_MOCK_HPP
23.689655
75
0.72198
igor-egorov
7bc20553db5798d3a40b8b3e586070525f7dc4f7
3,451
cpp
C++
Examples/IocTest/main.cpp
mrcao20/McQuickBoot
187a16ea9459fa5e2b3477b5280302a9090e8ccf
[ "MIT" ]
3
2020-03-29T18:41:42.000Z
2020-09-23T01:46:25.000Z
Examples/IocTest/main.cpp
mrcao20/McQuickBoot
187a16ea9459fa5e2b3477b5280302a9090e8ccf
[ "MIT" ]
3
2020-11-26T03:37:31.000Z
2020-12-21T02:17:17.000Z
Examples/IocTest/main.cpp
mrcao20/McQuickBoot
187a16ea9459fa5e2b3477b5280302a9090e8ccf
[ "MIT" ]
null
null
null
#include <QBuffer> #include <QCoreApplication> #include <QDebug> #include <QFile> #include <QTextStream> #include <QThread> #include <McIoc/ApplicationContext/impl/McLocalPathApplicationContext.h> #include <McIoc/ApplicationContext/impl/McAnnotationApplicationContext.h> #include <McIoc/ApplicationContext/impl/McXmlApplicationContext.h> #include "C.h" #include <McIoc/Utils/XmlBuilder/impl/McBean.h> #include <McIoc/Utils/XmlBuilder/impl/McBeanCollection.h> #include <McIoc/Utils/XmlBuilder/impl/McConnect.h> #include <McIoc/Utils/XmlBuilder/impl/McEnum.h> #include <McIoc/Utils/XmlBuilder/impl/McList.h> #include <McIoc/Utils/XmlBuilder/impl/McMap.h> #include <McIoc/Utils/XmlBuilder/impl/McPlaceholder.h> #include <McIoc/Utils/XmlBuilder/impl/McProperty.h> #include <McIoc/Utils/XmlBuilder/impl/McRef.h> #include <McIoc/Utils/XmlBuilder/impl/McValue.h> #include <QDomDocument> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); using namespace McXmlBuilder; McBeanCollection bc; McBeanPtr b1 = McBeanPtr::create(); bc.addBean(b1); b1->setBeanName("r"); b1->setClassName("R"); b1->setSingleton(true); b1->setPointer(false); McBeanPtr b = McBeanPtr::create(); bc.addBean(b); b->setBeanName("c"); b->setClassName("C"); McPropertyPtr p = McPropertyPtr::create(); b->addContent(p); p->setContent("text", "test c"); McConnectPtr c = McConnectPtr::create(); b->addContent(c); c->setSender("this"); c->setSignal("signal_send()"); c->setReceiver("r"); c->setSlot("slot_recv()"); c->setConnectionType("DirectConnection | UniqueConnection"); McEnumPtr en = McEnumPtr::create(); en->setScope("Qt"); en->setType("AlignmentFlag"); en->setValue("AlignLeft"); McPropertyPtr pp1 = McPropertyPtr::create(); pp1->setContent("align", en); b->addContent(pp1); McRefPtr ref = McRefPtr::create(); ref->setBeanName("r"); McPropertyPtr p3 = McPropertyPtr::create(); b->addContent(p3); p3->setContent("r", ref); McMapPtr m = McMapPtr::create(); m->addContent("jack", ref); McPropertyPtr p1 = McPropertyPtr::create(); b->addContent(p1); p1->setContent("hrs", m); McPlaceholderPtr plh = McPlaceholderPtr::create(); plh->setPlaceholder("objectName"); m->addContent(plh, ref); McListPtr ll = McListPtr::create(); ll->addContent("停封"); McPropertyPtr pp2 = McPropertyPtr::create(); pp2->setContent("texts", ll); b->addContent(pp2); auto doc = bc.toDomDocument(); qDebug() << doc.toString(4); QFile file(Mc::applicationDirPath() + "/test.xml"); file.open(QIODevice::WriteOnly); QTextStream stream(&file); doc.save(stream, 4); QSharedPointer<QBuffer> buf = QSharedPointer<QBuffer>::create(); buf->open(QIODevice::ReadWrite); bc.writeToDevice(buf.data()); auto appContext = McLocalPathApplicationContextPtr::create( R"(../../Examples/IocTest/myspring.xml)"); // auto appContext = McAnnotationApplicationContextPtr::create(); // auto appContext = McXmlApplicationContextPtr::create(buf.objectCast<QIODevice>()); QThread *t = new QThread(&a); t->start(); qDebug() << "t:" << t; auto ia = appContext->getBean<IA>("c", t); auto gadget = appContext->getBean<GadgetTest>("gadgetTest"); qDebug() << gadget->aaa << gadget->bbb; ia->a(); return a.exec(); }
32.252336
92
0.671689
mrcao20
7bc2289c2f00a37905ef4e3a1be95dcd6e18a1c3
1,929
cpp
C++
Code/Runtime/Asset/CacheStream.cpp
NathanSaidas/LiteForgeMirror
84068b62bff6e443b53c46107a3946e2645e4447
[ "MIT" ]
null
null
null
Code/Runtime/Asset/CacheStream.cpp
NathanSaidas/LiteForgeMirror
84068b62bff6e443b53c46107a3946e2645e4447
[ "MIT" ]
null
null
null
Code/Runtime/Asset/CacheStream.cpp
NathanSaidas/LiteForgeMirror
84068b62bff6e443b53c46107a3946e2645e4447
[ "MIT" ]
null
null
null
// ******************************************************************** // Copyright (c) 2019 Nathan Hanlan // // 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 "CacheStream.h" #if defined(LF_OS_WINDOWS) #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <Windows.h> #endif namespace lf { struct CacheFile { HANDLE mCacheFile; HANDLE mManifestFile; }; void CacheStream::Open(StreamMode mode, const String& cacheFilename, const String& manifestFilename, SizeT fileSize) { mMode = mode; mCacheFilename = cacheFilename; mManifestFilename = manifestFilename; mFileSize = fileSize; // ManifestFile: // Object ID: (2 bytes) // Object Location (4 bytes) // Object Size (4 bytes) // Object Capacity (4 bytes) } void CacheStream::Close() { } } // namespace lf
34.446429
116
0.67859
NathanSaidas
7bc4194e25196b4cc5d934b22032c7f2a2d5ac11
6,520
cpp
C++
src/overlay_params.cpp
DasCapschen/DiRT-Rally-2.0-Telemetry-HUD
7eaa754d7791239753b9d9209d574b654d120eb6
[ "MIT" ]
4
2020-02-21T18:16:42.000Z
2021-08-23T16:46:48.000Z
src/overlay_params.cpp
DasCapschen/DiRT-Rally-2.0-Telemetry-HUD
7eaa754d7791239753b9d9209d574b654d120eb6
[ "MIT" ]
null
null
null
src/overlay_params.cpp
DasCapschen/DiRT-Rally-2.0-Telemetry-HUD
7eaa754d7791239753b9d9209d574b654d120eb6
[ "MIT" ]
1
2020-06-09T10:57:22.000Z
2020-06-09T10:57:22.000Z
/* * Copyright © 2019 Intel Corporation * * 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 (including the next * paragraph) 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 <stdio.h> #include <string.h> #include <stdlib.h> #include <fstream> #include <errno.h> #include <sys/sysinfo.h> #include "overlay_params.h" #include "config.h" #include "mesa/util/os_socket.h" static enum overlay_param_position parse_position(const char *str) { if (!str || !strcmp(str, "top-left")) return LAYER_POSITION_TOP_LEFT; if (!strcmp(str, "top-right")) return LAYER_POSITION_TOP_RIGHT; if (!strcmp(str, "bottom-left")) return LAYER_POSITION_BOTTOM_LEFT; if (!strcmp(str, "bottom-right")) return LAYER_POSITION_BOTTOM_RIGHT; return LAYER_POSITION_TOP_LEFT; } static float parse_font_size_small(const char *str) { return strtof(str, NULL); } static float parse_font_size_medium(const char *str) { return strtof(str, NULL); } static float parse_font_size_big(const char *str) { return strtof(str, NULL); } static float parse_background_alpha(const char *str) { return strtof(str, NULL); } static uint32_t parse_fps_limit(const char *str) { return strtol(str, NULL, 0); } static unsigned parse_unsigned(const char *str) { return strtol(str, NULL, 0); } #define parse_width(s) parse_unsigned(s) #define parse_height(s) parse_unsigned(s) #define parse_vsync(s) parse_unsigned(s) #define parse_offset_x(s) parse_unsigned(s) #define parse_offset_y(s) parse_unsigned(s) static bool is_delimiter(char c) { return c == 0 || c == ',' || c == ':' || c == ';' || c == '='; } static int parse_string(const char *s, char *out_param, char *out_value) { int i = 0; for (; !is_delimiter(*s); s++, out_param++, i++) *out_param = *s; *out_param = 0; if (*s == '=') { s++; i++; for (; !is_delimiter(*s); s++, out_value++, i++) *out_value = *s; } else *(out_value++) = '1'; *out_value = 0; if (*s && is_delimiter(*s)) { s++; i++; } if (*s && !i) { fprintf(stderr, "mesa-overlay: syntax error: unexpected '%c' (%i) while " "parsing a string\n", *s, *s); fflush(stderr); } return i; } const char *overlay_param_names[] = { #define OVERLAY_PARAM_BOOL(name) #name, #define OVERLAY_PARAM_CUSTOM(name) OVERLAY_PARAMS #undef OVERLAY_PARAM_BOOL #undef OVERLAY_PARAM_CUSTOM }; void parse_overlay_env(struct overlay_params *params, const char *env) { uint32_t num; char key[256], value[256]; while ((num = parse_string(env, key, value)) != 0) { env += num; #define OVERLAY_PARAM_BOOL(name) \ if (!strcmp(#name, key)) { \ params->enabled[OVERLAY_PARAM_ENABLED_##name] = \ strtol(value, NULL, 0); \ continue; \ } #define OVERLAY_PARAM_CUSTOM(name) \ if (!strcmp(#name, key)) { \ params->name = parse_##name(value); \ continue; \ } OVERLAY_PARAMS #undef OVERLAY_PARAM_BOOL #undef OVERLAY_PARAM_CUSTOM fprintf(stderr, "Unknown option '%s'\n", key); } } void parse_overlay_config(struct overlay_params *params, const char *env) { memset(params, 0, sizeof(*params)); /* Visible by default */ params->enabled[OVERLAY_PARAM_ENABLED_show_debug] = false; params->enabled[OVERLAY_PARAM_ENABLED_show_time] = true; params->enabled[OVERLAY_PARAM_ENABLED_show_progress] = true; params->enabled[OVERLAY_PARAM_ENABLED_show_gauge] = true; params->enabled[OVERLAY_PARAM_ENABLED_show_inputs] = true; params->enabled[OVERLAY_PARAM_ENABLED_show_springs] = false; params->width = 300; params->height = 300; params->fps_limit = 0; params->vsync = -1; params->offset_x = 0; params->offset_y = 0; params->background_alpha = 0.5; // first pass with env var if (env) { parse_overlay_env(params, env); } else { // Get config options parseConfigFile(); for (auto& it : options) { #define OVERLAY_PARAM_BOOL(name) \ if (it.first == #name) { \ params->enabled[OVERLAY_PARAM_ENABLED_##name] = \ strtol(it.second.c_str(), NULL, 0); \ continue; \ } #define OVERLAY_PARAM_CUSTOM(name) \ if (it.first == #name) { \ params->name = parse_##name(it.second.c_str()); \ continue; \ } OVERLAY_PARAMS #undef OVERLAY_PARAM_BOOL #undef OVERLAY_PARAM_CUSTOM fprintf(stderr, "Unknown option '%s'\n", it.first.c_str()); } } // second pass, override config file settings with MANGOHUD_CONFIG if (env) parse_overlay_env(params, env); if (!params->font_size_small) params->font_size_small = 16.0f; if (!params->font_size_medium) params->font_size_medium = 32.0f; if (!params->font_size_big) params->font_size_big = 48.0f; }
29.369369
79
0.596166
DasCapschen
7bc509aa911f1dba9daf558ccc7ed516521b31a3
789
hpp
C++
src/unpack_command.hpp
tzvetkoff/giffler
87133592e064f66a611ce9e00b670c20ec99dd82
[ "Beerware" ]
null
null
null
src/unpack_command.hpp
tzvetkoff/giffler
87133592e064f66a611ce9e00b670c20ec99dd82
[ "Beerware" ]
null
null
null
src/unpack_command.hpp
tzvetkoff/giffler
87133592e064f66a611ce9e00b670c20ec99dd82
[ "Beerware" ]
null
null
null
/* * ---------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * <Latchezar Tzvetkoff> wrote this file. As long as you retain this notice you * can do whatever you want with this stuff. If we meet some day, and you think * this stuff is worth it, you can buy me a beer in return. Latchezar Tzvetkoff * ---------------------------------------------------------------------------- */ /* unpack_command.hpp */ #ifndef __giffler_unpack_command__ #define __giffler_unpack_command__ #include <iostream> namespace giffler { class UnpackCommand { private: std::string _in; std::string _out; public: UnpackCommand(int, char *const *); int execute(); }; } #endif /* !defined(__giffler_unpack_command__) */
21.916667
79
0.569075
tzvetkoff
7bc53ae94b3ca39bd14c3e0a7b5f30eb6c68be27
1,095
cpp
C++
test/math/convolution/fast_zeta_transform.test.cpp
emthrm/library
0876ba7ec64e23b5ec476a7a0b4880d497a36be1
[ "Unlicense" ]
1
2021-12-26T14:17:29.000Z
2021-12-26T14:17:29.000Z
test/math/convolution/fast_zeta_transform.test.cpp
emthrm/library
0876ba7ec64e23b5ec476a7a0b4880d497a36be1
[ "Unlicense" ]
3
2020-07-13T06:23:02.000Z
2022-02-16T08:54:26.000Z
test/math/convolution/fast_zeta_transform.test.cpp
emthrm/library
0876ba7ec64e23b5ec476a7a0b4880d497a36be1
[ "Unlicense" ]
null
null
null
/* * @brief 数学/畳み込み/高速ゼータ変換 */ #define PROBLEM "https://atcoder.jp/contests/arc100/tasks/arc100_e" // #define PROBLEM "https://atcoder.jp/contests/arc100/tasks/arc100_c" #include <algorithm> #include <functional> #include <iostream> #include <utility> #include <vector> #include "../../../math/convolution/fast_zeta_transform.hpp" int main() { using Pii = std::pair<int, int>; int n; std::cin >> n; std::vector<Pii> a(1 << n, {0, 0}); for (int i = 0; i < (1 << n); ++i) { std::cin >> a[i].first; } const std::function<Pii(Pii, Pii)> max = [](const Pii &a, const Pii &b) -> Pii { int tmp[]{a.first, a.second, b.first, b.second}; std::sort(tmp, tmp + 4, std::greater<int>()); return {tmp[0], tmp[1]}; }; a = fast_zeta_transform(a, false, {0, 0}, max); std::vector<int> ans(1 << n); for (int i = 0; i < (1 << n); ++i) { ans[i] = a[i].first + a[i].second; } for (int i = 1; i < (1 << n); ++i) { if (ans[i - 1] > ans[i]) { ans[i] = ans[i - 1]; } std::cout << ans[i] << '\n'; } return 0; }
27.375
83
0.527854
emthrm
7bc5b45449fe670815fcb8e5f14e42101ef1723c
3,168
cc
C++
Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/GroupInfo.cc
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
28
2015-09-22T21:43:32.000Z
2022-02-28T01:35:01.000Z
Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/GroupInfo.cc
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
98
2015-01-22T03:21:27.000Z
2022-03-02T01:47:00.000Z
Archive/Stroika_FINAL_for_STERL_1992/Tools/Portable/Emily/Sources/GroupInfo.cc
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
4
2019-02-21T16:45:25.000Z
2022-02-18T13:40:04.000Z
/* Copyright(c) Sophist Solutions Inc. 1991-1992. All rights reserved */ /* * $Header: /fuji/lewis/RCS/GroupInfo.cc,v 1.4 1992/07/21 18:28:39 sterling Exp $ * * Description: * * TODO: * * Changes: * $Log: GroupInfo.cc,v $ * Revision 1.4 1992/07/21 18:28:39 sterling * hi * * Revision 1.3 1992/07/16 15:24:40 sterling * hi * * Revision 1.2 1992/06/25 10:15:58 sterling * *** empty log message *** * * Revision 1.17 1992/05/19 11:35:49 sterling * hi * * Revision 1.16 92/05/13 18:47:06 18:47:06 lewis (Lewis Pringle) * STERL. * * Revision 1.15 92/04/08 17:22:53 17:22:53 sterling (Sterling Wight) * Cleaned up dialogs for motif * * * * */ // text before here will be retained: Do not remove or modify this line!!! #include "Language.hh" #include "Shape.hh" #include "GroupInfo.hh" GroupInfoX::GroupInfoX () : fTitle (), fViewInfo () { #if qMacUI BuildForMacUI (); #elif qMotifUI BuildForMotifUI (); #else BuildForUnknownGUI (); #endif /* GUI */ } GroupInfoX::~GroupInfoX () { RemoveFocus (&fViewInfo); RemoveSubView (&fTitle); RemoveSubView (&fViewInfo); } #if qMacUI void GroupInfoX::BuildForMacUI () { SetSize (Point (220, 323), eNoUpdate); fTitle.SetExtent (5, 5, 16, 305, eNoUpdate); fTitle.SetFont (&kSystemFont); fTitle.SetText (" Set Group Info"); fTitle.SetJustification (AbstractTextView::eJustCenter); AddSubView (&fTitle); fViewInfo.SetExtent (29, 4, 188, 316, eNoUpdate); AddSubView (&fViewInfo); AddFocus (&fViewInfo); } #elif qMotifUI void GroupInfoX::BuildForMotifUI () { SetSize (Point (234, 323), eNoUpdate); fTitle.SetExtent (5, 5, 20, 313, eNoUpdate); fTitle.SetFont (&kSystemFont); fTitle.SetText (" Set Group Info"); fTitle.SetJustification (AbstractTextView::eJustCenter); AddSubView (&fTitle); fViewInfo.SetExtent (29, 4, 188, 316, eNoUpdate); AddSubView (&fViewInfo); AddFocus (&fViewInfo); } #else void GroupInfoX::BuildForUnknownGUI (); { SetSize (Point (220, 323), eNoUpdate); fTitle.SetExtent (5, 5, 16, 305, eNoUpdate); fTitle.SetFont (&kSystemFont); fTitle.SetText (" Set Group Info"); fTitle.SetJustification (AbstractTextView::eJustCenter); AddSubView (&fTitle); fViewInfo.SetExtent (29, 4, 188, 316, eNoUpdate); AddSubView (&fViewInfo); AddFocus (&fViewInfo); } #endif /* GUI */ Point GroupInfoX::CalcDefaultSize_ (const Point& /*defaultSize*/) const { #if qMacUI return (Point (220, 323)); #elif qMotifUI return (Point (234, 323)); #else return (Point (220, 323)); #endif /* GUI */ } void GroupInfoX::Layout () { const Point kSizeDelta = CalcDefaultSize () - GetSize (); static const Point kOriginalfTitleSize = fTitle.GetSize (); fTitle.SetSize (kOriginalfTitleSize - Point (0, kSizeDelta.GetH ())); static const Point kOriginalfViewInfoSize = fViewInfo.GetSize (); fViewInfo.SetSize (kOriginalfViewInfoSize - Point (kSizeDelta.GetV (), kSizeDelta.GetH ())); View::Layout (); } // text past here will be retained: Do not remove or modify this line!!! #include "GroupItem.hh" #include "Dialog.hh" GroupInfo::GroupInfo (GroupItem& view) { GetViewItemInfo ().SetUpFromView (view); }
20.842105
94
0.681503
SophistSolutions
dcf5536bb29ae71b60c5178414f51678e576aa3d
1,479
cpp
C++
src/lib/Checksum/Checksum.cpp
Flowm/move-on-helium-sensors
3794d38671e1976c9801bcb8a9639465cdddb731
[ "Apache-2.0" ]
1
2021-11-11T01:49:28.000Z
2021-11-11T01:49:28.000Z
src/lib/Checksum/Checksum.cpp
Flowm/move-on-helium-sensors
3794d38671e1976c9801bcb8a9639465cdddb731
[ "Apache-2.0" ]
null
null
null
src/lib/Checksum/Checksum.cpp
Flowm/move-on-helium-sensors
3794d38671e1976c9801bcb8a9639465cdddb731
[ "Apache-2.0" ]
null
null
null
/* * Checksum.cpp * * Created on: Jan 31, 2018 * Author: tkale */ #include "Checksum.hpp" /** * Calculate CRC-16-CCITT in hardware * * @param [in] data A pointer to the data * @param [in] len The length of the data * * WARNING: Doesnt seem to work! * * @return The CRC16 checksum of data * */ uint16_t Checksum::crc16hw(const uint8_t* data, uint16_t len) { uint32_t checksum = 0x00; __HAL_RCC_CRC_CLK_ENABLE(); CRC_HandleTypeDef crc; crc.InputDataFormat = CRC_INPUTDATA_FORMAT_HALFWORDS; crc.Init = { DEFAULT_POLYNOMIAL_DISABLE, DEFAULT_INIT_VALUE_DISABLE, 0x1021, CRC_POLYLENGTH_16B, checksum, CRC_OUTPUTDATA_INVERSION_DISABLE }; if(HAL_CRC_Init(&crc) == HAL_OK){ checksum = HAL_CRC_Calculate(&crc, (uint32_t*)data, len); }else { printf("CRC INIT ERROR!"); } HAL_CRC_DeInit(&crc); __HAL_RCC_CRC_CLK_DISABLE(); // printf("%lu\r\n",checksum); return checksum; } /** * Calculate CRC-16-CCITT * * @param [in] data A pointer to the data * @param [in] len The length of the data * * @return The CRC16 checksum of data * */ uint16_t Checksum::crc16sw(const uint8_t* data, uint16_t len, uint16_t init) { uint16_t crc = init; uint16_t x; while(len > 0) { x = crc >> 8 ^ *data++; x ^= x >> 4; crc = (crc << 8) ^ (x << 12) ^ (x << 5) ^ x; len--; } return crc; }
21.434783
76
0.592292
Flowm
0d05be0a539ab2709befd17f4c1dd7575dcfc3fc
538
cpp
C++
791. Custom Sort String.cpp
ttang235/leetcode
ae2d6f61c80178f09de816210f53b00a838b0508
[ "MIT" ]
null
null
null
791. Custom Sort String.cpp
ttang235/leetcode
ae2d6f61c80178f09de816210f53b00a838b0508
[ "MIT" ]
null
null
null
791. Custom Sort String.cpp
ttang235/leetcode
ae2d6f61c80178f09de816210f53b00a838b0508
[ "MIT" ]
null
null
null
// https://leetcode.com/problems/custom-sort-string/description/ class Solution { public: string customSortString(string S, string T) { vector<int> cnt(26, 0); for(auto c : T) { cnt[c - 'a']++; } string res; for(auto c : S) { res += string(cnt[c-'a'], c); cnt[c-'a'] = 0; } for(int i = 0; i < 26; i++) { if(cnt[i] != 0) { res += string(cnt[i], char('a' + i)); } } return res; } };
23.391304
64
0.410781
ttang235
0d064ed4f1da137c1c12b430b7e50b792315d0d5
592
cpp
C++
src/ActiveBSP/src/ActorRegistry.cpp
fbaude/activebsp
d867d74e58bde38cc0f816bcb23c6c41a5bb4f81
[ "BSD-3-Clause" ]
null
null
null
src/ActiveBSP/src/ActorRegistry.cpp
fbaude/activebsp
d867d74e58bde38cc0f816bcb23c6c41a5bb4f81
[ "BSD-3-Clause" ]
null
null
null
src/ActiveBSP/src/ActorRegistry.cpp
fbaude/activebsp
d867d74e58bde38cc0f816bcb23c6c41a5bb4f81
[ "BSD-3-Clause" ]
null
null
null
#include "ActorRegistry.h" namespace activebsp { ActorRegistry * ActorRegistry::_instance = NULL; actor_registry_t & ActorRegistry::getActorRegistry() { static actor_registry_t * actor_handlers = new actor_registry_t(); return *actor_handlers; } ActorRegistry * ActorRegistry::getInstance() { if (_instance == NULL) { _instance = new ActorRegistry(); } return _instance; } ActorMaker::ActorMaker(const std::string name, const actor_handler_t & handler) { ActorRegistry::getInstance()->getActorRegistry()[name] = handler; } } // namespace activebsp
19.096774
79
0.716216
fbaude
0d07091ade61e54ebdde5051b8bcb2f3fb80e92b
1,376
cpp
C++
CepsyGLFramework/CepsyGLFramework/src/Graphics/AnimationData.cpp
cepsylon/CepsyGLFramework
72cf710c892ff34aeac5ed47b0b7799756a04032
[ "MIT" ]
null
null
null
CepsyGLFramework/CepsyGLFramework/src/Graphics/AnimationData.cpp
cepsylon/CepsyGLFramework
72cf710c892ff34aeac5ed47b0b7799756a04032
[ "MIT" ]
null
null
null
CepsyGLFramework/CepsyGLFramework/src/Graphics/AnimationData.cpp
cepsylon/CepsyGLFramework
72cf710c892ff34aeac5ed47b0b7799756a04032
[ "MIT" ]
null
null
null
#include "AnimationData.h" #include "Animation.h" #include "Application/Application.h" void AnimationData::update(float dt) { if (mAnimation) { mTime += dt; while (mAnimation->duration() < mTime) { mTime -= mAnimation->duration(); mPrevIndex = mIndex; mIndex = 0; } // TODO: fix this, we are assuming we rotate the root, it may not be the case while (mTime > (*mAnimation)[0].mRotation[mIndex].mTime) { mPrevIndex = mIndex; mIndex++; } } } void AnimationData::to_gui() { if (mAnimation.to_gui()) { mTime = 0.0f; mPrevIndex = 0u; mIndex = 1u; } } void AnimationData::upload_to_gpu() const { if (mAnimation) { std::vector<glm::mat4> matrices = get_matrices(); application.graphics().skeleton_buffer().update(matrices.data(), matrices.size() * sizeof(glm::mat4)); } } void AnimationData::set_animation(const std::string & name) { mAnimation = application.resources().get<Animation>(name); } std::vector<glm::mat4> AnimationData::get_matrices() const { // TODO: fix this, we are assuming we rotate the root, it may not be the case float t = mIndex == 0u ? mTime / (*mAnimation)[0].mRotation[mIndex].mTime : (mTime - (*mAnimation)[0].mRotation[mPrevIndex].mTime) / ((*mAnimation)[0].mRotation[mIndex].mTime - (*mAnimation)[0].mRotation[mPrevIndex].mTime); return mAnimation->get_matrices_at(t, mPrevIndex, mIndex); }
23.322034
149
0.682413
cepsylon
0d1b8a5ee0a0e3d963a4a9c2dc913b838395b83e
15,548
cpp
C++
sunvox_engine/psynth/psynths_filter.cpp
Sound-Linux-More/sunvox
7376fbe9f9bca92be1e17aefaac2e68b558d8357
[ "BSD-3-Clause" ]
100
2016-01-15T02:43:07.000Z
2022-03-16T14:02:38.000Z
sunvox_engine/psynth/psynths_filter.cpp
Sound-Linux-More/sunvox
7376fbe9f9bca92be1e17aefaac2e68b558d8357
[ "BSD-3-Clause" ]
2
2018-01-10T18:21:37.000Z
2021-12-05T01:48:08.000Z
sunvox_engine/psynth/psynths_filter.cpp
Sound-Linux-More/sunvox
7376fbe9f9bca92be1e17aefaac2e68b558d8357
[ "BSD-3-Clause" ]
17
2016-05-16T19:48:19.000Z
2022-03-23T10:59:42.000Z
/* psynths_filter.cpp. This file is part of the SunVox engine. Copyright (C) 2002 - 2008 Alex Zolotov <[email protected]> */ #include "psynth.h" //Unique names for objects in your synth: #define SYNTH_DATA filter_data #define SYNTH_HANDLER psynth_filter //And unique parameters: #define SYNTH_INPUTS 2 #define SYNTH_OUTPUTS 2 struct filter_channel { STYPE_CALC d1, d2, d3; }; /* uint16 g_exp_table[ 256 ] = { 256, 256, 257, 258, 258, 259, 260, 260, 261, 262, 263, 263, 264, 265, 265, 266, 267, 268, 268, 269, 270, 270, 271, 272, 273, 273, 274, 275, 276, 276, 277, 278, 279, 279, 280, 281, 282, 282, 283, 284, 285, 286, 286, 287, 288, 289, 289, 290, 291, 292, 293, 293, 294, 295, 296, 297, 297, 298, 299, 300, 301, 301, 302, 303, 304, 305, 306, 306, 307, 308, 309, 310, 311, 311, 312, 313, 314, 315, 316, 317, 317, 318, 319, 320, 321, 322, 323, 323, 324, 325, 326, 327, 328, 329, 330, 331, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 410, 411, 412, 413, 414, 415, 416, 417, 419, 420, 421, 422, 423, 424, 425, 427, 428, 429, 430, 431, 432, 434, 435, 436, 437, 438, 439, 441, 442, 443, 444, 445, 447, 448, 449, 450, 452, 453, 454, 455, 456, 458, 459, 460, 461, 463, 464, 465, 466, 468, 469, 470, 472, 473, 474, 475, 477, 478, 479, 481, 482, 483, 485, 486, 487, 488, 490, 491, 492, 494, 495, 496, 498, 499, 501, 502, 503, 505, 506, 507, 509, 510, }; */ enum { MODE_HQ = 0, MODE_HQ_MONO, MODE_LQ, MODE_LQ_MONO, MODES }; struct SYNTH_DATA { //Controls: ############################################################ CTYPE ctl_volume; CTYPE ctl_cutoff_freq; CTYPE ctl_resonance; CTYPE ctl_type; CTYPE ctl_response; CTYPE ctl_mode; CTYPE ctl_impulse; CTYPE ctl_mix; //Synth data: ########################################################## filter_channel fchan[ SYNTH_OUTPUTS ]; uint16 *exp_table; int tick_counter; //From 0 to tick_size CTYPE floating_volume; CTYPE floating_cutoff; CTYPE floating_resonance; }; int SYNTH_HANDLER( PSYTEXX_SYNTH_PARAMETERS ) { psynth_net *pnet = (psynth_net*)net; SYNTH_DATA *data = (SYNTH_DATA*)data_ptr; int retval = 0; switch( command ) { case COMMAND_GET_DATA_SIZE: retval = sizeof( SYNTH_DATA ); break; case COMMAND_GET_SYNTH_NAME: retval = (int)"Filter"; break; case COMMAND_GET_SYNTH_INFO: retval = (int)"State Variable Filter\n(Chamberlin version)\nDouble Sampled\n\n\ References: \n\ http://musicdsp.org/archive.php?classid=3 \n\ Hal Chamberlin, \"Musical Applications of Microprocessors\"\n\ 2nd Ed, Hayden Book Company 1985. pp 490-492.\n\n\ Use low \"response\" values\nfor smooth frequency, resonance\nor volume change"; break; case COMMAND_GET_INPUTS_NUM: retval = SYNTH_INPUTS; break; case COMMAND_GET_OUTPUTS_NUM: retval = SYNTH_OUTPUTS; break; case COMMAND_GET_FLAGS: retval = PSYNTH_FLAG_EFFECT; break; case COMMAND_INIT: psynth_register_ctl( synth_id, "Volume", "", 0, 256, 256, 0, &data->ctl_volume, net ); psynth_register_ctl( synth_id, "Freq", "Hz", 0, 14000, 14000, 0, &data->ctl_cutoff_freq, net ); psynth_register_ctl( synth_id, "Resonance", "", 0, 1530, 0, 0, &data->ctl_resonance, net ); psynth_register_ctl( synth_id, "Type", "l/h/b/n", 0, 3, 0, 1, &data->ctl_type, net ); psynth_register_ctl( synth_id, "Response", "", 0, 256, 256, 0, &data->ctl_response, net ); psynth_register_ctl( synth_id, "Mode", "HQ/HQmono/LQ/LQmono", 0, MODE_LQ_MONO, MODE_HQ, 1, &data->ctl_mode, net ); psynth_register_ctl( synth_id, "Impulse", "Hz", 0, 14000, 0, 0, &data->ctl_impulse, net ); psynth_register_ctl( synth_id, "Mix", "", 0, 256, 256, 0, &data->ctl_mix, net ); data->floating_volume = 256 * 256; data->floating_cutoff = 14000 * 256; data->floating_resonance = 0 * 256; for( int i = 0; i < SYNTH_OUTPUTS; i++ ) { data->fchan[ i ].d1 = 0; data->fchan[ i ].d2 = 0; data->fchan[ i ].d3 = 0; } data->tick_counter = 0; //data->exp_table = g_exp_table; retval = 1; break; case COMMAND_CLEAN: case COMMAND_ALL_NOTES_OFF: for( int i = 0; i < SYNTH_OUTPUTS; i++ ) { data->fchan[ i ].d1 = 0; data->fchan[ i ].d2 = 0; data->fchan[ i ].d3 = 0; } data->tick_counter = 0; retval = 1; break; case COMMAND_RENDER_REPLACE: if( !inputs[ 0 ] || !outputs[ 0 ] ) break; { if( data->ctl_mode == MODE_HQ_MONO || data->ctl_mode == MODE_LQ_MONO ) psynth_set_number_of_outputs( 1, synth_id, pnet ); else psynth_set_number_of_outputs( SYNTH_OUTPUTS, synth_id, pnet ); int tick_size = pnet->sampling_freq / 200; int ptr = 0; if( data->ctl_impulse ) { data->floating_cutoff = data->ctl_impulse * 256; data->ctl_impulse = 0; } while( 1 ) { int buf_size = tick_size - data->tick_counter; if( ptr + buf_size > sample_frames ) buf_size = sample_frames - ptr; int outputs_num = psynth_get_number_of_outputs( synth_id, pnet ); for( int ch = 0; ch < outputs_num; ch++ ) { STYPE *in = inputs[ ch ]; STYPE *out = outputs[ ch ]; //References: // http://musicdsp.org/archive.php?classid=3 // Hal Chamberlin, "Musical Applications of Microprocessors," 2nd Ed, Hayden Book Company 1985. pp 490-492. int fs, c, f, q, scale; fs = pnet->sampling_freq; if( data->ctl_mode == MODE_HQ || data->ctl_mode == MODE_HQ_MONO ) { //HQ: c = ( ( data->floating_cutoff / 256 ) * 32768 ) / ( fs * 2 ); f = ( 6433 * c ) / 32768; if( f >= 1024 ) f = 1023; q = 1536 - ( data->floating_resonance / 256 ); scale = q; } if( data->ctl_mode == MODE_LQ || data->ctl_mode == MODE_LQ_MONO ) { //LQ: c = ( ( ( data->floating_cutoff / 256 ) / 2 ) * 32768 ) / fs; f = ( 6433 * c ) / 32768; if( f >= 1024 ) f = 1023; q = 1536 - ( data->floating_resonance / 256 ); scale = q; } filter_channel *fchan = &data->fchan[ ch ]; STYPE_CALC d1 = fchan->d1; STYPE_CALC d2 = fchan->d2; STYPE_CALC d3 = fchan->d3; int vol = ( data->floating_volume /256 ); if( data->ctl_mix == 0 ) { //Filter disabled: if( vol == 256 ) { for( int i = ptr; i < ptr + buf_size; i++ ) out[ i ] = in[ i ]; } else { for( int i = ptr; i < ptr + buf_size; i++ ) { STYPE_CALC inp = in[ i ]; inp *= vol; inp /= 256; out[ i ] = (STYPE)inp; } } } else { //Filter enabled start: vol *= data->ctl_mix; vol /= 256; if( data->ctl_mode == MODE_HQ || data->ctl_mode == MODE_HQ_MONO ) switch( data->ctl_type ) { case 0: for( int i = ptr; i < ptr + buf_size; i++ ) { STYPE_CALC inp = in[ i ]; denorm_add_white_noise( inp ); #ifndef STYPE_FLOATINGPOINT inp *= 32; #endif STYPE_CALC low = d2 + ( f * d1 ) / 1024; STYPE_CALC high = inp - low - ( q * d1 ) / 1024; STYPE_CALC band = ( f * high ) / 1024 + d1; STYPE_CALC slow = low; low = low + ( f * band ) / 1024; high = inp - low - ( q * band ) / 1024; band = ( f * high ) / 1024 + band; STYPE_CALC outp; #ifndef STYPE_FLOATINGPOINT outp = ( ( d2 + slow ) / 2 ) / 32; #else outp = ( d2 + slow ) / 2; #endif outp *= vol; outp /= 256; d1 = band; d2 = low; out[ i ] = (STYPE)outp; } break; case 1: for( int i = ptr; i < ptr + buf_size; i++ ) { STYPE_CALC inp = in[ i ]; denorm_add_white_noise( inp ); #ifndef STYPE_FLOATINGPOINT inp *= 32; #endif STYPE_CALC low = d2 + ( f * d1 ) / 1024; STYPE_CALC high = inp - low - ( q * d1 ) / 1024; STYPE_CALC band = ( f * high ) / 1024 + d1; STYPE_CALC shigh = high; low = low + ( f * band ) / 1024; high = inp - low - ( q * band ) / 1024; band = ( f * high ) / 1024 + band; STYPE_CALC outp; #ifndef STYPE_FLOATINGPOINT outp = ( ( d3 + shigh ) / 2 ) / 32; #else outp = ( d3 + shigh ) / 2; #endif outp *= vol; outp /= 256; d1 = band; d2 = low; d3 = high; out[ i ] = (STYPE)outp; } break; case 2: for( int i = ptr; i < ptr + buf_size; i++ ) { STYPE_CALC inp = in[ i ]; denorm_add_white_noise( inp ); #ifndef STYPE_FLOATINGPOINT inp *= 32; #endif STYPE_CALC low = d2 + ( f * d1 ) / 1024; STYPE_CALC high = inp - low - ( q * d1 ) / 1024; STYPE_CALC band = ( f * high ) / 1024 + d1; STYPE_CALC sband = band; low = low + ( f * band ) / 1024; high = inp - low - ( q * band ) / 1024; band = ( f * high ) / 1024 + band; STYPE_CALC outp; #ifndef STYPE_FLOATINGPOINT outp = ( ( d1 + sband ) / 2 ) / 32; #else outp = ( d1 + sband ) / 2; #endif outp *= vol; outp /= 256; d1 = band; d2 = low; out[ i ] = (STYPE)outp; } break; case 3: for( int i = ptr; i < ptr + buf_size; i++ ) { STYPE_CALC inp = in[ i ]; denorm_add_white_noise( inp ); #ifndef STYPE_FLOATINGPOINT inp *= 32; #endif STYPE_CALC low = d2 + ( f * d1 ) / 1024; STYPE_CALC high = inp - low - ( q * d1 ) / 1024; STYPE_CALC band = ( f * high ) / 1024 + d1; STYPE_CALC snotch = high + low; low = low + ( f * band ) / 1024; high = inp - low - ( q * band ) / 1024; band = ( f * high ) / 1024 + band; STYPE_CALC outp; #ifndef STYPE_FLOATINGPOINT outp = ( ( d3 + snotch ) / 2 ) / 32; #else outp = ( d3 + snotch ) / 2; #endif outp *= vol; outp /= 256; d1 = band; d2 = low; d3 = high + low; out[ i ] = (STYPE)outp; } break; } if( data->ctl_mode == MODE_LQ || data->ctl_mode == MODE_LQ_MONO ) switch( data->ctl_type ) { case 0: for( int i = ptr; i < ptr + buf_size; i++ ) { STYPE_CALC inp = in[ i ]; denorm_add_white_noise( inp ); #ifndef STYPE_FLOATINGPOINT inp *= 32; #endif STYPE_CALC low = d2 + ( f * d1 ) / 1024; STYPE_CALC high = inp - low - ( q * d1 ) / 1024; STYPE_CALC band = ( f * high ) / 1024 + d1; STYPE_CALC outp; #ifndef STYPE_FLOATINGPOINT outp = low / 32; #else outp = low; #endif outp *= vol; outp /= 256; d1 = band; d2 = low; out[ i ] = (STYPE)outp; } break; case 1: for( int i = ptr; i < ptr + buf_size; i++ ) { STYPE_CALC inp = in[ i ]; denorm_add_white_noise( inp ); #ifndef STYPE_FLOATINGPOINT inp *= 32; #endif STYPE_CALC low = d2 + ( f * d1 ) / 1024; STYPE_CALC high = inp - low - ( q * d1 ) / 1024; STYPE_CALC band = ( f * high ) / 1024 + d1; STYPE_CALC outp; #ifndef STYPE_FLOATINGPOINT outp = high / 32; #else outp = high; #endif outp *= vol; outp /= 256; d1 = band; d2 = low; out[ i ] = (STYPE)outp; } break; case 2: for( int i = ptr; i < ptr + buf_size; i++ ) { STYPE_CALC inp = in[ i ]; denorm_add_white_noise( inp ); #ifndef STYPE_FLOATINGPOINT inp *= 32; #endif STYPE_CALC low = d2 + ( f * d1 ) / 1024; STYPE_CALC high = inp - low - ( q * d1 ) / 1024; STYPE_CALC band = ( f * high ) / 1024 + d1; STYPE_CALC outp; #ifndef STYPE_FLOATINGPOINT outp = band / 32; #else outp = band; #endif outp *= vol; outp /= 256; d1 = band; d2 = low; out[ i ] = (STYPE)outp; } break; case 3: for( int i = ptr; i < ptr + buf_size; i++ ) { STYPE_CALC inp = in[ i ]; denorm_add_white_noise( inp ); #ifndef STYPE_FLOATINGPOINT inp *= 32; #endif STYPE_CALC low = d2 + ( f * d1 ) / 1024; STYPE_CALC high = inp - low - ( q * d1 ) / 1024; STYPE_CALC band = ( f * high ) / 1024 + d1; STYPE_CALC outp; #ifndef STYPE_FLOATINGPOINT outp = ( high + low ) / 32; #else outp = high + low; #endif outp *= vol; outp /= 256; d1 = band; d2 = low; out[ i ] = (STYPE)outp; } break; } if( data->ctl_mix < 256 ) { //Mix result with source: int vol2 = ( data->floating_volume / 256 ); vol2 *= ( 256 - data->ctl_mix ); vol2 /= 256; for( int i = ptr; i < ptr + buf_size; i++ ) { STYPE_CALC inp = in[ i ]; inp *= vol2; inp /= 256; inp += out[ i ]; out[ i ] = (STYPE)inp; } } //...filter enabled end. } fchan->d1 = d1; fchan->d2 = d2; fchan->d3 = d3; } ptr += buf_size; data->tick_counter += buf_size; if( data->tick_counter >= tick_size ) { //Handle filter's tick: if( data->floating_cutoff / 256 > data->ctl_cutoff_freq ) { data->floating_cutoff -= data->ctl_response * 14000; if( data->floating_cutoff / 256 < data->ctl_cutoff_freq ) data->floating_cutoff = data->ctl_cutoff_freq * 256; } else if( data->floating_cutoff / 256 < data->ctl_cutoff_freq ) { data->floating_cutoff += data->ctl_response * 14000; if( data->floating_cutoff / 256 > data->ctl_cutoff_freq ) data->floating_cutoff = data->ctl_cutoff_freq * 256; } if( data->floating_resonance / 256 > data->ctl_resonance ) { data->floating_resonance -= data->ctl_response * 1530; if( data->floating_resonance / 256 < data->ctl_resonance ) data->floating_resonance = data->ctl_resonance * 256; } else if( data->floating_resonance / 256 < data->ctl_resonance ) { data->floating_resonance += data->ctl_response * 1530; if( data->floating_resonance / 256 > data->ctl_resonance ) data->floating_resonance = data->ctl_resonance * 256; } if( data->floating_volume / 256 > data->ctl_volume ) { data->floating_volume -= data->ctl_response * 256; if( data->floating_volume / 256 < data->ctl_volume ) data->floating_volume = data->ctl_volume * 256; } else if( data->floating_volume / 256 < data->ctl_volume ) { data->floating_volume += data->ctl_volume * 256; if( data->floating_volume / 256 > data->ctl_volume ) data->floating_volume = data->ctl_volume * 256; } data->tick_counter = 0; } if( ptr >= sample_frames ) break; } } retval = 1; break; case COMMAND_CLOSE: retval = 1; break; } return retval; }
27.087108
120
0.532223
Sound-Linux-More
0d2058ee7b206d3ca75aaa0e944ca25408010533
20,840
cpp
C++
src/engine/visibility/quadtree.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
2
2019-06-22T23:29:44.000Z
2019-07-07T18:34:04.000Z
src/engine/visibility/quadtree.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
src/engine/visibility/quadtree.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
/** * @file quadtree.cpp * @brief * @author Emmanuel RUFFIO ([email protected]) * @author Frederic SCHERMA ([email protected]) * @date 2001-12-25 * @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved. * @details */ #include "o3d/engine/precompiled.h" #include "o3d/engine/visibility/quadtree.h" #include "o3d/engine/visibility/visibilitymanager.h" #include "o3d/engine/scene/scene.h" #include "o3d/engine/object/camera.h" #include "o3d/engine/object/light.h" #include "o3d/geom/frustum.h" #include "o3d/core/vector2.h" #include "o3d/core/vector3.h" #include "o3d/geom/plane.h" #include "o3d/engine/context.h" #include "o3d/engine/matrix.h" #include "o3d/engine/primitive/primitivemanager.h" #include <algorithm> using namespace o3d; //--------------------------------------------------------------------------------------- // class QuadObject //--------------------------------------------------------------------------------------- QuadObject::QuadObject(Quadtree * _pQuadTree, SceneObject * _object): m_pObject(_object), m_pQuadTree(_pQuadTree) { } QuadObject::~QuadObject() { onDestroyed(); } void QuadObject::addZoneContainer(QuadZone * _zone) { O3D_ASSERT(std::find(m_zoneList.begin(), m_zoneList.end(), _zone) == m_zoneList.end()); m_zoneList.push_back(_zone); } void QuadObject::removeZoneContainer(QuadZone * _zone) { IT_QuadZoneList it = std::find(m_zoneList.begin(), m_zoneList.end(), _zone); O3D_ASSERT(it != m_zoneList.end()); m_zoneList.erase(it); if (m_zoneList.size() == 0) { onUnused(); } } //--------------------------------------------------------------------------------------- // class QuadZone //--------------------------------------------------------------------------------------- QuadZone::QuadZone(Quadtree * _quad, Vector2i _position, Float _size): m_pQuadTree(_quad), m_pParent(nullptr), m_position(_position), m_size(_size), m_subPosition(), m_objectList() { memset((void*)m_pChildren, 0, 4*sizeof(QuadZone*)); } QuadZone::~QuadZone() { for (Int32 k = 0; k < 4; ++k) { deletePtr(m_pChildren[k]); } m_subPosition.clear(); m_size = 0.0f; m_position.zero(); m_pQuadTree = nullptr; if (m_pParent != nullptr) { for (Int32 k = 0; k < 4 ; ++k) { if (m_pParent->m_pChildren[k] == this) { m_pParent->m_pChildren[k] = nullptr; break; } else if (k == 3) { O3D_ASSERT(0); } } } removeAllObjects(); } void QuadZone::draw(Scene *scene) { Vector3 absPosition = getAbsolutePosition(); PrimitiveManager *primitive = scene->getPrimitiveManager(); primitive->modelView().push(); primitive->modelView().translate(absPosition); primitive->setModelviewProjection(); // yellow primitive->setColor(1.0f, 1.0f, 0.0f); // We draw the edges of this zone // primitive->drawYAxisAlignedQuad(P_LINE_LOOP, Vector3(m_size, 1, m_size)); // Daw corners of this zone primitive->beginDraw(P_LINES); // top left primitive->addVertex(Vector3(-m_size, 0, -m_size)); primitive->addVertex(Vector3(-m_size*0.8, 0, -m_size)); primitive->addVertex(Vector3(-m_size, 0, -m_size)); primitive->addVertex(Vector3(-m_size, 0, -m_size*0.8)); // top right primitive->addVertex(Vector3(m_size, 0, -m_size)); primitive->addVertex(Vector3(m_size*0.8, 0, -m_size)); primitive->addVertex(Vector3(m_size, 0, -m_size)); primitive->addVertex(Vector3(m_size, 0, -m_size*0.8)); // bottom left primitive->addVertex(Vector3(-m_size, 0, m_size)); primitive->addVertex(Vector3(-m_size*0.8, 0, m_size)); primitive->addVertex(Vector3(-m_size, 0, m_size)); primitive->addVertex(Vector3(-m_size, 0, m_size*0.8)); // bottom right primitive->addVertex(Vector3(m_size, 0, m_size)); primitive->addVertex(Vector3(m_size*0.8, 0, m_size)); primitive->addVertex(Vector3(m_size, 0, m_size)); primitive->addVertex(Vector3(m_size, 0, m_size*0.8)); primitive->endDraw(); // // Now we draw connections // Vector3 absCenter = absPosition + Vector3(0.5f * m_size, 0.0f, 0.5f * m_size); // // primitive->beginDraw(P_LINES); // for (IT_ZoneObjectList it = m_objectList.begin(); it != m_objectList.end() ; it++) // { // primitive->addVertex(absCenter.getData()); // primitive->addVertex((*it)->getSceneObject()->getAbsoluteMatrix().getTranslationPtr()); // } // primitive->endDraw(); primitive->setColor(1.0f, 0.0f, 0.0f); primitive->modelView().pop(); for (Int32 k = 0; k < 4 ; ++k) { if (m_pChildren[k] != nullptr) { m_pChildren[k]->draw(scene); } } } Vector3 QuadZone::getAbsolutePosition() const { return (m_pQuadTree->getQuadCenterOrigin() + Vector3(Float(m_position[QUAD_X]), 0.0f, Float(m_position[QUAD_Z])) * m_size); } Vector3 QuadZone::getAbsoluteCenter() const { return (m_pQuadTree->getQuadCenter() + Vector3(m_position[QUAD_X] * m_size, 0.0f, m_position[QUAD_Z] * m_size)); } Bool QuadZone::hasChildren(QuadZone * _zone) const { if ((m_pChildren[0] != _zone) && (m_pChildren[1] != _zone) && (m_pChildren[2] != _zone) && (m_pChildren[3] != _zone)) { return False; } else { return True; } } Bool QuadZone::findZone(QuadZone * _zone) const { if ((m_pChildren[0] != _zone) && (m_pChildren[1] != _zone) && (m_pChildren[2] != _zone) && (m_pChildren[3] != _zone)) { for (Int32 k = 0; k < 4; ++k) { if ((m_pChildren[k] != nullptr) && m_pChildren[k]->findZone(_zone)) { return True; } } return False; } else { return True; } } // Add/Remove an object from the zone void QuadZone::addObject(QuadObject * _object) { O3D_ASSERT(_object != nullptr); // We add this zone in the _object _object->addZoneContainer(this); m_objectList.push_back(_object); _object->onDestroyed.connect(this, &QuadZone::onObjectDeletion); } void QuadZone::removeObject(QuadObject * _object) { O3D_ASSERT(_object != nullptr); IT_ZoneObjectList it = std::find(m_objectList.begin(), m_objectList.end(), _object); O3D_ASSERT(it != m_objectList.end()); m_objectList.erase(it); _object->removeZoneContainer(this); disconnect(_object); } void QuadZone::removeAllObjects() { for (IT_ZoneObjectList it = m_objectList.begin() ; it != m_objectList.end() ; it++) { (*it)->removeZoneContainer(this); disconnect(*it); } m_objectList.clear(); } QuadObject * QuadZone::findObject(SceneObject * _object) { for(IT_ZoneObjectList it = m_objectList.begin() ; it != m_objectList.end() ; it++) { if ((*it)->getSceneObject() == _object) { return *it; } } QuadObject * pObject; for (Int32 k = 0; k < 4 ; ++k) { if ((m_pChildren[k] != nullptr) && ((pObject = m_pChildren[k]->findObject(_object)) != nullptr)) { return pObject; } } return nullptr; } const QuadObject * QuadZone::findObject(SceneObject * _object) const { for(CIT_ZoneObjectList it = m_objectList.begin() ; it != m_objectList.end() ; it++) { if ((*it)->getSceneObject() == _object) { return *it; } } QuadObject * pObject; for (Int32 k = 0; k < 4 ; ++k) { if ((m_pChildren[k] != nullptr) && ((pObject = m_pChildren[k]->findObject(_object)) != nullptr)) { return pObject; } } return nullptr; } void QuadZone::setParent(QuadZone * _parent) { O3D_ASSERT(m_pParent == nullptr); m_pParent = _parent; } void QuadZone::onObjectDeletion() { EvtHandler * lSenderObject = getSender(); IT_ZoneObjectList it = std::find(m_objectList.begin(), m_objectList.end(), lSenderObject); O3D_ASSERT(it != m_objectList.end()); m_objectList.erase(it); } //--------------------------------------------------------------------------------------- // class QuadTree //--------------------------------------------------------------------------------------- O3D_IMPLEMENT_DYNAMIC_CLASS1(Quadtree, ENGINE_VISIBILITY_QUADTREE, VisibilityABC) Quadtree::Quadtree( BaseObject *parent, Int32 halfSize, Float zoneSize) : VisibilityABC(parent, Vector3(), Vector3(zoneSize*halfSize, 0.f, zoneSize*halfSize)), m_topZone(2*halfSize+1, 2*halfSize+1), m_objectMap(), m_zoneSize(zoneSize), m_center(0.0f, 0.0f, 0.0f), m_hysteresis(0.2f * zoneSize), m_currentPosition(0.0f, 0.0f, 0.0f) { for (Int32 j = 0 ; j < m_topZone.height() ; ++j) { for (Int32 i = 0 ; i < m_topZone.width() ; ++i) { m_topZone(i,j) = new QuadZone(this, Vector2i(i - halfSize, j - halfSize), m_zoneSize); } } } Quadtree::~Quadtree() { clear(); } void Quadtree::translate(const Vector2i & _move) { // TODO // Optimize with memcpy m_center += Vector3(_move[QUAD_X] * m_zoneSize, 0.0f, _move[QUAD_Z] * m_zoneSize); m_bbox.setCenter(m_center); if (Int32(_move.normInf()) >= m_topZone.width()) { Int32 halfSize = m_topZone.width() / 2; Int32 i,j; // We must destroy all the array for (Int32 k = 0; k < m_topZone.elt() ; ++k) { m_topZone[k]->removeAllObjects(); m_topZone[k]->setSize(m_zoneSize); i = Int32(k % m_topZone.width()) - halfSize; j = Int32(k / m_topZone.width()) - halfSize; m_topZone[k]->setPosition(Vector2i(i,j)); } return; } if ((_move[QUAD_Z] > 0) && (_move[QUAD_Z] < m_topZone.width())) { Int32 halfSize = m_topZone.width() / 2; for (Int32 j = 0; j < m_topZone.height(); ++j) { for (Int32 i = 0 ; i < _move[QUAD_Z]; ++i) { deletePtr(m_topZone(i,j)); } } for (Int32 j = 0; j < m_topZone.height(); ++j) { for (Int32 i = 0 ; i < m_topZone.width() - _move[QUAD_Z]; ++i) { m_topZone(i,j) = m_topZone(i + _move[QUAD_Z], j); m_topZone(i,j)->setPosition(Vector2i(i - halfSize, j - halfSize)); } } for (Int32 j = 0; j < m_topZone.height(); ++j) { for (Int32 i = m_topZone.width() - _move[QUAD_Z]; i < m_topZone.width() ; ++i) { m_topZone(i,j) = new QuadZone(this, Vector2i(i - halfSize, j - halfSize), m_zoneSize); } } } else if ((_move[QUAD_Z] < 0) && (_move[QUAD_Z] > -m_topZone.width())) { Int32 halfSize = m_topZone.width() / 2; for (Int32 j = 0; j < m_topZone.height(); ++j) { for (Int32 i = m_topZone.width() + _move[QUAD_Z] ; i < m_topZone.width() ; ++i) { deletePtr(m_topZone(i,j)); } } for (Int32 j = 0; j < m_topZone.height(); ++j) { for (Int32 i = m_topZone.width() - 1 ; i >= -_move[QUAD_Z]; --i) { m_topZone(i,j) = m_topZone(i + _move[QUAD_Z], j); m_topZone(i,j)->setPosition(Vector2i(i - halfSize, j - halfSize)); } } for (Int32 j = 0; j < m_topZone.height(); ++j) { for (Int32 i = 0; i < -_move[QUAD_Z]; ++i) { m_topZone(i,j) = new QuadZone(this, Vector2i(i - halfSize, j - halfSize), m_zoneSize); } } } if ((_move[QUAD_X] > 0) && (_move[QUAD_X] < Int32(m_topZone.height()))) { Int32 halfSize = m_topZone.height() / 2; for (Int32 i = 0; i < m_topZone.width(); ++i) { for (Int32 j = 0 ; j < _move[QUAD_X]; ++j) { deletePtr(m_topZone(i,j)); } } for (Int32 i = 0; i < m_topZone.width(); ++i) { for (Int32 j = 0 ; j < m_topZone.height() - _move[QUAD_X]; ++j) { m_topZone(i,j) = m_topZone(i, j + _move[QUAD_X]); m_topZone(i,j)->setPosition(Vector2i(i - halfSize, j - halfSize)); } } for (Int32 i = 0; i < m_topZone.width(); ++i) { for (Int32 j = m_topZone.height() - _move[QUAD_X]; j < m_topZone.height() ; ++j) { m_topZone(i,j) = new QuadZone(this, Vector2i(i - halfSize, j - halfSize), m_zoneSize); } } } else if ((_move[QUAD_X] < 0) && (_move[QUAD_X] > -m_topZone.height())) { Int32 halfSize = m_topZone.height() / 2; for (Int32 i = 0; i < m_topZone.width(); ++i) { for (Int32 j = m_topZone.height() + _move[QUAD_X] ; j < m_topZone.height() ; ++j) { deletePtr(m_topZone(i,j)); } } for (Int32 i = 0; i < m_topZone.width(); ++i) { for (Int32 j = m_topZone.height() - 1 ; j >= -_move[QUAD_X]; --j) { m_topZone(i,j) = m_topZone(i, j + _move[QUAD_X]); m_topZone(i,j)->setPosition(Vector2i(i - halfSize, j - halfSize)); } } for (Int32 i = 0; i < m_topZone.width(); ++i) { for (Int32 j = 0; j < -_move[QUAD_X]; ++j) { m_topZone(i,j) = new QuadZone(this, Vector2i(i - halfSize, j - halfSize), m_zoneSize); } } } } void Quadtree::onObjectUnused() { QuadObject * lObject = static_cast<QuadObject*>(getSender()); IT_ObjectMap it = m_objectMap.find(lObject->getSceneObject()); O3D_ASSERT(it != m_objectMap.end()); if (it != m_objectMap.end()) { m_objectMap.erase(it); } deletePtr(lObject); } // Clear all objects contained in the quadTree void Quadtree::clear() { for (Int32 k = 0 ; k < m_topZone.elt() ; ++k) { deletePtr(m_topZone[k]); } m_topZone.free(); EvtManager::instance()->processEvent(this); } inline Int32 Quadtree::getNumObjects()const { return Int32(m_objectMap.size()); } // Return the neighbor of a zone QuadZone * Quadtree::getNeighbor(const QuadZone & _zone, QuadDirection _direction) { O3D_ASSERT(!_zone.hasParent()); Int32 halfSize = m_topZone.width() / 2; Vector2i zoneRequested(_zone.getPosition()); switch (_direction) { case NORTH: zoneRequested[QUAD_X]++; break; case SOUTH: zoneRequested[QUAD_X]--; break; case EAST: zoneRequested[QUAD_Z]++; break; case WEST: zoneRequested[QUAD_Z]--; break; default: O3D_ASSERT(0); break; } // If the requested neighbor is outside the quadtree range, we return nullptr if (zoneRequested.normInf() > halfSize) { return nullptr; } else { return m_topZone(zoneRequested[QUAD_Z], zoneRequested[QUAD_X]); } } // Add an object (we suppose that it doesn't exist) void Quadtree::addObject(SceneObject *object) { Vector3 zoneOrigin(getQuadCenterOrigin()); Vector3 diff = object->getAbsoluteMatrix().getTranslation() - zoneOrigin; diff /= m_zoneSize; Vector2i relativPos(Int32(floorf(diff[Z])), Int32(floorf(diff[X]))); Int32 halfSize = m_topZone.width() / 2; // The quadtree is a square so ... if (relativPos.normInf() > halfSize) { // The object is outside the range of the quadtree // O3D_ERROR(E_InvalidParameter("Attempt to add an object outside the quadtree range")); O3D_WARNING("Attempt to add an object outside the quadtree range"); return; } QuadObject * newQuadObject = new QuadObject(this, object); m_topZone(halfSize + relativPos[QUAD_Z], halfSize + relativPos[QUAD_X])->addObject(newQuadObject); newQuadObject->onUnused.connect(this, &Quadtree::onObjectUnused, CONNECTION_ASYNCH); // Finally we add the object in the map m_objectMap[object] = newQuadObject; } // Remove an object. Function called by the user Bool Quadtree::removeObject(SceneObject *object) { if (object) { IT_ObjectMap it = m_objectMap.find(object); //O3D_ASSERT(it != m_objectMap.end()); if (it != m_objectMap.end()) { deletePtr(it->second); m_objectMap.erase(it); return True; } return False; } else { O3D_ERROR(E_InvalidParameter("object must be non null")); return False; } } // Update an object void Quadtree::updateObject(SceneObject *object) { if (object) { IT_ObjectMap it = m_objectMap.find(object); O3D_ASSERT(it != m_objectMap.end()); // What must be done ? QuadObject * pQuadObject = it->second; O3D_ASSERT(pQuadObject->getZoneNumber() > 0); // Only one owner for each object is supported yet //O3DVector3 relative = object->getAbsoluteMatrix().GetTranslation() - pQuadObject->getZoneList()[0]->getAbsoluteCenter(); Vector3 center = pQuadObject->getZoneList()[0]->getAbsoluteCenter(); // left plane Plane leftPlane(Vector3(-1.f, 0.f, 0.f), Vector3(center.x() - m_zoneSize * 0.5f, 0.f, 0.f)); Geometry::Clipping left = object->checkBounding(leftPlane); if (left != Geometry::CLIP_OUTSIDE) { //O3DApps::Message(O3DString("Change zone ") << object->getName(), ""); // Outside the previous zone removeObject(object); // Can be optimized a lot addObject(object); // Same here return; } // right plane Plane rightPlane(Vector3(1.f, 0.f, 0.f), Vector3(center.x() + m_zoneSize * 0.5f, 0.f, 0.f)); Geometry::Clipping right = object->checkBounding(rightPlane); if (right != Geometry::CLIP_OUTSIDE) { //O3DApps::Message(O3DString("Change zone ") << object->getName(), ""); // Outside the previous zone removeObject(object); // Can be optimized a lot addObject(object); // Same here return; } // bottom plane Plane bottomPlane(Vector3(0.f, 0.f, -1.f), Vector3(0.f, 0.f, center.z() - m_zoneSize * 0.5f)); Geometry::Clipping bottom = object->checkBounding(bottomPlane); if (bottom != Geometry::CLIP_OUTSIDE) { //O3DApps::Message(O3DString("Change zone ") << object->getName(), ""); // Outside the previous zone removeObject(object); // Can be optimized a lot addObject(object); // Same here return; } // top plane Plane topPlane(Vector3(0.f, 0.f, 1.f), Vector3(0.f, 0.f, center.z() + m_zoneSize * 0.5f)); Geometry::Clipping top = object->checkBounding(topPlane); if (top != Geometry::CLIP_OUTSIDE) { //System::print(String("Change zone ") << object->getName(), ""); // Outside the previous zone removeObject(object); // Can be optimized a lot addObject(object); // Same here return; } /*if (((left != Geometry::CLIP_OUTSIDE) || (right != Geometry::CLIP_OUTSIDE) || (top != Geometry::CLIP_OUTSIDE) || (bottom != Geometry::CLIP_OUTSIDE))) { // Outside the previous zone removeObject(object); // Can be optimized a lot //System::print(String("Change zone ") << object->getName(), ""); addObject(object); // Same here }*/ /*if (relative.normInf() > m_zoneSize) { // Outside the previous zone removeObject(object); // Can be optimized a lot printf("change zone %s\n", object->getName().toUtf8().getData()); addObject(object); // Same here }*/ } } // Check for visible object and add it to visibility manager void Quadtree::checkVisibleObject(const VisibilityInfos & _infos) { m_currentPosition = _infos.cameraPosition; Vector2f relativPos(m_currentPosition[Z] - m_center[Z], m_currentPosition[X] - m_center[X]); if (relativPos.normInf() > 0.5f*m_zoneSize + m_hysteresis) { // We need to change the quadtree // Which parts of the quadtree need to be changed relativPos /= m_zoneSize; relativPos[QUAD_Z] = floorf(relativPos[QUAD_Z] + 0.5f); relativPos[QUAD_X] = floorf(relativPos[QUAD_X] + 0.5f); Vector2i translation((Int32)relativPos[QUAD_Z], (Int32)relativPos[QUAD_X]); //if (translation.norm1() > 0) translate(translation); } SceneObject * object = nullptr; for (Int32 k = 0; k < m_topZone.elt() ; ++k) { // Visibility checks ... for (CIT_ZoneObjectList it = m_topZone[k]->getObjectList().begin() ; it != m_topZone[k]->getObjectList().end() ; it++) { object = (*it)->getSceneObject(); if (_infos.viewUseMaxDistance) { Float length = (object->getAbsoluteMatrix().getTranslation() - m_currentPosition).length(); if (length > _infos.viewMaxDistance) { continue; } } // depending if it is light or something else if (object->isLight()) { getScene()->getVisibilityManager()->addEffectiveLight(static_cast<Light*>(object)); } // even if it is as light it can be drawable for symbolics if (object->hasDrawable()) { getScene()->getVisibilityManager()->addObjectToDraw(object); } } } } void Quadtree::draw(const DrawInfo &drawInfo) { if (getScene()->getDrawObject(Scene::DRAW_QUADTREE)) { PrimitiveAccess primitive = getScene()->getPrimitiveManager()->access(drawInfo); // setup modelview primitive->modelView().set(getScene()->getActiveCamera()->getModelviewMatrix()); primitive->setColor(1.f, 1.f, 1.f); getScene()->getContext()->setLineWidth(2.0f); for (Int32 j = 0 ; j < m_topZone.height() ; ++j) { for (Int32 i = 0 ; i < m_topZone.width() ; ++i) { m_topZone(i,j)->draw(getScene()); } } getScene()->getContext()->setDefaultLineWidth(); primitive->setColor(0.0f, 1.0f, 0.0f); //primitive->modelView().push(); // Vector3 absPos(GetQuadOrigin()); // primitive->modelView().translate(absPos); // primitive->wireSphere1(Vector3(20.f,20.f,20.f)); //primitive->modelView().pop() } }
29.393512
128
0.614971
dream-overflow
0d251186cca5970cbdcc2327dd32d62023d31798
1,358
cpp
C++
tools/CustomUI/customUI.cpp
RuanauR/BetterEdit
9e4c031b8dec0c80f901f79d9f4a40173a52725b
[ "MIT" ]
30
2021-01-25T22:25:05.000Z
2022-01-22T13:18:19.000Z
tools/CustomUI/customUI.cpp
RuanauR/BetterEdit
9e4c031b8dec0c80f901f79d9f4a40173a52725b
[ "MIT" ]
9
2021-07-03T11:41:47.000Z
2022-03-30T15:14:46.000Z
tools/CustomUI/customUI.cpp
RuanauR/BetterEdit
9e4c031b8dec0c80f901f79d9f4a40173a52725b
[ "MIT" ]
3
2021-07-01T20:52:24.000Z
2022-01-13T16:16:58.000Z
#include "customUI.hpp" #include "../../hooks/EditorPauseLayer.hpp" void EditorPauseLayer_CB::onCustomizeUI(CCObject*) { UIManager::get()->startCustomizing(); this->onResume(nullptr); } void loadEditorCustomizations(EditorUI* self) { self->m_pCopyBtn->removeFromParent(); self->m_pPasteBtn->removeFromParent(); self->m_pCopyPasteBtn->removeFromParent(); self->m_pEditSpecialBtn->removeFromParent(); self->m_pEditGroupBtn->removeFromParent(); self->m_pEditObjectBtn->removeFromParent(); self->m_pCopyValuesBtn->removeFromParent(); self->m_pPasteStateBtn->removeFromParent(); self->m_pPasteColorBtn->removeFromParent(); self->m_pEditHSVBtn->removeFromParent(); self->m_pGoToLayerBtn->removeFromParent(); self->m_pDeselectBtn->removeFromParent(); } void loadUICustomizeBtn(EditorPauseLayer* self) { auto menu = as<CCMenu*>(self->m_pButton0->getParent()); auto winSize = cocos2d::CCDirector::sharedDirector()->getWinSize(); // auto spr = ButtonSprite::create( // "Customize UI", 0, 0, "goldFont.fnt", "GJ_button_01.png", 0, .8f // ); // spr->setScale(.7f); // auto btn = CCMenuItemSpriteExtra::create( // spr, self, menu_selector(EditorPauseLayer_CB::onCustomizeUI) // ); // btn->setPosition(0.0f, winSize.height - 60.0f); // menu->addChild(btn); }
34.820513
75
0.693667
RuanauR
0d2859253f6d4463f3e6be5b72a87d4de46e12f0
527
cpp
C++
solutions/228.summary-ranges.318085037.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
78
2020-10-22T11:31:53.000Z
2022-02-22T13:27:49.000Z
solutions/228.summary-ranges.318085037.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
null
null
null
solutions/228.summary-ranges.318085037.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
26
2020-10-23T15:10:44.000Z
2021-11-07T16:13:50.000Z
class Solution { public: vector<string> summaryRanges(vector<int> &nums) { vector<pair<int, int>> ranges; for (int n : nums) { if (ranges.empty() || ranges.back().second + 1 != n) ranges.emplace_back(n, n); else ranges.back().second++; } vector<string> result; for (auto &p : ranges) if (p.first == p.second) result.push_back(to_string(p.first)); else result.push_back(to_string(p.first) + "->" + to_string(p.second)); return result; } };
21.958333
74
0.56926
satu0king
0d293d4448c4883356ecfdab4bca391a47f039a1
234
cpp
C++
gds/vadd.cpp
TheGPU/amdgpu-code
bb249b33b8b9ad15c195b591959f5cedfb552044
[ "MIT" ]
4
2018-02-11T13:00:57.000Z
2018-06-02T13:15:47.000Z
gds/vadd.cpp
IceNarwhal/amdgpu-code
bb249b33b8b9ad15c195b591959f5cedfb552044
[ "MIT" ]
2
2017-04-04T19:53:04.000Z
2017-05-10T16:15:12.000Z
gds/vadd.cpp
TheGPU/amdgpu-code
bb249b33b8b9ad15c195b591959f5cedfb552044
[ "MIT" ]
1
2021-05-21T08:08:43.000Z
2021-05-21T08:08:43.000Z
#include<iostream> #include<hip/hip_runtime.h> #include<hip/hip_runtime_api.h> #define LEN 16 __global__ void vAdd(hipLaunchParm lp, float *A, float *B, float *C){ int tx = hipThreadIdx_x; C[tx] = A[tx] + B[tx]; } int main(){}
18
69
0.683761
TheGPU
0d300a3aaa94ad42feb187f211b34dc921b16a82
3,810
cpp
C++
C Plus Plus/Graph/Floyd_Warshall_Shortest_Path.cpp
Amisha328/DS-Algo
34576fbe95717b1d3e2f75b0a04c631ca1833091
[ "MIT" ]
8
2021-06-19T12:49:46.000Z
2021-08-01T05:32:54.000Z
C Plus Plus/Graph/Floyd_Warshall_Shortest_Path.cpp
Amisha328/DS-Algo
34576fbe95717b1d3e2f75b0a04c631ca1833091
[ "MIT" ]
61
2021-06-10T08:22:51.000Z
2021-07-29T05:47:52.000Z
C Plus Plus/Graph/Floyd_Warshall_Shortest_Path.cpp
Amisha328/DS-Algo
34576fbe95717b1d3e2f75b0a04c631ca1833091
[ "MIT" ]
6
2021-06-10T08:28:26.000Z
2021-07-23T03:36:46.000Z
/* Floyd Warshall Shortest Path Algorithm is applied to find the shortest distance between two vertices in a graph. It is based on a formula given by floyd-warshall i.e. distance(k)[i][j] = minimum of (distance(k-1)[i][j] , distance(k-1)[i][k] + distance(k-1)[k][j]) where, i and j are the source and destination vertex respectively and, k is the order of path matrix formed. */ // Implementation #include<bits/stdc++.h> using namespace std; // Structure of Graph class Graph{ // Number of vetices in a graph int vertices; // Path matrix for graph. vector< vector<int> > path; // Matrix to store the minimum distance between the two vertices. vector< vector<int> > min_distance; public: // Constructor Graph(int vertices){ this->vertices = vertices; // Initailize the path matrix with the size of number of vertices, // with the inital value to be infinite i.e. INT_MAX path.assign(vertices, vector<int>(vertices, INT_MAX)); min_distance.assign(vertices, vector<int>(vertices, INT_MAX)); // The shortes distance of a vertex to itself will always be zero. for(int i = 0; i<vertices; i++){ path[i][i] = 0; min_distance[i][i] = 0; } } void floyd_warshall(); void addEdge(int, int, int); void printGraph(); void printMinimumDistance(); }; // Method to add edge between two vertices with specific weight void Graph::addEdge(int source, int destination, int weight){ path[source][destination] = weight; } // Mehtod to find the shortet distance matrix using floyd-warshall algorithm void Graph::floyd_warshall(){ // Copying the path matrix to the min_distance matrix min_distance = path; // k - to determine the order of matrix for(int k=0; k<vertices; k++){ // i - to determine to source vertex for(int i=0; i<vertices; i++){ // j- to determine the destination vertex for(int j=0; j<vertices; j++){ // Condition for implementation of formula if (min_distance[i][j] > (min_distance[i][k] + min_distance[k][j]) && (min_distance[k][j] != INT_MAX && min_distance[i][k] != INT_MAX)) min_distance[i][j] = min_distance[i][k] + min_distance[k][j]; } } } } // Method to print the min_distance matrix void Graph::printGraph(){ for(int i=0; i<vertices; i++){ for(int j=0; j<vertices; j++){ if(path[i][j] == INT_MAX) cout<<"INF "; else cout<<path[i][j]<<" "; } cout<<endl; } } // Method to print the min_distance matrix void Graph::printMinimumDistance(){ for(int i=0; i<vertices; i++){ for(int j=0; j<vertices; j++){ if(min_distance[i][j] == INT_MAX) cout<<"INF "; else cout<<min_distance[i][j]<<" "; } cout<<endl; } } int main(){ // Object of graph with 5 vertices. Graph graph(5); // Adding edges to the graph. graph.addEdge(0, 1, 2); graph.addEdge(0, 2, 4); graph.addEdge(1, 2, 5); graph.addEdge(1, 4, 1); graph.addEdge(1, 3, 3); graph.addEdge(2, 4, 6); graph.addEdge(3, 4, 10); cout<<"\nDistance from each vertex : "<<endl; graph.printGraph(); graph.floyd_warshall(); cout<<"\nShortest distance by Floyd Wrashall Algorithm is : "<<endl; graph.printMinimumDistance(); return 0; } /* Time Complexity of Floyd Warshall is O(|V|^3). Space Complexity of Floyd Warshall is O(|V|^2), where V is number of vertices. */
28.222222
104
0.572441
Amisha328
0d36f6d5205dcebed842075a6aaef7dc389eea5b
1,720
hxx
C++
include/usagi/json/picojson/to_bool.hxx
usagi/usagi
2d57d21eeb92eadfdf4154a3e470aebfc3e388e5
[ "MIT" ]
2
2016-11-20T04:59:17.000Z
2017-02-13T01:44:37.000Z
include/usagi/json/picojson/to_bool.hxx
usagi/usagi
2d57d21eeb92eadfdf4154a3e470aebfc3e388e5
[ "MIT" ]
3
2015-09-28T12:00:02.000Z
2015-09-28T12:03:21.000Z
include/usagi/json/picojson/to_bool.hxx
usagi/usagi
2d57d21eeb92eadfdf4154a3e470aebfc3e388e5
[ "MIT" ]
3
2017-07-02T06:09:47.000Z
2018-07-09T01:00:57.000Z
#pragma once #include "type.hxx" namespace usagi::json::picojson { static inline auto to_bool( const boolean_type in ) { return in; } /// @note ECMA-262 NaN: Boolean( 0/0 ) -> false /// @note ECMA-262 +Inf: Boolean( +1/0 ) -> true /// @note ECMA-262 -Inf: Boolean( -1/0 ) -> true static inline auto to_bool( const number_type in ) { return not std::isnan( in ) and in != 0; } /// @note ECMA-262 empty-string: Boolean( "" ) -> false static inline auto to_bool( const string_type& in ) { return not in.empty(); } /// @note: ECMA-262 array: Boolean( [] ) -> true static inline auto to_bool( const array_type& ) { return true; } /// @note: ECMA-262 object: Boolean( {} ) -> true static inline auto to_bool( const object_type& ) { return true; } /// @note: ECMA-262 null: Boolean( null ) -> false static inline auto to_bool( const null_type& = null_type() ) { return false; } /// @brief ECMA-262 Boolean( in ) 互換変換 static inline auto to_bool( const value_type& in ) { if ( in.is< boolean_type >() ) return to_bool( in.get< boolean_type >() ); if ( in.is< number_type >() ) return to_bool( in.get< number_type >() ); if ( in.is< string_type >() ) return to_bool( in.get< string_type >() ); if ( in.is< array_type >() ) return to_bool( in.get< array_type >() ); if ( in.is< object_type >() ) return to_bool( in.get< object_type >() ); if ( in.is< null_type >() ) return to_bool(); return false; } /// @brief to_bool した結果を value_type で得る syntax sugar static inline auto to_bool_value( const value_type& in ) { return value_type( to_bool( in ) ); } }
27.741935
68
0.59593
usagi
0d379fa4ba8a49230f96d1116eb76ef27edaeec0
5,126
cc
C++
src/Hmm/HiddenMarkovModel.cc
alexanderrichard/squirrel
12614a9eb429500c8f341654043f33a1b6bd1d31
[ "AFL-3.0" ]
63
2016-07-08T13:35:27.000Z
2021-01-13T18:37:13.000Z
src/Hmm/HiddenMarkovModel.cc
alexanderrichard/squirrel
12614a9eb429500c8f341654043f33a1b6bd1d31
[ "AFL-3.0" ]
4
2017-08-04T09:25:10.000Z
2022-02-24T15:38:52.000Z
src/Hmm/HiddenMarkovModel.cc
alexanderrichard/squirrel
12614a9eb429500c8f341654043f33a1b6bd1d31
[ "AFL-3.0" ]
30
2016-05-11T02:24:46.000Z
2021-11-12T14:06:20.000Z
/* * Copyright 2016 Alexander Richard * * This file is part of Squirrel. * * Licensed under the Academic Free License 3.0 (the "License"). * You may not use this file except in compliance with the License. * You should have received a copy of the License along with Squirrel. * If not, see <https://opensource.org/licenses/AFL-3.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. */ /* * HiddenMarkovModel.cc * * Created on: Mar 4, 2015 * Author: richard */ #include "HiddenMarkovModel.hh" using namespace Hmm; /* * HiddenMarkovModel */ const Core::ParameterEnum HiddenMarkovModel::paramHmmType_("type", "standard-hmm, single-state-hmm", "standard-hmm", "hidden-markov-model"); const Core::ParameterString HiddenMarkovModel::paramHmmFile_("model-file", "", "hidden-markov-model"); const Core::ParameterString HiddenMarkovModel::paramTransitionProbabilityFile_("transition-probability-file", "", "hidden-markov-model"); HiddenMarkovModel::HiddenMarkovModel() : hmmFile_(Core::Configuration::config(paramHmmFile_)), transitionProbabilityFile_(Core::Configuration::config(paramTransitionProbabilityFile_)), nClasses_(0), nStates_(0), isInitialized_(false) {} void HiddenMarkovModel::initialize() { require(!isInitialized_); // load hmm definition if (hmmFile_.empty()) Core::Error::msg("HiddenMarkovModel::initialize: hmm-file not specified.") << Core::Error::abort; statesPerClass_.read(hmmFile_); // determine start states nClasses_ = statesPerClass_.size(); startStates_.resize(nClasses_); startStates_.at(0) = 0; for (u32 c = 1; c < nClasses_; c++) startStates_.at(c) = startStates_.at(c-1) + statesPerClass_.at(c-1); // compute mapping from state to class stateToClass_.resize(statesPerClass_.sum()); u32 state = 0; for (u32 c = 0; c < statesPerClass_.size(); c++) { for (u32 s = 0; s < statesPerClass_.at(c); s++) { stateToClass_.at(state) = c; state++; } } nStates_ = stateToClass_.size(); // load transition probabilities if (transitionProbabilityFile_.empty()) Core::Error::msg("HiddenMarkovModel::initialize: transition-probability-file not specified.") << Core::Error::abort; loopScores_.read(transitionProbabilityFile_); forwardScores_.resize(loopScores_.size()); forwardScores_.fill(1.0); forwardScores_.add(loopScores_, (Float)-1.0); loopScores_.log(); forwardScores_.log(); isInitialized_ = true; } u32 HiddenMarkovModel::nClasses() const { require(isInitialized_); return nClasses_; } u32 HiddenMarkovModel::nStates() const { require(isInitialized_); return nStates_; } u32 HiddenMarkovModel::nStates(u32 c) const { require(isInitialized_); require_lt(c, nClasses_); return statesPerClass_.at(c); } u32 HiddenMarkovModel::getClass(u32 state) const { require(isInitialized_); require_lt(state, nStates_); return stateToClass_.at(state); } u32 HiddenMarkovModel::startState(u32 c) const { require(isInitialized_); require_lt(c, nClasses_); return startStates_.at(c); } bool HiddenMarkovModel::isEndState(u32 state) const { require(isInitialized_); require_lt(state, nStates_); return ( (state == nStates_ - 1) || (stateToClass_.at(state) != stateToClass_.at(state+1)) ); } u32 HiddenMarkovModel::successor(u32 state) const { require(isInitialized_); require_lt(state, nStates_); require(!isEndState(state)); return state + 1; } Float HiddenMarkovModel::transitionScore(u32 stateFrom, u32 stateTo) const { require(isInitialized_); require_le(stateFrom, nStates_); if (stateFrom == stateTo) // loop transition return loopScores_.at(stateFrom); else if ((isEndState(stateFrom)) || (stateFrom + 1 == stateTo)) // forward transition return forwardScores_.at(stateFrom); else // invalid transition return -Types::inf<Float>(); } HiddenMarkovModel* HiddenMarkovModel::create() { switch ((HmmType) Core::Configuration::config(paramHmmType_)) { case standardHmm: Core::Log::os("Create standard-hmm."); return new HiddenMarkovModel(); break; case singleStateHmm: Core::Log::os("Create single-state-hmm."); return new SingleStateHiddenMarkovModel(); break; default: return 0; // this can not happen } } /* * SingleStateHiddenMarkovModel */ const Core::ParameterInt SingleStateHiddenMarkovModel::paramNumberOfClasses_("number-of-classes", 0, "hidden-markov-model"); SingleStateHiddenMarkovModel::SingleStateHiddenMarkovModel() : Precursor() { nClasses_ = Core::Configuration::config(paramNumberOfClasses_); nStates_ = nClasses_; require_gt(nClasses_, 0); } void SingleStateHiddenMarkovModel::initialize() { stateToClass_.resize(nStates_); for (u32 c = 0; c < nStates_; c++) stateToClass_.at(c) = c; statesPerClass_.resize(nClasses_); statesPerClass_.fill(1); startStates_.resize(nClasses_); for (u32 c = 0; c < nStates_; c++) startStates_.at(c) = c; loopScores_.resize(nStates_); loopScores_.fill(0.0); forwardScores_.resize(nStates_); forwardScores_.fill(0.0); isInitialized_ = true; }
28.960452
140
0.738978
alexanderrichard
0d3822f67c8867bd02497940e7c7d798801b842a
9,982
cpp
C++
plugins/WinVST/Ditherbox/Ditherbox.cpp
PanieriLorenzo/airwindows
03fe0bddb4689eddd5444116ba4862942d069b76
[ "MIT" ]
446
2018-01-22T18:03:39.000Z
2022-03-31T18:57:27.000Z
plugins/WinVST/Ditherbox/Ditherbox.cpp
PanieriLorenzo/airwindows
03fe0bddb4689eddd5444116ba4862942d069b76
[ "MIT" ]
33
2018-01-24T20:36:48.000Z
2022-03-23T21:27:37.000Z
plugins/WinVST/Ditherbox/Ditherbox.cpp
PanieriLorenzo/airwindows
03fe0bddb4689eddd5444116ba4862942d069b76
[ "MIT" ]
71
2018-02-16T18:17:21.000Z
2022-03-24T21:31:46.000Z
/* ======================================== * Ditherbox - Ditherbox.h * Copyright (c) 2016 airwindows, All rights reserved * ======================================== */ #ifndef __Ditherbox_H #include "Ditherbox.h" #endif AudioEffect* createEffectInstance(audioMasterCallback audioMaster) {return new Ditherbox(audioMaster);} Ditherbox::Ditherbox(audioMasterCallback audioMaster) : AudioEffectX(audioMaster, kNumPrograms, kNumParameters) { A = 0.86; Position = 99999999; contingentErrL = 0.0; contingentErrR = 0.0; currentDitherL = 0.0; currentDitherR = 0.0; bynL[0] = 1000; bynL[1] = 301; bynL[2] = 176; bynL[3] = 125; bynL[4] = 97; bynL[5] = 79; bynL[6] = 67; bynL[7] = 58; bynL[8] = 51; bynL[9] = 46; bynL[10] = 1000; noiseShapingL = 0.0; bynR[0] = 1000; bynR[1] = 301; bynR[2] = 176; bynR[3] = 125; bynR[4] = 97; bynR[5] = 79; bynR[6] = 67; bynR[7] = 58; bynR[8] = 51; bynR[9] = 46; bynR[10] = 1000; noiseShapingR = 0.0; NSOddL = 0.0; prevL = 0.0; nsL[0] = 0; nsL[1] = 0; nsL[2] = 0; nsL[3] = 0; nsL[4] = 0; nsL[5] = 0; nsL[6] = 0; nsL[7] = 0; nsL[8] = 0; nsL[9] = 0; nsL[10] = 0; nsL[11] = 0; nsL[12] = 0; nsL[13] = 0; nsL[14] = 0; nsL[15] = 0; NSOddR = 0.0; prevR = 0.0; nsR[0] = 0; nsR[1] = 0; nsR[2] = 0; nsR[3] = 0; nsR[4] = 0; nsR[5] = 0; nsR[6] = 0; nsR[7] = 0; nsR[8] = 0; nsR[9] = 0; nsR[10] = 0; nsR[11] = 0; nsR[12] = 0; nsR[13] = 0; nsR[14] = 0; nsR[15] = 0; lastSampleL = 0.0; outSampleL = 0.0; lastSampleR = 0.0; outSampleR = 0.0; iirSampleAL = 0.0; iirSampleBL = 0.0; iirSampleCL = 0.0; iirSampleDL = 0.0; iirSampleEL = 0.0; iirSampleFL = 0.0; iirSampleGL = 0.0; iirSampleHL = 0.0; iirSampleIL = 0.0; iirSampleJL = 0.0; iirSampleKL = 0.0; iirSampleLL = 0.0; iirSampleML = 0.0; iirSampleNL = 0.0; iirSampleOL = 0.0; iirSamplePL = 0.0; iirSampleQL = 0.0; iirSampleRL = 0.0; iirSampleSL = 0.0; iirSampleTL = 0.0; iirSampleUL = 0.0; iirSampleVL = 0.0; iirSampleWL = 0.0; iirSampleXL = 0.0; iirSampleYL = 0.0; iirSampleZL = 0.0; iirSampleAR = 0.0; iirSampleBR = 0.0; iirSampleCR = 0.0; iirSampleDR = 0.0; iirSampleER = 0.0; iirSampleFR = 0.0; iirSampleGR = 0.0; iirSampleHR = 0.0; iirSampleIR = 0.0; iirSampleJR = 0.0; iirSampleKR = 0.0; iirSampleLR = 0.0; iirSampleMR = 0.0; iirSampleNR = 0.0; iirSampleOR = 0.0; iirSamplePR = 0.0; iirSampleQR = 0.0; iirSampleRR = 0.0; iirSampleSR = 0.0; iirSampleTR = 0.0; iirSampleUR = 0.0; iirSampleVR = 0.0; iirSampleWR = 0.0; iirSampleXR = 0.0; iirSampleYR = 0.0; iirSampleZR = 0.0; //this is reset: values being initialized only once. Startup values, whatever they are. _canDo.insert("plugAsChannelInsert"); // plug-in can be used as a channel insert effect. _canDo.insert("plugAsSend"); // plug-in can be used as a send effect. _canDo.insert("x2in2out"); setNumInputs(kNumInputs); setNumOutputs(kNumOutputs); setUniqueID(kUniqueId); canProcessReplacing(); // supports output replacing canDoubleReplacing(); // supports double precision processing programsAreChunks(true); vst_strncpy (_programName, "Default", kVstMaxProgNameLen); // default program name } Ditherbox::~Ditherbox() {} VstInt32 Ditherbox::getVendorVersion () {return 1000;} void Ditherbox::setProgramName(char *name) {vst_strncpy (_programName, name, kVstMaxProgNameLen);} void Ditherbox::getProgramName(char *name) {vst_strncpy (name, _programName, kVstMaxProgNameLen);} //airwindows likes to ignore this stuff. Make your own programs, and make a different plugin rather than //trying to do versioning and preventing people from using older versions. Maybe they like the old one! static float pinParameter(float data) { if (data < 0.0f) return 0.0f; if (data > 1.0f) return 1.0f; return data; } VstInt32 Ditherbox::getChunk (void** data, bool isPreset) { float *chunkData = (float *)calloc(kNumParameters, sizeof(float)); chunkData[0] = A; /* Note: The way this is set up, it will break if you manage to save settings on an Intel machine and load them on a PPC Mac. However, it's fine if you stick to the machine you started with. */ *data = chunkData; return kNumParameters * sizeof(float); } VstInt32 Ditherbox::setChunk (void* data, VstInt32 byteSize, bool isPreset) { float *chunkData = (float *)data; A = pinParameter(chunkData[0]); /* We're ignoring byteSize as we found it to be a filthy liar */ /* calculate any other fields you need here - you could copy in code from setParameter() here. */ return 0; } void Ditherbox::setParameter(VstInt32 index, float value) { switch (index) { case kParamA: A = value; break; default: throw; // unknown parameter, shouldn't happen! } } float Ditherbox::getParameter(VstInt32 index) { switch (index) { case kParamA: return A; break; default: break; // unknown parameter, shouldn't happen! } return 0.0; //we only need to update the relevant name, this is simple to manage } void Ditherbox::getParameterName(VstInt32 index, char *text) { switch (index) { case kParamA: vst_strncpy (text, "Type", kVstMaxParamStrLen); break; default: break; // unknown parameter, shouldn't happen! } //this is our labels for displaying in the VST host } void Ditherbox::getParameterDisplay(VstInt32 index, char *text) { switch (index) { case kParamA: switch((VstInt32)( A * 24.999 )) //0 to almost edge of # of params { case 0: vst_strncpy (text, "Trunc", kVstMaxParamStrLen); break; case 1: vst_strncpy (text, "Flat", kVstMaxParamStrLen); break; case 2: vst_strncpy (text, "TPDF", kVstMaxParamStrLen); break; case 3: vst_strncpy (text, "Paul", kVstMaxParamStrLen); break; case 4: vst_strncpy (text, "DbPaul", kVstMaxParamStrLen); break; case 5: vst_strncpy (text, "Tape", kVstMaxParamStrLen); break; case 6: vst_strncpy (text, "HiGloss", kVstMaxParamStrLen); break; case 7: vst_strncpy (text, "Vinyl", kVstMaxParamStrLen); break; case 8: vst_strncpy (text, "Spatial", kVstMaxParamStrLen); break; case 9: vst_strncpy (text, "Natural", kVstMaxParamStrLen); break; case 10: vst_strncpy (text, "NJAD", kVstMaxParamStrLen); break; case 11: vst_strncpy (text, "Trunc", kVstMaxParamStrLen); break; case 12: vst_strncpy (text, "Flat", kVstMaxParamStrLen); break; case 13: vst_strncpy (text, "TPDF", kVstMaxParamStrLen); break; case 14: vst_strncpy (text, "Paul", kVstMaxParamStrLen); break; case 15: vst_strncpy (text, "DbPaul", kVstMaxParamStrLen); break; case 16: vst_strncpy (text, "Tape", kVstMaxParamStrLen); break; case 17: vst_strncpy (text, "HiGloss", kVstMaxParamStrLen); break; case 18: vst_strncpy (text, "Vinyl", kVstMaxParamStrLen); break; case 19: vst_strncpy (text, "Spatial", kVstMaxParamStrLen); break; case 20: vst_strncpy (text, "Natural", kVstMaxParamStrLen); break; case 21: vst_strncpy (text, "NJAD", kVstMaxParamStrLen); break; case 22: vst_strncpy (text, "SlewOnl", kVstMaxParamStrLen); break; case 23: vst_strncpy (text, "SubsOnl", kVstMaxParamStrLen); break; case 24: vst_strncpy (text, "Silhoue", kVstMaxParamStrLen); break; default: break; // unknown parameter, shouldn't happen! } break; default: break; // unknown parameter, shouldn't happen! } //this displays the values and handles 'popups' where it's discrete choices } void Ditherbox::getParameterLabel(VstInt32 index, char *text) { switch (index) { case kParamA: switch((VstInt32)( A * 24.999 )) //0 to almost edge of # of params { case 0: vst_strncpy (text, "16", kVstMaxParamStrLen); break; case 1: vst_strncpy (text, "16", kVstMaxParamStrLen); break; case 2: vst_strncpy (text, "16", kVstMaxParamStrLen); break; case 3: vst_strncpy (text, "16", kVstMaxParamStrLen); break; case 4: vst_strncpy (text, "16", kVstMaxParamStrLen); break; case 5: vst_strncpy (text, "16", kVstMaxParamStrLen); break; case 6: vst_strncpy (text, "16", kVstMaxParamStrLen); break; case 7: vst_strncpy (text, "16", kVstMaxParamStrLen); break; case 8: vst_strncpy (text, "16", kVstMaxParamStrLen); break; case 9: vst_strncpy (text, "16", kVstMaxParamStrLen); break; case 10: vst_strncpy (text, "16", kVstMaxParamStrLen); break; case 11: vst_strncpy (text, "24", kVstMaxParamStrLen); break; case 12: vst_strncpy (text, "24", kVstMaxParamStrLen); break; case 13: vst_strncpy (text, "24", kVstMaxParamStrLen); break; case 14: vst_strncpy (text, "24", kVstMaxParamStrLen); break; case 15: vst_strncpy (text, "24", kVstMaxParamStrLen); break; case 16: vst_strncpy (text, "24", kVstMaxParamStrLen); break; case 17: vst_strncpy (text, "24", kVstMaxParamStrLen); break; case 18: vst_strncpy (text, "24", kVstMaxParamStrLen); break; case 19: vst_strncpy (text, "24", kVstMaxParamStrLen); break; case 20: vst_strncpy (text, "24", kVstMaxParamStrLen); break; case 21: vst_strncpy (text, "24", kVstMaxParamStrLen); break; case 22: vst_strncpy (text, "y", kVstMaxParamStrLen); break; case 23: vst_strncpy (text, "y", kVstMaxParamStrLen); break; case 24: vst_strncpy (text, "tte", kVstMaxParamStrLen); break; default: break; // unknown parameter, shouldn't happen! } break; default: break; // unknown parameter, shouldn't happen! } //this displays the values and handles 'popups' where it's discrete choices } VstInt32 Ditherbox::canDo(char *text) { return (_canDo.find(text) == _canDo.end()) ? -1: 1; } // 1 = yes, -1 = no, 0 = don't know bool Ditherbox::getEffectName(char* name) { vst_strncpy(name, "Ditherbox", kVstMaxProductStrLen); return true; } VstPlugCategory Ditherbox::getPlugCategory() {return kPlugCategEffect;} bool Ditherbox::getProductString(char* text) { vst_strncpy (text, "airwindows Ditherbox", kVstMaxProductStrLen); return true; } bool Ditherbox::getVendorString(char* text) { vst_strncpy (text, "airwindows", kVstMaxVendorStrLen); return true; }
33.273333
104
0.676418
PanieriLorenzo
0d3f6b8cfd3a4a6999441ceb0071d9275d3534b3
4,071
cpp
C++
ds2/lib_demonsaw/component/chat_idle_component.cpp
demonsaw/Code
b036d455e9e034d7fd178e63d5e992242d62989a
[ "MIT" ]
132
2017-03-22T03:46:38.000Z
2022-03-08T15:08:16.000Z
ds2/lib_demonsaw/component/chat_idle_component.cpp
demonsaw/Code
b036d455e9e034d7fd178e63d5e992242d62989a
[ "MIT" ]
4
2017-04-06T17:46:10.000Z
2018-08-08T18:27:59.000Z
ds2/lib_demonsaw/component/chat_idle_component.cpp
demonsaw/Code
b036d455e9e034d7fd178e63d5e992242d62989a
[ "MIT" ]
30
2017-03-26T22:38:17.000Z
2021-11-21T20:50:17.000Z
// // The MIT License(MIT) // // Copyright(c) 2014 Demonsaw LLC // // 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 "chat_idle_component.h" #include "client/client_option_component.h" #include "command/client/request/client_chat_request_command.h" #include "http/http_code.h" #include "router/router_component.h" namespace eja { // Interface void chat_idle_component::init() { idle_component::init(); start(); } void chat_idle_component::shutdown() { idle_component::shutdown(); close(); } // Utility void chat_idle_component::open() { try { close(); // Open const auto owner = get_entity(); if (!owner) { log("Invalid entity (chat)"); return; } const auto router = owner->get<router_component>(); if (!router) { log("Invalid router (chat)"); return; } const auto option = owner->get<client_option_component>(); if (!option) { log("Invalid option (chat)"); return; } // Socket //m_socket->set_keep_alive(true); m_socket->set_timeout(option->get_socket_timeout()); m_socket->open(router->get_address(), router->get_port()); } catch (std::exception& /*ex*/) { //log(ex); } catch (...) { //log("Unknown Error (chat)"); } } void chat_idle_component::close() { try { // Close m_socket->close(); } catch (std::exception& /*ex*/) { //log(ex); } catch (...) { //log("Unknown Error (chat)"); } } void chat_idle_component::add(const std::string& message, const entity::ptr entity /*= nullptr*/) { const auto data = std::shared_ptr<chat_data>(new chat_data { entity, message, (entity ? chat_type::client : chat_type::group) }); m_queue.add(data); } void chat_idle_component::add(const entity::ptr entity, const std::string& message, const chat_type type) { const auto data = std::shared_ptr<chat_data>(new chat_data { entity, message, type } ); m_queue.add(data); } bool chat_idle_component::on_run() { const auto owner = get_entity(); if (!owner) return idle_component::on_run(); const auto data = m_queue.pop(); if (!data) return idle_component::on_run(); try { // Socket if (m_socket->invalid()) open(); // Command const auto request_command = client_chat_request_command::create(owner, m_socket); const auto request_status = request_command->execute(data->entity, data->message, data->type); if (request_status.is_error()) { // Try again? if (request_status.is_none()) m_queue.push_front(data); //log(request_status); open(); } } catch (std::exception& /*ex*/) { //log(e); m_queue.push_front(data); open(); } catch (...) { //log("Unknown Error (chat)"); m_queue.push_front(data); open(); } // Delay const auto delay = m_queue.empty() ? default_timeout::client::chat : default_timeout::error; set_delay(delay); return idle_component::on_run(); } bool chat_idle_component::on_stop() { close(); return idle_component::on_stop(); } }
23
131
0.669369
demonsaw
0d44f4292eb3dbad76d97d0ceb887f16194a6eb9
1,533
cpp
C++
test/bench/cpp/rbtree-ck.cpp
lovebaihezi/koka
b1670308f88dd1fc6c22cad28385fcb185d5b27d
[ "Apache-2.0" ]
2,057
2016-12-21T18:14:47.000Z
2022-03-30T13:51:43.000Z
test/bench/cpp/rbtree-ck.cpp
lovebaihezi/koka
b1670308f88dd1fc6c22cad28385fcb185d5b27d
[ "Apache-2.0" ]
207
2017-01-15T03:17:34.000Z
2022-03-23T06:39:40.000Z
test/bench/cpp/rbtree-ck.cpp
lovebaihezi/koka
b1670308f88dd1fc6c22cad28385fcb185d5b27d
[ "Apache-2.0" ]
116
2017-01-25T19:17:49.000Z
2022-03-11T01:25:57.000Z
// Try persisting std:map through copying; is too slow... // We should try to make a persistent RB tree in C++ but this is not trivial to do... #include <iostream> #include <map> #include <list> #include <algorithm> #include <memory> // #include "util/nat.h" // #include "util/list.h" // using namespace lean; using std::for_each; using std::list; typedef int nat; struct nat_lt_fn { bool operator()(nat const & n1, nat const & n2) const { return n1 < n2; } }; typedef std::map<nat, bool, nat_lt_fn> map_t; typedef std::shared_ptr<map_t> map; list<map>& cons(map m, list<map>& stack) { stack.push_front(m); return stack; } map head(list<map>& stack) { return stack.front(); } list<map> mk_map(unsigned n, unsigned freq) { list<map> stack; auto m = std::make_shared<map_t>(); while (n > 0) { --n; m->insert(std::make_pair(nat(n), n%10 == 0)); if (n % freq == 0) { stack = cons(std::make_shared<map_t>(*m) /* copy constructor */, stack); } } stack = cons(m, stack); return stack; } nat fold(map const & m) { nat r(0); for_each(m->begin(), m->end(), [&](std::pair<nat, bool> const & p) { if (p.second) r = r + nat(1); }); return r; } int main(int argc, char ** argv) { unsigned n = 4200; // 4200000; unsigned freq = 5; if (argc == 3) { n = atoi(argv[1]); freq = atoi(argv[2]); } list<map> m = mk_map(n, freq); std::cout << fold(head(m)) << "\n"; return 1; // signal that this test is not working }
24.333333
106
0.585127
lovebaihezi
0d4c744a76f95c97a248ba7f551d359e7406e9c4
4,225
hpp
C++
include/exec.hpp
geraldc-unm/Comb
790d054f9722e6752a27a1c2e08c135f9d5b8e75
[ "MIT" ]
21
2018-10-03T18:15:04.000Z
2022-02-16T08:07:50.000Z
include/exec.hpp
geraldc-unm/Comb
790d054f9722e6752a27a1c2e08c135f9d5b8e75
[ "MIT" ]
5
2019-10-07T23:06:57.000Z
2021-08-16T16:10:58.000Z
include/exec.hpp
geraldc-unm/Comb
790d054f9722e6752a27a1c2e08c135f9d5b8e75
[ "MIT" ]
6
2019-09-13T16:47:33.000Z
2022-03-03T16:17:32.000Z
////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2018-2021, Lawrence Livermore National Security, LLC. // // Produced at the Lawrence Livermore National Laboratory // // LLNL-CODE-758885 // // All rights reserved. // // This file is part of Comb. // // For details, see https://github.com/LLNL/Comb // Please also see the LICENSE file for MIT license. ////////////////////////////////////////////////////////////////////////////// #ifndef _EXEC_HPP #define _EXEC_HPP #include "config.hpp" #include <cstdio> #include <cstdlib> #include <cassert> #include <type_traits> #include "exec_utils.hpp" #include "memory.hpp" #include "ExecContext.hpp" #include "exec_fused.hpp" #include "exec_pol_seq.hpp" #include "exec_pol_omp.hpp" #include "exec_pol_cuda.hpp" #include "exec_pol_cuda_graph.hpp" #include "exec_pol_mpi_type.hpp" #include "exec_pol_raja.hpp" namespace COMB { template < typename my_context_type > struct ContextHolder { using context_type = my_context_type; bool m_available = false; bool available() const { return m_available; } template < typename ... Ts > void create(Ts&&... args) { destroy(); m_context = new context_type(std::forward<Ts>(args)...); } context_type& get() { assert(m_context != nullptr); return *m_context; } void destroy() { if (m_context) { delete m_context; m_context = nullptr; } } ~ContextHolder() { destroy(); } private: context_type* m_context = nullptr; }; struct Executors { Executors() { } Executors(Executors const&) = delete; Executors(Executors &&) = delete; Executors& operator=(Executors const&) = delete; Executors& operator=(Executors &&) = delete; void create_executors(Allocators& alocs) { base_cpu.create(); #ifdef COMB_ENABLE_MPI base_mpi.create(); #endif #ifdef COMB_ENABLE_CUDA base_cuda.create(); #endif #ifdef COMB_ENABLE_RAJA base_raja_cpu.create(); #ifdef COMB_ENABLE_CUDA base_raja_cuda.create(); #endif #endif seq.create(base_cpu.get(), alocs.host.allocator()); #ifdef COMB_ENABLE_OPENMP omp.create(base_cpu.get(), alocs.host.allocator()); #endif #ifdef COMB_ENABLE_CUDA cuda.create(base_cuda.get(), (alocs.access.use_device_preferred_for_cuda_util_aloc) ? alocs.cuda_managed_device_preferred_host_accessed.allocator() : alocs.cuda_hostpinned.allocator()); #endif #ifdef COMB_ENABLE_CUDA_GRAPH cuda_graph.create(base_cuda.get(), (alocs.access.use_device_preferred_for_cuda_util_aloc) ? alocs.cuda_managed_device_preferred_host_accessed.allocator() : alocs.cuda_hostpinned.allocator()); #endif #ifdef COMB_ENABLE_MPI mpi_type.create(base_mpi.get(), alocs.host.allocator()); #endif #ifdef COMB_ENABLE_RAJA raja_seq.create(base_raja_cpu.get(), alocs.host.allocator()); #ifdef COMB_ENABLE_OPENMP raja_omp.create(base_raja_cpu.get(), alocs.host.allocator()); #endif #ifdef COMB_ENABLE_CUDA raja_cuda.create(base_raja_cuda.get(), (alocs.access.use_device_preferred_for_cuda_util_aloc) ? alocs.cuda_managed_device_preferred_host_accessed.allocator() : alocs.cuda_hostpinned.allocator()); #endif #endif } ContextHolder<CPUContext> base_cpu; #ifdef COMB_ENABLE_MPI ContextHolder<MPIContext> base_mpi; #endif #ifdef COMB_ENABLE_CUDA ContextHolder<CudaContext> base_cuda; #endif #ifdef COMB_ENABLE_RAJA ContextHolder<RAJAContext<RAJA::resources::Host>> base_raja_cpu; #ifdef COMB_ENABLE_CUDA ContextHolder<RAJAContext<RAJA::resources::Cuda>> base_raja_cuda; #endif #endif ContextHolder<ExecContext<seq_pol>> seq; #ifdef COMB_ENABLE_OPENMP ContextHolder<ExecContext<omp_pol>> omp; #endif #ifdef COMB_ENABLE_CUDA ContextHolder<ExecContext<cuda_pol>> cuda; #ifdef COMB_ENABLE_CUDA_GRAPH ContextHolder<ExecContext<cuda_graph_pol>> cuda_graph; #endif #endif #ifdef COMB_ENABLE_MPI ContextHolder<ExecContext<mpi_type_pol>> mpi_type; #endif #ifdef COMB_ENABLE_RAJA ContextHolder<ExecContext<raja_seq_pol>> raja_seq; #ifdef COMB_ENABLE_OPENMP ContextHolder<ExecContext<raja_omp_pol>> raja_omp; #endif #ifdef COMB_ENABLE_CUDA ContextHolder<ExecContext<raja_cuda_pol>> raja_cuda; #endif #endif }; } // namespace COMB #endif // _EXEC_HPP
24.142857
199
0.725207
geraldc-unm
0d505c9bb221def9f896b1ac514935a8c9feb8ae
403
cpp
C++
Treads!/ScoreRecord.cpp
JoeKooler/Treads
5412d4a94a7b331aa37d04ff85e6f9e53da1150b
[ "MIT" ]
null
null
null
Treads!/ScoreRecord.cpp
JoeKooler/Treads
5412d4a94a7b331aa37d04ff85e6f9e53da1150b
[ "MIT" ]
null
null
null
Treads!/ScoreRecord.cpp
JoeKooler/Treads
5412d4a94a7b331aa37d04ff85e6f9e53da1150b
[ "MIT" ]
null
null
null
#include "ScoreRecord.hpp" using namespace std; ScoreRecord::ScoreRecord(std::string nameStr, int scoreVal, float timeVal) : name(nameStr), score(scoreVal), time(timeVal) { } void ScoreRecord::write(std::ostream & strm) const { strm << name << " "; strm << score << " "; strm << time << endl; } void ScoreRecord::read(std::istream & strm) { strm >> name >> score >> time; }
19.190476
123
0.62531
JoeKooler
0d55e3d06c3d011f9c37c453b15ebbd14e0e909e
126
cpp
C++
contrib/UnitTest++/src/tests/Main.cpp
Alexander-Ignatyev/optimer
fc0fb8ffd35e6326f60d77c144cfe7635a6edaa7
[ "BSD-3-Clause" ]
null
null
null
contrib/UnitTest++/src/tests/Main.cpp
Alexander-Ignatyev/optimer
fc0fb8ffd35e6326f60d77c144cfe7635a6edaa7
[ "BSD-3-Clause" ]
null
null
null
contrib/UnitTest++/src/tests/Main.cpp
Alexander-Ignatyev/optimer
fc0fb8ffd35e6326f60d77c144cfe7635a6edaa7
[ "BSD-3-Clause" ]
null
null
null
#include "../TestRunnerTeamCity.h" int main(int, char const *[]) { return UnitTest::RunAllTestsWithTeamCity(); }
15.75
48
0.650794
Alexander-Ignatyev
0d562cab15d064ea2ea82648da228fecb4314811
6,517
cpp
C++
src/PhantomEngine/PhantomUITextBox.cpp
DexianZhao/PhantomEngineV2
cc3bf02ca1d442713d471ca8835ca026bb32e841
[ "MIT" ]
1
2021-10-30T07:38:25.000Z
2021-10-30T07:38:25.000Z
src/PhantomEngine/PhantomUITextBox.cpp
DexianZhao/PhantomEngineV2
cc3bf02ca1d442713d471ca8835ca026bb32e841
[ "MIT" ]
null
null
null
src/PhantomEngine/PhantomUITextBox.cpp
DexianZhao/PhantomEngineV2
cc3bf02ca1d442713d471ca8835ca026bb32e841
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////////////////////////////////// /* 幻影游戏引擎, 2009-2016, Phantom Game Engine, http://www.aixspace.com Design Writer : 赵德贤 Dexian Zhao Email: [email protected] */ ////////////////////////////////////////////////////////////////////////////////////////////////////// #include "PhantomUITextBox.h" #include "PhantomManager.h" #include "PhantomUIDialog.h" extern "C"{ void openEdit(const char* szDefault, int x, int y, int w, int h, int id); int closeEdit(char* ret, int buflen); }; namespace Phantom{ UITextBox::UITextBox( BOOL bInit, UIDialog *dialogPtr ) : UIControl(bInit, dialogPtr) { m_controlType = UIControlType_EDITBOX; m_dialogPtr = dialogPtr; m_bLButtonDown = false; // m_bPassword = false; if(bInit) { m_bgElement.SetSourceRect(Rect(83, 0, 83 + 30, 30)); m_bgElement.SetRenderScale(false, false, Pixel(5, 5)); // m_bgElement.m_name = ("背景"); } // ClearElement(); AddElement(&m_bgElement); // m_borderWidth = 0; } char UITextBox::onMouseMessage( unsigned int uMsg, Pixel pt, unsigned int touchIndex ) {CPUTime(UITextBox); if( !m_bVisible || this->m_bIsBackground ) return false; if(!this->IsEnabledCtrl() && this->canHaveFocus()) { switch(uMsg) { case InputEventID_ButtonDown: case InputEventID_ButtonDblClk: case InputEventID_MouseMove: return isPtIn( pt ); default: return false; } } switch(uMsg) { case InputEventID_MouseMove: { char bMouseMove = isPtIn(pt); if(bMouseMove) { if(!m_bMouseEnter) this->onMouseEnter(); } } break; case InputEventID_ButtonDown: { if(isPtIn(pt) && canHaveFocus()) { m_bLButtonDown = (touchIndex + 1); for(int i=0;i<m_drawMgrs.size();i++) if(m_drawMgrs[i]->OnDownClick(pt, EventID_Click)) break; return true; } //if(m_bLButtonDown && isPtIn(pt)) //OnButtonClick(EventID_Click); //m_bLButtonDown = false; } break; case InputEventID_ButtonUp: { for(int i=0;i<m_drawMgrs.size();i++) m_drawMgrs[i]->OnUpClick(pt, EventID_Click); if(m_bLButtonDown == (touchIndex + 1) && isPtIn(pt) && !this->m_bReadOnly) { OnButtonClick(pt, EventID_Click); m_bLButtonDown = false; int x=0,y=0; this->m_dialogPtr->GetLocation(x,y); openEdit(this->m_text.str(), m_windowRect.left+x,m_windowRect.top+y, m_windowRect.GetWidth(), m_windowRect.GetHeight(), this->GetID()); return true; } } break; case InputEventID_ButtonDblClk: { if(isPtIn(pt) && canHaveFocus()) m_bLButtonDown = true; if(m_bLButtonDown && isPtIn(pt)) { OnButtonClick(pt, EventID_DoubleClick); return true; } m_bLButtonDown = false; } break; } return UIControl::onMouseMessage( uMsg, pt, touchIndex ); } VOID UITextBox::OnEditClose(BOOL bIsCancel, const char* text) { if(!bIsCancel) this->SetText(text); } void UITextBox::Render( float fElapsedTime ) {CPUTime(UITextBox); if( m_bVisible == false ) return; //if(this->m_bMouseEnter && m_bMouseEnterEffect) //{ // g_manager->SetBlendMode((BlendMode)m_mouseEnterSrc,(BlendMode)m_mouseEnterDesc); //} //else //{ g_manager->SetBlendMode((BlendMode)m_bgElement.m_nSrcBlend,(BlendMode)m_bgElement.m_nDestBlend); //} if(m_bgElement.GetTextureNewID() >= 0) { //if(m_bMouseEnter && m_bMouseEnterEffect) //m_dialogPtr->DrawElement(GetEnabled(), GetDisableColor(), &m_bgElement, &m_bgElement.rcTexture, &m_currentAnim.rc, this->m_mouseEnterColor * m_currentAnim.textureColor, true, &m_currentAnim); //else if(!this->m_bEnableUseImageText) m_dialogPtr->DrawElement(GetEnabled(), &m_bgElement, &m_bgElement.rcTexture, &m_currentAnim.rc, m_bgElement.textureColor * m_currentAnim.textureColor, &m_currentAnim, this); } Rect rc = m_currentAnim.rc; Pixel center(m_rotCenter.x + rc.left, m_rotCenter.y + rc.top); rc.left = (int)((float)(rc.left - center.x) * m_scale.x) + center.x; rc.right = (int)((float)(rc.right - center.x) * m_scale.x) + center.x; rc.top = (int)((float)(rc.top - center.y) * m_scale.y) + center.y; rc.bottom = (int)((float)(rc.bottom - center.y) * m_scale.y) + center.y; if(m_text.size() > 0) { m_bgElement.dwTextFormat = m_textFormat; //Rect rc = m_currentAnim.rc; //rc.inflate(-m_borderWidth, -m_borderWidth); if(m_bEnableUseImageText) RenderImgText(m_bgElement); } if(m_textPtr&&!m_bEnableUseImageText) { m_dialogPtr->DrawElement(m_textPtr, GetEnabled(), &m_bgElement, 0, &rc, m_textColor * m_currentAnim.textColor, &m_currentAnim, this, 0); } if(m_text.size() > 0) { //m_bgElement.dwTextFormat = m_textFormat; //Rect rc = m_currentAnim.rc; //rc.inflate(-m_borderWidth, -m_borderWidth); //if(m_bEnableUseImageText) // RenderImgText(m_bgElement); //else // m_dialogPtr->DrawElementText(GetEnabled(), m_currentAnim.rc, m_text.str(), &m_bgElement, &rc, m_textColor * m_currentAnim.textColor, m_nShadowWidth, m_shadowColor, true, &m_currentAnim); } this->RenderDrawMgrs(); } char UITextBox::LoadControl(CSafeFileHelperR& r) {CPUTime(UITextBox); UIControl::LoadControl( r ); skip_r sr; if(m_loadVersion>=0x000000A4) sr.begin(r.pStream); r >> m_borderWidth >> m_nSpacing >> m_rcText >> m_dfBlink >> m_dfLastBlink >> m_bCaretOn >> m_nCaret >> m_bInsertMode >> m_nSelStart >> m_nFirstVisible >> m_TextColor >> m_SelTextColor >> m_SelBkColor >> m_CaretColor >> m_bRenderBorder >> m_bPassword; r.pStream->read(m_rcRender, sizeof(m_rcRender)); if(this->m_loadVersion >= 0x00000066) { if(this->m_loadVersion<0x000000A2){ TypeArray<short_t> text; r >> text; } else { std::string str; r >> str; SetText(str.c_str()); } //SetText(text.c_str()); } if(m_loadVersion >= 0x00000068) { int sb = 0; r >> sb; m_scrollBarWidth = sb; } sr.end(); return true; } char UITextBox::SaveControl(CSafeFileHelperW& w) {CPUTime(UITextBox); UIControl::SaveControl( w ); skip_w sw(w.pStream); w << m_borderWidth << m_nSpacing << m_rcText << m_dfBlink << m_dfLastBlink << m_bCaretOn << m_nCaret << m_bInsertMode << m_nSelStart << m_nFirstVisible << m_TextColor << m_SelTextColor << m_SelBkColor << m_CaretColor << m_bRenderBorder << m_bPassword; w.pStream->write(m_rcRender, sizeof(m_rcRender)); w << m_text.str(); int sb = m_scrollBarWidth; w << sb; sw.end(); return true; } };
29.622727
197
0.651834
DexianZhao
0d579fffbca8a36f51ddfe773a5f0d234528cc0a
372
cpp
C++
IT-OOPs-A2/IT_OOP_L2Q2.cpp
umgbhalla/OOPsAssign
34cee8907fea4ee659b1e0cf146a2b1b09a96c3b
[ "MIT" ]
5
2021-09-03T18:33:40.000Z
2021-09-13T11:51:38.000Z
IT-OOPs-A2/IT_OOP_L2Q2.cpp
umgbhalla/OOPsAssign
34cee8907fea4ee659b1e0cf146a2b1b09a96c3b
[ "MIT" ]
1
2021-07-28T05:36:15.000Z
2021-07-28T05:36:15.000Z
IT-OOPs-A2/IT_OOP_L2Q2.cpp
umgbhalla/OOPsAssign
34cee8907fea4ee659b1e0cf146a2b1b09a96c3b
[ "MIT" ]
4
2021-07-28T05:26:52.000Z
2021-07-28T16:19:03.000Z
#include <iostream> using namespace std; int reversDigits(int n) { int rev_n = 0; while (n > 0) { rev_n = rev_n * 10 + n % 10; n = n / 10; } return rev_n; } int main() { int n = 0; cout << "Enter Integer value :: "; cin >> n; cout << "\nReverse of Integer value is :: " << reversDigits(n) << endl; return 0; }
14.88
75
0.5
umgbhalla
0d594964b80acaba29852914d098dd286b38795b
80
cpp
C++
Firefly/vendor/stb/stb_sprintf.cpp
Latias94/Firefly
ad6671df0b16ed9481b013936ba06ffc3be80e60
[ "Apache-2.0" ]
null
null
null
Firefly/vendor/stb/stb_sprintf.cpp
Latias94/Firefly
ad6671df0b16ed9481b013936ba06ffc3be80e60
[ "Apache-2.0" ]
null
null
null
Firefly/vendor/stb/stb_sprintf.cpp
Latias94/Firefly
ad6671df0b16ed9481b013936ba06ffc3be80e60
[ "Apache-2.0" ]
null
null
null
#include "ffpch.h" #define STB_SPRINTF_IMPLEMENTATION #include "stb_sprintf.h"
16
34
0.8
Latias94
0d5e451ba86c4fc06c9ee90cf820a4e0e7910b2e
41,787
cpp
C++
src/network/postgres_protocol_handler.cpp
phisiart/peloton
c2becb9d6f2e2c8f48696a371b0d7c0ff79d56fc
[ "Apache-2.0" ]
1
2017-04-17T15:19:36.000Z
2017-04-17T15:19:36.000Z
src/network/postgres_protocol_handler.cpp
phisiart/peloton
c2becb9d6f2e2c8f48696a371b0d7c0ff79d56fc
[ "Apache-2.0" ]
5
2017-04-23T17:16:14.000Z
2017-04-25T03:14:16.000Z
src/network/postgres_protocol_handler.cpp
phisiart/peloton-p3
c2becb9d6f2e2c8f48696a371b0d7c0ff79d56fc
[ "Apache-2.0" ]
null
null
null
//===----------------------------------------------------------------------===// // // Peloton // // postgres_protocol_handler.cpp // // Identification: src/network/postgres_protocol_handler.cpp // // Copyright (c) 2015-17, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "network/postgres_protocol_handler.h" #include <boost/algorithm/string.hpp> #include <cstdio> #include <unordered_map> #include "common/cache.h" #include "common/macros.h" #include "common/portal.h" #include "planner/abstract_plan.h" #include "planner/delete_plan.h" #include "planner/insert_plan.h" #include "planner/update_plan.h" #include "include/traffic_cop/traffic_cop.h" #include "type/types.h" #include "type/value.h" #include "type/value_factory.h" #include "network/marshal.h" #include "settings/settings_manager.h" namespace peloton { namespace network { // TODO: Remove hardcoded auth strings // Hardcoded authentication strings used during session startup. To be removed const std::unordered_map<std::string, std::string> // clang-format off PostgresProtocolHandler::parameter_status_map_ = boost::assign::map_list_of("application_name", "psql") ("client_encoding", "UTF8") ("DateStyle", "ISO, MDY") ("integer_datetimes", "on") ("IntervalStyle", "postgres") ("is_superuser", "on") ("server_encoding", "UTF8") ("server_version", "9.5devel") ("session_authorization", "postgres") ("standard_conforming_strings", "on") ("TimeZone", "US/Eastern"); // clang-format on PostgresProtocolHandler::PostgresProtocolHandler(tcop::TrafficCop *traffic_cop) : ProtocolHandler(traffic_cop), txn_state_(NetworkTransactionStateType::IDLE) { } PostgresProtocolHandler::~PostgresProtocolHandler() {} // TODO: This function is used when txn cache is done void PostgresProtocolHandler::ReplanPreparedStatement(Statement *statement) { std::string error_message; auto new_statement = traffic_cop_->PrepareStatement( statement->GetStatementName(), statement->GetQueryString(), error_message); // But then rip out its query plan and stick it in our old statement if (new_statement.get() == nullptr) { LOG_ERROR( "Failed to generate a new query plan for PreparedStatement '%s'\n%s", statement->GetStatementName().c_str(), error_message.c_str()); } else { LOG_DEBUG("Generating new plan for PreparedStatement '%s'", statement->GetStatementName().c_str()); auto old_plan = statement->GetPlanTree(); auto new_plan = new_statement->GetPlanTree(); statement->SetPlanTree(new_plan); new_statement->SetPlanTree(old_plan); statement->SetNeedsPlan(false); // TODO: We may need to delete the old plan and new statement here } } void PostgresProtocolHandler::SendInitialResponse() { std::unique_ptr<OutputPacket> response(new OutputPacket()); // send auth-ok ('R') response->msg_type = NetworkMessageType::AUTHENTICATION_REQUEST; PacketPutInt(response.get(), 0, 4); responses.push_back(std::move(response)); // Send the parameterStatus map ('S') for (auto it = parameter_status_map_.begin(); it != parameter_status_map_.end(); it++) { MakeHardcodedParameterStatus(*it); } // ready-for-query packet -> 'Z' SendReadyForQuery(NetworkTransactionStateType::IDLE); // we need to send the response right away SetFlushFlag(true); } void PostgresProtocolHandler::MakeHardcodedParameterStatus( const std::pair<std::string, std::string> &kv) { std::unique_ptr<OutputPacket> response(new OutputPacket()); response->msg_type = NetworkMessageType::PARAMETER_STATUS; PacketPutString(response.get(), kv.first); PacketPutString(response.get(), kv.second); responses.push_back(std::move(response)); } void PostgresProtocolHandler::PutTupleDescriptor( const std::vector<FieldInfo> &tuple_descriptor) { if (tuple_descriptor.empty()) return; std::unique_ptr<OutputPacket> pkt(new OutputPacket()); pkt->msg_type = NetworkMessageType::ROW_DESCRIPTION; PacketPutInt(pkt.get(), tuple_descriptor.size(), 2); for (auto col : tuple_descriptor) { PacketPutString(pkt.get(), std::get<0>(col)); // TODO: Table Oid (int32) PacketPutInt(pkt.get(), 0, 4); // TODO: Attr id of column (int16) PacketPutInt(pkt.get(), 0, 2); // Field data type (int32) PacketPutInt(pkt.get(), std::get<1>(col), 4); // Data type size (int16) PacketPutInt(pkt.get(), std::get<2>(col), 2); // Type modifier (int32) PacketPutInt(pkt.get(), -1, 4); // Format code for text PacketPutInt(pkt.get(), 0, 2); } responses.push_back(std::move(pkt)); } void PostgresProtocolHandler::SendDataRows(std::vector<StatementResult> &results, int colcount, int &rows_affected) { if (results.empty() || colcount == 0) return; size_t numrows = results.size() / colcount; // 1 packet per row for (size_t i = 0; i < numrows; i++) { std::unique_ptr<OutputPacket> pkt(new OutputPacket()); pkt->msg_type = NetworkMessageType::DATA_ROW; PacketPutInt(pkt.get(), colcount, 2); for (int j = 0; j < colcount; j++) { auto content = results[i * colcount + j].second; if (content.size() == 0) { // content is NULL PacketPutInt(pkt.get(), NULL_CONTENT_SIZE, 4); // no value bytes follow } else { // length of the row attribute PacketPutInt(pkt.get(), content.size(), 4); // contents of the row attribute PacketPutBytes(pkt.get(), content); } } responses.push_back(std::move(pkt)); } rows_affected = numrows; } void PostgresProtocolHandler::CompleteCommand(const std::string &query, const QueryType& query_type, int rows) { std::unique_ptr<OutputPacket> pkt(new OutputPacket()); pkt->msg_type = NetworkMessageType::COMMAND_COMPLETE; std::string query_type_string; Statement::ParseQueryTypeString(query, query_type_string); std::string tag = query_type_string ; switch (query_type) { /* After Begin, we enter a txn block */ case QueryType::QUERY_BEGIN: txn_state_ = NetworkTransactionStateType::BLOCK; break; /* After commit, we end the txn block */ case QueryType::QUERY_COMMIT: /* After rollback, the txn block is ended */ case QueryType::QUERY_ROLLBACK: txn_state_ = NetworkTransactionStateType::IDLE; break; case QueryType::QUERY_INSERT: tag += " 0 " + std::to_string(rows); break; case QueryType::QUERY_CREATE: { std::string create_type_string; Statement::ParseCreateTypeString(query, create_type_string); tag += " " + create_type_string; break; } case QueryType::QUERY_PREPARE: break; default: tag += " " + std::to_string(rows); } PacketPutString(pkt.get(), tag); responses.push_back(std::move(pkt)); } /* * put_empty_query_response - Informs the client that an empty query was sent */ void PostgresProtocolHandler::SendEmptyQueryResponse() { std::unique_ptr<OutputPacket> response(new OutputPacket()); response->msg_type = NetworkMessageType::EMPTY_QUERY_RESPONSE; responses.push_back(std::move(response)); } bool PostgresProtocolHandler::HardcodedExecuteFilter(QueryType query_type) { switch (query_type) { // Skip SET case QueryType::QUERY_SET: case QueryType::QUERY_SHOW: return false; // Skip duplicate BEGIN case QueryType::QUERY_BEGIN: if (txn_state_ == NetworkTransactionStateType::BLOCK) { return false; } break; // Skip duuplicate Commits and Rollbacks case QueryType::QUERY_COMMIT: case QueryType::QUERY_ROLLBACK: if (txn_state_ == NetworkTransactionStateType::IDLE) { return false; } default: break; } return true; } // The Simple Query Protocol // Fix mis-split bug: Previously, this function assumes there are multiple // queries in the string and split it by ';', which would cause one containing // ';' being split into multiple queries. // However, the multi-statement queries has been split by the psql client and // there is no need to split the query again. ProcessResult PostgresProtocolHandler::ExecQueryMessage(InputPacket *pkt, const size_t thread_id) { std::string query; PacketGetString(pkt, pkt->len, query); // pop out the last character if it is ';' if (query.back() == ';') { query.pop_back(); } boost::trim(query); protocol_type_ = NetworkProtocolType::POSTGRES_PSQL; if (!query.empty()) { std::vector<StatementResult> result; std::vector<FieldInfo> tuple_descriptor; std::string error_message; int rows_affected = 0; std::string query_type_string_; Statement::ParseQueryTypeString(query, query_type_string_); QueryType query_type; Statement::MapToQueryType(query_type_string_, query_type); query_ = query; query_type_ = query_type; switch (query_type) { case QueryType::QUERY_PREPARE: { std::string statement_name; std::vector<std::string> tokens; boost::split(tokens, query_, boost::is_any_of("(), ")); statement_name = tokens.at(1); std::size_t pos = boost::to_upper_copy(query_).find("AS"); std::string statement_query = query_.substr(pos + 3); boost::trim(statement_query); // Prepare statement std::shared_ptr<Statement> statement(nullptr); LOG_DEBUG("PrepareStatement[%s] => %s", statement_name.c_str(), statement_query.c_str()); statement = traffic_cop_->PrepareStatement(statement_name, statement_query, error_message); if (statement.get() == nullptr) { skipped_stmt_ = true; SendErrorResponse( {{NetworkMessageType::HUMAN_READABLE_ERROR, error_message}}); LOG_TRACE("ExecQuery Error"); SendReadyForQuery(NetworkTransactionStateType::IDLE); return ProcessResult::COMPLETE; } auto entry = std::make_pair(statement_name, statement); statement_cache_.insert(entry); for (auto table_id : statement->GetReferencedTables()) { table_statement_cache_[table_id].push_back(statement.get()); } break; } case QueryType::QUERY_EXECUTE: { std::string statement_name; std::vector<type::Value> param_values; bool unnamed = false; std::vector<std::string> tokens; boost::split(tokens, query, boost::is_any_of("(), ")); statement_name = tokens.at(1); auto statement_cache_itr = statement_cache_.find(statement_name); if (statement_cache_itr != statement_cache_.end()) { statement_ = *statement_cache_itr; } // Did not find statement with same name else { error_message_ = "The prepared statement does not exist"; LOG_ERROR("%s", error_message_.c_str()); SendErrorResponse( {{NetworkMessageType::HUMAN_READABLE_ERROR, error_message_}}); SendReadyForQuery(NetworkTransactionStateType::IDLE); return ProcessResult::COMPLETE; } query_type_ = statement_->GetQueryType(); query_ = statement_->GetQueryString(); std::vector<int> result_format(statement_->GetTupleDescriptor().size(), 0); result_format_ = result_format; for (std::size_t idx = 2; idx < tokens.size(); idx++) { std::string param_str = tokens.at(idx); boost::trim(param_str); if (param_str.empty()) { continue; } param_values.push_back(type::ValueFactory::GetVarcharValue(param_str)); } if (param_values.size() > 0) { statement_->GetPlanTree()->SetParameterValues(&param_values); } param_values_ = param_values; auto status = traffic_cop_->ExecuteStatement(statement_, param_values_, unnamed, nullptr, result_format_, results_, rows_affected_, error_message_, thread_id); if (traffic_cop_->is_queuing_) { return ProcessResult::PROCESSING; } ExecQueryMessageGetResult(status); return ProcessResult::COMPLETE; } default: { // prepareStatement std::string unnamed_statement = "unnamed"; statement_ = traffic_cop_->PrepareStatement(unnamed_statement, query_, error_message); if (statement_.get() == nullptr) { rows_affected = 0; SendErrorResponse( {{NetworkMessageType::HUMAN_READABLE_ERROR, error_message}}); SendReadyForQuery(NetworkTransactionStateType::IDLE); return ProcessResult::COMPLETE; } // ExecuteStatment std::vector<type::Value> param_values; param_values_ = param_values; bool unnamed = false; std::vector<int> result_format(statement_->GetTupleDescriptor().size(), 0); result_format_ = result_format; // should param_values and result_format be local variable? // should results_ be reset when PakcetManager.reset(), why results_ cannot be read? auto status = traffic_cop_->ExecuteStatement(statement_, param_values_, unnamed, nullptr, result_format_, results_, rows_affected_, error_message_, thread_id); if (traffic_cop_->is_queuing_) { return ProcessResult::PROCESSING; } ExecQueryMessageGetResult(status); return ProcessResult::COMPLETE; } } // send the attribute names PutTupleDescriptor(tuple_descriptor); // send the result rows SendDataRows(result, tuple_descriptor.size(), rows_affected); // The response to the SimpleQueryCommand is the query string. CompleteCommand(query_, query_type_, rows_affected); } else { SendEmptyQueryResponse(); } // PAVLO: 2017-01-15 // There used to be code here that would invoke this method passing // in NetworkMessageType::READY_FOR_QUERY as the argument. But when // I switched to strong types, this obviously doesn't work. So I // switched it to be NetworkTransactionStateType::IDLE. I don't know // we just don't always send back the internal txn state? SendReadyForQuery(NetworkTransactionStateType::IDLE); return ProcessResult::COMPLETE; } void PostgresProtocolHandler::ExecQueryMessageGetResult(ResultType status) { std::vector<FieldInfo> tuple_descriptor; if (status == ResultType::SUCCESS) { tuple_descriptor = statement_->GetTupleDescriptor(); } else if (status == ResultType::FAILURE) { // check status SendErrorResponse( {{NetworkMessageType::HUMAN_READABLE_ERROR, error_message_}}); SendReadyForQuery(NetworkTransactionStateType::IDLE); return; } // send the attribute names PutTupleDescriptor(tuple_descriptor); // send the result rows SendDataRows(results_, tuple_descriptor.size(), rows_affected_); // The response to the SimpleQueryCommand is the query string. CompleteCommand(query_, query_type_, rows_affected_); SendReadyForQuery(NetworkTransactionStateType::IDLE); } /* * exec_parse_message - handle PARSE message */ void PostgresProtocolHandler::ExecParseMessage(InputPacket *pkt) { std::string error_message, statement_name, query_string, query_type_string; GetStringToken(pkt, statement_name); QueryType query_type; // Read prepare statement name // Read query string GetStringToken(pkt, query_string); skipped_stmt_ = false; Statement::ParseQueryTypeString(query_string, query_type_string); Statement::MapToQueryType(query_type_string, query_type); // For an empty query or a query to be filtered, just send parse complete // response and don't execute if (query_string == "" || HardcodedExecuteFilter(query_type) == false) { skipped_stmt_ = true; skipped_query_string_ = std::move(query_string); skipped_query_type_ = std::move(query_type); // Send Parse complete response std::unique_ptr<OutputPacket> response(new OutputPacket()); response->msg_type = NetworkMessageType::PARSE_COMPLETE; responses.push_back(std::move(response)); return; } // Prepare statement std::shared_ptr<Statement> statement(nullptr); LOG_DEBUG("PrepareStatement[%s] => %s", statement_name.c_str(), query_string.c_str()); statement = traffic_cop_->PrepareStatement(statement_name, query_string, error_message); if (statement.get() == nullptr) { skipped_stmt_ = true; SendErrorResponse( {{NetworkMessageType::HUMAN_READABLE_ERROR, error_message}}); LOG_TRACE("ExecParse Error"); return; } // Read number of params int num_params = PacketGetInt(pkt, 2); // Read param types std::vector<int32_t> param_types(num_params); auto type_buf_begin = pkt->Begin() + pkt->ptr; auto type_buf_len = ReadParamType(pkt, num_params, param_types); // Cache the received query bool unnamed_query = statement_name.empty(); statement->SetParamTypes(param_types); // Stat if (settings::SettingsManager::GetInt(settings::SettingId::stats_mode) != STATS_TYPE_INVALID) { // Make a copy of param types for stat collection stats::QueryMetric::QueryParamBuf query_type_buf; query_type_buf.len = type_buf_len; query_type_buf.buf = PacketCopyBytes(type_buf_begin, type_buf_len); // Unnamed statement if (unnamed_query) { unnamed_stmt_param_types_ = query_type_buf; } else { statement_param_types_[statement_name] = query_type_buf; } } // Unnamed statement if (unnamed_query) { unnamed_statement_ = statement; } else { auto entry = std::make_pair(statement_name, statement); statement_cache_.insert(entry); for (auto table_id : statement->GetReferencedTables()) { table_statement_cache_[table_id].push_back(statement.get()); } } // Send Parse complete response std::unique_ptr<OutputPacket> response(new OutputPacket()); response->msg_type = NetworkMessageType::PARSE_COMPLETE; responses.push_back(std::move(response)); } void PostgresProtocolHandler::ExecBindMessage(InputPacket *pkt) { std::string portal_name, statement_name; // BIND message GetStringToken(pkt, portal_name); GetStringToken(pkt, statement_name); if (skipped_stmt_) { // send bind complete std::unique_ptr<OutputPacket> response(new OutputPacket()); response->msg_type = NetworkMessageType::BIND_COMPLETE; responses.push_back(std::move(response)); return; } // Read parameter format int num_params_format = PacketGetInt(pkt, 2); std::vector<int16_t> formats(num_params_format); auto format_buf_begin = pkt->Begin() + pkt->ptr; auto format_buf_len = ReadParamFormat(pkt, num_params_format, formats); int num_params = PacketGetInt(pkt, 2); // error handling if (num_params_format != num_params) { std::string error_message = "Malformed request: num_params_format is not equal to num_params"; SendErrorResponse( {{NetworkMessageType::HUMAN_READABLE_ERROR, error_message}}); return; } // Get statement info generated in PARSE message std::shared_ptr<Statement> statement; stats::QueryMetric::QueryParamBuf param_type_buf; // UNNAMED STATEMENT if (statement_name.empty()) { statement = unnamed_statement_; param_type_buf = unnamed_stmt_param_types_; // Check unnamed statement if (statement.get() == nullptr) { std::string error_message = "Invalid unnamed statement"; LOG_ERROR("%s", error_message.c_str()); SendErrorResponse( {{NetworkMessageType::HUMAN_READABLE_ERROR, error_message}}); return; } // NAMED STATEMENT } else { auto statement_cache_itr = statement_cache_.find(statement_name); if (statement_cache_itr != statement_cache_.end()) { statement = *statement_cache_itr; param_type_buf = statement_param_types_[statement_name]; } // Did not find statement with same name else { std::string error_message = "The prepared statement does not exist"; LOG_ERROR("%s", error_message.c_str()); SendErrorResponse( {{NetworkMessageType::HUMAN_READABLE_ERROR, error_message}}); return; } } const auto &query_string = statement->GetQueryString(); const auto &query_type = statement->GetQueryType(); // check if the loaded statement needs to be skipped skipped_stmt_ = false; if (HardcodedExecuteFilter(query_type) == false) { skipped_stmt_ = true; skipped_query_string_ = query_string; std::unique_ptr<OutputPacket> response(new OutputPacket()); // Send Bind complete response response->msg_type = NetworkMessageType::BIND_COMPLETE; responses.push_back(std::move(response)); return; } // Check whether somebody wants us to generate a new query plan // for this prepared statement if (statement->GetNeedsPlan()) { ReplanPreparedStatement(statement.get()); } // Group the parameter types and the parameters in this vector std::vector<std::pair<type::TypeId, std::string>> bind_parameters(num_params); std::vector<type::Value> param_values(num_params); auto param_types = statement->GetParamTypes(); auto val_buf_begin = pkt->Begin() + pkt->ptr; auto val_buf_len = ReadParamValue(pkt, num_params, param_types, bind_parameters, param_values, formats); int format_codes_number = PacketGetInt(pkt, 2); LOG_TRACE("format_codes_number: %d", format_codes_number); // Set the result-column format code if (format_codes_number == 0) { // using the default text format result_format_ = std::vector<int>(statement->GetTupleDescriptor().size(), 0); } else if (format_codes_number == 1) { // get the format code from packet auto result_format = PacketGetInt(pkt, 2); result_format_ = std::vector<int>( statement->GetTupleDescriptor().size(), result_format); } else { // get the format code for each column result_format_.clear(); for (int format_code_idx = 0; format_code_idx < format_codes_number; ++format_code_idx) { result_format_.push_back(PacketGetInt(pkt, 2)); LOG_TRACE("format code: %d", *result_format_.rbegin()); } } if (param_values.size() > 0) { statement->GetPlanTree()->SetParameterValues(&param_values); // Instead of tree traversal, we should put param values in the // executor context. } std::shared_ptr<stats::QueryMetric::QueryParams> param_stat(nullptr); if (settings::SettingsManager::GetInt(settings::SettingId::stats_mode) != STATS_TYPE_INVALID && num_params > 0) { // Make a copy of format for stat collection stats::QueryMetric::QueryParamBuf param_format_buf; param_format_buf.len = format_buf_len; param_format_buf.buf = PacketCopyBytes(format_buf_begin, format_buf_len); PL_ASSERT(format_buf_len > 0); // Make a copy of value for stat collection stats::QueryMetric::QueryParamBuf param_val_buf; param_val_buf.len = val_buf_len; param_val_buf.buf = PacketCopyBytes(val_buf_begin, val_buf_len); PL_ASSERT(val_buf_len > 0); param_stat.reset(new stats::QueryMetric::QueryParams( param_format_buf, param_type_buf, param_val_buf, num_params)); } // Construct a portal. // Notice that this will move param_values so no value will be left there. auto portal = new Portal(portal_name, statement, std::move(param_values), param_stat); std::shared_ptr<Portal> portal_reference(portal); auto itr = portals_.find(portal_name); // Found portal name in portal map if (itr != portals_.end()) { itr->second = portal_reference; } // Create a new entry in portal map else { portals_.insert(std::make_pair(portal_name, portal_reference)); } // send bind complete std::unique_ptr<OutputPacket> response(new OutputPacket()); response->msg_type = NetworkMessageType::BIND_COMPLETE; responses.push_back(std::move(response)); } size_t PostgresProtocolHandler::ReadParamType(InputPacket *pkt, int num_params, std::vector<int32_t> &param_types) { auto begin = pkt->ptr; // get the type of each parameter for (int i = 0; i < num_params; i++) { int param_type = PacketGetInt(pkt, 4); param_types[i] = param_type; } auto end = pkt->ptr; return end - begin; } size_t PostgresProtocolHandler::ReadParamFormat(InputPacket *pkt, int num_params_format, std::vector<int16_t> &formats) { auto begin = pkt->ptr; // get the format of each parameter for (int i = 0; i < num_params_format; i++) { formats[i] = PacketGetInt(pkt, 2); } auto end = pkt->ptr; return end - begin; } // For consistency, this function assumes the input vectors has the correct size size_t PostgresProtocolHandler::ReadParamValue( InputPacket *pkt, int num_params, std::vector<int32_t> &param_types, std::vector<std::pair<type::TypeId, std::string>> &bind_parameters, std::vector<type::Value> &param_values, std::vector<int16_t> &formats) { auto begin = pkt->ptr; ByteBuf param; for (int param_idx = 0; param_idx < num_params; param_idx++) { int param_len = PacketGetInt(pkt, 4); // BIND packet NULL parameter case if (param_len == -1) { // NULL mode auto peloton_type = PostgresValueTypeToPelotonValueType( static_cast<PostgresValueType>(param_types[param_idx])); bind_parameters[param_idx] = std::make_pair(peloton_type, std::string("")); param_values[param_idx] = type::ValueFactory::GetNullValueByType(peloton_type); } else { PacketGetBytes(pkt, param_len, param); if (formats[param_idx] == 0) { // TEXT mode std::string param_str = std::string(std::begin(param), std::end(param)); bind_parameters[param_idx] = std::make_pair(type::TypeId::VARCHAR, param_str); if ((unsigned int)param_idx >= param_types.size() || PostgresValueTypeToPelotonValueType( (PostgresValueType)param_types[param_idx]) == type::TypeId::VARCHAR) { param_values[param_idx] = type::ValueFactory::GetVarcharValue(param_str); } else { param_values[param_idx] = (type::ValueFactory::GetVarcharValue(param_str)) .CastAs(PostgresValueTypeToPelotonValueType( (PostgresValueType)param_types[param_idx])); } PL_ASSERT(param_values[param_idx].GetTypeId() != type::TypeId::INVALID); } else { // BINARY mode switch (static_cast<PostgresValueType>(param_types[param_idx])) { case PostgresValueType::INTEGER: { int int_val = 0; for (size_t i = 0; i < sizeof(int); ++i) { int_val = (int_val << 8) | param[i]; } bind_parameters[param_idx] = std::make_pair(type::TypeId::INTEGER, std::to_string(int_val)); param_values[param_idx] = type::ValueFactory::GetIntegerValue(int_val).Copy(); break; } case PostgresValueType::BIGINT: { int64_t int_val = 0; for (size_t i = 0; i < sizeof(int64_t); ++i) { int_val = (int_val << 8) | param[i]; } bind_parameters[param_idx] = std::make_pair(type::TypeId::BIGINT, std::to_string(int_val)); param_values[param_idx] = type::ValueFactory::GetBigIntValue(int_val).Copy(); break; } case PostgresValueType::DOUBLE: { double float_val = 0; unsigned long buf = 0; for (size_t i = 0; i < sizeof(double); ++i) { buf = (buf << 8) | param[i]; } PL_MEMCPY(&float_val, &buf, sizeof(double)); bind_parameters[param_idx] = std::make_pair(type::TypeId::DECIMAL, std::to_string(float_val)); param_values[param_idx] = type::ValueFactory::GetDecimalValue(float_val).Copy(); break; } case PostgresValueType::VARBINARY: { bind_parameters[param_idx] = std::make_pair(type::TypeId::VARBINARY, std::string(reinterpret_cast<char *>(&param[0]), param_len)); param_values[param_idx] = type::ValueFactory::GetVarbinaryValue( &param[0], param_len, true); break; } default: { LOG_ERROR("Do not support data type: %d", param_types[param_idx]); break; } } PL_ASSERT(param_values[param_idx].GetTypeId() != type::TypeId::INVALID); } } } auto end = pkt->ptr; return end - begin; } ProcessResult PostgresProtocolHandler::ExecDescribeMessage(InputPacket *pkt) { if (skipped_stmt_) { // send 'no-data' message std::unique_ptr<OutputPacket> response(new OutputPacket()); response->msg_type = NetworkMessageType::NO_DATA_RESPONSE; responses.push_back(std::move(response)); return ProcessResult::COMPLETE; } ByteBuf mode; std::string portal_name; PacketGetBytes(pkt, 1, mode); GetStringToken(pkt, portal_name); if (mode[0] == 'P') { LOG_TRACE("Describe a portal"); auto portal_itr = portals_.find(portal_name); // TODO: error handling here // Ahmed: This is causing the continuously running thread // Changed the function signature to return boolean // when false is returned, the connection is closed if (portal_itr == portals_.end()) { LOG_ERROR("Did not find portal : %s", portal_name.c_str()); std::vector<FieldInfo> tuple_descriptor; PutTupleDescriptor(tuple_descriptor); return ProcessResult::COMPLETE; } auto portal = portal_itr->second; if (portal == nullptr) { LOG_ERROR("Portal does not exist : %s", portal_name.c_str()); std::vector<FieldInfo> tuple_descriptor; PutTupleDescriptor(tuple_descriptor); return ProcessResult::TERMINATE; } auto statement = portal->GetStatement(); PutTupleDescriptor(statement->GetTupleDescriptor()); } else { LOG_TRACE("Describe a prepared statement"); } return ProcessResult::COMPLETE; } ProcessResult PostgresProtocolHandler::ExecExecuteMessage(InputPacket *pkt, const size_t thread_id) { // EXECUTE message protocol_type_ = NetworkProtocolType::POSTGRES_JDBC; std::string error_message, portal_name; GetStringToken(pkt, portal_name); // covers weird JDBC edge case of sending double BEGIN statements. Don't // execute them if (skipped_stmt_) { if (skipped_query_string_ == "") { SendEmptyQueryResponse(); } else { std::string skipped_query_type_string; Statement::ParseQueryTypeString(skipped_query_string_, skipped_query_type_string); // The response to ExecuteCommand is the query_type string token. CompleteCommand(skipped_query_type_string, skipped_query_type_, rows_affected_); } skipped_stmt_ = false; return ProcessResult::COMPLETE; } auto portal = portals_[portal_name]; if (portal.get() == nullptr) { LOG_ERROR("Did not find portal : %s", portal_name.c_str()); SendErrorResponse( {{NetworkMessageType::HUMAN_READABLE_ERROR, error_message_}}); SendReadyForQuery(txn_state_); return ProcessResult::TERMINATE; } statement_ = portal->GetStatement(); auto param_stat = portal->GetParamStat(); if (statement_.get() == nullptr) { LOG_ERROR("Did not find statement in portal : %s", portal_name.c_str()); SendErrorResponse( {{NetworkMessageType::HUMAN_READABLE_ERROR, error_message}}); SendReadyForQuery(txn_state_); return ProcessResult::TERMINATE; } auto statement_name = statement_->GetStatementName(); bool unnamed = statement_name.empty(); param_values_ = portal->GetParameters(); auto status = traffic_cop_->ExecuteStatement( statement_, param_values_, unnamed, param_stat, result_format_, results_, rows_affected_, error_message_, thread_id); if (traffic_cop_->is_queuing_) { return ProcessResult::PROCESSING; } ExecExecuteMessageGetResult(status); return ProcessResult::COMPLETE; } void PostgresProtocolHandler::ExecExecuteMessageGetResult(ResultType status) { const auto &query_type = statement_->GetQueryType(); switch (status) { case ResultType::FAILURE: LOG_ERROR("Failed to execute: %s", error_message_.c_str()); SendErrorResponse( {{NetworkMessageType::HUMAN_READABLE_ERROR, error_message_}}); return; case ResultType::ABORTED: if (query_type != QueryType::QUERY_ROLLBACK) { LOG_DEBUG("Failed to execute: Conflicting txn aborted"); // Send an error response if the abort is not due to ROLLBACK query SendErrorResponse({{NetworkMessageType::SQLSTATE_CODE_ERROR, SqlStateErrorCodeToString( SqlStateErrorCode::SERIALIZATION_ERROR)}}); } return; default: { auto tuple_descriptor = statement_->GetTupleDescriptor(); SendDataRows(results_, tuple_descriptor.size(), rows_affected_); // The reponse to ExecuteCommand is the query_type string token. CompleteCommand(statement_->GetQueryTypeString(), query_type, rows_affected_); return; } } } void PostgresProtocolHandler::GetResult() { traffic_cop_->ExecuteStatementPlanGetResult(); auto status = traffic_cop_->ExecuteStatementGetResult(rows_affected_); switch (protocol_type_) { case NetworkProtocolType::POSTGRES_JDBC: LOG_TRACE("JDBC result"); ExecExecuteMessageGetResult(status); break; case NetworkProtocolType::POSTGRES_PSQL: LOG_TRACE("PSQL result"); ExecQueryMessageGetResult(status); } } void PostgresProtocolHandler::ExecCloseMessage(InputPacket *pkt) { uchar close_type = 0; std::string name; PacketGetByte(pkt, close_type); PacketGetString(pkt, 0, name); bool is_unnamed = (name.size() == 0) ? true : false; switch (close_type) { case 'S': LOG_TRACE("Deleting statement %s from cache", name.c_str()); if (is_unnamed) { unnamed_statement_.reset(); } else { // TODO: Invalidate table_statement_cache! statement_cache_.delete_key(name); } break; case 'P': { LOG_TRACE("Deleting portal %s from cache", name.c_str()); auto portal_itr = portals_.find(name); if (portal_itr != portals_.end()) { // delete portal if it exists portals_.erase(portal_itr); } break; } default: // do nothing, simply send close complete break; } // Send close complete response std::unique_ptr<OutputPacket> response(new OutputPacket()); response->msg_type = NetworkMessageType::CLOSE_COMPLETE; responses.push_back(std::move(response)); } // The function tries to do a preliminary read to fetch the size value and // then reads the rest of the packet. // Assume: Packet length field is always 32-bit int bool PostgresProtocolHandler::ReadPacketHeader(Buffer& rbuf, InputPacket& rpkt) { // All packets other than the startup packet have a 5 bytes header size_t initial_read_size = sizeof(int32_t); // check if header bytes are available if (!rbuf.IsReadDataAvailable(initial_read_size + 1)) { // nothing more to read return false; } // get packet size from the header // Header also contains msg type rpkt.msg_type = static_cast<NetworkMessageType>(rbuf.GetByte(rbuf.buf_ptr)); // Skip the message type byte rbuf.buf_ptr++; // extract packet contents size //content lengths should exclude the length bytes rpkt.len = rbuf.GetUInt32BigEndian() - sizeof(uint32_t); // do we need to use the extended buffer for this packet? rpkt.is_extended = (rpkt.len > rbuf.GetMaxSize()); if (rpkt.is_extended) { LOG_TRACE("Using extended buffer for pkt size:%ld", rpkt.len); // reserve space for the extended buffer rpkt.ReserveExtendedBuffer(); } // we have processed the data, move buffer pointer rbuf.buf_ptr += initial_read_size; rpkt.header_parsed = true; return true; } // Tries to read the contents of a single packet, returns true on success, false // on failure. bool PostgresProtocolHandler::ReadPacket(Buffer &rbuf, InputPacket &rpkt) { if (rpkt.is_extended) { // extended packet mode auto bytes_available = rbuf.buf_size - rbuf.buf_ptr; auto bytes_required = rpkt.ExtendedBytesRequired(); // read minimum of the two ranges auto read_size = std::min(bytes_available, bytes_required); rpkt.AppendToExtendedBuffer(rbuf.Begin() + rbuf.buf_ptr, rbuf.Begin() + rbuf.buf_ptr + read_size); // data has been copied, move ptr rbuf.buf_ptr += read_size; if (bytes_required > bytes_available) { // more data needs to be read return false; } // all the data has been read rpkt.InitializePacket(); return true; } else { if (rbuf.IsReadDataAvailable(rpkt.len) == false) { // data not available yet, return return false; } // Initialize the packet's "contents" rpkt.InitializePacket(rbuf.buf_ptr, rbuf.Begin()); // We have processed the data, move buffer pointer rbuf.buf_ptr += rpkt.len; } return true; } ProcessResult PostgresProtocolHandler::Process(Buffer &rbuf, const size_t thread_id) { if (request.header_parsed == false) { // parse out the header first if (ReadPacketHeader(rbuf, request) == false) { // need more data return ProcessResult::MORE_DATA_REQUIRED; } } PL_ASSERT(request.header_parsed == true); if (request.is_initialized == false) { // packet needs to be initialized with rest of the contents if (PostgresProtocolHandler::ReadPacket(rbuf, request) == false) { // need more data return ProcessResult::MORE_DATA_REQUIRED; } } auto process_status = ProcessPacket(&request, thread_id); request.Reset(); return process_status; } /* * process_packet - Main switch block; process incoming packets, * Returns false if the session needs to be closed. */ ProcessResult PostgresProtocolHandler::ProcessPacket(InputPacket *pkt, const size_t thread_id) { LOG_TRACE("Message type: %c", static_cast<unsigned char>(pkt->msg_type)); // We don't set force_flush to true for `PBDE` messages because they're // part of the extended protocol. Buffer responses and don't flush until // we see a SYNC switch (pkt->msg_type) { case NetworkMessageType::SIMPLE_QUERY_COMMAND: { LOG_TRACE("SIMPLE_QUERY_COMMAND"); SetFlushFlag(true); return ExecQueryMessage(pkt, thread_id); } case NetworkMessageType::PARSE_COMMAND: { LOG_TRACE("PARSE_COMMAND"); ExecParseMessage(pkt); } break; case NetworkMessageType::BIND_COMMAND: { LOG_TRACE("BIND_COMMAND"); ExecBindMessage(pkt); } break; case NetworkMessageType::DESCRIBE_COMMAND: { LOG_TRACE("DESCRIBE_COMMAND"); return ExecDescribeMessage(pkt); } case NetworkMessageType::EXECUTE_COMMAND: { LOG_TRACE("EXECUTE_COMMAND"); return ExecExecuteMessage(pkt, thread_id); } case NetworkMessageType::SYNC_COMMAND: { LOG_TRACE("SYNC_COMMAND"); SendReadyForQuery(txn_state_); SetFlushFlag(true); } break; case NetworkMessageType::CLOSE_COMMAND: { LOG_TRACE("CLOSE_COMMAND"); ExecCloseMessage(pkt); } break; case NetworkMessageType::TERMINATE_COMMAND: { LOG_TRACE("TERMINATE_COMMAND"); SetFlushFlag(true); return ProcessResult::TERMINATE; } case NetworkMessageType::NULL_COMMAND: { LOG_TRACE("NULL"); SetFlushFlag(true); return ProcessResult::TERMINATE; } default: { LOG_ERROR("Packet type not supported yet: %d (%c)", static_cast<int>(pkt->msg_type), static_cast<unsigned char>(pkt->msg_type)); } } return ProcessResult::COMPLETE; } /* * send_error_response - Sends the passed string as an error response. * For now, it only supports the human readable 'M' message body */ void PostgresProtocolHandler::SendErrorResponse( std::vector<std::pair<NetworkMessageType, std::string>> error_status) { std::unique_ptr<OutputPacket> pkt(new OutputPacket()); pkt->msg_type = NetworkMessageType::ERROR_RESPONSE; for (auto entry : error_status) { PacketPutByte(pkt.get(), static_cast<unsigned char>(entry.first)); PacketPutString(pkt.get(), entry.second); } // put null terminator PacketPutByte(pkt.get(), 0); // don't care if write finished or not, we are closing anyway responses.push_back(std::move(pkt)); } void PostgresProtocolHandler::SendReadyForQuery(NetworkTransactionStateType txn_status) { std::unique_ptr<OutputPacket> pkt(new OutputPacket()); pkt->msg_type = NetworkMessageType::READY_FOR_QUERY; PacketPutByte(pkt.get(), static_cast<unsigned char>(txn_status)); responses.push_back(std::move(pkt)); } void PostgresProtocolHandler::Reset() { ProtocolHandler::Reset(); unnamed_statement_.reset(); result_format_.clear(); results_.clear(); param_values_.clear(); txn_state_ = NetworkTransactionStateType::IDLE; skipped_stmt_ = false; skipped_query_string_.clear(); statement_cache_.clear(); table_statement_cache_.clear(); portals_.clear(); } } // namespace network } // namespace peloton
35.056208
112
0.675042
phisiart
0d609507770c42304e822774cfce78e26207ce2f
1,580
cpp
C++
code/client/citicore/GameMode.Win32.cpp
MyNameIsYesgo/fivem
6def381fa0a992261a4414fae700c1c077e59327
[ "MIT" ]
5
2020-07-26T16:06:24.000Z
2021-05-01T14:29:40.000Z
code/client/citicore/GameMode.Win32.cpp
MyNameIsYesgo/fivem
6def381fa0a992261a4414fae700c1c077e59327
[ "MIT" ]
6
2021-05-11T09:09:11.000Z
2022-03-23T18:34:23.000Z
code/client/citicore/GameMode.Win32.cpp
MyNameIsYesgo/fivem
6def381fa0a992261a4414fae700c1c077e59327
[ "MIT" ]
3
2020-11-09T12:41:05.000Z
2022-01-24T23:16:15.000Z
#include "StdInc.h" #include "ComponentLoader.h" #include "ToolComponent.h" #include <ResumeComponent.h> #include <Error.h> extern "C" DLL_EXPORT void GameMode_Init() { ComponentLoader* loader = ComponentLoader::GetInstance(); loader->Initialize(); // TODO: init dep tree fwRefContainer<ComponentData> cliComponent = loader->LoadComponent("http-client"); cliComponent->GetInstances()[0]->Initialize(); fwRefContainer<ComponentData> gameComponent = loader->LoadComponent("citizen:game:main"); fwRefContainer<ComponentData> nuiComponent = loader->LoadComponent("nui:core"); nuiComponent->GetInstances()[0]->Initialize(); (dynamic_cast<LifeCycleComponent*>(nuiComponent->GetInstances()[0].GetRef()))->PreInitGame(); fwRefContainer<ComponentData> conComponent = loader->LoadComponent("conhost:v2"); conComponent->GetInstances()[0]->Initialize(); /*ComponentLoader::GetInstance()->ForAllComponents([&](fwRefContainer<ComponentData> componentData) { for (auto& instance : componentData->GetInstances()) { instance->Initialize(); } });*/ if (!gameComponent.GetRef()) { FatalError("Could not obtain citizen:game:main component, which is required for the game to start.\n"); return; } gameComponent->GetInstances()[0]->Initialize(); fwRefContainer<RunnableComponent> runnableGame = dynamic_component_cast<RunnableComponent*>(gameComponent->GetInstances()[0].GetRef()); if (runnableGame.GetRef() != nullptr) { runnableGame->Run(); } else { FatalError("citizen:game:main component does not implement RunnableComponent. Exiting.\n"); } }
29.259259
136
0.744304
MyNameIsYesgo
0d60e9f614496667146802167c8e9ef9105a60af
35,069
cc
C++
src/xwrouter_xid_handler.cc
telosprotocol/xwrouter
20ef56c4ec2eaf0b7fd8baab1e06dfbcfbfe22c7
[ "MIT" ]
13
2019-09-17T08:49:46.000Z
2020-01-13T08:06:14.000Z
src/xwrouter_xid_handler.cc
telosprotocol/xwrouter
20ef56c4ec2eaf0b7fd8baab1e06dfbcfbfe22c7
[ "MIT" ]
null
null
null
src/xwrouter_xid_handler.cc
telosprotocol/xwrouter
20ef56c4ec2eaf0b7fd8baab1e06dfbcfbfe22c7
[ "MIT" ]
null
null
null
// Copyright (c) 2017-2019 Telos Foundation & contributors // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "xwrouter/message_handler/xwrouter_xid_handler.h" #include <algorithm> #include "xpbase/base/kad_key/get_kadmlia_key.h" #include "xpbase/base/xip_parser.h" #include "xpbase/base/kad_key/platform_kadmlia_key.h" #include "xpbase/base/top_utils.h" #include "xkad/routing_table/routing_table.h" #include "xkad/routing_table/routing_utils.h" #include "xwrouter/register_routing_table.h" #include "xwrouter/message_handler/wrouter_message_handler.h" #include "xpbase/base/xip_parser.h" #include "xkad/routing_table/client_node_manager.h" #include "xkad/routing_table/dynamic_xip_manager.h" #include "xtransport/utils/transport_utils.h" #include "xpbase/base/kad_key/get_kadmlia_key.h" #include "xpbase/base/uint64_bloomfilter.h" #include "xpbase/base/redis_client.h" #include "xkad/gossip/rumor_filter.h" #include "xgossip/include/broadcast_layered.h" #include "xgossip/include/gossip_bloomfilter.h" #include "xgossip/include/gossip_bloomfilter_layer.h" #include "xgossip/include/gossip_utils.h" #include "xbase/xutl.h" #include "xtransport/message_manager/message_manager_intf.h" #include "xpbase/base/redis_utils.h" #include "xgossip/include/gossip_filter.h" namespace top { using namespace kadmlia; using namespace gossip; namespace wrouter { WrouterXidHandler::WrouterXidHandler( transport::TransportPtr transport_ptr, std::shared_ptr<gossip::GossipInterface> bloom_gossip_ptr, std::shared_ptr<gossip::GossipInterface> layered_gossip_ptr, std::shared_ptr<gossip::GossipInterface> bloom_layer_gossip_ptr, std::shared_ptr<gossip::GossipInterface> set_layer_gossip_ptr) : WrouterHandler( transport_ptr, bloom_gossip_ptr, layered_gossip_ptr, bloom_layer_gossip_ptr, set_layer_gossip_ptr) {} WrouterXidHandler::~WrouterXidHandler() {} int32_t WrouterXidHandler::SendPacket(transport::protobuf::RoutingMessage& message) { if (message.des_node_id().empty()) { TOP_WARN2("send illegal"); return enum_xerror_code_fail; } if (message.hop_num() >= kadmlia::kHopToLive) { TOP_WARN2("stop SendPacket hop_num(%d) beyond max_hop_num(%d)", message.hop_num(), kadmlia::kHopToLive); return enum_xerror_code_fail; } int ret = RandomlyCommunicate(message); if(enum_xerror_code_no_resource != ret) { TOP_WARN2("enum_xerror_code_no_resource"); return ret; } if (message.src_node_id().empty()) { // choose one random(right) id for this message uint64_t service_type = ParserServiceType(message.des_node_id()); RoutingTablePtr routing_table = nullptr; if (message.has_is_root() && message.is_root()) { routing_table = FindRoutingTable(true, static_cast<uint64_t>(kRoot), true, message.des_node_id()); } else { // attention: the last parameter set false is necessary routing_table = FindRoutingTable(false, service_type, false); } if (!routing_table) { TOP_WARN2("FindRoutingTable failed"); return enum_xerror_code_fail; } message.set_src_node_id(routing_table->get_local_node_info()->id()); } if (GossipPacketCheck(message)) { return SendGossip(message); } if (MulticastPacketCheck(message)) { return SendMulticast(message); } TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("SendPacket base xid", message); return SendGeneral(message); } int32_t WrouterXidHandler::SendToLocal(transport::protobuf::RoutingMessage& message) { std::string data; if (!message.SerializeToString(&data)) { TOP_WARN2("wrouter message SerializeToString failed"); return enum_xerror_code_fail; } uint8_t local_buf[kUdpPacketBufferSize]; base::xpacket_t packet(base::xcontext_t::instance(), local_buf, sizeof(local_buf), 0, false); Xip2Header header; memset(&header, 0, sizeof(header)); packet.get_body().push_back((uint8_t*)&header, enum_xip2_header_len); packet.get_body().push_back((uint8_t*)data.data(), data.size()); return transport_ptr_->SendToLocal(packet); } int32_t WrouterXidHandler::SendDirect( transport::protobuf::RoutingMessage& message, const std::string& ip, uint16_t port) { std::string data; if (!message.SerializeToString(&data)) { TOP_WARN2("wrouter message SerializeToString failed"); return enum_xerror_code_fail; } uint8_t local_buf[kUdpPacketBufferSize]; base::xpacket_t packet(base::xcontext_t::instance(), local_buf, sizeof(local_buf), 0, false); Xip2Header header; memset(&header, 0, sizeof(header)); packet.get_body().push_back((uint8_t*)&header, enum_xip2_header_len); packet.get_body().push_back((uint8_t*)data.data(), data.size()); packet.set_to_ip_addr(ip); packet.set_to_ip_port(port); return transport_ptr_->SendData(packet); } int32_t WrouterXidHandler::RecvPacket( transport::protobuf::RoutingMessage& message, base::xpacket_t& packet) { int32_t judgeown_code = JudgeOwnPacket(message, packet); switch (judgeown_code) { case kJudgeOwnError: { TOP_WARN2("RecvBaseXid failed"); return kRecvError; } case kJudgeOwnYes: { return kRecvOwn; } case kJudgeOwnNoAndContinue: { SendPacket(message); return kRecvOk; } case kJudgeOwnYesAndContinue: { SendPacket(message); return kRecvOwn; } default: break; } return kRecvOk; } uint64_t WrouterXidHandler::ParserServiceType(const std::string& kad_key) { auto kad_key_ptr = base::GetKadmliaKey(kad_key); return kad_key_ptr->GetServiceType(); } bool WrouterXidHandler::BroadcastByMultiRandomKadKey( const transport::protobuf::RoutingMessage& message, kadmlia::ResponseFunctor call_back, int64_t recursive_count) { auto main_call_back = [this,recursive_count,call_back](int status,transport::protobuf::RoutingMessage& message,base::xpacket_t& packet) { if(kKadTimeout == status) { if(0 == recursive_count) { return; } int64_t next_recursive_count = recursive_count - 1; BroadcastByMultiRandomKadKey(message,call_back,next_recursive_count); return; } call_back(status,message,packet); }; uint32_t channel_size = kMaxChannelSize; uint32_t message_id = CallbackManager::MessageId(); CallbackManager::Instance()->Add(message_id, kEnoughSuccessAckTimeout, main_call_back, 1); while(channel_size--) { auto des_service_type = ParserServiceType(message.des_node_id()); auto kad_key = std::make_shared<base::PlatformKadmliaKey>(des_service_type); transport::protobuf::RoutingMessage mutil_channel_message; mutil_channel_message.set_id(message_id); mutil_channel_message.set_des_node_id(kad_key->Get()); std::string data; if (!message.SerializeToString(&data)) { TOP_WARN2("wrouter message SerializeToString failed"); continue; } mutil_channel_message.set_is_root(message.is_root()); mutil_channel_message.set_broadcast(true); mutil_channel_message.set_data(data); mutil_channel_message.set_xid(global_xid->Get()); mutil_channel_message.set_type(kKadBroadcastFromMultiChannelRequest); mutil_channel_message.set_enable_ack(true); if(enum_xerror_code_fail == SendPacket(mutil_channel_message)) { TOP_WARN2("SendAfterAchiveMultiChannel failed"); continue; } } return true; } bool WrouterXidHandler::SendToByRandomNeighbors( const transport::protobuf::RoutingMessage& message) { std::string src_node_id = message.src_node_id(); if(src_node_id.empty()) { TOP_WARN2("src node id invalid."); return false; } uint64_t service_type = ParserServiceType(message.des_node_id()); RoutingTablePtr routing_table = nullptr; if (message.has_is_root() && message.is_root()) { routing_table = FindRoutingTable(true, static_cast<uint64_t>(kRoot), true, message.des_node_id()); } else { routing_table = FindRoutingTable(false, service_type, true, message.des_node_id()); } if (!routing_table) { TOP_WARN2("FindRoutingTable failed"); return false; } std::string des_xid = message.des_node_id(); std::vector<kadmlia::NodeInfoPtr> nodes = GetClosestNodes( routing_table, des_xid, kP2pRandomNumGeneral, false); std::string data; if (!message.SerializeToString(&data)) { TOP_WARN2("wrouter message SerializeToString failed"); return false; } auto it_find = std::find_if( nodes.begin(), nodes.end(), [des_xid](const kadmlia::NodeInfoPtr& node_info_ptr) { return node_info_ptr->node_id == des_xid; }); if(it_find != nodes.end()) { nodes = { *it_find }; } for(auto& node_ptr : nodes) { if(!node_ptr) { continue; } transport::protobuf::RoutingMessage send_to_message; send_to_message.set_is_root(message.is_root()); send_to_message.set_broadcast(false); send_to_message.set_data(data); send_to_message.set_xid(global_xid->Get()); send_to_message.set_type(kKadSendToFromRandomNeighborsRequest); send_to_message.set_enable_ack(false); send_to_message.set_des_node_id(node_ptr->node_id); if(enum_xerror_code_fail == SendPacket(send_to_message)) { TOP_WARN2("SendToByRandomNeighbors failed"); continue; } } return true; } void WrouterXidHandler::SendLinksAckToPeer( uint64_t src_message_id, const std::string& src_node_id, const std::string& peer_ip, uint16_t peer_port, uint64_t ack_type) { transport::protobuf::RoutingMessage message; message.set_des_node_id(src_node_id); message.set_data(base::xstring_utl::tostring(src_message_id)); message.set_type(ack_type); message.set_id(CallbackManager::MessageId()); message.set_xid(global_xid->Get()); message.set_broadcast(false); std::string msg; if (!message.SerializeToString(&msg)) { TOP_INFO("RoutingMessage SerializeToString failed!"); return ; } xbyte_buffer_t xdata{msg.begin(), msg.end()}; transport_ptr_->SendData(xdata, peer_ip, peer_port); } int32_t WrouterXidHandler::RandomlyCommunicate( transport::protobuf::RoutingMessage& message) { if(support_random_pattern_) { bool ret = true; if(message.has_broadcast() && message.broadcast()) { auto response_functor = [](int,transport::protobuf::RoutingMessage&,base::xpacket_t&) {}; ret = BroadcastByMultiRandomKadKey(message,response_functor); } else { ret = SendToByRandomNeighbors(message); } return (true == ret ? enum_xcode_successful : enum_xerror_code_fail); } return enum_xerror_code_no_resource; } void WrouterXidHandler::SupportRandomPattern() { support_random_pattern_ = true; } int32_t WrouterXidHandler::SendGeneral(transport::protobuf::RoutingMessage& message) { if (message.des_node_id().empty()) { assert(false); } uint64_t service_type = ParserServiceType(message.des_node_id()); RoutingTablePtr routing_table = nullptr; if (message.has_is_root() && message.is_root()) { routing_table = FindRoutingTable(true, static_cast<uint64_t>(kRoot), true, message.des_node_id()); } else { routing_table = FindRoutingTable(false, service_type, true, message.des_node_id()); } if (!routing_table) { TOP_WARN2("FindRoutingTable failed"); return enum_xerror_code_fail; } std::string des_xid = message.des_node_id(); std::vector<kadmlia::NodeInfoPtr> nodes = GetClosestNodes( routing_table, des_xid, 8, // choose 8 nodes then use bloomfilter choose kBroadcastGeneral nodes false); if (nodes.empty()) { TOP_WARN2("GetClosestNodes failed[%d][%d]", routing_table->nodes_size(), routing_table->get_local_node_info()->kadmlia_key()->xnetwork_id()); return enum_xerror_code_fail; } TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("SendData", message); return SendData(message, nodes, kBroadcastGeneral, false); } int32_t WrouterXidHandler::SendMulticast(transport::protobuf::RoutingMessage& message) { if (message.is_root()) { TOP_WARN2("wsend: send multicast base xid invalid, must not root message"); return enum_xerror_code_fail; } if (message.src_node_id().empty() || message.des_node_id().empty()) { assert(false); } auto gossip = message.mutable_gossip(); if (!gossip->has_msg_hash()) { std::string bin_data = message.data(); if (gossip->has_block()) { bin_data = gossip->block(); } if (!gossip->has_block() && gossip->has_header_hash()) { bin_data = gossip->header_hash(); } uint32_t msg_hash = base::xhash32_t::digest(message.xid() + std::to_string(message.id()) + bin_data); gossip->set_msg_hash(msg_hash); } uint64_t des_service_type = ParserServiceType(message.des_node_id()); RoutingTablePtr routing_table = FindRoutingTable(false, des_service_type, false); if (!routing_table || routing_table->nodes_size() == 0) { // attention: using the right root-routing (not exactlly kRoot) routing_table = FindRoutingTable(true, des_service_type, true, message.des_node_id()); if (!routing_table) { TOP_WARN2("FindRoutingTable failed"); return enum_xerror_code_fail; } // when packet arrive des network, than,multi_flag = default_value,that is kBroadcastGossip std::vector<kadmlia::NodeInfoPtr> nodes = GetClosestNodes( routing_table, message.des_node_id(), 8, false); if (nodes.empty()) { TOP_WARN2("GetClosestNodes failed"); return enum_xerror_code_fail; } #ifdef TOP_TESTING_PERFORMANCE TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE( std::string("SendData with root unicast to other net: ") + std::to_string(message.hop_nodes_size()), message); #endif //return SendData(message, nodes, 3, true); return SendData(message, nodes, 1, true); } #ifdef TOP_TESTING_PERFORMANCE TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE( std::string("SendData with root broadcast to other net: ") + std::to_string(message.hop_nodes_size()), message); #endif return GossipBroadcast( message, routing_table); } int32_t WrouterXidHandler::SendGossip(transport::protobuf::RoutingMessage& message) { if (!message.has_is_root() || !message.is_root()) { TOP_WARN2("SendGossip must be root_msg"); return enum_xerror_code_fail; } auto gossip = message.mutable_gossip(); if (!gossip->has_msg_hash()) { std::string bin_data = message.data(); if (gossip->has_block()) { bin_data = gossip->block(); } if (!gossip->has_block() && gossip->has_header_hash()) { bin_data = gossip->header_hash(); } uint32_t msg_hash = base::xhash32_t::digest(message.xid() + std::to_string(message.id()) + bin_data); gossip->set_msg_hash(msg_hash); } RoutingTablePtr routing_table = FindRoutingTable(true, static_cast<uint64_t>(kRoot), true, message.des_node_id()); if (!routing_table) { TOP_WARN2("FindRoutingTable failed"); return enum_xerror_code_fail; } return GossipBroadcast( message, routing_table); } int32_t WrouterXidHandler::GossipBroadcast( transport::protobuf::RoutingMessage& message, kadmlia::RoutingTablePtr& routing_table) { uint32_t gossip_type = message.gossip().gossip_type(); if (gossip_type == 0) { gossip_type = kGossipBloomfilter; } auto neighbors = routing_table->GetUnLockNodes(); if (!neighbors) { TOP_WARN2("GetUnLockNodes empty"); return enum_xerror_code_fail; } switch (gossip_type) { case kGossipBloomfilter: bloom_gossip_ptr_->Broadcast( routing_table->get_local_node_info()->hash64(), message, neighbors); break; case kGossipLayeredBroadcast: layered_gossip_ptr_->Broadcast( message, routing_table); break; case kGossipBloomfilterAndLayered: /* bloom_layer_gossip_ptr_->Broadcast( routing_table->get_local_node_info()->hash64(), message, neighbors); */ bloom_layer_gossip_ptr_->Broadcast(message, routing_table); break; case kGossipSetFilterAndLayered: set_layer_gossip_ptr_->Broadcast( routing_table->get_local_node_info()->hash64(), message, neighbors); break; default: TOP_WARN2("invalid gossip_type:%d", gossip_type); assert(false); break; } return enum_xcode_successful; } int32_t WrouterXidHandler::SendData( transport::protobuf::RoutingMessage& message, const std::vector<kadmlia::NodeInfoPtr>& neighbors, uint32_t next_size, bool broadcast_stride) { if (neighbors.empty()) { TOP_WARN2("invliad neighbors"); return enum_xerror_code_fail; } std::vector<NodeInfoPtr> rest_neighbors; if (message.broadcast()) { auto gossip_info = message.mutable_gossip(); gossip_info->set_diff_net(broadcast_stride); std::vector<uint64_t> new_bloomfilter_vec; for (auto i = 0; i < message.bloomfilter_size(); ++i) { new_bloomfilter_vec.push_back(message.bloomfilter(i)); } std::shared_ptr<base::Uint64BloomFilter> new_bloomfilter; if (new_bloomfilter_vec.empty()) { new_bloomfilter = std::make_shared<base::Uint64BloomFilter>( gossip::kGossipBloomfilterSize, gossip::kGossipBloomfilterHashNum); auto tmp_routing_table = FindRoutingTable(true, static_cast<uint64_t>(kRoot), true, message.des_node_id()); new_bloomfilter->Add(tmp_routing_table->get_local_node_info()->hash64()); } else { new_bloomfilter = std::make_shared<base::Uint64BloomFilter>( new_bloomfilter_vec, gossip::kGossipBloomfilterHashNum); } for (uint32_t i = 0; i < neighbors.size(); ++i) { NodeInfoPtr node_ptr = neighbors[i]; if ((node_ptr->xid).empty()) { TOP_WARN2("xid empty"); continue; } if (new_bloomfilter->Contain(node_ptr->hash64) && node_ptr->node_id != message.des_node_id()) { #ifdef TOP_TESTING_PERFORMANCE TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE( std::string("already sended to this node: ") + HexEncode(node_ptr->xid) + node_ptr->public_ip + ":" + check_cast<std::string>(node_ptr->public_port) + " : " + std::to_string(neighbors.size()), message); #endif continue; } rest_neighbors.push_back(node_ptr); new_bloomfilter->Add(node_ptr->hash64); if (rest_neighbors.size() >= next_size) { break; } } const std::vector<uint64_t>& bloomfilter_vec = new_bloomfilter->Uint64Vector(); message.clear_bloomfilter(); for (uint32_t i = 0; i < bloomfilter_vec.size(); ++i) { message.add_bloomfilter(bloomfilter_vec[i]); } } base::xpacket_t packet(base::xcontext_t::instance()); _xip2_header xip2_header; memset(&xip2_header, 0, sizeof(xip2_header)); std::string header((const char*)&xip2_header, sizeof(xip2_header)); std::string xbody; if (!message.SerializeToString(&xbody)) { TOP_WARN2("wrouter message SerializeToString failed"); return enum_xerror_code_fail; } std::string xdata = header + xbody; auto each_call = [this, &packet, &message, neighbors, &xdata] (kadmlia::NodeInfoPtr node_info_ptr) { if (!node_info_ptr) { TOP_WARN2("kadmlia::NodeInfoPtr null"); return false; } packet.reset(); packet.get_body().push_back((uint8_t*)xdata.data(), xdata.size()); packet.set_to_ip_addr(node_info_ptr->public_ip); packet.set_to_ip_port(node_info_ptr->public_port); // if (kadmlia::kKadSuccess != transport_ptr_->SendData(packet)) { if (kadmlia::kKadSuccess != transport_ptr_->SendDataWithProp(packet, node_info_ptr->udp_property)) { TOP_WARN2("SendData to endpoint(%s:%d) failed", node_info_ptr->public_ip.c_str(), node_info_ptr->public_port); return false; } #ifdef TOP_TESTING_PERFORMANCE TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE( std::string("send to: ") + node_info_ptr->public_ip + ":" + check_cast<std::string>(node_info_ptr->public_port) + ":" + std::to_string(neighbors.size()), message); #endif return true; }; if (message.broadcast()) { std::for_each(rest_neighbors.begin(), rest_neighbors.end(), each_call); } else { std::for_each(neighbors.begin(), neighbors.begin()+1, each_call); } return enum_xcode_successful; } bool WrouterXidHandler::HandleSystemMessage( transport::protobuf::RoutingMessage& message, kadmlia::RoutingTablePtr& routing_table) { static std::vector<int32_t> direct_vec = { kKadBootstrapJoinRequest, kKadBootstrapJoinResponse, kKadFindNodesRequest, kKadFindNodesResponse, kKadHeartbeatRequest, kKadHeartbeatResponse, kKadHandshake, kKadConnectRequest, kNatDetectRequest, kNatDetectResponse, kNatDetectHandshake2Node, kNatDetectHandshake2Boot, kNatDetectFinish, kUdpNatDetectRequest, kUdpNatDetectResponse, kUdpNatHeartbeat, kKadBroadcastFromMultiChannelRequest, kKadBroadcastFromMultiChannelAck, kKadSendToFromRandomNeighborsRequest, kGossipBlockSyncAsk, kGossipBlockSyncAck, kGossipBlockSyncRequest, kGossipBlockSyncResponse, }; auto it = std::find(direct_vec.begin(), direct_vec.end(), message.type()); if (it != direct_vec.end()) { return true; } /* // special for kconnect msg if (message.type() == kKadConnectRequest || message.type() == kKadConnectResponse) { if ((message.des_node_id()).compare(routing_table->get_local_node_info()->id()) == 0) { return true; } } */ return false; } int32_t WrouterXidHandler::HandleClientMessage( transport::protobuf::RoutingMessage& message, kadmlia::RoutingTablePtr routing_table) { if (!message.has_client_id()) { return kContinueReturn; } if (!routing_table) { return kErrorReturn; } kadmlia::LocalNodeInfoPtr local_node = routing_table->get_local_node_info(); if (!local_node) { return kErrorReturn; } if (!message.relay_flag()) { if (message.client_id() == local_node->id()) { return kContinueReturn; } // this is first relay node return kFirstRelayRetrun; } return kContinueReturn; } int32_t WrouterXidHandler::JudgeOwnPacket( transport::protobuf::RoutingMessage& message, base::xpacket_t& packet) { #ifndef NDEBUG // for test static uint64_t recv_start_time = 0; static std::atomic<uint32_t> recv_count(0); if (message.type() == kTestChainTrade || message.type() == kTestWpingRequest) { if (recv_start_time == 0) { recv_start_time = GetCurrentTimeMsec(); } ++recv_count; if (recv_count % 10000 == 0) { auto use_time_ms = double(GetCurrentTimeMsec() - recv_start_time) / 1000.0; uint32_t qps = (uint32_t)((double)recv_count / use_time_ms); std::cout << "recv " << recv_count << " use time:" << double(GetCurrentTimeMsec() - recv_start_time) << " ms. QPS:" << qps << std::endl; TOP_NETWORK_DEBUG_FOR_REDIS(message, "netqps", qps); } } #endif TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE( std::string("wrouter recv from: ") + packet.get_from_ip_addr() + std::string(":") + std::to_string(packet.get_from_ip_port()) + std::string(" to: ") + packet.get_to_ip_addr() + std::string(":") + std::to_string(packet.get_to_ip_port()), message); // usually only bootstrap message will come here if (message.des_node_id().empty()) { TOP_DEBUG("message type(%d) id(%d) des_node_id empty", message.type(), message.id()); TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("wrouter kJudgeOwnYes", message); return kJudgeOwnYes; } if(message.has_enable_ack() && message.enable_ack() && kKadBroadcastFromMultiChannelRequest == message.type()) { kadmlia::RoutingTablePtr routing_table = GetRoutingTable(kRoot, true); auto local_node_info = routing_table->get_local_node_info(); std::string local_ip = local_node_info->local_ip(); uint16_t local_port = local_node_info->local_port(); std::string packet_from_ip = packet.get_from_ip_addr(); uint16_t packet_from_port = packet.get_from_ip_port(); if(local_ip != packet_from_ip || local_port != packet_from_port) { SendLinksAckToPeer( message.id(), message.src_node_id(), packet_from_ip, packet_from_port, static_cast<uint64_t>(kKadBroadcastFromMultiChannelAck)); message.set_enable_ack(false); std::string body; if (!message.SerializeToString(&body)) { TOP_WARN2("wrouter message SerializeToString failed"); TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("wrouter kJudgeOwnError", message); return kJudgeOwnError; } std::string header((const char*)packet.get_body().data(), enum_xip2_header_len); std::string xdata = header + body; packet.reset(); packet.get_body().push_back((uint8_t*)xdata.data(), xdata.size()); } } if(kKadSendToFromRandomNeighborsRequest == message.type()) { uint64_t service_type = ParserServiceType(message.des_node_id()); auto routing_table = FindRoutingTable(message.is_root(), service_type, true, message.des_node_id()); if (!routing_table) { TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("wrouter kJudgeOwnError", message); return kJudgeOwnError; } auto local_node_info = routing_table->get_local_node_info(); if(local_node_info && message.des_node_id() != local_node_info->id()) { if(!SendToByRandomNeighbors(message)) { TOP_WARN2("SendToByRandomNeighbors failed"); TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("wrouter kJudgeOwnError", message); return kJudgeOwnError; } } } if (message.has_broadcast() && message.broadcast()) { auto gossip = message.mutable_gossip(); // TODO(smaug) get_from_ip_addr decrease performance gossip->set_pre_ip(packet.get_from_ip_addr()); gossip->set_pre_port(packet.get_from_ip_port()); #ifdef TOP_TESTING_PERFORMANCE static std::atomic<uint32_t> brt_rcv_count(0); static std::atomic<uint32_t> brt_filtered_rcv_count(0); static std::atomic<uint32_t> pre_all(0); static std::atomic<uint32_t> pre_filtered(0); static int64_t b_time = GetCurrentTimeMsec(); if (message.type() == kBroadcastPerformaceTest) { ++brt_rcv_count; } if (message.type() == kBroadcastPerformaceTestReset || (message.type() == kBroadcastPerformaceTest && brt_rcv_count % 50000 == 0)) { auto use_sec_time = (float)(GetCurrentTimeMsec() - b_time) / (float)1000.0; b_time = GetCurrentTimeMsec(); if (use_sec_time > 0.0 && brt_rcv_count > 0) { uint32_t tmp_all = brt_rcv_count - pre_all; uint32_t tmp_filter = brt_filtered_rcv_count - pre_filtered; std::string debug_info = base::StringUtil::str_fmt("brt receive all pkg: %u, qps: %f, filtered: %u, qps: %f", (uint32_t)brt_rcv_count, (float)tmp_all / (float)use_sec_time, (uint32_t)brt_filtered_rcv_count, (float)tmp_filter / (float)use_sec_time); std::cout << debug_info << std::endl; TOP_ERROR(debug_info.c_str()); } pre_all = (uint32_t)brt_rcv_count; pre_filtered = (uint32_t)brt_filtered_rcv_count; if (message.type() == kBroadcastPerformaceTestReset) { brt_rcv_count = 0; brt_filtered_rcv_count = 0; } } #endif if (gossip::GossipFilter::Instance()->FilterMessage(message)) { TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("wrouter kJudgeOwnNoAndContinue", message); return kJudgeOwnNoAndContinue; } #ifndef NDEBUG if (message.type() == kBroadcastPerformaceTest) { ++brt_filtered_rcv_count; } if (message.type() == kTestChainTrade) { TOP_NETWORK_DEBUG_FOR_REDIS(message, "stability_af"); } static uint64_t af_recv_start_time = 0; static std::atomic<uint32_t> af_recv_count(0); if (message.type() == kTestChainTrade || message.type() == kTestWpingRequest) { if (af_recv_start_time == 0) { af_recv_start_time = GetCurrentTimeMsec(); } ++af_recv_count; if (af_recv_count % 10000 == 0) { auto use_time_ms = double(GetCurrentTimeMsec() - af_recv_start_time) / 1000.0; uint32_t qps = (uint32_t)((double)af_recv_count / use_time_ms); std::cout << "$$$$$$$$$after filter recv " << af_recv_count << " use time:" << double(GetCurrentTimeMsec() - af_recv_start_time) << " ms. QPS:" << qps << std::endl; } } #endif if (message.is_root()) { TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("wrouter kJudgeOwnYesAndContinue", message); return kJudgeOwnYesAndContinue; } if (message.src_node_id().empty() || message.des_node_id().empty()) { assert(false); } uint64_t src_service_type = ParserServiceType(message.src_node_id()); uint64_t des_service_type = ParserServiceType(message.des_node_id()); if (src_service_type == des_service_type) { TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("wrouter kJudgeOwnYesAndContinue", message); return kJudgeOwnYesAndContinue; } RoutingTablePtr routing_table = FindRoutingTable(false, des_service_type, false); if (routing_table) { TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("wrouter kJudgeOwnYesAndContinue", message); return kJudgeOwnYesAndContinue; } TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("wrouter kJudgeOwnNoAndContinue", message); return kJudgeOwnNoAndContinue; } if (message.has_is_root() && message.is_root()) { TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("wrouter kJudgeOwnYes", message); return kJudgeOwnYes; } uint64_t service_type = ParserServiceType(message.des_node_id()); RoutingTablePtr routing_table = FindRoutingTable(false, service_type, false); if (!routing_table) { TOP_WARN2("FindRoutingTable failed, judge own packet: type(%d) failed", message.type()); TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("wrouter kJudgeOwnNoAndContinue", message); return kJudgeOwnNoAndContinue; } if (HandleSystemMessage(message, routing_table)) { TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("wrouter kJudgeOwnYes", message); return kJudgeOwnYes; } int32_t client_ret = HandleClientMessage(message, routing_table); if (client_ret == kErrorReturn) { TOP_WARN2("HandleClientMessageBaseXid failed"); TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("wrouter kJudgeOwnError", message); return kJudgeOwnError; } if (client_ret == kFirstRelayRetrun) { TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("wrouter kJudgeOwnYes", message); return kJudgeOwnYes; } std::string match_kad_xid = routing_table->get_local_node_info()->id(); if (message.des_node_id().compare(match_kad_xid) == 0) { TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("wrouter kJudgeOwnYes", message); return kJudgeOwnYes; } bool closest = false; if (routing_table->ClosestToTarget(message.des_node_id(), closest) != kadmlia::kKadSuccess) { TOP_WARN2("ClosestToTarget goes wrong"); TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("wrouter kJudgeOwnError", message); return kJudgeOwnError; } if (closest) { TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("wrouter kJudgeOwnYes", message); return kJudgeOwnYes; } TOP_NETWORK_DEBUG_FOR_PROTOMESSAGE("wrouter kJudgeOwnNoAndContinue", message); return kJudgeOwnNoAndContinue; } bool WrouterXidHandler::MulticastPacketCheck(transport::protobuf::RoutingMessage& message) { if (!message.has_broadcast() || !message.broadcast()) { return false; } if (message.has_is_root() && message.is_root()) { return false; } // broadcast to same network or different network return true; } bool WrouterXidHandler::GossipPacketCheck(transport::protobuf::RoutingMessage& message) { if (!message.has_broadcast() || !message.broadcast()) { return false; } if (!message.has_is_root() || !message.is_root()) { return false; } // broadcast to root network(all nodes) return true; } } // namespace wrouter } // namespace top
37.708602
144
0.645214
telosprotocol
0d638a65e38bcdbcae82f465615f70ed64c5b2ed
356
cpp
C++
QtOpenCV/main.cpp
ayaromenok/utils
d3bfd1f8b842def00d32834100ac893f2ae4638b
[ "MIT" ]
null
null
null
QtOpenCV/main.cpp
ayaromenok/utils
d3bfd1f8b842def00d32834100ac893f2ae4638b
[ "MIT" ]
7
2018-04-04T11:46:21.000Z
2020-06-12T14:44:31.000Z
QtOpenCV/main.cpp
ayaromenok/utils
d3bfd1f8b842def00d32834100ac893f2ae4638b
[ "MIT" ]
null
null
null
#include <QApplication> #include <QDebug> #include "cvwidget.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); qDebug() << "++++++++++++++++++++++++++++++++++++++++++"; qDebug() << "|\tQt OpenCV stub app \t|"; qDebug() << "------------------------------------------"; CvWidget w; w.show(); return a.exec(); }
22.25
61
0.424157
ayaromenok
0d6eecec20affe9494c0a8fdcc96b95db8d1a440
30,077
inl
C++
Lumos/External/imgui/plugins/ImGuiAl/fonts/ProggyCleanSZ.inl
perefm/Lumos
2f0ae4d0bad1447b5318043500751be1753666a2
[ "MIT" ]
672
2019-01-29T18:14:40.000Z
2022-03-31T20:38:40.000Z
Lumos/External/imgui/plugins/ImGuiAl/fonts/ProggyCleanSZ.inl
gameconstructer/Lumos
92f6e812fdfc9404bf557e131679ae9071f25c80
[ "MIT" ]
25
2019-10-05T17:16:13.000Z
2021-12-29T01:40:04.000Z
Lumos/External/imgui/plugins/ImGuiAl/fonts/ProggyCleanSZ.inl
gameconstructer/Lumos
92f6e812fdfc9404bf557e131679ae9071f25c80
[ "MIT" ]
83
2019-03-13T14:11:12.000Z
2022-03-30T02:52:49.000Z
// File: 'ProggyCleanSZ.ttf' (41228 bytes) // Exported using binary_to_compressed_c.cpp static const unsigned int ProggyCleanSZ_compressed_size = 9614; static const unsigned int ProggyCleanSZ_compressed_data[9616/4] = { 0x0000bc57, 0x00000000, 0x0ca10000, 0x00000400, 0x00010037, 0x000c0000, 0x00030080, 0x2f534f40, 0x74eb8832, 0x01000090, 0x2c158248, 0x616d634e, 0x23120270, 0x03000075, 0x241382a0, 0x74766352, 0x82178220, 0xfc042102, 0x02380482, 0x66796c67, 0x556ff4f2, 0x04070000, 0x90920000, 0x64616568, 0xd16791d7, 0xcc201b82, 0x36210382, 0x27108268, 0xc3014208, 0x04010000, 0x243b0f82, 0x78746d68, 0x807e008a, 0x98010000, 0x06020000, 0x61636f6c, 0x18b4b38f, 0x82050000, 0x0402291e, 0x7078616d, 0xda00ae01, 0x28201f82, 0x202c1082, 0x656d616e, 0x1f61d7d3, 0x94990000, 0xa42c1382, 0x74736f70, 0xef83aca6, 0x389b0000, 0xd22c3382, 0x70657270, 0x12010269, 0xf4040000, 0x08202f82, 0x012ecb84, 0x50180000, 0x0f5f0fca, 0x0300f53c, 0x00830008, 0x7767b723, 0x29078384, 0xd0a792bd, 0x80fe0000, 0x6f838003, 0x00080024, 0x00850002, 0x0000012a, 0x40fec004, 0x80030000, 0x05821083, 0x07830120, 0x0221038a, 0x25118200, 0x90000101, 0x15842400, 0x3d820220, 0x0a004022, 0x76200b82, 0x06820982, 0x3b820020, 0x83900121, 0xbc0223c8, 0x10828a02, 0x07858f20, 0x00c50123, 0x22668532, 0x94000904, 0x6c412b00, 0x40007374, 0xac200000, 0x00830008, 0x01000523, 0x834d8380, 0x80032103, 0x012101bf, 0x23b88280, 0x00800000, 0x0b830382, 0x07820120, 0x83800021, 0x88012001, 0x84002009, 0x2005870f, 0x870d8301, 0x2023901b, 0x83199501, 0x82002015, 0x84802000, 0x84238267, 0x88002027, 0x8561882d, 0x21058211, 0x13880000, 0x01800022, 0x05850d85, 0x0f828020, 0x03208384, 0x03200582, 0x47901b84, 0x1b850020, 0x1f821d82, 0x3f831d88, 0x3f410383, 0x84058405, 0x210982cd, 0x09830000, 0x03207789, 0xf38a1384, 0x01203782, 0x13872384, 0x0b88c983, 0x0d898f84, 0x00202982, 0x23900383, 0x87008021, 0x83df8301, 0x86118d03, 0x863f880d, 0x8f35880f, 0x2160820f, 0x04830300, 0x1c220382, 0x05820100, 0x4c000022, 0x09831182, 0x04001c24, 0x11823000, 0x0800082e, 0x00000200, 0xff007f00, 0xffffac20, 0x00220982, 0x09848100, 0xdf216682, 0x843586d5, 0x06012116, 0x04400684, 0xa58120d7, 0x00b127d8, 0x01b88d01, 0x2d8685ff, 0xc100c621, 0xf4be0801, 0x9e011c01, 0x88021402, 0x1403fc02, 0x9c035803, 0x1404de03, 0x50043204, 0xa2046204, 0x6e051e05, 0x1a06c405, 0xde067c06, 0x86074007, 0x5608f407, 0x9e087408, 0x1809d808, 0x90095209, 0x880a1e0a, 0x5e0b0c0b, 0x360cd00b, 0xf20c8a0c, 0xac0d660d, 0x580ef20d, 0x300f9e0e, 0x1a10b80f, 0xe8107c10, 0xbe115a11, 0x76120c12, 0x5413cc12, 0xfe13b413, 0xb6146014, 0x4815f214, 0xae158815, 0x1a16c015, 0xce168616, 0x96173c17, 0x5e18e817, 0xf618c218, 0x9e193e19, 0x501adc19, 0xf81aa41a, 0xd01b641b, 0x541c0c1c, 0xf21c9e1c, 0x9a1d321d, 0x481eda1d, 0xe81e961e, 0x7e1f2c1f, 0xae1fae1f, 0x01821820, 0x92203634, 0xd020ba20, 0x7c211c21, 0xf621a021, 0x8e226a22, 0x01821423, 0x83238821, 0x23a03601, 0x24e023b8, 0x24522408, 0x24982470, 0x250e25b6, 0x268a2568, 0x22018200, 0x82b22660, 0xe0be0801, 0xa2274827, 0x70281228, 0x1629b028, 0xc0292829, 0x3e2a002a, 0x682a682a, 0x322b0a2b, 0xb42b662b, 0x282cee2b, 0xa22c3c2c, 0x642d302d, 0xb22d802d, 0x2e2ef02d, 0x2e2fae2e, 0xfc2fbe2f, 0xd0306630, 0xbc314631, 0xa6322632, 0x8a332633, 0x6434f633, 0x4235d634, 0xdc358e35, 0x7a362e36, 0x7e37ee36, 0x4238e037, 0x1a39ae38, 0xb6397c39, 0xa23a363a, 0x843b0e3b, 0x423cf03b, 0x2a3d9e3c, 0xf43d8e3d, 0xce3e5e3e, 0xa23f323f, 0x72401a40, 0x3e41d840, 0x1042aa41, 0x82424842, 0xf842c042, 0xd4436a43, 0x92443244, 0x6045f644, 0xea45be45, 0xbc465c46, 0x82471c47, 0x5c48e247, 0x4849ce48, 0x15462400, 0x034d0808, 0x0b000700, 0x13000f00, 0x1b001700, 0x23001f00, 0x2b002700, 0x33002f00, 0x3b003700, 0x43003f00, 0x4b004700, 0x53004f00, 0x5b005700, 0x63005f00, 0x6b006700, 0x73006f00, 0x7b007700, 0x83007f00, 0x8b008700, 0x00008f00, 0x15333511, 0x20039631, 0x20178205, 0xd3038221, 0x20739707, 0x25008580, 0x028080fc, 0x05be8080, 0x04204a85, 0x05ce0685, 0x0107002a, 0x02000080, 0x00000400, 0x250d8b41, 0x33350100, 0x03920715, 0x13820320, 0x858d0120, 0x0e8d0320, 0xff260d83, 0x00808000, 0x54820106, 0x04800223, 0x845b8c80, 0x41332059, 0x078b068f, 0x82000121, 0x82fe2039, 0x84802003, 0x83042004, 0x23598a0e, 0x00180000, 0x03210082, 0x42ab9080, 0x73942137, 0x2013bb41, 0x8f978205, 0x2027a39b, 0x20b68801, 0x84b286fd, 0x91c88407, 0x41032011, 0x11a51130, 0x15000027, 0x80ff8000, 0x11af4103, 0x841b0341, 0x8bd983fd, 0x9be99bc9, 0x8343831b, 0x21f1821f, 0xb58300ff, 0x0f84e889, 0xf78a0484, 0x8000ff22, 0x0020eeb3, 0x14200082, 0x2130ef41, 0xeb431300, 0x4133200a, 0xd7410ecb, 0x9a07200b, 0x2027871b, 0x21238221, 0xe7828080, 0xe784fd20, 0xe8848020, 0xfe808022, 0x08880d85, 0xba41fd20, 0x82248205, 0x85eab02a, 0x008022e7, 0x2cd74200, 0x44010021, 0xd34406eb, 0x44312013, 0xcf8b0eef, 0x0d422f8b, 0x82332007, 0x0001212f, 0x8023cf82, 0x83000180, 0x820583de, 0x830682d4, 0x820020d4, 0x82dc850a, 0x20e282e9, 0xb2ff85fe, 0x010327e9, 0x02000380, 0x0f440400, 0x0c634407, 0x68825982, 0x85048021, 0x260a825d, 0x010b0000, 0x4400ff00, 0x2746103f, 0x08d74209, 0x4d440720, 0x0eaf4406, 0xc3441d20, 0x23078406, 0xff800002, 0x04845b83, 0x8d05b241, 0x1781436f, 0x6b8c87a5, 0x1521878e, 0x06474505, 0x01210783, 0x84688c00, 0x8904828e, 0x441e8cf7, 0x0b270cff, 0x80008000, 0x45030003, 0xfb430fab, 0x080f4107, 0x410bf942, 0xd34307e5, 0x070d4207, 0x80800123, 0x205d85fe, 0x849183fe, 0x20128404, 0x82809702, 0x00002217, 0x41839a09, 0x6b4408cf, 0x0733440f, 0x3b460720, 0x82798707, 0x97802052, 0x0000296f, 0xff800004, 0x01800100, 0x0021ef89, 0x0a914625, 0x410a4d41, 0x00250ed4, 0x00050000, 0x056d4280, 0x210a7b46, 0x21481300, 0x46ed8512, 0x00210bd1, 0x89718202, 0x21738877, 0x2b850001, 0x00220582, 0x87450a00, 0x0ddb4606, 0x41079b42, 0x9d420c09, 0x0b09420b, 0x8d820720, 0x9742fc84, 0x42098909, 0x00241e0f, 0x00800016, 0x0b47da82, 0x0837442e, 0x49079141, 0x13870b17, 0x44173745, 0xe5410f57, 0x4201200b, 0x01270643, 0x80fd8080, 0x84000180, 0x081d4606, 0x01210d85, 0x201b8400, 0x05414580, 0x66420320, 0x221a981a, 0xa40e0000, 0x0cf146f7, 0x4307f942, 0xdb471395, 0x21bf820f, 0x194300ff, 0x20878508, 0xa40685fe, 0x0f0021b0, 0x3b219fa4, 0x14894100, 0x20072942, 0x06cf4405, 0x90072d42, 0x096d41a5, 0xff808023, 0xaa028900, 0x808021a9, 0x9b82abc5, 0x2007fb44, 0x135d4615, 0x410a1942, 0x48460857, 0x2455410a, 0x1121ab82, 0x29234700, 0x4714fd41, 0x5b411729, 0x0773410f, 0x80800222, 0x22080942, 0x428000fe, 0xfd2008bc, 0x84056341, 0x2bd9481c, 0x00000023, 0x261b4212, 0x4405f74c, 0x9d8714ad, 0xc9440720, 0x1c81410d, 0xb787b085, 0x80410d84, 0x22368431, 0x41000080, 0x7f4a0587, 0x0ca54825, 0x4113cb42, 0x91441393, 0x07974107, 0x144c0120, 0x00ff2105, 0xfe228185, 0x63448000, 0x44802006, 0x0022364d, 0x87410c00, 0x147b4120, 0x851bc745, 0x0532429c, 0x420a6748, 0x002120dd, 0x4f8ba013, 0x37440d0b, 0x13774314, 0x45245b41, 0x80200db5, 0x41059945, 0x80204162, 0x00200082, 0x46362b42, 0xdf931399, 0x2f452783, 0x460f830b, 0x21420e85, 0x2392820c, 0xfe8000ff, 0x94410682, 0x097e4620, 0x04000022, 0x49051f4f, 0xdb470a73, 0x48032008, 0x3b48068b, 0x46022008, 0x00220c2f, 0xbf480600, 0x0eaf4905, 0xc5873f90, 0x4285bd84, 0x4900ff21, 0xfe200716, 0x05851085, 0x00000023, 0x4a03820a, 0x71431903, 0x0749410c, 0x8a07a145, 0x02152207, 0x05ec4100, 0x0782fe20, 0x211b8449, 0x6f828080, 0x80000c27, 0x80030001, 0x15eb4802, 0x2f002b23, 0x142f4300, 0x15216f82, 0x0da74401, 0x8508a351, 0x4d8020cf, 0x80200659, 0xe8898e83, 0x224bff20, 0x25f3830c, 0x03800080, 0xf74a0380, 0x207b8715, 0x876b861d, 0x48152007, 0x0787079f, 0xf2836086, 0x774a0383, 0x21f28417, 0x97430a00, 0x1485431c, 0x830b8d42, 0x4d03200b, 0x80200657, 0x21055043, 0xd7828080, 0x8242da86, 0x221f8318, 0x82001a00, 0x2c0f4e00, 0x940b1f53, 0x0741439b, 0xf74e3120, 0x0b174f12, 0x200bfb49, 0x0abb4121, 0x57413f82, 0x08994508, 0x240a3d44, 0x00018000, 0x20008280, 0x066441fc, 0x088b8020, 0x82000121, 0x48fd2015, 0x014a2c9b, 0x08434715, 0x43270352, 0x0b54140f, 0x0b01480f, 0x20173545, 0x053e4401, 0x80fe8022, 0x830a234f, 0x828020d6, 0x000225d7, 0x8000fd80, 0xdc410588, 0x82d49318, 0x180021d2, 0x552adb48, 0x77430d0f, 0x48bf9310, 0x034113e1, 0x0f75470f, 0xb2843387, 0x4b0e1046, 0xf58e06d6, 0x8400fd21, 0x44fcac2b, 0xdb4b0edb, 0x1fdb4105, 0x4b18df42, 0x1d210adf, 0x0a035101, 0x8308af42, 0x85cb866e, 0x201082ac, 0x2b8e4c01, 0x00000023, 0x30ab4114, 0x4124a341, 0x9741178f, 0x0d934113, 0x85118641, 0x43d88211, 0x91410572, 0x31934830, 0x4a13574f, 0x0b5116a9, 0x07ad4108, 0x4a0f9d42, 0xfe200fad, 0x4708aa41, 0x83482dba, 0x288f4d06, 0xb398c3bb, 0x44267b41, 0x2d4939d7, 0x0755410f, 0x200ebb45, 0x0f5f4215, 0x20191343, 0x06ef5301, 0xad4f0220, 0x43ce8239, 0xa78f3727, 0x5213ff42, 0x2f970bd1, 0x4305bb55, 0x8020111b, 0xac450083, 0x38b8450b, 0x21065f42, 0xed82010c, 0xb3440220, 0x10af441b, 0x480f8750, 0x57470737, 0x0c03490c, 0x4b420c84, 0x05d74c20, 0x87938ba9, 0xea838b94, 0xfe210387, 0x23864300, 0x4107fb4b, 0xd74c1b17, 0x0cb55709, 0x480fd141, 0xf541079d, 0x4780201f, 0x81520680, 0x20a98408, 0x47ad82fe, 0x80200ab4, 0x4106ae47, 0xf289204b, 0x2f4e0020, 0x174f4128, 0x200eab4f, 0x48c98315, 0x94a0130a, 0x1b4a8a82, 0x07275d3f, 0x4b071f44, 0x0f8b071b, 0x4a07034a, 0xa5411b17, 0x0fb1410b, 0x20057b43, 0x060d4a01, 0xf1840787, 0x220e154a, 0x82800001, 0x85058211, 0x082a5d08, 0x41200941, 0x1387133e, 0x4f490020, 0x0b774443, 0x33200b87, 0x8b0e5b5a, 0x072b41f7, 0x0b8b1383, 0x410b9f45, 0x012406f7, 0x00fd8080, 0x8209575a, 0x200e83fa, 0x0e6d5980, 0x82068545, 0x832d832c, 0x38144106, 0x48100021, 0x2f4b28b3, 0x13d7410c, 0x41135f4a, 0xa8830b2b, 0x4b05234b, 0x6a451117, 0x05414b06, 0x41234544, 0x4b5009d1, 0x0fcb472e, 0x5b44b59f, 0x07c5430b, 0x440d6549, 0x80210655, 0x82d68280, 0x4afe2019, 0x002030ec, 0x2105e347, 0xd74d80ff, 0x408b4128, 0x9f503320, 0x2793410a, 0xd454db82, 0x05e7512b, 0x4a5e134b, 0xc9410b21, 0x1fad4117, 0x4f000121, 0x96420685, 0x304b4305, 0x4606bb55, 0x472025cf, 0x490ddd57, 0xa7500ea3, 0x520f840f, 0xb78217e1, 0x4b43da82, 0x0bbe4808, 0x20316e4d, 0x20008200, 0x5e03820e, 0x4f63216b, 0x17eb4620, 0x450a6351, 0x6e410aa3, 0x41002024, 0xeb5f2f63, 0x33ab440b, 0x4a09e34e, 0x11951127, 0x41327241, 0xc39f2a6f, 0x230f9762, 0x15333507, 0x5f095e64, 0xfe2010a2, 0x43078763, 0x002125d0, 0x3b5f6300, 0x73601120, 0x131f480e, 0x521f5748, 0x2f43079b, 0x8315200e, 0x48e7864b, 0x0888082a, 0x8020e483, 0x21096d52, 0x108400fd, 0x5f47fd20, 0x42058405, 0x5048247c, 0x2b374713, 0x551b8b42, 0x215b0a87, 0x0b23410c, 0x2007bd4a, 0x05754d02, 0xfe800022, 0x440c7052, 0x1f820800, 0x0021cfa8, 0x20eb430c, 0xb7410020, 0x0b87440f, 0x43076f42, 0x6f420beb, 0x61fe200f, 0x9aa00c52, 0x5034e343, 0xf9570f21, 0x1f2d5d0f, 0x5d0c6f4b, 0x634d0b2d, 0x52b8a009, 0x0f200ca9, 0x681e9762, 0xf94d07bf, 0x0f494524, 0x200c054e, 0x139742fe, 0x04808022, 0x950c2057, 0x60158523, 0x13201fa7, 0x62052348, 0x0f8f0fbd, 0x638f1520, 0x0021819e, 0x34234100, 0x930f0b41, 0x1075600f, 0x80229a8f, 0xd863fe80, 0x085e4a25, 0x80000a26, 0x00038001, 0x610ea768, 0x834514cb, 0x0bc3430f, 0x70450120, 0x21808408, 0xa95c00fe, 0x1a2e4109, 0x0000002a, 0xff000007, 0x00800380, 0x210fdf58, 0x3d591500, 0x0cd14216, 0x0025ff8c, 0x03000102, 0x08636580, 0x35010024, 0x03821d33, 0x00011522, 0x20083542, 0x06d74400, 0x6b194764, 0xc142097f, 0x08a7480b, 0x490b8f43, 0x1f8b138f, 0x83000121, 0x84fe209e, 0x80fd2105, 0x85091041, 0x19825911, 0x0021d48d, 0x08935400, 0x5d19835a, 0xd9420e27, 0x08c36a06, 0x7d47b59f, 0x8a2f8b0f, 0x0e0b578d, 0x410e174c, 0xd18c1ae7, 0x51087a42, 0xd36505b3, 0x4a2f201a, 0x6f410d4b, 0x0beb530b, 0x88101543, 0x826a83a7, 0x200f82a5, 0x186a6580, 0x00208e86, 0x6c336741, 0xf7650b27, 0x131d420f, 0x421b6741, 0x2e42060f, 0x113a4211, 0x42316941, 0xb34737f7, 0x0f8b460c, 0x5407e556, 0x01200fa7, 0x200c595f, 0x82008280, 0x808021c2, 0x42268841, 0xef64091e, 0x1df74208, 0x41146946, 0x5145138d, 0x2190820f, 0xc4478080, 0x0a70460a, 0x20256141, 0x23008200, 0xfe800015, 0x6f19935e, 0xb18c15cf, 0x4213f149, 0x7d41133b, 0x42c9870b, 0x802010f9, 0x420b2c42, 0x8f441138, 0x267c4408, 0x500cb743, 0x8f410987, 0x05bb701d, 0x83440020, 0x3521223f, 0x0b794733, 0xfb62fe20, 0x4afd2010, 0xaf410ae7, 0x25ce8525, 0x01080000, 0x8b6b0000, 0x0983710b, 0x82010021, 0x064b5f75, 0x67140170, 0x436b0623, 0x14a9480d, 0x0c226282, 0xc36b8000, 0x06df441c, 0x93566f9b, 0x8302200f, 0x0c964152, 0x2005c142, 0x0fb86704, 0xb057238d, 0x050b5305, 0x4217eb47, 0xbd410bab, 0x0fb94410, 0x871f9956, 0x1e91567e, 0x2029b741, 0x20008200, 0x18b7410a, 0x27002322, 0x43092b46, 0x0f8f0fe7, 0x41000121, 0x889d111c, 0x14207b82, 0x00200382, 0x43188761, 0x475013e7, 0x6e33200c, 0x234e0eb3, 0x9b138313, 0x22b58517, 0x4e8000fd, 0x11971109, 0x202ee743, 0x08636a00, 0x87166f62, 0x38d75de7, 0xcb43c384, 0xa9b3a21d, 0x0b8363a7, 0x42135545, 0x814c0fd7, 0x1673440d, 0x43234f48, 0x00220571, 0x1f461300, 0x3459412e, 0x5e0b1b46, 0x6d410b7b, 0x09cd551f, 0x43227441, 0xd7b10c34, 0x410f0d65, 0xf54e2b8d, 0x07c94307, 0x2005594b, 0x0a0046fd, 0x4915eb46, 0xd38c20f5, 0x00250c83, 0x0080000a, 0x18934a00, 0x64130021, 0xd7500643, 0x0743420b, 0x470c2b50, 0xaa82076a, 0x67859b82, 0x211a6441, 0x779c0d00, 0x48057743, 0x51551337, 0x14a54c0b, 0x49082b41, 0x0a4b0888, 0x8080261f, 0x0d000000, 0x20048201, 0x1deb6a03, 0x420cc372, 0x07201783, 0x4306854d, 0x8b830c59, 0x59094c74, 0x9b44250f, 0x0fd7432c, 0xe94c0f97, 0x0e5d6b0d, 0x41115442, 0xb74a1ac1, 0x2243420a, 0x5b4f8f8f, 0x7507200f, 0x384b087f, 0x09d45409, 0x0020869a, 0x12200082, 0xab460382, 0x10075329, 0x54138346, 0xaf540fbf, 0x1ea75413, 0x9a0c9e54, 0x0f9343c1, 0x93430020, 0x0ba75c23, 0x760b6772, 0xef4b10cf, 0x4cff2009, 0x8d9a09a6, 0x00820020, 0x4134c345, 0x0f970fe1, 0x441fd74b, 0x9b4216e4, 0x43cd8405, 0xc79a094c, 0x840f5541, 0x2947470f, 0x540f555c, 0x234e1787, 0x0a1b6e0f, 0x6b087d54, 0xa8881d73, 0x0e000026, 0x00ff8000, 0x48189b52, 0x0f78088b, 0x0b83450b, 0x70061d4d, 0x1b86081f, 0x2008cb69, 0x0b334b02, 0x4a0cc34b, 0x1f611d0d, 0x010b210c, 0x7352a382, 0x11cf7d08, 0x4a0c2345, 0x0f8f0f89, 0xa5410120, 0x22f25414, 0x41282b41, 0x134106c7, 0x0b3d4818, 0x630b7b4c, 0x0f630c06, 0x41088208, 0x00282a2a, 0x01000008, 0x02800380, 0x48113f4e, 0x97750cf5, 0x07f1530f, 0x31610120, 0x6d802007, 0x8f840e33, 0x8208bf51, 0x0c737d61, 0x7f093379, 0x4f470f5b, 0x17855c0c, 0x46076157, 0xf5500fdf, 0x0f616910, 0x8080fe24, 0x148400ff, 0x2009c245, 0x127a4c03, 0x8315f341, 0x27d28215, 0x00010400, 0x000200ff, 0x851c0778, 0x886c8541, 0x203c824d, 0x243f4310, 0x3f003b22, 0x45093b4d, 0xf18f0b3b, 0x420fad42, 0x4b430b1f, 0x88f28808, 0xfe802188, 0x842a2642, 0x010625f6, 0x0280ff00, 0x250bfb78, 0x00170013, 0xbf6d2500, 0x07db760e, 0x410e3b7f, 0x00230e4f, 0x49030000, 0x0582055b, 0x07000326, 0x00000b00, 0x580bcd46, 0x00200cdd, 0x57078749, 0x8749160f, 0x0f994f0a, 0x41134761, 0x01200b31, 0x8a060a42, 0x437a8506, 0x7b512341, 0x5801202e, 0x057005d9, 0x0fc94108, 0x7a0f1d53, 0x634b0ba3, 0x7aaf8d08, 0x62580bb5, 0x8080222d, 0x23008200, 0x03800005, 0x7b0fcb45, 0x7f430cb3, 0x43012007, 0xfe220636, 0x0a828000, 0x460d1c41, 0x802008af, 0x881efb79, 0x0b174859, 0x6f0bc374, 0x27480feb, 0x00022207, 0x05f07680, 0x43065947, 0x0d7e0854, 0x4203200a, 0x0e940e61, 0x0022aa82, 0xfa820015, 0x05800322, 0x180fdb58, 0x8720af40, 0x0fa7418d, 0x610aa344, 0xff223149, 0x40188000, 0xe25f08b4, 0x10516105, 0x34674318, 0x05000022, 0x8021e782, 0x0d535902, 0x71088141, 0xaf84063d, 0x8405db41, 0x41022085, 0x00200e35, 0x463d835f, 0x152106d7, 0x0a355a33, 0x6917614e, 0x75411f4d, 0x184b8b07, 0x1809d344, 0x21092640, 0x0b828000, 0x42808021, 0x35420519, 0x20138208, 0x422d86fe, 0x07412428, 0x210e840e, 0x3b420000, 0x7bf58751, 0x9f781367, 0x0caf4d13, 0x8000ff22, 0x747bd487, 0x00ff210d, 0x0482b084, 0x27363b42, 0x03800103, 0x04800200, 0x0f174118, 0x46072f42, 0x00250c3b, 0x01030000, 0x47411800, 0x20c38315, 0x06855c01, 0x95880420, 0x83060021, 0x10434a2f, 0x14134518, 0x070b4218, 0xd984ea85, 0xe6854889, 0x06000023, 0x56af8d00, 0x4fa2053b, 0x9383fe20, 0x0d204f91, 0x1a534018, 0x070f4818, 0x500cd37b, 0xd7450b79, 0x0bd9420f, 0x830a4745, 0x777e84bb, 0x7542095a, 0x20138413, 0x3f401800, 0x0007213e, 0x4405e349, 0x0d550ff3, 0x16254c0c, 0x820ffe4a, 0x0400218a, 0x89066f41, 0x106b414f, 0xc84d0120, 0x80802206, 0x0c9a4b03, 0x00100024, 0xef650200, 0x003b2221, 0x4349183f, 0x1343440d, 0x6a0f3344, 0x78860ff3, 0x440a2546, 0x988c0a1b, 0x20187941, 0x079b5e80, 0x18080b43, 0x41191b4a, 0x59530c03, 0x25155212, 0x1146ff20, 0x091d520a, 0x7d000421, 0xae990be5, 0x2008d747, 0x10fb4500, 0xf3511320, 0x088f5205, 0x59350521, 0x708505cb, 0x2110fa45, 0x00820015, 0x03800322, 0x470f3342, 0xf1451c27, 0x07ed450f, 0x5b133d4c, 0xbf4b1363, 0x07f1410b, 0x6d146157, 0xf64505cb, 0x50088208, 0xc78f06c9, 0x431b2a41, 0x437e085b, 0x11034d07, 0x11ff4b18, 0x4f1ce541, 0x01202781, 0x2006a564, 0x178a4ffe, 0x2529ef41, 0x00008080, 0x0082000d, 0xaf450320, 0x13a34209, 0x8976b788, 0x0fff500b, 0x55074143, 0xfd200cd3, 0x0a334c18, 0x5105d467, 0xc46109af, 0x4dff2007, 0x9d821c43, 0x1dd74b18, 0x4c07b97c, 0x7c440fcd, 0x6603200e, 0xd4410683, 0x1200280e, 0x80ff8000, 0x41030003, 0x0b6b23bf, 0x0bc54906, 0x0f894618, 0x180ff753, 0x4517bd46, 0xfd200ecd, 0x18089c4b, 0x210bc746, 0x998200ff, 0x0e9bb08e, 0x00820020, 0x18001021, 0x6d274b45, 0xfd4c0c93, 0xdf451813, 0x0fe5450f, 0x5a47c382, 0x820a8b0a, 0x9b0320a4, 0x0ea34da8, 0x83421420, 0x26834105, 0x4f004b22, 0x4f05df45, 0xd3450fb1, 0x132f4a0f, 0x2387c38f, 0x80028023, 0x0cd05480, 0x830e8c58, 0x821f82b1, 0x42032025, 0xf5911cae, 0x1020db82, 0x0420df85, 0x55210f45, 0xc36810bb, 0x0f454c13, 0x680bed4d, 0x564217d3, 0x419f8307, 0x00212b9a, 0x1c0f530a, 0x43140d53, 0x8d431391, 0x15294f0e, 0x560f0944, 0xcf4205fb, 0x2a9f4305, 0x7f120742, 0xeb5e0c47, 0x18af6e0a, 0x840ff362, 0x1804849a, 0x200a6e44, 0x2c0a4204, 0x02000025, 0x4b040001, 0x5545091b, 0x09494a09, 0x1c000022, 0x18282b42, 0x53174f52, 0x0b410c7b, 0x75152012, 0xab44071f, 0x1317740b, 0x6f43278f, 0x08654717, 0x80800224, 0x3c7f80fc, 0x8401200b, 0x8d128210, 0x096b4318, 0x2f430320, 0x2611ad11, 0x80000b00, 0x50028001, 0x0020193f, 0x0b494118, 0x8f0fb945, 0x0a7952d1, 0x234d5682, 0x58a39b06, 0x2f6405cb, 0x0cf14719, 0x52131b46, 0xf68308f3, 0x09bc4c18, 0x20096e42, 0x180f4102, 0x07000029, 0x00008000, 0x44028002, 0x01420f57, 0x10c95c10, 0x11284c18, 0x80221185, 0x7f421e00, 0x00732240, 0x43431877, 0x0fcb4415, 0x0b834b18, 0x830f8f5a, 0x411f9b0f, 0xff700fb9, 0x09a94509, 0xd384fc20, 0x6f000121, 0x11940951, 0x834a8d42, 0x00002a70, 0x00000700, 0x80038004, 0x10974105, 0x1bd95518, 0x8021ac84, 0x0f764f80, 0x00244e82, 0x02800008, 0x04200182, 0x47110345, 0x91490cc3, 0x1831200f, 0x20160b51, 0x13b64404, 0x0e206783, 0x20053b48, 0x4a679103, 0x4e180bcb, 0x4f470c0f, 0x65072013, 0x3f6b0a73, 0x0d81540c, 0x31488020, 0x48802005, 0x0e4618e3, 0x0a00240b, 0x45028000, 0x9759093b, 0x0bf1420f, 0x470ca54c, 0x82830f2b, 0x0c624c18, 0x84140c41, 0xb3002025, 0x5fef8273, 0x4d8410b5, 0xe043fe20, 0x22719b08, 0x59020000, 0xeb410551, 0x08295006, 0x83000221, 0x203a86b5, 0x23008200, 0xff000011, 0x7c27135e, 0x1d7a1c93, 0x5d451817, 0x05ef4d0b, 0x20174d5f, 0x0a136180, 0xa784fd20, 0x4419b444, 0x077c10cd, 0x78802005, 0x59182a4b, 0xf5590f43, 0x0bef460c, 0x0b135418, 0x470b0742, 0x15200aff, 0x181b9345, 0x210f3956, 0xbd840001, 0x13415518, 0x4b05dd41, 0x13840dc4, 0xf0900320, 0x002a10ab, 0x01090000, 0x02000100, 0x93430280, 0x8bf98c13, 0x10476ae1, 0x02209f89, 0x2613fc43, 0x04000080, 0x83fe8001, 0x09b34465, 0x45870020, 0x08d34918, 0xa449ba84, 0x0800240d, 0x69028000, 0x438b1a7b, 0x220f634c, 0x87800001, 0x2007844c, 0x439a9604, 0x56181f87, 0xcf7b1b3f, 0x1756180c, 0x08e3470f, 0x3f647995, 0x1adf4708, 0xc35a1320, 0x0f3b4216, 0x5906c854, 0xa96c090b, 0x19294306, 0x00000024, 0x6f580016, 0x00572131, 0x46102b59, 0x4b7b0f17, 0x138f4707, 0x8954b787, 0x8243830f, 0x05fc4aab, 0x57590583, 0x84012011, 0x18e88212, 0x5908235a, 0xf04205f1, 0x0def532b, 0x1b4bffde, 0x0f374e17, 0xff9b2787, 0xfe808022, 0x1a41ed84, 0x20058505, 0x201182fe, 0x37495700, 0x00808022, 0x071f4118, 0x47480520, 0x1b47530f, 0x095b5e18, 0x630c6556, 0xdd450f4f, 0x0b81560b, 0x0f5f5918, 0x55180f83, 0x17420b4b, 0x20e78217, 0x724f1801, 0x20f48209, 0x820383fe, 0x80802415, 0x428000ff, 0x99654d1a, 0xd74c1808, 0x078b4e22, 0x2007f55f, 0x4b491807, 0xd14c1817, 0x45491809, 0x0dec440b, 0x20099d42, 0x07df7b80, 0x74269b41, 0x376c09bb, 0x1ba5600e, 0x830fb743, 0xbb4b180f, 0x6004202b, 0x8e431447, 0xb2002018, 0x831520d3, 0xbe0320bf, 0x08036fd3, 0x23904c18, 0x1420d4af, 0x4b304345, 0x5f461053, 0x130f431b, 0x180f3f44, 0x82094742, 0x754d18e0, 0x0a044c24, 0x41188142, 0x48180ec7, 0x93420aa7, 0x004b2226, 0x052b464f, 0x0cb76018, 0x733ecb41, 0xd0410d83, 0x0820472a, 0x0e93d78e, 0x1220eb83, 0x2005d741, 0x13174904, 0x11776318, 0xb9560020, 0x40cb4107, 0xa4083348, 0x070045db, 0x1390c593, 0x593bef47, 0x52181311, 0x4b440b33, 0x2eb7420f, 0xd990f5ad, 0x002210a4, 0x7b501700, 0x0c074b36, 0x490bad46, 0x48180b85, 0xfd470f25, 0x554c181f, 0x5780200c, 0x00200aa0, 0x0a125c18, 0x200e2556, 0x2c5e5501, 0x820d1541, 0x001123fb, 0x4518fe80, 0xf38c2753, 0x6d134979, 0x295107a7, 0xbf5f180f, 0x0fe3660c, 0x180b6079, 0x2007cd5f, 0x9ea78d03, 0x0987440d, 0x48050021, 0x1f4729b7, 0x0f9f4210, 0x13614f18, 0x17954f18, 0x830af750, 0x88fd20ac, 0x00fe21b1, 0x46460a88, 0x2437832e, 0x00140000, 0xaed28380, 0x831520d7, 0x0fd35da7, 0xa30fa165, 0x472383ef, 0x245a052b, 0x62d9c906, 0xb341079f, 0x4c53202b, 0x33200969, 0x4116f151, 0x179717a1, 0x195be183, 0x0f5e7013, 0x47081f47, 0xbf41271d, 0x4604200c, 0x1f472533, 0x47bf410c, 0xdb600120, 0x55601808, 0x209b8208, 0x591583fe, 0xd7ad0b13, 0x00010d25, 0x54020000, 0x274c116f, 0x1461430b, 0x4f0f1d6c, 0x681810a1, 0x8f8a07c4, 0x3e430a84, 0x05737224, 0x214397a2, 0x43979f10, 0x65180505, 0x99aa0f02, 0x0e000022, 0x20223341, 0x19e14237, 0xc542a19f, 0x0ed74808, 0x8020a38b, 0x4508fe50, 0x3f411553, 0x1caf4207, 0x6a0c9b5f, 0x13521bb3, 0x10d84115, 0x2022b148, 0x07df6100, 0x20294743, 0x11115853, 0x550f254b, 0xb1480fa9, 0x0fc7460f, 0x08374218, 0x784ffe20, 0x57022007, 0x012007e9, 0x0ac35818, 0x093a5618, 0x41145d52, 0x15851579, 0x4a190021, 0x05200563, 0x1829c746, 0x5909bb5a, 0x414410f9, 0x13695b07, 0x0b8d4f18, 0x0f754f18, 0x1b814f18, 0x20096d4b, 0x854f18fe, 0x32664c33, 0x600ca051, 0x7744056b, 0x0037221d, 0x068f6e3b, 0x8b7d1d20, 0x13fd410b, 0x4e1bf141, 0x4f180df7, 0x8025128f, 0x80000180, 0x096d51fe, 0x61234145, 0xc3a7092f, 0x9b20ef4e, 0x0ee74ec3, 0x0b4dc4c9, 0x26a74206, 0x9b2cdf4e, 0x13d74ecf, 0x1145d4a2, 0x1881430e, 0x4e348f50, 0xd79f27cb, 0x65fe8021, 0xaf4f0666, 0x43d7cc06, 0x04200637, 0x4e213f45, 0xcb9c24b7, 0x9c0eb94d, 0x22fb45c7, 0x08bb6118, 0xe76a0920, 0x0c6f5a1a, 0x770bfb6e, 0xbb7718bd, 0x090f5722, 0x8f450420, 0x08ef422d, 0x450fdb54, 0x8d451769, 0x0f99450b, 0x210b1f57, 0x5e4c8001, 0x00012406, 0x6e80fd80, 0x80230b3c, 0x1800fd80, 0x8408746e, 0x181f8519, 0x4a36c45c, 0x0f4305bd, 0x08734533, 0x97172342, 0x0fb75d17, 0x8000fe22, 0x15465018, 0xa783178b, 0x4507c05e, 0xd7b9237f, 0x9708314a, 0x8b1797bf, 0x058f45d7, 0xd880fe21, 0x467b54d9, 0x1797cb97, 0x4210bb41, 0xc1410781, 0x27a7452d, 0x4605c541, 0xd3440683, 0x00432322, 0xd7440047, 0x97c7970c, 0x20df8c17, 0x067d5e00, 0xe344dba7, 0x6bd68528, 0x0520071f, 0x591b7344, 0x1f6b0869, 0x067d422b, 0xb1670020, 0x4d7f8317, 0x676e2566, 0x49a39b08, 0x13200687, 0x0a737018, 0x490b4741, 0x1f8f138f, 0x1805c37e, 0x18091555, 0x200e2f4c, 0x4d5d18fe, 0x08bc5924, 0x0000002a, 0xff000019, 0x04800380, 0x66210747, 0xff5211eb, 0x13274c18, 0x5d42dd93, 0x13c9620f, 0x4c0d0568, 0x714c084a, 0x7f5f180b, 0x82de830e, 0x4c042012, 0x5b5a306c, 0x41002011, 0xd94f2617, 0x10836213, 0x181b1f56, 0x500e9d6c, 0x4118088f, 0xd686112e, 0x5a26db45, 0xc7ab064f, 0xb40f0950, 0x055943c7, 0x4d18a485, 0x1185117e, 0x4f18c9ae, 0x012032b3, 0x0a157a18, 0xb40a3d52, 0x0c4d50d1, 0x18059a4a, 0x8c0c194c, 0x1f5650d3, 0x54086942, 0x674207cf, 0x0c0f5326, 0x7708b768, 0xd9b7099f, 0x8407365e, 0x1eaf4197, 0x182a9346, 0x2031a370, 0x06cb6101, 0x2040ad41, 0x07365300, 0x2018aa41, 0x124a6303, 0x5619084d, 0x77183a77, 0xa7410821, 0x4dff2041, 0x58430611, 0x44c68a1e, 0x16212727, 0x74008200, 0x57202e2f, 0x18095152, 0x520f8b4b, 0xe9590f49, 0x13294617, 0x4d085552, 0xc84507f7, 0x05d76c06, 0x8000fe23, 0x20028401, 0x631685fd, 0xcc4119bd, 0x00002319, 0x4a180f00, 0xe3462643, 0x2d531818, 0x0cdb5917, 0x10b55118, 0x69430120, 0x41ff2006, 0xbda706c8, 0x5132c745, 0x7b460ceb, 0x1369470f, 0x20149761, 0x0c3a7e00, 0x5341fd20, 0x7b521805, 0x30c6450c, 0xf351cbb2, 0x45cbb80c, 0xfe220895, 0x48488000, 0xbd802008, 0x001325cc, 0x03000080, 0x20275f47, 0x1dcd564b, 0x18170d43, 0x86181554, 0x5cfe20d1, 0xa1410a43, 0x29944619, 0x1844b745, 0x9d3ae754, 0x2db845ce, 0x0920cb82, 0x1ae35018, 0x7610b949, 0x0f830fc3, 0x05430120, 0x08524407, 0x201bf442, 0x426f9f00, 0x6f940ccd, 0x9c11aa41, 0xc7511870, 0x17c74b08, 0x0c154218, 0x1b1b5318, 0x7e0de548, 0xbe7a0887, 0x95ef861c, 0x101b597b, 0x5f83ef94, 0xaf45fe20, 0x8def850c, 0x49208613, 0x6f673733, 0xc37b180b, 0x0fab460b, 0x7f1ba94c, 0x73180cc1, 0x33490a80, 0x38a37411, 0x440bcb4f, 0xe9582757, 0x17774718, 0x0120e397, 0x41081b5d, 0x664d057a, 0x14786e08, 0x200a624d, 0x216d4dff, 0x4e08234f, 0x9543216b, 0x0ff34510, 0x450f394e, 0xb1430f39, 0x82c09708, 0x07fc7a17, 0x201e025c, 0xae008380, 0x0f434dbb, 0x9f0c0b45, 0x0a3b4dbb, 0x4618bdc7, 0x5d4c32eb, 0x44c5ac12, 0xc7a30c49, 0x4411f344, 0x0c850c10, 0x58333b48, 0x4f42138f, 0x827e8330, 0x808021c5, 0x430d6b47, 0x55420e16, 0x26274d0b, 0x61312f7c, 0xcb430fe9, 0x13d76a17, 0x200d5d77, 0x0cc14e80, 0x200ab144, 0x271b4d03, 0x58070021, 0x59181683, 0x2d540cf5, 0x3335230c, 0x46410115, 0x20068406, 0x446b8202, 0x0b830b3d, 0x14000022, 0x4f2c137e, 0x81710817, 0x876e180f, 0x0f2f7e13, 0x450be376, 0x98820b2f, 0x0e45fe20, 0x18012006, 0x87178082, 0x44032020, 0xcd4221fe, 0x09f75c0d, 0x4523e345, 0x3f440c0f, 0x41178f17, 0x9f820c75, 0x5018fe20, 0x664822f6, 0x18c0901b, 0x512afb5a, 0x9d550789, 0x20bf9c1b, 0x066c4780, 0x530e7043, 0x80183b1f, 0x8f46087b, 0x4b432021, 0xad8f11b7, 0x85410f97, 0x21c5840c, 0x0e458080, 0x80fd2117, 0x08d15f18, 0x42188020, 0x7f562d42, 0x0b63512b, 0x178fb597, 0xd54ec58c, 0x1490410c, 0x44050c53, 0x00222945, 0x8f4f1500, 0x2a075305, 0x420afb66, 0x5f183755, 0x915a13f3, 0x41d89408, 0x4d780ba1, 0x2202490f, 0x240c4243, 0x80001400, 0x738718ff, 0x435e182d, 0x0b93410c, 0x182b0346, 0x180cab40, 0x18087752, 0x8216975b, 0x202282f0, 0x2c5758fe, 0xd741e589, 0x21175909, 0x4c095f58, 0x89420c33, 0x180f970f, 0x581ff355, 0xe2411347, 0x0902680e, 0xd541ef8a, 0x82002030, 0x01152300, 0x00870002, 0x58002422, 0x01240a86, 0x84001e00, 0x02220b86, 0x09860e00, 0x03000022, 0x0420178a, 0x05220b8a, 0x25881400, 0x17840620, 0x33860120, 0x22001223, 0x240b8500, 0x000f0001, 0x240b863f, 0x00070002, 0x240b8634, 0x00130003, 0x200b863b, 0x24238a04, 0x000a0005, 0x2017864e, 0x24178406, 0x04010003, 0x83578209, 0x850b85a7, 0x850b85a7, 0x240b85a7, 0x00260003, 0x83ad827c, 0x85a7852f, 0x85a78517, 0x30a7850b, 0x00650052, 0x00750067, 0x0061006c, 0x00320072, 0x22018230, 0x862f0034, 0x31330805, 0x79623500, 0x69725420, 0x6e617473, 0x69724720, 0x72656d6d, 0x75676552, 0x5472616c, 0x50205854, 0x67676f72, 0x656c4379, 0x54546e61, 0x30325a53, 0x822f3430, 0x35312902, 0x79006200, 0x54002000, 0x69245382, 0x74007300, 0x6e205d82, 0x47200f82, 0x6d220f84, 0x75826d00, 0x1d827220, 0x58005422, 0x50201582, 0x6f201582, 0x67208582, 0x43203382, 0x65208982, 0x54202d84, 0x53231f82, 0x41005a00, 0x1422099f, 0x0f410000, 0x87088206, 0x01012102, 0x78080982, 0x01020101, 0x01040103, 0x01060105, 0x01080107, 0x010a0109, 0x010c010b, 0x010e010d, 0x0110010f, 0x01120111, 0x01140113, 0x01160115, 0x01180117, 0x011a0119, 0x011c011b, 0x011e011d, 0x0020011f, 0x00040003, 0x00060005, 0x00080007, 0x000a0009, 0x000c000b, 0x000e000d, 0x0010000f, 0x00120011, 0x00140013, 0x00160015, 0x00180017, 0x001a0019, 0x001c001b, 0x001e001d, 0x09bd821f, 0x22002191, 0x24002300, 0x26002500, 0x28002700, 0x2a002900, 0x2c002b00, 0x2e002d00, 0x30002f00, 0x32003100, 0x34003300, 0x36003500, 0x38003700, 0x3a003900, 0x3c003b00, 0x3e003d00, 0x40003f00, 0x42004100, 0x44004300, 0x46004500, 0x48004700, 0x4a004900, 0x4c004b00, 0x4e004d00, 0x50004f00, 0x52005100, 0x54005300, 0x56005500, 0x58005700, 0x5a005900, 0x5c005b00, 0x5e005d00, 0x60005f00, 0x21016100, 0x23012201, 0x25012401, 0x27012601, 0x29012801, 0x2b012a01, 0x2d012c01, 0x2f012e01, 0x31013001, 0x33013201, 0x35013401, 0x37013601, 0x39013801, 0x3b013a01, 0x3d013c01, 0x3f013e01, 0x41014001, 0xa300ac00, 0x85008400, 0x9600bd00, 0x8600e800, 0x8b008e00, 0xa9009d00, 0xef00a400, 0xda008a00, 0x93008300, 0xf300f200, 0x97008d00, 0xc3008800, 0xf100de00, 0xaa009e00, 0xf400f500, 0xa200f600, 0xc900ad00, 0xae00c700, 0x63006200, 0x64009000, 0x6500cb00, 0xca00c800, 0xcc00cf00, 0xce00cd00, 0x6600e900, 0xd000d300, 0xaf00d100, 0xf0006700, 0xd6009100, 0xd500d400, 0xeb006800, 0x8900ed00, 0x69006a00, 0x6d006b00, 0x6e006c00, 0x6f00a000, 0x70007100, 0x73007200, 0x74007500, 0x77007600, 0x7800ea00, 0x79007a00, 0x7d007b00, 0xb8007c00, 0x7f00a100, 0x80007e00, 0xec008100, 0xba00ee00, 0x696e750e, 0x65646f63, 0x30783023, 0x8d313030, 0x8d32200e, 0x8d33200e, 0x8d34200e, 0x8d35200e, 0x8d36200e, 0x8d37200e, 0x8d38200e, 0x8d39200e, 0x8d61200e, 0x8d62200e, 0x8d63200e, 0x8d64200e, 0x8d65200e, 0x8c66200e, 0x3031210e, 0xef8d0e8d, 0xef8d3120, 0xef8d3120, 0xef8d3120, 0xef8d3120, 0xef8d3120, 0xef8d3120, 0xef8d3120, 0xef8d3120, 0xef8d3120, 0xef8d3120, 0xef8d3120, 0xef8d3120, 0xef8d3120, 0x0666312d, 0x656c6564, 0x45046574, 0x8c6f7275, 0x8d3820ec, 0x8d3820ec, 0x8d3820ec, 0x8d3820ec, 0x8d3820ec, 0x8d3820ec, 0x8d3820ec, 0x8d3820ec, 0x8d3820ec, 0x8d3820ec, 0x8d3820ec, 0x8d3820ec, 0x8d3820ec, 0x8d3820ec, 0x413820ec, 0x39200ddc, 0x200ddc41, 0x20ef8d39, 0x20ef8d39, 0x20ef8d39, 0x20ef8d39, 0x20ef8d39, 0x20ef8d39, 0x20ef8d39, 0x20ef8d39, 0x20ef8d39, 0x20ef8d39, 0x20ef8d39, 0x20ef8d39, 0x20ef8d39, 0x23ef8d39, 0x00006639, 0xa947fa05, 0x0000f26b, };
143.909091
148
0.805233
perefm
0d6fbe13958ea917914dd9f36a99095bedced173
25,912
cpp
C++
QTDialogs/ResultsAnalyzerTab/ResultsAnalyzerTab.cpp
msolids/musen
67d9a70d03d771ccda649c21b78d165684e31171
[ "BSD-3-Clause" ]
19
2020-09-28T07:22:50.000Z
2022-03-07T09:52:20.000Z
QTDialogs/ResultsAnalyzerTab/ResultsAnalyzerTab.cpp
LasCondes/musen
18961807928285ff802e050050f4c627dd7bec1e
[ "BSD-3-Clause" ]
5
2020-12-26T18:18:27.000Z
2022-02-23T22:56:43.000Z
QTDialogs/ResultsAnalyzerTab/ResultsAnalyzerTab.cpp
LasCondes/musen
18961807928285ff802e050050f4c627dd7bec1e
[ "BSD-3-Clause" ]
11
2020-11-02T11:32:03.000Z
2022-01-27T08:22:04.000Z
/* Copyright (c) 2013-2020, MUSEN Development Team. All rights reserved. This file is part of MUSEN framework http://msolids.net/musen. See LICENSE file for license and warranty information. */ #include "ResultsAnalyzerTab.h" #include "qtOperations.h" #include <QMessageBox> #include <QFileDialog> CAnalyzerThread::CAnalyzerThread(CResultsAnalyzer *_pAnalyzer, QObject *parent /*= 0*/) : QObject(parent) { m_pAnalyzer = _pAnalyzer; connect(&m_Thread, SIGNAL(started()), this, SLOT(StartAnalyzing())); } CAnalyzerThread::~CAnalyzerThread() { m_Thread.quit(); m_Thread.wait(); } void CAnalyzerThread::Run(const QString& _sFileName) { m_sFileName = _sFileName; this->moveToThread(&m_Thread); m_Thread.start(); } void CAnalyzerThread::Stop() { m_Thread.exit(); } void CAnalyzerThread::StopAnalyzing() { m_pAnalyzer->SetCurrentStatus(CResultsAnalyzer::EStatus::ShouldBeStopped); } void CAnalyzerThread::StartAnalyzing() { m_pAnalyzer->StartExport(m_sFileName.toStdString()); emit Finished(); } CResultsAnalyzerTab::CResultsAnalyzerTab(QWidget *parent) : CMusenDialog(parent) { ui.setupUi(this); m_pAnalyzer = nullptr; m_bAvoidSignal = false; m_pConstraintsEditorTab = new CConstraintsEditorTab(ui.tabWidget); m_pAnalyzerThread = nullptr; m_vTypesForTypeActive = { CResultsAnalyzer::EPropertyType::BondForce, CResultsAnalyzer::EPropertyType::BondNumber, CResultsAnalyzer::EPropertyType::Coordinate, CResultsAnalyzer::EPropertyType::CoordinationNumber, CResultsAnalyzer::EPropertyType::Deformation, CResultsAnalyzer::EPropertyType::Diameter, CResultsAnalyzer::EPropertyType::Distance, CResultsAnalyzer::EPropertyType::Duration, CResultsAnalyzer::EPropertyType::Energy, CResultsAnalyzer::EPropertyType::ForceNormal, CResultsAnalyzer::EPropertyType::ForceTangential, CResultsAnalyzer::EPropertyType::ForceTotal, CResultsAnalyzer::EPropertyType::KineticEnergy, CResultsAnalyzer::EPropertyType::Length, CResultsAnalyzer::EPropertyType::MaxOverlap, CResultsAnalyzer::EPropertyType::Orientation, CResultsAnalyzer::EPropertyType::PartNumber, CResultsAnalyzer::EPropertyType::PotentialEnergy, CResultsAnalyzer::EPropertyType::ResidenceTime, CResultsAnalyzer::EPropertyType::Strain, CResultsAnalyzer::EPropertyType::VelocityNormal, CResultsAnalyzer::EPropertyType::VelocityRotational, CResultsAnalyzer::EPropertyType::VelocityTangential, CResultsAnalyzer::EPropertyType::VelocityTotal, CResultsAnalyzer::EPropertyType::Stress, CResultsAnalyzer::EPropertyType::Temperature }; m_vTypesForDistanceActive = { CResultsAnalyzer::EPropertyType::Distance }; m_vTypesForComponentActive = { CResultsAnalyzer::EPropertyType::Coordinate, CResultsAnalyzer::EPropertyType::Distance, CResultsAnalyzer::EPropertyType::ForceNormal, CResultsAnalyzer::EPropertyType::ForceTangential, CResultsAnalyzer::EPropertyType::ForceTotal, CResultsAnalyzer::EPropertyType::VelocityNormal, CResultsAnalyzer::EPropertyType::VelocityRotational, CResultsAnalyzer::EPropertyType::VelocityTangential, CResultsAnalyzer::EPropertyType::VelocityTotal, CResultsAnalyzer::EPropertyType::Orientation, CResultsAnalyzer::EPropertyType::Stress }; m_vTypesForDistrParamsActive = { CResultsAnalyzer::EPropertyType::ResidenceTime }; resize(minimumSizeHint()); InitializeConnections(); } void CResultsAnalyzerTab::Initialize() { SetResultsTypeVisible(false); SetDistanceVisible(false); SetComponentVisible(false); SetCollisionsVisible(false); SetGeometryVisible(false); SetConstraintsVisible(false); SetConstraintMaterialsVisible(false); SetConstraintMaterials2Visible(false); SetConstraintVolumesVisible(false); SetConstraintGeometriesVisible(false); SetConstraintDiametersVisible(false); SetConstraintDiameters2Visible(false); InitializeAnalyzerTab(); } CResultsAnalyzerTab::~CResultsAnalyzerTab() { } void CResultsAnalyzerTab::SetPointers(CSystemStructure* _pSystemStructure, CUnitConvertor* _pUnitConvertor, CMaterialsDatabase* _pMaterialsDB, CGeometriesDatabase* _pGeometriesDB, CAgglomeratesDatabase* _pAgglomDB) { CMusenDialog::SetPointers(_pSystemStructure, _pUnitConvertor, _pMaterialsDB, _pGeometriesDB, _pAgglomDB); m_pAnalyzer->SetSystemStructure(_pSystemStructure); m_pAnalyzer->GetConstraintsPtr()->SetPointers(_pSystemStructure, _pMaterialsDB); m_pConstraintsEditorTab->SetPointers(_pSystemStructure, _pUnitConvertor, _pMaterialsDB, _pGeometriesDB, _pAgglomDB); m_pConstraintsEditorTab->SetConstraintsPtr(m_pAnalyzer->GetConstraintsPtr()); } void CResultsAnalyzerTab::UpdateSettings() { m_pAnalyzer->UpdateSettings(); m_pConstraintsEditorTab->UpdateSettings(); } void CResultsAnalyzerTab::InitializeConnections() const { // connect ComboBoxProperty connect(ui.listProperty, &QListWidget::currentRowChanged, this, &CResultsAnalyzerTab::NewPropertySelected); // buttons connect(ui.pushButtonCancel, SIGNAL(clicked()), this, SLOT(reject())); connect(ui.pushButtonExport, SIGNAL(clicked()), this, SLOT(ExportDataPressed())); // results type connect(ui.radioButtonDistribution, &QRadioButton::clicked, this, &CResultsAnalyzerTab::NewResultsTypeSelected); connect(ui.radioButtonAverage, &QRadioButton::clicked, this, &CResultsAnalyzerTab::NewResultsTypeSelected); connect(ui.radioButtonMaximum, &QRadioButton::clicked, this, &CResultsAnalyzerTab::NewResultsTypeSelected); connect(ui.radioButtonMinimum, &QRadioButton::clicked, this, &CResultsAnalyzerTab::NewResultsTypeSelected); connect(ui.lineEditDistrMin, &QLineEdit::editingFinished, this, &CResultsAnalyzerTab::NewDistrParamSet); connect(ui.lineEditDistrMax, &QLineEdit::editingFinished, this, &CResultsAnalyzerTab::NewDistrParamSet); connect(ui.lineEditDistrNClasses, &QLineEdit::editingFinished, this, &CResultsAnalyzerTab::NewDistrParamSet); // distance connect(ui.radioButtonToPoint, SIGNAL(clicked(bool)), this, SLOT(NewDistanceTypeSelected(bool))); connect(ui.radioButtonToLine, SIGNAL(clicked(bool)), this, SLOT(NewDistanceTypeSelected(bool))); connect(ui.lineEditX1, &QLineEdit::editingFinished, this, &CResultsAnalyzerTab::NewDataPointsSet); connect(ui.lineEditY1, &QLineEdit::editingFinished, this, &CResultsAnalyzerTab::NewDataPointsSet); connect(ui.lineEditZ1, &QLineEdit::editingFinished, this, &CResultsAnalyzerTab::NewDataPointsSet); connect(ui.lineEditX2, &QLineEdit::editingFinished, this, &CResultsAnalyzerTab::NewDataPointsSet); connect(ui.lineEditY2, &QLineEdit::editingFinished, this, &CResultsAnalyzerTab::NewDataPointsSet); connect(ui.lineEditZ2, &QLineEdit::editingFinished, this, &CResultsAnalyzerTab::NewDataPointsSet); // components connect(ui.radioButtonTotal, SIGNAL(clicked(bool)), this, SLOT(NewComponentSelected(bool))); connect(ui.radioButtonX, SIGNAL(clicked(bool)), this, SLOT(NewComponentSelected(bool))); connect(ui.radioButtonY, SIGNAL(clicked(bool)), this, SLOT(NewComponentSelected(bool))); connect(ui.radioButtonZ, SIGNAL(clicked(bool)), this, SLOT(NewComponentSelected(bool))); // relation connect(ui.radioButtonNumberRelated, SIGNAL(clicked(bool)), this, SLOT(NewRelationSelected(bool))); connect(ui.radioButtonFrequencyRelated, SIGNAL(clicked(bool)), this, SLOT(NewRelationSelected(bool))); // collisions type connect(ui.radioButtonPP, SIGNAL(clicked(bool)), this, SLOT(NewCollisionsTypeSelected(bool))); connect(ui.radioButtonPW, SIGNAL(clicked(bool)), this, SLOT(NewCollisionsTypeSelected(bool))); // geometry connect(ui.comboBoxGeometry, SIGNAL(currentIndexChanged(int)), this, SLOT(NewGeometrySelected(int))); // time data connect(ui.lineEditTimeFrom, &QLineEdit::editingFinished, this, &CResultsAnalyzerTab::NewTimeSet); connect(ui.lineEditTimeTo, &QLineEdit::editingFinished, this, &CResultsAnalyzerTab::NewTimeSet); connect(ui.lineEditTimeStep, &QLineEdit::editingFinished, this, &CResultsAnalyzerTab::NewTimeSet); connect(ui.radioButtonTimeSaved, &QRadioButton::clicked, this, &CResultsAnalyzerTab::NewTimeSet); connect(ui.radioButtonTimeStep, &QRadioButton::clicked, this, &CResultsAnalyzerTab::NewTimeSet); // constraints dialog connect(m_pConstraintsEditorTab, SIGNAL(finished(int)), this, SLOT(CloseDialog(int))); // timers connect(&m_UpdateTimer, SIGNAL(timeout()), this, SLOT(UpdateExportStatistics())); } void CResultsAnalyzerTab::SetResultsTypeVisible(bool _bVisible) { ui.groupBoxResultsType->setVisible(_bVisible); } void CResultsAnalyzerTab::SetDistanceVisible(bool _bVisible) { ui.groupBoxDistance->setVisible(_bVisible); } void CResultsAnalyzerTab::SetComponentVisible(bool _bVisible) { ui.frameComponent->setVisible(_bVisible); } void CResultsAnalyzerTab::SetCollisionsVisible(bool _bVisible) { ui.frameCollisions->setVisible(_bVisible); } void CResultsAnalyzerTab::SetGeometryVisible(bool _bVisible) { ui.frameGeometries->setVisible(_bVisible); } void CResultsAnalyzerTab::SetPoint2Visible(bool _bVisible) { ui.labelP2->setVisible(_bVisible); ui.lineEditX2->setVisible(_bVisible); ui.lineEditY2->setVisible(_bVisible); ui.lineEditZ2->setVisible(_bVisible); } void CResultsAnalyzerTab::SetConstraintsVisible(bool _bVisible) { if (!_bVisible) ui.tabWidget->removeTab(1); else { ui.tabWidget->addTab(m_pConstraintsEditorTab, "Constraints"); m_pConstraintsEditorTab->resize(m_pConstraintsEditorTab->minimumSizeHint()); } } void CResultsAnalyzerTab::SetConstraintMaterialsVisible(bool _bVisible) { m_pConstraintsEditorTab->SetMaterialsVisible(_bVisible); } void CResultsAnalyzerTab::SetConstraintMaterials2Visible(bool _bVisible) { m_pConstraintsEditorTab->SetMaterials2Visible(_bVisible); } void CResultsAnalyzerTab::SetConstraintVolumesVisible(bool _bVisible) { m_pConstraintsEditorTab->SetVolumesVisible(_bVisible); } void CResultsAnalyzerTab::SetConstraintGeometriesVisible(bool _bVisible) { m_pConstraintsEditorTab->SetGeometriesVisible(_bVisible); } void CResultsAnalyzerTab::SetConstraintDiametersVisible(bool _bVisible) { m_pConstraintsEditorTab->SetDiametersVisible(_bVisible); } void CResultsAnalyzerTab::SetConstraintDiameters2Visible(bool _bVisible) { m_pConstraintsEditorTab->SetDiameters2Visible(_bVisible); } void CResultsAnalyzerTab::UpdateSelectedProperty() { if (ui.groupBoxProperty->isHidden()) return; m_bAvoidSignal = true; UpdateSelectedResultsType(); UpdateResultsTypeActivity(); UpdateDistance(); UpdateDistanceVisibility(); UpdateComponentActivity(); UpdateTime(); UpdateDistrParams(); UpdateDistrParamsActivity(); m_bAvoidSignal = false; } void CResultsAnalyzerTab::UpdateSelectedResultsType() { if (ui.groupBoxResultsType->isHidden()) return; m_bAvoidSignal = true; switch (m_pAnalyzer->m_nResultsType) { case CResultsAnalyzer::EResultType::Distribution: ui.radioButtonDistribution->setChecked(true); break; case CResultsAnalyzer::EResultType::Average: ui.radioButtonAverage->setChecked(true); break; case CResultsAnalyzer::EResultType::Maximum: ui.radioButtonMaximum->setChecked(true); break; case CResultsAnalyzer::EResultType::Minimum: ui.radioButtonMinimum->setChecked(true); break; default: break; } UpdateDistrParamsActivity(); m_bAvoidSignal = false; } void CResultsAnalyzerTab::UpdateSelectedDistance() { if (ui.groupBoxDistance->isHidden()) return; m_bAvoidSignal = true; if (m_pAnalyzer->m_nDistance == CResultsAnalyzer::EDistanceType::ToPoint) ui.radioButtonToPoint->setChecked(true); else ui.radioButtonToLine->setChecked(true); SetPoint2Visible(m_pAnalyzer->m_nDistance == CResultsAnalyzer::EDistanceType::ToLine); m_bAvoidSignal = false; } void CResultsAnalyzerTab::UpdateSelectedComponent() { if (ui.frameComponent->isHidden()) return; m_bAvoidSignal = true; if (m_pAnalyzer->m_nComponent== CResultsAnalyzer::EVectorComponent::Total) ui.radioButtonTotal->setChecked(true); else if (m_pAnalyzer->m_nComponent == CResultsAnalyzer::EVectorComponent::X) ui.radioButtonX->setChecked(true); else if (m_pAnalyzer->m_nComponent == CResultsAnalyzer::EVectorComponent::Y) ui.radioButtonY->setChecked(true); else if (m_pAnalyzer->m_nComponent == CResultsAnalyzer::EVectorComponent::Z) ui.radioButtonZ->setChecked(true); m_bAvoidSignal = false; } void CResultsAnalyzerTab::UpdateSelectedRelation() { if (ui.frameCollisions->isHidden()) return; m_bAvoidSignal = true; if (m_pAnalyzer->m_nRelation== CResultsAnalyzer::ERelationType::Existing) ui.radioButtonNumberRelated->setChecked(true); else if (m_pAnalyzer->m_nRelation == CResultsAnalyzer::ERelationType::Appeared) ui.radioButtonFrequencyRelated->setChecked(true); m_bAvoidSignal = false; } void CResultsAnalyzerTab::UpdateSelectedCollisionsType() { if (ui.frameCollisions->isHidden()) return; m_bAvoidSignal = true; if (m_pAnalyzer->m_nCollisionType == CResultsAnalyzer::ECollisionType::ParticleParticle) { ui.radioButtonPP->setChecked(true); SetConstraintGeometriesVisible(false); SetConstraintMaterials2Visible(true); SetConstraintDiameters2Visible(true); } else if (m_pAnalyzer->m_nCollisionType == CResultsAnalyzer::ECollisionType::ParticleWall) { ui.radioButtonPW->setChecked(true); SetConstraintGeometriesVisible(true); SetConstraintMaterials2Visible(false); SetConstraintDiameters2Visible(false); } m_bAvoidSignal = false; } void CResultsAnalyzerTab::UpdateSelectedGeometry() { if (ui.frameGeometries->isHidden()) return; m_bAvoidSignal = true; ui.comboBoxGeometry->setCurrentIndex(static_cast<int>(m_pAnalyzer->m_nGeometryIndex)); m_bAvoidSignal = false; } void CResultsAnalyzerTab::UpdateDistance() { if (ui.groupBoxDistance->isHidden()) return; m_bAvoidSignal = true; ui.lineEditX1->setText(QString::number(m_pAnalyzer->m_Point1.x)); ui.lineEditY1->setText(QString::number(m_pAnalyzer->m_Point1.y)); ui.lineEditZ1->setText(QString::number(m_pAnalyzer->m_Point1.z)); ui.lineEditX2->setText(QString::number(m_pAnalyzer->m_Point2.x)); ui.lineEditY2->setText(QString::number(m_pAnalyzer->m_Point2.y)); ui.lineEditZ2->setText(QString::number(m_pAnalyzer->m_Point2.z)); SetPoint2Visible(m_pAnalyzer->m_nDistance == CResultsAnalyzer::EDistanceType::ToLine); m_bAvoidSignal = false; } void CResultsAnalyzerTab::UpdateTime() { m_bAvoidSignal = true; ui.lineEditTimeFrom->setText(QString::number(m_pAnalyzer->m_dTimeMin)); ui.lineEditTimeTo->setText(QString::number(m_pAnalyzer->m_dTimeMax)); if (m_pAnalyzer->m_bOnlySavedTP) ui.radioButtonTimeSaved->setChecked(true); else { ui.radioButtonTimeStep->setChecked(true); ui.lineEditTimeStep->setText(QString::number(m_pAnalyzer->m_dTimeStep)); } UpdateTimeParams(); m_bAvoidSignal = false; } void CResultsAnalyzerTab::UpdateDistrParams() { m_bAvoidSignal = true; ui.lineEditDistrMin->setText(QString::number(m_pAnalyzer->m_dPropMin)); ui.lineEditDistrMax->setText(QString::number(m_pAnalyzer->m_dPropMax)); ui.lineEditDistrNClasses->setText(QString::number(m_pAnalyzer->m_nPropSteps)); m_bAvoidSignal = false; } void CResultsAnalyzerTab::UpdateConstraints() { m_bAvoidSignal = true; if (ui.tabWidget->count() == 2) m_pConstraintsEditorTab->UpdateWholeView(); m_bAvoidSignal = false; } void CResultsAnalyzerTab::UpdateResultsTypeActivity() { if (ui.groupBoxResultsType->isHidden()) return; bool bActiveAll = std::find(m_vTypesForTypeActive.begin(), m_vTypesForTypeActive.end(), m_pAnalyzer->GetProperty()) != m_vTypesForTypeActive.end(); bool bActiveParam = std::find(m_vTypesForDistrParamsActive.begin(), m_vTypesForDistrParamsActive.end(), m_pAnalyzer->GetProperty()) != m_vTypesForDistrParamsActive.end(); ui.groupBoxResultsType->setEnabled(bActiveParam || bActiveAll); ui.radioButtonAverage->setEnabled(!bActiveParam); ui.radioButtonMaximum->setEnabled(!bActiveParam); ui.radioButtonMinimum->setEnabled(!bActiveParam); if (bActiveParam) ui.radioButtonDistribution->setChecked(true); else UpdateSelectedResultsType(); } void CResultsAnalyzerTab::UpdateDistanceVisibility() { bool bVisible = std::find(m_vTypesForDistanceActive.begin(), m_vTypesForDistanceActive.end(), m_pAnalyzer->GetProperty()) != m_vTypesForDistanceActive.end(); ui.groupBoxDistance->setVisible(bVisible); } void CResultsAnalyzerTab::UpdateComponentActivity() { if (ui.frameComponent->isHidden()) return; CResultsAnalyzer::EPropertyType p = m_pAnalyzer->GetProperty(); bool bActive = std::find(m_vTypesForComponentActive.begin(), m_vTypesForComponentActive.end(), p) != m_vTypesForComponentActive.end(); bool bNotActive = (ui.groupBoxDistance->isVisible() && p == CResultsAnalyzer::EPropertyType::Distance && m_pAnalyzer->m_nDistance == CResultsAnalyzer::EDistanceType::ToLine); ui.frameComponent->setEnabled(bActive && !bNotActive); } void CResultsAnalyzerTab::UpdateDistrParamsActivity() { CResultsAnalyzer::EPropertyType p = m_pAnalyzer->GetProperty(); bool bActive = std::find(m_vTypesForDistrParamsActive.begin(), m_vTypesForDistrParamsActive.end(), p) != m_vTypesForDistrParamsActive.end(); SetDistrParamsActive(bActive || (m_pAnalyzer->m_nResultsType == CResultsAnalyzer::EResultType::Distribution)); } void CResultsAnalyzerTab::UpdateTimeParams() { m_bAvoidSignal = true; if (m_pAnalyzer->m_nRelation == CResultsAnalyzer::ERelationType::Existing) // time points are analyzed ui.lineEditTimePoints->setText(QString::number(m_pAnalyzer->m_vTimePoints.size())); else // intervals are analyzed ui.lineEditTimePoints->setText(QString::number(m_pAnalyzer->m_vTimePoints.size() - 1)); ui.lineEditTimeStep->setEnabled(!m_pAnalyzer->m_bOnlySavedTP); m_bAvoidSignal = false; } void CResultsAnalyzerTab::SetWindowTitle(const QString& _sTitle) { this->setWindowTitle(_sTitle); } void CResultsAnalyzerTab::SetupGeometryCombo() { m_bAvoidSignal = true; ui.comboBoxGeometry->clear(); for (unsigned i = 0; i < m_pSystemStructure->GeometriesNumber(); ++i) ui.comboBoxGeometry->insertItem(i, QString::fromStdString(m_pSystemStructure->Geometry(i)->Name())); if (m_pSystemStructure->GeometriesNumber() > 0) ui.comboBoxGeometry->setCurrentIndex(0); m_bAvoidSignal = false; } void CResultsAnalyzerTab::SetStatusText(const QString& _sText) { ui.statusLabel->setText(_sText); } void CResultsAnalyzerTab::SetComponentActive(bool _bActive) { ui.frameComponent->setEnabled(_bActive); } void CResultsAnalyzerTab::SetDistrParamsActive(bool _bActive) { ui.frameDistrParams->setEnabled(_bActive); } void CResultsAnalyzerTab::UpdateWholeView() { UpdateSelectedProperty(); UpdateSelectedDistance(); UpdateSelectedComponent(); UpdateSelectedRelation(); UpdateSelectedGeometry(); UpdateDistance(); UpdateTime(); UpdateDistrParams(); UpdateDistanceVisibility(); UpdateComponentActivity(); UpdateConstraints(); } void CResultsAnalyzerTab::ExportDataPressed() { if (m_pAnalyzer->GetCurrentStatus() == CResultsAnalyzer::EStatus::Idle) { if (ui.listProperty->selectedItems().size() > 1) { CResultsAnalyzer::VPropertyType propertyTypes; for (const auto& iProperty : ui.listProperty->selectedItems()) propertyTypes.push_back(static_cast<CResultsAnalyzer::EPropertyType>(iProperty->data(Qt::UserRole).toUInt())); m_pAnalyzer->SetPropertyType(propertyTypes); } ExportData(); } else if (m_pAnalyzer->GetCurrentStatus() == CResultsAnalyzer::EStatus::Runned) if (m_pAnalyzerThread) m_pAnalyzerThread->StopAnalyzing(); } void CResultsAnalyzerTab::ExportData() { QString sFileName = QFileDialog::getSaveFileName(this, tr("Export data"), QString::fromStdString(m_pSystemStructure->GetFileName()) + ".csv", tr("Text files (*.csv);;All files (*.*);; Dat files(*.dat);;")); if (sFileName.isEmpty()) { SetStatusText(""); return; } if (!IsFileWritable(sFileName)) { QMessageBox::warning(this, "Writing error", "Unable to write - selected file is not writable"); SetStatusText(""); return; } SetStatusText("Exporting started. Please wait..."); ui.progressBarExporting->setValue(0); m_pConstraintsEditorTab->SetWidgetsEnabled(false); ui.framePropertiesTab->setEnabled(false); ui.pushButtonCancel->setEnabled(false); ui.pushButtonExport->setText("Stop"); emit DisableOpenGLView(); m_pAnalyzerThread = new CAnalyzerThread(m_pAnalyzer); connect(m_pAnalyzerThread, SIGNAL(Finished()), this, SLOT(ExportFinished())); m_pAnalyzerThread->Run(sFileName); m_UpdateTimer.start(100); } void CResultsAnalyzerTab::NewPropertySelected(int n_Row) { if (m_bAvoidSignal) return; unsigned propertyId = ui.listProperty->item(n_Row)->data(Qt::UserRole).toUInt(); m_pAnalyzer->SetPropertyType(static_cast<CResultsAnalyzer::EPropertyType>(propertyId)); UpdateResultsTypeActivity(); UpdateDistrParamsActivity(); UpdateDistanceVisibility(); UpdateComponentActivity(); } void CResultsAnalyzerTab::SetMultiplePropertySelection(bool _allow) const { ui.listProperty->setMaximumHeight(ui.listProperty->sizeHintForRow(0) * 6 + 2 * ui.listProperty->frameWidth()); if (!_allow) ui.listProperty->setSelectionMode(QAbstractItemView::SingleSelection); } void CResultsAnalyzerTab::AddAnalysisProperty(CResultsAnalyzer::EPropertyType _property, const QString& _rowNameComboBox, const QString& _sToolTip) { ui.listProperty->addItem(_rowNameComboBox); ui.listProperty->item(ui.listProperty->count() - 1)->setData(Qt::UserRole, E2I(_property)); ui.listProperty->item(ui.listProperty->count() - 1)->setToolTip(_sToolTip); } void CResultsAnalyzerTab::NewResultsTypeSelected(bool _bChecked) { if (!_bChecked) return; if (m_bAvoidSignal) return; if (ui.radioButtonDistribution->isChecked()) m_pAnalyzer->SetResultsType(CResultsAnalyzer::EResultType::Distribution); else if (ui.radioButtonAverage->isChecked()) m_pAnalyzer->SetResultsType(CResultsAnalyzer::EResultType::Average); else if (ui.radioButtonMaximum->isChecked()) m_pAnalyzer->SetResultsType(CResultsAnalyzer::EResultType::Maximum); else if (ui.radioButtonMinimum->isChecked()) m_pAnalyzer->SetResultsType(CResultsAnalyzer::EResultType::Minimum); UpdateDistrParamsActivity(); } void CResultsAnalyzerTab::NewDistanceTypeSelected(bool _bChecked) { if (!_bChecked) return; if (m_bAvoidSignal) return; if (ui.radioButtonToPoint->isChecked()) m_pAnalyzer->SetDistanceType(CResultsAnalyzer::EDistanceType::ToPoint); else m_pAnalyzer->SetDistanceType(CResultsAnalyzer::EDistanceType::ToLine); SetPoint2Visible(ui.radioButtonToLine->isChecked()); UpdateComponentActivity(); } void CResultsAnalyzerTab::NewComponentSelected(bool _bChecked) { if (!_bChecked) return; if (m_bAvoidSignal) return; if (ui.radioButtonTotal->isChecked()) m_pAnalyzer->SetVectorComponent(CResultsAnalyzer::EVectorComponent::Total); else if (ui.radioButtonX->isChecked()) m_pAnalyzer->SetVectorComponent(CResultsAnalyzer::EVectorComponent::X); else if (ui.radioButtonY->isChecked()) m_pAnalyzer->SetVectorComponent(CResultsAnalyzer::EVectorComponent::Y); else if (ui.radioButtonZ->isChecked()) m_pAnalyzer->SetVectorComponent(CResultsAnalyzer::EVectorComponent::Z); } void CResultsAnalyzerTab::NewRelationSelected(bool _bChecked) { if (!_bChecked) return; if (m_bAvoidSignal) return; if (ui.radioButtonNumberRelated->isChecked()) m_pAnalyzer->SetRelatonType(CResultsAnalyzer::ERelationType::Existing); else if (ui.radioButtonFrequencyRelated->isChecked()) m_pAnalyzer->SetRelatonType(CResultsAnalyzer::ERelationType::Appeared); UpdateTimeParams(); } void CResultsAnalyzerTab::NewCollisionsTypeSelected(bool _bChecked) { if (!_bChecked) return; if (m_bAvoidSignal) return; if (ui.radioButtonPP->isChecked()) m_pAnalyzer->SetCollisionType(CResultsAnalyzer::ECollisionType::ParticleParticle); else if (ui.radioButtonPW->isChecked()) m_pAnalyzer->SetCollisionType(CResultsAnalyzer::ECollisionType::ParticleWall); UpdateSelectedCollisionsType(); } void CResultsAnalyzerTab::NewGeometrySelected(int _nIndex) { if (_nIndex < 0) return; if (m_bAvoidSignal) return; m_pAnalyzer->SetGeometryIndex(_nIndex); } void CResultsAnalyzerTab::NewDataPointsSet() { if (m_bAvoidSignal) return; m_pAnalyzer->SetPoint1(CVector3(ui.lineEditX1->text().toDouble(), ui.lineEditY1->text().toDouble(), ui.lineEditZ1->text().toDouble())); m_pAnalyzer->SetPoint2(CVector3(ui.lineEditX2->text().toDouble(), ui.lineEditY2->text().toDouble(), ui.lineEditZ2->text().toDouble())); } void CResultsAnalyzerTab::NewTimeSet() { if (m_bAvoidSignal) return; m_bAvoidSignal = true; double dMin = ui.lineEditTimeFrom->text().toDouble(); double dMax = ui.lineEditTimeTo->text().toDouble(); double dStep = ui.lineEditTimeStep->text().toDouble(); bool bSaved = ui.radioButtonTimeSaved->isChecked(); m_pAnalyzer->SetTime(dMin, dMax, dStep, bSaved); UpdateTimeParams(); m_bAvoidSignal = false; } void CResultsAnalyzerTab::NewDistrParamSet() { if (m_bAvoidSignal) return; double dMin = ui.lineEditDistrMin->text().toDouble(); double dMax = ui.lineEditDistrMax->text().toDouble(); unsigned nSteps = ui.lineEditDistrNClasses->text().toUInt(); m_pAnalyzer->SetProperty(dMin, dMax, nSteps); } void CResultsAnalyzerTab::setVisible(bool _bVisible) { QDialog::setVisible(_bVisible); if (_bVisible) { UpdateWholeView(); if (m_size.isEmpty()) { adjustSize(); m_size = size(); } } } void CResultsAnalyzerTab::CloseDialog(int _nResult) { QDialog::done(_nResult); } void CResultsAnalyzerTab::UpdateExportStatistics() { int nProgress = (int)m_pAnalyzer->GetExportProgress(); ui.progressBarExporting->setValue(nProgress); SetStatusText(ss2qs(m_pAnalyzer->GetStatusDescription())); } void CResultsAnalyzerTab::ExportFinished() { m_UpdateTimer.stop(); m_pAnalyzerThread->Stop(); delete m_pAnalyzerThread; m_pAnalyzerThread = nullptr; ui.progressBarExporting->setValue(100); if (!m_pAnalyzer->IsError()) SetStatusText("Export finished."); else SetStatusText("Export failed: " + ss2qs(m_pAnalyzer->GetStatusDescription())); m_pConstraintsEditorTab->SetWidgetsEnabled(true); ui.framePropertiesTab->setEnabled(true); ui.pushButtonCancel->setEnabled(true); ui.pushButtonExport->setText("Export"); emit EnableOpenGLView(); }
35.790055
214
0.793339
msolids
0d710ac67539bcd4976b0e80fbb224a418b64377
10,383
hpp
C++
MyBot/discord_profile_filesystem.hpp
Sijumah/Sijdiscbot
c58433b1bcaacc17ee17637c2daa6ce07d6d4120
[ "Apache-2.0" ]
null
null
null
MyBot/discord_profile_filesystem.hpp
Sijumah/Sijdiscbot
c58433b1bcaacc17ee17637c2daa6ce07d6d4120
[ "Apache-2.0" ]
null
null
null
MyBot/discord_profile_filesystem.hpp
Sijumah/Sijdiscbot
c58433b1bcaacc17ee17637c2daa6ce07d6d4120
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Sijf.hpp" #include <string.h> #include <string> #include <deque> #include <tuple> #include <array> #include<vector> #include <optional> namespace Sijdisc { struct gameprofile { std::string game_name; std::deque<std::pair<std::string,double>> game_stats; //A deque of for instance, "Total Soldiers Placed","300.0". This is retrieved by reading and saving to files. std::deque<std::pair<std::string,std::string>> achievements; //Achievements on a game-per-game basis ie... "Aggressive!","Place 500 soldiers". gameprofile(const std::string& supgame_name, const std::deque<std::pair<std::string, double>>& supgame_stats = {}, const std::deque<std::pair<std::string, std::string>>& supachievments = {}) : game_name(supgame_name), game_stats(supgame_stats), achievements(supachievments) {} bool has_achievement_by_name(const std::string& searched_achievment) { for (auto&& it : achievements) { if (it.first == searched_achievment) { return true; } }return false; } std::optional<std::pair<std::string, double>*> find_stat_by_name(const std::string& supname) { for (auto&& it : game_stats) { if (it.first == supname) { return &it; } }return std::nullopt; } }; struct profile { std::string discord_id; std::string personal_nickname; //prompt for a nickname when creating the profile std::deque<gameprofile> game_ledger; profile(const std::string& supid = {}, const std::string& supnickname = {}, const std::deque<gameprofile>& supprofile = {}) : discord_id(supid), personal_nickname(supnickname), game_ledger(supprofile) {}; std::optional<gameprofile*> find_game_in_ledger(const std::string& game_name) { for (auto&& it : this->game_ledger) { if (it.game_name == game_name) { return &it; } }return std::nullopt; } void add_game_to_ledger(const std::string& game_name, const std::deque<std::pair<std::string, double>>& supgame_stats = {}, const std::deque<std::pair<std::string, std::string>>& supachievments = {}) { if (find_game_in_ledger(game_name)) { return; } //If game already exists, return. game_ledger.emplace_back(game_name,supgame_stats,supachievments); } //Otherwise add it to the list of games with the given achievements and stats. void add_modify_achievement_by_names(const std::string& gamename,const std::pair<std::string,std::string>& supachiev) { auto game = find_game_in_ledger(gamename); if (game) { //If the game was found if (!(* game)->has_achievement_by_name(supachiev.first)) { //If it doesnt already have the achievment, (*game)->achievements.push_back(supachiev); } //Add it. } } void add_modify_stat_by_names(const std::string& gamename,const std::pair<std::string ,double>& supstat) { auto game= find_game_in_ledger(gamename); //Find the game std::optional<std::pair<std::string, double>*> stat; if (game) {stat = (*game)->find_stat_by_name(supstat.first); //IF a game was found, find the stat by name. if (stat) { *stat.value() = supstat; } //If the stat was found, modify it, else { game.value()->game_stats.push_back(supstat); } //else, make a new entry for the stat. } }; }; //End of profile //╣├ struct profile_collection { std::deque<profile> collection; std::string path; //path to the folder where all of the people are stored void add_new_profile(const std::string& discord_id, const std::string& nickname) { this->collection.push_back(profile(discord_id, nickname, std::deque<gameprofile>{})); }; std::optional<profile*> get_profile_by_name(const std::string& supname) { for (auto&& it : this->collection) { if (it.personal_nickname == supname) return &it; } return std::nullopt; }; void add_games_to_profiles_by_name(const std::string& game_name, const Sijc::stl_ish auto& profile_names) { std::optional<profile*> helper; for (auto&& it : profile_names) { helper = get_profile_by_name(it); if (helper) { (*(helper))->add_game_to_ledger(game_name); } } } /* profile and gameprofile text file: personalnickname.txt: name >personal_nick< 12345 >discordid< dune#poker >gamelist< //list of game names separated by #'s soldiers placed#15%spice gained#20>dunestats< //The stats for a specific game in the form of thing#number%nextthing#nextnumber; the title being gamename+stats Agressive!#Play 500 Soldiers%Winner#Win 10 games >duneachievs< //the above except for achievements If I can these >< delimiters will be ╣ ├ */ void write_to_files() { //Oh god this was painful. I should have made it into a class system and so on. I was like "oh, it wont take too long to do manually". Ugh. for (auto&& it : collection) { //For each player, std::vector<std::string> to_write{}; //Less efficient than it could be, but it won't matter for this program. to_write.emplace_back(it.personal_nickname+">personal_nick<\n"+it.discord_id+">discordid<\n"); //Add their personal nickname and discord ids with identifiers to be found later std::string game_list_string{}; for (auto&& gameit : it.game_ledger) { //For each game, of each player: game_list_string += gameit.game_name+"#"; //add the name of the game to the string containing all games ie dune#poker std::string individual_game_stats{}; for (auto&& statsit : gameit.game_stats) { individual_game_stats += statsit.first + "#" + std::to_string(statsit.second) + "%"; } //for the gamestats, which is a container, make a string of the concactenation of the statname and its value ie soldiers placed#10; separate them with % for each new stat if (individual_game_stats.size() != 0) { if (individual_game_stats.back() == '%') { individual_game_stats.pop_back(); } } //remove an erroneous trailing % to_write.emplace_back(individual_game_stats+">" + gameit.game_name + "stats<\n"); //add that thing to the writing table, along with its identifier ie ">dunestats<" std::string individual_game_achievs{}; for (auto&& achievsit : gameit.achievements) { individual_game_achievs += achievsit.first + "#" + achievsit.second + "%"; } //Repeat that process with achievements which are two strings instead of a string and float if (individual_game_achievs.size() != 0) { if (individual_game_achievs.back() == '%') { individual_game_achievs.pop_back(); } } //remove an erroneous trailing % to_write.emplace_back(individual_game_achievs + ">" + gameit.game_name + "achievs<\n"); //Add THAT to the writing table with ">duneachievs<" } if (game_list_string.size() != 0) { if (game_list_string.back() == '#') { game_list_string.pop_back(); } } //remove an erroneous trailing # to_write.emplace_back(game_list_string + ">gamelist<\n"); //add the games list string to the doc such that its dune#poker>gamelist< Sijf::printtofile(to_write,path+"/"+it.personal_nickname+".txt",1); } }; ~profile_collection() { this->write_to_files(); }; profile_collection(const std::string& folder_path, const std::vector<std::string>& names_without_txt) { //it is only folder PATH, that way the constructor can just open the individual text files for the individual players. this->path = folder_path; std::fstream stream; //std::array<std::string, 3> std::vector<std::string> templat{"personal_nick","discordid","gamelist"}; for (auto&& it : names_without_txt) { ///One loop is one name-- one profile, one person, one body in christ everlasting, amen. stream.open(folder_path + "/"+it + ".txt"); std::deque<gameprofile> sup_gameprofiles; auto helper = Sijf::ret_many_file_lines<std::vector<std::string>>(stream, '>', '<',/*'╣', '├',*/ templat,false); //spits out personalnickname discordid gamelist auto gamelistseparated = Sijf::breakstring(helper.at(2), '#'); //separate the gamelist into for instance 'dune','poker' // soldiers placed#15 % spice gained#20 > dunestats< //The stats for a specific game in the form of thing#number%nextthing#nextnumber; the title being gamename+stats // Agressive!#Play 500 Soldiers % Winner#Win 10 games >duneachiev< //the above except for achievements for (auto gameit : gamelistseparated) { //Each of these is a game within each name's txt file auto gamestats = Sijf::retfileline(stream, '>', '<', (gameit + "stats")); ///*'╣', '├',*/ auto broken_game_stats = Sijf::breakstring(*gamestats, '%'); //Breaks into the category: "soldiers placed#15" std::deque<std::pair < std::string, double >> individual_game_stats{}; std::deque<std::pair<std::string, std::string>> individual_game_achievements{}; for (auto&& lesserit : broken_game_stats) { auto fully_broken_stat = Sijf::breakstring(lesserit, '#'); //Breaks into {"soldiers placed", "15"} individual_game_stats.emplace_back(fully_broken_stat.at(0), std::stod(fully_broken_stat.at(1))); }; //creates the pair and the "15" to a double auto gameachievs = Sijf::retfileline(stream, '>', '<',/*'╣', '├',*/ (gameit + "achievs")); auto broken_game_achievs = Sijf::breakstring(*gameachievs, '%'); for (auto&& lesserit : broken_game_achievs) { auto fully_broken_achiev = Sijf::breakstring(lesserit, '#'); //Breaks into {"barbaric!" "win 10 games"} individual_game_achievements.emplace_back(fully_broken_achiev.at(0), fully_broken_achiev.at(1)); } sup_gameprofiles.emplace_back(std::string{ gameit }, individual_game_stats, individual_game_achievements); } // gameprofile(const std::string & supgame_game, const std::deque<std::pair<std::string, double>>&supgame_stats, // const std::deque<std::pair<std::string, std::string>>&supachievments) : collection.emplace_back(helper.at(1),helper.at(0),sup_gameprofiles); stream.close(); } }; }; //End of profile_collection. }; //End of export sijdisc namespace
47.410959
313
0.663103
Sijumah
0d740f2ac7506d22caffb7fe306b683ddcb0402b
21,367
hpp
C++
src/vm/internal/ref_stream_tcp.hpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
14
2020-04-14T17:00:56.000Z
2021-08-30T08:29:26.000Z
src/vm/internal/ref_stream_tcp.hpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
27
2020-12-27T16:00:44.000Z
2021-08-01T13:12:14.000Z
src/vm/internal/ref_stream_tcp.hpp
BastianBlokland/novus
3b984c36855aa84d6746c14ff7e294ab7d9c1575
[ "MIT" ]
1
2020-05-29T18:33:37.000Z
2020-05-29T18:33:37.000Z
#pragma once #include "internal/os_include.hpp" #include "internal/platform_utilities.hpp" #include "internal/ref.hpp" #include "internal/ref_allocator.hpp" #include "internal/ref_string.hpp" #include "internal/settings.hpp" #include "internal/stream_opts.hpp" #include "internal/thread.hpp" #include "intrinsics.hpp" #include <atomic> #include <cstring> namespace vm::internal { #if defined(_WIN32) using SocketHandle = SOCKET; inline auto isSocketValid(SocketHandle s) noexcept { return s != INVALID_SOCKET; } inline auto getInvalidSocket() noexcept -> SocketHandle { return INVALID_SOCKET; } #else // !_WIN32 using SocketHandle = int; inline auto isSocketValid(SocketHandle s) noexcept { return s >= 0; } inline auto getInvalidSocket() noexcept -> SocketHandle { return -1; } #endif // !_WIN32 constexpr int32_t defaultConnectionBacklog = 64; constexpr int32_t receiveTimeoutSeconds = 15; enum class TcpStreamType : uint8_t { Server = 0, // Server cannot be used for sending or receiving but can accept new connections. Connection = 1, // Connections are be used for sending and receiving. }; enum class TcpStreamState : uint8_t { Valid = 0, Failed = 1, Closed = 2, }; enum class IpAddressFamily : uint8_t { IpV4 = 0, IpV6 = 1, }; inline auto isIpFamilyValid(IpAddressFamily family) noexcept { switch (family) { case IpAddressFamily::IpV4: case IpAddressFamily::IpV6: return true; } return false; } inline auto getIpFamilyCode(IpAddressFamily family) noexcept { switch (family) { case IpAddressFamily::IpV4: return AF_INET; case IpAddressFamily::IpV6: return AF_INET6; } return AF_UNSPEC; } inline auto getIpAddressSize(IpAddressFamily family) noexcept -> size_t { switch (family) { case IpAddressFamily::IpV4: return 4u; case IpAddressFamily::IpV6: return 16u; } return 0u; } auto configureSocket(SocketHandle sock) noexcept -> void; auto getTcpPlatformError() noexcept -> PlatformError; // Tcp implementation of the 'stream' interface. // Note: To avoid needing a vtable there is no abstract 'Stream' class but instead there are wrapper // functions that dispatch based on the 'RefKind' (see stream_utilities.hpp). class TcpStreamRef final : public Ref { friend class RefAllocator; public: TcpStreamRef(const TcpStreamRef& rhs) = delete; TcpStreamRef(TcpStreamRef&& rhs) = delete; ~TcpStreamRef() noexcept { // Close the socket if its still open. const bool isClosed = m_state.load(std::memory_order_acquire) == TcpStreamState::Closed; if (isSocketValid(m_socket) && !isClosed) { #if defined(_WIN32) ::closesocket(m_socket); #else // !_WIN32 ::close(m_socket); #endif // !_WIN32 } } auto operator=(const TcpStreamRef& rhs) -> TcpStreamRef& = delete; auto operator=(TcpStreamRef&& rhs) -> TcpStreamRef& = delete; [[nodiscard]] constexpr static auto getKind() { return RefKind::StreamTcp; } [[nodiscard]] auto isValid() noexcept -> bool { return isSocketValid(m_socket) && m_state.load(std::memory_order_acquire) == TcpStreamState::Valid; } auto shutdown() noexcept -> bool { if (m_type == TcpStreamType::Connection) { // Connection sockets we shutdown. #if defined(__APPLE__) return ::shutdown(m_socket, SHUT_RDWR) == 0; #elif defined(_WIN32) // !__APPLE__ return ::shutdown(m_socket, SD_BOTH) == 0; #else // !_WIN32 && !__APPLE__ return ::shutdown(m_socket, SHUT_RDWR) == 0; #endif // !_WIN32 && !__APPLE__ } // For server sockets there is no such thing so we already close the socket. const auto prevState = m_state.exchange(TcpStreamState::Closed, std::memory_order_acq_rel); if (isSocketValid(m_socket) && prevState != TcpStreamState::Closed) { #if defined(_WIN32) return ::closesocket(m_socket) == 0; #else // !_WIN32 return ::close(m_socket) == 0; #endif // !_WIN32 } return false; // Already closed before. } auto readString(ExecutorHandle* execHandle, PlatformError* pErr, StringRef* str) noexcept -> bool { if (unlikely(m_type != TcpStreamType::Connection)) { *pErr = PlatformError::StreamReadNotSupported; str->updateSize(0); return false; } if (unlikely(str->getSize() == 0)) { return true; } execHandle->setState(ExecState::Paused); int bytesRead = -1; while (m_state.load(std::memory_order_acquire) == TcpStreamState::Valid) { bytesRead = ::recv(m_socket, str->getCharDataPtr(), str->getSize(), 0); if (bytesRead >= 0) { break; // No error while reading. } // Retry the send for certain errors. #if defined(_WIN32) const bool shouldRetry = WSAGetLastError() == WSAEINTR; #else // !_WIN32 const bool shouldRetry = errno == EINTR; #endif // !_WIN32 if (!shouldRetry) { break; } threadYield(); // Yield between retries. } execHandle->setState(ExecState::Running); if (execHandle->trap()) { return false; // Aborted. } if (bytesRead < 0) { if (errno == EAGAIN) { *pErr = PlatformError::TcpTimeout; } else { *pErr = getTcpPlatformError(); } str->updateSize(0); m_state.store(TcpStreamState::Failed, std::memory_order_release); return false; } if (bytesRead == 0) { *pErr = PlatformError::StreamNoDataAvailable; str->updateSize(0); return false; } str->updateSize(bytesRead); return true; } auto writeString(ExecutorHandle* execHandle, PlatformError* pErr, StringRef* str) noexcept -> bool { if (unlikely(m_type != TcpStreamType::Connection)) { *pErr = PlatformError::StreamWriteNotSupported; return false; } if (str->getSize() == 0) { return true; } execHandle->setState(ExecState::Paused); int bytesWritten = -1; while (m_state.load(std::memory_order_acquire) == TcpStreamState::Valid) { bytesWritten = ::send(m_socket, str->getCharDataPtr(), str->getSize(), 0); if (bytesWritten >= 0) { break; // No error while writing. } // Retry the send for certain errors. #if defined(_WIN32) const bool shouldRetry = WSAGetLastError() == WSAEINTR; #else // !_WIN32 const bool shouldRetry = errno == EINTR; #endif // !_WIN32 if (!shouldRetry) { break; } threadYield(); // Yield between retries. } execHandle->setState(ExecState::Running); if (execHandle->trap()) { return false; // Aborted. } if (bytesWritten < 0) { *pErr = getTcpPlatformError(); m_state.store(TcpStreamState::Failed, std::memory_order_release); return false; } if (bytesWritten != static_cast<int>(str->getSize())) { *pErr = PlatformError::TcpUnknownError; return false; } return true; } auto setOpts(PlatformError* pErr, StreamOpts /*unused*/) noexcept -> bool { // TODO(bastian): Support non-blocking sockets. *pErr = PlatformError::StreamOptionsNotSupported; return false; } auto unsetOpts(PlatformError* pErr, StreamOpts /*unused*/) noexcept -> bool { // TODO(bastian): Support non-blocking sockets. *pErr = PlatformError::StreamOptionsNotSupported; return false; } auto acceptConnection(ExecutorHandle* execHandle, RefAllocator* alloc, PlatformError* pErr) -> TcpStreamRef* { if (unlikely(m_type != TcpStreamType::Server)) { *pErr = PlatformError::TcpInvalidServerSocket; return alloc->allocPlain<TcpStreamRef>(TcpStreamType::Connection, getInvalidSocket()); } // 'accept' call blocks so we mark ourselves as paused so the gc can trigger in the mean time. execHandle->setState(ExecState::Paused); SocketHandle sock = getInvalidSocket(); while (m_state.load(std::memory_order_acquire) == TcpStreamState::Valid) { // Accept a new connection from the socket. sock = ::accept(m_socket, nullptr, nullptr); if (isSocketValid(sock)) { break; // Valid connection accepted. } // Retry the accept for certain errors. bool shouldRetry = false; #if defined(_WIN32) switch (WSAGetLastError()) { case WSAEINTR: case WSAEWOULDBLOCK: case WSAECONNRESET: shouldRetry = true; break; } #else // !_WIN32 switch (errno) { case EINTR: case EAGAIN: case ECONNABORTED: shouldRetry = true; break; } #endif // !_WIN32 if (!shouldRetry) { break; } threadYield(); // Yield between retries. } // After resuming check if we should wait for gc (or if we are aborted). execHandle->setState(ExecState::Running); if (execHandle->trap()) { return nullptr; // Aborted. } if (!isSocketValid(sock)) { *pErr = getTcpPlatformError(); return alloc->allocPlain<TcpStreamRef>( TcpStreamType::Connection, sock, TcpStreamState::Failed); } configureSocket(sock); return alloc->allocPlain<TcpStreamRef>(TcpStreamType::Connection, sock); } private: TcpStreamType m_type; std::atomic<TcpStreamState> m_state; SocketHandle m_socket; inline explicit TcpStreamRef(TcpStreamType type, SocketHandle sock) noexcept : Ref{getKind()}, m_type{type}, m_state{TcpStreamState::Valid}, m_socket{sock} {} inline TcpStreamRef(TcpStreamType type, SocketHandle sock, TcpStreamState state) noexcept : Ref{getKind()}, m_type{type}, m_state{state}, m_socket{sock} {} }; inline auto configureSocket(SocketHandle sock) noexcept -> void { // Allow reusing the address, allows stopping and restarting the server without waiting for the // socket's wait-time to expire. int optVal = 1; ::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&optVal), sizeof(int)); // Configure the receive timeout; #if defined(_WIN32) int timeout = receiveTimeoutSeconds * 1'000; ::setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<char*>(&timeout), sizeof(timeout)); #else // !_WIN32 auto timeout = timeval{}; timeout.tv_sec = receiveTimeoutSeconds; timeout.tv_usec = 0; ::setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<char*>(&timeout), sizeof(timeout)); #endif // !_WIN32 } inline auto tcpOpenConnection( const Settings* settings, ExecutorHandle* execHandle, RefAllocator* alloc, PlatformError* pErr, StringRef* address, IpAddressFamily family, int32_t port) noexcept -> TcpStreamRef* { if (!settings->socketsEnabled) { *pErr = PlatformError::FeatureNetworkNotEnabled; return alloc->allocPlain<TcpStreamRef>(TcpStreamType::Connection, getInvalidSocket()); } if (port < 0 || port > std::numeric_limits<uint16_t>::max()) { *pErr = PlatformError::TcpInvalidPort; return alloc->allocPlain<TcpStreamRef>(TcpStreamType::Connection, getInvalidSocket()); } if (!isIpFamilyValid(family)) { *pErr = PlatformError::TcpInvalidAddressFamily; return alloc->allocPlain<TcpStreamRef>(TcpStreamType::Connection, getInvalidSocket()); } if (address->getSize() != getIpAddressSize(family)) { *pErr = PlatformError::TcpInvalidAddress; return alloc->allocPlain<TcpStreamRef>(TcpStreamType::Connection, getInvalidSocket()); } // Open a socket. const auto sock = socket(getIpFamilyCode(family), SOCK_STREAM, 0); if (!isSocketValid(sock)) { *pErr = getTcpPlatformError(); return alloc->allocPlain<TcpStreamRef>(TcpStreamType::Connection, sock, TcpStreamState::Failed); } configureSocket(sock); // 'connect' call blocks so we mark ourselves as paused so the gc can trigger in the mean time. execHandle->setState(ExecState::Paused); int res = -1; while (true) { switch (family) { case IpAddressFamily::IpV4: { sockaddr_in addr = {}; addr.sin_family = AF_INET; addr.sin_port = htons(static_cast<uint16_t>(port)); std::memcpy(&addr.sin_addr, address->getCharDataPtr(), 4u); res = ::connect(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(sockaddr_in)); } break; case IpAddressFamily::IpV6: { sockaddr_in6 addr = {}; addr.sin6_family = AF_INET6; addr.sin6_port = htons(static_cast<uint16_t>(port)); std::memcpy(&addr.sin6_addr, address->getCharDataPtr(), 16u); res = ::connect(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(sockaddr_in6)); } break; } if (res == 0) { break; // Success. } bool shouldRetry = false; #if defined(_WIN32) switch (WSAGetLastError()) { case WSAEINTR: shouldRetry = true; break; } #else // !_WIN32 switch (errno) { case EINTR: case EAGAIN: shouldRetry = true; break; } #endif // !_WIN32 if (!shouldRetry) { break; // Not an error we should retry. } threadYield(); // Yield between retries. } // After resuming check if we should wait for gc (or if we are aborted). execHandle->setState(ExecState::Running); if (execHandle->trap()) { return nullptr; } if (res < 0) { *pErr = getTcpPlatformError(); return alloc->allocPlain<TcpStreamRef>(TcpStreamType::Connection, sock, TcpStreamState::Failed); } // Socket has successfully connected to the remote. return alloc->allocPlain<TcpStreamRef>(TcpStreamType::Connection, sock); } inline auto tcpStartServer( const Settings* settings, RefAllocator* alloc, PlatformError* pErr, IpAddressFamily family, int32_t port, int32_t backlog) noexcept -> TcpStreamRef* { if (!settings->socketsEnabled) { *pErr = PlatformError::FeatureNetworkNotEnabled; return alloc->allocPlain<TcpStreamRef>(TcpStreamType::Server, getInvalidSocket()); } if (port < 0 || port > std::numeric_limits<uint16_t>::max()) { *pErr = PlatformError::TcpInvalidPort; return alloc->allocPlain<TcpStreamRef>(TcpStreamType::Server, getInvalidSocket()); } if (backlog > std::numeric_limits<int16_t>::max()) { *pErr = PlatformError::TcpInvalidBacklog; return alloc->allocPlain<TcpStreamRef>(TcpStreamType::Server, getInvalidSocket()); } if (!isIpFamilyValid(family)) { *pErr = PlatformError::TcpInvalidAddressFamily; return alloc->allocPlain<TcpStreamRef>(TcpStreamType::Connection, getInvalidSocket()); } // Open a socket. const auto sock = ::socket(getIpFamilyCode(family), SOCK_STREAM, 0); if (!isSocketValid(sock)) { *pErr = PlatformError::TcpSocketCouldNotBeAllocated; return alloc->allocPlain<TcpStreamRef>(TcpStreamType::Server, sock, TcpStreamState::Failed); } configureSocket(sock); // Bind the socket to any ip address at the given port. int res = -1; switch (family) { case IpAddressFamily::IpV4: { sockaddr_in addr = {}; addr.sin_family = AF_INET; addr.sin_port = htons(static_cast<uint16_t>(port)); addr.sin_addr.s_addr = INADDR_ANY; res = ::bind(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(sockaddr_in)); } break; case IpAddressFamily::IpV6: { sockaddr_in6 addr = {}; addr.sin6_family = AF_INET6; addr.sin6_port = htons(static_cast<uint16_t>(port)); addr.sin6_addr = in6addr_any; res = ::bind(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(sockaddr_in6)); } break; } if (res < 0) { *pErr = getTcpPlatformError(); return alloc->allocPlain<TcpStreamRef>(TcpStreamType::Server, sock, TcpStreamState::Failed); } // Start listening for new connections. if (listen(sock, backlog < 0 ? defaultConnectionBacklog : backlog) < 0) { *pErr = getTcpPlatformError(); return alloc->allocPlain<TcpStreamRef>(TcpStreamType::Server, sock, TcpStreamState::Failed); } // Socket is now ready to accept connections. return alloc->allocPlain<TcpStreamRef>(TcpStreamType::Server, sock); } inline auto tcpAcceptConnection( ExecutorHandle* execHandle, RefAllocator* alloc, PlatformError* pErr, Value stream) noexcept -> TcpStreamRef* { auto* streamRef = stream.getRef(); if (streamRef->getKind() != RefKind::StreamTcp) { *pErr = PlatformError::TcpInvalidSocket; return alloc->allocPlain<TcpStreamRef>(TcpStreamType::Connection, getInvalidSocket()); } auto* tcpStreamRef = static_cast<TcpStreamRef*>(streamRef); if (!tcpStreamRef->isValid()) { *pErr = PlatformError::TcpInvalidSocket; return alloc->allocPlain<TcpStreamRef>(TcpStreamType::Connection, getInvalidSocket()); } return tcpStreamRef->acceptConnection(execHandle, alloc, pErr); } inline auto tcpShutdown(PlatformError* pErr, Value stream) noexcept -> bool { auto* streamRef = stream.getRef(); if (streamRef->getKind() != RefKind::StreamTcp) { *pErr = PlatformError::TcpInvalidSocket; return false; } auto* tcpStreamRef = static_cast<TcpStreamRef*>(streamRef); if (!tcpStreamRef->isValid()) { *pErr = PlatformError::TcpInvalidSocket; return false; } return tcpStreamRef->shutdown(); } inline auto ipLookupAddress( const Settings* settings, ExecutorHandle* execHandle, RefAllocator* alloc, PlatformError* pErr, StringRef* hostName, IpAddressFamily family) noexcept -> StringRef* { if (!settings->socketsEnabled) { *pErr = PlatformError::FeatureNetworkNotEnabled; return alloc->allocStr(0); } if (!isIpFamilyValid(family)) { *pErr = PlatformError::TcpInvalidAddressFamily; return alloc->allocStr(0); } addrinfo hints = {}; hints.ai_family = getIpFamilyCode(family); hints.ai_socktype = SOCK_STREAM; // 'getaddrinfo' call blocks so mark ourselves as paused so the gc can trigger in the mean time. execHandle->setState(ExecState::Paused); addrinfo* res = nullptr; auto resCode = ::getaddrinfo(hostName->getCharDataPtr(), nullptr, &hints, &res); // After resuming check if we should wait for gc (or if we are aborted). execHandle->setState(ExecState::Running); if (execHandle->trap()) { // Cleanup the addinfo's incase any where allocated. if (res) { ::freeaddrinfo(res); } return nullptr; // Aborted. } if (resCode != 0 || !res) { switch (resCode) { case EAI_FAMILY: case EAI_FAIL: case EAI_NONAME: *pErr = PlatformError::TcpAddressNotFound; break; default: *pErr = PlatformError::TcpUnknownError; break; } return alloc->allocStr(0); } // Note: 'getaddrinfo' returns a linked list of addresses sorted by priority, we return the // first from the requested family. do { if (res->ai_family == hints.ai_family) { void* addrData = nullptr; switch (family) { case IpAddressFamily::IpV4: addrData = &reinterpret_cast<sockaddr_in*>(res->ai_addr)->sin_addr; break; case IpAddressFamily::IpV6: addrData = &reinterpret_cast<sockaddr_in6*>(res->ai_addr)->sin6_addr; break; } auto* str = alloc->allocStr(getIpAddressSize(family)); std::memcpy(str->getCharDataPtr(), addrData, str->getSize()); ::freeaddrinfo(res); // Free the list of addresses received from 'getaddrinfo'. return str; } } while ((res = res->ai_next)); *pErr = PlatformError::TcpAddressNotFound; ::freeaddrinfo(res); // Free the list of addresses received from 'getaddrinfo'. return alloc->allocStr(0); } inline auto getTcpPlatformError() noexcept -> PlatformError { #if defined(_WIN32) switch (WSAGetLastError()) { case WSAEINPROGRESS: return PlatformError::TcpAlreadyInProcess; case WSAENETDOWN: return PlatformError::TcpNetworkDown; case WSAEMFILE: case WSAENOBUFS: return PlatformError::TcpSocketCouldNotBeAllocated; case WSAEACCES: return PlatformError::TcpNoAccess; case WSAEADDRINUSE: return PlatformError::TcpAddressInUse; case WSAEAFNOSUPPORT: return PlatformError::TcpAddressFamilyNotSupported; case WSAECONNREFUSED: return PlatformError::TcpConnectionRefused; case WSAETIMEDOUT: return PlatformError::TcpTimeout; case WSAEHOSTUNREACH: return PlatformError::TcpNetworkUnreachable; case WSAHOST_NOT_FOUND: return PlatformError::TcpAddressNotFound; case WSAENETRESET: case WSAECONNRESET: return PlatformError::TcpRemoteResetConnection; case WSAESHUTDOWN: case WSAENOTSOCK: return PlatformError::TcpSocketIsDead; } #else // !_WIN32 switch (errno) { case EALREADY: return PlatformError::TcpAlreadyInProcess; case ENETDOWN: case EPROTO: case EHOSTDOWN: return PlatformError::TcpNetworkDown; case ENETUNREACH: return PlatformError::TcpNetworkUnreachable; case EMFILE: case ENFILE: case ENOBUFS: case ENOMEM: return PlatformError::TcpSocketCouldNotBeAllocated; case EACCES: return PlatformError::TcpNoAccess; case EADDRINUSE: return PlatformError::TcpAddressInUse; case EADDRNOTAVAIL: return PlatformError::TcpAddressUnavailable; case EAFNOSUPPORT: return PlatformError::TcpAddressFamilyNotSupported; case ECONNREFUSED: return PlatformError::TcpConnectionRefused; case ETIMEDOUT: return PlatformError::TcpTimeout; case ECONNRESET: return PlatformError::TcpRemoteResetConnection; case EPIPE: case EPROTOTYPE: case EBADF: case EINVAL: return PlatformError::TcpSocketIsDead; } #endif // !_WIN32 return PlatformError::TcpUnknownError; } } // namespace vm::internal
30.877168
100
0.683671
BastianBlokland
0d75976d5a721eda0c4153e5b1a0170f2675a3f5
926
cpp
C++
examples/CustomDemo/CustomServer/CustomServantImp.cpp
cSingleboy/TarsCpp
17b228b660d540baa1a93215fc007c5131a2fc68
[ "BSD-3-Clause" ]
386
2018-09-11T06:17:10.000Z
2022-03-31T05:59:41.000Z
examples/CustomDemo/CustomServer/CustomServantImp.cpp
cSingleboy/TarsCpp
17b228b660d540baa1a93215fc007c5131a2fc68
[ "BSD-3-Clause" ]
128
2018-09-12T03:43:33.000Z
2022-03-24T10:03:54.000Z
examples/CustomDemo/CustomServer/CustomServantImp.cpp
cSingleboy/TarsCpp
17b228b660d540baa1a93215fc007c5131a2fc68
[ "BSD-3-Clause" ]
259
2018-09-19T08:50:37.000Z
2022-03-11T07:17:56.000Z
#include "CustomServantImp.h" #include "servant/Application.h" using namespace std; ////////////////////////////////////////////////////// void CustomServantImp::initialize() { //initialize servant here: //... } ////////////////////////////////////////////////////// void CustomServantImp::destroy() { //destroy servant here: //... } int CustomServantImp::doRequest(tars::TarsCurrentPtr current, vector<char>& response) { //Return to the data package requested by the client itself, that is, the original package return (4-byte length + 4-byte request + buffer) const vector<char>& request = current->getRequestBuffer(); response = request; // cout << "doRequest: requestId:" << current->getRequestId() << ", funcName:" << current->getFuncName() << endl; return 0; } int CustomServantImp::doClose(TarsCurrentPtr current) { LOG->debug() << "close ip: " << current->getIp() << endl; return 0; }
23.74359
140
0.609071
cSingleboy
0d7d9e197253862c736a2348f2acca71e4567600
261
hpp
C++
tests/memory_resource_headers.hpp
olegpublicprofile/stdeasy
9f4ab01219f49ebab1983b4263d4dd6d3dc94bf0
[ "MIT" ]
5
2021-09-27T09:24:39.000Z
2021-10-14T12:34:46.000Z
tests/memory_resource_headers.hpp
olegpublicprofile/stdeasy
9f4ab01219f49ebab1983b4263d4dd6d3dc94bf0
[ "MIT" ]
null
null
null
tests/memory_resource_headers.hpp
olegpublicprofile/stdeasy
9f4ab01219f49ebab1983b4263d4dd6d3dc94bf0
[ "MIT" ]
null
null
null
#pragma once #include <stdeasy/memory_resource> #include <stdeasy/monotonic_buffer_resource> #include <stdeasy/polymorphic_allocator> #include <stdeasy/pool_options> #include <stdeasy/synchronized_pool_resource> #include <stdeasy/unsynchronized_pool_resource>
29
47
0.846743
olegpublicprofile
0d809854cbe613370439ebdcefa59e805b3642c0
11,783
cc
C++
tests/multi-test.cc
maxk-org/vdds
015473498661cb8f06868cce2dc4519a6452b861
[ "BSD-3-Clause" ]
null
null
null
tests/multi-test.cc
maxk-org/vdds
015473498661cb8f06868cce2dc4519a6452b861
[ "BSD-3-Clause" ]
null
null
null
tests/multi-test.cc
maxk-org/vdds
015473498661cb8f06868cce2dc4519a6452b861
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2021, Qualcomm Innovation Center, Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 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. // // SPDX-License-Identifier: BSD-3-Clause #include "vdds/domain.hpp" #include "vdds/pub.hpp" #include "vdds/sub.hpp" #include "vdds/query.hpp" #include "vdds/utils.hpp" #include "test-skell.hpp" #include <hogl/fmt/format.h> #include <fstream> // Multi Pub/Sub test // Data types struct timesync_msg : vdds::data { static const char* data_type; struct payload_t { uint64_t ptp_timestamp; uint64_t gps_timestamp; }; payload_t* payload() { return reinterpret_cast<payload_t*>(&this->plain); } const payload_t* payload() const { return reinterpret_cast<const payload_t*>(&this->plain); } uint64_t ptp_timestamp() const { return payload()->ptp_timestamp; } uint64_t gps_timestamp() const { return payload()->gps_timestamp; } }; struct sensor_msg : vdds::data { static const char* data_type; struct payload_t { uint64_t sample[4]; }; payload_t* payload() { return reinterpret_cast<payload_t*>(&this->plain); } }; struct detector_msg : vdds::data { static const char* data_type; struct payload_t { uint64_t avg[4]; }; payload_t* payload() { return reinterpret_cast<payload_t*>(&this->plain); } }; // Data type names const char* timesync_msg::data_type = "vdds.test.data.timesync"; const char* sensor_msg::data_type = "vdds.test.data.sensor"; const char* detector_msg::data_type = "vdds.test.data.detector"; // Simple thread + loop class engine { public: std::thread _thread; std::atomic_bool _killed; virtual void loop() = 0; void start() { _killed = false; _thread = std::thread([&](){ loop(); }); } void kill() { _killed = true; _thread.join(); } }; // Timer class timesync : public engine { private: std::string _name; // timer instance name (used for threads, tls, etc) hogl::area* _area; vdds::pub<timesync_msg> _pub; void loop() { hogl::tls tls(_name.c_str()); hogl::post(_area, _area->INFO, "timer %s started", _name); // Publish timesync every 20msec while (!_killed) { timesync_msg m; m.timestamp = tls.ring()->timestamp().to_nsec(); auto p = m.payload(); p->ptp_timestamp = m.timestamp - 123456; p->gps_timestamp = m.timestamp - 999999; hogl::post(_area, _area->INFO, hogl::arg_gstr("%s timesync: timestamp %llu: ptp %llu gps %llu"), _name, m.timestamp, m.ptp_timestamp(), m.gps_timestamp()); // Publish timesync data _pub.push(m); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } hogl::post(_area, _area->INFO, "timer %s stoped", _name); } public: timesync(vdds::domain& vd, const std::string& name) : _name(name), _area(hogl::add_area("TIMESYNC")), _pub(vd, _name, "/test/timesync") // publish {} }; // Driver class sensor_drv : public engine { private: std::string _sensor_name; // sensor name (used for topics, etc) std::string _name; // driver instance name (used for threads, tls, etc) hogl::area* _area; vdds::pub<sensor_msg> _pub; void loop() { hogl::tls tls(_name.c_str()); hogl::post(_area, _area->INFO, "driver %s started", _name); // Publish new data every 10msec while (!_killed) { sensor_msg m; m.timestamp = tls.ring()->timestamp().to_nsec(); auto p = m.payload(); p->sample[0] = 1; p->sample[1] = 2; p->sample[2] = 3; p->sample[3] = 4; hogl::post(_area, _area->INFO, hogl::arg_gstr("%s new-data: timestamp %llu: %u %u %u %u"), _name, m.timestamp, p->sample[0], p->sample[1], p->sample[2], p->sample[3]); // Publish sensor data _pub.push(m); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } hogl::post(_area, _area->INFO, "driver %s stoped", _name); } public: sensor_drv(vdds::domain& vd, const std::string& sensor_name) : _sensor_name(sensor_name), _name(fmt::format("DRV-{}", sensor_name)), _area(hogl::add_area("SENSOR-DRV")), _pub(vd, _name, fmt::format("/test/sensor/data/{}", sensor_name)) // publish {} }; // Detector class detector : public engine { private: std::string _name; // instance name (thread, tls, etc) hogl::area* _area; vdds::pub<detector_msg> _pub_det; using sensor_sub = vdds::sub<sensor_msg>; using unique_sub = std::unique_ptr<sensor_sub>; vdds::notifier_cv _nf; std::vector<unique_sub> _sub_sens; void process(sensor_msg& sm) { detector_msg dm; auto sp = sm.payload(); auto dp = dm.payload(); hogl::post(_area, _area->INFO, hogl::arg_gstr("%s new-data: timestamp %llu: %u %u %u %u"), _name, sm.timestamp, sp->sample[0], sp->sample[1], sp->sample[2], sp->sample[3]); // Generate new detection dm.timestamp = sm.timestamp; dp->avg[0] = (sp->sample[0] + sp->sample[1] + sp->sample[2] + sp->sample[3]) / 4; hogl::post(_area, _area->INFO, "%s detection seqno %llu timestamp %llu: avg %llu", _name, sm.seqno, sm.timestamp, dp->avg[0]); _pub_det.push(dm); } void loop() { hogl::tls tls(_name.c_str()); hogl::post(_area, _area->INFO, "detector %s started", _name); while (!_killed) { // Wait for data _nf.wait_for(std::chrono::milliseconds(100)); // Process sensor_msg sm; for (auto &ss : _sub_sens) { while (ss->pop(sm)) process(sm); } } hogl::post(_area, _area->INFO, "detector %s stoped", _name); } public: detector(vdds::domain& vd, const std::string& name, std::vector<std::string> sensor_names) : _name(name), _area(hogl::add_area("DETECTOR")), _pub_det(vd, name, fmt::format("/test/detector/data/{}", name)) { // Subscribe to sensors for (auto& s : sensor_names) _sub_sens.push_back( std::make_unique<sensor_sub>(vd, name, fmt::format("/test/sensor/data/{}", s), 16, &_nf) ); } }; // Controller class controller : public engine { private: std::string _name; // instance name (thread, tls, etc) hogl::area* _area; using detector_sub = vdds::sub<detector_msg>; using unique_detsub = std::unique_ptr<detector_sub>; using sensor_sub = vdds::sub<sensor_msg>; using unique_sensub = std::unique_ptr<sensor_sub>; std::vector<unique_detsub> _sub_dets; // detector subscriptions std::vector<unique_sensub> _sub_sens; // sensor subscriptions vdds::notifier_cv _nf_ts; vdds::sub<timesync_msg> _sub_ts; void process(unique_detsub& ds, detector_msg& dm) { auto dp = dm.payload(); hogl::post(_area, _area->INFO, hogl::arg_gstr("%s new detector %s data: timestamp %llu: %u"), _name, ds->topic()->name(), dm.timestamp, dp->avg[0]); } void process(unique_sensub& ss, sensor_msg& sm) { auto sp = sm.payload(); hogl::post(_area, _area->INFO, hogl::arg_gstr("%s new sensor data: timestamp %llu: %u %u %u %u"), _name, ss->topic()->name(), sm.timestamp, sp->sample[0], sp->sample[1], sp->sample[2], sp->sample[3]); } void process(timesync_msg& tm) { auto tp = tm.payload(); hogl::post(_area, _area->INFO, hogl::arg_gstr("%s timesync: timestamp %llu: ptp %llu gps %llu"), _name, tm.timestamp, tp->ptp_timestamp, tp->gps_timestamp); } void loop() { hogl::tls tls(_name.c_str()); hogl::post(_area, _area->INFO, "controller %s started", _name); while (!_killed) { // Wait for timesync _nf_ts.wait_for(std::chrono::milliseconds(100)); hogl::post(_area, _area->TRACE, "control loop %s # ph:B", _name); // Process timesync data timesync_msg tm; while (_sub_ts.pop(tm)) process(tm); // Process sensor data sensor_msg sm; for (auto &ss : _sub_sens) { while (ss->pop(sm)) process(ss, sm); } // Process detector data detector_msg dm; for (auto &ds : _sub_dets) { while (ds->pop(dm)) process(ds, dm); } hogl::post(_area, _area->TRACE, "control loop %s # ph:E", _name); } hogl::post(_area, _area->INFO, "controller %s stoped", _name); } public: controller(vdds::domain& vd, const std::string& name, std::vector<std::string> sensor_names, std::vector<std::string> detector_names) : _name(name), _area(hogl::add_area("CONTROL")), _sub_ts(vd, name, "/test/timesync", 2, &_nf_ts) // timesync sub uses CV notifier { // Subscribe to sensors for (auto& s : sensor_names) _sub_sens.push_back( std::make_unique<sensor_sub>(vd, name, fmt::format("/test/sensor/data/{}", s), 32) ); // Subscribe to detectors for (auto& s : detector_names) _sub_dets.push_back( std::make_unique<detector_sub>(vd, name, fmt::format("/test/detector/data/{}", s), 32) ); // No notifier for sensor and detector subs, but deeper queues, // we're going to process them when we get timesync. } }; bool run_test() { hogl::post(area, area->INFO, "Starting test"); // Create default domain vdds::domain vd("MAIN"); // Vector of drivers using unique_drv = std::unique_ptr<sensor_drv>; std::vector<unique_drv> drivers; // Create drivers std::vector<std::string> sensor_names = { "CAM0", "CAM1", "CAM2", "CAM3", "CAM4" }; for (auto& s: sensor_names) drivers.push_back( std::make_unique<sensor_drv>(vd, s) ); vd.dump(); // Create detectors detector det0(vd, "DET0", { "CAM0", "CAM1", "CAM4" }); detector det1(vd, "DET1", { "CAM0", "CAM2", "CAM3", "CAM4" }); // Create controllers controller ctrl0(vd, "CTRL0", { "CAM0" }, { "DET0", "DET1" }); controller ctrl1(vd, "CTRL1", { "CAM0", "CAM2" }, { "DET1" }); // Create timesyncs. // We don't even start the second one it's created simply to register second publisher. timesync sync0(vd, "SYNC0"); timesync sync1(vd, "SYNC1"); vd.dump(); // Start everything up ctrl0.start(); ctrl1.start(); det0.start(); det1.start(); for (auto& drv: drivers) drv->start(); sync0.start(); // Let things run for 2 seconds std::this_thread::sleep_for(std::chrono::seconds( optmap["duration"].as<unsigned int>() )); // Stop everything sync0.kill(); for (auto& drv: drivers) drv->kill(); det0.kill(); det1.kill(); ctrl0.kill(); ctrl1.kill(); vd.dump(); // Save domain as .dot for graphviz auto ss = std::ofstream("multi-test.dot", std::ofstream::trunc); vdds::utils::to_dot(vd, ss); // Simple query for one sensor vdds::query::domain_info di; vd.query(di, { "/test/sensor/data/CAM0", "any" }); hogl::post(area, area->INFO, "topic %s push_count %llu", di.topics[0].name, di.topics[0].push_count); // Dump all topics that carry sensor data vd.dump({ "any", sensor_msg::data_type }); return true; }
28.324519
115
0.671985
maxk-org
0d82900198357ad2693a24a411ddb415aad4b6a4
584
hpp
C++
src/JImage.hpp
jildertviet/ofxJVisuals
878c5b0e7a7dda49ddb71b3f5d19c13987706a73
[ "MIT" ]
null
null
null
src/JImage.hpp
jildertviet/ofxJVisuals
878c5b0e7a7dda49ddb71b3f5d19c13987706a73
[ "MIT" ]
6
2021-10-16T07:10:04.000Z
2021-12-26T13:23:54.000Z
src/JImage.hpp
jildertviet/ofxJVisuals
878c5b0e7a7dda49ddb71b3f5d19c13987706a73
[ "MIT" ]
null
null
null
// // Image.hpp // Bas // // Created by Jildert Viet on 18-03-16. // // #ifndef Image_hpp #define Image_hpp #include <stdio.h> #include "ofMain.h" #include "Event.hpp" class JImage: public Event{ enum DrawMode{ DEFAULT }; public: JImage(string filename, ofVec2f loc = ofVec2f(0,0)); JImage(){}; ofImage image; void display(); void specificFunction(); DrawMode drawMode = JImage::DrawMode::DEFAULT; bool loadImage(string path); bool bLoadSucces = false; }; #endif /* JImage_hpp */
16.685714
57
0.583904
jildertviet
0d8fe835f3d09c533a1b982dd950ec697e9208eb
188
cpp
C++
test.cpp
fobes/sfmath_tests
bc6b2f2a42b3392b421f042380b673d1da8b72f8
[ "Apache-2.0" ]
null
null
null
test.cpp
fobes/sfmath_tests
bc6b2f2a42b3392b421f042380b673d1da8b72f8
[ "Apache-2.0" ]
null
null
null
test.cpp
fobes/sfmath_tests
bc6b2f2a42b3392b421f042380b673d1da8b72f8
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include "../sfmath/CSfmathMatrix.h" TEST(TestCaseName, TestName) { CSfmathMatrix mtx; for (unsigned n = 0; n < 1000000; n++) { //CSfmathMatrix::Multiplication } }
17.090909
39
0.675532
fobes
0d92cd8e21f307d777b4560c55606afa00122de9
1,288
cpp
C++
TypeTraits/TypeTraits.cpp
jbcoe/CppSandbox
574dc31bbd3640a8cf1b7642c4a449bee687cce5
[ "MIT" ]
7
2015-01-18T13:30:09.000Z
2021-08-21T19:50:26.000Z
TypeTraits/TypeTraits.cpp
jbcoe/CppSandbox
574dc31bbd3640a8cf1b7642c4a449bee687cce5
[ "MIT" ]
1
2016-03-13T21:26:37.000Z
2016-03-13T21:26:37.000Z
TypeTraits/TypeTraits.cpp
jbcoe/CppSandbox
574dc31bbd3640a8cf1b7642c4a449bee687cce5
[ "MIT" ]
1
2016-02-16T04:56:25.000Z
2016-02-16T04:56:25.000Z
#include <iostream> #include <sstream> #include <type_traits> class CEmptyClass { public: static constexpr const char* name = "CEmptyClass"; }; class CDerivedClass : public CEmptyClass { public: static constexpr const char* name = "CDerivedClass"; }; template <typename T> std::string TypeName() { std::stringstream ss; if (std::is_const<typename std::remove_reference< typename std::remove_pointer<T>::type>::type>::value) { ss << "const "; } ss << std::remove_pointer< typename std::remove_reference<T>::type>::type::name; if (std::is_pointer<T>::value) { ss << '*'; } if (std::is_reference<T>::value) { ss << '&'; } return std::move(ss.str()); } template <typename A_t, typename B_t> void IsSame() { std::cout << "Is '" << TypeName<A_t>() << "' the same type as '" << TypeName<B_t>() << "' : " << std::is_same<A_t, B_t>::value << std::endl; } template <typename A_t> void IsConst() { std::cout << "Is '" << TypeName<A_t>() << "' constant : " << std::is_const<A_t>::value << std::endl; } int main(int argc, char* argv[]) { IsSame<CEmptyClass, CDerivedClass>(); IsSame<const CEmptyClass&, CEmptyClass>(); IsSame<CEmptyClass, CEmptyClass>(); IsConst<const CEmptyClass&>(); }
20.125
73
0.608696
jbcoe
0d957dd3a5434ce5e1c677cde6f7b212e1880753
368
cpp
C++
Day 3/A - Theatre Square.cpp
shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress
0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166
[ "MIT" ]
4
2019-12-12T19:59:50.000Z
2020-01-20T15:44:44.000Z
Day 3/A - Theatre Square.cpp
shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress
0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166
[ "MIT" ]
null
null
null
Day 3/A - Theatre Square.cpp
shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress
0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166
[ "MIT" ]
null
null
null
// Question Link ---> https://codeforces.com/problemset/problem/1/A // Day #3 #include <iostream> using namespace std; int main(void) { int m, n, a; long long width=0, height=0; cin >> m >> n >> a; if (m % a == 0) width = m/a; else width=(m/a+1); if (n %a == 0) height = n/a; else height=(n/a+1); cout << width*height << endl; return 0; }
23
68
0.557065
shtanriverdi
0d959fe632aca31aeb1f9e005ddebf88a16f9e3a
454
hpp
C++
cpp/include/models/linear_gradient_builder.hpp
rive-app/rive-android
bb1ececb0b0b0412fb9d2669e79d9410e041d0a2
[ "MIT" ]
133
2020-10-05T21:33:00.000Z
2022-03-30T11:17:31.000Z
cpp/include/models/linear_gradient_builder.hpp
rive-app/rive-android
bb1ececb0b0b0412fb9d2669e79d9410e041d0a2
[ "MIT" ]
113
2020-10-06T12:36:32.000Z
2022-03-21T10:58:35.000Z
cpp/include/models/linear_gradient_builder.hpp
rive-app/rive-android
bb1ececb0b0b0412fb9d2669e79d9410e041d0a2
[ "MIT" ]
17
2020-10-21T06:10:51.000Z
2022-01-06T06:42:42.000Z
#ifndef _RIVE_ANDROID_LINEAR_GRADIENT_BUILDER_HPP_ #define _RIVE_ANDROID_LINEAR_GRADIENT_BUILDER_HPP_ #include "jni_refs.hpp" #include "models/gradient_builder.hpp" namespace rive_android { class JNILinearGradientBuilder : public JNIGradientBuilder { public: JNILinearGradientBuilder(float sx, float sy, float ex, float ey) : JNIGradientBuilder(sx, sy, ex, ey) { } void apply(jobject paint) override; }; } // namespace rive_android #endif
22.7
103
0.790749
rive-app
0d9842cbceb2432c92e9e688bdfda737b392739e
4,286
cpp
C++
src/pose_estimation/Kabsch.cpp
LiliMeng/btrf
c13da164b11c5ada522fa40deeaffc32192c4bf9
[ "BSD-2-Clause" ]
9
2017-10-28T15:24:04.000Z
2021-12-28T13:51:05.000Z
src/pose_estimation/Kabsch.cpp
LiliMeng/btrf
c13da164b11c5ada522fa40deeaffc32192c4bf9
[ "BSD-2-Clause" ]
null
null
null
src/pose_estimation/Kabsch.cpp
LiliMeng/btrf
c13da164b11c5ada522fa40deeaffc32192c4bf9
[ "BSD-2-Clause" ]
3
2017-11-08T16:10:39.000Z
2019-05-21T03:40:02.000Z
#include <Eigen/Geometry> #include "Kabsch.hpp" // Given two sets of 3D points, find the rotation + translation + scale // which best maps the first set to the second. // Source: http://en.wikipedia.org/wiki/Kabsch_algorithm // The input 3D points are stored as columns. Eigen::Affine3d Find3DAffineTransform(Eigen::Matrix3Xd in, Eigen::Matrix3Xd out) { // Default output Eigen::Affine3d A; A.linear() = Eigen::Matrix3d::Identity(3, 3); A.translation() = Eigen::Vector3d::Zero(); if (in.cols() != out.cols()) throw "Find3DAffineTransform(): input data mis-match"; // First find the scale, by finding the ratio of sums of some distances, // then bring the datasets to the same scale. double dist_in = 0, dist_out = 0; for (int col = 0; col < in.cols()-1; col++) { dist_in += (in.col(col+1) - in.col(col)).norm(); dist_out += (out.col(col+1) - out.col(col)).norm(); } if (dist_in <= 0 || dist_out <= 0) return A; double scale = dist_out/dist_in; out /= scale; // printf("scale %lf\n", scale); // Find the centroids then shift to the origin Eigen::Vector3d in_ctr = Eigen::Vector3d::Zero(); Eigen::Vector3d out_ctr = Eigen::Vector3d::Zero(); for (int col = 0; col < in.cols(); col++) { in_ctr += in.col(col); out_ctr += out.col(col); } in_ctr /= in.cols(); out_ctr /= out.cols(); for (int col = 0; col < in.cols(); col++) { in.col(col) -= in_ctr; out.col(col) -= out_ctr; } // SVD Eigen::MatrixXd Cov = in * out.transpose(); Eigen::JacobiSVD<Eigen::MatrixXd> svd(Cov, Eigen::ComputeThinU | Eigen::ComputeThinV); // Find the rotation double d = (svd.matrixV() * svd.matrixU().transpose()).determinant(); if (d > 0) d = 1.0; else d = -1.0; Eigen::Matrix3d I = Eigen::Matrix3d::Identity(3, 3); I(2, 2) = d; Eigen::Matrix3d R = svd.matrixV() * I * svd.matrixU().transpose(); // The final transform A.linear() = scale * R; A.translation() = scale*(out_ctr - R*in_ctr); return A; } Eigen::Affine3d Find3DAffineTransformSameScale(Eigen::Matrix3Xd in, Eigen::Matrix3Xd out) { // Default output Eigen::Affine3d A; A.linear() = Eigen::Matrix3d::Identity(3, 3); A.translation() = Eigen::Vector3d::Zero(); if (in.cols() != out.cols()) throw "Find3DAffineTransform(): input data mis-match"; // Find the centroids then shift to the origin Eigen::Vector3d in_ctr = Eigen::Vector3d::Zero(); Eigen::Vector3d out_ctr = Eigen::Vector3d::Zero(); for (int col = 0; col < in.cols(); col++) { in_ctr += in.col(col); out_ctr += out.col(col); } in_ctr /= in.cols(); out_ctr /= out.cols(); for (int col = 0; col < in.cols(); col++) { in.col(col) -= in_ctr; out.col(col) -= out_ctr; } // SVD Eigen::MatrixXd Cov = in * out.transpose(); Eigen::JacobiSVD<Eigen::MatrixXd> svd(Cov, Eigen::ComputeThinU | Eigen::ComputeThinV); // Find the rotation double d = (svd.matrixV() * svd.matrixU().transpose()).determinant(); if (d > 0) d = 1.0; else d = -1.0; Eigen::Matrix3d I = Eigen::Matrix3d::Identity(3, 3); I(2, 2) = d; Eigen::Matrix3d R = svd.matrixV() * I * svd.matrixU().transpose(); // The final transform A.linear() = R; A.translation() = (out_ctr - R*in_ctr); return A; } // A function to test Find3DAffineTransform() void TestFind3DAffineTransform(){ // Create datasets with known transform Eigen::Matrix3Xd in(3, 100), out(3, 100); Eigen::Quaternion<double> Q(1, 3, 5, 2); Q.normalize(); Eigen::Matrix3d R = Q.toRotationMatrix(); double scale = 2.0; for (int row = 0; row < in.rows(); row++) { for (int col = 0; col < in.cols(); col++) { in(row, col) = log(2*row + 10.0)/sqrt(1.0*col + 4.0) + sqrt(col*1.0)/(row + 1.0); } } Eigen::Vector3d S; S << -5, 6, -27; for (int col = 0; col < in.cols(); col++) out.col(col) = scale*R*in.col(col) + S; Eigen::Affine3d A = Find3DAffineTransform(in, out); // See if we got the transform we expected if ( (scale*R-A.linear()).cwiseAbs().maxCoeff() > 1e-13 || (S-A.translation()).cwiseAbs().maxCoeff() > 1e-13) throw "Could not determine the affine transform accurately enough"; }
30.614286
90
0.602893
LiliMeng
0d98b716a60bd98f70382e2841346a5778e44157
1,580
cc
C++
simplest/src/NXSensitiveDetector.cc
maxwell-herrmann/geant4-simple-examples
0052d40fdc05baef05b4a6873c03d0d54885ad40
[ "BSD-2-Clause" ]
null
null
null
simplest/src/NXSensitiveDetector.cc
maxwell-herrmann/geant4-simple-examples
0052d40fdc05baef05b4a6873c03d0d54885ad40
[ "BSD-2-Clause" ]
null
null
null
simplest/src/NXSensitiveDetector.cc
maxwell-herrmann/geant4-simple-examples
0052d40fdc05baef05b4a6873c03d0d54885ad40
[ "BSD-2-Clause" ]
null
null
null
#include "NXSensitiveDetector.hh" #include "G4HCofThisEvent.hh" #include "G4Step.hh" #include "G4ThreeVector.hh" #include "G4SDManager.hh" #include "G4ios.hh" #include "G4RunManager.hh" //#include "NXRunAction.hh" #include "G4SystemOfUnits.hh" NXSensitiveDetector::NXSensitiveDetector(G4String name) : G4VSensitiveDetector(name) { } NXSensitiveDetector::~NXSensitiveDetector(){ } void NXSensitiveDetector::Initialize(G4HCofThisEvent* HCE) { } G4bool NXSensitiveDetector::ProcessHits(G4Step* aStep,G4TouchableHistory*) { G4StepPoint* pointPre=aStep->GetPreStepPoint(); G4StepPoint* pointPost=aStep->GetPostStepPoint(); G4TouchableHandle touchCur=pointPre->GetTouchableHandle(); G4VPhysicalVolume* volumeCur=touchCur->GetVolume(); G4String volumeCurName=volumeCur->GetName(); G4int copyNumofChamber=touchCur->GetCopyNumber(); G4Track* trackCur=aStep->GetTrack(); G4ParticleDefinition* particleCur = trackCur->GetDefinition(); G4String particleCurName = particleCur->GetParticleName(); G4double kineticEnergyCur = trackCur->GetKineticEnergy(); G4RunManager* runManager= G4RunManager::GetRunManager(); //NXRunAction* runActionCur=(NXRunAction *)runManager->GetUserRunAction(); G4cout << "Detector hit! " << pointPre->GetPosition() << " --> " << pointPost->GetPosition() << " by " << particleCurName << " with E=" << kineticEnergyCur / keV << "keV inside " << volumeCurName << G4endl; return true; } void NXSensitiveDetector::EndOfEvent(G4HCofThisEvent*) { G4cout << "Event end!" << G4endl; }
30.384615
100
0.731646
maxwell-herrmann
0d99dab65f7f7c4d0ce3127843baa892aa0eb166
1,183
cpp
C++
Data_Structures/Hashing/uni_number_of_occur.cpp
abhishekjha786/ds_algo
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
[ "MIT" ]
11
2020-03-20T17:24:28.000Z
2022-01-08T02:43:24.000Z
Data_Structures/Hashing/uni_number_of_occur.cpp
abhishekjha786/ds_algo
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
[ "MIT" ]
1
2021-07-25T11:24:46.000Z
2021-07-25T12:09:25.000Z
Data_Structures/Hashing/uni_number_of_occur.cpp
abhishekjha786/ds_algo
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
[ "MIT" ]
4
2020-03-20T17:24:36.000Z
2021-12-07T19:22:59.000Z
// Unique Number of Occurrences // Given an array of integers arr, write a function that // returns true if and only if the number of occurrences of each value in the array is unique. // Input: arr = [1,2,2,1,1,3] // Output: true // Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. // Example 2: // Input: arr = [1,2] // Output: false // Example 3: // Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] // Output: true // Solution: - // Create a map1 to store how many times the element occured. // Create a map2 to store how many times did the elements in map1 occured. // If any count > 1 in second map, return false. // Else return true. #include <bits/stdc++.h> using namespace std; bool uniqueOccurrences(vector<int> &arr) { unordered_map<int, int> mp; for (int ele : arr) { mp[ele]++; } unordered_map<int, int> mp2; for (auto itr = mp.begin(); itr != mp.end(); itr++) { mp2[itr->second]++; } for (auto itr2 = mp2.begin(); itr2 != mp2.end(); itr2++) { if (itr2->second > 1) { return false; } } return true; }
21.509091
118
0.60186
abhishekjha786
0d9e764e29695356fe651a9baabe3a8b74526157
1,736
cpp
C++
src/lp/escf.cpp
qaskai/MLCMST
0fa0529347eb6a44f45cf52dff477291c6fad433
[ "MIT" ]
null
null
null
src/lp/escf.cpp
qaskai/MLCMST
0fa0529347eb6a44f45cf52dff477291c6fad433
[ "MIT" ]
null
null
null
src/lp/escf.cpp
qaskai/MLCMST
0fa0529347eb6a44f45cf52dff477291c6fad433
[ "MIT" ]
null
null
null
#include <lp/escf.hpp> namespace MLCMST::lp { std::string ESCF::id() { static std::string id = "MP_ESCF"; return id; } ESCF::ESCF(bool exact_solution) : SCF(exact_solution) { } ESCF::ESCF(MLCMST::lp::LPSolverFactory mp_solver_factory) : SCF(mp_solver_factory) { } ESCF::~ESCF() = default; void ESCF::createConstraints() { createDemandConstraints(); createEnhancedCapacityConstraints(); createOneOutgoingConstraints(); createOneBetweenConstraints(); } void ESCF::createEnhancedCapacityConstraints() { for (auto [i,j] : _arc_set) { LinearExpr lhs = _flow_vars[i][j]; LinearExpr rhs; rhs += _arc_vars[i][j][0]; for (int l=1; l < _levels_number; l++) { rhs += (_mlcc_network->edgeCapacity(l-1) + 1) * _arc_vars[i][j][l]; } _mp_solver.MakeRowConstraint(lhs >= rhs); } for (int i : _vertex_set) { if (i == _mlcc_network->center()) continue; LinearExpr lhs = _flow_vars[i][_mlcc_network->center()]; LinearExpr rhs; for (int l=0; l < _levels_number; l++) { rhs += _mlcc_network->edgeCapacity(l) * _arc_vars[i][_mlcc_network->center()][l]; } _mp_solver.MakeRowConstraint(lhs <= rhs); } for (auto [i,j] : _arc_set) { if (j == _mlcc_network->center()) continue; LinearExpr lhs = _flow_vars[i][j]; LinearExpr rhs = (_mlcc_network->edgeCapacity(_levels_number-1) - _supply[j]) * _arc_vars[i][j][_levels_number-1]; for (int l=0; l < _levels_number-1; l++) { rhs += _mlcc_network->edgeCapacity(l) * _arc_vars[i][j][l]; } _mp_solver.MakeRowConstraint(lhs <= rhs); } } }
24.8
113
0.593894
qaskai
0d9eba0cd114e6380923e7b3393a2384d953ce4a
21,092
cpp
C++
ffscriptUT/ExpressionUT.cpp
VincentPT/xscript
cea6ee9e8c5af87af75188695ffa89080dce49b8
[ "MIT" ]
null
null
null
ffscriptUT/ExpressionUT.cpp
VincentPT/xscript
cea6ee9e8c5af87af75188695ffa89080dce49b8
[ "MIT" ]
null
null
null
ffscriptUT/ExpressionUT.cpp
VincentPT/xscript
cea6ee9e8c5af87af75188695ffa89080dce49b8
[ "MIT" ]
1
2019-12-24T22:24:01.000Z
2019-12-24T22:24:01.000Z
/****************************************************************** * File: ExpressionUT.cpp * Description: Test cases for checking compiling process, compiling * linking a single expression of C Lambda scripting * language. * Author: Vincent Pham * * Copyright (c) 2018 VincentPT. ** Distributed under the MIT License (http://opensource.org/licenses/MIT) ** * **********************************************************************/ #include "fftest.hpp" #include "ExpresionParser.h" #include <functional> #include "TemplateForTest.hpp" #include "Variable.h" #include "FunctionRegisterHelper.h" #include "BasicFunction.h" #include "BasicType.h" #include "FunctionFactory.h" using namespace std; using namespace ffscript; #include "ExpresionParser.h" #include "ScriptCompiler.h" #include "ScriptScope.h" #include "expressionunit.h" #include "Expression.h" namespace ffscriptUT { namespace ExpressionUT { FF_TEST_FUNCTION(ExpressionTest, testParseFunction1) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 + 2", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); FF_EXPECT_TRUE(units.size() == 3, L"the units is not 1 + 2"); } FF_TEST_FUNCTION(ExpressionTest, testParseFunction2) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 + 2 - (3 - 4)", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); FF_EXPECT_TRUE(units.size() == 9, L"the units is not '1 + 2 - (3 - 4)'"); } FF_TEST_FUNCTION(ExpressionTest, testParseFunction3) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 + \"hello\"", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); FF_EXPECT_TRUE(units.size() == 3, L"the units is not '1 + \"hello\"'"); } FF_TEST_FUNCTION(ExpressionTest, testParseFunction4) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 + L\"hello\" + 2", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); FF_EXPECT_TRUE(units.size() == 5, L"the units is not '1 + L\"hello\" + 2'"); } FF_TEST_FUNCTION(ExpressionTest, testCompile1) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 + 2", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); FF_EXPECT_TRUE(res, L"compile '1 + 2' failed!"); FF_EXPECT_TRUE(expList.size() == 1, L"compile '1 + 2' and retured more than one expression"); } FF_TEST_FUNCTION(ExpressionTest, testCompile2) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 + 2 + (3 - 4)", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); FF_EXPECT_TRUE(res, L"compile '1 + 2 + (3 - 4)' failed!"); FF_EXPECT_TRUE(expList.size() == 1, L"compile '1 + 2 + (3 - 4)' and retured more than one expression"); } FF_TEST_FUNCTION(ExpressionTest, testCompile2_checkfail1) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 + 2 + (3 - 4", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); FF_EXPECT_FALSE(res, L"compile '1 + 2 + (3 - 4' must be failed!"); } FF_TEST_FUNCTION(ExpressionTest, testCompile2_checkfail2) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 + 2 + 3 - 4)", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); FF_EXPECT_FALSE(res, L"compile '1 + 2 + 3 - 4)' must be failed!"); } FF_TEST_FUNCTION(ExpressionTest, testCompile2_checkfail3) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 + 2 + )3 - 4)", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); FF_EXPECT_FALSE(res, L"compile '1 + 2 + )3 - 4)' must be failed!"); } FF_TEST_FUNCTION(ExpressionTest, testCompile2_checkfail4) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 + 2 + (3 - 4(", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); FF_EXPECT_FALSE(res, L"compile '1 + 2 + (3 - 4(' must be failed!"); } FF_TEST_FUNCTION(ExpressionTest, testCompile3) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1+2,3", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); FF_EXPECT_TRUE(res, L"compile '1+2,3' failed!"); FF_EXPECT_TRUE(expList.size() == 2, L"compile '1+2,3' must return two expressions"); } FF_TEST_FUNCTION(ExpressionTest, testCompile4) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 + 2, 3", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); FF_EXPECT_TRUE(res, L"compile '1 + 2 , 3' failed!"); FF_EXPECT_TRUE(expList.size() == 2, L"compile '1 + 2, 3' must return two expressions"); } FF_TEST_FUNCTION(ExpressionTest, testCompile4_checkfail1) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L",1 + 2, 3", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); FF_EXPECT_FALSE(res, L"compile ',1 + 2, 3' must be failed!"); } FF_TEST_FUNCTION(ExpressionTest, testCompile4_checkfail2) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 + 2, 3,", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); FF_EXPECT_FALSE(res, L"compile '1 + 2, 3,' must be failed!"); } FF_TEST_FUNCTION(ExpressionTest, testCompile4_checkfail3) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L",1 + 2, 3,", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); FF_EXPECT_FALSE(res, L"compile ',1 + 2, 3,' must be failed!"); } FF_TEST_FUNCTION(ExpressionTest, testCompile5) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 + 2, 3 - 4", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); FF_EXPECT_TRUE(res, L"compile '1 + 2 + (3 - 4)' failed!"); FF_EXPECT_TRUE(expList.size() == 2, L"compile '1 + 2, 3 - 4' must return two expressions"); } FF_TEST_FUNCTION(ExpressionTest, testCompile6) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 + 2 * 3 - 4", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); FF_EXPECT_TRUE(res, L"compile '1 + 2 * 3 - 4' failed!"); FF_EXPECT_TRUE(expList.size() == 1, L"compile '1 + 2 * 3 - 4' must return one expression"); } FF_TEST_FUNCTION(ExpressionTest, testCompile6_checkfail1) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 + 2 3 * - 4", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); FF_EXPECT_FALSE(res, L"compile '1 + 2 3 * - 4' must failed!"); } FF_TEST_FUNCTION(ExpressionTest, testCompile6_1) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 + 2 * - 4", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); //because 1 + 2 * - 4 equal to 1 + 2 * (-4) //so the expression is valid FF_EXPECT_TRUE(res, L"compile '1 + 2 * - 4' must success!"); eResult = parser.link(expList.front().get()); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"link expression '1 + 2 * - 4' failed."); FF_EXPECT_TRUE(((Function*)expList.front()->getRoot().get())->getChild(0)->toString() == "1", L"first param of root function of '1 + 2 * (- 4)' must be '1'"); FF_EXPECT_TRUE(((Function*)expList.front()->getRoot().get())->getChild(1)->toString() == "*", L"second param of root function of '1 + 2 * (- 4)' must be '*'"); } FF_TEST_FUNCTION(ExpressionTest, testCompile6_2) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 + 2 * (- 4)", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); FF_EXPECT_TRUE(res, L"compile '1 + 2 * (- 4)' must success!"); eResult = parser.link(expList.front().get()); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"link expression '1 + 2 * (- 4)' failed."); FF_EXPECT_TRUE(expList.front()->getRoot()->toString() == "+", L"root unit of '1 + 2 * (- 4)' must be '+'"); FF_EXPECT_TRUE(((Function*)expList.front()->getRoot().get())->getChild(0)->toString() == "1", L"first param of root function of '1 + 2 * (- 4)' must be '1'"); FF_EXPECT_TRUE(((Function*)expList.front()->getRoot().get())->getChild(1)->toString() == "*", L"second param of root function of '1 + 2 * (- 4)' must be '*'"); } FF_TEST_FUNCTION(ExpressionTest, testCompile7) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 * 2 + 3", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); FF_EXPECT_TRUE(res, L"compile '1 * 2 + 3' failed!"); FF_EXPECT_TRUE(expList.size() == 1, L"compile '1 * 2 + 3' must return one expression"); FF_EXPECT_TRUE(expList.front()->getRoot()->toString() == "+", L"root unit of '1 * 2 + 3' must be '+'"); } FF_TEST_FUNCTION(ExpressionTest, testCompile8) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 * (2 + 3)", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); FF_EXPECT_TRUE(res, L"compile '1 * 2 + 3' failed!"); FF_EXPECT_TRUE(expList.size() == 1, L"compile '1 * (2 + 3)' must return one expression"); FF_EXPECT_TRUE(expList.front()->getRoot()->toString() == "*", L"root unit of '1 * (2 + 3)' must be '*'"); } FF_TEST_FUNCTION(ExpressionTest, testCompile9) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"1 + 2", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); FF_EXPECT_TRUE(res, L"compile '1 + 2' failed!"); eResult = parser.link(expList.front().get()); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"link expression '1 + 2' failed."); FF_EXPECT_TRUE(expList.front()->getRoot()->toString() == "+", L"root unit of '1 + 2' must be '+'"); FF_EXPECT_TRUE( ((Function*)expList.front()->getRoot().get())->getChild(0)->toString() == "1", L"first param of '1 + 2' must be '1'"); } static Function* createSumFunction(const string& name, int id) { return new FixParamFunction<2>(name, EXP_UNIT_ID_USER_FUNC, FUNCTION_PRIORITY_USER_FUNCTION, "int"); } FF_TEST_FUNCTION(ExpressionTest, testCompile11) { ScriptCompiler scriptCompiler; ExpressionParser parser(&scriptCompiler); FunctionRegisterHelper funcLibHelper(&scriptCompiler); const BasicTypes& basicType = scriptCompiler.getTypeManager()->getBasicTypes(); scriptCompiler.getTypeManager()->registerBasicTypes(&scriptCompiler); importBasicfunction(funcLibHelper); //register a custom function FunctionFactoryCdecl sumFactor(createSumFunction, ScriptType(basicType.TYPE_INT, "int")); scriptCompiler.registFunction("sum", "int,int", &sumFactor); list<ExpUnitRef> units; EExpressionResult eResult = parser.tokenize(L"sum(1,2)", units); FF_EXPECT_TRUE(eResult == EE_SUCCESS, L"parse string to units failed"); list<ExpressionRef> expList; bool res = parser.compile(units, expList); Expression* expressionPtr = expList.front().get(); parser.link(expressionPtr); FF_EXPECT_TRUE(res, L"compile 'sum(1,2)' failed!"); FF_EXPECT_TRUE(expList.front()->getRoot()->toString() == "sum", L"root unit of 'sum(1,2)' must be '+'"); FF_EXPECT_TRUE(((Function*)expList.front()->getRoot().get())->getChild(0)->toString() == "1", L"first param of 'sum(1,2)' must be '1'"); FF_EXPECT_TRUE(((Function*)expList.front()->getRoot().get())->getChild(1)->toString() == "2", L"second param of 'sum(1,2)' must be '2'"); } }; }
38.630037
162
0.725062
VincentPT
0d9f7963efa15408fd1a55f3f467edb554f6eab8
2,008
cpp
C++
src/framework/shared/object/fxuserobject.cpp
IT-Enthusiast-Nepal/Windows-Driver-Frameworks
bfee6134f30f92a90dbf96e98d54582ecb993996
[ "MIT" ]
994
2015-03-18T21:37:07.000Z
2019-04-26T04:04:14.000Z
src/framework/shared/object/fxuserobject.cpp
IT-Enthusiast-Nepal/Windows-Driver-Frameworks
bfee6134f30f92a90dbf96e98d54582ecb993996
[ "MIT" ]
13
2019-06-13T15:58:03.000Z
2022-02-18T22:53:35.000Z
src/framework/shared/object/fxuserobject.cpp
IT-Enthusiast-Nepal/Windows-Driver-Frameworks
bfee6134f30f92a90dbf96e98d54582ecb993996
[ "MIT" ]
350
2015-03-19T04:29:46.000Z
2019-05-05T23:26:50.000Z
/*++ Copyright (c) Microsoft Corporation Module Name: FxUserObject.cpp Abstract: This module implements the user object that device driver writers can use to take advantage of the driver frameworks infrastructure. Author: Environment: Both kernel and user mode Revision History: --*/ #include "fxobjectpch.hpp" #include "FxUserObject.hpp" // Tracing support extern "C" { #if defined(EVENT_TRACING) #include "FxUserObject.tmh" #endif } _Must_inspect_result_ NTSTATUS FxUserObject::_Create( __in PFX_DRIVER_GLOBALS FxDriverGlobals, __in_opt PWDF_OBJECT_ATTRIBUTES Attributes, __out FxUserObject** pUserObject ) { FxUserObject* pObject = NULL; NTSTATUS status; USHORT wrapperSize = 0; WDFOBJECT handle; #ifdef INLINE_WRAPPER_ALLOCATION #if FX_CORE_MODE==FX_CORE_USER_MODE wrapperSize = FxUserObject::GetWrapperSize(); #endif #endif pObject = new(FxDriverGlobals, Attributes, wrapperSize) FxUserObject(FxDriverGlobals); if (pObject == NULL) { DoTraceLevelMessage(FxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGOBJECT, "Memory allocation failed"); return STATUS_INSUFFICIENT_RESOURCES; } status = pObject->Commit(Attributes, &handle); if (!NT_SUCCESS(status)) { DoTraceLevelMessage(FxDriverGlobals, TRACE_LEVEL_ERROR, TRACINGOBJECT, "FxObject::Commit failed %!STATUS!", status); } if (NT_SUCCESS(status)) { *pUserObject = pObject; } else { pObject->DeleteFromFailedCreate(); } return status; } // // Public constructors // FxUserObject::FxUserObject( __in PFX_DRIVER_GLOBALS FxDriverGlobals ) : #ifdef INLINE_WRAPPER_ALLOCATION FxNonPagedObject(FX_TYPE_USEROBJECT, sizeof(FxUserObject) + GetWrapperSize(), FxDriverGlobals) #else FxNonPagedObject(FX_TYPE_USEROBJECT, sizeof(FxUserObject), FxDriverGlobals) #endif { return; }
18.766355
98
0.687749
IT-Enthusiast-Nepal
d3fbf002b267c042748459b159b2aab8fad1264f
1,469
hpp
C++
freeflow/sys/epoll.hpp
flowgrammable/freeflow-legacy
c5cd77495d44fe3a9e48a2e06fbb44f7418d388e
[ "Apache-2.0" ]
1
2017-07-30T04:18:29.000Z
2017-07-30T04:18:29.000Z
freeflow/sys/epoll.hpp
flowgrammable/freeflow-legacy
c5cd77495d44fe3a9e48a2e06fbb44f7418d388e
[ "Apache-2.0" ]
null
null
null
freeflow/sys/epoll.hpp
flowgrammable/freeflow-legacy
c5cd77495d44fe3a9e48a2e06fbb44f7418d388e
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2013-2014 Flowgrammable.org // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an "AS IS" // BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing // permissions and limitations under the License. #ifndef FREEFLOW_EPOLL_HPP #define FREEFLOW_EPOLL_HPP #include <unistd.h> #include <sys/epoll.h> #include <map> #include <vector> #include "freeflow/sys/error.hpp" #include "freeflow/sys/time.hpp" namespace freeflow { struct EPevent : epoll_event { enum Type : uint32_t { READ = EPOLLIN, WRITE = EPOLLOUT, CLOSED = EPOLLRDHUP, EDGE = EPOLLET, ONESHOT = EPOLLONESHOT, }; EPevent() = default; EPevent(const EPevent&) = default; EPevent(Type t, int fd); }; struct Epoll { Epoll(); ~Epoll(); int fd; std::map<int,EPevent> watched; }; Error add_reader(Epoll& e, int fd); Error add_writer(Epoll& e, int fd); Error del_reader(Epoll& e, int fd); Error del_writer(Epoll& e, int fd); using EPevents = std::vector<EPevent>; EPevents poll(Epoll& ep, const MicroTime& mt); } // namespace freeflow #include "epoll.ipp" #endif
21.925373
70
0.707965
flowgrammable
d3ff9946b91f77b916fb13f4d75fe6d4ba923dc0
3,102
cpp
C++
src/scams/impl/predefined_moc/eln/sca_eln_vcr.cpp
sivertism/mirror-sysc-ams
ae6a41555bbe32771799111b2a120fede6cb790f
[ "Apache-2.0" ]
null
null
null
src/scams/impl/predefined_moc/eln/sca_eln_vcr.cpp
sivertism/mirror-sysc-ams
ae6a41555bbe32771799111b2a120fede6cb790f
[ "Apache-2.0" ]
null
null
null
src/scams/impl/predefined_moc/eln/sca_eln_vcr.cpp
sivertism/mirror-sysc-ams
ae6a41555bbe32771799111b2a120fede6cb790f
[ "Apache-2.0" ]
null
null
null
/***************************************************************************** Copyright 2010-2014 Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V. Copyright 2015-2020 COSEDA Technologies GmbH *****************************************************************************/ /***************************************************************************** sca_eln_vcr.cpp - description Original Author: Karsten Einwich Fraunhofer IIS/EAS Dresden Created on: 13.05.2014 SVN Version : $Revision: 1703 $ SVN last checkin : $Date: 2014-04-23 12:10:42 +0200 (Wed, 23 Apr 2014) $ SVN checkin by : $Author: karsten $ SVN Id : $Id: sca_eln_r.cpp 1703 2014-04-23 10:10:42Z karsten $ *****************************************************************************/ /*****************************************************************************/ #include "scams/predefined_moc/eln/sca_eln_vcr.h" namespace sca_eln { sca_vcr::sca_vcr(sc_core::sc_module_name, const sca_util::sca_vector<std::pair<double,double> >& pwc_value_) : p("p"), n("n"), pwc_vector("pwc_value", pwc_value_) { nadd1=-1; nadd2=-1; unit="A"; domain="I"; } const char* sca_vcr::kind() const { return "sca_eln::sca_vcr"; } void sca_vcr::trace( sc_core::sc_trace_file* tf ) const { std::ostringstream str; str << "sc_trace of sca_vcr module not supported for module: " << this->name(); SC_REPORT_WARNING("SystemC-AMS",str.str().c_str()); } void sca_vcr::matrix_stamps() { nadd1 = add_equation(2); nadd2 = nadd1 + 1; B_wr(nadd1, p) = -1.0; B_wr(nadd1, n) = 1.0; B_wr(nadd1, nadd1) = 1.0; // 0 = nadd1 * 1.0 - v(p) + v(n) // nadd1 = ( v(p) - v(n) ) / 1.0 B_wr(p, nadd1) = 1.0; B_wr(n, nadd1) = -1.0; B_wr(nadd2,nadd2) = -1.0; // nadd2 = v(cp) - v(cn) B_wr(nadd2,cp) = 1.0; B_wr(nadd2,cn) = -1.0; add_pwl_b_stamp_to_B(nadd1,nadd1,nadd2,pwc_vector.get()); } bool sca_vcr::trace_init(sca_util::sca_implementation::sca_trace_object_data& data) { //trace will be activated after every complete cluster calculation //by teh synchronization layer return this->add_solver_trace(data); } void sca_vcr::trace(long id,sca_util::sca_implementation::sca_trace_buffer& buffer) { sca_core::sca_time ctime = sca_eln::sca_module::get_time(); buffer.store_time_stamp(id,ctime,x(nadd1)); } sca_util::sca_complex sca_vcr::calculate_ac_result(sca_util::sca_complex* res_vec) { return res_vec[nadd1]; } /** * experimental physical domain interface */ void sca_vcr::set_unit(const std::string& unit_) { unit=unit_; } const std::string& sca_vcr::get_unit() const { return unit; } void sca_vcr::set_unit_prefix(const std::string& prefix_) { unit_prefix=prefix_; } const std::string& sca_vcr::get_unit_prefix() const { return unit_prefix; } void sca_vcr::set_domain(const std::string& domain_) { domain=domain_; } const std::string& sca_vcr::get_domain() const { return domain; } } //namespace sca_eln
22.808824
83
0.574468
sivertism
31038acb562f5488eb00972ee8b3075b7079cd0b
17,446
cpp
C++
Tests/src/Collection/HashMap.cpp
BlockProject3D/Framework
1c27ef19d9a12d158a2b53f6bd28dd2d8e678912
[ "BSD-3-Clause" ]
2
2019-02-02T20:48:17.000Z
2019-02-22T09:59:40.000Z
Tests/src/Collection/HashMap.cpp
BlockProject3D/Framework
1c27ef19d9a12d158a2b53f6bd28dd2d8e678912
[ "BSD-3-Clause" ]
125
2020-01-14T18:26:38.000Z
2021-02-23T15:33:55.000Z
Tests/src/Collection/HashMap.cpp
BlockProject3D/Framework
1c27ef19d9a12d158a2b53f6bd28dd2d8e678912
[ "BSD-3-Clause" ]
1
2020-05-26T08:55:10.000Z
2020-05-26T08:55:10.000Z
// Copyright (c) 2020, BlockProject 3D // // 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 BlockProject 3D 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 OWNER 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 <cassert> #include <iostream> #include <gtest/gtest.h> #include <Framework/Name.hpp> #include <Framework/Memory/Utility.hpp> #include <Framework/Collection/HashMap.hpp> #include <Framework/Collection/Stringifier.HashMap.hpp> using namespace bpf::memory; using namespace bpf::collection; using namespace bpf; TEST(HashMap, Creation_1) { HashMap<String, int> map; map["test1"] = 0; map["test2"] = 3; map["test3"] = 7; } TEST(HashMap, Creation_2) { HashMap<int, int> lst; lst.Add(0, 0); lst.Add(1, 3); lst.Add(2, 7); EXPECT_EQ(lst[0], 0); EXPECT_EQ(lst[1], 3); EXPECT_EQ(lst[2], 7); } TEST(HashMap, PreHash) { EXPECT_NE(Hash<String>::ValueOf("B"), Hash<String>::ValueOf("C")); EXPECT_NE(Hash<String>::ValueOf("a"), Hash<String>::ValueOf("b")); EXPECT_NE(Hash<String>::ValueOf("a"), Hash<String>::ValueOf("aa")); EXPECT_NE(Hash<String>::ValueOf("a"), Hash<String>::ValueOf("a\a")); } TEST(HashMap, Creation_List) { HashMap<int, int> lst = { { 0, 0 }, { 1, 3 }, { 2, 7 } }; EXPECT_EQ(lst[0], 0); EXPECT_EQ(lst[1], 3); EXPECT_EQ(lst[2], 7); } TEST(HashMap, Add) { const int i = 12; HashMap<int, int> lst = { { 0, i }, { 1, 2 } }; EXPECT_EQ(lst.Size(), 2U); lst.Add(2, 3); EXPECT_EQ(lst.Size(), 3U); lst.Add(3, i); EXPECT_EQ(lst.Size(), 4U); EXPECT_STREQ(*String::ValueOf(lst), "{'0': 12, '1': 2, '2': 3, '3': 12}"); } TEST(HashMap, Indexer) { HashMap<int, int> lst = { { 0, 0 }, { 1, 3 }, { 2, 7 } }; EXPECT_EQ(lst[0], 0); EXPECT_EQ(lst[1], 3); EXPECT_EQ(lst[2], 7); const auto &lst1 = lst; EXPECT_THROW(lst1[-1], IndexException); lst[-1] = 42; EXPECT_EQ(lst1[-1], 42); } TEST(HashMap, FindByKey) { HashMap<int, int> lst = { { 0, 0 }, { 1, 3 }, { 2, 7 } }; EXPECT_EQ(lst.begin(), lst.FindByKey(0)); EXPECT_EQ(--lst.end(), lst.FindByKey(2)); EXPECT_EQ(lst.end(), lst.FindByKey(3)); } TEST(HashMap, FindByValue) { HashMap<int, int> lst = { { 0, 0 }, { 1, 3 }, { 2, 7 } }; EXPECT_EQ(lst.begin(), lst.FindByValue(0)); EXPECT_EQ(--lst.end(), lst.FindByValue(7)); EXPECT_EQ(--lst.end(), lst.FindByValue<ops::Greater>(3)); EXPECT_EQ(lst.end(), lst.FindByValue(42)); } TEST(HashMap, Find) { HashMap<int, int> lst = { { 0, 0 }, { 1, 3 }, { 2, 7 } }; EXPECT_EQ(++lst.begin(), lst.Find([](HashMap<int, int>::Iterator it) { return (it->Value == 3); })); EXPECT_EQ(lst.end(), lst.Find([](HashMap<int, int>::Iterator it) { return (it->Value == 42); })); } TEST(HashMap, Equal) { HashMap<int, int> lst = { { 0, 0 }, { 1, 3 }, { 2, 7 } }; HashMap<int, int> lst1 = { { 0, 0 }, { 1, 3 }, { 2, 7 } }; HashMap<int, int> lst2 = { { 0, 0 }, { 1, 3 } }; HashMap<int, int> lst3 = { { 0, 0 }, { 1, 3 }, { 2, 4 } }; EXPECT_TRUE(lst == lst1); EXPECT_FALSE(lst != lst1); EXPECT_FALSE(lst == lst2); EXPECT_TRUE(lst != lst2); EXPECT_FALSE(lst == lst3); EXPECT_TRUE(lst != lst3); } TEST(HashMap, Concatenate) { HashMap<int, int> lst = { { 0, 0 }, { 1, 3 }, { 2, 7 } }; HashMap<int, int> lst1 = { { 3, 0 }, { 1, 5 }, { 4, 7 } }; auto concatenated = lst + lst1; EXPECT_STREQ(*String::ValueOf(concatenated), "{'0': 0, '1': 5, '2': 7, '3': 0, '4': 7}"); lst1 += lst; EXPECT_STREQ(*String::ValueOf(lst1), "{'0': 0, '1': 3, '2': 7, '3': 0, '4': 7}"); EXPECT_STREQ(*String::ValueOf(lst), "{'0': 0, '1': 3, '2': 7}"); } TEST(HashMap, HasKey) { HashMap<int, int> lst = { { 0, 0 }, { 1, 3 }, { 2, 7 } }; EXPECT_EQ(lst[0], 0); EXPECT_EQ(lst[1], 3); EXPECT_EQ(lst[2], 7); EXPECT_TRUE(lst.HasKey(0)); EXPECT_TRUE(lst.HasKey(1)); EXPECT_TRUE(lst.HasKey(2)); } TEST(HashMap, Copy) { HashMap<int, int> lst; lst.Add(0, 0); lst.Add(1, 3); lst.Add(2, 7); auto copy = lst; EXPECT_EQ(lst[0], 0); EXPECT_EQ(lst[1], 3); EXPECT_EQ(lst[2], 7); auto cc = &copy; copy = *cc; EXPECT_EQ(copy[0], 0); EXPECT_EQ(copy[1], 3); EXPECT_EQ(copy[2], 7); } TEST(HashMap, Move) { HashMap<int, int> lst; lst.Add(0, 0); lst.Add(1, 3); lst.Add(2, 7); auto mv = std::move(lst); EXPECT_EQ(mv[0], 0); EXPECT_EQ(mv[1], 3); EXPECT_EQ(mv[2], 7); EXPECT_EQ(lst.Size(), 0U); EXPECT_EQ(lst.begin(), lst.end()); } TEST(HashMap, Remove) { HashMap<int, int> lst = { { 0, 0 }, { 1, 3 }, { 2, 7 }, { 3, 0 } }; lst.Remove(0, false); EXPECT_STREQ(*String::ValueOf(lst), "{'1': 3, '2': 7, '3': 0}"); lst.Add(0, 0); EXPECT_STREQ(*String::ValueOf(lst), "{'0': 0, '1': 3, '2': 7, '3': 0}"); lst.Remove(0); EXPECT_STREQ(*String::ValueOf(lst), "{'1': 3, '2': 7}"); lst.Remove<ops::Less>(7); EXPECT_STREQ(*String::ValueOf(lst), "{'2': 7}"); } TEST(HashMap, RemoveAt_1) { HashMap<int, int> lst = { { 0, 0 }, { 1, 3 }, { 2, 7 }, { 3, 0 } }; lst.RemoveAt(2); EXPECT_STREQ(*String::ValueOf(lst), "{'0': 0, '1': 3, '3': 0}"); lst.RemoveAt(++lst.begin()); EXPECT_STREQ(*String::ValueOf(lst), "{'0': 0, '3': 0}"); auto it = lst.begin(); lst.RemoveAt(it); EXPECT_STREQ(*String::ValueOf(lst), "{'3': 0}"); EXPECT_NE(it, lst.end()); lst.RemoveAt(--lst.end()); EXPECT_STREQ(*String::ValueOf(lst), "{}"); lst = { { 0, 0 }, { 1, 3 }, { 2, 7 }, { 3, 0 } }; lst.RemoveAt(--(--lst.end())); EXPECT_STREQ(*String::ValueOf(lst), "{'0': 0, '1': 3, '3': 0}"); lst.RemoveAt(lst.end()); EXPECT_STREQ(*String::ValueOf(lst), "{'0': 0, '1': 3, '3': 0}"); } TEST(HashMap, RemoveAt_2) { HashMap<int, int> lst = { { 0, 0 }, { 1, 3 }, { 2, 7 }, { 3, 0 } }; lst.RemoveAt(2); EXPECT_STREQ(*String::ValueOf(lst), "{'0': 0, '1': 3, '3': 0}"); lst.RemoveAt(++lst.begin()); EXPECT_STREQ(*String::ValueOf(lst), "{'0': 0, '3': 0}"); lst.RemoveAt(lst.begin()); EXPECT_STREQ(*String::ValueOf(lst), "{'3': 0}"); EXPECT_NE(lst.begin(), lst.end()); lst.RemoveAt(--lst.end()); EXPECT_STREQ(*String::ValueOf(lst), "{}"); lst = { { 0, 0 }, { 1, 3 }, { 2, 7 }, { 3, 0 } }; lst.RemoveAt(--(--lst.end())); EXPECT_STREQ(*String::ValueOf(lst), "{'0': 0, '1': 3, '3': 0}"); lst.RemoveAt(lst.end()); EXPECT_STREQ(*String::ValueOf(lst), "{'0': 0, '1': 3, '3': 0}"); } TEST(HashMap, Iterator_1) { HashMap<int, int> lst = { { 0, 0 }, { 1, 3 }, { 2, 7 }, { 3, 0 } }; auto it = lst.begin(); ++it; --it; EXPECT_EQ(it, lst.begin()); --it; ++it; EXPECT_EQ(it, ++lst.begin()); it = lst.end(); --it; ++it; EXPECT_EQ(it, lst.end()); ++it; --it; EXPECT_EQ(it, --lst.end()); } TEST(HashMap, Iterator_2) { HashMap<int, int> lst = { { 1, 3 }, { 2, 7 }, { 3, 0 } }; auto it = lst.begin(); ++it; --it; EXPECT_EQ(it, lst.begin()); --it; ++it; EXPECT_EQ(it, ++lst.begin()); it = lst.end(); --it; ++it; EXPECT_EQ(it, lst.end()); ++it; --it; EXPECT_EQ(it, --lst.end()); } TEST(HashMap, Iterator_3) { HashMap<int, int> lst = { { 1, 3 }, { 2, 7 }, { 3, 0 } }; auto it = lst.begin(); it += 2; EXPECT_EQ(it->Value, 0); it -= 2; EXPECT_EQ(it->Value, 3); it = lst.begin(); it += 42; EXPECT_EQ(it, lst.end()); it = lst.end(); it -= 42; EXPECT_EQ(it->Value, 3); } TEST(HashMap, Iterator_4) { HashMap<int, int> lst = { { 1, 3 }, { 2, 7 }, { 3, 0 } }; auto it1 = lst.begin(); const auto &it = it1; EXPECT_EQ((*it).Value, 3); EXPECT_EQ(it->Value, 3); EXPECT_EQ(it->Key, 1); ++it1; EXPECT_EQ((*it).Value, 7); EXPECT_EQ(it->Value, 7); EXPECT_EQ(it->Key, 2); } TEST(HashMap, ReverseIterator_1) { HashMap<int, int> lst = { { 0, 0 }, { 1, 3 }, { 2, 7 }, { 3, 0 } }; auto it = lst.rbegin(); ++it; --it; EXPECT_EQ(it, lst.rbegin()); --it; ++it; EXPECT_EQ(it, ++lst.rbegin()); it = lst.rend(); --it; ++it; EXPECT_EQ(it, lst.rend()); ++it; --it; EXPECT_EQ(it, --lst.rend()); } TEST(HashMap, ReverseIterator_2) { HashMap<int, int> lst = { { 1, 3 }, { 2, 7 }, { 3, 0 } }; auto it = lst.rbegin(); ++it; --it; EXPECT_EQ(it, lst.rbegin()); --it; ++it; EXPECT_EQ(it, ++lst.rbegin()); it = lst.rend(); --it; ++it; EXPECT_EQ(it, lst.rend()); ++it; --it; EXPECT_EQ(it, --lst.rend()); } TEST(HashMap, ReverseIterator_3) { HashMap<int, int> lst = { { 1, 3 }, { 2, 7 }, { 3, 0 } }; auto it = lst.rbegin(); it += 2; EXPECT_EQ(it->Value, 3); it -= 2; EXPECT_EQ(it->Value, 0); it = lst.rbegin(); it += 42; EXPECT_EQ(it, lst.rend()); it -= 42; EXPECT_EQ(it->Value, 0); } TEST(HashMap, ReverseIterator_4) { HashMap<int, int> lst = { { 1, 3 }, { 2, 7 }, { 3, 0 } }; auto it1 = lst.rbegin(); const auto &it = it1; EXPECT_EQ((*it).Value, 0); EXPECT_EQ(it->Value, 0); EXPECT_EQ(it->Key, 3); ++it1; EXPECT_EQ((*it).Value, 7); EXPECT_EQ(it->Value, 7); EXPECT_EQ(it->Key, 2); } TEST(HashMap, CIterator_1) { HashMap<int, int> lst1 = { { 0, 0 }, { 1, 3 }, { 2, 7 }, { 3, 0 } }; const auto &lst = lst1; auto it = lst.begin(); ++it; --it; EXPECT_EQ(it, lst.begin()); --it; ++it; EXPECT_EQ(it, ++lst.begin()); it = lst.end(); --it; ++it; EXPECT_EQ(it, lst.end()); ++it; --it; EXPECT_EQ(it, --lst.end()); } TEST(HashMap, CIterator_2) { HashMap<int, int> lst1 = { { 1, 3 }, { 2, 7 }, { 3, 0 } }; const auto &lst = lst1; auto it = lst.begin(); ++it; --it; EXPECT_EQ(it, lst.begin()); --it; ++it; EXPECT_EQ(it, ++lst.begin()); it = lst.end(); --it; ++it; EXPECT_EQ(it, lst.end()); ++it; --it; EXPECT_EQ(it, --lst.end()); } TEST(HashMap, CIterator_3) { HashMap<int, int> lst1 = { { 1, 3 }, { 2, 7 }, { 3, 0 } }; const auto &lst = lst1; auto it = lst.begin(); it += 2; EXPECT_EQ(it->Value, 0); it -= 2; EXPECT_EQ(it->Value, 3); it = lst.begin(); it += 42; EXPECT_EQ(it, lst.end()); it = lst.end(); it -= 42; EXPECT_EQ(it->Value, 3); } TEST(HashMap, CReverseIterator_1) { HashMap<int, int> lst1 = { { 0, 0 }, { 1, 3 }, { 2, 7 }, { 3, 0 } }; const auto &lst = lst1; auto it = lst.rbegin(); ++it; --it; EXPECT_EQ(it, lst.rbegin()); --it; ++it; EXPECT_EQ(it, ++lst.rbegin()); it = lst.rend(); --it; ++it; EXPECT_EQ(it, lst.rend()); ++it; --it; EXPECT_EQ(it, --lst.rend()); } TEST(HashMap, CReverseIterator_2) { HashMap<int, int> lst1 = { { 1, 3 }, { 2, 7 }, { 3, 0 } }; const auto &lst = lst1; auto it = lst.rbegin(); ++it; --it; EXPECT_EQ(it, lst.rbegin()); --it; ++it; EXPECT_EQ(it, ++lst.rbegin()); it = lst.rend(); --it; ++it; EXPECT_EQ(it, lst.rend()); ++it; --it; EXPECT_EQ(it, --lst.rend()); } TEST(HashMap, CReverseIterator_3) { HashMap<int, int> lst1 = { { 1, 3 }, { 2, 7 }, { 3, 0 } }; const auto &lst = lst1; auto it = lst.rbegin(); it += 2; EXPECT_EQ(it->Value, 3); it -= 2; EXPECT_EQ(it->Value, 0); it = lst.rbegin(); it += 42; EXPECT_EQ(it, lst.rend()); it -= 42; EXPECT_EQ(it->Value, 0); } TEST(HashMap, Clear) { HashMap<int, int> lst = { { 0, 0 }, { 1, 3 }, { 2, 7 }, { 3, 0 } }; EXPECT_EQ(lst.Size(), 4U); lst.Clear(); EXPECT_EQ(lst.Size(), 0U); EXPECT_EQ(lst.begin(), lst.end()); } TEST(HashMap, IterateForward_Test1) { int res = 0; HashMap<int, int> lst; lst.Add(0, 0); lst.Add(1, 3); lst.Add(2, 7); for (auto &i : lst) res += i.Key + i.Value; EXPECT_EQ(res, 13); } TEST(HashMap, IterateForward_Test2) { String res = ""; HashMap<String, int> map; map["test1"] = 0; map["test2"] = 3; map["test3"] = 7; for (auto &i : map) res += i.Key + String::ValueOf(i.Value) + ";"; EXPECT_STREQ(*res, "test37;test10;test23;"); } TEST(HashMap, IterateBackward_Test1) { int res = 0; HashMap<int, int> lst; lst.Add(0, 0); lst.Add(1, 3); lst.Add(2, 7); for (auto &i : Reverse(lst)) res += i.Key + i.Value; EXPECT_EQ(res, 13); } TEST(HashMap, IterateBackward_Test2) { String res = ""; HashMap<String, int> map; map["test1"] = 0; map["test2"] = 3; map["test3"] = 7; for (auto &i : Reverse(map)) res += i.Key + String::ValueOf(i.Value) + ";"; EXPECT_STREQ(*res, "test23;test10;test37;"); } TEST(HashMap, ReadWrite) { HashMap<String, int> map; map["test1"] = 0; map["test2"] = 3; map["test3"] = 7; EXPECT_EQ(map["test1"], 0); EXPECT_EQ(map["test2"], 3); EXPECT_EQ(map["test3"], 7); } TEST(HashMap, ReadWrite_NonCopy) { HashMap<String, UniquePtr<int>> map; map["test1"] = nullptr; map["test2"] = nullptr; map["test3"] = nullptr; EXPECT_EQ(map["test1"], nullptr); EXPECT_EQ(map["test2"], nullptr); EXPECT_EQ(map["test3"], nullptr); map["test1"] = MakeUnique<int>(0); map["test2"] = MakeUnique<int>(5); map["test3"] = MakeUnique<int>(9); EXPECT_EQ(*map["test1"], 0); EXPECT_EQ(*map["test2"], 5); EXPECT_EQ(*map["test3"], 9); } TEST(HashMap, ReadWrite_NonCopy_1) { HashMap<Name, UniquePtr<int>> map; map[bpf::Name("test1")] = nullptr; map[bpf::Name("test2")] = nullptr; map[bpf::Name("test3")] = nullptr; EXPECT_EQ(map[bpf::Name("test1")], nullptr); EXPECT_EQ(map[bpf::Name("test2")], nullptr); EXPECT_EQ(map[bpf::Name("test3")], nullptr); map[bpf::Name("test1")] = MakeUnique<int>(0); map[bpf::Name("test2")] = MakeUnique<int>(5); map[bpf::Name("test3")] = MakeUnique<int>(9); EXPECT_EQ(*map[bpf::Name("test1")], 0); EXPECT_EQ(*map[bpf::Name("test2")], 5); EXPECT_EQ(*map[bpf::Name("test3")], 9); } #ifdef BUILD_DEBUG static void RunLeakCheckBody() { HashMap<String, UniquePtr<int>> map; map["test1"] = nullptr; map["test2"] = nullptr; map["test3"] = nullptr; EXPECT_EQ(map["test1"], nullptr); EXPECT_EQ(map["test2"], nullptr); EXPECT_EQ(map["test3"], nullptr); map["test1"] = MakeUnique<int>(0); map["test2"] = MakeUnique<int>(5); map["test3"] = MakeUnique<int>(9); EXPECT_EQ(*map["test1"], 0); EXPECT_EQ(*map["test2"], 5); EXPECT_EQ(*map["test3"], 9); map["test3"] = nullptr; } TEST(HashMap, ReadWrite_LeakCheck) { fsize count = Memory::GetAllocCount(); RunLeakCheckBody(); EXPECT_EQ(count, Memory::GetAllocCount()); } #endif TEST(HashMap, Swap_1) { HashMap<int, int> lst; lst.Add(0, 0); lst.Add(1, 3); lst.Add(2, 7); lst.Swap(lst.begin(), --(--lst.end())); EXPECT_STREQ(*String::ValueOf(lst), "{'0': 3, '1': 0, '2': 7}"); } TEST(HashMap, Swap_2) { HashMap<int, int> lst; lst.Add(0, 0); lst.Add(1, 3); lst.Add(2, 7); lst.Swap(++lst.begin(), --lst.end()); EXPECT_STREQ(*String::ValueOf(lst), "{'0': 0, '1': 7, '2': 3}"); } TEST(HashMap, Swap_3) { HashMap<int, int> lst; lst.Add(0, 0); lst.Add(1, 7); lst.Swap(lst.begin(), --lst.end()); EXPECT_STREQ(*String::ValueOf(lst), "{'0': 7, '1': 0}"); } TEST(HashMap, Swap_4) { HashMap<int, UniquePtr<int>> lst; lst.Add(0, MakeUnique<int>(0)); lst.Add(1, MakeUnique<int>(7)); lst.Swap(lst.begin(), --lst.end()); } TEST(HashMap, Swap_Err_1) { HashMap<int, UniquePtr<int>> lst; lst.Swap(lst.begin(), --lst.end()); } TEST(HashMap, Swap_Err_2) { HashMap<int, int> lst; lst.Add(0, 0); lst.Add(1, 7); lst.Swap(lst.begin(), lst.begin()); lst.Swap(lst.end(), lst.end()); lst.Swap(--lst.end(), --lst.end()); EXPECT_STREQ(*String::ValueOf(lst), "{'0': 0, '1': 7}"); }
24.29805
104
0.542474
BlockProject3D
3109ae70bd42dca4f57abbda909aff86f6236ed1
8,269
cpp
C++
7_Queens/7_Queens.cpp
eduherminio/Academic_ArtificialIntelligence
f0ec4d35cef64a1bf6841ea7ecf1d33017b3745f
[ "MIT" ]
3
2017-05-16T22:25:16.000Z
2019-05-07T16:12:21.000Z
7_Queens/7_Queens.cpp
eduherminio/Academic_ArtificialIntelligence
f0ec4d35cef64a1bf6841ea7ecf1d33017b3745f
[ "MIT" ]
null
null
null
7_Queens/7_Queens.cpp
eduherminio/Academic_ArtificialIntelligence
f0ec4d35cef64a1bf6841ea7ecf1d33017b3745f
[ "MIT" ]
null
null
null
#include "header/nodo_reinas.h" #include "header/problema_csp.h" #include <iostream> #include <iomanip> const unsigned dimension = 15; const size_t iteraciones_max = 1000; const size_t n_problemas = 1000; typedef problema_csp::Problema_csp<nodo_reinas::Nodo_reinas> type_queens_noset; typedef problema_csp::Problema_csp<nodo_reinas::Nodo_reinas_set> type_queens_set; void single_sample(type_queens_noset problema, type_queens_set problema_set); void multiple_sample(type_queens_noset problema, type_queens_set problema_set); int main() { nodo_reinas::Nodo_reinas nodo_inicial(dimension, {}); // Nodo sin set, vector vacio inicial nodo_reinas::Nodo_reinas_set nodo_inicial_set(dimension, {}); //Nodo con set, vector vacio inicial problema_csp::Problema_csp<nodo_reinas::Nodo_reinas> problema(nodo_inicial); problema_csp::Problema_csp<nodo_reinas::Nodo_reinas_set> problema_set(nodo_inicial_set); single_sample(problema, problema_set); // Showing the position of the queens std::cout << "\n\n*************************************************************************" << std::endl; std::cout << "*************************************************************************\n\n" << std::endl; multiple_sample(problema, problema_set); // Showing stats after solving n_problemas return 0; } void single_sample(type_queens_noset problema, type_queens_set problema_set) { size_t iteraciones; std::cout << std::endl << "\t\t\t\tComplete example: " << std::endl << std::endl; // PROFUNDIDAD SIN SET if (problema.profundidad()) { std::cout << "\nPROFUNDIDAD SIN SET\n"; nodo_reinas::imprime_posicion(problema.get_solucion(), problema.get_nodos_expandidos()); } // PROFUNDIDAD CON SET if (problema_set.profundidad()) { std::cout << "\nPROFUNDIDAD CON SET\n"; nodo_reinas::imprime_posicion(problema_set.get_solucion(), problema.get_nodos_expandidos()); } // LAS_VEGAS_EXPANDIR SIN SET iteraciones = iteraciones_max; if (problema.las_vegas_expandir(iteraciones)) { std::cout << "\nLAS_VEGAS_EXPANDIR SIN SET\n"; nodo_reinas::imprime_posicion(problema.get_solucion(), problema.get_nodos_expandidos()); } std::cout << "Numero de iteraciones: " << iteraciones << std::endl; // LAS_VEGAS_EXPANDIR CON SET iteraciones = iteraciones_max; if (problema_set.las_vegas_expandir(iteraciones)) { std::cout << "\nLAS_VEGAS_EXPANDIR CON SET\n"; nodo_reinas::imprime_posicion(problema_set.get_solucion(), problema.get_nodos_expandidos()); } std::cout << "Numero de iteraciones: " << iteraciones << std::endl; // LAS_VEGAS_SUCESOR_ALEATORIO SIN SET iteraciones = iteraciones_max; if (problema.las_vegas_sucesor_aleatorio(iteraciones)) { std::cout << "\nLAS VEGAS SUCESOR ALEATORIO SIN SET\n"; nodo_reinas::imprime_posicion(problema.get_solucion(), problema.get_nodos_expandidos()); } std::cout << "Numero de iteraciones: " << iteraciones << std::endl; // LAS_VEGAS_SUCESOR_ALEATORIO CON SET iteraciones = iteraciones_max; if (problema_set.las_vegas_sucesor_aleatorio(iteraciones)) { std::cout << "\nLAS VEGAS SUCESOR ALEATORIO CON SET\n"; nodo_reinas::imprime_posicion(problema_set.get_solucion(), problema.get_nodos_expandidos()); } std::cout << "Numero de iteraciones: " << iteraciones << std::endl; } void multiple_sample(type_queens_noset problema, type_queens_set problema_set) { auto t = std::time(nullptr); tm tm; #if _MSC_VER && !__INTEL_COMPILER ::localtime_s(&tm, &t); #else tm = *std::localtime(&t); #endif double nodos_promedio_profundidad_no_set; double nodos_promedio_profundidad_set; double nodos_promedio_lasvegas_expandir_no_set; double nodos_promedio_lasvegas_expandir_set; double nodos_promedio_lasvegas_sucesor_no_set; double nodos_promedio_lasvegas_sucesor_set; double iteraciones_promedio_expandir_no_set; double iteraciones_promedio_expandir_set; double iteraciones_promedio_sucesor_no_set; double iteraciones_promedio_sucesor_set; size_t counter = 0; std::cout << "\t\t\t" << std::put_time(&tm, "%d-%m-%Y %H:%M:%S") << std::endl; std::cout << "\t\t\tNumber of Queens: " << dimension << std::endl; std::cout << "\t\t\tMax. iterations: " << iteraciones_max << std::endl; std::cout << "\tProcessing " << n_problemas << " samples to get statistical results" << std::endl; std::cout << "\t\t\t\t(...)" << std::endl << std::endl; while (true) { size_t iteraciones; static size_t nodos_expandidos_profundidad_set = 0; static size_t nodos_expandidos_profundidad_no_set = 0; static size_t nodos_expandidos_lasvegas_expandir_set = 0; static size_t nodos_expandidos_lasvegas_expandir_no_set = 0; static size_t nodos_expandidos_lasvegas_sucesor_set = 0; static size_t nodos_expandidos_lasvegas_sucesor_no_set = 0; static size_t iteraciones_expandir_no_set = 0; static size_t iteraciones_expandir_set = 0; static size_t iteraciones_sucesor_no_set = 0; static size_t iteraciones_sucesor_set = 0; // PROFUNDIDAD SIN SET problema.profundidad(); nodos_expandidos_profundidad_no_set += problema.get_nodos_expandidos(); // PROFUNDIDAD CON SET problema_set.profundidad(); nodos_expandidos_profundidad_set += problema.get_nodos_expandidos(); // LAS_VEGAS_EXPANDIR SIN SET iteraciones = iteraciones_max; problema.las_vegas_expandir(iteraciones); nodos_expandidos_lasvegas_expandir_no_set += problema.get_nodos_expandidos(); iteraciones_expandir_no_set += iteraciones; // LAS_VEGAS_EXPANDIR CON SET iteraciones = iteraciones_max; problema_set.las_vegas_expandir(iteraciones); nodos_expandidos_lasvegas_expandir_set += problema.get_nodos_expandidos(); iteraciones_expandir_set += iteraciones; // LAS_VEGAS_SUCESOR_ALEATORIO SIN SET iteraciones = iteraciones_max; problema.las_vegas_sucesor_aleatorio(iteraciones); nodos_expandidos_lasvegas_sucesor_no_set += problema.get_nodos_expandidos(); iteraciones_sucesor_no_set += iteraciones; // LAS_VEGAS_SUCESOR_ALEATORIO CON SET iteraciones = iteraciones_max; problema_set.las_vegas_sucesor_aleatorio(iteraciones); nodos_expandidos_lasvegas_sucesor_set += problema.get_nodos_expandidos(); iteraciones_sucesor_set += iteraciones; ++counter; if (counter == n_problemas) { nodos_promedio_profundidad_no_set = (double)nodos_expandidos_profundidad_no_set / counter; nodos_promedio_profundidad_set = (double)nodos_expandidos_profundidad_set / counter; nodos_promedio_lasvegas_expandir_no_set = (double)nodos_expandidos_lasvegas_expandir_no_set / counter; nodos_promedio_lasvegas_expandir_set = (double)nodos_expandidos_lasvegas_expandir_set / counter; nodos_promedio_lasvegas_sucesor_no_set = (double)nodos_expandidos_lasvegas_sucesor_no_set / counter; nodos_promedio_lasvegas_sucesor_set = (double)nodos_expandidos_lasvegas_sucesor_set / counter; iteraciones_promedio_expandir_no_set = (double)iteraciones_expandir_no_set / counter; iteraciones_promedio_expandir_set = (double)iteraciones_expandir_set / counter; iteraciones_promedio_sucesor_no_set = (double)iteraciones_sucesor_no_set / counter; iteraciones_promedio_sucesor_set = (double)iteraciones_sucesor_set / counter; break; } } std::cout << std::endl; std::cout << "-----------------------------------------------------------------------" << std::endl; std::cout << "\tAlgoritmo\t Nodos promedio\tIteraciones promedio\n" << std::endl; std::cout << "\tProf_no_set\t\t" << nodos_promedio_profundidad_no_set << std::endl; std::cout << "\tProf_set\t\t" << nodos_promedio_profundidad_set << std::endl; std::cout << "\tVegas_exp_no_set\t" << nodos_promedio_lasvegas_expandir_no_set << "\t\t\t"; std::cout << iteraciones_promedio_expandir_no_set << std::endl; std::cout << "\tVegas_exp_set\t\t" << nodos_promedio_lasvegas_expandir_set << "\t\t\t"; std::cout << iteraciones_promedio_expandir_set << std::endl; std::cout << "\tVegas_suc_no_set\t" << nodos_promedio_lasvegas_sucesor_no_set << "\t\t\t"; std::cout << iteraciones_promedio_sucesor_no_set << std::endl; std::cout << "\tVegas_suc_set\t\t" << nodos_promedio_lasvegas_sucesor_set << "\t\t\t"; std::cout << iteraciones_promedio_sucesor_set << std::endl; std::cout << "-----------------------------------------------------------------------" << std::endl; std::cout << std::endl; }
40.336585
107
0.743137
eduherminio
310c914eacea5d740c7c0b8b0d24c9615f52d05a
1,367
cpp
C++
all/native/geometry/WKTGeometryReader.cpp
JianYT/mobile-sdk
1835603e6cb7994222fea681928dc90055816628
[ "BSD-3-Clause" ]
155
2016-10-20T08:39:13.000Z
2022-02-27T14:08:32.000Z
all/native/geometry/WKTGeometryReader.cpp
JianYT/mobile-sdk
1835603e6cb7994222fea681928dc90055816628
[ "BSD-3-Clause" ]
448
2016-10-20T12:33:06.000Z
2022-03-22T14:42:58.000Z
all/native/geometry/WKTGeometryReader.cpp
JianYT/mobile-sdk
1835603e6cb7994222fea681928dc90055816628
[ "BSD-3-Clause" ]
64
2016-12-05T16:04:31.000Z
2022-02-07T09:36:22.000Z
#ifdef _CARTO_WKBT_SUPPORT #include "WKTGeometryReader.h" #include "components/Exceptions.h" #include "geometry/Geometry.h" #include "geometry/PointGeometry.h" #include "geometry/LineGeometry.h" #include "geometry/PolygonGeometry.h" #include "geometry/MultiGeometry.h" #include "geometry/MultiPointGeometry.h" #include "geometry/MultiLineGeometry.h" #include "geometry/MultiPolygonGeometry.h" #include "geometry/WKTGeometryParser.h" #include "utils/Log.h" #include <memory> #include <cstddef> #include <vector> #include <stack> #include <stdexcept> namespace carto { WKTGeometryReader::WKTGeometryReader() { } std::shared_ptr<Geometry> WKTGeometryReader::readGeometry(const std::string& wkt) const { std::string::const_iterator it = wkt.begin(); std::string::const_iterator end = wkt.end(); WKTGeometryParserImpl::encoding::space_type space; std::shared_ptr<Geometry> geometry; bool result = boost::spirit::qi::phrase_parse(it, end, WKTGeometryParser<std::string::const_iterator>(), space, geometry); if (!result) { throw ParseException("Failed to parse WKT geometry", wkt); } else if (it != wkt.end()) { throw ParseException("Could not parse to the end of WKT geometry", wkt, static_cast<int>(it - wkt.begin())); } return geometry; } } #endif
31.068182
130
0.699342
JianYT
3112f1173918bf0caabba1a67bd9bddc197d155b
7,235
cpp
C++
src-cpp/src/AST/ASTDumper.cpp
allen880117/NCTU-compiler-f19-hw4
0e2f9ed1d5870ae9909222b10cc0c9757bc6d51d
[ "MIT" ]
1
2020-12-10T18:25:48.000Z
2020-12-10T18:25:48.000Z
src/src/AST/ASTDumper.cpp
allen880117/NCTU-compiler-f19-hw4
0e2f9ed1d5870ae9909222b10cc0c9757bc6d51d
[ "MIT" ]
null
null
null
src/src/AST/ASTDumper.cpp
allen880117/NCTU-compiler-f19-hw4
0e2f9ed1d5870ae9909222b10cc0c9757bc6d51d
[ "MIT" ]
1
2020-12-21T11:49:22.000Z
2020-12-21T11:49:22.000Z
#include "AST/ASTDumper.hpp" #include "AST/program.hpp" #include "AST/declaration.hpp" #include "AST/variable.hpp" #include "AST/constant_value.hpp" #include "AST/function.hpp" #include "AST/compound_statement.hpp" #include "AST/assignment.hpp" #include "AST/print.hpp" #include "AST/read.hpp" #include "AST/variable_reference.hpp" #include "AST/binary_operator.hpp" #include "AST/unary_operator.hpp" #include "AST/if.hpp" #include "AST/while.hpp" #include "AST/for.hpp" #include "AST/return.hpp" #include "AST/function_call.hpp" #include <iostream> void ASTDumper::visit(ProgramNode *m) { this->print_space(); m->print(); this->space_counter_increase(); if (m->declaration_node_list != nullptr) for(uint i=0; i< m->declaration_node_list->size(); i++){ (*(m->declaration_node_list))[i]->accept(*this); } if (m->function_node_list != nullptr) for(uint i=0; i< m->function_node_list->size(); i++){ (*(m->function_node_list))[i]->accept(*this); } if (m->compound_statement_node != nullptr) m->compound_statement_node->accept(*this); this->space_counter_decrease(); } void ASTDumper::visit(DeclarationNode *m) { this->print_space(); m->print(); this->space_counter_increase(); if (m->variables_node_list != nullptr) for(uint i=0; i< m->variables_node_list->size(); i++){ (*(m->variables_node_list))[i]->accept(*this); } this->space_counter_decrease(); } void ASTDumper::visit(VariableNode *m) { this->print_space(); m->print(); this->space_counter_increase(); if (m->constant_value_node != nullptr) m->constant_value_node->accept(*this); this->space_counter_decrease(); } void ASTDumper::visit(ConstantValueNode *m) { this->print_space(); m->print(); // this->space_counter_increase(); // this->space_counter_decrease(); } void ASTDumper::visit(FunctionNode *m) { this->print_space(); m->print(); this->space_counter_increase(); if (m->parameters != nullptr) for(uint i=0; i< m->parameters->size(); i++){ (*(m->parameters))[i]->node->accept(*this); } if (m->body != nullptr) m->body->accept(*this); this->space_counter_decrease(); } void ASTDumper::visit(CompoundStatementNode *m) { this->print_space(); m->print(); this->space_counter_increase(); if (m->declaration_node_list != nullptr) for(uint i=0; i< m->declaration_node_list->size(); i++){ (*(m->declaration_node_list))[i]->accept(*this); } if (m->statement_node_list != nullptr) for(uint i=0; i< m->statement_node_list->size(); i++){ (*(m->statement_node_list))[i]->accept(*this); } this->space_counter_decrease(); } void ASTDumper::visit(AssignmentNode *m) { this->print_space(); m->print(); this->space_counter_increase(); if (m->variable_reference_node != nullptr) m->variable_reference_node->accept(*this); if (m->expression_node != nullptr) m->expression_node->accept(*this); this->space_counter_decrease(); } void ASTDumper::visit(PrintNode *m) { this->print_space(); m->print(); this->space_counter_increase(); if (m->expression_node != nullptr) m->expression_node->accept(*this); this->space_counter_decrease(); } void ASTDumper::visit(ReadNode *m) { this->print_space(); m->print(); this->space_counter_increase(); if (m->variable_reference_node != nullptr) m->variable_reference_node->accept(*this); this->space_counter_decrease(); } void ASTDumper::visit(VariableReferenceNode *m) { this->print_space(); m->print(); if (m->expression_node_list != nullptr) for(uint i=0; i< m->expression_node_list->size(); i++){ this->print_space(); std::cout<<"["<<std::endl; this->space_counter_increase(); (*(m->expression_node_list))[i]->accept(*this); this->space_counter_decrease(); this->print_space(); std::cout<<"]"<<std::endl; } } void ASTDumper::visit(BinaryOperatorNode *m) { this->print_space(); m->print(); this->space_counter_increase(); if (m->left_operand != nullptr) m->left_operand->accept(*this); if (m->right_operand != nullptr) m->right_operand->accept(*this); this->space_counter_decrease(); } void ASTDumper::visit(UnaryOperatorNode *m) { this->print_space(); m->print(); this->space_counter_increase(); if (m->operand != nullptr) m->operand->accept(*this); this->space_counter_decrease(); } void ASTDumper::visit(IfNode *m) { this->print_space(); m->print(); this->space_counter_increase(); if (m->condition != nullptr) m->condition->accept(*this); if (m->body != nullptr) for(uint i=0; i< m->body->size(); i++) (*(m->body))[i]->accept(*this); this->space_counter_decrease(); if (m->body_of_else != nullptr){ this->print_space(); std::cout<<"else"<<std::endl; this->space_counter_increase(); for(uint i=0; i< m->body_of_else->size(); i++) (*(m->body_of_else))[i]->accept(*this); this->space_counter_decrease(); } } void ASTDumper::visit(WhileNode *m) { this->print_space(); m->print(); this->space_counter_increase(); if (m->condition != nullptr) m->condition->accept(*this); if (m->body != nullptr) for(uint i=0; i< m->body->size(); i++) (*(m->body))[i]->accept(*this); this->space_counter_decrease(); } void ASTDumper::visit(ForNode *m) { this->print_space(); m->print(); this->space_counter_increase(); if (m->loop_variable_declaration != nullptr) m->loop_variable_declaration->accept(*this); if (m->initial_statement != nullptr) m->initial_statement->accept(*this); if (m->condition != nullptr) m->condition->accept(*this); if (m->body != nullptr) for(uint i=0; i< m->body->size(); i++) (*(m->body))[i]->accept(*this); this->space_counter_decrease(); } void ASTDumper::visit(ReturnNode *m) { this->print_space(); m->print(); this->space_counter_increase(); if (m->return_value != nullptr) m->return_value->accept(*this); this->space_counter_decrease(); } void ASTDumper::visit(FunctionCallNode *m) { this->print_space(); m->print(); this->space_counter_increase(); if (m->arguments != nullptr) for(uint i=0; i< m->arguments->size(); i++) (*(m->arguments))[i]->accept(*this); this->space_counter_decrease(); }
28.372549
68
0.566413
allen880117
311438a5c563372afc3e663c16bcee5b69593c16
1,823
cpp
C++
qt-mvvm/source/libmvvm_viewmodel/mvvm/viewmodel/standardviewitems.cpp
seaCheng/animation-
89a0cb0efbcfea202965a5851979ae6f1b67f8f0
[ "BSD-3-Clause" ]
6
2021-12-08T03:09:47.000Z
2022-02-24T03:51:14.000Z
qt-mvvm/source/libmvvm_viewmodel/mvvm/viewmodel/standardviewitems.cpp
seaCheng/animation-
89a0cb0efbcfea202965a5851979ae6f1b67f8f0
[ "BSD-3-Clause" ]
null
null
null
qt-mvvm/source/libmvvm_viewmodel/mvvm/viewmodel/standardviewitems.cpp
seaCheng/animation-
89a0cb0efbcfea202965a5851979ae6f1b67f8f0
[ "BSD-3-Clause" ]
null
null
null
// ************************************************************************** // // // Model-view-view-model framework for large GUI applications // //! @license GNU General Public License v3 or higher (see COPYING) //! @authors see AUTHORS // // ************************************************************************** // #include "mvvm/viewmodel/standardviewitems.h" #include "mvvm/model/sessionitem.h" #include "mvvm/viewmodel/viewmodelutils.h" using namespace ModelView; RootViewItem::RootViewItem(SessionItem* item) : ViewItem(item, ItemDataRole::DATA) {} //! --------------------------------------------------------------------------- ViewLabelItem::ViewLabelItem(SessionItem* item) : ViewItem(item, ItemDataRole::DISPLAY) {} QVariant ViewLabelItem::data(int role) const { if (!item()) return QVariant(); // use item's display role if (role == Qt::DisplayRole || role == Qt::EditRole) return QString::fromStdString(item()->displayName()); return ViewItem::data(role); } //! --------------------------------------------------------------------------- ViewDataItem::ViewDataItem(SessionItem* item) : ViewItem(item, ItemDataRole::DATA) {} Qt::ItemFlags ViewDataItem::flags() const { Qt::ItemFlags result = ViewItem::flags(); if (item() && item()->isEditable() && item()->isEnabled() && item()->data<QVariant>().isValid()) result |= Qt::ItemIsEditable; return result; } QVariant ViewDataItem::data(int role) const { if (role == Qt::DecorationRole) return Utils::DecorationRole(*item()); else if (role == Qt::CheckStateRole) return Utils::CheckStateRole(*item()); return ViewItem::data(role); } ViewEmptyItem::ViewEmptyItem() : ViewItem(nullptr, 0) {} QVariant ViewEmptyItem::data(int) const { return QVariant(); }
28.936508
100
0.56226
seaCheng
31145378480841bc41815445bf90027f49882f58
2,639
hpp
C++
Light/include/light/rendering/framebuffer.hpp
R-Bread/Light
151308c0159c4fe0d795b3c16f205e4af68710d7
[ "MIT" ]
1
2021-06-15T09:53:47.000Z
2021-06-15T09:53:47.000Z
Light/include/light/rendering/framebuffer.hpp
R-Bread/Light
151308c0159c4fe0d795b3c16f205e4af68710d7
[ "MIT" ]
21
2021-06-10T09:07:19.000Z
2022-01-30T21:52:24.000Z
Light/include/light/rendering/framebuffer.hpp
R-Bread/Light
151308c0159c4fe0d795b3c16f205e4af68710d7
[ "MIT" ]
9
2021-04-10T19:32:11.000Z
2021-05-19T16:29:25.000Z
#ifndef __FRAMEBUFFER_H__ #define __FRAMEBUFFER_H__ #include "core/base.hpp" namespace Light { enum class FramebufferTextureFormat { None, // Color Buffers RGBA8, RED_INTEGER, // Depth Buffers DEPTH24_STENCIL8, // Default depth Depth = DEPTH24_STENCIL8, /** * @brief First index of Depth Type attachment * @example Use like if(fmt < FramebufferAttachmentFormat::DepthType) { // Code for color buffers } */ DepthTypes = DEPTH24_STENCIL8 }; enum class TextureWrap { None, REPEAT, MIRRORED_REPEAT, CLAMP_TO_BORDER, CLAMP_TO_EDGE }; struct FramebufferTextureSpec { FramebufferTextureFormat textureFormat = FramebufferTextureFormat::None; TextureWrap wrapFormat = TextureWrap::None; FramebufferTextureSpec() = default; FramebufferTextureSpec( FramebufferTextureFormat format, TextureWrap wrap) : textureFormat(format), wrapFormat(wrap) {} }; struct FramebufferAttachmentsSpec { std::vector<FramebufferTextureSpec> attachments; FramebufferAttachmentsSpec() = default; FramebufferAttachmentsSpec( std::initializer_list<FramebufferTextureSpec> attachmentList) : attachments(attachmentList) {} std::vector<FramebufferTextureSpec>::iterator begin() { return attachments.begin(); } std::vector<FramebufferTextureSpec>::iterator end() { return attachments.end(); } std::vector<FramebufferTextureSpec>::const_iterator begin() const { return attachments.begin(); } std::vector<FramebufferTextureSpec>::const_iterator end() const { return attachments.end(); } }; struct FramebufferSpec { uint32_t width, height; uint32_t samples = 1; FramebufferAttachmentsSpec attachments; bool swapChainTarget = false; }; class Framebuffer { public: Framebuffer() = default; virtual ~Framebuffer() = default; virtual const FramebufferSpec& getSpec() const = 0; virtual uint32_t getColorAttachmentRendererId(uint32_t attachmentIndex = 0) const = 0; virtual void resize(uint32_t width, uint32_t height) = 0; virtual int readPixelInt(uint32_t attachmentIndex, uint32_t x, uint32_t y) = 0; virtual glm::vec4 readPixelVec4(uint32_t attachmentIndex, uint32_t x, uint32_t y) = 0; virtual void clearAttachment(uint32_t attachmentIndex, int clearValue) = 0; virtual void clearAttachment(uint32_t attachmentIndex, glm::vec4 clearValue) = 0; virtual void clearDepthAttachment() = 0; virtual void bind() = 0; virtual void unbind() = 0; virtual void bindAttachmentTexture(uint32_t attachmentIndex, uint32_t slot) = 0; static std::shared_ptr<Framebuffer> create(const FramebufferSpec& spec); }; } #endif // __FRAMEBUFFER_H__
25.375
101
0.750663
R-Bread
311ab21746a058d062ea864e75831f091f8667de
6,083
cpp
C++
test/class.cpp
16tons/camp
3edae6d6a06036bac5faf4e7b9e7b5dd8e463af8
[ "MIT" ]
1
2018-08-07T22:32:55.000Z
2018-08-07T22:32:55.000Z
test/class.cpp
16tons/camp
3edae6d6a06036bac5faf4e7b9e7b5dd8e463af8
[ "MIT" ]
null
null
null
test/class.cpp
16tons/camp
3edae6d6a06036bac5faf4e7b9e7b5dd8e463af8
[ "MIT" ]
null
null
null
/**************************************************************************** ** ** This file is part of the CAMP library. ** ** The MIT License (MIT) ** ** Copyright (C) 2009-2014 TEGESO/TEGESOFT and/or its subsidiary(-ies) and mother company. ** Contact: Tegesoft Information ([email protected]) ** ** 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 "class.hpp" #include <camp/classget.hpp> #include <boost/test/unit_test.hpp> using namespace ClassTest; //----------------------------------------------------------------------------- // Tests for camp::Class //----------------------------------------------------------------------------- BOOST_AUTO_TEST_SUITE(CLASS) //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(declare) { std::size_t count = camp::classCount(); camp::Class::declare<MyTempClass>(); BOOST_CHECK_EQUAL(camp::classCount(), count + 1); } //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(declareExceptions) { // to make sure it is declared camp::classByType<MyClass>(); BOOST_CHECK_THROW(camp::Class::declare<MyClass>(), camp::ClassAlreadyCreated); BOOST_CHECK_THROW(camp::Class::declare<MyUndeclaredClass>(), camp::ClassAlreadyCreated); } //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(get) { MyClass object; MyUndeclaredClass object2; BOOST_CHECK_EQUAL(camp::classById("ClassTest::MyClass").name(), "ClassTest::MyClass"); BOOST_CHECK_EQUAL(camp::classByType<MyClass>().name(), "ClassTest::MyClass"); BOOST_CHECK_EQUAL(camp::classByObject(object).name(), "ClassTest::MyClass"); BOOST_CHECK_EQUAL(camp::classByObject(&object).name(), "ClassTest::MyClass"); BOOST_CHECK_EQUAL(camp::classByTypeSafe<MyUndeclaredClass>(), static_cast<camp::Class*>(0)); BOOST_CHECK_THROW(camp::classById("ClassTest::MyUndeclaredClass"), camp::ClassNotFound); BOOST_CHECK_THROW(camp::classByType<MyUndeclaredClass>(), camp::ClassNotFound); BOOST_CHECK_THROW(camp::classByObject(object2), camp::ClassNotFound); BOOST_CHECK_THROW(camp::classByObject(&object2), camp::ClassNotFound); } //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(comparisons) { const camp::Class& class1 = camp::classByType<MyClass>(); const camp::Class& class2 = camp::classByType<MyClass2>(); BOOST_CHECK(class1 == class1); BOOST_CHECK(class1 != class2); BOOST_CHECK(class2 != class1); } //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(properties) { const camp::Class& metaclass = camp::classByType<MyClass>(); BOOST_CHECK_EQUAL(metaclass.propertyCount(), 1U); BOOST_CHECK_EQUAL(metaclass.hasProperty("prop"), true); BOOST_CHECK_EQUAL(metaclass.hasProperty("xxxx"), false); } //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(functions) { const camp::Class& metaclass = camp::classByType<MyClass>(); BOOST_CHECK_EQUAL(metaclass.functionCount(), 1U); BOOST_CHECK_EQUAL(metaclass.hasFunction("func"), true); BOOST_CHECK_EQUAL(metaclass.hasFunction("xxxx"), false); } //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(inheritance) { const camp::Class& derived = camp::classByType<Derived>(); BOOST_CHECK_EQUAL(derived.baseCount(), 1U); BOOST_CHECK_EQUAL(derived.base(0).name(), "ClassTest::Base"); BOOST_CHECK_THROW(derived.base(1), camp::OutOfRange); } //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(rtti) { Base* base = new Base; Base* derived = new Derived; Base* nortti = new DerivedNoRtti; Base* nortti2 = new Derived2NoRtti; BOOST_CHECK_EQUAL(camp::classByObject(base).name(), "ClassTest::Base"); // base is really a base BOOST_CHECK_EQUAL(camp::classByObject(*base).name(), "ClassTest::Base"); BOOST_CHECK_EQUAL(camp::classByObject(derived).name(), "ClassTest::Derived"); // CAMP finds its real type thanks to CAMP_RTTI BOOST_CHECK_EQUAL(camp::classByObject(*derived).name(), "ClassTest::Derived"); BOOST_CHECK_EQUAL(camp::classByObject(nortti).name(), "ClassTest::Base"); // CAMP fails to find its derived type without CAMP_RTTI BOOST_CHECK_EQUAL(camp::classByObject(*nortti).name(), "ClassTest::Base"); BOOST_CHECK_EQUAL(camp::classByObject(nortti2).name(), "ClassTest::Derived"); // CAMP finds the closest derived type which has CAMP_RTTI BOOST_CHECK_EQUAL(camp::classByObject(*nortti2).name(), "ClassTest::Derived"); delete nortti2; delete nortti; delete derived; delete base; } BOOST_AUTO_TEST_SUITE_END()
42.243056
141
0.605458
16tons
311b9b6de9cf2b8939ff1f533a5e465e28ae1f03
274
cpp
C++
GameFramework/Base/RenderSystem/RsIndexBuffer.cpp
GavWood/tutorials
d5140129b6acd6d61f6feedcd352c12e4ebabd40
[ "BSD-2-Clause" ]
8
2017-10-26T14:26:55.000Z
2022-01-07T07:35:39.000Z
GameFramework/Base/RenderSystem/RsIndexBuffer.cpp
GavWood/tutorials
d5140129b6acd6d61f6feedcd352c12e4ebabd40
[ "BSD-2-Clause" ]
1
2017-09-28T08:21:04.000Z
2017-10-04T09:17:57.000Z
GameFramework/Base/RenderSystem/RsIndexBuffer.cpp
GavWood/Game-Framework
d5140129b6acd6d61f6feedcd352c12e4ebabd40
[ "BSD-2-Clause" ]
1
2021-07-21T17:37:33.000Z
2021-07-21T17:37:33.000Z
//////////////////////////////////////////////////////////////////////////////// /// RsIndexBuffer.cpp #include "RsIndexBuffer.h" BtU32 RsIndexBuffer::IndType_Short = 1 << 0; BtU32 RsIndexBuffer::IndType_Long = 1 << 2; BtU32 RsIndexBuffer::IndType_Dynamic = 1 << 3;
27.4
80
0.5
GavWood
31259d261d4adfffd84bc8e11c6e76537527de79
7,003
cpp
C++
src/lib/import_export/csv_parser.cpp
IanJamesMcKay/InMemoryDB
a267d9522926eca9add2ad4512f8ce352daac879
[ "MIT" ]
1
2021-04-14T11:16:52.000Z
2021-04-14T11:16:52.000Z
src/lib/import_export/csv_parser.cpp
IanJamesMcKay/InMemoryDB
a267d9522926eca9add2ad4512f8ce352daac879
[ "MIT" ]
null
null
null
src/lib/import_export/csv_parser.cpp
IanJamesMcKay/InMemoryDB
a267d9522926eca9add2ad4512f8ce352daac879
[ "MIT" ]
1
2020-11-30T13:11:04.000Z
2020-11-30T13:11:04.000Z
#include "csv_parser.hpp" #include <fstream> #include <functional> #include <list> #include <memory> #include <optional> #include <string> #include <string_view> #include <utility> #include <vector> #include "constant_mappings.hpp" #include "import_export/csv_converter.hpp" #include "import_export/csv_meta.hpp" #include "resolve_type.hpp" #include "scheduler/job_task.hpp" #include "storage/chunk_encoder.hpp" #include "storage/column_encoding_utils.hpp" #include "storage/table.hpp" #include "utils/assert.hpp" #include "utils/load_table.hpp" namespace opossum { std::shared_ptr<Table> CsvParser::parse(const std::string& filename, const std::optional<CsvMeta>& csv_meta) { // If no meta info is given as a parameter, look for a json file if (csv_meta == std::nullopt) { _meta = process_csv_meta_file(filename + CsvMeta::META_FILE_EXTENSION); } else { _meta = *csv_meta; } auto table = _create_table_from_meta(); std::ifstream csvfile{filename}; std::string content{std::istreambuf_iterator<char>(csvfile), {}}; // return empty table if input file is empty if (!csvfile) return table; // make sure content ends with a delimiter for better row processing later if (content.back() != _meta.config.delimiter) content.push_back(_meta.config.delimiter); std::string_view content_view{content.c_str(), content.size()}; // Save chunks in list to avoid memory relocation std::list<ChunkColumns> columns_by_chunks; std::vector<std::shared_ptr<JobTask>> tasks; std::vector<size_t> field_ends; while (_find_fields_in_chunk(content_view, *table, field_ends)) { // create empty chunk columns_by_chunks.emplace_back(); auto& columns = columns_by_chunks.back(); // Only pass the part of the string that is actually needed to the parsing task std::string_view relevant_content = content_view.substr(0, field_ends.back()); // Remove processed part of the csv content content_view = content_view.substr(field_ends.back() + 1); // create and start parsing task to fill chunk tasks.emplace_back(std::make_shared<JobTask>([this, relevant_content, field_ends, &table, &columns]() { _parse_into_chunk(relevant_content, field_ends, *table, columns); })); tasks.back()->schedule(); } for (auto& task : tasks) { task->join(); } for (auto& chunk_columns : columns_by_chunks) { table->append_chunk(chunk_columns); } if (_meta.auto_compress) ChunkEncoder::encode_all_chunks(table); return table; } std::shared_ptr<Table> CsvParser::_create_table_from_meta() { TableColumnDefinitions colum_definitions; for (const auto& column_meta : _meta.columns) { auto column_name = column_meta.name; BaseCsvConverter::unescape(column_name); auto column_type = column_meta.type; BaseCsvConverter::unescape(column_type); const auto data_type = data_type_to_string.right.at(column_type); colum_definitions.emplace_back(column_name, data_type, column_meta.nullable); } return std::make_shared<Table>(colum_definitions, TableType::Data, _meta.chunk_size, UseMvcc::Yes); } bool CsvParser::_find_fields_in_chunk(std::string_view csv_content, const Table& table, std::vector<size_t>& field_ends) { field_ends.clear(); if (csv_content.empty()) { return false; } std::string search_for{_meta.config.separator, _meta.config.delimiter, _meta.config.quote}; size_t pos, from = 0; unsigned int rows = 0, field_count = 1; bool in_quotes = false; while (rows < table.max_chunk_size() || 0 == table.max_chunk_size()) { // Find either of row separator, column delimiter, quote identifier pos = csv_content.find_first_of(search_for, from); if (std::string::npos == pos) { break; } from = pos + 1; const char elem = csv_content.at(pos); // Make sure to "toggle" in_quotes ONLY if the quotes are not part of the string (i.e. escaped) if (elem == _meta.config.quote) { bool quote_is_escaped = false; if (_meta.config.quote != _meta.config.escape) { quote_is_escaped = pos != 0 && csv_content.at(pos - 1) == _meta.config.escape; } if (!quote_is_escaped) { in_quotes = !in_quotes; } } // Determine if delimiter marks end of row or is part of the (string) value if (elem == _meta.config.delimiter && !in_quotes) { Assert(field_count == table.column_count(), "Number of CSV fields does not match number of columns."); ++rows; field_count = 0; } // Determine if separator marks end of field or is part of the (string) value if (in_quotes || elem == _meta.config.quote) { continue; } ++field_count; field_ends.push_back(pos); } return true; } size_t CsvParser::_parse_into_chunk(std::string_view csv_chunk, const std::vector<size_t>& field_ends, const Table& table, ChunkColumns& columns) { // For each csv column create a CsvConverter which builds up a ValueColumn const auto column_count = table.column_count(); const auto row_count = field_ends.size() / column_count; std::vector<std::unique_ptr<BaseCsvConverter>> converters; for (ColumnID column_id{0}; column_id < column_count; ++column_id) { const auto is_nullable = table.column_is_nullable(column_id); const auto column_type = table.column_data_type(column_id); converters.emplace_back( make_unique_by_data_type<BaseCsvConverter, CsvConverter>(column_type, row_count, _meta.config, is_nullable)); } size_t start = 0; for (size_t row_id = 0; row_id < row_count; ++row_id) { for (ColumnID column_id{0}; column_id < column_count; ++column_id) { const auto end = field_ends.at(row_id * column_count + column_id); auto field = std::string{csv_chunk.substr(start, end - start)}; start = end + 1; if (!_meta.config.rfc_mode) { // CSV fields not following RFC 4810 might need some preprocessing _sanitize_field(field); } try { converters[column_id]->insert(field, row_id); } catch (const std::exception& exception) { throw std::logic_error("Exception while parsing CSV, row " + std::to_string(row_id) + ", column " + std::to_string(column_id) + ":\n" + exception.what()); } } } // Transform the field_offsets to columns and add columns to chunk. for (auto& converter : converters) { columns.push_back(converter->finish()); } return row_count; } void CsvParser::_sanitize_field(std::string& field) { const std::string linebreak(1, _meta.config.delimiter); const std::string escaped_linebreak = std::string(1, _meta.config.delimiter_escape) + std::string(1, _meta.config.delimiter); std::string::size_type pos = 0; while ((pos = field.find(escaped_linebreak, pos)) != std::string::npos) { field.replace(pos, escaped_linebreak.size(), linebreak); pos += linebreak.size(); } } } // namespace opossum
33.830918
117
0.691561
IanJamesMcKay