hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
b12d4c85a93587dca488414f0b1498bdfabdce6c
13,372
cpp
C++
Source/Kaggle.cpp
JakobStruye/AILib
7cd76c409aa77a8da615204fa5fd9d1724c5f8bb
[ "Zlib" ]
null
null
null
Source/Kaggle.cpp
JakobStruye/AILib
7cd76c409aa77a8da615204fa5fd9d1724c5f8bb
[ "Zlib" ]
null
null
null
Source/Kaggle.cpp
JakobStruye/AILib
7cd76c409aa77a8da615204fa5fd9d1724c5f8bb
[ "Zlib" ]
null
null
null
/*#include <SFML/Graphics.hpp> #include <rbf/SDRNetwork.h> #include <time.h> #include <iostream> #include <random> #include <array> #include <fstream> #include <sstream> #include <string> //#include <dirent.h> struct Label { std::string _name; std::vector<std::string> _members; Label(const std::string &name) : _name(name) {} }; int main() { std::vector<Label> labels; DIR *dir; dirent *ent; int totalImages = 0; int numReadFromEachDir = 5; if ((dir = opendir("Resources/train")) != nullptr) { readdir(dir); readdir(dir); while ((ent = readdir(dir)) != nullptr) { labels.push_back(Label(ent->d_name)); DIR *innerDir; // Get names of all files in this directory as members if ((innerDir = opendir((std::string("Resources/train/") + std::string(ent->d_name)).c_str())) != nullptr) { dirent *innerEnt; readdir(innerDir); readdir(innerDir); while ((innerEnt = readdir(innerDir)) != nullptr && labels.back()._members.size() < numReadFromEachDir) { if (std::string(innerEnt->d_name) != "") { labels.back()._members.push_back(innerEnt->d_name); totalImages++; } } closedir(innerDir); } } closedir(dir); } else { std::cerr << "Could not open Resources/train!" << std::endl; return 0; } sdr::SDRNetwork sdrnet; std::mt19937 generator(time(nullptr)); std::vector<sdr::SDRNetwork::LayerDesc> layerDescs(3); layerDescs[0]._width = 64; layerDescs[0]._height = 64; layerDescs[0]._receptiveRadius = 9; layerDescs[0]._inhibitionRadius = 6; layerDescs[1]._width = 48; layerDescs[1]._height = 48; layerDescs[1]._receptiveRadius = 9; layerDescs[1]._inhibitionRadius = 6; layerDescs[2]._width = 32; layerDescs[2]._height = 32; layerDescs[2]._receptiveRadius = 9; layerDescs[2]._inhibitionRadius = 6; const int inputWidth = 64; const int inputHeight = 64; sdrnet.createRandom(inputWidth, inputHeight, layerDescs, labels.size(), -0.01f, 0.01f, 0.0f, 0.05f, -0.01f, 0.01f, generator); sf::RenderTexture resizeTexture; resizeTexture.create(inputWidth, inputHeight); sf::RectangleShape clearRect; clearRect.setSize(sf::Vector2f(inputWidth, inputHeight)); clearRect.setFillColor(sf::Color::White); std::uniform_int_distribution<int> distImage(0, totalImages - 1); const float byteInv = 1.0f / 255.0f; int unsupervisedIterations = 1500; int supervisedIterations = 1000; for (int i = 0; i < unsupervisedIterations; i++) { resizeTexture.draw(clearRect); int index = distImage(generator); int li = 0; int mi = 0; int c = 0; for (int l = 0; l < labels.size(); l++) { int pc = c; c += labels[l]._members.size(); if (c > index) { li = l; mi = index - pc; break; } } sf::Texture source; if (!source.loadFromFile("Resources/train/" + labels[li]._name + "/" + labels[li]._members[mi])) { std::cerr << "Could not load \"" << ("Resources/train/" + labels[li]._name + "/" + labels[li]._members[mi]) << "\"!" << std::endl; continue; } source.setSmooth(true); sf::Sprite sprite; sprite.setTexture(source); sprite.setOrigin(source.getSize().x * 0.5f, source.getSize().y * 0.5f); sprite.setPosition(inputWidth / 2.0f, inputHeight / 2.0f); float scale = std::min(static_cast<float>(inputWidth) / source.getSize().x, static_cast<float>(inputHeight) / source.getSize().y); sprite.setScale(scale, scale); resizeTexture.draw(sprite); resizeTexture.display(); sf::Image resizedImage = resizeTexture.getTexture().copyToImage(); std::vector<float> input(resizedImage.getSize().x * resizedImage.getSize().y); for (int x = 0; x < inputWidth; x++) for (int y = 0; y < inputHeight; y++) { sf::Color color = resizedImage.getPixel(x, y); float greyscale = color.r * byteInv * 0.299f + color.g * byteInv * 0.587f + color.b * byteInv * 0.114f; input[x + y * inputWidth] = greyscale; } std::vector<float> output; sdrnet.getOutput(input, output, generator); sdrnet.updateUnsupervised(input, 0.001f, 0.01f, 0.005f); if (i % 25 == 0) std::cout << i / static_cast<float>(unsupervisedIterations) * 100.0f << "%" << std::endl; } sf::Image rfImage; sdrnet.getReceptiveFields(0, rfImage); rfImage.saveToFile("rfsnet.png"); for (int i = 0; i < supervisedIterations; i++) { resizeTexture.draw(clearRect); int index = distImage(generator); int li = 0; int mi = 0; int c = 0; for (int l = 0; l < labels.size(); l++) { int pc = c; c += labels[l]._members.size(); if (c > index) { li = l; mi = index - pc; break; } } sf::Texture source; if (!source.loadFromFile("Resources/train/" + labels[li]._name + "/" + labels[li]._members[mi])) { std::cerr << "Could not load \"" << ("Resources/train/" + labels[li]._name + "/" + labels[li]._members[mi]) << "\"!" << std::endl; continue; } source.setSmooth(true); sf::Sprite sprite; sprite.setTexture(source); sprite.setOrigin(source.getSize().x * 0.5f, source.getSize().y * 0.5f); sprite.setPosition(inputWidth / 2.0f, inputHeight / 2.0f); float scale = std::min(static_cast<float>(inputWidth) / source.getSize().x, static_cast<float>(inputHeight) / source.getSize().y); sprite.setScale(scale, scale); resizeTexture.draw(sprite); resizeTexture.display(); sf::Image resizedImage = resizeTexture.getTexture().copyToImage(); std::vector<float> input(resizedImage.getSize().x * resizedImage.getSize().y); for (int x = 0; x < inputWidth; x++) for (int y = 0; y < inputHeight; y++) { sf::Color color = resizedImage.getPixel(x, y); float greyscale = color.r * byteInv * 0.299f + color.g * byteInv * 0.587f + color.b * byteInv * 0.114f; input[x + y * inputWidth] = greyscale; } std::vector<float> output; sdrnet.getOutput(input, output, generator); int givenLabel = 0; for (int l = 1; l < output.size(); l++) { if (output[l] > output[givenLabel]) givenLabel = l; } std::vector<float> target(output.size(), 0.0f); target[li] = 1.0f; if (li == givenLabel) std::cout << "g"; sdrnet.updateSupervised(input, output, target, 0.005f, 0.001f, 0.3f); if (i % 25 == 0) std::cout << i / static_cast<float>(supervisedIterations) * 100.0f << "%" << std::endl; } std::ofstream toFile("result.csv"); toFile << "image,"; for (int l = 0; l < labels.size(); l++) if (l == labels.size() - 1) toFile << labels[l]._name; else toFile << labels[l]._name << ","; toFile << std::endl; // Export results DIR *testDir; dirent *testEnt; if ((testDir = opendir("Resources/test/test")) != nullptr) { readdir(testDir); readdir(testDir); while ((testEnt = readdir(testDir)) != nullptr) { std::string fullName = "Resources/test/test/" + std::string(testEnt->d_name); sf::Texture source; if (!source.loadFromFile(fullName)) { std::cerr << "Could not load \"" << fullName << "\"!" << std::endl; continue; } std::cout << "Eval: " << std::string(testEnt->d_name) << std::endl; toFile << std::string(testEnt->d_name) + ","; source.setSmooth(true); sf::Sprite sprite; sprite.setTexture(source); sprite.setOrigin(source.getSize().x * 0.5f, source.getSize().y * 0.5f); sprite.setPosition(inputWidth / 2.0f, inputHeight / 2.0f); float scale = std::min(static_cast<float>(inputWidth) / source.getSize().x, static_cast<float>(inputHeight) / source.getSize().y); sprite.setScale(scale, scale); resizeTexture.draw(sprite); resizeTexture.display(); sf::Image resizedImage = resizeTexture.getTexture().copyToImage(); std::vector<float> input(resizedImage.getSize().x * resizedImage.getSize().y); for (int x = 0; x < inputWidth; x++) for (int y = 0; y < inputHeight; y++) { sf::Color color = resizedImage.getPixel(x, y); float greyscale = color.r * byteInv * 0.299f + color.g * byteInv * 0.587f + color.b * byteInv * 0.114f; input[x + y * inputWidth] = greyscale; } std::vector<float> output; sdrnet.getOutput(input, output, generator); for (int i = 0; i < output.size(); i++) if (i == output.size() - 1) toFile << output[i]; else toFile << output[i] << ","; toFile << std::endl; } closedir(testDir); } toFile.close(); sf::RenderWindow window; window.create(sf::VideoMode(800, 600), "SDRRBFNetwork", sf::Style::Default); // Test int correct = 0; int testTotal = 0; float logSum = 0.0f; int currentLi = 0; int currentMi = 0; int currentGiven = 0; bool testKeyPressedLastFrame = false; // ----------------------------- Game Loop ----------------------------- bool quit = false; sf::Clock clock; float dt = 0.017f; bool first = true; sf::Font font; font.loadFromFile("Resources/arial.ttf"); sf::Image currentImage; std::vector<sf::Image> rbfImages; do { clock.restart(); // ----------------------------- Input ----------------------------- sf::Event windowEvent; while (window.pollEvent(windowEvent)) { switch (windowEvent.type) { case sf::Event::Closed: quit = true; break; } } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) quit = true; if (first || (!testKeyPressedLastFrame && sf::Keyboard::isKeyPressed(sf::Keyboard::T))) { resizeTexture.draw(clearRect); int index = distImage(generator); int li = 0; int mi = 0; int c = 0; for (int l = 0; l < labels.size(); l++) { int pc = c; c += labels[l]._members.size(); if (c > index) { li = l; mi = index - pc; break; } } sf::Texture source; if (!source.loadFromFile("Resources/train/" + labels[li]._name + "/" + labels[li]._members[mi])) { std::cerr << "Could not load \"" << ("Resources/train/" + labels[li]._name + "/" + labels[li]._members[mi]) << "\"!" << std::endl; continue; } source.setSmooth(true); sf::Sprite sprite; sprite.setTexture(source); sprite.setOrigin(source.getSize().x * 0.5f, source.getSize().y * 0.5f); sprite.setPosition(inputWidth / 2.0f, inputHeight / 2.0f); float scale = std::min(static_cast<float>(inputWidth) / source.getSize().x, static_cast<float>(inputHeight) / source.getSize().y); sprite.setScale(scale, scale); resizeTexture.draw(sprite); resizeTexture.display(); sf::Image resizedImage = resizeTexture.getTexture().copyToImage(); currentImage = resizedImage; std::vector<float> input(resizedImage.getSize().x * resizedImage.getSize().y); for (int x = 0; x < inputWidth; x++) for (int y = 0; y < inputHeight; y++) { sf::Color color = resizedImage.getPixel(x, y); float greyscale = color.r * byteInv * 0.299f + color.g * byteInv * 0.587f + color.b * byteInv * 0.114f; input[x + y * inputWidth] = greyscale; } std::vector<float> output; sdrnet.getOutput(input, output, generator); int givenLabel = 0; for (int l = 1; l < output.size(); l++) if (output[l] > output[givenLabel]) givenLabel = l; if (givenLabel == li) correct++; const float threshold = std::numeric_limits<float>::epsilon(); logSum += std::log(std::max(threshold, std::min(1.0f - threshold, output[li]))); testTotal++; currentLi = li; currentMi = mi; currentGiven = givenLabel; sdrnet.getImages(rbfImages); } first = false; testKeyPressedLastFrame = sf::Keyboard::isKeyPressed(sf::Keyboard::T); // ---------------------------- Rendering ---------------------------- window.clear(sf::Color::Blue); sf::Texture currentTexture; currentTexture.loadFromImage(currentImage); sf::Sprite sprite; sprite.setTexture(currentTexture); sprite.setOrigin(inputWidth / 2, inputHeight / 2); sprite.setPosition(400, 300); sprite.setScale(2.0f, 2.0f); window.draw(sprite); sf::Text text; text.setFont(font); text.setString("Actual: " + labels[currentLi]._name); text.setPosition(2.0f, 40.0f); window.draw(text); text.setString("Guess: " + labels[currentGiven]._name); text.setPosition(2.0f, 2.0f); window.draw(text); text.setString("% Correct: " + std::to_string(static_cast<float>(correct) / testTotal * 100.0f)); text.setPosition(2.0f, 548.0f); window.draw(text); text.setString("Log Loss: " + std::to_string(-logSum / testTotal)); text.setPosition(2.0f, 508.0f); window.draw(text); // Render RBF node states for (int l = 0; l < rbfImages.size(); l++) { sf::Texture layerTexture; layerTexture.loadFromImage(rbfImages[l]); sf::Sprite layerSprite; layerSprite.setTexture(layerTexture); layerSprite.setScale(2.0f, 2.0f); layerSprite.setPosition(800.0f - layerTexture.getSize().x * 2.0f, l * 128.0f); window.draw(layerSprite); } // ------------------------------------------------------------------- window.display(); dt = clock.getElapsedTime().asSeconds(); } while (!quit); }*/
24.007181
135
0.599462
JakobStruye
b12fc653ec42e9454da75e1f8ff8228692932820
1,741
cc
C++
testing/benchmarks/benchmark_shortmultiplication.cc
WarpRules/WVLInt
d446687e9fa9bc1118576f9f979e9e37cc5729f0
[ "MIT" ]
1
2020-04-19T22:10:53.000Z
2020-04-19T22:10:53.000Z
testing/benchmarks/benchmark_shortmultiplication.cc
WarpRules/WVLInt
d446687e9fa9bc1118576f9f979e9e37cc5729f0
[ "MIT" ]
null
null
null
testing/benchmarks/benchmark_shortmultiplication.cc
WarpRules/WVLInt
d446687e9fa9bc1118576f9f979e9e37cc5729f0
[ "MIT" ]
null
null
null
#include "../WMPInt.hh" #include "benchmark_timer.hh" #include <random> #include <memory> namespace { std::mt19937_64 rngEngine(0); volatile std::uint64_t gValueSink1, gValueSink2; } template<std::size_t kSize> void runMultiplicationBenchmark(std::size_t totalIterations) { std::unique_ptr<WMPUInt<kSize>> value1(new WMPUInt<kSize>); std::uint64_t resultSumMSW = 0, resultSumLSW = 0; for(std::size_t i = 0; i < kSize; ++i) { value1->data()[i] = rngEngine(); } Timer timer; std::uint64_t rhs = rngEngine(); for(std::size_t i = 0; i < totalIterations; ++i) { *value1 *= rhs; resultSumMSW += value1->data()[0]; resultSumLSW += value1->data()[kSize-1]; rhs += 3; } gValueSink1 = resultSumMSW; gValueSink2 = resultSumLSW; timer.printResult(kSize, totalIterations); } int main() { std::printf("Benchmarks for WMPUInt::operator*=(std::uint64_t):\n"); runMultiplicationBenchmark<2>(400000000); runMultiplicationBenchmark<3>(250000000); runMultiplicationBenchmark<4>(200000000); runMultiplicationBenchmark<5>(180000000); runMultiplicationBenchmark<6>(150000000); runMultiplicationBenchmark<7>(120000000); runMultiplicationBenchmark<8>(100000000); runMultiplicationBenchmark<10>(80000000); runMultiplicationBenchmark<16>(50000000); runMultiplicationBenchmark<24>(35000000); runMultiplicationBenchmark<32>(25000000); runMultiplicationBenchmark<50>(15000000); runMultiplicationBenchmark<150>(5000000); runMultiplicationBenchmark<256>(3000000); runMultiplicationBenchmark<1024>(800000); runMultiplicationBenchmark<1024*16>(50000); runMultiplicationBenchmark<1024*64>(12000); }
28.540984
72
0.699598
WarpRules
b12fcc072a1ac4d7084b78e82c6fad41f7babf9c
2,199
cxx
C++
MITK/Applications/CorrectVideoDistortion/niftkCorrectVideoDistortion.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
13
2018-07-28T13:36:38.000Z
2021-11-01T19:17:39.000Z
MITK/Applications/CorrectVideoDistortion/niftkCorrectVideoDistortion.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
null
null
null
MITK/Applications/CorrectVideoDistortion/niftkCorrectVideoDistortion.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
10
2018-08-20T07:06:00.000Z
2021-07-07T07:55:27.000Z
/*============================================================================= NifTK: A software platform for medical image computing. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #include <cstdlib> #include <mitkCorrectVideoFileDistortion.h> #include <mitkCorrectImageDistortion.h> #include <niftkCorrectVideoDistortionCLP.h> int main(int argc, char** argv) { PARSE_ARGS; bool successful = false; if ( input.length() == 0 || intrinsicLeft.length() == 0 || distortionLeft.length() == 0 || output.length() == 0 ) { commandLine.getOutput()->usage(commandLine); return EXIT_FAILURE; } if (input == output) { std::cerr << "Output filename is the same as the input ... I'm giving up." << std::endl; return EXIT_FAILURE; } bool isVideo = false; if (input.find_last_of(".") != std::string::npos) { std::string extension = input.substr(input.find_last_of(".")+1); if (extension == "avi") { isVideo = true; } } if (isVideo) { // Only supporting stereo video for now. if ( intrinsicRight.length() == 0 || distortionRight.length() == 0 ) { std::cerr << "For processing stereo video, the right channel must be specified" << std::endl; return EXIT_FAILURE; } mitk::CorrectVideoFileDistortion::Pointer correction = mitk::CorrectVideoFileDistortion::New(); successful = correction->Correct( input, intrinsicLeft, distortionLeft, intrinsicRight, distortionRight, output, writeInterleaved ); } else { mitk::CorrectImageDistortion::Pointer correction = mitk::CorrectImageDistortion::New(); successful = correction->Correct(input, intrinsicLeft, distortionLeft, output); } if (successful) { return EXIT_SUCCESS; } else { return EXIT_FAILURE; } }
24.707865
99
0.601182
NifTK
b13cdb21606690801381068e6f084a14399364de
5,489
cpp
C++
UICreator/Windows/PropertyWindows/BtnProperties.cpp
rohmer/LVGL_UI_Creator
37a19be55e1de95d56717786a27506d8c78fd1ae
[ "MIT" ]
33
2019-09-17T20:57:56.000Z
2021-11-20T21:50:51.000Z
UICreator/Windows/PropertyWindows/BtnProperties.cpp
rohmer/LVGL_UI_Creator
37a19be55e1de95d56717786a27506d8c78fd1ae
[ "MIT" ]
4
2019-10-21T08:38:11.000Z
2021-11-17T16:53:08.000Z
UICreator/Windows/PropertyWindows/BtnProperties.cpp
rohmer/LVGL_UI_Creator
37a19be55e1de95d56717786a27506d8c78fd1ae
[ "MIT" ]
16
2019-09-25T04:25:04.000Z
2022-03-28T07:46:18.000Z
#include "BtnProperties.h" lv_obj_t *BtnProperties::inkIn, *BtnProperties::inkOut, *BtnProperties::inkWait, *BtnProperties::toggle, *BtnProperties::layout, *BtnProperties::fitTop, *BtnProperties::fitBot, *BtnProperties::fitRight, *BtnProperties::fitLeft; lv_obj_t *BtnProperties::rel, *BtnProperties::ina, *BtnProperties::pr, *BtnProperties::tglPr, *BtnProperties::tglRel; void BtnProperties::CreateBtnProperties(PropertyWindow* pw) { pw->ObjectPropWin()->UpdateHeight(450); lv_obj_t* cont = lv_cont_create(pw->ObjectPropWin()->GetWindow(), nullptr); lv_cont_set_layout(cont, LV_LAYOUT_PRETTY); lv_cont_set_fit(cont, LV_FIT_FILL); pw->ObjectPropWin()->AddObjectToWindow(cont); lv_obj_t* props1 = lv_cont_create(cont, nullptr); lv_cont_set_layout(props1, LV_LAYOUT_PRETTY); lv_obj_set_size(props1, 370, 50); inkIn = PropertyControls::createNumericEntry(pw, props1, "Ink In", "/button/ink/in"); inkOut = PropertyControls::createNumericEntry(pw, props1, "Ink Out", "/button/ink/out"); inkWait = PropertyControls::createNumericEntry(pw, props1, "Ink Wait", "/button/ink/wait"); lv_obj_t* props2 = lv_cont_create(cont, nullptr); lv_cont_set_layout(props2, LV_LAYOUT_PRETTY); lv_obj_set_size(props2, 370, 100); toggle = lv_cb_create(props2, nullptr); lv_cb_set_text(toggle, "Toggle"); lv_obj_t* lLab = lv_label_create(props2, nullptr); lv_label_set_text(lLab, "Layout"); layout = lv_ddlist_create(props2, nullptr); lv_ddlist_set_options(layout, "Off\nCenter\nColumn Left\nColumn Mid\nColumn Right\nRow Top\nRow Mid\nRow Bottom\nPretty\nGrid"); lv_obj_set_user_data(layout, pw); lv_obj_set_event_cb(layout, layoutCB); std::string fits = "None\nTight\nFlood\nFill"; lv_obj_t* props3 = lv_cont_create(cont, nullptr); lv_cont_set_layout(props3, LV_LAYOUT_PRETTY); lv_obj_set_size(props3, 370, 100); lv_obj_t* fLeft= lv_label_create(props3, nullptr); lv_label_set_text(fLeft, "Fit Left"); fitLeft = lv_ddlist_create(props3, nullptr); lv_ddlist_set_options(fitLeft, fits.c_str()); sFitStruct* lfs = new sFitStruct(); lfs->fitNum = 0; lfs->pw = pw; lv_obj_set_user_data(fitLeft, lfs); lv_obj_set_event_cb(fitLeft, fitCB); lv_obj_t* fTop = lv_label_create(props3, nullptr); lv_label_set_text(fTop, "Fit Top"); fitTop= lv_ddlist_create(props3, nullptr); lv_ddlist_set_options(fitTop, fits.c_str()); sFitStruct* tfs = new sFitStruct(); tfs->fitNum = 1; tfs->pw = pw; lv_obj_set_user_data(fitTop, tfs); lv_obj_set_event_cb(fitTop, fitCB); lv_obj_t* props4 = lv_cont_create(cont, nullptr); lv_cont_set_layout(props4, LV_LAYOUT_PRETTY); lv_obj_set_size(props4, 370, 100); lv_obj_t* fright = lv_label_create(props4, nullptr); lv_label_set_text(fright, "Fit Right"); fitRight = lv_ddlist_create(props4, nullptr); lv_ddlist_set_options(fitRight, fits.c_str()); sFitStruct* rfs = new sFitStruct(); rfs->fitNum = 2; rfs->pw = pw; lv_obj_set_user_data(fitRight, lfs); lv_obj_set_event_cb(fitRight, fitCB); lv_obj_t* fBot = lv_label_create(props4, nullptr); lv_label_set_text(fBot, "Fit Bottom"); fitBot = lv_ddlist_create(props4, nullptr); lv_ddlist_set_options(fitBot, fits.c_str()); sFitStruct* bfs = new sFitStruct(); bfs->fitNum = 3; bfs->pw = pw; lv_obj_set_user_data(fitBot, tfs); lv_obj_set_event_cb(fitBot, fitCB); } void BtnProperties::fitCB(lv_obj_t* obj, lv_event_t event) { sFitStruct* fs = (sFitStruct*)lv_obj_get_user_data(obj); if (fs->pw->Drawing()) return; if (event == LV_EVENT_CLICKED) { lv_group_t* kbGroup = fs->pw->GetKBGroup(); lv_group_remove_all_objs(kbGroup); lv_group_add_obj(kbGroup, obj); } if(event==LV_EVENT_VALUE_CHANGED) { int fLeft = lv_btn_get_fit_left(obj); int fTop = lv_btn_get_fit_top(obj); int fRight = lv_btn_get_fit_right(obj); int fBot = lv_btn_get_fit_bottom(obj); if(fs->fitNum==0) { lv_btn_set_fit4(obj, lv_ddlist_get_selected(obj), fRight, fTop, fBot); return; } if (fs->fitNum == 1) { lv_btn_set_fit4(obj, fLeft, fRight, lv_ddlist_get_selected(obj), fBot); return; } if (fs->fitNum == 2) { lv_btn_set_fit4(obj, fLeft, lv_ddlist_get_selected(obj), fTop, fBot); return; } if (fs->fitNum == 3) { lv_btn_set_fit4(obj, fLeft, fRight, fTop, lv_ddlist_get_selected(obj)); return; } } } void BtnProperties::layoutCB(lv_obj_t* obj, lv_event_t event) { sFitStruct* fs = (sFitStruct*)lv_obj_get_user_data(obj); if (fs->pw->Drawing()) return; if (event == LV_EVENT_CLICKED) { lv_group_t* kbGroup = fs->pw->GetKBGroup(); lv_group_remove_all_objs(kbGroup); lv_group_add_obj(kbGroup, obj); } if (event == LV_EVENT_VALUE_CHANGED) { lv_btn_set_layout(obj, lv_ddlist_get_selected(obj)); } } void BtnProperties::UpdateBtnProperties(PropertyWindow* pw, json j) { pw->Drawing(true); if (pw->CurrentlyLoadedProp != PropertyWindow::eObjType::BUTTON) { pw->ObjectPropWin()->DeleteChildren(); CreateBtnProperties(pw); pw->CurrentlyLoadedProp = PropertyWindow::eObjType::BUTTON; } pw->Drawing(false); }
36.350993
235
0.675351
rohmer
b13e6fadb30260c6d1ec19809ce757f2283316cd
1,322
cpp
C++
src/executor.cpp
dixitgarg059/SimpleRA
0ecd8adb5b66f06256c28323bc57b5901f5c94e1
[ "MIT" ]
null
null
null
src/executor.cpp
dixitgarg059/SimpleRA
0ecd8adb5b66f06256c28323bc57b5901f5c94e1
[ "MIT" ]
null
null
null
src/executor.cpp
dixitgarg059/SimpleRA
0ecd8adb5b66f06256c28323bc57b5901f5c94e1
[ "MIT" ]
null
null
null
#include "global.h" void executeCommand() { switch (parsedQuery.queryType) { case CLEAR: executeCLEAR(); break; case CROSS: executeCROSS(); break; case DISTINCT: executeDISTINCT(); break; case EXPORT: executeEXPORT(); break; case INDEX: executeINDEX(); break; case JOIN: executeJOIN(); break; case LIST: executeLIST(); break; case LOAD: executeLOAD(); break; case PRINT: executePRINT(); break; case PROJECTION: executePROJECTION(); break; case RENAME: executeRENAME(); break; case SELECTION: executeSELECTION(); break; case SORT: executeSORT(); break; case SOURCE: executeSOURCE(); break; case LOAD_MATRIX: ExecuteLoadMatrix(); break; case PRINT_MATRIX: ExecutePrintMatrix(); break; case EXPORT_MATRIX: ExecuteExportMatrix(); break; case TRANSPOSE: ExecuteTranspose(); break; default: cout << "PARSING ERROR" << endl; } return; } void printRowCount(int rowCount) { cout << "\n\nRow Count: " << rowCount << endl; return; }
17.864865
50
0.520424
dixitgarg059
b140fcf86cd5552d8afcc644ddc9a79b9fc166fb
1,231
cpp
C++
p371e/get_sum.cpp
l33tdaima/l33tdaima
0a7a9573dc6b79e22dcb54357493ebaaf5e0aa90
[ "MIT" ]
1
2020-02-20T12:04:46.000Z
2020-02-20T12:04:46.000Z
p371e/get_sum.cpp
l33tdaima/l33tdaima
0a7a9573dc6b79e22dcb54357493ebaaf5e0aa90
[ "MIT" ]
null
null
null
p371e/get_sum.cpp
l33tdaima/l33tdaima
0a7a9573dc6b79e22dcb54357493ebaaf5e0aa90
[ "MIT" ]
null
null
null
// g++ -std=c++11 *.cpp -o test && ./test && rm -f test #include <vector> #include <limits> #include <iostream> using namespace std; class Solution { public: int getSum(int a, int b) { int sum = a ^ b; int carry = a & b; if (carry) { return getSum(sum, carry << 1); } else { return sum; } } int getSumIter(int a, int b) { int sum = a ^ b; int carry = a & b; while (carry != 0) { int newcarry = sum & (carry << 1); sum = sum ^ (carry << 1); carry = newcarry; } return sum; } int getSumIterV2(int a, int b) { while (b != 0) { int carry = a & b; a = a ^ b; b = carry << 1; } return a; } }; // TESTS int main(int argc, char const *argv[]) { vector< vector<int> > tests = { {1, 2}, {232, -76}, {2, 3}, {0, 4}, {4, 0} }; Solution sol; for (auto& t: tests) { assert(sol.getSum(t[0], t[1]) == t[0] + t[1]); assert(sol.getSumIter(t[0], t[1]) == t[0] + t[1]); assert(sol.getSumIterV2(t[0], t[1]) == t[0] + t[1]); } return 0; }
21.982143
60
0.418359
l33tdaima
b143e72955bf1407036f56934005582015bb04ce
4,813
hpp
C++
Source/AllProjects/WndUtils/CIDWUtils/CIDWUtils_2ColSectList.hpp
eudora-jia/CIDLib
02795d283d95f8a5a4fafa401b6189851901b81b
[ "MIT" ]
1
2019-05-28T06:33:01.000Z
2019-05-28T06:33:01.000Z
Source/AllProjects/WndUtils/CIDWUtils/CIDWUtils_2ColSectList.hpp
eudora-jia/CIDLib
02795d283d95f8a5a4fafa401b6189851901b81b
[ "MIT" ]
null
null
null
Source/AllProjects/WndUtils/CIDWUtils/CIDWUtils_2ColSectList.hpp
eudora-jia/CIDLib
02795d283d95f8a5a4fafa401b6189851901b81b
[ "MIT" ]
null
null
null
// // FILE NAME: CIDCtrls_2ColSectList.hpp // // AUTHOR: Dean Roddey // // CREATED: 01/20/2016 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements a convenient variation of the multi-column list box. It allows // you to display lists of key=value pair values with section titles, and nice divider // lines. Mostly it's just handling some custom draw. // // Client code just needs to set the per-row flag to true to have it be treated as a // section divider, in which case only the key part of the row is used, as the divider // text. We provide helper methods for adding a divider and non-divider row, which you // should use. // // Otherwise it's basically just a multi-column list box. Though we do create a // zero width 0th column, so that the left column can be right justified. // // It's read only, unless the client code derives from it and enabled any sort of // editing. // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) // --------------------------------------------------------------------------- // CLASS: T2ColSectList // PREFIX: wnd // --------------------------------------------------------------------------- class CIDWUTILSEXP T2ColSectList : public TMultiColListBox { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- T2ColSectList(); T2ColSectList(const T2ColSectList&) = delete; ~T2ColSectList(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- T2ColSectList& operator=(const T2ColSectList&) = delete; // ------------------------------------------------------------------- // Public, inherited methods // ------------------------------------------------------------------- tCIDLib::TVoid InitFromDesc ( const TWindow& wndParent , const TDlgItem& dlgiSrc , const tCIDCtrls::EWndThemes eTheme ) override; tCIDLib::TVoid QueryHints ( tCIDLib::TStrCollect& colToFill ) const override; // ------------------------------------------------------------------- // Public, non-virtual methods // ------------------------------------------------------------------- tCIDLib::TVoid AddDataRow ( const TString& strKey , const TString& strValue , const tCIDLib::TCard4 c4RowId = 0 ); tCIDLib::TVoid AddSectTitle ( const TString& strTitle ); protected : // ------------------------------------------------------------------- // Protected, inherited methods // ------------------------------------------------------------------- tCIDLib::TBoolean bCreated() override; tCIDLib::TBoolean bEraseBgn ( TGraphDrawDev& gdevToUse ) override; tCIDLib::TVoid CellClicked ( const tCIDLib::TCard4 c4Row , const tCIDLib::TCard4 c4Column , const tCIDLib::TBoolean bLeftButton ) override; tCIDCtrls::EMCLBCustRets eCustomDraw ( TGraphDrawDev& gdevTar , const tCIDLib::TCard4 c4Row , const tCIDLib::TCard4 c4Column , const tCIDLib::TBoolean bPost , const TArea& areaAt , TRGBClr& rgbBgn , TRGBClr& rgbText ) override; private : // ------------------------------------------------------------------- // Private data members // // m_colTmpCols // For internal efficiency, for loading up rows. // ------------------------------------------------------------------- tCIDLib::TStrList m_colTmpCols; // ------------------------------------------------------------------- // Magic macros // ------------------------------------------------------------------- RTTIDefs(T2ColSectList, TMultiColListBox) }; #pragma CIDLIB_POPPACK
32.52027
87
0.42219
eudora-jia
b144971956577c3c8efb0a4ab7527b4f7a5556e2
1,103
cpp
C++
VehFuncs/Steer.cpp
JuniorDjjr/VehFuncs
123c9228f99efe2a14030473542e2c0fff54c82f
[ "MIT" ]
32
2018-01-23T21:38:06.000Z
2022-02-06T21:02:42.000Z
VehFuncs/Steer.cpp
JuniorDjjr/VehFuncs
123c9228f99efe2a14030473542e2c0fff54c82f
[ "MIT" ]
41
2018-03-20T00:21:50.000Z
2021-12-05T10:01:49.000Z
VehFuncs/Steer.cpp
JuniorDjjr/VehFuncs
123c9228f99efe2a14030473542e2c0fff54c82f
[ "MIT" ]
3
2019-06-17T16:46:48.000Z
2020-05-12T01:40:33.000Z
#include "VehFuncsCommon.h" #include "NodeName.h" extern float iniDefaultSteerAngle; void ProcessSteer(CVehicle *vehicle, list<RwFrame*> frames) { for (RwFrame *frame : frames) { if (frame->object.parent && FRAME_EXTENSION(frame)->owner == vehicle) { const string name = GetFrameNodeName(frame); float angle = (vehicle->m_fSteerAngle * (-1.666666f)); float maxAngle = iniDefaultSteerAngle; if (name[0] == 'f') { //f_steer180 if (isdigit(name[7])) { maxAngle = (float)stoi(&name[7]); } angle *= maxAngle; } else { //movsteer or steering //movsteer_0.5 maxAngle = 1.0f; if (name[8] == '_') { if (isdigit(name[9])) { maxAngle = stof(&name[9]); } } angle *= 90.0f; angle *= maxAngle; } RestoreMatrixBackup(&frame->modelling, FRAME_EXTENSION(frame)->origMatrix); RwFrameRotate(frame, (RwV3d*)0x008D2E0C, angle, rwCOMBINEPRECONCAT); RwFrameUpdateObjects(frame); } else { ExtendedData &xdata = xData.Get(vehicle); xdata.steer.remove(frame); } } }
23.468085
79
0.606528
JuniorDjjr
b148bcb118f893a6be41aa15f775e8cb8fc9ff76
2,130
hpp
C++
include/morpheus/Utils.hpp
msurkovsky/morpheus
b938de5c5863f8fa08cd768576a08a6aa7d55e65
[ "MIT" ]
1
2019-08-16T11:01:00.000Z
2019-08-16T11:01:00.000Z
include/morpheus/Utils.hpp
It4innovations/morpheus
b938de5c5863f8fa08cd768576a08a6aa7d55e65
[ "MIT" ]
null
null
null
include/morpheus/Utils.hpp
It4innovations/morpheus
b938de5c5863f8fa08cd768576a08a6aa7d55e65
[ "MIT" ]
1
2019-08-16T11:00:56.000Z
2019-08-16T11:00:56.000Z
#ifndef MRPH_UTILS_H #define MRPH_UTILS_H #include "llvm/IR/Value.h" #include <string> #include <vector> #include <functional> namespace Utils { template<typename T> void store_if_not(std::vector<T> &values, const T &v, T excl); template<typename T> std::string pp_vector(const std::vector<T> &values, std::string delim=",", std::string lbracket="", std::string rbracket="", std::function<bool(const T &)> filter_fn=[] (const T &) { return true; }); std::string value_to_type(const llvm::Value &v, bool return_constant=true); std::string value_to_str(const llvm::Value &v, std::string name, bool return_constant=true); std::string compute_envelope_type(llvm::Value const *src, llvm::Value const *dest, const llvm::Value &tag, std::string delim=",", std::string lbracket="", std::string rbracket=""); std::string compute_envelope_value(llvm::Value const *src, llvm::Value const *dest, const llvm::Value &tag, bool include_constant=true, std::string delim="", std::string lbracket="", std::string rbracket=""); std::string compute_data_buffer_type(const llvm::Value &); std::string compute_data_buffer_value(const llvm::Value &, const llvm::Value &); std::string compute_msg_rqst_value(llvm::Value const *src, llvm::Value const *dest, const llvm::Value &tag, std::string buffered, std::string delim="", std::string lbracket="", std::string rbracket=""); } #endif // MRPH_UTILS_H
36.101695
92
0.476056
msurkovsky
b148f55db8c4920418447ad0e4d571bf43134d7d
239
cpp
C++
PSFExtractionHandler/Version.cpp
Lourdle/PSFExpand
471e04831f3aab1a5152064871c2571dfe8af4e1
[ "MIT" ]
null
null
null
PSFExtractionHandler/Version.cpp
Lourdle/PSFExpand
471e04831f3aab1a5152064871c2571dfe8af4e1
[ "MIT" ]
null
null
null
PSFExtractionHandler/Version.cpp
Lourdle/PSFExpand
471e04831f3aab1a5152064871c2571dfe8af4e1
[ "MIT" ]
null
null
null
#include "pch.h" #include "PSFExtHandlerFrame.h" DWORD PSFEXTRACTIONHANDLER_API PSFExtHandler_GetVersion() { return PSFEXTHANDLER_CURRENT_VERSION; } PCWSTR PSFEXTRACTIONHANDLER_API PSFExtHandler_GetVersionString() { return L"1.1.1"; }
14.058824
38
0.8159
Lourdle
b1495a1985cd8bda0dc6347be409582b805b2f90
3,002
cpp
C++
src/modules/cl/cl_vision.cpp
shobana-mcw/rpp
e4a5eb622b9abd0a5a936bf7174a84a5e2470b59
[ "MIT" ]
26
2019-09-04T17:48:41.000Z
2022-02-23T17:04:24.000Z
src/modules/cl/cl_vision.cpp
shobana-mcw/rpp
e4a5eb622b9abd0a5a936bf7174a84a5e2470b59
[ "MIT" ]
57
2019-09-06T21:37:34.000Z
2022-03-09T02:13:46.000Z
src/modules/cl/cl_vision.cpp
shobana-mcw/rpp
e4a5eb622b9abd0a5a936bf7174a84a5e2470b59
[ "MIT" ]
24
2019-09-04T23:12:07.000Z
2022-03-30T02:06:22.000Z
#include <cl/rpp_cl_common.hpp> #include "cl_declarations.hpp" /********************** Blur ************************/ float box_3x3[] = { 0.111, 0.111, 0.111, 0.111, 0.111, 0.111, 0.111, 0.111, 0.111, }; // cl_int // box_filter_cl(cl_mem srcPtr, RppiSize srcSize, // cl_mem dstPtr, unsigned int filterSize, // RppiChnFormat chnFormat, unsigned int channel, // rpp::Handle& handle) // { // unsigned short counter=0; // cl_int err; // float* filterBuffer; // if (filterSize == 3) filterBuffer= box_3x3; // else std::cerr << "Unimplemeted kernel Size"; // cl_context theContext; // clGetCommandQueueInfo( handle.GetStream(), // CL_QUEUE_CONTEXT, // sizeof(cl_context), &theContext, NULL); // cl_mem filtPtr = clCreateBuffer(theContext, CL_MEM_READ_ONLY, // sizeof(float)*filterSize*filterSize, NULL, NULL); // err = clEnqueueWriteBuffer(handle.GetStream(), filtPtr, CL_TRUE, 0, // sizeof(float)*filterSize*filterSize, // filterBuffer, 0, NULL, NULL); // cl_kernel theKernel; // cl_program theProgram; // if (chnFormat == RPPI_CHN_PLANAR) // { // CreateProgramFromBinary(handle,"convolution.cl","convolution.cl.bin","naive_convolution_planar",theProgram,theKernel); // clRetainKernel(theKernel); // // cl_kernel_initializer( handle.GetStream(), "convolution.cl", // // "naive_convolution_planar", theProgram, theKernel); // } // else if (chnFormat == RPPI_CHN_PACKED) // { // CreateProgramFromBinary(handle,"convolution.cl","convolution.cl.bin","naive_convolution_packed",theProgram,theKernel); // clRetainKernel(theKernel); // // cl_kernel_initializer( handle.GetStream(), "convolution.cl", // // "naive_convolution_packed", theProgram, theKernel); // } // else // {std::cerr << "Internal error: Unknown Channel format";} // err = clSetKernelArg(theKernel, counter++, sizeof(cl_mem), &srcPtr); // err |= clSetKernelArg(theKernel, counter++, sizeof(cl_mem), &dstPtr); // err |= clSetKernelArg(theKernel, counter++, sizeof(cl_mem), &filtPtr); // err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &srcSize.height); // err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &srcSize.width); // err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &channel); // err |= clSetKernelArg(theKernel, counter++, sizeof(unsigned int), &filterSize); // //---- // size_t gDim3[3]; // gDim3[0] = srcSize.width; // gDim3[1] = srcSize.height; // gDim3[2] = channel; // cl_kernel_implementer (handle, gDim3, NULL/*Local*/, theProgram, theKernel); // clReleaseMemObject(filtPtr); // return RPP_SUCCESS; // }
37.525
129
0.591939
shobana-mcw
b149f1b9fce687c6efc15d3b7628ffc1fba518f4
5,203
cpp
C++
src/tip/db/pg/query.cpp
zmij/pg_async
08e4078588827c87297168102d7ed6b9807ab818
[ "Artistic-2.0" ]
25
2016-02-12T14:06:23.000Z
2021-12-20T02:45:35.000Z
src/tip/db/pg/query.cpp
zmij/pg_async
08e4078588827c87297168102d7ed6b9807ab818
[ "Artistic-2.0" ]
9
2016-11-21T08:49:19.000Z
2019-07-02T10:52:35.000Z
src/tip/db/pg/query.cpp
zmij/pg_async
08e4078588827c87297168102d7ed6b9807ab818
[ "Artistic-2.0" ]
5
2018-03-16T11:46:23.000Z
2022-03-06T06:58:57.000Z
/* * query.cpp * * Created on: 11 июля 2015 г. * @author: zmij */ #include <tip/db/pg/query.hpp> #include <tip/db/pg/resultset.hpp> #include <tip/db/pg/database.hpp> #include <tip/db/pg/transaction.hpp> #include <tip/db/pg/log.hpp> #include <functional> namespace tip { namespace db { namespace pg { LOCAL_LOGGING_FACILITY_CFG(PGQUERY, config::QUERY_LOG); struct query::impl : std::enable_shared_from_this<query::impl> { dbalias alias_; transaction_mode mode_; transaction_ptr tran_; // @todo make it a weak pointer std::string expression_; type_oid_sequence param_types_; params_buffer params_; impl(dbalias const& alias, transaction_mode const& m, std::string const& expression) : alias_{alias}, mode_{m}, tran_{}, expression_{expression} { } impl(transaction_ptr tran, std::string const& expression) : alias_(tran->alias()), tran_(tran), expression_(expression) { } impl(dbalias const& alias, transaction_mode const& m, std::string const& expression, type_oid_sequence&& param_types, params_buffer&& params) : alias_{alias}, mode_{m}, tran_{}, expression_{expression}, param_types_{std::move(param_types)}, params_{std::move(params)} { } impl(transaction_ptr tran, std::string const& expression, type_oid_sequence&& param_types, params_buffer&& params) : alias_(tran->alias()), tran_(tran), expression_(expression), param_types_(std::move(param_types)), params_(std::move(params)) { } impl(impl const& rhs) : enable_shared_from_this(rhs), alias_(rhs.alias_), tran_(), expression_(rhs.expression_), param_types_(rhs.param_types_), params_(rhs.params_) { } void clear_params() { params_buffer params; io::protocol_write<BINARY_DATA_FORMAT>(params, (smallint)0); // format codes io::protocol_write<BINARY_DATA_FORMAT>(params, (smallint)0); // number of parameters } void run_async(query_result_callback const& res, error_callback const& err) { // TODO wrap res & err in strand if (!tran_) { db_service::begin( alias_, std::bind(&impl::handle_get_transaction, shared_from_this(), std::placeholders::_1, res, err), std::bind(&impl::handle_get_connection_error, shared_from_this(), std::placeholders::_1, err), mode_ ); } else { handle_get_transaction(tran_, res, err); } } void handle_get_transaction(transaction_ptr t, query_result_callback const& res, error_callback const& err) { namespace util = ::psst::util; tran_ = t; if (params_.empty()) { { local_log() << "Execute query " << (util::MAGENTA | util::BRIGHT) << expression_ << logger::severity_color(); } tran_->execute(expression_, res, err); } else { { local_log() << "Execute prepared query " << (util::MAGENTA | util::BRIGHT) << expression_ << logger::severity_color(); } tran_->execute(expression_, param_types_, params_, res, err); } tran_.reset(); } void handle_get_connection_error(error::db_error const& ec, error_callback const& err) { err(ec); } }; query::query(dbalias const& alias, std::string const& expression) : pimpl_(new impl(alias, transaction_mode{}, expression)) { } query::query(dbalias const& alias, transaction_mode const& mode, std::string const& expression) : pimpl_(new impl(alias, mode, expression)) { } query::query(transaction_ptr c, std::string const& expression) : pimpl_(new impl(c, expression)) { } query& query::bind() { pimpl_->clear_params(); return *this; } void query::run_async(query_result_callback const& res, error_callback const& err) const { pimpl_->run_async(res, err); pimpl_.reset(new impl(*pimpl_.get())); } void query::operator ()(query_result_callback const& res, error_callback const& err) const { run_async(res, err); } query::pimpl query::create_impl(dbalias const& alias, transaction_mode const& mode, std::string const& expression, type_oid_sequence&& param_types, params_buffer&& params) { return pimpl(new impl(alias, mode, expression, std::move(param_types), std::move(params))); } query::pimpl query::create_impl(transaction_ptr t, std::string const& expression, type_oid_sequence&& param_types, params_buffer&& params) { return pimpl(new impl(t, expression, std::move(param_types), std::move(params))); } query::params_buffer& query::buffer() { return pimpl_->params_; } type_oid_sequence& query::param_types() { return pimpl_->param_types_; } } // namespace pg } // namespace db } // namespace tip
26.819588
92
0.605612
zmij
b1510cc052f5d4aa66d6de79f3cdcb5f1fc305ea
327
hpp
C++
src/MaterialInterface.hpp
Attractadore/RaytracingCPU
535fa254f9bb071e922364bcbb5cae4486af73ea
[ "MIT" ]
null
null
null
src/MaterialInterface.hpp
Attractadore/RaytracingCPU
535fa254f9bb071e922364bcbb5cae4486af73ea
[ "MIT" ]
null
null
null
src/MaterialInterface.hpp
Attractadore/RaytracingCPU
535fa254f9bb071e922364bcbb5cae4486af73ea
[ "MIT" ]
null
null
null
#pragma once #include "Material.hpp" template <typename MaterialSubclass> requires std::is_base_of_v<Material, MaterialSubclass> const Material* getMaterialSubclass() { static MaterialSubclass material; return &material; } extern "C" { const Material* getMaterial(); using GetMaterialF = decltype(getMaterial); }
21.8
58
0.764526
Attractadore
b1512ddb9331e2c9f47f4ec0905e6f21e645d75f
1,424
cpp
C++
src/lib/storage/storage_manager.cpp
j-tr/DYOD_WS1920
768e0c44728e1eba7329b3183e63f107efad31a1
[ "MIT" ]
null
null
null
src/lib/storage/storage_manager.cpp
j-tr/DYOD_WS1920
768e0c44728e1eba7329b3183e63f107efad31a1
[ "MIT" ]
null
null
null
src/lib/storage/storage_manager.cpp
j-tr/DYOD_WS1920
768e0c44728e1eba7329b3183e63f107efad31a1
[ "MIT" ]
null
null
null
#include "storage_manager.hpp" #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "utils/assert.hpp" namespace opossum { StorageManager& StorageManager::get() { static StorageManager _instance; return _instance; } void StorageManager::add_table(const std::string& name, std::shared_ptr<Table> table) { auto r = _tables.insert(std::pair<std::string, std::shared_ptr<Table>>(name, table)); Assert(r.second, "Table with given name already exists"); } void StorageManager::drop_table(const std::string& name) { if (!_tables.erase(name)) { throw std::runtime_error("Table does not exist"); } } std::shared_ptr<Table> StorageManager::get_table(const std::string& name) const { return _tables.at(name); } bool StorageManager::has_table(const std::string& name) const { return _tables.find(name) != _tables.end(); } std::vector<std::string> StorageManager::table_names() const { std::vector<std::string> names; names.reserve(_tables.size()); for (auto& table : _tables) { names.push_back(table.first); } return names; } void StorageManager::print(std::ostream& out) const { for (auto& table : _tables) { out << table.first << " " << table.second->column_count() << " " << table.second->row_count() << " " << table.second->chunk_count() << std::endl; } } void StorageManager::reset() { _tables.clear(); } } // namespace opossum
27.384615
109
0.690309
j-tr
b155a737d02a767852f8ba6e0889f8615a053008
15,632
hpp
C++
src/pumipic_adjacency.hpp
cwsmith/pumi-pic
d1dada10c2f2b0f8b56b946ad8375d79cb85934b
[ "BSD-3-Clause" ]
null
null
null
src/pumipic_adjacency.hpp
cwsmith/pumi-pic
d1dada10c2f2b0f8b56b946ad8375d79cb85934b
[ "BSD-3-Clause" ]
null
null
null
src/pumipic_adjacency.hpp
cwsmith/pumi-pic
d1dada10c2f2b0f8b56b946ad8375d79cb85934b
[ "BSD-3-Clause" ]
null
null
null
#ifndef PUMIPIC_ADJACENCY_HPP #define PUMIPIC_ADJACENCY_HPP #include <iostream> #include "Omega_h_for.hpp" #include "Omega_h_adj.hpp" #include "Omega_h_element.hpp" #include "pumipic_utils.hpp" #include "pumipic_constants.hpp" //TODO use .get() to access data ? namespace pumipic { /* see description: Omega_h_simplex.hpp, Omega_h_refine_topology.hpp line 26 face_vert:0,2,1; 0,1,3; 1,2,3; 2,0,3. corresp. opp. vertexes: 3,2,0,1, by simplex_opposite_template(DIM, FDIM, iface, i) ? side note: r3d.cpp line 528: 3,2,1; 0,2,3; 0,3,1; 0,1,2 .Vertexes opp.:0,1,2,3 3 / | \ / | \ 0----|----2 \ | / \ | / 1 */ //retrieve face coords in the Omega_h order OMEGA_H_INLINE void get_face_coords(const Omega_h::Matrix<DIM, 4> &M, const Omega_h::LO iface, Omega_h::Few<Omega_h::Vector<DIM>, 3> &abc) { //face_vert:0,2,1; 0,1,3; 1,2,3; 2,0,3 OMEGA_H_CHECK(iface<4 && iface>=0); abc[0] = M[Omega_h::simplex_down_template(DIM, FDIM, iface, 0)]; abc[1] = M[Omega_h::simplex_down_template(DIM, FDIM, iface, 1)]; abc[2] = M[Omega_h::simplex_down_template(DIM, FDIM, iface, 2)]; #if DEBUG >2 std::cout << "face " << iface << ": \n"; #endif // DEBUG } OMEGA_H_INLINE void get_edge_coords(const Omega_h::Few<Omega_h::Vector<DIM>, 3> &abc, const Omega_h::LO iedge, Omega_h::Few<Omega_h::Vector<DIM>, 2> &ab) { //edge_vert:0,1; 1,2; 2,0 ab[0] = abc[Omega_h::simplex_down_template(FDIM, 1, iedge, 0)]; ab[1] = abc[Omega_h::simplex_down_template(FDIM, 1, iedge, 1)]; #ifdef DEBUG std::cout << "abc_index " << ab[0].data() << ", " << ab[1].data() << " iedge:" << iedge << "\n"; #endif // DEBUG } OMEGA_H_INLINE void check_face(const Omega_h::Matrix<DIM, 4> &M, const Omega_h::Few<Omega_h::Vector<DIM>, 3>& face, const Omega_h::LO faceid ) { Omega_h::Few<Omega_h::Vector<DIM>, 3> abc; get_face_coords( M, faceid, abc); #ifdef DEBUG print_array(abc[0].data(),3, "a"); print_array(face[0].data(),3, "face1"); print_array(abc[1].data(), 3, "b"); print_array(face[1].data(), 3, "face2"); print_array(abc[2].data(), 3, "c"); print_array(face[2].data(), 3, "face3"); #endif OMEGA_H_CHECK(true == compare_array(abc[0].data(), face[0].data(), DIM)); //a OMEGA_H_CHECK(true == compare_array(abc[1].data(), face[1].data(), DIM)); //b OMEGA_H_CHECK(true == compare_array(abc[2].data(), face[2].data(), DIM)); //c } // BC coords are not in order of its corresp. opp. vertexes. Bccoord of tet(iface, xpoint) //TODO Warning: Check opposite_template use in this before using OMEGA_H_INLINE bool find_barycentric_tet( const Omega_h::Matrix<DIM, 4> &Mat, const Omega_h::Vector<DIM> &pos, Omega_h::Write<Omega_h::Real> &bcc) { for(Omega_h::LO i=0; i<3; ++i) bcc[i] = -1; Omega_h::Real vals[4]; Omega_h::Few<Omega_h::Vector<DIM>, 3> abc; for(Omega_h::LO iface=0; iface<4; ++iface) // TODO last not needed { get_face_coords(Mat, iface, abc); auto vab = abc[1] - abc[0]; //b - a; auto vac = abc[2] - abc[0]; //c - a; auto vap = pos - abc[0]; // p - a; vals[iface] = osh_dot(vap, Omega_h::cross(vac, vab)); //ac, ab NOTE #if DEBUG >2 std::cout << "vol: " << vals[iface] << " for points_of_this_TET:\n" ; print_array(abc[0].data(),3); print_array(abc[1].data(),3); print_array(abc[2].data(),3); print_array(pos.data(),3, "point"); std::cout << "\n"; #endif // DEBUG } //volume using bottom face=0 get_face_coords(Mat, 0, abc); auto vtx3 = Omega_h::simplex_opposite_template(DIM, FDIM, 0); OMEGA_H_CHECK(3 == vtx3); // abc in order, for bottom face: M[0], M[2](=abc[1]), M[1](=abc[2]) Omega_h::Vector<DIM> cross_ac_ab = Omega_h::cross(abc[2]-abc[0], abc[1]-abc[0]); //NOTE Omega_h::Real vol6 = osh_dot(Mat[vtx3]-Mat[0], cross_ac_ab); Omega_h::Real inv_vol = 0.0; if(vol6 > EPSILON) // TODO tolerance inv_vol = 1.0/vol6; else { #if DEBUG >0 std::cout << vol6 << "too low \n"; #endif return 0; } bcc[0] = inv_vol * vals[0]; //for face0, cooresp. to its opp. vtx. bcc[1] = inv_vol * vals[1]; bcc[2] = inv_vol * vals[2]; bcc[3] = inv_vol * vals[3]; // 1-others return 1; //success } // BC coords are not in order of its corresp. vertexes. Bccoord of triangle (iedge, xpoint) // corresp. to vertex obtained from simplex_opposite_template(FDIM, 1, iedge) ? OMEGA_H_INLINE bool find_barycentric_tri_simple(const Omega_h::Few<Omega_h::Vector<DIM>, 3> &abc, const Omega_h::Vector<3> &xpoint, Omega_h::Write<Omega_h::Real> &bc) { Omega_h::Vector<DIM> a = abc[0]; Omega_h::Vector<DIM> b = abc[1]; Omega_h::Vector<DIM> c = abc[2]; Omega_h::Vector<DIM> cross = 1/2.0 * Omega_h::cross(b-a, c-a); //NOTE order Omega_h::Vector<DIM> norm = Omega_h::normalize(cross); Omega_h::Real area = osh_dot(norm, cross); if(std::abs(area) < 1e-6) //TODO return 0; Omega_h::Real fac = 1/(area*2.0); bc[0] = fac * osh_dot(norm, Omega_h::cross(b-a, xpoint-a)); bc[1] = fac * osh_dot(norm, Omega_h::cross(c-b, xpoint-b)); bc[2] = fac * osh_dot(norm, Omega_h::cross(xpoint-a, c-a)); return 1; } OMEGA_H_INLINE bool line_triangle_intx_simple(const Omega_h::Few<Omega_h::Vector<DIM>, 3> &abc, const Omega_h::Vector<DIM> &origin, const Omega_h::Vector<DIM> &dest, Omega_h::Vector<DIM> &xpoint, Omega_h::LO &edge, bool reverse=false ) { bool debug=0; edge = -1; xpoint = {0, 0, 0}; if(debug) { print_osh_vector(origin, "origin", false); print_osh_vector(dest, "dest"); } //Boundary exclusion. Don't set it globally and change randomnly. const Omega_h::Real bound_intol = 0;//SURFACE_EXCLUDE; //TODO optimum value ? bool found = false; const Omega_h::Vector<DIM> line = dest - origin; const Omega_h::Vector<DIM> edge0 = abc[1] - abc[0]; const Omega_h::Vector<DIM> edge1 = abc[2] - abc[0]; Omega_h::Vector<DIM> normv = Omega_h::cross(edge0, edge1); if(reverse) { normv = -1*normv; if(debug) std::cout << "Surface normal reversed \n"; } const Omega_h::Vector<DIM> snorm_unit = Omega_h::normalize(normv); const Omega_h::Real dist2plane = osh_dot(abc[0] - origin, snorm_unit); const Omega_h::Real proj_lined = osh_dot(line, snorm_unit); const Omega_h::Vector<DIM> surf2dest = dest - abc[0]; if(std::abs(proj_lined) >0) { const Omega_h::Real par_t = dist2plane/proj_lined; if(debug) std::cout << " abs(proj_lined)>0; par_t= " << par_t << " dist2plane= " << dist2plane << "; proj_lined= " << proj_lined << ";\n"; if (par_t > bound_intol && par_t <= 1.0) //TODO test tol value { xpoint = origin + par_t * line; Omega_h::Write<Omega_h::Real> bcc{3,0}; bool res = find_barycentric_tri_simple(abc, xpoint, bcc); if(debug) print_array(bcc.data(), 3, "BCC"); if(res) { if(bcc[0] < 0 || bcc[2] < 0 || bcc[0]+bcc[2] > 1.0) //TODO all zeros ? { edge = min_index(bcc.data(), 3, EPSILON); //TODO test tolerance } else { const Omega_h::Real proj = osh_dot(snorm_unit, surf2dest); if(proj >0) found = true; else if(proj<0) { if(debug) std::cout << "Particle Entering domain\n"; } else if(almost_equal(proj,0.0)) //TODO use tol { if(debug) std::cout << "Particle path on surface\n"; } } } if(debug) print_array(bcc.data(), 3, "BCCtri"); } else if(par_t >1.0) { if(debug) std::cout << "Error** Line origin and destination are on the same side of face \n"; } else if(par_t < bound_intol) // dist2plane ~0. Line contained in plane, no intersection? { if(debug) std::cout << "No/Self-intersection of ptcl origin with plane at origin. t= " << par_t << " " << dist2plane << " " << proj_lined << "\n"; } } else { std::cout << "Line and plane are parallel \n"; } return found; } //updated Feb 3 OMEGA_H_INLINE bool search_mesh(const Omega_h::Write<Omega_h::LO> pids, Omega_h::LO nelems, const Omega_h::Write<Omega_h::Real> &x0, const Omega_h::Write<Omega_h::Real> &y0, const Omega_h::Write<Omega_h::Real> &z0, const Omega_h::Write<Omega_h::Real> &x, const Omega_h::Write<Omega_h::Real> &y, const Omega_h::Write<Omega_h::Real> &z, const Omega_h::Adj &dual, const Omega_h::Adj &down_r2f, const Omega_h::Read<Omega_h::I8> &side_is_exposed, const Omega_h::LOs &mesh2verts, const Omega_h::Reals &coords, const Omega_h::LOs &face_verts, Omega_h::Write<Omega_h::LO> &part_flags, Omega_h::Write<Omega_h::LO> &elem_ids, Omega_h::Write<Omega_h::LO> &coll_adj_face_ids, Omega_h::Write<Omega_h::Real> &bccs, Omega_h::Write<Omega_h::Real> &xpoints, Omega_h::LO &loops, Omega_h::LO limit=0) { const auto down_r2fs = &down_r2f.ab2b; const auto dual_faces = &dual.ab2b; const auto dual_elems = &dual.a2ab; const int debug = 0; const int totNumPtcls = elem_ids.size(); Omega_h::Write<Omega_h::LO> elem_ids_next(totNumPtcls,-1); //particle search: adjacency + boundary crossing auto search_ptcl = OMEGA_H_LAMBDA( Omega_h::LO ielem) { // NOTE ielem is taken as sequential from 0 ... is it elementID ? TODO verify it const auto tetv2v = Omega_h::gather_verts<4>(mesh2verts, ielem); const auto M = Omega_h::gather_vectors<4, 3>(coords, tetv2v); // parallel_for loop for groups of remaining particles in this element //...... // Each group of particles inside the parallel_for. // TODO Change ntpcl, ip start and limit. Update global(?) indices inside. for(Omega_h::LO ip = 0; ip < totNumPtcls; ++ip) //HACK - each element checks all particles { //skip if the particle is not in this element or has been found if(elem_ids[ip] != ielem || part_flags[ip] <= 0) continue; if(debug) std::cerr << "Elem " << ielem << " ptcl:" << ip << "\n"; const Omega_h::Vector<3> orig{x0[ip], y0[ip], z0[ip]}; const Omega_h::Vector<3> dest{x[ip], y[ip], z[ip]}; Omega_h::Write<Omega_h::Real> bcc(4, -1.0); //TESTING. Check particle origin containment in current element find_barycentric_tet(M, orig, bcc); if(debug>3 && !(all_positive(bcc.data(), 4))) std::cerr << "ORIGIN ********NOT in elemet_id " << ielem << " \n"; find_barycentric_tet(M, dest, bcc); //check if the destination is in this element if(all_positive(bcc.data(), 4, 0)) //SURFACE_EXCLUDE)) TODO { // TODO interpolate Fields to ptcl position, and store them, for push // interpolateFields(bcc, ptcls); elem_ids_next[ip] = elem_ids[ip]; part_flags.data()[ip] = -1; if(debug) { std::cerr << "********found in " << ielem << " \n"; print_matrix(M); } continue; } //get element ID //TODO get map from omega methods. //2,3 nodes of faces. 0,2,1; 0,1,3; 1,2,3; 2,0,3 Omega_h::LOs fmap{2,1,1,3,2,3,0,3}; auto dface_ind = (*dual_elems)[ielem]; const auto beg_face = ielem *4; const auto end_face = beg_face +4; Omega_h::LO f_index = 0; bool inverse; for(auto iface = beg_face; iface < end_face; ++iface) //not 0..3 { const auto face_id = (*down_r2fs)[iface]; if(debug >1) std::cout << " \nFace: " << face_id << " dface_ind " << dface_ind << "\n"; Omega_h::Vector<3> xpoint{0,0,0}; auto fv2v = Omega_h::gather_verts<3>(face_verts, face_id); //Few<LO, 3> const auto face = Omega_h::gather_vectors<3, 3>(coords, fv2v); Omega_h::LO matInd1 = fmap[f_index*2], matInd2 = fmap[f_index*2+1]; if(debug >3) { std::cout << "Face_local_index "<< fv2v.data()[0] << " " << fv2v.data()[1] << " " << fv2v.data()[2] << "\n"; std::cout << "Mat index "<< tetv2v[matInd1] << " " << tetv2v[matInd2] << " " << matInd1 << " " << matInd2 << " \n"; std::cout << "Mat dat ind " << tetv2v.data()[0] << " " << tetv2v.data()[1] << " " << tetv2v.data()[2] << " " << tetv2v.data()[3] << "\n"; } if(fv2v.data()[1] == tetv2v[matInd1] && fv2v.data()[2] == tetv2v[matInd2]) inverse = false; else // if(fv2v.data()[1] == tetv2v[matInd2] && fv2v.data()[2] == tetv2v[matInd1]) { inverse = true; } //TODO not useful auto fcoords = Omega_h::gather_vectors<3, 3>(coords, fv2v); auto base = Omega_h::simplex_basis<3, 2>(fcoords); //edgres = Matrix<2,3> auto snormal = Omega_h::normalize(Omega_h::cross(base[0], base[1])); Omega_h::LO dummy = -1; bool detected = line_triangle_intx_simple(face, orig, dest, xpoint, dummy, inverse); if(debug && detected) std::cout << " Detected: For el=" << ielem << "\n"; if(detected && side_is_exposed[face_id]) { part_flags.data()[ip] = -1; for(Omega_h::LO i=0; i<3; ++i)xpoints[ip*3+i] = xpoint.data()[i]; //store current face_id and element_ids if(debug) print_osh_vector(xpoint, "COLLISION POINT"); elem_ids_next[ip] = -1; break; } else if(detected && !side_is_exposed[face_id]) { //OMEGA_H_CHECK(side2side_elems[side + 1] - side2side_elems[side] == 2); auto adj_elem = (*dual_faces)[dface_ind]; if(debug) std::cout << "Deletected For el=" << ielem << " ;face_id=" << (*down_r2fs)[iface] << " ;ADJ elem= " << adj_elem << "\n"; elem_ids_next[ip] = adj_elem; break; } if(!side_is_exposed[face_id])//TODO for DEBUG { if(debug) std::cout << "adj_element_across_this_face " << (*dual_faces)[dface_ind] << "\n"; const Omega_h::LO min_ind = min_index(bcc.data(), 4); if(f_index == min_ind) { if(debug) std::cout << "Min_bcc el|face_id=" << ielem << "," << (*down_r2fs)[iface] << " :unused adj_elem= " << (*dual_faces)[dface_ind] << "\n"; if(!detected) { elem_ids_next[ip] = (*dual_faces)[dface_ind]; if(debug) std::cout << "... adj_elem=" << elem_ids[ip] << "\n"; } } } if( !side_is_exposed[face_id]) ++dface_ind; ++f_index; } //iface }//ip }; bool found = false; loops = 0; while(!found) { if(debug) fprintf(stderr, "------------ %d ------------\n", loops); //TODO check if particle is on boundary and remove from list if so. // Searching all elements. TODO exclude those done ? Omega_h::parallel_for(nelems, search_ptcl, "search_ptcl"); found = true; auto cp_elm_ids = OMEGA_H_LAMBDA( Omega_h::LO i) { elem_ids[i] = elem_ids_next[i]; }; Omega_h::parallel_for(elem_ids.size(), cp_elm_ids, "copy_elem_ids"); // TODO synchronize //TODO this could be a sequential bottle-neck for(int i=0; i<totNumPtcls; ++i){ if(part_flags[i] > 0) {found = false; break;} } //Copy particle data from previous to next (adjacent) element ++loops; if(limit && loops>limit) break; } std::cerr << "search iterations " << loops << "\n"; return found; } //search_mesh } //namespace #ifdef DEBUG #undef DEBUG #endif // DEBUG #endif //define
35.446712
132
0.586681
cwsmith
b156cd0636e46b3c96590b3088c12e1ccdcedf99
2,573
cpp
C++
daemon/SimpleDriver.cpp
RufUsul/gator
6a944e7ee1f1c3ab9b2a57efd24c58503122db02
[ "BSD-3-Clause" ]
118
2015-03-24T16:09:42.000Z
2022-03-21T09:01:59.000Z
daemon/SimpleDriver.cpp
RufUsul/gator
6a944e7ee1f1c3ab9b2a57efd24c58503122db02
[ "BSD-3-Clause" ]
26
2016-03-03T23:24:08.000Z
2022-03-21T10:24:43.000Z
daemon/SimpleDriver.cpp
RufUsul/gator
6a944e7ee1f1c3ab9b2a57efd24c58503122db02
[ "BSD-3-Clause" ]
73
2015-06-09T09:44:06.000Z
2021-12-30T09:49:00.000Z
/* Copyright (C) 2013-2021 by Arm Limited. All rights reserved. */ #include "SimpleDriver.h" #include "Counter.h" SimpleDriver::~SimpleDriver() { DriverCounter * counters = mCounters; while (counters != nullptr) { DriverCounter * counter = counters; counters = counter->getNext(); delete counter; } } bool SimpleDriver::claimCounter(Counter & counter) const { return findCounter(counter) != nullptr; } bool SimpleDriver::countersEnabled() const { for (DriverCounter * counter = mCounters; counter != nullptr; counter = counter->getNext()) { if (counter->isEnabled()) { return true; } } return false; } void SimpleDriver::resetCounters() { for (DriverCounter * counter = mCounters; counter != nullptr; counter = counter->getNext()) { counter->setEnabled(false); } } void SimpleDriver::setupCounter(Counter & counter) { DriverCounter * const driverCounter = findCounter(counter); if (driverCounter == nullptr) { counter.setEnabled(false); return; } driverCounter->setEnabled(true); counter.setKey(driverCounter->getKey()); } int SimpleDriver::writeCounters(mxml_node_t * root) const { int count = 0; for (DriverCounter * counter = mCounters; counter != nullptr; counter = counter->getNext()) { mxml_node_t * node = mxmlNewElement(root, "counter"); mxmlElementSetAttr(node, "name", counter->getName()); ++count; } return count; } DriverCounter * SimpleDriver::findCounter(Counter & counter) const { DriverCounter * dcounter = nullptr; for (DriverCounter * driverCounter = mCounters; driverCounter != nullptr; driverCounter = driverCounter->getNext()) { if (strcasecmp(driverCounter->getName(), counter.getType()) == 0) { dcounter = driverCounter; counter.setType(driverCounter->getName()); break; } //to get the slot name when only part of the counter name is given //for eg: ARMv8_Cortex_A53 --> should be read as ARMv8_Cortex_A53_cnt0 std::string driverCounterName = driverCounter->getName(); std::string counterType = counter.getType(); counterType = counterType + "_cnt"; driverCounterName = driverCounterName.substr(0, counterType.length()); if (strcasecmp(driverCounterName.c_str(), counterType.c_str()) == 0) { dcounter = driverCounter; counter.setType(driverCounter->getName()); break; } } return dcounter; }
29.918605
97
0.642829
RufUsul
b15c049eecccec3753dee42ffac1733818ba59fa
1,492
hpp
C++
source/cuda_ray_tracer/CudaBindlessTexture.hpp
PetorSFZ/PhantasyEngineTestbed
3927539f17e483bd8095b60e837637e1985282e5
[ "MIT", "BSL-1.0", "Zlib", "BSD-3-Clause" ]
null
null
null
source/cuda_ray_tracer/CudaBindlessTexture.hpp
PetorSFZ/PhantasyEngineTestbed
3927539f17e483bd8095b60e837637e1985282e5
[ "MIT", "BSL-1.0", "Zlib", "BSD-3-Clause" ]
null
null
null
source/cuda_ray_tracer/CudaBindlessTexture.hpp
PetorSFZ/PhantasyEngineTestbed
3927539f17e483bd8095b60e837637e1985282e5
[ "MIT", "BSL-1.0", "Zlib", "BSD-3-Clause" ]
null
null
null
// See 'LICENSE_PHANTASY_ENGINE' for copyright and contributors. #pragma once #include <phantasy_engine/rendering/RawImage.hpp> #include "cuda_runtime.h" namespace phe { // CudaBindlessTexture // ------------------------------------------------------------------------------------------------ class CudaBindlessTexture final { public: // Constructors & destructors // -------------------------------------------------------------------------------------------- CudaBindlessTexture() noexcept = default; CudaBindlessTexture(const CudaBindlessTexture&) = delete; CudaBindlessTexture& operator= (const CudaBindlessTexture&) = delete; CudaBindlessTexture(CudaBindlessTexture&& other) noexcept; CudaBindlessTexture& operator= (CudaBindlessTexture&& other) noexcept; ~CudaBindlessTexture() noexcept; // Methods // -------------------------------------------------------------------------------------------- void load(const RawImage& image) noexcept; void destroy() noexcept; void swap(CudaBindlessTexture& other) noexcept; // Getters // -------------------------------------------------------------------------------------------- inline cudaTextureObject_t textureObject() const noexcept { return mTextureObject; } private: // Private members // -------------------------------------------------------------------------------------------- cudaArray* mCudaArray = nullptr; // CUDA memory for texture cudaTextureObject_t mTextureObject = 0; }; } // namespace phe
29.84
99
0.524129
PetorSFZ
b15d35cc1bbaee48923166e6f1b1613cf1d5dc58
11,522
hpp
C++
include/lexy/callback/container.hpp
foonathan/lexy
8c1ebec673b498bbb1728444d202586ea81c4142
[ "BSL-1.0" ]
527
2020-12-01T14:23:50.000Z
2022-03-31T11:30:24.000Z
include/lexy/callback/container.hpp
foonathan/lexy
8c1ebec673b498bbb1728444d202586ea81c4142
[ "BSL-1.0" ]
44
2020-12-01T18:39:38.000Z
2022-03-08T00:22:39.000Z
include/lexy/callback/container.hpp
foonathan/lexy
8c1ebec673b498bbb1728444d202586ea81c4142
[ "BSL-1.0" ]
24
2020-12-02T01:45:53.000Z
2022-03-22T21:31:31.000Z
// Copyright (C) 2020-2021 Jonathan Müller <jonathanmueller.dev@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #ifndef LEXY_CALLBACK_CONTAINER_HPP_INCLUDED #define LEXY_CALLBACK_CONTAINER_HPP_INCLUDED #include <lexy/callback/base.hpp> namespace lexy { struct nullopt; template <typename Container> using _detect_reserve = decltype(LEXY_DECLVAL(Container&).reserve(std::size_t())); template <typename Container> constexpr auto _has_reserve = _detail::is_detected<_detect_reserve, Container>; template <typename Container> struct _list_sink { Container _result; using return_type = Container; template <typename C = Container, typename U> auto operator()(U&& obj) -> decltype(LEXY_DECLVAL(C&).push_back(LEXY_FWD(obj))) { return _result.push_back(LEXY_FWD(obj)); } template <typename C = Container, typename... Args> auto operator()(Args&&... args) -> decltype(LEXY_DECLVAL(C&).emplace_back(LEXY_FWD(args)...)) { return _result.emplace_back(LEXY_FWD(args)...); } Container&& finish() && { return LEXY_MOV(_result); } }; template <typename Container, typename AllocFn> struct _list_alloc { AllocFn _alloc; using return_type = Container; template <typename Context> struct _with_context { const Context& _context; const AllocFn& _alloc; constexpr Container operator()(Container&& container) const { return LEXY_MOV(container); } constexpr Container operator()(nullopt&&) const { return Container(_detail::invoke(_alloc, _context)); } template <typename... Args> constexpr auto operator()(Args&&... args) const -> std::decay_t<decltype((LEXY_DECLVAL(Container&).push_back(LEXY_FWD(args)), ...), LEXY_DECLVAL(Container))> { Container result(_detail::invoke(_alloc, _context)); if constexpr (_has_reserve<Container>) result.reserve(sizeof...(args)); (result.emplace_back(LEXY_FWD(args)), ...); return result; } }; template <typename Context> constexpr auto operator[](const Context& context) const { return _with_context<Context>{context, _alloc}; } template <typename Context> constexpr auto sink(const Context& context) const { return _list_sink<Container>{Container(_detail::invoke(_alloc, context))}; } }; template <typename Container> struct _list { using return_type = Container; constexpr Container operator()(Container&& container) const { return LEXY_MOV(container); } constexpr Container operator()(nullopt&&) const { return Container(); } template <typename... Args> constexpr auto operator()(Args&&... args) const -> std::decay_t<decltype((LEXY_DECLVAL(Container&).push_back(LEXY_FWD(args)), ...), LEXY_DECLVAL(Container))> { Container result; if constexpr (_has_reserve<Container>) result.reserve(sizeof...(args)); (result.emplace_back(LEXY_FWD(args)), ...); return result; } template <typename C = Container, typename... Args> constexpr auto operator()(const typename C::allocator_type& allocator, Args&&... args) const -> decltype((LEXY_DECLVAL(C&).push_back(LEXY_FWD(args)), ...), C(allocator)) { Container result(allocator); if constexpr (_has_reserve<Container>) result.reserve(sizeof...(args)); (result.emplace_back(LEXY_FWD(args)), ...); return result; } constexpr auto sink() const { return _list_sink<Container>{Container()}; } template <typename C = Container> constexpr auto sink(const typename C::allocator_type& allocator) const { return _list_sink<Container>{Container(allocator)}; } template <typename AllocFn> constexpr auto allocator(AllocFn alloc_fn) const { return _list_alloc<Container, AllocFn>{alloc_fn}; } constexpr auto allocator() const { return allocator([](const auto& alloc) { return alloc; }); } }; /// A callback with sink that creates a list of things (e.g. a `std::vector`, `std::list`, etc.). /// It repeatedly calls `push_back()` and `emplace_back()`. template <typename Container> constexpr auto as_list = _list<Container>{}; } // namespace lexy namespace lexy { template <typename Container> struct _collection_sink { Container _result; using return_type = Container; template <typename C = Container, typename U> auto operator()(U&& obj) -> decltype(LEXY_DECLVAL(C&).insert(LEXY_FWD(obj))) { return _result.insert(LEXY_FWD(obj)); } template <typename C = Container, typename... Args> auto operator()(Args&&... args) -> decltype(LEXY_DECLVAL(C&).emplace(LEXY_FWD(args)...)) { return _result.emplace(LEXY_FWD(args)...); } Container&& finish() && { return LEXY_MOV(_result); } }; template <typename Container, typename AllocFn> struct _collection_alloc { AllocFn _alloc; using return_type = Container; template <typename Context> struct _with_context { const Context& _context; const AllocFn& _alloc; constexpr Container operator()(Container&& container) const { return LEXY_MOV(container); } constexpr Container operator()(nullopt&&) const { return Container(_detail::invoke(_alloc, _context)); } template <typename... Args> constexpr auto operator()(Args&&... args) const -> std::decay_t<decltype((LEXY_DECLVAL(Container&).insert(LEXY_FWD(args)), ...), LEXY_DECLVAL(Container))> { Container result(_detail::invoke(_alloc, _context)); if constexpr (_has_reserve<Container>) result.reserve(sizeof...(args)); (result.emplace(LEXY_FWD(args)), ...); return result; } }; template <typename Context> constexpr auto operator[](const Context& context) const { return _with_context<Context>{context, _alloc}; } template <typename Context> constexpr auto sink(const Context& context) const { return _collection_sink<Container>{Container(_detail::invoke(_alloc, context))}; } }; template <typename Container> struct _collection { using return_type = Container; constexpr Container operator()(Container&& container) const { return LEXY_MOV(container); } constexpr Container operator()(nullopt&&) const { return Container(); } template <typename... Args> constexpr auto operator()(Args&&... args) const -> std::decay_t<decltype((LEXY_DECLVAL(Container&).insert(LEXY_FWD(args)), ...), LEXY_DECLVAL(Container))> { Container result; if constexpr (_has_reserve<Container>) result.reserve(sizeof...(args)); (result.emplace(LEXY_FWD(args)), ...); return result; } template <typename C = Container, typename... Args> constexpr auto operator()(const typename C::allocator_type& allocator, Args&&... args) const -> decltype((LEXY_DECLVAL(C&).insert(LEXY_FWD(args)), ...), C(allocator)) { Container result(allocator); if constexpr (_has_reserve<Container>) result.reserve(sizeof...(args)); (result.emplace(LEXY_FWD(args)), ...); return result; } constexpr auto sink() const { return _collection_sink<Container>{Container()}; } template <typename C = Container> constexpr auto sink(const typename C::allocator_type& allocator) const { return _collection_sink<Container>{Container(allocator)}; } template <typename AllocFn> constexpr auto allocator(AllocFn alloc_fn) const { return _collection_alloc<Container, AllocFn>{alloc_fn}; } constexpr auto allocator() const { return allocator([](const auto& alloc) { return alloc; }); } }; /// A callback with sink that creates an unordered collection of things (e.g. a `std::set`, /// `std::unordered_map`, etc.). It repeatedly calls `insert()` and `emplace()`. template <typename T> constexpr auto as_collection = _collection<T>{}; } // namespace lexy namespace lexy { template <typename Container, typename Callback> class _collect_sink { public: constexpr explicit _collect_sink(Callback callback) : _callback(LEXY_MOV(callback)) {} template <typename C = Container> constexpr explicit _collect_sink(Callback callback, const typename C::allocator_type& allocator) : _result(allocator), _callback(LEXY_MOV(callback)) {} using return_type = Container; template <typename... Args> constexpr auto operator()(Args&&... args) -> decltype(void(LEXY_DECLVAL(Callback)(LEXY_FWD(args)...))) { _result.push_back(_callback(LEXY_FWD(args)...)); } constexpr auto finish() && { return LEXY_MOV(_result); } private: Container _result; LEXY_EMPTY_MEMBER Callback _callback; }; template <typename Callback> class _collect_sink<void, Callback> { public: constexpr explicit _collect_sink(Callback callback) : _count(0), _callback(LEXY_MOV(callback)) {} using return_type = std::size_t; template <typename... Args> constexpr auto operator()(Args&&... args) -> decltype(void(LEXY_DECLVAL(Callback)(LEXY_FWD(args)...))) { _callback(LEXY_FWD(args)...); ++_count; } constexpr auto finish() && { return _count; } private: std::size_t _count; LEXY_EMPTY_MEMBER Callback _callback; }; template <typename Container, typename Callback> class _collect { public: constexpr explicit _collect(Callback callback) : _callback(LEXY_MOV(callback)) {} constexpr auto sink() const { return _collect_sink<Container, Callback>(_callback); } template <typename C = Container> constexpr auto sink(const typename C::allocator_type& allocator) const { return _collect_sink<Container, Callback>(_callback, allocator); } private: LEXY_EMPTY_MEMBER Callback _callback; }; /// Returns a sink that invokes the void-returning callback multiple times, resulting in the number /// of times it was invoked. template <typename Callback> constexpr auto collect(Callback&& callback) { using callback_t = std::decay_t<Callback>; static_assert(std::is_void_v<typename callback_t::return_type>, "need to specify a container to collect into for non-void callbacks"); return _collect<void, callback_t>(LEXY_FWD(callback)); } /// Returns a sink that invokes the callback multiple times, storing each result in the container. template <typename Container, typename Callback> constexpr auto collect(Callback&& callback) { using callback_t = std::decay_t<Callback>; static_assert(!std::is_void_v<typename callback_t::return_type>, "cannot collect a void callback into a container"); return _collect<Container, callback_t>(LEXY_FWD(callback)); } } // namespace lexy #endif // LEXY_CALLBACK_CONTAINER_HPP_INCLUDED
29.16962
100
0.646242
foonathan
b15eac85caa7abd5dd2334f11f60df585288f2cb
757
cpp
C++
COJ/SRETAN.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
1
2019-09-29T03:58:35.000Z
2019-09-29T03:58:35.000Z
COJ/SRETAN.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
null
null
null
COJ/SRETAN.cpp
MartinAparicioPons/Competitive-Programming
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
[ "Apache-2.0" ]
null
null
null
#include <cmath> #include <iterator> #include <cstdio> #include <vector> #include <cstring> #include <string> #include <utility> #include <algorithm> #include <iostream> typedef long long tint; using namespace std; string DecToBin(tint number) { if(number == 0) return "4"; if(number == 1) return "7"; if(number % 2 == 0) return DecToBin(number/2) + "4"; else return DecToBin(number/2) + "7"; } int main(){ tint num, res, i=2, j=0; cin >> num; for(; (num > 0); i*=2){ num -= i; j++; } num += (i/2) - 1; string str = DecToBin (num); str = string(str.rbegin(), str.rend()); for(;(str.length() < j);){ str += "4"; } str = string(str.rbegin(), str.rend()); cout << str; }
19.410256
41
0.549538
MartinAparicioPons
b1606d4a3bedad21480294f3190261967dbe1146
23,796
cpp
C++
source/Common/Net/MessageCenterModule/MessageCenterModule.cpp
taroyuyu/KIMServer
e3017c2271a0700bb3e2a1b53a7e5748f94938f7
[ "MIT" ]
2
2020-09-13T08:05:41.000Z
2020-09-17T10:56:34.000Z
source/Common/Net/MessageCenterModule/MessageCenterModule.cpp
taroyuyu/KIMServer
e3017c2271a0700bb3e2a1b53a7e5748f94938f7
[ "MIT" ]
null
null
null
source/Common/Net/MessageCenterModule/MessageCenterModule.cpp
taroyuyu/KIMServer
e3017c2271a0700bb3e2a1b53a7e5748f94938f7
[ "MIT" ]
null
null
null
// // Created by taroyuyu on 2018/1/7. // #include "MessageCenterModule.h" #include <functional> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <unistd.h> #include <sys/ioctl.h> #include <sys/epoll.h> #include <sys/eventfd.h> #include <sys/timerfd.h> namespace kakaIM { namespace net { //数据报首部长度 const int kDatagramHeaderSize = 6; MessageCenterModule::MessageCenterModule(std::string listenIP, u_int16_t listenPort, std::shared_ptr<MessageCenterAdapter> adapter, size_t timeout) : mAdapater(adapter), m_serverSocket(listenIP, listenPort, TCPServerSocket::On, TCPServerSocket::On), mEpollInstance(-1), timmingWheelTimerfd(-1) { this->keepAlive = (timeout > 0); for (size_t i = 0; i < (timeout + 1); ++i) { this->connectionTimingWheel.emplace_back(std::set<int>()); } this->nextExpirewheelPointer = this->connectionTimingWheel.begin(); this->safeWheelPointer = this->connectionTimingWheel.end(); this->safeWheelPointer--; } MessageCenterModule::~MessageCenterModule() { } bool MessageCenterModule::init() { if (nullptr == this->mAdapater) { return false; } //创建Epoll实例 if (-1 == (this->mEpollInstance = epoll_create1(0))) { return false; } //timmingWheelTimerfd if (this->keepAlive) { this->timmingWheelTimerfd = ::timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);; if (this->timmingWheelTimerfd < 0) { return false; } struct itimerspec timerConfig; timerConfig.it_value.tv_sec = 1;//1秒之后超时 timerConfig.it_value.tv_nsec = 0; timerConfig.it_interval.tv_sec = 1;//间隔周期也是1秒 timerConfig.it_interval.tv_nsec = 0; if (-1 == timerfd_settime(this->timmingWheelTimerfd, 0, &timerConfig, nullptr)) {//相对定时器 return false; } //向Epill实例注册timmingWheelTimerfd struct epoll_event timmingWheelTimerEvent; timmingWheelTimerEvent.events = EPOLLIN; timmingWheelTimerEvent.data.fd = this->timmingWheelTimerfd; if (-1 == epoll_ctl(this->mEpollInstance, EPOLL_CTL_ADD, this->timmingWheelTimerfd, &timmingWheelTimerEvent)) { return false; } } return true; } void MessageCenterModule::execute() { this->m_serverSocket.listen(50); struct epoll_event serverSocketEvent; serverSocketEvent.events = EPOLLIN | EPOLLERR; serverSocketEvent.data.fd = this->m_serverSocket.getSocketfd(); //注册serverSocket的读事件和错误事件 if (-1 == epoll_ctl(this->mEpollInstance, EPOLL_CTL_ADD, this->m_serverSocket.getSocketfd(), &serverSocketEvent)) { perror("MessageCenterModule::execute()注册serverSOcket的读事件和错误事件失败"); } while (true == this->m_isStarted) { int const kHandleEventMaxCountPerLoop = 1024; static struct epoll_event happedEvents[kHandleEventMaxCountPerLoop]; //等待事件发送,超时时间为1秒 int happedEventsCount = epoll_wait(this->mEpollInstance, happedEvents, kHandleEventMaxCountPerLoop, 1000); if (-1 == happedEventsCount) { perror("MessageCenterModule::execute() 等待Epoll实例上的事件出错"); } for (int i = 0; i < happedEventsCount; ++i) { if (happedEvents[i].data.fd == this->m_serverSocket.getSocketfd()) { if (EPOLLIN & happedEvents[i].events) {//有新的连接 //接收连接 int connectionFD = this->acceptConnection(); if (this->keepAlive) { this->refreshConnection(connectionFD); } } if (EPOLLERR & happedEvents[i].events) {//连接出错 std::cout << "MessageCenterModule::" << __FUNCTION__ << " serverSocket fd = " << happedEvents[i].data.fd << " 连接出错" << std::endl; } } else if (happedEvents[i].data.fd != this->timmingWheelTimerfd) {//处理客户端上的数据 if (EPOLLRDHUP & happedEvents[i].events) {//连接关闭或读半关闭 //尝试读取连接上的数据,并处理 if(EPOLLIN & happedEvents[i].events){ this->readConnectionData(happedEvents[i].data.fd); } //关闭连接 this->closeConnection(happedEvents[i].data.fd); continue;//后续的写操作和储物处理不在处理 } else if (EPOLLIN & happedEvents[i].events) {//连接上有数据到达 if (this->keepAlive) { //刷新此连接 this->refreshConnection(happedEvents[i].data.fd); } //读取连接上的数据,并处理 this->readConnectionData(happedEvents[i].data.fd); } if (EPOLLOUT & happedEvents[i].events) {//连接上有数据待发送,且此时可以发送数据 //尝试发送数据 if (false == tryTowriteConnection(happedEvents[i].data.fd)) { //若连接上未有数据待发送,则让Epoll实例不再监听此连接的写事件 //让Epoll实例不再监听此连接的写事件 struct epoll_event connectionEvent; connectionEvent.events = EPOLLIN | EPOLLRDHUP | EPOLLERR; connectionEvent.data.fd = happedEvents[i].data.fd; if (-1 == epoll_ctl(this->mEpollInstance, EPOLL_CTL_MOD, happedEvents[i].data.fd, &connectionEvent)) { perror("MessageCenterModule::execute()取消监听此连接的写事件失败"); } } } if (EPOLLERR & happedEvents[i].events) {//连接出错 std::cout<<"MessageCenterModule::"<<__FUNCTION__<< " fd = " << happedEvents[i].data.fd << " 连接出错" << std::endl; //关闭连接 this->closeConnection(happedEvents[i].data.fd); } } else {//处理TimingWheel uint64_t expireCount = 0; if (sizeof(uint64_t) != ::read(this->timmingWheelTimerfd, &expireCount, sizeof(expireCount))) { std::cout << "MessageCenterModule::" << __FUNCTION__ << "read(timmingWheelTimerfd)出错" << std::endl; return; } if (this->keepAlive) { while (expireCount--) { this->refreshTimingWheel(); } } } } } } std::string MessageCenterModule::generateConnectionIdentifier(int socketfd) { timeval tv; gettimeofday(&tv, 0); return std::to_string((uint64_t) tv.tv_sec * 1000 + (uint64_t) tv.tv_usec / 1000) + std::to_string(socketfd); } int MessageCenterModule::acceptConnection() { //1.接收连接 TCPClientSocket clientSocket = this->m_serverSocket.accept(); clientSocket.setRecvBufferLowait(kDatagramHeaderSize); //2.分配缓冲区 this->socketInputBufferMap.erase(clientSocket.getSocketfd()); this->socketInputBufferMap.emplace( clientSocket.getSocketfd(), std::unique_ptr<CircleBuffer>(new CircleBuffer( kDatagramHeaderSize))); this->socketOutputBufferMap.erase(clientSocket.getSocketfd()); this->socketOutputBufferMap.emplace( clientSocket.getSocketfd(), std::unique_ptr<CircleBuffer>(new CircleBuffer( kDatagramHeaderSize))); //3.为此连接生成connectionIdentifier,并将其加入连接池 const std::string connectionIdentifier = this->generateConnectionIdentifier(clientSocket.getSocketfd()); this->mConnectionPool.erase(clientSocket.getSocketfd()); this->mConnectionPool.emplace(clientSocket.getSocketfd(), connectionIdentifier); //4.向Epoll实例中注册此连接的读事件、连接关闭事件、连接出错事件 struct epoll_event connectionEvent; connectionEvent.events = EPOLLIN | EPOLLRDHUP | EPOLLERR; connectionEvent.data.fd = clientSocket.getSocketfd(); if (-1 == epoll_ctl(this->mEpollInstance, EPOLL_CTL_ADD, clientSocket.getSocketfd(), &connectionEvent)) { perror("MessageCenterModule::acceptConnection()注册新连接的读事件和错误事件失败"); } //5.若开启KeepAlive机制,则将其加入当前时间lun if (this->keepAlive) { this->refreshConnection(clientSocket.getSocketfd()); } return clientSocket.getSocketfd(); } void MessageCenterModule::closeConnection(uint32_t connectionFD) { //1.关闭连接 ::close(connectionFD); this->connectionRetainCountTable.erase(connectionFD); //2.释放缓冲区 this->socketInputBufferMap.erase(connectionFD); this->socketOutputBufferMap.erase(connectionFD); //3.从Epoll实例中移除此连接的相关事件 epoll_ctl(this->mEpollInstance, EPOLL_CTL_DEL, connectionFD, nullptr); auto connectionIdentifierIt = this->mConnectionPool.find(connectionFD); if (connectionIdentifierIt != this->mConnectionPool.end()) { const std::string expireConnectionIdentifier = connectionIdentifierIt->second; //4.从连接池中清除对应的连接 this->mConnectionPool.erase(connectionIdentifierIt); //5.通知ConnectionDelegate for (auto connectionDelegate : this->connectionDelegateList) { connectionDelegate->didCloseConnection(expireConnectionIdentifier); } } } void MessageCenterModule::readConnectionData(uint32_t connectionFD) { //1.将数据读入输入缓冲区 static u_int8_t buffer[1024] = {0}; ssize_t readCount = read(connectionFD, buffer, 1024); if (readCount > 0) { auto it = this->socketInputBufferMap.find(connectionFD); if (it == this->socketInputBufferMap.end()) { //错误处理 std::cout << "MessageCenterModule::" << __FUNCTION__ << "异常" << __LINE__ << std::endl; //连接关闭 this->closeConnection(connectionFD); } else { it->second->append(buffer, readCount); ::google::protobuf::Message *message = nullptr; while (this->mAdapater->tryToretriveMessage(*it->second, &message)) { //分发消息 this->dispatchMessage(connectionFD, *message); delete message; }; //std::cout<<<<"输入缓冲区中已经不存在一条完整的消息"<<std::endl; } } else if (EOF == readCount) { //连接关闭 this->closeConnection(connectionFD); } else { //连接出错 this->closeConnection(connectionFD); } } bool MessageCenterModule::tryTowriteConnection(u_int32_t connectionFD) { auto outputBufferIt = this->socketOutputBufferMap.find(connectionFD); if (outputBufferIt == this->socketOutputBufferMap.end()) { //错处处理 std::cout << "fd = " << connectionFD << "有数据待发送,但是其相关的输出缓冲区找不到" << std::endl; return false; } else { //1.判断缓冲区中是否还待发送的数据 if (outputBufferIt->second->getUsed() > 0) {//缓冲区中存在待发送的数据 //1.获得socket发送缓冲区的容量 size_t output_buf_size; socklen_t output_buf_size_len = sizeof(output_buf_size); if (getsockopt(connectionFD, SOL_SOCKET, SO_SNDBUF, (void *) &output_buf_size, &output_buf_size_len) == -1) { //错误处理 } //2.获得socket发送缓存区已使用的容量 size_t outputBufUsed; if (EINVAL == ioctl(connectionFD, TIOCOUTQ, &outputBufUsed)) { //错误处理 } //3.计算socket发送缓冲区的剩余容量 size_t output_free_size = output_buf_size - outputBufUsed; //4.判断此时发送所需的内存空间 const size_t writeBytes = std::min(output_free_size,outputBufferIt->second->getUsed()); static u_int8_t *buffer = nullptr; static size_t currentBufferSize = 0; //5.更新缓冲区: 若本次write操作所能写入的最大字节数大于buffer,则删除旧的缓冲区,并分配新的缓冲区 if (writeBytes > currentBufferSize) { delete[] buffer;//一定要使用delete[] 进行删除,而不是delete,因为buffer本质上是指向一个数组 buffer = new u_int8_t[writeBytes]; currentBufferSize = writeBytes; } //6.从缓冲区中读取数据 size_t retrivedCount = outputBufferIt->second->retrive(buffer, writeBytes); //7.将数据写入socket的发送缓冲区 ssize_t writeCount = write(connectionFD, buffer, retrivedCount); if (retrivedCount != writeCount) { if(-1 == writeCount){ std::cerr << __FUNCTION__ << __LINE__ << "执行往socket输出缓冲区中输出数据时出现差错,errno="<<errno<< std::endl; }else{ size_t leftCount = retrivedCount - writeBytes; while (leftCount){ ssize_t count = write(connectionFD,buffer + writeCount,leftCount); if(-1 != count){ leftCount-=count; writeCount+=count; }else{ //错误处理 std::cerr << __FUNCTION__ << __LINE__ << "执行往socket输出缓冲区中输出数据时出现差错" << std::endl; break; } } } } return true; } else { return false; } } } void MessageCenterModule::dispatchMessage(int socketfd, ::google::protobuf::Message &message) { auto handlerIt = this->messageHandler.find(message.GetTypeName()); if (this->messageHandler.end() != handlerIt) { //1.从连接池中获得连接 auto connectionIdentifierIt = this->mConnectionPool.find(socketfd); std::string connectionIdentifier; if (connectionIdentifierIt == this->mConnectionPool.end()) {//不存在 //异常处理 std::cerr << "MessageCenterModule::" << __FUNCTION__ << " 找不到socketfd=" << socketfd << " 对应的连接标志符connectionIdentifier" << std::endl; return;; } connectionIdentifier = connectionIdentifierIt->second; if (false == this->messageFilterList.empty()) { auto it = this->messageFilterList.begin(); bool flag = true; while (it != this->messageFilterList.end()) { if ((*it)->doFilter(message, connectionIdentifier)) { //消息通过,执行下一个过滤器 it++; continue; } else { flag = false; break; } } if (flag) { handlerIt->second(message, connectionIdentifier); } } else { handlerIt->second(message, connectionIdentifier); } } } void MessageCenterModule::sendMessage(int socketfd, const ::google::protobuf::Message &message) { //1.找到socket对象的输出缓冲区 auto outputBufferIt = this->socketOutputBufferMap.find(socketfd); if (outputBufferIt == this->socketOutputBufferMap.end()) { //错误处理 std::cout << "MessageCenterModule::" << __FUNCTION__ << "异常" << __LINE__ << std::endl; } else { //2.由适配器对消息进行封装并将消息放入输出缓冲区 this->mAdapater->encapsulateMessageToByteStream(message, *outputBufferIt->second); //3.让Epoll实例监听此连接的Write事件 struct epoll_event connectionEvent; connectionEvent.events = EPOLLIN | EPOLLOUT | EPOLLRDHUP | EPOLLERR; connectionEvent.data.fd = socketfd; if (-1 == epoll_ctl(this->mEpollInstance, EPOLL_CTL_MOD, socketfd, &connectionEvent)) { perror("MessageCenterModule::sendMessage()监听此连接的写事件失败"); } } } void MessageCenterModule::setMessageHandler(const std::string &messageType, std::function<void(const ::google::protobuf::Message &, std::string)> messageHandler) { this->messageHandler[messageType] = messageHandler; } void MessageCenterModule::addMessageFilster(MessageFilter *filter) { auto filterIt = std::find(this->messageFilterList.begin(), this->messageFilterList.end(), filter); if (filterIt == this->messageFilterList.end()) { this->messageFilterList.emplace_back(filter); } } void MessageCenterModule::addConnectionDelegate(ConnectionDelegate *delegate) { auto delegateIt = std::find(connectionDelegateList.begin(), connectionDelegateList.end(), delegate); if (delegateIt == this->connectionDelegateList.end()) { this->connectionDelegateList.emplace_back(delegate); } } bool MessageCenterModule::sendMessage(std::string connectionIdentifier, const ::google::protobuf::Message &message) { auto it = std::find_if(this->mConnectionPool.begin(), this->mConnectionPool.end(), [connectionIdentifier]( const std::map<int, const std::string>::value_type item) -> bool { return item.second == connectionIdentifier; }); if (it != this->mConnectionPool.end()) { this->sendMessage(it->first, message); return true; } else { return false; } } std::pair<bool, std::pair<std::string, uint16_t>> MessageCenterModule::queryConnectionAddress(const std::string connectionIdentifier) { auto it = std::find_if(this->mConnectionPool.begin(), this->mConnectionPool.end(), [connectionIdentifier]( const std::map<int, const std::string>::value_type item) -> bool { return item.second == connectionIdentifier; }); if (it != this->mConnectionPool.end()) { TCPClientSocket clientSocket = it->first; struct sockaddr_in remoteAddr; memset(&remoteAddr, 0, sizeof(remoteAddr)); socklen_t remoteAddr_len = sizeof(remoteAddr); if (-1 == ::getpeername(it->first, (struct sockaddr *) &remoteAddr, &remoteAddr_len)) { return std::make_pair(false, std::make_pair("", 0)); } if (remoteAddr_len != sizeof(remoteAddr)) { return std::make_pair(false, std::make_pair("", 0)); } return std::make_pair(true, std::make_pair(::inet_ntoa(remoteAddr.sin_addr), ::ntohs(remoteAddr.sin_port))); } else { return std::make_pair(false, std::make_pair("", 0)); } } uint64_t MessageCenterModule::currentConnectionCount() { return this->mConnectionPool.size(); } void MessageCenterModule::refreshConnection(int connection) { std::lock_guard<std::mutex> lock(this->timmingWheelMutex); assert(this->safeWheelPointer != this->connectionTimingWheel.end()); auto recordIt = (*this->safeWheelPointer).find(connection); if(recordIt != this->safeWheelPointer->end()){ return; } this->safeWheelPointer->emplace(connection); auto connectionRetainRecordIt = this->connectionRetainCountTable.find(connection); if (this->connectionRetainCountTable.end() != connectionRetainRecordIt) { this->connectionRetainCountTable[connection] = connectionRetainRecordIt->second+1; } else { this->connectionRetainCountTable.emplace(connection, 1); } } void MessageCenterModule::refreshTimingWheel() { std::lock_guard<std::mutex> lock(this->timmingWheelMutex); //时间轮滚动 this->nextExpirewheelPointer++; this->safeWheelPointer++; if (this->connectionTimingWheel.end() == this->nextExpirewheelPointer) { this->nextExpirewheelPointer = this->connectionTimingWheel.begin(); } if (this->connectionTimingWheel.end() == this->safeWheelPointer) { this->safeWheelPointer = this->connectionTimingWheel.begin(); } //减少此时间轮上的连接的引用计数 for (auto connectionFd : *this->nextExpirewheelPointer) { //1.从连接池中获得连接 auto connectionIt = this->mConnectionPool.find(connectionFd); if (connectionIt != this->mConnectionPool.end()) { auto connectionRetainCountIt = this->connectionRetainCountTable.find(connectionFd); if (connectionRetainCountIt != this->connectionRetainCountTable.end()) { if (1 < connectionRetainCountIt->second) { //将此连接的引用计数减少 this->connectionRetainCountTable[connectionFd] = connectionRetainCountIt->second -1; } else {//关闭连接 this->closeConnection(connectionFd); } } else {//不存在关于此连接的引用计数,则直接关闭此连接 this->closeConnection(connectionFd); } } } //清空此时间轮 this->nextExpirewheelPointer->clear(); } } }
46.658824
139
0.512145
taroyuyu
b161935a85167fb519ad30c46b1d131851ea4900
437
cpp
C++
cpp/22880.cpp
jinhan814/BOJ
47d2a89a2602144eb08459cabac04d036c758577
[ "MIT" ]
9
2021-01-15T13:36:39.000Z
2022-02-23T03:44:46.000Z
cpp/22880.cpp
jinhan814/BOJ
47d2a89a2602144eb08459cabac04d036c758577
[ "MIT" ]
1
2021-07-31T17:11:26.000Z
2021-08-02T01:01:03.000Z
cpp/22880.cpp
jinhan814/BOJ
47d2a89a2602144eb08459cabac04d036c758577
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define fastio cin.tie(0)->sync_with_stdio(0) using namespace std; constexpr int MOD = 1e9 + 7; int main() { fastio; int n, ans = 1; cin >> n; vector<int> v, cnt; for (int i = 0; i < n; i++) { int t; cin >> t; if (v.empty() || v.back() < t) v.push_back(t), cnt.push_back(1); else cnt.back()++; } for (int i = 0; i + 1 < cnt.size(); i++) ans = 1LL * ans * (cnt[i] + 1) % MOD; cout << ans << '\n'; }
24.277778
79
0.540046
jinhan814
b1638fe27e79eee3625712a4b90c0cdf3747bc86
23,667
cpp
C++
Editor/src/EditorWndEditFunc.cpp
eaxeax/multitextor
1fe1b62e7e4b0acd8c24ad7d5893a7e25c6bc268
[ "BSD-2-Clause" ]
null
null
null
Editor/src/EditorWndEditFunc.cpp
eaxeax/multitextor
1fe1b62e7e4b0acd8c24ad7d5893a7e25c6bc268
[ "BSD-2-Clause" ]
null
null
null
Editor/src/EditorWndEditFunc.cpp
eaxeax/multitextor
1fe1b62e7e4b0acd8c24ad7d5893a7e25c6bc268
[ "BSD-2-Clause" ]
null
null
null
/* FreeBSD License Copyright (c) 2020-2021 vikonix: valeriy.kovalev.software@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "utils/SymbolType.h" #include "utils/Clipboard.h" #include "EditorWnd.h" #include "WndManager/WndManager.h" #include "WndManager/Dialog.h" #include "EditorApp.h" #include "Console/KeyCodes.h" #include "Dialogs/EditorDialogs.h" namespace _Editor { bool EditorWnd::EditC(input_t cmd) { if (m_readOnly) return true; //LOG(DEBUG) << " EditC " << std::hex << cmd << std::dec; TryDeleteSelectedBlock(); char16_t c = K_GET_CODE(cmd); if (c < ' ') c = '?'; size_t x = m_xOffset + m_cursorx; size_t y = m_firstLine + m_cursory; bool rc = MoveRight(K_ED(E_MOVE_RIGHT)); if (Application::getInstance().IsInsertMode()) { m_editor->SetUndoRemark("Add char"); rc = m_editor->AddCh(true, y, x, c); ChangeSelected(select_change::insert_ch, y, x, 1); } else { m_editor->SetUndoRemark("Change char"); rc = m_editor->ChangeCh(true, y, x, c); } return rc; } bool EditorWnd::EditDelC([[maybe_unused]] input_t cmd) { if (m_readOnly) return true; //LOG(DEBUG) << " EditDelC " << std::hex << cmd << std::dec; if (TryDeleteSelectedBlock()) { return true; } size_t x = m_xOffset + m_cursorx; size_t y = m_firstLine + m_cursory; bool rc{true}; if (y < m_editor->GetStrCount()) { auto str = m_editor->GetStr(y); size_t len = Editor::UStrLen(str); if (x < len) { //delete current char m_editor->SetUndoRemark("Del ch"); rc = m_editor->DelCh(true, y, x); ChangeSelected(select_change::delete_ch, y, x, 1); } else if (!y && !len) { m_editor->SetUndoRemark("Del line"); rc = m_editor->DelLine(true, y); ChangeSelected(select_change::delete_str, y); } else { m_editor->SetUndoRemark("Merge line"); rc = m_editor->MergeLine(true, y, x); if (!rc) { Beep(); EditorApp::SetErrorLine("String too long for merge"); } else ChangeSelected(select_change::merge_str, y, x); } } return rc; } bool EditorWnd::EditBS([[maybe_unused]] input_t cmd) { if (m_readOnly) return true; //LOG(DEBUG) << " EditBS " << std::hex << cmd << std::dec; size_t x = m_xOffset + m_cursorx; size_t y = m_firstLine + m_cursory; bool rc{true}; if (y > m_editor->GetStrCount()) { if (x) rc = MoveLeft(0); else rc = MoveUp(0); } else if (x) { //delete prev char auto str = m_editor->GetStr(y); size_t len = Editor::UStrLen(str); rc = MoveLeft(0); if (x <= len) { m_editor->SetUndoRemark("Del ch"); m_editor->DelCh(true, y, x - 1); ChangeSelected(select_change::delete_ch, y, x - 1, 1); } } else if (y) { //merge current line with prev rc = MoveUp(0); rc = MoveStrEnd(0); m_editor->SetUndoRemark("Merge line"); rc = m_editor->MergeLine(1, y - 1); if (!rc) { Beep(); EditorApp::SetErrorLine("String too long for merge"); } else ChangeSelected(select_change::merge_str, y - 1, m_xOffset + m_cursorx); } else if (m_editor->GetStrCount() == 1) { m_editor->SetUndoRemark("Del line"); rc = m_editor->DelLine(1, y); ChangeSelected(select_change::delete_str, y); } return rc; } bool EditorWnd::EditEnter([[maybe_unused]] input_t cmd) { if (m_readOnly) return true; //LOG(DEBUG) << " EditEnter " << std::hex << cmd << std::dec; size_t x = m_xOffset + m_cursorx; size_t y = m_firstLine + m_cursory; auto str = m_editor->GetStr(y); auto first = str.find_first_not_of(' '); if (first != std::string::npos && x > first) //if current string begins from spaces _GotoXY(first, y); bool rc = MoveDown(0); if (Application::getInstance().IsInsertMode() && y < m_editor->GetStrCount()) { m_editor->SetUndoRemark("Split line"); if (0 == x) { rc = InsertStr({}, y); ChangeSelected(select_change::insert_str, y); } else { //cut string rc = m_editor->SplitLine(1, y, x, m_xOffset + m_cursorx); ChangeSelected(select_change::split_str, y, x, m_xOffset + m_cursorx); } } return rc; } bool EditorWnd::EditTab([[maybe_unused]] input_t cmd) { if (m_readOnly) return true; //LOG(DEBUG) << " EditTab " << std::hex << cmd << std::dec; size_t x = m_xOffset + m_cursorx; size_t y = m_firstLine + m_cursory; size_t t = m_editor->GetTab(); size_t x1 = (x + t) - (x + t) % t; size_t len = x1 - x; MoveRight(static_cast<input_t>(len)); bool rc{true}; if (Application::getInstance().IsInsertMode() && y < m_editor->GetStrCount()) { char16_t ch = m_editor->GetSaveTab() ? S_TAB : ' '; std::u16string str; str.resize(len, ch); m_editor->SetUndoRemark("Add tab"); rc = m_editor->AddSubstr(true, y, x, str); ChangeSelected(select_change::insert_ch, y, x, len); } return rc; } bool EditorWnd::EditDelStr([[maybe_unused]] input_t cmd) { if (m_readOnly) return true; //LOG(DEBUG) << " EditDelStr " << std::hex << cmd << std::dec; size_t y = m_firstLine + m_cursory; m_editor->SetUndoRemark("Del line"); bool rc = m_editor->DelLine(true, y); ChangeSelected(select_change::delete_str, y); return rc; } bool EditorWnd::EditDelBegin([[maybe_unused]] input_t cmd) { if (m_readOnly) return true; //LOG(DEBUG) << " EditDelBegin " << std::hex << cmd << std::dec; size_t x = m_xOffset + m_cursorx; size_t y = m_firstLine + m_cursory; if (0 == x) return true; bool rc = MoveStrBegin(1); if (y < m_editor->GetStrCount()) { m_editor->SetUndoRemark("Del begin"); rc = m_editor->DelBegin(true, y, x); ChangeSelected(select_change::delete_ch, y, 0, x); } return rc; } bool EditorWnd::EditDelEnd([[maybe_unused]] input_t cmd) { if (m_readOnly) return true; //LOG(DEBUG) << " EditDelEnd " << std::hex << cmd << std::dec; size_t x = m_xOffset + m_cursorx; size_t y = m_firstLine + m_cursory; bool rc{true}; if (y < m_editor->GetStrCount()) { m_editor->SetUndoRemark("Del end"); rc = m_editor->DelEnd(true, y, x); ChangeSelected(select_change::delete_ch, y, x, m_editor->GetMaxStrLen() - x); } return rc; } bool EditorWnd::EditBlockCopy(input_t cmd) { if (m_readOnly) return true; if (m_selectState != select_state::complete) return true; LOG(DEBUG) << " EditBlockCopy " << std::hex << cmd << std::dec << " ss=" << static_cast<int>(m_selectState) << " t=" << static_cast<int>(m_selectType) << " bx=" << m_beginX << " by=" << m_beginY << " ex=" << m_endX << " ey=" << m_endY; select_t mode; std::vector<std::u16string> strArray; bool rc = CopySelected(strArray, mode); rc = PasteSelected(strArray, mode); return rc; } bool EditorWnd::EditBlockMove(input_t cmd) { if (m_readOnly) return true; if (m_selectState != select_state::complete) return true; LOG(DEBUG) << " EditBlockMove " << std::hex << cmd << std::dec << " ss=" << static_cast<int>(m_selectState) << " t=" << static_cast<int>(m_selectType) << " bx=" << m_beginX << " by=" << m_beginY << " ex=" << m_endX << " ey=" << m_endY; select_t mode; std::vector<std::u16string> strArray; bool rc = CopySelected(strArray, mode); rc = DelSelected(); rc = PasteSelected(strArray, mode); return rc; } bool EditorWnd::EditBlockDel(input_t cmd) { if (m_readOnly) return true; if (m_selectState != select_state::complete) return true; LOG(DEBUG) << " EditBlockDel " << std::hex << cmd << std::dec << " ss=" << static_cast<int>(m_selectState) << " t=" << static_cast<int>(m_selectType) << " bx=" << m_beginX << " by=" << m_beginY << " ex=" << m_endX << " ey=" << m_endY; CorrectSelection(); _GotoXY(m_beginX, m_beginY); bool rc = DelSelected(); return rc; } bool EditorWnd::EditUndo([[maybe_unused]] input_t cmd) { if (m_readOnly) return true; //LOG(DEBUG) << " EditUndo " << std::hex << cmd << std::dec; auto editCmd = m_editor->PeekUndo(); if (!editCmd) { EditorApp::SetErrorLine("Undo command absents"); m_editor->SetCurStr(STR_NOTDEFINED); if (!m_saved) m_editor->ClearModifyFlag(); return true; } if (editCmd->line != m_firstLine + m_cursory) { _GotoXY(editCmd->pos, editCmd->line); return true; } bool rc{true}; editCmd = m_editor->GetUndo(); if (editCmd) { if (m_selectState == select_state::complete) { //del mark ChangeSelected(select_change::clear); InvalidateRect(); } _GotoXY(editCmd->pos, editCmd->line); if (editCmd->command == cmd_t::CMD_SET_POS) ;//nothing to do else if (editCmd->command == cmd_t::CMD_END) { EditorApp::SetHelpLine("Wait while undo '" + editCmd->remark + "' command"); int n = 1; while ((editCmd = m_editor->GetUndo()) != std::nullopt) { if (editCmd->command == cmd_t::CMD_END) ++n; if (editCmd->command == cmd_t::CMD_BEGIN) --n; if (!n) break; rc = m_editor->Command(*editCmd); } EditorApp::SetHelpLine("Undo: '" + editCmd->remark + "'", stat_color::grayed); } else { EditorApp::SetHelpLine("Undo: '" + editCmd->remark + "'", stat_color::grayed); rc = m_editor->Command(*editCmd); } } return rc; } bool EditorWnd::EditRedo([[maybe_unused]] input_t cmd) { if (m_readOnly) return true; //LOG(DEBUG) << " EditRedo " << std::hex << cmd << std::dec; auto redoCmd = m_editor->PeekRedo(); if (!redoCmd) { EditorApp::SetErrorLine("Redo command absents"); return true; } if (redoCmd->line != m_firstLine + m_cursory) { _GotoXY(redoCmd->pos, redoCmd->line); return true; } bool rc{true}; redoCmd = m_editor->GetRedo(); if (redoCmd) { if (m_selectState == select_state::complete) { //del mark ChangeSelected(select_change::clear); InvalidateRect(); } _GotoXY(redoCmd->pos, redoCmd->line); if (redoCmd->command == cmd_t::CMD_SET_POS) ;//nothing to do else if (redoCmd->command == cmd_t::CMD_BEGIN) { EditorApp::SetHelpLine("Wait while redo '" + redoCmd->remark + "' command"); int n = 1; while ((redoCmd = m_editor->GetRedo()) != std::nullopt) { if (redoCmd->command == cmd_t::CMD_BEGIN) ++n; if (redoCmd->command == cmd_t::CMD_END) --n; if (!n) break; rc = m_editor->Command(*redoCmd); } EditorApp::SetHelpLine("Redo: '" + redoCmd->remark + "'", stat_color::grayed); } else { EditorApp::SetHelpLine("Redo: '" + redoCmd->remark + "'", stat_color::grayed); rc = m_editor->Command(*redoCmd); } } return rc; } bool EditorWnd::EditBlockIndent(input_t cmd) { if (m_readOnly) return true; if (m_selectState != select_state::complete) return true; LOG(DEBUG) << " EditBlockIndent " << std::hex << cmd << std::dec; input_t count{ K_GET_CODE(cmd) }; if (!count) count = 1; CorrectSelection(); EditCmd edit { cmd_t::CMD_BEGIN, m_beginY, m_beginX }; EditCmd undo { cmd_t::CMD_BEGIN, m_beginY, m_beginX }; m_editor->SetUndoRemark("Indent"); m_editor->AddUndoCommand(edit, undo); size_t n { m_endY - m_beginY }; bool save {true}; bool rc {}; size_t bx, ex; size_t i; for (i = 0; i <= n; ++i) { if (m_selectType == select_t::stream) { if (n == 0) { bx = m_beginX; ex = m_endX; } else if (i == 0) { bx = m_beginX; ex = m_editor->GetMaxStrLen(); } else if (i == n) { bx = 0; ex = m_endX; } else { bx = 0; ex = m_editor->GetMaxStrLen(); } } else if (m_selectType == select_t::line) { bx = 0; ex = m_editor->GetMaxStrLen(); } else { bx = m_beginX; ex = m_endX; } size_t y = m_beginY + i; size_t size = ex - bx + 1; if (size > m_editor->GetMaxStrLen()) size = m_editor->GetMaxStrLen(); if (size > count) rc = m_editor->Indent(save, y, bx, size, count); } edit.command = cmd_t::CMD_END; undo.command = cmd_t::CMD_END; m_editor->AddUndoCommand(edit, undo); return rc; } bool EditorWnd::EditBlockUndent(input_t cmd) { if (m_readOnly) return true; if (m_selectState != select_state::complete) return true; LOG(DEBUG) << " EditBlockUndent " << std::hex << cmd << std::dec; input_t count{ K_GET_CODE(cmd) }; if (!count) count = 1; CorrectSelection(); EditCmd edit { cmd_t::CMD_BEGIN, m_beginY, m_beginX }; EditCmd undo { cmd_t::CMD_BEGIN, m_beginY, m_beginX }; m_editor->SetUndoRemark("Undent"); m_editor->AddUndoCommand(edit, undo); size_t n { m_endY - m_beginY }; bool save { true }; bool rc { true }; size_t bx, ex; size_t i; for (i = 0; i <= n; ++i) { if (m_selectType == select_t::stream) { if (n == 0) { bx = m_beginX; ex = m_endX; } else if (i == 0) { bx = m_beginX; ex = m_editor->GetMaxStrLen(); } else if (i == n) { bx = 0; ex = m_endX; } else { bx = 0; ex = m_editor->GetMaxStrLen(); } } else if (m_selectType == select_t::line) { bx = 0; ex = m_editor->GetMaxStrLen(); } else { bx = m_beginX; ex = m_endX; } size_t y = m_beginY + i; size_t size = ex - bx + 1; if (size > m_editor->GetMaxStrLen()) size = m_editor->GetMaxStrLen(); if (size > count) rc = m_editor->Undent(save, y, bx, size, count); } edit.command = cmd_t::CMD_END; undo.command = cmd_t::CMD_END; m_editor->AddUndoCommand(edit, undo); return rc; } bool EditorWnd::EditCopyToClipboard(input_t cmd) { if (m_selectState != select_state::complete) return true; LOG(DEBUG) << " EditCopyToClipboard " << std::hex << cmd << std::dec; select_t mode; std::vector<std::u16string> strArray; bool rc = CopySelected(strArray, mode) && CopyToClipboard(strArray, mode != select_t::stream ? true : false); return rc; } bool EditorWnd::EditCutToClipboard(input_t cmd) { if (m_selectState != select_state::complete) return true; LOG(DEBUG) << " EditCutToClipboard " << std::hex << cmd << std::dec; select_t mode; std::vector<std::u16string> strArray; bool rc = CopySelected(strArray, mode) && DelSelected() && CopyToClipboard(strArray, mode != select_t::stream ? true : false); return rc; } bool EditorWnd::EditPasteFromClipboard(input_t cmd) { if (m_readOnly) return true; if (!IsClipboardReady()) return true; LOG(DEBUG) << " EditPasteFromClipboard " << std::hex << cmd << std::dec; TryDeleteSelectedBlock(); std::vector<std::u16string> strArray; bool rc = PasteFromClipboard(strArray) && PasteSelected(strArray, select_t::stream); //del mark ChangeSelected(select_change::clear); return rc; } bool EditorWnd::Reload([[maybe_unused]]input_t cmd) { //LOG(DEBUG) << " Reload"; m_selectState = select_state::no; m_selectType = select_t::stream; m_beginX = m_endX = 0; m_beginY = m_endY = 0; bool rc = m_editor->Load(); rc = Refresh(); return rc; } bool EditorWnd::Close([[maybe_unused]]input_t cmd) { m_close = true; return true; } bool EditorWnd::CtrlRefresh([[maybe_unused]] input_t cmd) { m_editor->FlushCurStr(); return Refresh(); } bool EditorWnd::Replace([[maybe_unused]] input_t cmd) { if (m_readOnly) return true; //LOG(DEBUG) << " Replace " << std::hex << cmd << std::dec; EditCmd edit{ cmd_t::CMD_BEGIN }; EditCmd undo{ cmd_t::CMD_BEGIN }; m_editor->SetUndoRemark("Replace"); bool undoCmd{}; auto prevMenu = Application::getInstance().SetAccessMenu(g_replaceMenu); WndManager::getInstance().Refresh(); size_t begin = m_firstLine + m_cursory; size_t strCount = m_editor->GetStrCount(); bool userBreak{}; bool reverce{}; bool prompt{true}; auto ProcInput = [this, &userBreak, &prompt, &reverce](bool found) -> bool { while(1) { if (found && !userBreak) EditorApp::SetErrorLine("Enter-Replace, Esc-Cancel"); else { EditorApp::SetErrorLine("Esc-Cancel"); Beep(); } input_t code; while ((code = CheckInput()) == 0); EditorApp::SetHelpLine(); if (found && code == K_ENTER) return true; else if (found && (code == 'a' || code == 'A')) { prompt = false; return true; } else if (code == K_ESC || code == 'q' || code == 'Q') { userBreak = true; break; } else if (code == 'n' || code == 'N' || code == K_DOWN || code == K_RIGHT) { reverce = false; break; } else if (code == 'p' || code == 'P' || code == K_UP || code == K_LEFT) { reverce = true; break; } } return false; }; size_t count{}; size_t progress{}; size_t fx{}, fy{}, fs{}; while (1) { bool found{}; HideFound(); if (!reverce) found = FindDown(!prompt); else { reverce = false; found = FindUp(!prompt); } if (found) { fx = m_foundX; fy = m_foundY; fs = m_foundSize; } else if (fs != 0) { //restore last found pos m_foundX = fx; m_foundY = fy; m_foundSize = fs; Invalidate(fy, invalidate_t::find, fx, fs); } if (!found && !prompt) break; if (prompt) { Repaint(); auto replace = ProcInput(found); if (!replace) { if (userBreak) break; else continue; } } if (!found) break; if (!prompt && !undoCmd) { undoCmd = true; edit.line = m_foundY; edit.pos = m_foundX; undo.line = m_foundY; undo.pos = m_foundX; m_editor->AddUndoCommand(edit, undo); EditorApp::SetHelpLine("Replace. Press any key for cancel."); } if (!prompt) { if (++progress == 1000) { progress = 0; userBreak = UpdateProgress((m_foundY - begin) * 99 / (strCount - begin)); if (userBreak) break; } } ++count; [[maybe_unused]]bool rc = ReplaceSubstr(m_foundY, m_foundX, FindDialog::s_vars.findStrW.size(), FindDialog::s_vars.replaceStrW); m_foundSize = FindDialog::s_vars.replaceStrW.size(); _GotoXY(m_foundX + m_foundSize, m_foundY); } if (undoCmd) { edit.command = cmd_t::CMD_END; undo.command = cmd_t::CMD_END; m_editor->AddUndoCommand(edit, undo); if (!count) EditorApp::SetErrorLine("String not found"); } Application::getInstance().SetAccessMenu(prevMenu); if (userBreak) EditorApp::SetHelpLine("User Abort", stat_color::grayed); else EditorApp::SetHelpLine("Ready"); WndManager::getInstance().Refresh(); return true; } bool EditorWnd::Save(input_t cmd) { input_t force{ K_GET_CODE(cmd) }; if (force == 0 && !m_editor->IsChanged()) return true; LOG(DEBUG) << " Save " << std::hex << cmd << std::dec; if (m_untitled) return SaveAs(0); try { [[maybe_unused]]bool rc = m_editor->Save(); } catch (const std::exception& ex) { LOG(ERROR) << __FUNC__ << "save as: exception " << ex.what(); MsgBox(MBoxKey::OK, "Save", { "File write error", "Check file access and try again" } ); return false; } UpdateAccessInfo(); m_saved = true; return true; } } //namespace _Editor
25.3394
157
0.532091
eaxeax
b166eea5c0726f94caddf579c3df35c2ee37bf92
6,107
cpp
C++
src/quadrature.cpp
JustAdamHere/MAGIC098-Exam
1e3cf42b1a64fb0de64172ae0c13f1888362904a
[ "MIT" ]
null
null
null
src/quadrature.cpp
JustAdamHere/MAGIC098-Exam
1e3cf42b1a64fb0de64172ae0c13f1888362904a
[ "MIT" ]
null
null
null
src/quadrature.cpp
JustAdamHere/MAGIC098-Exam
1e3cf42b1a64fb0de64172ae0c13f1888362904a
[ "MIT" ]
null
null
null
/****************************************************************************** * @details This is a file containing functions regarding quadratures. * * @author Adam Matthew Blakey * @date 2019/12/07 ******************************************************************************/ #include "common.hpp" #include "quadrature.hpp" #include <cassert> #include <cmath> #include <functional> #include <map> #include <iostream> namespace quadrature { // Cached storage. namespace { std::map<std::pair<int, int>, double> integrationPoints; std::map<std::pair<int, int>, double> weights; } /****************************************************************************** * legendrePolynomial * * @details Returns the ith derivative of the nth Legendre polynomial. * * @param[in] n Gives the degree of the polynomial. * @param[in] i The ith derivative. * @param[in] x The point at which to evaluate the polynomial. * @return The Legendre polynomial. ******************************************************************************/ f_double legendrePolynomial(const int &a_n, const int &a_i) { if (a_i==0) { switch(a_n) { case 0: return[](double x)->double { return 1; }; break; case 1: return[](double x)->double { return x; }; break; default: return[a_n](double x)->double { using namespace common; return addFunction( constantMultiplyFunction( double(2*a_n-1)/a_n * x, legendrePolynomial(a_n-1, 0) ), constantMultiplyFunction( -1, constantMultiplyFunction( double(a_n-1)/a_n, legendrePolynomial(a_n-2, 0) ) ) )(x); }; } } else { switch(a_n) { case 0: return[](double x)->double { return 0; }; break; case 1: return[a_i](double x)->double { return (a_i==1)?1:0; }; break; default: return[a_n, a_i](double x)->double { using namespace common; return addFunction( addFunction( constantMultiplyFunction( double(2*a_n-1)/(a_n-1) * x, legendrePolynomial(a_n-1, a_i) ), constantMultiplyFunction( -1, constantMultiplyFunction( double(a_n)/(a_n-1), legendrePolynomial(a_n-2, a_i) ) ) ), constantMultiplyFunction( (a_i-1) * double(2*a_n-1)/(a_n-1), legendrePolynomial(a_n-1, a_i-1) ) )(x); }; } } } /****************************************************************************** * legendrePolynomialRoots * * @details Calculates the ith root of the nth degree Legendre polynomial. * * @param[in] n Gives the degree of the polynomial. * @param[in] i Which root to return. * @return The root of the Legendre polynomial. ******************************************************************************/ double legendrePolynomialRoot(const int n, const int i) { double root = -cos(double(2*i + 1)/(2*n)*M_PI); while (fabs(legendrePolynomial(n, 0)(root)) >= 1e-5) root = root - legendrePolynomial(n, 0)(root)/legendrePolynomial(n, 1)(root); return root; } /****************************************************************************** * legendrePolynomialRoots * * @details Calculates the roots of the real roots of the nth Legendre * polynomial at the point x. * * @param[in] n Gives the degree of the polynomial. * @param[out] roots The n roots of the polynomial. ******************************************************************************/ void legendrePolynomialRoots(const int n, double roots[]) { for (int i=0; i<n; ++i) { roots[i] = legendrePolynomialRoot(n, i); } } /****************************************************************************** * gaussLegendreQuadrature * * @details Calculates the Gauss-Legendre quadrature of f between -1 and 1. * * @param[in] f A function, f, to integrate with. * @param[in] n What degree of Legendre polynomial to approximate * with. * @return The quadrature. ******************************************************************************/ double gaussLegendreQuadrature(const f_double f, const int n) { double weight, x; double h = double(2)/n; double quadrature = 0; for (int i=0; i<n; ++i) { x = legendrePolynomialRoot(n, i); weight = double(2) / ((1 - pow(x, 2))*pow(legendrePolynomial(n, 1)(x), 2)); quadrature += weight * f(x); } return quadrature; } /****************************************************************************** * trapeziumRule * * @details Uses composite trapezium rule with n-1 equal strips to give a * quadrature. * * @param[in] n How many values we're approximating the integral * with. * @param[in] fValues The function values at the sides of each strip. * @param[in] h The trip width. * @return The quadrature. ******************************************************************************/ double trapeziumRule(const int n, const double fValues[], const double h) { double answer = 0; answer += fValues[0]/2; for (int i=1; i<n-1; ++i) { answer += fValues[i]; } answer += fValues[n-1]/2; return h/(n-1) * answer; } double get_gaussLegendrePoint(const int &a_n, const int &a_i) { if (integrationPoints.find(std::make_pair(a_n, a_i)) == integrationPoints.end()) { integrationPoints[std::make_pair(a_n, a_i)] = legendrePolynomialRoot(a_n, a_i); } return integrationPoints[std::make_pair(a_n, a_i)]; } double get_gaussLegendreWeight(const int &a_n, const int &a_i) { if (weights.find(std::make_pair(a_n, a_i)) == weights.end()) { double xi = get_gaussLegendrePoint(a_n, a_i); weights[std::make_pair(a_n, a_i)] = double(2) / ((1 - pow(xi, 2))*pow(legendrePolynomial(a_n, 1)(xi), 2)); } return weights[std::make_pair(a_n, a_i)]; } }
27.633484
109
0.505486
JustAdamHere
b167384da66d1aad962db4df67d0000963764446
4,561
cc
C++
src/avi/avifile.cc
Joe136/octave-forge-video
eb31e64ae5933b09c3c05033404c89b9fe88c8b9
[ "BSD-2-Clause" ]
null
null
null
src/avi/avifile.cc
Joe136/octave-forge-video
eb31e64ae5933b09c3c05033404c89b9fe88c8b9
[ "BSD-2-Clause" ]
null
null
null
src/avi/avifile.cc
Joe136/octave-forge-video
eb31e64ae5933b09c3c05033404c89b9fe88c8b9
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (C) 2005 Stefan van der Walt <stefan@sun.ac.za> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <octave/oct.h> #include "oct-avifile.h" template <typename Num> void setp(Num &p, Num v) { if (!error_state) { p = v; } else { error_state = 0; } } DEFUN_DLD(avifile, args, nargout, "-*- texinfo -*-\n\ @deftypefn {Loadable Function} {@var{f} =} avifile (@var{filename}, [@var{parameter}, @var{value}, @dots{}])\n\ @deftypefnx {Loadable Function} avifile (\"codecs\")\n\ Create an AVI-format video file.\n\ \n\ The supported parameters are\n\ \n\ @table @asis\n\ @item @code{\"compression\"} or @code{\"codec\"}\n\ The type of encoder used (default: @code{\"msmpeg4v2\"})\n\ \n\ @item @code{\"fps\"}\n\ Encoding frame rate per second (default: @code{25.0})\n\ \n\ @item @code{\"gop\"}\n\ Group-of-pictures -- the number of frames after which a keyframe\n\ is inserted (default: @code{10})\n\ \n\ @item @code{\"bitrate\"}\n\ Encoding bitrate (default: @code{400000})\n\ @end table\n\ \n\ To see a list of the available codecs, do @code{avifile(\"codecs\")}.\n\ @end deftypefn\n\ \n\ @seealso{addframe, aviinfo, aviread}") { octave_value_list retval; if ( (args.length() == 1) && (args(0).string_value() == "codecs") ) { AVHandler::print_codecs(); return retval; } if ((args.length() == 0) || (args.length() % 2 != 1)) { print_usage(); return retval; } std::string filename = args(0).string_value(); if (error_state) { print_usage(); return retval; } // Parse parameters std::string codec = "mpeg4"; unsigned int bitrate = 400000; int gop_size = 10; double fps = 25; std::string title = ""; std::string author = ""; std::string comment = "Created using Octave-Avifile"; for (int i = 1; i < args.length(); i++) { std::string p = args(i).string_value(); octave_value v = args(i+1); if (!error_state) { if ((p == "codec") || (p == "compression")) { setp(codec, v.string_value()); } else if (p == "bitrate") { setp(bitrate, (unsigned int)v.int_value()); } else if (p == "gop") { setp(gop_size, v.int_value()); } else if (p == "fps") { setp(fps, v.double_value()); } else if (p == "title") { setp(title, v.string_value()); } else if (p == "author") { setp(author, v.string_value()); } else if (p == "comment") { setp(comment, v.string_value()); } else { error("avifile: unknown parameter \"%s\"", p.c_str()); return retval; } } i++; } Avifile *m = new Avifile(filename); if (error_state) { return retval; } m->av->set_codec(codec); m->av->set_bitrate(bitrate); m->av->set_gop_size(gop_size); m->av->set_framerate(fps); // Doesn't look like these values are ever encoded m->av->set_title(title); m->av->set_author(author); m->av->set_comment(comment); retval.append(octave_value(m)); return retval; } /* %!test %! fn="test_avifile1.avi"; %! m = avifile(fn, "codec", "mpeg4"); %! for i = 1:100 %! I = zeros(100,100); %! I(i,:) = i; %! I(:,i) = 200-i; %! addframe(m, I/255); %! endfor %! clear m %! assert(exist(fn,"file")) %! delete(fn) */
31.895105
111
0.619162
Joe136
b16d67df111542d39ee36d19d836a969750c38e0
2,379
cc
C++
Mu2eUtilities/src/SimpleSpectrum.cc
lborrel/Offline
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
[ "Apache-2.0" ]
1
2021-06-23T22:09:28.000Z
2021-06-23T22:09:28.000Z
Mu2eUtilities/src/SimpleSpectrum.cc
lborrel/Offline
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
[ "Apache-2.0" ]
125
2020-04-03T13:44:30.000Z
2021-10-15T21:29:57.000Z
Mu2eUtilities/src/SimpleSpectrum.cc
lborrel/Offline
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
[ "Apache-2.0" ]
null
null
null
// Simple approximations available for DIO spectrum. // // #include <cstddef> #include <vector> // Framework includes #include "cetlib/pow.h" #include "cetlib_except/exception.h" // Mu2e includes #include "Mu2eUtilities/inc/SimpleSpectrum.hh" using namespace std; using cet::pow; using cet::square; namespace mu2e { SimpleSpectrum::SimpleSpectrum( Spectrum::enum_type approx, const PhysicsParams& physicsParams ) : _approx ( approx ) , _phy ( physicsParams ) { if ( _approx > Spectrum::FlatTrunc && _phy.getCzarneckiCoefficients().empty() ) throw cet::exception("EmptyCoefficients") << " No Czarnecki coefficients available! Cannot use this approximation.\n" ; } SimpleSpectrum::~SimpleSpectrum() { } double SimpleSpectrum::getWeight(double E) const { double weight(0.); if ( _approx == Spectrum::Flat ) weight = getFlat (E, _phy); else if ( _approx == Spectrum::FlatTrunc ) weight = getFlatTrunc(E, _phy); else if ( _approx == Spectrum::Pol5 ) weight = getPol5 (E, _phy); else if ( _approx == Spectrum::Pol58 ) weight = getPol58 (E, _phy); return weight; } //======================================== // Simple approximations below //======================================== double SimpleSpectrum::getFlat(const double e, const PhysicsParams& phy ) { return 1.; } double SimpleSpectrum::getFlatTrunc(const double e, const PhysicsParams& phy ) { return ( e > phy.getEndpointEnergy() ) ? 0. : 1.; } double SimpleSpectrum::getPol5(const double e, const PhysicsParams& phy ) { const double delta = phy.getMuonEnergy() - e - cet::pow<2>( e )/(2*phy.getAtomicMass()); return (e > phy.getEndpointEnergy() ) ? 0. : phy.getCzarneckiCoefficient()*cet::pow<5>( delta ); } double SimpleSpectrum::getPol58(const double e, const PhysicsParams& phy ) { const double delta = phy.getMuonEnergy() - e - cet::pow<2>( e )/(2*phy.getAtomicMass()); if ( e > phy.getEndpointEnergy() ) return 0.; const auto & coeffs = phy.getCzarneckiCoefficients(); double prob(0.); double power = cet::pow<5>( delta ); for ( size_t i=0; i < coeffs.size() ; i++ ) { if( i > 0 ) power *= delta; prob += coeffs.at(i)*power; } return prob; } }
27.344828
100
0.604456
lborrel
b16dc711e3bdd1ec17ef5ae66bf4188e39e78af0
1,953
cpp
C++
tests/src/main.cpp
L-Acoustics/networkInterfaceHelper
5274c50ea2fb551ce187891a2759067d930ce589
[ "BSD-3-Clause" ]
null
null
null
tests/src/main.cpp
L-Acoustics/networkInterfaceHelper
5274c50ea2fb551ce187891a2759067d930ce589
[ "BSD-3-Clause" ]
null
null
null
tests/src/main.cpp
L-Acoustics/networkInterfaceHelper
5274c50ea2fb551ce187891a2759067d930ce589
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2016-2022, L-Acoustics * This file is part of LA_networkInterfaceHelper. * 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 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. * You should have received a copy of the BSD 3-clause License * along with LA_networkInterfaceHelper. If not, see <https://opensource.org/licenses/BSD-3-Clause>. */ /** * @file main.cpp * @author Christophe Calmejane */ #include <gtest/gtest.h> int main(int argc, char* argv[]) { try { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } catch (...) { return 1; } }
36.849057
100
0.758833
L-Acoustics
b174c219ac977fd5a825400b8c5c09415fa1bfb6
4,897
cpp
C++
Tutorial02/BasicTutorial1.cpp
DebugBSD/PruebasOgre3D
cc6644ef802cac0cca999638ca8979b3b794601d
[ "MIT" ]
null
null
null
Tutorial02/BasicTutorial1.cpp
DebugBSD/PruebasOgre3D
cc6644ef802cac0cca999638ca8979b3b794601d
[ "MIT" ]
null
null
null
Tutorial02/BasicTutorial1.cpp
DebugBSD/PruebasOgre3D
cc6644ef802cac0cca999638ca8979b3b794601d
[ "MIT" ]
null
null
null
// This file is part of the OGRE project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at https://www.ogre3d.org/licensing. // SPDX-License-Identifier: MIT #include "Ogre.h" #include "OgreApplicationContext.h" #include "OgreInput.h" #include "OgreRTShaderSystem.h" #include <iostream> using namespace Ogre; using namespace OgreBites; class BasicTutorial1 : public ApplicationContext , public InputListener { public: BasicTutorial1(); virtual ~BasicTutorial1() {} void setup(); bool keyPressed(const KeyboardEvent& evt); }; BasicTutorial1::BasicTutorial1() : ApplicationContext("OgreTutorialApp") { } // Aqui configuramos la escena void BasicTutorial1::setup() { // do not forget to call the base first ApplicationContext::setup(); addInputListener(this); // get a pointer to the already created root Root* root = getRoot(); SceneManager* scnMgr = root->createSceneManager(); // register our scene with the RTSS RTShader::ShaderGenerator* shadergen = RTShader::ShaderGenerator::getSingletonPtr(); shadergen->addSceneManager(scnMgr); // -- tutorial section start -- //! [turnlights] scnMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); //! [turnlights] //! Creamos una nueva entidad de tipo Light Light* light = scnMgr->createLight("MainLight"); //! Creamos un nuevo SceneNode para asociarle la Light SceneNode* lightNode = scnMgr->getRootSceneNode()->createChildSceneNode(); //! Asociamos la Light al Scene Node lightNode->attachObject(light); //! Establecemos su posicion en la escena. lightNode->setPosition(20, 80, 50); //! Creamos un nuevo SceneNode para asociarle la camara SceneNode* camNode = scnMgr->getRootSceneNode()->createChildSceneNode(); //! Creamos la camara Camera* cam = scnMgr->createCamera("myCam"); cam->setNearClipDistance(5); // specific to this sample cam->setAutoAspectRatio(true); camNode->attachObject(cam); // Asociamos la camara camNode->setPosition(0, 0, 140); // Establecemos su posicion //! and tell it to render into the main window getRenderWindow()->addViewport(cam); // Creamos una entidad (o objeto) Entity* ogreEntity = scnMgr->createEntity("ogrehead.mesh"); // Creamos un SceneNode hijo para asociarle la entidad creada anteriormente SceneNode* ogreNode = scnMgr->getRootSceneNode()->createChildSceneNode(); // En Ogre3D hay que asociar los objetos (o entidades) a SceneNode's ogreNode->attachObject(ogreEntity); // NOTA: Por defecto los SceneNodes se situan en la posicion 0,0,0 en la escena. // Movemos la camara para poder ver todos los objetos camNode->setPosition(0, 47, 222); // Creamos una segunda entidad (o objeto) Entity* ogreEntity2 = scnMgr->createEntity("ogrehead.mesh"); // Creamos un SceneNode hijo para asociarle la entidad creada anteriormente y le pasamos la posicion dentro de la escena SceneNode* ogreNode2 = scnMgr->getRootSceneNode()->createChildSceneNode(Vector3(84, 48, 0)); // En Ogre3D hay que asociar los objetos (o entidades) a SceneNode's ogreNode2->attachObject(ogreEntity2); // Creamos una tercera entidad (o objeto) Entity* ogreEntity3 = scnMgr->createEntity("ogrehead.mesh"); // Creamos un SceneNode hijo para asociarle la entidad creada anteriormente SceneNode* ogreNode3 = scnMgr->getRootSceneNode()->createChildSceneNode(); // Establecemos la posicion dentro de la escena ogreNode3->setPosition(0, 104, 0); // Establecemos su escala ogreNode3->setScale(2, 1.2, 1); // En Ogre3D hay que asociar los objetos (o entidades) a SceneNode's ogreNode3->attachObject(ogreEntity3); // Creamos una cuarta entidad (o objeto) Entity* ogreEntity4 = scnMgr->createEntity("ogrehead.mesh"); // Creamos un SceneNode hijo para asociarle la entidad creada anteriormente SceneNode* ogreNode4 = scnMgr->getRootSceneNode()->createChildSceneNode(); // Establecemos la posicion dentro de la escena ogreNode4->setPosition(-84, 48, 0); // Establecemos su rotacion en el eje Z (Roll) ogreNode4->roll(Degree(-90)); // En Ogre3D hay que asociar los objetos (o entidades) a SceneNode's ogreNode4->attachObject(ogreEntity4); } bool BasicTutorial1::keyPressed(const KeyboardEvent& evt) { if (evt.keysym.sym == SDLK_ESCAPE) { getRoot()->queueEndRendering(); } return true; } int main(int argc, char **argv) { try { BasicTutorial1 app; app.initApp(); app.getRoot()->startRendering(); app.closeApp(); } catch (const std::exception& e) { std::cerr << "Error occurred during execution: " << e.what() << '\n'; return 1; } return 0; }
30.042945
124
0.690219
DebugBSD
b17d9005e32ca7e74a76138ec3d21920b2b1ef1d
1,719
cpp
C++
cpp/leetcode/19.remove-nth-node-from-end-of-list.cpp
Gerrard-YNWA/piece_of_code
ea8c9f05a453c893cc1f10e9b91d4393838670c1
[ "MIT" ]
1
2021-11-02T05:17:24.000Z
2021-11-02T05:17:24.000Z
cpp/leetcode/19.remove-nth-node-from-end-of-list.cpp
Gerrard-YNWA/code
546230593c33ff322d3205499fe17cd6a9a437c1
[ "MIT" ]
null
null
null
cpp/leetcode/19.remove-nth-node-from-end-of-list.cpp
Gerrard-YNWA/code
546230593c33ff322d3205499fe17cd6a9a437c1
[ "MIT" ]
null
null
null
/* * @lc app=leetcode id=19 lang=cpp * * [19] Remove Nth Node From End of List */ #include<iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; ListNode* createLinkList(ListNode* head, int value) { ListNode *p = (ListNode*) malloc(sizeof(ListNode)); p->val = value; p->next = NULL; if (head == NULL) { head = p; } else { p->next = head; head = p; } return head; } void printLinkList(ListNode* head) { ListNode* cur = head; while (cur) { cout<<cur->val<<"->"; cur = cur->next; } cout<<endl; } // @lc code=start /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { auto slow = head, fast = head; for (auto i = 0; i < n; i++) fast = fast->next; if (!fast) return head->next; while(fast->next) { fast = fast->next; slow = slow->next; } slow->next = slow->next->next; return head; } }; // @lc code=end int main() { ListNode* head = NULL; for (auto i = 1; i < 10; i++){ head = createLinkList(head, i); } printLinkList(head); auto s = new Solution(); printLinkList(s->removeNthFromEnd(head, 5)); return 0; }
22.038462
62
0.531123
Gerrard-YNWA
b1833bc1679e730b452ffe1055feb24ec6380a2f
6,264
cpp
C++
runtime/sharings/gl/gl_buffer.cpp
PTS93/compute-runtime
0655045c7962d551e29008547a802e398b646c6e
[ "MIT" ]
null
null
null
runtime/sharings/gl/gl_buffer.cpp
PTS93/compute-runtime
0655045c7962d551e29008547a802e398b646c6e
[ "MIT" ]
null
null
null
runtime/sharings/gl/gl_buffer.cpp
PTS93/compute-runtime
0655045c7962d551e29008547a802e398b646c6e
[ "MIT" ]
null
null
null
/* * Copyright (C) 2018 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "config.h" #include "runtime/gmm_helper/gmm.h" #include "gl_buffer.h" #include "runtime/context/context.h" #include "runtime/mem_obj/buffer.h" #include "runtime/memory_manager/memory_manager.h" #include "runtime/helpers/get_info.h" #include "public/cl_gl_private_intel.h" using namespace OCLRT; Buffer *GlBuffer::createSharedGlBuffer(Context *context, cl_mem_flags flags, unsigned int bufferId, cl_int *errcodeRet) { ErrorCodeHelper errorCode(errcodeRet, CL_SUCCESS); CL_GL_BUFFER_INFO bufferInfo = {0}; bufferInfo.bufferName = bufferId; GLSharingFunctions *sharingFunctions = context->getSharing<GLSharingFunctions>(); if (sharingFunctions->acquireSharedBufferINTEL(&bufferInfo) == GL_FALSE) { errorCode.set(CL_INVALID_GL_OBJECT); return nullptr; } auto graphicsAllocation = GlBuffer::createGraphicsAllocation(context, bufferId, bufferInfo); if (!graphicsAllocation) { errorCode.set(CL_INVALID_GL_OBJECT); return nullptr; } auto glHandler = new GlBuffer(sharingFunctions, bufferId); return Buffer::createSharedBuffer(context, flags, glHandler, graphicsAllocation); } void GlBuffer::synchronizeObject(UpdateData &updateData) { const auto currentSharedHandle = updateData.memObject->getGraphicsAllocation()->peekSharedHandle(); CL_GL_BUFFER_INFO bufferInfo = {}; bufferInfo.bufferName = this->clGlObjectId; sharingFunctions->acquireSharedBufferINTEL(&bufferInfo); updateData.sharedHandle = bufferInfo.globalShareHandle; updateData.synchronizationStatus = SynchronizeStatus::ACQUIRE_SUCCESFUL; updateData.memObject->getGraphicsAllocation()->allocationOffset = bufferInfo.bufferOffset; if (currentSharedHandle != updateData.sharedHandle) { updateData.updateData = new CL_GL_BUFFER_INFO(bufferInfo); } } void GlBuffer::resolveGraphicsAllocationChange(osHandle currentSharedHandle, UpdateData *updateData) { const auto memObject = updateData->memObject; if (currentSharedHandle != updateData->sharedHandle) { const auto bufferInfo = std::unique_ptr<CL_GL_BUFFER_INFO>(static_cast<CL_GL_BUFFER_INFO *>(updateData->updateData)); auto oldGraphicsAllocation = memObject->getGraphicsAllocation(); popGraphicsAllocationFromReuse(oldGraphicsAllocation); Context *context = memObject->getContext(); auto newGraphicsAllocation = createGraphicsAllocation(context, clGlObjectId, *bufferInfo); if (newGraphicsAllocation == nullptr) { updateData->synchronizationStatus = SynchronizeStatus::SYNCHRONIZE_ERROR; } else { updateData->synchronizationStatus = SynchronizeStatus::ACQUIRE_SUCCESFUL; } memObject->resetGraphicsAllocation(newGraphicsAllocation); if (updateData->synchronizationStatus == SynchronizeStatus::ACQUIRE_SUCCESFUL) { memObject->getGraphicsAllocation()->allocationOffset = bufferInfo->bufferOffset; } } } void GlBuffer::popGraphicsAllocationFromReuse(GraphicsAllocation *graphicsAllocation) { std::unique_lock<std::mutex> lock(sharingFunctions->mutex); auto &graphicsAllocations = sharingFunctions->graphicsAllocationsForGlBufferReuse; auto foundIter = std::find_if(graphicsAllocations.begin(), graphicsAllocations.end(), [&graphicsAllocation](const std::pair<unsigned int, GraphicsAllocation *> &entry) { return entry.second == graphicsAllocation; }); if (foundIter != graphicsAllocations.end()) { std::iter_swap(foundIter, graphicsAllocations.end() - 1); graphicsAllocations.pop_back(); } graphicsAllocation->decReuseCount(); } void GlBuffer::releaseReusedGraphicsAllocation() { std::unique_lock<std::mutex> lock(sharingFunctions->mutex); auto &allocationsVector = sharingFunctions->graphicsAllocationsForGlBufferReuse; auto itEnd = allocationsVector.end(); for (auto it = allocationsVector.begin(); it != itEnd; it++) { if (it->first == clGlObjectId) { it->second->decReuseCount(); if (it->second->peekReuseCount() == 0) { std::iter_swap(it, itEnd - 1); allocationsVector.pop_back(); } break; } } } GraphicsAllocation *GlBuffer::createGraphicsAllocation(Context *context, unsigned int bufferId, _tagCLGLBufferInfo &bufferInfo) { GLSharingFunctions *sharingFunctions = context->getSharing<GLSharingFunctions>(); auto &allocationsVector = sharingFunctions->graphicsAllocationsForGlBufferReuse; GraphicsAllocation *graphicsAllocation = nullptr; bool reusedAllocation = false; std::unique_lock<std::mutex> lock(sharingFunctions->mutex); auto endIter = allocationsVector.end(); auto foundIter = std::find_if(allocationsVector.begin(), endIter, [&bufferId](const std::pair<unsigned int, GraphicsAllocation *> &entry) { return entry.first == bufferId; }); if (foundIter != endIter) { graphicsAllocation = foundIter->second; reusedAllocation = true; } if (!graphicsAllocation) { // couldn't find allocation for reuse - create new graphicsAllocation = context->getMemoryManager()->createGraphicsAllocationFromSharedHandle(bufferInfo.globalShareHandle, true); } if (!graphicsAllocation) { return nullptr; } graphicsAllocation->incReuseCount(); // decremented in releaseReusedGraphicsAllocation() called from MemObj destructor if (!reusedAllocation) { sharingFunctions->graphicsAllocationsForGlBufferReuse.push_back(std::make_pair(bufferId, graphicsAllocation)); if (bufferInfo.pGmmResInfo) { DEBUG_BREAK_IF(graphicsAllocation->gmm != nullptr); graphicsAllocation->gmm = new Gmm(bufferInfo.pGmmResInfo); } } return graphicsAllocation; } void GlBuffer::releaseResource(MemObj *memObject) { CL_GL_BUFFER_INFO bufferInfo = {}; bufferInfo.bufferName = this->clGlObjectId; sharingFunctions->releaseSharedBufferINTEL(&bufferInfo); }
40.412903
130
0.711686
PTS93
b18992a6acf3e3bda7390b807ab0980c6e8bf754
2,668
hpp
C++
renderer/abstract_renderable.hpp
Themaister/Granite
02d77ced67269278476aae7a178f8f2a4fbe9a75
[ "MIT" ]
1,003
2017-08-13T17:47:04.000Z
2022-03-29T15:56:55.000Z
renderer/abstract_renderable.hpp
Themaister/Granite
02d77ced67269278476aae7a178f8f2a4fbe9a75
[ "MIT" ]
10
2017-08-14T19:11:35.000Z
2021-12-10T12:51:53.000Z
renderer/abstract_renderable.hpp
Themaister/Granite
02d77ced67269278476aae7a178f8f2a4fbe9a75
[ "MIT" ]
107
2017-08-16T16:13:26.000Z
2022-03-03T06:42:19.000Z
/* Copyright (c) 2017-2020 Hans-Kristian Arntzen * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "aabb.hpp" #include "intrusive.hpp" namespace Granite { class RenderQueue; class RenderContext; class ShaderSuite; struct RenderInfoComponent; struct SpriteTransformInfo; enum class DrawPipeline : unsigned { Opaque, AlphaTest, AlphaBlend, }; enum RenderableFlagBits { RENDERABLE_FORCE_VISIBLE_BIT = 1 << 0, RENDERABLE_IMPLICIT_MOTION_BIT = 1 << 1 }; using RenderableFlags = uint32_t; class AbstractRenderable : public Util::IntrusivePtrEnabled<AbstractRenderable> { public: virtual ~AbstractRenderable() = default; virtual void get_render_info(const RenderContext &context, const RenderInfoComponent *transform, RenderQueue &queue) const = 0; virtual void get_depth_render_info(const RenderContext &context, const RenderInfoComponent *transform, RenderQueue &queue) const { return get_render_info(context, transform, queue); } virtual void get_motion_vector_render_info(const RenderContext &context, const RenderInfoComponent *transform, RenderQueue &queue) const { return get_render_info(context, transform, queue); } virtual void get_sprite_render_info(const SpriteTransformInfo &, RenderQueue &) const { } virtual bool has_static_aabb() const { return false; } virtual const AABB *get_static_aabb() const { static const AABB aabb(vec3(0.0f), vec3(0.0f)); return &aabb; } virtual DrawPipeline get_mesh_draw_pipeline() const { return DrawPipeline::Opaque; } RenderableFlags flags = 0; }; using AbstractRenderableHandle = Util::IntrusivePtr<AbstractRenderable>; }
29.644444
137
0.773613
Themaister
b18d202886031d11709d08f6c7ea84c0296daeb5
2,660
hpp
C++
REST/VersionInfo.hpp
NuLL3rr0r/tse-rtsq
84da0cc5ebecdfe7c6bf0e01e332eb131022eec2
[ "MIT" ]
5
2015-10-28T07:05:27.000Z
2021-09-29T12:14:17.000Z
REST/VersionInfo.hpp
NuLL3rr0r/tse-rtsq
84da0cc5ebecdfe7c6bf0e01e332eb131022eec2
[ "MIT" ]
null
null
null
REST/VersionInfo.hpp
NuLL3rr0r/tse-rtsq
84da0cc5ebecdfe7c6bf0e01e332eb131022eec2
[ "MIT" ]
2
2015-10-24T18:24:38.000Z
2019-02-02T05:06:48.000Z
/** * @file * @author Mohammad S. Babaei <info@babaei.net> * @version 0.1.0 * * @section LICENSE * * (The MIT License) * * Copyright (c) 2015 Mohammad S. Babaei * * 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. * * @section DESCRIPTION * * Provides application information. */ #ifndef REST_VERSIONINFO_HPP #define REST_VERSIONINFO_HPP #define VERSION_INFO_BUILD_COMPILER PRODUCT_BUILD_COMPILER #define VERSION_INFO_BUILD_DATE __DATE__ " " __TIME__ #define VERSION_INFO_BUILD_HOST PRODUCT_BUILD_HOST #define VERSION_INFO_BUILD_PROCESSOR PRODUCT_BUILD_PROCESSOR #define VERSION_INFO_BUILD_SYSTEM PRODUCT_BUILD_SYSTEM #define VERSION_INFO_PRODUCT_COMPANY_NAME PRODUCT_COMPANY_NAME #define VERSION_INFO_PRODUCT_COPYRIGHT_HOLDER PRODUCT_COPYRIGHT_HOLDER #define VERSION_INFO_PRODUCT_COPYRIGHT_YEAR PRODUCT_COPYRIGHT_YEAR #define VERSION_INFO_PRODUCT_COPYRIGHT PRODUCT_COPYRIGHT #define VERSION_INFO_PRODUCT_INTERNAL_NAME PRODUCT_INTERNAL_NAME #define VERSION_INFO_PRODUCT_NAME PRODUCT_NAME #define VERSION_INFO_PRODUCT_VERSION_MAJOR PRODUCT_VERSION_MAJOR #define VERSION_INFO_PRODUCT_VERSION_MINOR PRODUCT_VERSION_MINOR #define VERSION_INFO_PRODUCT_VERSION_PATCH PRODUCT_VERSION_PATCH #define VERSION_INFO_PRODUCT_VERSION_REVISION PRODUCT_VERSION_REVISION #define VERSION_INFO_PRODUCT_VERSION PRODUCT_VERSION #define VERSION_INFO_PRODUCT_DESCRIPTION PRODUCT_DESCRIPTION #endif /* REST_VERSIONINFO_HPP */
42.222222
80
0.756391
NuLL3rr0r
b190bc0cd3f948fbe43151b460281c197037edc7
4,374
cpp
C++
src/wm.cpp
cbeck88/HexWarfare
94a70b1889afc2fbd990892ed66be874ac70d1b4
[ "Apache-2.0" ]
null
null
null
src/wm.cpp
cbeck88/HexWarfare
94a70b1889afc2fbd990892ed66be874ac70d1b4
[ "Apache-2.0" ]
null
null
null
src/wm.cpp
cbeck88/HexWarfare
94a70b1889afc2fbd990892ed66be874ac70d1b4
[ "Apache-2.0" ]
null
null
null
/* Copyright 2014 Kristina Simpson <sweet.kristas@gmail.com> 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 <iostream> #include <sstream> #include <vector> #include "profile_timer.hpp" #include "sdl_wrapper.hpp" #include "wm.hpp" namespace graphics { namespace { std::vector<window_manager*>& get_windows() { static std::vector<window_manager*> res; return res; } } window_manager::window_manager() : window_(nullptr), renderer_(nullptr), width_(1024), height_(768) { } window_manager& window_manager::get_main_window() { ASSERT_LOG(!get_windows().empty(), "No windows in list, or has not been set."); return *get_windows().front(); } void window_manager::create_window(const std::string& title, int x, int y, int w, int h, Uint32 flags) { //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); profile::manager prof("SDL_CreateWindow"); window_ = SDL_CreateWindow(title.c_str(), x, y, w, h, flags); if(!window_) { std::stringstream ss; ss << "Could not create window: " << SDL_GetError() << "\n"; throw init_error(ss.str()); } width_ = w; height_ = h; area_ = rect(0, 0, w, h); // Search for opengl renderer int num_rend = SDL_GetNumRenderDrivers(); if(num_rend < 0) { std::stringstream ss; ss << "Could not enumerate renderers: " << SDL_GetError() << "\n"; throw init_error(ss.str()); } std::stringstream renderer_list; for(int n = 0; n != num_rend; ++n) { SDL_RendererInfo ri; int err = SDL_GetRenderDriverInfo(n, &ri); std::cerr << "XXX: Probing driver " << ri.name << ": " << ri.flags << " : texture dimensions " << ri.max_texture_width << "," << ri.max_texture_height << "\n"; if(err != 0) { std::stringstream ss; ss << "error getting details for renderer " << n << ": " << SDL_GetError() << "\n"; throw init_error(ss.str()); } renderer_list << " : " << ri.name; if(std::string(ri.name) == "opengl") { renderer_ = SDL_CreateRenderer(window_, n, SDL_RENDERER_ACCELERATED); if(!renderer_) { std::stringstream ss; ss << "Could not create renderer: " << SDL_GetError() << "\n"; throw init_error(ss.str()); } break; } } if(renderer_ == nullptr) { std::stringstream ss; ss << "No OpenGL renderer found, options" << renderer_list.str() << "\n"; throw init_error(ss.str()); } SDL_SetHintWithPriority(SDL_HINT_RENDER_VSYNC, "0", SDL_HINT_OVERRIDE); get_windows().emplace_back(this); } void window_manager::set_icon(const std::string& icon) { SDL_Surface* img = IMG_Load(icon.c_str()); if(img) { SDL_SetWindowIcon(window_, img); SDL_FreeSurface(img); } else { std::cerr << "Unable to load icon: " << icon << std::endl; } } void window_manager::gl_init() { //profile::manager prof("SDL_GL_CreateContext"); //glcontext_ = SDL_GL_CreateContext(window_); /* glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); glShadeModel(GL_SMOOTH); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glViewport(0, 0, GLsizei(width_), GLsizei(height_)); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); */ // Enable depth test //glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one //glDepthFunc(GL_LESS); // Cull triangles which normal is not towards the camera //glEnable(GL_CULL_FACE); } void window_manager::swap() { //SDL_GL_SwapWindow(window_); } void window_manager::update_window_size() { // In some cases this should be SDL_GL_GetDrawableSize SDL_GetWindowSize(window_, &width_, &height_); area_ = rect(0, 0, width_, height_); } window_manager::~window_manager() { //SDL_GL_DeleteContext(glcontext_); SDL_DestroyRenderer(renderer_); SDL_DestroyWindow(window_); } }
27.509434
162
0.678555
cbeck88
b1926efb7176112a705164e4f0e2efd9d1941c71
28,310
cpp
C++
tests/animation/src/AnimTests.cpp
MarkBrosche/hifi
71669af69675da78253a9e774ca5b3d303da5780
[ "Apache-2.0" ]
null
null
null
tests/animation/src/AnimTests.cpp
MarkBrosche/hifi
71669af69675da78253a9e774ca5b3d303da5780
[ "Apache-2.0" ]
null
null
null
tests/animation/src/AnimTests.cpp
MarkBrosche/hifi
71669af69675da78253a9e774ca5b3d303da5780
[ "Apache-2.0" ]
null
null
null
// // AnimTests.cpp // // Copyright 2015 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "AnimTests.h" #include <AnimNodeLoader.h> #include <AnimClip.h> #include <AnimBlendLinear.h> #include <AnimationLogging.h> #include <AnimVariant.h> #include <AnimExpression.h> #include <AnimUtil.h> #include <NodeList.h> #include <AddressManager.h> #include <AccountManager.h> #include <ResourceManager.h> #include <ResourceRequestObserver.h> #include <StatTracker.h> #include <test-utils/QTestExtensions.h> #include <test-utils/GLMTestUtils.h> QTEST_MAIN(AnimTests) const float TEST_EPSILON = 0.001f; void AnimTests::initTestCase() { DependencyManager::registerInheritance<LimitedNodeList, NodeList>(); DependencyManager::set<AccountManager>(); DependencyManager::set<AddressManager>(); DependencyManager::set<NodeList>(NodeType::Agent); DependencyManager::set<ResourceManager>(); DependencyManager::set<AnimationCache>(); DependencyManager::set<ResourceRequestObserver>(); DependencyManager::set<ResourceCacheSharedItems>(); DependencyManager::set<StatTracker>(); } void AnimTests::cleanupTestCase() { //DependencyManager::destroy<AnimationCache>(); DependencyManager::get<ResourceManager>()->cleanup(); } void AnimTests::testClipInternalState() { QString id = "my anim clip"; QString url = "https://hifi-public.s3.amazonaws.com/ozan/support/FightClubBotTest1/Animations/standard_idle.fbx"; float startFrame = 2.0f; float endFrame = 20.0f; float timeScale = 1.1f; bool loopFlag = true; bool mirrorFlag = false; AnimClip clip(id, url, startFrame, endFrame, timeScale, loopFlag, mirrorFlag); QVERIFY(clip.getID() == id); QVERIFY(clip.getType() == AnimNode::Type::Clip); QVERIFY(clip._url == url); QVERIFY(clip._startFrame == startFrame); QVERIFY(clip._endFrame == endFrame); QVERIFY(clip._timeScale == timeScale); QVERIFY(clip._loopFlag == loopFlag); QVERIFY(clip._mirrorFlag == mirrorFlag); } static float framesToSec(float secs) { const float FRAMES_PER_SECOND = 30.0f; return secs / FRAMES_PER_SECOND; } void AnimTests::testClipEvaulate() { AnimContext context(false, false, false, glm::mat4(), glm::mat4()); QString id = "myClipNode"; QString url = "https://hifi-public.s3.amazonaws.com/ozan/support/FightClubBotTest1/Animations/standard_idle.fbx"; float startFrame = 2.0f; float endFrame = 22.0f; float timeScale = 1.0f; bool loopFlag = true; bool mirrorFlag = false; auto vars = AnimVariantMap(); vars.set("FalseVar", false); AnimClip clip(id, url, startFrame, endFrame, timeScale, loopFlag, mirrorFlag); AnimVariantMap triggers; clip.evaluate(vars, context, framesToSec(10.0f), triggers); QCOMPARE_WITH_ABS_ERROR(clip._frame, 12.0f, TEST_EPSILON); // does it loop? triggers.clearMap(); clip.evaluate(vars, context, framesToSec(12.0f), triggers); QCOMPARE_WITH_ABS_ERROR(clip._frame, 3.0f, TEST_EPSILON); // Note: frame 3 and not 4, because extra frame between start and end. // did we receive a loop trigger? QVERIFY(triggers.hasKey("myClipNodeOnLoop")); // does it pause at end? triggers.clearMap(); clip.setLoopFlagVar("FalseVar"); clip.evaluate(vars, context, framesToSec(20.0f), triggers); QCOMPARE_WITH_ABS_ERROR(clip._frame, 22.0f, TEST_EPSILON); // did we receive a done trigger? QVERIFY(triggers.hasKey("myClipNodeOnDone")); } void AnimTests::testClipEvaulateWithVars() { AnimContext context(false, false, false, glm::mat4(), glm::mat4()); QString id = "myClipNode"; QString url = "https://hifi-public.s3.amazonaws.com/ozan/support/FightClubBotTest1/Animations/standard_idle.fbx"; float startFrame = 2.0f; float endFrame = 22.0f; float timeScale = 1.0f; bool loopFlag = true; bool mirrorFlag = false; float startFrame2 = 22.0f; float endFrame2 = 100.0f; float timeScale2 = 1.2f; bool loopFlag2 = false; auto vars = AnimVariantMap(); vars.set("startFrame2", startFrame2); vars.set("endFrame2", endFrame2); vars.set("timeScale2", timeScale2); vars.set("loopFlag2", loopFlag2); AnimClip clip(id, url, startFrame, endFrame, timeScale, loopFlag, mirrorFlag); clip.setStartFrameVar("startFrame2"); clip.setEndFrameVar("endFrame2"); clip.setTimeScaleVar("timeScale2"); clip.setLoopFlagVar("loopFlag2"); AnimVariantMap triggers; clip.evaluate(vars, context, framesToSec(0.1f), triggers); // verify that the values from the AnimVariantMap made it into the clipNode's // internal state QVERIFY(clip._startFrame == startFrame2); QVERIFY(clip._endFrame == endFrame2); QVERIFY(clip._timeScale == timeScale2); QVERIFY(clip._loopFlag == loopFlag2); } void AnimTests::testLoader() { auto url = QUrl("https://gist.githubusercontent.com/hyperlogic/756e6b7018c96c9778dba4ffb959c3c7/raw/4b37f10c9d2636608916208ba7b415c1a3f842ff/test.json"); // NOTE: This will warn about missing "test01.fbx", "test02.fbx", etc. if the resource loading code doesn't handle relative pathnames! // However, the test will proceed. AnimNodeLoader loader(url); const int timeout = 1000; QEventLoop loop; AnimNode::Pointer node = nullptr; connect(&loader, &AnimNodeLoader::success, [&](AnimNode::Pointer nodeIn) { node = nodeIn; }); loop.connect(&loader, SIGNAL(success(AnimNode::Pointer)), SLOT(quit())); loop.connect(&loader, SIGNAL(error(int, QString)), SLOT(quit())); QTimer::singleShot(timeout, &loop, SLOT(quit())); loop.exec(); QVERIFY((bool)node); QVERIFY(node->getID() == "blend"); QVERIFY(node->getType() == AnimNode::Type::BlendLinear); QVERIFY((bool)node); QVERIFY(node->getID() == "blend"); QVERIFY(node->getType() == AnimNode::Type::BlendLinear); auto blend = std::static_pointer_cast<AnimBlendLinear>(node); QVERIFY(blend->_alpha == 0.5f); QVERIFY(node->getChildCount() == 3); std::shared_ptr<AnimNode> nodes[3] = { node->getChild(0), node->getChild(1), node->getChild(2) }; QVERIFY(nodes[0]->getID() == "test01"); QVERIFY(nodes[0]->getChildCount() == 0); QVERIFY(nodes[1]->getID() == "test02"); QVERIFY(nodes[1]->getChildCount() == 0); QVERIFY(nodes[2]->getID() == "test03"); QVERIFY(nodes[2]->getChildCount() == 0); auto test01 = std::static_pointer_cast<AnimClip>(nodes[0]); QUrl relativeUrl01("test01.fbx"); QString url01 = url.resolved(relativeUrl01).toString(); QVERIFY(test01->_url == url01); QVERIFY(test01->_startFrame == 1.0f); QVERIFY(test01->_endFrame == 20.0f); QVERIFY(test01->_timeScale == 1.0f); QVERIFY(test01->_loopFlag == false); auto test02 = std::static_pointer_cast<AnimClip>(nodes[1]); QUrl relativeUrl02("test02.fbx"); QString url02 = url.resolved(relativeUrl02).toString(); QVERIFY(test02->_url == url02); QVERIFY(test02->_startFrame == 2.0f); QVERIFY(test02->_endFrame == 21.0f); QVERIFY(test02->_timeScale == 0.9f); QVERIFY(test02->_loopFlag == true); } void AnimTests::testVariant() { auto defaultVar = AnimVariant(); auto boolVarTrue = AnimVariant(true); auto boolVarFalse = AnimVariant(false); auto intVarZero = AnimVariant(0); auto intVarOne = AnimVariant(1); auto intVarNegative = AnimVariant(-1); auto floatVarZero = AnimVariant(0.0f); auto floatVarOne = AnimVariant(1.0f); auto floatVarNegative = AnimVariant(-1.0f); auto vec3Var = AnimVariant(glm::vec3(1.0f, -2.0f, 3.0f)); auto quatVar = AnimVariant(glm::quat(1.0f, 2.0f, -3.0f, 4.0f)); QVERIFY(defaultVar.isBool()); QVERIFY(defaultVar.getBool() == false); QVERIFY(boolVarTrue.isBool()); QVERIFY(boolVarTrue.getBool() == true); QVERIFY(boolVarFalse.isBool()); QVERIFY(boolVarFalse.getBool() == false); QVERIFY(intVarZero.isInt()); QVERIFY(intVarZero.getInt() == 0); QVERIFY(intVarOne.isInt()); QVERIFY(intVarOne.getInt() == 1); QVERIFY(intVarNegative.isInt()); QVERIFY(intVarNegative.getInt() == -1); QVERIFY(floatVarZero.isFloat()); QVERIFY(floatVarZero.getFloat() == 0.0f); QVERIFY(floatVarOne.isFloat()); QVERIFY(floatVarOne.getFloat() == 1.0f); QVERIFY(floatVarNegative.isFloat()); QVERIFY(floatVarNegative.getFloat() == -1.0f); QVERIFY(vec3Var.isVec3()); auto v = vec3Var.getVec3(); QVERIFY(v.x == 1.0f); QVERIFY(v.y == -2.0f); QVERIFY(v.z == 3.0f); QVERIFY(quatVar.isQuat()); auto q = quatVar.getQuat(); QVERIFY(q.w == 1.0f); QVERIFY(q.x == 2.0f); QVERIFY(q.y == -3.0f); QVERIFY(q.z == 4.0f); } void AnimTests::testAccumulateTime() { float startFrame = 0.0f; float endFrame = 10.0f; float timeScale = 1.0f; testAccumulateTimeWithParameters(startFrame, endFrame, timeScale); startFrame = 5.0f; endFrame = 15.0f; timeScale = 1.0f; testAccumulateTimeWithParameters(startFrame, endFrame, timeScale); startFrame = 0.0f; endFrame = 10.0f; timeScale = 0.5f; testAccumulateTimeWithParameters(startFrame, endFrame, timeScale); startFrame = 5.0f; endFrame = 15.0f; timeScale = 2.0f; testAccumulateTimeWithParameters(startFrame, endFrame, timeScale); startFrame = 0.0f; endFrame = 1.0f; timeScale = 1.0f; float dt = 1.0f; QString id = "testNode"; AnimVariantMap triggers; float loopFlag = true; float resultFrame = accumulateTime(startFrame, endFrame, timeScale, startFrame, dt, loopFlag, id, triggers); // a one frame looping animation should NOT trigger onLoop events QVERIFY(!triggers.hasKey("testNodeOnLoop")); const uint32_t MAX_TRIGGER_COUNT = 3; startFrame = 0.0f; endFrame = 1.1f; timeScale = 10.0f; dt = 10.0f; triggers.clearMap(); loopFlag = true; resultFrame = accumulateTime(startFrame, endFrame, timeScale, startFrame, dt, loopFlag, id, triggers); // a short animation with a large dt & a large timescale, should generate a onLoop event. QVERIFY(triggers.hasKey("testNodeOnLoop")); } void AnimTests::testAccumulateTimeWithParameters(float startFrame, float endFrame, float timeScale) const { float dt = (1.0f / 30.0f) / timeScale; // sec QString id = "testNode"; AnimVariantMap triggers; bool loopFlag = false; float resultFrame = accumulateTime(startFrame, endFrame, timeScale, startFrame, dt, loopFlag, id, triggers); QVERIFY(resultFrame == startFrame + 1.0f); QVERIFY(!triggers.hasKey("testNodeOnLoop")); triggers.clearMap(); resultFrame = accumulateTime(startFrame, endFrame, timeScale, resultFrame, dt, loopFlag, id, triggers); QVERIFY(resultFrame == startFrame + 2.0f); QVERIFY(!triggers.hasKey("testNodeOnLoop")); triggers.clearMap(); resultFrame = accumulateTime(startFrame, endFrame, timeScale, resultFrame, dt, loopFlag, id, triggers); QVERIFY(resultFrame == startFrame + 3.0f); QVERIFY(!triggers.hasKey("testNodeOnLoop")); triggers.clearMap(); // test onDone trigger and frame clamping. resultFrame = accumulateTime(startFrame, endFrame, timeScale, endFrame - 1.0f, dt, loopFlag, id, triggers); QVERIFY(resultFrame == endFrame); QVERIFY(triggers.hasKey("testNodeOnDone")); triggers.clearMap(); resultFrame = accumulateTime(startFrame, endFrame, timeScale, endFrame - 0.5f, dt, loopFlag, id, triggers); QVERIFY(resultFrame == endFrame); QVERIFY(triggers.hasKey("testNodeOnDone")); triggers.clearMap(); // test onLoop trigger and looping frame logic loopFlag = true; // should NOT trigger loop even though we stop at last frame, because there is an extra frame between end and start frames. resultFrame = accumulateTime(startFrame, endFrame, timeScale, endFrame - 1.0f, dt, loopFlag, id, triggers); QVERIFY(resultFrame == endFrame); QVERIFY(!triggers.hasKey("testNodeOnLoop")); triggers.clearMap(); // now we should hit loop trigger resultFrame = accumulateTime(startFrame, endFrame, timeScale, resultFrame, dt, loopFlag, id, triggers); QVERIFY(resultFrame == startFrame); QVERIFY(triggers.hasKey("testNodeOnLoop")); triggers.clearMap(); // should NOT trigger loop, even though we move past the end frame, because of extra frame between end and start. resultFrame = accumulateTime(startFrame, endFrame, timeScale, endFrame - 0.5f, dt, loopFlag, id, triggers); QVERIFY(resultFrame == endFrame + 0.5f); QVERIFY(!triggers.hasKey("testNodeOnLoop")); triggers.clearMap(); // now we should hit loop trigger resultFrame = accumulateTime(startFrame, endFrame, timeScale, resultFrame, dt, loopFlag, id, triggers); QVERIFY(resultFrame == startFrame + 0.5f); QVERIFY(triggers.hasKey("testNodeOnLoop")); triggers.clearMap(); } void AnimTests::testAnimPose() { const float PI = (float)M_PI; const glm::quat ROT_X_90 = glm::angleAxis(PI / 2.0f, glm::vec3(1.0f, 0.0f, 0.0f)); const glm::quat ROT_Y_180 = glm::angleAxis(PI, glm::vec3(0.0f, 1.0, 0.0f)); const glm::quat ROT_Z_30 = glm::angleAxis(PI / 6.0f, glm::vec3(1.0f, 0.0f, 0.0f)); std::vector<float> scaleVec = { 1.0f, 2.0f, 0.5f }; std::vector<glm::quat> rotVec = { glm::quat(), ROT_X_90, ROT_Y_180, ROT_Z_30, ROT_X_90 * ROT_Y_180 * ROT_Z_30, -ROT_Y_180 }; std::vector<glm::vec3> transVec = { glm::vec3(), glm::vec3(10.0f, 0.0f, 0.0f), glm::vec3(0.0f, 5.0f, 0.0f), glm::vec3(0.0f, 0.0f, 7.5f), glm::vec3(10.0f, 5.0f, 7.5f), glm::vec3(-10.0f, 5.0f, 7.5f), glm::vec3(10.0f, -5.0f, 7.5f), glm::vec3(10.0f, 5.0f, -7.5f) }; const float TEST_EPSILON = 0.001f; for (auto& scale : scaleVec) { for (auto& rot : rotVec) { for (auto& trans : transVec) { // build a matrix the old fashioned way. glm::mat4 scaleMat = glm::scale(glm::mat4(), glm::vec3(scale)); glm::mat4 rotTransMat = createMatFromQuatAndPos(rot, trans); glm::mat4 rawMat = rotTransMat * scaleMat; // use an anim pose to build a matrix by parts. AnimPose pose(scale, rot, trans); glm::mat4 poseMat = pose; QCOMPARE_WITH_ABS_ERROR(rawMat, poseMat, TEST_EPSILON); } } } for (auto& scale : scaleVec) { for (auto& rot : rotVec) { for (auto& trans : transVec) { // build a matrix the old fashioned way. glm::mat4 scaleMat = glm::scale(glm::mat4(), glm::vec3(scale)); glm::mat4 rotTransMat = createMatFromQuatAndPos(rot, trans); glm::mat4 rawMat = rotTransMat * scaleMat; // use an anim pose to decompse a matrix into parts AnimPose pose(rawMat); // now build a new matrix from those parts. glm::mat4 poseMat = pose; QCOMPARE_WITH_ABS_ERROR(rawMat, poseMat, TEST_EPSILON); } } } } void AnimTests::testAnimPoseMultiply() { const float PI = (float)M_PI; const glm::quat ROT_X_90 = glm::angleAxis(PI / 2.0f, glm::vec3(1.0f, 0.0f, 0.0f)); const glm::quat ROT_Y_180 = glm::angleAxis(PI, glm::vec3(0.0f, 1.0, 0.0f)); const glm::quat ROT_Z_30 = glm::angleAxis(PI / 6.0f, glm::vec3(1.0f, 0.0f, 0.0f)); std::vector<float> scaleVec = { 1.0f, 2.0f, 0.5f, }; std::vector<glm::quat> rotVec = { glm::quat(), ROT_X_90, ROT_Y_180, ROT_Z_30, ROT_X_90 * ROT_Y_180 * ROT_Z_30, -ROT_Y_180 }; std::vector<glm::vec3> transVec = { glm::vec3(), glm::vec3(10.0f, 0.0f, 0.0f), glm::vec3(0.0f, 5.0f, 0.0f), glm::vec3(0.0f, 0.0f, 7.5f), glm::vec3(10.0f, 5.0f, 7.5f), glm::vec3(-10.0f, 5.0f, 7.5f), glm::vec3(10.0f, -5.0f, 7.5f), glm::vec3(10.0f, 5.0f, -7.5f) }; const float TEST_EPSILON = 0.001f; std::vector<glm::mat4> matrixVec; std::vector<AnimPose> poseVec; for (auto& scale : scaleVec) { for (auto& rot : rotVec) { for (auto& trans : transVec) { // build a matrix the old fashioned way. glm::mat4 scaleMat = glm::scale(glm::mat4(), glm::vec3(scale)); glm::mat4 rotTransMat = createMatFromQuatAndPos(rot, trans); glm::mat4 rawMat = rotTransMat * scaleMat; matrixVec.push_back(rawMat); // use an anim pose to build a matrix by parts. AnimPose pose(scale, rot, trans); poseVec.push_back(pose); } } } for (int i = 0; i < matrixVec.size(); i++) { for (int j = 0; j < matrixVec.size(); j++) { // multiply the matrices together glm::mat4 matrix = matrixVec[i] * matrixVec[j]; // convert to matrix (note this will remove sheer from the matrix) AnimPose resultA(matrix); // multiply the poses together directly AnimPose resultB = poseVec[i] * poseVec[j]; /* qDebug() << "matrixVec[" << i << "] =" << matrixVec[i]; qDebug() << "matrixVec[" << j << "] =" << matrixVec[j]; qDebug() << "matrixResult =" << resultA; qDebug() << "poseVec[" << i << "] =" << poseVec[i]; qDebug() << "poseVec[" << j << "] =" << poseVec[j]; qDebug() << "poseResult =" << resultB; */ // compare results. QCOMPARE_WITH_ABS_ERROR(resultA.scale(), resultB.scale(), TEST_EPSILON); QCOMPARE_WITH_ABS_ERROR(resultA.rot(), resultB.rot(), TEST_EPSILON); QCOMPARE_WITH_ABS_ERROR(resultA.trans(), resultB.trans(), TEST_EPSILON); } } } void AnimTests::testAnimPoseInverse() { const float PI = (float)M_PI; const glm::quat ROT_X_90 = glm::angleAxis(PI / 2.0f, glm::vec3(1.0f, 0.0f, 0.0f)); const glm::quat ROT_Y_180 = glm::angleAxis(PI, glm::vec3(0.0f, 1.0, 0.0f)); const glm::quat ROT_Z_30 = glm::angleAxis(PI / 6.0f, glm::vec3(1.0f, 0.0f, 0.0f)); std::vector<float> scaleVec = { 1.0f, 2.0f, 0.5f }; std::vector<glm::quat> rotVec = { glm::quat(), ROT_X_90, ROT_Y_180, ROT_Z_30, ROT_X_90 * ROT_Y_180 * ROT_Z_30, -ROT_Y_180 }; std::vector<glm::vec3> transVec = { glm::vec3(), glm::vec3(10.0f, 0.0f, 0.0f), glm::vec3(0.0f, 5.0f, 0.0f), glm::vec3(0.0f, 0.0f, 7.5f), glm::vec3(10.0f, 5.0f, 7.5f), glm::vec3(-10.0f, 5.0f, 7.5f), glm::vec3(10.0f, -5.0f, 7.5f), glm::vec3(10.0f, 5.0f, -7.5f) }; const float TEST_EPSILON = 0.001f; for (auto& scale : scaleVec) { for (auto& rot : rotVec) { for (auto& trans : transVec) { // build a matrix the old fashioned way. glm::mat4 scaleMat = glm::scale(glm::mat4(), glm::vec3(scale)); glm::mat4 rotTransMat = createMatFromQuatAndPos(rot, trans); glm::mat4 rawMat = glm::inverse(rotTransMat * scaleMat); // use an anim pose to build a matrix by parts. AnimPose pose(scale, rot, trans); glm::mat4 poseMat = pose.inverse(); QCOMPARE_WITH_ABS_ERROR(rawMat, poseMat, TEST_EPSILON); } } } } void AnimTests::testExpressionTokenizer() { QString str = "(10 + x) >= 20.1 && (y != !z)"; AnimExpression e("x"); auto iter = str.cbegin(); AnimExpression::Token token = e.consumeToken(str, iter); QVERIFY(token.type == AnimExpression::Token::LeftParen); token = e.consumeToken(str, iter); QVERIFY(token.type == AnimExpression::Token::Int); QVERIFY(token.intVal == 10); token = e.consumeToken(str, iter); QVERIFY(token.type == AnimExpression::Token::Plus); token = e.consumeToken(str, iter); QVERIFY(token.type == AnimExpression::Token::Identifier); QVERIFY(token.strVal == "x"); token = e.consumeToken(str, iter); QVERIFY(token.type == AnimExpression::Token::RightParen); token = e.consumeToken(str, iter); QVERIFY(token.type == AnimExpression::Token::GreaterThanEqual); token = e.consumeToken(str, iter); QVERIFY(token.type == AnimExpression::Token::Float); QVERIFY(fabsf(token.floatVal - 20.1f) < 0.0001f); token = e.consumeToken(str, iter); QVERIFY(token.type == AnimExpression::Token::And); token = e.consumeToken(str, iter); QVERIFY(token.type == AnimExpression::Token::LeftParen); token = e.consumeToken(str, iter); QVERIFY(token.type == AnimExpression::Token::Identifier); QVERIFY(token.strVal == "y"); token = e.consumeToken(str, iter); QVERIFY(token.type == AnimExpression::Token::NotEqual); token = e.consumeToken(str, iter); QVERIFY(token.type == AnimExpression::Token::Not); token = e.consumeToken(str, iter); QVERIFY(token.type == AnimExpression::Token::Identifier); QVERIFY(token.strVal == "z"); token = e.consumeToken(str, iter); QVERIFY(token.type == AnimExpression::Token::RightParen); token = e.consumeToken(str, iter); str = "true"; iter = str.cbegin(); token = e.consumeToken(str, iter); QVERIFY(token.type == AnimExpression::Token::Bool); QVERIFY(token.intVal == (int)true); } void AnimTests::testExpressionParser() { auto vars = AnimVariantMap(); vars.set("f", false); vars.set("t", true); vars.set("ten", (int)10); vars.set("twenty", (int)20); vars.set("five", (float)5.0f); vars.set("forty", (float)40.0f); AnimExpression e("10"); QVERIFY(e._opCodes.size() == 1); if (e._opCodes.size() == 1) { QVERIFY(e._opCodes[0].type == AnimExpression::OpCode::Int); QVERIFY(e._opCodes[0].intVal == 10); } e = AnimExpression("(10)"); QVERIFY(e._opCodes.size() == 1); if (e._opCodes.size() == 1) { QVERIFY(e._opCodes[0].type == AnimExpression::OpCode::Int); QVERIFY(e._opCodes[0].intVal == 10); } e = AnimExpression("((10))"); QVERIFY(e._opCodes.size() == 1); if (e._opCodes.size() == 1) { QVERIFY(e._opCodes[0].type == AnimExpression::OpCode::Int); QVERIFY(e._opCodes[0].intVal == 10); } e = AnimExpression("12.5"); QVERIFY(e._opCodes.size() == 1); if (e._opCodes.size() == 1) { QVERIFY(e._opCodes[0].type == AnimExpression::OpCode::Float); QVERIFY(e._opCodes[0].floatVal == 12.5f); } e = AnimExpression("twenty"); QVERIFY(e._opCodes.size() == 1); if (e._opCodes.size() == 1) { QVERIFY(e._opCodes[0].type == AnimExpression::OpCode::Identifier); QVERIFY(e._opCodes[0].strVal == "twenty"); } e = AnimExpression("true || false"); QVERIFY(e._opCodes.size() == 3); if (e._opCodes.size() == 3) { QVERIFY(e._opCodes[0].type == AnimExpression::OpCode::Bool); QVERIFY(e._opCodes[0].intVal == (int)true); QVERIFY(e._opCodes[1].type == AnimExpression::OpCode::Bool); QVERIFY(e._opCodes[1].intVal == (int)false); QVERIFY(e._opCodes[2].type == AnimExpression::OpCode::Or); } e = AnimExpression("true || false && true"); QVERIFY(e._opCodes.size() == 5); if (e._opCodes.size() == 5) { QVERIFY(e._opCodes[0].type == AnimExpression::OpCode::Bool); QVERIFY(e._opCodes[0].intVal == (int)true); QVERIFY(e._opCodes[1].type == AnimExpression::OpCode::Bool); QVERIFY(e._opCodes[1].intVal == (int)false); QVERIFY(e._opCodes[2].type == AnimExpression::OpCode::Bool); QVERIFY(e._opCodes[2].intVal == (int)true); QVERIFY(e._opCodes[3].type == AnimExpression::OpCode::And); QVERIFY(e._opCodes[4].type == AnimExpression::OpCode::Or); } e = AnimExpression("(true || false) && true"); QVERIFY(e._opCodes.size() == 5); if (e._opCodes.size() == 5) { QVERIFY(e._opCodes[0].type == AnimExpression::OpCode::Bool); QVERIFY(e._opCodes[0].intVal == (int)true); QVERIFY(e._opCodes[1].type == AnimExpression::OpCode::Bool); QVERIFY(e._opCodes[1].intVal == (int)false); QVERIFY(e._opCodes[2].type == AnimExpression::OpCode::Or); QVERIFY(e._opCodes[3].type == AnimExpression::OpCode::Bool); QVERIFY(e._opCodes[3].intVal == (int)true); QVERIFY(e._opCodes[4].type == AnimExpression::OpCode::And); } e = AnimExpression("!(true || false) && true"); QVERIFY(e._opCodes.size() == 6); if (e._opCodes.size() == 6) { QVERIFY(e._opCodes[0].type == AnimExpression::OpCode::Bool); QVERIFY(e._opCodes[0].intVal == (int)true); QVERIFY(e._opCodes[1].type == AnimExpression::OpCode::Bool); QVERIFY(e._opCodes[1].intVal == (int)false); QVERIFY(e._opCodes[2].type == AnimExpression::OpCode::Or); QVERIFY(e._opCodes[3].type == AnimExpression::OpCode::Not); QVERIFY(e._opCodes[4].type == AnimExpression::OpCode::Bool); QVERIFY(e._opCodes[4].intVal == (int)true); QVERIFY(e._opCodes[5].type == AnimExpression::OpCode::And); } } #define TEST_BOOL_EXPR(EXPR) \ result = AnimExpression( #EXPR ).evaluate(vars); \ QVERIFY(result.type == AnimExpression::OpCode::Bool); \ QVERIFY(result.intVal == (int)(EXPR)) void AnimTests::testExpressionEvaluator() { auto vars = AnimVariantMap(); bool f = false; bool t = true; int ten = 10; int twenty = 20; float five = 5.0f; float fourty = 40.0f; vars.set("f", f); vars.set("t", t); vars.set("ten", ten); vars.set("twenty", twenty); vars.set("five", five); vars.set("forty", fourty); AnimExpression::OpCode result(AnimExpression::OpCode::Int); result = AnimExpression("10").evaluate(vars); QVERIFY(result.type == AnimExpression::OpCode::Int); QVERIFY(result.intVal == 10); result = AnimExpression("(10)").evaluate(vars); QVERIFY(result.type == AnimExpression::OpCode::Int); QVERIFY(result.intVal == 10); TEST_BOOL_EXPR(true); TEST_BOOL_EXPR(false); TEST_BOOL_EXPR(t); TEST_BOOL_EXPR(f); TEST_BOOL_EXPR(true || false); TEST_BOOL_EXPR(true || true); TEST_BOOL_EXPR(false || false); TEST_BOOL_EXPR(false || true); TEST_BOOL_EXPR(true && false); TEST_BOOL_EXPR(true && true); TEST_BOOL_EXPR(false && false); TEST_BOOL_EXPR(false && true); TEST_BOOL_EXPR(true || (false && true)); TEST_BOOL_EXPR(true || (false && false)); TEST_BOOL_EXPR(true || (true && true)); TEST_BOOL_EXPR(true || (true && false)); TEST_BOOL_EXPR(false || (false && true)); TEST_BOOL_EXPR(false || (false && false)); TEST_BOOL_EXPR(false || (true && true)); TEST_BOOL_EXPR(false || (true && false)); TEST_BOOL_EXPR((true && false) || true); TEST_BOOL_EXPR((true && false) || false); TEST_BOOL_EXPR((true && true) || true); TEST_BOOL_EXPR((true && true) || false); TEST_BOOL_EXPR((false && false) || true); TEST_BOOL_EXPR((false && false) || false); TEST_BOOL_EXPR((false && true) || true); TEST_BOOL_EXPR((false && true) || false); TEST_BOOL_EXPR(t || false); TEST_BOOL_EXPR(t || true); TEST_BOOL_EXPR(f || false); TEST_BOOL_EXPR(f || true); TEST_BOOL_EXPR(!true); TEST_BOOL_EXPR(!false); TEST_BOOL_EXPR(!true || true); TEST_BOOL_EXPR((!true && !false) || !true); TEST_BOOL_EXPR((!true && !false) || true); TEST_BOOL_EXPR((!true && false) || !true); TEST_BOOL_EXPR((!true && false) || true); TEST_BOOL_EXPR((true && !false) || !true); TEST_BOOL_EXPR((true && !false) || true); TEST_BOOL_EXPR((true && false) || !true); TEST_BOOL_EXPR((true && false) || true); TEST_BOOL_EXPR(!(true && f) || !t); TEST_BOOL_EXPR(!!!(t) && (!!f || true)); TEST_BOOL_EXPR(!(true && f) && true); }
34.821648
157
0.624691
MarkBrosche
b192c036d734938d90ec915503958f36131e0e29
746
hpp
C++
src/unisparks/layouts/pixelmap.hpp
azov/unisparks
5bf9adb5ef7bf6ac7bea3aaf2a75d3b124594b7e
[ "Apache-2.0" ]
null
null
null
src/unisparks/layouts/pixelmap.hpp
azov/unisparks
5bf9adb5ef7bf6ac7bea3aaf2a75d3b124594b7e
[ "Apache-2.0" ]
null
null
null
src/unisparks/layouts/pixelmap.hpp
azov/unisparks
5bf9adb5ef7bf6ac7bea3aaf2a75d3b124594b7e
[ "Apache-2.0" ]
null
null
null
#ifndef UNISPARKS_LAYOUTS_PIXELMAP_H #define UNISPARKS_LAYOUTS_PIXELMAP_H #include "unisparks/layout.hpp" #include "unisparks/util/math.hpp" namespace unisparks { class PixelMap : public Layout { public: PixelMap(size_t cnt, Point* pts) : PixelMap(cnt, pts, true) { } int pixelCount() const override { return count_; } Box bounds() const override { return bounds_; } Point at(int i) const override { return points_[i]; } protected: PixelMap(size_t cnt, Point* pts, bool calcb) : count_(cnt), points_(pts) { if (calcb) { bounds_ = calculateBounds(); } } Box bounds_; private: size_t count_; const Point* points_; }; } // namespace unisparks #endif /* UNISPARKS_LAYOUTS_PIXELMAP_H */
18.65
76
0.684987
azov
b198472286783670ae76102572fbcf75598882e7
171
cpp
C++
liblog/test/removeInvalidtest.cpp
qiu708/liblog
c7085dd059f065bedf45a401ff062215fc57b53f
[ "MIT" ]
null
null
null
liblog/test/removeInvalidtest.cpp
qiu708/liblog
c7085dd059f065bedf45a401ff062215fc57b53f
[ "MIT" ]
null
null
null
liblog/test/removeInvalidtest.cpp
qiu708/liblog
c7085dd059f065bedf45a401ff062215fc57b53f
[ "MIT" ]
null
null
null
// // Created by qiu on 2021/12/13. // #include<liblog/LogFile.h> int main() { liblog::LogFile f("/home/qiu/Desktop/log/log",600); f.removeInvalid(10*24*3600); }
15.545455
55
0.637427
qiu708
b19bdf174b8e51e6e986373802b5c6c291b22840
3,358
hpp
C++
Yannq/Hamiltonians/KitaevHexC24.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
Yannq/Hamiltonians/KitaevHexC24.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
Yannq/Hamiltonians/KitaevHexC24.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
#ifndef HAMILTONIANS_KITAEVHEXC24_HPP #define HAMILTONIANS_KITAEVHEXC24_HPP #include <Eigen/Eigen> #include <nlohmann/json.hpp> class KitaevHexC24 { private: static constexpr int N = 24; double Jx_; double Jy_; double Jz_; double hx_; public: KitaevHexC24(double J) : Jx_(J), Jy_(J), Jz_(J), hx_{} { } KitaevHexC24(double Jx, double Jy, double Jz) : Jx_(Jx), Jy_(Jy), Jz_(Jz), hx_{} { } KitaevHexC24(double J, double hx) : Jx_(J), Jy_(J), Jz_(J), hx_(hx) { } std::vector<std::pair<int,int> > xLinks() const { std::vector<std::pair<int,int> > res; //first row res.emplace_back(0,3); res.emplace_back(1,4); //second row res.emplace_back(5,9); res.emplace_back(6,10); res.emplace_back(7,11); //thrid row res.emplace_back(12,16); res.emplace_back(13,17); res.emplace_back(14,18); //forth row res.emplace_back(19,22); res.emplace_back(20,23); //between res.emplace_back(15,2); res.emplace_back(21,8); return res; } std::vector<std::pair<int,int> > yLinks() const { std::vector<std::pair<int,int> > res; //first row res.emplace_back(0,2); res.emplace_back(1,3); //second row res.emplace_back(5,8); res.emplace_back(6,9); res.emplace_back(7,10); //thrid row res.emplace_back(13,16); res.emplace_back(14,17); res.emplace_back(15,18); //forth row res.emplace_back(20,22); res.emplace_back(21,23); //between res.emplace_back(4,12); res.emplace_back(11,19); return res; } std::vector<std::pair<int,int> > zLinks() const { std::vector<std::pair<int,int> > res; res.emplace_back(2,5); res.emplace_back(3,6); res.emplace_back(4,7); res.emplace_back(8,12); res.emplace_back(9,13); res.emplace_back(10,14); res.emplace_back(11,15); res.emplace_back(16,19); res.emplace_back(17,20); res.emplace_back(18,21); res.emplace_back(11,15); res.emplace_back(0,22); res.emplace_back(1,23); return res; } nlohmann::json params() const { return nlohmann::json { {"name", "KITAEVHEXC24"}, {"Jx", Jx_}, {"Jy", Jy_}, {"Jz", Jz_}, {"hx", hx_}, }; } template<class State> typename State::Scalar operator()(const State& smp) const { typename State::Scalar s = 0.0; constexpr std::complex<double> I(0.,1.); for(auto &xx: xLinks()) { s += Jx_*smp.ratio(xx.first, xx.second); //xx } for(auto &yy: yLinks()) { int zzval = smp.sigmaAt(yy.first)*smp.sigmaAt(yy.second); s += -Jy_*zzval*smp.ratio(yy.first, yy.second); //yy } for(auto &zz: zLinks()) { int zzval = smp.sigmaAt(zz.first)*smp.sigmaAt(zz.second); s += Jz_*zzval; //yy } for(int n = 0; n < N; n++) { s += hx_*smp.ratio(n); } return s; } std::map<uint32_t, double> operator()(uint32_t col) const { std::map<uint32_t, double> m; for(auto &xx: xLinks()) { int t = (1 << xx.first) | (1 << xx.second); m[col ^ t] += Jx_; //xx } for(auto &yy: yLinks()) { int zzval = (1-2*int((col >> yy.first) & 1))*(1-2*int((col >> yy.second) & 1)); int t = (1 << yy.first) | (1 << yy.second); m[col ^ t] += -Jy_*zzval; //yy } for(auto &zz: zLinks()) { int zzval = (1-2*int((col >> zz.first) & 1))*(1-2*int((col >> zz.second) & 1)); m[col] += Jz_*zzval; //zz } for(int n = 0; n < N; n++) { m[col ^ (1<<n)] += hx_; } return m; } }; #endif//HAMILTONIANS_KITAEVHEXC24_HPP
19.637427
82
0.6081
cecri
b1a2ac30af70d4dfb0e578956784035fba4b9d05
237
hpp
C++
src/GameObject.hpp
mysterypaint/Hmm
d19da186083b2eead9c6f8953c447f6ec24da083
[ "MIT" ]
null
null
null
src/GameObject.hpp
mysterypaint/Hmm
d19da186083b2eead9c6f8953c447f6ec24da083
[ "MIT" ]
null
null
null
src/GameObject.hpp
mysterypaint/Hmm
d19da186083b2eead9c6f8953c447f6ec24da083
[ "MIT" ]
null
null
null
#pragma once #include "Game.hpp" #include "PHL.hpp" class GameObject { public: GameObject(int tex, int _x, int _y); ~GameObject(); void Step(); void Draw(); private: int x; int y; PHL_Surface objTexture; PHL_Rect srcRect; };
11.85
37
0.679325
mysterypaint
b1a5144beabeba521395c9bc28d740fc2f4b7eed
387
cpp
C++
src/Hord/Rule/State.cpp
komiga/hord
32be8ffb11bd74959c5cd5254e36d87f224b6f60
[ "MIT" ]
null
null
null
src/Hord/Rule/State.cpp
komiga/hord
32be8ffb11bd74959c5cd5254e36d87f224b6f60
[ "MIT" ]
null
null
null
src/Hord/Rule/State.cpp
komiga/hord
32be8ffb11bd74959c5cd5254e36d87f224b6f60
[ "MIT" ]
null
null
null
/** @copyright MIT license; see @ref index or the accompanying LICENSE file. */ #include <Hord/Rule/State.hpp> namespace Hord { namespace Rule { // class State implementation State::~State() noexcept = default; State::State() noexcept = default; State::State(State&&) noexcept = default; State& State::operator=(State&&) noexcept = default; } // namespace Rule } // namespace Hord
19.35
72
0.710594
komiga
b1a6a19204219f0f833690e1da76098eab53ec59
57
hpp
C++
include/inputHandler.hpp
Napam/tuna
d76407a763f46ff78ee1c5479e2a3b6b7f598980
[ "Apache-2.0" ]
null
null
null
include/inputHandler.hpp
Napam/tuna
d76407a763f46ff78ee1c5479e2a3b6b7f598980
[ "Apache-2.0" ]
1
2021-09-28T18:29:20.000Z
2021-09-28T18:29:20.000Z
include/inputHandler.hpp
Napam/Boids-SDL
d76407a763f46ff78ee1c5479e2a3b6b7f598980
[ "Apache-2.0" ]
null
null
null
#ifndef INPUT_HANDLER_H #define INPUT_HANDLER_H #endif
9.5
23
0.824561
Napam
b1a752c653fcb9c237eff6f9f88b9953d733d398
1,640
hpp
C++
libs/module/include/module.hpp
briancairl/snek
ebdd90ba2790bfcbf843c0eb52a13c7f212f8e8f
[ "MIT" ]
null
null
null
libs/module/include/module.hpp
briancairl/snek
ebdd90ba2790bfcbf843c0eb52a13c7f212f8e8f
[ "MIT" ]
null
null
null
libs/module/include/module.hpp
briancairl/snek
ebdd90ba2790bfcbf843c0eb52a13c7f212f8e8f
[ "MIT" ]
null
null
null
/** * @copyright 2022-present Brian Cairl * * @file module.hpp */ #pragma once // C++ Standard Library #include <string> #include <unordered_map> // Snek #include <snek/builder/fwd.hpp> #include <snek/config/fwd.hpp> namespace snek { /** * @brief Loads a collection of Routine implementations (a "module") from shared libraries * * Routines are loaded according to a manifest. The manifest will take the following structure: @verbatim { "my_routine" : { "path" : "libmymodule.so", "conf" : { "pi" : 3.1416, "cats" : 30 }, "create_fn" : "CreateRoutine", "loader_fn" : "CreateRoutineLoader" }, "my_other_routine" : { "path" : "test/module/libmodule.so", "conf" : { "dogs" : 1 }, "create_fn" : "CreateRoutine", "loader_fn" : "CreateRoutineLoader" } } @endverbatim * \n * <code>{"create_fn" : "CreateRoutine"}</code> and <code>{"loader_fn" : "CreateRoutineLoader"}</code> designate * the names of functions used to create Routine resource and a RoutineLoader resource, respectively. They * may required additional configuration parameters, which are specified through the <code>"conf"</code> * sub-structure. * * @param routine_lookup target lookup to add Routine plugins to * @param manifest configuration specifying how Routine plugin resources are to be loaded * * @throws anything RoutineLookup::add can throw when multiple routines with the same name are added to \c * routine_lookup */ void load_module(RoutineLookup& routine_lookup, const Config& manifest); } // namespace snek
27.79661
112
0.662195
briancairl
b1ad963f81d40174b1e125d529584cb24d137b8a
16,141
cpp
C++
js6chars.cpp
dubzzz/js6chars
33d23ce3d6ed51959acf961bccbfe2c0364e93c1
[ "MIT" ]
2
2017-02-21T22:43:10.000Z
2018-05-18T05:18:13.000Z
js6chars.cpp
dubzzz/js6chars
33d23ce3d6ed51959acf961bccbfe2c0364e93c1
[ "MIT" ]
1
2017-03-28T17:01:46.000Z
2017-03-28T17:01:46.000Z
js6chars.cpp
dubzzz/js6chars
33d23ce3d6ed51959acf961bccbfe2c0364e93c1
[ "MIT" ]
null
null
null
//#define _DEBUG #include <algorithm> #include <climits> #include <cstddef> #include <memory> #include <string> #include <vector> #ifdef _DEBUG #include <iostream> #include <typeinfo> #endif #include "js6chars.hpp" std::string char_repr(char value, bool* cannot_use); std::string str_repr(const char* str, bool* cannot_use); std::string str_repr(std::string const& in, bool* cannot_use); static std::string small_number_repr(int value) { return value == 0 ? "+[]" : value == 1 ? "+!+[]" : value == 2 ? "!+[]+!+[]" : "!+[]+" + number_repr(value -1); } static std::string number_repr_helper(int value) { if (value < 10) return small_number_repr(value) + "+[]"; return number_repr_helper(value/10) + "+(" + small_number_repr(value%10) + ")"; } std::string number_repr(int value) { if (value < 0) { return std::string("+(") + char_repr('-') + "+(" + number_repr_helper(-value) + "))"; } return value < 10 ? small_number_repr(value) : std::string("+(") + number_repr_helper(value) + ")"; } namespace { template <std::size_t N> std::string from_known(char value, const char (&real_str)[N], std::string&& generated) { std::string shortest_match; char const* it = std::find(std::begin(real_str), std::end(real_str), value); for ( ; it != std::end(real_str) ; it = std::find(std::next(it), std::end(real_str), value)) { std::string match = "(" + generated + "+[])" + "[" + number_repr((int)(it - real_str)) + "]"; if (shortest_match.empty() || shortest_match.size() > match.size()) { shortest_match = match; } } return shortest_match; } } struct Generator { virtual std::string operator() (char, bool*) = 0; }; // 0123456789 should be omitted from require variable as trivally constructibles struct NumberGenerator : Generator { static constexpr const char* generate = "0123456789"; static constexpr const char* require = ""; std::string operator() (char value, bool* /*cannot_use*/) override { return number_repr(value-'0') + "+[]"; } }; struct UndefinedGenerator : Generator { static constexpr const char* generate = "undefi"; static constexpr const char* require = ""; std::string operator() (char value, bool* /*cannot_use*/) override { return from_known(value, "undefined", "[][[]]"); } }; struct CommaGenerator : Generator { static constexpr const char* generate = ","; static constexpr const char* require = "conat"; std::string operator() (char /*value*/, bool* cannot_use) override { std::string data = str_repr("concat", cannot_use); return data.empty() ? "" : "([[]][" + data + "](+[])+[])[+[]]"; } }; struct NanGenerator : Generator { static constexpr const char* generate = "Na"; static constexpr const char* require = "u"; std::string operator() (char value, bool* cannot_use) override { return from_known(value, "NaN", "+" + char_repr('u', cannot_use)); } }; struct SmallerNanGenerator : Generator { static constexpr const char* generate = "Na"; static constexpr const char* require = ""; std::string operator() (char value, bool* /*cannot_use*/) override { return from_known(value, "NaN", "+(![]+[])"); } }; struct SmallerNanBisGenerator : Generator { static constexpr const char* generate = "Na"; static constexpr const char* require = ""; std::string operator() (char value, bool* /*cannot_use*/) override { return from_known(value, "NaN", "+[][+[]]"); } }; struct SmallerNanTerGenerator : Generator { static constexpr const char* generate = "Na"; static constexpr const char* require = ""; std::string operator() (char value, bool* /*cannot_use*/) override { return from_known(value, "NaN", "+[![]]"); } }; struct PlusGenerator : Generator { static constexpr const char* generate = "+"; static constexpr const char* require = "e"; std::string operator() (char value, bool* cannot_use) override { std::string data = str_repr("1e30", cannot_use); return data.empty() ? "" : from_known(value, "1e+30", "+(" + data + ")"); } }; struct MinusGenerator : Generator { static constexpr const char* generate = "-"; static constexpr const char* require = "indexOf"; std::string operator() (char /*value*/, bool* cannot_use) override { std::string data = str_repr("indexOf", cannot_use); return data.empty() ? "" : "([][" + data + "]([])+[])[+[]]"; } }; struct FindGenerator : Generator { static constexpr const char* generate = "ucto ()"; static constexpr const char* require = "find"; std::string operator() (char value, bool* cannot_use) override { std::string data = str_repr("find", cannot_use); return data.empty() ? "" : from_known(value, "function find()", "[][" + data + "]"); } }; struct TrueGenerator : Generator { static constexpr const char* generate = "true"; static constexpr const char* require = ""; std::string operator() (char value, bool* /*cannot_use*/) override { return from_known(value, "true", "!![]"); } }; struct FalseGenerator : Generator { static constexpr const char* generate = "false"; static constexpr const char* require = ""; std::string operator() (char value, bool* /*cannot_use*/) override { return from_known(value, "false", "![]"); } }; struct InfinityGenerator : Generator { static constexpr const char* generate = "Infity"; static constexpr const char* require = "e"; std::string operator() (char value, bool* cannot_use) override { std::string data = str_repr("1e1000", cannot_use); return data.empty() ? "" : from_known(value, "Infinity", "+(" + data + ")"); } }; struct SquareBracketGenerator : Generator { static constexpr const char* generate = "[objct AayIa]"; static constexpr const char* require = "entris"; std::string operator() (char value, bool* cannot_use) override { std::string data = str_repr("entries", cannot_use); return data.empty() ? "" : from_known(value, "[object Array Iterator]", "[][" + data + "]()"); } }; struct ClosedCurlyBracedGenerator : Generator {//console.log(([].find+[]).split([]+[]).sort().reverse()[0]); static constexpr const char* generate = "}"; static constexpr const char* require = "findspltrev"; std::string operator() (char /*value*/, bool* cannot_use) override { std::string data = str_repr("find", cannot_use); std::string split_method = str_repr("split", cannot_use); std::string reverse_method = str_repr("reverse", cannot_use); return data.empty() ? "" : "([][" + data + "]+[])[" + split_method + "]([]+[])[" + reverse_method + "]()[+[]]"; } }; struct ClassArrayGenerator : Generator { static constexpr const char* generate = "fi Aay(){"; static constexpr const char* require = "constru"; std::string operator() (char value, bool* cannot_use) override { std::string data = str_repr("constructor", cannot_use); return data.empty() ? "" : from_known(value, "function Array() {", "[][" + data + "]"); } }; struct ClassBooleanGenerator : Generator { static constexpr const char* generate = "fi Blea(){"; static constexpr const char* require = "constru"; std::string operator() (char value, bool* cannot_use) override { std::string data = str_repr("constructor", cannot_use); return data.empty() ? "" : from_known(value, "function Boolean() {", "(![])[" + data + "]"); } }; struct ClassNumberGenerator : Generator { static constexpr const char* generate = "fi Nmbe(){"; static constexpr const char* require = "constru"; std::string operator() (char value, bool* cannot_use) override { std::string data = str_repr("constructor", cannot_use); return data.empty() ? "" : from_known(value, "function Number() {", "(+[])[" + data + "]"); } }; struct ClassStringGenerator : Generator { static constexpr const char* generate = "fi Sg(){"; static constexpr const char* require = "constru"; std::string operator() (char value, bool* cannot_use) override { std::string data = str_repr("constructor", cannot_use); return data.empty() ? "" : from_known(value, "function String() {", "([]+[])[" + data + "]"); } }; struct ClassFunctionGenerator : Generator { static constexpr const char* generate = " F(){"; static constexpr const char* require = "construfid"; std::string operator() (char value, bool* cannot_use) override { std::string method_label = str_repr("find", cannot_use); std::string constructor = str_repr("constructor", cannot_use); return method_label.empty() || constructor.empty() ? "" : from_known(value, "function Function() {", "[][" + method_label + "][" + constructor + "]"); } }; struct NumberInBaseGenerator : Generator { static constexpr const char* generate = "abcdefhjklmpqsuvwxyz"; static constexpr const char* require = "toSring"; std::string operator() (char value, bool* cannot_use) override { int base = 11 + value -'a'; if (base <= 30) { // max is 36 base = ((int)(base/10) +1) * 10; } std::string data = str_repr("toString", cannot_use); return data.empty() ? "" : "(" + number_repr(10 + value -'a') + ")[" + data + "](" + number_repr(base) + ")"; } }; struct CGenerator : Generator { static constexpr const char* generate = "C"; static constexpr const char* require = "findconstructorreturn atobN"; std::string operator() (char, bool* cannot_use) override { std::string method_label = str_repr("find", cannot_use); std::string constructor = str_repr("constructor", cannot_use); std::string running_code = str_repr("return atob", cannot_use); std::string parameter = str_repr("20N", cannot_use); return method_label.empty() || constructor.empty() || running_code.empty() || parameter.empty() ? "" : "[][" + method_label + "][" + constructor + "](" + running_code + ")()(" + parameter + ")[" + number_repr(1) + "]"; } }; struct AllGenerator : Generator { static constexpr const char* require = "construfmChade";// and also ! std::string operator() (char value, bool* cannot_use) override { std::string constructor = str_repr("constructor", cannot_use); std::string method_charcode = str_repr("fromCharCode", cannot_use); return constructor.empty() || method_charcode.empty() ? "" : "([]+[])[" + constructor + "][" + method_charcode + "](" + number_repr((int)value) + ")"; } }; template <class Gen, class Tree> void push_dependency(Tree&& tree, char c) { constexpr const char* str = Gen::require; #ifdef _DEBUG std::cout << " (" << ((int)c) << ")'" << c << "' requires \"" << str << "\"" << std::endl; #endif tree[c - CHAR_MIN].emplace_back(str, std::make_unique<Gen>()); } template <class Gen, class Tree> void push_dependencies(Tree&& tree) { for (auto it = Gen::generate ; !!*it ; ++it) { push_dependency<Gen>(tree, *it); } } auto build_dependency_tree() { // for each char we declare the list of all the available Generator able to build it // give nthe definition of required entries // eg.: // '[' -> [ (find), call [].find ] std::vector< std::vector< std::pair<std::string, std::unique_ptr<Generator>> > > tree(256); #ifdef _DEBUG std::cout << "Start build_dependency_tree" << std::endl; #endif push_dependencies<NumberGenerator>(tree); push_dependencies<UndefinedGenerator>(tree); push_dependencies<CommaGenerator>(tree); push_dependencies<NanGenerator>(tree); push_dependencies<SmallerNanGenerator>(tree); push_dependencies<SmallerNanBisGenerator>(tree); push_dependencies<PlusGenerator>(tree); push_dependencies<MinusGenerator>(tree); push_dependencies<FindGenerator>(tree); push_dependencies<TrueGenerator>(tree); push_dependencies<FalseGenerator>(tree); push_dependencies<InfinityGenerator>(tree); push_dependencies<SquareBracketGenerator>(tree); push_dependencies<ClosedCurlyBracedGenerator>(tree); push_dependencies<ClassArrayGenerator>(tree); push_dependencies<ClassBooleanGenerator>(tree); push_dependencies<ClassNumberGenerator>(tree); push_dependencies<ClassStringGenerator>(tree); push_dependencies<ClassFunctionGenerator>(tree); push_dependencies<NumberInBaseGenerator>(tree); push_dependencies<CGenerator>(tree); push_dependencies<NumberInBaseGenerator>(tree); push_dependencies<ClassNumberGenerator>(tree); push_dependencies<ClassStringGenerator>(tree); push_dependencies<ClassFunctionGenerator>(tree); push_dependencies<NumberInBaseGenerator>(tree); push_dependencies<CGenerator>(tree); for (int c = (int)CHAR_MIN ; c <= (int)CHAR_MAX ; ++c) { unsigned idx = c - CHAR_MIN; if (tree[idx].empty()) { push_dependency<AllGenerator>(tree, (char)c); } } #ifdef _DEBUG std::cout << "End build_dependency_tree" << std::endl; #endif return tree; } std::string char_repr(char value, bool* cannot_use) { static const auto tree = build_dependency_tree(); #ifdef _DEBUG unsigned iter_id = std::count(cannot_use, cannot_use+256, true); for (unsigned i {} ; i != iter_id ; ++i) { std::cout << " "; } std::cout << "Generating (" << ((int)value) << ")'" << value << "'" << std::endl; #endif auto const& choices = tree[value - CHAR_MIN]; #ifdef _DEBUG for (unsigned i {} ; i != iter_id ; ++i) { std::cout << " "; } std::cout << " # " << choices.size() << " candidates" << std::endl; #endif // Keep only generators that can be used (do no require stuff being computed) std::vector<Generator*> generators; for (auto const& choice : choices) { std::string const& require = choice.first; if (std::find_if(require.begin(), require.end(), [cannot_use](auto c) { return cannot_use[c - CHAR_MIN]; }) == require.end()) { generators.push_back(choice.second.get()); } } #ifdef _DEBUG for (unsigned i {} ; i != iter_id ; ++i) { std::cout << " "; } std::cout << " # " << generators.size() << " selected" << std::endl; #endif // Find the best match cannot_use[value - CHAR_MIN] = true; std::string best_match; for (auto gen : generators) { #ifdef _DEBUG for (unsigned i {} ; i != iter_id ; ++i) { std::cout << " "; } std::cout << " :using generator <" << typeid(*gen).name() << ">" << std::endl; #endif std::string match = gen->operator()(value, cannot_use); #ifdef _DEBUG for (unsigned i {} ; i != iter_id ; ++i) { std::cout << " "; } std::cout << " :(" << ((int)value) << ")'" << value << "': <" << typeid(*gen).name() << "> : " << match << std::endl; #endif if (best_match.empty() || (best_match.size() > match.size() && ! match.empty())) { best_match = match; } } cannot_use[value - CHAR_MIN] = false; return best_match; } std::string char_repr(char value) { bool tab[CHAR_MAX-CHAR_MIN] = { 0 }; std::fill(std::begin(tab), std::end(tab), false); return char_repr(value, tab); } std::string str_repr(const char* str, bool* cannot_use) { std::string out {}; for (auto it = str ; *it ; ++it) { if (cannot_use[*it - CHAR_MIN]) { return out; } } for (auto it = str ; *it ; ++it) { auto forchar = char_repr(*it, cannot_use); if (forchar.empty()) { return ""; } if (it != str) { out += '+'; if (forchar[forchar.size() -3] == '+' && forchar[forchar.size() -2] == '[' && forchar[forchar.size() -1] == ']') { forchar = forchar.substr(0, forchar.size() -3); } if (forchar[0] == '+' || (forchar.size() >= 2 && forchar[0] == '!' && forchar[1] == '+')) { out += '('; out += forchar; out += ')'; } else { out += forchar; } } else { out += forchar; } } return out; } std::string str_repr(std::string const& in, bool* cannot_use) { return str_repr(in.c_str(), cannot_use); } std::string str_repr(const char* str) { bool tab[CHAR_MAX-CHAR_MIN] = { 0 }; std::fill(std::begin(tab), std::end(tab), false); return str_repr(str, tab); } std::string str_repr(std::string const& in) { return str_repr(in.c_str()); } std::string run_command(const char* str) { return std::string("[][") + str_repr("constructor") + "][" + str_repr("constructor") + "](" + str_repr(str) + ")()"; } std::string run_command(std::string const& in) { return run_command(in.c_str()); }
36.851598
156
0.640295
dubzzz
b1b285fb4549d82a79c9deb183109c485f6c8611
819
cpp
C++
android-31/android/view/accessibility/AccessibilityNodeInfo_ExtraRenderingInfo.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/view/accessibility/AccessibilityNodeInfo_ExtraRenderingInfo.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-31/android/view/accessibility/AccessibilityNodeInfo_ExtraRenderingInfo.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../util/Size.hpp" #include "./AccessibilityNodeInfo_ExtraRenderingInfo.hpp" namespace android::view::accessibility { // Fields // QJniObject forward AccessibilityNodeInfo_ExtraRenderingInfo::AccessibilityNodeInfo_ExtraRenderingInfo(QJniObject obj) : JObject(obj) {} // Constructors // Methods android::util::Size AccessibilityNodeInfo_ExtraRenderingInfo::getLayoutSize() const { return callObjectMethod( "getLayoutSize", "()Landroid/util/Size;" ); } jfloat AccessibilityNodeInfo_ExtraRenderingInfo::getTextSizeInPx() const { return callMethod<jfloat>( "getTextSizeInPx", "()F" ); } jint AccessibilityNodeInfo_ExtraRenderingInfo::getTextSizeUnit() const { return callMethod<jint>( "getTextSizeUnit", "()I" ); } } // namespace android::view::accessibility
22.135135
117
0.741148
YJBeetle
b1b776b174a42c35038442c68fb191d3fccd00fe
2,628
hpp
C++
common_types.hpp
milasudril/strint
a7f26ca3c89e0f15d195337c60b9ee389b92b549
[ "MIT" ]
null
null
null
common_types.hpp
milasudril/strint
a7f26ca3c89e0f15d195337c60b9ee389b92b549
[ "MIT" ]
null
null
null
common_types.hpp
milasudril/strint
a7f26ca3c89e0f15d195337c60b9ee389b92b549
[ "MIT" ]
null
null
null
//@ {"targets":[{"name":"common_types.hpp","type":"include"}]} #ifndef STRINT_COMMON_TYPES_HPP #define STRINT_COMMON_TYPES_HPP #include "integer.hpp" #include <climits> #include <cstdint> namespace Strint { enum class IntSize:int { Smallest = CHAR_BIT ,Short = CHAR_BIT * sizeof(short) ,Natural = CHAR_BIT * sizeof(int) ,Long = CHAR_BIT * sizeof(long) ,Pointer = CHAR_BIT * sizeof(void*) ,Largest = CHAR_BIT * sizeof(intmax_t) }; enum class Signedness:int{Signed,Unsigned}; template<int N,Signedness s> struct BitsToIntType; template<> struct BitsToIntType<8,Signedness::Signed> {typedef int8_t type;}; template<> struct BitsToIntType<16,Signedness::Signed> {typedef int16_t type;}; template<> struct BitsToIntType<32,Signedness::Signed> {typedef int32_t type;}; template<> struct BitsToIntType<64,Signedness::Signed> {typedef int64_t type;}; template<> struct BitsToIntType<8,Signedness::Unsigned> {typedef uint8_t type;}; template<> struct BitsToIntType<16,Signedness::Unsigned> {typedef uint16_t type;}; template<> struct BitsToIntType<32,Signedness::Unsigned> {typedef uint32_t type;}; template<> struct BitsToIntType<64,Signedness::Unsigned> {typedef uint64_t type;}; template<int N, Signedness s=Signedness::Signed> using SizedInteger = Integer<typename BitsToIntType<N, s>::type>; using Tiny = SizedInteger<static_cast<int>(IntSize::Smallest)>; using Short = SizedInteger<static_cast<int>(IntSize::Short)>; using Int = SizedInteger<static_cast<int>(IntSize::Natural)>; using Long = SizedInteger<static_cast<int>(IntSize::Long)>; using PtrDiff = SizedInteger<static_cast<int>(IntSize::Pointer)>; using Large = SizedInteger<static_cast<int>(IntSize::Largest)>; using UTiny = SizedInteger<static_cast<int>(IntSize::Smallest), Signedness::Unsigned>; using UShort = SizedInteger<static_cast<int>(IntSize::Short), Signedness::Unsigned>; using UInt = SizedInteger<static_cast<int>(IntSize::Natural), Signedness::Unsigned>; using ULong = SizedInteger<static_cast<int>(IntSize::Long), Signedness::Unsigned>; using Size = SizedInteger<static_cast<int>(IntSize::Pointer), Signedness::Unsigned>; using ULarge = SizedInteger<static_cast<int>(IntSize::Largest), Signedness::Unsigned>; using Int8 = SizedInteger<8>; using Int16 = SizedInteger<16>; using Int32 = SizedInteger<32>; using Int64 = SizedInteger<64>; using UInt8 = SizedInteger<8, Signedness::Unsigned>; using UInt16 = SizedInteger<16, Signedness::Unsigned>; using UInt32 = SizedInteger<32, Signedness::Unsigned>; using UInt64 = SizedInteger<64, Signedness::Unsigned>; } #endif
29.863636
87
0.746195
milasudril
b1baaf64557c922808099ef3543ae816a91ad419
9,709
cpp
C++
Samples/PosPrinter/cpp/Scenario1_ReceiptPrinter.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
2,504
2019-05-07T06:56:42.000Z
2022-03-31T19:37:59.000Z
Samples/PosPrinter/cpp/Scenario1_ReceiptPrinter.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
314
2019-05-08T16:56:30.000Z
2022-03-21T07:13:45.000Z
Samples/PosPrinter/cpp/Scenario1_ReceiptPrinter.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
2,219
2019-05-07T00:47:26.000Z
2022-03-30T21:12:31.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "Scenario1_ReceiptPrinter.xaml.h" using namespace SDKTemplate; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; using namespace Concurrency; using namespace Windows::Devices::PointOfService; using namespace Windows::UI::Core; using namespace Windows::Devices::Enumeration; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 Scenario1_ReceiptPrinter::Scenario1_ReceiptPrinter() : rootPage(MainPage::Current) { InitializeComponent(); ResetTheScenarioState(); } // //Creates multiple tasks, first to find a receipt printer, then to claim the printer and then to enable and add releasedevicerequested event handler. // void Scenario1_ReceiptPrinter::FindClaimEnable_Click(Platform::Object^ sender, RoutedEventArgs^ e) { create_task(FindReceiptPrinter()).then([this]() { if (printer != nullptr) { create_task(ClaimPrinter()).then([this](void) { if (claimedPrinter) { create_task(EnableAsync()).then([this](void) { releaseDeviceRequestedToken = claimedPrinter->ReleaseDeviceRequested::add (ref new TypedEventHandler<ClaimedPosPrinter^, PosPrinterReleaseDeviceRequestedEventArgs^ >(this, &Scenario1_ReceiptPrinter::ClaimedPrinter_ReleaseDeviceRequested)); }); } }); } }); } // //Default checkbox selection makes it an important transaction, hence we do not release claim when we get a release devicerequested event. // void Scenario1_ReceiptPrinter::ClaimedPrinter_ReleaseDeviceRequested(ClaimedPosPrinter ^claimedInstance, PosPrinterReleaseDeviceRequestedEventArgs ^args) { if (IsAnImportantTransaction) { create_task(claimedInstance->RetainDeviceAsync()); } else { ResetTheScenarioState(); } } // //Prints the line that is in the textbox. // void Scenario1_ReceiptPrinter::PrintLine_Click(Platform::Object ^sender, RoutedEventArgs e) { if (claimedPrinter != nullptr) { ReceiptPrintJob^ job = claimedPrinter->Receipt->CreateJob(); job->PrintLine(txtPrintLine->Text); create_task(job->ExecuteAsync()).then([this](bool status) { if (status) { rootPage->NotifyUser("Printed line", NotifyType::StatusMessage); } else { rootPage->NotifyUser("Could not Print line", NotifyType::ErrorMessage); } }); } else { rootPage->NotifyUser("Could not Print line. No claimed printer found.", NotifyType::ErrorMessage); } } void Scenario1_ReceiptPrinter::PrintReceipt_Click(Platform::Object ^sender, RoutedEventArgs e) { rootPage->NotifyUser("Trying to Print Receipt", NotifyType::StatusMessage); PrintReceipt(); } void Scenario1_ReceiptPrinter::EndScenario_Click(Platform::Object ^sender, RoutedEventArgs e) { ResetTheScenarioState(); rootPage->NotifyUser("Disconnected Printer", NotifyType::StatusMessage); } // //Actual claim method task that claims the printer asynchronously // task<void> Scenario1_ReceiptPrinter::ClaimPrinter() { if (claimedPrinter == nullptr) { return create_task(printer->ClaimPrinterAsync()).then([this](ClaimedPosPrinter^ _claimedPrinter) { this->claimedPrinter = _claimedPrinter; if (claimedPrinter != nullptr) { rootPage->NotifyUser("Claimed Printer", NotifyType::StatusMessage); } else { rootPage->NotifyUser("Claim Printer failed", NotifyType::ErrorMessage); } }); } return task_from_result(); } task<void> Scenario1_ReceiptPrinter::EnableAsync() { if (claimedPrinter) { return create_task(claimedPrinter->EnableAsync()).then([this](bool) { rootPage->NotifyUser("Enabled printer.", NotifyType::StatusMessage); }); } else { rootPage->NotifyUser("Error: Printer not claimed anymore to enable.", NotifyType::ErrorMessage); return task_from_result(); } } // //Prints a sample receipt. // void Scenario1_ReceiptPrinter::PrintReceipt() { if (printer != nullptr && claimedPrinter != nullptr) { String^ receiptString = "======================\n" + "| Sample Header |\n" + "======================\n" + "Item Price\n" + "----------------------\n" + "Books 10.40\n" + "Games 9.60\n" + "----------------------\n" + "Total----------- 20.00\n"; ReceiptPrintJob^ merchantJob = claimedPrinter->Receipt->CreateJob(); String^ merchantFooter = GetMerchantFooter(); PrintLineFeedAndCutPaper(merchantJob, receiptString + merchantFooter); ReceiptPrintJob^ customerJob = claimedPrinter->Receipt->CreateJob(); String^ customerFooter = GetCustomerFooter(); PrintLineFeedAndCutPaper(customerJob, receiptString + customerFooter); create_task(merchantJob->ExecuteAsync()).then([this, customerJob](bool) { rootPage->NotifyUser("Printed merchant receipt.", NotifyType::StatusMessage); create_task(customerJob->ExecuteAsync()).then([this](bool) { rootPage->NotifyUser("Printed customer receipt.", NotifyType::StatusMessage); }); }); } else { rootPage->NotifyUser("Must find and claim printer before printing.", NotifyType::ErrorMessage); } } Platform::String^ Scenario1_ReceiptPrinter::GetMerchantFooter() { return "\n" + "______________________\n" + "Tip\n" + "\n" + "______________________\n" + "Signature\n" + "\n" + "Merchant Copy\n"; } Platform::String^ Scenario1_ReceiptPrinter::GetCustomerFooter() { return "\n" + "______________________\n" + "Tip\n" + "\n" + "Customer Copy\n"; } // Cut the paper after printing enough blank lines to clear the paper cutter. void Scenario1_ReceiptPrinter::PrintLineFeedAndCutPaper(ReceiptPrintJob^ job, Platform::String^ receipt) { if (printer != nullptr && claimedPrinter != nullptr) { // Passing a multi-line string to the Print method results in // smoother paper feeding than sending multiple single-line strings // to PrintLine. Platform::String^ feedString = ""; for (unsigned int n = 0; n < claimedPrinter->Receipt->LinesToPaperCut; n++) { feedString += "\n"; } job->Print(receipt + feedString); if (printer->Capabilities->Receipt->CanCutPaper) { job->CutPaper(); } } } task<void> Scenario1_ReceiptPrinter::FindReceiptPrinter() { if (printer == nullptr) { rootPage->NotifyUser("Finding printer", NotifyType::StatusMessage); return DeviceHelpers::GetFirstReceiptPrinterAsync().then([this](PosPrinter^ _printer) { printer = _printer; if (printer != nullptr) { rootPage->NotifyUser("Got Printer with Device Id : " + printer->DeviceId, NotifyType::StatusMessage); } else { rootPage->NotifyUser("Could not get printer.", NotifyType::ErrorMessage); } }); } return task_from_result(); } // //Remove event handler and delete claimed instance. // void Scenario1_ReceiptPrinter::ResetTheScenarioState() { if (claimedPrinter != nullptr) { claimedPrinter->ReleaseDeviceRequested::remove(releaseDeviceRequestedToken); delete claimedPrinter; claimedPrinter = nullptr; } if (printer != nullptr) { delete printer; printer = nullptr; } } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> void Scenario1_ReceiptPrinter::OnNavigatedTo(NavigationEventArgs^ e) { ResetTheScenarioState(); } /// <summary> /// Invoked when this page is no longer displayed. /// </summary> /// <param name="e"></param> void Scenario1_ReceiptPrinter::OnNavigatedFrom(NavigationEventArgs^ e) { ResetTheScenarioState(); }
31.522727
190
0.604079
dujianxin
04d9e48a170099b714c2f35a7c751d66557da2ef
4,671
cpp
C++
ql/experimental/basismodels/fxfwdratehelper.cpp
sschlenkrich/quantlib
ff39ad2cd03d06d185044976b2e26ce34dca470c
[ "BSD-3-Clause" ]
null
null
null
ql/experimental/basismodels/fxfwdratehelper.cpp
sschlenkrich/quantlib
ff39ad2cd03d06d185044976b2e26ce34dca470c
[ "BSD-3-Clause" ]
17
2020-11-23T07:24:16.000Z
2022-03-28T10:29:06.000Z
ql/experimental/basismodels/fxfwdratehelper.cpp
sschlenkrich/quantlib
ff39ad2cd03d06d185044976b2e26ce34dca470c
[ "BSD-3-Clause" ]
7
2017-04-24T08:28:43.000Z
2022-03-15T08:59:54.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2016 Andre Miemiec This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ #include <ql/experimental/basismodels/fxfwdratehelper.hpp> #include <ql/quote.hpp> #include <ql/currency.hpp> #include <ql/cashflows/cashflows.hpp> namespace QuantLib { namespace FxFwdRateHelperDummyNamespace { void no_deletion(YieldTermStructure*) {} } FxFwdRateHelper::FxFwdRateHelper( Currency baseCurrency, Currency counterCurrency, Rate fxSpot, Natural spotLag, Calendar spotLagCal, BusinessDayConvention spotLagConv, Period swapTerm, Handle<Quote> points, Real unit, Handle<YieldTermStructure> baseCcyDiscTermStructureHandle, Handle<YieldTermStructure> cntrCcyDiscTermStructureHandle, BootstrapType bootstrapBaseOrCounter) : RelativeDateRateHelper(points), baseCurrency_(baseCurrency), counterCurrency_(counterCurrency), fxSpot_(fxSpot), spotLag_(spotLag), spotLagCalendar_(spotLagCal), spotLagConvention_(spotLagConv), swapTerm_(swapTerm), unit_(unit), baseCcyDiscTermStructureHandle_(baseCcyDiscTermStructureHandle), cntrCcyDiscTermStructureHandle_(cntrCcyDiscTermStructureHandle), bootstrapBaseOrCounter_(bootstrapBaseOrCounter) { QL_REQUIRE( (baseCurrency_ != counterCurrency_),"Currencies should differ!"); registerWith(baseCcyDiscTermStructureHandle_); registerWith(cntrCcyDiscTermStructureHandle_); initializeDates(); } void FxFwdRateHelper::initializeDates() { Date today = Settings::instance().evaluationDate(); Date effectiveDate = spotLagCalendar_.advance(today,spotLag_,Days,spotLagConvention_,false); Date terminationDate = effectiveDate + swapTerm_; earliestDate_ = effectiveDate; latestDate_ = spotLagCalendar_.adjust(terminationDate,spotLagConvention_); } void FxFwdRateHelper::setTermStructure(YieldTermStructure* t) { // do not set the relinkable handle as an observer - // force recalculation when needed bool observer = false; ext::shared_ptr<YieldTermStructure> temp(t, FxFwdRateHelperDummyNamespace::no_deletion); if(bootstrapBaseOrCounter_ == FxFwdRateHelper::Base){ cntrCcyDiscRelinkableHandle_.linkTo(*cntrCcyDiscTermStructureHandle_, observer); baseCcyDiscRelinkableHandle_.linkTo(temp, observer); } else { cntrCcyDiscRelinkableHandle_.linkTo(temp, observer); baseCcyDiscRelinkableHandle_.linkTo(*baseCcyDiscTermStructureHandle_, observer); } RelativeDateRateHelper::setTermStructure(t); } Real FxFwdRateHelper::impliedQuote() const { //discount factors at maturity Real baseCcyDiscountT_ = baseCcyDiscRelinkableHandle_->discount(latestDate_); Real cntrCcyDiscountT_ = cntrCcyDiscRelinkableHandle_->discount(latestDate_); //discount factors at spot Real baseCcyDiscountS_ = baseCcyDiscRelinkableHandle_->discount(earliestDate_); Real cntrCcyDiscountS_ = cntrCcyDiscRelinkableHandle_->discount(earliestDate_); Real impicitQuote = 0.0; impicitQuote = unit_*fxSpot_*(baseCcyDiscountT_/cntrCcyDiscountT_*cntrCcyDiscountS_/baseCcyDiscountS_ - 1.0); return impicitQuote; } void FxFwdRateHelper::accept(AcyclicVisitor& v) { Visitor<FxFwdRateHelper>* v1 = dynamic_cast<Visitor<FxFwdRateHelper>*>(&v); if (v1 != 0) v1->visit(*this); else RateHelper::accept(v); } }
38.925
136
0.665168
sschlenkrich
04de5ff46b49034da29bceabe7f3605a2ac177ff
1,713
cc
C++
squid/squid3-3.3.8.spaceify/src/tests/stub_icp.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-01-20T15:25:34.000Z
2017-12-20T06:47:42.000Z
squid/squid3-3.3.8.spaceify/src/tests/stub_icp.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-05-15T09:32:55.000Z
2016-02-18T13:43:31.000Z
squid/squid3-3.3.8.spaceify/src/tests/stub_icp.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
null
null
null
#include "squid.h" #include "comm/Connection.h" #include "ICP.h" #include "icp_opcode.h" #define STUB_API "icp_*.cc" #include "tests/STUB.h" #ifdef __cplusplus _icp_common_t::_icp_common_t() STUB _icp_common_t::_icp_common_t(char *buf, unsigned int len) STUB void _icp_common_t::handleReply(char *buf, Ip::Address &from) STUB _icp_common_t *_icp_common_t::createMessage(icp_opcode opcode, int flags, const char *url, int reqnum, int pad) STUB_RETVAL(NULL) icp_opcode _icp_common_t::getOpCode() const STUB_RETVAL(ICP_INVALID) ICPState::ICPState(icp_common_t &aHeader, HttpRequest *aRequest) STUB ICPState::~ICPState() STUB #endif Comm::ConnectionPointer icpIncomingConn; Comm::ConnectionPointer icpOutgoingConn; Ip::Address theIcpPublicHostID; HttpRequest* icpGetRequest(char *url, int reqnum, int fd, Ip::Address &from) STUB_RETVAL(NULL) bool icpAccessAllowed(Ip::Address &from, HttpRequest * icp_request) STUB_RETVAL(false) void icpCreateAndSend(icp_opcode, int flags, char const *url, int reqnum, int pad, int fd, const Ip::Address &from) STUB icp_opcode icpGetCommonOpcode() STUB_RETVAL(ICP_INVALID) int icpUdpSend(int, const Ip::Address &, icp_common_t *, log_type, int) STUB_RETVAL(0) log_type icpLogFromICPCode(icp_opcode opcode) STUB_RETVAL(LOG_TAG_NONE) void icpDenyAccess(Ip::Address &from, char *url, int reqnum, int fd) STUB void icpHandleIcpV3(int, Ip::Address &, char *, int) STUB int icpCheckUdpHit(StoreEntry *, HttpRequest * request) STUB_RETVAL(0) void icpConnectionsOpen(void) STUB void icpConnectionShutdown(void) STUB void icpConnectionClose(void) STUB int icpSetCacheKey(const cache_key * key) STUB_RETVAL(0) const cache_key *icpGetCacheKey(const char *url, int reqnum) STUB_RETVAL(NULL)
46.297297
129
0.798015
spaceify
04e14169876e30374d8279e8139c509bdc51e3a1
13,945
hpp
C++
2d/extra/TestCoordinatesR2.hpp
danston/gbc
0cb1ae062919b053edc1558bdf41757460703eca
[ "MIT" ]
16
2016-12-06T10:35:46.000Z
2022-01-19T01:20:56.000Z
2d/extra/TestCoordinatesR2.hpp
danston/gbc
0cb1ae062919b053edc1558bdf41757460703eca
[ "MIT" ]
1
2020-02-11T10:45:30.000Z
2021-03-12T11:08:03.000Z
2d/extra/TestCoordinatesR2.hpp
danston/gbc
0cb1ae062919b053edc1558bdf41757460703eca
[ "MIT" ]
3
2018-05-10T14:34:35.000Z
2021-12-20T10:01:21.000Z
// Copyright Dmitry Anisimov danston@ymail.com (c) 2016-2017. // README: /* This is a test class for testing generalized barycentric coordinates. */ #ifndef GBC_TESTCOORDINATESR2_HPP #define GBC_TESTCOORDINATESR2_HPP // STL includes. #include <vector> #include <iostream> #include <cmath> // Local includes. #include "Face.hpp" #include "VertexR2.hpp" #include "TriangulatorR2.hpp" #include "BarycentricCoordinatesR2.hpp" #include "../coords/WachspressR2.hpp" #include "../coords/DiscreteHarmonicR2.hpp" #include "../coords/MeanValueR2.hpp" #include "../coords/ThreePointsR2.hpp" #include "../coords/MetricR2.hpp" #include "../coords/BilinearR2.hpp" #include "../coords/PoissonR2.hpp" #include "../coords/CubicMeanValueR2.hpp" #include "../coords/GordonWixomR2.hpp" #include "../coords/PositiveGordonWixomR2.hpp" #include "../coords/PositiveMeanValueR2.hpp" #include "../coords/MaximumEntropyR2.hpp" #include "../coords/AffineR2.hpp" #include "../coords/LaplaceR2.hpp" #include "../coords/SibsonR2.hpp" #include "../coords/HarmonicR2.hpp" #include "../coords/LocalR2.hpp" namespace gbc { // Different theoretical properties of generalized barycentric coordinates. class BarycentricPropertiesR2 { public: // Constructor. BarycentricPropertiesR2(const std::vector<VertexR2> &v, const double tol = 1.0e-10, const bool verbose = true) : _v(v), _tol(tol), _verbose(verbose) { } // Properties. bool partitionOfUnity(const std::vector<double> &b) const { const size_t n = _v.size(); double sum = 0.0; for (size_t i = 0; i < n; ++i) sum += b[i]; const double diff = fabs(sum - 1.0); if (diff > _tol) { if (_verbose) std::cerr << "ERROR: Partition of unity difference is " << diff << ";" << std::endl; return false; } if (_verbose) std::cout << "Partition of unity: SUCCESS" << std::endl; return true; } bool linearReproduction(const VertexR2 &p, const std::vector<double> &b) const { const size_t n = _v.size(); VertexR2 sum; for (size_t i = 0; i < n; ++i) sum += b[i] * _v[i]; const VertexR2 diff = sum - p; if (fabs(diff.x()) > _tol || fabs(diff.y()) > _tol) { if (_verbose) std::cerr << "ERROR: Linear reproduction difference is " << diff << ";" << std::endl; return false; } if (_verbose) std::cout << "Linear reproduction: SUCCESS" << std::endl; return true; } bool boundedness(const std::vector<double> &b) const { const size_t n = _v.size(); for (size_t i = 0; i < n; ++i) { if (b[i] < 0.0 || b[i] > 1.0) { if (_verbose) std::cerr << "ERROR: Value out of range [0,1] with index " << i << ": " << b[i] << ";" << std::endl; return false; } } if (_verbose) std::cout << "Boundedness: SUCCESS" << std::endl; return true; } void checkAll(const VertexR2 &p, const std::vector<double> &b, bool &pu, bool &lr, bool &bd) const { pu = partitionOfUnity(b); lr = linearReproduction(p, b); bd = boundedness(b); if (_verbose) { std::cout << "\nPartition of unity: " << (pu ? "SUCCESS\n" : "FAILED\n"); std::cout << "Linear reproduction: " << (lr ? "SUCCESS\n" : "FAILED\n"); std::cout << "Boundedness: " << (bd ? "SUCCESS\n\n" : "FAILED\n"); } } void checkAll(const std::vector<VertexR2> &p) { bool puRes = true, lrRes = true, bdRes = true; for (size_t i = 0; i < p.size(); ++i) { bool pu, lr, bd; checkAll(p[i], p[i].b(), pu, lr, bd); if (!pu) puRes = false; if (!lr) lrRes = false; if (!bd) bdRes = false; } if (puRes) std::cout << "FINAL: Partition of unity: SUCCESS!\n"; else std::cout << "FINAL: Partition of unity: FAILED!\n"; if (lrRes) std::cout << "FINAL: Linear reproduction: SUCCESS!\n"; else std::cout << "FINAL: Linear reproduction: FAILED!\n"; if (bdRes) std::cout << "FINAL: Boundedness: SUCCESS!\n"; else std::cout << "FINAL: Boundedness: FAILED!\n"; } private: // Vertices of the polygon. const std::vector<VertexR2> &_v; // Tolerance. const double _tol; // Print data. const bool _verbose; }; // Class that verifies different properties and behaviour of generalzied barycentric coordinates in R2. class TestCoordinatesR2 { public: // Constructor. TestCoordinatesR2() : _tol(1.0e-10) { } // Function with different tests. void make() { // Edge length. const double edgeLength = 0.05; // Check barycentric properties on a irregular quad. std::vector<VertexR2> quad(4); quad[0] = VertexR2(0.1, 0.1); quad[1] = VertexR2(1.0, 0.0); quad[2] = VertexR2(0.9, 0.9); quad[3] = VertexR2(0.2, 1.0); std::vector<VertexR2> tp; std::vector<Face> tf; createMesh(quad, tp, tf, edgeLength); checkProperties(quad, tp, tf, edgeLength); // Compare Wachspress (WP), discrete harmonic (DH), Sibson (SB), and // Laplace (LP) coordinates on a circular polygon. std::vector<VertexR2> circular(7); circular[0] = VertexR2(0.745481549466664, 0.935590184544425); circular[1] = VertexR2(0.15182907469161, 0.858855133403299); circular[2] = VertexR2(0.000017768559782, 0.504215239502086); circular[3] = VertexR2(0.170481476091579, 0.123944761502761); circular[4] = VertexR2(0.767263215929374, 0.077424121120137); circular[5] = VertexR2(0.966378029661621, 0.319745919743979); circular[6] = VertexR2(0.877780665791445, 0.827538957307635); createMesh(circular, tp, tf, edgeLength); compare_WP_DH_SB_LP(circular, tp); // Compare mean value (MV) and positive mean value (PM) // coordinates on a convex polygon. std::vector<VertexR2> convex(6); convex[0] = VertexR2(0.087272832224228, 0.554398725870316); convex[1] = VertexR2(0.199047453819107, 0.137461645317987); convex[2] = VertexR2(0.681629947054142, 0.066493631606953); convex[3] = VertexR2(0.857275780988953, 0.210203859371798); convex[4] = VertexR2(0.9, 0.4); convex[5] = VertexR2(0.784533566935143, 0.776173768717299); createMesh(convex, tp, tf, edgeLength); compare_MV_PM(convex, tp); } private: // Tolerance. const double _tol; // Create triangle mesh for a given polygon. void createMesh(const std::vector<VertexR2> &poly, std::vector<VertexR2> &tp, std::vector<Face> &tf, const double edgeLength) { // Refine the polygon to create regular mesh. std::vector<VertexR2> refined; const size_t n = poly.size(); for (size_t i = 0; i < n; ++i) { refined.push_back(poly[i]); const size_t ip = (i + 1) % n; const size_t numS = ceil((poly[ip] - poly[i]).length() / edgeLength); for (size_t j = 1; j < numS; ++j) { VertexR2 vert = poly[i] + (double(j) / double(numS)) * (poly[ip] - poly[i]); refined.push_back(vert); } } // Create mesh. TriangulatorR2 tri(refined, edgeLength, true); tri.setPlanarGraph(true); tp.clear(); tf.clear(); tri.generate(tp, tf); } // Check different barycentric properties. void checkProperties(const std::vector<VertexR2> &poly, std::vector<VertexR2> &tp, const std::vector<Face> &tf, const double edgeLength) const { std::vector<BarycentricCoordinatesR2 *> all; all.push_back(new WachspressR2(poly, _tol)); all.push_back(new DiscreteHarmonicR2(poly, _tol)); all.push_back(new MeanValueR2(poly, _tol)); all.push_back(new ThreePointsR2(poly, _tol)); all.push_back(new MetricR2(poly, _tol)); all.push_back(new BilinearR2(poly, _tol)); all.push_back(new PoissonR2(poly, _tol)); all.push_back(new CubicMeanValueR2(poly, _tol)); all.push_back(new GordonWixomR2(poly, _tol)); all.push_back(new PositiveGordonWixomR2(poly, _tol)); all.push_back(new PositiveMeanValueR2(poly, _tol)); all.push_back(new MaximumEntropyR2(poly, _tol)); all.push_back(new AffineR2(poly, _tol)); all.push_back(new LaplaceR2(poly, _tol)); all.push_back(new SibsonR2(poly, _tol)); HarmonicR2* hmc = new HarmonicR2(poly, _tol); hmc->setMesh(tp, tf); all.push_back(hmc); LocalR2* lbc = new LocalR2(poly, _tol); lbc->setEdgeLength(edgeLength); lbc->setMesh(tp, tf); all.push_back(lbc); BarycentricPropertiesR2 bp(poly, _tol, false); for (size_t i = 0; i < all.size(); ++i) { all[i]->bc(tp); bool puRes = true, lrRes = true, bdRes = true; for (size_t j = 0; j < tp.size(); ++j) { bool pu, lr, bd; bp.checkAll(tp[j], tp[j].b(), pu, lr, bd); if (!pu) puRes = false; if (!lr) lrRes = false; if (!bd) bdRes = false; } if (puRes && lrRes && bdRes) std::cout << "Properties of " << all[i]-> name() << ": SUCCESS!\n"; else std::cout << "Properties " << puRes << " " << lrRes << " " << bdRes << " of " << all[i]-> name() << ": FAILED!\n"; } } // Compare Wachspress, discrete harmonic, Sibson, and Laplace coordinates on a regular polygon. // They all should give the same result. void compare_WP_DH_SB_LP(const std::vector<VertexR2> &circular, std::vector<VertexR2> &tp) const { std::vector<std::vector<double> > wpBB; std::vector<std::vector<double> > dhBB; std::vector<std::vector<double> > sbBB; std::vector<std::vector<double> > lpBB; WachspressR2 wp(circular, _tol); wp.compute(tp, wpBB); DiscreteHarmonicR2 dh(circular, _tol); dh.compute(tp, dhBB); WachspressR2 sb(circular, _tol); sb.compute(tp, sbBB); DiscreteHarmonicR2 lp(circular, _tol); lp.compute(tp, lpBB); assert(wpBB.size() == tp.size()); assert(wpBB.size() == dhBB.size() && dhBB.size() == sbBB.size() && sbBB.size() == lpBB.size()); bool res = true; double value = -100.0; for (size_t i = 0; i < tp.size(); ++i) { for (size_t j = 0; j < circular.size(); ++j) { if (fabs(wpBB[i][j] - dhBB[i][j]) > _tol || fabs(dhBB[i][j] - sbBB[i][j]) > _tol || fabs(sbBB[i][j] - lpBB[i][j]) > _tol) { value = std::max(fabs(wpBB[i][j] - dhBB[i][j]), value); value = std::max(fabs(dhBB[i][j] - sbBB[i][j]), value); value = std::max(fabs(sbBB[i][j] - lpBB[i][j]), value); res = false; break; } } if (!res) break; } if (res) std::cout << "Comparison of WP, DH, SB, and LP: SUCCESS!\n"; else std::cout << "Comparison of WP, DH, SB, and LP: " << value << " FAILED!\n"; } // Compare mean value and positive mean value coordinates on a convex polygon. // They should give the same result. void compare_MV_PM(const std::vector<VertexR2> &convex, std::vector<VertexR2> &tp) const { std::vector<std::vector<double> > mvBB; std::vector<std::vector<double> > pmBB; MeanValueR2 mv(convex, _tol); mv.compute(tp, mvBB); PositiveMeanValueR2 pm(convex, _tol); pm.compute(tp, pmBB); assert(mvBB.size() == tp.size()); assert(mvBB.size() == pmBB.size()); bool res = true; double value = 0.0; for (size_t i = 0; i < tp.size(); ++i) { for (size_t j = 0; j < convex.size(); ++j) { if (fabs(mvBB[i][j] - pmBB[i][j]) > _tol) { value = fabs(mvBB[i][j] - pmBB[i][j]); res = false; break; } } if (!res) break; } if (res) std::cout << "Comparison of MV and PM: SUCCESS!\n"; else std::cout << "Comparison of MV and PM: " << value << " FAILED!\n"; } }; } // namespace gbc #endif // GBC_TESTCOORDINATESR2_HPP
35.125945
124
0.507063
danston
04e32f046801bb7c6cff6759899efb55d923abcb
176
cpp
C++
Code/operator.cpp
capacitybuilding/Fundamentals-of-Programming-Source-Code
76d9a70b6b36c7eb1992de3806d1a16584904f76
[ "MIT" ]
null
null
null
Code/operator.cpp
capacitybuilding/Fundamentals-of-Programming-Source-Code
76d9a70b6b36c7eb1992de3806d1a16584904f76
[ "MIT" ]
null
null
null
Code/operator.cpp
capacitybuilding/Fundamentals-of-Programming-Source-Code
76d9a70b6b36c7eb1992de3806d1a16584904f76
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main(){ int a=5, b=8, c=7; bool x,y; x = a>c || b!= c && a==c; y = !x; cout<<x<<endl<<y<<endl; int d = 8/3 + a%2 - c*b; cout<<d; }
13.538462
25
0.522727
capacitybuilding
04e50efb75b1054fa5c0a1949ead6a43cc9b6226
1,829
cpp
C++
src/class.cpp
Oberon00/apollo
831f4e505afaa04ea827e99f4ced247bb0f0e476
[ "BSD-2-Clause" ]
25
2016-01-04T23:07:06.000Z
2022-03-03T11:24:55.000Z
src/class.cpp
Oberon00/apollo
831f4e505afaa04ea827e99f4ced247bb0f0e476
[ "BSD-2-Clause" ]
2
2018-05-21T18:15:49.000Z
2018-05-21T18:47:05.000Z
src/class.cpp
Oberon00/apollo
831f4e505afaa04ea827e99f4ced247bb0f0e476
[ "BSD-2-Clause" ]
6
2019-12-05T04:05:06.000Z
2022-03-03T11:24:38.000Z
// Part of the apollo library -- Copyright (c) Christian Neumüller 2015 // This file is subject to the terms of the BSD 2-Clause License. // See LICENSE.txt or http://opensource.org/licenses/BSD-2-Clause #include <apollo/class.hpp> #include <apollo/gc.hpp> static apollo::detail::light_key object_tag = {}; static int gc_instance(lua_State* L) BOOST_NOEXCEPT { if (!apollo::detail::is_apollo_instance(L, 1)) luaL_argerror(L, 1, "Expected apollo object."); apollo::gc_object<apollo::detail::instance_holder>(L); lua_pushnil(L); lua_setmetatable(L, 1); return 0; } APOLLO_API void apollo::detail::push_instance_metatable( lua_State* L, class_info const& cls) BOOST_NOEXCEPT { lua_rawgetp(L, LUA_REGISTRYINDEX, &cls); if (!lua_istable(L, -1)) { BOOST_ASSERT(lua_isnil(L, -1)); lua_pop(L, 1); lua_createtable(L, 1, 1); lua_pushlightuserdata(L, object_tag); lua_rawseti(L, -2, 1); lua_pushliteral(L, "__gc"); // Destroy through pointer to interface class. lua_pushcfunction(L, &gc_instance); lua_rawset(L, -3); // Copy metatable because we also want to return it. lua_pushvalue(L, -1); lua_rawsetp(L, LUA_REGISTRYINDEX, &cls); } #ifndef NDEBUG lua_rawgeti(L, -1, 1); BOOST_ASSERT(lua_touserdata(L, -1) == object_tag); lua_pop(L, 1); #endif } APOLLO_API bool apollo::detail::is_apollo_instance(lua_State* L, int idx) { // We don't have to check for type == userdata, as the object metatables get // a __metatable field by default, blocking Lua code from geting hold of the // object_tag. if (!lua_getmetatable(L, idx)) return false; lua_rawgeti(L, -1, 1); bool r = lua_touserdata(L, -1) == object_tag; lua_pop(L, 2); return r; }
29.031746
80
0.655549
Oberon00
04e68d245006b55e891ecd5d424b5f0885f02cbb
438
cpp
C++
Easy/374_Guess_Number_Higher_Or_Lower.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
1
2021-03-15T10:02:10.000Z
2021-03-15T10:02:10.000Z
Easy/374_Guess_Number_Higher_Or_Lower.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
null
null
null
Easy/374_Guess_Number_Higher_Or_Lower.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
null
null
null
// Forward declaration of guess API. // @param num, your guess // @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 int guess(int num); class Solution { public: int guessNumber(int n) { return play_game(1, n); } int play_game(int low, int high) { int m = low + (high-low)/2; return guess(m) == 0 ? m : (guess(m) == -1 ? play_game(low, m-1) : play_game(m+1, high)); } };
31.285714
97
0.598174
ShehabMMohamed
04e75e00d13ede9fdfaabd56a1494e95d0f1cd11
55,595
cpp
C++
compiler/parser.cpp
dmdecz/DM-MiniSQL
93a56e2d1a269715e53e70e0ee112f7f37e97a88
[ "MIT" ]
null
null
null
compiler/parser.cpp
dmdecz/DM-MiniSQL
93a56e2d1a269715e53e70e0ee112f7f37e97a88
[ "MIT" ]
null
null
null
compiler/parser.cpp
dmdecz/DM-MiniSQL
93a56e2d1a269715e53e70e0ee112f7f37e97a88
[ "MIT" ]
null
null
null
// A Bison parser, made by GNU Bison 3.4.1. // Skeleton implementation for Bison LALR(1) parsers in C++ // Copyright (C) 2002-2015, 2018-2019 Free Software Foundation, Inc. // 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 // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // As a special exception, you may create a larger work that contains // part or all of the Bison parser skeleton and distribute that work // under terms of your choice, so long as that work isn't itself a // parser generator using the skeleton or a modified version thereof // as a parser skeleton. Alternatively, if you modify or redistribute // the parser skeleton itself, you may (at your option) remove this // special exception, which will cause the skeleton and the resulting // Bison output files to be licensed under the GNU General Public // License without this special exception. // This special exception was added by the Free Software Foundation in // version 2.2 of Bison. // Undocumented macros, especially those whose name start with YY_, // are private implementation details. Do not rely on them. #include "parser.hpp" // Unqualified %code blocks. #line 27 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" # include "compiler.hpp" # include "compilertools/compilertools.hpp" #line 51 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> // FIXME: INFRINGES ON USER NAME SPACE. # define YY_(msgid) dgettext ("bison-runtime", msgid) # endif # endif # ifndef YY_ # define YY_(msgid) msgid # endif #endif // Whether we are compiled with exception support. #ifndef YY_EXCEPTIONS # if defined __GNUC__ && !defined __EXCEPTIONS # define YY_EXCEPTIONS 0 # else # define YY_EXCEPTIONS 1 # endif #endif #define YYRHSLOC(Rhs, K) ((Rhs)[K].location) /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ # ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (N) \ { \ (Current).begin = YYRHSLOC (Rhs, 1).begin; \ (Current).end = YYRHSLOC (Rhs, N).end; \ } \ else \ { \ (Current).begin = (Current).end = YYRHSLOC (Rhs, 0).end; \ } \ while (false) # endif // Suppress unused-variable warnings by "using" E. #define YYUSE(E) ((void) (E)) // Enable debugging if requested. #if YYDEBUG // A pseudo ostream that takes yydebug_ into account. # define YYCDEBUG if (yydebug_) (*yycdebug_) # define YY_SYMBOL_PRINT(Title, Symbol) \ do { \ if (yydebug_) \ { \ *yycdebug_ << Title << ' '; \ yy_print_ (*yycdebug_, Symbol); \ *yycdebug_ << '\n'; \ } \ } while (false) # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug_) \ yy_reduce_print_ (Rule); \ } while (false) # define YY_STACK_PRINT() \ do { \ if (yydebug_) \ yystack_print_ (); \ } while (false) #else // !YYDEBUG # define YYCDEBUG if (false) std::cerr # define YY_SYMBOL_PRINT(Title, Symbol) YYUSE (Symbol) # define YY_REDUCE_PRINT(Rule) static_cast<void> (0) # define YY_STACK_PRINT() static_cast<void> (0) #endif // !YYDEBUG #define yyerrok (yyerrstatus_ = 0) #define yyclearin (yyla.clear ()) #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab #define YYRECOVERING() (!!yyerrstatus_) namespace yy { #line 145 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" /* Return YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. */ std::string parser::yytnamerr_ (const char *yystr) { if (*yystr == '"') { std::string yyr; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; else goto append; append: default: yyr += *yyp; break; case '"': return yyr; } do_not_strip_quotes: ; } return yystr; } /// Build a parser object. parser::parser (Compiler& drv_yyarg) : #if YYDEBUG yydebug_ (false), yycdebug_ (&std::cerr), #endif drv (drv_yyarg) {} parser::~parser () {} parser::syntax_error::~syntax_error () YY_NOEXCEPT YY_NOTHROW {} /*---------------. | Symbol types. | `---------------*/ // by_state. parser::by_state::by_state () YY_NOEXCEPT : state (empty_state) {} parser::by_state::by_state (const by_state& that) YY_NOEXCEPT : state (that.state) {} void parser::by_state::clear () YY_NOEXCEPT { state = empty_state; } void parser::by_state::move (by_state& that) { state = that.state; that.clear (); } parser::by_state::by_state (state_type s) YY_NOEXCEPT : state (s) {} parser::symbol_number_type parser::by_state::type_get () const YY_NOEXCEPT { if (state == empty_state) return empty_symbol; else return yystos_[state]; } parser::stack_symbol_type::stack_symbol_type () {} parser::stack_symbol_type::stack_symbol_type (YY_RVREF (stack_symbol_type) that) : super_type (YY_MOVE (that.state), YY_MOVE (that.location)) { switch (that.type_get ()) { case 64: // select_condition_exp case 66: // exp case 69: // attribute_exp case 72: // constrain_exp value.YY_MOVE_OR_COPY< Expression * > (YY_MOVE (that.value)); break; case 53: // attr_list case 54: // value_list case 60: // select_list case 61: // table_list case 62: // select_condition case 63: // select_condition_list case 68: // attribute_list case 71: // constrain_list value.YY_MOVE_OR_COPY< ExpressionList * > (YY_MOVE (that.value)); break; case 48: // statement case 49: // show_statement case 50: // create_index_statement case 51: // drop_index_statement case 52: // insert_statement case 55: // drop_table_statement case 56: // drop_db_statement case 57: // use_statement case 58: // create_db_statement case 59: // select_statement case 65: // delete_statement case 67: // create_table_statement value.YY_MOVE_OR_COPY< Statement * > (YY_MOVE (that.value)); break; case 4: // DECIMAL value.YY_MOVE_OR_COPY< double > (YY_MOVE (that.value)); break; case 3: // NUMBER case 70: // variant_type value.YY_MOVE_OR_COPY< int > (YY_MOVE (that.value)); break; case 44: // STRING case 45: // FILENAME value.YY_MOVE_OR_COPY< std::string > (YY_MOVE (that.value)); break; case 47: // statement_list value.YY_MOVE_OR_COPY< std::vector<Statement*> > (YY_MOVE (that.value)); break; default: break; } #if 201103L <= YY_CPLUSPLUS // that is emptied. that.state = empty_state; #endif } parser::stack_symbol_type::stack_symbol_type (state_type s, YY_MOVE_REF (symbol_type) that) : super_type (s, YY_MOVE (that.location)) { switch (that.type_get ()) { case 64: // select_condition_exp case 66: // exp case 69: // attribute_exp case 72: // constrain_exp value.move< Expression * > (YY_MOVE (that.value)); break; case 53: // attr_list case 54: // value_list case 60: // select_list case 61: // table_list case 62: // select_condition case 63: // select_condition_list case 68: // attribute_list case 71: // constrain_list value.move< ExpressionList * > (YY_MOVE (that.value)); break; case 48: // statement case 49: // show_statement case 50: // create_index_statement case 51: // drop_index_statement case 52: // insert_statement case 55: // drop_table_statement case 56: // drop_db_statement case 57: // use_statement case 58: // create_db_statement case 59: // select_statement case 65: // delete_statement case 67: // create_table_statement value.move< Statement * > (YY_MOVE (that.value)); break; case 4: // DECIMAL value.move< double > (YY_MOVE (that.value)); break; case 3: // NUMBER case 70: // variant_type value.move< int > (YY_MOVE (that.value)); break; case 44: // STRING case 45: // FILENAME value.move< std::string > (YY_MOVE (that.value)); break; case 47: // statement_list value.move< std::vector<Statement*> > (YY_MOVE (that.value)); break; default: break; } // that is emptied. that.type = empty_symbol; } #if YY_CPLUSPLUS < 201103L parser::stack_symbol_type& parser::stack_symbol_type::operator= (stack_symbol_type& that) { state = that.state; switch (that.type_get ()) { case 64: // select_condition_exp case 66: // exp case 69: // attribute_exp case 72: // constrain_exp value.move< Expression * > (that.value); break; case 53: // attr_list case 54: // value_list case 60: // select_list case 61: // table_list case 62: // select_condition case 63: // select_condition_list case 68: // attribute_list case 71: // constrain_list value.move< ExpressionList * > (that.value); break; case 48: // statement case 49: // show_statement case 50: // create_index_statement case 51: // drop_index_statement case 52: // insert_statement case 55: // drop_table_statement case 56: // drop_db_statement case 57: // use_statement case 58: // create_db_statement case 59: // select_statement case 65: // delete_statement case 67: // create_table_statement value.move< Statement * > (that.value); break; case 4: // DECIMAL value.move< double > (that.value); break; case 3: // NUMBER case 70: // variant_type value.move< int > (that.value); break; case 44: // STRING case 45: // FILENAME value.move< std::string > (that.value); break; case 47: // statement_list value.move< std::vector<Statement*> > (that.value); break; default: break; } location = that.location; // that is emptied. that.state = empty_state; return *this; } #endif template <typename Base> void parser::yy_destroy_ (const char* yymsg, basic_symbol<Base>& yysym) const { if (yymsg) YY_SYMBOL_PRINT (yymsg, yysym); } #if YYDEBUG template <typename Base> void parser::yy_print_ (std::ostream& yyo, const basic_symbol<Base>& yysym) const { std::ostream& yyoutput = yyo; YYUSE (yyoutput); symbol_number_type yytype = yysym.type_get (); #if defined __GNUC__ && ! defined __clang__ && ! defined __ICC && __GNUC__ * 100 + __GNUC_MINOR__ <= 408 // Avoid a (spurious) G++ 4.8 warning about "array subscript is // below array bounds". if (yysym.empty ()) std::abort (); #endif yyo << (yytype < yyntokens_ ? "token" : "nterm") << ' ' << yytname_[yytype] << " (" << yysym.location << ": "; YYUSE (yytype); yyo << ')'; } #endif void parser::yypush_ (const char* m, YY_MOVE_REF (stack_symbol_type) sym) { if (m) YY_SYMBOL_PRINT (m, sym); yystack_.push (YY_MOVE (sym)); } void parser::yypush_ (const char* m, state_type s, YY_MOVE_REF (symbol_type) sym) { #if 201103L <= YY_CPLUSPLUS yypush_ (m, stack_symbol_type (s, std::move (sym))); #else stack_symbol_type ss (s, sym); yypush_ (m, ss); #endif } void parser::yypop_ (int n) { yystack_.pop (n); } #if YYDEBUG std::ostream& parser::debug_stream () const { return *yycdebug_; } void parser::set_debug_stream (std::ostream& o) { yycdebug_ = &o; } parser::debug_level_type parser::debug_level () const { return yydebug_; } void parser::set_debug_level (debug_level_type l) { yydebug_ = l; } #endif // YYDEBUG parser::state_type parser::yy_lr_goto_state_ (state_type yystate, int yysym) { int yyr = yypgoto_[yysym - yyntokens_] + yystate; if (0 <= yyr && yyr <= yylast_ && yycheck_[yyr] == yystate) return yytable_[yyr]; else return yydefgoto_[yysym - yyntokens_]; } bool parser::yy_pact_value_is_default_ (int yyvalue) { return yyvalue == yypact_ninf_; } bool parser::yy_table_value_is_error_ (int yyvalue) { return yyvalue == yytable_ninf_; } int parser::operator() () { return parse (); } int parser::parse () { // State. int yyn; /// Length of the RHS of the rule being reduced. int yylen = 0; // Error handling. int yynerrs_ = 0; int yyerrstatus_ = 0; /// The lookahead symbol. symbol_type yyla; /// The locations where the error started and ended. stack_symbol_type yyerror_range[3]; /// The return value of parse (). int yyresult; #if YY_EXCEPTIONS try #endif // YY_EXCEPTIONS { YYCDEBUG << "Starting parse\n"; /* Initialize the stack. The initial state will be set in yynewstate, since the latter expects the semantical and the location values to have been already stored, initialize these stacks with a primary value. */ yystack_.clear (); yypush_ (YY_NULLPTR, 0, YY_MOVE (yyla)); /*-----------------------------------------------. | yynewstate -- push a new symbol on the stack. | `-----------------------------------------------*/ yynewstate: YYCDEBUG << "Entering state " << yystack_[0].state << '\n'; // Accept? if (yystack_[0].state == yyfinal_) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: // Try to take a decision without lookahead. yyn = yypact_[yystack_[0].state]; if (yy_pact_value_is_default_ (yyn)) goto yydefault; // Read a lookahead token. if (yyla.empty ()) { YYCDEBUG << "Reading a token: "; #if YY_EXCEPTIONS try #endif // YY_EXCEPTIONS { symbol_type yylookahead (yylex (drv)); yyla.move (yylookahead); } #if YY_EXCEPTIONS catch (const syntax_error& yyexc) { YYCDEBUG << "Caught exception: " << yyexc.what() << '\n'; error (yyexc); goto yyerrlab1; } #endif // YY_EXCEPTIONS } YY_SYMBOL_PRINT ("Next token is", yyla); /* If the proper action on seeing token YYLA.TYPE is to reduce or to detect an error, take that action. */ yyn += yyla.type_get (); if (yyn < 0 || yylast_ < yyn || yycheck_[yyn] != yyla.type_get ()) goto yydefault; // Reduce or error. yyn = yytable_[yyn]; if (yyn <= 0) { if (yy_table_value_is_error_ (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } // Count tokens shifted since error; after three, turn off error status. if (yyerrstatus_) --yyerrstatus_; // Shift the lookahead token. yypush_ ("Shifting", yyn, YY_MOVE (yyla)); goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact_[yystack_[0].state]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- do a reduction. | `-----------------------------*/ yyreduce: yylen = yyr2_[yyn]; { stack_symbol_type yylhs; yylhs.state = yy_lr_goto_state_ (yystack_[yylen].state, yyr1_[yyn]); /* Variants are always initialized to an empty instance of the correct type. The default '$$ = $1' action is NOT applied when using variants. */ switch (yyr1_[yyn]) { case 64: // select_condition_exp case 66: // exp case 69: // attribute_exp case 72: // constrain_exp yylhs.value.emplace< Expression * > (); break; case 53: // attr_list case 54: // value_list case 60: // select_list case 61: // table_list case 62: // select_condition case 63: // select_condition_list case 68: // attribute_list case 71: // constrain_list yylhs.value.emplace< ExpressionList * > (); break; case 48: // statement case 49: // show_statement case 50: // create_index_statement case 51: // drop_index_statement case 52: // insert_statement case 55: // drop_table_statement case 56: // drop_db_statement case 57: // use_statement case 58: // create_db_statement case 59: // select_statement case 65: // delete_statement case 67: // create_table_statement yylhs.value.emplace< Statement * > (); break; case 4: // DECIMAL yylhs.value.emplace< double > (); break; case 3: // NUMBER case 70: // variant_type yylhs.value.emplace< int > (); break; case 44: // STRING case 45: // FILENAME yylhs.value.emplace< std::string > (); break; case 47: // statement_list yylhs.value.emplace< std::vector<Statement*> > (); break; default: break; } // Default location. { stack_type::slice range (yystack_, yylen); YYLLOC_DEFAULT (yylhs.location, range, yylen); yyerror_range[1].location = yylhs.location; } // Perform the reduction. YY_REDUCE_PRINT (yyn); #if YY_EXCEPTIONS try #endif // YY_EXCEPTIONS { switch (yyn) { case 2: #line 75 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { drv.execute_statement(yystack_[0].value.as < Statement * > ()); } #line 760 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 3: #line 76 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { drv.execute_statement(yystack_[0].value.as < Statement * > ()); } #line 766 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 4: #line 77 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { return 1; } #line 772 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 5: #line 81 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = nullptr; } #line 778 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 6: #line 82 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = yystack_[1].value.as < Statement * > (); } #line 784 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 7: #line 83 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = new Source_Statement(yystack_[1].value.as < std::string > ()); } #line 790 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 8: #line 84 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = yystack_[1].value.as < Statement * > (); } #line 796 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 9: #line 85 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = yystack_[1].value.as < Statement * > (); } #line 802 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 10: #line 86 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = new Quit_Statement; } #line 808 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 11: #line 87 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = yystack_[1].value.as < Statement * > (); } #line 814 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 12: #line 88 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = yystack_[1].value.as < Statement * > (); } #line 820 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 13: #line 89 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = yystack_[1].value.as < Statement * > (); } #line 826 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 14: #line 90 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = yystack_[1].value.as < Statement * > (); } #line 832 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 15: #line 91 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = yystack_[1].value.as < Statement * > (); } #line 838 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 16: #line 92 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = yystack_[1].value.as < Statement * > (); } #line 844 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 17: #line 93 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = yystack_[1].value.as < Statement * > (); } #line 850 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 18: #line 94 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = yystack_[1].value.as < Statement * > (); } #line 856 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 19: #line 98 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = new Show_Statement(0); } #line 862 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 20: #line 99 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = new Show_Statement(1); } #line 868 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 21: #line 103 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = new Create_Index_Statement(yystack_[1].value.as < std::string > (), yystack_[0].value.as < std::string > ()); } #line 876 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 22: #line 109 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = new Drop_Index_Statement(yystack_[1].value.as < std::string > (), yystack_[0].value.as < std::string > ()); } #line 884 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 23: #line 115 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = new Insert_Statement(yystack_[7].value.as < std::string > (), yystack_[5].value.as < ExpressionList * > (), yystack_[1].value.as < ExpressionList * > ()); } #line 892 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 24: #line 121 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < ExpressionList * > () = new ExpressionList; yylhs.value.as < ExpressionList * > ()->push_back(new String_Expression(yystack_[0].value.as < std::string > ())); } #line 898 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 25: #line 122 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < ExpressionList * > () = yystack_[2].value.as < ExpressionList * > (); yylhs.value.as < ExpressionList * > ()->push_back(new String_Expression(yystack_[0].value.as < std::string > ())); } #line 904 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 26: #line 126 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < ExpressionList * > () = new ExpressionList; yylhs.value.as < ExpressionList * > ()->push_back(yystack_[0].value.as < Expression * > ()); } #line 910 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 27: #line 127 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < ExpressionList * > () = yystack_[2].value.as < ExpressionList * > (); yylhs.value.as < ExpressionList * > ()->push_back(yystack_[0].value.as < Expression * > ()); } #line 916 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 28: #line 131 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = new Drop_Table_Statement(yystack_[0].value.as < std::string > ()); } #line 922 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 29: #line 135 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = new Drop_Database_Statement(yystack_[0].value.as < std::string > ()); } #line 928 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 30: #line 139 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = new Use_Statement(yystack_[0].value.as < std::string > ()); } #line 934 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 31: #line 143 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = new Create_Database_Statement(yystack_[0].value.as < std::string > ()); } #line 940 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 32: #line 147 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { Select_Statement * select = new Select_Statement; select->set_select(yystack_[3].value.as < ExpressionList * > ()); select->set_table(yystack_[1].value.as < ExpressionList * > ()); select->set_condition(yystack_[0].value.as < ExpressionList * > ()); yylhs.value.as < Statement * > () = select; } #line 952 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 33: #line 157 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < ExpressionList * > () = new ExpressionList; yylhs.value.as < ExpressionList * > ()->push_back(new String_Expression("*")); } #line 958 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 34: #line 158 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < ExpressionList * > () = new ExpressionList; yylhs.value.as < ExpressionList * > ()->push_back(new String_Expression(yystack_[0].value.as < std::string > ())); } #line 964 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 35: #line 159 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < ExpressionList * > () = yystack_[2].value.as < ExpressionList * > (); yylhs.value.as < ExpressionList * > ()->push_back(new String_Expression(yystack_[0].value.as < std::string > ())); } #line 970 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 36: #line 163 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < ExpressionList * > () = new ExpressionList; yylhs.value.as < ExpressionList * > ()->push_back(new String_Expression(yystack_[0].value.as < std::string > ())); } #line 976 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 37: #line 164 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < ExpressionList * > () = yystack_[2].value.as < ExpressionList * > (); yylhs.value.as < ExpressionList * > ()->push_back(new String_Expression(yystack_[0].value.as < std::string > ())); } #line 982 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 38: #line 168 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < ExpressionList * > () = nullptr; } #line 988 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 39: #line 169 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < ExpressionList * > () = yystack_[0].value.as < ExpressionList * > (); } #line 994 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 40: #line 173 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < ExpressionList * > () = new ExpressionList; yylhs.value.as < ExpressionList * > ()->push_back(yystack_[0].value.as < Expression * > ()); } #line 1000 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 41: #line 174 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < ExpressionList * > () = yystack_[2].value.as < ExpressionList * > (); yylhs.value.as < ExpressionList * > ()->push_back(yystack_[0].value.as < Expression * > ()); } #line 1006 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 42: #line 178 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Expression * > () = new Condition_Expression(yystack_[2].value.as < std::string > (), EQUAL, yystack_[0].value.as < Expression * > ()->values()); } #line 1012 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 43: #line 179 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Expression * > () = new Condition_Expression(yystack_[2].value.as < std::string > (), LESS, yystack_[0].value.as < Expression * > ()->values()); } #line 1018 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 44: #line 180 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Expression * > () = new Condition_Expression(yystack_[2].value.as < std::string > (), LARGE, yystack_[0].value.as < Expression * > ()->values()); } #line 1024 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 45: #line 181 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Expression * > () = new Condition_Expression(yystack_[2].value.as < std::string > (), NOT, yystack_[0].value.as < Expression * > ()->values()); } #line 1030 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 46: #line 185 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Statement * > () = new Delete_Statement(yystack_[2].value.as < std::string > (), yystack_[0].value.as < ExpressionList * > ()); } #line 1038 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 47: #line 191 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Expression * > () = new DMType_Expression(DMType(yystack_[0].value.as < std::string > ())); } #line 1044 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 48: #line 192 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Expression * > () = new DMType_Expression(DMType(yystack_[0].value.as < int > ())); } #line 1050 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 49: #line 193 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Expression * > () = new DMType_Expression(DMType(yystack_[0].value.as < double > ())); } #line 1056 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 50: #line 198 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { Create_Table_Statement * create = new Create_Table_Statement(yystack_[4].value.as < std::string > ()); create->set_attribute(yystack_[2].value.as < ExpressionList * > ()); create->set_constrain(yystack_[1].value.as < ExpressionList * > ()); yylhs.value.as < Statement * > () = create; } #line 1067 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 51: #line 207 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < ExpressionList * > () = new ExpressionList(); yylhs.value.as < ExpressionList * > ()->push_back(yystack_[0].value.as < Expression * > ()); } #line 1073 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 52: #line 208 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yystack_[2].value.as < ExpressionList * > ()->push_back(yystack_[0].value.as < Expression * > ()); yylhs.value.as < ExpressionList * > () = yystack_[2].value.as < ExpressionList * > (); } #line 1079 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 53: #line 212 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Expression * > () = new Attribute_Expression(yystack_[1].value.as < std::string > (), yystack_[0].value.as < int > (), 0); } #line 1085 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 54: #line 213 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Expression * > () = new Attribute_Expression(yystack_[2].value.as < std::string > (), yystack_[1].value.as < int > (), 1); } #line 1091 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 55: #line 217 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < int > () = -1; } #line 1097 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 56: #line 218 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < int > () = -2; } #line 1103 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 57: #line 219 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < int > () = yystack_[1].value.as < int > (); } #line 1109 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 58: #line 223 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < ExpressionList * > () = nullptr; } #line 1115 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 59: #line 224 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < ExpressionList * > () = new ExpressionList(); yylhs.value.as < ExpressionList * > ()->push_back(yystack_[0].value.as < Expression * > ()); } #line 1121 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 60: #line 225 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yystack_[2].value.as < ExpressionList * > ()->push_back(yystack_[0].value.as < Expression * > ()); yylhs.value.as < ExpressionList * > () = yystack_[2].value.as < ExpressionList * > (); } #line 1127 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 61: #line 229 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Expression * > () = new Constrain_Expression(0, yystack_[1].value.as < std::string > ()); } #line 1133 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; case 62: #line 230 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" { yylhs.value.as < Expression * > () = new Constrain_Expression(1, yystack_[1].value.as < std::string > ()); } #line 1139 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" break; #line 1143 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" default: break; } } #if YY_EXCEPTIONS catch (const syntax_error& yyexc) { YYCDEBUG << "Caught exception: " << yyexc.what() << '\n'; error (yyexc); YYERROR; } #endif // YY_EXCEPTIONS YY_SYMBOL_PRINT ("-> $$ =", yylhs); yypop_ (yylen); yylen = 0; YY_STACK_PRINT (); // Shift the result of the reduction. yypush_ (YY_NULLPTR, YY_MOVE (yylhs)); } goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: // If not already recovering from an error, report this error. if (!yyerrstatus_) { ++yynerrs_; error (yyla.location, yysyntax_error_ (yystack_[0].state, yyla)); } yyerror_range[1].location = yyla.location; if (yyerrstatus_ == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ // Return failure if at end of input. if (yyla.type_get () == yyeof_) YYABORT; else if (!yyla.empty ()) { yy_destroy_ ("Error: discarding", yyla); yyla.clear (); } } // Else will try to reuse lookahead token after shifting the error token. goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (false) YYERROR; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ yypop_ (yylen); yylen = 0; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus_ = 3; // Each real token shifted decrements this. { stack_symbol_type error_token; for (;;) { yyn = yypact_[yystack_[0].state]; if (!yy_pact_value_is_default_ (yyn)) { yyn += yyterror_; if (0 <= yyn && yyn <= yylast_ && yycheck_[yyn] == yyterror_) { yyn = yytable_[yyn]; if (0 < yyn) break; } } // Pop the current state because it cannot handle the error token. if (yystack_.size () == 1) YYABORT; yyerror_range[1].location = yystack_[0].location; yy_destroy_ ("Error: popping", yystack_[0]); yypop_ (); YY_STACK_PRINT (); } yyerror_range[2].location = yyla.location; YYLLOC_DEFAULT (error_token.location, yyerror_range, 2); // Shift the error token. error_token.state = yyn; yypush_ ("Shifting", YY_MOVE (error_token)); } goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; /*-----------------------------------------------------. | yyreturn -- parsing is finished, return the result. | `-----------------------------------------------------*/ yyreturn: if (!yyla.empty ()) yy_destroy_ ("Cleanup: discarding lookahead", yyla); /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ yypop_ (yylen); while (1 < yystack_.size ()) { yy_destroy_ ("Cleanup: popping", yystack_[0]); yypop_ (); } return yyresult; } #if YY_EXCEPTIONS catch (...) { YYCDEBUG << "Exception caught: cleaning lookahead and stack\n"; // Do not try to display the values of the reclaimed symbols, // as their printers might throw an exception. if (!yyla.empty ()) yy_destroy_ (YY_NULLPTR, yyla); while (1 < yystack_.size ()) { yy_destroy_ (YY_NULLPTR, yystack_[0]); yypop_ (); } throw; } #endif // YY_EXCEPTIONS } void parser::error (const syntax_error& yyexc) { error (yyexc.location, yyexc.what ()); } // Generate an error message. std::string parser::yysyntax_error_ (state_type yystate, const symbol_type& yyla) const { // Number of reported tokens (one for the "unexpected", one per // "expected"). size_t yycount = 0; // Its maximum. enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; // Arguments of yyformat. char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; /* There are many possibilities here to consider: - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in yyla) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yyla. (However, yyla is currently not documented for users.) - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (!yyla.empty ()) { int yytoken = yyla.type_get (); yyarg[yycount++] = yytname_[yytoken]; int yyn = yypact_[yystate]; if (!yy_pact_value_is_default_ (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; // Stay within bounds of both yycheck and yytname. int yychecklim = yylast_ - yyn + 1; int yyxend = yychecklim < yyntokens_ ? yychecklim : yyntokens_; for (int yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck_[yyx + yyn] == yyx && yyx != yyterror_ && !yy_table_value_is_error_ (yytable_[yyx + yyn])) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; break; } else yyarg[yycount++] = yytname_[yyx]; } } } char const* yyformat = YY_NULLPTR; switch (yycount) { #define YYCASE_(N, S) \ case N: \ yyformat = S; \ break default: // Avoid compiler warnings. YYCASE_ (0, YY_("syntax error")); YYCASE_ (1, YY_("syntax error, unexpected %s")); YYCASE_ (2, YY_("syntax error, unexpected %s, expecting %s")); YYCASE_ (3, YY_("syntax error, unexpected %s, expecting %s or %s")); YYCASE_ (4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); YYCASE_ (5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); #undef YYCASE_ } std::string yyres; // Argument number. size_t yyi = 0; for (char const* yyp = yyformat; *yyp; ++yyp) if (yyp[0] == '%' && yyp[1] == 's' && yyi < yycount) { yyres += yytnamerr_ (yyarg[yyi++]); ++yyp; } else yyres += *yyp; return yyres; } const signed char parser::yypact_ninf_ = -95; const signed char parser::yytable_ninf_ = -1; const signed char parser::yypact_[] = { 30, -17, -18, -35, 38, -32, 43, 3, 9, -5, -95, 8, -95, -4, 4, 11, 18, 49, 50, 51, 52, 53, 54, 55, -95, -95, -1, -95, 56, 6, 19, 32, -95, 39, 40, 42, 44, 45, -95, -95, -95, -95, -95, -95, -95, -95, -95, -95, -95, -95, -95, -95, -95, -95, 46, 47, -95, 57, -95, 48, -95, -95, 58, 63, 75, -95, 2, -95, 59, 60, -95, 61, 62, 62, 64, -95, 31, 65, -95, -95, -95, -7, 22, 67, -95, 67, -95, -95, -95, 66, 74, 25, 15, 68, 69, -3, -3, -3, -3, 62, 92, -95, 70, 71, -95, -95, -95, 28, 79, -95, -95, -95, -95, -95, -95, -95, -95, -95, 80, 72, 73, -95, -3, -95, 81, 83, 41, -95, -95, -95, -95, -3, -95 }; const unsigned char parser::yydefact_[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 34, 0, 10, 0, 0, 0, 0, 30, 0, 0, 0, 0, 0, 19, 20, 1, 4, 2, 18, 16, 17, 14, 9, 13, 11, 12, 6, 15, 8, 0, 0, 7, 0, 31, 0, 28, 29, 0, 0, 0, 36, 38, 35, 0, 0, 22, 0, 0, 0, 0, 32, 0, 58, 51, 21, 24, 0, 0, 46, 40, 39, 37, 55, 56, 0, 53, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 54, 0, 0, 52, 59, 50, 0, 0, 25, 48, 49, 47, 42, 43, 44, 45, 41, 0, 0, 0, 60, 0, 57, 0, 0, 0, 26, 61, 62, 23, 0, 27 }; const signed char parser::yypgoto_[] = { -95, -95, 87, -95, -95, -95, -95, -95, -95, -95, -95, -95, -95, -95, -95, -95, -95, 26, 16, -95, -94, -95, -95, 27, -95, -95, 12 }; const signed char parser::yydefgoto_[] = { -1, 11, 12, 13, 14, 15, 16, 81, 126, 17, 18, 19, 20, 21, 26, 66, 75, 83, 84, 22, 113, 23, 77, 78, 90, 92, 105 }; const unsigned char parser::yytable_[] = { 110, 111, 114, 115, 116, 54, 38, 27, 40, 73, 28, 24, 32, 1, 39, 37, 2, 3, 4, 36, 5, 43, 6, 7, 93, 94, 8, 25, 127, 44, 9, 55, 41, 10, 74, 1, 45, 132, 2, 3, 4, 112, 5, 46, 6, 7, 106, 107, 8, 29, 57, 30, 9, 59, 33, 10, 34, 31, 95, 96, 97, 98, 35, 58, 87, 88, 89, 102, 103, 76, 102, 103, 130, 131, 47, 48, 49, 50, 51, 52, 53, 56, 72, 60, 61, 108, 62, 68, 63, 64, 65, 67, 69, 71, 101, 118, 100, 91, 42, 85, 119, 120, 70, 76, 79, 80, 82, 99, 86, 122, 0, 123, 128, 109, 129, 117, 124, 125, 104, 121 }; const short parser::yycheck_[] = { 3, 4, 96, 97, 98, 6, 11, 25, 0, 7, 45, 28, 44, 5, 19, 6, 8, 9, 10, 16, 12, 25, 14, 15, 31, 32, 18, 44, 122, 25, 22, 32, 24, 25, 32, 5, 25, 131, 8, 9, 10, 44, 12, 25, 14, 15, 31, 32, 18, 11, 44, 13, 22, 21, 11, 25, 13, 19, 36, 37, 38, 39, 19, 44, 33, 34, 35, 42, 43, 44, 42, 43, 31, 32, 25, 25, 25, 25, 25, 25, 25, 25, 7, 44, 44, 17, 44, 30, 44, 44, 44, 44, 44, 30, 20, 3, 30, 32, 11, 73, 30, 30, 44, 44, 44, 44, 44, 40, 44, 30, -1, 31, 31, 44, 31, 99, 44, 44, 91, 107 }; const unsigned char parser::yystos_[] = { 0, 5, 8, 9, 10, 12, 14, 15, 18, 22, 25, 47, 48, 49, 50, 51, 52, 55, 56, 57, 58, 59, 65, 67, 28, 44, 60, 25, 45, 11, 13, 19, 44, 11, 13, 19, 16, 6, 11, 19, 0, 24, 48, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 6, 32, 25, 44, 44, 21, 44, 44, 44, 44, 44, 44, 61, 44, 30, 44, 44, 30, 7, 7, 32, 62, 44, 68, 69, 44, 44, 53, 44, 63, 64, 63, 44, 33, 34, 35, 70, 32, 71, 31, 32, 36, 37, 38, 39, 40, 30, 20, 42, 43, 69, 72, 31, 32, 17, 44, 3, 4, 44, 66, 66, 66, 66, 64, 3, 30, 30, 72, 30, 31, 44, 44, 54, 66, 31, 31, 31, 32, 66 }; const unsigned char parser::yyr1_[] = { 0, 46, 47, 47, 47, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 49, 49, 50, 51, 52, 53, 53, 54, 54, 55, 56, 57, 58, 59, 60, 60, 60, 61, 61, 62, 62, 63, 63, 64, 64, 64, 64, 65, 66, 66, 66, 67, 68, 68, 69, 69, 70, 70, 70, 71, 71, 71, 72, 72 }; const unsigned char parser::yyr2_[] = { 0, 2, 2, 1, 2, 1, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 4, 10, 1, 3, 1, 3, 3, 3, 2, 3, 5, 1, 1, 3, 1, 3, 0, 2, 1, 3, 3, 3, 3, 3, 5, 1, 1, 1, 7, 1, 3, 2, 3, 1, 1, 4, 0, 2, 3, 4, 4 }; // YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. // First, the terminals, then, starting at \a yyntokens_, nonterminals. const char* const parser::yytname_[] = { "$end", "error", "$undefined", "NUMBER", "DECIMAL", "SELECT", "FROM", "WHERE", "QUIT", "SOURCE", "CREATE", "TABLE", "USE", "DATABASE", "DROP", "INSERT", "INTO", "VALUES", "DELETE", "INDEX", "UNIQUE", "ON", "SHOW", "BLANK", "\"eof\"", "\";\"", "\"-\"", "\"+\"", "\"*\"", "\"/\"", "\"(\"", "\")\"", "\",\"", "\"int\"", "\"double\"", "\"char\"", "\"=\"", "\"<\"", "\">\"", "\"<>\"", "\"and\"", "\"or\"", "\"primary key\"", "\"foreign key\"", "STRING", "FILENAME", "$accept", "statement_list", "statement", "show_statement", "create_index_statement", "drop_index_statement", "insert_statement", "attr_list", "value_list", "drop_table_statement", "drop_db_statement", "use_statement", "create_db_statement", "select_statement", "select_list", "table_list", "select_condition", "select_condition_list", "select_condition_exp", "delete_statement", "exp", "create_table_statement", "attribute_list", "attribute_exp", "variant_type", "constrain_list", "constrain_exp", YY_NULLPTR }; #if YYDEBUG const unsigned char parser::yyrline_[] = { 0, 75, 75, 76, 77, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 98, 99, 103, 109, 115, 121, 122, 126, 127, 131, 135, 139, 143, 147, 157, 158, 159, 163, 164, 168, 169, 173, 174, 178, 179, 180, 181, 185, 191, 192, 193, 197, 207, 208, 212, 213, 217, 218, 219, 223, 224, 225, 229, 230 }; // Print the state stack on the debug stream. void parser::yystack_print_ () { *yycdebug_ << "Stack now"; for (stack_type::const_iterator i = yystack_.begin (), i_end = yystack_.end (); i != i_end; ++i) *yycdebug_ << ' ' << i->state; *yycdebug_ << '\n'; } // Report on the debug stream that the rule \a yyrule is going to be reduced. void parser::yy_reduce_print_ (int yyrule) { unsigned yylno = yyrline_[yyrule]; int yynrhs = yyr2_[yyrule]; // Print the symbols being reduced, and their result. *yycdebug_ << "Reducing stack by rule " << yyrule - 1 << " (line " << yylno << "):\n"; // The symbols being reduced. for (int yyi = 0; yyi < yynrhs; yyi++) YY_SYMBOL_PRINT (" $" << yyi + 1 << " =", yystack_[(yynrhs) - (yyi + 1)]); } #endif // YYDEBUG } // yy #line 1616 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.cpp" #line 233 "/Users/chenzhuo/Desktop/Working/DM/compiler/parser.y" void yy::parser::error (const location_type& l, const std::string& m) { throw Error(0, "Syntax Error: " + m); }
34.170252
209
0.562407
dmdecz
04e90aa196259a0992c63a9336d733d2b3ba37ce
274
cpp
C++
src/hsp3/linux/hsp3ext_linux.cpp
m4saka/OpenHSP
391f0a2100e701138d0610a5b94492d6f57ad1f2
[ "BSD-3-Clause" ]
null
null
null
src/hsp3/linux/hsp3ext_linux.cpp
m4saka/OpenHSP
391f0a2100e701138d0610a5b94492d6f57ad1f2
[ "BSD-3-Clause" ]
null
null
null
src/hsp3/linux/hsp3ext_linux.cpp
m4saka/OpenHSP
391f0a2100e701138d0610a5b94492d6f57ad1f2
[ "BSD-3-Clause" ]
null
null
null
// // HSP3 External program manager (dummy) // onion software/onitama 2004/6 // #include <stdio.h> #include <stdlib.h> #include <string.h> #include "hsp3ext_linux.h" void hsp3typeinit_dllcmd( HSP3TYPEINFO *info ) { } void hsp3typeinit_dllctrl( HSP3TYPEINFO *info ) { }
13.7
47
0.718978
m4saka
04e9e4057207faa5efe2c9538f8d03658fb50abb
5,244
hpp
C++
include/System/ComponentModel/EditorBrowsableAttribute.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/System/ComponentModel/EditorBrowsableAttribute.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/System/ComponentModel/EditorBrowsableAttribute.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Attribute #include "System/Attribute.hpp" // Including type: System.ComponentModel.EditorBrowsableState #include "System/ComponentModel/EditorBrowsableState.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Type namespace: System.ComponentModel namespace System::ComponentModel { // Forward declaring type: EditorBrowsableAttribute class EditorBrowsableAttribute; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::ComponentModel::EditorBrowsableAttribute); DEFINE_IL2CPP_ARG_TYPE(::System::ComponentModel::EditorBrowsableAttribute*, "System.ComponentModel", "EditorBrowsableAttribute"); // Type namespace: System.ComponentModel namespace System::ComponentModel { // Size: 0x14 #pragma pack(push, 1) // Autogenerated type: System.ComponentModel.EditorBrowsableAttribute // [TokenAttribute] Offset: FFFFFFFF // [AttributeUsageAttribute] Offset: 11B7034 class EditorBrowsableAttribute : public ::System::Attribute { public: #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private System.ComponentModel.EditorBrowsableState browsableState // Size: 0x4 // Offset: 0x10 ::System::ComponentModel::EditorBrowsableState browsableState; // Field size check static_assert(sizeof(::System::ComponentModel::EditorBrowsableState) == 0x4); public: // Creating conversion operator: operator ::System::ComponentModel::EditorBrowsableState constexpr operator ::System::ComponentModel::EditorBrowsableState() const noexcept { return browsableState; } // Get instance field reference: private System.ComponentModel.EditorBrowsableState browsableState ::System::ComponentModel::EditorBrowsableState& dyn_browsableState(); // public System.Void .ctor(System.ComponentModel.EditorBrowsableState state) // Offset: 0x1D5DD7C template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static EditorBrowsableAttribute* New_ctor(::System::ComponentModel::EditorBrowsableState state) { static auto ___internal__logger = ::Logger::get().WithContext("::System::ComponentModel::EditorBrowsableAttribute::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<EditorBrowsableAttribute*, creationType>(state))); } // public override System.Boolean Equals(System.Object obj) // Offset: 0x1D5DDA8 // Implemented from: System.Attribute // Base method: System.Boolean Attribute::Equals(System.Object obj) bool Equals(::Il2CppObject* obj); // public override System.Int32 GetHashCode() // Offset: 0x1D5DE44 // Implemented from: System.Attribute // Base method: System.Int32 Attribute::GetHashCode() int GetHashCode(); }; // System.ComponentModel.EditorBrowsableAttribute #pragma pack(pop) static check_size<sizeof(EditorBrowsableAttribute), 16 + sizeof(::System::ComponentModel::EditorBrowsableState)> __System_ComponentModel_EditorBrowsableAttributeSizeCheck; static_assert(sizeof(EditorBrowsableAttribute) == 0x14); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::ComponentModel::EditorBrowsableAttribute::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::ComponentModel::EditorBrowsableAttribute::Equals // Il2CppName: Equals template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::ComponentModel::EditorBrowsableAttribute::*)(::Il2CppObject*)>(&System::ComponentModel::EditorBrowsableAttribute::Equals)> { static const MethodInfo* get() { static auto* obj = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::ComponentModel::EditorBrowsableAttribute*), "Equals", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{obj}); } }; // Writing MetadataGetter for method: System::ComponentModel::EditorBrowsableAttribute::GetHashCode // Il2CppName: GetHashCode template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::ComponentModel::EditorBrowsableAttribute::*)()>(&System::ComponentModel::EditorBrowsableAttribute::GetHashCode)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::ComponentModel::EditorBrowsableAttribute*), "GetHashCode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
52.44
208
0.746568
RedBrumbler
04ea19b6bcee624c4eb7001cb0ca52b23154a017
2,017
cpp
C++
contests/leetcode-2020spring/d.cpp
Nightwish-cn/my_leetcode
40f206e346f3f734fb28f52b9cde0e0041436973
[ "MIT" ]
23
2020-03-30T05:44:56.000Z
2021-09-04T16:00:57.000Z
contests/leetcode-2020spring/d.cpp
Nightwish-cn/my_leetcode
40f206e346f3f734fb28f52b9cde0e0041436973
[ "MIT" ]
1
2020-05-10T15:04:05.000Z
2020-06-14T01:21:44.000Z
contests/leetcode-2020spring/d.cpp
Nightwish-cn/my_leetcode
40f206e346f3f734fb28f52b9cde0e0041436973
[ "MIT" ]
6
2020-03-30T05:45:04.000Z
2020-08-13T10:01:39.000Z
#include <bits/stdc++.h> #define INF 2000000000 using namespace std; typedef long long ll; int read(){ int f = 1, x = 0; char c = getchar(); while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();} while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar(); return f * x; } struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; bool isLeaf(TreeNode* root) { return root->left == NULL && root->right == NULL; } struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; template<typename T> ostream& operator << (ostream& os, const vector<T>& vec){ for (auto x: vec) os << x << " "; os << endl; return os; } template<typename T> ostream& operator << (ostream& os, const vector<vector<T>>& vec){ for (auto& v: vec){ for (auto x: v) os << x << " "; os << endl; } return os; } class Solution { bool vis[1000005]; queue<int> q; int step[1000005]; public: int minJump(vector<int>& jump) { memset(step, 0x3f, sizeof(step)); int cur = 0; vis[0] = true, q.push(0); step[0] = 0; int n = jump.size(); while (!q.empty()){ int h = q.front(); while (cur < h && cur < n){ while (cur < n && vis[cur]){ ++cur; } if (cur >= h || cur == n) break; step[cur] = step[h] + 1; vis[cur] = true; q.push(cur); } if (h + jump[h] < n){ if (!vis[h + jump[h]]){ vis[h + jump[h]] = true; step[h + jump[h]] = step[h] + 1; q.push(h + jump[h]);} }else return step[h]; } return 0; } }; Solution sol; void init(){ } void solve(){ // sol.convert(); } int main(){ init(); solve(); return 0; }
21.923913
67
0.446703
Nightwish-cn
04ea6d7dc99d806aa6e510ad4dbcc569c9ed63bf
1,490
cpp
C++
Sources/Sapphire/compute/dense/naive/NaiveCrossEntropy.cpp
sukim96/Sapphire
7eba047a376d2bfa6cc3182daa143cbe659a1c18
[ "MIT" ]
6
2021-07-06T10:52:33.000Z
2021-12-30T11:30:04.000Z
Sources/Sapphire/compute/dense/naive/NaiveCrossEntropy.cpp
sukim96/Sapphire
7eba047a376d2bfa6cc3182daa143cbe659a1c18
[ "MIT" ]
1
2022-01-07T12:18:03.000Z
2022-01-08T12:23:13.000Z
Sources/Sapphire/compute/dense/naive/NaiveCrossEntropy.cpp
sukim96/Sapphire
7eba047a376d2bfa6cc3182daa143cbe659a1c18
[ "MIT" ]
3
2021-12-05T06:21:50.000Z
2022-01-09T12:44:23.000Z
// Copyright (c) 2021, Justin Kim // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #define MIN_FLOAT 1.17549e-30f #include <Sapphire/compute/dense/naive/NaiveCrossEntropy.hpp> #include <cmath> #include <iostream> namespace Sapphire::Compute ::Dense::Naive { void CrossEntropy(float* y, const float* x, const float* label, int batchSize, int unitSize) { for (int i = 0; i < batchSize; ++i) { float sum = 0.0f; for (int j = 0; j < unitSize; ++j) { const auto idx = i * unitSize + j; const auto val = x[idx] == 0.0f ? MIN_FLOAT : x[idx]; sum -= label[idx] * logf(val); } y[i] = sum; } } void CrossEntropyBackward(float* dx, const float* x, const float* label, int batchSize, int unitSize) { for (int i = 0; i < batchSize; ++i) { for (int j = 0; j < unitSize; ++j) { const auto idx = i * unitSize + j; const auto val = x[idx] == 0.0f ? MIN_FLOAT : x[idx]; const auto outData = label[idx] / val; if (std::isnan(outData)) { std::cout << "nan detected" << std::endl; } dx[idx] -= outData; } } } }
28.113208
78
0.506711
sukim96
04eb0a954cad011f317dccf9516021c865a5a1e9
6,708
hpp
C++
include/rapidcheck/Show.hpp
bantamtools/rapidcheck
4187d901e786b1d89ab30e6b72ac1c0fc3d902cf
[ "BSD-2-Clause" ]
null
null
null
include/rapidcheck/Show.hpp
bantamtools/rapidcheck
4187d901e786b1d89ab30e6b72ac1c0fc3d902cf
[ "BSD-2-Clause" ]
1
2018-08-20T19:04:31.000Z
2018-08-20T19:04:31.000Z
include/rapidcheck/Show.hpp
bantamtools/rapidcheck
4187d901e786b1d89ab30e6b72ac1c0fc3d902cf
[ "BSD-2-Clause" ]
null
null
null
#pragma once #include <map> #include <vector> #include <deque> #include <forward_list> #include <list> #include <set> #include <unordered_set> #include <unordered_map> #include <memory> #include <cstdint> #include <type_traits> #include <array> #include <sstream> #include "rapidcheck/detail/Traits.h" namespace rc { namespace detail { template <typename TupleT, std::size_t I = std::tuple_size<TupleT>::value> struct TupleHelper; template <std::size_t I> struct TupleHelper<std::tuple<>, I> { static void showTuple(const std::tuple<> &tuple, std::ostream &os) {} }; template <typename TupleT> struct TupleHelper<TupleT, 1> { static void showTuple(const TupleT &tuple, std::ostream &os) { show(std::get<std::tuple_size<TupleT>::value - 1>(tuple), os); } }; template <typename TupleT, std::size_t I> struct TupleHelper { static void showTuple(const TupleT &tuple, std::ostream &os) { show(std::get<std::tuple_size<TupleT>::value - I>(tuple), os); os << ", "; TupleHelper<TupleT, I - 1>::showTuple(tuple, os); } }; template <typename T> void showValue(T value, typename std::enable_if<std::is_same<T, bool>::value, std::ostream>::type &os) { os << (value ? "true" : "false"); } template <typename T> void showValue(T value, typename std::enable_if<(std::is_same<T, char>::value || std::is_same<T, unsigned char>::value), std::ostream>::type &os) { os << static_cast<int>(value); } void showValue(const std::string &value, std::ostream &os); void showValue(const char *value, std::ostream &os); template <typename T> void showValue(T *p, std::ostream &os) { show(*p, os); auto flags = os.flags(); os << " (" << std::hex << std::showbase << p << ")"; os.flags(flags); } template <typename T, typename Deleter> void showValue(const std::unique_ptr<T, Deleter> &p, std::ostream &os) { show(p.get(), os); } template <typename T> void showValue(const std::shared_ptr<T> &p, std::ostream &os) { show(p.get(), os); } template <typename T1, typename T2> void showValue(const std::pair<T1, T2> &pair, std::ostream &os) { os << "("; show(pair.first, os); os << ", "; show(pair.second, os); os << ")"; } template <typename... Types> void showValue(const std::tuple<Types...> &tuple, std::ostream &os) { os << "("; detail::TupleHelper<std::tuple<Types...>>::showTuple(tuple, os); os << ")"; } template <typename T, typename Allocator> void showValue(const std::vector<T, Allocator> &value, std::ostream &os) { showCollection("[", "]", value, os); } template <typename T, typename Allocator> void showValue(const std::deque<T, Allocator> &value, std::ostream &os) { showCollection("[", "]", value, os); } template <typename T, typename Allocator> void showValue(const std::forward_list<T, Allocator> &value, std::ostream &os) { showCollection("[", "]", value, os); } template <typename T, typename Allocator> void showValue(const std::list<T, Allocator> &value, std::ostream &os) { showCollection("[", "]", value, os); } template <typename Key, typename Compare, typename Allocator> void showValue(const std::set<Key, Compare, Allocator> &value, std::ostream &os) { showCollection("{", "}", value, os); } template <typename Key, typename T, typename Compare, typename Allocator> void showValue(const std::map<Key, T, Compare, Allocator> &value, std::ostream &os) { showCollection("{", "}", value, os); } template <typename Key, typename Compare, typename Allocator> void showValue(const std::multiset<Key, Compare, Allocator> &value, std::ostream &os) { showCollection("{", "}", value, os); } template <typename Key, typename T, typename Compare, typename Allocator> void showValue(const std::multimap<Key, T, Compare, Allocator> &value, std::ostream &os) { showCollection("{", "}", value, os); } template <typename Key, typename Hash, typename KeyEqual, typename Allocator> void showValue(const std::unordered_set<Key, Hash, KeyEqual, Allocator> &value, std::ostream &os) { showCollection("{", "}", value, os); } template <typename Key, typename T, typename Hash, typename KeyEqual, typename Allocator> void showValue( const std::unordered_map<Key, T, Hash, KeyEqual, Allocator> &value, std::ostream &os) { showCollection("{", "}", value, os); } template <typename Key, typename Hash, typename KeyEqual, typename Allocator> void showValue( const std::unordered_multiset<Key, Hash, KeyEqual, Allocator> &value, std::ostream &os) { showCollection("{", "}", value, os); } template <typename Key, typename T, typename Hash, typename KeyEqual, typename Allocator> void showValue( const std::unordered_multimap<Key, T, Hash, KeyEqual, Allocator> &value, std::ostream &os) { showCollection("{", "}", value, os); } template <typename CharT, typename Traits, typename Allocator> void showValue(const std::basic_string<CharT, Traits, Allocator> &value, std::ostream &os) { showCollection("\"", "\"", value, os); } template <typename T, std::size_t N> void showValue(const std::array<T, N> &value, std::ostream &os) { showCollection("[", "]", value, os); } RC_SFINAE_TRAIT(HasShowValue, decltype(showValue(std::declval<T>(), std::cout))) template <typename T, bool = HasShowValue<T>::value, bool = IsStreamInsertible<T>::value> struct ShowDefault { static void show(const T & /*value*/, std::ostream &os) { os << "<\?\?\?>"; } }; template <typename T, bool X> struct ShowDefault<T, true, X> { static void show(const T &value, std::ostream &os) { showValue(value, os); } }; template <typename T> struct ShowDefault<T, false, true> { static void show(const T &value, std::ostream &os) { os << value; } }; } // namespace detail template <typename T> void show(const T &value, std::ostream &os) { detail::ShowDefault<T>::show(value, os); } template <typename T> std::string toString(const T &value) { std::ostringstream os; show(value, os); return os.str(); } template <typename Collection> void showCollection(const std::string &prefix, const std::string &suffix, const Collection &collection, std::ostream &os) { os << prefix; auto cbegin = begin(collection); auto cend = end(collection); if (cbegin != cend) { show(*cbegin, os); for (auto it = ++cbegin; it != cend; it++) { os << ", "; show(*it, os); } } os << suffix; } } // namespace rc
27.95
80
0.634466
bantamtools
04ed2a486a5f78dc27419c7a37bdacc4ba8b362a
3,785
cpp
C++
Minecraft_Advancements/settings/database.cpp
Chucky2401/Minecraft-Advancements
623a8923792af7925738b3db2a3f8590e92a32fb
[ "Apache-2.0" ]
2
2020-06-24T19:07:36.000Z
2020-11-10T12:04:35.000Z
Minecraft_Advancements/settings/database.cpp
Chucky2401/Minecraft-Advancements
623a8923792af7925738b3db2a3f8590e92a32fb
[ "Apache-2.0" ]
19
2020-05-08T10:50:53.000Z
2020-08-19T14:18:52.000Z
Minecraft_Advancements/settings/database.cpp
Chucky2401/Minecraft-Advancements
623a8923792af7925738b3db2a3f8590e92a32fb
[ "Apache-2.0" ]
1
2021-05-21T13:27:04.000Z
2021-05-21T13:27:04.000Z
#include "database.h" database::database() { } database::~database() { this->base.close(); } void database::initialisation(bool test) { param.initialisation(test); } /* * Fonction d'ouverture de la connexion à la Base de données */ bool database::createConnection(QString name) { bool bCreationReussi = false; bool bConnexionReussi = false; bool bDossier = false; this->base = QSqlDatabase::addDatabase("QSQLITE", name); this->resetAll(); if(!QDir(param.getBddPath()).exists()){ qDebug() << "Le dossier pour la BDD n'existe pas"; qInfo() << "Création dossier pour la BDD"; if(QDir().mkdir(param.getBddPath())) { qInfo() << "Création dossier pour la BDD OK"; bDossier = true; } else { setError("La création du dossier pour la base a échoué."); qCritical() << "Création dossier pour la BDD KO"; } } else { bDossier = true; } if(bDossier && !QFile::exists(param.getBddPath()+param.getBddName())){ qDebug() << param.getBddPath() + param.getBddName() << " - La base n'existe pas ! / " << name; QFile qfBaseDeDonnees(param.getBddPath() + param.getBddName()); qfBaseDeDonnees.open(QIODevice::WriteOnly); qfBaseDeDonnees.close(); this->base.setDatabaseName(param.getBddPath()+param.getBddName()); if (!this->base.open()) { setError("La base n'a pas pu être créé"); bConnexionReussi = false; } else { bConnexionReussi = true; } if(bConnexionReussi){ bCreationReussi = initialisationTable(); if(!bCreationReussi){ setError("La base n'existe pas ou son initialisation a échoué"); bConnexionReussi = false; } } } else { this->base.setDatabaseName(param.getBddPath()+param.getBddName()); if (!this->base.open()) { setError(this->base.lastError().text()); bConnexionReussi = false; } else { bConnexionReussi = true; } } return bConnexionReussi; } bool database::initialisationTable(){ QFile qfSqlCreation(":/files/minecraft_Advancements.sql"); QByteArray line; QSqlQuery query(this->base); bool bExecutionRequeteEchoue = false; if(!qfSqlCreation.open(QIODevice::ReadOnly)) qDebug() << "Echec Ouverture"; startTransaction(); while(!qfSqlCreation.atEnd()){ line = qfSqlCreation.readLine(); if(!bExecutionRequeteEchoue){ qDebug() << line; if(!query.exec(line)){ bExecutionRequeteEchoue = true; } } } stopTransaction(bExecutionRequeteEchoue); qfSqlCreation.close(); return !bExecutionRequeteEchoue; } void database::closeConnection(QString name){ QSqlDatabase::database(name); this->base.close(); this->base.removeDatabase(name); } bool database::isOpen(QString name){ QSqlDatabase::database(name); return base.isOpen(); } QSqlDatabase database::getBase(){ return this->base; } QSqlDriver* database::getDriver() { return this->base.driver(); } void database::resetAll(){ resetError(); } void database::resetError(){ this->lastBddError = ""; } QString database::getError(){ return this->lastBddError; } void database::setError(QString error){ this->lastBddError = error; } void database::startTransaction(){ this->base.transaction(); } void database::stopTransaction(bool error){ if (error){ bool retour = this->base.rollback(); qDebug() << "Rollback / " << retour; } else { bool retour = this->base.commit(); qDebug() << "Commit / " << retour; } }
25.402685
102
0.602114
Chucky2401
04ed4e52ad916c362db9388ca495e7ecff2eaba7
954
cpp
C++
src/main.cpp
mojyack/ResourceWrapper
2bede6c7c43f737aef27f6e0db558a56569492d4
[ "MIT" ]
null
null
null
src/main.cpp
mojyack/ResourceWrapper
2bede6c7c43f737aef27f6e0db558a56569492d4
[ "MIT" ]
null
null
null
src/main.cpp
mojyack/ResourceWrapper
2bede6c7c43f737aef27f6e0db558a56569492d4
[ "MIT" ]
null
null
null
#include <array> #include <Windows.h> #include "hook/error.hpp" #include "hook/hook.hpp" namespace { auto execute(PROCESS_INFORMATION& info, const wchar_t* const path) { auto startup = STARTUPINFOW{0}; return CreateProcessW( path, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &startup, &info) != FALSE; } } // namespace extern "C" __declspec(dllexport) auto CALLBACK RunW([[maybe_unused]] const HWND hWnd, const HINSTANCE hInstance, const LPWSTR lpszCmdline, [[maybe_unused]] const int nCmdShow) -> void { auto info = PROCESS_INFORMATION{0}; ASSERT(execute(info, lpszCmdline), "failed to launch target") hook::inject(info.hProcess); ResumeThread(info.hThread); CloseHandle(info.hThread); CloseHandle(info.hProcess); }
27.257143
186
0.578616
mojyack
04f697acc86401872c11c4c15b7534d3e0c20ea4
3,087
cpp
C++
example/math/src/math_expm1f.cpp
zhouyan/MCKL
1d03eb5a879e47e268efc73b1d433611e64307b3
[ "BSD-2-Clause" ]
12
2016-08-02T17:01:13.000Z
2021-03-04T12:11:33.000Z
example/math/src/math_expm1f.cpp
zhouyan/MCKL
1d03eb5a879e47e268efc73b1d433611e64307b3
[ "BSD-2-Clause" ]
5
2017-05-09T12:05:06.000Z
2021-03-16T10:39:23.000Z
example/math/src/math_expm1f.cpp
zhouyan/MCKL
1d03eb5a879e47e268efc73b1d433611e64307b3
[ "BSD-2-Clause" ]
2
2016-08-25T13:10:29.000Z
2019-05-01T01:54:29.000Z
//============================================================================ // MCKL/example/math/src/math_expm1f.cpp //---------------------------------------------------------------------------- // MCKL: Monte Carlo Kernel Library //---------------------------------------------------------------------------- // Copyright (c) 2013-2018, Yan Zhou // 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. // // 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 "math_asm.hpp" MCKL_EXAMPLE_DEFINE_MATH_ASM(A1R1, float, expm1, vs_expm1) int main(int argc, char **argv) { union { std::uint32_t u; float x; }; u = 0xC2AEAC4FU; union { std::uint32_t v; float y; }; v = 0x42B0C0A5U; const float ln2 = static_cast<float>(std::log(2.0l)); const float ln2by2 = static_cast<float>(std::log(2.0l) / 2.0l); math_asm_vs_expm1_check(u, v); mckl::Vector<MathBound<float>> bounds; bounds.push_back(MathBound<float>(x, -87)); bounds.push_back(MathBound<float>(-87, -70)); bounds.push_back(MathBound<float>(-70, -1)); bounds.push_back(MathBound<float>(-1, -ln2, "", "-ln(2)")); bounds.push_back(MathBound<float>(-ln2, -ln2by2, "-ln(2)", "-ln(2) / 2")); bounds.push_back(MathBound<float>(-ln2by2, -FLT_MIN, "-ln(2) / 2")); bounds.push_back(MathBound<float>(-FLT_MIN, FLT_MIN)); bounds.push_back(MathBound<float>(FLT_MIN, ln2by2, "", "ln(2) / 2")); bounds.push_back(MathBound<float>(ln2by2, ln2, "ln(2) / 2", "ln(2)")); bounds.push_back(MathBound<float>(ln2, 1, "ln(2)")); bounds.push_back(MathBound<float>(1, 70)); bounds.push_back(MathBound<float>(70, 87)); bounds.push_back(MathBound<float>(87, y)); math_asm(argc, argv, math_asm_vs_expm1, bounds); return 0; }
42.287671
78
0.630062
zhouyan
04fbf7d66ba3b8e08e4dde69f6c770967d24f055
758
cpp
C++
src/commands/fade_music_command.cpp
GhostInABottle/octopus_engine
50429e889493527bdc0e78b307937002e0f2c510
[ "BSD-2-Clause" ]
3
2017-10-02T03:18:59.000Z
2020-11-01T09:21:28.000Z
src/commands/fade_music_command.cpp
GhostInABottle/octopus_engine
50429e889493527bdc0e78b307937002e0f2c510
[ "BSD-2-Clause" ]
2
2019-04-06T21:48:08.000Z
2020-05-22T23:38:54.000Z
src/commands/fade_music_command.cpp
GhostInABottle/octopus_engine
50429e889493527bdc0e78b307937002e0f2c510
[ "BSD-2-Clause" ]
1
2017-07-17T20:58:26.000Z
2017-07-17T20:58:26.000Z
#include "../../include/commands/fade_music_command.hpp" #include "../../include/game.hpp" #include "../../include/utility/math.hpp" #include "../../include/xd/audio.hpp" Fade_Music_Command::Fade_Music_Command(Game& game, float volume, long duration) : Timed_Command(game, duration), music(game.get_playing_music()), old_volume(game.get_playing_music()->get_volume()), new_volume(volume), complete(false) {} void Fade_Music_Command::execute() { auto music_ptr = music.lock(); complete = stopped || !music_ptr || is_done(); if (!music_ptr) return; float alpha = get_alpha(complete); music_ptr->set_volume(lerp(old_volume, new_volume, alpha)); } bool Fade_Music_Command::is_complete() const { return complete; }
30.32
81
0.699208
GhostInABottle
ca088414aef7ec18e30c591538973ef84368dd73
1,460
cpp
C++
Project/zoolib/GameEngine/Cog_Indirect.cpp
ElectricMagic/zoolib_cxx
cb3ccfde931b3989cd420fa093153204a7899805
[ "MIT" ]
13
2015-01-28T21:05:09.000Z
2021-11-03T22:21:11.000Z
Project/zoolib/GameEngine/Cog_Indirect.cpp
ElectricMagic/zoolib_cxx
cb3ccfde931b3989cd420fa093153204a7899805
[ "MIT" ]
null
null
null
Project/zoolib/GameEngine/Cog_Indirect.cpp
ElectricMagic/zoolib_cxx
cb3ccfde931b3989cd420fa093153204a7899805
[ "MIT" ]
4
2018-11-16T08:33:33.000Z
2021-12-11T19:40:46.000Z
// Copyright (c) 2019 Andrew Green. MIT License. http://www.zoolib.org #include "zoolib/GameEngine/Cog_Indirect.h" #include "zoolib/Callable_Indirect.h" namespace ZooLib { namespace GameEngine { // ================================================================================================= #pragma mark - sCog_Indirect typedef Callable_Indirect<Cog::Signature> Callable_Indirect_Cog; void sSetIndirect(const Cog& iLHS, const Cog& iRHS) { if (ZP<Callable_Indirect_Cog> theIndirect = iLHS.DynamicCast<Callable_Indirect_Cog>()) theIndirect->Set(iRHS); else ZAssert(not iLHS); } Cog sCog_Indirect() { return sCallable_Indirect<Cog::Signature>().StaticCast<Cog::Callable>(); } Cog sCog_Indirect(Seq& ioSeq) { Cog theCog = sCog_Indirect(); ioSeq.Append(theCog); return theCog; } static Cog spCogFun_KillIndirects(const Cog& iSelf, const Param& iParam, SharedState_Mutable& ioState, const string8& iName) { Seq theSeq = ioState.Get<Seq>(iName); for (size_t x = 0, count = theSeq.Count(); x < count; ++x) { if (ZP<Callable_Indirect_Cog> theCallable = theSeq.Get<Cog>(x).DynamicCast<Callable_Indirect<Cog::Signature> >()) { theCallable->Set(null); } } ioState.Erase(iName); return true; } Cog sCog_KillIndirects(SharedState_Mutable& ioState, const string8& iName) { GEMACRO_Callable(spCallable, spCogFun_KillIndirects); return sBindR(spCallable, ioState, iName); } } // namespace GameEngine } // namespace ZooLib
25.172414
100
0.689041
ElectricMagic
ca09938c2377f316f4322d9f8973721a7d7388c8
4,311
cpp
C++
pxr/imaging/plugin/hdRpr/renderPass.cpp
superkomar/RadeonProRenderUSD
6b1db21768038a1f0a35c331369cd2e1f823df48
[ "Apache-2.0" ]
1
2021-08-20T01:16:36.000Z
2021-08-20T01:16:36.000Z
pxr/imaging/plugin/hdRpr/renderPass.cpp
superkomar/RadeonProRenderUSD
6b1db21768038a1f0a35c331369cd2e1f823df48
[ "Apache-2.0" ]
1
2021-04-03T09:38:59.000Z
2021-04-03T09:38:59.000Z
pxr/imaging/plugin/hdRpr/renderPass.cpp
superkomar/RadeonProRenderUSD
6b1db21768038a1f0a35c331369cd2e1f823df48
[ "Apache-2.0" ]
null
null
null
/************************************************************************ Copyright 2020 Advanced Micro Devices, Inc 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 "renderPass.h" #include "renderDelegate.h" #include "config.h" #include "rprApi.h" #include "renderBuffer.h" #include "renderParam.h" #include "pxr/imaging/hd/renderPassState.h" #include "pxr/imaging/hd/renderIndex.h" PXR_NAMESPACE_OPEN_SCOPE HdRprRenderPass::HdRprRenderPass(HdRenderIndex* index, HdRprimCollection const& collection, HdRprRenderParam* renderParam) : HdRenderPass(index, collection) , m_renderParam(renderParam) { } HdRprRenderPass::~HdRprRenderPass() { m_renderParam->GetRenderThread()->StopRender(); } static GfVec2i GetViewportSize(HdRenderPassStateSharedPtr const& renderPassState) { #if PXR_VERSION >= 2102 // XXX (RPR): there is no way to efficiently handle thew new camera framing API with RPR const CameraUtilFraming &framing = renderPassState->GetFraming(); if (framing.IsValid()) { return framing.dataWindow.GetSize(); } #endif // For applications that use the old viewport API instead of // the new camera framing API. const GfVec4f vp = renderPassState->GetViewport(); return GfVec2i(int(vp[2]), int(vp[3])); } void HdRprRenderPass::_Execute(HdRenderPassStateSharedPtr const& renderPassState, TfTokenVector const& renderTags) { // To avoid potential deadlock: // main thread locks config instance and requests render stop and // in the same time render thread trying to lock config instance to update its settings. // We should release config instance lock before requesting render thread to stop. // It could be solved in another way by using shared_mutex and // marking current write-lock as read-only after successful config->Sync // in such a way main and render threads would have read-only-locks that could coexist bool stopRender = false; { HdRprConfig* config; auto configInstanceLock = HdRprConfig::GetInstance(&config); config->Sync(GetRenderIndex()->GetRenderDelegate()); if (config->IsDirty(HdRprConfig::DirtyAll)) { stopRender = true; } } if (stopRender) { m_renderParam->GetRenderThread()->StopRender(); } auto rprApiConst = m_renderParam->GetRprApi(); GfVec2i newViewportSize = GetViewportSize(renderPassState); auto oldViewportSize = rprApiConst->GetViewportSize(); if (oldViewportSize != newViewportSize) { m_renderParam->AcquireRprApiForEdit()->SetViewportSize(newViewportSize); } if (rprApiConst->GetAovBindings() != renderPassState->GetAovBindings()) { m_renderParam->AcquireRprApiForEdit()->SetAovBindings(renderPassState->GetAovBindings()); } if (rprApiConst->GetCamera() != renderPassState->GetCamera()) { m_renderParam->AcquireRprApiForEdit()->SetCamera(renderPassState->GetCamera()); } if (rprApiConst->IsChanged() || m_renderParam->IsRenderShouldBeRestarted()) { for (auto& aovBinding : renderPassState->GetAovBindings()) { if (aovBinding.renderBuffer) { auto rprRenderBuffer = static_cast<HdRprRenderBuffer*>(aovBinding.renderBuffer); rprRenderBuffer->SetConverged(false); } } m_renderParam->GetRenderThread()->StartRender(); } } bool HdRprRenderPass::IsConverged() const { for (auto& aovBinding : m_renderParam->GetRprApi()->GetAovBindings()) { if (aovBinding.renderBuffer && !aovBinding.renderBuffer->IsConverged()) { return false; } } return true; } PXR_NAMESPACE_CLOSE_SCOPE
38.150442
116
0.677801
superkomar
ca1338da23e44252e723e9fe92f9784bdc41c7a1
763
hpp
C++
clstatphys/clstatphys/physics/fixed_boundary_normalmode.hpp
FIshikawa/ClassicalStatPhys
e4010480d3c7977829c1b3fdeaf51401a2409373
[ "MIT" ]
null
null
null
clstatphys/clstatphys/physics/fixed_boundary_normalmode.hpp
FIshikawa/ClassicalStatPhys
e4010480d3c7977829c1b3fdeaf51401a2409373
[ "MIT" ]
2
2020-01-21T08:54:05.000Z
2020-01-21T09:29:10.000Z
clstatphys/clstatphys/physics/fixed_boundary_normalmode.hpp
FIshikawa/ClassicalStatPhys
e4010480d3c7977829c1b3fdeaf51401a2409373
[ "MIT" ]
2
2020-07-18T03:36:32.000Z
2021-07-21T22:58:27.000Z
#ifndef FIXED_BOUNDARY_NORMALMODE_HPP #define FIXED_BOUNDARY_NORMALMODE_HPP #include <vector> void FixedBoundaryNormalMode(const std::vector<double>& z, std::vector<double>& z_k){ int num_particles = z.size() / 2; const double *x = &z[0]; const double *p = &z[num_particles]; double *x_k = &z_k[0]; double *p_k = &z_k[num_particles]; double normalize_constant = std::sqrt(2.0/(num_particles+1)); for(int i = 0; i < num_particles; ++i){ p_k[i] = 0; x_k[i] = 0; for(int j = 0 ; j < num_particles; ++j){ p_k[i] += normalize_constant * p[j] * std::sin(M_PI*(i+1)*(j+1)/(num_particles+1)); x_k[i] += normalize_constant * x[j] * std::sin(M_PI*(i+1)*(j+1)/(num_particles+1)); } } } #endif //FIXED_BOUNDARY_NORMALMODE_HPP
29.346154
89
0.642202
FIshikawa
ca139d93fca4d0cf3c52ef8f0a7655d8a8991cc6
8,707
cpp
C++
db/silkworm/trie/db_trie.cpp
flashbots/silkworm
7770793499d0c665754b17840f7b8edfd53ce8ba
[ "Apache-2.0" ]
1
2021-06-30T22:56:09.000Z
2021-06-30T22:56:09.000Z
db/silkworm/trie/db_trie.cpp
flashbots/silkworm
7770793499d0c665754b17840f7b8edfd53ce8ba
[ "Apache-2.0" ]
null
null
null
db/silkworm/trie/db_trie.cpp
flashbots/silkworm
7770793499d0c665754b17840f7b8edfd53ce8ba
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021 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. */ #include "db_trie.hpp" #include <bitset> #include <boost/endian/conversion.hpp> #include <silkworm/common/log.hpp> #include <silkworm/db/tables.hpp> namespace silkworm::trie { AccountTrieCursor::AccountTrieCursor(lmdb::Transaction&) {} Bytes AccountTrieCursor::first_uncovered_prefix() { // TODO[Issue 179] implement return {}; } std::optional<Bytes> AccountTrieCursor::key() const { // TODO[Issue 179] implement return std::nullopt; } void AccountTrieCursor::next() { // TODO[Issue 179] implement } bool AccountTrieCursor::can_skip_state() const { // TODO[Issue 179] implement return false; } StorageTrieCursor::StorageTrieCursor(lmdb::Transaction&) {} Bytes StorageTrieCursor::seek_to_account(ByteView) { // TODO[Issue 179] implement return {}; } Bytes StorageTrieCursor::first_uncovered_prefix() { // TODO[Issue 179] implement return Bytes(1, '\0'); } std::optional<Bytes> StorageTrieCursor::key() const { // TODO[Issue 179] implement return std::nullopt; } void StorageTrieCursor::next() { // TODO[Issue 179] implement } bool StorageTrieCursor::can_skip_state() const { // TODO[Issue 179] implement return false; } DbTrieLoader::DbTrieLoader(lmdb::Transaction& txn, etl::Collector& account_collector, etl::Collector& storage_collector) : txn_{txn}, storage_collector_{storage_collector} { hb_.node_collector = [&account_collector](ByteView unpacked_key, const Node& node) { if (unpacked_key.empty()) { return; } etl::Entry e; e.key = unpacked_key; e.value = marshal_node(node); account_collector.collect(e); }; } // calculate_root algo: // for iterateIHOfAccounts { // if canSkipState // goto use_account_trie // // for iterateAccounts from prevIH to currentIH { // use(account) // for iterateIHOfStorage within accountWithIncarnation{ // if canSkipState // goto use_storage_trie // // for iterateStorage from prevIHOfStorage to currentIHOfStorage { // use(storage) // } // use_storage_trie: // use(ihStorage) // } // } // use_account_trie: // use(AccTrie) // } evmc::bytes32 DbTrieLoader::calculate_root() { auto acc_state{txn_.open(db::table::kHashedAccounts)}; auto storage_state{txn_.open(db::table::kHashedStorage)}; StorageTrieCursor storage_trie{txn_}; for (AccountTrieCursor acc_trie{txn_};; acc_trie.next()) { if (acc_trie.can_skip_state()) { goto use_account_trie; } for (auto a{acc_state->seek(acc_trie.first_uncovered_prefix())}; a.has_value(); a = acc_state->get_next()) { const Bytes unpacked_key{unpack_nibbles(a->key)}; if (acc_trie.key().has_value() && acc_trie.key().value() < unpacked_key) { break; } const auto [account, err]{decode_account_from_storage(a->value)}; if (err != rlp::DecodingResult::kOk) { throw err; } evmc::bytes32 storage_root{kEmptyRoot}; if (account.incarnation) { const Bytes acc_with_inc{db::storage_prefix(a->key, account.incarnation)}; HashBuilder storage_hb; storage_hb.node_collector = [&](ByteView unpacked_key, const Node& node) { etl::Entry e{acc_with_inc, marshal_node(node)}; e.key.append(unpacked_key); storage_collector_.collect(e); }; for (storage_trie.seek_to_account(acc_with_inc);; storage_trie.next()) { if (storage_trie.can_skip_state()) { goto use_storage_trie; } for (auto s{storage_state->seek_dup(acc_with_inc, storage_trie.first_uncovered_prefix())}; s.has_value(); s = storage_state->get_next_dup()) { const ByteView packed_loc{s->substr(0, kHashLength)}; const ByteView value{s->substr(kHashLength)}; const Bytes unpacked_loc{unpack_nibbles(packed_loc)}; if (storage_trie.key().has_value() && storage_trie.key().value() < unpacked_loc) { break; } rlp_.clear(); rlp::encode(rlp_, value); storage_hb.add(packed_loc, rlp_); } use_storage_trie: if (!storage_trie.key().has_value()) { break; } // TODO[Issue 179] use storage trie } storage_root = storage_hb.root_hash(); } hb_.add(a->key, account.rlp(storage_root)); } use_account_trie: if (!acc_trie.key().has_value()) { break; } // TODO[Issue 179] use account trie } return hb_.root_hash(); } Bytes marshal_node(const Node& n) { size_t buf_size{/* 3 masks state/tree/hash 2 bytes each */ 6 + /* root hash */ (n.root_hash().has_value() ? kHashLength : 0u) + /* hashes */ n.hashes().size() * kHashLength}; Bytes buf(buf_size, '\0'); size_t pos{0}; boost::endian::store_big_u16(&buf[pos], n.state_mask()); pos += 2; boost::endian::store_big_u16(&buf[pos], n.tree_mask()); pos += 2; boost::endian::store_big_u16(&buf[pos], n.hash_mask()); pos += 2; if (n.root_hash().has_value()) { std::memcpy(&buf[pos], n.root_hash()->bytes, kHashLength); pos += kHashLength; } for (const auto& hash : n.hashes()) { std::memcpy(&buf[pos], hash.bytes, kHashLength); pos += kHashLength; } return buf; } Node unmarshal_node(ByteView v) { if (v.length() < 6) { // At least state/tree/hash masks need to be present throw std::invalid_argument("unmarshal_node : input too short"); } else { // Beyond the 6th byte the length must be a multiple of // kHashLength if ((v.length() - 6) % kHashLength) { throw std::invalid_argument("unmarshal_node : input len is invalid"); } } const auto state_mask{boost::endian::load_big_u16(v.data())}; v.remove_prefix(2); const auto tree_mask{boost::endian::load_big_u16(v.data())}; v.remove_prefix(2); const auto hash_mask{boost::endian::load_big_u16(v.data())}; v.remove_prefix(2); std::optional<evmc::bytes32> root_hash{std::nullopt}; if (std::bitset<16>(hash_mask).count() + 1 == v.length() / kHashLength) { root_hash = evmc::bytes32{}; std::memcpy(root_hash->bytes, v.data(), kHashLength); v.remove_prefix(kHashLength); } const size_t num_hashes{v.length() / kHashLength}; std::vector<evmc::bytes32> hashes(num_hashes); for (size_t i{0}; i < num_hashes; ++i) { std::memcpy(hashes[i].bytes, v.data(), kHashLength); v.remove_prefix(kHashLength); } return {state_mask, tree_mask, hash_mask, hashes, root_hash}; } evmc::bytes32 regenerate_db_tries(lmdb::Transaction& txn, const char* tmp_dir, const evmc::bytes32* expected_root) { etl::Collector account_collector{tmp_dir}; etl::Collector storage_collector{tmp_dir}; DbTrieLoader loader{txn, account_collector, storage_collector}; const evmc::bytes32 root{loader.calculate_root()}; if (expected_root && root != *expected_root) { SILKWORM_LOG(LogLevel::Error) << "Wrong trie root: " << to_hex(root) << ", expected: " << to_hex(*expected_root) << "\n"; throw WrongRoot{}; } auto account_tbl{txn.open(db::table::kTrieOfAccounts)}; account_collector.load(account_tbl.get()); auto storage_tbl{txn.open(db::table::kTrieOfStorage)}; storage_collector.load(storage_tbl.get()); return root; } } // namespace silkworm::trie
32.129151
120
0.6017
flashbots
ca154c34c94f3b2f621d8c7c6d878634797ab92c
179
hpp
C++
vendor/bindgen/tests/headers/templateref_opaque.hpp
mrkatebzadeh/rust-ibverbs
c0ea14f0e35be179a0370a7312b5fa07032adb27
[ "Apache-2.0", "MIT" ]
null
null
null
vendor/bindgen/tests/headers/templateref_opaque.hpp
mrkatebzadeh/rust-ibverbs
c0ea14f0e35be179a0370a7312b5fa07032adb27
[ "Apache-2.0", "MIT" ]
null
null
null
vendor/bindgen/tests/headers/templateref_opaque.hpp
mrkatebzadeh/rust-ibverbs
c0ea14f0e35be179a0370a7312b5fa07032adb27
[ "Apache-2.0", "MIT" ]
1
2021-02-02T10:49:21.000Z
2021-02-02T10:49:21.000Z
namespace detail { template<typename T> struct PointerType { typedef T* Type; }; } template<typename T> class UniquePtr { typedef typename detail::PointerType<T> Pointer; };
14.916667
50
0.73743
mrkatebzadeh
ca158d0b40a42ed2498685558f018116a563c158
2,490
cc
C++
game/src/gui/app/unit_list_view.cc
wateret/mengde
03c1894603b76916351550d03df8f4af38eb4ca6
[ "MIT" ]
24
2018-03-02T03:37:09.000Z
2021-08-18T02:34:23.000Z
game/src/gui/app/unit_list_view.cc
wateret/mengde
03c1894603b76916351550d03df8f4af38eb4ca6
[ "MIT" ]
99
2018-03-04T06:50:14.000Z
2019-08-25T09:02:20.000Z
game/src/gui/app/unit_list_view.cc
wateret/mengde
03c1894603b76916351550d03df8f4af38eb4ca6
[ "MIT" ]
9
2018-03-02T03:36:55.000Z
2019-02-27T07:11:28.000Z
#include "unit_list_view.h" #include "core/unit.h" #include "gui/uifw/button_view.h" #include "gui/uifw/scroll_view.h" #include "gui/uifw/text_view.h" #include "gui/uifw/vertical_list_view.h" namespace mengde { namespace gui { namespace app { UnitListView::UnitDetailView::UnitDetailView(const Rect& frame) : CompositeView(frame), unit_(nullptr), tv_name_(nullptr) { Rect tv_name_frame({0, 0}, {200, 100}); tv_name_ = new TextView(tv_name_frame); AddChild(tv_name_); } void UnitListView::UnitDetailView::SetUnit(const core::Unit* unit) { unit_ = unit; string name = unit->id(); tv_name_->SetText(name); } UnitListView::UnitListView(const Rect& frame, const vector<const core::Unit*>& unit_list) : CompositeView(frame), unit_list_(unit_list), unit_detail_view_(nullptr) { padding(8); bg_color(COLOR("darkgray")); const int margin = 8; const Vec2D btn_close_size = {150, 24}; const Vec2D list_view_size = {btn_close_size.x, GetActualFrameSize().y - (btn_close_size.y + margin)}; { Rect btn_close_frame({0, list_view_size.y + margin}, btn_close_size); ButtonView* btn_close = new ButtonView(&btn_close_frame, "Close"); btn_close->SetMouseButtonHandler([this](const foundation::MouseButtonEvent& e) { if (e.IsLeftButtonUp()) { this->visible(false); } return true; }); AddChild(btn_close); } { const int element_height = 24; Rect list_view_frame({0, 0}, list_view_size); VerticalListView* list_view = new VerticalListView(list_view_frame); for (auto unit : unit_list_) { std::string name = unit->id(); Rect button_frame({0, 0}, {list_view_size.x, element_height}); ButtonView* button = new ButtonView(&button_frame, name); button->SetMouseButtonHandler([this, unit](const foundation::MouseButtonEvent& e) { if (e.IsLeftButtonUp()) { this->SetUnit(unit); } return true; }); list_view->AddElement(button); } View* list_view_wrap = new ScrollView(list_view_frame, list_view); list_view_wrap->bg_color(COLOR("navy")); AddChild(list_view_wrap); } { const int udv_frame_x = list_view_size.x + 8; Rect cv_frame(udv_frame_x, 0, GetActualFrameSize().x - udv_frame_x, GetActualFrameSize().y); unit_detail_view_ = new UnitDetailView(cv_frame); unit_detail_view_->bg_color(COLOR("gray")); AddChild(unit_detail_view_); } } } // namespace app } // namespace gui } // namespace mengde
30.365854
104
0.687952
wateret
ca1a301277a8e8b0c83a241099f6583ca2697451
959
cpp
C++
src/utils/tst/Crc32Test.cpp
tuncalie/amazon-kinesis-video-streams-pic
f792b7da65c4f3a26ac211dcfa9fa060b1a02610
[ "Apache-2.0" ]
29
2020-02-14T22:35:59.000Z
2022-02-04T14:19:09.000Z
src/utils/tst/Crc32Test.cpp
tuncalie/amazon-kinesis-video-streams-pic
f792b7da65c4f3a26ac211dcfa9fa060b1a02610
[ "Apache-2.0" ]
137
2020-01-28T23:24:43.000Z
2022-03-21T05:06:53.000Z
src/utils/tst/Crc32Test.cpp
tuncalie/amazon-kinesis-video-streams-pic
f792b7da65c4f3a26ac211dcfa9fa060b1a02610
[ "Apache-2.0" ]
31
2020-02-24T19:47:41.000Z
2022-03-30T08:50:45.000Z
#include "UtilTestFixture.h" class Crc32Test : public UtilTestBase { }; TEST_F(Crc32Test, crc32FunctionalityTest) { PCHAR testString = (PCHAR) "testString"; PCHAR testStringNum = (PCHAR) "12345"; PCHAR testStringSingleChar = (PCHAR) "a"; PCHAR testStringLong = (PCHAR) "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; EXPECT_EQ((UINT32) 0, COMPUTE_CRC32((PBYTE) "", 0)); EXPECT_EQ((UINT32) 0, COMPUTE_CRC32(NULL, 0)); EXPECT_EQ((UINT32) 0, COMPUTE_CRC32(NULL, 2)); EXPECT_EQ((UINT32) 0xcbf53a1c, COMPUTE_CRC32((PBYTE) testStringNum, (UINT32) STRLEN(testStringNum))); EXPECT_EQ((UINT32) 0x18f4fd08, COMPUTE_CRC32((PBYTE) testString, (UINT32) STRLEN(testString))); EXPECT_EQ((UINT32) 0xe8b7be43, COMPUTE_CRC32((PBYTE) testStringSingleChar, (UINT32) STRLEN(testStringSingleChar))); EXPECT_EQ((UINT32) 0x46619d26, COMPUTE_CRC32((PBYTE) testStringLong, (UINT32) STRLEN(testStringLong))); }
45.666667
119
0.744526
tuncalie
ca1c7ef2de32b7050e86c17e29dde57dc15b4e3b
1,574
cpp
C++
leetcode/PartitionList/PartitionList.cpp
lizhenghn123/myAlgorithmStudy
1917d48debeab33436c705bf9bc2fe9cf49f95cf
[ "MIT" ]
2
2015-08-30T04:45:24.000Z
2015-08-30T04:45:36.000Z
leetcode/PartitionList/PartitionList.cpp
lizhenghn123/myAlgorithmStudy
1917d48debeab33436c705bf9bc2fe9cf49f95cf
[ "MIT" ]
null
null
null
leetcode/PartitionList/PartitionList.cpp
lizhenghn123/myAlgorithmStudy
1917d48debeab33436c705bf9bc2fe9cf49f95cf
[ "MIT" ]
4
2015-07-15T08:43:58.000Z
2021-04-10T12:55:29.000Z
// Source : https://oj.leetcode.com/problems/partition-list/ // Author : lizhenghn@gmail.com // Date : 2014-11-30 /********************************************************************************** * * Given a linked list and a value x, partition it such that all nodes less than x come * before nodes greater than or equal to x. * * You should preserve the original relative order of the nodes in each of the two partitions. * * For example, * Given 1->4->3->2->5->2 and x = 3, * return 1->2->2->4->3->5. * **********************************************************************************/ #include <stdio.h> #include <time.h> #include "../common/single_list.hpp" ListNode *partition(ListNode *head, int x) { if (head == NULL || head->next == NULL) return head; ListNode mindummy(0); ListNode *cursor_min = &mindummy; ListNode maxdummy(0); ListNode *cursor_max = &maxdummy; ListNode dummy(0); dummy.next = head; ListNode *p_prev = &dummy; ListNode *p = head; while (p) { if (p->val < x) { p_prev->next = p->next; p->next = NULL; cursor_min->next = p; cursor_min = p; p = p_prev->next; } else { ListNode *p_next = p->next; p->next = NULL; cursor_max->next = p; cursor_max = p; p = p_next; } } cursor_min->next = maxdummy.next; return mindummy.next; } void test_partition() { { int a[] = { 1, 4, 3, 2, 5, 2 }; ListNode *p = createList(a, sizeof(a) / sizeof(a[0])); printList(p); printList(partition(p, 3)); printf("------------------------\n"); } } int main() { test_partition(); getchar(); }
20.986667
93
0.54892
lizhenghn123
ca1eb4f211a4262074d74708084a2bb59b1a0411
9,384
cpp
C++
app/GameState.cpp
yousefh409/tankGame
0b191a1fb8d6c9040e641b4972cfe00452f25544
[ "MIT" ]
1
2021-08-09T02:36:28.000Z
2021-08-09T02:36:28.000Z
app/GameState.cpp
yousefh409/tankGame
0b191a1fb8d6c9040e641b4972cfe00452f25544
[ "MIT" ]
null
null
null
app/GameState.cpp
yousefh409/tankGame
0b191a1fb8d6c9040e641b4972cfe00452f25544
[ "MIT" ]
1
2021-09-04T04:50:10.000Z
2021-09-04T04:50:10.000Z
#include <string> #include <fstream> #include "GameState.h" #include "ScoresScreenState.h" #include "MainMenuState.h" #include "PauseState.h" // using namespace std; void GameState::initBackground() { this->background.setSize(sf::Vector2f(1024.0f, 768.0f)); backgroundTexture.loadFromFile(std::string(Maps::filePrefix + "background.png")); this->background.setTexture(&backgroundTexture); } void GameState::initializeLevel() { for (int i = 0; i < Maps::MAP_X; i++) { for (int j = 0; j < Maps::MAP_Y; j++) { if (Maps::levels[gameIndex].mapArray[i][j] == 1) { Wall wall(Maps::filePrefix + "border.png", sf::Vector2f(i * 50.0f, j * 70.0f), 0, 0.16, Maps::filePrefix); allSprites.push_back(make_shared<Wall>(wall)); } } } if (!this->isTest) { for (auto iter = Maps::levels[gameIndex].enemyTanks.begin(); iter != Maps::levels[gameIndex].enemyTanks.end(); iter++) { enemyTanks.push_back((*iter)->clone()); } } } void GameState::updateWindow() { //WE USE INDECIES RATHER THAN ITERATORS BECAUSE ITERATORS WILL BE INVALIDATED // IF WE INSERT ELEMENTS INTO THE VECTOR(WHICH WILL HAPPEN) unsigned allSpritesSize = allSprites.size(); for (unsigned i = 0; i < allSpritesSize; i++) { allSprites[i]->update(this->window, event, allSprites, clock); } unsigned enemyTankSize = enemyTanks.size(); for (unsigned i = 0; i < enemyTankSize; i++) { enemyTanks[i]->update(this->window, event, allSprites, clock); } for (auto iter = destroyed.begin(); iter != destroyed.end(); iter++) { (*iter)->update(this->window, event, allSprites, clock); } this->drawScore(); } void GameState::checkCollisions() { bool iterCollision = false; bool jterCollision = false; //WE USE INDECIES HERE TO MAKE THE DELETE SYNTAX EASIER unsigned spritesLength = allSprites.size(); unsigned enemyLength = enemyTanks.size(); for (unsigned i = 0; i < enemyLength; i++) { //Checking for collisions between all sprites and enemyTanks for (unsigned j = 0; j < spritesLength; j++) { if (allSprites[j]->isIntersect(enemyTanks[i].get())) { iterCollision = enemyTanks[i]->collision(allSprites[j].get()); jterCollision = allSprites[j]->collision(enemyTanks[i].get()); if (jterCollision) { destroyed.insert(allSprites[j]); allSprites.erase(allSprites.begin() + j); playHitSound(); spritesLength--; } if (iterCollision) { destroyed.insert(enemyTanks[i]); enemyTanks.erase(enemyTanks.begin() + i); playHitSound(); score.incrScore(100 * (enemyTanks.size() + 1)); enemyLength--; break; } } } } unsigned vectorLength = allSprites.size(); //WE USE INDECIES HERE TO MAKE THE DELETE SYNTAX EASIER for (unsigned i = 0; i < vectorLength; i++) { //Checking for collisions between all other sprites for (unsigned j = i + 1; j < vectorLength; j++) { if ((allSprites[i] != allSprites[j]) && allSprites[i]->isIntersect(allSprites[j].get())) { bool iterCollision = allSprites[i]->collision(allSprites[j].get()); bool jterCollision = allSprites[j]->collision(allSprites[i].get()); bool isSound = false; if (jterCollision) { destroyed.insert(allSprites[j]); allSprites.erase(allSprites.begin() + j); vectorLength--; playHitSound(); isSound = true; } if (iterCollision) { destroyed.insert(allSprites[i]); allSprites.erase(allSprites.begin() + i); vectorLength--; if (!isSound) { playHitSound(); } break; } } } } } void GameState::removeDestroyed() { for (auto iter = destroyed.begin(); iter != destroyed.end();) { if ((*iter)->isExploded(clock)) { iter = destroyed.erase(iter); } else { iter++; } } } bool GameState::gameOver() { if (this->isTest) { return false; } bool result = false; if (this->allSprites.front()->getHealth() <= 0) { result = true; } if (enemyTanks.size() == 0) { result = true; } return result; } void GameState::gameOverCheck() { if (!gameOver()) { checkCollisions(); updateWindow(); removeDestroyed(); } else { if (!isEndedSet) { int incrScore = 1000 - static_cast<int>(30.0f * this->clock.getElapsedTime().asSeconds()); if (incrScore < 0) { //Make sure that it is not negative incrScore = 0; } score.incrScore(incrScore); this->writeScoreFile(); whenEnded = clock.getElapsedTime(); isEndedSet = true; } sf::Time currentTime = clock.getElapsedTime(); if ((currentTime - whenEnded).asSeconds() >= 3) { this->quit = true; } else { drawGameOver(); } } } void GameState::drawGameOver() { this->drawScore(); sf::Font font; font.loadFromFile(Maps::filePrefix + "Unique.ttf"); sf::Text gameEnd; sf::FloatRect textRect = gameEnd.getLocalBounds(); gameEnd.setFont(font); gameEnd.setOrigin(textRect.width / 2.0f + 200, textRect.height / 2.0f); gameEnd.setPosition(this->window->getSize().x / 2.0f, this->window->getSize().y / 2.0f - 130); gameEnd.setCharacterSize(100); if (this->allSprites.front()->getHealth() > 0) { gameEnd.setString("YOU WON"); gameEnd.setFillColor(sf::Color::Green); } else { gameEnd.setString("YOU LOST"); gameEnd.setFillColor(sf::Color::Red); } this->window->draw(gameEnd); sf::Time currentTime = clock.getElapsedTime(); gameEnd.setString(to_string(static_cast<int>(4 - (currentTime - whenEnded).asSeconds()))); gameEnd.setCharacterSize(150); gameEnd.setFillColor(sf::Color::Blue); gameEnd.setOrigin(textRect.width / 2.0f + 30, textRect.height / 2.0f); gameEnd.setPosition(this->window->getSize().x / 2.0f, this->window->getSize().y / 2.0f); this->window->draw(gameEnd); } void GameState::initKeybinds() { ifstream fin(Maps::filePrefix + "gameStateKeybinds.txt"); if (!fin) { cout << "Cant find gameStateKeybinds.txt" << endl; } if (fin.is_open()) { std::string key = ""; std::string key2 = ""; while (fin >> key >> key2) { this->keybinds[key] = this->supportedKeys->at(key2); } } fin.close(); } GameState::GameState(sf::RenderWindow* window, std::map<std::string, int>* supportedKeys, std::stack<State*>* states, int newGame, bool isTestNew) : State(window, supportedKeys, states), gameIndex(newGame), isTest(isTestNew), score(newGame, 0), isEndedSet(false) { this->initBackground(); this->initKeybinds(); if (isTest) { this->allSprites.push_back(make_shared<SecondaryTank>(SecondaryTank(Maps::filePrefix + "tank.png", sf::Vector2f(1024.0f / 5, 768.0f / 5), 0, 0.4, Maps::filePrefix))); } this->allSprites.push_back(make_shared<MainTank>(MainTank(Maps::filePrefix + "tank.png", Maps::mainTankPositions[gameIndex], 0, 0.4, Maps::filePrefix))); this->initializeLevel(); font.loadFromFile(Maps::filePrefix + "Unique.ttf"); buffer.loadFromFile(Maps::filePrefix + "gunShot.wav"); sound.setBuffer(buffer); sound.setVolume(1.5); } void GameState::endState() { if ((gameIndex == Maps::levels.size()) && (this->allSprites.front()->getHealth() > 0)) { auto current = this->states->top(); this->states->pop(); this->states->push(new ScoresScreenState(this->window, this->supportedKeys, this->states)); this->states->push(current); } else { auto current = this->states->top(); this->states->pop(); if (this->allSprites.front()->getHealth() > 0) { this->states->push(new GameState(this->window, this->supportedKeys, this->states, gameIndex + 1, false)); } else { this->states->push(new GameState(this->window, this->supportedKeys, this->states, gameIndex, false)); } this->states->push(current); } this->quit = true; } void GameState::updateInput() { if(sf::Keyboard::isKeyPressed(sf::Keyboard::P)) { this->states->push(new PauseState(this->window, this->supportedKeys, this->states)); } else { this->checkForQuit(); this->gameOverCheck(); } } void GameState::update() { this->updateMousePositions(); this->updateInput(); } void GameState::render(sf::RenderWindow* target) { target->draw(background); this->gameOverCheck(); target->display(); } void GameState::writeScoreFile() { ofstream fout("scores.bin", ios::binary | ios::app); if (!fout) { cerr << "Cant open file: scores.bin" << endl; exit(-2); } fout << score; } void GameState::drawScore() { sf::Text writeScore; writeScore.setFont(font); writeScore.setCharacterSize(50); writeScore.setFillColor(sf::Color::Green); writeScore.setPosition(sf::Vector2f(10, 10)); writeScore.setString("LEVEL " + to_string(gameIndex) + " SCORE: " + to_string(score.getScore())); this->window->draw(writeScore); } void GameState::playHitSound() { sound.play(); }
29.790476
175
0.607737
yousefh409
ca231a2b1c35eed41abc2c038c3893d18372f464
1,629
hpp
C++
source/addon_manager.hpp
ZachHembree/reshade
b0278661b8b78d060d432f94abe04df33296457b
[ "BSD-3-Clause" ]
null
null
null
source/addon_manager.hpp
ZachHembree/reshade
b0278661b8b78d060d432f94abe04df33296457b
[ "BSD-3-Clause" ]
null
null
null
source/addon_manager.hpp
ZachHembree/reshade
b0278661b8b78d060d432f94abe04df33296457b
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2021 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #pragma once #include "addon_impl.hpp" #include "reshade_events.hpp" #include <string> #if RESHADE_ADDON #define RESHADE_ADDON_EVENT(name, ...) \ for (size_t cb = 0; cb < reshade::addon::event_list[static_cast<size_t>(reshade::addon_event::name)].size(); ++cb) /* Generates better code than ranged-based for loop */ \ reinterpret_cast<typename reshade::addon_event_traits<reshade::addon_event::name>::decl>(reshade::addon::event_list[static_cast<size_t>(reshade::addon_event::name)][cb])(__VA_ARGS__) #else #define RESHADE_ADDON_EVENT(name, ...) ((void)0) #endif #if RESHADE_ADDON namespace reshade::addon { struct info { void *handle; std::string name; std::string description; }; /// <summary> /// List of currently loaded add-ons. /// </summary> extern std::vector<info> loaded_info; /// <summary> /// List of installed add-on event callbacks. /// </summary> extern std::vector<void *> event_list[]; #if RESHADE_GUI /// <summary> /// List of overlays registered by loaded add-ons. /// </summary> extern std::vector<std::pair<std::string, void(*)(api::effect_runtime *, void *)>> overlay_list; #endif /// <summary> /// Load any add-ons found in the configured search paths. /// </summary> void load_addons(); /// <summary> /// Unload any add-ons previously loaded via <see cref="load_addons"/>. /// </summary> void unload_addons(); /// <summary> /// Enable or disable all loaded add-ons. /// </summary> void enable_or_disable_addons(bool enabled); } #endif
25.857143
185
0.693063
ZachHembree
ca2367364f57335e6d18f5f9dff9e4f650eae8a9
622
cpp
C++
src/examples/002Chapter/2-6-1-sales-data-type/main.cpp
artgonzalez/cpp-primer
0317e11b5821860d38a236f24c6f7d76638386f3
[ "MIT" ]
null
null
null
src/examples/002Chapter/2-6-1-sales-data-type/main.cpp
artgonzalez/cpp-primer
0317e11b5821860d38a236f24c6f7d76638386f3
[ "MIT" ]
null
null
null
src/examples/002Chapter/2-6-1-sales-data-type/main.cpp
artgonzalez/cpp-primer
0317e11b5821860d38a236f24c6f7d76638386f3
[ "MIT" ]
null
null
null
#include<iostream> #include "sales_data.h" int main() { SalesData data, data1; std::cout<<"Enter isbn: "; std::cin>>data.book_no; std::cout<<"Enter units old: "; std::cin>>data.units_sold; std::cout<<"Enter revenue: "; std::cin>>data.revenue; std::cout<<"Enter isbn: "; std::cin>>data1.book_no; std::cout<<"Enter units old: "; std::cin>>data1.units_sold; std::cout<<"Enter revenue: "; std::cin>>data1.revenue; if(data.book_no == data1.book_no) { std::cout<<data.units_sold * data.revenue + data1.units_sold * data1.revenue; } return 0; }
19.4375
85
0.594855
artgonzalez
ca2685aee0445a79ab41a69e46770279d98a2ed8
689
cpp
C++
test/unit/math/prim/scal/fun/lbeta_test.cpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
test/unit/math/prim/scal/fun/lbeta_test.cpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
test/unit/math/prim/scal/fun/lbeta_test.cpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
#include <stan/math/prim/scal.hpp> #include <boost/math/special_functions/fpclassify.hpp> #include <gtest/gtest.h> #include <limits> TEST(MathFunctions, lbeta) { using stan::math::lbeta; EXPECT_FLOAT_EQ(0.0, lbeta(1.0, 1.0)); EXPECT_FLOAT_EQ(2.981361, lbeta(0.1, 0.1)); EXPECT_FLOAT_EQ(-4.094345, lbeta(3.0, 4.0)); EXPECT_FLOAT_EQ(-4.094345, lbeta(4.0, 3.0)); } TEST(MathFunctions, lbeta_nan) { double nan = std::numeric_limits<double>::quiet_NaN(); EXPECT_PRED1(boost::math::isnan<double>, stan::math::lbeta(nan, 1.0)); EXPECT_PRED1(boost::math::isnan<double>, stan::math::lbeta(1.0, nan)); EXPECT_PRED1(boost::math::isnan<double>, stan::math::lbeta(nan, nan)); }
28.708333
72
0.696662
jrmie
ca27f8a9cf4247272301080a84f671ea6baac031
10,268
cpp
C++
native/src/seal/util/globals.cpp
nitrieu/SEAL
9fc376c19488be2bfd213780ee06789754f4b2c2
[ "MIT" ]
17
2019-12-02T09:26:24.000Z
2022-02-03T03:59:25.000Z
native/src/seal/util/globals.cpp
nitrieu/SEAL
9fc376c19488be2bfd213780ee06789754f4b2c2
[ "MIT" ]
1
2020-09-14T06:19:36.000Z
2020-09-14T06:19:36.000Z
native/src/seal/util/globals.cpp
nitrieu/SEAL
9fc376c19488be2bfd213780ee06789754f4b2c2
[ "MIT" ]
11
2019-12-02T22:02:39.000Z
2021-12-10T02:17:06.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include <cstdint> #include "seal/util/globals.h" #include "seal/smallmodulus.h" using namespace std; namespace seal { namespace util { namespace global_variables { std::shared_ptr<MemoryPool> const global_memory_pool{ std::make_shared<MemoryPoolMT>() }; #ifndef _M_CEE thread_local std::shared_ptr<MemoryPool> const tls_memory_pool{ std::make_shared<MemoryPoolST>() }; #else #pragma message("WARNING: Thread-local memory pools disabled to support /clr") #endif const map<size_t, vector<SmallModulus>> default_coeff_modulus_128 { /* Polynomial modulus: 1x^1024 + 1 Modulus count: 1 Total bit count: 27 */ { 1024,{ 0x7e00001 } }, /* Polynomial modulus: 1x^2048 + 1 Modulus count: 1 Total bit count: 54 */ { 2048,{ 0x3fffffff000001 } }, /* Polynomial modulus: 1x^4096 + 1 Modulus count: 3 Total bit count: 109 = 2 * 36 + 37 */ { 4096,{ 0xffffee001, 0xffffc4001, 0x1ffffe0001 } }, /* Polynomial modulus: 1x^8192 + 1 Modulus count: 5 Total bit count: 218 = 2 * 43 + 3 * 44 */ { 8192,{ 0x7fffffd8001, 0x7fffffc8001, 0xfffffffc001, 0xffffff6c001, 0xfffffebc001 } }, /* Polynomial modulus: 1x^16384 + 1 Modulus count: 9 Total bit count: 438 = 3 * 48 + 6 * 49 */ { 16384,{ 0xfffffffd8001, 0xfffffffa0001, 0xfffffff00001, 0x1fffffff68001, 0x1fffffff50001, 0x1ffffffee8001, 0x1ffffffea0001, 0x1ffffffe88001, 0x1ffffffe48001 } }, /* Polynomial modulus: 1x^32768 + 1 Modulus count: 16 Total bit count: 881 = 15 * 55 + 56 */ { 32768,{ 0x7fffffffe90001, 0x7fffffffbf0001, 0x7fffffffbd0001, 0x7fffffffba0001, 0x7fffffffaa0001, 0x7fffffffa50001, 0x7fffffff9f0001, 0x7fffffff7e0001, 0x7fffffff770001, 0x7fffffff380001, 0x7fffffff330001, 0x7fffffff2d0001, 0x7fffffff170001, 0x7fffffff150001, 0x7ffffffef00001, 0xfffffffff70001 } } }; const map<size_t, vector<SmallModulus>> default_coeff_modulus_192 { /* Polynomial modulus: 1x^1024 + 1 Modulus count: 1 Total bit count: 19 */ { 1024,{ 0x7f001 } }, /* Polynomial modulus: 1x^2048 + 1 Modulus count: 1 Total bit count: 37 */ { 2048,{ 0x1ffffc0001 } }, /* Polynomial modulus: 1x^4096 + 1 Modulus count: 3 Total bit count: 75 = 3 * 25 */ { 4096,{ 0x1ffc001, 0x1fce001, 0x1fc0001 } }, /* Polynomial modulus: 1x^8192 + 1 Modulus count: 4 Total bit count: 152 = 4 * 38 */ { 8192,{ 0x3ffffac001, 0x3ffff54001, 0x3ffff48001, 0x3ffff28001 } }, /* Polynomial modulus: 1x^16384 + 1 Modulus count: 6 Total bit count: 300 = 6 * 50 */ { 16384,{ 0x3ffffffdf0001, 0x3ffffffd48001, 0x3ffffffd20001, 0x3ffffffd18001, 0x3ffffffcd0001, 0x3ffffffc70001 } }, /* Polynomial modulus: 1x^32768 + 1 Modulus count: 11 Total bit count: 600 = 5 * 54 + 6 * 55 */ { 32768,{ 0x3fffffffd60001, 0x3fffffffca0001, 0x3fffffff6d0001, 0x3fffffff5d0001, 0x3fffffff550001, 0x7fffffffe90001, 0x7fffffffbf0001, 0x7fffffffbd0001, 0x7fffffffba0001, 0x7fffffffaa0001, 0x7fffffffa50001 } } }; const map<size_t, vector<SmallModulus>> default_coeff_modulus_256 { /* Polynomial modulus: 1x^1024 + 1 Modulus count: 1 Total bit count: 14 */ { 1024,{ 0x3001 } }, /* Polynomial modulus: 1x^2048 + 1 Modulus count: 1 Total bit count: 29 */ { 2048,{ 0x1ffc0001 } }, /* Polynomial modulus: 1x^4096 + 1 Modulus count: 1 Total bit count: 58 */ { 4096,{ 0x3ffffffff040001 } }, /* Polynomial modulus: 1x^8192 + 1 Modulus count: 3 Total bit count: 118 = 2 * 39 + 40 */ { 8192,{ 0x7ffffec001, 0x7ffffb0001, 0xfffffdc001 } }, /* Polynomial modulus: 1x^16384 + 1 Modulus count: 5 Total bit count: 237 = 3 * 47 + 2 * 48 */ { 16384,{ 0x7ffffffc8001, 0x7ffffff00001, 0x7fffffe70001, 0xfffffffd8001, 0xfffffffa0001 } }, /* Polynomial modulus: 1x^32768 + 1 Modulus count: 9 Total bit count: 476 = 52 + 8 * 53 */ { 32768,{ 0xffffffff00001, 0x1fffffffe30001, 0x1fffffffd80001, 0x1fffffffd10001, 0x1fffffffc50001, 0x1fffffffbf0001, 0x1fffffffb90001, 0x1fffffffb60001, 0x1fffffffa50001 } } }; namespace internal_mods { const SmallModulus m_sk(0x1fffffffffe00001); const SmallModulus m_tilde(uint64_t(1) << 32); const SmallModulus gamma(0x1fffffffffc80001); const vector<SmallModulus> aux_small_mods{ 0x1fffffffffb40001, 0x1fffffffff500001, 0x1fffffffff380001, 0x1fffffffff000001, 0x1ffffffffef00001, 0x1ffffffffee80001, 0x1ffffffffeb40001, 0x1ffffffffe780001, 0x1ffffffffe600001, 0x1ffffffffe4c0001, 0x1ffffffffdf40001, 0x1ffffffffdac0001, 0x1ffffffffda40001, 0x1ffffffffc680001, 0x1ffffffffc000001, 0x1ffffffffb880001, 0x1ffffffffb7c0001, 0x1ffffffffb300001, 0x1ffffffffb1c0001, 0x1ffffffffadc0001, 0x1ffffffffa400001, 0x1ffffffffa140001, 0x1ffffffff9d80001, 0x1ffffffff9140001, 0x1ffffffff8ac0001, 0x1ffffffff8a80001, 0x1ffffffff81c0001, 0x1ffffffff7800001, 0x1ffffffff7680001, 0x1ffffffff7080001, 0x1ffffffff6c80001, 0x1ffffffff6140001, 0x1ffffffff5f40001, 0x1ffffffff5700001, 0x1ffffffff4bc0001, 0x1ffffffff4380001, 0x1ffffffff3240001, 0x1ffffffff2dc0001, 0x1ffffffff1a40001, 0x1ffffffff11c0001, 0x1ffffffff0fc0001, 0x1ffffffff0d80001, 0x1ffffffff0c80001, 0x1ffffffff08c0001, 0x1fffffffefd00001, 0x1fffffffef9c0001, 0x1fffffffef600001, 0x1fffffffeef40001, 0x1fffffffeed40001, 0x1fffffffeed00001, 0x1fffffffeebc0001, 0x1fffffffed540001, 0x1fffffffed440001, 0x1fffffffed2c0001, 0x1fffffffed200001, 0x1fffffffec940001, 0x1fffffffec6c0001, 0x1fffffffebe80001, 0x1fffffffebac0001, 0x1fffffffeba40001, 0x1fffffffeb4c0001, 0x1fffffffeb280001, 0x1fffffffea780001, 0x1fffffffea440001, 0x1fffffffe9f40001, 0x1fffffffe97c0001, 0x1fffffffe9300001, 0x1fffffffe8d00001, 0x1fffffffe8400001, 0x1fffffffe7cc0001, 0x1fffffffe7bc0001, 0x1fffffffe7a80001, 0x1fffffffe7600001, 0x1fffffffe7500001, 0x1fffffffe6fc0001, 0x1fffffffe6d80001, 0x1fffffffe6ac0001, 0x1fffffffe6000001, 0x1fffffffe5d40001, 0x1fffffffe5a00001, 0x1fffffffe5940001, 0x1fffffffe54c0001, 0x1fffffffe5340001, 0x1fffffffe4bc0001, 0x1fffffffe4a40001, 0x1fffffffe3fc0001, 0x1fffffffe3540001, 0x1fffffffe2b00001, 0x1fffffffe2680001, 0x1fffffffe0480001, 0x1fffffffe00c0001, 0x1fffffffdfd00001, 0x1fffffffdfc40001, 0x1fffffffdf700001, 0x1fffffffdf340001, 0x1fffffffdef80001, 0x1fffffffdea80001, 0x1fffffffde680001, 0x1fffffffde000001, 0x1fffffffdde40001, 0x1fffffffddd80001, 0x1fffffffddd00001, 0x1fffffffddb40001, 0x1fffffffdd780001, 0x1fffffffdd4c0001, 0x1fffffffdcb80001, 0x1fffffffdca40001, 0x1fffffffdc380001, 0x1fffffffdc040001, 0x1fffffffdbb40001, 0x1fffffffdba80001, 0x1fffffffdb9c0001, 0x1fffffffdb740001, 0x1fffffffdb380001, 0x1fffffffda600001, 0x1fffffffda340001, 0x1fffffffda180001, 0x1fffffffd9700001, 0x1fffffffd9680001, 0x1fffffffd9440001, 0x1fffffffd9080001, 0x1fffffffd8c80001, 0x1fffffffd8800001, 0x1fffffffd82c0001, 0x1fffffffd7cc0001, 0x1fffffffd7b80001, 0x1fffffffd7840001, 0x1fffffffd73c0001 }; } } } }
40.425197
111
0.518699
nitrieu
ca2f096fc7e2cefe9b3da1c7588be696da465685
24,452
cpp
C++
cpp/shared/LILBuildManager.cpp
veosotano/lil
da2d0774615827d521362ffb731e8abfa3887507
[ "MIT" ]
6
2021-01-02T16:36:28.000Z
2022-01-23T21:50:29.000Z
cpp/shared/LILBuildManager.cpp
veosotano/lil
da2d0774615827d521362ffb731e8abfa3887507
[ "MIT" ]
null
null
null
cpp/shared/LILBuildManager.cpp
veosotano/lil
da2d0774615827d521362ffb731e8abfa3887507
[ "MIT" ]
null
null
null
/******************************************************************** * * LIL Is a Language * * AUTHORS: Miro Keller * * COPYRIGHT: ©2020-today: All Rights Reserved * * LICENSE: see LICENSE file * * This file is responsible for coordinating a build * ********************************************************************/ #include "LILBuildManager.h" #include "LILAssignment.h" #include "LILBoolLiteral.h" #include "LILCodeUnit.h" #include "LILConfiguration.h" #include "LILErrorMessage.h" #include "LILNumberLiteral.h" #include "LILOutputEmitter.h" #include "LILPlatformSupport.h" #include "LILRule.h" #include "LILRootNode.h" #include "LILSelector.h" #include "LILStringFunction.h" #include "LILStringLiteral.h" #include "LILValueList.h" #include "LILVarName.h" #include <sys/stat.h> #include <array> using namespace LIL; extern void LILPrintErrors(const std::vector<LILErrorMessage> & errors, const LILString & code); LILBuildManager::LILBuildManager() : _codeUnit(nullptr) , _config(std::make_unique<LILConfiguration>()) , _hasErrors(false) , _debug(false) , _verbose(false) , _noConfigureDefaults(false) , _debugConfigureDefaults(false) , _compileToS(false) , _warningLevel(0) { } inline bool file_exists (const std::string & name) { struct stat buffer; return (stat (name.c_str(), &buffer) == 0); } LILBuildManager::~LILBuildManager() { } void LILBuildManager::read() { std::string filePath = this->_directory.data() + "/" + this->_file.data(); std::ifstream file(filePath, std::ios::in); if (file.fail()) { LILErrorMessage ei; ei.message = "\nERROR: Failed to read the file "+this->_file.data(); ei.file = filePath; ei.line = 0; ei.column = 0; this->_errors.push_back(ei); this->_hasErrors = true; LILPrintErrors(this->_errors, ""); return; } std::stringstream buffer; buffer << file.rdbuf(); LILString lilStr(buffer.str()); this->_codeUnit = std::make_unique<LILCodeUnit>(); this->_codeUnit->setVerbose(this->_debugConfigureDefaults); this->_codeUnit->setNeedsConfigureDefaults(!this->_noConfigureDefaults); this->_codeUnit->setDebugConfigureDefaults(this->_debugConfigureDefaults); this->_codeUnit->setIsBeingImportedWithImport(true); this->_codeUnit->setArguments(this->_arguments); this->_codeUnit->setFile(this->_file); std::vector<std::shared_ptr<LILNode>> emptyVect; auto fullPath = this->_directory+"/"+this->_file; this->_codeUnit->addAlreadyImportedFile(fullPath, emptyVect, true); this->_codeUnit->addAlreadyImportedFile(fullPath, emptyVect, false); this->_codeUnit->setDir(this->_directory); this->_codeUnit->setCompilerDir(this->_compilerDir); this->_codeUnit->setSource(lilStr); this->_codeUnit->run(); if (this->_codeUnit->hasErrors()) { this->_hasErrors = true; } } void LILBuildManager::configure() { const auto & config = this->_codeUnit->getRootNode()->getConfigure(); std::unordered_map<std::string, std::shared_ptr<LILRule>> builds; std::unordered_map<std::string, std::shared_ptr<LILRule>> targets; for (const auto & conf : config) { if (conf->isA(InstructionTypeConfigure)) { const auto & nodes = conf->getChildNodes(); for (const auto & node : nodes) { if (node->isA(NodeTypeRule)) { auto rule = std::static_pointer_cast<LILRule>(node); const auto & firstSel = rule->getFirstSelector(); if (firstSel && firstSel->isA(NodeTypeSelector)) { auto sel = std::static_pointer_cast<LILSelector>(firstSel); const auto & selName = sel->getName(); if (selName == "builds" || selName == "targets") { for (const auto & childRule : rule->getChildRules()) { const auto & firstChildSel = childRule->getFirstSelector(); if (firstChildSel) { switch (firstChildSel->getSelectorType()) { case SelectorTypeUniversalSelector: { for (const auto & node : childRule->getValues()) { this->_config->applyConfig(node); } break; } case SelectorTypeNameSelector: { auto childSel = std::static_pointer_cast<LILSelector>(firstChildSel); if (selName == "builds") { builds[childSel->getName().data()] = childRule; } else { targets[childSel->getName().data()] = childRule; } break; } default: break; } } } } } } else if (node->isA(NodeTypeAssignment)) { this->_config->applyConfig(node); } else if (node->isA(NodeTypeUnaryExpression)) { this->_config->applyConfig(node); } } } } auto build = this->_config->getConfigString("build"); if (builds.count(build) > 0) { const auto & rule = builds[build]; for (const auto & node : rule->getValues()) { this->_config->applyConfig(node); } } auto target = this->_config->getConfigString("target"); if (target == "auto" || target == "") { target = LIL_getAutoTargetString(); } std::shared_ptr<LILStringLiteral> targetStr = std::make_shared<LILStringLiteral>(); targetStr->setValue(target); this->_config->setConfig("target", targetStr); if (targets.count(target) > 0) { const auto & rule = targets[target]; for (const auto & node : rule->getValues()) { this->_config->applyConfig(node); } } auto isAppStr = this->_config->getConfigString("isApp"); if (isAppStr == "auto") { std::shared_ptr<LILBoolLiteral> isAppBool = std::make_shared<LILBoolLiteral>(); //if we have rules or main menu, build as an app bool isApp = (this->_codeUnit->getRootNode()->getRules().size() > 0) || (this->_codeUnit->getRootNode()->hasMainMenu()); isAppBool->setValue(isApp); this->_config->setConfig("isApp", isAppBool); } auto formatStr = this->_config->getConfigString("format"); if (formatStr == "llvm" || formatStr == "s") { this->_compileToS = true; } auto outStr = this->_config->getConfigString("out"); if (outStr.length() == 0) { size_t dotIndex = this->_file.data().find_last_of("."); if (dotIndex != std::string::npos) { std::shared_ptr<LILStringLiteral> strLit = std::make_shared<LILStringLiteral>(); strLit->setValue(this->_file.data().substr(0, dotIndex)); this->_config->setConfig("out", strLit); } } if (this->_verbose) { std::cerr << "============================\n"; std::cerr << "==== USED CONFIGURATION ====\n"; std::cerr << "============================\n\n"; this->_config->printConfig(); std::cerr << "\n\n"; } } void LILBuildManager::build() { std::string suffix = this->_config->getConfigString("suffix"); bool isApp = this->_config->getConfigBool("isApp"); std::string out = this->_config->getConfigString("out"); std::string exeExt = this->_config->getConfigString("exeExt"); std::string objExt = this->_config->getConfigString("objExt"); std::string buildPath = this->_config->getConfigString("buildPath"); if (buildPath.substr(0, 1) != "/") { buildPath = this->_directory.data() + "/" + buildPath; } LIL_makeDir(buildPath); if (this->_config->getConfigBool("documentation")) { } if (this->_config->getConfigBool("compile", true)) { std::string filePath = this->_directory.data() + "/" + this->_file.data(); std::ifstream file(filePath, std::ios::in); if (file.fail()) { LILErrorMessage ei; ei.message = "\nERROR: Failed to read the file "+this->_file.data(); ei.file = filePath; ei.line = 0; ei.column = 0; this->_errors.push_back(ei); this->_hasErrors = true; LILPrintErrors(this->_errors, ""); return; } std::stringstream buffer; buffer << file.rdbuf(); LILString lilStr(buffer.str()); auto mainCodeUnit = std::make_unique<LILCodeUnit>(); mainCodeUnit->setVerbose(this->_verbose); mainCodeUnit->setImportStdLil(this->_config->getConfigBool("importStdLil")); mainCodeUnit->setStdLilPath(this->_config->getConfigString("stdLilPath")); mainCodeUnit->setDebugStdLil(this->_config->getConfigBool("debugStdLil")); mainCodeUnit->setNeedsConfigureDefaults(false); mainCodeUnit->setIsMain(this->_config->getConfigBool("isMain")); std::vector<LILString> constants; for (auto imp : this->_config->getConfigItems("constants")) { auto tmp = this->_config->extractString(imp); if (tmp.length() > 0) { constants.push_back(tmp); } } mainCodeUnit->setConstants(constants); std::vector<LILString> imports; for (auto imp : this->_config->getConfigItems("imports")) { auto tmp = this->_config->extractString(imp); if (tmp.length() > 0) { imports.push_back(tmp); } } mainCodeUnit->setImports(imports); mainCodeUnit->setArguments(this->_arguments); mainCodeUnit->setConfiguration(this->_config.get()); mainCodeUnit->setFile(this->_file); std::vector<std::shared_ptr<LILNode>> emptyVect; auto fullPath = this->_directory+"/"+this->_file; mainCodeUnit->addAlreadyImportedFile(fullPath, emptyVect, true); mainCodeUnit->addAlreadyImportedFile(fullPath, emptyVect, false); mainCodeUnit->setDir(this->_directory); mainCodeUnit->setCompilerDir(this->_compilerDir); mainCodeUnit->setSuffix(suffix); mainCodeUnit->setSource(lilStr); mainCodeUnit->run(); if (mainCodeUnit->hasErrors()) { this->_hasErrors = true; return; } std::unique_ptr<LILOutputEmitter> outEmitter = std::make_unique<LILOutputEmitter>(); outEmitter->setVerbose(this->_verbose); outEmitter->setDebugIREmitter(this->_debug); LILString oFile = out; oFile += (this->_compileToS ? ".s" : this->_config->getConfigString("objExt") ); outEmitter->setInFile(this->_file); outEmitter->setOutFile(oFile); outEmitter->setDir(buildPath); if (this->_config->getConfigBool("printOnly")) { outEmitter->printToOutput(mainCodeUnit->getRootNode()); } else { if (this->_compileToS) { outEmitter->compileToS(mainCodeUnit->getRootNode()); } else { outEmitter->compileToO(mainCodeUnit->getRootNode()); } } if (!this->_config->getConfigBool("singleFile")) { std::vector<std::string> linkFiles; for (const auto & filePair : mainCodeUnit->getNeededFilesForBuild()) { std::string fileDirAndName; std::string fileNameExt; std::string fileName; std::string fileDir; const std::string & fileStr = filePair.first.data(); bool fileIsVerbose = filePair.second; //remove the path of the main file from this one to see the relative subdir size_t dirIndex = fileStr.find(this->_directory.data()); if (dirIndex != std::string::npos) { fileDirAndName = fileStr.substr(this->_directory.length()+1); } else { fileDirAndName = fileStr; } size_t slashIndex = fileDirAndName.find_last_of("/"); if (slashIndex != std::string::npos) { fileDir = fileDirAndName.substr(0, slashIndex); fileNameExt = fileDirAndName.substr(slashIndex+1); } else { fileDir = ""; fileNameExt = fileDirAndName; } size_t dotIndex = fileNameExt.find_last_of("."); if (dotIndex != std::string::npos) { fileName = fileNameExt.substr(0, dotIndex); } else { fileName = fileNameExt; } std::string fpath = fileStr; if (suffix.length() > 0) { size_t extensionIndex = fileStr.find_last_of("."); if (extensionIndex != std::string::npos) { std::string spath = fpath.substr(0, extensionIndex) + "@" + suffix + fpath.substr(extensionIndex, fpath.length() - extensionIndex); fpath = spath; } } std::ifstream file(fpath, std::ios::in); if (file.fail()) { file = std::ifstream(fileStr.data(), std::ios::in); } if (file.fail()) { LILErrorMessage ei; ei.message = "\nERROR: Failed to read the file "+fileStr; ei.file = fileStr; ei.line = 0; ei.column = 0; this->_errors.push_back(ei); this->_hasErrors = true; LILPrintErrors(this->_errors, ""); return; } std::stringstream buffer; buffer << file.rdbuf(); LILString lilStr(buffer.str()); auto codeUnit = std::make_unique<LILCodeUnit>(); codeUnit->setVerbose(fileIsVerbose); codeUnit->setNeedsConfigureDefaults(false); codeUnit->setIsMain(false); codeUnit->setConstants(constants); codeUnit->setArguments(this->_arguments); codeUnit->setConfiguration(this->_config.get()); codeUnit->setSuffix(this->_config->getConfigString("suffix")); codeUnit->setFile(fileNameExt); std::vector<std::shared_ptr<LILNode>> emptyVect; codeUnit->addAlreadyImportedFile(fileStr, emptyVect, true); codeUnit->addAlreadyImportedFile(fileStr, emptyVect, false); if (fileDir.length() > 0) { codeUnit->setDir(fileDir); } else { codeUnit->setDir(this->_directory); } codeUnit->setCompilerDir(this->_compilerDir); codeUnit->setSource(lilStr); codeUnit->run(); std::unique_ptr<LILOutputEmitter> outEmitter = std::make_unique<LILOutputEmitter>(); outEmitter->setVerbose(fileIsVerbose); outEmitter->setDebugIREmitter(this->_debug); std::string oFile = fileName+this->_config->getConfigString("objExt"); std::string oDir = buildPath+"/"+fileDir; outEmitter->setInFile(fileNameExt); outEmitter->setOutFile(oFile); outEmitter->setDir(oDir); LIL_makeDir(oDir); if (this->_config->getConfigBool("printOnly")) { outEmitter->printToOutput(codeUnit->getRootNode()); } else { outEmitter->compileToO(codeUnit->getRootNode()); } linkFiles.push_back(oDir + "/" + oFile); } //for std::string outFileName = buildPath + "/" + out; if (this->_config->getConfigBool("link")) { #if defined(_WIN32) std::string linkCommand = "LINK " + buildPath + "/" + out + objExt; #else std::string linkCommand = "ld " + buildPath + "/" + out + objExt; #endif for (const auto & linkFile : linkFiles) { linkCommand += " " + linkFile; } if (isApp) { std::vector<std::string> flags; for (const auto & linkerFlag : this->_config->getConfigItems("linkerFlagsApp")) { auto tmp = this->_config->extractString(linkerFlag); if (tmp.length() > 0) { flags.push_back(tmp); } } for (const auto & flag : flags) { linkCommand += " " + flag; } } else { std::vector<std::string> flags; for (const auto & linkerFlag : this->_config->getConfigItems("linkerFlags")) { auto tmp = this->_config->extractString(linkerFlag); if (tmp.length() > 0) { flags.push_back(tmp); } } for (const auto & flag : flags) { linkCommand += " " + flag; } } linkCommand += " -o " + outFileName; #if defined(_WIN32) linkCommand += ".exe"; #endif if (this->_verbose) { std::cerr << "\n============================" << "\n"; std::cerr << "========= LINKING ==========" << "\n"; std::cerr << "============================" << "\n"; std::cerr << linkCommand << "\n\n"; } std::array<char, 128> linkBuffer; std::string linkResult; linkCommand.append(" 2>&1"); std::unique_ptr<FILE, decltype(&pclose)> linkPipe(popen(linkCommand.c_str(), "r"), pclose); if (!linkPipe) { std::cerr << "popen() to the linker failed!"; return; } while (fgets(linkBuffer.data(), linkBuffer.size(), linkPipe.get()) != nullptr) { linkResult += linkBuffer.data(); } if (linkResult.length() > 0) { std::cerr << linkResult; } if (!file_exists(outFileName)) { std::cerr << "\nThere was an error while linking. Exiting.\n\n"; return; } if (isApp) { if (this->_verbose) { std::cerr << "\n============================" << "\n"; std::cerr << "======== PACKAGING =========" << "\n"; std::cerr << "============================" << "\n"; } std::vector<std::string> steps; for (const auto & buildStep : this->_config->getConfigItems("appBuildSteps")) { auto tmp = this->_config->extractString(buildStep); if (tmp.length() > 0) { steps.push_back(tmp); } } for (const auto & step : steps) { if (this->_verbose) { std::cerr << step << "\n\n"; } std::array<char, 128> stepBuffer; std::string stepResult; std::string stepCommand = step; stepCommand.append(" 2>&1"); std::unique_ptr<FILE, decltype(&pclose)> stepPipe(popen(stepCommand.c_str(), "r"), pclose); if (!stepPipe) { std::cerr << "ERROR: popen() failed while trying to execute build step! \n"; return; } while (fgets(stepBuffer.data(), stepBuffer.size(), stepPipe.get()) != nullptr) { stepResult += stepBuffer.data(); } if (stepResult.length() > 0) { std::cerr << stepResult; std::cerr << "\nThere was an error while executing a build step. Exiting.\n\n"; return; } } } if (this->_config->getConfigBool("run")) { if (this->_verbose) { std::cerr << "\n============================" << "\n"; std::cerr << "======== RUNNING =========" << "\n"; std::cerr << "============================" << "\n"; } std::string runCommand = ""; if (isApp) { runCommand = this->_config->getConfigString("runCommandApp"); } else { runCommand = this->_config->getConfigString("runCommand"); } if (this->_verbose) { std::cerr << runCommand << "\n\n"; } std::array<char, 128> runBuffer; runCommand.append(" 2>&1"); std::unique_ptr<FILE, decltype(&pclose)> runPipe(popen(runCommand.c_str(), "r"), pclose); if (!runPipe) { std::cerr << "popen() to the executable failed!"; return; } while (fgets(runBuffer.data(), runBuffer.size(), runPipe.get()) != nullptr) { std::cerr << runBuffer.data(); } } } } } } bool LILBuildManager::hasErrors() const { return this->_hasErrors; } void LILBuildManager::setDirectory(LILString value) { this->_directory = value; } void LILBuildManager::setFile(LILString value) { this->_file = value; } void LILBuildManager::setCompilerDir(LILString value) { this->_compilerDir = value; auto strLit = std::make_shared<LILStringLiteral>(); strLit->setValue(value); this->_config->setConfig("compilerDir", strLit); } void LILBuildManager::setVerbose(bool value) { this->_verbose = value; } void LILBuildManager::setNoConfigureDefaults(bool value) { this->_noConfigureDefaults = value; } void LILBuildManager::setDebugConfigureDefaults(bool value) { this->_debugConfigureDefaults = value; } void LILBuildManager::setPrintOnly(bool value) { // this->_printOnly = value; // this->_link = false; // this->_run = false; // this->_singleFile = true; } void LILBuildManager::setSingleFile(bool value) { // this->_singleFile = value; // this->_link = false; // this->_run = false; } void LILBuildManager::setWarningLevel(int value) { this->_warningLevel = value; } void LILBuildManager::setArguments(std::vector<LILString> &&args) { this->_arguments = std::move(args); }
38.689873
155
0.490389
veosotano
ca2f6a0c2163d5293089d485da6020bb89428e26
865
cpp
C++
0485 - Max Consecutive Ones/cpp/main.cpp
xiaoswu/Leetcode
e4ae8b2f72a312ee247084457cf4e6dbcfd20e18
[ "MIT" ]
5
2018-10-18T06:47:19.000Z
2020-06-19T09:30:03.000Z
0485 - Max Consecutive Ones/cpp/main.cpp
xiaoswu/Leetcode
e4ae8b2f72a312ee247084457cf4e6dbcfd20e18
[ "MIT" ]
null
null
null
0485 - Max Consecutive Ones/cpp/main.cpp
xiaoswu/Leetcode
e4ae8b2f72a312ee247084457cf4e6dbcfd20e18
[ "MIT" ]
null
null
null
// //f main.cpp // 485 - Max Consecutive Ones // // Created by ynfMac on 2019/6/13. // Copyright © 2019 ynfMac. All rights reserved. // #include <iostream> #include <vector> using namespace std; class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { int k = nums[0]; int MaxOnes = 0; for (int i = 1; i < nums.size() ; i ++) { if (nums[i] == 1) { k++; } else{ if (k != 0) { MaxOnes = max(MaxOnes, k); k = 0; } } } return max(MaxOnes,k); } }; int main(int argc, const char * argv[]) { vector<int> sArray = {1,0,1,1,0,1}; int a = Solution().findMaxConsecutiveOnes(sArray); cout << a << endl; std::cout << "Hello, World!\n"; return 0; }
20.595238
54
0.468208
xiaoswu
ca2fe11a90e9d7f03d89ecbe2841ad400ba35139
1,748
cpp
C++
nTA/Source/Old Code/collider_Dynamic.cpp
loganjones/nTA-Total-Annihilation-Clone
d7d0e4d33f1d452d17cf2fed2b2bcb7f6d7d4d14
[ "MIT" ]
2
2020-05-09T20:50:12.000Z
2021-06-20T08:34:58.000Z
nTA/Source/Old Code/collider_Dynamic.cpp
loganjones/nTA-Total-Annihilation-Clone
d7d0e4d33f1d452d17cf2fed2b2bcb7f6d7d4d14
[ "MIT" ]
null
null
null
nTA/Source/Old Code/collider_Dynamic.cpp
loganjones/nTA-Total-Annihilation-Clone
d7d0e4d33f1d452d17cf2fed2b2bcb7f6d7d4d14
[ "MIT" ]
2
2018-01-08T00:12:04.000Z
2020-06-14T10:56:50.000Z
// collider_Dynamic.cpp // Author: Logan "Burn" Jones ///////////////////////// Date: 5/10/2002 // ///////////////////////////////////////////////////////////////////// #include "object.h" #include "collider_Dynamic.h" ///////////////////////////////////////////////////////////////////// // Default Construction/Destruction // collider_Dynamic::collider_Dynamic( const ColliderID_t eID ): object_Collider( COLLIER_Dynamic, eID ) {} collider_Dynamic::~collider_Dynamic() {} // ///////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // collider_Dynamic::AttachToSystem() // Author: Logan "Burn" Jones /////////////////////////////////////// Date: 5/22/2002 // //==================================================================== // Return: BOOL - // BOOL collider_Dynamic::AttachToSystem() { return FALSE; } // End collider_Dynamic::AttachToSystem() ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // collider_Dynamic::DetachFromSystem() // Author: Logan "Burn" Jones ///////////////////////////////////////// Date: 5/22/2002 // //==================================================================== // void collider_Dynamic::DetachFromSystem() { } // End collider_Dynamic::DetachFromSystem() ////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // End - collider_Dynamic.cpp // ///////////////////////////////
33.615385
71
0.308924
loganjones
ca34c0a84bc37834c1fd114093411524250ecd99
5,193
cpp
C++
src/Http/HttpResponse.cpp
MisakiOfScut/SingHttpServer
039636d7cee16ccc46c281456d71a410f3f16e23
[ "Apache-2.0" ]
1
2021-03-05T09:27:35.000Z
2021-03-05T09:27:35.000Z
src/Http/HttpResponse.cpp
MisakiOfScut/SingHttpServer
039636d7cee16ccc46c281456d71a410f3f16e23
[ "Apache-2.0" ]
null
null
null
src/Http/HttpResponse.cpp
MisakiOfScut/SingHttpServer
039636d7cee16ccc46c281456d71a410f3f16e23
[ "Apache-2.0" ]
null
null
null
#include "HttpResponse.h" #include "../Buffer/Buffer.h" #include <unistd.h> #include <fcntl.h> using namespace sing; const std::map<int, std::string> HttpResponse::statusCode2Message = { {200, "OK"}, {301,"Move Permanently"}, {400, "Bad Request"}, {403, "Forbidden"}, {404, "Not Found"} }; const std::map<std::string, std::string> HttpResponse::suffix2Type = { {".html", "text/html"}, {".xml", "text/xml"}, {".xhtml", "application/xhtml+xml"}, {".txt", "text/plain"}, {".rtf", "application/rtf"}, {".pdf", "application/pdf"}, {".word", "application/nsword"}, {".png", "image/png"}, {".gif", "image/gif"}, {".jpg", "image/jpeg"}, {".jpeg", "image/jpeg"}, {".au", "audio/basic"}, {".mpeg", "video/mpeg"}, {".mpg", "video/mpeg"}, {".avi", "video/x-msvideo"}, {".gz", "application/x-gzip"}, {".tar", "application/x-tar"}, {".css", "text/css"}, {".md", "text/plain"}, {".mp4", "video/mpeg4"}, {".mp3","audio/mp3"} }; /* 在获取报文体后再append到buffer, 通过addHeader设置Content-length和Content-type 如果body是文件则另外append,不要通过body设置避免一次copy */ void HttpResponse::appendToBuffer(Buffer* const output) const{ output->append("HTTP/1.1 " + std::to_string(code) + " "+statusMessage + "\r\n"); if(closeConn){ output->append("Connection: close\r\n"); }else{ output->append("Connection: Keep-Alive\r\n"); output->append("Keep-Alive: timeout=" + std::to_string(TIMEOUT)+"\r\n"); } output->append("Server: Sing/1.0\r\n"); for (const auto& header : headers) { output->append(header.first); output->append(": "); output->append(header.second); output->append("\r\n"); } output->append("\r\n"); if(body.size()>0) output->append(body); } void HttpResponse::makeResponse(HttpStatusCode code, bool close){ //set keep alive closeConn = close; //set code setStatusCode(code); auto it = statusCode2Message.find(code); if(it==statusCode2Message.end()){ setStatusCode(Code400_BadRequest); } //----------------do err response-----------------------// if(this->code!=Code200_Ok){ makeErrorResponse(statusMessage); return; } //----------------do static request---------------------// if(!path.empty()){ path = path=="/"?"/index.html":path; // if(path=="/"){ // body = "Sing Welcome!"; // addHeader("Content-length", std::to_string(body.size())); // addHeader("Content-type", "text/html"); // } /* 判断请求的资源文件 */ if(stat((srcDir + path).data(), &mmFileStat) < 0 || S_ISDIR(mmFileStat.st_mode)) { setStatusCode(Code404_NotFound); makeErrorResponse("File Not Found"); } else if(!(mmFileStat.st_mode & S_IROTH)) { setStatusCode(Code403_Forbidden); makeErrorResponse("Access Denied"); } else { int srcFd = open((srcDir + path).data(), O_RDONLY); if(srcFd < 0) { setStatusCode(Code404_NotFound); makeErrorResponse("File Not Found1"); }else{ /* 将文件映射到内存提高文件的访问速度 MAP_PRIVATE 建立一个写入时拷贝的私有映射*/ void* mmRet = mmap(0, (size_t)mmFileStat.st_size, PROT_READ, MAP_PRIVATE, srcFd, 0); if(mmRet == (void*)-1) { setStatusCode(Code404_NotFound); makeErrorResponse("File Not Found2"); return; } mmFile = static_cast<char*>(mmRet); ::close(srcFd); addHeader("Content-Type", getFileType()); addHeader("Content-Length", std::to_string(mmFileStat.st_size)); } } } setStatusMessage(statusCode2Message.at(this->code)); } void HttpResponse::makeErrorResponse(const std::string& msg){//FIX ME: send error page html file body += "<html><title>Server Error</title>"; body += "<body bgcolor=\"ffffff\">"; body += std::to_string(this->code) + " : " + statusCode2Message.at(code) + "\n"; body += "<p>" + msg + "</p>"; body += "<hr><em>sing web server</em></body></html>"; addHeader("Content-Type", "text/html"); addHeader("Content-Length", std::to_string(body.size())); } //判断文件类型 string HttpResponse::getFileType(){ string::size_type idx = path.find_last_of('.'); if(idx == string::npos) { return "text/plain"; } string suffix = path.substr(idx); if(suffix2Type.count(suffix) == 1) { return suffix2Type.find(suffix)->second; } return "text/plain"; } size_t HttpResponse::getFileSize()const{ return mmFileStat.st_size; } char* HttpResponse::getFile(){ return this->mmFile; } void HttpResponse::unmapFile(){ if(mmFile){ munmap(mmFile, mmFileStat.st_size); mmFile = nullptr; } } HttpResponse::~HttpResponse(){ unmapFile(); } void HttpResponse::reset(){ unmapFile(); mmFileStat = {0}; headers.clear(); code = Unknown; statusMessage.clear(); body.clear(); srcDir.clear(); path.clear(); }
29.338983
100
0.556711
MisakiOfScut
ca3a187da35e81c5a8209084c8db2087714b18f6
4,106
cpp
C++
src/admin/smart_log_mgr.cpp
hsungyang/poseidonos
0f523b36ccf0d70726364395ea96ac6ae3b845c3
[ "BSD-3-Clause" ]
38
2021-04-06T03:20:55.000Z
2022-03-02T09:33:28.000Z
src/admin/smart_log_mgr.cpp
gye-ul/poseidonos
bce8fe2cd1f36ede8647446ecc4cf8a9749e6918
[ "BSD-3-Clause" ]
19
2021-04-08T02:27:44.000Z
2022-03-23T00:59:04.000Z
src/admin/smart_log_mgr.cpp
gye-ul/poseidonos
bce8fe2cd1f36ede8647446ecc4cf8a9749e6918
[ "BSD-3-Clause" ]
28
2021-04-08T04:39:18.000Z
2022-03-24T05:56:00.000Z
/* * BSD LICENSE * Copyright (c) 2021 Samsung Electronics Corporation * 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 Samsung Electronics Corporation nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "src/admin/smart_log_mgr.h" #include <spdk/nvme_spec.h> #include "src/include/pos_event_id.hpp" namespace pos { SmartLogMgr::SmartLogMgr(void) { configManager = ConfigManagerSingleton::Instance(); } SmartLogMgr::SmartLogMgr(ConfigManager* configMgr) { configManager = configMgr; } SmartLogMgr::~SmartLogMgr(void) { } void SmartLogMgr::Init(void) { bool enabled = false; smartLogEnable = false; int ret = configManager->GetValue("admin", "smart_log_page", &enabled, CONFIG_TYPE_BOOL); if (ret == (int)POS_EVENT_ID::SUCCESS) { smartLogEnable = enabled; } memset(logPage, 0, MAX_VOLUME_COUNT * sizeof(struct SmartLogEntry)); } bool SmartLogMgr::GetSmartLogEnabled(void) { return smartLogEnable; } void* SmartLogMgr::GetLogPages(uint32_t arrayId) { return (void*)logPage[arrayId]; } void SmartLogMgr::IncreaseReadCmds(uint32_t volId, uint32_t arrayId) { if (GetSmartLogEnabled() == false) { return; } logPage[arrayId][volId].hostReadCommands = logPage[arrayId][volId].hostReadCommands + 1; return; } void SmartLogMgr::IncreaseWriteCmds(uint32_t volId, uint32_t arrayId) { if (GetSmartLogEnabled() == false) { return; } logPage[arrayId][volId].hostWriteCommands = logPage[arrayId][volId].hostWriteCommands + 1; return; } uint64_t SmartLogMgr::GetWriteCmds(uint32_t volId, uint32_t arrayId) { return logPage[arrayId][volId].hostWriteCommands; } uint64_t SmartLogMgr::GetReadCmds(uint32_t volId, uint32_t arrayId) { return logPage[arrayId][volId].hostReadCommands; } void SmartLogMgr::IncreaseReadBytes(uint64_t blkCnt, uint32_t volId, uint32_t arrayId) { if (GetSmartLogEnabled() == false) { return; } logPage[arrayId][volId].bytesRead = logPage[arrayId][volId].bytesRead + blkCnt * BLOCK_SIZE_SMART; return; } void SmartLogMgr::IncreaseWriteBytes(uint64_t blkCnt, uint32_t volId, uint32_t arrayId) { if (GetSmartLogEnabled() == false) { return; } logPage[arrayId][volId].bytesWritten = logPage[arrayId][volId].bytesWritten + blkCnt * BLOCK_SIZE_SMART; return; } uint64_t SmartLogMgr::GetReadBytes(uint32_t volId, uint32_t arrayId) { return logPage[arrayId][volId].bytesRead; } uint64_t SmartLogMgr::GetWriteBytes(uint32_t volId, uint32_t arrayId) { return logPage[arrayId][volId].bytesWritten; } } // namespace pos
27.931973
108
0.72528
hsungyang
ca3ac7fe57dbbf3314d62791bab2baaed4c08a24
16,399
cc
C++
arcane/ceapart/src/arcane/hyoda/HyodaEnvs.cc
cedricga91/framework
143eeccb5bf375df4a3f11b888681f84f60380c6
[ "Apache-2.0" ]
16
2021-09-20T12:37:01.000Z
2022-03-18T09:19:14.000Z
arcane/ceapart/src/arcane/hyoda/HyodaEnvs.cc
cedricga91/framework
143eeccb5bf375df4a3f11b888681f84f60380c6
[ "Apache-2.0" ]
66
2021-09-17T13:49:39.000Z
2022-03-30T16:24:07.000Z
arcane/ceapart/src/arcane/hyoda/HyodaEnvs.cc
cedricga91/framework
143eeccb5bf375df4a3f11b888681f84f60380c6
[ "Apache-2.0" ]
11
2021-09-27T16:48:55.000Z
2022-03-23T19:06:56.000Z
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*- //----------------------------------------------------------------------------- // Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com) // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: Apache-2.0 //----------------------------------------------------------------------------- /*---------------------------------------------------------------------------*/ /* HyodaEnvs.cc (C) 2000-2013 */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ #ifndef _HYODA_PLUGIN_ENVIRONMENTS_H_ #define _HYODA_PLUGIN_ENVIRONMENTS_H_ #include "arcane/IApplication.h" #include "arcane/IParallelMng.h" #include "arcane/AbstractService.h" #include "arcane/FactoryService.h" #include "arcane/IVariableMng.h" #include "arcane/SharedVariable.h" #include "arcane/CommonVariables.h" #include "arcane/IMesh.h" #include "arcane/IItemFamily.h" #include "arcane/materials/IMeshMaterialMng.h" #include "arcane/materials/IMeshMaterial.h" #include "arcane/materials/IMeshEnvironment.h" #include "arcane/materials/MeshMaterialModifier.h" #include "arcane/materials/MeshMaterialVariableRef.h" #include "arcane/materials/MaterialVariableBuildInfo.h" #include "arcane/materials/MeshEnvironmentBuildInfo.h" #include "arcane/materials/CellToAllEnvCellConverter.h" #include "arcane/materials/MatItemVector.h" #include "arcane/hyoda/Hyoda.h" #include "arcane/hyoda/HyodaArc.h" #include "arcane/hyoda/HyodaMix.h" #include "arcane/hyoda/HyodaIceT.h" #include "arcane/hyoda/IHyodaPlugin.h" //#include <GL/osmesa.h> #include "GL/glu.h" /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ ARCANE_BEGIN_NAMESPACE class HyodaMix; using namespace Arcane; using namespace Arcane::Materials; // ***************************************************************************** // * DEFINES // ***************************************************************************** #define HYODA_MAX_ENV 2 /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ class HyodaEnvs: public AbstractService, public IHyodaPlugin{ public: // ************************************************************************** // * Arcane Service HyodaEnvs // ************************************************************************** HyodaEnvs(const ServiceBuildInfo& sbi): AbstractService(sbi), m_sub_domain(sbi.subDomain()), m_default_mesh(m_sub_domain->defaultMesh()), m_material_mng(IMeshMaterialMng::getReference(m_default_mesh)), m_interface_normal(VariableBuildInfo(m_default_mesh, "InterfaceNormal")), m_interface_distance_env(VariableBuildInfo(m_default_mesh, "InterfaceDistance2ForEnv", IVariable::PNoDump|IVariable::PNoRestore)) { info() << "Loading Hyoda's environments plugin"; info() << "Setting a maximum of " << HYODA_MAX_ENV << " environments"; } // ************************************************************************** // * drawGlobalCell // ************************************************************************** int drawGlobalCell(Cell cell, Real min, Real max, Real val){ Real3 rgb; glBegin(GL_POLYGON); hyoda()->meshIceT()->setColor(min,max,val,rgb); glColor3d(rgb[0], rgb[1], rgb[2]); ENUMERATE_NODE(node, cell->nodes()){ glColor3d(rgb[0], rgb[1], rgb[2]); glVertex2d(m_default_mesh->nodesCoordinates()[node].x, m_default_mesh->nodesCoordinates()[node].y); } glEnd(); // On repasse pour dessiner les contours de la maille glBegin(GL_QUADS); glColor3d(0.0, 0.0, 0.0); ENUMERATE_NODE(node, cell->nodes()){ glVertex2d(m_default_mesh->nodesCoordinates()[node].x, m_default_mesh->nodesCoordinates()[node].y); } glEnd(); return 0; } // ************************************************************************** // * computeDistMinMax // ************************************************************************** void computeDistMinMax(Cell cell, Real3 normal, Real &dist_min, Real &dist_max){ // Détermination de l'intervalle de recherche pour le Newton dist_min = math::scaMul(m_default_mesh->nodesCoordinates()[cell.node(0)],normal); dist_max =math::scaMul(m_default_mesh->nodesCoordinates()[cell.node(0)],normal); const Integer& cell_nb_node=cell.nbNode(); for (Integer node_id = 0; node_id < cell_nb_node; ++node_id) { const Node& node=cell.node(node_id); Real dist = math::scaMul(m_default_mesh->nodesCoordinates()[node],normal); if (dist < dist_min) dist_min = dist; // premier sommet d'une maille quelconque if (dist > dist_max) dist_max = dist; // dernier sommet d'une maille quelconque } } // ************************************************************************** // * draw // ************************************************************************** int draw(IVariable *variable, Real global_min, Real global_max) { ARCANE_UNUSED(global_min); ARCANE_UNUSED(global_max); // On ne supporte pour l'instant que l'affichage pour des variables aux mailles // Le test se fait au sein de HyodaMix::xLine2Cell info()<<"\n\r\33[7m[HyodaEnvs::draw] Focusing on variable "<<variable->name()<< "\33[m"; MaterialVariableCellReal cell_variable(MaterialVariableBuildInfo(m_material_mng,variable->name())); MaterialVariableCellInt32 order_env(MaterialVariableBuildInfo(m_material_mng, "OrderEnv")); VariableCellArrayInteger number_env(VariableBuildInfo(m_default_mesh,"NumberEnv")); VariableCellInteger m_x_codes(VariableBuildInfo(m_default_mesh,"IntersectionCodes")); // Calcul des min et max locaux aux envCells debug()<<"\33[7m[HyodaEnvs::draw] Calcul des min et max locaux aux envCells\33[m"; Real local_min, local_max; local_min=local_max=0.0; ENUMERATE_ALLENVCELL(iAllEnvCell, m_material_mng, m_default_mesh->allCells()){ AllEnvCell allEnvCell = *iAllEnvCell; Cell cell=allEnvCell.globalCell(); for(int iEnvOrder=0, mx=allEnvCell.nbEnvironment(); iEnvOrder<mx; ++iEnvOrder){ Integer num_env = number_env[cell][iEnvOrder]; if (num_env==-1) continue; ENUMERATE_CELL_ENVCELL(iEnvCell,allEnvCell){ EnvCell envCell = *iEnvCell; if (num_env!=envCell.environmentId()) continue; Real val=cell_variable[envCell]; local_min = math::min(local_min,val); local_max = math::max(local_max,val); break; } // ENUMERATE_CELL_ENVCELL } // for } // ENUMERATE_ALLENVCELL local_min=m_sub_domain->parallelMng()->reduce(Parallel::ReduceMin, local_min); local_max=m_sub_domain->parallelMng()->reduce(Parallel::ReduceMax, local_max); debug()<<"\33[7m[HyodaEnvs::draw] ENUMERATE_ALLENVCELL\33[m"; ENUMERATE_ALLENVCELL(iAllEnvCell, m_material_mng, m_default_mesh->allCells()){ AllEnvCell allEnvCell = *iAllEnvCell; Cell cell=allEnvCell.globalCell(); Real3 normal = m_interface_normal[cell]; Int32UniqueArray xCodes(0); // Si c'est pas initialisé, on se retrouve avec normal=(0,0,0) if (normal.abs()==0.) continue; info()<<"\n\r\33[7m[HyodaEnvs::draw] #"<<cell.uniqueId()<<", normal="<<normal << "\33[m"; // On a qu'une seule origine par maille, on la calcule hyodaMix()->setCellOrigin(cell); m_x_codes[cell]=0; Real dist_min, dist_max; // On calcule les distance min et max pour être dans la maille computeDistMinMax(cell,normal,dist_min,dist_max); // On compte le nombre de milieux Int32 nbMilieux=0; ENUMERATE_CELL_ENVCELL(iEnvCell,allEnvCell) nbMilieux+=1; // On compte le nombre de milieux trouvés à partir des number_env Int32 nbNumberedMilieux=0; for(int iEnvOrder=0, mx=allEnvCell.nbEnvironment(); iEnvOrder<mx; ++iEnvOrder){ Integer num_env = number_env[cell][iEnvOrder]; if (num_env==-1) continue; nbNumberedMilieux+=1; } // On compte le nombre de milieux trouvés à partir des order_env Int32 nbOrderedMilieux=0; ENUMERATE_CELL_ENVCELL(iEnvCell,allEnvCell){ Integer ord_env = order_env[iEnvCell]; if (ord_env==-1) continue; if (ord_env > HYODA_MAX_ENV) warning() << "\33[7m[HyodaEnvs::draw] #"<<cell.uniqueId() << ": while counting nbOrderedMilieux, ord_env=" << ord_env << " > " << HYODA_MAX_ENV << "\33[m"; if (ord_env > HYODA_MAX_ENV) continue; nbOrderedMilieux+=1; } // Focus sur une maille //if (cell.uniqueId()==49){ { //info()<< "\n\33[7m[HyodaEnvs::draw] Cell "<<cell.uniqueId()<<"\33[m"; //info()<< "[HyodaEnvs::draw] nbMilieux " << nbMilieux; //info()<< "[HyodaEnvs::draw] nbNumberedMilieux "<< nbNumberedMilieux; //info()<< "[HyodaEnvs::draw] nbOrderedMilieux " << nbOrderedMilieux; /*ENUMERATE_CELL_ENVCELL(iEnvCell,allEnvCell){ Integer ord_env = order_env[iEnvCell]; if (ord_env>nbMilieux){ warning()<<"ord_env="<<ord_env<<" > nbMilieux="<<nbMilieux; ord_env=nbMilieux-1; //if (nbMilieux==1) ord_env=0; else fatal()<<"Cannot fix ord_env>nbMilieux"; } info()<<"\t[HyodaEnvs::draw] ord_env="<<ord_env; info()<<"\t[HyodaEnvs::draw] number_env[cell][ord_env]="<<number_env[cell][ord_env]; }*/ } Int32 iMilieux=0; for(int iEnvOrder=0, mx=allEnvCell.nbEnvironment(); iEnvOrder<mx; ++iEnvOrder){ Integer num_env = number_env[cell][iEnvOrder]; if (num_env==-1) continue; Real its_distance=m_interface_distance_env[cell][num_env]; info() << "[HyodaEnvs::draw] num_env=" << num_env << ", its distance=" << its_distance; if (its_distance < dist_min) warning()<<"its_distance < dist_min"; if (its_distance > dist_max) warning()<<"its_distance > dist_max"; // Il faut faire le xCellPoints pour setter les x[i] Int32 xPts=hyodaMix()->xCellPoints(cell, normal, its_distance, /*order=*/iMilieux); // Il faut traiter le cas < dist_min: on set le code à 0x0 if (its_distance < dist_min) xPts=0x0; // Il faut traiter le cas > dist_max: on set le code à 0xF if (its_distance > dist_max) xPts=0xF; // Cas où on a qu'un seul milieu if (nbNumberedMilieux==1) xPts=0xF; info() << "\t\33[7m[HyodaEnvs::draw] xPts["<<iEnvOrder<<"]="<<xPts<< "\33[m"; // Dans tous les cas, on l'ajoute pour pouvoir faire la distinction apres entre les x[i[0~11]] // On sauve les codes m_x_codes[cell]|=xPts<<(iMilieux<<2); xCodes.add(xPts); //if ((xPts!=0) && (xPts!=0xF)) hyodaMix()->xCellDrawNormal(cell, iOrg, its_distance); // On doit incrémenter iMilieux, c'est lui qui nous permet de trouver les bons x[i] iMilieux+=1; } //if (cell.uniqueId()==49) //info() << "[HyodaEnvs::draw] \33[7m#" << cell.uniqueId() << "\t" << xCodes<< "\33[m"; //<< ", m_x_codes[this]=" << m_x_codes[cell] << "\33[m"; // Pour chaque milieu, on revient pour remplir dans l'ordre // On fait dans ce sens (for, ENUMERATE_CELL_ENVCELL & break) pour éviter de jouer // avec order_env qui a tendance à être > nbMilieux // Mais dans ce sens, il y a des cas où l'on obtient pas (iMilieux==nbMilieux) // du fait de la non correspondance des number_env et environmentId() iMilieux=0; for(int iEnvOrder=0, mx=allEnvCell.nbEnvironment(); iEnvOrder<mx; ++iEnvOrder){ Integer hit_env=-1; Integer num_env = number_env[cell][iEnvOrder]; if (num_env==-1) continue; debug()<<"\t[HyodaEnvs::draw] Looking for num_env="<<num_env; // On déclenche les remplissage ENUMERATE_CELL_ENVCELL(iEnvCell,allEnvCell){ EnvCell envCell = *iEnvCell; //if (cell.uniqueId()==49) debug()<<"\t\t[HyodaEnvs::draw] envCell.environmentId()="<<envCell.environmentId(); if (num_env!=envCell.environmentId()) continue; //if (cell.uniqueId()==49){ { debug() << "\t\t[HyodaEnvs::draw] \33[7m" << iMilieux << "/" << (nbNumberedMilieux-1) << " val=" << cell_variable[envCell] << "\33[m"; debug()<<"\t\t[HyodaEnvs::draw] iMilieux="<<iMilieux; } hyodaMix()->xCellFill(cell, xCodes, local_min, local_max, cell_variable[envCell], /*order=*/iMilieux, nbNumberedMilieux); // On dit que l'on a hité le bon environment hit_env=num_env; iMilieux+=1; // On break car on a trouvé notre bonne envCell break; } // ENUMERATE_CELL_ENVCELL // Si on a pas trouvé le bon environment, on break pour essayer l'autre methode if (hit_env!=num_env){ warning()<< "\33[7m[HyodaEnvs::draw] #"<<cell.uniqueId() <<": Environement "<<num_env<<" non trouvé dans les milieux!\33[m"; break; } } // for // Si on a pas réussi à tout dessiner, on revient en passant par les order_env // en esperant ne pas tomber sur les cas où les orders sont > HYODA_MAX_ENV // Cas i23.plt à l'iteration 186 if (iMilieux!=nbNumberedMilieux){ warning()<< "\33[7m[HyodaEnvs::draw] #"<<cell.uniqueId() <<": tous les milieux n'ont pas été dessinés!\33[m"; Integer iOrderedMilieux=0; Integer iPatchOffset=0; ENUMERATE_CELL_ENVCELL(ienvcell,allEnvCell){ EnvCell envCell = *ienvcell; Integer order = order_env[ienvcell]; if (order == -1 ) continue; if (order > HYODA_MAX_ENV){ warning() << "\33[7m[HyodaEnvs::draw] #"<<cell.uniqueId() <<": order_env > "<<HYODA_MAX_ENV<<"\33[m"; continue; } if (order>=nbOrderedMilieux){ warning() << "\33[7m[HyodaEnvs::draw] #"<<cell.uniqueId() << ": En redessinant via order_env, le milieu "<<order << " est réclamé, alors qu'on en a "<<nbOrderedMilieux<<"\33[m"; warning() << "\33[7m[HyodaEnvs::draw] #"<<cell.uniqueId() << ": On tente de patcher l'offset\33[m"; iPatchOffset=1; } // On vérifie qu'on ne tombe pas négatif if (order<iPatchOffset) continue; hyodaMix()->xCellFill(cell, xCodes, local_min, local_max, cell_variable[envCell], order-iPatchOffset, nbOrderedMilieux); iOrderedMilieux+=1; } // Cette fois ci, on ne peut plus rien faire if (iOrderedMilieux!=nbOrderedMilieux) warning() << "\33[7m[HyodaEnvs::draw] #"<<cell.uniqueId() << ": Même via les order_env, les milieux n'ont pas tous été dessinés\33[m"; } } // ENUMERATE_ALLENVCELL return 0; } private: ISubDomain *m_sub_domain; IMesh* m_default_mesh; IMeshMaterialMng *m_material_mng ; VariableCellReal3 m_interface_normal; VariableCellArrayReal m_interface_distance_env; }; ARCANE_REGISTER_SUB_DOMAIN_FACTORY(HyodaEnvs, IHyodaPlugin, HyodaEnvs); /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ ARCANE_END_NAMESPACE /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ #endif // _HYODA_PLUGIN_ENVIRONMENTS_H_
44.683924
103
0.555827
cedricga91
ca3d27f086d8d36741f98d4dea0686144d74af66
3,539
cpp
C++
Source/DialogueSystemEditor/Private/BehaviorTreeEditor/QuestionCustomization.cpp
ericzhou9/UE4-DialogueSystem
cc3c600916c4f73cebc33ed0a7c5cf45954f2413
[ "MIT" ]
null
null
null
Source/DialogueSystemEditor/Private/BehaviorTreeEditor/QuestionCustomization.cpp
ericzhou9/UE4-DialogueSystem
cc3c600916c4f73cebc33ed0a7c5cf45954f2413
[ "MIT" ]
null
null
null
Source/DialogueSystemEditor/Private/BehaviorTreeEditor/QuestionCustomization.cpp
ericzhou9/UE4-DialogueSystem
cc3c600916c4f73cebc33ed0a7c5cf45954f2413
[ "MIT" ]
1
2019-08-18T06:13:51.000Z
2019-08-18T06:13:51.000Z
//Copyright (c) 2016 Artem A. Mavrin and other contributors #pragma once #include "DialogueSystemEditorPrivatePCH.h" #include "QuestionCustomization.h" #include "DetailLayoutBuilder.h" #include "DetailWidgetRow.h" #include "IDetailPropertyRow.h" #include "DetailCategoryBuilder.h" #define LOCTEXT_NAMESPACE "DialogueSystem" TSharedRef<IDetailCustomization> FQuestionDetails::MakeInstance() { return MakeShareable(new FQuestionDetails); } void FQuestionDetails::CustomizeDetails(IDetailLayoutBuilder& DetailBuilder) { IDetailCategoryBuilder& Category = DetailBuilder.EditCategory("Question"); SettingsProperty = DetailBuilder.GetProperty(GET_MEMBER_NAME_CHECKED(UBTComposite_Question, DialogueSettings)); SettingNameProperty = DetailBuilder.GetProperty(GET_MEMBER_NAME_CHECKED(UBTComposite_Question, SettingName)); Category.AddProperty(GET_MEMBER_NAME_CHECKED(UBTComposite_Question, QuestionThumbnail)); IDetailCategoryBuilder& VisibilityCategory = DetailBuilder.EditCategory("QuestionVisibility"); VisibilityCategory.AddProperty(GET_MEMBER_NAME_CHECKED(UBTComposite_Question, bVisible)); VisibilityCategory.AddProperty(GET_MEMBER_NAME_CHECKED(UBTComposite_Question, bHideAfterSelect)); VisibilityCategory.AddProperty(GET_MEMBER_NAME_CHECKED(UBTComposite_Question, DialogueSettings)); IDetailPropertyRow& SettingName = VisibilityCategory.AddProperty(SettingNameProperty); SettingName.CustomWidget() .NameContent() [ SettingNameProperty->CreatePropertyNameWidget() ] .ValueContent() [ SNew(SComboButton) .OnGetMenuContent(this, &FQuestionDetails::OnGetVariableList) .ContentPadding(FMargin(2.0f, 2.0f)) .ButtonContent() [ SNew(STextBlock) .Text(this, &FQuestionDetails::GetCurrentSettingName) .Font(IDetailLayoutBuilder::GetDetailFont()) ] ]; } void FQuestionDetails::OnSettingNameChange(FString NewValue) { SettingNameProperty->SetValueFromFormattedString(NewValue); } TSharedRef<SWidget> FQuestionDetails::OnGetVariableList() const { TArray<FString> VariableList = GetVariableList(); FMenuBuilder MenuBuilder(true, NULL); for (int32 i = 0; i < VariableList.Num(); i++) { FUIAction ItemAction(FExecuteAction::CreateSP(this, &FQuestionDetails::OnSettingNameChange, VariableList[i])); MenuBuilder.AddMenuEntry(FText::FromString(VariableList[i]), TAttribute<FText>(), FSlateIcon(), ItemAction); } return MenuBuilder.MakeWidget(); } FText FQuestionDetails::GetCurrentSettingName() const { FText SettingName; TArray<FString> VariableList = GetVariableList(); SettingNameProperty->GetValueAsDisplayText(SettingName); for (int32 i = 0; i < VariableList.Num(); i++) { if (SettingName.EqualTo(FText::FromString(VariableList[i]))) { return SettingName; } } SettingNameProperty->SetValueFromFormattedString(FString("None")); return FText::FromString("None"); } TArray<FString> FQuestionDetails::GetVariableList() const { UObject* QuetionSettings; TArray<FString> List; FPropertyAccess::Result Result = SettingsProperty->GetValue(QuetionSettings); if (Result == FPropertyAccess::Success && QuetionSettings != NULL) { UBlueprintGeneratedClass* BP = Cast<UBlueprintGeneratedClass>(QuetionSettings); if (BP) { ADialogueSettings* DialogueSettings = Cast<ADialogueSettings>(BP->ClassDefaultObject); if (DialogueSettings) { List = DialogueSettings->GetBoolVariables(); } } } return List; } #undef LOCTEXT_NAMESPACE
32.172727
113
0.767166
ericzhou9
ca40d96972b04ababacbc585f500b18a892c4b8a
19,047
cpp
C++
OnlineSubsystemB3atZUtils/Source/OnlineSubsystemB3atZUtils/Private/OnlineEngineInterfaceImpl.cpp
philippbb/OnlineSubsytemB3atZPlugin
17ad7c220fddd24bc36860ad9bbc20b3a98bb357
[ "MIT" ]
10
2017-07-22T13:04:45.000Z
2021-12-22T10:02:32.000Z
OnlineSubsystemB3atZUtils/Source/OnlineSubsystemB3atZUtils/Private/OnlineEngineInterfaceImpl.cpp
philippbb/OnlineSubsytemB3atZPlugin
17ad7c220fddd24bc36860ad9bbc20b3a98bb357
[ "MIT" ]
null
null
null
OnlineSubsystemB3atZUtils/Source/OnlineSubsystemB3atZUtils/Private/OnlineEngineInterfaceImpl.cpp
philippbb/OnlineSubsytemB3atZPlugin
17ad7c220fddd24bc36860ad9bbc20b3a98bb357
[ "MIT" ]
3
2017-05-06T20:31:43.000Z
2020-07-01T01:45:37.000Z
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved // Plugin written by Philipp Buerki. Copyright 2017. All Rights reserved.. #include "OnlineEngineInterfaceImpl.h" #include "OnlineSubsystemB3atZ.h" #include "Interfaces/OnlineIdentityInterface.h" #include "OnlineSubsystemB3atZUtils.h" UB3atZOnlineEngineInterfaceImpl::UB3atZOnlineEngineInterfaceImpl(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } bool UB3atZOnlineEngineInterfaceImpl::IsLoaded(FName OnlineIdentifier) { return IOnlineSubsystemB3atZ::IsLoaded(OnlineIdentifier); } FName UB3atZOnlineEngineInterfaceImpl::GetOnlineIdentifier(FWorldContext& WorldContext) { IOnlineSubsystemB3atZUtils* Utils = Online::GetUtils(); if (Utils) { return Utils->GetOnlineIdentifier(WorldContext); } return NAME_None; } FName UB3atZOnlineEngineInterfaceImpl::GetOnlineIdentifier(UWorld* World) { IOnlineSubsystemB3atZUtils* Utils = Online::GetUtils(); if (Utils) { return Utils->GetOnlineIdentifier(World); } return NAME_None; } bool UB3atZOnlineEngineInterfaceImpl::DoesInstanceExist(FName OnlineIdentifier) { return IOnlineSubsystemB3atZ::DoesInstanceExist(OnlineIdentifier); } void UB3atZOnlineEngineInterfaceImpl::ShutdownOnlineSubsystem(FName OnlineIdentifier) { IOnlineSubsystemB3atZ* OnlineSub = IOnlineSubsystemB3atZ::Get(OnlineIdentifier); if (OnlineSub) { OnlineSub->Shutdown(); } } void UB3atZOnlineEngineInterfaceImpl::DestroyOnlineSubsystem(FName OnlineIdentifier) { IOnlineSubsystemB3atZ::Destroy(OnlineIdentifier); } TSharedPtr<const FUniqueNetId> UB3atZOnlineEngineInterfaceImpl::CreateUniquePlayerId(const FString& Str) { UE_LOG(LogInit, VeryVerbose, TEXT("OnlineEngineInterface CreateUniquePlayerId")); IOnlineIdentityPtr IdentityInt = Online::GetIdentityInterface(); if (IdentityInt.IsValid()) { UE_LOG(LogInit, VeryVerbose, TEXT("OnlineEngineInterface CreateUniquePlayerId IdInterface Valid")); return IdentityInt->CreateUniquePlayerId(Str); } return nullptr; } TSharedPtr<const FUniqueNetId> UB3atZOnlineEngineInterfaceImpl::GetUniquePlayerId(UWorld* World, int32 LocalUserNum) { UE_LOG(LogInit, VeryVerbose, TEXT("OnlineEngineInterfaceImpl GetUniquePlayerID")); IOnlineIdentityPtr IdentityInt = Online::GetIdentityInterface(World); if (IdentityInt.IsValid()) { UE_LOG(LogInit, VeryVerbose, TEXT("OnlineEngineInterfaceImpl GetUniquePlayerId IdInterface is valid")); TSharedPtr<const FUniqueNetId> UniqueId = IdentityInt->GetUniquePlayerId(LocalUserNum); return UniqueId; } return nullptr; } FString UB3atZOnlineEngineInterfaceImpl::GetPlayerNickname(UWorld* World, const FUniqueNetId& UniqueId) { UE_LOG(LogInit, VeryVerbose, TEXT("OnlineEngineInterfaceImpl GetPlayerNickname")); IOnlineIdentityPtr IdentityInt = Online::GetIdentityInterface(World); if (IdentityInt.IsValid()) { UE_LOG(LogInit, VeryVerbose, TEXT("OnlineEngineInterfaceImpl GetPlayerNickname IdentityInt is Valid")); return IdentityInt->GetPlayerNickname(UniqueId); } static FString InvalidName(TEXT("InvalidOSSUser")); return InvalidName; } bool UB3atZOnlineEngineInterfaceImpl::GetPlayerPlatformNickname(UWorld* World, int32 LocalUserNum, FString& OutNickname) { IOnlineSubsystemB3atZ* PlatformSubsystem = IOnlineSubsystemB3atZ::GetByPlatform(false); if (PlatformSubsystem) { IOnlineIdentityPtr OnlineIdentityInt = PlatformSubsystem->GetIdentityInterface(); if (OnlineIdentityInt.IsValid()) { OutNickname = OnlineIdentityInt->GetPlayerNickname(LocalUserNum); if (!OutNickname.IsEmpty()) { return true; } } } return false; } bool UB3atZOnlineEngineInterfaceImpl::AutoLogin(UWorld* World, int32 LocalUserNum, const FOnlineAutoLoginComplete& InCompletionDelegate) { IOnlineIdentityPtr IdentityInt = Online::GetIdentityInterface(World); if (IdentityInt.IsValid()) { FName OnlineIdentifier = GetOnlineIdentifier(World); OnLoginCompleteDelegateHandle = IdentityInt->AddOnLoginCompleteDelegate_Handle(LocalUserNum, FOnLoginCompleteDelegate::CreateUObject(this, &ThisClass::OnAutoLoginComplete, OnlineIdentifier, InCompletionDelegate)); if (IdentityInt->AutoLogin(LocalUserNum)) { // Async login started return true; } } // Not waiting for async login return false; } void UB3atZOnlineEngineInterfaceImpl::OnAutoLoginComplete(int32 LocalUserNum, bool bWasSuccessful, const FUniqueNetId& UserId, const FString& Error, FName OnlineIdentifier, FOnlineAutoLoginComplete InCompletionDelegate) { UE_LOG(LogInit, VeryVerbose, TEXT("OnlineEngineInterface OnAutoLoginComplete")); IOnlineIdentityPtr IdentityInt = Online::GetIdentityInterface(OnlineIdentifier); if (IdentityInt.IsValid()) { IdentityInt->ClearOnLoginCompleteDelegate_Handle(LocalUserNum, OnLoginCompleteDelegateHandle); } InCompletionDelegate.ExecuteIfBound(LocalUserNum, bWasSuccessful, Error); } bool UB3atZOnlineEngineInterfaceImpl::IsLoggedIn(UWorld* World, int32 LocalUserNum) { IOnlineIdentityPtr IdentityInt = Online::GetIdentityInterface(World); if (IdentityInt.IsValid()) { return (IdentityInt->GetLoginStatus(LocalUserNum) == ELoginStatusB3atZ::LoggedIn); } return false; } void UB3atZOnlineEngineInterfaceImpl::StartSession(UWorld* World, FName SessionName, FOnlineSessionStartComplete& InCompletionDelegate) { UE_LOG(LogInit, VeryVerbose, TEXT("OEII StartSession")); IOnlineSessionPtr SessionInt = Online::GetSessionInterface(World); if (SessionInt.IsValid()) { FNamedOnlineSession* Session = SessionInt->GetNamedSession(SessionName); if (Session && (Session->SessionState == EB3atZOnlineSessionState::Pending || Session->SessionState == EB3atZOnlineSessionState::Ended)) { FName OnlineIdentifier = GetOnlineIdentifier(World); FDelegateHandle StartSessionCompleteHandle = SessionInt->AddOnStartSessionCompleteDelegate_Handle(FOnStartSessionCompleteDelegate::CreateUObject(this, &ThisClass::OnStartSessionComplete, OnlineIdentifier, InCompletionDelegate)); OnStartSessionCompleteDelegateHandles.Add(OnlineIdentifier, StartSessionCompleteHandle); SessionInt->StartSession(SessionName); } else { InCompletionDelegate.ExecuteIfBound(SessionName, false); } } else { InCompletionDelegate.ExecuteIfBound(SessionName, false); } } void UB3atZOnlineEngineInterfaceImpl::OnStartSessionComplete(FName SessionName, bool bWasSuccessful, FName OnlineIdentifier, FOnlineSessionStartComplete CompletionDelegate) { UE_LOG(LogInit, VeryVerbose, TEXT("OEII StartSession OnStartSessionComplete")); IOnlineSessionPtr SessionInt = Online::GetSessionInterface(OnlineIdentifier); if (SessionInt.IsValid()) { // Cleanup the login delegate before calling create below FDelegateHandle* DelegateHandle = OnStartSessionCompleteDelegateHandles.Find(OnlineIdentifier); if (DelegateHandle) { SessionInt->ClearOnStartSessionCompleteDelegate_Handle(*DelegateHandle); } } CompletionDelegate.ExecuteIfBound(SessionName, bWasSuccessful); } void UB3atZOnlineEngineInterfaceImpl::EndSession(UWorld* World, FName SessionName, FOnlineSessionEndComplete& InCompletionDelegate) { UE_LOG(LogInit, VeryVerbose, TEXT("OEII EndSession")); IOnlineSessionPtr SessionInt = Online::GetSessionInterface(World); if (SessionInt.IsValid()) { FName OnlineIdentifier = GetOnlineIdentifier(World); FDelegateHandle EndSessionCompleteHandle = SessionInt->AddOnEndSessionCompleteDelegate_Handle(FOnEndSessionCompleteDelegate::CreateUObject(this, &ThisClass::OnEndSessionComplete, OnlineIdentifier, InCompletionDelegate)); OnEndSessionCompleteDelegateHandles.Add(OnlineIdentifier, EndSessionCompleteHandle); SessionInt->EndSession(SessionName); } else { InCompletionDelegate.ExecuteIfBound(SessionName, false); } } void UB3atZOnlineEngineInterfaceImpl::OnEndSessionComplete(FName SessionName, bool bWasSuccessful, FName OnlineIdentifier, FOnlineSessionEndComplete CompletionDelegate) { UE_LOG(LogInit, VeryVerbose, TEXT("OEII OnEndSessionComplete")); IOnlineSessionPtr SessionInt = Online::GetSessionInterface(OnlineIdentifier); if (SessionInt.IsValid()) { FDelegateHandle* DelegateHandle = OnEndSessionCompleteDelegateHandles.Find(OnlineIdentifier); if (DelegateHandle) { SessionInt->ClearOnEndSessionCompleteDelegate_Handle(*DelegateHandle); } } CompletionDelegate.ExecuteIfBound(SessionName, bWasSuccessful); } bool UB3atZOnlineEngineInterfaceImpl::DoesSessionExist(UWorld* World, FName SessionName) { UE_LOG(LogInit, VeryVerbose, TEXT("OEII DoesSessionExist")); FOnlineSessionSettings* SessionSettings = nullptr; IOnlineSessionPtr SessionInt = Online::GetSessionInterface(World); if (SessionInt.IsValid()) { SessionSettings = SessionInt->GetSessionSettings(SessionName); } return SessionSettings != nullptr; } bool UB3atZOnlineEngineInterfaceImpl::GetSessionJoinability(UWorld* World, FName SessionName, FJoinabilitySettings& OutSettings) { UE_LOG(LogInit, VeryVerbose, TEXT("OEII Get Session Joinability")); bool bValidData = false; IOnlineSessionPtr SessionInt = Online::GetSessionInterface(World); if (SessionInt.IsValid()) { FOnlineSessionSettings* SessionSettings = SessionInt->GetSessionSettings(SessionName); if (SessionSettings) { OutSettings.SessionName = SessionName; OutSettings.bPublicSearchable = SessionSettings->bShouldAdvertise; OutSettings.bAllowInvites = SessionSettings->bAllowInvites; OutSettings.bJoinViaPresence = SessionSettings->bAllowJoinViaPresence; OutSettings.bJoinViaPresenceFriendsOnly = SessionSettings->bAllowJoinViaPresenceFriendsOnly; bValidData = true; } } return bValidData; } void UB3atZOnlineEngineInterfaceImpl::UpdateSessionJoinability(UWorld* World, FName SessionName, bool bPublicSearchable, bool bAllowInvites, bool bJoinViaPresence, bool bJoinViaPresenceFriendsOnly) { UE_LOG(LogInit, VeryVerbose, TEXT("OEII UpdateSessionJoinability")); IOnlineSessionPtr SessionInt = Online::GetSessionInterface(World); if (SessionInt.IsValid()) { FOnlineSessionSettings* SessionSettings = SessionInt->GetSessionSettings(SessionName); if (SessionSettings != nullptr) { SessionSettings->bShouldAdvertise = bPublicSearchable; SessionSettings->bAllowInvites = bAllowInvites; SessionSettings->bAllowJoinViaPresence = bJoinViaPresence && !bJoinViaPresenceFriendsOnly; SessionSettings->bAllowJoinViaPresenceFriendsOnly = bJoinViaPresenceFriendsOnly; SessionInt->UpdateSession(SessionName, *SessionSettings, true); } } } void UB3atZOnlineEngineInterfaceImpl::RegisterPlayer(UWorld* World, FName SessionName, const FUniqueNetId& UniqueId, bool bWasInvited) { UE_LOG(LogInit, VeryVerbose, TEXT("OEII Register Player")); IOnlineSessionPtr SessionInt = Online::GetSessionInterface(World); if (SessionInt.IsValid() && UniqueId.IsValid()) { SessionInt->RegisterPlayer(SessionName, UniqueId, bWasInvited); } } void UB3atZOnlineEngineInterfaceImpl::UnregisterPlayer(UWorld* World, FName SessionName, const FUniqueNetId& UniqueId) { UE_LOG(LogInit, VeryVerbose, TEXT("OEII UnregisterPlayer")); IOnlineSessionPtr SessionInt = Online::GetSessionInterface(World); if (SessionInt.IsValid()) { SessionInt->UnregisterPlayer(SessionName, UniqueId); } } bool UB3atZOnlineEngineInterfaceImpl::GetResolvedConnectString(UWorld* World, FName SessionName, FString& URL) { UE_LOG(LogInit, VeryVerbose, TEXT("OEII GetResolvedConnectString")); IOnlineSessionPtr SessionInt = Online::GetSessionInterface(World); if (SessionInt.IsValid() && SessionInt->GetResolvedConnectString(SessionName, URL)) { return true; } return false; } TSharedPtr<FVoicePacket> UB3atZOnlineEngineInterfaceImpl::GetLocalPacket(UWorld* World, uint8 LocalUserNum) { IOnlineB3atZVoicePtr VoiceInt = Online::GetB3atZVoiceInterface(World); if (VoiceInt.IsValid()) { TSharedPtr<FVoicePacket> LocalPacket = VoiceInt->GetLocalPacket(LocalUserNum); return LocalPacket; } return nullptr; } TSharedPtr<FVoicePacket> UB3atZOnlineEngineInterfaceImpl::SerializeRemotePacket(UWorld* World, FArchive& Ar) { IOnlineB3atZVoicePtr VoiceInt = Online::GetB3atZVoiceInterface(World); if (VoiceInt.IsValid()) { return VoiceInt->SerializeRemotePacket(Ar); } return nullptr; } void UB3atZOnlineEngineInterfaceImpl::StartNetworkedVoice(UWorld* World, uint8 LocalUserNum) { IOnlineB3atZVoicePtr VoiceInt = Online::GetB3atZVoiceInterface(World); if (VoiceInt.IsValid()) { VoiceInt->StartNetworkedVoice(LocalUserNum); } } void UB3atZOnlineEngineInterfaceImpl::StopNetworkedVoice(UWorld* World, uint8 LocalUserNum) { IOnlineB3atZVoicePtr VoiceInt = Online::GetB3atZVoiceInterface(World); if (VoiceInt.IsValid()) { VoiceInt->StopNetworkedVoice(LocalUserNum); } } void UB3atZOnlineEngineInterfaceImpl::ClearVoicePackets(UWorld* World) { IOnlineB3atZVoicePtr VoiceInt = Online::GetB3atZVoiceInterface(World); if (VoiceInt.IsValid()) { VoiceInt->ClearVoicePackets(); } } bool UB3atZOnlineEngineInterfaceImpl::MuteRemoteTalker(UWorld* World, uint8 LocalUserNum, const FUniqueNetId& PlayerId, bool bIsSystemWide) { IOnlineB3atZVoicePtr VoiceInt = Online::GetB3atZVoiceInterface(World); if (VoiceInt.IsValid()) { return VoiceInt->MuteRemoteTalker(LocalUserNum, PlayerId, bIsSystemWide); } return false; } bool UB3atZOnlineEngineInterfaceImpl::UnmuteRemoteTalker(UWorld* World, uint8 LocalUserNum, const FUniqueNetId& PlayerId, bool bIsSystemWide) { IOnlineB3atZVoicePtr VoiceInt = Online::GetB3atZVoiceInterface(World); if (VoiceInt.IsValid()) { return VoiceInt->UnmuteRemoteTalker(LocalUserNum, PlayerId, bIsSystemWide); } return false; } int32 UB3atZOnlineEngineInterfaceImpl::GetNumLocalTalkers(UWorld* World) { IOnlineB3atZVoicePtr VoiceInt = Online::GetB3atZVoiceInterface(World); if (VoiceInt.IsValid()) { return VoiceInt->GetNumLocalTalkers(); } return 0; } void UB3atZOnlineEngineInterfaceImpl::ShowLeaderboardUI(UWorld* World, const FString& CategoryName) { IOnlineExternalUIPtr ExternalUI = Online::GetExternalUIInterface(); if(ExternalUI.IsValid()) { ExternalUI->ShowLeaderboardUI(CategoryName); } } void UB3atZOnlineEngineInterfaceImpl::ShowAchievementsUI(UWorld* World, int32 LocalUserNum) { IOnlineExternalUIPtr ExternalUI = Online::GetExternalUIInterface(); if (ExternalUI.IsValid()) { ExternalUI->ShowAchievementsUI(LocalUserNum); } } void UB3atZOnlineEngineInterfaceImpl::BindToExternalUIOpening(const FOnlineExternalUIChanged& Delegate) { UE_LOG(LogInit, VeryVerbose, TEXT("OEII BindToExternalUIOpening")); IOnlineSubsystemB3atZ* SubSystem = IOnlineSubsystemB3atZ::IsLoaded() ? IOnlineSubsystemB3atZ::Get() : nullptr; if (SubSystem != nullptr) { UE_LOG(LogInit, VeryVerbose, TEXT("OEII BindToExternalUIOpening Subsystem ptr valid")); IOnlineExternalUIPtr ExternalUI = SubSystem->GetExternalUIInterface(); if (ExternalUI.IsValid()) { FOnExternalUIChangeDelegate OnExternalUIChangeDelegate; OnExternalUIChangeDelegate.BindUObject(this, &ThisClass::OnExternalUIChange, Delegate); ExternalUI->AddOnExternalUIChangeDelegate_Handle(OnExternalUIChangeDelegate); } } IOnlineSubsystemB3atZ* SubSystemConsole = IOnlineSubsystemB3atZ::GetByPlatform(); if (SubSystemConsole != nullptr && SubSystem != SubSystemConsole) { IOnlineExternalUIPtr ExternalUI = SubSystemConsole->GetExternalUIInterface(); if (ExternalUI.IsValid()) { FOnExternalUIChangeDelegate OnExternalUIChangeDelegate; OnExternalUIChangeDelegate.BindUObject(this, &ThisClass::OnExternalUIChange, Delegate); ExternalUI->AddOnExternalUIChangeDelegate_Handle(OnExternalUIChangeDelegate); } } } void UB3atZOnlineEngineInterfaceImpl::OnExternalUIChange(bool bInIsOpening, FOnlineExternalUIChanged Delegate) { Delegate.ExecuteIfBound(bInIsOpening); } void UB3atZOnlineEngineInterfaceImpl::DumpSessionState(UWorld* World) { IOnlineSessionPtr SessionInt = Online::GetSessionInterface(GetWorld()); if (SessionInt.IsValid()) { SessionInt->DumpSessionState(); } } void UB3atZOnlineEngineInterfaceImpl::DumpVoiceState(UWorld* World) { IOnlineB3atZVoicePtr VoiceInt = Online::GetB3atZVoiceInterface(World); if (VoiceInt.IsValid()) { UE_LOG(LogB3atZOnline, Verbose, TEXT("\n%s"), *VoiceInt->GetVoiceDebugState()); } } //void UB3atZOnlineEngineInterfaceImpl::DumpChatState(UWorld* World) //{ // IB3atZOnlineChatPtr ChatInt = Online::GetChatInterface(World); // if (ChatInt.IsValid()) // { // ChatInt->DumpChatState(); // } //} #if WITH_EDITOR bool UB3atZOnlineEngineInterfaceImpl::SupportsOnlinePIE() { return Online::GetUtils()->SupportsOnlinePIE(); } void UB3atZOnlineEngineInterfaceImpl::SetShouldTryOnlinePIE(bool bShouldTry) { Online::GetUtils()->SetShouldTryOnlinePIE(bShouldTry); } int32 UB3atZOnlineEngineInterfaceImpl::GetNumPIELogins() { return Online::GetUtils()->GetNumPIELogins(); } void UB3atZOnlineEngineInterfaceImpl::SetForceDedicated(FName OnlineIdentifier, bool bForce) { IOnlineSubsystemB3atZ* OnlineSub = IOnlineSubsystemB3atZ::Get(OnlineIdentifier); if (OnlineSub) { OnlineSub->SetForceDedicated(bForce); } } void UB3atZOnlineEngineInterfaceImpl::LoginPIEInstance(FName OnlineIdentifier, int32 LocalUserNum, int32 PIELoginNum, FOnPIELoginComplete& CompletionDelegate) { UE_LOG(LogInit, VeryVerbose, TEXT("OEII LoginPIEInstance")); FString ErrorStr; if (SupportsOnlinePIE()) { TArray<FOnlineAccountCredentials> PIELogins; Online::GetUtils()->GetPIELogins(PIELogins); if (PIELogins.IsValidIndex(PIELoginNum)) { IOnlineIdentityPtr IdentityInt = Online::GetIdentityInterface(OnlineIdentifier); if (IdentityInt.IsValid()) { FDelegateHandle DelegateHandle = IdentityInt->AddOnLoginCompleteDelegate_Handle(LocalUserNum, FOnLoginCompleteDelegate::CreateUObject(this, &ThisClass::OnPIELoginComplete, OnlineIdentifier, CompletionDelegate)); OnLoginPIECompleteDelegateHandlesForPIEInstances.Add(OnlineIdentifier, DelegateHandle); IdentityInt->Login(LocalUserNum, PIELogins[PIELoginNum]); } else { ErrorStr = TEXT("No identify interface to login"); } } else { ErrorStr = TEXT("Invalid credentials for PIE login"); } } else { ErrorStr = TEXT("PIE login not supported"); } if (!ErrorStr.IsEmpty()) { CompletionDelegate.ExecuteIfBound(LocalUserNum, false, ErrorStr); } } void UB3atZOnlineEngineInterfaceImpl::OnPIELoginComplete(int32 LocalUserNum, bool bWasSuccessful, const FUniqueNetId& UserId, const FString& Error, FName OnlineIdentifier, FOnlineAutoLoginComplete InCompletionDelegate) { UE_LOG(LogInit, VeryVerbose, TEXT("OEII OnPIELoginComplete")); IOnlineIdentityPtr IdentityInt = Online::GetIdentityInterface(OnlineIdentifier); // Cleanup the login delegate before calling create below FDelegateHandle* DelegateHandle = OnLoginPIECompleteDelegateHandlesForPIEInstances.Find(OnlineIdentifier); if (DelegateHandle) { IdentityInt->ClearOnLoginCompleteDelegate_Handle(LocalUserNum, *DelegateHandle); OnLoginPIECompleteDelegateHandlesForPIEInstances.Remove(OnlineIdentifier); } InCompletionDelegate.ExecuteIfBound(LocalUserNum, bWasSuccessful, Error); } #endif
32.670669
231
0.806479
philippbb
ca42af470ab617eaefb44cdd1bd074cb0fbb60d8
3,136
cpp
C++
src/meta/processors/schema/DropEdgeProcessor.cpp
jackwener/nebula
d83f26db7ecc09cb9d97148dda7cb013a1aff08b
[ "Apache-2.0" ]
1
2022-02-17T03:41:13.000Z
2022-02-17T03:41:13.000Z
src/meta/processors/schema/DropEdgeProcessor.cpp
jackwener/nebula
d83f26db7ecc09cb9d97148dda7cb013a1aff08b
[ "Apache-2.0" ]
null
null
null
src/meta/processors/schema/DropEdgeProcessor.cpp
jackwener/nebula
d83f26db7ecc09cb9d97148dda7cb013a1aff08b
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2018 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #include "meta/processors/schema/DropEdgeProcessor.h" namespace nebula { namespace meta { void DropEdgeProcessor::process(const cpp2::DropEdgeReq& req) { GraphSpaceID spaceId = req.get_space_id(); CHECK_SPACE_ID_AND_RETURN(spaceId); folly::SharedMutex::ReadHolder rHolder(LockUtils::snapshotLock()); folly::SharedMutex::WriteHolder wHolder(LockUtils::tagAndEdgeLock()); const auto& edgeName = req.get_edge_name(); EdgeType edgeType; auto indexKey = MetaKeyUtils::indexEdgeKey(spaceId, edgeName); auto iRet = doGet(indexKey); if (nebula::ok(iRet)) { edgeType = *reinterpret_cast<const EdgeType*>(nebula::value(iRet).c_str()); resp_.id_ref() = to(edgeType, EntryType::EDGE); } else { auto retCode = nebula::error(iRet); if (retCode == nebula::cpp2::ErrorCode::E_KEY_NOT_FOUND) { if (req.get_if_exists()) { retCode = nebula::cpp2::ErrorCode::SUCCEEDED; } else { LOG(ERROR) << "Drop edge failed :" << edgeName << " not found."; retCode = nebula::cpp2::ErrorCode::E_EDGE_NOT_FOUND; } } else { LOG(ERROR) << "Get edgetype failed, edge name " << edgeName << " error: " << apache::thrift::util::enumNameSafe(retCode); } handleErrorCode(retCode); onFinished(); return; } auto indexes = getIndexes(spaceId, edgeType); if (!nebula::ok(indexes)) { handleErrorCode(nebula::error(indexes)); onFinished(); return; } if (!nebula::value(indexes).empty()) { LOG(ERROR) << "Drop edge error, index conflict, please delete index first."; handleErrorCode(nebula::cpp2::ErrorCode::E_CONFLICT); onFinished(); return; } auto ftIdxRet = getFTIndex(spaceId, edgeType); if (nebula::ok(ftIdxRet)) { LOG(ERROR) << "Drop edge error, fulltext index conflict, " << "please delete fulltext index first."; handleErrorCode(nebula::cpp2::ErrorCode::E_CONFLICT); onFinished(); return; } if (nebula::error(ftIdxRet) != nebula::cpp2::ErrorCode::E_INDEX_NOT_FOUND) { handleErrorCode(nebula::error(ftIdxRet)); onFinished(); return; } auto ret = getEdgeKeys(spaceId, edgeType); if (!nebula::ok(ret)) { handleErrorCode(nebula::error(ret)); onFinished(); return; } auto keys = nebula::value(ret); keys.emplace_back(std::move(indexKey)); LOG(INFO) << "Drop Edge " << edgeName; doSyncMultiRemoveAndUpdate(std::move(keys)); } ErrorOr<nebula::cpp2::ErrorCode, std::vector<std::string>> DropEdgeProcessor::getEdgeKeys( GraphSpaceID id, EdgeType edgeType) { std::vector<std::string> keys; auto key = MetaKeyUtils::schemaEdgePrefix(id, edgeType); auto iterRet = doPrefix(key); if (!nebula::ok(iterRet)) { LOG(ERROR) << "Edge schema prefix failed, edgetype " << edgeType; return nebula::error(iterRet); } auto iter = nebula::value(iterRet).get(); while (iter->valid()) { keys.emplace_back(iter->key()); iter->next(); } return keys; } } // namespace meta } // namespace nebula
30.153846
90
0.661671
jackwener
ca45982704eec4d69cd4481bcfb725d71800db45
4,008
cpp
C++
Engine/source/gfx/gfxVertexTypes.cpp
camporter/Torque3D
938e28b6f36883cb420da4b04253b1394467a1f4
[ "Unlicense" ]
13
2015-04-13T21:46:01.000Z
2017-11-20T22:12:04.000Z
Engine/source/gfx/gfxVertexTypes.cpp
timmgt/Torque3D
ebc6c9cf3a2c7642b2cd30be3726810a302c3deb
[ "Unlicense" ]
1
2015-11-16T23:57:12.000Z
2015-12-01T03:24:08.000Z
Engine/source/gfx/gfxVertexTypes.cpp
timmgt/Torque3D
ebc6c9cf3a2c7642b2cd30be3726810a302c3deb
[ "Unlicense" ]
10
2015-01-05T15:58:31.000Z
2021-11-20T14:05:46.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 "platform/platform.h" #include "gfx/gfxVertexTypes.h" GFXImplementVertexFormat( GFXVertexP ) { addElement( "POSITION", GFXDeclType_Float3 ); } GFXImplementVertexFormat( GFXVertexPT ) { addElement( "POSITION", GFXDeclType_Float3 ); addElement( "TEXCOORD", GFXDeclType_Float2, 0 ); } GFXImplementVertexFormat( GFXVertexPTT ) { addElement( "POSITION", GFXDeclType_Float3 ); addElement( "TEXCOORD", GFXDeclType_Float2, 0 ); addElement( "TEXCOORD", GFXDeclType_Float2, 1 ); } GFXImplementVertexFormat( GFXVertexPTTT ) { addElement( "POSITION", GFXDeclType_Float3 ); addElement( "TEXCOORD", GFXDeclType_Float2, 0 ); addElement( "TEXCOORD", GFXDeclType_Float2, 1 ); addElement( "TEXCOORD", GFXDeclType_Float2, 2 ); } GFXImplementVertexFormat( GFXVertexPC ) { addElement( "POSITION", GFXDeclType_Float3 ); addElement( "COLOR", GFXDeclType_Color ); } GFXImplementVertexFormat( GFXVertexPCN ) { addElement( "POSITION", GFXDeclType_Float3 ); addElement( "NORMAL", GFXDeclType_Float3 ); addElement( "COLOR", GFXDeclType_Color ); } GFXImplementVertexFormat( GFXVertexPCT ) { addElement( "POSITION", GFXDeclType_Float3 ); addElement( "COLOR", GFXDeclType_Color ); addElement( "TEXCOORD", GFXDeclType_Float2, 0 ); } GFXImplementVertexFormat( GFXVertexPCTT ) { addElement( "POSITION", GFXDeclType_Float3 ); addElement( "COLOR", GFXDeclType_Color ); addElement( "TEXCOORD", GFXDeclType_Float2, 0 ); addElement( "TEXCOORD", GFXDeclType_Float2, 1 ); } GFXImplementVertexFormat( GFXVertexPN ) { addElement( "POSITION", GFXDeclType_Float3 ); addElement( "NORMAL", GFXDeclType_Float3 ); } GFXImplementVertexFormat( GFXVertexPNT ) { addElement( "POSITION", GFXDeclType_Float3 ); addElement( "NORMAL", GFXDeclType_Float3 ); addElement( "TEXCOORD", GFXDeclType_Float2, 0 ); } GFXImplementVertexFormat( GFXVertexPNTT ) { addElement( "POSITION", GFXDeclType_Float3 ); addElement( "NORMAL", GFXDeclType_Float3 ); addElement( "TANGENT", GFXDeclType_Float3 ); addElement( "TEXCOORD", GFXDeclType_Float2, 0 ); } GFXImplementVertexFormat( GFXVertexPNTBT ) { addElement( "POSITION", GFXDeclType_Float3 ); addElement( "NORMAL", GFXDeclType_Float3 ); addElement( "TANGENT", GFXDeclType_Float3 ); addElement( "BINORMAL", GFXDeclType_Float3 ); addElement( "TEXCOORD", GFXDeclType_Float2, 0 ); } GFXImplementVertexFormat( GFXVertexPNTTB ) { addElement( "POSITION", GFXDeclType_Float3 ); addElement( "NORMAL", GFXDeclType_Float3 ); addElement( "TANGENT", GFXDeclType_Float3 ); addElement( "BINORMAL", GFXDeclType_Float3 ); addElement( "TEXCOORD", GFXDeclType_Float2, 0 ); addElement( "TEXCOORD", GFXDeclType_Float2, 1 ); }
33.4
79
0.715569
camporter
ca463eccc6c273452daf9c38250ac6b2afe6fc12
3,818
cpp
C++
src/Magnum/Vk/Test/DescriptorSetLayoutVkTest.cpp
nodoteve/magnum
8bb1da98b9c41fd0baa2246759721d8b8196a36b
[ "MIT" ]
null
null
null
src/Magnum/Vk/Test/DescriptorSetLayoutVkTest.cpp
nodoteve/magnum
8bb1da98b9c41fd0baa2246759721d8b8196a36b
[ "MIT" ]
null
null
null
src/Magnum/Vk/Test/DescriptorSetLayoutVkTest.cpp
nodoteve/magnum
8bb1da98b9c41fd0baa2246759721d8b8196a36b
[ "MIT" ]
null
null
null
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021 Vladimír Vondruš <mosra@centrum.cz> 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 <Corrade/Containers/Reference.h> #include "Magnum/Vk/DescriptorSetLayoutCreateInfo.h" #include "Magnum/Vk/Result.h" #include "Magnum/Vk/VulkanTester.h" namespace Magnum { namespace Vk { namespace Test { namespace { struct DescriptorSetLayoutVkTest: VulkanTester { explicit DescriptorSetLayoutVkTest(); void construct(); void constructMove(); void wrap(); }; DescriptorSetLayoutVkTest::DescriptorSetLayoutVkTest() { addTests({&DescriptorSetLayoutVkTest::construct, &DescriptorSetLayoutVkTest::constructMove, &DescriptorSetLayoutVkTest::wrap}); } void DescriptorSetLayoutVkTest::construct() { { DescriptorSetLayout layout{device(), DescriptorSetLayoutCreateInfo{ {{15, DescriptorType::UniformBuffer}} }}; CORRADE_VERIFY(layout.handle()); CORRADE_COMPARE(layout.handleFlags(), HandleFlag::DestroyOnDestruction); } /* Shouldn't crash or anything */ CORRADE_VERIFY(true); } void DescriptorSetLayoutVkTest::constructMove() { DescriptorSetLayout a{device(), DescriptorSetLayoutCreateInfo{ {{15, DescriptorType::UniformBuffer}} }}; VkDescriptorSetLayout handle = a.handle(); DescriptorSetLayout b = std::move(a); CORRADE_VERIFY(!a.handle()); CORRADE_COMPARE(b.handle(), handle); CORRADE_COMPARE(b.handleFlags(), HandleFlag::DestroyOnDestruction); DescriptorSetLayout c{NoCreate}; c = std::move(b); CORRADE_VERIFY(!b.handle()); CORRADE_COMPARE(b.handleFlags(), HandleFlags{}); CORRADE_COMPARE(c.handle(), handle); CORRADE_COMPARE(c.handleFlags(), HandleFlag::DestroyOnDestruction); CORRADE_VERIFY(std::is_nothrow_move_constructible<DescriptorSetLayout>::value); CORRADE_VERIFY(std::is_nothrow_move_assignable<DescriptorSetLayout>::value); } void DescriptorSetLayoutVkTest::wrap() { VkDescriptorSetLayout layout{}; CORRADE_COMPARE(Result(device()->CreateDescriptorSetLayout(device(), DescriptorSetLayoutCreateInfo{ {{15, DescriptorType::UniformBuffer}} }, nullptr, &layout)), Result::Success); auto wrapped = DescriptorSetLayout::wrap(device(), layout, HandleFlag::DestroyOnDestruction); CORRADE_COMPARE(wrapped.handle(), layout); /* Release the handle again, destroy by hand */ CORRADE_COMPARE(wrapped.release(), layout); CORRADE_VERIFY(!wrapped.handle()); device()->DestroyDescriptorSetLayout(device(), layout, nullptr); } }}}} CORRADE_TEST_MAIN(Magnum::Vk::Test::DescriptorSetLayoutVkTest)
36.361905
97
0.724201
nodoteve
ca46d49183d68ba4fd293829855e4a89d2097e7d
1,690
cpp
C++
dbms/src/Storages/DeltaMerge/tests/gtest_dm_configuration.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
85
2022-03-25T09:03:16.000Z
2022-03-25T09:45:03.000Z
dbms/src/Storages/DeltaMerge/tests/gtest_dm_configuration.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
7
2022-03-25T08:59:10.000Z
2022-03-25T09:40:13.000Z
dbms/src/Storages/DeltaMerge/tests/gtest_dm_configuration.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
11
2022-03-25T09:15:36.000Z
2022-03-25T09:45:07.000Z
// Copyright 2022 PingCAP, 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. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wsign-compare" #include <gtest/gtest.h> #pragma GCC diagnostic pop #include <Common/Checksum.h> #include <Storages/DeltaMerge/DMChecksumConfig.h> namespace DB::DM { template <ChecksumAlgo algo> void runSerializationTest() { DMChecksumConfig original{{{"abc", "abc"}, {"123", "123"}}, TIFLASH_DEFAULT_CHECKSUM_FRAME_SIZE, algo}; std::stringstream ss; ss << original; DMChecksumConfig deserialized(ss); ASSERT_EQ(original.getChecksumAlgorithm(), deserialized.getChecksumAlgorithm()); ASSERT_EQ(original.getChecksumFrameLength(), deserialized.getChecksumFrameLength()); ASSERT_EQ(original.getDebugInfo(), deserialized.getDebugInfo()); ASSERT_EQ(original.getEmbeddedChecksum(), deserialized.getEmbeddedChecksum()); }; #define TEST_SERIALIZATION(ALGO) \ TEST(DMConfiguration, ALGO##Serialization) { runSerializationTest<DB::ChecksumAlgo::ALGO>(); } TEST_SERIALIZATION(None) TEST_SERIALIZATION(CRC32) TEST_SERIALIZATION(CRC64) TEST_SERIALIZATION(City128) TEST_SERIALIZATION(XXH3) } // namespace DB::DM
34.489796
107
0.762722
solotzg
ca47a50bfa12b39f1a5c61eca23cd0ba3c58f36a
3,020
cpp
C++
src/backend/graphs/dijkstra.cpp
alex-x-o/Djiki
a684fc890ed867d4bb3deeedd4f327959dfbd68a
[ "MIT" ]
null
null
null
src/backend/graphs/dijkstra.cpp
alex-x-o/Djiki
a684fc890ed867d4bb3deeedd4f327959dfbd68a
[ "MIT" ]
null
null
null
src/backend/graphs/dijkstra.cpp
alex-x-o/Djiki
a684fc890ed867d4bb3deeedd4f327959dfbd68a
[ "MIT" ]
null
null
null
#include "dijkstra.hpp" #include <cmath> #include <QMap> #include <QSet> Dijkstra::Dijkstra() : GraphAlgorithm() { definePseudocode(); } Dijkstra::Dijkstra(Graph *g) : GraphAlgorithm(g) { definePseudocode(); } void Dijkstra::definePseudocode() { code.setInput("Graph G, starting node and target node"); code.setOutput("Shortest path from the starting node to the target node in graph G (if such path exists)"); code += "Put all nodes from graph G in set Q"; code += "While Q is not empty do"; code += "\tFind node N from Q which has with the smallest found distance to the starting node and delete it from Q"; code += "\tIf N is the target node "; code += "\t\tThen inform that the path has been found and reconstruct it (going backwards from the target node)"; code += "\tFor every node M from Q which is direct neighbour of N do"; code += "\t\tIf current distance from the starting node to M is bigger than distance from the starting node to M over node N "; code += "\t\t\tThen change parent of node M to N and remember new distance"; code += "Inform that requested path doesn't exist (Q is empty and path was not found)"; } void Dijkstra::solve() { QSet<Node*> Q; QMap<Node*, double> D; QMap<Node*, Node*> parent; parent[start] = start; for (auto& node: graph.getNodes()) { addState(node, 1); Q.insert(node); D[node] = std::numeric_limits<double>::infinity(); } D[start] = 0; while (Q.size() > 0) { Node* n = *Q.begin(); addState(n, 2); addState(n, 3); Q.erase(Q.find(n)); for (auto &w : Q) { addState(w, 2); if (std::fabs(D[w] - std::numeric_limits<double>::infinity()) < 0.001 && D[w] < D[n]) n = w; } if (std::fabs(D[n] - std::numeric_limits<double>::infinity()) < 0.001) { outcome = QString("Requested path doesn't exist!"); return; } addState(n, 4); if (n == end) { outcome = QString("Path has been found!"); std::vector<Node*> path; while (parent[n] != n) { addState(n, 5); path.push_back(n); n = parent[n]; } path.push_back(start); addState(start, 5); std::reverse(std::begin(path), std::end(path)); return; } for (auto m : graph.getNeighboursWeighted(n).toStdMap()) { addState(n, 6); addState(m.first, 7); if (std::fabs(D[m.first] - std::numeric_limits<double>::infinity()) < 0.001 || D[n] + m.second < D[m.first]) { addState(m.first, 8); D[m.first] = D[n] + m.second; parent[m.first] = n; } } } addState(start, 9); outcome = QString("Requested path doesn't exist!"); }
26.725664
131
0.533113
alex-x-o
ca494563b3c4c534a1c8c663e830bf8291d513d2
554
cpp
C++
BCPlayerBuilder/source_cpp/main.cpp
CommanderAsdasd/bcplayer
bf3481c9f08fb810660367b083392304479daaef
[ "MIT" ]
null
null
null
BCPlayerBuilder/source_cpp/main.cpp
CommanderAsdasd/bcplayer
bf3481c9f08fb810660367b083392304479daaef
[ "MIT" ]
null
null
null
BCPlayerBuilder/source_cpp/main.cpp
CommanderAsdasd/bcplayer
bf3481c9f08fb810660367b083392304479daaef
[ "MIT" ]
null
null
null
//#include <iostream> //#include <string> //#include <fstream> //#include <limits> //#include "MData.h" //#include "OSC.h" //#include "MPlayer.h" //#include "DelayLine.h" //#include "MML.h" #include "GUI.h" using namespace std; static const int SAMPLE_RATE = 44100; static const int TABLE_SIZE = 4096; static const int ENV_TABLE_SIZE = 1024; const float TWO_PI = 6.283185307; const int FRAMES_PER_BUFFER = 256; int main() { // initialize GUI // the GUI class is the main controller of this app GUI gui; gui.initialize(); gui.run(); return 0; }
18.466667
52
0.694946
CommanderAsdasd
ca4b7c114facc65a8b4b07e6a942df5ff8f8dbfc
3,737
cpp
C++
storage/diskmgr/services/storage_service/event_handler/src/local_envent_poll.cpp
peeweep/distributeddatamgr_file
1e624bbc3850815fa1b2642c67123b7785bec6a1
[ "Apache-2.0" ]
null
null
null
storage/diskmgr/services/storage_service/event_handler/src/local_envent_poll.cpp
peeweep/distributeddatamgr_file
1e624bbc3850815fa1b2642c67123b7785bec6a1
[ "Apache-2.0" ]
null
null
null
storage/diskmgr/services/storage_service/event_handler/src/local_envent_poll.cpp
peeweep/distributeddatamgr_file
1e624bbc3850815fa1b2642c67123b7785bec6a1
[ "Apache-2.0" ]
5
2021-09-13T11:18:04.000Z
2021-11-25T14:12:15.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 "local_envent_poll.h" #define LOG_TAG "LocalEventPoll" #include <cerrno> #include <cstdio> #include <cstdlib> #include <fcntl.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <sys/un.h> #include <unistd.h> #include <vector> #include "local_event_send.h" #include "storage_hilog.h" using namespace OHOS; static const int CTRL_PIPE_SHUT_DOWN = 0; static const int NUM_ONE_ = 1; static const int NUM_TWO_ = 2; pthread_mutex_t eventPollClientsLock = PTHREAD_MUTEX_INITIALIZER; LocalEventPoll::LocalEventPoll(int socketFd) { Init(socketFd); } void LocalEventPoll::Init(int socketFd) { eventPollSock = socketFd; } LocalEventPoll::~LocalEventPoll() { if (eventPollCtrlPipe[0] != -1) { close(eventPollCtrlPipe[0]); close(eventPollCtrlPipe[1]); } for (auto pair : eventPollClients) { pair.second->DelRef(); } } int LocalEventPoll::StartListener() { if (eventPollSock == -1) { errno = EINVAL; return -1; } eventPollClients[eventPollSock] = new LocalEventSend(eventPollSock); if (pipe2(eventPollCtrlPipe, O_CLOEXEC)) { return -1; } if (pthread_create(&eventPollThread, nullptr, LocalEventPoll::ListenThread, this)) { return -1; } return 0; } void *LocalEventPoll::ListenThread(void *obj) { LocalEventPoll *me = reinterpret_cast<LocalEventPoll *>(obj); me->RunListener(); pthread_exit(nullptr); return nullptr; } void LocalEventPoll::EventProcess(std::vector<pollfd> &fds) { std::vector<LocalEventSend *> pending; pthread_mutex_lock(&eventPollClientsLock); const int size = fds.size(); for (int i = NUM_ONE_; i < size; ++i) { const struct pollfd &p = fds[i]; if (p.revents & (POLLIN | POLLERR)) { auto it = eventPollClients.find(p.fd); if (it == eventPollClients.end()) { continue; } LocalEventSend *c = it->second; pending.push_back(c); c->AddRef(); } } pthread_mutex_unlock(&eventPollClientsLock); for (LocalEventSend *c : pending) { OnDataAvailable(c); c->DelRef(); } } void LocalEventPoll::RunListener() { std::vector<pollfd> fds; while (true) { pthread_mutex_lock(&eventPollClientsLock); fds.reserve(NUM_TWO_ + eventPollClients.size()); fds.push_back({ .fd = eventPollCtrlPipe[0], .events = POLLIN }); for (auto pair : eventPollClients) { const int fd = pair.second->getSocket(); fds.push_back({ .fd = fd, .events = POLLIN }); } pthread_mutex_unlock(&eventPollClientsLock); if (TEMP_FAILURE_RETRY(poll(fds.data(), fds.size(), -1)) < 0) { sleep(1); continue; } if (fds[0].revents & (POLLIN | POLLERR)) { char c = CTRL_PIPE_SHUT_DOWN; TEMP_FAILURE_RETRY(read(eventPollCtrlPipe[0], &c, 1)); if (c == CTRL_PIPE_SHUT_DOWN) { break; } continue; } EventProcess(fds); } }
26.132867
88
0.629917
peeweep
ca4d4f51743e6e0930346d80194500d895426651
7,134
hpp
C++
random/boost/random/poisson_ext/devroye/detail/q.hpp
rogard/boost_sandbox_statistics
16aacbc716a31a9f7bb6c535b1c90dc343282a23
[ "BSL-1.0" ]
null
null
null
random/boost/random/poisson_ext/devroye/detail/q.hpp
rogard/boost_sandbox_statistics
16aacbc716a31a9f7bb6c535b1c90dc343282a23
[ "BSL-1.0" ]
null
null
null
random/boost/random/poisson_ext/devroye/detail/q.hpp
rogard/boost_sandbox_statistics
16aacbc716a31a9f7bb6c535b1c90dc343282a23
[ "BSL-1.0" ]
null
null
null
////////////////////////////////////////////////////////////////////////////// // random::poisson_ex::poisson_devroye::q_function::standard.hpp // // // // // // (C) Copyright 2010 Erwann Rogard // // Use, modification and distribution are subject to 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 BOOST_RANDOM_POISSON_EXT_DEVROYE_Q_FUNCTION_STANDARD_HPP_ER_2010 #define BOOST_RANDOM_POISSON_EXT_DEVROYE_Q_FUNCTION_STANDARD_HPP_ER_2010 #include <cmath> #include <stdexcept> #include <string> #include <boost/format.hpp> #include <boost/mpl/bool.hpp> #include <boost/random/poisson_ext/devroye/detail/math.hpp> namespace boost{ namespace random{ namespace poisson{ namespace devroye{ namespace detail{ // The q-function is needed in either version of step4 of the algorithm. // See equation (4), p.199. // // TODO make static template<typename Int,typename T,typename P> struct q { typedef devroye::detail::math<Int,T,P> ma_; // TODO perhaps make this a template or runtime choice // For now overwrite manually. Checking may impedede speed a bit. typedef boost::mpl::bool_<true> do_check_; typedef std::string str_; typedef boost::format f_; static const str_ name(){ return "devroye::detail::q"; } public: q(){} typedef T float_; typedef Int int_; float_ q_fun(const int_& mean,const int_& y)const{ BOOST_ASSERT(y>=(-mean)); float_ result; if(y<0){ result = this->impl1(mean,y); }else{ if(y==0){ result = this->impl2(mean,y); }else{ if(y>0){ result = this->impl3(mean,y); }else{ throw std::runtime_error(name() + "q"); } } } if(do_check_::value){ this->check_against_slow_version(mean,y,result); this->check_lemma1(mean,y,result); this->check_lemma2(mean,y,result); } return result; } private: float_ slow_version(const int_& mean,const int_& y)const { return y * ma_::log(y) - ma_::log ( ma_::factorial(mean+y,P())/ma_::factorial(mean,P()) ); } void check_against_slow_version( const int_& mean, const int_& y, const float_& result )const { static const str_ str = name() + "::check_bound_against_slow_version, q(%1%) = %2% != %3%"; float_ alt = this->slow_version(mean,y); std::cout << "alt=" << alt << ' '; std::cout << "res=" << result << std::endl; if((result> alt + ma_::eps()) || (alt> result + ma_::eps()) ) { throw std::runtime_error( ( boost::format(str) % y % result % alt ).str() ); } } // Lemma 1, p.199 // q(y) < upper_bound(y) if y >= -mean float_ upper_bound(const int_& mean,const int_& y)const{ float_ num = ( - ma_::to_float(y) * ma_::to_float(1+y) ); float_ den = ma_::to_float(2 * mean); den += ma_::to_float((y<0)?0:y); return num / den; } void check_lemma1( const int_& mean, const int_& y, const float_& result )const{ if( y >= mean ){ float_ b = this->upper_bound(mean,y); if( result>b ){ static const str_ str = name() + "::check_bound, %1% = q(%2%) > %3%"; throw std::runtime_error( ( boost::format(str) % result % y % b ).str() ); } } } // Lemma 2, p. 199 void check_lemma2( const int_& mean, const int_& y, const float_& q_val )const{ static const str_ str1 = "q::check_lemma2(%1%,%2%,%3%) : failed condition(s) :"; int_ yp1 = y + 1; int_ yp1pm1 = yp1 + mean; int_ y2p1 = 2 * y + 1; int_ ysq = y * y; int_ yp1sq = yp1 * yp1; int_ m2 = 2 * mean; int_ msq = mean * mean; int_ mcu = msq * mean; float_ lhs = q_val + ma_::to_float( y * yp1 ) / ma_::to_float( m2 ); str_ str2; bool fail = false; if(y>=0) { if(!(lhs >= 0)){ str2 += (f_("1: lhs = %1% >= 0")%lhs).str(); fail = true; } }else{ if(!(lhs <= 0)){ str2 += (f_("1: lhs = %1% <= 0")%lhs).str(); fail = true; } } float_ rhs = ma_::to_float( y * yp1 * y2p1 ) / ma_::to_float(12 * msq); if(!(lhs <= rhs)){ f_ f2(" 2: lhs = %1% <= rhs = %2%"); str2 += (f2%lhs%rhs).str(); fail = true; } float_ num = ma_::to_float( ysq * yp1sq ); if(y>=0){ rhs -= ( num / ma_::to_float(12 * mcu) ); }else{ rhs -= ( num / ma_::to_float(12 * msq * yp1pm1) ); } if(!(lhs >= rhs)){ f_ f3(" 3: lhs = %1% >= rhs = %2%"); str2 += (f_(f3)%lhs%rhs).str(); fail = true; } if(fail){ str2 = (f_(str1)%mean%y%q_val).str() + str2; throw std::runtime_error(str2); } } // TODO consider using // #include <boost/math/tools/series.hpp> float_ impl1(const int_& mean,const int_& y)const{ BOOST_ASSERT(y<0); float_ im1 = ma_::to_float(1) / ma_::to_float(mean); float_ result = ma_::to_float(0); int_ n = -(y+1) + 1; for(int_ i = 0; i < n; i++){ result += ma_::log1p(-ma_::to_float(i)*im1,P()); } return result; } float_ impl2(const int_& mean,const int_& y)const{ BOOST_ASSERT(y==0); return ma_::to_float(0); } float_ impl3(const int_& mean,const int_& y)const{ BOOST_ASSERT(y>0); float_ im1 = ma_::to_float(1) / ma_::to_float(mean); float_ result = ma_::to_float(0); int n = y+1; for(int_ i = 1; i < n; i++){ result -= ma_::log1p(ma_::to_float(i)*im1,P()); } return result; } }; }// q_function }// devroye }// poisson }// random }// boost #endif
31.152838
83
0.442248
rogard
ca4f4b45c69b4f7c5b399abcd10a1b798a90b78d
1,516
hpp
C++
shared_model/backend/protobuf/queries/proto_get_account_detail.hpp
132/iroha
66e1a490dc8917530020c53d162c573571deafd3
[ "Apache-2.0" ]
null
null
null
shared_model/backend/protobuf/queries/proto_get_account_detail.hpp
132/iroha
66e1a490dc8917530020c53d162c573571deafd3
[ "Apache-2.0" ]
null
null
null
shared_model/backend/protobuf/queries/proto_get_account_detail.hpp
132/iroha
66e1a490dc8917530020c53d162c573571deafd3
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_PROTO_GET_ACCOUNT_DETAIL_HPP #define IROHA_PROTO_GET_ACCOUNT_DETAIL_HPP #include "backend/protobuf/common_objects/trivial_proto.hpp" #include "backend/protobuf/queries/proto_account_detail_pagination_meta.hpp" #include "interfaces/queries/get_account_detail.hpp" #include "queries.pb.h" namespace shared_model { namespace proto { class GetAccountDetail final : public TrivialProto<interface::GetAccountDetail, iroha::protocol::Query> { public: template <typename QueryType> explicit GetAccountDetail(QueryType &&query); GetAccountDetail(const GetAccountDetail &o); GetAccountDetail(GetAccountDetail &&o) noexcept; const interface::types::AccountIdType &accountId() const override; boost::optional<interface::types::AccountDetailKeyType> key() const override; boost::optional<interface::types::AccountIdType> writer() const override; boost::optional<const interface::AccountDetailPaginationMeta &> paginationMeta() const override; private: // ------------------------------| fields |------------------------------- const iroha::protocol::GetAccountDetail &account_detail_; const boost::optional<const AccountDetailPaginationMeta> pagination_meta_; }; } // namespace proto } // namespace shared_model #endif // IROHA_PROTO_GET_ACCOUNT_DETAIL_HPP
32.255319
80
0.699208
132
ca564e8b1d61f61713643cc87ba19b36b6b1be5e
2,525
cc
C++
modules/audio_processing/agc2/gain_controller2.cc
laloli/webrtc_src
2a4d70cc93ddd3074e51c0a2c2de507ac6babc2a
[ "DOC", "BSD-3-Clause" ]
6
2020-03-18T08:21:45.000Z
2021-02-06T14:37:57.000Z
modules/audio_processing/agc2/gain_controller2.cc
laloli/webrtc_src
2a4d70cc93ddd3074e51c0a2c2de507ac6babc2a
[ "DOC", "BSD-3-Clause" ]
1
2018-02-10T01:29:22.000Z
2018-02-10T01:29:22.000Z
modules/audio_processing/agc2/gain_controller2.cc
laloli/webrtc_src
2a4d70cc93ddd3074e51c0a2c2de507ac6babc2a
[ "DOC", "BSD-3-Clause" ]
3
2018-07-23T04:52:42.000Z
2021-12-18T07:37:15.000Z
/* * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/audio_processing/agc2/gain_controller2.h" #include <cmath> #include "modules/audio_processing/audio_buffer.h" #include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/atomicops.h" #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_minmax.h" namespace webrtc { int GainController2::instance_count_ = 0; GainController2::GainController2() : data_dumper_( new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))), sample_rate_hz_(AudioProcessing::kSampleRate48kHz), fixed_gain_(1.f) {} GainController2::~GainController2() = default; void GainController2::Initialize(int sample_rate_hz) { RTC_DCHECK(sample_rate_hz == AudioProcessing::kSampleRate8kHz || sample_rate_hz == AudioProcessing::kSampleRate16kHz || sample_rate_hz == AudioProcessing::kSampleRate32kHz || sample_rate_hz == AudioProcessing::kSampleRate48kHz); sample_rate_hz_ = sample_rate_hz; data_dumper_->InitiateNewSetOfRecordings(); data_dumper_->DumpRaw("sample_rate_hz", sample_rate_hz_); data_dumper_->DumpRaw("fixed_gain_linear", fixed_gain_); } void GainController2::Process(AudioBuffer* audio) { if (fixed_gain_ == 1.f) return; for (size_t k = 0; k < audio->num_channels(); ++k) { for (size_t j = 0; j < audio->num_frames(); ++j) { audio->channels_f()[k][j] = rtc::SafeClamp( fixed_gain_ * audio->channels_f()[k][j], -32768.f, 32767.f); } } } void GainController2::ApplyConfig( const AudioProcessing::Config::GainController2& config) { RTC_DCHECK(Validate(config)); fixed_gain_ = std::pow(10.f, config.fixed_gain_db / 20.f); } bool GainController2::Validate( const AudioProcessing::Config::GainController2& config) { return config.fixed_gain_db >= 0.f; } std::string GainController2::ToString( const AudioProcessing::Config::GainController2& config) { std::stringstream ss; ss << "{enabled: " << (config.enabled ? "true" : "false") << ", " << "fixed_gain_dB: " << config.fixed_gain_db << "}"; return ss.str(); } } // namespace webrtc
33.223684
74
0.712475
laloli
ca57dabdc17deda917652f0906b3ba5e57e4e783
2,863
hpp
C++
src/geometry/3d/vector.hpp
IsraelEfraim/cpp-engine
039bcad97d55635a7a8f31d0d80ce59095ebb6cb
[ "MIT" ]
null
null
null
src/geometry/3d/vector.hpp
IsraelEfraim/cpp-engine
039bcad97d55635a7a8f31d0d80ce59095ebb6cb
[ "MIT" ]
null
null
null
src/geometry/3d/vector.hpp
IsraelEfraim/cpp-engine
039bcad97d55635a7a8f31d0d80ce59095ebb6cb
[ "MIT" ]
2
2021-03-15T18:51:32.000Z
2021-07-19T23:45:49.000Z
#ifndef CPP_ENGINE_VECTOR_HPP #define CPP_ENGINE_VECTOR_HPP #include <cmath> #include <type_traits> #include "../axis.hpp" #include "../../utility/concepts.hpp" namespace engine::space3D { template <class V> concept Dim3_Vec = requires(std::remove_cvref_t<V> v) { { v.x } -> Number; { v.y } -> Number; { v.z } -> Number; }; template <Number T> struct Vector_3D { T x; T y; T z; }; /* Shorthands */ using Vector_3Di = Vector_3D<int>; using Vector_3Df = Vector_3D<float>; using Vector_3Dd = Vector_3D<double>; /* Utility */ template <Dim3_Vec U, Dim3_Vec V> auto dot_product(U const& u, V const& v) { return u.x * v.x + u.y * v.y + u.z * v.z; } template <Dim3_Vec U> auto magnitude(U const& u) { return std::sqrt(dot_product(u, u)); } template <Dim3_Vec U> auto normalize(U const& u) -> U { if (auto mag = magnitude(u); mag > 0) { auto inv = 1 / mag; return { u.x * inv, u.y * inv, u.z * inv }; } return u; } template <Dim3_Vec U, Dim3_Vec V> auto minus(U const& u, V const& v) -> U { return U{ u.x - v.x, u.y - v.y, u.z - v.z }; } template <Dim3_Vec U, Dim3_Vec V> auto operator-(U const& u, V const& v) -> U { return minus(u, v); } template <Dim3_Vec U, Dim3_Vec V> auto plus(U const& u, V const& v) -> U { return U{ u.x + v.x, u.y + v.y, u.z + v.z }; } template <Dim3_Vec U, Dim3_Vec V> auto operator+(U const& u, V const& v) -> U { return plus(u, v); } template <Dim3_Vec U, Dim3_Vec V> auto distance_squared(U const& u, V const& v) { auto delta = u - v; return dot_product(delta, delta); } template <axis::Axis A> struct less_t {}; template <Dim3_Vec U, Dim3_Vec V> inline constexpr auto less(axis::X_t, U && u, V && v) -> bool { return u.x < v.x; } template <Dim3_Vec U, Dim3_Vec V> inline constexpr auto less(axis::Y_t, U && u, V && v) -> bool { return u.y < v.y; } template <Dim3_Vec U, Dim3_Vec V> inline constexpr auto less(axis::Z_t, U && u, V && v) -> bool { return u.z < v.z; } template <> struct less_t<axis::X_t> { template <Dim3_Vec U, Dim3_Vec V> inline constexpr auto operator()(U && u, V && v) -> bool { return less(axis::X, u, v); } }; inline constexpr auto less(axis::X_t) -> less_t<axis::X_t> { return {}; } template <> struct less_t<axis::Y_t> { template <Dim3_Vec U, Dim3_Vec V> inline constexpr auto operator()(U && u, V && v) -> bool { return less(axis::Y, u, v); } }; inline constexpr auto less(axis::Y_t) -> less_t<axis::Y_t> { return {}; } template <> struct less_t<axis::Z_t> { template <Dim3_Vec U, Dim3_Vec V> inline constexpr auto operator()(U && u, V && v) -> bool { return less(axis::Z, u, v); } }; inline constexpr auto less(axis::Z_t) -> less_t<axis::Z_t> { return {}; } } // namespace engine::space3D #endif //CPP_ENGINE_VECTOR_HPP
21.207407
63
0.603213
IsraelEfraim
ca59a756a78a6fd211a7406b981ca12acd46d72c
12,012
cpp
C++
HoikuCamApp/src/Palettes.cpp
h7ga40/PeachCam
06d023a908dc38228e77b47f80bc8496a4d35806
[ "Apache-2.0" ]
1
2019-12-13T05:51:34.000Z
2019-12-13T05:51:34.000Z
HoikuCamApp/src/Palettes.cpp
h7ga40/PeachCam
06d023a908dc38228e77b47f80bc8496a4d35806
[ "Apache-2.0" ]
null
null
null
HoikuCamApp/src/Palettes.cpp
h7ga40/PeachCam
06d023a908dc38228e77b47f80bc8496a4d35806
[ "Apache-2.0" ]
1
2021-09-17T15:41:36.000Z
2021-09-17T15:41:36.000Z
#include "Palettes.h" const uint8_t colormap_rainbow[] = { 1, 3, 74, 0, 3, 74, 0, 3, 75, 0, 3, 75, 0, 3, 76, 0, 3, 76, 0, 3, 77, 0, 3, 79, 0, 3, 82, 0, 5, 85, 0, 7, 88, 0, 10, 91, 0, 14, 94, 0, 19, 98, 0, 22, 100, 0, 25, 103, 0, 28, 106, 0, 32, 109, 0, 35, 112, 0, 38, 116, 0, 40, 119, 0, 42, 123, 0, 45, 128, 0, 49, 133, 0, 50, 134, 0, 51, 136, 0, 52, 137, 0, 53, 139, 0, 54, 142, 0, 55, 144, 0, 56, 145, 0, 58, 149, 0, 61, 154, 0, 63, 156, 0, 65, 159, 0, 66, 161, 0, 68, 164, 0, 69, 167, 0, 71, 170, 0, 73, 174, 0, 75, 179, 0, 76, 181, 0, 78, 184, 0, 79, 187, 0, 80, 188, 0, 81, 190, 0, 84, 194, 0, 87, 198, 0, 88, 200, 0, 90, 203, 0, 92, 205, 0, 94, 207, 0, 94, 208, 0, 95, 209, 0, 96, 210, 0, 97, 211, 0, 99, 214, 0, 102, 217, 0, 103, 218, 0, 104, 219, 0, 105, 220, 0, 107, 221, 0, 109, 223, 0, 111, 223, 0, 113, 223, 0, 115, 222, 0, 117, 221, 0, 118, 220, 1, 120, 219, 1, 122, 217, 2, 124, 216, 2, 126, 214, 3, 129, 212, 3, 131, 207, 4, 132, 205, 4, 133, 202, 4, 134, 197, 5, 136, 192, 6, 138, 185, 7, 141, 178, 8, 142, 172, 10, 144, 166, 10, 144, 162, 11, 145, 158, 12, 146, 153, 13, 147, 149, 15, 149, 140, 17, 151, 132, 22, 153, 120, 25, 154, 115, 28, 156, 109, 34, 158, 101, 40, 160, 94, 45, 162, 86, 51, 164, 79, 59, 167, 69, 67, 171, 60, 72, 173, 54, 78, 175, 48, 83, 177, 43, 89, 179, 39, 93, 181, 35, 98, 183, 31, 105, 185, 26, 109, 187, 23, 113, 188, 21, 118, 189, 19, 123, 191, 17, 128, 193, 14, 134, 195, 12, 138, 196, 10, 142, 197, 8, 146, 198, 6, 151, 200, 5, 155, 201, 4, 160, 203, 3, 164, 204, 2, 169, 205, 2, 173, 206, 1, 175, 207, 1, 178, 207, 1, 184, 208, 0, 190, 210, 0, 193, 211, 0, 196, 212, 0, 199, 212, 0, 202, 213, 1, 207, 214, 2, 212, 215, 3, 215, 214, 3, 218, 214, 3, 220, 213, 3, 222, 213, 4, 224, 212, 4, 225, 212, 5, 226, 212, 5, 229, 211, 5, 232, 211, 6, 232, 211, 6, 233, 211, 6, 234, 210, 6, 235, 210, 7, 236, 209, 7, 237, 208, 8, 239, 206, 8, 241, 204, 9, 242, 203, 9, 244, 202, 10, 244, 201, 10, 245, 200, 10, 245, 199, 11, 246, 198, 11, 247, 197, 12, 248, 194, 13, 249, 191, 14, 250, 189, 14, 251, 187, 15, 251, 185, 16, 252, 183, 17, 252, 178, 18, 253, 174, 19, 253, 171, 19, 254, 168, 20, 254, 165, 21, 254, 164, 21, 255, 163, 22, 255, 161, 22, 255, 159, 23, 255, 157, 23, 255, 155, 24, 255, 149, 25, 255, 143, 27, 255, 139, 28, 255, 135, 30, 255, 131, 31, 255, 127, 32, 255, 118, 34, 255, 110, 36, 255, 104, 37, 255, 101, 38, 255, 99, 39, 255, 93, 40, 255, 88, 42, 254, 82, 43, 254, 77, 45, 254, 69, 47, 254, 62, 49, 253, 57, 50, 253, 53, 52, 252, 49, 53, 252, 45, 55, 251, 39, 57, 251, 33, 59, 251, 32, 60, 251, 31, 60, 251, 30, 61, 251, 29, 61, 251, 28, 62, 250, 27, 63, 250, 27, 65, 249, 26, 66, 249, 26, 68, 248, 25, 70, 248, 24, 73, 247, 24, 75, 247, 25, 77, 247, 25, 79, 247, 26, 81, 247, 32, 83, 247, 35, 85, 247, 38, 86, 247, 42, 88, 247, 46, 90, 247, 50, 92, 248, 55, 94, 248, 59, 96, 248, 64, 98, 248, 72, 101, 249, 81, 104, 249, 87, 106, 250, 93, 108, 250, 95, 109, 250, 98, 110, 250, 100, 111, 251, 101, 112, 251, 102, 113, 251, 109, 117, 252, 116, 121, 252, 121, 123, 253, 126, 126, 253, 130, 128, 254, 135, 131, 254, 139, 133, 254, 144, 136, 254, 151, 140, 255, 158, 144, 255, 163, 146, 255, 168, 149, 255, 173, 152, 255, 176, 153, 255, 178, 155, 255, 184, 160, 255, 191, 165, 255, 195, 168, 255, 199, 172, 255, 203, 175, 255, 207, 179, 255, 211, 182, 255, 216, 185, 255, 218, 190, 255, 220, 196, 255, 222, 200, 255, 225, 202, 255, 227, 204, 255, 230, 206, 255, 233, 208 }; const uint8_t colormap_grayscale[] = { 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 15, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 20, 20, 20, 21, 21, 21, 22, 22, 22, 23, 23, 23, 24, 24, 24, 25, 25, 25, 26, 26, 26, 27, 27, 27, 28, 28, 28, 29, 29, 29, 30, 30, 30, 31, 31, 31, 32, 32, 32, 33, 33, 33, 34, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 40, 40, 40, 41, 41, 41, 42, 42, 42, 43, 43, 43, 44, 44, 44, 45, 45, 45, 46, 46, 46, 47, 47, 47, 48, 48, 48, 49, 49, 49, 50, 50, 50, 51, 51, 51, 52, 52, 52, 53, 53, 53, 54, 54, 54, 55, 55, 55, 56, 56, 56, 57, 57, 57, 58, 58, 58, 59, 59, 59, 60, 60, 60, 61, 61, 61, 62, 62, 62, 63, 63, 63, 64, 64, 64, 65, 65, 65, 66, 66, 66, 67, 67, 67, 68, 68, 68, 69, 69, 69, 70, 70, 70, 71, 71, 71, 72, 72, 72, 73, 73, 73, 74, 74, 74, 75, 75, 75, 76, 76, 76, 77, 77, 77, 78, 78, 78, 79, 79, 79, 80, 80, 80, 81, 81, 81, 82, 82, 82, 83, 83, 83, 84, 84, 84, 85, 85, 85, 86, 86, 86, 87, 87, 87, 88, 88, 88, 89, 89, 89, 90, 90, 90, 91, 91, 91, 92, 92, 92, 93, 93, 93, 94, 94, 94, 95, 95, 95, 96, 96, 96, 97, 97, 97, 98, 98, 98, 99, 99, 99, 100, 100, 100, 101, 101, 101, 102, 102, 102, 103, 103, 103, 104, 104, 104, 105, 105, 105, 106, 106, 106, 107, 107, 107, 108, 108, 108, 109, 109, 109, 110, 110, 110, 111, 111, 111, 112, 112, 112, 113, 113, 113, 114, 114, 114, 115, 115, 115, 116, 116, 116, 117, 117, 117, 118, 118, 118, 119, 119, 119, 120, 120, 120, 121, 121, 121, 122, 122, 122, 123, 123, 123, 124, 124, 124, 125, 125, 125, 126, 126, 126, 127, 127, 127, 128, 128, 128, 129, 129, 129, 130, 130, 130, 131, 131, 131, 132, 132, 132, 133, 133, 133, 134, 134, 134, 135, 135, 135, 136, 136, 136, 137, 137, 137, 138, 138, 138, 139, 139, 139, 140, 140, 140, 141, 141, 141, 142, 142, 142, 143, 143, 143, 144, 144, 144, 145, 145, 145, 146, 146, 146, 147, 147, 147, 148, 148, 148, 149, 149, 149, 150, 150, 150, 151, 151, 151, 152, 152, 152, 153, 153, 153, 154, 154, 154, 155, 155, 155, 156, 156, 156, 157, 157, 157, 158, 158, 158, 159, 159, 159, 160, 160, 160, 161, 161, 161, 162, 162, 162, 163, 163, 163, 164, 164, 164, 165, 165, 165, 166, 166, 166, 167, 167, 167, 168, 168, 168, 169, 169, 169, 170, 170, 170, 171, 171, 171, 172, 172, 172, 173, 173, 173, 174, 174, 174, 175, 175, 175, 176, 176, 176, 177, 177, 177, 178, 178, 178, 179, 179, 179, 180, 180, 180, 181, 181, 181, 182, 182, 182, 183, 183, 183, 184, 184, 184, 185, 185, 185, 186, 186, 186, 187, 187, 187, 188, 188, 188, 189, 189, 189, 190, 190, 190, 191, 191, 191, 192, 192, 192, 193, 193, 193, 194, 194, 194, 195, 195, 195, 196, 196, 196, 197, 197, 197, 198, 198, 198, 199, 199, 199, 200, 200, 200, 201, 201, 201, 202, 202, 202, 203, 203, 203, 204, 204, 204, 205, 205, 205, 206, 206, 206, 207, 207, 207, 208, 208, 208, 209, 209, 209, 210, 210, 210, 211, 211, 211, 212, 212, 212, 213, 213, 213, 214, 214, 214, 215, 215, 215, 216, 216, 216, 217, 217, 217, 218, 218, 218, 219, 219, 219, 220, 220, 220, 221, 221, 221, 222, 222, 222, 223, 223, 223, 224, 224, 224, 225, 225, 225, 226, 226, 226, 227, 227, 227, 228, 228, 228, 229, 229, 229, 230, 230, 230, 231, 231, 231, 232, 232, 232, 233, 233, 233, 234, 234, 234, 235, 235, 235, 236, 236, 236, 237, 237, 237, 238, 238, 238, 239, 239, 239, 240, 240, 240, 241, 241, 241, 242, 242, 242, 243, 243, 243, 244, 244, 244, 245, 245, 245, 246, 246, 246, 247, 247, 247, 248, 248, 248, 249, 249, 249, 250, 250, 250, 251, 251, 251, 252, 252, 252, 253, 253, 253, 254, 254, 254, 255, 255, 255 }; const uint8_t colormap_ironblack[] = { 255, 255, 255, 253, 253, 253, 251, 251, 251, 249, 249, 249, 247, 247, 247, 245, 245, 245, 243, 243, 243, 241, 241, 241, 239, 239, 239, 237, 237, 237, 235, 235, 235, 233, 233, 233, 231, 231, 231, 229, 229, 229, 227, 227, 227, 225, 225, 225, 223, 223, 223, 221, 221, 221, 219, 219, 219, 217, 217, 217, 215, 215, 215, 213, 213, 213, 211, 211, 211, 209, 209, 209, 207, 207, 207, 205, 205, 205, 203, 203, 203, 201, 201, 201, 199, 199, 199, 197, 197, 197, 195, 195, 195, 193, 193, 193, 191, 191, 191, 189, 189, 189, 187, 187, 187, 185, 185, 185, 183, 183, 183, 181, 181, 181, 179, 179, 179, 177, 177, 177, 175, 175, 175, 173, 173, 173, 171, 171, 171, 169, 169, 169, 167, 167, 167, 165, 165, 165, 163, 163, 163, 161, 161, 161, 159, 159, 159, 157, 157, 157, 155, 155, 155, 153, 153, 153, 151, 151, 151, 149, 149, 149, 147, 147, 147, 145, 145, 145, 143, 143, 143, 141, 141, 141, 139, 139, 139, 137, 137, 137, 135, 135, 135, 133, 133, 133, 131, 131, 131, 129, 129, 129, 126, 126, 126, 124, 124, 124, 122, 122, 122, 120, 120, 120, 118, 118, 118, 116, 116, 116, 114, 114, 114, 112, 112, 112, 110, 110, 110, 108, 108, 108, 106, 106, 106, 104, 104, 104, 102, 102, 102, 100, 100, 100, 98, 98, 98, 96, 96, 96, 94, 94, 94, 92, 92, 92, 90, 90, 90, 88, 88, 88, 86, 86, 86, 84, 84, 84, 82, 82, 82, 80, 80, 80, 78, 78, 78, 76, 76, 76, 74, 74, 74, 72, 72, 72, 70, 70, 70, 68, 68, 68, 66, 66, 66, 64, 64, 64, 62, 62, 62, 60, 60, 60, 58, 58, 58, 56, 56, 56, 54, 54, 54, 52, 52, 52, 50, 50, 50, 48, 48, 48, 46, 46, 46, 44, 44, 44, 42, 42, 42, 40, 40, 40, 38, 38, 38, 36, 36, 36, 34, 34, 34, 32, 32, 32, 30, 30, 30, 28, 28, 28, 26, 26, 26, 24, 24, 24, 22, 22, 22, 20, 20, 20, 18, 18, 18, 16, 16, 16, 14, 14, 14, 12, 12, 12, 10, 10, 10, 8, 8, 8, 6, 6, 6, 4, 4, 4, 2, 2, 2, 0, 0, 0, 0, 0, 9, 2, 0, 16, 4, 0, 24, 6, 0, 31, 8, 0, 38, 10, 0, 45, 12, 0, 53, 14, 0, 60, 17, 0, 67, 19, 0, 74, 21, 0, 82, 23, 0, 89, 25, 0, 96, 27, 0, 103, 29, 0, 111, 31, 0, 118, 36, 0, 120, 41, 0, 121, 46, 0, 122, 51, 0, 123, 56, 0, 124, 61, 0, 125, 66, 0, 126, 71, 0, 127, 76, 1, 128, 81, 1, 129, 86, 1, 130, 91, 1, 131, 96, 1, 132, 101, 1, 133, 106, 1, 134, 111, 1, 135, 116, 1, 136, 121, 1, 136, 125, 2, 137, 130, 2, 137, 135, 3, 137, 139, 3, 138, 144, 3, 138, 149, 4, 138, 153, 4, 139, 158, 5, 139, 163, 5, 139, 167, 5, 140, 172, 6, 140, 177, 6, 140, 181, 7, 141, 186, 7, 141, 189, 10, 137, 191, 13, 132, 194, 16, 127, 196, 19, 121, 198, 22, 116, 200, 25, 111, 203, 28, 106, 205, 31, 101, 207, 34, 95, 209, 37, 90, 212, 40, 85, 214, 43, 80, 216, 46, 75, 218, 49, 69, 221, 52, 64, 223, 55, 59, 224, 57, 49, 225, 60, 47, 226, 64, 44, 227, 67, 42, 228, 71, 39, 229, 74, 37, 230, 78, 34, 231, 81, 32, 231, 85, 29, 232, 88, 27, 233, 92, 24, 234, 95, 22, 235, 99, 19, 236, 102, 17, 237, 106, 14, 238, 109, 12, 239, 112, 12, 240, 116, 12, 240, 119, 12, 241, 123, 12, 241, 127, 12, 242, 130, 12, 242, 134, 12, 243, 138, 12, 243, 141, 13, 244, 145, 13, 244, 149, 13, 245, 152, 13, 245, 156, 13, 246, 160, 13, 246, 163, 13, 247, 167, 13, 247, 171, 13, 248, 175, 14, 248, 178, 15, 249, 182, 16, 249, 185, 18, 250, 189, 19, 250, 192, 20, 251, 196, 21, 251, 199, 22, 252, 203, 23, 252, 206, 24, 253, 210, 25, 253, 213, 27, 254, 217, 28, 254, 220, 29, 255, 224, 30, 255, 227, 39, 255, 229, 53, 255, 231, 67, 255, 233, 81, 255, 234, 95, 255, 236, 109, 255, 238, 123, 255, 240, 137, 255, 242, 151, 255, 244, 165, 255, 246, 179, 255, 248, 193, 255, 249, 207, 255, 251, 221, 255, 253, 235, 255, 255, 24 };
15.419769
39
0.484182
h7ga40
3ed11a7a66441cc5b9a178f25561931f6c0df40f
5,008
cpp
C++
src/ice/src/ice/net/service.cpp
qis/ice-coroutines
30bb5fe7956e48230756db112ee71d6a1aa71202
[ "MIT" ]
2
2019-03-23T16:57:17.000Z
2020-11-24T20:10:45.000Z
src/ice/src/ice/net/service.cpp
qis/ice-coroutines
30bb5fe7956e48230756db112ee71d6a1aa71202
[ "MIT" ]
null
null
null
src/ice/src/ice/net/service.cpp
qis/ice-coroutines
30bb5fe7956e48230756db112ee71d6a1aa71202
[ "MIT" ]
null
null
null
#include "ice/net/service.hpp" #include <ice/error.hpp> #include <ice/net/event.hpp> #include <vector> #include <cassert> #include <ctime> #if ICE_OS_WIN32 # include <windows.h> # include <winsock2.h> #else # if ICE_OS_LINUX # include <sys/epoll.h> # include <sys/eventfd.h> # elif ICE_OS_FREEBSD # include <sys/event.h> # endif # include <unistd.h> #endif #include <ice/log.hpp> namespace ice::net { #if ICE_OS_WIN32 void service::close_type::operator()(std::uintptr_t handle) noexcept { ::CloseHandle(reinterpret_cast<HANDLE>(handle)); } #else void service::close_type::operator()(int handle) noexcept { ::close(handle); } #endif std::error_code service::create() noexcept { #if ICE_OS_WIN32 struct wsa { wsa() noexcept { WSADATA wsadata = {}; if (const auto rc = ::WSAStartup(MAKEWORD(2, 2), &wsadata)) { ec = make_error_code(rc); } const auto major = LOBYTE(wsadata.wVersion); const auto minor = HIBYTE(wsadata.wVersion); if (major < 2 || (major == 2 && minor < 2)) { ec = make_error_code(errc::version_mismatch); } } std::error_code ec; }; static const wsa wsa; if (wsa.ec) { return wsa.ec; } handle_type handle(::CreateIoCompletionPort(INVALID_HANDLE_VALUE, nullptr, 0, 1)); if (!handle) { return make_error_code(::GetLastError()); } #elif ICE_OS_LINUX handle_type handle(::epoll_create1(0)); if (!handle) { return make_error_code(errno); } handle_type events(::eventfd(0, EFD_NONBLOCK)); if (!events) { return make_error_code(errno); } epoll_event nev = { EPOLLONESHOT, {} }; if (::epoll_ctl(handle, EPOLL_CTL_ADD, events, &nev) < 0) { return make_error_code(errno); } events_ = std::move(events); #elif ICE_OS_FREEBSD handle_type handle(::kqueue()); if (!handle) { return make_error_code(errno); } struct kevent nev = {}; EV_SET(&nev, 0, EVFILT_USER, EV_ADD | EV_CLEAR, 0, 0, nullptr); if (::kevent(handle, &nev, 1, nullptr, 0, nullptr) < 0) { return make_error_code(errno); } #endif handle_ = std::move(handle); return interrupt(); } std::error_code service::run(std::size_t event_buffer_size) noexcept { #if ICE_OS_WIN32 using data_type = OVERLAPPED_ENTRY; using size_type = ULONG; #elif ICE_OS_LINUX using data_type = struct epoll_event; using size_type = int; #elif ICE_OS_FREEBSD using data_type = struct kevent; using size_type = int; #endif std::vector<data_type> events; events.resize(event_buffer_size); const auto index = index_.set(this); const auto events_data = events.data(); const auto events_size = static_cast<size_type>(events.size()); auto stop = stop_.load(std::memory_order_acquire); #if ICE_OS_FREEBSD const timespec ts = { 0, 1000000 }; #endif while (true) { #if ICE_OS_WIN32 size_type count = 0; const DWORD timeout = stop ? 1 : INFINITE; if (!::GetQueuedCompletionStatusEx(handle_.as<HANDLE>(), events_data, events_size, &count, timeout, FALSE)) { if (const auto rc = ::GetLastError(); rc != ERROR_ABANDONED_WAIT_0 && rc != WAIT_TIMEOUT) { return make_error_code(rc); } break; } if (count < 1) { break; } #else # if ICE_OS_LINUX const auto timeout = stop ? 1 : -1; const auto count = ::epoll_wait(handle_, events_data, events_size, timeout); # elif ICE_OS_FREEBSD const auto timeout = stop ? &ts : nullptr; const auto count = ::kevent(handle_, nullptr, 0, events_data, events_size, timeout); # endif if (count < 1) { if (count < 0 && errno != EINTR) { return make_error_code(errno); } if (stop_.load(std::memory_order_acquire)) { break; } } #endif auto interrupted = false; for (size_type i = 0; i < count; i++) { auto& entry = events_data[i]; #if ICE_OS_WIN32 if (const auto ev = static_cast<event*>(entry.lpOverlapped)) { ev->resume(); continue; } #elif ICE_OS_LINUX if (const auto ev = reinterpret_cast<event*>(entry.data.ptr)) { ev->resume(); continue; } #elif ICE_OS_FREEBSD if (const auto ev = reinterpret_cast<event*>(entry.udata)) { ev->resume(); continue; } #endif interrupted = true; stop = stop_.load(std::memory_order_acquire); } if (interrupted) { process(); } } return {}; } std::error_code service::interrupt() noexcept { #if ICE_OS_WIN32 if (!::PostQueuedCompletionStatus(handle_.as<HANDLE>(), 0, 0, nullptr)) { return make_error_code(::GetLastError()); } #elif ICE_OS_LINUX epoll_event nev{ EPOLLOUT | EPOLLONESHOT, {} }; if (::epoll_ctl(handle_, EPOLL_CTL_MOD, events_, &nev) < 0) { return make_error_code(errno); } #elif ICE_OS_FREEBSD struct kevent nev {}; EV_SET(&nev, 0, EVFILT_USER, 0, NOTE_TRIGGER, 0, nullptr); if (::kevent(handle_, &nev, 1, nullptr, 0, nullptr) < 0) { return make_error_code(errno); } #endif return {}; } } // namespace ice::net
25.292929
113
0.646765
qis
3ed646ff1b7510c69a2b47bdc86e7c5a81e66083
17,659
hpp
C++
Ipopt-3.2.1/Ipopt/examples/ScalableProblems/MittelmannBndryCntrlNeum.hpp
FredericLiu/CarND-MPC-P5
e4c68920edd0468ae73357864dde6d61bc1c4205
[ "MIT" ]
null
null
null
Ipopt-3.2.1/Ipopt/examples/ScalableProblems/MittelmannBndryCntrlNeum.hpp
FredericLiu/CarND-MPC-P5
e4c68920edd0468ae73357864dde6d61bc1c4205
[ "MIT" ]
null
null
null
Ipopt-3.2.1/Ipopt/examples/ScalableProblems/MittelmannBndryCntrlNeum.hpp
FredericLiu/CarND-MPC-P5
e4c68920edd0468ae73357864dde6d61bc1c4205
[ "MIT" ]
null
null
null
// Copyright (C) 2005, 2006 International Business Machines and others. // All Rights Reserved. // This code is published under the Common Public License. // // $Id: MittelmannBndryCntrlNeum.hpp 759 2006-07-07 03:07:08Z andreasw $ // // Authors: Andreas Waechter IBM 2005-10-18 // based on MyNLP.hpp #ifndef __MITTELMANNBNDRYCNTRLNEUM_HPP__ #define __MITTELMANNBNDRYCNTRLNEUM_HPP__ #include "IpTNLP.hpp" #include "RegisteredTNLP.hpp" #ifdef HAVE_CMATH # include <cmath> #else # ifdef HAVE_MATH_H # include <math.h> # else # error "don't have header file for math" # endif #endif using namespace Ipopt; /** Base class for boundary control problems with Neumann boundary * conditions, as formulated by Hans Mittelmann as Examples 5-8 in * "Optimization Techniques for Solving Elliptic Control Problems * with Control and State Constraints. Part 1: Boundary Control" */ class MittelmannBndryCntrlNeumBase : public RegisteredTNLP { public: /** Constructor. N is the number of mesh points in one dimension * (excluding boundary). */ MittelmannBndryCntrlNeumBase(); /** Default destructor */ virtual ~MittelmannBndryCntrlNeumBase(); /**@name Overloaded from TNLP */ //@{ /** Method to return some info about the nlp */ virtual bool get_nlp_info(Index& n, Index& m, Index& nnz_jac_g, Index& nnz_h_lag, IndexStyleEnum& index_style); /** Method to return the bounds for my problem */ virtual bool get_bounds_info(Index n, Number* x_l, Number* x_u, Index m, Number* g_l, Number* g_u); /** Method to return the starting point for the algorithm */ virtual bool get_starting_point(Index n, bool init_x, Number* x, bool init_z, Number* z_L, Number* z_U, Index m, bool init_lambda, Number* lambda); /** Method to return the objective value */ virtual bool eval_f(Index n, const Number* x, bool new_x, Number& obj_value); /** Method to return the gradient of the objective */ virtual bool eval_grad_f(Index n, const Number* x, bool new_x, Number* grad_f); /** Method to return the constraint residuals */ virtual bool eval_g(Index n, const Number* x, bool new_x, Index m, Number* g); /** Method to return: * 1) The structure of the jacobian (if "values" is NULL) * 2) The values of the jacobian (if "values" is not NULL) */ virtual bool eval_jac_g(Index n, const Number* x, bool new_x, Index m, Index nele_jac, Index* iRow, Index *jCol, Number* values); /** Method to return: * 1) The structure of the hessian of the lagrangian (if "values" is NULL) * 2) The values of the hessian of the lagrangian (if "values" is not NULL) */ virtual bool eval_h(Index n, const Number* x, bool new_x, Number obj_factor, Index m, const Number* lambda, bool new_lambda, Index nele_hess, Index* iRow, Index* jCol, Number* values); //@} /** Method for returning scaling parameters */ virtual bool get_scaling_parameters(Number& obj_scaling, bool& use_x_scaling, Index n, Number* x_scaling, bool& use_g_scaling, Index m, Number* g_scaling); /** @name Solution Methods */ //@{ /** This method is called after the optimization, and could write an * output file with the optimal profiles */ virtual void finalize_solution(SolverReturn status, Index n, const Number* x, const Number* z_L, const Number* z_U, Index m, const Number* g, const Number* lambda, Number obj_value); //@} protected: /** Method for setting the internal parameters that define the * problem. It must be called by the child class in its * implementation of InitializeParameters. */ void SetBaseParameters(Index N, Number alpha, Number lb_y, Number ub_y, Number lb_u, Number ub_u, Number u_init); /**@name Functions that defines a particular instance. */ //@{ /** Target profile function for y (and initial guess function) */ virtual Number y_d_cont(Number x1, Number x2) const =0; /** Forcing function for the elliptic equation */ virtual Number d_cont(Number x1, Number x2, Number y) const =0; /** First partial derivative of forcing function w.r.t. y */ virtual Number d_cont_dy(Number x1, Number x2, Number y) const =0; /** Second partial derivative of forcing function w.r.t. y,y */ virtual Number d_cont_dydy(Number x1, Number x2, Number y) const =0; /** returns true if second partial derivative of d_cont * w.r.t. y,y is always zero. */ virtual bool d_cont_dydy_alwayszero() const =0; /** Function in Neuman boundary condition */ virtual Number b_cont(Number x1, Number x2, Number y, Number u) const =0; /** First partial derivative of b_cont w.r.t. y */ virtual Number b_cont_dy(Number x1, Number x2, Number y, Number u) const =0; /** First partial derivative of b_cont w.r.t. u */ virtual Number b_cont_du(Number x1, Number x2, Number y, Number u) const =0; /** Second partial derivative of b_cont w.r.t. y,y */ virtual Number b_cont_dydy(Number x1, Number x2, Number y, Number u) const =0; /** returns true if second partial derivative of b_cont * w.r.t. y,y is always zero. */ virtual bool b_cont_dydy_alwayszero() const =0; //@} private: /**@name Methods to block default compiler methods. * The compiler automatically generates the following three methods. * Since the default compiler implementation is generally not what * you want (for all but the most simple classes), we usually * put the declarations of these methods in the private section * and never implement them. This prevents the compiler from * implementing an incorrect "default" behavior without us * knowing. (See Scott Meyers book, "Effective C++") * */ //@{ MittelmannBndryCntrlNeumBase(const MittelmannBndryCntrlNeumBase&); MittelmannBndryCntrlNeumBase& operator=(const MittelmannBndryCntrlNeumBase&); //@} /**@name Problem specification */ //@{ /** Number of mesh points in one dimension (excluding boundary) */ Index N_; /** Step size */ Number h_; /** h_ squaredd */ Number hh_; /** overall lower bound on y */ Number lb_y_; /** overall upper bound on y */ Number ub_y_; /** overall lower bound on u */ Number lb_u_; /** overall upper bound on u */ Number ub_u_; /** Initial value for the constrols u */ Number u_init_; /** Weighting parameter for the control target deviation functional * in the objective */ Number alpha_; /** Array for the target profile for y */ Number* y_d_; //@} /**@name Auxilliary methods */ //@{ /** Translation of mesh point indices to NLP variable indices for * y(x_ij) */ inline Index y_index(Index i, Index j) const { return j + (N_+2)*i; } /** Translation of mesh point indices to NLP variable indices for * u(x_ij) on {0} x (0,1) boudnary*/ inline Index u0j_index(Index j) const { return (N_+2)*(N_+2) + j-1; } /** Translation of mesh point indices to NLP variable indices for * u(x_ij) on {1} x (0,1) boudnary*/ inline Index u1j_index(Index j) const { return (N_+2)*(N_+2) + N_ + j-1; } /** Translation of mesh point indices to NLP variable indices for * u(x_ij) on (0,1) x {0} boudnary*/ inline Index ui0_index(Index j) const { return (N_+2)*(N_+2) + 2*N_ + j-1; } /** Translation of mesh point indices to NLP variable indices for * u(x_ij) on (0,1) x {1} boudnary*/ inline Index ui1_index(Index j) const { return (N_+2)*(N_+2) + 3*N_ + j-1; } /** Compute the grid coordinate for given index in x1 direction */ inline Number x1_grid(Index i) const { return h_*(Number)i; } /** Compute the grid coordinate for given index in x2 direction */ inline Number x2_grid(Index j) const { return h_*(Number)j; } //@} }; /** Class implementating Example 5 */ class MittelmannBndryCntrlNeum1 : public MittelmannBndryCntrlNeumBase { public: MittelmannBndryCntrlNeum1() {} virtual ~MittelmannBndryCntrlNeum1() {} virtual bool InitializeProblem(Index N) { if (N<1) { printf("N has to be at least 1."); return false; } Number alpha = 0.01; Number lb_y = -1e20; Number ub_y = 2.071; Number lb_u = 3.7; Number ub_u = 4.5; Number u_init = (ub_u+lb_u)/2.; SetBaseParameters(N, alpha, lb_y, ub_y, lb_u, ub_u, u_init); return true; } protected: /** Target profile function for y */ virtual Number y_d_cont(Number x1, Number x2) const { return 2. - 2.*(x1*(x1-1.) + x2*(x2-1.)); } /** Forcing function for the elliptic equation */ virtual Number d_cont(Number x1, Number x2, Number y) const { return 0.; } /** First partial derivative of forcing function w.r.t. y */ virtual Number d_cont_dy(Number x1, Number x2, Number y) const { return 0.; } /** Second partial derivative of forcing function w.r.t y,y */ virtual Number d_cont_dydy(Number x1, Number x2, Number y) const { return 0.; } /** returns true if second partial derivative of d_cont * w.r.t. y,y is always zero. */ virtual bool d_cont_dydy_alwayszero() const { return true; } /** Function in Neuman boundary condition */ virtual Number b_cont(Number x1, Number x2, Number y, Number u) const { return u - y*y; } /** First partial derivative of b_cont w.r.t. y */ virtual Number b_cont_dy(Number x1, Number x2, Number y, Number u) const { return - 2.*y; } /** First partial derivative of b_cont w.r.t. u */ virtual Number b_cont_du(Number x1, Number x2, Number y, Number u) const { return 1.; } /** Second partial derivative of b_cont w.r.t. y,y */ virtual Number b_cont_dydy(Number x1, Number x2, Number y, Number u) const { return -2.; } /** returns true if second partial derivative of b_cont * w.r.t. y,y is always zero. */ virtual bool b_cont_dydy_alwayszero() const { return false; } private: /**@name hide implicitly defined contructors copy operators */ //@{ MittelmannBndryCntrlNeum1(const MittelmannBndryCntrlNeum1&); MittelmannBndryCntrlNeum1& operator=(const MittelmannBndryCntrlNeum1&); //@} }; /** Class implementating Example 6 */ class MittelmannBndryCntrlNeum2 : public MittelmannBndryCntrlNeumBase { public: MittelmannBndryCntrlNeum2() {} virtual ~MittelmannBndryCntrlNeum2() {} virtual bool InitializeProblem(Index N) { if (N<1) { printf("N has to be at least 1."); return false; } Number alpha = 0.; Number lb_y = -1e20; Number ub_y = 2.835; Number lb_u = 6.; Number ub_u = 9.; Number u_init = (ub_u+lb_u)/2.; SetBaseParameters(N, alpha, lb_y, ub_y, lb_u, ub_u, u_init); return true; } protected: /** Target profile function for y */ virtual Number y_d_cont(Number x1, Number x2) const { return 2. - 2.*(x1*(x1-1.) + x2*(x2-1.)); } /** Forcing function for the elliptic equation */ virtual Number d_cont(Number x1, Number x2, Number y) const { return 0.; } /** First partial derivative of forcing function w.r.t. y */ virtual Number d_cont_dy(Number x1, Number x2, Number y) const { return 0.; } /** Second partial derivative of forcing function w.r.t y,y */ virtual Number d_cont_dydy(Number x1, Number x2, Number y) const { return 0.; } /** returns true if second partial derivative of d_cont * w.r.t. y,y is always zero. */ virtual bool d_cont_dydy_alwayszero() const { return true; } /** Function in Neuman boundary condition */ virtual Number b_cont(Number x1, Number x2, Number y, Number u) const { return u - y*y; } /** First partial derivative of b_cont w.r.t. y */ virtual Number b_cont_dy(Number x1, Number x2, Number y, Number u) const { return - 2.*y; } /** First partial derivative of b_cont w.r.t. u */ virtual Number b_cont_du(Number x1, Number x2, Number y, Number u) const { return 1.; } /** Second partial derivative of b_cont w.r.t. y,y */ virtual Number b_cont_dydy(Number x1, Number x2, Number y, Number u) const { return -2.; } /** returns true if second partial derivative of b_cont * w.r.t. y,y is always zero. */ virtual bool b_cont_dydy_alwayszero() const { return false; } private: /**@name hide implicitly defined contructors copy operators */ //@{ MittelmannBndryCntrlNeum2(const MittelmannBndryCntrlNeum2&); MittelmannBndryCntrlNeum2& operator=(const MittelmannBndryCntrlNeum2&); //@} }; /** Class implementating Example 7 */ class MittelmannBndryCntrlNeum3 : public MittelmannBndryCntrlNeumBase { public: MittelmannBndryCntrlNeum3() {} virtual ~MittelmannBndryCntrlNeum3() {} virtual bool InitializeProblem(Index N) { if (N<1) { printf("N has to be at least 1."); return false; } Number alpha = 0.01; Number lb_y = -1e20; Number ub_y = 2.7; Number lb_u = 1.8; Number ub_u = 2.5; Number u_init = (ub_u+lb_u)/2.; SetBaseParameters(N, alpha, lb_y, ub_y, lb_u, ub_u, u_init); return true; } protected: /** Target profile function for y */ virtual Number y_d_cont(Number x1, Number x2) const { return 2. - 2.*(x1*(x1-1.) + x2*(x2-1.)); } /** Forcing function for the elliptic equation */ virtual Number d_cont(Number x1, Number x2, Number y) const { return y*y*y-y; } /** First partial derivative of forcing function w.r.t. y */ virtual Number d_cont_dy(Number x1, Number x2, Number y) const { return 3.*y*y-1.; } /** Second partial derivative of forcing function w.r.t y,y */ virtual Number d_cont_dydy(Number x1, Number x2, Number y) const { return 6.*y; } /** returns true if second partial derivative of d_cont * w.r.t. y,y is always zero. */ virtual bool d_cont_dydy_alwayszero() const { return false; } /** Function in Neuman boundary condition */ virtual Number b_cont(Number x1, Number x2, Number y, Number u) const { return u; } /** First partial derivative of b_cont w.r.t. y */ virtual Number b_cont_dy(Number x1, Number x2, Number y, Number u) const { return 0.; } /** First partial derivative of b_cont w.r.t. u */ virtual Number b_cont_du(Number x1, Number x2, Number y, Number u) const { return 1.; } /** Second partial derivative of b_cont w.r.t. y,y */ virtual Number b_cont_dydy(Number x1, Number x2, Number y, Number u) const { return 0.; } /** returns true if second partial derivative of b_cont * w.r.t. y,y is always zero. */ virtual bool b_cont_dydy_alwayszero() const { return true; } private: /**@name hide implicitly defined contructors copy operators */ //@{ MittelmannBndryCntrlNeum3(const MittelmannBndryCntrlNeum3&); MittelmannBndryCntrlNeum3& operator=(const MittelmannBndryCntrlNeum3&); //@} }; /** Class implementating Example 8 */ class MittelmannBndryCntrlNeum4 : public MittelmannBndryCntrlNeumBase { public: MittelmannBndryCntrlNeum4() {} virtual ~MittelmannBndryCntrlNeum4() {} virtual bool InitializeProblem(Index N) { if (N<1) { printf("N has to be at least 1."); return false; } Number alpha = 0.; Number lb_y = -1e20; Number ub_y = 2.7; Number lb_u = 1.8; Number ub_u = 2.5; Number u_init = (ub_u+lb_u)/2.; SetBaseParameters(N, alpha, lb_y, ub_y, lb_u, ub_u, u_init); return true; } protected: /** Target profile function for y */ virtual Number y_d_cont(Number x1, Number x2) const { return 2. - 2.*(x1*(x1-1.) + x2*(x2-1.)); } /** Forcing function for the elliptic equation */ virtual Number d_cont(Number x1, Number x2, Number y) const { return y*y*y-y; } /** First partial derivative of forcing function w.r.t. y */ virtual Number d_cont_dy(Number x1, Number x2, Number y) const { return 3.*y*y-1.; } /** Second partial derivative of forcing function w.r.t y,y */ virtual Number d_cont_dydy(Number x1, Number x2, Number y) const { return 6.*y; } /** returns true if second partial derivative of d_cont * w.r.t. y,y is always zero. */ virtual bool d_cont_dydy_alwayszero() const { return false; } /** Function in Neuman boundary condition */ virtual Number b_cont(Number x1, Number x2, Number y, Number u) const { return u; } /** First partial derivative of b_cont w.r.t. y */ virtual Number b_cont_dy(Number x1, Number x2, Number y, Number u) const { return 0.; } /** First partial derivative of b_cont w.r.t. u */ virtual Number b_cont_du(Number x1, Number x2, Number y, Number u) const { return 1.; } /** Second partial derivative of b_cont w.r.t. y,y */ virtual Number b_cont_dydy(Number x1, Number x2, Number y, Number u) const { return 0.; } /** returns true if second partial derivative of b_cont * w.r.t. y,y is always zero. */ virtual bool b_cont_dydy_alwayszero() const { return true; } private: /**@name hide implicitly defined contructors copy operators */ //@{ MittelmannBndryCntrlNeum4(const MittelmannBndryCntrlNeum4&); MittelmannBndryCntrlNeum4& operator=(const MittelmannBndryCntrlNeum4&); //@} }; #endif
30.818499
96
0.652075
FredericLiu
3ed857c981698a26f97bf209304c7bfbf3006fda
301
cpp
C++
atcoder/abc081/A/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
8
2020-12-23T07:54:53.000Z
2021-11-23T02:46:35.000Z
atcoder/abc081/A/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
1
2020-11-07T13:22:29.000Z
2020-12-20T12:54:00.000Z
atcoder/abc081/A/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
1
2021-01-16T03:40:10.000Z
2021-01-16T03:40:10.000Z
#include <bits/stdc++.h> using namespace std; using ll = long long; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); string S; cin >> S; int count = 0; for (auto c : S) { if (c == '1') ++count; } cout << count << endl; return 0; }
15.842105
37
0.518272
xirc
3eddf8426a021bc2fc0d94415a8a9df10e934c7e
8,769
cpp
C++
src/lib/Output.cpp
alexkorochkin/mcray
2cfa58d2cd6f872612f6396d65781ad83211c06c
[ "MIT" ]
7
2020-12-16T08:23:31.000Z
2022-01-15T22:56:26.000Z
src/lib/Output.cpp
alexkorochkin/mcray
2cfa58d2cd6f872612f6396d65781ad83211c06c
[ "MIT" ]
null
null
null
src/lib/Output.cpp
alexkorochkin/mcray
2cfa58d2cd6f872612f6396d65781ad83211c06c
[ "MIT" ]
2
2020-12-16T08:23:34.000Z
2022-01-10T21:05:54.000Z
/* * Output.cpp * * Author: * Oleg Kalashev * * Copyright (c) 2020 Institute for Nuclear Research, RAS * * 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 "Output.h" #include<sys/stat.h> #include <map> #include <utility> #include "ParticleStack.h" namespace mcray { SpectrumOutput::SpectrumOutput(std::string aFile, double aEmin, double aStep): fEmin(aEmin), fLogStep(log(aStep)), fFile(aFile) { fEmin /= sqrt(aStep);//center bins in Emin*aStep^N //std::ofstream fileOut; //fileOut.open(fFile.c_str());//make sure file can be created and delete the contents of old file if it exists //if(!fileOut) //Exception::Throw("Failed to open " + fFile + " for writing"); //fileOut.close(); } SpectrumOutput::~SpectrumOutput() { } void SpectrumOutput::AddParticle(const Particle& aParticle) { int iBin = log(aParticle.Energy/fEmin)/fLogStep; if(iBin<0) return;//skip output of particles with E<Emin Vector& spec = fSpectra[aParticle.Type]; std::vector<int>& numbers = fNumberOfParticles[aParticle.Type]; while((int)spec.size()<=iBin) { spec.push_back(0); numbers.push_back(0); } spec[iBin] += aParticle.Weight; numbers[iBin] += 1; } void SpectrumOutput::Flush(bool aFinal) { if(!aFinal) return;//intermedeate output is not supported std::ofstream fileOut; fileOut.open(fFile.c_str());//replace previous content //fileOut.open(fFile.c_str(), std::ios::app);//don't remove previous contents if(!fileOut) Exception::Throw("Failed to open " + fFile + " for writing"); //fileOut.seekp(std::ios::beg);//every next spectrum output is saved in the beginning of the file unsigned int nBins = 0; for(int p=0; p<ParticleTypeEOF; p++) { unsigned int size = fSpectra[p].size(); if(size>nBins) nBins = size; } double mult = exp(fLogStep); double E=fEmin*sqrt(mult); double deltaEmult = sqrt(mult) - 1./sqrt(mult); for(unsigned int iE=0; iE<nBins; iE++, E*=mult) { fileOut << E*units.Eunit*1e6;//eV for(unsigned int p=0; p<ParticleTypeEOF; p++) { double intFlux = 0; int nParticles = 0; if(fSpectra[p].size()>iE) { intFlux = fSpectra[p][iE]; nParticles = fNumberOfParticles[p][iE]; } fileOut << "\t" << intFlux*deltaEmult*E << "\t" << nParticles;//print dN(E)/dE * E^2 } fileOut << '\n'; } fileOut << "\n\n";/// delimiters between consequent spectra outputs fileOut.close(); } RawOutput::RawOutput(std::string aDir, bool aCheckRepetitions, bool aOverwriteExisting): fParticles(0), fDir(aDir), fCheckRepetitions(aCheckRepetitions), fHeaderWritten(ParticleTypeEOF,false), fFlushInProgress(false) { SetOutputDir(aDir, aOverwriteExisting); fParticles = new std::vector<Particle>[ParticleTypeEOF]; } RawOutput::~RawOutput() { delete[] fParticles; } void RawOutput::SetOutputDir(std::string aDir, bool aOverwriteExisting) { fDir = aDir; if(mkdir(fDir.c_str(),0777)) { if(aOverwriteExisting) { system(("rm -r " + aDir).c_str()); if(!mkdir(fDir.c_str(),0777)) return; } Exception::Throw("Failed to create directory " + aDir); } } void RawOutput::CopyToStack(ParticleStack& aStack) { for(int p=0; p<ParticleTypeEOF; p++) { std::vector<Particle>& particles = fParticles[p]; if(particles.size()) aStack.AddSecondaries(particles); } } void RawOutput::AddParticle(const Particle& aParticle) { fParticles[aParticle.Type].push_back(aParticle); } void RawOutput::Flush(bool aFinal) { if(fFlushInProgress) Exception::Throw("RawOutput::Flush(): was invoked from more than one thread"); fFlushInProgress = true; if(fCheckRepetitions && aFinal) LookForRepetitions(fParticles); for(int p=0; p<ParticleTypeEOF; p++) { std::vector<Particle>& particles = fParticles[p]; if(particles.size()==0) continue; std::string fileName = fDir + "/" + Particle::Name((ParticleType)p); std::ofstream file; file.open(fileName.c_str(), std::ios::app); if(!file) { fFlushInProgress = false; Exception::Throw("Failed to open " + fileName + " for writing"); } std::vector<Particle>::const_iterator pit = particles.begin(); if(!fHeaderWritten[p]) { WriteHeader(file, *pit); file << "\n"; fHeaderWritten[p] = true; } for(; pit != particles.end(); pit++) { Write(file, *pit); file << "\n"; } file.close(); particles.clear(); } fFlushInProgress = false; } void RawOutput::WriteHeader(std::ostream& aOut, const Particle& aFirstParticle){ aOut << "# E/eV\tweight\tNinteractions\tz_fin\tsinBeta\tD_lastDeflection/Mpc\tD_source\tz_source"; } void RawOutput::Write(std::ostream& aOut, const Particle& aParticle){ double beta = aParticle.DeflectionAngle(); double sinBeta = (beta<0.5*M_PI)?sin(aParticle.DeflectionAngle()):1.;//to enable correct filtering based on sin(beta) set sin=1 for particles deflected by angles larger than Pi/2 double d = cosmology.z2d(aParticle.SourceParticle->Time.z())/units.Mpc; double l = cosmology.z2d(aParticle.LastDeflectionTime().z())/units.Mpc; aOut << aParticle.Energy*units.Eunit*1e6 << "\t" << aParticle.Weight << "\t" << aParticle.Ninteractions << "\t" << aParticle.Time.z() << "\t" //used for debugging << sinBeta << "\t" << l << "\t" << d << "\t" << aParticle.SourceParticle->Time.z(); //used to filter on base of PSF and jet angle or on base of source Z } void RawOutput::LookForRepetitions(std::vector<Particle>* aParticles) { std::map<float, int> energies; for(int p=0; p<ParticleTypeEOF; p++) { std::vector<Particle>& particles = aParticles[p]; for(std::vector<Particle>::const_iterator pit = particles.begin(); pit != particles.end(); pit++) { if(!pit->Ninteractions)//skipping particles which did not interact continue; float log10E = (float)log10(pit->Energy*units.Eunit*1e6); energies[log10E]++; } } std::ofstream file; for (std::map<float,int>::iterator it = energies.begin(); it != energies.end(); it++) { if(it->second > 1) { if(!file.is_open()) { std::cerr << "Repetitions found" << std::endl; std::string fileName = fDir + "/repetitions"; file.open(fileName.c_str(),std::ios::out); if(!file.is_open()) Exception::Throw("Failed to create " + fileName); } file << it->first << "\t" << it->second << "\n"; } } if(file.is_open()) file.close(); } void RawOutput3D::Write(std::ostream& aOut, const Particle& aParticle){ double T = aParticle.Time.t()-aParticle.SourceParticle->Time.t(); aOut << aParticle.Energy/units.eV << "\t" << aParticle.Weight << "\t" << aParticle.X[0]/T << "\t" << aParticle.X[1]/T << "\t" << 1.-aParticle.X[2]/T << "\t" << aParticle.Pdir[0] << "\t" << aParticle.Pdir[1] << "\t" << 1.-aParticle.Pdir[2] << "\t" << aParticle.fCascadeProductionTime.z() << "\t" << aParticle.Ninteractions; if(fSaveSourceZ) aOut << "\t" << aParticle.SourceParticle->Time.z(); if(fSaveSourceE) aOut << "\t" << aParticle.SourceParticle->Energy/units.eV; if(fSaveId){ aOut << "\t" << aParticle.id; } } void RawOutput3D::WriteHeader(std::ostream& aOut, const Particle& aFirstParticle){ aOut << "# " << Particle::Name(aFirstParticle.Type); if(!fSaveSourceZ){ aOut << "\tz_src = "<< aFirstParticle.SourceParticle->Time.z(); } if(!fSaveSourceE){ aOut << "\tE_src/eV = "<< aFirstParticle.SourceParticle->Energy/units.eV; } aOut << "\t" << "T/Mpc = " << (aFirstParticle.Time.t()-aFirstParticle.SourceParticle->Time.t())/units.Mpc << "\n#\n"; aOut << "# E/eV\tweight\tx/T\ty/T\t1-(z/T)\tPx/P\tPy/P\t1-(Pz/P)\tz_cascade_production\tN_interactions"; if(fSaveSourceZ){ aOut << "\tz_src"; } if(fSaveSourceE){ aOut << "\tE_src/eV"; } if(fSaveId){ aOut << "\tId"; } } } /* namespace mcray */
31.317857
179
0.670886
alexkorochkin
3edf417f411114268d513802deda9e5558814bb5
259
cc
C++
test/spsc_queue_test_bm.cc
orientye/orientnet
0a3d6fad1fbf6896b60fd9fe8157cc8599dbd0cc
[ "MIT" ]
5
2020-09-23T00:19:58.000Z
2021-03-24T11:13:27.000Z
test/spsc_queue_test_bm.cc
orientye/orientnet
0a3d6fad1fbf6896b60fd9fe8157cc8599dbd0cc
[ "MIT" ]
null
null
null
test/spsc_queue_test_bm.cc
orientye/orientnet
0a3d6fad1fbf6896b60fd9fe8157cc8599dbd0cc
[ "MIT" ]
null
null
null
// Copyright (c) 2021 The orientnet Authors. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "util/concurrent/spsc_queue.h"
43.166667
77
0.764479
orientye
3ee200db8752b3ff03988c3cf42742cb71cd1fcc
39
hpp
C++
src/boost_vmd_is_empty_list.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_vmd_is_empty_list.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_vmd_is_empty_list.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/vmd/is_empty_list.hpp>
19.5
38
0.794872
miathedev
3ee48bfa21f9c248217abd0c95a5b28d58a00904
64,451
cxx
C++
src/ptlib/common/object.cxx
sverdlin/opalvoip-ptlib
f6e144cba6a94c2978b9a4dbe0df2f5d53bed3be
[ "Beerware" ]
null
null
null
src/ptlib/common/object.cxx
sverdlin/opalvoip-ptlib
f6e144cba6a94c2978b9a4dbe0df2f5d53bed3be
[ "Beerware" ]
null
null
null
src/ptlib/common/object.cxx
sverdlin/opalvoip-ptlib
f6e144cba6a94c2978b9a4dbe0df2f5d53bed3be
[ "Beerware" ]
null
null
null
/* * object.cxx * * Global object support. * * Portable Windows Library * * Copyright (c) 1993-1998 Equivalence Pty. Ltd. * * The contents of this file are subject to the Mozilla Public License * Version 1.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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific language governing rights and limitations * under the License. * * The Original Code is Portable Windows Library. * * The Initial Developer of the Original Code is Equivalence Pty. Ltd. * * Portions are Copyright (C) 1993 Free Software Foundation, Inc. * All Rights Reserved. * * Contributor(s): ______________________________________. */ #ifdef __GNUC__ #pragma implementation "pfactory.h" #endif // __GNUC__ #include <ptlib.h> #include <ptlib/pfactory.h> #include <ptlib/pprocess.h> #include <sstream> #include <fstream> #include <ctype.h> #include <limits> #ifdef _WIN32 #include <ptlib/msos/ptlib/debstrm.h> #if defined(_MSC_VER) #include <crtdbg.h> #endif #elif defined(__NUCLEUS_PLUS__) #include <ptlib/NucleusDebstrm.h> #else #include <signal.h> #endif #if P_HAS_DEMANGLE #include <cxxabi.h> #endif PDebugLocation::PDebugLocation(const PDebugLocation * location) { if (location) { m_file = location->m_file; m_line = location->m_line; m_extra = location->m_extra; } else { m_file = NULL; m_line = 0; m_extra = NULL; } } void PDebugLocation::PrintOn(ostream & strm, const char * prefix) const { if (m_file == NULL && m_extra == NULL) return; if (prefix != NULL) strm << prefix; if (m_file != NULL) { const char * name = strrchr(m_file, PDIR_SEPARATOR); if (name != NULL) strm << name+1; else strm << m_file; if (m_line > 0) strm << '(' << m_line << ')'; } if (m_extra != NULL) { if (m_file != NULL) strm << ' '; strm << m_extra; } } /////////////////////////////////////////////////////////////////////////////// PFactoryBase::FactoryMap & PFactoryBase::GetFactories() { static FactoryMap factories; return factories; } PFactoryBase::FactoryMap::~FactoryMap() { FactoryMap::iterator entry; for (entry = begin(); entry != end(); ++entry){ delete entry->second; entry->second = NULL; } } void PFactoryBase::FactoryMap::DestroySingletons() { Wait(); for (iterator it = begin(); it != end(); ++it) it->second->DestroySingletons(); Signal(); } PFactoryBase & PFactoryBase::InternalGetFactory(const std::string & className, PFactoryBase * (*createFactory)()) { FactoryMap & factories = GetFactories(); PWaitAndSignal mutex(factories); FactoryMap::const_iterator entry = factories.find(className); if (entry != factories.end()) { PAssert(entry->second != NULL, "Factory map returned NULL for existing key"); return *entry->second; } PMEMORY_IGNORE_ALLOCATIONS_FOR_SCOPE; PFactoryBase * factory = createFactory(); factories[className] = factory; return *factory; } #if P_USE_ASSERTS static PCriticalSection & GetAssertMutex() { static PCriticalSection cs; return cs; } extern void PPlatformAssertFunc(const PDebugLocation & location, const char * msg, char defaultAction); extern void PPlatformWalkStack(ostream & strm, PThreadIdentifier id, PUniqueThreadIdentifier uid, unsigned framesToSkip, bool noSymbols, bool exception); #if PTRACING void PTrace::WalkStack(ostream & strm, PThreadIdentifier id, PUniqueThreadIdentifier uid, bool noSymbols) { PWaitAndSignal lock(GetAssertMutex()); PPlatformWalkStack(strm, id, uid, 1, noSymbols, false); // 1 means skip reporting PTrace::WalkStack } #endif // PTRACING PAssertWalkStackModes PAssertWalkStackMode = PAssertWalkStackSymbols; unsigned PAssertCount; static PDebugLocation const s_ExceptionLocation("try/catch"); static void InternalAssertFunc(const PDebugLocation & location, const char * msg) { #if defined(_WIN32) DWORD errorCode = GetLastError(); #else int errorCode = errno; #endif PWaitAndSignal lock(GetAssertMutex()); static bool s_RecursiveAssert = false; if (s_RecursiveAssert) return; s_RecursiveAssert = true; ++PAssertCount; std::string str; { ostringstream strm; strm << "Assertion fail: "; if (msg != NULL) strm << msg << ", "; location.PrintOn(strm, "location "); if (errorCode != 0) strm << ", error=" << errorCode; strm << ", when=" << PTime().AsString(PTime::LoggingFormat PTRACE_PARAM(, PTrace::GetTimeZone())); if (PAssertWalkStackMode == PAssertWalkStackDisabled) strm << ", stack walk disabled"; else PPlatformWalkStack(strm, PNullThreadIdentifier, 0, 2, // 2 means skip reporting InternalAssertFunc & PAssertFunc PAssertWalkStackMode == PAssertWalkStackNoSymbols, &location == &s_ExceptionLocation); strm << ends; str = strm.str(); } const char * env; #if P_EXCEPTIONS //Throw a runtime exception if the environment variable is set env = ::getenv("PTLIB_ASSERT_EXCEPTION"); if (env == NULL) env = ::getenv("PWLIB_ASSERT_EXCEPTION"); if (env != NULL) env = "T"; else #endif env = ::getenv("PTLIB_ASSERT_ACTION"); if (env == NULL) env = ::getenv("PWLIB_ASSERT_ACTION"); if (env == NULL) env = PProcess::Current().IsServiceProcess() ? "i" : ""; PPlatformAssertFunc(location, str.c_str(), *env); s_RecursiveAssert = false; } bool PAssertFunc(const PDebugLocation & location, PStandardAssertMessage msg) { if (msg == POutOfMemory) { // Special case, do not use ostrstream in other PAssertFunc if have // a memory out situation as that would probably also fail! static const char fmt[] = "Out of memory at file %.100s, line %u, class %.30s"; char msgbuf[sizeof(fmt)+100+10+30]; snprintf(msgbuf, sizeof(msgbuf), fmt, location.m_file, location.m_line, location.m_extra); PPlatformAssertFunc(location, msgbuf, 'A'); return false; } static const char * const textmsg[PMaxStandardAssertMessage] = { NULL, "Out of memory", "Null pointer reference", "Invalid cast to non-descendant class", "Invalid array index", "Invalid array element", "Stack empty", "Unimplemented function", "Invalid parameter", "Operating System error", "File not open", "Unsupported feature", "Invalid or closed operating system window" }; if (msg >= 0 && msg < PMaxStandardAssertMessage) InternalAssertFunc(location, textmsg[msg]); else { char msgbuf[21]; snprintf(msgbuf, sizeof(msgbuf), "Assertion %i", msg); InternalAssertFunc(location, msgbuf); } return false; } bool PAssertFunc(const PDebugLocation & location, const char * msg) { // Done this way so WalkStack removes the correct number of irrelevant frames InternalAssertFunc(location, msg); return false; } bool PAssertException(const char * source, const std::exception * ex) { std::ostringstream msg; msg << "Exception "; if (ex != NULL) msg << '(' << PObject::GetClassName(typeid(*ex)) << " \"" << ex->what() << "\") "; msg << "caught in " << source; InternalAssertFunc(s_ExceptionLocation, msg.str().c_str()); return false; } #endif // P_USE_ASSERTS PObject::Comparison PObject::CompareObjectMemoryDirect(const PObject & obj) const { return InternalCompareObjectMemoryDirect(this, &obj, sizeof(obj)); } PObject::Comparison PObject::InternalCompareObjectMemoryDirect(const PObject * obj1, const PObject * obj2, PINDEX size) { if (obj2 == NULL) return PObject::LessThan; if (obj1 == NULL) return PObject::GreaterThan; int retval = memcmp((const void *)obj1, (const void *)obj2, size); if (retval < 0) return PObject::LessThan; if (retval > 0) return PObject::GreaterThan; return PObject::EqualTo; } PObject * PObject::Clone() const { PAssertAlways(PUnimplementedFunction); return NULL; } PObject::Comparison PObject::Compare(const PObject & obj) const { return (Comparison)CompareObjectMemoryDirect(obj); } void PObject::PrintOn(ostream & strm) const { strm << GetClassName(); } void PObject::ReadFrom(istream &) { } PINDEX PObject::HashFunction() const { return 0; } std::string PObject::GetClassName(const std::type_info & t) { std::string name; #if P_HAS_DEMANGLE int status = -1; char * demangle = abi::__cxa_demangle(t.name(), NULL, NULL, &status); if (status == 0) { name = demangle; runtime_free(demangle); } else #endif name = t.name(); if (name.compare(0, 6, "class ") == 0) name.erase(0, 6); else if (name.compare(0, 7, "struct ") == 0) name.erase(0, 7); return name; } /////////////////////////////////////////////////////////////////////////////// // General reference counting support PSmartPointer::PSmartPointer(const PSmartPointer & ptr) { object = ptr.object; if (object != NULL) ++object->referenceCount; } PSmartPointer & PSmartPointer::operator=(const PSmartPointer & ptr) { if (object == ptr.object) return *this; if ((object != NULL) && (--object->referenceCount == 0)) delete object; // This reduces, but does not close, the multi-threading window for failure if (ptr.object != NULL && PAssert(++ptr.object->referenceCount > 1, "Multi-thread failure in PSmartPointer")) object = ptr.object; else object = NULL; return *this; } PSmartPointer::~PSmartPointer() { if ((object != NULL) && (--object->referenceCount == 0)) delete object; } PObject::Comparison PSmartPointer::Compare(const PObject & obj) const { PAssert(PIsDescendant(&obj, PSmartPointer), PInvalidCast); PSmartObject * other = ((const PSmartPointer &)obj).object; if (object == other) return EqualTo; return object < other ? LessThan : GreaterThan; } ////////////////////////////////////////////////////////////////////////////////////////// #if PMEMORY_CHECK #undef malloc #undef calloc #undef realloc #undef free #if (__cplusplus >= 201103L) void * operator new(size_t nSize) #elif (__GNUC__ >= 3) || ((__GNUC__ == 2)&&(__GNUC_MINOR__ >= 95)) //2.95.X & 3.X void * operator new(size_t nSize) throw (std::bad_alloc) #else void * operator new(size_t nSize) #endif { return PMemoryHeap::Allocate(nSize, (const char *)NULL, 0, NULL); } #if (__cplusplus >= 201103L) void * operator new[](size_t nSize) #elif (__GNUC__ >= 3) || ((__GNUC__ == 2)&&(__GNUC_MINOR__ >= 95)) //2.95.X & 3.X void * operator new[](size_t nSize) throw (std::bad_alloc) #else void * operator new[](size_t nSize) #endif { return PMemoryHeap::Allocate(nSize, (const char *)NULL, 0, NULL); } #if (__cplusplus >= 201103L) void operator delete(void * ptr) noexcept #elif (__GNUC__ >= 3) || ((__GNUC__ == 2)&&(__GNUC_MINOR__ >= 95)) //2.95.X & 3.X void operator delete(void * ptr) throw() #else void operator delete(void * ptr) #endif { PMemoryHeap::Deallocate(ptr, NULL); } #if (__cplusplus >= 201103L) void operator delete[](void * ptr) noexcept #elif (__GNUC__ >= 3) || ((__GNUC__ == 2)&&(__GNUC_MINOR__ >= 95)) //2.95.X & 3.X void operator delete[](void * ptr) throw() #else void operator delete[](void * ptr) #endif { PMemoryHeap::Deallocate(ptr, NULL); } char PMemoryHeap::Header::GuardBytes[NumGuardBytes]; static const size_t MaxMemoryDumBytes = 16; static void * DeletedPtr; static void * UninitialisedPtr; static void * GuardedPtr; PMemoryHeap & PMemoryHeap::GetInstance() { // The following is done like this to get over brain dead compilers that cannot // guarentee that a static global is contructed before it is used. static PMemoryHeap real_instance; return real_instance; } PMemoryHeap::PMemoryHeap() : m_listHead(NULL) , m_listTail(NULL) , m_allocationRequest(1) , m_allocationBreakpoint(0) , m_firstRealObject(0) , m_flags(NoLeakPrint) , m_allocFillChar('\xCD') // Microsoft debug heap values , m_freeFillChar('\xDD') , m_currentMemoryUsage(0) , m_peakMemoryUsage(0) , m_currentObjects(0) , m_peakObjects(0) , m_totalObjects(0) , m_leakDumpStream(NULL) { const char * env = getenv("PTLIB_MEMORY_CHECK"); switch (atoi(env != NULL ? env : "1")) { case 0 : m_state = e_Disabled; break; case 2 : m_state = e_TrackOnly; break; default : m_state = e_Active; break; } for (PINDEX i = 0; i < Header::NumGuardBytes; i++) Header::GuardBytes[i] = '\xFD'; memset(&DeletedPtr, m_freeFillChar, sizeof(DeletedPtr)); memset(&UninitialisedPtr, m_allocFillChar, sizeof(UninitialisedPtr)); memset(&GuardedPtr, '\xFD', sizeof(GuardedPtr)); #if defined(_WIN32) InitializeCriticalSection(&m_mutex); static PDebugStream debug; m_leakDumpStream = &debug; #else #if defined(P_PTHREADS) #ifdef PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP pthread_mutex_t recursiveMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; m_mutex = recursiveMutex; #else pthread_mutex_init(&m_mutex, NULL); #endif #elif defined(P_VXWORKS) m_mutex = semMCreate(SEM_Q_FIFO); #endif m_leakDumpStream = &cerr; #endif } PMemoryHeap::~PMemoryHeap() { m_state = e_Destroyed; if (m_leakDumpStream != NULL) { *m_leakDumpStream << "Final memory statistics:\n"; InternalDumpStatistics(*m_leakDumpStream); InternalDumpObjectsSince(m_firstRealObject, *m_leakDumpStream); } #if defined(_WIN32) DeleteCriticalSection(&m_mutex); PProcess::Current().WaitOnExitConsoleWindow(); #elif defined(P_PTHREADS) pthread_mutex_destroy(&m_mutex); #elif defined(P_VXWORKS) semDelete((SEM_ID)m_mutex); #endif } void PMemoryHeap::Lock() { #if defined(_WIN32) EnterCriticalSection(&m_mutex); #elif defined(P_PTHREADS) pthread_mutex_lock(&m_mutex); #elif defined(P_VXWORKS) semTake((SEM_ID)m_mutex, WAIT_FOREVER); #endif } void PMemoryHeap::Unlock() { #if defined(_WIN32) LeaveCriticalSection(&m_mutex); #elif defined(P_PTHREADS) pthread_mutex_unlock(&m_mutex); #elif defined(P_VXWORKS) semGive((SEM_ID)m_mutex); #endif } void * PMemoryHeap::Allocate(size_t nSize, const char * file, int line, const char * className) { return GetInstance().InternalAllocate(nSize, file, line, className, false); } void * PMemoryHeap::Allocate(size_t count, size_t size, const char * file, int line) { return GetInstance().InternalAllocate(count*size, file, line, NULL, true); } void * PMemoryHeap::InternalAllocate(size_t nSize, const char * file, int line, const char * className, bool zeroFill) { if (m_state <= e_Disabled) return malloc(nSize); Header * obj = (Header *)malloc(sizeof(Header) + nSize + sizeof(Header::GuardBytes)); if (obj == NULL) { PAssertAlways(POutOfMemory); return NULL; } Lock(); if (m_allocationBreakpoint != 0 && m_allocationRequest == m_allocationBreakpoint) PBreakToDebugger(); // Ignore all allocations made before main() is called. This is indicated // by PProcess::PreInitialise() clearing the NoLeakPrint flag. Why do we do // this? because the GNU compiler is broken in the way it does static global // C++ object construction and destruction. if (m_firstRealObject == 0 && (m_flags&NoLeakPrint) == 0) { if (m_leakDumpStream != NULL) *m_leakDumpStream << "PTLib memory checking activated." << endl; m_firstRealObject = m_allocationRequest; } m_currentMemoryUsage += nSize; if (m_currentMemoryUsage > m_peakMemoryUsage) m_peakMemoryUsage = m_currentMemoryUsage; m_currentObjects++; if (m_currentObjects > m_peakObjects) m_peakObjects = m_currentObjects; m_totalObjects++; obj->m_request = m_allocationRequest++; obj->m_prev = m_listTail; if (m_listTail != NULL) m_listTail->m_next = obj; m_listTail = obj; if (m_listHead == NULL) m_listHead = obj; obj->m_next = NULL; Unlock(); obj->m_size = nSize; obj->m_fileName = file; obj->m_line = (WORD)line; obj->m_threadId = PThread::GetCurrentThreadId(); obj->m_className = className; obj->m_flags = m_flags; char * data = (char *)&obj[1]; if (m_state == e_Active) { memcpy(obj->m_guard, obj->GuardBytes, sizeof(obj->m_guard)); memset(data, zeroFill ? '\0' : m_allocFillChar, nSize); memcpy(&data[nSize], obj->GuardBytes, sizeof(obj->m_guard)); } else if (zeroFill) memset(data, '\0', nSize); return data; } void * PMemoryHeap::Reallocate(void * ptr, size_t nSize, const char * file, int line) { return GetInstance().InternalReallocate(ptr, nSize, file, line); } void * PMemoryHeap::InternalReallocate(void * ptr, size_t nSize, const char * file, int line) { if (m_state <= e_Disabled) return realloc(ptr, nSize); if (ptr == NULL) return Allocate(nSize, file, line, NULL); if (nSize == 0) { Deallocate(ptr, NULL); return NULL; } if (InternalValidate(ptr, NULL, m_leakDumpStream) != Ok) return NULL; Header * obj = (Header *)realloc(((Header *)ptr)-1, sizeof(Header) + nSize + sizeof(obj->m_guard)); if (obj == NULL) { PAssertAlways(POutOfMemory); return NULL; } Lock(); if (m_allocationBreakpoint != 0 && m_allocationRequest == m_allocationBreakpoint) PBreakToDebugger(); m_currentMemoryUsage -= obj->m_size; m_currentMemoryUsage += nSize; if (m_currentMemoryUsage > m_peakMemoryUsage) m_peakMemoryUsage = m_currentMemoryUsage; obj->m_request = m_allocationRequest++; if (obj->m_prev != NULL) obj->m_prev->m_next = obj; else m_listHead = obj; if (obj->m_next != NULL) obj->m_next->m_prev = obj; else m_listTail = obj; Unlock(); obj->m_size = nSize; obj->m_fileName = file; obj->m_line = (WORD)line; char * data = (char *)&obj[1]; if (m_state == e_Active) memcpy(&data[nSize], obj->GuardBytes, sizeof(obj->m_guard)); return data; } void PMemoryHeap::Deallocate(void * ptr, const char * className) { GetInstance().InternalDeallocate(ptr, className); } void PMemoryHeap::InternalDeallocate(void * ptr, const char * className) { if (m_state <= e_Disabled) return free(ptr); if (ptr == NULL) return; Header * obj = ((Header *)ptr)-1; switch (InternalValidate(ptr, className, m_leakDumpStream)) { case Trashed : free(obj); // Try and free out extended version, and continue return; case Inactive : case Bad : free(ptr); // Try and free it as if we didn't allocate it, and continue return; default : break; } Lock(); if (obj->m_prev != NULL) obj->m_prev->m_next = obj->m_next; else m_listHead = obj->m_next; if (obj->m_next != NULL) obj->m_next->m_prev = obj->m_prev; else m_listTail = obj->m_prev; m_currentMemoryUsage -= obj->m_size; m_currentObjects--; Unlock(); if (m_state == e_Active) memset(ptr, m_freeFillChar, obj->m_size); // Make use of freed data noticable free(obj); } PMemoryHeap::Validation PMemoryHeap::Validate(const void * ptr, const char * className, ostream * error) { return GetInstance().InternalValidate(ptr, className, error); } #ifdef PTRACING #define PMEMORY_VALIDATE_ERROR(arg) if (error != NULL) { *error << arg << '\n'; PTrace::WalkStack(*error); error->flush(); } #else #define PMEMORY_VALIDATE_ERROR(arg) if (error != NULL) *error << arg << endl #endif PMemoryHeap::Validation PMemoryHeap::InternalValidate(const void * ptr, const char * className, ostream * error) { if (m_state <= e_Disabled) return Inactive; if (ptr == NULL) return Bad; Header * obj = ((Header *)ptr) - 1; Header * link = obj; if (m_state == e_Active) { Lock(); unsigned count = m_currentObjects; Header * link = m_listTail; while (link != NULL && link != obj && count-- > 0) { if (link->m_prev == DeletedPtr || link->m_prev == UninitialisedPtr || link->m_prev == GuardedPtr) { PMEMORY_VALIDATE_ERROR("Block " << ptr << " trashed!"); Unlock(); return Trashed; } link = link->m_prev; } Unlock(); } if (link != obj) { PMEMORY_VALIDATE_ERROR("Block " << ptr << " not in heap!"); return Bad; } if (m_state == e_Active) { if (memcmp(obj->m_guard, obj->GuardBytes, sizeof(obj->m_guard)) != 0) { PMEMORY_VALIDATE_ERROR("Underrun at " << ptr << '[' << obj->m_size << "] #" << obj->m_request); return Corrupt; } if (memcmp((char *)ptr + obj->m_size, obj->GuardBytes, sizeof(obj->m_guard)) != 0) { PMEMORY_VALIDATE_ERROR("Overrun at " << ptr << '[' << obj->m_size << "] #" << obj->m_request); return Corrupt; } } if (!(className == NULL && obj->m_className == NULL) && (className == NULL || obj->m_className == NULL || (className != obj->m_className && strcmp(obj->m_className, className) != 0))) { PMEMORY_VALIDATE_ERROR("PObject " << ptr << '[' << obj->m_size << "] #" << obj->m_request << " allocated as \"" << (obj->m_className != NULL ? obj->m_className : "<NULL>") << "\" and should be \"" << (className != NULL ? className : "<NULL>") << "\"."); return Corrupt; } return Ok; } PBoolean PMemoryHeap::ValidateHeap(ostream * error) { return GetInstance().InternalValidateHeap(error); } bool PMemoryHeap::InternalValidateHeap(ostream * error) { if (error == NULL) { error = m_leakDumpStream; if (error == NULL) return false; } if (m_state == e_Active) { Lock(); Header * obj = m_listHead; while (obj != NULL) { if (memcmp(obj->m_guard, obj->GuardBytes, sizeof(obj->m_guard)) != 0) { if (error != NULL) *error << "Underrun at " << (obj + 1) << '[' << obj->m_size << "] #" << obj->m_request << endl; Unlock(); return false; } if (memcmp((char *)(obj + 1) + obj->m_size, obj->GuardBytes, sizeof(obj->m_guard)) != 0) { if (error != NULL) *error << "Overrun at " << (obj + 1) << '[' << obj->m_size << "] #" << obj->m_request << endl; Unlock(); return false; } obj = obj->m_next; } Unlock(); } #if defined(_WIN32) && defined(_DEBUG) if (!_CrtCheckMemory()) { if (error != NULL) *error << "Heap failed MSVCRT validation!" << endl; return false; } #endif if (error != NULL) *error << "Heap passed validation." << endl; return true; } PBoolean PMemoryHeap::SetIgnoreAllocations(PBoolean ignore) { PMemoryHeap & mem = GetInstance(); PBoolean ignoreAllocations = (mem.m_flags&NoLeakPrint) != 0; if (ignore) mem.m_flags |= NoLeakPrint; else mem.m_flags &= ~NoLeakPrint; return ignoreAllocations; } void PMemoryHeap::DumpStatistics() { ostream * strm = GetInstance().m_leakDumpStream; if (strm != NULL) DumpStatistics(*strm); } static void OutputMemory(ostream & strm, size_t bytes) { if (bytes < 10000) { strm << bytes << " bytes"; return; } if (bytes < 10240000) strm << (bytes+1023)/1024 << "kb"; else strm << (bytes+1048575)/1048576 << "Mb"; strm << " (" << bytes << ')'; } void PMemoryHeap::DumpStatistics(ostream & strm) { if (PProcess::IsInitialised()) { PProcess::MemoryUsage usage; PProcess::Current().GetMemoryUsage(usage); strm << "\n" "Virtual memory usage : "; OutputMemory(strm, usage.m_virtual); strm << "\n" "Resident memory usage : "; OutputMemory(strm, usage.m_resident); strm << "\n" "Process heap memory max : "; OutputMemory(strm, usage.m_max); strm << "\n" "Process memory heap usage: "; OutputMemory(strm, usage.m_current); } GetInstance().InternalDumpStatistics(strm); } void PMemoryHeap::InternalDumpStatistics(ostream & strm) { Lock(); strm << "\n" "Current memory usage : "; OutputMemory(strm, m_currentMemoryUsage); strm << "\n" "Current objects count : " << m_currentObjects << "\n" "Peak memory usage : "; OutputMemory(strm, m_peakMemoryUsage); strm << "\n" "Peak objects created : " << m_peakObjects << "\n" "Total objects created : " << m_totalObjects << "\n" "Next allocation request : " << m_allocationRequest << '\n' << endl; Unlock(); } void PMemoryHeap::GetState(State & state) { state.allocationNumber = GetInstance().m_allocationRequest; } void PMemoryHeap::SetAllocationBreakpoint(alloc_t point) { GetInstance().m_allocationBreakpoint = point; } void PMemoryHeap::DumpObjectsSince(const State & state) { PMemoryHeap & mem = GetInstance(); if (mem.m_leakDumpStream != NULL) mem.InternalDumpObjectsSince(state.allocationNumber, *mem.m_leakDumpStream); } void PMemoryHeap::DumpObjectsSince(const State & state, ostream & strm) { GetInstance().InternalDumpObjectsSince(state.allocationNumber, strm); } void PMemoryHeap::InternalDumpObjectsSince(DWORD objectNumber, ostream & strm) { Lock(); bool first = true; for (Header * obj = m_listHead; obj != NULL; obj = obj->m_next) { if (obj->m_request < objectNumber || (obj->m_flags&NoLeakPrint) != 0) continue; if (first && m_state == e_Destroyed) { *m_leakDumpStream << "\nMemory leaks detected, press Enter to display . . ." << flush; #if !defined(_WIN32) cin.get(); #endif *m_leakDumpStream << '\n'; first = false; } BYTE * data = (BYTE *)&obj[1]; if (obj->m_fileName != NULL) strm << obj->m_fileName << '(' << obj->m_line << ") : "; strm << '#' << obj->m_request << ' ' << (void *)data << " [" << obj->m_size << "] "; if (obj->m_className != NULL) strm << "class=\"" << obj->m_className << "\" "; if (PProcess::IsInitialised() && obj->m_threadId != PNullThreadIdentifier) { strm << "thread="; PThread * thread = PProcess::Current().GetThread(obj->m_threadId); if (thread != NULL) strm << '"' << thread->GetThreadName() << "\" "; else strm << "0x" << hex << obj->m_threadId << dec << ' '; } strm << '\n' << hex << setfill('0') << PBYTEArray(data, std::min(MaxMemoryDumBytes, obj->m_size), false) << dec << setfill(' ') << endl; } Unlock(); } #else // PMEMORY_CHECK #if defined(_MSC_VER) && defined(_DEBUG) static _CRT_DUMP_CLIENT pfnOldCrtDumpClient; static bool hadCrtDumpLeak = false; static void __cdecl MyCrtDumpClient(void * ptr, size_t size) { if(_CrtReportBlockType(ptr) == P_CLIENT_BLOCK) { const PObject * obj = (PObject *)ptr; _RPT1(_CRT_WARN, "Class %s\n", obj->GetClassName().c_str()); hadCrtDumpLeak = true; } if (pfnOldCrtDumpClient != NULL) pfnOldCrtDumpClient(ptr, size); } PMemoryHeap::PMemoryHeap() { _CrtMemCheckpoint(&initialState); pfnOldCrtDumpClient = _CrtSetDumpClient(MyCrtDumpClient); _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) & ~_CRTDBG_ALLOC_MEM_DF); } PMemoryHeap::~PMemoryHeap() { _CrtMemDumpAllObjectsSince(&initialState); _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) & ~_CRTDBG_LEAK_CHECK_DF); } void PMemoryHeap::CreateInstance() { static PMemoryHeap instance; } void * PMemoryHeap::Allocate(size_t nSize, const char * file, int line, const char * className) { CreateInstance(); return _malloc_dbg(nSize, className != NULL ? P_CLIENT_BLOCK : _NORMAL_BLOCK, file, line); } void * PMemoryHeap::Allocate(size_t count, size_t iSize, const char * file, int line) { CreateInstance(); return _calloc_dbg(count, iSize, _NORMAL_BLOCK, file, line); } void * PMemoryHeap::Reallocate(void * ptr, size_t nSize, const char * file, int line) { CreateInstance(); return _realloc_dbg(ptr, nSize, _NORMAL_BLOCK, file, line); } void PMemoryHeap::Deallocate(void * ptr, const char * className) { _free_dbg(ptr, className != NULL ? P_CLIENT_BLOCK : _NORMAL_BLOCK); } PMemoryHeap::Validation PMemoryHeap::Validate(const void * ptr, const char * className, ostream * /*strm*/) { CreateInstance(); if (!_CrtIsValidHeapPointer(ptr)) return Bad; if (_CrtReportBlockType(ptr) != P_CLIENT_BLOCK) return Ok; const PObject * obj = (PObject *)ptr; return strcmp(obj->GetClass(), className) == 0 ? Ok : Trashed; } PBoolean PMemoryHeap::ValidateHeap(ostream * /*strm*/) { CreateInstance(); return _CrtCheckMemory(); } PBoolean PMemoryHeap::SetIgnoreAllocations(PBoolean ignoreAlloc) { CreateInstance(); int flags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); if (ignoreAlloc) _CrtSetDbgFlag(flags & ~_CRTDBG_ALLOC_MEM_DF); else _CrtSetDbgFlag(flags | _CRTDBG_ALLOC_MEM_DF); return (flags & _CRTDBG_ALLOC_MEM_DF) == 0; } void PMemoryHeap::DumpStatistics() { CreateInstance(); _CrtMemState state; _CrtMemCheckpoint(&state); _CrtMemDumpStatistics(&state); } void PMemoryHeap::DumpStatistics(ostream & /*strm*/) { DumpStatistics(); } void PMemoryHeap::GetState(State & state) { CreateInstance(); _CrtMemCheckpoint(&state); } void PMemoryHeap::DumpObjectsSince(const State & state) { CreateInstance(); _CrtMemDumpAllObjectsSince(&state); } void PMemoryHeap::DumpObjectsSince(const State & state, ostream & /*strm*/) { CreateInstance(); DumpObjectsSince(state); } void PMemoryHeap::SetAllocationBreakpoint(alloc_t objectNumber) { CreateInstance(); _CrtSetBreakAlloc(objectNumber); } #endif // defined(_MSC_VER) && defined(_DEBUG) #endif // PMEMORY_CHECK /////////////////////////////////////////////////////////////////////////////// // Large integer support #ifdef P_NEEDS_INT64 void PInt64__::Add(const PInt64__ & v) { unsigned long old = low; high += v.high; low += v.low; if (low < old) high++; } void PInt64__::Sub(const PInt64__ & v) { unsigned long old = low; high -= v.high; low -= v.low; if (low > old) high--; } void PInt64__::Mul(const PInt64__ & v) { DWORD p1 = (low&0xffff)*(v.low&0xffff); DWORD p2 = (low >> 16)*(v.low >> 16); DWORD p3 = (high&0xffff)*(v.high&0xffff); DWORD p4 = (high >> 16)*(v.high >> 16); low = p1 + (p2 << 16); high = (p2 >> 16) + p3 + (p4 << 16); } void PInt64__::Div(const PInt64__ & v) { long double dividend = high; dividend *= 4294967296.0; dividend += low; long double divisor = high; divisor *= 4294967296.0; divisor += low; long double quotient = dividend/divisor; low = quotient; high = quotient/4294967296.0; } void PInt64__::Mod(const PInt64__ & v) { PInt64__ t = *this; t.Div(v); t.Mul(t); Sub(t); } void PInt64__::ShiftLeft(int bits) { if (bits >= 32) { high = low << (bits - 32); low = 0; } else { high <<= bits; high |= low >> (32 - bits); low <<= bits; } } void PInt64__::ShiftRight(int bits) { if (bits >= 32) { low = high >> (bits - 32); high = 0; } else { low >>= bits; low |= high << (32 - bits); high >>= bits; } } PBoolean PInt64::Lt(const PInt64 & v) const { if ((long)high < (long)v.high) return true; if ((long)high > (long)v.high) return false; if ((long)high < 0) return (long)low > (long)v.low; return (long)low < (long)v.low; } PBoolean PInt64::Gt(const PInt64 & v) const { if ((long)high > (long)v.high) return true; if ((long)high < (long)v.high) return false; if ((long)high < 0) return (long)low < (long)v.low; return (long)low > (long)v.low; } PBoolean PUInt64::Lt(const PUInt64 & v) const { if (high < v.high) return true; if (high > v.high) return false; return low < high; } PBoolean PUInt64::Gt(const PUInt64 & v) const { if (high > v.high) return true; if (high < v.high) return false; return low > high; } static void Out64(ostream & stream, PUInt64 num) { char buf[25]; char * p = &buf[sizeof(buf)]; *--p = '\0'; switch (stream.flags()&ios::basefield) { case ios::oct : while (num != 0) { *--p = (num&7) + '0'; num >>= 3; } break; case ios::hex : while (num != 0) { *--p = (num&15) + '0'; if (*p > '9') *p += 7; num >>= 4; } break; default : while (num != 0) { *--p = num%10 + '0'; num /= 10; } } if (*p == '\0') *--p = '0'; stream << p; } ostream & operator<<(ostream & stream, const PInt64 & v) { if (v >= 0) Out64(stream, v); else { int w = stream.width(); stream.put('-'); if (w > 0) stream.width(w-1); Out64(stream, -v); } return stream; } ostream & operator<<(ostream & stream, const PUInt64 & v) { Out64(stream, v); return stream; } static PUInt64 Inp64(istream & stream) { int base; switch (stream.flags()&ios::basefield) { case ios::oct : base = 8; break; case ios::hex : base = 16; break; default : base = 10; } if (isspace(stream.peek())) stream.get(); PInt64 num = 0; while (isxdigit(stream.peek())) { int c = stream.get() - '0'; if (c > 9) c -= 7; if (c > 9) c -= 32; num = num*base + c; } return num; } istream & operator>>(istream & stream, PInt64 & v) { if (isspace(stream.peek())) stream.get(); switch (stream.peek()) { case '-' : stream.ignore(); v = -(PInt64)Inp64(stream); break; case '+' : stream.ignore(); default : v = (PInt64)Inp64(stream); } return stream; } istream & operator>>(istream & stream, PUInt64 & v) { v = Inp64(stream); return stream; } #endif #ifdef P_TORNADO // the library provided with Tornado 2.0 does not contain implementation // for the functions defined below, therefor the own implementation ostream & ostream::operator<<(PInt64 v) { return *this << (long)(v >> 32) << (long)(v & 0xFFFFFFFF); } ostream & ostream::operator<<(PUInt64 v) { return *this << (long)(v >> 32) << (long)(v & 0xFFFFFFFF); } istream & istream::operator>>(PInt64 & v) { return *this >> (long)(v >> 32) >> (long)(v & 0xFFFFFFFF); } istream & istream::operator>>(PUInt64 & v) { return *this >> (long)(v >> 32) >> (long)(v & 0xFFFFFFFF); } #endif // P_TORNADO /////////////////////////////////////////////////////////////////////////////// namespace PProfiling { static uint64_t InitFrequency() { #if defined(P_LINUX) ifstream cpuinfo("/proc/cpuinfo", ios::in); while (cpuinfo.good()) { char line[100]; cpuinfo.getline(line, sizeof(line)); if (strncmp(line, "cpu MHz", 7) == 0) return (uint64_t)(atof(strchr(line, ':')+1)*1000000); } return 2000000000; // 2GHz #elif defined(_M_IX86) || defined(_M_X64) || defined(_WIN32) LARGE_INTEGER li; QueryPerformanceFrequency(&li); return li.QuadPart * 1000; #elif defined(CLOCK_MONOTONIC) return 1000000000ULL; #else return 1000000ULL; #endif } static uint64_t gs_Frequency = InitFrequency(); int64_t CyclesToNanoseconds(uint64_t cycles) { static long double const gs_CyclesPerNanoseconds = (long double)gs_Frequency/PTimeInterval::SecsToNano; return (int64_t)(cycles/gs_CyclesPerNanoseconds); } float CyclesToSeconds(uint64_t cycles) { return (float)((double)cycles/gs_Frequency); } #if P_PROFILING // Currently only supported in GNU && *nix enum FunctionType { e_AutoEntry, e_AutoExit, e_ManualEntry, e_ManualExit, e_SystemEntry, e_SystemExit }; struct FunctionRawData { PPROFILE_EXCLUDE(FunctionRawData(FunctionType type, void * function, void * caller)); PPROFILE_EXCLUDE(FunctionRawData(FunctionType type, const PDebugLocation * location)); PPROFILE_EXCLUDE(void Dump(ostream & out) const); // Do not use memory check allocation PPROFILE_EXCLUDE(void * operator new(size_t nSize)); PPROFILE_EXCLUDE(void operator delete(void * ptr)); union { // Note for correct operation m_pointer must overlay m_name struct { void * m_pointer; void * m_caller; }; struct { const char * m_name; const char * m_file; unsigned m_line; }; } m_function; FunctionType m_type; PThreadIdentifier m_threadIdentifier; PUniqueThreadIdentifier m_threadUniqueId; uint64_t m_when; FunctionRawData * m_link; private: FunctionRawData(const FunctionRawData &) { } void operator=(const FunctionRawData &) { } }; struct ThreadRawData : Thread { PPROFILE_EXCLUDE(ThreadRawData( PThreadIdentifier threadId, PUniqueThreadIdentifier uniqueId, const char * name, float real, float systemCPU, float userCPU )); PPROFILE_EXCLUDE(void Dump(ostream & out) const); // Do not use memory check allocation PPROFILE_EXCLUDE(void * operator new(size_t nSize)); PPROFILE_EXCLUDE(void operator delete(void * ptr)); ThreadRawData * m_link; }; struct Database { public: PPROFILE_EXCLUDE(Database()); PPROFILE_EXCLUDE(~Database()); bool m_enabled; atomic<FunctionRawData *> m_functions; atomic<ThreadRawData *> m_threads; uint64_t m_start; }; static Database s_database; ///////////////////////////////////////////////////////////////////// FunctionRawData::FunctionRawData(FunctionType type, void * function, void * caller) : m_type(type) , m_threadIdentifier(PThread::GetCurrentThreadId()) , m_threadUniqueId(PThread::GetCurrentUniqueIdentifier()) , m_when(GetCycles()) { m_function.m_pointer = function; m_function.m_caller = caller; m_link = s_database.m_functions.exchange(this); } FunctionRawData::FunctionRawData(FunctionType type, const PDebugLocation * location) : m_type(type) , m_threadIdentifier(PThread::GetCurrentThreadId()) , m_threadUniqueId(PThread::GetCurrentUniqueIdentifier()) , m_when(GetCycles()) { if (location) { m_function.m_name = location->m_extra; m_function.m_file = location->m_file; m_function.m_line = location->m_line; } else { m_function.m_name = NULL; m_function.m_file = NULL; m_function.m_line = 0; } m_link = s_database.m_functions.exchange(this); } void * FunctionRawData::operator new(size_t nSize) { return runtime_malloc(nSize); } void FunctionRawData::operator delete(void * ptr) { runtime_free(ptr); } void FunctionRawData::Dump(ostream & out) const { switch (m_type) { case e_AutoEntry: out << "AutoEnter\t" << m_function.m_pointer << '\t' << m_function.m_caller; break; case e_AutoExit: out << "AutoExit\t" << m_function.m_pointer << '\t' << m_function.m_caller; break; case e_ManualEntry: out << "ManualEnter\t" << m_function.m_name << '\t' << m_function.m_file << '(' << m_function.m_line << ')'; break; case e_ManualExit: out << "ManualExit\t" << m_function.m_name << '\t'; break; default : PAssertAlways(PLogicError); } out << '\t' << m_threadUniqueId << '\t' << m_when << '\n'; } ///////////////////////////////////////////////////////////////////// ThreadRawData::ThreadRawData(PThreadIdentifier threadId, PUniqueThreadIdentifier uniqueId, const char * name, float realTime, float systemCPU, float userCPU) : Thread(threadId, uniqueId, name, realTime, systemCPU, userCPU) { } void * ThreadRawData::operator new(size_t nSize) { return runtime_malloc(nSize); } void ThreadRawData::operator delete(void * ptr) { runtime_free(ptr); } void ThreadRawData::Dump(ostream & out) const { out << "Thread\t" << m_name << '\t' << m_threadId << '\t' << m_uniqueId << '\t' << m_realTime << '\t' << m_userCPU << '\t' << m_systemCPU << '\n'; } void OnThreadEnded(const PThread & thread, const PTimeInterval & realTime, const PTimeInterval & systemCPU, const PTimeInterval & userCPU) { if (s_database.m_enabled) { ThreadRawData * info = new ThreadRawData(thread.GetThreadId(), thread.GetUniqueIdentifier(), thread.GetThreadName(), realTime.GetMilliSeconds()/1000.0f, systemCPU.GetMilliSeconds()/1000.0f, userCPU.GetMilliSeconds()/1000.0f); info->m_link = s_database.m_threads.exchange(info); } } ///////////////////////////////////////////////////////////////////// Block::Block(const PDebugLocation & location) : m_location(location) { if (s_database.m_enabled) new FunctionRawData(e_ManualEntry, &location); } Block::~Block() { if (s_database.m_enabled) new FunctionRawData(e_ManualExit, &m_location); } ///////////////////////////////////////////////////////////////////// Database::Database() : m_enabled(getenv("PTLIB_PROFILING_ENABLED") != NULL) , m_functions(NULL) , m_threads(NULL) , m_start(GetCycles()) { } Database::~Database() { if (static_cast<FunctionRawData *>(m_functions) == NULL) return; const char * filename; if ((filename = getenv("PTLIB_RAW_PROFILING_FILENAME")) != NULL) { ofstream out(filename, ios::out | ios::trunc); if (out.is_open()) Dump(out); } if ((filename = getenv("PTLIB_PROFILING_FILENAME")) != NULL) { ofstream out(filename, ios::out | ios::trunc); if (out.is_open()) Analyse(out, strstr(filename, ".html") != NULL); } Reset(); } void Enable(bool enab) { s_database.m_enabled = enab; } bool IsEnabled() { return s_database.m_enabled; } void Reset() { s_database.m_start = GetCycles(); ThreadRawData * thrd = s_database.m_threads.exchange(NULL); FunctionRawData * func = s_database.m_functions.exchange(NULL); while (func != NULL) { FunctionRawData * del = func; func = func->m_link; delete del; } while (thrd != NULL) { ThreadRawData * del = thrd; thrd = thrd->m_link; delete del; } } void PreSystem() { if (s_database.m_enabled) new FunctionRawData(e_SystemEntry, NULL); } void PostSystem() { if (s_database.m_enabled) new FunctionRawData(e_SystemExit, NULL); } void Dump(ostream & strm) { for (ThreadRawData * info = s_database.m_threads; info != NULL; info = info->m_link) info->Dump(strm); for (FunctionRawData * info = s_database.m_functions; info != NULL; info = info->m_link) info->Dump(strm); } class CpuTime { private: uint64_t m_cycles; double m_time; public: CpuTime(uint64_t cycles) : m_cycles(cycles) , m_time(CyclesToSeconds(cycles)) { } private: void PrintOn(ostream & strm) const { strm << m_cycles << " ("; if (m_time >= 1) { if (m_time >= 1000) strm.precision(0); else if (m_time >= 100) strm.precision(1); else if (m_time >= 10) strm.precision(2); else strm.precision(3); strm << m_time; } else if (m_time >= 0.001) { if (m_time >= 0.1) strm.precision(1); else if (m_time >= 0.01) strm.precision(2); else strm.precision(3); strm << 1000.0*m_time << 'm'; } else { if (m_time >= 0.0001) strm.precision(1); else if (m_time >= 0.00001) strm.precision(2); else strm.precision(3); strm << 1000000.0*m_time << '\xb5'; // Greek mu, micro symbol in most fonts } strm << "s)"; } friend ostream & operator<<(ostream & strm, const CpuTime & c) { if (strm.width() < 10) c.PrintOn(strm); else { ostringstream str; c.PrintOn(str); strm << str.str(); } return strm; } }; __inline static float Percentage(float v1, float v2) { return v2 > 0 ? 100.0f * v1 / v2 : 0.0f; } void Analysis::ToText(ostream & strm) const { std::streamsize threadNameWidth = 0; std::streamsize functionNameWidth = 0; for (ThreadByUsage::const_iterator thrd = m_threadByUsage.begin(); thrd != m_threadByUsage.end(); ++thrd) { std::streamsize len = thrd->second.m_name.length(); if (len > threadNameWidth) threadNameWidth = len; for (FunctionMap::const_iterator func = thrd->second.m_functions.begin(); func != thrd->second.m_functions.end(); ++func) { len = func->first.length(); if (len > functionNameWidth) functionNameWidth = len; } } threadNameWidth += 3; functionNameWidth += 2; strm << "Summary profile:" " threads=" << m_threadByID.size() << "," " functions=" << m_functionCount << "," " cycles=" << m_durationCycles << "," " frequency=" << gs_Frequency << "," " time=" << left << fixed << setprecision(3) << CyclesToSeconds(m_durationCycles) << '\n'; for (ThreadByUsage::const_iterator thrd = m_threadByUsage.begin(); thrd != m_threadByUsage.end(); ++thrd) { strm << " Thread \"" << setw(threadNameWidth) << (thrd->second.m_name+'"') << " id=" << setw(8) << thrd->second.m_uniqueId << " real=" << setw(10) << setprecision(3) << thrd->second.m_realTime << " sys=" << setw(10) << setprecision(3) << thrd->second.m_systemCPU << " user=" << setw(10) << setprecision(3) << thrd->second.m_userCPU; if (thrd->first >= 0) strm << " (" << setprecision(2) << thrd->first << "%)"; strm << '\n'; for (FunctionMap::const_iterator func = thrd->second.m_functions.begin(); func != thrd->second.m_functions.end(); ++func) { uint64_t avg = func->second.m_sum / func->second.m_count; strm << " " << left << setw(functionNameWidth) << func->first << " count=" << setw(10) << func->second.m_count << " min=" << setw(24) << CpuTime(func->second.m_minimum) << " max=" << setw(24) << CpuTime(func->second.m_maximum) << " avg=" << setw(24) << CpuTime(avg); if (thrd->second.m_realTime > 0) strm << " (" << setprecision(2) << Percentage(CyclesToSeconds(func->second.m_sum), thrd->second.m_realTime) << "%)"; strm << '\n'; } } } class EscapedHTML { private: const std::string m_str; public: EscapedHTML(const std::string & str) : m_str(str) { } friend ostream & operator<<(ostream & strm, const EscapedHTML & e) { for (size_t i = 0; i < e.m_str.length(); ++i) { switch (e.m_str[i]) { case '"': strm << "&quot;"; break; case '<': strm << "&lt;"; break; case '>': strm << "&gt;"; break; case '&': strm << "&amp;"; break; default: strm << e.m_str[i]; } } return strm; } }; void Analysis::ToHTML(ostream & strm) const { strm << "<H2>Summary profile</H2>" "<table border=1 cellspacing=1 cellpadding=12>" "<tr>" "<th>Threads<th>Functions<th>Cycles<th>Frequency<th>Time" "<tr>" "<td align=center>" << m_threadByID.size() << "<td align=center>" << m_functionCount << "<td align=center>" << m_durationCycles << "<td align=center>" << gs_Frequency << "<td align=center>" << fixed << setprecision(3) << CyclesToSeconds(m_durationCycles) << "</table>" "<p>" "<table width=\"100%\" border=1 cellspacing=0 cellpadding=8>" "<tr><th width=\"1%\">ID" "<th align=left>Thread" "<th width=\"5%\" nowrap>Real Time" "<th width=\"5%\" nowrap>System CPU" "<th width=\"5%\" align=right nowrap>System Core %" "<th width=\"5%\" nowrap>User CPU" "<th width=\"5%\" align=right nowrap>User Core %"; for (ThreadByUsage::const_iterator thrd = m_threadByUsage.begin(); thrd != m_threadByUsage.end(); ++thrd) { strm << "<tr>" "<td width=\"1%\" align=center>" << thrd->second.m_uniqueId << "<td>" << EscapedHTML(thrd->second.m_name) << setprecision(3) << "<td width=\"5%\" align=center>" << thrd->second.m_realTime << 's' << "<td width=\"5%\" align=center>" << thrd->second.m_systemCPU << 's' << "<td width=\"5%\" align=right>"; if (thrd->first >= 0) strm << setprecision(2) << Percentage(thrd->second.m_systemCPU, thrd->second.m_realTime) << '%'; else strm << "&nbsp;"; strm << "<td width=\"5%\" align=center>" << thrd->second.m_userCPU << 's' << "<td width=\"5%\" align=right>"; if (thrd->first >= 0) strm << setprecision(2) << thrd->first << '%'; else strm << "&nbsp;"; if (!thrd->second.m_functions.empty()) { strm << "<tr><td>&nbsp;<td colspan=\"9999\">" "<table border=1 cellspacing=1 cellpadding=4 width=100%>" "<th align=left>Function" "<th>Count" "<th>Minimum" "<th>Maximum" "<th>Average" "<th align=right nowrap>Core %"; for (FunctionMap::const_iterator func = thrd->second.m_functions.begin(); func != thrd->second.m_functions.end(); ++func) { uint64_t avg = func->second.m_sum / func->second.m_count; strm << "<tr>" "<td>" << EscapedHTML(func->first) << "<td align=center>" << func->second.m_count << "<td align=center nowrap>" << CpuTime(func->second.m_minimum) << "<td align=center nowrap>" << CpuTime(func->second.m_maximum) << "<td align=center nowrap>" << CpuTime(avg); if (thrd->second.m_realTime > 0) strm << "<td align=right>" << setprecision(2) << Percentage(CyclesToSeconds(func->second.m_sum), thrd->second.m_realTime) << '%'; } strm << "</table>"; } } strm << "</table>"; } static ThreadByID::iterator AddThreadByID(ThreadByID & threadByID, const PThread::Times & times) { Thread threadInfo(times.m_threadId, times.m_uniqueId); threadInfo.m_name = times.m_name.GetPointer(); threadInfo.m_realTime = times.m_real.GetMilliSeconds()/1000.0f; threadInfo.m_systemCPU = times.m_kernel.GetMilliSeconds()/1000.0f; threadInfo.m_userCPU = times.m_user.GetMilliSeconds()/1000.0f; threadInfo.m_running = true; return threadByID.insert(make_pair(times.m_uniqueId, threadInfo)).first; } void Analyse(Analysis & analysis) { analysis.m_durationCycles = GetCycles() - s_database.m_start; std::list<PThread::Times> times; PThread::GetTimes(times); for (std::list<PThread::Times>::iterator it = times.begin(); it != times.end(); ++it) AddThreadByID(analysis.m_threadByID, *it); for (ThreadRawData * thrd = s_database.m_threads; thrd != NULL; thrd = thrd->m_link) analysis.m_threadByID.insert(make_pair(thrd->m_uniqueId, *thrd)); for (FunctionRawData * exit = s_database.m_functions; exit != NULL; exit = exit->m_link) { std::string functionName; switch (exit->m_type) { default : continue; case e_ManualExit: functionName = exit->m_function.m_name; break; case e_AutoExit: stringstream strm; strm << exit->m_function.m_pointer; functionName = strm.str(); break; } uint64_t subFunctionAccumulator = 0; // Find the next entry in that thread FunctionRawData * entry; for (entry = exit->m_link; entry != NULL; entry = entry->m_link) { if (entry->m_threadUniqueId != exit->m_threadUniqueId) continue; switch (entry->m_type) { case e_ManualEntry : case e_AutoEntry: case e_SystemEntry : if (entry->m_function.m_pointer == exit->m_function.m_pointer) break; continue; // Should not happen! default : // Have an exit, so look for matching entry FunctionRawData * subEntry; for (subEntry = entry->m_link; subEntry != NULL; subEntry = subEntry->m_link) { if (subEntry->m_threadUniqueId == entry->m_threadUniqueId && subEntry->m_function.m_pointer == entry->m_function.m_pointer) break; } if (subEntry == NULL) continue; // Should not happen! // Amount of time in sub-function, subtract it off later subFunctionAccumulator += entry->m_when - subEntry->m_when; entry = subEntry; continue; } ThreadByID::iterator thrd = analysis.m_threadByID.find(entry->m_threadUniqueId); if (thrd == analysis.m_threadByID.end()) { PThread::Times threadTimes; PThread::GetTimes(entry->m_threadIdentifier, threadTimes); thrd = AddThreadByID(analysis.m_threadByID, threadTimes); } FunctionMap & functions = thrd->second.m_functions; FunctionMap::iterator func = functions.find(functionName); if (func == functions.end()) { func = functions.insert(make_pair(functionName, Function())).first; ++analysis.m_functionCount; } uint64_t diff = exit->m_when - entry->m_when - subFunctionAccumulator; if (func->second.m_minimum > diff) func->second.m_minimum = diff; if (func->second.m_maximum < diff) func->second.m_maximum = diff; func->second.m_sum += diff; ++func->second.m_count; break; } } for (ThreadByID::iterator thrd = analysis.m_threadByID.begin(); thrd != analysis.m_threadByID.end(); ++thrd) analysis.m_threadByUsage.insert(make_pair(Percentage(thrd->second.m_userCPU, thrd->second.m_realTime), thrd->second)); } void Analyse(ostream & strm, bool html) { Analysis analysis; Analyse(analysis); if (html) analysis.ToHTML(strm); else analysis.ToText(strm); } #endif // P_PROFILING #if PTRACING struct TimeScope::Implementation { PDebugLocation m_location; PTimeInterval m_thresholdTime; PTimeInterval m_throttleTime; unsigned m_throttledLogLevel; unsigned m_unthrottledLogLevel; unsigned m_thresholdPercent; unsigned m_maxHistory; PMinMaxAvg<PTimeInterval> m_mma; unsigned m_countTimesOverThreshold; PTime m_lastOutputTime; PTimeInterval m_lastDuration; struct History { explicit History(const PTimeInterval & duration, const PDebugLocation & location) : m_when(), m_duration(duration), m_location(location) { } PTime const m_when; PTimeInterval const m_duration; PDebugLocation const m_location; }; std::list<History> m_history; PCriticalSection m_mutex; Implementation(const PDebugLocation & location, unsigned thresholdTime, unsigned throttleTime, unsigned throttledLogLevel, unsigned unthrottledLogLevel, unsigned thresholdPercent, unsigned maxHistory) : m_location(location) , m_thresholdTime(thresholdTime) , m_throttleTime(throttleTime) , m_throttledLogLevel(throttledLogLevel) , m_unthrottledLogLevel(unthrottledLogLevel) , m_thresholdPercent(thresholdPercent) , m_maxHistory(maxHistory) , m_mma("s") , m_countTimesOverThreshold(0) , m_lastOutputTime(0) { } void EndMeasurement(const void * ptr, const PObject * object, const PDebugLocation * location, const PNanoSeconds & duration) { PWaitAndSignal lock(m_mutex); m_lastDuration = duration; m_mma.Accumulate(duration); if (!PTrace::CanTrace(m_throttledLogLevel) || duration < m_thresholdTime) return; ++m_countTimesOverThreshold; if (m_mma.GetCount() < 3) return; PTime now; unsigned percentOver = m_countTimesOverThreshold * 100 / m_mma.GetCount(); bool isTime = (now - m_lastOutputTime) > m_throttleTime; unsigned level = isTime && percentOver >= m_thresholdPercent ? m_throttledLogLevel : m_unthrottledLogLevel; if (PTrace::CanTrace(level)) { ostream & trace = PTrace::Begin(level, m_location.m_file, m_location.m_line, object, "TimeScope"); trace << m_location.m_extra << '(' << ptr << "):" " since=" << m_lastOutputTime.AsString(PTime::TodayFormat, PTrace::GetTimeZone()) << "," << setprecision(3) << scientific << showbase << m_mma << noshowbase << " thresh=" << PScaleSI(m_thresholdTime) << ';' << m_thresholdPercent << "%," " slow=" << m_countTimesOverThreshold << '/' << m_mma.GetCount() << ' ' << percentOver << '%'; if (location) location->PrintOn(trace, " where="); for (list<History>::iterator it = m_history.begin(); it != m_history.end(); ++it) { trace << "\n when=" << it->m_when.AsString(PTime::TodayFormat, PTrace::GetTimeZone()) << "," " duration=" << PScaleSI(it->m_duration); it->m_location.PrintOn(trace, "where="); } trace << PTrace::End; } if (isTime) { m_mma.Reset(); m_countTimesOverThreshold = 0; m_lastOutputTime = now; m_history.clear(); } if (m_maxHistory > 0) { m_history.push_back(History(duration, location)); if (m_history.size() > m_maxHistory) m_history.pop_front(); } } }; TimeScope::TimeScope(const PDebugLocation & location, unsigned thresholdTime, unsigned throttleTime, unsigned throttledLogLevel, unsigned unthrottledLogLevel, unsigned thresholdPercent, unsigned maxHistory) // Note that there is a race here on he static definition of the TimeScope isntance, // that would leak precisely one Implementation object, big deal. : m_implementation(new Implementation(location, thresholdTime, throttleTime, throttledLogLevel, unthrottledLogLevel, thresholdPercent, maxHistory)) { } TimeScope::TimeScope(const TimeScope & other) : m_implementation(new Implementation(other.m_implementation->m_location, other.m_implementation->m_thresholdTime.GetSeconds(), other.m_implementation->m_throttleTime.GetSeconds(), other.m_implementation->m_throttledLogLevel, other.m_implementation->m_unthrottledLogLevel, other.m_implementation->m_thresholdPercent, other.m_implementation->m_maxHistory)) { } TimeScope::~TimeScope() { delete m_implementation; } void TimeScope::SetThrottleTime(unsigned throttleTime) { PWaitAndSignal lock(m_implementation->m_mutex); m_implementation->m_throttleTime = throttleTime; } void TimeScope::SetThrottledLogLevel(unsigned throttledLogLevel) { PWaitAndSignal lock(m_implementation->m_mutex); m_implementation->m_throttledLogLevel = throttledLogLevel; } void TimeScope::SetUnthrottledLogLevel(unsigned unthrottledLogLevel) { PWaitAndSignal lock(m_implementation->m_mutex); m_implementation->m_unthrottledLogLevel = unthrottledLogLevel; } void TimeScope::SetThresholdPercent(unsigned thresholdPercent) { PWaitAndSignal lock(m_implementation->m_mutex); m_implementation->m_thresholdPercent = thresholdPercent; } void TimeScope::SetMaxHistory(unsigned maxHistory) { PWaitAndSignal lock(m_implementation->m_mutex); m_implementation->m_maxHistory = maxHistory; } void TimeScope::EndMeasurement(const void * context, const PObject * object, const PDebugLocation * location, uint64_t startCycle) { m_implementation->EndMeasurement(context, object, location, CyclesToNanoseconds(GetCycles() - startCycle)); } const PTimeInterval & TimeScope::GetLastDuration() const { return m_implementation->m_lastDuration; } #endif // PTRACING /// ///////////////////////////////////////////////////////////////// class HighWaterMarks { typedef std::map<std::string, HighWaterMarkData*> DataMap; DataMap m_data; PCriticalSection m_mutex; public: ~HighWaterMarks() { for (DataMap::const_iterator it = m_data.begin(); it != m_data.end(); ++it) delete it->second; } HighWaterMarkData & Get(const type_info & ti) { std::string name = ti.name(); if (name.compare(0, 6, "class ") == 0) name.erase(0, 6); else if (name.compare(0, 7, "struct ") == 0) name.erase(0, 7); PWaitAndSignal lock(m_mutex); DataMap::iterator it = m_data.find(name); if (it == m_data.end()) it = m_data.insert(make_pair(name, new HighWaterMarkData(name))).first; return *it->second; } std::map<std::string, unsigned> Get() const { std::map<std::string, unsigned> data; PWaitAndSignal lock(m_mutex); for (DataMap::const_iterator it = m_data.begin(); it != m_data.end(); ++it) data[it->first] = it->second->m_highWaterMark; return data; } }; static HighWaterMarks & GetHighWaterMarks() { static HighWaterMarks s_highWaterMarks; return s_highWaterMarks; } HighWaterMarkData::HighWaterMarkData(const std::string & name) : m_name(name) , m_totalCount(0) , m_highWaterMark(0) { } void HighWaterMarkData::NewInstance() { unsigned totalCount = ++m_totalCount; unsigned highWaterMark = m_highWaterMark; while (totalCount > highWaterMark) { if (m_highWaterMark.compare_exchange_strong(highWaterMark, totalCount)) break; highWaterMark = m_highWaterMark; } } HighWaterMarkData & HighWaterMarkData::Get(const type_info & ti) { return GetHighWaterMarks().Get(ti); } std::map<std::string, unsigned> HighWaterMarkData::Get() { return GetHighWaterMarks().Get(); } }; // namespace PProfiling #if P_PROFILING #ifdef __GNUC__ extern "C" { #undef new PPROFILE_EXCLUDE(void __cyg_profile_func_enter(void * function, void * caller)); PPROFILE_EXCLUDE(void __cyg_profile_func_exit(void * function, void * caller)); void __cyg_profile_func_enter(void * function, void * caller) { if (PProfiling::s_database.m_enabled) new PProfiling::FunctionRawData(PProfiling::e_AutoEntry, function, caller); } void __cyg_profile_func_exit(void * function, void * caller) { if (PProfiling::s_database.m_enabled) new PProfiling::FunctionRawData(PProfiling::e_AutoExit, function, caller); } }; #endif // __GNUC__ #endif // P_PROFILING // End Of File ///////////////////////////////////////////////////////////////
26.072411
153
0.608028
sverdlin