hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
495d6d0beddca557ede7775b6206744dafd4081b
582
cpp
C++
snippets/cpp/VS_Snippets_Data/Classic WebData XmlElement.SetAttributeNode1 Example/CPP/source.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
2
2020-03-12T19:26:36.000Z
2022-01-10T21:45:33.000Z
snippets/cpp/VS_Snippets_Data/Classic WebData XmlElement.SetAttributeNode1 Example/CPP/source.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
555
2019-09-23T22:22:58.000Z
2021-07-15T18:51:12.000Z
snippets/cpp/VS_Snippets_Data/Classic WebData XmlElement.SetAttributeNode1 Example/CPP/source.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
3
2020-01-29T16:31:15.000Z
2021-08-24T07:00:15.000Z
// <Snippet1> #using <System.Xml.dll> using namespace System; using namespace System::IO; using namespace System::Xml; int main() { XmlDocument^ doc = gcnew XmlDocument; doc->LoadXml( "<book xmlns:bk='urn:samples' bk:ISBN='1-861001-57-5'><title>Pride And Prejudice</title></book>" ); XmlElement^ root = doc->DocumentElement; // Add a new attribute. XmlAttribute^ attr = root->SetAttributeNode( "genre", "urn:samples" ); attr->Value = "novel"; Console::WriteLine( "Display the modified XML..." ); Console::WriteLine( doc->InnerXml ); } // </Snippet1>
25.304348
116
0.670103
BohdanMosiyuk
495d74a4b2c72b6b43a2f4ca7d741b10949046a2
5,119
cpp
C++
src/modules/MouseUtils/FindMyMouse/dllmain.cpp
szlatkow/PowerToys
e62df46c6181551e80b7ce2cf85f03beccbfadf2
[ "MIT" ]
3
2021-11-21T03:03:41.000Z
2021-11-21T23:57:28.000Z
src/modules/MouseUtils/FindMyMouse/dllmain.cpp
szlatkow/PowerToys
e62df46c6181551e80b7ce2cf85f03beccbfadf2
[ "MIT" ]
9
2021-05-12T17:12:35.000Z
2021-10-30T14:57:56.000Z
src/modules/MouseUtils/FindMyMouse/dllmain.cpp
szlatkow/PowerToys
e62df46c6181551e80b7ce2cf85f03beccbfadf2
[ "MIT" ]
2
2021-05-26T09:02:21.000Z
2021-05-26T09:02:22.000Z
#include "pch.h" #include <interface/powertoy_module_interface.h> #include <common/SettingsAPI/settings_objects.h> #include "trace.h" #include "FindMyMouse.h" #include <thread> #include <common/utils/logger_helper.h> namespace { const wchar_t JSON_KEY_PROPERTIES[] = L"properties"; const wchar_t JSON_KEY_VALUE[] = L"value"; const wchar_t JSON_KEY_DO_NOT_ACTIVATE_ON_GAME_MODE[] = L"do_not_activate_on_game_mode"; } extern "C" IMAGE_DOS_HEADER __ImageBase; HMODULE m_hModule; BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { m_hModule = hModule; switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: Trace::RegisterProvider(); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: Trace::UnregisterProvider(); break; } return TRUE; } // The PowerToy name that will be shown in the settings. const static wchar_t* MODULE_NAME = L"FindMyMouse"; // Add a description that will we shown in the module settings page. const static wchar_t* MODULE_DESC = L"Focus the mouse pointer"; // Implement the PowerToy Module Interface and all the required methods. class FindMyMouse : public PowertoyModuleIface { private: // The PowerToy state. bool m_enabled = false; // Load initial settings from the persisted values. void init_settings(); // Helper function to extract the settings void parse_settings(PowerToysSettings::PowerToyValues& settings); public: // Constructor FindMyMouse() { LoggerHelpers::init_logger(MODULE_NAME, L"ModuleInterface", LogSettings::findMyMouseLoggerName); init_settings(); }; // Destroy the powertoy and free memory virtual void destroy() override { delete this; } // Return the localized display name of the powertoy virtual const wchar_t* get_name() override { return MODULE_NAME; } // Return the non localized key of the powertoy, this will be cached by the runner virtual const wchar_t* get_key() override { return MODULE_NAME; } // Return JSON with the configuration options. virtual bool get_config(wchar_t* buffer, int* buffer_size) override { HINSTANCE hinstance = reinterpret_cast<HINSTANCE>(&__ImageBase); // Create a Settings object. PowerToysSettings::Settings settings(hinstance, get_name()); settings.set_description(MODULE_DESC); return settings.serialize_to_buffer(buffer, buffer_size); } // Signal from the Settings editor to call a custom action. // This can be used to spawn more complex editors. virtual void call_custom_action(const wchar_t* action) override { } // Called by the runner to pass the updated settings values as a serialized JSON. virtual void set_config(const wchar_t* config) override { try { // Parse the input JSON string. PowerToysSettings::PowerToyValues values = PowerToysSettings::PowerToyValues::from_json_string(config, get_key()); parse_settings(values); values.save_to_settings_file(); } catch (std::exception&) { // Improper JSON. } } // Enable the powertoy virtual void enable() { m_enabled = true; Trace::EnableFindMyMouse(true); std::thread([]() { FindMyMouseMain(m_hModule); }).detach(); } // Disable the powertoy virtual void disable() { m_enabled = false; Trace::EnableFindMyMouse(false); FindMyMouseDisable(); } // Returns if the powertoys is enabled virtual bool is_enabled() override { return m_enabled; } }; // Load the settings file. void FindMyMouse::init_settings() { try { // Load and parse the settings file for this PowerToy. PowerToysSettings::PowerToyValues settings = PowerToysSettings::PowerToyValues::load_from_settings_file(FindMyMouse::get_key()); parse_settings(settings); } catch (std::exception&) { // Error while loading from the settings file. Let default values stay as they are. } } void FindMyMouse::parse_settings(PowerToysSettings::PowerToyValues& settings) { FindMyMouseSetDoNotActivateOnGameMode(true); auto settingsObject = settings.get_raw_json(); if (settingsObject.GetView().Size()) { try { auto jsonPropertiesObject = settingsObject.GetNamedObject(JSON_KEY_PROPERTIES).GetNamedObject(JSON_KEY_DO_NOT_ACTIVATE_ON_GAME_MODE); FindMyMouseSetDoNotActivateOnGameMode((bool)jsonPropertiesObject.GetNamedBoolean(JSON_KEY_VALUE)); } catch (...) { Logger::warn("Failed to get 'do not activate on game mode' setting"); } } else { Logger::info("Find My Mouse settings are empty"); } } extern "C" __declspec(dllexport) PowertoyModuleIface* __cdecl powertoy_create() { return new FindMyMouse(); }
27.521505
145
0.671616
szlatkow
4962d1a74ef7c19f1b044641bc6bbca98bedcb01
2,311
cc
C++
solutions/001-025/11/main.cc
PysKa-Ratzinger/personal_project_euler_solutions
ff05c38f3c9cbcd4d6f09f81034bc299c7144476
[ "MIT" ]
1
2019-04-19T01:05:07.000Z
2019-04-19T01:05:07.000Z
solutions/001-025/11/main.cc
PysKa-Ratzinger/personal_project_euler_solutions
ff05c38f3c9cbcd4d6f09f81034bc299c7144476
[ "MIT" ]
null
null
null
solutions/001-025/11/main.cc
PysKa-Ratzinger/personal_project_euler_solutions
ff05c38f3c9cbcd4d6f09f81034bc299c7144476
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BUFFER_SZ 512 #define ROWS 20 #define COLS 20 bool isNumber(int character){ return character >= '0' && character <= '9'; } unsigned long magic2(int grid[ROWS][COLS]){ unsigned long res = 0; unsigned long temp; for(int i=0; i<ROWS; i++){ for(int j=0; j<COLS; j++){ if(j<COLS-4){ temp = grid[i][j] * grid[i][j+1] * grid[i][j+2] * grid[i][j+3]; if(temp > res) res = temp; } if(i<ROWS-4){ temp = grid[i][j] * grid[i+1][j] * grid[i+2][j] * grid[i+3][j]; if(temp > res) res = temp; } if(i<ROWS-4 && j<COLS-4){ temp = grid[i][j] * grid[i+1][j+1] * grid[i+2][j+2] * grid[i+3][j+4]; if(temp > res) res = temp; } if(i>3 && j<COLS-4){ temp = grid[i][j] * grid[i-1][j+1] * grid[i-2][j+2] * grid[i-3][j+3]; if(temp > res) res = temp; } } } return res; } unsigned long magic(FILE* input_file){ int grid[ROWS][COLS]; bool wasNumber = false; int input; int number = 0; int row_idx = 0; int col_idx = 0; while((input = getc(input_file)) != EOF){ if(isNumber(input)){ number *= 10; number += input - '0'; wasNumber = true; }else if(wasNumber){ grid[row_idx][col_idx] = number; number = 0; wasNumber = false; col_idx++; if(col_idx == COLS){ col_idx = 0; row_idx++; } } } return magic2(grid); } int main(){ unsigned long res = 0; char buffer[BUFFER_SZ]; printf("Insert the name of the input file: "); fgets(buffer, BUFFER_SZ, stdin); buffer[strlen(buffer)-1] = '\0'; FILE* input_file = fopen(buffer, "r"); if(input_file == NULL){ perror("fopen"); exit(EXIT_FAILURE); }else{ printf("File opened successfully.\n"); } res = magic(input_file); fclose(input_file); printf("If you can trust me, the number you are " "looking for is %lu\n", res); return 0; }
24.326316
79
0.465599
PysKa-Ratzinger
4964b54bcc941dd66b264ede259bbf384a01cb92
416
cpp
C++
functions/prime_between_two_nums.cpp
sahilduhan/Learn-C-plus-plus
80dba2ee08b36985deb297293a0318da5d6ace94
[ "RSA-MD" ]
null
null
null
functions/prime_between_two_nums.cpp
sahilduhan/Learn-C-plus-plus
80dba2ee08b36985deb297293a0318da5d6ace94
[ "RSA-MD" ]
null
null
null
functions/prime_between_two_nums.cpp
sahilduhan/Learn-C-plus-plus
80dba2ee08b36985deb297293a0318da5d6ace94
[ "RSA-MD" ]
null
null
null
#include <bits/stdc++.h> using namespace std; bool prime_between_two_nums(int num) { for (int i = 2; i < sqrt(num); i++) if (num % 2 == 0) { return false; } else { return true; } } int main() { int a, b; for (int i = a; i <= b; i++) { if (prime_between_two_nums(i)) cout << i << endl; } return 0; }
16
39
0.427885
sahilduhan
496bf95d0aaecdc00598dc9fb87e2231003b1054
2,591
cpp
C++
ffl/source/utils/FFL_Clock.cpp
zhenfei2016/FFL-v2
376c79a0611af580d4767a4bbb05822f1a4fd454
[ "MIT" ]
null
null
null
ffl/source/utils/FFL_Clock.cpp
zhenfei2016/FFL-v2
376c79a0611af580d4767a4bbb05822f1a4fd454
[ "MIT" ]
null
null
null
ffl/source/utils/FFL_Clock.cpp
zhenfei2016/FFL-v2
376c79a0611af580d4767a4bbb05822f1a4fd454
[ "MIT" ]
null
null
null
/* * This file is part of FFL project. * * The MIT License (MIT) * Copyright (C) 2017-2018 zhufeifei All rights reserved. * * FFL_Clock.cpp * Created by zhufeifei(34008081@qq.com) on 2018/04/29 * https://github.com/zhenfei2016/FFL-v2.git * * 时钟类,可以获取当前时间,改变时钟速度,修改时钟原点偏移 * y=ax +b */ #include <utils/FFL_Clock.hpp> namespace FFL { // // y=(a/KA_RATIO) x +b // 当前设置的a参数的放大倍数,实际的值= a/KA_RATIO // // static const int64_t KA_RATIO = 100; // // y=x*a /KA_RATIO // static int64_t getY(int64_t x, int64_t a) { return (int64_t)((double)(x * a) / KA_RATIO); } Clock::Clock():mListener(NULL){ reset(); } Clock::~Clock() { } void Clock::reset() { mB = 0; mA = KA_RATIO; } IClockListener* Clock::setListener(IClockListener* listener){ IClockListener* ret = mListener; mListener=listener; return ret; } // // 当前时间 // int64_t Clock::nowUs() { return nowUs(0); } // // 这个时钟的当前时间 systemUs:返回系统时钟的时间 // int64_t Clock::nowUs(int64_t* systemUs) { int64_t now = FFL_getNowUs(); if (systemUs) { *systemUs = now; } if (equalSystemClock()) { return now; } // // 转化到当前时钟的时间值 // y=ax +b // int64_t clockNow = getY(now, mA) + mB; FFL_LOG_INFO("Clock x:%" lld64 " y:%" lld64 "a=%" lld64 " b=%" lld64, now, clockNow, mA, mB); return clockNow; } // // 转换当前时钟的一个时间段转成系统时钟时间段 // 例如可以把当前时钟5分钟转成系统时钟8分钟 // int64_t Clock::clockToWorldTimeBucket(int64_t dy) { // // y=ax+b // 计算dx // return (int64_t)(double)(dy * 100) / mA; } int64_t Clock::SystemToClockRelativeUs(int64_t dx) { // // y=ax+b // 计算dy // return (int64_t)((double)(dx * mA) / 100); } int64_t Clock::worldToClockUs(int64_t x) { // // y=ax+b // 计算dy // return (int64_t)getY(x, mA) + mB; } // // 时钟速度,默认1.0时正常时钟值 // uint32_t Clock::speed() { return mA; } void Clock::setSpeed(uint32_t percent) { if (percent != mA) { int64_t x; int64_t y = nowUs(&x); // // 计算新的a,b参数 // b=y-ax // uint32_t oldA=mA; mA = percent; mB = y - (int64_t)((double)(mA* x) / KA_RATIO); if(mListener){ int32_t type=0; if(percent>oldA) type=1; else if(percent<oldA) type=-1; mListener->onSpeedChange(type, mA); } } } // // 偏移 // int64_t Clock::offset() { return mOffset; } void Clock::setOffset(int64_t offset) { mOffset = offset; } // // 是否系统时钟一致的 // bool Clock::equalSystemClock() { return mA == KA_RATIO; } }
17.868966
95
0.565033
zhenfei2016
496c85b7a32734eabd51d4fa2d7f9cce3a028f70
2,001
cpp
C++
nmainwindow.cpp
NeoProject/NeoPaintPrototype
ebfca88f7ddc2011daebf6d221c8e099f6e03645
[ "Info-ZIP" ]
null
null
null
nmainwindow.cpp
NeoProject/NeoPaintPrototype
ebfca88f7ddc2011daebf6d221c8e099f6e03645
[ "Info-ZIP" ]
null
null
null
nmainwindow.cpp
NeoProject/NeoPaintPrototype
ebfca88f7ddc2011daebf6d221c8e099f6e03645
[ "Info-ZIP" ]
null
null
null
#include "nmainwindow.h" #include "NGadget/nstatusbar.h" #include "NGadget/nmenubar.h" #include "NGadget/ntoolbar.h" #include <QLabel> #include <NCanvas/ncanvas.h> #include "NGadget/nabout.h" #include "NCanvas/ntabwidget.h" #include <QMenu> #include <QAction> #include "NGadget/ntablettest.h" #include "NDockWidget/ndockwidget.h" #include "NGadget/nabout.h" #include "NGadget/ntablettest.h" #include "NCanvas/ncanvasview.h" NMainWindow::NMainWindow(QWidget *parent) : QMainWindow(parent), neoStatusBar(new NStatusBar(this)), neoMenuBar(new NMenuBar(this)), neoToolBar(new NToolBar(this)), neoTabWidget(new NTabWidget(this)), neoPrototype(new NDockWidget(this)), neoAbout(new NAbout(tr("NeoPaintPrototype"))), neoTabletTest(new NTabletTest) { initWidget(); initConnection(); setDockNestingEnabled(true); neoPrototype->setAllowedAreas(Qt::LeftDockWidgetArea); neoPrototype->setMinimumWidth(300); // neoTabWidget->nCanvas->setMessage(neoStatusBar->nStatusMessage); } NMainWindow::~NMainWindow() { } void NMainWindow::initWidget() { setStatusBar(neoStatusBar); setMenuBar(neoMenuBar); addToolBar(neoToolBar); setCentralWidget(neoTabWidget); addDockWidget(Qt::LeftDockWidgetArea, neoPrototype); } void NMainWindow::initConnection() { connect(neoMenuBar->NFile.Close, &QAction::triggered, this, &NMainWindow::close); connect(neoMenuBar->NHelp.About, &QAction::triggered, neoAbout, &NAbout::show); connect(neoMenuBar->NHelp.TabletTest, &QAction::triggered, neoTabletTest, &NTabletTest::show); connect(neoMenuBar->NFile.New, &QAction::triggered, neoTabWidget, &NTabWidget::newCanvas); // connect(neoMenuBar, &NMenuBar::sendFileName, neoTabWidget->nView, &NCanvasView::openFile); // connect(neoMenuBar, &NMenuBar::sendSaveFileName, neoTabWidget->nView, &NCanvasView::saveFile); // connect(neoTabWidget->nCanvas, &NCanvas::tabletStatusChanged, neoStatusBar, &NStatusBar::changeStatus); }
31.761905
109
0.74013
NeoProject
4971d7fbcdd6db28eff49825d3b8a5b959f4e86a
3,757
cpp
C++
Project/Part Five: Data Cache/Code/CacheStats.cpp
HernandezDerekJ/Computer-Architecture-3339
03785b02169a76ca0b1b38205bd5e64adde2b727
[ "MIT" ]
null
null
null
Project/Part Five: Data Cache/Code/CacheStats.cpp
HernandezDerekJ/Computer-Architecture-3339
03785b02169a76ca0b1b38205bd5e64adde2b727
[ "MIT" ]
null
null
null
Project/Part Five: Data Cache/Code/CacheStats.cpp
HernandezDerekJ/Computer-Architecture-3339
03785b02169a76ca0b1b38205bd5e64adde2b727
[ "MIT" ]
null
null
null
/****************************** * CacheStats.cpp submitted by: Derek Hernandez (djh119) * CS 3339 - Spring 2019 * Project 4 Branch Predictor * Copyright 2019, all rights reserved * Updated by Lee B. Hinkle based on prior work by Martin Burtscher and Molly O'Neil ******************************/ #include <iostream> #include <cstdlib> #include <iomanip> #include "CacheStats.h" using namespace std; CacheStats::CacheStats() { cout << "Cache Config: "; if(!CACHE_EN) { cout << "cache disabled" << endl; } else { cout << (SETS * WAYS * BLOCKSIZE) << " B ("; cout << BLOCKSIZE << " bytes/block, " << SETS << " sets, " << WAYS << " ways)" << endl; cout << " Latencies: Lookup = " << LOOKUP_LATENCY << " cycles, "; cout << "Read = " << READ_LATENCY << " cycles, "; cout << "Write = " << WRITE_LATENCY << " cycles" << endl; } loads = 0; stores = 0; load_misses = 0; store_misses = 0; writebacks = 0; /* TODO: your code here */ tag = uint32_t(0); index = uint32_t(0); stallLatency = 0; for(int a = 0; a < SETS; a++){ w[a]=0; for(int b = 0; b < WAYS; b++){ tags[a][b] = uint32_t(0); modify[a][b] = 0; valid[a][b] = 0; } } } int CacheStats::access(uint32_t addr, ACCESS_TYPE type) { if(!CACHE_EN) { // cache is off return (type == LOAD) ? READ_LATENCY : WRITE_LATENCY; } /* TODO: your code here */ // Vars // Offset == log2 (32) // Set == 3 (2^3) index = (addr >> 5) & 0x7; //Data to store tag = addr >> 8; //Reset Stall stallLatency = 0; //Loads and Stores if (type == STORE) stores++; else if(type == LOAD) loads++; //HIT //tags match and its not empty(vaild) for(int a = 0; a < WAYS; a++){ if((tags[index][a] == tag) && (valid[index][a])){ stallLatency = LOOKUP_LATENCY; if(type == STORE) modify[index][a] = 1; return stallLatency; } } // Miss two types Clean, Dirty if(type == STORE) store_misses++; else if(type == LOAD) load_misses++; //Clean Modify == 0 Latency == 30 if(modify[index][w[index]] == 0){ stallLatency = stallLatency + READ_LATENCY; } //Dirty Modify == 1 Latency == 10+30 else if(modify[index][w[index]] == 1){ stallLatency = stallLatency + READ_LATENCY + WRITE_LATENCY; writebacks++; } //Install into cache tags[index][w[index]] = tag; valid[index][w[index]] = 1; //Determine Modify,based on type if(type == LOAD){ modify[index][w[index]] = 0; } else if(type == STORE){ modify[index][w[index]] = 1; } //Control w values, round robin 4 way, never go over 3 if (w[index] == 3){ w[index] = 0; } else{ w[index]++; } return stallLatency; } void CacheStats::printFinalStats() { /* TODO: your code here (don't forget to drain the cache of writebacks) */ // Write Back == Dirty/Modified (Whenever modify is true) for(int x = 0; x < SETS; x++){ for(int y = 0; y < WAYS; y++){ if(modify[x][y]) writebacks++; } } int accesses = loads + stores; int misses = load_misses + store_misses; cout << "Accesses: " << accesses << endl; cout << " Loads: " << loads << endl; cout << " Stores: " << stores << endl; cout << "Misses: " << misses << endl; cout << " Load misses: " << load_misses << endl; cout << " Store misses: " << store_misses << endl; cout << "Writebacks: " << writebacks << endl; cout << "Hit Ratio: " << fixed << setprecision(1) << 100.0 * (accesses - misses) / accesses; cout << "%" << endl; }
28.24812
94
0.526218
HernandezDerekJ
49724ecba26a56c2e2550a77eae9f9b0eabb32ef
2,919
cpp
C++
application/CMatrix.cpp
HO-COOH/Console
f6132e4135db0c5432a2943a8f5f367a6ce1167d
[ "MIT" ]
3
2020-06-05T05:18:32.000Z
2021-07-29T01:13:07.000Z
application/CMatrix.cpp
HO-COOH/Console
f6132e4135db0c5432a2943a8f5f367a6ce1167d
[ "MIT" ]
null
null
null
application/CMatrix.cpp
HO-COOH/Console
f6132e4135db0c5432a2943a8f5f367a6ce1167d
[ "MIT" ]
null
null
null
#include "Console.h" #include "ConsoleEngine.h" #include "TimedEvent.hpp" #include <iostream> #include <thread> #include <random> #include <vector> #include <array> #include <functional> static std::mt19937 rdEng{ std::random_device{}() }; char randomChar() { static std::uniform_int_distribution<int> rdNum{ '!', '}' }; return rdNum(rdEng); } int main(int argc, char** argv) { ConsoleEngine eng{ console }; eng.setAsciiMode(); const auto width = console.getWidth(); const auto height = console.getHeight(); std::uniform_int_distribution rdNumHeight{ 0, (int)height }; std::vector<short> head( width, 0); std::vector<short> tail( width, 0); std::vector<short> length(width, 0); std::vector<bool> hasContent(width); ScopedTimer t{ 60000 }; std::vector<short> emptyCol; emptyCol.reserve(width); while (true) { /*Get empty columns*/ for (auto col = 0; col < width; ++col) { if (!hasContent[col]) emptyCol.push_back(col); } /*select some empty columns*/ if (emptyCol.size() > width/2) { std::array<short, 10> toFill; std::uniform_int_distribution rd{ 0, static_cast<int>(emptyCol.size() - 1) }; std::generate(toFill.begin(), toFill.end(), [&rd, &emptyCol] {return emptyCol[rd(rdEng)]; }); for (auto& col : toFill) { eng.buffer(0, col).Char.AsciiChar = randomChar(); eng.buffer(0, col).Attributes = static_cast<WORD>(Color::WHITE) | FOREGROUND_INTENSITY; hasContent[col] = true; head[col] = 1; length[col] = rdNumHeight(rdEng); } } for (auto i = 0; i < width; ++i) { /*generate a random char at [head] position*/ if (hasContent[i]) { if (head[i] != 0) { eng.buffer(head[i], i).Char.AsciiChar = randomChar(); eng.buffer(head[i] - 1, i).Attributes = static_cast<WORD>(Color::GREEN) | FOREGROUND_INTENSITY; eng.buffer(head[i], i).Attributes = static_cast<WORD>(Color::WHITE) | FOREGROUND_INTENSITY; ++head[i]; if (head[i] >= height) head[i] = 0; } /*delete the char at [tail] position */ if ( head[i]==0||head[i]-tail[i] >= length[i]) { eng.buffer(tail[i], i).Char.AsciiChar = ' '; ++tail[i]; if (tail[i] >= height) { tail[i] = 0; hasContent[i] = false; } } } } eng.draw(); emptyCol.clear(); t.wait(); } }
31.053191
115
0.488866
HO-COOH
49736fe0cc0e1cb621c5a52218f6fc60f8067e53
2,524
cc
C++
model/mosesdecoder/util/tempfile_test.cc
saeedesm/UNMT_AH
cc171bf66933b5c0ad8a0ab87e57f7364312a7df
[ "Apache-2.0" ]
3
2020-02-28T21:42:44.000Z
2021-03-12T13:56:16.000Z
tools/mosesdecoder-master/util/tempfile_test.cc
Pangeamt/nectm
6b84f048698f2530b9fdbb30695f2e2217c3fbfe
[ "Apache-2.0" ]
2
2020-11-06T14:40:10.000Z
2020-12-29T19:03:11.000Z
tools/mosesdecoder-master/util/tempfile_test.cc
Pangeamt/nectm
6b84f048698f2530b9fdbb30695f2e2217c3fbfe
[ "Apache-2.0" ]
2
2019-11-26T05:27:16.000Z
2019-12-17T01:53:43.000Z
#include "util/tempfile.hh" #include <fstream> #include <boost/filesystem.hpp> #define BOOST_TEST_MODULE TempFileTest #include <boost/test/unit_test.hpp> namespace util { namespace { BOOST_AUTO_TEST_CASE(temp_dir_has_path) { BOOST_CHECK(temp_dir().path().size() > 0); } BOOST_AUTO_TEST_CASE(temp_dir_creates_temp_directory) { const temp_dir t; BOOST_CHECK(boost::filesystem::exists(t.path())); BOOST_CHECK(boost::filesystem::is_directory(t.path())); } BOOST_AUTO_TEST_CASE(temp_dir_creates_unique_directory) { BOOST_CHECK(temp_dir().path() != temp_dir().path()); } BOOST_AUTO_TEST_CASE(temp_dir_cleans_up_directory) { std::string path; { const temp_dir t; path = t.path(); } BOOST_CHECK(!boost::filesystem::exists(path)); } BOOST_AUTO_TEST_CASE(temp_dir_cleanup_succeeds_if_directory_contains_file) { std::string path; { const temp_dir t; path = t.path(); boost::filesystem::create_directory(path + "/directory"); std::ofstream file((path + "/file").c_str()); file << "Text"; file.flush(); } BOOST_CHECK(!boost::filesystem::exists(path)); } BOOST_AUTO_TEST_CASE(temp_dir_cleanup_succeeds_if_directory_is_gone) { std::string path; { const temp_dir t; path = t.path(); boost::filesystem::remove_all(path); } BOOST_CHECK(!boost::filesystem::exists(path)); } BOOST_AUTO_TEST_CASE(temp_file_has_path) { BOOST_CHECK(temp_file().path().size() > 0); } BOOST_AUTO_TEST_CASE(temp_file_creates_temp_file) { const temp_file f; BOOST_CHECK(boost::filesystem::exists(f.path())); BOOST_CHECK(boost::filesystem::is_regular_file(f.path())); } BOOST_AUTO_TEST_CASE(temp_file_creates_unique_file) { BOOST_CHECK(temp_file().path() != temp_file().path()); } BOOST_AUTO_TEST_CASE(temp_file_creates_writable_file) { const std::string data = "Test-data-goes-here"; const temp_file f; std::ofstream outfile(f.path().c_str()); outfile << data; outfile.flush(); std::string read_data; std::ifstream infile(f.path().c_str()); infile >> read_data; BOOST_CHECK_EQUAL(data, read_data); } BOOST_AUTO_TEST_CASE(temp_file_cleans_up_file) { std::string path; { const temp_file f; path = f.path(); } BOOST_CHECK(!boost::filesystem::exists(path)); } BOOST_AUTO_TEST_CASE(temp_file_cleanup_succeeds_if_file_is_gone) { std::string path; { const temp_file t; path = t.path(); boost::filesystem::remove(path); } BOOST_CHECK(!boost::filesystem::exists(path)); } } // namespace anonymous } // namespace util
21.033333
74
0.717116
saeedesm
49777283d6c10ab1c31f8cbaa2667c61dda384cf
3,352
hh
C++
geometry2.hh
lnw/nano-tori
5f43722085154c9315ada572108a360e6601dd1a
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
geometry2.hh
lnw/nano-tori
5f43722085154c9315ada572108a360e6601dd1a
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
geometry2.hh
lnw/nano-tori
5f43722085154c9315ada572108a360e6601dd1a
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
// Copyright (c) 2019, Lukas Wirz // All rights reserved. // This file is part of 'nano-tori' which is released under the BSD-2-clause license. // See file LICENSE in this project. #ifndef GEOMETRY2_HH #define GEOMETRY2_HH #include <cassert> #include <cmath> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> #include "auxiliary.hh" using namespace std; struct matrix2d; struct coord2d { double x[2]; coord2d(const double y[2]) { x[0] = y[0]; x[1] = y[1]; } explicit coord2d(const double x_=0, const double y=0) { x[0] = x_; x[1] = y; } coord2d operator/(const double s) const { return coord2d(*this) /= s; } coord2d operator*(const double s) const { return coord2d(*this) *= s; } coord2d operator+(const coord2d& y) const { return coord2d(*this) += y; } coord2d operator-(const coord2d& y) const { return coord2d(*this) -= y; } coord2d& operator+=(const coord2d& y){ x[0] += y[0]; x[1] += y[1]; return *this; } coord2d& operator-=(const coord2d& y){ x[0] -= y[0]; x[1] -= y[1]; return *this; } coord2d& operator*=(const double& y){ x[0] *= y; x[1] *= y; return *this; } coord2d& operator/=(const double& y){ x[0] /= y; x[1] /= y; return *this; } coord2d operator-() const {coord2d y(-x[0],-x[1]); return y;} coord2d operator*(const matrix2d& m) const; double& operator[](unsigned int i){ return x[i]; } double operator[](unsigned int i) const { return x[i]; } double norm() const {return sqrt(x[0]*x[0] + x[1]*x[1]);} friend ostream& operator<<(ostream& S, const coord2d &c2) { S << "{" << c2[0] << ", " << c2[1] << "}"; return S; } }; coord2d operator*(const double &d, const coord2d &c2d); struct structure2d { vector<coord2d> dat; vector<coord2d>::iterator begin(){return dat.begin();} vector<coord2d>::iterator end(){return dat.end();} structure2d operator*(const matrix2d& m) const; coord2d& operator[](unsigned int i){ return dat[i]; } coord2d operator[](unsigned int i) const { return dat[i]; } void push_back(const coord2d &c2d){dat.push_back(c2d);} size_t size() const {return dat.size();} bool contains(coord2d p) const; void crop(double x1, double y1, double x2, double y2); // assume that all points are consecutive, and both ends are connected // if the curve is self-intersecting, every intersection changes the sign, but the total sign is positive double area() const; friend ostream& operator<<(ostream& S, const structure2d &s2) { S << s2.dat; return S; } }; struct matrix2d { double values[4]; explicit matrix2d(const double w=0, const double x=0, const double y=0, const double z=0) { // (0,0), (0,1), (1,0), (1,1) values[0]=w; values[1]=x; values[2]=y; values[3]=z; } double& operator()(int i, int j) { return values[i*2+j]; } // i: row, j: column double operator()(int i, int j) const { return values[i*2+j]; } double& operator[](unsigned int i) { return values[i]; } double operator[](unsigned int i) const { return values[i]; } coord2d operator*(const coord2d& c2d) const; structure2d operator*(const structure2d& s2d) const; friend ostream& operator<<(ostream& S, const matrix2d &M) { S << "{"; for(int i=0;i<2;i++) S << vector<double>(&M.values[i*2],&M.values[(i+1)*2]) << (i+1<2?",":"}"); return S; } }; #endif
31.622642
123
0.636038
lnw
497938523755e3be70e0d1cc9bdad40f50ed3590
4,777
cpp
C++
playlistTable.cpp
allenyin/musicplayer2
429c5e86afc01df21161023d359826d65c9b35ec
[ "MIT" ]
1
2016-06-05T15:14:22.000Z
2016-06-05T15:14:22.000Z
playlistTable.cpp
allenyin/musicplayer2
429c5e86afc01df21161023d359826d65c9b35ec
[ "MIT" ]
null
null
null
playlistTable.cpp
allenyin/musicplayer2
429c5e86afc01df21161023d359826d65c9b35ec
[ "MIT" ]
1
2019-04-17T15:19:08.000Z
2019-04-17T15:19:08.000Z
#include "playlistTable.h" #include "playlistmodel.h" #include <stdio.h> #include <iostream> #include <QApplication> #include <QHeaderView> #include <QMimeData> #include <QDebug> class PlaylistModel; PlaylistTable::PlaylistTable(QWidget* parent) : QTableView(parent) { // edit only when F2 is pressed setEditTriggers(QAbstractItemView::EditKeyPressed); setAlternatingRowColors(true); // entire row is selected when any item is clicked setSelectionBehavior(QAbstractItemView::SelectRows); setSelectionMode(QAbstractItemView::ContiguousSelection); // enable drag and drop setDragEnabled(true); setAcceptDrops(true); setDropIndicatorShown(true); setDefaultDropAction(Qt::MoveAction); setDragDropOverwriteMode(false); setDragDropMode(QTableView::DragDrop); } PlaylistTable::~PlaylistTable() { } void PlaylistTable::mouseDoubleClickEvent(QMouseEvent* e) { QPoint clickPos = e->pos(); QModelIndex clickIdx = QTableView::indexAt(clickPos); #if DEBUG_PLAYLISTVIEW qDebug()<< "Double click at (" << clickPos.x() << ", " << clickPos.y(); qDebug()<< "ModelIndex: (" << clickIdx.row() << ", " << clickIdx.column(); #endif emit(QTableView::activated(clickIdx)); } void PlaylistTable::mouseReleaseEvent(QMouseEvent* e) { if (e->button() == Qt::LeftButton) { // Use base handler QTableView::mouseReleaseEvent(e); } else { QTableView::mouseReleaseEvent(e); } } #if DEBUG_PLAYLISTVIEW void PlaylistTable::contextMenuEvent(QContextMenuEvent* e) { QPoint clickPos = e->pos(); QModelIndex clickIdx = QTableView::indexAt(clickPos); qDebug() << "Right click at (" << clickPos.x() << ", " << clickPos.y() << ")"; qDebug() << "ModelIndex: (" << clickIdx.row() << ", " << clickIdx.column() << ")"; } #endif void PlaylistTable::keyPressEvent(QKeyEvent *event) { // selectionMode must be contiguous if (event->key() == Qt::Key_Delete) { if (selectionModel()->hasSelection()) { QModelIndexList selected = selectionModel()->selectedRows(); PlaylistModel *model = (PlaylistModel*)(QTableView::model()); model->removeMedia(selected.front().row(), selected.back().row()); } } else { QTableView::keyPressEvent(event); } } void PlaylistTable::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasFormat("myMediaItem")) { //qDebug() << "playlistTable::dragEnterEvent()"; #if DEBUG_PLAYLISTVIEW QPoint dragPos = event->pos(); QModelIndex dragIdx = QTableView::indexAt(dragPos); qDebug()<<"dragIdx is " << dragIdx; #endif event->accept(); } else { event->ignore(); } } void PlaylistTable::dragMoveEvent(QDragMoveEvent *event) { if (event->mimeData()->hasFormat("myMediaItem")) { //qDebug() << "playlistTable::dragMoveEvent(myMediaItem)"; event->setDropAction(Qt::MoveAction); event->accept(); } else { event->ignore(); } } void PlaylistTable::dropEvent(QDropEvent *event) { //qDebug()<<"PlaylistTable::dropEvent()"; if (event->mimeData()->hasFormat("myMediaItem")) { // this is when we re-arrange items in the playlist QByteArray itemData = event->mimeData()->data("myMediaItem"); QDataStream dataStream(&itemData, QIODevice::ReadOnly); QString header; dataStream >> header; qDebug() << "Header is: " << header; if (header == "playlistItem") { QPoint dropPos = event->pos(); int dropRow = QTableView::indexAt(dropPos).row(); QList<int> itemRowList; while (!dataStream.atEnd()) { int itemRow; dataStream >> itemRow; itemRowList << itemRow; } qSort(itemRowList); int offset = dropRow - itemRowList.back(); #if DEBUG_PLAYLISTVIEW qDebug()<<"dropRow is " << dropRow; #endif PlaylistModel *model = static_cast<PlaylistModel*>(QTableView::model()); model->swapSong(dropRow, itemRowList, offset); event->setDropAction(Qt::MoveAction); event->accept(); } if (header == "libraryItem") { QList<QHash<QString, QString> > itemList; QHash<QString, QString> hash; while (!dataStream.atEnd()) { dataStream >> hash; itemList << hash; } PlaylistModel *model = static_cast<PlaylistModel*>(QTableView::model()); model->addMediaList(itemList); event->setDropAction(Qt::CopyAction); event->accept(); } } else { event->ignore(); } }
30.621795
86
0.609378
allenyin
497a1492afe717c7f57e2f374dd963873003af7b
28,261
cpp
C++
benchmark/message/message.cpp
smart-cloud/actor-zeta
9597d6c21843a5e24a7998d09ff041d2f948cc63
[ "BSD-3-Clause" ]
20
2016-01-07T07:37:52.000Z
2019-06-02T12:04:25.000Z
benchmark/message/message.cpp
smart-cloud/actor-zeta
9597d6c21843a5e24a7998d09ff041d2f948cc63
[ "BSD-3-Clause" ]
30
2017-03-10T14:47:46.000Z
2019-05-09T19:23:25.000Z
benchmark/message/message.cpp
jinncrafters/actor-zeta
9597d6c21843a5e24a7998d09ff041d2f948cc63
[ "BSD-3-Clause" ]
6
2017-03-10T14:06:01.000Z
2018-08-13T18:19:37.000Z
#include <benchmark/benchmark.h> #include <iostream> #include <map> #include <memory> #include <string> #include <vector> #include <actor-zeta/make_message.hpp> #include "fixtures.hpp" #include "register_benchmark.hpp" namespace benchmark_messages { static volatile int64_t message_sz = 0; using raw_t = actor_zeta::mailbox::message*; using smart_t = actor_zeta::mailbox::message_ptr; namespace by_name { BENCHMARK_TEMPLATE_DEFINE_F(fixture_t, RawPtrMessage_Name, raw_t) (benchmark::State& state) { while (state.KeepRunning()) { auto message = actor_zeta::make_message_ptr( actor_zeta::base::address_t::empty_address(), name_); auto tmp = sizeof(*message); delete message; if (static_cast<int64_t>(tmp) > static_cast<int64_t>(benchmark_messages::message_sz)) benchmark_messages::message_sz = static_cast<int64_t>(tmp); } } BENCHMARK_TEMPLATE_DEFINE_F(fixture_t, SmartPtrMessage_Name, smart_t) (benchmark::State& state) { while (state.KeepRunning()) { auto message = actor_zeta::make_message( actor_zeta::base::address_t::empty_address(), name_); auto tmp = sizeof(*message); if (static_cast<int64_t>(tmp) > static_cast<int64_t>(benchmark_messages::message_sz)) benchmark_messages::message_sz = static_cast<int64_t>(tmp); } } BENCHMARK_REGISTER_F(fixture_t, RawPtrMessage_Name)->DenseRange(0, 64, 8); BENCHMARK_REGISTER_F(fixture_t, SmartPtrMessage_Name)->DenseRange(0, 64, 8); } // namespace by_name namespace by_args { template<typename... Args> auto message_arg_tmpl(uint64_t name_, Args&&... args) -> void; namespace raw_ptr { template<typename... Args> auto message_arg_tmpl(uint64_t name_, Args&&... args) -> void { auto message = actor_zeta::make_message_ptr( actor_zeta::base::address_t::empty_address(), name_, std::forward<Args>(args)...); auto tmp = sizeof(*message); delete message; if (static_cast<int64_t>(tmp) > static_cast<int64_t>(benchmark_messages::message_sz)) benchmark_messages::message_sz = static_cast<int64_t>(tmp); } template<typename T, std::size_t... I> auto call_message_arg_tmpl(uint64_t name_, T& packed_tuple, actor_zeta::type_traits::index_sequence<I...>) -> void { message_arg_tmpl(name_, (std::get<I>(packed_tuple))...); } } // namespace raw_ptr namespace smart_ptr { template<typename... Args> auto message_arg_tmpl(uint64_t name_, Args&&... args) -> void { auto message = actor_zeta::make_message( actor_zeta::base::address_t::empty_address(), name_, std::forward<Args>(args)...); auto tmp = sizeof(*message); if (static_cast<int64_t>(tmp) > static_cast<int64_t>(benchmark_messages::message_sz)) benchmark_messages::message_sz = static_cast<int64_t>(tmp); } template<typename T, std::size_t... I> auto call_message_arg_tmpl(uint64_t name_, T& packed_tuple, actor_zeta::type_traits::index_sequence<I...>) -> void { message_arg_tmpl(name_, (std::get<I>(packed_tuple))...); } } // namespace smart_ptr #define REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture, bm_name, type) REGISTER_BENCHMARK_FOR_RAWPTR_ARGS(fixture, bm_name, raw_t, benchmark_messages::by_args::raw_ptr, type) #define REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture, bm_name, type) REGISTER_BENCHMARK_FOR_SMARTPTR_ARGS(fixture, bm_name, smart_t, benchmark_messages::by_args::smart_ptr, type) namespace trivial_args { REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_long_double, long double);*/ REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_long_double, long double);*/ } // namespace trivial_args namespace smart_pointer_args { //REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_shared_ptr_long_double, long double);*/ //REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_shared_ptr_long_double, long double);*/ } // namespace smart_pointer_args namespace container_args { //REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_vec_t, RawPtrMessage_Args_std_vector_long_double, long double);*/ //REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_list_t, RawPtrMessage_Args_std_list_long_double, long double);*/ //REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_map_t, RawPtrMessage_Args_std_map_long_double, long double);*/ //REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_set_t, RawPtrMessage_Args_std_set_long_double, long double);*/ //REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_vec_t, SmartPtrMessage_Args_std_vector_long_double, long double);*/ //REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_list_t, SmartPtrMessage_Args_std_list_long_double, long double);*/ //REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_map_t, SmartPtrMessage_Args_std_map_long_double, long double);*/ //REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_int, int); /*REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_int8, int8_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_int16, int16_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_int32, int32_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_int64, int64_t); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_short, short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_unsigned_short, unsigned short); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_unsigned_int, unsigned int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_unsigned_long_int, unsigned long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_long_int, long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_long_long_int, long long int); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_long_long, long long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_long, long); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_float, float); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_double, double); REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_set_t, SmartPtrMessage_Args_std_set_long_double, long double);*/ } // namespace container_args namespace custom_args { //REGISTER_MESSAGE_BENCHMARK_FOR_RAWPTR_ARGS(fixture_t, RawPtrMessage_Args_custom_1, custom_1_t); //REGISTER_MESSAGE_BENCHMARK_FOR_SMARTPTR_ARGS(fixture_t, SmartPtrMessage_Args_custom_1, custom_1_t); } // namespace custom_args } // namespace by_args class memory_manager_t : public benchmark::MemoryManager { void Start() BENCHMARK_OVERRIDE {} void Stop(Result* result) BENCHMARK_OVERRIDE { result->max_bytes_used = message_sz; } }; } // namespace benchmark_messages // Run the benchmark int main(int argc, char** argv) { benchmark::Initialize(&argc, argv); if (benchmark::ReportUnrecognizedArguments(argc, argv)) return 1; std::unique_ptr<benchmark::MemoryManager> mm(new benchmark_messages::memory_manager_t()); benchmark::RegisterMemoryManager(mm.get()); benchmark::RunSpecifiedBenchmarks(); benchmark::Shutdown(); benchmark::RegisterMemoryManager(nullptr); return 0; }
81.20977
186
0.78695
smart-cloud
497f10f04c580ca0ed1cf2ec41db964cbea1859c
5,472
cpp
C++
TAO/tao/Synch_Queued_Message.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tao/Synch_Queued_Message.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tao/Synch_Queued_Message.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// -*- C++ -*- // $Id: Synch_Queued_Message.cpp 93465 2011-03-02 16:16:33Z vzykov $ #include "tao/Synch_Queued_Message.h" #include "tao/debug.h" #include "tao/ORB_Core.h" #include "ace/Malloc_T.h" #include "ace/Message_Block.h" TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO_Synch_Queued_Message::TAO_Synch_Queued_Message ( const ACE_Message_Block *contents, TAO_ORB_Core *oc, ACE_Allocator *alloc, bool is_heap_allocated) : TAO_Queued_Message (oc, alloc, is_heap_allocated) , contents_ (const_cast<ACE_Message_Block*> (contents)) , current_block_ (contents_) , own_contents_ (is_heap_allocated) { } TAO_Synch_Queued_Message::~TAO_Synch_Queued_Message (void) { if (this->own_contents_ && this->contents_ != 0) { ACE_Message_Block::release (this->contents_); } } const ACE_Message_Block * TAO_Synch_Queued_Message::current_block (void) const { return this->current_block_; } size_t TAO_Synch_Queued_Message::message_length (void) const { if (this->current_block_ == 0) { return 0; } return this->current_block_->total_length (); } int TAO_Synch_Queued_Message::all_data_sent (void) const { return this->current_block_ == 0; } void TAO_Synch_Queued_Message::fill_iov (int iovcnt_max, int &iovcnt, iovec iov[]) const { ACE_ASSERT (iovcnt_max > iovcnt); for (const ACE_Message_Block *message_block = this->current_block_; message_block != 0 && iovcnt < iovcnt_max; message_block = message_block->cont ()) { size_t const message_block_length = message_block->length (); // Check if this block has any data to be sent. if (message_block_length > 0) { // Collect the data in the iovec. iov[iovcnt].iov_base = message_block->rd_ptr (); iov[iovcnt].iov_len = static_cast<u_long> (message_block_length); // Increment iovec counter. ++iovcnt; } } } void TAO_Synch_Queued_Message::bytes_transferred (size_t &byte_count) { this->state_changed_i (TAO_LF_Event::LFS_ACTIVE); while (this->current_block_ != 0 && byte_count > 0) { size_t const l = this->current_block_->length (); if (byte_count < l) { this->current_block_->rd_ptr (byte_count); byte_count = 0; return; } byte_count -= l; this->current_block_->rd_ptr (l); this->current_block_ = this->current_block_->cont (); while (this->current_block_ != 0 && this->current_block_->length () == 0) { this->current_block_ = this->current_block_->cont (); } } if (this->current_block_ == 0) this->state_changed (TAO_LF_Event::LFS_SUCCESS, this->orb_core_->leader_follower ()); } TAO_Queued_Message * TAO_Synch_Queued_Message::clone (ACE_Allocator *alloc) { TAO_Synch_Queued_Message *qm = 0; // Clone the message block. // NOTE: We wantedly do the cloning from <current_block_> instead of // starting from <contents_> since we dont want to clone blocks that // have already been sent on the wire. Waste of memory and // associated copying. ACE_Message_Block *mb = this->current_block_->clone (); if (alloc) { ACE_NEW_MALLOC_RETURN (qm, static_cast<TAO_Synch_Queued_Message *> ( alloc->malloc (sizeof (TAO_Synch_Queued_Message))), TAO_Synch_Queued_Message (mb, this->orb_core_, alloc, true), 0); } else { ACE_NEW_RETURN (qm, TAO_Synch_Queued_Message (mb, this->orb_core_, 0, true), 0); } return qm; } void TAO_Synch_Queued_Message::destroy (void) { if (this->own_contents_) { ACE_Message_Block::release (this->contents_); this->current_block_ = 0; this->contents_ = 0; } if (this->is_heap_created_) { // If we have an allocator release the memory to the allocator // pool. if (this->allocator_) { ACE_DES_FREE (this, this->allocator_->free, TAO_Synch_Queued_Message); } else // global release.. { delete this; } } } void TAO_Synch_Queued_Message::copy_if_necessary (const ACE_Message_Block* chain) { if (!this->own_contents_) { // Go through the message block chain looking for the message block // that matches our "current" message block. for (const ACE_Message_Block* mb = chain; mb != 0; mb = mb->cont ()) { if (mb == this->current_block_) { // Once we have found the message block, we need to // clone the current block so that if another thread comes // in and calls reset() on the output stream (via another // invocation on the transport), it doesn't cause the rest // of our message to be released. this->own_contents_ = true; this->contents_ = this->current_block_->clone (); this->current_block_ = this->contents_; break; } } } } TAO_END_VERSIONED_NAMESPACE_DECL
27.223881
82
0.591374
cflowe
4982369fda4f70dff76a384072ccfc38881b1405
1,961
cpp
C++
libminifi/src/utils/file/PathUtils.cpp
achristianson/nifi-minifi-cpp-experimental
e41101f7f20d0fea287b3a97f2f611988bf1ea12
[ "Apache-2.0" ]
3
2018-01-11T19:48:07.000Z
2019-06-11T09:39:05.000Z
libminifi/src/utils/file/PathUtils.cpp
achristianson/nifi-minifi-cpp-experimental
e41101f7f20d0fea287b3a97f2f611988bf1ea12
[ "Apache-2.0" ]
null
null
null
libminifi/src/utils/file/PathUtils.cpp
achristianson/nifi-minifi-cpp-experimental
e41101f7f20d0fea287b3a97f2f611988bf1ea12
[ "Apache-2.0" ]
1
2019-02-25T19:47:06.000Z
2019-02-25T19:47:06.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 "utils/file/PathUtils.h" #include "utils/file/FileUtils.h" #include <iostream> namespace org { namespace apache { namespace nifi { namespace minifi { namespace utils { namespace file { bool PathUtils::getFileNameAndPath(const std::string &path, std::string &filePath, std::string &fileName) { const std::size_t found = path.find_last_of(FileUtils::get_separator()); /** * Don't make an assumption about about the path, return false for this case. * Could make the assumption that the path is just the file name but with the function named * getFileNameAndPath we expect both to be there ( a fully qualified path ). * */ if (found == std::string::npos || found == path.length() - 1) { return false; } if (found == 0) { filePath = ""; // don't assume that path is not empty filePath += FileUtils::get_separator(); fileName = path.substr(found + 1); return true; } filePath = path.substr(0, found); fileName = path.substr(found + 1); return true; } } /* namespace file */ } /* namespace utils */ } /* namespace minifi */ } /* namespace nifi */ } /* namespace apache */ } /* namespace org */
33.810345
107
0.704233
achristianson
21a316b503d0458ef2a590ffd7f9f0cc7481d0d4
1,234
cpp
C++
Modeler/ScriptDoc.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
1
2022-02-14T15:46:44.000Z
2022-02-14T15:46:44.000Z
Modeler/ScriptDoc.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
null
null
null
Modeler/ScriptDoc.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
2
2022-01-10T22:17:06.000Z
2022-01-17T09:34:08.000Z
// ScriptDoc.cpp : implementation file // #include "stdafx.h" #ifdef _DEBUG #undef new #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CScriptDoc IMPLEMENT_DYNCREATE(CScriptDoc, CDocument) CScriptDoc::CScriptDoc() { } BOOL CScriptDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; return TRUE; } CScriptDoc::~CScriptDoc() { } BEGIN_MESSAGE_MAP(CScriptDoc, CDocument) //{{AFX_MSG_MAP(CScriptDoc) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CScriptDoc diagnostics #ifdef _DEBUG void CScriptDoc::AssertValid() const { CDocument::AssertValid(); } void CScriptDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CScriptDoc serialization void CScriptDoc::Serialize(CArchive& ar) { ((CEditView*)m_viewList.GetHead())->SerializeRaw(ar); } ///////////////////////////////////////////////////////////////////////////// // CScriptDoc commands
18.984615
77
0.551053
openlastchaos
21a4e4a96b4ee13c38d7e855aff3f790b3cc2052
1,696
cpp
C++
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/storage-manager/src/SMLogging.cpp
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
null
null
null
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/storage-manager/src/SMLogging.cpp
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
null
null
null
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/storage-manager/src/SMLogging.cpp
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
2
2022-02-27T14:00:01.000Z
2022-03-31T06:24:22.000Z
/* Copyright (C) 2019 MariaDB Corporation 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdarg.h> #include <unistd.h> #include "SMLogging.h" using namespace std; namespace { storagemanager::SMLogging *smLog = NULL; boost::mutex m; }; namespace storagemanager { SMLogging::SMLogging() { //TODO: make this configurable setlogmask (LOG_UPTO (LOG_DEBUG)); openlog ("StorageManager", LOG_PID | LOG_NDELAY | LOG_PERROR | LOG_CONS, LOG_LOCAL1); } SMLogging::~SMLogging() { syslog(LOG_INFO, "CloseLog"); closelog(); } SMLogging * SMLogging::get() { if (smLog) return smLog; boost::mutex::scoped_lock s(m); if (smLog) return smLog; smLog = new SMLogging(); return smLog; } void SMLogging::log(int priority,const char *format, ...) { va_list args; va_start(args, format); #ifdef DEBUG va_list args2; va_copy(args2, args); vfprintf(stderr, format, args2); fprintf(stderr, "\n"); va_end(args2); #endif vsyslog(priority, format, args); va_end(args); } }
22.315789
89
0.68809
zettadb
21a55d0c5e3ca82fd2e04d7ccd567e8d7846fe1a
4,204
cpp
C++
Source/Cache/FrameCache.cpp
Karshilov/Dorothy-SSR
cce19ed2218d76f941977370f6b3894e2f87236a
[ "MIT" ]
43
2020-01-29T02:22:41.000Z
2021-12-06T04:20:12.000Z
Source/Cache/FrameCache.cpp
Jilliana8397/Dorothy-SSR
5ad647909c5e20cb7ebde9a1a054cdb944969dcb
[ "MIT" ]
1
2020-03-19T16:23:12.000Z
2020-03-19T16:23:12.000Z
Source/Cache/FrameCache.cpp
Jilliana8397/Dorothy-SSR
5ad647909c5e20cb7ebde9a1a054cdb944969dcb
[ "MIT" ]
8
2020-03-08T13:46:08.000Z
2021-07-19T11:30:23.000Z
/* Copyright (c) 2021 Jin Li, http://www.luvfight.me Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Const/Header.h" #include "Cache/FrameCache.h" #include "Const/XmlTag.h" #include "Cache/TextureCache.h" #include "Cache/ClipCache.h" #include "Node/Sprite.h" NS_DOROTHY_BEGIN FrameActionDef* FrameCache::loadFrame(String frameStr) { if (Path::getExt(frameStr) == "frame"_slice) return load(frameStr); BLOCK_START { auto parts = frameStr.split("::"_slice); BREAK_IF(parts.size() != 2); FrameActionDef* def = FrameActionDef::create(); def->clipStr = parts.front(); Vec2 origin{}; if (SharedClipCache.isClip(parts.front())) { Texture2D* tex = nullptr; Rect rect; std::tie(tex, rect) = SharedClipCache.loadTexture(parts.front()); origin = rect.origin; } auto tokens = parts.back().split(","_slice); BREAK_IF(tokens.size() != 4); auto it = tokens.begin(); float width = Slice::stof(*it); float height = Slice::stof(*++it); int count = Slice::stoi(*++it); def->duration = Slice::stof(*++it); for (int i = 0; i < count; i++) { def->rects.push_back(New<Rect>(origin.x + i * width, origin.y, width, height)); } return def; } BLOCK_END Warn("invalid frame str not load: \"{}\".", frameStr); return nullptr; } bool FrameCache::isFrame(String frameStr) const { auto parts = frameStr.split("::"_slice); if (parts.size() == 1) return Path::getExt(parts.front()) == "frame"_slice; else if (parts.size() == 2) return parts.back().split(","_slice).size() == 4; else return false; } std::shared_ptr<XmlParser<FrameActionDef>> FrameCache::prepareParser(String filename) { return std::shared_ptr<XmlParser<FrameActionDef>>(new Parser(FrameActionDef::create(), Path::getPath(filename))); } void FrameCache::Parser::xmlSAX2Text(const char* s, size_t len) { } void FrameCache::Parser::xmlSAX2StartElement(const char* name, size_t len, const std::vector<AttrSlice>& attrs) { switch (Xml::Frame::Element(name[0])) { case Xml::Frame::Element::Dorothy: { for (int i = 0; attrs[i].first != nullptr;i++) { switch (Xml::Frame::Dorothy(attrs[i].first[0])) { case Xml::Frame::Dorothy::File: { Slice file(attrs[++i]); std::string localFile = Path::concat({_path, file}); _item->clipStr = SharedContent.exist(localFile) ? localFile : file.toString(); break; } case Xml::Frame::Dorothy::Duration: _item->duration = s_cast<float>(std::atof(attrs[++i].first)); break; } } break; } case Xml::Frame::Element::Clip: { for (int i = 0; attrs[i].first != nullptr; i++) { switch (Xml::Frame::Clip(attrs[i].first[0])) { case Xml::Frame::Clip::Rect: { Slice attr(attrs[++i]); auto tokens = attr.split(","); AssertUnless(tokens.size() == 4, "invalid clip rect str for: \"{}\"", attr); auto it = tokens.begin(); float x = Slice::stof(*it); float y = Slice::stof(*++it); float w = Slice::stof(*++it); float h = Slice::stof(*++it); _item->rects.push_back(New<Rect>(x, y, w, h)); break; } } } break; } } } void FrameCache::Parser::xmlSAX2EndElement(const char* name, size_t len) { } NS_DOROTHY_END
34.178862
463
0.672217
Karshilov
21a5dad926c4e000099bd64e80dadf40be432e3f
381
hpp
C++
src/delta.hpp
crockeo/hc
a5f9eaa1051e8825fa765d120d8ea76682909a5a
[ "MIT" ]
null
null
null
src/delta.hpp
crockeo/hc
a5f9eaa1051e8825fa765d120d8ea76682909a5a
[ "MIT" ]
null
null
null
src/delta.hpp
crockeo/hc
a5f9eaa1051e8825fa765d120d8ea76682909a5a
[ "MIT" ]
null
null
null
#ifndef _DELTA_HPP_ #define _DELTA_HPP_ ////////// // Code // // Getting the current system time in milliseconds. int getTimeMillis(); // A utility to do some delta timing stuff. class Delta { private: int last, curr; bool first; public: // Constructing a delta. Delta(); // Getting the time since the last time this was run. float since(); }; #endif
15.24
57
0.650919
crockeo
21a5f501ef3650eec5efbe46f08a594997b372d5
652
cpp
C++
Codeforces/A_Games.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
Codeforces/A_Games.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
Codeforces/A_Games.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define endl "\n" #define pi acos(-1) #define faster_io ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); using namespace std; int main() { //freopen("/home/sohel/Documents/my_codes/out.txt", "wt", stdout); faster_io; int n, cnt_rep = 0, cnt = 0; cin >> n; int h[n], a[n]; for (int i = 0; i < n; i++) { cin >> h[i] >> a[i]; } for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (h[i] == a[j]) cnt++; if(a[i] == h[j]) cnt++; } } cout << cnt << endl; return 0; }
21.733333
77
0.435583
Sohelr360
21a61f52b9ddbd1d42dcc22dee17ed910b20266f
6,950
hpp
C++
include/crocoddyl/multibody/frames.hpp
ggory15/crocoddyl
4708428676f596f93ffe2df739faeb5cc38d2326
[ "BSD-3-Clause" ]
null
null
null
include/crocoddyl/multibody/frames.hpp
ggory15/crocoddyl
4708428676f596f93ffe2df739faeb5cc38d2326
[ "BSD-3-Clause" ]
null
null
null
include/crocoddyl/multibody/frames.hpp
ggory15/crocoddyl
4708428676f596f93ffe2df739faeb5cc38d2326
[ "BSD-3-Clause" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (C) 2018-2020, LAAS-CNRS, University of Edinburgh // Copyright note valid unless otherwise stated in individual files. // All rights reserved. /////////////////////////////////////////////////////////////////////////////// #ifndef CROCODDYL_MULTIBODY_FRAMES_HPP_ #define CROCODDYL_MULTIBODY_FRAMES_HPP_ #include "crocoddyl/multibody/fwd.hpp" #include "crocoddyl/multibody/friction-cone.hpp" #include "crocoddyl/core/mathbase.hpp" #include <pinocchio/spatial/se3.hpp> #include <pinocchio/spatial/motion.hpp> #include <pinocchio/spatial/force.hpp> namespace crocoddyl { typedef std::size_t FrameIndex; template <typename _Scalar> struct FrameTranslationTpl { EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef _Scalar Scalar; typedef typename MathBaseTpl<Scalar>::Vector3s Vector3s; explicit FrameTranslationTpl() : frame(0), oxf(Vector3s::Zero()) {} FrameTranslationTpl(const FrameTranslationTpl<Scalar>& value) : frame(value.frame), oxf(value.oxf) {} FrameTranslationTpl(const FrameIndex& frame, const Vector3s& oxf) : frame(frame), oxf(oxf) {} friend std::ostream& operator<<(std::ostream& os, const FrameTranslationTpl<Scalar>& X) { os << " frame: " << X.frame << std::endl << "translation: " << std::endl << X.oxf.transpose() << std::endl; return os; } FrameIndex frame; Vector3s oxf; }; template <typename _Scalar> struct FrameRotationTpl { EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef _Scalar Scalar; typedef typename MathBaseTpl<Scalar>::Matrix3s Matrix3s; explicit FrameRotationTpl() : frame(0), oRf(Matrix3s::Identity()) {} FrameRotationTpl(const FrameRotationTpl<Scalar>& value) : frame(value.frame), oRf(value.oRf) {} FrameRotationTpl(const FrameIndex& frame, const Matrix3s& oRf) : frame(frame), oRf(oRf) {} friend std::ostream& operator<<(std::ostream& os, const FrameRotationTpl<Scalar>& X) { os << " frame: " << X.frame << std::endl << "rotation: " << std::endl << X.oRf << std::endl; return os; } FrameIndex frame; Matrix3s oRf; }; template <typename _Scalar> struct FramePlacementTpl { EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef _Scalar Scalar; typedef pinocchio::SE3Tpl<Scalar> SE3; explicit FramePlacementTpl() : frame(0), oMf(SE3::Identity()) {} FramePlacementTpl(const FramePlacementTpl<Scalar>& value) : frame(value.frame), oMf(value.oMf) {} FramePlacementTpl(const FrameIndex& frame, const SE3& oMf) : frame(frame), oMf(oMf) {} friend std::ostream& operator<<(std::ostream& os, const FramePlacementTpl<Scalar>& X) { os << " frame: " << X.frame << std::endl << "placement: " << std::endl << X.oMf << std::endl; return os; } FrameIndex frame; pinocchio::SE3Tpl<Scalar> oMf; }; template <typename _Scalar> struct FrameMotionTpl { EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef _Scalar Scalar; typedef pinocchio::MotionTpl<Scalar> Motion; explicit FrameMotionTpl() : frame(0), oMf(Motion::Zero()) {} FrameMotionTpl(const FrameMotionTpl<Scalar>& value) : frame(value.frame), oMf(value.oMf) {} FrameMotionTpl(const FrameIndex& frame, const Motion& oMf) : frame(frame), oMf(oMf) {} friend std::ostream& operator<<(std::ostream& os, const FrameMotionTpl<Scalar>& X) { os << " frame: " << X.frame << std::endl << "motion: " << std::endl << X.oMf << std::endl; return os; } FrameIndex frame; pinocchio::MotionTpl<Scalar> oMf; }; template <typename _Scalar> struct FrameForceTpl { EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef _Scalar Scalar; typedef pinocchio::ForceTpl<Scalar> Force; explicit FrameForceTpl() : frame(0), oFf(Force::Zero()) {} FrameForceTpl(const FrameForceTpl<Scalar>& value) : frame(value.frame), oFf(value.oFf) {} FrameForceTpl(const FrameIndex& frame, const Force& oFf) : frame(frame), oFf(oFf) {} friend std::ostream& operator<<(std::ostream& os, const FrameForceTpl<Scalar>& X) { os << "frame: " << X.frame << std::endl << "force: " << std::endl << X.oFf << std::endl; return os; } FrameIndex frame; pinocchio::ForceTpl<Scalar> oFf; }; template <typename _Scalar> struct FrameFrictionConeTpl { EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef _Scalar Scalar; typedef FrictionConeTpl<Scalar> FrictionCone; explicit FrameFrictionConeTpl() : frame(0), oRf(FrictionCone()) {} FrameFrictionConeTpl(const FrameFrictionConeTpl<Scalar>& value) : frame(value.frame), oRf(value.oRf) {} FrameFrictionConeTpl(const FrameIndex& frame, const FrictionCone& oRf) : frame(frame), oRf(oRf) {} friend std::ostream& operator<<(std::ostream& os, const FrameFrictionConeTpl& X) { os << "frame: " << X.frame << std::endl << " cone: " << std::endl << X.oRf << std::endl; return os; } FrameIndex frame; FrictionCone oRf; }; template <typename _Scalar> class FrameCoPSupportTpl { EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef _Scalar Scalar; typedef typename MathBaseTpl<Scalar>::Vector2s Vector2s; typedef typename MathBaseTpl<Scalar>::Vector3s Vector3s; typedef Eigen::Matrix<Scalar, 4, 6> Matrix46; public: explicit FrameCoPSupportTpl() : frame_(0), support_region_(Vector2s::Zero()) { update_A(); } FrameCoPSupportTpl(const FrameCoPSupportTpl<Scalar>& value) : frame_(value.get_frame()), support_region_(value.get_support_region()), A_(value.get_A()) {} FrameCoPSupportTpl(const FrameIndex& frame, const Vector2s& support_region) : frame_(frame), support_region_(support_region) { update_A(); } friend std::ostream& operator<<(std::ostream& os, const FrameCoPSupportTpl<Scalar>& X) { os << " frame: " << X.get_frame() << std::endl << "foot dimensions: " << std::endl << X.get_support_region() << std::endl; return os; } // Define the inequality matrix A to implement A * f >= 0. Compare eq.(18-19) in // https://hal.archives-ouvertes.fr/hal-02108449/document void update_A() { A_ << Scalar(0), Scalar(0), support_region_[0] / Scalar(2), Scalar(0), Scalar(-1), Scalar(0), Scalar(0), Scalar(0), support_region_[0] / Scalar(2), Scalar(0), Scalar(1), Scalar(0), Scalar(0), Scalar(0), support_region_[1] / Scalar(2), Scalar(1), Scalar(0), Scalar(0), Scalar(0), Scalar(0), support_region_[1] / Scalar(2), Scalar(-1), Scalar(0), Scalar(0); } void set_frame(FrameIndex frame) { frame_ = frame; } void set_support_region(const Vector2s& support_region) { support_region_ = support_region; update_A(); } const FrameIndex& get_frame() const { return frame_; } const Vector2s& get_support_region() const { return support_region_; } const Matrix46& get_A() const { return A_; } private: FrameIndex frame_; //!< contact frame ID Vector2s support_region_; //!< cop support region = (length, width) Matrix46 A_; //!< inequality matrix }; } // namespace crocoddyl #endif // CROCODDYL_MULTIBODY_FRAMES_HPP_
36.387435
119
0.684029
ggory15
21a8243a1b25a7c9c5eb843cc756b8ef79e3e2ad
789
cpp
C++
src/cpp/common/acsNtripStream.cpp
RodrigoNaves/ginan-bitbucket-update-tests
4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c
[ "Apache-2.0" ]
73
2021-07-08T23:35:08.000Z
2022-03-31T15:17:58.000Z
src/cpp/common/acsNtripStream.cpp
RodrigoNaves/ginan-bitbucket-update-tests
4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c
[ "Apache-2.0" ]
5
2021-09-27T14:27:32.000Z
2022-03-21T23:50:02.000Z
src/cpp/common/acsNtripStream.cpp
RodrigoNaves/ginan-bitbucket-update-tests
4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c
[ "Apache-2.0" ]
39
2021-07-12T05:42:51.000Z
2022-03-31T15:15:34.000Z
#include "acsNtripStream.hpp" #include <boost/system/error_code.hpp> #include <list> void NtripStream::getData() { receivedDataBufferMtx.lock(); //if ( receivedDataBuffer.size() > 0 ) // BOOST_LOG_TRIVIAL(debug) << "NtripStream::getData(), receivedDataBuffer.size() = " << receivedDataBuffer.size() << std::endl; receivedData.insert(receivedData.end(), receivedDataBuffer.begin(), receivedDataBuffer.end()); receivedDataBuffer.clear(); receivedDataBufferMtx.unlock(); } void NtripStream::connected() { start_read_stream(); } bool NtripStream::dataChunkDownloaded(vector<char> dataChunk) { receivedDataBufferMtx.lock(); for ( int j = 0; j < chunked_message_length; j++ ) receivedDataBuffer.push_back(dataChunk[j]); receivedDataBufferMtx.unlock(); return false; }
24.65625
132
0.737643
RodrigoNaves
21a97cdb8a3aca9743c770e22e6a6be248f6da18
1,163
cpp
C++
bzoj/1064.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
3
2017-09-17T09:12:50.000Z
2018-04-06T01:18:17.000Z
bzoj/1064.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
bzoj/1064.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
#include <bits/stdc++.h> using namespace std; inline int read(){ int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+ch-'0';ch=getchar();} return x*f; } const int inf = 1<<30; int n, m, cnt, maxn, minx, ans, tmp; struct edge{int to,nxt,val;}e[2000020]; int head[100020], vis[100020], mark[100020]; void ins(int x, int y, int v){ e[++cnt].nxt = head[x]; e[cnt].to = y; e[head[x]=cnt].val = v; } void ins(int x, int y){ ins(x, y, 1); ins(y, x, -1); } int gcd(int a, int b){return b?gcd(b, a%b):a;} void dfs(int x, int len){ if(vis[x]){ans = gcd(ans, abs(mark[x]-len)); return;} vis[x] = 1; mark[x] = len; maxn = max(maxn, len); minx = min(minx, len); for(int i = head[x]; i; i=e[i].nxt) dfs(e[i].to, len+e[i].val); } int main(){ n=read(); m=read(); for(int i = 1,x,y; i <= m; i++){ x=read();y=read(); ins(x, y); } for(int i = 1; i <= n; i++){ if(vis[i]) continue; minx = inf; maxn = -inf; dfs(i, 1); tmp += maxn-minx+1; } int ans2 = 3; if(!ans) ans = tmp; else while(ans2<=ans&&ans%ans2)ans2++; if(ans<3) puts("-1 -1"); else printf("%d %d\n", ans, ans2); }
24.744681
62
0.545142
swwind
21afeaaaffd32f0e17161a02333cff232f80cdef
790
hpp
C++
src/beast/include/beast/core/detail/clamp.hpp
Py9595/Backpack-Travel-Underlying-Code
c5758792eba7cdd62cb6ff46e642e8e4e4e5417e
[ "BSL-1.0" ]
5
2018-02-02T04:50:43.000Z
2020-10-14T08:15:01.000Z
src/beast/include/beast/core/detail/clamp.hpp
Py9595/Backpack-Travel-Underlying-Code
c5758792eba7cdd62cb6ff46e642e8e4e4e5417e
[ "BSL-1.0" ]
10
2019-01-07T05:33:34.000Z
2020-07-15T00:09:26.000Z
src/beast/include/beast/core/detail/clamp.hpp
Py9595/Backpack-Travel-Underlying-Code
c5758792eba7cdd62cb6ff46e642e8e4e4e5417e
[ "BSL-1.0" ]
4
2017-06-06T12:49:07.000Z
2021-07-01T07:44:49.000Z
// // Copyright (c) 2013-2017 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BEAST_CORE_DETAIL_CLAMP_HPP #define BEAST_CORE_DETAIL_CLAMP_HPP #include <limits> #include <cstdlib> namespace beast { namespace detail { template<class UInt> static std::size_t clamp(UInt x) { if(x >= (std::numeric_limits<std::size_t>::max)()) return (std::numeric_limits<std::size_t>::max)(); return static_cast<std::size_t>(x); } template<class UInt> static std::size_t clamp(UInt x, std::size_t limit) { if(x >= limit) return limit; return static_cast<std::size_t>(x); } } // detail } // beast #endif
19.268293
79
0.696203
Py9595
21b0580c4ba426b315ac89f33121ce92e45e01e7
1,098
cpp
C++
src/main.cpp
rathyon/xgp
8aba899746665d4d6afd51c9e83d5065e2f51abb
[ "MIT" ]
null
null
null
src/main.cpp
rathyon/xgp
8aba899746665d4d6afd51c9e83d5065e2f51abb
[ "MIT" ]
null
null
null
src/main.cpp
rathyon/xgp
8aba899746665d4d6afd51c9e83d5065e2f51abb
[ "MIT" ]
null
null
null
#include "XGPApp.h" using namespace xgp; XGPApp* app; void errorCallback(int error, const char* description) { app->errorCallback(error, description); } void reshapeCallback(GLFWwindow* window, int width, int height) { app->reshapeCallback(width, height); } void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { app->keyCallback(key, scancode, action, mods); } void mouseButtonCallback(GLFWwindow* window, int button, int action, int mods) { app->mouseButtonCallback(button, action, mods); } void mousePosCallback(GLFWwindow* window, double xpos, double ypos) { app->mousePosCallback(xpos, ypos); } int main() { app = new XGPApp("XGP - eXperimental Graphics Program", 640, 480); app->init(); //Set callbacks glfwSetErrorCallback(errorCallback); glfwSetFramebufferSizeCallback(app->window(), reshapeCallback); glfwSetKeyCallback(app->window(), keyCallback); glfwSetMouseButtonCallback(app->window(), mouseButtonCallback); glfwSetCursorPosCallback(app->window(), mousePosCallback); app->loop(); app->cleanup(); delete app; exit(EXIT_SUCCESS); }
26.780488
83
0.752277
rathyon
21b6c0fcfb8354aeeebc7f80a886fac90f1979fc
2,318
cpp
C++
odevice/app/src/main/jni/ParallelME/runtime/src/parallelme/Runtime.cpp
rcarvs/android-ocr
f8760afd378607ced0beca0b2c1beda14ea4ab49
[ "MIT" ]
5
2016-08-09T17:09:46.000Z
2020-12-12T21:17:33.000Z
src/parallelme/Runtime.cpp
ParallelME/runtime
80c3104c88e8efe9e4d746aa2976702c84f6302d
[ "Apache-2.0" ]
12
2016-04-07T19:42:02.000Z
2017-06-12T13:37:50.000Z
src/parallelme/Runtime.cpp
ParallelME/runtime
80c3104c88e8efe9e4d746aa2976702c84f6302d
[ "Apache-2.0" ]
2
2017-04-07T20:31:10.000Z
2021-04-19T23:24:38.000Z
/* _ __ ____ * _ __ ___ _____ ___ __ __ ___ __ / | / / __/ * | _ \/ _ | _ | / _ | / / / / / __/ / / | / / /__ * | __/ __ | ___|/ __ |/ /_/ /__/ __/ /__ / / v / /__ * |_| /_/ |_|_|\_\/_/ |_/____/___/___/____/ /_/ /_/____/ * */ #include <parallelme/Runtime.hpp> #include <parallelme/Task.hpp> #include "Worker.hpp" #include "dynloader/dynLoader.h" using namespace parallelme; Runtime::~Runtime() = default; void Runtime::loadDevices() { if(!dynLoadOpenCL()) throw RuntimeConstructionError("No OpenCL devices found."); int err; // Get the number of platforms. unsigned numPlatforms; err = clGetPlatformIDs(0, nullptr, &numPlatforms); if(err < 0) throw RuntimeConstructionError(std::to_string(err)); // Get the platforms. auto platforms = std::unique_ptr<cl_platform_id []>{new cl_platform_id[numPlatforms]}; err = clGetPlatformIDs(numPlatforms, platforms.get(), nullptr); if(err < 0) throw RuntimeConstructionError(std::to_string(err)); // Initialize the devices for each platform. for(unsigned i = 0; i < numPlatforms; ++i) { unsigned numDevices; err = clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_ALL, 0, nullptr, &numDevices); if(err < 0) throw RuntimeConstructionError(std::to_string(err)); std::unique_ptr<cl_device_id []> devices{new cl_device_id[numDevices]}; err = clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_ALL, numDevices, devices.get(), nullptr); if(err < 0) throw RuntimeConstructionError(std::to_string(err)); for(unsigned j = 0; j < numDevices; ++j) _devices.push_back(std::make_shared<Device>(devices[j])); } } void Runtime::startWorkers(JavaVM *jvm) { for(auto &device : _devices) _workers.push_back(std::make_shared<Worker>(device)); for(auto &worker : _workers) worker->run(_scheduler, jvm); } void Runtime::submitTask(std::unique_ptr<Task> task) { _scheduler->push(std::move(task)); for(auto &worker : _workers) worker->wakeUp(); } void Runtime::finish() { _scheduler->waitUntilIdle(); for(auto &worker : _workers) worker->finish(); }
30.5
79
0.597929
rcarvs
21b7b165f624e89398583caebcbdf007153ffcea
6,181
cpp
C++
qmk_firmware/quantum/serial_link/tests/transport_tests.cpp
igagis/best84kb
e4f58e0138b0835b39e636d69658183a8e74594e
[ "MIT" ]
2
2019-05-13T05:19:02.000Z
2021-11-29T09:07:43.000Z
qmk_firmware/quantum/serial_link/tests/transport_tests.cpp
igagis/best84kb
e4f58e0138b0835b39e636d69658183a8e74594e
[ "MIT" ]
null
null
null
qmk_firmware/quantum/serial_link/tests/transport_tests.cpp
igagis/best84kb
e4f58e0138b0835b39e636d69658183a8e74594e
[ "MIT" ]
1
2020-11-05T02:23:49.000Z
2020-11-05T02:23:49.000Z
/* The MIT License (MIT) Copyright (c) 2016 Fred Sundvik Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "gtest/gtest.h" #include "gmock/gmock.h" using testing::_; using testing::ElementsAreArray; using testing::Args; extern "C" { #include "serial_link/protocol/transport.h" } struct test_object1 { uint32_t test; }; struct test_object2 { uint32_t test1; uint32_t test2; }; MASTER_TO_ALL_SLAVES_OBJECT(master_to_slave, test_object1); MASTER_TO_SINGLE_SLAVE_OBJECT(master_to_single_slave, test_object1); SLAVE_TO_MASTER_OBJECT(slave_to_master, test_object1); static remote_object_t* test_remote_objects[] = { REMOTE_OBJECT(master_to_slave), REMOTE_OBJECT(master_to_single_slave), REMOTE_OBJECT(slave_to_master), }; class Transport : public testing::Test { public: Transport() { Instance = this; add_remote_objects(test_remote_objects, sizeof(test_remote_objects) / sizeof(remote_object_t*)); } ~Transport() { Instance = nullptr; reinitialize_serial_link_transport(); } MOCK_METHOD0(signal_data_written, void ()); MOCK_METHOD1(router_send_frame, void (uint8_t destination)); void router_send_frame(uint8_t destination, uint8_t* data, uint16_t size) { router_send_frame(destination); std::copy(data, data + size, std::back_inserter(sent_data)); } static Transport* Instance; std::vector<uint8_t> sent_data; }; Transport* Transport::Instance = nullptr; extern "C" { void signal_data_written(void) { Transport::Instance->signal_data_written(); } void router_send_frame(uint8_t destination, uint8_t* data, uint16_t size) { Transport::Instance->router_send_frame(destination, data, size); } } TEST_F(Transport, write_to_local_signals_an_event) { begin_write_master_to_slave(); EXPECT_CALL(*this, signal_data_written()); end_write_master_to_slave(); begin_write_slave_to_master(); EXPECT_CALL(*this, signal_data_written()); end_write_slave_to_master(); begin_write_master_to_single_slave(1); EXPECT_CALL(*this, signal_data_written()); end_write_master_to_single_slave(1); } TEST_F(Transport, writes_from_master_to_all_slaves) { update_transport(); test_object1* obj = begin_write_master_to_slave(); obj->test = 5; EXPECT_CALL(*this, signal_data_written()); end_write_master_to_slave(); EXPECT_CALL(*this, router_send_frame(0xFF)); update_transport(); transport_recv_frame(0, sent_data.data(), sent_data.size()); test_object1* obj2 = read_master_to_slave(); EXPECT_NE(obj2, nullptr); EXPECT_EQ(obj2->test, 5); } TEST_F(Transport, writes_from_slave_to_master) { update_transport(); test_object1* obj = begin_write_slave_to_master(); obj->test = 7; EXPECT_CALL(*this, signal_data_written()); end_write_slave_to_master(); EXPECT_CALL(*this, router_send_frame(0)); update_transport(); transport_recv_frame(3, sent_data.data(), sent_data.size()); test_object1* obj2 = read_slave_to_master(2); EXPECT_EQ(read_slave_to_master(0), nullptr); EXPECT_NE(obj2, nullptr); EXPECT_EQ(obj2->test, 7); } TEST_F(Transport, writes_from_master_to_single_slave) { update_transport(); test_object1* obj = begin_write_master_to_single_slave(3); obj->test = 7; EXPECT_CALL(*this, signal_data_written()); end_write_master_to_single_slave(3); EXPECT_CALL(*this, router_send_frame(4)); update_transport(); transport_recv_frame(0, sent_data.data(), sent_data.size()); test_object1* obj2 = read_master_to_single_slave(); EXPECT_NE(obj2, nullptr); EXPECT_EQ(obj2->test, 7); } TEST_F(Transport, ignores_object_with_invalid_id) { update_transport(); test_object1* obj = begin_write_master_to_single_slave(3); obj->test = 7; EXPECT_CALL(*this, signal_data_written()); end_write_master_to_single_slave(3); EXPECT_CALL(*this, router_send_frame(4)); update_transport(); sent_data[sent_data.size() - 1] = 44; transport_recv_frame(0, sent_data.data(), sent_data.size()); test_object1* obj2 = read_master_to_single_slave(); EXPECT_EQ(obj2, nullptr); } TEST_F(Transport, ignores_object_with_size_too_small) { update_transport(); test_object1* obj = begin_write_master_to_slave(); obj->test = 7; EXPECT_CALL(*this, signal_data_written()); end_write_master_to_slave(); EXPECT_CALL(*this, router_send_frame(_)); update_transport(); sent_data[sent_data.size() - 2] = 0; transport_recv_frame(0, sent_data.data(), sent_data.size() - 1); test_object1* obj2 = read_master_to_slave(); EXPECT_EQ(obj2, nullptr); } TEST_F(Transport, ignores_object_with_size_too_big) { update_transport(); test_object1* obj = begin_write_master_to_slave(); obj->test = 7; EXPECT_CALL(*this, signal_data_written()); end_write_master_to_slave(); EXPECT_CALL(*this, router_send_frame(_)); update_transport(); sent_data.resize(sent_data.size() + 22); sent_data[sent_data.size() - 1] = 0; transport_recv_frame(0, sent_data.data(), sent_data.size()); test_object1* obj2 = read_master_to_slave(); EXPECT_EQ(obj2, nullptr); }
32.703704
104
0.738554
igagis
21c04010e161eed4e3d4bc7c6c16d1be21dec5af
2,977
hpp
C++
src/number_theory/modulo.hpp
RamchandraApte/OmniTemplate
f150f451871b0ab43ac39a798186278106da1527
[ "MIT" ]
14
2019-04-23T21:44:12.000Z
2022-03-04T22:48:59.000Z
src/number_theory/modulo.hpp
RamchandraApte/OmniTemplate
f150f451871b0ab43ac39a798186278106da1527
[ "MIT" ]
3
2019-04-25T10:45:32.000Z
2020-08-05T22:40:39.000Z
src/number_theory/modulo.hpp
RamchandraApte/OmniTemplate
f150f451871b0ab43ac39a798186278106da1527
[ "MIT" ]
1
2020-07-16T22:16:33.000Z
2020-07-16T22:16:33.000Z
#pragma once #include "core/all.hpp" namespace modulo_namespace { template <typename... Args> using invert_t = decltype(invert(std::declval<Args>()...)); /*! @brief Returns \f$a^b\f$ * @param a the base * @param b the exponent * * Time complexity: \f$O(\log_2 |b|)\f$ multiplications */ template <typename T> T power(T a, ll b) { if (b < 0) { if constexpr (experimental::is_detected_v<invert_t, multiplies<>, decltype(a)>) { a = invert(multiplies{}, a); b = -b; } else { assert(("b < 0 but unable to inverse a", false)); } } T ret = identity(multiplies<>{}, a); for (; b; b >>= 1, a *= a) { if (b & 1) { ret *= a; } } return ret; } /*! @brief Returns the remainder of a divided by b as a nonnegative integer in [0, b).*/ ll mod(ll a, const ll b) { a %= b; if (a < 0) { a += b; } return a; } /*! Set a to the remainder when divided by b. */ ll mod_eq(ll &a, const ll b) { return a = mod(a, b); } /*! no_mod tag class allows a modulo object to be quickly constructed from an integer in the range * [0, b) without performing a modulo operation.*/ struct no_mod {}; struct modulo { inline static ll modulus = 1e9 + 7; //!< Modulus used for operations like modular multiplication /*! Modular arithmetic class */ ll x; //!< The representative element, which is in [0, M) modulo() : x{0LL} {} template <typename T, typename = enable_if_t<is_integral<T>::value, void>> modulo(T x_) : x(mod(x_, modulo::modulus)) {} modulo(ll x_, no_mod) : x(x_) {} explicit operator auto() const { return x; } }; modulo operator"" _M(const unsigned long long x) { return modulo{x}; } modulo identity(plus<>, modulo) { return 0; } modulo identity(multiplies<>, modulo) { return 1; } modulo operator+(modulo const &a, modulo const &b) { ll const sum = a.x + b.x; return {sum >= modulo::modulus ? sum - modulo::modulus : sum, no_mod{}}; } modulo operator++(modulo &a) { return a += 1; } modulo operator-(modulo const &a) { return {modulo::modulus - a.x, no_mod{}}; } // To avoid ADL issues using ::operator-; bin(==, modulo); modulo operator*(modulo const &a, modulo const &b) { /*! Computes a times b modulo modulo::modulus using long double */ const ull quot = ld(a.x) * ld(b.x) / ld(modulo::modulus); // Computes the approximate remainder const ll rem = ull(a.x) * ull(b.x) - ull(modulo::modulus) * quot; if (rem < 0) { return {rem + modulo::modulus, no_mod{}}; } if (rem >= modulo::modulus) { return {rem - modulo::modulus, no_mod{}}; } return {rem, no_mod{}}; } modulo invert(multiplies<>, modulo const &b) { /*! Computes the modular inverse \f$b^{-1} \pmod{M}\f$ */ assert(b != 0); return power(b, modulo::modulus - 2); } using ::operator/; template <typename Stream> auto &operator<<(Stream &os, modulo const &m) { return os << m.x; } } // namespace modulo_namespace using namespace modulo_namespace; namespace std { template <> struct hash<modulo> { ll operator()(modulo const &x) const { return x.x; } }; } // namespace std
32.714286
98
0.642257
RamchandraApte
21cb346ca25d20a839156d4a39c533e1731addd1
737
cpp
C++
Questions Level-Wise/Hard/find-minimum-in-rotated-sorted-array-ii.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
2
2021-03-05T22:32:23.000Z
2021-03-05T22:32:29.000Z
Questions Level-Wise/Hard/find-minimum-in-rotated-sorted-array-ii.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
null
null
null
Questions Level-Wise/Hard/find-minimum-in-rotated-sorted-array-ii.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
null
null
null
class Solution { public: int binarysearch(vector<int> nums,int l,int h) { while(l<h) { int mid=(h-l)/2+l; if(nums[l]<nums[h]) return nums[l]; else if(l+1==h) return nums[h]; else if(nums[l]>=nums[mid]&&nums[mid]<=nums[h]) { int temp1=binarysearch(nums,l,mid); int temp2=binarysearch(nums,mid,h); if(temp1<temp2) return temp1; return temp2; } else l=mid; } return nums[0]; } int findMin(vector<int>& nums) { return binarysearch(nums,0,nums.size()-1); } };
24.566667
59
0.419267
PrakharPipersania
21cca6a5317fcb2283a18c2ce3170313a1fa433f
757
cpp
C++
locs.cpp
yurivict/crate
cf25e21ad2b7bce320c5d04a6ad27c8e67d4e09f
[ "BSD-3-Clause" ]
14
2019-08-04T13:03:10.000Z
2021-03-14T13:19:55.000Z
locs.cpp
yurivict/crate
cf25e21ad2b7bce320c5d04a6ad27c8e67d4e09f
[ "BSD-3-Clause" ]
null
null
null
locs.cpp
yurivict/crate
cf25e21ad2b7bce320c5d04a6ad27c8e67d4e09f
[ "BSD-3-Clause" ]
2
2020-05-08T04:52:13.000Z
2021-03-14T13:20:38.000Z
// Copyright (C) 2019 by Yuri Victorovich. All rights reserved. #include "locs.h" #include "util.h" #include <string> namespace Locations { const char *jailDirectoryPath = "/var/run/crate"; const char *jailSubDirectoryIfaces = "/ifaces"; const char *cacheDirectoryPath = "/var/cache/crate"; const std::string ctxFwUsersFilePath = std::string(jailDirectoryPath) + "/ctx-firewall-users"; const std::string baseArchive = std::string(Locations::cacheDirectoryPath) + "/base.txz"; const std::string baseArchiveUrl = STRg("ftp://ftp1.freebsd.org/pub/FreeBSD/snapshots/" << Util::getSysctlString("hw.machine") << "/" << Util::getSysctlString("kern.osrelease") << "/base.txz"); }
37.85
128
0.652576
yurivict
21d0edae97d5d9f1b8d6bc3ff5d01a05b2e4fd7a
1,797
cpp
C++
oneEngine/oneGame/source/engine/physics/collider/types/CBoxCollider.cpp
jonting/1Engine
f22ba31f08fa96fe6405ebecec4f374138283803
[ "BSD-3-Clause" ]
8
2017-12-08T02:59:31.000Z
2022-02-02T04:30:03.000Z
oneEngine/oneGame/source/engine/physics/collider/types/CBoxCollider.cpp
jonting/1Engine
f22ba31f08fa96fe6405ebecec4f374138283803
[ "BSD-3-Clause" ]
2
2021-04-16T03:44:42.000Z
2021-08-30T06:48:44.000Z
oneEngine/oneGame/source/engine/physics/collider/types/CBoxCollider.cpp
jonting/1Engine
f22ba31f08fa96fe6405ebecec4f374138283803
[ "BSD-3-Clause" ]
1
2021-04-16T02:09:54.000Z
2021-04-16T02:09:54.000Z
#include "engine/physics/motion/CRigidbody.h" #include "CBoxCollider.h" #include "physical/physics/shapes/physBoxShape.h" CBoxCollider::CBoxCollider ( Vector3d const& size ) { vExtents = size; vCenterOfMass = Vector3d( 0,0,0 ); //pCollisionShape = Physics::CreateBoxShape( vExtents * 0.5f ); pCollisionShape = new physBoxShape( vExtents * 0.5f ); } CBoxCollider::CBoxCollider ( BoundingBox const& bbox, Vector3d const& pos ) { vExtents = bbox.GetSize(); //vCenterOfMass = bbox.GetCenterPoint() - pos; vCenterOfMass = pos; //pCollisionShape = Physics::CreateBoxShape( vExtents * 0.5f ); //pCollisionShape = Physics::CreateBoxShape( vExtents * 0.5f, bbox.GetCenterPoint() ); pCollisionShape = new physBoxShape( vExtents * 0.5f, bbox.GetCenterPoint() ); } CBoxCollider::~CBoxCollider ( void ) { Physics::FreeShape( pCollisionShape ); } // Setters void CBoxCollider::SetSize ( Vector3d const& size ) { // Set the current extents of the collider vExtents = size; // Get the Havok object and set the size of it. ((physBoxShape*)pCollisionShape)->setHalfExtents( Vector3d( vExtents.x*0.5f, vExtents.y*0.5f, vExtents.z*0.5f ) ); // Change the rigid body's current shape to the new collider object if ( pRigidBody ) pRigidBody->SetShape( pCollisionShape ); } void CBoxCollider::Set ( BoundingBox const& bbox, Vector3d const& pos ) { vExtents = bbox.GetSize(); vCenterOfMass = bbox.GetCenterPoint() - pos; // Get the Havok object and set the size of it. ((physBoxShape*)pCollisionShape)->setHalfExtents( Vector3d( vExtents.x*0.5f, vExtents.y*0.5f, vExtents.z*0.5f ) ); // Change the rigid body's current shape to the new collider object if ( pRigidBody ) pRigidBody->SetShape( pCollisionShape ); } // Getters Vector3d CBoxCollider::GetSize ( void ) { return vExtents; }
30.457627
115
0.72788
jonting
21d3802f04245351d855c9ca5900a75a6cde87b5
2,522
cpp
C++
src/EZOI/1018/kaleidoscope.cpp
krishukr/cpp-code
1c94401682227bd86c0d9295134d43582247794e
[ "MIT" ]
1
2021-08-13T14:27:39.000Z
2021-08-13T14:27:39.000Z
src/EZOI/1018/kaleidoscope.cpp
krishukr/cpp-code
1c94401682227bd86c0d9295134d43582247794e
[ "MIT" ]
null
null
null
src/EZOI/1018/kaleidoscope.cpp
krishukr/cpp-code
1c94401682227bd86c0d9295134d43582247794e
[ "MIT" ]
null
null
null
#include <algorithm> #include <cstdio> #include <iostream> typedef long long ll; int n, m; template <typename T> T read(); class Star { private: const static int MAX_N = 200050; public: struct Node { int v; int nxt; ll w; } node[MAX_N << 1]; int head[MAX_N]; int cnt; void create(int u, int v, ll w) { node[++cnt].v = v; node[cnt].nxt = head[u]; node[cnt].w = w; head[u] = cnt; } }; class MST { private: Star* star; const static int MAX_N = 200050; protected: ll dis[MAX_N]; bool vis[MAX_N]; int tot, crt = 1; public: MST(Star* star) { this->star = star; } ll prim() { std::fill(dis, dis + n + 10, 0x3f3f3f3f3f3f3f3f); for (int i = star->head[1]; i; i = star->node[i].nxt) { int v = star->node[i].v; dis[v] = std::min(dis[v], star->node[i].w); } ll ans = 0; while (++tot < n) { ll min = 0x3f3f3f3f3f3f3f3f; vis[crt] = true; for (int i = 1; i <= n; i++) { if (!vis[i] and min > dis[i]) { min = dis[i]; crt = i; } } ans += min; for (int i = star->head[crt]; i; i = star->node[i].nxt) { int v = star->node[i].v; ll w = star->node[i].w; if (dis[v] > w and !vis[v]) { dis[v] = w; } } } return ans; } }; signed main() { freopen("kaleidoscope.in", "r", stdin); freopen("kaleidoscope.out", "w", stdout); int t = read<int>(); while (t--) { n = read<int>(), m = read<int>(); Star* star = new Star(); for (int i = 1; i <= m; i++) { int x = read<int>(), y = read<int>(); ll z = read<ll>(); for (int i = 0; i < n; i++) { star->create((x + i) % n + 1, (y + i) % n + 1, z); star->create((y + i) % n + 1, (x + i) % n + 1, z); } } MST* mst = new MST(star); std::cout << mst->prim() << '\n'; } fclose(stdin); fclose(stdout); return 0; } template <typename T> T read() { T x = 0, 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; }
21.016667
69
0.406027
krishukr
21d677c56deb7822da554788ffea2a4b46844ef7
4,985
cpp
C++
wbc/ahl_robot/src/utils/math.cpp
daichi-yoshikawa/ahl_wbc
ea241562e521c7509d3b0405393996998f7cdc6e
[ "BSD-3-Clause" ]
33
2015-12-16T15:32:22.000Z
2022-03-21T05:09:40.000Z
wbc/ahl_robot/src/utils/math.cpp
daichi-yoshikawa/ahl_wbc
ea241562e521c7509d3b0405393996998f7cdc6e
[ "BSD-3-Clause" ]
3
2016-06-08T09:53:44.000Z
2020-10-26T11:27:23.000Z
wbc/ahl_robot/src/utils/math.cpp
daichi-yoshikawa/ahl_wbc
ea241562e521c7509d3b0405393996998f7cdc6e
[ "BSD-3-Clause" ]
10
2016-01-27T10:30:01.000Z
2022-03-21T05:08:27.000Z
/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2015, Daichi Yoshikawa * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Daichi Yoshikawa nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Author: Daichi Yoshikawa * *********************************************************************/ #include <iostream> #include "ahl_robot/utils/math.hpp" namespace ahl_robot { namespace math { void computeEr(const Eigen::Quaternion<double>& q, Eigen::MatrixXd& Er) { Er.resize(4, 3); Er << -q.x(), -q.y(), -q.z(), q.w(), q.z(), -q.y(), -q.z(), q.w(), q.x(), q.y(), -q.x(), q.w(); Er = 0.5 * Er; } void calculateInverseTransformationMatrix(const Eigen::Matrix4d& src, Eigen::Matrix4d& dst) { dst = Eigen::Matrix4d::Identity(); Eigen::Matrix3d R_trans = src.block(0, 0, 3, 3).transpose(); dst.block(0, 0, 3, 3) = R_trans; dst.block(0, 3, 3, 1) = -R_trans * src.block(0, 3, 3, 1); } void rpyToRotationMatrix(const std::vector<double>& rpy, Eigen::Matrix3d& mat) { double sin_a = sin(rpy[2]); double cos_a = cos(rpy[2]); double sin_b = sin(rpy[1]); double cos_b = cos(rpy[1]); double sin_g = sin(rpy[0]); double cos_g = cos(rpy[0]); mat.coeffRef(0, 0) = cos_a * cos_b; mat.coeffRef(0, 1) = cos_a * sin_b * sin_g - sin_a * cos_g; mat.coeffRef(0, 2) = cos_a * sin_b * cos_g + sin_a * sin_g; mat.coeffRef(1, 0) = sin_a * cos_b; mat.coeffRef(1, 1) = sin_a * sin_b * sin_g + cos_a * cos_g; mat.coeffRef(1, 2) = sin_a * sin_b * cos_g - cos_a * sin_g; mat.coeffRef(2, 0) = -sin_b; mat.coeffRef(2, 1) = cos_b * sin_g; mat.coeffRef(2, 2) = cos_b * cos_g; } void rpyToRotationMatrix(const Eigen::Vector3d& rpy, Eigen::Matrix3d& mat) { double sin_a = sin(rpy.coeff(2)); double cos_a = cos(rpy.coeff(2)); double sin_b = sin(rpy.coeff(1)); double cos_b = cos(rpy.coeff(1)); double sin_g = sin(rpy.coeff(0)); double cos_g = cos(rpy.coeff(0)); mat.coeffRef(0, 0) = cos_a * cos_b; mat.coeffRef(0, 1) = cos_a * sin_b * sin_g - sin_a * cos_g; mat.coeffRef(0, 2) = cos_a * sin_b * cos_g + sin_a * sin_g; mat.coeffRef(1, 0) = sin_a * cos_b; mat.coeffRef(1, 1) = sin_a * sin_b * sin_g + cos_a * cos_g; mat.coeffRef(1, 2) = sin_a * sin_b * cos_g - cos_a * sin_g; mat.coeffRef(2, 0) = -sin_b; mat.coeffRef(2, 1) = cos_b * sin_g; mat.coeffRef(2, 2) = cos_b * cos_g; } void rpyToQuaternion(const Eigen::Vector3d& rpy, Eigen::Quaternion<double>& q) { double a = rpy.coeff(0); double b = rpy.coeff(1); double g = rpy.coeff(2); double sin_b_half = sin(0.5 * b); double cos_b_half = cos(0.5 * b); double diff_a_g_half = 0.5 * (a - g); double sum_a_g_half = 0.5 * (a + g); q.x() = sin_b_half * cos(diff_a_g_half); q.y() = sin_b_half * sin(diff_a_g_half); q.z() = cos_b_half * sin(sum_a_g_half); q.w() = cos_b_half * cos(sum_a_g_half); } void xyzrpyToTransformationMatrix(const Eigen::Vector3d& xyz, const Eigen::Vector3d& rpy, Eigen::Matrix4d& T) { T = Eigen::Matrix4d::Identity(); Eigen::Matrix3d R; rpyToRotationMatrix(rpy, R); T.block(0, 0, 3, 3) = R; T.block(0, 3, 3, 1) = xyz; } } // namespace math } // namespace ahl_robot
38.053435
113
0.608425
daichi-yoshikawa
21dcf21fc5692fa094e45e1ac901bd23ca517dbe
146
cpp
C++
MemLeak/src/Shape/Line/Line.cpp
pk8868/MemLeak
72f937110c2b67547f67bdea60d2e80b0f5581a1
[ "MIT" ]
null
null
null
MemLeak/src/Shape/Line/Line.cpp
pk8868/MemLeak
72f937110c2b67547f67bdea60d2e80b0f5581a1
[ "MIT" ]
null
null
null
MemLeak/src/Shape/Line/Line.cpp
pk8868/MemLeak
72f937110c2b67547f67bdea60d2e80b0f5581a1
[ "MIT" ]
null
null
null
#include "mpch.h" #include "Line.hpp" namespace ml { Line::Line(Vec2f a, Vec2f b) { transform.setPoint(a, 0); transform.setPoint(b, 1); } }
16.222222
31
0.650685
pk8868
21e7e4c022bf5ddcc7dc9dfefcdc89b2686c2df5
332
cpp
C++
docs/mfc/codesnippet/CPP/clistbox-class_29.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
965
2017-06-25T23:57:11.000Z
2022-03-31T14:17:32.000Z
docs/mfc/codesnippet/CPP/clistbox-class_29.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
3,272
2017-06-24T00:26:34.000Z
2022-03-31T22:14:07.000Z
docs/mfc/codesnippet/CPP/clistbox-class_29.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
951
2017-06-25T12:36:14.000Z
2022-03-26T22:49:06.000Z
void CMyODListBox::OnLButtonDown(UINT nFlags, CPoint point) { BOOL bOutside = TRUE; UINT uItem = ItemFromPoint(point, bOutside); if (!bOutside) { // Set the anchor to be the middle item. SetAnchorIndex(uItem); ASSERT((UINT)GetAnchorIndex() == uItem); } CListBox::OnLButtonDown(nFlags, point); }
23.714286
59
0.662651
bobbrow
21e857cd750b4772a92043e4d352ae467ee5893d
28,999
cpp
C++
cws/src/v20180312/CwsClient.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
cws/src/v20180312/CwsClient.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
cws/src/v20180312/CwsClient.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/cws/v20180312/CwsClient.h> #include <tencentcloud/core/Executor.h> #include <tencentcloud/core/Runnable.h> using namespace TencentCloud; using namespace TencentCloud::Cws::V20180312; using namespace TencentCloud::Cws::V20180312::Model; using namespace std; namespace { const string VERSION = "2018-03-12"; const string ENDPOINT = "cws.tencentcloudapi.com"; } CwsClient::CwsClient(const Credential &credential, const string &region) : CwsClient(credential, region, ClientProfile()) { } CwsClient::CwsClient(const Credential &credential, const string &region, const ClientProfile &profile) : AbstractClient(ENDPOINT, VERSION, credential, region, profile) { } CwsClient::CreateMonitorsOutcome CwsClient::CreateMonitors(const CreateMonitorsRequest &request) { auto outcome = MakeRequest(request, "CreateMonitors"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); CreateMonitorsResponse rsp = CreateMonitorsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return CreateMonitorsOutcome(rsp); else return CreateMonitorsOutcome(o.GetError()); } else { return CreateMonitorsOutcome(outcome.GetError()); } } void CwsClient::CreateMonitorsAsync(const CreateMonitorsRequest& request, const CreateMonitorsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->CreateMonitors(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::CreateMonitorsOutcomeCallable CwsClient::CreateMonitorsCallable(const CreateMonitorsRequest &request) { auto task = std::make_shared<std::packaged_task<CreateMonitorsOutcome()>>( [this, request]() { return this->CreateMonitors(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::CreateSitesOutcome CwsClient::CreateSites(const CreateSitesRequest &request) { auto outcome = MakeRequest(request, "CreateSites"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); CreateSitesResponse rsp = CreateSitesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return CreateSitesOutcome(rsp); else return CreateSitesOutcome(o.GetError()); } else { return CreateSitesOutcome(outcome.GetError()); } } void CwsClient::CreateSitesAsync(const CreateSitesRequest& request, const CreateSitesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->CreateSites(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::CreateSitesOutcomeCallable CwsClient::CreateSitesCallable(const CreateSitesRequest &request) { auto task = std::make_shared<std::packaged_task<CreateSitesOutcome()>>( [this, request]() { return this->CreateSites(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::CreateSitesScansOutcome CwsClient::CreateSitesScans(const CreateSitesScansRequest &request) { auto outcome = MakeRequest(request, "CreateSitesScans"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); CreateSitesScansResponse rsp = CreateSitesScansResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return CreateSitesScansOutcome(rsp); else return CreateSitesScansOutcome(o.GetError()); } else { return CreateSitesScansOutcome(outcome.GetError()); } } void CwsClient::CreateSitesScansAsync(const CreateSitesScansRequest& request, const CreateSitesScansAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->CreateSitesScans(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::CreateSitesScansOutcomeCallable CwsClient::CreateSitesScansCallable(const CreateSitesScansRequest &request) { auto task = std::make_shared<std::packaged_task<CreateSitesScansOutcome()>>( [this, request]() { return this->CreateSitesScans(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::CreateVulsMisinformationOutcome CwsClient::CreateVulsMisinformation(const CreateVulsMisinformationRequest &request) { auto outcome = MakeRequest(request, "CreateVulsMisinformation"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); CreateVulsMisinformationResponse rsp = CreateVulsMisinformationResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return CreateVulsMisinformationOutcome(rsp); else return CreateVulsMisinformationOutcome(o.GetError()); } else { return CreateVulsMisinformationOutcome(outcome.GetError()); } } void CwsClient::CreateVulsMisinformationAsync(const CreateVulsMisinformationRequest& request, const CreateVulsMisinformationAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->CreateVulsMisinformation(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::CreateVulsMisinformationOutcomeCallable CwsClient::CreateVulsMisinformationCallable(const CreateVulsMisinformationRequest &request) { auto task = std::make_shared<std::packaged_task<CreateVulsMisinformationOutcome()>>( [this, request]() { return this->CreateVulsMisinformation(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::CreateVulsReportOutcome CwsClient::CreateVulsReport(const CreateVulsReportRequest &request) { auto outcome = MakeRequest(request, "CreateVulsReport"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); CreateVulsReportResponse rsp = CreateVulsReportResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return CreateVulsReportOutcome(rsp); else return CreateVulsReportOutcome(o.GetError()); } else { return CreateVulsReportOutcome(outcome.GetError()); } } void CwsClient::CreateVulsReportAsync(const CreateVulsReportRequest& request, const CreateVulsReportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->CreateVulsReport(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::CreateVulsReportOutcomeCallable CwsClient::CreateVulsReportCallable(const CreateVulsReportRequest &request) { auto task = std::make_shared<std::packaged_task<CreateVulsReportOutcome()>>( [this, request]() { return this->CreateVulsReport(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DeleteMonitorsOutcome CwsClient::DeleteMonitors(const DeleteMonitorsRequest &request) { auto outcome = MakeRequest(request, "DeleteMonitors"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DeleteMonitorsResponse rsp = DeleteMonitorsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DeleteMonitorsOutcome(rsp); else return DeleteMonitorsOutcome(o.GetError()); } else { return DeleteMonitorsOutcome(outcome.GetError()); } } void CwsClient::DeleteMonitorsAsync(const DeleteMonitorsRequest& request, const DeleteMonitorsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DeleteMonitors(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DeleteMonitorsOutcomeCallable CwsClient::DeleteMonitorsCallable(const DeleteMonitorsRequest &request) { auto task = std::make_shared<std::packaged_task<DeleteMonitorsOutcome()>>( [this, request]() { return this->DeleteMonitors(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DeleteSitesOutcome CwsClient::DeleteSites(const DeleteSitesRequest &request) { auto outcome = MakeRequest(request, "DeleteSites"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DeleteSitesResponse rsp = DeleteSitesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DeleteSitesOutcome(rsp); else return DeleteSitesOutcome(o.GetError()); } else { return DeleteSitesOutcome(outcome.GetError()); } } void CwsClient::DeleteSitesAsync(const DeleteSitesRequest& request, const DeleteSitesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DeleteSites(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DeleteSitesOutcomeCallable CwsClient::DeleteSitesCallable(const DeleteSitesRequest &request) { auto task = std::make_shared<std::packaged_task<DeleteSitesOutcome()>>( [this, request]() { return this->DeleteSites(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DescribeConfigOutcome CwsClient::DescribeConfig(const DescribeConfigRequest &request) { auto outcome = MakeRequest(request, "DescribeConfig"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeConfigResponse rsp = DescribeConfigResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeConfigOutcome(rsp); else return DescribeConfigOutcome(o.GetError()); } else { return DescribeConfigOutcome(outcome.GetError()); } } void CwsClient::DescribeConfigAsync(const DescribeConfigRequest& request, const DescribeConfigAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeConfig(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DescribeConfigOutcomeCallable CwsClient::DescribeConfigCallable(const DescribeConfigRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeConfigOutcome()>>( [this, request]() { return this->DescribeConfig(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DescribeMonitorsOutcome CwsClient::DescribeMonitors(const DescribeMonitorsRequest &request) { auto outcome = MakeRequest(request, "DescribeMonitors"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeMonitorsResponse rsp = DescribeMonitorsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeMonitorsOutcome(rsp); else return DescribeMonitorsOutcome(o.GetError()); } else { return DescribeMonitorsOutcome(outcome.GetError()); } } void CwsClient::DescribeMonitorsAsync(const DescribeMonitorsRequest& request, const DescribeMonitorsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeMonitors(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DescribeMonitorsOutcomeCallable CwsClient::DescribeMonitorsCallable(const DescribeMonitorsRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeMonitorsOutcome()>>( [this, request]() { return this->DescribeMonitors(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DescribeSiteQuotaOutcome CwsClient::DescribeSiteQuota(const DescribeSiteQuotaRequest &request) { auto outcome = MakeRequest(request, "DescribeSiteQuota"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeSiteQuotaResponse rsp = DescribeSiteQuotaResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeSiteQuotaOutcome(rsp); else return DescribeSiteQuotaOutcome(o.GetError()); } else { return DescribeSiteQuotaOutcome(outcome.GetError()); } } void CwsClient::DescribeSiteQuotaAsync(const DescribeSiteQuotaRequest& request, const DescribeSiteQuotaAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeSiteQuota(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DescribeSiteQuotaOutcomeCallable CwsClient::DescribeSiteQuotaCallable(const DescribeSiteQuotaRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeSiteQuotaOutcome()>>( [this, request]() { return this->DescribeSiteQuota(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DescribeSitesOutcome CwsClient::DescribeSites(const DescribeSitesRequest &request) { auto outcome = MakeRequest(request, "DescribeSites"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeSitesResponse rsp = DescribeSitesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeSitesOutcome(rsp); else return DescribeSitesOutcome(o.GetError()); } else { return DescribeSitesOutcome(outcome.GetError()); } } void CwsClient::DescribeSitesAsync(const DescribeSitesRequest& request, const DescribeSitesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeSites(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DescribeSitesOutcomeCallable CwsClient::DescribeSitesCallable(const DescribeSitesRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeSitesOutcome()>>( [this, request]() { return this->DescribeSites(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DescribeSitesVerificationOutcome CwsClient::DescribeSitesVerification(const DescribeSitesVerificationRequest &request) { auto outcome = MakeRequest(request, "DescribeSitesVerification"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeSitesVerificationResponse rsp = DescribeSitesVerificationResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeSitesVerificationOutcome(rsp); else return DescribeSitesVerificationOutcome(o.GetError()); } else { return DescribeSitesVerificationOutcome(outcome.GetError()); } } void CwsClient::DescribeSitesVerificationAsync(const DescribeSitesVerificationRequest& request, const DescribeSitesVerificationAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeSitesVerification(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DescribeSitesVerificationOutcomeCallable CwsClient::DescribeSitesVerificationCallable(const DescribeSitesVerificationRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeSitesVerificationOutcome()>>( [this, request]() { return this->DescribeSitesVerification(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DescribeVulsOutcome CwsClient::DescribeVuls(const DescribeVulsRequest &request) { auto outcome = MakeRequest(request, "DescribeVuls"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeVulsResponse rsp = DescribeVulsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeVulsOutcome(rsp); else return DescribeVulsOutcome(o.GetError()); } else { return DescribeVulsOutcome(outcome.GetError()); } } void CwsClient::DescribeVulsAsync(const DescribeVulsRequest& request, const DescribeVulsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeVuls(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DescribeVulsOutcomeCallable CwsClient::DescribeVulsCallable(const DescribeVulsRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeVulsOutcome()>>( [this, request]() { return this->DescribeVuls(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DescribeVulsNumberOutcome CwsClient::DescribeVulsNumber(const DescribeVulsNumberRequest &request) { auto outcome = MakeRequest(request, "DescribeVulsNumber"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeVulsNumberResponse rsp = DescribeVulsNumberResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeVulsNumberOutcome(rsp); else return DescribeVulsNumberOutcome(o.GetError()); } else { return DescribeVulsNumberOutcome(outcome.GetError()); } } void CwsClient::DescribeVulsNumberAsync(const DescribeVulsNumberRequest& request, const DescribeVulsNumberAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeVulsNumber(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DescribeVulsNumberOutcomeCallable CwsClient::DescribeVulsNumberCallable(const DescribeVulsNumberRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeVulsNumberOutcome()>>( [this, request]() { return this->DescribeVulsNumber(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::DescribeVulsNumberTimelineOutcome CwsClient::DescribeVulsNumberTimeline(const DescribeVulsNumberTimelineRequest &request) { auto outcome = MakeRequest(request, "DescribeVulsNumberTimeline"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeVulsNumberTimelineResponse rsp = DescribeVulsNumberTimelineResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeVulsNumberTimelineOutcome(rsp); else return DescribeVulsNumberTimelineOutcome(o.GetError()); } else { return DescribeVulsNumberTimelineOutcome(outcome.GetError()); } } void CwsClient::DescribeVulsNumberTimelineAsync(const DescribeVulsNumberTimelineRequest& request, const DescribeVulsNumberTimelineAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeVulsNumberTimeline(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::DescribeVulsNumberTimelineOutcomeCallable CwsClient::DescribeVulsNumberTimelineCallable(const DescribeVulsNumberTimelineRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeVulsNumberTimelineOutcome()>>( [this, request]() { return this->DescribeVulsNumberTimeline(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::ModifyConfigAttributeOutcome CwsClient::ModifyConfigAttribute(const ModifyConfigAttributeRequest &request) { auto outcome = MakeRequest(request, "ModifyConfigAttribute"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); ModifyConfigAttributeResponse rsp = ModifyConfigAttributeResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return ModifyConfigAttributeOutcome(rsp); else return ModifyConfigAttributeOutcome(o.GetError()); } else { return ModifyConfigAttributeOutcome(outcome.GetError()); } } void CwsClient::ModifyConfigAttributeAsync(const ModifyConfigAttributeRequest& request, const ModifyConfigAttributeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->ModifyConfigAttribute(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::ModifyConfigAttributeOutcomeCallable CwsClient::ModifyConfigAttributeCallable(const ModifyConfigAttributeRequest &request) { auto task = std::make_shared<std::packaged_task<ModifyConfigAttributeOutcome()>>( [this, request]() { return this->ModifyConfigAttribute(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::ModifyMonitorAttributeOutcome CwsClient::ModifyMonitorAttribute(const ModifyMonitorAttributeRequest &request) { auto outcome = MakeRequest(request, "ModifyMonitorAttribute"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); ModifyMonitorAttributeResponse rsp = ModifyMonitorAttributeResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return ModifyMonitorAttributeOutcome(rsp); else return ModifyMonitorAttributeOutcome(o.GetError()); } else { return ModifyMonitorAttributeOutcome(outcome.GetError()); } } void CwsClient::ModifyMonitorAttributeAsync(const ModifyMonitorAttributeRequest& request, const ModifyMonitorAttributeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->ModifyMonitorAttribute(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::ModifyMonitorAttributeOutcomeCallable CwsClient::ModifyMonitorAttributeCallable(const ModifyMonitorAttributeRequest &request) { auto task = std::make_shared<std::packaged_task<ModifyMonitorAttributeOutcome()>>( [this, request]() { return this->ModifyMonitorAttribute(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::ModifySiteAttributeOutcome CwsClient::ModifySiteAttribute(const ModifySiteAttributeRequest &request) { auto outcome = MakeRequest(request, "ModifySiteAttribute"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); ModifySiteAttributeResponse rsp = ModifySiteAttributeResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return ModifySiteAttributeOutcome(rsp); else return ModifySiteAttributeOutcome(o.GetError()); } else { return ModifySiteAttributeOutcome(outcome.GetError()); } } void CwsClient::ModifySiteAttributeAsync(const ModifySiteAttributeRequest& request, const ModifySiteAttributeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->ModifySiteAttribute(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::ModifySiteAttributeOutcomeCallable CwsClient::ModifySiteAttributeCallable(const ModifySiteAttributeRequest &request) { auto task = std::make_shared<std::packaged_task<ModifySiteAttributeOutcome()>>( [this, request]() { return this->ModifySiteAttribute(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } CwsClient::VerifySitesOutcome CwsClient::VerifySites(const VerifySitesRequest &request) { auto outcome = MakeRequest(request, "VerifySites"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); VerifySitesResponse rsp = VerifySitesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return VerifySitesOutcome(rsp); else return VerifySitesOutcome(o.GetError()); } else { return VerifySitesOutcome(outcome.GetError()); } } void CwsClient::VerifySitesAsync(const VerifySitesRequest& request, const VerifySitesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->VerifySites(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } CwsClient::VerifySitesOutcomeCallable CwsClient::VerifySitesCallable(const VerifySitesRequest &request) { auto task = std::make_shared<std::packaged_task<VerifySitesOutcome()>>( [this, request]() { return this->VerifySites(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); }
33.719767
210
0.683851
li5ch
21e9d91ffbb9f9ccc18cf739ab91c534075e5f63
422
cpp
C++
CodeForces/SystemofEquations.cpp
mysterio0801/CP
68983c423a42f98d6e9bf5375bc3f936e980d631
[ "MIT" ]
null
null
null
CodeForces/SystemofEquations.cpp
mysterio0801/CP
68983c423a42f98d6e9bf5375bc3f936e980d631
[ "MIT" ]
null
null
null
CodeForces/SystemofEquations.cpp
mysterio0801/CP
68983c423a42f98d6e9bf5375bc3f936e980d631
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; int temp = n; int count = 0; map<int, int> mp; while (n != 0) { int a = sqrt(n); int b = temp - pow(a, 2); mp[a] = b; n--; } for (auto &pr : mp) { if (pr.first + pow(pr.second, 2) == m) { count++; } if (pr.second + pow(pr.first, 2) == m && (pr.second == 0 || pr.first == 0)) { count++; } } cout << count; }
16.88
79
0.481043
mysterio0801
21e9ecdbe50ce01fc0c3a82d9ea330a09897dad5
14,755
cpp
C++
Engine/source/T3D/components/physics/rigidBodyComponent.cpp
John3/t3d_benchmarking
27a5780ad704aa91b45ff1bb0d69ed07668d03be
[ "MIT" ]
10
2015-03-12T20:20:34.000Z
2021-02-03T08:07:31.000Z
Engine/source/T3D/components/physics/rigidBodyComponent.cpp
John3/t3d_benchmarking
27a5780ad704aa91b45ff1bb0d69ed07668d03be
[ "MIT" ]
3
2015-07-04T23:50:43.000Z
2016-08-01T09:19:52.000Z
Engine/source/T3D/components/physics/rigidBodyComponent.cpp
John3/t3d_benchmarking
27a5780ad704aa91b45ff1bb0d69ed07668d03be
[ "MIT" ]
6
2015-11-28T16:18:26.000Z
2020-03-29T17:14:56.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "T3D/components/physics/rigidBodyComponent.h" #include "core/util/safeDelete.h" #include "console/consoleTypes.h" #include "console/consoleObject.h" #include "core/stream/bitStream.h" #include "console/engineAPI.h" #include "sim/netConnection.h" #include "T3D/physics/physicsBody.h" #include "T3D/physics/physicsPlugin.h" #include "T3D/physics/physicsWorld.h" #include "T3D/physics/physicsCollision.h" #include "T3D/components/collision/collisionComponent.h" bool RigidBodyComponent::smNoCorrections = false; bool RigidBodyComponent::smNoSmoothing = false; ////////////////////////////////////////////////////////////////////////// // Constructor/Destructor ////////////////////////////////////////////////////////////////////////// RigidBodyComponent::RigidBodyComponent() : Component() { mMass = 20; mDynamicFriction = 1; mStaticFriction = 0.1f; mRestitution = 10; mLinearDamping = 0; mAngularDamping = 0; mLinearSleepThreshold = 1; mAngularSleepThreshold = 1; mWaterDampingScale = 0.1f; mBuoyancyDensity = 1; mSimType = SimType_ServerOnly; mPhysicsRep = NULL; mResetPos = MatrixF::Identity; mOwnerColComponent = NULL; mFriendlyName = "RigidBody(Component)"; } RigidBodyComponent::~RigidBodyComponent() { } IMPLEMENT_CO_NETOBJECT_V1(RigidBodyComponent); bool RigidBodyComponent::onAdd() { if(! Parent::onAdd()) return false; return true; } void RigidBodyComponent::onRemove() { Parent::onRemove(); } void RigidBodyComponent::initPersistFields() { Parent::initPersistFields(); } //This is mostly a catch for situations where the behavior is re-added to the object and the like and we may need to force an update to the behavior void RigidBodyComponent::onComponentAdd() { Parent::onComponentAdd(); if (isServerObject()) { storeRestorePos(); PhysicsPlugin::getPhysicsResetSignal().notify(this, &RigidBodyComponent::_onPhysicsReset); } CollisionComponent *colComp = mOwner->getComponent<CollisionComponent>(); if (colComp) { colComp->onCollisionChanged.notify(this, &RigidBodyComponent::updatePhysics); updatePhysics(colComp->getCollisionData()); } else updatePhysics(); } void RigidBodyComponent::onComponentRemove() { Parent::onComponentRemove(); if (isServerObject()) { PhysicsPlugin::getPhysicsResetSignal().remove(this, &RigidBodyComponent::_onPhysicsReset); } CollisionComponent *colComp = mOwner->getComponent<CollisionComponent>(); if (colComp) { colComp->onCollisionChanged.remove(this, &RigidBodyComponent::updatePhysics); } SAFE_DELETE(mPhysicsRep); } void RigidBodyComponent::componentAddedToOwner(Component *comp) { CollisionComponent *colComp = dynamic_cast<CollisionComponent*>(comp); if (colComp) { colComp->onCollisionChanged.notify(this, &RigidBodyComponent::updatePhysics); updatePhysics(colComp->getCollisionData()); } } void RigidBodyComponent::componentRemovedFromOwner(Component *comp) { //test if this is a shape component! CollisionComponent *colComp = dynamic_cast<CollisionComponent*>(comp); if (colComp) { colComp->onCollisionChanged.remove(this, &RigidBodyComponent::updatePhysics); updatePhysics(); } } void RigidBodyComponent::ownerTransformSet(MatrixF *mat) { if (mPhysicsRep) mPhysicsRep->setTransform(mOwner->getTransform()); } void RigidBodyComponent::updatePhysics(PhysicsCollision* collision) { SAFE_DELETE(mPhysicsRep); if (!PHYSICSMGR) return; mWorld = PHYSICSMGR->getWorld(isServerObject() ? "server" : "client"); if (!collision) return; mPhysicsRep = PHYSICSMGR->createBody(); mPhysicsRep->init(collision, mMass, 0, mOwner, mWorld); mPhysicsRep->setMaterial(mRestitution, mDynamicFriction, mStaticFriction); mPhysicsRep->setDamping(mLinearDamping, mAngularDamping); mPhysicsRep->setSleepThreshold(mLinearSleepThreshold, mAngularSleepThreshold); mPhysicsRep->setTransform(mOwner->getTransform()); // The reset position is the transform on the server // at creation time... its not used on the client. if (isServerObject()) { storeRestorePos(); PhysicsPlugin::getPhysicsResetSignal().notify(this, &RigidBodyComponent::_onPhysicsReset); } } U32 RigidBodyComponent::packUpdate(NetConnection *con, U32 mask, BitStream *stream) { U32 retMask = Parent::packUpdate(con, mask, stream); if (stream->writeFlag(mask & StateMask)) { // This will encode the position relative to the control // object position. // // This will compress the position to as little as 6.25 // bytes if the position is within about 30 meters of the // control object. // // Worst case its a full 12 bytes + 2 bits if the position // is more than 500 meters from the control object. // stream->writeCompressedPoint(mState.position); // Use only 3.5 bytes to send the orientation. stream->writeQuat(mState.orientation, 9); // If the server object has been set to sleep then // we don't need to send any velocity. if (!stream->writeFlag(mState.sleeping)) { // This gives me ~0.015f resolution in velocity magnitude // while only costing me 1 bit of the velocity is zero length, // <5 bytes in normal cases, and <8 bytes if the velocity is // greater than 1000. AssertWarn(mState.linVelocity.len() < 1000.0f, "PhysicsShape::packUpdate - The linVelocity is out of range!"); stream->writeVector(mState.linVelocity, 1000.0f, 16, 9); // For angular velocity we get < 0.01f resolution in magnitude // with the most common case being under 4 bytes. AssertWarn(mState.angVelocity.len() < 10.0f, "PhysicsShape::packUpdate - The angVelocity is out of range!"); stream->writeVector(mState.angVelocity, 10.0f, 10, 9); } } return retMask; } void RigidBodyComponent::unpackUpdate(NetConnection *con, BitStream *stream) { Parent::unpackUpdate(con, stream); if (stream->readFlag()) // StateMask { PhysicsState state; // Read the encoded and compressed position... commonly only 6.25 bytes. stream->readCompressedPoint(&state.position); // Read the compressed quaternion... 3.5 bytes. stream->readQuat(&state.orientation, 9); state.sleeping = stream->readFlag(); if (!state.sleeping) { stream->readVector(&state.linVelocity, 1000.0f, 16, 9); stream->readVector(&state.angVelocity, 10.0f, 10, 9); } if (!smNoCorrections && mPhysicsRep && mPhysicsRep->isDynamic()) { // Set the new state on the physics object immediately. mPhysicsRep->applyCorrection(state.getTransform()); mPhysicsRep->setSleeping(state.sleeping); if (!state.sleeping) { mPhysicsRep->setLinVelocity(state.linVelocity); mPhysicsRep->setAngVelocity(state.angVelocity); } mPhysicsRep->getState(&mState); } // If there is no physics object then just set the // new state... the tick will take care of the // interpolation and extrapolation. if (!mPhysicsRep || !mPhysicsRep->isDynamic()) mState = state; } } void RigidBodyComponent::processTick() { Parent::processTick(); if (!mPhysicsRep || !PHYSICSMGR) return; // Note that unlike TSStatic, the serverside PhysicsShape does not // need to play the ambient animation because even if the animation were // to move collision shapes it would not affect the physx representation. PROFILE_START(RigidBodyComponent_ProcessTick); if (!mPhysicsRep->isDynamic()) return; // SINGLE PLAYER HACK!!!! if (PHYSICSMGR->isSinglePlayer() && isClientObject() && getServerObject()) { RigidBodyComponent *servObj = (RigidBodyComponent*)getServerObject(); mOwner->setTransform(servObj->mState.getTransform()); mRenderState[0] = servObj->mRenderState[0]; mRenderState[1] = servObj->mRenderState[1]; return; } // Store the last render state. mRenderState[0] = mRenderState[1]; // If the last render state doesn't match the last simulation // state then we got a correction and need to Point3F errorDelta = mRenderState[1].position - mState.position; const bool doSmoothing = !errorDelta.isZero() && !smNoSmoothing; const bool wasSleeping = mState.sleeping; // Get the new physics state. mPhysicsRep->getState(&mState); updateContainerForces(); // Smooth the correction back into the render state. mRenderState[1] = mState; if (doSmoothing) { F32 correction = mClampF(errorDelta.len() / 20.0f, 0.1f, 0.9f); mRenderState[1].position.interpolate(mState.position, mRenderState[0].position, correction); mRenderState[1].orientation.interpolate(mState.orientation, mRenderState[0].orientation, correction); } //Check if any collisions occured findContact(); // If we haven't been sleeping then update our transform // and set ourselves as dirty for the next client update. if (!wasSleeping || !mState.sleeping) { // Set the transform on the parent so that // the physics object isn't moved. mOwner->setTransform(mState.getTransform()); // If we're doing server simulation then we need // to send the client a state update. if (isServerObject() && mPhysicsRep && !smNoCorrections && !PHYSICSMGR->isSinglePlayer() // SINGLE PLAYER HACK!!!! ) setMaskBits(StateMask); } PROFILE_END(); } void RigidBodyComponent::findContact() { SceneObject *contactObject = NULL; VectorF *contactNormal = new VectorF(0, 0, 0); Vector<SceneObject*> overlapObjects; mPhysicsRep->findContact(&contactObject, contactNormal, &overlapObjects); if (!overlapObjects.empty()) { //fire our signal that the physics sim said collisions happened onPhysicsCollision.trigger(*contactNormal, overlapObjects); } } void RigidBodyComponent::_onPhysicsReset(PhysicsResetEvent reset) { if (reset == PhysicsResetEvent_Store) mResetPos = mOwner->getTransform(); else if (reset == PhysicsResetEvent_Restore) { mOwner->setTransform(mResetPos); } } void RigidBodyComponent::storeRestorePos() { mResetPos = mOwner->getTransform(); } void RigidBodyComponent::applyImpulse(const Point3F &pos, const VectorF &vec) { if (mPhysicsRep && mPhysicsRep->isDynamic()) mPhysicsRep->applyImpulse(pos, vec); } void RigidBodyComponent::applyRadialImpulse(const Point3F &origin, F32 radius, F32 magnitude) { if (!mPhysicsRep || !mPhysicsRep->isDynamic()) return; // TODO: Find a better approximation of the // force vector using the object box. VectorF force = mOwner->getWorldBox().getCenter() - origin; F32 dist = force.magnitudeSafe(); force.normalize(); if (dist == 0.0f) force *= magnitude; else force *= mClampF(radius / dist, 0.0f, 1.0f) * magnitude; mPhysicsRep->applyImpulse(origin, force); // TODO: There is no simple way to really sync this sort of an // event with the client. // // The best is to send the current physics snapshot, calculate the // time difference from when this event occured and the time when the // client recieves it, and then extrapolate where it should be. // // Even then its impossible to be absolutely sure its synced. // // Bottom line... you shouldn't use physics over the network like this. // } void RigidBodyComponent::updateContainerForces() { PROFILE_SCOPE(RigidBodyComponent_updateContainerForces); // If we're not simulating don't update forces. PhysicsWorld *world = PHYSICSMGR->getWorld(isServerObject() ? "server" : "client"); if (!world || !world->isEnabled()) return; ContainerQueryInfo info; info.box = mOwner->getWorldBox(); info.mass = mMass; // Find and retreive physics info from intersecting WaterObject(s) mOwner->getContainer()->findObjects(mOwner->getWorldBox(), WaterObjectType | PhysicalZoneObjectType, findRouter, &info); // Calculate buoyancy and drag F32 angDrag = mAngularDamping; F32 linDrag = mLinearDamping; F32 buoyancy = 0.0f; Point3F cmass = mPhysicsRep->getCMassPosition(); F32 density = mBuoyancyDensity; if (density > 0.0f) { if (info.waterCoverage > 0.0f) { F32 waterDragScale = info.waterViscosity * mWaterDampingScale; F32 powCoverage = mPow(info.waterCoverage, 0.25f); angDrag = mLerp(angDrag, angDrag * waterDragScale, powCoverage); linDrag = mLerp(linDrag, linDrag * waterDragScale, powCoverage); } buoyancy = (info.waterDensity / density) * mPow(info.waterCoverage, 2.0f); // A little hackery to prevent oscillation // Based on this blog post: // (http://reinot.blogspot.com/2005/11/oh-yes-they-float-georgie-they-all.html) // JCF: disabled! Point3F buoyancyForce = buoyancy * -world->getGravity() * TickSec * mMass; mPhysicsRep->applyImpulse(cmass, buoyancyForce); } // Update the dampening as the container might have changed. mPhysicsRep->setDamping(linDrag, angDrag); // Apply physical zone forces. if (!info.appliedForce.isZero()) mPhysicsRep->applyImpulse(cmass, info.appliedForce); }
31.595289
148
0.681261
John3
21ed3f17619794aef95953a386f528f7ea2f97a7
1,335
cpp
C++
Sort/heap_sort_src/heap_sort.cpp
yichenluan/Algorithm101
a516fa5dad34ed431fa6fb2efab7bce4a90213bc
[ "MIT" ]
1
2018-10-30T10:02:11.000Z
2018-10-30T10:02:11.000Z
Sort/heap_sort_src/heap_sort.cpp
yichenluan/Algorithm101
a516fa5dad34ed431fa6fb2efab7bce4a90213bc
[ "MIT" ]
null
null
null
Sort/heap_sort_src/heap_sort.cpp
yichenluan/Algorithm101
a516fa5dad34ed431fa6fb2efab7bce4a90213bc
[ "MIT" ]
null
null
null
#include <vector> #include <iostream> using namespace std; template<class It> void printByIt(It begin, It end); template<class It> void printByIt(It begin, It end) { for (It curr = begin; curr != end; ++curr) { cout << *curr << " "; } cout << endl; } void sink(vector<int>& a, int k, int N) { int child = 2 * (k+1) - 1; while (child <= N) { if (child < N && a[child] < a[child+1]) { child++; } if (a[k] >= a[child]) { break; } swap(a[k], a[child]); k = child; child = 2 *(k+1) - 1; } } void heap_sort(vector<int>& a) { int N = a.size() - 1; for (int k = N/2; k >= 0; --k) { sink(a, k, N); } while (N > 0) { swap(a[0], a[N--]); sink(a, 0, N); } } int main() { //vector<int> unorder = {5, 4, 3, 4, 1, 4, 2}; //vector<int> unorder = { 2, 4, 3, 1}; //vector<int> unorder = {5, 4, 9, 4, 7, 4, 2}; //vector<int> unorder = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; //vector<int> unorder = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; //vector<int> unorder = { 3, 2, 1}; vector<int> unorder; cout << "before order: "; printByIt(unorder.begin(), unorder.end()); heap_sort(unorder); cout << "after order: "; printByIt(unorder.begin(), unorder.end()); }
22.25
60
0.468914
yichenluan
21ee74d06c68e18c398f9bb4c9583345361f9456
60
hpp
C++
src/boost_spirit_home_support_nonterminal_locals.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_spirit_home_support_nonterminal_locals.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_spirit_home_support_nonterminal_locals.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/spirit/home/support/nonterminal/locals.hpp>
30
59
0.816667
miathedev
21f009619fb86e73eede2854736e9fb710b9ac1d
15,993
cpp
C++
src/bridge/jni/NativeOsIo.cpp
codegitpro/qt-app
d8cdc29156c324d174362ac971d11b7989483395
[ "Libpng", "Zlib" ]
null
null
null
src/bridge/jni/NativeOsIo.cpp
codegitpro/qt-app
d8cdc29156c324d174362ac971d11b7989483395
[ "Libpng", "Zlib" ]
null
null
null
src/bridge/jni/NativeOsIo.cpp
codegitpro/qt-app
d8cdc29156c324d174362ac971d11b7989483395
[ "Libpng", "Zlib" ]
null
null
null
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from portal.djinni #include "NativeOsIo.hpp" // my header #include "Marshal.hpp" #include "NativeBinaryResult.hpp" #include "NativeBoolResult.hpp" #include "NativeCancellationToken.hpp" #include "NativeFileType.hpp" #include "NativeHeader.hpp" #include "NativeHttpProgressResult.hpp" #include "NativeHttpResult.hpp" #include "NativeHttpVerb.hpp" #include "NativeLogType.hpp" #include "NativeLongResult.hpp" #include "NativeStringResult.hpp" #include "NativeStringsResult.hpp" #include "NativeVoidResult.hpp" namespace djinni_generated { NativeOsIo::NativeOsIo() : ::djinni::JniInterface<::ai::OsIo, NativeOsIo>() {} NativeOsIo::~NativeOsIo() = default; NativeOsIo::JavaProxy::JavaProxy(JniType j) : Handle(::djinni::jniGetThreadEnv(), j) { } NativeOsIo::JavaProxy::~JavaProxy() = default; void NativeOsIo::JavaProxy::log(::ai::LogType c_type, int32_t c_line, const std::string & c_file, const std::string & c_message) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_log, ::djinni::get(::djinni_generated::NativeLogType::fromCpp(jniEnv, c_type)), ::djinni::get(::djinni::I32::fromCpp(jniEnv, c_line)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_file)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_message))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::log_lines(::ai::LogType c_type, int32_t c_line, const std::string & c_file, const std::vector<std::string> & c_messages) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_logLines, ::djinni::get(::djinni_generated::NativeLogType::fromCpp(jniEnv, c_type)), ::djinni::get(::djinni::I32::fromCpp(jniEnv, c_line)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_file)), ::djinni::get(::djinni::List<::djinni::String>::fromCpp(jniEnv, c_messages))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::file_readall(const std::string & c_path, const std::shared_ptr<::ai::BinaryResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_fileReadall, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_path)), ::djinni::get(::djinni_generated::NativeBinaryResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::file_writeall(const std::string & c_path, const std::vector<uint8_t> & c_content, const std::shared_ptr<::ai::BoolResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_fileWriteall, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_path)), ::djinni::get(::djinni::Binary::fromCpp(jniEnv, c_content)), ::djinni::get(::djinni_generated::NativeBoolResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::file_writeall_safely(const std::string & c_path, const std::vector<uint8_t> & c_content, const std::shared_ptr<::ai::BoolResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_fileWriteallSafely, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_path)), ::djinni::get(::djinni::Binary::fromCpp(jniEnv, c_content)), ::djinni::get(::djinni_generated::NativeBoolResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::file_write_password(const std::string & c_username, const std::string & c_password, const std::shared_ptr<::ai::BoolResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_fileWritePassword, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_username)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_password)), ::djinni::get(::djinni_generated::NativeBoolResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::file_read_password(const std::string & c_username, const std::shared_ptr<::ai::StringResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_fileReadPassword, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_username)), ::djinni::get(::djinni_generated::NativeStringResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::file_size(const std::string & c_path, const std::shared_ptr<::ai::LongResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_fileSize, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_path)), ::djinni::get(::djinni_generated::NativeLongResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } bool NativeOsIo::JavaProxy::file_thumbnail(const std::string & c_path, ::ai::FileType c_type, const std::shared_ptr<::ai::BinaryResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); auto jret = jniEnv->CallBooleanMethod(Handle::get().get(), data.method_fileThumbnail, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_path)), ::djinni::get(::djinni_generated::NativeFileType::fromCpp(jniEnv, c_type)), ::djinni::get(::djinni_generated::NativeBinaryResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni::Bool::toCpp(jniEnv, jret); } void NativeOsIo::JavaProxy::copy_file(const std::string & c_current_path, const std::string & c_new_path, const std::shared_ptr<::ai::BoolResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_copyFile, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_current_path)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_new_path)), ::djinni::get(::djinni_generated::NativeBoolResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::make_path(const std::string & c_path, const std::shared_ptr<::ai::BoolResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_makePath, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_path)), ::djinni::get(::djinni_generated::NativeBoolResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::rename_file(const std::string & c_current_path, const std::string & c_new_path, const std::shared_ptr<::ai::BoolResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_renameFile, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_current_path)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_new_path)), ::djinni::get(::djinni_generated::NativeBoolResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } std::shared_ptr<::ai::CancellationToken> NativeOsIo::JavaProxy::http_request(::ai::HttpVerb c_verb, const std::string & c_url, const std::vector<::ai::Header> & c_headers, const std::string & c_body, const std::shared_ptr<::ai::HttpResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); auto jret = jniEnv->CallObjectMethod(Handle::get().get(), data.method_httpRequest, ::djinni::get(::djinni_generated::NativeHttpVerb::fromCpp(jniEnv, c_verb)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_url)), ::djinni::get(::djinni::List<::djinni_generated::NativeHeader>::fromCpp(jniEnv, c_headers)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_body)), ::djinni::get(::djinni_generated::NativeHttpResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni_generated::NativeCancellationToken::toCpp(jniEnv, jret); } std::shared_ptr<::ai::CancellationToken> NativeOsIo::JavaProxy::http_upload_file(::ai::HttpVerb c_verb, const std::string & c_url, const std::string & c_file_path, const std::vector<::ai::Header> & c_headers, const std::shared_ptr<::ai::HttpProgressResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); auto jret = jniEnv->CallObjectMethod(Handle::get().get(), data.method_httpUploadFile, ::djinni::get(::djinni_generated::NativeHttpVerb::fromCpp(jniEnv, c_verb)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_url)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_file_path)), ::djinni::get(::djinni::List<::djinni_generated::NativeHeader>::fromCpp(jniEnv, c_headers)), ::djinni::get(::djinni_generated::NativeHttpProgressResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni_generated::NativeCancellationToken::toCpp(jniEnv, jret); } std::shared_ptr<::ai::CancellationToken> NativeOsIo::JavaProxy::http_download_file(const std::string & c_url, const std::string & c_file_path, const std::vector<::ai::Header> & c_headers, int64_t c_size, const std::string & c_md5, const std::shared_ptr<::ai::HttpProgressResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); auto jret = jniEnv->CallObjectMethod(Handle::get().get(), data.method_httpDownloadFile, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_url)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_file_path)), ::djinni::get(::djinni::List<::djinni_generated::NativeHeader>::fromCpp(jniEnv, c_headers)), ::djinni::get(::djinni::I64::fromCpp(jniEnv, c_size)), ::djinni::get(::djinni::String::fromCpp(jniEnv, c_md5)), ::djinni::get(::djinni_generated::NativeHttpProgressResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); return ::djinni_generated::NativeCancellationToken::toCpp(jniEnv, jret); } void NativeOsIo::JavaProxy::wait(int32_t c_millis, const std::shared_ptr<::ai::VoidResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_wait, ::djinni::get(::djinni::I32::fromCpp(jniEnv, c_millis)), ::djinni::get(::djinni_generated::NativeVoidResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::file_expand_directories(const std::vector<std::string> & c_paths, const std::shared_ptr<::ai::StringsResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_fileExpandDirectories, ::djinni::get(::djinni::List<::djinni::String>::fromCpp(jniEnv, c_paths)), ::djinni::get(::djinni_generated::NativeStringsResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::file_copy_hierarchy(const std::string & c_dest_root_path, const std::vector<std::string> & c_dest_relative_paths, const std::vector<std::string> & c_src_paths) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_fileCopyHierarchy, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_dest_root_path)), ::djinni::get(::djinni::List<::djinni::String>::fromCpp(jniEnv, c_dest_relative_paths)), ::djinni::get(::djinni::List<::djinni::String>::fromCpp(jniEnv, c_src_paths))); ::djinni::jniExceptionCheck(jniEnv); } void NativeOsIo::JavaProxy::file_clear_cache(const std::string & c_username, const std::shared_ptr<::ai::BoolResult> & c_result) { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeOsIo>::get(); jniEnv->CallVoidMethod(Handle::get().get(), data.method_fileClearCache, ::djinni::get(::djinni::String::fromCpp(jniEnv, c_username)), ::djinni::get(::djinni_generated::NativeBoolResult::fromCpp(jniEnv, c_result))); ::djinni::jniExceptionCheck(jniEnv); } } // namespace djinni_generated
70.144737
292
0.640718
codegitpro
21f1d8be0a830d3e3a426259d4832472feff02c5
2,354
cc
C++
lite/kernels/host/sequence_unpad_compute.cc
714627034/Paddle-Lite
015ba88a4d639db0b73603e37f83e47be041a4eb
[ "Apache-2.0" ]
1,799
2019-08-19T03:29:38.000Z
2022-03-31T14:30:50.000Z
lite/kernels/host/sequence_unpad_compute.cc
714627034/Paddle-Lite
015ba88a4d639db0b73603e37f83e47be041a4eb
[ "Apache-2.0" ]
3,767
2019-08-19T03:36:04.000Z
2022-03-31T14:37:26.000Z
lite/kernels/host/sequence_unpad_compute.cc
yingshengBD/Paddle-Lite
eea59b66f61bb2acad471010c9526eeec43a15ca
[ "Apache-2.0" ]
798
2019-08-19T02:28:23.000Z
2022-03-31T08:31:54.000Z
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/kernels/host/sequence_unpad_compute.h" namespace paddle { namespace lite { namespace kernels {} // namespace kernels } // namespace lite } // namespace paddle using SequenceUnpadFloat32 = paddle::lite::kernels::host::SequenceUnpadCompute<float>; REGISTER_LITE_KERNEL( sequence_unpad, kHost, kFloat, kAny, SequenceUnpadFloat32, float32) .BindInput("X", {LiteType::GetTensorTy(TARGET(kHost), PRECISION(kFloat), DATALAYOUT(kAny))}) .BindInput("Length", {LiteType::GetTensorTy(TARGET(kHost), PRECISION(kInt64), DATALAYOUT(kAny))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kHost), PRECISION(kFloat), DATALAYOUT(kAny))}) .Finalize(); using SequenceUnpadInt64 = paddle::lite::kernels::host::SequenceUnpadCompute<int64_t>; REGISTER_LITE_KERNEL( sequence_unpad, kHost, kFloat, kAny, SequenceUnpadInt64, int64) .BindInput("X", {LiteType::GetTensorTy(TARGET(kHost), PRECISION(kInt64), DATALAYOUT(kAny))}) .BindInput("Length", {LiteType::GetTensorTy(TARGET(kHost), PRECISION(kInt64), DATALAYOUT(kAny))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kHost), PRECISION(kInt64), DATALAYOUT(kAny))}) .Finalize();
40.586207
75
0.56712
714627034
21f5c9bd775815a5e340b8446a0d8ec77a9db745
3,236
hxx
C++
opencascade/VrmlData_Box.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/VrmlData_Box.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/VrmlData_Box.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 2006-05-25 // Created by: Alexander GRIGORIEV // Copyright (c) 2006-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef VrmlData_Box_HeaderFile #define VrmlData_Box_HeaderFile #include <VrmlData_Geometry.hxx> #include <gp_XYZ.hxx> /** * Inplementation of the Box node. * This node is defined by Size vector, assumong that the box center is located * in (0., 0., 0.) and that each corner is 0.5*|Size| distance from the center. */ class VrmlData_Box : public VrmlData_Geometry { public: // ---------- PUBLIC METHODS ---------- /** * Empty constructor */ inline VrmlData_Box () : mySize (2., 2., 2.) {} /** * Constructor */ inline VrmlData_Box (const VrmlData_Scene& theScene, const char * theName, const Standard_Real sizeX = 2., const Standard_Real sizeY = 2., const Standard_Real sizeZ = 2.) : VrmlData_Geometry (theScene, theName), mySize (sizeX, sizeY, sizeZ) {} /** * Query the Box size */ inline const gp_XYZ& Size () const { return mySize; } /** * Set the Box Size */ inline void SetSize (const gp_XYZ& theSize) { mySize = theSize; SetModified(); } /** * Query the primitive topology. This method returns a Null shape if there * is an internal error during the primitive creation (zero radius, etc.) */ Standard_EXPORT virtual const Handle(TopoDS_TShape)& TShape () Standard_OVERRIDE; /** * Create a copy of this node. * If the parameter is null, a new copied node is created. Otherwise new node * is not created, but rather the given one is modified. */ Standard_EXPORT virtual Handle(VrmlData_Node) Clone (const Handle(VrmlData_Node)& theOther)const Standard_OVERRIDE; /** * Fill the Node internal data from the given input stream. */ Standard_EXPORT virtual VrmlData_ErrorStatus Read (VrmlData_InBuffer& theBuffer) Standard_OVERRIDE; /** * Write the Node to output stream. */ Standard_EXPORT virtual VrmlData_ErrorStatus Write (const char * thePrefix) const Standard_OVERRIDE; private: // ---------- PRIVATE FIELDS ---------- gp_XYZ mySize; public: // Declaration of CASCADE RTTI DEFINE_STANDARD_RTTI_INLINE(VrmlData_Box,VrmlData_Geometry) }; // Definition of HANDLE object using Standard_DefineHandle.hxx DEFINE_STANDARD_HANDLE (VrmlData_Box, VrmlData_Geometry) #endif
31.115385
95
0.64555
valgur
21f88e293e61d25342f8ab1972bd6644b2b65b9d
904
cpp
C++
atcoder/abc156f.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
1
2020-04-04T14:56:12.000Z
2020-04-04T14:56:12.000Z
atcoder/abc156f.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
atcoder/abc156f.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll=long long; void solve() { int k,q; cin >> k >> q; vector<ll> d(k); for (auto& x: d) { cin >> x; } while (q--) { ll n,x,m; cin >> n >> x >> m; n--; x %= m; ll sum = 0; for (auto& x: d) { sum += x%m; } // a_n ll z = x + (n/k) * sum; { ll r = n%k; for (int i = 0; i < r; i++) { z += d[i]%m; } } // #>, cross ll res = z / m; // #=, for (int i = 0; i < k; i++) { if (d[i]%m == 0 && i < n) { res += 1 + (n-i-1) / k; } } res = n - res; cout << res << '\n'; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); return 0; }
18.08
41
0.301991
sogapalag
21fb53a330953c1ce3974576a63b90ad5df83880
4,214
hpp
C++
include/ndtree/algorithm/node_neighbors.hpp
gnzlbg/htree
30e29145b6b0b0f4d1106f05376df94bd58cadc9
[ "BSL-1.0" ]
15
2015-09-02T13:25:55.000Z
2021-04-23T04:02:19.000Z
include/ndtree/algorithm/node_neighbors.hpp
gnzlbg/htree
30e29145b6b0b0f4d1106f05376df94bd58cadc9
[ "BSL-1.0" ]
1
2015-11-18T03:50:18.000Z
2016-06-16T08:34:01.000Z
include/ndtree/algorithm/node_neighbors.hpp
gnzlbg/htree
30e29145b6b0b0f4d1106f05376df94bd58cadc9
[ "BSL-1.0" ]
4
2016-05-20T18:57:27.000Z
2019-03-17T09:18:13.000Z
#pragma once /// \file node_neighbors.hpp #include <ndtree/algorithm/node_location.hpp> #include <ndtree/algorithm/node_or_parent_at.hpp> #include <ndtree/algorithm/shift_location.hpp> #include <ndtree/concepts.hpp> #include <ndtree/location/default.hpp> #include <ndtree/relations/neighbor.hpp> #include <ndtree/types.hpp> #include <ndtree/utility/static_const.hpp> #include <ndtree/utility/stack_vector.hpp> namespace ndtree { inline namespace v1 { // struct node_neighbors_fn { /// Finds neighbors of node at location \p loc across the Manifold /// (appends them to a push_back-able container) template <typename Manifold, typename Tree, typename Loc, typename PushBackableContainer, CONCEPT_REQUIRES_(Location<Loc>{})> auto operator()(Manifold positions, Tree const& t, Loc&& loc, PushBackableContainer& s) const noexcept -> void { static_assert(Tree::dimension() == ranges::uncvref_t<Loc>::dimension(), ""); // For all same level neighbor positions for (auto&& sl_pos : positions()) { auto neighbor = node_or_parent_at(t, shift_location(loc, positions[sl_pos])); if (!neighbor.idx) { continue; } NDTREE_ASSERT((neighbor.level == loc.level()) || (neighbor.level == (loc.level() - 1)), "found neighbor must either be at the same level or at the " "parent level"); // if the neighbor found is a leaf node we are done // note: it is either at the same or parent level of the node // (doesn't matter which case it is, it is the correct neighbor) if (t.is_leaf(neighbor.idx)) { s.push_back(neighbor.idx); } else { // if it has children we add the children sharing a face with the node for (auto&& cp : Manifold{}.children_sharing_face(sl_pos)) { s.push_back(t.child(neighbor.idx, cp)); } } } } /// Finds neighbors of node at location \p loc across the Manifold /// /// \returns stack allocated vector containing the neighbors template <typename Manifold, typename Tree, typename Loc, int max_no_neighbors = Manifold::no_child_level_neighbors(), CONCEPT_REQUIRES_(Location<Loc>{})> auto operator()(Manifold, Tree const& t, Loc&& loc) const noexcept -> stack_vector<node_idx, max_no_neighbors> { static_assert(Tree::dimension() == ranges::uncvref_t<Loc>::dimension(), ""); stack_vector<node_idx, max_no_neighbors> neighbors; (*this)(Manifold{}, t, loc, neighbors); return neighbors; } /// Finds set of unique neighbors of node at location \p loc across all /// manifolds /// /// \param t [in] tree. /// \param loc [in] location (location of the node). /// \returns stack allocated vector containing the unique set of neighbors /// template <typename Tree, typename Loc, int nd = Tree::dimension(), CONCEPT_REQUIRES_(Location<Loc>{})> auto operator()(Tree const& t, Loc&& loc) const noexcept -> stack_vector<node_idx, max_no_neighbors(nd)> { stack_vector<node_idx, max_no_neighbors(nd)> neighbors; // For each surface manifold append the neighbors using manifold_rng = meta::as_list<meta::integer_range<int, 1, nd + 1>>; meta::for_each(manifold_rng{}, [&](auto m_) { using manifold = manifold_neighbors<nd, decltype(m_){}>; (*this)(manifold{}, t, loc, neighbors); }); // sort them and remove dupplicates ranges::sort(neighbors); neighbors.erase(ranges::unique(neighbors), end(neighbors)); return neighbors; } /// Finds set of unique neighbors of node \p n across all manifolds /// /// \param t [in] tree. /// \param n [in] node index. /// \returns stack allocated vector containing the unique set of neighbors /// template <typename Tree, typename Loc = location::default_location<Tree::dimension()>, CONCEPT_REQUIRES_(Location<Loc>{})> auto operator()(Tree const& t, node_idx n, Loc l = Loc{}) const noexcept { return (*this)(t, node_location(t, n, l)); } }; namespace { constexpr auto&& node_neighbors = static_const<node_neighbors_fn>::value; } // namespace } // namespace v1 } // namespace ndtree
38.66055
80
0.665638
gnzlbg
21fd4bc267f14b60f09e459e847e00fd01369c86
995
cpp
C++
Arrays/moveposneg.cpp
thisisnitish/cp-dsa-
9ae94930b65f8dc293d088e9148960939b9f6fa4
[ "MIT" ]
4
2020-12-29T09:27:10.000Z
2022-02-12T14:20:23.000Z
Arrays/moveposneg.cpp
thisisnitish/cp-dsa-
9ae94930b65f8dc293d088e9148960939b9f6fa4
[ "MIT" ]
1
2021-11-27T06:15:28.000Z
2021-11-27T06:15:28.000Z
Arrays/moveposneg.cpp
thisisnitish/cp-dsa-
9ae94930b65f8dc293d088e9148960939b9f6fa4
[ "MIT" ]
1
2021-11-17T21:42:57.000Z
2021-11-17T21:42:57.000Z
/* Move all negative numbers to beginning and positive to end with constant extra space Input: -12, 11, -13, -5, 6, -7, 5, -3, -6 Output: -12 -13 -5 -7 -3 -6 11 6 5 https://www.geeksforgeeks.org/move-negative-numbers-beginning-positive-end-constant-extra-space/ */ #include<iostream> using namespace std; int main() { int n; cin>>n; int arr[n]; for(int i=0; i<n; i++){ cin>>arr[i]; } //two pointer approach int left = 0, right = n-1; while(left <= right){ if(arr[left] < 0 && arr[right] < 0) left++; else if(arr[left] > 0 && arr[right] < 0){ swap(arr[left], arr[right]); left++; right--; } else if(arr[left] > 0 && arr[right] > 0){ right--; } else if(arr[left] < 0 && arr[right] > 0){ left++; right--; } } //display the array for(int i=0; i<n; i++) cout<<arr[i]<<" "; cout<<endl; return 0; }
21.170213
96
0.491457
thisisnitish
21fece503f73452353bb3fdc2d5faf6d4d5d2db7
29,388
cpp
C++
com/netfx/src/clr/dlls/mscorsec/acuihelp.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/netfx/src/clr/dlls/mscorsec/acuihelp.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/netfx/src/clr/dlls/mscorsec/acuihelp.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //***************************************************************************** //***************************************************************************** #include "stdpch.h" #include "richedit.h" #include "commctrl.h" #include "resource.h" #include "corpolicy.h" #include "corperm.h" #include "corhlpr.h" #include "winwrap.h" #include "acuihelp.h" #include "acui.h" //+--------------------------------------------------------------------------- // // Function: ACUISetArrowCursorSubclass // // Synopsis: subclass routine for setting the arrow cursor. This can be // set on multiline edit routines used in the dialog UIs for // the default Authenticode provider // // Arguments: [hwnd] -- window handle // [uMsg] -- message id // [wParam] -- parameter 1 // [lParam] -- parameter 2 // // Returns: TRUE if message handled, FALSE otherwise // // Notes: // //---------------------------------------------------------------------------- LRESULT CALLBACK ACUISetArrowCursorSubclass ( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { //HDC hdc; WNDPROC wndproc; //PAINTSTRUCT ps; wndproc = (WNDPROC)WszGetWindowLong(hwnd, GWLP_USERDATA); switch ( uMsg ) { case WM_SETCURSOR: SetCursor(WszLoadCursor(NULL, IDC_ARROW)); return( TRUE ); break; case WM_CHAR: if ( wParam != (WPARAM)' ' ) { break; } case WM_LBUTTONDOWN: return(TRUE); case WM_LBUTTONDBLCLK: case WM_MBUTTONDBLCLK: case WM_RBUTTONDBLCLK: case WM_RBUTTONUP: case WM_MBUTTONUP: case WM_RBUTTONDOWN: case WM_MBUTTONDOWN: return( TRUE ); break; case EM_SETSEL: return( TRUE ); break; case WM_PAINT: WszCallWindowProc(wndproc, hwnd, uMsg, wParam, lParam); if ( hwnd == GetFocus() ) { DrawFocusRectangle(hwnd, NULL); } return( TRUE ); break; case WM_SETFOCUS: InvalidateRect(hwnd, NULL, FALSE); UpdateWindow(hwnd); SetCursor(WszLoadCursor(NULL, IDC_ARROW)); return( TRUE ); case WM_KILLFOCUS: InvalidateRect(hwnd, NULL, TRUE); UpdateWindow(hwnd); return( TRUE ); } return(WszCallWindowProc(wndproc, hwnd, uMsg, wParam, lParam)); } //+--------------------------------------------------------------------------- // // Function: RebaseControlVertical // // Synopsis: Take the window control, if it has to be resized for text, do // so. Reposition it adjusted for delta pos and return any // height difference for the text resizing // // Arguments: [hwndDlg] -- host dialog // [hwnd] -- control // [hwndNext] -- next control // [fResizeForText] -- resize for text flag // [deltavpos] -- delta vertical position // [oline] -- original number of lines // [minsep] -- minimum separator // [pdeltaheight] -- delta in control height // // Returns: (none) // // Notes: // //---------------------------------------------------------------------------- VOID RebaseControlVertical ( HWND hwndDlg, HWND hwnd, HWND hwndNext, BOOL fResizeForText, int deltavpos, int oline, int minsep, int* pdeltaheight ) { int x = 0; int y = 0; int odn = 0; int orig_w; RECT rect; RECT rectNext; RECT rectDlg; TEXTMETRIC tm={0}; // // Set the delta height to zero for now. If we resize the text // a new one will be calculated // *pdeltaheight = 0; // // Get the control window rectangle // GetWindowRect(hwnd, &rect); GetWindowRect(hwndNext, &rectNext); odn = rectNext.top - rect.bottom; orig_w = rect.right - rect.left; MapWindowPoints(NULL, hwndDlg, (LPPOINT) &rect, 2); // // If we have to resize the control due to text, find out what font // is being used and the number of lines of text. From that we'll // calculate what the new height for the control is and set it up // if ( fResizeForText == TRUE ) { HDC hdc; HFONT hfont; HFONT hfontOld; int cline; int h; int w; int dh; int lineHeight; // // Get the metrics of the current control font // hdc = GetDC(hwnd); if (hdc == NULL) { hdc = GetDC(NULL); if (hdc == NULL) { return; } } hfont = (HFONT)WszSendMessage(hwnd, WM_GETFONT, 0, 0); if ( hfont == NULL ) { hfont = (HFONT)WszSendMessage(hwndDlg, WM_GETFONT, 0, 0); } hfontOld = (HFONT)SelectObject(hdc, hfont); if(!GetTextMetrics(hdc, &tm)) { tm.tmHeight=32; //hopefully GetRichEditControlLineHeight will replace it. // If not - we have to take a guess because we can't fail RebaseControlVertical tm.tmMaxCharWidth=16; // doesn't matter that much but should be bigger than 0 }; lineHeight = GetRichEditControlLineHeight(hwnd); if (lineHeight == 0) { lineHeight = tm.tmHeight; } // // Set the minimum separation value // if ( minsep == 0 ) { minsep = lineHeight; } // // Calculate the width and the new height needed // cline = (int)WszSendMessage(hwnd, EM_GETLINECOUNT, 0, 0); h = cline * lineHeight; w = GetEditControlMaxLineWidth(hwnd, hdc, cline); w += 3; // a little bump to make sure string will fit if (w > orig_w) { w = orig_w; } SelectObject(hdc, hfontOld); ReleaseDC(hwnd, hdc); // // Calculate an addition to height by checking how much space was // left when there were the original # of lines and making sure that // that amount is still left when we do any adjustments // h += ( ( rect.bottom - rect.top ) - ( oline * lineHeight ) ); dh = h - ( rect.bottom - rect.top ); // // If the current height is too small, adjust for it, otherwise // leave the current height and just adjust for the width // if ( dh > 0 ) { SetWindowPos(hwnd, NULL, 0, 0, w, h, SWP_NOZORDER | SWP_NOMOVE); } else { SetWindowPos( hwnd, NULL, 0, 0, w, ( rect.bottom - rect.top ), SWP_NOZORDER | SWP_NOMOVE ); } if ( cline < WszSendMessage(hwnd, EM_GETLINECOUNT, 0, 0) ) { AdjustEditControlWidthToLineCount(hwnd, cline, &tm); } } // // If we have to use deltavpos then calculate the X and the new Y // and set the window position appropriately // if ( deltavpos != 0 ) { GetWindowRect(hwndDlg, &rectDlg); MapWindowPoints(NULL, hwndDlg, (LPPOINT) &rectDlg, 2); x = rect.left - rectDlg.left - GetSystemMetrics(SM_CXEDGE); y = rect.top - rectDlg.top - GetSystemMetrics(SM_CYCAPTION) + deltavpos; SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOZORDER | SWP_NOSIZE); } // // Get the window rect for the next control and see what the distance // is between the current control and it. With that we must now // adjust our deltaheight, if the distance to the next control is less // than a line height then make it a line height, otherwise just let it // be // if ( hwndNext != NULL ) { int dn; GetWindowRect(hwnd, &rect); GetWindowRect(hwndNext, &rectNext); dn = rectNext.top - rect.bottom; if ( odn > minsep ) { if ( dn < minsep ) { *pdeltaheight = minsep - dn; } } else { if ( dn < odn ) { *pdeltaheight = odn - dn; } } } } int GetRichEditControlLineHeight(HWND hwnd) { RECT rect; POINT pointInFirstRow; POINT pointInSecondRow; int secondLineCharIndex; int i; RECT originalRect; GetWindowRect(hwnd, &originalRect); // // HACK ALERT, believe it or not there is no way to get the height of the current // font in the edit control, so get the position a character in the first row and the position // of a character in the second row, and do the subtraction to get the // height of the font // WszSendMessage(hwnd, EM_POSFROMCHAR, (WPARAM) &pointInFirstRow, (LPARAM) 0); // // HACK ON TOP OF HACK ALERT, // since there may not be a second row in the edit box, keep reducing the width // by half until the first row falls over into the second row, then get the position // of the first char in the second row and finally reset the edit box size back to // it's original size // secondLineCharIndex = (int)WszSendMessage(hwnd, EM_LINEINDEX, (WPARAM) 1, (LPARAM) 0); if (secondLineCharIndex == -1) { for (i=0; i<20; i++) { GetWindowRect(hwnd, &rect); SetWindowPos( hwnd, NULL, 0, 0, (rect.right-rect.left)/2, rect.bottom-rect.top, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER); secondLineCharIndex = (int)WszSendMessage(hwnd, EM_LINEINDEX, (WPARAM) 1, (LPARAM) 0); if (secondLineCharIndex != -1) { break; } } if (secondLineCharIndex == -1) { // if we failed after twenty tries just reset the control to its original size // and get the heck outa here!! SetWindowPos(hwnd, NULL, 0, 0, originalRect.right-originalRect.left, originalRect.bottom-originalRect.top, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER); return 0; } WszSendMessage(hwnd, EM_POSFROMCHAR, (WPARAM) &pointInSecondRow, (LPARAM) secondLineCharIndex); SetWindowPos(hwnd, NULL, 0, 0, originalRect.right-originalRect.left, originalRect.bottom-originalRect.top, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } else { WszSendMessage(hwnd, EM_POSFROMCHAR, (WPARAM) &pointInSecondRow, (LPARAM) secondLineCharIndex); } return (pointInSecondRow.y - pointInFirstRow.y); } //+--------------------------------------------------------------------------- // // Function: FormatACUIResourceString // // Synopsis: formats a string given a resource id and message arguments // // Arguments: [StringResourceId] -- resource id // [aMessageArgument] -- message arguments // [ppszFormatted] -- formatted string goes here // // Returns: S_OK if successful, any valid HRESULT otherwise // //---------------------------------------------------------------------------- HRESULT FormatACUIResourceString (HINSTANCE hResources, UINT StringResourceId, DWORD_PTR* aMessageArgument, LPWSTR* ppszFormatted) { HRESULT hr = S_OK; WCHAR sz[MAX_LOADSTRING_BUFFER]; LPVOID pvMsg; pvMsg = NULL; sz[0] = NULL; // // Load the string resource and format the message with that string and // the message arguments // if (StringResourceId != 0) { if ( WszLoadString(hResources, StringResourceId, sz, MAX_LOADSTRING_BUFFER) == 0 ) { return(HRESULT_FROM_WIN32(GetLastError())); } if ( WszFormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ARGUMENT_ARRAY, sz, 0, 0, (LPWSTR)&pvMsg, 0, (va_list *)aMessageArgument) == 0) { hr = HRESULT_FROM_WIN32(GetLastError()); } } else { if ( WszFormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ARGUMENT_ARRAY, (char *)aMessageArgument[0], 0, 0, (LPWSTR)&pvMsg, 0, (va_list *)&aMessageArgument[1]) == 0) { hr = HRESULT_FROM_WIN32(GetLastError()); } } if (pvMsg) { *ppszFormatted = new WCHAR[wcslen((WCHAR *)pvMsg) + 1]; if (*ppszFormatted) { wcscpy(*ppszFormatted, (WCHAR *)pvMsg); } LocalFree(pvMsg); } return( hr ); } //+--------------------------------------------------------------------------- // // Function: CalculateControlVerticalDistance // // Synopsis: calculates the vertical distance from the bottom of Control1 // to the top of Control2 // // Arguments: [hwnd] -- parent dialog // [Control1] -- first control // [Control2] -- second control // // Returns: the distance in pixels // // Notes: assumes control1 is above control2 // //---------------------------------------------------------------------------- int CalculateControlVerticalDistance (HWND hwnd, UINT Control1, UINT Control2) { RECT rect1; RECT rect2; GetWindowRect(GetDlgItem(hwnd, Control1), &rect1); GetWindowRect(GetDlgItem(hwnd, Control2), &rect2); return( rect2.top - rect1.bottom ); } //+--------------------------------------------------------------------------- // // Function: CalculateControlVerticalDistanceFromDlgBottom // // Synopsis: calculates the distance from the bottom of the control to // the bottom of the dialog // // Arguments: [hwnd] -- dialog // [Control] -- control // // Returns: the distance in pixels // // Notes: // //---------------------------------------------------------------------------- int CalculateControlVerticalDistanceFromDlgBottom (HWND hwnd, UINT Control) { RECT rect; RECT rectControl; GetClientRect(hwnd, &rect); GetWindowRect(GetDlgItem(hwnd, Control), &rectControl); return( rect.bottom - rectControl.bottom ); } //+--------------------------------------------------------------------------- // // Function: ACUICenterWindow // // Synopsis: centers the given window // // Arguments: [hWndToCenter] -- window handle // // Returns: (none) // // Notes: This code was stolen from ATL and hacked upon madly :-) // //---------------------------------------------------------------------------- VOID ACUICenterWindow (HWND hWndToCenter) { HWND hWndCenter; // determine owner window to center against DWORD dwStyle = (DWORD) WszGetWindowLong(hWndToCenter, GWL_STYLE); if(dwStyle & WS_CHILD) hWndCenter = ::GetParent(hWndToCenter); else hWndCenter = ::GetWindow(hWndToCenter, GW_OWNER); if (hWndCenter == NULL) { return; } // get coordinates of the window relative to its parent RECT rcDlg; ::GetWindowRect(hWndToCenter, &rcDlg); RECT rcArea; RECT rcCenter; HWND hWndParent; if(!(dwStyle & WS_CHILD)) { // don't center against invisible or minimized windows if(hWndCenter != NULL) { DWORD dwStyle2 = (DWORD) WszGetWindowLong(hWndCenter, GWL_STYLE); if(!(dwStyle2 & WS_VISIBLE) || (dwStyle2 & WS_MINIMIZE)) hWndCenter = NULL; } // center within screen coordinates WszSystemParametersInfo(SPI_GETWORKAREA, NULL, &rcArea, NULL); if(hWndCenter == NULL) rcCenter = rcArea; else ::GetWindowRect(hWndCenter, &rcCenter); } else { // center within parent client coordinates hWndParent = ::GetParent(hWndToCenter); ::GetClientRect(hWndParent, &rcArea); ::GetClientRect(hWndCenter, &rcCenter); ::MapWindowPoints(hWndCenter, hWndParent, (POINT*)&rcCenter, 2); } int DlgWidth = rcDlg.right - rcDlg.left; int DlgHeight = rcDlg.bottom - rcDlg.top; // find dialog's upper left based on rcCenter int xLeft = (rcCenter.left + rcCenter.right) / 2 - DlgWidth / 2; int yTop = (rcCenter.top + rcCenter.bottom) / 2 - DlgHeight / 2; // if the dialog is outside the screen, move it inside if(xLeft < rcArea.left) xLeft = rcArea.left; else if(xLeft + DlgWidth > rcArea.right) xLeft = rcArea.right - DlgWidth; if(yTop < rcArea.top) yTop = rcArea.top; else if(yTop + DlgHeight > rcArea.bottom) yTop = rcArea.bottom - DlgHeight; // map screen coordinates to child coordinates ::SetWindowPos( hWndToCenter, HWND_TOPMOST, xLeft, yTop, -1, -1, SWP_NOSIZE | SWP_NOACTIVATE ); } //+--------------------------------------------------------------------------- // // Function: ACUIViewHTMLHelpTopic // // Synopsis: html help viewer // // Arguments: [hwnd] -- caller window // [pszTopic] -- topic // // Returns: (none) // // Notes: // //---------------------------------------------------------------------------- VOID ACUIViewHTMLHelpTopic (HWND hwnd, LPSTR pszTopic) { // HtmlHelpA( // hwnd, // "%SYSTEMROOT%\\help\\iexplore.chm>large_context", // HH_DISPLAY_TOPIC, // (DWORD)pszTopic // ); } //+--------------------------------------------------------------------------- // // Function: GetEditControlMaxLineWidth // // Synopsis: gets the maximum line width of the edit control // //---------------------------------------------------------------------------- int GetEditControlMaxLineWidth (HWND hwndEdit, HDC hdc, int cline) { int index; int line; int charwidth; int maxwidth = 0; CHAR szMaxBuffer[1024]; WCHAR wsz[1024]; TEXTRANGEA tr; SIZE size; tr.lpstrText = szMaxBuffer; for ( line = 0; line < cline; line++ ) { index = (int)WszSendMessage(hwndEdit, EM_LINEINDEX, (WPARAM)line, 0); charwidth = (int)WszSendMessage(hwndEdit, EM_LINELENGTH, (WPARAM)index, 0); tr.chrg.cpMin = index; tr.chrg.cpMax = index + charwidth; WszSendMessage(hwndEdit, EM_GETTEXTRANGE, 0, (LPARAM)&tr); wsz[0] = NULL; MultiByteToWideChar(0, 0, (const char *)tr.lpstrText, -1, &wsz[0], 1024); if (wsz[0]) { GetTextExtentPoint32W(hdc, &wsz[0], charwidth, &size); if ( size.cx > maxwidth ) { maxwidth = size.cx; } } } return( maxwidth ); } //+--------------------------------------------------------------------------- // // Function: DrawFocusRectangle // // Synopsis: draws the focus rectangle for the edit control // //---------------------------------------------------------------------------- void DrawFocusRectangle (HWND hwnd, HDC hdc) { RECT rect; //PAINTSTRUCT ps; BOOL fReleaseDC = FALSE; if ( hdc == NULL ) { hdc = GetDC(hwnd); if ( hdc == NULL ) { return; } fReleaseDC = TRUE; } GetClientRect(hwnd, &rect); DrawFocusRect(hdc, &rect); if ( fReleaseDC == TRUE ) { ReleaseDC(hwnd, hdc); } } //+--------------------------------------------------------------------------- // // Function: GetHotKeyCharPositionFromString // // Synopsis: gets the character position for the hotkey, zero means // no-hotkey // //---------------------------------------------------------------------------- int GetHotKeyCharPositionFromString (LPWSTR pwszText) { LPWSTR psz = pwszText; while ( ( psz = wcschr(psz, L'&') ) != NULL ) { psz++; if ( *psz != L'&' ) { break; } } if ( psz == NULL ) { return( 0 ); } return (int)(( psz - pwszText ) ); } //+--------------------------------------------------------------------------- // // Function: GetHotKeyCharPosition // // Synopsis: gets the character position for the hotkey, zero means // no-hotkey // //---------------------------------------------------------------------------- int GetHotKeyCharPosition (HWND hwnd) { int nPos = 0; WCHAR szText[MAX_LOADSTRING_BUFFER] = L""; if (WszGetWindowText(hwnd, szText, MAX_LOADSTRING_BUFFER)) { nPos = GetHotKeyCharPositionFromString(szText); } return nPos; } //+--------------------------------------------------------------------------- // // Function: FormatHotKeyOnEditControl // // Synopsis: formats the hot key on an edit control by making it underlined // //---------------------------------------------------------------------------- VOID FormatHotKeyOnEditControl (HWND hwnd, int hkcharpos) { CHARRANGE cr; CHARFORMAT cf; assert( hkcharpos != 0 ); cr.cpMin = hkcharpos - 1; cr.cpMax = hkcharpos; WszSendMessage(hwnd, EM_EXSETSEL, 0, (LPARAM)&cr); memset(&cf, 0, sizeof(CHARFORMAT)); cf.cbSize = sizeof(CHARFORMAT); cf.dwMask = CFM_UNDERLINE; cf.dwEffects |= CFM_UNDERLINE; WszSendMessage(hwnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cf); cr.cpMin = -1; cr.cpMax = 0; WszSendMessage(hwnd, EM_EXSETSEL, 0, (LPARAM)&cr); } //+--------------------------------------------------------------------------- // // Function: AdjustEditControlWidthToLineCount // // Synopsis: adjust edit control width to the given line count // //---------------------------------------------------------------------------- void AdjustEditControlWidthToLineCount(HWND hwnd, int cline, TEXTMETRIC* ptm) { RECT rect; int w; int h; GetWindowRect(hwnd, &rect); h = rect.bottom - rect.top; w = rect.right - rect.left; while ( cline < WszSendMessage(hwnd, EM_GETLINECOUNT, 0, 0) ) { w += ptm->tmMaxCharWidth?ptm->tmMaxCharWidth:16; SetWindowPos(hwnd, NULL, 0, 0, w, h, SWP_NOZORDER | SWP_NOMOVE); printf( "Line count adjusted to = %d\n", (DWORD) WszSendMessage(hwnd, EM_GETLINECOUNT, 0, 0) ); } } DWORD CryptUISetRicheditTextW(HWND hwndDlg, UINT id, LPCWSTR pwsz) { EDITSTREAM editStream; STREAMIN_HELPER_STRUCT helpStruct; SetRicheditIMFOption(GetDlgItem(hwndDlg, id)); // // setup the edit stream struct since it is the same no matter what // editStream.dwCookie = (DWORD_PTR) &helpStruct; editStream.dwError = 0; editStream.pfnCallback = SetRicheditTextWCallback; if (!GetRichEdit2Exists() || !fRichedit20Usable(GetDlgItem(hwndDlg, id))) { WszSetDlgItemText(hwndDlg, id, pwsz); return 0; } helpStruct.pwsz = pwsz; helpStruct.byteoffset = 0; helpStruct.fStreamIn = TRUE; SendDlgItemMessageA(hwndDlg, id, EM_STREAMIN, SF_TEXT | SF_UNICODE, (LPARAM) &editStream); return editStream.dwError; } void SetRicheditIMFOption(HWND hWndRichEdit) { DWORD dwOptions; if (GetRichEdit2Exists() && fRichedit20Usable(hWndRichEdit)) { dwOptions = (DWORD)SendMessageA(hWndRichEdit, EM_GETLANGOPTIONS, 0, 0); dwOptions |= IMF_UIFONTS; SendMessageA(hWndRichEdit, EM_SETLANGOPTIONS, 0, dwOptions); } } DWORD CALLBACK SetRicheditTextWCallback( DWORD_PTR dwCookie, // application-defined value LPBYTE pbBuff, // pointer to a buffer LONG cb, // number of bytes to read or write LONG *pcb // pointer to number of bytes transferred ) { STREAMIN_HELPER_STRUCT *pHelpStruct = (STREAMIN_HELPER_STRUCT *) dwCookie; LONG lRemain = ((wcslen(pHelpStruct->pwsz) * sizeof(WCHAR)) - pHelpStruct->byteoffset); if (pHelpStruct->fStreamIn) { // // The whole string can be copied first time // if ((cb >= (LONG) (wcslen(pHelpStruct->pwsz) * sizeof(WCHAR))) && (pHelpStruct->byteoffset == 0)) { memcpy(pbBuff, pHelpStruct->pwsz, wcslen(pHelpStruct->pwsz) * sizeof(WCHAR)); *pcb = wcslen(pHelpStruct->pwsz) * sizeof(WCHAR); pHelpStruct->byteoffset = *pcb; } // // The whole string has been copied, so terminate the streamin callbacks // by setting the num bytes copied to 0 // else if (((LONG)(wcslen(pHelpStruct->pwsz) * sizeof(WCHAR))) <= pHelpStruct->byteoffset) { *pcb = 0; } // // The rest of the string will fit in this buffer // else if (cb >= (LONG) ((wcslen(pHelpStruct->pwsz) * sizeof(WCHAR)) - pHelpStruct->byteoffset)) { memcpy( pbBuff, ((BYTE *)pHelpStruct->pwsz) + pHelpStruct->byteoffset, ((wcslen(pHelpStruct->pwsz) * sizeof(WCHAR)) - pHelpStruct->byteoffset)); *pcb = ((wcslen(pHelpStruct->pwsz) * sizeof(WCHAR)) - pHelpStruct->byteoffset); pHelpStruct->byteoffset += ((wcslen(pHelpStruct->pwsz) * sizeof(WCHAR)) - pHelpStruct->byteoffset); } // // copy as much as possible // else { memcpy( pbBuff, ((BYTE *)pHelpStruct->pwsz) + pHelpStruct->byteoffset, cb); *pcb = cb; pHelpStruct->byteoffset += cb; } } else { // // This is the EM_STREAMOUT which is only used during the testing of // the richedit2.0 functionality. (we know our buffer is 32 bytes) // if (cb <= 32) { memcpy(pHelpStruct->psz, pbBuff, cb); } *pcb = cb; } return 0; } static BOOL fRichedit20UsableCheckMade = FALSE; static BOOL fRichedit20UsableVar = FALSE; BOOL fRichedit20Usable(HWND hwndEdit) { EDITSTREAM editStream; STREAMIN_HELPER_STRUCT helpStruct; LPWSTR pwsz = L"Test String"; LPSTR pwszCompare = "Test String"; char compareBuf[32]; if (fRichedit20UsableCheckMade) { return (fRichedit20UsableVar); } // // setup the edit stream struct since it is the same no matter what // editStream.dwCookie = (DWORD_PTR) &helpStruct; editStream.dwError = 0; editStream.pfnCallback = SetRicheditTextWCallback; helpStruct.pwsz = pwsz; helpStruct.byteoffset = 0; helpStruct.fStreamIn = TRUE; SendMessageA(hwndEdit, EM_SETSEL, 0, -1); SendMessageA(hwndEdit, EM_STREAMIN, SF_TEXT | SF_UNICODE | SFF_SELECTION, (LPARAM) &editStream); memset(&(compareBuf[0]), 0, 32 * sizeof(char)); helpStruct.psz = compareBuf; helpStruct.fStreamIn = FALSE; SendMessageA(hwndEdit, EM_STREAMOUT, SF_TEXT, (LPARAM) &editStream); fRichedit20UsableVar = (strcmp(pwszCompare, compareBuf) == 0); fRichedit20UsableCheckMade = TRUE; SetWindowTextA(hwndEdit, ""); return (fRichedit20UsableVar); }
28.811765
115
0.500272
npocmaka
1d019fde0e400dd85407182f3575e568a42677b0
1,127
cpp
C++
Source/RTSProject/Plugins/RealTimeStrategy/Source/RealTimeStrategy/Private/Libraries/RTSConstructionLibrary.cpp
HeadClot/ue4-rts
53499c49942aada835b121c89419aaa0be624cbd
[ "MIT" ]
617
2017-04-16T13:34:20.000Z
2022-03-31T23:43:47.000Z
Source/RTSProject/Plugins/RealTimeStrategy/Source/RealTimeStrategy/Private/Libraries/RTSConstructionLibrary.cpp
freezernick/ue4-rts
14ac47ce07d920c01c999f78996791c75de8ff8a
[ "MIT" ]
178
2017-04-05T19:30:21.000Z
2022-03-11T05:44:03.000Z
Source/RTSProject/Plugins/RealTimeStrategy/Source/RealTimeStrategy/Private/Libraries/RTSConstructionLibrary.cpp
freezernick/ue4-rts
14ac47ce07d920c01c999f78996791c75de8ff8a
[ "MIT" ]
147
2017-06-27T08:35:09.000Z
2022-03-28T03:06:17.000Z
#include "Libraries/RTSConstructionLibrary.h" #include "Construction/RTSBuilderComponent.h" int32 URTSConstructionLibrary::GetConstructableBuildingIndex(AActor* Builder, TSubclassOf<AActor> BuildingClass) { if (!IsValid(Builder)) { return INDEX_NONE; } URTSBuilderComponent* BuilderComponent = Builder->FindComponentByClass<URTSBuilderComponent>(); if (!IsValid(BuilderComponent)) { return INDEX_NONE; } return BuilderComponent->GetConstructibleBuildingClasses().IndexOfByKey(BuildingClass); } TSubclassOf<AActor> URTSConstructionLibrary::GetConstructableBuildingClass(AActor* Builder, int32 BuildingIndex) { if (!IsValid(Builder)) { return nullptr; } URTSBuilderComponent* BuilderComponent = Builder->FindComponentByClass<URTSBuilderComponent>(); if (!IsValid(BuilderComponent)) { return nullptr; } TArray<TSubclassOf<AActor>> ConstructableBuildings = BuilderComponent->GetConstructibleBuildingClasses(); return ConstructableBuildings.IsValidIndex(BuildingIndex) ? ConstructableBuildings[BuildingIndex] : nullptr; }
28.175
112
0.753327
HeadClot
1d01d78a62b4b0e4ac4e5254e1866e2051263ade
710
hpp
C++
source/query_processor.hpp
simonenkos/dnsperf
85f8ba97b9a85cf84b2d87610f829d526af459f8
[ "MIT" ]
null
null
null
source/query_processor.hpp
simonenkos/dnsperf
85f8ba97b9a85cf84b2d87610f829d526af459f8
[ "MIT" ]
null
null
null
source/query_processor.hpp
simonenkos/dnsperf
85f8ba97b9a85cf84b2d87610f829d526af459f8
[ "MIT" ]
null
null
null
#ifndef DNSPERF_QUERY_PROCESSOR_HPP #define DNSPERF_QUERY_PROCESSOR_HPP #include <string> #include <cstdint> #include "query_result.hpp" /** * Interface of processor which is responsible for making a query. */ struct query_processor { query_processor() = default; query_processor(const query_processor & other) = default; query_processor( query_processor && other) = default; query_processor & operator=(const query_processor & other) = default; query_processor & operator=( query_processor && other) = default; virtual ~query_processor() = default; virtual query_result process(const std::string & url) const = 0; }; #endif //DNSPERF_QUERY_PROCESSOR_HPP
25.357143
73
0.725352
simonenkos
1d0af241a2faaa6acd1f66644a479013f931bef4
868
cpp
C++
src/lib/MutexBase.cpp
romoadri21/boi
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
[ "BSD-3-Clause" ]
null
null
null
src/lib/MutexBase.cpp
romoadri21/boi
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
[ "BSD-3-Clause" ]
null
null
null
src/lib/MutexBase.cpp
romoadri21/boi
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010, Piet Hein Schouten. All rights reserved. * This code is licensed under a BSD-style license that can be * found in the LICENSE file. The license can also be found at: * http://www.boi-project.org/license */ #include "ThreadLockData.h" #include "Mutex.h" #include "MutexBase.h" namespace BOI { MutexBase::MutexBase() : m_mutexId(0), m_lockData() { } void MutexBase::Attach(Mutex* pMutex) { pMutex->m_pBase = this; pMutex->m_pMutex = &m_mutexes[m_mutexId]; m_mutexId = (m_mutexId + 1) % BOI_MUTEXBASE_MAX_QMUTEXES; } ThreadLockData* MutexBase::GetData() { ThreadLockData* pThreadLockData = m_lockData.localData(); if (pThreadLockData == NULL) { pThreadLockData = new ThreadLockData; m_lockData.setLocalData(pThreadLockData); } return pThreadLockData; } } // namespace BOI
18.869565
63
0.686636
romoadri21
1d0bd93afc7c766106a533846cefcae4e2fd40c8
3,426
cc
C++
src/server_main.cc
magazino/tf_service
da63e90b062a57eb1280b589ef8f249be5d422c4
[ "Apache-2.0" ]
17
2019-12-11T14:26:21.000Z
2022-01-30T03:41:40.000Z
src/server_main.cc
magazino/tf_service
da63e90b062a57eb1280b589ef8f249be5d422c4
[ "Apache-2.0" ]
8
2019-12-13T14:45:32.000Z
2022-02-14T16:22:30.000Z
src/server_main.cc
magazino/tf_service
da63e90b062a57eb1280b589ef8f249be5d422c4
[ "Apache-2.0" ]
2
2020-07-29T08:47:50.000Z
2021-12-13T10:38:39.000Z
// Copyright 2019 Magazino GmbH // // 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 // // https://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 <iostream> #include <memory> #include <thread> #include "ros/ros.h" #include "tf_service/buffer_server.h" #include "boost/program_options.hpp" namespace po = boost::program_options; int main(int argc, char** argv) { int num_threads = 0; po::options_description desc("Options"); // clang-format off desc.add_options() ("help", "show usage") ("num_threads", po::value<int>(&num_threads)->default_value(0), "Number of handler threads. 0 means number of CPU cores.") ("cache_time", po::value<double>(), "Buffer cache time of the underlying TF buffer in seconds.") ("max_timeout", po::value<double>(), "Requests with lookup timeouts (seconds) above this will be blocked.") ("frames_service", "Advertise the tf2_frames service.") ("debug", "Advertise the tf2_frames service (same as --frames_service).") ("add_legacy_server", "If set, also run a tf2_ros::BufferServer.") ("legacy_server_namespace", po::value<std::string>(), "Use a separate namespace for the legacy action server.") ; // clang-format on po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); } catch (const po::error& exception) { std::cerr << exception.what() << std::endl; return EXIT_FAILURE; } po::notify(vm); if (vm.count("help")) { std::cout << desc << std::endl; return EXIT_FAILURE; } ros::init(argc, argv, "tf_service"); // boost::po overflows unsigned int for negative values passed to argv, // so we use a signed one and check manually. if (num_threads < 0) { ROS_ERROR("The number of threads can't be negative."); return EXIT_FAILURE; } else if (num_threads == 0) { ROS_INFO_STREAM("--num_threads unspecified / zero, using available cores."); num_threads = std::thread::hardware_concurrency(); } tf_service::ServerOptions options; if (vm.count("cache_time")) options.cache_time = ros::Duration(vm["cache_time"].as<double>()); if (vm.count("max_timeout")) options.max_timeout = ros::Duration(vm["max_timeout"].as<double>()); options.debug = vm.count("frames_service") || vm.count("debug"); options.add_legacy_server = vm.count("add_legacy_server"); options.legacy_server_namespace = vm.count("legacy_server_namespace") ? vm["legacy_server_namespace"].as<std::string>() : ros::this_node::getName(); ROS_INFO_STREAM("Starting server with " << num_threads << " handler threads"); ROS_INFO_STREAM_COND(options.add_legacy_server, "Also starting a legacy tf2::BufferServer in namespace " << options.legacy_server_namespace); tf_service::Server server(options); ros::AsyncSpinner spinner(num_threads); spinner.start(); ros::waitForShutdown(); spinner.stop(); return EXIT_SUCCESS; }
36.063158
80
0.686223
magazino
1d0ebd650e004eb8f4e81f6a905b6b1723f5f9f7
63,741
cpp
C++
src/plugin/kernel/src/AFCKernelModule.cpp
ArkGame/ArkGameFrame
a7f8413dd416cd1ac5b12adbdd84f010f59f11e2
[ "Apache-2.0" ]
168
2016-08-18T07:24:48.000Z
2018-02-06T06:40:45.000Z
src/plugin/kernel/src/AFCKernelModule.cpp
Mu-L/ARK
a7f8413dd416cd1ac5b12adbdd84f010f59f11e2
[ "Apache-2.0" ]
11
2019-05-27T12:26:02.000Z
2021-05-12T02:45:16.000Z
src/plugin/kernel/src/AFCKernelModule.cpp
ArkGame/ArkGameFrame
a7f8413dd416cd1ac5b12adbdd84f010f59f11e2
[ "Apache-2.0" ]
51
2016-09-01T10:17:38.000Z
2018-02-06T10:45:25.000Z
/* * This source file is part of ARK * For the latest info, see https://github.com/ArkNX * * Copyright (c) 2013-2020 ArkNX authors. * * 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 "base/AFDefine.hpp" #include "kernel/include/AFCKernelModule.hpp" #include "kernel/include/AFCEntity.hpp" #include "kernel/include/AFCTable.hpp" #include "kernel/include/AFCDataList.hpp" #include "kernel/include/AFCContainer.hpp" namespace ark { AFCKernelModule::AFCKernelModule() { inner_nodes_.AddElement(AFEntityMetaBaseEntity::config_id(), ARK_NEW int32_t(0)); inner_nodes_.AddElement(AFEntityMetaBaseEntity::class_name(), ARK_NEW int32_t(0)); inner_nodes_.AddElement(AFEntityMetaBaseEntity::map_id(), ARK_NEW int32_t(0)); inner_nodes_.AddElement(AFEntityMetaBaseEntity::map_inst_id(), ARK_NEW int32_t(0)); } AFCKernelModule::~AFCKernelModule() { objects_.clear(); } bool AFCKernelModule::Init() { delete_list_.clear(); m_pMapModule = FindModule<AFIMapModule>(); m_pClassModule = FindModule<AFIClassMetaModule>(); m_pConfigModule = FindModule<AFIConfigModule>(); m_pGUIDModule = FindModule<AFIGUIDModule>(); auto container_func = std::bind(&AFCKernelModule::OnContainerCallBack, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5); AddCommonContainerCallBack(std::move(container_func), 999999); // after other callbacks being done AddSyncCallBack(); return true; } bool AFCKernelModule::Update() { cur_exec_object_ = NULL_GUID; if (!delete_list_.empty()) { for (auto it : delete_list_) { DestroyEntity(it); } delete_list_.clear(); } for (auto& iter : objects_) { auto pEntity = iter.second; if (pEntity == nullptr) { continue; } pEntity->Update(); } AFClassCallBackManager::OnDelaySync(); return true; } bool AFCKernelModule::PreShut() { return DestroyAll(); } bool AFCKernelModule::CopyData(std::shared_ptr<AFIEntity> pEntity, std::shared_ptr<AFIStaticEntity> pStaticEntity) { if (pEntity == nullptr || nullptr == pStaticEntity) { return false; } // static node manager must be not empty auto pStaticNodeManager = GetNodeManager(pStaticEntity); if (pStaticNodeManager == nullptr || pStaticNodeManager->IsEmpty()) { return false; } // node manager must be empty auto pNodeManager = GetNodeManager(pEntity); if (pNodeManager == nullptr || !pNodeManager->IsEmpty()) { return false; } // copy data auto& data_list = pStaticNodeManager->GetDataList(); for (auto& iter : data_list) { auto pData = iter.second; pNodeManager->CreateData(pData); } return true; } std::shared_ptr<AFIEntity> AFCKernelModule::CreateEntity(const guid_t& self, const int map_id, const int map_instance_id, const std::string& class_name, const ID_TYPE config_id, const AFIDataList& args) { guid_t object_id = self; auto pMapInfo = m_pMapModule->GetMapInfo(map_id); if (pMapInfo == nullptr) { ARK_LOG_ERROR("There is no scene, scene = {}", map_id); return nullptr; } if (!pMapInfo->ExistInstance(map_instance_id)) { ARK_LOG_ERROR("There is no group, scene = {} group = {}", map_id, map_instance_id); return nullptr; } auto pClassMeta = m_pClassModule->FindMeta(class_name); if (nullptr == pClassMeta) { ARK_LOG_ERROR("There is no class meta, name = {}", class_name); return nullptr; } std::shared_ptr<AFIStaticEntity> pStaticEntity = nullptr; if (config_id > 0) { auto pStaticEntity = GetStaticEntity(config_id); if (nullptr == pStaticEntity) { ARK_LOG_ERROR("There is no config, config_id = {}", config_id); return nullptr; } if (pStaticEntity->GetClassName() != class_name) { ARK_LOG_ERROR("Config class does not match entity class, config_id = {}", config_id); return nullptr; } } // check args num size_t arg_count = args.GetCount(); if (arg_count % 2 != 0) { ARK_LOG_ERROR("Args count is wrong, count = {}", arg_count); return nullptr; } if (object_id == NULL_GUID) { object_id = m_pGUIDModule->CreateGUID(); } // Check if the entity exists if (GetEntity(object_id) != nullptr) { ARK_LOG_ERROR("The entity has existed, id = {}", object_id); return nullptr; } std::shared_ptr<AFIEntity> pEntity = std::make_shared<AFCEntity>(pClassMeta, object_id, config_id, map_id, map_instance_id, args); objects_.insert(object_id, pEntity); if (class_name == AFEntityMetaPlayer::self_name()) { pMapInfo->AddEntityToInstance(map_instance_id, object_id, true); } //else if (class_name == AFEntityMetaPlayer::self_name()) // to do : npc type for now we do not have //{ //} CopyData(pEntity, pStaticEntity); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_PRE_LOAD_DATA, args); // original args here DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_LOAD_DATA, args); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_PRE_EFFECT_DATA, args); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_EFFECT_DATA, args); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_POST_EFFECT_DATA, args); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_DATA_FINISHED, args); return pEntity; } std::shared_ptr<AFIEntity> AFCKernelModule::CreateContainerEntity( const guid_t& self, const uint32_t container_index, const std::string& class_name, const ID_TYPE config_id) { auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("There is no object, object = {}", self); return nullptr; } auto pContainer = pEntity->FindContainer(container_index); if (pContainer == nullptr) { ARK_LOG_ERROR("There is no container, container = {}", container_index); return nullptr; } auto pClassMeta = m_pClassModule->FindMeta(class_name); if (nullptr == pClassMeta) { ARK_LOG_ERROR("There is no class meta, name = {}", class_name); return nullptr; } std::shared_ptr<AFIStaticEntity> pStaticEntity = nullptr; if (config_id > 0) { auto pStaticEntity = GetStaticEntity(config_id); if (nullptr == pStaticEntity) { ARK_LOG_ERROR("There is no config, config_id = {}", config_id); return nullptr; } if (pStaticEntity->GetClassName() != class_name) { ARK_LOG_ERROR("Config class does not match entity class, config_id = {}", config_id); return nullptr; } } auto map_id = pEntity->GetMapID(); auto pMapInfo = m_pMapModule->GetMapInfo(map_id); if (pMapInfo == nullptr) { ARK_LOG_ERROR("There is no scene, scene = {}", map_id); return nullptr; } auto map_instance_id = pEntity->GetMapEntityID(); if (!pMapInfo->ExistInstance(map_instance_id)) { ARK_LOG_ERROR("There is no group, scene = {} group = {}", map_id, map_instance_id); return nullptr; } guid_t object_id = m_pGUIDModule->CreateGUID(); // Check if the entity exists if (GetEntity(object_id) != nullptr) { ARK_LOG_ERROR("The entity has existed, id = {}", object_id); return nullptr; } std::shared_ptr<AFIEntity> pContainerEntity = std::make_shared<AFCEntity>(pClassMeta, object_id, config_id, map_id, map_instance_id, AFCDataList()); objects_.insert(object_id, pContainerEntity); CopyData(pContainerEntity, pStaticEntity); pContainer->Place(pContainerEntity); AFCDataList args; DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_PRE_LOAD_DATA, args); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_LOAD_DATA, args); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_PRE_EFFECT_DATA, args); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_EFFECT_DATA, args); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_POST_EFFECT_DATA, args); DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_DATA_FINISHED, args); return pContainerEntity; } std::shared_ptr<AFIStaticEntity> AFCKernelModule::GetStaticEntity(const ID_TYPE config_id) { return m_pConfigModule->FindStaticEntity(config_id); } std::shared_ptr<AFIEntity> AFCKernelModule::GetEntity(const guid_t& self) { return objects_.find_value(self); } bool AFCKernelModule::DestroyAll() { for (auto& iter : objects_) { auto& pEntity = iter.second; if (pEntity->GetParentContainer() != nullptr) { continue; } delete_list_.push_back(iter.second->GetID()); } // run another frame Update(); return true; } bool AFCKernelModule::DestroyEntity(const guid_t& self) { if (self == cur_exec_object_ && self != NULL_GUID) { return DestroySelf(self); } auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("Cannot find this object, self={}", NULL_GUID); return false; } auto pParentContainer = pEntity->GetParentContainer(); if (pParentContainer) { // use container to destroy its entity return pParentContainer->Destroy(self); } else { return InnerDestroyEntity(pEntity); } } bool AFCKernelModule::DestroySelf(const guid_t& self) { delete_list_.push_back(self); return true; } bool AFCKernelModule::InnerDestroyEntity(std::shared_ptr<AFIEntity> pEntity) { if (pEntity == nullptr) { ARK_LOG_ERROR("Cannot find this object, self={}", NULL_GUID); return false; } auto& self = pEntity->GetID(); int32_t map_id = pEntity->GetMapID(); int32_t inst_id = pEntity->GetMapEntityID(); std::shared_ptr<AFMapInfo> pMapInfo = m_pMapModule->GetMapInfo(map_id); if (pMapInfo != nullptr) { const std::string& class_name = pEntity->GetClassName(); pMapInfo->RemoveEntityFromInstance( inst_id, self, ((class_name == AFEntityMetaPlayer::self_name()) ? true : false)); DoEvent(self, class_name, ArkEntityEvent::ENTITY_EVT_PRE_DESTROY, AFCDataList()); DoEvent(self, class_name, ArkEntityEvent::ENTITY_EVT_DESTROY, AFCDataList()); return objects_.erase(self); } else { ARK_LOG_ERROR("Cannot find this map, object_id={} map={} inst={}", self, map_id, inst_id); return false; } } bool AFCKernelModule::AddEventCallBack(const guid_t& self, const int nEventID, EVENT_PROCESS_FUNCTOR&& cb) { std::shared_ptr<AFIEntity> pEntity = GetEntity(self); ARK_ASSERT_RET_VAL(pEntity != nullptr, false); auto pEventManager = GetEventManager(pEntity); ARK_ASSERT_RET_VAL(pEventManager != nullptr, false); return pEventManager->AddEventCallBack(nEventID, std::move(cb)); } bool AFCKernelModule::AddClassCallBack(const std::string& class_name, CLASS_EVENT_FUNCTOR&& cb, const int32_t prio) { return m_pClassModule->AddClassCallBack(class_name, std::move(cb), prio); } bool AFCKernelModule::AddNodeCallBack( const std::string& class_name, const std::string& name, DATA_NODE_EVENT_FUNCTOR&& cb, const int32_t prio) { auto pClassMeta = m_pClassModule->FindMeta(class_name); ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false); auto index = pClassMeta->GetIndex(name); if (index == 0) { return false; } AddNodeCallBack(class_name, index, std::move(cb), prio); return true; } bool AFCKernelModule::AddTableCallBack( const std::string& class_name, const std::string& name, DATA_TABLE_EVENT_FUNCTOR&& cb, const int32_t prio) { auto pClassMeta = m_pClassModule->FindMeta(class_name); ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false); auto index = pClassMeta->GetIndex(name); if (index == 0) { return false; } AddTableCallBack(class_name, index, std::move(cb), prio); return true; } bool AFCKernelModule::AddNodeCallBack( const std::string& class_name, const uint32_t index, DATA_NODE_EVENT_FUNCTOR&& cb, const int32_t prio) { auto pClassMeta = m_pClassModule->FindMeta(class_name); ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false); auto pDataMeta = pClassMeta->FindDataMeta(index); ARK_ASSERT_RET_VAL(pDataMeta != nullptr, false); auto pCallBack = pClassMeta->GetClassCallBackManager(); ARK_ASSERT_RET_VAL(pCallBack != nullptr, false); pCallBack->AddDataCallBack(index, std::move(cb), prio); return true; } bool AFCKernelModule::AddTableCallBack( const std::string& class_name, const uint32_t index, DATA_TABLE_EVENT_FUNCTOR&& cb, const int32_t prio) { auto pClassMeta = m_pClassModule->FindMeta(class_name); ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false); auto pTableMeta = pClassMeta->FindTableMeta(index); ARK_ASSERT_RET_VAL(pTableMeta != nullptr, false); auto pCallBack = pClassMeta->GetClassCallBackManager(); ARK_ASSERT_RET_VAL(pCallBack != nullptr, false); pCallBack->AddTableCallBack(index, std::move(cb), prio); return true; } bool AFCKernelModule::AddContainerCallBack( const std::string& class_name, const uint32_t index, CONTAINER_EVENT_FUNCTOR&& cb, const int32_t prio) { auto pClassMeta = m_pClassModule->FindMeta(class_name); ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false); auto pContainerMeta = pClassMeta->FindContainerMeta(index); ARK_ASSERT_RET_VAL(pContainerMeta != nullptr, false); auto pCallBack = pClassMeta->GetClassCallBackManager(); ARK_ASSERT_RET_VAL(pCallBack != nullptr, false); pCallBack->AddContainerCallBack(index, std::move(cb), prio); return true; } bool AFCKernelModule::AddCommonContainerCallBack(CONTAINER_EVENT_FUNCTOR&& cb, const int32_t prio) { auto pClassMeta = m_pClassModule->FindMeta(AFEntityMetaPlayer::self_name()); ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false); auto& meta_list = pClassMeta->GetContainerMetaList(); for (auto& iter : meta_list) { auto pMeta = iter.second; if (!pMeta) { continue; } AddContainerCallBack(AFEntityMetaPlayer::self_name(), pMeta->GetIndex(), std::move(cb), prio); } return true; } bool AFCKernelModule::AddCommonClassEvent(CLASS_EVENT_FUNCTOR&& cb, const int32_t prio) { auto& class_meta_list = m_pClassModule->GetMetaList(); for (auto& iter : class_meta_list) { auto pClassMeta = iter.second; if (nullptr == pClassMeta) { continue; } AddClassCallBack(iter.first, std::move(cb), prio); } return true; } bool AFCKernelModule::AddLeaveSceneEvent(const std::string& class_name, SCENE_EVENT_FUNCTOR&& cb, const int32_t prio) { auto pClassMeta = m_pClassModule->FindMeta(class_name); ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false); auto pCallBack = pClassMeta->GetClassCallBackManager(); ARK_ASSERT_RET_VAL(pCallBack != nullptr, false); return pCallBack->AddLeaveSceneEvent(std::move(cb), prio); } bool AFCKernelModule::AddEnterSceneEvent(const std::string& class_name, SCENE_EVENT_FUNCTOR&& cb, const int32_t prio) { auto pClassMeta = m_pClassModule->FindMeta(class_name); ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false); auto pCallBack = pClassMeta->GetClassCallBackManager(); ARK_ASSERT_RET_VAL(pCallBack != nullptr, false); return pCallBack->AddEnterSceneEvent(std::move(cb), prio); } bool AFCKernelModule::AddMoveEvent(const std::string& class_name, MOVE_EVENT_FUNCTOR&& cb, const int32_t prio) { auto pClassMeta = m_pClassModule->FindMeta(class_name); ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false); auto pCallBack = pClassMeta->GetClassCallBackManager(); ARK_ASSERT_RET_VAL(pCallBack != nullptr, false); return pCallBack->AddMoveEvent(std::move(cb), prio); } void AFCKernelModule::AddSyncCallBack() { // node sync call back auto node_func = std::bind(&AFCKernelModule::OnSyncNode, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4); AFClassCallBackManager::AddNodeSyncCallBack(ArkDataMask::PF_SYNC_VIEW, std::move(node_func)); AFClassCallBackManager::AddNodeSyncCallBack(ArkDataMask::PF_SYNC_SELF, std::move(node_func)); // table sync call back auto table_func = std::bind(&AFCKernelModule::OnSyncTable, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4); AFClassCallBackManager::AddTableSyncCallBack(ArkDataMask::PF_SYNC_VIEW, std::move(table_func)); AFClassCallBackManager::AddTableSyncCallBack(ArkDataMask::PF_SYNC_SELF, std::move(table_func)); // container sync call back auto container_func = std::bind(&AFCKernelModule::OnSyncContainer, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5, std::placeholders::_6); AFClassCallBackManager::AddContainerSyncCallBack(ArkDataMask::PF_SYNC_VIEW, std::move(container_func)); AFClassCallBackManager::AddContainerSyncCallBack(ArkDataMask::PF_SYNC_SELF, std::move(container_func)); // data delay call back auto delay_func = std::bind( &AFCKernelModule::OnDelaySyncData, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3); AFClassCallBackManager::AddDelaySyncCallBack(ArkDataMask::PF_SYNC_VIEW, std::move(delay_func)); AFClassCallBackManager::AddDelaySyncCallBack(ArkDataMask::PF_SYNC_SELF, std::move(delay_func)); // send msg functor auto view_func = std::bind(&AFCKernelModule::SendToView, this, std::placeholders::_1, std::placeholders::_2); sync_functors.insert(std::make_pair(ArkDataMask::PF_SYNC_VIEW, std::forward<SYNC_FUNCTOR>(view_func))); auto self_func = std::bind(&AFCKernelModule::SendToSelf, this, std::placeholders::_1, std::placeholders::_2); sync_functors.insert(std::make_pair(ArkDataMask::PF_SYNC_SELF, std::forward<SYNC_FUNCTOR>(self_func))); } int AFCKernelModule::OnSyncNode( const guid_t& self, const uint32_t index, const ArkDataMask mask_value, const AFIData& data) { // find parent entity auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("sync node failed entity do no exist, self={}", self); return -1; } AFMsg::pb_entity pb_data; auto entity_id = self; auto pb_entity = pb_data.mutable_data(); auto pParentContainer = pEntity->GetParentContainer(); if (pParentContainer != nullptr) { if (!TryAddContainerPBEntity(pParentContainer, self, *pb_data.mutable_data(), entity_id, pb_entity)) { ARK_LOG_ERROR("sync node failed container entity do no exist, self={}", self); return -1; } } if (!NodeToPBData(index, data, pb_entity)) { ARK_LOG_ERROR("node to pb failed, self={}, index={}", self, index); return -1; } pb_data.set_id(entity_id); if (SendSyncMsg(entity_id, mask_value, pb_data) < 0) { ARK_LOG_ERROR("send sync msg failed, self={}, index={}", entity_id, index); return -1; } return 0; } int AFCKernelModule::OnSyncTable( const guid_t& self, const TABLE_EVENT_DATA& event, const ArkDataMask mask_value, const AFIData& data) { ArkTableOpType op_type = static_cast<ArkTableOpType>(event.op_type_); switch (op_type) { case ArkTableOpType::TABLE_ADD: { OnSyncTableAdd(self, event, mask_value); } break; case ArkTableOpType::TABLE_DELETE: { OnSyncTableDelete(self, event, mask_value); } break; case ArkTableOpType::TABLE_SWAP: // do not have yet break; case ArkTableOpType::TABLE_UPDATE: { OnSyncTableUpdate(self, event, mask_value, data); } break; case ArkTableOpType::TABLE_COVERAGE: // will do something break; default: break; } return 0; } int AFCKernelModule::OnSyncContainer(const guid_t& self, const uint32_t index, const ArkDataMask mask, const ArkContainerOpType op_type, uint32_t src_index, uint32_t dest_index) { switch (op_type) { case ArkContainerOpType::OP_PLACE: { OnSyncContainerPlace(self, index, mask, src_index); } break; case ArkContainerOpType::OP_REMOVE: { OnSyncContainerRemove(self, index, mask, src_index); } break; case ArkContainerOpType::OP_DESTROY: { OnSyncContainerDestroy(self, index, mask, src_index); } break; case ArkContainerOpType::OP_SWAP: { OnSyncContainerSwap(self, index, mask, src_index, dest_index); } break; default: break; } return 0; } int AFCKernelModule::OnDelaySyncData(const guid_t& self, const ArkDataMask mask_value, const AFDelaySyncData& data) { if (data.node_list_.size() == 0 && data.table_list_.size() == 0) { return 0; } // find parent entity auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("sync delay data failed entity do no exist, self={}", self); return -1; } AFMsg::pb_delay_entity pb_data; auto entity_id = self; auto pb_entity = pb_data.mutable_data(); auto pParentContainer = pEntity->GetParentContainer(); if (pParentContainer != nullptr) { if (!TryAddContainerPBEntity(pParentContainer, self, *pb_data.mutable_data(), entity_id, pb_entity)) { ARK_LOG_ERROR("sync delay data failed container entity do no exist, self={}", self); return -1; } } // node to pb for (auto& iter : data.node_list_) { auto pNode = iter; if (!NodeToPBData(pNode, pb_entity)) { continue; } } // table to pb for (auto& iter : data.table_list_) { auto table_index = iter.first; auto& table = iter.second; DelayTableToPB(table, table_index, pb_data, *pb_entity); } // container to pb for (auto& iter : data.container_list_) { auto container_index = iter.first; auto& container = iter.second; DelayContainerToPB(pEntity, container, container_index, pb_data); } pb_data.set_id(entity_id); if (SendSyncMsg(entity_id, mask_value, pb_data) < 0) { ARK_LOG_ERROR("send sync msg failed, self={}", self); return -1; } return 0; } int AFCKernelModule::OnSyncTableAdd(const guid_t& self, const TABLE_EVENT_DATA& event, const ArkDataMask mask_value) { // find parent entity auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("sync table failed entity do no exist, self={}", self); return -1; } auto pTable = pEntity->FindTable(event.table_index_); if (nullptr == pTable) { ARK_LOG_ERROR("sync table failed table do no exist, self={}, table={}", self, event.table_name_); return -1; } auto pRow = pTable->FindRow(event.row_); if (nullptr == pRow) { ARK_LOG_ERROR( "sync table failed table row do no exist, self={}, table={}, row={}", self, event.table_name_, event.row_); return -1; } AFMsg::pb_entity_table_add pb_data; auto entity_id = self; auto pb_entity = pb_data.mutable_data(); auto pParentContainer = pEntity->GetParentContainer(); if (pParentContainer != nullptr) { if (!TryAddContainerPBEntity(pParentContainer, self, *pb_data.mutable_data(), entity_id, pb_entity)) { ARK_LOG_ERROR("sync node failed container entity do no exist, self={}", self); return -1; } } AFMsg::pb_entity_data pb_row; if (!RowToPBData(pRow, event.row_, &pb_row)) { ARK_LOG_ERROR( "sync table failed table row do no exist, self={}, table={}, row={}", self, event.table_name_, event.row_); return -1; } AFMsg::pb_table pb_table; pb_table.mutable_datas_value()->insert({event.row_, pb_row}); pb_entity->mutable_datas_table()->insert({event.table_index_, pb_table}); pb_data.set_id(entity_id); SendSyncMsg(entity_id, mask_value, pb_data); return 0; } int AFCKernelModule::OnSyncTableDelete(const guid_t& self, const TABLE_EVENT_DATA& event, const ArkDataMask mask_value) { // find parent entity auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("sync table failed entity do no exist, self={}", self); return -1; } AFMsg::pb_entity_table_delete pb_data; auto entity_id = self; auto pb_entity = pb_data.mutable_data(); auto pParentContainer = pEntity->GetParentContainer(); if (pParentContainer != nullptr) { if (!TryAddContainerPBEntity(pParentContainer, self, *pb_data.mutable_data(), entity_id, pb_entity)) { ARK_LOG_ERROR("sync node failed container entity do no exist, self={}", self); return -1; } } AFMsg::pb_entity_data pb_row; AFMsg::pb_table pb_table; pb_table.mutable_datas_value()->insert({event.row_, pb_row}); pb_entity->mutable_datas_table()->insert({event.table_index_, pb_table}); SendSyncMsg(entity_id, mask_value, pb_data); return 0; } int AFCKernelModule::OnSyncTableUpdate( const guid_t& self, const TABLE_EVENT_DATA& event, const ArkDataMask mask_value, const AFIData& data) { // find parent entity auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("sync table failed entity do no exist, self={}", self); return -1; } AFMsg::pb_entity_table_update pb_data; auto entity_id = self; auto pb_entity = pb_data.mutable_data(); auto pParentContainer = pEntity->GetParentContainer(); if (pParentContainer != nullptr) { if (!TryAddContainerPBEntity(pParentContainer, self, *pb_data.mutable_data(), entity_id, pb_entity)) { ARK_LOG_ERROR("sync node failed container entity do no exist, self={}", self); return -1; } } AFMsg::pb_entity_data pb_row; if (!NodeToPBData(event.data_index_, data, &pb_row)) { ARK_LOG_ERROR( "sync table failed table node do no exist, self={}, table={}, row={}", self, event.table_name_, event.row_); return -1; } AFMsg::pb_table pb_table; pb_table.mutable_datas_value()->insert({event.row_, pb_row}); pb_entity->mutable_datas_table()->insert({event.table_index_, pb_table}); pb_data.set_id(entity_id); SendSyncMsg(entity_id, mask_value, pb_data); return 0; } int AFCKernelModule::OnSyncContainerPlace( const guid_t& self, const uint32_t index, const ArkDataMask mask, uint32_t src_index) { // find parent entity auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("sync container failed entity do no exist, self={}", self); return -1; } auto pContainer = pEntity->FindContainer(index); if (pEntity == nullptr) { ARK_LOG_ERROR("sync container failed container do no exist, self={}, container={}", self, index); return -1; } auto pContainerEntity = pContainer->Find(src_index); if (pContainerEntity == nullptr) { ARK_LOG_ERROR("sync container failed container entity do no exist, self={}, container={}, entity={}", self, index, src_index); return -1; } if (pContainerEntity->IsSent()) { AFMsg::pb_container_place pb_data; pb_data.set_id(self); pb_data.set_index(index); pb_data.set_entity_index(src_index); pb_data.set_entity_id(pContainerEntity->GetID()); SendSyncMsg(self, mask, pb_data); } else { AFMsg::pb_container_create pb_data; if (!EntityToPBData(pContainerEntity, pb_data.mutable_data())) { ARK_LOG_ERROR("sync container failed container entity to pb failed, self={}, container={}, entity={}", self, index, src_index); return -1; } pb_data.set_id(self); pb_data.set_index(index); pb_data.set_entity_index(src_index); SendSyncMsg(self, mask, pb_data); } return 0; } int AFCKernelModule::OnSyncContainerRemove( const guid_t& self, const uint32_t index, const ArkDataMask mask, uint32_t src_index) { // find parent entity auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("sync container failed entity do no exist, self={}", self); return -1; } AFMsg::pb_container_remove pb_data; pb_data.set_id(self); pb_data.set_index(index); pb_data.set_entity_index(src_index); SendSyncMsg(self, mask, pb_data); return 0; } int AFCKernelModule::OnSyncContainerDestroy( const guid_t& self, const uint32_t index, const ArkDataMask mask, uint32_t src_index) { // find parent entity auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("sync container failed entity do no exist, self={}", self); return -1; } AFMsg::pb_container_destroy pb_data; pb_data.set_id(self); pb_data.set_index(index); pb_data.set_entity_index(src_index); SendSyncMsg(self, mask, pb_data); return 0; } int AFCKernelModule::OnSyncContainerSwap( const guid_t& self, const uint32_t index, const ArkDataMask mask, uint32_t src_index, uint32_t dest_index) { // find parent entity auto pEntity = GetEntity(self); if (pEntity == nullptr) { ARK_LOG_ERROR("sync container failed entity do no exist, self={}", self); return -1; } AFMsg::pb_container_swap pb_data; pb_data.set_id(self); pb_data.set_index(index); pb_data.set_src_index(src_index); pb_data.set_dest_index(dest_index); SendSyncMsg(self, mask, pb_data); return 0; } bool AFCKernelModule::DelayTableToPB( const AFDelaySyncTable& table, const uint32_t index, AFMsg::pb_delay_entity& data, AFMsg::pb_entity_data& pb_entity) { AFMsg::pb_table pb_table; AFMsg::delay_clear_row clear_row_list; for (auto& iter : table.row_list_) { AFMsg::pb_entity_data pb_row; auto row_index = iter.first; auto& row_data = iter.second; for (auto& iter_row : row_data.node_list_) { auto pNode = iter_row; if (NodeToPBData(pNode, &pb_row)) { pb_table.mutable_datas_value()->insert({row_index, pb_row}); } } if (row_data.need_clear_) { clear_row_list.add_row_list(row_index); } } if (table.need_clear_) { data.add_clear_tables(index); } if (clear_row_list.row_list_size() > 0) { data.mutable_clear_rows()->insert({index, clear_row_list}); } pb_entity.mutable_datas_table()->insert({index, pb_table}); return true; } bool AFCKernelModule::DelayContainerToPB(std::shared_ptr<AFIEntity> pEntity, const AFDelaySyncContainer& container, const uint32_t index, AFMsg::pb_delay_entity& data) { AFMsg::delay_container pb_delay_container; AFMsg::pb_container pb_conatiner; for (auto& iter : container.index_list_) { auto entity_index = iter; auto pContaier = pEntity->FindContainer(index); if (pContaier == nullptr) { continue; } auto pContainerEntity = pContaier->Find(entity_index); if (pContainerEntity == nullptr) { pb_delay_container.mutable_entity_list()->insert({entity_index, NULL_GUID}); } else if (pEntity->IsSent()) { pb_delay_container.mutable_entity_list()->insert({entity_index, pContainerEntity->GetID()}); } else { AFMsg::pb_entity pb_container_entity; if (!EntityToPBData(pContainerEntity, &pb_container_entity)) { continue; } pb_conatiner.mutable_datas_value()->insert({entity_index, pb_container_entity}); } } if (pb_conatiner.datas_value_size() > 0) { data.mutable_data()->mutable_datas_container()->insert({index, pb_conatiner}); } data.mutable_container_entity()->insert({index, pb_delay_container}); AFMsg::delay_container pb_destroy_entity; for (auto& iter : container.destroy_list_) { auto entity_index = iter; pb_destroy_entity.mutable_entity_list()->insert({entity_index, NULL_GUID}); } data.mutable_destroy_entity()->insert({index, pb_destroy_entity}); return true; } bool AFCKernelModule::TryAddContainerPBEntity(std::shared_ptr<AFIContainer> pContainer, const guid_t& self, AFMsg::pb_entity_data& pb_entity_data, guid_t& parent_id, AFMsg::pb_entity_data*& pb_container_entity) { parent_id = pContainer->GetParentID(); auto pParentEntity = GetEntity(parent_id); if (pParentEntity == nullptr) { ARK_LOG_ERROR("parent entity do no exist, parent={}", parent_id); return false; } auto self_index = pContainer->Find(self); if (self_index == 0) { ARK_LOG_ERROR("entity is not in container, self={}", self); return false; } AFMsg::pb_container pb_container; auto result_container = pb_entity_data.mutable_datas_container()->insert({pContainer->GetIndex(), pb_container}); if (!result_container.second) { ARK_LOG_ERROR("entity insert container failed, self={} container index = {}", self, pContainer->GetIndex()); return false; } auto& container = result_container.first->second; AFMsg::pb_entity pb_entity; auto result_entity = container.mutable_datas_value()->insert({self_index, pb_entity}); if (!result_entity.second) { ARK_LOG_ERROR("container insert entity failed, self={} container index = {}", self, pContainer->GetIndex()); return false; } auto& entity = result_entity.first->second; pb_container_entity = entity.mutable_data(); return true; } int AFCKernelModule::SendSyncMsg(const guid_t& self, const ArkDataMask mask_value, const google::protobuf::Message& msg) { auto iter = sync_functors.find(mask_value); if (iter == sync_functors.end()) { return -1; } iter->second(self, msg); return 0; } int AFCKernelModule::SendToView(const guid_t& self, const google::protobuf::Message& msg) { auto pEntity = GetEntity(self); if (nullptr == pEntity) { return -1; } auto map_id = pEntity->GetMapID(); auto inst_id = pEntity->GetMapEntityID(); AFCDataList map_inst_entity_list; m_pMapModule->GetInstEntityList(map_id, inst_id, map_inst_entity_list); for (size_t i = 0; i < map_inst_entity_list.GetCount(); i++) { auto pViewEntity = GetEntity(map_inst_entity_list.Int64(i)); if (pViewEntity == nullptr) { continue; } const std::string& strObjClassName = pViewEntity->GetClassName(); if (AFEntityMetaPlayer::self_name() == strObjClassName) { SendToSelf(pViewEntity->GetID(), msg); } } return 0; } int AFCKernelModule::SendToSelf(const guid_t& self, const google::protobuf::Message& msg) { //SendMsgPBToGate(AFMsg::EGMI_ACK_NODE_DATA, entity, ident); return 0; } bool AFCKernelModule::DoEvent( const guid_t& self, const std::string& class_name, ArkEntityEvent class_event, const AFIDataList& args) { return m_pClassModule->DoClassEvent(self, class_name, class_event, args); } bool AFCKernelModule::DoEvent(const guid_t& self, const int event_id, const AFIDataList& args) { std::shared_ptr<AFIEntity> pEntity = GetEntity(self); ARK_ASSERT_RET_VAL(pEntity != nullptr, false); auto pEventManager = GetEventManager(pEntity); ARK_ASSERT_RET_VAL(pEventManager != nullptr, false); return pEventManager->DoEvent(event_id, args); } bool AFCKernelModule::Exist(const guid_t& self) { return (objects_.find_value(self) != nullptr); } bool AFCKernelModule::LogSelfInfo(const guid_t& id) { return false; } int AFCKernelModule::LogObjectData(const guid_t& guid) { auto entity = GetEntity(guid); if (entity == nullptr) { return -1; } auto pNodeManager = GetNodeManager(entity); ARK_ASSERT_RET_VAL(pNodeManager != nullptr, -1); auto pTableManager = GetTableManager(entity); ARK_ASSERT_RET_VAL(pTableManager != nullptr, -1); auto& node_list = pNodeManager->GetDataList(); for (auto& iter : node_list) { auto pData = iter.second; if (!pData) { continue; } ARK_LOG_TRACE("Player[{}] Node[{}] Value[{}]", guid, pData->GetName(), pData->ToString()); } auto& table_list = pTableManager->GetTableList(); for (auto& iter : table_list) { auto pTable = iter.second; if (!pTable) { continue; } for (auto pRow = pTable->First(); pRow != nullptr; pRow = pTable->Next()) { auto pRowNodeManager = GetNodeManager(pRow); if (!pRowNodeManager) { continue; } auto& row_data_list = pRowNodeManager->GetDataList(); for (auto& iter_row : row_data_list) { auto pNode = iter_row.second; if (!pNode) { continue; } ARK_LOG_TRACE("Player[{}] Table[{}] Row[{}] Col[{}] Value[{}]", guid, pTable->GetName(), pRow->GetRow(), pNode->GetName(), pNode->ToString()); } } } return 0; } bool AFCKernelModule::LogInfo(const guid_t& id) { std::shared_ptr<AFIEntity> pEntity = GetEntity(id); if (pEntity == nullptr) { ARK_LOG_ERROR("Cannot find entity, id = {}", id); return false; } if (m_pMapModule->IsInMapInstance(id)) { int map_id = pEntity->GetMapID(); ARK_LOG_INFO("----------child object list-------- , id = {} mapid = {}", id, map_id); AFCDataList entity_list; int online_count = m_pMapModule->GetMapOnlineList(map_id, entity_list); for (int i = 0; i < online_count; ++i) { guid_t target_entity_id = entity_list.Int64(i); ARK_LOG_INFO("id = {} mapid = {}", target_entity_id, map_id); } } else { ARK_LOG_INFO("---------print object start--------, id = {}", id); ARK_LOG_INFO("---------print object end--------, id = {}", id); } return true; } //--------------entity to pb db data------------------ bool AFCKernelModule::EntityToDBData(const guid_t& self, AFMsg::pb_db_entity& pb_data) { std::shared_ptr<AFIEntity> pEntity = GetEntity(self); return EntityToDBData(pEntity, pb_data); } bool AFCKernelModule::EntityToDBData(std::shared_ptr<AFIEntity> pEntity, AFMsg::pb_db_entity& pb_data) { ARK_ASSERT_RET_VAL(pEntity != nullptr, false); auto pNodeManager = GetNodeManager(pEntity); ARK_ASSERT_RET_VAL(pNodeManager != nullptr, false); auto pTableManager = GetTableManager(pEntity); ARK_ASSERT_RET_VAL(pTableManager != nullptr, false); auto pContainerManager = GetContainerManager(pEntity); ARK_ASSERT_RET_VAL(pContainerManager != nullptr, false); pb_data.set_id(pEntity->GetID()); pb_data.set_config_id(pEntity->GetConfigID()); pb_data.set_map_id(pEntity->GetMapID()); pb_data.set_map_inst_id(pEntity->GetMapEntityID()); pb_data.set_class_name(pEntity->GetClassName()); // node to db auto& node_list = pNodeManager->GetDataList(); for (auto& iter : node_list) { auto pNode = iter.second; if (!pNode) { continue; } if (!pNode->HaveMask(ArkDataMask::PF_SAVE)) { continue; } NodeToDBData(pNode, *pb_data.mutable_data()); } // table to db auto& table_list = pTableManager->GetTableList(); for (auto& iter : table_list) { auto pTable = iter.second; if (!pTable) { continue; } if (!pTable->HaveMask(ArkDataMask::PF_SAVE)) { continue; } AFMsg::pb_db_table pb_table; if (!TableToDBData(pTable, pb_table)) { continue; } pb_data.mutable_data()->mutable_datas_table()->insert({pTable->GetName(), pb_table}); } // container to db auto& container_list = pContainerManager->GetContainerList(); for (auto& iter : container_list) { auto pContainer = iter.second; if (!pContainer) { continue; } AFMsg::pb_db_container pb_container; for (auto index = pContainer->First(); index > 0; index = pContainer->Next()) { auto pSubEntity = pContainer->Find(index); if (!pSubEntity) { continue; } AFMsg::pb_db_entity pb_container_entity; if (!EntityToDBData(pSubEntity, pb_container_entity)) { continue; } pb_container.mutable_datas_value()->insert({index, pb_container_entity}); } if (pb_container.datas_value_size() > 0) { pb_data.mutable_data()->mutable_datas_entity()->insert({pContainer->GetName(), pb_container}); } } return true; } std::shared_ptr<AFIEntity> AFCKernelModule::CreateEntity(const AFMsg::pb_db_entity& pb_data) { auto entity_id = pb_data.id(); auto pEntity = GetEntity(entity_id); if (pEntity != nullptr) { ARK_LOG_ERROR("entity already exists, object = {}", entity_id); return nullptr; } const std::string& class_name = pb_data.class_name(); auto pClassMeta = m_pClassModule->FindMeta(class_name); if (nullptr == pClassMeta) { ARK_LOG_ERROR("There is no class meta, name = {}", class_name); return nullptr; } auto map_id = pb_data.map_id(); auto map_inst_id = pb_data.map_inst_id(); auto pMapInfo = m_pMapModule->GetMapInfo(map_id); if (pMapInfo == nullptr) { ARK_LOG_ERROR("There is no scene, scene = {}", map_id); return nullptr; } auto pCEntity = std::make_shared<AFCEntity>(pClassMeta, entity_id, NULL_INT, map_id, map_inst_id, AFCDataList()); pEntity = std::static_pointer_cast<AFIEntity>(pCEntity); objects_.insert(entity_id, pEntity); if (class_name == AFEntityMetaPlayer::self_name()) { pMapInfo->AddEntityToInstance(map_inst_id, entity_id, true); } //else if (class_name == AFEntityMetaPlayer::self_name()) // to do : npc type for now we do not have //{ //} // init data auto& pb_db_entity_data = pb_data.data(); // node data auto pNodeManager = pCEntity->GetNodeManager(); if (nullptr != pNodeManager) { DBDataToNode(pNodeManager, pb_db_entity_data); } // table data auto pTableManager = pCEntity->GetTableManager(); if (nullptr != pTableManager) { for (auto& iter : pb_db_entity_data.datas_table()) { DBDataToTable(pEntity, iter.first, iter.second); } } // container data for (auto& iter : pb_db_entity_data.datas_entity()) { DBDataToContainer(pEntity, iter.first, iter.second); } // todo : add new event? AFCDataList args; DoEvent(entity_id, class_name, ArkEntityEvent::ENTITY_EVT_PRE_LOAD_DATA, args); DoEvent(entity_id, class_name, ArkEntityEvent::ENTITY_EVT_LOAD_DATA, args); DoEvent(entity_id, class_name, ArkEntityEvent::ENTITY_EVT_PRE_EFFECT_DATA, args); DoEvent(entity_id, class_name, ArkEntityEvent::ENTITY_EVT_EFFECT_DATA, args); DoEvent(entity_id, class_name, ArkEntityEvent::ENTITY_EVT_POST_EFFECT_DATA, args); DoEvent(entity_id, class_name, ArkEntityEvent::ENTITY_EVT_DATA_FINISHED, args); return pEntity; } bool AFCKernelModule::SendCustomMessage(const guid_t& target, const uint32_t msg_id, const AFIDataList& args) { ARK_ASSERT_RET_VAL(Exist(target) && msg_id > 0, false); AFMsg::pb_custom_message custom_message; custom_message.set_message_id(msg_id); size_t count = args.GetCount(); for (size_t i = 0; i < count; i++) { auto data_type = args.GetType(i); switch (data_type) { case ark::ArkDataType::DT_BOOLEAN: custom_message.add_data_list()->set_bool_value(args.Bool(i)); break; case ark::ArkDataType::DT_INT32: custom_message.add_data_list()->set_int_value(args.Int(i)); break; case ark::ArkDataType::DT_UINT32: custom_message.add_data_list()->set_uint_value(args.UInt(i)); break; case ark::ArkDataType::DT_INT64: custom_message.add_data_list()->set_int64_value(args.Int64(i)); break; case ark::ArkDataType::DT_UINT64: custom_message.add_data_list()->set_uint64_value(args.UInt64(i)); break; case ark::ArkDataType::DT_FLOAT: custom_message.add_data_list()->set_float_value(args.Float(i)); break; case ark::ArkDataType::DT_DOUBLE: custom_message.add_data_list()->set_double_value(args.Double(i)); break; case ark::ArkDataType::DT_STRING: custom_message.add_data_list()->set_str_value(args.String(i)); break; default: break; } } // send message return true; } // pb table to entity table bool AFCKernelModule::DBDataToTable( std::shared_ptr<AFIEntity> pEntity, const std::string& name, const AFMsg::pb_db_table& pb_table) { auto pTable = pEntity->FindTable(name); ARK_ASSERT_RET_VAL(pTable != nullptr, false); auto pCTable = dynamic_cast<AFCTable*>(pTable); ARK_ASSERT_RET_VAL(pCTable != nullptr, false); for (auto& iter : pb_table.datas_value()) { auto row_index = iter.first; if (row_index == NULL_INT) { continue; } auto& pb_db_entity_data = iter.second; auto pRow = pCTable->CreateRow(row_index, AFCDataList()); if (pRow == nullptr) { continue; } auto pNodeManager = GetNodeManager(pRow); if (pNodeManager == nullptr) { continue; } DBDataToNode(pNodeManager, pb_db_entity_data); } return true; } bool AFCKernelModule::DBDataToContainer( std::shared_ptr<AFIEntity> pEntity, const std::string& name, const AFMsg::pb_db_container& pb_data) { auto pContainer = pEntity->FindContainer(name); if (nullptr == pContainer) { return false; } auto pCContainer = std::dynamic_pointer_cast<AFCContainer>(pContainer); if (nullptr == pCContainer) { return false; } for (auto& iter : pb_data.datas_value()) { auto pContainerEntity = CreateEntity(iter.second); if (nullptr == pContainerEntity) { continue; } pCContainer->InitEntityList(iter.first, pContainerEntity); } return true; } int AFCKernelModule::OnContainerCallBack(const guid_t& self, const uint32_t index, const ArkContainerOpType op_type, const uint32_t src_index, const uint32_t dest_index) { if (op_type == ArkContainerOpType::OP_DESTROY) { // destroy entity auto pEntity = GetEntity(self); ARK_ASSERT_RET_VAL(pEntity != nullptr, 0); auto pContainer = pEntity->FindContainer(index); ARK_ASSERT_RET_VAL(pContainer != nullptr, 0); auto pContainerEntity = pContainer->Find(src_index); ARK_ASSERT_RET_VAL(pContainerEntity != nullptr, 0); InnerDestroyEntity(pContainerEntity); } return 0; } bool AFCKernelModule::DBDataToNode( std::shared_ptr<AFNodeManager> pNodeManager, const AFMsg::pb_db_entity_data& pb_db_entity_data) { //bool data for (auto& iter : pb_db_entity_data.datas_bool()) { auto pNode = pNodeManager->CreateData(iter.first); if (pNode == nullptr) { continue; } pNode->SetBool(iter.second); } //int32 data for (auto& iter : pb_db_entity_data.datas_int32()) { auto pNode = pNodeManager->CreateData(iter.first); if (pNode == nullptr) { continue; } pNode->SetInt32(iter.second); } //uint32 data for (auto& iter : pb_db_entity_data.datas_uint32()) { auto pNode = pNodeManager->CreateData(iter.first); if (pNode == nullptr) { continue; } pNode->SetUInt32(iter.second); } //int64 data for (auto& iter : pb_db_entity_data.datas_int64()) { auto pNode = pNodeManager->CreateData(iter.first); if (pNode == nullptr) { continue; } pNode->SetInt64(iter.second); } //uint64 data for (auto& iter : pb_db_entity_data.datas_uint64()) { auto pNode = pNodeManager->CreateData(iter.first); if (pNode == nullptr) { continue; } pNode->SetUInt64(iter.second); } //float data for (auto& iter : pb_db_entity_data.datas_float()) { auto pNode = pNodeManager->CreateData(iter.first); if (pNode == nullptr) { continue; } pNode->SetFloat(iter.second); } //double data for (auto& iter : pb_db_entity_data.datas_double()) { auto pNode = pNodeManager->CreateData(iter.first); if (pNode == nullptr) { continue; } pNode->SetDouble(iter.second); } //string data for (auto& iter : pb_db_entity_data.datas_string()) { auto pNode = pNodeManager->CreateData(iter.first); if (pNode == nullptr) { continue; } pNode->SetString(iter.second); } return true; } //----------------------------- bool AFCKernelModule::NodeToDBData(AFINode* pNode, AFMsg::pb_db_entity_data& pb_data) { ARK_ASSERT_RET_VAL(pNode != nullptr, false); auto& name = pNode->GetName(); switch (pNode->GetType()) { case ArkDataType::DT_BOOLEAN: pb_data.mutable_datas_bool()->insert({name, pNode->GetBool()}); break; case ArkDataType::DT_INT32: pb_data.mutable_datas_int32()->insert({name, pNode->GetInt32()}); break; case ArkDataType::DT_UINT32: pb_data.mutable_datas_uint32()->insert({name, pNode->GetUInt32()}); break; case ArkDataType::DT_INT64: pb_data.mutable_datas_int64()->insert({name, pNode->GetInt64()}); break; case ArkDataType::DT_UINT64: pb_data.mutable_datas_uint64()->insert({name, pNode->GetUInt64()}); break; case ArkDataType::DT_FLOAT: pb_data.mutable_datas_float()->insert({name, pNode->GetFloat()}); break; case ArkDataType::DT_DOUBLE: pb_data.mutable_datas_double()->insert({name, pNode->GetDouble()}); break; case ArkDataType::DT_STRING: pb_data.mutable_datas_string()->insert({name, pNode->GetString()}); break; default: ARK_ASSERT_RET_VAL(0, false); break; } return true; } bool AFCKernelModule::TableToDBData(AFITable* pTable, AFMsg::pb_db_table& pb_data) { ARK_ASSERT_RET_VAL(pTable != nullptr, false); for (auto pRow = pTable->First(); pRow != nullptr; pRow = pTable->Next()) { auto pNodeManager = GetNodeManager(pRow); if (!pNodeManager) { continue; } AFMsg::pb_db_entity_data row_data; auto& data_list = pNodeManager->GetDataList(); for (auto& iter : data_list) { NodeToDBData(iter.second, row_data); } pb_data.mutable_datas_value()->insert({pRow->GetRow(), row_data}); } return true; } //----------entity to pb client data--------------- bool AFCKernelModule::NodeToPBData(AFINode* pNode, AFMsg::pb_entity_data* pb_data) { ARK_ASSERT_RET_VAL(pNode != nullptr && pb_data != nullptr, false); auto index = pNode->GetIndex(); switch (pNode->GetType()) { case ArkDataType::DT_BOOLEAN: pb_data->mutable_datas_bool()->insert({index, pNode->GetBool()}); break; case ArkDataType::DT_INT32: pb_data->mutable_datas_int32()->insert({index, pNode->GetInt32()}); break; case ArkDataType::DT_UINT32: pb_data->mutable_datas_uint32()->insert({index, pNode->GetUInt32()}); break; case ArkDataType::DT_INT64: pb_data->mutable_datas_int64()->insert({index, pNode->GetInt64()}); break; case ArkDataType::DT_UINT64: pb_data->mutable_datas_uint64()->insert({index, pNode->GetUInt64()}); break; case ArkDataType::DT_FLOAT: pb_data->mutable_datas_float()->insert({index, pNode->GetFloat()}); break; case ArkDataType::DT_DOUBLE: pb_data->mutable_datas_double()->insert({index, pNode->GetDouble()}); break; case ArkDataType::DT_STRING: pb_data->mutable_datas_string()->insert({index, pNode->GetString()}); break; default: ARK_ASSERT_RET_VAL(0, false); break; } return true; } bool AFCKernelModule::NodeToPBData(const uint32_t index, const AFIData& data, AFMsg::pb_entity_data* pb_data) { ARK_ASSERT_RET_VAL(index > 0 && pb_data != nullptr, false); switch (data.GetType()) { case ArkDataType::DT_BOOLEAN: pb_data->mutable_datas_bool()->insert({index, data.GetBool()}); break; case ArkDataType::DT_INT32: pb_data->mutable_datas_int32()->insert({index, data.GetInt()}); break; case ArkDataType::DT_UINT32: pb_data->mutable_datas_uint32()->insert({index, data.GetUInt()}); break; case ArkDataType::DT_INT64: pb_data->mutable_datas_int64()->insert({index, data.GetInt64()}); break; case ArkDataType::DT_UINT64: pb_data->mutable_datas_uint64()->insert({index, data.GetUInt64()}); break; case ArkDataType::DT_FLOAT: pb_data->mutable_datas_float()->insert({index, data.GetFloat()}); break; case ArkDataType::DT_DOUBLE: pb_data->mutable_datas_double()->insert({index, data.GetDouble()}); break; case ArkDataType::DT_STRING: pb_data->mutable_datas_string()->insert({index, data.GetString()}); break; default: ARK_ASSERT_RET_VAL(0, false); break; } return true; } bool AFCKernelModule::TableToPBData(AFITable* pTable, const uint32_t index, AFMsg::pb_table* pb_data) { ARK_ASSERT_RET_VAL(pTable != nullptr && index > 0 && pb_data != nullptr, false); for (AFIRow* pRow = pTable->First(); pRow != nullptr; pRow = pTable->Next()) { AFMsg::pb_entity_data row_data; if (!RowToPBData(pRow, pRow->GetRow(), &row_data)) { continue; } pb_data->mutable_datas_value()->insert({index, row_data}); } return true; } bool AFCKernelModule::ContainerToPBData(std::shared_ptr<AFIContainer> pContainer, AFMsg::pb_container* pb_data) { ARK_ASSERT_RET_VAL(pContainer != nullptr && pb_data != nullptr, false); for (auto index = pContainer->First(); index > 0; index = pContainer->Next()) { auto pEntity = pContainer->Find(index); if (nullptr == pEntity) { continue; } AFMsg::pb_entity pb_entity; if (!EntityToPBData(pEntity, &pb_entity)) { continue; } pb_data->mutable_datas_value()->insert({index, pb_entity}); } return true; } bool AFCKernelModule::RowToPBData(AFIRow* pRow, const uint32_t index, AFMsg::pb_entity_data* pb_data) { ARK_ASSERT_RET_VAL(pRow != nullptr && index > 0 && pb_data != nullptr, false); auto pNodeManager = GetNodeManager(pRow); if (!pNodeManager) { return false; } auto& data_list = pNodeManager->GetDataList(); for (auto& iter : data_list) { NodeToPBData(iter.second, pb_data); } return true; } bool AFCKernelModule::TableRowDataToPBData( const uint32_t index, uint32_t row, const uint32_t col, const AFIData& data, AFMsg::pb_entity_data* pb_data) { ARK_ASSERT_RET_VAL(index > 0 && row > 0 && col > 0 && pb_data != nullptr, false); AFMsg::pb_entity_data row_data; if (!NodeToPBData(col, data, &row_data)) { return false; } AFMsg::pb_table table_data; table_data.mutable_datas_value()->insert({row, row_data}); pb_data->mutable_datas_table()->insert({index, table_data}); return true; } bool AFCKernelModule::EntityToPBData(std::shared_ptr<AFIEntity> pEntity, AFMsg::pb_entity* pb_data) { ARK_ASSERT_RET_VAL(pEntity != nullptr && pb_data != nullptr, false); pb_data->set_id(pEntity->GetID()); EntityNodeToPBData(pEntity, pb_data->mutable_data()); EntityTableToPBData(pEntity, pb_data->mutable_data()); EntityContainerToPBData(pEntity, pb_data->mutable_data()); return true; } bool AFCKernelModule::EntityToPBDataByMask( std::shared_ptr<AFIEntity> pEntity, ArkMaskType mask, AFMsg::pb_entity* pb_data) { ARK_ASSERT_RET_VAL(pEntity != nullptr && pb_data != nullptr, false); pb_data->set_id(pEntity->GetID()); EntityNodeToPBData(pEntity, pb_data->mutable_data(), mask); EntityTableToPBData(pEntity, pb_data->mutable_data(), mask); EntityContainerToPBData(pEntity, pb_data->mutable_data(), mask); return true; } bool AFCKernelModule::EntityContainerToPBData( std::shared_ptr<AFIEntity> pEntity, AFMsg::pb_entity_data* pb_data, const ArkMaskType mask) { ARK_ASSERT_RET_VAL(pEntity != nullptr && pb_data != nullptr, false); auto pContainerManager = GetContainerManager(pEntity); ARK_ASSERT_RET_VAL(pContainerManager != nullptr, false); auto& container_list = pContainerManager->GetContainerList(); for (auto& iter : container_list) { auto pContainer = iter.second; if (!pContainer) { continue; } if (!mask.none()) { auto result = (pContainer->GetMask() & mask); if (!result.any()) { continue; } } AFMsg::pb_container pb_container; if (!ContainerToPBData(pContainer, &pb_container)) { continue; } pb_data->mutable_datas_container()->insert({iter.first, pb_container}); } return true; } //node all to pb data bool AFCKernelModule::EntityNodeToPBData( std::shared_ptr<AFIEntity> pEntity, AFMsg::pb_entity_data* pb_data, const ArkMaskType mask /* = 0*/) { ARK_ASSERT_RET_VAL(pEntity != nullptr && pb_data != nullptr, false); auto pNodeManager = GetNodeManager(pEntity); ARK_ASSERT_RET_VAL(pNodeManager != nullptr, false); auto& data_list = pNodeManager->GetDataList(); for (auto& iter : data_list) { auto pNode = iter.second; if (!pNode) { continue; } if (!mask.none()) { auto result = (pNode->GetMask() & mask); if (!result.any()) { continue; } } NodeToPBData(pNode, pb_data); } return true; } bool AFCKernelModule::EntityTableToPBData( std::shared_ptr<AFIEntity> pEntity, AFMsg::pb_entity_data* pb_data, const ArkMaskType mask /* = 0*/) { ARK_ASSERT_RET_VAL(pEntity != nullptr && pb_data != nullptr, false); auto pTableManager = GetTableManager(pEntity); ARK_ASSERT_RET_VAL(pTableManager != nullptr, false); auto& data_list = pTableManager->GetTableList(); for (auto& iter : data_list) { auto pTable = iter.second; if (!pTable) { continue; } if (!mask.none()) { auto result = (pTable->GetMask() & mask); if (!result.any()) { continue; } } const auto index = pTable->GetIndex(); AFMsg::pb_table table_data; if (!TableToPBData(pTable, index, &table_data)) { continue; } pb_data->mutable_datas_table()->insert({index, table_data}); } return true; } // -----------get entity manager-------------- std::shared_ptr<AFNodeManager> AFCKernelModule::GetNodeManager(std::shared_ptr<AFIStaticEntity> pStaticEntity) const { if (pStaticEntity == nullptr) { return nullptr; } auto pCStaticEntity = std::dynamic_pointer_cast<AFCStaticEntity>(pStaticEntity); if (pCStaticEntity == nullptr) { return nullptr; } return pCStaticEntity->GetNodeManager(); } std::shared_ptr<AFNodeManager> AFCKernelModule::GetNodeManager(std::shared_ptr<AFIEntity> pEntity) const { if (pEntity == nullptr) { return nullptr; } auto pCEnity = std::dynamic_pointer_cast<AFCEntity>(pEntity); if (pCEnity == nullptr) { return nullptr; } return pCEnity->GetNodeManager(); } std::shared_ptr<AFNodeManager> AFCKernelModule::GetNodeManager(AFIRow* pRow) const { if (pRow == nullptr) { return nullptr; } auto pCRow = dynamic_cast<AFCRow*>(pRow); if (pCRow == nullptr) { return nullptr; } return pCRow->GetNodeManager(); } std::shared_ptr<AFTableManager> AFCKernelModule::GetTableManager(std::shared_ptr<AFIEntity> pEntity) const { if (pEntity == nullptr) { return nullptr; } auto pCEnity = std::dynamic_pointer_cast<AFCEntity>(pEntity); if (pCEnity == nullptr) { return nullptr; } return pCEnity->GetTableManager(); } std::shared_ptr<AFIContainerManager> AFCKernelModule::GetContainerManager(std::shared_ptr<AFIEntity> pEntity) const { if (pEntity == nullptr) { return nullptr; } auto pCEnity = std::dynamic_pointer_cast<AFCEntity>(pEntity); if (pCEnity == nullptr) { return nullptr; } return pCEnity->GetContainerManager(); } std::shared_ptr<AFIEventManager> AFCKernelModule::GetEventManager(std::shared_ptr<AFIEntity> pEntity) const { if (pEntity == nullptr) { return nullptr; } auto pCEnity = std::dynamic_pointer_cast<AFCEntity>(pEntity); if (pCEnity == nullptr) { return nullptr; } return pCEnity->GetEventManager(); } } // namespace ark
28.725101
120
0.643259
ArkGame
1d10590f67240a9e3501b73e806bb57d339aeb08
574
cpp
C++
UnitTest/OpenToolTest.cpp
Neuromancer2701/OpenTool
b109e1d798fcca92f23b12e1bb5de898361641a4
[ "Apache-2.0" ]
1
2017-08-30T05:59:47.000Z
2017-08-30T05:59:47.000Z
UnitTest/OpenToolTest.cpp
Neuromancer2701/OpenTool
b109e1d798fcca92f23b12e1bb5de898361641a4
[ "Apache-2.0" ]
null
null
null
UnitTest/OpenToolTest.cpp
Neuromancer2701/OpenTool
b109e1d798fcca92f23b12e1bb5de898361641a4
[ "Apache-2.0" ]
null
null
null
//============================================================================ // Name : OpenToolTest.cpp // Author : // Version : // Copyright : // Description : Hello World in C++, Ansi-style //============================================================================ #include "Server.h" #include "Timer.h" #include <unistd.h> #include <iostream> using namespace std; int main() { bool listening = true; cout << "This is a Test." << endl; Server Test_Server(12000); while(listening) { sleep(1); //Test.Available(); } return 0; }
17.393939
78
0.439024
Neuromancer2701
1d117be860a84dc612994f2ead8819ad6300b505
6,885
cpp
C++
src/cli.cpp
CynusW/pg-fetch
bbcd639dbdc67e94f8b02c99b267a12b24300465
[ "MIT" ]
1
2020-04-16T15:10:20.000Z
2020-04-16T15:10:20.000Z
src/cli.cpp
CynusW/pg-fetch
bbcd639dbdc67e94f8b02c99b267a12b24300465
[ "MIT" ]
null
null
null
src/cli.cpp
CynusW/pg-fetch
bbcd639dbdc67e94f8b02c99b267a12b24300465
[ "MIT" ]
null
null
null
#include "pgf/cli.hpp" #include "pgf/util.hpp" #include <cassert> namespace pgf { CommandOptionValue::CommandOptionValue(const CommandOptionValueType& type) : type(type) { switch (type) { case CommandOptionValueType::Int: data = 0; break; case CommandOptionValueType::String: data = std::string(); break; case CommandOptionValueType::Bool: default: data = false; break; } } void CommandOptions::AddOption(const std::string& name, char shortName, const CommandOptionValueType& type) { m_options.push_back(CommandOptionName{ name, shortName }); m_values.push_back(CommandOptionValue{ type }); } std::vector<CommandOptionValue>::iterator CommandOptions::FindOptionValue(const std::string& name) { if (name.empty()) return m_values.end(); unsigned int index = 0; while (index < m_options.size()) { const auto& opt = m_options[index]; if (opt.name == name) break; ++index; } return m_values.begin() + index; } std::vector<CommandOptionValue>::const_iterator CommandOptions::FindOptionValue(const std::string& name) const { if (name.empty()) return m_values.end(); unsigned int index = 0; while (index < m_options.size()) { const auto& opt = m_options[index++]; if (opt.name == name) break; } return m_values.begin() + index; } std::vector<CommandOptionValue>::iterator CommandOptions::FindOptionValue(char name) { unsigned int index = 0; while (index < m_options.size()) { const auto& opt = m_options[index]; if (opt.shortName == name) break; ++index; } return m_values.begin() + index; } std::vector<CommandOptionValue>::const_iterator CommandOptions::FindOptionValue(char name) const { unsigned int index = 0; while (index < m_options.size()) { const auto& opt = m_options[index]; if (opt.shortName == name) break; ++index; } return m_values.begin() + index; } bool CommandOptions::HasOption(const std::string& name) { return std::find_if( m_options.begin(), m_options.end(), [&name](const CommandOptionName& opt) { return opt.name == name; } ) != m_options.end(); } bool CommandOptions::HasOption(char name) { return std::find_if( m_options.begin(), m_options.end(), [&name](const CommandOptionName& opt) { return opt.shortName == name; } ) != m_options.end(); } void CommandOptions::SetOptionValue(const std::string& name, bool value) { auto optValue = this->FindOptionValue(name); if (optValue == m_values.end()) return; if (optValue->type != CommandOptionValueType::Bool) return; optValue->data = value; } void CommandOptions::SetOptionValue(const std::string& name, int value) { auto optValue = this->FindOptionValue(name); if (optValue == m_values.end()) return; if (optValue->type != CommandOptionValueType::Int) return; optValue->data = value; } void CommandOptions::SetOptionValue(const std::string& name, const std::string& value) { auto optValue = this->FindOptionValue(name); if (optValue == m_values.end()) return; if (optValue->type != CommandOptionValueType::String) return; optValue->data = value; } void CommandOptions::ProcessArguments(std::vector<std::string>& args) { for (unsigned int i = 0; i < args.size(); ++i) { std::string arg = args[i]; if (util::StartsWith(arg, "--")) { arg = util::ToLower(arg.substr(2)); if (!HasOption(arg)) { continue; } auto optValue = this->FindOptionValue(arg); if (optValue == m_values.end()) continue; switch (optValue->type) { case CommandOptionValueType::String: if (i + 1 < args.size()) { optValue->data = args[i + 1]; args.erase(args.begin() + i + 1); } break; case CommandOptionValueType::Int: if (i + 1 < args.size()) { optValue->data = std::stoi(args[i + 1]); args.erase(args.begin() + i + 1); } break; case CommandOptionValueType::Bool: default: optValue->data = true; break; } args.erase(args.begin() + (i--)); } else if (util::StartsWith(arg, "-")) { arg = util::ToLower(arg.substr(1)); for (char c : arg) { if (!HasOption(c)) continue; auto optValue = this->FindOptionValue(c); if (optValue == m_values.end()) continue; switch (optValue->type) { case CommandOptionValueType::String: if (i + 1 < args.size()) { optValue->data = args[i + 1]; args.erase(args.begin() + i + 1); } break; case CommandOptionValueType::Int: if (i + 1 < args.size()) { optValue->data = std::stoi(args[i + 1]); args.erase(args.begin() + i + 1); } break; case CommandOptionValueType::Bool: default: optValue->data = true; break; } } args.erase(args.begin() + (i--)); } } } }
28.6875
114
0.444735
CynusW
1d12265999bf15a69bf71cd08842c9fa6a5943cb
4,741
cpp
C++
src/dialog/PriceHistory.cpp
captain-igloo/greenthumb
39d62004e6f6b6fa7da52b3f6ff1c198b04e1d72
[ "MIT" ]
3
2019-04-08T19:17:51.000Z
2019-05-21T01:01:29.000Z
src/dialog/PriceHistory.cpp
captain-igloo/greenthumb
39d62004e6f6b6fa7da52b3f6ff1c198b04e1d72
[ "MIT" ]
1
2019-04-30T23:39:06.000Z
2019-07-27T00:07:20.000Z
src/dialog/PriceHistory.cpp
captain-igloo/greenthumb
39d62004e6f6b6fa7da52b3f6ff1c198b04e1d72
[ "MIT" ]
1
2019-02-28T09:22:18.000Z
2019-02-28T09:22:18.000Z
/** * Copyright 2020 Colin Doig. Distributed under the MIT license. */ #include <wx/wx.h> #include <wx/dcclient.h> #include <wx/dcmemory.h> #include <wx/file.h> #include <wx/sizer.h> #include <wx/mstream.h> #include <wx/stdpaths.h> #include <wx/stattext.h> #include <wx/wfstream.h> #include <wx/url.h> #include <curl/curl.h> #include <iomanip> #include <iostream> #include <sstream> #include <greentop/ExchangeApi.h> #include "dialog/PriceHistory.h" #include "Util.h" namespace greenthumb { namespace dialog { size_t writeToStream(char* buffer, size_t size, size_t nitems, wxMemoryOutputStream* stream) { size_t realwrote = size * nitems; stream->Write(buffer, realwrote); return realwrote; } PriceHistory::PriceHistory(wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &pos, const wxSize &size, long style, const wxString &name) : wxDialog(parent, id, title, pos, size, style, name) { int borderWidth = 10; int borderFlags = wxTOP | wxRIGHT | wxLEFT; wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL); wxFlexGridSizer* gridSizer = new wxFlexGridSizer(2, borderWidth, borderWidth); wxStaticText* bettingOnLabel = new wxStaticText(this, wxID_ANY, "Betting on:"); gridSizer->Add(bettingOnLabel); bettingOn = new wxStaticText(this, wxID_ANY, ""); gridSizer->Add(bettingOn); wxStaticText* lastPriceTradedLabel = new wxStaticText(this, wxID_ANY, "Last price matched:"); gridSizer->Add(lastPriceTradedLabel); lastPriceTraded = new wxStaticText(this, wxID_ANY, ""); gridSizer->Add(lastPriceTraded); vbox->Add(gridSizer, 0, borderFlags, borderWidth); chartPanel = new ImagePanel( this, wxID_ANY, wxDefaultPosition, wxSize(CHART_WIDTH, CHART_HEIGHT), wxSUNKEN_BORDER ); vbox->Add(chartPanel, 0, borderFlags, borderWidth); wxSizer* buttonSizer = CreateButtonSizer(wxCLOSE); if (buttonSizer) { vbox->Add(buttonSizer, 0, wxTOP | wxBOTTOM | wxALIGN_RIGHT, borderWidth); } SetSizer(vbox); vbox->Fit(this); Bind(wxEVT_BUTTON, &PriceHistory::OnClose, this, wxID_CLOSE); } void PriceHistory::SetLastPriceTraded(const double lastPriceTraded) { if (lastPriceTraded > 0) { std::ostringstream lastPriceStream; lastPriceStream << std::fixed << std::setprecision(2) << lastPriceTraded; wxString label((lastPriceStream.str()).c_str(), wxConvUTF8); this->lastPriceTraded->SetLabel(label); } } void PriceHistory::SetRunner(const entity::Market& market, const greentop::sport::Runner& runner) { if (market.HasRunner(runner.getSelectionId())) { greentop::sport::RunnerCatalog rc = market.GetRunner(runner.getSelectionId()); std::string runnerName = rc.getRunnerName(); if (runner.getHandicap().isValid()) { runnerName = runnerName + " " + wxString::Format(wxT("%.1f"), runner.getHandicap().getValue()); } bettingOn->SetLabel( GetSelectionName(market.GetMarketCatalogue(), rc, runner.getHandicap()) ); } LoadChart(market, runner); } void PriceHistory::LoadChart( const entity::Market& market, const greentop::sport::Runner& runner ) { wxString marketId(market.GetMarketCatalogue().getMarketId().substr(2)); std::ostringstream oStream; oStream << runner.getSelectionId().getValue(); wxString selectionId = oStream.str(); wxString handicap = "0"; greentop::Optional<double> optionalHandicap = runner.getHandicap(); if (optionalHandicap.isValid()) { std::ostringstream handicapStream; handicapStream << optionalHandicap.getValue(); handicap = handicapStream.str(); } wxString chartUrl = "https://xtsd.betfair.com/LoadRunnerInfoChartAction/?marketId=" + market.GetMarketCatalogue().getMarketId().substr(2) + "&selectionId=" + selectionId + "&handicap=" + handicap; curl_global_init(CURL_GLOBAL_DEFAULT); CURL* curl = curl_easy_init(); if (curl) { wxMemoryOutputStream out; curl_easy_setopt(curl, CURLOPT_URL, static_cast<const char*>(chartUrl.c_str())); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeToStream); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out); CURLcode res = curl_easy_perform(curl); if (res == CURLE_OK) { wxMemoryInputStream in(out); wxImage image(in, wxBITMAP_TYPE_JPEG); wxBitmap chart = wxBitmap(image); chartPanel->SetBitmap(chart); } curl_easy_cleanup(curl); } curl_global_cleanup(); } void PriceHistory::OnClose(wxCommandEvent& event) { EndModal(wxID_OK); } } }
31.606667
99
0.674119
captain-igloo
1d131892aa907fe7c6c9b8a43c537b45deac968d
382
hpp
C++
include/locic/Support/Hasher.hpp
scross99/locic
a24bb380e17f8af69e7389acf8ce354c91a2abf3
[ "MIT" ]
80
2015-02-19T21:38:57.000Z
2016-05-25T06:53:12.000Z
include/locic/Support/Hasher.hpp
scross99/locic
a24bb380e17f8af69e7389acf8ce354c91a2abf3
[ "MIT" ]
8
2015-02-20T09:47:20.000Z
2015-11-13T07:49:17.000Z
include/locic/Support/Hasher.hpp
scross99/locic
a24bb380e17f8af69e7389acf8ce354c91a2abf3
[ "MIT" ]
6
2015-02-20T11:26:19.000Z
2016-04-13T14:30:39.000Z
#ifndef LOCIC_SUPPORT_HASHER_HPP #define LOCIC_SUPPORT_HASHER_HPP #include <cstddef> #include <locic/Support/Hash.hpp> namespace locic{ class Hasher { public: Hasher(); void addValue(size_t value); template <typename T> void add(const T& object) { addValue(hashObject<T>(object)); } size_t get() const; private: size_t seed_; }; } #endif
12.322581
35
0.675393
scross99
1d14c8e3d86aa27baf03d1b5648d2047ed72ea52
3,198
hpp
C++
orca_topside/include/orca_topside/topside_widget.hpp
clydemcqueen/orca3
283a5c193948021cd4f6d75f97be9032e0703ad7
[ "MIT" ]
31
2020-11-23T17:26:36.000Z
2022-03-07T09:46:20.000Z
orca_topside/include/orca_topside/topside_widget.hpp
clydemcqueen/orca3
283a5c193948021cd4f6d75f97be9032e0703ad7
[ "MIT" ]
6
2021-04-29T17:47:31.000Z
2022-02-24T17:10:00.000Z
orca_topside/include/orca_topside/topside_widget.hpp
clydemcqueen/orca3
283a5c193948021cd4f6d75f97be9032e0703ad7
[ "MIT" ]
11
2021-02-12T12:16:05.000Z
2022-02-10T11:18:47.000Z
// MIT License // // Copyright (c) 2021 Clyde McQueen // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #ifndef ORCA_TOPSIDE__TOPSIDE_WIDGET_HPP_ #define ORCA_TOPSIDE__TOPSIDE_WIDGET_HPP_ #include <QBoxLayout> #include <QWidget> #include "orca_topside/video_pipeline.hpp" QT_BEGIN_NAMESPACE class QLabel; QT_END_NAMESPACE namespace orca_topside { class TeleopNode; class TopsideLayout; class TopsideWidget : public QWidget { Q_OBJECT public: explicit TopsideWidget(std::shared_ptr<TeleopNode> node, QWidget *parent = nullptr); void about_to_quit(); void set_armed(bool armed); void set_hold(bool enabled); void set_tilt(int tilt); void set_depth(double target, double actual); void set_lights(int lights); void set_status(uint32_t status, double voltage); void set_trim_x(double v); void set_trim_y(double v); void set_trim_z(double v); void set_trim_yaw(double v); static void update_pipeline(const std::shared_ptr<VideoPipeline> & pipeline, QLabel *label, const char *prefix); void update_pipeline_f() { update_pipeline(video_pipeline_f_, pipeline_f_label_, "F"); } void update_pipeline_l() { update_pipeline(video_pipeline_l_, pipeline_l_label_, "L"); } void update_pipeline_r() { update_pipeline(video_pipeline_r_, pipeline_r_label_, "R"); } protected: void closeEvent(QCloseEvent *event) override; void keyPressEvent(QKeyEvent *event) override; private slots: void update_fps(); private: std::shared_ptr<TeleopNode> node_; std::shared_ptr<VideoPipeline> video_pipeline_f_; std::shared_ptr<VideoPipeline> video_pipeline_l_; std::shared_ptr<VideoPipeline> video_pipeline_r_; GstWidget *gst_widget_f_; GstWidget *gst_widget_l_; GstWidget *gst_widget_r_; TopsideLayout *cam_layout_; QLabel *armed_label_; QLabel *hold_label_; QLabel *depth_label_; QLabel *lights_label_; QLabel *pipeline_f_label_; QLabel *pipeline_l_label_; QLabel *pipeline_r_label_; QLabel *status_label_; QLabel *tilt_label_; QLabel *trim_x_label_; QLabel *trim_y_label_; QLabel *trim_z_label_; QLabel *trim_yaw_label_; }; } // namespace orca_topside #endif // ORCA_TOPSIDE__TOPSIDE_WIDGET_HPP_
30.169811
93
0.772358
clydemcqueen
1d1a805f6372f1eca7b7c40773034606e218253a
8,602
cpp
C++
sources/GS_CO_0.3/main.cpp
Jazzzy/GS_CO_FirstOpenGLProject
4048b15fdc75ecf826258c1193bb6da2f2b28e7a
[ "Apache-2.0" ]
null
null
null
sources/GS_CO_0.3/main.cpp
Jazzzy/GS_CO_FirstOpenGLProject
4048b15fdc75ecf826258c1193bb6da2f2b28e7a
[ "Apache-2.0" ]
null
null
null
sources/GS_CO_0.3/main.cpp
Jazzzy/GS_CO_FirstOpenGLProject
4048b15fdc75ecf826258c1193bb6da2f2b28e7a
[ "Apache-2.0" ]
null
null
null
#pragma once #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cmath> #include <Windows.h> #include "Camara.h" #include "objLoader.h" #include "player.h" #include "Luz.h" #include "hud.h" #include "mundo.h" #include "colisiones.h" #include <conio.h> #include <stdlib.h> #include <al\al.h> #include <al\alc.h> #include "sound.h" //#include <al\alu.h> //#include <al\alut.h> using namespace std; void Display(); void Reshape(int w, int h); void Keyboard(unsigned char key, int x, int y); void KeyboardUp(unsigned char key, int x, int y); void MueveRaton(int x, int y); void PulsaRaton(int button, int state, int x, int y); void Timer(int value); void Idle(); void Iniciar(); void Malla(); void update(int value); void updatePlayer(int value); void chase(int value); bool endGame = false; bool g_key[256] = {false}; bool g_shift_down = false; bool g_fps_mode = true; int g_viewport_width = 1240; int g_viewport_height = 720; int bang_g_viewport_width = 1240; int bang_g_viewport_height = 720; bool g_mouse_left_down = false; bool g_mouse_right_down = false; // Movement settings const float velMov = 0.1; const float g_rotation_speed = M_PI / 180 * 0.1; const float velAc = 0.0075; const float velDec = -0.0025; //Player Player *player; objloader *cargador; GLuint suelo; int caja; int test; //Light Luz *luz; GLfloat LuzPos[] = { 0.0f, 200.0f, 0.0f, 1.0f }; GLfloat SpotDir[] = { 0.0f, -200.0f, 0.0f }; //World Mundo *mundo; int dificultad = 1; vector<Ball*> _ranas; vector<Box*> _cajas; float _timeUntilUpdate = 0; float _timeUntilUpdatePlayer = 0; //Frogs int chaseNum = 0; //Sound sound *audio; //HUD char msg[50]; char datosHud[50]; int bangCounter = 0; char *bang; char bang1[10] = "BANG!!"; char bang2[10] = "PIUM!!"; char bang3[10] = "PUM!!"; char bang4[10] = "PAYUM!!"; /* */ int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowSize(1240, 720); glutCreateWindow("Global Strike: Counter Offensive"); glutIgnoreKeyRepeat(1); glutDisplayFunc(Display); glutIdleFunc(Display); glutReshapeFunc(Reshape); glutMouseFunc(PulsaRaton); glutMotionFunc(MueveRaton); glutPassiveMotionFunc(MueveRaton); glutKeyboardFunc(Keyboard); glutKeyboardUpFunc(KeyboardUp); glutIdleFunc(Idle); Iniciar(); glutTimerFunc(TIMER_MS, update, 0); glutTimerFunc(TIMER_MS, updatePlayer, 0); glutTimerFunc(3000, chase, chaseNum); glutTimerFunc(1, Timer, 0); glutMainLoop(); return 0; } void Iniciar(){ audio = new sound; GLfloat Ambient[] = { 1.0f, 1.0f, 1.0f, 1.0f }; GLfloat Diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f }; GLfloat SpecRef[] = { 1.0f, 1.0f, 1.0f, 1.0f }; GLfloat Specular[] = { 1.0f, 1.0f, 1.0f, 1.0f }; printf("\n\n*_*_*_*_*_*_*_*_*_*_*_*_WELCOME TO FROGZ_*_*_*_*_*_*_*_*_*_*_*_*\n\n"); printf("Inserte dificultad:\n\n\tTest: 0\n\n\tFacil: 1\n\n\tNormalillo: 2\n\n\tRanas Astronautas: 3\n"); do{ scanf(" %d", &dificultad); } while (dificultad != 1 && dificultad != 2 && dificultad != 0 && dificultad != 3); mundo = new Mundo(audio,dificultad); player = new Player(mundo,audio); glEnable(GL_TEXTURE_2D); glEnable(GL_SMOOTH); glShadeModel(GL_SMOOTH); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_NORMALIZE); // Ilumination luz = new Luz(); glutSetCursor(GLUT_CURSOR_NONE); } void Reshape(int w, int h) { g_viewport_width = w; g_viewport_height = h; glViewport(0, 0, (GLsizei)w, (GLsizei)h); //set the viewport to the current window specifications glMatrixMode(GL_PROJECTION); //set the matrix to projection glLoadIdentity(); gluPerspective(60, (GLfloat)w / (GLfloat)h, 0.1, 100.0); //set the perspective (angle of sight, width, height, ,depth) glMatrixMode(GL_MODELVIEW); //set the matrix back to model } void Keyboard(unsigned char key, int x, int y) { if (key == 27) { exit(0); } if (key == 'p') { g_fps_mode = !g_fps_mode; if (g_fps_mode) { glutSetCursor(GLUT_CURSOR_NONE); glutWarpPointer(g_viewport_width / 2, g_viewport_height / 2); } else { glutSetCursor(GLUT_CURSOR_LEFT_ARROW); } } if (glutGetModifiers() == GLUT_ACTIVE_SHIFT) { g_shift_down = true; } else { g_shift_down = false; } if (key == 'r' || key == 'R'){ player->Recargar(); } g_key[key] = true; } void KeyboardUp(unsigned char key, int x, int y) { g_key[key] = false; } void Timer(int value) { if (g_fps_mode) { if (g_key['w'] || g_key['W']) { player->Acelerar(velAc); } else if (g_key['s'] || g_key['S']) { player->Acelerar(-velAc); } else if (!g_key['w'] && !g_key['W'] && !g_key['s'] && !g_key['S']){ player->Decelerar(velDec); } if (g_key['a'] || g_key['A']) { player->AcelerarHorizontal(velAc); } else if (g_key['d'] || g_key['D']) { player->AcelerarHorizontal(-velAc); } else if (!g_key['a'] && !g_key['A'] && !g_key['d'] && !g_key['D']){ player->DecelerarHorizontal(velDec); } } glutTimerFunc(1, Timer, 0); } void Idle() { Display(); } void PulsaRaton(int button, int state, int x, int y) { if (state == GLUT_DOWN) { if (button == GLUT_LEFT_BUTTON) { if (g_fps_mode){ g_mouse_left_down = true; player->Disparo(); bangCounter = 40; switch (rand() % 4){ case 0: bang = bang1; break; case 1: bang = bang2; break; case 2: bang = bang3; break; case 3: bang = bang4; break; } bang_g_viewport_width = (rand() % (g_viewport_width - 200)) + 100; bang_g_viewport_height = (rand() % (g_viewport_height - 100)) + 50; } } else if (button == GLUT_RIGHT_BUTTON) { g_mouse_right_down = true; } } else if (state == GLUT_UP) { if (button == GLUT_LEFT_BUTTON) { g_mouse_left_down = false; } else if (button == GLUT_RIGHT_BUTTON) { g_mouse_right_down = false; } } } void MueveRaton(int x, int y) { static bool just_warped = false; if (just_warped) { just_warped = false; return; } if (g_fps_mode) { int dx = x - g_viewport_width / 2; int dy = y - g_viewport_height / 2; if (dx) { player->RotarHorizontal(g_rotation_speed*dx); } if (dy) { player->RotarVertical(g_rotation_speed*dy); } glutWarpPointer(g_viewport_width / 2, g_viewport_height / 2); just_warped = true; } } void Display(void) { glClearColor(0.0, 0.0, 0.0, 1.0); //clear the screen to black glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //clear the color buffer and the depth buffer glMatrixMode(GL_PROJECTION); //set the matrix to projection glLoadIdentity(); gluPerspective(60, (GLfloat)g_viewport_width / (GLfloat)g_viewport_height, 0.1, 200.0); //set the perspective (angle of sight, width, height, ,depth) glMatrixMode(GL_MODELVIEW); //set the matrix back to model glLoadIdentity(); if (endGame){ mundo->end(); exit(0); } //Camera Position player->Refresh(g_fps_mode); //Light luz->refresh(LuzPos,SpotDir); //World mundo->dibujarMundoEstatico(); mundo->dibujarMundoDinamico(); //Weapon if (g_fps_mode){ player->dibujaArma(); } else{ player->dibujarModelo(); } //HUD sprintf(msg, "Ranas restantes: [%d]", mundo->getRanas().size()); sprintf(datosHud,"Vida: [%d] Balas: [%d]",player->getVida(),player->getBalas()); hud(msg, g_viewport_width, g_viewport_height,5,20); hud(datosHud, g_viewport_width, g_viewport_height, g_viewport_width -400 , g_viewport_height-20); if (player->getBalas() > 0){ if (bangCounter > 0){ bangCounter--; hudBang(bang, g_viewport_width, g_viewport_height, bang_g_viewport_width, bang_g_viewport_height); } } if ((mundo->getRanas().size() <= 0 && dificultad!=0) || player->getVida()<= 0){ fin(g_viewport_width, g_viewport_height); Sleep(500); endGame = true; } glutSwapBuffers(); //swap the buffers } void update(int value) { if (g_fps_mode){ _ranas = mundo->getRanas(); _cajas = mundo->getCajas(); advance(_ranas, _cajas, (float)TIMER_MS / 1000.0f, _timeUntilUpdatePlayer, mundo,(dificultad!=3)); glutPostRedisplay(); } glutTimerFunc(TIMER_MS, update, 0); } void updatePlayer(int value) { if (g_fps_mode){ _ranas = mundo->getRanas(); _cajas = mundo->getCajas(); advancePlayer(player->hitball, player, _ranas, _cajas, (float)TIMER_MS / 1000.0f, _timeUntilUpdatePlayer); glutPostRedisplay(); } glutTimerFunc(1, updatePlayer, 0); } void chase(int value) { if (g_fps_mode){ _ranas = mundo->getRanas(); chasePlayer(player->hitball, player, _ranas, chaseNum); chaseNum++; if (chaseNum >= numRanas){ chaseNum = 0; } glutPostRedisplay(); } glutTimerFunc(500, chase, 0); }
19.461538
150
0.666008
Jazzzy
1d1e65eb821351186e10c0160fe1b1419c21d2bc
3,786
cpp
C++
codeforces/1288f.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
1
2020-04-04T14:56:12.000Z
2020-04-04T14:56:12.000Z
codeforces/1288f.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
codeforces/1288f.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct MCMF { using F = int; const static F INF = 0x3f3f3f3f; // using F = long long; const static F INF = 0x3f3f3f3f3f3f3f3f; struct Edge { int v, bro; F cap, cost; Edge() {} Edge(int _v, int _bro, F _cap, F _cost) : v(_v), bro(_bro), cap(_cap), cost(_cost) {} }; vector<Edge> e; vector<int> pos, pre; vector<F> dis; vector<bool> trk; int n, s, t, m; MCMF(int _n, int _s, int _t) : n(_n), s(_s), t(_t), m(0) { pos.assign(n, -1); pre.resize(n); dis.resize(n); trk.resize(n); e.reserve(4e5); } void add(int u, int v, F cap = INF, F cost = 0) { assert(u < n && v < n); e.emplace_back(v, pos[u], cap, cost); pos[u] = m++; e.emplace_back(u, pos[v], 0, -cost); pos[v] = m++; } bool spfa() { queue<int> q; fill(pre.begin(), pre.end(), -1); fill(dis.begin(), dis.end(), INF); fill(trk.begin(), trk.end(), false); dis[s] = 0; trk[s] = true; q.push(s); while(!q.empty()){ int u = q.front(); q.pop(); trk[u] = false; for (int i = pos[u]; i != -1; i = e[i].bro){ int v = e[i].v; if (e[i].cap > 0 && dis[v] > dis[u] + e[i].cost){ dis[v] = dis[u] + e[i].cost; pre[v] = i; if (!trk[v]){ trk[v] = true; q.push(v); } } } } return pre[t] != -1; } pair<F,F> mcmf() { F flow = 0, cost = 0; while (spfa()) { // (dijkstra()) { // don't need max-flow, but min cost. require each push at least -COST if (dis[t] >= 0) break; F f = INF; for (int i = pre[t]; i != -1; i = pre[e[i^1].v]) f = min(f, e[i].cap); for (int i = pre[t]; i != -1; i = pre[e[i^1].v]){ e[i].cap -= f; e[i^1].cap += f; cost += e[i].cost * f; } flow += f; } return {flow, cost}; } }; void solve() { int n1,n2,m,r,b; cin >> n1 >> n2 >> m >> r >> b; string s1,s2; cin >> s1 >> s2; int S = n1+n2, T = S + 1; MCMF g(T+1, S, T); for (int _ = 0; _ < m; _++) { int x,y; cin >> x >> y; x--;y--; y+=n1; g.add(x, y, 1, r); g.add(y, x, 1, b); } int cnt = 0; const int CAP = 2*m; const int COST = 100005; for (int i = 0; i < n1; i++) { if (s1[i] == 'R') { g.add(S, i, 1, -COST); g.add(S, i, CAP); cnt++; } else if (s1[i] == 'B') { g.add(i, T, 1, -COST); g.add(i, T, CAP); cnt++; } else { g.add(S, i, CAP); g.add(i, T, CAP); } } for (int i = 0; i < n2; i++) { int k = i + n1; if (s2[i] == 'B') { g.add(S, k, 1, -COST); g.add(S, k, CAP); cnt++; } else if (s2[i] == 'R') { g.add(k, T, 1, -COST); g.add(k, T, CAP); cnt++; } else { g.add(S, k, CAP); g.add(k, T, CAP); } } int flow,cost; tie(flow,cost) = g.mcmf(); cost += cnt * COST; if (cost >= COST) { cout << -1; return; } cout << cost << "\n"; for (int i = 0; i < m; i++) { if (g.e[i*4 + 1].cap) { cout << 'R'; } else if (g.e[i*4 + 3].cap) { cout << 'B'; } else { cout << 'U'; } } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); return 0; }
26.851064
93
0.368727
sogapalag
1d20c2d41c5beddc32aea4e0a322fc051891a8da
2,800
cpp
C++
Engine/Source/Editor/AudioEditor/Private/SoundSubmixGraphNode.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Editor/AudioEditor/Private/SoundSubmixGraphNode.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Editor/AudioEditor/Private/SoundSubmixGraphNode.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "SoundSubmixGraph/SoundSubmixGraphNode.h" #include "Sound/SoundSubmix.h" #include "SoundSubmixGraph/SoundSubmixGraphSchema.h" #include "SoundSubmixGraph/SoundSubmixGraph.h" #define LOCTEXT_NAMESPACE "SoundSubmixGraphNode" USoundSubmixGraphNode::USoundSubmixGraphNode(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) , ChildPin(NULL) , ParentPin(NULL) { } bool USoundSubmixGraphNode::CheckRepresentsSoundSubmix() { if (!SoundSubmix) { return false; } for (int32 ChildIndex = 0; ChildIndex < ChildPin->LinkedTo.Num(); ChildIndex++) { USoundSubmixGraphNode* ChildNode = CastChecked<USoundSubmixGraphNode>(ChildPin->LinkedTo[ChildIndex]->GetOwningNode()); if (!SoundSubmix->ChildSubmixes.Contains(ChildNode->SoundSubmix)) { return false; } } for (int32 ChildIndex = 0; ChildIndex < SoundSubmix->ChildSubmixes.Num(); ChildIndex++) { bool bFoundChild = false; for (int32 NodeChildIndex = 0; NodeChildIndex < ChildPin->LinkedTo.Num(); NodeChildIndex++) { USoundSubmixGraphNode* ChildNode = CastChecked<USoundSubmixGraphNode>(ChildPin->LinkedTo[NodeChildIndex]->GetOwningNode()); if (ChildNode->SoundSubmix == SoundSubmix->ChildSubmixes[ChildIndex]) { bFoundChild = true; break; } } if (!bFoundChild) { return false; } } return true; } FLinearColor USoundSubmixGraphNode::GetNodeTitleColor() const { return Super::GetNodeTitleColor(); } void USoundSubmixGraphNode::AllocateDefaultPins() { check(Pins.Num() == 0); ChildPin = CreatePin(EGPD_Output, TEXT("SoundSubmix"), FString(), nullptr, LOCTEXT("SoundSubmixChildren", "Children").ToString()); ParentPin = CreatePin(EGPD_Input, TEXT("SoundSubmix"), FString(), nullptr, FString()); } void USoundSubmixGraphNode::AutowireNewNode(UEdGraphPin* FromPin) { if (FromPin) { const USoundSubmixGraphSchema* Schema = CastChecked<USoundSubmixGraphSchema>(GetSchema()); if (FromPin->Direction == EGPD_Input) { Schema->TryCreateConnection(FromPin, ChildPin); } else { Schema->TryCreateConnection(FromPin, ParentPin); } } } bool USoundSubmixGraphNode::CanCreateUnderSpecifiedSchema(const UEdGraphSchema* Schema) const { return Schema->IsA(USoundSubmixGraphSchema::StaticClass()); } FText USoundSubmixGraphNode::GetNodeTitle(ENodeTitleType::Type TitleType) const { if (SoundSubmix) { return FText::FromString(SoundSubmix->GetName()); } else { return Super::GetNodeTitle(TitleType); } } bool USoundSubmixGraphNode::CanUserDeleteNode() const { USoundSubmixGraph* SoundSubmixGraph = CastChecked<USoundSubmixGraph>(GetGraph()); // Cannot remove the root node from the graph return SoundSubmix != SoundSubmixGraph->GetRootSoundSubmix(); } #undef LOCTEXT_NAMESPACE
25.225225
131
0.756071
windystrife
1d22dee0f995a9780c5640ceacf6fdbcb0c4d5bf
5,048
cpp
C++
ecm/src/v20190719/model/PeakBase.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
ecm/src/v20190719/model/PeakBase.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
ecm/src/v20190719/model/PeakBase.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/ecm/v20190719/model/PeakBase.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Ecm::V20190719::Model; using namespace std; PeakBase::PeakBase() : m_peakCpuNumHasBeenSet(false), m_peakMemoryNumHasBeenSet(false), m_peakStorageNumHasBeenSet(false), m_recordTimeHasBeenSet(false) { } CoreInternalOutcome PeakBase::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("PeakCpuNum") && !value["PeakCpuNum"].IsNull()) { if (!value["PeakCpuNum"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `PeakBase.PeakCpuNum` IsInt64=false incorrectly").SetRequestId(requestId)); } m_peakCpuNum = value["PeakCpuNum"].GetInt64(); m_peakCpuNumHasBeenSet = true; } if (value.HasMember("PeakMemoryNum") && !value["PeakMemoryNum"].IsNull()) { if (!value["PeakMemoryNum"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `PeakBase.PeakMemoryNum` IsInt64=false incorrectly").SetRequestId(requestId)); } m_peakMemoryNum = value["PeakMemoryNum"].GetInt64(); m_peakMemoryNumHasBeenSet = true; } if (value.HasMember("PeakStorageNum") && !value["PeakStorageNum"].IsNull()) { if (!value["PeakStorageNum"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `PeakBase.PeakStorageNum` IsInt64=false incorrectly").SetRequestId(requestId)); } m_peakStorageNum = value["PeakStorageNum"].GetInt64(); m_peakStorageNumHasBeenSet = true; } if (value.HasMember("RecordTime") && !value["RecordTime"].IsNull()) { if (!value["RecordTime"].IsString()) { return CoreInternalOutcome(Core::Error("response `PeakBase.RecordTime` IsString=false incorrectly").SetRequestId(requestId)); } m_recordTime = string(value["RecordTime"].GetString()); m_recordTimeHasBeenSet = true; } return CoreInternalOutcome(true); } void PeakBase::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_peakCpuNumHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "PeakCpuNum"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_peakCpuNum, allocator); } if (m_peakMemoryNumHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "PeakMemoryNum"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_peakMemoryNum, allocator); } if (m_peakStorageNumHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "PeakStorageNum"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_peakStorageNum, allocator); } if (m_recordTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RecordTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_recordTime.c_str(), allocator).Move(), allocator); } } int64_t PeakBase::GetPeakCpuNum() const { return m_peakCpuNum; } void PeakBase::SetPeakCpuNum(const int64_t& _peakCpuNum) { m_peakCpuNum = _peakCpuNum; m_peakCpuNumHasBeenSet = true; } bool PeakBase::PeakCpuNumHasBeenSet() const { return m_peakCpuNumHasBeenSet; } int64_t PeakBase::GetPeakMemoryNum() const { return m_peakMemoryNum; } void PeakBase::SetPeakMemoryNum(const int64_t& _peakMemoryNum) { m_peakMemoryNum = _peakMemoryNum; m_peakMemoryNumHasBeenSet = true; } bool PeakBase::PeakMemoryNumHasBeenSet() const { return m_peakMemoryNumHasBeenSet; } int64_t PeakBase::GetPeakStorageNum() const { return m_peakStorageNum; } void PeakBase::SetPeakStorageNum(const int64_t& _peakStorageNum) { m_peakStorageNum = _peakStorageNum; m_peakStorageNumHasBeenSet = true; } bool PeakBase::PeakStorageNumHasBeenSet() const { return m_peakStorageNumHasBeenSet; } string PeakBase::GetRecordTime() const { return m_recordTime; } void PeakBase::SetRecordTime(const string& _recordTime) { m_recordTime = _recordTime; m_recordTimeHasBeenSet = true; } bool PeakBase::RecordTimeHasBeenSet() const { return m_recordTimeHasBeenSet; }
27.736264
140
0.695721
suluner
918f20f50d64eb3cfc21d7e7cd53b8b6c2a70df5
6,728
cc
C++
src/ShaderCompiler/Private/MetalCompiler.cc
PixPh/kaleido3d
8a8356586f33a1746ebbb0cfe46b7889d0ae94e9
[ "MIT" ]
38
2019-01-10T03:10:12.000Z
2021-01-27T03:14:47.000Z
src/ShaderCompiler/Private/MetalCompiler.cc
fuqifacai/kaleido3d
ec77753b516949bed74e959738ef55a0bd670064
[ "MIT" ]
null
null
null
src/ShaderCompiler/Private/MetalCompiler.cc
fuqifacai/kaleido3d
ec77753b516949bed74e959738ef55a0bd670064
[ "MIT" ]
8
2019-04-16T07:56:27.000Z
2020-11-19T02:38:37.000Z
#include <Kaleido3D.h> #include "MetalCompiler.h" #include <Core/Utils/MD5.h> #include <Core/Os.h> #include "GLSLangUtils.h" #include "SPIRVCrossUtils.h" #define METAL_BIN_DIR_MACOS "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/usr/bin/" #define METAL_BIN_DIR_IOS "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/usr/bin/" #define METAL_COMPILE_TMP "/.metaltmp/" #define COMPILE_OPTION "-arch air64 -emit-llvm -c" #include <string.h> using namespace std; namespace k3d { NGFXShaderCompileResult mtlCompile(string const& source, String & metalIR); MetalCompiler::MetalCompiler() { sInitializeGlSlang(); } MetalCompiler::~MetalCompiler() { sFinializeGlSlang(); } NGFXShaderCompileResult MetalCompiler::Compile(String const& src, NGFXShaderDesc const& inOp, NGFXShaderBundle& bundle) { if (inOp.Format == NGFX_SHADER_FORMAT_TEXT) { if (inOp.Lang == NGFX_SHADER_LANG_METALSL) { if (m_IsMac) { } else // iOS { } } else // process hlsl or glsl { bool canConvertToMetalSL = false; switch (inOp.Lang) { case NGFX_SHADER_LANG_ESSL: case NGFX_SHADER_LANG_GLSL: case NGFX_SHADER_LANG_HLSL: case NGFX_SHADER_LANG_VKGLSL: canConvertToMetalSL = true; break; default: break; } if (canConvertToMetalSL) { EShMessages messages = (EShMessages)(EShMsgSpvRules | EShMsgVulkanRules); switch (inOp.Lang) { case NGFX_SHADER_LANG_ESSL: case NGFX_SHADER_LANG_GLSL: case NGFX_SHADER_LANG_VKGLSL: break; case NGFX_SHADER_LANG_HLSL: messages = (EShMessages)(EShMsgVulkanRules | EShMsgSpvRules | EShMsgReadHlsl); break; default: break; } glslang::TProgram& program = *new glslang::TProgram; TBuiltInResource Resources; initResources(Resources); const char* shaderStrings[1]; EShLanguage stage = findLanguage(inOp.Stage); glslang::TShader* shader = new glslang::TShader(stage); shaderStrings[0] = src.CStr(); shader->setStrings(shaderStrings, 1); shader->setEntryPoint(inOp.EntryFunction.CStr()); if (!shader->parse(&Resources, 100, false, messages)) { puts(shader->getInfoLog()); puts(shader->getInfoDebugLog()); return NGFX_SHADER_COMPILE_FAILED; } program.addShader(shader); if (!program.link(messages)) { puts(program.getInfoLog()); puts(program.getInfoDebugLog()); return NGFX_SHADER_COMPILE_FAILED; } vector<unsigned int> spirv; GlslangToSpv(*program.getIntermediate(stage), spirv); if (program.buildReflection()) { ExtractAttributeData(program, bundle.Attributes); ExtractUniformData(inOp.Stage, program, bundle.BindingTable); } else { return NGFX_SHADER_COMPILE_FAILED; } uint32 bufferLoc = 0; vector<spirv_cross::MSLVertexAttr> vertAttrs; for (auto& attr : bundle.Attributes) { spirv_cross::MSLVertexAttr vAttrib; vAttrib.location = attr.VarLocation; vAttrib.msl_buffer = attr.VarBindingPoint; vertAttrs.push_back(vAttrib); bufferLoc = attr.VarBindingPoint; } vector<spirv_cross::MSLResourceBinding> resBindings; for (auto& binding : bundle.BindingTable.Bindings) { if (binding.VarType == NGFX_SHADER_BIND_BLOCK) { bufferLoc ++; spirv_cross::MSLResourceBinding resBind; resBind.stage = rhiShaderStageToSpvModel(binding.VarStage); resBind.desc_set = 0; resBind.binding = binding.VarNumber; resBind.msl_buffer = bufferLoc; resBindings.push_back(resBind); } } auto metalc = make_unique<spirv_cross::CompilerMSL>(spirv); spirv_cross::CompilerMSL::Options config; config.flip_vert_y = false; config.entry_point_name = inOp.EntryFunction.CStr(); auto result = metalc->compile(config, &vertAttrs, &resBindings); if (m_IsMac) { auto ret = mtlCompile(result, bundle.RawData); if (ret == NGFX_SHADER_COMPILE_FAILED) return ret; bundle.Desc = inOp; bundle.Desc.Format = NGFX_SHADER_FORMAT_BYTE_CODE; bundle.Desc.Lang = NGFX_SHADER_LANG_METALSL; } else { bundle.RawData = {result.c_str()}; bundle.Desc = inOp; bundle.Desc.Format = NGFX_SHADER_FORMAT_TEXT; bundle.Desc.Lang = NGFX_SHADER_LANG_METALSL; } } } } else { if (inOp.Lang == NGFX_SHADER_LANG_METALSL) { } else { } } return NGFX_SHADER_COMPILE_OK; } const char* MetalCompiler::GetVersion() { return "Metal"; } NGFXShaderCompileResult mtlCompile(string const& source, String & metalIR) { #if K3DPLATFORM_OS_MAC MD5 md5(source); auto name = md5.toString(); auto intermediate = string(".") + METAL_COMPILE_TMP; Os::Path::MakeDir(intermediate.c_str()); auto tmpSh = intermediate + name + ".metal"; auto tmpAr = intermediate + name + ".air"; auto tmpLib = intermediate + name + ".metallib"; Os::File shSrcFile(tmpSh.c_str()); shSrcFile.Open(IOWrite); shSrcFile.Write(source.data(), source.size()); shSrcFile.Close(); auto mcc = string(METAL_BIN_DIR_MACOS) + "metal"; auto mlink = string(METAL_BIN_DIR_MACOS) + "metallib"; auto ccmd = mcc + " -arch air64 -c -o " + tmpAr + " " + tmpSh; auto ret = system(ccmd.c_str()); if(ret) { return NGFX_SHADER_COMPILE_FAILED; } auto lcmd = mlink + " -split-module -o " + tmpLib + " " + tmpAr; ret = system(lcmd.c_str()); if(ret) { return NGFX_SHADER_COMPILE_FAILED; } Os::MemMapFile bcFile; bcFile.Open(tmpLib.c_str(), IORead); metalIR = { bcFile.FileData(), (size_t)bcFile.GetSize() }; bcFile.Close(); //Os::Remove(intermediate.c_str()); #endif return NGFX_SHADER_COMPILE_OK; } }
31.586854
121
0.582194
PixPh
9194384a31c83f2f72a2087ad9b27858c9062688
582
cpp
C++
libs/boost.fiber/libs/fiber/src/barrier.cpp
ghisguth/tasks
ce04926dbee2ab1204ed34e50dbce53f0303bde1
[ "MIT" ]
1
2016-11-18T02:34:18.000Z
2016-11-18T02:34:18.000Z
libs/boost.fiber/libs/fiber/src/barrier.cpp
ghisguth/tasks
ce04926dbee2ab1204ed34e50dbce53f0303bde1
[ "MIT" ]
null
null
null
libs/boost.fiber/libs/fiber/src/barrier.cpp
ghisguth/tasks
ce04926dbee2ab1204ed34e50dbce53f0303bde1
[ "MIT" ]
null
null
null
// Copyright Oliver Kowalke 2009. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "boost/fiber/barrier.hpp" #include <boost/assert.hpp> namespace boost { namespace fibers { bool barrier::wait() { mutex::scoped_lock lk( mtx_); bool cycle( cycle_); if ( 0 == --current_) { cycle_ = ! cycle_; current_ = initial_; cond_.notify_all(); return true; } else { while ( cycle == cycle_) cond_.wait( lk); } return false; } }}
16.628571
61
0.651203
ghisguth
919a463419264750d166d11f2fcd75703cf8ae1f
32,321
cpp
C++
XRVessels/XRVesselCtrlDemo/ParserTreeNode.cpp
dbeachy1/XRVessels
8dd2d879886154de2f31fa75393d8a6ac56a2089
[ "MIT" ]
10
2021-08-20T05:49:10.000Z
2022-01-07T13:00:20.000Z
XRVessels/XRVesselCtrlDemo/ParserTreeNode.cpp
dbeachy1/XRVessels
8dd2d879886154de2f31fa75393d8a6ac56a2089
[ "MIT" ]
null
null
null
XRVessels/XRVesselCtrlDemo/ParserTreeNode.cpp
dbeachy1/XRVessels
8dd2d879886154de2f31fa75393d8a6ac56a2089
[ "MIT" ]
4
2021-09-11T12:08:01.000Z
2022-02-09T00:16:19.000Z
/** XR Vessel add-ons for OpenOrbiter Space Flight Simulator Copyright (C) 2006-2021 Douglas Beachy 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 3 of the License, or 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, see <https://www.gnu.org/licenses/>. Email: mailto:doug.beachy@outlook.com Web: https://www.alteaaerospace.com **/ //------------------------------------------------------------------------- // ParserTreeNode.cpp : implementation of ParserTreeNode class; maintains state // for a given node in our parser tree. //------------------------------------------------------------------------- #include <windows.h> #include <limits> #include "ParserTreeNode.h" // so numeric_limits<T> min, max will compile #undef min #undef max /* Here is an example of how a simple parser tree might look: ParserTreeNode(nullptr) // root node / \ (Set) \ / (Config) (Engine) / \ / / \ (MainBoth, MainLeft, MainRight, (AttitudeHold) (AirspeedHold) Retro...,Hover..., Scram...) / \ / / \ / / \ / (Pitch, AOA) (#targetAirspeed -- this is a leaf node) / / / / (ThrottleLevel, (#targetX #targetBank -- leaf node) GimbalX, GimbayY, ...) / / (#doubleValue) or (#boolValue) */ // Constructor // csNodeText = "Set", "MainLeft", etc. If null, denotes the root node of the tree. Will be cloned internally. // nodeGroup = arbitrary group ID that groups like nodes together when constructing help strings // pNodeData = arbitrary data assigned to this node that is for use by the caller as he sees fit. May be null, although this is normally only null for top-level nodes. // Typically, however, this will be data that will be used later by the LeafHandler of this node or one of its children. This is clone internally. // pCallback = handler that executes for leaf nodes; should be null for non-leaf nodes. This is not cloned internally. ParserTreeNode::ParserTreeNode(const char *pNodeText, const int nodeGroup, const NodeData *pNodeData, LeafHandler *pCallback) : m_nodeGroup(nodeGroup), m_pLeafHandler(pCallback), m_pParentNode(nullptr) { m_pCSNodeText = ((pNodeText != nullptr) ? new CString(pNodeText) : nullptr); // clone it m_pNodeData = ((pNodeData != nullptr) ? pNodeData->Clone() : nullptr); // deep-clone it } // Destructor ParserTreeNode::~ParserTreeNode() { // recursively free all our child nodes for (unsigned int i=0; i < m_children.size(); i++) delete m_children[i]; // free our node text and NodeDAta that we created via cloning in the constructor delete m_pCSNodeText; delete m_pNodeData; } // Add a child node to this node void ParserTreeNode::AddChild(ParserTreeNode *pChildNode) { _ASSERTE(pChildNode != nullptr); pChildNode->SetParentNode(this); // we are the parent m_children.push_back(pChildNode); } // NOTE: for parsing purposes, all string comparisons are case-insensitive. // Parse the command and set csCommand to a full auto-completed string if possible. // Some examples: // S -> returns "Set" // s m -> returns "Set MainBoth" // -> (again) "Set MainLeft" // // autocompletionTokenIndex = maintains state as we scroll through possible autocompletion choices // direction: true = tab direction forward, false = tab direction backward // Returns true if we autocompleted all commands in csCommand bool ParserTreeNode::AutoComplete(CString &csCommand, AUTOCOMPLETION_STATE *pACState, const bool direction) const { csCommand = csCommand.Trim(); if (csCommand.IsEmpty()) return false; // nothing to complete // parse the command into space-separated pieces vector<CString> argv; ParseToSpaceDelimitedTokens(csCommand, argv); // recursively parse all arguments const int autocompletedTokenCount = AutoComplete(argv, 0, pACState, direction); // now reconstruct the full string from the auto-completed pieces csCommand.Empty(); for (unsigned int i=0; i < argv.size(); i++) { if (i > 0) csCommand += " "; csCommand += argv[i]; } const bool autoCompletedAll = (autocompletedTokenCount == argv.size()); // if we autocompleted all tokens successfully, append a trailing space if (autoCompletedAll) csCommand += " "; return autoCompletedAll; } // Recursive method to auto-complete all commands in argv. // argv = arguments to be autocompleted // startingIndex = 0-based index at which to start parsing // autocompletionTokenIndex = maintains state as we scroll through possible autocompletion choices // direction: true = tab direction forward, false = tab direction backward // Returns # of nodes auto-completed (may be zero) int ParserTreeNode::AutoComplete(vector<CString> &argv, const int startingIndex, AUTOCOMPLETION_STATE *pACState, const bool direction) const { _ASSERTE(startingIndex >= 0); _ASSERTE(startingIndex < static_cast<int>(argv.size())); _ASSERTE(pACState != nullptr); int autocompletedTokens = 0; // try to parse the requested token by finding a match with one of our child nodes CString &csToken = argv[startingIndex]; // By design, only track autocompletion state for the *last* token on the line; otherwise we would // overwrite the command following the one we would autocomplete. AUTOCOMPLETION_STATE *pActiveACState = ((startingIndex == (argv.size()-1)) ? pACState : nullptr); const int nextArgIndex = startingIndex + 1; ParserTreeNode *pMatchingChild = FindChildForToken(csToken, pActiveACState, direction); if (pMatchingChild != nullptr) { // Note: by design, we count a token as autocompleted if even if was already complete autocompletedTokens++; argv[startingIndex] = *pMatchingChild->GetNodeText(); // change argv entry to completed token; e.g., "Set", "Main", etc. if (nextArgIndex < static_cast<int>(argv.size())) // any more arguments to parse? { // now let's recurse down to the next level and try to autocomplete the next level down autocompletedTokens += pMatchingChild->AutoComplete(argv, nextArgIndex, pACState, direction); // propagate the ACState that was passed in } } else // no matching child { // let's see if we're a leaf node AND this is the last token on the line (i.e., the first leaf node parameter) if ((m_pLeafHandler != nullptr) && (nextArgIndex == static_cast<int>(argv.size()))) { // this is leaf node parameter #1, so let's see if there are any autocompletion tokens available for it const char **pFirstParamTokens = m_pLeafHandler->GetFirstParamAutocompletionTokens(this); // may be nullptr // let's try to find a unique match const char *pAutocompletedToken = AutocompleteToken(argv[startingIndex], pACState, direction, pFirstParamTokens); if (pAutocompletedToken != nullptr) { autocompletedTokens++; argv[startingIndex] = pAutocompletedToken; // change argv entry to completed token // since this is the last token on the line, there is nothing else to parse: fall through and return } } } return autocompletedTokens; } // Parse the command until either the entire command is parsed (and executed via its leaf handler) // or we locate a syntax or value error. // // Returns true on success, false on error // pCommand = command to be parsed // statusOut = output buffer for result text bool ParserTreeNode::Parse(const char *pCommand, CString &statusOut) const { CString csCommand = CString(pCommand).Trim(); if (csCommand.IsEmpty()) { statusOut = "command is empty."; return false; } // parse the command into space-separated pieces vector<CString> argv; ParseToSpaceDelimitedTokens(csCommand, argv); // recursively parse all arguments and execute the command CString commandStatus; bool success = Parse(argv, 0, commandStatus); statusOut.Format("Command: [%s]\r\n", csCommand); statusOut += (success ? "" : "Error: ") + commandStatus; return success; } // Recursive method that will parse the command and recurse down to our child nodes until we execute the // command or locate a syntax error. // // argv = arguments to be parsed // startingIndex = 0-based index at which to start parsing; NOTE: may be beyond end of argv if this is a leaf node that takes no arguments // autocompletionTokenIndex = maintains state as we scroll through possible autocompletion choices // Returns true on success, false on error bool ParserTreeNode::Parse(vector<CString> &argv, const int startingIndex, CString &statusOut) const { _ASSERTE(startingIndex >= 0); // do not validate argv against startingIndex here: may be beyond end of argv if this is a leaf node that takes no arguments statusOut.Empty(); bool retVal = false; // assume failure // if this is a leaf node, invoke the leafHandler execute the action for this node if (m_pLeafHandler != nullptr) { _ASSERTE(m_children.size() == 0); // leaf nodes must not have any children // build vector of remaining arguments vector<CString> remainingArgv; for (int i=startingIndex; i < static_cast<int>(argv.size()); i++) remainingArgv.push_back(argv[i]); // invoke the leaf handler to execute this command retVal = m_pLeafHandler->Execute(this, remainingArgv, statusOut); } else // not a leaf node, so let's keep recursing down... { const int nextArgIndex = startingIndex + 1; if (startingIndex < static_cast<int>(argv.size())) // more arguments to parse? { // try to parse the requested token by finding a match with one of our child nodes CString &csToken = argv[startingIndex]; ParserTreeNode *pMatchingChild = FindChildForToken(csToken, nullptr, true); // must have exact match here (direction is moot) if (pMatchingChild != nullptr) { // command token is valid const int nextArgIndex = startingIndex + 1; // Note: there may not be any more arguments to parse here; e.g., for leaf nodes that take no arguments. // Therefore, we always recurse down to the next level and attempt to parse/execute it. retVal = pMatchingChild->Parse(argv, nextArgIndex, statusOut); } else // unknown command { statusOut.Format("Invalid command token: [%s]", csToken); // fall through and return false } } else // no more arguments, but this is not a leaf node { statusOut = "Required token missing; options are: "; AppendChildNodeNames(statusOut); // fall through and return false } } return retVal; } // Sets argsOut to a list of bracket-grouped available arguments for the supplied command. // Returns the level for which the available arguments pertain. // For example: // "" -> (returns 1), argsOut = [Set, Config, ...] // Set -> (returns 2), argsOut = [MainBoth, MainLeft, ...] // Set foo -> (returns 2), argsOut = [MainBoth, MainLeft, ...] (foo is invalid, but the user can still correct 'foo' to be one of the valid options) // Set MainBoth -> (returns 3), argsOut = [ThrottleLevel, GimbalX, GimbalY, ...] // "foo" -> (returns 1), argsOut = [Set, Config, ...] (foo is an invalid command) int ParserTreeNode::GetAvailableArgumentsForCommand(const char *pCommand, vector<CString> &argsOut) const { CString csCommand = CString(pCommand).Trim(); // parse the command into space-separated pieces vector<CString> argv; ParseToSpaceDelimitedTokens(csCommand, argv); // recursively parse all arguments argsOut.clear(); // reset int argLevel = GetAvailableArgumentsForCommand(argv, 0, argsOut); return argLevel; } // Recursively parse the supplied command and populate argsOut with bracket-grouped, valid arguments for this command. // argv = arguments to parse // startingIndex = index into argv to parse; also denotes our recursion level (0...n) // argsOut = will be populated with valid arguments for this command // Returns the level for which the arguments in argsOut pertain. int ParserTreeNode::GetAvailableArgumentsForCommand(vector<CString> &argv, const int startingIndex, vector<CString> &argsOut) const { _ASSERTE(startingIndex >= 0); int retVal; // if this is a leaf node, we have reached the end of the chain, so show the leaf handler's help text if (m_pLeafHandler != nullptr) { _ASSERTE(m_children.size() == 0); // leaf nodes must not have any children CString csHelp; m_pLeafHandler->GetArgumentHelp(this, csHelp); argsOut.push_back("[" + csHelp + "]"); // e.g., "[<double> (range -1.0 - 1.0)]" retVal = startingIndex; // startingIndex also matches our recursion level } else // not a leaf node, so let's keep recursing down... { ParserTreeNode *pMatchingChild = nullptr; if (startingIndex < static_cast<int>(argv.size())) // more arguments to parse? { // try to parse the requested token by finding a match with one of our child nodes CString &csToken = argv[startingIndex]; pMatchingChild = FindChildForToken(csToken, nullptr, true); // must have exact match here (direction is moot) } const int nextArgIndex = startingIndex + 1; if (pMatchingChild != nullptr) { // command token is valid, so let's recurse down to the next level (keep parsing) const int nextArgIndex = startingIndex + 1; retVal = pMatchingChild->GetAvailableArgumentsForCommand(argv, nextArgIndex, argsOut); // recurse down } else { // No child node found and this is NOT a leaf node, so we have invalid tokens at this level. // Therefore, we return a list of this level's child nodes (available options), grouped in brackets [ ... ]. int currentNodeGroup; for (unsigned int i=0; i < m_children.size(); i++) { const ParserTreeNode *pChild = m_children[i]; _ASSERTE(pChild != nullptr); CString nodeText = *m_children[i]->GetNodeText(); // enclose a given group of commands in brackets for clarity if (i == 0) { currentNodeGroup = pChild->GetNodeGroup(); // first node at this level, so its group is the active group now nodeText = " [" + nodeText; // first group start } else if (pChild->GetNodeGroup() != currentNodeGroup) { // new group coming, so append closing "]" to previous command text and prepend " [" to this command text currentNodeGroup = pChild->GetNodeGroup(); // this is the new active group argsOut.back() += "]"; nodeText = " [" + nodeText; } argsOut.push_back(nodeText); } argsOut.back() += "]"; // last group end retVal = startingIndex; } } _ASSERTE(argsOut.size() > 0); return retVal; } // appends csOut with formatted names for all our child nodes void ParserTreeNode::AppendChildNodeNames(CString &csOut) const { for (unsigned int i=0; i < m_children.size(); i++) { if (i > 0) csOut += ", "; csOut += *m_children[i]->GetNodeText(); // e.g., "Set", "MainBoth", etc. } } // static factory method that creates a new autocompletion state; it is the caller's responsibility to eventually free this ParserTreeNode::AUTOCOMPLETION_STATE *ParserTreeNode::AllocateNewAutocompletionState() { AUTOCOMPLETION_STATE *pNew = reinterpret_cast<AUTOCOMPLETION_STATE *>(new ParserTreeNode::AutocompletionState()); ResetAutocompletionState(pNew); return pNew; } // static utility method to reset the autcompletion state to a new command void ParserTreeNode::ResetAutocompletionState(AUTOCOMPLETION_STATE *pACState) { AutocompletionState *ptr = reinterpret_cast<AutocompletionState *>(pACState); // cast back to actual type ptr->significantCharacters = 0; ptr->tokenCandidateIndex = 0; } // Examine our child nodes and try to locate a case-insensitive match for the supplied token. // acState : tracks autocompletion state between successive autocompletion calls; if null, do not track autocompletion for this token (i.e., this is not the final token on the command line) // direction: true = tab direction forward, false = tab direction backward // Returns node on a match or nullptr if no match found OR if more than one match found. ParserTreeNode *ParserTreeNode::FindChildForToken(const CString &csToken, AUTOCOMPLETION_STATE *pACState, const bool direction) const { if (csToken.IsEmpty()) return nullptr; // sanity check // NOTE: do not modify this object's state *except* for the last token on the command line AutocompletionState *pActiveACState = reinterpret_cast<AutocompletionState *>(pACState); // cast back to actual type // assume no autocompletionstate int significantCharacters = csToken.GetLength(); int tokenCandidateIndex = 0; if (pActiveACState != nullptr) { // we may be stepping through the possible candidates significantCharacters = pActiveACState->significantCharacters; if (significantCharacters <= 0) { // we were reset, so test all characters in the token significantCharacters = csToken.GetLength(); } tokenCandidateIndex = pActiveACState->tokenCandidateIndex; } _ASSERTE(significantCharacters <= csToken.GetLength()); // step through each of our child nodes and build a list of all case-insensitive matches vector<ParserTreeNode *> matchingNodes; for (unsigned int i=0; i < m_children.size(); i++) { ParserTreeNode *pCandidate = m_children[i]; const CString csNodeTextPrefix = pCandidate->GetNodeText()->Left(significantCharacters); const CString csTokenPrefix = csToken.Left(significantCharacters); if (csTokenPrefix.CompareNoCase(csNodeTextPrefix) == 0) matchingNodes.push_back(pCandidate); // we have a match } // decide which matching node to use ParserTreeNode *pRetVal = nullptr; const int matchingNodeCount = static_cast<int>(matchingNodes.size()); if (matchingNodeCount > 0) { _ASSERTE(tokenCandidateIndex >= 0); _ASSERTE(tokenCandidateIndex < matchingNodeCount); if (pActiveACState == nullptr) // not stepping through multiple tokens? { // must have exactly *one* match or we cannot autocomplete this token pRetVal = ((matchingNodeCount == 1) ? matchingNodes.front() : nullptr); } else // we're stepping through multiple tokens (always on the last token on the line) { pRetVal = matchingNodes[tokenCandidateIndex]; // update our AutocompletionState for next time pActiveACState->significantCharacters = significantCharacters; if (direction) // forward? { if (++pActiveACState->tokenCandidateIndex >= matchingNodeCount) pActiveACState->tokenCandidateIndex = 0; // wrap around to beginning } else // backward { if (--pActiveACState->tokenCandidateIndex < 0) pActiveACState->tokenCandidateIndex = (matchingNodeCount - 1); // wrap around to end } } } return pRetVal; } // Try to autocomplete the supplied token using the supplied list of valid token values. // (This method is similar to 'FindChildForToken' above.) // // acState : tracks autocompletion state between successive autocompletion calls; if null, do not track autocompletion for this token (i.e., this is not the final token on the command line) // direction: true = tab direction forward, false = tab direction backward // pValidTokenValues: may be nullptr. Otherwise, points to a nullptr-terminated array of valid token values. // Returns autocompleted token on a match or nullptr if pValidTokenValues is nullptr OR no match found OR if more than one match found. const char *ParserTreeNode::AutocompleteToken(const CString &csToken, AUTOCOMPLETION_STATE *pACState, const bool direction, const char **pValidTokenValues) const { if (pValidTokenValues == nullptr) return nullptr; // no autocompletion possible if (csToken.IsEmpty()) return nullptr; // sanity check // NOTE: do not modify this object's state *except* for the last token on the command line AutocompletionState *pActiveACState = reinterpret_cast<AutocompletionState *>(pACState); // cast back to actual type // assume no autocompletionstate int significantCharacters = csToken.GetLength(); int tokenCandidateIndex = 0; if (pActiveACState != nullptr) { // we may be stepping through the possible candidates significantCharacters = pActiveACState->significantCharacters; if (significantCharacters <= 0) { // we were reset, so test all characters in the token significantCharacters = csToken.GetLength(); } tokenCandidateIndex = pActiveACState->tokenCandidateIndex; } _ASSERTE(significantCharacters <= csToken.GetLength()); // step through each of our valid tokens and build a list of all case-insensitive matches vector<const char *> matchingTokens; for (const char **ppValidToken = pValidTokenValues; *ppValidToken != nullptr; ppValidToken++) { CString candidate = *ppValidToken; // valid token (a possible match) const CString csNodeTextPrefix = candidate.Left(significantCharacters); const CString csTokenPrefix = csToken.Left(significantCharacters); if (csTokenPrefix.CompareNoCase(csNodeTextPrefix) == 0) matchingTokens.push_back(*ppValidToken); // we have a match } // decide which matching node to use const char *pRetVal = nullptr; const int matchingTokenCount = static_cast<int>(matchingTokens.size()); if (matchingTokenCount > 0) { _ASSERTE(tokenCandidateIndex >= 0); _ASSERTE(tokenCandidateIndex < matchingTokenCount); if (pActiveACState == nullptr) // not stepping through multiple tokens? { // must have exactly *one* match or we cannot autocomplete this token pRetVal = ((matchingTokenCount == 1) ? matchingTokens.front() : nullptr); } else // we're stepping through multiple tokens (always on the last token on the line) { pRetVal = matchingTokens[tokenCandidateIndex]; // update our AutocompletionState for next time pActiveACState->significantCharacters = significantCharacters; if (direction) // forward? { if (++pActiveACState->tokenCandidateIndex >= matchingTokenCount) pActiveACState->tokenCandidateIndex = 0; // wrap around to beginning } else // backward { if (--pActiveACState->tokenCandidateIndex < 0) pActiveACState->tokenCandidateIndex = (matchingTokenCount - 1); // wrap around to end } } } return pRetVal; } // static utility method that will parse a given command string into space-delimited tokens // argv = contains parse-delmited tokens; NOTE: it is the caller's responsibility to free the CString objects // added to the vector. // Returns: # of valid (i.e., non-empty) tokens parsed; i.e., argv.size() int ParserTreeNode::ParseToSpaceDelimitedTokens(const char *pCommand, vector<CString> &argv) { CString csCommand(pCommand); int tokenIndex = 0; while (tokenIndex >= 0) { CString token = csCommand.Tokenize(" ", tokenIndex); if (!token.IsEmpty()) { argv.push_back(token.Trim()); // whack any other non-printables } } return static_cast<int>(argv.size()); } // // LeafHandler static utility methods // // Parse a validated double from the supplied string. // // Parameters: // pStr = string to be parsed // dblOut = will be set to parsed value, regardless of whether it is in range // min = minimum valid value, inclusive // max = maximum valid value, inclusive // pCSErrorMsgOut = if non-null, will be set to error reason if parse or validation fails // // Returns: true if value parsed successfully and is in range, false otherwise. bool ParserTreeNode::LeafHandler::ParseValidatedDouble(const char *pStr, double &dblOut, const double min, const double max, CString *pCSErrorMsgOut) { bool parseSuccessful = ParseDouble(pStr, dblOut); bool inRange = ((dblOut >= min) && (dblOut <= max)); if (pCSErrorMsgOut != nullptr) { if (!parseSuccessful) { pCSErrorMsgOut->Format("Invalid argument: '%s'", pStr); } else // parse successful { if (!inRange) { if ((min != numeric_limits<double>::min()) && (max != numeric_limits<double>::max())) { // normal limits defined pCSErrorMsgOut->Format("Value out-of-range (%.4lf); valid range is %.4lf - %.4lf.", dblOut, min, max); } else if (min == numeric_limits<double>::min()) { // upper limit, but no lower limit pCSErrorMsgOut->Format("Value too large (%.4lf); must be <= %.4lf.", dblOut, max); } else // must be max == numeric_limits<double>::max() { // lower limit, but no upper limit pCSErrorMsgOut->Format("Value too small (%.4lf); must be >= %.4lf.", dblOut, min); } } } } return inRange; } // Parse a validated boolean from the supplied string. // // Parameters: // pStr = string to be parsed; for success, must be one of "true", "on", "false", or "off" (case-insensitive) // boolOut = will be set to parsed value, regardless of whether it is valid // pCSErrorMsgOut = if non-null, will be set to error reason if parse fails // // Returns: true if value parsed is valid, false otherwise bool ParserTreeNode::LeafHandler::ParseValidatedBool(const char *pStr, bool &boolOut, CString *pCSErrorMsgOut) { bool success = ParseBool(pStr, boolOut); if ((pCSErrorMsgOut != nullptr) && (!success)) pCSErrorMsgOut->Format("Invalid boolean value (%s); valid options are 'true', 'on', 'false', or 'off' (case-insensitive).", pStr); return success; } // Parse a validated integer from the supplied string. // // Parameters: // pStr = string to be parsed // intOut = will be set to parsed value, regardless of whether it is in range // min = minimum valid value, inclusive // max = maximum valid value, inclusive // pCSErrorMsgOut = if non-null, will be set to error reason if parse or validation fails // // Returns: true if value parsed successfully and is in range, false otherwise. bool ParserTreeNode::LeafHandler::ParseValidatedInt(const char *pStr, int &intOut, const int min, const int max, CString *pCSErrorMsgOut) { bool parseSuccessful = ParseInt(pStr, intOut); bool inRange = (parseSuccessful && (intOut >= min) && (intOut <= max)); if (pCSErrorMsgOut != nullptr) { if (!parseSuccessful) pCSErrorMsgOut->Format("Invalid argument: '%s'", pStr); else if (!inRange) // value parsed successfully, but is it out-of-range? pCSErrorMsgOut->Format("Value out-of-range (%d); valid range is %d - %d.", intOut, min, max); } return inRange; } // Parse a double from the supplied string; returns true on success, false on error. // On success, dblOut will contain the parsed value. // Returns true if value parsed successfully, or false if value could not be parsed (invalid string). bool ParserTreeNode::LeafHandler::ParseDouble(const char *pStr, double &dblOut) { _ASSERTE(pStr != nullptr); // we use sscanf_s instead of atof here because it has error handling return (sscanf_s(pStr, "%lf", &dblOut) == 1); } // Parse a boolean from the supplied string; returns true on success, false on error. // pStr: should be one of "true", "on", "false", or "off" (case-insensitive). // On success, boolOut will contain the parsed value. // Returns true if value parsed successfully, or false if value could not be parsed (invalid string). bool ParserTreeNode::LeafHandler::ParseBool(const char *pStr, bool &boolOut) { _ASSERTE(pStr != nullptr); bool success = false; if (!_stricmp(pStr, "true") || !_stricmp(pStr, "on")) { boolOut = success = true; } else if (!_stricmp(pStr, "false") || !_stricmp(pStr, "off")) { boolOut = false; success = true; } // else fall through and return false return success; } // Parse an integer from the supplied string; returns true on success, false on error. // On success, intOut will contain the parsed value. // Returns true if value parsed successfully, or false if value could not be parsed (invalid string) bool ParserTreeNode::LeafHandler::ParseInt(const char *pStr, int &intOut) { _ASSERTE(pStr != nullptr); // we use sscanf_s instead of atof here because it has error handling return (sscanf_s(pStr, "%d", &intOut) == 1); } // Recursively build a tree of all command help text appended to csOut. // indent = indent for this line in csOut. void ParserTreeNode::BuildCommandHelpTree(int recursionLevel, CString &csOut) { // build indent string CString csIndent; for (int i=0; i < recursionLevel; i++) csIndent += " "; csOut += csIndent; // indent this line // add our command text const CString *pNodeText = GetNodeText(); if (pNodeText != nullptr) { csOut += *pNodeText; csOut += " "; } // if we're a leaf node, see if we have any help text if (m_pLeafHandler != nullptr) { CString csLeafHelp; m_pLeafHandler->GetArgumentHelp(this, csLeafHelp); csOut += csLeafHelp; // add the leaf node text, too } // terminate this line if (csOut.GetLength() > 0) // prevent extra root node newline and indent { csOut += "\r\n"; recursionLevel++; } // recurse down to all our children for (unsigned i=0; i < m_children.size(); i++) m_children[i]->BuildCommandHelpTree(recursionLevel, csOut); if (m_children.size() > 0) // not a leaf node? csOut += "\r\n"; // add separator line }
42.696169
189
0.643173
dbeachy1
919d7d690b95402d371b19dc25e50af043a8fb21
2,188
cpp
C++
src/main.cpp
daichi-ishida/Visual-Simulation-of-Smoke
b925d0cfc86f642ab4ee9470e67360b2ab5adcb2
[ "MIT" ]
13
2018-06-12T11:42:19.000Z
2021-12-28T00:57:46.000Z
src/main.cpp
daichi-ishida/Visual-Simulation-of-Smoke
b925d0cfc86f642ab4ee9470e67360b2ab5adcb2
[ "MIT" ]
2
2018-05-10T13:32:02.000Z
2018-05-12T18:32:53.000Z
src/main.cpp
daichi-ishida/Visual-Simulation-of-Smoke
b925d0cfc86f642ab4ee9470e67360b2ab5adcb2
[ "MIT" ]
7
2020-01-06T07:07:19.000Z
2021-12-06T15:43:00.000Z
#include <memory> #include <sys/time.h> #define GLFW_INCLUDE_GLU #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include "constants.hpp" #include "Scene.hpp" #include "Simulator.hpp" #include "MACGrid.hpp" int main() { if (glfwInit() == GLFW_FALSE) { fprintf(stderr, "Initialization failed!\n"); } if (OFFSCREEN_MODE) { glfwWindowHint(GLFW_VISIBLE, 0); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow *window = glfwCreateWindow(WIN_WIDTH, WIN_HEIGHT, WIN_TITLE, NULL, NULL); if (window == NULL) { fprintf(stderr, "Window creation failed!"); glfwTerminate(); } glfwMakeContextCurrent(window); glewExperimental = true; if (glewInit() != GLEW_OK) { fprintf(stderr, "GLEW initialization failed!\n"); } // set background color glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glLineWidth(1.2f); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE); double time = 0.0; int step = 1; std::shared_ptr<MACGrid> grids = std::make_shared<MACGrid>(); std::unique_ptr<Simulator> simulator = std::make_unique<Simulator>(grids, time); std::unique_ptr<Scene> scene = std::make_unique<Scene>(grids); printf("\n*** SIMULATION START ***\n"); struct timeval s, e; // scene->writeData(); while (glfwWindowShouldClose(window) == GL_FALSE && glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS) { printf("\n=== STEP %d ===\n", step); time += DT; gettimeofday(&s, NULL); simulator->update(); scene->update(); // scene->writeData(); scene->render(); gettimeofday(&e, NULL); printf("time = %lf\n", (e.tv_sec - s.tv_sec) + (e.tv_usec - s.tv_usec) * 1.0E-6); ++step; if (time >= FINISH_TIME) { break; } glfwSwapBuffers(window); glfwPollEvents(); } printf("\n*** SIMULATION END ***\n"); glfwTerminate(); return 0; }
25.149425
106
0.59415
daichi-ishida
91a7b84e71b83bb1d8f1f43442cbe90a3dafe442
1,143
cpp
C++
source/src/graphics.cpp
AndrewPomorski/KWCGame
b1a748ad0b11d44c6df329345e072cf63fcb5e16
[ "MIT" ]
null
null
null
source/src/graphics.cpp
AndrewPomorski/KWCGame
b1a748ad0b11d44c6df329345e072cf63fcb5e16
[ "MIT" ]
null
null
null
source/src/graphics.cpp
AndrewPomorski/KWCGame
b1a748ad0b11d44c6df329345e072cf63fcb5e16
[ "MIT" ]
null
null
null
#include "SDL.h" #include <SDL2/SDL_image.h> #include "graphics.h" #include "globals.h" /* * Graphics class implementation. * Holds all information dealing with game graphics. */ Graphics::Graphics(){ SDL_CreateWindowAndRenderer(globals::SCREEN_WIDTH, globals::SCREEN_HEIGHT, 0, &this->_window, &this->_renderer); SDL_SetWindowTitle(this->_window, "Hong"); } Graphics::~Graphics(){ SDL_DestroyWindow(this->_window); SDL_DestroyRenderer(this->_renderer); } SDL_Surface* Graphics::loadImage( const std::string &filePath ){ if ( this->_spriteSheets.count(filePath) == 0 ){ /* * the file from this path hasn't been loaded yet. */ this->_spriteSheets[filePath] = IMG_Load(filePath.c_str()); } return _spriteSheets[filePath]; } void Graphics::blitSurface( SDL_Texture* texture, SDL_Rect* sourceRectangle, SDL_Rect* destinationRectangle ) { SDL_RenderCopy( this->_renderer, texture, sourceRectangle, destinationRectangle ); } void Graphics::flip(){ SDL_RenderPresent(this->_renderer); } void Graphics::clear(){ SDL_RenderClear(this->_renderer); } SDL_Renderer* Graphics::getRenderer() const { return this->_renderer; }
22.86
113
0.741907
AndrewPomorski
91a8b666f9cf365fc0a1b889422c3d8fac1755d8
3,809
cpp
C++
qCC/ccColorGradientDlg.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
null
null
null
qCC/ccColorGradientDlg.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
null
null
null
qCC/ccColorGradientDlg.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
1
2019-02-03T12:19:42.000Z
2019-02-03T12:19:42.000Z
//########################################################################## //# # //# CLOUDCOMPARE # //# # //# 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; version 2 or later of the License. # //# # //# 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. # //# # //# COPYRIGHT: EDF R&D / TELECOM ParisTech (ENST-TSI) # //# # //########################################################################## #include "ccColorGradientDlg.h" //Local #include "ccQtHelpers.h" //Qt #include <QColorDialog> //system #include <assert.h> //persistent parameters static QColor s_firstColor(Qt::black); static QColor s_secondColor(Qt::white); static ccColorGradientDlg::GradientType s_lastType(ccColorGradientDlg::Default); static double s_lastFreq = 5.0; ccColorGradientDlg::ccColorGradientDlg(QWidget* parent) : QDialog(parent, Qt::Tool) , Ui::ColorGradientDialog() { setupUi(this); connect(firstColorButton, &QAbstractButton::clicked, this, &ccColorGradientDlg::changeFirstColor); connect(secondColorButton, &QAbstractButton::clicked, this, &ccColorGradientDlg::changeSecondColor); //restore previous parameters ccQtHelpers::SetButtonColor(secondColorButton, s_secondColor); ccQtHelpers::SetButtonColor(firstColorButton, s_firstColor); setType(s_lastType); bandingFreqSpinBox->setValue(s_lastFreq); } unsigned char ccColorGradientDlg::getDimension() const { return static_cast<unsigned char>(directionComboBox->currentIndex()); } void ccColorGradientDlg::setType(ccColorGradientDlg::GradientType type) { switch(type) { case Default: defaultRampRadioButton->setChecked(true); break; case TwoColors: customRampRadioButton->setChecked(true); break; case Banding: bandingRadioButton->setChecked(true); break; default: assert(false); } } ccColorGradientDlg::GradientType ccColorGradientDlg::getType() const { //ugly hack: we use 's_lastType' here as the type is only requested //when the dialog is accepted if (customRampRadioButton->isChecked()) s_lastType = TwoColors; else if (bandingRadioButton->isChecked()) s_lastType = Banding; else s_lastType = Default; return s_lastType; } void ccColorGradientDlg::getColors(QColor& first, QColor& second) const { assert(customRampRadioButton->isChecked()); first = s_firstColor; second = s_secondColor; } double ccColorGradientDlg::getBandingFrequency() const { //ugly hack: we use 's_lastFreq' here as the frequency is only requested //when the dialog is accepted s_lastFreq = bandingFreqSpinBox->value(); return s_lastFreq; } void ccColorGradientDlg::changeFirstColor() { QColor newCol = QColorDialog::getColor(s_firstColor, this); if (newCol.isValid()) { s_firstColor = newCol; ccQtHelpers::SetButtonColor(firstColorButton, s_firstColor); } } void ccColorGradientDlg::changeSecondColor() { QColor newCol = QColorDialog::getColor(s_secondColor, this); if (newCol.isValid()) { s_secondColor = newCol; ccQtHelpers::SetButtonColor(secondColorButton, s_secondColor); } }
31.221311
101
0.631137
ohanlonl
91abcc4e5cff1535f9fe5d288498f031d2373a63
4,016
hpp
C++
include/public/coherence/io/pof/PofAnnotationSerializer.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-01T21:38:30.000Z
2021-11-03T01:35:11.000Z
include/public/coherence/io/pof/PofAnnotationSerializer.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
1
2020-07-24T17:29:22.000Z
2020-07-24T18:29:04.000Z
include/public/coherence/io/pof/PofAnnotationSerializer.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-10T18:40:58.000Z
2022-02-18T01:23:40.000Z
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ #ifndef COH_POF_ANNOTATION_SERIALIZER_HPP #define COH_POF_ANNOTATION_SERIALIZER_HPP #include "coherence/lang.ns" #include "coherence/io/pof/PofReader.hpp" #include "coherence/io/pof/PofSerializer.hpp" #include "coherence/io/pof/PofWriter.hpp" COH_OPEN_NAMESPACE3(coherence,io,pof) /** * A PofAnnotationSerializer provides annotation based (de)serialization. * This serializer must be instantiated with the intended class which is * eventually scanned for the presence of the following annotations. * <ul> * <li>coherence::io::pof::annotation::Portable</li> * <li>coherence::io::pof::annotation::PortableProperty</li> * </ul> * * This serializer supports classes iff they are annotated with the type level * annotation; Portable. This annotation is a marker indicating the ability * to (de)serialize using this serializer. * * All methods annotated with PortableProperty are explicitly * deemed POF serializable with the option of specifying overrides to * provide explicit behaviour such as: * <ul> * <li>explicit POF indexes</li> * <li>Custom coherence::io::pof::reflect::Codec to * specify concrete implementations / customizations</li> * </ul> * * The PortableProperty::getIndex() (POF index) can be omitted iff the * auto-indexing feature is enabled. This is enabled by instantiating this * class with the \c fAutoIndex constructor argument. This feature * determines the index based on any explicit indexes specified and the name * of the portable properties. Currently objects with multiple versions is * not supported. The following illustrates the auto index algorithm: * <table border=1> * <tr><td>Name</td><td>Explicit Index</td><td>Determined Index</td></tr> * <tr><td>c</td><td>1</td><td>1</td> * <tr><td>a</td><td></td><td>0</td> * <tr><td>b</td><td></td><td>2</td> * </table> * * <b>NOTE:</b> This implementation does support objects that implement * Evolvable. * * @author hr 2011.06.29 * * @since 3.7.1 * * @see COH_REGISTER_TYPED_CLASS * @see COH_REGISTER_POF_ANNOTATED_CLASS * @see COH_REGISTER_POF_ANNOTATED_CLASS_AI * @see Portable */ class COH_EXPORT PofAnnotationSerializer : public class_spec<PofAnnotationSerializer, extends<Object>, implements<PofSerializer> > { friend class factory<PofAnnotationSerializer>; // ----- constructors --------------------------------------------------- protected: /** * Constructs a PofAnnotationSerializer. * * @param nTypeId the POF type id * @param vClz type this serializer is aware of * @param fAutoIndex turns on the auto index feature, default = false */ PofAnnotationSerializer(int32_t nTypeId, Class::View vClz, bool fAutoIndex = false); // ----- PofSerializer interface ---------------------------------------- public: /** * {@inheritDoc} */ virtual void serialize(PofWriter::Handle hOut, Object::View v) const; /** * {@inheritDoc} */ virtual Object::Holder deserialize(PofReader::Handle hIn) const; // ---- helpers --------------------------------------------------------- protected: /** * Initialize this class based on the provided information. * * @param nTypeId the POF type id * @param vClz type this serializer is aware of * @param fAutoIndex turns on the auto index feature */ virtual void initialize(int32_t nTypeId, Class::View vClz, bool fAutoIndex); // ---- data members ---------------------------------------------------- private: /** * A structural definition of the type information. */ FinalHandle<Object> f_ohTypeMetadata; }; COH_CLOSE_NAMESPACE3 #endif // COH_POF_ANNOTATION_SERIALIZER_HPP
33.190083
92
0.648904
chpatel3
91adf96fa00a4e220217519094393215a1cf1770
4,088
hpp
C++
Canvas/Canvas.hpp
sidmishraw/the-manipulator
f63e4a70dafa752a14411dadf89974aa948bfe54
[ "BSD-3-Clause" ]
1
2021-11-25T01:11:34.000Z
2021-11-25T01:11:34.000Z
Canvas/Canvas.hpp
sidmishraw/the-manipulator
f63e4a70dafa752a14411dadf89974aa948bfe54
[ "BSD-3-Clause" ]
null
null
null
Canvas/Canvas.hpp
sidmishraw/the-manipulator
f63e4a70dafa752a14411dadf89974aa948bfe54
[ "BSD-3-Clause" ]
null
null
null
// // Canvas.hpp // the-manipulator // // Created by Sidharth Mishra on 2/18/18. // #ifndef Canvas_hpp #define Canvas_hpp #include <memory> #include <map> #include "Picture.hpp" #include "Tmnper.hpp" namespace Manipulator { /** * The canvas where the pictures are drawn. */ using namespace std; class Canvas { /** * All the pictures added to the canvas. * I feel that having a map with Z-Index makes it easier for me to implement * the selected image movement thingy! */ std::map<int,std::shared_ptr<Manipulator::Picture>> pictures; // // denotes the z-depth? // int currentDepth; // // pointer to the foreground picture. // std::shared_ptr<Manipulator::Picture> foregroundPic; // // the depth of the selected picture // int selectionDepth; public: /** * Initializes the canvas with initial properties. */ Canvas(); /** * Adds the picture at the filePath to the canvas, if not added returns false. */ bool addPicture(std::string filePath, float tx, float ty); // // The selection render pass using the color selection method // void beginSelectionRenderPass(); void endSelectionRenderPass(); /** * Renders the canvas, drawing the pictures, one at a time in the order they were added to it. */ void render(); /** * Saves the canvas composition to disk with the provided fileName. */ bool saveCompositionToDisk(std::string fileName); /** * Manipulates the Picture depending on the mode of its manipulator: * - Scales/resizes the current - selected picture or the picture on the foreground. * - 2D translation of the foregroundPic. Does nothing if there is no foregroundPic or no selected pic. * - Computes the rotation by taking into account the delta w.r.t. the center of the * border of the selected picture. */ void manipulatePicture(const ofVec2f &src, const ofVec2f &dest); /** * Selects the picture on the foreground. */ void selectForegroundPicture(); /** * De-Selects the picture on the foreground. */ void deselectForegroundPicture(); /** * Selects the picture at the specified (x,y) co-ordinate if possible. */ void selectPictureAt(int x, int y); /** * Moves the selected image up in the z. (-ve) */ void cyclePicturesUp(); /** * Moves the selected image down in the z. (+ve) */ void cyclePicturesDown(); /** * Deletes the selected picture from the canvas. */ void deletePicture(); // Processing for constrained TRS of selected image // s -- scale // x -- x translate // y -- y translate // r -- rotate void processConstrained(char flag, bool isPositive); /* ------------------------------------------------------------ */ /** * Saves the canvas state to disk with the provided fileName. */ bool saveStateToDisk(std::string fileName); /** * Loads the canvas state from the disk. */ void loadStateFromDisk(std::string fileName); /** * Serializes the contents of the Canvas into a string to be saved onto disk. */ string toString(); /** * De-serializes the contents of the string restoring the canvas. */ void fromString(string contents); /* ------------------------------------------------------------ */ }; } #endif /* Canvas_hpp */
28
111
0.518836
sidmishraw
91b5701c29df069d7c47d5e8cdbb85b3183b0582
1,255
cpp
C++
graphs/dinic.cpp
hsnavarro/icpc-notebook
5e501ecdd56a2a719d2a3a5e99e09d926d7231a3
[ "MIT" ]
null
null
null
graphs/dinic.cpp
hsnavarro/icpc-notebook
5e501ecdd56a2a719d2a3a5e99e09d926d7231a3
[ "MIT" ]
null
null
null
graphs/dinic.cpp
hsnavarro/icpc-notebook
5e501ecdd56a2a719d2a3a5e99e09d926d7231a3
[ "MIT" ]
null
null
null
// Dinic - O(n^2 * m) // Max flow const int N = 1e5 + 5; const int INF = 0x3f3f3f3f; struct edge { int v, c, f; }; int n, s, t, h[N], st[N]; vector<edge> edgs; vector<int> g[N]; // directed from u to v with cap(u, v) = c void add_edge(int u, int v, int c) { int k = edgs.size(); edgs.push_back({v, c, 0}); edgs.push_back({u, 0, 0}); g[u].push_back(k); g[v].push_back(k+1); } int bfs() { memset(h, 0, sizeof h); h[s] = 1; queue<int> q; q.push(s); while(q.size()) { int u = q.front(); q.pop(); for(auto i : g[u]) { int v = edgs[i].v; if(!h[v] and edgs[i].f < edgs[i].c) h[v] = h[u] + 1, q.push(v); } } return h[t]; } int dfs(int u, int flow) { if(!flow or u == t) return flow; for(int &i = st[u]; i < g[u].size(); i++) { edge &dir = edgs[g[u][i]], &rev = edgs[g[u][i]^1]; int v = dir.v; if(h[v] != h[u] + 1) continue; int inc = min(flow, dir.c - dir.f); inc = dfs(v, inc); if(inc) { dir.f += inc, rev.f -= inc; return inc; } } return 0; } int dinic() { int flow = 0; while(bfs()) { memset(st, 0, sizeof st); while(int inc = dfs(s, INF)) flow += inc; } return flow; }
19.920635
55
0.467729
hsnavarro
91b78f33891c2e2ba7f7dc198195baf90da2033d
4,582
cpp
C++
tests/tests/array/test_fixedlengtharray.cpp
jnory/YuNomi
c7a2750010d531af53a7a3007ca9b9e6b69dae93
[ "MIT" ]
8
2016-09-10T05:45:59.000Z
2019-04-06T13:27:18.000Z
tests/tests/array/test_fixedlengtharray.cpp
jnory/YuNomi
c7a2750010d531af53a7a3007ca9b9e6b69dae93
[ "MIT" ]
1
2017-11-18T19:49:37.000Z
2018-05-05T09:49:27.000Z
tests/tests/array/test_fixedlengtharray.cpp
jnory/YuNomi
c7a2750010d531af53a7a3007ca9b9e6b69dae93
[ "MIT" ]
1
2015-12-06T20:51:10.000Z
2015-12-06T20:51:10.000Z
#include "gtest/gtest.h" #include "yunomi/array/fixedlengtharray.hpp" TEST(TestFixedLengthArray, test_init){ yunomi::array::FixedLengthArray array(10, 1); EXPECT_EQ(10, array.size()); EXPECT_EQ(1, array.bits_per_slot()); } TEST(TestFixedLengthArray, test_ten_values){ yunomi::array::FixedLengthArray array(10, 4); EXPECT_EQ(10, array.size()); EXPECT_EQ(4, array.bits_per_slot()); for(std::size_t i = 0; i < 10; ++i){ array[i] = i; EXPECT_EQ(i, uint64_t(array[i])); } for(std::size_t i = 0; i < 10; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } } TEST(TestFixedLengthArray, test_thousand_values){ yunomi::array::FixedLengthArray array(1000, 10); EXPECT_EQ(1000, array.size()); for(std::size_t i = 0; i < 1000; ++i){ array[i] = i; } for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } } TEST(TestFixedLengthArray, test_resize){ yunomi::array::FixedLengthArray array(1000, 10); for(std::size_t i = 0; i < 1000; ++i){ array[i] = i; } array.resize(1500, 10); for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } for(std::size_t i = 1000; i < 1500; ++i){ EXPECT_EQ(0, uint64_t(array[i])); } } TEST(TestFixedLengthArray, test_resize2){ yunomi::array::FixedLengthArray array(1000, 10); for(std::size_t i = 0; i < 1000; ++i){ array[i] = i; } array.resize(1500, 11); for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } for(std::size_t i = 1000; i < 1500; ++i){ EXPECT_EQ(0, uint64_t(array[i])); } } TEST(TestFixedLengthArray, test_thousand_values_template){ yunomi::array::ConstLengthArray<10> array(1000); EXPECT_EQ(1000, array.size()); EXPECT_EQ(10, array.bits_per_slot()); for(std::size_t i = 0; i < 1000; ++i){ array[i] = i; } for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } array.resize(1500); for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } for(std::size_t i = 1000; i < 1500; ++i){ EXPECT_EQ(0, uint64_t(array[i])); } } TEST(TestFixedLengthArray, test_thousand_values_template_8bit){ yunomi::array::ConstLengthArray<8> array(1000); EXPECT_EQ(1000, array.size()); EXPECT_EQ(8, array.bits_per_slot()); for(std::size_t i = 0; i < 1000; ++i){ array[i] = i % 256; } for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i % 256, uint64_t(array[i])); } array.resize(1500); for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i % 256, uint64_t(array[i])); } for(std::size_t i = 1000; i < 1500; ++i){ EXPECT_EQ(0, uint64_t(array[i])); } } TEST(TestFixedLengthArray, test_thousand_values_template_16bit){ yunomi::array::ConstLengthArray<16> array(1000); EXPECT_EQ(1000, array.size()); EXPECT_EQ(16, array.bits_per_slot()); for(std::size_t i = 0; i < 1000; ++i){ array[i] = i; } for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } array.resize(1500); for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } for(std::size_t i = 1000; i < 1500; ++i){ EXPECT_EQ(0, uint64_t(array[i])); } } TEST(TestFixedLengthArray, test_thousand_values_template_32bit){ yunomi::array::ConstLengthArray<32> array(1000); EXPECT_EQ(1000, array.size()); EXPECT_EQ(32, array.bits_per_slot()); for(std::size_t i = 0; i < 1000; ++i){ array[i] = i; } for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } array.resize(1500); for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } for(std::size_t i = 1000; i < 1500; ++i){ EXPECT_EQ(0, uint64_t(array[i])); } } TEST(TestFixedLengthArray, test_thousand_values_template_64bit){ yunomi::array::ConstLengthArray<64> array(1000); EXPECT_EQ(1000, array.size()); EXPECT_EQ(64, array.bits_per_slot()); for(std::size_t i = 0; i < 1000; ++i){ array[i] = i; } for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } array.resize(1500); for(std::size_t i = 0; i < 1000; ++i){ EXPECT_EQ(i, uint64_t(array[i])); } for(std::size_t i = 1000; i < 1500; ++i){ EXPECT_EQ(0, uint64_t(array[i])); } } //TODO write tests //TODO write tests for the size==0
29
64
0.576168
jnory
91b9c11ee85bd7fb70b44e8e5b0058dd47d0d269
7,635
hpp
C++
kernel/bb/Brick11/src/pilot.hpp
Bhaskers-Blu-Org2/Sora
6aa5411db71199e56d5cb24265b01a89f49b40f4
[ "BSD-2-Clause" ]
270
2015-07-17T15:43:43.000Z
2019-04-21T12:13:58.000Z
kernel/bb/Brick11/src/pilot.hpp
JamesLinus/Sora
6aa5411db71199e56d5cb24265b01a89f49b40f4
[ "BSD-2-Clause" ]
null
null
null
kernel/bb/Brick11/src/pilot.hpp
JamesLinus/Sora
6aa5411db71199e56d5cb24265b01a89f49b40f4
[ "BSD-2-Clause" ]
106
2015-07-20T10:40:34.000Z
2019-04-25T10:02:26.000Z
#pragma once #include "ieee80211a_cmn.h" #include "ieee80211facade.hpp" #include <intalg.h> // // Pilot sequence as defined in 802.11a // const char PilotSgn[128] = { 0, 0, 0, -1, -1, -1, 0, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, 0, 0, -1, 0, 0, -1, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, -1, -1, 0, 0, 0, -1, 0, -1, -1, -1, 0, -1, 0, -1, -1, 0, -1, -1, 0, 0, 0, 0, 0, -1, -1, 0, 0, -1, -1, 0, -1, 0, -1, 0, 0, -1, -1, -1, 0, 0, -1, -1, -1, -1, 0, -1, -1, 0, -1, 0, 0, 0, 0, -1, 0, -1, 0, -1, 0, -1, -1, -1, -1, -1, 0, -1, 0, 0, -1, 0, -1, 0, 0, 0, -1, -1, 0, -1, -1, -1, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, 0, 0, // # 127: reserved for PLCP signal }; DEFINE_LOCAL_CONTEXT(T11aAddPilot, CF_VOID); template<short BPSK_MOD = 10720> class T11aAddPilot { public: template<TFILTER_ARGS> class Filter : public TFilter<TFILTER_PARAMS> { private: uchar m_PilotIndex; void _init () { m_PilotIndex = 127; } public: DEFINE_IPORT(COMPLEX16, 48); DEFINE_OPORT(COMPLEX16, 64); public: REFERENCE_LOCAL_CONTEXT(Filter); STD_TFILTER_CONSTRUCTOR(Filter) { // The output symbols contain data subcarrriers, pilot subcarriers, and zero subcarriers. // Here we prepare the output pin queue with zero buffer, to make symbol composition easier. opin().zerobuf(); _init (); } STD_TFILTER_RESET() { _init (); } STD_TFILTER_FLUSH() { } BOOL_FUNC_PROCESS(ipin) { while (ipin.check_read()) { const COMPLEX16 *in = ipin.peek(); COMPLEX16 *out = opin().append(); add_pilot (out, in); m_PilotIndex++; if (m_PilotIndex >= 127) m_PilotIndex = 0; ipin.pop(); Next()->Process(opin()); } return true; } FINL void add_pilot (COMPLEX16* out, const COMPLEX16* in ) { ulong i; for (i = 64 - 26; i < 64; i++) { if (i == 64 - 7 || i == 64 - 21) continue; out[i] = *in; in ++; } for (i = 1; i <= 26; i++) { if (i == 7 || i == 21) continue; out[i] = *in; in ++; } if (!PilotSgn[m_PilotIndex]) { out[7].re = BPSK_MOD; out[7].im = 0; out[21].re = -BPSK_MOD; out[21].im = 0; out[64-7].re = BPSK_MOD; out[64-7].im = 0; out[64-21].re = BPSK_MOD; out[64-21].im = 0; } else { out[7].re = - BPSK_MOD; out[7].im = 0; out[21].re = BPSK_MOD; out[21].im = 0; out[64-7].re = - BPSK_MOD; out[64-7].im = 0; out[64-21].re = - BPSK_MOD; out[64-21].im = 0; } //printf ( "add pilot\n" ); //for ( int i=0; i< 16; i++ ) { // for (int j=0; j<4; j++ ) { // printf ( "<%d, %d> ", out[i*4+j].re, out[i*4+j].im ); // } // printf ( "\n" ); //} } }; }; // pilot freq compensation on 64 complexes DEFINE_LOCAL_CONTEXT(TPilotTrack, CF_PhaseCompensate, CF_PilotTrack, CF_11aRxVector); template<TFILTER_ARGS> class TPilotTrack : public TFilter<TFILTER_PARAMS> { private: CTX_VAR_RW (FP_RAD, CFO_tracker); CTX_VAR_RW (FP_RAD, SFO_tracker); CTX_VAR_RW (FP_RAD, CFO_comp ); CTX_VAR_RW (FP_RAD, SFO_comp ); CTX_VAR_RW (vcs, CompCoeffs, [16] ); CTX_VAR_RW (ulong, symbol_count); protected: FINL void _rotate ( vcs * dst, vcs * src, vcs * coeffs ) { rep_mul<7> (dst, src, coeffs ); rep_mul<7> (dst+9, src+9, coeffs+9 ); } FINL void _build_coeff ( COMPLEX16* pcoeffs, FP_RAD ave, FP_RAD delta ) { FP_RAD th = ave - delta * 26; int i; for (i = 64-26; i < 64; i++) { pcoeffs[i].re = ucos(th); pcoeffs[i].im = -usin(th); th += delta; } th += delta; // 0 subcarrier, dc // subcarrier 1 - 26 for (i = 1; i <= 26; i++) { pcoeffs[i].re = ucos(th); pcoeffs[i].im = -usin(th); th += delta; } } FINL void _pilot_track ( vcs * input, vcs * output ) { COMPLEX16* pc = (COMPLEX16*) input; // FP_RAD th1 = uatan2 ( pc[64-21].im, pc[64-21].re ); FP_RAD th2 = uatan2 ( pc[64-7].im, pc[64-7].re ); FP_RAD th3 = uatan2 ( pc[7].im, pc[7].re ); FP_RAD th4 = uatan2 ( -pc[21].im, -pc[21].re ); if (PilotSgn[symbol_count]) { th1 += FP_PI; th2 += FP_PI; th3 += FP_PI; th4 += FP_PI; } symbol_count++; if (symbol_count >= 127) symbol_count = 0; _dump_text ( "Pilots: <%d,%d> %d <%d,%d> %d <%d,%d> %d <%d,%d> %d \n\n", pc[64-21].re, pc[64-21].im, th1, pc[64-7].re, pc[64-7].im, th2, pc[7].re, pc[7].im, th3, pc[21].re, pc[21].im, th4 ); // subcarrier rotation = const_rotate + i * delta_rotate // estimate the const part FP_RAD avgTheta = (th1 + th2 + th3 + th4) / 4; // estimate the delta part FP_RAD delTheta = ((th3 - th1) / (21 + 7) + (th4 - th2) / (21 + 7)) >> 1; // pilot rotate vcs rotate_coeffs[16]; _build_coeff ( (COMPLEX16*) rotate_coeffs, avgTheta, delTheta ); _rotate ( output, input, rotate_coeffs ); // debug _dump_symbol<64>( "after pilot", (COMPLEX16*) output); // update tracker CFO_tracker += avgTheta >> 2; SFO_tracker += delTheta >> 2; CFO_comp += avgTheta + (CFO_tracker ); SFO_comp += delTheta + (SFO_tracker ); // Debug _dump_text ( "Tracker:: avg %lf del %lf CFO %lf SFO %lf\nFreqComp:: CFO %lf SFO %lf\n", fprad2rad (avgTheta), fprad2rad (delTheta), fprad2rad (CFO_tracker), fprad2rad (SFO_tracker), fprad2rad (CFO_comp), fprad2rad (SFO_comp) ); _build_coeff ( (COMPLEX16*) CompCoeffs, CFO_comp, SFO_comp ); } public: DEFINE_IPORT(COMPLEX16, 64); DEFINE_OPORT(COMPLEX16, 64); public: REFERENCE_LOCAL_CONTEXT(TPilotTrack); STD_TFILTER_CONSTRUCTOR(TPilotTrack) BIND_CONTEXT (CF_PilotTrack::CFO_tracker, CFO_tracker) BIND_CONTEXT (CF_PilotTrack::SFO_tracker, SFO_tracker) BIND_CONTEXT (CF_PilotTrack::symbol_count, symbol_count) BIND_CONTEXT (CF_PhaseCompensate::CFO_comp, CFO_comp) BIND_CONTEXT (CF_PhaseCompensate::SFO_comp, SFO_comp) BIND_CONTEXT (CF_PhaseCompensate::CompCoeffs, CompCoeffs) { } STD_TFILTER_RESET() { } BOOL_FUNC_PROCESS(ipin) { while (ipin.check_read()) { vcs *input = (vcs*)ipin.peek(); vcs *output = (vcs*)opin().append(); // _dump_symbol<64>("before pilot\n", (COMPLEX16*) input); _pilot_track ( input, output ); ipin.pop(); bool rc = Next()->Process(opin()); if (!rc) return false; } return true; } };
28.173432
101
0.472692
Bhaskers-Blu-Org2
91ba70ddc6aa008b545aa52db848a7b88fafef6e
1,238
cpp
C++
wpl1000/utility.cpp
ola-ct/gpstools
6a221553077139ad30e0ddf9ee155024ad7a4d26
[ "BSD-3-Clause" ]
null
null
null
wpl1000/utility.cpp
ola-ct/gpstools
6a221553077139ad30e0ddf9ee155024ad7a4d26
[ "BSD-3-Clause" ]
null
null
null
wpl1000/utility.cpp
ola-ct/gpstools
6a221553077139ad30e0ddf9ee155024ad7a4d26
[ "BSD-3-Clause" ]
null
null
null
// $Id$ // Copyright (c) 2009 Oliver Lau <oliver@ersatzworld.net> #include "stdafx.h" VOID Warn(LPTSTR lpszMessage) { MessageBox(NULL, (LPCTSTR)lpszMessage, TEXT("Fehler"), MB_OK); } VOID Error(LPTSTR lpszFunction, LONG lErrCode) { LPVOID lpMsgBuf; LPVOID lpDisplayBuf; if (lErrCode == 0) lErrCode = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, lErrCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR)); StringCchPrintf((LPTSTR)lpDisplayBuf, LocalSize(lpDisplayBuf) / sizeof(TCHAR), TEXT("%s fehlgeschlagen mit Fehler %d: %s"), lpszFunction, lErrCode, lpMsgBuf); MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Fehler"), MB_OK); LocalFree(lpMsgBuf); LocalFree(lpDisplayBuf); } VOID ErrorExit(LPTSTR lpszFunction, LONG lErrCode) { Error(lpszFunction, lErrCode); ExitProcess(lErrCode); }
27.511111
93
0.64378
ola-ct
91bbe1f1e423082754525c7a24e8c6c981b1580a
498
cpp
C++
DUT S2/M2103 - Prog Objet/cplus/tests_TPs/testTP1.cpp
Carduin/IUT
2642c23d3a3c4932ddaeb9d5f482be35def9273b
[ "MIT" ]
5
2022-02-08T09:36:54.000Z
2022-02-10T08:47:17.000Z
DUT S2/M2103 - Prog Objet/cplus/tests_TPs/testTP1.cpp
Carduin/IUT
2642c23d3a3c4932ddaeb9d5f482be35def9273b
[ "MIT" ]
null
null
null
DUT S2/M2103 - Prog Objet/cplus/tests_TPs/testTP1.cpp
Carduin/IUT
2642c23d3a3c4932ddaeb9d5f482be35def9273b
[ "MIT" ]
3
2021-12-10T16:11:46.000Z
2022-02-15T15:07:41.000Z
#include "Fenetre.h" #include "Souris.h" int main (int argc, char **argv){ gtk_init(&argc, &argv); Fenetre f; Souris s; int b, x, y; f.apparait("Test TP1",500,400,0,0,100,100,100); s.associerA(f); f.choixCouleurTrace(255,100,100); f.ecrit(10,100,"Bravo, vous avez bien parametre votre environnement !!"); f.choixCouleurTrace(0,0,0); f.ecrit(100,240,"CLIQUER POUR QUITTER"); while (!s.testeBoutons(x, y, b)); f.disparait(); return 0; }
17.172414
77
0.608434
Carduin
91bf84920e2f84cee2312fae1434faf045fc4cc4
622
cpp
C++
source/globjects/source/AttachedRenderbuffer.cpp
kateyy/globjects
4c5fc073063ca52ea32ce0adb57009a3c52f72a8
[ "MIT" ]
18
2016-09-03T05:12:25.000Z
2022-02-23T15:52:33.000Z
external/globjects-0.5.0/source/globjects/source/AttachedRenderbuffer.cpp
3d-scan/rgbd-recon
c4a5614eaa55dd93c74da70d6fb3d813d74f2903
[ "MIT" ]
1
2016-05-04T09:06:29.000Z
2016-05-04T09:06:29.000Z
external/globjects-0.5.0/source/globjects/source/AttachedRenderbuffer.cpp
3d-scan/rgbd-recon
c4a5614eaa55dd93c74da70d6fb3d813d74f2903
[ "MIT" ]
7
2016-04-20T13:58:50.000Z
2018-07-09T15:47:26.000Z
#include <globjects/AttachedRenderbuffer.h> #include <cassert> #include <globjects/Renderbuffer.h> using namespace gl; namespace globjects { AttachedRenderbuffer::AttachedRenderbuffer(Framebuffer * fbo, const GLenum attachment, Renderbuffer * renderBuffer) : FramebufferAttachment(fbo, attachment) , m_renderBuffer(renderBuffer) { } bool AttachedRenderbuffer::isRenderBufferAttachment() const { return true; } Renderbuffer * AttachedRenderbuffer::renderBuffer() { return m_renderBuffer; } const Renderbuffer * AttachedRenderbuffer::renderBuffer() const { return m_renderBuffer; } } // namespace globjects
17.771429
116
0.790997
kateyy
91bfc642eda962ce91587806eaa7a91d8024a553
4,510
cpp
C++
training/POJ/3728.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
68
2017-10-08T04:44:23.000Z
2019-08-06T20:15:02.000Z
training/POJ/3728.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
null
null
null
training/POJ/3728.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
18
2017-05-31T02:52:23.000Z
2019-07-05T09:18:34.000Z
// written at 09:33 on 5 Mar 2017 #include <cctype> #include <cfloat> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <string> #include <sstream> #include <algorithm> #include <complex> #include <deque> #include <list> #include <map> #include <queue> #include <set> #include <stack> #include <vector> #include <utility> #include <bitset> #include <numeric> #define IOS std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); // #define __DEBUG__ #ifdef __DEBUG__ #define DEBUG(...) printf(__VA_ARGS__) #else #define DEBUG(...) #endif #define filename "" #define setfile() freopen(filename".in", "r", stdin); freopen(filename".ans", "w", stdout); #define resetfile() freopen("/dev/tty", "r", stdin); freopen("/dev/tty", "w", stdout); system("more " filename".ans"); #define rep(i, j, k) for (int i = j; i < k; ++i) #define irep(i, j, k) for (int i = j - 1; i >= k; --i) using namespace std; template <typename T> inline T sqr(T a) { return a * a;}; typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef pair<int, int > Pii; const double pi = acos(-1.0); const int INF = INT_MAX; const ll LLINF = LLONG_MAX; const int MAX_V = 1e5 + 10; const int MAX_LOG_V = 20; int V, A[MAX_V], Q; vector<int> G[MAX_V]; int parent[MAX_LOG_V][MAX_V], depth[MAX_V]; int dp_max[MAX_LOG_V][MAX_V], dp_min[MAX_LOG_V][MAX_V]; int dp_up[MAX_LOG_V][MAX_V], dp_down[MAX_LOG_V][MAX_V]; void dfs(int v, int p, int d) { parent[0][v] = p; depth[v] = d; if (p != -1) { dp_max[0][v] = max(A[v], A[p]); dp_min[0][v] = min(A[v], A[p]); dp_up[0][v] = max(0, A[p] - A[v]); dp_down[0][v] = max(0, A[v] - A[p]); } for (int i = 0; i < G[v].size(); i++) if (G[v][i] != p) dfs(G[v][i], v, d + 1); } void init(int V) { memset(dp_max, 0, sizeof dp_max); memset(dp_min, 0x3f, sizeof dp_min); dfs(0, -1, 0); for (int k = 0; k + 1 < MAX_LOG_V; k++) for (int v = 0; v < V; v++) if (parent[k][v] < 0) parent[k + 1][v] = -1; else { int u = parent[k][v]; parent[k + 1][v] = parent[k][u]; dp_max[k + 1][v] = max(dp_max[k][v], dp_max[k][u]); dp_min[k + 1][v] = min(dp_min[k][v], dp_min[k][u]); dp_up[k + 1][v] = max(max(dp_up[k][v], dp_up[k][u]), dp_max[k][u] - dp_min[k][v]); dp_down[k + 1][v]= max(max(dp_down[k][v], dp_down[k][u]), dp_max[k][v] - dp_min[k][u]); } } int lca(int u, int v) { if (depth[u] > depth[v]) swap(u, v); for (int k = 0; k < MAX_LOG_V; k++) if ((depth[v] - depth[u]) >> k & 1) v = parent[k][v]; if (u == v) return u; for (int k = MAX_LOG_V - 1; k >= 0; k--) if (parent[k][v] != parent[k][u]) { v = parent[k][v]; u = parent[k][u]; } return parent[0][u]; } int up(int v, int s, int &imin) { imin = INF; int res = 0, pre_min = INF; for (int k = MAX_LOG_V - 1; k >= 0; k--) if (s >> k & 1) { imin = min(imin, dp_min[k][v]); res = max(res, dp_up[k][v]); res = max(res, dp_max[k][v] - pre_min); pre_min = min(pre_min, dp_min[k][v]); v = parent[k][v]; } return res; } int down(int v, int s, int &imax) { imax = 0; int res = 0, pre_max = 0; for (int k = MAX_LOG_V - 1; k >= 0; k--) if (s >> k & 1) { imax = max(imax, dp_max[k][v]); res = max(res, dp_down[k][v]); res = max(res, pre_max - dp_min[k][v]); pre_max = max(pre_max, dp_max[k][v]); v = parent[k][v]; } return res; } int main(int argc, char const *argv[]) { scanf("%d", &V); for (int i = 0; i < V; i++) scanf("%d", A + i); for (int i = 0, u, v; i < V - 1; i++) { scanf("%d%d", &u, &v); --u, --v; G[u].push_back(v); G[v].push_back(u); } init(V); scanf("%d", &Q); for (int i = 0, u, v; i < Q; i++) { scanf("%d%d", &u, &v); --u, --v; int p = lca(u, v); // cout << p << " " << u << "<->" << v << endl; int imax, imin; int iup = up(u, depth[u] - depth[p], imin); int idown = down(v, depth[v] - depth[p], imax); // cout << imin << " " << imax << endl; printf("%d\n", max(max(iup, idown), imax - imin)); } return 0; }
29.096774
118
0.497339
voleking
91c2b85dd910620172b6fd358a4f88b066339835
1,042
cpp
C++
test/HW_B2/tests_task_D.cpp
GAlekseyV/YandexTraining
e49ce6616e2584a80857a8b2f45b700f12b1fb85
[ "Unlicense" ]
1
2021-09-21T23:24:37.000Z
2021-09-21T23:24:37.000Z
test/HW_B2/tests_task_D.cpp
GAlekseyV/YandexTraining
e49ce6616e2584a80857a8b2f45b700f12b1fb85
[ "Unlicense" ]
null
null
null
test/HW_B2/tests_task_D.cpp
GAlekseyV/YandexTraining
e49ce6616e2584a80857a8b2f45b700f12b1fb85
[ "Unlicense" ]
null
null
null
#include <algorithm> #include <catch2/catch.hpp> #include <vector> std::vector<int> calc_ans(const std::vector<int> &seq, int l); TEST_CASE("D. Лавочки в атриуме", " ") { REQUIRE(calc_ans({ 0, 2 }, 5) == std::vector<int>{ 2 }); REQUIRE(calc_ans({ 1, 4, 8, 11 }, 13) == std::vector<int>{ 4, 8 }); REQUIRE(calc_ans({ 1, 6, 8, 11, 12, 13 }, 14) == std::vector<int>{ 6, 8 }); REQUIRE(calc_ans({ 0 }, 1) == std::vector<int>{ 0 }); } bool isOdd(long long n) { if (n % 2 == 1) { return true; } return false; } std::vector<int> calc_ans(const std::vector<int> &seq, int l) { int border = 0; std::vector<int> ans; if (seq.size() == 1) { ans.push_back(seq[0]); } else { border = l / 2; auto it = std::lower_bound(seq.begin(), seq.end(), border); if (isOdd(l)) { if (*(it) == border) { ans.push_back(*it); } else { ans.push_back(*(it - 1)); ans.push_back(*(it)); } } else { ans.push_back(*(it - 1)); ans.push_back(*(it)); } } return ans; }
22.170213
77
0.53167
GAlekseyV
91c4a0ead6e52ce6c394ce7b7155be6042fb6f51
1,684
cpp
C++
tests/src/test_colors.cpp
jegabe/ColorMyConsole
825855916f93279477051c54715fe76a99629c2a
[ "MIT" ]
null
null
null
tests/src/test_colors.cpp
jegabe/ColorMyConsole
825855916f93279477051c54715fe76a99629c2a
[ "MIT" ]
null
null
null
tests/src/test_colors.cpp
jegabe/ColorMyConsole
825855916f93279477051c54715fe76a99629c2a
[ "MIT" ]
null
null
null
// (c) 2021 Jens Ganter-Benzing. Licensed under the MIT license. #include <iostream> #include <colmc/setup.h> #include <colmc/sequences.h> using namespace colmc; struct color { const char* esc_sequence; const char* name; }; const struct color bg_colors[] = { { back::black, "black " }, { back::red, "red " }, { back::green, "green " }, { back::yellow, "yellow " }, { back::blue, "blue " }, { back::magenta, "magenta" }, { back::cyan, "cyan " }, { back::white, "white " } }; const struct color fg_colors[] = { { fore::black, "black " }, { fore::red, "red " }, { fore::green, "green " }, { fore::yellow, "yellow " }, { fore::blue, "blue " }, { fore::magenta, "magenta" }, { fore::cyan, "cyan " }, { fore::white, "white " } }; int main() { setup(); std::cout << " "; for (std::size_t fg_index = 0; fg_index < (sizeof(fg_colors)/sizeof(fg_colors[0])); ++fg_index) { std::cout << fg_colors[fg_index].esc_sequence << fg_colors[fg_index].name; } std::cout << std::endl; for (std::size_t bg_index = 0; bg_index < (sizeof(bg_colors)/sizeof(bg_colors[0])); ++bg_index) { std::cout << bg_colors[bg_index].esc_sequence << fore::reset << bg_colors[bg_index].name; for (std::size_t fg_index = 0; fg_index < (sizeof(fg_colors)/sizeof(fg_colors[0])); ++fg_index) { std::cout << back::reset << " "; std::cout << bg_colors[bg_index].esc_sequence; std::cout << fg_colors[fg_index].esc_sequence << fore::dim << "X " << fore::normal << "X " << fore::bright << "X " << reset_all; } std::cout << std::endl; } std::cout << reset_all << "Press return to terminate"; std::cin.get(); return 0; }
30.071429
132
0.589074
jegabe
91c6879681bb3ad66670d6360cc3f0a4fac38d31
2,807
cp
C++
Comm/Mod/Streams.cp
romiras/Blackbox-fw-playground
6de94dc65513e657a9b86c1772e2c07742b608a8
[ "BSD-2-Clause" ]
1
2016-03-17T08:27:05.000Z
2016-03-17T08:27:05.000Z
Comm/Mod/Streams.cps
Spirit-of-Oberon/LightBox
8a45ed11dcc02ae97e86f264dcee3e07c910ff9d
[ "BSD-2-Clause" ]
null
null
null
Comm/Mod/Streams.cps
Spirit-of-Oberon/LightBox
8a45ed11dcc02ae97e86f264dcee3e07c910ff9d
[ "BSD-2-Clause" ]
1
2018-03-14T17:53:27.000Z
2018-03-14T17:53:27.000Z
MODULE CommStreams; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = "" issues = "" **) IMPORT Meta; CONST (* portable error codes: *) done* = 0; noSuchProtocol* = 1; invalidLocalAdr* = 2; invalidRemoteAdr* = 3; networkDown* = 4; localAdrInUse* = 5; remoteAdrInUse* = 6; TYPE Adr* = POINTER TO ARRAY OF CHAR; Stream* = POINTER TO ABSTRACT RECORD END; StreamAllocator* = PROCEDURE (localAdr, remoteAdr: ARRAY OF CHAR; OUT s: Stream; OUT res: INTEGER); Listener* = POINTER TO ABSTRACT RECORD END; ListenerAllocator* = PROCEDURE (localAdr: ARRAY OF CHAR; OUT l: Listener; OUT res: INTEGER); PROCEDURE (s: Stream) RemoteAdr* (): Adr, NEW, ABSTRACT; PROCEDURE (s: Stream) IsConnected* (): BOOLEAN, NEW, ABSTRACT; PROCEDURE (s: Stream) WriteBytes* ( IN x: ARRAY OF BYTE; beg, len: INTEGER; OUT written: INTEGER), NEW, ABSTRACT; PROCEDURE (s: Stream) ReadBytes* ( VAR x: ARRAY OF BYTE; beg, len: INTEGER; OUT read: INTEGER), NEW, ABSTRACT; PROCEDURE (s: Stream) Close*, NEW, ABSTRACT; PROCEDURE NewStream* (protocol, localAdr, remoteAdr: ARRAY OF CHAR; OUT s: Stream; OUT res: INTEGER); VAR ok: BOOLEAN; m, p: Meta.Item; mod: Meta.Name; v: RECORD (Meta.Value) p: StreamAllocator END; BEGIN ASSERT(protocol # "", 20); res := noSuchProtocol; mod := protocol$; Meta.Lookup(mod, m); IF m.obj = Meta.modObj THEN m.Lookup("NewStream", p); IF p.obj = Meta.procObj THEN p.GetVal(v, ok); IF ok THEN v.p(localAdr, remoteAdr, s, res) END END END END NewStream; PROCEDURE (l: Listener) LocalAdr* (): Adr, NEW, ABSTRACT; PROCEDURE (l: Listener) Accept* (OUT s: Stream), NEW, ABSTRACT; PROCEDURE (l: Listener) Close*, NEW, ABSTRACT; PROCEDURE NewListener* (protocol, localAdr: ARRAY OF CHAR; OUT l: Listener; OUT res: INTEGER); VAR ok: BOOLEAN; m, p: Meta.Item; mod: Meta.Name; v: RECORD(Meta.Value) p: ListenerAllocator END; BEGIN ASSERT(protocol # "", 20); res := noSuchProtocol; mod := protocol$; Meta.Lookup(mod, m); IF m.obj = Meta.modObj THEN m.Lookup("NewListener", p); IF p.obj = Meta.procObj THEN p.GetVal(v, ok); IF ok THEN v.p(localAdr, l, res) END END END END NewListener; END CommStreams.
32.639535
105
0.56466
romiras
91ca06b4ec287cce73acf4d73eb84dcf5e090adb
587
hxx
C++
src/include/Elastic/Apm/Config/IRawSnapshot.hxx
SergeyKleyman/elastic-apm-agent-cpp-prototype
67d2c7ad5a50e1a6b75d6725a89ae3fc5a92d517
[ "Apache-2.0" ]
null
null
null
src/include/Elastic/Apm/Config/IRawSnapshot.hxx
SergeyKleyman/elastic-apm-agent-cpp-prototype
67d2c7ad5a50e1a6b75d6725a89ae3fc5a92d517
[ "Apache-2.0" ]
null
null
null
src/include/Elastic/Apm/Config/IRawSnapshot.hxx
SergeyKleyman/elastic-apm-agent-cpp-prototype
67d2c7ad5a50e1a6b75d6725a89ae3fc5a92d517
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Elastic/Apm/Util/String.hxx" #include "Elastic/Apm/Util/Optional.hxx" namespace Elastic { namespace Apm { namespace Config { using namespace Elastic::Apm; class IRawSnapshot { protected: using String = Util::String; template< typename T > using Optional = Util::Optional< T >; public: struct ValueData { String value; String dbgValueSourceDesc; }; virtual Optional< ValueData > operator[]( const char* optName ) const = 0; protected: ~IRawSnapshot() = default; }; } } } // namespace Elastic::Apm::Config
16.305556
78
0.667802
SergeyKleyman
91cad30ec6590d8dda7374c959f0048d19154093
467
cpp
C++
src/receivers/evaluator/IdentifierReceiverEvaluator.cpp
benhj/arrow
a88caec0bcf44f70343d6f8d3a4be5790d903ddb
[ "MIT" ]
19
2019-12-10T07:35:08.000Z
2021-09-27T11:49:37.000Z
src/receivers/evaluator/IdentifierReceiverEvaluator.cpp
benhj/arrow
a88caec0bcf44f70343d6f8d3a4be5790d903ddb
[ "MIT" ]
22
2020-02-09T15:39:53.000Z
2020-03-02T19:04:40.000Z
src/receivers/evaluator/IdentifierReceiverEvaluator.cpp
benhj/arrow
a88caec0bcf44f70343d6f8d3a4be5790d903ddb
[ "MIT" ]
2
2020-02-17T21:20:43.000Z
2020-03-02T00:42:08.000Z
/// (c) Ben Jones 2019 #include "IdentifierReceiverEvaluator.hpp" #include "parser/LanguageException.hpp" #include <utility> namespace arrow { IdentifierReceiverEvaluator::IdentifierReceiverEvaluator(Token tok) : m_tok(std::move(tok)) { } void IdentifierReceiverEvaluator::evaluate(Type incoming, Environment & environment) const { // automatically does a replace environment.add(m_tok.raw, std::move(incoming)); } }
24.578947
94
0.702355
benhj
91ce8c90b43c369c3352048a25ece820de97be26
814
cpp
C++
src/Frameworks/PythonFramework/PythonSchedulePipe.cpp
Terryhata6/Mengine
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
[ "MIT" ]
39
2016-04-21T03:25:26.000Z
2022-01-19T14:16:38.000Z
src/Frameworks/PythonFramework/PythonSchedulePipe.cpp
Terryhata6/Mengine
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
[ "MIT" ]
23
2016-06-28T13:03:17.000Z
2022-02-02T10:11:54.000Z
src/Frameworks/PythonFramework/PythonSchedulePipe.cpp
Terryhata6/Mengine
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
[ "MIT" ]
14
2016-06-22T20:45:37.000Z
2021-07-05T12:25:19.000Z
#include "PythonSchedulePipe.h" namespace Mengine { ////////////////////////////////////////////////////////////////////////// PythonSchedulePipe::PythonSchedulePipe() { } ////////////////////////////////////////////////////////////////////////// PythonSchedulePipe::~PythonSchedulePipe() { } ////////////////////////////////////////////////////////////////////////// void PythonSchedulePipe::initialize( const pybind::object & _cb, const pybind::args & _args ) { m_cb = _cb; m_args = _args; } ////////////////////////////////////////////////////////////////////////// float PythonSchedulePipe::onSchedulerPipe( uint32_t _id, uint32_t _index ) { float delay = m_cb.call_args( _id, _index, m_args ); return delay; } }
31.307692
97
0.388206
Terryhata6
91d1246dbb9d80b62a7368a32a0b933ea8a5ccea
5,318
cpp
C++
services/common/platform/os_wrapper/feature/source/slide_window_processor.cpp
openharmony-gitee-mirror/ai_engine
abf3eee0b07b68ff49e984d787545c532370f973
[ "Apache-2.0" ]
2
2021-10-03T08:57:00.000Z
2021-10-03T12:28:52.000Z
services/common/platform/os_wrapper/feature/source/slide_window_processor.cpp
openharmony-gitee-mirror/ai_engine
abf3eee0b07b68ff49e984d787545c532370f973
[ "Apache-2.0" ]
null
null
null
services/common/platform/os_wrapper/feature/source/slide_window_processor.cpp
openharmony-gitee-mirror/ai_engine
abf3eee0b07b68ff49e984d787545c532370f973
[ "Apache-2.0" ]
2
2021-09-13T11:15:25.000Z
2021-10-03T08:57:11.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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 "slide_window_processor.h" #include <memory> #include "aie_log.h" #include "aie_macros.h" #include "aie_retcode_inner.h" #include "securec.h" using namespace OHOS::AI::Feature; namespace { const uint8_t ILLEGAL_BUFFER_MULTIPLIER = 0; } SlideWindowProcessor::SlideWindowProcessor() : isInitialized_(false), workBuffer_(nullptr), inputFeature_(nullptr), inType_(UNKNOWN), typeSize_(0), startIndex_(0), initIndex_(0), bufferSize_(0), windowSize_(0), stepSize_(0) {} SlideWindowProcessor::~SlideWindowProcessor() { Release(); } int32_t SlideWindowProcessor::Init(const FeatureProcessorConfig *config) { if (isInitialized_) { HILOGE("[SlideWindowProcessor]Fail to init more than once. Release it, then try again"); return RETCODE_FAILURE; } if (config == nullptr) { HILOGE("[SlideWindowProcessor]Fail to init with null config"); return RETCODE_FAILURE; } auto localConfig = *(static_cast<const SlideWindowProcessorConfig *>(config)); if (localConfig.dataType == UNKNOWN) { HILOGE("[SlideWindowProcessor]Fail with unsupported dataType[UNKNOWN]"); return RETCODE_FAILURE; } if (localConfig.windowSize < localConfig.stepSize) { HILOGE("[SlideWindowProcessor]Illegal configuration. The stepSize cannot be greater than windowSize"); return RETCODE_FAILURE; } if (localConfig.bufferMultiplier == ILLEGAL_BUFFER_MULTIPLIER) { HILOGE("[SlideWindowProcessor]Illegal configuration. The bufferMultiplier cannot be zero"); return RETCODE_FAILURE; } inType_ = localConfig.dataType; typeSize_ = CONVERT_DATATYPE_TO_SIZE(inType_); windowSize_ = localConfig.windowSize; stepSize_ = localConfig.stepSize * typeSize_; initIndex_ = (windowSize_ * typeSize_) - stepSize_; startIndex_ = initIndex_; bufferSize_ = (windowSize_ * localConfig.bufferMultiplier) * typeSize_; if (windowSize_ > MAX_SAMPLE_SIZE) { HILOGE("[SlideWindowProcessor]The required memory size is larger than MAX_SAMPLE_SIZE[%zu]", MAX_SAMPLE_SIZE); return RETCODE_FAILURE; } AIE_NEW(workBuffer_, char[bufferSize_]); if (workBuffer_ == nullptr) { HILOGE("[SlideWindowProcessor]Fail to allocate memory for workBuffer"); return RETCODE_FAILURE; } (void)memset_s(workBuffer_, bufferSize_, 0, bufferSize_); inputFeature_ = workBuffer_; isInitialized_ = true; return RETCODE_SUCCESS; } void SlideWindowProcessor::Release() { AIE_DELETE_ARRAY(workBuffer_); inputFeature_ = nullptr; isInitialized_ = false; } int32_t SlideWindowProcessor::Process(const FeatureData &input, FeatureData &output) { if (!isInitialized_) { HILOGE("[SlideWindowProcessor]Fail to process without successfully init"); return RETCODE_FAILURE; } if (input.dataType != inType_) { HILOGE("[SlideWindowProcessor]Fail with unmatched input dataType"); return RETCODE_FAILURE; } if (input.data == nullptr || input.size == 0) { HILOGE("[SlideWindowProcessor]Fail with NULL input"); return RETCODE_FAILURE; } size_t inputBytes = input.size * typeSize_; if (inputBytes != stepSize_) { HILOGE("[SlideWindowProcessor]Fail with unmatched input dataSize, expected [%zu]", stepSize_ / typeSize_); return RETCODE_FAILURE; } if (output.data != nullptr || output.size != 0) { HILOGE("[SlideWindowProcessor]Fail with non-empty output"); return RETCODE_FAILURE; } output.dataType = inType_; // Update the last window by the input data of new window errno_t retCode = memcpy_s(workBuffer_ + startIndex_, bufferSize_ - startIndex_, input.data, inputBytes); if (retCode != EOK) { HILOGE("[SlideWindowProcessor]Fail to copy input data to workBuffer [%d]", retCode); return RETCODE_FAILURE; } output.data = inputFeature_; output.size = windowSize_; startIndex_ += stepSize_; // Slide to the next position inputFeature_ += stepSize_; // Post-processing if (bufferSize_ - startIndex_ < stepSize_) { errno_t retCode = memmove_s(workBuffer_, bufferSize_, inputFeature_, initIndex_); if (retCode != EOK) { HILOGE("[SlideWindowProcessor]Fail with memory move. Error code[%d]", retCode); return RETCODE_FAILURE; } startIndex_ = initIndex_; inputFeature_ = workBuffer_; } return RETCODE_SUCCESS; }
36.176871
115
0.672245
openharmony-gitee-mirror
91d1a1704e26fdad9ce7d50a91d33736456872b1
2,677
cpp
C++
src/EnemyController.cpp
CS126SP20/final-project-Tejesh2001
70a5d11504f968714392c92d70c472c38e4b0116
[ "MIT" ]
null
null
null
src/EnemyController.cpp
CS126SP20/final-project-Tejesh2001
70a5d11504f968714392c92d70c472c38e4b0116
[ "MIT" ]
null
null
null
src/EnemyController.cpp
CS126SP20/final-project-Tejesh2001
70a5d11504f968714392c92d70c472c38e4b0116
[ "MIT" ]
1
2020-09-06T12:47:47.000Z
2020-09-06T12:47:47.000Z
#pragma once #include "mylibrary/EnemyController.h" #include <cinder/app/AppBase.h> #include "cinder/Rand.h" #include "mylibrary/CoordinateConversions.h" #include "mylibrary/ProjectWideConstants.h" namespace mylibrary { using std::list; EnemyController::EnemyController() = default; void EnemyController::setup(b2World &my_world) { // Setting up world and location for test world_ = &my_world; location_for_test = new b2Vec2(0, 0); } void EnemyController::update() { for (auto p = enemies.begin(); p != enemies.end();) { // if the enemy is dead, it removes the body if (!enemies.empty() && p->IsDead()) { world_->DestroyBody(p->GetBody()); p = enemies.erase(p); } else { p->update(); ++p; } } } void EnemyController::draw() { for (auto &particle : enemies) { particle.draw(); } } void EnemyController::AddEnemies(int amount) { int kTestAmount = 3; // I add 3 enemies in my test cases there test amount is three float world_width; if (amount <= kTestAmount) { world_width = global::kLeftMostIndex; } else { world_width = (conversions::ToBox2DCoordinates( static_cast<float>(cinder::app::getWindowWidth()))); } for (int i = 0; i < amount; i++) { b2BodyDef body_def; body_def.type = b2_dynamicBody; // Sets the position of the enemy on top of the screen somewhere if (location_for_test->y != global::kLowerMostIndex) { body_def.position.Set(ci::randFloat(world_width), global::kLowerMostIndex); } else { body_def.position.Set(location_for_test->x, location_for_test->y); location_for_test->y = kActualY; } CreateBody(body_def); } } b2BodyDef &EnemyController::CreateBody(b2BodyDef &body_def) { Enemy enemy; // Creating enemy and its corresponding properties body_def.userData = &enemy; body_def.bullet = true; enemy.SetBody(world_->CreateBody(&body_def)); b2PolygonShape dynamic_box; // Setting dimensions of enemy dynamic_box.SetAsBox( conversions::ToBox2DCoordinates(global::kBoxDimensions.x), conversions::ToBox2DCoordinates(global::kBoxDimensions.y)); b2FixtureDef fixture_def; // Setting properties of fixture fixture_def.shape = &dynamic_box; fixture_def.density = global::kDensity; fixture_def.friction = global::kFriction; fixture_def.restitution = global::kRestitution / kBounceLimiter; // bounce // Setting body properties enemy.GetBody()->CreateFixture(&fixture_def); enemy.setup(global::kBoxDimensions); enemies.push_back(enemy); return body_def; } std::list<Enemy> &EnemyController::GetEnemies() { return enemies; } } // namespace mylibrary
29.417582
77
0.694061
CS126SP20
91d36c33b4309f5b67ce330f27d457282e6e7748
3,077
cpp
C++
tests/test_task_wine.cpp
accosmin/zob
9e840894ffd6ab718fa800aca67e4a25e941e546
[ "MIT" ]
6
2015-04-14T19:42:38.000Z
2015-11-12T17:41:35.000Z
tests/test_task_wine.cpp
cyy1991/nano
9e840894ffd6ab718fa800aca67e4a25e941e546
[ "MIT" ]
93
2015-04-10T19:02:38.000Z
2016-03-09T17:56:16.000Z
tests/test_task_wine.cpp
accosmin/zob
9e840894ffd6ab718fa800aca67e4a25e941e546
[ "MIT" ]
2
2015-05-27T16:42:31.000Z
2015-08-21T14:39:55.000Z
#include "task.h" #include "utest.h" using namespace nano; NANO_BEGIN_MODULE(test_wine) NANO_CASE(failed) { const auto task = get_tasks().get("wine"); NANO_REQUIRE(task); task->from_json(to_json("path", "/dev/null?!")); NANO_CHECK(!task->load()); } NANO_CASE(default_config) { const auto task = nano::get_tasks().get("wine"); NANO_REQUIRE(task); json_t json; task->to_json(json); size_t folds = 0; from_json(json, "folds", folds); NANO_CHECK_EQUAL(folds, 10u); } NANO_CASE(loading) { const auto idims = tensor3d_dim_t{13, 1, 1}; const auto odims = tensor3d_dim_t{3, 1, 1}; const auto target_sum = scalar_t(2) - static_cast<scalar_t>(nano::size(odims)); const auto folds = size_t(10); const auto samples = size_t(178); const auto task = nano::get_tasks().get("wine"); NANO_REQUIRE(task); task->from_json(to_json("folds", folds)); NANO_REQUIRE(task->load()); task->describe("wine"); NANO_CHECK_EQUAL(task->idims(), idims); NANO_CHECK_EQUAL(task->odims(), odims); NANO_CHECK_EQUAL(task->fsize(), folds); NANO_CHECK_EQUAL(task->size(), folds * samples); for (size_t f = 0; f < task->fsize(); ++ f) { for (const auto p : {protocol::train, protocol::valid, protocol::test}) { for (size_t i = 0, size = task->size({f, p}); i < size; ++ i) { const auto sample = task->get({f, p}, i, i + 1); const auto& input = sample.idata(0); const auto& target = sample.odata(0); NANO_CHECK_EQUAL(input.dims(), idims); NANO_CHECK_EQUAL(target.dims(), odims); NANO_CHECK_CLOSE(target.vector().sum(), target_sum, epsilon0<scalar_t>()); } NANO_CHECK_EQUAL(task->labels({f, p}).size(), static_cast<size_t>(nano::size(odims))); } NANO_CHECK_EQUAL(task->size({f, protocol::train}), 40 * samples / 100); NANO_CHECK_EQUAL(task->size({f, protocol::valid}), 30 * samples / 100); NANO_CHECK_EQUAL(task->size({f, protocol::test}), 54); NANO_CHECK_EQUAL( task->size({f, protocol::train}) + task->size({f, protocol::valid}) + task->size({f, protocol::test}), task->size() / task->fsize()); NANO_CHECK_LESS_EQUAL(task->duplicates(f), size_t(0)); NANO_CHECK_LESS_EQUAL(task->intersections(f), size_t(0)); } NANO_CHECK_LESS_EQUAL(task->duplicates(), size_t(0)); NANO_CHECK_LESS_EQUAL(task->intersections(), size_t(0)); NANO_CHECK_EQUAL(task->labels().size(), static_cast<size_t>(nano::size(odims))); } NANO_END_MODULE()
34.573034
110
0.524212
accosmin
91d6c987140b6541aca2aed66d50f33a51601c24
4,924
cpp
C++
dev/Code/Sandbox/Editor/PropertiesDialog.cpp
crazyskateface/lumberyard
164512f8d415d6bdf37e195af319ffe5f96a8f0b
[ "AML" ]
5
2018-08-17T21:05:55.000Z
2021-04-17T10:48:26.000Z
dev/Code/Sandbox/Editor/PropertiesDialog.cpp
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
null
null
null
dev/Code/Sandbox/Editor/PropertiesDialog.cpp
JulianoCristian/Lumberyard-3
dc523dd780f3cd1874251181b7cf6848b8db9959
[ "AML" ]
5
2017-12-05T16:36:00.000Z
2021-04-27T06:33:54.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "stdafx.h" #include "PropertiesDialog.h" ///////////////////////////////////////////////////////////////////////////// // CPropertiesDialog dialog CPropertiesDialog::CPropertiesDialog(const CString& title, XmlNodeRef& node, CWnd* pParent /*=NULL*/, bool bShowSearchBar /*=false*/) : CXTResizeDialog(CPropertiesDialog::IDD, pParent) { //{{AFX_DATA_INIT(CPropertiesDialog) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT m_bShowSearchBar = bShowSearchBar; m_title = title; m_node = node; } void CPropertiesDialog::DoDataExchange(CDataExchange* pDX) { CXTResizeDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CPropertiesDialog) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CPropertiesDialog, CXTResizeDialog) //{{AFX_MSG_MAP(CPropertiesDialog) ON_WM_DESTROY() ON_WM_CLOSE() ON_WM_SIZE() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CPropertiesDialog message handlers BOOL CPropertiesDialog::OnInitDialog() { CXTResizeDialog::OnInitDialog(); SetWindowText(m_title); CRect rc; GetClientRect(rc); m_wndProps.Create(WS_CHILD | WS_VISIBLE | WS_BORDER, rc, this); m_wndProps.SetUpdateCallback(functor(*this, &CPropertiesDialog::OnPropertyChange)); if (m_bShowSearchBar) { int inputH = 18; m_searchLabel.Create("Search:", WS_CHILD | WS_VISIBLE, rc, this, NULL); m_searchLabel.ModifyStyleEx(WS_EX_CLIENTEDGE, 0); m_input.Create(WS_CHILD | WS_VISIBLE | ES_WANTRETURN | ES_AUTOHSCROLL | WS_TABSTOP, rc, this, NULL); m_input.SetFont(CFont::FromHandle((HFONT)::GetStockObject(SYSTEM_FONT))); m_input.ModifyStyleEx(0, WS_EX_STATICEDGE); m_input.SetWindowText(""); m_wndProps.MoveWindow(rc.left + 4, rc.top + 10 + inputH, rc.right - 8, rc.bottom - 28 - inputH, true); } else { m_wndProps.MoveWindow(rc.left + 4, rc.top + 4, rc.right - 8, rc.bottom - 24, true); } if (m_node) { m_wndProps.CreateItems(m_node); } AutoLoadPlacement("Dialogs\\PropertyDlg"); ConfigureLayout(); if (m_bShowSearchBar) { m_input.SetFocus(); } return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } BOOL CPropertiesDialog::PreTranslateMessage(MSG* msg) { if (msg->message == WM_KEYUP) { if (m_bShowSearchBar && (&m_input == GetFocus())) { CString result; m_input.GetWindowText(result); m_wndProps.RestrictToItemsContaining(result); } } else if (msg->message == WM_KEYDOWN) { if (msg->wParam == VK_RETURN) { // Hey, dialog, please don't gobble up the enter key. // It's necessary for edit controls within the property control to work optimally. m_wndProps.SendMessage(WM_KEYDOWN, VK_RETURN, 0); } } return CXTResizeDialog::PreTranslateMessage(msg); } void CPropertiesDialog::OnDestroy() { CXTResizeDialog::OnDestroy(); } void CPropertiesDialog::OnClose() { // reset search bar information m_wndProps.RestrictToItemsContaining(""); m_wndProps.RemoveAllItems(); CXTResizeDialog::OnClose(); } void CPropertiesDialog::OnSize(UINT nType, int cx, int cy) { CXTResizeDialog::OnSize(nType, cx, cy); if (m_wndProps.m_hWnd) { ConfigureLayout(); } } void CPropertiesDialog::ConfigureLayout() { CRect rc; GetClientRect(rc); if (m_bShowSearchBar) { int inputH = 18; m_searchLabel.MoveWindow(rc.left + 4, rc.top + 4, 50, inputH, SWP_NOZORDER); m_input.MoveWindow(rc.left + 58, rc.top + 4, rc.right - 4 - 58, inputH, SWP_NOZORDER); m_wndProps.MoveWindow(rc.left + 4, rc.top + 10 + inputH, rc.right - 8, rc.bottom - 28 - inputH, true); } else { m_wndProps.MoveWindow(rc.left + 4, rc.top + 4, rc.right - 8, rc.bottom - 24, true); } } void CPropertiesDialog::OnPropertyChange(IVariable* pVar) { if (m_varCallback) { m_varCallback(pVar); } } void CPropertiesDialog::OnCancel() { DestroyWindow(); }
26.907104
133
0.647238
crazyskateface
91d9b1be00d77e8275bd5320f99ca23afed93674
509
hpp
C++
src/Engine/Scene/Scene.hpp
Liljan/Ape-Engine
174842ada3a565e83569722837b242fa9faa4114
[ "MIT" ]
null
null
null
src/Engine/Scene/Scene.hpp
Liljan/Ape-Engine
174842ada3a565e83569722837b242fa9faa4114
[ "MIT" ]
null
null
null
src/Engine/Scene/Scene.hpp
Liljan/Ape-Engine
174842ada3a565e83569722837b242fa9faa4114
[ "MIT" ]
null
null
null
#pragma once #include "Engine/Datatypes.hpp" #include <SFML/Graphics/RenderWindow.hpp> class SceneManager; class ResourceManager; class Scene { public: ~Scene() = default; virtual void HandleInput(sf::Event& event) = 0; virtual void Update(float dt) = 0; virtual void Draw(sf::RenderWindow& window) = 0; virtual void Load() = 0; virtual void Unload() = 0; virtual uint32 GetType() const = 0; protected: SceneManager* m_SceneManager = nullptr; ResourceManager* m_ResourceManager = nullptr; };
18.178571
49
0.72888
Liljan
91daa744e6036e1ebcf5ffd4390aefcb7762e1e3
3,539
cpp
C++
HackerRank/SherlocAndMiniMax.cpp
andrasigneczi/cpp_lang_taining
1198df6a896d0f6fce281e069abba88ef40598fc
[ "Apache-2.0" ]
null
null
null
HackerRank/SherlocAndMiniMax.cpp
andrasigneczi/cpp_lang_taining
1198df6a896d0f6fce281e069abba88ef40598fc
[ "Apache-2.0" ]
null
null
null
HackerRank/SherlocAndMiniMax.cpp
andrasigneczi/cpp_lang_taining
1198df6a896d0f6fce281e069abba88ef40598fc
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ull = unsigned long long; vector<string> split_string(string); // Complete the sherlockAndMinimax function below. int sherlockAndMinimax_(vector<int> arr, int p, int q) { set<int> arr2(arr.begin(), arr.end()); int retVal = p; int maX = -1; int beg = p; int end = q; // special cases if(*arr2.begin() >= q) { return p; } else if(*prev(arr2.end()) <= p) { return q; } else if(*arr2.begin() > p && *arr2.begin() < q) { retVal = p; maX = abs(p - *arr2.begin()); beg = *arr2.begin(); } for(int i = beg; i <= end; ++i) { auto it = arr2.lower_bound(i); if(it == arr2.end()) { /* int tmp = max(maX, abs(i - *prev(arr2.end()))); if(tmp != maX) { maX = tmp; retVal = i; } */ int tmp = max(maX, abs(q - *prev(arr2.end()))); if(tmp != maX) { maX = tmp; retVal = q; } break; } else { if(*it != i) { // I need the min of prev and this one auto prv = prev(it); int tmp; if(prv != arr2.end()) { int m = min(abs(i - *prv), abs(i - *it)); tmp = max(maX, m); } else { tmp = max(maX, abs(i - *it)); } if(tmp != maX) { maX = tmp; retVal = i; } } else { // min() = 0, nothin to do } } //cout << "i: " << i << " maX: " << maX << " retVal: " << retVal << "\n"; } return retVal; } int sherlockAndMinimax(vector<int> arr, int p, int q) { set<int> arr2(arr.begin(), arr.end()); int retVal = p; int maX = -1; int beg = p; int end = q; // special cases if(*arr2.begin() >= q) { return p; } else if(*prev(arr2.end()) <= p) { return q; } } int main() { ofstream fout(getenv("OUTPUT_PATH")); int n; cin >> n; cin.ignore(numeric_limits<streamsize>::max(), '\n'); string arr_temp_temp; getline(cin, arr_temp_temp); vector<string> arr_temp = split_string(arr_temp_temp); vector<int> arr(n); for (int i = 0; i < n; i++) { int arr_item = stoi(arr_temp[i]); arr[i] = arr_item; } string pq_temp; getline(cin, pq_temp); vector<string> pq = split_string(pq_temp); int p = stoi(pq[0]); int q = stoi(pq[1]); int result = sherlockAndMinimax(arr, p, q); fout << result << "\n"; fout.close(); return 0; } vector<string> split_string(string input_string) { string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { return x == y and x == ' '; }); input_string.erase(new_end, input_string.end()); while (input_string[input_string.length() - 1] == ' ') { input_string.pop_back(); } vector<string> splits; char delimiter = ' '; size_t i = 0; size_t pos = input_string.find(delimiter); while (pos != string::npos) { splits.push_back(input_string.substr(i, pos - i)); i = pos + 1; pos = input_string.find(delimiter, i); } splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); return splits; }
23.751678
115
0.472167
andrasigneczi
91de5fa1a8e651537de6d2da28989c95dbbf40f9
10,420
cpp
C++
Source/Mesh.cpp
DavidColson/Polybox
6c3d5939c4baa124e5113fd4146a654f6005e7f6
[ "MIT" ]
252
2021-08-18T10:43:37.000Z
2022-03-20T18:43:59.000Z
Source/Mesh.cpp
DavidColson/Polybox
6c3d5939c4baa124e5113fd4146a654f6005e7f6
[ "MIT" ]
3
2021-12-01T09:08:33.000Z
2022-01-14T08:56:19.000Z
Source/Mesh.cpp
DavidColson/Polybox
6c3d5939c4baa124e5113fd4146a654f6005e7f6
[ "MIT" ]
10
2021-11-30T16:17:54.000Z
2022-03-28T17:56:18.000Z
#include "Mesh.h" #include "Core/Json.h" #include "Core/Base64.h" #include <SDL_rwops.h> #include <string> // *********************************************************************** int Primitive::GetNumVertices() { return (int)m_vertices.size(); } // *********************************************************************** Vec3f Primitive::GetVertexPosition(int index) { return m_vertices[index].pos; } // *********************************************************************** Vec4f Primitive::GetVertexColor(int index) { return m_vertices[index].col; } // *********************************************************************** Vec2f Primitive::GetVertexTexCoord(int index) { return m_vertices[index].tex; } // *********************************************************************** Vec3f Primitive::GetVertexNormal(int index) { return m_vertices[index].norm; } // *********************************************************************** int Primitive::GetMaterialTextureId() { return m_baseColorTexture; } // *********************************************************************** Mesh::~Mesh() { } // *********************************************************************** int Mesh::GetNumPrimitives() { return (int)m_primitives.size(); } // *********************************************************************** Primitive* Mesh::GetPrimitive(int index) { return &m_primitives[index]; } // *********************************************************************** // Actually owns the data struct Buffer { char* pBytes{ nullptr }; size_t byteLength{ 0 }; }; // Does not actually own the data struct BufferView { // pointer to some place in a buffer char* pBuffer{ nullptr }; size_t length{ 0 }; enum Target { Array, ElementArray }; Target target; }; struct Accessor { // pointer to some place in a buffer view char* pBuffer{ nullptr }; int count{ 0 }; enum ComponentType { Byte, UByte, Short, UShort, UInt, Float }; ComponentType componentType; enum Type { Scalar, Vec2, Vec3, Vec4, Mat2, Mat3, Mat4 }; Type type; }; // *********************************************************************** std::vector<Mesh*> Mesh::LoadMeshes(const char* filePath) { std::vector<Mesh*> outMeshes; // Consider caching loaded json files somewhere since LoadScene and LoadMeshes are doing duplicate work here SDL_RWops* pFileRead = SDL_RWFromFile(filePath, "rb"); uint64_t size = SDL_RWsize(pFileRead); char* pData = new char[size]; SDL_RWread(pFileRead, pData, size, 1); SDL_RWclose(pFileRead); std::string file(pData, pData + size); delete[] pData; JsonValue parsed = ParseJsonFile(file); bool validGltf = parsed["asset"]["version"].ToString() == "2.0"; if (!validGltf) return std::vector<Mesh*>(); std::vector<Buffer> rawDataBuffers; JsonValue& jsonBuffers = parsed["buffers"]; for (int i = 0; i < jsonBuffers.Count(); i++) { Buffer buf; buf.byteLength = jsonBuffers[i]["byteLength"].ToInt(); buf.pBytes = new char[buf.byteLength]; std::string encodedBuffer = jsonBuffers[i]["uri"].ToString().substr(37); memcpy(buf.pBytes, DecodeBase64(encodedBuffer).data(), buf.byteLength); rawDataBuffers.push_back(buf); } std::vector<BufferView> bufferViews; JsonValue& jsonBufferViews = parsed["bufferViews"]; for (int i = 0; i < jsonBufferViews.Count(); i++) { BufferView view; int bufIndex = jsonBufferViews[i]["buffer"].ToInt(); view.pBuffer = rawDataBuffers[bufIndex].pBytes + jsonBufferViews[i]["byteOffset"].ToInt(); //@Incomplete, byte offset could not be provided, in which case we assume 0 view.length = jsonBufferViews[i]["byteLength"].ToInt(); // @Incomplete, target may not be provided int target = jsonBufferViews[i]["target"].ToInt(); if (target == 34963) view.target = BufferView::ElementArray; else if (target = 34962) view.target = BufferView::Array; bufferViews.push_back(view); } std::vector<Accessor> accessors; JsonValue& jsonAccessors = parsed["accessors"]; accessors.reserve(jsonAccessors.Count()); for (int i = 0; i < jsonAccessors.Count(); i++) { Accessor acc; JsonValue& jsonAcc = jsonAccessors[i]; int idx = jsonAcc["bufferView"].ToInt(); acc.pBuffer = bufferViews[idx].pBuffer + jsonAcc["byteOffset"].ToInt(); acc.count = jsonAcc["count"].ToInt(); int compType = jsonAcc["componentType"].ToInt(); switch (compType) { case 5120: acc.componentType = Accessor::Byte; break; case 5121: acc.componentType = Accessor::UByte; break; case 5122: acc.componentType = Accessor::Short; break; case 5123: acc.componentType = Accessor::UShort; break; case 5125: acc.componentType = Accessor::UInt; break; case 5126: acc.componentType = Accessor::Float; break; default: break; } std::string type = jsonAcc["type"].ToString(); if (type == "SCALAR") acc.type = Accessor::Scalar; else if (type == "VEC2") acc.type = Accessor::Vec2; else if (type == "VEC3") acc.type = Accessor::Vec3; else if (type == "VEC4") acc.type = Accessor::Vec4; else if (type == "MAT2") acc.type = Accessor::Mat2; else if (type == "MAT3") acc.type = Accessor::Mat3; else if (type == "MAT4") acc.type = Accessor::Mat4; accessors.push_back(acc); } outMeshes.reserve(parsed["meshes"].Count()); for (int i = 0; i < parsed["meshes"].Count(); i++) { JsonValue& jsonMesh = parsed["meshes"][i]; Mesh* pMesh = new Mesh(); pMesh->m_name = jsonMesh.HasKey("name") ? jsonMesh["name"].ToString() : ""; for (int j = 0; j < jsonMesh["primitives"].Count(); j++) { JsonValue& jsonPrimitive = jsonMesh["primitives"][j]; Primitive prim; if (jsonPrimitive.HasKey("mode")) { if (jsonPrimitive["mode"].ToInt() != 4) { return std::vector<Mesh*>(); // Unsupported topology type } } // Get material texture if (jsonPrimitive.HasKey("material")) { int materialId = jsonPrimitive["material"].ToInt(); JsonValue& jsonMaterial = parsed["materials"][materialId]; JsonValue& pbr = jsonMaterial["pbrMetallicRoughness"]; if (pbr.HasKey("baseColorTexture")) { int textureId = pbr["baseColorTexture"]["index"].ToInt(); int imageId = parsed["textures"][textureId]["source"].ToInt(); prim.m_baseColorTexture = imageId; } } int nVerts = accessors[jsonPrimitive["attributes"]["POSITION"].ToInt()].count; JsonValue& jsonAttr = jsonPrimitive["attributes"]; Vec3f* vertPositionBuffer = (Vec3f*)accessors[jsonAttr["POSITION"].ToInt()].pBuffer; Vec3f* vertNormBuffer = jsonAttr.HasKey("NORMAL") ? (Vec3f*)accessors[jsonAttr["NORMAL"].ToInt()].pBuffer : nullptr; Vec2f* vertTexCoordBuffer = jsonAttr.HasKey("TEXCOORD_0") ? (Vec2f*)accessors[jsonAttr["TEXCOORD_0"].ToInt()].pBuffer : nullptr; // Interlace vertex data std::vector<VertexData> indexedVertexData; indexedVertexData.reserve(nVerts); if (jsonAttr.HasKey("COLOR_0")) { Vec4f* vertColBuffer = (Vec4f*)accessors[jsonAttr["COLOR_0"].ToInt()].pBuffer; for (int i = 0; i < nVerts; i++) { indexedVertexData.push_back({vertPositionBuffer[i], vertColBuffer[i], vertTexCoordBuffer[i], vertNormBuffer[i]}); } } else { for (int i = 0; i < nVerts; i++) { indexedVertexData.push_back({vertPositionBuffer[i], Vec4f(1.0f, 1.0f, 1.0f, 1.0f), vertTexCoordBuffer[i], vertNormBuffer[i]}); } } // Flatten indices int nIndices = accessors[jsonPrimitive["indices"].ToInt()].count; uint16_t* indexBuffer = (uint16_t*)accessors[jsonPrimitive["indices"].ToInt()].pBuffer; prim.m_vertices.reserve(nIndices); for (int i = 0; i < nIndices; i++) { uint16_t index = indexBuffer[i]; prim.m_vertices.push_back(indexedVertexData[index]); } pMesh->m_primitives.push_back(std::move(prim)); } outMeshes.push_back(pMesh); } for (int i = 0; i < rawDataBuffers.size(); i++) { delete rawDataBuffers[i].pBytes; } return std::move(outMeshes); } // *********************************************************************** std::vector<Image*> Mesh::LoadTextures(const char* filePath) { std::vector<Image*> outImages; // Consider caching loaded json files somewhere since LoadScene/LoadMeshes/LoadImages are doing duplicate work here SDL_RWops* pFileRead = SDL_RWFromFile(filePath, "rb"); uint64_t size = SDL_RWsize(pFileRead); char* pData = new char[size]; SDL_RWread(pFileRead, pData, size, 1); SDL_RWclose(pFileRead); std::string file(pData, pData + size); delete[] pData; JsonValue parsed = ParseJsonFile(file); bool validGltf = parsed["asset"]["version"].ToString() == "2.0"; if (!validGltf) return std::vector<Image*>(); if (parsed.HasKey("images")) { outImages.reserve(parsed["images"].Count()); for (size_t i = 0; i < parsed["images"].Count(); i++) { JsonValue& jsonImage = parsed["images"][i]; std::string type = jsonImage["mimeType"].ToString(); std::string imagePath = "Assets/" + jsonImage["name"].ToString() + "." + type.substr(6, 4); Image* pImage = new Image(imagePath); outImages.emplace_back(pImage); } } return std::move(outImages); }
30.828402
174
0.533685
DavidColson
91de6d6f2835be44a67f4886901402cab72c55e3
4,432
hh
C++
net.ssa/xrLC/OpenMesh/Tools/Utils/MeshCheckerT.hh
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:19.000Z
2022-03-26T17:00:19.000Z
xrLC/OpenMesh/Tools/Utils/MeshCheckerT.hh
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
null
null
null
xrLC/OpenMesh/Tools/Utils/MeshCheckerT.hh
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:21.000Z
2022-03-26T17:00:21.000Z
//============================================================================= // // OpenMesh // Copyright (C) 2003 by Computer Graphics Group, RWTH Aachen // www.openmesh.org // //----------------------------------------------------------------------------- // // License // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Library General Public License as published // by the Free Software Foundation, version 2. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // //----------------------------------------------------------------------------- // // $Revision: 1.7 $ // $Date: 2004/01/13 15:23:32 $ // //============================================================================= #ifndef OPENMESH_MESHCHECKER_HH #define OPENMESH_MESHCHECKER_HH //== INCLUDES ================================================================= #include <OpenMesh/Core/System/config.h> #include <OpenMesh/Core/System/omstream.hh> #include <OpenMesh/Core/Utils/GenProg.hh> #include <OpenMesh/Core/Attributes/Attributes.hh> #include <iostream> //== NAMESPACES =============================================================== namespace OpenMesh { namespace Utils { //== CLASS DEFINITION ========================================================= /** Check integrity of mesh. * * This class provides several functions to check the integrity of a mesh. */ template <class Mesh> class MeshCheckerT { public: /// constructor MeshCheckerT(const Mesh& _mesh) : mesh_(_mesh) {} /// destructor ~MeshCheckerT() {} /// what should be checked? enum CheckTargets { CHECK_EDGES = 1, CHECK_VERTICES = 2, CHECK_FACES = 4, CHECK_ALL = 255, }; /// check it, return true iff ok bool check( unsigned int _targets=CHECK_ALL, std::ostream& _os=omerr ); private: bool is_deleted(typename Mesh::VertexHandle _vh) { return (mesh_.has_vertex_status() ? mesh_.status(_vh).deleted() : false); } bool is_deleted(typename Mesh::EdgeHandle _eh) { return (mesh_.has_edge_status() ? mesh_.status(_eh).deleted() : false); } bool is_deleted(typename Mesh::FaceHandle _fh) { return (mesh_.has_face_status() ? mesh_.status(_fh).deleted() : false); } // ref to mesh const Mesh& mesh_; }; //============================================================================= } // namespace Utils } // namespace OpenMesh //============================================================================= #if defined(OM_INCLUDE_TEMPLATES) && !defined(OPENMESH_MESHCHECKER_C) #define OPENMESH_MESHCHECKER_TEMPLATES #include "MeshCheckerT.cc" #endif //============================================================================= #endif // OPENMESH_MESHCHECKER_HH defined //=============================================================================
38.53913
80
0.38944
ixray-team
91de7e1728ff20b377605f083a700c47bb1f9670
1,650
cpp
C++
vision_slam/VO/opticalflow_direct/direct_method.cpp
kant/VO
2acf9cb88eb2ec43adc272b57fd140bcace53e97
[ "MIT" ]
1
2021-03-20T04:52:45.000Z
2021-03-20T04:52:45.000Z
vision_slam/VO/opticalflow_direct/direct_method.cpp
kant/VO
2acf9cb88eb2ec43adc272b57fd140bcace53e97
[ "MIT" ]
null
null
null
vision_slam/VO/opticalflow_direct/direct_method.cpp
kant/VO
2acf9cb88eb2ec43adc272b57fd140bcace53e97
[ "MIT" ]
1
2021-06-05T23:30:49.000Z
2021-06-05T23:30:49.000Z
#include <iostream> #include <fstream> #include <list> #include <vector> #include <chrono> #include <ctime> #include <climits> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/features2d/features2d.hpp> #include <g2o/core/base_unary_edge.h> #include <g2o/core/block_solver.h> #include <g2o/core/optimization_algorithm_levenberg.h> #include <g2o/solvers/dense/linear_solver_dense.h> #include <g2o/core/robust_kernel.h> #include <g2o/types/sba/types_six_dof_expmap.h> using namespace std; using namespace g2o; // 一次测量的值,包括一个世界坐标系下三维点与一个灰度值 struct Measurement { Measurement ( Eigen::Vector3d p, float g ) : pos_world ( p ), grayscale ( g ) {} Eigen::Vector3d pos_world; float grayscale; }; // inline 修饰内联函数, 像素坐标到相机坐标 inline Eigen::Vector3d pixelToCam ( int u, int v, int d, float fx, float fy, float cx, float cy, float scale ) { float zz = float ( d ) /scale; // Give a measurment float x_cam = zz* ( u-cx ) /fx; float y_cam = zz* ( v-cy ) /fy; return Eigen::Vector3d ( x_cam, y_cam, zz ); } // inline , 相机坐标到像素坐标 inline Eigen::Vector2d camToPixel ( float x, float y, float z, float fx, float fy, float cx, float cy ) { float u = fx*x/z+cx; float v = fy*y/z+cy; return Eigen::Vector2d ( u,v ); } // 直接法估计位姿 // 输入:测量值(空间点的灰度),新的灰度图,相机内参; 输出:相机位姿 // 返回:true为成功,false失败 bool poseEstimationDirect ( const vector<Measurement>& measurements, cv::Mat* gray, Eigen::Matrix3f& intrinsics, Eigen::Isometry3d& Tcw ); // Isometry3d --> 是 欧式 变换矩阵。 其实是一个 4 x 4 矩阵 int main(int argc, char const *argv[]) { /* code */ return 0; }
27.5
110
0.695152
kant
91e8f446e650ca0fded7d5f413dc6a1eda5c0fc9
1,707
cpp
C++
sources/game/spatial.cpp
ucpu/mazetd
f6ef70a142579b558caa4a7d0e5bdd8177e5fa75
[ "MIT" ]
2
2021-06-27T01:58:23.000Z
2021-08-16T20:24:29.000Z
sources/game/spatial.cpp
ucpu/mazetd
f6ef70a142579b558caa4a7d0e5bdd8177e5fa75
[ "MIT" ]
2
2022-02-03T23:40:10.000Z
2022-03-15T06:22:29.000Z
sources/game/spatial.cpp
ucpu/mazetd
f6ef70a142579b558caa4a7d0e5bdd8177e5fa75
[ "MIT" ]
1
2022-01-26T21:07:41.000Z
2022-01-26T21:07:41.000Z
#include <cage-core/entitiesVisitor.h> #include <cage-core/spatialStructure.h> #include "../game.h" #include "../grid.h" namespace { Holder<SpatialStructure> monstersData = newSpatialStructure({}); Holder<SpatialStructure> structsData = newSpatialStructure({}); Holder<SpatialQuery> monstersQuery = newSpatialQuery(monstersData.share()); Holder<SpatialQuery> structsQuery = newSpatialQuery(structsData.share()); void gameReset() { monstersData->clear(); structsData->clear(); } void gameUpdate() { monstersData->clear(); CAGE_ASSERT(globalGrid); entitiesVisitor([&](Entity *e, const MovementComponent &mv, const MonsterComponent &) { monstersData->update(e->name(), mv.position()); }, gameEntities(), false); monstersData->rebuild(); } struct Callbacks { EventListener<void()> gameResetListener; EventListener<void()> gameUpdateListener; Callbacks() { gameResetListener.attach(eventGameReset()); gameResetListener.bind<&gameReset>(); gameUpdateListener.attach(eventGameUpdate(), 30); gameUpdateListener.bind<&gameUpdate>(); } } callbacksInstance; } SpatialQuery *spatialMonsters() { return +monstersQuery; } SpatialQuery *spatialStructures() { return +structsQuery; } void spatialUpdateStructures() { structsData->clear(); CAGE_ASSERT(globalGrid); entitiesVisitor([&](Entity *e, const PositionComponent &pos, const BuildingComponent &) { structsData->update(e->name(), globalGrid->center(pos.tile)); }, gameEntities(), false); entitiesVisitor([&](Entity *e, const PositionComponent &pos, const TrapComponent &) { structsData->update(e->name(), globalGrid->center(pos.tile)); }, gameEntities(), false); structsData->rebuild(); }
23.708333
90
0.727592
ucpu
91eb95f6a67a682eb83e45a9575e14e3f217c3b9
372
cpp
C++
Core/Logger/src/Logger.cpp
WSeegers/-toy-StackMachine
4d1c1b487369604f931f4bfa459e350b5349a9c3
[ "MIT" ]
null
null
null
Core/Logger/src/Logger.cpp
WSeegers/-toy-StackMachine
4d1c1b487369604f931f4bfa459e350b5349a9c3
[ "MIT" ]
null
null
null
Core/Logger/src/Logger.cpp
WSeegers/-toy-StackMachine
4d1c1b487369604f931f4bfa459e350b5349a9c3
[ "MIT" ]
null
null
null
#include "../include/Logger.hpp" #include <iostream> void Logger::LexicalError(const std::string &msg, int line, int index) { std::cerr << "Lexical Error -> " << line << ":" << index << " : " << msg << std::endl; } void Logger::RuntimeError(const std::string &msg, int line) { std::cerr << "Runtime Error -> Line " << line << " : " << msg << std::endl; }
23.25
70
0.572581
WSeegers
91ef59cbd345291b9cbc8c26db1740a71088a7ff
4,449
cpp
C++
src/Psn/Exports.cpp
ahmed-agiza/OpenPhySyn
51841240e5213a7e74bc6321bbe4193323378c8e
[ "BSD-3-Clause" ]
null
null
null
src/Psn/Exports.cpp
ahmed-agiza/OpenPhySyn
51841240e5213a7e74bc6321bbe4193323378c8e
[ "BSD-3-Clause" ]
null
null
null
src/Psn/Exports.cpp
ahmed-agiza/OpenPhySyn
51841240e5213a7e74bc6321bbe4193323378c8e
[ "BSD-3-Clause" ]
null
null
null
// BSD 3-Clause License // Copyright (c) 2019, SCALE Lab, Brown University // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include "Exports.hpp" #include <OpenPhySyn/Psn/Psn.hpp> #include <memory> #include "PsnLogger/PsnLogger.hpp" namespace psn { #ifndef OPENROAD_BUILD int import_def(const char* def_path) { return Psn::instance().readDef(def_path); } int import_lef(const char* lef_path, int ignore_routing_layers) { return Psn::instance().readLef(lef_path); } int import_lib(const char* lib_path) { return import_liberty(lib_path); } int import_liberty(const char* lib_path) { return Psn::instance().readLib(lib_path); } int export_def(const char* lib_path) { return Psn::instance().writeDef(lib_path); } int print_liberty_cells() { Liberty* liberty = Psn::instance().liberty(); if (!liberty) { PsnLogger::instance().error("Did not find any liberty files, use " "import_liberty <file name> first."); return -1; } sta::LibertyCellIterator cell_iter(liberty); while (cell_iter.hasNext()) { sta::LibertyCell* cell = cell_iter.next(); PsnLogger::instance().info("Cell: {}", cell->name()); } return 1; } #endif int set_wire_rc(float res_per_micon, float cap_per_micron) { Psn::instance().setWireRC(res_per_micon, cap_per_micron); return 1; } int set_max_area(float area) { Psn::instance().settings()->setMaxArea(area); return 1; } int link(const char* top_module) { return link_design(top_module); } int link_design(const char* top_module) { return Psn::instance().linkDesign(top_module); } void version() { print_version(); } int transform_internal(std::string transform_name, std::vector<std::string> args) { return Psn::instance().runTransform(transform_name, args); } void help() { print_usage(); } void print_usage() { Psn::instance().printUsage(); } void print_transforms() { Psn::instance().printTransforms(true); } void print_version() { Psn::instance().printVersion(); } Database& get_database() { return *(Psn::instance().database()); } Liberty& get_liberty() { return *(Psn::instance().liberty()); } int set_log(const char* level) { return set_log_level(level); } int set_log_level(const char* level) { return Psn::instance().setLogLevel(level); } int set_log_pattern(const char* pattern) { return Psn::instance().setLogPattern(pattern); } DatabaseHandler& get_handler() { return get_database_handler(); } DatabaseHandler& get_database_handler() { return *(Psn::instance().handler()); } SteinerTree* create_steiner_tree(const char* net_name) { auto net = Psn::instance().handler()->net(net_name); return create_steiner_tree(net); } SteinerTree* create_steiner_tree(Net* net) { auto pt = SteinerTree::create(net, &(Psn::instance()), 3); SteinerTree* tree = pt.get(); pt.release(); return tree; } } // namespace psn
22.469697
80
0.710497
ahmed-agiza
91f3b792dec221d489aa79578b01b1f483bfe1c8
22,008
cpp
C++
SimplECircuitCybSys/src/SimplECircuitCybSys.cpp
gpvigano/DigitalScenarioFramework
a1cab48df1f4a3d9b54e6cf00c5d0d0058e771f1
[ "MIT" ]
1
2021-12-21T17:28:39.000Z
2021-12-21T17:28:39.000Z
SimplECircuitCybSys/src/SimplECircuitCybSys.cpp
gpvigano/DigitalScenarioFramework
a1cab48df1f4a3d9b54e6cf00c5d0d0058e771f1
[ "MIT" ]
null
null
null
SimplECircuitCybSys/src/SimplECircuitCybSys.cpp
gpvigano/DigitalScenarioFramework
a1cab48df1f4a3d9b54e6cf00c5d0d0058e771f1
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------// // Digital Scenario Framework // // by Giovanni Paolo Vigano', 2021 // //--------------------------------------------------------------------// // // Distributed under the MIT Software License. // See http://opensource.org/licenses/MIT // #include <SimplECircuitCybSys/SimplECircuitCybSys.h> #include <SimplECircuitCybSys/SimplECircuitSolver.h> #include <discenfw/xp/EnvironmentModel.h> #include <discenfw/util/MessageLog.h> #include <boost/config.hpp> // for BOOST_SYMBOL_EXPORT #include <iostream> #include <sstream> using namespace discenfw::xp; namespace { inline std::string BoolToString(bool val) { return val ? "true" : "false"; } } namespace simplecircuit_cybsys { SimplECircuitCybSys::SimplECircuitCybSys() { Circuit = std::make_unique<simplecircuit_cybsys::ElectronicCircuit>(); } void SimplECircuitCybSys::CreateEntityStateTypes() { if (ComponentEntityType) { return; } ComponentEntityType = CreateEntityStateType( "", "Electronic Component", { {"connections","0"}, {"connected","false"}, {"burnt out","false"}, }, { { "connected", { "true","false" } }, {"burnt out", { "true","false" }}, }, {} ); ResistorEntityType = CreateEntityStateType( "Electronic Component", "Resistor", { }, { {"connections",{"0","1","2"}}, }, { "Pin1", "Pin2" } ); LedEntityType = CreateEntityStateType( "Electronic Component", "LED", { {"lit up","false"}, }, { {"connections",{"0","1","2"}}, { "lit up", { "true","false" } }, }, { "Anode", "Cathode" } ); PowerEntityType = CreateEntityStateType( "Electronic Component", "Power Supply", { }, { {"connections",{"0","1","2"}}, }, { "+", "-" } ); SwitchEntityType = CreateEntityStateType( "Electronic Component", "Switch", { {"position","0"}, }, { {"connections",{"0","1","2","3"}}, { "position", { "0","1" } }, }, { "In", "Out0", "Out1" } ); } void SimplECircuitCybSys::ClearSystem() { Circuit->Components.clear(); } void SimplECircuitCybSys::InitFailureConditions() { // set a default failure condition (any component burnt out) PropertyCondition burntOutCond({ "burnt out",BoolToString(true) }); Condition anyBurntOut({ {EntityCondition::ANY,{burntOutCond}} }); FailureCondition = anyBurntOut; } void SimplECircuitCybSys::InitRoles() { std::shared_ptr<EnvironmentModel> model = GetModel(); if (model->GetRoleNames().empty()) { PropertyCondition burntOutCond({ "burnt out",BoolToString(true) }); Condition anyBurntOut({ { EntityCondition::ANY,{ burntOutCond } } }); xp::SetRole( "Default", {}, // SuccessCondition {}, // FailureCondition {}, // DeadlockCondition { // ResultReward { { ActionResult::IN_PROGRESS,0 }, { ActionResult::SUCCEEDED,1000 }, { ActionResult::FAILED,-1000 }, { ActionResult::DEADLOCK,-10 }, }, // PropertyCountRewards {}, // EntityConditionRewards { }, // FeatureRewards { } } ); } } void SimplECircuitCybSys::ResetSystem() { Circuit->Reset(); } bool SimplECircuitCybSys::ExecuteAction(const Action& action) { enum ActionId { CONNECT, SWITCH, DISCONNECT }; static std::map<std::string, ActionId> actionNames{ { "connect",CONNECT }, { "switch",SWITCH }, { "disconnect",DISCONNECT }, }; switch (actionNames[action.TypeId]) { case CONNECT: return DoConnectAction(action); case SWITCH: return DoSwitchAction(action); case DISCONNECT: return DoDisconnectAction(action); default: break; } return false; } void SimplECircuitCybSys::SynchronizeState(std::shared_ptr<xp::EnvironmentState> environmentState) { // TODO: alternative: just update existing entities and remove dangling entities? environmentState->Clear(); // synchronize component states for (const auto& comp : Circuit->Components) { std::string entityId = comp.first; const auto& component = comp.second; std::shared_ptr<Led> led = AsLed(component); std::shared_ptr<Switch> sw = AsSwitch(component); std::shared_ptr<PowerSupplyDC> powerSupply = AsPowerSupplyDC(component); std::shared_ptr<Resistor> resistor = AsResistor(component); // get the properties of the current component bool nowBurnt = component->BurntOut; bool nowConnected = component->Connected; int nowConn = component->GetConnectedLeadsCount(); bool nowLit = led && led->LitUp; int nowPos = (int)(sw && sw->Position == SwitchPosition::POS1); // update the entity state for the current component std::shared_ptr<EntityState> entState = environmentState->GetEntityState(entityId); if (!entState) { std::shared_ptr<EntityStateType> entType; if (!ComponentEntityType) { CreateEntityStateTypes(); } if (powerSupply) entType = PowerEntityType; else if (led) entType = LedEntityType; else if (sw) entType = SwitchEntityType; else if (resistor) entType = ResistorEntityType; //else if (transistor) entType = TransistorEntityType; else entType = ComponentEntityType; entState = EntityState::Make(entType->GetTypeName(),entType->GetModelName()); //entState = std::make_shared<EntityState>(entType->GetTypeName(),entType->GetModelName()); environmentState->SetEntityState(entityId, entState); } std::vector< std::pair<std::string, std::shared_ptr<ElectronicComponentLead> >> leads; component->GetLeads(leads); // store new component relationships for (const auto& eLead : leads) { if (!eLead.second->Connections.empty()) { RelationshipLink link; link.EntityId = eLead.second->Connections[0].Component; link.LinkId = eLead.second->Connections[0].Lead; entState->SetRelationship(eLead.first, link); } else { entState->RemoveRelationship(eLead.first); } } // set the properties for the entity state entState->SetPropertyValue("burnt out", BoolToString(nowBurnt)); entState->SetPropertyValue("connected", BoolToString(nowConnected)); entState->SetPropertyValue("connections", std::to_string(nowConn)); if (led) { entState->SetPropertyValue("lit up", BoolToString(nowLit)); } if (sw) { entState->SetPropertyValue("position", std::to_string(nowPos)); } if (LogEnabled) { if (nowBurnt) { LogStream << entityId << " => burnt out" << std::endl; FlushLog(LOG_DEBUG); } if (nowLit) { LogStream << entityId << " => lit up" << std::endl; FlushLog(LOG_DEBUG); } if (nowPos) { LogStream << entityId << " => on" << std::endl; FlushLog(LOG_DEBUG); } } } } const std::vector<ActionRef>& SimplECircuitCybSys::GetAvailableActions( const std::string& roleId, bool smartSelection ) const { CachedAvailableActions.clear(); std::shared_ptr<PowerSupplyDC> powerSupply = Circuit->GetPowerSupply(); bool circuitIsComplete = false; if (smartSelection) { if(powerSupply && powerSupply->GetConnectedLeadsCount()==2) { circuitIsComplete = true; for (const auto& compItem : Circuit->Components) { // Check if at least one component is connected but not fully connected // (power supply was already checked) if (compItem.second != powerSupply && compItem.second->GetConnectedLeadsCount() == 1) { circuitIsComplete = false; break; } } } } std::vector<std::string> actionNames{ "connect", "switch" }; for (const auto& compItem : Circuit->Components) { std::string compId = compItem.first; std::shared_ptr<ElectronicComponent> component = compItem.second; bool powerSupplyConnected = powerSupply && powerSupply->AnyLeadConnected(); std::string powerId = Circuit->GetComponentName(powerSupply); if (!component->BurntOut) { auto sw = AsSwitch(component); if (sw) { bool canBeSwitched = true; if (smartSelection) { canBeSwitched = circuitIsComplete && sw->GetConnectedLeadsCount() > 1 && sw->Lead("In")->Connected(); } // possible deadlock: repeatedly switching --> deadlock detection required if (canBeSwitched) { CacheAvailableAction( { "switch",{ compId,sw->Position == SwitchPosition::POS0 ? "1" : "0" } } ); } // alternative solution: // allow switch-on only, this avoids possible deadlocks //if (canBeSwitched && sw->Position == SwitchPosition::POS0) //... } // if (!component->AllLeadsConnected()) ... // allow only 2 connections per component to simplify the circuit simulation if (component->GetConnectedLeadsCount() < 2) { std::vector< std::shared_ptr<ElectronicComponentLead> > leads; std::vector< std::string > leadNames; component->GetLeads(leads); component->GetLeadNames(leadNames); for (const auto& otherCompItem : Circuit->Components) { std::string otherCompId = otherCompItem.first; std::shared_ptr<ElectronicComponent> otherComponent = otherCompItem.second; bool connectingPowerSupply = (otherComponent == powerSupply || component == powerSupply); bool connectedToPowerSupply = (otherComponent->Connected || component->Connected); bool canBeConnected = (!otherComponent->BurntOut && otherComponent != component && !otherComponent->AllLeadsConnected() && !component->ConnectedTo(otherCompId) ); if (smartSelection) { canBeConnected = canBeConnected && (connectingPowerSupply || connectedToPowerSupply); } if (canBeConnected) { std::vector< std::shared_ptr<ElectronicComponentLead> > otherLeads; std::vector< std::string > otherLeadNames; otherComponent->GetLeads(otherLeads); otherComponent->GetLeadNames(otherLeadNames); for (size_t i = 0; i < leads.size(); i++) { const auto& lead = leads[i]; // allow only 1 connection per lead to simplify the circuit simulation if (!lead->Connected()) { for (size_t j = 0; j < otherLeads.size(); j++) { const auto& otherLead = otherLeads[j]; if (!otherLead->Connected()) { // prevent parallel connections of components to simplify the circuit simulation //if (otherLead != lead && !otherLead->ConnectedTo(compId, leadNames[i])) if (otherLead != lead && !otherLead->ConnectedTo(compId)) { CacheAvailableAction( { "connect", { compId, leadNames[i], otherCompId, otherLeadNames[j] } } ); } } } } } } } } } } return CachedAvailableActions; } bool SimplECircuitCybSys::DoConnectAction(const Action& action) { // decode parameters const std::string& component1Id = action.Params[0]; const std::string& lead1Id = action.Params[1]; const std::string& component2Id = action.Params[2]; const std::string& lead2Id = action.Params[3]; // prevent connecting a lead with itself if (component1Id == component2Id && lead1Id == lead2Id) { return false; } std::shared_ptr<ElectronicComponent> component1 = Circuit->FindComponent(component1Id); std::shared_ptr<ElectronicComponent> component2 = Circuit->FindComponent(component2Id); // check if components exist if (!component1 || !component2) { return false; } // check if already connected if (component1->ConnectedTo(component2Id, lead2Id)) { return false; } // allow only 1 connection per lead to simplify the circuit simulation if (component1->Lead(lead1Id)->Connected() || component2->Lead(lead2Id)->Connected()) { return false; } if (LogEnabled) { LogStream << "> " << component1Id << "/" << lead1Id << " <--> " << component2Id << "/" << lead2Id << std::endl; FlushLog(LOG_DEBUG); } // update the circuit Circuit->Connect(component1Id, lead1Id, component2Id, lead2Id); SolveElectronicCircuit(*Circuit); return true; } bool SimplECircuitCybSys::DoSwitchAction(const Action& action) { // decode parameters const std::string& switchId = action.Params[0]; const std::string& posId = action.Params[1]; bool pos = std::atoi(posId.c_str()) > 0; auto sw = AsSwitch(Circuit->FindComponent(switchId)); if (!sw) { return false; } if (LogEnabled) { LogStream << std::noboolalpha << "> " << switchId << ": " << pos << std::endl; FlushLog(LOG_DEBUG); } // update the circuit sw->Position = (SwitchPosition)pos; SolveElectronicCircuit(*Circuit); return true; } bool SimplECircuitCybSys::DoDisconnectAction(const Action& action) { size_t numParams = action.Params.size(); if(numParams!=2 && numParams!=4) { return false; } // decode parameters const std::string& component1Id = action.Params[0]; const std::string& lead1Id = action.Params[1]; std::shared_ptr<ElectronicComponent> component1 = Circuit->FindComponent(component1Id); if (!component1->Lead(lead1Id)->Connected()) { return false; } if (numParams == 2) { // update the circuit Circuit->Disconnect(component1Id, lead1Id); } else //if (numParams == 4) { const std::string& component2Id = action.Params[2]; const std::string& lead2Id = action.Params[3]; // prevent connecting a lead with itself if (component1Id == component2Id && lead1Id == lead2Id) { return false; } std::shared_ptr<ElectronicComponent> component2 = Circuit->FindComponent(component2Id); // check if components exist if (!component1 || !component2) { return false; } // check if already connected if (!component1->ConnectedTo(component2Id, lead2Id)) { return false; } if (!component2->Lead(lead2Id)->Connected()) { return false; } if (LogEnabled) { LogStream << "> " << component1Id << "/" << lead1Id << " X--X " << component2Id << "/" << lead2Id << std::endl; FlushLog(LOG_DEBUG); } // update the circuit Circuit->Disconnect(component1Id, lead1Id, component2Id, lead2Id); } SolveElectronicCircuit(*Circuit); return true; } std::shared_ptr<ElectronicComponent> SimplECircuitCybSys::CreateComponentFromConfiguration( const std::string& config, std::string& compId) { std::istringstream iStr(config); if (!iStr.good()) { return nullptr; } std::shared_ptr<ElectronicComponent> comp; std::string compType; iStr >> compType >> compId; comp = MakeComponent(compType); if (comp) { ReadComponentConfiguration(iStr, comp); Circuit->Components[compId] = comp; } return comp; } const std::string SimplECircuitCybSys::GetComponentConfiguration(const std::string& compId) { std::shared_ptr<ElectronicComponent> comp = Circuit->FindComponent(compId); if (!comp) { return ""; } std::ostringstream oStr; std::shared_ptr<Led> led = AsLed(comp); if (led) { oStr << led->Type->Name; } std::shared_ptr<Resistor> r = AsResistor(comp); if (r) { oStr << r->Ohm << " " << r->Max_mW; } std::shared_ptr<Switch> sw = AsSwitch(comp); if (sw) { oStr << sw->MaxVoltage_mV << " " << sw->MaxCurrent_mA; } std::shared_ptr<PowerSupplyDC> powerSupply = AsPowerSupplyDC(comp); if (powerSupply) { oStr << powerSupply->Voltage_mV << " " << powerSupply->MaxCurrent_mA; } return oStr.str(); } bool SimplECircuitCybSys::SetComponentConfiguration(const std::string& compId, const std::string& config) { std::shared_ptr<ElectronicComponent> comp = Circuit->FindComponent(compId); if (!comp) { return false; } std::istringstream iStr(config); ReadComponentConfiguration(iStr, comp); return true; } bool SimplECircuitCybSys::SetConfiguration(const std::string& config) { Initialize(); Circuit->Components.clear(); bool firstRead = true; std::istringstream iStr(config); while (iStr.good()) { std::string compConfig; std::getline(iStr, compConfig); std::string compId; std::shared_ptr<ElectronicComponent> comp = CreateComponentFromConfiguration( compConfig, compId); if (firstRead &&!comp) { return false; } firstRead = false; } Initialize(true); return true; } const std::string SimplECircuitCybSys::GetConfiguration() { std::ostringstream oStr; for (const auto& comp : Circuit->Components) { oStr << comp.second->GetTypeName() << " " << comp.first << " "; oStr << GetComponentConfiguration(comp.first); oStr << "\n"; } return oStr.str(); } const std::string SimplECircuitCybSys::ReadEntityConfiguration(const std::string& entityId) { return GetComponentConfiguration(entityId); } bool SimplECircuitCybSys::WriteEntityConfiguration(const std::string& entityId, const std::string& config) { return SetComponentConfiguration(entityId, config); } bool SimplECircuitCybSys::ConfigureEntity(const std::string& entityId, const std::string& entityType, const std::string& config) { std::shared_ptr<ElectronicComponent> comp; if (Circuit->Components.find(entityId) != Circuit->Components.end()) { comp = Circuit->Components[entityId]; if (comp->GetTypeName() != entityType) { Circuit->Components.erase(entityId); comp = nullptr; } } if (!comp) { comp = MakeComponent(entityType); if (!comp) { return false; } Circuit->Components[entityId] = comp; } std::istringstream iStr(config); ReadComponentConfiguration(iStr, comp); return true; } bool SimplECircuitCybSys::RemoveEntity(const std::string& entityId) { if (Circuit->Components.find(entityId) != Circuit->Components.end()) { std::shared_ptr<ElectronicComponent> comp = Circuit->Components[entityId]; Circuit->Disconnect(entityId); Circuit->Components.erase(entityId); return true; } return false; } const std::string SimplECircuitCybSys::GetSystemInfo(const std::string& infoId) const { std::ostringstream oStr; if (infoId == "" || infoId == "CircuitSchema") { // create a schematic representation of the circuit in one text line std::shared_ptr<PowerSupplyDC> powerSupply = Circuit->GetPowerSupply(); if (!powerSupply) return ""; std::shared_ptr<ElectronicComponentLead> posLead = powerSupply->GetPositiveLead(); std::shared_ptr<ElectronicComponentLead> negLead = powerSupply->GetNegativeLead(); if (!posLead->Connected() || !negLead->Connected()) return ""; int connectedComponents = 0; for (const auto& comp : Circuit->Components) { if (comp.second->GetConnectedLeadsCount() > 1) connectedComponents++; } std::vector<std::string> foundComponents; bool closedCircuit = Circuit->GetCircuitComponents(foundComponents); oStr << " (+)-"; for (std::string compName : foundComponents) { const auto& comp = Circuit->Components[compName]; const auto& sw = AsSwitch(comp); const auto& led = AsLed(comp); oStr << "-{" << compName; if (led && led->LitUp) oStr << "*"; if (sw && sw->Position == SwitchPosition::POS0) oStr << "o"; if (sw && sw->Position == SwitchPosition::POS1) oStr << "*"; oStr << "}-"; } if (closedCircuit) oStr << "-(-) {" << connectedComponents << "}"; } else if (infoId == "CircuitInfo") { // List circuit components and their state for (const auto& compPair : Circuit->Components) { const auto& component = compPair.second; if (component->GetConnectedLeadsCount() > 1) { oStr << compPair.first; const auto& sw = AsSwitch(component); if (sw) oStr << "#" << (int)sw->Position; const auto& led = AsLed(component); if (led && led->LitUp) oStr << "*"; if (component->BurntOut) { oStr << "[burnt out]"; } std::vector< std::shared_ptr<ElectronicComponentLead> > leads; component->GetLeads(leads); if (!leads.empty()) { oStr << "@"; } bool first = true; for (const auto& connLead : leads) { if (connLead->Connected()) { if (!first) oStr << ","; first = false; oStr << connLead->Name << ">" << connLead->Connections[0].Component << "." << connLead->Connections[0].Lead; } } oStr << " "; } } } std::string info = oStr.str(); return info; } void SimplECircuitCybSys::ReadComponentConfiguration(std::istringstream& iStr, std::shared_ptr<ElectronicComponent> comp) { std::shared_ptr<Led> led = AsLed(comp); if (led) { std::string ledType; iStr >> ledType; led->Type = GetLedType(ledType); if (!led->Type) { LogStream << "Unknown LED type: " << ledType << std::endl; FlushLog(LOG_ERROR); } } std::shared_ptr<Resistor> r = AsResistor(comp); if (r) { iStr >> r->Ohm >> r->Max_mW; } std::shared_ptr<Switch> sw = AsSwitch(comp); if (sw) { iStr >> sw->MaxVoltage_mV >> sw->MaxCurrent_mA; } std::shared_ptr<PowerSupplyDC> powerSupply = AsPowerSupplyDC(comp); if (powerSupply) { iStr >> powerSupply->Voltage_mV >> powerSupply->MaxCurrent_mA; } } std::shared_ptr<ElectronicComponent> SimplECircuitCybSys::MakeComponent(const std::string& compType) { std::shared_ptr<ElectronicComponent> comp; if (compType == "PowerSupplyDC") { comp = std::make_shared<PowerSupplyDC>(); } else if (compType == "LED") { comp = std::make_shared<Led>(nullptr); } else if (compType == "Resistor") { comp = std::make_shared<Resistor>(); } else if (compType == "Switch") { comp = std::make_shared<Switch>(); } return comp; } extern "C" BOOST_SYMBOL_EXPORT SimplECircuitCybSys CyberSystem; SimplECircuitCybSys CyberSystem; } // namespace simplecircuit_cybsys
25.325662
129
0.639313
gpvigano
91f65d12c52f59ce95cf6cfcb87d5e478ce374e8
1,860
cpp
C++
SDLClassesTests/SurfaceTest.cpp
SmallLuma/SDLClasses
6348dd5d75b366d5e5e67f4074d7ebe0bd2173ee
[ "Zlib" ]
4
2017-06-27T03:34:32.000Z
2018-03-12T01:30:25.000Z
SDLClassesTests/SurfaceTest.cpp
SmallLuma/SDLClasses
6348dd5d75b366d5e5e67f4074d7ebe0bd2173ee
[ "Zlib" ]
null
null
null
SDLClassesTests/SurfaceTest.cpp
SmallLuma/SDLClasses
6348dd5d75b366d5e5e67f4074d7ebe0bd2173ee
[ "Zlib" ]
null
null
null
#include "stdafx.h" #include "CppUnitTest.h" #include <SDLInstance.h> #include <Window.h> #include <Vector4.h> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace SDLClassesTests { TEST_CLASS(SurfaceTest) { public: TEST_METHOD(SimpleDraw) { using namespace SDL; ::SDL::SDLInstance sdl(::SDL::SDLInstance::InitParam::Video | ::SDL::SDLInstance::InitParam::Events); Window wnd("HelloWorld", Rect<int32_t>{ Window::Center,Window::Center,1024,768 }, Window::WindowFlag::Null); auto& sur = wnd.GetWindowSurface(); sur.Clear(Color<uint8_t>{ 0,0,255,255 }); sur.Fill(Rect<int32_t>{ 50,50,150,150 }, Color<uint8_t>{ 0,255,0,255 }); std::vector<Rect<int32_t>> rects = { {750,350,200,200}, {0,350,200,200} }; sur.Fill(rects, Color<uint8_t>{ 255,0,0,255 }); wnd.UpdateWindowSurface(); sdl.Delay(500); sur.Shade([](int x, int y, Surface& thisSur, Color<uint8_t> oldColor) { return Color<uint8_t> { static_cast<uint8_t>(x % 255), static_cast<uint8_t>(y % 255), 128, 255 }; }); wnd.UpdateWindowSurface(); sdl.Delay(500); } TEST_METHOD(BlitTest) { using namespace SDL; ::SDL::SDLInstance sdl(::SDL::SDLInstance::InitParam::Everything); Window wnd("HelloWorld", Rect<int32_t>{ Window::Center, Window::Center, 1024, 768 }, Window::WindowFlag::Null); Surface sur1(512, 512, 32, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF); auto& wsur = wnd.GetWindowSurface(); sur1.Shade([](int x, int y, Surface& thisSur, Color<uint8_t> oldColor) { return Color<uint8_t> { static_cast<uint8_t>(x % 255), static_cast<uint8_t>(y % 255), 128, 255 }; }); wsur.BlitFrom(sur1, Rect<int32_t>{0, 0, 512, 512}, Rect<int32_t>{100, 100, 512, 512}); wnd.UpdateWindowSurface(); sdl.Delay(300); } }; }
25.833333
114
0.649462
SmallLuma
91f82f77b5df8436fbb041aa30b09d76d3c6190c
1,254
hpp
C++
include/codegen/include/UnityEngine/AddComponentMenu.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/AddComponentMenu.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/AddComponentMenu.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:29 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Attribute #include "System/Attribute.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Completed forward declares // Type namespace: UnityEngine namespace UnityEngine { // Autogenerated type: UnityEngine.AddComponentMenu class AddComponentMenu : public System::Attribute { public: // private System.String m_AddComponentMenu // Offset: 0x10 ::Il2CppString* m_AddComponentMenu; // private System.Int32 m_Ordering // Offset: 0x18 int m_Ordering; // public System.Void .ctor(System.String menuName) // Offset: 0x12E6D80 static AddComponentMenu* New_ctor(::Il2CppString* menuName); // public System.Void .ctor(System.String menuName, System.Int32 order) // Offset: 0x12E6DBC static AddComponentMenu* New_ctor(::Il2CppString* menuName, int order); }; // UnityEngine.AddComponentMenu } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::AddComponentMenu*, "UnityEngine", "AddComponentMenu"); #pragma pack(pop)
35.828571
90
0.698565
Futuremappermydud
91fe1f3f1f9adda77b276622415cd80ae8fdd668
1,904
cpp
C++
gui/menu-predicate.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
10
2016-12-28T22:06:31.000Z
2021-05-24T13:42:30.000Z
gui/menu-predicate.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
4
2015-10-09T23:55:10.000Z
2020-04-04T08:09:22.000Z
gui/menu-predicate.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
null
null
null
// -*- coding: us-ascii-unix -*- // Copyright 2012 Lukas Kemmer // // 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 "gui/menu-predicate.hh" #include "util/convenience.hh" namespace faint{ BoundMenuPred::BoundMenuPred(menu_item_id_t id, predicate_t predicate) : m_id(id), m_pred(predicate) {} void BoundMenuPred::Update(MenuReference& menu, const MenuFlags& flags) const{ bool enable = (flags.toolSelection && fl(MenuPred::TOOL_SELECTION, m_pred)) || (flags.rasterSelection && fl(MenuPred::RASTER_SELECTION, m_pred)) || (flags.objectSelection && fl(MenuPred::OBJECT_SELECTION, m_pred)) || (flags.hasObjects && fl(MenuPred::HAS_OBJECTS, m_pred)) || (flags.dirty && fl(MenuPred::DIRTY, m_pred)) || (flags.canUndo && fl(MenuPred::CAN_UNDO, m_pred)) || (flags.canRedo && fl(MenuPred::CAN_REDO, m_pred)) || (flags.numSelected > 1 && fl(MenuPred::MULTIPLE_SELECTED, m_pred)) || (flags.groupIsSelected && fl(MenuPred::GROUP_IS_SELECTED, m_pred)) || (flags.canMoveForward && fl(MenuPred::CAN_MOVE_FORWARD, m_pred)) || (flags.canMoveBackward && fl(MenuPred::CAN_MOVE_BACKWARD, m_pred)); menu.Enable(m_id, enable); } MenuPred::MenuPred(predicate_t predicate) : m_predicate(predicate) {} BoundMenuPred MenuPred::GetBound(menu_item_id_t id) const{ return BoundMenuPred(id, m_predicate); } }
37.333333
80
0.703256
lukas-ke
91fe5ec015a859e4baf8fbfd0bede4e736578a86
1,417
hpp
C++
node/silkworm/stagedsync/stage_senders.hpp
elmato/silkworm
711c73547cd1f7632ff02d5f86dfac5b0d249344
[ "Apache-2.0" ]
null
null
null
node/silkworm/stagedsync/stage_senders.hpp
elmato/silkworm
711c73547cd1f7632ff02d5f86dfac5b0d249344
[ "Apache-2.0" ]
null
null
null
node/silkworm/stagedsync/stage_senders.hpp
elmato/silkworm
711c73547cd1f7632ff02d5f86dfac5b0d249344
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021-2022 The Silkworm Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef SILKWORM_STAGEDSYNC_STAGE_SENDERS_HPP_ #define SILKWORM_STAGEDSYNC_STAGE_SENDERS_HPP_ #include <silkworm/stagedsync/common.hpp> #include <silkworm/stagedsync/stage_senders/recovery_farm.hpp> namespace silkworm::stagedsync { class Senders final : public IStage { public: explicit Senders(NodeSettings* node_settings) : IStage(db::stages::kSendersKey, node_settings){}; ~Senders() override = default; StageResult forward(db::RWTxn& txn) final; StageResult unwind(db::RWTxn& txn, BlockNum to) final; StageResult prune(db::RWTxn& txn) final; std::vector<std::string> get_log_progress() final; bool stop() final; private: std::unique_ptr<recovery::RecoveryFarm> farm_{nullptr}; }; } // namespace silkworm::stagedsync #endif // SILKWORM_STAGEDSYNC_STAGE_SENDERS_HPP_
32.953488
101
0.754411
elmato
6201580492f357eb45a9360ec184df9935f3f922
668
cpp
C++
UVA00455.cpp
MaSteve/UVA-problems
3a240fcca02e24a9c850b7e86062f8581df6f95f
[ "MIT" ]
17
2015-12-08T18:50:03.000Z
2022-03-16T01:23:20.000Z
UVA00455.cpp
MaSteve/UVA-problems
3a240fcca02e24a9c850b7e86062f8581df6f95f
[ "MIT" ]
null
null
null
UVA00455.cpp
MaSteve/UVA-problems
3a240fcca02e24a9c850b7e86062f8581df6f95f
[ "MIT" ]
6
2017-04-04T18:16:23.000Z
2020-06-28T11:07:22.000Z
#include <iostream> using namespace std; int main() { int T; bool first = false; cin >> T; while (T--) { if (first) printf("\n"); else first = true; string s; cin >> s; int i = 1; for (; i < s.length(); i++) { if (s.length() % i == 0) { bool ok = true; for (int j = 0; j < i && ok; j++) { for (int k = 1; k * i + j < s.length() && ok; k++) { ok = (s[j] == s[j + k * i]); } } if (ok) break; } } printf("%d\n", i); } return 0; }
23.034483
72
0.314371
MaSteve
6201cd24ce5a7f05c39a41e0ccc84a601d0df075
518
cc
C++
c++/Programmazione 2/funzionisuperiori.cc
paoli7612/homework
17a0d8f9bfbbcbe6a615a5b9e2b2276ac5e6f267
[ "Apache-2.0" ]
null
null
null
c++/Programmazione 2/funzionisuperiori.cc
paoli7612/homework
17a0d8f9bfbbcbe6a615a5b9e2b2276ac5e6f267
[ "Apache-2.0" ]
null
null
null
c++/Programmazione 2/funzionisuperiori.cc
paoli7612/homework
17a0d8f9bfbbcbe6a615a5b9e2b2276ac5e6f267
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int map(int (*fun)(const int*, const int), const int* array, const int len) { return fun(array, len); } int sum(const int* array, const int len) { int s = 0; for (int i=0; i<len; i++) s += array[i]; return s; } int prod(const int* array, const int len) { int s = 1; for (int i=0; i<len; i++) s *= array[i]; return s; } int main(int argc, char **argv) { int a[] = {1, 2, 3, 4}; cout << map(sum, a, 4) << endl; cout << map(prod, a, 4) << endl; return 0; }
14.388889
75
0.571429
paoli7612