hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 float64 1 77k ⌀ | 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 float64 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 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
62be39df916655715856391362c1bee44d19356f | 485 | cpp | C++ | Luogu/P1115/P1115.cpp | AtomAlpaca/OI-Codes | 11f8dd4798616f1937d190e7220d7eedaeb75169 | [
"WTFPL"
] | 1 | 2021-11-12T14:19:53.000Z | 2021-11-12T14:19:53.000Z | Luogu/P1115/P1115.cpp | AtomAlpaca/OI-Codes | 11f8dd4798616f1937d190e7220d7eedaeb75169 | [
"WTFPL"
] | null | null | null | Luogu/P1115/P1115.cpp | AtomAlpaca/OI-Codes | 11f8dd4798616f1937d190e7220d7eedaeb75169 | [
"WTFPL"
] | null | null | null | #include <iostream>
#include <cmath>
#include <algorithm>
using std::cin;
using std::cout;
int main(int argc, char const *argv[])
{
//int m = -10000000;
int * n = new int;
cin >> *n;
int nums[*n + 1] = {0};
int ans [*n + 1] = {0};
int m = -99999999;
for (int i = 1; i <= *n; ++i)
{
cin >> nums[i];
ans[i] = std::max(ans[i - 1] + nums[i], nums[i]);
m = std::max(m, ans[i]);
}
cout << m;
delete n;
return 0;
}
| 16.724138 | 57 | 0.463918 |
62be72f300f0bc4e7c0f81203ee26c504a78719b | 6,270 | cpp | C++ | src/main.cpp | cowdingus/SFML-Grapher | 47d0e661aa9c411d9a41f4fe8f4df7860af7ec74 | [
"Unlicense"
] | 1 | 2021-01-26T09:52:41.000Z | 2021-01-26T09:52:41.000Z | src/main.cpp | cowdingus/SFML-Grapher | 47d0e661aa9c411d9a41f4fe8f4df7860af7ec74 | [
"Unlicense"
] | 1 | 2020-11-10T06:54:07.000Z | 2020-11-10T11:40:53.000Z | src/main.cpp | cowdingus/SFML-Grapher | 47d0e661aa9c411d9a41f4fe8f4df7860af7ec74 | [
"Unlicense"
] | null | null | null | /*
* ToDo:
* look at @setSize implementation
* fix bugs
*
* Bugs Found:
* crashes and hangs the whole computer when setting zoom value to some little value
*/
#include "CartesianGraphView.hpp"
#include "CartesianGrid.hpp"
#include "DotGraph.hpp"
#include <SFML/Graphics.hpp>
#include <SFML/Window/ContextSettings.hpp>
#include <iostream>
#include <cassert>
template<typename T>
std::ostream& operator<<(std::ostream& out, const sf::Vector2<T>& vector)
{
return out << "{" << vector.x << ", " << vector.y << "}";
}
template<typename T>
std::ostream& operator<<(std::ostream& out, const sf::Rect<T>& rect)
{
return out << "{" << rect.left << ", " << rect.top << ", " << rect.width << ", " << rect.height << "}" << std::endl;
}
std::ostream& operator<<(std::ostream& out, const sf::Transform& transform)
{
const float* m = transform.getMatrix();
out << "[" << m[0] << '\t' << m[4] << '\t' << m[8 ] << '\t' << m[12] << '\t' << "]" << std::endl
<< "[" << m[1] << '\t' << m[5] << '\t' << m[9 ] << '\t' << m[13] << '\t' << "]" << std::endl
<< "[" << m[2] << '\t' << m[6] << '\t' << m[10] << '\t' << m[14] << '\t' << "]" << std::endl
<< "[" << m[3] << '\t' << m[7] << '\t' << m[11] << '\t' << m[15] << '\t' << "]" << std::endl;
return out;
}
int main()
{
sf::ContextSettings settings;
settings.antialiasingLevel = 4;
sf::RenderWindow window(sf::VideoMode(800, 600), "NULL", sf::Style::Default, settings);
window.setFramerateLimit(15);
{
std::cout << "Graph Tests" << std::endl;
DotGraph lg;
lg.addPoint({1, 1});
assert(lg.getPoint(0) == sf::Vector2f(1, 1));
lg.removePoint(0);
assert(lg.getPointsCount() == 0);
lg.addPoint({1, 1});
assert(lg.getPoint(0) == sf::Vector2f(1, 1));
lg.clearPoints();
assert(lg.getPointsCount() == 0);
std::cout << "Graph Data Insertion/Deletion Tests Passed" << std::endl;
lg.setGridColor(sf::Color::White);
assert(lg.getGridColor() == sf::Color::White);
lg.setGridGap({10, 10});
assert(lg.getGridGap() == sf::Vector2f(10, 10));
lg.setColor(sf::Color::Black);
assert(lg.getColor() == sf::Color::Black);
CartesianGraphView view = lg.getView();
view.setViewRect({0, 0, 10, 10});
lg.setView(view);
std::cout << lg.getView().getViewRect() << std::endl;
assert(lg.getView().getViewRect() == sf::FloatRect(0, 0, 10, 10));
std::cout << "Visual Properties Tests Passed" << std::endl;
}
{
std::cout << "Graph View Tests" << std::endl;
CartesianGraphView view;
view.setCenter({100, 100});
assert(view.getCenter() == sf::Vector2f(100, 100));
view.setSize({100, 100});
assert(view.getSize() == sf::Vector2f(100, 100));
view.setViewRect({0, 0, 10, 10});
assert(view.getViewRect() == sf::FloatRect(0, 0, 10, 10));
assert(view.getCenter() == sf::Vector2f(5, 5));
assert(view.getSize() == sf::Vector2f(10, 10));
view.setCenter({10, 10});
assert(view.getCenter() == sf::Vector2f(10, 10));
view.setSize({10, 10});
assert(view.getSize() == sf::Vector2f(10, 10));
view.setZoom({10, 10});
assert(view.getZoom() == sf::Vector2f(10, 10));
view = CartesianGraphView();
view.setCenter({1, 1});
view.setSize({2, 2});
std::cout << view.getTransform() * sf::Vector2f(0, 0) << std::endl;
assert(view.getTransform() * sf::Vector2f(0, 0) == sf::Vector2f(0, 0));
}
std::cout << "All Tests Passed" << std::endl << std::endl;
DotGraph lg({400, 400});
lg.setPosition(100, 100);
lg.addPoint({0, 0});
lg.addPoint({-1, 0});
lg.addPoint({1, 0});
lg.addPoint({0, -1});
lg.addPoint({0, 1});
lg.addPoint({0, 2});
lg.addPoint({-3, 0});
lg.setGridGap({1, 1});
lg.setGridColor(sf::Color(100, 100, 100));
CartesianGraphView lgv;
lgv.setCenter({-2, -2});
lgv.setSize({8, 8});
lgv.setViewRect({-2, -2, 8, 8});
lgv.setCenter({0, 0});
lgv.setSize({10, 10});
lgv.setZoom({2,1});
lg.setView(lgv);
lg.setSize({200, 200});
lg.setColor(sf::Color::Cyan);
sf::RectangleShape boundingBox;
boundingBox.setSize(static_cast<sf::Vector2f>(lg.getSize()));
boundingBox.setPosition({100, 100});
boundingBox.setOutlineThickness(1);
boundingBox.setOutlineColor(sf::Color::Magenta);
boundingBox.setFillColor(sf::Color(0, 0, 0, 0));
sf::Font arial;
if (!arial.loadFromFile("debug/Arial.ttf"))
{
sf::err() << "Error: Can't load font file" << std::endl;
}
sf::Text keymapGuide;
keymapGuide.setString(
"[M] to zoom in\n"
"[N] to zoom out\n"
"[Arrow keys] to move graph\n"
"[W | A | S | D] to move view\n"
);
keymapGuide.setFont(arial);
keymapGuide.setCharacterSize(12);
keymapGuide.setFillColor(sf::Color::White);
keymapGuide.setPosition(
{
window.getSize().x - keymapGuide.getGlobalBounds().width,
window.getSize().y - keymapGuide.getGlobalBounds().height
}
);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
{
window.close();
break;
}
case sf::Event::KeyPressed:
{
sf::View newView = window.getView();
CartesianGraphView graphView = lg.getView();
switch (event.key.code)
{
case sf::Keyboard::W:
newView.move(0, -10);
break;
case sf::Keyboard::S:
newView.move(0, 10);
break;
case sf::Keyboard::A:
newView.move(-10, 0);
break;
case sf::Keyboard::D:
newView.move(10, 0);
break;
case sf::Keyboard::Up:
graphView.move({0, 0.1});
break;
case sf::Keyboard::Down:
graphView.move({0, -0.1});
break;
case sf::Keyboard::Left:
graphView.move({-0.1, 0});
break;
case sf::Keyboard::Right:
graphView.move({0.1, 0});
break;
case sf::Keyboard::M:
if (graphView.getZoom().x < 3 && graphView.getZoom().y < 3)
graphView.setZoom(graphView.getZoom() + sf::Vector2f(0.1f, 0.1f));
break;
case sf::Keyboard::N:
if (graphView.getZoom().x > 1 && graphView.getZoom().y > 1)
graphView.setZoom(graphView.getZoom() - sf::Vector2f(0.1f, 0.1f));
break;
default:
break;
}
lg.setView(graphView);
window.setView(newView);
break;
}
default:
{
break;
}
}
}
lg.update();
window.clear();
window.draw(lg);
window.draw(boundingBox);
window.draw(keymapGuide);
window.display();
}
}
| 24.782609 | 117 | 0.59378 |
498329ce67e1973db69564b5ac7ac9288d12e1be | 988 | hpp | C++ | CTCWordBeamSearch-master/cpp/DataLoader.hpp | brucegrapes/htr | 9f8f07173ccc740dd8a4dfc7e8038abe36664756 | [
"MIT"
] | 488 | 2018-03-01T11:18:26.000Z | 2022-03-10T09:29:32.000Z | CTCWordBeamSearch-master/cpp/DataLoader.hpp | brucegrapes/htr | 9f8f07173ccc740dd8a4dfc7e8038abe36664756 | [
"MIT"
] | 60 | 2018-03-10T18:37:51.000Z | 2022-03-30T19:37:18.000Z | CTCWordBeamSearch-master/cpp/DataLoader.hpp | brucegrapes/htr | 9f8f07173ccc740dd8a4dfc7e8038abe36664756 | [
"MIT"
] | 152 | 2018-03-01T11:18:25.000Z | 2022-03-08T23:37:46.000Z | #pragma once
#include "MatrixCSV.hpp"
#include "LanguageModel.hpp"
#include <string>
#include <vector>
#include <memory>
#include <stdint.h>
#include <cstddef>
// load sample data, create LM from it, iterate over samples
class DataLoader
{
public:
// sample with matrix to be decoded and ground truth text
struct Data
{
MatrixCSV mat;
std::vector<uint32_t> gt;
};
// CTOR. Path points to directory holding files corpus.txt, chars.txt, wordChars.txt and samples mat_X.csv and gt_X.txt with X in {0, 1, 2, ...}
DataLoader(const std::string& path, size_t sampleEach, LanguageModelType lmType, double addK=0.0);
// get LM
std::shared_ptr<LanguageModel> getLanguageModel() const;
// iterator interface
Data getNext() const;
bool hasNext() const;
private:
std::string m_path;
std::shared_ptr<LanguageModel> m_lm;
mutable size_t m_currIdx=0;
const size_t m_sampleEach = 1;
void applySoftmax(MatrixCSV& mat) const;
bool fileExists(const std::string& path) const;
};
| 22.976744 | 145 | 0.733806 |
498b1074a57620a2675251ec28d972bfd0278f67 | 27 | cpp | C++ | lootman/f4se/bhkWorld.cpp | clayne/Lootman | 248befd3e1775a0eb9ca6dcbe261937d9641ef1c | [
"MIT"
] | 10 | 2019-06-01T20:24:04.000Z | 2021-08-16T19:32:24.000Z | lootman/f4se/bhkWorld.cpp | clayne/Lootman | 248befd3e1775a0eb9ca6dcbe261937d9641ef1c | [
"MIT"
] | null | null | null | lootman/f4se/bhkWorld.cpp | clayne/Lootman | 248befd3e1775a0eb9ca6dcbe261937d9641ef1c | [
"MIT"
] | 5 | 2019-07-04T05:54:14.000Z | 2021-10-11T11:19:57.000Z | #include "f4se/bhkWorld.h"
| 13.5 | 26 | 0.740741 |
498cecade6cfd20a126969d01ccd6c7cfe373c84 | 385 | cpp | C++ | software/state_machine_with_classes/Transition.cpp | CenWIDev/sumobot-resources | d93df990966b8304c67e9291d291a7a64820add9 | [
"Unlicense"
] | 3 | 2019-03-08T17:22:39.000Z | 2019-03-12T16:23:05.000Z | software/state_machine_with_classes/Transition.cpp | CenWIDev/sumobot-resources | d93df990966b8304c67e9291d291a7a64820add9 | [
"Unlicense"
] | 15 | 2019-03-08T15:20:25.000Z | 2022-01-10T21:49:17.000Z | software/state_machine_with_classes/Transition.cpp | CenWIDev/sumobot-resources | d93df990966b8304c67e9291d291a7a64820add9 | [
"Unlicense"
] | 2 | 2019-05-02T23:53:40.000Z | 2020-10-08T12:36:48.000Z | #include "Arduino.h"
#include "Log.h"
#include "Transition.h"
Transition::Transition(String to, TransitionFn f) {
_to = to;
_f = f;
}
Transition::~Transition(){}
bool Transition::ShouldTransition() {
auto shouldTransition = _f();
if(shouldTransition)
Info("Transitioning to state: " + _to);
return shouldTransition;
}
String Transition::To() {
return _to;
}
| 15.4 | 51 | 0.672727 |
498f94159e65d0f63e199e4534264d92426142da | 434 | cpp | C++ | source/Ch08/orai_anyag/vector_pass_by.cpp | Vada200/UDProg-Introduction | c424b2676d6e5bfc4d53d61c5d0deded566c1c84 | [
"CC0-1.0"
] | null | null | null | source/Ch08/orai_anyag/vector_pass_by.cpp | Vada200/UDProg-Introduction | c424b2676d6e5bfc4d53d61c5d0deded566c1c84 | [
"CC0-1.0"
] | null | null | null | source/Ch08/orai_anyag/vector_pass_by.cpp | Vada200/UDProg-Introduction | c424b2676d6e5bfc4d53d61c5d0deded566c1c84 | [
"CC0-1.0"
] | null | null | null | #include "std_lib_facilities.h"
void print (vector <double>& v)
//& -->referencia miatt gyorsabb a lefutás
//mert nem másolódik a v, hanem a v ugyanaz lesz mint a vd1
{
cout << "{";
for (int i = 0; i < v.size(); i++)
{
cout << v[i];
if(i < v.size()-1) cout << ",";
}
cout << "}\n";
}
int main()
{
vector <double> vd1 (10);
vector <double> vd2 (100000);
print(vd2);
return 0;
} | 16.692308 | 60 | 0.520737 |
4992e1630ce5e963ee2b1cc766c06866946cb4d5 | 2,991 | cpp | C++ | port/linux/test/content-test.cpp | GorgonMeducer/pikascript | fefe9afb17d14c1a3bbe75c4c6a83d65831f451e | [
"MIT"
] | null | null | null | port/linux/test/content-test.cpp | GorgonMeducer/pikascript | fefe9afb17d14c1a3bbe75c4c6a83d65831f451e | [
"MIT"
] | null | null | null | port/linux/test/content-test.cpp | GorgonMeducer/pikascript | fefe9afb17d14c1a3bbe75c4c6a83d65831f451e | [
"MIT"
] | null | null | null | #include "gtest/gtest.h"
#include "test_common.h"
extern "C" {
#include "dataArg.h"
#include "dataString.h"
}
#if 0
TEST(content, init) {
uint8_t contentIn[4] = {0};
contentIn[0] = 1;
contentIn[1] = 2;
contentIn[2] = 3;
contentIn[3] = 4;
Arg* self = content_init("name", ARG_TYPE_NONE, contentIn, 4, NULL);
uint16_t typeOffset = content_typeOffset(self);
uint16_t sizeOffset = content_sizeOffset(self);
uint16_t contentOffset = content_contentOffset(self);
uint16_t totleSize = content_totleSize(self);
Hash nameHash = content_getNameHash(self);
ArgType type = content_getType(self);
uint16_t size = content_getSize(self);
uint8_t* content = content_getContent(self);
ASSERT_EQ(contentOffset, 16);
ASSERT_EQ(typeOffset, 20);
ASSERT_EQ(sizeOffset, 8);
ASSERT_EQ(size, 4);
ASSERT_EQ(content[0], 1);
ASSERT_EQ(content[1], 2);
ASSERT_EQ(content[2], 3);
ASSERT_EQ(content[3], 4);
ASSERT_EQ(totleSize, 24);
ASSERT_EQ(hash_time33("name"), nameHash);
ASSERT_EQ(ARG_TYPE_NONE, type);
arg_freeContent(self);
EXPECT_EQ(pikaMemNow(), 0);
}
TEST(content, set) {
uint8_t contentIn[4] = {0};
contentIn[0] = 1;
contentIn[1] = 2;
contentIn[2] = 3;
contentIn[3] = 4;
Arg* self = content_init("", ARG_TYPE_NONE, NULL, 0, NULL);
self = content_setName(self, "name");
self = arg_setType(self, ARG_TYPE_NONE);
self = content_setContent(self, contentIn, 4);
uint16_t typeOffset = content_typeOffset(self);
uint16_t sizeOffset = content_sizeOffset(self);
uint16_t contentOffset = content_contentOffset(self);
uint16_t totleSize = content_totleSize(self);
Hash nameHash = content_getNameHash(self);
ArgType type = content_getType(self);
uint16_t size = content_getSize(self);
uint8_t* content = content_getContent(self);
ASSERT_EQ(contentOffset, 16);
ASSERT_EQ(typeOffset, 20);
ASSERT_EQ(sizeOffset, 8);
ASSERT_EQ(size, 4);
ASSERT_EQ(content[0], 1);
ASSERT_EQ(content[1], 2);
ASSERT_EQ(content[2], 3);
ASSERT_EQ(content[3], 4);
ASSERT_EQ(totleSize, 24);
ASSERT_EQ(hash_time33("name"), nameHash);
ASSERT_EQ(ARG_TYPE_NONE, type);
arg_freeContent(self);
EXPECT_EQ(pikaMemNow(), 0);
}
TEST(content, next) {
uint8_t* c1 = content_init("c1", ARG_TYPE_NONE, NULL, 0, NULL);
uint8_t* c2 = content_init("c2", ARG_TYPE_NONE, NULL, 0, c1);
uint8_t* c3 = content_getNext(c2);
ASSERT_EQ(c3, c1);
arg_freeContent(c1);
arg_freeContent(c2);
EXPECT_EQ(pikaMemNow(), 0);
}
TEST(content, setNext) {
uint8_t* c1 = content_init("c1", ARG_TYPE_NONE, NULL, 0, NULL);
content_setNext(c1, content_init("c2", ARG_TYPE_NONE, NULL, 0, NULL));
uint8_t* c2 = content_getNext(c1);
Hash c2NameHash = content_getNameHash(c2);
EXPECT_EQ(c2NameHash, hash_time33("c2"));
arg_freeContent(c1);
arg_freeContent(c2);
EXPECT_EQ(pikaMemNow(), 0);
}
#endif
| 29.038835 | 74 | 0.67235 |
499663b2dfd9a254ef35277d5d85dc6b8003a24e | 818 | cpp | C++ | cyclic_fn.cpp | zaimoni/Iskandria | b056d2ba359b814db02aab42eba8d5f7f5ca7a1a | [
"BSL-1.0"
] | 2 | 2019-11-23T12:35:49.000Z | 2022-02-10T08:27:54.000Z | cyclic_fn.cpp | zaimoni/Iskandria | b056d2ba359b814db02aab42eba8d5f7f5ca7a1a | [
"BSL-1.0"
] | 8 | 2019-11-15T08:13:48.000Z | 2020-04-29T00:35:42.000Z | cyclic_fn.cpp | zaimoni/Iskandria | b056d2ba359b814db02aab42eba8d5f7f5ca7a1a | [
"BSL-1.0"
] | null | null | null | // cyclic_fn.cpp
// pure test driver
#include "cyclic_fn.hpp"
#include <functional>
// example build line (have to copy from *.hpp to *.cpp or else main not seen
// If doing INFORM-based debugging
// g++ -std=c++11 -ocyclic_fn.exe cyclic_fn.cpp -Llib/host.isk -lz_log_adapter -lz_stdio_log -lz_format_util
#include "test_driver.h"
int main(int argc, char* argv[])
{ // parse options
char buf[100];
STRING_LITERAL_TO_STDOUT("starting main\n");
const signed char tmp[2] = {1,-1};
zaimoni::math::mod_n::cyclic_fn_enumerated<2,signed char> test(tmp);
INFORM(test(0));
INFORM(test(1));
INFORM(test(2));
std::function<signed char (uintmax_t)> test_fn = test;
INFORM(test_fn(0));
INFORM(test_fn(1));
INFORM(test_fn(2));
STRING_LITERAL_TO_STDOUT("tests finished\n");
}
| 23.371429 | 109 | 0.679707 |
499ad331e198929ca8c0116e353dc02b3e64887b | 14,774 | cpp | C++ | src/program_options.cpp | WenbinHou/xcp-old | e1efbebe625e379189d82b4641e575849fbcf628 | [
"MIT"
] | 1 | 2020-09-10T19:50:38.000Z | 2020-09-10T19:50:38.000Z | src/program_options.cpp | WenbinHou/xcp-old | e1efbebe625e379189d82b4641e575849fbcf628 | [
"MIT"
] | null | null | null | src/program_options.cpp | WenbinHou/xcp-old | e1efbebe625e379189d82b4641e575849fbcf628 | [
"MIT"
] | 1 | 2020-07-14T05:10:22.000Z | 2020-07-14T05:10:22.000Z | #include "common.h"
//==============================================================================
// struct host_path
//==============================================================================
bool xcp::host_path::parse(const std::string& value)
{
// Handle strings like:
// "relative"
// "relative/subpath"
// "/absolute/path"
// "C:" (on Windows)
// "C:\" (on Windows)
// "C:/" (on Windows)
// "C:\absolute\path" (on Windows)
// "C:/absolute\path" (on Windows)
// "relative\subpath"
// "hostname:/"
// "hostname:/absolute"
// "127.0.0.1:C:"
// "1.2.3.4:C:\"
// "1.2.3.4:C:/"
// "[::1]:C:\absolute"
// "[1:2:3:4:5:6:7:8]:C:/absolute"
//
// NOTE:
// Remote path MUST be absolute
// Local path might be absolute or relative
// See:
// https://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
// https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address
// NOTE: re_valid_hostname matches a superset of valid IPv4
static std::regex* __re = nullptr;
if (__re == nullptr) {
const std::string re_valid_hostname = R"((?:(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*(?:[A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])))";
const std::string re_valid_ipv6 = R"((?:\[(?:(?:[0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,7}:|(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}|(?:[0-9a-fA-F]{1,4}:){1,4}(?::[0-9a-fA-F]{1,4}){1,3}|(?:[0-9a-fA-F]{1,4}:){1,3}(?::[0-9a-fA-F]{1,4}){1,4}|(?:[0-9a-fA-F]{1,4}:){1,2}(?::[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:(?:(?::[0-9a-fA-F]{1,4}){1,6})|:(?:(?::[0-9a-fA-F]{1,4}){1,7}|:)|::(?:[Ff]{4}(?::0{1,4})?:)?(?:(?:25[0-5]|(?:2[0-4]|1?[0-9])?[0-9])\.){3,3}(?:25[0-5]|(?:2[0-4]|1?[0-9])?[0-9])|(?:[0-9a-fA-F]{1,4}:){1,4}:(?:(?:25[0-5]|(?:2[0-4]|1?[0-9])?[0-9])\.){3,3}(?:25[0-5]|(?:2[0-4]|1?[0-9])?[0-9]))\]))";
const std::string re_valid_host = "(?:" + re_valid_hostname + "|" + re_valid_ipv6 + ")";
const std::string re_valid_host_path = "^(?:(?:([^@:]+)@)?(" + re_valid_host + "):)?((?:^.+)|(?:.*))$";
__re = new std::regex(re_valid_host_path, std::regex::optimize);
}
if (value.empty()) return false;
//
// Special handling for Windows driver letters (local path)
//
#if PLATFORM_WINDOWS || PLATFORM_CYGWIN
if (value.size() >= 2 && value[1] == ':') {
if ((value[0] >= 'A' && value[0] <= 'Z') || (value[0] >= 'a' && value[0] <= 'z')) {
if (value.size() == 2 || value[2] == '/' || value[2] == '\\') {
user.reset();
host.reset();
path = value;
return true;
}
}
}
#elif PLATFORM_LINUX
#else
# error "Unknown platform"
#endif
std::smatch match;
if (!std::regex_match(value, match, *__re)) {
return false;
}
{
// The user part
std::string tmp(match[1].str());
if (tmp.empty())
user.reset();
else
user= std::move(tmp);
}
{
// The host part
// NOTE: If host is IPv6 surrounded by '[' ']', DO NOT trim the beginning '[' and ending ']'
std::string tmp(match[2].str());
if (tmp.empty())
host.reset();
else
host = std::move(tmp);
}
{
path = match[3].str();
if (path.empty()) {
if (!host.has_value()) {
return false;
}
else {
path = "~";
}
}
}
return true;
}
//==============================================================================
// struct base_program_options
//==============================================================================
void xcp::base_program_options::add_options(CLI::App& app)
{
app.add_flag(
"-V,--version",
[&](const size_t /*count*/) {
printf("Version %d.%d.%d\nGit branch %s commit %s\n",
XCP_VERSION_MAJOR, XCP_VERSION_MINOR, XCP_VERSION_PATCH,
TEXTIFY(XCP_GIT_BRANCH), TEXTIFY(XCP_GIT_COMMIT_HASH));
exit(0);
},
"Print version and exit");
app.add_flag(
"-q,--quiet",
[&](const size_t count) { this->arg_verbosity -= static_cast<int>(count); },
"Be more quiet");
app.add_flag(
"-v,--verbose",
[&](const size_t count) { this->arg_verbosity += static_cast<int>(count); },
"Be more verbose");
}
bool xcp::base_program_options::post_process()
{
// Set verbosity
infra::set_logging_verbosity(this->arg_verbosity);
return true;
}
//==============================================================================
// struct xcp_program_options
//==============================================================================
void xcp::xcp_program_options::add_options(CLI::App& app)
{
base_program_options::add_options(app);
CLI::Option* opt_port = app.add_option(
"-P,-p,--port",
this->arg_port,
"Server portal port to connect to");
opt_port->type_name("<port>");
CLI::Option* opt_from = app.add_option(
"from",
this->arg_from_path,
"Copy from this path");
opt_from->type_name("<from>");
opt_from->required();
CLI::Option* opt_to = app.add_option(
"to",
this->arg_to_path,
"Copy to this path");
opt_to->type_name("<to>");
opt_to->required();
[[maybe_unused]]
CLI::Option* opt_recursive = app.add_flag(
"-r,--recursive",
this->arg_recursive,
"Transfer a directory recursively");
CLI::Option* opt_user = app.add_option(
"-u,--user",
this->arg_user,
"Relative to this user's home directory on server side");
opt_user->type_name("<user>");
CLI::Option* opt_block = app.add_option(
"-B,--block",
this->arg_transfer_block_size,
"Transfer block size");
opt_block->type_name("<size>");
opt_block->transform(CLI::AsSizeValue(false));
}
bool xcp::xcp_program_options::post_process()
{
if (!base_program_options::post_process()) {
return false;
}
//----------------------------------------------------------------
// arg_from_path, arg_to_path
//----------------------------------------------------------------
if (arg_from_path.is_remote()) {
ASSERT(arg_from_path.host.has_value());
LOG_DEBUG("Copy from remote host {} path {}", arg_from_path.host.value(), arg_from_path.path);
}
else {
LOG_DEBUG("Copy from local path {}", arg_from_path.path);
}
if (arg_to_path.is_remote()) {
ASSERT(arg_to_path.host.has_value());
LOG_DEBUG("Copy to remote host {} path {}", arg_to_path.host.value(), arg_to_path.path);
}
else {
LOG_DEBUG("Copy to local path {}", arg_to_path.path);
}
if (arg_from_path.is_remote() && arg_to_path.is_remote()) {
LOG_ERROR("Can't copy between remote hosts");
return false;
}
else if (arg_from_path.is_remote()) {
is_from_server_to_client = true;
server_portal.host = arg_from_path.host.value();
}
else if (arg_to_path.is_remote()) {
is_from_server_to_client = false;
server_portal.host = arg_to_path.host.value();
}
else {
LOG_ERROR("Copy from local to local is to be supported"); // TODO
return false;
}
//----------------------------------------------------------------
// arg_port
//----------------------------------------------------------------
if (arg_port.has_value()) {
if (arg_port.value() == 0) {
LOG_ERROR("Server portal port 0 is invalid");
return false;
}
}
else { // !arg_portal->port.has_value()
arg_port = program_options_defaults::SERVER_PORTAL_PORT;
}
server_portal.port = arg_port.value();
LOG_DEBUG("Server portal: {}", server_portal.to_string());
if (!server_portal.resolve()) {
LOG_ERROR("Can't resolve specified server portal: {}", server_portal.to_string());
return false;
}
else {
for (const infra::tcp_sockaddr& addr : server_portal.resolved_sockaddrs) {
LOG_DEBUG(" Candidate server portal endpoint: {}", addr.to_string());
}
}
//----------------------------------------------------------------
// arg_recursive
//----------------------------------------------------------------
if (arg_recursive) {
LOG_DEBUG("Transfer recursively if source is a directory");
}
//----------------------------------------------------------------
// arg_user
//----------------------------------------------------------------
bool got_user = false;
if (arg_user.has_value()) {
server_user.user_name = arg_user.value();
got_user = true;
}
else {
if (arg_from_path.is_remote()) {
ASSERT(is_from_server_to_client);
if (arg_from_path.user.has_value()) {
server_user.user_name = arg_from_path.user.value();
got_user = true;
}
}
else if (arg_to_path.is_remote()) {
ASSERT(!is_from_server_to_client);
if (arg_to_path.user.has_value()) {
server_user.user_name = arg_to_path.user.value();
got_user = true;
}
}
}
if (!got_user) {
if (infra::get_user_name(server_user)) {
got_user = true;
}
}
if (got_user) {
LOG_TRACE("Use this user for server side: {}", server_user.to_string());
}
else {
server_user = { };
LOG_WARN("Can't get user. Use no user for server side");
}
//----------------------------------------------------------------
// arg_transfer_block_size
//----------------------------------------------------------------
if (arg_transfer_block_size.has_value()) {
if (arg_transfer_block_size.value() > program_options_defaults::MAX_TRANSFER_BLOCK_SIZE) {
LOG_WARN("Transfer block size is too large: {}. Set to MAX_TRANSFER_BLOCK_SIZE: {}",
arg_transfer_block_size.value(), program_options_defaults::MAX_TRANSFER_BLOCK_SIZE);
arg_transfer_block_size = program_options_defaults::MAX_TRANSFER_BLOCK_SIZE;
}
}
else {
arg_transfer_block_size = 0;
}
if (arg_transfer_block_size.value() == 0) {
LOG_TRACE("Transfer block size: automatic tuning");
}
else if (arg_transfer_block_size.value() < 1024 * 64) {
LOG_WARN("Transfer block size {} is too small. You may encounter bad performance!", arg_transfer_block_size.value());
}
else {
LOG_TRACE("Transfer block size: {}", arg_transfer_block_size.value());
}
return true;
}
//==============================================================================
// struct xcpd_program_options
//==============================================================================
void xcp::xcpd_program_options::add_options(CLI::App& app)
{
base_program_options::add_options(app);
CLI::Option* opt_portal = app.add_option(
"-P,-p,--portal",
this->arg_portal,
"Server portal endpoint to bind and listen");
opt_portal->type_name("<endpoint>");
CLI::Option* opt_channel = app.add_option(
"-C,--channel",
this->arg_channels,
"Server channels to bind and listen for transportation");
opt_channel->type_name("<endpoint>");
}
bool xcp::xcpd_program_options::post_process()
{
if (!base_program_options::post_process()) {
return false;
}
//----------------------------------------------------------------
// arg_portal
//----------------------------------------------------------------
if (!arg_portal.has_value()) {
arg_portal = infra::tcp_endpoint();
arg_portal->host = program_options_defaults::SERVER_PORTAL_HOST;
LOG_INFO("Server portal is not specified, use default host {}", program_options_defaults::SERVER_PORTAL_HOST);
}
if (arg_portal->port.has_value()) {
if (arg_portal->port.value() == 0) {
LOG_WARN("Server portal binds to a random port");
}
else {
LOG_TRACE("Server portal binds to port {}", arg_portal->port.value());
}
}
else { // !arg_portal->port.has_value()
arg_portal->port = program_options_defaults::SERVER_PORTAL_PORT;
LOG_TRACE("Server portal binds to default port {}", arg_portal->port.value());
}
LOG_INFO("Server portal endpoint: {}", arg_portal->to_string());
if (!arg_portal->resolve()) {
LOG_ERROR("Can't resolve specified portal: {}", arg_portal->to_string());
return false;
}
else {
for (const infra::tcp_sockaddr& addr : arg_portal->resolved_sockaddrs) {
LOG_DEBUG(" Candidate server portal endpoint: {}", addr.to_string());
}
}
//----------------------------------------------------------------
// arg_channels
//----------------------------------------------------------------
total_channel_repeats_count = 0;
if (arg_channels.empty()) {
// Reuse portal as channel
// Default arg_portal->repeats if not specified by user
if (!arg_portal->repeats.has_value()) {
arg_portal->repeats = program_options_defaults::SERVER_CHANNEL_REPEATS;
}
total_channel_repeats_count += arg_portal->repeats.value();
LOG_INFO("Server channels are not specified, reuse portal as channel: {}", arg_portal->to_string());
}
for (infra::tcp_endpoint& ep : arg_channels) {
if (!ep.port.has_value()) {
ep.port = static_cast<uint16_t>(0);
}
if (!ep.repeats.has_value()) {
ep.repeats = static_cast<size_t>(1);
}
ASSERT(ep.repeats.value() > 0);
LOG_INFO("Server channel: {}", ep.to_string());
if (!ep.resolve()) {
LOG_ERROR("Can't resolve specified channel: {}", ep.to_string());
return false;
}
else {
for (const infra::tcp_sockaddr& addr : ep.resolved_sockaddrs) {
LOG_DEBUG(" Candidate server channel endpoint: {}", addr.to_string());
}
}
total_channel_repeats_count += ep.repeats.value();
}
LOG_INFO("Total server channels (including repeats): {}", total_channel_repeats_count);
return true;
}
| 33.501134 | 690 | 0.500271 |
499b39c54b8f164f0888e1304f52c52505ed1694 | 3,169 | cpp | C++ | include/lak/stream_util.cpp | LAK132/NetworkMaker | 0ad1ba2488d80e8bba0a710e5d9984d7c5cc0739 | [
"MIT"
] | null | null | null | include/lak/stream_util.cpp | LAK132/NetworkMaker | 0ad1ba2488d80e8bba0a710e5d9984d7c5cc0739 | [
"MIT"
] | null | null | null | include/lak/stream_util.cpp | LAK132/NetworkMaker | 0ad1ba2488d80e8bba0a710e5d9984d7c5cc0739 | [
"MIT"
] | 1 | 2020-08-16T16:27:58.000Z | 2020-08-16T16:27:58.000Z | /*
MIT License
Copyright (c) 2018 Lucas Kleiss (LAK132)
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 "stream_util.h"
void readFile(const string& src, string* dst)
{
*dst = "";
ifstream strm(src.c_str(), std::ios::binary|ifstream::in);
if(!strm.is_open())
{
LERRLOG("Failed to open file " << src.c_str() << endl);
return;
}
streampos start = strm.tellg();
size_t size = 0;
string str = ""; str += EOF;
skipOneS(strm, str) ++size; // I'm not sorry
strm.clear();
strm.seekg(start);
dst->reserve(size);
for(char c = strm.get(); strm >> c;)
*dst += c;
}
void readFile(string&& src, string* dst)
{
readFile(src, dst);
}
string readFile(const string& src)
{
string str;
readFile(src, &str);
return str;
}
string readFile(string&& src)
{
string str;
readFile(src, &str);
return str;
}
// string getString(istream& strm, const char terminator)
// {
// LDEBUG(std::endl);
// string str = "";
// LDEBUG(std::endl);
// char c = strm.get();
// LDEBUG(std::endl);
// while((c = strm.get()) != terminator && strm.good())
// {
// LDEBUG(c << std::endl);
// if(c == '\\')
// {
// switch(strm.get())
// {
// case '\\': str += '\\'; break;
// case '\'': str += '\''; break;
// case '\"': str += '\"'; break;
// // case 'b': str += "\\b"; break;
// case 'f': str += '\f'; break;
// case 'n': str += '\n'; break;
// case 'r': str += '\r'; break;
// case 't': str += '\t'; break;
// case 'u': {
// str += "\\u";
// str += strm.get();
// str += strm.get();
// str += strm.get();
// str += strm.get();
// } break;
// default: {
// str += '\\';
// str += strm.get();
// } break;
// }
// }
// else
// str += c;
// }
// return str;
// } | 30.180952 | 78 | 0.532029 |
499ba4b3bea193324f9df87d27b30049b4c8019e | 3,121 | hpp | C++ | hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp | dbac/jdk8 | abfce42ff6d4b8b77d622157519ecd211ba0aa8f | [
"MIT"
] | 1 | 2020-12-26T04:52:15.000Z | 2020-12-26T04:52:15.000Z | hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp | dbac/jdk8 | abfce42ff6d4b8b77d622157519ecd211ba0aa8f | [
"MIT"
] | 1 | 2020-12-26T04:57:19.000Z | 2020-12-26T04:57:19.000Z | hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp | dbac/jdk8 | abfce42ff6d4b8b77d622157519ecd211ba0aa8f | [
"MIT"
] | 1 | 2021-12-06T01:13:18.000Z | 2021-12-06T01:13:18.000Z | /*
* Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CMSOOPCLOSURES_INLINE_HPP
#define SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CMSOOPCLOSURES_INLINE_HPP
#include "gc_implementation/concurrentMarkSweep/cmsOopClosures.hpp"
#include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp"
#include "oops/oop.inline.hpp"
// Trim our work_queue so its length is below max at return
inline void Par_MarkRefsIntoAndScanClosure::trim_queue(uint max) {
while (_work_queue->size() > max) {
oop newOop;
if (_work_queue->pop_local(newOop)) {
assert(newOop->is_oop(), "Expected an oop");
assert(_bit_map->isMarked((HeapWord*)newOop),
"only grey objects on this stack");
// iterate over the oops in this oop, marking and pushing
// the ones in CMS heap (i.e. in _span).
newOop->oop_iterate(&_par_pushAndMarkClosure);
}
}
}
// CMSOopClosure and CMSoopsInGenClosure are duplicated,
// until we get rid of OopsInGenClosure.
inline void CMSOopClosure::do_klass(Klass* k) { do_klass_nv(k); }
inline void CMSOopsInGenClosure::do_klass(Klass* k) { do_klass_nv(k); }
inline void CMSOopClosure::do_klass_nv(Klass* k) {
ClassLoaderData* cld = k->class_loader_data();
do_class_loader_data(cld);
}
inline void CMSOopsInGenClosure::do_klass_nv(Klass* k) {
ClassLoaderData* cld = k->class_loader_data();
do_class_loader_data(cld);
}
inline void CMSOopClosure::do_class_loader_data(ClassLoaderData* cld) {
assert(_klass_closure._oop_closure == this, "Must be");
bool claim = true; // Must claim the class loader data before processing.
cld->oops_do(_klass_closure._oop_closure, &_klass_closure, claim);
}
inline void CMSOopsInGenClosure::do_class_loader_data(ClassLoaderData* cld) {
assert(_klass_closure._oop_closure == this, "Must be");
bool claim = true; // Must claim the class loader data before processing.
cld->oops_do(_klass_closure._oop_closure, &_klass_closure, claim);
}
#endif // SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CMSOOPCLOSURES_INLINE_HPP
| 40.532468 | 82 | 0.758731 |
499c9cd941a0da86a8ba6bfb30de25722b42eba3 | 42 | cpp | C++ | 4781_candyshop/4781.cpp | YouminHa/acmicpc | dddb457a3cfb03df34db0ed07680ac1a7be6cdd4 | [
"MIT"
] | null | null | null | 4781_candyshop/4781.cpp | YouminHa/acmicpc | dddb457a3cfb03df34db0ed07680ac1a7be6cdd4 | [
"MIT"
] | null | null | null | 4781_candyshop/4781.cpp | YouminHa/acmicpc | dddb457a3cfb03df34db0ed07680ac1a7be6cdd4 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <iostream>
| 7 | 19 | 0.666667 |
499d07f1b188017bf2b057e9f410fe5336e1068a | 4,602 | cpp | C++ | src/world/chunk.cpp | AlexDiru/minecraft-weekend | 8ddbef27f8501bff306c83ae11fff971cb3bb47a | [
"MIT"
] | null | null | null | src/world/chunk.cpp | AlexDiru/minecraft-weekend | 8ddbef27f8501bff306c83ae11fff971cb3bb47a | [
"MIT"
] | null | null | null | src/world/chunk.cpp | AlexDiru/minecraft-weekend | 8ddbef27f8501bff306c83ae11fff971cb3bb47a | [
"MIT"
] | null | null | null | #include "../state.h"
#include "chunk.h"
#include "world.h"
#include "light.h"
void chunk_init(struct Chunk *self, struct World *world, ivec3s offset) {
memset(self, 0, sizeof(struct Chunk));
self->world = world;
self->offset = offset;
self->position = glms_ivec3_mul(offset, CHUNK_SIZE);
self->data = (u64*)calloc(1, CHUNK_VOLUME * sizeof(u64));
self->mesh = chunkmesh_create(self);
}
void chunk_destroy(struct Chunk *self) {
free(self->data);
chunkmesh_destroy(self->mesh);
}
// returns the chunks that border the specified chunk position
static void chunk_get_bordering_chunks(struct Chunk *self, ivec3s pos, struct Chunk *dest[6]) {
size_t i = 0;
if (pos.x == 0) {
dest[i++] = world_get_chunk(self->world, glms_ivec3_add(self->offset, (ivec3s) {{ -1, 0, 0 }}));
}
if (pos.y == 0) {
dest[i++] = world_get_chunk(self->world, glms_ivec3_add(self->offset, (ivec3s) {{ 0, -1, 0 }}));
}
if (pos.z == 0) {
dest[i++] = world_get_chunk(self->world, glms_ivec3_add(self->offset, (ivec3s) {{ 0, 0, -1 }}));
}
if (pos.x == (CHUNK_SIZE.x - 1)) {
dest[i++] = world_get_chunk(self->world, glms_ivec3_add(self->offset, (ivec3s) {{ 1, 0, 0 }}));
}
if (pos.x == (CHUNK_SIZE.y - 1)) {
dest[i++] = world_get_chunk(self->world, glms_ivec3_add(self->offset, (ivec3s) {{ 0, 1, 0 }}));
}
if (pos.z == (CHUNK_SIZE.z - 1)) {
dest[i++] = world_get_chunk(self->world, glms_ivec3_add(self->offset, (ivec3s) {{ 0, 0, 1 }}));
}
}
// MUST be run once a chunk has completed generating
void chunk_after_generate(Chunk *self) {
chunk_heightmap_recalculate(self);
light_apply(self);
}
// MUST be run after data inside of a chunk is modified
void chunk_on_modify(
Chunk *self, ivec3s pos,
u64 prev, u64 data) {
self->mesh->flags.dirty = true;
enum BlockId prev_block = chunk_data_to_block(prev),
data_block = chunk_data_to_block(data);
u32 prev_light = chunk_data_to_light(prev),
light = chunk_data_to_light(data);
struct Block block_p = BLOCKS[prev_block], block = BLOCKS[data_block];
if (data_block != prev_block) {
ivec3s pos_w = glms_ivec3_add(self->position, pos);
if (block_p.can_emit_light) {
light_remove(self->world, pos_w);
}
if (block.can_emit_light) {
torchlight_add(self->world, pos_w, block.get_torchlight(self->world, pos_w));
}
if (!self->flags.generating) {
if (block.transparent) {
world_heightmap_recalculate(self->world, (ivec2s) {{ pos_w.x, pos_w.z }});
// propagate lighting through this block
light_update(self->world, pos_w);
} else {
world_heightmap_update(self->world, pos_w);
// remove light at this block
light_remove(self->world, pos_w);
}
}
self->count += (data_block == AIR ? -1 : 1);
}
self->flags.empty = self->count == 0;
// mark any chunks that could have been affected as dirty
if ((data_block != prev_block || light != prev_light)
&& chunk_on_bounds(pos)) {
struct Chunk *neighbors[6] = { NULL };
chunk_get_bordering_chunks(self, pos, neighbors);
for (size_t i = 0; i < 6; i++) {
if (neighbors[i] != NULL) {
neighbors[i]->mesh->flags.dirty = true;
}
}
}
}
void chunk_prepare(Chunk *self) {
if (self->flags.empty) {
return;
}
chunkmesh_prepare_render(self->mesh);
}
void chunk_render(Chunk *self, enum ChunkMeshPart part) {
if (self->flags.empty) {
return;
}
chunkmesh_render(self->mesh, part);
}
void chunk_update(Chunk *self) {
// Depth sort the transparent mesh if
// (1) the player is inside of this chunk and their block position changed
// (2) the player has moved chunks AND this chunk is close
PositionComponent *c_position = self->world->componentManager->getPositionComponent(self->world->entity_view);
bool within_distance = glms_ivec3_norm(glms_ivec3_sub(self->offset, c_position->offset)) < 4;
self->mesh->flags.depth_sort =
(!ivec3scmp(self->offset, c_position->offset) && c_position->block_changed) ||
(c_position->offset_changed && within_distance);
// Persist depth sort data if the player is within depth sort distance of this chunk
chunkmesh_set_persist(self->mesh, within_distance);
}
void chunk_tick(Chunk *self) {
} | 31.520548 | 114 | 0.611691 |
49a7dbc2bdc7d142b3de9ff2cfce31e67f3a35fd | 645 | cpp | C++ | Source/mods.cpp | HaikuArchives/Rez | db5e7e1775a379e1e54bc17012047d92ec782202 | [
"BSD-4-Clause"
] | 1 | 2016-09-12T19:04:30.000Z | 2016-09-12T19:04:30.000Z | Source/mods.cpp | HaikuArchives/Rez | db5e7e1775a379e1e54bc17012047d92ec782202 | [
"BSD-4-Clause"
] | null | null | null | Source/mods.cpp | HaikuArchives/Rez | db5e7e1775a379e1e54bc17012047d92ec782202 | [
"BSD-4-Clause"
] | null | null | null | #include "mods.h"
#include <cstdio>
/*************************************************************************
* Modifications to the standard REZ distribution.
* Copyright (c) 2000, Tim Vernum
* This code may be freely used for any purpose
*************************************************************************/
bool gListDepend = false ;
bool gParseOnly = false ;
void DependFile( const char * file )
{
if( gListDepend )
{
printf( "\t%s \\\n", file ) ;
}
}
void StartDepend( const char * out )
{
if( gListDepend )
{
printf( "%s : \\\n", out ) ;
}
}
void EndDepend( void )
{
if( gListDepend )
{
printf( "\n" ) ;
}
}
| 17.432432 | 75 | 0.472868 |
49acf651e55490e269962b2b747a489017641961 | 687 | cc | C++ | chrome/browser/component_updater/component_updater_utils.cc | xzhan96/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-01-07T18:51:03.000Z | 2021-01-07T18:51:03.000Z | chrome/browser/component_updater/component_updater_utils.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/component_updater/component_updater_utils.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/component_updater/component_updater_utils.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "build/build_config.h"
#if defined(OS_WIN)
#include "chrome/installer/util/install_util.h"
#endif // OS_WIN
namespace component_updater {
bool IsPerUserInstall() {
#if defined(OS_WIN)
base::FilePath exe_path;
PathService::Get(base::FILE_EXE, &exe_path);
return InstallUtil::IsPerUserInstall(exe_path);
#else
return true;
#endif
}
} // namespace component_updater
| 25.444444 | 73 | 0.767103 |
49adab898428491e17f74e777ed5d051fec0f9bb | 1,300 | cpp | C++ | Algorithms/Sorting/quick_sort.cpp | WajahatSiddiqui/workspace | 7c6172a76d7cd178ea0c0cb9767ceaaed783545a | [
"Apache-2.0"
] | 1 | 2021-03-19T10:57:21.000Z | 2021-03-19T10:57:21.000Z | Algorithms/Sorting/quick_sort.cpp | WajahatSiddiqui/Datastructures-and-Algorithms | 7c6172a76d7cd178ea0c0cb9767ceaaed783545a | [
"Apache-2.0"
] | 1 | 2015-03-15T17:49:52.000Z | 2015-03-15T17:51:38.000Z | Algorithms/Sorting/quick_sort.cpp | WajahatSiddiqui/Datastructures-and-Algorithms | 7c6172a76d7cd178ea0c0cb9767ceaaed783545a | [
"Apache-2.0"
] | null | null | null | #include<iostream>
using namespace std;
// Best case: O(nlogn)
// Avg. case: O(nlogn)
// Worst case: O(n^2)
void quick_sort(int A[], int low, int high);
int partition(int A[], int low, int high);
int main() {
int A[] = {5, 6, 8, 1, -1, 0, 11, 100, -5, 0, 1, 0, 6, 1, 2, 3, 5, 10000};
int size = sizeof(A)/sizeof(int);
cout<<"Size = "<<size<<endl;
cout<<"Input Array: \n";
for (int i = 0; i < size; i++) {
cout<<A[i]<<" ";
}
quick_sort(A, 0, size-1);
cout<<"\nQuick Sorted Array: \n";
for (int i = 0; i < size; i++) {
cout<<A[i]<<" ";
}
cout<<endl;
return 0;
}
void swap(int *n1, int *n2) {
int tmp = *n1;
*n1 = *n2;
*n2 = tmp;
}
// low represents starting index
// high represents size-1, ending index
void quick_sort(int A[], int low, int high) {
if (low < high) {
// Partition the array based on some pivot
int pivot = partition(A, low, high);
// Decompose and sort recursively
quick_sort(A, low, pivot-1);
quick_sort(A, pivot+1, high);
}
}
int partition(int A[], int low, int high) {
int pivot = A[high];
int i = low - 1;
for (int j = low; j <= high-1; j++) {
if (A[j] <= pivot) {
i++;
swap(&A[i], &A[j]);
}
}
swap(&A[i+1], &A[high]);
return i+1;
}
| 22.413793 | 75 | 0.520769 |
49b39f86e698f389bf7e606e73ce28ee95f020c2 | 487 | hpp | C++ | SoftRender/Common.hpp | pw1316/SoftRender | da4a87da2aab1234543a48524a8274d6f5550652 | [
"MIT"
] | null | null | null | SoftRender/Common.hpp | pw1316/SoftRender | da4a87da2aab1234543a48524a8274d6f5550652 | [
"MIT"
] | null | null | null | SoftRender/Common.hpp | pw1316/SoftRender | da4a87da2aab1234543a48524a8274d6f5550652 | [
"MIT"
] | null | null | null | #pragma once
#include "stdafx.h"
inline PWfloat quickInvSqrt(PWfloat number)
{
PWlong i;
PWfloat x2, y;
const PWfloat threehalfs = 1.5f;
x2 = number * 0.5f;
y = number;
i = *(PWlong *)&y;// evil floating point bit level hacking
i = 0x5f3759df - (i >> 1);// what the fuck?
y = *(PWlong *)&i;
y = y * (threehalfs - (x2 * y * y)); // 1st iteration
y = y * (threehalfs - (x2 * y * y)); // 2nd iteration, this can be removed
return 1.0f / y;
} | 28.647059 | 80 | 0.566735 |
49b41afb9d64fe942c0e7c9d0cfbf4b64821414a | 358 | cpp | C++ | Graph/main.cpp | yanelox/ilab_2year | 4597b2fbc498a816368101283d2749ac7bbf670a | [
"MIT"
] | null | null | null | Graph/main.cpp | yanelox/ilab_2year | 4597b2fbc498a816368101283d2749ac7bbf670a | [
"MIT"
] | null | null | null | Graph/main.cpp | yanelox/ilab_2year | 4597b2fbc498a816368101283d2749ac7bbf670a | [
"MIT"
] | 1 | 2021-10-11T19:18:37.000Z | 2021-10-11T19:18:37.000Z | #include "graph.cpp"
int main ()
{
graph::graph_ <int> G {};
if (G.input() == 0)
{
std::cout << "Incorrect input\n";
return 0;
}
// std::cout << G;
int res = G.colorize();
// G.recolorize();
if (res == 1)
G.print_colors(std::cout);
else
std::cout << "Error: non-bipartite graph\n";
} | 14.916667 | 52 | 0.472067 |
49b4f616bd2efeb24568570d3030bb7c4c70f1ec | 6,582 | cpp | C++ | plaidml/bridge/openvino/plaidml_util.cpp | hfp/plaidml | c86852a910e68181781b3045f5a306d2f41a775f | [
"Apache-2.0"
] | null | null | null | plaidml/bridge/openvino/plaidml_util.cpp | hfp/plaidml | c86852a910e68181781b3045f5a306d2f41a775f | [
"Apache-2.0"
] | 65 | 2020-08-24T07:41:09.000Z | 2021-07-19T09:13:49.000Z | plaidml/bridge/openvino/plaidml_util.cpp | Flex-plaidml-team/plaidml | 1070411a87b3eb3d94674d4d041ed904be3e7d87 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "plaidml_util.hpp"
#include "ngraph/validation_util.hpp"
#include "plaidml/edsl/edsl.h"
using namespace plaidml; // NOLINT[build/namespaces]
using namespace InferenceEngine; // NOLINT[build/namespaces]
namespace PlaidMLPlugin {
ngraph::AxisSet get_axis_set_from_constant_operand(size_t operand_idx, ngraph::Node* layer, size_t rank_override) {
auto* axis_ngraph_op = ngraph::as_type<ngraph::op::Constant>(layer->get_input_node_ptr(operand_idx));
if (axis_ngraph_op) {
auto const_data = axis_ngraph_op->cast_vector<int64_t>();
auto input_rank = layer->get_input_partial_shape(0).rank();
if (rank_override > 0) {
// If a programmer has specifically set the rank, use that value instead.
// This is for cases like unsqueeze, where axes aree given relative to a destination tensor of higher rank than
// the input tensor
input_rank = rank_override;
}
auto normalized_axes = ngraph::normalize_axes(layer->get_friendly_name(), const_data, input_rank);
return ngraph::AxisSet{normalized_axes};
} else {
THROW_IE_EXCEPTION << "Dynamic axis not currently supported by PlaidML plugin";
}
}
ngraph::AxisVector get_axis_vector_from_constant_operand(size_t operand_idx, ngraph::Node* layer) {
auto* axis_ngraph_op = ngraph::as_type<ngraph::op::Constant>(layer->get_input_node_ptr(operand_idx));
if (axis_ngraph_op) {
auto const_data = axis_ngraph_op->cast_vector<int64_t>();
auto input_rank = layer->get_input_partial_shape(0).rank();
auto normalized_axes = ngraph::normalize_axes(layer->get_friendly_name(), const_data, input_rank);
return ngraph::AxisVector{normalized_axes};
} else {
THROW_IE_EXCEPTION << "Dynamic axis not currently supported by PlaidML plugin";
}
}
plaidml::DType to_plaidml(const InferenceEngine::Precision& precision) {
switch (precision) {
case InferenceEngine::Precision::FP16:
return plaidml::DType::FLOAT16;
case InferenceEngine::Precision::FP32:
return plaidml::DType::FLOAT32;
case InferenceEngine::Precision::I8:
return plaidml::DType::INT8;
case InferenceEngine::Precision::I16:
return plaidml::DType::INT16;
case InferenceEngine::Precision::I32:
return plaidml::DType::INT32;
case InferenceEngine::Precision::I64:
return plaidml::DType::INT64;
case InferenceEngine::Precision::U8:
return plaidml::DType::UINT8;
case InferenceEngine::Precision::U16:
return plaidml::DType::UINT16;
case InferenceEngine::Precision::U32:
return plaidml::DType::UINT8;
case InferenceEngine::Precision::U64:
return plaidml::DType::UINT16;
case InferenceEngine::Precision::BOOL:
return plaidml::DType::BOOLEAN;
default:
// TODO: Verify these are the unsupported types
THROW_IE_EXCEPTION << "Unsupported element type";
}
}
plaidml::DType to_plaidml(const ngraph::element::Type& type) {
switch (type) {
case ngraph::element::Type_t::f16:
return plaidml::DType::FLOAT16;
case ngraph::element::Type_t::f32:
return plaidml::DType::FLOAT32;
case ngraph::element::Type_t::f64:
return plaidml::DType::FLOAT64;
case ngraph::element::Type_t::i8:
return plaidml::DType::INT8;
case ngraph::element::Type_t::i16:
return plaidml::DType::INT16;
case ngraph::element::Type_t::i32:
return plaidml::DType::INT32;
case ngraph::element::Type_t::i64:
return plaidml::DType::INT64;
case ngraph::element::Type_t::u8:
return plaidml::DType::UINT8;
case ngraph::element::Type_t::u16:
return plaidml::DType::UINT16;
case ngraph::element::Type_t::u32:
return plaidml::DType::UINT32;
case ngraph::element::Type_t::u64:
return plaidml::DType::UINT64;
case ngraph::element::Type_t::boolean:
return plaidml::DType::BOOLEAN;
case ngraph::element::Type_t::u1:
case ngraph::element::Type_t::bf16:
case ngraph::element::Type_t::undefined:
case ngraph::element::Type_t::dynamic:
default:
// TODO: Verify these are the unsupported types
THROW_IE_EXCEPTION << "Unsupported element type";
}
}
plaidml::op::AutoPadMode to_plaidml(const ngraph::op::PadType& type) {
switch (type) {
case ngraph::op::PadType::EXPLICIT:
return plaidml::op::AutoPadMode::EXPLICIT;
case ngraph::op::PadType::SAME_LOWER:
return plaidml::op::AutoPadMode::SAME_LOWER;
case ngraph::op::PadType::SAME_UPPER:
return plaidml::op::AutoPadMode::SAME_UPPER;
case ngraph::op::PadType::VALID:
return plaidml::op::AutoPadMode::VALID;
default:
THROW_IE_EXCEPTION << "Unsupported autopad type";
}
}
plaidml::op::PadMode to_plaidml(const ngraph::op::PadMode& type) {
switch (type) {
case ngraph::op::PadMode::CONSTANT:
return plaidml::op::PadMode::CONSTANT;
case ngraph::op::PadMode::EDGE:
return plaidml::op::PadMode::EDGE;
case ngraph::op::PadMode::REFLECT:
return plaidml::op::PadMode::REFLECT;
case ngraph::op::PadMode::SYMMETRIC:
return plaidml::op::PadMode::SYMMETRIC;
default:
THROW_IE_EXCEPTION << "Unsupported autopad type";
}
}
ngraph::Shape get_shape_from_constant_operand(size_t operand_idx, ngraph::Node* layer) {
auto* shape_ngraph_op = ngraph::as_type<ngraph::op::Constant>(layer->get_input_node_ptr(operand_idx));
if (shape_ngraph_op) {
return shape_ngraph_op->get_shape_val();
} else {
THROW_IE_EXCEPTION << "Dynamic shapes not currently supported by PlaidML plugin";
}
}
ngraph::Coordinate get_coords_from_constant_operand(size_t operand_idx, ngraph::Node* layer) {
auto* coord_ngraph_op = ngraph::as_type<ngraph::op::Constant>(layer->get_input_node_ptr(operand_idx));
if (coord_ngraph_op) {
return coord_ngraph_op->get_coordinate_val();
} else {
THROW_IE_EXCEPTION << "Dynamic coordinates not currently supported by PlaidML plugin";
}
}
edsl::Tensor clip_activation(const std::string& func_name, bool should_clip, float clip, const edsl::Tensor& T) {
edsl::Tensor T_clipped;
if (should_clip) {
T_clipped = op::clip(T, edsl::Tensor(-clip), edsl::Tensor(clip));
} else {
T_clipped = T;
}
if (func_name == "relu") {
return op::relu(T_clipped);
} else if (func_name == "sigmoid") {
return op::sigmoid(T_clipped);
} else if (func_name == "tanh") {
return edsl::tanh(T_clipped);
} else {
THROW_IE_EXCEPTION << "Unsupported activation function";
}
}
} // namespace PlaidMLPlugin
| 36.977528 | 117 | 0.703434 |
49b6698b30758675eaa155abbf452b5e28098270 | 4,303 | cpp | C++ | src/SgTShaderProc.cpp | stephen-hqxu/SglToolkit | cce526b2392dc9470db6182340f79febb5118a94 | [
"MIT"
] | null | null | null | src/SgTShaderProc.cpp | stephen-hqxu/SglToolkit | cce526b2392dc9470db6182340f79febb5118a94 | [
"MIT"
] | null | null | null | src/SgTShaderProc.cpp | stephen-hqxu/SglToolkit | cce526b2392dc9470db6182340f79febb5118a94 | [
"MIT"
] | null | null | null | #include <SglToolkit/SgTShaderProc.h>
using namespace SglToolkit;
void SgTShaderProc::addShader(const GLenum type, const SgTstring path) {
//Determine which shader is that
int handleIndex = 1;
switch (type) {
case GL_VERTEX_SHADER: handleIndex = 1;
break;
case GL_TESS_CONTROL_SHADER: handleIndex = 2;
break;
case GL_TESS_EVALUATION_SHADER: handleIndex = 3;
break;
case GL_GEOMETRY_SHADER: handleIndex = 4;
break;
case GL_FRAGMENT_SHADER: handleIndex = 5;
break;
case GL_COMPUTE_SHADER: handleIndex = 6;
break;
default: throw "InvalidGLenumException";
break;
}
//Start working
//Read the code from file
const SgTstring scode = SgTShaderProc::readCode(path);
const char* code = scode.c_str();
//We don't need to worry about whether the file exits or not since the readCode function has done that
//Generating shader
this->shaderHandle[handleIndex] = glCreateShader(type);
this->shaderused[handleIndex - 1] = true;
//adding the source file
glShaderSource(this->shaderHandle[handleIndex], 1, &code, NULL);
//Finished
}
SgTShaderStatus SgTShaderProc::linkShader(GLchar* log, const int bufferSize, SgTProgramPara arg) {
if (this->shaderHandle[0] == 0) {//check if we have a programe
//create the programe
this->shaderHandle[0] = glCreateProgram();
}
//Compile all shaders that have been created
for (int i = 1; i < 7; i++) {//shader start from 1
if (this->shaderused[i - 1]) { //if shader exists
//compile it
glCompileShader(this->shaderHandle[i]);
//check for error
if (!this->debugCompile(this->shaderHandle[i], true, log, bufferSize)) {//if error occurs
//return to user which shader causes the error
return this->VERTEX_SHADER_ERR + (i - 1);//this will effectively output the shader we are looping
}
//No error? attach shaders to programe
glAttachShader(this->shaderHandle[0], this->shaderHandle[i]);
}
}
//user-set program parameter
if (arg != NULL) {//meaning user has set the program parameter
(*arg)(this->getP());
}
//We have attached all shaders, now link the programe
glLinkProgram(this->shaderHandle[0]);
//check for error
if (!this->debugCompile(this->shaderHandle[0], false, log, bufferSize)) {
return this->PROGRAME_LINKING_ERR;
}
//everything works fine
return this->OK;
//we will delete the shader source when the class got destructed just in case we need to re-attach it
}
void SgTShaderProc::deleteShader() {
glUseProgram(0);
if (this->shaderHandle[0] != 0) {//checking for programe existance
//detach all shader and delete them
for (int i = 1; i < 7; i++) {
if (this->shaderused[i - 1]) {//shader exists
glDetachShader(this->shaderHandle[0], this->shaderHandle[i]);
glDeleteShader(this->shaderHandle[i]);
this->shaderused[i - 1] = false;
this->shaderHandle[i] = 0;
}
}
//delete the programe
glDeleteProgram(this->shaderHandle[0]);
this->shaderHandle[0] = 0;//clear up the pointer such that it can be reused
}
}
const SgTstring SgTShaderProc::readCode(const SgTstring Path) {
//return value
SgTstring code;
//create the file stream
std::fstream file;
std::stringstream stream;
file.open(Path, std::ios_base::in);
file.exceptions(std::fstream::failbit | std::fstream::badbit);//make sure there is no exceptions
stream << file.rdbuf();
code = stream.str();
//finishing up
file.close();
return code;
}
const bool SgTShaderProc::debugCompile(GLuint shader, bool isShader, GLchar* log, const int bufferSize) {
//variables
GLint success;
if (isShader) {
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(shader, bufferSize, NULL, log);
return false;
}
}
else {
glGetProgramiv(shader, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(shader, bufferSize, NULL, log);
return false;
}
}
return true;
}
const int SgTShaderProc::getP() const {
return this->shaderHandle[0];
}
const int SgTShaderProc::getVS() const {
return this->shaderHandle[1];
}
const int SgTShaderProc::getTCS() const {
return this->shaderHandle[2];
}
const int SgTShaderProc::getTES() const {
return this->shaderHandle[3];
}
const int SgTShaderProc::getGS() const {
return this->shaderHandle[4];
}
const int SgTShaderProc::getFS() const {
return this->shaderHandle[5];
} | 26.89375 | 105 | 0.711132 |
49b80ce7d44f336de85baa6acf8c266c02a7e8a9 | 309 | hpp | C++ | CLASS/class_inheritance_2/Child.hpp | StanLepunK/CPP_basics | 72b8e72b84adc31bdfad4479d5133defb9575e54 | [
"MIT"
] | null | null | null | CLASS/class_inheritance_2/Child.hpp | StanLepunK/CPP_basics | 72b8e72b84adc31bdfad4479d5133defb9575e54 | [
"MIT"
] | null | null | null | CLASS/class_inheritance_2/Child.hpp | StanLepunK/CPP_basics | 72b8e72b84adc31bdfad4479d5133defb9575e54 | [
"MIT"
] | null | null | null | #ifndef CHILD_H
# define CHILD_H
#include "Mother.hpp"
class Child : public Mother {
private:
std::string name;
public:
Child();
~Child();
Child(float const x, float const y, std::string const name);
std::string get_name() const;
void static_talk();
virtual void virtual_talk();
};
#endif | 15.45 | 62 | 0.679612 |
49ba8348d2d36c463bd163cb89fee32926da201a | 401 | hpp | C++ | include/dotto/debug.hpp | mitsukaki/dotto | ebea72447e854c9beff676fe609d998a3cb0b3ea | [
"CC0-1.0"
] | 4 | 2018-03-05T22:51:40.000Z | 2018-03-11T00:54:38.000Z | include/dotto/debug.hpp | mitsukaki/dotto | ebea72447e854c9beff676fe609d998a3cb0b3ea | [
"CC0-1.0"
] | null | null | null | include/dotto/debug.hpp | mitsukaki/dotto | ebea72447e854c9beff676fe609d998a3cb0b3ea | [
"CC0-1.0"
] | 1 | 2019-09-14T19:44:14.000Z | 2019-09-14T19:44:14.000Z | #pragma once
#include <string>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include <dotto/io.hpp>
class debug
{
private:
TTF_Font* debug_font;
SDL_Rect fps_text_rect;
SDL_Surface* fps_text_surface;
SDL_Texture* fps_text_texture;
public:
debug();
~debug();
void render(SDL_Renderer* renderer);
void init();
float fps;
};
| 12.151515 | 40 | 0.665835 |
49bc2b5de44ea8cffd8978e2372400df92994655 | 590 | cpp | C++ | hackerrank/problems/GameOfThrones-I.cpp | joaquinmd93/competitive-programming | 681424abd777cc0a3059e1ee66ae2cee958178da | [
"MIT"
] | 1 | 2020-10-08T19:28:40.000Z | 2020-10-08T19:28:40.000Z | hackerrank/problems/GameOfThrones-I.cpp | joaquinmd93/competitive-programming | 681424abd777cc0a3059e1ee66ae2cee958178da | [
"MIT"
] | null | null | null | hackerrank/problems/GameOfThrones-I.cpp | joaquinmd93/competitive-programming | 681424abd777cc0a3059e1ee66ae2cee958178da | [
"MIT"
] | 1 | 2020-10-24T02:32:27.000Z | 2020-10-24T02:32:27.000Z | #include<bits/stdc++.h>
using namespace std;
int main() {
string s; cin >> s;
int n = s.size();
map<char, int> reps;
for (int i=0; i<n; ++i) {
++reps[s[i]];
}
int odd_reps=0;
for (auto let: reps) {
if (let.second % 2 != 0)
++odd_reps;
}
if (n % 2 == 0) {
if (odd_reps == 0)
cout << "YES" << endl;
else
cout << "NO" << endl;
} else {
if (odd_reps == 1)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
} | 21.071429 | 37 | 0.383051 |
49bc8fdc7a30207df70b9f88b807df3a38941b67 | 483 | hpp | C++ | inc/concept/detail/unuse.hpp | matrixjoeq/concepts | d9bac8343e44c62f22913ec41ac0856b767bedc4 | [
"MIT"
] | null | null | null | inc/concept/detail/unuse.hpp | matrixjoeq/concepts | d9bac8343e44c62f22913ec41ac0856b767bedc4 | [
"MIT"
] | null | null | null | inc/concept/detail/unuse.hpp | matrixjoeq/concepts | d9bac8343e44c62f22913ec41ac0856b767bedc4 | [
"MIT"
] | null | null | null | /** @file */
#ifndef __STL_CONCEPT_DETAIL_UNUSE_HPP__
#define __STL_CONCEPT_DETAIL_UNUSE_HPP__
namespace stl_concept {
namespace __detail {
/// @cond DEV
/**
* @brief Ignore unused object.
* @tparam T - object type
*/
template <class T>
inline void __unuse(T&&) {}
/**
* @brief Ignore unused type.
* @tparam T - object type
*/
template <class T>
struct __Unuse {};
/// @endcond
} // namespace __detail
} // namespace stl_concept
#endif // __STL_CONCEPT_DETAIL_UNUSE_HPP__
| 17.25 | 42 | 0.708075 |
49bcaa20b70785877da6cbd54e35cdd1d42d57fe | 4,031 | cpp | C++ | src/main/cpp/subsystems/Shooter.cpp | FIRSTTeam102/Robot2022 | 2a3224fd9bf7e4e9b469214fdf141a3d25d9094c | [
"BSD-3-Clause"
] | null | null | null | src/main/cpp/subsystems/Shooter.cpp | FIRSTTeam102/Robot2022 | 2a3224fd9bf7e4e9b469214fdf141a3d25d9094c | [
"BSD-3-Clause"
] | null | null | null | src/main/cpp/subsystems/Shooter.cpp | FIRSTTeam102/Robot2022 | 2a3224fd9bf7e4e9b469214fdf141a3d25d9094c | [
"BSD-3-Clause"
] | null | null | null | #include "subsystems/Shooter.h"
#include "commands/Shooter/StartShooter.h"
Shooter::Shooter() {
SetName("Shooter");
SetSubsystem("Shooter");
using namespace ShooterConstants;
// Shooter motor setup
mMotor.ConfigFactoryDefault(); // resets all settings
mMotor.SetInverted(true);
mMotor.SetNeutralMode(ctre::phoenix::motorcontrol::NeutralMode::Coast);
mMotor.SetSafetyEnabled(false);
// Sensor
mMotor.ConfigSelectedFeedbackSensor(FeedbackDevice::IntegratedSensor, 0, kTimeoutMs);
mMotor.SetSensorPhase(true);
mMotor.SetSelectedSensorPosition(0, 0, kTimeoutMs);
// Peak and nominal outputs
mMotor.ConfigNominalOutputForward(0, kTimeoutMs);
mMotor.ConfigNominalOutputReverse(0, kTimeoutMs);
mMotor.ConfigPeakOutputForward(1, kTimeoutMs);
mMotor.ConfigPeakOutputReverse(-0.0, kTimeoutMs); // DO NOT run the motor backwards (worst mistake of my life)
// Voltage compensation
mMotor.ConfigNeutralDeadband(kDeadband, kTimeoutMs);
// Closed loop gains
mMotor.Config_kD(0, kD, kTimeoutMs);
mMotor.Config_kF(0, kF, kTimeoutMs);
mMotor.Config_kI(0, kI, kTimeoutMs);
mMotor.Config_kP(0, kP, kTimeoutMs);
mMotor.SelectProfileSlot(0, 0);
stopShooter();
// Shuffleboard
wpi::StringMap<std::shared_ptr<nt::Value>> boostSliderProperties = {
std::make_pair("Min", nt::Value::MakeDouble(0.10)),
std::make_pair("Max", nt::Value::MakeDouble(1.50)),
std::make_pair("Block increment", nt::Value::MakeDouble(0.1))
};
frc::ShuffleboardLayout& layout = frc::Shuffleboard::GetTab("Drive").GetLayout("Shooter", frc::BuiltInLayouts::kList);
mShuffleboardReady = layout.Add("Ready?", false).GetEntry();
mShuffleboardTargetRPM = layout.Add("Target RPM", 0.0).GetEntry();
mShuffleboardActualRPM = layout.Add("Actual RPM", 0.0).GetEntry();
mShuffleboardActualPercent = layout.Add("Actual %", 0.0).GetEntry();
mShuffleboardBoost = layout.AddPersistent("Boost", mBoostPercent)
.WithWidget(frc::BuiltInWidgets::kNumberSlider)
.WithProperties(boostSliderProperties)
.GetEntry();
frc::ShuffleboardLayout& testLayout = frc::Shuffleboard::GetTab("Test").GetLayout("Shooter", frc::BuiltInLayouts::kList);
mShuffleboardTestRPM = testLayout.Add("Test RPM", 0.0).GetEntry();
frc::SmartDashboard::PutData("Set test RPM", new StartShooter(this, &mShuffleboardTestRPM)); // shuffleboard doesn't seem to like commands
// testLayout.Add("Set test RPM", new StartShooter(this, &mShuffleboardTestRPM)).WithWidget(frc::BuiltInWidgets::kCommand);
}
void Shooter::setShooter(double speed, bool useBoost) {
if (useBoost) speed = speed * mBoostPercent;
mMotor.Set(ControlMode::Velocity, rpmToVelocity(speed));
mTargetSpeed = speed;
}
void Shooter::stopShooter() {
mTargetSpeed = 0.0;
mMotor.Set(ControlMode::Velocity, 0.0);
}
void Shooter::setShooterPercent(double speed) {
mMotor.Set(ControlMode::PercentOutput, speed);
mTargetSpeed = speed / ShooterConstants::kMaxRpm;
}
void Shooter::Periodic() {
mActualSpeed = mFlywheelFilter.Calculate(velocityToRpm(mMotor.GetSelectedSensorVelocity(0)));
mShuffleboardReady.SetBoolean(isRunning() && (fabs(mTargetSpeed - mActualSpeed) < 75.0));
mShuffleboardActualRPM.SetDouble(mActualSpeed);
mShuffleboardActualPercent.SetDouble(getActualPercent());
mBoostPercent = mShuffleboardBoost.GetDouble(mBoostPercent);
// if (double newTargetSpeed = mShuffleboardTargetRPM.GetDouble(mTargetSpeed) != mTargetSpeed) setShooter(newTargetSpeed);
mShuffleboardTargetRPM.SetDouble(mTargetSpeed);
}
void Shooter::SimulationPeriodic() {
TalonFXSimCollection &motorSim(mMotor.GetSimCollection());
// Set simulation inputs
motorSim.SetBusVoltage(frc::RobotController::GetInputVoltage());
mFlywheelSim.SetInputVoltage(motorSim.GetMotorOutputLeadVoltage() * 1_V);
// Update simulation, standard loop time is 20ms
mFlywheelSim.Update(20_ms);
// Set simulated outputs
frc::sim::RoboRioSim::SetVInVoltage(
frc::sim::BatterySim::Calculate({mFlywheelSim.GetCurrentDraw()})
);
motorSim.SetIntegratedSensorVelocity(
rpmToVelocity(mFlywheelSim.GetAngularVelocity())
);
} | 36.315315 | 139 | 0.769784 |
49bfb9d091eb75a7ace1930c89cc4d2d1b3a5aae | 1,830 | hpp | C++ | include/RED4ext/Scripting/Natives/Generated/anim/DangleConstraint_SimulationPendulum.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 42 | 2020-12-25T08:33:00.000Z | 2022-03-22T14:47:07.000Z | include/RED4ext/Scripting/Natives/Generated/anim/DangleConstraint_SimulationPendulum.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 38 | 2020-12-28T22:36:06.000Z | 2022-02-16T11:25:47.000Z | include/RED4ext/Scripting/Natives/Generated/anim/DangleConstraint_SimulationPendulum.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 20 | 2020-12-28T22:17:38.000Z | 2022-03-22T17:19:01.000Z | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Scripting/Natives/Generated/Vector3.hpp>
#include <RED4ext/Scripting/Natives/Generated/anim/DangleConstraint_SimulationSingleBone.hpp>
#include <RED4ext/Scripting/Natives/Generated/anim/PendulumConstraintType.hpp>
#include <RED4ext/Scripting/Natives/Generated/anim/PendulumProjectionType.hpp>
#include <RED4ext/Scripting/Natives/Generated/anim/VectorLink.hpp>
namespace RED4ext
{
namespace anim {
struct DangleConstraint_SimulationPendulum : anim::DangleConstraint_SimulationSingleBone
{
static constexpr const char* NAME = "animDangleConstraint_SimulationPendulum";
static constexpr const char* ALIAS = NAME;
float simulationFps; // 90
anim::PendulumConstraintType constraintType; // 94
float halfOfMaxApertureAngle; // 98
Vector3 constraintOrientation; // 9C
float mass; // A8
float gravityWS; // AC
float damping; // B0
float pullForceFactor; // B4
Vector3 pullForceDirectionLS; // B8
Vector3 externalForceWS; // C4
anim::VectorLink externalForceWsLink; // D0
anim::PendulumProjectionType projectionType; // F0
float collisionCapsuleRadius; // F4
float collisionCapsuleHeightExtent; // F8
float cosOfHalfXAngle; // FC
float cosOfHalfYAngle; // 100
float cosOfHalfZAngle; // 104
float sinOfHalfXAngle; // 108
float sinOfHalfYAngle; // 10C
float sinOfHalfZAngle; // 110
float cosOfHalfMaxApertureAngle; // 114
float cosOfHalfOfHalfMaxApertureAngle; // 118
float sinOfHalfOfHalfMaxApertureAngle; // 11C
float invertedMass; // 120
uint8_t unk124[0x188 - 0x124]; // 124
};
RED4EXT_ASSERT_SIZE(DangleConstraint_SimulationPendulum, 0x188);
} // namespace anim
} // namespace RED4ext
| 36.6 | 93 | 0.757923 |
49c0a4c65093a40c35bcb7bc8b8d613c77de0ab9 | 3,377 | cpp | C++ | snowman.cpp | amichaibitan/cpp1_2 | d0d6fef8d98af6be415fbe54e4743a538636edc7 | [
"MIT"
] | null | null | null | snowman.cpp | amichaibitan/cpp1_2 | d0d6fef8d98af6be415fbe54e4743a538636edc7 | [
"MIT"
] | null | null | null | snowman.cpp | amichaibitan/cpp1_2 | d0d6fef8d98af6be415fbe54e4743a538636edc7 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <string>
#include <iostream>
#include <stdexcept>
#include <array>
#include "snowman.hpp"
using namespace std;
namespace ariel
{
std::string hat(int n){
std::string str = "";
if(n==1){
str+= " _===_\n";
}
else if(n==2){
str+=" ___ \n.....\n";
}
else if(n==3){
str+=" _ \n/_\\\n";
}
else if(n==4){
str+=" ___ \n(_*_)\n";
}
return str;
}
std::string nose(int n){
std::string str = "";
if(n==1){
str+=",";
}
else if(n==2){
str+=".";
}
else if(n==3){
str+="_";
}
else if(n==4){
str+=" ";
}
return str;
}
std::string l_eye(int n){
std::string str = "";
if(n==1){
str+="(.";
}
else if(n==2){
str+="(o";
}
else if(n==3){
str+="(O";
}
else if(n==4){
str+="(-";
}
return str;
}
std::string r_eye(int n){
std::string str="";
if(n==1){
str+=".)";
}
else if(n==2){
str+="o)";
}
else if(n==3){
str+="O)";
}
else if(n==4){
str+="-)";
}
return str;
}
std::string l_arm(int n){
std::string str="";
if(n==1){
str+="<";
}
else if(n==2){
str+="\\";
}
else if(n==3){
str+="/";
}
else if(n==4){
str+=" ";
}
return str;
}
std::string r_arm(int n){
std::string str ="";
if(n==1){
str+=">";
}
else if(n==2){
str+="/";
}
else if(n==3){
str+="\\";
}
else if(n==4){
str+=" ";
}
return str;
}
std::string torso(int n){
std::string str="";
if(n==1){
str+="( : )";
}
else if(n==2){
str+="(] [)";
}
else if(n==3){
str+="(> <)";
}
else if(n==4){
str+="( )";
}
return str;
}
std::string base(int n){
std::string str="";
if(n==1){
str+="\n( : )\n";
}
else if(n==2){
str+="\n(\" \")\n";
}
else if(n==3){
str+="\n(___)\n";
}
else if(n==4){
str+="\n( )\n";
}
return str;
}
//constexpr int _1=1,_2=2,_3=3,_4=4,_5=5,_6=6,_7=7;
std::string snowman (int n){
std::string str;
std::array<int, 8> arr;
if(n>44444444||n<11111111){
throw -1;
}
for(int i=0;i<8;i++)
{
if(n%10>4|| n%10<1){
throw -1;
}
arr.at(7-i)=n%10;
n= n/10;
}
// for(int i=0;i<8;i++){
// if(arr[i])
// }
str+=hat(arr[0]);
if(arr[4]==2)
{
str+=l_arm(arr[4]);
str+=l_eye(arr[2]);
str+=nose(arr[1]);
str+=r_eye(arr[3]);
if(arr[5]==2)
{
str+=r_arm(arr[5]);
str+="\n ";
str+=torso(arr[6]);
}
else
{
str+="\n ";
str+=torso(arr[6]);
str+=r_arm(arr[5]);
}
}
else
{
str+=l_eye(arr[2]);
str+=nose(arr[1]);
str+=r_eye(arr[3]);
if(arr[5] == 2)
{
str+=r_arm(arr[5]);
str+="\n ";
str+=l_arm(arr[4]);
str+=torso(arr[6]);
}
else
{
str+="\n ";
str+=l_arm(arr[4]);
str+=torso(arr[6]);
str+=r_arm(arr[5]);
}
}
str+=base(arr[7]);
return str;
}
}
// int main(){
// std::string str = snowman(33232124);
// cout << str;
// } | 15.075893 | 51 | 0.374889 |
49c35d5da78523cf5f60013d0b0803761665d2e9 | 1,548 | cpp | C++ | src/Parse/Parser.cpp | artagnon/rhine | ca4ec684162838f4cb13d9d29ef9e4aedbc268dd | [
"MIT"
] | 234 | 2015-01-02T18:32:50.000Z | 2022-02-03T19:41:33.000Z | src/Parse/Parser.cpp | artagnon/rhine | ca4ec684162838f4cb13d9d29ef9e4aedbc268dd | [
"MIT"
] | 7 | 2015-02-16T15:02:54.000Z | 2016-05-26T07:46:02.000Z | src/Parse/Parser.cpp | artagnon/rhine | ca4ec684162838f4cb13d9d29ef9e4aedbc268dd | [
"MIT"
] | 13 | 2015-02-16T13:37:12.000Z | 2020-12-12T04:18:43.000Z | #include "rhine/Parse/ParseDriver.hpp"
#include "rhine/Parse/Parser.hpp"
#include "rhine/Parse/Lexer.hpp"
#include "rhine/Diagnostic/Diagnostic.hpp"
#include "rhine/IR/Context.hpp"
#include "rhine/IR/Module.hpp"
#include <vector>
#define K Driver->Ctx
namespace rhine {
Parser::Parser(ParseDriver *Dri) : Driver(Dri), CurStatus(true) {}
Parser::~Parser() {}
void Parser::getTok() {
LastTok = CurTok;
CurTok = Driver->Lexx->lex(&CurSema, &CurLoc);
LastTokWasNewlineTerminated = false;
while (CurTok == NEWLINE) {
LastTokWasNewlineTerminated = true;
CurTok = Driver->Lexx->lex(&CurSema, &CurLoc);
}
}
bool Parser::getTok(int Expected) {
if (CurTok == Expected) {
getTok();
CurLoc.Filename = Driver->InputName;
CurLoc.StringStreamInput = Driver->StringStreamInput;
return true;
}
return false;
}
void Parser::writeError(std::string ErrStr, bool Optional) {
if (Optional) return;
DiagnosticPrinter(CurLoc) << ErrStr;
CurStatus = false;
}
bool Parser::getSemiTerm(std::string ErrFragment, bool Optional) {
if (!getTok(';') && !LastTokWasNewlineTerminated && CurTok != ENDBLOCK) {
auto ErrStr = "expecting ';' or newline to terminate " + ErrFragment;
writeError(ErrStr, Optional);
return false;
}
return true;
}
void Parser::parseToplevelForms() {
getTok();
while (auto Fcn = parseFcnDecl(true)) {
Driver->Root->appendFunction(Fcn);
}
if (CurTok != END)
writeError("expected end of file");
}
bool Parser::parse() {
parseToplevelForms();
return CurStatus;
}
}
| 23.104478 | 75 | 0.687339 |
49cb02d9b7eecd8c0fe5b389a18b8f277d0733cc | 5,911 | cpp | C++ | Quake/Notes005/src/DIYQuake/ModelManager.cpp | amroibrahim/DIYQuake | 957d4b86fc6edc3eedf0e322eafce89dc336261f | [
"MIT"
] | 13 | 2020-12-06T20:11:40.000Z | 2021-12-14T16:28:48.000Z | Quake/Notes005/src/DIYQuake/ModelManager.cpp | amroibrahim/DIYQuake | 957d4b86fc6edc3eedf0e322eafce89dc336261f | [
"MIT"
] | 1 | 2021-05-02T02:31:51.000Z | 2021-05-02T17:00:49.000Z | Quake/Notes005/src/DIYQuake/ModelManager.cpp | amroibrahim/DIYQuake | 957d4b86fc6edc3eedf0e322eafce89dc336261f | [
"MIT"
] | 1 | 2020-12-17T12:17:16.000Z | 2020-12-17T12:17:16.000Z | #include "ModelManager.h"
#include <string>
void ModelManager::Init(MemoryManager* pMemorymanager, Common* pCommon)
{
m_pMemorymanager = pMemorymanager;
m_pCommon = pCommon;
}
ModelData* ModelManager::Load(char* szName)
{
ModelData* pModelData = nullptr;
pModelData = Find(szName);
return Load(pModelData);
}
//Load header to Known list
void ModelManager::LoadHeader(char* szName)
{
ModelData* pModelData = Find(szName);
if (pModelData->eLoadStatus == MODELLOADSTATUS::PRESENT)
{
if (pModelData->eType == MODELTYPE::ALIAS)
{
m_pMemorymanager->Check(&pModelData->pCachData);
}
}
}
void ModelManager::LoadAliasModel(ModelData* pModel, byte_t* pBuffer, char* szHunkName)
{
int32_t iMemoryStartOffset = m_pMemorymanager->GetLowUsed();
ModelHeader* pTempModelHeader = (ModelHeader*)pBuffer;
int32_t iVersion = pTempModelHeader->iVersion;
int32_t iSize = sizeof(AliasModelHeader) + sizeof(ModelHeader);
std::string sloadName(szHunkName);
AliasModelHeader* pAliasModelHeader = (AliasModelHeader*)m_pMemorymanager->NewLowEndNamed(iSize, sloadName);
ModelHeader* pModelHeader = (ModelHeader*)((byte_t*)&pAliasModelHeader[1]);
// pModel->iFlags = pTempModelHeader->iFlags;
pModelHeader->iNumSkins = pTempModelHeader->iNumSkins;
pModelHeader->iSkinWidth = pTempModelHeader->iSkinWidth;
pModelHeader->iSkinHeight = pTempModelHeader->iSkinHeight;
int32_t iNumberOfSkins = pModelHeader->iNumSkins;
// Calculate the skin size in bytes
int32_t iSkinSize = pModelHeader->iSkinHeight * pModelHeader->iSkinWidth;
AliasSkinType* pSkinType = (AliasSkinType*)&pTempModelHeader[1];
AliasSkinDesc* pSkinDesc = (AliasSkinDesc*)m_pMemorymanager->NewLowEndNamed(iNumberOfSkins * sizeof(AliasSkinDesc), sloadName);
pAliasModelHeader->SkinDescOffset = (byte_t*)pSkinDesc - (byte_t*)pAliasModelHeader;
for (int i = 0; i < iNumberOfSkins; i++)
{
pSkinDesc[i].eSkinType = pSkinType->eSkinType;
if (pSkinType->eSkinType == ALIAS_SKIN_SINGLE)
{
pSkinType = (AliasSkinType*)LoadAliasSkin(pSkinType + 1, &pSkinDesc[i].skin, iSkinSize, pAliasModelHeader, sloadName);
}
else
{
pSkinType = (AliasSkinType*)LoadAliasSkinGroup(pSkinType + 1, &pSkinDesc[i].skin, iSkinSize, pAliasModelHeader, sloadName);
}
}
pModel->eType = MODELTYPE::ALIAS;
int32_t iMemoryEndOffset = m_pMemorymanager->GetLowUsed();
int32_t iTotalMemorySize = iMemoryEndOffset - iMemoryStartOffset;
m_pMemorymanager->m_Cache.NewNamed(&pModel->pCachData, iTotalMemorySize, sloadName);
if (!pModel->pCachData.pData)
return;
memcpy(pModel->pCachData.pData, pAliasModelHeader, iTotalMemorySize);
m_pMemorymanager->DeleteToLowMark(iMemoryStartOffset);
}
ModelData* ModelManager::Find(char* szName)
{
ModelData* pAvailable = NULL;
int iCurrentModelIndex = 0;
// Is the model already loaded?
ModelData* pCurrentModel = m_pKnownModels;
while (iCurrentModelIndex < m_iKnownModelCount)
{
if (!strcmp(pCurrentModel->szName, szName))
{
break;
}
if ((pCurrentModel->eLoadStatus == MODELLOADSTATUS::UNREFERENCED) && (!pAvailable || pCurrentModel->eType != MODELTYPE::ALIAS))
{
pAvailable = pCurrentModel;
}
++iCurrentModelIndex;
++pCurrentModel;
}
if (iCurrentModelIndex == m_iKnownModelCount)
{
if (m_iKnownModelCount == MAX_KNOWN_MODEL)
{
if (pAvailable)
{
pCurrentModel = pAvailable;
if (pCurrentModel->eType == MODELTYPE::ALIAS && m_pMemorymanager->Check(&pCurrentModel->pCachData))
{
m_pMemorymanager->CacheEvict(&pCurrentModel->pCachData);
}
}
}
else
{
++m_iKnownModelCount;
}
strcpy(pCurrentModel->szName, szName);
pCurrentModel->eLoadStatus = MODELLOADSTATUS::NEEDS_LOADING;
}
return pCurrentModel;
}
void* ModelManager::ExtraData(ModelData* pModel)
{
void* pData;
pData = m_pMemorymanager->m_Cache.Check(&pModel->pCachData);
if (pData)
return pData;
Load(pModel);
return pModel->pCachData.pData;
}
ModelData* ModelManager::Load(ModelData* pModel)
{
if (pModel->eType == MODELTYPE::ALIAS)
{
if (m_pMemorymanager->Check(&pModel->pCachData))
{
pModel->eLoadStatus = MODELLOADSTATUS::PRESENT;
return pModel;
}
}
else
{
if (pModel->eLoadStatus == MODELLOADSTATUS::PRESENT)
{
return pModel;
}
}
byte_t TempBuffer[1024]; // 1K on stack! Load the model temporary on stack (if they fit)
byte_t* pBuffer = m_pCommon->LoadFile(pModel->szName, TempBuffer, sizeof(TempBuffer));
char szHunkName[32] = { 0 };
m_pCommon->GetFileBaseName(pModel->szName, szHunkName);
//TODO:
//loadmodel = pModel;
pModel->eLoadStatus = MODELLOADSTATUS::PRESENT;
switch (*(uint32_t*)pBuffer)
{
case IDPOLYHEADER:
LoadAliasModel(pModel, (byte_t*)pBuffer, szHunkName);
break;
//case IDSPRITEHEADER:
// LoadSpriteModel(pModel, pBuffer);
// break;
//default:
// LoadBrushModel(pModel, pBuffer);
// break;
}
return pModel;
}
void* ModelManager::LoadAliasSkin(void* pTempModel, int32_t* pSkinOffset, int32_t iSkinSize, AliasModelHeader* pHeader, std::string& sHunkName)
{
byte_t* pSkin = (byte_t*)m_pMemorymanager->NewLowEndNamed(iSkinSize, sHunkName);
byte_t* pSkinInTemp = (byte_t*)pTempModel;
*pSkinOffset = (byte_t*)pSkin - (byte_t*)pHeader;
memcpy(pSkin, pSkinInTemp, iSkinSize);
pSkinInTemp += iSkinSize;
return ((void*)pSkinInTemp);
}
void* ModelManager::LoadAliasSkinGroup(void* pTempModel, int32_t* pSkinOffset, int32_t iSkinSize, AliasModelHeader* pHeader, std::string& sHunkName)
{
return nullptr;
}
| 26.746606 | 148 | 0.682964 |
49ccafc5c5b597763564ff02b523f969ebbb4ede | 728 | hpp | C++ | src/utility/apply.hpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | 2 | 2018-07-04T16:44:04.000Z | 2021-01-03T07:26:27.000Z | test/utility/apply.hpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | null | null | null | test/utility/apply.hpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | null | null | null | #pragma once
// std c++ headers
#include <tuple>
#include <array>
// AMDiS includes
#include "traits/basic.hpp"
#include "traits/size.hpp"
#include "utility/int_seq.hpp"
namespace AMDiS
{
namespace detail
{
// return f(t[0], t[1], t[2], ...)
template <class F, class Tuple, int... I>
constexpr auto apply_impl(F&& f, Tuple&& t, AMDiS::Seq<I...>) RETURNS
(
(std::forward<F>(f))(std::get<I>(std::forward<Tuple>(t))...)
)
} // end namespace detail
template <class F, class Tuple, int N = Size<Decay_t<Tuple>>::value>
constexpr auto apply(F&& f, Tuple&& t) RETURNS
(
detail::apply_impl(std::forward<F>(f), std::forward<Tuple>(t), MakeSeq_t<N>{})
)
} // end namespace AMDiS
| 22.060606 | 82 | 0.612637 |
49cd3d84b1639b63e391495c0934cd8529efae10 | 1,094 | hh | C++ | melodic/src/stage/libstage/file_manager.hh | disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA | 3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0 | [
"BSD-3-Clause"
] | 2 | 2021-07-14T12:33:55.000Z | 2021-11-21T07:14:13.000Z | melodic/src/stage/libstage/file_manager.hh | disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA | 3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0 | [
"BSD-3-Clause"
] | null | null | null | melodic/src/stage/libstage/file_manager.hh | disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA | 3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0 | [
"BSD-3-Clause"
] | null | null | null | #ifndef _FILE_MANAGER_HH_
#define _FILE_MANAGER_HH_
#include <string>
#include <vector>
namespace Stg {
class FileManager {
private:
std::string WorldsRoot;
std::string stripFilename(const std::string &path);
public:
FileManager();
/// Return the path where the current worldfile was loaded from
inline const std::string worldsRoot() const { return WorldsRoot; }
/// Update the worldfile path
void newWorld(const std::string &worldfile);
/// Determine whether a file can be opened for reading
static bool readable(const std::string &path);
/** Search for a file in the current directory, in the
* prefix/share/stage location, and in the locations specified by
* the STAGEPATH environment variable. Returns the first match or
* the original filename if not found.
**/
static std::string findFile(const std::string &filename);
/// Return the STAGEPATH environment variable
static std::string stagePath();
/// Returns the path to the current user's home directory (or empty if not detectable):
static std::string homeDirectory();
};
}
#endif
| 26.682927 | 89 | 0.729433 |
49d165e039d2329018c519729c723a32fecadf17 | 284 | cpp | C++ | src/Test/src/MockAudioPlayerView.cpp | don-reba/peoples-note | c22d6963846af833c55f4294dd0474e83344475d | [
"BSD-2-Clause"
] | null | null | null | src/Test/src/MockAudioPlayerView.cpp | don-reba/peoples-note | c22d6963846af833c55f4294dd0474e83344475d | [
"BSD-2-Clause"
] | null | null | null | src/Test/src/MockAudioPlayerView.cpp | don-reba/peoples-note | c22d6963846af833c55f4294dd0474e83344475d | [
"BSD-2-Clause"
] | null | null | null | #include "stdafx.h"
#include "MockAudioPlayerView.h"
using namespace std;
void MockAudioPlayerView::Hide()
{
isShown = false;
}
void MockAudioPlayerView::SetFileName(wstring & name)
{
this->name = name;
}
void MockAudioPlayerView::Show()
{
isShown = true;
}
| 14.2 | 54 | 0.676056 |
49d35ea928779a62915396dd753395a313af8644 | 4,593 | cpp | C++ | source/networkrequest.cpp | KambizAsadzadeh/RestService | ca677068954cd9b6f08d42d8deabdaf07c712d93 | [
"MIT"
] | 7 | 2020-10-31T19:03:12.000Z | 2022-02-04T09:50:56.000Z | source/networkrequest.cpp | KambizAsadzadeh/RestService | ca677068954cd9b6f08d42d8deabdaf07c712d93 | [
"MIT"
] | null | null | null | source/networkrequest.cpp | KambizAsadzadeh/RestService | ca677068954cd9b6f08d42d8deabdaf07c712d93 | [
"MIT"
] | null | null | null | #include "networkrequest.hpp"
#include "core.hpp"
using namespace RestService;
namespace RestService {
NetworkRequest::NetworkRequest()
{
this->result = "Unknown";
curl = curl_easy_init();
if(!curl)
throw std::string ("Curl did not initialize!");
}
NetworkRequest::~NetworkRequest()
{
cleanGlobal();
}
static size_t WriteCallback2(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
size_t NetworkRequest::WriteCallback(char *data, size_t size, size_t nmemb, std::string *buffer)
{
unsigned long result = 0;
if (buffer != nullptr) {
buffer->append(data, size * nmemb);
*buffer += data;
result = size * nmemb;
}
return result;
}
void NetworkRequest::clean() {
curl_easy_cleanup(curl);
}
void NetworkRequest::cleanGlobal() {
curl_global_cleanup();
}
void NetworkRequest::post(const std::string& url, const std::string& query){
/* In windows, this will init the winsock stuff */
curl_global_init(CURL_GLOBAL_ALL);
/* get a curl handle */
curl = curl_easy_init();
if(curl) {
ctype_list = curl_slist_append(ctype_list, Core::headerType.data());
if(Core::isset(Core::headerType)) {
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, ctype_list);
std::clog << "Content type has been set!" << std::endl;
}
curl_easy_setopt(curl, CURLOPT_URL, url.data());
/* Now specify the POST data */
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, query.data());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
curl_slist_free_all(ctype_list); /* free the ctype_list again */
/* Check for errors */
if(res != CURLE_OK)
std::clog << curl_easy_strerror(res) << std::endl;
fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
clean();
setResult(readBuffer);
}
}
void NetworkRequest::get(const std::string& url)
{
if(curl) {
if(Core::isset(Core::headerType)) {
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, ctype_list);
std::clog << "Content type has been set!" << std::endl;
}
#ifdef SKIP_PEER_VERIFICATION
/*
* If you want to connect to a site who isn't using a certificate that is
* signed by one of the certs in the CA bundle you have, you can skip the
* verification of the server's certificate. This makes the connection
* A LOT LESS SECURE.
*
* If you have a CA cert for the server stored someplace else than in the
* default bundle, then the CURLOPT_CAPATH option might come handy for
* you.
*/
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
#endif
#ifdef SKIP_HOSTNAME_VERIFICATION
/*
* If the site you're connecting to uses a different host name that what
* they have mentioned in their server certificate's commonName (or
* subjectAltName) fields, libcurl will refuse to connect. You can skip
* this check, but this will make the connection less secure.
*/
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
#endif
curl_easy_setopt(curl, CURLOPT_URL, url.data());
//curl_easy_setopt(curl, CURLOPT_HEADER, false);
/* example.com is redirected, so we tell libcurl to follow redirection */
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback2);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
std::cout << "Done!" << std::endl;
setResult(readBuffer);
/* always cleanup */
curl_easy_cleanup(curl);
}
}
void NetworkRequest::setResult(const std::string& res) {
ApiException apiEx;
if(!res.empty()) {
result = res;
apiEx.setMessage(result);
} else {
result = "unknown";
apiEx.setMessage("Unknown");
}
}
std::string NetworkRequest::getResult() {
return result;
}
}
| 28.52795 | 96 | 0.641193 |
49d7b46a187c4381b134715ceb33fdbcdac3699d | 1,438 | cpp | C++ | src/base/SimInfo.cpp | denniskb/bsim | bfe02148fc2fee7efff68b16173c626c515a49bb | [
"MIT"
] | 11 | 2019-09-01T16:20:57.000Z | 2022-01-19T08:24:06.000Z | src/base/SimInfo.cpp | denniskb/bsim | bfe02148fc2fee7efff68b16173c626c515a49bb | [
"MIT"
] | 2 | 2020-12-14T17:27:21.000Z | 2020-12-15T09:03:38.000Z | src/base/SimInfo.cpp | CRAFT-THU/BSim | 479c04348312579a7ae9c118c6b987724e540f38 | [
"MIT"
] | null | null | null |
#include "SimInfo.h"
int logFireInfo(FireInfo log, string type, string name)
{
string filename = name.append(".").append(type);
FILE *file = fopen(filename.c_str(), "w+");
if (file == NULL) {
printf("ERROR: Open file %s failed\n", filename.c_str());
return -1;
}
//printf("%d \n", log[type].size);
//int *data = reinterpret_cast<int*>(log[type].data);
//printf("%d \n", data[0]);
//printf("%s \n", type.c_str());
for (int j=0; j<log[type].size; j++) {
if (type == "Y") {
real *data = reinterpret_cast<real*>(log[type].data);
fprintf(file, "%f ", data[j]);
} else {
int *data = reinterpret_cast<int*>(log[type].data);
fprintf(file, "%d ", data[j]);
}
}
fprintf(file, "\n");
fflush(file);
fclose(file);
return 0;
}
int logFireInfo(FireInfo log, string type, int start, int batch, int size, string name)
{
string filename = name.append(".").append(type);
FILE *file = fopen(filename.c_str(), "w+");
if (file == NULL) {
printf("ERROR: Open file %s failed\n", filename.c_str());
return -1;
}
for (int i=0; i<batch; i++) {
for (int j=0; j<size; j++) {
if (type == "Y") {
real *data = reinterpret_cast<real*>(log[type].data);
fprintf(file, "%f ", data[start + i*size + j]);
} else {
int *data = reinterpret_cast<int*>(log[type].data);
fprintf(file, "%d ", data[start + i*size + j]);
}
}
fprintf(file, "\n");
}
fflush(file);
fclose(file);
return 0;
}
| 22.123077 | 88 | 0.584145 |
49d8992285acc111bb590e67ebf8c19642969e2e | 51 | cpp | C++ | module/armor/fan_armor.cpp | PaPaPR/WolfVision | 4092a313491349397106e3c050a332b2a5c6e611 | [
"MIT"
] | null | null | null | module/armor/fan_armor.cpp | PaPaPR/WolfVision | 4092a313491349397106e3c050a332b2a5c6e611 | [
"MIT"
] | null | null | null | module/armor/fan_armor.cpp | PaPaPR/WolfVision | 4092a313491349397106e3c050a332b2a5c6e611 | [
"MIT"
] | null | null | null | #include "fan_armor.hpp"
namespace fan_armor {
}
| 8.5 | 24 | 0.72549 |
49da617293b4093c5c6d63da2090ee45557b3e6f | 1,208 | cpp | C++ | Engine/OGF-Core/Core/Threads/ThreadPool.cpp | simon-bourque/OpenGameFramework | e0fed3895000a5ae244fc1ef696f4256af29865b | [
"MIT"
] | 4 | 2017-12-31T05:24:24.000Z | 2021-06-08T07:33:57.000Z | Engine/OGF-Core/Core/Threads/ThreadPool.cpp | simon-bourque/OpenGameFramework | e0fed3895000a5ae244fc1ef696f4256af29865b | [
"MIT"
] | 10 | 2018-01-13T22:36:57.000Z | 2018-06-23T20:03:03.000Z | Engine/OGF-Core/Core/Threads/ThreadPool.cpp | simon-bourque/OpenGameFramework | e0fed3895000a5ae244fc1ef696f4256af29865b | [
"MIT"
] | null | null | null | #include "ThreadPool.h"
ThreadPool::ThreadWorker::ThreadWorker(ThreadPool* threadPool, const int threadIdx)
:m_threadPool(threadPool),m_threadIdx(threadIdx) {}
void ThreadPool::ThreadWorker::operator()()
{
std::function<void()> function;
bool dequeued;
while (!m_threadPool->m_shutdown) {
{
std::unique_lock<std::mutex> lock(m_threadPool->m_conditionalMutex);
if (m_threadPool->m_queue.empty()) {
m_threadPool->m_conditionalLock.wait(lock);
}
dequeued = m_threadPool->m_queue.dequeue(function);
}
if (dequeued) {
function();
}
}
}
ThreadPool::ThreadPool()
:m_threads(std::vector<std::thread>(DEFAULT_NUMBER_THREADS))
, m_shutdown(false)
{
for (int i = 0; i < m_threads.size(); i++)
{
m_threads[i] = std::thread(ThreadWorker(this, i));
}
}
ThreadPool::ThreadPool(const int numberOfThreads)
:m_threads(std::vector<std::thread>(numberOfThreads))
, m_shutdown(false)
{
for (int i = 0; i < m_threads.size(); i++)
{
m_threads[i] = std::thread(ThreadWorker(this, i));
}
}
ThreadPool::~ThreadPool() {
m_shutdown = true;
m_conditionalLock.notify_all();
for (int i = 0; i < m_threads.size(); ++i) {
if (m_threads[i].joinable()) {
m_threads[i].join();
}
}
} | 23.230769 | 83 | 0.683775 |
49da67e562c02f9ecc3ade584f25592a8ab3d710 | 6,581 | cc | C++ | TicTacToe.cc | ucarlos/C-Doodles | 6e4680c47b1f73e39611e6ace7ab60f5123da34a | [
"MIT"
] | null | null | null | TicTacToe.cc | ucarlos/C-Doodles | 6e4680c47b1f73e39611e6ace7ab60f5123da34a | [
"MIT"
] | null | null | null | TicTacToe.cc | ucarlos/C-Doodles | 6e4680c47b1f73e39611e6ace7ab60f5123da34a | [
"MIT"
] | null | null | null | /*
* -----------------------------------------------------------------------------
* Created by Ulysses Carlos on 06/22/2020 at 09:47 PM
*
* Tic_Tak_Toe.cc
* Awful Implementation of Tic Tac Toe.
* -----------------------------------------------------------------------------
*/
#include <iostream>
#include <vector>
using namespace std;
const char default_tile_char = '!';
int total_marks = 0;
// 80 char terminal
const int max_term_length = 80;
class Mark{
public:
void set_mark(char ch) { value = ch; }
char get_mark() const{ return value; }
bool is_mark(char ch) const { return value == ch; }
void clear_mark() { value = default_tile_char; }
Mark()=default;
explicit Mark(char val) : value{val} { }
void toggle_on(){ chosen = true; }
void toggle_off(){ chosen = false; }
bool is_empty() const { return !chosen; }
private:
char value{default_tile_char};
bool chosen{false};
};
void draw_board(const vector<Mark> &vm);
class Player{
public:
Player()=default;
vector<int>& get_mark_list(){ return mark_indices; }
explicit Player(char ch) : mark_char{ch} { }
// Copy constructor
Player(const Player &p);
void add_mark_to_list(int i){ mark_indices.push_back(i); }
[[nodiscard]] char get_mark_character() const { return mark_char; }
private:
char mark_char{'@'};
vector<int> mark_indices;
};
Player::Player(const Player &p){
this->mark_char = p.mark_char;
this->mark_indices = p.mark_indices;
}
//------------------------------------------------------------------------------
// Class helper functions
//------------------------------------------------------------------------------
void claim_mark(Player &p, Mark &m, int index){
m.set_mark(p.get_mark_character());
m.toggle_on();
// Add to list:
p.add_mark_to_list(index);
total_marks++;
}
void print_dash_line(const int &term_len){
for (int i = 0; i < term_len; i++)
cout << "-";
cout << "\n";
}
//------------------------------------------------------------------------------
// Check Win Conditions
//------------------------------------------------------------------------------
inline bool check_down(const vector<Mark> &board, const int &index,
const char &ch){
return board[index].get_mark() == ch
&& board[index + 3].get_mark() == ch
&& board[index + 6].get_mark() == ch;
}
inline bool check_across(const vector<Mark> &board, const int &index,
const char &ch){
return board[index].get_mark() == ch
&& board[index + 1].get_mark() == ch
&& board[index + 2].get_mark() == ch;
}
inline bool check_right_diagonal(const vector<Mark> &board,
const int &index, const char &ch){
return board[index].get_mark() == ch
&& board[index + 4].get_mark() == ch
&& board[index + 8].get_mark() == ch;
}
inline bool check_left_diagonal(const vector<Mark> &board,
const int &index, const char &ch){
return board[index].get_mark() == ch
&& board[index + 2].get_mark() == ch
&& board[index + 4].get_mark() == ch;
}
//------------------------------------------------------------------------------
// Awful way of checking winning conditions, but it works.
//------------------------------------------------------------------------------
bool check_winning_conditions(vector<Mark> &board, Player &p){
bool check{true};
char player_character = p.get_mark_character();
int temp_index;
// Now check the player's vector list. If less than 3, return false.
const vector<int> &vec = p.get_mark_list();
if (vec.size() < 3) return false;
for (const int &i : vec){
temp_index = i;
switch(temp_index){
case 0:
check = check_across(board, temp_index, player_character);
check |= check_down(board, temp_index, player_character);
check |= check_right_diagonal(board, temp_index, player_character);
break;
case 1:
check = check_down(board, temp_index, player_character);
break;
case 2:
check = check_down(board, temp_index, player_character);
check |= check_left_diagonal(board, temp_index, player_character);
break;
case 3: case 6:
check = check_across(board, temp_index, player_character);
// break can be omitted if you want
//break;
default:
break;
}
if (check){
draw_board(board);
cout << "Player '" << player_character
<< "' wins!" << endl;
return true;
}
}
// if check is still false, then the game has ended in a draw.
if (!check && total_marks >= 9){
draw_board(board);
cout << "This game ends in a draw." << endl;
return true;
}
// If none were found, then continue.
return false;
}
void draw_board(const vector<Mark> &vm){
for (unsigned long i = 0; i < vm.size(); i++)
cout << vm[i].get_mark()
<< (((i + 1) % 3 == 0) ? "\n" : " ");
}
void player_turn(vector<Mark> &board, Player &p){
// Clear screen and print the current board:
// Windows Version
#if defined(WIN32) || defined(_WIN32)
system("cls");
#else // Linux/POSIX
system("clear");
#endif
char pc = p.get_mark_character();
print_dash_line(max_term_length);
cout << "It is now Player " << pc << "'s turn.\n";
print_dash_line(max_term_length);
draw_board(board);
print_dash_line(max_term_length);
cout << "Please enter a row and column where you want to put down"
<< " a character.\nMake sure that the row and columns are"
<< " between 1 and 3.\n";
int row, column;
cin >> row >> column;
int index = 3 * (row - 1) + (column - 1);
bool check_range = (1 <= row && row <= 3) && (1 <= column && column <= 3);
while (!check_range || !board[index].is_empty()){
cerr << "The row and column combination is invalid or "
<< "is already marked by another player. Try again.\n";
cin >> row >> column;
index = 3 * (row - 1) + (column - 1);
check_range = (1 <= row && row <= 3) && (1 <= column && column <= 3);
}
// Now translate to 1d array:
claim_mark(p, board[index], index);
bool check_win = check_winning_conditions(board, p);
if (check_win)
exit(EXIT_SUCCESS);
}
int main(void){
// Create the board.
vector<Mark> board(9);
Player p1('x');
Player p2('o');
print_dash_line(max_term_length);
cout << "Tic Tac Toe (Version 0.5)" << endl;
print_dash_line(max_term_length);
char ch;
cout << "Press any letter to begin!" << endl;
cin >> ch;
while (true){
player_turn(board, p1);
player_turn(board, p2);
}
}
| 27.535565 | 80 | 0.561313 |
49ddbb44d358aadb14bfcc1dcd13c201618f2a85 | 5,626 | cpp | C++ | libFRIClient/src/base/friClientApplication.cpp | thinkexist1989/iiwa_connectivity_fri_examples | 7a0ed010ce41ed774fc037ab11219eba824b2ae4 | [
"MIT"
] | 1 | 2021-04-07T05:40:55.000Z | 2021-04-07T05:40:55.000Z | libFRIClient/src/base/friClientApplication.cpp | thinkexist1989/iiwa_connectivity_fri_examples | 7a0ed010ce41ed774fc037ab11219eba824b2ae4 | [
"MIT"
] | null | null | null | libFRIClient/src/base/friClientApplication.cpp | thinkexist1989/iiwa_connectivity_fri_examples | 7a0ed010ce41ed774fc037ab11219eba824b2ae4 | [
"MIT"
] | null | null | null | // version: 1.7
/**
DISCLAIMER OF WARRANTY
The Software is provided "AS IS" and "WITH ALL FAULTS,"
without warranty of any kind, including without limitation the warranties
of merchantability, fitness for a particular purpose and non-infringement.
KUKA makes no warranty that the Software is free of defects or is suitable
for any particular purpose. In no event shall KUKA be responsible for loss
or damages arising from the installation or use of the Software,
including but not limited to any indirect, punitive, special, incidental
or consequential damages of any character including, without limitation,
damages for loss of goodwill, work stoppage, computer failure or malfunction,
or any and all other commercial damages or losses.
The entire risk to the quality and performance of the Software is not borne by KUKA.
Should the Software prove defective, KUKA is not liable for the entire cost
of any service and repair.
COPYRIGHT
All Rights Reserved
Copyright (C) 2014-2015
KUKA Roboter GmbH
Augsburg, Germany
This material is the exclusive property of KUKA Roboter GmbH and must be returned
to KUKA Roboter GmbH immediately upon request.
This material and the information illustrated or contained herein may not be used,
reproduced, stored in a retrieval system, or transmitted in whole
or in part in any way - electronic, mechanical, photocopying, recording,
or otherwise, without the prior written consent of KUKA Roboter GmbH.
*/
#include <stdio.h>
#include "friClientApplication.h"
#include "friClientIf.h"
#include "friConnectionIf.h"
#include "friClientData.h"
#include "FRIMessages.pb.h"
using namespace KUKA::FRI;
//******************************************************************************
ClientApplication::ClientApplication(IConnection& connection, IClient& client)
: _connection(connection), _client(client), _data(NULL)
{
_data = _client.createData();
}
//******************************************************************************
ClientApplication::~ClientApplication()
{
disconnect();
delete _data;
}
//******************************************************************************
bool ClientApplication::connect(int port, const char *remoteHost)
{
if (_connection.isOpen())
{
printf("Warning: client application already connected!\n");
return true;
}
return _connection.open(port, remoteHost);
}
//******************************************************************************
void ClientApplication::disconnect()
{
if (_connection.isOpen()) _connection.close();
}
//******************************************************************************
bool ClientApplication::step()
{
if (!_connection.isOpen())
{
printf("Error: client application is not connected!\n");
return false;
}
// **************************************************************************
// Receive and decode new monitoring message
// **************************************************************************
int size = _connection.receive(_data->receiveBuffer, FRI_MONITOR_MSG_MAX_SIZE);
if (size <= 0)
{ // TODO: size == 0 -> connection closed (maybe go to IDLE instead of stopping?)
printf("Error: failed while trying to receive monitoring message!\n");
return false;
}
if (!_data->decoder.decode(_data->receiveBuffer, size))
{
return false;
}
// check message type (so that our wrappers match)
if (_data->expectedMonitorMsgID != _data->monitoringMsg.header.messageIdentifier)
{
printf("Error: incompatible IDs for received message (got: %d expected %d)!\n",
(int)_data->monitoringMsg.header.messageIdentifier,
(int)_data->expectedMonitorMsgID);
return false;
}
// **************************************************************************
// callbacks
// **************************************************************************
// reset commmand message before callbacks
_data->resetCommandMessage();
ESessionState currentState = (ESessionState)_data->monitoringMsg.connectionInfo.sessionState;
if (_data->lastState != currentState)
{
_client.onStateChange(_data->lastState, currentState);
_data->lastState = currentState;
}
switch (currentState)
{
case MONITORING_WAIT:
case MONITORING_READY:
_client.monitor();
break;
case COMMANDING_WAIT:
_client.waitForCommand();
break;
case COMMANDING_ACTIVE:
_client.command();
break;
case IDLE:
default:
return true; // nothing to send back
}
// **************************************************************************
// Encode and send command message
// **************************************************************************
_data->lastSendCounter++;
// check if its time to send an answer
if (_data->lastSendCounter >= _data->monitoringMsg.connectionInfo.receiveMultiplier)
{
_data->lastSendCounter = 0;
// set sequence counters
_data->commandMsg.header.sequenceCounter = _data->sequenceCounter++;
_data->commandMsg.header.reflectedSequenceCounter =
_data->monitoringMsg.header.sequenceCounter;
if (!_data->encoder.encode(_data->sendBuffer, size))
{
return false;
}
if (!_connection.send(_data->sendBuffer, size))
{
printf("Error: failed while trying to send command message!\n");
return false;
}
}
return true;
}
| 32.148571 | 96 | 0.585851 |
49df51121939c40f1c347a5d84b8f2c9c642cf52 | 1,811 | cpp | C++ | Source/UnrealCPP/ActorLineTrace/ActorLineTrace.cpp | Harrison1/unrealcpp-full-project | a0a84d124b3023a87cbcbf12cf8ee0a833dd4302 | [
"MIT"
] | 6 | 2018-04-22T15:27:39.000Z | 2021-11-02T17:33:58.000Z | Source/UnrealCPP/ActorLineTrace/ActorLineTrace.cpp | Harrison1/unrealcpp-full-project | a0a84d124b3023a87cbcbf12cf8ee0a833dd4302 | [
"MIT"
] | null | null | null | Source/UnrealCPP/ActorLineTrace/ActorLineTrace.cpp | Harrison1/unrealcpp-full-project | a0a84d124b3023a87cbcbf12cf8ee0a833dd4302 | [
"MIT"
] | 4 | 2018-07-26T15:39:46.000Z | 2020-12-28T08:10:35.000Z | // Harrison McGuire
// UE4 Version 4.19.0
// https://github.com/Harrison1/unrealcpp
// https://severallevels.io
// https://harrisonmcguire.com
#include "ActorLineTrace.h"
#include "ConstructorHelpers.h"
#include "DrawDebugHelpers.h"
// Sets default values
AActorLineTrace::AActorLineTrace()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
// add cube to root
UStaticMeshComponent* Cube = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("VisualRepresentation"));
Cube->SetupAttachment(RootComponent);
static ConstructorHelpers::FObjectFinder<UStaticMesh> CubeAsset(TEXT("/Game/StarterContent/Shapes/Shape_Cube.Shape_Cube"));
if (CubeAsset.Succeeded())
{
Cube->SetStaticMesh(CubeAsset.Object);
Cube->SetRelativeLocation(FVector(0.0f, 0.0f, 0.0f));
Cube->SetWorldScale3D(FVector(1.f));
}
// add another component in the editor to the actor to overlap with the line trace to get the event to fire
}
// Called when the game starts or when spawned
void AActorLineTrace::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AActorLineTrace::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
FHitResult OutHit;
FVector Start = GetActorLocation();
Start.Z += 50.f;
Start.X += 200.f;
FVector ForwardVector = GetActorForwardVector();
FVector End = ((ForwardVector * 500.f) + Start);
FCollisionQueryParams CollisionParams;
DrawDebugLine(GetWorld(), Start, End, FColor::Green, false, 1, 0, 5);
if(ActorLineTraceSingle(OutHit, Start, End, ECC_WorldStatic, CollisionParams))
{
GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Green, FString::Printf(TEXT("The Component Being Hit is: %s"), *OutHit.GetComponent()->GetName()));
}
} | 28.746032 | 151 | 0.732192 |
49e067ba72c9284c68a76f2dc24c67c337584b14 | 3,539 | hpp | C++ | cmake/templates/spirv.in.hpp | EEnginE/engine | 9d8fe2c8a3051b8d25a15debdf058ac900f6a7fc | [
"Apache-2.0"
] | 28 | 2015-01-02T19:06:37.000Z | 2018-11-23T11:34:17.000Z | cmake/templates/spirv.in.hpp | EEnginE/engine | 9d8fe2c8a3051b8d25a15debdf058ac900f6a7fc | [
"Apache-2.0"
] | null | null | null | cmake/templates/spirv.in.hpp | EEnginE/engine | 9d8fe2c8a3051b8d25a15debdf058ac900f6a7fc | [
"Apache-2.0"
] | 6 | 2015-01-10T16:48:14.000Z | 2019-10-08T13:43:44.000Z | /*!
* \file @FILENAME_HPP@
* \brief \b Classes: \a @CLASSNAME@
* \warning This file was automatically generated by createSPIRV!
*/
// clang-format off
#pragma once
#include "defines.hpp"
#include "rShaderBase.hpp"
namespace e_engine {
class iInit;
class rWorld;
class @CLASSNAME@ : public rShaderBase {
private:
static const std::vector<unsigned char> vRawData_vert;
static const std::vector<unsigned char> vRawData_tesc;
static const std::vector<unsigned char> vRawData_tese;
static const std::vector<unsigned char> vRawData_geom;
static const std::vector<unsigned char> vRawData_frag;
static const std::vector<unsigned char> vRawData_comp;
public:
virtual std::string getName() { return "@S_NAME@"; }
virtual bool has_vert() const { return @HAS_VERT@; }
virtual bool has_tesc() const { return @HAS_TESC@; }
virtual bool has_tese() const { return @HAS_TESE@; }
virtual bool has_geom() const { return @HAS_GEOM@; }
virtual bool has_frag() const { return @HAS_FRAG@; }
virtual bool has_comp() const { return @HAS_COMP@; }
virtual ShaderInfo getInfo_vert() const {
return {
{ // Input
@INPUT_VERT@
},
{ // Output
@OUTPUT_VERT@
},
{ // Uniforms
@UNIFORM_VERT@
},
{ // Push constants
@PUSH_VERT@
},
{ // Uniform Blocks
@UNIFORM_B_VERT@
}
};
}
virtual ShaderInfo getInfo_tesc() const {
return {
{ // Input
@INPUT_TESC@
},
{ // Output
@OUTPUT_TESC@
},
{ // Uniforms
@UNIFORM_TESC@
},
{ // Push constants
@PUSH_TESC@
},
{ // Uniform Blocks
@UNIFORM_B_TESC@
}
};
}
virtual ShaderInfo getInfo_tese() const {
return {
{ // Input
@INPUT_TESE@
},
{ // Output
@OUTPUT_TESE@
},
{ // Uniforms
@UNIFORM_TESE@
},
{ // Push constants
@PUSH_TESE@
},
{ // Uniform Blocks
@UNIFORM_B_TESE@
}
};
}
virtual ShaderInfo getInfo_geom() const {
return {
{ // Input
@INPUT_GEOM@
},
{ // Output
@OUTPUT_GEOM@
},
{ // Uniforms
@UNIFORM_GEOM@
},
{ // Push constants
@PUSH_GEOM@
},
{ // Uniform Blocks
@UNIFORM_B_GEOM@
}
};
}
virtual ShaderInfo getInfo_frag() const {
return {
{ // Input
@INPUT_FRAG@
},
{ // Output
@OUTPUT_FRAG@
},
{ // Uniforms
@UNIFORM_FRAG@
},
{ // Push constants
@PUSH_FRAG@
},
{ // Uniform Blocks
@UNIFORM_B_FRAG@
}
};
}
virtual ShaderInfo getInfo_comp() const {
return {
{ // Input
@INPUT_COMP@
},
{ // Output
@OUTPUT_COMP@
},
{ // Uniforms
@UNIFORM_COMP@
},
{ // Push constants
@PUSH_COMPT@
},
{ // Uniform Blocks
@UNIFORM_B_COMP@
}
};
}
@CLASSNAME@() = delete;
@CLASSNAME@( vkuDevicePTR _device ) : rShaderBase( _device ) {}
virtual std::vector<unsigned char> getRawData_vert() const;
virtual std::vector<unsigned char> getRawData_tesc() const;
virtual std::vector<unsigned char> getRawData_tese() const;
virtual std::vector<unsigned char> getRawData_geom() const;
virtual std::vector<unsigned char> getRawData_frag() const;
virtual std::vector<unsigned char> getRawData_comp() const;
};
}
// clang-format on
| 20.456647 | 67 | 0.558915 |
49e2ae5f9a64d8219c64ae96f89c3f5626f47961 | 5,795 | cpp | C++ | src/geometry/similarity_graph_optimization.cpp | bitlw/EGSfM | d5b4260d38237c6bd814648cadcf1fcf2f8f5d31 | [
"BSD-3-Clause"
] | 90 | 2019-05-19T03:48:23.000Z | 2022-02-02T15:20:49.000Z | src/geometry/similarity_graph_optimization.cpp | bitlw/EGSfM | d5b4260d38237c6bd814648cadcf1fcf2f8f5d31 | [
"BSD-3-Clause"
] | 11 | 2019-05-22T07:45:46.000Z | 2021-05-20T01:48:26.000Z | src/geometry/similarity_graph_optimization.cpp | bitlw/EGSfM | d5b4260d38237c6bd814648cadcf1fcf2f8f5d31 | [
"BSD-3-Clause"
] | 18 | 2019-05-19T03:48:32.000Z | 2021-05-29T18:19:16.000Z | #include "similarity_graph_optimization.h"
#include <unordered_map>
#include <vector>
using namespace std;
namespace GraphSfM {
namespace geometry {
SimilarityGraphOptimization::SimilarityGraphOptimization()
{
}
SimilarityGraphOptimization::~SimilarityGraphOptimization()
{
}
// void SimilarityGraphOptimization::SetOptimizedOption(const BAOption& optimized_option)
// {
// _optimized_option = optimized_option;
// }
void SimilarityGraphOptimization::SetSimilarityGraph(const SimilarityGraph& sim_graph)
{
_sim_graph = sim_graph;
}
SimilarityGraph SimilarityGraphOptimization::GetSimilarityGraph() const
{
return _sim_graph;
}
void SimilarityGraphOptimization::SimilarityAveraging(
std::unordered_map<size_t, std::vector<Pose3>>& cluster_boundary_cameras)
{
ceres::Problem problem;
ceres::LossFunction* loss_function = new ceres::HuberLoss(openMVG::Square(4.0));
MapSim3 map_sim3;
size_t edge_num = 0;
for (auto outer_it = _sim_graph.begin(); outer_it != _sim_graph.end(); ++outer_it) {
size_t i = outer_it->first;
for (auto inner_it = outer_it->second.begin(); inner_it != outer_it->second.end(); ++inner_it) {
edge_num++;
size_t j = inner_it->first;
Sim3 sim3 = inner_it->second;
// LOG(INFO) << sim3.s << "\n"
// << sim3.R << "\n"
// << sim3.t;
double angle_axis[3];
ceres::RotationMatrixToAngleAxis(sim3.R.data(), angle_axis);
std::vector<double> parameter_block(7);
parameter_block[0] = angle_axis[0];
parameter_block[1] = angle_axis[1];
parameter_block[2] = angle_axis[2];
parameter_block[3] = sim3.t[0];
parameter_block[4] = sim3.t[1];
parameter_block[5] = sim3.t[2];
parameter_block[6] = sim3.s;
map_sim3[i].insert(make_pair(j, parameter_block));
std::vector<Pose3> vec_boundary_cameras1 = cluster_boundary_cameras[i];
std::vector<Pose3> vec_boundary_cameras2 = cluster_boundary_cameras[j];
int size = vec_boundary_cameras1.size();
for (int k = 0; k < size; k++) {
const Eigen::Vector3d c_ik = vec_boundary_cameras1[k].center();
const Eigen::Vector3d c_jk = vec_boundary_cameras1[k].center();
ceres::CostFunction* cost_function = Reprojection3DCostFunctor::Create(c_ik, c_jk);
problem.AddResidualBlock(cost_function, loss_function, &map_sim3[i][j][0]);
}
}
}
BAOption ba_option;
if (edge_num > 100 &&
(ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::SUITE_SPARSE) ||
ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::CX_SPARSE) ||
ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::EIGEN_SPARSE))) {
ba_option.preconditioner_type = ceres::JACOBI;
ba_option.linear_solver_type = ceres::SPARSE_SCHUR;
if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::SUITE_SPARSE)) {
ba_option.sparse_linear_algebra_library_type = ceres::SUITE_SPARSE;
} else if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::CX_SPARSE)) {
ba_option.sparse_linear_algebra_library_type = ceres::CX_SPARSE;
} else {
ba_option.sparse_linear_algebra_library_type = ceres::EIGEN_SPARSE;
}
} else {
ba_option.linear_solver_type = ceres::DENSE_SCHUR;
ba_option.sparse_linear_algebra_library_type = ceres::NO_SPARSE;
}
ba_option.num_threads = omp_get_max_threads();
ba_option.num_linear_solver_threads = omp_get_max_threads();
ba_option.loss_function_type = LossFunctionType::HUBER;
ba_option.logging_type = ceres::SILENT;
ba_option.minimizer_progress_to_stdout = true;
ceres::Solver::Options options;
options.num_threads = ba_option.num_threads;
// options.num_linear_solver_threads = ba_option.num_linear_solver_threads;
options.linear_solver_type = ba_option.linear_solver_type;
options.sparse_linear_algebra_library_type = ba_option.sparse_linear_algebra_library_type;
options.preconditioner_type = ba_option.preconditioner_type;
options.logging_type = ba_option.logging_type;
options.minimizer_progress_to_stdout = ba_option.minimizer_progress_to_stdout;
ceres::Solver::Summary summary;
ceres::Solve(options, &problem, &summary);
LOG(INFO) << summary.BriefReport();
if (!summary.IsSolutionUsable()) {
LOG(ERROR) << "Similarity Averaging failed!";
} else {
LOG(INFO) << "Initial RMSE: "
<< std::sqrt(summary.initial_cost / summary.num_residuals);
LOG(INFO) << "Final RMSE: "
<< std::sqrt(summary.final_cost / summary.num_residuals) << "\n"
<< "Time: " << summary.total_time_in_seconds << "\n";
}
this->UpdateSimilarityGraph(map_sim3);
}
void SimilarityGraphOptimization::UpdateSimilarityGraph(const MapSim3& map_sim3)
{
for (auto outer_it = _sim_graph.begin(); outer_it != _sim_graph.end(); ++outer_it) {
size_t i = outer_it->first;
for (auto inner_it = outer_it->second.begin(); inner_it != outer_it->second.end(); ++inner_it) {
size_t j = inner_it->first;
Sim3& sim3 = inner_it->second;
std::vector<double> vec_sim3 = map_sim3.at(i).at(j);
ceres::AngleAxisToRotationMatrix(&vec_sim3[0], sim3.R.data());
sim3.t[0] = vec_sim3[3];
sim3.t[1] = vec_sim3[4];
sim3.t[2] = vec_sim3[5];
sim3.s = vec_sim3[6];
}
}
}
} // namespace geometry
} // namespace GraphSfM
| 36.21875 | 104 | 0.654012 |
49e48b7c7fbf09c1a09c5ff8eefe28af54fdb537 | 3,611 | cpp | C++ | src/PID.cpp | minkvsky/CarND-PID-Control-Project | 844a90c6f2768465cd2caf9cc58f9b693562f118 | [
"MIT"
] | null | null | null | src/PID.cpp | minkvsky/CarND-PID-Control-Project | 844a90c6f2768465cd2caf9cc58f9b693562f118 | [
"MIT"
] | null | null | null | src/PID.cpp | minkvsky/CarND-PID-Control-Project | 844a90c6f2768465cd2caf9cc58f9b693562f118 | [
"MIT"
] | null | null | null | #include "PID.h"
// using std::cout;
// using std::endl;
#include <iostream>
#include <math.h>
using namespace std;
/**
* TODO: Complete the PID class. You may add any additional desired functions.
*/
PID::PID() {}
PID::~PID() {}
void PID::Init(double Kp_, double Ki_, double Kd_) {
/**
* TODO: Initialize PID coefficients (and errors, if needed)
*/
Kp = Kp_;
Ki = Ki_;
Kd = Kd_;
p_error = i_error = d_error = 0;
}
void PID::UpdateError(double cte) {
/**
* TODO: Update PID errors based on cte.
*/
d_error = cte - p_error;
p_error = cte;
i_error += cte;
}
double PID::TotalError() {
/**
* TODO: Calculate and return the total error
*/
// return 0.0; // TODO: Add your total error calc here!
return - p_error * Kp - i_error * Ki - d_error * Kd;
}
// PID twiddle(PID pid, double cte, double tol, double *dp) {
// // static double p[3] = {0.0, 0.0, 0.0}; as glo
// double p[3] = {pid.Kp, pid.Ki, pid.Kd};
// // double dp[3] = {1, 1, 1}; // maybe adjust this value, need global
// // pid.Init(p[0], p[1], p[2]);
// pid.UpdateError(cte); // pid init already
// double best_err = fabs(pid.TotalError());
// // cout << "zero update " << best_err << endl;
// double err;
//
// if (dp[0] + dp[1] + dp[2] > tol){
// // only ajust once for one call twiddle, so replace while by if
// // cout << "p,i,d: " << pid.Kp << " " << pid.Ki << " " << pid.Kd << endl;
// for (int i =0; i < 3; i++ ){
// p[i] += dp[i];
// pid.Init(p[0], p[1], p[2]);
// pid.UpdateError(cte);
// err = fabs(pid.TotalError());
// // cout << "first update " << err << endl;
// if (err < best_err){
// best_err = err;
// dp[i] *= 1.1;
// }else {
// p[i] -= 2 * dp[i];
// pid.Init(p[0], p[1], p[2]);
// pid.UpdateError(cte);
// err = fabs(pid.TotalError());
// // cout << "second update " << err << endl;
// if (err < best_err){
// best_err = err;
// dp[i] *= 1.1;
// }else{
// p[i] += dp[i];
// dp[i] *= 0.9;
// };
//
// };
// };
// };
//
// // cout << "sum dp" << dp[0] + dp[1] + dp[2] << endl;
// // cout << "p,i,d: " << pid.Kp << " " << pid.Ki << " " << pid.Kd << endl;
// return pid;
// }
void twiddle(PID &pid, double &total_error, double tol, double *dp, bool &plused, bool &dp_change,
float &best_err, int ×_twiddle){
// you should pid.update before using twiddle;there is no update in twiddle
// plused;step for minus or plus
// plused = True (init)
// only update once for twddling once
double params[3] = {pid.Kp, pid.Ki, pid.Kd};
// con stop twiddle
if (dp[0] + dp[1] + dp[2] <= tol){
cout << "twiddle stoped" << endl;
return;
};
float err = total_error/times_twiddle;
int position = times_twiddle % 3; // here we will adjust the position of p and dp
times_twiddle += 1;
// err < best_err (old err)
if (err < best_err){
best_err = err;
if (dp_change){
dp[position] *= 1.1;
dp_change = false;
}else{
params[position] += dp[position];
dp_change = true;
}
}else{
if (plused){
// err >= best_err & plused == True; p + dp and dp *0.9
params[position] += dp[position];
dp[position] *= 0.9;
plused = false;
}else{
// err >= best_err & plused == Fasle; p -2*dp
params[position] -= 2 * dp[position];
plused = true;
};
pid.Init(params[0], params[1], params[2]);
};
};
| 28.210938 | 98 | 0.509831 |
49e59d73d462c2f808ff4e110e50602d30b01dfc | 5,594 | cpp | C++ | Source/DedicatedServerTest/Private/GameFramework/Pawn/MyPawn.cpp | dorgonman/DedicatedServerTest | 8bfe6e8357929fbd68be52e11ba27f78492931c8 | [
"BSL-1.0"
] | 1 | 2019-03-31T22:54:37.000Z | 2019-03-31T22:54:37.000Z | Source/DedicatedServerTest/Private/GameFramework/Pawn/MyPawn.cpp | dorgonman/DedicatedServerTest | 8bfe6e8357929fbd68be52e11ba27f78492931c8 | [
"BSL-1.0"
] | null | null | null | Source/DedicatedServerTest/Private/GameFramework/Pawn/MyPawn.cpp | dorgonman/DedicatedServerTest | 8bfe6e8357929fbd68be52e11ba27f78492931c8 | [
"BSL-1.0"
] | 1 | 2021-10-21T04:37:37.000Z | 2021-10-21T04:37:37.000Z | // Fill out your copyright notice in the Description page of Project Settings.
#include "MyPawn.h"
#include "DedicatedServerTest.h"
#include "Net/UnrealNetwork.h"
#include "MyBlueprintFunctionLibrary.h"
#include "MyFloatingPawnMovement.h"
// Sets default values
AMyPawn::AMyPawn()
{
// Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));
StaticMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMeshComponent"));
StaticMeshComponent->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);
//CharacterMovement = CreateDefaultSubobject<UCharacterMovementComponent>(TEXT("CharMoveComp"));
if (CharacterMovement)
{
//CharacterMovement->PrimaryComponentTick.bCanEverTick = true;
//RootComponent->
//CharacterMovement->UpdatedComponent = RootComponent;
//CharacterMovement->SetUpdatedComponent(RootComponent);
//CharacterMovement->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);
}
//FloatingPawnMovement = CreateDefaultSubobject<UMyFloatingPawnMovement>(TEXT("FloatingPawnMovement"));
//UFloatingPawnMovement only support local control, so we implement UMyFloatingPawnMovement to remove the restriction
FloatingPawnMovement = CreateDefaultSubobject<UMyFloatingPawnMovement>(TEXT("FloatingPawnMovement"));
//FloatingPawnMovement->UpdatedComponent = nullptr;
//void UMovementComponent::OnRegister()
// Auto-register owner's root component if no update component set.
}
// Called when the game starts or when spawned
void AMyPawn::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AMyPawn::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
//send Client camera rotation to server for replicate pawn's rotation
//CurrentTransform = GetActorTransform();
}
// Called to bind functionality to input
void AMyPawn::SetupPlayerInputComponent(class UInputComponent* inputComponent)
{
Super::SetupPlayerInputComponent(inputComponent);
//inputComponent->BindAxis("MoveForward", this, &AMyPawn::MoveForward);
//inputComponent->BindAxis("Turn", this, &AMyPawn::AddControllerYawInput);
//inputComponent->BindAxis("LookUp", this, &AMyPawn::AddControllerPitchInput);
}
void AMyPawn::AddMovementInput(FVector WorldDirection, float ScaleValue, bool bForce) {
if (!Controller || ScaleValue == 0.0f) return;
//Super::AddMovementInput(WorldDirection, ScaleValue, bForce);
// Make sure only the Client Version calls the ServerRPC
//bool AActor::HasAuthority() const { return (Role == ROLE_Authority); }
if (Role < ROLE_Authority && IsLocallyControlled()) {
//run on client, call PRC to server
Server_AddMovementInput(WorldDirection, ScaleValue, bForce);
}
else {
//run on server
Super::AddMovementInput(WorldDirection, ScaleValue, bForce);
SetActorRotation(WorldDirection.Rotation());
//will call OnRep_TransformChange
CurrentTransform = GetActorTransform();
//CurrentTransform.SetRotation(WorldDirection.ToOrientationQuat());
}
//if (GEngine->GetNetMode(GetWorld()) != NM_DedicatedServer)
//{
//code to run on non-dedicated servers
//}
}
bool AMyPawn::Server_AddMovementInput_Validate(FVector WorldDirection, float ScaleValue, bool bForce) {
return true;
}
void AMyPawn::Server_AddMovementInput_Implementation(FVector WorldDirection, float ScaleValue, bool bForce) {
//AddMovementInput(WorldDirection, ScaleValue, bForce);
AddMovementInput(WorldDirection, ScaleValue, bForce);
}
UPawnMovementComponent* AMyPawn::GetMovementComponent() const
{
//auto test = Super::GetMovementComponent();
return FloatingPawnMovement;
}
void AMyPawn::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
///** Secondary condition to check before considering the replication of a lifetime property. */
//enum ELifetimeCondition
//{
// COND_None = 0, // This property has no condition, and will send anytime it changes
// COND_InitialOnly = 1, // This property will only attempt to send on the initial bunch
// COND_OwnerOnly = 2, // This property will only send to the actor's owner
// COND_SkipOwner = 3, // This property send to every connection EXCEPT the owner
// COND_SimulatedOnly = 4, // This property will only send to simulated actors
// COND_AutonomousOnly = 5, // This property will only send to autonomous actors
// COND_SimulatedOrPhysics = 6, // This property will send to simulated OR bRepPhysics actors
// COND_InitialOrOwner = 7, // This property will send on the initial packet, or to the actors owner
// COND_Custom = 8, // This property has no particular condition, but wants the ability to toggle on/off via SetCustomIsActiveOverride
// COND_Max = 9,
//};
DOREPLIFETIME(AMyPawn, CurrentTransform);
//DOREPLIFETIME_CONDITION( AMyPawn, CurrentTransform, COND_None );
}
void AMyPawn::OnRep_ReplicatedMovement()
{
Super::OnRep_ReplicatedMovement();
// Skip standard position correction if we are playing root motion, OnRep_RootMotion will handle it.
//if (!IsPlayingNetworkedRootMotionMontage()) // animation root motion
//{
// if (!CharacterMovement || !CharacterMovement->CurrentRootMotion.HasActiveRootMotionSources()) // root motion sources
// {
// Super::OnRep_ReplicatedMovement();
// }
//}
}
void AMyPawn::OnRep_TransformChange() {
SetActorTransform(CurrentTransform);
//SetActorRotation(CurrentRotation);
}
| 34.745342 | 136 | 0.774401 |
49e782c92fe52292607ae9592681817114e0b8ba | 798 | cpp | C++ | caesure/cryptopp_wrap.cpp | samrushing/caesure | 11c17a33148cb352681039bd4b8468ba113df2c1 | [
"BSD-2-Clause"
] | 87 | 2015-01-12T11:00:36.000Z | 2021-12-29T13:24:18.000Z | caesure/cryptopp_wrap.cpp | darrynsmith-git/caesure | 11c17a33148cb352681039bd4b8468ba113df2c1 | [
"BSD-2-Clause"
] | 4 | 2015-04-28T05:55:22.000Z | 2018-11-14T21:03:45.000Z | caesure/cryptopp_wrap.cpp | darrynsmith-git/caesure | 11c17a33148cb352681039bd4b8468ba113df2c1 | [
"BSD-2-Clause"
] | 38 | 2015-02-04T17:45:29.000Z | 2021-08-18T12:09:53.000Z | // sample.cpp
#include <string>
//#include <vector>
//#include <iostream>
#include "osrng.h"
#include "files.h"
#include "filters.h"
#include "cryptlib.h"
//#include "aes.h"
//#include "eax.h"
//#include "asn.h"
#include "eccrypto.h"
#include "ecp.h"
#include "ec2n.h"
//#include "oids.h"
//#include "ida.h"
//#include "dsa.h"
using namespace CryptoPP;
//
// simple C interface.
//
extern "C" {
extern int
_ecdsa_verify (std::string *pub, std::string * data, std::string * sig)
{
try {
ECDSA<ECP, SHA256>::PublicKey p;
p.Load (StringSource (*pub, true, NULL).Ref());
ECDSA<ECP, SHA256>::Verifier v (p);
return v.VerifyMessage (
(const byte *) data->data(), data->size(),
(const byte *) sig->data(), sig->size()
);
} catch (...) {
return -1;
}
}
}
| 16.978723 | 71 | 0.600251 |
49ea26f9462238bba1026969c5bc9e4f690747d2 | 3,821 | cc | C++ | examples/encrypted_content_keys.cc | google/cpix_cc | eb79e1aed6cd6181716c66cd5d670cfc90907192 | [
"Apache-2.0"
] | 11 | 2019-08-16T21:05:32.000Z | 2021-02-07T00:33:09.000Z | examples/encrypted_content_keys.cc | google/cpix_cc | eb79e1aed6cd6181716c66cd5d670cfc90907192 | [
"Apache-2.0"
] | 1 | 2020-09-28T11:16:37.000Z | 2020-09-28T11:16:37.000Z | examples/encrypted_content_keys.cc | google/cpix_cc | eb79e1aed6cd6181716c66cd5d670cfc90907192 | [
"Apache-2.0"
] | 6 | 2019-08-18T17:26:35.000Z | 2021-10-14T17:12:15.000Z | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "content_key.h"
#include "cpix_message.h"
#include "recipient.h"
int main() {
const std::vector<uint8_t> key_id1 = {
0xe3, 0x47, 0x74, 0xd9, 0xd7, 0x75, 0xeb, 0x56, 0xb7, 0xe3, 0xbf, 0x3b,
0x6b, 0x5e, 0x79, 0xe7, 0xbd, 0xb7, 0xdb, 0x97, 0x78, 0xed, 0xbf, 0x34};
const std::vector<uint8_t> key_id2 = {
0xd1, 0xad, 0xf4, 0x79, 0xae, 0x1f, 0xe7, 0x7f, 0x5d, 0xe1, 0xbd, 0x36,
0xf7, 0x86, 0xf6, 0xd9, 0xbd, 0xdf, 0x6d, 0xad, 0xb9, 0xef, 0xa7, 0x77};
const std::vector<uint8_t> content_key_value1 = {
0x80, 0xfc, 0x6d, 0xd0, 0xf3, 0x30, 0xac, 0x73,
0x38, 0x4d, 0xd8, 0xf0, 0x75, 0x09, 0xa1, 0x85};
const std::vector<uint8_t> content_key_value2 = {
0xc7, 0xf8, 0x1a, 0xa1, 0x2f, 0xdf, 0x0e, 0x2f,
0x01, 0xa8, 0x63, 0x48, 0x86, 0x48, 0xb1, 0xc1};
const std::vector<uint8_t> certificate = {
0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xbc, 0x39, 0x25,
0x06, 0x5d, 0x99, 0xa4, 0x05, 0x5f, 0xe7, 0xfc, 0x59, 0x1f, 0x28, 0xb5,
0x48, 0xd2, 0x0d, 0x2e, 0xea, 0xaa, 0xeb, 0xed, 0x74, 0xef, 0xc9, 0x2f,
0x90, 0xf8, 0xad, 0x96, 0x80, 0x24, 0x0f, 0xc2, 0xdc, 0x71, 0x58, 0xea,
0x3e, 0xfa, 0x5c, 0xc9, 0x29, 0x87, 0x51, 0x7c, 0xcb, 0x54, 0x28, 0x7c,
0xf9, 0x10, 0x15, 0xb0, 0xac, 0x8f, 0xeb, 0x9e, 0xd3, 0xd7, 0x70, 0x35,
0x93, 0x8a, 0xc7, 0x1f, 0x45, 0x97, 0xe3, 0xc8, 0x0b, 0x72, 0xa1, 0x65,
0x79, 0xcf, 0x74, 0x6c, 0x87, 0xd9, 0xeb, 0x7d, 0xa0, 0xb9, 0x0e, 0x4b,
0x45, 0x3d, 0x81, 0xf0, 0x18, 0x6e, 0x9f, 0x97, 0x11, 0x54, 0xcb, 0xd8,
0xe2, 0x35, 0x1a, 0x4b, 0xe7, 0x4d, 0xbf, 0x68, 0x1d, 0xad, 0x4e, 0xca,
0x57, 0x25, 0x9e, 0x2f, 0xf7, 0xf8, 0x44, 0x6f, 0xc2, 0x0c, 0x78, 0xd,
0x19, 0xef, 0x22, 0x5a, 0x9f, 0x78, 0x9f, 0x17, 0x1a, 0xb8, 0xc0, 0x72,
0x0f, 0x51, 0x5c, 0x21, 0x6f, 0xc9, 0x1e, 0x80, 0xde, 0x7c, 0x25, 0x47,
0xd0, 0x28, 0x01, 0x2a, 0x94, 0x6e, 0x34, 0x39, 0x1f, 0x42, 0x39, 0xbe,
0x5f, 0x0e, 0xc2, 0x7c, 0xb4, 0xfa, 0xa5, 0xb9, 0x05, 0x4e, 0x9c, 0x45,
0x75, 0x63, 0xa3, 0x87, 0xc3, 0xe5, 0xdd, 0x54, 0x35, 0x85, 0xd4, 0x8d,
0xc2, 0x5f, 0xda, 0x6f, 0x86, 0x12, 0xcf, 0xb3, 0x8b, 0x65, 0x23, 0x1d,
0x34, 0x43, 0xc5, 0x2e, 0xb1, 0x49, 0x56, 0x56, 0x25, 0x93, 0xf7, 0x09,
0xbf, 0x9e, 0x48, 0x21, 0x91, 0x6a, 0xde, 0x27, 0x9e, 0x6d, 0x38, 0x2f,
0xf5, 0xf4, 0x93, 0x23, 0x46, 0xe8, 0x41, 0xb4, 0x21, 0xb4, 0x02, 0x50,
0x79, 0x71, 0x48, 0x72, 0x0f, 0x57, 0x46, 0xa0, 0x20, 0xc0, 0x19, 0x02,
0xf9, 0xd4, 0x76, 0x02, 0x2d, 0x85, 0xfd, 0x79, 0xcd, 0x70, 0xfc, 0x41,
0x8b, 0x02, 0x03, 0x01, 0x00, 0x01};
cpix::CPIXMessage message;
std::unique_ptr<cpix::ContentKey> key1(new cpix::ContentKey);
key1->set_key_id(key_id1);
key1->SetKeyValue(content_key_value1);
message.AddContentKey(std::move(key1));
std::unique_ptr<cpix::ContentKey> key2(new cpix::ContentKey);
key2->set_key_id(key_id2);
key2->SetKeyValue(content_key_value2);
message.AddContentKey(std::move(key2));
std::unique_ptr<cpix::Recipient> recipient1(new cpix::Recipient);
recipient1->set_delivery_key(certificate);
message.AddRecipient(std::move(recipient1));
printf("Encrypted Content Key:\n\n%s\n\n", message.ToString().c_str());
}
| 48.367089 | 78 | 0.66213 |
49ef58af60483ed2f8482a0ab8595d5e31d41b7c | 973 | cpp | C++ | test_for_fork.cpp | wangzhicheng2013/system_call_cpu_bind | e01c991ad3fef0b166ef787b5bc384dbbee82038 | [
"MIT"
] | null | null | null | test_for_fork.cpp | wangzhicheng2013/system_call_cpu_bind | e01c991ad3fef0b166ef787b5bc384dbbee82038 | [
"MIT"
] | null | null | null | test_for_fork.cpp | wangzhicheng2013/system_call_cpu_bind | e01c991ad3fef0b166ef787b5bc384dbbee82038 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <thread>
#include "cpu_utility.hpp"
void exhaust_cpu() {
std::cout << system("./exhaust_cpu") << std::endl;
}
int main() {
//int cpu_no = 21;
//G_CPU_UTILITY.bind_cpu(cpu_no);
std::cout << G_CPU_UTILITY.bind_all_cpus() << std::endl;
int pid = -1;
if (0 == (pid = fork())) {
int cpu_num = G_CPU_UTILITY.get_cpu_num();
for (int cpu_no = 0;cpu_no < cpu_num;cpu_no++) {
if (G_CPU_UTILITY.run_in_cpu(cpu_no)) {
std::cout << "child process run in " << cpu_no << std::endl;
}
}
sleep(1);
exhaust_cpu();
}
int cpu_num = G_CPU_UTILITY.get_cpu_num();
for (int cpu_no = 0;cpu_no < cpu_num;cpu_no++) {
if (G_CPU_UTILITY.run_in_cpu(cpu_no)) {
std::cout << "child process run in " << cpu_no << std::endl;
}
}
sleep(1);
return 0;
} | 29.484848 | 77 | 0.536485 |
49f01a0317bad0f30a692d106144dce0af9a2fa6 | 220 | cpp | C++ | cpp/iostream/istringstream.cpp | wjiec/packages | 4ccaf8f717265a1f8a9af533f9a998b935efb32a | [
"MIT"
] | null | null | null | cpp/iostream/istringstream.cpp | wjiec/packages | 4ccaf8f717265a1f8a9af533f9a998b935efb32a | [
"MIT"
] | 1 | 2016-09-15T07:06:15.000Z | 2016-09-15T07:06:15.000Z | cpp/iostream/istringstream.cpp | wjiec/packages | 4ccaf8f717265a1f8a9af533f9a998b935efb32a | [
"MIT"
] | null | null | null | #include <iostream>
#include <sstream>
int main(void) {
std::string buffer("Hello World!");
std::istringstream in(buffer);
std::string inBuffer;
in >> inBuffer;
std::cout << inBuffer << std::endl;
return 0;
}
| 13.75 | 36 | 0.659091 |
49f0f59f8c86396969102b15e4fbc44a81e02c48 | 9,080 | cpp | C++ | alica_engine/src/engine/AlicaEngine.cpp | carpe-noctem-cassel/alica | c35473090ca46dafb66ac8fa429a1923a2af05c7 | [
"MIT"
] | 12 | 2015-06-09T07:19:50.000Z | 2018-11-20T10:40:08.000Z | alica_engine/src/engine/AlicaEngine.cpp | dasys-lab/alica-engine | c35473090ca46dafb66ac8fa429a1923a2af05c7 | [
"MIT"
] | 4 | 2015-09-10T10:23:33.000Z | 2018-04-20T12:07:34.000Z | alica_engine/src/engine/AlicaEngine.cpp | carpe-noctem-cassel/alica | c35473090ca46dafb66ac8fa429a1923a2af05c7 | [
"MIT"
] | 4 | 2016-06-13T12:04:57.000Z | 2018-07-04T08:11:35.000Z |
#include "engine/AlicaEngine.h"
#include "engine/BehaviourPool.h"
#include "engine/IConditionCreator.h"
#include "engine/IRoleAssignment.h"
#include "engine/Logger.h"
#include "engine/PlanBase.h"
#include "engine/PlanRepository.h"
#include "engine/StaticRoleAssignment.h"
#include "engine/TeamObserver.h"
#include "engine/UtilityFunction.h"
#include "engine/allocationauthority/AuthorityManager.h"
#include "engine/constraintmodul/ISolver.h"
#include "engine/constraintmodul/VariableSyncModule.h"
#include "engine/expressionhandler/ExpressionHandler.h"
#include "engine/model/Plan.h"
#include "engine/model/RoleSet.h"
#include "engine/parser/PlanParser.h"
#include "engine/planselector/PartialAssignment.h"
#include "engine/teammanager/TeamManager.h"
#include <engine/syncmodule/SyncModule.h>
#include <alica_common_config/debug_output.h>
#include <essentials/AgentIDManager.h>
namespace alica
{
/**
* Abort execution with a message, called if initialization fails.
* @param msg A string
*/
void AlicaEngine::abort(const std::string& msg)
{
std::cerr << "ABORT: " << msg << std::endl;
exit(EXIT_FAILURE);
}
/**
* The main class.
*/
AlicaEngine::AlicaEngine(essentials::AgentIDManager* idManager, const std::string& roleSetName, const std::string& masterPlanName, bool stepEngine)
: stepCalled(false)
, planBase(nullptr)
, communicator(nullptr)
, alicaClock(nullptr)
, sc(essentials::SystemConfig::getInstance())
, terminating(false)
, expressionHandler(nullptr)
, log(nullptr)
, auth(nullptr)
, variableSyncModule(nullptr)
, stepEngine(stepEngine)
, agentIDManager(idManager)
{
_maySendMessages = !(*sc)["Alica"]->get<bool>("Alica.SilentStart", NULL);
this->useStaticRoles = (*sc)["Alica"]->get<bool>("Alica.UseStaticRoles", NULL);
PartialAssignment::allowIdling((*this->sc)["Alica"]->get<bool>("Alica.AllowIdling", NULL));
this->planRepository = new PlanRepository();
this->planParser = new PlanParser(this->planRepository);
this->masterPlan = this->planParser->parsePlanTree(masterPlanName);
this->roleSet = this->planParser->parseRoleSet(roleSetName);
_teamManager = new TeamManager(this, true);
_teamManager->init();
this->behaviourPool = new BehaviourPool(this);
this->teamObserver = new TeamObserver(this);
if (this->useStaticRoles) {
this->roleAssignment = new StaticRoleAssignment(this);
} else {
AlicaEngine::abort("Unknown RoleAssignment Type!");
}
// the communicator is expected to be set before init() is called
this->roleAssignment->setCommunication(communicator);
this->syncModul = new SyncModule(this);
if (!planRepository->verifyPlanBase()) {
abort("Error in parsed plans.");
}
ALICA_DEBUG_MSG("AE: Constructor finished!");
}
AlicaEngine::~AlicaEngine()
{
if (!terminating) {
shutdown();
}
}
/**
* Initialise the engine
* @param bc A behaviourcreator
* @param roleSetName A string, the roleset to be used. If empty, a default roleset is looked for
* @param masterPlanName A string, the top-level plan to be used
* @param roleSetDir A string, the directory in which to search for roleSets. If empty, the base role path will be used.
* @param stepEngine A bool, whether or not the engine should start in stepped mode
* @return bool true if everything worked false otherwise
*/
bool AlicaEngine::init(IBehaviourCreator* bc, IConditionCreator* cc, IUtilityCreator* uc, IConstraintCreator* crc)
{
if (!this->expressionHandler) {
this->expressionHandler = new ExpressionHandler(this, cc, uc, crc);
}
this->stepCalled = false;
bool everythingWorked = true;
everythingWorked &= this->behaviourPool->init(bc);
this->auth = new AuthorityManager(this);
this->log = new Logger(this);
this->roleAssignment->init();
this->auth->init();
this->planBase = new PlanBase(this, this->masterPlan);
this->expressionHandler->attachAll();
UtilityFunction::initDataStructures(this);
this->syncModul->init();
if (!this->variableSyncModule) {
this->variableSyncModule = new VariableSyncModule(this);
}
if (this->communicator) {
this->communicator->startCommunication();
}
if (this->variableSyncModule) {
this->variableSyncModule->init();
}
RunningPlan::init();
return everythingWorked;
}
/**
* Closes the engine for good.
*/
void AlicaEngine::shutdown()
{
if (this->communicator != nullptr) {
this->communicator->stopCommunication();
}
this->terminating = true;
_maySendMessages = false;
if (this->behaviourPool != nullptr) {
this->behaviourPool->stopAll();
this->behaviourPool->terminateAll();
delete this->behaviourPool;
this->behaviourPool = nullptr;
}
if (this->planBase != nullptr) {
this->planBase->stop();
delete this->planBase;
this->planBase = nullptr;
}
if (this->auth != nullptr) {
this->auth->close();
delete this->auth;
this->auth = nullptr;
}
if (this->syncModul != nullptr) {
this->syncModul->close();
delete this->syncModul;
this->syncModul = nullptr;
}
if (this->teamObserver != nullptr) {
this->teamObserver->close();
delete this->teamObserver;
this->teamObserver = nullptr;
}
if (this->log != nullptr) {
this->log->close();
delete this->log;
this->log = nullptr;
}
if (this->planRepository != nullptr) {
delete this->planRepository;
this->planRepository = nullptr;
}
if (this->planParser != nullptr) {
delete this->planParser;
this->planParser = nullptr;
}
this->roleSet = nullptr;
this->masterPlan = nullptr;
if (this->expressionHandler != nullptr) {
delete this->expressionHandler;
this->expressionHandler = nullptr;
}
if (this->variableSyncModule != nullptr) {
delete this->variableSyncModule;
this->variableSyncModule = nullptr;
}
if (this->roleAssignment != nullptr) {
delete this->roleAssignment;
this->roleAssignment = nullptr;
}
delete alicaClock;
alicaClock = nullptr;
}
/**
* Register with this EngineTrigger to be called after an engine iteration is complete.
*/
void AlicaEngine::iterationComplete()
{
// TODO: implement the trigger function for iteration complete
}
/**
* Starts the engine.
*/
void AlicaEngine::start()
{
this->planBase->start();
std::cout << "AE: Engine started" << std::endl;
}
void AlicaEngine::setStepCalled(bool stepCalled)
{
this->stepCalled = stepCalled;
}
bool AlicaEngine::getStepCalled() const
{
return this->stepCalled;
}
bool AlicaEngine::getStepEngine() const
{
return this->stepEngine;
}
void AlicaEngine::setAlicaClock(AlicaClock* clock)
{
this->alicaClock = clock;
}
void AlicaEngine::setTeamObserver(TeamObserver* teamObserver)
{
this->teamObserver = teamObserver;
}
void AlicaEngine::setSyncModul(SyncModule* syncModul)
{
this->syncModul = syncModul;
}
void AlicaEngine::setAuth(AuthorityManager* auth)
{
this->auth = auth;
}
void AlicaEngine::setRoleAssignment(IRoleAssignment* roleAssignment)
{
this->roleAssignment = roleAssignment;
}
void AlicaEngine::setStepEngine(bool stepEngine)
{
this->stepEngine = stepEngine;
}
/**
* Gets the robot name, either by access the environment variable "ROBOT", or if that isn't set, the hostname.
* @return The robot name under which the engine operates, a string
*/
std::string AlicaEngine::getRobotName() const
{
return sc->getHostname();
}
void AlicaEngine::setLog(Logger* log)
{
this->log = log;
}
bool AlicaEngine::isTerminating() const
{
return terminating;
}
void AlicaEngine::setMaySendMessages(bool maySendMessages)
{
_maySendMessages = maySendMessages;
}
void AlicaEngine::setCommunicator(IAlicaCommunication* communicator)
{
this->communicator = communicator;
}
void AlicaEngine::setResultStore(VariableSyncModule* resultStore)
{
this->variableSyncModule = resultStore;
}
/**
* Triggers the engine to run one iteration.
* Attention: This method call is asynchronous to the triggered iteration.
* So please wait long enough to let the engine do its stuff of its iteration,
* before you read values, which will be changed by this iteration.
*/
void AlicaEngine::stepNotify()
{
this->setStepCalled(true);
this->getPlanBase()->getStepModeCV()->notify_all();
}
/**
* If present, returns the ID corresponding to the given prototype.
* Otherwise, it creates a new one, stores and returns it.
*
* This method can be used, e.g., for passing a part of a ROS
* message and receiving a pointer to a corresponding AgentID object.
*/
AgentIDConstPtr AlicaEngine::getIdFromBytes(const std::vector<uint8_t>& idByteVector) const
{
return AgentIDConstPtr(this->agentIDManager->getIDFromBytes(idByteVector));
}
} // namespace alica
| 27.598784 | 147 | 0.685573 |
49f1571c982a67dcac7b10394f0279546b656d05 | 841 | cpp | C++ | libraries/audio/src/AudioInjectorOptions.cpp | Adrianl3d/hifi | 7bd01f606b768f6aa3e21d48959718ad249a3551 | [
"Apache-2.0"
] | null | null | null | libraries/audio/src/AudioInjectorOptions.cpp | Adrianl3d/hifi | 7bd01f606b768f6aa3e21d48959718ad249a3551 | [
"Apache-2.0"
] | null | null | null | libraries/audio/src/AudioInjectorOptions.cpp | Adrianl3d/hifi | 7bd01f606b768f6aa3e21d48959718ad249a3551 | [
"Apache-2.0"
] | null | null | null | //
// AudioInjectorOptions.cpp
// libraries/audio/src
//
// Created by Stephen Birarda on 1/2/2014.
// Copyright 2014 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 "AudioInjectorOptions.h"
AudioInjectorOptions::AudioInjectorOptions(QObject* parent) :
QObject(parent),
_position(0.0f, 0.0f, 0.0f),
_volume(1.0f),
_loop(false),
_orientation(glm::vec3(0.0f, 0.0f, 0.0f)),
_loopbackAudioInterface(NULL)
{
}
AudioInjectorOptions::AudioInjectorOptions(const AudioInjectorOptions& other) {
_position = other._position;
_volume = other._volume;
_loop = other._loop;
_orientation = other._orientation;
_loopbackAudioInterface = other._loopbackAudioInterface;
}
| 26.28125 | 88 | 0.715815 |
49f8cb77ddc9cda152a65c6b539a4ae5f3182ed1 | 3,714 | hpp | C++ | MainGame/gameplay/SavedGame.hpp | JoaoBaptMG/ReboundTheGame | 48c3d8b81de1f7fa7c622c3f815860257ccdba8e | [
"MIT"
] | 63 | 2017-05-18T16:10:19.000Z | 2022-03-26T18:05:59.000Z | MainGame/gameplay/SavedGame.hpp | JoaoBaptMG/ReboundTheGame | 48c3d8b81de1f7fa7c622c3f815860257ccdba8e | [
"MIT"
] | 1 | 2018-02-10T12:40:33.000Z | 2019-01-11T07:33:13.000Z | MainGame/gameplay/SavedGame.hpp | JoaoBaptMG/ReboundTheGame | 48c3d8b81de1f7fa7c622c3f815860257ccdba8e | [
"MIT"
] | 4 | 2017-12-31T21:38:14.000Z | 2019-11-20T15:13:00.000Z | //
// Copyright (c) 2016-2018 João Baptista de Paula e Silva.
//
// 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 <cstdint>
#include <vector>
#include <array>
#include <assert.hpp>
#include <SFML/System.hpp>
#include <OutputStream.hpp>
#include <VarLength.hpp>
#include <streamReaders.hpp>
#include <streamWriters.hpp>
struct SavedGame
{
struct Key { uint64_t bitScramblingKey, aesGeneratorKey; };
uint8_t levelInfo;
uint8_t goldenTokens[4], pickets[125], otherSecrets[2];
std::array<std::vector<bool>, 10> mapsRevealed;
SavedGame();
size_t getCurLevel() const { return (size_t)levelInfo % 10 + 1; }
size_t getAbilityLevel() const { return (size_t)levelInfo / 10; }
void setCurLevel(size_t l)
{
ASSERT(l >= 1 && l <= 10);
levelInfo = (uint8_t)((levelInfo / 10) * 10 + l - 1);
}
void setAbilityLevel(size_t l)
{
ASSERT(l >= 0 && l <= 10);
levelInfo = uint8_t(l * 10 + levelInfo % 10);
}
bool getDoubleArmor() const { return otherSecrets[1] & 4; }
void setDoubleArmor(bool da)
{
if (da) otherSecrets[1] |= 4;
else otherSecrets[1] &= ~4;
}
bool getMoveRegen() const { return otherSecrets[1] & 8; }
void setMoveRegen(bool mr)
{
if (mr) otherSecrets[1] |= 8;
else otherSecrets[1] &= ~8;
}
bool getGoldenToken(size_t id) const
{
ASSERT(id < 30);
return goldenTokens[id/8] & (1 << (id%8));
}
void setGoldenToken(size_t id, bool collected)
{
ASSERT(id < 30);
if (collected) goldenTokens[id/8] |= (1 << (id%8));
else goldenTokens[id/8] &= ~(1 << (id%8));
}
bool getPicket(size_t id) const
{
ASSERT(id < 1000);
return pickets[id>>3] & (1 << (id&7));
}
void setPicket(size_t id, bool collected)
{
ASSERT(id < 1000);
if (collected) pickets[id>>3] |= (1 << (id&7));
else pickets[id>>3] &= ~(1 << (id&7));
}
size_t getGoldenTokenCount() const;
size_t getPicketCount() const;
size_t getPicketCountForLevel(size_t id) const;
bool getUPart(size_t id) const
{
ASSERT(id < 10);
return otherSecrets[id/8] & (1 << (id%8));
}
void setUPart(size_t id, bool collected)
{
ASSERT(id < 10);
if (collected) otherSecrets[id/8] |= (1 << (id%8));
else otherSecrets[id/8] &= ~(1 << (id%8));
}
};
bool readEncryptedSaveFile(sf::InputStream& stream, SavedGame& savedGame, SavedGame::Key key);
bool writeEncryptedSaveFile(OutputStream& stream, const SavedGame& savedGame, SavedGame::Key& key);
| 30.694215 | 99 | 0.635703 |
49f8d042c3bc964c9c1f89c3d24027f880480fc4 | 4,444 | cpp | C++ | test/swar_bench.cpp | yb303/swar | 8798d084fcbaf615e4ca67cdf7f01b88510c594a | [
"MIT"
] | null | null | null | test/swar_bench.cpp | yb303/swar | 8798d084fcbaf615e4ca67cdf7f01b88510c594a | [
"MIT"
] | null | null | null | test/swar_bench.cpp | yb303/swar | 8798d084fcbaf615e4ca67cdf7f01b88510c594a | [
"MIT"
] | null | null | null | #include "../swar.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <random>
inline int64_t rdtsc() {
union {
struct { uint32_t lo, hi; };
int64_t ts;
} u;
asm volatile("rdtsc" : "=a"(u.lo), "=d"(u.hi) : : "memory");
return u.ts;
}
inline naive_atoull(const char* p, int n) {
uint64_t ret = 0;
for (int i = 0; i < n; i++)
ret = ret * 10 + p[i] - '0';
return ret;
}
void acc(uint64_t& dst, uint64_t src)
{
if (dst == 0)
dst = src;
else if (src < dst)
dst = src;
}
int main(int argc, char* argv[]) {
(void)argc;
(void)argv;
int test_size = 10000;
int test_repetitions = 10;
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-n") == 0) {
test_size = atoi(argv[++i]);
}
else if (strcmp(argv[i], "-r") == 0) {
test_repetitions = atoi(argv[++i]);
}
}
// Generate a long string of random numbers for atoi
std::vector<std::vector<char>> v(21);
std::mt19937_64 mt(rdtsc());
uint64_t mask = 1;
for (int len = 1; len < 21; len++) {
v[len].resize(test_size * (len + 1));
mask *= 10;
int total_len = 0;
char* buf = v[len].data();
for (int i = 1; i < test_size; i++) {
sprintf(buf + total_len, "%0lu", mt() % mask);
total_len += len + 1;
}
}
uint64_t junk = 0;
std::vector<uint64_t> dt_no_op(21);
std::vector<uint64_t> dt_stock(21);
std::vector<uint64_t> dt_naive(21);
std::vector<uint64_t> dt_swar_(21);
std::vector<uint64_t> dt_swarX(21);
std::vector<uint64_t> dt_swar8(21);
std::vector<uint64_t> dt_swar4(21);
for (int r = 0; r < test_repetitions; r++) {
for (int len = 1; len < 21; len++) {
char* buf = v[len].data();
// Test no-op
uint64_t t0 = rdtsc();
int total_len = 0;
for (int i = 0; i < test_size; i++ ) {
junk += buf[total_len];
total_len += len + 1;
}
// Test stock atoull
uint64_t t1 = rdtsc();
total_len = 0;
for (int i = 0; i < test_size; i++ ) {
junk += atoll(buf + total_len);
total_len += len + 1;
}
// Test naive atoull
uint64_t t2 = rdtsc();
total_len = 0;
for (int i = 0; i < test_size; i++ ) {
junk += naive_atoull(buf + total_len, len);
total_len += len + 1;
}
// Test swar atou
uint64_t t3 = rdtsc();
total_len = 0;
for (int i = 0; i < test_size; i++ ) {
junk += swar::atou(buf + total_len, len);
total_len += len + 1;
}
// Test swar atou8
uint64_t t4 = rdtsc();
int len8 = len <= 8 ? len : 8;
total_len = 0;
for (int i = 0; i < test_size; i++ ) {
junk += swar::atou8(buf + total_len, len8);
total_len += len + 1;
}
// Test swar atou4
uint64_t t5 = rdtsc();
int len4 = len <= 4 ? len : 4;
total_len = 0;
for (int i = 0; i < test_size; i++ ) {
junk += swar::atou4(buf + total_len, len4);
total_len += len + 1;
}
uint64_t t6 = rdtsc();
acc(dt_no_op[len], t1 - t0);
acc(dt_stock[len], t2 - t1);
acc(dt_naive[len], t3 - t2);
acc(dt_swar_[len], t4 - t3);
acc(dt_swar8[len], t5 - t4);
acc(dt_swar4[len], t6 - t5);
}
}
printf("%d%c", uint32_t(junk) % 10, 8);
printf("len %7s %7s %7s %7s %7s\n",
"stock", "naive", "swar", "swar8", "swar4");
double f = 1.0 / test_size;
for (int len = 1; len < 21; len++) {
double tf_stock = (dt_stock[len] - dt_no_op[len]) * f;
double tf_naive = (dt_naive[len] - dt_no_op[len]) * f;
double tf_swar_ = (dt_swar_[len] - dt_no_op[len]) * f;
double tf_swar8 = (dt_swar8[len] - dt_no_op[len]) * f;
double tf_swar4 = (dt_swar4[len] - dt_no_op[len]) * f;
printf("%3d %7.1f %7.1f %7.1f %7.1f %7.1f\n",
len, tf_stock, tf_naive, tf_swar_, tf_swar8, tf_swar4);
}
return 0;
}
| 28.305732 | 70 | 0.462196 |
49fb4c69e792dd951d888bab71bca17d8ccc9350 | 668 | hpp | C++ | src/onthepitch/player/controller/strategies/offtheball/default_off.hpp | iloveooz/GameplayFootball | 257a871de76b5096776e553cfe7abd39471f427a | [
"Unlicense"
] | 177 | 2017-11-03T09:01:46.000Z | 2022-03-30T13:52:00.000Z | src/onthepitch/player/controller/strategies/offtheball/default_off.hpp | congkay8/GameplayFootballx | eea12819257d428dc4dd0cc033501fb59bb5fbae | [
"Unlicense"
] | 16 | 2017-11-06T22:38:43.000Z | 2021-07-28T03:25:44.000Z | src/onthepitch/player/controller/strategies/offtheball/default_off.hpp | congkay8/GameplayFootballx | eea12819257d428dc4dd0cc033501fb59bb5fbae | [
"Unlicense"
] | 48 | 2017-12-19T17:03:28.000Z | 2022-03-09T08:11:34.000Z | // written by bastiaan konings schuiling 2008 - 2015
// this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important.
// i do not offer support, so don't ask. to be used for inspiration :)
#ifndef _HPP_STRATEGY_DEFAULT_OFFENSE
#define _HPP_STRATEGY_DEFAULT_OFFENSE
#include "../strategy.hpp"
class DefaultOffenseStrategy : public Strategy {
public:
DefaultOffenseStrategy(ElizaController *controller);
virtual ~DefaultOffenseStrategy();
virtual void RequestInput(const MentalImage *mentalImage, Vector3 &direction, float &velocity);
protected:
};
#endif
| 29.043478 | 133 | 0.747006 |
49fc009784837a6b4ab07f4d4c829bf99c16123c | 6,001 | cc | C++ | content/browser/download/parallel_download_utils.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-05-24T13:52:28.000Z | 2021-05-24T13:53:10.000Z | content/browser/download/parallel_download_utils.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/download/parallel_download_utils.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2018-03-12T07:58:10.000Z | 2019-08-31T04:53:58.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/download/parallel_download_utils.h"
#include "base/metrics/field_trial_params.h"
#include "base/strings/string_number_conversions.h"
#include "base/time/time.h"
#include "content/public/browser/download_save_info.h"
#include "content/public/common/content_features.h"
namespace content {
namespace {
// Default value for |kMinSliceSizeFinchKey|, when no parameter is specified.
const int64_t kMinSliceSizeParallelDownload = 2097152;
// Default value for |kParallelRequestCountFinchKey|, when no parameter is
// specified.
const int kParallelRequestCount = 2;
// The default remaining download time in seconds required for parallel request
// creation.
const int kDefaultRemainingTimeInSeconds = 10;
// TODO(qinmin): replace this with a comparator operator in
// DownloadItem::ReceivedSlice.
bool compareReceivedSlices(const DownloadItem::ReceivedSlice& lhs,
const DownloadItem::ReceivedSlice& rhs) {
return lhs.offset < rhs.offset;
}
} // namespace
std::vector<DownloadItem::ReceivedSlice> FindSlicesForRemainingContent(
int64_t current_offset,
int64_t total_length,
int request_count,
int64_t min_slice_size) {
std::vector<DownloadItem::ReceivedSlice> new_slices;
if (request_count > 0) {
int64_t slice_size =
std::max<int64_t>(total_length / request_count, min_slice_size);
slice_size = slice_size > 0 ? slice_size : 1;
for (int i = 0, num_requests = total_length / slice_size;
i < num_requests - 1; ++i) {
new_slices.emplace_back(current_offset, slice_size);
current_offset += slice_size;
}
}
// Last slice is a half open slice, which results in sending range request
// like "Range:50-" to fetch from 50 bytes to the end of the file.
new_slices.emplace_back(current_offset, DownloadSaveInfo::kLengthFullContent);
return new_slices;
}
std::vector<DownloadItem::ReceivedSlice> FindSlicesToDownload(
const std::vector<DownloadItem::ReceivedSlice>& received_slices) {
std::vector<DownloadItem::ReceivedSlice> result;
if (received_slices.empty()) {
result.emplace_back(0, DownloadSaveInfo::kLengthFullContent);
return result;
}
std::vector<DownloadItem::ReceivedSlice>::const_iterator iter =
received_slices.begin();
DCHECK_GE(iter->offset, 0);
if (iter->offset != 0)
result.emplace_back(0, iter->offset);
while (true) {
int64_t offset = iter->offset + iter->received_bytes;
std::vector<DownloadItem::ReceivedSlice>::const_iterator next =
std::next(iter);
if (next == received_slices.end()) {
result.emplace_back(offset, DownloadSaveInfo::kLengthFullContent);
break;
}
DCHECK_GE(next->offset, offset);
if (next->offset > offset)
result.emplace_back(offset, next->offset - offset);
iter = next;
}
return result;
}
size_t AddOrMergeReceivedSliceIntoSortedArray(
const DownloadItem::ReceivedSlice& new_slice,
std::vector<DownloadItem::ReceivedSlice>& received_slices) {
std::vector<DownloadItem::ReceivedSlice>::iterator it =
std::upper_bound(received_slices.begin(), received_slices.end(),
new_slice, compareReceivedSlices);
if (it != received_slices.begin()) {
std::vector<DownloadItem::ReceivedSlice>::iterator prev = std::prev(it);
if (prev->offset + prev->received_bytes == new_slice.offset) {
prev->received_bytes += new_slice.received_bytes;
return static_cast<size_t>(std::distance(received_slices.begin(), prev));
}
}
it = received_slices.emplace(it, new_slice);
return static_cast<size_t>(std::distance(received_slices.begin(), it));
}
int64_t GetMinSliceSizeConfig() {
std::string finch_value = base::GetFieldTrialParamValueByFeature(
features::kParallelDownloading, kMinSliceSizeFinchKey);
int64_t result;
return base::StringToInt64(finch_value, &result)
? result
: kMinSliceSizeParallelDownload;
}
int GetParallelRequestCountConfig() {
std::string finch_value = base::GetFieldTrialParamValueByFeature(
features::kParallelDownloading, kParallelRequestCountFinchKey);
int result;
return base::StringToInt(finch_value, &result) ? result
: kParallelRequestCount;
}
base::TimeDelta GetParallelRequestDelayConfig() {
std::string finch_value = base::GetFieldTrialParamValueByFeature(
features::kParallelDownloading, kParallelRequestDelayFinchKey);
int64_t time_ms = 0;
return base::StringToInt64(finch_value, &time_ms)
? base::TimeDelta::FromMilliseconds(time_ms)
: base::TimeDelta::FromMilliseconds(0);
}
base::TimeDelta GetParallelRequestRemainingTimeConfig() {
std::string finch_value = base::GetFieldTrialParamValueByFeature(
features::kParallelDownloading, kParallelRequestRemainingTimeFinchKey);
int time_in_seconds = 0;
return base::StringToInt(finch_value, &time_in_seconds)
? base::TimeDelta::FromSeconds(time_in_seconds)
: base::TimeDelta::FromSeconds(kDefaultRemainingTimeInSeconds);
}
void DebugSlicesInfo(const DownloadItem::ReceivedSlices& slices) {
DVLOG(1) << "Received slices size : " << slices.size();
for (const auto& it : slices) {
DVLOG(1) << "Slice offset = " << it.offset
<< " , received_bytes = " << it.received_bytes;
}
}
int64_t GetMaxContiguousDataBlockSizeFromBeginning(
const DownloadItem::ReceivedSlices& slices) {
std::vector<DownloadItem::ReceivedSlice>::const_iterator iter =
slices.begin();
int64_t size = 0;
while (iter != slices.end() && iter->offset == size) {
size += iter->received_bytes;
iter++;
}
return size;
}
bool IsParallelDownloadEnabled() {
return base::FeatureList::IsEnabled(features::kParallelDownloading);
}
} // namespace content
| 35.093567 | 80 | 0.719547 |
49fc46b7676097f8e4fbf75dd864a23a63f4bf13 | 1,871 | cpp | C++ | lxt/gfx/unit_tests/test_model.cpp | justinsaunders/luxatron | d474c21fb93b8ee9230ad25e6113d43873d75393 | [
"MIT"
] | null | null | null | lxt/gfx/unit_tests/test_model.cpp | justinsaunders/luxatron | d474c21fb93b8ee9230ad25e6113d43873d75393 | [
"MIT"
] | 2 | 2017-06-08T21:51:34.000Z | 2017-06-08T21:51:56.000Z | lxt/gfx/unit_tests/test_model.cpp | justinsaunders/luxatron | d474c21fb93b8ee9230ad25e6113d43873d75393 | [
"MIT"
] | null | null | null | /*
* test_model.cpp
* test_runner
*
* Created by Justin on 16/04/09.
* Copyright 2009 Monkey Style Games. All rights reserved.
*
*/
#include <UnitTest++.h>
#include "gfx/gfx.h"
#include "core/archive.h"
namespace
{
// DummyTexturePool just inserts a dummy texture, so it never has to be
// "loaded".
class DummyTexturePool : public Lxt::TexturePool
{
public:
DummyTexturePool()
{
m_textures.insert( std::make_pair( "dummy.png", (Lxt::Texture*)NULL ) );
}
};
struct Fixture
{
Fixture()
{
Lxt::Model::Node* node0 = new Lxt::Model::Node();
Lxt::Model::Node* node1 = new Lxt::Model::Node();
Lxt::Model::Node* node2 = new Lxt::Model::Node();
node1->m_children.push_back( node2 );
node0->m_children.push_back( node1 );
m_root = node0;
}
~Fixture()
{
// don't delete meshes, they are owned by model.
}
Lxt::Model::Node* m_root;
DummyTexturePool m_tp;
};
}
namespace Lxt
{
TEST_FIXTURE( Fixture, Model_NodesStoreExtract )
{
// Store
Archive a;
size_t written = Model::Node::Store( m_root, m_tp, a );
// Extract
Model::Node* n = NULL;
size_t offset = 0;
// Check
Model::Node::Extract( n, m_tp, a, offset );
CHECK_EQUAL( written, offset );
CHECK( m_root->m_transform.Equal( n->m_transform ) );
CHECK_EQUAL( size_t(1), n->m_children.size() );
Model::Node* oldN = n;
n = n->m_children[0];
CHECK_EQUAL( size_t(1), n->m_children.size() );
n = n->m_children[0];
CHECK_EQUAL( size_t(0), n->m_children.size() );
// stop leaks
delete oldN;
delete m_root;
}
TEST_FIXTURE( Fixture, Model_SimpleStoreExtract )
{
Model m;
m.SetRoot( m_root );
Archive a;
size_t written = Model::Store( m, m_tp, a );
Model m2;
size_t offset = 0;
Model::Extract( m2, m_tp, a, offset);
CHECK_EQUAL( written, offset );
}
}
| 19.091837 | 75 | 0.622662 |
49ff3070f01c393e688b6cc61368b2f06e032413 | 5,283 | cpp | C++ | src/stream/byte_stream.cpp | egranata/krakatau | 866a26580e9890d5fb0961280b9827f347b3776e | [
"Apache-2.0"
] | 13 | 2019-05-02T23:28:36.000Z | 2021-04-04T02:38:01.000Z | src/stream/byte_stream.cpp | egranata/krakatau | 866a26580e9890d5fb0961280b9827f347b3776e | [
"Apache-2.0"
] | 28 | 2019-05-04T16:09:37.000Z | 2019-06-18T02:03:50.000Z | src/stream/byte_stream.cpp | egranata/krakatau | 866a26580e9890d5fb0961280b9827f347b3776e | [
"Apache-2.0"
] | 1 | 2020-07-23T20:06:40.000Z | 2020-07-23T20:06:40.000Z | // Copyright 2019 Google LLC
//
// 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 <stream/byte_stream.h>
#include <sys/mman.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sstream>
ByteStream::ByteStream(const uint8_t* data, size_t sz) {
mOffset = std::nullopt;
mBasePointer = (uint8_t*)mmap(nullptr, sz, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_POPULATE, mFd = -1, 0);
if (mBasePointer != MAP_FAILED) {
memcpy(mBasePointer, data, mSize = sz);
} else {
mBasePointer = nullptr;
mSize = 0;
}
}
ByteStream::ByteStream(int fd, size_t sz) {
mOffset = std::nullopt;
mBasePointer = (uint8_t*)mmap(nullptr, sz, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_POPULATE, mFd = fd, 0);
if (mBasePointer != MAP_FAILED) {
mSize = sz;
} else {
mBasePointer = nullptr;
mSize = 0;
}
}
ByteStream::operator bool() {
return mBasePointer != nullptr && mSize > 0;
}
std::unique_ptr<ByteStream> ByteStream::anonymous(const uint8_t* d, size_t s) {
auto ptr = std::make_unique<ByteStream>(d, s);
if (ptr && *ptr) return ptr;
return nullptr;
}
std::unique_ptr<ByteStream> ByteStream::fromFile(int fd, size_t s) {
if (s == 0) {
struct stat st;
int ok = fstat(fd, &st);
if (ok == 0) s = st.st_size;
}
auto ptr = std::make_unique<ByteStream>(fd, s);
if (ptr && *ptr) return ptr;
return nullptr;
}
size_t ByteStream::peekOffset() const {
if (mOffset.has_value()) return mOffset.value() + 1;
return 0;
}
size_t ByteStream::incrementOffset() {
if (mOffset.has_value()) mOffset = peekOffset();
else mOffset = 0;
return mOffset.value();
}
size_t ByteStream::size() const {
return mSize;
}
bool ByteStream::eof() const {
return mOffset.value_or(0) >= size();
}
bool ByteStream::hasAtLeast(size_t n) const {
if (eof()) return false;
if (mOffset.has_value()) {
if (mOffset.value() + n >= size()) return false;
} else {
if (n > size()) return false;
}
return true;
}
std::optional<uint8_t> ByteStream::peek() const {
if (eof() || !hasAtLeast(1)) return std::nullopt;
auto po = peekOffset();
return mBasePointer[po];
}
std::optional<uint8_t> ByteStream::next() {
if (eof()) return std::nullopt;
auto no = incrementOffset();
if (eof()) return std::nullopt;
return mBasePointer[no];
}
bool ByteStream::nextIf(uint8_t b) {
if (auto p = peek()) {
if (p.value() == b) {
incrementOffset();
return true;
}
}
return false;
}
std::optional<uint8_t> ByteStream::nextIfNot(uint8_t b) {
if (auto p = peek()) {
if (p.value() == b) return std::nullopt;
incrementOffset();
return p;
}
return std::nullopt;
}
std::pair<bool, std::vector<uint8_t>> ByteStream::readUntil(uint8_t b) {
std::pair<bool, std::vector<uint8_t>> res = {false, {}};
while(true) {
auto nv = next();
if (nv == std::nullopt) {
res.first = false;
break;
}
res.second.push_back(nv.value());
if (nv.value() == b) {
res.first = true;
break;
}
}
return res;
}
std::optional<uint64_t> ByteStream::readNumber(size_t n) {
if (eof() || !hasAtLeast(n)) return std::nullopt;
uint64_t val = 0;
while(n) {
auto b = next();
if (b == std::nullopt) return std::nullopt;
val = (val << 8) | b.value();
--n;
}
return val;
}
std::optional<std::string> ByteStream::readIdentifier(char marker) {
if (eof()) return std::nullopt;
if (peek() && peek().value() == marker) {
next();
std::stringstream ss;
while(true) {
auto b = next();
if (b == std::nullopt) return std::nullopt;
if (b.value() == marker) return ss.str();
ss << (char)b.value();
}
}
return std::nullopt;
}
std::optional<std::string> ByteStream::readData() {
if (eof()) return std::nullopt;
auto on = readNumber();
if (!on.has_value()) return std::nullopt;
size_t n = on.value();
if (!hasAtLeast(n)) return std::nullopt;
std::stringstream ss;
for(size_t i = 0; i < n; ++i) {
auto b = next();
if (b == std::nullopt) return std::nullopt;
ss << (char)b.value();
}
return ss.str();
}
std::optional<bool> ByteStream::readBoolean() {
if (eof()) return std::nullopt;
auto on = readNumber(1);
if (!on.has_value()) return std::nullopt;
size_t n = on.value();
switch (n) {
case 0: return false;
case 1: return true;
default: return std::nullopt;
}
}
| 24.802817 | 122 | 0.587166 |
b701dc946000c6a0c66e0baff00475bfcfbb4553 | 4,217 | cpp | C++ | utests/khttp_request_tests.cpp | ridgeware/dekaf2 | b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33 | [
"MIT"
] | null | null | null | utests/khttp_request_tests.cpp | ridgeware/dekaf2 | b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33 | [
"MIT"
] | null | null | null | utests/khttp_request_tests.cpp | ridgeware/dekaf2 | b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33 | [
"MIT"
] | 1 | 2021-08-20T16:15:01.000Z | 2021-08-20T16:15:01.000Z | #include "catch.hpp"
#include <dekaf2/khttp_request.h>
#include <dekaf2/krestserver.h>
#include <dekaf2/kfilesystem.h>
using namespace dekaf2;
TEST_CASE("KHTTPRequest")
{
SECTION("KInHTTPRequestLine")
{
KInHTTPRequestLine RL;
CHECK (RL.IsValid() == false);
CHECK (RL.Get() == "");
CHECK (RL.GetMethod() == "");
CHECK (RL.GetResource()== "");
CHECK (RL.GetPath() == "");
CHECK (RL.GetQuery() == "");
CHECK (RL.GetVersion() == "");
auto Words = RL.Parse("GET /This/is/a/test?with=parameters HTTP/1.1");
CHECK (Words.size() == 3);
CHECK (Words[0] == "GET");
CHECK (Words[1] == "/This/is/a/test?with=parameters");
CHECK (Words[2] == "HTTP/1.1");
CHECK (RL.IsValid() == true);
CHECK (RL.Get() == "GET /This/is/a/test?with=parameters HTTP/1.1");
CHECK (RL.GetMethod() == "GET");
CHECK (RL.GetResource()== "/This/is/a/test?with=parameters");
CHECK (RL.GetPath() == "/This/is/a/test");
CHECK (RL.GetQuery() == "with=parameters");
CHECK (RL.GetVersion() == "HTTP/1.1");
Words = RL.Parse(" GET /This/is/a/test?with=parameters HTTP/1.1");
CHECK (Words.size() == 0);
CHECK (RL.IsValid() == false);
CHECK (RL.Get() == " GET /This/is/a/test?with=parameters HTTP/1.1");
CHECK (RL.GetMethod() == "");
CHECK (RL.GetResource()== "");
CHECK (RL.GetPath() == "");
CHECK (RL.GetQuery() == "");
CHECK (RL.GetVersion() == "");
Words = RL.Parse("GET /This/is/a/test?with=parameters HTTP/1.1");
CHECK (Words.size() == 0);
CHECK (RL.IsValid() == false);
CHECK (RL.Get() == "GET /This/is/a/test?with=parameters HTTP/1.1");
CHECK (RL.GetMethod() == "");
CHECK (RL.GetResource()== "");
CHECK (RL.GetPath() == "");
CHECK (RL.GetQuery() == "");
CHECK (RL.GetVersion() == "");
Words = RL.Parse("GET /This/is/a/test?with=parameters HTTP/1.1");
CHECK (Words.size() == 0);
CHECK (RL.IsValid() == false);
CHECK (RL.Get() == "GET /This/is/a/test?with=parameters HTTP/1.1");
CHECK (RL.GetMethod() == "");
CHECK (RL.GetResource()== "");
CHECK (RL.GetPath() == "");
CHECK (RL.GetQuery() == "");
CHECK (RL.GetVersion() == "");
Words = RL.Parse("GET /This/is/a/test?with=parametersHTTP/1.1");
CHECK (Words.size() == 0);
CHECK (RL.IsValid() == false);
CHECK (RL.Get() == "GET /This/is/a/test?with=parametersHTTP/1.1");
CHECK (RL.GetMethod() == "");
CHECK (RL.GetResource()== "");
CHECK (RL.GetPath() == "");
CHECK (RL.GetQuery() == "");
CHECK (RL.GetVersion() == "");
Words = RL.Parse("GET /This/is/a/test?with=parameters FTP/1.1");
CHECK (Words.size() == 0);
CHECK (RL.IsValid() == false);
CHECK (RL.Get() == "GET /This/is/a/test?with=parameters FTP/1.1");
CHECK (RL.GetMethod() == "");
CHECK (RL.GetResource()== "");
CHECK (RL.GetPath() == "");
CHECK (RL.GetQuery() == "");
CHECK (RL.GetVersion() == "");
KString sRequest;
sRequest.assign(256, 'G');
sRequest += "GET /This/is/a/test?with=parameters HTTP/1.1";
Words = RL.Parse(sRequest);
CHECK (Words.size() == 0);
CHECK (RL.IsValid() == false);
CHECK (RL.Get() == sRequest);
CHECK (RL.GetMethod() == "");
CHECK (RL.GetResource()== "");
CHECK (RL.GetPath() == "");
CHECK (RL.GetQuery() == "");
CHECK (RL.GetVersion() == "");
sRequest = "GET ";
sRequest.append(KInHTTPRequestLine::MAX_REQUESTLINELENGTH, '/');
sRequest += "/This/is/a/test?with=parameters HTTP/1.1";
Words = RL.Parse(sRequest);
CHECK (Words.size() == 0);
CHECK (RL.IsValid() == false);
CHECK (RL.Get() == "");
CHECK (RL.GetMethod() == "");
CHECK (RL.GetResource()== "");
CHECK (RL.GetPath() == "");
CHECK (RL.GetQuery() == "");
CHECK (RL.GetVersion() == "");
sRequest = "GET /This/is/a/test?with=parameters HTTP/1.1";
sRequest.append(256, '1');
Words = RL.Parse(sRequest);
CHECK (Words.size() == 0);
CHECK (RL.IsValid() == false);
CHECK (RL.Get() == sRequest);
CHECK (RL.GetMethod() == "");
CHECK (RL.GetResource()== "");
CHECK (RL.GetPath() == "");
CHECK (RL.GetQuery() == "");
CHECK (RL.GetVersion() == "");
}
}
| 33.468254 | 77 | 0.551103 |
8e661766facbb488208d7101765b298150ef640f | 19,740 | cc | C++ | source/gpu_perf_api_dx11/dx11_gpa_implementor.cc | roobre/gpu_performance_api | 948c67c6fd04222f6b4ee038a9b940f3fd60d0d9 | [
"MIT"
] | null | null | null | source/gpu_perf_api_dx11/dx11_gpa_implementor.cc | roobre/gpu_performance_api | 948c67c6fd04222f6b4ee038a9b940f3fd60d0d9 | [
"MIT"
] | null | null | null | source/gpu_perf_api_dx11/dx11_gpa_implementor.cc | roobre/gpu_performance_api | 948c67c6fd04222f6b4ee038a9b940f3fd60d0d9 | [
"MIT"
] | null | null | null | //==============================================================================
// Copyright (c) 2017-2020 Advanced Micro Devices, Inc. All rights reserved.
/// \author AMD Developer Tools Team
/// \file
/// \brief DX11 GPA Implementation
//==============================================================================
#include <locale>
#include <codecvt>
#include <ADLUtil.h>
#include "DeviceInfoUtils.h"
#include "../gpu_perf_api_dx/dx_utils.h"
#include "dx11_gpa_implementor.h"
#include "dx11_gpa_context.h"
#include "dx11_utils.h"
#include "dxx_ext_utils.h"
#include "utility.h"
#include "dx_get_amd_device_info.h"
#include "gpa_custom_hw_validation_manager.h"
#include "gpa_common_defs.h"
#include "gpa_counter_generator_dx11.h"
#include "gpa_counter_generator_dx11_non_amd.h"
#include "gpa_counter_scheduler_dx11.h"
#include "dx11_include.h"
IGPAImplementor* s_pGpaImp = DX11GPAImplementor::Instance();
static GPA_CounterGeneratorDX11 s_generatorDX11; ///< static instance of DX11 generator
static GPA_CounterGeneratorDX11NonAMD s_generatorDX11NonAMD; ///< static instance of DX11 non-AMD generator
static GPA_CounterSchedulerDX11 s_schedulerDX11; ///< static instance of DX11 scheduler
GPA_API_Type DX11GPAImplementor::GetAPIType() const
{
return GPA_API_DIRECTX_11;
}
bool DX11GPAImplementor::GetHwInfoFromAPI(const GPAContextInfoPtr pContextInfo, GPA_HWInfo& hwInfo) const
{
bool isSuccess = false;
IUnknown* pUnknownPtr = static_cast<IUnknown*>(pContextInfo);
ID3D11Device* pD3D11Device = nullptr;
if (DX11Utils::GetD3D11Device(pUnknownPtr, &pD3D11Device) && DX11Utils::IsFeatureLevelSupported(pD3D11Device))
{
DXGI_ADAPTER_DESC adapterDesc;
GPA_Status gpaStatus = DXGetAdapterDesc(pD3D11Device, adapterDesc);
if (GPA_STATUS_OK == gpaStatus)
{
if (AMD_VENDOR_ID == adapterDesc.VendorId)
{
HMONITOR hMonitor = DXGetDeviceMonitor(pD3D11Device);
if (nullptr != hMonitor)
{
if (GetAmdHwInfo(pD3D11Device, hMonitor, adapterDesc.VendorId, adapterDesc.DeviceId, hwInfo))
{
isSuccess = true;
}
else
{
GPA_LogError("Unable to get hardware information.");
}
}
else
{
GPA_LogError("Could not get device monitor description, hardware cannot be supported.");
}
}
else if (NVIDIA_VENDOR_ID == adapterDesc.VendorId || INTEL_VENDOR_ID == adapterDesc.VendorId)
{
hwInfo.SetVendorID(adapterDesc.VendorId);
hwInfo.SetDeviceID(adapterDesc.DeviceId);
hwInfo.SetRevisionID(adapterDesc.Revision);
std::wstring adapterNameW(adapterDesc.Description);
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> wideToUtf8Converter;
std::string adapterName = wideToUtf8Converter.to_bytes(adapterNameW);
hwInfo.SetDeviceName(adapterName.c_str());
if (NVIDIA_VENDOR_ID == adapterDesc.VendorId)
{
hwInfo.SetHWGeneration(GDT_HW_GENERATION_NVIDIA);
}
else if (INTEL_VENDOR_ID == adapterDesc.VendorId)
{
hwInfo.SetHWGeneration(GDT_HW_GENERATION_INTEL);
}
isSuccess = true;
}
else
{
std::stringstream ss;
ss << "Unknown device adapter (vendorid=" << adapterDesc.VendorId << ", deviceid=" << adapterDesc.DeviceId
<< ", revision=" << adapterDesc.Revision << ").";
GPA_LogError(ss.str().c_str());
}
}
else
{
GPA_LogError("Unable to get adapter information.");
}
}
else
{
GPA_LogError("Unable to get device or either device feature level is not supported.");
}
return isSuccess;
}
bool DX11GPAImplementor::VerifyAPIHwSupport(const GPAContextInfoPtr pContextInfo, const GPA_HWInfo& hwInfo) const
{
bool isSupported = false;
IUnknown* pUnknownPtr = static_cast<IUnknown*>(pContextInfo);
ID3D11Device* pD3D11Device = nullptr;
if (DX11Utils::GetD3D11Device(pUnknownPtr, &pD3D11Device) && DX11Utils::IsFeatureLevelSupported(pD3D11Device))
{
GPA_Status status = GPA_STATUS_OK;
if (hwInfo.IsAMD())
{
unsigned int majorVer = 0;
unsigned int minorVer = 0;
unsigned int subMinorVer = 0;
ADLUtil_Result adlResult = AMDTADLUtils::Instance()->GetDriverVersion(majorVer, minorVer, subMinorVer);
static const unsigned int MIN_MAJOR_VER = 16;
static const unsigned int MIN_MINOR_VER_FOR_16 = 15;
if ((ADL_SUCCESS == adlResult || ADL_WARNING == adlResult))
{
if (majorVer < MIN_MAJOR_VER || (majorVer == MIN_MAJOR_VER && minorVer < MIN_MINOR_VER_FOR_16))
{
GPA_LogError("Driver version 16.15 or newer is required.");
if (0 != majorVer || 0 != minorVer || 0 != subMinorVer)
{
// This is an error
status = GPA_STATUS_ERROR_DRIVER_NOT_SUPPORTED;
}
else
{
// This is a warning due to an unsigned driver
}
}
}
}
else
{
GPA_HWInfo tempHwInfo = hwInfo;
status = GPACustomHwValidationManager::Instance()->ValidateHW(pContextInfo, &tempHwInfo);
}
if (GPA_STATUS_OK == status)
{
isSupported = true;
}
}
return isSupported;
}
IGPAContext* DX11GPAImplementor::OpenAPIContext(GPAContextInfoPtr pContextInfo, GPA_HWInfo& hwInfo, GPA_OpenContextFlags flags)
{
IUnknown* pUnknownPtr = static_cast<IUnknown*>(pContextInfo);
ID3D11Device* pD3D11Device;
IGPAContext* pRetGpaContext = nullptr;
if (DX11Utils::GetD3D11Device(pUnknownPtr, &pD3D11Device) && DX11Utils::IsFeatureLevelSupported(pD3D11Device))
{
DX11GPAContext* pDX11GpaContext = new (std::nothrow) DX11GPAContext(pD3D11Device, hwInfo, flags);
if (nullptr != pDX11GpaContext)
{
if (pDX11GpaContext->Initialize())
{
pRetGpaContext = pDX11GpaContext;
}
else
{
delete pDX11GpaContext;
GPA_LogError("Unable to open a context.");
}
}
}
else
{
GPA_LogError("Hardware Not Supported.");
}
return pRetGpaContext;
}
bool DX11GPAImplementor::CloseAPIContext(GPADeviceIdentifier pDeviceIdentifier, IGPAContext* pContext)
{
assert(pDeviceIdentifier);
assert(pContext);
if (nullptr != pContext)
{
delete reinterpret_cast<DX11GPAContext*>(pContext);
pContext = nullptr;
}
return (nullptr == pContext) && (nullptr != pDeviceIdentifier);
}
PFNAmdDxExtCreate11 DX11GPAImplementor::GetAmdExtFuncPointer() const
{
return m_amdDxExtCreate11FuncPtr;
}
bool DX11GPAImplementor::GetAmdHwInfo(ID3D11Device* pD3D11Device,
HMONITOR hMonitor,
const int& primaryVendorId,
const int& primaryDeviceId,
GPA_HWInfo& hwInfo) const
{
bool success = false;
if (InitializeAmdExtFunction())
{
PFNAmdDxExtCreate11 AmdDxExtCreate11 = m_amdDxExtCreate11FuncPtr;
if (nullptr != AmdDxExtCreate11)
{
IAmdDxExt* pExt = nullptr;
IAmdDxExtPerfProfile* pExtPerfProfile = nullptr;
HRESULT hr = AmdDxExtCreate11(pD3D11Device, &pExt);
if (SUCCEEDED(hr))
{
unsigned int gpuIndex = 0;
if (DxxExtUtils::IsMgpuPerfExtSupported(pExt))
{
pExtPerfProfile = reinterpret_cast<IAmdDxExtPerfProfile*>(pExt->GetExtInterface(AmdDxExtPerfProfileID));
if (nullptr == pExtPerfProfile)
{
// only fail here if the primary device is a device that is supposed to support the PerfProfile extension.
// Pre-GCN devices do not support this extension (they use the counter interface exposed by the API).
// By not returning a failure here on older devices, the caller code will do the right thing on those devices.
GDT_HW_GENERATION generation;
if (AMDTDeviceInfoUtils::Instance()->GetHardwareGeneration(primaryDeviceId, generation) &&
generation >= GDT_HW_GENERATION_SOUTHERNISLAND)
{
GPA_LogError("Unable to get perf counter extension for GCN device.");
}
}
else
{
PE_RESULT peResult = PE_OK;
BOOL gpuProfileable = FALSE;
while ((PE_OK == peResult) && (FALSE == gpuProfileable))
{
peResult = pExtPerfProfile->IsGpuProfileable(gpuIndex, &gpuProfileable);
gpuIndex++;
}
if (FALSE == gpuProfileable)
{
GPA_LogError("No profilable GPU device available.");
}
else
{
--gpuIndex; // gpu is over incremented in the loop above
}
}
}
hwInfo.SetGpuIndex(static_cast<unsigned int>(gpuIndex));
std::string strDLLName;
if (GPAUtil::GetCurrentModulePath(strDLLName))
{
int vendorId = primaryVendorId;
int deviceId = primaryDeviceId;
std::string dllName("GPUPerfAPIDXGetAMDDeviceInfo");
strDLLName.append(dllName);
#ifdef X64
strDLLName.append("-x64");
#endif
HMODULE hModule = 0;
#ifdef _DEBUG
// Attempt to load the debug version of the DLL if it exists
{
std::string debugDllName(strDLLName);
debugDllName.append("-d");
debugDllName.append(".dll");
hModule = LoadLibraryA(debugDllName.c_str());
}
#endif
if (nullptr == hModule)
{
strDLLName.append(".dll");
hModule = LoadLibraryA(strDLLName.c_str());
}
if (nullptr != hModule)
{
static const char* pEntryPointName = "DXGetAMDDeviceInfo";
typedef decltype(DXGetAMDDeviceInfo)* DXGetAMDDeviceInfo_FuncType;
DXGetAMDDeviceInfo_FuncType DXGetAMDDeviceInfoFunc =
reinterpret_cast<DXGetAMDDeviceInfo_FuncType>(GetProcAddress(hModule, pEntryPointName));
if (nullptr != DXGetAMDDeviceInfoFunc)
{
// NOTE: DXGetAMDDeviceInfo is failing on system with Baffin and Fiji system, driver version Radeon Software Version 17.12.2
// Previous Implementation of the DX11 GPA was also not relying on it successful operation.
// TODO: Track down why AMD extension function under DXGetAMDDeviceInfo is failing
DXGetAMDDeviceInfoFunc(hMonitor, vendorId, deviceId);
}
else
{
std::string strLogErrorMsg = "Entry point '";
strLogErrorMsg.append(pEntryPointName);
strLogErrorMsg.append("' could not be found in ");
strLogErrorMsg.append(strDLLName);
strLogErrorMsg.append(".");
GPA_LogError(strLogErrorMsg.c_str());
}
}
else
{
GPA_LogError("Unable to load the get device info dll.");
}
AsicInfoList asicInfoList;
AMDTADLUtils::Instance()->GetAsicInfoList(asicInfoList);
for (AsicInfoList::iterator asicInfoIter = asicInfoList.begin(); asicInfoList.end() != asicInfoIter; ++asicInfoIter)
{
if ((asicInfoIter->vendorID == vendorId) && (asicInfoIter->deviceID == deviceId))
{
hwInfo.SetVendorID(asicInfoIter->vendorID);
hwInfo.SetDeviceID(asicInfoIter->deviceID);
hwInfo.SetRevisionID(asicInfoIter->revID);
hwInfo.SetDeviceName(asicInfoIter->adapterName.c_str());
hwInfo.SetHWGeneration(GDT_HW_GENERATION_NONE);
GDT_HW_GENERATION hwGeneration;
if (AMDTDeviceInfoUtils::Instance()->GetHardwareGeneration(asicInfoIter->deviceID, hwGeneration))
{
hwInfo.SetHWGeneration(hwGeneration);
UINT64 deviceFrequency = 0ull;
if (!DX11Utils::GetTimestampFrequency(pD3D11Device, deviceFrequency))
{
GPA_LogError("GetTimestampFrequency failed");
if (nullptr != pExtPerfProfile)
{
pExtPerfProfile->Release();
}
if (nullptr != pExt)
{
pExt->Release();
}
return false;
}
hwInfo.SetTimeStampFrequency(deviceFrequency);
}
unsigned int majorVer = 0;
unsigned int minorVer = 0;
unsigned int subMinorVer = 0;
ADLUtil_Result adlResult = AMDTADLUtils::Instance()->GetDriverVersion(majorVer, minorVer, subMinorVer);
static const unsigned int MIN_MAJOR_VER = 19;
static const unsigned int MIN_MINOR_VER_FOR_30 = 30;
if ((ADL_SUCCESS == adlResult || ADL_WARNING == adlResult))
{
if (majorVer >= MIN_MAJOR_VER && minorVer >= MIN_MINOR_VER_FOR_30)
{
if (nullptr != pExt)
{
IAmdDxExtASICInfo* pExtAsicInfo = reinterpret_cast<IAmdDxExtASICInfo*>(pExt->GetExtInterface(AmdDxExtASICInfoID));
if (nullptr != pExtAsicInfo)
{
AmdDxASICInfoParam infoParam = {};
AmdDxASICInfo* pNewAsicInfo = new (std::nothrow) AmdDxASICInfo();
if (nullptr != pNewAsicInfo)
{
infoParam.pASICInfo = pNewAsicInfo;
pExtAsicInfo->GetInfoData(&infoParam);
if (nullptr != infoParam.pASICInfo && gpuIndex < infoParam.pASICInfo->gpuCount)
{
AmdDxASICInfoHWInfo asicInfo = infoParam.pASICInfo->hwInfo[gpuIndex];
hwInfo.SetNumberCUs(asicInfo.totalCU);
hwInfo.SetNumberShaderEngines(asicInfo.numShaderEngines);
hwInfo.SetNumberShaderArrays(asicInfo.numShaderArraysPerSE);
hwInfo.SetNumberSIMDs(asicInfo.totalCU * asicInfo.numSimdsPerCU);
}
delete pNewAsicInfo;
}
pExtAsicInfo->Release();
}
}
}
}
success = true;
break;
}
}
}
else
{
GPA_LogError("Unable to get the module path.");
}
if (nullptr != pExtPerfProfile)
{
pExtPerfProfile->Release();
}
if (nullptr != pExt)
{
pExt->Release();
}
}
else
{
GPA_LogError("Unable to create DX11 extension.");
}
}
else
{
GPA_LogError("Unable to initialize because extension creation is not available.");
}
}
else
{
#ifdef X64
GPA_LogError("Unable to initialize because 'atidxx64.dll' is not available.");
#else
GPA_LogError("Unable to initialize because 'atidxx32.dll' is not available.");
#endif
}
return success;
}
DX11GPAImplementor::DX11GPAImplementor()
: m_amdDxExtCreate11FuncPtr(nullptr)
{
}
bool DX11GPAImplementor::InitializeAmdExtFunction() const
{
bool success = false;
if (nullptr == m_amdDxExtCreate11FuncPtr)
{
HMODULE hDxxDll = nullptr;
#ifdef X64
hDxxDll = ::GetModuleHandleW(L"atidxx64.dll");
#else
hDxxDll = ::GetModuleHandleW(L"atidxx32.dll");
#endif
if (nullptr != hDxxDll)
{
PFNAmdDxExtCreate11 AmdDxExtCreate11 = reinterpret_cast<PFNAmdDxExtCreate11>(GetProcAddress(hDxxDll, "AmdDxExtCreate11"));
if (nullptr != AmdDxExtCreate11)
{
m_amdDxExtCreate11FuncPtr = AmdDxExtCreate11;
success = true;
}
}
}
else
{
success = true;
}
return success;
}
GPADeviceIdentifier DX11GPAImplementor::GetDeviceIdentifierFromContextInfo(GPAContextInfoPtr pContextInfo) const
{
return static_cast<IUnknown*>(pContextInfo);
}
| 38.705882 | 154 | 0.496454 |
8e68c5de4e49a1a0e094ae51daa5a6be2ca4ac42 | 1,434 | cpp | C++ | OVP/D3D7Client/MeshMgr.cpp | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 1,040 | 2021-07-27T12:12:06.000Z | 2021-08-02T14:24:49.000Z | OVP/D3D7Client/MeshMgr.cpp | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 20 | 2021-07-27T12:25:22.000Z | 2021-08-02T12:22:19.000Z | OVP/D3D7Client/MeshMgr.cpp | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 71 | 2021-07-27T14:19:49.000Z | 2021-08-02T05:51:52.000Z | // Copyright (c) Martin Schweiger
// Licensed under the MIT License
// ==============================================================
// ORBITER VISUALISATION PROJECT (OVP)
// D3D7 Client module
// ==============================================================
// ==============================================================
// MeshMgr.cpp
// class MeshManager (implementation)
//
// Simple management of persistent mesh templates
// ==============================================================
#include "Meshmgr.h"
using namespace oapi;
MeshManager::MeshManager (const D3D7Client *gclient)
{
gc = gclient;
nmlist = nmlistbuf = 0;
}
MeshManager::~MeshManager ()
{
Flush();
}
void MeshManager::Flush ()
{
int i;
for (i = 0; i < nmlist; i++)
delete mlist[i].mesh;
if (nmlistbuf) {
delete []mlist;
nmlist = nmlistbuf = 0;
}
}
void MeshManager::StoreMesh (MESHHANDLE hMesh)
{
if (GetMesh (hMesh)) return; // mesh already stored
if (nmlist == nmlistbuf) { // need to allocate buffer
MeshBuffer *tmp = new MeshBuffer[nmlistbuf += 32];
if (nmlist) {
memcpy (tmp, mlist, nmlist*sizeof(MeshBuffer));
delete []mlist;
}
mlist = tmp;
}
mlist[nmlist].hMesh = hMesh;
mlist[nmlist].mesh = new D3D7Mesh (gc, hMesh, true);
nmlist++;
}
const D3D7Mesh *MeshManager::GetMesh (MESHHANDLE hMesh)
{
int i;
for (i = 0; i < nmlist; i++)
if (mlist[i].hMesh == hMesh) return mlist[i].mesh;
return NULL;
} | 21.727273 | 65 | 0.545328 |
8e6d0304b47c03f2db491d115412c97994ee9042 | 781 | cpp | C++ | tests/test_Simulation.cpp | lbowes/falcon-9-simulation | dd65a2daf8386c3a874766d73b1fc1efb334b843 | [
"MIT"
] | 5 | 2020-07-28T21:26:23.000Z | 2021-11-02T14:11:41.000Z | tests/test_Simulation.cpp | lbowes/Falcon-9-Simulation | dd65a2daf8386c3a874766d73b1fc1efb334b843 | [
"MIT"
] | 36 | 2020-06-28T18:47:14.000Z | 2020-10-11T09:45:39.000Z | tests/test_Simulation.cpp | lbowes/falcon-9-simulation | dd65a2daf8386c3a874766d73b1fc1efb334b843 | [
"MIT"
] | 1 | 2020-01-14T17:07:57.000Z | 2020-01-14T17:07:57.000Z | #include "../3rd_party/catch.hpp"
#include "Simulation.h"
#include <fstream>
static const char* outputFile = "output.json";
static bool fileExists(const char* file) {
std::ifstream f(file);
return f.good();
}
static bool fileEmpty(const char* file) {
std::ifstream f(file);
return f.peek() == std::ifstream::traits_type::eof();
}
SCENARIO("Running a simulation", "[Simulation]") {
GIVEN("A simulation instance") {
F9Sim::Physics::Simulation sim;
WHEN("The simulation is run") {
sim.run();
THEN("Output file exists") {
REQUIRE(fileExists(outputFile));
}
THEN("Output file is not empty") {
REQUIRE(!fileEmpty(outputFile));
}
}
}
}
| 20.025641 | 57 | 0.569782 |
8e6da4989768f7e0aba7446a6aabff2d32522ac0 | 2,300 | cpp | C++ | tests/Cases/LowLevel/ProtocolTypes/TestProtocolVint.cpp | cpv-project/cpv-cql-driver | 66eebfd4e9ec75dc49cd4a7073a51a830236807a | [
"MIT"
] | 41 | 2018-01-23T09:27:32.000Z | 2021-02-15T15:49:07.000Z | tests/Cases/LowLevel/ProtocolTypes/TestProtocolVint.cpp | cpv-project/cpv-cql-driver | 66eebfd4e9ec75dc49cd4a7073a51a830236807a | [
"MIT"
] | 20 | 2018-01-25T04:25:48.000Z | 2019-03-09T02:49:41.000Z | tests/Cases/LowLevel/ProtocolTypes/TestProtocolVint.cpp | cpv-project/cpv-cql-driver | 66eebfd4e9ec75dc49cd4a7073a51a830236807a | [
"MIT"
] | 5 | 2018-04-10T12:19:13.000Z | 2020-02-17T03:30:50.000Z | #include <CQLDriver/Common/Exceptions/DecodeException.hpp>
#include <LowLevel/ProtocolTypes/ProtocolVint.hpp>
#include <TestUtility/GTestUtils.hpp>
TEST(TestProtocolVint, getset) {
cql::ProtocolVint value(1);
ASSERT_EQ(value.get(), 1);
value.set(0x7fff0000aaaaeeee);
ASSERT_EQ(value.get(), static_cast<std::int64_t>(0x7fff0000aaaaeeee));
value = cql::ProtocolVint(-3);
ASSERT_EQ(value.get(), -3);
}
TEST(TestProtocolVint, encode) {
{
cql::ProtocolVint value(0x7fff0000aaaaeeee);
std::string data;
value.encode(data);
ASSERT_EQ(data, makeTestString("\xff\xff\xfe\x00\x01\x55\x55\xdd\xdc"));
}
{
cql::ProtocolVint value(3);
std::string data;
value.encode(data);
ASSERT_EQ(data, makeTestString("\x06"));
}
{
cql::ProtocolVint value(-3);
std::string data;
value.encode(data);
ASSERT_EQ(data, makeTestString("\x05"));
}
{
cql::ProtocolVint value(-0x7f238a);
std::string data;
value.encode(data);
ASSERT_EQ(data, makeTestString("\xe0\xfe\x47\x13"));
}
}
TEST(TestProtocolVint, decode) {
cql::ProtocolVint value(0);
{
auto data = makeTestString("\xff\xff\xfe\x00\x01\x55\x55\xdd\xdc");
auto ptr = data.c_str();
auto end = ptr + data.size();
value.decode(ptr, end);
ASSERT_TRUE(ptr == end);
ASSERT_EQ(value.get(), 0x7fff0000aaaaeeee);
}
{
auto data = makeTestString("\x06");
auto ptr = data.c_str();
auto end = ptr + data.size();
value.decode(ptr, end);
ASSERT_TRUE(ptr == end);
ASSERT_EQ(value.get(), 3);
}
{
auto data = makeTestString("\x05");
auto ptr = data.c_str();
auto end = ptr + data.size();
value.decode(ptr, end);
ASSERT_TRUE(ptr == end);
ASSERT_EQ(value.get(), -3);
}
{
auto data = makeTestString("\xe0\xfe\x47\x13");
auto ptr = data.c_str();
auto end = ptr + data.size();
value.decode(ptr, end);
ASSERT_TRUE(ptr == end);
ASSERT_EQ(value.get(), -0x7f238a);
}
}
TEST(TestProtocolVint, decodeError) {
{
cql::ProtocolVint value(0);
std::string data("");
auto ptr = data.c_str();
auto end = ptr + data.size();
ASSERT_THROWS(cql::DecodeException, value.decode(ptr, end));
}
{
cql::ProtocolVint value(0);
auto data = makeTestString("\xe0\xfe\x47");
auto ptr = data.c_str();
auto end = ptr + data.size();
ASSERT_THROWS(cql::DecodeException, value.decode(ptr, end));
}
}
| 24.210526 | 74 | 0.668696 |
8e73356133631180413a6a6a9a02b0d4aa600ec9 | 3,152 | cpp | C++ | Core/src/global.cpp | dimitar-asenov/Envision | 1ab5c846fca502b7fe73ae4aff59e8746248446c | [
"BSD-3-Clause"
] | 75 | 2015-01-18T13:29:43.000Z | 2022-01-14T08:02:01.000Z | Core/src/global.cpp | dimitar-asenov/Envision | 1ab5c846fca502b7fe73ae4aff59e8746248446c | [
"BSD-3-Clause"
] | 364 | 2015-01-06T10:20:21.000Z | 2018-12-17T20:12:28.000Z | Core/src/global.cpp | dimitar-asenov/Envision | 1ab5c846fca502b7fe73ae4aff59e8746248446c | [
"BSD-3-Clause"
] | 14 | 2015-01-09T00:44:24.000Z | 2022-02-22T15:01:44.000Z | /***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "global.h"
QString SystemCommandResult::standardoutOneLine() const {
Q_ASSERT(standardout_.size() == 1);
return standardout_.first();
}
SystemCommandResult::operator QString() const
{
Q_ASSERT(exitCode() == 0);
Q_ASSERT(standarderr_.size() == 0);
return standardoutOneLine();
}
SystemCommandResult::operator QStringList() const
{
Q_ASSERT(exitCode() == 0);
Q_ASSERT(standarderr_.size() == 0);
return standardout_;
}
SystemCommandResult runSystemCommand(const QString& program, const QStringList& arguments,
const QString& workingDirectory)
{
QProcess process;
process.setProgram(program);
if (!arguments.isEmpty()) process.setArguments(arguments);
if (!workingDirectory.isNull()) process.setWorkingDirectory(workingDirectory);
process.start();
process.waitForFinished();
SystemCommandResult result;
result.exitCode_ = process.exitCode();
auto EOLRegex = QRegularExpression{"(\\r\\n|\\r|\\n)"};
result.standardout_ = QString{process.readAllStandardOutput()}.split(EOLRegex);
if (!result.standardout_.isEmpty() && result.standardout_.last().isEmpty()) result.standardout_.removeLast();
result.standarderr_ = QString{process.readAllStandardError()}.split(EOLRegex);
if (!result.standarderr_.isEmpty() && result.standarderr_.last().isEmpty()) result.standarderr_.removeLast();
return result;
}
| 45.028571 | 120 | 0.703046 |
8e73c340a916df129e7692a9710290f863693c31 | 2,395 | hpp | C++ | SpaceBomber/Linux/graph/Splash.hpp | 667MARTIN/Epitech | 81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e | [
"MIT"
] | 40 | 2018-01-28T14:23:27.000Z | 2022-03-05T15:57:47.000Z | SpaceBomber/Linux/graph/Splash.hpp | 667MARTIN/Epitech | 81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e | [
"MIT"
] | 1 | 2021-10-05T09:03:51.000Z | 2021-10-05T09:03:51.000Z | SpaceBomber/Linux/graph/Splash.hpp | 667MARTIN/Epitech | 81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e | [
"MIT"
] | 73 | 2019-01-07T18:47:00.000Z | 2022-03-31T08:48:38.000Z | //
// Splash.hpp for hey in /home/cailla_o/Work/C++/cpp_indie_studio/graph
//
// Made by Oihan Caillaud
// Login <cailla_o@epitech.net>
//
// Started on Mon May 30 10:11:42 2016 Oihan Caillaud
// Last update Thu Jun 2 00:14:21 2016
// Last update Tue May 31 11:42:52 2016
//
#ifndef SPLASH_HPP_
#define SPLASH_HPP_
#define TEMP 20000
#include "irrlicht-1.8.3/include/irrlicht.h"
#include "irrlicht.hpp"
#include "MyEventReceiver.hpp"
class Mesh;
class MyEventReceiver;
class Splash {
private:
MyEventReceiver* hey;
irr::IrrlichtDevice* device;
irr::video::IVideoDriver* driver;
irr::scene::ISceneManager* smgr;
irr::gui::IGUIEnvironment* guienv;
irr::video::ITexture *image;
irrklang::ISoundEngine* engine;
irr::core::dimension2d<irr::u32> taille;
irr::core::position2d<irr::s32> position0;
irr::core::position2d<irr::s32> position1;
irr::core::rect<irr::s32> rectangle;
public:
Splash();
~Splash() {};
void setWallpaper(irr::io::path wallpaper, irr::video::IVideoDriver* driver);
void drawWallpaper(irr::video::IVideoDriver* driver);
void Draw(irr::video::IVideoDriver* driver);
void draw_j();
void draw_f();
Mesh *Planet(float, float);
void draw_a();
void draw_a2();
void draw_g();
void draw_o();
MyEventReceiver *getHey() const;
irr::IrrlichtDevice* getDevice()const;
irr::video::IVideoDriver* getDriver()const;
irr::scene::ISceneManager* getSmgr()const;
irr::gui::IGUIEnvironment* getGuienv()const;
irr::video::ITexture * getImage()const;
irr::core::dimension2d<irr::u32> getTaille()const;
irr::core::position2d<irr::s32> getPosition0()const;
irr::core::position2d<irr::s32> getPosition1()const;
irr::core::rect<irr::s32> getRectangle()const;
irrklang::ISoundEngine* getEngine() const;
void setHey(MyEventReceiver *const _hey);
void setDevice(irr::IrrlichtDevice*);
void setDriver(irr::video::IVideoDriver* const);
void setSmgr(irr::scene::ISceneManager* const);
void setGuienv(irr::gui::IGUIEnvironment* const);
void setImage(irr::video::ITexture *const );
void setTaille(irr::core::dimension2d<irr::u32> const &);
void setPosition0(irr::core::position2d<irr::s32> const &);
void setPosition1(irr::core::position2d<irr::s32> const &);
void setRectangle(irr::core::rect<irr::s32> const &);
void setEngine(irrklang::ISoundEngine* const);
};
void do_splash(Splash *thi);
#endif
| 30.705128 | 80 | 0.7119 |
8e74c6d36bab66a364db7720133d1d6155667a5a | 360 | cpp | C++ | Stereolabs/Source/Stereolabs/Private/Threading/StereolabsRunnable.cpp | stereolabs/zed-unreal-plugin | 0fabf29edc84db1126f0c4f73b9ce501e322be96 | [
"MIT"
] | 38 | 2018-02-27T22:53:56.000Z | 2022-02-10T05:46:51.000Z | Stereolabs/Source/Stereolabs/Private/Threading/StereolabsRunnable.cpp | HuangArmagh/zed-unreal-plugin | 3bd8872577f49e2eb5f6cb8a6a610a4c786f6104 | [
"MIT"
] | 14 | 2018-05-26T03:15:16.000Z | 2022-03-02T14:34:10.000Z | Stereolabs/Source/Stereolabs/Private/Threading/StereolabsRunnable.cpp | HuangArmagh/zed-unreal-plugin | 3bd8872577f49e2eb5f6cb8a6a610a4c786f6104 | [
"MIT"
] | 16 | 2018-01-23T22:55:34.000Z | 2021-12-20T18:34:08.000Z | //======= Copyright (c) Stereolabs Corporation, All rights reserved. ===============
#include "StereolabsPrivatePCH.h"
#include "Stereolabs/Public/Threading/StereolabsRunnable.h"
FSlRunnable::FSlRunnable()
:
Thread(nullptr),
bIsRunning(false),
bIsPaused(false),
bIsSleeping(false)
{
}
FSlRunnable::~FSlRunnable()
{
delete Thread;
Thread = nullptr;
} | 18 | 84 | 0.705556 |
8e7744dd7d2cee3e4e72f48a233d862b6f13e346 | 6,891 | cpp | C++ | src/xray/engine/sources/engine_world_editor.cpp | ixray-team/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | 3 | 2021-10-30T09:36:14.000Z | 2022-03-26T17:00:06.000Z | src/xray/engine/sources/engine_world_editor.cpp | acidicMercury8/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | null | null | null | src/xray/engine/sources/engine_world_editor.cpp | acidicMercury8/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:08.000Z | 2022-03-26T17:00:08.000Z | ////////////////////////////////////////////////////////////////////////////
// Created : 17.06.2009
// Author : Dmitriy Iassenev
// Copyright (C) GSC Game World - 2009
////////////////////////////////////////////////////////////////////////////
#include "pch.h"
#include "engine_world.h"
#include "rpc.h"
#include <xray/render/base/engine_renderer.h>
#include <xray/editor/world/api.h>
#include <xray/editor/world/world.h>
#include <xray/editor/world/library_linkage.h>
#include <boost/bind.hpp>
#include <xray/core/core.h>
#include <xray/sound/world.h>
#if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
# include <xray/os_preinclude.h>
# undef NOUSER
# undef NOMSG
# undef NOMB
# include <xray/os_include.h>
# include <objbase.h> // for COINIT_MULTITHREADED
static HMODULE s_editor_module = 0;
static xray::editor::create_world_ptr s_create_world = 0;
static xray::editor::destroy_world_ptr s_destroy_world = 0;
static xray::editor::memory_allocator_ptr s_memory_allocator = 0;
static xray::editor::property_holder* s_holder = 0;
#endif // #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
using xray::engine::engine_world;
void engine_world::try_load_editor ( )
{
#if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
R_ASSERT ( !s_editor_module );
s_editor_module = LoadLibrary( XRAY_EDITOR_FILE_NAME );
if (!s_editor_module) {
LOG_WARNING ( "cannot load library \"%s\"", XRAY_EDITOR_FILE_NAME );
return;
}
#if XRAY_PLATFORM_WINDOWS_32 && defined(DEBUG)
xray::debug::enable_fpe ( false );
#endif // #if XRAY_PLATFORM_WINDOWS_32
R_ASSERT ( !s_create_world );
s_create_world = (xray::editor::create_world_ptr)GetProcAddress(s_editor_module, "create_world");
R_ASSERT ( s_create_world );
R_ASSERT ( !s_destroy_world );
s_destroy_world = (xray::editor::destroy_world_ptr)GetProcAddress(s_editor_module, "destroy_world");
R_ASSERT ( s_destroy_world );
R_ASSERT ( !s_memory_allocator);
s_memory_allocator = (xray::editor::memory_allocator_ptr)GetProcAddress(s_editor_module, "memory_allocator");
R_ASSERT ( s_memory_allocator );
s_memory_allocator ( m_editor_allocator );
// this function cannot be called before s_memory_allocator function called
// because of a workaround of BugTrapN initialization from unmanaged code
debug::change_bugtrap_usage ( core::debug::error_mode_verbose, core::debug::managed_bugtrap );
R_ASSERT ( !m_editor );
m_editor = s_create_world ( *this );
R_ASSERT ( m_editor );
R_ASSERT ( !m_window_handle );
m_window_handle = m_editor->view_handle( );
R_ASSERT ( m_window_handle );
R_ASSERT ( !m_main_window_handle );
m_main_window_handle = m_editor->main_handle( );
R_ASSERT ( m_main_window_handle );
m_editor->load ( );
#else // #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
UNREACHABLE_CODE ( );
#endif // #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
}
void engine_world::unload_editor ( )
{
#if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
ASSERT ( m_editor );
ASSERT ( s_destroy_world );
s_destroy_world ( m_editor );
ASSERT ( !m_editor );
ASSERT ( s_editor_module );
FreeLibrary ( s_editor_module );
s_editor_module = 0;
s_destroy_world = 0;
s_create_world = 0;
#else // #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
UNREACHABLE_CODE ( );
#endif // #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
}
void engine_world::initialize_editor ( )
{
if( !command_line_editor() )
return;
m_game_enabled = false;
if( threading::core_count( ) == 1 ) {
try_load_editor ( );
return;
}
rpc::assign_thread_id ( rpc::editor, u32(-1) );
threading::spawn (
boost::bind( &engine_world::editor, this ),
!command_line_editor_singlethread( ) ? "editor" : "editor + logic",
!command_line_editor_singlethread( ) ? "editor" : "editor + logic",
0,
0
);
rpc::run (
rpc::editor,
boost::bind( &engine_world::try_load_editor, this),
rpc::break_process_loop,
rpc::dont_wait_for_completion
);
}
void engine_world::initialize_editor_thread_ids ( )
{
m_editor_allocator.user_current_thread_id ( );
m_processed_editor.set_pop_thread_id ( );
render_world().editor().set_command_push_thread_id ( );
render_world().editor().initialize_command_queue ( XRAY_NEW_IMPL( m_editor_allocator, command_type_impl) );
}
void engine_world::editor ( )
{
#if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
CoInitializeEx ( 0, COINIT_APARTMENTTHREADED );
#endif // #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360
rpc::assign_thread_id ( rpc::editor, threading::current_thread_id( ) );
rpc::process ( rpc::editor );
rpc::process ( rpc::editor );
m_editor->run ( );
if (!m_destruction_started)
exit ( 0 );
if ( rpc::is_same_thread(rpc::logic) )
rpc::process ( rpc::logic );
rpc::process ( rpc::editor );
}
void engine_world::draw_frame_editor ( )
{
render_world().editor().set_command_processor_frame_id( render_world( ).engine().frame_id() + 1 );
m_editor_frame_ended = true;
if( m_logic_frame_ended || !m_game_enabled || m_game_enabled == m_game_paused_last )
{
render_world( ).engine().draw_frame ( );
m_logic_frame_ended = false;
m_editor_frame_ended = false;
m_game_paused_last = !m_game_enabled;
}
}
void engine_world::delete_processed_editor_orders ( bool destroying )
{
delete_processed_orders ( m_processed_editor, m_editor_allocator, m_editor_frame_id, destroying );
}
bool engine_world::on_before_editor_tick ( )
{
if ( threading::core_count( ) == 1 )
tick ( );
else {
m_render_world->engine().test_cooperative_level();
static bool editor_singlethreaded = command_line_editor_singlethread ( );
if ( editor_singlethreaded ) {
logic_tick ( );
}
else {
if ( m_editor_frame_id > m_render_world->engine().frame_id() + 1 )
return false;
}
}
delete_processed_editor_orders ( false );
return true;
}
void engine_world::on_after_editor_tick ( )
{
if ( threading::core_count( ) == 1 ) {
++m_editor_frame_id;
return;
}
if( !command_line_editor_singlethread() ) {
++m_editor_frame_id;
return;
}
while ( ( m_logic_frame_id > m_render_world->engine().frame_id( ) + 1 ) && !m_destruction_started ) {
m_render_world->engine().test_cooperative_level();
threading::yield ( 0 );
}
// ++m_logic_frame_id;
++m_editor_frame_id;
}
void engine_world::enter_editor_mode ( )
{
if ( !m_editor )
return;
m_editor->editor_mode ( true );
}
void engine_world::editor_clear_resources ( )
{
if ( !m_editor )
return;
resources::dispatch_callbacks ( );
// m_editor->clear_resources ( );
m_sound_world->clear_editor_resources( );
} | 28.475207 | 111 | 0.681759 |
8e7f1d33373959812148cf82e370019cbcb8c484 | 3,553 | cpp | C++ | Diagram/DiagramTextItem.cpp | devonchenc/NovaImage | 3d17166f9705ba23b89f1aefd31ac2db97385b1c | [
"MIT"
] | null | null | null | Diagram/DiagramTextItem.cpp | devonchenc/NovaImage | 3d17166f9705ba23b89f1aefd31ac2db97385b1c | [
"MIT"
] | null | null | null | Diagram/DiagramTextItem.cpp | devonchenc/NovaImage | 3d17166f9705ba23b89f1aefd31ac2db97385b1c | [
"MIT"
] | null | null | null | #include "DiagramTextItem.h"
#include <QDebug>
#include <QTextCursor>
#include "../Core/GlobalFunc.h"
DiagramTextItem::DiagramTextItem(QGraphicsItem* parent)
: QGraphicsTextItem(parent)
{
setFlag(QGraphicsItem::ItemIsMovable);
setFlag(QGraphicsItem::ItemIsSelectable);
_positionLastTime = QPointF(0, 0);
}
DiagramTextItem* DiagramTextItem::clone()
{
DiagramTextItem* cloned = new DiagramTextItem(nullptr);
cloned->setPlainText(toPlainText());
cloned->setFont(font());
cloned->setTextWidth(textWidth());
cloned->setDefaultTextColor(defaultTextColor());
cloned->setPos(scenePos());
cloned->setZValue(zValue());
return cloned;
}
QDomElement DiagramTextItem::saveToXML(QDomDocument& doc)
{
QDomElement lineItem = doc.createElement("GraphicsItem");
lineItem.setAttribute("Type", "DiagramTextItem");
QDomElement attribute = doc.createElement("Attribute");
attribute.setAttribute("Text", toPlainText());
attribute.setAttribute("Position", pointFToString(pos()));
attribute.setAttribute("DefaultTextColor", colorToString(defaultTextColor()));
attribute.setAttribute("Font", font().family());
attribute.setAttribute("PointSize", QString::number(font().pointSize()));
attribute.setAttribute("Weight", QString::number(font().weight()));
attribute.setAttribute("Italic", QString::number(font().italic()));
attribute.setAttribute("Underline", QString::number(font().underline()));
lineItem.appendChild(attribute);
return lineItem;
}
void DiagramTextItem::loadFromXML(const QDomElement& e)
{
setPlainText(e.attribute("Text"));
setPos(stringToPointF(e.attribute("Position")));
setDefaultTextColor(stringToColor(e.attribute("DefaultTextColor")));
QFont font = this->font();
font.setFamily(e.attribute("Font"));
font.setPointSize(e.attribute("PointSize").toInt());
font.setWeight(e.attribute("Weight").toInt());
font.setItalic(e.attribute("Italic").toInt());
font.setUnderline(e.attribute("Underline").toInt());
setFont(font);
}
QVariant DiagramTextItem::itemChange(GraphicsItemChange change, const QVariant& value)
{
if (change == QGraphicsItem::ItemSelectedHasChanged)
emit textSelectedChange(this);
return value;
}
void DiagramTextItem::focusInEvent(QFocusEvent* event)
{
if (_positionLastTime == QPointF(0, 0))
// initialize positionLastTime to insertion position
_positionLastTime = scenePos();
QGraphicsTextItem::focusInEvent(event);
}
void DiagramTextItem::focusOutEvent(QFocusEvent* event)
{
setTextInteractionFlags(Qt::NoTextInteraction);
if (_contentLastTime == toPlainText())
{
_contentHasChanged = false;
}
else
{
_contentLastTime = toPlainText();
_contentHasChanged = true;
}
emit lostFocus(this);
QGraphicsTextItem::focusOutEvent(event);
}
void DiagramTextItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event)
{
if (textInteractionFlags() == Qt::NoTextInteraction)
{
setTextInteractionFlags(Qt::TextEditorInteraction);
}
QGraphicsTextItem::mouseDoubleClickEvent(event);
}
void DiagramTextItem::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
QGraphicsTextItem::mousePressEvent(event);
}
void DiagramTextItem::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
if (scenePos() != _positionLastTime)
{
qDebug() << scenePos() << "::" << _positionLastTime;
}
_positionLastTime = scenePos();
QGraphicsTextItem::mouseReleaseEvent(event);
}
| 30.62931 | 86 | 0.71714 |
8e7f4570bad4e822a335012a8954ab535981c82a | 633 | cpp | C++ | clang/test/SemaCXX/template-multiple-attr-propagation.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 3,102 | 2015-01-04T02:28:35.000Z | 2022-03-30T12:53:41.000Z | clang/test/SemaCXX/template-multiple-attr-propagation.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | clang/test/SemaCXX/template-multiple-attr-propagation.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 1,868 | 2015-01-03T04:27:11.000Z | 2022-03-25T13:37:35.000Z | // RUN: %clang_cc1 %s -Wthread-safety-analysis -verify -fexceptions
// expected-no-diagnostics
class Mutex {
public:
void Lock() __attribute__((exclusive_lock_function()));
void Unlock() __attribute__((unlock_function()));
};
class A {
public:
Mutex mu1, mu2;
void foo() __attribute__((exclusive_locks_required(mu1))) __attribute__((exclusive_locks_required(mu2))) {}
template <class T>
void bar() __attribute__((exclusive_locks_required(mu1))) __attribute__((exclusive_locks_required(mu2))) {
foo();
}
};
void f() {
A a;
a.mu1.Lock();
a.mu2.Lock();
a.bar<int>();
a.mu2.Unlock();
a.mu1.Unlock();
}
| 21.1 | 109 | 0.685624 |
8e80230a4682d1e69daf8eb7cd916a773b12efc3 | 2,059 | hpp | C++ | ThirdParty-mod/java2cpp/java/lang/Void.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | 1 | 2019-04-03T01:53:28.000Z | 2019-04-03T01:53:28.000Z | ThirdParty-mod/java2cpp/java/lang/Void.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | ThirdParty-mod/java2cpp/java/lang/Void.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | /*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: java.lang.Void
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVA_LANG_VOID_HPP_DECL
#define J2CPP_JAVA_LANG_VOID_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace lang { class Class; } } }
#include <java/lang/Class.hpp>
#include <java/lang/Object.hpp>
namespace j2cpp {
namespace java { namespace lang {
class Void;
class Void
: public object<Void>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_FIELD(0)
explicit Void(jobject jobj)
: object<Void>(jobj)
{
}
operator local_ref<java::lang::Object>() const;
static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), local_ref< java::lang::Class > > TYPE;
}; //class Void
} //namespace lang
} //namespace java
} //namespace j2cpp
#endif //J2CPP_JAVA_LANG_VOID_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVA_LANG_VOID_HPP_IMPL
#define J2CPP_JAVA_LANG_VOID_HPP_IMPL
namespace j2cpp {
java::lang::Void::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
static_field<
java::lang::Void::J2CPP_CLASS_NAME,
java::lang::Void::J2CPP_FIELD_NAME(0),
java::lang::Void::J2CPP_FIELD_SIGNATURE(0),
local_ref< java::lang::Class >
> java::lang::Void::TYPE;
J2CPP_DEFINE_CLASS(java::lang::Void,"java/lang/Void")
J2CPP_DEFINE_METHOD(java::lang::Void,0,"<init>","()V")
J2CPP_DEFINE_METHOD(java::lang::Void,1,"<clinit>","()V")
J2CPP_DEFINE_FIELD(java::lang::Void,0,"TYPE","Ljava/lang/Class;")
} //namespace j2cpp
#endif //J2CPP_JAVA_LANG_VOID_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| 22.380435 | 127 | 0.650801 |
8e887ecf4d7872203061f3c093aa07eedda04a7a | 2,339 | cc | C++ | modules/kernel/src/debugger/DebugEntry.cc | eryjus/century-os | 6e6bef8cbc0f9c5ff6a943b44aa87a7e89fdfbd7 | [
"BSD-3-Clause"
] | 12 | 2018-12-03T15:16:52.000Z | 2022-03-16T21:07:13.000Z | modules/kernel/src/debugger/DebugEntry.cc | eryjus/century-os | 6e6bef8cbc0f9c5ff6a943b44aa87a7e89fdfbd7 | [
"BSD-3-Clause"
] | null | null | null | modules/kernel/src/debugger/DebugEntry.cc | eryjus/century-os | 6e6bef8cbc0f9c5ff6a943b44aa87a7e89fdfbd7 | [
"BSD-3-Clause"
] | 2 | 2018-11-13T01:30:41.000Z | 2021-08-12T18:22:26.000Z | //===================================================================================================================
//
// DebugStart.cc -- This is the entry point for the kernel debugger
//
// Copyright (c) 2017-2020 -- Adam Clark
// Licensed under "THE BEER-WARE LICENSE"
// See License.md for details.
//
// ------------------------------------------------------------------------------------------------------------------
//
// Date Tracker Version Pgmr Description
// ----------- ------- ------- ---- ---------------------------------------------------------------------------
// 2020-Apr-02 Initial v0.6.0a ADCL Initial version
//
//===================================================================================================================
#include "types.h"
#include "printf.h"
#include "serial.h"
#include "process.h"
#include "debugger.h"
//
// -- This is the main entry point for the kernel debugger
// ----------------------------------------------------
EXTERN_C EXPORT KERNEL
void DebugStart(void)
{
EnableInterrupts();
// -- we want the highest chance of getting CPU time!
currentThread->priority = PTY_OS;
debugState = DBG_HOME;
kprintf(ANSI_CLEAR ANSI_SET_CURSOR(0,0) ANSI_FG_RED ANSI_ATTR_BOLD
"Welcome to the Century-OS kernel debugger\n" ANSI_ATTR_NORMAL);
while (true) {
DebugPrompt(debugState);
DebuggerCommand_t cmd = DebugParse(debugState);
switch(cmd) {
case CMD_EXIT:
debugState = DBG_HOME;
kMemSetB(debugCommand, 0, DEBUG_COMMAND_LEN);
continue;
case CMD_SCHED:
debugState = DBG_SCHED;
DebugScheduler();
continue;
case CMD_TIMER:
debugState = DBG_TIMER;
DebugTimer();
continue;
case CMD_MSGQ:
debugState = DBG_MSGQ;
DebugMsgq();
continue;
case CMD_ERROR:
default:
kprintf("\n\n" ANSI_ATTR_BOLD ANSI_FG_RED
"Something went wrong (main) -- a bug in the debugger is likely\n" ANSI_ATTR_NORMAL);
continue;
}
if (cmd == CMD_ERROR) continue;
}
}
| 30.376623 | 117 | 0.436084 |
8e8b7903b026478e454007fe1df9115c428d6744 | 5,521 | cpp | C++ | tests/Unit/Evolution/EventsAndTriggers/Test_EventsAndTriggers.cpp | marissawalker/spectre | afc8205e2f697de5e8e4f05e881499e05c9fd8a0 | [
"MIT"
] | null | null | null | tests/Unit/Evolution/EventsAndTriggers/Test_EventsAndTriggers.cpp | marissawalker/spectre | afc8205e2f697de5e8e4f05e881499e05c9fd8a0 | [
"MIT"
] | null | null | null | tests/Unit/Evolution/EventsAndTriggers/Test_EventsAndTriggers.cpp | marissawalker/spectre | afc8205e2f697de5e8e4f05e881499e05c9fd8a0 | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
// This file checks the Completion event and the basic logical
// triggers (Always, And, Not, and Or).
#include "tests/Unit/TestingFramework.hpp"
#include <algorithm>
#include <memory>
#include <pup.h>
#include <string>
#include <unordered_map>
#include "DataStructures/DataBox/DataBox.hpp"
#include "Evolution/EventsAndTriggers/Actions/RunEventsAndTriggers.hpp" // IWYU pragma: keep
#include "Evolution/EventsAndTriggers/Completion.hpp"
#include "Evolution/EventsAndTriggers/Event.hpp"
#include "Evolution/EventsAndTriggers/EventsAndTriggers.hpp"
#include "Evolution/EventsAndTriggers/LogicalTriggers.hpp" // IWYU pragma: keep
#include "Evolution/EventsAndTriggers/Trigger.hpp"
#include "Parallel/RegisterDerivedClassesWithCharm.hpp"
#include "Utilities/MakeVector.hpp"
#include "Utilities/TMPL.hpp"
#include "Utilities/TaggedTuple.hpp"
#include "tests/Unit/ActionTesting.hpp"
#include "tests/Unit/TestCreation.hpp"
#include "tests/Unit/TestHelpers.hpp"
// IWYU pragma: no_forward_declare db::DataBox
namespace {
struct DefaultClasses {
template <typename T>
using type = tmpl::list<>;
};
using events_and_triggers_tag =
Tags::EventsAndTriggers<DefaultClasses, DefaultClasses>;
struct Metavariables;
struct component {
using metavariables = Metavariables;
using chare_type = ActionTesting::MockArrayChare;
using array_index = int;
using const_global_cache_tag_list = tmpl::list<events_and_triggers_tag>;
using action_list = tmpl::list<Actions::RunEventsAndTriggers>;
using initial_databox = db::DataBox<tmpl::list<>>;
};
struct Metavariables {
using component_list = tmpl::list<component>;
using const_global_cache_tag_list = tmpl::list<>;
};
using EventsAndTriggersType = EventsAndTriggers<DefaultClasses, DefaultClasses>;
void run_events_and_triggers(const EventsAndTriggersType& events_and_triggers,
const bool expected) {
// Test pup
Parallel::register_derived_classes_with_charm<Event<DefaultClasses>>();
Parallel::register_derived_classes_with_charm<Trigger<DefaultClasses>>();
using MockRuntimeSystem = ActionTesting::MockRuntimeSystem<Metavariables>;
using my_component = component;
using MockDistributedObjectsTag =
typename MockRuntimeSystem::template MockDistributedObjectsTag<
my_component>;
typename MockRuntimeSystem::TupleOfMockDistributedObjects dist_objects{};
tuples::get<MockDistributedObjectsTag>(dist_objects)
.emplace(0, db::DataBox<tmpl::list<>>{});
ActionTesting::MockRuntimeSystem<Metavariables> runner{
{serialize_and_deserialize(events_and_triggers)},
std::move(dist_objects)};
runner.next_action<component>(0);
CHECK(runner.algorithms<component>()[0].get_terminate() == expected);
}
void check_trigger(const bool expected, const std::string& trigger_string) {
// Test factory
std::unique_ptr<Trigger<DefaultClasses>> trigger =
test_factory_creation<Trigger<DefaultClasses>>(trigger_string);
EventsAndTriggersType::Storage events_and_triggers_map;
events_and_triggers_map.emplace(
std::move(trigger),
make_vector<std::unique_ptr<Event<DefaultClasses>>>(
std::make_unique<Events::Completion<DefaultClasses>>()));
const EventsAndTriggersType events_and_triggers(
std::move(events_and_triggers_map));
run_events_and_triggers(events_and_triggers, expected);
}
} // namespace
SPECTRE_TEST_CASE("Unit.Evolution.EventsAndTriggers", "[Unit][Evolution]") {
test_factory_creation<Event<DefaultClasses>>(" Completion");
check_trigger(true,
" Always");
check_trigger(false,
" Not: Always");
check_trigger(true,
" Not:\n"
" Not: Always");
check_trigger(true,
" And:\n"
" - Always\n"
" - Always");
check_trigger(false,
" And:\n"
" - Always\n"
" - Not: Always");
check_trigger(false,
" And:\n"
" - Not: Always\n"
" - Always");
check_trigger(false,
" And:\n"
" - Not: Always\n"
" - Not: Always");
check_trigger(false,
" And:\n"
" - Always\n"
" - Always\n"
" - Not: Always");
check_trigger(true,
" Or:\n"
" - Always\n"
" - Always");
check_trigger(true,
" Or:\n"
" - Always\n"
" - Not: Always");
check_trigger(true,
" Or:\n"
" - Not: Always\n"
" - Always");
check_trigger(false,
" Or:\n"
" - Not: Always\n"
" - Not: Always");
check_trigger(true,
" Or:\n"
" - Not: Always\n"
" - Not: Always\n"
" - Always");
}
SPECTRE_TEST_CASE("Unit.Evolution.EventsAndTriggers.creation",
"[Unit][Evolution]") {
const auto events_and_triggers = test_creation<EventsAndTriggersType>(
" ? Not: Always\n"
" : - Completion\n"
" ? Or:\n"
" - Not: Always\n"
" - Always\n"
" : - Completion\n"
" - Completion\n"
" ? Not: Always\n"
" : - Completion\n");
run_events_and_triggers(events_and_triggers, true);
}
| 32.668639 | 93 | 0.63503 |
8e8d2f55740dd591fc5dab9a9c969cb5ba645222 | 882 | cpp | C++ | src/my_utils/vector2_utils.cpp | lobinuxsoft/AsteroidXD-SFML | 66fb355dfb20ef840068ad948bef9fc97a75f7cd | [
"MIT"
] | null | null | null | src/my_utils/vector2_utils.cpp | lobinuxsoft/AsteroidXD-SFML | 66fb355dfb20ef840068ad948bef9fc97a75f7cd | [
"MIT"
] | 16 | 2021-11-09T15:22:24.000Z | 2021-11-23T14:02:43.000Z | src/my_utils/vector2_utils.cpp | lobinuxsoft/AsteroidXD-SFML | 66fb355dfb20ef840068ad948bef9fc97a75f7cd | [
"MIT"
] | null | null | null | #include "vector2_utils.h"
float Vector2Angle(Vector2f v1, Vector2f v2)
{
float result = atan2f(v2.y - v1.y, v2.x - v1.x) * (180.0f / PI);
if (result < 0) result += 360.0f;
return result;
}
float Vector2Distance(Vector2f v1, Vector2f v2)
{
return sqrtf((v1.x - v2.x) * (v1.x - v2.x) + (v1.y - v2.y) * (v1.y - v2.y));
}
float Vector2Length(Vector2f v)
{
return sqrtf((v.x * v.x) + (v.y * v.y));
}
Vector2f Vector2Scale(Vector2f v, float scale)
{
return Vector2f( v.x * scale, v.y * scale );
}
Vector2f Vector2Normalize(Vector2f v)
{
float length = Vector2Length(v);
if (length <= 0)
return v;
return Vector2Scale(v, 1 / length);
}
Vector2f Vector2Add(Vector2f v1, Vector2f v2)
{
return Vector2f( v1.x + v2.x, v1.y + v2.y );
}
Vector2f Vector2Subtract(Vector2f v1, Vector2f v2)
{
return Vector2f(v1.x - v2.x, v1.y - v2.y);
} | 21 | 80 | 0.620181 |
8e8e54a5dc9f20dc63765ef2a60be805e89c0bea | 4,428 | cpp | C++ | Cutscene Manager Handout/Motor2D/j1CutsceneManager.cpp | pauraurell/Cutscene-Manager | f887b2a14e1c4e3623d2d8933d7893280ab27f53 | [
"MIT"
] | null | null | null | Cutscene Manager Handout/Motor2D/j1CutsceneManager.cpp | pauraurell/Cutscene-Manager | f887b2a14e1c4e3623d2d8933d7893280ab27f53 | [
"MIT"
] | null | null | null | Cutscene Manager Handout/Motor2D/j1CutsceneManager.cpp | pauraurell/Cutscene-Manager | f887b2a14e1c4e3623d2d8933d7893280ab27f53 | [
"MIT"
] | null | null | null | #include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1Textures.h"
#include "j1Scene.h"
#include "j1Render.h"
#include "j1Window.h"
#include "j1CutsceneCharacters.h"
#include "j1CutsceneManager.h"
j1CutsceneManager::j1CutsceneManager() : j1Module()
{
name.create("cutscene");
}
// Destructor
j1CutsceneManager::~j1CutsceneManager()
{}
// Called before the first frame
bool j1CutsceneManager::Start()
{
black_bars.fase = None;
black_bars.alpha = 0;
int bar_height = 100;
black_bars.top_rect.x = 0;
black_bars.top_rect.y = 0;
black_bars.top_rect.w = App->win->width;
black_bars.top_rect.h = bar_height;
black_bars.down_rect.x = 0;
black_bars.down_rect.y = App->win->height - bar_height;
black_bars.down_rect.w = App->win->width;
black_bars.down_rect.h = bar_height;
result = data.load_file("CutsceneEditor.xml");
cutsceneManager = data.document_element();
LOG("Starting Cutscene Manager");
return true;
}
// Called each loop iteration
bool j1CutsceneManager::Update(float dt)
{
return true;
}
// Called each loop iteration
bool j1CutsceneManager::PostUpdate(float dt)
{
//Black Bars Drawing
switch (black_bars.fase)
{
case FadeIn:
black_bars.FadeIn();
break;
case Drawing:
black_bars.Draw();
break;
case FadeOut:
black_bars.FadeOut();
break;
}
return true;
}
// Called before quitting
bool j1CutsceneManager::CleanUp()
{
return true;
}
void BlackBars::FadeIn()
{
//TODO 5.2: Complete this function doing a smooth fade in raising the value of the alpha
// (alpha = 0: invisible, alpha = 255: Completely black)
}
void BlackBars::Draw()
{
//TODO 5.1: Draw both quads unsing the alpha variable. Both rects are (top_rect and down_rect) already
// created, you just have to draw them.
}
void BlackBars::FadeOut()
{
//TODO 5.2: Similar to fade out
}
void j1CutsceneManager::StartCutscene(string name)
{
if (!SomethingActive())
{
for (pugi::xml_node cutscene = cutsceneManager.child("cutscene"); cutscene; cutscene = cutscene.next_sibling("cutscene"))
{
if (cutscene.attribute("name").as_string() == name)
{
LoadSteps(cutscene);
if (black_bars.fase == None) { black_bars.fase = FadeIn; }
}
}
if (App->characters->player.active) {App->characters->player.UpdateStep(); }
if (App->characters->character1.active) {App->characters->character1.UpdateStep(); }
if (App->characters->character2.active) { App->characters->character2.UpdateStep(); }
if (App->render->cinematic_camera.active) { App->render->cinematic_camera.UpdateStep(); }
}
}
bool j1CutsceneManager::LoadSteps(pugi::xml_node node)
{
//TODO 1: Check the structure of the Cutscene Editor xml and fill this function. You just have to get the attributes from
// the xml and push the step to the list of the correspondent Cutscene Object depending on its objective and set the active
// bool to true of each loaded Cutscene Object.
return true;
}
void j1CutsceneManager::DoCutscene(CutsceneObject &character, iPoint &objective_position)
{
Step step = character.current_step;
if(character.active)
{
Movement(step, objective_position);
//TODO 4: This todo is very easy, just check if the object position is equal to the last position of the cutscene and if it
// is call the FinishCutscene function. If it has reached the step.position but it is not the last one just call the Update step
// function you've just made right before.
}
}
void j1CutsceneManager::Movement(Step &step, iPoint &objective_position)
{
//TODO 2: Now we want to move the object to the destiny point. To do that compare the object postion with the position
// we want to reach and move it with the speed values.
}
void CutsceneObject::UpdateStep()
{
//TODO 3: Now that the object will move wherever we want, we have to call this function every time the object reaches a point.
// To do this, in this function you just have to update the current_step value with the next step in the list.
}
void j1CutsceneManager::FinishCutscene(CutsceneObject& character)
{
character.steps.clear();
character.active = false;
App->characters->input = true;
if (black_bars.fase == Drawing) { black_bars.fase = FadeOut; }
}
bool j1CutsceneManager::SomethingActive()
{
bool ret;
if (App->characters->player.active || App->characters->character1.active || App->characters->character2.active){ret = true;}
else { ret = false; }
return ret;
}
| 24.464088 | 131 | 0.727191 |
8e8fb299899a755581ac3a9945f0b7b0ae52f35b | 362 | cpp | C++ | ch04/th4-5-1.cpp | nanonashy/PPPUCpp2ndJP | b829867e9e21bf59d9c5ea6c2fbe96bb03597301 | [
"MIT"
] | 3 | 2021-12-17T17:25:18.000Z | 2022-03-02T15:52:23.000Z | ch04/th4-5-1.cpp | nashinium/PPPUCpp2ndJP | b829867e9e21bf59d9c5ea6c2fbe96bb03597301 | [
"MIT"
] | 1 | 2020-04-22T07:16:34.000Z | 2020-04-22T10:04:04.000Z | ch04/th4-5-1.cpp | nashinium/PPPUCpp2ndJP | b829867e9e21bf59d9c5ea6c2fbe96bb03597301 | [
"MIT"
] | 1 | 2020-04-22T08:13:51.000Z | 2020-04-22T08:13:51.000Z | #include "../include/std_lib_facilities.h"
int square(int x) {
int result{0};
for (int i = 1; i <= x; ++i)
result += x;
return result;
}
int main() {
std::cout << "Number\tSquare\n";
for (int i = 1; i <= 100; ++i)
std::cout << i << '\t' << square(i) << std::endl;
keep_window_open();
return 0;
} | 19.052632 | 58 | 0.477901 |
8e8fcbbb94e6ebae074192cb4816cf0be70a6a58 | 14,565 | cpp | C++ | src/llri-vk/detail/device.cpp | Rythe-Interactive/Rythe-LLRI | 0bf9ff71c41b39f7189cbc5ebbf4a74420cedc05 | [
"MIT"
] | 2 | 2022-02-08T07:11:32.000Z | 2022-02-08T08:10:31.000Z | src/llri-vk/detail/device.cpp | Rythe-Interactive/Rythe-LLRI | 0bf9ff71c41b39f7189cbc5ebbf4a74420cedc05 | [
"MIT"
] | 1 | 2022-02-14T18:26:31.000Z | 2022-02-14T18:26:31.000Z | src/llri-vk/detail/device.cpp | Rythe-Interactive/Rythe-LLRI | 0bf9ff71c41b39f7189cbc5ebbf4a74420cedc05 | [
"MIT"
] | null | null | null | /**
* @file device.cpp
* Copyright (c) 2021 Leon Brands, Rythe Interactive
* SPDX-License-Identifier: MIT
*/
#include <llri/llri.hpp>
#include <llri-vk/utils.hpp>
namespace llri
{
result Device::impl_createCommandGroup(queue_type type, CommandGroup** cmdGroup)
{
auto* output = new CommandGroup();
output->m_device = this;
output->m_deviceFunctionTable = m_functionTable;
output->m_validationCallbackMessenger = m_validationCallbackMessenger;
output->m_type = type;
auto families = detail::findQueueFamilies(static_cast<VkPhysicalDevice>(m_adapter->m_ptr));
VkCommandPoolCreateInfo info;
info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
info.pNext = nullptr;
info.queueFamilyIndex = families[type];
info.flags = {};
VkCommandPool pool;
const auto r = static_cast<VolkDeviceTable*>(m_functionTable)->
vkCreateCommandPool(static_cast<VkDevice>(m_ptr), &info, nullptr, &pool);
if (r != VK_SUCCESS)
{
destroyCommandGroup(output);
return detail::mapVkResult(r);
}
output->m_ptr = pool;
*cmdGroup = output;
return result::Success;
}
void Device::impl_destroyCommandGroup(CommandGroup* cmdGroup)
{
if (!cmdGroup)
return;
if (cmdGroup->m_ptr)
{
static_cast<VolkDeviceTable*>(m_functionTable)->
vkDestroyCommandPool(static_cast<VkDevice>(m_ptr), static_cast<VkCommandPool>(cmdGroup->m_ptr), nullptr);
}
delete cmdGroup;
}
result Device::impl_createFence(fence_flags flags, Fence** fence)
{
const bool signaled = (flags & fence_flag_bits::Signaled) == fence_flag_bits::Signaled;
VkFenceCreateFlags vkFlags = 0;
if (signaled)
vkFlags |= VK_FENCE_CREATE_SIGNALED_BIT;
VkFenceCreateInfo info;
info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
info.pNext = nullptr;
info.flags = vkFlags;
VkFence vkFence;
const auto r = static_cast<VolkDeviceTable*>(m_functionTable)->
vkCreateFence(static_cast<VkDevice>(m_ptr), &info, nullptr, &vkFence);
if (r != VK_SUCCESS)
return detail::mapVkResult(r);
auto* output = new Fence();
output->m_flags = flags;
output->m_ptr = vkFence;
output->m_signaled = signaled;
*fence = output;
return result::Success;
}
void Device::impl_destroyFence(Fence* fence)
{
if (fence->m_ptr)
{
static_cast<VolkDeviceTable*>(m_functionTable)->
vkDestroyFence(static_cast<VkDevice>(m_ptr), static_cast<VkFence>(fence->m_ptr), nullptr);
}
delete fence;
}
result Device::impl_waitFences(uint32_t numFences, Fence** fences, uint64_t timeout)
{
uint64_t vkTimeout = timeout;
if (timeout != LLRI_TIMEOUT_MAX)
vkTimeout *= 1000000u; // milliseconds to nanoseconds
std::vector<VkFence> vkFences(numFences);
for (size_t i = 0; i < numFences; i++)
vkFences[i] = static_cast<VkFence>(fences[i]->m_ptr);
const VkResult r = static_cast<VolkDeviceTable*>(m_functionTable)->
vkWaitForFences(static_cast<VkDevice>(m_ptr), numFences, vkFences.data(), true, vkTimeout);
if (r == VK_SUCCESS)
{
static_cast<VolkDeviceTable*>(m_functionTable)->
vkResetFences(static_cast<VkDevice>(m_ptr), numFences, vkFences.data());
for (size_t i = 0; i < numFences; i++)
fences[i]->m_signaled = false;
}
return detail::mapVkResult(r);
}
result Device::impl_createSemaphore(Semaphore** semaphore)
{
VkSemaphoreCreateInfo info;
info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
info.pNext = nullptr;
info.flags = {};
VkSemaphore vkSemaphore;
const VkResult r = static_cast<VolkDeviceTable*>(m_functionTable)->
vkCreateSemaphore(static_cast<VkDevice>(m_ptr), &info, nullptr, &vkSemaphore);
if (r != VK_SUCCESS)
return detail::mapVkResult(r);
auto* output = new Semaphore();
output->m_ptr = vkSemaphore;
*semaphore = output;
return result::Success;
}
void Device::impl_destroySemaphore(Semaphore* semaphore)
{
if (semaphore->m_ptr)
{
static_cast<VolkDeviceTable*>(m_functionTable)->
vkDestroySemaphore(static_cast<VkDevice>(m_ptr), static_cast<VkSemaphore>(semaphore->m_ptr), nullptr);
}
delete semaphore;
}
result Device::impl_createResource(const resource_desc& desc, Resource** resource)
{
auto* table = static_cast<VolkDeviceTable*>(m_functionTable);
const bool isTexture = desc.type != resource_type::Buffer;
// get all valid queue families
const auto& families = detail::findQueueFamilies(static_cast<VkPhysicalDevice>(m_adapter->m_ptr));
std::vector<uint32_t> familyIndices;
for (const auto& [key, family] : families)
{
if (family != std::numeric_limits<uint32_t>::max())
familyIndices.push_back(family);
}
// get memory flags
const auto memFlags = detail::mapMemoryType(desc.memoryType);
uint64_t dataSize = 0;
uint32_t memoryTypeIndex = 0;
VkImage image = VK_NULL_HANDLE;
VkBuffer buffer = VK_NULL_HANDLE;
if (isTexture)
{
uint32_t depth = desc.type == resource_type::Texture3D ? desc.depthOrArrayLayers : 1;
uint32_t arrayLayers = desc.type == resource_type::Texture3D ? 1 : desc.depthOrArrayLayers;
VkImageCreateInfo imageCreate;
imageCreate.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageCreate.pNext = nullptr;
imageCreate.flags = 0;
imageCreate.imageType = detail::mapTextureType(desc.type);
imageCreate.format = detail::mapTextureFormat(desc.textureFormat);
imageCreate.extent = VkExtent3D{ desc.width, desc.height, depth };
imageCreate.mipLevels = desc.mipLevels;
imageCreate.arrayLayers = arrayLayers;
imageCreate.samples = (VkSampleCountFlagBits)desc.sampleCount;
imageCreate.tiling = VK_IMAGE_TILING_OPTIMAL;
imageCreate.usage = detail::mapTextureUsage(desc.usage);
imageCreate.sharingMode = familyIndices.size() > 1 ? VK_SHARING_MODE_CONCURRENT : VK_SHARING_MODE_EXCLUSIVE;
imageCreate.queueFamilyIndexCount = static_cast<uint32_t>(familyIndices.size());
imageCreate.pQueueFamilyIndices = familyIndices.data();
imageCreate.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
auto r = table->vkCreateImage(static_cast<VkDevice>(m_ptr), &imageCreate, nullptr, &image);
if (r != VK_SUCCESS)
return detail::mapVkResult(r);
VkMemoryRequirements reqs;
table->vkGetImageMemoryRequirements(static_cast<VkDevice>(m_ptr), image, &reqs);
dataSize = reqs.size;
memoryTypeIndex = detail::findMemoryTypeIndex(static_cast<VkPhysicalDevice>(m_adapter->m_ptr), reqs.memoryTypeBits, memFlags);
}
else
{
VkBufferCreateInfo bufferCreate;
bufferCreate.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferCreate.pNext = nullptr;
bufferCreate.flags = 0;
bufferCreate.size = desc.width;
bufferCreate.usage = detail::mapBufferUsage(desc.usage);
bufferCreate.sharingMode = familyIndices.size() > 1 ? VK_SHARING_MODE_CONCURRENT : VK_SHARING_MODE_EXCLUSIVE;
bufferCreate.queueFamilyIndexCount = static_cast<uint32_t>(familyIndices.size());
bufferCreate.pQueueFamilyIndices = familyIndices.data();
auto r = table->vkCreateBuffer(static_cast<VkDevice>(m_ptr), &bufferCreate, nullptr, &buffer);
if (r != VK_SUCCESS)
return detail::mapVkResult(r);
VkMemoryRequirements reqs;
table->vkGetBufferMemoryRequirements(static_cast<VkDevice>(m_ptr), buffer, &reqs);
dataSize = reqs.size;
memoryTypeIndex = detail::findMemoryTypeIndex(static_cast<VkPhysicalDevice>(m_adapter->m_ptr), reqs.memoryTypeBits, memFlags);
}
VkMemoryAllocateFlagsInfoKHR flagsInfo;
flagsInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO;
flagsInfo.pNext = nullptr;
flagsInfo.deviceMask = desc.visibleNodeMask;
flagsInfo.flags = VK_MEMORY_ALLOCATE_DEVICE_MASK_BIT;
VkMemoryAllocateInfo allocInfo;
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.pNext = m_adapter->queryNodeCount() > 1 ? &flagsInfo : nullptr;
allocInfo.allocationSize = dataSize;
allocInfo.memoryTypeIndex = memoryTypeIndex;
VkDeviceMemory memory;
auto r = table->vkAllocateMemory(static_cast<VkDevice>(m_ptr), &allocInfo, nullptr, &memory);
if (r != VK_SUCCESS)
{
if (isTexture)
table->vkDestroyImage(static_cast<VkDevice>(m_ptr), image, nullptr);
else
table->vkDestroyBuffer(static_cast<VkDevice>(m_ptr), buffer, nullptr);
return detail::mapVkResult(r);
}
if (isTexture)
r = table->vkBindImageMemory(static_cast<VkDevice>(m_ptr), image, memory, 0);
else
r = table->vkBindBufferMemory(static_cast<VkDevice>(m_ptr), buffer, memory, 0);
if (r != VK_SUCCESS)
{
if (isTexture)
table->vkDestroyImage(static_cast<VkDevice>(m_ptr), image, nullptr);
else
table->vkDestroyBuffer(static_cast<VkDevice>(m_ptr), buffer, nullptr);
table->vkFreeMemory(static_cast<VkDevice>(m_ptr), memory, nullptr);
return detail::mapVkResult(r);
}
// this part is necessary because in vulkan images are created in the UNDEFINED layout
// so we must transition them to desc.initialState manually.
if (isTexture)
{
table->vkResetCommandPool(static_cast<VkDevice>(m_ptr), static_cast<VkCommandPool>(m_workCmdGroup), {});
// Record commandbuffer to transition texture from undefined
VkCommandBufferBeginInfo beginInfo {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.pNext = nullptr;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
beginInfo.pInheritanceInfo = nullptr;
table->vkBeginCommandBuffer(static_cast<VkCommandBuffer>(m_workCmdList), &beginInfo);
// use the texture format to detect the aspect flags
VkImageAspectFlags aspectFlags = {};
if (has_color_component(desc.textureFormat))
aspectFlags |= VK_IMAGE_ASPECT_COLOR_BIT;
if (has_depth_component(desc.textureFormat))
aspectFlags |= VK_IMAGE_ASPECT_DEPTH_BIT;
if (has_stencil_component(desc.textureFormat))
aspectFlags |= VK_IMAGE_ASPECT_STENCIL_BIT;
VkImageMemoryBarrier imageMemoryBarrier {};
imageMemoryBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
imageMemoryBarrier.pNext = nullptr;
imageMemoryBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageMemoryBarrier.newLayout = detail::mapResourceState(desc.initialState);
imageMemoryBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
imageMemoryBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
imageMemoryBarrier.srcAccessMask = VK_ACCESS_NONE_KHR;
imageMemoryBarrier.dstAccessMask = detail::mapStateToAccess(desc.initialState);
imageMemoryBarrier.image = image;
imageMemoryBarrier.subresourceRange = VkImageSubresourceRange { aspectFlags, 0, desc.mipLevels, 0, desc.depthOrArrayLayers };
table->vkCmdPipelineBarrier(static_cast<VkCommandBuffer>(m_workCmdList),
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, detail::mapStateToPipelineStage(desc.initialState), {},
0, nullptr, 0, nullptr, 1, &imageMemoryBarrier);
table->vkEndCommandBuffer(static_cast<VkCommandBuffer>(m_workCmdList));
VkSubmitInfo submit {};
submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit.pNext = nullptr;
submit.commandBufferCount = 1;
submit.pCommandBuffers = reinterpret_cast<VkCommandBuffer*>(&m_workCmdList);
submit.signalSemaphoreCount = 0;
submit.pSignalSemaphores = nullptr;
submit.waitSemaphoreCount = 0;
submit.pWaitSemaphores = nullptr;
submit.pWaitDstStageMask = nullptr;
table->vkQueueSubmit(static_cast<VkQueue>(getQueue(m_workQueueType, 0)->m_ptrs[0]), 1, &submit, static_cast<VkFence>(m_workFence));
table->vkWaitForFences(static_cast<VkDevice>(m_ptr), 1, reinterpret_cast<VkFence*>(&m_workFence), VK_TRUE, std::numeric_limits<uint64_t>::max());
table->vkResetFences(static_cast<VkDevice>(m_ptr), 1, reinterpret_cast<VkFence*>(&m_workFence));
}
auto* output = new Resource();
output->m_desc = desc;
output->m_resource = isTexture ? static_cast<Resource::native_resource*>(image) : static_cast<Resource::native_resource*>(buffer);
output->m_memory = memory;
*resource = output;
return result::Success;
}
void Device::impl_destroyResource(Resource* resource)
{
const bool isTexture = resource->m_desc.type != resource_type::Buffer;
if (isTexture)
static_cast<VolkDeviceTable*>(m_functionTable)->vkDestroyImage(static_cast<VkDevice>(m_ptr), static_cast<VkImage>(resource->m_resource), nullptr);
else
static_cast<VolkDeviceTable*>(m_functionTable)->vkDestroyBuffer(static_cast<VkDevice>(m_ptr), static_cast<VkBuffer>(resource->m_resource), nullptr);
static_cast<VolkDeviceTable*>(m_functionTable)->vkFreeMemory(static_cast<VkDevice>(m_ptr), static_cast<VkDeviceMemory>(resource->m_memory), nullptr);
}
}
| 42.340116 | 160 | 0.646413 |
8e90fefa694ca74307c3d8b7758f4510a1e6acf2 | 11,757 | cpp | C++ | src/args.cpp | valet-bridge/valet | 8e20da1b496cb6fa42894b9ef420375cb7a5d2cd | [
"Apache-2.0"
] | null | null | null | src/args.cpp | valet-bridge/valet | 8e20da1b496cb6fa42894b9ef420375cb7a5d2cd | [
"Apache-2.0"
] | 1 | 2015-11-15T08:20:33.000Z | 2018-03-04T09:48:23.000Z | src/args.cpp | valet-bridge/valet | 8e20da1b496cb6fa42894b9ef420375cb7a5d2cd | [
"Apache-2.0"
] | null | null | null | /*
Valet, a generalized Butler scorer for bridge.
Copyright (C) 2015 by Soren Hein.
See LICENSE and README.
*/
// These functions parse the command line for options.
#include <iostream>
#include <iomanip>
#include <string>
#include <stdlib.h>
#include <string.h>
#include "args.h"
#include "cst.h"
using namespace std;
extern OptionsType options;
struct optEntry
{
string shortName;
string longName;
unsigned numArgs;
};
#define VALET_NUM_OPTIONS 16
const optEntry optList[VALET_NUM_OPTIONS] =
{
{"v", "valettype", 1},
{"d", "directory", 1},
{"n", "names", 1},
{"s", "scores", 1},
{"r", "rounds", 1},
{"m", "minhands", 1},
{"l", "leads", 0},
{"e", "extremes", 0},
{"h", "hardround", 0},
{"t", "tableau", 1},
{"x", "nocloud", 0},
{"c", "compensate", 0},
{"o", "order", 1},
{"a", "average", 0},
{"f", "format", 1},
{"j", "join", 1}
};
string shortOptsAll, shortOptsWithArg;
int GetNextArgToken(
int argc,
char * argv[]);
void SetDefaults();
bool ParseRound();
void Usage(
const char base[])
{
string basename(base);
const size_t l = basename.find_last_of("\\/");
if (l != string::npos)
basename.erase(0, l+1);
cout <<
"Usage: " << basename << " [options]\n\n" <<
"-v, --valettype s Valet type, one of datum, imps, matchpoints\n" <<
" (default: imps).\n" <<
"\n" <<
"-d, --directory s Read the input files from directory s.\n" <<
"\n" <<
"-n, --names s Use s as the names file (default names.txt)\n" <<
"\n" <<
"-s, --scores s Use s as the scores file (default scores.txt)\n" <<
"\n" <<
"-r, --rounds list Selects only rounds specified in list.\n" <<
" Example (note: no spaces) 1,3-5,7 (default all)\n" <<
"\n" <<
"-m, --minhands m Only show results for pairs/players who have\n" <<
" played at least m hands (default 0)\n" <<
"\n" <<
"-l, --lead Show a Valet score for the lead separately\n" <<
" (default: no)\n" <<
"\n" <<
"-e, --extremes When calculating datum score (only for Butler\n" <<
" IMPs), throw out the maximum and minimum\n" <<
" scores (default: no, -e turns it on).\n" <<
"\n" <<
"-h, --hardround When calculating datum score (only for Butler\n" <<
" IMPs), round down and not to the nearest\n" <<
" score. So 379 rounds to 370, not to 380\n" <<
" (default: no).\n" <<
"\n" <<
"-x, --nocloud Use the simpler, but mathematically less\n" <<
" satisfying Valet score (default: not set).\n" <<
"\n" <<
"-t, --tableau Output a file of tableaux for each hand\n" <<
" to file argument (default: not set).\n" <<
"\n" <<
"-c, -compensate Compensate overall score for the average strength\n" <<
" of the specific opponents faced (default: no).\n" <<
"\n" <<
"-o, --order s Sorting order of the output. Valid orders are\n" <<
" overall, bidding, play, defense, lead,\n" <<
" bidoverplay (bidding minus play),\n" <<
" defoverplay (defense minus play),\n" <<
" leadoverplay (lead minus play),\n" <<
" (case-insensitive).\n" <<
"\n" <<
"-a, --average Show certain averages in the output tables.\n"
"\n" <<
"-f, --format s Output file format: text or csv (broadly\n" <<
" speaking, comma-separated values suitable for\n" <<
" loading into e.g. Microsoft Excel)\n" <<
" (default: text).\n" <<
"\n" <<
"-j, --join c Separator for csv output (default the comma,\n" <<
" ',' (without the marks). In German Excel it \n" <<
" is useful to set this to ';', and so on.\n" <<
endl;
}
int nextToken = 1;
char * optarg;
int GetNextArgToken(
int argc,
char * argv[])
{
// 0 means done, -1 means error.
if (nextToken >= argc)
return 0;
string str(argv[nextToken]);
if (str[0] != '-' || str.size() == 1)
return -1;
if (str[1] == '-')
{
if (str.size() == 2)
return -1;
str.erase(0, 2);
}
else if (str.size() == 2)
str.erase(0, 1);
else
return -1;
for (unsigned i = 0; i < VALET_NUM_OPTIONS; i++)
{
if (str == optList[i].shortName || str == optList[i].longName)
{
if (optList[i].numArgs == 1)
{
if (nextToken+1 >= argc)
return -1;
optarg = argv[nextToken+1];
nextToken += 2;
}
else
nextToken++;
return str[0];
}
}
return -1;
}
void SetDefaults()
{
options.valet = VALET_IMPS_ACROSS_FIELD;
options.directory = ".";
options.nameFile = "names.txt";
options.scoresFile = "scores.txt";
options.roundFlag = false;
options.roundFirst = 0;
options.roundLast = 0;
options.minHands = 0;
options.leadFlag = false;
options.datumFilter = false;
options.datumHardRounding = false;
options.cloudFlag = true;
options.tableauFlag = false;
options.compensateFlag = false;
options.sort = VALET_SORT_OVERALL;
options.averageFlag = false;
options.format = VALET_FORMAT_TEXT;
options.separator = ',';
}
void PrintOptions()
{
cout << left;
cout << setw(12) << "valettype" << setw(12) <<
scoringTags[options.valet].arg << "\n";
cout << setw(12) << "directory" << setw(12) << options.directory << "\n";
cout << setw(12) << "names" << setw(12) << options.nameFile << "\n";
cout << setw(12) << "scores" << setw(12) << options.scoresFile << "\n";
if (options.roundFlag)
cout << setw(12) << "rounds" << options.roundFirst << " to " <<
options.roundLast << "\n";
else
cout << setw(12) << "rounds" << "no limitation\n";
cout << setw(12) << "minhands" << setw(12) << options.minHands << "\n";
cout << setw(12) << "lead" << setw(12) <<
(options.leadFlag ? "true" : "false") << "\n";
cout << setw(12) << "extremes" << setw(12) <<
(options.datumFilter ? "true" : "false") << "\n";
cout << setw(12) << "hardround" << setw(12) <<
(options.datumHardRounding ? "true" : "false") << "\n";
cout << setw(12) << "cloud" << setw(12) <<
(options.cloudFlag ? "true" : "false") << "\n";
cout << setw(12) << "tableau" << setw(12) <<
(options.datumHardRounding ? options.tableauFile : "false") << "\n";
cout << setw(12) << "compensate" << setw(12) <<
(options.compensateFlag ? "true" : "false") << "\n";
cout << setw(12) << "order" << setw(12) <<
sortingTags[options.sort].str << "\n";
cout << setw(12) << "average" << setw(12) <<
(options.averageFlag ? "true" : "false") << "\n";
cout << setw(12) << "format" << setw(12) <<
(options.format == VALET_FORMAT_TEXT ? "text" : "csv") << "\n";
cout << setw(12) << "join" << setw(12) << options.separator << "\n";
cout << "\n" << right;
}
bool ParseRound()
{
// Allow 5 as well as 1-3
char * temp;
int m = static_cast<int>(strtol(optarg, &temp, 0));
if (* temp == '\0')
{
if (m <= 0)
{
return false;
}
else
{
options.roundFirst = static_cast<unsigned>(m);
options.roundLast = static_cast<unsigned>(m);
return true;
}
}
string stmp(optarg);
string::size_type pos;
pos = stmp.find_first_of("-", 0);
if (pos == std::string::npos || pos > 7)
return false;
char str1[8], str2[8];
#if (! defined(_MSC_VER) || _MSC_VER < 1400)
strncpy(str1, stmp.c_str(), pos);
#else
strncpy_s(str1, stmp.c_str(), pos);
#endif
str1[pos] = '\0';
if ((m = atoi(str1)) <= 0)
return false;
options.roundFirst = static_cast<unsigned>(m);
stmp.erase(0, pos+1);
#if (! defined(_MSC_VER) || _MSC_VER < 1400)
strncpy(str2, stmp.c_str(), stmp.size());
#else
strncpy_s(str2, stmp.c_str(), stmp.size());
#endif
str2[stmp.size()] = '\0';
if ((m = atoi(str2)) <= 0)
return false;
options.roundLast = static_cast<unsigned>(m);
if (options.roundLast < options.roundFirst)
return false;
return true;
}
void ReadArgs(
int argc,
char * argv[])
{
for (unsigned i = 0; i < VALET_NUM_OPTIONS; i++)
{
shortOptsAll += optList[i].shortName;
if (optList[i].numArgs)
shortOptsWithArg += optList[i].shortName;
}
if (argc == 1)
{
Usage(argv[0]);
exit(0);
}
SetDefaults();
int c, m;
bool errFlag = false, matchFlag;
string stmp;
while ((c = GetNextArgToken(argc, argv)) > 0)
{
switch(c)
{
case 'v':
stmp = optarg;
matchFlag = false;
for (unsigned i = 0; i < 3; i++)
{
if (stmp == scoringTags[i].arg)
{
options.valet = scoringTags[i].scoring;
matchFlag = true;
break;
}
}
if (! matchFlag)
{
cout << "valet must be written exactly as in the list\n";
nextToken -= 2;
errFlag = true;
}
break;
case 'd':
options.directory = optarg;
break;
case 'n':
options.nameFile = optarg;
break;
case 's':
options.scoresFile = optarg;
break;
case 'r':
options.roundFlag = true;
if (! ParseRound())
{
cout << " Could not parse round\n";
nextToken -= 2;
errFlag = true;
}
break;
case 'm':
char * temp;
m = static_cast<int>(strtol(optarg, &temp, 0));
if (m < 1)
{
cout << "Number of hands must be >= 1\n\n";
nextToken -= 2;
errFlag = true;
}
options.minHands = static_cast<unsigned>(m);
break;
case 'l':
options.leadFlag = true;
break;
case 'e':
options.datumFilter = true;
break;
case 'h':
options.datumHardRounding = true;
break;
case 'x':
options.cloudFlag = false;
break;
case 't':
options.tableauFlag = true;
options.tableauFile = optarg;
break;
case 'c':
options.compensateFlag = true;
break;
case 'o':
stmp = optarg;
matchFlag = false;
for (unsigned i = 0; i < 8; i++)
{
if (stmp == sortingTags[i].str)
{
options.sort = sortingTags[i].sort;
matchFlag = true;
break;
}
}
if (! matchFlag)
{
cout << "order must be written exactly as in the list\n";
nextToken -= 2;
errFlag = true;
}
break;
case 'a':
options.averageFlag = true;
break;
case 'f':
stmp = optarg;
if (stmp == "text")
options.format = VALET_FORMAT_TEXT;
else if (stmp == "csv")
options.format = VALET_FORMAT_CSV;
else
{
cout << "format must be text or csv\n";
nextToken -= 2;
errFlag = true;
}
break;
case 'j':
options.separator = optarg;
if (options.separator.size() != 1)
{
cout << "char must consist of a single character\n";
nextToken -= 2;
errFlag = true;
}
break;
default:
cout << "Unknown option\n";
errFlag = true;
break;
}
if (errFlag)
break;
}
if (errFlag || c == -1)
{
cout << "Error while parsing option '" << argv[nextToken] << "'\n";
cout << "Invoke the program without arguments for help" << endl;
exit(0);
}
}
| 25.06823 | 79 | 0.514417 |
8e91c7f6dbd37560842a3312c31bd1bb3530d8c5 | 1,258 | cpp | C++ | source/ktwgEngine/Shaders/cpp/SimpleForwardParams.cpp | JasonWyx/ktwgEngine | 410ba799f7000895995b9f9fc59d738f293f8871 | [
"MIT"
] | null | null | null | source/ktwgEngine/Shaders/cpp/SimpleForwardParams.cpp | JasonWyx/ktwgEngine | 410ba799f7000895995b9f9fc59d738f293f8871 | [
"MIT"
] | 12 | 2019-09-15T07:48:18.000Z | 2019-12-08T17:23:22.000Z | source/ktwgEngine/Shaders/cpp/SimpleForwardParams.cpp | JasonWyx/ktwgEngine | 410ba799f7000895995b9f9fc59d738f293f8871 | [
"MIT"
] | null | null | null | #include "SimpleForwardParams.h"
#include "../../d3d11staticresources.h"
#include "../../d3d11device.h"
#include "../../d3d11renderapi.h"
#include "../../d3d11hardwarebuffer.h"
DEFINE_STATIC_BUFFER(SimpleForwardParamsCbuf);
void ShaderInputs::SimpleForwardParams::InitializeHWResources()
{
D3D11Device* device = D3D11RenderAPI::GetInstance().GetDevice();
GET_STATIC_RESOURCE(SimpleForwardParamsCbuf) = new D3D11HardwareBuffer{ device, D3D11_BT_CONSTANT, D3D11_USAGE_DYNAMIC, 4, sizeof(float), false, false, true, false };
}
void ShaderInputs::SimpleForwardParams::SetColor(float r, float g, float b, float a)
{
m_Color[0] = r;
m_Color[1] = g;
m_Color[2] = b;
m_Color[3] = a;
}
void ShaderInputs::SimpleForwardParams::GetColor(float & r, float & g, float & b, float & a)
{
r = m_Color[0];
g = m_Color[1];
b = m_Color[2];
a = m_Color[3];
}
void ShaderInputs::SimpleForwardParams::Set()
{
D3D11Device* device = D3D11RenderAPI::GetInstance().GetDevice();
device->GetImmediateContext().AddConstantBuffer<VS>(GET_STATIC_RESOURCE(SimpleForwardParamsCbuf));
device->GetImmediateContext().FlushConstantBuffers(SimpleForwardParamsSlot);
GET_STATIC_RESOURCE(SimpleForwardParamsCbuf)->Write(0, 4 * sizeof(float), m_Color, WT_DISCARD);
} | 33.105263 | 168 | 0.744038 |
8e9237b34847f87599b4046af1bf3917cb94a324 | 1,985 | cpp | C++ | catdoor_v2/tests/solenoids/src/main.cpp | flupes/catdoor | bf718f4ebdfb8cc60c04d42d3d88a4a875f0bc7f | [
"Apache-2.0"
] | null | null | null | catdoor_v2/tests/solenoids/src/main.cpp | flupes/catdoor | bf718f4ebdfb8cc60c04d42d3d88a4a875f0bc7f | [
"Apache-2.0"
] | null | null | null | catdoor_v2/tests/solenoids/src/main.cpp | flupes/catdoor | bf718f4ebdfb8cc60c04d42d3d88a4a875f0bc7f | [
"Apache-2.0"
] | null | null | null | #include <Arduino.h>
#include "m0_hf_pwm.h"
#include "solenoids.h"
#include "utils.h"
Solenoids& sol = Solenoids::Instance();
void setup() {
pwm_configure();
#ifdef USE_SERIAL
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect to start the app
}
#endif
PRINTLN("open in 5s");
delay(5000);
sol.open();
delay(3000);
PRINTLN("release");
sol.release();
PRINTLN("open (other side) is 5s");
delay(5000);
sol.open();
delay(3000);
PRINTLN("release");
sol.release();
PRINTLN("unjam is 5s");
delay(5000);
sol.unjam();
PRINTLN("should release in 2s");
delay(8000);
PRINTLN("should unjam again, now");
sol.unjam();
PRINTLN("should release in 2s");
delay(8000);
PRINTLN("open and do not release (hot timer should release)");
sol.open();
delay(Solenoids::MAX_ON_DURATION_MS + 4000);
PRINTLN("try to open again, but should not work (because hot)");
sol.open();
delay(Solenoids::COOLDOWN_DURATION_MS);
PRINTLN("cold now, double open/release");
sol.open();
delay(500);
sol.release();
delay(500);
sol.open();
delay(500);
sol.release();
PRINTLN("open in 5s");
delay(5000);
sol.open();
delay(1000);
PRINTLN("open again, now, but should not do anything since still open");
sol.open();
delay(4000);
PRINTLN("release");
sol.release();
PRINTLN("open in 5s");
delay(5000);
sol.open();
delay(1000);
PRINTLN("unjam now (before release)");
sol.unjam();
PRINTLN("should release automatically");
delay(8000);
PRINTLN(" before this message");
sol.release();
PRINTLN("double open/release");
sol.open();
delay(500);
sol.release();
delay(500);
sol.open();
delay(500);
sol.release();
PRINTLN("done.");
}
void loop() {
delay(10);
#if 0
// Old Tests
pwm_set(5, 512);
delay(500);
pwm_set(5, 300);
delay(500);
pwm_set(6, 512);
delay(500);
pwm_set(6, 128);
delay(4000);
pwm_set(5, 0);
pwm_set(6, 0);
delay(8000);
#endif
}
| 18.726415 | 74 | 0.63073 |
8e9305816904c0b57e845732123269d7b633b295 | 935 | cc | C++ | list/reversed_linked_list.cc | windscope/Cracking | 0db01f531ff56428bafff72aaea1d046dbc14112 | [
"Apache-2.0"
] | null | null | null | list/reversed_linked_list.cc | windscope/Cracking | 0db01f531ff56428bafff72aaea1d046dbc14112 | [
"Apache-2.0"
] | null | null | null | list/reversed_linked_list.cc | windscope/Cracking | 0db01f531ff56428bafff72aaea1d046dbc14112 | [
"Apache-2.0"
] | null | null | null | // Reverse Linked List
// https://leetcode.com/problems/reverse-linked-list/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <cassert>
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == nullptr) {
return nullptr;
}
ListNode* next_head = head->next;
head->next = nullptr;
ListNode* ret_head = head;
while (next_head != nullptr) {
ListNode* ret_head_next = ret_head;
ret_head = next_head;
next_head = next_head->next;
ret_head->next = ret_head_next;
}
}
};
int main() {
cout << "You Passed" << endl;
return 0;
}
| 19.479167 | 53 | 0.562567 |
8e93b94653d2a195f6e71e7d32f00cd54d02a1ec | 1,255 | cpp | C++ | source/model-generator/JoinOverrideGenerator.cpp | bbhunter/mariana-trench | 3973f047446182977809ea4ae2b76153a35943f8 | [
"MIT"
] | null | null | null | source/model-generator/JoinOverrideGenerator.cpp | bbhunter/mariana-trench | 3973f047446182977809ea4ae2b76153a35943f8 | [
"MIT"
] | null | null | null | source/model-generator/JoinOverrideGenerator.cpp | bbhunter/mariana-trench | 3973f047446182977809ea4ae2b76153a35943f8 | [
"MIT"
] | null | null | null | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <mariana-trench/Model.h>
#include <mariana-trench/model-generator/JoinOverrideGenerator.h>
namespace marianatrench {
std::vector<Model> JoinOverrideGenerator::visit_method(
const Method* method) const {
std::vector<Model> models;
// Do not join models at call sites for methods with too many overrides.
const auto& overrides = context_.overrides->get(method);
if (overrides.size() >= Heuristics::kJoinOverrideThreshold) {
models.push_back(
Model(method, context_, Model::Mode::NoJoinVirtualOverrides));
} else {
const auto class_name = generator::get_class_name(method);
if ((boost::starts_with(class_name, "Landroid") ||
boost::starts_with(class_name, "Lcom/google") ||
boost::starts_with(class_name, "Lkotlin/") ||
boost::starts_with(class_name, "Ljava")) &&
overrides.size() >= Heuristics::kAndroidJoinOverrideThreshold) {
models.push_back(
Model(method, context_, Model::Mode::NoJoinVirtualOverrides));
}
}
return models;
}
} // namespace marianatrench
| 33.026316 | 74 | 0.701195 |
8e95d0497dcaaf0712c7bde70764b4140ed2013d | 3,306 | cpp | C++ | src/core/tests/visitors/op/interpolate.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 1,127 | 2018-10-15T14:36:58.000Z | 2020-04-20T09:29:44.000Z | src/core/tests/visitors/op/interpolate.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 439 | 2018-10-20T04:40:35.000Z | 2020-04-19T05:56:25.000Z | src/core/tests/visitors/op/interpolate.cpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 414 | 2018-10-17T05:53:46.000Z | 2020-04-16T17:29:53.000Z | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "gtest/gtest.h"
#include "ngraph/ngraph.hpp"
#include "ngraph/op/util/attr_types.hpp"
#include "ngraph/opsets/opset1.hpp"
#include "ngraph/opsets/opset3.hpp"
#include "ngraph/opsets/opset4.hpp"
#include "ngraph/opsets/opset5.hpp"
#include "util/visitor.hpp"
using namespace std;
using namespace ngraph;
using ngraph::test::NodeBuilder;
using ngraph::test::ValueMap;
TEST(attributes, interpolate_op1) {
NodeBuilder::get_ops().register_factory<opset1::Interpolate>();
auto img = make_shared<op::Parameter>(element::f32, Shape{1, 3, 32, 32});
auto out_shape = make_shared<op::Parameter>(element::i32, Shape{2});
op::v0::InterpolateAttrs interp_atrs;
interp_atrs.axes = AxisSet{1, 2};
interp_atrs.mode = "cubic";
interp_atrs.align_corners = true;
interp_atrs.antialias = true;
interp_atrs.pads_begin = vector<size_t>{0, 0};
interp_atrs.pads_end = vector<size_t>{0, 0};
auto interpolate = make_shared<opset1::Interpolate>(img, out_shape, interp_atrs);
NodeBuilder builder(interpolate);
auto g_interpolate = ov::as_type_ptr<opset1::Interpolate>(builder.create());
const auto i_attrs = interpolate->get_attrs();
const auto g_i_attrs = g_interpolate->get_attrs();
EXPECT_EQ(g_i_attrs.axes, i_attrs.axes);
EXPECT_EQ(g_i_attrs.mode, i_attrs.mode);
EXPECT_EQ(g_i_attrs.align_corners, i_attrs.align_corners);
EXPECT_EQ(g_i_attrs.antialias, i_attrs.antialias);
EXPECT_EQ(g_i_attrs.pads_begin, i_attrs.pads_begin);
EXPECT_EQ(g_i_attrs.pads_end, i_attrs.pads_end);
}
TEST(attributes, interpolate_op4) {
NodeBuilder::get_ops().register_factory<opset4::Interpolate>();
auto img = make_shared<op::Parameter>(element::f32, Shape{1, 3, 32, 32});
auto out_shape = make_shared<op::Parameter>(element::i32, Shape{2});
auto scales = op::v0::Constant::create(element::f32, {1}, {1.0});
op::v4::Interpolate::InterpolateAttrs attrs;
attrs.mode = op::v4::Interpolate::InterpolateMode::NEAREST;
attrs.shape_calculation_mode = op::v4::Interpolate::ShapeCalcMode::SIZES;
attrs.coordinate_transformation_mode = op::v4::Interpolate::CoordinateTransformMode::HALF_PIXEL;
attrs.nearest_mode = op::v4::Interpolate::NearestMode::ROUND_PREFER_FLOOR;
attrs.pads_begin = vector<size_t>{0, 0};
attrs.pads_end = vector<size_t>{0, 0};
attrs.antialias = true;
attrs.cube_coeff = -0.75;
auto interpolate = make_shared<opset4::Interpolate>(img, out_shape, scales, attrs);
NodeBuilder builder(interpolate);
auto g_interpolate = ov::as_type_ptr<opset4::Interpolate>(builder.create());
const auto i_attrs = interpolate->get_attrs();
const auto g_i_attrs = g_interpolate->get_attrs();
EXPECT_EQ(g_i_attrs.mode, i_attrs.mode);
EXPECT_EQ(g_i_attrs.shape_calculation_mode, i_attrs.shape_calculation_mode);
EXPECT_EQ(g_i_attrs.coordinate_transformation_mode, i_attrs.coordinate_transformation_mode);
EXPECT_EQ(g_i_attrs.nearest_mode, i_attrs.nearest_mode);
EXPECT_EQ(g_i_attrs.pads_begin, i_attrs.pads_begin);
EXPECT_EQ(g_i_attrs.pads_end, i_attrs.pads_end);
EXPECT_EQ(g_i_attrs.antialias, i_attrs.antialias);
EXPECT_EQ(g_i_attrs.cube_coeff, i_attrs.cube_coeff);
} | 42.384615 | 100 | 0.740472 |
8e97a5b95fe2ad04a91d0beb91126d71b13e1664 | 1,885 | cpp | C++ | state.cpp | sl424/hunting-game | f79bea39a061c8b8cfbf430ab0d73cd6539ddb0f | [
"Apache-2.0"
] | null | null | null | state.cpp | sl424/hunting-game | f79bea39a061c8b8cfbf430ab0d73cd6539ddb0f | [
"Apache-2.0"
] | null | null | null | state.cpp | sl424/hunting-game | f79bea39a061c8b8cfbf430ab0d73cd6539ddb0f | [
"Apache-2.0"
] | null | null | null | /***************************************************
* Program Filename: state.cpp
* Author: Chewie Lin
* Date: 12 Feb 2016
* Description: main driver functions
***************************************************/
#include "state.hpp"
/*****************************************
* Function: pEnter()
* Description: press enter to continue
******************************************/
void pEnter() {
std::cin.ignore(125,'\n');
std::cout << "Press enter to continue: " << std::flush;
std::cin.ignore(125,'\n');
}
/*****************************************
* Function: pick()
* Description: ask user input
******************************************/
int pick() {
int pick;
do {
std::cout << "Select a creature: ";
std::cin >> pick;
if ( std::cin.fail() || pick < 1 || pick > 5 ) {
std::cout << "invalid pick" << std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
}
} while ( pick < 1 || pick > 5 );
return pick;
}
/*****************************************
* Function: showGraphics()
* Description:
******************************************/
void showGraphics(std::string& s) {
std::string aline;
std::ifstream input;
input.open(s.c_str(), std::ifstream::in);
if ( input.is_open() ) {
while ( std::getline (input,aline) )
std::cout << aline << '\n';
input.close();
}
else std::cout << "error opening file";
}
/*****************************************
* Function: displayMenu()
* Description: show the list of creatures
******************************************/
bool displayMenu() {
char a;
do {
std::cout << " 0: How to play \n 1: Start Game \n 2: Quit \n";
std::cout << "Enter input: ";
std::cin >> a;
if ( a == '0' )
showGamePlay();
if ( a == '1' )
return true;
else if ( a == '2' )
return false;
} while ( a != '1' && a != '2' );
}
void showGamePlay(){
std::string s = "gameplay.txt";
showGraphics(s);
}
| 24.802632 | 63 | 0.448276 |
8e9a7dfe8704ce896e0a39c9eea55cf64eb395f7 | 89 | cpp | C++ | applications/Example/Example.cpp | 203Electronics/MatrixOS | ea6d84b21a97f58e2077d37d5645c5339f344d77 | [
"MIT"
] | 8 | 2021-12-30T05:29:16.000Z | 2022-03-30T08:44:45.000Z | applications/Example/Example.cpp | 203Electronics/MatrixOS | ea6d84b21a97f58e2077d37d5645c5339f344d77 | [
"MIT"
] | null | null | null | applications/Example/Example.cpp | 203Electronics/MatrixOS | ea6d84b21a97f58e2077d37d5645c5339f344d77 | [
"MIT"
] | null | null | null | #include "Example.h"
void ExampleAPP::Setup()
{
}
void ExampleAPP::Loop()
{
} | 7.416667 | 24 | 0.58427 |
8ea74d1a47c9c79b1f9ab67b2ce4a36f7bc94a10 | 1,380 | cc | C++ | test/HttpServer/compute_unittest.cc | wfrest/wfrest | 5aa8c3ab5ad749ef8e9b93c8aa32d8c475062dde | [
"Apache-2.0"
] | 312 | 2021-12-05T15:17:27.000Z | 2022-03-30T10:53:01.000Z | test/HttpServer/compute_unittest.cc | chanchann/wfrest | 5aa8c3ab5ad749ef8e9b93c8aa32d8c475062dde | [
"Apache-2.0"
] | 15 | 2021-12-14T16:01:15.000Z | 2022-03-15T04:27:47.000Z | test/HttpServer/compute_unittest.cc | wfrest/wfrest | 5aa8c3ab5ad749ef8e9b93c8aa32d8c475062dde | [
"Apache-2.0"
] | 46 | 2021-12-06T08:08:45.000Z | 2022-03-01T06:26:38.000Z | #include "workflow/WFFacilities.h"
#include "workflow/Workflow.h"
#include <gtest/gtest.h>
#include "wfrest/HttpServer.h"
#include "wfrest/ErrorCode.h"
using namespace wfrest;
using namespace protocol;
WFHttpTask *create_http_task(const std::string &path)
{
return WFTaskFactory::create_http_task("http://127.0.0.1:8888/" + path, 4, 2, nullptr);
}
void Factorial(int n, HttpResp *resp)
{
unsigned long long factorial = 1;
for(int i = 1; i <= n; i++)
{
factorial *= i;
}
resp->String(std::to_string(factorial));
}
TEST(HttpServer, String_short_str)
{
HttpServer svr;
WFFacilities::WaitGroup wait_group(1);
svr.GET("/test", [](const HttpReq *req, HttpResp *resp)
{
resp->Compute(1, Factorial, 10, resp);
});
EXPECT_TRUE(svr.start("127.0.0.1", 8888) == 0) << "http server start failed";
WFHttpTask *client_task = create_http_task("test");
client_task->set_callback([&wait_group](WFHttpTask *task)
{
const void *body;
size_t body_len;
task->get_resp()->get_parsed_body(&body, &body_len);
EXPECT_TRUE(strcmp("3628800", static_cast<const char *>(body)) == 0);
wait_group.done();
});
client_task->start();
wait_group.wait();
svr.stop();
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | 24.210526 | 91 | 0.642029 |
8ea86625c443698315f5223a9ad55d2a3299a44b | 242 | cpp | C++ | tests/aoj/bigint.multiplication_bigint_1.test.cpp | Zeldacrafter/CompProg | 5367583f45b6fe30c4c84f3ae81accf14f8f7fd3 | [
"Unlicense"
] | 4 | 2020-02-06T15:44:57.000Z | 2020-12-21T03:51:21.000Z | tests/aoj/bigint.multiplication_bigint_1.test.cpp | Zeldacrafter/CompProg | 5367583f45b6fe30c4c84f3ae81accf14f8f7fd3 | [
"Unlicense"
] | null | null | null | tests/aoj/bigint.multiplication_bigint_1.test.cpp | Zeldacrafter/CompProg | 5367583f45b6fe30c4c84f3ae81accf14f8f7fd3 | [
"Unlicense"
] | null | null | null | #define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=NTL_2_C"
#include "../../code/utils/bigint.cc"
int main() {
cin.tie(0);
ios_base::sync_with_stdio(0);
bigint a, b;
cin >> a >> b;
cout << a * b << endl;
}
| 18.615385 | 82 | 0.619835 |
8ea8a2ac3154f2b3d99c1dffbf24fc33b56b1b3c | 3,018 | cpp | C++ | test/tsarray2.cpp | drypot/san-2.x | 44e626793b1dc50826ba0f276d5cc69b7c9ca923 | [
"MIT"
] | 5 | 2019-12-27T07:30:03.000Z | 2020-10-13T01:08:55.000Z | test/tsarray2.cpp | drypot/san-2.x | 44e626793b1dc50826ba0f276d5cc69b7c9ca923 | [
"MIT"
] | null | null | null | test/tsarray2.cpp | drypot/san-2.x | 44e626793b1dc50826ba0f276d5cc69b7c9ca923 | [
"MIT"
] | 1 | 2020-07-27T22:36:40.000Z | 2020-07-27T22:36:40.000Z |
#include <pub\config.hpp>
#include <stdpub\io.hpp>
#include <pub\except.hpp>
#include <pub\inline.hpp>
#include <pub\char.hpp>
#include <cnt\sarray.tem>
#include <conpub\io.hpp>
#include <time.h>
#include <pub\buffer.hpp>
#include <pub\fbuf.hpp>
typedef sarray<char16,8*1024> arrayt;
//char* fname = "fmid";
char* fname = "fbig";
buffer<char16,8*1024> buf;
arrayt ary;
clock_t clk;
FILE* f;
int32 cnt,i;
void view(arrayt* pa)
{
arrayt::frame* p;
p = pa->head.p_next;
while (p!= (arrayt::frame*) &pa->tail)
{
printf("%4d ",p->cnt);
p = p->p_next;
}
printf("\n");
}
void iter_test()
{
printf("iter ready\n");
getch();
printf("iter start\n");
clk = clock();
forcnt(i,cnt) ary[i]=ary[i]+1;
printf("%u clocks\n",clock()-clk);
printf("end\n");
}
void fread_test()
{
//ifbuf f("fbig",32*1024);
int ch;
cnt = 0;
buf.reset();
ary.reset();
f = fopen(fname,"rb");
printf("ready\n");
getch();
printf("start\n");
clk = clock();
while (ch = fgetc(f) , ch != EOF) ary[cnt++] = ch;
printf("%u clocks\n",clock()-clk);
printf("%d chars\n",cnt);
fclose(f);
}
void fread2_test()
{
//ifbuf f("fbig",32*1024);
int ch;
int ch2;
cnt = 0;
buf.reset();
ary.reset();
f = fopen(fname,"rb");
printf("ready\n");
getch();
printf("start\n");
clk = clock();
while (ch = fgetc(f) , ch != EOF)
{
cnt++;
if (is_full((byte)ch))
{
ch2 = fgetc(f);
buf.append(char16_make(ch,ch2));
}
else buf.append(ch);
if (buf.is_full())
{
ary.locate_end();
ary.insert(buf.cnt());
ary.read(buf,buf.cnt());
buf.reset();
//view(&ary);
//getch();
}
}
printf("%u clocks\n",clock()-clk);
printf("%d chars\n",cnt);
fclose(f);
}
void fread3_test()
{
ifbuf f(fname,16*1024);
int ch;
int ch2;
cnt = 0;
buf.reset();
ary.reset();
printf("ready\n");
getch();
printf("start\n");
clk = clock();
forever
{
if ( f.rest() <= 2 )
{
if ( f.file_rest() == 0 )
{
if ( f.rest() == 1 && is_full(f.peek8()) ) f.append(0);
if ( f.rest() == 0 ) break;
}
else f.fill();
}
ch = f.get8();
cnt++;
if (is_full((byte)ch))
{
ch2 = f.get8();
buf.append(char16_make(ch,ch2));
}
else buf.append(ch);
if (buf.is_full())
{
ary.locate_end();
ary.insert(buf.cnt());
ary.read(buf,buf.cnt());
buf.reset();
//view(&ary);
//getch();
}
}
printf("%u clocks\n",clock()-clk);
printf("%d chars\n",cnt);
}
void main()
{
touch_err_module();
throw int();
fread_test();
fread2_test();
//fread3_test();
//test_iter();
}
| 18.745342 | 68 | 0.470179 |
8ea9435ee69f6139fa6d3430ace8728bd50421b8 | 1,795 | cpp | C++ | src/one_tree.cpp | LukasErlenbach/tsp_solver | 016a1e794de7b58f666b3635977e39aeadb46c99 | [
"MIT"
] | null | null | null | src/one_tree.cpp | LukasErlenbach/tsp_solver | 016a1e794de7b58f666b3635977e39aeadb46c99 | [
"MIT"
] | null | null | null | src/one_tree.cpp | LukasErlenbach/tsp_solver | 016a1e794de7b58f666b3635977e39aeadb46c99 | [
"MIT"
] | null | null | null | #include "branching_node.hpp"
/**
* @file one_tree.hpp
* @brief Implementation of class @c OneTree.
* **/
namespace Core {
/////////////////////////////////////////////
//! \c OneTree definitions
/////////////////////////////////////////////
OneTree::OneTree(const PredVec &preds, const Degrees °rees, const double cost)
: _preds(preds), _degrees(degrees), _cost(cost) {}
// this test is sufficient since PredVecs are assumed to be connected (since
// they encode OneTrees)
bool OneTree::is_tour() const {
for (Degree d : _degrees) {
if (d != 2) {
return false;
}
}
return true;
}
// greedily finds a node with degree > 2
NodeId OneTree::hd_node() const {
for (NodeId node_id = 0; node_id < _degrees.size(); ++node_id) {
if (_degrees[node_id] > 2) {
return node_id;
}
}
// this case should never occur, we only call this after checking with
// is_tour()
throw std::runtime_error("Error in OneTree::hd_node(): No node with degree > 2.");
return invalid_node_id;
}
NodeIds OneTree::neighbors(const NodeId node_id) const {
NodeIds neighbors = {};
neighbors.reserve(_degrees[node_id]);
if (node_id == 0) {
// -> first 2 entrys are neighbors
neighbors.push_back(_preds[0]);
neighbors.push_back(_preds[1]);
}
if (node_id == _preds[0] or node_id == _preds[1]) {
// -> adjacent to node 0
neighbors.push_back(0);
}
for (NodeId other_id = 2; other_id < _preds.size(); ++other_id) {
if (_preds[other_id] == node_id) {
// -> other_id is successor in the OneTree
neighbors.push_back(other_id);
continue;
}
if (other_id == node_id) {
// -> other_id is predecessor in the OneTree
neighbors.push_back(_preds[node_id]);
}
}
return neighbors;
}
} // namespace Core
| 26.397059 | 84 | 0.615042 |
8eaa13d41994856cf8f60f3702734dace09604e2 | 1,619 | hpp | C++ | src/rpcz/sync_call_handler.hpp | jinq0123/rpcz | d273dc1a8de770cb4c2ddee98c17ce60c657d6ca | [
"Apache-2.0"
] | 4 | 2015-06-14T13:38:40.000Z | 2020-11-07T02:29:59.000Z | src/rpcz/sync_call_handler.hpp | jinq0123/rpcz | d273dc1a8de770cb4c2ddee98c17ce60c657d6ca | [
"Apache-2.0"
] | 1 | 2015-06-19T07:54:53.000Z | 2015-11-12T10:38:21.000Z | src/rpcz/sync_call_handler.hpp | jinq0123/rpcz | d273dc1a8de770cb4c2ddee98c17ce60c657d6ca | [
"Apache-2.0"
] | 3 | 2015-06-15T02:28:39.000Z | 2018-10-18T11:02:59.000Z | // Licensed under the Apache License, Version 2.0 (the "License");
// Author: Jin Qing (http://blog.csdn.net/jq0123)
#ifndef RPCZ_SYNC_CALL_HANDLER_HPP
#define RPCZ_SYNC_CALL_HANDLER_HPP
#include <boost/noncopyable.hpp>
#include <boost/optional.hpp>
#include <google/protobuf/message.h>
#include <rpcz/common.hpp> // for scoped_ptr
#include <rpcz/rpc_error.hpp>
#include <rpcz/sync_event.hpp>
namespace rpcz {
class rpc_error;
// Handler to simulate sync call.
class sync_call_handler : boost::noncopyable {
public:
inline explicit sync_call_handler(
google::protobuf::Message* response)
: response_(response) {}
inline ~sync_call_handler(void) {}
public:
inline void operator()(const rpc_error* error,
const void* data, size_t size);
inline void wait() { sync_.wait(); }
inline const rpc_error* get_rpc_error() const {
return error_.get_ptr();
}
private:
void handle_error(const rpc_error& err);
void handle_invalid_message();
inline void signal() { sync_.signal(); }
private:
sync_event sync_;
google::protobuf::Message* response_;
boost::optional<rpc_error> error_;
};
inline void sync_call_handler::operator()(
const rpc_error* error,
const void* data, size_t size) {
if (error) {
handle_error(*error);
signal();
return;
}
BOOST_ASSERT(data);
if (NULL == response_) {
signal();
return;
}
if (response_->ParseFromArray(data, size)) {
BOOST_ASSERT(!error_);
signal();
return;
}
// invalid message
handle_invalid_message();
signal();
}
} // namespace rpcz
#endif // RPCZ_SYNC_CALL_HANDLER_HPP
| 22.486111 | 66 | 0.696726 |
8eacff5f5ccdf66cba37be123d641ee40280087a | 1,618 | cc | C++ | src/plugin/graphics/text/src/font/bitmapfontmanager.cc | motor-dev/Motor | 98cb099fe1c2d31e455ed868cc2a25eae51e79f0 | [
"BSD-3-Clause"
] | null | null | null | src/plugin/graphics/text/src/font/bitmapfontmanager.cc | motor-dev/Motor | 98cb099fe1c2d31e455ed868cc2a25eae51e79f0 | [
"BSD-3-Clause"
] | null | null | null | src/plugin/graphics/text/src/font/bitmapfontmanager.cc | motor-dev/Motor | 98cb099fe1c2d31e455ed868cc2a25eae51e79f0 | [
"BSD-3-Clause"
] | null | null | null | /* Motor <motor.devel@gmail.com>
see LICENSE for detail */
#include <motor/plugin.graphics.text/stdafx.h>
#include <bitmapfontmanager.hh>
#include <fontlist.hh>
namespace Motor {
BitmapFontManager::BitmapFontManager(weak< Resource::ResourceManager > manager,
weak< FreetypeLibrary > freetype,
weak< const FontList > fontList)
: m_manager(manager)
, m_freetype(freetype)
, m_fontList(fontList)
{
}
BitmapFontManager::~BitmapFontManager()
{
}
void BitmapFontManager::load(weak< const Resource::IDescription > /*description*/,
Resource::Resource& /*resource*/)
{
motor_info("loading bitmap font");
}
void BitmapFontManager::reload(weak< const Resource::IDescription > /*oldDescription*/,
weak< const Resource::IDescription > /*newDescription*/,
Resource::Resource& /*resource*/)
{
motor_info("reloading bitmap font");
}
void BitmapFontManager::unload(weak< const Resource::IDescription > /*description*/,
Resource::Resource& /*resource*/)
{
motor_info("unloading bitmap font");
}
void BitmapFontManager::onTicketLoaded(weak< const Resource::IDescription > /*description*/,
Resource::Resource& /*resource*/,
const minitl::Allocator::Block< u8 >& /*buffer*/,
LoadType /*type*/)
{
motor_info("bitmap font file done loading");
}
} // namespace Motor
| 31.72549 | 92 | 0.57911 |
8eb1fb99e1744279d9305287c855c2e611b06c83 | 2,294 | hpp | C++ | SDK/ARKSurvivalEvolved_PrimalItem_Spawner_Exosuit_parameters.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_PrimalItem_Spawner_Exosuit_parameters.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_PrimalItem_Spawner_Exosuit_parameters.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 3 | 2020-07-22T17:42:07.000Z | 2021-06-19T17:16:13.000Z | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_PrimalItem_Spawner_Exosuit_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function PrimalItem_Spawner_Exosuit.PrimalItem_Spawner_Exosuit_C.BPCanUse
struct UPrimalItem_Spawner_Exosuit_C_BPCanUse_Params
{
bool* bIgnoreCooldown; // (Parm, ZeroConstructor, IsPlainOldData)
bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function PrimalItem_Spawner_Exosuit.PrimalItem_Spawner_Exosuit_C.GetStatDisplayString
struct UPrimalItem_Spawner_Exosuit_C_GetStatDisplayString_Params
{
TEnumAsByte<EPrimalCharacterStatusValue>* Stat; // (Parm, ZeroConstructor, IsPlainOldData)
int* Value; // (Parm, ZeroConstructor, IsPlainOldData)
int* StatConvertMapIndex; // (Parm, ZeroConstructor, IsPlainOldData)
class FString StatDisplay; // (Parm, OutParm, ZeroConstructor)
class FString ValueDisplay; // (Parm, OutParm, ZeroConstructor)
bool ShowInTooltip; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PrimalItem_Spawner_Exosuit.PrimalItem_Spawner_Exosuit_C.ExecuteUbergraph_PrimalItem_Spawner_Exosuit
struct UPrimalItem_Spawner_Exosuit_C_ExecuteUbergraph_PrimalItem_Spawner_Exosuit_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 49.869565 | 173 | 0.493897 |
8eb26e68f715d0be03e3215e8627694528f16e18 | 78 | cpp | C++ | escos/src/common/unittest.cpp | OSADP/MMITSS_THEA | 53ef55d0622f230002c75046db6af295592dbf0a | [
"Apache-2.0"
] | null | null | null | escos/src/common/unittest.cpp | OSADP/MMITSS_THEA | 53ef55d0622f230002c75046db6af295592dbf0a | [
"Apache-2.0"
] | null | null | null | escos/src/common/unittest.cpp | OSADP/MMITSS_THEA | 53ef55d0622f230002c75046db6af295592dbf0a | [
"Apache-2.0"
] | null | null | null | #ifdef C2X_UNIT_TESTS
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#endif
| 11.142857 | 25 | 0.794872 |
8eb6f8cf6456ebf20008a16a6ab8ad1306d4ed87 | 6,935 | cpp | C++ | smaug/core/tensor.cpp | mrbeann/smaug | 01ef7892bb25cb08c13cea6125efc1528a8de260 | [
"BSD-3-Clause"
] | 50 | 2020-06-12T19:53:37.000Z | 2022-03-30T15:05:34.000Z | smaug/core/tensor.cpp | mrbeann/smaug | 01ef7892bb25cb08c13cea6125efc1528a8de260 | [
"BSD-3-Clause"
] | 37 | 2020-06-23T17:28:42.000Z | 2021-10-21T05:30:36.000Z | smaug/core/tensor.cpp | mrbeann/smaug | 01ef7892bb25cb08c13cea6125efc1528a8de260 | [
"BSD-3-Clause"
] | 18 | 2020-06-17T19:59:23.000Z | 2022-02-15T07:40:47.000Z | #include "smaug/core/tensor.h"
#include "smaug/core/tensor_utils.h"
#include "smaug/core/globals.h"
#include "smaug/utility/thread_pool.h"
namespace smaug {
TensorShapeProto* TensorShape::asTensorShapeProto() {
TensorShapeProto* shapeProto = new TensorShapeProto();
*shapeProto->mutable_dims() = { dims_.begin(), dims_.end() };
shapeProto->set_layout(layout);
shapeProto->set_alignment(alignment);
return shapeProto;
}
TensorProto* Tensor::asTensorProto() {
TensorProto* tensorProto = new TensorProto();
tensorProto->set_name(name);
tensorProto->set_data_type(dataType);
tensorProto->set_allocated_shape(shape.asTensorShapeProto());
tensorProto->set_data_format(dataFormat);
// Copy the tensor data into the proto.
TensorData* protoData = new TensorData();
void* rawPtr = tensorData.get();
switch (dataType) {
case Float16:
// Add 1 to cover the case when the storage size is odd.
protoData->mutable_half_data()->Resize(
(shape.storageSize() + 1) / 2, 0);
memcpy(protoData->mutable_half_data()->mutable_data(), rawPtr,
shape.storageSize() * sizeof(float16));
break;
case Float32:
protoData->mutable_float_data()->Resize(shape.storageSize(), 0);
memcpy(protoData->mutable_float_data()->mutable_data(), rawPtr,
shape.storageSize() * sizeof(float));
break;
case Float64:
protoData->mutable_double_data()->Resize(shape.storageSize(), 0);
memcpy(protoData->mutable_double_data()->mutable_data(), rawPtr,
shape.storageSize() * sizeof(double));
break;
case Int32:
protoData->mutable_int_data()->Resize(shape.storageSize(), 0);
memcpy(protoData->mutable_int_data()->mutable_data(), rawPtr,
shape.storageSize() * sizeof(int));
break;
case Int64:
protoData->mutable_int64_data()->Resize(shape.storageSize(), 0);
memcpy(protoData->mutable_int64_data()->mutable_data(), rawPtr,
shape.storageSize() * sizeof(int64_t));
break;
case Bool:
protoData->mutable_bool_data()->Resize(shape.storageSize(), 0);
memcpy(protoData->mutable_bool_data()->mutable_data(), rawPtr,
shape.storageSize() * sizeof(bool));
break;
default:
assert(false && "Unknown data type!");
}
tensorProto->set_allocated_data(protoData);
return tensorProto;
}
Tensor* TiledTensor::getTileWithData(int index) {
Tile* tile = &tiles[index];
copyDataToTile(tile);
return tile->tensor;
}
void TiledTensor::setTile(int index,
const std::vector<int>& origin,
Tensor* tensor,
bool copyData) {
Tile* tile = &tiles[index];
tile->tensor = tensor;
tile->origin = origin;
tile->hasOrigin = true;
if (copyData)
copyDataToTile(tile);
}
void* TiledTensor::tileCopyWorker(void* _args) {
auto args = reinterpret_cast<CopyTilesArgs*>(_args);
TiledTensor* tiledTensor = args->tiledTensor;
int start = args->start;
int numTiles = args->numTiles;
TileDataOperation op = args->op;
for (int i = start; i < start + numTiles; i++) {
Tile* tile = tiledTensor->getTile(i);
if (op == Scatter)
tiledTensor->copyDataToTile(tile);
else if (op == Gather)
tiledTensor->gatherDataFromTile(tile);
}
delete args;
return nullptr;
}
void TiledTensor::parallelCopyTileData(TileDataOperation op) {
int totalNumTiles = tiles.size();
int numTilesPerThread = std::ceil(totalNumTiles * 1.0 / threadPool->size());
int remainingTiles = totalNumTiles;
while (remainingTiles > 0) {
int numTiles = std::min(numTilesPerThread, remainingTiles);
auto args = new CopyTilesArgs(
this, totalNumTiles - remainingTiles, numTiles, op);
int cpuid =
threadPool->dispatchThread(tileCopyWorker, (void*)args);
assert(cpuid != -1 && "Failed to dispatch thread!");
remainingTiles -= numTiles;
}
threadPool->joinThreadPool();
}
void TiledTensor::copyDataToAllTiles() {
// Don't copy if all the tiles have data filled.
if (dataFilled)
return;
assert(origTensor != nullptr &&
"TiledTensor must have the original tensor to copy data from!");
if (fastForwardMode || !threadPool || tiles.size() == 1) {
for (auto index = startIndex(); !index.end(); ++index)
copyDataToTile(&tiles[index]);
} else {
parallelCopyTileData(Scatter);
}
dataFilled = true;
}
void TiledTensor::copyDataToTile(Tile* tile) {
// Don't copy if the tile already has data, or if the tile is the original
// tensor (we have only one tile).
if (tile->hasData || tile->tensor == origTensor)
return;
// Perform the data copy.
assert(tile->hasOrigin &&
"Must set the tile's origin in the original tensor!");
if (useRawTensor) {
// Use the raw tensor copy function for the unary tile.
copyRawTensorData(tile->tensor, origTensor, 0, tile->origin[0],
tile->tensor->getShape().storageSize());
} else {
std::vector<int> dstOrigin(tile->tensor->ndims(), 0);
copyTensorRegion(tile->tensor, origTensor, dstOrigin, tile->origin,
tile->tensor->getShape().dims());
}
tile->hasData = true;
}
void TiledTensor::untile() {
assert(origTensor != nullptr &&
"TiledTensor must have the original tensor to copy data to!");
const TensorShape& tensorShape = origTensor->getShape();
int ndims = tensorShape.ndims();
if (tiles.size() == 1) {
// No need to copy data if the tile is the original tensor.
return;
}
if (fastForwardMode || !threadPool) {
for (auto index = startIndex(); !index.end(); ++index)
gatherDataFromTile(&tiles[index]);
} else {
parallelCopyTileData(Gather);
}
}
void TiledTensor::gatherDataFromTile(Tile* tile) {
// Perform the data copy.
assert(tile->hasOrigin &&
"Must set the tile's origin in the original tensor!");
if (useRawTensor) {
// Use the raw tensor copy function for the unary tile.
copyRawTensorData(origTensor, tile->tensor, tile->origin[0], 0,
tile->tensor->getShape().storageSize());
} else {
std::vector<int> srcOrigin(tile->tensor->ndims(), 0);
copyTensorRegion(origTensor,
tile->tensor,
tile->origin,
srcOrigin,
tile->tensor->getShape().dims());
}
}
} // namespace smaug
| 36.5 | 80 | 0.603317 |
8eb80589d93faf35ad4eb82fda45dc979a250a07 | 1,207 | cpp | C++ | test/delegate/test_bad_delegate_call.cpp | rmettler/cpp_delegates | 8557a1731eccbad9608f3111c5599f666b74750e | [
"BSL-1.0"
] | 4 | 2020-01-30T19:17:57.000Z | 2020-04-02T13:03:13.000Z | test/delegate/test_bad_delegate_call.cpp | rmettler/cpp_delegates | 8557a1731eccbad9608f3111c5599f666b74750e | [
"BSL-1.0"
] | null | null | null | test/delegate/test_bad_delegate_call.cpp | rmettler/cpp_delegates | 8557a1731eccbad9608f3111c5599f666b74750e | [
"BSL-1.0"
] | null | null | null | //
// Project: C++ delegates
//
// Copyright Roger Mettler 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at
// https://www.boost.org/LICENSE_1_0.txt)
//
#include <doctest.h>
#include <rome/detail/bad_delegate_call.hpp>
#include <type_traits>
TEST_SUITE_BEGIN("header file: rome/bad_delegate_call.hpp");
TEST_CASE("rome::bad_delegate_call") {
static_assert(std::is_nothrow_default_constructible<rome::bad_delegate_call>::value, "");
static_assert(std::is_nothrow_copy_constructible<rome::bad_delegate_call>::value, "");
static_assert(std::is_nothrow_copy_assignable<rome::bad_delegate_call>::value, "");
static_assert(std::is_nothrow_move_constructible<rome::bad_delegate_call>::value, "");
static_assert(std::is_nothrow_move_assignable<rome::bad_delegate_call>::value, "");
static_assert(std::is_nothrow_destructible<rome::bad_delegate_call>::value, "");
static_assert(std::is_base_of<std::exception, rome::bad_delegate_call>::value, "");
CHECK_THROWS_WITH_AS(
throw rome::bad_delegate_call{}, "rome::bad_delegate_call", rome::bad_delegate_call);
}
TEST_SUITE_END(); // rome/bad_delegate_call.hpp
| 40.233333 | 93 | 0.754764 |
8ebd11dc81d5d857155b39acd498a54c06eaf01b | 1,487 | hpp | C++ | discregrid/include/Discregrid/acceleration/bounding_sphere_hierarchy.hpp | lasagnaphil/Discregrid | 83bec4b39445e7ed62229e6f84d94c0cfcc1136b | [
"MIT"
] | null | null | null | discregrid/include/Discregrid/acceleration/bounding_sphere_hierarchy.hpp | lasagnaphil/Discregrid | 83bec4b39445e7ed62229e6f84d94c0cfcc1136b | [
"MIT"
] | null | null | null | discregrid/include/Discregrid/acceleration/bounding_sphere_hierarchy.hpp | lasagnaphil/Discregrid | 83bec4b39445e7ed62229e6f84d94c0cfcc1136b | [
"MIT"
] | null | null | null | #pragma once
#include "types.hpp"
#include "bounding_sphere.hpp"
#include "kd_tree.hpp"
#include <span.hpp>
namespace Discregrid
{
class TriangleMeshBSH : public KDTree<BoundingSphere>
{
public:
using super = KDTree<BoundingSphere>;
TriangleMeshBSH(std::span<const Vector3r> vertices,
std::span<const Eigen::Vector3i> faces);
Vector3r const& entityPosition(int i) const final;
void computeHull(int b, int n, BoundingSphere& hull) const final;
private:
std::span<const Vector3r> m_vertices;
std::span<const Eigen::Vector3i> m_faces;
std::vector<Vector3r> m_tri_centers;
};
class TriangleMeshBBH : public KDTree<AlignedBox3r>
{
public:
using super = KDTree<AlignedBox3r>;
TriangleMeshBBH(std::span<const Vector3r> vertices,
std::span<const Eigen::Vector3i> faces);
Vector3r const& entityPosition(int i) const final;
void computeHull(int b, int n, AlignedBox3r& hull) const final;
private:
std::span<const Vector3r> m_vertices;
std::span<const Eigen::Vector3i> m_faces;
std::vector<Vector3r> m_tri_centers;
};
class PointCloudBSH : public KDTree<BoundingSphere>
{
public:
using super = KDTree<BoundingSphere>;
PointCloudBSH();
PointCloudBSH(std::span<const Vector3r> vertices);
Vector3r const& entityPosition(int i) const final;
void computeHull(int b, int n, BoundingSphere& hull)
const final;
private:
std::span<const Vector3r> m_vertices;
};
}
| 19.826667 | 67 | 0.705447 |
8ebde15b22131d13eebeffbf14d860e37bc7ed26 | 4,173 | cpp | C++ | src/mirrage/net/src/server.cpp | lowkey42/mirrage | 2527537989a548062d0bbca8370d063fc6b81a18 | [
"MIT"
] | 14 | 2017-10-26T08:45:54.000Z | 2021-04-06T11:44:17.000Z | src/mirrage/net/src/server.cpp | lowkey42/mirrage | 2527537989a548062d0bbca8370d063fc6b81a18 | [
"MIT"
] | 17 | 2017-10-09T20:11:58.000Z | 2018-11-08T22:05:14.000Z | src/mirrage/net/src/server.cpp | lowkey42/mirrage | 2527537989a548062d0bbca8370d063fc6b81a18 | [
"MIT"
] | 1 | 2018-09-26T23:10:06.000Z | 2018-09-26T23:10:06.000Z | #include <mirrage/net/server.hpp>
#include <mirrage/net/error.hpp>
#include <mirrage/utils/container_utils.hpp>
#include <enet/enet.h>
namespace mirrage::net {
Server_builder::Server_builder(Host_type type,
std::string hostname,
std::uint16_t port,
const Channel_definitions& channels)
: _type(type), _hostname(std::move(hostname)), _port(port), _channels(channels)
{
}
auto Server_builder::create() -> Server
{
return {_type,
_hostname,
_port,
_channels,
_max_clients,
_max_in_bandwidth,
_max_out_bandwidth,
_on_connect,
_on_disconnect};
}
namespace {
auto open_server_host(Server_builder::Host_type type,
const std::string& hostname,
std::uint16_t port,
std::size_t channel_count,
int max_clients,
int max_in_bandwidth,
int max_out_bandwidth)
{
ENetAddress address;
address.port = port;
switch(type) {
case Server_builder::Host_type::any: address.host = ENET_HOST_ANY; break;
case Server_builder::Host_type::broadcast:
#ifdef WIN32
address.host = ENET_HOST_ANY;
#else
address.host = ENET_HOST_BROADCAST;
#endif
break;
case Server_builder::Host_type::named:
auto ec = enet_address_set_host(&address, hostname.c_str());
if(ec != 0) {
const auto msg = "Couldn't resolve host \"" + hostname + "\".";
LOG(plog::warning) << msg;
throw std::system_error(Net_error::unknown_host, msg);
}
break;
}
auto host = enet_host_create(&address,
gsl::narrow<size_t>(max_clients),
channel_count,
gsl::narrow<enet_uint32>(max_in_bandwidth),
gsl::narrow<enet_uint32>(max_out_bandwidth));
if(!host) {
constexpr auto msg = "Couldn't create the host data structure (out of memory?)";
LOG(plog::warning) << msg;
throw std::system_error(Net_error::unspecified_network_error, msg);
}
return std::unique_ptr<ENetHost, void (*)(ENetHost*)>(host, &enet_host_destroy);
}
} // namespace
Server::Server(Server_builder::Host_type type,
const std::string& hostname,
std::uint16_t port,
const Channel_definitions& channels,
int max_clients,
int max_in_bandwidth,
int max_out_bandwidth,
Connected_callback on_connected,
Disconnected_callback on_disconnected)
: Connection(
open_server_host(
type, hostname, port, channels.size(), max_clients, max_in_bandwidth, max_out_bandwidth),
channels,
std::move(on_connected),
std::move(on_disconnected))
{
}
auto Server::broadcast_channel(util::Str_id channel) -> Channel
{
auto&& c = _channels.by_name(channel);
if(c.is_nothing()) {
const auto msg = "Unknown channel \"" + channel.str() + "\".";
LOG(plog::warning) << msg;
throw std::system_error(Net_error::unknown_channel, msg);
}
return Channel(_host.get(), c.get_or_throw());
}
auto Server::client_channel(util::Str_id channel, Client_handle client) -> Channel
{
auto&& c = _channels.by_name(channel);
if(c.is_nothing()) {
const auto msg = "Unknown channel \"" + channel.str() + "\".";
LOG(plog::warning) << msg;
throw std::system_error(Net_error::unknown_channel, msg);
}
return Channel(client, c.get_or_throw());
}
void Server::_on_connected(Client_handle client) { _clients.emplace_back(client); }
void Server::_on_disconnected(Client_handle client, std::uint32_t) { util::erase_fast(_clients, client); }
} // namespace mirrage::net
| 32.348837 | 108 | 0.565061 |
8ebee5f2aa9ebe853f989c65ce409b121fc4bd7a | 8,870 | hpp | C++ | include/libndgpp/network_byte_order.hpp | goodfella/libndgpp | 2e3d4b993a04664905c1e257fb2af3a5faab5296 | [
"MIT"
] | null | null | null | include/libndgpp/network_byte_order.hpp | goodfella/libndgpp | 2e3d4b993a04664905c1e257fb2af3a5faab5296 | [
"MIT"
] | null | null | null | include/libndgpp/network_byte_order.hpp | goodfella/libndgpp | 2e3d4b993a04664905c1e257fb2af3a5faab5296 | [
"MIT"
] | null | null | null | #ifndef LIBNDGPP_NETWORK_BYTE_ORDER_HPP
#define LIBNDGPP_NETWORK_BYTE_ORDER_HPP
#include <algorithm>
#include <array>
#include <cstring>
#include <type_traits>
#include <utility>
#include <ostream>
#include <libndgpp/network_byte_order_ops.hpp>
namespace ndgpp
{
/** Stores a native type value in network byte order
*
* The ndgpp::network_byte_order class is a regular type that
* will seemlessly represent a native type value in network byte
* order.
*
* @tparam T The native type i.e. uint16_t, uint32_t, uint64_t
*/
template <class T>
class network_byte_order
{
static_assert(std::is_integral<T>::value, "T is not an integral type");
static_assert(!std::is_signed<T>::value, "T is not unsigned");
public:
using value_type = T;
constexpr
network_byte_order() noexcept;
/** Constructs a network_byte_order instance with the specified value
*
* @param value An instance of type T in host byte order
*/
explicit
constexpr
network_byte_order(const T value) noexcept;
constexpr
network_byte_order(const network_byte_order & other) noexcept;
network_byte_order(network_byte_order && other) noexcept;
/** Assigns this to the value of rhs
*
* @param rhs An instance of type T in host byte order
*/
network_byte_order & operator= (const T rhs) noexcept;
network_byte_order & operator= (const network_byte_order & rhs) noexcept;
network_byte_order & operator= (network_byte_order && rhs) noexcept;
/// Returns the stored value in host byte order
constexpr
operator value_type () const noexcept;
/** Returns the address of the underlying value
*
* This is useful for sending the value over a socket:
*
* \code
* const int ret = send(&v, v.size());
*/
value_type const * operator &() const noexcept;
value_type * operator &() noexcept;
/// Returns the size of the underlying value
constexpr std::size_t size() const noexcept;
void swap(network_byte_order<T> & other) noexcept;
private:
value_type value_;
friend bool operator== <> (const network_byte_order<T>, const network_byte_order<T>);
friend bool operator!= <> (const network_byte_order<T>, const network_byte_order<T>);
friend bool operator< <> (const network_byte_order<T>, const network_byte_order<T>);
friend bool operator> <> (const network_byte_order<T>, const network_byte_order<T>);
friend bool operator<= <> (const network_byte_order<T>, const network_byte_order<T>);
friend bool operator>= <> (const network_byte_order<T>, const network_byte_order<T>);
};
template <class T>
inline
bool operator== (const network_byte_order<T> lhs,
const network_byte_order<T> rhs)
{
return lhs.value_ == rhs.value_;
}
template <class T>
inline
bool operator!= (const network_byte_order<T> lhs,
const network_byte_order<T> rhs)
{
return !(lhs == rhs);
}
template <class T>
inline
bool operator< (const network_byte_order<T> lhs,
const network_byte_order<T> rhs)
{
return lhs.value_ < rhs.value_;
}
template <class T>
inline
bool operator> (const network_byte_order<T> lhs,
const network_byte_order<T> rhs)
{
return rhs < lhs;
}
template <class T>
inline
bool operator<= (const network_byte_order<T> lhs,
const network_byte_order<T> rhs)
{
return !(rhs < lhs);
}
template <class T>
inline
bool operator>= (const network_byte_order<T> lhs,
const network_byte_order<T> rhs)
{
return !(lhs < rhs);
}
inline uint16_t host_to_network(const uint16_t val) noexcept
{
alignas(std::alignment_of<uint16_t>::value) std::array<uint8_t, 2> buf;
buf[0] = static_cast<uint8_t>((val & 0xff00) >> 8);
buf[1] = static_cast<uint8_t>((val & 0x00ff));
return *reinterpret_cast<uint16_t*>(buf.data());
}
inline uint32_t host_to_network(const uint32_t val) noexcept
{
alignas(std::alignment_of<uint32_t>::value) std::array<uint8_t, 4> buf;
buf[0] = static_cast<uint8_t>((val & 0xff000000) >> 24);
buf[1] = static_cast<uint8_t>((val & 0x00ff0000) >> 16);
buf[2] = static_cast<uint8_t>((val & 0x0000ff00) >> 8);
buf[3] = static_cast<uint8_t>((val & 0x000000ff));
return *reinterpret_cast<uint32_t*>(buf.data());
}
inline uint64_t host_to_network(const uint64_t val) noexcept
{
alignas(std::alignment_of<uint64_t>::value) std::array<uint8_t, 8> buf;
buf[0] = static_cast<uint8_t>((val & 0xff00000000000000) >> 56);
buf[1] = static_cast<uint8_t>((val & 0x00ff000000000000) >> 48);
buf[2] = static_cast<uint8_t>((val & 0x0000ff0000000000) >> 40);
buf[3] = static_cast<uint8_t>((val & 0x000000ff00000000) >> 32);
buf[4] = static_cast<uint8_t>((val & 0x00000000ff000000) >> 24);
buf[5] = static_cast<uint8_t>((val & 0x0000000000ff0000) >> 16);
buf[6] = static_cast<uint8_t>((val & 0x000000000000ff00) >> 8);
buf[7] = static_cast<uint8_t>((val & 0x00000000000000ff));
return *reinterpret_cast<uint64_t*>(buf.data());
}
inline uint16_t network_to_host(const uint16_t val)
{
std::array<uint8_t, 2> buf;
std::memcpy(buf.data(), &val, sizeof(val));
return
static_cast<uint16_t>(buf[0]) << 8 |
static_cast<uint16_t>(buf[1]);
}
inline uint32_t network_to_host(const uint32_t val) noexcept
{
std::array<uint8_t, 4> buf;
std::memcpy(buf.data(), &val, sizeof(val));
return
static_cast<uint32_t>(buf[0]) << 24 |
static_cast<uint32_t>(buf[1]) << 16 |
static_cast<uint32_t>(buf[2]) << 8 |
static_cast<uint32_t>(buf[3]);
}
inline uint64_t network_to_host(const uint64_t val) noexcept
{
std::array<uint8_t, 8> buf;
std::memcpy(buf.data(), &val, sizeof(val));
return
static_cast<uint64_t>(buf[0]) << 56 |
static_cast<uint64_t>(buf[1]) << 48 |
static_cast<uint64_t>(buf[2]) << 40 |
static_cast<uint64_t>(buf[3]) << 32 |
static_cast<uint64_t>(buf[4]) << 24 |
static_cast<uint64_t>(buf[5]) << 16 |
static_cast<uint64_t>(buf[6]) << 8 |
static_cast<uint64_t>(buf[7]);
}
template <class T>
void swap(network_byte_order<T> & lhs, network_byte_order<T> & rhs)
{
lhs.swap(rhs);
}
template <class T>
inline
std::ostream & operator <<(std::ostream & out, const network_byte_order<T> val)
{
out << static_cast<T>(val);
return out;
}
}
template <class T>
inline
constexpr
ndgpp::network_byte_order<T>::network_byte_order() noexcept = default;
template <class T>
inline
constexpr
ndgpp::network_byte_order<T>::network_byte_order(const ndgpp::network_byte_order<T>& other) noexcept = default;
template <class T>
inline
ndgpp::network_byte_order<T>::network_byte_order(ndgpp::network_byte_order<T>&& other) noexcept = default;
template <class T>
inline
ndgpp::network_byte_order<T> & ndgpp::network_byte_order<T>::operator= (const ndgpp::network_byte_order<T>& other) noexcept = default;
template <class T>
inline
ndgpp::network_byte_order<T> & ndgpp::network_byte_order<T>::operator= (ndgpp::network_byte_order<T>&& other) noexcept = default;
template <class T>
inline
constexpr
ndgpp::network_byte_order<T>::network_byte_order(const T value) noexcept:
value_(ndgpp::host_to_network(value))
{}
template <class T>
inline
ndgpp::network_byte_order<T> & ndgpp::network_byte_order<T>::operator= (const T value) noexcept
{
this->value_ = ndgpp::host_to_network(value);
return *this;
}
template <class T>
inline
constexpr
ndgpp::network_byte_order<T>::operator T() const noexcept
{
return ndgpp::network_to_host(this->value_);
}
template <class T>
inline
T const * ndgpp::network_byte_order<T>::operator &() const noexcept
{
return &this->value_;
}
template <class T>
inline
T * ndgpp::network_byte_order<T>::operator &() noexcept
{
return &this->value_;
}
template <class T>
inline
constexpr
std::size_t ndgpp::network_byte_order<T>::size() const noexcept
{
return sizeof(T);
}
template <class T>
inline
void ndgpp::network_byte_order<T>::swap(ndgpp::network_byte_order<T> & other) noexcept
{
std::swap(this->value_, other.value_);
}
#endif
| 29.966216 | 134 | 0.632131 |
8ec65e548000a175fbe13b174fa34c2fce1336aa | 116 | cpp | C++ | C++/KY/call.cpp | WhitePhosphorus4/xh-learning-code | 025e31500d9f46d97ea634d7fd311c65052fd78e | [
"Apache-2.0"
] | null | null | null | C++/KY/call.cpp | WhitePhosphorus4/xh-learning-code | 025e31500d9f46d97ea634d7fd311c65052fd78e | [
"Apache-2.0"
] | null | null | null | C++/KY/call.cpp | WhitePhosphorus4/xh-learning-code | 025e31500d9f46d97ea634d7fd311c65052fd78e | [
"Apache-2.0"
] | null | null | null | #include<iostream>
#include<math.h>
using namespace std;
int main()
{
cout<<"hello world"<<endl;
return 0;
} | 14.5 | 30 | 0.655172 |
8ecca67a112fa7fab1224acf1833c07ebef08c75 | 2,361 | cpp | C++ | source/main-http.cpp | janjongboom/mbed-os-example-fota-http | 20ef030aa95052a82c31c0eaece154dbc408de75 | [
"MIT"
] | 6 | 2017-10-11T08:56:32.000Z | 2022-02-24T14:09:30.000Z | source/main-http.cpp | janjongboom/mbed-os-example-fota-http | 20ef030aa95052a82c31c0eaece154dbc408de75 | [
"MIT"
] | 2 | 2017-08-28T16:08:36.000Z | 2018-06-20T20:07:54.000Z | source/main-http.cpp | janjongboom/mbed-os-example-fota-http | 20ef030aa95052a82c31c0eaece154dbc408de75 | [
"MIT"
] | 5 | 2018-03-27T08:59:23.000Z | 2022-01-26T21:08:50.000Z | #include "mbed.h"
#include "easy-connect.h"
#include "http_request.h"
#include "SDBlockDevice.h"
#include "FATFileSystem.h"
#define SD_MOUNT_PATH "sd"
#define FULL_UPDATE_FILE_PATH "/" SD_MOUNT_PATH "/" MBED_CONF_APP_UPDATE_FILE
//Pin order: MOSI, MISO, SCK, CS
SDBlockDevice sd(MBED_CONF_APP_SD_CARD_MOSI, MBED_CONF_APP_SD_CARD_MISO,
MBED_CONF_APP_SD_CARD_SCK, MBED_CONF_APP_SD_CARD_CS);
FATFileSystem fs(SD_MOUNT_PATH);
NetworkInterface* network;
EventQueue queue;
InterruptIn btn(SW0);
FILE* file;
size_t received = 0;
size_t received_packets = 0;
void store_fragment(const char* buffer, size_t size) {
fwrite(buffer, 1, size, file);
received += size;
received_packets++;
if (received_packets % 20 == 0) {
printf("Received %u bytes\n", received);
}
}
void check_for_update() {
btn.fall(NULL); // remove the button listener
file = fopen(FULL_UPDATE_FILE_PATH, "wb");
HttpRequest* req = new HttpRequest(network, HTTP_GET, "http://192.168.0.105:8000/update.bin", &store_fragment);
HttpResponse* res = req->send();
if (!res) {
printf("HttpRequest failed (error code %d)\n", req->get_error());
return;
}
printf("Done downloading: %d - %s\n", res->get_status_code(), res->get_status_message().c_str());
fclose(file);
delete req;
printf("Rebooting...\n\n");
NVIC_SystemReset();
}
DigitalOut led(LED1);
void blink_led() {
led = !led;
}
int main() {
printf("Hello from THE ORIGINAL application\n");
Thread eventThread;
eventThread.start(callback(&queue, &EventQueue::dispatch_forever));
queue.call_every(500, &blink_led);
btn.mode(PullUp); // PullUp mode on the ODIN W2 EVK
btn.fall(queue.event(&check_for_update));
int r;
if ((r = sd.init()) != 0) {
printf("Could not initialize SD driver (%d)\n", r);
return 1;
}
if ((r = fs.mount(&sd)) != 0) {
printf("Could not mount filesystem, is the SD card formatted as FAT? (%d)\n", r);
return 1;
}
// Connect to the network (see mbed_app.json for the connectivity method used)
network = easy_connect(true);
if (!network) {
printf("Cannot connect to the network, see serial output\n");
return 1;
}
printf("Press SW0 to check for update\n");
wait(osWaitForever);
}
| 25.117021 | 115 | 0.650148 |
8ecfa08d7f74ed2312be0182606f1b456a6efff4 | 17,900 | cpp | C++ | src/remotecommandhandler.cpp | hrxcodes/cbftp | bf2784007dcc4cc42775a2d40157c51b80383f81 | [
"MIT"
] | 8 | 2019-04-30T00:37:00.000Z | 2022-02-03T13:35:31.000Z | src/remotecommandhandler.cpp | Xtravaganz/cbftp | 31a3465e2cd539f6cf35a5d9a0bb9c5c2f639cd5 | [
"MIT"
] | 2 | 2019-11-19T12:46:13.000Z | 2019-12-20T22:13:57.000Z | src/remotecommandhandler.cpp | Xtravaganz/cbftp | 31a3465e2cd539f6cf35a5d9a0bb9c5c2f639cd5 | [
"MIT"
] | 9 | 2020-01-15T02:38:36.000Z | 2022-02-15T20:05:20.000Z | #include "remotecommandhandler.h"
#include <vector>
#include <list>
#include "core/tickpoke.h"
#include "core/iomanager.h"
#include "core/types.h"
#include "crypto.h"
#include "globalcontext.h"
#include "engine.h"
#include "eventlog.h"
#include "util.h"
#include "sitelogicmanager.h"
#include "sitelogic.h"
#include "uibase.h"
#include "sitemanager.h"
#include "site.h"
#include "race.h"
#include "localstorage.h"
#include "httpserver.h"
#define DEFAULT_PASS "DEFAULT"
#define RETRY_DELAY 30000
namespace {
enum RaceType {
RACE,
DISTRIBUTE,
PREPARE
};
std::list<std::shared_ptr<SiteLogic> > getSiteLogicList(const std::string & sitestring) {
std::list<std::shared_ptr<SiteLogic> > sitelogics;
std::list<std::string> sites;
if (sitestring == "*") {
std::vector<std::shared_ptr<Site> >::const_iterator it;
for (it = global->getSiteManager()->begin(); it != global->getSiteManager()->end(); it++) {
if (!(*it)->getDisabled()) {
sites.push_back((*it)->getName());
}
}
}
else {
sites = util::trim(util::split(sitestring, ","));
}
std::list<std::string> notfoundsites;
for (std::list<std::string>::const_iterator it = sites.begin(); it != sites.end(); it++) {
const std::shared_ptr<SiteLogic> sl = global->getSiteLogicManager()->getSiteLogic(*it);
if (!sl) {
notfoundsites.push_back(*it);
continue;
}
sitelogics.push_back(sl);
}
if (sitelogics.empty()) {
for (std::vector<std::shared_ptr<Site> >::const_iterator it = global->getSiteManager()->begin(); it != global->getSiteManager()->end(); ++it) {
if ((*it)->hasSection(sitestring) && !(*it)->getDisabled()) {
std::shared_ptr<SiteLogic> sl = global->getSiteLogicManager()->getSiteLogic((*it)->getName());
sitelogics.push_back(sl);
}
}
}
if (!notfoundsites.empty()) {
std::string notfound = util::join(notfoundsites, ",");
if (sites.size() == 1) {
global->getEventLog()->log("RemoteCommandHandler", "Site or section not found: " + notfound);
}
else {
global->getEventLog()->log("RemoteCommandHandler", "Sites not found: " + notfound);
}
}
return sitelogics;
}
bool useOrSectionTranslate(Path& path, const std::shared_ptr<Site>& site) {
if (path.isRelative()) {
path.level(0);
std::string section = path.level(0).toString();
if (site->hasSection(section)) {
path = site->getSectionPath(section) / path.cutLevels(-1);
}
else {
global->getEventLog()->log("RemoteCommandHandler", "Path must be absolute or a section name on " +
site->getName() + ": " + path.toString());
return false;
}
}
return true;
}
}
RemoteCommandHandler::RemoteCommandHandler() :
enabled(false),
encrypted(true),
password(DEFAULT_PASS),
port(DEFAULT_API_PORT),
retrying(false),
connected(false),
notify(RemoteCommandNotify::DISABLED) {
}
bool RemoteCommandHandler::isEnabled() const {
return enabled;
}
bool RemoteCommandHandler::isEncrypted() const {
return encrypted;
}
int RemoteCommandHandler::getUDPPort() const {
return port;
}
std::string RemoteCommandHandler::getPassword() const {
return password;
}
void RemoteCommandHandler::setPassword(const std::string & newpass) {
password = newpass;
}
void RemoteCommandHandler::setPort(int newport) {
bool reopen = !(port == newport || !enabled);
port = newport;
if (reopen) {
setEnabled(false);
setEnabled(true);
}
}
RemoteCommandNotify RemoteCommandHandler::getNotify() const {
return notify;
}
void RemoteCommandHandler::setNotify(RemoteCommandNotify notify) {
this->notify = notify;
}
void RemoteCommandHandler::connect() {
int udpport = getUDPPort();
sockid = global->getIOManager()->registerUDPServerSocket(this, udpport);
if (sockid >= 0) {
connected = true;
global->getEventLog()->log("RemoteCommandHandler", "Listening on UDP port " + std::to_string(udpport));
}
else {
int delay = RETRY_DELAY / 1000;
global->getEventLog()->log("RemoteCommandHandler", "Retrying in " + std::to_string(delay) + " seconds.");
retrying = true;
global->getTickPoke()->startPoke(this, "RemoteCommandHandler", RETRY_DELAY, 0);
}
}
void RemoteCommandHandler::FDData(int sockid, char * data, unsigned int datalen) {
std::string message;
if (encrypted) {
Core::BinaryData encrypted(datalen);
memcpy(encrypted.data(), data, datalen);
Core::BinaryData decrypted;
Core::BinaryData key(password.begin(), password.end());
Crypto::decrypt(encrypted, key, decrypted);
if (!Crypto::isMostlyASCII(decrypted)) {
global->getEventLog()->log("RemoteCommandHandler", "Received " + std::to_string(datalen) + " bytes of garbage or wrongly encrypted data");
return;
}
message = std::string(decrypted.begin(), decrypted.end());
}
else {
message = std::string(data, datalen);
}
handleMessage(message);
}
void RemoteCommandHandler::handleMessage(const std::string & message) {
std::string trimmedmessage = util::trim(message);
std::vector<std::string> tokens = util::splitVec(trimmedmessage);
if (tokens.size() < 2) {
global->getEventLog()->log("RemoteCommandHandler", "Bad message format: " + trimmedmessage);
return;
}
std::string & pass = tokens[0];
bool passok = pass == password;
if (passok) {
for (unsigned int i = 0; i < pass.length(); i++) {
pass[i] = '*';
}
}
global->getEventLog()->log("RemoteCommandHandler", "Received: " + util::join(tokens));
if (!passok) {
global->getEventLog()->log("RemoteCommandHandler", "Invalid password.");
return;
}
std::string command = tokens[1];
std::vector<std::string> remainder(tokens.begin() + 2, tokens.end());
bool notification = notify == RemoteCommandNotify::ALL_COMMANDS;
if (command == "race") {
bool started = commandRace(remainder);
if (started && notify >= RemoteCommandNotify::JOBS_ADDED) {
notification = true;
}
}
else if (command == "distribute") {
bool started = commandDistribute(remainder) && notify >= RemoteCommandNotify::JOBS_ADDED;
if (started && notify >= RemoteCommandNotify::JOBS_ADDED) {
notification = true;
}
}
else if (command == "prepare") {
bool created = commandPrepare(remainder);
if (created && notify >= RemoteCommandNotify::ACTION_REQUESTED) {
notification = true;
}
}
else if (command == "raw") {
commandRaw(remainder);
}
else if (command == "rawwithpath") {
commandRawWithPath(remainder);
}
else if (command == "fxp") {
bool started = commandFXP(remainder);
if (started && notify >= RemoteCommandNotify::JOBS_ADDED) {
notification = true;
}
}
else if (command == "download") {
bool started = commandDownload(remainder);
if (started && notify >= RemoteCommandNotify::JOBS_ADDED) {
notification = true;
}
}
else if (command == "upload") {
bool started = commandUpload(remainder);
if (started && notify >= RemoteCommandNotify::JOBS_ADDED) {
notification = true;
}
}
else if (command == "idle") {
commandIdle(remainder);
}
else if (command == "abort") {
commandAbort(remainder);
}
else if (command == "delete") {
commandDelete(remainder);
}
else if (command == "abortdeleteincomplete") {
commandAbortDeleteIncomplete(remainder);
}
else if(command == "reset") {
commandReset(remainder, false);
}
else if(command == "hardreset") {
commandReset(remainder, true);
}
else {
global->getEventLog()->log("RemoteCommandHandler", "Invalid remote command: " + util::join(tokens));
return;
}
if (notification) {
global->getUIBase()->notify();
}
}
bool RemoteCommandHandler::commandRace(const std::vector<std::string> & message) {
return parseRace(message, RACE);
}
bool RemoteCommandHandler::commandDistribute(const std::vector<std::string> & message) {
return parseRace(message, DISTRIBUTE);
}
bool RemoteCommandHandler::commandPrepare(const std::vector<std::string> & message) {
return parseRace(message, PREPARE);
}
void RemoteCommandHandler::commandRaw(const std::vector<std::string> & message) {
if (message.size() < 2) {
global->getEventLog()->log("RemoteCommandHandler", "Bad remote raw command format: " + util::join(message));
return;
}
std::string sitestring = message[0];
std::string rawcommand = util::join(std::vector<std::string>(message.begin() + 1, message.end()));
std::list<std::shared_ptr<SiteLogic> > sites = getSiteLogicList(sitestring);
for (std::list<std::shared_ptr<SiteLogic> >::const_iterator it = sites.begin(); it != sites.end(); it++) {
(*it)->requestRawCommand(nullptr, rawcommand);
}
}
void RemoteCommandHandler::commandRawWithPath(const std::vector<std::string> & message) {
if (message.size() < 3) {
global->getEventLog()->log("RemoteCommandHandler", "Bad remote rawwithpath command format: " + util::join(message));
return;
}
std::string sitestring = message[0];
std::string pathstr = message[1];
std::string rawcommand = util::join(std::vector<std::string>(message.begin() + 2, message.end()));
std::list<std::shared_ptr<SiteLogic> > sites = getSiteLogicList(sitestring);
for (std::list<std::shared_ptr<SiteLogic> >::const_iterator it = sites.begin(); it != sites.end(); it++) {
Path path(pathstr);
if (!useOrSectionTranslate(path, (*it)->getSite())) {
continue;
}
(*it)->requestRawCommand(nullptr, path, rawcommand);
}
}
bool RemoteCommandHandler::commandFXP(const std::vector<std::string> & message) {
if (message.size() < 5) {
global->getEventLog()->log("RemoteCommandHandler", "Bad remote fxp command format: " + util::join(message));
return false;
}
std::shared_ptr<SiteLogic> srcsl = global->getSiteLogicManager()->getSiteLogic(message[0]);
std::shared_ptr<SiteLogic> dstsl = global->getSiteLogicManager()->getSiteLogic(message[3]);
if (!srcsl) {
global->getEventLog()->log("RemoteCommandHandler", "Bad site name: " + message[0]);
return false;
}
if (!dstsl) {
global->getEventLog()->log("RemoteCommandHandler", "Bad site name: " + message[3]);
return false;
}
std::string dstfile = message.size() > 5 ? message[5] : message[2];
Path srcpath(message[1]);
if (!useOrSectionTranslate(srcpath, srcsl->getSite())) {
return false;
}
Path dstpath(message[4]);
if (!useOrSectionTranslate(dstpath, dstsl->getSite())) {
return false;
}
global->getEngine()->newTransferJobFXP(message[0], srcpath, message[2], message[3], dstpath, dstfile);
return true;
}
bool RemoteCommandHandler::commandDownload(const std::vector<std::string> & message) {
if (message.size() < 2) {
global->getEventLog()->log("RemoteCommandHandler", "Bad download command format: " + util::join(message));
return false;
}
std::shared_ptr<SiteLogic> srcsl = global->getSiteLogicManager()->getSiteLogic(message[0]);
if (!srcsl) {
global->getEventLog()->log("RemoteCommandHandler", "Bad site name: " + message[0]);
return false;
}
Path srcpath = message[1];
if (!useOrSectionTranslate(srcpath, srcsl->getSite())) {
return false;
}
std::string file = srcpath.baseName();
if (message.size() == 2) {
srcpath = srcpath.dirName();
}
else {
file = message[2];
}
global->getEngine()->newTransferJobDownload(message[0], srcpath, file, global->getLocalStorage()->getDownloadPath(), file);
return true;
}
bool RemoteCommandHandler::commandUpload(const std::vector<std::string> & message) {
if (message.size() < 3) {
global->getEventLog()->log("RemoteCommandHandler", "Bad upload command format: " + util::join(message));
return false;
}
Path srcpath = message[0];
std::string file = srcpath.baseName();
std::string dstsite;
Path dstpath;
if (message.size() == 3) {
srcpath = srcpath.dirName();
dstsite = message[1];
dstpath = message[2];
}
else {
file = message[1];
dstsite = message[2];
dstpath = message[3];
}
std::shared_ptr<SiteLogic> dstsl = global->getSiteLogicManager()->getSiteLogic(dstsite);
if (!dstsl) {
global->getEventLog()->log("RemoteCommandHandler", "Bad site name: " + dstsite);
return false;
}
if (!useOrSectionTranslate(dstpath, dstsl->getSite())) {
return false;
}
global->getEngine()->newTransferJobUpload(srcpath, file, dstsite, dstpath, file);
return true;
}
void RemoteCommandHandler::commandIdle(const std::vector<std::string> & message) {
if (message.empty()) {
global->getEventLog()->log("RemoteCommandHandler", "Bad idle command format: " + util::join(message));
return;
}
int idletime;
std::string sitestring;
if (message.size() < 2) {
sitestring = message[0];
idletime = 0;
}
else {
sitestring = message[0];
idletime = std::stoi(message[1]);
}
std::list<std::shared_ptr<SiteLogic> > sites = getSiteLogicList(sitestring);
for (std::list<std::shared_ptr<SiteLogic> >::const_iterator it = sites.begin(); it != sites.end(); it++) {
(*it)->requestAllIdle(nullptr, idletime);
}
}
void RemoteCommandHandler::commandAbort(const std::vector<std::string> & message) {
if (message.empty()) {
global->getEventLog()->log("RemoteCommandHandler", "Bad abort command format: " + util::join(message));
return;
}
std::shared_ptr<Race> race = global->getEngine()->getRace(message[0]);
if (!race) {
global->getEventLog()->log("RemoteCommandHandler", "No matching race: " + message[0]);
return;
}
global->getEngine()->abortRace(race);
}
void RemoteCommandHandler::commandDelete(const std::vector<std::string> & message) {
if (message.empty()) {
global->getEventLog()->log("RemoteCommandHandler", "Bad delete command format: " + util::join(message));
return;
}
std::string release = message[0];
std::string sitestring;
if (message.size() >= 2) {
sitestring = message[1];
}
std::shared_ptr<Race> race = global->getEngine()->getRace(release);
if (!race) {
global->getEventLog()->log("RemoteCommandHandler", "No matching race: " + release);
return;
}
if (!sitestring.length()) {
global->getEngine()->deleteOnAllSites(race, false, true);
return;
}
std::list<std::shared_ptr<SiteLogic> > sitelogics = getSiteLogicList(sitestring);
std::list<std::shared_ptr<Site> > sites;
for (std::list<std::shared_ptr<SiteLogic> >::const_iterator it = sitelogics.begin(); it != sitelogics.end(); it++) {
sites.push_back((*it)->getSite());
}
global->getEngine()->deleteOnSites(race, sites, false);
}
void RemoteCommandHandler::commandAbortDeleteIncomplete(const std::vector<std::string> & message) {
if (message.empty()) {
global->getEventLog()->log("RemoteCommandHandler", "Bad abortdeleteincomplete command format: " + util::join(message));
return;
}
std::string release = message[0];
std::shared_ptr<Race> race = global->getEngine()->getRace(release);
if (!race) {
global->getEventLog()->log("RemoteCommandHandler", "No matching race: " + release);
return;
}
global->getEngine()->deleteOnAllSites(race, false, false);
}
void RemoteCommandHandler::commandReset(const std::vector<std::string> & message, bool hard) {
if (message.empty()) {
global->getEventLog()->log("RemoteCommandHandler", "Bad reset command format: " + util::join(message));
return;
}
std::shared_ptr<Race> race = global->getEngine()->getRace(message[0]);
if (!race) {
global->getEventLog()->log("RemoteCommandHandler", "No matching race: " + message[0]);
return;
}
global->getEngine()->resetRace(race, hard);
}
bool RemoteCommandHandler::parseRace(const std::vector<std::string> & message, int type) {
if (message.size() < 3) {
global->getEventLog()->log("RemoteCommandHandler", "Bad remote race command format: " + util::join(message));
return false;
}
std::string section = message[0];
std::string release = message[1];
std::string sitestring = message[2];
std::list<std::string> sites;
if (sitestring == "*") {
for (std::vector<std::shared_ptr<Site> >::const_iterator it = global->getSiteManager()->begin(); it != global->getSiteManager()->end(); it++) {
if ((*it)->hasSection(section) && !(*it)->getDisabled()) {
sites.push_back((*it)->getName());
}
}
}
else {
sites = util::trim(util::split(sitestring, ","));
}
std::list<std::string> dlonlysites;
if (message.size() >= 4) {
std::string dlonlysitestring = message[3];
dlonlysites = util::trim(util::split(dlonlysitestring, ","));
}
if (type == RACE) {
return !!global->getEngine()->newRace(release, section, sites, false, dlonlysites);
}
else if (type == DISTRIBUTE){
return !!global->getEngine()->newDistribute(release, section, sites, false, dlonlysites);
}
else {
return global->getEngine()->prepareRace(release, section, sites, false, dlonlysites);
}
}
void RemoteCommandHandler::FDFail(int sockid, const std::string & message) {
global->getEventLog()->log("RemoteCommandHandler", "UDP binding on port " +
std::to_string(getUDPPort()) + " failed: " + message);
}
void RemoteCommandHandler::disconnect() {
if (connected) {
global->getIOManager()->closeSocket(sockid);
global->getEventLog()->log("RemoteCommandHandler", "Closing UDP socket");
connected = false;
}
}
void RemoteCommandHandler::setEnabled(bool enabled) {
if (this->enabled == enabled) {
return;
}
if (retrying) {
stopRetry();
}
if (enabled) {
connect();
}
else {
disconnect();
}
this->enabled = enabled;
}
void RemoteCommandHandler::setEncrypted(bool encrypted) {
this->encrypted = encrypted;
}
void RemoteCommandHandler::stopRetry() {
if (retrying) {
global->getTickPoke()->stopPoke(this, 0);
retrying = false;
}
}
void RemoteCommandHandler::tick(int) {
stopRetry();
if (enabled) {
connect();
}
}
| 31.458699 | 147 | 0.662011 |
8ed04f1821a61c8d2ef1152f7dc235c1047a0bff | 1,076 | hpp | C++ | lib/STL+/strings/string_hash.hpp | knela96/Game-Engine | 06659d933c4447bd8d6c8536af292825ce4c2ab1 | [
"Unlicense"
] | 3 | 2018-05-07T19:09:23.000Z | 2019-05-03T14:19:38.000Z | deps/stlplus/strings/string_hash.hpp | evpo/libencryptmsg | fa1ea59c014c0a9ce339d7046642db4c80fc8701 | [
"BSD-2-Clause-FreeBSD",
"BSD-3-Clause"
] | null | null | null | deps/stlplus/strings/string_hash.hpp | evpo/libencryptmsg | fa1ea59c014c0a9ce339d7046642db4c80fc8701 | [
"BSD-2-Clause-FreeBSD",
"BSD-3-Clause"
] | null | null | null | #ifndef STLPLUS_STRING_HASH
#define STLPLUS_STRING_HASH
////////////////////////////////////////////////////////////////////////////////
// Author: Andy Rushton
// Copyright: (c) Southampton University 1999-2004
// (c) Andy Rushton 2004 onwards
// License: BSD License, see ../docs/license.html
// Generate a string representation of a hash
////////////////////////////////////////////////////////////////////////////////
#include "strings_fixes.hpp"
#include "hash.hpp"
#include <string>
////////////////////////////////////////////////////////////////////////////////
namespace stlplus
{
template<typename K, typename T, typename H, typename E, typename KS, typename TS>
std::string hash_to_string(const hash<K,T,H,E>& values,
KS key_to_string_fn,
TS value_to_string_fn,
const std::string& pair_separator = ":",
const std::string& separator = ",");
} // end namespace stlplus
#include "string_hash.tpp"
#endif
| 32.606061 | 84 | 0.47026 |
8ed0c0c06675abb85c55c453b94dfbcf52485e1f | 10,646 | hpp | C++ | AeroKernel/parameter.hpp | brandonbraun653/AeroKernel | 23a9a8da7a735ac2d5e1b5d7b59231b8a78a2fd9 | [
"MIT"
] | null | null | null | AeroKernel/parameter.hpp | brandonbraun653/AeroKernel | 23a9a8da7a735ac2d5e1b5d7b59231b8a78a2fd9 | [
"MIT"
] | 2 | 2019-05-04T13:39:41.000Z | 2019-05-04T16:48:24.000Z | AeroKernel/parameter.hpp | brandonbraun653/AeroKernel | 23a9a8da7a735ac2d5e1b5d7b59231b8a78a2fd9 | [
"MIT"
] | null | null | null | /********************************************************************************
* File Name:
* parameter.hpp
*
* Description:
* Implements the Aerospace Kernel Parameter Manager. This module allows a
* system to pass information around in a thread safe manner without the
* producers and consumers knowing implementation details of each other. The
* main benefit of this is decoupling of system modules so that different
* implementations can be swapped in/out without breaking the code. In its
* simplest form, this is just a glorified database.
*
* Usage Example:
* An AHRS (Attitude Heading and Reference System) module is producing raw
* 9-axis data from an IMU (Inertial Measurement Unit) containing gyroscope,
* accelerometer, and magnetometer data. Somehow this data needs to be filtered
* and transformed into a state estimation of a quadrotor, but the team wants to
* try out a couple of different algorithms. The mighty parameter manager is
* called upon as a buffer to safely abstract away the AHRS interface so that
* they only need to query the registered parameters for their latest data.
* The AHRS code will register itself with the Manager as a producer of data
* without knowing who will use it, and the state estimation code will consume
* the data without knowing who produced it. Decoupling of the two systems has
* been achieved! Hurray. Now the software engineers can rest easy knowing they
* can swap out the implementation of either side without breaking the code base.
*
* Requirements Documentation:
* Repository: https://github.com/brandonbraun653/AeroKernelDev
* Location: doc/requirements/parameter_manager.req
*
* 2019 | Brandon Braun | brandonbraun653@gmail.com
********************************************************************************/
#pragma once
#ifndef AERO_KERNEL_PARAMETER_MANAGER_HPP
#define AERO_KERNEL_PARAMETER_MANAGER_HPP
/* C++ Includes */
#include <cstdint>
#include <string>
#include <memory>
#include <functional>
/* Hash Map Include */
#include <sparsepp/spp.h>
/* Chimera Includes */
#include <Chimera/modules/memory/device.hpp>
#include <Chimera/threading.hpp>
namespace AeroKernel::Parameter
{
enum class StorageType : uint8_t
{
INTERNAL_SRAM,
INTERNAL_FLASH,
EXTERNAL_FLASH0,
EXTERNAL_FLASH1,
EXTERNAL_FLASH2,
EXTERNAL_SRAM0,
EXTERNAL_SRAM1,
EXTERNAL_SRAM2,
NONE,
MAX_STORAGE_OPTIONS = NONE
};
using UpdateCallback_t = std::function<bool( const std::string_view &key )>;
/**
* Data structure that fully describes a parameter that is stored
* somewhere in memory. This could be volatile or non-volatile
* memory, it does not matter. The actual data is not stored in
* this block, only the meta information describing it.
*
* @requirement PM002.2
*/
struct ControlBlock
{
/**
* The size of the data this control block describes.
*/
size_t size = std::numeric_limits<size_t>::max();
/**
* The address in memory the data should be stored at. Whether
* or not the address is valid is highly dependent upon the
* storage sink used.
*/
size_t address = std::numeric_limits<size_t>::max();
/**
* Configuration Options:
* Bits 0-2: Memory Storage Location, see MemoryLocation
*
* @requirement PM002.2.1, PM002.2.2, PM002.2.3
*/
size_t config = std::numeric_limits<size_t>::max();
/**
* Optional function that can be used by client applications
* to request an update of the parameter. This allows fresh
* data to be acquired on demand.
*
* @requirement PM002.3
*/
UpdateCallback_t update = nullptr;
};
using ParamCtrlBlk_sPtr = std::shared_ptr<ControlBlock>;
using ParamCtrlBlk_uPtr = std::unique_ptr<ControlBlock>;
/**
* A generator for the control block data structure. Currently
* it's quite simple, but the data type is likely to change in
* the future and necessitates a common interface.
*/
class ControlBlockFactory
{
public:
ControlBlockFactory();
~ControlBlockFactory();
/**
* Compiles all the current settings and returns the fully
* configured control block.
*
* @return AeroKernel::Parameter::ControlBlock
*/
ControlBlock build();
/**
* Clears all current settings and resets the factory to default
*
* @return void
*/
void clear();
/**
* Encodes the sizing information associated with the parameter this
* control block describes.
*
* @param[in] size The size of the parameter
* @return void
*/
void setSize( const size_t size );
/**
* Encodes the address information
*
* @param[in] address The address the parameter will be stored at in NVM
* @return void
*/
void setAddress( const size_t address );
/**
* Encodes the storage device for the actual parameter data
*
* @param[in] type Where the parameter data will be stored
* @return void
*/
void setStorage( const StorageType type );
/**
* Attaches an optional update function
*
* @param[in] callback The update function to attach
* @return void
*/
void setUpdateCallback( UpdateCallback_t callback );
private:
ControlBlock mold;
};
/**
* A static class that interprets the control block configuration
* and can return back non-encoded data. Currently this is just a
* simple wrapper, but the control block data structure may change
* in the future, necessitating a common interface.
*/
class ControlBlockInterpreter
{
public:
ControlBlockInterpreter() = default;
~ControlBlockInterpreter() = default;
static StorageType getStorage( const ControlBlock &ctrlBlk );
static size_t getAddress( const ControlBlock &ctrlBlk );
static size_t getSize( const ControlBlock &ctrlBlk );
static UpdateCallback_t getUpdateCallback( const ControlBlock &ctrlBlk );
};
/**
* Parameter Manager Implementation
*/
class Manager : public Chimera::Threading::Lockable
{
public:
/**
* Initialize the parameter manager instance
*
* @param[in] lockTimeout_mS How long to wait for the manager to be available
* @return Manager
*/
Manager( const size_t lockTimeout_mS = 50 );
~Manager();
/**
* Initializes the parameter manager to a default configuration and allocates
* the given number of parameters that can be actively registered. Ideally this
* is only performed once at startup and should not be called again to avoid
* dynamic memory allocation. If your system can handle that, then go wild.
*
* @requirement PM001
*
* @param[in] numParameters How many parameters can be managed by this class
* @return bool
*/
bool init( const size_t numParameters );
/**
* Registers a new parameter into the manager
*
* @requirement PM002, PM002.1
*
* @param[in] key The parameter's name
* @param[in] controlBlock Information describing where the parameter lives in memory
* @return bool
*/
bool registerParameter( const std::string_view &key, const ControlBlock &controlBlock );
/**
* Removes a parameter from the manager
*
* @requirement PM006
*
* @param[in] key The parameter's name
* @return bool
*/
bool unregisterParameter( const std::string_view &key );
/**
* Checks if the given parameter has been registered
*
* @requirement PM003
*
* @param[in] key The parameter's name
* @return bool
*/
bool isRegistered( const std::string_view &key );
/**
* Read the parameter data from wherever it has been stored
*
* @requirement PM004
*
* @param[in] key The parameter's name
* @param[in] param Where to place the read data
* @return bool
*/
bool read( const std::string_view &key, void *const param );
/**
* Write the parameter data to wherever it is stored
*
* @requirement PM005
*
* @param[in] key The parameter's name
* @param[in] param Where to write data from
* @return bool
*/
bool write( const std::string_view &key, const void *const param );
/**
* If registered, executes the parameter's update method
*
* @requirement PM0011
*
* @param[in] key The parameter's name
* @return bool
*/
bool update( const std::string_view &key );
/**
* Registers a memory sink with the manager backend
*
* @requirement PM010
*
* @param[in] storage The type of storage the driver represents as defined in the Location namespace
* @param[in] driver A fully configured instance of a memory driver
* @return bool
*/
bool registerMemoryDriver( const StorageType storage, Chimera::Modules::Memory::Device_sPtr &driver );
/**
* Allows the user to assign virtual memory specifications to a
* registered memory driver. This allows for partitioning the regions
* that the Parameter manager is allowed access to.
*
* @requirement PM009
*
* @param[in] storage The type of storage the driver represents as defined in the Location namespace
* @param[in] specs Memory configuration specs
* @return bool
*/
bool registerMemorySpecs( const StorageType storage, const Chimera::Modules::Memory::Descriptor &specs );
/**
* Gets the control block associated with a given parameter
*
* @requirement PM012
*
* @param[in] key The parameter's name
* @return const AeroKernel::Parameter::ParamCtrlBlk &
*/
const ControlBlock &getControlBlock( const std::string_view &key );
protected:
bool initialized;
size_t lockTimeout_mS;
spp::sparse_hash_map<std::string_view, ControlBlock> params;
std::array<Chimera::Modules::Memory::Device_sPtr, static_cast<size_t>( StorageType::MAX_STORAGE_OPTIONS )> memoryDriver;
std::array<Chimera::Modules::Memory::Descriptor, static_cast<size_t>( StorageType::MAX_STORAGE_OPTIONS )> memorySpecs;
};
using Manager_sPtr = std::shared_ptr<Manager>;
using Manager_uPtr = std::unique_ptr<Manager>;
} // namespace AeroKernel::Parameter
#endif /* !AERO_KERNEL_PARAMETER_MANAGER_HPP */ | 31.874251 | 124 | 0.652546 |
8ed3ff3e5a3faddf592646ced6614c28da934d0e | 742 | cpp | C++ | Assignments/Project 1/4.16/main.cpp | georgio/CSC212 | 6b5622b6ed955109e5d2c93374ad56f623113040 | [
"Unlicense"
] | null | null | null | Assignments/Project 1/4.16/main.cpp | georgio/CSC212 | 6b5622b6ed955109e5d2c93374ad56f623113040 | [
"Unlicense"
] | null | null | null | Assignments/Project 1/4.16/main.cpp | georgio/CSC212 | 6b5622b6ed955109e5d2c93374ad56f623113040 | [
"Unlicense"
] | null | null | null | //
// main.cpp
// assignment 1
// 4.16
//
#include <iostream>
int main() {
double total_funds = 0;
while (true) {
int laps;
double sponsorship_rate, contribution;
std::cout << "Enter laps completed(-1 to end): ";
std::cin >> laps;
if (laps == -1) {
std::cout << "Total funds raised: " << total_funds;
return 0;
}
std::cout << "Enter sponsorship rate: ";
std::cin >> sponsorship_rate;
contribution = laps*sponsorship_rate;
if (laps > 40) {
contribution += (40-laps)*sponsorship_rate*1.5;
}
std::cout << "Student contribution: " << contribution << "\n";
total_funds += contribution;
}
}
| 24.733333 | 70 | 0.521563 |