hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dd83d4744f2f8bad872ada1b8777f900caa23599 | 1,175 | cpp | C++ | Sid's Levels/Level - 1/DynamicProgramming/PaintManyHouse1.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 14 | 2021-08-22T18:21:14.000Z | 2022-03-08T12:04:23.000Z | Sid's Levels/Level - 1/DynamicProgramming/PaintManyHouse1.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 1 | 2021-10-17T18:47:17.000Z | 2021-10-17T18:47:17.000Z | Sid's Levels/Level - 1/DynamicProgramming/PaintManyHouse1.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 5 | 2021-09-01T08:21:12.000Z | 2022-03-09T12:13:39.000Z | //OM GAN GANAPATHAYE NAMO NAMAH
//JAI SHRI RAM
//JAI BAJRANGBALI
//AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n, k;
cin >> n >> k;
int arr[n][k];
for(int i = 0; i < n; i++)
{
for(int j = 0; j < k; j++)
{
cin >> arr[i][j];
}
}
int dp[n][k];
//the first row will anyway be same for dp and arr
for(int i = 0; i < k; i++)
{
dp[0][i] = arr[0][i];
}
//remaining
for(int i = 1; i < n; i++)
{
for(int j = 0; j < k; j++)
{
int cur = arr[i][j];
int min = INT_MAX;
//minimum in the previous row other than current index
for(int l = 0; l < k; l++)
{
if(l != j && dp[i-1][l] < min)
{
min = dp[i-1][l];
}
}
dp[i][j] = cur + min;
}
}
int res = INT_MAX;
//find the minimum in the last row
for(int i = 0; i < k; i++)
{
if(dp[n-1][i] < res)
res = dp[n-1][i];
}
cout << res << endl;
}
| 22.596154 | 67 | 0.403404 | Tiger-Team-01 |
dd85f0e48ce5b3e42eb69c3bf5a73870503a1197 | 560 | cpp | C++ | Playground/src/play.cpp | celestialkey/VisceralCombatEngine | b8021218401be5504ff07b087d9562c8c8ddbfb4 | [
"Apache-2.0"
] | null | null | null | Playground/src/play.cpp | celestialkey/VisceralCombatEngine | b8021218401be5504ff07b087d9562c8c8ddbfb4 | [
"Apache-2.0"
] | null | null | null | Playground/src/play.cpp | celestialkey/VisceralCombatEngine | b8021218401be5504ff07b087d9562c8c8ddbfb4 | [
"Apache-2.0"
] | null | null | null |
#include <VCE.h>
#include <glm/vec3.hpp>
class ExampleLayer : public VCE::Layer
{
public:
ExampleLayer()
: Layer("Example") {}
~ExampleLayer() {
}
void OnUpdate() override {
}
void OnAttach(){
}
void OnDetach(){
}
void OnEvent(VCE::Event& e) override {
//VCE_TRACE("ExampleLayer::OnEvent -> {0}", e);
}
};
class TestBed : public VCE::Application
{
public:
TestBed() {
PushLayer(new ExampleLayer());
}
~TestBed() {
}
};
// Called by the engine (extern'd in it)
VCE::Application* VCE::CreateApplication() {
return new TestBed();
} | 13.333333 | 49 | 0.6375 | celestialkey |
dd8abd59e2aa4e7a14513e5204334387c32565cd | 5,591 | cpp | C++ | src/object/Triangle.cpp | NyantasticUwU/nyengine | b6a47d2bfb101366eeda1b318e66f09d37317688 | [
"MIT"
] | 2 | 2021-12-26T05:10:41.000Z | 2022-01-30T19:51:23.000Z | src/object/Triangle.cpp | NyantasticUwU/Nyengine | b6a47d2bfb101366eeda1b318e66f09d37317688 | [
"MIT"
] | null | null | null | src/object/Triangle.cpp | NyantasticUwU/Nyengine | b6a47d2bfb101366eeda1b318e66f09d37317688 | [
"MIT"
] | null | null | null | #include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <Nyengine/backend/error.hpp>
#include <Nyengine/exceptions/GLException.hpp>
#include <Nyengine/object/Triangle.hpp>
#include <cstdlib>
#define TOP_VERT_POS 0.0f, 0.5f, 0.0f
#define BML_VERT_POS -0.5f, -0.5f, 0.0f
#define BMR_VERT_POS 0.5f, -0.5f, 0.0f
#define TOP_TEX_COORDS 0.5f, 1.0f
#define BML_TEX_COORDS 0.0f, 0.0f
#define BMR_TEX_COORDS 1.0f, 0.0f
#define ALL_NORMALS 0.0f, 0.0f, 1.0f
using nyengine::exceptions::GLException;
/// The triangle's VAO.
static GLuint s_vao{0u};
/// The triangle's VBO.
static GLuint s_vbo{0u};
/// Determines whether a triangle has been created.
static bool s_isTriangleCreated{false};
/// Creates the OpenGL vertex array object for the triangle.
/// Throws GLException on error.
static void createTriangle()
{
if (!s_isTriangleCreated)
{
using namespace nyengine;
// Creating VAO.
glGenVertexArrays(1, &s_vao);
glBindVertexArray(s_vao);
// Creating vertex buffer object.
/// Represents vertex coordinates for the triangle.
static constexpr float VERTICIES[]{
TOP_VERT_POS, TOP_TEX_COORDS, ALL_NORMALS, // Top vert.
BML_VERT_POS, BML_TEX_COORDS, ALL_NORMALS, // Bottom left vert.
BMR_VERT_POS, BMR_TEX_COORDS, ALL_NORMALS // Bottom right vert.
};
/// Represents the stride of vertex attributes for the triangle.
static constexpr type::int32_dynamic_t STRIDE{8 * sizeof(float)};
glGenBuffers(1, &s_vbo);
glBindBuffer(GL_ARRAY_BUFFER, s_vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(VERTICIES), VERTICIES, GL_STATIC_DRAW);
backend::assertThrow(backend::getGLErrors(), GLException::BUFFER_DATA_ERR);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, STRIDE, (void *)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, STRIDE, (void *)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, STRIDE, (void *)(5 * sizeof(float)));
glEnableVertexAttribArray(2);
// Setting clean up for atexit.
std::atexit([]() {
if (s_isTriangleCreated)
{
// Cleaning up memory allocated by OpenGL.
glDeleteVertexArrays(1, &s_vao);
glDeleteBuffers(1, &s_vbo);
// Clearing any OpenGL errors.
backend::getGLErrors();
}});
s_isTriangleCreated = true;
}
}
/// Contains all Nyengine objects.
namespace nyengine::object
{
/// Creates a triangle with the specified shader.
/// Throws GLException on error.
Triangle::Triangle(const shader::Shader &shader) : m_shader{shader}
{
createTriangle();
}
/// Draws the triangle.
/// Throws GLException on error.
void Triangle::draw() const
{
m_shader.useForDrawing();
const GLint uniformloc{glGetUniformLocation(m_shader.id(), "u_transform")};
glUniformMatrix4fv(uniformloc, 1, GL_FALSE, glm::value_ptr(m_transform));
backend::assertThrow(backend::getGLErrors(), GLException::SET_UNIFORM_ERR);
glBindVertexArray(s_vao);
glDrawArrays(GL_TRIANGLES, 0, 3);
backend::assertThrow(backend::getGLErrors(), GLException::DRAW_ERR);
}
/// Translates the triangle.
inline void Triangle::translate(geometry::Point3DF trans, bool isLocal) noexcept
{
this->translate(trans.x, trans.y, trans.z, isLocal);
}
/// Translates the triangle.
void Triangle::translate(
float32_dynamic_t x,
float32_dynamic_t y,
float32_dynamic_t z,
bool isLocal) noexcept
{
const glm::vec3 trans{x, y, z};
m_transform = (isLocal)
? glm::translate(m_transform, trans)
: glm::translate(glm::mat4{1.0f}, trans) * m_transform;
m_translation = m_transform[3];
}
/// Scales the triangle.
inline void Triangle::scale(geometry::Point3DF trans) noexcept
{
this->scale(trans.x, trans.y, trans.z);
}
/// Scales the triangle.
void Triangle::scale(float32_dynamic_t x, float32_dynamic_t y, float32_dynamic_t z) noexcept
{
const glm::vec3 s{x, y, z};
m_scale *= s;
m_transform = glm::scale(m_transform, s);
}
/// Rotates the triangle. The z coordinate does nothing.
inline void Triangle::rotate(float32_dynamic_t deg, geometry::Point3DF trans) noexcept
{
this->rotate(deg, trans.x, trans.y, trans.z);
}
/// Rotates the triangle.
void Triangle::rotate(
float32_dynamic_t deg,
float32_dynamic_t x,
float32_dynamic_t y,
float32_dynamic_t z) noexcept
{
const glm::vec3 rot{x, y, -z};
m_rotation += rot * deg;
m_transform = glm::rotate(m_transform, glm::radians(deg), rot);
}
/// Gets the translation of the triangle.
geometry::Point3DF Triangle::getTranslation() const noexcept
{
return geometry::Point3DF{m_translation.x, m_translation.y, m_translation.z};
}
/// Gets the scale of the triangle.
geometry::Point3DF Triangle::getScale() const noexcept
{
return geometry::Point3DF{m_scale.x, m_scale.y, m_scale.z};
}
/// Gets the rotation of the triangle.
geometry::Point3DF Triangle::getRotation() const noexcept
{
return geometry::Point3DF{m_rotation.x, m_rotation.y, m_rotation.z};
}
}
| 35.386076 | 96 | 0.649258 | NyantasticUwU |
dd8b9c11be4672e652573d47c070799316dff0f5 | 7,445 | cpp | C++ | test/pcr-grafo.cpp | gafeol/chinese-postman | 1b1dd9173ad0f58d325e0a973e2689625094df0b | [
"MIT"
] | null | null | null | test/pcr-grafo.cpp | gafeol/chinese-postman | 1b1dd9173ad0f58d325e0a973e2689625094df0b | [
"MIT"
] | 16 | 2020-02-23T05:46:26.000Z | 2021-01-27T02:09:49.000Z | test/pcr-grafo.cpp | gafeol/chinese-postman | 1b1dd9173ad0f58d325e0a973e2689625094df0b | [
"MIT"
] | 1 | 2020-12-11T18:26:31.000Z | 2020-12-11T18:26:31.000Z | #include "gtest/gtest.h"
#include "bits/stdc++.h"
using namespace std;
#include "../code/grafo.hpp"
#include "../code/pcr-grafo.cpp"
void print(vector<int> v){
printf("vector with %d elements:\n", (int)v.size());
for(int x: v)
printf("%d ", x);
puts("");
}
TEST(PCRGrafo, Simples){
Grafo G(2, { {0, 1, 2.}});
PCR pcr;
auto ans = pcr.solveById(G, {0});
EXPECT_EQ(ans, vector<int>(2, 0));
}
TEST(PCRGrafo, SimplesSemR){
Grafo G(2, { {0, 1, 2.}});
PCR pcr;
auto ans = pcr.solveById(G, {});
EXPECT_EQ(ans, vector<int>());
}
TEST(PCRGrafo, Arvore){
Grafo G(3, { {0, 1, 2.}, {1, 2, 1.}});
PCR pcr;
auto ans = pcr.solveById(G, {1});
EXPECT_EQ(ans, vector<int>(2, 1));
}
TEST(PCRGrafo, Circuito) {
Grafo G(4, {{0, 1, 1.},
{1, 2, 2.},
{2, 3, 3.},
{3, 0, 4.}});
PCR pcr;
auto ans = pcr.solveById(G, {1, 2, 3});
vector<int> exp = {0, 1, 2, 3};
EXPECT_EQ(ans, exp);
}
TEST(PCRGrafo, Circuito2) {
Grafo G(4, {{0, 1, 10.},
{1, 2, 2.},
{2, 3, 3.},
{3, 0, 4.}});
PCR pcr;
auto ans = pcr.solveById(G, {1, 2, 3});
vector<int> exp = {3, 2, 1, 1, 2, 3};
EXPECT_EQ(ans, exp);
}
TEST(PCRGrafo, Circuito3) {
Grafo G(4, {{0, 1, 10.},
{1, 2, 2.},
{2, 3, 3.},
{3, 0, 4.}});
PCR pcr;
auto ans = pcr.solveById(G, {1, 2});
vector<int> exp = {1, 2, 2, 1};
EXPECT_EQ(ans, exp);
}
/*
0 1
0 2
0 3
1 4
2 5
3 6
*/
TEST(PCRGrafo, Estrela){
Grafo G(7, {{0, 1},
{0, 2},
{0, 3},
{1, 4},
{2, 5},
{3, 6}});
PCR pcr;
auto ans = pcr.solveById(G, {3, 4, 5});
// trilha se inicia em 1
auto exp = vector<int> { 3, 3, 0, 2, 5, 5, 2, 1, 4, 4, 1, 0 };
EXPECT_EQ(ans, exp);
}
TEST(PCRGrafo, EstrelaComAtalhos){
Grafo G(7, {{0, 1}, // 0
{0, 2},// 1
{0, 3},// 2
{1, 4},// 3
{2, 5},// 4
{3, 6},// 5
{4, 5},// 6
{5, 6},// 7
{6, 4}});// 8
PCR pcr;
auto ans = pcr.solveById(G, {3, 4, 5});
// trilha se inicia em 1, solucao otima com custo 8
auto exp = vector<int> {3, 8, 5, 2, 1, 4, 6, 3 };
EXPECT_EQ(ans, exp);
}
/// Exemplo apresentado na seção do PCR da monografia.
/// Solução ótima encontrada, com custo 16
TEST(PCRGrafo, Exemplo){
const int a = 0, b = 1, c = 2, d = 3, e = 4, f = 5;
Grafo G(6, {{a, b, 2.}, // 0
{a, c, 4.}, // 1
{b, c, 2.}, // 2
{b, d, 1.}, // 3
{c, d, 1.}, // 4
{b, f, 3.}, // 5
{d, f, 2.}, // 6
{c, e, 5.}, // 7
{e, f, 2.}}); // 8
PCR pcr;
auto ans = pcr.solveById(G, {0, 1, 2, 8});
auto exp = vector<int>{1, 4, 6, 8, 8, 6, 4, 2, 0};
EXPECT_EQ(ans, exp);
}
/*
1 2 3
0 3 1
3 2 1
1 3 2
0 1 2
Custo: 11 (duplica 1 3 2)
TEST(PCCGrafo, Ciclo){
Grafo G(4, { make_tuple(1, 2, 3),
make_tuple(0, 3, 1),
make_tuple(3, 2, 1),
make_tuple(1, 3, 2),
make_tuple(0, 1, 2)});
PCC pcc(G);
auto ans = pcc.solve();
EXPECT_DOUBLE_EQ(ans.first, 11);
EXPECT_TRUE(pcc.checkSolution(ans));
}
// Este teste força o algoritmo a usar arestas paralelas de custos diferentes
TEST(PCCGrafo, ArestasParalelas){
Grafo G(2, {make_tuple(0, 1, 2.),
make_tuple(0, 1, 3.)});
PCC pcc(G);
auto ans = pcc.solveById();
EXPECT_DOUBLE_EQ(ans.first, 5);
EXPECT_TRUE(pcc.checkSolutionById(ans));
}
0 3 2
3 2 7
0 1 4
3 4 10
1 5 1
1 6 3
Tem que duplicar todas arestas, custo otimo 2*27 = 54
TEST(PCCGrafo, Arvore){
Grafo G(7, { make_tuple(0, 3, 2.),
make_tuple(3, 2, 7),
make_tuple(0, 1, 4),
make_tuple(3, 4, 10),
make_tuple(1, 5, 1),
make_tuple(1, 6, 3)});
PCC pcc(G);
auto ans = pcc.solveById();
EXPECT_DOUBLE_EQ(ans.first, 54);
EXPECT_TRUE(pcc.checkSolutionById(ans));
}
TEST(PCCGrafo, CustoErradoId){
Grafo G(7, { make_tuple(0, 3, 2.),
make_tuple(3, 2, 7),
make_tuple(0, 1, 4),
make_tuple(3, 4, 10),
make_tuple(1, 5, 1),
make_tuple(1, 6, 3)});
PCC pcc(G);
auto ans = pcc.solveById();
EXPECT_DOUBLE_EQ(ans.first, 54);
ans.first = 53.9;
EXPECT_FALSE(pcc.checkSolutionById(ans));
ans.first = 54.1;
EXPECT_FALSE(pcc.checkSolutionById(ans));
}
TEST(PCCGrafo, CustoErrado){
Grafo G(7, { make_tuple(0, 3, 2.),
make_tuple(3, 2, 7),
make_tuple(0, 1, 4),
make_tuple(3, 4, 10),
make_tuple(1, 5, 1),
make_tuple(1, 6, 3)});
PCC pcc(G);
auto ans = pcc.solve();
EXPECT_DOUBLE_EQ(ans.first, 54);
ans.first = 53.9;
EXPECT_FALSE(pcc.checkSolution(ans));
ans.first = 54.1;
EXPECT_FALSE(pcc.checkSolution(ans));
}
TEST(PCCGrafo, CircuitoErradoId){
Grafo G(5, {{0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 0}});
PCC pcc(G);
pair<double, vector<int>> ans;
ans.first = 6;
ans.second = {0, 1, 2, 3, 4, 1};
EXPECT_FALSE(pcc.checkSolutionById(ans));
ans.first = 7;
ans.second = {0, 1, 2, 3, 4, 0, 1};
EXPECT_FALSE(pcc.checkSolutionById(ans));
ans.first = 6;
ans.second = {1, 2, 3, 4, 0, 1};
EXPECT_FALSE(pcc.checkSolutionById(ans));
}
TEST(PCCGrafo, CheckSolucoesId){
Grafo G(5, {{0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 0}});
PCC pcc(G);
auto ans = pcc.solveById();
EXPECT_DOUBLE_EQ(5, ans.first);
EXPECT_TRUE(pcc.checkSolutionById(ans));
ans.first = 10;
int sz = ans.second.size();
for(int i=0;i<sz;i++)
ans.second.push_back(ans.second[i]);
EXPECT_TRUE(pcc.checkSolutionById(ans));
ans.first = 5;
ans.second = {1, 2, 3, 4, 0};
EXPECT_TRUE(pcc.checkSolutionById(ans));
ans.first = 7;
ans.second = {1, 2, 3, 4, 0, 1, 1};
EXPECT_TRUE(pcc.checkSolutionById(ans));
}
TEST(PCCGrafo, CircuitoErrado){
Grafo G(5, {{0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 0}});
PCC pcc(G);
auto ans = pcc.solve();
EXPECT_DOUBLE_EQ(5, ans.first);
EXPECT_TRUE(pcc.checkSolution(ans));
ans.first = 6;
ans.second = {0, 1, 2, 3, 4, 0, 1};
EXPECT_FALSE(pcc.checkSolution(ans));
ans.first = 7;
ans.second = {0, 1, 2, 3, 4, 0, 1, 0};
EXPECT_TRUE(pcc.checkSolution(ans));
ans.first = 5;
ans.second = {1, 2, 3, 4, 0, 1};
EXPECT_TRUE(pcc.checkSolution(ans));
ans.first = 4;
ans.second = {1, 2, 3, 4, 0};
EXPECT_FALSE(pcc.checkSolution(ans));
}
TEST(PCCGrafo, CaminhoSimples){
Grafo G(3, {{0, 1}, {1, 2}});
PCC pcc(G);
auto ans = pcc.solveById();
EXPECT_DOUBLE_EQ(4, ans.first);
EXPECT_TRUE(pcc.checkSolutionById(ans));
ans = pcc.solve();
EXPECT_DOUBLE_EQ(4, ans.first);
EXPECT_TRUE(pcc.checkSolution(ans));
}
TEST(PCCGrafo, ArestaNaoPercorrida){
Grafo G(3, {{0, 1}, {1, 2}});
PCC pcc(G);
pair<double, vector<int>> ansId = {2., {0, 0}};
EXPECT_FALSE(pcc.checkSolutionById(ansId));
pair<double, vector<int>> ans = {2., {0, 1, 0}};
EXPECT_FALSE(pcc.checkSolution(ans));
}
*/
| 25.323129 | 77 | 0.495903 | gafeol |
dd8bde52178f466f2a1e2db53d81f217fef502ce | 1,484 | hpp | C++ | headers/ScriptTree.hpp | mcidclan/i3d-engine | 222bfc3669f78079b0a77ca756f44decb24e0272 | [
"Apache-2.0"
] | 1 | 2018-01-16T03:26:21.000Z | 2018-01-16T03:26:21.000Z | headers/ScriptTree.hpp | mcidclan/i3d-engine | 222bfc3669f78079b0a77ca756f44decb24e0272 | [
"Apache-2.0"
] | null | null | null | headers/ScriptTree.hpp | mcidclan/i3d-engine | 222bfc3669f78079b0a77ca756f44decb24e0272 | [
"Apache-2.0"
] | null | null | null | #ifndef SCRIPTTREE_HPP
#define SCRIPTTREE_HPP
#include "ScriptSheet.hpp"
class ScriptTree : public Element
{
public:
/// Constructor.
ScriptTree();
/// Destructor.
~ScriptTree();
///
static void draw(void);
///
void addNewScriptSheet(Script const);
///@{
/// Allow to set the current ScriptSheet.
void setCurrentScriptSheet(uint const);
void setCurrentScriptSheet(void);
///@}
///
template <uint D>
void setCurrentTie(uint (&)[D]);
///@{
/// Actions.
void aDo_move(void* const);
///@}
private:
/// Allows access to the current instance,
/// from static functions.
static ScriptTree* current;
/// The root of the ScriptSheet tree.
ScriptSheet* root;
/// Current ScriptSheet.
ScriptSheet* currentsheet;
/// Current tie information.
uint* tie;
/// Current tie information.
uint tiedepth;
///
uint relativesheetid;
/// Allows to switch properly to an other ScriptSheet.
void switchSheet(ScriptSheet* const);
///@{
/// Allow to move through the ScriptTree.
void moveToUp(void);
void moveToDown(void);
void moveToLeft(void);
void moveToRight(void);
///@}
/// Allows to move horizontally, through the children.
void horizontalMove(ScriptSheet* const);
};
/// Set the current tie on which we have to work.
template <uint D>
void ScriptTree::setCurrentTie(uint (&tie)[D])
{
this->tie = tie;
this->tiedepth = D;
}
#endif
| 17.458824 | 57 | 0.639488 | mcidclan |
dd8d3ce076299ed8f04602687eb19af22203af15 | 1,946 | hpp | C++ | src/socket_pipeline_factory.hpp | sgalkin/notifications-backend | bf995816ecbfc54818f4d6277d4dbb695252cf75 | [
"MIT"
] | 2 | 2017-01-02T02:02:23.000Z | 2021-04-15T09:21:27.000Z | src/socket_pipeline_factory.hpp | sgalkin/notifications-backend | bf995816ecbfc54818f4d6277d4dbb695252cf75 | [
"MIT"
] | null | null | null | src/socket_pipeline_factory.hpp | sgalkin/notifications-backend | bf995816ecbfc54818f4d6277d4dbb695252cf75 | [
"MIT"
] | null | null | null | #pragma once
#include <wangle/channel/Pipeline.h>
#include <wangle/channel/Handler.h>
#include <wangle/channel/EventBaseHandler.h>
#include <wangle/channel/AsyncSocketHandler.h>
#include <folly/io/async/AsyncTransport.h>
#include <folly/Demangle.h>
#include <glog/logging.h>
#include <tuple>
#include <memory>
#include <utility>
namespace detail {
template<size_t I, typename Handlers>
typename std::enable_if<I == std::tuple_size<Handlers>::value, wangle::PipelineBase&>::type
add(Handlers*, wangle::PipelineBase& p) { return p; }
template<size_t I = 0, typename Handlers>
typename std::enable_if<I < std::tuple_size<Handlers>::value, wangle::PipelineBase&>::type
add(Handlers* handlers, wangle::PipelineBase& pipeline) {
VLOG(3) << "adding " << folly::demangle(typeid(typename std::tuple_element<I, Handlers>::type).name());
return add<I + 1>(handlers, pipeline.addBack(&std::get<I>(*handlers)));
}
template<typename Pipeline, typename... Args>
class SocketPipelineFactory : public wangle::PipelineFactory<Pipeline> {
public:
explicit SocketPipelineFactory(Args... args) :
handlers_(std::forward_as_tuple(args...))
{}
virtual ~SocketPipelineFactory() = default;
virtual typename Pipeline::Ptr newPipeline(std::shared_ptr<folly::AsyncTransportWrapper> sock) override {
auto pipeline = Pipeline::create();
pipeline->addBack(wangle::AsyncSocketHandler(sock));
pipeline->addBack(wangle::EventBaseHandler());
detail::add(&handlers_, *pipeline);
pipeline->finalize();
return pipeline;
}
private:
std::tuple<Args...> handlers_;
};
}
template<typename Pipeline>
struct SocketPipelineFactory {
template<typename... Args>
static std::shared_ptr<typename wangle::PipelineFactory<Pipeline>> create(Args... args) {
return std::make_shared<detail::SocketPipelineFactory<Pipeline, Args...>>(std::forward<Args>(args)...);
}
};
| 32.433333 | 111 | 0.707605 | sgalkin |
dd9130c36a6b9d2e25027ed8d8676612edcdb0ed | 9,108 | cpp | C++ | CityRenderingEngine/engine/rendering/Shader.cpp | roooodcastro/city-rendering-engine | eb0f2f948ab509baf7f5e08ec05f6eb510805eac | [
"MIT"
] | 2 | 2021-03-13T13:33:25.000Z | 2021-03-13T14:19:18.000Z | CityRenderingEngine/engine/rendering/Shader.cpp | roooodcastro/city-rendering-engine | eb0f2f948ab509baf7f5e08ec05f6eb510805eac | [
"MIT"
] | 1 | 2020-05-23T05:48:01.000Z | 2020-05-24T08:36:06.000Z | CityRenderingEngine/engine/rendering/Shader.cpp | roooodcastro/city-rendering-engine | eb0f2f948ab509baf7f5e08ec05f6eb510805eac | [
"MIT"
] | 1 | 2021-03-13T13:33:33.000Z | 2021-03-13T13:33:33.000Z | #include "Shader.h"
Shader::Shader(int name, const std::string &vertexFilename, const std::string &fragmentFilename) :
Resource(name) {
this->vertexFilename = std::string(vertexFilename);
this->fragmentFilename = std::string(fragmentFilename);
this->geometryFilename = "";
this->tessCtrlFilename = "";
this->tessEvalFilename = "";
this->shaderParameters = new std::vector<ShaderParameter*>();
}
Shader::~Shader(void) {
for (auto it = shaderParameters->begin(); it != shaderParameters->end(); it++) {
delete (*it);
}
shaderParameters->clear();
delete shaderParameters;
shaderParameters = nullptr;
}
void Shader::load() {
Renderer *renderer = Naquadah::getRenderer();
if (renderer != nullptr) {
std::string vertexCode = FileIO::mergeLines(FileIO::readTextFile(vertexFilename));
std::string fragmentCode = FileIO::mergeLines(FileIO::readTextFile(fragmentFilename));
std::string geometryCode = FileIO::mergeLines(FileIO::readTextFile(geometryFilename));
std::string tessCtrlCode = FileIO::mergeLines(FileIO::readTextFile(tessCtrlFilename));
std::string tessEvalCode = FileIO::mergeLines(FileIO::readTextFile(tessEvalFilename));
this->program = glCreateProgram();
vertexId = compileShader(program, GL_VERTEX_SHADER, vertexCode.c_str());
fragmentId = compileShader(program, GL_FRAGMENT_SHADER, fragmentCode.c_str());
if (geometryCode.size() > 0)
geometryId = compileShader(program, GL_GEOMETRY_SHADER, geometryCode.c_str());
if (tessCtrlCode.size() > 0 && tessEvalCode.size() > 0) {
tessCtrlId = compileShader(program, GL_TESS_CONTROL_SHADER, tessCtrlCode.c_str());
tessEvalId = compileShader(program, GL_TESS_EVALUATION_SHADER, tessEvalCode.c_str());
}
setDefaultAttributes();
if (linkProgram(program))
valid = true;
} else
valid = false;
loaded = true;
}
void Shader::unload() {
// First detach and delete each individual shader
glDetachShader(program, vertexId);
glDeleteShader(vertexId);
glDetachShader(program, fragmentId);
glDeleteShader(fragmentId);
glDetachShader(program, geometryId);
glDeleteShader(geometryId);
glDetachShader(program, tessCtrlId);
glDeleteShader(tessCtrlId);
glDetachShader(program, tessEvalId);
glDeleteShader(tessEvalId);
// Then delete the shader program
glDeleteProgram(program);
loaded = false;
valid = false;
}
void Shader::reload() {
if (loaded)
unload();
load();
}
/*
* This function should set up which generic attribute attaches to which
* input variable of the vertex shader. I always make my vertex shaders
* use the same basic names (i.e "position" for positions...) so that it
* becomes trivial to attach vertex data to shaders, without having to
* mess around with layout qualifiers in the shaders themselves etc.
*/
void Shader::setDefaultAttributes() {
Renderer *renderer = Naquadah::getRenderer();
if (renderer != nullptr) {
bindAttributeLocation(program, VERTEX_BUFFER, "position");
bindAttributeLocation(program, UV_MAP_BUFFER, "uv_map");
bindAttributeLocation(program, NORMAL_BUFFER, "normal");
//renderer->bindAttributeLocation(program, LOC_TANGENT_BUFFER, "tangent");
}
}
int Shader::compileShader(GLuint program, GLenum shaderType, const char *shaderCode) {
if (glIsProgram(program)) {
GLuint shader = glCreateShader(shaderType);
glShaderSource(shader, 1, &shaderCode, nullptr);
glCompileShader(shader);
GLint status = GL_FALSE, infoLogLength = 10;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_TRUE) {
glAttachShader(program, shader);
//logOpenGLError("ATTACH_" + getShaderTypeName(shaderType));
return shader;
} else {
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);
std::vector<char> infoLog(infoLogLength, 'X');
glGetShaderInfoLog(shader, infoLogLength, nullptr, &infoLog[0]);
std::cerr << "OpenGL Error compiling " << getShaderTypeName(shaderType) << " of Shader Program '" <<
name << "':" << std::endl;
std::cerr << &infoLog[0] << std::endl;
//logOpenGLError("COMPILE_" + getShaderTypeName(shaderType));
}
}
return -1;
}
bool Shader::linkProgram(GLuint program) {
if (glIsProgram(program)) {
glLinkProgram(program);
GLint status = GL_FALSE, len = 10;
glGetProgramiv(program, GL_LINK_STATUS, &status);
if (status == GL_TRUE) return true;
// If we can't link, print the error to the console
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &len);
std::vector<char> log(len, 'X');
glGetProgramInfoLog(program, len, nullptr, &log[0]);
std::cerr << &log[0] << std::endl;
//logOpenGLError("LINK_PROGRAM");
}
return false;
}
void Shader::bindAttributeLocation(GLuint program, GLuint location, std::string attrName) {
glBindAttribLocation(program, location, attrName.c_str());
}
void Shader::updateShaderParameters(bool forceUpdate) {
for (int i = 0; i < shaderParameters->size(); i++) {
ShaderParameter *parameter = shaderParameters->at(i);
if (parameter->hasValueChanged() || forceUpdate) {
GLuint location = glGetUniformLocation(program, parameter->parameterName.c_str());
if (location != -1) {
switch (parameter->parameterType) {
case PARAMETER_INT:
glUniform1iv(location, parameter->valueSize, (int*) parameter->getValue());
break;
case PARAMETER_FLOAT:
glUniform1fv(location, parameter->valueSize, (float*) parameter->getValue());
break;
case PARAMETER_DOUBLE:
glUniform1dv(location, parameter->valueSize, (double*) parameter->getValue());
break;
case PARAMETER_VECTOR_2:
glUniform2fv(location, parameter->valueSize, (float*) parameter->getValue());
break;
case PARAMETER_VECTOR_3:
glUniform3fv(location, parameter->valueSize, (float*) parameter->getValue());
break;
case PARAMETER_VECTOR_4:
glUniform4fv(location, parameter->valueSize, (float*) parameter->getValue());
break;
case PARAMETER_MATRIX_3:
glUniformMatrix3fv(location, parameter->valueSize, false, (float*) parameter->getValue());
break;
case PARAMETER_MATRIX_4:
glUniformMatrix4fv(location, parameter->valueSize, false, (float*) parameter->getValue());
break;
}
}
}
}
}
void Shader::addShaderParameter(ShaderParameter *shaderParameter) {
bool exists = false;
for (int i = 0; i < shaderParameters->size(); i++) {
if (shaderParameters->at(i)->parameterName == shaderParameter->parameterName) {
exists = true;
}
}
if (!exists) {
shaderParameters->emplace_back(shaderParameter);
}
}
void Shader::addShaderParameter(std::string paramName, ParameterType paramType, void *value) {
bool exists = false;
for (int i = 0; i < shaderParameters->size(); i++) {
if (shaderParameters->at(i)->parameterName == paramName) {
exists = true;
}
}
if (!exists) {
shaderParameters->push_back(new ShaderParameter(paramName, paramType, value));
}
}
void Shader::removeShaderParameter(std::string parameterName) {
for (int i = 0; i < shaderParameters->size(); i++) {
if (shaderParameters->at(i)->parameterName == parameterName) {
ShaderParameter *shaderParameter = shaderParameters->at(i);
shaderParameters->erase(shaderParameters->begin() + i);
delete shaderParameter;
return;
}
}
}
ShaderParameter *Shader::getShaderParameter(std::string parameterName) {
for (int i = 0; i < shaderParameters->size(); i++) {
if (shaderParameters->at(i)->parameterName == parameterName) {
return shaderParameters->at(i);
}
}
return nullptr;
}
Shader *Shader::getOrCreate(int name, const std::string &vertexFilename, const std::string &fragFilename,
bool preLoad) {
if (ResourcesManager::resourceExists(name)) {
return (Shader*) ResourcesManager::getResource(name);
} else {
Shader *newShader = new Shader(name, vertexFilename, fragFilename);
ResourcesManager::addResource(newShader, preLoad);
return newShader;
}
}
bool Shader::operator==(Shader &other) {
if (&other)
return this->program == other.program;
return false;
}
bool Shader::operator!=(Shader &other) {
return !(*this == other);
} | 38.923077 | 112 | 0.631862 | roooodcastro |
dd9200c61d8c4cd4db529e1a3b741d54afd1f909 | 434 | cpp | C++ | IpcDelegate/DelegateWCaller.cpp | antonplakhotnyk/ipcdelegates | 0fc30118747596035fd13bf1dd55fa8c61fd1ad5 | [
"MIT"
] | 1 | 2021-09-18T12:34:01.000Z | 2021-09-18T12:34:01.000Z | IpcDelegate/DelegateWCaller.cpp | antonplakhotnyk/ipcdelegates | 0fc30118747596035fd13bf1dd55fa8c61fd1ad5 | [
"MIT"
] | null | null | null | IpcDelegate/DelegateWCaller.cpp | antonplakhotnyk/ipcdelegates | 0fc30118747596035fd13bf1dd55fa8c61fd1ad5 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "DelegateWCaller.h"
ThreadLocalStoregePtr<DelegateWCaller> DelegateWCaller::s_instance;
DelegateWCaller::DelegateWCaller()
{
return_if_not_equal(s_instance, NULL);
s_instance = this;
}
DelegateWCaller::~DelegateWCaller()
{
return_if_not_equal(s_instance, this);
s_instance = NULL;
}
DelegateWCaller* DelegateWCaller::GetDefault()
{
return_x_if_equal(s_instance,NULL,NULL);
return s_instance;
}
| 18.083333 | 67 | 0.790323 | antonplakhotnyk |
dd94e0f533379c1640c090d79c994a102bb4e0f2 | 19,460 | cpp | C++ | src/Test/inversionTest/inversionTest.cpp | pwang234/lsms | 6044153b6138512093e457bdc0c15c699c831778 | [
"BSD-3-Clause"
] | 16 | 2018-04-03T15:35:47.000Z | 2022-03-01T03:19:23.000Z | src/Test/inversionTest/inversionTest.cpp | pwang234/lsms | 6044153b6138512093e457bdc0c15c699c831778 | [
"BSD-3-Clause"
] | 8 | 2019-07-30T13:59:18.000Z | 2022-03-31T17:43:35.000Z | src/Test/inversionTest/inversionTest.cpp | pwang234/lsms | 6044153b6138512093e457bdc0c15c699c831778 | [
"BSD-3-Clause"
] | 9 | 2018-06-30T00:30:48.000Z | 2022-01-31T09:14:29.000Z | /* -*- c-file-style: "bsd"; c-basic-offset: 2; indent-tabs-mode: nil -*- */
// test the inverion algorithm for multiple scattering codes for the solution of
// tau = (1 - tG)^-1 t
// where t is a block diagonal matrix
// note that the diagonal blocks G_ii == 0
#include <stdio.h>
#include "Complex.hpp"
#include "Matrix.hpp"
#include <vector>
#include <chrono>
#include <ctime>
#ifdef ARCH_CUDA
#include "inversionTest_cuda.hpp"
#endif
extern "C"
{
void block_inv_(Complex *a, Complex *vecs, int *lda, int *na, int *mp, int *ipvt, int *blk_sz, int *nblk, Complex *delta,
int *iwork, double *rwork, Complex *work1, int *alg,
int *idcol, int *iprint);
}
// #include "makegij_new.cpp"
void usage(const char *name)
{
printf("usage: %s <matrix type> [options]\n",name);
printf(" matrix type: 1: 1-tG and G, t Hilbert matrices, options: <block size> <num blocks>\n");
printf(" 2: 1-tG and G = -1, t = 1\n");
}
template <typename T>
void zeroMatrix(Matrix<T> &m)
{
for(int i=0; i<m.n_row(); i++)
for(int j=0; j<m.n_col(); j++)
m(i,j) = 0.0;
}
template <typename T>
void unitMatrix(Matrix<T> &m)
{
for(int i=0; i<m.n_row(); i++)
{
for(int j=0;j<m.n_col(); j++)
m(i,j) = 0.0;
m(i,i) = 1.0;
}
}
Real matrixDistance(Matrix<Complex> &a, Matrix<Complex> &b)
{
Real d=0.0;
for(int i=0; i<a.n_col(); i++)
for(int j=0; j<a.n_row(); j++)
d += ((a(i,j)-b(i,j)) * std::conj(a(i,j)-b(i,j))).real();
return std::sqrt(d);
}
void writeMatrix(Matrix<Complex> &a)
{
for(int i=0; i<a.n_col(); i++)
for(int j=0; j<a.n_row(); j++)
printf("%d %d %f %f\n",i,j,a(i,j).real(), a(i,j).imag());
}
void writeMatrixDifference(Matrix<Complex> &a, Matrix<Complex> &b)
{
for(int i=0; i<a.n_col(); i++)
for(int j=0; j<a.n_row(); j++)
{
if(a(i,j) != b(i,j))
{
printf("(%d,%d): (%f, %f) != (%f, %f)\n", i,j,
a(i,j).real(), a(i,j).imag(), b(i,j).real(), b(i,j).imag());
}
}
}
template <typename T>
void makeHilbertMatrix(Matrix<T> &m)
{
for(int i=0; i<m.n_row(); i++)
for(int j=0; j<m.n_col(); j++)
m(i,j) = 1.0/(Complex(i+j+1));
}
template <typename T>
void zeroDiagonalBlocks(Matrix<T> &m, int blockSize)
{
int n=m.n_row();
for(int iBlock=0; iBlock<n/blockSize; iBlock++)
for(int jBlock=0; jBlock<n/blockSize; jBlock++)
{
int ii=iBlock*blockSize;
int jj=jBlock*blockSize;
for(int i=0; i<std::min(blockSize, n-ii); i++)
for(int j=0; j<std::min(blockSize, n-jj); j++)
m(ii+i, jj+j) = 0.0;
}
}
// type 1 matrix:
//
void makeType1Matrix(Matrix<Complex> &m, Matrix<Complex> &G0, std::vector<Matrix<Complex> > &tMatrices, int blockSize, int numBlocks)
{
int n = m.n_row();
Complex mone = -1.0;
Complex zero = 0.0;
// unitMatrix(m);
// loop over the blocks to build -tG
// m_ij <- t_i G_ij
for(int iBlock=0; iBlock<numBlocks; iBlock++)
for(int jBlock=0; jBlock<numBlocks; jBlock++)
{
// ZGEMM(TRANSA,TRANSB,M,N,K,ALPHA, A,LDA, B,LDB, BETA,C,LDC)
// C := alpha*op( A )*op( B ) + beta*C,
BLAS::zgemm_("N","N",&blockSize,&blockSize,&blockSize,&mone,
&tMatrices[iBlock](0,0), &blockSize,
&G0(iBlock*blockSize,jBlock*blockSize), &n,
&zero, &m(iBlock*blockSize,jBlock*blockSize), &n);
}
// add unit matrix
for(int i=0; i<m.n_row(); i++)
m(i,i) = 1.0 + m(i,i);
}
// given the m-Matrix [(blockSize*numBlocks) x (blockSize*numBlocks)] and tMatrix[0] [blockSize x blockSize]
// calculate the t00-Matrix ast the blockSize x blockSize diagonal block of (1 - tG)^-1 t
void solveTau00Reference(Matrix<Complex> &tau00, Matrix<Complex> &m, std::vector<Matrix<Complex> > &tMatrices, int blockSize, int numBlocks)
{
// reference algorithm. Use LU factorization and linear solve for dense matrices in LAPACK
Matrix<Complex> tau(blockSize * numBlocks, blockSize);
zeroMatrix(tau);
// copy t[0] into the top part of tau
for(int i=0; i<blockSize; i++)
for(int j=0; j<blockSize; j++)
tau(i,j) = tMatrices[0](i,j);
int n = blockSize * numBlocks;
int ipiv[n];
int info;
LAPACK::zgesv_(&n, &blockSize, &m(0,0), &n, ipiv, &tau(0,0), &n, &info);
// copy result into tau00
for(int i=0; i<blockSize; i++)
for(int j=0; j<blockSize; j++)
tau00(i,j) = tau(i,j);
}
void solveTau00zgetrf(Matrix<Complex> &tau00, Matrix<Complex> &m, std::vector<Matrix<Complex> > &tMatrices, int blockSize, int numBlocks)
{
// reference algorithm. Use LU factorization and linear solve for dense matrices in LAPACK
Matrix<Complex> tau(blockSize * numBlocks, blockSize);
zeroMatrix(tau);
// copy t[0] into the top part of t
for(int i=0; i<blockSize; i++)
for(int j=0; j<blockSize; j++)
tau(i,j) = tMatrices[0](i,j);
int n = blockSize * numBlocks;
int ipiv[n];
Matrix<Complex> work(n,blockSize);
std::vector<std::complex<float> > swork(n*(n+blockSize));
std::vector<double> rwork(n);
int info, iter;
LAPACK::zgetrf_(&n, &n, &m(0,0), &n, &ipiv[0], &info);
LAPACK::zgetrs_("N", &n, &blockSize, &m(0,0), &n, &ipiv[0], &tau(0,0), &n, &info);
// copy result into tau00
for(int i=0; i<blockSize; i++)
for(int j=0; j<blockSize; j++)
tau00(i,j) = tau(i,j);
}
#ifndef ARCH_IBM
void solveTau00zcgesv(Matrix<Complex> &tau00, Matrix<Complex> &m, std::vector<Matrix<Complex> > &tMatrices, int blockSize, int numBlocks)
{
// reference algorithm. Use LU factorization and linear solve for dense matrices in LAPACK
Matrix<Complex> tau(blockSize * numBlocks, blockSize);
Matrix<Complex> t(blockSize * numBlocks, blockSize);
zeroMatrix(tau);
zeroMatrix(t);
// copy t[0] into the top part of t
for(int i=0; i<blockSize; i++)
for(int j=0; j<blockSize; j++)
t(i,j) = tMatrices[0](i,j);
int n = blockSize * numBlocks;
int ipiv[n];
Matrix<Complex> work(n,blockSize);
std::vector<std::complex<float> > swork(n*(n+blockSize));
std::vector<double> rwork(n);
int info, iter;
LAPACK::zcgesv_(&n, &blockSize, &m(0,0), &n, ipiv, &t(0,0), &n, &tau(0,0), &n,
&work(0,0), &swork[0], &rwork[0],
&iter, &info);
// copy result into tau00
for(int i=0; i<blockSize; i++)
for(int j=0; j<blockSize; j++)
tau00(i,j) = tau(i,j);
}
#endif
void solveTau00zblocklu(Matrix<Complex> &tau00, Matrix<Complex> &m, std::vector<Matrix<Complex> > &tMatrices, int blockSize, int numBlocks)
{
int nrmat_ns = blockSize * numBlocks;
int ipvt[nrmat_ns];
int info;
int alg = 2, iprint = 0;
Complex vecs[42]; // dummy, not used for alg=2
int nblk = 3;
Matrix<Complex> delta(blockSize, blockSize);
int iwork[nrmat_ns];
Real rwork[nrmat_ns];
Complex work1[nrmat_ns];
int blk_sz[1000];
blk_sz[0]=blockSize;
if(nblk==1)
blk_sz[0]=nrmat_ns;
else if(nblk==2)
blk_sz[1]=nrmat_ns-blk_sz[0];
else if(nblk>2)
{
int min_sz=(nrmat_ns-blk_sz[0])/(nblk-1);
int rem=(nrmat_ns-blk_sz[0])%(nblk-1);
int i=1;
for(;i<=rem;i++)
blk_sz[i]=min_sz+1;
for(;i<nblk;i++)
blk_sz[i]=min_sz;
}
int idcol[blk_sz[0]]; idcol[0]=0;
// with m = [[A B][C D]], A: blk_sz[0] x blk_sz[0]
// calculate the Schur complement m/D of m with A set to zero,
// i.e. delta = B D^-1 C
block_inv_(&m(0,0), vecs, &nrmat_ns, &nrmat_ns, &nrmat_ns, ipvt,
blk_sz, &nblk, &delta(0,0),
iwork, rwork, work1, &alg, idcol, &iprint);
Matrix<Complex> wbig(blockSize, blockSize);
// setup unit matrix...............................................
// n.b. this is the top diagonal block of the kkr matrix m
// i.e. 1 - t_0 G_00, with G_ii == 0 this is just the unit matrix
unitMatrix(wbig);
// c get 1-delta and put it in wbig
for(int i=0; i<blockSize; i++)
for(int j=0; j<blockSize; j++)
wbig(i,j) -= delta(i,j);
// c ================================================================
// c create tau00 => {[1-t*G]**(-1)}*t : for central site only.......
// c ----------------------------------------------------------------
LAPACK::zgetrf_(&blockSize, &blockSize, &wbig(0,0), &blockSize, ipvt, &info);
for(int i=0; i<blockSize; i++)
for(int j=0; j<blockSize; j++)
tau00(i,j) = tMatrices[0](i,j);
LAPACK::zgetrs_("N", &blockSize, &blockSize, &wbig(0,0), &blockSize, ipvt, &tau00(0,0), &blockSize, &info);
}
void block_inverse(Matrix<Complex> &a, int *blk_sz, int nblk, Matrix<Complex> &delta, int *ipvt, int *idcol);
void solveTau00zblocklu_cpp(Matrix<Complex> &tau00, Matrix<Complex> &m, std::vector<Matrix<Complex> > &tMatrices, int blockSize, int numBlocks)
{
int nrmat_ns = blockSize * numBlocks;
int ipvt[nrmat_ns];
int info;
int nblk = 3;
Matrix<Complex> delta(blockSize, blockSize);
int blk_sz[1000];
blk_sz[0]=blockSize;
if(nblk==1)
blk_sz[0]=nrmat_ns;
else if(nblk==2)
blk_sz[1]=nrmat_ns-blk_sz[0];
else if(nblk>2)
{
int min_sz=(nrmat_ns-blk_sz[0])/(nblk-1);
int rem=(nrmat_ns-blk_sz[0])%(nblk-1);
int i=1;
for(;i<=rem;i++)
blk_sz[i]=min_sz+1;
for(;i<nblk;i++)
blk_sz[i]=min_sz;
}
int idcol[blk_sz[0]]; idcol[0]=0;
// with m = [[A B][C D]], A: blk_sz[0] x blk_sz[0]
// calculate the Schur complement m/D of m with A set to zero,
// i.e. delta = B D^-1 C
block_inverse(m, blk_sz, nblk, delta, ipvt, idcol);
Matrix<Complex> wbig(blockSize, blockSize);
// setup unit matrix...............................................
// n.b. this is the top diagonal block of the kkr matrix m
// i.e. 1 - t_0 G_00, with G_ii == 0 this is just the unit matrix
unitMatrix(wbig);
// c get 1-delta and put it in wbig
for(int i=0; i<blockSize; i++)
for(int j=0; j<blockSize; j++)
wbig(i,j) -= delta(i,j);
// c ================================================================
// c create tau00 => {[1-t*G]**(-1)}*t : for central site only.......
// c ----------------------------------------------------------------
LAPACK::zgetrf_(&blockSize, &blockSize, &wbig(0,0), &blockSize, ipvt, &info);
for(int i=0; i<blockSize; i++)
for(int j=0; j<blockSize; j++)
tau00(i,j) = tMatrices[0](i,j);
LAPACK::zgetrs_("N", &blockSize, &blockSize, &wbig(0,0), &blockSize, ipvt, &tau00(0,0), &blockSize, &info);
}
int main(int argc, char *argv[])
{
int matrixType, blockSize=18, numBlocks=113;
bool printMatrices=false;
#ifdef ARCH_CUDA
DeviceHandles deviceHandles;
initCuda(deviceHandles);
#endif
printf("Test of inversion routine for LSMS\n");
if(argc<2)
{
usage(argv[0]);
return 0;
}
matrixType = atoi(argv[1]);
if(argc>2)
{
blockSize = atoi(argv[2]);
}
if(argc>3)
{
numBlocks = atoi(argv[3]);
}
int n = blockSize*numBlocks;
printf("Matrix type : %6d\n",matrixType);
printf("Block Size : %6d\n",blockSize);
printf("Number of Blocks : %6d\n",numBlocks);
printf("Total Matrix Size: %6d\n",n);
std::vector<Matrix<Complex> > tMatrices;
Matrix<Complex> G0(n, n);
tMatrices.resize(numBlocks);
#ifdef ARCH_CUDA
DeviceData devData;
allocDeviceData(deviceHandles, devData, blockSize, numBlocks);
#endif
if(matrixType == 1)
{
for(int i=0; i<numBlocks; i++)
{
tMatrices[i].resize(blockSize, blockSize);
makeHilbertMatrix<Complex>(tMatrices[i]);
}
makeHilbertMatrix<Complex>(G0);
zeroDiagonalBlocks(G0, blockSize);
} else if(matrixType == 2) {
for(int i=0; i<numBlocks; i++)
{
tMatrices[i].resize(blockSize, blockSize);
unitMatrix<Complex>(tMatrices[i]);
}
zeroMatrix<Complex>(G0);
} else {
for(int i=0; i<numBlocks; i++)
{
tMatrices[i].resize(blockSize, blockSize);
unitMatrix<Complex>(tMatrices[i]);
}
zeroMatrix(G0);
}
Matrix<Complex> m(n, n);
Matrix<Complex> tau00(blockSize, blockSize);
makeType1Matrix(m, G0, tMatrices, blockSize, numBlocks);
Matrix<Complex> tau00Reference(blockSize, blockSize);
auto startTimeReference = std::chrono::system_clock::now();
solveTau00Reference(tau00Reference, m, tMatrices, blockSize, numBlocks);
auto endTimeReference = std::chrono::system_clock::now();
std::chrono::duration<double> timeReference = endTimeReference - startTimeReference;
makeType1Matrix(m, G0, tMatrices, blockSize, numBlocks);
Matrix<Complex> tau00zgetrf(blockSize, blockSize);
auto startTimeZgetrf = std::chrono::system_clock::now();
solveTau00zgetrf(tau00zgetrf, m, tMatrices, blockSize, numBlocks);
auto endTimeZgetrf = std::chrono::system_clock::now();
std::chrono::duration<double> timeZgetrf = endTimeZgetrf - startTimeZgetrf;
makeType1Matrix(m, G0, tMatrices, blockSize, numBlocks);
Matrix<Complex> tau00zblocklu(blockSize, blockSize);
auto startTimeZblocklu = std::chrono::system_clock::now();
solveTau00zblocklu(tau00zblocklu, m, tMatrices, blockSize, numBlocks);
auto endTimeZblocklu = std::chrono::system_clock::now();
std::chrono::duration<double> timeZblocklu = endTimeZblocklu - startTimeZblocklu;
makeType1Matrix(m, G0, tMatrices, blockSize, numBlocks);
Matrix<Complex> tau00zblocklu_cpp(blockSize, blockSize);
auto startTimeZblocklu_cpp = std::chrono::system_clock::now();
solveTau00zblocklu_cpp(tau00zblocklu_cpp, m, tMatrices, blockSize, numBlocks);
auto endTimeZblocklu_cpp = std::chrono::system_clock::now();
std::chrono::duration<double> timeZblocklu_cpp = endTimeZblocklu_cpp - startTimeZblocklu_cpp;
#ifndef ARCH_IBM
makeType1Matrix(m, G0, tMatrices, blockSize, numBlocks);
Matrix<Complex> tau00zcgesv(blockSize, blockSize);
auto startTimeZcgesv = std::chrono::system_clock::now();
solveTau00zcgesv(tau00zcgesv, m, tMatrices, blockSize, numBlocks);
auto endTimeZcgesv = std::chrono::system_clock::now();
std::chrono::duration<double> timeZcgesv = endTimeZcgesv - startTimeZcgesv;
#endif
Real d = matrixDistance(tau00Reference, tau00zblocklu);
printf("d2 (t00Reference, tau00zblocklu) = %g\n", d);
d = matrixDistance(tau00Reference, tau00zblocklu_cpp);
printf("d2 (t00Reference, tau00zblocklu_cpp) = %g\n", d);
#ifndef ARCH_IBM
d = matrixDistance(tau00Reference, tau00zcgesv);
printf("d2 (t00Reference, tau00zcgesv) = %g\n", d);
#endif
d = matrixDistance(tau00Reference, tau00zgetrf);
printf("d2 (t00Reference, tau00zgetrf) = %g\n", d);
printf("t(Reference) = %fsec\n",timeReference.count());
printf("t(zblocklu) = %fsec\n",timeZblocklu.count());
printf("t(zblocklu_cpp) = %fsec\n",timeZblocklu_cpp.count());
#ifndef ARCH_IBM
printf("t(zcgesv) = %fsec\n",timeZcgesv.count());
#endif
printf("t(zgetrf) = %fsec\n",timeZgetrf.count());
#ifdef ARCH_CUDA
printf("\nCUDA and cuBLAS:\n");
if(false)
{
makeType1Matrix(m, G0, tMatrices, blockSize, numBlocks);
Matrix<Complex> tau00zgetrf_cublas(blockSize, blockSize);
auto startTimeZgetrf_cublas_transfer = std::chrono::system_clock::now();
transferMatrixToGPU(devData.m, m);
transferMatrixToGPU(devData.tMatrices[0], tMatrices[0]);
auto startTimeZgetrf_cublas = std::chrono::system_clock::now();
solveTau00zgetrf_cublas(deviceHandles.cublasHandle, devData, tau00zgetrf_cublas, blockSize, numBlocks);
auto endTimeZgetrf_cublas = std::chrono::system_clock::now();
std::chrono::duration<double> timeZgetrf_cublas = endTimeZgetrf_cublas - startTimeZgetrf_cublas;
std::chrono::duration<double> timeZgetrf_cublas_transfer = endTimeZgetrf_cublas - startTimeZgetrf_cublas_transfer;
d = matrixDistance(tau00Reference, tau00zgetrf_cublas);
printf("d2 (t00Reference, tau00zgetrf_cublas) = %g\n", d);
printf("t(zgetrf_cublas) = %fsec [%fsec]\n",timeZgetrf_cublas.count(), timeZgetrf_cublas_transfer.count());
}
if(false)
{
makeType1Matrix(m, G0, tMatrices, blockSize, numBlocks);
Matrix<Complex> tau00zblocklu_cublas(blockSize, blockSize);
auto startTimeZblocklu_cublas_transfer = std::chrono::system_clock::now();
transferMatrixToGPU(devData.m, m);
transferMatrixToGPU(devData.tMatrices[0], tMatrices[0]);
auto startTimeZblocklu_cublas = std::chrono::system_clock::now();
solveTau00zblocklu_cublas(deviceHandles.cublasHandle, devData, tau00zblocklu_cublas, m, tMatrices, blockSize, numBlocks);
auto endTimeZblocklu_cublas = std::chrono::system_clock::now();
std::chrono::duration<double> timeZblocklu_cublas = endTimeZblocklu_cublas - startTimeZblocklu_cublas;
std::chrono::duration<double> timeZblocklu_cublas_transfer = endTimeZblocklu_cublas - startTimeZblocklu_cublas_transfer;
d = matrixDistance(tau00Reference, tau00zblocklu_cublas);
printf("d2 (t00Reference, tau00zblocklu_cublas) = %g\n", d);
printf("t(zblocklu_cublas) = %fsec [%fsec]\n",timeZblocklu_cublas.count(), timeZblocklu_cublas_transfer.count());
}
// Summit doesn't have cuda 10.2 yet
#ifndef ARCH_IBM
makeType1Matrix(m, G0, tMatrices, blockSize, numBlocks);
Matrix<Complex> tau00zzgesv_cusolver(blockSize, blockSize);
auto startTimeZzgesv_cusolver_transfer = std::chrono::system_clock::now();
transferMatrixToGPU(devData.m, m);
transferMatrixToGPU(devData.tMatrices[0], tMatrices[0]);
auto startTimeZzgesv_cusolver = std::chrono::system_clock::now();
solveTau00zzgesv_cusolver(deviceHandles, devData, tau00zzgesv_cusolver, m, tMatrices, blockSize,
numBlocks);
auto endTimeZzgesv_cusolver = std::chrono::system_clock::now();
std::chrono::duration<double> timeZzgesv_cusolver = endTimeZzgesv_cusolver -
startTimeZzgesv_cusolver;
std::chrono::duration<double> timeZzgesv_cusolver_transfer = endTimeZzgesv_cusolver -
startTimeZzgesv_cusolver_transfer;
d = matrixDistance(tau00Reference, tau00zzgesv_cusolver);
printf("d2 (t00Reference, tau00zzgesv_cusolver) = %g\n", d);
printf("t(zzgesv_cusolver) = %fsec [%fsec]\n",timeZzgesv_cusolver.count(),
timeZzgesv_cusolver_transfer.count());
#endif
makeType1Matrix(m, G0, tMatrices, blockSize, numBlocks);
Matrix<Complex> tau00zgetrf_cusolver(blockSize, blockSize);
auto startTimeZgetrf_cusolver_transfer = std::chrono::system_clock::now();
transferMatrixToGPU(devData.m, m);
transferMatrixToGPU(devData.tMatrices[0], tMatrices[0]);
auto startTimeZgetrf_cusolver = std::chrono::system_clock::now();
solveTau00zgetrf_cusolver(deviceHandles, devData,
tau00zgetrf_cusolver, blockSize, numBlocks);
auto endTimeZgetrf_cusolver = std::chrono::system_clock::now();
std::chrono::duration<double> timeZgetrf_cusolver = endTimeZgetrf_cusolver -
startTimeZgetrf_cusolver;
std::chrono::duration<double> timeZgetrf_cusolver_transfer = endTimeZgetrf_cusolver -
startTimeZgetrf_cusolver_transfer;
d = matrixDistance(tau00Reference, tau00zgetrf_cusolver);
printf("d2 (t00Reference, tau00zgetrf_cusolver) = %g\n", d);
printf("t(zgetrf_cusolver) = %fsec [%fsec]\n",timeZgetrf_cusolver.count(),
timeZgetrf_cusolver_transfer.count());
#endif
transferMatrixToGPU(devData.tMatrices[0], tMatrices[0]);
//transferTest(deviceHandles, devData, tau00zzgesv_cusolver,
// blockSize, numBlocks);
transferMatrixFromGPU(tau00, devData.tMatrices[0]);
printMatrices=true;
if(printMatrices)
{
// printf("\ntau00Reference:\n"); writeMatrix(tMatrices[0]); // writeMatrix(tau00Reference);
// printf("\ntau00zzgesv_cusolver:\n"); writeMatrix(tau00zzgesv_cusolver);
writeMatrixDifference(tau00Reference, tau00zgetrf_cusolver);
}
#ifdef ARCH_CUDA
freeDeviceData(devData);
finalizeCuda(deviceHandles);
#endif
return 0;
}
| 34.260563 | 143 | 0.657554 | pwang234 |
dd9775b14fb517b4787f3443b4dc09d7f7649b0c | 627 | cpp | C++ | 0300/30/334a.cpp | actium/cf | d7be128c3a9adb014a231a399f1c5f19e1ab2a38 | [
"Unlicense"
] | 1 | 2020-07-03T15:55:52.000Z | 2020-07-03T15:55:52.000Z | 0300/30/334a.cpp | actium/cf | d7be128c3a9adb014a231a399f1c5f19e1ab2a38 | [
"Unlicense"
] | null | null | null | 0300/30/334a.cpp | actium/cf | d7be128c3a9adb014a231a399f1c5f19e1ab2a38 | [
"Unlicense"
] | 3 | 2020-10-01T14:55:28.000Z | 2021-07-11T11:33:58.000Z | #include <iostream>
void solve(size_t n)
{
const size_t k = n * n; // number of candy bags
const size_t s = k * (k + 1) / 2; // total number of candies
const size_t m = s / n; // how many candies to give to a brother
for (size_t i = 0; i < n; ++i) {
const char* separator = "";
for (size_t j = 0; j < n / 2; ++j) {
std::cout << separator << k - n * i / 2 - j << ' ' << 1 + n * i / 2 + j;
separator = " ";
}
std::cout << '\n';
}
}
int main()
{
size_t n;
std::cin >> n;
solve(n);
return 0;
}
| 20.9 | 84 | 0.424242 | actium |
dd99e164394592e3eebd0d58569f6acee1ed53bd | 386 | cxx | C++ | src/emu/emu_frame.cxx | ascottix/tickle | de3b7df8a6e719b7682398ac689a7e439b40876f | [
"MIT"
] | 1 | 2021-05-31T21:09:50.000Z | 2021-05-31T21:09:50.000Z | src/emu/emu_frame.cxx | ascottix/tickle | de3b7df8a6e719b7682398ac689a7e439b40876f | [
"MIT"
] | null | null | null | src/emu/emu_frame.cxx | ascottix/tickle | de3b7df8a6e719b7682398ac689a7e439b40876f | [
"MIT"
] | null | null | null | /*
Tickle class library
Copyright (c) 2003,2004 Alessandro Scotti
*/
#include "emu_frame.h"
void TFrame::playForceFeedbackEffect( int player, TForceFeedbackEffect fx, unsigned param )
{
}
void TFrame::stopForceFeedbackEffect( int player )
{
}
void TFrame::setPlayerLight( int player, bool on )
{
}
void TFrame::incrementCoinCounter( int counter )
{
}
| 16.782609 | 92 | 0.69171 | ascottix |
dd9aca1571856fb2454e2a7b96281500aa1435d4 | 2,913 | hpp | C++ | include/wtf/controls/button.hpp | ahunter-eyelock/wtf | c232d89cdf9817c28c4c4937300caf117bcb6876 | [
"BSL-1.0"
] | 5 | 2017-05-25T03:41:18.000Z | 2021-06-05T14:04:30.000Z | include/wtf/controls/button.hpp | ahunter-eyelock/wtf | c232d89cdf9817c28c4c4937300caf117bcb6876 | [
"BSL-1.0"
] | null | null | null | include/wtf/controls/button.hpp | ahunter-eyelock/wtf | c232d89cdf9817c28c4c4937300caf117bcb6876 | [
"BSL-1.0"
] | 3 | 2021-03-18T20:40:27.000Z | 2021-04-02T11:46:25.000Z | /** @file
@copyright David Mott (c) 2016. Distributed under the Boost Software License Version 1.0. See LICENSE.md or http://boost.org/LICENSE_1_0.txt for details.
*/
#pragma once
#define DOXY_INHERIT_BUTTON_SUPER \
DOXY_INHERIT_WINDOW \
DOXY_INHERIT_HAS_TEXT \
DOXY_INHERIT_HAS_FONT \
DOXY_INHERIT_HAS_ENABLE \
DOXY_INHERIT_HAS_INVALIDATE \
DOXY_INHERIT_HAS_MOVE \
DOXY_INHERIT_HAS_STYLE \
DOXY_INHERIT_WM_COMMAND
namespace wtf {
namespace controls {
/** @class button
@brief A standard clickable push style button.
@ingroup Controls
@image html button.png
*/
struct button : DOXY_INHERIT_BUTTON_SUPER window_impl<button,
policy::has_text,
policy::has_font,
policy::has_enable,
policy::has_invalidate,
policy::has_move,
policy::has_style,
messages::wm_command
> {
//! @brief Gets the ideal size of the control
size ideal_size() const {
size oRet;
wtf::exception::throw_lasterr_if(::SendMessage(*this, BCM_GETIDEALSIZE, 0, reinterpret_cast<LPARAM>(&oRet)), [](LRESULT l) { return !l; });
return oRet;
}
protected:
template <typename, template <typename> typename...> friend struct window_impl;
#if WTF_USE_COMMON_CONTROLS
static constexpr TCHAR sub_window_class_name[] = WC_BUTTON;
#else
static constexpr TCHAR sub_window_class_name[] = _T("BUTTON");
#endif
static constexpr TCHAR window_class_name[] = _T("wtf_button");
template <WNDPROC wp> using window_class_type = super_window_class<window_class_name, sub_window_class_name, wp>;
private:
void add(window &) override {}
};
/** @class checkbox
@brief A dual state (boolean) check box.
@ingroup Controls
@image html checkbox.png
*/
struct checkbox : button {
checkbox() {
window::_style |= BS_AUTOCHECKBOX;
}
};
/** @class radio_group
@brief A radio_button that starts a group.
@details Only a single radio_button in a radio_group may be selected at a time
@ingroup Controls
@image html radio_button.png
*/
struct radio_group : button {
radio_group() {
window::_style |= (BS_AUTORADIOBUTTON | WS_GROUP);
}
};
/** @class radio_button
@brief An element in a radio_group. Only a single item in a radio_group can be selected at one time
@ingroup Controls
@image html radio_button.png
*/
struct radio_button : button {
radio_button() {
window::_style |= BS_AUTORADIOBUTTON;
}
};
/** @class tristate
@brief A tri-state check box.
@details A tristate is similar to a checkbox. It has an on-off state like a checkbox plus a third greyed state.
@ingroup Controls
@image html tristate.png
*/
struct tristate : button {
tristate() {
window::_style |= BS_AUTO3STATE;
}
};
}
}
| 27.224299 | 153 | 0.665294 | ahunter-eyelock |
dda1cd7733e087861418bad1122ad4f836c97efa | 755 | cpp | C++ | examples/c++/tutorial/callback_from_javscript/hello_function_direct.cpp | Rabbid76/WasmExamples | 3290bd7ea44c4cd03688c2c1935f9b986a9c8e52 | [
"MIT"
] | null | null | null | examples/c++/tutorial/callback_from_javscript/hello_function_direct.cpp | Rabbid76/WasmExamples | 3290bd7ea44c4cd03688c2c1935f9b986a9c8e52 | [
"MIT"
] | null | null | null | examples/c++/tutorial/callback_from_javscript/hello_function_direct.cpp | Rabbid76/WasmExamples | 3290bd7ea44c4cd03688c2c1935f9b986a9c8e52 | [
"MIT"
] | null | null | null | // Copyright 2012 The Emscripten Authors. All rights reserved.
// Emscripten is available under two separate licenses, the MIT license and the
// University of Illinois/NCSA Open Source License. Both these licenses can be
// found in the LICENSE file.
// Call compiled C/C++ code “directly” from JavaScript
// https://emscripten.org/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html#call-compiled-c-c-code-directly-from-javascript
#include <cmath>
#include <iostream>
#include <emscripten.h>
EMSCRIPTEN_KEEPALIVE double calc_sqrt(double value) {
return std::sqrt(value);
}
EMSCRIPTEN_KEEPALIVE void output(const char *message) {
std::cout << message << std::endl;
}
int main() {
output("start ..\n");
return 0;
} | 31.458333 | 143 | 0.743046 | Rabbid76 |
dda431c0c96fbd2e81c5b5adec0628915b8cf3f5 | 3,380 | cpp | C++ | s32v234_sdk/libs/utils/communications/src/NameIterator.cpp | intesight/Panorama4AIWAYS | 46e1988e54a5155be3b3b47c486b3f722be00b5c | [
"WTFPL"
] | null | null | null | s32v234_sdk/libs/utils/communications/src/NameIterator.cpp | intesight/Panorama4AIWAYS | 46e1988e54a5155be3b3b47c486b3f722be00b5c | [
"WTFPL"
] | null | null | null | s32v234_sdk/libs/utils/communications/src/NameIterator.cpp | intesight/Panorama4AIWAYS | 46e1988e54a5155be3b3b47c486b3f722be00b5c | [
"WTFPL"
] | 2 | 2021-01-21T02:06:16.000Z | 2021-01-28T10:47:37.000Z | /******************************************************************************
* (C) Copyright CogniVue Corp. 2010 All right reserved.
* Confidential Information
*
* All parts of the CogniVue Corp. Program Source are protected by copyright law
* and all rights are reserved.
* This documentation may not, in whole or in part, be copied, photocopied,
* reproduced, translated, or reduced to any electronic medium or machine
* readable form without prior consent, in writing, from Cognivue.
******************************************************************************/
/* Information for doxygen */
/**
* \file <<FileName>>
* \brief <<One line Description>>
*
* <<Replace this with Multiline description. This should describe the
* file in general.>>
*/
/***************************************************************************/
/* Include files. */
#include "MessagingManagerTypesPriv.hpp"
#include "oal.h"
#include "global_errors.h"
#include <stdint.h>
/***************************************************************************/
/* Local Literals & definitions */
/***************************************************************************/
/* Externally defined global data */
/***************************************************************************/
/* Locally defined global data */
/***************************************************************************/
/**
* \par Constructor
*
* \warning
* \todo
* \bug
**************************************************************************/
NameIterator::NameIterator()
: mpNodeCurrent(0)
{
}
/***************************************************************************/
/**
* \par Destructor
*
* \warning
* \todo
* \bug
**************************************************************************/
NameIterator::~NameIterator()
{
}
/***************************************************************************/
/**
* \par Returns true if the iteration has more elements.
* In other words, returns true if Next() would return an element rather.
*
* \return true There is another element in the container
* \return false There is no more elements in the container
*
* \warning Only safe to call after Iterator has been initialized by container
* \todo
* \bug
**************************************************************************/
bool NameIterator::HasNext()
{
bool hasNext = false;
if(mpNodeCurrent != 0 &&
mpNodeCurrent->mpNodeNext != 0)
{
hasNext = true;
}
return hasNext;
}
/***************************************************************************/
/**
* \par Returns the next element in the iteration.
* Calling this method repeatedly until the HasNext() method returns false
* will return each element in the container exactly once.
*
* \return Name* Pointer to the next element in the container
*
* \warning Only safe to call if HasNext returned true
* \todo
* \bug
**************************************************************************/
Name* NameIterator::Next()
{
MSG_MGR_ERROR(mpNodeCurrent != 0 &&
mpNodeCurrent->mpNodeNext != 0);
mpNodeCurrent = mpNodeCurrent->mpNodeNext;
Name* pName = (Name*)(mpNodeCurrent);
return pName;
}
| 29.649123 | 83 | 0.436686 | intesight |
dda6f5df74e791e3f1331de50dc8a149f5de33eb | 16,233 | cpp | C++ | node_modules/lzz-gyp/lzz-source/gram_LexBlockToken.cpp | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | 3 | 2019-09-18T16:44:33.000Z | 2021-03-29T13:45:27.000Z | node_modules/lzz-gyp/lzz-source/gram_LexBlockToken.cpp | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | null | null | null | node_modules/lzz-gyp/lzz-source/gram_LexBlockToken.cpp | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | 2 | 2019-03-29T01:06:38.000Z | 2019-09-18T16:44:34.000Z | // gram_LexBlockToken.cpp
//
#include "gram_LexBlockToken.h"
// std lib
#include <cassert>
// gram
#include "gram_BlockTable.h"
#include "gram_CharBlock.h"
#include "gram_Lexer.h"
#include "gram_Message.h"
#include "gram_Prep.h"
#include "gram_TokenBlock.h"
#include "gram_TokenNumber.h"
// config
#include "conf_Config.h"
// util
#include "util_Exception.h"
#define LZZ_INLINE inline
namespace
{
using namespace gram;
}
namespace
{
struct LexBlock
{
Prep & prep;
virtual bool isEndToken (int number) = 0;
bool tokenLex (basl::Token & res_token);
bool charLex (basl::Token & res_token);
bool lex (basl::Token & res_token, bool charlex = false);
public:
explicit LexBlock (Prep & prep);
~ LexBlock ();
};
}
namespace
{
struct LexBlock1 : LexBlock
{
int expr_nest;
int tmpl_nest;
bool isEndToken (int number);
public:
explicit LexBlock1 (Prep & prep);
~ LexBlock1 ();
};
}
namespace
{
struct LexBlock2 : LexBlock
{
int lparen;
int rparen;
int expr_nest;
bool isEndToken (int number);
public:
explicit LexBlock2 (Prep & prep, int lparen = LPAREN_TOKEN, int rparen = RPAREN_TOKEN);
~ LexBlock2 ();
};
}
namespace
{
struct LexBlock5 : LexBlock2
{
public:
explicit LexBlock5 (Prep & prep);
~ LexBlock5 ();
};
}
namespace
{
struct LexBlock7 : LexBlock2
{
public:
explicit LexBlock7 (Prep & prep);
~ LexBlock7 ();
};
}
namespace
{
struct LexBlock4 : LexBlock
{
int expr_nest;
bool isEndToken (int number);
public:
explicit LexBlock4 (Prep & prep);
~ LexBlock4 ();
};
}
namespace
{
struct LexBlock3 : LexBlock
{
int brac_nest;
int expr_nest;
bool isEndToken (int number);
public:
explicit LexBlock3 (Prep & prep);
~ LexBlock3 ();
};
}
namespace
{
struct LexBlock8 : LexBlock
{
int gt;
int expr_nest;
bool isEndToken (int number);
public:
explicit LexBlock8 (Prep & prep, int gt = GT_TOKEN);
~ LexBlock8 ();
};
}
namespace
{
struct LexBlock9 : LexBlock8
{
public:
explicit LexBlock9 (Prep & prep);
~ LexBlock9 ();
};
}
namespace
{
struct LexBlock10 : LexBlock
{
bool isEndToken (int number);
public:
explicit LexBlock10 (Prep & prep);
~ LexBlock10 ();
};
}
namespace gram
{
bool lexBlockToken (Prep & prep, int lex_state, basl::Token & token)
{
bool found = false;
switch (lex_state)
{
// template args
case 1:
{
found = LexBlock1 (prep).lex (token);
break;
}
// parenthesized expr
case 2:
{
found = LexBlock2 (prep).lex (token);
break;
}
// copy and brace init expr
case 3:
{
found = LexBlock3 (prep).lex (token);
break;
}
// direct init expr or func default arg
case 4:
{
found = LexBlock4 (prep).lex (token);
break;
}
// array dimension
case 5:
{
found = LexBlock5 (prep).lex (token);
break;
}
// func body
case 7:
{
found = LexBlock7 (prep).lex (token);
break;
}
// tmpl param default arg
case 8:
{
found = LexBlock8 (prep).lex (token);
break;
}
// enumerator init
case 9:
{
found = LexBlock9 (prep).lex (token);
break;
}
// return stmt (in navigators)
case 10:
{
found = LexBlock10 (prep).lex (token);
break;
}
default:
{
assert (false);
}
}
return found;
}
}
namespace
{
bool LexBlock::tokenLex (basl::Token & res_token)
{
bool found = false;
// goto real mode
prep.setRealMode (true);
basl::Token next = prep.getNextToken ();
if (! isEndToken (next.getNumber ()))
{
util::Loc start_loc = next.getLoc ();
TokenBlock block (start_loc);
do
{
block.append (next);
next = prep.getNextToken ();
// watch out for EOT token
if (next.getNumber () == EOT)
{
if (prep.fromFile ())
{
msg::eofInCodeBlock (start_loc);
throw util::Exception ();
}
break;
}
}
while (! isEndToken (next.getNumber ()));
util::Ident lexeme = addBlock (block);
res_token = basl::Token (BLOCK_TOKEN, start_loc, lexeme);
found = true;
}
// need to unget the end token as it's not part of the block
prep.ungetToken (next);
// back to lzz mode
prep.setRealMode (false);
return found;
}
}
namespace
{
bool LexBlock::charLex (basl::Token & res_token)
{
using namespace util;
bool found = false;
basl::TokenDeque & token_set = prep.getPendingTokens ();
Lexer & lexer = prep.getLexer ();
Loc start_loc = token_set.empty () ? lexer.getLoc () : token_set.front ().getLoc ();
CharBlock block (start_loc);
bool found_end = false;
// first use tokens
if (! token_set.empty ())
{
while (! (token_set.empty () || found_end))
{
// check if terminating token
basl::Token const & token = token_set.front ();
if (isEndToken (token.getNumber ()))
{
found_end = true;
}
else
{
// otherwise append lexeme and pop token
block.append (' ');
block.append (token.getLexeme ().c_str ());
token_set.pop_front ();
// found something
found = true;
}
}
block.append (' ');
}
// read from lexer if block not found end
while (! found_end)
{
char ch;
// should not find end of file
if (! lexer.peekChar (ch))
{
// error if lexing from file
if (lexer.fromFile ())
{
msg::eofInCodeBlock (start_loc);
throw Exception ();
}
// otherwise lexing BLOCK so must have found end
found_end = true;
break;
}
// check if start of comment
char next_ch;
if (ch == '/' && lexer.peekChar (next_ch, 1) && (next_ch == '*' || next_ch == '/'))
{
// save start of comment loc
util::Loc loc = lexer.getLoc ();
// read and append '/'
lexer.readChar (ch);
block.append (ch);
// read and append second character
lexer.readChar (ch);
block.append (ch);
if (ch == '*')
{
// c-comment
for (;;)
{
// should not be end of file
if (! lexer.readChar (ch))
{
msg::eofInCComment (loc);
throw Exception ();
}
block.append (ch);
if (ch == '*' && lexer.peekChar (next_ch) && next_ch == '/')
{
// read and append '/'
lexer.readChar (ch);
block.append (ch);
break;
}
}
}
else
{
// cpp comment
do
{
lexer.readChar (ch);
block.append (ch);
}
while (ch != '\n');
}
}
// check if start of char literal
else if (ch == '\'')
{
// save start of literal
util::Loc loc = lexer.getLoc ();
// read and append quote
lexer.readChar (ch);
block.append (ch);
// next character must not be a quote
if (lexer.peekChar (ch) && ch == '\'')
{
msg::emptyLiteralChar (loc);
throw Exception ();
}
for (bool esc = false;;)
{
lexer.readChar (ch);
if (ch == '\n')
{
msg::newlineInLiteralChar (loc);
throw Exception ();
}
block.append (ch);
if (esc)
{
esc = false;
}
else if (ch == '\'')
{
break;
}
else if (ch == '\\')
{
esc = true;
}
}
// found something
found = true;
}
// check if start of string literal
else if (ch == '\"')
{
// save start of literal
util::Loc loc = lexer.getLoc ();
// read and append quote
lexer.readChar (ch);
block.append (ch);
for (bool esc = false;;)
{
lexer.readChar (ch);
if (ch == '\n')
{
msg::newlineInLiteralString (loc);
throw Exception ();
}
block.append (ch);
if (esc)
{
esc = false;
}
else if (ch == '\"')
{
break;
}
else if (ch == '\\')
{
esc = true;
}
}
// found something
found = true;
}
else
{
// check if special character
int number = 0;
switch (ch)
{
case '>':
case '<':
{
// make sure the token isn't left or right shift
if (lexer.peekChar (next_ch, 1) && next_ch == ch)
{
lexer.readChar (ch);
block.append (ch);
}
else
{
number = (ch == '<') ? LT_TOKEN : GT_TOKEN;
}
break;
}
case '(':
{
number = LPAREN_TOKEN;
break;
}
case ')':
{
number = RPAREN_TOKEN;
break;
}
case '[':
{
number = LBRACK_TOKEN;
break;
}
case ']':
{
number = RBRACK_TOKEN;
break;
}
case '{':
{
number = LBRACE_TOKEN;
break;
}
case '}':
{
number = RBRACE_TOKEN;
break;
}
case ';':
{
number = SEMI_TOKEN;
break;
}
case ',':
{
number = COMMA_TOKEN;
break;
}
}
if (number > 0 && isEndToken (number))
{
// found end of block
found_end = true;
}
else
{
// read and append char
lexer.readChar (ch);
block.append (ch);
// found something if ch not space or newline
if (! (ch == ' ' || ch == '\n'))
{
found = true;
}
}
}
}
if (found)
{
// free unused memory in block then add to table
block.freeze ();
util::Ident lexeme = addBlock (block);
res_token = basl::Token (BLOCK_TOKEN, start_loc, lexeme);
}
return found;
}
}
namespace
{
bool LexBlock::lex (basl::Token & res_token, bool charlex)
{
// are we preprocessing the block?
bool found = false;
if (! charlex && conf::getOptionValue (conf::opt_prep_block))
{
found = tokenLex (res_token);
}
else
{
found = charLex (res_token);
}
return found;
}
}
namespace
{
LZZ_INLINE LexBlock::LexBlock (Prep & prep)
: prep (prep)
{}
}
namespace
{
LexBlock::~ LexBlock ()
{}
}
namespace
{
bool LexBlock1::isEndToken (int number)
{
bool result = false;
if (tmpl_nest == 0 && expr_nest == 0 && number == GT_TOKEN)
{
result = true;
}
else if (number == LPAREN_TOKEN)
{
++ expr_nest;
}
else if (number == RPAREN_TOKEN)
{
-- expr_nest;
}
else if (expr_nest == 0)
{
if (number == LT_TOKEN)
{
++ tmpl_nest;
}
else if (number == GT_TOKEN)
{
-- tmpl_nest;
}
}
return result;
}
}
namespace
{
LZZ_INLINE LexBlock1::LexBlock1 (Prep & prep)
: LexBlock (prep), expr_nest (0), tmpl_nest (0)
{}
}
namespace
{
LexBlock1::~ LexBlock1 ()
{}
}
namespace
{
bool LexBlock2::isEndToken (int number)
{
bool result = false;
if (expr_nest == 0 && number == rparen)
{
result = true;
}
else if (number == lparen)
{
++ expr_nest;
}
else if (number == rparen)
{
-- expr_nest;
}
return result;
}
}
namespace
{
LZZ_INLINE LexBlock2::LexBlock2 (Prep & prep, int lparen, int rparen)
: LexBlock (prep), lparen (lparen), rparen (rparen), expr_nest (0)
{}
}
namespace
{
LexBlock2::~ LexBlock2 ()
{}
}
namespace
{
LZZ_INLINE LexBlock5::LexBlock5 (Prep & prep)
: LexBlock2 (prep, LBRACK_TOKEN, RBRACK_TOKEN)
{}
}
namespace
{
LexBlock5::~ LexBlock5 ()
{}
}
namespace
{
LZZ_INLINE LexBlock7::LexBlock7 (Prep & prep)
: LexBlock2 (prep, LBRACE_TOKEN, RBRACE_TOKEN)
{}
}
namespace
{
LexBlock7::~ LexBlock7 ()
{}
}
namespace
{
bool LexBlock4::isEndToken (int number)
{
bool result = false;
// in functor def arg may end with ';'
if (expr_nest == 0 && (number == RPAREN_TOKEN || number == COMMA_TOKEN || number == SEMI_TOKEN))
{
result = true;
}
else if (number == LPAREN_TOKEN)
{
++ expr_nest;
}
else if (number == RPAREN_TOKEN)
{
-- expr_nest;
}
return result;
}
}
namespace
{
LZZ_INLINE LexBlock4::LexBlock4 (Prep & prep)
: LexBlock (prep), expr_nest (0)
{}
}
namespace
{
LexBlock4::~ LexBlock4 ()
{}
}
namespace
{
bool LexBlock3::isEndToken (int number)
{
bool result = false;
if ((brac_nest == 0 && expr_nest == 0 && number == COMMA_TOKEN) || number == SEMI_TOKEN)
{
result = true;
}
else if (number == LBRACE_TOKEN)
{
++ brac_nest;
expr_nest = 0;
}
else if (number == RBRACE_TOKEN && brac_nest > 0)
{
-- brac_nest;
}
else if (brac_nest == 0)
{
if (number == LPAREN_TOKEN)
{
++ expr_nest;
}
else if (number == RPAREN_TOKEN && expr_nest > 0)
{
-- expr_nest;
}
}
return result;
}
}
namespace
{
LZZ_INLINE LexBlock3::LexBlock3 (Prep & prep)
: LexBlock (prep), brac_nest (0), expr_nest (0)
{}
}
namespace
{
LexBlock3::~ LexBlock3 ()
{}
}
namespace
{
bool LexBlock8::isEndToken (int number)
{
bool result = false;
if (expr_nest == 0 && (number == gt || number == COMMA_TOKEN))
{
result = true;
}
else if (number == LPAREN_TOKEN)
{
++ expr_nest;
}
else if (number == RPAREN_TOKEN && expr_nest > 0)
{
-- expr_nest;
}
return result;
}
}
namespace
{
LZZ_INLINE LexBlock8::LexBlock8 (Prep & prep, int gt)
: LexBlock (prep), gt (gt), expr_nest (0)
{}
}
namespace
{
LexBlock8::~ LexBlock8 ()
{}
}
namespace
{
LZZ_INLINE LexBlock9::LexBlock9 (Prep & prep)
: LexBlock8 (prep, RBRACE_TOKEN)
{}
}
namespace
{
LexBlock9::~ LexBlock9 ()
{}
}
namespace
{
bool LexBlock10::isEndToken (int number)
{
bool result = false;
// just capture until next semi
if (number == SEMI_TOKEN)
{
result = true;
}
return result;
}
}
namespace
{
LZZ_INLINE LexBlock10::LexBlock10 (Prep & prep)
: LexBlock (prep)
{}
}
namespace
{
LexBlock10::~ LexBlock10 ()
{}
}
#undef LZZ_INLINE
| 21.136719 | 102 | 0.468613 | SuperDizor |
dda824fc3f7aaabf17558567b32137f9bc919c72 | 10,876 | cpp | C++ | analyser/utility.cpp | jnmaloney/sc2-map-analyzer | b5adb13fb72a0f0a8c278241700791e7907ad4ad | [
"WTFPL"
] | 4 | 2015-11-14T17:17:30.000Z | 2020-05-13T05:51:12.000Z | analyser/utility.cpp | jnmaloney/sc2-map-analyzer | b5adb13fb72a0f0a8c278241700791e7907ad4ad | [
"WTFPL"
] | null | null | null | analyser/utility.cpp | jnmaloney/sc2-map-analyzer | b5adb13fb72a0f0a8c278241700791e7907ad4ad | [
"WTFPL"
] | 1 | 2020-05-13T05:53:54.000Z | 2020-05-13T05:53:54.000Z | #include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "outstreams.hpp"
#include "utility.hpp"
#include "sc2mapTypes.hpp"
const char* projectURL = "http://www.sc2mapster.com/assets/sc2-map-analyzer";
const char* adminEmail = "dimfish.mapper@gmail.com";
void removeChars( const char* chars, string* s )
{
string::size_type i = s->find_first_of( chars );
while( i != string::npos )
{
s->erase( i, 1 );
i = s->find_first_of( chars, i );
}
}
void replaceChars( const char* chars, const char* with, string* s )
{
string::size_type i = s->find_first_of( chars );
while( i != string::npos )
{
s->erase( i, 1 );
s->insert( i, with );
i = s->find_first_of( chars, i + strlen( with ) );
}
}
void makeLower( string* s )
{
string lowered;
for( int i = 0; i < s->size(); ++i )
{
char c = s->at( i );
if( isupper( c ) )
{
lowered.append( 1, tolower( c ) );
} else {
lowered.append( 1, c );
}
}
s->assign( lowered );
}
void trimLeadingSpaces( string* s )
{
while( s->length() > 0 && s->at( 0 ) == ' ' )
{
s->erase( 0, 1 );
}
}
void trimTrailingSpaces( string* s )
{
while( s->length() > 0 && s->at( s->length() - 1 ) == ' ' )
{
s->erase( s->length() - 1, 1 );
}
}
float xtof_helper( char c )
{
if( isdigit( c ) )
{
return (float) (c-48);
}
switch( c )
{
case 'a': case 'A': return 10.0f;
case 'b': case 'B': return 11.0f;
case 'c': case 'C': return 12.0f;
case 'd': case 'D': return 13.0f;
case 'e': case 'E': return 14.0f;
case 'f': case 'F': return 15.0f;
}
}
float xtof( char c1, char c0 )
{
if( !isxdigit( c1 ) ) { printError( "'%c' is not a hex digit.\n", c1 ); exit( -1 ); }
if( !isxdigit( c0 ) ) { printError( "'%c' is not a hex digit.\n", c0 ); exit( -1 ); }
float f = 16.0f*xtof_helper( c1 ) + xtof_helper( c0 );
return f / 255.0f;
}
void formatPath( string* s )
{
// paths should have
// replace all forward slashes with backslashes to
// ensure consistent path characters
size_t lookHere = 0;
size_t foundHere;
while( (foundHere = s->find( "/", lookHere ))
!= string::npos )
{
s->replace( foundHere, 1, "\\" );
lookHere = foundHere + 1;
}
// if the filename ends in a "\" we will interpret
// it as a directory, but the trailing slash wigs out the
// call to stat so trim any here
while( s->size() > 0 &&
s->at( s->size() - 1 ) == '\\' )
{
s->erase( s->size() - 1 );
}
}
float snapIfNearInt( float x )
{
// if a float is within 0.1 of an integer
// value, snap it to the integer
if( fabs( x - ceil( x ) ) < 0.1 )
{
return ceil( x );
}
if( fabs( x - floor( x ) ) < 0.1 )
{
return floor( x );
}
return x;
}
float p2pDistance( point* p1, point* p2 )
{
return sqrt( (p1->mx - p2->mx)*(p1->mx - p2->mx) +
(p1->my - p2->my)*(p1->my - p2->my) );
}
float alterSaturationComponent( float zeroToOne, float component ) {
float dGrey = component - 0.5f;
return zeroToOne*dGrey + 0.5f;
}
void alterSaturation( float zeroToOne, Color* c ) {
c->r = alterSaturationComponent( zeroToOne, c->r );
c->g = alterSaturationComponent( zeroToOne, c->g );
c->b = alterSaturationComponent( zeroToOne, c->b );
}
void mixWith( Color* changing, Color* mixer ) {
changing->r = 0.5f * (changing->r + mixer->r);
changing->g = 0.5f * (changing->g + mixer->g);
changing->b = 0.5f * (changing->b + mixer->b);
}
void gradient( float zeroToOne,
Color* c1,
Color* c2,
Color* c3,
Color* cOut )
{
// there are 2 gradients between 3 colors
float d = 2.0f * zeroToOne;
Color* low;
Color* high;
if( d < 0.0f ) {
// min out at low color
low = c1;
cOut->r = low->r;
cOut->g = low->g;
cOut->b = low->b;
return;
} else if( d < 1.0f ) {
low = c1;
high = c2;
} else if( d < 2.0f ) {
low = c2;
high = c3;
d -= 1.0f;
} else {
// max out at high color
high = c3;
cOut->r = high->r;
cOut->g = high->g;
cOut->b = high->b;
return;
}
// otherwise use 0.0 <= d <= 1.0 to calculate
// a gradient between the chosen low/high color
cOut->r = low->r + d*(high->r - low->r);
cOut->g = low->g + d*(high->g - low->g);
cOut->b = low->b + d*(high->b - low->b);
}
void gradient( float zeroToOne,
Color* c1,
Color* c2,
Color* c3,
Color* c4,
Color* cOut )
{
// there are 3 gradients between 4 colors
float d = 3.0f * zeroToOne;
Color* low;
Color* high;
if( d < 0.0f ) {
// min out at low color
low = c1;
cOut->r = low->r;
cOut->g = low->g;
cOut->b = low->b;
return;
} else if( d < 1.0f ) {
low = c1;
high = c2;
} else if( d < 2.0f ) {
low = c2;
high = c3;
d -= 1.0f;
} else if( d < 3.0f ) {
low = c3;
high = c4;
d -= 2.0f;
} else {
// max out at high color
high = c4;
cOut->r = high->r;
cOut->g = high->g;
cOut->b = high->b;
return;
}
// otherwise use 0.0 <= d <= 1.0 to calculate
// a gradient between the chosen low/high color
cOut->r = low->r + d*(high->r - low->r);
cOut->g = low->g + d*(high->g - low->g);
cOut->b = low->b + d*(high->b - low->b);
}
void gradient( float zeroToOne,
Color* c1,
Color* c2,
Color* c3,
Color* c4,
Color* c5,
Color* c6,
Color* c7,
Color* cOut )
{
// there are 6 gradients between 7 colors
float d = 6.0f * zeroToOne;
Color* low;
Color* high;
if( d < 0.0f ) {
// min out at low color
low = c1;
cOut->r = low->r;
cOut->g = low->g;
cOut->b = low->b;
return;
} else if( d < 1.0f ) {
low = c1;
high = c2;
} else if( d < 2.0f ) {
low = c2;
high = c3;
d -= 1.0f;
} else if( d < 3.0f ) {
low = c3;
high = c4;
d -= 2.0f;
} else if( d < 4.0f ) {
low = c4;
high = c5;
d -= 3.0f;
} else if( d < 5.0f ) {
low = c5;
high = c6;
d -= 4.0f;
} else if( d < 6.0f ) {
low = c6;
high = c7;
d -= 5.0f;
} else {
// max out at high color
high = c7;
cOut->r = high->r;
cOut->g = high->g;
cOut->b = high->b;
return;
}
// otherwise use 0.0 <= d <= 1.0 to calculate
// a gradient between the chosen low/high color
cOut->r = low->r + d*(high->r - low->r);
cOut->g = low->g + d*(high->g - low->g);
cOut->b = low->b + d*(high->b - low->b);
}
void gradient( float zeroToOne,
Color* c1,
Color* c2,
Color* c3,
Color* c4,
Color* c5,
Color* c6,
Color* c7,
Color* c8,
Color* c9,
Color* c10,
Color* c11,
Color* cOut )
{
// there are 10 gradients between 11 colors, using
// a non-uniform scale (because middle gradients
// are stretch across bigger portions of the map,
// generally
//
// 0 6 11 15 18 20 22 25 29 34 40
// * 6 * 5 * 4 * 3 * 2 * 2 * 3 * 4 * 5 * 6 *
// ^
// |
// 1st color
float d = 40.0f * zeroToOne;
Color* low;
Color* high;
if( d < 0.0f ) {
// min out at low color
low = c1;
cOut->r = low->r;
cOut->g = low->g;
cOut->b = low->b;
return;
} else if( d < 6.0f ) {
low = c1;
high = c2;
d = (d - 0.0f) / 6.0f;
} else if( d < 11.0f ) {
low = c2;
high = c3;
d = (d - 6.0f) / 5.0f;
} else if( d < 15.0f ) {
low = c3;
high = c4;
d = (d - 11.0f) / 4.0f;
} else if( d < 18.0f ) {
low = c4;
high = c5;
d = (d - 15.0f) / 3.0f;
} else if( d < 20.0f ) {
low = c5;
high = c6;
d = (d - 18.0f) / 2.0f;
} else if( d < 22.0f ) {
low = c6;
high = c7;
d = (d - 20.0f) / 2.0f;
} else if( d < 25.0f ) {
low = c7;
high = c8;
d = (d - 22.0f) / 3.0f;
} else if( d < 29.0f ) {
low = c8;
high = c9;
d = (d - 25.0f) / 4.0f;
} else if( d < 34.0f ) {
low = c9;
high = c10;
d = (d - 29.0f) / 5.0f;
} else if( d < 40.0f ) {
low = c10;
high = c11;
d = (d - 34.0f) / 6.0f;
} else {
// max out at high color
high = c11;
cOut->r = high->r;
cOut->g = high->g;
cOut->b = high->b;
return;
}
// otherwise use 0.0 <= d <= 1.0 to calculate
// a gradient between the chosen low/high color
cOut->r = low->r + d*(high->r - low->r);
cOut->g = low->g + d*(high->g - low->g);
cOut->b = low->b + d*(high->b - low->b);
}
void gradient( float zeroToOne,
int repeat,
Color* c1,
Color* c2,
Color* c3,
Color* cOut )
{
float r = 3.0f * (float) repeat;
// end up with 0 <= d <= 3
float d = fmodf( r * 2.0f * fabs( zeroToOne - 0.5f ), 3.0f );
Color* low;
Color* high;
if( d < 0.5f ) {
low = c1;
high = c2;
d = d + 0.5f;
} else if( d < 1.5f ) {
low = c2;
high = c3;
d = d - 0.5f;
} else if( d < 2.5f ) {
low = c3;
high = c1;
d = d - 1.5f;
} else { //if( d < 3.5f ) {
low = c1;
high = c2;
d = d - 2.5f;
}
// otherwise use 0.0 <= d <= 1.0 to calculate
// a gradient between the chosen low/high color
cOut->r = low->r + d*(high->r - low->r);
cOut->g = low->g + d*(high->g - low->g);
cOut->b = low->b + d*(high->b - low->b);
}
void gradientNoBlend( float zeroToOne,
int repeat,
Color* c1,
Color* c2,
Color* c3,
Color* cOut )
{
float r = 3.0f * (float) repeat;
// end up with 0 <= d <= 3
float d = fmodf( r * 2.0f * fabs( zeroToOne - 0.5f ), 3.0f );
if( d < 0.5f ) {
cOut->r = c1->r;
cOut->g = c1->g;
cOut->b = c1->b;
} else if( d < 1.5f ) {
cOut->r = c2->r;
cOut->g = c2->g;
cOut->b = c2->b;
} else if( d < 2.5f ) {
cOut->r = c3->r;
cOut->g = c3->g;
cOut->b = c3->b;
} else { //if( d < 3.5f ) {
cOut->r = c1->r;
cOut->g = c1->g;
cOut->b = c1->b;
}
}
| 20.482109 | 88 | 0.448602 | jnmaloney |
ddaba7911a963f31b5c6b3b0b30284bd93ffaa84 | 1,022 | cpp | C++ | CodeForces.367/C.cpp | JoaoBaptMG/CompetitiveProgrammingSolutions | 4ecd4e1568b1104a683ea59367defe5cd39a34e8 | [
"MIT"
] | null | null | null | CodeForces.367/C.cpp | JoaoBaptMG/CompetitiveProgrammingSolutions | 4ecd4e1568b1104a683ea59367defe5cd39a34e8 | [
"MIT"
] | null | null | null | CodeForces.367/C.cpp | JoaoBaptMG/CompetitiveProgrammingSolutions | 4ecd4e1568b1104a683ea59367defe5cd39a34e8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include <limits>
using namespace std;
#define MIN(a,b) ((a)<(b)?(a):(b))
constexpr size_t MAX = 1000000000000000000;
int main()
{
size_t n;
cin >> n;
vector<size_t> cs;
cs.resize(n);
for (auto &c : cs)
cin >> c;
vector<string> strs;
strs.resize(n);
vector<string> revs;
revs.reserve(n);
for (auto &str : strs)
{
cin >> str;
string rev{str.crbegin(), str.crend()};
revs.push_back(rev);
}
vector<size_t> astr, arev;
astr.resize(n);
arev.resize(n);
astr[0] = 0;
arev[0] = cs[0];
for (size_t i = 1; i < n; i++)
{
astr[i] = MAX;
if (revs[i-1] <= strs[i]) astr[i] = MIN(astr[i], arev[i-1]);
if (strs[i-1] <= strs[i]) astr[i] = MIN(astr[i], astr[i-1]);
arev[i] = MAX;
if (revs[i-1] <= revs[i]) arev[i] = MIN(arev[i], arev[i-1] + cs[i]);
if (strs[i-1] <= revs[i]) arev[i] = MIN(arev[i], astr[i-1] + cs[i]);
}
auto res = MIN(astr[n-1], arev[n-1]);
if (res == MAX) cout << "-1" << endl;
else cout << res << endl;
}
| 17.322034 | 70 | 0.55773 | JoaoBaptMG |
ddadda47e31887cbc89d0c3e9e5f286e0c408a59 | 1,030 | cpp | C++ | src/2D/Dot.cpp | htmlcsjs/funni-marching | 2a03d55abdd5f7915c6c26f7212edd9705095757 | [
"MIT"
] | null | null | null | src/2D/Dot.cpp | htmlcsjs/funni-marching | 2a03d55abdd5f7915c6c26f7212edd9705095757 | [
"MIT"
] | null | null | null | src/2D/Dot.cpp | htmlcsjs/funni-marching | 2a03d55abdd5f7915c6c26f7212edd9705095757 | [
"MIT"
] | null | null | null | #include <raylib.h>
#include "Dot.hpp"
using namespace helpers2D;
Dot::Dot(Vector2 gridPos, Color colour, float unitSize)
{
this->gridPos = gridPos;
this->colour = colour;
this->unitSize = unitSize;
this->setGridPos(gridPos);
}
Dot::Dot(int x, int y, Color colour, float unitSize)
{
this->gridPos = (Vector2){x, y};
this->colour = colour;
this->unitSize = unitSize;
this->setGridPos((Vector2){x, y});
}
Dot::~Dot()
{
}
void Dot::render()
{
DrawCircleV(realPos, 2, colour);
}
void Dot::setColour(Color colour)
{
this->colour = colour;
}
void Dot::setGridPos(Vector2 pos)
{
int halfScreenX = GetScreenWidth() / 2;
int halfScreenY = GetScreenHeight() / 2;
this->gridPos = pos;
this->realPos.x = (pos.x) * unitSize + halfScreenX;
this->realPos.y = (pos.y * -1) * unitSize + halfScreenY;
}
Vector2 Dot::getGridPos()
{
return gridPos;
}
void Dot::updateUnitSize(float unitSize)
{
this->unitSize = unitSize;
this->setGridPos(this->gridPos);
}
| 18.070175 | 60 | 0.636893 | htmlcsjs |
ddb89b6f4ad2377670c03416708b3d6bed3ddbc9 | 12,607 | cpp | C++ | imagecore/image/resizecrop.cpp | shahzadlone/vireo | 73e7176d0255a9506b009c9ab8cc532ecd86e98c | [
"MIT"
] | 890 | 2017-12-15T17:55:42.000Z | 2022-03-27T07:46:49.000Z | imagecore/image/resizecrop.cpp | shahzadlone/vireo | 73e7176d0255a9506b009c9ab8cc532ecd86e98c | [
"MIT"
] | 29 | 2017-12-16T21:49:08.000Z | 2021-09-08T23:04:10.000Z | imagecore/image/resizecrop.cpp | shahzadlone/vireo | 73e7176d0255a9506b009c9ab8cc532ecd86e98c | [
"MIT"
] | 88 | 2017-12-15T19:29:49.000Z | 2022-03-21T00:59:29.000Z | /*
* MIT License
*
* Copyright (c) 2017 Twitter
*
* 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 "imagecore/imagecore.h"
#include "imagecore/image/colorspace.h"
#include "imagecore/image/rgba.h"
#include "imagecore/utils/mathutils.h"
#include "imagecore/utils/securemath.h"
#include "imagecore/image/resizecrop.h"
#include "imagecore/image/yuv.h"
#include "imagecore/image/internal/filters.h"
namespace imagecore {
ResizeCropOperation::ResizeCropOperation()
{
m_FilteredImage[0] = NULL;
m_FilteredImage[1] = NULL;
m_CropRegion = NULL;
m_OutputWidth = 0;
m_OutputHeight = 0;
m_OutputMod = 1;
m_TargetWidth = 0;
m_TargetHeight = 0;
m_ResizeMode = kResizeMode_ExactCrop;
m_CropGravity = kGravityHeuristic;
m_ResizeQuality = kResizeQuality_High;
m_OutputColorModel = kColorModel_RGBX;
m_AllowUpsample = true;
m_AllowDownsample = true;
m_BackgroundFillColor = RGBA(255, 255, 255, 0);
}
ResizeCropOperation::~ResizeCropOperation()
{
for( unsigned int i = 0; i < 2; i++ ) {
if( m_FilteredImage[i] != NULL ) {
delete m_FilteredImage[i];
m_FilteredImage[i] = NULL;
}
}
if( m_CropRegion ) {
delete m_CropRegion;
m_CropRegion = NULL;
}
}
int ResizeCropOperation::performResizeCrop(Image*& resizedImage)
{
resizedImage = NULL;
if( m_ImageReader == NULL || m_OutputWidth == 0 || m_OutputHeight == 0 ) {
return IMAGECORE_INVALID_IMAGE_SIZE;
}
int ret = IMAGECORE_SUCCESS;
if( (ret = readHeader()) != IMAGECORE_SUCCESS ) {
return ret;
}
if( (ret = load()) != IMAGECORE_SUCCESS ) {
return ret;
}
if( (ret = fillBackground()) != IMAGECORE_SUCCESS ) {
return ret;
}
if( (ret = resize()) != IMAGECORE_SUCCESS ) {
return ret;
}
if( (ret = rotateCrop()) != IMAGECORE_SUCCESS ) {
return ret;
}
resizedImage = m_FilteredImage[m_WhichImage];
return IMAGECORE_SUCCESS;
}
int ResizeCropOperation::performResizeCrop(ImageRGBA*& resizedImage)
{
Image* image = NULL;
if( performResizeCrop(image) == IMAGECORE_SUCCESS && image != NULL ) {
resizedImage = image->asRGBA();
if (resizedImage != NULL) {
return IMAGECORE_SUCCESS;
}
}
return IMAGECORE_UNKNOWN_ERROR;
}
static float calcScale(unsigned int orientedWidth, unsigned int orientedHeight, unsigned int desiredWidth, unsigned int desiredHeight, bool fit, bool allowUpsample, bool allowDownsample)
{
float widthScale = (float)desiredWidth / (float)orientedWidth;
float heightScale = (float)desiredHeight / (float)orientedHeight;
float scale = fit ? fminf(widthScale, heightScale) : fmaxf(widthScale, heightScale);
if( !allowUpsample ) {
scale = fminf(scale, 1.0f);
}
if( !allowDownsample ) {
scale = fmaxf(scale, 1.0f);
}
return scale;
}
static void calcOutputSize(unsigned int orientedWidth, unsigned int orientedHeight, unsigned int desiredWidth, unsigned int desiredHeight, unsigned int& targetWidth, unsigned int& targetHeight, unsigned int& outputWidth, unsigned int& outputHeight, EResizeMode resizeMode, bool allowUpsample, bool allowDownsample, ImageRegion* cropRegion, unsigned int outputMod)
{
// If we have a crop region, we're attempting to scale the specified region to the output size.
unsigned sourceWidth = cropRegion != NULL ? cropRegion->width() : orientedWidth;
unsigned sourceHeight = cropRegion != NULL ? cropRegion->height() : orientedHeight;
float scale = calcScale(sourceWidth, sourceHeight, desiredWidth, desiredHeight, resizeMode == kResizeMode_AspectFit, allowUpsample, allowDownsample);
if( cropRegion != NULL ) {
// Adjust the crop region, since the actual crop occurs after scaling.
cropRegion->left(scale * (float)cropRegion->left());
cropRegion->top(scale * (float)cropRegion->top());
cropRegion->width(scale * (float)cropRegion->width());
cropRegion->height(scale * (float)cropRegion->height());
}
targetWidth = roundf(scale * orientedWidth);
targetHeight = roundf(scale * orientedHeight);
if( resizeMode == kResizeMode_ExactCrop ) {
// The final cropped output should match the desired aspect ratio.
float croppedScale = calcScale(desiredWidth, desiredHeight, targetWidth, targetHeight, true, false, true);
outputWidth = roundf(croppedScale * desiredWidth);
outputHeight = roundf(croppedScale * desiredHeight);
} else if( resizeMode == kResizeMode_Stretch ) {
outputWidth = desiredWidth;
outputHeight = desiredHeight;
targetWidth = desiredWidth;
targetHeight = desiredHeight;
} else {
outputWidth = targetWidth;
outputHeight = targetHeight;
}
if( outputMod != 1 ) {
outputWidth -= outputWidth % outputMod;
outputHeight -= outputHeight % outputMod;
}
}
void ResizeCropOperation::estimateOutputSize(unsigned int imageWidth, unsigned int imageHeight, unsigned int& outputWidth, unsigned int& outputHeight)
{
calcOutputSize(imageWidth, imageHeight, m_OutputWidth, m_OutputHeight, m_TargetWidth, m_TargetHeight, outputWidth, outputHeight, m_ResizeMode, m_AllowUpsample, m_AllowDownsample, m_CropRegion, m_OutputMod);
}
int ResizeCropOperation::readHeader()
{
// Read the image header.
m_InputWidth = m_ImageReader->getWidth();
m_InputHeight = m_ImageReader->getHeight();
m_TargetWidth = 0;
m_TargetHeight = 0;
if( !Image::validateSize(m_InputWidth, m_InputHeight) ) {
fprintf(stderr, "error: bad image dimensions\n");
return IMAGECORE_INVALID_IMAGE_SIZE;
}
m_Orientation = m_ImageReader->getOrientation();
unsigned int orientedWidth = m_ImageReader->getOrientedWidth();
unsigned int orientedHeight = m_ImageReader->getOrientedHeight();
calcOutputSize(orientedWidth, orientedHeight, m_OutputWidth, m_OutputHeight, m_TargetWidth, m_TargetHeight, m_OutputWidth, m_OutputHeight, m_ResizeMode, m_AllowUpsample, m_AllowDownsample, m_CropRegion, m_OutputMod);
if( m_Orientation == kImageOrientation_Left || m_Orientation == kImageOrientation_Right ) {
// Flip it back, we work on the image in the file orientation.
swap(m_TargetWidth, m_TargetHeight);
}
// Allow conversion between RGBA <-> RGBX, otherwise respect the output color model specified.
if( Image::colorModelIsRGBA(m_OutputColorModel) && Image::colorModelIsRGBA(m_ImageReader->getNativeColorModel()) ) {
m_OutputColorModel = m_ImageReader->getNativeColorModel();
}
return IMAGECORE_SUCCESS;
}
int ResizeCropOperation::load()
{
unsigned int reducedWidth;
unsigned int reducedHeight;
m_ImageReader->computeReadDimensions(m_TargetWidth, m_TargetHeight, reducedWidth, reducedHeight);
// Prepare the work buffers.
unsigned int padAmount = max(ImageRGBA::getDownsampleFilterKernelSize(m_ResizeQuality), ImageRGBA::getUpsampleFilterKernelSize(m_ResizeQuality));
unsigned int bufferWidth = max(reducedWidth, m_TargetWidth);
unsigned int bufferHeight = max(reducedHeight, m_TargetHeight);
unsigned int alignment = 16;
unsigned int padSize = max(padAmount, Image::colorModelIsYUV(m_OutputColorModel) ? 16U : 4U);
// Add an extra (alignment) rows to height, because we might rotate the image later, and need to have enough room on that axis for the row alignment.
unsigned int extraRows = m_ImageReader->getOrientedHeight() != m_ImageReader->getHeight() ? alignment * 2U : 0;
m_FilteredImage[0] = Image::create(m_OutputColorModel, bufferWidth, bufferHeight + extraRows, padSize, alignment);
if( m_FilteredImage[0] == NULL ) {
return IMAGECORE_OUT_OF_MEMORY;
}
// Since the second work buffer will be used to hold the resampled output, it doesn't need to be as large as the first.
m_FilteredImage[1] = Image::create(m_OutputColorModel, max(m_TargetWidth, (bufferWidth + 1) / 2), max(m_TargetHeight, (bufferHeight + 1) / 2) + extraRows, padSize, alignment);
if( m_FilteredImage[1] == NULL ) {
return IMAGECORE_OUT_OF_MEMORY;
}
m_WhichImage = 0;
START_CLOCK(decompress);
m_FilteredImage[m_WhichImage]->setDimensions(reducedWidth, reducedHeight);
bool result = m_ImageReader->readImage(m_FilteredImage[m_WhichImage]);
if (!result) {
fprintf(stderr, "error: unable to read source image\n");
}
END_CLOCK(decompress);
return (result ? IMAGECORE_SUCCESS : IMAGECORE_READ_ERROR);
}
int ResizeCropOperation::fillBackground()
{
if( m_FilteredImage[m_WhichImage]->getColorModel() == kColorModel_RGBA && m_BackgroundFillColor.a == 255 ) {
ImageRGBA* image = (ImageRGBA*)m_FilteredImage[m_WhichImage];
const float3 fillColor = ColorSpace::byteToFloat(RGBA(m_BackgroundFillColor.r,
m_BackgroundFillColor.g,
m_BackgroundFillColor.b));
const float3 linearFillColor = ColorSpace::srgbToLinear(fillColor);
unsigned int framePitch;
unsigned int width = image->getWidth();
unsigned int height = image->getHeight();
uint8_t* buffer = image->lockRect(width, height, framePitch);
for( unsigned int y = 0; y < height; y++ ) {
for( unsigned int x = 0; x < width; x++ ) {
RGBA* rgba = (RGBA*)(&buffer[y * framePitch + x * 4]);
if( rgba->a == 0 ) {
*rgba = ColorSpace::floatToByte(fillColor);
} else if( rgba->a < 255 ) {
float a = rgba->a / 255.0f;
const float3 currentColor = ColorSpace::srgbToLinear(ColorSpace::byteToFloat(*rgba));
*rgba = ColorSpace::floatToByte(ColorSpace::linearToSrgb(float3(a) * currentColor + float3(1-a) * linearFillColor));
}
}
}
image->unlockRect();
}
return IMAGECORE_SUCCESS;
}
int ResizeCropOperation::resize()
{
Image* inImage = m_FilteredImage[m_WhichImage];
Image* outImage = m_FilteredImage[m_WhichImage ^ 1];
// Do a fast iterative 2x2 reduce, equivalent in quality to the 'free' DCT downsampling done by the JPEG decoder,
// until the image is in the right range for the filter step. This done for input formats other than JPEG.
while( inImage->getWidth() / 2 >= m_TargetWidth && inImage->getHeight() / 2 >= m_TargetHeight ) {
START_CLOCK(reduce);
inImage->reduceHalf(outImage);
END_CLOCK(reduce);
m_WhichImage ^= 1;
inImage = m_FilteredImage[m_WhichImage];
outImage = m_FilteredImage[m_WhichImage ^ 1];
}
// If the reduce didn't happen to get us to the right size, do a final high-quality filter step.
if( inImage->getWidth() != m_TargetWidth || inImage->getHeight() != m_TargetHeight ) {
START_CLOCK(filter);
outImage->setDimensions(m_TargetWidth, m_TargetHeight);
if( !inImage->resize(outImage, m_ResizeQuality) ) {
return IMAGECORE_OUT_OF_MEMORY;
}
END_CLOCK(filter);
m_WhichImage ^= 1;
}
return IMAGECORE_SUCCESS;
}
int ResizeCropOperation::rotateCrop()
{
// Apply the EXIF rotation.
if( m_Orientation == kImageOrientation_Down || m_Orientation == kImageOrientation_Left || m_Orientation == kImageOrientation_Right ) {
START_CLOCK(orient);
switch( m_Orientation ) {
case kImageOrientation_Down:
m_FilteredImage[m_WhichImage]->rotate(m_FilteredImage[m_WhichImage ^ 1], kImageOrientation_Up);
break;
case kImageOrientation_Left:
m_FilteredImage[m_WhichImage]->rotate(m_FilteredImage[m_WhichImage ^ 1], kImageOrientation_Right);
break;
case kImageOrientation_Right:
m_FilteredImage[m_WhichImage]->rotate(m_FilteredImage[m_WhichImage ^ 1], kImageOrientation_Left);
break;
}
m_WhichImage ^= 1;
END_CLOCK(orient);
}
if( m_CropRegion != NULL ) {
m_FilteredImage[m_WhichImage]->crop(*m_CropRegion);
}
if( m_ResizeMode == kResizeMode_ExactCrop ) {
ImageRegion* bound = ImageRegion::fromGravity(
m_FilteredImage[m_WhichImage]->getWidth(),
m_FilteredImage[m_WhichImage]->getHeight(),
m_OutputWidth,
m_OutputHeight,
m_CropGravity);
ASSERT(bound != NULL);
m_FilteredImage[m_WhichImage]->crop(*bound);
delete bound;
}
return IMAGECORE_SUCCESS;
}
}
| 37.858859 | 363 | 0.742524 | shahzadlone |
ddbb58fbfc32beb830ce5c4cbb001b584f7e6ebc | 668 | hpp | C++ | engine/src/Graphics/GraphicsFeatureSkybox.hpp | aleksigron/graphics-toolkit | f8e60c57316a72dff9de07512e9771deb3799208 | [
"MIT"
] | null | null | null | engine/src/Graphics/GraphicsFeatureSkybox.hpp | aleksigron/graphics-toolkit | f8e60c57316a72dff9de07512e9771deb3799208 | [
"MIT"
] | null | null | null | engine/src/Graphics/GraphicsFeatureSkybox.hpp | aleksigron/graphics-toolkit | f8e60c57316a72dff9de07512e9771deb3799208 | [
"MIT"
] | null | null | null | #pragma once
#include "Graphics/GraphicsFeature.hpp"
#include "Resources/MeshId.hpp"
#include "Resources/ShaderId.hpp"
namespace kokko
{
class GraphicsFeatureSkybox : public GraphicsFeature
{
public:
GraphicsFeatureSkybox();
virtual void Initialize(const InitializeParameters& parameters) override;
virtual void Deinitialize(const InitializeParameters& parameters) override;
virtual void Upload(const UploadParameters& parameters) override;
virtual void Submit(const SubmitParameters& parameters) override;
virtual void Render(const RenderParameters& parameters) override;
private:
ShaderId shaderId;
MeshId meshId;
unsigned int uniformBufferId;
};
}
| 22.266667 | 76 | 0.811377 | aleksigron |
ddbd4223512edb5495185104243cf8654a1a8c6c | 1,619 | cpp | C++ | gym/index20_29/ioi2021_26/PE.cpp | daklqw/IOI2021-training | 4f21cef8eec47330e3db77a3d90cbe2309fa8294 | [
"Apache-2.0"
] | 6 | 2020-10-12T05:07:03.000Z | 2021-09-11T14:54:58.000Z | gym/index20_29/ioi2021_26/PE.cpp | daklqw/IOI2021-training | 4f21cef8eec47330e3db77a3d90cbe2309fa8294 | [
"Apache-2.0"
] | null | null | null | gym/index20_29/ioi2021_26/PE.cpp | daklqw/IOI2021-training | 4f21cef8eec47330e3db77a3d90cbe2309fa8294 | [
"Apache-2.0"
] | 2 | 2021-02-09T02:06:31.000Z | 2021-10-06T01:25:08.000Z | #include <bits/stdc++.h>
const int MAXN = 2e5 + 10;
typedef long long LL;
int head[MAXN], nxt[MAXN << 1], to[MAXN << 1], tot;
void adde(int b, int e) {
nxt[++tot] = head[b]; to[head[b] = tot] = e;
nxt[++tot] = head[e]; to[head[e] = tot] = b;
}
struct _ {
LL n, p;
bool operator < (_ b) const {
return n > b.n;
}
_ operator + (_ b) const {
return (_) {std::min(n, p + b.n), p + b.p};
}
} ;
LL A[MAXN];
int idx;
std::multiset<_> S[MAXN];
void reduce(int u, LL _v) {
_ v = (_) {std::min(_v, 0ll), _v};
while (!S[u].empty() && (!(v < *S[u].begin()) || v.p < 0)) {
v = v + *S[u].begin();
S[u].erase(S[u].begin());
}
if (S[u].empty() && v.p <= 0) return ;
S[u].insert(v);
}
int merge(int x, int y) {
if (!x || !y) return x | y;
if (S[x].size() > S[y].size()) std::swap(x, y);
for (auto t : S[x]) S[y].insert(t);
S[x].clear();
return y;
}
int dfs(int u, int fa) {
int r = 0;
for (int i = head[u]; i; i = nxt[i])
if (to[i] != fa)
r = merge(r, dfs(to[i], u));
if (!r) S[r = ++idx].clear();
reduce(r, A[u]);
return r;
}
int main() {
std::ios_base::sync_with_stdio(false), std::cin.tie(0);
int Q; std::cin >> Q;
while (Q --> 0) {
int n, T;
std::cin >> n >> T;
for (int i = 1; i <= n; ++i)
std::cin >> A[i];
for (int i = 1, x, y; i < n; ++i)
std::cin >> x >> y, adde(x, y);
adde(T, n + 1); A[n + 1] = 0x3f3f3f3f3f3f3f3fll;
int r = dfs(1, 0);
LL sm = 0;
for (auto t : S[r])
if (sm + t.n >= 0) sm += t.p;
else break;
if (sm > 1e15)
std::cout << "escaped\n";
else
std::cout << "trapped\n";
memset(head, 0, n + 2 << 2);
tot = 1; idx = 0;
}
return 0;
}
| 22.486111 | 61 | 0.489809 | daklqw |
ddc5df8417f0d66c102954748ec58a5a0d94cc94 | 8,406 | cc | C++ | libgearman-server/queue.cc | alionurdemetoglu/gearmand | dd9ac59a730f816e0dc5f27f98fdc06a08cc4c22 | [
"BSD-3-Clause"
] | 712 | 2016-07-02T03:32:22.000Z | 2022-03-23T14:23:02.000Z | libgearman-server/queue.cc | alionurdemetoglu/gearmand | dd9ac59a730f816e0dc5f27f98fdc06a08cc4c22 | [
"BSD-3-Clause"
] | 294 | 2016-07-03T16:17:41.000Z | 2022-03-30T04:37:49.000Z | libgearman-server/queue.cc | alionurdemetoglu/gearmand | dd9ac59a730f816e0dc5f27f98fdc06a08cc4c22 | [
"BSD-3-Clause"
] | 163 | 2016-07-08T10:03:38.000Z | 2022-01-21T05:03:48.000Z | /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Gearmand client and server library.
*
* Copyright (C) 2011 Data Differential, http://datadifferential.com/
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * 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.
*
* * The names of its contributors may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "gear_config.h"
#include <iostream>
#include <boost/program_options.hpp>
#include "libgearman-server/common.h"
#include <libgearman-server/queue.h>
#include <libgearman-server/plugins/queue/base.h>
#include <libgearman-server/queue.hpp>
#include <libgearman-server/log.h>
#include <assert.h>
gearmand_error_t gearman_queue_add(gearman_server_st *server,
const char *unique,
size_t unique_size,
const char *function_name,
size_t function_name_size,
const void *data,
size_t data_size,
gearman_job_priority_t priority,
int64_t when)
{
assert(server->state.queue_startup == false);
gearmand_error_t ret;
if (server->queue_version == QUEUE_VERSION_NONE)
{
return GEARMAND_SUCCESS;
}
else if (server->queue_version == QUEUE_VERSION_FUNCTION)
{
assert(server->queue.functions->_add_fn);
ret= (*(server->queue.functions->_add_fn))(server,
(void *)server->queue.functions->_context,
unique, unique_size,
function_name,
function_name_size,
data, data_size, priority,
when);
}
else
{
assert(server->queue.object);
ret= server->queue.object->store(server,
unique, unique_size,
function_name,
function_name_size,
data, data_size, priority,
when);
}
if (gearmand_success(ret))
{
ret= gearman_queue_flush(server);
}
return ret;
}
gearmand_error_t gearman_queue_flush(gearman_server_st *server)
{
if (server->queue_version != QUEUE_VERSION_NONE)
{
if (server->queue_version == QUEUE_VERSION_FUNCTION)
{
assert(server->queue.functions->_flush_fn);
return (*(server->queue.functions->_flush_fn))(server, (void *)server->queue.functions->_context);
}
assert(server->queue.object);
return server->queue.object->flush(server);
}
return GEARMAND_SUCCESS;
}
gearmand_error_t gearman_queue_done(gearman_server_st *server,
const char *unique,
size_t unique_size,
const char *function_name,
size_t function_name_size)
{
if (server->queue_version == QUEUE_VERSION_NONE)
{
return GEARMAND_SUCCESS;
}
else if (server->queue_version == QUEUE_VERSION_FUNCTION)
{
assert(server->queue.functions->_done_fn);
return (*(server->queue.functions->_done_fn))(server,
(void *)server->queue.functions->_context,
unique, unique_size,
function_name,
function_name_size);
}
else
{
assert(server->queue.object);
return server->queue.object->done(server,
unique, unique_size,
function_name,
function_name_size);
}
}
void gearman_server_save_job(gearman_server_st& server,
const gearman_server_job_st* server_job)
{
if (server.queue_version == QUEUE_VERSION_CLASS)
{
assert(server.queue.object);
server.queue.object->save_job(server, server_job);
}
}
void gearman_server_set_queue(gearman_server_st& server,
void *context,
gearman_queue_add_fn *add,
gearman_queue_flush_fn *flush,
gearman_queue_done_fn *done,
gearman_queue_replay_fn *replay)
{
delete server.queue.functions;
server.queue.functions= NULL;
delete server.queue.object;
server.queue.object= NULL;
if (add)
{
server.queue_version= QUEUE_VERSION_FUNCTION;
server.queue.functions= new queue_st();
if (server.queue.functions)
{
server.queue.functions->_context= context;
server.queue.functions->_add_fn= add;
server.queue.functions->_flush_fn= flush;
server.queue.functions->_done_fn= done;
server.queue.functions->_replay_fn= replay;
}
assert(server.queue.functions);
}
else
{
server.queue_version= QUEUE_VERSION_NONE;
}
}
void gearman_server_set_queue(gearman_server_st& server,
gearmand::queue::Context* context)
{
delete server.queue.functions;
server.queue.functions= NULL;
delete server.queue.object;
server.queue.object= NULL;
assert(context);
{
server.queue_version= QUEUE_VERSION_CLASS;
server.queue.object= context;
}
}
namespace gearmand {
namespace queue {
plugins::Queue::vector all_queue_modules;
void add(plugins::Queue* arg)
{
all_queue_modules.push_back(arg);
}
void load_options(boost::program_options::options_description &all)
{
for (plugins::Queue::vector::iterator iter= all_queue_modules.begin();
iter != all_queue_modules.end();
++iter)
{
all.add((*iter)->command_line_options());
}
}
gearmand_error_t initialize(gearmand_st *, std::string name)
{
bool launched= false;
if (name.empty())
{
return GEARMAND_SUCCESS;
}
std::transform(name.begin(), name.end(), name.begin(), ::tolower);
for (plugins::Queue::vector::iterator iter= all_queue_modules.begin();
iter != all_queue_modules.end();
++iter)
{
if ((*iter)->compare(name) == 0)
{
if (launched)
{
return gearmand_gerror("Attempt to initialize multiple queues", GEARMAND_UNKNOWN_OPTION);
}
gearmand_error_t rc;
if (gearmand_failed(rc= (*iter)->initialize()))
{
return gearmand_log_gerror(GEARMAN_DEFAULT_LOG_PARAM, rc,
"Failed to initialize %s: %s", name.c_str(), (*iter)->error_string().c_str());
}
launched= true;
}
}
if (launched == false)
{
return gearmand_log_gerror(GEARMAN_DEFAULT_LOG_PARAM, GEARMAND_UNKNOWN_OPTION, "Unknown queue %s", name.c_str());
}
return GEARMAND_SUCCESS;
}
} // namespace queue
} // namespace gearmand
| 31.840909 | 117 | 0.600048 | alionurdemetoglu |
ddcc60459156355b4af5441ffd68e7ed6df73f5b | 26,108 | cpp | C++ | CullingModule/MaskedSWOcclusionCulling/Stage/BinTrianglesStage.cpp | SungJJinKang/Parallel_Culling | 17d1302f500bd38df75583c81a7091b975a3ef91 | [
"MIT"
] | 10 | 2021-12-25T09:22:39.000Z | 2022-02-27T19:39:45.000Z | CullingModule/MaskedSWOcclusionCulling/Stage/BinTrianglesStage.cpp | SungJJinKang/Parallel_Culling | 17d1302f500bd38df75583c81a7091b975a3ef91 | [
"MIT"
] | 1 | 2021-11-17T03:15:13.000Z | 2021-11-18T02:51:55.000Z | CullingModule/MaskedSWOcclusionCulling/Stage/BinTrianglesStage.cpp | SungJJinKang/Parallel_Culling | 17d1302f500bd38df75583c81a7091b975a3ef91 | [
"MIT"
] | 1 | 2022-01-09T23:14:30.000Z | 2022-01-09T23:14:30.000Z | #include "BinTrianglesStage.h"
#include <vector>
#include "../MaskedSWOcclusionCulling.h"
#include "../SWDepthBuffer.h"
#include "../Utility/vertexTransformationHelper.h"
#include "../Utility/depthBufferTileHelper.h"
#include "../Utility/RasterizerHelper.h"
#define BIN_VERTEX_INDICE_COUNT_PER_THREAD 24
#define DEFAULT_BINNED_TRIANGLE_COUNT_PER_LOOP 8
#define CONVERT_TO_M256I(_M256F) *reinterpret_cast<const culling::M256I*>(&_M256F)
EVERYCULLING_FORCE_INLINE void culling::BinTrianglesStage::Clipping
(
const culling::M256F* const clipspaceVertexX,
const culling::M256F* const clipspaceVertexY,
const culling::M256F* const clipspaceVertexZ,
const culling::M256F* const clipspaceVertexW,
std::uint32_t& triangleCullMask
)
{
const culling::M256F pointANdcPositiveW = _mm256_andnot_ps(_mm256_set1_ps(-0.0f), clipspaceVertexW[0]);
const culling::M256F pointBNdcPositiveW = _mm256_andnot_ps(_mm256_set1_ps(-0.0f), clipspaceVertexW[1]);
const culling::M256F pointCNdcPositiveW = _mm256_andnot_ps(_mm256_set1_ps(-0.0f), clipspaceVertexW[2]);
const culling::M256F pointANdcX = _mm256_cmp_ps(_mm256_andnot_ps(_mm256_set1_ps(-0.0f), clipspaceVertexX[0]), pointANdcPositiveW, _CMP_LE_OQ); // make positive values ( https://stackoverflow.com/questions/23847377/how-does-this-function-compute-the-absolute-value-of-a-float-through-a-not-and-a )
const culling::M256F pointBNdcX = _mm256_cmp_ps(_mm256_andnot_ps(_mm256_set1_ps(-0.0f), clipspaceVertexX[1]), pointBNdcPositiveW, _CMP_LE_OQ);
const culling::M256F pointCNdcX = _mm256_cmp_ps(_mm256_andnot_ps(_mm256_set1_ps(-0.0f), clipspaceVertexX[2]), pointCNdcPositiveW, _CMP_LE_OQ);
const culling::M256F pointANdcY = _mm256_cmp_ps(_mm256_andnot_ps(_mm256_set1_ps(-0.0f), clipspaceVertexY[0]), pointANdcPositiveW, _CMP_LE_OQ);
const culling::M256F pointBNdcY = _mm256_cmp_ps(_mm256_andnot_ps(_mm256_set1_ps(-0.0f), clipspaceVertexY[1]), pointBNdcPositiveW, _CMP_LE_OQ);
const culling::M256F pointCNdcY = _mm256_cmp_ps(_mm256_andnot_ps(_mm256_set1_ps(-0.0f), clipspaceVertexY[2]), pointCNdcPositiveW, _CMP_LE_OQ);
const culling::M256F pointANdcZ = _mm256_cmp_ps(_mm256_andnot_ps(_mm256_set1_ps(-0.0f), clipspaceVertexZ[0]), pointANdcPositiveW, _CMP_LE_OQ);
const culling::M256F pointBNdcZ = _mm256_cmp_ps(_mm256_andnot_ps(_mm256_set1_ps(-0.0f), clipspaceVertexZ[1]), pointBNdcPositiveW, _CMP_LE_OQ);
const culling::M256F pointCNdcZ = _mm256_cmp_ps(_mm256_andnot_ps(_mm256_set1_ps(-0.0f), clipspaceVertexZ[2]), pointCNdcPositiveW, _CMP_LE_OQ);
culling::M256I pointAInFrustum = _mm256_and_si256(_mm256_and_si256(*reinterpret_cast<const culling::M256I*>(&pointANdcX), *reinterpret_cast<const culling::M256I*>(&pointANdcY)), *reinterpret_cast<const culling::M256I*>(&pointANdcZ));
culling::M256I pointBInFrustum = _mm256_and_si256(_mm256_and_si256(*reinterpret_cast<const culling::M256I*>(&pointBNdcX), *reinterpret_cast<const culling::M256I*>(&pointBNdcY)), *reinterpret_cast<const culling::M256I*>(&pointBNdcZ));
culling::M256I pointCInFrustum = _mm256_and_si256(_mm256_and_si256(*reinterpret_cast<const culling::M256I*>(&pointCNdcX), *reinterpret_cast<const culling::M256I*>(&pointCNdcY)), *reinterpret_cast<const culling::M256I*>(&pointCNdcZ));
// if All vertices of triangle is out of volume, cull the triangle
const culling::M256I verticesInFrustum = _mm256_or_si256(_mm256_or_si256(*reinterpret_cast<const culling::M256I*>(&pointAInFrustum), *reinterpret_cast<const culling::M256I*>(&pointBInFrustum)), *reinterpret_cast<const culling::M256I*>(&pointCInFrustum));
triangleCullMask &= _mm256_movemask_ps(*reinterpret_cast<const culling::M256F*>(&verticesInFrustum));
}
EVERYCULLING_FORCE_INLINE culling::M256F culling::BinTrianglesStage::ComputePositiveWMask
(
const culling::M256F* const clipspaceVertexW
)
{
const culling::M256F pointA_W_IsNegativeValue = _mm256_cmp_ps(clipspaceVertexW[0], _mm256_set1_ps(std::numeric_limits<float>::epsilon()), _CMP_GE_OQ);
const culling::M256F pointB_W_IsNegativeValue = _mm256_cmp_ps(clipspaceVertexW[1], _mm256_set1_ps(std::numeric_limits<float>::epsilon()), _CMP_GE_OQ);
const culling::M256F pointC_W_IsNegativeValue = _mm256_cmp_ps(clipspaceVertexW[2], _mm256_set1_ps(std::numeric_limits<float>::epsilon()), _CMP_GE_OQ);
return _mm256_and_ps(pointA_W_IsNegativeValue, _mm256_and_ps(pointB_W_IsNegativeValue, pointC_W_IsNegativeValue));
}
EVERYCULLING_FORCE_INLINE void culling::BinTrianglesStage::BackfaceCulling
(
culling::M256F* const screenPixelX,
culling::M256F* const screenPixelY,
std::uint32_t& triangleCullMask
)
{
culling::M256F triArea1 = _mm256_mul_ps(_mm256_sub_ps(screenPixelX[1], screenPixelX[0]), _mm256_sub_ps(screenPixelY[2], screenPixelY[0]));
culling::M256F triArea2 = _mm256_mul_ps(_mm256_sub_ps(screenPixelX[0], screenPixelX[2]), _mm256_sub_ps(screenPixelY[0], screenPixelY[1]));
culling::M256F triArea = _mm256_sub_ps(triArea1, triArea2);
culling::M256F ccwMask = _mm256_cmp_ps(triArea, _mm256_set1_ps(std::numeric_limits<float>::epsilon()), _CMP_GT_OQ);
// Return a lane mask with all front faces set
triangleCullMask &= _mm256_movemask_ps(ccwMask);
}
EVERYCULLING_FORCE_INLINE void culling::BinTrianglesStage::PassTrianglesToTileBin
(
const culling::M256F& pointAScreenPixelPosX,
const culling::M256F& pointAScreenPixelPosY,
const culling::M256F& pointANdcSpaceVertexZ,
const culling::M256F& pointBScreenPixelPosX,
const culling::M256F& pointBScreenPixelPosY,
const culling::M256F& pointBNdcSpaceVertexZ,
const culling::M256F& pointCScreenPixelPosX,
const culling::M256F& pointCScreenPixelPosY,
const culling::M256F& pointCNdcSpaceVertexZ,
const std::uint32_t& triangleCullMask,
const size_t triangleCountPerLoop,
const culling::M256I& outBinBoundingBoxMinX,
const culling::M256I& outBinBoundingBoxMinY,
const culling::M256I& outBinBoundingBoxMaxX,
const culling::M256I& outBinBoundingBoxMaxY
)
{
for (size_t triangleIndex = 0; triangleIndex < triangleCountPerLoop; triangleIndex++)
{
if ((triangleCullMask & (1 << triangleIndex)) != 0x00000000)
{
const int intersectingMinBoxX = (reinterpret_cast<const int*>(&outBinBoundingBoxMinX))[triangleIndex]; // this is screen space coordinate
const int intersectingMinBoxY = (reinterpret_cast<const int*>(&outBinBoundingBoxMinY))[triangleIndex];
const int intersectingMaxBoxX = (reinterpret_cast<const int*>(&outBinBoundingBoxMaxX))[triangleIndex];
const int intersectingMaxBoxY = (reinterpret_cast<const int*>(&outBinBoundingBoxMaxY))[triangleIndex];
assert(intersectingMinBoxX <= intersectingMaxBoxX);
assert(intersectingMinBoxY <= intersectingMaxBoxY);
const int startBoxIndexX = MIN((int)(mMaskedOcclusionCulling->mDepthBuffer.mResolution.mColumnTileCount - 1), intersectingMinBoxX / TILE_WIDTH);
const int startBoxIndexY = MIN((int)(mMaskedOcclusionCulling->mDepthBuffer.mResolution.mRowTileCount - 1), intersectingMinBoxY / TILE_HEIGHT);
const int endBoxIndexX = MIN((int)(mMaskedOcclusionCulling->mDepthBuffer.mResolution.mColumnTileCount - 1), intersectingMaxBoxX / TILE_WIDTH);
const int endBoxIndexY = MIN((int)(mMaskedOcclusionCulling->mDepthBuffer.mResolution.mRowTileCount - 1), intersectingMaxBoxY / TILE_HEIGHT);
assert(startBoxIndexX >= 0 && startBoxIndexX < (int)(mMaskedOcclusionCulling->mDepthBuffer.mResolution.mColumnTileCount));
assert(startBoxIndexY >= 0 && startBoxIndexY < (int)(mMaskedOcclusionCulling->mDepthBuffer.mResolution.mRowTileCount));
assert(endBoxIndexX >= 0 && endBoxIndexX <= (int)(mMaskedOcclusionCulling->mDepthBuffer.mResolution.mColumnTileCount));
assert(endBoxIndexY >= 0 && endBoxIndexY <= (int)(mMaskedOcclusionCulling->mDepthBuffer.mResolution.mRowTileCount));
for (size_t y = startBoxIndexY; y <= endBoxIndexY; y++)
{
for (size_t x = startBoxIndexX; x <= endBoxIndexX; x++)
{
Tile* const targetTile = mMaskedOcclusionCulling->mDepthBuffer.GetTile(y, x);
//assert(targetTile->mBinnedTriangleList.GetIsBinFull() == false);
const size_t triListIndex = targetTile->mBinnedTriangleCount++;
if(triListIndex < BIN_TRIANGLE_CAPACITY_PER_TILE)
{
targetTile->mBinnedTriangleList[triListIndex].PointAVertexX = (reinterpret_cast<const float*>(&pointAScreenPixelPosX))[triangleIndex];
targetTile->mBinnedTriangleList[triListIndex].PointAVertexY = (reinterpret_cast<const float*>(&pointAScreenPixelPosY))[triangleIndex];
targetTile->mBinnedTriangleList[triListIndex].PointAVertexZ = (reinterpret_cast<const float*>(&pointANdcSpaceVertexZ))[triangleIndex];
targetTile->mBinnedTriangleList[triListIndex].PointBVertexX = (reinterpret_cast<const float*>(&pointBScreenPixelPosX))[triangleIndex];
targetTile->mBinnedTriangleList[triListIndex].PointBVertexY = (reinterpret_cast<const float*>(&pointBScreenPixelPosY))[triangleIndex];
targetTile->mBinnedTriangleList[triListIndex].PointBVertexZ = (reinterpret_cast<const float*>(&pointBNdcSpaceVertexZ))[triangleIndex];
targetTile->mBinnedTriangleList[triListIndex].PointCVertexX = (reinterpret_cast<const float*>(&pointCScreenPixelPosX))[triangleIndex];
targetTile->mBinnedTriangleList[triListIndex].PointCVertexY = (reinterpret_cast<const float*>(&pointCScreenPixelPosY))[triangleIndex];
targetTile->mBinnedTriangleList[triListIndex].PointCVertexZ = (reinterpret_cast<const float*>(&pointCNdcSpaceVertexZ))[triangleIndex];
}
}
}
}
}
}
EVERYCULLING_FORCE_INLINE void culling::BinTrianglesStage::GatherVertices
(
const float* const vertices,
const size_t verticeCount,
const std::uint32_t* const vertexIndices,
const size_t indiceCount,
const size_t currentIndiceIndex,
const size_t vertexStrideByte,
const size_t fetchTriangleCount,
culling::M256F* outVerticesX,
culling::M256F* outVerticesY,
culling::M256F* outVerticesZ
)
{
assert(indiceCount % 3 == 0);
assert(currentIndiceIndex % 3 == 0);
assert(indiceCount != 0); // TODO : implement gatherVertices when there is no indiceCount
//Gather Indices
const std::uint32_t* currentVertexIndices = vertexIndices + currentIndiceIndex;
const culling::M256I indiceIndexs = _mm256_set_epi32(21, 18, 15, 12, 9, 6, 3, 0);
static const culling::M256I SIMD_LANE_MASK[9] = {
_mm256_setr_epi32(0, 0, 0, 0, 0, 0, 0, 0),
_mm256_setr_epi32(~0, 0, 0, 0, 0, 0, 0, 0),
_mm256_setr_epi32(~0, ~0, 0, 0, 0, 0, 0, 0),
_mm256_setr_epi32(~0, ~0, ~0, 0, 0, 0, 0, 0),
_mm256_setr_epi32(~0, ~0, ~0, ~0, 0, 0, 0, 0),
_mm256_setr_epi32(~0, ~0, ~0, ~0, ~0, 0, 0, 0),
_mm256_setr_epi32(~0, ~0, ~0, ~0, ~0, ~0, 0, 0),
_mm256_setr_epi32(~0, ~0, ~0, ~0, ~0, ~0, ~0, 0),
_mm256_setr_epi32(~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0)
};
// Compute per-lane index list offset that guards against out of bounds memory accesses
const culling::M256I safeIndiceIndexs = _mm256_and_si256(indiceIndexs, SIMD_LANE_MASK[fetchTriangleCount]);
culling::M256I m256i_indices[3];
//If stride is 7
//Current Value
//m256i_indices[0] : 0 ( first vertex index ), 3, 6, 9, 12, 15, 18, 21
//m256i_indices[1] : 1 ( second vertex index ), 4, 7, 10, 13, 16, 19, 22
//m256i_indices[2] : 2, 5, 8, 11, 14, 17, 20, 23
//Point1 indices of Triangles
m256i_indices[0] = _mm256_i32gather_epi32(reinterpret_cast<const int*>(currentVertexIndices + 0), safeIndiceIndexs, 4); // why 4? -> vertexIndices is std::uint32_t( 4byte )
//Point2 indices of Triangles
m256i_indices[1] = _mm256_i32gather_epi32(reinterpret_cast<const int*>(currentVertexIndices + 1), safeIndiceIndexs, 4);
//Point3 indices of Triangles
m256i_indices[2] = _mm256_i32gather_epi32(reinterpret_cast<const int*>(currentVertexIndices + 2), safeIndiceIndexs, 4);
if(vertexStrideByte > 0)
{
//Consider Stride
//If StrideByte is 28
//m256i_indices[0] : 0 * 28, 3 * 28, 6 * 28, 9 * 28, 12 * 28, 15 * 28, 18 * 28, 21 * 28
//m256i_indices[1] : 1 * 28, 4 * 28, 7 * 28, 10 * 28, 13 * 28, 16 * 28, 19 * 28, 22 * 28
//m256i_indices[2] : 2 * 28, 5 * 28, 8 * 28, 11 * 28, 14 * 28, 17 * 28, 20 * 28, 23 * 28
const culling::M256I m256i_stride = _mm256_set1_epi32(static_cast<int>(vertexStrideByte));
m256i_indices[0] = _mm256_mullo_epi32(m256i_indices[0], m256i_stride);
m256i_indices[1] = _mm256_mullo_epi32(m256i_indices[1], m256i_stride);
m256i_indices[2] = _mm256_mullo_epi32(m256i_indices[2], m256i_stride);
}
//Gather vertexs
//Should consider vertexStride(vertices isn't stored contiguously because generally vertex datas is stored with uv, normal datas...)
//And Should consider z value
for (size_t i = 0; i < 3; i++)
{
outVerticesX[i] = _mm256_i32gather_ps((float*)vertices, m256i_indices[i], 1);
outVerticesY[i] = _mm256_i32gather_ps((float*)vertices + 1, m256i_indices[i], 1);
outVerticesZ[i] = _mm256_i32gather_ps((float*)vertices + 2, m256i_indices[i], 1);
}
}
void culling::BinTrianglesStage::ConvertToPlatformDepth(culling::M256F* const depth)
{
#if (NDC_RANGE == MINUS_ONE_TO_POSITIVE_ONE)
for (size_t i = 0; i < 3; i++)
{
//depth[i]
}
#endif
}
/*
void culling::BinTrianglesStage::BinTriangleThreadJob(const size_t cameraIndex)
{
while (true)
{
culling::EntityBlock* const nextEntityBlock = GetNextEntityBlock(cameraIndex, false);
if (nextEntityBlock != nullptr)
{
for (size_t entityIndex = 0; entityIndex < nextEntityBlock->mCurrentEntityCount; entityIndex++)
{
const size_t binnedTriangleListIndex = mMaskedOcclusionCulling->IncreamentBinnedOccluderCountIfPossible();
if (binnedTriangleListIndex != 0)
{
if
(
(nextEntityBlock->GetIsCulled(entityIndex, cameraIndex) == false) &&
(nextEntityBlock->GetIsOccluder(entityIndex) == true)
)
{
const culling::Mat4x4 modelToClipSpaceMatrix = mCullingSystem->GetCameraViewProjectionMatrix(cameraIndex) * nextEntityBlock->GetModelMatrix(entityIndex);
const VertexData& vertexData = nextEntityBlock->mVertexDatas[entityIndex];
BinTriangles
(
binnedTriangleListIndex,
reinterpret_cast<const float*>(vertexData.mVertices),
vertexData.mVerticeCount,
vertexData.mIndices,
vertexData.mIndiceCount,
vertexData.mVertexStride,
modelToClipSpaceMatrix.data()
);
}
}
else
{
return;
}
}
}
else
{
return;
}
}
}
*/
void culling::BinTrianglesStage::BinTriangleThreadJobByObjectOrder(const size_t cameraIndex)
{
std::vector<OccluderData> sortedOccluderList = mMaskedOcclusionCulling->mOccluderListManager.GetSortedOccluderList();
std::uint64_t totalBinnedIndiceCount = 0;
for (size_t entityInfoIndex = 0; entityInfoIndex < sortedOccluderList.size() && totalBinnedIndiceCount < MAX_BINNED_INDICE_COUNT ; entityInfoIndex++)
{
culling::OccluderData& occluderInfo = sortedOccluderList[entityInfoIndex];
culling::EntityBlock* const entityBlock = occluderInfo.mEntityBlock;
const size_t entityIndexInEntityBlock = occluderInfo.mEntityIndexInEntityBlock;
assert(entityBlock->GetIsOccluder(entityIndexInEntityBlock) == true);
assert(entityBlock->GetIsCulled(entityIndexInEntityBlock) == false);
std::atomic<std::uint64_t>& atomic_binnedIndiceCountOfCurrentEntity = entityBlock->mVertexDatas[entityIndexInEntityBlock].mBinnedIndiceCount;
const culling::Vec3* const vertices = entityBlock->mVertexDatas[entityIndexInEntityBlock].mVertices;
const std::uint64_t verticeCount = entityBlock->mVertexDatas[entityIndexInEntityBlock].mVerticeCount;
const std::uint32_t* const indices = entityBlock->mVertexDatas[entityIndexInEntityBlock].mIndices;
const std::uint64_t totalIndiceCount = entityBlock->mVertexDatas[entityIndexInEntityBlock].mIndiceCount;
const std::uint64_t vertexStride = entityBlock->mVertexDatas[entityIndexInEntityBlock].mVertexStride;
std::uint64_t currentBinnedIndiceCountOfCurrentEntity = 0;
while (totalBinnedIndiceCount + currentBinnedIndiceCountOfCurrentEntity < MAX_BINNED_INDICE_COUNT)
{
static_assert(BIN_VERTEX_INDICE_COUNT_PER_THREAD % 3 == 0);
currentBinnedIndiceCountOfCurrentEntity = atomic_binnedIndiceCountOfCurrentEntity.fetch_add(BIN_VERTEX_INDICE_COUNT_PER_THREAD, std::memory_order_seq_cst);
if (currentBinnedIndiceCountOfCurrentEntity < totalIndiceCount)
{
const culling::Mat4x4 modelToClipSpaceMatrix = mCullingSystem->GetCameraViewProjectionMatrix(cameraIndex) * entityBlock->GetModelMatrix(entityIndexInEntityBlock);
const std::uint32_t* const startIndicePtr = indices + currentBinnedIndiceCountOfCurrentEntity;
const std::uint32_t indiceCount = MIN(BIN_VERTEX_INDICE_COUNT_PER_THREAD, totalIndiceCount - currentBinnedIndiceCountOfCurrentEntity);
BinTriangles
(
reinterpret_cast<const float*>(vertices),
verticeCount,
startIndicePtr,
indiceCount,
vertexStride,
modelToClipSpaceMatrix.data()
);
}
else
{
break;
}
}
totalBinnedIndiceCount += MIN(totalIndiceCount, currentBinnedIndiceCountOfCurrentEntity);
}
}
culling::BinTrianglesStage::BinTrianglesStage(MaskedSWOcclusionCulling* mMOcclusionCulling)
: MaskedSWOcclusionCullingStage{ mMOcclusionCulling }
{
}
void culling::BinTrianglesStage::ResetCullingModule(const unsigned long long currentTickCount)
{
MaskedSWOcclusionCullingStage::ResetCullingModule(currentTickCount);
}
void culling::BinTrianglesStage::CullBlockEntityJob(const size_t cameraIndex, const unsigned long long currentTickCount)
{
if(WHEN_TO_BIN_TRIANGLE(currentTickCount))
{
#ifdef FETCH_OBJECT_SORT_FROM_DOOMS_ENGINE_IN_BIN_TRIANGLE_STAGE
BinTriangleThreadJobByObjectOrder(cameraIndex);
#else
BinTriangleThreadJob(cameraIndex);
#endif
}
}
const char* culling::BinTrianglesStage::GetCullingModuleName() const
{
return "BinTrianglesStage";
}
EVERYCULLING_FORCE_INLINE void culling::BinTrianglesStage::BinTriangles
(
const float* const vertices,
const size_t verticeCount,
const std::uint32_t* const vertexIndices,
const size_t indiceCount,
const size_t vertexStrideByte,
const float* const modelToClipspaceMatrix
)
{
std::int32_t currentIndiceIndex = -(DEFAULT_BINNED_TRIANGLE_COUNT_PER_LOOP * 3);
assert(indiceCount != 0); // check GatherVertices function
while (currentIndiceIndex < (std::int32_t)indiceCount)
{
currentIndiceIndex += (DEFAULT_BINNED_TRIANGLE_COUNT_PER_LOOP * 3);
if(currentIndiceIndex >= (std::int32_t)indiceCount)
{
break;
}
const size_t fetchTriangleCount = MIN(8, (indiceCount - currentIndiceIndex) / 3);
assert(fetchTriangleCount != 0);
// First 4 bits show if traingle is valid
// Current Value : 00000000 00000000 00000000 11111111
std::uint32_t triangleCullMask = (1 << fetchTriangleCount) - 1;
//Why Size of array is 3?
//A culling::M256F can have 8 floating-point
//A TwoDTriangle have 3 point
//So If you have just one culling::M256F variable, a floating-point is unused.
//Not to make unused space, 12 floating point is required per axis
// culling::M256F * 3 -> 8 TwoDTriangle with no unused space
//We don't need z value in Binning stage!!!
// Triangle's First Vertex X is in ndcSpaceVertexX[0][0]
// Triangle's Second Vertex X is in ndcSpaceVertexX[0][1]
// Triangle's Third Vertex X is in ndcSpaceVertexX[0][2]
culling::M256F ndcSpaceVertexX[3], ndcSpaceVertexY[3], ndcSpaceVertexZ[3], oneDividedByW[3];
//Gather Vertex with indice
//WE ARRIVE AT MODEL SPACE COORDINATE!
GatherVertices(vertices, verticeCount, vertexIndices, indiceCount, currentIndiceIndex, vertexStrideByte, fetchTriangleCount, ndcSpaceVertexX, ndcSpaceVertexY, ndcSpaceVertexZ);
//////////////////////////////////////////////////
for(int i = 0 ; i < 3 ; i++)
{
oneDividedByW[i] = culling::M256F_MUL_AND_ADD(ndcSpaceVertexX[i], _mm256_set1_ps(modelToClipspaceMatrix[3]), culling::M256F_MUL_AND_ADD(ndcSpaceVertexY[i], _mm256_set1_ps(modelToClipspaceMatrix[7]), culling::M256F_MUL_AND_ADD(ndcSpaceVertexZ[i], _mm256_set1_ps(modelToClipspaceMatrix[11]), _mm256_set1_ps(modelToClipspaceMatrix[15]))));
}
const culling::M256F positiveWMask = ComputePositiveWMask(oneDividedByW);
const culling::M256I allOne = _mm256_set1_epi64x(0xFFFFFFFFFFFFFFFF);
const culling::M256F negativeWMask = _mm256_xor_ps(positiveWMask, *reinterpret_cast<const __m256*>(&allOne));
triangleCullMask &= _mm256_movemask_ps(*reinterpret_cast<const culling::M256F*>(&positiveWMask));
if (triangleCullMask == 0x00000000)
{
continue;
}
/*
for (int i = 0; i < 3; i++)
{
const culling::M256F point_W_IsNegativeValue = _mm256_cmp_ps(oneDividedByW[i], _mm256_set1_ps(std::numeric_limits<float>::epsilon()), _CMP_LT_OQ);
oneDividedByW[i] = _mm256_blendv_ps(oneDividedByW[i], _mm256_set1_ps(1.0f), point_W_IsNegativeValue);
}
*/
//////////////////////////////////////////////////
//Convert Model space Vertex To Clip space Vertex
//WE ARRIVE AT CLIP SPACE COORDINATE. W IS NOT 1
culling::vertexTransformationHelper::TransformThreeVerticesToClipSpace
(
ndcSpaceVertexX,
ndcSpaceVertexY,
ndcSpaceVertexZ,
modelToClipspaceMatrix
);
Clipping(ndcSpaceVertexX, ndcSpaceVertexY, ndcSpaceVertexZ, oneDividedByW, triangleCullMask);
if (triangleCullMask == 0x00000000)
{
continue;
}
for (int i = 0; i < 3; i++)
{
oneDividedByW[i] = culling::M256F_DIV(_mm256_set1_ps(1.0f), oneDividedByW[i]);
}
//////////////////////////////////////////////////
// Now Z value is on NDC coordinate
for (int i = 0; i < 3; i++)
{
ndcSpaceVertexZ[i] = culling::M256F_MUL(ndcSpaceVertexZ[i], oneDividedByW[i]);
}
//////////////////////////////////////////////////
culling::M256F screenPixelPosX[3], screenPixelPosY[3];
culling::vertexTransformationHelper::ConvertClipSpaceThreeVerticesToScreenPixelSpace(ndcSpaceVertexX, ndcSpaceVertexY, oneDividedByW, screenPixelPosX, screenPixelPosY, mMaskedOcclusionCulling->mDepthBuffer);
BackfaceCulling(screenPixelPosX, screenPixelPosY, triangleCullMask);
if (triangleCullMask == 0x00000000)
{
continue;
}
//////////////////////////////////////////////////
Sort_8_3DTriangles
(
screenPixelPosX[0],
screenPixelPosY[0],
ndcSpaceVertexZ[0],
screenPixelPosX[1],
screenPixelPosY[1],
ndcSpaceVertexZ[1],
screenPixelPosX[2],
screenPixelPosY[2],
ndcSpaceVertexZ[2]
);
culling::M256F LEFT_MIDDLE_POINT_X;
culling::M256F LEFT_MIDDLE_POINT_Y;
culling::M256F LEFT_MIDDLE_POINT_Z;
culling::M256F RIGHT_MIDDLE_POINT_X;
culling::M256F RIGHT_MIDDLE_POINT_Y;
culling::M256F RIGHT_MIDDLE_POINT_Z;
// split triangle
culling::rasterizerHelper::GetMiddlePointOfTriangle
(
screenPixelPosX[0],
screenPixelPosY[0],
ndcSpaceVertexZ[0],
screenPixelPosX[1],
screenPixelPosY[1],
ndcSpaceVertexZ[1],
screenPixelPosX[2],
screenPixelPosY[2],
ndcSpaceVertexZ[2],
LEFT_MIDDLE_POINT_X,
LEFT_MIDDLE_POINT_Y,
LEFT_MIDDLE_POINT_Z,
RIGHT_MIDDLE_POINT_X,
RIGHT_MIDDLE_POINT_Y,
RIGHT_MIDDLE_POINT_Z
);
#ifdef DEBUG_CULLING
#endif
{
//Bin Bottom Flat Triangle
culling::M256I outBinBoundingBoxMinX, outBinBoundingBoxMinY, outBinBoundingBoxMaxX, outBinBoundingBoxMaxY;
//Bin Triangles to tiles
//Compute Bin Bounding Box
//Get Intersecting Bin List
culling::depthBufferTileHelper::ComputeBinBoundingBoxFromThreeVertices
(
screenPixelPosX[0],
screenPixelPosY[0],
LEFT_MIDDLE_POINT_X,
LEFT_MIDDLE_POINT_Y,
RIGHT_MIDDLE_POINT_X,
RIGHT_MIDDLE_POINT_Y,
outBinBoundingBoxMinX,
outBinBoundingBoxMinY,
outBinBoundingBoxMaxX,
outBinBoundingBoxMaxY,
mMaskedOcclusionCulling->mDepthBuffer
);
#ifdef DEBUG_CULLING
for (size_t triangleIndex = 0; triangleIndex < fetchTriangleCount; triangleIndex++)
{
if ((triangleCullMask & (1 << triangleIndex)) != 0x00000000)
{
assert(reinterpret_cast<const int*>(&outBinBoundingBoxMinX)[triangleIndex] <= reinterpret_cast<const int*>(&outBinBoundingBoxMaxX)[triangleIndex]);
assert(reinterpret_cast<const int*>(&outBinBoundingBoxMinY)[triangleIndex] <= reinterpret_cast<const int*>(&outBinBoundingBoxMaxY)[triangleIndex]);
}
}
#endif
// Pass triangle in counter clock wise
PassTrianglesToTileBin
(
screenPixelPosX[0],
screenPixelPosY[0],
ndcSpaceVertexZ[0],
LEFT_MIDDLE_POINT_X,
LEFT_MIDDLE_POINT_Y,
LEFT_MIDDLE_POINT_Z,
RIGHT_MIDDLE_POINT_X,
RIGHT_MIDDLE_POINT_Y,
RIGHT_MIDDLE_POINT_Z,
triangleCullMask,
fetchTriangleCount,
outBinBoundingBoxMinX,
outBinBoundingBoxMinY,
outBinBoundingBoxMaxX,
outBinBoundingBoxMaxY
);
}
{
//Bin Top Flat Triangle
culling::M256I outBinBoundingBoxMinX, outBinBoundingBoxMinY, outBinBoundingBoxMaxX, outBinBoundingBoxMaxY;
culling::depthBufferTileHelper::ComputeBinBoundingBoxFromThreeVertices
(
screenPixelPosX[2],
screenPixelPosY[2],
RIGHT_MIDDLE_POINT_X,
RIGHT_MIDDLE_POINT_Y,
LEFT_MIDDLE_POINT_X,
LEFT_MIDDLE_POINT_Y,
outBinBoundingBoxMinX,
outBinBoundingBoxMinY,
outBinBoundingBoxMaxX,
outBinBoundingBoxMaxY,
mMaskedOcclusionCulling->mDepthBuffer
);
#ifdef DEBUG_CULLING
for (size_t triangleIndex = 0; triangleIndex < fetchTriangleCount; triangleIndex++)
{
if ((triangleCullMask & (1 << triangleIndex)) != 0x00000000)
{
assert(reinterpret_cast<const int*>(&outBinBoundingBoxMinX)[triangleIndex] <= reinterpret_cast<const int*>(&outBinBoundingBoxMaxX)[triangleIndex]);
assert(reinterpret_cast<const int*>(&outBinBoundingBoxMinY)[triangleIndex] <= reinterpret_cast<const int*>(&outBinBoundingBoxMaxY)[triangleIndex]);
}
}
#endif
// Pass triangle in counter clock wise
PassTrianglesToTileBin
(
screenPixelPosX[2],
screenPixelPosY[2],
ndcSpaceVertexZ[2],
RIGHT_MIDDLE_POINT_X,
RIGHT_MIDDLE_POINT_Y,
RIGHT_MIDDLE_POINT_Z,
LEFT_MIDDLE_POINT_X,
LEFT_MIDDLE_POINT_Y,
LEFT_MIDDLE_POINT_Z,
triangleCullMask,
fetchTriangleCount,
outBinBoundingBoxMinX,
outBinBoundingBoxMinY,
outBinBoundingBoxMaxX,
outBinBoundingBoxMaxY
);
}
}
}
| 37.782923 | 339 | 0.753486 | SungJJinKang |
ddcf9616c31ed55cc59255bdcdb74bdf1cdfa94d | 23,940 | cpp | C++ | source/base/Scene.cpp | chillpert/renderer | 9c953cef10ebec7a2c8fe5763a2c10105729deab | [
"Zlib"
] | 2 | 2020-11-18T18:20:12.000Z | 2020-12-18T19:24:00.000Z | source/base/Scene.cpp | chillpert/rayex | 9c953cef10ebec7a2c8fe5763a2c10105729deab | [
"Zlib"
] | null | null | null | source/base/Scene.cpp | chillpert/rayex | 9c953cef10ebec7a2c8fe5763a2c10105729deab | [
"Zlib"
] | null | null | null | #include "base/Scene.hpp"
#include "api/Components.hpp"
#define STB_IMAGE_IMPLEMENTATION
#include "stb/stb_image.h"
namespace RAYEX_NAMESPACE
{
CameraUbo cameraUbo;
std::shared_ptr<Geometry> triangle = nullptr; ///< A dummy triangle that will be placed in the scene if it empty. This assures the AS creation.
std::shared_ptr<GeometryInstance> triangleInstance = nullptr;
std::vector<GeometryInstanceSSBO> memAlignedGeometryInstances;
std::vector<MaterialSSBO> memAlignedMaterials;
auto Scene::getGeometryInstances( ) const -> const std::vector<std::shared_ptr<GeometryInstance>>&
{
return _geometryInstances;
}
auto Scene::getGeometryInstance( size_t index ) const -> std::shared_ptr<GeometryInstance>
{
if ( index < _geometryInstances.size( ) )
{
return _geometryInstances[index];
}
else
{
RX_ERROR( "Geometry Instances out of bound." );
return nullptr;
}
}
void Scene::submitGeometryInstance( std::shared_ptr<GeometryInstance> geometryInstance )
{
if ( !_dummy )
{
if ( _geometryInstances.size( ) > _settings->_maxGeometryInstances )
{
RX_ERROR( "Failed to submit geometry instance because instance buffer size has been exceeded. To avoid this error, increase the amount of supported geometry instances using RAYEX_NAMESPACE::Rayex::Settings::setMaxGeometryInstances(size_t)." );
return;
}
}
_geometryInstances.push_back( geometryInstance );
_uploadGeometryInstancesToBuffer = true;
}
void Scene::setGeometryInstances( const std::vector<std::shared_ptr<GeometryInstance>>& geometryInstances )
{
_geometryInstances.clear( );
_geometryInstances.reserve( geometryInstances.size( ) );
for ( auto geometryInstance : geometryInstances )
{
submitGeometryInstance( geometryInstance );
}
_uploadGeometryInstancesToBuffer = true;
}
void Scene::removeGeometryInstance( std::shared_ptr<GeometryInstance> geometryInstance )
{
if ( geometryInstance == nullptr )
{
RX_ERROR( "An invalid geometry instance can not be removed." );
return;
}
// Create a copy of all geometry instances
std::vector<std::shared_ptr<GeometryInstance>> temp( _geometryInstances );
// Clear the original container
_geometryInstances.clear( );
_geometryInstances.reserve( temp.size( ) );
// Iterate over the container with the copies
for ( auto it : temp )
{
// Delete the given geometry instance if it matches
if ( it != geometryInstance )
{
_geometryInstances.push_back( it );
}
}
_uploadGeometryInstancesToBuffer = true;
}
void Scene::clearGeometryInstances( )
{
// Only allow clearing the scene if there is no dummy element.
if ( !_dummy )
{
_geometryInstances.clear( );
_uploadGeometryInstancesToBuffer = true;
}
}
void Scene::popGeometryInstance( )
{
// Only allow clearing the scene if the scene is not empty and does not contain a dummy element.
if ( !_geometryInstances.empty( ) && !_dummy )
{
_geometryInstances.erase( _geometryInstances.end( ) - 1 );
_uploadGeometryInstancesToBuffer = true;
}
}
void Scene::submitGeometry( std::shared_ptr<Geometry> geometry )
{
if ( !_dummy )
{
if ( _geometries.size( ) >= _settings->_maxGeometry )
{
RX_ERROR( "Failed to submit geometry because geometries buffer size has been exceeded. To avoid this error, increase the amount of supported geometries using RAYEX_NAMESPACE::Rayex::Settings::setMaxGeometries(size_t)." );
return;
}
}
_geometries.push_back( geometry );
_uploadGeometries = true;
}
void Scene::setGeometries( const std::vector<std::shared_ptr<Geometry>>& geometries )
{
_geometries.clear( );
_geometries.reserve( geometries.size( ) );
for ( auto geometry : geometries )
{
submitGeometry( geometry );
}
_uploadGeometries = true;
}
void Scene::removeGeometry( std::shared_ptr<Geometry> geometry )
{
if ( geometry == nullptr )
{
RX_ERROR( "An invalid geometry can not be removed." );
return;
}
// Removing a geometry also means removing all its instances.
std::vector<std::shared_ptr<GeometryInstance>> instancesToDelete;
for ( auto it : _geometryInstances )
{
if ( it->geometryIndex == geometry->geometryIndex )
{
instancesToDelete.push_back( it );
}
}
// Remove all instances of that geometry index
// Create a copy of all geometry instances
std::vector<std::shared_ptr<GeometryInstance>> temp3( _geometryInstances );
// Clear the original container
_geometryInstances.clear( );
_geometryInstances.reserve( temp3.size( ) );
// Iterate over the container with the copies
for ( auto it : temp3 )
{
// Delete the given geometry instance if it matches
if ( it->geometryIndex != geometry->geometryIndex )
{
_geometryInstances.push_back( it );
}
}
_uploadGeometryInstancesToBuffer = true;
std::vector<std::shared_ptr<Geometry>> temp( _geometries );
_geometries.clear( );
_geometries.reserve( temp.size( ) );
uint32_t geometryIndex = 0;
for ( auto it : temp )
{
if ( it != geometry )
{
it->geometryIndex = geometryIndex++;
_geometries.push_back( it );
}
}
--components::geometryIndex;
_uploadGeometries = true; // @todo Might not be necessary.
// Update geometry indices for geometry instances.
std::vector<std::shared_ptr<GeometryInstance>> temp2( _geometryInstances );
_geometryInstances.clear( );
_geometries.reserve( temp2.size( ) );
geometryIndex = 0;
for ( auto it : temp2 )
{
if ( it->geometryIndex > geometry->geometryIndex )
{
--it->geometryIndex;
_geometryInstances.push_back( it );
}
else
{
_geometryInstances.push_back( it );
}
}
_uploadGeometryInstancesToBuffer = true;
}
void Scene::removeGeometry( uint32_t geometryIndex )
{
for ( auto it : _geometries )
{
if ( it->geometryIndex == geometryIndex )
{
removeGeometry( it );
break;
}
}
}
void Scene::clearGeometries( )
{
RX_INFO( "Clearing geometry." );
_geometries.clear( );
_geometryInstances.clear( );
// Reset index counter.
components::geometryIndex = 0;
// Reset texture counter.
components::textureIndex = 0;
_uploadGeometries = true;
_uploadGeometryInstancesToBuffer = true;
}
void Scene::popGeometry( )
{
if ( !_geometries.empty( ) )
{
removeGeometry( *( _geometries.end( ) - 1 ) );
}
}
auto Scene::findGeometry( std::string_view path ) const -> std::shared_ptr<Geometry>
{
for ( std::shared_ptr<Geometry> geometry : _geometries )
{
if ( geometry->path == path )
{
return geometry;
}
}
RX_INFO( "Could not find geometry in scene." );
return nullptr;
}
void Scene::setEnvironmentMap( std::string_view path )
{
_environmentMapTexturePath = path;
_useEnvironmentMap = true;
_uploadEnvironmentMap = true;
}
void Scene::removeEnvironmentMap( )
{
_useEnvironmentMap = false;
}
void Scene::setCamera( std::shared_ptr<Camera> camera )
{
_cameras.insert( camera );
_currentCamera = camera;
}
void Scene::setCamera( int width, int height, const glm::vec3& position )
{
auto cam = std::make_shared<Camera>( width, height, position );
_cameras.insert( cam );
_currentCamera = cam;
}
void Scene::load( const std::string& path )
{
/*
// This might need to be moved to api.cpp anyways, because it requires direct access to some of the buffers apparently.
tinygltf::Model model;
tinygltf::TinyGLTF loader;
std::string errors;
std::string warnings;
bool res = loader.LoadASCIIFromFile( &model, &errors, &warnings, path );
if ( !warnings.empty( ) )
{
RX_WARN( "GLTF: ", warnings );
}
if ( !errors.empty( ) )
{
RX_ERROR( "GLTF: ", errors );
}
RX_ASSERT( res, "Failed to parse gltf file at ", path );
RX_WARN( "GLTF support not implemented yet." );
*/
}
void Scene::prepareBuffers( )
{
// Resize and initialize buffers with "dummy data".
// The advantage of doing this is that the buffers are all initialized right away (even though it is invalid data) and
// this makes it possible to call fill instead of initialize again, when changing any of the data below.
std::vector<GeometryInstanceSSBO> geometryInstances( _settings->_maxGeometryInstances );
_geometryInstancesBuffer.init( geometryInstances, components::maxResources );
// @todo is this even necessary?
std::vector<MaterialSSBO> materials( _settings->_maxMaterials );
_materialBuffers.init( materials, components::maxResources );
_vertexBuffers.resize( _settings->_maxGeometry );
_indexBuffers.resize( _settings->_maxGeometry );
_materialIndexBuffers.resize( _settings->_maxGeometry );
_textures.resize( _settings->_maxTextures );
initCameraBuffer( );
}
void Scene::initCameraBuffer( )
{
_cameraUniformBuffer.init( );
}
void Scene::uploadCameraBuffer( uint32_t imageIndex )
{
// Upload camera.
if ( _currentCamera != nullptr )
{
if ( _currentCamera->_updateView )
{
cameraUbo.view = _currentCamera->getViewMatrix( );
cameraUbo.viewInverse = _currentCamera->getViewInverseMatrix( );
_currentCamera->_updateView = false;
}
if ( _currentCamera->_updateProj )
{
cameraUbo.projection = _currentCamera->getProjectionMatrix( );
cameraUbo.projectionInverse = _currentCamera->getProjectionInverseMatrix( );
_currentCamera->_updateProj = false;
}
cameraUbo.position = glm::vec4( _currentCamera->getPosition( ), _currentCamera->getAperture( ) );
cameraUbo.front = glm::vec4( _currentCamera->getFront( ), _currentCamera->getFocalDistance( ) );
}
_cameraUniformBuffer.upload( imageIndex, cameraUbo );
}
void Scene::uploadEnvironmentMap( )
{
_uploadEnvironmentMap = false;
_environmentMap.init( _environmentMapTexturePath );
if ( _removeEnvironmentMap )
{
removeEnvironmentMap( );
_removeEnvironmentMap = false;
}
}
void Scene::uploadGeometries( )
{
_uploadGeometries = false;
memAlignedMaterials.clear( );
memAlignedMaterials.reserve( components::_materials.size( ) );
// Create all textures of a material
for ( size_t i = 0; i < components::_materials.size( ); ++i )
{
// Convert to memory aligned struct
MaterialSSBO mat2;
mat2.diffuse = glm::vec4( components::_materials[i].kd, -1.0F );
mat2.emission = glm::vec4( components::_materials[i].emission, components::_materials[i].ns );
mat2.dissolve = components::_materials[i].d;
mat2.ior = components::_materials[i].ni;
mat2.illum = components::_materials[i].illum;
mat2.fuzziness = components::_materials[i].fuzziness;
// Set up texture
/// TODO: move STB process to a dedicated function
if ( !components::_materials[i].diffuseTexPath.empty( ) )
{
mat2.diffuse.w = static_cast<float>( components::textureIndex );
auto texture = std::make_shared<vkCore::Texture>( );
std::string path = components::assetsPath + components::_materials[i].diffuseTexPath;
int width;
int height;
int channels;
stbi_uc* pixels = stbi_load( path.c_str( ), &width, &height, &channels, STBI_rgb_alpha );
if ( pixels == nullptr )
{
RX_ERROR( "Failed to load texture from ", path );
}
texture->init<stbi_uc>( path, pixels, width, height );
stbi_image_free( pixels );
_textures[components::textureIndex++] = texture;
}
memAlignedMaterials.push_back( mat2 );
}
// upload materials
_materialBuffers.upload( memAlignedMaterials );
for ( size_t i = 0; i < _geometries.size( ); ++i )
{
if ( i < _geometries.size( ) )
{
if ( _geometries[i] != nullptr )
{
if ( !_geometries[i]->initialized )
{
// Only keep one copy of both index and vertex buffers each.
_vertexBuffers[i].init( _geometries[i]->vertices, 2, true );
_indexBuffers[i].init( _geometries[i]->indices, 2, true );
_materialIndexBuffers[i].init( _geometries[i]->matIndex, 2, true );
_geometries[i]->initialized = true;
RX_SUCCESS( "Initialized Geometries." );
}
}
}
}
RX_SUCCESS( "Uploaded Geometries." );
}
void Scene::uploadGeometryInstances( )
{
if ( _settings->_maxGeometryInstancesChanged )
{
_settings->_maxGeometryInstancesChanged = false;
std::vector<GeometryInstanceSSBO> geometryInstances( _settings->_maxGeometryInstances );
_geometryInstancesBuffer.init( geometryInstances, components::maxResources );
updateSceneDescriptors( );
}
_uploadGeometryInstancesToBuffer = false;
memAlignedGeometryInstances.resize( _geometryInstances.size( ) );
std::transform( _geometryInstances.begin( ), _geometryInstances.end( ), memAlignedGeometryInstances.begin( ),
[]( std::shared_ptr<GeometryInstance> instance ) { return GeometryInstanceSSBO { instance->transform,
instance->geometryIndex }; } );
_geometryInstancesBuffer.upload( memAlignedGeometryInstances );
RX_SUCCESS( "Uploaded geometry instances." );
}
void Scene::translateDummy( )
{
auto dummyInstance = getGeometryInstance( triangle->geometryIndex );
auto camPos = _currentCamera->getPosition( );
dummyInstance->setTransform( glm::translate( glm::mat4( 1.0F ), glm::vec3( camPos.x, camPos.y, camPos.z + 2.0F ) ) );
}
void Scene::addDummy( )
{
_dummy = true;
Vertex v1;
v1.normal = glm::vec3( 0.0F, 1.0F, 0.0F );
v1.pos = glm::vec3( -0.00001F, 0.0F, 0.00001F );
Vertex v2;
v2.normal = glm::vec3( 0.0F, 1.0F, 0.0F );
v2.pos = glm::vec3( 0.00001F, 0.0F, 0.00001F );
Vertex v3;
v3.normal = glm::vec3( 0.0F, 1.0F, 0.0F );
v3.pos = glm::vec3( 0.00001F, 0.0F, -0.00001F );
triangle = std::make_shared<Geometry>( );
triangle->vertices = { v1, v2, v3 };
triangle->indices = { 0, 1, 2 };
triangle->geometryIndex = components::geometryIndex++;
triangle->matIndex = { 0 }; // a single triangle for the material buffer
triangle->path = "Custom Dummy Triangle";
triangle->dynamic = true;
Material mat;
triangle->setMaterial( mat );
auto camPos = _currentCamera->getPosition( );
auto transform = glm::translate( glm::mat4( 1.0F ), glm::vec3( camPos.x, camPos.y, camPos.z + 2.0F ) );
triangleInstance = instance( triangle );
submitGeometry( triangle );
submitGeometryInstance( triangleInstance );
RX_VERBOSE( "Scene is empty. Added dummy element." );
}
void Scene::removeDummy( )
{
if ( triangle != nullptr && _geometryInstances.size( ) > 1 )
{
_dummy = false;
RX_VERBOSE( "Removing dummy element." );
removeGeometry( triangle );
triangle = nullptr;
}
}
void Scene::initSceneDescriptorSets( )
{
_sceneDescriptors.bindings.reset( );
// Camera uniform buffer
_sceneDescriptors.bindings.add( 0, vk::DescriptorType::eUniformBuffer, vk::ShaderStageFlagBits::eRaygenKHR | vk::ShaderStageFlagBits::eClosestHitKHR );
// Scene description buffer
_sceneDescriptors.bindings.add( 1, vk::DescriptorType::eStorageBuffer, vk::ShaderStageFlagBits::eClosestHitKHR | vk::ShaderStageFlagBits::eAnyHitKHR );
// Environment map
_sceneDescriptors.bindings.add( 2, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eMissKHR );
_sceneDescriptors.layout = _sceneDescriptors.bindings.initLayoutUnique( );
_sceneDescriptors.pool = _sceneDescriptors.bindings.initPoolUnique( components::maxResources );
_sceneDescriptorsets = vkCore::allocateDescriptorSets( _sceneDescriptors.pool.get( ), _sceneDescriptors.layout.get( ) );
}
void Scene::initGeoemtryDescriptorSets( )
{
_geometryDescriptors.bindings.reset( );
// Vertex buffers
_geometryDescriptors.bindings.add( 0,
vk::DescriptorType::eStorageBuffer,
vk::ShaderStageFlagBits::eClosestHitKHR,
_settings->_maxGeometry,
vk::DescriptorBindingFlagBits::eUpdateAfterBind );
// Index buffers
_geometryDescriptors.bindings.add( 1,
vk::DescriptorType::eStorageBuffer,
vk::ShaderStageFlagBits::eClosestHitKHR,
_settings->_maxGeometry,
vk::DescriptorBindingFlagBits::eUpdateAfterBind );
// MatIndex buffers
_geometryDescriptors.bindings.add( 2,
vk::DescriptorType::eStorageBuffer,
vk::ShaderStageFlagBits::eClosestHitKHR | vk::ShaderStageFlagBits::eAnyHitKHR,
_settings->_maxGeometry,
vk::DescriptorBindingFlagBits::eUpdateAfterBind );
// Textures
if ( !_immutableSampler )
{
_immutableSampler = vkCore::initSamplerUnique( vkCore::getSamplerCreateInfo( ) );
}
std::vector<vk::Sampler> immutableSamplers( _settings->_maxTextures );
for ( auto& immutableSampler : immutableSamplers )
{
immutableSampler = _immutableSampler.get( );
}
_geometryDescriptors.bindings.add( 3,
vk::DescriptorType::eCombinedImageSampler,
vk::ShaderStageFlagBits::eClosestHitKHR,
_settings->_maxTextures,
vk::DescriptorBindingFlagBits::eUpdateAfterBind,
immutableSamplers.data( ) );
_geometryDescriptors.bindings.add( 4,
vk::DescriptorType::eStorageBuffer,
vk::ShaderStageFlagBits::eClosestHitKHR | vk::ShaderStageFlagBits::eAnyHitKHR,
1,
vk::DescriptorBindingFlagBits::eUpdateAfterBind );
_geometryDescriptors.layout = _geometryDescriptors.bindings.initLayoutUnique( vk::DescriptorSetLayoutCreateFlagBits::eUpdateAfterBindPool );
_geometryDescriptors.pool = _geometryDescriptors.bindings.initPoolUnique( vkCore::global::swapchainImageCount, vk::DescriptorPoolCreateFlagBits::eUpdateAfterBind );
_geometryDescriptorSets = vkCore::allocateDescriptorSets( _geometryDescriptors.pool.get( ), _geometryDescriptors.layout.get( ) );
}
void Scene::updateSceneDescriptors( )
{
// Environment map
vk::DescriptorImageInfo environmentMapTextureInfo;
if ( _environmentMap.getImageView( ) && _environmentMap.getSampler( ) )
{
environmentMapTextureInfo.imageLayout = _environmentMap.getLayout( );
environmentMapTextureInfo.imageView = _environmentMap.getImageView( );
environmentMapTextureInfo.sampler = _environmentMap.getSampler( );
}
else
{
RX_FATAL( "No default environment map provided." );
}
_sceneDescriptors.bindings.writeArray( _sceneDescriptorsets, 0, _cameraUniformBuffer._bufferInfos.data( ) );
_sceneDescriptors.bindings.writeArray( _sceneDescriptorsets, 1, _geometryInstancesBuffer.getDescriptorInfos( ).data( ) );
_sceneDescriptors.bindings.write( _sceneDescriptorsets, 2, &environmentMapTextureInfo );
_sceneDescriptors.bindings.update( );
}
void Scene::updateGeoemtryDescriptors( )
{
RX_ASSERT( _geometries.size( ) <= _settings->_maxGeometry, "Can not bind more than ", _settings->_maxGeometry, " geometries." );
RX_ASSERT( _vertexBuffers.size( ) == _settings->_maxGeometry, "Vertex buffers container size and geometry limit must be identical." );
RX_ASSERT( _indexBuffers.size( ) == _settings->_maxGeometry, "Index buffers container size and geometry limit must be identical." );
RX_ASSERT( _textures.size( ) == _settings->_maxTextures, "Texture container size and texture limit must be identical." );
// Vertex buffers infos
std::vector<vk::DescriptorBufferInfo> vertexBufferInfos;
vertexBufferInfos.reserve( _vertexBuffers.size( ) );
for ( const auto& vertexBuffer : _vertexBuffers )
{
vk::DescriptorBufferInfo vertexDataBufferInfo( vertexBuffer.get( ).empty( ) ? nullptr : vertexBuffer.get( 0 ),
0,
VK_WHOLE_SIZE );
vertexBufferInfos.push_back( vertexDataBufferInfo );
}
// Index buffers infos
std::vector<vk::DescriptorBufferInfo> indexBufferInfos;
indexBufferInfos.reserve( _indexBuffers.size( ) );
for ( const auto& indexBuffer : _indexBuffers )
{
vk::DescriptorBufferInfo indexDataBufferInfo( indexBuffer.get( ).empty( ) ? nullptr : indexBuffer.get( 0 ),
0,
VK_WHOLE_SIZE );
indexBufferInfos.push_back( indexDataBufferInfo );
}
// MatIndices infos
std::vector<vk::DescriptorBufferInfo> matIndexBufferInfos;
matIndexBufferInfos.reserve( _materialIndexBuffers.size( ) );
for ( const auto& materialIndexBuffer : _materialIndexBuffers )
{
vk::DescriptorBufferInfo materialIndexDataBufferInfo( materialIndexBuffer.get( ).empty( ) ? nullptr : materialIndexBuffer.get( 0 ),
0,
VK_WHOLE_SIZE );
matIndexBufferInfos.push_back( materialIndexDataBufferInfo );
}
// Texture samplers
std::vector<vk::DescriptorImageInfo> textureInfos;
textureInfos.reserve( _textures.size( ) );
for ( size_t i = 0; i < _settings->_maxTextures; ++i )
{
vk::DescriptorImageInfo textureInfo = { };
if ( _textures[i] != nullptr )
{
textureInfo.imageLayout = _textures[i]->getLayout( );
textureInfo.imageView = _textures[i]->getImageView( );
textureInfo.sampler = _immutableSampler.get( );
}
else
{
textureInfo.imageLayout = { };
textureInfo.sampler = _immutableSampler.get( );
}
textureInfos.push_back( textureInfo );
}
// Write to and update descriptor bindings
_geometryDescriptors.bindings.writeArray( _geometryDescriptorSets, 0, vertexBufferInfos.data( ) );
_geometryDescriptors.bindings.writeArray( _geometryDescriptorSets, 1, indexBufferInfos.data( ) );
_geometryDescriptors.bindings.writeArray( _geometryDescriptorSets, 2, matIndexBufferInfos.data( ) ); // matIndices
_geometryDescriptors.bindings.writeArray( _geometryDescriptorSets, 3, textureInfos.data( ) );
_geometryDescriptors.bindings.writeArray( _geometryDescriptorSets, 4, _materialBuffers.getDescriptorInfos( ).data( ) ); // materials
_geometryDescriptors.bindings.update( );
}
void Scene::upload( vk::Fence fence, uint32_t imageIndex )
{
}
} // namespace RAYEX_NAMESPACE
| 33.576438 | 251 | 0.639223 | chillpert |
ddd0a91af586334670d6a6b91d1ff92e5e6a002d | 5,374 | cpp | C++ | src/mesh.cpp | hippo-o-matic/telabrium | 9f7e6db3540372e43a555ac0b6c6bc457c39fad2 | [
"MIT"
] | null | null | null | src/mesh.cpp | hippo-o-matic/telabrium | 9f7e6db3540372e43a555ac0b6c6bc457c39fad2 | [
"MIT"
] | null | null | null | src/mesh.cpp | hippo-o-matic/telabrium | 9f7e6db3540372e43a555ac0b6c6bc457c39fad2 | [
"MIT"
] | null | null | null | #include "telabrium/mesh.h"
std::vector<Mesh*> Mesh::meshes{};
Mesh::Mesh(std::vector<Vertex> vertices, std::vector<unsigned int> indices, std::vector<Texture> texs, std::vector<std::shared_ptr<Material>> mats, glm::mat4 transform){
this->vertices = vertices;
this->indices = indices;
this->textures = texs;
this->materials = mats;
this->transform = transform;
setTransform(transform);
meshes.push_back(this);
// now that we have all the required data, set the vertex buffers and its attribute pointers.
setupMesh();
}
Mesh::~Mesh() {
meshes.erase(std::find(meshes.begin(), meshes.end(), this));
}
// render the mesh
void Mesh::Draw(Shader &shader){
// TODO: restructure using buffers or smthing so we can send multiple textures of one type, not just the last one
// Bind all textures
unsigned tex_unit = GL_TEXTURE0;
for(auto it : textures) {
glActiveTexture(tex_unit);
shader.set((it.type).c_str(), (int)tex_unit);
if(it.type == "texture_cubemap") {
glBindTexture(GL_TEXTURE_CUBE_MAP, it.glID);
} else {
glBindTexture(GL_TEXTURE_2D, it.glID);
}
tex_unit++;
}
// Send material data
shader.set("model", getWorldTransform());
// draw mesh
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
// Cleanup
glBindVertexArray(0);
glActiveTexture(GL_TEXTURE0);
}
// initializes all the buffer objects/arrays
void Mesh::setupMesh(){
// create buffers/arrays
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
// load data into vertex buffers
glBindBuffer(GL_ARRAY_BUFFER, VBO);
// A great thing about structs is that their memory layout is sequential for all its items.
// The effect is that we can simply pass a pointer to the struct and it translates perfectly to a glm::vec3/2 array which
// again translates to 3/2 floats which translates to a byte array.
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW);
// set the vertex attribute pointers
// vertex Positions
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
// vertex normals
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Normal));
// vertex texture coords
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, TexCoords));
// vertex tangent
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Tangent));
// vertex bitangent
glEnableVertexAttribArray(4);
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Bitangent));
glBindVertexArray(0);
}
std::vector<Vertex> calcVertex(const std::vector<float> &verticies, const std::vector<float> &texcoords) {
std::vector<Vertex> v;
// Establish some empty Vertex structs
for(long unsigned int i=0; i < verticies.size() / 3; i++){
v.push_back(Vertex());
}
// Put all the vertex coords into the vertex vector
for(long unsigned int i = 0, j = 0; i <= v.size(); i++, j+=3) {
v[i].pos = glm::vec3(verticies[j], verticies[j+1], verticies[j+2]);
}
// Calculate vertex normals,
for(long unsigned int i=0, j=0; i <= v.size(); i++, j+=3){ //The i + 3 is to make sure we don't go past where there are values
glm::vec3 U(v[j+1].pos - v[j].pos);
glm::vec3 V(v[j+2].pos - v[j].pos);
glm::vec3 N(
U.y*V.z - U.z*V.y,
U.z*V.x - U.x*V.z,
U.x*V.y - U.y*V.x
);
v[i].Normal = N;
}
// Generate texcoords if there are none
if (texcoords.empty()){
for(long unsigned int i=0; i + 4 <= v.size(); i+=4){
v[i].TexCoords = glm::vec2(0, 0);
v[i+1].TexCoords = glm::vec2(1, 0);
v[i+2].TexCoords = glm::vec2(1, 1);
v[i+3].TexCoords = glm::vec2(0, 1);
}
} else {
for(long unsigned int i=0; i < v.size(); i++){
v[i].TexCoords = glm::vec2(texcoords[i], texcoords[i+1]);
}
}
// Calculate the tangent and bitangents for each triangle
for(long unsigned int i=0; i + 2 < v.size(); i+=3){
glm::vec3 edge1 = v[i+1].pos - v[i].pos;
glm::vec3 edge2 = v[i+2].pos - v[i].pos;
glm::vec2 delta1 = v[i+1].TexCoords - v[i].TexCoords;
glm::vec2 delta2 = v[i+2].TexCoords - v[i].TexCoords;
// Scary math
float f = 1.0f / (delta1.x * delta2.y - delta2.x * delta1.y);
v[i].Tangent.x = f * (delta2.y * edge1.x - delta1.y * edge2.x);
v[i].Tangent.y = f * (delta2.y * edge1.y - delta1.y * edge2.y);
v[i].Tangent.z = f * (delta2.y * edge1.z - delta1.y * edge2.z);
v[i].Tangent = glm::normalize(v[i].Tangent);
v[i+1].Tangent = v[i].Tangent;
v[i+2].Tangent = v[i].Tangent;
v[i].Bitangent.x = f * (-delta2.x * edge1.x + delta1.x * edge2.x);
v[i].Bitangent.y = f * (-delta2.x * edge1.y + delta1.x * edge2.y);
v[i].Bitangent.z = f * (-delta2.x * edge1.z + delta1.x * edge2.z);
v[i].Bitangent = glm::normalize(v[i].Bitangent);
v[i+1].Bitangent = v[i].Bitangent;
v[i+2].Bitangent = v[i].Bitangent;
}
return v;
} | 34.012658 | 170 | 0.654447 | hippo-o-matic |
ddd8060da9c848e4177eda87f82979824d44aee8 | 7,696 | cpp | C++ | chart/svg.cpp | 5r1gsOi1/other | 16da2846da4f80cdbccf0232696301c50c10c005 | [
"MIT"
] | null | null | null | chart/svg.cpp | 5r1gsOi1/other | 16da2846da4f80cdbccf0232696301c50c10c005 | [
"MIT"
] | null | null | null | chart/svg.cpp | 5r1gsOi1/other | 16da2846da4f80cdbccf0232696301c50c10c005 | [
"MIT"
] | null | null | null |
#include "svg.h"
svg::Text::Text(const std::string &text, const Point<double> &p,
const Point<double> &d, const svg::Attributes &font,
const svg::Attributes &fill)
: text_(text), p_(p), d_(d) {
name = "text";
attributes.insert(font.begin(), font.end());
attributes.insert(fill.begin(), fill.end());
children.push_back(std::make_unique<PlainText>(text));
}
void svg::Text::OutputAttributes(std::ostream &s) const {
Tag::OutputAttributes(s);
s << " x=\"" << p_.x << "\" y=\"" << p_.y << "\"";
if (d_.x != 0.) {
s << " dx=\"" << d_.x << "\"";
}
if (d_.y != 0.) {
s << "dy =\"" << d_.y << "\"";
}
}
svg::Line::Line(const Point<double> &p1, const Point<double> &p2,
const svg::Attributes &stroke)
: p1_(p1), p2_(p2) {
name = "line";
attributes.insert(stroke.begin(), stroke.end());
}
void svg::Line::OutputAttributes(std::ostream &s) const {
Tag::OutputAttributes(s);
s << " x1=\"" << p1_.x << "\" y1=\"" << p1_.y << "\"";
s << " x2=\"" << p2_.x << "\" y2=\"" << p2_.y << "\"";
}
svg::Rect::Rect(const Point<double> p, const Point<double> size,
const svg::Attributes &attributes_)
: p_(p), size_(size) {
name = "rect";
attributes = attributes_;
}
svg::Rect::Rect(const PointArea area, const svg::Attributes &attributes_)
: svg::Rect::Rect(area.min, {area.width(), area.height()}, attributes_) {}
void svg::Rect::OutputAttributes(std::ostream &s) const {
Tag::OutputAttributes(s);
s << " x=\"" << p_.x << "\" y=\"" << p_.y << "\"";
s << " width=\"" << size_.x << "\" height=\"" << size_.y << "\"";
}
svg::Path::Path(const std::vector<std::pair<Point<double>, char>> &points,
const svg::Attributes &attributes_)
: points_(points) {
Path::name = "path";
attributes = attributes_;
}
svg::Path::Path(const std::vector<Point<double>> &points,
const svg::Attributes &attributes_) {
points_.reserve(points.size());
for (auto &p : points) {
points_.push_back(std::make_pair(p, '\0'));
}
if (not points_.empty()) {
points_.begin()->second = 'M';
}
Path::name = "path";
attributes = attributes_;
}
void svg::Path::OutputAttributes(std::ostream &s) const {
Tag::OutputAttributes(s);
if (not points_.empty()) {
std::ios init(nullptr);
init.copyfmt(s);
constexpr const int p{1};
s << " d=\"";
for (auto it = points_.begin(); it != points_.end(); ++it) {
if (it->second != '\0') {
s << it->second << " ";
}
s << std::setprecision(p) << std::fixed << it->first.x << ","
<< std::setprecision(p) << std::fixed << it->first.y << " ";
}
s << "\"";
s.copyfmt(init);
}
}
void svg::Path::OutToStream(std::ostream &s, const int indent) const {
if (not this->points_.empty()) {
Tag::OutToStream(s, indent);
}
}
svg::Title::Title(const std::string &title) {
name = "title";
children.push_back(std::make_unique<PlainText>(title));
}
void svg::Tag::OutputAttributes(std::ostream &s) const {
for (auto &i : attributes) {
s << " " << i.first << "=\"" << static_cast<std::string>(i.second) << "\"";
}
}
void svg::Tag::OutputChildren(std::ostream &s, const int indent) const {
for (auto &i : children) {
if (i->IsOnASeparateLine()) {
i->OutToStream(s, indent);
} else {
i->OutToStream(s);
}
}
}
void svg::Tag::OutToStream(std::ostream &s, const int indent) const {
s << std::string(indent, ' ') << "<" << name;
OutputAttributes(s);
if (not children.empty()) {
s << ">";
bool need_line_break = false;
for (auto &i : children) {
if (i->IsOnASeparateLine()) {
need_line_break = true;
}
}
if (need_line_break) {
s << std::endl;
}
OutputChildren(s, indent + indent_delta);
if (need_line_break) {
s << std::string(indent, ' ');
}
s << "</" << name << ">\n";
} else {
s << "/>\n";
}
}
void svg::Tag::AddChild(svg::Base *child) {
children.push_back(std::unique_ptr<Base>(child));
}
svg::PlainText::PlainText(const std::string &text) : text_(text) {}
bool svg::PlainText::IsOnASeparateLine() const { return false; }
void svg::PlainText::OutToStream(std::ostream &s, const int indent) const {
std::ignore = indent;
s << text_;
}
svg::PlainText::~PlainText() = default;
svg::Attributes svg::CreateFillAttributes(const std::string &color,
const std::string &rule,
const std::string &opacity) {
Attributes attributes;
if (not color.empty()) {
attributes.insert({"fill", color});
}
if (not rule.empty()) {
attributes.insert({"fill-rule", rule});
}
if (not opacity.empty()) {
attributes.insert({"fill-opacity", opacity});
}
return attributes;
}
svg::Attributes svg::CreateStrokeAttributes(
const std::string &color, const double width, const std::string &linecap,
const std::string &dash, const std::string &opacity,
const std::string &linejoin, const std::string &vector_effect) {
Attributes attributes;
if (not color.empty()) {
attributes.insert({"stroke", color});
}
attributes.insert({"stroke-width", attributes::FixedPointNumber(width)});
if (not linecap.empty()) {
attributes.insert({"stroke-linecap", linecap});
}
if (not dash.empty()) {
attributes.insert({"stroke-dasharray", dash});
}
if (not opacity.empty()) {
attributes.insert({"stroke-opacity", opacity});
}
if (not linejoin.empty()) {
attributes.insert({"stroke-linejoin", linejoin});
}
if (not vector_effect.empty()) {
attributes.insert({"vector-effect", vector_effect});
} // "non-scaling-stroke"
return attributes;
}
svg::Attributes svg::CreateFontAttributes(const std::string &family,
const double size) {
return svg::Attributes{{"font-family", family},
{"font-size", attributes::FixedPointNumber(size)}};
}
svg::Attributes svg::CreateTransformAttributes(const Point<double> scale,
const Point<double> translate) {
return svg::Attributes{
{"transform", "translate(" + std::to_string(translate.x) + " " +
std::to_string(translate.y) + ") scale(" +
std::to_string(scale.x) + " " +
std::to_string(scale.y) + ")"}};
}
svg::Attributes svg::CreateStandardSvgAttributes(
const Point<double> image_size) {
return Attributes{
{"width", attributes::Pixels(image_size.x)},
{"height", attributes::Pixels(image_size.y)},
{"viewBox", attributes::ViewBox(0, 0, image_size.x, image_size.y)},
{"xmlns", std::string("http://www.w3.org/2000/svg")},
{"version", attributes::FixedPointNumber(1.1)}};
}
svg::Attributes svg::CreateSvgAttributes(const Point<double> position,
const Point<double> size) {
return Attributes{
{"width", attributes::Pixels(size.x)},
{"height", attributes::Pixels(size.y)},
{"x", attributes::Pixels(position.x)},
{"y", attributes::Pixels(position.y)},
};
}
svg::Attributes operator+(const svg::Attributes &a1,
const svg::Attributes &a2) {
svg::Attributes r = a1;
r.insert(a2.begin(), a2.end());
return r;
}
svg::Attributes operator+(svg::Attributes &&a1, const svg::Attributes &a2) {
svg::Attributes r = std::move(a1);
r.insert(a2.begin(), a2.end());
return r;
}
svg::Attributes operator+(const svg::Attributes &a1, svg::Attributes &&a2) {
svg::Attributes r = std::move(a2);
r.insert(a1.begin(), a1.end());
return r;
}
| 30.0625 | 79 | 0.577313 | 5r1gsOi1 |
dddc0efa996e2ed1d7b24fdebd85c2b337fbf75b | 7,646 | cpp | C++ | src/blocks/blocks.cpp | TehPwns/PwnsianCartograph | 1533a63344dc08485c4693c7413b4bc2a9b69bf0 | [
"MIT"
] | 2 | 2019-09-29T10:07:56.000Z | 2020-06-08T17:32:01.000Z | src/blocks/blocks.cpp | jamesrwaugh/PwnsianCartographer | 1533a63344dc08485c4693c7413b4bc2a9b69bf0 | [
"MIT"
] | null | null | null | src/blocks/blocks.cpp | jamesrwaugh/PwnsianCartographer | 1533a63344dc08485c4693c7413b4bc2a9b69bf0 | [
"MIT"
] | null | null | null | #include <fstream>
#include "json11.hpp"
#include "ZipLib/ZipFile.h"
#include "utility/lodepng.h"
#include "utility/utility.h"
#include "blocks/blocks.h"
namespace
{
/* This is a std::map comparison functor that returns
* true if two SDL_Colors are similar. By doing this,
* similar colors can be grouped together */
struct SimilarColorCompare
{
static const int tol = 20;
bool operator()(const SDL_Color& a, const SDL_Color& b)
{
return (abs(a.r-b.r) < tol) && (abs(a.g-b.g) < tol) && (abs(a.b-b.b) < tol);
}
};
}
namespace blocks
{
BlockID::BlockID(unsigned id, unsigned meta)
: id(id), meta(meta)
{
}
BlockID::BlockID(const std::string& string)
{
//Example: "405-3.png" or "405-3"
size_t dashpos = string.find('-'),
dotpos = string.find('.');
/* Note that if dash is not found, ".png" will be passed to
* atoi, but it will consume only the numeric chracters */
id = std::atoi(string.substr(0,dashpos).c_str());
if(dashpos != std::string::npos) {
meta = std::atoi(string.substr(dashpos+1, dotpos).c_str());
}
}
bool BlockID::operator<(const BlockID& other) const
{
if(id < other.id)
return true;
else if(id == other.id)
return (meta < other.meta);
return false;
}
bool BlockID::operator==(const BlockID& other) const
{
return (id == other.id) && (meta == other.meta);
}
bool BlockID::operator!=(const BlockID& other) const
{
return !(*this == other);
}
BlockID::operator std::string() const
{
std::stringstream ss;
ss << id << '-' << meta;
return ss.str();
}
}
namespace blocks
{
BlockColors::BlockColors()
{
rgba = SDL_AllocFormat(SDL_PIXELFORMAT_RGBA8888);
}
BlockColors::~BlockColors()
{
SDL_FreeFormat(rgba);
}
void BlockColors::load(const std::string& zipFileName, const std::string& cacheFileName)
{
using namespace json11;
//Keep filenames for later
this->zipFileName = zipFileName;
this->cacheFileName = cacheFileName;
//Zip file interface
auto archive = ZipFile::Open(zipFileName);
//Cache JSON. This is a single { } of key:value of "blockid-meta" to .zip CRC and RGBA color
// ex: {"2-4": {"crc": 5234231, "color": 2489974272}, ... }
std::string parseErr;
Json cacheJson = Json::parse(readFile(cacheFileName), parseErr);
if(!parseErr.empty()) {
log("Could not read cache \"", cacheFileName, "\": ", parseErr);
}
/* Will be true if computeColor is called, basically if cache is missing
* or CRC changed in zip for any file */
bool hadToRecompute = false;
for(unsigned i = 0; i != archive->GetEntriesCount(); ++i)
{
/* Name and CRC of the block image in .zip
* substr on the name is used to cut off the .png at the end */
auto entry = archive->GetEntry(i);
unsigned zipcrc = entry->GetCrc32();
std::string name = entry->GetName();
name = name.substr(0, name.find('.'));
/* To get a block color, first the cache is checked.
* if it's not there, the color is recomputed. If that happens,
* "hadToRecompute" is set to true, and a new .json cache will be written out */
Json key = cacheJson[name];
if(key.is_null()) {
//Look for key with a 0 meta. e.g, "404-0" and not "404"
std::string nameWithMeta = name + "-0";
key = cacheJson[nameWithMeta];
}
SDL_Color blockColor;
if(key.is_object() && (unsigned)key["crc"].int_value() == zipcrc) {
Uint32 cachePixel = key["color"].int_value();
SDL_GetRGBA(cachePixel, rgba, &blockColor.r, &blockColor.g, &blockColor.b, &blockColor.a);
} else {
blockColor = computeColor(entry);
hadToRecompute = true;
}
//Store color and CRC in this object
blockColors[name] = std::make_pair(blockColor, zipcrc);
}
//If any blocks were not found in cache
if(hadToRecompute) {
saveNewJsonCache();
}
}
bool BlockColors::isLoaded() const
{
return isLoaded();
}
SDL_Color BlockColors::computeColor(const ZipArchiveEntry::Ptr& blockImage)
{
/* computeColor method: For each non-transparent pixel,
* count the number of times the pixel color has appeared, grouping
* similarly-colored pixels. The highest counted is the color for the block*/
//Get the raw PNG data from the .zip, and decode it into pixels
std::vector<char> pngBytes = readZipEntry(blockImage);
std::vector<unsigned char> pixels;
unsigned w = 0, h = 0;
lodepng::decode(pixels, w, h, (const unsigned char*)pngBytes.data(), pngBytes.size());
/* A map of {color -> use counts}. By using SimilarColorCompare as the comparison,
* similar colors are said to be equal, "averaging" the colors */
std::map<SDL_Color, unsigned, SimilarColorCompare> colorCounts;
/* Record non-transparent colors. The recorded color is the RGA value with 255 alpha
* To prevent solid blocks like grass having transparency because the
* first zero-alpha pixel being not 255 alpha */
for(unsigned i = 0; i != pixels.size(); i += 4)
{
Uint8 r, g, b, a;
r = pixels[i+0];
g = pixels[i+1];
b = pixels[i+2];
a = pixels[i+3];
if(a != SDL_ALPHA_TRANSPARENT) {
colorCounts[ SDL_Color{r, g, b, SDL_ALPHA_OPAQUE} ] += 1;
}
}
//Get iterator to element in map with most use counts
auto it = std::max_element(colorCounts.begin(), colorCounts.end(),
[](auto& pair0, auto& pair1) { return pair0.second < pair1.second; });
//Return key type at that iterator; the color
return it->first;
}
std::vector<char> BlockColors::readZipEntry(const ZipArchiveEntry::Ptr& blockImage)
{
//This is different from readStream, size needs to be gotten this way
size_t size = blockImage->GetSize();
std::vector<char> content(size);
//Read "size" bytes into string
std::istream* stream = blockImage->GetDecompressionStream();
stream->read(content.data(), size);
return content;
}
void BlockColors::saveNewJsonCache() const
{
std::ofstream file(cacheFileName);
if(!file.is_open()) {
error("Could not open ", cacheFileName, " for writing new cahce");
}
json11::Json::object root;
for(const auto& pair : blockColors)
{
std::string id = pair.first; //BlockID -> string conversion
const auto& value = pair.second;
//Convience
SDL_Color color = value.first;
unsigned crc = value.second;
Uint32 pixel = SDL_MapRGBA(rgba, color.r, color.g, color.b, color.a);
root.insert(
{ id, json11::Json::object{{"crc",(int)crc}, {"color",(int)pixel}} }
);
}
file << json11::Json(root).dump() << std::endl;
file.close();
}
SDL_Color BlockColors::getBlockColor(unsigned id, unsigned meta) const
{
return getBlockColor(BlockID{id,meta});
}
SDL_Color BlockColors::getBlockColor(const BlockID& blockid) const
{
auto it = blockColors.find(blockid);
if(it != blockColors.end()) {
return it->second.first;
} else {
/* Base recursive case, if meta 0 isn't found, we safely
* say we don't know the block */
if(blockid.meta == 0) {
return SDL_Color{255, 20, 147, 255}; //Unknown color
}
/* If not found, check if we have the block with no metadata.
* This helps cases like crops and rotated stairs which metadata
* doesn't determine color, only break color*/
return getBlockColor(blockid.id, 0);
}
}
}
| 28.636704 | 102 | 0.62451 | TehPwns |
ddde8814f7d88f245f52a933fb352c08d4e86293 | 1,310 | cpp | C++ | core/src/scene/spriteAtlas.cpp | flyskyosg/tangram-es | 7d0d7297485fdb388455b15810690c1568bdbedb | [
"MIT"
] | null | null | null | core/src/scene/spriteAtlas.cpp | flyskyosg/tangram-es | 7d0d7297485fdb388455b15810690c1568bdbedb | [
"MIT"
] | 1 | 2020-10-09T21:57:12.000Z | 2020-10-09T21:57:12.000Z | core/src/scene/spriteAtlas.cpp | quitejonny/tangram-es | b457b7fc59e3e0f3c6d7bc26a0b5fe62098376fb | [
"MIT"
] | 1 | 2019-08-31T14:43:29.000Z | 2019-08-31T14:43:29.000Z | #include "scene/spriteAtlas.h"
#include "platform.h"
namespace Tangram {
SpriteAtlas::SpriteAtlas(std::shared_ptr<Texture> _texture) : m_texture(_texture) {}
void SpriteAtlas::addSpriteNode(const std::string& _name, glm::vec2 _origin, glm::vec2 _size) {
float atlasWidth = m_texture->getWidth();
float atlasHeight = m_texture->getHeight();
float uvL = _origin.x / atlasWidth;
float uvR = uvL + _size.x / atlasWidth;
float uvB = 1.f - _origin.y / atlasHeight;
float uvT = uvB - _size.y / atlasHeight;
m_spritesNodes[_name] = SpriteNode { { uvL, uvB }, { uvR, uvT }, _size, _origin };
}
bool SpriteAtlas::getSpriteNode(const std::string& _name, SpriteNode& _node) const {
auto it = m_spritesNodes.find(_name);
if (it == m_spritesNodes.end()) {
return false;
}
_node = it->second;
return true;
}
void SpriteAtlas::updateSpriteNodes(std::shared_ptr<Texture> _texture) {
m_texture = _texture;
for (auto& spriteNode : m_spritesNodes) {
// Use the origin of the spriteNode set when the node was created
addSpriteNode(spriteNode.first.k, spriteNode.second.m_origin, spriteNode.second.m_size);
}
}
void SpriteAtlas::bind(RenderState& rs, GLuint _slot) {
m_texture->update(rs, _slot);
m_texture->bind(rs, _slot);
}
}
| 29.111111 | 96 | 0.683206 | flyskyosg |
50b19e19646e237e6d85ddbf8d5ba26389c7cc86 | 4,245 | hpp | C++ | src/apps/avsinfo/item.hpp | januswel/avsutil | 417a07e794a4ec7549dc8453407d541755bb4bb3 | [
"MIT"
] | null | null | null | src/apps/avsinfo/item.hpp | januswel/avsutil | 417a07e794a4ec7549dc8453407d541755bb4bb3 | [
"MIT"
] | 1 | 2015-01-05T15:45:31.000Z | 2015-01-05T15:45:31.000Z | src/apps/avsinfo/item.hpp | januswel/avsutil | 417a07e794a4ec7549dc8453407d541755bb4bb3 | [
"MIT"
] | null | null | null | /*
* item.hpp
* Declarations and definitions for the classes to format and show data
*
* Copyright (C) 2010 janus_wel<janus.wel.3@gmail.com>
* see LICENSE for redistributing, modifying, and so on.
* */
#ifndef ITEM_HPP
#define ITEM_HPP
#include "../../helper/typeconv.hpp"
#include "../../helper/observer.hpp"
#include <locale>
namespace avsinfo {
namespace items {
// formating traits
template<typename Char> struct format_default_traits;
template<> struct format_default_traits<char> {
typedef char char_type;
static const unsigned int header_margin = 24;
static bool is_alignment(void) { return true; }
static bool is_preceding_delimiter(void) { return true; }
static const char_type* delimiter(void) { return ": "; }
static bool is_unit(void) { return true; }
};
template<> struct format_default_traits<wchar_t> {
typedef wchar_t char_type;
static const unsigned int header_margin = 24;
static bool is_alignment(void) { return true; }
static bool is_preceding_delimiter(void) { return true; }
static const char_type* delimiter(void) { return L": "; }
static bool is_unit(void) { return true; }
};
// the base class to represent an item to show
template<
typename Info, typename Char,
typename FormatTraits = format_default_traits<Char> >
class basic_item : public pattern::observer::basic_observer<bool> {
public:
typedef Info info_type;
typedef Char char_type;
typedef std::basic_string<char_type> string_type;
typedef std::basic_stringstream<char_type> stringstream_type;
protected:
// member variables
bool is_human_friendly;
static util::string::typeconverter& tconv(void) {
static util::string::typeconverter
tconv(std::locale::classic());
return tconv;
}
static stringstream_type& ss(void) {
static std::stringstream ss;
return ss;
}
// virtual functions
// these functions determine the content to be outputed
virtual const char_type* header(void) const = 0;
virtual const char_type* unit(void) const = 0;
virtual string_type value(const info_type&) const = 0;
public:
// implementations for virtual function of the super class
// pattern::observer::basic_observer
void update_state(const state_type& s) {
is_human_friendly = s;
}
// destructor
virtual ~basic_item(void) {}
// convert informations to string
string_type to_string(const info_type& info) const {
if (!is_human_friendly) {
return value(info);
}
ss().clear();
ss().str("");
if (FormatTraits::is_alignment()) {
ss()
<< std::left
<< std::setw(FormatTraits::header_margin);
if (FormatTraits::is_preceding_delimiter()) {
ss()
<< string_type(header())
+ FormatTraits::delimiter();
}
else {
ss() << header() << FormatTraits::delimiter();
}
}
else {
ss() << header() << FormatTraits::delimiter();
}
ss() << value(info);
if (FormatTraits::is_unit()) ss() << unit();
return ss().str();
}
};
}
}
#endif // ITEM_HPP
| 36.594828 | 78 | 0.487868 | januswel |
50b31a428465b311f3c9df5a4f0f2133d7972adb | 3,479 | hpp | C++ | code/include/terrain/Seed.hpp | Shutter-Island-Team/Shutter-island | c5e7c0b2c60c34055e64104dcbc396b9e1635f33 | [
"MIT"
] | 4 | 2016-06-24T09:22:18.000Z | 2019-06-13T13:50:53.000Z | code/include/terrain/Seed.hpp | Shutter-Island-Team/Shutter-island | c5e7c0b2c60c34055e64104dcbc396b9e1635f33 | [
"MIT"
] | null | null | null | code/include/terrain/Seed.hpp | Shutter-Island-Team/Shutter-island | c5e7c0b2c60c34055e64104dcbc396b9e1635f33 | [
"MIT"
] | 2 | 2016-06-10T12:46:17.000Z | 2018-10-14T06:37:21.000Z | /**
* @file Seed.hpp
*
* @brief Everything related to a seed of the map
*/
#ifndef SEED_HPP
#define SEED_HPP
#include "Biome.hpp"
#include "../../lib/voro++/src/voro++.hh"
#include <memory>
#include <utility>
/**
* @brief
* Representing a bi-dimensional vertex by a pair of float.
*/
typedef std::pair<float, float> Vertex2D;
/**
* @brief
* Typedef of the shared_pointers onto the "voronoicell_neighbor"
* class defined in "voro++".
*/
typedef std::shared_ptr<voro::voronoicell_neighbor> voroNeighborPtr;
/**
* @brief
* The Seed class represents a point of the considered constrained plane
* used to generate a Voronoi diagram.
* In other word, from a seed will blossom a Voronoi cell in the generated
* Voronoi diagram.
*/
class Seed {
public:
/**
* @brief
* Default constructor.
*/
Seed();
/**
* @brief Constructor
*
* @param x Abscissa of the seed
* @param y Ordinna of the seed
* @param biome Type of the biome (default : Undefined)
*/
Seed(float x, float y, Biome biome = Undefined);
/**
* @brief Copy constructor
*
* @param seed The Seed to copy in order to initialize the
* current Seed.
*/
Seed(const Seed& seed);
/**
* @brief Setter on the abscissa of the seed
*
* @param newX The new abscissa
*/
void setX(float newX);
/**
* @brief Getter on the abscissa of the seed
*
* @return The abscissa
*/
float getX() const;
/**
* @brief Setter on the ordinna of the seed
*
* @param newY The new ordinna
*/
void setY(float newY);
/**
* @brief Getter on the ordinna of the seed
*
* @return The ordinna
*/
float getY() const;
/**
* @brief Setter on the abscissa of the centroid of the seed
*
* @param newX The new abscissa
*/
void setCentroidX(float newX);
/**
* @brief Getter on the abscissa of the centroid of the seed
*
* @return The abscissa
*/
float getCentroidX() const;
/**
* @brief Setter on the ordinna of the centroid of the seed
*
* @param newY The new ordinna
*/
void setCentroidY(float newY);
/**
* @brief Getter on the ordinna of the centroid of the seed
*
* @return The ordinna
*/
float getCentroidY() const;
/**
* @brief Setter on the biome of the seed
*
* @param newBiome The new biome
*/
void setBiome(Biome newBiome);
/**
* @brief Getter on the Biome of the seed
*
* @return The biome
*/
Biome getBiome() const;
/**
* @brief Setter for the cell of the seed
*
* @param newCell The new cell
*/
void setCell(voroNeighborPtr newCell);
/**
* @brief Getter on the cell of the seed
*
* @return A copy of the cell
*/
voroNeighborPtr getCell() const;
/**
* @brief Overrides the assignment operator.
*
* @param seed The Seed to assign to the calling Seed.
* @return The assigned seed.
*/
Seed& operator = (const Seed& seed);
/**
* @brief Destroyer
*/
~Seed();
private:
/// @brief The position of the seed.
Vertex2D position;
/// @brief The centroid associated with the seed.
Vertex2D centroid;
/// @brief The type of the biome of the seed.
Biome biomeType;
/// @brief The cell.
voroNeighborPtr cell;
};
#endif
| 19.435754 | 75 | 0.586663 | Shutter-Island-Team |
50b39fc44ab63a6ea19a9c136f69b6861a151226 | 2,719 | cpp | C++ | 9_stacks/53_postfix_evaluation.cpp | meyash/dust | 8f90d7f9cc42f61193c737cde14e9c4bb32884b4 | [
"MIT"
] | 1 | 2020-09-30T10:36:06.000Z | 2020-09-30T10:36:06.000Z | 9_stacks/53_postfix_evaluation.cpp | meyash/dust | 8f90d7f9cc42f61193c737cde14e9c4bb32884b4 | [
"MIT"
] | null | null | null | 9_stacks/53_postfix_evaluation.cpp | meyash/dust | 8f90d7f9cc42f61193c737cde14e9c4bb32884b4 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
// program for evaluating a postfix expression
class Stack{
private:
int size;
int top;
int *s;
public:
Stack(){
top=-1;
}
Stack(int size){
this->size=size;
s=new int[size];
top=-1;
}
~Stack(){
delete s;
}
void push(int x){
if(top>=size-1){
cout<<"Stack Full!"<<endl;
return;
}
top=top+1;
s[top]=x;
cout<<"Pushed : "<<x<<" at index : "<<top<<endl;
}
int pop(){
if(top<0){
cout<<"Stack empty already!"<<endl;
return 0;
}
int bakup=s[top];
top=top-1;
cout<<"Popped : "<<bakup<<" from index : "<<top+1<<endl;
return bakup;
}
void peek(int index){
if(index<=0||index>top){
cout<<"Invalid index!"<<endl;
return;
}
int bakup=top;
while(bakup!=index){
bakup--;
}
cout<<"Element at index : "<<index<<" is : "<<s[bakup]<<endl;
}
int getTopIndex(){
return top;
}
int getTopElement(){
return s[top];
}
int isEmpty(){
if(top==-1){
cout<<"Empty!"<<endl;
return 0;
}else{
cout<<"Not Empty!"<<endl;
return 1;
}
}
int isFull(){
if(top==size-1){
cout<<"stack full!"<<endl;
return 1;
}else{
cout<<"stack not full!"<<endl;
return 0;
}
}
};
int isOperant(char x){
if(x=='+'||x=='-'||x=='*'||x=='/'){
return 1;
}else{
return 0;
}
}
int getResult(int a, int b, char op){
if(op=='+'){
return b+a;
}else if(op=='-'){
return b-a;
}else if(op=='*'){
return b*a;
}else if(op=='/'){
return b/a;
}
}
int main(){
char postfix[]={'3','5','*','6','2','/','+','4','-','\0'};
Stack s(strlen(postfix)+1);
int x1=0;
int x2=0;
int result=0;
int i=0;
while(postfix[i]!='\0'){
if(isOperant(postfix[i])){
x2=s.pop();
x1=s.pop();
result=getResult(x2,x1,postfix[i]);
s.push(result);
i++;
}else{
s.push(postfix[i]-'0');
i++;
}
}
int ans=0;
ans=s.pop();
cout<<"Answer = "<<ans<<endl;
}
| 21.752 | 73 | 0.36815 | meyash |
50b61748fffd338c421aa1f6dbe818075634c348 | 1,165 | cpp | C++ | mdlink/src/base/test/Test.cpp | sz6636/DataCore | e2ef9bd2c22ee9e2845675b6435a14fa607f3551 | [
"Apache-2.0"
] | 144 | 2017-11-08T07:19:13.000Z | 2021-07-26T14:13:02.000Z | mdlink/src/base/test/Test.cpp | sz6636/DataCore | e2ef9bd2c22ee9e2845675b6435a14fa607f3551 | [
"Apache-2.0"
] | 13 | 2017-12-14T17:16:12.000Z | 2019-06-16T22:22:36.000Z | mdlink/src/base/test/Test.cpp | quantOS-org/DataCore | e2ef9bd2c22ee9e2845675b6435a14fa607f3551 | [
"Apache-2.0"
] | 88 | 2017-11-21T01:31:00.000Z | 2021-06-19T01:01:04.000Z |
/***********************************************************************
Copyright 2017 quantOS-org
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
***********************************************************************/
#include "DynamicClass.h"
#include "ini/IniAPi.h"
#include "msg/MarketBook.h"
using namespace dy;
void mainxx(int argc, char *argv[])
{
DynamicClass *dc = DynamicClass::Load("ini.dll");
IniApi *api = (IniApi *)dc->NewObject("NewIniApi", NULL);
api->Parse("feedclient.ini");
long port;
api->GetInteger("CLIENT", "port", 0, port);
printf("port=%d\n", port);
api->Release();
dc->Free();
printf("sizeof(MarketBook) =%d\n", sizeof(MarketBook));
} | 29.125 | 72 | 0.63691 | sz6636 |
50b67756fac108abbadc34a53df7a5f79ea2765d | 43 | cpp | C++ | source/dummy-includes/gui/Top_level_window.include.cpp | alf-p-steinbach/winapi | 866a3bcf5eddf4237db56790559bb0310f183abc | [
"MIT"
] | 1 | 2021-11-21T18:55:34.000Z | 2021-11-21T18:55:34.000Z | source/dummy-includes/gui/Top_level_window.include.cpp | alf-p-steinbach/winapi | 866a3bcf5eddf4237db56790559bb0310f183abc | [
"MIT"
] | null | null | null | source/dummy-includes/gui/Top_level_window.include.cpp | alf-p-steinbach/winapi | 866a3bcf5eddf4237db56790559bb0310f183abc | [
"MIT"
] | null | null | null | #include <winapi/gui/Top_level_window.hpp>
| 21.5 | 42 | 0.813953 | alf-p-steinbach |
50b8c79e0c202d2b30feecd5492d531031762bdf | 2,588 | cpp | C++ | examples/single channel analysis/main.cpp | dsilko/SOM | 9d27f101176b789305e783f643930a7a1c384bc5 | [
"Apache-2.0"
] | 9 | 2018-05-19T21:37:06.000Z | 2021-05-31T20:10:34.000Z | examples/single channel analysis/main.cpp | dsilko/SOM | 9d27f101176b789305e783f643930a7a1c384bc5 | [
"Apache-2.0"
] | null | null | null | examples/single channel analysis/main.cpp | dsilko/SOM | 9d27f101176b789305e783f643930a7a1c384bc5 | [
"Apache-2.0"
] | 3 | 2018-06-30T20:55:56.000Z | 2020-09-14T20:35:23.000Z | /* Copyright 2018 Denis Silko. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http:www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "som.hpp"
#include "som_cv_view.hpp"
using namespace cv;
using namespace som;
using namespace std;
static const string THREE_CHANNEL_MAPS_WINDOW_NAME = "Three-channel map";
static const string SINGLE_CHANNEL_MAPS_WINDOW_NAME = "Single channel maps";
int main(int argc, const char * argv[]) {
// BGR colors
vector<float> red {0.00, 0.0, 1.00},
green {0.0, 1.0, 0.00},
blue {1.00, 0.0, 0.00},
yellow {0.20, 1.0, 1.00},
orange {0.25, 0.4, 1.00},
purple {1.0, 0.0, 1.00},
dk_green {0.25, 0.5, 0.00},
dk_blue {0.50, 0.0, 0.00};
vector<vector<float>> data{red, green, blue, yellow, orange, purple, dk_green, dk_blue};
const auto radius = 60;
const auto hexSize = 3;
const auto channels = 3;
const auto learningRate = 0.1;
const auto epochs = 5000;
SOM som(CPU);
som.create(radius, hexSize, channels);
som.prepare(data, MINMAX_BY_COLUMNS, RANDOM_FROM_DATA);
som.train(epochs, learningRate);
// Draw single channel maps
vector<Mat> singleChannelMaps {
drawSingleChannelMap(som, 0, ColormapConfiguration(COLORSCALE_PARULA)),
drawSingleChannelMap(som, 1, ColormapConfiguration(COLORSCALE_PARULA)),
drawSingleChannelMap(som, 2, ColormapConfiguration(COLORSCALE_PARULA))
};
// Concatenate maps
Mat allMaps;
hconcat(singleChannelMaps, allMaps);
// Draw and show single channel maps
namedWindow(SINGLE_CHANNEL_MAPS_WINDOW_NAME);
moveWindow(SINGLE_CHANNEL_MAPS_WINDOW_NAME, 90, 100);
imshow(SINGLE_CHANNEL_MAPS_WINDOW_NAME, allMaps);
// Draw and show three-channel map
namedWindow(THREE_CHANNEL_MAPS_WINDOW_NAME);
moveWindow(THREE_CHANNEL_MAPS_WINDOW_NAME, 600, 20);
imshow(THREE_CHANNEL_MAPS_WINDOW_NAME, draw3DMap(som));
waitKey();
cv::destroyAllWindows();
return 0;
}
| 34.506667 | 92 | 0.670402 | dsilko |
50bc2625799d5caeff4058aba67a42c68ea290fc | 9,408 | cpp | C++ | firmware-usbhost/common/cardreader/sberbank/test/SberbankPacketLayerTest.cpp | Zzzzipper/cppprojects | e9c9b62ca1e411320c24a3d168cab259fa2590d3 | [
"MIT"
] | null | null | null | firmware-usbhost/common/cardreader/sberbank/test/SberbankPacketLayerTest.cpp | Zzzzipper/cppprojects | e9c9b62ca1e411320c24a3d168cab259fa2590d3 | [
"MIT"
] | 1 | 2021-09-03T13:03:20.000Z | 2021-09-03T13:03:20.000Z | firmware-usbhost/common/cardreader/sberbank/test/SberbankPacketLayerTest.cpp | Zzzzipper/cppprojects | e9c9b62ca1e411320c24a3d168cab259fa2590d3 | [
"MIT"
] | null | null | null | #include "cardreader/sberbank/SberbankPacketLayer.h"
#include "timer/include/TimerEngine.h"
#include "utils/include/Hex.h"
#include "test/include/Test.h"
#include "logger/include/Logger.h"
class TestSberbankFrameLayer : public Sberbank::FrameLayerInterface {
public:
TestSberbankFrameLayer(StringBuilder *result) : result(result), observer(NULL) {}
virtual void setObserver(Sberbank::FrameLayerObserver *observer) { this->observer = observer; }
virtual void reset() {
*result << "<FL::reset>";
}
virtual bool sendPacket(Buffer *data) {
*result << "<FL::sendPacket=" << data->getLen() << ",data=";
for(uint16_t i = 0; i < data->getLen(); i++) {
result->addHex((*data)[i]);
}
*result << ">";
return true;
}
virtual bool sendControl(uint8_t control) {
*result << "<FL::sendControl=" << control << ">";
return true;
}
bool addRecvData(const char *hex) {
Buffer buf(SBERBANK_FRAME_SIZE);
hexToData(hex, &buf);
observer->procPacket(buf.getData(), buf.getLen());
return true;
}
private:
StringBuilder *result;
Sberbank::FrameLayerObserver *observer;
};
class TestSberbankPacketLayerObserver : public Sberbank::PacketLayerObserver {
public:
TestSberbankPacketLayerObserver(StringBuilder *result) : result(result) {}
virtual void procPacket(const uint8_t *data, const uint16_t dataLen) {
*result << "<event=RecvData,len=" << dataLen << ",data=";
for(uint16_t i = 0; i < dataLen; i++) {
result->addHex(data[i]);
}
*result << ">";
}
virtual void procControl(uint8_t control) {
*result << "<control=" << control << ">";
}
virtual void procError(Error error) {
switch(error) {
// case TaskLayerObserver::Error_OK: *str << "<event=OK>"; return;
// case TaskLayerObserver::Error_ConnectFailed: *str << "<event=ConnectFailed>"; return;
// case TaskLayerObserver::Error_RemoteClose: *str << "<event=RemoteClose>"; return;
// case TaskLayerObserver::Error_SendFailed: *str << "<event=SendFailed>"; return;
// case TaskLayerObserver::Error_RecvFailed: *str << "<event=RecvFailed>"; return;
// case TaskLayerObserver::Error_RecvTimeout: *str << "<event=RecvTimeout>"; return;
default: *result << "<event=" << error << ">";
}
}
private:
StringBuilder *result;
};
class SberbankPacketLayerTest : public TestSet {
public:
SberbankPacketLayerTest();
bool init();
void cleanup();
bool test();
bool testBrokenChain();
bool testSendBigData();
private:
StringBuilder *result;
TimerEngine *timerEngine;
TestSberbankFrameLayer *frameLayer;
TestSberbankPacketLayerObserver *observer;
Sberbank::PacketLayer *layer;
};
TEST_SET_REGISTER(SberbankPacketLayerTest);
SberbankPacketLayerTest::SberbankPacketLayerTest() {
TEST_CASE_REGISTER(SberbankPacketLayerTest, test);
TEST_CASE_REGISTER(SberbankPacketLayerTest, testBrokenChain);
TEST_CASE_REGISTER(SberbankPacketLayerTest, testSendBigData);
}
bool SberbankPacketLayerTest::init() {
this->result = new StringBuilder(2048, 2048);
this->timerEngine = new TimerEngine();
this->frameLayer = new TestSberbankFrameLayer(result);
this->observer = new TestSberbankPacketLayerObserver(result);
this->layer = new Sberbank::PacketLayer(this->timerEngine, this->frameLayer);
this->layer->setObserver(observer);
return true;
}
void SberbankPacketLayerTest::cleanup() {
delete this->layer;
delete this->observer;
delete this->frameLayer;
delete this->timerEngine;
delete this->result;
}
bool SberbankPacketLayerTest::test() {
layer->reset();
// send
Buffer data1(256);
TEST_NUMBER_NOT_EQUAL(0, hexToData("c00c001d440a00cd00000000000000ffffffff", &data1));
layer->sendPacket(&data1);
TEST_STRING_EQUAL("<FL::reset><FL::sendPacket=23,data=0013C00C001D440A00CD00000000000000FFFFFFFF661D>", result->getString());
result->clear();
// recv frame1
TEST_NUMBER_EQUAL(true, frameLayer->addRecvData(
"80b400bc00f66e07800000323730333335003833"
"3239353131353735343600303030310034323736"
"36332a2a2a2a2a2a323931350000000030322f32"
"30008e848e819085488e3a000000000000000000"
"000000000000000000000000000085f03301460a"
"0200013230303233313431005669736100000000"
"0000000000000000363331303030303030303436"
"000000008171e79003bfc422a73796f0ee4e0c5b"
"a05d4d56d2634db744cab644740e69c9c4ddaa6b"
"5f828a3a"));
TEST_STRING_EQUAL("<FL::sendControl=6>", result->getString());
result->clear();
// recv frame2
TEST_NUMBER_EQUAL(true, frameLayer->addRecvData(
"010fc54f4a2097b251e70627a1357bc803c719"));
TEST_STRING_EQUAL("<FL::sendControl=4><event=RecvData,len=195,data="
"00BC00F66E078000003237303333350038333239"
"3531313537353436003030303100343237363633"
"2A2A2A2A2A2A323931350000000030322F323000"
"8E848E819085488E3A0000000000000000000000"
"00000000000000000000000085F03301460A0200"
"0132303032333134310056697361000000000000"
"0000000000003633313030303030303034360000"
"00008171E79003BFC422A73796F0EE4E0C5BA05D"
"4D56D2634DB744CAB644740E69C9C4DDAA6B5F82"
"C54F4A2097B251E70627A1357BC803>",
result->getString());
result->clear();
return true;
}
bool SberbankPacketLayerTest::testBrokenChain() {
layer->reset();
// send
Buffer data1(256);
TEST_NUMBER_NOT_EQUAL(0, hexToData("c00c001d440a00cd00000000000000ffffffff", &data1));
layer->sendPacket(&data1);
TEST_STRING_EQUAL("<FL::reset><FL::sendPacket=23,data=0013C00C001D440A00CD00000000000000FFFFFFFF661D>", result->getString());
result->clear();
// recv frame1
TEST_NUMBER_EQUAL(true, frameLayer->addRecvData(
"80b400bc00f66e07800000323730333335003833"
"3239353131353735343600303030310034323736"
"36332a2a2a2a2a2a323931350000000030322f32"
"30008e848e819085488e3a000000000000000000"
"000000000000000000000000000085f03301460a"
"0200013230303233313431005669736100000000"
"0000000000000000363331303030303030303436"
"000000008171e79003bfc422a73796f0ee4e0c5b"
"a05d4d56d2634db744cab644740e69c9c4ddaa6b"
"5f828a3a"));
TEST_STRING_EQUAL("<FL::sendControl=6>", result->getString());
result->clear();
// wait frame
timerEngine->tick(SBERBANK_FRAME_TIMEOUT);
timerEngine->execute();
TEST_STRING_EQUAL("", result->getString());
// new frame
TEST_NUMBER_EQUAL(true, frameLayer->addRecvData(
"000B0004001D440A8009200000973D"));
TEST_STRING_EQUAL("<FL::sendControl=4><event=RecvData,len=11,data="
"0004001D440A8009200000>",
result->getString());
result->clear();
return true;
}
bool SberbankPacketLayerTest::testSendBigData() {
layer->reset();
TEST_STRING_EQUAL("<FL::reset>", result->getString());
result->clear();
// send
Buffer data1(2048);
TEST_NUMBER_NOT_EQUAL(0, hexToData(
"0009022200008002190004020704005300424753"
"014d51ab0044e350020000001e00690000000201"
"343c47000209b50000fe7800000000ff06820183"
"df0d0101df1682017a2200000022049999122221"
"0000272099990130000000309999990630880000"
"3094999915309600003102999915311200003120"
"9999153158000031599999153337000033499999"
"1534000000349999990535280000358999991536"
"0000003699999906370000003799999905380000"
"0039999999064000000049999999034276800042"
"7689990450000000509999990251000000559999"
"9901560000005999999902600000006999999902"
"6011000060110999066011200060114999066011"
"7400601174990660117700601177990660118600"
"6011999906605461006054629907620000006299"
"99990e6440000065999999067005230070052399"
"3178255510782555193160598200605982993178"
"2599007825999931782601007826019931701342"
"0070134209317084271170842711317825460078"
"2546993081000000819999990e90000000905099"
"990e90510000905199991290520000909999990e"
"91110000911199990e94000000998999990e9990"
"00009999999908ff06820183df0d0102df168201"
"7a2202200022022099ff3751220037512499ff40"
"43240040432499fe4080730040807499fe408240"
"0040824199fe4083440040834599fe4096530040"
"965399fe41034000", &data1));
layer->sendPacket(&data1);
TEST_STRING_EQUAL(
"<FL::sendPacket=184,data="
"80B4000902220000800219000402070400530042"
"4753014D51AB0044E350020000001E0069000000"
"0201343C47000209B50000FE7800000000FF0682"
"0183DF0D0101DF1682017A220000002204999912"
"2221000027209999013000000030999999063088"
"0000309499991530960000310299991531120000"
"3120999915315800003159999915333700003349"
"9999153400000034999999053528000035899999"
"1536000000369999990637000000379999990538"
"000073F2>", result->getString());
result->clear();
layer->procControl(Sberbank::Control_ACK);
TEST_STRING_EQUAL(
"<FL::sendPacket=184,data="
"81B4003999999906400000004999999903427680"
"0042768999045000000050999999025100000055"
"9999990156000000599999990260000000699999"
"9902601100006011099906601120006011499906"
"6011740060117499066011770060117799066011"
"8600601199990660546100605462990762000000"
"629999990E644000006599999906700523007005"
"2399317825551078255519316059820060598299"
"3178259900782599993178260100782601993170"
"13420C69>", result->getString());
result->clear();
layer->procControl(Sberbank::Control_BEL);
TEST_STRING_EQUAL(
"<FL::sendPacket=172,data="
"02A8007013420931708427117084271131782546"
"00782546993081000000819999990E9000000090"
"5099990E90510000905199991290520000909999"
"990E91110000911199990E94000000998999990E"
"999000009999999908FF06820183DF0D0102DF16"
"82017A2202200022022099FF3751220037512499"
"FF4043240040432499FE4080730040807499FE40"
"82400040824199FE4083440040834599FE409653"
"0040965399FE41034000D109>", result->getString());
result->clear();
layer->procControl(Sberbank::Control_EOT);
return true;
}
| 34.086957 | 126 | 0.790497 | Zzzzipper |
50bea8f351b4996d449b0857880e4841c980f7c7 | 6,183 | cc | C++ | src/script_detector_test.cc | nitsakh/cld3 | 484afe9ba7438d078e60b3a26e7fb590213c0e17 | [
"Apache-2.0"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | src/script_detector_test.cc | pkasting/cld3 | 006f75a2ab4c3b6cbfcf0a1a7924e67efb70e628 | [
"Apache-2.0"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | src/script_detector_test.cc | pkasting/cld3 | 006f75a2ab4c3b6cbfcf0a1a7924e67efb70e628 | [
"Apache-2.0"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | /* Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "script_detector.h"
#include <iostream>
#include "utils.h"
namespace chrome_lang_id {
namespace script_detector_test {
Script GetScript(const char *p) {
const int num_bytes = utils::OneCharLen(p);
return chrome_lang_id::GetScript(p, num_bytes);
}
bool PrintAndReturnStatus(bool status) {
if (status) {
std::cout << " Success" << std::endl;
return true;
} else {
std::cout << " Failure" << std::endl;
return false;
}
}
bool TestGreekScript() {
std::cout << "Running " << __FUNCTION__ << std::endl;
// The first two conditions check first / last character from the Greek and
// Coptic script. The last two ones are negative tests.
return PrintAndReturnStatus(
kScriptGreek == GetScript("Ͱ") && kScriptGreek == GetScript("Ͽ") &&
kScriptGreek == GetScript("δ") && kScriptGreek == GetScript("Θ") &&
kScriptGreek == GetScript("Δ") && kScriptGreek != GetScript("a") &&
kScriptGreek != GetScript("0"));
}
bool TestCyrillicScript() {
std::cout << "Running " << __FUNCTION__ << std::endl;
return PrintAndReturnStatus(
kScriptCyrillic == GetScript("Ѐ") && kScriptCyrillic == GetScript("ӿ") &&
kScriptCyrillic == GetScript("ш") && kScriptCyrillic == GetScript("Б") &&
kScriptCyrillic == GetScript("Ӱ"));
}
bool TestHebrewScript() {
std::cout << "Running " << __FUNCTION__ << std::endl;
return PrintAndReturnStatus(
kScriptHebrew == GetScript("֑") && kScriptHebrew == GetScript("״") &&
kScriptHebrew == GetScript("ד") && kScriptHebrew == GetScript("ה") &&
kScriptHebrew == GetScript("צ"));
}
bool TestArabicScript() {
std::cout << "Running " << __FUNCTION__ << std::endl;
return PrintAndReturnStatus(kScriptArabic == GetScript("م") &&
kScriptArabic == GetScript("خ"));
}
bool TestHangulJamoScript() {
std::cout << "Running " << __FUNCTION__ << std::endl;
return PrintAndReturnStatus(kScriptHangulJamo == GetScript("ᄀ") &&
kScriptHangulJamo == GetScript("ᇿ") &&
kScriptHangulJamo == GetScript("ᄡ") &&
kScriptHangulJamo == GetScript("ᆅ") &&
kScriptHangulJamo == GetScript("ᅘ"));
}
bool TestHiraganaScript() {
std::cout << "Running " << __FUNCTION__ << std::endl;
return PrintAndReturnStatus(kScriptHiragana == GetScript("ぁ") &&
kScriptHiragana == GetScript("ゟ") &&
kScriptHiragana == GetScript("こ") &&
kScriptHiragana == GetScript("や") &&
kScriptHiragana == GetScript("ぜ"));
}
bool TestKatakanaScript() {
std::cout << "Running " << __FUNCTION__ << std::endl;
return PrintAndReturnStatus(kScriptKatakana == GetScript("゠") &&
kScriptKatakana == GetScript("ヿ") &&
kScriptKatakana == GetScript("ヂ") &&
kScriptKatakana == GetScript("ザ") &&
kScriptKatakana == GetScript("ヸ"));
}
bool TestOtherScripts() {
std::cout << "Running " << __FUNCTION__ << std::endl;
bool test_successful = true;
if (kScriptOtherUtf8OneByte != GetScript("^") ||
kScriptOtherUtf8OneByte != GetScript("$")) {
test_successful = false;
}
// Unrecognized 2-byte scripts. For info on the scripts mentioned below, see
// http://www.unicode.org/charts/#scripts Note: the scripts below are uniquely
// associated with a language. Still, the number of queries in those
// languages is small and we didn't want to increase the code size and
// latency, so (at least for now) we do not treat them specially.
// The following three tests are, respectively, for Armenian, Syriac and
// Thaana.
if (kScriptOtherUtf8TwoBytes != GetScript("Ձ") ||
kScriptOtherUtf8TwoBytes != GetScript("ܔ") ||
kScriptOtherUtf8TwoBytes != GetScript("ށ")) {
test_successful = false;
}
// Unrecognized 3-byte script: CJK Unified Ideographs: not uniquely associated
// with a language.
if (kScriptOtherUtf8ThreeBytes != GetScript("万") ||
kScriptOtherUtf8ThreeBytes != GetScript("両")) {
test_successful = false;
}
// Unrecognized 4-byte script: CJK Unified Ideographs Extension C. Note:
// there is a nice UTF-8 encoder / decoder at https://mothereff.in/utf-8
if (kScriptOtherUtf8FourBytes != GetScript("\xF0\xAA\x9C\x94")) {
test_successful = false;
}
// Unrecognized 4-byte script: CJK Unified Ideographs Extension E
if (kScriptOtherUtf8FourBytes != GetScript("\xF0\xAB\xA0\xB5") ||
kScriptOtherUtf8FourBytes != GetScript("\xF0\xAC\xBA\xA1")) {
test_successful = false;
}
return PrintAndReturnStatus(test_successful);
}
} // namespace script_detector_test
} // namespace chrome_lang_id
// Runs the feature extraction tests.
int main(int argc, char **argv) {
const bool tests_successful =
chrome_lang_id::script_detector_test::TestGreekScript() &&
chrome_lang_id::script_detector_test::TestCyrillicScript() &&
chrome_lang_id::script_detector_test::TestHebrewScript() &&
chrome_lang_id::script_detector_test::TestArabicScript() &&
chrome_lang_id::script_detector_test::TestHangulJamoScript() &&
chrome_lang_id::script_detector_test::TestHiraganaScript() &&
chrome_lang_id::script_detector_test::TestKatakanaScript() &&
chrome_lang_id::script_detector_test::TestOtherScripts();
return tests_successful ? 0 : 1;
}
| 38.166667 | 80 | 0.645156 | nitsakh |
50bf35b436c40c1331e01bffee540f2abe560afb | 10,482 | cpp | C++ | tao/x11/anytypecode/any_basic_impl.cpp | ClausKlein/taox11 | 669cfd2d0be258722c7ee32b23f2e5cb83e4520f | [
"MIT"
] | 20 | 2019-11-13T12:31:20.000Z | 2022-02-27T12:30:39.000Z | tao/x11/anytypecode/any_basic_impl.cpp | ClausKlein/taox11 | 669cfd2d0be258722c7ee32b23f2e5cb83e4520f | [
"MIT"
] | 46 | 2019-11-15T20:40:18.000Z | 2022-03-31T19:04:36.000Z | tao/x11/anytypecode/any_basic_impl.cpp | ClausKlein/taox11 | 669cfd2d0be258722c7ee32b23f2e5cb83e4520f | [
"MIT"
] | 5 | 2019-11-12T15:00:50.000Z | 2022-01-17T17:33:05.000Z | /**
* @file any_basic_impl.cpp
* @author Martin Corino
*
* @brief TAOX11 CORBA Any_impl class for basic language
*
* @copyright Copyright (c) Remedy IT Expertise BV
*/
#include "tao/CDR.h"
#include "tao/x11/anytypecode/any_basic_impl.h"
#include "tao/x11/anytypecode/any_unknown_type.h"
#include "tao/x11/anytypecode/any.h"
#include "tao/x11/anytypecode/typecode_impl.h"
#include "tao/x11/anytypecode/typecode_constants.h"
#include "tao/x11/system_exception.h"
#include "ace/Auto_Ptr.h"
#include "ace/OS_NS_string.h"
namespace TAOX11_NAMESPACE
{
Any_Basic_Impl::Any_Basic_Impl (CORBA::typecode_reference tc,
void *value)
: Any_Impl (tc),
kind_ (static_cast <uint32_t> (CORBA::TCKind::tk_null))
{
this->kind_ = static_cast <uint32_t> (TC_helper::unaliased_kind (tc));
switch (static_cast<CORBA::TCKind> (this->kind_))
{
case CORBA::TCKind::tk_short:
this->u_.s = *static_cast<int16_t *> (value);
break;
case CORBA::TCKind::tk_ushort:
this->u_.us = *static_cast<uint16_t *> (value);
break;
case CORBA::TCKind::tk_long:
this->u_.l = *static_cast<int32_t *> (value);
break;
case CORBA::TCKind::tk_ulong:
this->u_.ul = *static_cast<uint32_t *> (value);
break;
case CORBA::TCKind::tk_float:
this->u_.f = *static_cast<float *> (value);
break;
case CORBA::TCKind::tk_double:
this->u_.d = *static_cast<double *> (value);
break;
case CORBA::TCKind::tk_boolean:
this->u_.b = *static_cast<bool *> (value);
break;
case CORBA::TCKind::tk_char:
this->u_.c = *static_cast<char *> (value);
break;
case CORBA::TCKind::tk_octet:
this->u_.o = *static_cast<uint8_t *> (value);
break;
case CORBA::TCKind::tk_longlong:
this->u_.ll = *static_cast<int64_t *> (value);
break;
case CORBA::TCKind::tk_ulonglong:
this->u_.ull = *static_cast<uint64_t *> (value);
break;
case CORBA::TCKind::tk_longdouble:
this->u_.ld = *static_cast<long double *> (value);
break;
case CORBA::TCKind::tk_wchar:
this->u_.wc = *static_cast<wchar_t *> (value);
break;
default:
break;
}
}
void
Any_Basic_Impl::insert (CORBA::Any &any,
CORBA::typecode_reference tc,
const void *value)
{
Any_Basic_Impl *new_impl {};
ACE_NEW (new_impl,
Any_Basic_Impl (std::move(tc),
const_cast<void *> (value)));
ref_type safe_new_impl (new_impl);
any.replace (safe_new_impl);
}
bool
Any_Basic_Impl::extract (const CORBA::Any &any,
CORBA::typecode_reference tc,
void *_tao_elem)
{
try
{
CORBA::typecode_reference any_tc = any.type ();
bool const _tao_equiv =
any_tc->equivalent (tc);
if (!_tao_equiv)
{
return false;
}
Any_Impl::ref_type const impl = any.impl ();
if (impl && !impl->encoded ())
{
ref_type const narrow_impl =
std::dynamic_pointer_cast<Any_Basic_Impl> (impl);
if (!narrow_impl)
{
return false;
}
Any_Basic_Impl::assign_value (_tao_elem, narrow_impl);
return true;
}
Any_Basic_Impl *replacement =
Any_Basic_Impl::create_empty (any_tc);
ref_type replacement_safety (replacement);
// We know this will work since the unencoded case is covered above.
Unknown_IDL_Type::ref_type const unk =
std::dynamic_pointer_cast<Unknown_IDL_Type> (impl);
if (!unk)
return false;
// Get the kind of the type where we are extracting in ie. the
// aliased type if there are any. Passing the aliased kind
// will not help.
CORBA::TCKind const tck = tc->kind ();
// We don't want the rd_ptr of unk to move, in case it is
// shared by another Any. This copies the state, not the buffer.
TAO_InputCDR for_reading (unk->_tao_get_cdr ());
bool const good_decode =
replacement_safety->demarshal_value (for_reading,
static_cast<uint32_t> (tck));
if (good_decode)
{
Any_Basic_Impl::assign_value (_tao_elem,
replacement_safety,
static_cast<uint32_t> (tck));
const_cast<CORBA::Any &> (any).replace (replacement_safety);
return true;
}
}
catch (const CORBA::Exception&)
{
}
return false;
}
bool
Any_Basic_Impl::marshal_value (TAO_OutputCDR &cdr)
{
CORBA::TCKind const tckind = static_cast<CORBA::TCKind> (this->kind_);
switch (tckind)
{
case CORBA::TCKind::tk_short:
return cdr << this->u_.s;
case CORBA::TCKind::tk_ushort:
return cdr << this->u_.us;
case CORBA::TCKind::tk_long:
return cdr << this->u_.l;
case CORBA::TCKind::tk_ulong:
return cdr << this->u_.ul;
case CORBA::TCKind::tk_float:
return cdr << this->u_.f;
case CORBA::TCKind::tk_double:
return cdr << this->u_.d;
case CORBA::TCKind::tk_boolean:
return cdr << TAO_OutputCDR::from_boolean (this->u_.b);
case CORBA::TCKind::tk_char:
return cdr << TAO_OutputCDR::from_char (this->u_.c);
case CORBA::TCKind::tk_octet:
return cdr << TAO_OutputCDR::from_octet (this->u_.o);
case CORBA::TCKind::tk_longlong:
return cdr << this->u_.ll;
case CORBA::TCKind::tk_ulonglong:
return cdr << this->u_.ull;
case CORBA::TCKind::tk_longdouble:
return cdr << this->u_.ld;
case CORBA::TCKind::tk_wchar:
return cdr << TAO_OutputCDR::from_wchar (this->u_.wc);
default:
return false;
}
}
bool
Any_Basic_Impl::demarshal_value (TAO_InputCDR &cdr)
{
return this->demarshal_value (cdr,
this->kind_);
}
bool
Any_Basic_Impl::demarshal_value (TAO_InputCDR &cdr,
uint32_t tck)
{
CORBA::TCKind const tckind = static_cast<CORBA::TCKind> (tck);
switch (tckind)
{
case CORBA::TCKind::tk_short:
return cdr >> this->u_.s;
case CORBA::TCKind::tk_ushort:
return cdr >> this->u_.us;
case CORBA::TCKind::tk_long:
return cdr >> this->u_.l;
case CORBA::TCKind::tk_ulong:
return cdr >> this->u_.ul;
case CORBA::TCKind::tk_float:
return cdr >> this->u_.f;
case CORBA::TCKind::tk_double:
return cdr >> this->u_.d;
case CORBA::TCKind::tk_boolean:
return cdr >> TAO_InputCDR::to_boolean (this->u_.b);
case CORBA::TCKind::tk_char:
return cdr >> TAO_InputCDR::to_char (this->u_.c);
case CORBA::TCKind::tk_octet:
return cdr >> TAO_InputCDR::to_octet (this->u_.o);
case CORBA::TCKind::tk_longlong:
return cdr >> this->u_.ll;
case CORBA::TCKind::tk_ulonglong:
return cdr >> this->u_.ull;
case CORBA::TCKind::tk_longdouble:
return cdr >> this->u_.ld;
case CORBA::TCKind::tk_wchar:
return cdr >> TAO_InputCDR::to_wchar (this->u_.wc);
default:
return false;
}
}
void
Any_Basic_Impl::_tao_decode (TAO_InputCDR &cdr)
{
if (! this->demarshal_value (cdr))
{
throw CORBA::MARSHAL ();
}
}
Any_Basic_Impl *
Any_Basic_Impl::create_empty (CORBA::typecode_reference tc)
{
CORBA::TCKind const kind = tc->kind ();
Any_Basic_Impl * retval = nullptr;
switch (kind)
{
case CORBA::TCKind::tk_longlong:
{
int64_t tmp (0LL);
ACE_NEW_RETURN (retval,
Any_Basic_Impl (tc, &tmp),
nullptr);
}
break;
case CORBA::TCKind::tk_longdouble:
{
long double tmp (0L);
ACE_NEW_RETURN (retval,
Any_Basic_Impl (tc, &tmp),
nullptr);
}
break;
default:
{
uint64_t tmp (0ULL);
ACE_NEW_RETURN (retval,
Any_Basic_Impl (tc, &tmp),
nullptr);
}
break;
}
return retval;
}
void
Any_Basic_Impl::assign_value (void *dest, ref_type src)
{
Any_Basic_Impl::assign_value (dest,
src,
src->kind_);
}
void
Any_Basic_Impl::assign_value (void *dest,
ref_type src,
uint32_t tck)
{
CORBA::TCKind const kind = static_cast<CORBA::TCKind> (tck);
switch (kind)
{
case CORBA::TCKind::tk_short:
*static_cast<int16_t *> (dest) = src->u_.s;
break;
case CORBA::TCKind::tk_ushort:
*static_cast<uint16_t *> (dest) = src->u_.us;
break;
case CORBA::TCKind::tk_long:
*static_cast<int32_t *> (dest) = src->u_.l;
break;
case CORBA::TCKind::tk_ulong:
*static_cast<uint32_t *> (dest) = src->u_.ul;
break;
case CORBA::TCKind::tk_float:
*static_cast<float *> (dest) = src->u_.f;
break;
case CORBA::TCKind::tk_double:
*static_cast<double *> (dest) = src->u_.d;
break;
case CORBA::TCKind::tk_boolean:
*static_cast<bool *> (dest) = src->u_.b;
break;
case CORBA::TCKind::tk_char:
*static_cast<char *> (dest) = src->u_.c;
break;
case CORBA::TCKind::tk_octet:
*static_cast<uint8_t *> (dest) = src->u_.o;
break;
case CORBA::TCKind::tk_longlong:
*static_cast<int64_t *> (dest) = src->u_.ll;
break;
case CORBA::TCKind::tk_ulonglong:
*static_cast<uint64_t *> (dest) = src->u_.ull;
break;
case CORBA::TCKind::tk_longdouble:
*static_cast<long double *> (dest) = src->u_.ld;
break;
case CORBA::TCKind::tk_wchar:
*static_cast<wchar_t *> (dest) = src->u_.wc;
break;
default:
break;
}
}
} // namespace TAOX11_NAMESPACE
| 29.27933 | 76 | 0.552757 | ClausKlein |
50bf537dc72710a950a61ebc021c4ac0ceeb84a6 | 168 | cpp | C++ | Volt/src/core/Resources.cpp | Daninjakiwi/Volt | bd62f8fcde96607e8f63ecb25056a1bae72a7c30 | [
"MIT"
] | null | null | null | Volt/src/core/Resources.cpp | Daninjakiwi/Volt | bd62f8fcde96607e8f63ecb25056a1bae72a7c30 | [
"MIT"
] | null | null | null | Volt/src/core/Resources.cpp | Daninjakiwi/Volt | bd62f8fcde96607e8f63ecb25056a1bae72a7c30 | [
"MIT"
] | null | null | null | #include <core/Resources.hpp>
namespace volt::resources {
unsigned long long s_current = 1;
unsigned long long assignId() {
s_current++;
return s_current;
}
} | 16.8 | 34 | 0.708333 | Daninjakiwi |
50cf0fa30936c32123570f9e8010583fa3eeb72f | 7,230 | cc | C++ | transpiler/tfhe_transpiler.cc | EtorgFalo/fully-homomorphic-encryption | e055442bb4efb16d26f5e2c2c09529fa17fb2d60 | [
"Apache-2.0"
] | null | null | null | transpiler/tfhe_transpiler.cc | EtorgFalo/fully-homomorphic-encryption | e055442bb4efb16d26f5e2c2c09529fa17fb2d60 | [
"Apache-2.0"
] | null | null | null | transpiler/tfhe_transpiler.cc | EtorgFalo/fully-homomorphic-encryption | e055442bb4efb16d26f5e2c2c09529fa17fb2d60 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 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 "transpiler/tfhe_transpiler.h"
#include <string>
#include <utility>
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/strings/substitute.h"
#include "transpiler/common_transpiler.h"
#include "xls/common/status/status_macros.h"
#include "xls/contrib/xlscc/metadata_output.pb.h"
#include "xls/ir/function.h"
#include "xls/ir/node.h"
#include "xls/ir/node_iterator.h"
#include "xls/ir/nodes.h"
#include "xls/public/value.h"
namespace xls {
class Node;
} // namespace xls
namespace fully_homomorphic_encryption {
namespace transpiler {
namespace {
using xls::Bits;
using xls::Function;
using xls::Literal;
using xls::Node;
using xls::Op;
using xls::Param;
std::string NodeReference(const Node* node) {
return absl::StrFormat("temp_nodes[%d]", node->id());
}
std::string ParamBitReference(const Node* param, int offset) {
int64_t param_bits = param->GetType()->GetFlatBitCount();
if (param_bits == 1) {
if (param->Is<xls::TupleIndex>() || param->Is<xls::ArrayIndex>()) {
return param->operand(0)->GetName();
}
}
return absl::StrFormat("&%s[%d]", param->GetName(), offset);
}
std::string OutputBitReference(absl::string_view output_arg, int offset) {
return absl::StrFormat("&%s[%d]", output_arg, offset);
}
std::string CopyTo(absl::string_view destination, absl::string_view source) {
return absl::Substitute(" bootsCOPY($0, $1, bk);\n", destination, source);
}
} // namespace
// Input: "result", 0, Node(id = 3)
// Output: result[0] = temp_nodes[3];
std::string TfheTranspiler::CopyNodeToOutput(absl::string_view output_arg,
int offset,
const xls::Node* node) {
return CopyTo(OutputBitReference(output_arg, offset), NodeReference(node));
}
// Input: Node(id = 4), Param("some_param"), 3
// Output: temp_nodes[4] = &some_param[3];
std::string TfheTranspiler::CopyParamToNode(const xls::Node* node,
const xls::Node* param,
int offset) {
return CopyTo(NodeReference(node), ParamBitReference(param, offset));
}
// Input: Node(id = 5)
// Output: temp_nodes[5] = new new_gate_bootstrapping_ciphertext(bk->params);
std::string TfheTranspiler::InitializeNode(const Node* node) {
return absl::Substitute(
" $0 = new_gate_bootstrapping_ciphertext(bk->params);\n",
NodeReference(node));
}
// Input: Node(id = 5, op = kNot, operands = Node(id = 2))
// Output: " bootsNOT(temp_nodes[5], temp_nodes[2], bk);\n\n"
absl::StatusOr<std::string> TfheTranspiler::Execute(const Node* node) {
absl::ParsedFormat<'s', 's'> statement{
"// Unsupported Op kind; arguments \"%s\", \"%s\"\n\n"};
switch (node->op()) {
case Op::kAnd:
statement = absl::ParsedFormat<'s', 's'>{" bootsAND(%s, %s, bk);\n\n"};
break;
case Op::kOr:
statement = absl::ParsedFormat<'s', 's'>{" bootsOR(%s, %s, bk);\n\n"};
break;
case Op::kNot:
statement = absl::ParsedFormat<'s', 's'>{" bootsNOT(%s, %s, bk);\n\n"};
break;
case Op::kLiteral:
statement =
absl::ParsedFormat<'s', 's'>{" bootsCONSTANT(%s, %s, bk);\n\n"};
break;
default:
return absl::InvalidArgumentError("Unsupported Op kind.");
}
std::vector<std::string> arguments;
if (node->Is<Literal>()) {
const Literal* literal = node->As<Literal>();
XLS_ASSIGN_OR_RETURN(const Bits bit, literal->value().GetBitsWithStatus());
if (bit.IsOne()) {
arguments.push_back("1");
} else if (bit.IsZero()) {
arguments.push_back("0");
} else {
// We allow literals strictly for pulling values out of [param] arrays.
for (const Node* user : literal->users()) {
if (!user->Is<xls::ArrayIndex>()) {
return absl::InvalidArgumentError("Unsupported literal value.");
}
}
return "";
}
} else {
for (const Node* operand_node : node->operands()) {
arguments.push_back(NodeReference(operand_node));
}
}
return absl::StrFormat(statement, NodeReference(node),
absl::StrJoin(arguments, ", "));
}
absl::StatusOr<std::string> TfheTranspiler::TranslateHeader(
const xls::Function* function,
const xlscc_metadata::MetadataOutput& metadata,
absl::string_view header_path) {
XLS_ASSIGN_OR_RETURN(const std::string header_guard,
PathToHeaderGuard(header_path));
static constexpr absl::string_view kHeaderTemplate =
R"(#ifndef $2
#define $2
// clang-format off
#include "$3"
// clang-format on
#include "absl/status/status.h"
#include "absl/types/span.h"
#include "tfhe/tfhe.h"
#include "tfhe/tfhe_io.h"
#include "transpiler/data/tfhe_data.h"
$0;
$1#endif // $2
)";
XLS_ASSIGN_OR_RETURN(std::string signature,
FunctionSignature(function, metadata));
absl::optional<std::string> typed_overload =
TypedOverload(metadata, "Tfhe", "absl::Span<LweSample>",
"const TFheGateBootstrappingCloudKeySet*");
return absl::Substitute(kHeaderTemplate, signature,
typed_overload.value_or(""), header_guard,
GetTypeHeader(header_path));
}
absl::StatusOr<std::string> TfheTranspiler::FunctionSignature(
const Function* function, const xlscc_metadata::MetadataOutput& metadata) {
return transpiler::FunctionSignature(
metadata, "LweSample", "const TFheGateBootstrappingCloudKeySet*", "bk");
}
absl::StatusOr<std::string> TfheTranspiler::Prelude(
const Function* function, const xlscc_metadata::MetadataOutput& metadata) {
// $0: function name
// $1: non-key parameter string
static constexpr absl::string_view kPrelude =
R"(#include <unordered_map>
#include "absl/status/status.h"
#include "absl/types/span.h"
#include "transpiler/common_runner.h"
#include "tfhe/tfhe.h"
#include "tfhe/tfhe_io.h"
static StructReverseEncodeOrderSetter ORDER;
$0 {
std::unordered_map<int, LweSample*> temp_nodes;
)";
XLS_ASSIGN_OR_RETURN(std::string signature,
FunctionSignature(function, metadata));
return absl::Substitute(kPrelude, signature);
}
absl::StatusOr<std::string> TfheTranspiler::Conclusion() {
return R"( for (auto pair : temp_nodes) {
delete_gate_bootstrapping_ciphertext(pair.second);
}
return absl::OkStatus();
}
)";
}
} // namespace transpiler
} // namespace fully_homomorphic_encryption
| 32.421525 | 79 | 0.661964 | EtorgFalo |
50da228a4efeb9be695227234ac39bcb65f691ff | 1,316 | cpp | C++ | test/Preprocessor/feature_tests.cpp | LambdaMan/clang | 6edb1bc43453c555f37f713992cd99c674806ead | [
"Apache-2.0"
] | 3,102 | 2015-01-04T02:28:35.000Z | 2022-03-30T12:53:41.000Z | test/Preprocessor/feature_tests.cpp | LambdaMan/clang | 6edb1bc43453c555f37f713992cd99c674806ead | [
"Apache-2.0"
] | 31 | 2015-01-27T20:39:41.000Z | 2020-04-23T16:24:20.000Z | test/Preprocessor/feature_tests.cpp | LambdaMan/clang | 6edb1bc43453c555f37f713992cd99c674806ead | [
"Apache-2.0"
] | 1,868 | 2015-01-03T04:27:11.000Z | 2022-03-25T13:37:35.000Z | // RUN: %clang_cc1 %s -triple=i686-apple-darwin9 -verify -DVERIFY
// expected-no-diagnostics
#ifndef __has_feature
#error Should have __has_feature
#endif
#if __has_feature(something_we_dont_have)
#error Bad
#endif
#if !__has_builtin(__builtin_huge_val) || \
!__has_builtin(__builtin_shufflevector) || \
!__has_builtin(__builtin_convertvector) || \
!__has_builtin(__builtin_trap) || \
!__has_builtin(__c11_atomic_init) || \
!__has_builtin(__builtin_launder) || \
!__has_feature(attribute_analyzer_noreturn) || \
!__has_feature(attribute_overloadable)
#error Clang should have these
#endif
// These are technically implemented as keywords, but __has_builtin should
// still return true.
#if !__has_builtin(__builtin_LINE) || \
!__has_builtin(__builtin_FILE) || \
!__has_builtin(__builtin_FUNCTION) || \
!__has_builtin(__builtin_COLUMN) || \
!__has_builtin(__array_rank) || \
!__has_builtin(__underlying_type) || \
!__has_builtin(__is_trivial) || \
!__has_builtin(__has_unique_object_representations)
#error Clang should have these
#endif
// This is a C-only builtin.
#if __has_builtin(__builtin_types_compatible_p)
#error Clang should not have this in C++ mode
#endif
#if __has_builtin(__builtin_insanity)
#error Clang should not have this
#endif
| 29.909091 | 74 | 0.74848 | LambdaMan |
50e04d4202600b671afb2e3cbf1aa54f37b0b376 | 1,811 | cpp | C++ | android-31/android/net/wifi/WifiManager_LocalOnlyHotspotCallback.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/net/wifi/WifiManager_LocalOnlyHotspotCallback.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-30/android/net/wifi/WifiManager_LocalOnlyHotspotCallback.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "./WifiManager_LocalOnlyHotspotReservation.hpp"
#include "./WifiManager_LocalOnlyHotspotCallback.hpp"
namespace android::net::wifi
{
// Fields
jint WifiManager_LocalOnlyHotspotCallback::ERROR_GENERIC()
{
return getStaticField<jint>(
"android.net.wifi.WifiManager$LocalOnlyHotspotCallback",
"ERROR_GENERIC"
);
}
jint WifiManager_LocalOnlyHotspotCallback::ERROR_INCOMPATIBLE_MODE()
{
return getStaticField<jint>(
"android.net.wifi.WifiManager$LocalOnlyHotspotCallback",
"ERROR_INCOMPATIBLE_MODE"
);
}
jint WifiManager_LocalOnlyHotspotCallback::ERROR_NO_CHANNEL()
{
return getStaticField<jint>(
"android.net.wifi.WifiManager$LocalOnlyHotspotCallback",
"ERROR_NO_CHANNEL"
);
}
jint WifiManager_LocalOnlyHotspotCallback::ERROR_TETHERING_DISALLOWED()
{
return getStaticField<jint>(
"android.net.wifi.WifiManager$LocalOnlyHotspotCallback",
"ERROR_TETHERING_DISALLOWED"
);
}
// QJniObject forward
WifiManager_LocalOnlyHotspotCallback::WifiManager_LocalOnlyHotspotCallback(QJniObject obj) : JObject(obj) {}
// Constructors
WifiManager_LocalOnlyHotspotCallback::WifiManager_LocalOnlyHotspotCallback()
: JObject(
"android.net.wifi.WifiManager$LocalOnlyHotspotCallback",
"()V"
) {}
// Methods
void WifiManager_LocalOnlyHotspotCallback::onFailed(jint arg0) const
{
callMethod<void>(
"onFailed",
"(I)V",
arg0
);
}
void WifiManager_LocalOnlyHotspotCallback::onStarted(android::net::wifi::WifiManager_LocalOnlyHotspotReservation arg0) const
{
callMethod<void>(
"onStarted",
"(Landroid/net/wifi/WifiManager$LocalOnlyHotspotReservation;)V",
arg0.object()
);
}
void WifiManager_LocalOnlyHotspotCallback::onStopped() const
{
callMethod<void>(
"onStopped",
"()V"
);
}
} // namespace android::net::wifi
| 25.152778 | 125 | 0.76201 | YJBeetle |
50e8b3bc7fab3baae19f84c708171c1fd13c7094 | 8,448 | cpp | C++ | src/projects/base/springs/test_BASE_rsda.cpp | rserban/chrono | bee5e30b2ce3b4ac62324799d1366b6db295830e | [
"BSD-3-Clause"
] | 1 | 2020-03-05T13:00:41.000Z | 2020-03-05T13:00:41.000Z | src/projects/base/springs/test_BASE_rsda.cpp | rserban/chrono | bee5e30b2ce3b4ac62324799d1366b6db295830e | [
"BSD-3-Clause"
] | null | null | null | src/projects/base/springs/test_BASE_rsda.cpp | rserban/chrono | bee5e30b2ce3b4ac62324799d1366b6db295830e | [
"BSD-3-Clause"
] | 1 | 2022-03-27T15:12:24.000Z | 2022-03-27T15:12:24.000Z | #include "chrono/physics/ChSystemSMC.h"
#include "chrono/physics/ChSystemNSC.h"
#include "chrono/solver/ChIterativeSolverLS.h"
#include "chrono/solver/ChIterativeSolverVI.h"
#include "chrono/solver/ChDirectSolverLS.h"
#include "chrono/solver/ChSolverPSOR.h"
#include "chrono/solver/ChSolverBB.h"
#include "chrono_thirdparty/filesystem/path.h"
#ifdef CHRONO_PARDISO_MKL
#include "chrono_pardisomkl/ChSolverPardisoMKL.h"
#endif
#ifdef CHRONO_PARDISOPROJECT
#include "chrono_pardisoproject/ChSolverPardisoProject.h"
#endif
#ifdef CHRONO_MUMPS
#include "chrono_mumps/ChSolverMumps.h"
#endif
#include "chrono_irrlicht/ChIrrApp.h"
using namespace chrono;
using namespace chrono::irrlicht;
using std::cout;
using std::endl;
int main(int argc, char* argv[]) {
// Number of bodies and links/RSDAs
int n = 3;
// Fix one of the bodies (0, 1, ..., n-1)
int fixed_body = 0;
// Break one of the links (0, 1, ..., n-1)
int broken_link = -1;
double step_size = 5e-4;
double g = 0;
////ChSolver::Type solver_type = ChSolver::Type::BARZILAIBORWEIN;
////ChSolver::Type solver_type = ChSolver::Type::MINRES;
////ChSolver::Type solver_type = ChSolver::Type::GMRES;
////ChSolver::Type solver_type = ChSolver::Type::SPARSE_LU;
ChSolver::Type solver_type = ChSolver::Type::SPARSE_QR;
////ChSolver::Type solver_type = ChSolver::Type::PARDISO_MKL;
////ChSolver::Type solver_type = ChSolver::Type::MUMPS;
////ChTimestepper::Type integrator_type = ChTimestepper::Type::EULER_IMPLICIT;
ChTimestepper::Type integrator_type = ChTimestepper::Type::EULER_IMPLICIT_PROJECTED;
////ChTimestepper::Type integrator_type = ChTimestepper::Type::HHT;
bool verbose_solver = false;
bool verbose_integrator = true;
// System, solver and integrator
ChSystemSMC sys;
sys.Set_G_acc(ChVector<>(0, 0, g));
if (solver_type == ChSolver::Type::PARDISO_MKL) {
#ifdef CHRONO_PARDISO_MKL
std::cout << "Using Pardiso MKL solver" << std::endl;
auto solver = chrono_types::make_shared<ChSolverPardisoMKL>();
solver->LockSparsityPattern(true);
sys.SetSolver(solver);
#else
solver_type = ChSolver::Type::PSOR;
#endif
} else if (solver_type == ChSolver::Type::PARDISO_PROJECT) {
#ifdef CHRONO_PARDISOPROJECT
std::cout << "Using Pardiso PROJECT solver" << std::endl;
auto solver = chrono_types::make_shared<ChSolverPardisoProject>();
solver->LockSparsityPattern(true);
sys.SetSolver(solver);
#else
solver_type = ChSolver::Type::PSOR;
#endif
} else if (solver_type == ChSolver::Type::MUMPS) {
#ifdef CHRONO_MUMPS
std::cout << "Using MUMPS solver" << std::endl;
auto solver = chrono_types::make_shared<ChSolverMumps>();
solver->LockSparsityPattern(true);
solver->EnableNullPivotDetection(true);
solver->GetMumpsEngine().SetICNTL(14, 50);
sys.SetSolver(solver);
#else
solver_type = ChSolver::Type::PSOR;
#endif
} else {
sys.SetSolverType(solver_type);
switch (solver_type) {
case ChSolver::Type::SPARSE_LU:
case ChSolver::Type::SPARSE_QR: {
std::cout << "Using a direct sparse LS solver" << std::endl;
auto solver = std::static_pointer_cast<ChDirectSolverLS>(sys.GetSolver());
solver->LockSparsityPattern(false);
solver->UseSparsityPatternLearner(false);
break;
}
case ChSolver::Type::BARZILAIBORWEIN:
case ChSolver::Type::APGD:
case ChSolver::Type::PSOR: {
std::cout << "Using an iterative VI solver" << std::endl;
auto solver = std::static_pointer_cast<ChIterativeSolverVI>(sys.GetSolver());
solver->SetMaxIterations(100);
solver->SetOmega(0.8);
solver->SetSharpnessLambda(1.0);
////sys.SetMaxPenetrationRecoverySpeed(1.5);
////sys.SetMinBounceSpeed(2.0);
break;
}
case ChSolver::Type::BICGSTAB:
case ChSolver::Type::MINRES:
case ChSolver::Type::GMRES: {
std::cout << "Using an iterative LS solver" << std::endl;
auto solver = std::static_pointer_cast<ChIterativeSolverLS>(sys.GetSolver());
solver->SetMaxIterations(200);
solver->SetTolerance(1e-10);
solver->EnableDiagonalPreconditioner(true);
break;
}
}
}
sys.GetSolver()->SetVerbose(verbose_solver);
sys.SetTimestepperType(integrator_type);
switch (integrator_type) {
case ChTimestepper::Type::HHT: {
auto integrator = std::static_pointer_cast<ChTimestepperHHT>(sys.GetTimestepper());
integrator->SetAlpha(-0.2);
integrator->SetMaxiters(50);
integrator->SetAbsTolerances(1e-4, 1e2);
integrator->SetMode(ChTimestepperHHT::ACCELERATION);
integrator->SetStepControl(false);
integrator->SetModifiedNewton(false);
integrator->SetScaling(false);
break;
}
case ChTimestepper::Type::EULER_IMPLICIT: {
auto integrator = std::static_pointer_cast<ChTimestepperEulerImplicit>(sys.GetTimestepper());
integrator->SetMaxiters(50);
integrator->SetAbsTolerances(1e-4, 1e2);
break;
}
}
sys.GetTimestepper()->SetVerbose(verbose_integrator);
double length = 1;
double del_angle = CH_C_2PI / n;
double radius = (length / 2) / std::tan(del_angle / 2);
std::vector<std::shared_ptr<ChBody>> bodies;
ChVector<> loc;
ChQuaternion<> rot;
double angle = 0;
for (int i = 0; i < n; i++) {
loc.x() = radius * std::sin(angle);
loc.z() = radius * std::cos(angle);
rot = Q_from_AngY(angle);
auto body = chrono_types::make_shared<ChBody>();
body->SetNameString("body_" + std::to_string(i));
body->SetPos(loc);
body->SetRot(rot);
if (i == fixed_body)
body->SetBodyFixed(true);
auto box = chrono_types::make_shared<ChBoxShape>();
box->GetBoxGeometry().SetLengths(ChVector<>(length, length / 6, length / 6));
body->AddAsset(box);
body->AddAsset(chrono_types::make_shared<ChColorAsset>(0.0f, 0.0f, (i * 1.0f) / (n - 1)));
sys.AddBody(body);
bodies.push_back(body);
angle += del_angle;
}
ChQuaternion<> z2y = Q_from_AngX(-CH_C_PI_2);
for (int i = 0; i < n; i++) {
if (i == broken_link)
continue;
int j = (i == n - 1) ? 0 : i + 1;
auto rev = chrono_types::make_shared<ChLinkRevolute>();
rev->SetNameString("rev" + std::to_string(i));
ChVector<> rloc = bodies[i]->TransformPointLocalToParent(ChVector<>(length/2, 0, 0));
rev->Initialize(bodies[i], bodies[j], ChFrame<>(rloc, bodies[i]->GetRot() * z2y));
sys.AddLink(rev);
auto rsda = chrono_types::make_shared<ChLinkRSDA>();
rsda->SetNameString("rsda" + std::to_string(i));
rsda->SetSpringCoefficient(10);
rsda->SetDampingCoefficient(3);
rsda->SetRestAngle(0);
rsda->Initialize(bodies[i], bodies[j], //
true, //
ChCoordsys<>(ChVector<>(+length / 2, 0, 0), z2y), //
ChCoordsys<>(ChVector<>(-length / 2, 0, 0), z2y)); //
sys.AddLink(rsda);
rsda->AddAsset(chrono_types::make_shared<ChRotSpringShape>(length / 4, 100));
}
// Create the Irrlicht application
ChIrrApp application(&sys, L"RSDA test", irr::core::dimension2d<irr::u32>(800, 600), VerticalDir::Z);
application.AddTypicalLogo();
application.AddTypicalSky();
application.AddTypicalLights();
application.AddTypicalCamera(irr::core::vector3df(0, 2, radius), irr::core::vector3df(0, 0, radius));
application.AssetBindAll();
application.AssetUpdateAll();
// Simulation loop
while (application.GetDevice()->run()) {
application.BeginScene();
application.DrawAll();
tools::drawAllLinkframes(sys, application.GetVideoDriver(), 1.5);
application.EndScene();
sys.DoStepDynamics(step_size);
}
}
| 36.89083 | 105 | 0.612808 | rserban |
50edc4d9ef001d030d556464c6d5993d12b03ca6 | 28,036 | hpp | C++ | external/boost_1_60_0/qsboost/preprocessor/detail/dmc/auto_rec.hpp | wouterboomsma/quickstep | a33447562eca1350c626883f21c68125bd9f776c | [
"MIT"
] | 1 | 2019-06-27T17:54:13.000Z | 2019-06-27T17:54:13.000Z | external/boost_1_60_0/qsboost/preprocessor/detail/dmc/auto_rec.hpp | wouterboomsma/quickstep | a33447562eca1350c626883f21c68125bd9f776c | [
"MIT"
] | null | null | null | external/boost_1_60_0/qsboost/preprocessor/detail/dmc/auto_rec.hpp | wouterboomsma/quickstep | a33447562eca1350c626883f21c68125bd9f776c | [
"MIT"
] | null | null | null | # /* **************************************************************************
# * *
# * (C) Copyright Paul Mensonides 2002.
# * Distributed under the Boost Software License, Version 1.0. (See
# * accompanying file LICENSE_1_0.txt or copy at
# * http://www.boost.org/LICENSE_1_0.txt)
# * *
# ************************************************************************** */
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef QSBOOST_PREPROCESSOR_DETAIL_AUTO_REC_HPP
# define QSBOOST_PREPROCESSOR_DETAIL_AUTO_REC_HPP
#
# include <qsboost/preprocessor/control/iif.hpp>
#
# /* BOOST_PP_AUTO_REC */
#
# define QSBOOST_PP_AUTO_REC(pred, n) QSBOOST_PP_NODE_ENTRY_ ## n(pred)
#
# define QSBOOST_PP_NODE_ENTRY_256(p) QSBOOST_PP_NODE_128(p)(p)(p)(p)(p)(p)(p)(p)
# define QSBOOST_PP_NODE_ENTRY_128(p) QSBOOST_PP_NODE_64(p)(p)(p)(p)(p)(p)(p)
# define QSBOOST_PP_NODE_ENTRY_64(p) QSBOOST_PP_NODE_32(p)(p)(p)(p)(p)(p)
# define QSBOOST_PP_NODE_ENTRY_32(p) QSBOOST_PP_NODE_16(p)(p)(p)(p)(p)
# define QSBOOST_PP_NODE_ENTRY_16(p) QSBOOST_PP_NODE_8(p)(p)(p)(p)
# define QSBOOST_PP_NODE_ENTRY_8(p) QSBOOST_PP_NODE_4(p)(p)(p)
# define QSBOOST_PP_NODE_ENTRY_4(p) QSBOOST_PP_NODE_2(p)(p)
# define QSBOOST_PP_NODE_ENTRY_2(p) QSBOOST_PP_NODE_1(p)
#
# define QSBOOST_PP_NODE_128(p) QSBOOST_PP_IIF(p##(128), QSBOOST_PP_NODE_64, QSBOOST_PP_NODE_192)
# define QSBOOST_PP_NODE_64(p) QSBOOST_PP_IIF(p##(64), QSBOOST_PP_NODE_32, QSBOOST_PP_NODE_96)
# define QSBOOST_PP_NODE_32(p) QSBOOST_PP_IIF(p##(32), QSBOOST_PP_NODE_16, QSBOOST_PP_NODE_48)
# define QSBOOST_PP_NODE_16(p) QSBOOST_PP_IIF(p##(16), QSBOOST_PP_NODE_8, QSBOOST_PP_NODE_24)
# define QSBOOST_PP_NODE_8(p) QSBOOST_PP_IIF(p##(8), QSBOOST_PP_NODE_4, QSBOOST_PP_NODE_12)
# define QSBOOST_PP_NODE_4(p) QSBOOST_PP_IIF(p##(4), QSBOOST_PP_NODE_2, QSBOOST_PP_NODE_6)
# define QSBOOST_PP_NODE_2(p) QSBOOST_PP_IIF(p##(2), QSBOOST_PP_NODE_1, QSBOOST_PP_NODE_3)
# define QSBOOST_PP_NODE_1(p) QSBOOST_PP_IIF(p##(1), 1, 2)
# define QSBOOST_PP_NODE_3(p) QSBOOST_PP_IIF(p##(3), 3, 4)
# define QSBOOST_PP_NODE_6(p) QSBOOST_PP_IIF(p##(6), QSBOOST_PP_NODE_5, QSBOOST_PP_NODE_7)
# define QSBOOST_PP_NODE_5(p) QSBOOST_PP_IIF(p##(5), 5, 6)
# define QSBOOST_PP_NODE_7(p) QSBOOST_PP_IIF(p##(7), 7, 8)
# define QSBOOST_PP_NODE_12(p) QSBOOST_PP_IIF(p##(12), QSBOOST_PP_NODE_10, QSBOOST_PP_NODE_14)
# define QSBOOST_PP_NODE_10(p) QSBOOST_PP_IIF(p##(10), QSBOOST_PP_NODE_9, QSBOOST_PP_NODE_11)
# define QSBOOST_PP_NODE_9(p) QSBOOST_PP_IIF(p##(9), 9, 10)
# define QSBOOST_PP_NODE_11(p) QSBOOST_PP_IIF(p##(11), 11, 12)
# define QSBOOST_PP_NODE_14(p) QSBOOST_PP_IIF(p##(14), QSBOOST_PP_NODE_13, QSBOOST_PP_NODE_15)
# define QSBOOST_PP_NODE_13(p) QSBOOST_PP_IIF(p##(13), 13, 14)
# define QSBOOST_PP_NODE_15(p) QSBOOST_PP_IIF(p##(15), 15, 16)
# define QSBOOST_PP_NODE_24(p) QSBOOST_PP_IIF(p##(24), QSBOOST_PP_NODE_20, QSBOOST_PP_NODE_28)
# define QSBOOST_PP_NODE_20(p) QSBOOST_PP_IIF(p##(20), QSBOOST_PP_NODE_18, QSBOOST_PP_NODE_22)
# define QSBOOST_PP_NODE_18(p) QSBOOST_PP_IIF(p##(18), QSBOOST_PP_NODE_17, QSBOOST_PP_NODE_19)
# define QSBOOST_PP_NODE_17(p) QSBOOST_PP_IIF(p##(17), 17, 18)
# define QSBOOST_PP_NODE_19(p) QSBOOST_PP_IIF(p##(19), 19, 20)
# define QSBOOST_PP_NODE_22(p) QSBOOST_PP_IIF(p##(22), QSBOOST_PP_NODE_21, QSBOOST_PP_NODE_23)
# define QSBOOST_PP_NODE_21(p) QSBOOST_PP_IIF(p##(21), 21, 22)
# define QSBOOST_PP_NODE_23(p) QSBOOST_PP_IIF(p##(23), 23, 24)
# define QSBOOST_PP_NODE_28(p) QSBOOST_PP_IIF(p##(28), QSBOOST_PP_NODE_26, QSBOOST_PP_NODE_30)
# define QSBOOST_PP_NODE_26(p) QSBOOST_PP_IIF(p##(26), QSBOOST_PP_NODE_25, QSBOOST_PP_NODE_27)
# define QSBOOST_PP_NODE_25(p) QSBOOST_PP_IIF(p##(25), 25, 26)
# define QSBOOST_PP_NODE_27(p) QSBOOST_PP_IIF(p##(27), 27, 28)
# define QSBOOST_PP_NODE_30(p) QSBOOST_PP_IIF(p##(30), QSBOOST_PP_NODE_29, QSBOOST_PP_NODE_31)
# define QSBOOST_PP_NODE_29(p) QSBOOST_PP_IIF(p##(29), 29, 30)
# define QSBOOST_PP_NODE_31(p) QSBOOST_PP_IIF(p##(31), 31, 32)
# define QSBOOST_PP_NODE_48(p) QSBOOST_PP_IIF(p##(48), QSBOOST_PP_NODE_40, QSBOOST_PP_NODE_56)
# define QSBOOST_PP_NODE_40(p) QSBOOST_PP_IIF(p##(40), QSBOOST_PP_NODE_36, QSBOOST_PP_NODE_44)
# define QSBOOST_PP_NODE_36(p) QSBOOST_PP_IIF(p##(36), QSBOOST_PP_NODE_34, QSBOOST_PP_NODE_38)
# define QSBOOST_PP_NODE_34(p) QSBOOST_PP_IIF(p##(34), QSBOOST_PP_NODE_33, QSBOOST_PP_NODE_35)
# define QSBOOST_PP_NODE_33(p) QSBOOST_PP_IIF(p##(33), 33, 34)
# define QSBOOST_PP_NODE_35(p) QSBOOST_PP_IIF(p##(35), 35, 36)
# define QSBOOST_PP_NODE_38(p) QSBOOST_PP_IIF(p##(38), QSBOOST_PP_NODE_37, QSBOOST_PP_NODE_39)
# define QSBOOST_PP_NODE_37(p) QSBOOST_PP_IIF(p##(37), 37, 38)
# define QSBOOST_PP_NODE_39(p) QSBOOST_PP_IIF(p##(39), 39, 40)
# define QSBOOST_PP_NODE_44(p) QSBOOST_PP_IIF(p##(44), QSBOOST_PP_NODE_42, QSBOOST_PP_NODE_46)
# define QSBOOST_PP_NODE_42(p) QSBOOST_PP_IIF(p##(42), QSBOOST_PP_NODE_41, QSBOOST_PP_NODE_43)
# define QSBOOST_PP_NODE_41(p) QSBOOST_PP_IIF(p##(41), 41, 42)
# define QSBOOST_PP_NODE_43(p) QSBOOST_PP_IIF(p##(43), 43, 44)
# define QSBOOST_PP_NODE_46(p) QSBOOST_PP_IIF(p##(46), QSBOOST_PP_NODE_45, QSBOOST_PP_NODE_47)
# define QSBOOST_PP_NODE_45(p) QSBOOST_PP_IIF(p##(45), 45, 46)
# define QSBOOST_PP_NODE_47(p) QSBOOST_PP_IIF(p##(47), 47, 48)
# define QSBOOST_PP_NODE_56(p) QSBOOST_PP_IIF(p##(56), QSBOOST_PP_NODE_52, QSBOOST_PP_NODE_60)
# define QSBOOST_PP_NODE_52(p) QSBOOST_PP_IIF(p##(52), QSBOOST_PP_NODE_50, QSBOOST_PP_NODE_54)
# define QSBOOST_PP_NODE_50(p) QSBOOST_PP_IIF(p##(50), QSBOOST_PP_NODE_49, QSBOOST_PP_NODE_51)
# define QSBOOST_PP_NODE_49(p) QSBOOST_PP_IIF(p##(49), 49, 50)
# define QSBOOST_PP_NODE_51(p) QSBOOST_PP_IIF(p##(51), 51, 52)
# define QSBOOST_PP_NODE_54(p) QSBOOST_PP_IIF(p##(54), QSBOOST_PP_NODE_53, QSBOOST_PP_NODE_55)
# define QSBOOST_PP_NODE_53(p) QSBOOST_PP_IIF(p##(53), 53, 54)
# define QSBOOST_PP_NODE_55(p) QSBOOST_PP_IIF(p##(55), 55, 56)
# define QSBOOST_PP_NODE_60(p) QSBOOST_PP_IIF(p##(60), QSBOOST_PP_NODE_58, QSBOOST_PP_NODE_62)
# define QSBOOST_PP_NODE_58(p) QSBOOST_PP_IIF(p##(58), QSBOOST_PP_NODE_57, QSBOOST_PP_NODE_59)
# define QSBOOST_PP_NODE_57(p) QSBOOST_PP_IIF(p##(57), 57, 58)
# define QSBOOST_PP_NODE_59(p) QSBOOST_PP_IIF(p##(59), 59, 60)
# define QSBOOST_PP_NODE_62(p) QSBOOST_PP_IIF(p##(62), QSBOOST_PP_NODE_61, QSBOOST_PP_NODE_63)
# define QSBOOST_PP_NODE_61(p) QSBOOST_PP_IIF(p##(61), 61, 62)
# define QSBOOST_PP_NODE_63(p) QSBOOST_PP_IIF(p##(63), 63, 64)
# define QSBOOST_PP_NODE_96(p) QSBOOST_PP_IIF(p##(96), QSBOOST_PP_NODE_80, QSBOOST_PP_NODE_112)
# define QSBOOST_PP_NODE_80(p) QSBOOST_PP_IIF(p##(80), QSBOOST_PP_NODE_72, QSBOOST_PP_NODE_88)
# define QSBOOST_PP_NODE_72(p) QSBOOST_PP_IIF(p##(72), QSBOOST_PP_NODE_68, QSBOOST_PP_NODE_76)
# define QSBOOST_PP_NODE_68(p) QSBOOST_PP_IIF(p##(68), QSBOOST_PP_NODE_66, QSBOOST_PP_NODE_70)
# define QSBOOST_PP_NODE_66(p) QSBOOST_PP_IIF(p##(66), QSBOOST_PP_NODE_65, QSBOOST_PP_NODE_67)
# define QSBOOST_PP_NODE_65(p) QSBOOST_PP_IIF(p##(65), 65, 66)
# define QSBOOST_PP_NODE_67(p) QSBOOST_PP_IIF(p##(67), 67, 68)
# define QSBOOST_PP_NODE_70(p) QSBOOST_PP_IIF(p##(70), QSBOOST_PP_NODE_69, QSBOOST_PP_NODE_71)
# define QSBOOST_PP_NODE_69(p) QSBOOST_PP_IIF(p##(69), 69, 70)
# define QSBOOST_PP_NODE_71(p) QSBOOST_PP_IIF(p##(71), 71, 72)
# define QSBOOST_PP_NODE_76(p) QSBOOST_PP_IIF(p##(76), QSBOOST_PP_NODE_74, QSBOOST_PP_NODE_78)
# define QSBOOST_PP_NODE_74(p) QSBOOST_PP_IIF(p##(74), QSBOOST_PP_NODE_73, QSBOOST_PP_NODE_75)
# define QSBOOST_PP_NODE_73(p) QSBOOST_PP_IIF(p##(73), 73, 74)
# define QSBOOST_PP_NODE_75(p) QSBOOST_PP_IIF(p##(75), 75, 76)
# define QSBOOST_PP_NODE_78(p) QSBOOST_PP_IIF(p##(78), QSBOOST_PP_NODE_77, QSBOOST_PP_NODE_79)
# define QSBOOST_PP_NODE_77(p) QSBOOST_PP_IIF(p##(77), 77, 78)
# define QSBOOST_PP_NODE_79(p) QSBOOST_PP_IIF(p##(79), 79, 80)
# define QSBOOST_PP_NODE_88(p) QSBOOST_PP_IIF(p##(88), QSBOOST_PP_NODE_84, QSBOOST_PP_NODE_92)
# define QSBOOST_PP_NODE_84(p) QSBOOST_PP_IIF(p##(84), QSBOOST_PP_NODE_82, QSBOOST_PP_NODE_86)
# define QSBOOST_PP_NODE_82(p) QSBOOST_PP_IIF(p##(82), QSBOOST_PP_NODE_81, QSBOOST_PP_NODE_83)
# define QSBOOST_PP_NODE_81(p) QSBOOST_PP_IIF(p##(81), 81, 82)
# define QSBOOST_PP_NODE_83(p) QSBOOST_PP_IIF(p##(83), 83, 84)
# define QSBOOST_PP_NODE_86(p) QSBOOST_PP_IIF(p##(86), QSBOOST_PP_NODE_85, QSBOOST_PP_NODE_87)
# define QSBOOST_PP_NODE_85(p) QSBOOST_PP_IIF(p##(85), 85, 86)
# define QSBOOST_PP_NODE_87(p) QSBOOST_PP_IIF(p##(87), 87, 88)
# define QSBOOST_PP_NODE_92(p) QSBOOST_PP_IIF(p##(92), QSBOOST_PP_NODE_90, QSBOOST_PP_NODE_94)
# define QSBOOST_PP_NODE_90(p) QSBOOST_PP_IIF(p##(90), QSBOOST_PP_NODE_89, QSBOOST_PP_NODE_91)
# define QSBOOST_PP_NODE_89(p) QSBOOST_PP_IIF(p##(89), 89, 90)
# define QSBOOST_PP_NODE_91(p) QSBOOST_PP_IIF(p##(91), 91, 92)
# define QSBOOST_PP_NODE_94(p) QSBOOST_PP_IIF(p##(94), QSBOOST_PP_NODE_93, QSBOOST_PP_NODE_95)
# define QSBOOST_PP_NODE_93(p) QSBOOST_PP_IIF(p##(93), 93, 94)
# define QSBOOST_PP_NODE_95(p) QSBOOST_PP_IIF(p##(95), 95, 96)
# define QSBOOST_PP_NODE_112(p) QSBOOST_PP_IIF(p##(112), QSBOOST_PP_NODE_104, QSBOOST_PP_NODE_120)
# define QSBOOST_PP_NODE_104(p) QSBOOST_PP_IIF(p##(104), QSBOOST_PP_NODE_100, QSBOOST_PP_NODE_108)
# define QSBOOST_PP_NODE_100(p) QSBOOST_PP_IIF(p##(100), QSBOOST_PP_NODE_98, QSBOOST_PP_NODE_102)
# define QSBOOST_PP_NODE_98(p) QSBOOST_PP_IIF(p##(98), QSBOOST_PP_NODE_97, QSBOOST_PP_NODE_99)
# define QSBOOST_PP_NODE_97(p) QSBOOST_PP_IIF(p##(97), 97, 98)
# define QSBOOST_PP_NODE_99(p) QSBOOST_PP_IIF(p##(99), 99, 100)
# define QSBOOST_PP_NODE_102(p) QSBOOST_PP_IIF(p##(102), QSBOOST_PP_NODE_101, QSBOOST_PP_NODE_103)
# define QSBOOST_PP_NODE_101(p) QSBOOST_PP_IIF(p##(101), 101, 102)
# define QSBOOST_PP_NODE_103(p) QSBOOST_PP_IIF(p##(103), 103, 104)
# define QSBOOST_PP_NODE_108(p) QSBOOST_PP_IIF(p##(108), QSBOOST_PP_NODE_106, QSBOOST_PP_NODE_110)
# define QSBOOST_PP_NODE_106(p) QSBOOST_PP_IIF(p##(106), QSBOOST_PP_NODE_105, QSBOOST_PP_NODE_107)
# define QSBOOST_PP_NODE_105(p) QSBOOST_PP_IIF(p##(105), 105, 106)
# define QSBOOST_PP_NODE_107(p) QSBOOST_PP_IIF(p##(107), 107, 108)
# define QSBOOST_PP_NODE_110(p) QSBOOST_PP_IIF(p##(110), QSBOOST_PP_NODE_109, QSBOOST_PP_NODE_111)
# define QSBOOST_PP_NODE_109(p) QSBOOST_PP_IIF(p##(109), 109, 110)
# define QSBOOST_PP_NODE_111(p) QSBOOST_PP_IIF(p##(111), 111, 112)
# define QSBOOST_PP_NODE_120(p) QSBOOST_PP_IIF(p##(120), QSBOOST_PP_NODE_116, QSBOOST_PP_NODE_124)
# define QSBOOST_PP_NODE_116(p) QSBOOST_PP_IIF(p##(116), QSBOOST_PP_NODE_114, QSBOOST_PP_NODE_118)
# define QSBOOST_PP_NODE_114(p) QSBOOST_PP_IIF(p##(114), QSBOOST_PP_NODE_113, QSBOOST_PP_NODE_115)
# define QSBOOST_PP_NODE_113(p) QSBOOST_PP_IIF(p##(113), 113, 114)
# define QSBOOST_PP_NODE_115(p) QSBOOST_PP_IIF(p##(115), 115, 116)
# define QSBOOST_PP_NODE_118(p) QSBOOST_PP_IIF(p##(118), QSBOOST_PP_NODE_117, QSBOOST_PP_NODE_119)
# define QSBOOST_PP_NODE_117(p) QSBOOST_PP_IIF(p##(117), 117, 118)
# define QSBOOST_PP_NODE_119(p) QSBOOST_PP_IIF(p##(119), 119, 120)
# define QSBOOST_PP_NODE_124(p) QSBOOST_PP_IIF(p##(124), QSBOOST_PP_NODE_122, QSBOOST_PP_NODE_126)
# define QSBOOST_PP_NODE_122(p) QSBOOST_PP_IIF(p##(122), QSBOOST_PP_NODE_121, QSBOOST_PP_NODE_123)
# define QSBOOST_PP_NODE_121(p) QSBOOST_PP_IIF(p##(121), 121, 122)
# define QSBOOST_PP_NODE_123(p) QSBOOST_PP_IIF(p##(123), 123, 124)
# define QSBOOST_PP_NODE_126(p) QSBOOST_PP_IIF(p##(126), QSBOOST_PP_NODE_125, QSBOOST_PP_NODE_127)
# define QSBOOST_PP_NODE_125(p) QSBOOST_PP_IIF(p##(125), 125, 126)
# define QSBOOST_PP_NODE_127(p) QSBOOST_PP_IIF(p##(127), 127, 128)
# define QSBOOST_PP_NODE_192(p) QSBOOST_PP_IIF(p##(192), QSBOOST_PP_NODE_160, QSBOOST_PP_NODE_224)
# define QSBOOST_PP_NODE_160(p) QSBOOST_PP_IIF(p##(160), QSBOOST_PP_NODE_144, QSBOOST_PP_NODE_176)
# define QSBOOST_PP_NODE_144(p) QSBOOST_PP_IIF(p##(144), QSBOOST_PP_NODE_136, QSBOOST_PP_NODE_152)
# define QSBOOST_PP_NODE_136(p) QSBOOST_PP_IIF(p##(136), QSBOOST_PP_NODE_132, QSBOOST_PP_NODE_140)
# define QSBOOST_PP_NODE_132(p) QSBOOST_PP_IIF(p##(132), QSBOOST_PP_NODE_130, QSBOOST_PP_NODE_134)
# define QSBOOST_PP_NODE_130(p) QSBOOST_PP_IIF(p##(130), QSBOOST_PP_NODE_129, QSBOOST_PP_NODE_131)
# define QSBOOST_PP_NODE_129(p) QSBOOST_PP_IIF(p##(129), 129, 130)
# define QSBOOST_PP_NODE_131(p) QSBOOST_PP_IIF(p##(131), 131, 132)
# define QSBOOST_PP_NODE_134(p) QSBOOST_PP_IIF(p##(134), QSBOOST_PP_NODE_133, QSBOOST_PP_NODE_135)
# define QSBOOST_PP_NODE_133(p) QSBOOST_PP_IIF(p##(133), 133, 134)
# define QSBOOST_PP_NODE_135(p) QSBOOST_PP_IIF(p##(135), 135, 136)
# define QSBOOST_PP_NODE_140(p) QSBOOST_PP_IIF(p##(140), QSBOOST_PP_NODE_138, QSBOOST_PP_NODE_142)
# define QSBOOST_PP_NODE_138(p) QSBOOST_PP_IIF(p##(138), QSBOOST_PP_NODE_137, QSBOOST_PP_NODE_139)
# define QSBOOST_PP_NODE_137(p) QSBOOST_PP_IIF(p##(137), 137, 138)
# define QSBOOST_PP_NODE_139(p) QSBOOST_PP_IIF(p##(139), 139, 140)
# define QSBOOST_PP_NODE_142(p) QSBOOST_PP_IIF(p##(142), QSBOOST_PP_NODE_141, QSBOOST_PP_NODE_143)
# define QSBOOST_PP_NODE_141(p) QSBOOST_PP_IIF(p##(141), 141, 142)
# define QSBOOST_PP_NODE_143(p) QSBOOST_PP_IIF(p##(143), 143, 144)
# define QSBOOST_PP_NODE_152(p) QSBOOST_PP_IIF(p##(152), QSBOOST_PP_NODE_148, QSBOOST_PP_NODE_156)
# define QSBOOST_PP_NODE_148(p) QSBOOST_PP_IIF(p##(148), QSBOOST_PP_NODE_146, QSBOOST_PP_NODE_150)
# define QSBOOST_PP_NODE_146(p) QSBOOST_PP_IIF(p##(146), QSBOOST_PP_NODE_145, QSBOOST_PP_NODE_147)
# define QSBOOST_PP_NODE_145(p) QSBOOST_PP_IIF(p##(145), 145, 146)
# define QSBOOST_PP_NODE_147(p) QSBOOST_PP_IIF(p##(147), 147, 148)
# define QSBOOST_PP_NODE_150(p) QSBOOST_PP_IIF(p##(150), QSBOOST_PP_NODE_149, QSBOOST_PP_NODE_151)
# define QSBOOST_PP_NODE_149(p) QSBOOST_PP_IIF(p##(149), 149, 150)
# define QSBOOST_PP_NODE_151(p) QSBOOST_PP_IIF(p##(151), 151, 152)
# define QSBOOST_PP_NODE_156(p) QSBOOST_PP_IIF(p##(156), QSBOOST_PP_NODE_154, QSBOOST_PP_NODE_158)
# define QSBOOST_PP_NODE_154(p) QSBOOST_PP_IIF(p##(154), QSBOOST_PP_NODE_153, QSBOOST_PP_NODE_155)
# define QSBOOST_PP_NODE_153(p) QSBOOST_PP_IIF(p##(153), 153, 154)
# define QSBOOST_PP_NODE_155(p) QSBOOST_PP_IIF(p##(155), 155, 156)
# define QSBOOST_PP_NODE_158(p) QSBOOST_PP_IIF(p##(158), QSBOOST_PP_NODE_157, QSBOOST_PP_NODE_159)
# define QSBOOST_PP_NODE_157(p) QSBOOST_PP_IIF(p##(157), 157, 158)
# define QSBOOST_PP_NODE_159(p) QSBOOST_PP_IIF(p##(159), 159, 160)
# define QSBOOST_PP_NODE_176(p) QSBOOST_PP_IIF(p##(176), QSBOOST_PP_NODE_168, QSBOOST_PP_NODE_184)
# define QSBOOST_PP_NODE_168(p) QSBOOST_PP_IIF(p##(168), QSBOOST_PP_NODE_164, QSBOOST_PP_NODE_172)
# define QSBOOST_PP_NODE_164(p) QSBOOST_PP_IIF(p##(164), QSBOOST_PP_NODE_162, QSBOOST_PP_NODE_166)
# define QSBOOST_PP_NODE_162(p) QSBOOST_PP_IIF(p##(162), QSBOOST_PP_NODE_161, QSBOOST_PP_NODE_163)
# define QSBOOST_PP_NODE_161(p) QSBOOST_PP_IIF(p##(161), 161, 162)
# define QSBOOST_PP_NODE_163(p) QSBOOST_PP_IIF(p##(163), 163, 164)
# define QSBOOST_PP_NODE_166(p) QSBOOST_PP_IIF(p##(166), QSBOOST_PP_NODE_165, QSBOOST_PP_NODE_167)
# define QSBOOST_PP_NODE_165(p) QSBOOST_PP_IIF(p##(165), 165, 166)
# define QSBOOST_PP_NODE_167(p) QSBOOST_PP_IIF(p##(167), 167, 168)
# define QSBOOST_PP_NODE_172(p) QSBOOST_PP_IIF(p##(172), QSBOOST_PP_NODE_170, QSBOOST_PP_NODE_174)
# define QSBOOST_PP_NODE_170(p) QSBOOST_PP_IIF(p##(170), QSBOOST_PP_NODE_169, QSBOOST_PP_NODE_171)
# define QSBOOST_PP_NODE_169(p) QSBOOST_PP_IIF(p##(169), 169, 170)
# define QSBOOST_PP_NODE_171(p) QSBOOST_PP_IIF(p##(171), 171, 172)
# define QSBOOST_PP_NODE_174(p) QSBOOST_PP_IIF(p##(174), QSBOOST_PP_NODE_173, QSBOOST_PP_NODE_175)
# define QSBOOST_PP_NODE_173(p) QSBOOST_PP_IIF(p##(173), 173, 174)
# define QSBOOST_PP_NODE_175(p) QSBOOST_PP_IIF(p##(175), 175, 176)
# define QSBOOST_PP_NODE_184(p) QSBOOST_PP_IIF(p##(184), QSBOOST_PP_NODE_180, QSBOOST_PP_NODE_188)
# define QSBOOST_PP_NODE_180(p) QSBOOST_PP_IIF(p##(180), QSBOOST_PP_NODE_178, QSBOOST_PP_NODE_182)
# define QSBOOST_PP_NODE_178(p) QSBOOST_PP_IIF(p##(178), QSBOOST_PP_NODE_177, QSBOOST_PP_NODE_179)
# define QSBOOST_PP_NODE_177(p) QSBOOST_PP_IIF(p##(177), 177, 178)
# define QSBOOST_PP_NODE_179(p) QSBOOST_PP_IIF(p##(179), 179, 180)
# define QSBOOST_PP_NODE_182(p) QSBOOST_PP_IIF(p##(182), QSBOOST_PP_NODE_181, QSBOOST_PP_NODE_183)
# define QSBOOST_PP_NODE_181(p) QSBOOST_PP_IIF(p##(181), 181, 182)
# define QSBOOST_PP_NODE_183(p) QSBOOST_PP_IIF(p##(183), 183, 184)
# define QSBOOST_PP_NODE_188(p) QSBOOST_PP_IIF(p##(188), QSBOOST_PP_NODE_186, QSBOOST_PP_NODE_190)
# define QSBOOST_PP_NODE_186(p) QSBOOST_PP_IIF(p##(186), QSBOOST_PP_NODE_185, QSBOOST_PP_NODE_187)
# define QSBOOST_PP_NODE_185(p) QSBOOST_PP_IIF(p##(185), 185, 186)
# define QSBOOST_PP_NODE_187(p) QSBOOST_PP_IIF(p##(187), 187, 188)
# define QSBOOST_PP_NODE_190(p) QSBOOST_PP_IIF(p##(190), QSBOOST_PP_NODE_189, QSBOOST_PP_NODE_191)
# define QSBOOST_PP_NODE_189(p) QSBOOST_PP_IIF(p##(189), 189, 190)
# define QSBOOST_PP_NODE_191(p) QSBOOST_PP_IIF(p##(191), 191, 192)
# define QSBOOST_PP_NODE_224(p) QSBOOST_PP_IIF(p##(224), QSBOOST_PP_NODE_208, QSBOOST_PP_NODE_240)
# define QSBOOST_PP_NODE_208(p) QSBOOST_PP_IIF(p##(208), QSBOOST_PP_NODE_200, QSBOOST_PP_NODE_216)
# define QSBOOST_PP_NODE_200(p) QSBOOST_PP_IIF(p##(200), QSBOOST_PP_NODE_196, QSBOOST_PP_NODE_204)
# define QSBOOST_PP_NODE_196(p) QSBOOST_PP_IIF(p##(196), QSBOOST_PP_NODE_194, QSBOOST_PP_NODE_198)
# define QSBOOST_PP_NODE_194(p) QSBOOST_PP_IIF(p##(194), QSBOOST_PP_NODE_193, QSBOOST_PP_NODE_195)
# define QSBOOST_PP_NODE_193(p) QSBOOST_PP_IIF(p##(193), 193, 194)
# define QSBOOST_PP_NODE_195(p) QSBOOST_PP_IIF(p##(195), 195, 196)
# define QSBOOST_PP_NODE_198(p) QSBOOST_PP_IIF(p##(198), QSBOOST_PP_NODE_197, QSBOOST_PP_NODE_199)
# define QSBOOST_PP_NODE_197(p) QSBOOST_PP_IIF(p##(197), 197, 198)
# define QSBOOST_PP_NODE_199(p) QSBOOST_PP_IIF(p##(199), 199, 200)
# define QSBOOST_PP_NODE_204(p) QSBOOST_PP_IIF(p##(204), QSBOOST_PP_NODE_202, QSBOOST_PP_NODE_206)
# define QSBOOST_PP_NODE_202(p) QSBOOST_PP_IIF(p##(202), QSBOOST_PP_NODE_201, QSBOOST_PP_NODE_203)
# define QSBOOST_PP_NODE_201(p) QSBOOST_PP_IIF(p##(201), 201, 202)
# define QSBOOST_PP_NODE_203(p) QSBOOST_PP_IIF(p##(203), 203, 204)
# define QSBOOST_PP_NODE_206(p) QSBOOST_PP_IIF(p##(206), QSBOOST_PP_NODE_205, QSBOOST_PP_NODE_207)
# define QSBOOST_PP_NODE_205(p) QSBOOST_PP_IIF(p##(205), 205, 206)
# define QSBOOST_PP_NODE_207(p) QSBOOST_PP_IIF(p##(207), 207, 208)
# define QSBOOST_PP_NODE_216(p) QSBOOST_PP_IIF(p##(216), QSBOOST_PP_NODE_212, QSBOOST_PP_NODE_220)
# define QSBOOST_PP_NODE_212(p) QSBOOST_PP_IIF(p##(212), QSBOOST_PP_NODE_210, QSBOOST_PP_NODE_214)
# define QSBOOST_PP_NODE_210(p) QSBOOST_PP_IIF(p##(210), QSBOOST_PP_NODE_209, QSBOOST_PP_NODE_211)
# define QSBOOST_PP_NODE_209(p) QSBOOST_PP_IIF(p##(209), 209, 210)
# define QSBOOST_PP_NODE_211(p) QSBOOST_PP_IIF(p##(211), 211, 212)
# define QSBOOST_PP_NODE_214(p) QSBOOST_PP_IIF(p##(214), QSBOOST_PP_NODE_213, QSBOOST_PP_NODE_215)
# define QSBOOST_PP_NODE_213(p) QSBOOST_PP_IIF(p##(213), 213, 214)
# define QSBOOST_PP_NODE_215(p) QSBOOST_PP_IIF(p##(215), 215, 216)
# define QSBOOST_PP_NODE_220(p) QSBOOST_PP_IIF(p##(220), QSBOOST_PP_NODE_218, QSBOOST_PP_NODE_222)
# define QSBOOST_PP_NODE_218(p) QSBOOST_PP_IIF(p##(218), QSBOOST_PP_NODE_217, QSBOOST_PP_NODE_219)
# define QSBOOST_PP_NODE_217(p) QSBOOST_PP_IIF(p##(217), 217, 218)
# define QSBOOST_PP_NODE_219(p) QSBOOST_PP_IIF(p##(219), 219, 220)
# define QSBOOST_PP_NODE_222(p) QSBOOST_PP_IIF(p##(222), QSBOOST_PP_NODE_221, QSBOOST_PP_NODE_223)
# define QSBOOST_PP_NODE_221(p) QSBOOST_PP_IIF(p##(221), 221, 222)
# define QSBOOST_PP_NODE_223(p) QSBOOST_PP_IIF(p##(223), 223, 224)
# define QSBOOST_PP_NODE_240(p) QSBOOST_PP_IIF(p##(240), QSBOOST_PP_NODE_232, QSBOOST_PP_NODE_248)
# define QSBOOST_PP_NODE_232(p) QSBOOST_PP_IIF(p##(232), QSBOOST_PP_NODE_228, QSBOOST_PP_NODE_236)
# define QSBOOST_PP_NODE_228(p) QSBOOST_PP_IIF(p##(228), QSBOOST_PP_NODE_226, QSBOOST_PP_NODE_230)
# define QSBOOST_PP_NODE_226(p) QSBOOST_PP_IIF(p##(226), QSBOOST_PP_NODE_225, QSBOOST_PP_NODE_227)
# define QSBOOST_PP_NODE_225(p) QSBOOST_PP_IIF(p##(225), 225, 226)
# define QSBOOST_PP_NODE_227(p) QSBOOST_PP_IIF(p##(227), 227, 228)
# define QSBOOST_PP_NODE_230(p) QSBOOST_PP_IIF(p##(230), QSBOOST_PP_NODE_229, QSBOOST_PP_NODE_231)
# define QSBOOST_PP_NODE_229(p) QSBOOST_PP_IIF(p##(229), 229, 230)
# define QSBOOST_PP_NODE_231(p) QSBOOST_PP_IIF(p##(231), 231, 232)
# define QSBOOST_PP_NODE_236(p) QSBOOST_PP_IIF(p##(236), QSBOOST_PP_NODE_234, QSBOOST_PP_NODE_238)
# define QSBOOST_PP_NODE_234(p) QSBOOST_PP_IIF(p##(234), QSBOOST_PP_NODE_233, QSBOOST_PP_NODE_235)
# define QSBOOST_PP_NODE_233(p) QSBOOST_PP_IIF(p##(233), 233, 234)
# define QSBOOST_PP_NODE_235(p) QSBOOST_PP_IIF(p##(235), 235, 236)
# define QSBOOST_PP_NODE_238(p) QSBOOST_PP_IIF(p##(238), QSBOOST_PP_NODE_237, QSBOOST_PP_NODE_239)
# define QSBOOST_PP_NODE_237(p) QSBOOST_PP_IIF(p##(237), 237, 238)
# define QSBOOST_PP_NODE_239(p) QSBOOST_PP_IIF(p##(239), 239, 240)
# define QSBOOST_PP_NODE_248(p) QSBOOST_PP_IIF(p##(248), QSBOOST_PP_NODE_244, QSBOOST_PP_NODE_252)
# define QSBOOST_PP_NODE_244(p) QSBOOST_PP_IIF(p##(244), QSBOOST_PP_NODE_242, QSBOOST_PP_NODE_246)
# define QSBOOST_PP_NODE_242(p) QSBOOST_PP_IIF(p##(242), QSBOOST_PP_NODE_241, QSBOOST_PP_NODE_243)
# define QSBOOST_PP_NODE_241(p) QSBOOST_PP_IIF(p##(241), 241, 242)
# define QSBOOST_PP_NODE_243(p) QSBOOST_PP_IIF(p##(243), 243, 244)
# define QSBOOST_PP_NODE_246(p) QSBOOST_PP_IIF(p##(246), QSBOOST_PP_NODE_245, QSBOOST_PP_NODE_247)
# define QSBOOST_PP_NODE_245(p) QSBOOST_PP_IIF(p##(245), 245, 246)
# define QSBOOST_PP_NODE_247(p) QSBOOST_PP_IIF(p##(247), 247, 248)
# define QSBOOST_PP_NODE_252(p) QSBOOST_PP_IIF(p##(252), QSBOOST_PP_NODE_250, QSBOOST_PP_NODE_254)
# define QSBOOST_PP_NODE_250(p) QSBOOST_PP_IIF(p##(250), QSBOOST_PP_NODE_249, QSBOOST_PP_NODE_251)
# define QSBOOST_PP_NODE_249(p) QSBOOST_PP_IIF(p##(249), 249, 250)
# define QSBOOST_PP_NODE_251(p) QSBOOST_PP_IIF(p##(251), 251, 252)
# define QSBOOST_PP_NODE_254(p) QSBOOST_PP_IIF(p##(254), QSBOOST_PP_NODE_253, QSBOOST_PP_NODE_255)
# define QSBOOST_PP_NODE_253(p) QSBOOST_PP_IIF(p##(253), 253, 254)
# define QSBOOST_PP_NODE_255(p) QSBOOST_PP_IIF(p##(255), 255, 256)
#
# endif
| 97.686411 | 121 | 0.613497 | wouterboomsma |
50f7edccc0ac196f1aad25b391b45a3e96e74f17 | 392 | cpp | C++ | C++/LeetCode/1094.cpp | Nimesh-Srivastava/DSA | db33aa138f0df8ab6015d2e8ec3ddde1c6838848 | [
"MIT"
] | 4 | 2021-08-28T19:16:50.000Z | 2022-03-04T19:46:31.000Z | C++/LeetCode/1094.cpp | Nimesh-Srivastava/DSA | db33aa138f0df8ab6015d2e8ec3ddde1c6838848 | [
"MIT"
] | 8 | 2021-10-29T19:10:51.000Z | 2021-11-03T12:38:00.000Z | C++/LeetCode/1094.cpp | Nimesh-Srivastava/DSA | db33aa138f0df8ab6015d2e8ec3ddde1c6838848 | [
"MIT"
] | 4 | 2021-09-06T05:53:07.000Z | 2021-12-24T10:31:40.000Z | class Solution {
public:
bool carPooling(vector<vector<int>>& trips, int capacity) {
vector<int> stops(1001);
for(auto& t : trips){
stops[t[1]] += t[0];
stops[t[2]] -= t[0];
}
for(int i = 0; i < 1001 && capacity >= 0; i++)
capacity -= stops[i];
return capacity >= 0;
}
};
| 21.777778 | 63 | 0.420918 | Nimesh-Srivastava |
50fcb736c46786162e91826264882395b4d35651 | 564 | cpp | C++ | C++/Majority Element.cpp | mafia1989/leetcode | f0bc9708a58602866818120556d8b8caf114811e | [
"MIT"
] | 3 | 2015-08-29T15:25:13.000Z | 2015-08-29T15:25:21.000Z | C++/Majority Element.cpp | mafia1989/leetcode | f0bc9708a58602866818120556d8b8caf114811e | [
"MIT"
] | null | null | null | C++/Majority Element.cpp | mafia1989/leetcode | f0bc9708a58602866818120556d8b8caf114811e | [
"MIT"
] | null | null | null | // Majority Element
// Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
// You may assume that the array is non-empty and the majority element always exist in the array.
// Credits:
// Special thanks to @ts for adding this problem and creating all test cases.
// My Solution
class Solution {
public:
int majorityElement(vector<int>& nums)
{
sort(nums.begin(),nums.end());
int i = nums.size()/2;
return nums[i];
}
};
| 22.56 | 129 | 0.636525 | mafia1989 |
dd0d393b57d2f50c574c998da4e07d6290419fc5 | 3,184 | hpp | C++ | android-31/java/lang/Integer.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/java/lang/Integer.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/java/lang/Integer.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #pragma once
#include "./Number.hpp"
class JByteArray;
class JCharArray;
class JIntArray;
class JString;
class JClass;
class JObject;
class JString;
namespace java::lang::invoke
{
class MethodHandles_Lookup;
}
namespace java::util
{
class Optional;
}
namespace java::lang
{
class Integer : public java::lang::Number
{
public:
// Fields
static jint BYTES();
static jint MAX_VALUE();
static jint MIN_VALUE();
static jint SIZE();
static JClass TYPE();
// QJniObject forward
template<typename ...Ts> explicit Integer(const char *className, const char *sig, Ts...agv) : java::lang::Number(className, sig, std::forward<Ts>(agv)...) {}
Integer(QJniObject obj);
// Constructors
Integer(jint arg0);
Integer(JString arg0);
// Methods
static jint bitCount(jint arg0);
static jint compare(jint arg0, jint arg1);
static jint compareUnsigned(jint arg0, jint arg1);
static java::lang::Integer decode(JString arg0);
static jint divideUnsigned(jint arg0, jint arg1);
static java::lang::Integer getInteger(JString arg0);
static java::lang::Integer getInteger(JString arg0, jint arg1);
static java::lang::Integer getInteger(JString arg0, java::lang::Integer arg1);
static jint hashCode(jint arg0);
static jint highestOneBit(jint arg0);
static jint lowestOneBit(jint arg0);
static jint max(jint arg0, jint arg1);
static jint min(jint arg0, jint arg1);
static jint numberOfLeadingZeros(jint arg0);
static jint numberOfTrailingZeros(jint arg0);
static jint parseInt(JString arg0);
static jint parseInt(JString arg0, jint arg1);
static jint parseInt(JString arg0, jint arg1, jint arg2, jint arg3);
static jint parseUnsignedInt(JString arg0);
static jint parseUnsignedInt(JString arg0, jint arg1);
static jint parseUnsignedInt(JString arg0, jint arg1, jint arg2, jint arg3);
static jint remainderUnsigned(jint arg0, jint arg1);
static jint reverse(jint arg0);
static jint reverseBytes(jint arg0);
static jint rotateLeft(jint arg0, jint arg1);
static jint rotateRight(jint arg0, jint arg1);
static jint signum(jint arg0);
static jint sum(jint arg0, jint arg1);
static JString toBinaryString(jint arg0);
static JString toHexString(jint arg0);
static JString toOctalString(jint arg0);
static JString toString(jint arg0);
static JString toString(jint arg0, jint arg1);
static jlong toUnsignedLong(jint arg0);
static JString toUnsignedString(jint arg0);
static JString toUnsignedString(jint arg0, jint arg1);
static java::lang::Integer valueOf(jint arg0);
static java::lang::Integer valueOf(JString arg0);
static java::lang::Integer valueOf(JString arg0, jint arg1);
jbyte byteValue() const;
jint compareTo(java::lang::Integer arg0) const;
jint compareTo(JObject arg0) const;
java::util::Optional describeConstable() const;
jdouble doubleValue() const;
jboolean equals(JObject arg0) const;
jfloat floatValue() const;
jint hashCode() const;
jint intValue() const;
jlong longValue() const;
java::lang::Integer resolveConstantDesc(java::lang::invoke::MethodHandles_Lookup arg0) const;
jshort shortValue() const;
JString toString() const;
};
} // namespace java::lang
| 32.824742 | 159 | 0.742776 | YJBeetle |
dd0ff75d855374f9c747ed9d15eb9f449a830db4 | 2,179 | cpp | C++ | Fuji/Source/MFDisplay.cpp | TurkeyMan/fuji | afd6a26c710ce23965b088ad158fe916d6a1a091 | [
"BSD-2-Clause"
] | 35 | 2015-01-19T22:07:48.000Z | 2022-02-21T22:17:53.000Z | Fuji/Source/MFDisplay.cpp | TurkeyMan/fuji | afd6a26c710ce23965b088ad158fe916d6a1a091 | [
"BSD-2-Clause"
] | 1 | 2022-02-23T09:34:15.000Z | 2022-02-23T09:34:15.000Z | Fuji/Source/MFDisplay.cpp | TurkeyMan/fuji | afd6a26c710ce23965b088ad158fe916d6a1a091 | [
"BSD-2-Clause"
] | 4 | 2015-05-11T03:31:35.000Z | 2018-09-27T04:55:57.000Z | #include "Fuji_Internal.h"
#include "MFDisplay_Internal.h"
#include "DebugMenu.h"
#include "MFView.h"
#include "MFSystem.h"
MFDisplay *gpCurrentDisplay = NULL;
extern MFInitParams gInitParams;
bool gAppHasFocus = true;
MFInitStatus MFDisplay_InitModule(int moduleId, bool bPerformInitialisation)
{
DebugMenu_AddMenu("Display Options", "Fuji Options");
MFDisplay_InitModulePlatformSpecific();
if(!gpCurrentDisplay)
{
gpCurrentDisplay = MFDisplay_CreateDefault("Fuji Display");
if(!gpCurrentDisplay)
return MFIS_Failed;
}
return MFIS_Succeeded;
}
void MFDisplay_DeinitModule()
{
MFDisplay_DeinitModulePlatformSpecific();
}
MF_API MFDisplay *MFDisplay_CreateDefault(const char *pName)
{
MFDisplaySettings displaySettings;
MFDisplay_GetDefaults(&displaySettings);
return MFDisplay_Create(pName, &displaySettings);
}
MF_API MFDisplay *MFDisplay_SetCurrent(MFDisplay *pDisplay)
{
MFDisplay *pOld = gpCurrentDisplay;
gpCurrentDisplay = pDisplay;
return pOld;
}
MF_API MFDisplay *MFDisplay_GetCurrent()
{
return gpCurrentDisplay;
}
MF_API const MFDisplaySettings *MFDisplay_GetDisplaySettings(const MFDisplay *pDisplay)
{
if(!pDisplay)
pDisplay = gpCurrentDisplay;
return &pDisplay->settings;
}
MF_API MFDisplayOrientation MFDisplay_GetDisplayOrientation(const MFDisplay *pDisplay)
{
if(!pDisplay)
pDisplay = gpCurrentDisplay;
return pDisplay->orientation;
}
MF_API void MFDisplay_GetDisplayRect(MFRect *pRect, const MFDisplay *pDisplay)
{
if(!pDisplay)
pDisplay = gpCurrentDisplay;
pRect->x = pRect->y = 0;
pRect->width = (float)pDisplay->settings.width;
pRect->height = (float)pDisplay->settings.height;
}
MF_API float MFDisplay_GetAspectRatio(const MFDisplay *pDisplay)
{
if(!pDisplay)
pDisplay = gpCurrentDisplay;
return pDisplay->aspectRatio;
}
MF_API bool MFDisplay_IsVisible(const MFDisplay *pDisplay)
{
if(!pDisplay)
pDisplay = gpCurrentDisplay;
return pDisplay->bIsVisible;
}
MF_API bool MFDisplay_HasFocus(const MFDisplay *pDisplay)
{
if(!pDisplay)
pDisplay = gpCurrentDisplay;
return pDisplay->bHasFocus;
}
| 21.574257 | 88 | 0.748967 | TurkeyMan |
dd11e279934ebc90ec69eba1ca076e0831883b68 | 340 | cpp | C++ | Data Structures/Priority Queue/1. Basics/HeapUse.cpp | kunal299/Data-Structures-and-Algorithms | 5fed697211566108f732762768da938cfe83ec5f | [
"MIT"
] | 1 | 2022-01-13T14:04:58.000Z | 2022-01-13T14:04:58.000Z | Data Structures/Priority Queue/1. Basics/HeapUse.cpp | kunal299/Data-Structures-and-Algorithms | 5fed697211566108f732762768da938cfe83ec5f | [
"MIT"
] | null | null | null | Data Structures/Priority Queue/1. Basics/HeapUse.cpp | kunal299/Data-Structures-and-Algorithms | 5fed697211566108f732762768da938cfe83ec5f | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
#include "PriorityQueue.h"
int main() {
PriorityQueue p;
p.insert(100);
p.insert(10);
p.insert(15);
p.insert(4);
p.insert(17);
p.insert(21);
p.insert(67);
cout<<p.getSize()<<endl;
cout<<p.getMin()<<endl;
while(!p.isEmpty()) {
cout<<p.removeMin()<<" ";
}
cout<<endl;
return 0;
} | 13.076923 | 27 | 0.617647 | kunal299 |
dd125c3185aab95b520af8e2fb5d78bc92e550ba | 2,283 | hpp | C++ | src/ui/budget/InitialBalanceForm.hpp | vimofthevine/UnderBudget | 5711be8e5da3cb7a78da007fe43cf1ce1b796493 | [
"Apache-2.0"
] | 2 | 2016-07-17T02:12:44.000Z | 2016-11-22T14:04:55.000Z | src/ui/budget/InitialBalanceForm.hpp | vimofthevine/UnderBudget | 5711be8e5da3cb7a78da007fe43cf1ce1b796493 | [
"Apache-2.0"
] | null | null | null | src/ui/budget/InitialBalanceForm.hpp | vimofthevine/UnderBudget | 5711be8e5da3cb7a78da007fe43cf1ce1b796493 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2013 Kyle Treubig
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INITIALBALANCEFORM_HPP
#define INITIALBALANCEFORM_HPP
// Qt include(s)
#include <QIcon>
#include <QSharedPointer>
#include <QWidget>
// UnderBudget include(s)
#include "budget/Balance.hpp"
// Forward declaration(s)
class QPushButton;
namespace ub {
// Forward declaration(s)
class ContributorsListWidget;
class Money;
class MoneyEdit;
/**
* Initial balance input form widget.
*
* @ingroup ui_budget
*/
class InitialBalanceForm : public QWidget
{
Q_OBJECT
public:
/**
* Constructs a new initial balance entry form.
*
* @param[in] balance initial balance being edited by this form
* @param[in] stack undoable command stack
* @param[in] parent parent widget
*/
InitialBalanceForm(QSharedPointer<Balance> balance,
QUndoStack* stack, QWidget* parent = 0);
private slots:
/**
* Updates the initial balance based on the user-entered value.
*
* @param[in] value new initial balance value
*/
void updateValue(const Money& value);
/**
* Updates the net value field.
*/
void updateDisplayedValue();
/**
* Toggles the display of advanced input fields.
*/
void showAdvanced(bool show);
private:
/** Undo stack for all commands */
QUndoStack* undoStack;
/** Balance being modified */
QSharedPointer<Balance> balance;
/** Money entry field */
MoneyEdit* valueField;
/** Show-advanced button */
QPushButton* toggleButton;
/** Add-contributor button */
QPushButton* addButton;
/** Delete-contributor button */
QPushButton* deleteButton;
/** Expand icon */
QIcon expand;
/** Collapse icon */
QIcon collapse;
/** Balance contributors widget */
ContributorsListWidget* contributors;
};
}
#endif //INITIALBALANCEFORM_HPP
| 22.60396 | 75 | 0.722295 | vimofthevine |
dd132877fcebee38e4972f20350b129d64ad637d | 95 | cpp | C++ | launcher/InstanceTask.cpp | Spacc-Inc/MultiMC5-Cracked | 4afe2466fd5639bf8a03bfb866c070e705420d86 | [
"Apache-2.0"
] | 2,777 | 2015-01-02T17:20:34.000Z | 2021-10-20T12:34:27.000Z | launcher/InstanceTask.cpp | Spacc-Inc/MultiMC5-Cracked | 4afe2466fd5639bf8a03bfb866c070e705420d86 | [
"Apache-2.0"
] | 3,537 | 2015-01-01T00:51:03.000Z | 2021-10-20T07:35:33.000Z | launcher/InstanceTask.cpp | Spacc-Inc/MultiMC5-Cracked | 4afe2466fd5639bf8a03bfb866c070e705420d86 | [
"Apache-2.0"
] | 774 | 2015-01-07T19:44:39.000Z | 2021-10-19T18:10:38.000Z | #include "InstanceTask.h"
InstanceTask::InstanceTask()
{
}
InstanceTask::~InstanceTask()
{
}
| 9.5 | 29 | 0.715789 | Spacc-Inc |
dd13a2f00ec8f99b59bf0341a140adaa501a99fa | 1,672 | cpp | C++ | engine/test/ECS/SystemImplementations.cpp | targodan/gameProgramming | 5c0b36bee271dca65636d0317324a2bb786613f0 | [
"MIT"
] | 1 | 2019-07-14T11:32:30.000Z | 2019-07-14T11:32:30.000Z | engine/test/ECS/SystemImplementations.cpp | targodan/gameProgramming | 5c0b36bee271dca65636d0317324a2bb786613f0 | [
"MIT"
] | null | null | null | engine/test/ECS/SystemImplementations.cpp | targodan/gameProgramming | 5c0b36bee271dca65636d0317324a2bb786613f0 | [
"MIT"
] | null | null | null | #include "SystemImplementations.h"
engine::util::BlockingQueue<std::string> __executionQueue;
DEFINE_SYSTEM_ID(TestSystem1);
DEFINE_SYSTEM_ID(TestSystem2);
DEFINE_SYSTEM_ID(TestSystem3);
DEFINE_SYSTEM_ID(TestSystem4);
DEFINE_SYSTEM_ID(TestSystem5);
DEFINE_SYSTEM_ID(TestSystem6);
DEFINE_SYSTEM_ID(TestSystem7);
DEFINE_SYSTEM_ID(TestSystem8);
DEFINE_SYSTEM_ID(TestSystemParallel1);
DEFINE_SYSTEM_ID(TestSystemParallel2);
DEFINE_SYSTEM_ID(TestSystemParallel3);
DEFINE_SYSTEM_ID(TestSystemParallel4);
DEFINE_SYSTEM_ID(TestSystemParallel5);
DEFINE_SYSTEM_ID(TestSystemParallel6);
DEFINE_SYSTEM_ID(TestSystemParallel7);
DEFINE_SYSTEM_ID(TestSystemParallel8);
DEFINE_SYSTEM_ID(LoopTest0);
DEFINE_SYSTEM_ID(LoopTest1);
DEFINE_SYSTEM_ID(LoopTest2);
DEFINE_SYSTEM_ID(LoopTest3);
ECS_REGISTER_SYSTEM(TestSystem1);
ECS_REGISTER_SYSTEM(TestSystem2);
ECS_REGISTER_SYSTEM(TestSystem3);
ECS_REGISTER_SYSTEM(TestSystem4);
ECS_REGISTER_SYSTEM(TestSystem5);
ECS_REGISTER_SYSTEM(TestSystem6);
ECS_REGISTER_SYSTEM(TestSystem7);
ECS_REGISTER_SYSTEM(TestSystem8);
ECS_REGISTER_SYSTEM(TestSystemParallel1);
ECS_REGISTER_SYSTEM(TestSystemParallel2);
ECS_REGISTER_SYSTEM(TestSystemParallel3);
ECS_REGISTER_SYSTEM(TestSystemParallel4);
ECS_REGISTER_SYSTEM(TestSystemParallel5);
ECS_REGISTER_SYSTEM(TestSystemParallel6);
ECS_REGISTER_SYSTEM(TestSystemParallel7);
ECS_REGISTER_SYSTEM(TestSystemParallel8);
ECS_REGISTER_SYSTEM(LoopTest0);
ECS_REGISTER_SYSTEM(LoopTest1);
ECS_REGISTER_SYSTEM(LoopTest2);
ECS_REGISTER_SYSTEM(LoopTest3);
Array<systemId_t> LoopTest3::getDependencies() const {
return {LoopTest2::systemTypeId()};
}
DEFINE_SYSTEM_ID(ThrowTest);
ECS_REGISTER_SYSTEM(ThrowTest); | 29.857143 | 58 | 0.869019 | targodan |
dd168941ffd462fce5616825c67e258ac0429ef3 | 3,609 | hh | C++ | code/language/language.hh | jmpcosta/loc | 0efc9aadd4cc08a6c5c6841f494862b35f4533be | [
"MIT"
] | null | null | null | code/language/language.hh | jmpcosta/loc | 0efc9aadd4cc08a6c5c6841f494862b35f4533be | [
"MIT"
] | null | null | null | code/language/language.hh | jmpcosta/loc | 0efc9aadd4cc08a6c5c6841f494862b35f4533be | [
"MIT"
] | null | null | null | // *****************************************************************************************
//
// File description:
//
// Author: Joao Costa
// Purpose: Provide the definitions/declarations for a generic programming language
//
// *****************************************************************************************
#ifndef LOC_LANGUAGE_HH_
#define LOC_LANGUAGE_HH_
// *****************************************************************************************
//
// Section: Import headers
//
// *****************************************************************************************
// Import C++ system headers
#include <string>
#include <vector>
// Import own headers
#include "trace_macros.hh"
#include "loc_defs.hh"
#include "language/comment.hh"
#include "language/languageType.hh"
#include "parser/parserType.hh"
// *****************************************************************************************
//
// Section: Function declaration
//
// *****************************************************************************************
/// @brief Class that represents a generic language
class language
{
public:
/// @brief Class constructor
virtual ~language ( void );
/// @brief Class destructor
language ( void );
typedef std::vector<comment *>::iterator iterator; ///< An alias for the language comment iterator
typedef std::vector<comment *>::const_iterator const_iterator; ///< An alias for the language comment constant iterator
// Forward fileSet iterator for the container vector
/// @brief Return an iterator proxy to the begining of the comment vector
/// @return Comment begin iterator
virtual iterator begin () { return comments.begin(); }
/// @brief Return a constant iterator proxy to the begining of the comment vector
/// @return Constant begin iterator
virtual const_iterator begin () const { return comments.begin(); }
/// @brief Return an iterator proxy to the end of the comment vector
/// @return End iterator
virtual iterator end () { return comments.end(); }
/// @brief Return a constant iterator proxy to the end of the comment vector
/// @return Constant end iterator
virtual const_iterator end () const { return comments.end(); }
/// @brief Add a new comment object, i.e. what identifies a comment, the set of start and end (comment) tokens
/// @param [in] pc - New comment
virtual void addComment ( comment * pc ) { comments.push_back( pc ); }
/// @brief Get the language comment tokens
/// @return The reference to the vector holding the comment object addresses
virtual std::vector<comment *> & getComments ( void ) { return comments; }
/// @brief Get the language type, i.e. the language ID
/// @return Language identifier (enumeration)
virtual languageType getType ( void ) { return lang; }
/// @brief Obtain the name of the language
/// @return Name of the language
virtual const char * getName ( void ) { return name.c_str(); }
/// @brief Obtain the type of parser for a language
/// @return The type of parser required for the language
parserType getParserType ( void );
protected:
// Variables
// Specific language
languageType lang; ///< ID of the language
std::string name; ///< Name of the language
// Support more than one comment tokens in the language
std::vector<comment *> comments; ///< List of comments of the programming language
TRACE_CLASSNAME_DECLARATION
};
#endif // LOC_LANGUAGE_HH_
| 32.809091 | 126 | 0.573289 | jmpcosta |
dd1a05cfb12b8904f58a1b9f3a5289ed050ccc7d | 762 | cpp | C++ | src/NcursesArt/StringVectorIntersection.cpp | MarkOates/allegro_flare | b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7 | [
"MIT"
] | 25 | 2015-03-30T02:02:43.000Z | 2019-03-04T22:29:12.000Z | src/NcursesArt/StringVectorIntersection.cpp | MarkOates/allegro_flare | b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7 | [
"MIT"
] | 122 | 2015-04-01T08:15:26.000Z | 2019-10-16T20:31:22.000Z | src/NcursesArt/StringVectorIntersection.cpp | allegroflare/allegro_flare | 21d6fe2a5a5323102285598c8a8c75b393ce0322 | [
"MIT"
] | 4 | 2020-02-25T18:17:31.000Z | 2021-04-17T05:06:52.000Z |
#include <NcursesArt/StringVectorIntersection.hpp>
#include <algorithm>
#include <algorithm>
namespace NcursesArt
{
StringVectorIntersection::StringVectorIntersection(std::vector<std::string> v1, std::vector<std::string> v2)
: v1(v1)
, v2(v2)
{
}
StringVectorIntersection::~StringVectorIntersection()
{
}
std::vector<std::string> StringVectorIntersection::intersection()
{
std::vector<std::string> result;
result.resize(v1.size() + v2.size());
std::vector<std::string>::iterator it;
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
it = std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), result.begin());
result.resize(it - result.begin());
return result;
}
} // namespace NcursesArt
| 18.142857 | 108 | 0.681102 | MarkOates |
dd1aa2c7d1a8f835e038bcd6b9ff50255d00566b | 1,992 | hpp | C++ | TestSuite-Intensive/HashComputationTests.hpp | CERIT-SC/echo2 | d07af458e2e0562f85dcbba490ae370909627bd5 | [
"CC-BY-4.0",
"Unlicense"
] | null | null | null | TestSuite-Intensive/HashComputationTests.hpp | CERIT-SC/echo2 | d07af458e2e0562f85dcbba490ae370909627bd5 | [
"CC-BY-4.0",
"Unlicense"
] | null | null | null | TestSuite-Intensive/HashComputationTests.hpp | CERIT-SC/echo2 | d07af458e2e0562f85dcbba490ae370909627bd5 | [
"CC-BY-4.0",
"Unlicense"
] | null | null | null | //
// HashComputationTests.h
// EchoErrorCorrection
//
// Created by Miloš Šimek on 08/02/14.
//
#ifndef __EchoErrorCorrection__HashComputationTests__
#define __EchoErrorCorrection__HashComputationTests__
#include <vector>
#include <memory>
#include <string>
#include <set>
using namespace std;
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include "../Echo/HashComputation.hpp"
#include "../Echo/SequenceFileLoader.hpp"
#include "../Echo/Sequence.hpp"
#include "../Echo/RandomisedAccess.hpp"
class HashComputationTests : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(HashComputationTests);
CPPUNIT_TEST(uniqueIdTest);
CPPUNIT_TEST(validPositionTest);
CPPUNIT_TEST(allIdFromTableTest);
CPPUNIT_TEST(allIdInTableTest);
CPPUNIT_TEST(seqUnderAllTest);
CPPUNIT_TEST(occurrenceCorrectnessTest);
CPPUNIT_TEST_SUITE_END();
SequenceFileLoader* loader;
vector<Sequence> seqArray;
RandomisedAccess* access;
HashComputation* computation;
HashPtr hashTable1, hashTable3, hashTable4;
vector<HashPtr> tables;
string path; //path to TestSuite files
public:
HashComputationTests();
void setUp();
void tearDown();
void uniqueIdTest();
void validPositionTest();
void allIdFromTableTest();
void allIdInTableTest();
void seqUnderAllTest();
void occurrenceCorrectnessTest();
//possible tests:
//if sequence has 2 or more same hashes - one closer to beginning has to be stored
//tests for file, in with sequence length varies
private:
unsigned hashFunction(const char *startPos, const char *endPos) { //same hash function that HashComputation uses
unsigned hash = 0;
for (const char* it = startPos; it != endPos; it++) {
if(*it < 4) hash = 65599 * hash + *it;
}
return hash ^ (hash >> 16);
}
};
#endif /* defined(__EchoErrorCorrection__HashComputationTests__) */
| 28.056338 | 116 | 0.702309 | CERIT-SC |
dd2306d353d630bdbc3936a89bbed00dd2db8cd1 | 2,181 | cpp | C++ | src/client/Client.cpp | violetaperezandrade/Taller-Prog-I-2021-1C-Chipa | 0e13e9990a31f3b061f8654cc78ba679123dba08 | [
"MIT"
] | null | null | null | src/client/Client.cpp | violetaperezandrade/Taller-Prog-I-2021-1C-Chipa | 0e13e9990a31f3b061f8654cc78ba679123dba08 | [
"MIT"
] | null | null | null | src/client/Client.cpp | violetaperezandrade/Taller-Prog-I-2021-1C-Chipa | 0e13e9990a31f3b061f8654cc78ba679123dba08 | [
"MIT"
] | null | null | null | #include "Client.h"
Client::Client(char *ip, char *port, Logger& logger, Config& config) :
skt(),
logger(logger),
entities(),
ip(ip),
port(port),
config(config)
{}
Client::~Client(){
}
int Client::connect(char* ip, char* port){
return skt.connect(ip, port,logger);
}
int Client::send(const char* msg, size_t len){
return skt.send(msg, len,logger);
}
int Client::recv(char* msg, size_t len){
return skt.receive(msg,len,logger);
}
void Client::run(){
logger.infoMsg("Se inicia un cliente", __FILE__, __LINE__);
SDLManager sdlMngr(logger);
int playerNumber = 0;
int playerAmount = config.getPlayersAmount();
Login login(logger, sdlMngr, skt, playerNumber);
logger.infoMsg("Soy el jugador numero " + std::to_string(playerNumber), __FILE__, __LINE__);
int status = login.runLoginWindow(ip,port);
if(status < 0){
logger.errorMsg("Algo salio mal en ventana de login", __FILE__, __LINE__);
return;
}
bool keepRunning = true;
bool serverActive = true;
bool play = true;
int endGame = 0;
Monitor monitor(logger);
SoundManager soundManager(logger, play);
View view(monitor,
logger,
config,
sdlMngr,
keepRunning,
serverActive,
playerNumber,
soundManager,
playerAmount,
endGame);
Input* input = new Input(skt, logger, keepRunning, serverActive, play);
Processor* processor = new Processor(monitor,
skt,
logger,
keepRunning,
serverActive,
playerAmount,
endGame);
logger.debugMsg("Se lanza thread INPUT", __FILE__, __LINE__);
logger.debugMsg("Se lanza thread PROCESSOR", __FILE__, __LINE__);
input->start();
processor->start();
view.run();
processor->stop();
input->stop();
processor->join();
input->join();
delete input;
delete processor;
} | 26.277108 | 96 | 0.553416 | violetaperezandrade |
dd2377b5bb4232678c645fa93e35b8aa1b9c6eb6 | 525 | hpp | C++ | bulb/components/membrane/include/Membrane/Log.hpp | mondoo/Clove | 3989dc3fea0d886a69005c1e0bb4396501f336f2 | [
"MIT"
] | 33 | 2020-01-09T04:57:29.000Z | 2021-08-14T08:02:43.000Z | bulb/components/membrane/include/Membrane/Log.hpp | mondoo/Clove | 3989dc3fea0d886a69005c1e0bb4396501f336f2 | [
"MIT"
] | 234 | 2019-10-25T06:04:35.000Z | 2021-08-18T05:47:41.000Z | bulb/components/membrane/include/Membrane/Log.hpp | mondoo/Clove | 3989dc3fea0d886a69005c1e0bb4396501f336f2 | [
"MIT"
] | 4 | 2020-02-11T15:28:42.000Z | 2020-09-07T16:22:58.000Z | #pragma once
namespace membrane {
public enum class LogLevel {
Trace,
Debug,
Info,
Warning,
Error,
Critical,
};
}
namespace membrane {
public delegate void LogSink(System::String ^ message);
/**
* @brief Managed Logger wrapper design to be called from Bulb.
*/
public ref class Log{
public:
static void write(LogLevel level, System::String ^ message);
static void addSink(LogSink ^ sink, System::String ^ pattern);
};
} | 20.192308 | 70 | 0.592381 | mondoo |
dd26a695f33e4b8c525c136ac0d95e1ec23a9421 | 3,165 | cpp | C++ | addcomputerwindow.cpp | athenabjorg/sacr | f923d91cd754258af53d65448e9e870cec274c2e | [
"MIT"
] | 1 | 2016-11-29T10:55:55.000Z | 2016-11-29T10:55:55.000Z | addcomputerwindow.cpp | athenabjorg/sacr | f923d91cd754258af53d65448e9e870cec274c2e | [
"MIT"
] | null | null | null | addcomputerwindow.cpp | athenabjorg/sacr | f923d91cd754258af53d65448e9e870cec274c2e | [
"MIT"
] | 1 | 2016-11-29T10:40:25.000Z | 2016-11-29T10:40:25.000Z | #include "addcomputerwindow.h"
#include "ui_addcomputerwindow.h"
#include "service.h"
AddComputerWindow::AddComputerWindow(QWidget *parent) :
QDialog(parent),
ui(new Ui::AddComputerWindow) // Constructor
{
ui->setupUi(this);
_service = nullptr;
setFixedSize(width(),height());
}
AddComputerWindow::~AddComputerWindow() // Deconstructor
{
delete ui;
}
// ---------------------------------- OTHER FUNCTIONS ---------------------------------- //
void AddComputerWindow::set_service(service *s) // Forwarded service
{
_service = s;
}
// ---------------------------------- COMPUTER FUNCTIONS ---------------------------------- //
void AddComputerWindow::on_addButton_clicked() // To add a new computer
{
QString name = ui -> nameInput -> text();
QString year = ui -> yearBuiltInput -> text();
QString built;
QString type = ui -> typeInput -> currentText();
QString about = ui -> ComputerAddInfo -> toPlainText();
QString abouturl = ui -> inputInfoUrl -> text();
bool valid = true;
if(year.isEmpty())
{
built = "0";
}
else
{
built = "1";
}
// Check if fiels are left empty and if name is allready taken and if so print out a red error msg
if(name.isEmpty())
{
valid = false;
ui -> errorLabelName -> setText("<span style='color: #ED1C58'>Name is empty");
}
else if((_service->findComputer(0, name.toStdString()).size()) > 0)
{
valid = false;
ui -> errorLabelName -> setText("<span style='color: #ED1C58'>Name is taken");
}
else
{
ui -> errorLabelName -> setText("<span style='color: #ED1C58'> ");
}
QRegExp re("\\d*");
//Error check year built
if(year.toInt() > _service->whatYearIsIt())
{
ui -> errorLabelYear -> setText("<span style='color: #ED1C58'>Year is in the future");
valid = false;
}
else if(!year.isEmpty() && !re.exactMatch(year))
{
ui -> errorLabelYear -> setText("<span style='color: #ED1C58'>Year is invalid");
valid = false;
}
else if(year.isEmpty())
{
year = "0";
}
else
{
ui -> errorLabelYear -> setText("<span style='color: #ED1C58'> ");
}
// If everything checks out, add the new computer and close the addcomputerwindow
if(valid)
{
Computer computer;
string computerID, imageURL;
_service -> addComputer(" ", name.toStdString(), year.toStdString(), type.toStdString(), built.toStdString(), " ", about.toStdString(), abouturl.toStdString());
computer = _service->getComputer(name.toStdString());
computerID = computer.getID();
imageURL = "../sacr/PicCom/" + computerID + ".jpg";
QString qImageURL = QString::fromStdString(imageURL);
QImage image = QImage(_fileName);
image.save(qImageURL);
close();
}
}
void AddComputerWindow::on_ComputerAddPic_clicked() // Opens a window to select a picture
{
_fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), "/home", tr("Image Files (*.png *.jpg *.bmp)"));
}
| 29.036697 | 168 | 0.573144 | athenabjorg |
dd2ef15656b0263cc21efd1db28f38513ae3f63a | 1,211 | hpp | C++ | include/minimax.hpp | JBarmentlo/Gomoku-AI | 2b1b91f7a4a2707eeb65da8c27912f7266d4e92b | [
"MIT"
] | null | null | null | include/minimax.hpp | JBarmentlo/Gomoku-AI | 2b1b91f7a4a2707eeb65da8c27912f7266d4e92b | [
"MIT"
] | null | null | null | include/minimax.hpp | JBarmentlo/Gomoku-AI | 2b1b91f7a4a2707eeb65da8c27912f7266d4e92b | [
"MIT"
] | null | null | null | #ifndef MINIMAX_H
#define MINIMAX_H
#include "defines.hpp"
#include "pattern.hpp"
#include "state.hpp"
#include "eval.hpp"
#include "thread_pool.hpp"
#include <deque>
int minimax_single_fred(State state, int limit, std::deque<int> past_scores = std::deque<int>(), int depth = 0, int alpha = BLACK_WIN, int beta = WHITE_WIN, int *out_eval = nullptr);
int minimax_beam(State state, int limit, int depth = 0, int alpha = BLACK_WIN, int beta = WHITE_WIN);
// int minimax_no_len(State state, int limit, int depth = 0, int alpha = BLACK_WIN, int beta = WHITE_WIN);
int minimax_fred_start(thread_pool& pool, State state, int limit, std::deque<int> past_scores = std::deque<int>(), bool return_eval = false);
// int minimax_fred_start_brother(State state, int limit);
int minimax_fred_start_brother(State state, int limit, int *out_eval = nullptr);
int minimax_fred_start_brother_k_beam(State state, int limit, int *out_eval = nullptr);
int minimax_fred(State state, int limit, std::deque<int> past_scores = std::deque<int>(), int depth = 1, int alpha = BLACK_WIN, int beta = WHITE_WIN);
std::pair<int, int> minimax_starter(State state, int limit, int type = MINMAX_CLASSIC);
#endif // !MINIMAX_H | 46.576923 | 185 | 0.735756 | JBarmentlo |
dd3053d1c9731640d77b57445d448c567b1d424c | 2,932 | cpp | C++ | 7DRL 2017/Projectile.cpp | marukrap/woozoolike | ca16b67bce61828dded707f1c529558646daf0b3 | [
"MIT"
] | 37 | 2017-03-26T00:20:49.000Z | 2021-02-11T18:23:22.000Z | 7DRL 2017/Projectile.cpp | marukrap/woozoolike | ca16b67bce61828dded707f1c529558646daf0b3 | [
"MIT"
] | null | null | null | 7DRL 2017/Projectile.cpp | marukrap/woozoolike | ca16b67bce61828dded707f1c529558646daf0b3 | [
"MIT"
] | 9 | 2017-03-24T04:38:35.000Z | 2021-08-22T00:02:43.000Z | #include "Projectile.hpp"
#include "Actor.hpp"
#include "World.hpp"
#include "Utility.hpp" // plotPath
#include <cassert>
Projectile::Projectile(Actor& actor, std::vector<sf::Vector2i> path)
: Entity(L'\\', 0xea)
, actor(actor)
, path(path)
{
sf::Vector2i dir = path.front() - actor.getPosition();
if (dir.x != 0 && dir.y == 0)
{
glyph = L'-';
tileNumber = 0xeb;
}
else if (dir.x == 0 && dir.y != 0)
{
glyph = L'|';
tileNumber = 0xec;
}
else if (dir.x + dir.y == 0)
{
glyph = L'/';
tileNumber = 0xed;
}
assert(dir.x != 0 || dir.y != 0);
setPosition(path.front());
}
EntityType Projectile::getEntityType() const
{
return EntityType::Projectile;
}
std::wstring Projectile::getName(Article article) const
{
std::wstring name = L"projectile"; // unused
return attachArticle(name, article);
}
Actor& Projectile::getActor() const
{
return actor;
}
bool Projectile::isFinished() const
{
return path.empty();
}
void Projectile::update(sf::Time dt)
{
//* Projectile delay
static const sf::Time delay = sf::seconds(0.02f);
elapsedTime += dt;
if (elapsedTime < delay)
return;
elapsedTime -= delay;
//*/
if (path.empty())
return;
path.erase(path.begin());
// REMOVE: dynamic_cast
Actor* target = dynamic_cast<Actor*>(world->getLevel().getEntity(getPosition(), Level::ActorLayer));
if (target && !target->isDestroyed() && target->getActorType() != actor.getActorType())
{
actor.attack(*target, true);
path.clear();
}
if (!path.empty())
setPosition(path.front());
}
void ProjectileQueue::add(Actor& actor, const sf::Vector2i& target, int count)
{
assert(actor.getPosition() != target);
auto path = plotPath(actor.getPosition(), target);
for (int i = 0; i < count - 1; ++i)
projectiles.emplace_back(std::make_unique<Projectile>(actor, path));
projectiles.emplace_back(std::make_unique<Projectile>(actor, std::move(path)));
}
void ProjectileQueue::add(Actor& actor, std::vector<sf::Vector2i> path, int count)
{
for (int i = 0; i < count - 1; ++i)
projectiles.emplace_back(std::make_unique<Projectile>(actor, path));
projectiles.emplace_back(std::make_unique<Projectile>(actor, std::move(path)));
}
bool ProjectileQueue::isEmpty() const
{
return projectiles.empty();
}
void ProjectileQueue::update(sf::Time dt)
{
if (projectiles.empty())
return;
if (projectiles.front()->isFinished())
{
Actor& actor = projectiles.front()->getActor();
projectiles.erase(projectiles.begin());
if (projectiles.empty())
{
// HACK: end player turn
if (actor.getActorType() == ActorType::Player)
world->endPlayerTurn();
}
}
else
projectiles.front()->update(dt);
world->dirty();
}
void ProjectileQueue::draw(Renderer& renderer)
{
if (!projectiles.empty())
projectiles.front()->draw(renderer);
} | 20.361111 | 102 | 0.633356 | marukrap |
dd307e3fbcae22a0dfa13366beafd27099f4b9c1 | 334 | hpp | C++ | src/JoinDialog.hpp | Ralith/nachat | 7f58fe7ce9c71912a4001435d0ba82f52b8e5b19 | [
"Apache-2.0"
] | 52 | 2016-08-03T00:34:00.000Z | 2019-10-26T09:46:11.000Z | src/JoinDialog.hpp | Ralith/nachat | 7f58fe7ce9c71912a4001435d0ba82f52b8e5b19 | [
"Apache-2.0"
] | 10 | 2016-07-29T04:48:51.000Z | 2018-02-22T05:11:12.000Z | src/JoinDialog.hpp | Ralith/nachat | 7f58fe7ce9c71912a4001435d0ba82f52b8e5b19 | [
"Apache-2.0"
] | 16 | 2016-07-29T00:01:16.000Z | 2018-08-10T20:03:10.000Z | #ifndef NATIVE_CHAT_JOIN_DIALOG_HPP_
#define NATIVE_CHAT_JOIN_DIALOG_HPP_
#include <QDialog>
namespace Ui {
class JoinDialog;
}
class JoinDialog : public QDialog {
Q_OBJECT
public:
JoinDialog(QWidget *parent = nullptr);
~JoinDialog();
QString room();
void accept() override;
private:
Ui::JoinDialog *ui;
};
#endif
| 12.846154 | 40 | 0.733533 | Ralith |
dd3362004592eef59dc7eed25bde12e3d0934b33 | 4,060 | hh | C++ | src/Nn/NeuralNetwork.hh | alexanderrichard/squirrel | 12614a9eb429500c8f341654043f33a1b6bd1d31 | [
"AFL-3.0"
] | 63 | 2016-07-08T13:35:27.000Z | 2021-01-13T18:37:13.000Z | src/Nn/NeuralNetwork.hh | alexanderrichard/squirrel | 12614a9eb429500c8f341654043f33a1b6bd1d31 | [
"AFL-3.0"
] | 4 | 2017-08-04T09:25:10.000Z | 2022-02-24T15:38:52.000Z | src/Nn/NeuralNetwork.hh | alexanderrichard/squirrel | 12614a9eb429500c8f341654043f33a1b6bd1d31 | [
"AFL-3.0"
] | 30 | 2016-05-11T02:24:46.000Z | 2021-11-12T14:06:20.000Z | /*
* Copyright 2016 Alexander Richard
*
* This file is part of Squirrel.
*
* Licensed under the Academic Free License 3.0 (the "License").
* You may not use this file except in compliance with the License.
* You should have received a copy of the License along with Squirrel.
* If not, see <https://opensource.org/licenses/AFL-3.0>.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
/*
* NeuralNetwork.hh
*
* Created on: May 13, 2014
* Author: richard
*/
#ifndef NN_NEURALNETWORK_HH_
#define NN_NEURALNETWORK_HH_
#include <vector>
#include <Core/CommonHeaders.hh>
#include "Types.hh"
#include "Layer.hh"
#include "Connection.hh"
#include "MultiPortLayer.hh"
namespace Nn {
class NeuralNetwork
{
private:
static const Core::ParameterStringList paramConnections_;
static const Core::ParameterInt paramInputDimension_;
static const Core::ParameterInt paramSourceWidth_;
static const Core::ParameterInt paramSourceHeight_;
static const Core::ParameterInt paramSourceChannels_;
static const Core::ParameterString paramWriteParamsTo_;
static const Core::ParameterString paramLoadParamsFrom_;
static const Core::ParameterInt paramLoadParamsEpoch_;
private:
u32 inputDimension_;
u32 sourceWidth_;
u32 sourceHeight_;
u32 sourceChannels_;
u32 nLayer_;
InputLayer inputLayer_; // connects input to the network
std::vector<Layer*> layer_;
std::vector<Connection*> connections_;
std::map<std::string, u32> layerNameToIndex_;
bool isRecurrent_;
bool isInitialized_;
bool isComputing_;
std::string writeParamsTo_;
std::string loadParamsFrom_;
u32 loadParamsEpoch_;
bool layerExists(std::string& layerName);
void addLayer(std::string& layerName);
void addConnection(Connection* connection, bool needsWeightsFileSuffix);
void buildNetwork();
bool containsLayer(BaseLayer* layer, std::vector<BaseLayer*> v);
void checkTopology();
void logTopology();
public:
NeuralNetwork();
virtual ~NeuralNetwork();
/*
* @param minibatchSize the size of a mini batch
* @param maxMemory the number of time frames memorized in the activations/error signal container
*/
void initialize(u32 maxMemory = 1);
// public because it is used in Layer::addInternalConnections
void addConnection(std::string& connectionName, BaseLayer* sourceLayer, BaseLayer* destLayer,
u32 sourcePort, u32 destPort, bool needsWeightsFileSuffix = false);
bool isRecurrent() const { return isRecurrent_; }
bool requiresFullMemorization() const; // do all timeframes need to be stored for sequence forwarding?
u32 lastRecurrentLayerIndex() const;
void setMinibatchSize(u32 batchSize);
void setMaximalMemory(u32 maxMemory);
u32 nLayer() const { return nLayer_; }
u32 nConnections() const { return connections_.size(); }
Layer& layer(u32 layerIndex) const;
Layer& layer(std::string& name) const;
Layer& outputLayer() const { return layer(nLayer_ - 1); }
Connection& connection(u32 connectionIndex) const;
u32 inputDimension() const { return inputDimension_; }
u32 outputDimension() const { return outputLayer().nOutputUnits(0); }
// forward the given mini batch up to layer maxLayerIndex (default: forward to the output layer)
void forward(Matrix& minibatch, u32 layerIndexFrom = 0, u32 layerIndexTo = Types::max<u32>());
void forwardTimeframe(MatrixContainer& batchedSequence, u32 t, u32 layerIndexFrom = 0, u32 layerIndexTo = Types::max<u32>(), bool greedyForwarding = true);
void forwardSequence(MatrixContainer& batchedSequence, bool greedyForwarding = true);
void reset();
void setTrainingMode(bool trainingMode, u32 firstTrainableLayerIndex = 0);
void saveNeuralNetworkParameters();
void saveNeuralNetworkParameters(const std::string& suffix);
bool isComputing() const { return isComputing_; }
void initComputation(bool sync = true);
void finishComputation(bool sync = true);
};
} // namespace
#endif /* NN_NEURALNETWORK_HH_ */
| 32.48 | 156 | 0.766256 | alexanderrichard |
dd3515a357b8ef97eafa3158ec23d4ca7256337e | 733 | hpp | C++ | proxy/cert/certificate_generator.hpp | plater-inc/proxy | f277fd8b3b5bf19b29c8f07055b65ed34c9a8dda | [
"MIT"
] | null | null | null | proxy/cert/certificate_generator.hpp | plater-inc/proxy | f277fd8b3b5bf19b29c8f07055b65ed34c9a8dda | [
"MIT"
] | null | null | null | proxy/cert/certificate_generator.hpp | plater-inc/proxy | f277fd8b3b5bf19b29c8f07055b65ed34c9a8dda | [
"MIT"
] | null | null | null | #ifndef PROXY_CERT_GENERATE_CERTIFICATE_HPP
#define PROXY_CERT_GENERATE_CERTIFICATE_HPP
#include "rsa_maker.hpp"
#include <boost/noncopyable.hpp>
#include <boost/tuple/tuple.hpp>
#include <string>
namespace proxy {
namespace cert {
struct certificate_generator : private boost::noncopyable {
certificate_generator(rsa_maker &rsa_maker);
boost::tuple<std::string, std::string> generate_root_certificate();
boost::tuple<std::string, std::string>
generate_certificate(std::string host, std::string root_private_key,
std::string root_cert, rsa_maker::reschedule reschedule);
private:
rsa_maker &rsa_maker_;
};
} // namespace cert
} // namespace proxy
#endif // PROXY_CERT_GENERATE_CERTIFICATE_HPP | 26.178571 | 80 | 0.763984 | plater-inc |
dd38d788ed370d349a756f000bd5526fb2acef0e | 4,777 | cpp | C++ | src/base.cpp | tansongchen/AwesomeLandlordBot | 21bee7e09211258f5c5074f61e1c67c0da9291c5 | [
"MIT"
] | null | null | null | src/base.cpp | tansongchen/AwesomeLandlordBot | 21bee7e09211258f5c5074f61e1c67c0da9291c5 | [
"MIT"
] | null | null | null | src/base.cpp | tansongchen/AwesomeLandlordBot | 21bee7e09211258f5c5074f61e1c67c0da9291c5 | [
"MIT"
] | null | null | null | #include "base.h"
#include <algorithm>
#include <iostream>
#include <sstream>
using namespace std;
void output(const Group &group) {
for (const auto &card : group) cout << card << " ";
}
Level card_to_level(Card card) { return card / 4 + card / 53; }
Level char_to_level(char c) {
switch (c) {
case 't': case 'T': return 7;
case 'j': case 'J': return 8;
case 'q': case 'Q': return 9;
case 'k': case 'K': return 10;
case 'a': case 'A': return 11;
case '2': return 12;
case 'b': case 'B': return 13;
case 'r': case 'R': return 14;
default: return c - '3';
}
}
ostream &operator<<(ostream &os, const Combination &combinations) {
for (const auto &level : combinations) os << level << " ";
return os;
}
vector<Combination> combinations(const vector<Level> &universe, unsigned k) {
vector<Combination> result;
if (k == 0) return result;
int n = universe.size();
int expn = 1 << n;
int bits = (1 << k) - 1;
while (bits < expn) {
Combination combination;
for (int i = 0; i != n; ++i)
if ((bits >> i) & 1) combination.insert(universe[i]);
int x = bits & -bits;
int y = bits + x;
int z = (bits & ~y);
bits = z / x;
bits >>= 1;
bits |= y;
result.push_back(combination);
}
return result;
}
Counter::Counter() : array<Count, maximumLevel>{} {}
Counter::Counter(const map<Level, Count> &m) : array<Count, maximumLevel>{} {
for (const auto &item : m) (*this)[item.first] = item.second;
}
Counter::Counter(const Group &group) : array<Count, maximumLevel>{} {
for (const Card &card : group) ++(*this)[card_to_level(card)];
}
Counter::Counter(const char *s) : array<Count, maximumLevel>{} {
for (const char &c : string(s)) ++(*this)[char_to_level(c)];
}
Group Counter::get_group(const Group &myCards) const {
Group group;
Counter counter(*this);
for (const auto card : myCards) {
Level l = card_to_level(card);
if (counter[l]) {
group.insert(card);
--counter[l];
}
}
return group;
}
ostream &operator<<(ostream &os, const Counter &counter) {
for (const auto &level : allLevels) {
cout << level << ": " << counter[level] << ", ";
}
return os;
}
Hand::Hand(Level _level, Level _length, Count _size, Count _cosize,
const Combination &_attached)
: level(_level),
length(_length),
size(_size),
cosize(_cosize),
attached(_attached) {}
Hand::Hand(const Counter &counter)
: level(0), length(1), size(1), cosize(0), attached{} {
if (counter == Counter()) {
*this = pass;
return;
}
const auto it1 = max_element(counter.rbegin(), counter.rend());
size = *it1;
level = redJokerLevel - (it1 - counter.rbegin());
const auto it2 = find_if(it1, counter.rend(),
[this](Count count) { return count != this->size; });
length = it2 - it1;
const auto it3 = find_if(
counter.rbegin(), counter.rend(),
[this](Count count) { return count != this->size && count != 0; });
if (it3 != counter.rend()) {
short attachedLevels = size == 4 ? 2 * length : length;
cosize = *it3;
for (const Level &l : allLevels)
if (counter[l] == cosize && attachedLevels > 0) {
attached.insert(l);
--attachedLevels;
}
}
}
Hand::Hand(const char *s) : Hand(Counter(s)) {}
Counter Hand::get_counter() const {
Counter counter;
for (Level i = 0; i != length; ++i) counter[level - i] = size;
if (cosize)
for (const auto &l : attached) counter[l] = cosize;
return counter;
}
bool Hand::operator==(const Hand &hand) const {
return level == hand.level && length == hand.length && size == hand.size &&
cosize == hand.cosize && attached == hand.attached;
}
ostream &operator<<(ostream &os, const Hand &hand) {
os << "Level: " << hand.level << ", Length: " << hand.length
<< ", Size: " << hand.size << ", Cosize: " << hand.cosize
<< ", Attached: " << hand.attached;
return os;
}
Hand::operator string() const {
ostringstream os;
os << "Level: " << level << ", Length: " << length
<< ", Size: " << size << ", Cosize: " << cosize
<< ", Attached: " << attached;
return os.str();
}
bool Hand::is_valid() const {
bool valid;
switch (size) {
case 1:
valid = *this == rocket ||
cosize == 0 && (length == 1 || length >= 5);
break;
case 2:
valid = cosize == 0 && (length == 1 || length >= 3);
break;
case 3:
valid = cosize <= 2 && attached.size() == length;
break;
case 4:
valid = cosize <= 2 && attached.size() == length * 2;
break;
default: throw runtime_error("Attack with invalid Counter!");
}
if (length > 1 && !(*this == rocket)) valid &= (level < maximumChainableLevel);
return valid;
}
| 27.454023 | 81 | 0.579024 | tansongchen |
dd3a0f55a0af65f4d10afb950121c92332eec956 | 8,496 | cpp | C++ | codeforces/contests/1523/E.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 18 | 2020-08-27T05:27:50.000Z | 2022-03-08T02:56:48.000Z | codeforces/contests/1523/E.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | null | null | null | codeforces/contests/1523/E.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 1 | 2020-10-13T05:23:58.000Z | 2020-10-13T05:23:58.000Z | #include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<string, string> pss;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pii> vii;
typedef vector<ll> vl;
typedef vector<vl> vvl;
double EPS=1e-9;
int INF=1000000005;
long long INFF=1000000000000000005ll;
double PI=acos(-1);
int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 };
int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 };
// ll MOD = 1000000007;
#define DEBUG fprintf(stderr, "====TESTING====\n")
#define VALUE(x) cerr << "The value of " << #x << " is " << x << '\n'
#define OUT(x) cout << x << '\n'
#define OUTH(x) cout << x << " "
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define READ(x) for(auto &(z):x) cin >> z;
#define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a))
#define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a))
#define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a))
#define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a))
#define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a))
#define EACH(a, b) for (auto&(a) : (b))
#define REP(i, n) FOR(i, 0, n)
#define REPN(i, n) FORN(i, 1, n)
#define MAX(a, b) a=max(a, b)
#define MIN(a, b) a=min(a, b)
#define SQR(x) ((ll)(x) * (x))
#define RESET(a, b) memset(a, b, sizeof(a))
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define ALL(v) v.begin(), v.end()
#define ALLA(arr, sz) arr, arr + sz
#define SIZE(v) (int)v.size()
#define SORT(v) sort(ALL(v))
#define REVERSE(v) reverse(ALL(v))
#define SORTA(arr, sz) sort(ALLA(arr, sz))
#define REVERSEA(arr, sz) reverse(ALLA(arr, sz))
#define PERMUTE next_permutation
#define TC(t) while (t--)
#define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL)
#define what_is(x) cerr << #x << " is " << x << '\n'
template<const int &MOD>
struct _m_int {
int val;
_m_int(int64_t v = 0) {
if (v < 0) v = v % MOD + MOD;
if (v >= MOD) v %= MOD;
val = int(v);
}
_m_int(uint64_t v) {
if (v >= MOD) v %= MOD;
val = int(v);
}
_m_int(int v) : _m_int(int64_t(v)) {}
_m_int(unsigned v) : _m_int(uint64_t(v)) {}
explicit operator int() const { return val; }
explicit operator unsigned() const { return val; }
explicit operator int64_t() const { return val; }
explicit operator uint64_t() const { return val; }
explicit operator double() const { return val; }
explicit operator long double() const { return val; }
_m_int& operator+=(const _m_int &other) {
val -= MOD - other.val;
if (val < 0) val += MOD;
return *this;
}
_m_int& operator-=(const _m_int &other) {
val -= other.val;
if (val < 0) val += MOD;
return *this;
}
static unsigned fast_mod(uint64_t x, unsigned m = MOD) {
#if !defined(_WIN32) || defined(_WIN64)
return unsigned(x % m);
#endif
// Optimized mod for Codeforces 32-bit machines.
// x must be less than 2^32 * m for this to work, so that x / m fits in an unsigned 32-bit int.
unsigned x_high = unsigned(x >> 32), x_low = unsigned(x);
unsigned quot, rem;
asm("divl %4\n"
: "=a" (quot), "=d" (rem)
: "d" (x_high), "a" (x_low), "r" (m));
return rem;
}
_m_int& operator*=(const _m_int &other) {
val = fast_mod(uint64_t(val) * other.val);
return *this;
}
_m_int& operator/=(const _m_int &other) {
return *this *= other.inv();
}
friend _m_int operator+(const _m_int &a, const _m_int &b) { return _m_int(a) += b; }
friend _m_int operator-(const _m_int &a, const _m_int &b) { return _m_int(a) -= b; }
friend _m_int operator*(const _m_int &a, const _m_int &b) { return _m_int(a) *= b; }
friend _m_int operator/(const _m_int &a, const _m_int &b) { return _m_int(a) /= b; }
_m_int& operator++() {
val = val == MOD - 1 ? 0 : val + 1;
return *this;
}
_m_int& operator--() {
val = val == 0 ? MOD - 1 : val - 1;
return *this;
}
_m_int operator++(int) { _m_int before = *this; ++*this; return before; }
_m_int operator--(int) { _m_int before = *this; --*this; return before; }
_m_int operator-() const {
return val == 0 ? 0 : MOD - val;
}
friend bool operator==(const _m_int &a, const _m_int &b) { return a.val == b.val; }
friend bool operator!=(const _m_int &a, const _m_int &b) { return a.val != b.val; }
friend bool operator<(const _m_int &a, const _m_int &b) { return a.val < b.val; }
friend bool operator>(const _m_int &a, const _m_int &b) { return a.val > b.val; }
friend bool operator<=(const _m_int &a, const _m_int &b) { return a.val <= b.val; }
friend bool operator>=(const _m_int &a, const _m_int &b) { return a.val >= b.val; }
static const int SAVE_INV = int(1e6) + 5;
static _m_int save_inv[SAVE_INV];
static void prepare_inv() {
// Make sure MOD is prime, which is necessary for the inverse algorithm below.
for (int64_t p = 2; p * p <= MOD; p += p % 2 + 1)
assert(MOD % p != 0);
save_inv[0] = 0;
save_inv[1] = 1;
for (int i = 2; i < SAVE_INV; i++)
save_inv[i] = save_inv[MOD % i] * (MOD - MOD / i);
}
_m_int inv() const {
if (save_inv[1] == 0)
prepare_inv();
if (val < SAVE_INV)
return save_inv[val];
_m_int product = 1;
int v = val;
while (v >= SAVE_INV) {
product *= MOD - MOD / v;
v = MOD % v;
}
return product * save_inv[v];
}
_m_int pow(int64_t p) const {
if (p < 0)
return inv().pow(-p);
_m_int a = *this, result = 1;
while (p > 0) {
if (p & 1)
result *= a;
p >>= 1;
if (p > 0)
a *= a;
}
return result;
}
friend ostream& operator<<(ostream &os, const _m_int &m) {
return os << m.val;
}
};
template<const int &MOD> _m_int<MOD> _m_int<MOD>::save_inv[_m_int<MOD>::SAVE_INV];
extern const int MOD = int(1e9) + 7;
using mod_int = _m_int<MOD>;
vector<mod_int> _factorial = {1, 1}, _inv_factorial = {1, 1};
void prepare_factorials(int64_t maximum) {
static int prepared_maximum = 1;
if (maximum <= prepared_maximum)
return;
// Prevent increasing maximum by only 1 each time.
maximum += maximum / 16;
_factorial.resize(maximum + 1);
_inv_factorial.resize(maximum + 1);
for (int i = prepared_maximum + 1; i <= maximum; i++) {
_factorial[i] = i * _factorial[i - 1];
_inv_factorial[i] = _inv_factorial[i - 1] / i;
}
prepared_maximum = int(maximum);
}
mod_int factorial(int n) {
if (n < 0) return 0;
prepare_factorials(n);
return _factorial[n];
}
mod_int inv_factorial(int n) {
if (n < 0) return 0;
prepare_factorials(n);
return _inv_factorial[n];
}
mod_int choose(int64_t n, int64_t r) {
if (r < 0 || r > n) return 0;
prepare_factorials(n);
return _factorial[n] * _inv_factorial[r] * _inv_factorial[n - r];
}
mod_int permute(int64_t n, int64_t r) {
if (r < 0 || r > n) return 0;
prepare_factorials(n);
return _factorial[n] * _inv_factorial[n - r];
}
mod_int inv_choose(int64_t n, int64_t r) {
assert(0 <= r && r <= n);
prepare_factorials(n);
return _inv_factorial[n] * _factorial[r] * _factorial[n - r];
}
mod_int inv_permute(int64_t n, int64_t r) {
assert(0 <= r && r <= n);
prepare_factorials(n);
return _inv_factorial[n] * _factorial[n - r];
}
template<typename T_vector>
void output_vector(const T_vector &v, bool line_break = false, bool add_one = false, int start = -1, int end = -1) {
if (start < 0) start = 0;
if (end < 0) end = int(v.size());
for (int i = start; i < end; i++) {
cout << v[i] + (add_one ? 1 : 0) << (line_break ? '\n' : i < end - 1 ? ' ' : '\n');
}
}
void solve() {
ll n, k; cin >> n >> k;
mod_int ans = 1;
FORN(m, 1, n) ans += choose(n - 1 - (m - 1) * k + m, m) / choose(n, m);
OUT(ans);
}
int main() {
FAST_INP;
// #ifndef ONLINE_JUDGE
// freopen("input.txt","r", stdin);
// freopen("output.txt","w", stdout);
// #endif
int tc; cin >> tc;
TC(tc) solve();
// solve();
return 0;
} | 28.702703 | 116 | 0.558145 | wingkwong |
dd3a313bda7373a86c693fa4ab2922c2fb931887 | 2,186 | cpp | C++ | test/core/image_view/planar_rgba_view.cpp | NEDJIMAbelgacem/gil | 8ea3644825d4b2dcabda6d4ce6281d4882f45c61 | [
"BSL-1.0"
] | 1 | 2020-04-07T18:50:07.000Z | 2020-04-07T18:50:07.000Z | test/core/image_view/planar_rgba_view.cpp | NEDJIMAbelgacem/gil | 8ea3644825d4b2dcabda6d4ce6281d4882f45c61 | [
"BSL-1.0"
] | null | null | null | test/core/image_view/planar_rgba_view.cpp | NEDJIMAbelgacem/gil | 8ea3644825d4b2dcabda6d4ce6281d4882f45c61 | [
"BSL-1.0"
] | null | null | null | //
// Copyright 2018 Mateusz Loskot <mateusz at loskot dot net>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#define BOOST_TEST_MODULE gil/test/core/image_view/planar_rgba_view
#include "unit_test.hpp"
#include <boost/gil.hpp>
#include <cstdint>
namespace boost { namespace gil {
namespace test { namespace fixture {
gil::point_t d{2, 2};
std::uint8_t r[] = { 1, 2, 3, 4 };
std::uint8_t g[] = { 10, 20, 30, 40 };
std::uint8_t b[] = { 110, 120, 130, 140 };
std::uint8_t a[] = { 251, 252, 253, 254 };
}}}}
namespace gil = boost::gil;
namespace fixture = boost::gil::test::fixture;
using dont_print_log_value_planar_pixel_reference = boost::gil::planar_pixel_reference<std::uint8_t&, boost::gil::rgba_t>;
BOOST_TEST_DONT_PRINT_LOG_VALUE(dont_print_log_value_planar_pixel_reference)
BOOST_AUTO_TEST_CASE(dimensions)
{
auto v = gil::planar_rgba_view(fixture::d.x, fixture::d.y, fixture::r, fixture::g, fixture::b, fixture::a, sizeof(std::uint8_t) * 2);
BOOST_TEST(!v.empty());
BOOST_TEST(v.dimensions() == fixture::d);
BOOST_TEST(v.num_channels() == 4u);
BOOST_TEST(v.size() == static_cast<std::size_t>(fixture::d.x * fixture::d.y));
}
BOOST_AUTO_TEST_CASE(front)
{
auto v = gil::planar_rgba_view(fixture::d.x, fixture::d.y, fixture::r, fixture::g, fixture::b, fixture::a, sizeof(std::uint8_t) * 2);
gil::rgba8_pixel_t const pf{1, 10, 110, 251};
BOOST_TEST(v.front() == pf);
}
BOOST_AUTO_TEST_CASE(back)
{
auto v = gil::planar_rgba_view(fixture::d.x, fixture::d.y, fixture::r, fixture::g, fixture::b, fixture::a, sizeof(std::uint8_t) * 2);
gil::rgba8_pixel_t const pb{4, 40, 140, 254};
BOOST_TEST(v.back() == pb);
}
BOOST_AUTO_TEST_CASE(pixel_equal_to_operator)
{
auto v = gil::planar_rgba_view(fixture::d.x, fixture::d.y, fixture::r, fixture::g, fixture::b, fixture::a, sizeof(std::uint8_t) * 2);
for (std::ptrdiff_t i = 0; i < static_cast<std::ptrdiff_t>(v.size()); i++)
{
gil::rgba8_pixel_t const p{fixture::r[i], fixture::g[i], fixture::b[i], fixture::a[i]};
BOOST_TEST(v[i] == p);
}
}
| 34.15625 | 137 | 0.677493 | NEDJIMAbelgacem |
dd42e2299952576abfc5c3e0dd064ac7445070db | 3,010 | cc | C++ | openfl-webm/0,0,4/project/libvpx-generic/test/idctllm_test.cc | kudorado/HaxePlus | b312ad16420aa31731e55a1ac5f282cc46a557fc | [
"Apache-2.0"
] | null | null | null | openfl-webm/0,0,4/project/libvpx-generic/test/idctllm_test.cc | kudorado/HaxePlus | b312ad16420aa31731e55a1ac5f282cc46a557fc | [
"Apache-2.0"
] | null | null | null | openfl-webm/0,0,4/project/libvpx-generic/test/idctllm_test.cc | kudorado/HaxePlus | b312ad16420aa31731e55a1ac5f282cc46a557fc | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2010 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
extern "C" {
#include "vpx_config.h"
#include "vpx_rtcd.h"
}
#include "third_party/googletest/src/include/gtest/gtest.h"
typedef void (*idct_fn_t)(short *input, unsigned char *pred_ptr,
int pred_stride, unsigned char *dst_ptr,
int dst_stride);
namespace {
class IDCTTest : public ::testing::TestWithParam<idct_fn_t>
{
protected:
virtual void SetUp()
{
int i;
UUT = GetParam();
memset(input, 0, sizeof(input));
/* Set up guard blocks */
for(i=0; i<256; i++)
output[i] = ((i&0xF)<4&&(i<64))?0:-1;
}
idct_fn_t UUT;
short input[16];
unsigned char output[256];
unsigned char predict[256];
};
TEST_P(IDCTTest, TestGuardBlocks)
{
int i;
for(i=0; i<256; i++)
if((i&0xF) < 4 && i<64)
EXPECT_EQ(0, output[i]) << i;
else
EXPECT_EQ(255, output[i]);
}
TEST_P(IDCTTest, TestAllZeros)
{
int i;
UUT(input, output, 16, output, 16);
for(i=0; i<256; i++)
if((i&0xF) < 4 && i<64)
EXPECT_EQ(0, output[i]) << "i==" << i;
else
EXPECT_EQ(255, output[i]) << "i==" << i;
}
TEST_P(IDCTTest, TestAllOnes)
{
int i;
input[0] = 4;
UUT(input, output, 16, output, 16);
for(i=0; i<256; i++)
if((i&0xF) < 4 && i<64)
EXPECT_EQ(1, output[i]) << "i==" << i;
else
EXPECT_EQ(255, output[i]) << "i==" << i;
}
TEST_P(IDCTTest, TestAddOne)
{
int i;
for(i=0; i<256; i++)
predict[i] = i;
input[0] = 4;
UUT(input, predict, 16, output, 16);
for(i=0; i<256; i++)
if((i&0xF) < 4 && i<64)
EXPECT_EQ(i+1, output[i]) << "i==" << i;
else
EXPECT_EQ(255, output[i]) << "i==" << i;
}
TEST_P(IDCTTest, TestWithData)
{
int i;
for(i=0; i<16; i++)
input[i] = i;
UUT(input, output, 16, output, 16);
for(i=0; i<256; i++)
if((i&0xF) > 3 || i>63)
EXPECT_EQ(255, output[i]) << "i==" << i;
else if(i == 0)
EXPECT_EQ(11, output[i]) << "i==" << i;
else if(i == 34)
EXPECT_EQ(1, output[i]) << "i==" << i;
else if(i == 2 || i == 17 || i == 32)
EXPECT_EQ(3, output[i]) << "i==" << i;
else
EXPECT_EQ(0, output[i]) << "i==" << i;
}
INSTANTIATE_TEST_CASE_P(C, IDCTTest,
::testing::Values(vp8_short_idct4x4llm_c));
#if HAVE_MMX
INSTANTIATE_TEST_CASE_P(MMX, IDCTTest,
::testing::Values(vp8_short_idct4x4llm_mmx));
#endif
}
| 23.888889 | 71 | 0.522591 | kudorado |
dd433bb40cca08baa391b4f92040225e8dfc141f | 1,052 | hpp | C++ | libs/fnd/utility/include/bksge/fnd/utility.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/fnd/utility/include/bksge/fnd/utility.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/fnd/utility/include/bksge/fnd/utility.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file utility.hpp
*
* @brief Utility library
*
* @author myoukaku
*/
#ifndef BKSGE_FND_UTILITY_HPP
#define BKSGE_FND_UTILITY_HPP
#include <bksge/fnd/utility/as_const.hpp>
#include <bksge/fnd/utility/cmp_equal.hpp>
#include <bksge/fnd/utility/cmp_greater.hpp>
#include <bksge/fnd/utility/cmp_greater_equal.hpp>
#include <bksge/fnd/utility/cmp_less.hpp>
#include <bksge/fnd/utility/cmp_less_equal.hpp>
#include <bksge/fnd/utility/cmp_not_equal.hpp>
#include <bksge/fnd/utility/exchange.hpp>
#include <bksge/fnd/utility/index_sequence.hpp>
#include <bksge/fnd/utility/index_sequence_for.hpp>
#include <bksge/fnd/utility/integer_sequence.hpp>
#include <bksge/fnd/utility/in_place.hpp>
#include <bksge/fnd/utility/in_place_index.hpp>
#include <bksge/fnd/utility/in_place_type.hpp>
#include <bksge/fnd/utility/in_range.hpp>
#include <bksge/fnd/utility/make_index_sequence.hpp>
#include <bksge/fnd/utility/make_integer_sequence.hpp>
#include <bksge/fnd/utility/to_underlying.hpp>
#endif // BKSGE_FND_UTILITY_HPP
| 32.875 | 55 | 0.769011 | myoukaku |
dd46f1b2015bc2b587f3c2485ded71b9bce52874 | 612 | hpp | C++ | Boss/Mod/ConnectFinderByHardcode.hpp | 3nprob/clboss | 0435b6c074347ce82e490a5988534054e9d7348d | [
"MIT"
] | 108 | 2020-10-01T17:12:40.000Z | 2022-03-30T09:18:03.000Z | Boss/Mod/ConnectFinderByHardcode.hpp | 3nprob/clboss | 0435b6c074347ce82e490a5988534054e9d7348d | [
"MIT"
] | 94 | 2020-10-03T13:40:30.000Z | 2022-03-30T09:18:00.000Z | Boss/Mod/ConnectFinderByHardcode.hpp | 3nprob/clboss | 0435b6c074347ce82e490a5988534054e9d7348d | [
"MIT"
] | 17 | 2020-10-29T13:27:59.000Z | 2022-03-18T13:05:03.000Z | #ifndef BOSS_MOD_CONNECTFINDERBYHARDCODE_HPP
#define BOSS_MOD_CONNECTFINDERBYHARDCODE_HPP
#include<memory>
namespace S { class Bus; }
namespace Boss { namespace Mod {
/** class Boss::Mod::ConnectFinderByHardcode
*
* @brief provides some possible connection
* candidates from a hardcoded list.
*/
class ConnectFinderByHardcode {
private:
class Impl;
std::unique_ptr<Impl> pimpl;
public:
ConnectFinderByHardcode() =delete;
ConnectFinderByHardcode(S::Bus& bus);
ConnectFinderByHardcode(ConnectFinderByHardcode&&);
~ConnectFinderByHardcode();
};
}}
#endif /* BOSS_MOD_CONNECTFINDERBYHARDCODE_HPP */
| 20.4 | 52 | 0.78268 | 3nprob |
dd4838a1eec025dab1bc990b6f4a0469eef844e5 | 484 | cpp | C++ | doc/source/overview/functor.cpp | fujiehuang/ecto | fea744337aa1fad1397c9a3ba5baa143993cb5eb | [
"BSD-3-Clause"
] | 77 | 2015-01-30T15:45:43.000Z | 2022-03-03T02:29:37.000Z | doc/source/overview/functor.cpp | fujiehuang/ecto | fea744337aa1fad1397c9a3ba5baa143993cb5eb | [
"BSD-3-Clause"
] | 37 | 2015-01-18T21:04:36.000Z | 2021-07-09T08:24:54.000Z | doc/source/overview/functor.cpp | fujiehuang/ecto | fea744337aa1fad1397c9a3ba5baa143993cb5eb | [
"BSD-3-Clause"
] | 29 | 2015-02-17T14:37:18.000Z | 2021-11-16T07:46:26.000Z | #include <iostream>
#include <string>
//start
struct Printer
{
Printer(const std::string& prefix, const std::string& suffix)
:
prefix_(prefix),
suffix_(suffix)
{
}
void
operator()(std::ostream& out, const std::string& message)
{
out << prefix_ << message << suffix_;
}
std::string prefix_, suffix_;
};
//end
int
main()
{
Printer p("start>> ", "<< stop\n");
std::string message = "Hello Function.";
p(std::cout, message);
return 0;
}
| 16.689655 | 63 | 0.60124 | fujiehuang |
dd4877305f4c2b8a449f605b1390ae134871cba2 | 10,135 | cc | C++ | src/remote_adapter/remote_adapter_client/remote_client/tests/remote_client_test.cc | LuxoftSDL/sdl_atf | 454487dafdc422db724cceb02827a6738e93203b | [
"BSD-3-Clause"
] | 6 | 2016-03-04T20:27:37.000Z | 2021-11-06T08:05:00.000Z | src/remote_adapter/remote_adapter_client/remote_client/tests/remote_client_test.cc | smartdevicelink/sdl_atf | 08354ae6633169513639a3d9257acd1229a5caa2 | [
"BSD-3-Clause"
] | 122 | 2016-03-09T20:03:50.000Z | 2022-01-31T14:26:36.000Z | src/remote_adapter/remote_adapter_client/remote_client/tests/remote_client_test.cc | smartdevicelink/sdl_atf | 08354ae6633169513639a3d9257acd1229a5caa2 | [
"BSD-3-Clause"
] | 41 | 2016-03-10T09:34:00.000Z | 2020-12-01T09:08:24.000Z | #include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "common/constants.h"
#include "mock_rpc_connection.h"
#include "remote_client.h"
namespace test {
static constexpr const char *kRpcName = "Test_RPC";
static const rpc_parameter kEmptyParameter;
using rpc_connection::connection_ptr;
using ::testing::_;
using ::testing::ByMove;
using ::testing::Return;
using ::testing::ReturnRef;
class RemoteClient_Test : public testing::Test {
public:
RPCLIB_MSGPACK::object_handle
response_pack(const response_type &response) const {
std::stringstream sbuf;
RPCLIB_MSGPACK::pack(sbuf, response);
RPCLIB_MSGPACK::object_handle obj_handle;
RPCLIB_MSGPACK::unpack(obj_handle, sbuf.str().data(), sbuf.str().size(), 0);
return obj_handle;
}
MockRpcConnection *CreateRpcConnection();
std::unique_ptr<lua_lib::RemoteClient> remote_client_;
};
MockRpcConnection *RemoteClient_Test::CreateRpcConnection() {
MockRpcConnection *mock = new MockRpcConnection();
EXPECT_CALL(*mock, set_timeout(10000));
EXPECT_CALL(*mock, call(constants::client_connected))
.WillOnce(Return(ByMove(response_pack(
response_type(std::string(), constants::error_codes::SUCCESS)))));
return mock;
}
TEST_F(RemoteClient_Test, Connected_Expect_False) {
MockRpcConnection *mock_connection = CreateRpcConnection();
remote_client_.reset(
new lua_lib::RemoteClient(connection_ptr(mock_connection)));
EXPECT_CALL(*mock_connection, get_connection_state())
.WillOnce(Return(rpc::client::connection_state::disconnected));
const bool bConnect = remote_client_->connected();
EXPECT_EQ(false, bConnect);
}
TEST_F(RemoteClient_Test, Connected_Expect_True) {
MockRpcConnection *mock_connection = CreateRpcConnection();
remote_client_.reset(
new lua_lib::RemoteClient(connection_ptr(mock_connection)));
EXPECT_CALL(*mock_connection, get_connection_state())
.WillOnce(Return(rpc::client::connection_state::connected));
const bool bConnect = remote_client_->connected();
EXPECT_EQ(true, bConnect);
}
TEST_F(RemoteClient_Test, Content_Call_Expect_NO_CONNECTION) {
MockRpcConnection *mock_connection = CreateRpcConnection();
remote_client_.reset(
new lua_lib::RemoteClient(connection_ptr(mock_connection)));
EXPECT_CALL(*mock_connection, get_connection_state())
.WillOnce(Return(rpc::client::connection_state::disconnected));
auto response = remote_client_->content_call(kRpcName, kEmptyParameter);
EXPECT_EQ(constants::error_codes::NO_CONNECTION, response.second);
}
TEST_F(RemoteClient_Test, Content_Call_Expect_SUCCESS) {
MockRpcConnection *mock_connection = CreateRpcConnection();
remote_client_.reset(
new lua_lib::RemoteClient(connection_ptr(mock_connection)));
EXPECT_CALL(*mock_connection, get_connection_state())
.WillOnce(Return(rpc::client::connection_state::connected));
EXPECT_CALL(*mock_connection, call(kRpcName, kEmptyParameter))
.WillOnce(Return(ByMove(response_pack(
response_type(std::string(), constants::error_codes::SUCCESS)))));
auto response = remote_client_->content_call(kRpcName, kEmptyParameter);
EXPECT_EQ(constants::error_codes::SUCCESS, response.second);
}
TEST_F(RemoteClient_Test, File_Call_Expect_NO_CONNECTION) {
MockRpcConnection *mock_connection = CreateRpcConnection();
remote_client_.reset(
new lua_lib::RemoteClient(connection_ptr(mock_connection)));
EXPECT_CALL(*mock_connection, get_connection_state())
.WillOnce(Return(rpc::client::connection_state::disconnected));
auto response = remote_client_->file_call(kRpcName, kEmptyParameter);
EXPECT_EQ(constants::error_codes::NO_CONNECTION, response.second);
}
TEST_F(RemoteClient_Test, File_Call_Expect_Response_FAILED) {
MockRpcConnection *mock_connection = CreateRpcConnection();
remote_client_.reset(
new lua_lib::RemoteClient(connection_ptr(mock_connection)));
rpc_parameter parameters(kEmptyParameter);
parameters.push_back(
std::make_pair(std::to_string(0), constants::param_types::INT));
parameters.push_back(std::make_pair(std::to_string(constants::kMaxSizeData),
constants::param_types::INT));
EXPECT_CALL(*mock_connection, get_connection_state())
.WillOnce(Return(rpc::client::connection_state::connected));
EXPECT_CALL(*mock_connection, call(kRpcName, parameters))
.WillOnce(Return(ByMove(response_pack(
response_type(std::string(), constants::error_codes::FAILED)))));
auto response = remote_client_->file_call(kRpcName, kEmptyParameter);
EXPECT_EQ(constants::error_codes::FAILED, response.second);
}
TEST_F(RemoteClient_Test, File_Call_With_Bad_File_Name_Expect_FAILED) {
MockRpcConnection *mock_connection = CreateRpcConnection();
remote_client_.reset(
new lua_lib::RemoteClient(connection_ptr(mock_connection)));
rpc_parameter parameters = {
std::make_pair("", constants::param_types::STRING),
std::make_pair(".", constants::param_types::STRING),
std::make_pair(std::to_string(0), constants::param_types::INT),
std::make_pair(std::to_string(constants::kMaxSizeData),
constants::param_types::INT)};
EXPECT_CALL(*mock_connection, get_connection_state())
.WillOnce(Return(rpc::client::connection_state::connected));
EXPECT_CALL(*mock_connection, call(kRpcName, parameters))
.WillOnce(Return(ByMove(response_pack(
response_type(std::string(), constants::error_codes::SUCCESS)))));
auto response = remote_client_->file_call(
kRpcName, rpc_parameter(parameters.begin(), parameters.begin() + 2));
EXPECT_EQ(constants::error_codes::FAILED, response.second);
}
TEST_F(RemoteClient_Test, File_Call_Without_Offset_Expect_SUCCESS) {
MockRpcConnection *mock_connection = CreateRpcConnection();
remote_client_.reset(
new lua_lib::RemoteClient(connection_ptr(mock_connection)));
rpc_parameter parameters = {
std::make_pair("", constants::param_types::STRING),
std::make_pair(kRpcName, constants::param_types::STRING),
std::make_pair(std::to_string(0), constants::param_types::INT),
std::make_pair(std::to_string(constants::kMaxSizeData),
constants::param_types::INT)};
std::string tmp_path(constants::kTmpPath);
tmp_path.append(parameters[1].first);
EXPECT_CALL(*mock_connection, get_connection_state())
.WillOnce(Return(rpc::client::connection_state::connected));
EXPECT_CALL(*mock_connection, call(kRpcName, parameters))
.WillOnce(Return(ByMove(response_pack(
response_type(kRpcName, constants::error_codes::SUCCESS)))));
auto response = remote_client_->file_call(
kRpcName, rpc_parameter(parameters.begin(), parameters.begin() + 2));
EXPECT_EQ(tmp_path, response.first);
EXPECT_EQ(constants::error_codes::SUCCESS, response.second);
}
TEST_F(RemoteClient_Test, File_Call_With_1_Offset_Expect_SUCCESS) {
MockRpcConnection *mock_connection = CreateRpcConnection();
remote_client_.reset(
new lua_lib::RemoteClient(connection_ptr(mock_connection)));
rpc_parameter parameters = {
std::make_pair("", constants::param_types::STRING),
std::make_pair(kRpcName, constants::param_types::STRING),
std::make_pair(std::to_string(0), constants::param_types::INT),
std::make_pair(std::to_string(constants::kMaxSizeData),
constants::param_types::INT)};
std::string tmp_path(constants::kTmpPath);
tmp_path.append(parameters[1].first);
const int offset = 10;
EXPECT_CALL(*mock_connection, get_connection_state())
.WillOnce(Return(rpc::client::connection_state::connected));
EXPECT_CALL(*mock_connection, call(kRpcName, parameters))
.WillOnce(Return(ByMove(response_pack(response_type(kRpcName, offset)))));
parameters[parameters.size() - 2] =
std::make_pair(std::to_string(offset), constants::param_types::INT);
EXPECT_CALL(*mock_connection, call(kRpcName, parameters))
.WillOnce(Return(ByMove(response_pack(
response_type(kRpcName, constants::error_codes::SUCCESS)))));
auto response = remote_client_->file_call(
kRpcName, rpc_parameter(parameters.begin(), parameters.begin() + 2));
EXPECT_EQ(tmp_path, response.first);
EXPECT_EQ(constants::error_codes::SUCCESS, response.second);
}
TEST_F(RemoteClient_Test, File_Call_With_2_Offset_Expect_SUCCESS) {
MockRpcConnection *mock_connection = CreateRpcConnection();
remote_client_.reset(
new lua_lib::RemoteClient(connection_ptr(mock_connection)));
rpc_parameter parameters = {
std::make_pair("", constants::param_types::STRING),
std::make_pair(kRpcName, constants::param_types::STRING),
std::make_pair(std::to_string(0), constants::param_types::INT),
std::make_pair(std::to_string(constants::kMaxSizeData),
constants::param_types::INT)};
std::string tmp_path(constants::kTmpPath);
tmp_path.append(parameters[1].first);
const int offset_1 = 10;
const int offset_2 = 20;
EXPECT_CALL(*mock_connection, get_connection_state())
.WillOnce(Return(rpc::client::connection_state::connected));
EXPECT_CALL(*mock_connection, call(kRpcName, parameters))
.WillOnce(
Return(ByMove(response_pack(response_type(kRpcName, offset_1)))));
parameters[parameters.size() - 2] =
std::make_pair(std::to_string(offset_1), constants::param_types::INT);
EXPECT_CALL(*mock_connection, call(kRpcName, parameters))
.WillOnce(
Return(ByMove(response_pack(response_type(kRpcName, offset_2)))));
parameters[parameters.size() - 2] =
std::make_pair(std::to_string(offset_2), constants::param_types::INT);
EXPECT_CALL(*mock_connection, call(kRpcName, parameters))
.WillOnce(Return(ByMove(response_pack(
response_type(kRpcName, constants::error_codes::SUCCESS)))));
auto response = remote_client_->file_call(
kRpcName, rpc_parameter(parameters.begin(), parameters.begin() + 2));
EXPECT_EQ(tmp_path, response.first);
EXPECT_EQ(constants::error_codes::SUCCESS, response.second);
}
} // namespace test
| 35.939716 | 80 | 0.741589 | LuxoftSDL |
dd510d529f7f6ad984c58682d60dc73be915849e | 7,204 | cpp | C++ | src/projects/smc_validation/test_SMC_cor_normal.cpp | rserban/chrono | bee5e30b2ce3b4ac62324799d1366b6db295830e | [
"BSD-3-Clause"
] | 1 | 2020-03-05T13:00:41.000Z | 2020-03-05T13:00:41.000Z | src/projects/smc_validation/test_SMC_cor_normal.cpp | rserban/chrono | bee5e30b2ce3b4ac62324799d1366b6db295830e | [
"BSD-3-Clause"
] | null | null | null | src/projects/smc_validation/test_SMC_cor_normal.cpp | rserban/chrono | bee5e30b2ce3b4ac62324799d1366b6db295830e | [
"BSD-3-Clause"
] | 1 | 2022-03-27T15:12:24.000Z | 2022-03-27T15:12:24.000Z | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Cecily Sunday, Radu Serban
// =============================================================================
//
// This project simulates the collision of a sphere against another sphere and
// compares the measured coefficient of restitution against the input
// coefficient of restitution
//
// =============================================================================
#include "./test_SMC.h"
int main(int argc, char* argv[]) {
// Update accordingly. The rest of main should remain largely the same between projects.
const std::string projname = "test_cor_normal";
if (CreateOutputPath(projname) != 0) {
fprintf(stderr, "Error creating output data directory\n");
return -1;
}
// Print the sim set - up parameters to userlog
GetLog() << "\nCopyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << ".VCMS\n";
GetLog() << "\nTesting SMC multicore coefficient of restitution....\n";
// Create a file for logging data
const std::string fname = GetChronoOutputPath() + "/dat.csv";
std::ofstream dat(fname, std::ofstream::out);
dat << "force_model, cor_in, cor_out, e\n";
// Execute test for each force model
std::vector<std::string> fmodels = {"hooke", "hertz", "plaincoulomb", "flores"};
for (int f = 0; f < fmodels.size(); ++f) {
for (int var = 0; var <= 100; var += 10) {
// Create a shared material to be used by the all bodies
float y_modulus = 2.0e5f; /// Default 2e5
float p_ratio = 0.3f; /// Default 0.3f
float s_frict = 0.3f; /// Usually in 0.1 range, rarely above. Default 0.6f
float k_frict = 0.3f; /// Default 0.6f
float roll_frict = 0.0f; /// Usually around 1E-3
float spin_frict = 0.0f; /// Usually around 1E-3
float cor_in = (float)var / 100; /// Default 0.4f
float ad = 0.0f; /// Magnitude of the adhesion in the Constant adhesion model
float adDMT = 0.0f; /// Magnitude of the adhesion in the DMT adhesion model
float adSPerko = 0.0f; /// Magnitude of the adhesion in the SPerko adhesion model
auto mat = chrono_types::make_shared<ChMaterialSurfaceSMC>();
mat->SetYoungModulus(y_modulus);
mat->SetPoissonRatio(p_ratio);
mat->SetSfriction(s_frict);
mat->SetKfriction(k_frict);
mat->SetRollingFriction(roll_frict);
mat->SetSpinningFriction(spin_frict);
mat->SetRestitution(cor_in);
mat->SetAdhesion(ad);
mat->SetAdhesionMultDMT(adDMT);
mat->SetAdhesionSPerko(adSPerko);
// Create a multicore SMC system and set the system parameters
double time_step = 1.0E-5;
double out_step = 1.0E-2;
double time_sim = 0.5;
ChVector<> gravity(0, 0, 0);
ChSystemMulticoreSMC msystem;
SetSimParameters(&msystem, gravity, force_to_enum(fmodels[f]));
msystem.SetNumThreads(2);
// Add the colliding spheres to the system
double rad = 0.5;
double mass = 1.0;
ChVector<> pos(0, rad * 1.25, 0);
ChVector<> init_v(0, -1, 0);
auto body1 = AddSphere(0, &msystem, mat, rad, mass, pos, init_v);
auto body2 = AddSphere(1, &msystem, mat, rad, mass, pos * -1, init_v * -1);
// Create the Irrlicht visualization.
#ifdef CHRONO_IRRLICHT
bool vis = true;
auto application = SetSimVis(&msystem, time_step, vis);
#endif
// Calculate motion parameters prior to collision
ChVector<> rel_v_in = body2->GetPos_dt() - body1->GetPos_dt();
real rel_vm_in = rel_v_in.Length();
// Print the sim set - up parameters to userlog once
if (f == 0 && var == 0) {
GetLog() << "\ntime_step, " << time_step << "\nout_step, " << out_step << "\ntotal_sim_time, "
<< time_sim << "\nadhesion_model, "
<< static_cast<int>(msystem.GetSettings()->solver.adhesion_force_model)
<< "\ntangential_displ_model, "
<< static_cast<int>(msystem.GetSettings()->solver.tangential_displ_mode) << "\ntimestepper, "
<< static_cast<int>(msystem.GetTimestepperType()) << "\ngravity_x, " << gravity.x()
<< "\ngravity_y, " << gravity.y() << "\ngravity_z, " << gravity.z() << "\nyoungs_modulus, "
<< y_modulus << "\npoissons_ratio, " << p_ratio << "\nstatic_friction, " << s_frict
<< "\nkinetic_friction, " << k_frict << "\nrolling_friction, " << roll_frict
<< "\nspinning_friction, " << spin_frict << "\ncor, "
<< "0 - 1"
<< "\nconstant_adhesion, " << ad << "\nDMT_adhesion_multiplier, " << adDMT
<< "\nperko_adhesion_multiplier, " << adSPerko << "\n";
}
GetLog() << "\nModel #" << f << " (" << fmodels[f].c_str() << ") var setting #" << var << "\n";
// Set the soft-real-time cycle parameters
double time = 0.0;
double out_time = 0.0;
// Iterate through simulation. Calculate resultant forces and motion for each timestep
while (time < time_sim) {
#ifdef CHRONO_IRRLICHT
if (application != NULL) {
application->BeginScene(true, true, SColor(255, 255, 255, 255));
application->DrawAll();
}
#endif
while (time == 0 || time < out_time) {
msystem.DoStepDynamics(time_step);
time += time_step;
}
out_time = time - time_step + out_step;
#ifdef CHRONO_IRRLICHT
if (application != NULL)
application->EndScene();
#endif
}
// Delete Visualization
#ifdef CHRONO_IRRLICHT
if (application != NULL)
delete application;
#endif
// Check results. Should fail test if abs(cor_dif) >= 1.0e-3
ChVector<> rel_v_out = body2->GetPos_dt() - body1->GetPos_dt();
real rel_vm_out = rel_v_out.Length();
real cor_out = rel_vm_out / rel_vm_in;
real cor_dif = cor_in - cor_out;
dat << fmodels[f].c_str() << "," << cor_in << "," << cor_out << "," << abs(cor_dif) << "\n";
}
}
dat.close();
return 0;
} | 43.660606 | 118 | 0.524847 | rserban |
dd567373adbfeea697f13831a0b1da6729f31d95 | 7,094 | hpp | C++ | include/depthai-bootloader-shared/Bootloader.hpp | diablodale/depthai-bootloader-shared | 126f344155346836a6a2d67b0993c161b6b48729 | [
"MIT"
] | 2 | 2020-11-01T22:28:01.000Z | 2021-02-25T23:10:24.000Z | include/depthai-bootloader-shared/Bootloader.hpp | diablodale/depthai-bootloader-shared | 126f344155346836a6a2d67b0993c161b6b48729 | [
"MIT"
] | 2 | 2022-01-20T17:59:28.000Z | 2022-01-25T14:15:37.000Z | include/depthai-bootloader-shared/Bootloader.hpp | diablodale/depthai-bootloader-shared | 126f344155346836a6a2d67b0993c161b6b48729 | [
"MIT"
] | 3 | 2021-05-17T13:33:22.000Z | 2022-03-19T07:06:12.000Z | #pragma once
// std
#include <cstdint>
#include <map>
// project
#include "Type.hpp"
#include "Section.hpp"
#include "Memory.hpp"
namespace dai
{
namespace bootloader
{
namespace request {
enum Command : uint32_t {
USB_ROM_BOOT = 0,
BOOT_APPLICATION,
UPDATE_FLASH,
GET_BOOTLOADER_VERSION,
BOOT_MEMORY,
UPDATE_FLASH_EX,
UPDATE_FLASH_EX_2,
NO_OP,
GET_BOOTLOADER_TYPE,
SET_BOOTLOADER_CONFIG,
GET_BOOTLOADER_CONFIG,
BOOTLOADER_MEMORY,
};
struct BaseRequest {
BaseRequest(Command command) : cmd(command){}
Command cmd;
};
// Specific request PODs
struct UsbRomBoot : BaseRequest {
// Common
UsbRomBoot() : BaseRequest(USB_ROM_BOOT) {}
static constexpr auto VERSION = "0.0.2";
static constexpr const char* NAME = "UsbRomBoot";
};
struct BootApplication : BaseRequest {
// Common
BootApplication() : BaseRequest(BOOT_APPLICATION) {}
// Data
static constexpr const char* VERSION = "0.0.2";
static constexpr const char* NAME = "BootApplication";
};
struct UpdateFlash : BaseRequest {
// Common
UpdateFlash() : BaseRequest(UPDATE_FLASH) {}
// Data
enum Storage : uint32_t { SBR, BOOTLOADER };
Storage storage;
uint32_t totalSize;
uint32_t numPackets;
static constexpr const char* VERSION = "0.0.2";
static constexpr const char* NAME = "UpdateFlash";
};
struct GetBootloaderVersion : BaseRequest {
// Common
GetBootloaderVersion() : BaseRequest(GET_BOOTLOADER_VERSION) {}
// Data
static constexpr const char* VERSION = "0.0.2";
static constexpr const char* NAME = "GetBootloaderVersion";
};
// 0.0.12 or higher
struct BootMemory : BaseRequest {
// Common
BootMemory() : BaseRequest(BOOT_MEMORY) {}
// Data
uint32_t totalSize;
uint32_t numPackets;
static constexpr const char* VERSION = "0.0.12";
static constexpr const char* NAME = "BootMemory";
};
// UpdateFlashEx - Additional options
struct UpdateFlashEx : BaseRequest {
// Common
UpdateFlashEx() : BaseRequest(UPDATE_FLASH_EX) {}
// Data
Memory memory;
Section section;
uint32_t totalSize;
uint32_t numPackets;
static constexpr const char* VERSION = "0.0.12";
static constexpr const char* NAME = "UpdateFlashEx";
};
// UpdateFlashEx2 - Additional options
struct UpdateFlashEx2 : BaseRequest {
// Common
UpdateFlashEx2() : BaseRequest(UPDATE_FLASH_EX_2) {}
// Data
Memory memory;
uint32_t offset;
uint32_t totalSize;
uint32_t numPackets;
static constexpr const char* VERSION = "0.0.12";
static constexpr const char* NAME = "UpdateFlashEx2";
};
struct GetBootloaderType : BaseRequest {
// Common
GetBootloaderType() : BaseRequest(GET_BOOTLOADER_TYPE) {}
// Data
static constexpr const char* VERSION = "0.0.12";
static constexpr const char* NAME = "GetBootloaderType";
};
// 0.0.14 or higher
struct SetBootloaderConfig : BaseRequest {
// Common
SetBootloaderConfig() : BaseRequest(SET_BOOTLOADER_CONFIG) {}
// Data
Memory memory = Memory::AUTO;
int64_t offset = -1;
uint32_t clearConfig = 0;
uint32_t totalSize = 0;
uint32_t numPackets = 0;
static constexpr const char* VERSION = "0.0.14";
static constexpr const char* NAME = "SetBootloaderConfig";
};
struct GetBootloaderConfig : BaseRequest {
// Common
GetBootloaderConfig() : BaseRequest(GET_BOOTLOADER_CONFIG) {}
// Data
Memory memory = Memory::AUTO;
int64_t offset = -1;
uint32_t maxSize = 0;
static constexpr const char* VERSION = "0.0.14";
static constexpr const char* NAME = "GetBootloaderConfig";
};
struct BootloaderMemory : BaseRequest {
// Common
BootloaderMemory() : BaseRequest(BOOTLOADER_MEMORY) {}
// Data
static constexpr const char* VERSION = "0.0.14";
static constexpr const char* NAME = "BootloaderMemory";
};
}
namespace response {
enum Command : uint32_t {
FLASH_COMPLETE = 0,
FLASH_STATUS_UPDATE,
BOOTLOADER_VERSION,
BOOTLOADER_TYPE,
GET_BOOTLOADER_CONFIG,
BOOTLOADER_MEMORY,
BOOT_APPLICATION,
};
struct BaseResponse {
BaseResponse(Command command) : cmd(command){}
Command cmd;
};
// Specific request PODs
struct FlashComplete : BaseResponse {
// Common
FlashComplete() : BaseResponse(FLASH_COMPLETE) {}
// Data
uint32_t success;
char errorMsg[64];
static constexpr const char* VERSION = "0.0.2";
static constexpr const char* NAME = "FlashComplete";
};
struct FlashStatusUpdate : BaseResponse {
// Common
FlashStatusUpdate() : BaseResponse(FLASH_STATUS_UPDATE) {}
// Data
float progress;
static constexpr const char* VERSION = "0.0.2";
static constexpr const char* NAME = "FlashStatusUpdate";
};
struct BootloaderVersion : BaseResponse {
// Common
BootloaderVersion() : BaseResponse(BOOTLOADER_VERSION) {}
// Data
uint32_t major, minor, patch;
static constexpr const char* VERSION = "0.0.2";
static constexpr const char* NAME = "BootloaderVersion";
};
struct BootloaderType : BaseResponse {
// Common
BootloaderType() : BaseResponse(BOOTLOADER_TYPE) {}
// Data
Type type;
static constexpr const char* VERSION = "0.0.12";
static constexpr const char* NAME = "BootloaderType";
};
// 0.0.14
struct GetBootloaderConfig : BaseResponse {
// Common
GetBootloaderConfig() : BaseResponse(GET_BOOTLOADER_CONFIG) {}
// Data
uint32_t success;
char errorMsg[64];
uint32_t totalSize;
uint32_t numPackets;
static constexpr const char* VERSION = "0.0.14";
static constexpr const char* NAME = "GetBootloaderConfig";
};
struct BootloaderMemory : BaseResponse {
// Common
BootloaderMemory() : BaseResponse(BOOTLOADER_MEMORY) {}
// Data
Memory memory;
static constexpr const char* VERSION = "0.0.14";
static constexpr const char* NAME = "BootloaderMemory";
};
struct BootApplication : BaseResponse {
// Common
BootApplication() : BaseResponse(BOOT_APPLICATION) {}
// Data
uint32_t success;
char errorMsg[64];
static constexpr const char* VERSION = "0.0.14";
static constexpr const char* NAME = "BootApplication";
};
}
} // namespace bootloader
} // namespace dai
| 25.245552 | 71 | 0.605018 | diablodale |
dd5db0c0a0273185a12b41f41a87dff3822db3cc | 4,585 | hpp | C++ | src/butterfly/public/butterfly/flattened_serializer.hpp | ButterflyStats/butterfly | 339e91a882cadc1a8f72446616f7d7f1480c3791 | [
"Apache-2.0"
] | 19 | 2017-04-13T07:46:59.000Z | 2021-12-05T20:58:54.000Z | src/butterfly/public/butterfly/flattened_serializer.hpp | ButterflyStats/butterfly | 339e91a882cadc1a8f72446616f7d7f1480c3791 | [
"Apache-2.0"
] | 5 | 2018-03-21T17:06:23.000Z | 2021-12-03T10:58:46.000Z | src/butterfly/public/butterfly/flattened_serializer.hpp | ButterflyStats/butterfly | 339e91a882cadc1a8f72446616f7d7f1480c3791 | [
"Apache-2.0"
] | 4 | 2018-03-11T12:12:07.000Z | 2020-11-17T07:46:37.000Z | /**
* @file flattened_serializer.hpp
* @author Robin Dietrich <me (at) invokr (dot) org>
*
* @par License
* Butterfly Replay Parser
* Copyright 2014-2016 Robin Dietrich
*
* 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.
*
* @par Description
* Code used to handle Source 2's new flattened serializer structure and related class information.
*/
#ifndef BUTTERFLY_FLATTENED_SERIALIZER_HPP
#define BUTTERFLY_FLATTENED_SERIALIZER_HPP
#include <string>
#include <vector>
#include <cstdint>
#include <iostream>
#include <butterfly/proto/netmessages.pb.h>
#include <butterfly/util_assert.hpp>
#include <butterfly/util_dict.hpp>
#include <butterfly/util_noncopyable.hpp>
#include <butterfly/property_decoder.hpp>
namespace butterfly {
// forward decl
struct entity_classes;
/** Field information */
struct fs_info {
/** Name */
std::string name;
/** Original field index */
uint32_t field;
/** Encoder hash */
uint64_t encoder;
/** Outer type hash */
uint64_t type;
/** Bits used to encode type */
uint32_t bits : 31;
/** Whether this property is dynamic */
bool dynamic : 1;
/** Encoding flags */
uint32_t flags;
/** Min val */
float min;
/** Max val */
float max;
};
/** Type information about a property */
struct fs_typeinfo {
/** Whether this property is pointing at another class */
bool is_table : 1;
/** Index of said table */
uint16_t table : 15;
/** Whether this property is dynamic */
bool is_dynamic : 1;
/** Number of members if this is an array */
uint16_t size : 15;
/** Decoder */
decoder_fcn* decoder;
/** Normal information */
fs_info* info;
};
/** Flattened serializer table for a single networked class, points to decoder and property */
struct fs {
/** Returns field at given position */
const fs& operator[]( uint32_t n ) const {
if ( info->dynamic && properties.size() == 1 ) {
return properties[0];
}
ASSERT_TRUE( n < properties.size(), "FS out-of-bounds" );
return properties[n];
}
/** List of fields / props */
std::vector<fs> properties;
/** Pointer to decoder */
decoder_fcn* decoder;
/** Pointer to field info */
fs_info* info;
/** FS name */
std::string name;
/** Hash */
uint64_t hash;
};
/** Flattened serializer structure introduced in Source 2 */
class flattened_serializer : noncopyable {
public:
/** Initialize serializer from data */
flattened_serializer( uint8_t* data, uint32_t size );
/** Destructor */
~flattened_serializer();
/** Build serializers for given entity classes */
void build( entity_classes& cls );
/** Dump serializer at given index to console */
void spew( uint32_t idx, std::ostream& out = std::cout );
/** Return serializer at given index */
const fs& get( uint32_t idx );
/** Returns original type-symbol as string */
std::string get_otype( fs_info* f );
private:
/** Serializer data from replay */
CSVCMsg_FlattenedSerializer serializers;
/** Flattening tables */
std::vector<fs> tables;
/** Tables indexed by name and position */
dict<fs> tables_internal;
/** Stores metadata per property */
std::unordered_map<uint32_t, fs_typeinfo> metadata;
/** Spew implementation */
void spew_impl( uint32_t idx, void* tbl, std::string target = "", bool internal = false );
/** Returns metadata for field */
fs_typeinfo& get_metadata( uint32_t field );
/** Fill string information */
void app_name_hash( std::string n, fs& f );
};
} /* butterfly */
#endif /* BUTTERFLY_FLATTENED_SERIALIZER_HPP */
| 31.40411 | 102 | 0.606325 | ButterflyStats |
e5776cdb74b9e77981175b3832ee10b23e5a8aa0 | 1,620 | cpp | C++ | src/Avalanche/Output.cpp | EvanJRichard/wallet-core | c228cf400827856fac055a42f842f0b1a37fc9ee | [
"MIT"
] | null | null | null | src/Avalanche/Output.cpp | EvanJRichard/wallet-core | c228cf400827856fac055a42f842f0b1a37fc9ee | [
"MIT"
] | 1 | 2021-03-03T17:23:34.000Z | 2021-03-03T17:24:50.000Z | src/Avalanche/Output.cpp | EvanJRichard/wallet-core | c228cf400827856fac055a42f842f0b1a37fc9ee | [
"MIT"
] | null | null | null | // Copyright © 2017-2020 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "../BinaryCoding.h"
#include "Output.h"
using namespace TW::Avalanche;
bool compareOutputForSort(Output lhs, Output rhs) {
if (std::get<0>(lhs) != std::get<0>(rhs)) {
return std::get<0>(lhs) < std::get<0>(rhs);
}
if (std::get<1>(lhs) != std::get<1>(rhs)) {
return std::get<1>(lhs) < std::get<1>(rhs);
}
return std::lexicographical_compare(std::get<2>(lhs).begin(), std::get<2>(lhs).end(), std::get<2>(rhs).begin(), std::get<2>(rhs).end());
}
void TW::Avalanche::SortOutputs(std::vector<Output> &outputs){
// sort the addresses in the outputs, then sort the outputs themselves
for (auto &output : outputs) {
std::sort(std::get<2>(output).begin(), std::get<2>(output).begin());
}
std::sort(outputs.begin(), outputs.end(), compareOutputForSort);
}
// must first call SortOutputs
void TW::Avalanche::EncodeOutputs(std::vector<Output> outputs, Data &data) {
TW::encode32BE(outputs.size(), data);
for (auto output : outputs) {
TW::encode64BE(std::get<0>(output), data);
TW::encode32BE(std::get<1>(output), data);
std::vector<Address> addrs = std::get<2>(output);
TW::encode32BE(addrs.size(), data);
for (auto addr : addrs) {
for (auto byte : addr.getKeyHash()) {
data.push_back(byte);
}
}
}
} | 36.818182 | 140 | 0.619136 | EvanJRichard |
e57d28a6484083152eda26da625041181a622e8e | 93 | cpp | C++ | KGE/Core/ClassCapabilities/ClassFactory.cpp | jkeywo/KGE | 5ad2619a4e205dd549cdf638854db356a80694ea | [
"MIT"
] | 1 | 2016-08-10T14:03:29.000Z | 2016-08-10T14:03:29.000Z | KGE/Core/ClassCapabilities/ClassFactory.cpp | jkeywo/KGE | 5ad2619a4e205dd549cdf638854db356a80694ea | [
"MIT"
] | null | null | null | KGE/Core/ClassCapabilities/ClassFactory.cpp | jkeywo/KGE | 5ad2619a4e205dd549cdf638854db356a80694ea | [
"MIT"
] | null | null | null | #include "KGE.hpp"
#include "Core/ClassCapabilities/ClassFactory.hpp"
namespace KGE
{
};
| 9.3 | 50 | 0.731183 | jkeywo |
e57ed5b81b770ae0a7ec4bb2ce5ae9f7ae9042e1 | 5,481 | cpp | C++ | Minecraft/main.cpp | borbrudar/Minecraft_clone | 117fbe94390f96e3a6227129de60c08a5cc2ccdc | [
"MIT"
] | null | null | null | Minecraft/main.cpp | borbrudar/Minecraft_clone | 117fbe94390f96e3a6227129de60c08a5cc2ccdc | [
"MIT"
] | null | null | null | Minecraft/main.cpp | borbrudar/Minecraft_clone | 117fbe94390f96e3a6227129de60c08a5cc2ccdc | [
"MIT"
] | null | null | null | #include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "Shader.h"
#include "Camera.h"
#include "World.h"
#include "State.h"
#include "Menu.h"
#include "Crosshair.h"
#include "Light.h"
#include <iostream>
#include <functional>
//function prototypes
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void processInput(GLFWwindow *window);
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods);
//global variables
//screensize
const int screenWidth = 800, screenHeight = 600;
//camera
Camera camera(glm::vec3(0.0f, 0.0f, 3.0f));
float lastX = (float)(screenWidth / 2.f);
float lastY = (float)(screenHeight / 2.f);
bool firstMouse = true;
// time
float deltaTime = 0.0f;
float lastFrame = 0.0f;
//chunks (numberOfChunks is a perfect square)
int numberOfChunks = 16;
enum class state {
game,
menu
};
state gameState = state::menu;
bool swappedState = false, rightPosition = false;
int main() {
//initialize the window
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//initialize the window
GLFWwindow *window = glfwCreateWindow(screenWidth, screenHeight, "Minecraft", NULL, NULL);
if (window == NULL) {
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
//set callback functions
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetMouseButtonCallback(window, mouse_button_callback);
//initialize glad
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
//some other opengl settings
glEnable(GL_DEPTH_TEST);
if(gameState == state::game) glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
else if (gameState == state::menu) glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
//create a shaderprogram
Shader defShader("shaders/vertexShader.vs", "shaders/fragementShader.fs");
Shader menuShader("shaders/menV.vs", "shaders/menF.fs");
//create the minecraft world
std::unique_ptr<State> state;
if (gameState == state::game) state = std::make_unique<World>(numberOfChunks, defShader);
else state = std::make_unique<Menu>(menuShader);
//projection matrix - model and view are elsewhere
glm::mat4 projection = glm::perspective(glm::radians(45.0f), (float)screenWidth / (float)screenHeight, 0.1f, 100.0f);
//lighting
Light sun;
bool day = true;
//crosshair
Crosshair hair;
hair.loadCrosshair(menuShader);
//render loop
while (!glfwWindowShouldClose(window)) {
//check the game state
if (swappedState) {
if (gameState == state::game) state = std::make_unique<World>(numberOfChunks, defShader);
else if (gameState == state::menu) state = std::make_unique<Menu>(menuShader);
if (gameState == state::game) glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
else if (gameState == state::menu) glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
swappedState = false;
}
//calculate time
float currentFrame = (float)glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
//process key input
state->processInput(window, camera, deltaTime);
//view matrix (updated every frame)
glm::mat4 view = camera.GetViewMatrix();
// draw here ----------------------------------------------------------------------
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//forward the view and projection matrices (they're intrinsic)
defShader.setMat4("view", view);
defShader.setMat4("projection", projection);
//lighting
defShader.setVec3("viewPos", camera.Position);
sun.update(defShader);
//draw the crosshair
if (gameState == state::game) hair.drawCrosshair(menuShader);
//draw the world
if (gameState == state::game) state->draw(defShader);
else if(gameState == state::menu) state->draw(menuShader);
//----------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents();
}
//exit
glfwTerminate();
return 0;
}
//call this everytime we adjust window size, to change to change the viewport accordingly
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
//process mouse input
void mouse_callback(GLFWwindow* window, double xpos, double ypos) {
if (firstMouse)
{
lastX = (float)xpos;
lastY = (float)ypos;
firstMouse = false;
}
float xoffset = (float)xpos - lastX;
float yoffset = lastY - (float)ypos; // reversed since y-coordinates go from bottom to top
lastX = (float)xpos;
lastY = (float)ypos;
if (gameState == state::game) camera.ProcessMouseMovement(xoffset, yoffset);
if (xpos > 211 && xpos < 586 && ypos > 271 && ypos < 316) rightPosition = true; else rightPosition = false;
}
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) {
if (gameState == state::menu && rightPosition && action == GLFW_PRESS) {
rightPosition = false;
gameState = state::game;
swappedState = true;
}
} | 29.788043 | 118 | 0.711002 | borbrudar |
e57f89777e9d75938abf3e8db1555548c7e350e2 | 158 | hpp | C++ | igb_util/tbl.hpp | centrevillage/igb_sdk | 9c7fc06a016ddb281f5ba3602abae8de8ae5b8f5 | [
"MIT"
] | null | null | null | igb_util/tbl.hpp | centrevillage/igb_sdk | 9c7fc06a016ddb281f5ba3602abae8de8ae5b8f5 | [
"MIT"
] | null | null | null | igb_util/tbl.hpp | centrevillage/igb_sdk | 9c7fc06a016ddb281f5ba3602abae8de8ae5b8f5 | [
"MIT"
] | null | null | null | #ifndef IGB_UTIL_TBL_H
#define IGB_UTIL_TBL_H
#include <cstdint>
namespace igb {
extern const uint32_t euclid_tbl_32[32];
}
#endif /* IGB_UTIL_TBL_H */
| 11.285714 | 40 | 0.753165 | centrevillage |
e580f7ee4d42f78a71c76ce2b3086842041142f6 | 3,896 | cc | C++ | lib/src/whereami.cc | GabrielNagy/libwhereami | 8061b056b38ad2508b735465eae4bd9817091183 | [
"Apache-2.0"
] | 16 | 2017-07-12T05:58:59.000Z | 2022-03-11T01:07:10.000Z | lib/src/whereami.cc | GabrielNagy/libwhereami | 8061b056b38ad2508b735465eae4bd9817091183 | [
"Apache-2.0"
] | 41 | 2017-07-07T16:44:57.000Z | 2019-08-27T13:05:38.000Z | lib/src/whereami.cc | GabrielNagy/libwhereami | 8061b056b38ad2508b735465eae4bd9817091183 | [
"Apache-2.0"
] | 16 | 2017-07-05T15:23:40.000Z | 2022-03-17T21:11:20.000Z | #include <whereami/whereami.hpp>
#include <whereami/version.h>
#include <internal/vm.hpp>
#include <internal/sources/cgroup_source.hpp>
#include <internal/sources/cpuid_source.hpp>
#include <internal/sources/lparstat_source.hpp>
#include <internal/detectors/docker_detector.hpp>
#include <internal/detectors/hyperv_detector.hpp>
#include <internal/detectors/kvm_detector.hpp>
#include <internal/detectors/ldom_detector.hpp>
#include <internal/detectors/lpar_detector.hpp>
#include <internal/detectors/lxc_detector.hpp>
#include <internal/detectors/nspawn_detector.hpp>
#include <internal/detectors/openvz_detector.hpp>
#include <internal/detectors/virtualbox_detector.hpp>
#include <internal/detectors/vmware_detector.hpp>
#include <internal/detectors/wpar_detector.hpp>
#include <internal/detectors/xen_detector.hpp>
#include <internal/detectors/zone_detector.hpp>
#include <leatherman/logging/logging.hpp>
#if defined(_WIN32)
#include <internal/sources/wmi_source.hpp>
#else
#include <internal/sources/dmi_source.hpp>
#include <internal/sources/system_profiler_source.hpp>
#endif
using namespace std;
using namespace whereami;
using namespace whereami::detectors;
namespace whereami {
string version()
{
LOG_DEBUG("whereami version is {1}", WHEREAMI_VERSION_WITH_COMMIT);
return WHEREAMI_VERSION_WITH_COMMIT;
}
vector<result> hypervisors()
{
vector<result> results;
#if defined(_WIN32)
sources::wmi smbios_source;
#else
sources::dmi smbios_source;
#endif
sources::cpuid cpuid_source;
sources::cgroup cgroup_source;
sources::lparstat lparstat_source;
sources::system_profiler system_profiler_source;
auto virtualbox_result = detectors::virtualbox(cpuid_source, smbios_source, system_profiler_source);
if (virtualbox_result.valid()) {
results.emplace_back(virtualbox_result);
}
auto vmware_result = detectors::vmware(cpuid_source, smbios_source, system_profiler_source);
if (vmware_result.valid()) {
results.emplace_back(vmware_result);
}
auto docker_result = detectors::docker(cgroup_source);
if (docker_result.valid()) {
results.emplace_back(docker_result);
}
auto lxc_result = detectors::lxc(cgroup_source);
if (lxc_result.valid()) {
results.emplace_back(lxc_result);
}
auto nspawn_result = detectors::nspawn(cgroup_source);
if (nspawn_result.valid()) {
results.emplace_back(nspawn_result);
}
auto openvz_result = detectors::openvz();
if (openvz_result.valid()) {
results.emplace_back(openvz_result);
}
auto kvm_result = detectors::kvm(cpuid_source, smbios_source);
if (kvm_result.valid()) {
results.emplace_back(kvm_result);
}
auto hyperv_result = detectors::hyperv(cpuid_source, smbios_source);
if (hyperv_result.valid()) {
results.emplace_back(hyperv_result);
}
auto xen_result = detectors::xen(cpuid_source);
if (xen_result.valid()) {
results.emplace_back(xen_result);
}
auto lpar_result = detectors::lpar(lparstat_source);
if (lpar_result.valid()) {
results.emplace_back(lpar_result);
}
auto wpar_result = detectors::wpar(lparstat_source);
if (wpar_result.valid()) {
results.emplace_back(wpar_result);
}
auto zone_result = detectors::zone();
if (zone_result.valid()) {
results.emplace_back(zone_result);
}
#if defined(__sparc__)
auto ldom_result = detectors::ldom();
if (ldom_result.valid()) {
results.emplace_back(ldom_result);
}
#endif
return results;
}
} // namespace whereami
| 27.828571 | 108 | 0.676335 | GabrielNagy |
e58210f26fc474f5d08ca8c3c7683221196f9f0c | 912 | cpp | C++ | src/libraries/KIRK/Utils/LogStream.cpp | lucashilbig/BA_Pathtracing_Fur | bed01d44ef93ff674436e002c82cb8c4663e2832 | [
"MIT"
] | null | null | null | src/libraries/KIRK/Utils/LogStream.cpp | lucashilbig/BA_Pathtracing_Fur | bed01d44ef93ff674436e002c82cb8c4663e2832 | [
"MIT"
] | null | null | null | src/libraries/KIRK/Utils/LogStream.cpp | lucashilbig/BA_Pathtracing_Fur | bed01d44ef93ff674436e002c82cb8c4663e2832 | [
"MIT"
] | null | null | null | /*
* RT
* LogStream.cpp
*
* @author: Hendrik Schwanekamp
* @mail: hendrik.schwanekamp@gmx.net
*
* Implements the LogStream class, which provides stream style input for captain KIRKS log.(see Log.h)
*
*
*/
// includes
//--------------------
#include "LogStream.h"
//--------------------
// namespace
//--------------------
namespace KIRK {
namespace LOG {
//--------------------
// function definitions of the LogStream class
//-------------------------------------------------------------------
LogStream::LogStream(const LogStream &ls) : logger(ls.logger), sFileline(ls.sFileline), lvl(ls.lvl)
{
mFilepath = ls.mFilepath;
str(ls.str());
}
LogStream::LogStream(Log &logger, Level lvl, const char * const filepath, std::string line) : logger(logger), sFileline(line), lvl(lvl)
{
mFilepath = filepath;
}
LogStream::~LogStream()
{
logger.log(lvl, mFilepath, sFileline, "%", str());
}
}} | 21.209302 | 135 | 0.566886 | lucashilbig |
e5843478dbdf15ec767427a3747a0d7e46e86e3a | 39,066 | cpp | C++ | CompilerGenerator/lib/dregx/Grammar.cpp | Deruago/DREGX | f3221b137ae64a5d176095bcbb6472f6c356ad32 | [
"Apache-2.0"
] | 1 | 2022-02-18T19:46:46.000Z | 2022-02-18T19:46:46.000Z | CompilerGenerator/lib/dregx/Grammar.cpp | Deruago/DREGX | f3221b137ae64a5d176095bcbb6472f6c356ad32 | [
"Apache-2.0"
] | null | null | null | CompilerGenerator/lib/dregx/Grammar.cpp | Deruago/DREGX | f3221b137ae64a5d176095bcbb6472f6c356ad32 | [
"Apache-2.0"
] | null | null | null | /*
* This file is auto-generated and auto-maintained by DLDL
* Do not change code in this as it can be overwritten.
*
* For more information see the DLDL repo: https://github.com/Deruago/DLDL
* For more information about Deamer: https://github.com/Deruago/theDeamerProject
*/
#include "dregx/Grammar.h"
#include "dregx/Language.h"
dregx::Grammar::Grammar(dregx::Language* language)
: ::deamer::language::generator::definition::property::user::Grammar<
dregx::Language>(language)
{
}
void dregx::Grammar::GenerateObjects()
{
// Non-Terminal initialization
program.Set(::deamer::language::type::definition::object::main::NonTerminal("program", { program_deamerreserved_star__stmt___opt_pad.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
deamerreserved_star__stmt__.Set(::deamer::language::type::definition::object::main::NonTerminal("deamerreserved_star__stmt__", { deamerreserved_star__stmt___stmt_deamerreserved_star__stmt__.Pointer(),deamerreserved_star__stmt___EMPTY.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , true));
stmt.Set(::deamer::language::type::definition::object::main::NonTerminal("stmt", { stmt_word.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
word.Set(::deamer::language::type::definition::object::main::NonTerminal("word", { word_group.Pointer(),word_square.Pointer(),word_standalone.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
group.Set(::deamer::language::type::definition::object::main::NonTerminal("group", { group_opt_pad_LEFT_CURLY_BRACKET_or_concat_opt_pad_RIGHT_CURLY_BRACKET_OPTIONAL.Pointer(),group_opt_pad_LEFT_CURLY_BRACKET_or_concat_opt_pad_RIGHT_CURLY_BRACKET_STAR.Pointer(),group_opt_pad_LEFT_CURLY_BRACKET_or_concat_opt_pad_RIGHT_CURLY_BRACKET_PLUS.Pointer(),group_opt_pad_LEFT_CURLY_BRACKET_or_concat_opt_pad_RIGHT_CURLY_BRACKET_extension_modifier.Pointer(),group_opt_pad_LEFT_CURLY_BRACKET_or_concat_opt_pad_RIGHT_CURLY_BRACKET.Pointer(),group_opt_pad_LEFT_CURLY_BRACKET_deamerreserved_plus__word___opt_pad_RIGHT_CURLY_BRACKET_OPTIONAL.Pointer(),group_opt_pad_LEFT_CURLY_BRACKET_deamerreserved_plus__word___opt_pad_RIGHT_CURLY_BRACKET_STAR.Pointer(),group_opt_pad_LEFT_CURLY_BRACKET_deamerreserved_plus__word___opt_pad_RIGHT_CURLY_BRACKET_PLUS.Pointer(),group_opt_pad_LEFT_CURLY_BRACKET_deamerreserved_plus__word___opt_pad_RIGHT_CURLY_BRACKET_extension_modifier.Pointer(),group_opt_pad_LEFT_CURLY_BRACKET_deamerreserved_plus__word___opt_pad_RIGHT_CURLY_BRACKET.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
deamerreserved_plus__word__.Set(::deamer::language::type::definition::object::main::NonTerminal("deamerreserved_plus__word__", { deamerreserved_plus__word___word.Pointer(),deamerreserved_plus__word___word_deamerreserved_plus__word__.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , true));
or_concat.Set(::deamer::language::type::definition::object::main::NonTerminal("or_concat", { or_concat_or_element_opt_pad_OR_deamerreserved_arrow__or_element__.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
deamerreserved_arrow__or_element__.Set(::deamer::language::type::definition::object::main::NonTerminal("deamerreserved_arrow__or_element__", { deamerreserved_arrow__or_element___or_element_deamerreserved_star__opt_pad__OR__or_element__.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , true));
deamerreserved_star__opt_pad__OR__or_element__.Set(::deamer::language::type::definition::object::main::NonTerminal("deamerreserved_star__opt_pad__OR__or_element__", { deamerreserved_star__opt_pad__OR__or_element___opt_pad_OR_or_element_deamerreserved_star__opt_pad__OR__or_element__.Pointer(),deamerreserved_star__opt_pad__OR__or_element___EMPTY.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , true));
or_element.Set(::deamer::language::type::definition::object::main::NonTerminal("or_element", { or_element_deamerreserved_plus__word__.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
square.Set(::deamer::language::type::definition::object::main::NonTerminal("square", { square_capture_extension_modifier.Pointer(),square_capture_PLUS.Pointer(),square_capture_STAR.Pointer(),square_capture_OPTIONAL.Pointer(),square_capture.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
capture.Set(::deamer::language::type::definition::object::main::NonTerminal("capture", { capture_opt_pad_LEFT_SQUARE_BRACKET_NOT_deamerreserved_star__capture_logic___RIGHT_SQUARE_BRACKET.Pointer(),capture_opt_pad_LEFT_SQUARE_BRACKET_deamerreserved_star__capture_logic___RIGHT_SQUARE_BRACKET.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
deamerreserved_star__capture_logic__.Set(::deamer::language::type::definition::object::main::NonTerminal("deamerreserved_star__capture_logic__", { deamerreserved_star__capture_logic___capture_logic_deamerreserved_star__capture_logic__.Pointer(),deamerreserved_star__capture_logic___EMPTY.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , true));
capture_logic.Set(::deamer::language::type::definition::object::main::NonTerminal("capture_logic", { capture_logic_capture_range.Pointer(),capture_logic_capture_special_character.Pointer(),capture_logic_capture_letter.Pointer(),capture_logic_capture_number.Pointer(),capture_logic_capture_whitespace.Pointer(),capture_logic_capture_symbols.Pointer(),capture_logic_capture_structure.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
capture_symbols.Set(::deamer::language::type::definition::object::main::NonTerminal("capture_symbols", { capture_symbols_OTHER.Pointer(),capture_symbols_PLUS.Pointer(),capture_symbols_STAR.Pointer(),capture_symbols_COMMA.Pointer(),capture_symbols_OR.Pointer(),capture_symbols_OPTIONAL.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
capture_whitespace.Set(::deamer::language::type::definition::object::main::NonTerminal("capture_whitespace", { capture_whitespace_SPACE.Pointer(),capture_whitespace_TAB.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
capture_range.Set(::deamer::language::type::definition::object::main::NonTerminal("capture_range", { capture_range_capture_letter_range.Pointer(),capture_range_capture_number_range.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
capture_letter_range.Set(::deamer::language::type::definition::object::main::NonTerminal("capture_letter_range", { capture_letter_range_any_letter_exclude_underscore_MIN_any_letter_exclude_underscore.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
capture_number_range.Set(::deamer::language::type::definition::object::main::NonTerminal("capture_number_range", { capture_number_range_NUMBER_MIN_NUMBER.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
capture_number.Set(::deamer::language::type::definition::object::main::NonTerminal("capture_number", { capture_number_any_number.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
capture_letter.Set(::deamer::language::type::definition::object::main::NonTerminal("capture_letter", { capture_letter_any_letter.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
capture_special_character.Set(::deamer::language::type::definition::object::main::NonTerminal("capture_special_character", { capture_special_character_special_char_any.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
extension_modifier.Set(::deamer::language::type::definition::object::main::NonTerminal("extension_modifier", { extension_modifier_opt_pad_LEFT_BRACKET_min_repition_opt_pad_COMMA_max_repition_opt_pad_RIGHT_BRACKET.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
min_repition.Set(::deamer::language::type::definition::object::main::NonTerminal("min_repition", { min_repition_opt_pad_deamerreserved_plus__NUMBER__.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
deamerreserved_plus__NUMBER__.Set(::deamer::language::type::definition::object::main::NonTerminal("deamerreserved_plus__NUMBER__", { deamerreserved_plus__NUMBER___NUMBER.Pointer(),deamerreserved_plus__NUMBER___NUMBER_deamerreserved_plus__NUMBER__.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , true));
max_repition.Set(::deamer::language::type::definition::object::main::NonTerminal("max_repition", { max_repition_opt_pad_deamerreserved_plus__NUMBER__.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
standalone.Set(::deamer::language::type::definition::object::main::NonTerminal("standalone", { standalone_opt_pad_any_letter.Pointer(),standalone_opt_pad_any_number.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
opt_pad.Set(::deamer::language::type::definition::object::main::NonTerminal("opt_pad", { opt_pad_optional_padding.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
optional_padding.Set(::deamer::language::type::definition::object::main::NonTerminal("optional_padding", { optional_padding_deamerreserved_star__padding__.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
deamerreserved_star__padding__.Set(::deamer::language::type::definition::object::main::NonTerminal("deamerreserved_star__padding__", { deamerreserved_star__padding___padding_deamerreserved_star__padding__.Pointer(),deamerreserved_star__padding___EMPTY.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , true));
padding.Set(::deamer::language::type::definition::object::main::NonTerminal("padding", { padding_SPACE.Pointer(),padding_TAB.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
special_char_any.Set(::deamer::language::type::definition::object::main::NonTerminal("special_char_any", { special_char_any_SLASH_any.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
any_number.Set(::deamer::language::type::definition::object::main::NonTerminal("any_number", { any_number_NUMBER.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
any_letter.Set(::deamer::language::type::definition::object::main::NonTerminal("any_letter", { any_letter_any_letter_exclude_underscore.Pointer(),any_letter_UNDERSCORE.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
any_letter_exclude_underscore.Set(::deamer::language::type::definition::object::main::NonTerminal("any_letter_exclude_underscore", { any_letter_exclude_underscore_T_.Pointer(),any_letter_exclude_underscore_R_.Pointer(),any_letter_exclude_underscore_N_.Pointer(),any_letter_exclude_underscore_B_.Pointer(),any_letter_exclude_underscore_V_.Pointer(),any_letter_exclude_underscore_A_.Pointer(),any_letter_exclude_underscore_LETTER.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
capture_structure.Set(::deamer::language::type::definition::object::main::NonTerminal("capture_structure", { capture_structure_LEFT_CURLY_BRACKET.Pointer(),capture_structure_RIGHT_CURLY_BRACKET.Pointer(),capture_structure_LEFT_SQUARE_BRACKET.Pointer(),capture_structure_LEFT_BRACKET.Pointer(),capture_structure_RIGHT_BRACKET.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
any.Set(::deamer::language::type::definition::object::main::NonTerminal("any", { any_LEFT_CURLY_BRACKET.Pointer(),any_RIGHT_CURLY_BRACKET.Pointer(),any_LEFT_SQUARE_BRACKET.Pointer(),any_RIGHT_SQUARE_BRACKET.Pointer(),any_LEFT_BRACKET.Pointer(),any_RIGHT_BRACKET.Pointer(),any_COMMA.Pointer(),any_OR.Pointer(),any_MIN.Pointer(),any_OPTIONAL.Pointer(),any_UNDERSCORE.Pointer(),any_NOT.Pointer(),any_NUMBER.Pointer(),any_T_.Pointer(),any_N_.Pointer(),any_R_.Pointer(),any_B_.Pointer(),any_V_.Pointer(),any_A_.Pointer(),any_LETTER.Pointer(),any_SPACE.Pointer(),any_TAB.Pointer(),any_PLUS.Pointer(),any_STAR.Pointer(),any_OTHER.Pointer(),any_SLASH.Pointer() } , ::deamer::language::type::definition::object::main::NonTerminalAbstraction::Standard , false));
// Production-Rule initialization
deamerreserved_star__stmt___stmt_deamerreserved_star__stmt__.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->stmt.Pointer(),Language->deamerreserved_star__stmt__.Pointer() }));
deamerreserved_star__stmt___EMPTY.Set(::deamer::language::type::definition::object::main::ProductionRule());
program_deamerreserved_star__stmt___opt_pad.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->deamerreserved_star__stmt__.Pointer(),Language->opt_pad.Pointer() }));
stmt_word.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->word.Pointer() }));
word_group.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->group.Pointer() }));
word_square.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->square.Pointer() }));
word_standalone.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->standalone.Pointer() }));
group_opt_pad_LEFT_CURLY_BRACKET_or_concat_opt_pad_RIGHT_CURLY_BRACKET_OPTIONAL.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->opt_pad.Pointer(),Language->LEFT_CURLY_BRACKET.Pointer(),Language->or_concat.Pointer(),Language->opt_pad.Pointer(),Language->RIGHT_CURLY_BRACKET.Pointer(),Language->OPTIONAL.Pointer() }));
group_opt_pad_LEFT_CURLY_BRACKET_or_concat_opt_pad_RIGHT_CURLY_BRACKET_STAR.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->opt_pad.Pointer(),Language->LEFT_CURLY_BRACKET.Pointer(),Language->or_concat.Pointer(),Language->opt_pad.Pointer(),Language->RIGHT_CURLY_BRACKET.Pointer(),Language->STAR.Pointer() }));
group_opt_pad_LEFT_CURLY_BRACKET_or_concat_opt_pad_RIGHT_CURLY_BRACKET_PLUS.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->opt_pad.Pointer(),Language->LEFT_CURLY_BRACKET.Pointer(),Language->or_concat.Pointer(),Language->opt_pad.Pointer(),Language->RIGHT_CURLY_BRACKET.Pointer(),Language->PLUS.Pointer() }));
group_opt_pad_LEFT_CURLY_BRACKET_or_concat_opt_pad_RIGHT_CURLY_BRACKET_extension_modifier.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->opt_pad.Pointer(),Language->LEFT_CURLY_BRACKET.Pointer(),Language->or_concat.Pointer(),Language->opt_pad.Pointer(),Language->RIGHT_CURLY_BRACKET.Pointer(),Language->extension_modifier.Pointer() }));
group_opt_pad_LEFT_CURLY_BRACKET_or_concat_opt_pad_RIGHT_CURLY_BRACKET.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->opt_pad.Pointer(),Language->LEFT_CURLY_BRACKET.Pointer(),Language->or_concat.Pointer(),Language->opt_pad.Pointer(),Language->RIGHT_CURLY_BRACKET.Pointer() }));
deamerreserved_plus__word___word.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->word.Pointer() }));
deamerreserved_plus__word___word_deamerreserved_plus__word__.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->word.Pointer(),Language->deamerreserved_plus__word__.Pointer() }));
group_opt_pad_LEFT_CURLY_BRACKET_deamerreserved_plus__word___opt_pad_RIGHT_CURLY_BRACKET_OPTIONAL.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->opt_pad.Pointer(),Language->LEFT_CURLY_BRACKET.Pointer(),Language->deamerreserved_plus__word__.Pointer(),Language->opt_pad.Pointer(),Language->RIGHT_CURLY_BRACKET.Pointer(),Language->OPTIONAL.Pointer() }));
group_opt_pad_LEFT_CURLY_BRACKET_deamerreserved_plus__word___opt_pad_RIGHT_CURLY_BRACKET_STAR.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->opt_pad.Pointer(),Language->LEFT_CURLY_BRACKET.Pointer(),Language->deamerreserved_plus__word__.Pointer(),Language->opt_pad.Pointer(),Language->RIGHT_CURLY_BRACKET.Pointer(),Language->STAR.Pointer() }));
group_opt_pad_LEFT_CURLY_BRACKET_deamerreserved_plus__word___opt_pad_RIGHT_CURLY_BRACKET_PLUS.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->opt_pad.Pointer(),Language->LEFT_CURLY_BRACKET.Pointer(),Language->deamerreserved_plus__word__.Pointer(),Language->opt_pad.Pointer(),Language->RIGHT_CURLY_BRACKET.Pointer(),Language->PLUS.Pointer() }));
group_opt_pad_LEFT_CURLY_BRACKET_deamerreserved_plus__word___opt_pad_RIGHT_CURLY_BRACKET_extension_modifier.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->opt_pad.Pointer(),Language->LEFT_CURLY_BRACKET.Pointer(),Language->deamerreserved_plus__word__.Pointer(),Language->opt_pad.Pointer(),Language->RIGHT_CURLY_BRACKET.Pointer(),Language->extension_modifier.Pointer() }));
group_opt_pad_LEFT_CURLY_BRACKET_deamerreserved_plus__word___opt_pad_RIGHT_CURLY_BRACKET.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->opt_pad.Pointer(),Language->LEFT_CURLY_BRACKET.Pointer(),Language->deamerreserved_plus__word__.Pointer(),Language->opt_pad.Pointer(),Language->RIGHT_CURLY_BRACKET.Pointer() }));
deamerreserved_arrow__or_element___or_element_deamerreserved_star__opt_pad__OR__or_element__.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->or_element.Pointer(),Language->deamerreserved_star__opt_pad__OR__or_element__.Pointer() }));
deamerreserved_star__opt_pad__OR__or_element___opt_pad_OR_or_element_deamerreserved_star__opt_pad__OR__or_element__.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->opt_pad.Pointer(),Language->OR.Pointer(),Language->or_element.Pointer(),Language->deamerreserved_star__opt_pad__OR__or_element__.Pointer() }));
deamerreserved_star__opt_pad__OR__or_element___EMPTY.Set(::deamer::language::type::definition::object::main::ProductionRule());
or_concat_or_element_opt_pad_OR_deamerreserved_arrow__or_element__.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->or_element.Pointer(),Language->opt_pad.Pointer(),Language->OR.Pointer(),Language->deamerreserved_arrow__or_element__.Pointer() }));
or_element_deamerreserved_plus__word__.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->deamerreserved_plus__word__.Pointer() }));
square_capture_extension_modifier.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->capture.Pointer(),Language->extension_modifier.Pointer() }));
square_capture_PLUS.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->capture.Pointer(),Language->PLUS.Pointer() }));
square_capture_STAR.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->capture.Pointer(),Language->STAR.Pointer() }));
square_capture_OPTIONAL.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->capture.Pointer(),Language->OPTIONAL.Pointer() }));
square_capture.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->capture.Pointer() }));
deamerreserved_star__capture_logic___capture_logic_deamerreserved_star__capture_logic__.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->capture_logic.Pointer(),Language->deamerreserved_star__capture_logic__.Pointer() }));
deamerreserved_star__capture_logic___EMPTY.Set(::deamer::language::type::definition::object::main::ProductionRule());
capture_opt_pad_LEFT_SQUARE_BRACKET_NOT_deamerreserved_star__capture_logic___RIGHT_SQUARE_BRACKET.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->opt_pad.Pointer(),Language->LEFT_SQUARE_BRACKET_NOT.Pointer(),Language->deamerreserved_star__capture_logic__.Pointer(),Language->RIGHT_SQUARE_BRACKET.Pointer() }));
capture_opt_pad_LEFT_SQUARE_BRACKET_deamerreserved_star__capture_logic___RIGHT_SQUARE_BRACKET.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->opt_pad.Pointer(),Language->LEFT_SQUARE_BRACKET.Pointer(),Language->deamerreserved_star__capture_logic__.Pointer(),Language->RIGHT_SQUARE_BRACKET.Pointer() }));
capture_logic_capture_range.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->capture_range.Pointer() }));
capture_logic_capture_special_character.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->capture_special_character.Pointer() }));
capture_logic_capture_letter.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->capture_letter.Pointer() }));
capture_logic_capture_number.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->capture_number.Pointer() }));
capture_logic_capture_whitespace.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->capture_whitespace.Pointer() }));
capture_logic_capture_symbols.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->capture_symbols.Pointer() }));
capture_logic_capture_structure.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->capture_structure.Pointer() }));
capture_symbols_OTHER.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->OTHER.Pointer() }));
capture_symbols_PLUS.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->PLUS.Pointer() }));
capture_symbols_STAR.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->STAR.Pointer() }));
capture_symbols_COMMA.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->COMMA.Pointer() }));
capture_symbols_OR.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->OR.Pointer() }));
capture_symbols_OPTIONAL.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->OPTIONAL.Pointer() }));
capture_whitespace_SPACE.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->SPACE.Pointer() }));
capture_whitespace_TAB.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->TAB.Pointer() }));
capture_range_capture_letter_range.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->capture_letter_range.Pointer() }));
capture_range_capture_number_range.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->capture_number_range.Pointer() }));
capture_letter_range_any_letter_exclude_underscore_MIN_any_letter_exclude_underscore.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->any_letter_exclude_underscore.Pointer(),Language->MIN.Pointer(),Language->any_letter_exclude_underscore.Pointer() }));
capture_number_range_NUMBER_MIN_NUMBER.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->NUMBER.Pointer(),Language->MIN.Pointer(),Language->NUMBER.Pointer() }));
capture_number_any_number.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->any_number.Pointer() }));
capture_letter_any_letter.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->any_letter.Pointer() }));
capture_special_character_special_char_any.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->special_char_any.Pointer() }));
extension_modifier_opt_pad_LEFT_BRACKET_min_repition_opt_pad_COMMA_max_repition_opt_pad_RIGHT_BRACKET.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->opt_pad.Pointer(),Language->LEFT_BRACKET.Pointer(),Language->min_repition.Pointer(),Language->opt_pad.Pointer(),Language->COMMA.Pointer(),Language->max_repition.Pointer(),Language->opt_pad.Pointer(),Language->RIGHT_BRACKET.Pointer() }));
deamerreserved_plus__NUMBER___NUMBER.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->NUMBER.Pointer() }));
deamerreserved_plus__NUMBER___NUMBER_deamerreserved_plus__NUMBER__.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->NUMBER.Pointer(),Language->deamerreserved_plus__NUMBER__.Pointer() }));
min_repition_opt_pad_deamerreserved_plus__NUMBER__.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->opt_pad.Pointer(),Language->deamerreserved_plus__NUMBER__.Pointer() }));
max_repition_opt_pad_deamerreserved_plus__NUMBER__.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->opt_pad.Pointer(),Language->deamerreserved_plus__NUMBER__.Pointer() }));
standalone_opt_pad_any_letter.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->opt_pad.Pointer(),Language->any_letter.Pointer() }));
standalone_opt_pad_any_number.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->opt_pad.Pointer(),Language->any_number.Pointer() }));
opt_pad_optional_padding.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->optional_padding.Pointer() }));
deamerreserved_star__padding___padding_deamerreserved_star__padding__.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->padding.Pointer(),Language->deamerreserved_star__padding__.Pointer() }));
deamerreserved_star__padding___EMPTY.Set(::deamer::language::type::definition::object::main::ProductionRule());
optional_padding_deamerreserved_star__padding__.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->deamerreserved_star__padding__.Pointer() }));
padding_SPACE.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->SPACE.Pointer() }));
padding_TAB.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->TAB.Pointer() }));
special_char_any_SLASH_any.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->SLASH.Pointer(),Language->any.Pointer() }));
any_number_NUMBER.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->NUMBER.Pointer() }));
any_letter_any_letter_exclude_underscore.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->any_letter_exclude_underscore.Pointer() }));
any_letter_UNDERSCORE.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->UNDERSCORE.Pointer() }));
any_letter_exclude_underscore_T_.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->T_.Pointer() }));
any_letter_exclude_underscore_R_.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->R_.Pointer() }));
any_letter_exclude_underscore_N_.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->N_.Pointer() }));
any_letter_exclude_underscore_B_.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->B_.Pointer() }));
any_letter_exclude_underscore_V_.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->V_.Pointer() }));
any_letter_exclude_underscore_A_.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->A_.Pointer() }));
any_letter_exclude_underscore_LETTER.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->LETTER.Pointer() }));
capture_structure_LEFT_CURLY_BRACKET.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->LEFT_CURLY_BRACKET.Pointer() }));
capture_structure_RIGHT_CURLY_BRACKET.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->RIGHT_CURLY_BRACKET.Pointer() }));
capture_structure_LEFT_SQUARE_BRACKET.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->LEFT_SQUARE_BRACKET.Pointer() }));
capture_structure_LEFT_BRACKET.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->LEFT_BRACKET.Pointer() }));
capture_structure_RIGHT_BRACKET.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->RIGHT_BRACKET.Pointer() }));
any_LEFT_CURLY_BRACKET.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->LEFT_CURLY_BRACKET.Pointer() }));
any_RIGHT_CURLY_BRACKET.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->RIGHT_CURLY_BRACKET.Pointer() }));
any_LEFT_SQUARE_BRACKET.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->LEFT_SQUARE_BRACKET.Pointer() }));
any_RIGHT_SQUARE_BRACKET.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->RIGHT_SQUARE_BRACKET.Pointer() }));
any_LEFT_BRACKET.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->LEFT_BRACKET.Pointer() }));
any_RIGHT_BRACKET.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->RIGHT_BRACKET.Pointer() }));
any_COMMA.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->COMMA.Pointer() }));
any_OR.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->OR.Pointer() }));
any_MIN.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->MIN.Pointer() }));
any_OPTIONAL.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->OPTIONAL.Pointer() }));
any_UNDERSCORE.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->UNDERSCORE.Pointer() }));
any_NOT.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->NOT.Pointer() }));
any_NUMBER.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->NUMBER.Pointer() }));
any_T_.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->T_.Pointer() }));
any_N_.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->N_.Pointer() }));
any_R_.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->R_.Pointer() }));
any_B_.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->B_.Pointer() }));
any_V_.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->V_.Pointer() }));
any_A_.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->A_.Pointer() }));
any_LETTER.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->LETTER.Pointer() }));
any_SPACE.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->SPACE.Pointer() }));
any_TAB.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->TAB.Pointer() }));
any_PLUS.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->PLUS.Pointer() }));
any_STAR.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->STAR.Pointer() }));
any_OTHER.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->OTHER.Pointer() }));
any_SLASH.Set(::deamer::language::type::definition::object::main::ProductionRule({ Language->SLASH.Pointer() }));
// Unknown references
// Add object calls
// AddObject(...)
AddObject(program);
AddObject(deamerreserved_star__stmt__);
AddObject(stmt);
AddObject(word);
AddObject(group);
AddObject(deamerreserved_plus__word__);
AddObject(or_concat);
AddObject(deamerreserved_arrow__or_element__);
AddObject(deamerreserved_star__opt_pad__OR__or_element__);
AddObject(or_element);
AddObject(square);
AddObject(capture);
AddObject(deamerreserved_star__capture_logic__);
AddObject(capture_logic);
AddObject(capture_symbols);
AddObject(capture_whitespace);
AddObject(capture_range);
AddObject(capture_letter_range);
AddObject(capture_number_range);
AddObject(capture_number);
AddObject(capture_letter);
AddObject(capture_special_character);
AddObject(extension_modifier);
AddObject(min_repition);
AddObject(deamerreserved_plus__NUMBER__);
AddObject(max_repition);
AddObject(standalone);
AddObject(opt_pad);
AddObject(optional_padding);
AddObject(deamerreserved_star__padding__);
AddObject(padding);
AddObject(special_char_any);
AddObject(any_number);
AddObject(any_letter);
AddObject(any_letter_exclude_underscore);
AddObject(capture_structure);
AddObject(any);
AddObject(deamerreserved_star__stmt___stmt_deamerreserved_star__stmt__);
AddObject(deamerreserved_star__stmt___EMPTY);
AddObject(program_deamerreserved_star__stmt___opt_pad);
AddObject(stmt_word);
AddObject(word_group);
AddObject(word_square);
AddObject(word_standalone);
AddObject(group_opt_pad_LEFT_CURLY_BRACKET_or_concat_opt_pad_RIGHT_CURLY_BRACKET_OPTIONAL);
AddObject(group_opt_pad_LEFT_CURLY_BRACKET_or_concat_opt_pad_RIGHT_CURLY_BRACKET_STAR);
AddObject(group_opt_pad_LEFT_CURLY_BRACKET_or_concat_opt_pad_RIGHT_CURLY_BRACKET_PLUS);
AddObject(group_opt_pad_LEFT_CURLY_BRACKET_or_concat_opt_pad_RIGHT_CURLY_BRACKET_extension_modifier);
AddObject(group_opt_pad_LEFT_CURLY_BRACKET_or_concat_opt_pad_RIGHT_CURLY_BRACKET);
AddObject(deamerreserved_plus__word___word);
AddObject(deamerreserved_plus__word___word_deamerreserved_plus__word__);
AddObject(group_opt_pad_LEFT_CURLY_BRACKET_deamerreserved_plus__word___opt_pad_RIGHT_CURLY_BRACKET_OPTIONAL);
AddObject(group_opt_pad_LEFT_CURLY_BRACKET_deamerreserved_plus__word___opt_pad_RIGHT_CURLY_BRACKET_STAR);
AddObject(group_opt_pad_LEFT_CURLY_BRACKET_deamerreserved_plus__word___opt_pad_RIGHT_CURLY_BRACKET_PLUS);
AddObject(group_opt_pad_LEFT_CURLY_BRACKET_deamerreserved_plus__word___opt_pad_RIGHT_CURLY_BRACKET_extension_modifier);
AddObject(group_opt_pad_LEFT_CURLY_BRACKET_deamerreserved_plus__word___opt_pad_RIGHT_CURLY_BRACKET);
AddObject(deamerreserved_arrow__or_element___or_element_deamerreserved_star__opt_pad__OR__or_element__);
AddObject(deamerreserved_star__opt_pad__OR__or_element___opt_pad_OR_or_element_deamerreserved_star__opt_pad__OR__or_element__);
AddObject(deamerreserved_star__opt_pad__OR__or_element___EMPTY);
AddObject(or_concat_or_element_opt_pad_OR_deamerreserved_arrow__or_element__);
AddObject(or_element_deamerreserved_plus__word__);
AddObject(square_capture_extension_modifier);
AddObject(square_capture_PLUS);
AddObject(square_capture_STAR);
AddObject(square_capture_OPTIONAL);
AddObject(square_capture);
AddObject(deamerreserved_star__capture_logic___capture_logic_deamerreserved_star__capture_logic__);
AddObject(deamerreserved_star__capture_logic___EMPTY);
AddObject(capture_opt_pad_LEFT_SQUARE_BRACKET_NOT_deamerreserved_star__capture_logic___RIGHT_SQUARE_BRACKET);
AddObject(capture_opt_pad_LEFT_SQUARE_BRACKET_deamerreserved_star__capture_logic___RIGHT_SQUARE_BRACKET);
AddObject(capture_logic_capture_range);
AddObject(capture_logic_capture_special_character);
AddObject(capture_logic_capture_letter);
AddObject(capture_logic_capture_number);
AddObject(capture_logic_capture_whitespace);
AddObject(capture_logic_capture_symbols);
AddObject(capture_logic_capture_structure);
AddObject(capture_symbols_OTHER);
AddObject(capture_symbols_PLUS);
AddObject(capture_symbols_STAR);
AddObject(capture_symbols_COMMA);
AddObject(capture_symbols_OR);
AddObject(capture_symbols_OPTIONAL);
AddObject(capture_whitespace_SPACE);
AddObject(capture_whitespace_TAB);
AddObject(capture_range_capture_letter_range);
AddObject(capture_range_capture_number_range);
AddObject(capture_letter_range_any_letter_exclude_underscore_MIN_any_letter_exclude_underscore);
AddObject(capture_number_range_NUMBER_MIN_NUMBER);
AddObject(capture_number_any_number);
AddObject(capture_letter_any_letter);
AddObject(capture_special_character_special_char_any);
AddObject(extension_modifier_opt_pad_LEFT_BRACKET_min_repition_opt_pad_COMMA_max_repition_opt_pad_RIGHT_BRACKET);
AddObject(deamerreserved_plus__NUMBER___NUMBER);
AddObject(deamerreserved_plus__NUMBER___NUMBER_deamerreserved_plus__NUMBER__);
AddObject(min_repition_opt_pad_deamerreserved_plus__NUMBER__);
AddObject(max_repition_opt_pad_deamerreserved_plus__NUMBER__);
AddObject(standalone_opt_pad_any_letter);
AddObject(standalone_opt_pad_any_number);
AddObject(opt_pad_optional_padding);
AddObject(deamerreserved_star__padding___padding_deamerreserved_star__padding__);
AddObject(deamerreserved_star__padding___EMPTY);
AddObject(optional_padding_deamerreserved_star__padding__);
AddObject(padding_SPACE);
AddObject(padding_TAB);
AddObject(special_char_any_SLASH_any);
AddObject(any_number_NUMBER);
AddObject(any_letter_any_letter_exclude_underscore);
AddObject(any_letter_UNDERSCORE);
AddObject(any_letter_exclude_underscore_T_);
AddObject(any_letter_exclude_underscore_R_);
AddObject(any_letter_exclude_underscore_N_);
AddObject(any_letter_exclude_underscore_B_);
AddObject(any_letter_exclude_underscore_V_);
AddObject(any_letter_exclude_underscore_A_);
AddObject(any_letter_exclude_underscore_LETTER);
AddObject(capture_structure_LEFT_CURLY_BRACKET);
AddObject(capture_structure_RIGHT_CURLY_BRACKET);
AddObject(capture_structure_LEFT_SQUARE_BRACKET);
AddObject(capture_structure_LEFT_BRACKET);
AddObject(capture_structure_RIGHT_BRACKET);
AddObject(any_LEFT_CURLY_BRACKET);
AddObject(any_RIGHT_CURLY_BRACKET);
AddObject(any_LEFT_SQUARE_BRACKET);
AddObject(any_RIGHT_SQUARE_BRACKET);
AddObject(any_LEFT_BRACKET);
AddObject(any_RIGHT_BRACKET);
AddObject(any_COMMA);
AddObject(any_OR);
AddObject(any_MIN);
AddObject(any_OPTIONAL);
AddObject(any_UNDERSCORE);
AddObject(any_NOT);
AddObject(any_NUMBER);
AddObject(any_T_);
AddObject(any_N_);
AddObject(any_R_);
AddObject(any_B_);
AddObject(any_V_);
AddObject(any_A_);
AddObject(any_LETTER);
AddObject(any_SPACE);
AddObject(any_TAB);
AddObject(any_PLUS);
AddObject(any_STAR);
AddObject(any_OTHER);
AddObject(any_SLASH);
// Place higher level operations here.
// ReplaceObject(..., ...)
// DeleteObject(..., ...)
}
| 115.922849 | 1,160 | 0.823094 | Deruago |
e585362947b3f83e240e63a1a23faeb270f9ec20 | 134 | cpp | C++ | clang-ast/functions.cpp | strandfield/cxxast | 423e383b7d85d1c1c9299f86fec9b2231031ee78 | [
"MIT"
] | null | null | null | clang-ast/functions.cpp | strandfield/cxxast | 423e383b7d85d1c1c9299f86fec9b2231031ee78 | [
"MIT"
] | null | null | null | clang-ast/functions.cpp | strandfield/cxxast | 423e383b7d85d1c1c9299f86fec9b2231031ee78 | [
"MIT"
] | null | null | null |
void foo(int a = 3 + 5)
{
int b = a + 2;
}
int add(int a, int b)
{
return a + b;
}
int bar() = delete;
struct A { };
A aa();
| 7.882353 | 23 | 0.470149 | strandfield |
e58965da2cee30be0d50e000f5ee49d8f91f20e4 | 743 | hpp | C++ | include/engge/System/Locator.hpp | scemino/engge | 3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f | [
"MIT"
] | 127 | 2018-12-09T18:40:02.000Z | 2022-03-06T00:10:07.000Z | include/engge/System/Locator.hpp | scemino/engge | 3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f | [
"MIT"
] | 267 | 2019-02-26T22:16:48.000Z | 2022-02-09T09:49:22.000Z | include/engge/System/Locator.hpp | scemino/engge | 3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f | [
"MIT"
] | 17 | 2019-02-26T20:45:34.000Z | 2021-06-17T15:06:26.000Z | #pragma once
#include <memory>
namespace ng {
class Logger;
class EntityManager;
template<typename TService>
struct Locator {
Locator() = delete;
~Locator() = delete;
inline static void set(std::shared_ptr<TService> pService) {
m_pService = std::move(pService);
}
template<class ..._Args>
inline static TService &create(_Args &&...__args) {
m_pService = std::move(std::make_shared<TService>(std::forward<_Args>(__args)...));
return *m_pService;
}
inline static TService &get() {
return *m_pService;
}
static void reset() {
m_pService.reset();
}
private:
static std::shared_ptr<TService> m_pService;
};
template<typename TService>
std::shared_ptr<TService> Locator<TService>::m_pService{};
}
| 19.552632 | 87 | 0.690444 | scemino |
e58bd11358f20b23fb3950f147a9474f656c3c54 | 841 | hpp | C++ | third_party/boost/simd/detail/dispatch/function.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | 6 | 2018-02-25T22:23:33.000Z | 2021-01-15T15:13:12.000Z | third_party/boost/simd/detail/dispatch/function.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | null | null | null | third_party/boost/simd/detail/dispatch/function.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | 7 | 2017-12-12T12:36:31.000Z | 2020-02-10T14:27:07.000Z | //==================================================================================================
/*!
@file
Gateway header for dispatched function and callable object helpers
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
**/
//==================================================================================================
#ifndef BOOST_SIMD_DETAIL_DISPATCH_FUNCTION_HPP_INCLUDED
#define BOOST_SIMD_DETAIL_DISPATCH_FUNCTION_HPP_INCLUDED
#include <boost/simd/detail/dispatch/function/functor.hpp>
#include <boost/simd/detail/dispatch/function/make_callable.hpp>
#include <boost/simd/detail/dispatch/function/overload.hpp>
#include <boost/simd/detail/dispatch/function/register_namespace.hpp>
#endif
| 36.565217 | 100 | 0.617122 | SylvainCorlay |
e58d230f12544730c43fd2986347fa7e9fd6aa8c | 1,997 | cpp | C++ | ocuequation/sol_project3d.cpp | maexlich/opencurrent | a51c5a8105563d2f7e260ee7debf79bda2c2dcf0 | [
"Apache-2.0"
] | 4 | 2016-11-16T15:29:31.000Z | 2018-03-27T03:29:14.000Z | ocuequation/sol_project3d.cpp | laosunhust/FluidSolver | d0c7fa235853863efdf44b742c70cf6673c8cf9e | [
"Apache-2.0"
] | 1 | 2020-01-26T12:29:00.000Z | 2020-01-26T13:56:20.000Z | ocuequation/sol_project3d.cpp | laosunhust/FluidSolver | d0c7fa235853863efdf44b742c70cf6673c8cf9e | [
"Apache-2.0"
] | 1 | 2018-02-14T16:13:13.000Z | 2018-02-14T16:13:13.000Z | /*
* Copyright 2008-2009 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstdio>
#include "ocuutil/float_routines.h"
#include "ocustorage/grid3dops.h"
#include "ocuequation/sol_project3d.h"
namespace ocu {
BoundaryCondition
Sol_ProjectDivergence3DBase::convert_bc_to_poisson_eqn(const BoundaryCondition &bc) const
{
BoundaryCondition ret;
if (bc.type == BC_PERIODIC) {
ret.type = BC_PERIODIC;
}
else if (bc.type == BC_FORCED_INFLOW_VARIABLE_SLIP) {
ret.type = BC_NEUMANN;
ret.value = 0;
}
else {
printf("[ERROR] Sol_ProjectDivergence3DBase::convert_bc_to_poisson_eqn - invalid boundary condition type %d\n", bc.type);
}
return ret;
}
bool
Sol_ProjectDivergence3DBase::initialize_base_storage(
int nx, int ny, int nz, double hx, double hy, double hz, Grid3DUntyped *u_val, Grid3DUntyped *v_val, Grid3DUntyped *w_val)
{
if (!check_valid_mac_dimensions(*u_val, *v_val, *w_val, nx, ny, nz)) {
printf("[ERROR] Sol_ProjectDivergence3DBase::initialize_base_storage - u,v,w grid dimensions mismatch\n");
return false;
}
if (!check_float(hx) || !check_float(hy) || !check_float(hz)) {
printf("[ERROR] Sol_ProjectDivergence3DBase::initialize_base_storage - garbage hx,hy,hz value\n");
return false;
}
_hx = hx;
_hy = hy;
_hz = hz;
_nx = nx;
_ny = ny;
_nz = nz;
return true;
}
} // end namespace
| 27.736111 | 126 | 0.689034 | maexlich |
e58ed9392c9ae65e6ee5203e04719ebcaf119c45 | 1,044 | cpp | C++ | src/plugins/lmp/nativeplaylist.cpp | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 120 | 2015-01-22T14:10:39.000Z | 2021-11-25T12:57:16.000Z | src/plugins/lmp/nativeplaylist.cpp | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 8 | 2015-02-07T19:38:19.000Z | 2017-11-30T20:18:28.000Z | src/plugins/lmp/nativeplaylist.cpp | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 33 | 2015-02-07T16:59:55.000Z | 2021-10-12T00:36:40.000Z | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* 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 "nativeplaylist.h"
#include <util/sll/prelude.h>
#include "mediainfo.h"
#include "playlistparsers/playlist.h"
namespace LC
{
namespace LMP
{
Playlist ToDumbPlaylist (const NativePlaylist_t& playlist)
{
return Util::Map (playlist,
[] (const NativePlaylistItem_t& item)
{
return item.second ?
PlaylistItem { item.first, *item.second } :
PlaylistItem { item.first };
});
}
NativePlaylist_t FromDumbPlaylist (const Playlist& playlist)
{
return Util::Map (playlist,
[] (const PlaylistItem& item)
{
return NativePlaylistItem_t { item.Source_, item.GetMediaInfo () };
});
}
}
}
| 26.769231 | 83 | 0.600575 | Maledictus |
e5927ffb529c65b9f5e55dbb433a58c5c6b78421 | 896 | cpp | C++ | PC_Aula_04/sumofthreevalues/main.cpp | ElizabethYasmin/PC | e3cd03d7f80fae366df1181d5b87514ea8ee597c | [
"MIT"
] | null | null | null | PC_Aula_04/sumofthreevalues/main.cpp | ElizabethYasmin/PC | e3cd03d7f80fae366df1181d5b87514ea8ee597c | [
"MIT"
] | null | null | null | PC_Aula_04/sumofthreevalues/main.cpp | ElizabethYasmin/PC | e3cd03d7f80fae366df1181d5b87514ea8ee597c | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
#include <map>
#include <iterator>
#include <unordered_map>
using namespace std;
//entrada
//4 8
//2 7 5 1
//salida
//1 3 4
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
int n,x; cin >> n >> x;
vector<pair<int, int>> arr;
for(int i = 1; i <= n; i++){
int a; cin >> a;
pair<int, int> p; p.first = a; p.second = i;
arr.push_back(p);
}
sort(begin(arr), end(arr));
for(int i = 0; i < n; i++){
int l, r; l = 0; r = n-1;
while(l != r){
int target; target = x - arr.at(i).first;
if(l != i && r != i && arr.at(l).first + arr.at(r).first == target){
cout << arr.at(i).second << " " << arr.at(l).second
<< " " << arr.at(r).second << endl;
return 0;
}
if(arr.at(l).first + arr.at(r).first < target){
l++;
}
else{
r--;
}
}
}
cout << "IMPOSSIBLE" << endl;
} | 20.837209 | 71 | 0.534598 | ElizabethYasmin |
e5948e8070bfbf1ea11438202b237294b3949a8f | 2,027 | cpp | C++ | skse64/nva_skse_plugin/main.cpp | michaeljdietz/NpcVoiceActivation | df62efc5e6ed9510e4f9423561071d7119a3a44b | [
"MIT"
] | 1 | 2020-02-11T12:25:39.000Z | 2020-02-11T12:25:39.000Z | skse64/nva_skse_plugin/main.cpp | michaeljdietz/NpcVoiceActivation | df62efc5e6ed9510e4f9423561071d7119a3a44b | [
"MIT"
] | null | null | null | skse64/nva_skse_plugin/main.cpp | michaeljdietz/NpcVoiceActivation | df62efc5e6ed9510e4f9423561071d7119a3a44b | [
"MIT"
] | null | null | null | #include "skse64/PluginAPI.h" // super
#include "skse64_common/skse_version.h" // What version of SKSE is running?
#include <shlobj.h>
#include <time.h>
#include "NpcVoiceActivation.h"
static PluginHandle g_pluginHandle = kPluginHandle_Invalid;
static SKSEPapyrusInterface * g_papyrus = NULL;
void SKSEMessageHandler(SKSEMessagingInterface::Message *);
extern "C" {
bool SKSEPlugin_Query(const SKSEInterface * skse, PluginInfo * info) { // Called by SKSE to learn about this plugin and check that it's safe to load it
gLog.OpenRelative(CSIDL_PERSONAL, "\\My Games\\Skyrim Special Edition\\SKSE\\NpcVoiceActivation.log");
gLog.SetPrintLevel(IDebugLog::kLevel_Message);
gLog.SetLogLevel(IDebugLog::kLevel_Message);
_MESSAGE("NpcVoiceActivation");
// populate info structure
info->infoVersion = PluginInfo::kInfoVersion;
info->name = "NpcVoiceActivation";
info->version = 1;
// store plugin handle so we can identify ourselves later
g_pluginHandle = skse->GetPluginHandle();
NpcVoiceActivation::RegisterHandle(&g_pluginHandle);
NpcVoiceActivation::RegisterMessagingInterface((SKSEMessagingInterface *)skse->QueryInterface(kInterface_Messaging));
if(skse->isEditor)
{
_MESSAGE("loaded in editor, marking as incompatible");
return false;
}
else if(skse->runtimeVersion != RUNTIME_VERSION_1_5_39 /*RUNTIME_VR_VERSION_1_3_64*/ )
{
_MESSAGE("unsupported runtime version %08X", skse->runtimeVersion);
return false;
}
// ### do not do anything else in this callback
// ### only fill out PluginInfo and return true/false
// supported runtime version
return true;
}
bool SKSEPlugin_Load(const SKSEInterface * skse) {
_MESSAGE("NpcVoiceActivation loaded");
g_papyrus = (SKSEPapyrusInterface *)skse->QueryInterface(kInterface_Papyrus);
bool btest = g_papyrus->Register(NpcVoiceActivation::RegisterFuncs);
if (btest) {
_MESSAGE("Register Succeeded");
}
return true;
}
}; | 31.184615 | 153 | 0.721756 | michaeljdietz |
e5961fb0ed5969839d1299b5c1204a99916bb110 | 2,874 | cpp | C++ | main.cpp | a-roy/vectype | 5b735949e7795ae7ded008d8e6b408c179a911a9 | [
"MIT"
] | null | null | null | main.cpp | a-roy/vectype | 5b735949e7795ae7ded008d8e6b408c179a911a9 | [
"MIT"
] | null | null | null | main.cpp | a-roy/vectype | 5b735949e7795ae7ded008d8e6b408c179a911a9 | [
"MIT"
] | null | null | null | #include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_IMAGE_H
#include FT_GLYPH_H
#include <cstddef>
#include <iostream>
#include <vector>
#include <stdexcept>
#include "Preprocess.hpp"
constexpr auto openSans = "../fonts/Open_Sans/OpenSans-Regular.ttf";
constexpr auto inter = "../fonts/Inter/static/Inter-Regular.ttf";
void error_callback(int error, const char* description) noexcept
{
std::cerr << "Error: " << description << std::endl;
}
void Run()
{
FT_Error error;
FT_Library library;
FT_Face face;
error = FT_Init_FreeType(&library);
if (error != FT_Err_Ok)
{
throw std::runtime_error{ "Could not initialize Freetype." };
}
error = FT_New_Face(
library,
inter,
0,
std::addressof(face));
if (error == FT_Err_Unknown_File_Format)
{
throw std::runtime_error{ "Font format is unsupported." };
}
else if (error != FT_Err_Ok)
{
throw std::runtime_error{ "Font file could not be read." };
}
std::cout << "Loaded font face " << face->family_name << std::endl << std::flush;
std::vector<vt::GlyphGrid> grids;
std::vector<float> curvesBuffer;
std::vector<std::uint16_t> gridsBuffer;
vt::ProcessGlyphs(face, grids);
vt::PackGlyphGrids(grids, 128, curvesBuffer, gridsBuffer);
glfwSetErrorCallback(error_callback);
if (!glfwInit())
{
throw std::runtime_error{ "Could not initialize GLFW." };
}
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
auto window = glfwCreateWindow(640, 480, "VecType Demo", nullptr, nullptr);
if (window == nullptr)
{
glfwTerminate();
throw std::runtime_error{ "Could not create window." };
}
glfwMakeContextCurrent(window);
gladLoadGLLoader(reinterpret_cast<GLADloadproc>(glfwGetProcAddress));
glfwSwapInterval(1);
while (!glfwWindowShouldClose(window))
{
int width, height;
glfwGetFramebufferSize(window, &width, &height);
float ratio = width / static_cast<float>(height);
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// TODO
// Set up OpenGL objects, etc.
// Render some text to the screen
// Show zooming functionality
// Integrate with Nuklear UI
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
FT_Done_Face(face);
FT_Done_FreeType(library);
}
void main()
{
try
{
Run();
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
| 23.752066 | 85 | 0.635003 | a-roy |
e5972d73b9f84337197231658d1be4fd71d2a214 | 2,680 | hpp | C++ | src/Points.hpp | sweetpony/hplotlib | 574f3bab8e86b3b91b477e81acdbc101e7a48aaf | [
"MIT"
] | null | null | null | src/Points.hpp | sweetpony/hplotlib | 574f3bab8e86b3b91b477e81acdbc101e7a48aaf | [
"MIT"
] | 31 | 2015-01-04T15:52:46.000Z | 2015-03-02T20:37:52.000Z | src/Points.hpp | sweetpony/hplotlib | 574f3bab8e86b3b91b477e81acdbc101e7a48aaf | [
"MIT"
] | null | null | null | #ifndef POINTS_H
#define POINTS_H
#include <map>
#include <vector>
#include "Drawable.hpp"
namespace hpl
{
struct SimplePoints {
SimplePoints(int n, double const* x, double const* y, bool ownsX, bool ownsY) : _n(n), _x(x), _y(y), _ownsX(ownsX), _ownsY(ownsY) {}
virtual ~SimplePoints() {
if (_ownsX) {
delete[] _x;
}
if (_ownsY) {
delete[] _y;
}
}
const int _n;
const double* _x, * _y;
const bool _ownsX, _ownsY;
};
class Points : public Drawable, private SimplePoints
{
public:
enum Symbol {
Dot,
Plus,
Cross,
Asterisk,
Diamond,
Circle,
CirclePlus,
CircleCross,
Triangle,
DownwardTriangle,
RightwardTriangle,
LeftwardTriangle,
Square,
Hourglass,
Bowtie,
VerticalBar,
HorizontalBar,
FilledDiamond,
FilledCircle,
FilledTriangle,
FilledDownwardTriangle,
FilledRightwardTriangle,
FilledLeftwardTriangle,
FilledSquare,
FilledHourglass,
FilledBowtie,
FilledVerticalBar,
FilledHorizontalBar
};
Points(int n, double const* x, double const* y, const Limits& limits, bool ownsData = false) :
Drawable(Type_Points, limits), SimplePoints(n, x, y, ownsData, ownsData), points(new SimplePoints(n, x, y, false, false)){}
virtual ~Points() {
delete points;
}
virtual inline int n() const {
return points->_n;
}
virtual inline const double* x() const {
return points->_x;
}
virtual inline const double* y() const {
return points->_y;
}
virtual inline void setColor(const Color& c) {
color = c;
changed.invoke(plotId);
}
virtual inline Color getColor() const {
return color;
}
inline void setSymbolSize(double thick) {
size = thick;
changed.invoke(plotId);
}
inline double getSymbolSize() const {
return size;
}
void setSymbol(Symbol s);
inline Symbol getSymbol() const {
return symbol;
}
//! @todo how to handle filling of symbols?
inline bool isFilledSymbol() const {
return symbol >= FilledDiamond;
}
virtual void recalculateData();
protected:
std::vector<std::pair<double, double> > getSymbolVertices() const;
void setTypeForSymbol();
SimplePoints* points;
Color color = Color(0.0f, 0.0f, 0.0f);
double size = 1.0;
Symbol symbol = Dot;
bool limitsInCalc = false;
const unsigned int maxSymbolVertices = 64;
};
}
#endif // POINTS_H
| 21.788618 | 136 | 0.589552 | sweetpony |
e5ae270e563e31731d79d73e716eca4327ecafb6 | 2,611 | cpp | C++ | external/wapopp/src/wapopp.cpp | ZabalaMariano/PISA | 344063799847e89f2f4bd7d75d606ccb95620d30 | [
"Apache-2.0"
] | null | null | null | external/wapopp/src/wapopp.cpp | ZabalaMariano/PISA | 344063799847e89f2f4bd7d75d606ccb95620d30 | [
"Apache-2.0"
] | 1 | 2019-05-05T20:53:08.000Z | 2019-05-05T20:53:08.000Z | src/wapopp.cpp | pisa-engine/wapopp | 25ff64e373bfaf51b24191cc7181b7db56119654 | [
"Apache-2.0"
] | 1 | 2021-02-27T11:46:50.000Z | 2021-02-27T11:46:50.000Z | #include <wapopp/detail.hpp>
#include <iostream>
using namespace wapopp;
template <class C, class Fn>
void append_content(nlohmann::json const &node, std::vector<Content> &contents, Fn read_content)
{
auto content = read_content(node);
if (detail::holds<C>(content)) {
contents.push_back(detail::take<C>(std::move(content)));
}
}
[[nodiscard]] auto Record::read(std::istream &is) -> Result
{
std::string line;
std::getline(is, line);
try {
nlohmann::json data = nlohmann::json::parse(line);
std::vector<Content> contents;
for (auto &&content_entry : data["contents"]) {
if (auto type_pos = content_entry.find("type"); type_pos != content_entry.end()) {
auto type = type_pos->get<std::string>();
if (type == "kicker") {
append_content<Kicker>(
content_entry, contents, detail::read_simple_content<Kicker>);
} else if (type == "title") {
append_content<Title>(
content_entry, contents, detail::read_simple_content<Title>);
} else if (type == "byline") {
append_content<Byline>(
content_entry, contents, detail::read_simple_content<Byline>);
} else if (type == "sanitized_html") {
append_content<Text>(
content_entry, contents, detail::read_simple_content<Text>);
} else if (type == "date") {
append_content<Date>(content_entry, contents, detail::read_date);
} else if (type == "author_info") {
append_content<AuthorInfo>(content_entry, contents, detail::read_author_info);
} else if (type == "image") {
append_content<Image>(content_entry, contents, detail::read_image);
}
}
}
return Record{data["id"],
detail::read_field_or<std::string>(data, "article_url", ""),
detail::read_field_or<std::string>(data, "title", ""),
detail::read_field_or<std::string>(data, "author", ""),
detail::read_field_or<std::string>(data, "type", ""),
detail::read_field_or<std::string>(data, "source", ""),
detail::read_field_or<std::uint64_t>(data, "published_date", 0u),
std::move(contents)};
} catch (nlohmann::detail::exception const& error) {
return Error{error.what(), line};
}
}
| 45.017241 | 98 | 0.540406 | ZabalaMariano |
e5ae2cb4820257ef537ec1a808c3216f172f7912 | 2,699 | cpp | C++ | isaac_variant_caller/src/lib/blt_util/vcf_record.cpp | sequencing/isaac_variant_caller | ed24e20b097ee04629f61014d3b81a6ea902c66b | [
"BSL-1.0"
] | 21 | 2015-01-09T01:11:28.000Z | 2019-09-04T03:48:21.000Z | isaac_variant_caller/src/lib/blt_util/vcf_record.cpp | sequencing/isaac_variant_caller | ed24e20b097ee04629f61014d3b81a6ea902c66b | [
"BSL-1.0"
] | 4 | 2015-07-23T09:38:39.000Z | 2018-02-01T05:37:26.000Z | isaac_variant_caller/src/lib/blt_util/vcf_record.cpp | sequencing/isaac_variant_caller | ed24e20b097ee04629f61014d3b81a6ea902c66b | [
"BSL-1.0"
] | 13 | 2015-01-29T16:41:26.000Z | 2021-06-25T02:42:32.000Z | // -*- mode: c++; indent-tabs-mode: nil; -*-
//
// Copyright (c) 2009-2013 Illumina, Inc.
//
// This software is provided under the terms and conditions of the
// Illumina Open Source Software License 1.
//
// You should have received a copy of the Illumina Open Source
// Software License 1 along with this program. If not, see
// <https://github.com/sequencing/licenses/>
//
/// \file
/// \author Chris Saunders
///
#include "blt_util/parse_util.hh"
#include "blt_util/vcf_record.hh"
#include <cassert>
#include <cctype>
#include <algorithm>
#include <iostream>
struct convert {
void operator()(char& c) const { c = toupper((unsigned char)c); }
};
static
void
stoupper(std::string& s) {
std::for_each(s.begin(), s.end(), convert());
}
bool
vcf_record::
set(const char* s) {
static const char sep('\t');
static const unsigned maxword(5);
clear();
// simple tab parse:
const char* start(s);
const char* p(start);
unsigned wordindex(0);
while (wordindex<maxword) {
if ((*p == sep) || (*p == '\n') || (*p == '\0')) {
switch (wordindex) {
case 0:
chrom=std::string(start,p-start);
break;
case 1:
pos=illumina::blt_util::parse_int(start);
assert(start==p);
break;
case 2:
// skip this field...
break;
case 3:
ref=std::string(start,p-start);
stoupper(ref);
break;
case 4:
// additional parse loop for ',' character:
{
const char* p2(start);
while (p2<=p) {
if ((*p2==',') || (p2==p)) {
alt.push_back(std::string(start,p2-start));
stoupper(alt.back());
start=p2+1;
}
p2++;
}
}
break;
default:
assert(0);
break;
}
start=p+1;
wordindex++;
}
if ((*p == '\n') || (*p == '\0')) break;
++p;
}
return (wordindex >= maxword);
}
std::ostream& operator<<(std::ostream& os, const vcf_record& vcfr) {
os << vcfr.chrom << '\t'
<< vcfr.pos << '\t'
<< '.' << '\t'
<< vcfr.ref << '\t';
const unsigned nalt(vcfr.alt.size());
for (unsigned a(0); a<nalt; ++a) {
if (a) os << ',';
os << vcfr.alt[a];
}
os << '\t'
<< '.' << '\t'
<< '.' << '\t'
<< '.' << '\t'
<< '.' << '\n';
return os;
}
| 21.766129 | 69 | 0.447203 | sequencing |
e5bd49436f9eeb15db70929ebd045e02532880b6 | 5,437 | cpp | C++ | src/opencv_bridge/shape_finder.cpp | cognitive-machines/garooda-core | 509f54ad0db7916f963418e5c5af302dbacf1147 | [
"MIT"
] | null | null | null | src/opencv_bridge/shape_finder.cpp | cognitive-machines/garooda-core | 509f54ad0db7916f963418e5c5af302dbacf1147 | [
"MIT"
] | null | null | null | src/opencv_bridge/shape_finder.cpp | cognitive-machines/garooda-core | 509f54ad0db7916f963418e5c5af302dbacf1147 | [
"MIT"
] | 1 | 2018-04-11T15:20:14.000Z | 2018-04-11T15:20:14.000Z | /*
MIT License
Copyright (c) 2018 Cognitive Machines
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 "shape_finder.hpp"
#include "../helper_macros.hpp"
#include "../utilities.hpp"
#include "geometric_transform.hpp"
using namespace std;
using namespace cv;
namespace cm {
namespace lib_bridge {
bool circle_finder( Mat & in, Mat & out,
const algo_pipeline_params & params,
computed_objects & result_obj )
{
double dp = 2.0;
double minDist = 0.0;
double cannyParam1 = 100.0;
double cannyParam2 = 100.0;
int minRadius = 0;
int maxRadius = 0;
bool iterativeFinder = false;
try
{
read_double_param("circle_finder", dp);
read_double_param("circle_finder", minDist);
read_double_param("circle_finder", cannyParam1);
read_double_param("circle_finder", cannyParam2);
read_int_param("circle_finder", minRadius);
read_int_param("circle_finder", maxRadius);
read_bool_param("circle_finder", iterativeFinder);
if(iterativeFinder == true)
{
vector<Mat> images = cm::get_geometric_tranforms(in);
for(auto &img : images)
{
circle_finder_impl(img, dp, minDist, cannyParam1, cannyParam2,
minRadius, maxRadius, false, result_obj);
}
}
else
{
circle_finder_impl(in, dp, minDist, cannyParam1, cannyParam2,
minRadius, maxRadius, true, result_obj);
}
}
catch(...)
{
return false;
}
return true;
}
bool rectangle_finder( Mat & in, Mat & out,
const algo_pipeline_params & params,
computed_objects & result_obj )
{
int threshold_step = 45;
double shape_appoximator_ratio = 0.03;
double min_contour_area = 0.001;
double max_contour_area = 0.25;
double cosine_angle = 0.4;
bool iterativeFinder = false;
try
{
read_int_param("rectangle_finder", threshold_step);
read_double_param("rectangle_finder", shape_appoximator_ratio);
read_double_param("rectangle_finder", min_contour_area);
read_double_param("rectangle_finder", max_contour_area);
read_double_param("rectangle_finder", cosine_angle);
read_bool_param("rectangle_finder", iterativeFinder);
if(iterativeFinder == true)
{
vector<Mat> images = cm::get_geometric_tranforms(in);
for(auto &img : images)
{
rectangle_finder_impl(img, threshold_step, shape_appoximator_ratio,
min_contour_area, max_contour_area,
cosine_angle, false, result_obj);
}
}
else
{
rectangle_finder_impl(in, threshold_step, shape_appoximator_ratio,
min_contour_area, max_contour_area,
cosine_angle, true, result_obj);
}
}
catch(...)
{
return false;
}
return true;
}
bool line_finder( Mat & in, Mat & out,
const algo_pipeline_params & params,
computed_objects & result_obj )
{
double rho = 0.0;
double theta = 0.0;
double threshold = 100.0;
double length_factor = 0.20;
double max_seperation = 20.0;
bool iterativeFinder = 0;
try
{
read_double_param("line_finder", rho);
read_double_param("line_finder", theta);
read_double_param("line_finder", threshold);
read_double_param("line_finder", length_factor);
read_double_param("line_finder", max_seperation);
read_bool_param("line_finder", iterativeFinder);
if(iterativeFinder == true)
{
vector<Mat> images = cm::get_geometric_tranforms(in);
for(auto &img : images)
{
line_finder_impl(img, rho, theta, threshold,
length_factor, max_seperation,
false, result_obj);
}
}
else
{
line_finder_impl(in, rho, theta, threshold,
length_factor, max_seperation,
true, result_obj);
}
}
catch(...)
{
return false;
}
return true;
}
}
}
| 30.544944 | 83 | 0.611734 | cognitive-machines |
e5c772b4f528699b418485df6a9f46d0dd0e823d | 1,540 | cpp | C++ | android-31/android/nfc/tech/NfcF.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/nfc/tech/NfcF.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/android/nfc/tech/NfcF.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../../JByteArray.hpp"
#include "../Tag.hpp"
#include "./NfcF.hpp"
namespace android::nfc::tech
{
// Fields
// QJniObject forward
NfcF::NfcF(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
android::nfc::tech::NfcF NfcF::get(android::nfc::Tag arg0)
{
return callStaticObjectMethod(
"android.nfc.tech.NfcF",
"get",
"(Landroid/nfc/Tag;)Landroid/nfc/tech/NfcF;",
arg0.object()
);
}
void NfcF::close() const
{
callMethod<void>(
"close",
"()V"
);
}
void NfcF::connect() const
{
callMethod<void>(
"connect",
"()V"
);
}
JByteArray NfcF::getManufacturer() const
{
return callObjectMethod(
"getManufacturer",
"()[B"
);
}
jint NfcF::getMaxTransceiveLength() const
{
return callMethod<jint>(
"getMaxTransceiveLength",
"()I"
);
}
JByteArray NfcF::getSystemCode() const
{
return callObjectMethod(
"getSystemCode",
"()[B"
);
}
android::nfc::Tag NfcF::getTag() const
{
return callObjectMethod(
"getTag",
"()Landroid/nfc/Tag;"
);
}
jint NfcF::getTimeout() const
{
return callMethod<jint>(
"getTimeout",
"()I"
);
}
jboolean NfcF::isConnected() const
{
return callMethod<jboolean>(
"isConnected",
"()Z"
);
}
void NfcF::setTimeout(jint arg0) const
{
callMethod<void>(
"setTimeout",
"(I)V",
arg0
);
}
JByteArray NfcF::transceive(JByteArray arg0) const
{
return callObjectMethod(
"transceive",
"([B)[B",
arg0.object<jbyteArray>()
);
}
} // namespace android::nfc::tech
| 15.714286 | 59 | 0.612987 | YJBeetle |
e5c9d0d7f99be8a66a9bb4acbad6911cc0607c83 | 14,369 | cc | C++ | src/coord/http/http_router.cc | lujingwei002/coord | cb5e5723293d8529663ca89e0c1d6b8c348fffff | [
"MIT"
] | null | null | null | src/coord/http/http_router.cc | lujingwei002/coord | cb5e5723293d8529663ca89e0c1d6b8c348fffff | [
"MIT"
] | null | null | null | src/coord/http/http_router.cc | lujingwei002/coord | cb5e5723293d8529663ca89e0c1d6b8c348fffff | [
"MIT"
] | null | null | null | #include "coord/http/http_router.h"
#include "coord/http/http_server.h"
#include "coord/http/http_request.h"
#include "coord/http/http_response.h"
#include "coord/component/script_component.h"
#include "coord/coord.h"
#include "util/os/path.h"
#include "util/date/date.h"
namespace coord {
namespace http {
CC_IMPLEMENT(HttpRouter, "coord::http::HttpRouter")
HttpRouter* newHttpRouter(Coord* coord, HttpServer* server) {
HttpRouter* httpRouter = new HttpRouter(coord, server);
return httpRouter;
}
http_router_handler::~http_router_handler() {
if(this->ref >= 0) {
luaL_unref(this->coord->Script->L, LUA_REGISTRYINDEX, this->ref);
this->ref = LUA_NOREF;
}
}
void http_router_handler::recvHttpRequest(HttpRequest* request) {
if(this->recvHttpRequestFunc != NULL){
this->recvHttpRequestFunc(request);
}
}
HttpRouter::HttpRouter(Coord* coord, HttpServer* server){
this->coord = coord;
this->server = server;
}
HttpRouter::~HttpRouter(){
}
HttpRouteNode* HttpRouter::searchNode(HttpRouteNode* root, int i, int argc, const char** argv) {
const char* word = argv[i];
if (root->path[0] == ':' && *word != 0) {
if (root->nodeArr.size() <= 0 && i >= argc - 1 && root->handler != NULL) {
return root;
}
} else if (root->path[0] == '*') {
if (root->nodeArr.size() <= 0) {
return root;
}
} else if (strcmp(root->path.c_str(), argv[i]) == 0) {
if (i >= argc - 1 && root->handler != NULL) {
return root;
}
}
if (i >= argc - 1) {
return NULL;
}
word = argv[i + 1];
HttpRouteNode* node = NULL;
auto const it = root->nodeDict.find(word);
if (it != root->nodeDict.end()) {
node = this->searchNode(it->second, i + 1, argc, argv);
if (node) {
return node;
}
}
if (root->requiredNode) {
node = this->searchNode(root->requiredNode, i + 1, argc, argv);
if (node) {
return node;
}
}
if (root->optionalNode) {
node = this->searchNode(root->optionalNode, i + 1, argc, argv);
if (node) {
return node;
}
}
return NULL;
}
HttpRouteNode* HttpRouter::searchNode(const char* method, const char* url) {
RouterMethodTree* methodTree = this->getMethodTree(method);
static thread_local int argc = 0;
static thread_local const char* argv[16];
static char buffer[1024];
strncpy(buffer, url, sizeof(buffer) - 1);
//非法的路径
if (*buffer == 0 || buffer[0] != '/') {
return NULL;
}
// /a/b拆分成a和b /a/b/拆分成a和b和空白
argv[0] = buffer + 1;
argc = 1;
for (char *c = (char*)buffer + 1; *c != 0; c++) {
if (*c == '/') {
*c = 0;
argv[argc] = c + 1;
argc++;
if (argc >= 16) {
return NULL;
}
}
}
const char* word = argv[0];
HttpRouteNode* node = NULL;
HttpRouteNode* root = methodTree->root;
auto const it = root->nodeDict.find(word);
if (it != root->nodeDict.end()) {
node = this->searchNode(it->second, 0, argc, argv);
if (node) {
return node;
}
}
if (root->requiredNode) {
node = this->searchNode(root->requiredNode, 0, argc, argv);
if (node) {
return node;
}
}
if (root->optionalNode) {
node = this->searchNode(root->optionalNode, 0, argc, argv);
if (node) {
return node;
}
}
return node;
}
http_router_handler* HttpRouter::searchHandler(const char* group, const char* url) {
HttpRouteNode* node = this->searchNode(group, url);
if (!node) {
return NULL;
}
return node->handler;
}
void HttpRouter::recvHttpRequest(HttpRequest* request) {
if (strcmp(request->Method.c_str(), "OPTIONS") == 0) {
request->GetResponse()->Allow();
return;
}
http_router_handler* handler = this->searchHandler(request->Method.c_str(), request->Path.c_str());
if(handler == NULL){
throw HttpPageNotFoundException(request->Path.c_str());
return;
}
handler->recvHttpRequest(request);
}
void HttpRouter::Trace() {
for(auto const& it : this->trees){
auto event = it.first;
auto tree = it.second;
for(auto const it1 : tree->root->nodeArr) {
this->trace(event.c_str(), it1);
}
}
}
void HttpRouter::trace(const char* event, HttpRouteNode* node) {
auto handler = node->handler;
if (handler != NULL){
uint64_t averageTime = handler->times <= 0 ? 0 : (handler->consumeTime/handler->times);
this->coord->LogDebug("[HttpRouter] %10s | %10d | %10s | %s", event, handler->times, date::FormatNano(averageTime), node->fullPath.c_str());
}
for(auto const it : node->nodeArr) {
this->trace(event, it);
}
}
bool HttpRouter::Get(const char* path, HttpRouter_RecvHttpRequest func){
http_router_handler* handler = new http_router_handler(this->coord, func);
return this->addRoute("GET", path, handler);
}
bool HttpRouter::Get(const char* path, ScriptComponent* object, int ref) {
http_router_handler* handler = new http_router_handler(this->coord, std::bind(&ScriptComponent::recvHttpRequest, object, std::placeholders::_1, ref), ref);
return this->addRoute("GET", path, handler);
}
bool HttpRouter::Post(const char* path, HttpRouter_RecvHttpRequest func){
http_router_handler* handler = new http_router_handler(this->coord, func);
return this->addRoute("POST", path, handler);
}
bool HttpRouter::Post(const char* path, ScriptComponent* object, int ref) {
http_router_handler* handler = new http_router_handler(this->coord, std::bind(&ScriptComponent::recvHttpRequest, object, std::placeholders::_1, ref), ref);
return this->addRoute("POST", path, handler);
}
bool HttpRouter::Static(const char* url, const char* dir) {
http_router_handler* handler = new http_router_handler(this->coord, std::bind(&HttpRouter::recvStaticRequest, this, std::placeholders::_1, dir));
return this->addRoute("GET", url, handler);
}
bool HttpRouter::StaticFile(const char* url, const char* path) {
http_router_handler* handler = new http_router_handler(this->coord, std::bind(&HttpRouter::recvStaticFileRequest, this, std::placeholders::_1, path));
return this->addRoute("GET", url, handler);
}
int HttpRouter::Get(lua_State* L) {
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(L,1,"coord::http::HttpRouter",0,&tolua_err) ||
!tolua_isstring(L,2,0,&tolua_err) ||
!tolua_isusertype(L,3,"coord::ScriptComponent",0,&tolua_err) ||
(!tolua_isfunction(L,4,0,&tolua_err) && !tolua_istable(L,4,0,&tolua_err)) ||
!tolua_isnoobj(L,5,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
const char* route = (const char*) tolua_tostring(L, 2, 0);
coord::ScriptComponent* object = ((coord::ScriptComponent*) tolua_tousertype(L,3,0));
if(tolua_isfunction(L,4,0,&tolua_err)) {
lua_pushvalue(L, 4);
int ref = luaL_ref(L, LUA_REGISTRYINDEX);
if (ref < 0) {
tolua_error(L, "error in function 'Get'.\nattempt to set a nil function", NULL);
return 0;
}
bool result = this->Get(route, object, ref);
if(!result) {
luaL_unref(L, LUA_REGISTRYINDEX, ref);
}
tolua_pushboolean(L, result);
} else if(tolua_istable(L,4,0,&tolua_err)) {
bool result = true;
lua_pushnil(L); /* first key */
while (lua_next(L, 4) != 0) {
static thread_local char fullRoute[128];
snprintf(fullRoute, sizeof(fullRoute), "%s.%s", route, lua_tostring(L, -2));
char* c = NULL;
for(char* i = fullRoute; *i != 0; i++) {
if(*i == '.') {
c = i + 1;
} else if (c != NULL) {
*i = tolower(*i);
}
}
/* uses 'key' (at index -2) and 'value' (at index -1) */
if(tolua_isfunction(L,-1,0,&tolua_err)) {
int ref = luaL_ref(L, LUA_REGISTRYINDEX);
if (ref < 0) {
return 0;
}
bool result = this->Get(fullRoute, object, ref);
if(!result) {
luaL_unref(L, LUA_REGISTRYINDEX, ref);
}
} else {
/* removes 'value'; keeps 'key' for next iteration */
lua_pop(L, 1);
}
}
tolua_pushboolean(L, result);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(L,"#ferror in function 'Get'.",&tolua_err);
return 0;
#endif
}
int HttpRouter::Post(lua_State* L) {
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(L,1,"coord::http::HttpRouter",0,&tolua_err) ||
!tolua_isstring(L,2,0,&tolua_err) ||
!tolua_isusertype(L,3,"coord::ScriptComponent",0,&tolua_err) ||
(!tolua_isfunction(L,4,0,&tolua_err) && !tolua_istable(L,4,0,&tolua_err)) ||
!tolua_isnoobj(L,5,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
const char* route = (const char*) tolua_tostring(L, 2, 0);
coord::ScriptComponent* object = ((coord::ScriptComponent*) tolua_tousertype(L,3,0));
if(tolua_isfunction(L,4,0,&tolua_err)) {
lua_pushvalue(L, 4);
int ref = luaL_ref(L, LUA_REGISTRYINDEX);
if (ref < 0) {
tolua_error(L, "error in function 'Post'.\nattempt to set a nil function", NULL);
return 0;
}
bool result = this->Post(route, object, ref);
if(!result) {
luaL_unref(L, LUA_REGISTRYINDEX, ref);
}
tolua_pushboolean(L, result);
} else if(tolua_istable(L,4,0,&tolua_err)) {
bool result = true;
lua_pushnil(L); /* first key */
while (lua_next(L, 4) != 0) {
static thread_local char fullRoute[128];
snprintf(fullRoute, sizeof(fullRoute), "%s.%s", route, lua_tostring(L, -2));
char* c = NULL;
for(char* i = fullRoute; *i != 0; i++) {
if(*i == '.') {
c = i + 1;
} else if (c != NULL) {
*i = tolower(*i);
}
}
/* uses 'key' (at index -2) and 'value' (at index -1) */
if(tolua_isfunction(L,-1,0,&tolua_err)) {
int ref = luaL_ref(L, LUA_REGISTRYINDEX);
if (ref < 0) {
return 0;
}
bool result = this->Post(fullRoute, object, ref);
if(!result) {
luaL_unref(L, LUA_REGISTRYINDEX, ref);
}
} else {
/* removes 'value'; keeps 'key' for next iteration */
lua_pop(L, 1);
}
}
tolua_pushboolean(L, result);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(L,"#ferror in function 'Post'.",&tolua_err);
return 0;
#endif
}
void HttpRouter::recvStaticRequest(HttpRequest* request, const char* dir) {
std::string path = dir;
path = os::path::Join(path, request->Path);
path = os::path::Join(this->server->config.AssetDir, path);
request->GetResponse()->File(path.c_str());
}
void HttpRouter::recvStaticFileRequest(HttpRequest* request, const char* dir) {
std::string path = dir;
path = os::path::Join(this->server->config.AssetDir, path);
request->GetResponse()->File(path.c_str());
}
bool HttpRouter::addRoute(const char* method, const char* path, http_router_handler* handler) {
RouterMethodTree* methodTree = this->getMethodTree(method);
this->coord->coreLogDebug("[HttpRouter] addRoute, method=%s, path=%s", method, path);
HttpRouteNode* node = methodTree->root;
int pathLen = strlen(path);
if(pathLen == 0){
return false;
} else if(path[0] != '/') {
return false;
} else {
int wordStart = 1;
int wordEnd = wordStart;
int i = wordStart;
while(true) {
for(i = wordStart; i < pathLen; i++){
if(path[i] == '/') {
wordEnd = i - 1;
break;
}
}
if (i >= pathLen){
wordEnd = i - 1;
}
std::string word(path + wordStart, wordEnd - wordStart + 1);
auto it = node->nodeDict.find(word);
if (it == node->nodeDict.end()){
HttpRouteNode* newNode = new HttpRouteNode(word.c_str());
node->nodeDict[word] = newNode;
node->nodeArr.push_back(newNode);
if (word.size() > 0 && word[0] == ':') {
node->requiredNode = newNode;
} else if (word.size() > 0 && word[0] == '*') {
node->optionalNode = newNode;
}
node = newNode;
} else {
node = it->second;
}
if (i >= pathLen){
break;
}
wordStart = i + 1;
wordEnd = wordStart;
}
}
if(handler != NULL) {
if(node->handler != NULL){
return false;
}
node->handler = handler;
node->fullPath = path;
} else {
node->handler = NULL;
}
//this->coord->coreLogDebug("bbb %s %s", node->path.c_str(), node->fullPath.c_str());
return true;
}
RouterMethodTree* HttpRouter::getMethodTree(const char* method) {
const auto it = this->trees.find(method);
if (it == this->trees.end()){
RouterMethodTree* methodTree = new RouterMethodTree();
this->trees[method] = methodTree;
return methodTree;
} else {
return it->second;
}
}
}
}
| 33.57243 | 159 | 0.540747 | lujingwei002 |
e5ca5dbf8e25ffc1053c221303b79c3636c7313f | 7,970 | cpp | C++ | data/160.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | data/160.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | data/160.cpp | TianyiChen/rdcpp-data | 75c6868c876511e3ce143fdc3c08ddd74c7aa4ea | [
"MIT"
] | null | null | null | int bx,ch, BX2,
/*l*///dW
uxB90 ,/*N*/Sw//2zMl
,//uT
qsaYA5, Hf ,/*F*/vH ,GhVn
,o4XZE
, KFn
//F
,/*S7o*/rar,Kr , zO,
Vnv
,
o0RIc/**/
, DCGX ,
fK ,
K, fFq, Z0w
,
de, Eagnj ,du
,q1, Cv ,xzUt ,ls ,
l64h
,nYEv , ia7
, KF
, r ,V ,
b, RDcV ,
nU8; void f_f0 ()
{ int
Qco; volatile int f2w , YS4,vfvy
,
/*g*/Zm
,sRc ,aIP;
return ;/*db*/return
;
return
;Qco=
aIP+
f2w+//Z
YS4
+vfvy/*C*/+ Zm+sRc ;
return
; }void//9
f_f1(){{/*f*/volatile int d9
,
Tru ,G1iCu,eG
,
VJH, vQWj1 ,lKBJ ,cKFs5z5
//1Z
,
Y , jV , pqwp; if (
true )
nU8=pqwp + d9+Tru+
G1iCu
+ eG ; else{ ;
{
return
;//5d
{ {
} }
}}
{{ if(
true){ } else {} }for (int
/*0*/i=1;
i</*Hi*/ 1 ;++i ) if(true ){ if(true) {{for
(int i=1 ;i< 2 ;++i ) for (int i=1; i< 3;++i )
{ volatile int
OLn;bx = OLn;}//LZObCt
}}else if(true)return
; else/*KZ*/{}
{ {}
{}}} else{{return ;
} /*EW*/ }for
(int i=1 ; //
i<4 ;++i/*F*///Gt3
)
{
for
(int i=1
;
i<
5;++i
) return
;{{ { {}//eKNj
} } } return ;
}}{volatile int ZX
,P , KBRTAMh, zd
,yo5i ;
return ;;
ch//o
=
yo5i
+ZX +//p8K
P
+
KBRTAMh +zd ;
} BX2
= VJH+vQWj1+lKBJ+cKFs5z5+Y
+
jV
;/*77S*/
} { ; {//
int rF4/*yJUK2*/ ; volatile int pq,/*Ys*/mm/*NBxs*/ , FS
,/*Bmgd*/Qk
,
C3I /*rsbwN*/,Jb//vW
/*h4*/
,JMn //6BEy
,
LhwK
;rF4= LhwK +pq+mm; uxB90=FS+ /*F3i*/Qk +//W6GCrR
C3I
+ Jb + JMn//tfjh
;{ volatile int/*4l*/ Zq0p ,s;return
;
Sw =s + Zq0p;
}
};return ;}for(int i=1;i<6;++i
) {
for (int i=1; i<7 ;++i) if
(true/*D3E*/)
;else
{ int yJx
//9
;volatile int VPLr1 ,
/**/ENA, eXebYm ,el ,eFQ7,
RK, tuvUFv
, NQ4,
Mm6m
, m8Oy ,nIST, RHZE
,
uwH5, Yit4
, R
/*DxoxJw*/;
qsaYA5= R//G
+/**///a
VPLr1 + ENA + eXebYm
/*6Z*/
+ el; { return ;
if (true )
{ }else { }
}
return ;//kk
for(int
i=1; i< //BGI
8;++i//9v8
)if( true
)return ;
else { volatile int Z,
gwR ,
Oa ; Hf =/*i*/Oa
+
Z+ gwR//jOP
;{ }}; for(int i=1
;i<
9;++i
) if( /*5*/true//8Vs6
) ;else
if( true)
if
( true )
yJx = /*x*/eFQ7 + RK+ tuvUFv +NQ4+
Mm6m
+m8Oy; else{
{/*rlnB*/
{ { }}
}{{ ; } }if (//EJ
true
)//WI
{{/*3mcyR*/
for (int
i=1 ; i< 10;++i )for
(int
i=1
;
i<11 ;++i/*8k*/); } if(
true)
{}else
;}else for
(int i=1 ; i<
12;++i
)
{volatile int Vz, bf ;vH =bf +
Vz; //
{ return ; } } { } } else if/*XfQ*/(/*s*//*uie*/true ){
{}{
{ }return ;
}{{ return//0y0l
;
{
}}{
for(int i=1;
i<13;++i
){ }
//zA
}}if(
true/*D*/ ) return ;
else{/*n*/ }} //Vw
else if
( true )
for (int i=1
;i< 14
;++i ) if(true
)if ( true )
{ {/*0*/} } else
{int Mny
;
volatile int
S,
X4 ; { int PN
;//A
volatile int//sk
Ie
,RGlr
;PN
=RGlr+
Ie
;} /*RAk*/
for(int
i=1
;
/*gH*/i<
/*O*/15
;++i )for(int
i=1; i<16;++i
) for (int i=1 /*OJOf*/;i<17;++i)if ( true
){
{
return ;//
{
} }return ; } else
{
volatile int QDQ2
; //H
GhVn=
QDQ2 ; }{
{ }
}Mny =X4/*Ps6*/+
S
; }
else for
(int i=1 ;
i<18
;++i){volatile int fIgla//E5
,E; {return ;
{} } ;o4XZE
=E
+ fIgla ;}
else/**/
KFn =nIST+ RHZE+ uwH5 +
//D4K6
Yit4 //nRci
;
}return
;{
return/*p*/
;if/*dI9*/ (true){
{ /**/}
{}
} else { for(int
i=1
;i< 19 ;++i )for (int i=1
;i<20 ;++i ){{}
if(
true)
if(true)/*fhbo*/return ;else ; else {} }/*l2J*/if//UQI
(true)
{
{//I
} } //v3
else if
(true) {for(int /*IJI*/i=1; i<21
;++i
) if(true
) {} else
//
{}
{ { /*u*/}//Umn
; }}else { /*jOZ*/{for (int i=1
/*p*/;
i< //
22//9
;++i /**/)//p
{{ } } }
}}{ {
for
(int
i=1 ;i< 23 ;++i
)
{
}{
}if (true//
){
} else ; if ( true
)
if//gP
( true ); else{ }else { ;
/*cB*/} } { ; }
}/*cVeo*/} {for (int
i=1 ;i<24 ;++i){;/**/for(int i=1 ;i<25;++i
) ;//Fz
} {
volatile int
kA
,
sfi7l ;rar//N
= sfi7l + kA; ; } {volatile int hIZ ,yBLt2
//
;Kr//cP
=yBLt2/*nU*/ +
hIZ ;
{ {
//xV
} } }
} }
/*LO*/{ {{ {volatile int Oq//
;
//DR
{}//DDvs
zO= Oq ;
}
} {
for (int i=1; i</*XkO*/ 26;++i ) //
{ int G
;
volatile int ej ,
J
; if
(true //GAU
)
return ;else G
=
J +//4
ej ; } }
;
}
{ volatile int QfYkM , Dqr6E6
,
prkD ;
Vnv//A
=
prkD
//4gT
+ QfYkM+
Dqr6E6;{//zuVV
{
{volatile int
yD, C ; o0RIc =C
+ yD
;
}} }{
if//
( true
)//csyP
{ volatile int
bQQ/*h*/; DCGX = bQQ
;//
}else
; }{return ; {}} //
}//0aCm
for
(int
i=1
;/*X*/
i<27;++i)
{ int
//LEPZ
Ao
;volatile int xFQCM//Hj
,
U //Q
/*m*/,NZh /*t*/,
yl;
Ao =
yl +xFQCM+ U/*aT7P*/+
NZh ;
{
volatile int Fv ,/*Bxk*/d0p;
fK=d0p +
Fv;{{/*IgT*/ }} }
}
}{int etom ;
volatile int yVLZ,G0
,//JmeW
O3 , UV ; etom /*oork*/= UV + yVLZ+ G0+O3 ; if (true
)
{; /*D3aWax*/{{return ; /*5Z*/ for(int i=1//
;i<
28;++i) {
volatile int NRX
; K= NRX ;
} }
}} /*nNy*/else{ volatile int aTFOC
,pr1 , Y1l,VE,zJt,
lO/*y4*/,
srGh //4n
, X67 ,i7y3 , xwm, HxpT ;{int
XuW //y
;
volatile int N ,i ,
rQv1, h/*o*/ ;
{//d
int DQ ;//HJs
volatile int bSIJ;
DQ
=bSIJ
;
{
} } XuW= h + N +/*k*/i + //Rj
rQv1 ;{ if(
true
)if
( true
) //
{
} else
for (int i=1;i<29
;++i
){}else
;
/*S*/}
} fFq =
HxpT
+aTFOC
+pr1 +Y1l;{
{ {{/*lk*/{ } { }}} }
} if( true
)
for(int i=1 ;/*Fae7*/i<30;++i
)if
( true
)
if
( true)if ( true)//p
Z0w
=/**/VE+zJt+
lO
+ srGh; else {;if ( true
){ {
}} else for (int i=1//uji
; i</*kn4*/ 31
;++i) {
{//S
{ }for(int /*6v*/i=1;i<
32;++i ); {}
}
/*yN*/{
}{{}
} }//Rg
}/*auuj*/else
; else de
=X67+/*1dDM*/ i7y3
+xwm//3d
;else
{int PPE8;
volatile int v ,
ro, JvqM ,gvL,oEHzh, Wc;
for//
(int i=1
;i< 33 ;++i
)PPE8=
Wc+v
+ro+ JvqM
;
{ {}
for
(int i=1;i< 34 /*HMh*/;++i ){} } Eagnj
=
gvL
//7
+oEHzh;{/*h1jr*/
{ {
} {
} } ; { }}
} return
;
}
{if
(
true);else ; {{
volatile int
BHwV , Yr;
du= Yr+BHwV; }/*8*/; {}}
}}
return ; }/*VOf*/ void f_f2 () //J75R
{
for (int //y
i=1 ; i< 35
;++i)return
;return ;for (int i=1 ; i<
36;++i
) { for (int
i=1;i<//
37;++i ) {{/*i*/{
}
} if(true) ;
else{return ; } }; {for/*1NU1*/(int
i=1 ;i< 38;++i)for (int
i=1
;i<39
;++i){
{{}
}{{ } }
{for
(int
i=1
;
i<40//sVg
;++i)
return ;{} } { ; }}{ ;
} {
{ }
} {{
volatile int ozeEA,k8t
;{ } if
(
true)for(int i=1
/*zg*/;
i<
41/*ur*/ ;++i){ }
else
q1/*Nl*/ = k8t+ ozeEA
;{} }
}
} {return ; {//8
{ {}}
{
} }
}
//hz
} ;
for (int
i=1 ; i<
42;++i ){
{ {/**/ if( true )return ;else { }
; }
{ if//Ks
(/*L2*/true ) {volatile int HI7h ;
Cv//
= HI7h; }
else
if
(true ) if(true/*PjiL*/)
{}else {return ; {
}
}else
{//a9
;}} };
{volatile int
WGx,
nPF ,A6 ;xzUt=//
A6
/*wE*/+
WGx
+
/*r1*/nPF;{ volatile int
Ne ,/*jTb*/d
;{}
ls= d+Ne;
}
if (/*41Rb*/true) {
volatile int Kx //h
, V1Z
,bW;l64h =//t8OU
bW+ Kx
+V1Z; { volatile int mjz,Yz6
;{ } {} //CB2CR
{ volatile int Y1z
; nYEv
= Y1z;/*OeJ*/}/**/for (int
i=1
;
i< 43
;++i) return
; ia7 =Yz6
+mjz
;
}
//rR
;}else
return ;}
return
; { int pL3;
volatile int dMM, oQu0
,
sq
//bU
, sO
;
{ int /*R*/ ElRd ; volatile int
PG,C9Ek,lpb, bx7, q4Kd7; for(int i=1;i<44 ;++i
)KF=q4Kd7 +PG;
return ; ElRd= C9Ek + lpb/*Uf*/+ bx7;} return
/*jQ*/ ;{ {}; }
pL3 =
sO+
dMM
+
oQu0
+sq;
{return ;
}} {
volatile int
Hjb5, YZ
,rR,//
yrKr,u27UQY4;;if//E4
( true
)r=u27UQY4
+Hjb5 +YZ
+/**/rR + yrKr ; else ;//BZ
{return ; }}
}
return ; }
int main//zoq
()
{int KH;volatile int fS,sZD ,
kJea7
,wLN
,
hzm/*3X*/
,USLHj
,
dOX0lb;KH
=
dOX0lb
+
fS +sZD+kJea7
+wLN +hzm
+//8BWB
USLHj ; {
volatile int oBG2,
fc,v7WJtA//V
/*vBQ*/,Z9T ,ij;//cBd
;{volatile int N4cN , ngiOC/*yxjV*/,i3I, nUE
;
for (int i=1;
i< 45 ;++i )V=nUE
+ N4cN+ngiOC+
i3I
; { volatile int/**/ Juf , /*dD*/
Pj ,DzWR, BxelU
;for
(int i=1//Co4Ad
;
i< 46;++i ) b=BxelU+Juf+Pj //
+/*MW*/ DzWR
;/*EE3*/
}if( true
){
;} else{ ;;//JkUT
}
} for
(int i=1
; i<47 ;++i )RDcV = ij
/*S*//*sCf*/+//6
oBG2+fc+
v7WJtA+Z9T ;
;}
;
return
2016438834
; }
/*6*/ | 10.584329 | 61 | 0.451945 | TianyiChen |
e5d0dded93d29a397065b6a49c30a50f7ae2bd26 | 3,488 | cpp | C++ | Basic4GL/Basic4GLSyntaxHighlighter.cpp | basic4gl-guy/basic4gl | 5d4da444d36cdd5e020062adb02373e3efb21303 | [
"BSD-3-Clause"
] | 1 | 2020-01-14T11:25:00.000Z | 2020-01-14T11:25:00.000Z | Basic4GL/Basic4GLSyntaxHighlighter.cpp | basic4gl-guy/basic4gl | 5d4da444d36cdd5e020062adb02373e3efb21303 | [
"BSD-3-Clause"
] | null | null | null | Basic4GL/Basic4GLSyntaxHighlighter.cpp | basic4gl-guy/basic4gl | 5d4da444d36cdd5e020062adb02373e3efb21303 | [
"BSD-3-Clause"
] | null | null | null | #include "Basic4GLSyntaxHighlighter.h"
#include "basic4glMisc.h"
Basic4GLSyntaxHighlighter::Basic4GLSyntaxHighlighter(QTextDocument* parent, TomBasicCompiler& compiler)
: QSyntaxHighlighter(parent), compiler(compiler)
{
// Setup formats
defaultFormat.setForeground(QBrush(0x000080));
keywordFormat.setForeground(Qt::blue);
functionFormat.setForeground(Qt::red);
constantFormat.setForeground(defaultFormat.foreground());
constantFormat.setFontWeight(75); // Bold??
numberFormat.setForeground(defaultFormat.foreground());
numberFormat.setFontWeight(75);
stringFormat.setForeground(Qt::darkGreen);
commentFormat.setForeground(QBrush(0x657CA7));
commentFormat.setFontItalic(true);
includeFormat.setForeground(defaultFormat.foreground());
includeFormat.setBackground(QBrush(0xffffd0));
hyperlinkFormat.setBackground(includeFormat.background());
hyperlinkFormat.setForeground(Qt::blue);
hyperlinkFormat.setUnderlineStyle(QTextCharFormat::SingleUnderline);
}
void Basic4GLSyntaxHighlighter::highlightBlock(const QString& text)
{
// Include special case
if (text.left(8).toLower() == "include ") {
setFormat(0, 8, includeFormat);
setFormat(8, text.length() - 8, hyperlinkFormat);
return;
}
if (text.left(13).toLower() == "includeblock ")
{
setFormat(0, 13, includeFormat);
setFormat(13, text.length() - 13, hyperlinkFormat);
return;
}
// Break line into tokens
int i = 0;
while (i < text.length()) {
// Skip whitespace
while (i < text.length() && text[i] <= ' ')
i++;
if (i < text.length()) {
// Identify basic token type
QChar c = text[i].toLower();
int left = i;
int style;
if (c.isLetter() || c == '_')
style = 1; // 1 = keyword
else if (c.isDigit() || c == '.')
style = 2; // 2 = Number
else if (c == '"')
style = 3; // 3 = String
else if (c == '\'')
style = 4; // 4 = Comment
else
style = 5; // 5 = Symbol
i++;
bool done = false;
while (i < text.length() && !done) {
// Look for end of token
c = text[i].toLower();
switch (style) {
case 1:
if (c == '$' || c == '%' || c == '#') {
i++;
done = true;
}
else
done = !(c.isLetterOrNumber() || c == '_');
break;
case 2:
done = !(c.isNumber() || c == '.');
break;
case 3:
done = c == '"';
if (done)
i++;
break;
case 4:
done = false;
break;
case 5:
done = true;
};
if (!done)
i++;
}
QString token = text.mid(left, i - left);
std::string tokenStr = CppString(token.toLower());
// Determine text format
QTextCharFormat* format = &defaultFormat;
switch (style)
{
case 1:
if (compiler.IsReservedWord(tokenStr) || compiler.IsOperator(tokenStr))
{
format = &keywordFormat;
}
else if (compiler.IsFunction(tokenStr))
{
format = &functionFormat;
}
else if (compiler.IsConstant(tokenStr))
{
format = &constantFormat;
}
break;
case 2:
format = &numberFormat;
break;
case 3:
format = &stringFormat;
break;
case 4:
format = &commentFormat;
break;
case 5:
if (compiler.IsOperator(tokenStr))
{
format = &keywordFormat;
}
break;
}
// Apply format
setFormat(left, i - left, *format);
}
}
// TODO: Breakpoint styling??
}
| 24.055172 | 104 | 0.590023 | basic4gl-guy |
e5d2656845eaec6f883ac4f3e23c2e8b787d79ad | 817 | cpp | C++ | .LHP/.Lop12/.HSG/.A.Thuc/TPHCM - 09-11-2020/A. Find the Vertex/main.cpp | sxweetlollipop2912/MaCode | 661d77a2096e4d772fda2b6a7f80c84113b2cde9 | [
"MIT"
] | null | null | null | .LHP/.Lop12/.HSG/.A.Thuc/TPHCM - 09-11-2020/A. Find the Vertex/main.cpp | sxweetlollipop2912/MaCode | 661d77a2096e4d772fda2b6a7f80c84113b2cde9 | [
"MIT"
] | null | null | null | .LHP/.Lop12/.HSG/.A.Thuc/TPHCM - 09-11-2020/A. Find the Vertex/main.cpp | sxweetlollipop2912/MaCode | 661d77a2096e4d772fda2b6a7f80c84113b2cde9 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#define maxN 500001
typedef long maxn;
maxn m, n;
int d[maxN];
std::vector <maxn> ad[maxN];
void Prepare() {
std::cin >> n >> m;
for(maxn i = 0; i < n; i++) std::cin >> d[i];
for(maxn i = 0; i < m; i++) {
maxn u, v; std::cin >> u >> v;
--u, --v;
ad[u].push_back(v);
ad[v].push_back(u);
}
}
maxn Process() {
for(maxn u = 0, i; u < n; u++) {
if (d[u] != 0) continue;
for(i = 0; i < ad[u].size(); i++) {
maxn v = ad[u][i];
if (d[v] != 1) break;
}
if (i == ad[u].size()) return u;
}
return 0;
}
int main() {
std::ios_base::sync_with_stdio(0);
std::cin.tie(0);
Prepare();
std::cout << Process() + 1;
}
| 17.020833 | 49 | 0.457772 | sxweetlollipop2912 |
e5d2ba6fef35a74eb25cef8968b3b95ff8736d35 | 9,743 | cpp | C++ | src/core/WidgetContainer.cpp | Knobin/ptk | 1ea55b638d7240679eced0e165ab78a8f5d2278b | [
"MIT"
] | null | null | null | src/core/WidgetContainer.cpp | Knobin/ptk | 1ea55b638d7240679eced0e165ab78a8f5d2278b | [
"MIT"
] | null | null | null | src/core/WidgetContainer.cpp | Knobin/ptk | 1ea55b638d7240679eced0e165ab78a8f5d2278b | [
"MIT"
] | null | null | null | //
// core/WidgetContainer.cpp
// pTK
//
// Created by Robin Gustafsson on 2019-11-18.
//
// pTK Headers
#include "ptk/core/WidgetContainer.hpp"
namespace pTK
{
WidgetContainer::WidgetContainer()
: IterableSequence<Ref<Widget>>(), Widget()
{
setSizePolicy(SizePolicy::Type::Expanding);
initCallbacks();
}
WidgetContainer::~WidgetContainer()
{
for (auto& item : *this)
item->setParent(nullptr);
}
void WidgetContainer::add(const Ref<Widget>& widget)
{
if (std::find(cbegin(), cend(), widget) == cend())
{
container().push_back(widget);
widget->setParent(this);
onAdd(widget);
draw();
}
}
void WidgetContainer::remove(const Ref<Widget>& widget)
{
auto it = std::find(cbegin(), cend(), widget);
if (it != cend())
{
widget->setParent(nullptr);
onRemove(widget);
container().erase(it);
draw();
}
}
void WidgetContainer::setPosHint(const Point& pos)
{
const Point deltaPos{pos - getPosition()};
for (auto& item : *this)
{
Point wPos{item->getPosition()};
wPos += deltaPos;
item->setPosHint(wPos);
}
Widget::setPosHint(pos);
}
void WidgetContainer::onDraw(SkCanvas* canvas)
{
PTK_ASSERT(canvas, "Canvas is undefined");
drawBackground(canvas);
for (auto& item : *this)
item->onDraw(canvas);
}
bool WidgetContainer::updateChild(Widget* widget)
{
if (!m_busy)
{
m_busy = true;
WidgetContainer::const_iterator it{std::find_if(cbegin(), cend(), [&](WidgetContainer::const_reference item) {
return item.get() == widget;
})};
if (it != cend())
{
onChildUpdate(static_cast<size_type>(it - cbegin()));
draw();
m_busy = false;
return true;
}
}
return false;
}
bool WidgetContainer::drawChild(Widget* widget)
{
if (!m_busy)
{
m_busy = true;
WidgetContainer::const_iterator it{std::find_if(cbegin(), cend(), [&](WidgetContainer::const_reference item) {
return item.get() == widget;
})};
if (it != cend())
{
onChildDraw(static_cast<size_type>(it - cbegin()));
draw();
m_busy = false;
return true;
}
}
return false;
}
void WidgetContainer::onClickCallback(const ClickEvent& evt)
{
Widget *lastClicked{m_lastClickedWidget};
bool found{false};
const Point& pos{evt.pos};
for (auto& item : *this)
{
const Point startPos{item->getPosition()};
const Size wSize{item->getSize()};
const Point endPos{AddWithoutOverflow(startPos.x, static_cast<Point::value_type>(wSize.width)),
AddWithoutOverflow(startPos.y, static_cast<Point::value_type>(wSize.height))};
if ((startPos.x <= pos.x) && (endPos.x >= pos.x))
{
if ((startPos.y <= pos.y) && (endPos.y >= pos.y))
{
Widget* temp{item.get()}; // Iterator might change, when passing the event.
item->triggerEvent<ClickEvent>(evt);
m_lastClickedWidget = temp;
found = true;
}
}
}
if (lastClicked != nullptr && (lastClicked != m_lastClickedWidget || !found))
{
LeaveClickEvent lcEvent{evt.button, evt.pos};
lastClicked->triggerEvent<LeaveClickEvent>(lcEvent);
}
if (!found)
m_lastClickedWidget = nullptr;
}
void WidgetContainer::onReleaseCallback(const ReleaseEvent& evt)
{
if (m_lastClickedWidget != nullptr)
m_lastClickedWidget->triggerEvent<ReleaseEvent>(evt);
}
void WidgetContainer::onKeyCallback(const KeyEvent& evt)
{
if (m_lastClickedWidget != nullptr)
m_lastClickedWidget->triggerEvent<KeyEvent>(evt);
}
void WidgetContainer::onInputCallback(const InputEvent& evt)
{
if (m_lastClickedWidget != nullptr)
m_lastClickedWidget->triggerEvent<InputEvent>(evt);
}
void WidgetContainer::onHoverCallback(const MotionEvent& evt)
{
const Point& pos{evt.pos};
for (auto& it : *this)
{
const Point startPos{it->getPosition()};
const Size wSize{it->getSize()};
const Point endPos{AddWithoutOverflow(startPos.x, static_cast<Point::value_type>(wSize.width)),
AddWithoutOverflow(startPos.y, static_cast<Point::value_type>(wSize.height))};
if ((startPos.x <= pos.x) && (endPos.x >= pos.x))
{
if ((startPos.y <= pos.y) && (endPos.y >= pos.y))
{
// Send Leave Event.
if (m_currentHoverWidget != it.get() || m_currentHoverWidget == nullptr)
{
Widget* temp{it.get()}; // Iterator might change, when passing the event.
if (m_currentHoverWidget != nullptr)
{
LeaveEvent lEvent{evt.pos};
m_currentHoverWidget->triggerEvent<LeaveEvent>(lEvent);
}
// New current hovered Widget.
m_currentHoverWidget = temp;
// Fire Enter event on this and on to child.
EnterEvent entEvent{evt.pos};
triggerEvent<EnterEvent>(entEvent);
}
m_currentHoverWidget->triggerEvent<MotionEvent>(evt);
return;
}
}
}
if (m_currentHoverWidget != nullptr)
{
LeaveEvent lEvent{evt.pos};
m_currentHoverWidget->triggerEvent<LeaveEvent>(lEvent);
}
// New current hovered Widget.
m_currentHoverWidget = nullptr;
}
void WidgetContainer::onEnterCallback(const EnterEvent& evt)
{
if (m_currentHoverWidget != nullptr)
m_currentHoverWidget->triggerEvent<EnterEvent>(evt);
}
void WidgetContainer::onLeaveCallback(const LeaveEvent& evt)
{
if (m_currentHoverWidget != nullptr)
{
m_currentHoverWidget->triggerEvent<LeaveEvent>(evt);
// Reset current hovered Widget.
m_currentHoverWidget = nullptr;
}
}
void WidgetContainer::onScrollCallback(const ScrollEvent& evt)
{
if (m_currentHoverWidget != nullptr)
m_currentHoverWidget->triggerEvent<ScrollEvent>(evt);
}
void WidgetContainer::setBackground(const Color& color)
{
m_background = color;
}
const Color& WidgetContainer::getBackground() const
{
return m_background;
}
Widget *WidgetContainer::getSelectedWidget() const
{
return m_lastClickedWidget;
}
bool WidgetContainer::busy() const
{
return m_busy;
}
void WidgetContainer::drawBackground(SkCanvas *canvas) const
{
PTK_ASSERT(canvas, "Canvas is undefined");
// Set Size and Point
const SkPoint pos{convertToSkPoint(getPosition())};
SkPoint size{convertToSkPoint(getSize())};
size += pos; // skia needs the size to be pos+size.
// Set Color
SkPaint paint;
paint.setAntiAlias(true);
paint.setARGB(m_background.a, m_background.r, m_background.g, m_background.b);
// Draw Rect
SkRect rect{};
rect.set(pos, size);
paint.setStyle(SkPaint::kStrokeAndFill_Style);
canvas->drawRoundRect(rect, 0, 0, paint);
}
void WidgetContainer::initCallbacks()
{
/*onKey([container = this](Event::Type type, KeyCode keycode){
if (auto widget = container->m_currentHoverWidget)
widget->handleKeyEvent(type, keycode);
return false; // Do not remove callback, ever.
});*/
addListener<KeyEvent>([&](const KeyEvent& evt) { onKeyCallback(evt); return false; });
addListener<InputEvent>([&](const InputEvent& evt) { onInputCallback(evt); return false; });
addListener<MotionEvent>([&](const MotionEvent& evt) { onHoverCallback(evt); return false; });
addListener<EnterEvent>([&](const EnterEvent& evt) { onEnterCallback(evt); return false; });
addListener<LeaveEvent>([&](const LeaveEvent& evt) { onLeaveCallback(evt); return false; });
// addListener<LeaveClickEvent>([&](const LeaveClickEvent& evt) { onLeaveClickEvent(evt); return false; });
addListener<ScrollEvent>([&](const ScrollEvent& evt) { onScrollCallback(evt); return false; });
addListener<ClickEvent>([&](const ClickEvent& evt) { onClickCallback(evt); return false; });
addListener<ReleaseEvent>([&](const ReleaseEvent& evt) { onReleaseCallback(evt); return false; });
addListener<LeaveClickEvent>([container = this](const LeaveClickEvent& evt){
if (container->m_lastClickedWidget != nullptr)
{
container->m_lastClickedWidget->triggerEvent<LeaveClickEvent>(evt);
container->m_lastClickedWidget = nullptr;
}
return false;
});
}
} // namespace pTK
| 31.327974 | 122 | 0.552089 | Knobin |
e5ddb7c8304e14f6a1444e747cc44b9e3245a2f9 | 14,503 | cpp | C++ | source code/dvcc/v1.4.2.2/toolpannel/romcheck.cpp | HarleyEhrich/DvccSimulationEnvironment | fdb082eb52c18a95015fc12058824345875cf038 | [
"Apache-2.0"
] | null | null | null | source code/dvcc/v1.4.2.2/toolpannel/romcheck.cpp | HarleyEhrich/DvccSimulationEnvironment | fdb082eb52c18a95015fc12058824345875cf038 | [
"Apache-2.0"
] | null | null | null | source code/dvcc/v1.4.2.2/toolpannel/romcheck.cpp | HarleyEhrich/DvccSimulationEnvironment | fdb082eb52c18a95015fc12058824345875cf038 | [
"Apache-2.0"
] | null | null | null | #include "romcheck.h"
#include "ui_romcheck.h"
ROMCheck::ROMCheck(QWidget *parent,systemDataSet* data) :
QWidget(parent),
ui(new Ui::ROMCheck)
{
ui->setupUi(this);
this->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
//绑定主窗口数据集
this->data=data;
this->matchPattrn=new QRegularExpression(("[0-9A-Fa-f]{6,6}"));
//设置行数
this->ui->ROMTable->setRowCount(this->data->rom_row_size);
//设置拉伸适应
ui->ROMTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
this->on_freshRom_clicked();
}
ROMCheck::~ROMCheck()
{
delete ui;
}
///数据刷新接口
bool ROMCheck::freshData(){
this->on_freshRom_clicked();
return true;
}
///
/// \brief ROMCheck::getMCInHex 获得微指令16进制码字符串
/// \param row
/// \param dataBack
/// \return
///
bool ROMCheck::getMCInHex(int row,QString& dataBack){
dataBack.clear();
if(row>this->data->rom_row_size) return false;
dataBack.append(this->hexNumberSet[binaToDec(0,0,
this->data->data_rom[row][8],
this->data->data_rom[row][7],this->data->data_rom[row][6],this->data->data_rom[row][5])]);
dataBack.append(this->hexNumberSet[binaToDec(0,0,
this->data->data_rom[row][4],this->data->data_rom[row][3],this->data->data_rom[row][2],this->data->data_rom[row][1])]);
dataBack.append(this->hexNumberSet[binaToDec(0,0,
this->data->data_rom[row][16],this->data->data_rom[row][15],this->data->data_rom[row][14],this->data->data_rom[row][13])]);
dataBack.append(this->hexNumberSet[binaToDec(0,0,
this->data->data_rom[row][12],this->data->data_rom[row][11],this->data->data_rom[row][10],this->data->data_rom[row][9])]);
dataBack.append(this->hexNumberSet[binaToDec(0,0,
this->data->data_rom[row][24],this->data->data_rom[row][23],this->data->data_rom[row][22],this->data->data_rom[row][21])]);
dataBack.append(this->hexNumberSet[binaToDec(0,0,
this->data->data_rom[row][20],this->data->data_rom[row][19],
this->data->data_rom[row][18],this->data->data_rom[row][17])]);
return true;
}
///
/// \brief ROMCheck::getB1B0Statu 获得B1B0状态字符串
/// \param row
/// \param dataBack
/// \return
///
bool ROMCheck::getB1B0Statu(int row,QString& dataBack){
dataBack.clear();
if(row>this->data->rom_row_size) return false;
if(this->data->data_rom[row][17]==0&&this->data->data_rom[row][16]==0){
dataBack="Input";
}else if(this->data->data_rom[row][17]==0&&this->data->data_rom[row][16]==1){
dataBack="RAM";
}else if(this->data->data_rom[row][17]==1&&this->data->data_rom[row][16]==0){
dataBack="Output";
}else if(this->data->data_rom[row][17]==1&&this->data->data_rom[row][16]==1){
dataBack="None";
}
return true;
}
bool ROMCheck::getB1B0(int row, QString &dataBack)
{
dataBack.clear();
if(row>this->data->rom_row_size) return false;
if(this->data->data_rom[row][mB1]){
dataBack+='1';
}else{
dataBack+='0';
}
if(this->data->data_rom[row][mB0]){
dataBack+='1';
}else{
dataBack+='0';
}
return true;
}
///
/// \brief ROMCheck::getAStatu A字符串
/// \param row
/// \param dataBack
/// \return
///
bool ROMCheck::getAStatu(int row,QString& dataBack){
dataBack.clear();
if(row>this->data->rom_row_size) return false;
int _a3= this->data->data_rom[row][ma3];
int _a2= this->data->data_rom[row][ma2];
int _a1= this->data->data_rom[row][ma1];
if (_a3 == 0 && _a2 == 0 && _a1 == 0) {//内部输入设备不选中
dataBack="None";
}
else if (_a3 == 0 && _a2 == 0 && _a1 == 1) {//RiIN
dataBack="R";
dataBack.append((char)(this->data->data_ir%4+'0'));
}
else if (_a3 == 0 && _a2 == 1 && _a1 == 0) {//DR1
dataBack="DR1";
}
else if (_a3 == 0 && _a2 == 1 && _a1 == 1) {//DR2
dataBack="DR2";
}
else if (_a3 == 1 && _a2 == 0 && _a1 == 0) {//LDIR
dataBack="IR";
}
else if (_a3 == 1 && _a2 == 0 && _a1 == 1) {//LDAD(PC)
dataBack ="PC";
}
else if (_a3 == 1 && _a2 == 1 && _a1 == 0) {//LDAR
dataBack="AR";
}
else if (_a3 == 1 && _a2 == 1 && _a1 == 1) {//NONE
dataBack="NONE";
}
return true;
}
bool ROMCheck::getA(int row, QString &dataBack)
{
dataBack.clear();
if(row>this->data->rom_row_size) return false;
if(this->data->data_rom[row][ma3]){
dataBack+='1';
}else{
dataBack+='0';
}
if(this->data->data_rom[row][ma2]){
dataBack+='1';
}else{
dataBack+='0';
}
if(this->data->data_rom[row][ma1]){
dataBack+='1';
}else{
dataBack+='0';
}
return true;
}
///
/// \brief ROMCheck::getBStatu B字符串
/// \param row
/// \param dataBack
/// \return
///
bool ROMCheck::getBStatu(int row,QString& dataBack){
dataBack.clear();
if(row>this->data->rom_row_size) return false;
int _c3=this->data->data_rom[row][mc3];
int _c2=this->data->data_rom[row][mc2];
int _c1=this->data->data_rom[row][mc1];
int _b3=this->data->data_rom[row][mb3];
int _b2=this->data->data_rom[row][mb2];
int _b1=this->data->data_rom[row][mb1];
if (_b3 == 0 && _b2 == 0 && _b1 == 0) {//内部输出设备不存在
dataBack="NONE";
}
else if (_b3 == 0 && _b2 == 0 && _b1 == 1) {//RS-B
dataBack="R(S)";
dataBack.append((char)(((this->data->data_ir) % 8)/4+'0'));
}
else if (_b3 == 0 && _b2 == 1 && _b1 == 0) {//RD-B
dataBack="R";
dataBack.append((char)((this->data->data_ir) % 4+'0'));
}
else if (_b3 == 0 && _b2 == 1 && _b1 == 1) {//RI-B(选R2)
dataBack="R2";
}
else if (_b3 == 1 && _b2 == 0 && _b1 == 0) {//299-B
dataBack="299";
}
else if (_b3 == 1 && _b2 == 0 && _b1 == 1) {//ALU-B
if (_c3 == 1 && _c2 == 0 && _c1 == 1) {//AR是否有效
dataBack="ALU(AR)";
}
else {
dataBack="ALU";
}
}
else if (_b3 == 1 && _b2 == 1 && _b1 == 0) {//PC-B
dataBack="PC";
}
else if (_b3 == 1 && _b2 == 1 && _b1 == 1) {//NOne
dataBack="NONE";
}
return true;
}
bool ROMCheck::getB(int row, QString &dataBack)
{
dataBack.clear();
if(row>this->data->rom_row_size) return false;
if(this->data->data_rom[row][mb3]){
dataBack+='1';
}else{
dataBack+='0';
}
if(this->data->data_rom[row][mb2]){
dataBack+='1';
}else{
dataBack+='0';
}
if(this->data->data_rom[row][mb1]){
dataBack+='1';
}else{
dataBack+='0';
}
return true;
}
///
/// \brief ROMCheck::getCStatu C字符串
/// \param row
/// \param dataBack
/// \return
///
bool ROMCheck::getCStatu(int row,QString& dataBack){
dataBack.clear();
if(row>this->data->rom_row_size) return false;
int _c3=this->data->data_rom[row][9];
int _c2=this->data->data_rom[row][8];
int _c1=this->data->data_rom[row][7];
if (_c3 == 0 && _c2 == 0 && _c1 == 0) {//顺序执行
dataBack="顺序执行";
}
else if (_c3 == 0 && _c2 == 0 && _c1 == 1) {//P(1)
dataBack="P(1)";
}
else if (_c3 == 0 && _c2 == 1 && _c1 == 0) {//P(2)
dataBack="p(2)";
}
else if (_c3 == 0 && _c2 == 1 && _c1 == 1) {//P(3)
dataBack="p(3)";
}
else if (_c3 == 1 && _c2 == 0 && _c1 == 0) {//P(4)
dataBack="p(4)";
}
else if (_c3 == 1 && _c2 == 0 && _c1 == 1) {//AR
dataBack="AR选中\n顺序执行";
}
else if (_c3 == 1 && _c2 == 1 && _c1 == 0) {//LDPC
dataBack="Pc+1\n顺序执行";
}
else if (_c3 == 1 && _c2 == 1 && _c1 == 1) {//NONE
dataBack="NONE";
}
return true;
}
bool ROMCheck::getC(int row, QString &dataBack)
{
dataBack.clear();
if(row>this->data->rom_row_size) return false;
if(this->data->data_rom[row][mc3]){
dataBack+='1';
}else{
dataBack+='0';
}
if(this->data->data_rom[row][mc2]){
dataBack+='1';
}else{
dataBack+='0';
}
if(this->data->data_rom[row][mc1]){
dataBack+='1';
}else{
dataBack+='0';
}
return true;
}
///
/// \brief ROMCheck::getNextMroAD 获取下一微地址字符串,未经P跳转处理
/// \param row
/// \param dataBack
/// \return
///
bool ROMCheck::getNextMroAD(int row,QString &dataBack){
dataBack.clear();
if(row>this->data->rom_row_size) return false;
int _u6=this->data->data_rom[row][6];
int _u5=this->data->data_rom[row][5];
int _u4=this->data->data_rom[row][4];
int _u3=this->data->data_rom[row][3];
int _u2=this->data->data_rom[row][2];
int _u1=this->data->data_rom[row][1];
dataBack=QString("%1").arg(binaToDec(_u6,_u5,_u4, _u3, _u2,_u1),
6,//Width
2,//Hexc
QLatin1Char('0')//Fill letter
);
return true;
}
bool ROMCheck::getS3S0(int row, QString &dataBack)
{
if(row>this->data->rom_row_size) return false;
dataBack.clear();
if(this->data->data_rom[row][ms3]){
dataBack+='1';
}else{
dataBack+='0';
}
if(this->data->data_rom[row][ms2]){
dataBack+='1';
}else{
dataBack+='0';
}
if(this->data->data_rom[row][ms1]){
dataBack+='1';
}else{
dataBack+='0';
}
if(this->data->data_rom[row][ms0]){
dataBack+='1';
}else{
dataBack+='0';
}
return true;
}
bool ROMCheck::getM(int row, QString &dataBack)
{
if(row>this->data->rom_row_size) return false;
dataBack.clear();
if(this->data->data_rom[row][mm]){
dataBack='1';
}else{
dataBack='0';
}
return true;
}
bool ROMCheck::getCn(int row, QString &dataBack)
{
if(row>this->data->rom_row_size) return false;
dataBack.clear();
if(this->data->data_rom[row][mcn]){
dataBack='1';
}else{
dataBack='0';
}
return true;
}
bool ROMCheck::getWe(int row, QString &dataBack)
{
if(row>this->data->rom_row_size) return false;
dataBack.clear();
if(this->data->data_rom[row][mwe]){
dataBack='1';
}else{
dataBack='0';
}
return true;
}
//数据刷新
void ROMCheck::on_freshRom_clicked()
{
this->ui->ROMTable->blockSignals(true);
//初始化数据
QString hexcOutStirng="000";
for(int rowIndex=0;rowIndex<this->data->rom_row_size;rowIndex++){
//输出rom内容
this->getMCInHex(rowIndex,hexcOutStirng);
this->ui->ROMTable->setItem(rowIndex,1,new QTableWidgetItem(hexcOutStirng));
this->getB1B0Statu(rowIndex,hexcOutStirng);
this->ui->ROMTable->setItem(rowIndex,2,new QTableWidgetItem(hexcOutStirng));
this->getAStatu(rowIndex,hexcOutStirng);
this->ui->ROMTable->setItem(rowIndex,3,new QTableWidgetItem(hexcOutStirng));
this->getBStatu(rowIndex,hexcOutStirng);
this->ui->ROMTable->setItem(rowIndex,4,new QTableWidgetItem(hexcOutStirng));
this->getCStatu(rowIndex,hexcOutStirng);
this->ui->ROMTable->setItem(rowIndex,5,new QTableWidgetItem(hexcOutStirng));
this->getNextMroAD(rowIndex,hexcOutStirng);
this->ui->ROMTable->setItem(rowIndex,6,new QTableWidgetItem(hexcOutStirng));
//输出地址序号
hexcOutStirng=QString("%1").arg(rowIndex,4,16,QLatin1Char('0'));
this->ui->ROMTable->setItem(rowIndex,0,new QTableWidgetItem(hexcOutStirng));
}
this->ui->ROMTable->blockSignals(false);
}
//数据更改
void ROMCheck::on_ROMTable_itemChanged(QTableWidgetItem *item)
{
int row=item->row();
int column=item->column();
if(column==1){
if(this->matchPattrn->match(item->text()).hasMatch()){
//数据保存
this->updateRomRowData(row,item->text());
}else{
item->setText(this->oldText);
}
}
}
//保存原始数据
void ROMCheck::on_ROMTable_cellDoubleClicked(int row, int column)
{
this->oldText=this->ui->ROMTable->item(row,column)->text();
}
//更新表格内容到rom
bool ROMCheck::updateRomRowData(int &row, QString mcString)
{
if(row>this->data->rom_row_size){
return false;
}
//8 9 10 11
int trans=hexcToDec(mcString[4]);
this->data->data_rom[row][ms3] = trans /8;
this->data->data_rom[row][ms2] = trans % 8 / 4;
this->data->data_rom[row][ms1] = trans % 8 % 4/2;
this->data->data_rom[row][ms0] = trans % 8 % 4 % 2;
trans=hexcToDec(mcString[5]);
this->data->data_rom[row][mm] = trans /8;
this->data->data_rom[row][mcn] = trans % 8 / 4;
this->data->data_rom[row][mwe] = trans % 8 % 4/2;
this->data->data_rom[row][mB1] = trans % 8 % 4 % 2;
trans=hexcToDec(mcString[2]);
this->data->data_rom[row][mB0] = trans /8;
this->data->data_rom[row][ma3] = trans % 8 / 4;
this->data->data_rom[row][ma2] = trans % 8 % 4/2;
this->data->data_rom[row][ma1] = trans % 8 % 4 % 2;
trans=hexcToDec(mcString[3]);
this->data->data_rom[row][mb3] = trans /8;
this->data->data_rom[row][mb2] = trans % 8 / 4;
this->data->data_rom[row][mb1] = trans % 8 % 4/2;
this->data->data_rom[row][mc3] = trans % 8 % 4 % 2;
trans=hexcToDec(mcString[0]);
this->data->data_rom[row][mc2] = trans /8;
this->data->data_rom[row][mc1] = trans % 8 / 4;
this->data->data_rom[row][mu6] = trans % 8 % 4/2;
this->data->data_rom[row][mu5] = trans % 8 % 4 % 2;
trans=hexcToDec(mcString[1]);
this->data->data_rom[row][mu4] = trans /8;
this->data->data_rom[row][mu3] = trans % 8 / 4;
this->data->data_rom[row][mu2] = trans % 8 % 4/2;
this->data->data_rom[row][mu1] = trans % 8 % 4 % 2;
return true;
}
bool ROMCheck::setEditModel(bool edit){
this->on_freshRom_clicked();
this->ui->edit_btn->setChecked(edit);
this->on_edit_btn_clicked(true);
if(this->isHidden()==true){
this->show();
}
return true;
}
void ROMCheck::on_edit_btn_clicked(bool checked)
{
if(checked){
this->ui->ROMTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
this->ui->edit_btn->setText(tr("编辑"));
this->ui->ROMCheckTitle->setText(tr("RAM内存"));
}else{
this->ui->ROMTable->setEditTriggers(QAbstractItemView::DoubleClicked);
this->ui->edit_btn->setText(tr("停止编辑"));
this->ui->ROMCheckTitle->setText(tr("RAM内存(编辑模式)"));
}
}
| 27.415879 | 172 | 0.558022 | HarleyEhrich |
e5eb15e032f439684881419a7791b92d2a8730c4 | 3,356 | cpp | C++ | cpp_config_test/main.cpp | lyrahgames/cpp-config-test | 0a69a6298e576496fe52296b5678f804035b163f | [
"MIT"
] | null | null | null | cpp_config_test/main.cpp | lyrahgames/cpp-config-test | 0a69a6298e576496fe52296b5678f804035b163f | [
"MIT"
] | null | null | null | cpp_config_test/main.cpp | lyrahgames/cpp-config-test | 0a69a6298e576496fe52296b5678f804035b163f | [
"MIT"
] | null | null | null | #include <iomanip>
#include <iostream>
using namespace std;
#define CAPTURE(X) \
cout << right << setw(5) << ' ' << left << setw(30) << #X << right << " = " \
<< setw(15) << (X) << '\n'
#define CAPTURE_UNDEF(X) \
cout << right << setw(5) << ' ' << left << setw(30) << #X << right \
<< setw(15 + 4) << " undefined\n"
inline void separate() {
cout << setfill('-') << setw(80) << '\n' << setfill(' ');
}
int main() {
separate();
cout << "C++ Configuration Test:\n";
separate();
cout << "Operating System Macros:\n";
#ifdef __linux__
CAPTURE(__linux__);
#else
CAPTURE_UNDEF(__linux__);
#endif
#ifdef __ANDROID__
CAPTURE(__ANDROID__);
#else
CAPTURE_UNDEF(__ANDROID__);
#endif
#ifdef __APPLE__
CAPTURE(__APPLE__);
#else
CAPTURE_UNDEF(__APPLE__);
#endif
#ifdef _WIN32
CAPTURE(_WIN32);
#else
CAPTURE_UNDEF(_WIN32);
#endif
#ifdef _WIN64
CAPTURE(_WIN64);
#else
CAPTURE_UNDEF(_WIN64);
#endif
cout << '\n';
cout << "Compiler Macros:\n";
cout << " "
<< "GCC:\n";
#ifdef __GNUC__
CAPTURE(__GNUC__);
#else
CAPTURE_UNDEF(__GNUC__);
#endif
#ifdef __GNUC_MINOR__
CAPTURE(__GNUC_MINOR__);
#else
CAPTURE_UNDEF(__GNUC_MINOR__);
#endif
#ifdef __GNUC_PATCHLEVEL__
CAPTURE(__GNUC_PATCHLEVEL__);
#else
CAPTURE_UNDEF(__GNUC_PATCHLEVEL__);
#endif
cout << " "
<< "Clang:\n";
#ifdef __clang__
CAPTURE(__clang__);
#else
CAPTURE_UNDEF(__clang__);
#endif
#ifdef __clang_major__
CAPTURE(__clang_major__);
#else
CAPTURE_UNDEF(__clang_major__);
#endif
#ifdef __clang_minor__
CAPTURE(__clang_minor__);
#else
CAPTURE_UNDEF(__clang_minor__);
#endif
#ifdef __clang_patchlevel__
CAPTURE(__clang_patchlevel__);
#else
CAPTURE_UNDEF(__clang_patchlevel__);
#endif
#ifdef __clang_version__
CAPTURE(__clang_version__);
#else
CAPTURE_UNDEF(__clang_version__);
#endif
#ifdef __apple_build_version__
CAPTURE(__apple_build_version__);
#else
CAPTURE_UNDEF(__apple_build_version__);
#endif
cout << " "
<< "Microsoft:\n";
#ifdef _MSC_VER
CAPTURE(_MSC_VER);
#else
CAPTURE_UNDEF(_MSC_VER);
#endif
#ifdef _MSC_FULL_VER
CAPTURE(_MSC_FULL_VER);
#else
CAPTURE_UNDEF(_MSC_FULL_VER);
#endif
#ifdef _MSC_BUILD
CAPTURE(_MSC_BUILD);
#else
CAPTURE_UNDEF(_MSC_BUILD);
#endif
cout << " "
<< "MinGW:\n";
#ifdef __MINGW32__
CAPTURE(__MINGW32__);
#else
CAPTURE_UNDEF(__MINGW32__);
#endif
#ifdef __MINGW32_MAJOR_VERSION__
CAPTURE(__MINGW32_MAJOR_VERSION__);
#else
CAPTURE_UNDEF(__MINGW32_MAJOR_VERSION__);
#endif
#ifdef __MINGW32_MINOR_VERSION__
CAPTURE(__MINGW32_MINOR_VERSION__);
#else
CAPTURE_UNDEF(__MINGW32_MINOR_VERSION__);
#endif
#ifdef __MINGW64__
CAPTURE(__MINGW64__);
#else
CAPTURE_UNDEF(__MINGW64__);
#endif
#ifdef __MINGW64_VERSION_MAJOR__
CAPTURE(__MINGW64_VERSION_MAJOR__);
#else
CAPTURE_UNDEF(__MINGW64_VERSION_MAJOR__);
#endif
#ifdef __MINGW64_VERSION_MINOR__
CAPTURE(__MINGW64_VERSION_MINOR__);
#else
CAPTURE_UNDEF(__MINGW64_VERSION_MINOR__);
#endif
cout << " "
<< "Intel:\n";
#ifdef __INTEL_COMPILER
CAPTURE(__INTEL_COMPILER);
#else
CAPTURE_UNDEF(__INTEL_COMPILER);
#endif
#ifdef __INTEL_COMPILER_BUILD_DATE
CAPTURE(__INTEL_COMPILER_BUILD_DATE);
#else
CAPTURE_UNDEF(__INTEL_COMPILER_BUILD_DATE);
#endif
separate();
} | 20.716049 | 79 | 0.698749 | lyrahgames |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.