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
e39b753b6cabd5be0caf1cfb97206065fdc29e2f
445
cpp
C++
src/register/ProgramRegister.cpp
openx86/emulator
829454a2dbc99ffa3ccdf81f7473e69f8b8ce896
[ "Apache-2.0" ]
1
2022-01-16T18:24:32.000Z
2022-01-16T18:24:32.000Z
src/register/ProgramRegister.cpp
openx86/emulator
829454a2dbc99ffa3ccdf81f7473e69f8b8ce896
[ "Apache-2.0" ]
null
null
null
src/register/ProgramRegister.cpp
openx86/emulator
829454a2dbc99ffa3ccdf81f7473e69f8b8ce896
[ "Apache-2.0" ]
null
null
null
// // Created by 86759 on 2022-01-14. // #include "ProgramRegister.h" //uint32_t ProgramRegister::IP_r = 0x1234FFF0; uint32_t ProgramRegister::IP_r = 0x0000FFF0; uint16_t ProgramRegister::IP() { return (uint16_t)IP_r; } uint32_t ProgramRegister::EIP() { return (uint32_t)IP_r; } void ProgramRegister::IP(uint16_t value) { auto* tmp = (uint16_t *)(&IP_r); *tmp = value; } void ProgramRegister::EIP(uint32_t value) { IP_r = value; }
34.230769
92
0.703371
openx86
e3a602a3aef9e02c33f422efc535c9a5d9eb82e6
3,467
cpp
C++
dialogs/dialoginfocontent.cpp
avttrue/fungus
c6ca9ef94317ecbe930da25606ca7331f048ef60
[ "MIT" ]
null
null
null
dialogs/dialoginfocontent.cpp
avttrue/fungus
c6ca9ef94317ecbe930da25606ca7331f048ef60
[ "MIT" ]
2
2020-08-20T05:04:33.000Z
2020-09-22T17:10:39.000Z
dialogs/dialoginfocontent.cpp
avttrue/fungus
c6ca9ef94317ecbe930da25606ca7331f048ef60
[ "MIT" ]
null
null
null
#include "dialoginfocontent.h" #include "properties.h" #include "helpers/helper.h" #include "helpers/widgethelper.h" #include "controls/separators.h" #include <QDebug> #include <QApplication> #include <QIcon> #include <QToolBar> #include <QVBoxLayout> #include <QTextBrowser> #include <QScrollBar> DialogInfoContent::DialogInfoContent(QWidget *parent, const QString& title) : DialogBody(parent, title, ":/resources/img/info.svg") { m_Content = new QTextBrowser(this); m_Content->setOpenLinks(false); QObject::connect(m_Content, &QTextBrowser::forwardAvailable, [=](bool value) { m_ActionForward->setEnabled(value); }); QObject::connect(m_Content, &QTextBrowser::backwardAvailable, [=](bool value) { m_ActionBackward->setEnabled(value); }); QObject::connect(m_Content, &QTextBrowser::anchorClicked, this, &DialogInfoContent::slotAnchorClicked); ToolBar()->setIconSize(QSize(config->ButtonSize(), config->ButtonSize())); m_ActionBackward = new QAction(QIcon(":/resources/img/left_arrow.svg"),tr("Backward")); QObject::connect(m_ActionBackward, &QAction::triggered, [=](){ m_Content->backward(); }); m_ActionBackward->setAutoRepeat(false); m_ActionBackward->setEnabled(false); addToolBarAction(ToolBar(), m_ActionBackward, CSS_TOOLBUTTON); m_ActionForward = new QAction(QIcon(":/resources/img/right_arrow.svg"), tr("Forward")); QObject::connect(m_ActionForward, &QAction::triggered, [=](){ m_Content->forward(); }); m_ActionForward->setAutoRepeat(false); m_ActionForward->setEnabled(false); addToolBarAction(ToolBar(), m_ActionForward, CSS_TOOLBUTTON); auto m_ActionHome = new QAction(QIcon(":/resources/img/up_arrow.svg"), tr("Main page")); QObject::connect(m_ActionHome, &QAction::triggered, [=](){ m_Content->home(); }); m_ActionHome->setAutoRepeat(false); addToolBarAction(ToolBar(), m_ActionHome, CSS_TOOLBUTTON); ToolBar()->addWidget(new WidgetSpacer()); addDialogContent(m_Content); resize(DIC_WINDOW_SIZE); QObject::connect(this, &QObject::destroyed, [=]() { qDebug() << "DialogInfoContent" << windowTitle() << "destroyed"; }); qDebug() << "DialogInfoContent" << windowTitle() << "created"; } void DialogInfoContent::slotAnchorClicked(const QUrl &link) { qDebug() << __func__; if(!link.isValid()) return; if(!link.toString().contains(QRegExp(EXTERN_URL_RG))) { auto source_page = m_Content->source().toString(); auto target_page = link.toString(); qDebug() << "Source page:" << source_page; qDebug() << "Target page:" << target_page; if(source_page.endsWith(HELP_PAGE_TRIGGER)) config->setHelpPage(target_page); auto res_type = m_Content->sourceType(); m_Content->setSource(link, res_type); return; } OpenUrl(link); } void DialogInfoContent::setHtmlContent(const QString& content) { m_Content->setHtml(content); } void DialogInfoContent::setMarkdownSource(const QString &source) { m_Content->setSource(QUrl(source), QTextDocument::MarkdownResource); } void DialogInfoContent::setMarkdownContent(const QString &content) { m_Content->document()->setMarkdown(content, QTextDocument::MarkdownDialectCommonMark); } void DialogInfoContent::scrollUp() { auto vScrollBar = m_Content->verticalScrollBar(); vScrollBar->triggerAction(QScrollBar::SliderToMinimum); }
34.326733
107
0.697721
avttrue
e3a76a7d5a9ad27f7f5c11215c2b9968dee26da7
1,123
cpp
C++
Knottenbelt/Week5/printpyramid.cpp
AnthonyChuah/CPPscripts
c8376c4bf191949fc31b4e70226a2c42f8e7f1c2
[ "bzip2-1.0.6" ]
null
null
null
Knottenbelt/Week5/printpyramid.cpp
AnthonyChuah/CPPscripts
c8376c4bf191949fc31b4e70226a2c42f8e7f1c2
[ "bzip2-1.0.6" ]
null
null
null
Knottenbelt/Week5/printpyramid.cpp
AnthonyChuah/CPPscripts
c8376c4bf191949fc31b4e70226a2c42f8e7f1c2
[ "bzip2-1.0.6" ]
null
null
null
#include <iostream> using namespace std; void print_pyramid(int height); // Prints a pyramid of specified height. Must be between 1 to 30 inclusive. int main() { int desired_height = 0; bool acceptable_input = false; cout << "This program prints a 'pyramid' shape of\n" << "a specified height on the screen.\n\n"; while (!(acceptable_input)) { cout << "How high would you like the pyramid? (1 to 30 inclusive): "; cin >> desired_height; if (desired_height >= 1 && desired_height <= 30) { acceptable_input = true; } else { acceptable_input = false; } } print_pyramid(desired_height); return 0; } void print_pyramid(int height) { int preceding_spaces = 0; int rownum = 0, num_stars = 0; for (int i = 0; i < height; i++) { preceding_spaces = height - 1 - i; // Print the preceding spaces. for (int j = 0; j < preceding_spaces; j++) cout << " "; // Print the stars. rownum = i + 1; num_stars = rownum * 2; for (int k = 0; k < num_stars; k++) cout << "*"; // Print a newline. cout << "\n"; } }
22.918367
75
0.593054
AnthonyChuah
e3ab727a12ecd7a103417cb4164ae11c8f1cbcb2
371
hpp
C++
include/vengine/core/ICvar.hpp
BlackPhrase/V-Engine
ee9a9c63a380732dace75bcc1e398cabc444feba
[ "MIT" ]
1
2018-06-22T15:46:42.000Z
2018-06-22T15:46:42.000Z
include/vengine/core/ICvar.hpp
BlackPhrase/V-Engine
ee9a9c63a380732dace75bcc1e398cabc444feba
[ "MIT" ]
3
2018-05-13T14:15:53.000Z
2018-05-29T08:06:26.000Z
include/vengine/core/ICvar.hpp
BlackPhrase/V-Engine
ee9a9c63a380732dace75bcc1e398cabc444feba
[ "MIT" ]
null
null
null
/// @file /// @brief console variable #pragma once struct ICvar { /// virtual const char *GetName() const = 0; /// virtual const char *GetDescription() const = 0; /// virtual void SetValue(const char *asValue) = 0; /// virtual const char *GetValue() const = 0; /// virtual const char *GetDefValue() const = 0; /// virtual void ResetValue() = 0; };
14.84
48
0.622642
BlackPhrase
e3af0bcfa99893069bb658d4565f8036db45a21a
1,128
cpp
C++
tests/basic_bvalue/test_events.cpp
fbdtemme/bencode
edf7dd5b580c44723821dbf737c8412d628294e4
[ "MIT" ]
25
2020-08-24T01:54:10.000Z
2021-12-22T08:55:54.000Z
tests/basic_bvalue/test_events.cpp
fbdtemme/bencode
edf7dd5b580c44723821dbf737c8412d628294e4
[ "MIT" ]
1
2021-12-29T05:38:56.000Z
2021-12-29T05:38:56.000Z
tests/basic_bvalue/test_events.cpp
fbdtemme/bencode
edf7dd5b580c44723821dbf737c8412d628294e4
[ "MIT" ]
4
2020-08-18T19:31:26.000Z
2022-02-01T18:57:51.000Z
// // Created by fbdtemme on 8/17/20. // #include <catch2/catch.hpp> #include <bencode/traits/all.hpp> #include "bencode/bvalue.hpp" #include <bencode/events/debug_to.hpp> #include <sstream> namespace bc = bencode; static const bc::bvalue b{ {"a", 1}, {"b", 1u}, {"d", false}, {"e", "string"}, {"f", std::vector{1, 2, 3, 4}} }; constexpr std::string_view b_events = R"(begin dict (size=5) string (const&) (size=1, value="a") dict key integer (1) dict value string (const&) (size=1, value="b") dict key integer (1) dict value string (const&) (size=1, value="d") dict key integer (0) dict value string (const&) (size=1, value="e") dict key string (const&) (size=6, value="string") dict value string (const&) (size=1, value="f") dict key begin list (size=4) integer (1) list item integer (2) list item integer (3) list item integer (4) list item end list dict value end dict )"; TEST_CASE("producing events from bvalue", "[bvalue][events]") { std::ostringstream os {}; auto consumer = bc::events::debug_to(os); bc::connect(consumer, b); CHECK(os.str() == b_events); }
17.625
61
0.636525
fbdtemme
e3b0dd6a5575aea71ec80c5b75359167d8ad7ff8
78
cpp
C++
test/llvm_test_code/inst_interaction/heap_01.cpp
janniclas/phasar
324302ae96795e6f0a065c14d4f7756b1addc2a4
[ "MIT" ]
1
2022-02-15T07:56:29.000Z
2022-02-15T07:56:29.000Z
test/llvm_test_code/inst_interaction/heap_01.cpp
fabianbs96/phasar
5b8acd046d8676f72ce0eb85ca20fdb0724de444
[ "MIT" ]
null
null
null
test/llvm_test_code/inst_interaction/heap_01.cpp
fabianbs96/phasar
5b8acd046d8676f72ce0eb85ca20fdb0724de444
[ "MIT" ]
null
null
null
int main() { int *i = new int(42); int j = *i; delete i; return j; }
9.75
23
0.487179
janniclas
e3b29b3ec003afca116f3c9e3d6618eb0bd3b6f7
3,083
cpp
C++
tc 160+/PrimeSequences.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/PrimeSequences.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/PrimeSequences.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> using namespace std; #define MAX_NUM_ 10000001 // 6bits = 1parity bit + 32 different offsets in the same int int P_[(MAX_NUM_>>6) + 1]; // negative logic (1 bit marks a non-prime) // for x >= 0 inline bool is_prime(int x) { return x==2 ? true : (x&1 ? !((P_[(x>>6)]>>((x>>1)&0x1f))&1) : false); } // only call for odd x inline void mark_nonprime(int x) { x >>= 1; P_[x>>5] |= (1<<(x&0x1f)); } void init_primes() { for (long long x=3; x<=MAX_NUM_; x+=2) { if (is_prime(x) && x<=MAX_NUM_/x) { const long long z = x<<1; for (long long y=x*x; y<=MAX_NUM_; y+=z) { mark_nonprime(y); } } } } char cnt[10000001]; class PrimeSequences { public: int getLargestGenerator(int N, int D) { init_primes(); memset(cnt, 0, sizeof cnt); cnt[2] = 1; for (int i=3; i<=N; ++i) { if (is_prime(i)) { const int x = i/2; cnt[i] = cnt[x] + 1; } } for (int i=N; i>=1; --i) { if (cnt[i] >= D) { return i; } } return -1; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 10; int Arg1 = 2; int Arg2 = 7; verify_case(0, Arg2, getLargestGenerator(Arg0, Arg1)); } void test_case_1() { int Arg0 = 42; int Arg1 = 3; int Arg2 = 23; verify_case(1, Arg2, getLargestGenerator(Arg0, Arg1)); } void test_case_2() { int Arg0 = 666; int Arg1 = 7; int Arg2 = -1; verify_case(2, Arg2, getLargestGenerator(Arg0, Arg1)); } void test_case_3() { int Arg0 = 1337; int Arg1 = 5; int Arg2 = 47; verify_case(3, Arg2, getLargestGenerator(Arg0, Arg1)); } void test_case_4() { int Arg0 = 100000; int Arg1 = 5; int Arg2 = 2879; verify_case(4, Arg2, getLargestGenerator(Arg0, Arg1)); } void test_case_5() { int Arg0 = 40000; int Arg1 = 1; int Arg2 = 39989; verify_case(5, Arg2, getLargestGenerator(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { PrimeSequences ___test; ___test.run_test(-1); } // END CUT HERE
41.662162
317
0.560817
ibudiselic
e3b5558af7210b6a155636a5a85cb56a32de785f
3,941
hpp
C++
libs/core/font/include/bksge/core/font/otf/feature_variations.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/core/font/include/bksge/core/font/otf/feature_variations.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/core/font/include/bksge/core/font/otf/feature_variations.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file feature_variations.hpp * * @brief FeatureVariations の定義 * * @author myoukaku */ #ifndef BKSGE_CORE_FONT_OTF_FEATURE_VARIATIONS_HPP #define BKSGE_CORE_FONT_OTF_FEATURE_VARIATIONS_HPP #include <bksge/core/font/otf/read_big_endian.hpp> #include <bksge/core/font/otf/types.hpp> #include <bksge/fnd/memory/unique_ptr.hpp> #include <bksge/fnd/memory/make_unique.hpp> #include <cstdint> #include <vector> namespace bksge { namespace otf { struct FeatureVariations { struct FeatureTableSubstitutionRecord { friend std::uint8_t const* ReadBigEndian( std::uint8_t const* ptr, FeatureTableSubstitutionRecord* dst, std::uint8_t const* start) { ptr = ReadBigEndian(ptr, &dst->featureIndex); ptr = ReadBigEndian(ptr, &dst->alternateFeatureOffset); if (dst->alternateFeatureOffset != 0) { // TODO //alternateFeature = bksge::make_unique<AlternateFeature>( // start + alternateFeatureOffset); (void)start; } return ptr; } uint16 featureIndex; Offset32 alternateFeatureOffset; }; struct FeatureTableSubstitution { explicit FeatureTableSubstitution(std::uint8_t const* ptr) { auto const start = ptr; uint16 majorVersion; uint16 minorVersion; uint16 substitutionCount; ptr = ReadBigEndian(ptr, &majorVersion); ptr = ReadBigEndian(ptr, &minorVersion); ptr = ReadBigEndian(ptr, &substitutionCount); substitutions.resize(substitutionCount); ptr = ReadBigEndian(ptr, &substitutions, start); } std::vector<FeatureTableSubstitutionRecord> substitutions; }; struct Condition { explicit Condition(std::uint8_t const* ptr) { ptr = ReadBigEndian(ptr, &Format); ptr = ReadBigEndian(ptr, &AxisIndex); ptr = ReadBigEndian(ptr, &FilterRangeMinValue); ptr = ReadBigEndian(ptr, &FilterRangeMaxValue); } uint16 Format; uint16 AxisIndex; F2DOT14 FilterRangeMinValue; F2DOT14 FilterRangeMaxValue; }; struct ConditionSet { explicit ConditionSet(std::uint8_t const* ptr) { auto const start = ptr; uint16 conditionCount; ptr = ReadBigEndian(ptr, &conditionCount); for (uint16 i = 0; i < conditionCount; ++i) { Offset32 conditionOffset; ptr = ReadBigEndian(ptr, &conditionOffset); conditions.emplace_back(start + conditionOffset); } } std::vector<Condition> conditions; }; struct FeatureVariationRecord { friend std::uint8_t const* ReadBigEndian( std::uint8_t const* ptr, FeatureVariationRecord* dst, std::uint8_t const* start) { Offset32 conditionSetOffset; Offset32 featureTableSubstitutionOffset; ptr = ReadBigEndian(ptr, &conditionSetOffset); ptr = ReadBigEndian(ptr, &featureTableSubstitutionOffset); if (conditionSetOffset != 0) { dst->conditionSet = bksge::make_unique<ConditionSet>( start + conditionSetOffset); } if (featureTableSubstitutionOffset != 0) { dst->featureTableSubstitution = bksge::make_unique<FeatureTableSubstitution>( start + featureTableSubstitutionOffset); } return ptr; } bksge::unique_ptr<ConditionSet> conditionSet; bksge::unique_ptr<FeatureTableSubstitution> featureTableSubstitution; }; explicit FeatureVariations(std::uint8_t const* ptr) { auto const start = ptr; uint16 majorVersion; uint16 minorVersion; uint32 featureVariationRecordCount; ptr = ReadBigEndian(ptr, &majorVersion); ptr = ReadBigEndian(ptr, &minorVersion); ptr = ReadBigEndian(ptr, &featureVariationRecordCount); featureVariationRecords.resize(featureVariationRecordCount); ptr = ReadBigEndian(ptr, &featureVariationRecords, start); } std::vector<FeatureVariationRecord> featureVariationRecords; }; } // namespace otf } // namespace bksge #endif // BKSGE_CORE_FONT_OTF_FEATURE_VARIATIONS_HPP
23.884848
72
0.700584
myoukaku
e3b88ecd795aecca9420e84d7bd0e9558d9f160b
16,020
cpp
C++
ParticlePlay/Core/Game.cpp
spywhere/Legacy-ParticlePlay
0c1ec6e4706f72b64e0408cc79cdeffce535b484
[ "BSD-3-Clause" ]
null
null
null
ParticlePlay/Core/Game.cpp
spywhere/Legacy-ParticlePlay
0c1ec6e4706f72b64e0408cc79cdeffce535b484
[ "BSD-3-Clause" ]
null
null
null
ParticlePlay/Core/Game.cpp
spywhere/Legacy-ParticlePlay
0c1ec6e4706f72b64e0408cc79cdeffce535b484
[ "BSD-3-Clause" ]
null
null
null
#include "Game.hpp" #ifdef PPDEBUG #include <iostream> #endif ppGame::ppGame(){ this->mainWindow = NULL; this->renderer = NULL; this->graphics = NULL; this->backgroundColor = new ppColor(); this->gameInput = new ppInput(this); this->gameIO = new ppIO(); this->randomizer = new ppRandomizer(); this->ims = NULL; this->title = "My Game"; this->currentState = NULL; this->screenWidth = 640; this->width = 640; this->screenHeight = 480; this->height = 480; this->targetFPS = 60; this->targetUPS = 60; this->running = false; this->restarting = false; this->resizable = false; this->fullscreen = false; this->showFPS = false; this->vSync = false; this->idleTime = 0; this->fps = 0; this->ups = 0; this->art = 0; this->aut = 0; } const char* ppGame::GetTitle(){ return this->title; } void ppGame::SetTitle(const char* title){ this->title = title; if(this->mainWindow){ SDL_SetWindowTitle(this->mainWindow, title); } } int ppGame::GetScreenWidth(){ return this->screenWidth; } int ppGame::GetScreenHeight(){ return this->screenHeight; } int ppGame::GetWidth(){ return this->width; } int ppGame::GetHeight(){ return this->height; } ppRandomizer* ppGame::GetRandomizer(){ return this->randomizer; } void ppGame::SetScreenSize(int width, int height){ this->screenWidth = width; this->screenHeight = height; this->SetSize(width, height); this->RestartGame(); } void ppGame::SetSize(int width, int height){ this->width = width; this->height = height; if(this->renderer){ SDL_RenderSetLogicalSize(this->renderer, this->width, this->height); } } bool ppGame::IsResizable(){ return this->resizable; } void ppGame::SetResizable(bool resizable){ this->resizable = resizable; this->RestartGame(); } bool ppGame::IsFullscreen(){ return this->fullscreen; } void ppGame::SetFullscreen(bool fullscreen){ this->fullscreen = fullscreen; this->RestartGame(); } void ppGame::OnEvent(SDL_Event* event) { switch(event->type){ case SDL_QUIT: if(!this->currentState || !this->currentState->OnEvent(event)){ this->running = false; } break; case SDL_KEYDOWN: case SDL_KEYUP: case SDL_MOUSEMOTION: case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: case SDL_MOUSEWHEEL: case SDL_JOYAXISMOTION: case SDL_JOYBALLMOTION: case SDL_JOYHATMOTION: case SDL_JOYBUTTONDOWN: case SDL_JOYBUTTONUP: case SDL_JOYDEVICEADDED: case SDL_JOYDEVICEREMOVED: case SDL_CONTROLLERAXISMOTION: case SDL_CONTROLLERBUTTONDOWN: case SDL_CONTROLLERBUTTONUP: case SDL_CONTROLLERDEVICEADDED: case SDL_CONTROLLERDEVICEREMOVED: case SDL_CONTROLLERDEVICEREMAPPED: case SDL_FINGERDOWN: case SDL_FINGERUP: case SDL_FINGERMOTION: case SDL_DOLLARGESTURE: case SDL_DOLLARRECORD: case SDL_MULTIGESTURE: if(!this->currentState || !this->currentState->OnEvent(event)){ this->gameInput->OnEvent(event); } break; case SDL_APP_TERMINATING: #ifdef PPDEBUG std::cout << "Getting force close..." << std::endl; #endif if(!this->currentState || !this->currentState->OnEvent(event)){ this->running = false; } break; case SDL_APP_LOWMEMORY: #ifdef PPDEBUG std::cout << "Low memory..." << std::endl; #endif if(this->currentState){ this->currentState->OnEvent(event); } break; case SDL_WINDOWEVENT: if(event->window.event == SDL_WINDOWEVENT_RESIZED){ this->SetScreenSize(event->window.data1, event->window.data2); } if(this->currentState){ this->currentState->OnEvent(event); } break; default: if(this->currentState){ this->currentState->OnEvent(event); } break; } } int ppGame::StartGame(){ #ifdef PPDEBUG std::cout << "Initializing SDL... "; #endif if(SDL_Init(SDL_INIT_EVERYTHING) < 0) { #ifndef PPDEBUG std::cout << "Error: "; #endif std::cout << SDL_GetError() << std::endl; return 1; } SDL_version sdlCompiledVersion; SDL_version sdlLinkedVersion; SDL_VERSION(&sdlCompiledVersion); SDL_GetVersion(&sdlLinkedVersion); if(SDL_VERSION_NUMBER(&sdlLinkedVersion) < SDL_VERSION_NUMBER(&sdlCompiledVersion)){ std::cout << "The installed SDL is not compatible. [" << SDL_VERSION_CONCAT(&sdlLinkedVersion) << "<" << SDL_VERSION_CONCAT(&sdlCompiledVersion) << "]" << std::endl; return 1; } #ifdef PPDEBUG std::cout << "v" << SDL_VERSION_CONCAT(&sdlLinkedVersion) << std::endl; std::cout << "Initializing SDL_image... "; #endif int imgFlags = IMG_INIT_JPG|IMG_INIT_PNG|IMG_INIT_TIF; if((IMG_Init(imgFlags) & imgFlags) != imgFlags) { #ifndef PPDEBUG std::cout << "Error: "; #endif std::cout << IMG_GetError() << std::endl; return 1; } SDL_version imgCompiledVersion; SDL_IMAGE_VERSION(&imgCompiledVersion); const SDL_version *imgLinkedVersion = IMG_Linked_Version(); if(SDL_VERSION_NUMBER(imgLinkedVersion) < SDL_VERSION_NUMBER(&imgCompiledVersion)){ std::cout << "The installed SDL_image is not compatible. [" << SDL_VERSION_CONCAT(imgLinkedVersion) << "<" << SDL_VERSION_CONCAT(&imgCompiledVersion) << "]" << std::endl; return 1; } #ifdef PPDEBUG std::cout << "v" << SDL_VERSION_CONCAT(imgLinkedVersion) << std::endl; std::cout << "Initializing SDL_net... "; #endif if(SDLNet_Init() < 0) { #ifndef PPDEBUG std::cout << "Error: "; #endif std::cout << SDLNet_GetError() << std::endl; return 1; } SDL_version netCompiledVersion; SDL_NET_VERSION(&netCompiledVersion); const SDL_version *netLinkedVersion = SDLNet_Linked_Version(); if(SDL_VERSION_NUMBER(netLinkedVersion) < SDL_VERSION_NUMBER(&netCompiledVersion)){ std::cout << "The installed SDL_net is not compatible. [" << SDL_VERSION_CONCAT(netLinkedVersion) << "<" << SDL_VERSION_CONCAT(&netCompiledVersion) << "]" << std::endl; return 1; } #ifdef PPDEBUG std::cout << "v" << SDL_VERSION_CONCAT(netLinkedVersion) << std::endl; #endif do{ Uint32 speedTimer = SDL_GetTicks(); #ifdef PPDEBUG std::cout << "Creating window... "; #endif Uint32 flags = 0; if(this->resizable){ flags |= SDL_WINDOW_RESIZABLE; } if(this->fullscreen){ flags |= SDL_WINDOW_FULLSCREEN; } if(!(this->mainWindow = SDL_CreateWindow(this->title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, this->screenWidth, this->screenHeight, flags))) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Unexpected error has occurred", "Cannot initialize window.", 0); return 1; } #ifdef PPDEBUG std::cout << "in " << (SDL_GetTicks()-speedTimer) << "ms" << std::endl; speedTimer = SDL_GetTicks(); std::cout << "Creating renderer... "; #endif if(!(this->renderer = SDL_CreateRenderer(this->mainWindow, -1, 0))) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Unexpected error has occurred", "Cannot initialize renderer.", 0); return 1; } this->graphics = new ppGraphics(this->renderer); if(this->renderer){ #ifdef PPDEBUG std::cout << "in " << (SDL_GetTicks()-speedTimer) << "ms" << std::endl; SDL_RendererInfo rendererInfo; SDL_GetRendererInfo(this->renderer, &rendererInfo); std::cout << "Using \"" << rendererInfo.name << "\" as rendering engine..." << std::endl; speedTimer = SDL_GetTicks(); std::cout << "Configuring renderer... "; #endif SDL_Rect* rect = new SDL_Rect; rect->x = 0; rect->y = 0; rect->w = this->screenWidth; rect->h = this->screenHeight; SDL_RenderSetViewport(this->renderer, rect); SDL_RenderSetLogicalSize(this->renderer, this->width, this->height); } if(!this->restarting){ #ifdef PPDEBUG std::cout << "in " << (SDL_GetTicks()-speedTimer) << "ms" << std::endl; speedTimer = SDL_GetTicks(); std::cout << "Initializing Adaptive Music System... "; #endif this->ims = new ppIMS(this, this->randomizer); if(this->ims->Init()){ SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Unexpected error has occurred", "Cannot initialize Adaptive Music System.", 0); return 1; } } #ifdef PPDEBUG std::cout << "in " << (SDL_GetTicks()-speedTimer) << "ms" << std::endl; if(!this->currentState) { std::cout << "No state found..." << std::endl; SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING, "Warning!", "State not found.", 0); } speedTimer = SDL_GetTicks(); std::cout << "Preparing... "; #endif this->running = true; if(this->currentState && this->currentState->GetGame()){ this->currentState->OnInit(); } SDL_Event* event = new SDL_Event(); Uint32 lastTimer = SDL_GetTicks(), timeNow; Uint32 lastTime = lastTimer, avgRenderTime = 0, avgUpdateTime = 0; int renderDelta = 0, updateDelta = 0, renderDeltaTime=0, updateDeltaTime=0; int frames = 0, updates = 0; Uint32 msPerRender = 1000.0f / this->targetFPS; Uint32 msPerUpdate = 1000.0f / this->targetUPS; #ifdef PPDEBUG std::cout << "in " << (SDL_GetTicks()-speedTimer) << "ms" << std::endl; speedTimer = SDL_GetTicks(); std::cout << "Running... " << std::endl; #endif if(this->restarting){ this->restarting = false; if(this->currentState && this->currentState->GetGame()){ this->currentState->OnRestore(); } } while(this->running) { timeNow = SDL_GetTicks(); renderDelta += (timeNow - lastTime); renderDeltaTime += (timeNow - lastTime); updateDelta += (timeNow - lastTime); updateDeltaTime += (timeNow - lastTime); lastTime = timeNow; while(SDL_PollEvent(event)) { this->OnEvent(event); } if(updateDelta > msPerUpdate){ speedTimer = SDL_GetTicks(); updateDelta -= msPerUpdate; updates++; if(this->currentState && this->currentState->GetGame()){ this->currentState->OnUpdate(this->gameInput, updateDeltaTime); } updateDeltaTime = 0; this->ims->Update(); this->gameInput->OnUpdate(); avgUpdateTime += SDL_GetTicks()-speedTimer; } if(!this->vSync || renderDelta > msPerRender){ speedTimer = SDL_GetTicks(); renderDelta -= msPerRender; frames++; SDL_SetRenderDrawColor(this->renderer, this->backgroundColor->GetR(), this->backgroundColor->GetG(), this->backgroundColor->GetB(), this->backgroundColor->GetA()); SDL_RenderClear(this->renderer); if(this->currentState && this->currentState->GetGame()){ SDL_SetRenderDrawColor(this->renderer, 255, 255, 255, 255); SDL_SetRenderDrawBlendMode(this->renderer, SDL_BLENDMODE_BLEND); this->currentState->OnRender(this->graphics, renderDeltaTime); } renderDeltaTime = 0; if(this->showFPS){ SDL_SetRenderDrawColor(this->renderer, 255, 255, 255, 127); SDL_Rect* rect = new SDL_Rect; rect->x = 0; rect->y = 0; rect->w = this->width; rect->h = 6; SDL_RenderFillRect(this->renderer, rect); // FPS if(this->fps > 0){ Uint8 delta = this->fps / this->width; SDL_SetRenderDrawColor(this->renderer, 0, (255-(delta*2)), 0, 127); SDL_Rect* rect = new SDL_Rect; rect->x = 0; rect->y = 1; rect->w = this->fps % this->width; rect->h = 2; SDL_RenderFillRect(this->renderer, rect); } // UPS if(this->ups > 0){ Uint8 delta = this->ups / this->width; SDL_SetRenderDrawColor(this->renderer, 0, 0, (255-(delta*2)), 127); SDL_Rect* rect = new SDL_Rect; rect->x = 0; rect->y = 3; rect->w = this->ups % this->width; rect->h = 2; SDL_RenderFillRect(this->renderer, rect); } } SDL_RenderPresent(this->renderer); avgRenderTime += SDL_GetTicks()-speedTimer; } if(this->idleTime > 0){ SDL_Delay(this->idleTime); } if(SDL_GetTicks() - lastTimer >= 1000){ this->fps = frames; this->ups = updates; this->art = avgRenderTime/fps; this->aut = avgUpdateTime/ups; frames = 0; updates = 0; lastTimer = SDL_GetTicks(); #ifdef PPDEBUG if(this->showFPS){ std::cout << "FPS: " << fps << " [" << art <<"ms] UPS: " << ups << " [" << aut << "ms]" << std::endl; } #endif avgRenderTime = 0; avgUpdateTime = 0; } } if(this->currentState){ this->currentState->OnExit(); } #ifdef PPDEBUG speedTimer = SDL_GetTicks(); std::cout << "Destroying... "; #endif if(!this->restarting){ this->ims->Quit(); } SDL_DestroyRenderer(this->renderer); SDL_DestroyWindow(this->mainWindow); #ifdef PPDEBUG std::cout << "in " << (SDL_GetTicks()-speedTimer) << "ms" << std::endl; speedTimer = SDL_GetTicks(); if(this->restarting){ std::cout << "Restarting..." << std::endl; } #endif } while(this->restarting); IMG_Quit(); SDLNet_Quit(); SDL_Quit(); #ifdef PPDEBUG std::cout << "Quitting..." << std::endl; #endif return 0; } void ppGame::RestartGame(){ if(!this->running){ return; } if(this->currentState && this->currentState->GetGame()){ this->currentState->OnRestart(); } this->running = false; this->restarting = true; } void ppGame::QuitGame(){ this->running = false; } ppInput* ppGame::GetGameInput(){ return this->gameInput; } ppIO* ppGame::GetGameIO(){ return this->gameIO; } ppIMS* ppGame::GetInteractiveMusicSystem(){ return this->ims; } // GameIO* ppGame::getGameIO(){ // } // SoundPlayer* ppGame::getSoundPlayer(){ // } void ppGame::AddState(const char* name, ppState* state){ #ifdef PPDEBUG std::cout << "Add a new state \"" << name << "\"..." << std::endl; #endif state->SetName(name); this->states.insert(std::pair<const char*, ppState*>(name, state)); } void ppGame::EnterState(ppState* state){ if(!state->GetGame()){ state->SetGame(this); if(this->running){ state->OnInit(); } }else if(state->IsNeedInit() && this->running){ state->OnInit(); } if(this->currentState){ this->currentState->OnExit(); } #ifdef PPDEBUG std::cout << "Enter a state \"" << state->GetName() << "\"..." << std::endl; #endif this->currentState = state; } void ppGame::EnterState(const char* name){ ppState* state = this->GetState(name); if(state){ if(!state->GetGame()){ state->SetGame(this); if(this->running){ state->OnInit(); } }else if(state->IsNeedInit() && this->running){ state->OnInit(); } if(this->currentState){ this->currentState->OnExit(); } #ifdef PPDEBUG std::cout << "Enter a state \"" << state->GetName() << "\"..." << std::endl; #endif this->currentState = state; } } void ppGame::EnterState(const char* name, ppState* state){ this->AddState(name, state); this->EnterState(state); } ppState* ppGame::GetState(const char* name){ if(this->states.empty()){ return NULL; } std::map<const char*, ppState*>::iterator it; it = this->states.find(name); if(it != this->states.end()){ return it->second; } return NULL; } bool ppGame::HasState(const char* name){ return false; } const char* ppGame::GetCurrentStateName(){ return this->currentState->GetName(); } void ppGame::RemoveState(const char* name){ if(this->states.empty()){ return; } std::map<const char*, ppState*>::iterator it; it = this->states.find(name); if(it != this->states.end()){ this->states.erase(it); } } ppColor* ppGame::GetBackgroundColor(){ return this->backgroundColor; } void ppGame::SetBackgroundColor(ppColor* color){ this->backgroundColor = color; } int ppGame::GetFPS(){ return this->fps; } int ppGame::GetUPS(){ return this->ups; } int ppGame::GetAvgRenderTime(){ return this->art; } int ppGame::GetAvgUpdateTime(){ return this->aut; } int ppGame::GetTargetFPS(){ return this->targetFPS; } void ppGame::SetTargetFPS(int targetFPS){ this->targetFPS = targetFPS; } int ppGame::GetTargetUPS(){ return this->targetUPS; } void ppGame::SetTargetUPS(int targetUPS){ this->targetUPS = targetUPS; } int ppGame::GetIdleTime(){ return this->idleTime; } void ppGame::SetIdleTime(int idleTime){ this->idleTime = idleTime; } bool ppGame::IsShowFPS(){ return this->showFPS; } void ppGame::SetShowFPS(bool showFPS){ this->showFPS = showFPS; } bool ppGame::IsVSync(){ return this->vSync; } void ppGame::SetVSync(bool vSync){ this->vSync = vSync; } ppGame::~ppGame(){ // Pure virtual // Will run on destroy only free(this->gameInput); free(this->backgroundColor); }
25.228346
172
0.664732
spywhere
e3c5563ad5e846dbbfcf0aa2c002aa0cab240eb3
1,813
cpp
C++
src/nWrappedVariantMap.cpp
lucaspcamargo/neiatree
0da0ff4f06fb650885eda10830f59cd48e23e12f
[ "BSD-2-Clause" ]
1
2017-11-13T06:55:27.000Z
2017-11-13T06:55:27.000Z
src/nWrappedVariantMap.cpp
lucaspcamargo/neiatree
0da0ff4f06fb650885eda10830f59cd48e23e12f
[ "BSD-2-Clause" ]
null
null
null
src/nWrappedVariantMap.cpp
lucaspcamargo/neiatree
0da0ff4f06fb650885eda10830f59cd48e23e12f
[ "BSD-2-Clause" ]
null
null
null
#include "nWrappedVariantMap.h" #include "../util/nIODefines.h" #define nWRAPPED_VARIANT_MAP_VERSION 1 nWrappedVariantMap::nWrappedVariantMap(QObject *parent) : QObject(parent) { } nWrappedVariantMap::nWrappedVariantMap(QIODevice * device, QObject *parent) : QObject(parent) { load(device); } void nWrappedVariantMap::load(QIODevice * device) { bool opened = false; if(!device->isOpen()) { opened = true; device->open(QIODevice::ReadOnly); } QVariantMap map; { QDataStream in(device); in.setVersion(nQT_DATA_STREAM_VERSION); quint32 magicNum; quint8 version; in >> magicNum; in >> version; if(magicNum != nMAGIC_NUM_WRAPPED_VARIANT_MAP) throw "nWrappedVariantMap::load(QIODevice * device): Error reading stream: wrong magic number."; if(version != nWRAPPED_VARIANT_MAP_VERSION) throw "nWrappedVariantMap::load(QIODevice * device): Error reading stream: unrecognized version."; in >> map; } m_name = map["name"].toString(); m_version = map["version"].toString(); m_type = map["type"].toString(); m_map = map["map"].toMap(); if(opened)device->close(); } void nWrappedVariantMap::save(QIODevice * device) { bool opened = false; if(!device->isOpen()) { opened = true; device->open(QIODevice::WriteOnly); } QVariantMap map; map["name"] = m_name; map["version"] = m_version; map["type"] = m_type; map["map"] = m_map; { QDataStream out(device); out.setVersion(nQT_DATA_STREAM_VERSION); out << quint32(nMAGIC_NUM_WRAPPED_VARIANT_MAP); out << quint8(nWRAPPED_VARIANT_MAP_VERSION); out << map; } if(opened)device->close(); }
21.583333
110
0.623828
lucaspcamargo
e3cb5b87104a4b9b4de93e8bc6a87325f9879f7b
4,370
cpp
C++
src/matrix.cpp
pradeep0295/MINI-DATABASE
34e9e568b40dd82dab0c1963073c9a5d627937c2
[ "MIT" ]
null
null
null
src/matrix.cpp
pradeep0295/MINI-DATABASE
34e9e568b40dd82dab0c1963073c9a5d627937c2
[ "MIT" ]
null
null
null
src/matrix.cpp
pradeep0295/MINI-DATABASE
34e9e568b40dd82dab0c1963073c9a5d627937c2
[ "MIT" ]
null
null
null
#include "matrix.h" using namespace std; Matrix::Matrix(string matrixName) { // logger.log("Matrix::Matrix"); this->sourceFileName = "../data/" + matrixName + ".csv"; this->matrixName = matrixName; } bool Matrix::load(){ // logger.log("Matrix::load"); fstream fin(this->sourceFileName, ios::in); uint colcount = 0; char c; while(fin.get(c)){ if(c=='\n') break; if(c==',') colcount++; } this->noOfRows = colcount+1; this->noOfColumns = colcount+1; if(this->noOfRows < this->maxRowsPerBlock){ this->maxRowsPerBlock = this->noOfRows; this->maxColumnsPerBlock = this->noOfColumns; } this->rowBlockCount = ceil((double)this->noOfRows/this->maxColumnsPerBlock);// + (this->noOfRows%this->maxColumnsPerBlock)?1:0; this->columnBlockCount = this->rowBlockCount; if(this->blockify()) return true; fin.close(); return false; } bool Matrix::blockify(){ // logger.log("Matrix::blockify"); ifstream fin(this->sourceFileName); string word; pair<uint,uint> PageIndex={0,0}; for(int i=0;i< this->noOfRows;i++){ vector<int> rowOfPage; for(int j=0; j< this->noOfColumns; j++){ word=""; char c; while(fin.get(c)){ if(c==',' or c=='\n') break; word+=c; } stringstream s(word); int temp; s>>temp; rowOfPage.push_back(temp); if(j%noOfColumns == this->maxColumnsPerBlock-1 || j == this->noOfColumns-1){ writeRowInPage(PageIndex,rowOfPage); PageIndex.second++; } } PageIndex.second = 0; if(i%noOfRows == this->maxRowsPerBlock-1) PageIndex.first++; } return true; } void Matrix::writeRowInPage(pair<uint,uint> PageIndex,vector<int> &rowOfPage){ int row=PageIndex.first; int col=PageIndex.second; string pageName="../data/temp/page_"+to_string(row)+"_"+to_string(col); fstream fout(pageName,ios::binary|ios::app); int32_t num; for(int i=0;i<rowOfPage.size();i++){ num=rowOfPage[i]; fout.write((char*) &num,sizeof(num)); } fout.close(); } vector<vector<int>> Matrix::GetPage(int r,int c){ auto ind = getIndex(r,c); cout<<ind.first<<endl; cout<<ind.second<<endl; int rows= maxRowsPerBlock, cols= maxColumnsPerBlock; if(ind.first == rowBlockCount-1 && noOfRows%maxRowsPerBlock) rows = noOfRows%maxRowsPerBlock; if(ind.second == columnBlockCount-1 && noOfRows%maxRowsPerBlock) cols = noOfColumns%maxColumnsPerBlock; string pageName="../data/temp/page_"+to_string(ind.first)+"_"+to_string(ind.second); ifstream fin(pageName,ios::binary); int32_t num; vector<vector<int>> res(rows,std::vector<int>(cols)); for(int i=0;i<rows and fin ;i++) for(int j=0;j<cols and fin;j++){ fin.read((char*) &num, sizeof(num)); res[i][j]=num; // cout<<res[i][j]<<endl; } fin.close(); return res; } void Matrix::writeBackPage(vector<vector<int>> &matrix,int row, int col){ string pageName="../data/temp/page_"+to_string(row)+"_"+to_string(col); ofstream fout(pageName,ios::binary); int32_t num; int Rows=matrix.size(); int Columns=matrix[0].size(); for(int i=0;i<Rows and fout ;i++) for(int j=0;j<Columns and fout;j++){ num=matrix[i][j]; fout.write((char*) &num, sizeof(num)); } fout.close(); } pair<uint,uint> Matrix::getIndex(int i, int j){ if(this->is_transposed) return {j,i}; return {i,j}; } vector<vector<int>> Matrix::transposePage(vector<vector<int>> &matrix){ vector<vector<int>> tmatrix(matrix.size(), vector<int>(matrix[0].size())); cout<<matrix.size()<<matrix[0].size()<<endl; for(int i=0;i<matrix.size();i++){ for(int j=0;j<matrix[0].size();j++){ tmatrix[i][j] = matrix[j][i]; } // cout<<endl; } return tmatrix; } void Matrix::transpose(){ for(int i=0;i< this->rowBlockCount;i++){ for(int j=0;j< this->columnBlockCount;j++){ vector<vector<int>> matrixPage = GetPage(i,j); matrixPage = transposePage(matrixPage); writeBackPage(matrixPage,i,j); } } this->is_transposed = !this->is_transposed; } // int main(){ // Matrix A("z"); // A.load(); // A.transpose(); // }
26.646341
131
0.59405
pradeep0295
e3cd8e50ad33d6a2b481363f1eda813086603b0a
2,706
cpp
C++
Tests/unit/core/test_parser.cpp
mrcomcast123/Thunder
21d827ad7da0f3bf805d0eaf4b0759d1846c1e3b
[ "Apache-2.0" ]
null
null
null
Tests/unit/core/test_parser.cpp
mrcomcast123/Thunder
21d827ad7da0f3bf805d0eaf4b0759d1846c1e3b
[ "Apache-2.0" ]
null
null
null
Tests/unit/core/test_parser.cpp
mrcomcast123/Thunder
21d827ad7da0f3bf805d0eaf4b0759d1846c1e3b
[ "Apache-2.0" ]
null
null
null
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2020 RDK Management * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../IPTestAdministrator.h" #include <gtest/gtest.h> #include <core/core.h> using namespace WPEFramework; using namespace WPEFramework::Core; class Deserializer { private: typedef ParserType<TerminatorCarriageReturnLineFeed, Deserializer> Parser; public : Deserializer() : _parser(*this) { } void operations() { _parser.Reset(); _parser.CollectWord(); _parser.CollectWord('/'); _parser.CollectWord(Core::ParserType<TerminatorCarriageReturnLineFeed, Deserializer>::ParseState::UPPERCASE); _parser.CollectWord('/',Core::ParserType<TerminatorCarriageReturnLineFeed, Deserializer>::ParseState::UPPERCASE); _parser.CollectLine(); _parser.CollectLine(Core::ParserType<TerminatorCarriageReturnLineFeed, Deserializer>::ParseState::UPPERCASE); _parser.FlushLine(); _parser.PassThrough(5); } ~Deserializer() { } private: Parser _parser; }; TEST(test_parser_type, simple_parser_type) { Deserializer deserializer; deserializer.operations(); } TEST(test_text_parser, simple_text_parser) { TextFragment inputLine("/Service/testing/parsertest"); TextParser textparser(inputLine); textparser.Skip(2); textparser.Skip('S'); textparser.Find(_T("e")); textparser.SkipWhiteSpace(); textparser.SkipLine(); OptionalType<TextFragment> token; textparser.ReadText(token, _T("/")); } TEST(test_path_parser, simple_path_parser) { TextFragment inputFile("C://Service/testing/pathparsertest.txt"); PathParser pathparser(inputFile); EXPECT_EQ(pathparser.Drive().Value(),'C'); EXPECT_STREQ(pathparser.Path().Value().Text().c_str(),_T("//Service/testing")); EXPECT_STREQ(pathparser.FileName().Value().Text().c_str(),_T("pathparsertest.txt")); EXPECT_STREQ(pathparser.BaseFileName().Value().Text().c_str(),_T("pathparsertest")); EXPECT_STREQ(pathparser.Extension().Value().Text().c_str(),_T("txt"));; }
30.404494
121
0.712121
mrcomcast123
e3d064a029d3dcd4f0eccffdff63a1ae8d446981
434
cc
C++
algorithm/modifying/remove.cc
HelloCodeMing/ToySTL
8221688f8674ab214e3e57abe262b02f952c8036
[ "MIT" ]
1
2015-09-11T00:33:43.000Z
2015-09-11T00:33:43.000Z
algorithm/modifying/remove.cc
HelloCodeMing/ToySTL
8221688f8674ab214e3e57abe262b02f952c8036
[ "MIT" ]
null
null
null
algorithm/modifying/remove.cc
HelloCodeMing/ToySTL
8221688f8674ab214e3e57abe262b02f952c8036
[ "MIT" ]
null
null
null
#include <predef.hpp> template <class Iter, class T> Iter remove(Iter first, Iter last, const T& value) { for (auto iter = first; iter != last; ++iter) { if (*iter != value) *first++ = *iter; } return first; } int main() { std::string str = "hey, *****."; assert(std::string( str.begin(), ::remove(str.begin(), str.end(), '*')) == "hey, ."); return 0; }
20.666667
67
0.486175
HelloCodeMing
e3d0ad501d0f03b2972c296f03686a83f25b9f19
8,713
hxx
C++
BTech Project/Code/OpacityFunctionGeneration.hxx
aishwaryamallampati/BTech-IIITDM
4cfc25a4e6e066b848361cb92770cad3260c7d48
[ "MIT" ]
null
null
null
BTech Project/Code/OpacityFunctionGeneration.hxx
aishwaryamallampati/BTech-IIITDM
4cfc25a4e6e066b848361cb92770cad3260c7d48
[ "MIT" ]
null
null
null
BTech Project/Code/OpacityFunctionGeneration.hxx
aishwaryamallampati/BTech-IIITDM
4cfc25a4e6e066b848361cb92770cad3260c7d48
[ "MIT" ]
null
null
null
#pragma once #ifndef OpacityFunctionGeneration_hxx #define OpacityFunctionGeneration_hxx template <typename TInputImage> OpacityFunctionGeneration<TInputImage>::OpacityFunctionGeneration(HistogramType::Pointer histogram, float *binWidth, float *binMinimum) { this->max_g = -100000; this->min_g = 100000; this->max_h = -100000; this->min_h = 100000; this->CalculateMeanFirstDirectionalDerivative(histogram, binWidth, binMinimum); this->CalculateMeanSecondDirectionalDerivative(histogram, binWidth, binMinimum); this->CalculateOpacity(histogram); this->StoreAllValues(histogram, binWidth, binMinimum); } template <typename TInputImage> void OpacityFunctionGeneration<TInputImage>::CalculateMeanFirstDirectionalDerivative(HistogramType::Pointer histogram, float *binWidth, float *binMinimum) { //calculation of g(v) this->g = (float*)calloc(histogram->GetSize(0), sizeof(float)); for (int i = 0;i < (histogram->GetSize(0));i++)//dataValue Axis { float avg_sum = 0; for (int k = 0;k < (histogram->GetSize(2));k++)//secondDerivative Axis { float sum_g = 0; int freq_g = 0; for (int j = 0;j < (histogram->GetSize(1));j++)//gradientMagnitude Axis { HistogramType::IndexType index(Dimension); index[0] = i; index[1] = j; index[2] = k; int frequency = histogram->GetFrequency(index); if (frequency != 0) { freq_g = freq_g + frequency; sum_g = sum_g + (frequency*(binMinimum[1] + j*binWidth[1])); } } if (freq_g != 0) { avg_sum = avg_sum + (sum_g / freq_g);//fix i and k then iterate over j. } } //this->g[i] = (avg_sum / (histogram->GetSize(2)));//fix i and for all the averages over k find final average. this->g[i] = avg_sum; if (this->g[i] < this->min_g) //finding min_g this->min_g = this->g[i]; if (this->g[i] > this->max_g) //finding max_g this->max_g = this->g[i]; } cout << "\nPrinting g:" << "\n"; #pragma omp parallel #pragma omp for for (int i = 0;i < (histogram->GetSize(0));i++) { cout << "g[" << i << "]=" << this->g[i] << "\n"; } cout << "max_g=" << this->max_g << " min_g=" << this->min_g << "\n"; } template <typename TInputImage> void OpacityFunctionGeneration<TInputImage>::CalculateMeanSecondDirectionalDerivative(HistogramType::Pointer histogram, float *binWidth, float *binMinimum) { //calculation of h(v) this->h = (float*)calloc((histogram->GetSize(0)), sizeof(float)); for (int i = 0;i < (histogram->GetSize(0));i++)//dataValue Axis { float avg_sum = 0; for (int j = 0;j < (histogram->GetSize(1));j++)//gradientMagnitude Axis { float sum_h = 0; int freq_h = 0; for (int k = 0;k <(histogram->GetSize(2));k++)//secondDerivative Axis { HistogramType::IndexType index(Dimension); index[0] = i; index[1] = j; index[2] = k; int frequency = histogram->GetFrequency(index); if (frequency != 0) { freq_h = freq_h + frequency; sum_h = sum_h + (frequency*(binMinimum[2] + k*binWidth[2])); } } if (freq_h != 0) { avg_sum = avg_sum + (sum_h / freq_h);//fix i and k then iterate over j. } } //this->h[i] = (avg_sum / (histogram->GetSize(1)));//fix i and for all the averages over k find final average. this->h[i] = avg_sum; if (this->h[i] < this->min_h) //finding min_h this->min_h = this->h[i]; if (this->h[i] > this->max_h) //finding max_h this->max_h = this->h[i]; } cout << "\nPrinting h:" << "\n"; for (int i = 0;i < (histogram->GetSize(0));i++) { cout << "h[" << i << "]=" << this->h[i] << "\n"; } cout << "max_h=" << this->max_h << " min_h=" << this->min_h << "\n"; } /*template <typename TInputImage> void OpacityFunctionGeneration<TInputImage>::CalculateMeanFirstDirectionalDerivative(HistogramType::Pointer histogram, float *binWidth, float *binMinimum) { //calculation of g(v) this->g = (float*)calloc(histogram->GetSize(0), sizeof(float)); for (int i = 0;i < (histogram->GetSize(0));i++)//dataValue Axis { float avg_sum = 0.0; float sum_g = 0.0; int freq_g = 0.0; for (int k = 0;k < (histogram->GetSize(2));k++)//secondDerivative Axis { for (int j = 0;j < (histogram->GetSize(1));j++)//gradientMagnitude Axis { HistogramType::IndexType index(Dimension); index[0] = i; index[1] = j; index[2] = k; int frequency = histogram->GetFrequency(index); if (frequency != 0) { freq_g = freq_g + frequency; sum_g = sum_g + (frequency*((binMinimum[1] + j*binWidth[1])+(binWidth[1]/2))); } } /*if (freq_j != 0) { avg_sum = avg_sum + (sum_j / freq_j);//fix i and k then iterate over j. sum_k = sum_k + avg_sum*fre }*/ /*} //this->g[i] = (avg_sum / (histogram->GetSize(2)));//fix i and for all the averages over k find final average. /*if (freq_g == 0) { this->g[i] = 0.1; //just to remove the contribution of this g continue; }*/ /*this->g[i] = (float)(sum_g / freq_g); //this->g[i] = (float)(this->g[i] / histogram->GetSize[2]); if (this->g[i] < this->min_g) //finding min_g this->min_g = this->g[i]; if (this->g[i] > this->max_g) //finding max_g this->max_g = this->g[i]; } cout << "\nPrinting g:" << "\n"; #pragma omp parallel #pragma omp for for (int i = 0;i < (histogram->GetSize(0));i++) { cout << "g[" << i << "]=" << this->g[i] << "\n"; } cout << "max_g=" << this->max_g << " min_g=" << this->min_g << "\n"; } template <typename TInputImage> void OpacityFunctionGeneration<TInputImage>::CalculateMeanSecondDirectionalDerivative(HistogramType::Pointer histogram, float *binWidth, float *binMinimum) { //calculation of h(v) this->h = (float*)calloc((histogram->GetSize(0)), sizeof(float)); for (int i = 0;i < (histogram->GetSize(0));i++)//dataValue Axis { float avg_sum = 0.0; float sum_h = 0.0; int freq_h = 0.0; for (int j = 0;j < (histogram->GetSize(1));j++)//gradientMagnitude Axis { for (int k = 0;k <(histogram->GetSize(2));k++)//secondDerivative Axis { HistogramType::IndexType index(Dimension); index[0] = i; index[1] = j; index[2] = k; int frequency = histogram->GetFrequency(index); if (frequency != 0) { freq_h = freq_h + frequency; sum_h = sum_h + (frequency*((binMinimum[2] + k*binWidth[2]) + (binWidth[2]/2))); } } /*if (freq_h != 0) { avg_sum = avg_sum + (sum_h / freq_h);//fix i and k then iterate over j. }*/ /*} //this->h[i] = (avg_sum / (histogram->GetSize(1)));//fix i and for all the averages over k find final average. /*if (freq_h == 0) { this->h[i] = 100000; //just to remove the contribution of this h continue; }*/ /*this->h[i] = (float)(sum_h / freq_h); if (this->h[i] < this->min_h) //finding min_h this->min_h = this->h[i]; if (this->h[i] > this->max_h) //finding max_h this->max_h = this->h[i]; } cout << "\nPrinting h:" << "\n"; for (int i = 0;i < (histogram->GetSize(0));i++) { cout << "h[" << i << "]=" << this->h[i] << "\n"; } cout << "max_h=" << this->max_h << " min_h=" << this->min_h << "\n"; }*/ template <typename TInputImage> void OpacityFunctionGeneration<TInputImage>::CalculateOpacity(HistogramType::Pointer histogram) { //calculation of sigma float e = 2.71828; float sigma = (2 * sqrtf(e) * max_g) / (max_h - min_h); cout << "sigma=" << sigma << "\n"; //calculation of p(v) this->p = (float*)calloc((histogram->GetSize(0)), sizeof(float)); for (int i = 0;i < (histogram->GetSize(0));i++) { this->p[i] = -((((sigma)*(sigma))*this->h[i]) / (this->g[i])); } cout << "\nPrinting p:" << "\n"; for (int i = 0;i < (histogram->GetSize(0));i++) { cout << "p[" << i << "]=" << this->p[i] << "\n"; } //calculation of alpha(v) this->alpha = (float*)calloc((histogram->GetSize(0)), sizeof(float)); for (int i = 0;i <(histogram->GetSize(0));i++) { if ((this->p[i] <= sigma) && (this->p[i] >= -(sigma))) { this->alpha[i] = 0.6; // original version } else { this->alpha[i] = 0.0; } } cout << "\nPrinting alpha:" << "\n"; for (int i = 0;i < (histogram->GetSize(0));i++) { cout << "alpha[" << i << "]=" << this->alpha[i] << "\n"; } } template <typename TInputImage> void OpacityFunctionGeneration<TInputImage>::StoreAllValues(HistogramType::Pointer histogram, float *binWidth, float *binMinimum) { // storing all values in excel ofstream allValues; allValues.open("allValues.CSV"); allValues << "dataValue" << "," << "g[v]" << "," << "h[v]" << "," << "p[v]" << "," << "alpha[v]" << "\n"; for (int i = 0;i < (histogram->GetSize(0));i++) { allValues << binMinimum[0] + i*binWidth[0] << "," << this->g[i] << "," << this->h[i] << "," << this->p[i] << "," << this->alpha[i] << "\n"; } allValues.close(); } #endif // OpacityFunctionGeneration_hxx
31.568841
155
0.603466
aishwaryamallampati
e3e278cccac2eb35046bbb61377c9ba179ce4fb1
5,447
cpp
C++
Super Smash TV/Super Smash TV/Source/ModulePlayer_Legs.cpp
YunqianAo/Filosaurios
23f191c48629a5b6ee7b4d3e69a541dd0e1bb381
[ "MIT" ]
2
2021-03-07T10:32:01.000Z
2021-03-07T10:32:04.000Z
Super Smash TV/Super Smash TV/Source/ModulePlayer_Legs.cpp
YunqianAo/Filosaurios
23f191c48629a5b6ee7b4d3e69a541dd0e1bb381
[ "MIT" ]
null
null
null
Super Smash TV/Super Smash TV/Source/ModulePlayer_Legs.cpp
YunqianAo/Filosaurios
23f191c48629a5b6ee7b4d3e69a541dd0e1bb381
[ "MIT" ]
8
2021-02-23T18:06:22.000Z
2021-02-24T19:12:48.000Z
//#include "ModulePlayer_Legs.h" // //#include "Application.h" //#include "ModuleTextures.h" //#include "ModuleInput.h" //#include "ModuleRender.h" //#include "ModuleParticles.h" //#include "ModuleCollisions.h" //#include "ModuleAudio.h" //#include "ModuleFadeToBlack.h" // //#include "SDL/include/SDL_scancode.h" // // //ModulePlayer_Leg::ModulePlayer_Leg(bool startEnabled) : Module(startEnabled) //{ // // LEGS // legs_down_idle.PushBack({ 128, 16, 16, 16 }); // legs_up_idle.PushBack({ 192, 16, 16, 16 }); // legs_l_idle.PushBack({ 208, 16, 16, 16 }); // legs_r_idle.PushBack({ 160, 16, 16, 16 }); // // // move upwards // upAnim.PushBack({ 0, 16, 16, 16 });// 1 // upAnim.PushBack({ 16, 16, 16, 16 });// 2 // upAnim.PushBack({ 32, 16, 16, 16 });// 3 // upAnim.PushBack({ 48, 16, 16, 16 });// 4 // upAnim.PushBack({ 64, 16, 16, 16 });// 5 // upAnim.PushBack({ 80, 16, 16, 16 });// 6 // upAnim.loop = true; // upAnim.speed = 0.2f; // // // Move down // legs_down.PushBack({ 0, 0, 16, 16 });// 1 // legs_down.PushBack({ 16, 0, 16, 16 });// 2 // legs_down.PushBack({ 32, 0, 16, 16 });// 3 // legs_down.PushBack({ 48, 0, 16, 16 });// 4 // legs_down.PushBack({ 64, 0, 16, 16 });// 5 // legs_down.PushBack({ 80, 0, 16, 16 });// 6 // legs_down.PushBack({ 96, 0, 16, 16 });// 7 // legs_down.PushBack({ 112, 0, 16, 16 });// 8 // // legs_down.loop = true; // legs_down.speed = 0.2f; // // // Move left // legs_l.PushBack({ 96, 32, 16, 16 });// 7 // legs_l.PushBack({ 80, 32, 16, 16 });// 6 // legs_l.PushBack({ 64, 32, 16, 16 });// 5 // legs_l.PushBack({ 48, 32, 16, 16 });// 4 // legs_l.PushBack({ 32, 32, 16, 16 });// 3 // legs_l.PushBack({ 16, 32, 16, 16 });// 2 // legs_l.PushBack({ 0, 32, 16, 16 });// 1 // // legs_l.loop = true; // legs_l.speed = 0.2f; // // // Move right // legs_r.PushBack({ 0, 48, 16, 16 });// 1 // legs_r.PushBack({ 16, 48, 16, 16 });// 2 // legs_r.PushBack({ 32, 48, 16, 16 });// 3 // legs_r.PushBack({ 48, 48, 16, 16 });// 4 // legs_r.PushBack({ 64, 48, 16, 16 });// 5 // legs_r.PushBack({ 80, 48, 16, 16 });// 6 // legs_r.PushBack({ 96, 48, 16, 16 });// 7 // legs_r.loop = true; // legs_r.speed = 0.2f; // // // //} // // //bool ModulePlayer_Leg::Start() //{ // LOG("Loading player textures"); // // bool ret = true; // // texture = App->textures->Load("Resources/Sprites/Characters/Player.png"); // currentAnimation = &legs_idle; // position.x = 121; // position.y = 135; // // destroyed = false; // // bool bandera_GodMode = false; // // collider = App->collisions->AddCollider({ position.x, position.y, 14, 25 }, Collider::Type::PLAYER, this); // // return ret; //} // //update_status ModulePlayer_Leg::Update() //{ // // Moving the player with the camera scroll // App->player->position.x += 0; // // // Body movent // // Shoot bullet right // if (App->input->keys[SDL_SCANCODE_RIGHT] == KEY_STATE::KEY_REPEAT) // { // currentAnimation = &legs_r_idle; // } // // // Shoot bullet left // if (App->input->keys[SDL_SCANCODE_LEFT] == KEY_STATE::KEY_REPEAT) // { // currentAnimation = &legs_l_idle; // } // // // Shoot bullet up // if (App->input->keys[SDL_SCANCODE_UP] == KEY_STATE::KEY_REPEAT) // { // // currentAnimation = &upAnim_idle; // } // // // // if (App->input->keys[SDL_SCANCODE_S] == KEY_STATE::KEY_REPEAT) // { // position.y += speed; // // currentAnimation = &legs_down; // } // // if (App->input->keys[SDL_SCANCODE_W] == KEY_STATE::KEY_REPEAT) // { // position.y -= speed; // // currentAnimation = &upAnim; // } // // // if (App->input->keys[SDL_SCANCODE_A] == KEY_STATE::KEY_REPEAT) // { // position.x -= speed; // // currentAnimation = &legs_l; // } // // // if (App->input->keys[SDL_SCANCODE_D] == KEY_STATE::KEY_REPEAT) // { // position.x += speed; // // currentAnimation = &legs_r; // } // // if (App->input->keys[SDL_SCANCODE_F2] == KEY_STATE::KEY_DOWN) // { // if (GodMode == false) { // GodMode = true; // } // else if(GodMode == true) { // GodMode = false; // } // // } // // // // // If no up/down movement detected, set the current animation back to idle // if (App->input->keys[SDL_SCANCODE_RIGHT] == KEY_STATE::KEY_IDLE // && App->input->keys[SDL_SCANCODE_LEFT] == KEY_STATE::KEY_IDLE // && App->input->keys[SDL_SCANCODE_UP] == KEY_STATE::KEY_IDLE // // && App->input->keys[SDL_SCANCODE_S] == KEY_STATE::KEY_IDLE // && App->input->keys[SDL_SCANCODE_W] == KEY_STATE::KEY_IDLE // && App->input->keys[SDL_SCANCODE_A] == KEY_STATE::KEY_IDLE // && App->input->keys[SDL_SCANCODE_D] == KEY_STATE::KEY_IDLE) // // currentAnimation = &legs_idle; // // collider->SetPos(position.x+1, position.y-12); // // currentAnimation->Update(); // // // return update_status::UPDATE_CONTINUE; //} // //update_status ModulePlayer_Leg::PostUpdate() //{ // if (!destroyed) // { // SDL_Rect rect = currentAnimation->GetCurrentFrame(); // App->render->Blit(texture, position.x, position.y, &rect); // } // // return update_status::UPDATE_CONTINUE; //} // //void ModulePlayer_Leg::OnCollision(Collider* c1, Collider* c2) //{ // if (c2->type == Collider::Type::WALL && destroyed == false && GodMode == false) // { // App->fade->FadeToBlack((Module*)App->sceneLevel, (Module*)App->sceneLose, 90); // destroyed = true; // // } // // if (c2->type == Collider::Type::DOOR && destroyed == false) // { // App->fade->FadeToBlack((Module*)App->sceneLevel, (Module*)App->sceneWin, 90); // destroyed = true; // } // //}
25.938095
109
0.596842
YunqianAo
e3e4c33c1e4a1f8bfc439cfcf0b7bde39b09ce4b
4,133
cpp
C++
v1/CUCT.cpp
lanyj/mcts
8394acaf3e83020b0bdfaa6117553d1ad64be291
[ "MIT" ]
null
null
null
v1/CUCT.cpp
lanyj/mcts
8394acaf3e83020b0bdfaa6117553d1ad64be291
[ "MIT" ]
null
null
null
v1/CUCT.cpp
lanyj/mcts
8394acaf3e83020b0bdfaa6117553d1ad64be291
[ "MIT" ]
null
null
null
#pragma once #include <time.h> #include "stdafx.h" #include "CUCT.h" #include "OthelloCBoard.h" #include "OXOCBoard.h" #include "GobangCBoard.h" void* CUCT::getCNode(const void *list, int index) { return ((CList<CNode*>*) list)->get(index); } void CUCT::exchangeCNode(const void *list, int i, int j) { CNode* m = (CNode*) ((CList<CNode*>*) list)->get(i); CNode* n = (CNode*) ((CList<CNode*>*) list)->get(j); ((CList<CNode*>*) list)->set(i, n); ((CList<CNode*>*) list)->set(j, m); } int CUCT::compareToCNode(const void* l, const void* r) { double v1 = ((CNode *) l)->value(); double v2 = ((CNode *) r)->value(); return (v1 == v2 ? 0 : (v1 > v2 ? 1 : -1)); } int CUCT::random(int bounds) { return rand() % bounds; } CNode* CUCT::randomChoiceCNode(CList<CNode*> *list) { if (list->isEmpty()) { return NULL; } return list->get(random(list->size())); } CMove* CUCT::randomChoiceCMove(CList<CMove*> *list) { if (list->isEmpty()) { return NULL; } return list->get(random(list->size())); } CMove* CUCT::uctMove(CBoard* _board, int itermax) { CNode* root = new CNode(NULL, NULL, _board); for(; itermax--;) { CNode* node = root; CBoard *board = _board->clone(); CNode* n = select(node, board); n = expansion(n, board); double res = simulation(n, board); backUp(n, res); delete board; } // printf("\nBEGIN...\n"); // for (int i = root->children->size() - 1; i >= 0; i--) { // root->children->get(i)->move->toString(); // printf(" -> %f, %f, %f\n", root->children->get(i)->visits, root->children->get(i)->score, root->children->get(i)->value()); // } CMove* move; double mostVist = -100; int index = -1; for (int i = root->children->size() - 1; i >= 0; i--) { CNode* tmp = root->children->get(i); /* if ((tmp->score / tmp->visits) > mostVist) { mostVist = (tmp->score / tmp->visits); index = i; } */ if (tmp->visits > mostVist) { mostVist = tmp->visits; index = i; } } move = root->children->get(index)->move->clone(); // printf("\nCHOSEN:->"); // move->toString(); // printf("\nEND..."); clearUp(root); return move; } CNode* CUCT::select(CNode* root, CBoard* board) { if (root->children->isEmpty()) { return root; } CNode* next = root->uctSelectChild(); board->applyMove(next->move); while (!next->children->isEmpty()) { next = next->uctSelectChild(); board->applyMove(next->move); } return next; } CNode* CUCT::expansion(CNode* root, CBoard* board) { if (board->isGameOver()) { return root; } CNode* node = NULL; CList<CMove*>* moves = board->getMoves(); while (!moves->isEmpty()) { root->addNode(moves->removeLast(), board); } delete moves; return randomChoiceCNode(root->children); } double CUCT::simulation(CNode* root, CBoard* board) { while (!board->isGameOver()) { CList<CMove*>* moves = board->getMoves(); CMove* m = randomChoiceCMove(moves); board->applyMove(m); while (!moves->isEmpty()) { delete moves->removeLast(); } delete moves; } double res = board->getResult(root->player); return res; } void CUCT::backUp(CNode* node, double res) { node->update(res); if (node->parent != NULL) { backUp(node->parent, -res); } } void CUCT::clearUp(CNode* node) { if (node->move != NULL) { delete node->move; } CList<CNode*> *children = node->children; while(!children->isEmpty()) { clearUp(children->removeLast()); } delete node; } void CUCT::uctPlayGame() { char c[3] = { '.', 'X', 'O' }; // OXOCBoard, GobangCBoard, OthelloCBoard CBoard *board = new OthelloCBoard(8); board->printCBoard(); printf("\n"); CMove *move; while(!board->isGameOver()) { if(board->getCurrentPlayer() == 1) { move = uctMove(board, 1000); } else { move = uctMove(board, 100); } printf("\nPlayer %c STEP: ", c[board->getCurrentPlayer()]); move->toString(); printf("\n"); board->applyMove(move); board->printCBoard(); printf("\n"); delete move; } printf("Player: %c -> %lf\n", c[board->getCurrentPlayer()], board->getResult(board->getCurrentPlayer())); printf("Player: %c -> %lf\n", c[3 - board->getCurrentPlayer()], board->getResult(3 - board->getCurrentPlayer())); delete board; }
24.311765
127
0.616017
lanyj
e3e5ce311956c5949defb8b4ef5f3eb86aae4eac
1,670
cpp
C++
luogu/codes/P1637.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
1
2018-12-22T06:43:59.000Z
2018-12-22T06:43:59.000Z
luogu/codes/P1637.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
null
null
null
luogu/codes/P1637.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
null
null
null
/************************************************************* * > File Name : P1637.cpp * > Author : Tony * > Created Time : 2019/08/26 16:20:04 * > Algorithm : [DataStructure]BIT **************************************************************/ #include <bits/stdc++.h> using namespace std; inline int read() { int x = 0; int f = 1; char ch = getchar(); while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();} while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();} return x * f; } const int maxn = 30010; int n, m, a[maxn]; int tree1[maxn], tree2[maxn]; int A[maxn]; int cntl[maxn], cntr[maxn]; void add1(int x, int k) { for (; x <= n; x += x & -x) tree1[x] += k; } void add2(int x, int k) { for (; x <= n; x += x & -x) tree2[x] += k; } int ask1(int x) { int ans = 0; for (; x; x -= x & -x) ans += tree1[x]; return ans; } int ask2(int x) { int ans = 0; for (; x; x -= x & -x) ans += tree2[x]; return ans; } int main() { n = read(); for (int i = 1; i <= n; ++i) { A[i] = a[i] = read(); } sort(A + 1, A + 1 + n); m = unique(A + 1, A + 1 + n) - (A + 1); for (int i = 1; i <= n; ++i) { add1(lower_bound(A + 1, A + 1 + n, a[i]) - A, 1); cntl[i] = ask1((lower_bound(A + 1, A + 1 + n, a[i]) - A) - 1); } for (int i = n; i >= 1; --i) { add2(lower_bound(A + 1, A + 1 + n, a[i]) - A, 1); cntr[i] = n - i - ask2((lower_bound(A + 1, A + 1 + n, a[i]) - A)) + 1; } long long ans = 0; for (int i = 2; i < n; ++i) { ans += cntl[i] * cntr[i]; } printf("%lld\n", ans); return 0; }
25.692308
78
0.40479
Tony031218
e3e86f09cecd130e1dae59ea842f994ee802df60
1,362
cpp
C++
sdk/packages/engine_gems/state/test/io.cpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
null
null
null
sdk/packages/engine_gems/state/test/io.cpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
null
null
null
sdk/packages/engine_gems/state/test/io.cpp
ddr95070/RMIsaac
ee3918f685f0a88563248ddea11d089581077973
[ "FSFAP" ]
1
2022-01-28T16:37:51.000Z
2022-01-28T16:37:51.000Z
/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. */ #include "packages/engine_gems/state/io.hpp" #include "capnp/message.h" #include "engine/core/buffers/shared_buffer.hpp" #include "packages/engine_gems/state/state.hpp" #include "packages/engine_gems/state/test/domains.hpp" #include "gtest/gtest.h" namespace isaac { namespace state { namespace { constexpr double kFoo = 13.1; constexpr double kBar = -0.3; constexpr double kTur = 0.57; } // namespace TEST(State, ToFromProto) { FooBarTur actual; actual.foo() = kFoo; actual.bar() = kBar; actual.tur() = kTur; ::capnp::MallocMessageBuilder message; auto builder = message.initRoot<StateProto>(); std::vector<isaac::SharedBuffer> buffers; ToProto(actual, builder, buffers); auto reader = builder.asReader(); FooBarTur expected; FromProto(reader, buffers, expected); EXPECT_EQ(expected.foo(), kFoo); EXPECT_EQ(expected.bar(), kBar); EXPECT_EQ(expected.tur(), kTur); } } // namespace state } // namespace isaac
28.978723
74
0.755507
ddr95070
e3f97601d1618d140eef14b54a9e1772f1888f27
766
cpp
C++
docs/mfc/codesnippet/CPP/cmap-class_7.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
14
2018-01-28T18:10:55.000Z
2021-11-16T13:21:18.000Z
docs/mfc/codesnippet/CPP/cmap-class_7.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
null
null
null
docs/mfc/codesnippet/CPP/cmap-class_7.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
2
2018-10-10T07:37:30.000Z
2019-06-21T15:18:07.000Z
CMap<int, int, CPoint, CPoint> myMap; // Add 10 elements to the map. for (int i = 0; i < 10; i++) myMap.SetAt(i, CPoint(i, i)); // Remove the elements with even key values. POSITION pos = myMap.GetStartPosition(); int nKey; CPoint pt; while (pos != NULL) { myMap.GetNextAssoc(pos, nKey, pt); if ((nKey % 2) == 0) myMap.RemoveKey(nKey); } // Print the element values. pos = myMap.GetStartPosition(); while (pos != NULL) { myMap.GetNextAssoc(pos, nKey, pt); _tprintf_s(_T("Current key value at %d: %d,%d\n"), nKey, pt.x, pt.y); }
29.461538
63
0.456919
jmittert
5400027446cdf509e429e4d3ccc5f028497d1ddb
478
cpp
C++
Squareandcube.cpp
aaryan0348/E-Lab-Object-Oriented-Programming
29f3ca80dbf2268441b5b9e426415650a607195a
[ "MIT" ]
null
null
null
Squareandcube.cpp
aaryan0348/E-Lab-Object-Oriented-Programming
29f3ca80dbf2268441b5b9e426415650a607195a
[ "MIT" ]
null
null
null
Squareandcube.cpp
aaryan0348/E-Lab-Object-Oriented-Programming
29f3ca80dbf2268441b5b9e426415650a607195a
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; class Number { public: int n; void getNumber() { cin>>n; } }; class Square:public Number { public: void getSquare() { cout<<(n*n)<<endl; } }; class Cube:public Number { public: void getCube() { cout<<((n*n)*n)<<endl; } }; int main() { Square objS ; objS.getNumber(); objS.getSquare(); Cube objC ; objC.getNumber(); objC.getCube(); return 0; }
14.9375
31
0.529289
aaryan0348
540320795eb258402122b38c3d1370a5f5a411ba
126
hpp
C++
src/order_type.hpp
Twon/cpp_crypto_algos
e785f6c25ef50dc3c2f593b08b6857dffcd32eca
[ "MIT" ]
null
null
null
src/order_type.hpp
Twon/cpp_crypto_algos
e785f6c25ef50dc3c2f593b08b6857dffcd32eca
[ "MIT" ]
null
null
null
src/order_type.hpp
Twon/cpp_crypto_algos
e785f6c25ef50dc3c2f593b08b6857dffcd32eca
[ "MIT" ]
null
null
null
#pragma once #include <boost/describe/enum.hpp> namespace profitview { BOOST_DEFINE_ENUM_CLASS(OrderType, Limit, Market) }
12.6
49
0.785714
Twon
54034083f157980cf15348c7a892b4d443125820
560
hpp
C++
include/CompositeSceneElement.hpp
renato-cefet-rj/openglbase
9218fc3e53bc08f799f10ac4111cb579bc2dd6b3
[ "MIT" ]
3
2018-06-11T16:20:02.000Z
2019-11-14T19:44:11.000Z
include/CompositeSceneElement.hpp
renato-cefet-rj/openglbase
9218fc3e53bc08f799f10ac4111cb579bc2dd6b3
[ "MIT" ]
1
2018-06-11T02:41:11.000Z
2018-06-14T13:38:16.000Z
include/CompositeSceneElement.hpp
renato-cefet-rj/openglbase
9218fc3e53bc08f799f10ac4111cb579bc2dd6b3
[ "MIT" ]
1
2018-07-18T15:12:33.000Z
2018-07-18T15:12:33.000Z
#ifndef __COMPOSITE_SCENE_ELEMENT__ #define __COMPOSITE_SCENE_ELEMENT__ #define CompositeSceneElementNull (CompositeSceneElement*)0 #include <SceneElement.hpp> #include <list> typedef std::list<SceneElement*>::iterator ElementsIterator; class CompositeSceneElement: public SceneElement { public: CompositeSceneElement(); virtual ~CompositeSceneElement(); virtual CompositeSceneElement* append(SceneElement* se); virtual void draw(glm::mat4 transform); private: std::list<SceneElement*> elements; }; #endif
24.347826
64
0.748214
renato-cefet-rj
5408b77717bb800fadb85a9972a8b1f37af731b2
394
hh
C++
Cassie_Example/opt_two_step/periodic/c_code/include/frost/gen/J_swing_toe_linear_velocity_z_RightStance.hh
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
Cassie_Example/opt_two_step/periodic/c_code/include/frost/gen/J_swing_toe_linear_velocity_z_RightStance.hh
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
Cassie_Example/opt_two_step/periodic/c_code/include/frost/gen/J_swing_toe_linear_velocity_z_RightStance.hh
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
/* * Automatically Generated from Mathematica. * Fri 5 Nov 2021 09:01:51 GMT-04:00 */ #ifndef J_SWING_TOE_LINEAR_VELOCITY_Z_RIGHTSTANCE_HH #define J_SWING_TOE_LINEAR_VELOCITY_Z_RIGHTSTANCE_HH namespace frost { namespace gen { void J_swing_toe_linear_velocity_z_RightStance(double *p_output1, const double *var1); } } #endif // J_SWING_TOE_LINEAR_VELOCITY_Z_RIGHTSTANCE_HH
24.625
94
0.78934
prem-chand
5415d1124c1fd493d6ec1787b2e2835f96e6cede
1,220
cpp
C++
aoj/itp2/itp2_8_d.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
aoj/itp2/itp2_8_d.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
aoj/itp2/itp2_8_d.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using pii = pair<int, int>; #define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i) #define all(x) (x).begin(),(x).end() #define m0(x) memset(x,0,sizeof(x)) int dx4[4] = {1,0,-1,0}, dy4[4] = {0,1,0,-1}; int main(){ multimap<string, int> m; int q; cin>>q; for(int i = 0; i < q; i++) { int cmd; string key; cin>>cmd>>key; if(cmd==0) { int x; cin>>x; m.insert(make_pair(key,x)); } else if(cmd==1) { auto range = m.equal_range(key); for(auto i = range.first; i != range.second; i++) { cout<<i->second<<endl; } } else if(cmd==2) { m.erase(key); } else if(cmd==3) { string key2; cin>>key2; auto bg = m.lower_bound(key); auto en = m.upper_bound(key2); for(auto i = bg; i != en; i++) { cout<<i->first<<" "<<i->second<<endl; } } } return 0; }
21.034483
61
0.402459
yu3mars
541bfaffb4ce6c05ac29375db2c5ba4705b308b8
810
cpp
C++
src/tracelog/private/tracelog.cpp
aeon-engine/libaeon
e42b39e621dcd0a0fba05e1c166fc688288fb69b
[ "BSD-2-Clause" ]
7
2017-02-19T16:22:16.000Z
2021-03-02T05:47:39.000Z
src/tracelog/private/tracelog.cpp
aeon-engine/libaeon
e42b39e621dcd0a0fba05e1c166fc688288fb69b
[ "BSD-2-Clause" ]
61
2017-05-29T06:11:17.000Z
2021-03-28T21:51:44.000Z
src/tracelog/private/tracelog.cpp
aeon-engine/libaeon
e42b39e621dcd0a0fba05e1c166fc688288fb69b
[ "BSD-2-Clause" ]
2
2017-05-28T17:17:40.000Z
2017-07-14T21:45:16.000Z
// Distributed under the BSD 2-Clause License - Copyright 2012-2021 Robin Degen #include <aeon/tracelog/tracelog.h> #include "context.h" namespace aeon::tracelog { namespace detail { [[nodiscard]] auto add_entry(const char *func) -> trace_log_entry * { return detail::trace_log_context::get_singleton().add_scoped_log_entry(func); } void add_exit(trace_log_entry *entry) { detail::trace_log_context::get_singleton().add_scoped_log_exit(entry); } void add_event(const char *func) { detail::trace_log_context::get_singleton().add_event(func); } } // namespace detail void initialize() { detail::trace_log_context::get_singleton().initialize(); } void write(const std::filesystem::path &file) { detail::trace_log_context::get_singleton().write(file); } } // namespace aeon::tracelog
20.25
81
0.741975
aeon-engine
54241cf24a2498962ebfbf4679ac5c865480b286
1,844
cpp
C++
codes/codechef/COVID19B.cpp
smmehrab/problem-solving
4aeab1673f18d3270ee5fc9b64ed6805eacf4af5
[ "MIT" ]
null
null
null
codes/codechef/COVID19B.cpp
smmehrab/problem-solving
4aeab1673f18d3270ee5fc9b64ed6805eacf4af5
[ "MIT" ]
null
null
null
codes/codechef/COVID19B.cpp
smmehrab/problem-solving
4aeab1673f18d3270ee5fc9b64ed6805eacf4af5
[ "MIT" ]
null
null
null
/* ************************************************ username : smmehrab fullname : s.m.mehrabul islam email : mehrab.24csedu.001@gmail.com institute : university of dhaka, bangladesh session : 2017-2018 ************************************************ */ #include<bits/stdc++.h> using namespace std; int main(){ int testCases, n, worstCase, bestCase, t, x; cin >> testCases; while(testCases--){ cin >> n; vector<int> v(n); for(int &x : v) cin >> x; bestCase = n; worstCase = 0; map<pair<int,int>, vector<int>> pairsMeetingAt; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++) { if(v[i]>v[j]){ t= ((j-i)*120)/(v[i]-v[j]); x = i*120+v[i]*t; assert(120*i+v[i]*t == 120*j+v[j]*t); pairsMeetingAt[{t,x}].push_back(i); pairsMeetingAt[{t,x}].push_back(j); } } } for(int infectedAthlete=0; infectedAthlete<n; infectedAthlete++){ vector<bool>isInfected(n, false); isInfected[infectedAthlete]=true; for(auto entry : pairsMeetingAt){ bool spread = false; for(int athlete : entry.second) spread |= isInfected[athlete]; if(spread){ for(int athlete : entry.second) isInfected[athlete]=true; } } int totalInfected=0; for(int athlete=0; athlete<n; athlete++){ if(isInfected[athlete]) totalInfected++; } bestCase = min(bestCase, totalInfected); worstCase = max(worstCase, totalInfected); } cout << bestCase << " " << worstCase << endl; } return 0; }
30.229508
78
0.457158
smmehrab
5425887d7dc38fe98b25608a3311e5a1f22a96aa
299
cpp
C++
ALGS200x/Week2/Challenge2-6/CPP/reuse_main.cpp
davidlowryduda/udacity
fd55ab3f40a77baa49e47a8c08ce42cd823decd9
[ "MIT" ]
null
null
null
ALGS200x/Week2/Challenge2-6/CPP/reuse_main.cpp
davidlowryduda/udacity
fd55ab3f40a77baa49e47a8c08ce42cd823decd9
[ "MIT" ]
null
null
null
ALGS200x/Week2/Challenge2-6/CPP/reuse_main.cpp
davidlowryduda/udacity
fd55ab3f40a77baa49e47a8c08ce42cd823decd9
[ "MIT" ]
null
null
null
/* * Compute fib(0) + ... + fib(n) % 10. * * The key is that fib(0) + ... + fib(n) = fib(n+2) - 1. */ #include <iostream> #include "reuse_util.h" int main() { long num, ans; while (std::cin >> num) { ans = (fast_fib_mod(num+2, 10) + 9) % 10; std::cout << ans << std::endl; } }
15.736842
56
0.494983
davidlowryduda
542941f130e87debf917c04e1a8ba28f233f17c6
600
cpp
C++
URI/Beginner/Little Ducks.cpp
Mhmd-Hisham/Problem-Solving
7ce0955b697e735c5ccb37347d9bec83e57339b5
[ "MIT" ]
null
null
null
URI/Beginner/Little Ducks.cpp
Mhmd-Hisham/Problem-Solving
7ce0955b697e735c5ccb37347d9bec83e57339b5
[ "MIT" ]
null
null
null
URI/Beginner/Little Ducks.cpp
Mhmd-Hisham/Problem-Solving
7ce0955b697e735c5ccb37347d9bec83e57339b5
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; unsigned long long N; int main () { while ( cin >> N && N != -1 ){ cout << ((N>0)? N-1 : 0) << '\n'; } return 0; } /* unsigned long long you dump bitch! input:- ----------- inline string ToString( int n ){ stringstream s; s << n; return s.str(); } int ToInt( char s ){ int n = 0; stringstream (s) >> n; return n; } 0 1 10000000000000000000 -1 0 1 10000000000000000000 -1 100 0 0 1 (n=0)? { n = 9; c = 1 } 9, 9 (n>0)? { n-= (C+1); c = 0;} --, -- 100 0 0 1 output:- ----------- Problem: */
7.142857
35
0.486667
Mhmd-Hisham
542a3b3353400afc9648553f6802ff70e4dd2870
2,451
cpp
C++
src/voiceinfo.cpp
moutend/AudioAgent
dbdc6eff00986892ba1d334a91826a249ddac93d
[ "MIT" ]
1
2019-10-22T08:20:46.000Z
2019-10-22T08:20:46.000Z
src/voiceinfo.cpp
moutend/AudioAgent
dbdc6eff00986892ba1d334a91826a249ddac93d
[ "MIT" ]
null
null
null
src/voiceinfo.cpp
moutend/AudioAgent
dbdc6eff00986892ba1d334a91826a249ddac93d
[ "MIT" ]
null
null
null
#include <cpplogger/cpplogger.h> #include <cstring> #include <ppltasks.h> #include <roapi.h> #include <robuffer.h> #include <wrl.h> #include "context.h" #include "util.h" #include "voiceinfo.h" using namespace Microsoft::WRL; using namespace Windows::Media::SpeechSynthesis; using namespace concurrency; using namespace Windows::Storage::Streams; using namespace Windows::Media; using Windows::Foundation::Metadata::ApiInformation; extern Logger::Logger *Log; DWORD WINAPI voiceInfo(LPVOID context) { Log->Info(L"Start Voice info thread", GetCurrentThreadId(), __LONGFILE__); VoiceInfoContext *ctx = static_cast<VoiceInfoContext *>(context); if (ctx == nullptr) { Log->Fail(L"Failed to obtain ctx", GetCurrentThreadId(), __LONGFILE__); return E_FAIL; } RoInitialize(RO_INIT_MULTITHREADED); auto synth = ref new SpeechSynthesizer(); ctx->Count = synth->AllVoices->Size; ctx->VoiceProperties = new VoiceProperty *[synth->AllVoices->Size]; unsigned int defaultVoiceIndex{}; VoiceInformation ^ defaultInfo = synth->DefaultVoice; for (unsigned int i = 0; i < ctx->Count; ++i) { synth->Voice = synth->AllVoices->GetAt(i); ctx->VoiceProperties[i] = new VoiceProperty(); size_t idLength = wcslen(synth->Voice->Id->Data()); ctx->VoiceProperties[i]->Id = new wchar_t[idLength + 1]{}; std::wmemcpy(ctx->VoiceProperties[i]->Id, synth->Voice->Id->Data(), idLength); size_t displayNameLength = wcslen(synth->Voice->DisplayName->Data()); ctx->VoiceProperties[i]->DisplayName = new wchar_t[displayNameLength + 1]{}; std::wmemcpy(ctx->VoiceProperties[i]->DisplayName, synth->Voice->DisplayName->Data(), displayNameLength); size_t languageLength = wcslen(synth->Voice->Language->Data()); ctx->VoiceProperties[i]->Language = new wchar_t[languageLength + 1]{}; std::wmemcpy(ctx->VoiceProperties[i]->Language, synth->Voice->Language->Data(), languageLength); ctx->VoiceProperties[i]->SpeakingRate = synth->Options->SpeakingRate; ctx->VoiceProperties[i]->AudioPitch = synth->Options->AudioPitch; ctx->VoiceProperties[i]->AudioVolume = synth->Options->AudioVolume; if (defaultInfo->Id->Equals(synth->Voice->Id)) { defaultVoiceIndex = i; } } ctx->DefaultVoiceIndex = defaultVoiceIndex; RoUninitialize(); Log->Info(L"End Voice info thread", GetCurrentThreadId(), __LONGFILE__); return S_OK; }
31.025316
80
0.69849
moutend
542af8de6323bca1b994754e62fe67893df61f91
6,349
cpp
C++
Demo05-Application/DemoApplication.cpp
iondune/ionEngine
7ce3394dafbabf0e0bb9f5d07dbfae31161800d4
[ "MIT" ]
36
2015-06-28T14:53:06.000Z
2021-10-31T04:26:53.000Z
Demo05-Application/DemoApplication.cpp
iondune/ionEngine
7ce3394dafbabf0e0bb9f5d07dbfae31161800d4
[ "MIT" ]
90
2015-05-01T07:21:43.000Z
2017-08-30T01:16:41.000Z
Demo05-Application/DemoApplication.cpp
iondune/ionEngine
7ce3394dafbabf0e0bb9f5d07dbfae31161800d4
[ "MIT" ]
9
2016-04-08T07:48:02.000Z
2019-07-22T15:13:53.000Z
#include <ionWindow.h> #include <ionGraphics.h> #include <ionGraphicsGL.h> #include <ionScene.h> #include <ionApplication.h> using namespace ion; using namespace ion::Scene; using namespace ion::Graphics; int main() { //////////////////// // ionEngine Init // //////////////////// Log::AddDefaultOutputs(); SingletonPointer<CGraphicsAPI> GraphicsAPI; SingletonPointer<CWindowManager> WindowManager; SingletonPointer<CTimeManager> TimeManager; SingletonPointer<CSceneManager> SceneManager; SingletonPointer<CAssetManager> AssetManager; GraphicsAPI->Init(new Graphics::COpenGLImplementation()); WindowManager->Init(GraphicsAPI); TimeManager->Init(WindowManager); SceneManager->Init(GraphicsAPI); AssetManager->Init(GraphicsAPI); CWindow * Window = WindowManager->CreateWindow(vec2i(1600, 900), "DemoApplication", EWindowType::Windowed); AssetManager->AddAssetPath("Assets"); AssetManager->SetShaderPath("Shaders"); AssetManager->SetTexturePath("Images"); SharedPointer<IGraphicsContext> Context = GraphicsAPI->GetWindowContext(Window); SharedPointer<IRenderTarget> RenderTarget = Context->GetBackBuffer(); RenderTarget->SetClearColor(color3f(0.3f)); ///////////////// // Load Assets // ///////////////// CSimpleMesh * SphereMesh = CGeometryCreator::CreateSphere(); CSimpleMesh * SkyBoxMesh = CGeometryCreator::CreateCube(); CSimpleMesh * PlaneMesh = CGeometryCreator::CreatePlane(vec2f(100.f)); SharedPointer<IShader> DiffuseShader = AssetManager->LoadShader("Diffuse"); SharedPointer<IShader> SimpleShader = AssetManager->LoadShader("Simple"); SharedPointer<IShader> SpecularShader = AssetManager->LoadShader("Specular"); SharedPointer<IShader> SkyBoxShader = AssetManager->LoadShader("SkyBox"); SharedPointer<ITextureCubeMap> SkyBoxTexture = AssetManager->LoadCubeMapTexture( "DarkStormyLeft2048.png", "DarkStormyRight2048.png", "DarkStormyUp2048.png", "DarkStormyDown2048.png", "DarkStormyFront2048.png", "DarkStormyBack2048.png"); //////////////////// // ionScene Setup // //////////////////// CRenderPass * RenderPass = new CRenderPass(Context); RenderPass->SetRenderTarget(RenderTarget); SceneManager->AddRenderPass(RenderPass); CPerspectiveCamera * Camera = new CPerspectiveCamera(Window->GetAspectRatio()); Camera->SetPosition(vec3f(0, 3, -5)); Camera->SetFocalLength(0.4f); RenderPass->SetActiveCamera(Camera); CCameraController * Controller = new CCameraController(Camera); Controller->SetTheta(15.f * Constants32::Pi / 48.f); Controller->SetPhi(-Constants32::Pi / 16.f); Window->AddListener(Controller); TimeManager->MakeUpdateTick(0.02)->AddListener(Controller); ///////////////// // Add Objects // ///////////////// CSimpleMeshSceneObject * LightSphere1 = new CSimpleMeshSceneObject(); LightSphere1->SetMesh(SphereMesh); LightSphere1->SetShader(SimpleShader); LightSphere1->SetPosition(vec3f(0, 1, 0)); RenderPass->AddSceneObject(LightSphere1); CSimpleMeshSceneObject * LightSphere2 = new CSimpleMeshSceneObject(); LightSphere2->SetMesh(SphereMesh); LightSphere2->SetShader(SimpleShader); LightSphere2->SetPosition(vec3f(4, 2, 0)); RenderPass->AddSceneObject(LightSphere2); CSimpleMeshSceneObject * LightSphere3 = new CSimpleMeshSceneObject(); LightSphere3->SetMesh(SphereMesh); LightSphere3->SetShader(SimpleShader); LightSphere3->SetPosition(vec3f(12, 3, 0)); RenderPass->AddSceneObject(LightSphere3); CSimpleMeshSceneObject * SpecularSphere = new CSimpleMeshSceneObject(); SpecularSphere->SetMesh(SphereMesh); SpecularSphere->SetShader(SpecularShader); SpecularSphere->SetPosition(vec3f(3, 3, 6)); SpecularSphere->GetMaterial().Ambient = vec3f(0.05f); RenderPass->AddSceneObject(SpecularSphere); CSimpleMeshSceneObject * PlaneObject = new CSimpleMeshSceneObject(); PlaneObject->SetMesh(PlaneMesh); PlaneObject->SetShader(DiffuseShader); PlaneObject->GetMaterial().Ambient = vec3f(0.05f, 0.05f, 0.1f); RenderPass->AddSceneObject(PlaneObject); CSimpleMeshSceneObject * PlaneObject2 = new CSimpleMeshSceneObject(); PlaneObject2->SetMesh(PlaneMesh); PlaneObject2->SetShader(DiffuseShader); PlaneObject2->SetScale(0.5f); PlaneObject2->GetMaterial().Ambient = vec3f(0.05f); PlaneObject2->SetFeatureEnabled(Graphics::EDrawFeature::PolygonOffset, true); PlaneObject2->SetPolygonOffsetAmount(-1.f); RenderPass->AddSceneObject(PlaneObject2); CSimpleMeshSceneObject * SkySphereObject = new CSimpleMeshSceneObject(); SkySphereObject->SetMesh(SkyBoxMesh); SkySphereObject->SetShader(SkyBoxShader); SkySphereObject->SetTexture("uTexture", SkyBoxTexture); RenderPass->AddSceneObject(SkySphereObject); CPointLight * Light1 = new CPointLight(); Light1->SetPosition(vec3f(0, 1, 0)); Light1->SetColor(Color::Basic::Red); RenderPass->AddLight(Light1); CPointLight * Light2 = new CPointLight(); Light2->SetPosition(vec3f(4, 2, 0)); Light2->SetColor(Color::Basic::Green); RenderPass->AddLight(Light2); CPointLight * Light3 = new CPointLight(); Light3->SetPosition(vec3f(12, 3, 0)); Light3->SetColor(Color::Basic::Blue); RenderPass->AddLight(Light3); /////////////// // Main Loop // /////////////// TimeManager->Init(WindowManager); while (WindowManager->Run()) { TimeManager->Update(); float const MinimumBrightness = 0.2f; float const MaximumBrightness = 1.f - MinimumBrightness; float const Brightness = (Sin<float>((float) TimeManager->GetRunTime()) / 2.f + 0.5f) * MaximumBrightness + MinimumBrightness; float const Radius = Brightness * 10.f; Light1->SetRadius(Radius); Light2->SetRadius(Radius); Light3->SetRadius(Radius); float const Bright = 1; float const Dim = 0.5f; LightSphere1->GetMaterial().Diffuse = color3f(Bright, Dim, Dim) * Brightness; LightSphere2->GetMaterial().Diffuse = color3f(Dim, Bright, Dim) * Brightness; LightSphere3->GetMaterial().Diffuse = color3f(Dim, Dim, Bright) * Brightness; LightSphere1->SetScale(Brightness); LightSphere2->SetScale(Brightness); LightSphere3->SetScale(Brightness); SkySphereObject->SetPosition(Camera->GetPosition()); RenderTarget->ClearColorAndDepth(); SceneManager->DrawAll(); Window->SwapBuffers(); } return 0; }
33.951872
129
0.724366
iondune
5432f046bf6cf00712950ba32f3906c1e6110f9a
3,058
hpp
C++
include/uMon/z80.hpp
trevor-makes/uMon
484dc46be45d6eb5ed37f9235ab28d5d3bb40344
[ "MIT" ]
null
null
null
include/uMon/z80.hpp
trevor-makes/uMon
484dc46be45d6eb5ed37f9235ab28d5d3bb40344
[ "MIT" ]
null
null
null
include/uMon/z80.hpp
trevor-makes/uMon
484dc46be45d6eb5ed37f9235ab28d5d3bb40344
[ "MIT" ]
null
null
null
// https://github.com/trevor-makes/uMon.git // Copyright (c) 2022 Trevor Makes #pragma once #include "z80/asm.hpp" #include "z80/dasm.hpp" #include "uCLI.hpp" namespace uMon { namespace z80 { template <typename API> bool parse_operand(Operand& op, uCLI::Tokens tokens) { // Handle indirect operand surronded by parentheses bool is_indirect = false; if (tokens.peek_char() == '(') { is_indirect = true; tokens.split_at('('); tokens = tokens.split_at(')'); // Split optional displacement following +/- uCLI::Tokens disp_tok = tokens; bool is_minus = false; disp_tok.split_at('+'); if (!disp_tok.has_next()) { disp_tok = tokens; disp_tok.split_at('-'); is_minus = true; } // Parse displacement and apply sign uMON_OPTION_UINT(API, uint16_t, disp, 0, disp_tok, return false); op.value = is_minus ? -disp : disp; } // Parse operand as char, number, or token bool is_string = tokens.is_string(); auto op_str = tokens.next(); uint16_t value; if (is_string) { uMON_FMT_ERROR(API, strlen(op_str) > 1, "chr", op_str, return false); op.token = TOK_IMMEDIATE; op.value = op_str[0]; } else if (API::get_labels().get_addr(op_str, value)) { op.token = TOK_IMMEDIATE; op.value = value; } else if (parse_unsigned(value, op_str)) { op.token = TOK_IMMEDIATE; op.value = value; } else { op.token = pgm_bsearch(TOK_STR, op_str); uMON_FMT_ERROR(API, op.token == TOK_INVALID, "arg", op_str, return false); } if (is_indirect) { op.token |= TOK_INDIRECT; } return true; } template <typename API> bool parse_instruction(Instruction& inst, uCLI::Tokens args) { const char* mnemonic = args.next(); inst.mnemonic = pgm_bsearch(MNE_STR, mnemonic); uMON_FMT_ERROR(API, inst.mnemonic == MNE_INVALID, "op", mnemonic, return false); // Parse operands for (Operand& op : inst.operands) { if (!args.has_next()) break; if (!parse_operand<API>(op, args.split_at(','))) return false; } // Error if unparsed operands remain uMON_FMT_ERROR(API, args.has_next(), "rem", args.next(), return false); return true; } template <typename API> void cmd_asm(uCLI::Args args) { uMON_EXPECT_ADDR(API, uint16_t, start, args, return); // Parse and assemble instruction Instruction inst; if (parse_instruction<API>(inst, args)) { uint8_t size = asm_instruction<API>(inst, start); if (size > 0) { set_prompt<API>(args.command(), start + size); } } } template <typename API, uint8_t MAX_ROWS = 24> void cmd_dasm(uCLI::Args args) { // Default size to one instruction if not provided uMON_EXPECT_ADDR(API, uint16_t, start, args, return); uMON_OPTION_UINT(API, uint16_t, size, 1, args, return); uint16_t end_incl = start + size - 1; uint16_t next = dasm_range<API, MAX_ROWS>(start, end_incl); uint16_t part = next - start; if (part < size) { set_prompt<API>(args.command(), next, size - part); } else { set_prompt<API>(args.command(), next); } } } // namespace z80 } // namespace uMon
27.8
82
0.66416
trevor-makes
f9ab206b58a1253d0da876422963da3d8d50cae4
738
hpp
C++
libs/fnd/units/include/bksge/fnd/units/bit.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/fnd/units/include/bksge/fnd/units/bit.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/fnd/units/include/bksge/fnd/units/bit.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file bit.hpp * * @brief bit の定義 * * @author myoukaku */ #ifndef BKSGE_FND_UNITS_BIT_HPP #define BKSGE_FND_UNITS_BIT_HPP #include <bksge/fnd/units/base_dimensions/information.hpp> #include <bksge/fnd/units/detail/quantity.hpp> #include <bksge/fnd/units/detail/si_prefix.hpp> #include <bksge/fnd/units/detail/binary_prefix.hpp> namespace bksge { namespace units { // ビット template <typename T> using bit = quantity<T, information_dimension>; template <typename T> using bits = bit<T>; BKSGE_UNITS_SI_PREFIX(bit); BKSGE_UNITS_SI_PREFIX(bits); BKSGE_UNITS_BINARY_PREFIX(bit); BKSGE_UNITS_BINARY_PREFIX(bits); } // namespace units } // namespace bksge #endif // BKSGE_FND_UNITS_BIT_HPP
20.5
71
0.727642
myoukaku
f9ad4312de5c1a791a43fc1f5c8245b363d36f9a
4,636
hh
C++
include/utrig_matrix.hh
sylvainouel/metl
94fa40b9aabdf869cab8e6b92305a9fe5252f989
[ "MIT" ]
null
null
null
include/utrig_matrix.hh
sylvainouel/metl
94fa40b9aabdf869cab8e6b92305a9fe5252f989
[ "MIT" ]
null
null
null
include/utrig_matrix.hh
sylvainouel/metl
94fa40b9aabdf869cab8e6b92305a9fe5252f989
[ "MIT" ]
null
null
null
#ifndef UTRIG_MATRIX_HH #define UTRIG_MATRIX_HH /* Copyright (c) 2005-2015, Sylvain Ouellet 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. */ // that is an upper triangular matrx. i.e. only elements m(i,j) where // j>i are accessibles namespace metl { template <class T> class utrig_matrix; template<class T> struct utrig_matrix_iterator { utrig_matrix_iterator(utrig_matrix<T>& point_to) : m(point_to), i(0), j(1) {} utrig_matrix_iterator(utrig_matrix<T>& point_to, unsigned init_i, unsigned init_j) : m(point_to), i(init_i), j(init_j) { assert(j>i); } inline T& operator*() { return m(i,j); } inline const T& operator*() const { return m(i,j); } inline utrig_matrix_iterator& operator++() { assert(j>i); assert(j<m.cols); if (++j == m.cols) { ++i; j=i+1; } return *this; } inline bool operator==(const utrig_matrix_iterator& rhs) const { return (&m==&rhs.m && i==rhs.i && j==rhs.j); } inline bool operator!=(const utrig_matrix_iterator& rhs) const { return !(operator==(rhs)); } inline unsigned get_i() const { return i; } // this is needed. we need to know were the iterator points. inline unsigned get_j() const { return j; } private: utrig_matrix<T>& m; unsigned i, j; friend class utrig_matrix<T>; }; template<class T> class utrig_matrix { public: typedef utrig_matrix_iterator<T> iterator; utrig_matrix() {}; utrig_matrix(unsigned nrows, unsigned ncols); ~utrig_matrix(); utrig_matrix(const utrig_matrix& m); utrig_matrix& operator= (const utrig_matrix& m); // Access methods to get the (i,j) element: inline T& operator() (unsigned i, unsigned j) { assert(j>i); return data_[i][j-i-1]; }; inline const T& operator() (unsigned i, unsigned j) const { assert(j>i); return data_[i][j-i-1]; }; iterator begin() { return iterator(*this); } const iterator end() { return iterator(*this, rows-1, cols); } private: T** data_; unsigned rows, cols; friend class utrig_matrix_iterator<T>; }; template<class T> utrig_matrix<T>::utrig_matrix(const utrig_matrix<T>& m) : data_(0), rows(m.rows), cols(m.cols) { if (rows==0) return; // allocate memory data_ = new T*[rows]; for (unsigned i=0; i<rows; ++i) data_[i] = new T[cols-i-1]; for (unsigned i=0; i<rows; ++i) for (unsigned j=i+1; j<cols; ++j) operator()(i,j) = m.operator()(i,j); } template <class T> utrig_matrix<T>& utrig_matrix<T>::operator= (const utrig_matrix<T>& m) { if (this == &m) return *this; if (cols!=m.cols || rows!=m.rows) { for (unsigned i=0; i<rows; ++i) delete[] data_[i]; if (rows!=m.rows) { if (rows!=0) delete[] data_; if (m.rows>0) data_ = new T*[m.rows]; else data_ = 0; } rows=m.rows; cols=m.cols; for (unsigned i=0; i<m.rows; ++i) { data_[i] = new T[m.cols]; } } // copy data from old matrix to new one for (unsigned i=0; i<rows; ++i) for (unsigned j=i+1; j<cols; ++j) operator()(i,j) = m.operator()(i,j); return *this; } template<class T> utrig_matrix<T>::utrig_matrix(unsigned nrows, unsigned ncols) : data_(0), rows(nrows), cols(ncols) { if (rows==0) return; data_ = new T*[nrows]; for (unsigned i=0; i<nrows; ++i) data_[i] = new T[ncols]; for (unsigned i=0; i<nrows; ++i) for (unsigned j=i+1; j<ncols; ++j) operator()(i,j) = 0; } template<class T> utrig_matrix<T>::~utrig_matrix() { if (rows>0) { for (unsigned i=0; i<rows; ++i) delete[] data_[i]; delete[] data_; } } } #endif
21.663551
107
0.646894
sylvainouel
f9b2d5bdc7028669a74eee6f1765882ce5cf49d7
8,467
cc
C++
framework/render/vk/vk_image_barrier.cc
ans-hub/gdm_framework
4218bb658d542df2c0568c4d3aac813cd1f18e1b
[ "MIT" ]
1
2020-12-30T23:50:01.000Z
2020-12-30T23:50:01.000Z
framework/render/vk/vk_image_barrier.cc
ans-hub/gdm_framework
4218bb658d542df2c0568c4d3aac813cd1f18e1b
[ "MIT" ]
null
null
null
framework/render/vk/vk_image_barrier.cc
ans-hub/gdm_framework
4218bb658d542df2c0568c4d3aac813cd1f18e1b
[ "MIT" ]
null
null
null
// ************************************************************* // File: vk_image_barrier.cc // Author: Novoselov Anton @ 2020 // URL: https://github.com/ans-hub/gdm_framework // ************************************************************* #include "vk_image_barrier.h" #include "render/vk/vk_image.h" #include "render/vk/vk_image_view.h" #include "system/assert_utils.h" #include "system/bits_utils.h" // --public Resource<ImageBarrier> gdm::vk::Resource<gdm::vk::ImageBarrier>::Resource(api::Device* device) : BaseResourceBuilder(*device) { ptr_->image_barrier_.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; ptr_->image_barrier_.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; ptr_->image_barrier_.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; ptr_->image_barrier_.subresourceRange.baseMipLevel = 0; ptr_->image_barrier_.subresourceRange.levelCount = 1; ptr_->image_barrier_.subresourceRange.baseArrayLayer = 0; ptr_->image_barrier_.subresourceRange.layerCount = 1; ptr_->image_barrier_.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; } gdm::vk::Resource<gdm::vk::ImageBarrier>::~Resource() { FillAspectMask(ptr_->image_barrier_.newLayout, VK_FORMAT_UNDEFINED); FillAccessMasks(ptr_->image_barrier_.oldLayout, ptr_->image_barrier_.newLayout); ptr_->src_stage_mask_ = api::helpers::GetStageMask(ptr_->image_barrier_.srcAccessMask); ptr_->dst_stage_mask_ = api::helpers::GetStageMask(ptr_->image_barrier_.dstAccessMask); } auto gdm::vk::Resource<gdm::vk::ImageBarrier>::AddImage(VkImage image) -> Resource::self { ptr_->image_barrier_.image = image; return *this; } auto gdm::vk::Resource<gdm::vk::ImageBarrier>::AddOldLayout(gfx::EImageLayout old_layout) -> Resource::self { ptr_->image_barrier_.oldLayout = VkImageLayout(old_layout); return *this; } auto gdm::vk::Resource<gdm::vk::ImageBarrier>::AddNewLayout(gfx::EImageLayout new_layout) -> Resource::self { ptr_->image_barrier_.newLayout = VkImageLayout(new_layout); return *this; } // --private Resource<ImageBarrier> void gdm::vk::Resource<gdm::vk::ImageBarrier>::FillAspectMask(VkImageLayout layout, VkFormat format) { if (layout != VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) ptr_->image_barrier_.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; else { bool has_stencil = api::helpers::HasStencil(format); if (has_stencil) ptr_->image_barrier_.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; else ptr_->image_barrier_.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; } } void gdm::vk::Resource<gdm::vk::ImageBarrier>::FillAccessMasks(VkImageLayout old_layout, VkImageLayout new_layout) { if (old_layout == VK_IMAGE_LAYOUT_PREINITIALIZED && new_layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_PREINITIALIZED && new_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && new_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_PRESENT_SRC_KHR && new_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL && new_layout == VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_UNDEFINED && new_layout == VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) { ptr_->image_barrier_.srcAccessMask = 0; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_UNDEFINED && new_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = 0; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_UNDEFINED && new_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = 0; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_PREINITIALIZED && new_layout == VK_IMAGE_LAYOUT_GENERAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_GENERAL && new_layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL && new_layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_GENERAL && new_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL && new_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL && new_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_SHADER_READ_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_UNDEFINED && new_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = 0; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_UNDEFINED && new_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = 0; ptr_->image_barrier_.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; } else if (old_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL && new_layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) { ptr_->image_barrier_.srcAccessMask = VK_ACCESS_SHADER_READ_BIT; ptr_->image_barrier_.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; } else { ASSERTF(false, "Unsupported yet image layout transition"); } } // --helpers auto gdm::vk::helpers::GetStageMask(VkAccessFlags access) -> VkPipelineStageFlagBits { VkPipelineStageFlagBits mask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; if (bits::HasFlag(access, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT)) return VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT; else if (bits::HasFlag(access, VK_ACCESS_UNIFORM_READ_BIT)) return VK_PIPELINE_STAGE_VERTEX_SHADER_BIT; // TODO: else if (bits::HasFlag(access, VK_ACCESS_TRANSFER_WRITE_BIT)) return VK_PIPELINE_STAGE_TRANSFER_BIT; else if (bits::HasFlag(access, VK_ACCESS_TRANSFER_READ_BIT)) return VK_PIPELINE_STAGE_TRANSFER_BIT; else if (bits::HasFlag(access, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT)) return VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; else if (bits::HasFlag(access, VK_ACCESS_SHADER_READ_BIT)) return VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; else return mask; }
45.767568
134
0.77867
ans-hub
f9b78cda5b9efe33a1367fbf98be44327b177636
1,399
cpp
C++
priminitial.cpp
jei3di/DigraphMaker
40758f19057df663ac95f5f8a2e1cff8614a7c49
[ "MIT" ]
null
null
null
priminitial.cpp
jei3di/DigraphMaker
40758f19057df663ac95f5f8a2e1cff8614a7c49
[ "MIT" ]
null
null
null
priminitial.cpp
jei3di/DigraphMaker
40758f19057df663ac95f5f8a2e1cff8614a7c49
[ "MIT" ]
null
null
null
#include "priminitial.h" #include "ui_priminitial.h" #include "testfilegraph.h" #include "manualgraphscreen.h" #include "prim.h" int initialPrim = 0; int getInitialPrim(){ return initialPrim; } PrimInitial::PrimInitial(QWidget *parent) : QDialog(parent), ui(new Ui::PrimInitial) { ui->setupUi(this); int tempNodes; node *tempNode; bool auto_manualGraph; if(getManualGraph()) auto_manualGraph = false; else auto_manualGraph = true; if(auto_manualGraph){ // Automatic graph. tempNode = getAutoNodesArray(); tempNodes = getAutoNodes(); }else{ tempNode = getNodesArrayManual(); tempNodes = getManualNodes(); } // Nodes: QString label3; while(tempNodes >= 0){ string label = tempNode->label; QString label2 = QString::fromStdString(label); if(tempNodes == 0) label3 += label2 + "."; else label3 += label2 + ", "; tempNode = tempNode->next; tempNodes--; } if(auto_manualGraph) setNodesXY(); // Setting values for X & Y. else setManualNodesXY(); ui->nodes->appendPlainText(label3); } PrimInitial::~PrimInitial() { delete ui; } void PrimInitial::on_execute_clicked() { QString initialQ = ui->initial->text(); initialPrim = initialQ.toInt(); Prim *PrimW = new Prim(this); PrimW->setModal(true); PrimW->show(); }
20.275362
67
0.631165
jei3di
f9b882f4a86ced95a63cb4d4ee4670b8874d3417
2,203
cpp
C++
sources/details/http_service.cpp
RKulagin/keyboard-suggest
5dcb5ca524448cc6bd8a390a6eea5861e70a3598
[ "MIT" ]
null
null
null
sources/details/http_service.cpp
RKulagin/keyboard-suggest
5dcb5ca524448cc6bd8a390a6eea5861e70a3598
[ "MIT" ]
null
null
null
sources/details/http_service.cpp
RKulagin/keyboard-suggest
5dcb5ca524448cc6bd8a390a6eea5861e70a3598
[ "MIT" ]
null
null
null
#include "details/http_service.h" #include <sstream> namespace { std::string GetLastWord(const std::string &input) { std::stringstream s(input); std::string last_word; while (!s.eof()) { std::string t; s >> t; if (!t.empty()) { last_word = std::move(t); } } return last_word; } } // namespace void HttpService::Run(uint16_t port) { auto resource = std::make_shared<restbed::Resource>(); resource->set_path("/data"); resource->set_method_handler("GET", [this](const std::shared_ptr<restbed::Session> session) { Input input; input.input = session->get_request()->get_query_parameter("input", ""); input.last_word = GetLastWord(input.input); std::cout << input.last_word << std::endl; InternalState new_state; auto answer = MakeSuggestions(input, storage_, state_, new_state); holder_.Change(std::move(answer)); state_ = std::move(new_state); std::unique_lock<SceneHolder> lk(holder_); session->close(restbed::OK, holder_.data(), {{"Content-Type", "application/json"}}); }); auto viewer = std::make_shared<restbed::Resource>(); viewer->set_path("/viewer/{filename: (index.html|render.js)}"); viewer->set_method_handler("GET", [this](const std::shared_ptr<restbed::Session> session) { const auto request = session->get_request(); const std::string filename = request->get_path_parameter("filename"); std::ifstream stream(viewer_path_ + filename, std::ifstream::in); if (stream.is_open()) { const std::string body = std::string(std::istreambuf_iterator<char>(stream), std::istreambuf_iterator<char>()); session->close(restbed::OK, body); } else { session->close(restbed::NOT_FOUND); } }); auto settings = std::make_shared<restbed::Settings>(); settings->set_port(port); settings->set_default_header("Connection", "close"); std::cout << "Press Ctrl+C to stop the service." << std::endl; const std::string full_url = "http://localhost:" + std::to_string(port) + "/viewer/index.html"; std::cout << "Staring service: " << full_url << std::endl; restbed::Service service; service.publish(viewer); service.publish(resource); service.start(settings); }
32.880597
117
0.670903
RKulagin
f9bf74c6d7846e335efe0b4a9bbe840ecc741d63
1,040
hpp
C++
fsc/include/win/event.hpp
gbucknell/fsc-sdk
11b7cda4eea35ec53effbe37382f4b28020cd59d
[ "MIT" ]
null
null
null
fsc/include/win/event.hpp
gbucknell/fsc-sdk
11b7cda4eea35ec53effbe37382f4b28020cd59d
[ "MIT" ]
null
null
null
fsc/include/win/event.hpp
gbucknell/fsc-sdk
11b7cda4eea35ec53effbe37382f4b28020cd59d
[ "MIT" ]
null
null
null
// (c) Copyright 2008 Samuel Debionne. // // Distributed under the MIT Software License. (See accompanying file // license.txt) or copy at http://www.opensource.org/licenses/mit-license.php) // // See http://code.google.com/p/fsc-sdk/ for the library home page. // // $Revision: $ // $History: $ /// \file event.hpp /// Windows event #if !defined(__WIN_EVENT_HPP__) #define __WIN_EVENT_HPP__ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <windows.h> #include <boost/shared_ptr.hpp> #include <win/exception.hpp> namespace win { typedef boost::shared_ptr<void> event_t; inline event_t create_event(BOOL _bManualReset = FALSE) { event_t h(::CreateEvent(NULL, _bManualReset, FALSE, NULL), ::CloseHandle); if (!h) throw runtime_error("CreateEvent failed"); return h; } inline void set(event_t _h) { if (::SetEvent(_h.get())) throw runtime_error("SetEvent failed"); } } //namespace win #endif //__WIN_EVENT_HPP__
18.245614
80
0.651923
gbucknell
f9c13584f53883ed1e2dee30914e17d2bdc172b2
451
cpp
C++
dispenso/detail/per_thread_info.cpp
jeffamstutz/dispenso
0fb1db63a386c1ba59cd761677af6e9f0052c61c
[ "MIT" ]
1
2022-01-26T01:12:01.000Z
2022-01-26T01:12:01.000Z
dispenso/detail/per_thread_info.cpp
jeffamstutz/dispenso
0fb1db63a386c1ba59cd761677af6e9f0052c61c
[ "MIT" ]
null
null
null
dispenso/detail/per_thread_info.cpp
jeffamstutz/dispenso
0fb1db63a386c1ba59cd761677af6e9f0052c61c
[ "MIT" ]
null
null
null
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE.md file in the root directory of this source tree. #include <dispenso/detail/per_thread_info.h> namespace dispenso { namespace detail { PerThreadInfo& PerPoolPerThreadInfo::info() { static DISPENSO_THREAD_LOCAL PerThreadInfo perThreadInfo; return perThreadInfo; } } // namespace detail } // namespace dispenso
25.055556
66
0.767184
jeffamstutz
f9c2d9051da33322513478c8801323bd6ad62d57
69
cpp
C++
lib/cmake/Qt5Qml/Qt5Qml_QQmlNativeDebugConnectorFactory_Import.cpp
samlior/Qt5.15.0-rc2-static-macosx10.15
b9a1698a9a44baefbf3aa258af2ef487f12beff0
[ "blessing" ]
null
null
null
lib/cmake/Qt5Qml/Qt5Qml_QQmlNativeDebugConnectorFactory_Import.cpp
samlior/Qt5.15.0-rc2-static-macosx10.15
b9a1698a9a44baefbf3aa258af2ef487f12beff0
[ "blessing" ]
null
null
null
lib/cmake/Qt5Qml/Qt5Qml_QQmlNativeDebugConnectorFactory_Import.cpp
samlior/Qt5.15.0-rc2-static-macosx10.15
b9a1698a9a44baefbf3aa258af2ef487f12beff0
[ "blessing" ]
null
null
null
#include <QtPlugin> Q_IMPORT_PLUGIN(QQmlNativeDebugConnectorFactory)
23
48
0.884058
samlior
f9c4007b6b9ce98129216fc8e3dad7db8d32b9a4
6,915
cpp
C++
src/geo/test/latlng_codec_test.cpp
empiredan/pegasus
a095172ad1559cc0e65c7807a2baedc607cde50c
[ "Apache-2.0" ]
1,352
2017-10-16T03:24:54.000Z
2020-08-18T04:44:23.000Z
src/geo/test/latlng_codec_test.cpp
empiredan/pegasus
a095172ad1559cc0e65c7807a2baedc607cde50c
[ "Apache-2.0" ]
299
2017-10-19T05:33:32.000Z
2020-08-17T09:03:39.000Z
src/geo/test/latlng_codec_test.cpp
empiredan/pegasus
a095172ad1559cc0e65c7807a2baedc607cde50c
[ "Apache-2.0" ]
240
2017-10-16T05:57:04.000Z
2020-08-18T10:02:36.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include <memory> #include <gtest/gtest.h> #include <geo/lib/latlng_codec.h> #include <dsn/utility/errors.h> namespace pegasus { namespace geo { TEST(latlng_codec_test, set_latlng_indices) { latlng_codec codec; ASSERT_FALSE(codec.set_latlng_indices(3, 3).is_ok()); ASSERT_TRUE(codec.set_latlng_indices(3, 4).is_ok()); ASSERT_TRUE(codec.set_latlng_indices(4, 3).is_ok()); } TEST(latlng_codec_for_lbs_test, decode_from_value) { latlng_codec codec; ASSERT_TRUE(codec.set_latlng_indices(5, 4).is_ok()); double lat_degrees = 12.345; double lng_degrees = 67.890; S2LatLng latlng; std::string test_value = "00:00:00:00:01:5e|2018-04-26|2018-04-28|ezp8xchrr|" + std::to_string(lng_degrees) + "|" + std::to_string(lat_degrees) + "|24.043028|4.15921|0|-1"; ASSERT_TRUE(codec.decode_from_value(test_value, latlng)); ASSERT_DOUBLE_EQ(latlng.lat().degrees(), lat_degrees); ASSERT_DOUBLE_EQ(latlng.lng().degrees(), lng_degrees); test_value = "|2018-04-26|2018-04-28|ezp8xchrr|" + std::to_string(lng_degrees) + "|" + std::to_string(lat_degrees) + "|24.043028|4.15921|0|-1"; ASSERT_TRUE(codec.decode_from_value(test_value, latlng)); ASSERT_DOUBLE_EQ(latlng.lat().degrees(), lat_degrees); ASSERT_DOUBLE_EQ(latlng.lng().degrees(), lng_degrees); test_value = "00:00:00:00:01:5e||2018-04-28|ezp8xchrr|" + std::to_string(lng_degrees) + "|" + std::to_string(lat_degrees) + "|24.043028|4.15921|0|-1"; ASSERT_TRUE(codec.decode_from_value(test_value, latlng)); ASSERT_DOUBLE_EQ(latlng.lat().degrees(), lat_degrees); ASSERT_DOUBLE_EQ(latlng.lng().degrees(), lng_degrees); test_value = "00:00:00:00:01:5e|2018-04-26|2018-04-28|ezp8xchrr|" + std::to_string(lng_degrees) + "|" + std::to_string(lat_degrees) + "||4.15921|0|-1"; ASSERT_TRUE(codec.decode_from_value(test_value, latlng)); ASSERT_DOUBLE_EQ(latlng.lat().degrees(), lat_degrees); ASSERT_DOUBLE_EQ(latlng.lng().degrees(), lng_degrees); test_value = "00:00:00:00:01:5e|2018-04-26|2018-04-28|ezp8xchrr|" + std::to_string(lng_degrees) + "|" + std::to_string(lat_degrees) + "|24.043028|4.15921|0|"; ASSERT_TRUE(codec.decode_from_value(test_value, latlng)); ASSERT_DOUBLE_EQ(latlng.lat().degrees(), lat_degrees); ASSERT_DOUBLE_EQ(latlng.lng().degrees(), lng_degrees); test_value = "00:00:00:00:01:5e|2018-04-26|2018-04-28|ezp8xchrr||" + std::to_string(lat_degrees) + "|24.043028|4.15921|0|-1"; ASSERT_FALSE(codec.decode_from_value(test_value, latlng)); test_value = "00:00:00:00:01:5e|2018-04-26|2018-04-28|ezp8xchrr|" + std::to_string(lng_degrees) + "||24.043028|4.15921|0|-1"; ASSERT_FALSE(codec.decode_from_value(test_value, latlng)); test_value = "00:00:00:00:01:5e|2018-04-26|2018-04-28|ezp8xchrr|||24.043028|4.15921|0|-1"; ASSERT_FALSE(codec.decode_from_value(test_value, latlng)); } TEST(latlng_codec_for_aibox_test, decode_from_value) { latlng_codec codec; ASSERT_TRUE(codec.set_latlng_indices(0, 1).is_ok()); double lat_degrees = 12.345; double lng_degrees = 67.890; S2LatLng latlng; std::string test_value = std::to_string(lat_degrees) + "|" + std::to_string(lng_degrees); ASSERT_TRUE(codec.decode_from_value(test_value, latlng)); ASSERT_DOUBLE_EQ(latlng.lat().degrees(), lat_degrees); ASSERT_DOUBLE_EQ(latlng.lng().degrees(), lng_degrees); test_value = std::to_string(lat_degrees) + "|" + std::to_string(lng_degrees) + "|24.043028"; ASSERT_TRUE(codec.decode_from_value(test_value, latlng)); ASSERT_DOUBLE_EQ(latlng.lat().degrees(), lat_degrees); ASSERT_DOUBLE_EQ(latlng.lng().degrees(), lng_degrees); test_value = std::to_string(lat_degrees) + "|" + std::to_string(lng_degrees) + "||"; ASSERT_TRUE(codec.decode_from_value(test_value, latlng)); ASSERT_DOUBLE_EQ(latlng.lat().degrees(), lat_degrees); ASSERT_DOUBLE_EQ(latlng.lng().degrees(), lng_degrees); test_value = "|" + std::to_string(lat_degrees) + "|" + std::to_string(lng_degrees); ASSERT_FALSE(codec.decode_from_value(test_value, latlng)); test_value = "|" + std::to_string(lat_degrees); ASSERT_FALSE(codec.decode_from_value(test_value, latlng)); test_value = std::to_string(lng_degrees) + "|"; ASSERT_FALSE(codec.decode_from_value(test_value, latlng)); test_value = "|"; ASSERT_FALSE(codec.decode_from_value(test_value, latlng)); } TEST(latlng_codec_encode_test, encode_to_value) { latlng_codec codec; double lat_degrees = 12.345; double lng_degrees = 67.890; std::string value; ASSERT_TRUE(codec.set_latlng_indices(0, 1).is_ok()); ASSERT_TRUE(codec.encode_to_value(lat_degrees, lng_degrees, value)); ASSERT_EQ("12.345000|67.890000", value); ASSERT_TRUE(codec.set_latlng_indices(1, 0).is_ok()); ASSERT_TRUE(codec.encode_to_value(lat_degrees, lng_degrees, value)); ASSERT_EQ("67.890000|12.345000", value); ASSERT_TRUE(codec.set_latlng_indices(4, 5).is_ok()); ASSERT_TRUE(codec.encode_to_value(lat_degrees, lng_degrees, value)); ASSERT_EQ("||||12.345000|67.890000", value); ASSERT_TRUE(codec.set_latlng_indices(5, 4).is_ok()); ASSERT_TRUE(codec.encode_to_value(lat_degrees, lng_degrees, value)); ASSERT_EQ("||||67.890000|12.345000", value); ASSERT_TRUE(codec.set_latlng_indices(0, 3).is_ok()); ASSERT_TRUE(codec.encode_to_value(lat_degrees, lng_degrees, value)); ASSERT_EQ("12.345000|||67.890000", value); ASSERT_TRUE(codec.set_latlng_indices(3, 1).is_ok()); ASSERT_TRUE(codec.encode_to_value(lat_degrees, lng_degrees, value)); ASSERT_EQ("|67.890000||12.345000", value); ASSERT_FALSE(codec.encode_to_value(91, lng_degrees, value)); ASSERT_FALSE(codec.encode_to_value(-91, lng_degrees, value)); ASSERT_FALSE(codec.encode_to_value(lat_degrees, 181, value)); ASSERT_FALSE(codec.encode_to_value(lat_degrees, -181, value)); } } // namespace geo } // namespace pegasus
41.909091
100
0.701518
empiredan
f9c440dadba1c1355f84f73cb718dd9ee0efebeb
1,320
cpp
C++
CLI/files/PostTagCribFile.cpp
maxitg/PostTagSystem
7d7c506ed32ab105b2ad064ababf2299fc9e9cfd
[ "MIT" ]
6
2021-05-19T15:48:41.000Z
2022-02-06T05:38:20.000Z
CLI/files/PostTagCribFile.cpp
maxitg/PostTagSystem
7d7c506ed32ab105b2ad064ababf2299fc9e9cfd
[ "MIT" ]
6
2021-02-26T22:14:42.000Z
2021-03-15T19:16:55.000Z
CLI/files/PostTagCribFile.cpp
maxitg/PostTagSystem
7d7c506ed32ab105b2ad064ababf2299fc9e9cfd
[ "MIT" ]
null
null
null
#include "PostTagCribFile.hpp" #include "boost/format.hpp" using PostTagSystem::TagState; PostTagCribFile PostTagCribFileReader::read_file() { uint8_t file_magic = read_u8(); PostTagFileMagic format_magic = CribFileMagic; if (file_magic != format_magic) { throw std::runtime_error((boost::format("File magic number 0x%X did not match expected 0x%X") % static_cast<unsigned int>(file_magic) % static_cast<unsigned int>(format_magic)) .str()); } uint8_t version = read_u8(); switch (version) { case Version1: return read_file_V1(); default: throw std::runtime_error( (boost::format("Unsupported file version %u") % static_cast<unsigned int>(version)).str()); } } PostTagCribFile PostTagCribFileReader::read_file_V1() { PostTagCribFile file; file.version = Version1; file.checkpoint_count = read_u64(); file.checkpoints = read_checkpoints(file.checkpoint_count); return file; } std::vector<TagState> PostTagCribFileReader::read_checkpoints(uint64_t checkpoint_count) { std::vector<TagState> checkpoints(checkpoint_count); for (size_t i = 0; i < checkpoint_count; i++) { checkpoints[i].headState = read_u8(); checkpoints[i].tape = read_prefixed_bits(); } return checkpoints; }
28.695652
110
0.689394
maxitg
f9c45a730d3db5a964e21252cbf049c8ea4be75a
225
cpp
C++
sensor_fsm_coro_sched/Sources/fut_cpp.cpp
bbelson2/k22f_coro
f4388f39110dd60553d9b579a65ceadd518b1396
[ "MIT" ]
null
null
null
sensor_fsm_coro_sched/Sources/fut_cpp.cpp
bbelson2/k22f_coro
f4388f39110dd60553d9b579a65ceadd518b1396
[ "MIT" ]
null
null
null
sensor_fsm_coro_sched/Sources/fut_cpp.cpp
bbelson2/k22f_coro
f4388f39110dd60553d9b579a65ceadd518b1396
[ "MIT" ]
null
null
null
/* * fut_cpp.cpp * * Created on: 23 Nov 2018 * Author: Bruce Belson */ using namespace scheduling; upromise ufuture<int32_t> delayed_light(int32_t delay) { return } extern "C" int fut_test() { return 0; }
9.782609
47
0.653333
bbelson2
f9c92ba4b8a8bd6b518dc3b775ec0a5af0250f9f
1,162
cpp
C++
CoCoJoystick2PC/Blinker.cpp
ranaur/CoCoJoystick2PC
a49308201fbc04e20083eabd111b62b18d1b1211
[ "MIT" ]
null
null
null
CoCoJoystick2PC/Blinker.cpp
ranaur/CoCoJoystick2PC
a49308201fbc04e20083eabd111b62b18d1b1211
[ "MIT" ]
null
null
null
CoCoJoystick2PC/Blinker.cpp
ranaur/CoCoJoystick2PC
a49308201fbc04e20083eabd111b62b18d1b1211
[ "MIT" ]
null
null
null
#include "Blinker.h" void Blinker::play(const uint16_t *playTimes, int repeat = -1) { /*debug("Blinker::play() "); debugvar("repeat = ", repeat); debugvar("playTimes = ", (int)playTimes); debugln("");*/ _playTimes = playTimes; _repeat = repeat; on(); } void Blinker::loop(uint32_t now = millis()) { /*debugvar("start = ", _start); debugvar(" now = ", now); debugvar(" repeat = ", _repeat); debugvar(" position = ", _position); debugln("");*/ if(_repeat == 0) return; // it is not playing if(now > _nextFade) { _fade(_intensityStep * (_turningOn ? 1 : -1)); _nextFade += _timeStep; } if(now < _playUntil) return; // time to play next "time" has not yet arrived if(_playTimes[_position] == 0) { // ended the play if(_repeat < 0) { _reset(); return; } // infinite play _repeat--; if(_repeat == 0) { // turn off off(); } else { // play again _reset(); } } _playUntil += _playTimes[_position]; if(_position % 2 == 0) { on(); //debugln("ON"); } else { //debugln("OFF"); off(); } _position++; }
21.518519
79
0.539587
ranaur
f9caa1df7fb789af7b22ecafbb4c1b70cef620c0
3,230
cpp
C++
equalization_CPU.cpp
Programacion-multinucleo-2018/assignment-4-histogram-equalization-leeseu95
8cff72e9bb2f8e6427d88407af6f1d221bc921f4
[ "MIT" ]
null
null
null
equalization_CPU.cpp
Programacion-multinucleo-2018/assignment-4-histogram-equalization-leeseu95
8cff72e9bb2f8e6427d88407af6f1d221bc921f4
[ "MIT" ]
null
null
null
equalization_CPU.cpp
Programacion-multinucleo-2018/assignment-4-histogram-equalization-leeseu95
8cff72e9bb2f8e6427d88407af6f1d221bc921f4
[ "MIT" ]
null
null
null
//Seung Hoon Lee - A01021720 //Tarea 4 - Equalization CPU version //g++ -o equalization_CPU equalization_CPU.cpp -lopencv_core -lopencv_highgui -lopencv_imgproc -std=c++11 #include <iostream> #include <cstdio> #include <cmath> #include <chrono> #include <cstdlib> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace std; void createHistogram(cv::Mat& input, long *h_s) { int index; for(int i = 0; i < input.rows; i++) { for(int j = 0; j < input.cols; j++) { index = (int)input.at<uchar>(i,j); h_s[index]++; // h_s[0] = 1; // cout << h_s[index] << endl; } } } void normalize(cv::Mat& input, long *h_s) { long temp[256] = {}; for(int i = 0; i < 256; i++) { temp[i] = h_s[i]; } //Reinicializamos en 0 el histograma orgiinal for(int i = 0; i < 256; i++) { h_s[i] = 0; } for(int i = 0; i < 256; i++) { for(int j = 0; j <= i; j++) { h_s[i] += temp[j]; } int normalizeVar = (h_s[i]*255) / (input.rows*input.cols); // if (normalizeVar < 0) { // normalizeVar = abs(normalizeVar); // } h_s[i] = normalizeVar; // cout << h_s[i] << endl; //Debug } } void equalize(cv::Mat& input, cv::Mat& output, long * h_s){ int index; for(int i = 0; i < input.rows; i++) { for(int j = 0; j < input.cols; j++) { index = (int)input.at<uchar>(i,j); output.at<uchar>(i,j) = h_s[index]; } } } void equalizer(cv::Mat& input, cv::Mat& output) //Le pasamos de parametro solo el input , output con CV { cout << "Input image step: " << input.step << " rows: " << input.rows << " cols: " << input.cols << endl; // cout << input.rows * input.cols << endl; // Calculate total number of bytes of input and output image // Step = cols * number of colors // size_t colorBytes = input.step * input.rows; long h_s[256] = {}; createHistogram(input, h_s); normalize(input, h_s); equalize(input, output, h_s); // cout << h_s[0] << endl; //Debug } int main(int argc, char *argv[]) { string imagePath; if(argc < 2) imagePath = "Images/dog1.jpeg"; else imagePath = argv[1]; // Read input image from the disk cv::Mat input = cv::imread(imagePath, CV_LOAD_IMAGE_COLOR); if (input.empty()) { cout << "Image Not Found!" << std::endl; cin.get(); return -1; } //Create output image cv::Mat temp(input.rows, input.cols, CV_8UC1); //Creamos una matriz temporal para cambiar el input a una griz cv::Mat output(input.rows, input.cols, CV_8UC1); //Se tiene que cambiar a CV_8UC1 en vez de CV_8UC3 //Cambiamos el input a un gray cv::cvtColor(input, temp, CV_BGR2GRAY); //Call the wrapper function auto start_cpu = chrono::high_resolution_clock::now(); equalizer(temp, output); auto end_cpu = chrono::high_resolution_clock::now(); chrono::duration<float, std::milli> duration_ms = end_cpu - start_cpu; printf("La cantidad de tiempo que se tarda cada ejecucion es alrededor de: %f ms\n", duration_ms.count()); //Allow the windows to resize namedWindow("Input", cv::WINDOW_NORMAL); namedWindow("Output", cv::WINDOW_NORMAL); //Show the input and output imshow("Input", input); imshow("Output", output); //Wait for key press cv::waitKey(); return 0; }
26.47541
110
0.635604
Programacion-multinucleo-2018
f9d124788ff81a2d9ca43f51be668ee6169d3593
865
cpp
C++
chapter1/02/RandomColorGenerator.cpp
ps-group/modern-gl-samples
53e075ec21418597b37c71c895111c0c77cab72b
[ "MIT" ]
1
2017-06-20T06:56:57.000Z
2017-06-20T06:56:57.000Z
chapter1/02/RandomColorGenerator.cpp
ps-group/modern-gl-samples
53e075ec21418597b37c71c895111c0c77cab72b
[ "MIT" ]
null
null
null
chapter1/02/RandomColorGenerator.cpp
ps-group/modern-gl-samples
53e075ec21418597b37c71c895111c0c77cab72b
[ "MIT" ]
null
null
null
#include "RandomColorGenerator.h" namespace { std::vector<glm::vec4> MakePalette() { // Превращает rgb(255, 0, 128) в vec4{ 1, 0, 0.5, 1 } auto rgb = [](unsigned red, unsigned green, unsigned blue) { return glm::vec4(float(red) / 255.f, float(green) / 255.f, float(blue) / 255.f, 1); }; // Цвета подобраны на сайте https://websafecolors.info/color-chart return { rgb(0, 204, 102), rgb(102, 102, 102), rgb(102, 153, 204), rgb(153, 255, 153), rgb(204, 153, 51), rgb(0, 255, 102), rgb(204, 0, 102), rgb(204, 102, 255), rgb(102, 255, 255), rgb(153, 255, 102), }; } } RandomColorGenerator::RandomColorGenerator() : m_palette(MakePalette()) , m_generator(m_rd()) , m_indexDist(0, m_palette.size() - 1u) { } glm::vec4 RandomColorGenerator::GenerateColor() { const size_t index = m_indexDist(m_generator); return m_palette.at(index); }
21.625
85
0.652023
ps-group
f9da5c9167ab9dd80ceae603d3c1c26bc81fa148
846
cpp
C++
Pacientes.cpp
victorortiz98/ManchesterTriage-Stack-and-List-
df2a37b79c6491bd616eab1adccc2cec83952784
[ "Apache-2.0" ]
null
null
null
Pacientes.cpp
victorortiz98/ManchesterTriage-Stack-and-List-
df2a37b79c6491bd616eab1adccc2cec83952784
[ "Apache-2.0" ]
null
null
null
Pacientes.cpp
victorortiz98/ManchesterTriage-Stack-and-List-
df2a37b79c6491bd616eab1adccc2cec83952784
[ "Apache-2.0" ]
null
null
null
// // Created by Víctor Ortiz on 14/06/2021. // #include "Pacientes.hpp" #include <iostream> #include <string> Pacientes::Pacientes(int id, std::string dni, std::string nombre, std::string apellido1, std::string apellido2, int edad, char sexo) { IdPaciente = id; Dni = dni; Nombre = nombre; Apellido1= apellido1; Apellido2= apellido2; Edad = edad; Sexo= sexo; } int Pacientes ::getIdPaciente(){ return IdPaciente; } std :: string Pacientes::getDni(){ return Dni; } std::string Pacientes:: getNombre(){ return Nombre; } std::string Pacientes:: getApellido1(){ return Apellido1; } std::string Pacientes:: getApellido2(){ return Apellido2;} int Pacientes::getEdad(){ return Edad;} char Pacientes::getSexo(){ return Sexo;} Pacientes::~Pacientes() { }
20.634146
133
0.638298
victorortiz98
f9e0c35c957f936951c83aef0311f3c8d7d00e27
761
cpp
C++
cpp_tries/ch05/ex7.cpp
frankji/CPP-Primer-Plus-6
20ddba26faec93a347c96b866db853c2d154b639
[ "MIT" ]
null
null
null
cpp_tries/ch05/ex7.cpp
frankji/CPP-Primer-Plus-6
20ddba26faec93a347c96b866db853c2d154b639
[ "MIT" ]
null
null
null
cpp_tries/ch05/ex7.cpp
frankji/CPP-Primer-Plus-6
20ddba26faec93a347c96b866db853c2d154b639
[ "MIT" ]
null
null
null
#include <iostream> #include <string> struct car { std::string make; //use std::string if you do not want to claim the name space here. int year; }; //';' after struct. int main() { using namespace std; int ncars; cout << "How many cars do you wish to catalog? "; cin >> ncars; cin.get(); car * info = new car[ncars]; for(int i = 0; i < ncars; ++i) { cout << "Car #" << i + 1 << ":" << endl; cout << "Please enter the make: "; getline(cin, info[i].make); cout << "Please enter the year made: "; cin >> info[i].year; cin.get(); //Release '\n' out of the input queue. } cout << "Here is your collection: " << endl; for(int i = 0; i < ncars; ++i) { cout << info[i].year << " " << info[i].make << endl; } delete [] info; return 0; }
22.382353
85
0.576873
frankji
f9f1c65e9f04a5566b5cf6c7aeb49613bea6509d
55,896
cpp
C++
tests/test.cpp
OpenJij/cimod
14728142d5fca3f1dac4d63a9c6fcd17e82bce9f
[ "Apache-2.0" ]
8
2020-03-24T09:29:21.000Z
2022-01-12T17:06:20.000Z
tests/test.cpp
OpenJij/cimod
14728142d5fca3f1dac4d63a9c6fcd17e82bce9f
[ "Apache-2.0" ]
18
2020-04-16T01:31:25.000Z
2022-03-08T03:00:01.000Z
tests/test.cpp
OpenJij/cimod
14728142d5fca3f1dac4d63a9c6fcd17e82bce9f
[ "Apache-2.0" ]
3
2020-05-23T16:53:08.000Z
2021-07-01T08:51:28.000Z
#include "gtest/gtest.h" #include "../src/binary_quadratic_model.hpp" #include "../src/binary_polynomial_model.hpp" #include "../src/binary_quadratic_model_dict.hpp" #include "test_bqm.hpp" #include <nlohmann/json.hpp> #include <unordered_map> #include <utility> #include <vector> #include <cstdint> #include <string> #include <iostream> #include <tuple> using json = nlohmann::json; using namespace cimod; namespace { TEST(DenseConstructionTest, Construction) { BQMTester<Dense>::test_DenseConstructionTest_Construction(); BQMTester<Sparse>::test_DenseConstructionTest_Construction(); BQMTester<Dict>::test_DenseConstructionTest_Construction(); } TEST(DenseConstructionTest, ConstructionString) { BQMTester<Dense>::test_DenseConstructionTest_ConstructionString(); BQMTester<Sparse>::test_DenseConstructionTest_ConstructionString(); BQMTester<Dict>::test_DenseConstructionTest_ConstructionString(); } TEST(DenseConstructionTest, ConstructionMatrix) { BQMTester<Dense>::test_DenseConstructionTest_ConstructionMatrix(); BQMTester<Sparse>::test_DenseConstructionTest_ConstructionMatrix(); } TEST(DenseConstructionTest, ConstructionMatrix2) { BQMTester<Dense>::test_DenseConstructionTest_ConstructionMatrix2(); BQMTester<Sparse>::test_DenseConstructionTest_ConstructionMatrix2(); } TEST(DenseBQMFunctionTest, add_variable) { BQMTester<Dense>::test_DenseBQMFunctionTest_add_variable(); BQMTester<Sparse>::test_DenseBQMFunctionTest_add_variable(); BQMTester<Dict>::test_DenseBQMFunctionTest_add_variable(); } TEST(DenseBQMFunctionTest, add_variables_from) { BQMTester<Dense>::test_DenseBQMFunctionTest_add_variables_from(); BQMTester<Sparse>::test_DenseBQMFunctionTest_add_variables_from(); BQMTester<Dict>::test_DenseBQMFunctionTest_add_variables_from(); } TEST(DenseBQMFunctionTest, add_interaction) { BQMTester<Dense>::test_DenseBQMFunctionTest_add_interaction(); BQMTester<Sparse>::test_DenseBQMFunctionTest_add_interaction(); BQMTester<Dict>::test_DenseBQMFunctionTest_add_interaction(); } TEST(DenseBQMFunctionTest, add_interactions_from) { BQMTester<Dense>::test_DenseBQMFunctionTest_add_interactions_from(); BQMTester<Sparse>::test_DenseBQMFunctionTest_add_interactions_from(); BQMTester<Dict>::test_DenseBQMFunctionTest_add_interactions_from(); } TEST(DenseBQMFunctionTest, add_offset) { BQMTester<Dense>::test_DenseBQMFunctionTest_add_offset(); BQMTester<Sparse>::test_DenseBQMFunctionTest_add_offset(); BQMTester<Dict>::test_DenseBQMFunctionTest_add_offset(); } TEST(DenseBQMFunctionTest, energy) { BQMTester<Dense>::test_DenseBQMFunctionTest_energy(); BQMTester<Sparse>::test_DenseBQMFunctionTest_energy(); BQMTester<Dict>::test_DenseBQMFunctionTest_energy(); } TEST(DenseBQMFunctionTest, energies) { BQMTester<Dense>::test_DenseBQMFunctionTest_energies(); BQMTester<Sparse>::test_DenseBQMFunctionTest_energies(); BQMTester<Dict>::test_DenseBQMFunctionTest_energies(); } TEST(DenseBQMFunctionTest, empty) { BQMTester<Dense>::test_DenseBQMFunctionTest_empty(); BQMTester<Sparse>::test_DenseBQMFunctionTest_empty(); BQMTester<Dict>::test_DenseBQMFunctionTest_empty(); } TEST(DenseBQMFunctionTest, to_qubo) { BQMTester<Dense>::test_DenseBQMFunctionTest_to_qubo(); BQMTester<Sparse>::test_DenseBQMFunctionTest_to_qubo(); BQMTester<Dict>::test_DenseBQMFunctionTest_to_qubo(); } TEST(DenseBQMFunctionTest, to_ising) { BQMTester<Dense>::test_DenseBQMFunctionTest_to_ising(); BQMTester<Sparse>::test_DenseBQMFunctionTest_to_ising(); BQMTester<Dict>::test_DenseBQMFunctionTest_to_ising(); } TEST(DenseBQMFunctionTest, from_qubo) { BQMTester<Dense>::test_DenseBQMFunctionTest_from_qubo(); BQMTester<Sparse>::test_DenseBQMFunctionTest_from_qubo(); BQMTester<Dict>::test_DenseBQMFunctionTest_from_qubo(); } TEST(DenseBQMFunctionTest, from_ising) { BQMTester<Dense>::test_DenseBQMFunctionTest_from_ising(); BQMTester<Sparse>::test_DenseBQMFunctionTest_from_ising(); BQMTester<Dict>::test_DenseBQMFunctionTest_from_ising(); } TEST(DenseBQMFunctionTest, remove_variable) { BQMTester<Dense>::test_DenseBQMFunctionTest_remove_variable(); BQMTester<Sparse>::test_DenseBQMFunctionTest_remove_variable(); BQMTester<Dict>::test_DenseBQMFunctionTest_remove_variable(); } TEST(DenseBQMFunctionTest, remove_variables_from) { BQMTester<Dense>::test_DenseBQMFunctionTest_remove_variables_from(); BQMTester<Sparse>::test_DenseBQMFunctionTest_remove_variables_from(); BQMTester<Dict>::test_DenseBQMFunctionTest_remove_variables_from(); } TEST(DenseBQMFunctionTest, remove_interaction) { BQMTester<Dense>::test_DenseBQMFunctionTest_remove_interaction(); BQMTester<Sparse>::test_DenseBQMFunctionTest_remove_interaction(); BQMTester<Dict>::test_DenseBQMFunctionTest_remove_interaction(); } TEST(DenseBQMFunctionTest, scale) { BQMTester<Dense>::test_DenseBQMFunctionTest_scale(); BQMTester<Sparse>::test_DenseBQMFunctionTest_scale(); BQMTester<Dict>::test_DenseBQMFunctionTest_scale(); } TEST(DenseBQMFunctionTest, normalize) { BQMTester<Dense>::test_DenseBQMFunctionTest_normalize(); BQMTester<Sparse>::test_DenseBQMFunctionTest_normalize(); BQMTester<Dict>::test_DenseBQMFunctionTest_normalize(); } TEST(DenseBQMFunctionTest, fix_variable) { BQMTester<Dense>::test_DenseBQMFunctionTest_fix_variable(); BQMTester<Sparse>::test_DenseBQMFunctionTest_fix_variable(); BQMTester<Dict>::test_DenseBQMFunctionTest_fix_variable(); } TEST(DenseBQMFunctionTest, flip_variable) { BQMTester<Dense>::test_DenseBQMFunctionTest_flip_variable(); BQMTester<Sparse>::test_DenseBQMFunctionTest_flip_variable(); BQMTester<Dict>::test_DenseBQMFunctionTest_flip_variable(); } TEST(DenseBQMFunctionTest, flip_variable_binary) { BQMTester<Dense>::test_DenseBQMFunctionTest_flip_variable_binary(); BQMTester<Sparse>::test_DenseBQMFunctionTest_flip_variable_binary(); BQMTester<Dict>::test_DenseBQMFunctionTest_flip_variable_binary(); } TEST(DenseBQMFunctionTest, change_vartype) { BQMTester<Dense>::test_DenseBQMFunctionTest_change_vartype(); BQMTester<Sparse>::test_DenseBQMFunctionTest_change_vartype(); BQMTester<Dict>::test_DenseBQMFunctionTest_change_vartype(); } TEST(DenseBQMFunctionTest, to_serializable) { BQMTester<Dense>::test_DenseBQMFunctionTest_to_serializable(); BQMTester<Sparse>::test_DenseBQMFunctionTest_to_serializable(); BQMTester<Dict>::test_DenseBQMFunctionTest_to_serializable(); } TEST(DenseBQMFunctionTest, from_serializable) { BQMTester<Dense>::test_DenseBQMFunctionTest_from_serializable(); BQMTester<Sparse>::test_DenseBQMFunctionTest_from_serializable(); BQMTester<Dict>::test_DenseBQMFunctionTest_from_serializable(); } //google test for binary polynomial model bool EXPECT_CONTAIN(double val, const PolynomialValueList<double> &poly_value) { int count = 0; for (const auto &it: poly_value) { if (std::abs(it - val) < 0.000000000000001/*std::pow(10, -15)*/) { count++; } } if (count >= 1) { return true; } else { return false; } } void StateTestBPMUINT(const BinaryPolynomialModel<uint32_t, double> &bpm) { EXPECT_EQ(bpm.GetNumVariables(), 4); EXPECT_DOUBLE_EQ(bpm.GetOffset(), 0.0); EXPECT_EQ(bpm.GetNumInteractions(), 15); EXPECT_EQ(bpm.GetDegree(), 4); //Polynomial EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1} ), 1.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({2} ), 2.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({3} ), 3.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({4} ), 4.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 2} ), 12.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 3} ), 13.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 4} ), 14.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({2, 3} ), 23.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({2, 4} ), 24.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({3, 4} ), 34.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 2, 3} ), 123.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 2, 4} ), 124.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 3, 4} ), 134.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({2, 3, 4} ), 234.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 2, 3, 4}), 1234.0); //Polynomial duplicate key if (bpm.GetVartype() == cimod::Vartype::SPIN) { EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 1, 1} ), 1.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 1, 1, 2} ), 12.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 3, 3, 3} ), 13.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({3, 2, 3, 2, 3, 2}), 23.0); } else if (bpm.GetVartype() == cimod::Vartype::BINARY) { EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 1, 1, 1} ), 1.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 1, 1, 2, 2} ), 12.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 3, 3, 3, 1} ), 13.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({3, 2, 3, 2, 3, 2, 2}), 23.0); } //variables_to_integers EXPECT_EQ(bpm.GetVariablesToIntegers(1), 0); EXPECT_EQ(bpm.GetVariablesToIntegers(2), 1); EXPECT_EQ(bpm.GetVariablesToIntegers(3), 2); EXPECT_EQ(bpm.GetVariablesToIntegers(4), 3); //Polynomial Key EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{1} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{2} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{3} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{4} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{1, 2} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{1, 3} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{1, 4} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{2, 3} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{2, 4} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{3, 4} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{1, 2, 3} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{1, 2, 4} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{1, 3, 4} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{2, 3, 4} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{1, 2, 3, 4}), 1); //Polynomial Val EXPECT_TRUE(EXPECT_CONTAIN(1.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(2.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(3.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(4.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(12.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(13.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(14.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(23.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(24.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(34.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(123.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(124.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(134.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(234.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(1234.0, bpm.GetValueList())); //sorted_variables auto sorted_variables = bpm.GetSortedVariables(); EXPECT_EQ(sorted_variables[0], 1); EXPECT_EQ(sorted_variables[1], 2); EXPECT_EQ(sorted_variables[2], 3); EXPECT_EQ(sorted_variables[3], 4); //variables EXPECT_EQ(bpm.GetVariables().count(1), 1); EXPECT_EQ(bpm.GetVariables().count(2), 1); EXPECT_EQ(bpm.GetVariables().count(3), 1); EXPECT_EQ(bpm.GetVariables().count(4), 1); } void StateTestBPMINT(const BinaryPolynomialModel<int32_t, double> &bpm) { EXPECT_EQ(bpm.GetNumVariables(), 4); EXPECT_DOUBLE_EQ(bpm.GetOffset(), 0.0); EXPECT_EQ(bpm.GetNumInteractions(), 15); EXPECT_EQ(bpm.GetDegree(), 4); //Polynomial EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-1} ), 1.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-2} ), 2.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-3} ), 3.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-4} ), 4.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-2, -1} ), 12.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-3, -1} ), 13.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-4, -1} ), 14.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-3, -2} ), 23.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-4, -2} ), 24.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-4, -3} ), 34.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-3, -2, -1} ), 123.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-4, -2, -1} ), 124.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-4, -3, -1} ), 134.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-4, -3, -2} ), 234.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-4, -3, -2, -1}), 1234.0); //Polynomial duplicate key if (bpm.GetVartype() == cimod::Vartype::SPIN) { EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-1, -1, -1} ), 1.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-1, -1, -1, -2} ), 12.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-1, -3, -3, -3} ), 13.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-3, -2, -3, -2, -3, -2}), 23.0); } else if (bpm.GetVartype() == cimod::Vartype::BINARY) { EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-1, -1, -1, -1} ), 1.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-1, -1, -1, -2, -2} ), 12.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-1, -3, -3, -3, -1} ), 13.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({-3, -2, -3, -2, -3, -2, -2}), 23.0); } //variables_to_integers EXPECT_EQ(bpm.GetVariablesToIntegers(-4), 0); EXPECT_EQ(bpm.GetVariablesToIntegers(-3), 1); EXPECT_EQ(bpm.GetVariablesToIntegers(-2), 2); EXPECT_EQ(bpm.GetVariablesToIntegers(-1), 3); //Polynomial Key EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-1} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-2} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-3} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-4} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-2, -1} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-3, -1} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-4, -1} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-3, -2} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-4, -2} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-4, -3} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-3, -2, -1} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-4, -2, -1} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-4, -3, -1} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-4, -3, -2} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<int32_t>{-4, -3, -2, -1}), 1); //Polynomial Val EXPECT_TRUE(EXPECT_CONTAIN(1.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(2.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(3.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(4.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(12.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(13.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(14.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(23.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(24.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(34.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(123.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(124.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(134.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(234.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(1234.0, bpm.GetValueList())); //sorted_variables auto sorted_variables = bpm.GetSortedVariables(); EXPECT_EQ(sorted_variables[0], -4); EXPECT_EQ(sorted_variables[1], -3); EXPECT_EQ(sorted_variables[2], -2); EXPECT_EQ(sorted_variables[3], -1); //variables EXPECT_EQ(bpm.GetVariables().count(-1), 1); EXPECT_EQ(bpm.GetVariables().count(-2), 1); EXPECT_EQ(bpm.GetVariables().count(-3), 1); EXPECT_EQ(bpm.GetVariables().count(-4), 1); } void StateTestBPMString(const BinaryPolynomialModel<std::string, double> &bpm) { EXPECT_EQ(bpm.GetNumVariables(), 4); EXPECT_DOUBLE_EQ(bpm.GetOffset(), 0.0); EXPECT_EQ(bpm.GetNumInteractions(), 15); EXPECT_EQ(bpm.GetDegree(), 4); //Polynomial EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a"} ), 1.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"b"} ), 2.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"c"} ), 3.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"d"} ), 4.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "b"} ), 12.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "c"} ), 13.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "d"} ), 14.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"b", "c"} ), 23.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"b", "d"} ), 24.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"c", "d"} ), 34.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "b", "c"} ), 123.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "b", "d"} ), 124.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "c", "d"} ), 134.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"b", "c", "d"} ), 234.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "b", "c", "d"}), 1234.0); //Polynomial duplicate key if (bpm.GetVartype() == cimod::Vartype::SPIN) { EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "a", "a"} ), 1.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "a", "a", "b"} ), 12.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "c", "c", "c"} ), 13.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"c", "b", "c", "b", "c", "b"}), 23.0); } else if (bpm.GetVartype() == cimod::Vartype::BINARY) { EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "a", "a", "a"} ), 1.0 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "a", "a", "b", "b"} ), 12.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"a", "c", "c", "c", "a"} ), 13.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({"c", "b", "c", "b", "c", "b", "b"}), 23.0); } //variables_to_integers EXPECT_EQ(bpm.GetVariablesToIntegers("a"), 0); EXPECT_EQ(bpm.GetVariablesToIntegers("b"), 1); EXPECT_EQ(bpm.GetVariablesToIntegers("c"), 2); EXPECT_EQ(bpm.GetVariablesToIntegers("d"), 3); //Polynomial Key EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"a"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"b"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"c"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"d"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"a", "b"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"a", "c"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"a", "d"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"b", "c"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"b", "d"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"c", "d"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"a", "b", "c"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"a", "b", "d"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"a", "c", "d"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"b", "c", "d"} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<std::string>{"a", "b", "c", "d"}), 1); //Polynomial Value EXPECT_TRUE(EXPECT_CONTAIN(1.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(2.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(3.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(4.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(12.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(13.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(14.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(23.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(24.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(34.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(123.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(124.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(134.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(234.0 , bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(1234.0, bpm.GetValueList())); //sorted_variables auto sorted_variables = bpm.GetSortedVariables(); EXPECT_EQ(sorted_variables[0], "a"); EXPECT_EQ(sorted_variables[1], "b"); EXPECT_EQ(sorted_variables[2], "c"); EXPECT_EQ(sorted_variables[3], "d"); //variables EXPECT_EQ(bpm.GetVariables().count("a"), 1); EXPECT_EQ(bpm.GetVariables().count("b"), 1); EXPECT_EQ(bpm.GetVariables().count("c"), 1); EXPECT_EQ(bpm.GetVariables().count("d"), 1); } template<typename IndexType> void StateTestBPMEmpty(const BinaryPolynomialModel<IndexType, double> &bpm) { EXPECT_EQ(bpm.GetNumVariables(), 0); EXPECT_DOUBLE_EQ(bpm.GetOffset(), 0.0); EXPECT_EQ(bpm.GetNumInteractions(), 0); EXPECT_EQ(bpm.GetDegree(), 0); //Polynomial EXPECT_EQ(bpm.GetPolynomial().size(), 0); //variables_to_integers EXPECT_EQ(bpm.GetVariablesToIntegers().size(), 0); //Polynomial Key EXPECT_EQ(bpm.GetKeyList().size(), 0); //Polynomial Val EXPECT_EQ(bpm.GetValueList().size(), 0); //sorted_variables auto sorted_variables = bpm.GetSortedVariables(); EXPECT_EQ(sorted_variables.size(), 0); //variables EXPECT_EQ(bpm.GetVariables().size(), 0); } Polynomial<uint32_t, double> GeneratePolynomialUINT() { Polynomial<uint32_t, double> polynomial { //linear biases {{1}, 1.0}, {{2}, 2.0}, {{3}, 3.0}, {{4}, 4.0}, //quadratic biases {{1, 2}, 12.0}, {{1, 3}, 13.0}, {{1, 4}, 14.0}, {{2, 3}, 23.0}, {{2, 4}, 24.0}, {{3, 4}, 34.0}, //polynomial biases {{1, 2, 3}, 123.0}, {{1, 2, 4}, 124.0}, {{1, 3, 4}, 134.0}, {{2, 3, 4}, 234.0}, {{1, 2, 3, 4}, 1234.0} }; return polynomial; } Polynomial<int32_t, double> GeneratePolynomialINT() { Polynomial<int32_t, double> polynomial { //linear biases {{-1}, 1.0}, {{-2}, 2.0}, {{-3}, 3.0}, {{-4}, 4.0}, //quadratic biases {{-1, -2}, 12.0}, {{-1, -3}, 13.0}, {{-1, -4}, 14.0}, {{-2, -3}, 23.0}, {{-2, -4}, 24.0}, {{-3, -4}, 34.0}, //polynomial biases {{-1, -2, -3}, 123.0}, {{-1, -2, -4}, 124.0}, {{-1, -3, -4}, 134.0}, {{-2, -3, -4}, 234.0}, {{-1, -2, -3, -4}, 1234.0} }; return polynomial; } Polynomial<std::string, double> GeneratePolynomialString() { Polynomial<std::string, double> polynomial { //linear biases {{"a"}, 1.0}, {{"b"}, 2.0}, {{"c"}, 3.0}, {{"d"}, 4.0}, //quadratic biases {{"a", "b"}, 12.0}, {{"a", "c"}, 13.0}, {{"a", "d"}, 14.0}, {{"b", "c"}, 23.0}, {{"b", "d"}, 24.0}, {{"c", "d"}, 34.0}, //polynomial biases {{"a", "b", "c"}, 123.0}, {{"a", "b", "d"}, 124.0}, {{"a", "c", "d"}, 134.0}, {{"b", "c", "d"}, 234.0}, {{"a", "b", "c", "d"}, 1234.0} }; return polynomial; } TEST(ConstructionBPM, PolyMapUINT) { BinaryPolynomialModel<uint32_t, double> bpm(GeneratePolynomialUINT(), Vartype::SPIN); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMUINT(bpm); } TEST(ConstructionBPM, PolyMapINT) { BinaryPolynomialModel<int32_t, double> bpm(GeneratePolynomialINT(), Vartype::SPIN); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMINT(bpm); } TEST(ConstructionBPM, PolyMapString) { BinaryPolynomialModel<std::string, double> bpm(GeneratePolynomialString(), Vartype::SPIN); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMString(bpm); } TEST(ConstructionBPM, PolyKeyValueUINT) { PolynomialKeyList<uint32_t> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialUINT()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } BinaryPolynomialModel<uint32_t, double> bpm(poly_key, poly_value, Vartype::SPIN); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMUINT(bpm); } TEST(ConstructionBPM, PolyKeyValueINT) { PolynomialKeyList<int32_t> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialINT()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } BinaryPolynomialModel<int32_t, double> bpm(poly_key, poly_value, Vartype::SPIN); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMINT(bpm); } TEST(ConstructionBPM, PolyKeyValueStrign) { PolynomialKeyList<std::string> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialString()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } BinaryPolynomialModel<std::string, double> bpm(poly_key, poly_value, Vartype::SPIN); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMString(bpm); } TEST(AddInteractionBPM, basic) { Polynomial<uint32_t, double> polynomial { {{1}, 1.0}, {{2}, 2.0}, {{1, 2}, 12.0}, {{1, 2, 3}, 123.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); bpm.AddInteraction({3}, 3.0); bpm.AddInteraction({4}, 4.0); bpm.AddInteraction({1, 3}, 13.0); bpm.AddInteraction({1, 4}, 14.0); bpm.AddInteraction({2, 3}, 23.0); bpm.AddInteraction({2, 4}, 24.0); bpm.AddInteraction({3, 4}, 34.0); bpm.AddInteraction({1, 2, 4}, 124.0); bpm.AddInteraction({1, 3, 4}, 134.0); bpm.AddInteraction({2, 3, 4}, 234.0); bpm.AddInteraction({1, 2, 3, 4}, 1234.0); StateTestBPMUINT(bpm); } TEST(AddInteractionBPM, self_loop_SPIN) { Polynomial<uint32_t, double> polynomial { {{1}, 1.0}, {{2}, 2.0}, {{1, 2}, 12.0}, {{1, 2, 3}, 123.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); bpm.AddInteraction({3, 3, 3}, 3.0); bpm.AddInteraction({4, 4, 4, 4, 4}, 4.0); bpm.AddInteraction({1, 3, 1, 3, 3, 1}, 13.0); bpm.AddInteraction({1, 1, 1, 4, 4, 4}, 14.0); bpm.AddInteraction({3, 3, 3, 2, 2, 2}, 23.0); bpm.AddInteraction({2, 4}, 24.0); bpm.AddInteraction({3, 4}, 34.0); bpm.AddInteraction({1, 2, 4}, 124.0); bpm.AddInteraction({1, 3, 4}, 134.0); bpm.AddInteraction({2, 3, 4, 2, 4, 3, 3, 4, 2}, 234.0); bpm.AddInteraction({1, 2, 3, 4}, 1234.0); StateTestBPMUINT(bpm); } TEST(AddInteractionBPM, self_loop_BINARY) { Polynomial<uint32_t, double> polynomial { {{1}, 1.0}, {{2}, 2.0}, {{1, 2}, 12.0}, {{1, 2, 3}, 123.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::BINARY); bpm.AddInteraction({3, 3}, 3.0); bpm.AddInteraction({4, 4, 4}, 4.0); bpm.AddInteraction({1, 1, 3}, 13.0); bpm.AddInteraction({1, 4, 4, 4}, 14.0); bpm.AddInteraction({3, 3, 2}, 23.0); bpm.AddInteraction({2, 4}, 24.0); bpm.AddInteraction({3, 4}, 34.0); bpm.AddInteraction({1, 2, 4}, 124.0); bpm.AddInteraction({1, 3, 4}, 134.0); bpm.AddInteraction({2, 3, 4}, 234.0); bpm.AddInteraction({1, 2, 3, 3, 4, 1}, 1234.0); StateTestBPMUINT(bpm); } TEST(AddInteractionBPM, duplicate_value_1) { Polynomial<uint32_t, double> polynomial = GeneratePolynomialUINT(); for (auto &&it: polynomial) { it.second /= 2; } BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); for (const auto &it: polynomial) { bpm.AddInteraction(it.first, it.second); }; StateTestBPMUINT(bpm); } TEST(AddInteractionBPM, duplicate_value_2) { Polynomial<uint32_t, double> polynomial = GeneratePolynomialUINT(); BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); for (const auto &it: polynomial) { bpm.AddInteraction(it.first, -it.second); }; StateTestBPMEmpty(bpm); } TEST(AddInteractionsFromBPM, PolyMap) { BinaryPolynomialModel<uint32_t, double> bpm({}, Vartype::SPIN); bpm.AddInteractionsFrom(GeneratePolynomialUINT()); StateTestBPMUINT(bpm); } TEST(AddInteractionsFromBPM, PolyKeyValue) { PolynomialKeyList<uint32_t> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialUINT()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } BinaryPolynomialModel<uint32_t, double> bpm({}, Vartype::SPIN); bpm.AddInteractionsFrom(poly_key, poly_value); StateTestBPMUINT(bpm); } TEST(AddOffsetBPM, basic) { Polynomial<uint32_t, double> polynomial; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); bpm.AddOffset(3.0); EXPECT_DOUBLE_EQ(bpm.GetOffset(), 3.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({}) , 3.0); bpm.AddOffset(3.0); EXPECT_DOUBLE_EQ(bpm.GetOffset(), 6.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({}) , 6.0); bpm.AddOffset(-6.0); StateTestBPMEmpty(bpm); } TEST(RemoveInteractionBPM, basic) { Polynomial<uint32_t, double> polynomial = { //linear biases {{1}, 1.0}, {{2}, 2.0}, {{3}, 3.0}, {{4}, 4.0}, //quadratic biases {{1, 2}, 12.0}, {{1, 3}, 13.0}, {{1, 4}, 14.0}, {{2, 3}, 23.0}, {{2, 4}, 24.0}, {{3, 4}, 34.0}, //To be removed {{11, 12, 14}, -1.0}, {{7}, -2.0}, {{2, 11}, -9.0}, {{}, -3}, //polynomial biases {{1, 2, 3}, 123.0}, {{1, 2, 4}, 124.0}, {{1, 3, 4}, 134.0}, {{2, 3, 4}, 234.0}, {{1, 2, 3, 4}, 1234.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({} ), -3.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({7} ), -2.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({2, 11} ), -9.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({11, 12, 14}), -1.0); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{7} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{2, 11} ), 1); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{11, 12, 14}), 1); EXPECT_TRUE(EXPECT_CONTAIN(-3.0, bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(-2.0, bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(-9.0, bpm.GetValueList())); EXPECT_TRUE(EXPECT_CONTAIN(-1.0, bpm.GetValueList())); bpm.RemoveInteraction({} ); bpm.RemoveInteraction({7} ); bpm.RemoveInteraction({2, 11} ); bpm.RemoveInteraction({11, 12, 14}); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({} ), 0.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({7} ), 0.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({2, 11} ), 0.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({11, 12, 14}), 0.0); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{} ), 0); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{7} ), 0); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{2, 11} ), 0); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{11, 12, 14}), 0); EXPECT_FALSE(EXPECT_CONTAIN(-3.0, bpm.GetValueList())); EXPECT_FALSE(EXPECT_CONTAIN(-2.0, bpm.GetValueList())); EXPECT_FALSE(EXPECT_CONTAIN(-9.0, bpm.GetValueList())); EXPECT_FALSE(EXPECT_CONTAIN(-1.0, bpm.GetValueList())); StateTestBPMUINT(bpm); } TEST(RemoveInteractionBPM, remove_all) { Polynomial<uint32_t, double> polynomial = GeneratePolynomialUINT(); BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); for (const auto &it: polynomial) { bpm.RemoveInteraction(it.first); }; StateTestBPMEmpty(bpm); } TEST(RemoveInteractionBPM, self_loop_SPIN) { Polynomial<uint32_t, double> polynomial { {{1}, 1.0}, {{2}, 2.0}, {{1, 2}, 12.0}, {{1, 2, 3}, 123.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); bpm.RemoveInteraction({1, 1, 1}); bpm.RemoveInteraction({2, 2, 2, 2, 2}); bpm.RemoveInteraction({1, 1, 1, 2, 2, 2, 2, 2}); bpm.RemoveInteraction({1, 1, 1, 2, 2, 2, 3, 3, 3}); StateTestBPMEmpty(bpm); } TEST(RemoveInteractionBPM, self_loop_BINARY) { Polynomial<uint32_t, double> polynomial { {{1}, 1.0}, {{2}, 2.0}, {{1, 2}, 12.0}, {{1, 2, 3}, 123.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::BINARY); bpm.RemoveInteraction({1, 1}); bpm.RemoveInteraction({2, 2, 2, 2}); bpm.RemoveInteraction({1, 1, 1, 2, 2, 2}); bpm.RemoveInteraction({1, 1, 2, 2, 2, 3}); StateTestBPMEmpty(bpm); } TEST(RemoveInteractionsFromBPM, basic) { Polynomial<uint32_t, double> polynomial { //linear biases {{1}, 1.0}, {{2}, 2.0}, {{3}, 3.0}, {{4}, 4.0}, //quadratic biases {{1, 2}, 12.0}, {{1, 3}, 13.0}, {{1, 4}, 14.0}, {{2, 3}, 23.0}, {{2, 4}, 24.0}, {{3, 4}, 34.0}, //To be removed {{11, 12, 14}, -1.0}, {{7}, -2.0}, {{2, 11}, -9.0}, {{}, -3}, //polynomial biases {{1, 2, 3}, 123.0}, {{1, 2, 4}, 124.0}, {{1, 3, 4}, 134.0}, {{2, 3, 4}, 234.0}, {{1, 2, 3, 4}, 1234.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); PolynomialKeyList<uint32_t> removed_key_list = { {11, 14, 12}, {7}, {11, 2}, {} }; bpm.RemoveInteractionsFrom(removed_key_list); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({} ), 0.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({7} ), 0.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({2, 11} ), 0.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({11, 12, 14}), 0.0); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{} ), 0); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{7} ), 0); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{2, 11} ), 0); EXPECT_EQ(std::count(bpm.GetKeyList().begin(), bpm.GetKeyList().end(), std::vector<uint32_t>{11, 12, 14}), 0); EXPECT_FALSE(EXPECT_CONTAIN(-3.0, bpm.GetValueList())); EXPECT_FALSE(EXPECT_CONTAIN(-2.0, bpm.GetValueList())); EXPECT_FALSE(EXPECT_CONTAIN(-9.0, bpm.GetValueList())); EXPECT_FALSE(EXPECT_CONTAIN(-1.0, bpm.GetValueList())); StateTestBPMUINT(bpm); } TEST(RemoveInteractionsFromBPM, remove_all) { Polynomial<uint32_t, double> polynomial = GeneratePolynomialUINT(); BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); PolynomialKeyList<uint32_t> removed_key_list; for (const auto &it: polynomial) { removed_key_list.push_back(it.first); } bpm.RemoveInteractionsFrom(removed_key_list); StateTestBPMEmpty(bpm); } TEST(RemoveOffsetBPM, basic) { Polynomial<uint32_t, double> polynomial = { //linear biases {{1}, 1.0}, {{2}, 2.0}, {{3}, 3.0}, {{4}, 4.0}, //quadratic biases {{1, 2}, 12.0}, {{1, 3}, 13.0}, {{1, 4}, 14.0}, {{2, 3}, 23.0}, {{2, 4}, 24.0}, {{3, 4}, 34.0}, //To be removed {{}, 100}, //polynomial biases {{1, 2, 3}, 123.0}, {{1, 2, 4}, 124.0}, {{1, 3, 4}, 134.0}, {{2, 3, 4}, 234.0}, {{1, 2, 3, 4}, 1234.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); bpm.RemoveOffset(); StateTestBPMUINT(bpm); } TEST(EnergyBPM, SPIN) { Polynomial<uint32_t, double> polynomial { {{0}, 0.0}, {{1}, 1.0}, {{2}, 2.0}, {{0, 1}, 11.0}, {{0, 2}, 22.0}, {{1, 2}, 12.0}, {{0, 1, 2}, 123.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); Sample<uint32_t> sample_variables_spin_1{{0, +1}, {1, +1}, {2, +1}}; Sample<uint32_t> sample_variables_spin_2{{0, +1}, {1, -1}, {2, +1}}; Sample<uint32_t> sample_variables_spin_3{{0, -1}, {1, -1}, {2, -1}}; EXPECT_DOUBLE_EQ(bpm.Energy(sample_variables_spin_1), +171.0); EXPECT_DOUBLE_EQ(bpm.Energy(sample_variables_spin_2), -123.0); EXPECT_DOUBLE_EQ(bpm.Energy(sample_variables_spin_3), -81.0 ); std::vector<int32_t> sample_vec_variables_spin_1{+1, +1, +1}; std::vector<int32_t> sample_vec_variables_spin_2{+1, -1, +1}; std::vector<int32_t> sample_vec_variables_spin_3{-1, -1, -1}; EXPECT_DOUBLE_EQ(bpm.Energy(sample_vec_variables_spin_1), +171.0); EXPECT_DOUBLE_EQ(bpm.Energy(sample_vec_variables_spin_2), -123.0); EXPECT_DOUBLE_EQ(bpm.Energy(sample_vec_variables_spin_3), -81.0 ); } TEST(EnergyBPM, BINARY) { Polynomial<uint32_t, double> polynomial { {{0}, 0.0}, {{1}, 1.0}, {{2}, 2.0}, {{0, 1}, 11.0}, {{0, 2}, 22.0}, {{1, 2}, 12.0}, {{0, 1, 2}, 123.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::BINARY); Sample<uint32_t> sample_variables_binary_1{{0, +1}, {1, +1}, {2, +1}}; Sample<uint32_t> sample_variables_binary_2{{0, +1}, {1, +0}, {2, +1}}; Sample<uint32_t> sample_variables_binary_3{{0, +0}, {1, +0}, {2, +0}}; EXPECT_DOUBLE_EQ(bpm.Energy(sample_variables_binary_1), +171.0); EXPECT_DOUBLE_EQ(bpm.Energy(sample_variables_binary_2), +24.0 ); EXPECT_DOUBLE_EQ(bpm.Energy(sample_variables_binary_3), 0.0 ); std::vector<int32_t> sample_vec_variables_binary_1{+1, +1, +1}; std::vector<int32_t> sample_vec_variables_binary_2{+1, +0, +1}; std::vector<int32_t> sample_vec_variables_binary_3{+0, +0, +0}; EXPECT_DOUBLE_EQ(bpm.Energy(sample_vec_variables_binary_1), +171.0); EXPECT_DOUBLE_EQ(bpm.Energy(sample_vec_variables_binary_2), +24.0 ); EXPECT_DOUBLE_EQ(bpm.Energy(sample_vec_variables_binary_3), 0.0 ); } TEST(EnergiesBPM, SPIN) { Polynomial<uint32_t, double> polynomial { {{0}, 0.0}, {{1}, 1.0}, {{2}, 2.0}, {{0, 1}, 11.0}, {{0, 2}, 22.0}, {{1, 2}, 12.0}, {{0, 1, 2}, 123.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); std::vector<Sample<uint32_t>> sample_variables_spin { {{0, +1}, {1, +1}, {2, +1}}, {{0, +1}, {1, -1}, {2, +1}}, {{0, -1}, {1, -1}, {2, -1}} }; std::vector<double> en_vec = bpm.Energies(sample_variables_spin); EXPECT_DOUBLE_EQ(en_vec[0], +171.0); EXPECT_DOUBLE_EQ(en_vec[1], -123.0); EXPECT_DOUBLE_EQ(en_vec[2], -81.0 ); std::vector<std::vector<int32_t>> sample_vec_variables_spin { {+1, +1, +1}, {+1, -1, +1}, {-1, -1, -1} }; std::vector<double> en_vec_vec = bpm.Energies(sample_vec_variables_spin); EXPECT_DOUBLE_EQ(en_vec_vec[0], +171.0); EXPECT_DOUBLE_EQ(en_vec_vec[1], -123.0); EXPECT_DOUBLE_EQ(en_vec_vec[2], -81.0 ); } TEST(EnergiesBPM, BINARY) { Polynomial<uint32_t, double> polynomial { {{0}, 0.0}, {{1}, 1.0}, {{2}, 2.0}, {{0, 1}, 11.0}, {{0, 2}, 22.0}, {{1, 2}, 12.0}, {{0, 1, 2}, 123.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); std::vector<Sample<uint32_t>> sample_variables_binary { {{0, +1}, {1, +1}, {2, +1}}, {{0, +1}, {1, +0}, {2, +1}}, {{0, +0}, {1, +0}, {2, +0}} }; std::vector<double> en_vec = bpm.Energies(sample_variables_binary); EXPECT_DOUBLE_EQ(en_vec[0], +171.0); EXPECT_DOUBLE_EQ(en_vec[1], +24.0 ); EXPECT_DOUBLE_EQ(en_vec[2], 0.0 ); std::vector<std::vector<int32_t>> sample_vec_variables_binary { {+1, +1, +1}, {+1, +0, +1}, {+0, +0, +0} }; std::vector<double> en_vec_vec = bpm.Energies(sample_vec_variables_binary); EXPECT_DOUBLE_EQ(en_vec_vec[0], +171.0); EXPECT_DOUBLE_EQ(en_vec_vec[1], +24.0 ); EXPECT_DOUBLE_EQ(en_vec_vec[2], 0.0 ); } TEST(ScaleBPM, all_scale) { Polynomial<uint32_t, double> polynomial = GeneratePolynomialUINT(); for (auto &&it: polynomial) { it.second *= 2; } BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); bpm.Scale(0.5); StateTestBPMUINT(bpm); } TEST(ScaleBPM, ignored_interaction) { Polynomial<uint32_t, double> polynomial = GeneratePolynomialUINT(); for (auto &&it: polynomial) { it.second *= 2; } BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); bpm.Scale(0.5, {{1,2}, {2, 4}, {1, 3, 4}}); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 2} ), 12.0*2 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({2, 4} ), 24.0*2 ); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({1, 3, 4}), 134.0*2); bpm.AddInteraction({1, 2} , -12.0); bpm.AddInteraction({2, 4} , -24.0); bpm.AddInteraction({1, 3, 4}, -134.0); StateTestBPMUINT(bpm); } TEST(ScaleBPM, ignored_offset) { Polynomial<uint32_t, double> polynomial { {{}, 100.0} }; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, Vartype::SPIN); bpm.Scale(0.5, {std::vector<uint32_t>{}}); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({}), 100.0); bpm.Scale(0.5, {}, true); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({}), 100.0); bpm.Scale(0.5, {{}}, true); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({}), 100.0); bpm.Scale(0.5); EXPECT_DOUBLE_EQ(bpm.GetPolynomial({}), 50.0); } TEST(NormalizeBPM, all_normalize) { Polynomial<uint32_t, double> polynomial { {{0}, 0.0}, {{1}, 1.0}, {{2}, 2.0}, {{0, 1}, 11.0}, {{0, 2}, 22.0}, {{1, 2}, 12.0}, {{0, 1, 2}, +12} }; Vartype vartype = Vartype::SPIN; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, vartype); bpm.normalize({-1, 1}); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({1}), 1.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({2}), 2.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({0, 1}), 11.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({0, 2}), 22.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({1, 2}), 12.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({0, 1, 2}), 12.0/22.0); } TEST(NormalizeBPM, ignored_interaction) { Polynomial<uint32_t, double> polynomial { {{0}, 0.0}, {{1}, 1.0}, {{2}, 2.0}, {{0, 1}, 11.0}, {{0, 2}, 22.0}, {{1, 2}, 12.0}, {{0, 1, 2}, +12} }; Vartype vartype = Vartype::SPIN; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, vartype); bpm.normalize({-1, 1}, {{0, 1, 2}}); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({1}), 1.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({2}), 2.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({0, 1}), 11.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({0, 2}), 22.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({1, 2}), 12.0/22.0); EXPECT_DOUBLE_EQ(bpm.GetPolynomial().at({0, 1, 2}), 12.0); } TEST(SerializableBPM, UINT) { BinaryPolynomialModel<uint32_t, double> bpm(GeneratePolynomialUINT(), Vartype::SPIN); BinaryPolynomialModel<uint32_t, double> bpm_from = BinaryPolynomialModel<uint32_t, double>::FromSerializable(bpm.ToSerializable()); StateTestBPMUINT(bpm_from); } TEST(SerializableBPM, INT) { BinaryPolynomialModel<int32_t, double> bpm(GeneratePolynomialINT(), Vartype::SPIN); BinaryPolynomialModel<int32_t, double> bpm_from = BinaryPolynomialModel<int32_t, double>::FromSerializable(bpm.ToSerializable()); StateTestBPMINT(bpm_from); } TEST(SerializableBPM, String) { BinaryPolynomialModel<std::string, double> bpm(GeneratePolynomialString(), Vartype::SPIN); BinaryPolynomialModel<std::string, double> bpm_from = BinaryPolynomialModel<std::string, double>::FromSerializable(bpm.ToSerializable()); StateTestBPMString(bpm_from); } TEST(SerializableBPM, StringToUINT) { BinaryPolynomialModel<std::string, double> bpm(GeneratePolynomialString(), Vartype::SPIN); auto obj = bpm.ToSerializable(); std::vector<std::size_t> string_to_num(obj["variables"].size()); std::iota(string_to_num.begin(), string_to_num.end(), 1); obj["variables"] = string_to_num; BinaryPolynomialModel<uint32_t, double> bpm_from = BinaryPolynomialModel<uint32_t, double>::FromSerializable(obj); StateTestBPMUINT(bpm_from); } TEST(SerializableBPM, StringToINT) { BinaryPolynomialModel<std::string, double> bpm(GeneratePolynomialString(), Vartype::SPIN); auto obj = bpm.ToSerializable(); std::vector<std::size_t> string_to_num(4); string_to_num[0] = -1; string_to_num[1] = -2; string_to_num[2] = -3; string_to_num[3] = -4; obj["variables"] = string_to_num; BinaryPolynomialModel<int32_t, double> bpm_from = BinaryPolynomialModel<int32_t, double>::FromSerializable(obj); StateTestBPMINT(bpm_from); } TEST(FromHubo, MapUINT) { auto bpm = BinaryPolynomialModel<uint32_t, double>::FromHubo(GeneratePolynomialUINT()); EXPECT_EQ(Vartype::BINARY, bpm.GetVartype()); StateTestBPMUINT(bpm); } TEST(FromHubo, MapINT) { auto bpm = BinaryPolynomialModel<int32_t, double>::FromHubo(GeneratePolynomialINT()); EXPECT_EQ(Vartype::BINARY, bpm.GetVartype()); StateTestBPMINT(bpm); } TEST(FromHubo, MapString) { auto bpm = BinaryPolynomialModel<std::string, double>::FromHubo(GeneratePolynomialString()); EXPECT_EQ(Vartype::BINARY, bpm.GetVartype()); StateTestBPMString(bpm); } TEST(FromHubo, KeyValueUINT) { PolynomialKeyList<uint32_t> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialUINT()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } auto bpm = BinaryPolynomialModel<uint32_t, double>::FromHubo(poly_key, poly_value); EXPECT_EQ(Vartype::BINARY, bpm.GetVartype()); StateTestBPMUINT(bpm); } TEST(FromHubo, KeyValueINT) { PolynomialKeyList<int32_t> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialINT()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } auto bpm = BinaryPolynomialModel<int32_t, double>::FromHubo(poly_key, poly_value); EXPECT_EQ(Vartype::BINARY, bpm.GetVartype()); StateTestBPMINT(bpm); } TEST(FromHubo, KeyValueString) { PolynomialKeyList<std::string> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialString()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } auto bpm = BinaryPolynomialModel<std::string, double>::FromHubo(poly_key, poly_value); EXPECT_EQ(Vartype::BINARY, bpm.GetVartype()); StateTestBPMString(bpm); } TEST(FromHising, MapUINT) { auto bpm = BinaryPolynomialModel<uint32_t, double>::FromHising(GeneratePolynomialUINT()); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMUINT(bpm); } TEST(FromHising, MapINT) { auto bpm = BinaryPolynomialModel<int32_t, double>::FromHising(GeneratePolynomialINT()); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMINT(bpm); } TEST(FromHising, MapString) { auto bpm = BinaryPolynomialModel<std::string, double>::FromHising(GeneratePolynomialString()); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMString(bpm); } TEST(FromHising, KeyValueUINT) { PolynomialKeyList<uint32_t> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialUINT()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } auto bpm = BinaryPolynomialModel<uint32_t, double>::FromHising(poly_key, poly_value); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMUINT(bpm); } TEST(FromHising, KeyValueINT) { PolynomialKeyList<int32_t> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialINT()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } auto bpm = BinaryPolynomialModel<int32_t, double>::FromHising(poly_key, poly_value); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMINT(bpm); } TEST(FromHising, KeyValueString) { PolynomialKeyList<std::string> poly_key; PolynomialValueList<double> poly_value; for (const auto &it: GeneratePolynomialString()) { poly_key.push_back(it.first); poly_value.push_back(it.second); } auto bpm = BinaryPolynomialModel<std::string, double>::FromHising(poly_key, poly_value); EXPECT_EQ(Vartype::SPIN, bpm.GetVartype()); StateTestBPMString(bpm); } TEST(ClearBPM, basic) { Polynomial<uint32_t, double> polynomial { {{0}, 0.0}, {{1}, 1.0}, {{2}, 2.0}, {{0, 1}, 11.0}, {{0, 2}, 22.0}, {{1, 2}, 12.0}, {{0, 1, 2}, 123.0} }; Vartype vartype = Vartype::BINARY; BinaryPolynomialModel<uint32_t, double> bpm(polynomial, vartype); bpm.Clear(); Sample<uint32_t> sample_variables_binary_1{{0, +1}, {1, +1}, {2, +1}}; Sample<uint32_t> sample_variables_binary_2{{0, +1}, {1, +0}, {2, +1}}; Sample<uint32_t> sample_variables_binary_3{{0, +0}, {1, +0}, {2, +0}}; EXPECT_TRUE(bpm.GetPolynomial().empty()); EXPECT_TRUE(bpm.GetVariables().empty()); EXPECT_EQ(bpm.GetVartype(), Vartype::BINARY); //Chech if the methods in Binary Polynomial Model work properly after executing empty() EXPECT_EQ(bpm.GetNumVariables(), 0); bpm.RemoveVariable(1); bpm.RemoveVariablesFrom(std::vector<uint32_t>{1,2,3,4,5}); bpm.RemoveInteraction(std::vector<uint32_t>{1,2}); bpm.RemoveInteractionsFrom(std::vector<std::vector<uint32_t>>{{1,2},{1,3},{1,4}}); bpm.Scale(1.0); bpm.normalize(); //energy EXPECT_THROW(bpm.Energy(sample_variables_binary_1), std::runtime_error); EXPECT_THROW(bpm.Energy(sample_variables_binary_2), std::runtime_error); EXPECT_THROW(bpm.Energy(sample_variables_binary_3), std::runtime_error); //Reset polynomial model bpm.AddInteraction({0, 1} , 11.0, Vartype::BINARY); bpm.AddInteraction({0, 2} , 22.0); bpm.AddInteraction({1, 2} , 12.0); bpm.AddInteraction({0, 1, 2}, 123.0); bpm.AddInteraction({0}, 0.0); bpm.AddInteraction({1}, 1.0); bpm.AddInteraction({2}, 2.0); //Check energy EXPECT_DOUBLE_EQ(bpm.Energy(sample_variables_binary_1), +171.0); EXPECT_DOUBLE_EQ(bpm.Energy(sample_variables_binary_2), +24.0 ); EXPECT_DOUBLE_EQ(bpm.Energy(sample_variables_binary_3), 0.0 ); EXPECT_EQ(bpm.GetNumVariables(), 3); EXPECT_EQ(bpm.GetVariables().count(0), 1); EXPECT_EQ(bpm.GetVariables().count(1), 1); EXPECT_EQ(bpm.GetVariables().count(2), 1); for (const auto &it: bpm.GetPolynomial()) { EXPECT_DOUBLE_EQ(it.second, polynomial[it.first]); } EXPECT_EQ(bpm.GetVartype(), Vartype::BINARY); } TEST(VartypeBPM, SpinBinarySpin) { auto bpm = BinaryPolynomialModel<uint32_t, double>::FromHising(GeneratePolynomialUINT()); auto bpm_binary = BinaryPolynomialModel<uint32_t, double>(bpm.ToHubo(), Vartype::BINARY); auto bpm_ising = BinaryPolynomialModel<uint32_t, double>(bpm_binary.ToHising(), Vartype::SPIN); StateTestBPMUINT(bpm_ising); } TEST(VartypeBPM, BinarySPINBinary) { auto bpm = BinaryPolynomialModel<uint32_t, double>::FromHubo(GeneratePolynomialUINT()); auto bpm_ising = BinaryPolynomialModel<uint32_t, double>(bpm.ToHising(), Vartype::SPIN); auto bpm_bianry = BinaryPolynomialModel<uint32_t, double>(bpm_ising.ToHubo(), Vartype::BINARY); StateTestBPMUINT(bpm_bianry); } TEST(VartypeBPM, ChangeVartypeSpinBinarySpin) { auto bpm = BinaryPolynomialModel<uint32_t, double>::FromHising(GeneratePolynomialUINT()); auto bpm_binary = bpm.ChangeVartype(Vartype::BINARY, true); auto bpm_ising = bpm_binary.ChangeVartype(Vartype::SPIN, true); StateTestBPMUINT(bpm_ising); bpm.ChangeVartype(Vartype::SPIN); StateTestBPMUINT(bpm); } TEST(VartypeBPM, ChangeVartypeBinarySPINBinary) { auto bpm = BinaryPolynomialModel<uint32_t, double>::FromHubo(GeneratePolynomialUINT()); auto bpm_ising = bpm.ChangeVartype(Vartype::SPIN, true); auto bpm_binary = bpm_ising.ChangeVartype(Vartype::BINARY, true); StateTestBPMUINT(bpm_binary); bpm.ChangeVartype(Vartype::BINARY); StateTestBPMUINT(bpm); } }
36.390625
140
0.641799
OpenJij
f9f353042a4420e0583fe7220f685aa28073b632
303
hpp
C++
opencv/build/modules/core/test/test_intrin512.simd_declarations.hpp
soyyuz/opencv-contrib-ARM64
25386df773f88a071532ec69ff541c31e62ec8f2
[ "Apache-2.0" ]
null
null
null
opencv/build/modules/core/test/test_intrin512.simd_declarations.hpp
soyyuz/opencv-contrib-ARM64
25386df773f88a071532ec69ff541c31e62ec8f2
[ "Apache-2.0" ]
null
null
null
opencv/build/modules/core/test/test_intrin512.simd_declarations.hpp
soyyuz/opencv-contrib-ARM64
25386df773f88a071532ec69ff541c31e62ec8f2
[ "Apache-2.0" ]
1
2022-03-27T03:35:07.000Z
2022-03-27T03:35:07.000Z
#define CV_CPU_SIMD_FILENAME "/home/epasholl/opencv/opencv-master/modules/core/test/test_intrin512.simd.hpp" #define CV_CPU_DISPATCH_MODE AVX512_SKX #include "opencv2/core/private/cv_cpu_include_simd_declarations.hpp" #define CV_CPU_DISPATCH_MODES_ALL AVX512_SKX, BASELINE #undef CV_CPU_SIMD_FILENAME
37.875
108
0.864686
soyyuz
f9f66adc04cca9dbd2103b56d3dcc874ff35bcec
2,787
hpp
C++
lexer/token.hpp
CobaltXII/cxcc
2e8f34e851b3cbe6699e443fd3950d630ff170b7
[ "MIT" ]
3
2019-05-27T04:50:51.000Z
2019-06-18T16:27:58.000Z
lexer/token.hpp
CobaltXII/cxcc
2e8f34e851b3cbe6699e443fd3950d630ff170b7
[ "MIT" ]
null
null
null
lexer/token.hpp
CobaltXII/cxcc
2e8f34e851b3cbe6699e443fd3950d630ff170b7
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> // All token types. enum token_type_t { // Special tokens. tk_identifier, tk_lit_integer, tk_lit_string, tk_lit_character, tk_eof, // Reserved words. tk_if, tk_int, tk_else, tk_while, tk_return, tk_break, tk_continue, // Punctuation. tk_left_parenthesis, tk_right_parenthesis, tk_left_bracket, tk_right_bracket, tk_left_brace, tk_right_brace, tk_comma, tk_semicolon, // Binary operators. tk_bi_division, tk_bi_modulo, tk_bi_assignment, tk_bi_addition_assignment, tk_bi_subtraction_assignment, tk_bi_multiplication_assignment, tk_bi_division_assignment, tk_bi_modulo_assignment, tk_bi_logical_and, tk_bi_logical_or, tk_bi_relational_equal, tk_bi_relational_non_equal, tk_bi_relational_greater_than, tk_bi_relational_lesser_than, tk_bi_relational_greater_than_or_equal_to, tk_bi_relational_lesser_than_or_equal_to, tk_bi_binary_or, tk_bi_binary_xor, tk_bi_binary_and_assignment, tk_bi_binary_or_assignment, tk_bi_binary_xor_assignment, tk_bi_binary_left_shift, tk_bi_binary_right_shift, tk_bi_binary_left_shift_assignment, tk_bi_binary_right_shift_assignment, // Unary operators. tk_un_logical_not, tk_un_binary_not, // Ambiguous operators. tk_plus, tk_minus, tk_asterisk, tk_ampersand }; // All token types as strings. std::string token_type_str[] = { // Special tokens. "identifier", "integer literal", "string literal", "character literal", "end-of-file", // Reserved words. "'if'", "'int'", "'else'", "'while'", "'return'", "'break'", "'continue'", // Punctuation. "'('", "')'", "'['", "']'", "'{'", "'}'", "','", "';'", // Binary operators. "'/'", "'%'", "'='", "'+='", "'-='", "'*='", "'/='", "'%='", "'&&'", "'||'", "'=='", "'!='", "'>'", "'<'", "'>='", "'<='", "'|'", "'^'", "'&='", "'|='", "'^='", "'<<'", "'>>'", "'<<='", "'>>='", // Unary operators. "'!'", "'~'", // Ambiguous operators. "'+'", "'-'", "'*'", "'&'" }; // All token types as strings, padded. std::vector<std::string> make_token_type_str_pad() { std::vector<std::string> token_type_str_pad; long max_length = 0; for (int i = 0; i < sizeof(token_type_str) / sizeof(token_type_str[0]); i++) { if (token_type_str[i].length() > max_length) { max_length = token_type_str[i].length(); } } for (int i = 0; i < sizeof(token_type_str) / sizeof(token_type_str[0]); i++) { std::string padding(max_length - token_type_str[i].length(), ' '); token_type_str_pad.push_back(token_type_str[i] + padding); } return token_type_str_pad; } // All token types as strings, padded. std::vector<std::string> token_type_str_pad = make_token_type_str_pad(); // A token. struct token_t { token_type_t type; std::string text; long lineno; long colno; };
18.335526
79
0.666308
CobaltXII
f9f84c5062a5075b73119aad4133f93568f6d0ac
1,207
cpp
C++
trainings/2015-10-06-Multi-University-2015-10/B.cpp
HcPlu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
9
2017-10-07T13:35:45.000Z
2021-06-07T17:36:55.000Z
trainings/2015-10-06-Multi-University-2015-10/B.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
null
null
null
trainings/2015-10-06-Multi-University-2015-10/B.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
3
2018-04-24T05:27:21.000Z
2019-04-25T06:06:00.000Z
#include <iostream> using namespace std; const int mod = 1e9 + 7; const int N = 1e6 + 11; int prime[N + 10]; long long f[N + 10], ok[N + 10]; void init() { for (int i = 2; i <= N; i++) { prime[i] = 1; ok[i] = 0; } for (int i = 2; i <= N; i++) { if (prime[i]) { for (int j = i + i; j <= N; j += i) { prime[j] = 0; } for (long long j = i; j <= N; j *= i) { ok[j] = i; } } } f[1] = 1; for (int i = 2; i <= N; i++) { f[i] = f[i - 1]; if (ok[i]) { f[i] = f[i] * ok[i] % mod; } } } long long power(const long long &x, const long long &k) { long long answer = 1, number = x; for (long long i = k; i > 0; i >>= 1) { if (i & 1) { (answer *= number) %= mod; } (number *= number) %= mod; } return answer; } int n; void solve() { scanf("%d", &n); int ans = 1LL * f[n + 1] * power(n + 1, mod - 2) % mod; printf("%d\n", ans); } int main() { int tests; scanf("%d", &tests); init(); for (int i = 1; i <= tests; i++) { solve(); } return 0; }
18.569231
59
0.375311
HcPlu
e600f394d0516ef29fef83a6ff839fc159589f0e
1,441
hpp
C++
hot/commons/include/hot/commons/PartialKeyMappingBase.hpp
freesummer/SIMD-Matcher
3b1889d2924d243daff4939e7328bef431d9859a
[ "0BSD" ]
null
null
null
hot/commons/include/hot/commons/PartialKeyMappingBase.hpp
freesummer/SIMD-Matcher
3b1889d2924d243daff4939e7328bef431d9859a
[ "0BSD" ]
null
null
null
hot/commons/include/hot/commons/PartialKeyMappingBase.hpp
freesummer/SIMD-Matcher
3b1889d2924d243daff4939e7328bef431d9859a
[ "0BSD" ]
null
null
null
#ifndef __HOT__COMMONS__PARTIAL_KEY_MAPPING_BASE_HPP___ #define __HOT__COMMONS__PARTIAL_KEY_MAPPING_BASE_HPP___ #include "hot/commons/include/hot/commons/DiscriminativeBit.hpp" namespace hot { namespace commons { /** * A Base class for all partial key mapping informations * A Partial key mapping must be able to extract a set of discriminative bits and form partial keys consisting only of those bits * */ class PartialKeyMappingBase { public: uint16_t mMostSignificantDiscriminativeBitIndex; uint16_t mLeastSignificantDiscriminativeBitIndex; protected: //This does not initialize the fields and is only allowed to be called from subclasses //This can be used if both fields are copied together with another field using 64bit operations or better simd or avx instructions PartialKeyMappingBase() { } protected: PartialKeyMappingBase(uint16_t mostSignificantBitIndex, uint16_t leastSignificantBitIndex) : mMostSignificantDiscriminativeBitIndex(mostSignificantBitIndex), mLeastSignificantDiscriminativeBitIndex(leastSignificantBitIndex) { } PartialKeyMappingBase(PartialKeyMappingBase const existing, DiscriminativeBit const & significantKeyInformation) : PartialKeyMappingBase( std::min(existing.mMostSignificantDiscriminativeBitIndex, significantKeyInformation.mAbsoluteBitIndex), std::max(existing.mLeastSignificantDiscriminativeBitIndex, significantKeyInformation.mAbsoluteBitIndex) ) { } }; } } #endif
36.025
226
0.834837
freesummer
e601409f0ab4f79c59b7e57a7c626886caede9b3
39,335
cpp
C++
src/Main/Gui/CoreWindow.cpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
4
2016-06-03T18:41:43.000Z
2020-04-17T20:28:58.000Z
src/Main/Gui/CoreWindow.cpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
null
null
null
src/Main/Gui/CoreWindow.cpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
null
null
null
/* * Copyright (c) 2014-2022 The Voxie Authors * * 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. */ // QDBusConnection should be included as early as possible: // https://bugreports.qt.io/browse/QTBUG-48351 / // https://bugreports.qt.io/browse/QTBUG-48377 #include <QtDBus/QDBusConnection> #include "CoreWindow.hpp" #include <Voxie/Util.hpp> #include <VoxieClient/DBusAdaptors.hpp> #include <VoxieClient/DBusProxies.hpp> #include <VoxieBackend/IO/OperationImport.hpp> #include <VoxieBackend/IO/OperationResult.hpp> #include <Main/Gui/AboutDialogWindow.hpp> #include <Main/Gui/ButtonLabel.hpp> #include <Main/Gui/OpenFileDialog.hpp> #include <Main/Gui/PluginManagerWindow.hpp> #include <Main/Gui/PreferencesWindow.hpp> #include <Main/Gui/ScriptConsole.hpp> #include <Main/Gui/SidePanel.hpp> #include <Main/Gui/SliceView.hpp> #include <Main/Gui/VScrollArea.hpp> #include <Main/DirectoryManager.hpp> #include <Main/Root.hpp> #include <Main/Component/SessionManager.hpp> #include <Main/Help/HelpLinkHandler.hpp> #include <Main/Component/ScriptLauncher.hpp> #include <Voxie/Component/HelpCommon.hpp> #include <Voxie/Component/Plugin.hpp> #include <Voxie/Node/NodePrototype.hpp> #include <VoxieClient/Exception.hpp> #include <Voxie/Gui/ErrorMessage.hpp> #include <Voxie/IO/SaveFileDialog.hpp> #include <Voxie/Vis/VisualizerNode.hpp> #include <VoxieClient/ObjectExport/BusManager.hpp> #include <functional> #include <assert.h> #include <QCloseEvent> #include <QtCore/QDebug> #include <QtCore/QProcess> #include <QtCore/QSettings> #include <QtCore/QUrl> #include <QtDBus/QDBusMessage> #include <QtGui/QDesktopServices> #include <QtGui/QScreen> #include <QtGui/QWindow> #include <QtWidgets/QDockWidget> #include <QtWidgets/QFileDialog> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QLabel> #include <QtWidgets/QMdiSubWindow> #include <QtWidgets/QMenuBar> #include <QtWidgets/QMessageBox> #include <QtWidgets/QPushButton> #include <QtWidgets/QScrollArea> #include <QtWidgets/QSplitter> #include <QtWidgets/QStatusBar> #include <QtWidgets/QVBoxLayout> using namespace vx::io; using namespace vx::gui; using namespace vx; using namespace vx::plugin; using namespace vx::visualization; using namespace vx; ActiveVisualizerProviderImpl::~ActiveVisualizerProviderImpl() {} VisualizerNode* ActiveVisualizerProviderImpl::activeVisualizer() const { return win->getActiveVisualizer(); } QList<Node*> ActiveVisualizerProviderImpl::selectedNodes() const { return win->sidePanel->selectedNodes(); } void ActiveVisualizerProviderImpl::setSelectedNodes( const QList<Node*>& nodes) const { win->sidePanel->dataflowWidget->setSelectedNodes(nodes); } namespace vx { namespace gui { class Gui : public ExportedObject { friend class GuiAdaptorImpl; CoreWindow* window; public: Gui(CoreWindow* window); virtual ~Gui(); }; class GuiAdaptorImpl : public GuiAdaptor { Gui* object; public: GuiAdaptorImpl(Gui* object) : GuiAdaptor(object), object(object) {} virtual ~GuiAdaptorImpl() {} QList<QDBusObjectPath> selectedNodes() const override; QList<QDBusObjectPath> selectedObjects() const override; QDBusObjectPath activeVisualizer() const override; void RaiseWindow(const QMap<QString, QDBusVariant>& options) override; qulonglong GetMainWindowID( const QMap<QString, QDBusVariant>& options) override; void setMdiViewMode(const QString& mdiViewMode) override { if (mdiViewMode == "de.uni_stuttgart.Voxie.MdiViewMode.SubWindow") { object->window->setTilePattern(false); } else if (mdiViewMode == "de.uni_stuttgart.Voxie.MdiViewMode.SubWindowTiled") { object->window->setTilePattern(true); } bool isToggleChecked = object->window->toggleTabbedAction->isChecked(); bool isTabbed = (mdiViewMode == "de.uni_stuttgart.Voxie.MdiViewMode.Tabbed"); if ((isToggleChecked && !isTabbed) || (!isToggleChecked && isTabbed)) { object->window->toggleTabbedAction->trigger(); } } QString mdiViewMode() const override { QString mode; if (object->window->getMdiArea()->viewMode() == QMdiArea::TabbedView) { mode = "de.uni_stuttgart.Voxie.MdiViewMode.Tabbed"; } else if (object->window->getTilePattern()) { mode = "de.uni_stuttgart.Voxie.MdiViewMode.SubWindowTiled"; } else { mode = "de.uni_stuttgart.Voxie.MdiViewMode.SubWindow"; } return mode; } }; } // namespace gui } // namespace vx Gui::Gui(CoreWindow* window) : ExportedObject("Gui", window, true), window(window) { new GuiAdaptorImpl(this); // https://bugreports.qt.io/browse/QTBUG-48008 // https://randomguy3.wordpress.com/2010/09/07/the-magic-of-qtdbus-and-the-propertychanged-signal/ connect(window, &CoreWindow::activeVisualizerChanged, [=](VisualizerNode* visualizer) { // http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-properties // org.freedesktop.DBus.Properties.PropertiesChanged (STRING // interface_name, // DICT<STRING,VARIANT> // changed_properties, // ARRAY<STRING> // invalidated_properties); QString propertyName = "ActiveVisualizer"; auto value = ExportedObject::getPath(visualizer); QDBusMessage signal = QDBusMessage::createSignal( window->getGuiDBusObject()->getPath().path(), "org.freedesktop.DBus.Properties", "PropertiesChanged"); signal << dbusMakeVariant<QString>("de.uni_stuttgart.Voxie.Gui") .variant(); QMap<QString, QDBusVariant> changedProps; changedProps.insert(propertyName, dbusMakeVariant<QDBusObjectPath>(value)); signal << dbusMakeVariant<QMap<QString, QDBusVariant>>(changedProps) .variant(); signal << dbusMakeVariant<QList<QString>>(QStringList()).variant(); getBusManager()->sendEverywhere(signal); }); connect(window->sidePanel, &SidePanel::nodeSelectionChanged, [=]() { // http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-properties // org.freedesktop.DBus.Properties.PropertiesChanged (STRING // interface_name, // DICT<STRING,VARIANT> // changed_properties, // ARRAY<STRING> // invalidated_properties); QString propertyName = "SelectedNodes"; QString propertyNameOld = "SelectedObjects"; QList<QDBusObjectPath> value; for (const auto& obj : window->sidePanel->selectedNodes()) value << ExportedObject::getPath(obj); QDBusMessage signal = QDBusMessage::createSignal( window->getGuiDBusObject()->getPath().path(), "org.freedesktop.DBus.Properties", "PropertiesChanged"); signal << dbusMakeVariant<QString>("de.uni_stuttgart.Voxie.Gui").variant(); QMap<QString, QDBusVariant> changedProps; changedProps.insert(propertyName, dbusMakeVariant<QList<QDBusObjectPath>>(value)); changedProps.insert(propertyNameOld, dbusMakeVariant<QList<QDBusObjectPath>>(value)); signal << dbusMakeVariant<QMap<QString, QDBusVariant>>(changedProps).variant(); signal << dbusMakeVariant<QStringList>(QStringList()).variant(); getBusManager()->sendEverywhere(signal); }); } Gui::~Gui() {} QList<QDBusObjectPath> GuiAdaptorImpl::selectedNodes() const { try { QList<QDBusObjectPath> res; for (const auto& obj : object->window->sidePanel->selectedNodes()) res << ExportedObject::getPath(obj); return res; } catch (Exception& e) { e.handle(object); return QList<QDBusObjectPath>(); } } QList<QDBusObjectPath> GuiAdaptorImpl::selectedObjects() const { try { QList<QDBusObjectPath> res; for (const auto& obj : object->window->sidePanel->selectedNodes()) res << ExportedObject::getPath(obj); return res; } catch (Exception& e) { e.handle(object); return QList<QDBusObjectPath>(); } } QDBusObjectPath GuiAdaptorImpl::activeVisualizer() const { try { return ExportedObject::getPath(object->window->getActiveVisualizer()); } catch (Exception& e) { e.handle(object); return ExportedObject::getPath(nullptr); } } void GuiAdaptorImpl::RaiseWindow(const QMap<QString, QDBusVariant>& options) { try { ExportedObject::checkOptions(options); object->window->activateWindow(); object->window->raise(); } catch (Exception& e) { e.handle(object); } } qulonglong GuiAdaptorImpl::GetMainWindowID( const QMap<QString, QDBusVariant>& options) { try { ExportedObject::checkOptions(options); return object->window->winId(); } catch (Exception& e) { e.handle(object); return 0; } } CoreWindow::CoreWindow(vx::Root* root, QWidget* parent) : QMainWindow(parent), visualizers(), activeVisualizer(nullptr), isBeginDestroyed(false), activeVisualizerProvider(this) { connect(this, &CoreWindow::activeVisualizerChanged, this, [this](VisualizerNode* current) { Q_EMIT activeVisualizerProvider.activeVisualizerChanged(current); }); this->setWindowTitle("Voxie"); this->initMenu(); this->initStatusBar(); this->initWidgets(root); this->guiDBusObject = new Gui(this); this->setWindowIcon(QIcon(":/icons-voxie/voxel-data-32.png")); } CoreWindow::~CoreWindow() { isBeginDestroyed = true; } void CoreWindow::insertPlugin(const QSharedPointer<Plugin>& plugin) { if (plugin->uiCommands().size() > 0) { QMenu* pluginEntry = this->pluginsMenu->addMenu(plugin->name()); // Insert UI Actions QList<QAction*> pluginActions; for (QAction* action : plugin->uiCommands()) { pluginActions.append(action); } pluginEntry->addActions(pluginActions); } } void CoreWindow::addVisualizer(VisualizerNode* visualizer) { if (visualizer == nullptr) { return; } VisualizerContainer* container = new VisualizerContainer(this->mdiArea, visualizer); this->visualizers.append(container); connect(container, &QObject::destroyed, this, [=]() { if (isBeginDestroyed) return; this->visualizers.removeAll(container); }); QAction* windowEntry = this->windowMenu->addAction(visualizer->icon(), container->windowTitle()); connect(windowEntry, &QAction::triggered, container, &VisualizerContainer::activate); connect(container, &QWidget::destroyed, windowEntry, &QAction::deleteLater); connect(visualizer, &QWidget::destroyed, container, &VisualizerContainer::closeWindow); QMetaObject::Connection connection = connect(container, &VisualizerContainer::sidePanelVisiblityChanged, [=](bool visible) { // qDebug() << "VisualizerContainer::sidePanelVisiblityChanged" // << container << visualizer << visible; if (visible == false) return; if (this->activeVisualizer != visualizer) { this->activeVisualizer = visualizer; Q_EMIT activeVisualizerChanged(visualizer); } this->mdiArea->setActiveSubWindow(container->window); // This is disabled because it is also e.g. triggered when the // main window regains focus and causes another node to be // selected in this case //// update sidepanel to view data of selected visualizer // this->sidePanel->nodeTree->select(visualizer); }); connect(container, &QObject::destroyed, this, [=]() { if (isBeginDestroyed) return; if (this->activeVisualizer == visualizer) { this->activeVisualizer = nullptr; Q_EMIT activeVisualizerChanged(nullptr); } disconnect(connection); }); QVector<QWidget*> sections = visualizer->dynamicSections(); for (QWidget* section : sections) visualizer->addPropertySection(section); visualizer->mainView()->setFocus(); this->activeVisualizer = visualizer; Q_EMIT activeVisualizerChanged(visualizer); } VisualizerNode* CoreWindow::getActiveVisualizer() { return activeVisualizer; } void CoreWindow::initMenu() { QMenuBar* menu = new QMenuBar(this); QMenu* fileMenu = menu->addMenu("&File"); this->pluginsMenu = menu->addMenu("Plu&gins"); this->scriptsMenu = menu->addMenu("&Scripts"); { connect(scriptsMenu, &QMenu::aboutToShow, this, &CoreWindow::populateScriptsMenu); } this->windowMenu = menu->addMenu("&Window"); QMenu* helpMenu = menu->addMenu("&Help"); // Lets the user begin a new session by destroying all data nodes QAction* newAction = fileMenu->addAction(QIcon(":/icons/blue-document.png"), "&New..."); newAction->setShortcut(QKeySequence("Ctrl+N")); connect(newAction, &QAction::triggered, this, &CoreWindow::newSession); QAction* openAction = fileMenu->addAction( QIcon(":/icons/blue-folder-horizontal-open.png"), "&Open…"); openAction->setShortcut(QKeySequence("Ctrl+O")); connect(openAction, &QAction::triggered, this, &CoreWindow::loadFile); QAction* loadAction = fileMenu->addAction( QIcon(":/icons/folder-horizontal.png"), "&Load Voxie Project"); loadAction->setShortcut(QKeySequence("Ctrl+L")); connect(loadAction, &QAction::triggered, this, [this] { if (newSession()) loadProject(); }); QAction* importAction = fileMenu->addAction(QIcon(":/icons/folder--plus.png"), "&Import Project/Node Group"); importAction->setShortcut(QKeySequence("Ctrl+I")); connect(importAction, &QAction::triggered, this, &CoreWindow::loadProject); QAction* saveAction = fileMenu->addAction(QIcon(":/icons/disk.png"), "&Save Voxie Project"); saveAction->setShortcut(QKeySequence("Ctrl+S")); connect(saveAction, &QAction::triggered, this, &CoreWindow::saveProject); fileMenu->addSeparator(); QAction* addNodeAction = fileMenu->addAction(QIcon(":/icons/disk.png"), "Add n&ew node"); addNodeAction->setShortcut(QKeySequence("Ctrl+Shift+E")); connect(addNodeAction, &QAction::triggered, this, [this]() { auto globalPos = QCursor::pos(); Node* obj = nullptr; sidePanel->showContextMenu(obj, globalPos); }); QAction* addNodeActionAsChild = fileMenu->addAction(QIcon(":/icons/disk.png"), "Add n&ew node as child"); addNodeActionAsChild->setShortcut(QKeySequence("Ctrl+E")); connect(addNodeActionAsChild, &QAction::triggered, this, [this]() { auto globalPos = QCursor::pos(); Node* obj = nullptr; if (sidePanel->selectedNodes().size()) obj = sidePanel->selectedNodes()[0]; sidePanel->showContextMenu(obj, globalPos); }); fileMenu->addSeparator(); QAction* preferencesAction = fileMenu->addAction(QIcon(":/icons/gear.png"), "&Preferences…"); connect(preferencesAction, &QAction::triggered, this, [this]() -> void { PreferencesWindow* preferences = new PreferencesWindow(this); preferences->setAttribute(Qt::WA_DeleteOnClose); preferences->exec(); }); QAction* quitAction = fileMenu->addAction(QIcon(":/icons/cross.png"), "E&xit"); quitAction->setShortcut(QKeySequence("Ctrl+Q")); connect(quitAction, &QAction::triggered, this, &QMainWindow::close); QAction* pluginManagerAction = this->pluginsMenu->addAction( QIcon(":/icons/plug.png"), "&Plugin Manager…"); connect(pluginManagerAction, &QAction::triggered, this, [this]() -> void { PluginManagerWindow* pluginmanager = new PluginManagerWindow(this); pluginmanager->setAttribute(Qt::WA_DeleteOnClose); pluginmanager->exec(); }); this->pluginsMenu->addSeparator(); scriptsMenuStaticSize = 0; QAction* scriptConsoleAction = this->scriptsMenu->addAction( QIcon(":/icons/application-terminal.png"), "&JS Console…"); scriptsMenuStaticSize++; connect(scriptConsoleAction, &QAction::triggered, this, [this]() -> void { ScriptConsole* console = new ScriptConsole(this, "Voxie - JS Console"); console->setAttribute(Qt::WA_DeleteOnClose); connect(console, &ScriptConsole::executeCode, this, [console](const QString& code) -> void { Root::instance()->exec(code, code, [console](const QString& text) { console->appendLine(text); }); }); console->show(); console->activateWindow(); }); QAction* pythonConsoleAction = this->scriptsMenu->addAction( QIcon(":/icons/application-terminal.png"), "&Python Console…"); scriptsMenuStaticSize++; pythonConsoleAction->setShortcut(QKeySequence("Ctrl+Shift+S")); connect(pythonConsoleAction, &QAction::triggered, this, [this]() -> void { auto service = Root::instance()->mainDBusService(); if (!service) { QMessageBox( QMessageBox::Critical, Root::instance()->mainWindow()->windowTitle(), QString("Cannot launch python console because DBus is not available"), QMessageBox::Ok, Root::instance()->mainWindow()) .exec(); return; } ScriptConsole* console = new ScriptConsole(this, "Voxie - Python Console"); console->setAttribute(Qt::WA_DeleteOnClose); // TODO: This should probably also use ScriptLauncher auto process = new QProcess(); connect(console, &QObject::destroyed, process, &QProcess::closeWriteChannel); process->setProcessChannelMode(QProcess::MergedChannels); process->setWorkingDirectory( Root::instance()->directoryManager()->baseDir()); process->setProgram( Root::instance()->directoryManager()->pythonExecutable()); QStringList args; args << "-i"; args << "-u"; args << "-c"; QString escapedPythonLibDirs = escapePythonStringArray( vx::Root::instance()->directoryManager()->allPythonLibDirs()); args << "import sys; sys.path = " + escapedPythonLibDirs + " + sys.path; " + "import numpy as np; import voxie; args = " "voxie.parser.parse_args(); context = " "voxie.VoxieContext(args); instance = " "context.createInstance();"; service->addArgumentsTo(args); process->setArguments(args); connect<void (QProcess::*)(int, QProcess::ExitStatus), std::function<void(int, QProcess::ExitStatus)>>( process, &QProcess::finished, console, std::function<void(int, QProcess::ExitStatus)>( [process, console](int exitCode, QProcess::ExitStatus exitStatus) -> void { console->appendLine( QString( "Script host finished with exit status %1 / exit code %2") .arg(exitStatus) .arg(exitCode)); process->deleteLater(); })); auto isStarted = createQSharedPointer<bool>(); connect(process, &QProcess::started, this, [isStarted]() { *isStarted = true; }); connect(process, &QProcess::stateChanged, this, [process, isStarted](QProcess::ProcessState newState) { if (newState == QProcess::NotRunning && !*isStarted) { Root::instance()->log( QString("Error while starting script host: %1") .arg(process->error())); process->deleteLater(); } }); connect(process, &QProcess::readyRead, console, [process, console]() -> void { QString data = QString(process->readAll()); console->append(data); }); connect(console, &ScriptConsole::executeCode, process, [process, console](const QString& code) -> void { QString code2 = code + "\n"; console->append(code2); // TODO: handle case when python process does not read input process->write(code2.toUtf8()); }); process->start(); console->show(); console->activateWindow(); }); // TODO: Clean up #if defined(Q_OS_LINUX) || defined(Q_OS_MACOS) QAction* pythonConsoleTerminalAction = this->scriptsMenu->addAction( QIcon(":/icons/application-terminal.png"), "Python Console (&terminal)…"); scriptsMenuStaticSize++; pythonConsoleTerminalAction->setShortcut(QKeySequence("Ctrl+Shift+T")); connect( pythonConsoleTerminalAction, &QAction::triggered, this, [this]() -> void { auto service = Root::instance()->mainDBusService(); if (!service) { QMessageBox( QMessageBox::Critical, Root::instance()->mainWindow()->windowTitle(), QString( "Cannot launch python console because DBus is not available"), QMessageBox::Ok, Root::instance()->mainWindow()) .exec(); return; } QStringList args; #if !defined(Q_OS_MACOS) // TODO: clean up args << "--"; #endif args << Root::instance()->directoryManager()->pythonExecutable(); args << "-i"; args << "-u"; args << "-c"; QString escapedPythonLibDirs = escapePythonStringArray( vx::Root::instance()->directoryManager()->allPythonLibDirs()); args << "import sys; sys.path = " + escapedPythonLibDirs + " + sys.path; " + "import numpy as np; import voxie; args = " "voxie.parser.parse_args(); context = " "voxie.VoxieContext(args); instance = " "context.createInstance();"; auto output = createQSharedPointer<QString>(); #if defined(Q_OS_MACOS) service->addArgumentsTo(args); QString command = escapeArguments(args); QString script = "tell application \"Terminal\" to do script " + appleScriptEscape(command); qDebug() << script.toUtf8().data(); QStringList osascriptArgs; osascriptArgs << "-e"; osascriptArgs << script; auto process = new QProcess(); Root::instance()->scriptLauncher()->setupEnvironment( process, false); // Set PYTHONPATH etc. process->setProgram("osascript"); process->setArguments(osascriptArgs); process->start(); #else auto process = Root::instance()->scriptLauncher()->startScript( "gnome-terminal", nullptr, args, new QProcess(), output, false); #endif // TODO: Move parts to ScriptLauncher? // TODO: This should be done before the process is started #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) QObject::connect( process, &QProcess::errorOccurred, Root::instance(), [](QProcess::ProcessError error) { QMessageBox(QMessageBox::Critical, "Error while starting python console", QString() + "Error while starting python console: " + QVariant::fromValue(error).toString(), QMessageBox::Ok) .exec(); }); #endif QObject::connect( process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>( &QProcess::finished), Root::instance(), [output](int exitCode, QProcess::ExitStatus exitStatus) { if (exitStatus != QProcess::NormalExit || exitCode != 0) { QString scriptOutputString = *output; if (scriptOutputString != "") scriptOutputString = "\n\nScript output:\n" + scriptOutputString; QMessageBox(QMessageBox::Critical, "Error while starting python console", QString() + "Error while starting python console: " + QVariant::fromValue(exitStatus).toString() + ", code = " + QString::number(exitCode) + scriptOutputString, QMessageBox::Ok) .exec(); } else { /* QString scriptOutputString = *output; if (scriptOutputString != "") { QMessageBox(QMessageBox::Warning, "Warnings while starting python console", QString() + "Warnings while starting python console:\n" + scriptOutputString, QMessageBox::Ok) .exec(); } */ } }); }); #endif this->scriptsMenu->addSeparator(); scriptsMenuStaticSize++; QAction* cascadeAction = this->windowMenu->addAction( QIcon(":/icons/applications-blue.png"), "&Cascade"); connect(cascadeAction, &QAction::triggered, [=]() -> void { this->mdiArea->cascadeSubWindows(); isTilePattern = false; }); QAction* tileAction = this->windowMenu->addAction( QIcon(":/icons/application-tile.png"), "&Tile"); connect(tileAction, &QAction::triggered, [=]() -> void { this->mdiArea->tileSubWindows(); isTilePattern = true; }); QAction* fillAction = this->windowMenu->addAction( QIcon(":/icons/application-blue.png"), "&Fill"); connect(fillAction, &QAction::triggered, [=]() -> void { QMdiSubWindow* subwindow = this->mdiArea->currentSubWindow(); if (subwindow == nullptr) { return; } subwindow->setWindowState(subwindow->windowState() | Qt::WindowMaximized); }); toggleTabbedAction = this->windowMenu->addAction( QIcon(":/icons/application-dock-tab.png"), "Ta&bbed"); toggleTabbedAction->setCheckable(true); connect(toggleTabbedAction, &QAction::toggled, [=]() -> void { bool checked = toggleTabbedAction->isChecked(); cascadeAction->setEnabled(!checked); tileAction->setEnabled(!checked); fillAction->setEnabled(!checked); if (checked) { this->mdiArea->setViewMode(QMdiArea::TabbedView); } else { this->mdiArea->setViewMode(QMdiArea::SubWindowView); this->setTilePattern(isTilePattern); } }); this->windowMenu->addSeparator(); QAction* helpShowAction = helpMenu->addAction(QIcon(":/icons/book-question.png"), "&Show help…"); connect(helpShowAction, &QAction::triggered, []() -> void { Root::instance()->helpLinkHandler()->handleLink( vx::help::uriForHelpTopic("main")); }); QAction* helpIndexAction = helpMenu->addAction(QIcon(":/icons/book-open-list.png"), "&Index…"); connect(helpIndexAction, &QAction::triggered, []() -> void { Root::instance()->helpLinkHandler()->handleLink( vx::help::uriForHelp("index")); }); QAction* oldManualAction = helpMenu->addAction(QIcon(":/icons/book-question.png"), "&Old manual…"); connect(oldManualAction, &QAction::triggered, this, [this]() -> void { auto oldManualFile = Root::instance()->directoryManager()->oldManualFile(); if (oldManualFile == "") QMessageBox(QMessageBox::Warning, this->windowTitle(), "Old manual file not found.", QMessageBox::Ok, this) .exec(); else QDesktopServices::openUrl(QUrl::fromLocalFile(oldManualFile)); }); QAction* homepageAction = helpMenu->addAction("&Homepage…"); connect(homepageAction, &QAction::triggered, []() -> void { QDesktopServices::openUrl( QUrl("https://github.com/voxie-viewer/voxie", QUrl::TolerantMode)); }); QAction* aboutAction = helpMenu->addAction(QIcon(":/icons/information.png"), "&About…"); connect(aboutAction, &QAction::triggered, this, [this]() -> void { AboutDialogWindow* aboutwindow = new AboutDialogWindow(this); aboutwindow->setAttribute(Qt::WA_DeleteOnClose); aboutwindow->exec(); }); this->setMenuBar(menu); } void CoreWindow::initStatusBar() { QStatusBar* statusBar = new QStatusBar(this); this->setStatusBar(statusBar); } void CoreWindow::initWidgets(vx::Root* root) { auto container = new QSplitter(Qt::Horizontal); { { this->mdiArea = new QMdiArea(this); this->mdiArea->setTabsClosable(true); sidePanel = new SidePanel(root, this); connect(sidePanel, &SidePanel::openFile, this, &CoreWindow::loadFile); connect(sidePanel, &SidePanel::nodeSelectionChanged, this, [this]() { Q_EMIT activeVisualizerProvider.nodeSelectionChanged( sidePanel->selectedNodes()); }); if (sidePanelOnLeft) { container->addWidget(sidePanel); container->addWidget(this->mdiArea); container->setCollapsible(1, false); } else { container->addWidget(this->mdiArea); container->setCollapsible(0, false); container->addWidget(sidePanel); } } } this->setCentralWidget(container); } void CoreWindow::populateScriptsMenu() { QList<QAction*> actions = this->scriptsMenu->actions(); for (int i = this->scriptsMenuStaticSize; i < actions.size(); i++) { this->scriptsMenu->removeAction(actions.at(i)); } for (auto scriptDirectory : Root::instance()->directoryManager()->scriptPath()) { QDir scriptDir = QDir(scriptDirectory); QStringList scripts = scriptDir.entryList(QStringList("*.js"), QDir::Files | QDir::Readable); for (QString script : scripts) { if (script.endsWith("~")) continue; QString scriptFile = scriptDirectory + "/" + script; if (QFileInfo(scriptFile).isExecutable()) continue; QString baseName = scriptFile; if (baseName.endsWith(".exe")) baseName = scriptFile.left(scriptFile.length() - 4); if (QFile::exists(baseName + ".json")) continue; QAction* action = this->scriptsMenu->addAction( QIcon(":/icons/script-attribute-j.png"), script); connect(action, &QAction::triggered, this, [scriptFile]() -> void { Root::instance()->execFile(scriptFile); }); } } this->scriptsMenu->addSeparator(); for (auto scriptDirectory : Root::instance()->directoryManager()->scriptPath()) { QDir scriptDir = QDir(scriptDirectory); QStringList scripts = scriptDir.entryList(QStringList("*"), QDir::Files | QDir::Readable); for (QString script : scripts) { if (script.endsWith("~")) continue; QString scriptFile = scriptDirectory + "/" + script; if (!QFileInfo(scriptFile).isExecutable()) continue; QString baseName = scriptFile; if (baseName.endsWith(".exe")) baseName = scriptFile.left(scriptFile.length() - 4); if (QFile::exists(baseName + ".json")) continue; QAction* action = this->scriptsMenu->addAction( QIcon(":/icons/script-attribute-e.png"), script); connect(action, &QAction::triggered, this, [scriptFile]() -> void { Root::instance()->scriptLauncher()->startScript(scriptFile); }); } } this->scriptsMenu->addSeparator(); { QStringList fileTypes; Root::instance()->settings()->beginGroup("scripting"); int sizeExternals = Root::instance()->settings()->beginReadArray("externals"); for (int i = 0; i < sizeExternals; ++i) { Root::instance()->settings()->setArrayIndex(i); fileTypes.append(Root::instance() ->settings() ->value("extension") .toString() .split(';')); } Root::instance()->settings()->endArray(); Root::instance()->settings()->endGroup(); if (!fileTypes.contains("*.py")) fileTypes << "*.py"; for (auto scriptDirectory : Root::instance()->directoryManager()->scriptPath()) { QDir scriptDir = QDir(scriptDirectory); QStringList externalScripts = scriptDir.entryList(fileTypes, QDir::Files | QDir::Readable); for (QString script : externalScripts) { if (script.endsWith("~")) continue; QString scriptFile = scriptDirectory + "/" + script; if (QFileInfo(scriptFile).isExecutable()) continue; QString baseName = scriptFile; if (baseName.endsWith(".exe")) baseName = scriptFile.left(scriptFile.length() - 4); if (QFile::exists(baseName + ".json")) continue; QAction* action = this->scriptsMenu->addAction( QIcon(":/icons/script-attribute-p.png"), script); connect( action, &QAction::triggered, this, [this, scriptFile]() -> void { Root::instance()->settings()->beginGroup("scripting"); int size = Root::instance()->settings()->beginReadArray("externals"); bool found = false; for (int i = 0; i < size; ++i) { Root::instance()->settings()->setArrayIndex(i); QString executable = Root::instance() ->settings() ->value("executable") .toString(); for (const QString& ext : Root::instance() ->settings() ->value("extension") .toString() .split(';')) { QRegExp regexp(ext, Qt::CaseInsensitive, QRegExp::WildcardUnix); if (regexp.exactMatch(scriptFile) == false) continue; Root::instance()->scriptLauncher()->startScript(scriptFile, &executable); found = true; break; } if (found) break; } if (!found && scriptFile.endsWith(".py")) { // startScript will handle python files Root::instance()->scriptLauncher()->startScript(scriptFile); found = true; } if (!found) QMessageBox(QMessageBox::Critical, this->windowTitle(), QString("Failed to find interpreter for script " + scriptFile), QMessageBox::Ok, this) .exec(); Root::instance()->settings()->endArray(); Root::instance()->settings()->endGroup(); }); } } } } bool CoreWindow::newSession() { // Only show the confirmation dialog if there are actually any datasets loaded // right now if (Root::instance()->nodes().size() > 0) { // Ask the user for confirmation before removing everything that's currently // loaded QMessageBox::StandardButton confirmation; confirmation = QMessageBox::warning(this, "Voxie", "Warning: This will close all currently loaded " "nodes.\nAre you sure?", QMessageBox::Yes | QMessageBox::No); // User selected Yes -> Destroy all datasets (and visualizers, slices) if (confirmation == QMessageBox::Yes) { clearNodes(); return true; } return false; } return true; } void CoreWindow::clearNodes() { for (const auto& node : Root::instance()->nodes()) { node->destroy(); } } void CoreWindow::loadFile() { new vx::OpenFileDialog(Root::instance(), this); } /** * @brief This method opens a file dialog to let the user save all currently * loaded files and settigns as a voxie project The project is then saved in a * script file, which can be used to load it again */ bool CoreWindow::saveProject() { SessionManager* sessionManager = new SessionManager(); vx::io::SaveFileDialog dialog(this, "Save as...", QString()); dialog.addFilter(FilenameFilter("Voxie Project", {"*.vxprj.py"}), nullptr); dialog.setup(); // TODO: This should be asynchronous if (dialog.exec() != QDialog::Accepted) return false; // Pass the selected filename and list of loaded datasets to the // SessionManager class, which handles saving and loading projects sessionManager->saveSession(dialog.selectedFiles().first()); return true; } void CoreWindow::loadProject() { SessionManager* sessionManager = new SessionManager(); QFileDialog dialog(this, "Select a Voxie Project or Node Group File..."); dialog.setDefaultSuffix("vxprj.py"); dialog.setAcceptMode(QFileDialog::AcceptOpen); dialog.setNameFilter("Voxie Project Files (*.vxprj.py *.ngrp.py)"); dialog.setOption(QFileDialog::DontUseNativeDialog, true); if (dialog.exec() != QDialog::Accepted) return; QString filename = dialog.selectedFiles().first(); sessionManager->loadSession(filename); } void CoreWindow::closeEvent(QCloseEvent* event) { // Skip the close dialog if there are no nodes if (vx::Root::instance()->nodes().size() > 0) { QMessageBox closeDialog; closeDialog.setText("Do you want to save your current project?"); closeDialog.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); closeDialog.setDefaultButton(QMessageBox::Save); closeDialog.setWindowIcon(QIcon(":/icons-voxie/voxel-data-32.png")); int ret = closeDialog.exec(); switch (ret) { case QMessageBox::Save: if (saveProject()) { closeDialog.close(); clearNodes(); event->accept(); } else { event->ignore(); } break; case QMessageBox::Discard: closeDialog.close(); clearNodes(); event->accept(); break; case QMessageBox::Cancel: event->ignore(); break; } } else { event->accept(); } }
37.785783
101
0.620542
voxie-viewer
e606d8c4f285ec6b7003f20ac139c639eb31ab64
723
cpp
C++
problems/lc1492/solution1.cpp
caohongjian/leetcode
bba854b407b1caa6a237ceb726592ff0458b3a29
[ "MIT" ]
1
2020-07-01T10:42:09.000Z
2020-07-01T10:42:09.000Z
problems/lc1492/solution1.cpp
murmur-wheel/leetcode
bba854b407b1caa6a237ceb726592ff0458b3a29
[ "MIT" ]
null
null
null
problems/lc1492/solution1.cpp
murmur-wheel/leetcode
bba854b407b1caa6a237ceb726592ff0458b3a29
[ "MIT" ]
null
null
null
// // Created by chj on 2020/7/3. // // https://leetcode-cn.com/problems/the-kth-factor-of-n/ #include <algorithm> #include <cmath> #include <iostream> #include <vector> // 先计算 n 的所有因子,然后排序 class Solution { public: int kthFactor(int n, int k) { std::vector<int> v; const int K = std::sqrt(n); for (int i = 1; i <= K; ++i) { // 如果 i 是 n 的因子,那么 n / i 也一定是 n 的因子 if (n % i == 0) { v.push_back(i); v.push_back(n / i); } } v.push_back(n); std::sort(v.begin(), v.end()); v.erase(std::unique(v.begin(), v.end()), v.end()); return k <= v.size() ? v[k - 1] : -1; } }; int main() { std::cout << "n = 100, k = 3, f = " << Solution().kthFactor(1000, 12); }
20.083333
72
0.518672
caohongjian
e607a84e0da2e6ead2c9ef694996341c13242b3a
376
cpp
C++
C++_Stroustrup/3-Objects,Types,Values/repeatWord.cpp
Cristo12345/CS_Review
7a0c60074a8a6d23f973e4e5e570e3ef22eec252
[ "MIT" ]
1
2020-07-17T01:54:43.000Z
2020-07-17T01:54:43.000Z
C++_Stroustrup/3-Objects,Types,Values/repeatWord.cpp
Cristo12345/CS_Review
7a0c60074a8a6d23f973e4e5e570e3ef22eec252
[ "MIT" ]
null
null
null
C++_Stroustrup/3-Objects,Types,Values/repeatWord.cpp
Cristo12345/CS_Review
7a0c60074a8a6d23f973e4e5e570e3ef22eec252
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { string prev = " "; string curr; int numOfWords = 0; while (cin >> curr) { numOfWords++; if (prev == curr) { cout << "word number " << numOfWords << '\n'; cout << "repeated word: " << curr << '\n'; } prev = curr; } return 0; }
15.666667
57
0.441489
Cristo12345
e60ce1a683fd10624ac4867548ce8a7124228753
352
hpp
C++
src/Graphics/Rect.hpp
ryu-raptor/amf
33a42cf1025ea512f23c4769a5be27d6a0c335bc
[ "MIT" ]
1
2020-05-31T02:25:39.000Z
2020-05-31T02:25:39.000Z
src/Graphics/Rect.hpp
ryu-raptor/amf
33a42cf1025ea512f23c4769a5be27d6a0c335bc
[ "MIT" ]
null
null
null
src/Graphics/Rect.hpp
ryu-raptor/amf
33a42cf1025ea512f23c4769a5be27d6a0c335bc
[ "MIT" ]
null
null
null
#include "Graphics/glHeaders.hpp" namespace Graphics { struct Rect { GLfloat width; GLfloat height; GLfloat x; GLfloat y; Rect(GLfloat x, GLfloat y, GLfloat width, GLfloat height) { this->width = width; this->height = height; this->x = x; this->y = y; } }; } // namespace Graphics
17.6
61
0.565341
ryu-raptor
e610989d946185f78f5fca7972a237425365bf05
1,933
cpp
C++
Test/PKTest/Native/Src/UART/UART.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
529
2015-03-10T00:17:45.000Z
2022-03-17T02:21:19.000Z
Test/PKTest/Native/Src/UART/UART.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
495
2015-03-10T22:02:46.000Z
2019-05-16T13:05:00.000Z
Test/PKTest/Native/Src/UART/UART.cpp
PervasiveDigital/netmf-interpreter
03d84fe76e0b666ebec62d17d69c55c45940bc40
[ "Apache-2.0" ]
332
2015-03-10T08:04:36.000Z
2022-03-29T04:18:36.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "UART.h" //------------------------------------------------------------------------------ BOOL UART::UART_Receive(char * RecvBuffer, int MaxExpected, int MaxLoop) { INT16 CountReceived = 0; INT16 LoopCount=0; do { if (LoopCount++ > MaxLoop) { break; } CountReceived += USART_Read(UART::ComPort, &RecvBuffer[CountReceived], (sizeof (char)*(MaxExpected-CountReceived))); if (CountReceived >= MaxExpected) { return true; } if (!USART_Flush(UART::ComPort)) { Comment("Failed to flush"); return false; } } while(1); if (CountReceived < MaxExpected) { UART::Comment("wrong rcv count"); return false; } return true; } BOOL UART::UART_Transmit(char * XmitBuffer, int MaxToSend, int MaxLoop) { INT16 CountSent=0; INT16 LoopCount=0; do { if (LoopCount++ > MaxLoop) { break; } CountSent += USART_Write(UART::ComPort, &XmitBuffer[CountSent], (MaxToSend-CountSent)*sizeof(char)); if (CountSent >= MaxToSend) { return true; } } while(1); //if (!USART_Flush(UART::ComPort)) // { // Comment("Failed to flush"); // return false; //} return true; }
27.225352
201
0.375582
PervasiveDigital
e610f8c0a4ba877de1909e9d7f7231f6d42adcdc
612
hpp
C++
MemLeak/src/RenderTarget/RenderTarget.hpp
pk8868/MemLeak
72f937110c2b67547f67bdea60d2e80b0f5581a1
[ "MIT" ]
null
null
null
MemLeak/src/RenderTarget/RenderTarget.hpp
pk8868/MemLeak
72f937110c2b67547f67bdea60d2e80b0f5581a1
[ "MIT" ]
null
null
null
MemLeak/src/RenderTarget/RenderTarget.hpp
pk8868/MemLeak
72f937110c2b67547f67bdea60d2e80b0f5581a1
[ "MIT" ]
null
null
null
#pragma once // --------- Graphics -------- // #include "Texture/Texture.hpp" #include "Image/Image.hpp" #include "Sprite/Sprite.hpp" #include "Shape/Rect/Rectangle.hpp" #include "Shape/Line/Line.hpp" #include "Text/Text.hpp" namespace ml { class Image; class Sprite; class Rectangle; class Line; class Text; struct Color; class RenderTarget { public: virtual void clear(Color color) = 0; virtual void render(Sprite& sprite) = 0; virtual void render(Rectangle& rectangle) = 0; virtual void render(Line& line) = 0; virtual void render(Text& text) = 0; virtual void display() = 0; }; }
18.545455
48
0.678105
pk8868
e6130dcbaecdbfc71c41191cb6355739dbac954e
5,216
cpp
C++
Core/src/GFX/2D/Sprite.cpp
IridescentRose/Stardust-Engine
ee6a6b5841c16dddf367564a92eb263827631200
[ "MIT" ]
55
2020-10-07T01:54:49.000Z
2022-03-26T11:39:11.000Z
Core/src/GFX/2D/Sprite.cpp
IridescentRose/Ionia
ee6a6b5841c16dddf367564a92eb263827631200
[ "MIT" ]
15
2020-05-30T18:22:50.000Z
2020-08-08T11:01:36.000Z
Core/src/GFX/2D/Sprite.cpp
IridescentRose/Ionia
ee6a6b5841c16dddf367564a92eb263827631200
[ "MIT" ]
6
2020-10-22T11:09:47.000Z
2022-01-07T13:10:09.000Z
#include <GFX/2D/Sprite.h> namespace Stardust::GFX::Render2D{ Sprite::Sprite() { tex = -1; offset = { 0, 0 }; scaleFactor = { 1.0, 1.0 }; rotation = {0, 0}; } Sprite::~Sprite() { model.deleteData(); } Sprite::Sprite(unsigned int t) { rotation = {0, 0}; tex = t; Texture* tex2 = g_TextureManager->getTex(t); scaleFactor = { 1.0, 1.0 }; mesh.position = { -tex2->width / 2.0f,-tex2->height / 2.0f, 0, //0 tex2->width / 2.0f,-tex2->height / 2.0f, 0, //1 tex2->width / 2.0f, tex2->height / 2.0f, 0, //2 -tex2->width / 2.0f, tex2->height / 2.0f, 0, //3 }; mesh.color = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, }; Texture* tD = g_TextureManager->getTex(t); float hPercent = (float)tD->height / (float)tD->pHeight; float wPercent = (float)tD->width / (float)tD->pWidth; mesh.uv = { 0, 0, wPercent, 0, wPercent, hPercent, 0, hPercent }; mesh.indices = { 3, 2, 1, 1, 0, 3 }; model.addData(mesh); } Sprite::Sprite(unsigned int t, glm::vec2 size) { rotation = {0, 0}; tex = t; scaleFactor = { 1.0, 1.0 }; mesh.position = { -size.x / 2.0f,-size.y / 2.0f, 0, //0 size.x / 2.0f,-size.y / 2.0f, 0, //1 size.x/2.0f, size.y/2.0f, 0, //2 -size.x / 2.0f, size.y / 2.0f, 0, //3 }; mesh.color = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, }; Texture* tD = g_TextureManager->getTex(t); float hPercent = (float)tD->height / (float)tD->pHeight; float wPercent = (float)tD->width / (float)tD->pWidth; mesh.uv = { 0, 0, wPercent, 0, wPercent, hPercent, 0, hPercent }; mesh.indices = { 3, 2, 1, 1, 0, 3 }; model.addData(mesh); } Sprite::Sprite(unsigned int t, glm::vec2 pos, glm::vec2 extent) { tex = t; rotation = {0, 0}; scaleFactor = { 1.0, 1.0 }; Texture* tD = g_TextureManager->getTex(t); mesh.color = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, }; float hstart = (float)pos.y / (float)tD->pHeight; float wstart = (float)pos.x / (float)tD->pWidth; float hPercent = (float)(pos.y + extent.y) / (float)tD->pHeight; float wPercent = (float)(pos.x + extent.x) / (float)tD->pWidth; mesh.uv = { wstart, hstart, wPercent, hstart, wPercent, hPercent, wstart, hPercent, }; mesh.position = { -extent.x / 2.0f,-extent.y / 2.0f, 0, //0 extent.x / 2.0f,-extent.y / 2.0f, 0, //1 extent.x / 2.0f, extent.y / 2.0f, 0, //2 -extent.x / 2.0f, extent.y / 2.0f, 0, //3 }; mesh.indices = { 3, 2, 1, 1, 0, 3 }; model.addData(mesh); } void Sprite::setLayer(int i) { mesh.position.clear(); mesh.position[0*3 + 2] = i; mesh.position[1*3 + 2] = i; mesh.position[2*3 + 2] = i; mesh.position[3*3 + 2] = i; model.addData(mesh); } void Sprite::setPosition(float x, float y) { offset = { x, y }; } void Sprite::setScale(float x, float y) { scaleFactor = { x, y }; } void Sprite::setColor(float r, float g, float b, float a) { mesh.color.clear(); mesh.color = { r, g, b, a, r, g, b, a, r, g, b, a, r, g, b, a, }; model.addData(mesh); } void Sprite::setTexture(unsigned int t) { tex = t; } void Sprite::rotate(float x, float y){ rotation = {x, y}; } void Sprite::draw() { //Matrix translation GFX::pushMatrix(); GFX::clearModelMatrix(); GFX::translateModelMatrix(glm::vec3(offset.x, offset.y, 1.0f)); GFX::pushMatrix(); GFX::scaleModelMatrix(glm::vec3(scaleFactor.x, scaleFactor.y, 1.0f)); GFX::pushMatrix(); GFX::rotateModelMatrix({ rotation.x, rotation.y, 0.0f }); g_TextureManager->bindTex(tex); model.draw(); GFX::popMatrix(); GFX::popMatrix(); GFX::popMatrix(); } void Sprite::setAmbientLight(AmbientLight light) { ambient = light; } void Sprite::addPointLight(PointLight light) { pointLights.push_back(light); } void Sprite::calculateLighting() { uint8_t r = (float)ambient.r * ambient.intensity; uint8_t g = (float)ambient.g * ambient.intensity; uint8_t b = (float)ambient.b * ambient.intensity; for (auto p : pointLights) { float distance = sqrtf((p.x - offset.x * 2.0f) * (p.x - offset.x * 2.0f) + (p.y - offset.y * 2.0f) * (p.y - offset.y * 2.0f)); float corrRange = (p.range * 10 - distance) / (p.range * 10); float intensityMax = 1.0f - ambient.intensity; float intensity = 0.0f; if (p.intensity > intensityMax) { intensity = intensityMax; } else { intensity = p.intensity; } if (corrRange > 1.0f) { corrRange = 1.0f; } if (corrRange > 0.0f) { r += ((float)p.r) * intensity * corrRange; g += ((float)p.g) * intensity * corrRange; b += ((float)p.b) * intensity * corrRange; } if (r > 255) { r = 255; } if (g > 255) { g = 255; } if (b > 255) { b = 255; } if (r < 0) { r = 0; } if (g < 0) { g = 0; } if (b < 0) { b = 0; } } setColor( (float)r / 255.0f, (float)g / 255.0f, (float)b / 255.0f, 1.0f); } void Sprite::clearPointLights() { pointLights.clear(); } }
19.247232
129
0.555982
IridescentRose
e6161a37befbd06765140d51a77698fabb16a6e3
735
cpp
C++
Pat/pat1002.cpp
yuanyangwangTJ/algorithm
ab7a959a00f290a0adc9af278f9a5de60be22af1
[ "MIT" ]
null
null
null
Pat/pat1002.cpp
yuanyangwangTJ/algorithm
ab7a959a00f290a0adc9af278f9a5de60be22af1
[ "MIT" ]
null
null
null
Pat/pat1002.cpp
yuanyangwangTJ/algorithm
ab7a959a00f290a0adc9af278f9a5de60be22af1
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; void read( int n,char num[10][5]); int main() { char num[10][5] = {"ling","yi","er","san","si","wu","liu","qi","ba","jiu"}; cout<<"please input a num:"<<endl; int count = 0,n; int t = getchar(); while( t !='\n' ) { n = t - '0'; count += n; t = getchar(); } read( count,num ); return 0; } void read( int n,char num[10][5] ) { int t; int cnt = 1; t = n; for( cnt=1;t>10; ) { t /= 10; cnt *= 10; } int rest; for( ;cnt>0;) { rest = n/cnt; n %= cnt; cnt /= 10; cout<<num[rest]; if(cnt>0) cout<<" "; } }
18.846154
80
0.391837
yuanyangwangTJ
e61f0b8fa40fda776d213a2fe4870cbafa49572d
65,710
cc
C++
sdk/sdk/share/linphone/coreapi/linphonecore_jni.cc
doyaGu/C0501Q_HWJL01
07a71328bd9038453cbb1cf9c276a3dd1e416d63
[ "MIT" ]
1
2021-10-09T08:05:50.000Z
2021-10-09T08:05:50.000Z
sdk/sdk/share/linphone/coreapi/linphonecore_jni.cc
doyaGu/C0501Q_HWJL01
07a71328bd9038453cbb1cf9c276a3dd1e416d63
[ "MIT" ]
null
null
null
sdk/sdk/share/linphone/coreapi/linphonecore_jni.cc
doyaGu/C0501Q_HWJL01
07a71328bd9038453cbb1cf9c276a3dd1e416d63
[ "MIT" ]
null
null
null
/* linphonecore_jni.cc Copyright (C) 2010 Belledonne Communications, Grenoble, France This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <jni.h> #include "linphonecore_utils.h" #include <ortp/zrtp.h> #ifdef TUNNEL_ENABLED #include "linphone_tunnel.h" #endif extern "C" { #include "mediastreamer2/mediastream.h" } #include "mediastreamer2/msjava.h" #include "private.h" #include <cpu-features.h> #ifdef ANDROID #include <android/log.h> extern "C" void libmsilbc_init(); #ifdef HAVE_X264 extern "C" void libmsx264_init(); #endif #ifdef HAVE_AMR extern "C" void libmsamr_init(); #endif #ifdef HAVE_SILK extern "C" void libmssilk_init(); #endif #ifdef HAVE_G729 extern "C" void libmsbcg729_init(); #endif #endif /*ANDROID*/ static JavaVM *jvm=0; #ifdef ANDROID static void linphone_android_log_handler(OrtpLogLevel lev, const char *fmt, va_list args){ int prio; switch(lev){ case ORTP_DEBUG: prio = ANDROID_LOG_DEBUG; break; case ORTP_MESSAGE: prio = ANDROID_LOG_INFO; break; case ORTP_WARNING: prio = ANDROID_LOG_WARN; break; case ORTP_ERROR: prio = ANDROID_LOG_ERROR; break; case ORTP_FATAL: prio = ANDROID_LOG_FATAL; break; default: prio = ANDROID_LOG_DEFAULT; break; } __android_log_vprint(prio, LOG_DOMAIN, fmt, args); } int dumbMethodForAllowingUsageOfCpuFeaturesFromStaticLibMediastream() { return (android_getCpuFamily() == ANDROID_CPU_FAMILY_ARM && (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0); } #endif /*ANDROID*/ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *ajvm, void *reserved) { #ifdef ANDROID ms_set_jvm(ajvm); #endif /*ANDROID*/ jvm=ajvm; return JNI_VERSION_1_2; } //LinphoneFactory extern "C" void Java_org_linphone_core_LinphoneCoreFactoryImpl_setDebugMode(JNIEnv* env ,jobject thiz ,jboolean isDebug) { if (isDebug) { linphone_core_enable_logs_with_cb(linphone_android_log_handler); } else { linphone_core_disable_logs(); } } // LinphoneCore class LinphoneCoreData { public: LinphoneCoreData(JNIEnv* env, jobject lc,jobject alistener, jobject auserdata) { core = env->NewGlobalRef(lc); listener = env->NewGlobalRef(alistener); userdata = auserdata?env->NewGlobalRef(auserdata):0; memset(&vTable,0,sizeof(vTable)); vTable.show = showInterfaceCb; vTable.auth_info_requested = authInfoRequested; vTable.display_status = displayStatusCb; vTable.display_message = displayMessageCb; vTable.display_warning = displayMessageCb; vTable.global_state_changed = globalStateChange; vTable.registration_state_changed = registrationStateChange; vTable.call_state_changed = callStateChange; vTable.call_encryption_changed = callEncryptionChange; vTable.text_received = text_received; vTable.new_subscription_request = new_subscription_request; vTable.notify_presence_recv = notify_presence_recv; listenerClass = (jclass)env->NewGlobalRef(env->GetObjectClass( alistener)); /*displayStatus(LinphoneCore lc,String message);*/ displayStatusId = env->GetMethodID(listenerClass,"displayStatus","(Lorg/linphone/core/LinphoneCore;Ljava/lang/String;)V"); /*void generalState(LinphoneCore lc,int state); */ globalStateId = env->GetMethodID(listenerClass,"globalState","(Lorg/linphone/core/LinphoneCore;Lorg/linphone/core/LinphoneCore$GlobalState;Ljava/lang/String;)V"); globalStateClass = (jclass)env->NewGlobalRef(env->FindClass("org/linphone/core/LinphoneCore$GlobalState")); globalStateFromIntId = env->GetStaticMethodID(globalStateClass,"fromInt","(I)Lorg/linphone/core/LinphoneCore$GlobalState;"); /*registrationState(LinphoneCore lc, LinphoneProxyConfig cfg, LinphoneCore.RegistrationState cstate, String smessage);*/ registrationStateId = env->GetMethodID(listenerClass,"registrationState","(Lorg/linphone/core/LinphoneCore;Lorg/linphone/core/LinphoneProxyConfig;Lorg/linphone/core/LinphoneCore$RegistrationState;Ljava/lang/String;)V"); registrationStateClass = (jclass)env->NewGlobalRef(env->FindClass("org/linphone/core/LinphoneCore$RegistrationState")); registrationStateFromIntId = env->GetStaticMethodID(registrationStateClass,"fromInt","(I)Lorg/linphone/core/LinphoneCore$RegistrationState;"); /*callState(LinphoneCore lc, LinphoneCall call, LinphoneCall.State cstate,String message);*/ callStateId = env->GetMethodID(listenerClass,"callState","(Lorg/linphone/core/LinphoneCore;Lorg/linphone/core/LinphoneCall;Lorg/linphone/core/LinphoneCall$State;Ljava/lang/String;)V"); callStateClass = (jclass)env->NewGlobalRef(env->FindClass("org/linphone/core/LinphoneCall$State")); callStateFromIntId = env->GetStaticMethodID(callStateClass,"fromInt","(I)Lorg/linphone/core/LinphoneCall$State;"); /*callEncryption(LinphoneCore lc, LinphoneCall call, boolean encrypted,String auth_token);*/ callEncryptionChangedId=env->GetMethodID(listenerClass,"callEncryptionChanged","(Lorg/linphone/core/LinphoneCore;Lorg/linphone/core/LinphoneCall;ZLjava/lang/String;)V"); /*void ecCalibrationStatus(LinphoneCore.EcCalibratorStatus status, int delay_ms, Object data);*/ ecCalibrationStatusId = env->GetMethodID(listenerClass,"ecCalibrationStatus","(Lorg/linphone/core/LinphoneCore;Lorg/linphone/core/LinphoneCore$EcCalibratorStatus;ILjava/lang/Object;)V"); ecCalibratorStatusClass = (jclass)env->NewGlobalRef(env->FindClass("org/linphone/core/LinphoneCore$EcCalibratorStatus")); ecCalibratorStatusFromIntId = env->GetStaticMethodID(ecCalibratorStatusClass,"fromInt","(I)Lorg/linphone/core/LinphoneCore$EcCalibratorStatus;"); /*void newSubscriptionRequest(LinphoneCore lc, LinphoneFriend lf, String url)*/ newSubscriptionRequestId = env->GetMethodID(listenerClass,"newSubscriptionRequest","(Lorg/linphone/core/LinphoneCore;Lorg/linphone/core/LinphoneFriend;Ljava/lang/String;)V"); /*void notifyPresenceReceived(LinphoneCore lc, LinphoneFriend lf);*/ notifyPresenceReceivedId = env->GetMethodID(listenerClass,"notifyPresenceReceived","(Lorg/linphone/core/LinphoneCore;Lorg/linphone/core/LinphoneFriend;)V"); /*void textReceived(LinphoneCore lc, LinphoneChatRoom cr,LinphoneAddress from,String message);*/ textReceivedId = env->GetMethodID(listenerClass,"textReceived","(Lorg/linphone/core/LinphoneCore;Lorg/linphone/core/LinphoneChatRoom;Lorg/linphone/core/LinphoneAddress;Ljava/lang/String;)V"); proxyClass = (jclass)env->NewGlobalRef(env->FindClass("org/linphone/core/LinphoneProxyConfigImpl")); proxyCtrId = env->GetMethodID(proxyClass,"<init>", "(J)V"); callClass = (jclass)env->NewGlobalRef(env->FindClass("org/linphone/core/LinphoneCallImpl")); callCtrId = env->GetMethodID(callClass,"<init>", "(J)V"); chatRoomClass = (jclass)env->NewGlobalRef(env->FindClass("org/linphone/core/LinphoneChatRoomImpl")); chatRoomCtrId = env->GetMethodID(chatRoomClass,"<init>", "(J)V"); friendClass = (jclass)env->NewGlobalRef(env->FindClass("org/linphone/core/LinphoneFriendImpl"));; friendCtrId =env->GetMethodID(friendClass,"<init>", "(J)V"); addressClass = (jclass)env->NewGlobalRef(env->FindClass("org/linphone/core/LinphoneAddressImpl")); addressCtrId =env->GetMethodID(addressClass,"<init>", "(J)V"); } ~LinphoneCoreData() { JNIEnv *env = 0; jvm->AttachCurrentThread(&env,NULL); env->DeleteGlobalRef(core); env->DeleteGlobalRef(listener); if (userdata) env->DeleteGlobalRef(userdata); env->DeleteGlobalRef(listenerClass); env->DeleteGlobalRef(globalStateClass); env->DeleteGlobalRef(registrationStateClass); env->DeleteGlobalRef(callStateClass); env->DeleteGlobalRef(proxyClass); env->DeleteGlobalRef(callClass); env->DeleteGlobalRef(chatRoomClass); env->DeleteGlobalRef(friendClass); } jobject core; jobject listener; jobject userdata; jclass listenerClass; jmethodID displayStatusId; jmethodID newSubscriptionRequestId; jmethodID notifyPresenceReceivedId; jmethodID textReceivedId; jclass globalStateClass; jmethodID globalStateId; jmethodID globalStateFromIntId; jclass registrationStateClass; jmethodID registrationStateId; jmethodID registrationStateFromIntId; jclass callStateClass; jmethodID callStateId; jmethodID callStateFromIntId; jmethodID callEncryptionChangedId; jclass ecCalibratorStatusClass; jmethodID ecCalibrationStatusId; jmethodID ecCalibratorStatusFromIntId; jclass proxyClass; jmethodID proxyCtrId; jclass callClass; jmethodID callCtrId; jclass chatRoomClass; jmethodID chatRoomCtrId; jclass friendClass; jmethodID friendCtrId; jclass addressClass; jmethodID addressCtrId; LinphoneCoreVTable vTable; static void showInterfaceCb(LinphoneCore *lc) { } static void byeReceivedCb(LinphoneCore *lc, const char *from) { } static void displayStatusCb(LinphoneCore *lc, const char *message) { JNIEnv *env = 0; jint result = jvm->AttachCurrentThread(&env,NULL); if (result != 0) { ms_error("cannot attach VM\n"); return; } LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data(lc); env->CallVoidMethod(lcData->listener,lcData->displayStatusId,lcData->core,env->NewStringUTF(message)); } static void displayMessageCb(LinphoneCore *lc, const char *message) { } static void authInfoRequested(LinphoneCore *lc, const char *realm, const char *username) { } static void globalStateChange(LinphoneCore *lc, LinphoneGlobalState gstate,const char* message) { JNIEnv *env = 0; jint result = jvm->AttachCurrentThread(&env,NULL); if (result != 0) { ms_error("cannot attach VM\n"); return; } LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data(lc); env->CallVoidMethod(lcData->listener ,lcData->globalStateId ,lcData->core ,env->CallStaticObjectMethod(lcData->globalStateClass,lcData->globalStateFromIntId,(jint)gstate), message ? env->NewStringUTF(message) : NULL); } static void registrationStateChange(LinphoneCore *lc, LinphoneProxyConfig* proxy,LinphoneRegistrationState state,const char* message) { JNIEnv *env = 0; jint result = jvm->AttachCurrentThread(&env,NULL); if (result != 0) { ms_error("cannot attach VM\n"); return; } LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data(lc); env->CallVoidMethod(lcData->listener ,lcData->registrationStateId ,lcData->core ,env->NewObject(lcData->proxyClass,lcData->proxyCtrId,(jlong)proxy) ,env->CallStaticObjectMethod(lcData->registrationStateClass,lcData->registrationStateFromIntId,(jint)state), message ? env->NewStringUTF(message) : NULL); } jobject getCall(JNIEnv *env , LinphoneCall *call){ jobject jobj=0; if (call!=NULL){ void *up=linphone_call_get_user_pointer(call); if (up==NULL){ jobj=env->NewObject(callClass,callCtrId,(jlong)call); jobj=env->NewGlobalRef(jobj); linphone_call_set_user_pointer(call,(void*)jobj); linphone_call_ref(call); }else{ jobj=(jobject)up; } } return jobj; } static void callStateChange(LinphoneCore *lc, LinphoneCall* call,LinphoneCallState state,const char* message) { JNIEnv *env = 0; jint result = jvm->AttachCurrentThread(&env,NULL); jobject jcall; if (result != 0) { ms_error("cannot attach VM\n"); return; } LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data(lc); env->CallVoidMethod(lcData->listener ,lcData->callStateId ,lcData->core ,(jcall=lcData->getCall(env,call)) ,env->CallStaticObjectMethod(lcData->callStateClass,lcData->callStateFromIntId,(jint)state), message ? env->NewStringUTF(message) : NULL); if (state==LinphoneCallReleased){ linphone_call_set_user_pointer(call,NULL); env->DeleteGlobalRef(jcall); } } static void callEncryptionChange(LinphoneCore *lc, LinphoneCall* call, bool_t encrypted,const char* authentication_token) { JNIEnv *env = 0; jint result = jvm->AttachCurrentThread(&env,NULL); if (result != 0) { ms_error("cannot attach VM\n"); return; } LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data(lc); env->CallVoidMethod(lcData->listener ,lcData->callEncryptionChangedId ,lcData->core ,lcData->getCall(env,call) ,encrypted ,authentication_token ? env->NewStringUTF(authentication_token) : NULL); } static void notify_presence_recv (LinphoneCore *lc, LinphoneFriend *my_friend) { JNIEnv *env = 0; jint result = jvm->AttachCurrentThread(&env,NULL); if (result != 0) { ms_error("cannot attach VM\n"); return; } LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data(lc); env->CallVoidMethod(lcData->listener ,lcData->notifyPresenceReceivedId ,lcData->core ,env->NewObject(lcData->friendClass,lcData->friendCtrId,(jlong)my_friend)); } static void new_subscription_request (LinphoneCore *lc, LinphoneFriend *my_friend, const char* url) { JNIEnv *env = 0; jint result = jvm->AttachCurrentThread(&env,NULL); if (result != 0) { ms_error("cannot attach VM\n"); return; } LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data(lc); env->CallVoidMethod(lcData->listener ,lcData->newSubscriptionRequestId ,lcData->core ,env->NewObject(lcData->friendClass,lcData->friendCtrId,(jlong)my_friend) ,url ? env->NewStringUTF(url) : NULL); } static void text_received(LinphoneCore *lc, LinphoneChatRoom *room, const LinphoneAddress *from, const char *message) { JNIEnv *env = 0; jint result = jvm->AttachCurrentThread(&env,NULL); if (result != 0) { ms_error("cannot attach VM\n"); return; } LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data(lc); env->CallVoidMethod(lcData->listener ,lcData->textReceivedId ,lcData->core ,env->NewObject(lcData->chatRoomClass,lcData->chatRoomCtrId,(jlong)room) ,env->NewObject(lcData->addressClass,lcData->addressCtrId,(jlong)from) ,message ? env->NewStringUTF(message) : NULL); } static void ecCalibrationStatus(LinphoneCore *lc, LinphoneEcCalibratorStatus status, int delay_ms, void *data) { JNIEnv *env = 0; jint result = jvm->AttachCurrentThread(&env,NULL); if (result != 0) { ms_error("cannot attach VM\n"); return; } LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data(lc); env->CallVoidMethod(lcData->listener ,lcData->ecCalibrationStatusId ,lcData->core ,env->CallStaticObjectMethod(lcData->ecCalibratorStatusClass,lcData->ecCalibratorStatusFromIntId,(jint)status) ,delay_ms ,data ? data : NULL); if (data != NULL &&status !=LinphoneEcCalibratorInProgress ) { //final state, releasing global ref env->DeleteGlobalRef((jobject)data); } } }; extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_newLinphoneCore(JNIEnv* env ,jobject thiz ,jobject jlistener ,jstring juserConfig ,jstring jfactoryConfig ,jobject juserdata){ const char* userConfig = juserConfig?env->GetStringUTFChars(juserConfig, NULL):NULL; const char* factoryConfig = jfactoryConfig?env->GetStringUTFChars(jfactoryConfig, NULL):NULL; LinphoneCoreData* ldata = new LinphoneCoreData(env,thiz,jlistener,juserdata); #ifdef HAVE_ILBC libmsilbc_init(); // requires an fpu #endif #ifdef HAVE_X264 libmsx264_init(); #endif #ifdef HAVE_AMR libmsamr_init(); #endif #ifdef HAVE_SILK libmssilk_init(); #endif #ifdef HAVE_G729 libmsbcg729_init(); #endif jlong nativePtr = (jlong)linphone_core_new( &ldata->vTable ,userConfig ,factoryConfig ,ldata); //clear auth info list linphone_core_clear_all_auth_info((LinphoneCore*) nativePtr); //clear existing proxy config linphone_core_clear_proxy_config((LinphoneCore*) nativePtr); if (userConfig) env->ReleaseStringUTFChars(juserConfig, userConfig); if (factoryConfig) env->ReleaseStringUTFChars(jfactoryConfig, factoryConfig); return nativePtr; } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_delete(JNIEnv* env ,jobject thiz ,jlong lc) { LinphoneCoreData* lcData = (LinphoneCoreData*)linphone_core_get_user_data((LinphoneCore*)lc); linphone_core_destroy((LinphoneCore*)lc); delete lcData; } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_clearProxyConfigs(JNIEnv* env, jobject thiz,jlong lc) { linphone_core_clear_proxy_config((LinphoneCore*)lc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setDefaultProxyConfig( JNIEnv* env ,jobject thiz ,jlong lc ,jlong pc) { linphone_core_set_default_proxy((LinphoneCore*)lc,(LinphoneProxyConfig*)pc); } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_getDefaultProxyConfig( JNIEnv* env ,jobject thiz ,jlong lc) { LinphoneProxyConfig *config=0; linphone_core_get_default_proxy((LinphoneCore*)lc,&config); return (jlong)config; } extern "C" jlongArray Java_org_linphone_core_LinphoneCoreImpl_getProxyConfigList(JNIEnv* env, jobject thiz, jlong lc) { const MSList* proxies = linphone_core_get_proxy_config_list((LinphoneCore*)lc); int proxyCount = ms_list_size(proxies); jlongArray jProxies = env->NewLongArray(proxyCount); jlong *jInternalArray = env->GetLongArrayElements(jProxies, NULL); for (int i = 0; i < proxyCount; i++ ) { jInternalArray[i] = (unsigned long) (proxies->data); proxies = proxies->next; } env->ReleaseLongArrayElements(jProxies, jInternalArray, 0); return jProxies; } extern "C" int Java_org_linphone_core_LinphoneCoreImpl_addProxyConfig( JNIEnv* env ,jobject thiz ,jobject jproxyCfg ,jlong lc ,jlong pc) { LinphoneProxyConfig* proxy = (LinphoneProxyConfig*)pc; linphone_proxy_config_set_user_data(proxy, env->NewGlobalRef(jproxyCfg)); return linphone_core_add_proxy_config((LinphoneCore*)lc,(LinphoneProxyConfig*)pc); } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_clearAuthInfos(JNIEnv* env, jobject thiz,jlong lc) { linphone_core_clear_all_auth_info((LinphoneCore*)lc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_addAuthInfo( JNIEnv* env ,jobject thiz ,jlong lc ,jlong pc) { linphone_core_add_auth_info((LinphoneCore*)lc,(LinphoneAuthInfo*)pc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_iterate( JNIEnv* env ,jobject thiz ,jlong lc) { linphone_core_iterate((LinphoneCore*)lc); } extern "C" jobject Java_org_linphone_core_LinphoneCoreImpl_invite( JNIEnv* env ,jobject thiz ,jlong lc ,jstring juri) { const char* uri = env->GetStringUTFChars(juri, NULL); LinphoneCoreData *lcd=(LinphoneCoreData*)linphone_core_get_user_data((LinphoneCore*)lc); LinphoneCall* lCall = linphone_core_invite((LinphoneCore*)lc,uri); env->ReleaseStringUTFChars(juri, uri); return lcd->getCall(env,lCall); } extern "C" jobject Java_org_linphone_core_LinphoneCoreImpl_inviteAddress( JNIEnv* env ,jobject thiz ,jlong lc ,jlong to) { LinphoneCoreData *lcd=(LinphoneCoreData*)linphone_core_get_user_data((LinphoneCore*)lc); return lcd->getCall(env, linphone_core_invite_address((LinphoneCore*)lc,(LinphoneAddress*)to)); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_terminateCall( JNIEnv* env ,jobject thiz ,jlong lc ,jlong call) { linphone_core_terminate_call((LinphoneCore*)lc,(LinphoneCall*)call); } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_getRemoteAddress( JNIEnv* env ,jobject thiz ,jlong lc) { return (jlong)linphone_core_get_current_call_remote_address((LinphoneCore*)lc); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_isInCall( JNIEnv* env ,jobject thiz ,jlong lc) { return linphone_core_in_call((LinphoneCore*)lc); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_isInComingInvitePending( JNIEnv* env ,jobject thiz ,jlong lc) { return linphone_core_inc_invite_pending((LinphoneCore*)lc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_acceptCall( JNIEnv* env ,jobject thiz ,jlong lc ,jlong call) { linphone_core_accept_call((LinphoneCore*)lc,(LinphoneCall*)call); } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_getCallLog( JNIEnv* env ,jobject thiz ,jlong lc ,jint position) { return (jlong)ms_list_nth_data(linphone_core_get_call_logs((LinphoneCore*)lc),position); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_getNumberOfCallLogs( JNIEnv* env ,jobject thiz ,jlong lc) { return ms_list_size(linphone_core_get_call_logs((LinphoneCore*)lc)); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setNetworkStateReachable( JNIEnv* env ,jobject thiz ,jlong lc ,jboolean isReachable) { linphone_core_set_network_reachable((LinphoneCore*)lc,isReachable); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setPlaybackGain( JNIEnv* env ,jobject thiz ,jlong lc ,jfloat gain) { linphone_core_set_playback_gain_db((LinphoneCore*)lc,gain); } extern "C" float Java_org_linphone_core_LinphoneCoreImpl_getPlaybackGain( JNIEnv* env ,jobject thiz ,jlong lc) { return linphone_core_get_playback_gain_db((LinphoneCore*)lc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_muteMic( JNIEnv* env ,jobject thiz ,jlong lc ,jboolean isMuted) { linphone_core_mute_mic((LinphoneCore*)lc,isMuted); } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_interpretUrl( JNIEnv* env ,jobject thiz ,jlong lc ,jstring jurl) { const char* url = env->GetStringUTFChars(jurl, NULL); jlong result = (jlong)linphone_core_interpret_url((LinphoneCore*)lc,url); env->ReleaseStringUTFChars(jurl, url); return result; } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_sendDtmf( JNIEnv* env ,jobject thiz ,jlong lc ,jchar dtmf) { linphone_core_send_dtmf((LinphoneCore*)lc,dtmf); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_playDtmf( JNIEnv* env ,jobject thiz ,jlong lc ,jchar dtmf ,jint duration) { linphone_core_play_dtmf((LinphoneCore*)lc,dtmf,duration); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_stopDtmf( JNIEnv* env ,jobject thiz ,jlong lc) { linphone_core_stop_dtmf((LinphoneCore*)lc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_clearCallLogs(JNIEnv* env ,jobject thiz ,jlong lc) { linphone_core_clear_call_logs((LinphoneCore*)lc); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_isMicMuted( JNIEnv* env ,jobject thiz ,jlong lc) { return linphone_core_is_mic_muted((LinphoneCore*)lc); } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_findPayloadType(JNIEnv* env ,jobject thiz ,jlong lc ,jstring jmime ,jint rate) { const char* mime = env->GetStringUTFChars(jmime, NULL); jlong result = (jlong)linphone_core_find_payload_type((LinphoneCore*)lc,mime,rate); env->ReleaseStringUTFChars(jmime, mime); return result; } extern "C" jlongArray Java_org_linphone_core_LinphoneCoreImpl_listVideoPayloadTypes(JNIEnv* env ,jobject thiz ,jlong lc) { const MSList* codecs = linphone_core_get_video_codecs((LinphoneCore*)lc); int codecsCount = ms_list_size(codecs); jlongArray jCodecs = env->NewLongArray(codecsCount); jlong *jInternalArray = env->GetLongArrayElements(jCodecs, NULL); for (int i = 0; i < codecsCount; i++ ) { jInternalArray[i] = (unsigned long) (codecs->data); codecs = codecs->next; } env->ReleaseLongArrayElements(jCodecs, jInternalArray, 0); return jCodecs; } extern "C" jlongArray Java_org_linphone_core_LinphoneCoreImpl_listAudioPayloadTypes(JNIEnv* env ,jobject thiz ,jlong lc) { const MSList* codecs = linphone_core_get_audio_codecs((LinphoneCore*)lc); int codecsCount = ms_list_size(codecs); jlongArray jCodecs = env->NewLongArray(codecsCount); jlong *jInternalArray = env->GetLongArrayElements(jCodecs, NULL); for (int i = 0; i < codecsCount; i++ ) { jInternalArray[i] = (unsigned long) (codecs->data); codecs = codecs->next; } env->ReleaseLongArrayElements(jCodecs, jInternalArray, 0); return jCodecs; } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_enablePayloadType(JNIEnv* env ,jobject thiz ,jlong lc ,jlong pt ,jboolean enable) { return linphone_core_enable_payload_type((LinphoneCore*)lc,(PayloadType*)pt,enable); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_enableEchoCancellation(JNIEnv* env ,jobject thiz ,jlong lc ,jboolean enable) { linphone_core_enable_echo_cancellation((LinphoneCore*)lc,enable); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_enableEchoLimiter(JNIEnv* env ,jobject thiz ,jlong lc ,jboolean enable) { linphone_core_enable_echo_limiter((LinphoneCore*)lc,enable); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_isEchoCancellationEnabled(JNIEnv* env ,jobject thiz ,jlong lc ) { return linphone_core_echo_cancellation_enabled((LinphoneCore*)lc); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_isEchoLimiterEnabled(JNIEnv* env ,jobject thiz ,jlong lc ) { return linphone_core_echo_limiter_enabled((LinphoneCore*)lc); } extern "C" jobject Java_org_linphone_core_LinphoneCoreImpl_getCurrentCall(JNIEnv* env ,jobject thiz ,jlong lc ) { LinphoneCoreData *lcdata=(LinphoneCoreData*)linphone_core_get_user_data((LinphoneCore*)lc); return lcdata->getCall(env,linphone_core_get_current_call((LinphoneCore*)lc)); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_addFriend(JNIEnv* env ,jobject thiz ,jlong lc ,jlong aFriend ) { linphone_core_add_friend((LinphoneCore*)lc,(LinphoneFriend*)aFriend); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setPresenceInfo(JNIEnv* env ,jobject thiz ,jlong lc ,jint minute_away ,jstring jalternative_contact ,jint status) { const char* alternative_contact = jalternative_contact?env->GetStringUTFChars(jalternative_contact, NULL):NULL; linphone_core_set_presence_info((LinphoneCore*)lc,minute_away,alternative_contact,(LinphoneOnlineStatus)status); if (alternative_contact) env->ReleaseStringUTFChars(jalternative_contact, alternative_contact); } extern "C" long Java_org_linphone_core_LinphoneCoreImpl_createChatRoom(JNIEnv* env ,jobject thiz ,jlong lc ,jstring jto) { const char* to = env->GetStringUTFChars(jto, NULL); LinphoneChatRoom* lResult = linphone_core_create_chat_room((LinphoneCore*)lc,to); env->ReleaseStringUTFChars(jto, to); return (long)lResult; } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_enableVideo(JNIEnv* env ,jobject thiz ,jlong lc ,jboolean vcap_enabled ,jboolean display_enabled) { linphone_core_enable_video((LinphoneCore*)lc, vcap_enabled,display_enabled); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_isVideoEnabled(JNIEnv* env ,jobject thiz ,jlong lc) { return linphone_core_video_enabled((LinphoneCore*)lc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setPlayFile(JNIEnv* env ,jobject thiz ,jlong lc ,jstring jpath) { const char* path = jpath?env->GetStringUTFChars(jpath, NULL):NULL; linphone_core_set_play_file((LinphoneCore*)lc,path); if (path) env->ReleaseStringUTFChars(jpath, path); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setRing(JNIEnv* env ,jobject thiz ,jlong lc ,jstring jpath) { const char* path = jpath?env->GetStringUTFChars(jpath, NULL):NULL; linphone_core_set_ring((LinphoneCore*)lc,path); if (path) env->ReleaseStringUTFChars(jpath, path); } extern "C" jstring Java_org_linphone_core_LinphoneCoreImpl_getRing(JNIEnv* env ,jobject thiz ,jlong lc ) { const char* path = linphone_core_get_ring((LinphoneCore*)lc); if (path) { return env->NewStringUTF(path); } else { return NULL; } } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setRootCA(JNIEnv* env ,jobject thiz ,jlong lc ,jstring jpath) { const char* path = jpath?env->GetStringUTFChars(jpath, NULL):NULL; linphone_core_set_root_ca((LinphoneCore*)lc,path); if (path) env->ReleaseStringUTFChars(jpath, path); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_enableKeepAlive(JNIEnv* env ,jobject thiz ,jlong lc ,jboolean enable) { linphone_core_enable_keep_alive((LinphoneCore*)lc,enable); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_isKeepAliveEnabled(JNIEnv* env ,jobject thiz ,jlong lc) { return linphone_core_keep_alive_enabled((LinphoneCore*)lc); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_startEchoCalibration(JNIEnv* env ,jobject thiz ,jlong lc ,jobject data) { return linphone_core_start_echo_calibration((LinphoneCore*)lc , LinphoneCoreData::ecCalibrationStatus , data?env->NewGlobalRef(data):NULL); } extern "C" int Java_org_linphone_core_LinphoneCoreImpl_getMediaEncryption(JNIEnv* env ,jobject thiz ,jlong lc ) { return (int)linphone_core_get_media_encryption((LinphoneCore*)lc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setMediaEncryption(JNIEnv* env ,jobject thiz ,jlong lc ,int menc) { linphone_core_set_media_encryption((LinphoneCore*)lc,(LinphoneMediaEncryption)menc); } extern "C" int Java_org_linphone_core_LinphoneCallParamsImpl_getMediaEncryption(JNIEnv* env ,jobject thiz ,jlong cp ) { return (int)linphone_call_params_get_media_encryption((LinphoneCallParams*)cp); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_mediaEncryptionSupported(JNIEnv* env ,jobject thiz ,jlong lc, jint menc ) { return linphone_core_media_encryption_supported((LinphoneCore*)lc,(LinphoneMediaEncryption)menc); } extern "C" void Java_org_linphone_core_LinphoneCallParamsImpl_setMediaEncryption(JNIEnv* env ,jobject thiz ,jlong cp ,int jmenc) { linphone_call_params_set_media_encryption((LinphoneCallParams*)cp,(LinphoneMediaEncryption)jmenc); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_getMediaEncryptionMandatory(JNIEnv* env ,jobject thiz ,jlong lc ) { return linphone_core_is_media_encryption_mandatory((LinphoneCore*)lc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setMediaEncryptionMandatory(JNIEnv* env ,jobject thiz ,jlong lc , jboolean yesno ) { linphone_core_set_media_encryption_mandatory((LinphoneCore*)lc, yesno); } //ProxyConfig extern "C" jlong Java_org_linphone_core_LinphoneProxyConfigImpl_newLinphoneProxyConfig(JNIEnv* env,jobject thiz) { LinphoneProxyConfig* proxy = linphone_proxy_config_new(); return (jlong) proxy; } extern "C" void Java_org_linphone_core_LinphoneProxyConfigImpl_delete(JNIEnv* env,jobject thiz,jlong ptr) { linphone_proxy_config_destroy((LinphoneProxyConfig*)ptr); } extern "C" void Java_org_linphone_core_LinphoneProxyConfigImpl_setIdentity(JNIEnv* env,jobject thiz,jlong proxyCfg,jstring jidentity) { const char* identity = env->GetStringUTFChars(jidentity, NULL); linphone_proxy_config_set_identity((LinphoneProxyConfig*)proxyCfg,identity); env->ReleaseStringUTFChars(jidentity, identity); } extern "C" jstring Java_org_linphone_core_LinphoneProxyConfigImpl_getIdentity(JNIEnv* env,jobject thiz,jlong proxyCfg) { const char* identity = linphone_proxy_config_get_identity((LinphoneProxyConfig*)proxyCfg); if (identity) { return env->NewStringUTF(identity); } else { return NULL; } } extern "C" int Java_org_linphone_core_LinphoneProxyConfigImpl_setProxy(JNIEnv* env,jobject thiz,jlong proxyCfg,jstring jproxy) { const char* proxy = env->GetStringUTFChars(jproxy, NULL); int err=linphone_proxy_config_set_server_addr((LinphoneProxyConfig*)proxyCfg,proxy); env->ReleaseStringUTFChars(jproxy, proxy); return err; } extern "C" jstring Java_org_linphone_core_LinphoneProxyConfigImpl_getProxy(JNIEnv* env,jobject thiz,jlong proxyCfg) { const char* proxy = linphone_proxy_config_get_addr((LinphoneProxyConfig*)proxyCfg); if (proxy) { return env->NewStringUTF(proxy); } else { return NULL; } } extern "C" int Java_org_linphone_core_LinphoneProxyConfigImpl_setRoute(JNIEnv* env,jobject thiz,jlong proxyCfg,jstring jroute) { if (jroute != NULL) { const char* route = env->GetStringUTFChars(jroute, NULL); int err=linphone_proxy_config_set_route((LinphoneProxyConfig*)proxyCfg,route); env->ReleaseStringUTFChars(jroute, route); return err; } else { return linphone_proxy_config_set_route((LinphoneProxyConfig*)proxyCfg,NULL); } } extern "C" jstring Java_org_linphone_core_LinphoneProxyConfigImpl_getRoute(JNIEnv* env,jobject thiz,jlong proxyCfg) { const char* route = linphone_proxy_config_get_route((LinphoneProxyConfig*)proxyCfg); if (route) { return env->NewStringUTF(route); } else { return NULL; } } extern "C" void Java_org_linphone_core_LinphoneProxyConfigImpl_enableRegister(JNIEnv* env,jobject thiz,jlong proxyCfg,jboolean enableRegister) { linphone_proxy_config_enable_register((LinphoneProxyConfig*)proxyCfg,enableRegister); } extern "C" jboolean Java_org_linphone_core_LinphoneProxyConfigImpl_isRegistered(JNIEnv* env,jobject thiz,jlong proxyCfg) { return linphone_proxy_config_is_registered((LinphoneProxyConfig*)proxyCfg); } extern "C" jboolean Java_org_linphone_core_LinphoneProxyConfigImpl_isRegisterEnabled(JNIEnv* env,jobject thiz,jlong proxyCfg) { return linphone_proxy_config_register_enabled((LinphoneProxyConfig*)proxyCfg); } extern "C" void Java_org_linphone_core_LinphoneProxyConfigImpl_edit(JNIEnv* env,jobject thiz,jlong proxyCfg) { linphone_proxy_config_edit((LinphoneProxyConfig*)proxyCfg); } extern "C" void Java_org_linphone_core_LinphoneProxyConfigImpl_done(JNIEnv* env,jobject thiz,jlong proxyCfg) { linphone_proxy_config_done((LinphoneProxyConfig*)proxyCfg); } extern "C" jstring Java_org_linphone_core_LinphoneProxyConfigImpl_normalizePhoneNumber(JNIEnv* env,jobject thiz,jlong proxyCfg,jstring jnumber) { if (jnumber == 0) { ms_error("cannot normalized null number"); } const char* number = env->GetStringUTFChars(jnumber, NULL); int len = env->GetStringLength(jnumber); if (len == 0) { ms_warning("cannot normalize empty number"); return jnumber; } char targetBuff[2*len];// returned number can be greater than origin (specially in case of prefix insertion linphone_proxy_config_normalize_number((LinphoneProxyConfig*)proxyCfg,number,targetBuff,sizeof(targetBuff)); jstring normalizedNumber = env->NewStringUTF(targetBuff); env->ReleaseStringUTFChars(jnumber, number); return normalizedNumber; } extern "C" jstring Java_org_linphone_core_LinphoneProxyConfigImpl_getDomain(JNIEnv* env ,jobject thiz ,jlong proxyCfg) { const char* domain = linphone_proxy_config_get_domain((LinphoneProxyConfig*)proxyCfg); if (domain) { return env->NewStringUTF(domain); } else { return NULL; } } extern "C" void Java_org_linphone_core_LinphoneProxyConfigImpl_setDialEscapePlus(JNIEnv* env,jobject thiz,jlong proxyCfg,jboolean value) { linphone_proxy_config_set_dial_escape_plus((LinphoneProxyConfig*)proxyCfg,value); } extern "C" void Java_org_linphone_core_LinphoneProxyConfigImpl_setDialPrefix(JNIEnv* env ,jobject thiz ,jlong proxyCfg ,jstring jprefix) { const char* prefix = env->GetStringUTFChars(jprefix, NULL); linphone_proxy_config_set_dial_prefix((LinphoneProxyConfig*)proxyCfg,prefix); env->ReleaseStringUTFChars(jprefix, prefix); } extern "C" void Java_org_linphone_core_LinphoneProxyConfigImpl_enablePublish(JNIEnv* env ,jobject thiz ,jlong proxyCfg ,jboolean val) { linphone_proxy_config_enable_publish((LinphoneProxyConfig*)proxyCfg,val); } extern "C" jboolean Java_org_linphone_core_LinphoneProxyConfigImpl_publishEnabled(JNIEnv* env,jobject thiz,jlong proxyCfg) { return linphone_proxy_config_publish_enabled((LinphoneProxyConfig*)proxyCfg); } //Auth Info extern "C" jlong Java_org_linphone_core_LinphoneAuthInfoImpl_newLinphoneAuthInfo(JNIEnv* env , jobject thiz , jstring jusername , jstring juserid , jstring jpassword , jstring jha1 , jstring jrealm) { const char* username = env->GetStringUTFChars(jusername, NULL); const char* password = env->GetStringUTFChars(jpassword, NULL); jlong auth = (jlong)linphone_auth_info_new(username,NULL,password,NULL,NULL); env->ReleaseStringUTFChars(jusername, username); env->ReleaseStringUTFChars(jpassword, password); return auth; } extern "C" void Java_org_linphone_core_LinphoneAuthInfoImpl_delete(JNIEnv* env , jobject thiz , jlong ptr) { linphone_auth_info_destroy((LinphoneAuthInfo*)ptr); } //LinphoneAddress extern "C" jlong Java_org_linphone_core_LinphoneAddressImpl_newLinphoneAddressImpl(JNIEnv* env ,jobject thiz ,jstring juri ,jstring jdisplayName) { const char* uri = env->GetStringUTFChars(juri, NULL); LinphoneAddress* address = linphone_address_new(uri); if (jdisplayName && address) { const char* displayName = env->GetStringUTFChars(jdisplayName, NULL); linphone_address_set_display_name(address,displayName); env->ReleaseStringUTFChars(jdisplayName, displayName); } env->ReleaseStringUTFChars(juri, uri); return (jlong) address; } extern "C" void Java_org_linphone_core_LinphoneAddressImpl_delete(JNIEnv* env ,jobject thiz ,jlong ptr) { linphone_address_destroy((LinphoneAddress*)ptr); } extern "C" jstring Java_org_linphone_core_LinphoneAddressImpl_getDisplayName(JNIEnv* env ,jobject thiz ,jlong ptr) { const char* displayName = linphone_address_get_display_name((LinphoneAddress*)ptr); if (displayName) { return env->NewStringUTF(displayName); } else { return 0; } } extern "C" jstring Java_org_linphone_core_LinphoneAddressImpl_getUserName(JNIEnv* env ,jobject thiz ,jlong ptr) { const char* userName = linphone_address_get_username((LinphoneAddress*)ptr); if (userName) { return env->NewStringUTF(userName); } else { return 0; } } extern "C" jstring Java_org_linphone_core_LinphoneAddressImpl_getDomain(JNIEnv* env ,jobject thiz ,jlong ptr) { const char* domain = linphone_address_get_domain((LinphoneAddress*)ptr); if (domain) { return env->NewStringUTF(domain); } else { return 0; } } extern "C" jstring Java_org_linphone_core_LinphoneAddressImpl_toString(JNIEnv* env ,jobject thiz ,jlong ptr) { char* uri = linphone_address_as_string((LinphoneAddress*)ptr); jstring juri =env->NewStringUTF(uri); ms_free(uri); return juri; } extern "C" jstring Java_org_linphone_core_LinphoneAddressImpl_toUri(JNIEnv* env ,jobject thiz ,jlong ptr) { char* uri = linphone_address_as_string_uri_only((LinphoneAddress*)ptr); jstring juri =env->NewStringUTF(uri); ms_free(uri); return juri; } extern "C" void Java_org_linphone_core_LinphoneAddressImpl_setDisplayName(JNIEnv* env ,jobject thiz ,jlong address ,jstring jdisplayName) { const char* displayName = jdisplayName!= NULL?env->GetStringUTFChars(jdisplayName, NULL):NULL; linphone_address_set_display_name((LinphoneAddress*)address,displayName); if (displayName != NULL) env->ReleaseStringUTFChars(jdisplayName, displayName); } //CallLog extern "C" jlong Java_org_linphone_core_LinphoneCallLogImpl_getFrom(JNIEnv* env ,jobject thiz ,jlong ptr) { return (jlong)((LinphoneCallLog*)ptr)->from; } extern "C" jlong Java_org_linphone_core_LinphoneCallLogImpl_getTo(JNIEnv* env ,jobject thiz ,jlong ptr) { return (jlong)((LinphoneCallLog*)ptr)->to; } extern "C" jboolean Java_org_linphone_core_LinphoneCallLogImpl_isIncoming(JNIEnv* env ,jobject thiz ,jlong ptr) { return ((LinphoneCallLog*)ptr)->dir==LinphoneCallIncoming?JNI_TRUE:JNI_FALSE; } /*payloadType*/ extern "C" jstring Java_org_linphone_core_PayloadTypeImpl_toString(JNIEnv* env,jobject thiz,jlong ptr) { PayloadType* pt = (PayloadType*)ptr; char* value = ms_strdup_printf("[%s] clock [%i], bitrate [%i]" ,payload_type_get_mime(pt) ,payload_type_get_rate(pt) ,payload_type_get_bitrate(pt)); jstring jvalue =env->NewStringUTF(value); ms_free(value); return jvalue; } extern "C" jstring Java_org_linphone_core_PayloadTypeImpl_getMime(JNIEnv* env,jobject thiz,jlong ptr) { PayloadType* pt = (PayloadType*)ptr; jstring jvalue =env->NewStringUTF(payload_type_get_mime(pt)); return jvalue; } extern "C" jint Java_org_linphone_core_PayloadTypeImpl_getRate(JNIEnv* env,jobject thiz, jlong ptr) { PayloadType* pt = (PayloadType*)ptr; return payload_type_get_rate(pt); } //LinphoneCall extern "C" void Java_org_linphone_core_LinphoneCallImpl_finalize(JNIEnv* env ,jobject thiz ,jlong ptr) { LinphoneCall *call=(LinphoneCall*)ptr; linphone_call_unref(call); } extern "C" jlong Java_org_linphone_core_LinphoneCallImpl_getCallLog( JNIEnv* env ,jobject thiz ,jlong ptr) { return (jlong)linphone_call_get_call_log((LinphoneCall*)ptr); } extern "C" jboolean Java_org_linphone_core_LinphoneCallImpl_isIncoming( JNIEnv* env ,jobject thiz ,jlong ptr) { return linphone_call_get_dir((LinphoneCall*)ptr)==LinphoneCallIncoming?JNI_TRUE:JNI_FALSE; } extern "C" jlong Java_org_linphone_core_LinphoneCallImpl_getRemoteAddress( JNIEnv* env ,jobject thiz ,jlong ptr) { return (jlong)linphone_call_get_remote_address((LinphoneCall*)ptr); } extern "C" jint Java_org_linphone_core_LinphoneCallImpl_getState( JNIEnv* env ,jobject thiz ,jlong ptr) { return (jint)linphone_call_get_state((LinphoneCall*)ptr); } extern "C" void Java_org_linphone_core_LinphoneCallImpl_enableEchoCancellation( JNIEnv* env ,jobject thiz ,jlong ptr ,jboolean value) { linphone_call_enable_echo_cancellation((LinphoneCall*)ptr,value); } extern "C" jboolean Java_org_linphone_core_LinphoneCallImpl_isEchoCancellationEnabled( JNIEnv* env ,jobject thiz ,jlong ptr) { return linphone_call_echo_cancellation_enabled((LinphoneCall*)ptr); } extern "C" void Java_org_linphone_core_LinphoneCallImpl_enableEchoLimiter( JNIEnv* env ,jobject thiz ,jlong ptr ,jboolean value) { linphone_call_enable_echo_limiter((LinphoneCall*)ptr,value); } extern "C" jboolean Java_org_linphone_core_LinphoneCallImpl_isEchoLimiterEnabled( JNIEnv* env ,jobject thiz ,jlong ptr) { return linphone_call_echo_limiter_enabled((LinphoneCall*)ptr); } extern "C" jobject Java_org_linphone_core_LinphoneCallImpl_getReplacedCall( JNIEnv* env ,jobject thiz ,jlong ptr) { LinphoneCoreData *lcd=(LinphoneCoreData*)linphone_core_get_user_data(linphone_call_get_core((LinphoneCall*)ptr)); return lcd->getCall(env,linphone_call_get_replaced_call((LinphoneCall*)ptr)); } extern "C" jfloat Java_org_linphone_core_LinphoneCallImpl_getCurrentQuality( JNIEnv* env ,jobject thiz ,jlong ptr) { return (jfloat)linphone_call_get_current_quality((LinphoneCall*)ptr); } extern "C" jfloat Java_org_linphone_core_LinphoneCallImpl_getAverageQuality( JNIEnv* env ,jobject thiz ,jlong ptr) { return (jfloat)linphone_call_get_average_quality((LinphoneCall*)ptr); } //LinphoneFriend extern "C" long Java_org_linphone_core_LinphoneFriendImpl_newLinphoneFriend(JNIEnv* env ,jobject thiz ,jstring jFriendUri) { LinphoneFriend* lResult; if (jFriendUri) { const char* friendUri = env->GetStringUTFChars(jFriendUri, NULL); lResult= linphone_friend_new_with_addr(friendUri); env->ReleaseStringUTFChars(jFriendUri, friendUri); } else { lResult = linphone_friend_new(); } return (long)lResult; } extern "C" void Java_org_linphone_core_LinphoneFriendImpl_setAddress(JNIEnv* env ,jobject thiz ,jlong ptr ,jlong linphoneAddress) { linphone_friend_set_addr((LinphoneFriend*)ptr,(LinphoneAddress*)linphoneAddress); } extern "C" long Java_org_linphone_core_LinphoneFriendImpl_getAddress(JNIEnv* env ,jobject thiz ,jlong ptr) { return (long)linphone_friend_get_address((LinphoneFriend*)ptr); } extern "C" void Java_org_linphone_core_LinphoneFriendImpl_setIncSubscribePolicy(JNIEnv* env ,jobject thiz ,jlong ptr ,jint policy) { linphone_friend_set_inc_subscribe_policy((LinphoneFriend*)ptr,(LinphoneSubscribePolicy)policy); } extern "C" jint Java_org_linphone_core_LinphoneFriendImpl_getIncSubscribePolicy(JNIEnv* env ,jobject thiz ,jlong ptr) { return linphone_friend_get_inc_subscribe_policy((LinphoneFriend*)ptr); } extern "C" void Java_org_linphone_core_LinphoneFriendImpl_enableSubscribes(JNIEnv* env ,jobject thiz ,jlong ptr ,jboolean value) { linphone_friend_enable_subscribes((LinphoneFriend*)ptr,value); } extern "C" jboolean Java_org_linphone_core_LinphoneFriendImpl_isSubscribesEnabled(JNIEnv* env ,jobject thiz ,jlong ptr) { return linphone_friend_subscribes_enabled((LinphoneFriend*)ptr); } extern "C" jboolean Java_org_linphone_core_LinphoneFriendImpl_getStatus(JNIEnv* env ,jobject thiz ,jlong ptr) { return linphone_friend_get_status((LinphoneFriend*)ptr); } extern "C" void Java_org_linphone_core_LinphoneFriendImpl_edit(JNIEnv* env ,jobject thiz ,jlong ptr) { return linphone_friend_edit((LinphoneFriend*)ptr); } extern "C" void Java_org_linphone_core_LinphoneFriendImpl_done(JNIEnv* env ,jobject thiz ,jlong ptr) { linphone_friend_done((LinphoneFriend*)ptr); } //LinphoneChatRoom extern "C" long Java_org_linphone_core_LinphoneChatRoomImpl_getPeerAddress(JNIEnv* env ,jobject thiz ,jlong ptr) { return (long) linphone_chat_room_get_peer_address((LinphoneChatRoom*)ptr); } extern "C" void Java_org_linphone_core_LinphoneChatRoomImpl_sendMessage(JNIEnv* env ,jobject thiz ,jlong ptr ,jstring jmessage) { const char* message = env->GetStringUTFChars(jmessage, NULL); linphone_chat_room_send_message((LinphoneChatRoom*)ptr,message); env->ReleaseStringUTFChars(jmessage, message); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setVideoWindowId(JNIEnv* env ,jobject thiz ,jlong lc ,jobject obj) { jobject oldWindow = (jobject) linphone_core_get_native_video_window_id((LinphoneCore*)lc); if (oldWindow != NULL) { env->DeleteGlobalRef(oldWindow); } if (obj != NULL) { obj = env->NewGlobalRef(obj); } linphone_core_set_native_video_window_id((LinphoneCore*)lc,(unsigned long)obj); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setPreviewWindowId(JNIEnv* env ,jobject thiz ,jlong lc ,jobject obj) { jobject oldWindow = (jobject) linphone_core_get_native_preview_window_id((LinphoneCore*)lc); if (oldWindow != NULL) { env->DeleteGlobalRef(oldWindow); } if (obj != NULL) { obj = env->NewGlobalRef(obj); } linphone_core_set_native_preview_window_id((LinphoneCore*)lc,(unsigned long)obj); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setDeviceRotation(JNIEnv* env ,jobject thiz ,jlong lc ,jint rotation) { linphone_core_set_device_rotation((LinphoneCore*)lc,rotation); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setFirewallPolicy(JNIEnv *env, jobject thiz, jlong lc, int enum_value){ linphone_core_set_firewall_policy((LinphoneCore*)lc,(LinphoneFirewallPolicy)enum_value); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_getFirewallPolicy(JNIEnv *env, jobject thiz, jlong lc){ return linphone_core_get_firewall_policy((LinphoneCore*)lc); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setStunServer(JNIEnv *env, jobject thiz, jlong lc, jstring jserver){ const char* server = NULL; if (jserver) server=env->GetStringUTFChars(jserver, NULL); linphone_core_set_stun_server((LinphoneCore*)lc,server); if (server) env->ReleaseStringUTFChars(jserver,server); } extern "C" jstring Java_org_linphone_core_LinphoneCoreImpl_getStunServer(JNIEnv *env, jobject thiz, jlong lc){ const char *ret= linphone_core_get_stun_server((LinphoneCore*)lc); if (ret==NULL) return NULL; jstring jvalue =env->NewStringUTF(ret); return jvalue; } extern "C" void Java_org_linphone_core_LinphoneCallParamsImpl_audioBandwidth(JNIEnv *env, jobject thiz, jlong lcp, jint bw){ linphone_call_params_set_audio_bandwidth_limit((LinphoneCallParams*)lcp, bw); } extern "C" void Java_org_linphone_core_LinphoneCallParamsImpl_enableVideo(JNIEnv *env, jobject thiz, jlong lcp, jboolean b){ linphone_call_params_enable_video((LinphoneCallParams*)lcp, b); } extern "C" jboolean Java_org_linphone_core_LinphoneCallParamsImpl_getVideoEnabled(JNIEnv *env, jobject thiz, jlong lcp){ return linphone_call_params_video_enabled((LinphoneCallParams*)lcp); } extern "C" jboolean Java_org_linphone_core_LinphoneCallParamsImpl_localConferenceMode(JNIEnv *env, jobject thiz, jlong lcp){ return linphone_call_params_local_conference_mode((LinphoneCallParams*)lcp); } extern "C" void Java_org_linphone_core_LinphoneCallParamsImpl_destroy(JNIEnv *env, jobject thiz, jlong lc){ return linphone_call_params_destroy((LinphoneCallParams*)lc); } extern "C" jlong Java_org_linphone_core_LinphoneCoreImpl_createDefaultCallParams(JNIEnv *env, jobject thiz, jlong lc){ return (jlong) linphone_core_create_default_call_parameters((LinphoneCore*)lc); } extern "C" jlong Java_org_linphone_core_LinphoneCallImpl_getCurrentParamsCopy(JNIEnv *env, jobject thiz, jlong lc){ return (jlong) linphone_call_params_copy(linphone_call_get_current_params((LinphoneCall*)lc)); } extern "C" jlong Java_org_linphone_core_LinphoneCallImpl_enableCamera(JNIEnv *env, jobject thiz, jlong lc, jboolean b){ linphone_call_enable_camera((LinphoneCall *)lc, (bool_t) b); } extern "C" jboolean Java_org_linphone_core_LinphoneCallImpl_cameraEnabled(JNIEnv *env, jobject thiz, jlong lc){ linphone_call_camera_enabled((LinphoneCall *)lc); } extern "C" jobject Java_org_linphone_core_LinphoneCoreImpl_inviteAddressWithParams(JNIEnv *env, jobject thiz, jlong lc, jlong addr, jlong params){ LinphoneCoreData *lcd=(LinphoneCoreData*)linphone_core_get_user_data((LinphoneCore*)lc); return lcd->getCall(env,linphone_core_invite_address_with_params((LinphoneCore *)lc, (const LinphoneAddress *)addr, (const LinphoneCallParams *)params)); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_updateAddressWithParams(JNIEnv *env, jobject thiz, jlong lc, jlong call, jlong params){ return (jint) linphone_core_update_call((LinphoneCore *)lc, (LinphoneCall *)call, (LinphoneCallParams *)params); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_updateCall(JNIEnv *env, jobject thiz, jlong lc, jlong call, jlong params){ return (jint) linphone_core_update_call((LinphoneCore *)lc, (LinphoneCall *)call, (const LinphoneCallParams *)params); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setPreferredVideoSize(JNIEnv *env, jobject thiz, jlong lc, jint width, jint height){ MSVideoSize vsize; vsize.width = (int)width; vsize.height = (int)height; linphone_core_set_preferred_video_size((LinphoneCore *)lc, vsize); } extern "C" jintArray Java_org_linphone_core_LinphoneCoreImpl_getPreferredVideoSize(JNIEnv *env, jobject thiz, jlong lc){ MSVideoSize vsize = linphone_core_get_preferred_video_size((LinphoneCore *)lc); jintArray arr = env->NewIntArray(2); int tVsize [2]= {vsize.width,vsize.height}; env->SetIntArrayRegion(arr, 0, 2, tVsize); return arr; } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setDownloadBandwidth(JNIEnv *env, jobject thiz, jlong lc, jint bw){ linphone_core_set_download_bandwidth((LinphoneCore *)lc, (int) bw); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setUploadBandwidth(JNIEnv *env, jobject thiz, jlong lc, jint bw){ linphone_core_set_upload_bandwidth((LinphoneCore *)lc, (int) bw); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setDownloadPtime(JNIEnv *env, jobject thiz, jlong lc, jint ptime){ linphone_core_set_download_ptime((LinphoneCore *)lc, (int) ptime); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setUploadPtime(JNIEnv *env, jobject thiz, jlong lc, jint ptime){ linphone_core_set_upload_ptime((LinphoneCore *)lc, (int) ptime); } extern "C" int Java_org_linphone_core_LinphoneProxyConfigImpl_getState(JNIEnv* env,jobject thiz,jlong ptr) { return (int) linphone_proxy_config_get_state((const LinphoneProxyConfig *) ptr); } extern "C" void Java_org_linphone_core_LinphoneProxyConfigImpl_setExpires(JNIEnv* env,jobject thiz,jlong ptr,jint delay) { linphone_proxy_config_expires((LinphoneProxyConfig *) ptr, (int) delay); } extern "C" jint Java_org_linphone_core_LinphoneCallImpl_getDuration(JNIEnv* env,jobject thiz,jlong ptr) { linphone_call_get_duration((LinphoneCall *) ptr); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_getSignalingTransportPort(JNIEnv* env,jobject thiz,jlong ptr, jint code) { LCSipTransports tr; linphone_core_get_sip_transports((LinphoneCore *) ptr, &tr); switch (code) { case 0: return tr.udp_port; case 1: return tr.tcp_port; case 3: return tr.tls_port; default: return -2; } } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setSignalingTransportPorts(JNIEnv* env,jobject thiz,jlong ptr,jint udp, jint tcp, jint tls) { LinphoneCore *lc = (LinphoneCore *) ptr; LCSipTransports tr; tr.udp_port = udp; tr.tcp_port = tcp; tr.tls_port = tls; linphone_core_set_sip_transports(lc, &tr); // tr will be copied } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_enableIpv6(JNIEnv* env,jobject thiz ,jlong lc, jboolean enable) { linphone_core_enable_ipv6((LinphoneCore*)lc,enable); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_adjustSoftwareVolume(JNIEnv* env,jobject thiz ,jlong ptr, jint db) { linphone_core_set_playback_gain_db((LinphoneCore *) ptr, db); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_pauseCall(JNIEnv *env,jobject thiz,jlong pCore, jlong pCall) { return linphone_core_pause_call((LinphoneCore *) pCore, (LinphoneCall *) pCall); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_pauseAllCalls(JNIEnv *env,jobject thiz,jlong pCore) { return linphone_core_pause_all_calls((LinphoneCore *) pCore); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_resumeCall(JNIEnv *env,jobject thiz,jlong pCore, jlong pCall) { return linphone_core_resume_call((LinphoneCore *) pCore, (LinphoneCall *) pCall); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_isInConference(JNIEnv *env,jobject thiz,jlong pCore) { return linphone_core_is_in_conference((LinphoneCore *) pCore); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_enterConference(JNIEnv *env,jobject thiz,jlong pCore) { return 0 == linphone_core_enter_conference((LinphoneCore *) pCore); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_leaveConference(JNIEnv *env,jobject thiz,jlong pCore) { linphone_core_leave_conference((LinphoneCore *) pCore); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_addAllToConference(JNIEnv *env,jobject thiz,jlong pCore) { linphone_core_add_all_to_conference((LinphoneCore *) pCore); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_addToConference(JNIEnv *env,jobject thiz,jlong pCore, jlong pCall) { linphone_core_add_to_conference((LinphoneCore *) pCore, (LinphoneCall *) pCall); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_removeFromConference(JNIEnv *env,jobject thiz,jlong pCore, jlong pCall) { linphone_core_remove_from_conference((LinphoneCore *) pCore, (LinphoneCall *) pCall); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_terminateConference(JNIEnv *env,jobject thiz,jlong pCore) { linphone_core_terminate_conference((LinphoneCore *) pCore); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_getConferenceSize(JNIEnv *env,jobject thiz,jlong pCore) { return linphone_core_get_conference_size((LinphoneCore *) pCore); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_terminateAllCalls(JNIEnv *env,jobject thiz,jlong pCore) { linphone_core_terminate_all_calls((LinphoneCore *) pCore); } extern "C" jobject Java_org_linphone_core_LinphoneCoreImpl_getCall(JNIEnv *env,jobject thiz,jlong pCore,jint position) { LinphoneCoreData *lcd=(LinphoneCoreData*)linphone_core_get_user_data((LinphoneCore*)pCore); LinphoneCall* lCall = (LinphoneCall*) ms_list_nth_data(linphone_core_get_calls((LinphoneCore *) pCore),position); return lcd->getCall(env,lCall); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_getCallsNb(JNIEnv *env,jobject thiz,jlong pCore) { return ms_list_size(linphone_core_get_calls((LinphoneCore *) pCore)); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_transferCall(JNIEnv *env,jobject thiz,jlong pCore, jlong pCall, jstring jReferTo) { const char* cReferTo=env->GetStringUTFChars(jReferTo, NULL); linphone_core_transfer_call((LinphoneCore *) pCore, (LinphoneCall *) pCall, cReferTo); env->ReleaseStringUTFChars(jReferTo, cReferTo); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_transferCallToAnother(JNIEnv *env,jobject thiz,jlong pCore, jlong pCall, jlong pDestCall) { linphone_core_transfer_call_to_another((LinphoneCore *) pCore, (LinphoneCall *) pCall, (LinphoneCall *) pDestCall); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setZrtpSecretsCache(JNIEnv *env,jobject thiz,jlong pCore, jstring jFile) { if (jFile) { const char* cFile=env->GetStringUTFChars(jFile, NULL); linphone_core_set_zrtp_secrets_file((LinphoneCore *) pCore,cFile); env->ReleaseStringUTFChars(jFile, cFile); } else { linphone_core_set_zrtp_secrets_file((LinphoneCore *) pCore,NULL); } } extern "C" jobject Java_org_linphone_core_LinphoneCoreImpl_findCallFromUri(JNIEnv *env,jobject thiz,jlong pCore, jstring jUri) { const char* cUri=env->GetStringUTFChars(jUri, NULL); LinphoneCall *call= (LinphoneCall *) linphone_core_find_call_from_uri((LinphoneCore *) pCore,cUri); env->ReleaseStringUTFChars(jUri, cUri); LinphoneCoreData *lcdata=(LinphoneCoreData*)linphone_core_get_user_data((LinphoneCore*)pCore); return (jobject) lcdata->getCall(env,call); } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_setVideoDevice(JNIEnv *env,jobject thiz,jlong pCore,jint id) { LinphoneCore* lc = (LinphoneCore *) pCore; const char** devices = linphone_core_get_video_devices(lc); if (devices == NULL) { ms_error("No existing video devices\n"); return -1; } int i; for(i=0; i<=id; i++) { if (devices[i] == NULL) break; ms_message("Existing device %d : %s\n", i, devices[i]); if (i==id) { return linphone_core_set_video_device(lc, devices[i]); } } return -1; } extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_getVideoDevice(JNIEnv *env,jobject thiz,jlong pCore) { LinphoneCore* lc = (LinphoneCore *) pCore; const char** devices = linphone_core_get_video_devices(lc); if (devices == NULL) { ms_error("No existing video devices\n"); return -1; } const char* cam = linphone_core_get_video_device(lc); if (cam == NULL) { ms_error("No current video device\n"); } else { int i=0; while(devices[i] != NULL) { if (strcmp(devices[i], cam) == 0) return i; i++; } } ms_warning("Returning default (0) device\n"); return 0; } extern "C" jstring Java_org_linphone_core_LinphoneCallImpl_getAuthenticationToken(JNIEnv* env,jobject thiz,jlong ptr) { LinphoneCall *call = (LinphoneCall *) ptr; const char* token = linphone_call_get_authentication_token(call); if (token == NULL) return NULL; return env->NewStringUTF(token); } extern "C" jboolean Java_org_linphone_core_LinphoneCallImpl_isAuthenticationTokenVerified(JNIEnv* env,jobject thiz,jlong ptr) { LinphoneCall *call = (LinphoneCall *) ptr; return linphone_call_get_authentication_token_verified(call); } extern "C" void Java_org_linphone_core_LinphoneCallImpl_setAuthenticationTokenVerified(JNIEnv* env,jobject thiz,jlong ptr,jboolean verified) { LinphoneCall *call = (LinphoneCall *) ptr; linphone_call_set_authentication_token_verified(call, verified); } extern "C" jfloat Java_org_linphone_core_LinphoneCallImpl_getPlayVolume(JNIEnv* env, jobject thiz, jlong ptr) { LinphoneCall *call = (LinphoneCall *) ptr; return linphone_call_get_play_volume(call); } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_soundResourcesLocked(JNIEnv* env,jobject thiz,jlong ptr){ return linphone_core_sound_resources_locked((LinphoneCore *) ptr); } // Needed by Galaxy S (can't switch to/from speaker while playing and still keep mic working) // Implemented directly in msandroid.cpp (sound filters for Android). extern "C" void msandroid_hack_speaker_state(bool speakerOn); extern "C" void Java_org_linphone_LinphoneManager_hackSpeakerState(JNIEnv* env,jobject thiz,jboolean speakerOn){ msandroid_hack_speaker_state(speakerOn); } // End Galaxy S hack functions extern "C" jint Java_org_linphone_core_LinphoneCoreImpl_getMaxCalls(JNIEnv *env,jobject thiz,jlong pCore) { return (jint) linphone_core_get_max_calls((LinphoneCore *) pCore); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_setMaxCalls(JNIEnv *env,jobject thiz,jlong pCore, jint max) { linphone_core_set_max_calls((LinphoneCore *) pCore, (int) max); } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_tunnelAddServerAndMirror(JNIEnv *env,jobject thiz,jlong pCore, jstring jHost, jint port, jint mirror, jint delay) { #ifdef TUNNEL_ENABLED LinphoneTunnel *tunnel=((LinphoneCore *) pCore)->tunnel; if (!tunnel) return; const char* cHost=env->GetStringUTFChars(jHost, NULL); linphone_tunnel_add_server_and_mirror(tunnel, cHost, port, mirror, delay); env->ReleaseStringUTFChars(jHost, cHost); #endif } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_tunnelAutoDetect(JNIEnv *env,jobject thiz,jlong pCore) { #ifdef TUNNEL_ENABLED LinphoneTunnel *tunnel=((LinphoneCore *) pCore)->tunnel; if (!tunnel) return; linphone_tunnel_auto_detect(tunnel); #endif } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_tunnelCleanServers(JNIEnv *env,jobject thiz,jlong pCore) { #ifdef TUNNEL_ENABLED LinphoneTunnel *tunnel=((LinphoneCore *) pCore)->tunnel; if (!tunnel) return; linphone_tunnel_clean_servers(tunnel); #endif } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_tunnelEnable(JNIEnv *env,jobject thiz,jlong pCore, jboolean enable) { #ifdef TUNNEL_ENABLED LinphoneTunnel *tunnel=((LinphoneCore *) pCore)->tunnel; if (!tunnel) return; linphone_tunnel_enable(tunnel, enable); #endif } extern "C" void Java_org_linphone_core_LinphoneCoreImpl_tunnelEnableLogs(JNIEnv *env,jobject thiz,jlong pCore, jboolean enable) { #ifdef TUNNEL_ENABLED LinphoneTunnel *tunnel=((LinphoneCore *) pCore)->tunnel; if (!tunnel) return; linphone_tunnel_enable_logs(tunnel, enable); #endif } extern "C" jboolean Java_org_linphone_core_LinphoneCoreImpl_isTunnelAvailable(JNIEnv *env,jobject thiz){ return linphone_core_tunnel_available(); }
39.441777
221
0.749779
doyaGu
e61fb7b2d1a457280a1a01460af170753b30afe6
323
hpp
C++
src/Time/StepControllers/Factory.hpp
macedo22/spectre
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
[ "MIT" ]
117
2017-04-08T22:52:48.000Z
2022-03-25T07:23:36.000Z
src/Time/StepControllers/Factory.hpp
GitHimanshuc/spectre
4de4033ba36547113293fe4dbdd77591485a4aee
[ "MIT" ]
3,177
2017-04-07T21:10:18.000Z
2022-03-31T23:55:59.000Z
src/Time/StepControllers/Factory.hpp
geoffrey4444/spectre
9350d61830b360e2d5b273fdd176dcc841dbefb0
[ "MIT" ]
85
2017-04-07T19:36:13.000Z
2022-03-01T10:21:00.000Z
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include "Time/StepControllers/BinaryFraction.hpp" #include "Utilities/TMPL.hpp" namespace StepControllers { /// Typelist of standard StepControllers using standard_step_controllers = tmpl::list<BinaryFraction>; } // namespace Triggers
24.846154
61
0.786378
macedo22
e6279c8736443f7a57545a58a85e0ea38cb142db
2,756
cpp
C++
procedures/p9/start_host.cpp
devenrao/openpower-proc-control
1dc3acd254df36670e978ad2fc4af13d7ce84bcb
[ "Apache-2.0" ]
1
2020-04-22T17:21:10.000Z
2020-04-22T17:21:10.000Z
procedures/p9/start_host.cpp
devenrao/openpower-proc-control
1dc3acd254df36670e978ad2fc4af13d7ce84bcb
[ "Apache-2.0" ]
5
2017-06-30T10:14:12.000Z
2021-11-28T19:42:41.000Z
procedures/p9/start_host.cpp
devenrao/openpower-proc-control
1dc3acd254df36670e978ad2fc4af13d7ce84bcb
[ "Apache-2.0" ]
7
2017-03-24T22:33:51.000Z
2022-01-20T05:31:29.000Z
/** * Copyright (C) 2017 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "cfam_access.hpp" #include "ext_interface.hpp" #include "p9_cfam.hpp" #include "registration.hpp" #include "targeting.hpp" #include <phosphor-logging/log.hpp> namespace openpower { namespace p9 { using namespace phosphor::logging; using namespace openpower::cfam::access; using namespace openpower::cfam::p9; using namespace openpower::targeting; /** * @brief Starts the self boot engine on P9 position 0 to kick off a boot. * @return void */ void startHost() { Targeting targets; const auto& master = *(targets.begin()); log<level::INFO>("Running P9 procedure startHost", entry("NUM_PROCS=%d", targets.size())); // Ensure asynchronous clock mode is set writeReg(master, P9_LL_MODE_REG, 0x00000001); // Clock mux select override for (const auto& t : targets) { writeRegWithMask(t, P9_ROOT_CTRL8, 0x0000000C, 0x0000000C); } // Enable P9 checkstop to be reported to the BMC // Setup FSI2PIB to report checkstop writeReg(master, P9_FSI_A_SI1S, 0x20000000); // Enable Xstop/ATTN interrupt writeReg(master, P9_FSI2PIB_TRUE_MASK, 0x60000000); // Arm it writeReg(master, P9_FSI2PIB_INTERRUPT, 0xFFFFFFFF); // Kick off the SBE to start the boot // Choose seeprom side to boot from cfam_data_t sbeSide = 0; if (getBootCount() > 0) { sbeSide = 0; log<level::INFO>("Setting SBE seeprom side to 0", entry("SBE_SIDE_SELECT=%d", 0)); } else { sbeSide = 0x00004000; log<level::INFO>("Setting SBE seeprom side to 1", entry("SBE_SIDE_SELECT=%d", 1)); } // Bit 17 of the ctrl status reg indicates sbe seeprom boot side // 0 -> Side 0, 1 -> Side 1 writeRegWithMask(master, P9_SBE_CTRL_STATUS, sbeSide, 0x00004000); // Ensure SBE start bit is 0 to handle warm reboot scenarios writeRegWithMask(master, P9_CBS_CS, 0x00000000, 0x80000000); // Start the SBE writeRegWithMask(master, P9_CBS_CS, 0x80000000, 0x80000000); } REGISTER_PROCEDURE("startHost", startHost) } // namespace p9 } // namespace openpower
28.412371
75
0.678882
devenrao
e62e24ff2c8aa962e2d1d0a9b8ad0ad284d9d26d
23,246
hh
C++
src/buffer.hh
everard/libecstk-buffer
bfc24012f6ece148a3bdb6f21765c7b3fd6e938f
[ "BSL-1.0" ]
null
null
null
src/buffer.hh
everard/libecstk-buffer
bfc24012f6ece148a3bdb6f21765c7b3fd6e938f
[ "BSL-1.0" ]
null
null
null
src/buffer.hh
everard/libecstk-buffer
bfc24012f6ece148a3bdb6f21765c7b3fd6e938f
[ "BSL-1.0" ]
null
null
null
// Copyright Nezametdinov E. Ildus 2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) // #ifndef H_639425CCA60E448B9BEB43186E06CA57 #define H_639425CCA60E448B9BEB43186E06CA57 #include <type_traits> #include <algorithm> #include <array> #include <climits> #include <cstddef> #include <cstdint> #include <limits> #include <ranges> #include <span> #include <concepts> #include <utility> #include <tuple> namespace ecstk { namespace std = ::std; //////////////////////////////////////////////////////////////////////////////// // Utility types. //////////////////////////////////////////////////////////////////////////////// using std::size_t; //////////////////////////////////////////////////////////////////////////////// // Compile-time addition of values of unsigned type. Generates compilation error // on wrap-around. //////////////////////////////////////////////////////////////////////////////// namespace detail { template <std::unsigned_integral T, T X, T Y, T... Rest> constexpr auto static_add() noexcept -> T requires(static_cast<T>(X + Y) >= Y) { if constexpr(sizeof...(Rest) == 0) { return (X + Y); } else { return static_add<T, static_cast<T>(X + Y), Rest...>(); } } } // namespace detail template <size_t X, size_t Y, size_t... Rest> constexpr auto static_sum = detail::static_add<size_t, X, Y, Rest...>(); //////////////////////////////////////////////////////////////////////////////// // Forward declaration of buffer storage types and buffer interface. //////////////////////////////////////////////////////////////////////////////// template <size_t N, typename T, typename Tag> struct buffer_storage_normal; template <size_t N, typename T, typename Tag> struct buffer_storage_secure; template <size_t N, typename T, typename Tag> struct buffer_storage_ref; template <typename Storage> struct buffer_impl; //////////////////////////////////////////////////////////////////////////////// // Buffer concepts. //////////////////////////////////////////////////////////////////////////////// template <typename T> concept static_buffer = std::ranges::sized_range<T> && (std::derived_from< T, buffer_impl<buffer_storage_normal< T::static_size(), typename T::value_type, typename T::tag>>> || std::derived_from< T, buffer_impl<buffer_storage_secure< T::static_size(), typename T::value_type, typename T::tag>>> || std::derived_from< T, buffer_impl<buffer_storage_ref< T::static_size(), typename T::value_type, typename T::tag>>>); // clang-format off template <typename T> concept static_byte_buffer = static_buffer<T> && std::same_as< std::remove_cv_t<std::ranges::range_value_t<T>>, unsigned char>; template <typename R> concept byte_range = std::ranges::sized_range<R> && std::same_as< std::remove_cv_t<std::ranges::range_value_t<R>>, unsigned char>; // clang-format on //////////////////////////////////////////////////////////////////////////////// // Utility functions. //////////////////////////////////////////////////////////////////////////////// namespace detail { // Checks value types of the given buffer types. Returns true if all buffer // types share the same value type, and false otherwise. template <static_buffer Buffer0, static_buffer Buffer1, static_buffer... Buffers> constexpr auto check_homogeneity() noexcept -> bool { auto f = std::same_as<std::remove_cv_t<typename Buffer0::value_type>, std::remove_cv_t<typename Buffer1::value_type>>; if constexpr(sizeof...(Buffers) == 0) { return f; } else { return f && check_homogeneity<Buffer0, Buffers...>(); } } // Checks for possible buffer overflow when trying to fit a buffer of type // {Buffer0} into a buffer of type {Buffer1} starting from the given {Offset}. template <size_t Offset, static_buffer Buffer0, static_buffer Buffer1> constexpr auto check_buffer_overflow() noexcept -> bool { auto same_value_type = std::same_as<std::remove_cv_t<typename Buffer0::value_type>, std::remove_cv_t<typename Buffer1::value_type>>; auto no_overflow = (static_sum<Offset, Buffer0::static_size()> <= Buffer1::static_size()); return (same_value_type && no_overflow); } // Computes the size of the joint buffer. template <static_buffer Buffer, static_buffer... Buffers> constexpr auto compute_joint_buffer_size() noexcept -> size_t { if constexpr(sizeof...(Buffers) == 0) { return Buffer::static_size(); } else { return static_sum<Buffer::static_size(), compute_joint_buffer_size<Buffers...>()>; } } } // namespace detail template <static_buffer Buffer0, static_buffer Buffer1, static_buffer... Buffers> constexpr auto are_homogeneous_buffers = detail::check_homogeneity<Buffer0, Buffer1, Buffers...>(); template <size_t Offset, static_buffer Buffer0, static_buffer Buffer1> constexpr auto no_buffer_overflow = detail::check_buffer_overflow<Offset, Buffer0, Buffer1>(); template <static_buffer Buffer, static_buffer... Buffers> constexpr auto joint_buffer_size = detail::compute_joint_buffer_size<Buffer, Buffers...>(); //////////////////////////////////////////////////////////////////////////////// // Buffer tag types. //////////////////////////////////////////////////////////////////////////////// struct default_buffer_tag {}; template <typename T> struct wrapped_buffer_tag {}; template <static_buffer Buffer, static_buffer... Buffers> using joint_buffer_tag = std::conditional_t< (sizeof...(Buffers) == 0), typename Buffer::tag, std::tuple<wrapped_buffer_tag<typename Buffer::tag>, wrapped_buffer_tag<typename Buffers::tag>...>>; //////////////////////////////////////////////////////////////////////////////// // Byte sequences. //////////////////////////////////////////////////////////////////////////////// // Mutable sequence. using mut_byte_sequence = std::span<unsigned char>; // Immutable sequence. using byte_sequence = std::span<unsigned char const>; //////////////////////////////////////////////////////////////////////////////// // Buffer types. //////////////////////////////////////////////////////////////////////////////// // Main specializations. template <size_t N, typename T = unsigned char, typename Tag = default_buffer_tag> using buffer = buffer_impl<buffer_storage_normal<N, T, Tag>>; template <size_t N, typename T = unsigned char, typename Tag = default_buffer_tag> using secure_buf = buffer_impl<buffer_storage_secure<N, T, Tag>>; template <size_t N, typename T = unsigned char, typename Tag = default_buffer_tag> using buffer_ref = buffer_impl<buffer_storage_ref<N, T, Tag>>; // Joint buffer types. template <static_buffer Buffer, static_buffer... Buffers> using joint_buffer = buffer<joint_buffer_size<Buffer, Buffers...>, std::remove_cv_t<typename Buffer::value_type>, joint_buffer_tag<Buffer, Buffers...>>; template <static_buffer Buffer, static_buffer... Buffers> using joint_buffer_secure = secure_buf<joint_buffer_size<Buffer, Buffers...>, std::remove_cv_t<typename Buffer::value_type>, joint_buffer_tag<Buffer, Buffers...>>; //////////////////////////////////////////////////////////////////////////////// // Buffer reference types. //////////////////////////////////////////////////////////////////////////////// template <static_buffer T> using mut_ref = buffer_ref<T::static_size(), typename T::value_type, typename T::tag>; template <static_buffer T> using ref = buffer_ref<T::static_size(), typename T::value_type const, typename T::tag>; namespace detail { template <static_buffer Buffer_src, static_buffer Buffer_dst> using select_ref = std::conditional_t<std::is_const_v<Buffer_src> || std::is_const_v<typename Buffer_src::value_type>, ref<Buffer_dst>, mut_ref<Buffer_dst>>; } // namespace detail //////////////////////////////////////////////////////////////////////////////// // Buffer implementation. //////////////////////////////////////////////////////////////////////////////// template <size_t Offset, static_buffer Buffer_src, static_buffer Buffer_dst0, static_buffer... Buffers_dst> constexpr auto is_valid_buffer_operation = (are_homogeneous_buffers<Buffer_src, Buffer_dst0, Buffers_dst...> && no_buffer_overflow<Offset, joint_buffer<Buffer_dst0, Buffers_dst...>, Buffer_src>); template <static_buffer... Buffers> constexpr auto are_valid_extraction_target = (!std::derived_from<Buffers, buffer_storage_ref<Buffers::static_size(), typename Buffers::value_type, typename Buffers::tag>> && ...); template <size_t Offset, static_buffer Buffer_src, static_buffer Buffer_dst0, static_buffer... Buffers_dst> constexpr auto is_valid_extract_operation = (is_valid_buffer_operation<Offset, Buffer_src, Buffer_dst0, Buffers_dst...> && are_valid_extraction_target<Buffer_dst0, Buffers_dst...>); template <typename Storage> struct buffer_impl : Storage { using value_type = typename Storage::value_type; using tag = typename Storage::tag; using mut_ref = buffer_ref<Storage::static_size, value_type, tag>; using ref = buffer_ref<Storage::static_size, value_type const, tag>; static constexpr auto is_noexcept = std::is_nothrow_copy_constructible_v<value_type>; constexpr auto begin() noexcept { return data(); } constexpr auto begin() const noexcept { return data(); } constexpr auto end() noexcept { return data() + static_size(); } constexpr auto end() const noexcept { return data() + static_size(); } static constexpr auto size() noexcept -> size_t { return Storage::static_size; } static constexpr auto static_size() noexcept -> size_t { return Storage::static_size; } constexpr auto& operator[](size_t i) noexcept { return data()[i]; } constexpr auto& operator[](size_t i) const noexcept { return data()[i]; } constexpr auto data() noexcept { return this->data_; } constexpr auto data() const noexcept { return static_cast<std::add_const_t<value_type>*>(this->data_); } template <size_t Offset, static_buffer Buffer, static_buffer... Buffers> constexpr void copy_into(Buffer& x, Buffers&... rest) const noexcept(is_noexcept) requires( is_valid_buffer_operation<Offset, buffer_impl, Buffer, Buffers...>) { copy_into_<Offset>(x, rest...); } template <static_buffer Buffer, static_buffer... Buffers> constexpr void copy_into(Buffer& x, Buffers&... rest) const noexcept(is_noexcept) requires( is_valid_buffer_operation<0, buffer_impl, Buffer, Buffers...>) { copy_into<0>(x, rest...); } template <size_t Offset, static_buffer Buffer, static_buffer... Buffers> constexpr auto& fill_from(Buffer const& x, Buffers const&... rest) noexcept( is_noexcept) requires(is_valid_buffer_operation<Offset, buffer_impl, Buffer, Buffers...>) { return fill_from_<Offset>(x, rest...); } template <static_buffer Buffer, static_buffer... Buffers> constexpr auto& fill_from(Buffer const& x, Buffers const&... rest) noexcept( is_noexcept) requires(is_valid_buffer_operation<0, buffer_impl, Buffer, Buffers...>) { return fill_from<0>(x, rest...); } template <size_t Offset, static_buffer Buffer, static_buffer... Buffers> constexpr auto extract() const noexcept(is_noexcept) -> decltype(auto) requires( is_valid_extract_operation<Offset, buffer_impl, Buffer, Buffers...>) { if constexpr(sizeof...(Buffers) == 0) { auto r = Buffer{}; copy_into_<Offset>(r); return r; } else { auto r = std::tuple<Buffer, Buffers...>{}; extract_tuple_<Offset, 0>(r); return r; } } template <static_buffer Buffer, static_buffer... Buffers> constexpr auto extract() const noexcept(is_noexcept) -> decltype(auto) requires( is_valid_extract_operation<0, buffer_impl, Buffer, Buffers...>) { return extract<0, Buffer, Buffers...>(); } template <size_t Offset, static_buffer Buffer, static_buffer... Buffers> constexpr auto view_as() noexcept -> decltype(auto) requires( is_valid_buffer_operation<Offset, buffer_impl, Buffer, Buffers...>) { return view_as_<Offset, buffer_impl, Buffer, Buffers...>(*this); } template <size_t Offset, static_buffer Buffer, static_buffer... Buffers> constexpr auto view_as() const noexcept -> decltype(auto) requires( is_valid_buffer_operation<Offset, buffer_impl, Buffer, Buffers...>) { return view_as_<Offset, buffer_impl const, Buffer, Buffers...>(*this); } template <static_buffer Buffer, static_buffer... Buffers> constexpr auto view_as() noexcept -> decltype(auto) requires( is_valid_buffer_operation<0, buffer_impl, Buffer, Buffers...>) { return view_as<0, Buffer, Buffers...>(); } template <static_buffer Buffer, static_buffer... Buffers> constexpr auto view_as() const noexcept -> decltype(auto) requires( is_valid_buffer_operation<0, buffer_impl, Buffer, Buffers...>) { return view_as<0, Buffer, Buffers...>(); } operator mut_ref() noexcept { return mut_ref{data()}; } operator ref() const noexcept { return ref{data()}; } private: template <size_t Offset, typename Buffer, typename... Buffers> constexpr void copy_into_(Buffer& x, Buffers&... rest) const noexcept(is_noexcept) { std::copy_n(data() + Offset, x.static_size(), x.data()); if constexpr(sizeof...(Buffers) != 0) { copy_into_<Offset + Buffer::static_size()>(rest...); } } template <size_t Offset, typename Buffer, typename... Buffers> constexpr auto& fill_from_(Buffer const& x, Buffers const&... rest) noexcept(is_noexcept) { std::copy_n(x.data(), x.static_size(), data() + Offset); if constexpr(sizeof...(Buffers) != 0) { fill_from_<Offset + Buffer::static_size()>(rest...); } return *this; } template <size_t Offset, typename Buffer_src, typename Buffer_dst0, typename... Buffers_dst> static constexpr auto view_as_(Buffer_src& self) noexcept -> decltype(auto) { if constexpr(sizeof...(Buffers_dst) == 0) { return detail::select_ref<Buffer_src, Buffer_dst0>{self.data() + Offset}; } else { auto r = std::tuple<detail::select_ref<Buffer_src, Buffer_dst0>, detail::select_ref<Buffer_src, Buffers_dst>...>{}; view_as_tuple_<Offset, 0>(self, r); return r; } } template <size_t Offset, size_t I, typename Tuple> constexpr void extract_tuple_(Tuple& t) const noexcept(is_noexcept) { copy_into_<Offset>(std::get<I>(t)); if constexpr((I + 1) < std::tuple_size_v<Tuple>) { extract_tuple_< Offset + std::tuple_element_t<I, Tuple>::static_size(), I + 1>( t); } } template <size_t Offset, size_t I, typename Buffer, typename Tuple> static constexpr void view_as_tuple_(Buffer& self, Tuple& t) noexcept { std::get<I>(t).data_ = self.data() + Offset; if constexpr((I + 1) < std::tuple_size_v<Tuple>) { view_as_tuple_< Offset + std::tuple_element_t<I, Tuple>::static_size(), I + 1>( self, t); } } template <typename T> friend struct buffer_impl; }; //////////////////////////////////////////////////////////////////////////////// // Buffer comparison. //////////////////////////////////////////////////////////////////////////////// template <static_buffer Buffer0, static_buffer Buffer1> constexpr auto is_valid_buffer_comparison = (std::same_as<typename Buffer0::value_type, typename Buffer1::value_type> && std::same_as<typename Buffer0::tag, typename Buffer1::tag> && std::totally_ordered<typename Buffer0::value_type> && (Buffer0::static_size() == Buffer1::static_size())); template <static_buffer Buffer0, static_buffer Buffer1> constexpr auto operator<(Buffer0 const& x, Buffer1 const& y) noexcept -> bool requires(is_valid_buffer_comparison<Buffer0, Buffer1>) { return std::ranges::lexicographical_compare(x, y); } template <static_buffer Buffer0, static_buffer Buffer1> constexpr auto operator>(Buffer0 const& x, Buffer1 const& y) noexcept -> bool requires(is_valid_buffer_comparison<Buffer0, Buffer1>) { return std::ranges::lexicographical_compare(y, x); } template <static_buffer Buffer0, static_buffer Buffer1> constexpr auto operator<=(Buffer0 const& x, Buffer1 const& y) noexcept -> bool requires(is_valid_buffer_comparison<Buffer0, Buffer1>) { return !(x > y); } template <static_buffer Buffer0, static_buffer Buffer1> constexpr auto operator>=(Buffer0 const& x, Buffer1 const& y) noexcept -> bool requires(is_valid_buffer_comparison<Buffer0, Buffer1>) { return !(x < y); } template <static_buffer Buffer0, static_buffer Buffer1> constexpr auto operator==(Buffer0 const& x, Buffer1 const& y) noexcept -> bool requires(is_valid_buffer_comparison<Buffer0, Buffer1>) { return std::ranges::equal(x, y); } template <static_buffer Buffer0, static_buffer Buffer1> constexpr auto operator!=(Buffer0 const& x, Buffer1 const& y) noexcept -> bool requires(is_valid_buffer_comparison<Buffer0, Buffer1>) { return !(x == y); } //////////////////////////////////////////////////////////////////////////////// // Buffer storage types. //////////////////////////////////////////////////////////////////////////////// template <size_t N, typename T, typename Tag> struct buffer_storage_normal { static constexpr size_t static_size = N; using value_type = T; using tag = Tag; T data_[N]; }; template <typename T, typename Tag> struct buffer_storage_normal<0, T, Tag> { static constexpr size_t static_size = 0; using value_type = T; using tag = Tag; static constexpr auto data_ = static_cast<value_type*>(nullptr); }; template <size_t N, typename T, typename Tag> struct buffer_storage_secure { static constexpr size_t static_size = N; using value_type = T; using tag = Tag; ~buffer_storage_secure() { auto volatile ptr = data_; std::fill_n(ptr, N, T{}); } T data_[N]; }; template <typename T, typename Tag> struct buffer_storage_secure<0, T, Tag> { static constexpr size_t static_size = 0; using value_type = T; using tag = Tag; static constexpr auto data_ = static_cast<value_type*>(nullptr); }; template <size_t N, typename T, typename Tag> struct buffer_storage_ref { static constexpr size_t static_size = N; using value_type = T; using tag = Tag; protected: buffer_storage_ref() noexcept : data_{} { } buffer_storage_ref(T* x) noexcept : data_{x} { } template <typename Storage> friend struct buffer_impl; T* data_; }; //////////////////////////////////////////////////////////////////////////////// // Buffer viewing and joining. //////////////////////////////////////////////////////////////////////////////// template <size_t Chunk_size, static_buffer Buffer> constexpr auto view_buffer_by_chunks(Buffer& x) noexcept -> decltype(auto) requires((Buffer::static_size() % Chunk_size) == 0) { using view = detail::select_ref< Buffer, buffer<Chunk_size, typename Buffer::value_type, typename Buffer::tag>>; return ([&x]<size_t... Indices>(std::index_sequence<Indices...>) { return buffer<sizeof...(Indices), view>{ x.template view_as<Indices * Chunk_size, view>()...}; })(std::make_index_sequence<Buffer::static_size() / Chunk_size>{}); } template <static_buffer Buffer, static_buffer... Buffers> constexpr auto join_buffers(Buffer const& x, Buffers const&... rest) noexcept(Buffer::is_noexcept) -> decltype(auto) { auto r = joint_buffer<Buffer, Buffers...>{}; r.fill_from(x, rest...); return r; } template <static_buffer Buffer, static_buffer... Buffers> constexpr auto join_buffers_secure(Buffer const& x, Buffers const&... rest) noexcept(Buffer::is_noexcept) -> decltype(auto) { auto r = joint_buffer_secure<Buffer, Buffers...>{}; r.fill_from(x, rest...); return r; } //////////////////////////////////////////////////////////////////////////////// // Buffer conversion. //////////////////////////////////////////////////////////////////////////////// namespace detail { template <typename T> concept integer = std::integral<T> && !std::same_as<std::remove_cv_t<T>, bool>; } // namespace detail template <detail::integer T> constexpr auto integer_size = static_sum< ((std::numeric_limits<std::make_unsigned_t<T>>::digits / CHAR_BIT)), ((std::numeric_limits<std::make_unsigned_t<T>>::digits % CHAR_BIT) != 0)>; template <detail::integer T, static_byte_buffer Buffer> constexpr auto is_valid_buffer_conversion = // (Buffer::static_size() == integer_size<T>); template <detail::integer T, static_byte_buffer Buffer> constexpr void int_to_buffer(T x, Buffer& buf) noexcept requires(is_valid_buffer_conversion<T, Buffer>) { for(size_t i = 0; i < integer_size<T>; ++i) { buf[i] = static_cast<unsigned char>( static_cast<std::make_unsigned_t<T>>(x) >> (i * CHAR_BIT)); } } template <detail::integer T> constexpr auto int_to_buffer(T x) noexcept -> decltype(auto) { buffer<integer_size<T>> r; int_to_buffer(x, r); return r; } template <detail::integer T, static_byte_buffer Buffer> constexpr void buffer_to_int(Buffer const& buf, T& x) noexcept requires(is_valid_buffer_conversion<T, Buffer>) { using unsigned_type = std::make_unsigned_t<T>; auto r = unsigned_type{}; for(size_t i = 0; i < integer_size<T>; ++i) { r |= static_cast<unsigned_type>(buf[i]) << (i * CHAR_BIT); } x = static_cast<T>(r); } template <detail::integer T, static_byte_buffer Buffer> constexpr auto buffer_to_int(Buffer const& buf) noexcept -> T requires(is_valid_buffer_conversion<T, Buffer>) { T r; return buffer_to_int(buf, r), r; } } // namespace ecstk #endif // H_639425CCA60E448B9BEB43186E06CA57
32.557423
80
0.5992
everard
e62ee9e181a93fb397260670761fcfae4f0e9098
1,001
hh
C++
extern/typed-geometry/src/typed-geometry/functions/matrix/translation.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
extern/typed-geometry/src/typed-geometry/functions/matrix/translation.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
extern/typed-geometry/src/typed-geometry/functions/matrix/translation.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
#pragma once #include <typed-geometry/types/mat.hh> #include <typed-geometry/types/vec.hh> #include <typed-geometry/detail/scalar_traits.hh> namespace tg { template <int D, class T> [[nodiscard]] constexpr mat<D + 1, D + 1, T> translation(vec<D, T> const& v) { auto m = mat<D + 1, D + 1, T>::identity; m[D] = vec<D + 1, T>(v, T(1)); return m; } template <int D, class T> [[nodiscard]] constexpr mat<D + 1, D + 1, T> translation(pos<D, T> const& v) { auto m = mat<D + 1, D + 1, T>::identity; m[D] = vec<D + 1, T>(vec<D, T>(v), T(1)); return m; } template <class T, class = enable_if<is_scalar<T>>> [[nodiscard]] constexpr mat<3, 3, T> translation(T x, T y) { auto m = mat<3, 3, T>::identity; m[2] = vec<3, T>(x, y, T(1)); return m; } template <class T, class = enable_if<is_scalar<T>>> [[nodiscard]] constexpr mat<4, 4, T> translation(T x, T y, T z) { auto m = mat<4, 4, T>::identity; m[3] = vec<4, T>(x, y, z, T(1)); return m; } } // namespace tg
23.833333
76
0.578422
rovedit
e635aca950b1081dfe827536399f5dbbd1340138
4,691
cpp
C++
src/lib_cpp/AvTrajectoryPlanner.cpp
joshuajbennett/av-trajectory-planner
522e5193c6aeeeba1ebaca3d43e26bdd21c56340
[ "MIT" ]
6
2019-10-13T23:32:59.000Z
2022-03-13T17:36:42.000Z
src/lib_cpp/AvTrajectoryPlanner.cpp
joshuajbennett/av-trajectory-planner
522e5193c6aeeeba1ebaca3d43e26bdd21c56340
[ "MIT" ]
null
null
null
src/lib_cpp/AvTrajectoryPlanner.cpp
joshuajbennett/av-trajectory-planner
522e5193c6aeeeba1ebaca3d43e26bdd21c56340
[ "MIT" ]
6
2019-04-07T02:29:47.000Z
2021-12-09T02:14:28.000Z
#include <fstream> #include <iostream> #include "AvTrajectoryPlanner.hpp" #include "IterativeLQR.hpp" using namespace av_structs; using namespace iterative_lqr; namespace av_trajectory_planner { Planner::Planner() {} Planner::Planner( AvState init, AvState goal, AvParams config, Boundary av_outline, SolverParams solver_settings) : initial_state {init} , goal_state {goal} , vehicle_config {config} , vehicle_outline {av_outline} , settings {solver_settings} { if(settings.constrain_velocity) { std::cout << "Velocity clamping enabled." << std::endl; } if(settings.constrain_steering_angle) { std::cout << "Steering angle clamping enabled." << std::endl; } } Planner::~Planner() {} void Planner::setGoal(AvState goal) { goal_state = goal; } AvState Planner::getGoal() { return goal_state; } void Planner::setInitialState(AvState init) { initial_state = init; } AvState Planner::getInitialState() { return initial_state; } void Planner::setVehicleConfig(AvParams config) { vehicle_config = config; } void Planner::setVehicleOutline(Boundary av_outline) { vehicle_outline = av_outline; } void Planner::clearObstacles() { obstacles.resize(0); } void Planner::appendObstacleTrajectory(ObstacleTrajectory obs_trajectory) { obstacles.push_back(std::move(obs_trajectory)); } void Planner::appendObstacleStatic(ObstacleStatic obs_static) { ObstacleTrajectory static_traj; static_traj.outline = obs_static.outline; static_traj.table.push_back(obs_static.obs_pose); static_traj.table.push_back(obs_static.obs_pose); static_traj.dt = settings.max_time; obstacles.push_back(std::move(static_traj)); } std::vector<ObstacleTrajectory> Planner::getObstacleTrajectories() { return obstacles; } void Planner::setSolverMaxTime(double max_time) { settings.max_time = max_time; } void Planner::setSolverTimeStep(double dt) { settings.solver_dt = dt; } void Planner::setSolverEpsilon(double epsilon) { settings.epsilon_suboptimality = epsilon; } void Planner::setSolverMaxIterations(unsigned int max_iter) { settings.max_iterations = max_iter; } void Planner::enableVelocityConstraint() { settings.constrain_velocity = true; } void Planner::disableVelocityConstraint() { settings.constrain_velocity = false; } void Planner::enableSteeringConstraint() { settings.constrain_steering_angle = true; } void Planner::disableSteeringConstraint() { settings.constrain_steering_angle = false; } void Planner::loadFromJson(std::string raw_json) { Json::Value root; Json::Reader reader; bool parsingSuccessful = reader.parse(raw_json, root); if(!parsingSuccessful) { // report to the user the failure and their locations in the document. std::cout << "Failed to parse configuration\n" << reader.getFormattedErrorMessages(); return; } initial_state.loadFromJson(root["initial_state"]); goal_state.loadFromJson(root["goal_state"]); vehicle_config.loadFromJson(root["vehicle_config"]); vehicle_outline.loadFromJson(root["vehicle_outline"]); obstacles.resize(0); for(auto obstacle : root["obstacles"]) { ObstacleTrajectory temp_obstacle; temp_obstacle.loadFromJson(obstacle); obstacles.push_back(temp_obstacle); } settings.loadFromJson(root["settings"]); } std::string Planner::saveToJson() { Json::Value root; root["initial_state"] = initial_state.saveToJson(); root["goal_state"] = goal_state.saveToJson(); root["vehicle_config"] = vehicle_config.saveToJson(); root["vehicle_outline"] = vehicle_outline.saveToJson(); Json::Value obstacle_list; for(auto obstacle : obstacles) { obstacle_list.append(obstacle.saveToJson()); } root["obstacles"] = obstacle_list; root["settings"] = settings.saveToJson(); Json::StyledWriter writer; return writer.write(root); } AvTrajectory Planner::solveTrajectory() { IterativeLQR ilqr = IterativeLQR(initial_state, goal_state, vehicle_config, vehicle_outline, settings); return std::move(ilqr.solveTrajectory()); } AvState Planner::dynamics(AvState input, AvAction action) { AvState output; output.x = input.vel_f * cos(input.delta_f) * cos(input.psi); output.y = input.vel_f * cos(input.delta_f) * sin(input.psi); output.psi = input.vel_f * sin(input.delta_f); output.delta_f = action.turn_rate; output.vel_f = action.accel_f; return (std::move(output)); } AvState Planner::apply_dynamics(AvState input, AvState current_dynamics, double dt) { AvState output; output = input + current_dynamics * dt; return (std::move(output)); } AvState Planner::euler_step_unforced(AvState input, double dt) { AvState current_dynamics = dynamics(input, AvAction {0.0, 0.0}); return (std::move(apply_dynamics(input, current_dynamics, dt))); } } // namespace av_trajectory_planner
22.882927
96
0.762737
joshuajbennett
e63bee55ed587adeac07ed6bfe9ee359b3fad55a
1,495
cpp
C++
cpp/src/exercise/e0200/e0134.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
cpp/src/exercise/e0200/e0134.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
cpp/src/exercise/e0200/e0134.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
// https://leetcode-cn.com/problems/gas-station/ #include "extern.h" class S0134 { public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { if (gas.empty()) return -1; for (int i = 0; i < gas.size(); ++i) { gas[i] -= cost[i]; } int total = 0; int cnt = 0, result = 0, start_idx = -1; bool in_cnt = false; for (int i = 0; i < gas.size() * 2; ++i) { int v = gas[i % gas.size()]; if (!in_cnt && v >= 0) { in_cnt = true; total = v; cnt = 1; start_idx = i % gas.size(); } else if (in_cnt) { if (total + v < 0) { in_cnt = false; result = max(result, cnt); if (result >= gas.size()) return start_idx; } else { ++cnt; total += v; } } } result = max(result, cnt); if (result >= gas.size()) return start_idx; else return -1; } }; TEST(e0200, e0134) { vector<int> gas, cost; gas = str_to_vec<int>("[1,2,3,4,5]"); cost = str_to_vec<int>("[3,4,5,1,2]"); ASSERT_EQ(S0134().canCompleteCircuit(gas, cost), 3); gas = str_to_vec<int>("[2,3,4]"); cost = str_to_vec<int>("[3,4,3]"); ASSERT_EQ(S0134().canCompleteCircuit(gas, cost), -1); }
28.75
65
0.419398
ajz34
e63fd302503fcab3eb0a026adde5c4098535f023
4,239
hpp
C++
include/vop.hpp
zhu48/led_strip
f74f0663cbf5a8b68a54f54ce04691c45e03253b
[ "MIT" ]
null
null
null
include/vop.hpp
zhu48/led_strip
f74f0663cbf5a8b68a54f54ce04691c45e03253b
[ "MIT" ]
null
null
null
include/vop.hpp
zhu48/led_strip
f74f0663cbf5a8b68a54f54ce04691c45e03253b
[ "MIT" ]
null
null
null
#ifndef VOP_HPP #define VOP_HPP #include <cstddef> namespace vop { /** * Vector add two containers, putting the result into a third container. * * \tparam itr_l Iterator type of the left-hand-side addition operand container. * \tparam itr_r Iterator type of the right-hand-side addition operand container. * \tparam itr_sum Iterator type of the addition result container. * * \param sum Iterator into the addition result container. * \param l Iterator into the left-hand-side addition operand container. * \param r Iterator into the right-hand-side addition operand container. * \param leng Number of elements to perform vector addition over. */ template<typename itr_l, typename itr_r, typename itr_sum> constexpr void sum( itr_sum sum, itr_l l, itr_r r, std::size_t leng ); /** * Take the vector minimum of two containers, putting the result into a third container. * * \tparam itr_l Iterator type of the left-hand-side minimization operand container. * \tparam itr_r Iterator type of the right-hand-side minimization operand container. * \tparam itr_min Iterator type of the minimization result container. * * \param min Iterator into the minimization result container. * \param l Iterator into the left-hand-side minimization operand container. * \param r Iterator into the right-hand-side minimization operand container. * \param leng Number of elements to perform vector minimization over. */ template<typename itr_l, typename itr_r, typename itr_min> constexpr void min( itr_min min, itr_l l, itr_r r, std::size_t leng ); /** * Vector multiply a range by a scaler value. * * \tparam itr Iterator type of the range to multiply. * \tparam scale_type Type of the scaler to multiply by. * * \param begin Iterator to the beginning of the range. * \param end Iterator to one-past-the-end of the range. * \param s The scaler to multiply by. */ template<typename itr, typename scale_type> constexpr void mult( itr begin, itr end, scale_type s ); /** * Take evenly-spaced samples from a range, and put the result into another range. * * \tparam stride The sample spacing. * \tparam itr Iterator type of the range to sample. * \tparam output_itr Iterator type of the range to store samples to. * * \param out_begin Iterator to the beginning of the range to write samples to. * \param begin Iterator to the beginning of the range to take samples of. * \param end Iterator to one-past-the-end of the range to take samples of. * * \return Returns an iterator to the next position in the output range. */ template<std::size_t stride, typename itr, typename output_itr> constexpr output_itr sample( output_itr out_begin, itr begin, itr end ); /** * Take evenly-spaced samples through a range of indices. * * Take evenly-spaced samples of the indices into a values range. For each sampled index, write * the value in the values range at that index into the results range. * * \tparam stride The sample spacing. * \tparam idx_itr Iterator type of the range containing index-type objects. * \tparam val_itr Iterator type of the range containing the values to sample. * \tparam output_itr Iterator type of the results range. * * \param out_begin Iterator to the beginning of the results range. * \param idx_begin Iterator to the beginning of the index-containing range. * \param idx_end Iterator to one-past-the-end of the index-containing range. * \param values_begin Iterator to the beginning of the values range. * * \return Returns an iterator to the next position in the output range. */ template<std::size_t stride, typename idx_itr, typename val_itr, typename output_itr> constexpr output_itr sample_by_index( output_itr out_begin, idx_itr idx_begin, idx_itr idx_end, val_itr values_begin ); } #include "vop.ipp" #endif // #ifndef VOP_HPP
43.255102
99
0.681529
zhu48
e6441c8b37b7d62746b4b3b37a1f3808926c119f
2,226
hpp
C++
include/eagine/integer_range.hpp
matus-chochlik/eagine-core
5bc2d6b9b053deb3ce6f44f0956dfccd75db4649
[ "BSL-1.0" ]
1
2022-01-25T10:31:51.000Z
2022-01-25T10:31:51.000Z
include/eagine/integer_range.hpp
matus-chochlik/eagine-core
5bc2d6b9b053deb3ce6f44f0956dfccd75db4649
[ "BSL-1.0" ]
null
null
null
include/eagine/integer_range.hpp
matus-chochlik/eagine-core
5bc2d6b9b053deb3ce6f44f0956dfccd75db4649
[ "BSL-1.0" ]
null
null
null
/// @file /// /// Copyright Matus Chochlik. /// 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 EAGINE_INTEGER_RANGE_HPP #define EAGINE_INTEGER_RANGE_HPP #include "iterator.hpp" namespace eagine { /// @brief Integer range type template usable in range-based loops. /// @ingroup type_utils /// /// Instances of this class can be used as the range in range-based for loops /// instead of using, comparing and incrementing a for loop variable. template <typename T> class integer_range { public: /// @brief Default constructor. /// @post empty() /// @post begin() == end() constexpr integer_range() noexcept = default; /// @brief Initialization specifying the past the end integer value. /// @post size() == e constexpr integer_range(const T e) noexcept : _end{e} {} /// @brief Initialization specifying the begin and past the end integer values. /// @post size() == e - b constexpr integer_range(const T b, const T e) noexcept : _begin{b} , _end{e} {} /// @brief Iterator type alias. using iterator = selfref_iterator<T>; /// @brief Iteration count type alias. using size_type = decltype(std::declval<T>() - std::declval<T>()); /// @brief Indicates that the range is empty. /// @see size constexpr auto empty() const noexcept { return _end == _begin; } /// @brief Returns the number of iteration steps in this range. /// @see empty constexpr auto size() const noexcept { return _end - _begin; } /// @brief Returns the iterator to the start of the range. constexpr auto begin() const noexcept -> iterator { return {_begin}; } /// @brief Returns the iterator past the end of the range. constexpr auto end() const noexcept -> iterator { return {_end}; } private: const T _begin{0}; const T _end{0}; }; /// @brief Deduction guide for integer_range. /// @ingroup type_utils template <typename B, typename E> integer_range(B, E) -> integer_range<std::common_type_t<B, E>>; } // namespace eagine #endif // EAGINE_INTEGER_RANGE_HPP
27.481481
83
0.660827
matus-chochlik
e6463ce0d96cd56d96d6b0d963dfa3c44edc9660
629
cpp
C++
collision.cpp
CaptainDreamcast/Torchbearer
144a1d8eca66e994dc832fc4116431ea267e00d9
[ "MIT" ]
null
null
null
collision.cpp
CaptainDreamcast/Torchbearer
144a1d8eca66e994dc832fc4116431ea267e00d9
[ "MIT" ]
null
null
null
collision.cpp
CaptainDreamcast/Torchbearer
144a1d8eca66e994dc832fc4116431ea267e00d9
[ "MIT" ]
null
null
null
#include "collision.h" #include <prism/blitz.h> static struct { CollisionListData* mPlayerCollisionList; CollisionListData* mObstacleCollisionList; } gCollisionData; void initCollisions() { gCollisionData.mPlayerCollisionList = addCollisionListToHandler(); gCollisionData.mObstacleCollisionList = addCollisionListToHandler(); addCollisionHandlerCheck(gCollisionData.mPlayerCollisionList, gCollisionData.mObstacleCollisionList); } CollisionListData* getPlayerCollisionList() { return gCollisionData.mPlayerCollisionList; } CollisionListData* getObstacleCollisionList() { return gCollisionData.mObstacleCollisionList; }
25.16
102
0.844197
CaptainDreamcast
e646b1207910a2f5c038c30eb2ad659a8e39e21b
7,158
cpp
C++
src/HubLabelStore.cpp
dbahrdt/path_finder
1105966e5b50590acd9aca30ceb6922b0e40c259
[ "Apache-2.0" ]
1
2021-03-12T23:18:30.000Z
2021-03-12T23:18:30.000Z
src/HubLabelStore.cpp
dbahrdt/path_finder
1105966e5b50590acd9aca30ceb6922b0e40c259
[ "Apache-2.0" ]
8
2020-05-27T17:25:58.000Z
2020-05-29T10:39:54.000Z
src/HubLabelStore.cpp
dbahrdt/path_finder
1105966e5b50590acd9aca30ceb6922b0e40c259
[ "Apache-2.0" ]
1
2020-10-19T09:01:09.000Z
2020-10-19T09:01:09.000Z
// // Created by sokol on 23.01.20. // #include "path_finder/storage/HubLabelStore.h" #include <cstring> #include <execution> #include <memory> #include <path_finder/helper/Static.h> #include <sstream> #include <utility> namespace pathFinder { HubLabelStore::HubLabelStore(size_t numberOfLabels) { m_forwardOffset = new OffsetElement[numberOfLabels]; m_backwardOffset = new OffsetElement[numberOfLabels]; m_backwardLabels = nullptr; m_forwardLabels = nullptr; this->m_numberOfLabels = numberOfLabels; } void HubLabelStore::store(const std::vector<CostNode> &label, NodeId id, EdgeDirection direction) { auto &storePointer = direction ? m_forwardLabels : m_backwardLabels; auto &offsetPointer = direction ? m_forwardOffset : m_backwardOffset; auto &size = direction ? m_forwardLabelSize : m_backwardLabelSize; offsetPointer[id] = OffsetElement{size, (uint32_t)label.size()}; { auto * newData = new CostNode[size + label.size()]; std::copy(storePointer, storePointer+size, newData); std::copy(label.begin(), label.end(), storePointer+size); std::swap(newData, storePointer); delete[] newData; } size += label.size(); } void HubLabelStore::store(std::vector<HubLabelStore::IdLabelPair> &idLabels, EdgeDirection direction) { size_t allocationSize = std::accumulate( idLabels.begin(), idLabels.end(), (size_t)0, [](size_t init, const HubLabelStore::IdLabelPair &idLabelPair) { return init + idLabelPair.second.size(); }); auto &storePointer = direction ? m_forwardLabels : m_backwardLabels; auto &offsetPointer = direction ? m_forwardOffset : m_backwardOffset; auto &size = direction ? m_forwardLabelSize : m_backwardLabelSize; { CostNode * newData = new CostNode[size + allocationSize]; std::copy(storePointer, storePointer+size, newData); std::swap(newData, storePointer); delete[] newData; } std::cout << "writing labels: 0/" << idLabels.size() << '\r'; int i = 0; for (auto &&[id, label] : idLabels) { offsetPointer[id] = OffsetElement{size, (uint32_t)label.size()}; std::memcpy(storePointer + size, label.data(), sizeof(CostNode) * label.size()); size += label.size(); label.clear(); char newLineChar = (i == idLabels.size() - 1) ? '\n' : '\r'; std::cout << "writing labels: " << ++i << '/' << idLabels.size() << newLineChar; } } MyIterator<const CostNode *> HubLabelStore::retrieveIt(NodeId id, EdgeDirection direction) const { if (id > m_numberOfLabels - 1) throw std::runtime_error("[HublabelStore] node id does not exist."); auto offsetElement = direction ? m_forwardOffset[id] : m_backwardOffset[id]; auto labelEnd = offsetElement.position + offsetElement.size; const auto &storePointer = direction ? m_forwardLabels : m_backwardLabels; return MyIterator<const CostNode *>(storePointer + offsetElement.position, storePointer + labelEnd); } std::vector<CostNode> HubLabelStore::retrieve(NodeId id, EdgeDirection direction) const { if (id > m_numberOfLabels - 1) throw std::runtime_error("[HublabelStore] node id does not exist."); bool forward = (EdgeDirection::FORWARD == direction); auto offsetElement = forward ? m_forwardOffset[id] : m_backwardOffset[id]; if (offsetElement.size == 0) { return std::vector<CostNode>(); } std::vector<CostNode> storeVec; storeVec.reserve(offsetElement.size); auto labelEnd = offsetElement.position + offsetElement.size; volatile const auto &storePointer = forward ? m_forwardLabels : m_backwardLabels; for (auto i = offsetElement.position; i < labelEnd; ++i) { storeVec.push_back(storePointer[i]); } return storeVec; } void HubLabelStore::retrieve(NodeId id, EdgeDirection direction, CostNode *&storeVec, size_t &size) const { if (id > m_numberOfLabels - 1) throw std::runtime_error("[HublabelStore] node id does not exist."); bool forward = (EdgeDirection::FORWARD == direction); auto offsetElement = forward ? m_forwardOffset[id] : m_backwardOffset[id]; if (offsetElement.size == 0) { storeVec = nullptr; size = 0; return; } auto labelEnd = offsetElement.position + offsetElement.size; storeVec = new CostNode[offsetElement.size]; size = offsetElement.size; const auto storePointer = forward ? m_forwardLabels : m_backwardLabels; for (auto i = offsetElement.position, j = (size_t)0; i < labelEnd; ++i, ++j) { storeVec[j] = storePointer[i]; } } size_t HubLabelStore::getNumberOfLabels() const { return m_numberOfLabels; } HubLabelStore::HubLabelStore(HubLabelStoreInfo hubLabelStoreInfo) { this->m_forwardLabels = hubLabelStoreInfo.forwardLabels; this->m_backwardLabels = hubLabelStoreInfo.backwardLabels; this->m_forwardOffset = hubLabelStoreInfo.forwardOffset; this->m_backwardOffset = hubLabelStoreInfo.backwardOffset; this->m_numberOfLabels = hubLabelStoreInfo.numberOfLabels; this->m_forwardLabelSize = hubLabelStoreInfo.forwardLabelSize; this->m_backwardLabelSize = hubLabelStoreInfo.backwardLabelSize; this->m_forwardLabelsMMap = hubLabelStoreInfo.forwardLabelsMMap; this->m_backwardLabelsMMap = hubLabelStoreInfo.backwardLabelsMMap; this->m_forwardOffsetMMap = hubLabelStoreInfo.forwardOffsetMMap; this->m_backwardOffsetMMap = hubLabelStoreInfo.backwardOffsetMMap; this->calculatedUntilLevel = hubLabelStoreInfo.calculatedUntilLevel; } HubLabelStore::~HubLabelStore() { Static::conditionalFree(m_forwardLabels, m_forwardLabelsMMap, m_forwardLabelSize * sizeof(CostNode)); Static::conditionalFree(m_backwardLabels, m_backwardLabelsMMap, m_backwardLabelSize * sizeof(CostNode)); Static::conditionalFree(m_forwardOffset, m_forwardOffsetMMap, m_numberOfLabels * sizeof(OffsetElement)); Static::conditionalFree(m_backwardOffset, m_backwardOffsetMMap, m_numberOfLabels * sizeof(OffsetElement)); } size_t HubLabelStore::getForwardLabelsSize() const { return m_forwardLabelSize; } size_t HubLabelStore::getBackwardLabelsSize() const { return m_backwardLabelSize; } size_t HubLabelStore::getForwardOffsetSize() const { return m_numberOfLabels; } size_t HubLabelStore::getBackwardOffsetSize() const { return m_numberOfLabels; } [[maybe_unused]] std::string HubLabelStore::printStore() const { std::stringstream ss; for (NodeId i = 0; i < m_numberOfLabels; ++i) { std::vector<CostNode> forwardVec = retrieve(i, EdgeDirection::FORWARD); std::vector<CostNode> backwardVec = retrieve(i, EdgeDirection::BACKWARD); ss << "label for id: " << i << '\n'; ss << "forward:" << '\n'; for (const auto &[id, cost, previousNode] : forwardVec) { ss << id << ' ' << cost << ' ' << previousNode << '\n'; } ss << "backward:" << '\n'; for (const auto &[id, cost, previousNode] : backwardVec) { ss << id << ' ' << cost << ' ' << previousNode << '\n'; } } return ss.str(); } std::shared_ptr<HubLabelStore> HubLabelStore::makeShared(size_t numberOfLabels) { return std::make_shared<HubLabelStore>(numberOfLabels); } auto HubLabelStore::getSpaceConsumption() const -> size_t { return (m_forwardLabelSize + m_backwardLabelSize) * sizeof(CostNode) + (m_numberOfLabels + m_numberOfLabels) * sizeof (OffsetElement); }; } // namespace pathFinder
42.607143
115
0.732886
dbahrdt
e64c1c47e9dd2b799f5cfa689d48ce9a9eef9980
3,871
cpp
C++
src/component/text_component.cpp
equal-games/equal
acaf0d456d7b996dd2a6bc23150cd45ddf618296
[ "BSD-2-Clause", "Apache-2.0" ]
7
2019-08-07T21:27:27.000Z
2020-11-27T16:33:16.000Z
src/component/text_component.cpp
equal-games/equal
acaf0d456d7b996dd2a6bc23150cd45ddf618296
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
src/component/text_component.cpp
equal-games/equal
acaf0d456d7b996dd2a6bc23150cd45ddf618296
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Equal Games * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <equal/component/text_component.hpp> #include <equal/component/transform_component.hpp> #include <equal/core/game_object.hpp> #include <equal/core/logger.hpp> #include <equal/core/resource.hpp> #include <equal/helper/error.hpp> #include <equal/helper/string.hpp> #ifdef EQ_SDL #include <SDL2/SDL_ttf.h> #endif namespace eq { TextComponent::TextComponent(Font *font) { m_font = font; } TextComponent::TextComponent(const std::string &text, Font *font) { m_text = str::utf8_to_wchar(text.c_str()); m_font = font; } TextComponent::~TextComponent() { delete m_font; } uint32_t TextComponent::font_size() const { return m_font_size; } void TextComponent::font_size(uint32_t font_size) { if (m_font_size != font_size) { m_font_size = font_size; m_need_update = true; } } Text::Overflow TextComponent::overflow_x() const { return m_overflow_x; } void TextComponent::overflow_x(Text::Overflow overflow) { if (m_overflow_x != overflow) { m_overflow_x = overflow; } } Text::Overflow TextComponent::overflow_y() const { return m_overflow_y; } void TextComponent::overflow_y(Text::Overflow overflow) { if (m_overflow_y != overflow) { m_overflow_y = overflow; } } const Position &TextComponent::offset() const { return m_offset; } void TextComponent::offset(const Position &offset) { if (m_offset != offset) { m_offset = offset; } } const Color &TextComponent::color() const { return m_color; } void TextComponent::color(const Color &color) { if (m_color != color) { m_color = color; } } const std::wstring &TextComponent::text() const { return m_text; } void TextComponent::text(const std::wstring &text) { if (m_text != text) { m_text = text; m_need_update = true; } } void TextComponent::text(const std::string &text) { this->text(str::utf8_to_wchar(text.c_str())); } bool TextComponent::masked() const { return m_masked; } void TextComponent::masked(bool masked) { if (m_masked != masked) { m_masked = masked; } } void TextComponent::alignment(const Text::Alignment &align) { if (m_align != align) { m_align = align; } } void TextComponent::style(const Text::Style &style) { if (m_style != style) { m_style = style; } } Font *TextComponent::font() const { return m_font; } void TextComponent::font(Font *font) { if (m_font != font) { m_font = font; m_need_update = true; } } const BoundingBox &TextComponent::crop() const { return m_crop; } void TextComponent::crop(const BoundingBox &crop) { if (m_crop != crop) { m_crop = crop; m_need_update = true; } } void TextComponent::fixed_update(const Timestep &timestep) {} void TextComponent::update(const Timestep &timestep) { if (m_need_update) { m_need_update = false; if (!m_text.empty()) { m_target->visible(true); TransformComponent *transform{m_target->get<TransformComponent>()}; #ifdef EQ_SDL std::string text_value = str::wchar_to_utf8(m_text.c_str()); int w, h; if (TTF_SizeText(static_cast<TTF_Font *>(m_font->data), text_value.c_str(), &w, &h) != 0) { EQ_THROW("Can't draw game object: {}", TTF_GetError()); } transform->size(Size{w, h}); #endif } else { m_target->visible(false); } } } } // namespace eq
25.136364
99
0.690778
equal-games
e64d514d029ead61d9be0d128d5db871d7ff7a1f
3,173
cpp
C++
tests/nnti/cpp-api/NntiOpVectorTest.cpp
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-01-25T21:21:07.000Z
2021-04-29T17:24:00.000Z
tests/nnti/cpp-api/NntiOpVectorTest.cpp
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
8
2018-10-09T14:35:30.000Z
2020-09-30T20:09:42.000Z
tests/nnti/cpp-api/NntiOpVectorTest.cpp
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-04-23T19:01:36.000Z
2021-05-11T07:44:55.000Z
// Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. #include "nnti/nnti_pch.hpp" #include <mpi.h> #include "gtest/gtest.h" #include "faodel-common/Common.hh" #include "nnti/nntiConfig.h" #include <unistd.h> #include <string.h> #include <pthread.h> #include <iostream> #include <thread> #include <vector> #include "nnti/nnti_transport.hpp" #include "nnti/nnti_op.hpp" #include "nnti/nnti_wid.hpp" #include "test_utils.hpp" using namespace std; using namespace faodel; string default_config_string = R"EOF( # default to using mpi, but allow override in config file pointed to by CONFIG nnti.transport.name mpi )EOF"; class test_op : public nnti::core::nnti_op { private: test_op(void); public: test_op( nnti::transports::transport *transport, nnti::datatype::nnti_work_id *wid) : nnti_op( wid) { return; } }; class NntiOpVectorTest : public testing::Test { protected: Configuration config; nnti::transports::transport *t=nullptr; void SetUp () override { config = Configuration(default_config_string); config.AppendFromReferences(); test_setup(0, NULL, config, "OpVectorTest", t); } void TearDown () override { NNTI_result_t nnti_rc = NNTI_OK; bool init; init = t->initialized(); EXPECT_TRUE(init); if (init) { nnti_rc = t->stop(); EXPECT_EQ(nnti_rc, NNTI_OK); } } }; const int num_op=1024; TEST_F(NntiOpVectorTest, start1) { nnti::datatype::nnti_work_id wid(t); std::vector<test_op*> mirror; nnti::core::nnti_op_vector op_vector(1024); mirror.reserve(1024); for (int i = 0; i < num_op; ++i) { test_op *op = new test_op(t, &wid); op_vector.add(op); mirror[i] = op; if (i % 10 == 0) { uint32_t victim_index = i/2; nnti::core::nnti_op *victim_op = op_vector.remove(victim_index); EXPECT_EQ(victim_op, mirror[victim_index]); op = new test_op(t, &wid); op_vector.add(op); mirror[victim_index] = op; EXPECT_EQ(op_vector.at(victim_index), mirror[victim_index]); delete victim_op; } } for (uint32_t i = 0; i < mirror.size(); ++i) { EXPECT_EQ(op_vector.at(i), mirror[i]); op_vector.remove(i); delete mirror[i]; } } int main(int argc, char *argv[]) { ::testing::InitGoogleTest(&argc, argv); int provided; MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided); int mpi_rank,mpi_size; MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); MPI_Comm_size(MPI_COMM_WORLD, &mpi_size); EXPECT_EQ(1, mpi_size); assert(1==mpi_size); int rc = RUN_ALL_TESTS(); cout <<"Tester completed all tests.\n"; MPI_Barrier(MPI_COMM_WORLD); bootstrap::Finish(); MPI_Finalize(); return (rc); }
22.034722
78
0.607942
faodel
e6514457bc2b8dd014f85c0b00fe47f067f7155e
283
cpp
C++
tests/test3.cpp
chrisroman/llvm-pass-skeleton
5e0308c38bd8aec7ac33b794f7d9551cfdf01733
[ "MIT" ]
1
2020-10-26T02:45:22.000Z
2020-10-26T02:45:22.000Z
tests/test3.cpp
chrisroman/llvm-pass-skeleton
5e0308c38bd8aec7ac33b794f7d9551cfdf01733
[ "MIT" ]
null
null
null
tests/test3.cpp
chrisroman/llvm-pass-skeleton
5e0308c38bd8aec7ac33b794f7d9551cfdf01733
[ "MIT" ]
null
null
null
#include <stdlib.h> /* exit, EXIT_FAILURE */ #include "track_nullptr.h" void deref_null(int argc) { int *p = nullptr; if (argc == 1) { p = &argc; } *p = 42; } int main(int argc, char** argv) { //escape(&nullp); deref_null(argc); return 0; }
16.647059
48
0.537102
chrisroman
e654beaee6fadb0fdaad20ec16f713cbb088f20b
1,275
hpp
C++
android-31/android/icu/text/DateIntervalInfo.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/icu/text/DateIntervalInfo.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-30/android/icu/text/DateIntervalInfo.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../../../JObject.hpp" namespace android::icu::text { class DateIntervalInfo_PatternInfo; } namespace android::icu::util { class ULocale; } class JObject; class JString; namespace java::util { class Locale; } namespace android::icu::text { class DateIntervalInfo : public JObject { public: // Fields // QJniObject forward template<typename ...Ts> explicit DateIntervalInfo(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} DateIntervalInfo(QJniObject obj); // Constructors DateIntervalInfo(android::icu::util::ULocale arg0); DateIntervalInfo(java::util::Locale arg0); // Methods JObject clone() const; android::icu::text::DateIntervalInfo cloneAsThawed() const; jboolean equals(JObject arg0) const; android::icu::text::DateIntervalInfo freeze() const; jboolean getDefaultOrder() const; JString getFallbackIntervalPattern() const; android::icu::text::DateIntervalInfo_PatternInfo getIntervalPattern(JString arg0, jint arg1) const; jint hashCode() const; jboolean isFrozen() const; void setFallbackIntervalPattern(JString arg0) const; void setIntervalPattern(JString arg0, jint arg1, JString arg2) const; }; } // namespace android::icu::text
25.5
157
0.737255
YJBeetle
e655ee06e0db284b536e2a0f8e9c737708efaf2e
850
cpp
C++
src/atom.cpp
chiang-yuan/csh4lmp
8a8dff5d2b65ce463e4d58dc52e35a6114b7e597
[ "MIT" ]
9
2019-03-22T03:45:24.000Z
2021-02-18T04:19:12.000Z
src/atom.cpp
Chiang-Yuan/csh4lmp
8a8dff5d2b65ce463e4d58dc52e35a6114b7e597
[ "MIT" ]
null
null
null
src/atom.cpp
Chiang-Yuan/csh4lmp
8a8dff5d2b65ce463e4d58dc52e35a6114b7e597
[ "MIT" ]
1
2022-03-31T11:57:07.000Z
2022-03-31T11:57:07.000Z
#include "atom.h" Atom::Atom() { delete_flag = false; bondNum = 0; bondID = std::vector<bigint>(MAX_BONDS_PER_ATOM); bonds = std::vector<Bond*>(MAX_BONDS_PER_ATOM); angleNum = 0; } Atom::~Atom() { } bool operator==(const Atom& lhs, const Atom& rhs) { return (lhs.id == rhs.id); } bool operator!=(const Atom & lhs, const Atom & rhs) { return !(lhs == rhs); } Atom & operator&=(Atom & lhs, const Atom & rhs) { lhs.id = rhs.id; lhs.molecule = rhs.molecule; lhs.type = rhs.type; lhs.q = rhs.q; lhs.x[0] = rhs.x[0]; lhs.x[1] = rhs.x[1]; lhs.x[2] = rhs.x[2]; lhs.n[0] = rhs.n[0]; lhs.n[1] = rhs.n[1]; lhs.n[2] = rhs.n[2]; strcpy(lhs.name, rhs.name); lhs.delete_flag = rhs.delete_flag; lhs.bondNum = rhs.bondNum; lhs.bondID = rhs.bondID; lhs.bonds = rhs.bonds; lhs.angleNum = rhs.angleNum; lhs.angles = rhs.angles; return lhs; }
19.318182
63
0.625882
chiang-yuan
e65cb69470313025359f0dd0053f56a558f24d34
6,099
cpp
C++
Engine/Core/Sources/Threading/ThreadPool.cpp
makdenis/YetAnotherProject
e43cc3ca2d4a13984f97f0949f88ab17fa6905d3
[ "MIT" ]
1
2018-05-02T10:40:26.000Z
2018-05-02T10:40:26.000Z
Engine/Core/Sources/Threading/ThreadPool.cpp
makdenis/YetAnotherProject
e43cc3ca2d4a13984f97f0949f88ab17fa6905d3
[ "MIT" ]
9
2018-03-26T10:22:07.000Z
2018-05-22T20:43:14.000Z
Engine/Core/Sources/Threading/ThreadPool.cpp
makdenis/YetAnotherProject
e43cc3ca2d4a13984f97f0949f88ab17fa6905d3
[ "MIT" ]
6
2018-04-15T16:03:32.000Z
2018-05-21T22:02:49.000Z
#include "ThreadPool.hpp" #include <assert.h> #define LOCK(MUTEX) std::unique_lock<std::mutex> lock /******************************************************************** * TaskBacket ********************************************************************/ TaskBacket::TaskBacket() { bComplitted = true; } TaskBacket::~TaskBacket() { } bool TaskBacket::AddTask(IRunable* newTask) { if (!newTask) return false; bComplitted = false; { LOCK(mutex_storedTasks); storedTasks.emplace_back(newTask); } return true; } bool TaskBacket::MarkAsDone(IRunable* doneTask) { assert(doneTask); { LOCK(mutex_processingTasks); processingTasks.erase(doneTask); if (processingTasks.size()) return false; if (mutex_storedTasks.try_lock()) { bool bDone = !storedTasks.size(); mutex_storedTasks.unlock(); bComplitted = bDone; return bDone; } else return false; } } bool TaskBacket::IsCompleted() { return bComplitted; } IRunable* TaskBacket::GetTask() { IRunable* task; { mutex_storedTasks.lock(); if (!storedTasks.size()) { mutex_storedTasks.unlock(); return nullptr; } task = storedTasks.front(); storedTasks.pop_front(); { LOCK(mutex_processingTasks); processingTasks.emplace(task); mutex_storedTasks.unlock(); } } return task; } void TaskBacket::Wait() { while (!bComplitted) { std::this_thread::sleep_for(std::chrono::microseconds(300)); } } /******************************************************************** * ThreadPool ********************************************************************/ std::deque<IRunable*> ThreadPool::tasks = std::deque<IRunable*>(); std::deque<IRunable*> ThreadPool::tasks_exclusive = std::deque<IRunable*>(); std::deque<TaskBacket*> ThreadPool::backets = std::deque<TaskBacket*>(); std::unordered_set<Thread*> ThreadPool::threads = std::unordered_set<Thread*>(); std::unordered_set<Thread*> ThreadPool::threads_exclusive = std::unordered_set<Thread*>(); std::unordered_map<Thread*, UNIQUE(Thread)> ThreadPool::allThreads; std::atomic<size_t> ThreadPool::maxThreadCount = 1; std::atomic<bool> ThreadPool::bProcessBacket = false; bool ThreadPool::AddTask(IRunable* task, bool bExlusiveThread) { if (!task) return false; if (!bExlusiveThread) { { LOCK(mutex_tasks); tasks.emplace_back(task); } { LOCK(mutex_threads); if (NewThreadRequired(bExlusiveThread)) { CreateThread(bExlusiveThread); } } } else { { LOCK(mutex_tasks_exclusive); tasks_exclusive.emplace_back(task); } { LOCK(mutex_threads_exclusive); if (NewThreadRequired(bExlusiveThread)) { CreateThread(bExlusiveThread); } } } return true; } bool ThreadPool::AddTaskBacket(TaskBacket& backet) { if (backet.IsCompleted()) return true; { LOCK(mutex_backets); backets.emplace_back(&backet); } AddTask(new BacketRunable(), false); return true; } ThreadTask ThreadPool::GetRunTask(Thread* thread, IRunable* complittedTask) { if (!thread) return ThreadTask(); bool bExclusive = false; ThreadTask result; { LOCK(mutex_threads_exclusive); if (threads_exclusive.count(thread)) { result = GetRunTask_exclusive(thread, complittedTask); bExclusive = true; } } if (!bExclusive) { if (bProcessBacket) { result = GetRunTask_backet(thread, complittedTask); } else { result = GetRunTask_common(thread, complittedTask); } } if (complittedTask) { delete complittedTask; } if (result == ThreadTask::ShouldDie) { DeleteThread(bExclusive, thread); } return result; } ThreadTask ThreadPool::GetRunTask_common(Thread* thread, IRunable* complittedTask) { ThreadTask result = ThreadTask::NextLoop; { LOCK(mutex_tasks); if (ShouldDie(thread)) { result = ThreadTask::ShouldDie; } else if (tasks.size()) { // get new task result.task = tasks.front(); result.bDie = false; tasks.pop_front(); // start process a backet if (dynamic_cast<BacketRunable*>(result.task)) { delete result.task; bProcessBacket = true; result = ThreadTask::NextLoop; } } else { result = ThreadTask::NextLoop; } } return result; } ThreadTask ThreadPool::GetRunTask_backet(Thread* thread, IRunable* complittedTask) { ThreadTask result = ThreadTask::NextLoop; { LOCK(mutex_backets); bool bDone = false; if (complittedTask) { bDone = backets.front()->MarkAsDone(complittedTask); } else { bDone = backets.front()->IsCompleted(); } if (!bDone) // try to get a new task { IRunable* newTask = backets.front()->GetTask(); if (newTask) { result.task = newTask; result.bDie = false; } else { result = ThreadTask::NextLoop; } } if (bDone) // the lates task is done { bProcessBacket = false; backets.pop_front(); result = ShouldDie(thread) ? ThreadTask::ShouldDie : ThreadTask::NextLoop; } } return result; } ThreadTask ThreadPool::GetRunTask_exclusive(Thread* thread, IRunable* complittedTask) { ThreadTask result = ThreadTask::NextLoop; { LOCK(mutex_tasks_exclusive); if (tasks_exclusive.size()) { result.task = tasks_exclusive.front(); result.bDie = false; tasks_exclusive.pop_front(); return result; } } { LOCK(mutex_threads); threads_exclusive.erase(thread); threads.emplace(thread); return result; } } bool ThreadPool::ShouldDie(Thread* thread) { return threads.size() > maxThreadCount; } bool ThreadPool::NewThreadRequired(bool bExlusive) { if (!bExlusive) { return threads.size() < maxThreadCount; } else { return true; } } void ThreadPool::CreateThread(bool bExlusive) { UNIQUE(Thread) newThread = Thread::Get(); Thread* thread_ptr = newThread.get(); allThreads[thread_ptr] = std::move(newThread); if (!bExlusive) { threads.emplace(thread_ptr); } else { threads_exclusive.emplace(thread_ptr); } thread_ptr->Run(); } void ThreadPool::DeleteThread(bool bExlusive, Thread* thread) { if (!bExlusive) { threads.erase(thread); } else { threads_exclusive.erase(thread); } allThreads.erase(thread); }
17.99115
90
0.654697
makdenis
e65ddf9e93182443c1db22f317c886713ade7900
4,028
hpp
C++
include/jitana/analysis/call_graph.hpp
Xbeas/jitana
fc33976cf6f4cbb91263a06bae32e9ad07fc5551
[ "0BSD" ]
31
2017-04-21T03:25:46.000Z
2022-02-20T20:59:23.000Z
include/jitana/analysis/call_graph.hpp
Xbeas/jitana
fc33976cf6f4cbb91263a06bae32e9ad07fc5551
[ "0BSD" ]
3
2020-12-21T09:02:06.000Z
2021-03-16T10:37:38.000Z
include/jitana/analysis/call_graph.hpp
Xbeas/jitana
fc33976cf6f4cbb91263a06bae32e9ad07fc5551
[ "0BSD" ]
9
2017-06-06T19:30:43.000Z
2021-05-19T19:50:03.000Z
/* * Copyright (c) 2015, 2016, Yutaka Tsutano * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #ifndef JITANA_CALL_GRAPH_HPP #define JITANA_CALL_GRAPH_HPP #include "jitana/jitana.hpp" #include <algorithm> #include <boost/type_erasure/any_cast.hpp> #include <boost/range/iterator_range.hpp> namespace jitana { struct method_call_edge_property { bool virtual_call; insn_vertex_descriptor caller_insn_vertex; }; inline void print_graphviz_attr(std::ostream& os, const method_call_edge_property& prop) { os << "color=red, label="; os << (prop.virtual_call ? "virtual" : "direct"); os << ", taillabel=" << prop.caller_insn_vertex; } inline void add_call_graph_edges(virtual_machine& vm, const method_vertex_descriptor& v) { using boost::type_erasure::any_cast; auto& mg = vm.methods(); // Abort if we already have an outgoing call graph edge to avoid // creating duplicates. For performacnce, we should have flags // indicating if we have already computed the call graph for this edge. for (const auto& me : boost::make_iterator_range(out_edges(v, mg))) { if (any_cast<method_call_edge_property*>(&mg[me]) != nullptr) { return; } } auto ig = mg[v].insns; // Iterate over the instruction graph vertices. for (const auto& iv : boost::make_iterator_range(vertices(ig))) { // Get the vertex property. const auto& prop = ig[iv]; // Ignore if it is a non-DEX instruction. if (is_pseudo(prop.insn)) { continue; } // Determine the type of the instruction. method_call_edge_property eprop; const auto& insn_info = info(op(prop.insn)); if (insn_info.can_virtually_invoke()) { eprop.virtual_call = true; } else if (insn_info.can_directly_invoke()) { eprop.virtual_call = false; } else { // Not an invoke instruction. continue; } eprop.caller_insn_vertex = iv; // Get the target method handle. dex_method_hdl method_hdl; if (insn_info.odex_only()) { // Optimized: uses vtable. Unless we know the type of the target // method's class, we cannot tell the method handle. // auto off = // any_cast<code::i_invoke_quick>(prop.insn).const_val; continue; } else { method_hdl = *const_val<dex_method_hdl>(prop.insn); } // Add an edge to the methood graph. auto target_v = vm.find_method(method_hdl, false); if (target_v) { add_edge(v, *target_v, eprop, mg); } } } inline void add_call_graph_edges(virtual_machine& vm) { auto& mg = vm.methods(); std::for_each(vertices(mg).first, vertices(mg).second, [&](const method_vertex_descriptor& v) { add_call_graph_edges(vm, v); }); } } #endif
34.724138
80
0.588878
Xbeas
e661ff980e7be9bfb2ab4ac0cca88b59be10469d
1,100
cpp
C++
Libraries/RobsJuceModules/romos/Framework/romos_ProcessingStatus.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Libraries/RobsJuceModules/romos/Framework/romos_ProcessingStatus.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Libraries/RobsJuceModules/romos/Framework/romos_ProcessingStatus.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
//#include "romos_ProcessingStatus.h" //using namespace romos; ProcessingStatus processingStatus; // definition of the global object //----------------------------------------------------------------------------------------------------------------------------------------- // construction/destruction: ProcessingStatus::ProcessingStatus() { setSystemSampleRate(44100.0); setTempo(120.0); setBufferSize(66); // 66 yields best performance with IdentityChain performance test } ProcessingStatus::~ProcessingStatus() { } //----------------------------------------------------------------------------------------------------------------------------------------- // setup: void ProcessingStatus::setSystemSampleRate(double newSampleRate) { systemSampleRate = newSampleRate; systemSamplePeriod = 1.0 / systemSampleRate; freqToOmegaFactor = (2.0*PI) / systemSampleRate; } void ProcessingStatus::setTempo(double newTempo) { tempo = newTempo; } void ProcessingStatus::setBufferSize(int newBufferSize) { if( newBufferSize <= maxBufferSize ) bufferSize = newBufferSize; }
26.190476
139
0.565455
RobinSchmidt
e66291ea7314d2fbde3ac9368ba51effc802e746
636
cpp
C++
String/10_permutations.cpp
ritikrajdev/450DSA
a9efa8c8be781fd7b101407ac807a83b8a0929f4
[ "MIT" ]
null
null
null
String/10_permutations.cpp
ritikrajdev/450DSA
a9efa8c8be781fd7b101407ac807a83b8a0929f4
[ "MIT" ]
null
null
null
String/10_permutations.cpp
ritikrajdev/450DSA
a9efa8c8be781fd7b101407ac807a83b8a0929f4
[ "MIT" ]
null
null
null
#include <algorithm> #include <string> #include <vector> using namespace std; class Solution { void helper(string &S, int l, int r, vector<string> &vec) { if (l == r) { vec.push_back(S); return; } for (int i = l; i <= r; i++) { swap(S[i], S[l]); helper(S, l + 1, r, vec); swap(S[i], S[l]); } } public: vector<string> find_permutation(string S) { std::sort(S.begin(), S.end()); vector<string> vec; helper(S, 0, S.size() - 1, vec); std::sort(vec.begin(), vec.end()); return vec; } };
21.2
63
0.463836
ritikrajdev
e662bb84a95721dbc93162a81e9bd8ec016474b3
1,627
hpp
C++
src/message_service.hpp
madmongo1/blog-october-2020
95968a7c6bc9ed8476f72d0ec107544b5ec26498
[ "BSL-1.0" ]
1
2021-02-12T00:18:55.000Z
2021-02-12T00:18:55.000Z
src/message_service.hpp
madmongo1/blog-october-2020
95968a7c6bc9ed8476f72d0ec107544b5ec26498
[ "BSL-1.0" ]
1
2020-12-21T09:53:31.000Z
2020-12-21T09:53:31.000Z
src/message_service.hpp
madmongo1/blog-october-2020
95968a7c6bc9ed8476f72d0ec107544b5ec26498
[ "BSL-1.0" ]
null
null
null
// // Created by rhodges on 09/11/2020. // #pragma once #include "async_condition_variable.hpp" #include "basic_distributor.hpp" #include "config.hpp" #include <memory> struct message_service_impl { using executor_type = net::strand<net::io_context::executor_type>; message_service_impl(net::io_context::executor_type const &exec); net::awaitable<void> run(); auto connect(net::any_io_executor client_exec) -> net::awaitable<basic_connection<std::string>>; void stop(); auto get_executor() const -> executor_type const & { return exec_; } private: void listen_for_stop(std::function<void()> slot); executor_type exec_; error_code stop_reason_; std::vector<std::function<void()>> stop_signals_; async_condition_variable stop_condition_{get_executor()}; basic_distributor_impl<std::string> message_dist_; }; struct message_service { using executor_type = net::io_context::executor_type; message_service(executor_type const &exec); message_service(message_service &&) noexcept = default; message_service & operator=(message_service &&) noexcept = default; message_service(message_service const &) = delete; message_service & operator=(message_service const &) = delete; void reset() noexcept; ~message_service(); auto connect() -> net::awaitable<basic_connection<std::string>>; auto get_executor() const -> executor_type const & { return exec_; } private: executor_type exec_; std::shared_ptr<message_service_impl> impl_; };
20.3375
70
0.684696
madmongo1
e667ecb9ae71a5f34cf7f886ad808bd62d96ccbb
5,179
hpp
C++
include/vecl/broadcast.hpp
ethereal-sheep/vecl
519e8e90a1cd2c424f0a666e24da2d2ad3ffdcaf
[ "MIT" ]
1
2021-09-15T13:13:16.000Z
2021-09-15T13:13:16.000Z
include/vecl/broadcast.hpp
ethereal-sheep/vecl
519e8e90a1cd2c424f0a666e24da2d2ad3ffdcaf
[ "MIT" ]
1
2022-01-03T09:52:35.000Z
2022-01-03T09:52:35.000Z
include/vecl/broadcast.hpp
ethereal-sheep/vecl
519e8e90a1cd2c424f0a666e24da2d2ad3ffdcaf
[ "MIT" ]
null
null
null
#ifndef VECL_BROADCAST_H #define VECL_BROADCAST_H #include "config/config.h" #include <memory> #include <functional> #include <vector> #include <memory_resource> namespace vecl { /** * @brief A Broadcast is a smart event-handler that models a * broadcast design pattern. * * The container allows functions to listen to the broadcast. * The broadcast will invoke all functions that are listening * to it when triggered. * * A token is given to the listener when they listen to the broadcast. * It handles the lifetime of the listener within the container. * When the token goes out of scope, the listener dies and * will be automatically removed from the container. * * @tparam Callable Callable object type */ template<typename Callable> class broadcast { public: /** @brief type traits for container */ using callback = Callable; using token = std::shared_ptr<callback>; using allocator_type = std::pmr::polymorphic_allocator<std::byte>; /** * @note MEMBER FUNCTIONS */ /** * @brief Default Constructor. * * @param mr Pointer to a pmr resource. Default gets the default * global pmr resource via get_default_resource(). */ explicit broadcast( allocator_type mr = std::pmr::get_default_resource() ) : _listeners(mr) { } /** * @brief Default Copy Constructor. Uses same memory resource as * other. */ broadcast(const broadcast& other) = default; /** * @brief Memory-Extended Copy Constructor. Uses provided * memory_resource to allocate copied arrays from other. * * @param other Const-reference to other. * @param mr Pointer to a pmr resource. */ broadcast( const broadcast& other, allocator_type mr ) : _listeners(other._listeners, mr) { } /** * @brief Default Move Constructor. Constructs container with * the contents of other using move-semantics. After the move, other * is guaranteed to be empty. */ broadcast(broadcast&& other) = default; /** * @brief Memory-Extended Move Constructor. If memory_resource used * by other is not the same as memory_resource provided, the * construction resolves to a Memory-Extended copy construction. In * which case, other is not guranteed to be empty after the move. * * @param other Universal-reference to other. * @param mr Pointer to a pmr resource. */ broadcast( broadcast&& other, allocator_type mr ) : _listeners(std::move(other._listeners), mr) { } /** * @brief Copy-Assignment Operator. Uses same memory resource as * other. If the memory_resource of this is equal to that of other, * the memory owned by this may be reused when possible. * * @param other Const-reference to other. */ broadcast& operator=(const broadcast& other) = default; /** * @brief Move-Assignment Operator. Assigns contents of other using * move-semantics. After the move, other is guaranteed to be empty. * * @param other Universal-reference to other. */ broadcast& operator=(broadcast&& other) = default; /** * @return Copy of allocator_type object used by the container. */ VECL_NODISCARD allocator_type get_allocator() const VECL_NOEXCEPT { return _listeners.get_allocator(); } /** * @note CAPACITY */ /** * @return Number of listeners. * * @warning Size is only an approximation as there may be dead listeners * who have not been cleaned up. */ VECL_NODISCARD auto size() const VECL_NOEXCEPT { return _listeners.size(); } /** * @brief Checks if the container is empty. * * @warning Only an approximation as there may be dead listeners * who have not been cleaned up. */ VECL_NODISCARD bool empty() const VECL_NOEXCEPT { return _listeners.empty(); } /** * @note MODIFIERS */ /** * @brief Registers a function to listen to the broadcast. * * @param callable Callable object to be registered * * @return Listener token(shared_ptr). When the token goes out * of scope, the listener is revoked. */ VECL_NODISCARD token listen(Callable&& callable) { token handle = std::make_shared<callback>(callable); _listeners.push_back(handle); return handle; } /** * @brief Triggers a broadcast to all listeners. * * @tparam Args Variadic argument list * * @param args Variadic arguments to be passed to listeners. */ template<typename... Args> void trigger(Args&&... args) { for (auto weak : _listeners) { if (auto callable = weak.lock()) (*callable)(std::forward<Args>(args)...); } _listeners.erase( std::remove_if( _listeners.begin(), _listeners.end(), [](auto weak) { return weak.expired(); } ), _listeners.end()); } /** * @brief Swaps the contents of two broadcasts. The swap operation * of two broadcasts with different memory_resource is undefined. */ friend void swap(broadcast& lhs, broadcast& rhs) VECL_NOEXCEPT { std::swap(lhs._subs, rhs._subs); } private: using weak = std::weak_ptr<callback>; using listeners = std::pmr::vector<weak>; listeners _listeners; }; } #endif
24.088372
74
0.674068
ethereal-sheep
e66ccf5db157f828ccdc7aea66caca4da8442d63
320
hpp
C++
include/base64-cpp/detail/decode-common.hpp
contour-terminal/base64-cpp
885789cd7ec427cf63eef867f6c273eaa92b5d88
[ "Apache-2.0" ]
2
2021-07-11T21:03:13.000Z
2021-07-23T23:47:29.000Z
include/base64-cpp/detail/decode-common.hpp
contour-terminal/base64-cpp
885789cd7ec427cf63eef867f6c273eaa92b5d88
[ "Apache-2.0" ]
1
2021-08-03T05:51:53.000Z
2021-08-16T14:32:49.000Z
include/base64-cpp/detail/decode-common.hpp
contour-terminal/base64-cpp
885789cd7ec427cf63eef867f6c273eaa92b5d88
[ "Apache-2.0" ]
null
null
null
#pragma once #include <cstdint> #include <cstdlib> #include <string_view> namespace base64::detail::decoder { auto static const inline alphabet = std::string_view{"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}; struct invalid_input final { size_t const offset; uint8_t const byte; }; }
16.842105
121
0.76875
contour-terminal
e66d0362b11a8ef129db894387de321567d9e3fc
6,918
cpp
C++
Anime4KCore/src/ACOpenCL.cpp
king350023/Anime4KCPP
659442101b884108c24811de3c669283d2d8b20e
[ "MIT" ]
null
null
null
Anime4KCore/src/ACOpenCL.cpp
king350023/Anime4KCPP
659442101b884108c24811de3c669283d2d8b20e
[ "MIT" ]
null
null
null
Anime4KCore/src/ACOpenCL.cpp
king350023/Anime4KCPP
659442101b884108c24811de3c669283d2d8b20e
[ "MIT" ]
null
null
null
#define DLL #include "ACOpenCL.hpp" Anime4KCPP::OpenCL::GPUList::GPUList( const int platforms, std::vector<int> devices, std::string message ) :platforms(platforms), devices(std::move(devices)), message(std::move(message)) {} int Anime4KCPP::OpenCL::GPUList::operator[](int pID) const { return devices[pID]; } std::string& Anime4KCPP::OpenCL::GPUList::operator()() noexcept { return message; } Anime4KCPP::OpenCL::GPUInfo::GPUInfo(const bool supported, std::string message) : supported(supported), message(std::move(message)) {}; std::string& Anime4KCPP::OpenCL::GPUInfo::operator()() noexcept { return message; } Anime4KCPP::OpenCL::GPUInfo::operator bool() const noexcept { return supported; } Anime4KCPP::OpenCL::GPUList Anime4KCPP::OpenCL::listGPUs() { cl_int err = 0; cl_uint platforms = 0; cl_uint devices = 0; cl_platform_id* platform = nullptr; cl_device_id* device = nullptr; size_t platformNameLength = 0; size_t deviceNameLength = 0; char* platformName = nullptr; char* deviceName = nullptr; std::ostringstream msg; std::vector<int> devicesVector; err = clGetPlatformIDs(0, nullptr, &platforms); if (err != CL_SUCCESS || !platforms) return GPUList(0, { 0 }, "No suppoted platform"); platform = new cl_platform_id[platforms]; err = clGetPlatformIDs(platforms, platform, nullptr); if (err != CL_SUCCESS) { delete[] platform; return GPUList(0, { 0 }, "inital platform error"); } for (cl_uint i = 0; i < platforms; i++) { err = clGetPlatformInfo(platform[i], CL_PLATFORM_NAME, 0, nullptr, &platformNameLength); if (err != CL_SUCCESS) { delete[] platform; return GPUList(0, { 0 }, "Failed to get platform name length information"); } platformName = new char[platformNameLength]; err = clGetPlatformInfo(platform[i], CL_PLATFORM_NAME, platformNameLength, platformName, nullptr); if (err != CL_SUCCESS) { delete[] platformName; delete[] platform; return GPUList(0, { 0 }, "Failed to get platform name information"); } msg << "Platform " << i << ": " << platformName << std::endl; delete[] platformName; err = clGetDeviceIDs(platform[i], CL_DEVICE_TYPE_GPU, 0, nullptr, &devices); if (err != CL_SUCCESS || !devices) { if (platforms == 1) { delete[] platform; return GPUList(0, { 0 }, "No supported GPU"); } devicesVector.push_back(0); msg << " No supported GPU in this platform" << std::endl; continue; } devicesVector.push_back(devices); device = new cl_device_id[devices]; err = clGetDeviceIDs(platform[i], CL_DEVICE_TYPE_GPU, devices, device, nullptr); if (err != CL_SUCCESS) { delete[] device; delete[] platform; return GPUList(0, { 0 }, "inital GPU error"); } for (cl_uint j = 0; j < devices; j++) { err = clGetDeviceInfo(device[j], CL_DEVICE_NAME, 0, nullptr, &deviceNameLength); if (err != CL_SUCCESS) { delete[] device; delete[] platform; return GPUList(0, { 0 }, "Failed to get device name length information"); } deviceName = new char[deviceNameLength]; err = clGetDeviceInfo(device[j], CL_DEVICE_NAME, deviceNameLength, deviceName, nullptr); if (err != CL_SUCCESS) { delete[] deviceName; delete[] device; delete[] platform; return GPUList(0, { 0 }, "Failed to get device name information"); } msg << " Device " << j << ": " << deviceName << std::endl; delete[] deviceName; } delete[] device; } delete[] platform; return GPUList(platforms, devicesVector, msg.str()); } Anime4KCPP::OpenCL::GPUInfo Anime4KCPP::OpenCL::checkGPUSupport(unsigned int pID, unsigned int dID) { cl_int err = 0; cl_uint platforms = 0; cl_uint devices = 0; cl_platform_id firstPlatform = nullptr; cl_device_id device = nullptr; size_t platformNameLength = 0; size_t deviceNameLength = 0; char* platformName = nullptr; char* deviceName = nullptr; err = clGetPlatformIDs(0, nullptr, &platforms); if (err != CL_SUCCESS || !platforms) return GPUInfo(false, "No suppoted platform"); cl_platform_id* tmpPlatform = new cl_platform_id[platforms]; err = clGetPlatformIDs(platforms, tmpPlatform, nullptr); if (err != CL_SUCCESS) { delete[] tmpPlatform; return GPUInfo(false, "inital platform error"); } if (pID >= 0 && pID < platforms) firstPlatform = tmpPlatform[pID]; else firstPlatform = tmpPlatform[0]; delete[] tmpPlatform; err = clGetPlatformInfo(firstPlatform, CL_PLATFORM_NAME, 0, nullptr, &platformNameLength); if (err != CL_SUCCESS) return GPUInfo(false, "Failed to get platform name length information"); platformName = new char[platformNameLength]; err = clGetPlatformInfo(firstPlatform, CL_PLATFORM_NAME, platformNameLength, platformName, nullptr); if (err != CL_SUCCESS) { delete[] platformName; return GPUInfo(false, "Failed to get platform name information"); } err = clGetDeviceIDs(firstPlatform, CL_DEVICE_TYPE_GPU, 0, nullptr, &devices); if (err != CL_SUCCESS || !devices) { delete[] platformName; return GPUInfo(false, "No supported GPU"); } cl_device_id* tmpDevice = new cl_device_id[devices]; err = clGetDeviceIDs(firstPlatform, CL_DEVICE_TYPE_GPU, devices, tmpDevice, nullptr); if (err != CL_SUCCESS) { delete[] platformName; delete[] tmpDevice; return GPUInfo(false, "No supported GPU"); } if (dID >= 0 && dID < devices) device = tmpDevice[dID]; else device = tmpDevice[0]; delete[] tmpDevice; err = clGetDeviceInfo(device, CL_DEVICE_NAME, 0, nullptr, &deviceNameLength); if (err != CL_SUCCESS) { delete[] platformName; return GPUInfo(false, "Failed to get device name length information"); } deviceName = new char[deviceNameLength]; err = clGetDeviceInfo(device, CL_DEVICE_NAME, deviceNameLength, deviceName, nullptr); if (err != CL_SUCCESS) { delete[] deviceName; delete[] platformName; return GPUInfo(false, "Failed to get device name information"); } GPUInfo ret(true, std::string("Platform: ") + platformName + "\n" + " Device: " + deviceName); delete[] deviceName; delete[] platformName; return ret; }
29.564103
106
0.60769
king350023
e66d8f43e0402f89403e33ec0325b45b1e0c90de
3,124
cpp
C++
volume_I/acm_1096.cpp
raidenluikang/acm.timus.ru
9b7c99eb03959acff9dd96326eec642a2c31ed04
[ "MIT" ]
null
null
null
volume_I/acm_1096.cpp
raidenluikang/acm.timus.ru
9b7c99eb03959acff9dd96326eec642a2c31ed04
[ "MIT" ]
null
null
null
volume_I/acm_1096.cpp
raidenluikang/acm.timus.ru
9b7c99eb03959acff9dd96326eec642a2c31ed04
[ "MIT" ]
null
null
null
#include <cstdio> char in [ 65536 ]; char const* o; int a[ 1024 ]; int b[ 1024 ]; bool visit[1024] ; int que [ 1024 ] ; int dist[ 1024 ] ; int prv [ 1024 ]; int n; // number of bus int n_q; int nxt[ 2048 ] ; //int dst[ 2028 ] ; int head[2048 ] ; static int readInt() { int u = 0; while(*o && *o <= 32)++o; while(*o >= 48 && *o <= 57) u = (u << 3) + (u << 1) + (*o ++ - 48); return u; } int readData() { o = in; in[fread(in,1,sizeof(in)-4,stdin)] = 0; //1. n n = readInt(); for(int i = 1; i <= n; ++i) { a[i] = readInt(); b[i] = readInt(); } n_q = readInt(); a[n+1] = readInt(); b[n+1] = readInt(); return 0; } int bfs() { for(int i = 0 ;i != 1024; ++i) { visit[i] = false; prv[i] = 0; dist[i] = 1024; } for(int i = 0; i != 2048; ++i) head[i] = 0; for(int i= 1 ; i <=n;++i) { // i = 1 : p = 2 and 3 // i = 2 : p = 4 and 5 and etc. //++p; nxt[i] = head[a[i]]; head[a[i]] = i; //dst[ p ] = i; //++p; //nxt[p] = head[b[i]]; //head[b[i]] = p; } int h = 0, t = 0; que[t++] = n + 1; visit[n+1] = true; dist[n+1] = 0; while( h < t ) { int u = que[h++]; int au = a[u]; int bu = b[u]; for(int e = head[au]; e != 0; e = nxt[e]) { int v = e ; if (!visit[v]) { visit[v] = true; dist[v] = 1 + dist[u]; prv[v] = u; que[t++] = v; } } if (au != bu) { for(int e = head[bu]; e != 0; e = nxt[e]) { int v = e; if (!visit[v]) { visit[v] = true; dist[v] = 1 + dist[u]; prv[v] = u; que[t++] = v; } } } } int ans = 0; int deep = 1024; for(int i = 1; i <= n; ++i) { if (visit[i] && (n_q == a[i] || n_q == b[i])) { if ( deep > dist[ i ] ) { ans = i; deep = dist[i]; } } } return ans; } int writeData(int ans) { if (ans == 0) { puts("IMPOSSIBLE"); return 0; } int h = 0; int cur = ans; char * w = in + 16384; while(cur != n + 1) { ++h; // number of changes *--w = '\n'; int u = cur; do *--w = u % 10 + '0'; while(u/=10); cur = prv[cur]; } //now number of changes *--w = '\n'; do *--w = h % 10 + '0'; while(h/=10); fwrite(w, 1, in + 16384 - w, stdout); return 0; } int solve() { int ans; readData(); ans = bfs(); writeData(ans); return 0; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif solve(); return 0; }
18.057803
71
0.338668
raidenluikang
e670f1dce1004823bd8f2e342c2e7b076495df78
5,123
cpp
C++
cpp/include/math/matrix.cpp
kyuridenamida/competitive-library
a2bea434c4591359c208b865d2d4dc25574df24d
[ "MIT" ]
3
2017-04-09T10:12:31.000Z
2019-02-11T03:11:27.000Z
cpp/include/math/matrix.cpp
kyuridenamida/competitive-library
a2bea434c4591359c208b865d2d4dc25574df24d
[ "MIT" ]
null
null
null
cpp/include/math/matrix.cpp
kyuridenamida/competitive-library
a2bea434c4591359c208b865d2d4dc25574df24d
[ "MIT" ]
1
2019-11-29T06:11:10.000Z
2019-11-29T06:11:10.000Z
#pragma once #include "../util.hpp" template<typename T> class Vec { protected: using iterator = typename vector<T>::iterator; using const_iterator = typename vector<T>::const_iterator; using reference = T&; using const_reference = const T&; vector<T> v; template<typename Unop> Vec<T> unop_new(Unop op) const { Vec<T> res(v.size()); transform(begin(v), end(v), res.begin(), op); return res; } template<typename Binop> Vec<T>& binop(const Vec<T> &r, Binop op) { transform(r.begin(), r.end(), v.begin(), v.begin(), op); return *this; } template<typename Binop> Vec<T> binop_new(const Vec<T> &r, Binop op) const { Vec<T> res(v.size()); transform(r.begin(), r.end(), v.begin(), res.begin(), op); return res; } public: Vec(int n) : v(n) {} Vec(int n, const T &val) : v(n, val) {} Vec(const vector<T> &w) : v(w) {} int size() const noexcept { return v.size(); } const_iterator begin() const noexcept { return v.begin(); } const_iterator end() const noexcept { return v.end(); } iterator begin() noexcept { return v.begin(); } iterator end() noexcept { return v.end(); } reference operator[] (int i) { return v[i]; } const_reference operator[] (int i) const { return v[i]; } Vec<T> operator-() const { return unop_new([](T val){ return -val; }); }; Vec<T> &operator+=(const Vec<T> &r) { return binop(r, [](T x, T y) { return x + y; }); } Vec<T> &operator-=(const Vec<T> &r) { return binop(r, [](T x, T y) { return x - y; }); } Vec<T> operator+(const Vec<T> &r) const { return binop_new(r, [](T x, T y) { return x + y; }); } Vec<T> operator-(const Vec<T> &r) const { return binop_new(r, [](T x, T y) { return x - y; }); } T dot(const Vec<T> &r) const { return inner_product(v.begin(), v.end(), r.begin(), T(0)); } T norm() const { return this->dot(v); } void push_back(const T &r) { v.push_back(r); } void concat(const Vec<T> &r) { v.insert(v.end(), r.begin(), r.end()); } }; template<typename T> class Matrix : public Vec<Vec<T>> { public: using Vec<Vec<T>>::Vec; Matrix(int n, int m, const T &val) : Vec<Vec<T>>::Vec(n, Vec<T>(m, val)) {} int Y() const { return this->size(); } int X() const { return (*this)[0].size(); } Matrix<T> transpose() const { const int row = Y(), col = X(); Matrix res(col, row); for (int j = 0; j < col; ++j) { for (int i = 0; i < row; ++i) { res[j][i] = (*this)[i][j]; } } return res; } Matrix<T> operator*(const Matrix<T> &r) const { Matrix<T> tr = r.transpose(); const int row = Y(), col = tr.Y(); assert (X() == tr.X()); Matrix<T> res(row, col); for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { res[i][j] = (*this)[i].dot(tr[j]); } } return res; } Vec<T> operator*(const Vec<T> &r) const { const int row = Y(), col = r.Y(); assert (r.size() == col); Vec<T> res(row); for (int i = 0; i < row; ++i) { res[i] = (*this)[i].dot(r); } return res; } Matrix<T> &operator*=(const Matrix<T> &r) { return *this = *this * r; } Matrix<T> operator^(ll n) const { const int m = Y(); assert (m == X()); Matrix<T> A = *this, res(m, m, 0); for (int i = 0; i < m; ++i) res[i][i] = 1; while (n > 0) { if (n % 2) res *= A; A = A * A; n /= 2; } return res; } void concat_right(const Vec<T> &r) { const int n = Y(); assert (n == r.size()); for (int i = 0; i < n; ++i) { (*this)[i].push_back(r[i]); } } void concat_right(const Matrix<T> &r) { const int n = Y(); assert (n == r.Y()); for (int i = 0; i < n; ++i) { (*this)[i].concat(r[i]); } } void concat_below(const Vec<T> &r) { assert (Y() == 0 || X() == r.size()); this->push_back(r); } void concat_below(const Matrix<T> &r) { assert (Y() == 0 || X() == r.X()); for (Vec<T> i: r) (*this).push_back(i); } int rank() const { Matrix<T> A = *this; if (Y() == 0) return 0; const int n = Y(), m = X(); int r = 0; for (int i = 0; r < n && i < m; ++i) { int pivot = r; for (int j = r+1; j < n; ++j) { if (abs(A[j][i]) > abs(A[pivot][i])) pivot = j; } swap(A[pivot], A[r]); if (is_zero(A[r][i])) continue; for (int k = m-1; k >= i; --k) A[r][k] = A[r][k] / A[r][i]; for(int j = r+1; j < n; ++j) { for(int k = m-1; k >= i; --k) { A[j][k] -= A[r][k] * A[j][i]; } } ++r; } return r; } T det() const { const int n = Y(); if (n == 0) return 1; assert (Y() == X()); Matrix<T> A = *this; T D = 1; for (int i = 0; i < n; ++i) { int pivot = i; for (int j = i+1; j < n; ++j) { if (abs(A[j][i]) > abs(A[pivot][i])) pivot = j; } swap(A[pivot], A[i]); D = D * A[i][i] * T(i != pivot ? -1 : 1); if (is_zero(A[i][i])) break; for(int j = i+1; j < n; ++j) { for(int k = n-1; k >= i; --k) { A[j][k] -= A[i][k] * A[j][i] / A[i][i]; } } } return D; } };
28.943503
78
0.486824
kyuridenamida
e6747b18e969ed210e3bd2c2b55fee3281fa92c7
1,585
cpp
C++
gameuit-console-game-engine/Player.cpp
phuctm97/console-game-engine
b90f4bc50950d75491c82f18820a004e92fe38fe
[ "MIT" ]
null
null
null
gameuit-console-game-engine/Player.cpp
phuctm97/console-game-engine
b90f4bc50950d75491c82f18820a004e92fe38fe
[ "MIT" ]
null
null
null
gameuit-console-game-engine/Player.cpp
phuctm97/console-game-engine
b90f4bc50950d75491c82f18820a004e92fe38fe
[ "MIT" ]
1
2021-05-23T06:14:25.000Z
2021-05-23T06:14:25.000Z
#include "Player.h" #include "Game.h" Player::Player() { _width = 5; _height = 10; Game::getInstance()->registerInputNotification( CC_CALLBACK_1(Player::processInput, this) ); } Player::~Player() {} void Player::moveUp() { int y = getPositionY(); y -= 1; setPositionY( y ); } void Player::moveDown() { int y = getPositionY(); y += 1; setPositionY( y ); } void Player::setPositionX( int x ) { if ( x < 0 || x > Game::getInstance()->getWidth() - _width ) return; GameObject::setPositionX( x ); } void Player::setPositionY( int y ) { if ( y < 0 || y > Game::getInstance()->getHeight() - _height ) return; GameObject::setPositionY( y ); } int Player::getWidth() const { return _width; } void Player::setWidth( int width ) { if ( _width == width ) return; _width_old = _width; _width = width; _dirty = true; } int Player::getHeight() const { return _height; } void Player::setHeight( int height ) { if ( _height == height ) return; _height_old = _height; _height = height; _dirty = true; } void Player::childUpdate() {} void Player::childRender() { for ( int i = 0; i < _height_old; i++ ) { Console::setCursor( _positionX_old, _positionY_old + i ); for ( int j = 0; j < _width_old; j++ ) { std::cout << char( 0x20 ); } } for ( int i = 0; i < _height; i++ ) { Console::setCursor( _positionX, _positionY + i ); for ( int j = 0; j < _width; j++ ) { std::cout << char( 178 ); } } } void Player::childReset() { GameObject::reset(); _width_old = _width; _height_old = _height; } void Player::processInput( int pressedKey ) { }
16.684211
93
0.624606
phuctm97
e67e6a7eef68204b34ac5e6b2f6ebad8deca1b6d
7,262
cpp
C++
main.cpp
jiangzhuti/DMProxy
0a95e5173079eca6b61e7661b3f4d5d3a2ae08a6
[ "WTFPL" ]
null
null
null
main.cpp
jiangzhuti/DMProxy
0a95e5173079eca6b61e7661b3f4d5d3a2ae08a6
[ "WTFPL" ]
null
null
null
main.cpp
jiangzhuti/DMProxy
0a95e5173079eca6b61e7661b3f4d5d3a2ae08a6
[ "WTFPL" ]
null
null
null
#include <map> #include <set> #include <sstream> #include <memory> #include <utility> #include <tuple> #include <boost/program_options.hpp> #include <boost/asio.hpp> #include <boost/algorithm/string.hpp> #include "network/dmp_cs.hpp" #include "platforms/platforms.hpp" #include "utils/others.hpp" #include "utils/rw_lock.hpp" //use 'static' to prevent clang for generating -Wmissing-variable-declarations warnings static int server_threads, client_threads; static uint16_t server_port; static std::string server_host; static std::string uri; static boost::asio::io_service server_io_service; static boost::asio::io_service platform_io_service; //STL Containers are thread-safe for concurrent read, so need a rw lock //see https://stackoverflow.com/questions/7455982/is-stl-vector-concurrent-read-thread-safe typedef std::map<std::string, platform_base_ptr_t> roomstr_platform_map; static roomstr_platform_map rp_map; static rw_mutex_t rp_rw_mtx; namespace po = boost::program_options; void on_platform_close(std::string roomstr) { wlock_t wlock(rp_rw_mtx); rp_map.erase(roomstr); } void on_server_close(std::string roomstr, connection_hdl hdl) { wlock_t wlock(rp_rw_mtx); if (rp_map.count(roomstr) == 0) { return; } auto pbase = rp_map[roomstr]; pbase->erase_listener(hdl); if (pbase->listeners_count() == 0) { pbase->close(); rp_map.erase(roomstr); } } void on_server_message(std::string old_roomstr, connection_hdl hdl, message_ptr msg) { if (msg->get_opcode() != opcode::TEXT) { //ignored; return; } std::error_code ec; //payload format :: "platform-tag" + "_" + "roomid" std::string roomstr = msg->get_payload(); boost::trim(roomstr); auto pos = roomstr.find_first_of('_'); if (!(roomstr.length() > 3 && pos > 0 && pos < roomstr.length() - 1)) { server.send(hdl, std::string("format error!"), opcode::TEXT, ec); SERVER_CLOSE_AND_REPORT_WHEN_ERROR(ec, hdl); return; } std::string tag = std::string(roomstr, 0, pos); std::string roomid = std::string(roomstr, pos + 1); platform_base_ptr_t pbase; wlock_t rp_wlock(rp_rw_mtx); if (old_roomstr == roomstr && rp_map.count(old_roomstr) != 0) return; auto s_conn = server.get_con_from_hdl(hdl); s_conn->set_message_handler(std::bind(on_server_message, roomstr, std::placeholders::_1, std::placeholders::_2)); if (rp_map.count(old_roomstr) != 0) { auto old_pbase = rp_map[old_roomstr]; old_pbase->erase_listener(hdl); if (old_pbase->listeners_count() == 0) { old_pbase->close(); rp_map.erase(old_roomstr); } } if (rp_map.count(roomstr) != 0) { pbase = rp_map[roomstr]; if (!pbase->have_listener(hdl)) { pbase->add_listener(hdl); return; } } else { pbase = platform_get_instance(tag, platform_io_service, roomid); if (pbase == nullptr) { server.send(hdl, std::string("platform ") + tag + std::string(" is not valid!"), opcode::TEXT, ec); SERVER_CLOSE_AND_REPORT_WHEN_ERROR(ec, hdl); return; } websocketpp::lib::error_code ec; if (!pbase->is_room_valid()) { server.send(hdl, std::string("roomid invalid!"), opcode::TEXT, ec); SERVER_CLOSE_AND_REPORT_WHEN_ERROR(ec, hdl); return; } } auto conn_ptr = server.get_con_from_hdl(hdl); conn_ptr->set_close_handler(std::bind(on_server_close, roomstr, std::placeholders::_1)); pbase->add_listener(hdl); pbase->set_close_callback(on_platform_close);\ rp_map[roomstr] = pbase; pbase->start(); } int main(int argc, char *argv[]) { po::options_description desc("Allowed Options:"); desc.add_options() ("help", "Produce help message") ("server-host", po::value<std::string>(&server_host)->default_value("localhost"), "Set the DMProxy server port, default to 9001") ("server-port", po::value<uint16_t>(&server_port)->default_value(9001), "Set the DMProxy server port, default to 9001") ("server-threads", po::value<int>(&server_threads)->default_value(3), "Set the number of the DMProxy server io_service threads, defalut to 3") ("client-threads", po::value<int>(&client_threads)->default_value(3), "Set the number of the DMProxy client io_service threads, defalut to 3"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << std::endl; return 1; } platforms_init(); try { server.clear_access_channels(websocketpp::log::alevel::all); server.clear_error_channels(websocketpp::log::alevel::all); server.init_asio(&server_io_service); server.set_reuse_addr(true); server.set_message_handler(std::bind(on_server_message, std::string(), std::placeholders::_1, std::placeholders::_2)); server.set_socket_init_handler([](connection_hdl, boost::asio::ip::tcp::socket & s) { boost::asio::ip::tcp::no_delay option(true); s.set_option(option); }); server.set_listen_backlog(8192); server.listen(server_host, std::to_string(server_port)); server.start_accept(); client.clear_access_channels(websocketpp::log::alevel::all); client.clear_error_channels(websocketpp::log::alevel::all); client.set_user_agent("Mozilla/5.0 (X11; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0"); client.init_asio(&platform_io_service); boost::asio::io_service::work platform_work(platform_io_service); typedef websocketpp::lib::shared_ptr<std::thread> thread_ptr; std::vector<thread_ptr> s_ts, c_ts; for (auto i = 0; i < server_threads; i++) { s_ts.push_back(std::make_shared<std::thread>([&]() { server_io_service.run(); std::cout << "server thread returned\n"; })); } for (auto i = 0; i < client_threads; i++) { c_ts.push_back(std::make_shared<std::thread>([&]() { platform_io_service.run(); std::cout << "client thread returned\n"; })); } for (auto i : s_ts) { i->join(); } for (auto i : c_ts) { i->join(); } } catch (websocketpp::exception const &e) { std::cout << "Exception:" << e.what() <<std::endl; } return 0; }
39.043011
155
0.576012
jiangzhuti
e680e9aa39e997fe9a04909728b929bce7da9ac2
7,386
cpp
C++
src/api/JavaIntegration.cpp
davidcorbin/mygcc-application
9e978e4d6e4cd3d8534bbc73f38c45b205258cc9
[ "MIT" ]
2
2019-01-18T02:33:45.000Z
2019-02-01T23:44:05.000Z
src/api/JavaIntegration.cpp
davidcorbin/mygcc-application
9e978e4d6e4cd3d8534bbc73f38c45b205258cc9
[ "MIT" ]
null
null
null
src/api/JavaIntegration.cpp
davidcorbin/mygcc-application
9e978e4d6e4cd3d8534bbc73f38c45b205258cc9
[ "MIT" ]
null
null
null
/** * Copyright 2018 <David Corbin, Mitchell Harvey> */ #include <include/api/JavaIntegration.hpp> #include <include/FileNotFound.hpp> #include <QDesktopServices> #include <QUrl> #include <QFileInfo> #include <QTextStream> #include <QDebug> #include <QSettings> #include <QApplication> #include <string> #include <algorithm> #include <random> #include <regex> // NOLINT #define MYGCC_API_FILENAME "mygcc-api-jar-with-dependencies.jar" #define VALID_JAVA_VER_REG "1.8|10" #define JAVA_PATH_MAC "/Library/Internet Plug-Ins/JavaAppletPlugin." \ "plugin/Contents/Home/bin/java" #define INSTALL_JAVA_SITE "https://facadeapp.cc/installjava8" JavaIntegration::JavaIntegration() { fm = new FileManager; } void JavaIntegration::startAPIThread() { auto *initvect = getInitVect(); auto *enckey = getEncKey(); qputenv("initvect", initvect->c_str()); qputenv("enckey", enckey->c_str()); startAPIServerCmd(); } void JavaIntegration::startAPIServerCmd() { std::string jarPath = fm->getResourcePath(MYGCC_API_FILENAME); auto *javaPath = findJava(); if (!javaPath->empty()) { if (checkJavaVersion(javaPath)) { qDebug() << "Valid Java version found at" << javaPath->c_str(); std::string fullStr = "\"" + *javaPath + "\" -cp \"" + jarPath + "\" com.mygcc.api.Main"; qDebug() << "Starting API with command:" << fullStr.c_str(); javaProcess.start(fullStr.c_str()); } else { qDebug() << "Invalid java version"; // Open site to show user how to install java QDesktopServices::openUrl(QUrl(INSTALL_JAVA_SITE)); qApp->exit(1); } } else { qDebug("%s", "Could not start java server"); // Open site to show user how to install java QDesktopServices::openUrl(QUrl(INSTALL_JAVA_SITE)); qApp->exit(1); } } int JavaIntegration::stopAPIServerCmd() { javaProcess.close(); return 0; } int JavaIntegration::getAPIPort() { return 8080; } std::string* JavaIntegration::findJava() { // Use the standard path for finding java on macOS #if defined(__APPLE__) || defined(__MACH__) qDebug() << "Checking for java at known macOS path" << JAVA_PATH_MAC; QFileInfo check_file(JAVA_PATH_MAC); if (check_file.exists()) { qDebug() << "Known macOS java path found"; return new std::string(JAVA_PATH_MAC); } else { qDebug() << "Known macOS java path NOT found"; return new std::string(""); } #endif // User registry keys for finding java on Windows #if defined(_WIN32) || defined(_WIN64) // 64 bit registry key QSettings jreKey64("HKEY_LOCAL_MACHINE\\SOFTWARE" \ "\\JavaSoft\\Java Runtime Environment", QSettings::Registry64Format); // 32 bit registry key QSettings jreKey32("HKEY_LOCAL_MACHINE\\Software\\WOW6432Node" \ "\\JavaSoft\\Java Runtime Environment", QSettings::Registry32Format); // If JAVA installed if (jreKey32.allKeys().contains("CurrentVersion", Qt::CaseInsensitive) || jreKey64.allKeys().contains("CurrentVersion", Qt::CaseInsensitive)) { QSettings *jreKey; if (jreKey32.allKeys().contains("CurrentVersion", Qt::CaseInsensitive)) { qDebug("32 bit Java FOUND"); jreKey = &jreKey32; } if (jreKey64.allKeys().contains("CurrentVersion", Qt::CaseInsensitive)) { qDebug("64 bit JAVA FOUND"); jreKey = &jreKey64; } auto version = jreKey->value("CurrentVersion").toString(); qDebug() << "Latest java version identified:" << version.toStdString().c_str(); if (version.contains("1.8")) { QSettings jreVerKey(jreKey->fileName() + "\\" + version, QSettings::Registry64Format); if (jreVerKey.childKeys().contains("JavaHome", Qt::CaseInsensitive)) { auto javaHome = jreVerKey.value("JavaHome").toString(); qDebug() << "Java home identified:" << javaHome.toStdString().c_str(); return new std::string(javaHome.toStdString() + "\\bin\\java.exe"); } else { qWarning("JavaHome key NOT FOUND"); } } else { qWarning("Java version '1.8' NOT FOUND"); } } else { qWarning("Java NOT FOUND in default install path"); } return new std::string(""); #endif #if defined(__unix) || defined(__unix__) || defined(__linux__) // Check for java in $PATH QProcess findJavaExe; findJavaExe.start("java"); bool started = findJavaExe.waitForStarted(); QByteArray stdoutput; do { stdoutput += findJavaExe.readAllStandardOutput(); } while (!findJavaExe.waitForFinished(100) && findJavaExe.isOpen()); // If java executable in path if (started) { return new std::string("java"); } else { return new std::string(""); } #endif } bool JavaIntegration::checkJavaVersion(std::string *javaPath) { auto *path = new std::string(javaPath->c_str()); QProcess javaInPath; javaInPath.start(("\"" + *path + "\" -version").c_str()); javaInPath.waitForFinished(); QString out(javaInPath.readAllStandardError()); auto output = out.toStdString(); std::string line(output.begin(), std::find(output.begin(), output.end(), '\n')); qDebug("%s", line.c_str()); std::regex re(VALID_JAVA_VER_REG); return std::regex_search(line, re); } std::string* JavaIntegration::getInitVect() { try { QString ivpath = QString::fromStdString(fm->getDataPath("initvect")); qDebug() << "Initialization vector path: " << ivpath; QFile file(ivpath); if (file.open(QIODevice::ReadOnly)) { QTextStream in(&file); std::string line = in.readLine().toStdString(); file.close(); return new std::string(line.c_str()); } } catch (FileNotFound &e) { // Generate init vect auto *initvect = reinterpret_cast<char *>(malloc(sizeof(char) * 17)); genRandomString(initvect); QString datadir = QString::fromStdString(fm->getDataDir()); QFile file(datadir + "/initvect"); // Open file if (file.open(QIODevice::ReadWrite)) { QTextStream stream(&file); stream << initvect << endl; } std::string stdinitvect(initvect); return new std::string(stdinitvect.c_str()); } return nullptr; } std::string* JavaIntegration::getEncKey() { try { QString ivpath = QString::fromStdString(fm->getDataPath("enckey")); qDebug() << "Encryption key path: " << ivpath; QFile file(ivpath); if (file.open(QIODevice::ReadOnly)) { QTextStream in(&file); auto line = in.readLine().toStdString(); file.close(); return new std::string(line.c_str()); } } catch (FileNotFound &e) { // Generate encryption key auto *initvect = reinterpret_cast<char *>(malloc(sizeof(char) * 17)); genRandomString(initvect); QString datadir = QString::fromStdString(fm->getDataDir()); QFile file(datadir + "/enckey"); // Open file if (file.open(QIODevice::ReadWrite)) { QTextStream stream(&file); stream << initvect << endl; } std::string stdenckey(initvect); return new std::string(stdenckey.c_str()); } return nullptr; } void JavaIntegration::genRandomString(char *s, int size) { std::random_device rd; std::mt19937 mt(rd()); std::uniform_real_distribution<> dist(1, 26); static const char alphanum[] = "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < size; ++i) { s[i] = alphanum[static_cast<int>(dist(mt)) % (sizeof(alphanum) - 1)]; } s[size] = 0; }
30.647303
78
0.653804
davidcorbin
e697b4d120c2cb38fccd361679dd9388b4d1da22
1,435
cpp
C++
Range Queries/Pizzeria Queries.cpp
DecSP/cses-downloader
12a8f37665a33f6f790bd2c355f84dea8a0e332c
[ "MIT" ]
2
2022-02-12T12:30:13.000Z
2022-02-12T13:59:20.000Z
Range Queries/Pizzeria Queries.cpp
DecSP/cses-downloader
12a8f37665a33f6f790bd2c355f84dea8a0e332c
[ "MIT" ]
2
2022-02-12T11:09:41.000Z
2022-02-12T11:55:49.000Z
Range Queries/Pizzeria Queries.cpp
DecSP/cses-downloader
12a8f37665a33f6f790bd2c355f84dea8a0e332c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define ll long long using namespace std; const int INF=2e9; void buildTree(int v, int tl, int tr,vector<int>&st,vector<int>&a){ if (tl==tr){ st[v]=a[tl]; return; } int mid = (tl+tr)>>1; buildTree(v*2,tl,mid,st,a); buildTree(v*2+1,mid+1,tr,st,a); st[v]=min(st[v*2],st[v*2+1]); } int get(int v, int l, int r, int tl, int tr,vector<int>&st){ if (l>r) return INF; if (tl==l&&tr==r)return st[v]; int mid=(tl+tr)>>1; return min(get(v*2,l,min(mid,r),tl,mid,st),get(v*2+1,max(l,mid+1),r,mid+1,tr,st)); } void update(int v, int tl, int tr, int pos,vector<int>&st,vector<int>&a){ if (tl==tr){ st[v]=a[pos]; return; } int mid=(tl+tr)>>1; if (pos<=mid) update(v*2,tl,mid,pos,st,a); else update(v*2+1,mid+1,tr,pos,st,a); st[v]=min(st[v*2],st[v*2+1]); } int main(){ ios::sync_with_stdio(false);cin.tie(NULL); int n,q; cin>>n>>q; vector<int> a1(n),a2(n),a(n); for(int i=0;i<n;++i){ cin>>a[i]; a1[i]=a[i]-i-1; a2[i]=a[i]-n+i; } vector<int>st1(n*4),st2(n*4); buildTree(1,0,n-1,st1,a1); buildTree(1,0,n-1,st2,a2); for (int i=0;i<q;++i){ int t,pos;cin>>t>>pos;--pos; if (t==2){ int re1=get(1,0,pos,0,n-1,st1)-a1[pos]; int re2=get(1,pos,n-1,0,n-1,st2)-a2[pos]; cout<<min(re1,re2)+a[pos]<<'\n'; } else { int val;cin>>val; a1[pos]+=val-a[pos]; a2[pos]+=val-a[pos]; a[pos]=val; update(1,0,n-1,pos,st1,a1); update(1,0,n-1,pos,st2,a2); } } return 0; }
22.076923
83
0.570035
DecSP
e69af1c7058358166fb3546346080ab385e380b6
2,439
cpp
C++
flow/walker/serial_node_walker.cpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
1
2017-08-11T19:12:24.000Z
2017-08-11T19:12:24.000Z
flow/walker/serial_node_walker.cpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
11
2018-07-07T20:09:44.000Z
2020-02-16T22:45:09.000Z
flow/walker/serial_node_walker.cpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
null
null
null
//------------------------------------------------------------ // snakeoil (c) Alexis Constantin Link // Distributed under the MIT license //------------------------------------------------------------ #include "serial_node_walker.h" using namespace so_flow ; //********************************************************************************************** serial_node_walker::serial_node_walker( void_t ) {} //********************************************************************************************** serial_node_walker::serial_node_walker( this_rref_t ) {} //********************************************************************************************** serial_node_walker::~serial_node_walker( void_t ) {} //********************************************************************************************** serial_node_walker::this_ptr_t serial_node_walker::create( so_memory::purpose_cref_t p ) { return so_flow::memory::alloc( this_t(), p ) ; } //********************************************************************************************** void_t serial_node_walker::destroy( this_ptr_t ptr ) { so_flow::memory::dealloc( ptr ) ; } //********************************************************************************************** void_t serial_node_walker::walk( so_flow::inode::nodes_rref_t init_nodes ) { // trigger { so_flow::inode::nodes_t nodes = init_nodes ; while(nodes.size() != 0) { so_flow::inode::nodes_t inner_nodes = std::move( nodes ) ; for(so_flow::inode_ptr_t nptr : inner_nodes) { nptr->on_trigger( nodes ) ; } } } // update { so_flow::inode::nodes_t nodes = init_nodes ; while(nodes.size() != 0) { so_flow::inode::nodes_t inner_nodes = std::move( nodes ) ; for(so_flow::inode_ptr_t nptr : inner_nodes) { nptr->on_update( nodes ) ; } } } } //********************************************************************************************** void_t serial_node_walker::walk( so_flow::inode::nodes_cref_t init_nodes ) { so_flow::inode::nodes_t nodes = init_nodes ; this_t::walk( std::move(nodes) ) ; } //********************************************************************************************** void_t serial_node_walker::destroy( void_t ) { this_t::destroy( this ) ; }
32.52
96
0.388684
aconstlink
e69c6bea04a01f6f89963ff6a688ded77cbf26d1
3,279
hpp
C++
Test/TestCommon/TestFunction.hpp
SpaceGameEngine/SpaceGameEngine
cc7bbadbc3ed9577d1d6c9b4470d2c4926ed5ef8
[ "Apache-2.0" ]
3
2019-11-25T04:08:44.000Z
2020-08-13T09:53:43.000Z
Test/TestCommon/TestFunction.hpp
SpaceGameEngine/SpaceGameEngine
cc7bbadbc3ed9577d1d6c9b4470d2c4926ed5ef8
[ "Apache-2.0" ]
3
2019-07-11T09:20:43.000Z
2021-01-17T10:21:22.000Z
Test/TestCommon/TestFunction.hpp
SpaceGameEngine/SpaceGameEngine
cc7bbadbc3ed9577d1d6c9b4470d2c4926ed5ef8
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021 creatorlxd 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. */ #pragma once #include "Function.hpp" #include "gtest/gtest.h" using namespace SpaceGameEngine; void func_(int i) { } void func_2(int i, int i2) { } int func_3(int i, int i2) { return 0; } struct functor { int operator()() { return 1; } }; struct test_func_class { int test() { return 1; } int test2() const { return 2; } }; TEST(Function, IsCorrectFunctionTest) { ASSERT_TRUE((IsCorrectFunction<decltype(func_), void(int)>::Value)); ASSERT_FALSE((IsCorrectFunction<decltype(func_2), void(int)>::Value)); ASSERT_TRUE((IsCorrectFunction<decltype(func_2), void(int, int)>::Value)); ASSERT_FALSE((IsCorrectFunction<decltype(func_3), void(int, int)>::Value)); ASSERT_TRUE((IsCorrectFunction<decltype(func_3), int(int, int)>::Value)); ASSERT_TRUE((IsCorrectFunction<functor, int(void)>::Value)); ASSERT_FALSE((IsCorrectFunction<int, void()>::Value)); ASSERT_TRUE((IsCorrectFunction<decltype(&test_func_class::test), int(test_func_class*)>::Value)); ASSERT_TRUE((IsCorrectFunction<decltype(&test_func_class::test2), int(const test_func_class*)>::Value)); } TEST(Function, IsFunctionTest) { Function<void()> func([]() {}); ASSERT_TRUE(Function<void()>::IsFunction<decltype(func)>::Value); ASSERT_TRUE(!Function<void()>::IsFunction<int>::Value); } TEST(Function, ConstructionTest) { auto lambda = [](void) -> int { return 1; }; Function<int(void)> func(lambda); ASSERT_TRUE((int (*)(void))lambda == (int (*)(void))func.Get<decltype(lambda)>()); ASSERT_TRUE(lambda() == func()); Function<int(void)> func2 = func; ASSERT_TRUE((int (*)(void))func2.Get<decltype(lambda)>() == (int (*)(void))func.Get<decltype(lambda)>()); Function<int(void)> func3([]() -> int { return 2; }); func3 = func2; ASSERT_TRUE(func3() == func2()); Function<void(int)> func5 = &func_; // use function pointer ASSERT_TRUE(func5.Get<decltype(&func_)>() == &func_); Function<int(test_func_class*)> func6 = &test_func_class::test; test_func_class tc; ASSERT_TRUE(func6(&tc) == tc.test()); Function<int(void)> func7 = functor(); ASSERT_TRUE(func7() == functor()()); // use functor Function<int(int)> func8 = [](int i) { return i; }; ASSERT_TRUE(func8(1) == 1); } TEST(Function, MetaDataTest) { Function<void(int)> func(&func_); ASSERT_TRUE(func.GetMetaData() == GetMetaData<decltype(&func_)>()); } TEST(Function, ComparisionTest) { Function<void(int)> func(&func_); Function<void(int)> func2 = func; ASSERT_EQ(func, func2); } TEST(Function, CopyTest) { Function<void(int)> func(&func_); Function<void(int), MemoryManagerAllocator> func2([](int) -> void {}); Function<void(int), StdAllocator> func3([](int) -> void {}); func2 = func; func3 = func2; ASSERT_EQ(func, func2); ASSERT_EQ(func2, func3); }
29.017699
105
0.705398
SpaceGameEngine
e69e9d7b12708f9aaa96c03cfcc653303225302b
16,151
hpp
C++
include/codegen/include/GlobalNamespace/LevelSelectionNavigationController.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/GlobalNamespace/LevelSelectionNavigationController.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/GlobalNamespace/LevelSelectionNavigationController.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: HMUI.NavigationController #include "HMUI/NavigationController.hpp" // Including type: StandardLevelDetailViewController/ContentType #include "GlobalNamespace/StandardLevelDetailViewController.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: LoadingControl class LoadingControl; // Forward declaring type: LevelCollectionViewController class LevelCollectionViewController; // Forward declaring type: LevelPackDetailViewController class LevelPackDetailViewController; // Skipping declaration: StandardLevelDetailViewController because it is already included! // Forward declaring type: AppStaticSettingsSO class AppStaticSettingsSO; // Forward declaring type: IBeatmapLevelPack class IBeatmapLevelPack; // Forward declaring type: IBeatmapLevel class IBeatmapLevel; // Forward declaring type: IDifficultyBeatmap class IDifficultyBeatmap; // Forward declaring type: IPreviewBeatmapLevel class IPreviewBeatmapLevel; // Forward declaring type: IAnnotatedBeatmapLevelCollection class IAnnotatedBeatmapLevelCollection; // Forward declaring type: IBeatmapLevelCollection class IBeatmapLevelCollection; } // Forward declaring namespace: System namespace System { // Forward declaring type: Action`2<T1, T2> template<typename T1, typename T2> class Action_2; // Forward declaring type: Action`2<T1, T2> template<typename T1, typename T2> class Action_2; // Forward declaring type: Action`1<T> template<typename T> class Action_1; // Forward declaring type: Action`2<T1, T2> template<typename T1, typename T2> class Action_2; // Forward declaring type: Action`2<T1, T2> template<typename T1, typename T2> class Action_2; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: GameObject class GameObject; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Autogenerated type: LevelSelectionNavigationController class LevelSelectionNavigationController : public HMUI::NavigationController { public: // Nested type: GlobalNamespace::LevelSelectionNavigationController::$$c__DisplayClass42_0 class $$c__DisplayClass42_0; // private LoadingControl _loadingControl // Offset: 0x90 GlobalNamespace::LoadingControl* loadingControl; // private LevelCollectionViewController _levelCollectionViewController // Offset: 0x98 GlobalNamespace::LevelCollectionViewController* levelCollectionViewController; // private LevelPackDetailViewController _levelPackDetailViewController // Offset: 0xA0 GlobalNamespace::LevelPackDetailViewController* levelPackDetailViewController; // private StandardLevelDetailViewController _levelDetailViewController // Offset: 0xA8 GlobalNamespace::StandardLevelDetailViewController* levelDetailViewController; // private AppStaticSettingsSO _appStaticSettings // Offset: 0xB0 GlobalNamespace::AppStaticSettingsSO* appStaticSettings; // private System.Action`2<LevelSelectionNavigationController,StandardLevelDetailViewController/ContentType> didPresentDetailContentEvent // Offset: 0xB8 System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::StandardLevelDetailViewController::ContentType>* didPresentDetailContentEvent; // private System.Action`2<LevelSelectionNavigationController,IBeatmapLevelPack> didSelectLevelPackEvent // Offset: 0xC0 System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IBeatmapLevelPack*>* didSelectLevelPackEvent; // private System.Action`1<LevelSelectionNavigationController> didPressPlayButtonEvent // Offset: 0xC8 System::Action_1<GlobalNamespace::LevelSelectionNavigationController*>* didPressPlayButtonEvent; // private System.Action`2<LevelSelectionNavigationController,IBeatmapLevelPack> didPressOpenPackButtonEvent // Offset: 0xD0 System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IBeatmapLevelPack*>* didPressOpenPackButtonEvent; // private System.Action`2<LevelSelectionNavigationController,IBeatmapLevel> didPressPracticeButtonEvent // Offset: 0xD8 System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IBeatmapLevel*>* didPressPracticeButtonEvent; // private System.Action`2<LevelSelectionNavigationController,IDifficultyBeatmap> didChangeDifficultyBeatmapEvent // Offset: 0xE0 System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IDifficultyBeatmap*>* didChangeDifficultyBeatmapEvent; // private System.Boolean _showPlayerStatsInDetailView // Offset: 0xE8 bool showPlayerStatsInDetailView; // private System.Boolean _showPracticeButtonInDetailView // Offset: 0xE9 bool showPracticeButtonInDetailView; // private IBeatmapLevelPack _levelPack // Offset: 0xF0 GlobalNamespace::IBeatmapLevelPack* levelPack; // private IPreviewBeatmapLevel _beatmapLevelToBeSelectedAfterPresent // Offset: 0xF8 GlobalNamespace::IPreviewBeatmapLevel* beatmapLevelToBeSelectedAfterPresent; // public System.Void add_didPresentDetailContentEvent(System.Action`2<LevelSelectionNavigationController,StandardLevelDetailViewController/ContentType> value) // Offset: 0xBF6CE8 void add_didPresentDetailContentEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::StandardLevelDetailViewController::ContentType>* value); // public System.Void remove_didPresentDetailContentEvent(System.Action`2<LevelSelectionNavigationController,StandardLevelDetailViewController/ContentType> value) // Offset: 0xBF7438 void remove_didPresentDetailContentEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::StandardLevelDetailViewController::ContentType>* value); // public System.Void add_didSelectLevelPackEvent(System.Action`2<LevelSelectionNavigationController,IBeatmapLevelPack> value) // Offset: 0xBF6AFC void add_didSelectLevelPackEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IBeatmapLevelPack*>* value); // public System.Void remove_didSelectLevelPackEvent(System.Action`2<LevelSelectionNavigationController,IBeatmapLevelPack> value) // Offset: 0xBF724C void remove_didSelectLevelPackEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IBeatmapLevelPack*>* value); // public System.Void add_didPressPlayButtonEvent(System.Action`1<LevelSelectionNavigationController> value) // Offset: 0xBF6BA0 void add_didPressPlayButtonEvent(System::Action_1<GlobalNamespace::LevelSelectionNavigationController*>* value); // public System.Void remove_didPressPlayButtonEvent(System.Action`1<LevelSelectionNavigationController> value) // Offset: 0xBF72F0 void remove_didPressPlayButtonEvent(System::Action_1<GlobalNamespace::LevelSelectionNavigationController*>* value); // public System.Void add_didPressOpenPackButtonEvent(System.Action`2<LevelSelectionNavigationController,IBeatmapLevelPack> value) // Offset: 0xBF6D8C void add_didPressOpenPackButtonEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IBeatmapLevelPack*>* value); // public System.Void remove_didPressOpenPackButtonEvent(System.Action`2<LevelSelectionNavigationController,IBeatmapLevelPack> value) // Offset: 0xBF74DC void remove_didPressOpenPackButtonEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IBeatmapLevelPack*>* value); // public System.Void add_didPressPracticeButtonEvent(System.Action`2<LevelSelectionNavigationController,IBeatmapLevel> value) // Offset: 0xBF6C44 void add_didPressPracticeButtonEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IBeatmapLevel*>* value); // public System.Void remove_didPressPracticeButtonEvent(System.Action`2<LevelSelectionNavigationController,IBeatmapLevel> value) // Offset: 0xBF7394 void remove_didPressPracticeButtonEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IBeatmapLevel*>* value); // public System.Void add_didChangeDifficultyBeatmapEvent(System.Action`2<LevelSelectionNavigationController,IDifficultyBeatmap> value) // Offset: 0xBF6A58 void add_didChangeDifficultyBeatmapEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IDifficultyBeatmap*>* value); // public System.Void remove_didChangeDifficultyBeatmapEvent(System.Action`2<LevelSelectionNavigationController,IDifficultyBeatmap> value) // Offset: 0xBF71A8 void remove_didChangeDifficultyBeatmapEvent(System::Action_2<GlobalNamespace::LevelSelectionNavigationController*, GlobalNamespace::IDifficultyBeatmap*>* value); // public IDifficultyBeatmap get_selectedDifficultyBeatmap() // Offset: 0xBF787C GlobalNamespace::IDifficultyBeatmap* get_selectedDifficultyBeatmap(); // public System.Void SetData(IAnnotatedBeatmapLevelCollection annotatedBeatmapLevelCollection, System.Boolean showPackHeader, System.Boolean showPlayerStats, System.Boolean showPracticeButton, UnityEngine.GameObject noDataInfoPrefab) // Offset: 0xBF7B40 void SetData(GlobalNamespace::IAnnotatedBeatmapLevelCollection* annotatedBeatmapLevelCollection, bool showPackHeader, bool showPlayerStats, bool showPracticeButton, UnityEngine::GameObject* noDataInfoPrefab); // public System.Void SelectLevel(IPreviewBeatmapLevel beatmapLevel) // Offset: 0xBF6E30 void SelectLevel(GlobalNamespace::IPreviewBeatmapLevel* beatmapLevel); // private System.Void SetData(IBeatmapLevelPack levelPack, System.Boolean showPackHeader, System.Boolean showPlayerStats, System.Boolean showPracticeButton) // Offset: 0xBF8654 void SetData(GlobalNamespace::IBeatmapLevelPack* levelPack, bool showPackHeader, bool showPlayerStats, bool showPracticeButton); // private System.Void SetData(IBeatmapLevelCollection beatmapLevelCollection, System.Boolean showPlayerStats, System.Boolean showPracticeButton, UnityEngine.GameObject noDataInfoPrefab) // Offset: 0xBF8874 void SetData(GlobalNamespace::IBeatmapLevelCollection* beatmapLevelCollection, bool showPlayerStats, bool showPracticeButton, UnityEngine::GameObject* noDataInfoPrefab); // public System.Void ShowLoading() // Offset: 0xBF78B0 void ShowLoading(); // private System.Void PresentViewControllersForPack() // Offset: 0xBF8900 void PresentViewControllersForPack(); // private System.Void PresentViewControllersForLevelCollection() // Offset: 0xBF8A78 void PresentViewControllersForLevelCollection(); // private System.Void HideLoading() // Offset: 0xBF8B8C void HideLoading(); // private System.Void HideDetailViewController() // Offset: 0xBF8D78 void HideDetailViewController(); // private System.Void HandleLevelCollectionViewControllerDidSelectLevel(LevelCollectionViewController viewController, IPreviewBeatmapLevel level) // Offset: 0xBF9388 void HandleLevelCollectionViewControllerDidSelectLevel(GlobalNamespace::LevelCollectionViewController* viewController, GlobalNamespace::IPreviewBeatmapLevel* level); // private System.Void HandleLevelCollectionViewControllerDidSelectPack(LevelCollectionViewController viewController) // Offset: 0xBF9434 void HandleLevelCollectionViewControllerDidSelectPack(GlobalNamespace::LevelCollectionViewController* viewController); // private System.Void PresentDetailViewController(HMUI.ViewController viewController, System.Boolean immediately) // Offset: 0xBF8BA4 void PresentDetailViewController(HMUI::ViewController* viewController, bool immediately); // private System.Void HandleLevelDetailViewControllerDidPressPlayButton(StandardLevelDetailViewController viewController) // Offset: 0xBF94CC void HandleLevelDetailViewControllerDidPressPlayButton(GlobalNamespace::StandardLevelDetailViewController* viewController); // private System.Void HandleLevelDetailViewControllerDidPressPracticeButton(StandardLevelDetailViewController viewController, IBeatmapLevel level) // Offset: 0xBF9530 void HandleLevelDetailViewControllerDidPressPracticeButton(GlobalNamespace::StandardLevelDetailViewController* viewController, GlobalNamespace::IBeatmapLevel* level); // private System.Void HandleLevelDetailViewControllerDidChangeDifficultyBeatmap(StandardLevelDetailViewController viewController, IDifficultyBeatmap beatmap) // Offset: 0xBF95A8 void HandleLevelDetailViewControllerDidChangeDifficultyBeatmap(GlobalNamespace::StandardLevelDetailViewController* viewController, GlobalNamespace::IDifficultyBeatmap* beatmap); // private System.Void HandleLevelDetailViewControllerDidPresentContent(StandardLevelDetailViewController viewController, StandardLevelDetailViewController/ContentType contentType) // Offset: 0xBF9620 void HandleLevelDetailViewControllerDidPresentContent(GlobalNamespace::StandardLevelDetailViewController* viewController, GlobalNamespace::StandardLevelDetailViewController::ContentType contentType); // private System.Void HandleLevelDetailViewControllerDidPressOpenLevelPackButton(StandardLevelDetailViewController viewController, IBeatmapLevelPack levelPack) // Offset: 0xBF9698 void HandleLevelDetailViewControllerDidPressOpenLevelPackButton(GlobalNamespace::StandardLevelDetailViewController* viewController, GlobalNamespace::IBeatmapLevelPack* levelPack); // private System.Void HandleLevelDetailViewControllerLevelFavoriteStatusDidChange(StandardLevelDetailViewController viewController, System.Boolean favoriteStatus) // Offset: 0xBF9710 void HandleLevelDetailViewControllerLevelFavoriteStatusDidChange(GlobalNamespace::StandardLevelDetailViewController* viewController, bool favoriteStatus); // public System.Void RefreshDetail() // Offset: 0xBF8420 void RefreshDetail(); // protected override System.Void DidActivate(System.Boolean firstActivation, HMUI.ViewController/ActivationType activationType) // Offset: 0xBF8DDC // Implemented from: HMUI.ViewController // Base method: System.Void ViewController::DidActivate(System.Boolean firstActivation, HMUI.ViewController/ActivationType activationType) void DidActivate(bool firstActivation, HMUI::ViewController::ActivationType activationType); // protected override System.Void DidDeactivate(HMUI.ViewController/DeactivationType deactivationType) // Offset: 0xBF90C8 // Implemented from: HMUI.ViewController // Base method: System.Void ViewController::DidDeactivate(HMUI.ViewController/DeactivationType deactivationType) void DidDeactivate(HMUI::ViewController::DeactivationType deactivationType); // public System.Void .ctor() // Offset: 0xBF972C // Implemented from: HMUI.NavigationController // Base method: System.Void NavigationController::.ctor() // Base method: System.Void ContainerViewController::.ctor() // Base method: System.Void ViewController::.ctor() // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static LevelSelectionNavigationController* New_ctor(); }; // LevelSelectionNavigationController } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::LevelSelectionNavigationController*, "", "LevelSelectionNavigationController"); #pragma pack(pop)
68.147679
238
0.815925
Futuremappermydud
e69ff09b9fe3e439dfdf90160d2aa3aeeea5129e
3,967
hpp
C++
src/device_model/device.hpp
bburns/cppagent
c1891c631465ebc9b63a4b3c627727ca3da14ee8
[ "Apache-2.0" ]
null
null
null
src/device_model/device.hpp
bburns/cppagent
c1891c631465ebc9b63a4b3c627727ca3da14ee8
[ "Apache-2.0" ]
null
null
null
src/device_model/device.hpp
bburns/cppagent
c1891c631465ebc9b63a4b3c627727ca3da14ee8
[ "Apache-2.0" ]
null
null
null
// // Copyright Copyright 2009-2022, AMT – The Association For Manufacturing Technology (“AMT”) // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma once #include <map> #include <unordered_map> #include "component.hpp" #include "data_item/data_item.hpp" #include "utilities.hpp" namespace mtconnect { namespace source::adapter { class Adapter; } namespace device_model { class Device : public Component { public: // Constructor that sets variables from an attribute map Device(const std::string &name, entity::Properties &props); ~Device() override = default; auto getptr() const { return std::dynamic_pointer_cast<Device>(Entity::getptr()); } void initialize() override { Component::initialize(); buildDeviceMaps(getptr()); resolveReferences(getptr()); } static entity::FactoryPtr getFactory(); static entity::FactoryPtr getRoot(); void setOptions(const ConfigOptions &options); // Add/get items to/from the device name to data item mapping void addDeviceDataItem(DataItemPtr dataItem); DataItemPtr getDeviceDataItem(const std::string &name) const; void addAdapter(source::adapter::Adapter *anAdapter) { m_adapters.emplace_back(anAdapter); } ComponentPtr getComponentById(const std::string &aId) const { auto comp = m_componentsById.find(aId); if (comp != m_componentsById.end()) return comp->second.lock(); else return nullptr; } void addComponent(ComponentPtr aComponent) { m_componentsById.insert(make_pair(aComponent->getId(), aComponent)); } DevicePtr getDevice() const override { return getptr(); } // Return the mapping of Device to data items const auto &getDeviceDataItems() const { return m_deviceDataItemsById; } void addDataItem(DataItemPtr dataItem, entity::ErrorList &errors) override; std::vector<source::adapter::Adapter *> m_adapters; auto getMTConnectVersion() const { maybeGet<std::string>("mtconnectVersion"); } // Cached data items DataItemPtr getAvailability() const { return m_availability; } DataItemPtr getAssetChanged() const { return m_assetChanged; } DataItemPtr getAssetRemoved() const { return m_assetRemoved; } void setPreserveUuid(bool v) { m_preserveUuid = v; } bool preserveUuid() const { return m_preserveUuid; } void registerDataItem(DataItemPtr di); void registerComponent(ComponentPtr c) { m_componentsById[c->getId()] = c; } protected: void cachePointers(DataItemPtr dataItem); protected: bool m_preserveUuid {false}; DataItemPtr m_availability; DataItemPtr m_assetChanged; DataItemPtr m_assetRemoved; // Mapping of device names to data items std::unordered_map<std::string, std::weak_ptr<data_item::DataItem>> m_deviceDataItemsByName; std::unordered_map<std::string, std::weak_ptr<data_item::DataItem>> m_deviceDataItemsById; std::unordered_map<std::string, std::weak_ptr<data_item::DataItem>> m_deviceDataItemsBySource; std::unordered_map<std::string, std::weak_ptr<Component>> m_componentsById; }; using DevicePtr = std::shared_ptr<Device>; } // namespace device_model using DevicePtr = std::shared_ptr<device_model::Device>; } // namespace mtconnect
34.798246
100
0.693471
bburns
e6a036880c3a3f663d89be8053627349388e1e82
2,439
cpp
C++
src/mesh/adjacent_table.cpp
ZJUCADGeoSim/hausdorff
df9fdf0294d7efd4ec694ec5135487344e509231
[ "MIT" ]
13
2021-09-06T07:19:28.000Z
2022-03-29T15:48:21.000Z
src/mesh/adjacent_table.cpp
ZJUCADGeoSim/hausdorff
df9fdf0294d7efd4ec694ec5135487344e509231
[ "MIT" ]
null
null
null
src/mesh/adjacent_table.cpp
ZJUCADGeoSim/hausdorff
df9fdf0294d7efd4ec694ec5135487344e509231
[ "MIT" ]
null
null
null
/* State Key Lab of CAD&CG Zhejiang Unv. Author: Yicun Zheng (3130104113@zju.edu.cn) Haoran Sun (hrsun@zju.edu.cn) Jin Huang (hj@cad.zju.edu.cn) Copyright (c) 2004-2021 <Jin Huang> All rights reserved. Licensed under the MIT License. */ #include "adjacent_table.hpp" using namespace zjucad::matrix; bool get_neighbor_edge(const matrixst_t &prims, size_t p1, size_t p2, edge_t &e) { size_t point_count = 0; for (size_t vi = 0; vi < prims.size(1); ++vi) { for (size_t vj = 0; vj < prims.size(1); ++vj) { if (prims(vi, p1) == prims(vj, p2)) { if (point_count == 0) { e.first = prims(vi, p1); } else if (point_count == 1) { e.second = prims(vi, p1); } else { return false; } point_count++; } } } if (point_count != 2) { return false; } else { return true; } } void build_primitive_adjacent_table_from_mesh(const matrixd_t &v, const matrixst_t &prims, primitive_adjacent_table &table) { // build vertex-primitives map std::vector<std::vector<size_t>> vpmap(v.size(2)); for (size_t pi = 0; pi < prims.size(2); ++pi) { for (size_t vi = 0; vi < prims.size(1); ++vi) { vpmap[prims(vi, pi)].push_back(pi); } } // iterate vertex to build primitive adjacent table for (size_t i = 0; i < vpmap.size(); ++i) { if (vpmap[i].size() <= 1) continue; for (size_t p1 = 0; p1 < vpmap[i].size(); ++p1) { for (size_t p2 = p1 + 1; p2 < vpmap[i].size(); ++p2) { edge_t e; if (get_neighbor_edge(prims, vpmap[i][p1], vpmap[i][p2], e)) { // std::cout << "prim " << prims(colon(), vpmap[i][p1]) << prims(colon(), vpmap[i][p2]) << std::endl; // std::cout << "e: " << e.first << " " << e.second << std::endl; table.table_.emplace(primitive_pair(vpmap[i][p1], vpmap[i][p2]), e); } } } } // for(auto i = table.table_.begin(); i != table.table_.end(); ++i){ // std::cout << i->first.pair_.first << "-" << i->first.pair_.second << ": " << i->second.first << ", " << i->second.second << std::endl; // } // std::cout << "size: " << table.table_.size() << std::endl; }
34.352113
145
0.497745
ZJUCADGeoSim
e6a4978f3667fb150541ef0fd3dd77dbb74beba1
1,601
cpp
C++
src/main.cpp
Benjins/simple-vm
ef31ea36ad698a47da81642c97d718d3415bd133
[ "CC-BY-4.0" ]
null
null
null
src/main.cpp
Benjins/simple-vm
ef31ea36ad698a47da81642c97d718d3415bd133
[ "CC-BY-4.0" ]
null
null
null
src/main.cpp
Benjins/simple-vm
ef31ea36ad698a47da81642c97d718d3415bd133
[ "CC-BY-4.0" ]
null
null
null
#include "../header/VM.h" #include "../header/Instruction.h" #include "../header/Parser.h" #include "../header/AST.h" #include "../header/DLLFile.h" #include <assert.h> #include <iostream> //#include <dlfcn.h> using std::cout; using std::endl; int main(int argc, char** argv){ #if TESTING VM x; bool allPass = true; x.CompileAndLoadCode("examples/test2.svm"); x.SaveByteCode("examples/test2.svb"); x.LoadByteCode("examples/test2.svb"); allPass &= (x.Execute("main") == 5); allPass &= (x.Execute("testOne") == 1); allPass &= (x.Execute("testTwo") == 1); allPass &= (x.Execute("testThree") == 0); allPass &= (x.Execute("testFour") == 9); cout << (allPass ? "allPass" : "some failed.") << endl; return allPass ? 0 : 1; #elif COMPILER //VM Compiler if(argc < 2){ cout << "\nError: Must supply at least one input file.\n"; return -1; } char* fileNameC = argv[1]; string fileName = string(fileNameC); vector<string> dllNames; for(int i = 2; i < argc; i++){ char* dllNameC = argv[i]; string dllName = string(dllNameC); dllNames.push_back(dllName); } VM x; if(x.CompileAndLoadCode(fileName, &dllNames)){ x.SaveByteCode(fileName + ".svb"); x.LoadByteCode(fileName + ".svb"); x.Execute("main"); } #else //VM runner if(argc < 2){ cout << "\nError: Must supply at least one input file.\n"; return -1; } string fileName = string(argv[1]); string functionName = (argc > 2) ? string(argv[2]) : "main"; VM x; if(x.LoadByteCode(fileName)){ int retVal = x.Execute(functionName); cout << "\nReturned: " << retVal << endl; } #endif return 0; }
21.065789
61
0.63273
Benjins
e6a94ff699f2a4401b126ee510999617cc827c1e
5,894
cpp
C++
Source/Motor2D/Wall.cpp
BarcinoLechiguino/Project_F
9e40c771f5ce6b821e3d380edd5d92fb129cdf53
[ "MIT" ]
1
2020-04-28T16:09:51.000Z
2020-04-28T16:09:51.000Z
Source/Motor2D/Wall.cpp
Aitorlb7/Project_F
9e40c771f5ce6b821e3d380edd5d92fb129cdf53
[ "MIT" ]
3
2020-03-03T09:57:49.000Z
2020-04-25T16:02:36.000Z
Source/Motor2D/Wall.cpp
BarcinoLechiguino/Project-RTS
9e40c771f5ce6b821e3d380edd5d92fb129cdf53
[ "MIT" ]
1
2020-11-06T22:31:26.000Z
2020-11-06T22:31:26.000Z
#include "Application.h" #include "Render.h" #include "Textures.h" #include "Audio.h" #include "Map.h" #include "Pathfinding.h" #include "Player.h" #include "GuiManager.h" #include "GuiElement.h" #include "GuiHealthbar.h" #include "GuiCreationBar.h" #include "FowManager.h" #include "EntityManager.h" #include "Wall.h" Wall::Wall(int x, int y, ENTITY_TYPE type, int level) : Building(x, y, type, level) { InitEntity(); } Wall::~Wall() { } bool Wall::Awake(pugi::xml_node& config) { return true; } bool Wall::Start() { App->pathfinding->ChangeWalkability(tile_position, this, NON_WALKABLE); return true; } bool Wall::PreUpdate() { return true; } bool Wall::Update(float dt, bool do_logic) { if (building_state == BUILDING_STATE::CONSTRUCTING) { ConstructBuilding(); } // FOG OF WAR is_visible = fow_entity->is_visible; return true; } bool Wall::PostUpdate() { if (current_health <= 0) { App->entity_manager->DeleteEntity(this); } return true; } bool Wall::CleanUp() { App->pathfinding->ChangeWalkability(tile_position, this, WALKABLE); //The entity is cleared from the walkability map. App->entity_manager->ChangeEntityMap(tile_position, this, true); //The entity is cleared from the entity_map. entity_sprite = nullptr; if (is_selected) { App->player->DeleteEntityFromBuffers(this); } App->gui_manager->DeleteGuiElement(healthbar); App->fow_manager->DeleteFowEntity(fow_entity); return true; } void Wall::Draw() { //App->render->Blit(entity_sprite, (int)pixel_position.x, (int)pixel_position.y - 20, &wall_rect); //Magic if (construction_finished) { App->render->Blit(entity_sprite, (int)pixel_position.x + 2, (int)pixel_position.y + 2, NULL); //Magic } } void Wall::LevelChanges() { switch (level) { case 1: wall_rect = wall_rect_1; break; case 2: wall_rect = wall_rect_2; max_health = 750; current_health = max_health; //infantry_level++; // TALK ABOUT THIS break; default: wall_rect = wall_rect_2; break; } } void Wall::ConstructBuilding() { if (!constructing_building) { creation_bar->is_visible = true; creation_bar->SetNewCreationTime(construction_time); fow_entity->provides_visibility = false; constructing_building = true; } else { creation_bar->UpdateCreationBarValue(); for (int y = 0; y != tiles_occupied.y; ++y) { for (int x = 0; x != tiles_occupied.x; ++x) { int pos_y = tile_position.y + y; int pos_x = tile_position.x + x; iPoint draw_position = App->map->MapToWorld(pos_x, pos_y); if (App->player->buildable_tile_tex != nullptr) { App->render->Blit(App->player->buildable_tile_tex, draw_position.x + 2, draw_position.y + 2, nullptr); } } } /*if (App->player->townhall_build_tex != nullptr) { SDL_SetTextureAlphaMod(App->player->wall_build_tex, (Uint8)(current_rate * 255.0f)); }*/ if (creation_bar->creation_finished) { fow_entity->provides_visibility = true; building_state = BUILDING_STATE::IDLE; construction_finished = true; constructing_building = false; } } } void Wall::InitEntity() { // POSITION & SIZE iPoint world_position = App->map->MapToWorld(tile_position.x, tile_position.y); pixel_position.x = (float)world_position.x; pixel_position.y = (float)world_position.y; center_point = fPoint(pixel_position.x, pixel_position.y + App->map->data.tile_height); tiles_occupied.x = 1; tiles_occupied.y = 1; // TEXTURE & SECTIONS entity_sprite = App->entity_manager->GetWallTexture(); wall_rect_1 = { 0, 0, 106, 95 }; // NEED REVISION wall_rect_2 = { 108, 0, 106, 95 }; wall_rect = wall_rect_1; // FLAGS is_selected = false; // BUILDING CONSTRUCTION VARIABLES construction_time = 5.0f; // STATS max_health = 500; current_health = max_health; // HEALTHBAR & CREATION BAR if (App->entity_manager->CheckTileAvailability(tile_position, this)) { AttachHealthbarToEntity(); AttachCreationBarToEntity(); } // FOG OF WAR is_visible = true; is_neutral = false; provides_visibility = true; range_of_vision = 4; fow_entity = App->fow_manager->CreateFowEntity(tile_position, is_neutral, provides_visibility); //fow_entity->frontier = App->fow_manager->CreateRectangularFrontier(range_of_vision, range_of_vision, tile_position); fow_entity->frontier = App->fow_manager->CreateCircularFrontier(range_of_vision, tile_position); fow_entity->line_of_sight = App->fow_manager->GetLineOfSight(fow_entity->frontier); } void Wall::AttachHealthbarToEntity() { healthbar_position_offset.x = -30; //Magic healthbar_position_offset.y = -6; healthbar_background_rect = { 618, 1, MAX_BUILDING_HEALTHBAR_WIDTH, 9 }; healthbar_rect = { 618, 23, MAX_BUILDING_HEALTHBAR_WIDTH, 9 }; int healthbar_position_x = (int)pixel_position.x + healthbar_position_offset.x; // X and Y position of the healthbar's hitbox. int healthbar_position_y = (int)pixel_position.y + healthbar_position_offset.y; // The healthbar's position is already calculated in GuiHealthbar. healthbar = (GuiHealthbar*)App->gui_manager->CreateHealthbar(GUI_ELEMENT_TYPE::HEALTHBAR, healthbar_position_x, healthbar_position_y, true, &healthbar_rect, &healthbar_background_rect, this); } void Wall::AttachCreationBarToEntity() { creation_bar_position_offset.x = -30; // Magic creation_bar_position_offset.y = 6; creation_bar_background_rect = { 618, 1, MAX_CREATION_BAR_WIDTH, 9 }; creation_bar_rect = { 618, 23, MAX_CREATION_BAR_WIDTH, 9 }; int creation_bar_position_x = (int)pixel_position.x + creation_bar_position_offset.x; int creation_bar_position_y = (int)pixel_position.y + creation_bar_position_offset.y; creation_bar = (GuiCreationBar*)App->gui_manager->CreateCreationBar(GUI_ELEMENT_TYPE::CREATIONBAR, creation_bar_position_x, creation_bar_position_y, false , &creation_bar_rect, &creation_bar_background_rect, this); }
24.661088
192
0.725993
BarcinoLechiguino
e6aa28a55c657282a31df9acaf79c1edf228f159
3,171
cc
C++
charstream.cc
justinleona/capstone
4a525cad12fba07a43452776a0e289148f04a12d
[ "MIT" ]
1
2021-06-26T05:32:43.000Z
2021-06-26T05:32:43.000Z
charstream.cc
justinleona/capstone
4a525cad12fba07a43452776a0e289148f04a12d
[ "MIT" ]
2
2019-10-14T06:46:43.000Z
2019-10-18T04:34:20.000Z
charstream.cc
justinleona/capstone
4a525cad12fba07a43452776a0e289148f04a12d
[ "MIT" ]
null
null
null
#include "charstream.h" #include <iomanip> #include "notimplemented.h" using namespace std; charbuf::charbuf(char* s, size_t n, size_t offset) : offset(offset) { auto begin = s; auto c = s; auto end = s + n; // set begin, current, and end states for reading setg(begin, c, end); setp(begin, end); } streampos charbuf::seekpos(streampos pos, ios_base::openmode which) { const pos_type& rel = pos - pos_type(off_type(offset)); bool in = which & ios_base::openmode::_S_in; cout << "seekpos(" << hex << pos << ", in=" << in << ")" << endl; return seekoff(rel, ios_base::beg, which); } long repos(streamoff pos, char* begin, char* cur, char* end, ios_base::seekdir way) { switch (way) { case ios_base::beg: return begin + pos - cur; break; case ios_base::cur: return pos; break; case ios_base::end: return end + pos - cur; break; default: break; } return -1; } streampos charbuf::seekoff(streamoff pos, ios_base::seekdir way, ios_base::openmode which) { bool in = which & ios_base::openmode::_S_in; cout << "seekoff(" << hex << pos << "," << way << ", in=" << in << ")" << endl; // no separate begin/end - single array in memory char* begin = eback(); char* end = egptr(); long goff = repos(pos, begin, gptr(), end, way); long poff = repos(pos, begin, pptr(), end, way); char* cg = gptr() + goff; char* cp = pptr() + poff; // cout << "gptr=" << hex << (uint64_t)gptr() << " goffset=" << goff << endl; bool set = false; if (which & ios_base::in) { if (begin <= cg && cg < end) { gbump(goff); set = true; } } if (which & ios_base::out) { if (begin <= cp && cp < end) { pbump(poff); set = true; } } if (set) { return gptr() - begin; } return -1; } // below are implemented so we know if we're using features we'd expect to provide but don't! streambuf* charbuf::setbuf(char* s, streamsize n) { // cerr << "setbuf not yet implemented" << endl; throw not_implemented{"setbuf not yet implemented!"}; } int charbuf::underflow() { // cerr << "underflow not yet implemented" << endl; throw not_implemented{"underflow not yet implemented!"}; } int charbuf::pbackfail(int c) { // cerr << "pbackfail not yet implemented" << endl; throw not_implemented{"pbackfail not yet implemented!"}; } int charbuf::overflow(int c) { // cerr << "overflow not yet implemented" << endl; throw not_implemented{"overflow not yet implemented!"}; } charstream::charstream(char* s, size_t n, size_t offset) : istream(&b), ostream(&b), b(s, n, offset) { rdbuf(&b); } charstream::charstream(uint8_t* s, size_t n, size_t offset) : charstream((char*)s, n, offset) {} void dumpBytes(uint8_t bytes[], size_t size, uint64_t offset) { cout << hex << setfill('0') << setw(8) << (unsigned int)offset << ": "; for (uint64_t i = 0; i != size; ++i) { if (i > 0 && i % 16 == 0) cout << endl << hex << setfill('0') << setw(8) << (unsigned int)(i + offset) << ": "; else if (i > 0 && i % 2 == 0) cout << " "; cout << hex << setfill('0') << setw(2) << (unsigned int)bytes[i]; } cout << endl; }
27.815789
102
0.595396
justinleona
e6b2f4dcf87049372bc1672a82aeddf019ace903
4,286
cpp
C++
editor/gui/toolbar_dock.cpp
ChronicallySerious/Rootex
bf2a0997b6aa5be84dbfc0e7826c31ff693ca0f1
[ "MIT" ]
166
2019-06-19T19:51:45.000Z
2022-03-24T13:03:29.000Z
editor/gui/toolbar_dock.cpp
rahil627/Rootex
44f827d469bddc7167b34dedf80d7a8b984fdf20
[ "MIT" ]
312
2019-06-13T19:39:25.000Z
2022-03-02T18:37:22.000Z
editor/gui/toolbar_dock.cpp
rahil627/Rootex
44f827d469bddc7167b34dedf80d7a8b984fdf20
[ "MIT" ]
23
2019-10-04T11:02:21.000Z
2021-12-24T16:34:52.000Z
#include "toolbar_dock.h" #include "editor/editor_application.h" #include "framework/scene_loader.h" #include "framework/system.h" #include "editor/editor_system.h" #include "vendor/ImGUI/imgui.h" #include "vendor/ImGUI/imgui_stdlib.h" #include "vendor/ImGUI/imgui_impl_dx11.h" #include "vendor/ImGUI/imgui_impl_win32.h" Variant ToolbarDock::disablePlayInEditor(const Event* e) { m_InEditorPlaying = false; EditorApplication::GetSingleton()->setGameMode(false); if (!m_StartPlayingScene.empty()) { SceneLoader::GetSingleton()->loadScene(m_StartPlayingScene, {}); m_StartPlayingScene.clear(); } PRINT("Stopped Scene in Editor"); return true; } ToolbarDock::ToolbarDock() { m_Binder.bind(EditorEvents::EditorSceneIsClosing, this, &ToolbarDock::disablePlayInEditor); m_Binder.bind(RootexEvents::QuitEditorWindow, this, &ToolbarDock::disablePlayInEditor); m_FPSRecords.resize(m_FPSRecordsPoolSize, 0.0f); } void ToolbarDock::draw(float deltaMilliseconds) { ZoneScoped; if (m_ToolbarDockSettings.m_IsActive) { if (ImGui::Begin("Toolbar")) { if (SceneLoader::GetSingleton()->getCurrentScene()) { static int playModeSelected = 0; static const char* playModes[3] = { "Play Scene in Editor", "Play Scene in Game", "Play Game" }; if (m_InEditorPlaying) { ImColor lightErrorColor = EditorSystem::GetSingleton()->getFatalColor(); lightErrorColor.Value.x *= 0.8f; ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)lightErrorColor); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)(EditorSystem::GetSingleton()->getFatalColor())); if (ImGui::Button("Stop " ICON_ROOTEX_WINDOW_CLOSE, { ImGui::GetContentRegionAvailWidth(), 40.0f })) { disablePlayInEditor(nullptr); } ImGui::PopStyleColor(2); } else { if (ImGui::Button("Play " ICON_ROOTEX_FORT_AWESOME, { ImGui::GetContentRegionAvailWidth(), 40.0f })) { switch (playModeSelected) { case 0: m_InEditorPlaying = true; m_StartPlayingScene = SceneLoader::GetSingleton()->getCurrentScene()->getScenePath(); EventManager::GetSingleton()->call(EditorEvents::EditorSaveAll); EditorApplication::GetSingleton()->setGameMode(true); SceneLoader::GetSingleton()->loadScene(m_StartPlayingScene, {}); PRINT("Loaded Scene in Editor"); break; case 1: m_InEditorPlaying = false; EventManager::GetSingleton()->call(EditorEvents::EditorSaveAll); OS::RunApplication("\"" + OS::GetGameExecutablePath() + "\" " + SceneLoader::GetSingleton()->getCurrentScene()->getScenePath()); PRINT("Launched Game process with Scene"); break; case 2: m_InEditorPlaying = false; EventManager::GetSingleton()->call(EditorEvents::EditorSaveAll); OS::RunApplication("\"" + OS::GetGameExecutablePath() + "\""); PRINT("Launched Game process"); break; default: WARN("Unknown play mode found"); } } } #ifdef TRACY_ENABLE if (ImGui::Button("Start Tracy " ICON_ROOTEX_EXTERNAL_LINK " ")) { OS::OpenFileInSystemEditor("rootex/vendor/Tracy/Tracy.exe"); } ImGui::SameLine(); #endif // TRACY_ENABLE ImGui::SetNextItemWidth(ImGui::GetContentRegionAvailWidth()); if (ImGui::BeginCombo("##Play Mode", playModes[playModeSelected])) { for (int i = 0; i < sizeof(playModes) / sizeof(playModes[0]); i++) { if (ImGui::MenuItem(playModes[i])) { playModeSelected = i; } } ImGui::EndCombo(); } } ImGui::SetNextItemWidth(ImGui::GetContentRegionAvailWidth()); ImGui::SliderFloat("##Delta Multiplier", Application::GetSingleton()->getDeltaMultiplierPtr(), -2.0f, 2.0f, ""); if (ImGui::IsItemDeactivatedAfterEdit()) { Application::GetSingleton()->resetDeltaMultiplier(); } if (ImGui::TreeNodeEx("Editor")) { RootexFPSGraph("FPS", m_FPSRecords, EditorApplication::GetSingleton()->getAppFrameTimer().getLastFPS()); ImGui::TreePop(); } for (auto& systems : System::GetSystems()) { for (auto& system : systems) { if (ImGui::TreeNodeEx(system->getName().c_str())) { system->draw(); ImGui::TreePop(); } } } } ImGui::End(); } }
29.558621
135
0.667755
ChronicallySerious
e6b49ac73d171bdfd88cd61f75bf9d7d7d1d4ba7
5,188
cpp
C++
config_manager.cpp
KA8KPN/keyer-ng
93f07dca6249574e19ee3331bd3c7240ddd5d4a5
[ "Apache-2.0" ]
1
2022-02-22T05:46:49.000Z
2022-02-22T05:46:49.000Z
config_manager.cpp
KA8KPN/keyer-ng
93f07dca6249574e19ee3331bd3c7240ddd5d4a5
[ "Apache-2.0" ]
null
null
null
config_manager.cpp
KA8KPN/keyer-ng
93f07dca6249574e19ee3331bd3c7240ddd5d4a5
[ "Apache-2.0" ]
null
null
null
#include "config_manager.h" #include "paddles.h" #include "display.h" #include "keying.h" #include "memories.h" #include "wpm.h" #include <EEPROM.h> #include <ctype.h> config_manager system_config_manager; #define MAGIC 0x5a0d #define PADDLES_REVERSE_FLAG 0x01 #define SIDETONE_OFF_FLAG 0x02 #pragma pack(1) typedef struct persistent_config { uint16_t magic; uint16_t size; uint8_t configFlags; uint8_t transmitter; #ifdef FEATURE_MEMORIES uint8_t memories[MEMORY_SIZE]; #endif // FEATURE_MEMORIES #ifdef FEATURE_SPEED_CONTROL int wpm_offset; #endif // FEATURE_SPEED_CONTROL uint16_t checksum; } persistent_config_t; #pragma pack() void error_tone(void) { tone(SIDETONE, 100); delay(200); noTone(SIDETONE); } static persistent_config_t s_persistentConfig; // returns TRUE if the checksum has changed static bool update_checksum(persistent_config_t *conf) { uint16_t sum = 0; for (size_t i=0; i<((sizeof(persistent_config_t)/2)-1); ++i) { sum += ((uint16_t *)conf)[i]; } if (~sum != conf->checksum) { conf->checksum = ~sum; return true; } return false; } // returns TRUE if the checksum is valid static bool validate_checksum(persistent_config_t *conf) { uint16_t sum = 0; for (size_t i=0; i<(sizeof(persistent_config_t)/2); ++i) { sum += ((uint16_t *)conf)[i]; } return sum == ~0U; } static void write_eeprom(bool force) { int max_address; max_address = sizeof(persistent_config_t); if (update_checksum(&s_persistentConfig) || force) { // Write the memory, but only if that works for (int i=0; i<max_address; ++i) { if (EEPROM.read(i) != ((uint8_t *)&s_persistentConfig)[i]) { EEPROM.write(i, ((uint8_t *)&s_persistentConfig)[i]); } } } } config_manager::config_manager(void): m_paddlesMode(MODE_PADDLE_NORMAL), m_isInCommandMode(false), m_currentXmitter(1), m_processing(false) { } void config_manager::process_command(const char *command) { if (!m_processing) { switch(command[0]) { case 'N': m_paddlesMode = PADDLES_REVERSE(); if (PADDLES_REVERSE_FLAG & s_persistentConfig.configFlags) { s_persistentConfig.configFlags &= ~PADDLES_REVERSE_FLAG; } else { s_persistentConfig.configFlags |= PADDLES_REVERSE_FLAG; } command_mode(false); break; case 'O': if (SIDETONE_OFF_FLAG & s_persistentConfig.configFlags) { s_persistentConfig.configFlags &= ~SIDETONE_OFF_FLAG; } else { s_persistentConfig.configFlags |= SIDETONE_OFF_FLAG; } TOGGLE_SIDETONE_ENABLE(); command_mode(false); break; case '0': case '1': case '2': case '3': case '4': m_currentXmitter = command[0] - '0'; s_persistentConfig.transmitter = m_currentXmitter; KEYING_SELECT_TRANSMITTER(m_currentXmitter); command_mode(false); break; case 'P': if (isdigit(command[1])) { RECORD_MEMORY(atoi(command+1)); m_processing = true; } else { error_tone(); } break; default: error_tone(); break; } } } static void two_beeps(bool first_is_low, bool second_is_low) { if (first_is_low) { tone(SIDETONE, 600); } else { tone(SIDETONE, 1200); } delay(100); noTone(SIDETONE); delay(50); if (second_is_low) { tone(SIDETONE, 600); } else { tone(SIDETONE, 1200); } delay(100); noTone(SIDETONE); delay(50); } void config_manager::memory_start_tones(void) { two_beeps(false, false); } void config_manager::memory_end_tones(void) { two_beeps(true, true); } void config_manager::command_mode(bool is_in_command_mode) { if (is_in_command_mode) { two_beeps(true, false); } else { if (m_isInCommandMode) { two_beeps(false, true); } RECORD_MEMORY(0); s_persistentConfig.wpm_offset = WPM_GET_OFFSET(); m_processing = false; write_eeprom(false); } m_isInCommandMode = is_in_command_mode; DISPLAY_MANAGER_PROG_MODE(m_isInCommandMode); KEYING_COMMAND_MODE(m_isInCommandMode); } void config_manager_initialize(void) { // Attempt to read the config from the EEPROM int max_address; max_address = sizeof(persistent_config_t); for (int i=0; i<max_address; ++i) { ((uint8_t *)&s_persistentConfig)[i] = EEPROM.read(i); } // If the magic is right, the size is right, and the checksum is right, then I'm good, otherwise initialize if ((MAGIC != s_persistentConfig.magic) || (s_persistentConfig.size != sizeof(s_persistentConfig)) || !validate_checksum(&s_persistentConfig)) { memset(&s_persistentConfig, 0, sizeof(s_persistentConfig)); s_persistentConfig.magic = MAGIC; s_persistentConfig.size = sizeof(s_persistentConfig); s_persistentConfig.transmitter = 1; write_eeprom(true); } // MEMORIES_CONFIG(s_persistentConfig.memories); if (s_persistentConfig.configFlags & PADDLES_REVERSE_FLAG) { PADDLES_REVERSE(); } if (s_persistentConfig.configFlags & SIDETONE_OFF_FLAG) { TOGGLE_SIDETONE_ENABLE(); } if (0 != s_persistentConfig.wpm_offset) { WPM_SET_OFFSET(s_persistentConfig.wpm_offset); } KEYING_SELECT_TRANSMITTER(s_persistentConfig.transmitter); }
23.581818
142
0.689476
KA8KPN