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
973c113401f4674b562d4ebf3724e179531270e7
185
cpp
C++
src/stan/language/grammars/expression07_grammar_inst.cpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
src/stan/language/grammars/expression07_grammar_inst.cpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
src/stan/language/grammars/expression07_grammar_inst.cpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
null
null
null
#include "expression07_grammar_def.hpp" #include "iterator_typedefs.hpp" namespace stan { namespace lang { template struct expression07_grammar<pos_iterator_t>; } } // namespace stan
20.555556
53
0.8
alashworth
973c1d1aef3085b665141d6b9dfc1f5600ed76b1
838
cpp
C++
Classes/Device.cpp
Tang1705/Happy-Reconstruction
2040310be4475deff0a8d251feaf32d7ba82d0ff
[ "Apache-2.0" ]
5
2021-12-13T08:48:07.000Z
2022-01-04T01:28:40.000Z
Classes/Device.cpp
xmtc56606/Reconstruction
7eadf91b397fa2067b983be1a31c9603043d1360
[ "Apache-2.0" ]
null
null
null
Classes/Device.cpp
xmtc56606/Reconstruction
7eadf91b397fa2067b983be1a31c9603043d1360
[ "Apache-2.0" ]
1
2022-03-28T06:04:34.000Z
2022-03-28T06:04:34.000Z
#include "Device.h" #include <QDebug> Device* Device::instance = nullptr; Device::Device() { vector<CameraInfo> cams = CameraPointGrey::getCameraList(); if (cams.size() != 0) { hasCamera = true; camera = Camera::NewCamera(0, cams[0].busID, triggerModeSoftware); CameraSettings camSettings; camSettings.shutter = 25; camSettings.gain = 0.0; camera->setCameraSettings(camSettings); camera->startCapture(); } projector = new ProjectorLC4500(0); if (projector->getIsRunning())hasProjector = true; } Device* Device::getInstance() { if (instance == nullptr) instance = new Device(); return instance; } Camera* Device::getCamera() { return camera; } Projector* Device::getProjector() { return projector; } bool Device::getHasCamera() { return hasCamera; } bool Device::getHasProjector() { return hasProjector; }
17.458333
68
0.711217
Tang1705
9741c086d1b97a36b72febad8eb1f70578664ab7
2,492
cpp
C++
src/args_test.cpp
JoelSjogren/video-organizer
fc5a5c1a2fce39f2b9d8343c07c53108321ef260
[ "Apache-2.0" ]
2
2015-04-17T11:28:57.000Z
2016-11-13T13:03:08.000Z
src/args_test.cpp
JoelSjogren/video-organizer
fc5a5c1a2fce39f2b9d8343c07c53108321ef260
[ "Apache-2.0" ]
null
null
null
src/args_test.cpp
JoelSjogren/video-organizer
fc5a5c1a2fce39f2b9d8343c07c53108321ef260
[ "Apache-2.0" ]
null
null
null
/********************************** * args_test.cpp * **********************************/ #include "args_test.h" #include "args.h" #include "fileman.h" #include <string> using std::string; ArgsTest::ArgsTest() : Test("Args") { const char* files[] = { "Chuck.S05E01.HDTV.XviD-LOL.avi", "Community.S04E02.HDTV.x264-LOL.mp4", "subdir/Chuck.S05E02.HDTV.XviD-LOL.avi", "The.Prestige.2006.720p.Bluray.x264.anoXmous.mp4", }; const int filec = sizeof(files) / sizeof(*files); const string indir = getdir() + "input/"; const string outdir = getdir() + "output/"; { // Prepare workspace Args args; FileMan fileman(args); fileman.remove_all(getdir()); for (int i = 0; i < filec; i++) fileman.touch(indir + files[i]); fileman.dig(outdir); } { // Test 1: minimal char* argv[] = { (char*) "video-organizer", (char*) indir.c_str(), (char*) "--verbosity=-1", // suppress warnings }; int argc = sizeof(argv) / sizeof(*argv); Args args(argc, argv); EQ(args.undo, false); EQ(args.outdir, "./"); EQ(args.infiles.size(), (unsigned) 1); EQ(args.action, Args::MOVE); EQ(args.verbosity, -1); EQ(args.recursive, false); EQ(args.include_part, false); EQ(args.clean, 0); } { // Test 2: short options char* argv[] = { (char*) "video-organizer", (char*) indir.c_str(), (char*) "-v", (char*) "-1", (char*) "-o", (char*) outdir.c_str(), (char*) "-c", (char*) "-r", (char*) "-p", }; int argc = sizeof(argv) / sizeof(*argv); Args args(argc, argv); EQ(args.undo, false); EQ(args.outdir, outdir); EQ(args.infiles.size(), (unsigned) 1); EQ(args.action, Args::COPY); EQ(args.verbosity, -1); EQ(args.recursive, true); EQ(args.include_part, true); EQ(args.clean, 0); } { // Test 3: long options string outdirarg = "--outdir=" + outdir; // put on stack char* argv[] = { (char*) "video-organizer", (char*) "--link", (char*) indir.c_str(), (char*) "--verbosity=-1", (char*) outdirarg.c_str(), (char*) "--recursive", (char*) "--part", (char*) "--clean=3M", }; int argc = sizeof(argv) / sizeof(*argv); Args args(argc, argv); EQ(args.undo, false); EQ(args.outdir, outdir); EQ(args.infiles.size(), (unsigned) 1); EQ(args.action, Args::LINK); EQ(args.verbosity, -1); EQ(args.recursive, true); EQ(args.include_part, true); EQ(args.clean, 3*1024*1024); } }
26.795699
58
0.554575
JoelSjogren
97466246b549d44e5bfbfba129449c424b573d6e
2,501
cpp
C++
test/test_timer.cpp
chyh1990/futures_cpp
8e60e74af0cffff0a9749682a4caf1768277c04b
[ "MIT" ]
71
2017-12-18T10:35:41.000Z
2021-12-11T19:57:34.000Z
test/test_timer.cpp
chyh1990/futures_cpp
8e60e74af0cffff0a9749682a4caf1768277c04b
[ "MIT" ]
1
2017-12-19T09:31:46.000Z
2017-12-20T07:08:01.000Z
test/test_timer.cpp
chyh1990/futures_cpp
8e60e74af0cffff0a9749682a4caf1768277c04b
[ "MIT" ]
7
2017-12-20T01:55:44.000Z
2019-12-06T12:25:55.000Z
#include <gtest/gtest.h> #include <futures/EventExecutor.h> #include <futures/Timeout.h> #include <futures/Timer.h> #include <futures/Future.h> using namespace futures; TEST(Executor, Timer) { EventExecutor ev; auto f = TimerFuture(&ev, 1) .andThen([&ev] (Unit) { std::cerr << "DONE" << std::endl; return makeOk(); }); ev.spawn(std::move(f)); ev.run(); std::cerr << "END" << std::endl; } TEST(Future, Timeout) { EventExecutor ev; auto f = makeEmpty<int>(); auto f1 = timeout(&ev, std::move(f), 1.0) .then([] (Try<int> v) { if (v.hasException()) std::cerr << "ERROR" << std::endl; return makeOk(); }); ev.spawn(std::move(f1)); ev.run(); } TEST(Future, AllTimeout) { EventExecutor ev; std::vector<BoxedFuture<int>> f; f.emplace_back(TimerFuture(&ev, 1.0) .then([] (Try<Unit> v) { if (v.hasException()) std::cerr << "ERROR" << std::endl; else std::cerr << "Timer1 done" << std::endl; return makeOk(1); }).boxed()); f.emplace_back(TimerFuture(&ev, 2.0) .then([] (Try<Unit> v) { if (v.hasException()) std::cerr << "ERROR" << std::endl; else std::cerr << "Timer2 done" << std::endl; return makeOk(2); }).boxed()); auto all = makeWhenAll(f.begin(), f.end()) .andThen([] (std::vector<int> ids) { std::cerr << "done" << std::endl; return makeOk(); }); ev.spawn(std::move(all)); ev.run(); } BoxedFuture<std::vector<int>> rwait(EventExecutor &ev, std::vector<int> &v, int n) { if (n == 0) return makeOk(std::move(v)).boxed(); return TimerFuture(&ev, 0.1) .andThen( [&ev, &v, n] (Unit) { v.push_back(n); return rwait(ev, v, n - 1); }).boxed(); } TEST(Future, RecursiveTimer) { EventExecutor ev; std::vector<int> idxes; auto w10 = rwait(ev, idxes, 10) .andThen([] (std::vector<int> idxes) { for (auto e: idxes) std::cerr << e << std::endl; return makeOk(); }); ev.spawn(std::move(w10)); ev.run(); } TEST(Future, TimerKeeper) { EventExecutor ev; auto timer = std::make_shared<TimerKeeper>(&ev, 1); auto f = [timer, &ev] (double sec) { return delay(&ev, sec) .andThen([timer] (Unit) { return TimerKeeperFuture(timer); }) .then([] (Try<Unit> err) { if (err.hasException()) { std::cerr << "ERR: " << err.exception().what() << std::endl; } else { std::cerr << "Timeout: " << (uint64_t)(EventExecutor::current()->getNow() * 1000.0) << std::endl; } return makeOk(); }); }; ev.spawn(f(0.2)); ev.spawn(f(0.4)); ev.run(); }
21.376068
102
0.580968
chyh1990
974aa1b66be0b4d7e57c440ac9130fdb6c4d7a61
960
cpp
C++
lib/Food.cpp
prakashutoledo/pacman-cpp
0d3e46bd79970d722bc83fd5aeb52a34ad6c27e5
[ "Apache-2.0" ]
1
2021-04-19T12:10:01.000Z
2021-04-19T12:10:01.000Z
lib/Food.cpp
prakashutoledo/pacman-cpp
0d3e46bd79970d722bc83fd5aeb52a34ad6c27e5
[ "Apache-2.0" ]
null
null
null
lib/Food.cpp
prakashutoledo/pacman-cpp
0d3e46bd79970d722bc83fd5aeb52a34ad6c27e5
[ "Apache-2.0" ]
null
null
null
#include "Food.h" void Food::Initilize(Position * position) { this->position = position; drawing = CreateBitmap(position); CollisionDetection::Instance()->Add(this); } Food::Food(int x, int y) { Initilize(new Position(x - FOOD_RADIUS, y - FOOD_RADIUS)); } Food::Food(Position * position) { Initilize(position); } Bitmap * Food::CreateBitmap(Position * position) { #ifdef DEBUG if (position == 0) throw new NullReferenceException("position", "Food::CreateBitmap"); #endif Bitmap * bmp = new Bitmap(2 * FOOD_RADIUS + 1, 2 * FOOD_RADIUS + 1, position->X(), position->Y()); Color * color = new Color(FOOD_COLOR_R, FOOD_COLOR_G, FOOD_COLOR_B); bmp->Clean(); bmp->DrawFilledCircle(FOOD_RADIUS, FOOD_RADIUS, FOOD_RADIUS, color); return bmp; } void Food::WasEaten() { DrawingElement::WasEaten(); Reconstruction::Instance()->FoodEaten(); }
22.857143
106
0.628125
prakashutoledo
974c5c2a8c7403ab4d50628b70c73d0b2bb150e3
2,200
hpp
C++
srcs/boxpp/boxpp/base/systems/Barrior.hpp
whoamiho1006/boxpp
5de2c5f9b2303ac6f539192f6407e9acf9144f8b
[ "MIT" ]
2
2019-11-13T13:57:37.000Z
2019-11-25T09:55:17.000Z
srcs/boxpp/boxpp/base/systems/Barrior.hpp
whoamiho1006/boxpp
5de2c5f9b2303ac6f539192f6407e9acf9144f8b
[ "MIT" ]
null
null
null
srcs/boxpp/boxpp/base/systems/Barrior.hpp
whoamiho1006/boxpp
5de2c5f9b2303ac6f539192f6407e9acf9144f8b
[ "MIT" ]
null
null
null
#pragma once #include <boxpp/base/BaseMacros.hpp> #include <boxpp/base/BaseTypes.hpp> #include <boxpp/base/opacities/posix.hpp> #include <boxpp/base/opacities/windows.hpp> namespace boxpp { /* Barrior is for guarding specific blocks. */ class BOXPP FBarrior { public: FASTINLINE FBarrior() { #if PLATFORM_WINDOWS w32_compat::InitializeCriticalSection(&__CS__); #endif #if PLATFORM_POSIX pthread_mutex_init(&__MUTEX__, nullptr); #endif } FASTINLINE ~FBarrior() { #if PLATFORM_WINDOWS w32_compat::DeleteCriticalSection(&__CS__); #endif #if PLATFORM_POSIX pthread_mutex_destroy(&__MUTEX__); #endif } public: /* Enter to behind of barrior. */ FASTINLINE void Enter() const { #if PLATFORM_WINDOWS if (!w32_compat::TryEnterCriticalSection(&__CS__)) w32_compat::EnterCriticalSection(&__CS__); #endif #if PLATFORM_POSIX if (pthread_mutex_trylock(&__MUTEX__)) pthread_mutex_lock(&__MUTEX__); #endif } /* Try enter to behind of barrior. */ FASTINLINE bool TryEnter() const { register bool RetVal = false; #if PLATFORM_WINDOWS RetVal = w32_compat::TryEnterCriticalSection(&__CS__); #endif #if PLATFORM_POSIX RetVal = !pthread_mutex_trylock(&__MUTEX__); #endif return RetVal; } /* Leave from behind of barrior. */ FASTINLINE void Leave() const { #if PLATFORM_WINDOWS w32_compat::LeaveCriticalSection(&__CS__); #endif #if PLATFORM_POSIX pthread_mutex_unlock(&__MUTEX__); #endif } private: #if PLATFORM_WINDOWS mutable w32_compat::CRITICAL_SECTION __CS__; #endif #if PLATFORM_POSIX mutable pthread_mutex_t __MUTEX__; #endif }; /* Barrior scope. */ class FBarriorScope { public: FASTINLINE FBarriorScope(FBarrior& Barrior) : Barrior(&Barrior) { Barrior.Enter(); } FASTINLINE FBarriorScope(const FBarrior& Barrior) : Barrior(&Barrior) { Barrior.Enter(); } FASTINLINE ~FBarriorScope() { Barrior->Leave(); } private: const FBarrior* Barrior; }; #define BOX_BARRIOR_SCOPED(BarriorInstance) \ boxpp::FBarriorScope BOX_CONCAT(__Scope_At_, __LINE__) (BarriorInstance) #define BOX_DO_WITH_BARRIOR(BarriorInstance, ...) \ if (true) { BOX_BARRIOR_SCOPED(BarriorInstance); __VA_ARGS__ } }
20.754717
73
0.735
whoamiho1006
9752b0ceb7349ca95afc55b5ed16da2d464af0a3
3,746
cpp
C++
test/core/vector_specialisation_test.cpp
marovira/apollo
79920864839066c4e24d87de92c36dde4a315b10
[ "BSD-3-Clause" ]
1
2020-05-02T14:33:42.000Z
2020-05-02T14:33:42.000Z
test/core/vector_specialisation_test.cpp
marovira/apollo
79920864839066c4e24d87de92c36dde4a315b10
[ "BSD-3-Clause" ]
null
null
null
test/core/vector_specialisation_test.cpp
marovira/apollo
79920864839066c4e24d87de92c36dde4a315b10
[ "BSD-3-Clause" ]
null
null
null
#include <core/vector.hpp> #include <catch2/catch.hpp> TEMPLATE_TEST_CASE( "[Vector] - specialised constructors", "[core]", float, double, int) { SECTION("Empty constructor: size 2") { core::Vector2<TestType> v; REQUIRE(v.x == TestType{0}); REQUIRE(v.y == TestType{0}); } SECTION("Empty constructor: size 3") { core::Vector3<TestType> v; REQUIRE(v.x == TestType{0}); REQUIRE(v.y == TestType{0}); REQUIRE(v.z == TestType{0}); } SECTION("Empty constructor: size 4") { core::Vector4<TestType> v; REQUIRE(v.x == TestType{0}); REQUIRE(v.y == TestType{0}); REQUIRE(v.z == TestType{0}); REQUIRE(v.w == TestType{0}); } SECTION("Uniform constructor: size 2") { core::Vector2<TestType> v{TestType{1}}; REQUIRE(v.x == TestType{1}); REQUIRE(v.y == TestType{1}); } SECTION("Uniform constructor: size 3") { core::Vector3<TestType> v{TestType{1}}; REQUIRE(v.x == TestType{1}); REQUIRE(v.y == TestType{1}); REQUIRE(v.z == TestType{1}); } SECTION("Uniform constructor: size 2") { core::Vector4<TestType> v{TestType{1}}; REQUIRE(v.x == TestType{1}); REQUIRE(v.y == TestType{1}); REQUIRE(v.z == TestType{1}); REQUIRE(v.w == TestType{1}); } SECTION("Parameterised constructor: size 2") { core::Vector2<TestType> v{TestType{1}, TestType{2}}; REQUIRE(v.x == TestType{1}); REQUIRE(v.y == TestType{2}); } SECTION("Parameterised constructor: size 3") { core::Vector3<TestType> v{TestType{1}, TestType{2}, TestType{3}}; REQUIRE(v.x == TestType{1}); REQUIRE(v.y == TestType{2}); REQUIRE(v.z == TestType{3}); } SECTION("Parameterised constructor: size 4") { core::Vector4<TestType> v{ TestType{1}, TestType{2}, TestType{3}, TestType{4}}; REQUIRE(v.x == TestType{1}); REQUIRE(v.y == TestType{2}); REQUIRE(v.z == TestType{3}); REQUIRE(v.w == TestType{4}); } } TEMPLATE_TEST_CASE( "[Vector] - specialised operator[]", "[core]", float, double, int) { SECTION("Non-const version: size 2") { core::Vector2<TestType> v{TestType{1}, TestType{2}}; REQUIRE(v[0] == TestType{1}); REQUIRE(v[1] == TestType{2}); } SECTION("Const version: size 2") { const core::Vector2<TestType> v{TestType{1}, TestType{2}}; REQUIRE(v[0] == TestType{1}); REQUIRE(v[1] == TestType{2}); } SECTION("Non-const version: size 3") { core::Vector3<TestType> v{TestType{1}, TestType{2}, TestType{3}}; REQUIRE(v[0] == TestType{1}); REQUIRE(v[1] == TestType{2}); REQUIRE(v[2] == TestType{3}); } SECTION("Const version: size 3") { const core::Vector3<TestType> v{TestType{1}, TestType{2}, TestType{3}}; REQUIRE(v[0] == TestType{1}); REQUIRE(v[1] == TestType{2}); REQUIRE(v[2] == TestType{3}); } SECTION("Non-const version: size 4") { core::Vector4<TestType> v{ TestType{1}, TestType{2}, TestType{3}, TestType{4}}; REQUIRE(v[0] == TestType{1}); REQUIRE(v[1] == TestType{2}); REQUIRE(v[2] == TestType{3}); REQUIRE(v[3] == TestType{4}); } SECTION("Const version: size 4") { const core::Vector4<TestType> v{ TestType{1}, TestType{2}, TestType{3}, TestType{4}}; REQUIRE(v[0] == TestType{1}); REQUIRE(v[1] == TestType{2}); REQUIRE(v[2] == TestType{3}); REQUIRE(v[3] == TestType{4}); } }
24.973333
79
0.533102
marovira
97530a740cbd510778a20901f769a6207c46fb76
2,688
cpp
C++
cpp/cpp/685. Redundant Connection II.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
3
2021-08-07T07:01:34.000Z
2021-08-07T07:03:02.000Z
cpp/cpp/685. Redundant Connection II.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
null
null
null
cpp/cpp/685. Redundant Connection II.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
null
null
null
// https://leetcode.com/problems/redundant-connection-ii/ // In this problem, a rooted tree is a directed graph such that, there is exactly // one node (the root) for which all other nodes are descendants of this node, plus // every node has exactly one parent, except for the root node which has no // parents. // The given input is a directed graph that started as a rooted tree with n nodes // (with distinct values from 1 to n), with one additional directed edge added. The // added edge has two different vertices chosen from 1 to n, and was not an edge // that already existed. // The resulting graph is given as a 2D-array of edges. Each element of edges is a // pair [ui, vi] that represents a directed edge connecting nodes ui and vi, where // ui is a parent of child vi. // Return an edge that can be removed so that the resulting graph is a rooted tree // of n nodes. If there are multiple answers, return the answer that occurs last in // the given 2D-array. //////////////////////////////////////////////////////////////////////////////// // union find not work, since edge has direction may cause cycle // search for node with two parents -> edgeA, edgeB // perform union find without edgeB // -> 1) if tree is valid, return edgeB // -> 2) if found a cycle return a) edgeA or the causing edge // -> 3) return edgeB class Solution { public: vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) { int n = edges.size(); vector<int> edgeA, edgeB; // search for node with two parents for (int i = 1; i <= n; ++i) parents[i] = 0; for (auto& edge : edges) { // (parent) edge[0] -> (child) edge[1] if (parents[edge[1]] == 0) { // new edge parents[edge[1]] = edge[0]; } else { // edge with two parents edgeA = {parents[edge[1]], edge[1]}; edgeB = edge; } } // union find without edgeB for (int i = 1; i <= n; ++i) parents[i] = i; for (auto& edge : edges) { if (edge == edgeB) continue; // skip edgeB if (!unionNodes(edge[0], edge[1])) { if (edgeA.empty()) return edge; return edgeA; } } return edgeB; } private: unordered_map<int, int> parents; int find(int x) { if (parents[x] != x) parents[x] = find(parents[x]); return parents[x]; } bool unionNodes(int x, int y) { // (parent) x -> (child) y int xP = find(x); if (xP == y) return false; // found a cycle int yP = find(y); if (xP != yP) parents[yP] = xP; return true; } };
38.4
83
0.579241
longwangjhu
97545d9fcf31e1ca0b370f0a32ea117b6cfedd49
3,899
cpp
C++
src/astra/astra_point.cpp
Delicode/astra
2654b99102b999a15d3221b0e5a11bb5291f7689
[ "Apache-2.0" ]
170
2015-10-20T08:31:16.000Z
2021-12-01T01:47:32.000Z
src/astra/astra_point.cpp
Delicode/astra
2654b99102b999a15d3221b0e5a11bb5291f7689
[ "Apache-2.0" ]
42
2015-10-20T23:20:17.000Z
2022-03-18T05:47:08.000Z
src/astra/astra_point.cpp
Delicode/astra
2654b99102b999a15d3221b0e5a11bb5291f7689
[ "Apache-2.0" ]
83
2015-10-22T14:53:00.000Z
2021-11-04T03:09:48.000Z
// This file is part of the Orbbec Astra SDK [https://orbbec3d.com] // Copyright (c) 2015 Orbbec 3D // // 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. // // Be excellent to each other. #include <astra_core/capi/astra_types.h> #include <astra/capi/astra_ctypes.h> #include "astra_generic_stream_api.hpp" #include <astra/capi/streams/point_capi.h> #include <astra/capi/streams/point_types.h> #include <astra/capi/streams/stream_types.h> #include <string.h> #include <cassert> #include <astra/capi/streams/image_capi.h> ASTRA_BEGIN_DECLS ASTRA_API_EX astra_status_t astra_reader_get_pointstream(astra_reader_t reader, astra_pointstream_t* pointStream) { return astra_reader_get_stream(reader, ASTRA_STREAM_COLOR, DEFAULT_SUBTYPE, pointStream); } ASTRA_API_EX astra_status_t astra_frame_get_pointframe(astra_reader_frame_t readerFrame, astra_pointframe_t* pointFrame) { return astra_reader_get_imageframe(readerFrame, ASTRA_STREAM_POINT, DEFAULT_SUBTYPE, pointFrame); } ASTRA_API_EX astra_status_t astra_frame_get_pointframe_with_subtype(astra_reader_frame_t readerFrame, astra_stream_subtype_t subtype, astra_pointframe_t* pointFrame) { return astra_reader_get_imageframe(readerFrame, ASTRA_STREAM_POINT, subtype, pointFrame); } ASTRA_API_EX astra_status_t astra_pointframe_get_frameindex(astra_pointframe_t pointFrame, astra_frame_index_t* index) { return astra_generic_frame_get_frameindex(pointFrame, index); } ASTRA_API_EX astra_status_t astra_pointframe_get_data_byte_length(astra_pointframe_t pointFrame, size_t* byteLength) { return astra_imageframe_get_data_byte_length(pointFrame, byteLength); } ASTRA_API_EX astra_status_t astra_pointframe_get_data_ptr(astra_pointframe_t pointFrame, astra_vector3f_t** data, size_t* byteLength) { void* voidData = nullptr; astra_imageframe_get_data_ptr(pointFrame, &voidData, byteLength); *data = static_cast<astra_vector3f_t*>(voidData); return ASTRA_STATUS_SUCCESS; } ASTRA_API_EX astra_status_t astra_pointframe_copy_data(astra_pointframe_t pointFrame, astra_vector3f_t* data) { return astra_imageframe_copy_data(pointFrame, data); } ASTRA_API_EX astra_status_t astra_pointframe_get_metadata(astra_pointframe_t pointFrame, astra_image_metadata_t* metadata) { return astra_imageframe_get_metadata(pointFrame, metadata); } ASTRA_END_DECLS
41.478723
108
0.595794
Delicode
97545f1944b626487fa100e059cfbcfc2a64195d
129
cpp
C++
dependencies/physx-4.1/source/geomutils/src/pcm/GuPCMContactSphereSphere.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/physx-4.1/source/geomutils/src/pcm/GuPCMContactSphereSphere.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/physx-4.1/source/geomutils/src/pcm/GuPCMContactSphereSphere.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:d16864b0d69d3a425328f013d6bb2842892c448c6a7cdc5077078ae6564113f8 size 3329
32.25
75
0.883721
realtehcman
975467ff92a3e30d15262dd5d6e95dc133ef5092
1,795
cpp
C++
ysu/test_common/testutil.cpp
lik2129/ysu_coin
47e40ed5d4000fc59566099929bd08a9ae16a4c1
[ "BSD-3-Clause" ]
null
null
null
ysu/test_common/testutil.cpp
lik2129/ysu_coin
47e40ed5d4000fc59566099929bd08a9ae16a4c1
[ "BSD-3-Clause" ]
null
null
null
ysu/test_common/testutil.cpp
lik2129/ysu_coin
47e40ed5d4000fc59566099929bd08a9ae16a4c1
[ "BSD-3-Clause" ]
null
null
null
#include <ysu/crypto_lib/random_pool.hpp> #include <ysu/node/testing.hpp> #include <ysu/test_common/testutil.hpp> #include <gtest/gtest.h> #include <cstdlib> #include <numeric> using namespace std::chrono_literals; /* Convenience constants for tests which are always on the test network */ namespace { ysu::ledger_constants dev_constants (ysu::ysu_networks::ysu_dev_network); } ysu::keypair const & ysu::zero_key (dev_constants.zero_key); ysu::keypair const & ysu::dev_genesis_key (dev_constants.dev_genesis_key); ysu::account const & ysu::ysu_dev_account (dev_constants.ysu_dev_account); std::string const & ysu::ysu_dev_genesis (dev_constants.ysu_dev_genesis); ysu::account const & ysu::genesis_account (dev_constants.genesis_account); ysu::block_hash const & ysu::genesis_hash (dev_constants.genesis_hash); ysu::uint128_t const & ysu::genesis_amount (dev_constants.genesis_amount); ysu::account const & ysu::burn_account (dev_constants.burn_account); void ysu::wait_peer_connections (ysu::system & system_a) { auto wait_peer_count = [&system_a](bool in_memory) { auto num_nodes = system_a.nodes.size (); system_a.deadline_set (20s); size_t peer_count = 0; while (peer_count != num_nodes * (num_nodes - 1)) { ASSERT_NO_ERROR (system_a.poll ()); peer_count = std::accumulate (system_a.nodes.cbegin (), system_a.nodes.cend (), std::size_t{ 0 }, [in_memory](auto total, auto const & node) { if (in_memory) { return total += node->network.size (); } else { auto transaction = node->store.tx_begin_read (); return total += node->store.peer_count (transaction); } }); } }; // Do a pre-pass with in-memory containers to reduce IO if still in the process of connecting to peers wait_peer_count (true); wait_peer_count (false); }
33.240741
145
0.732591
lik2129
975504aa4082edaf5699b688a1441696cf8721dc
24,484
cpp
C++
src/qt/transactiontablemodel.cpp
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
13
2019-01-23T04:36:05.000Z
2022-02-21T11:20:25.000Z
src/qt/transactiontablemodel.cpp
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
null
null
null
src/qt/transactiontablemodel.cpp
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
3
2019-01-24T07:48:15.000Z
2021-06-11T13:34:44.000Z
//此源码被清华学神尹成大魔王专业翻译分析并修改 //尹成QQ77025077 //尹成微信18510341407 //尹成所在QQ群721929980 //尹成邮箱 yinc13@mails.tsinghua.edu.cn //尹成毕业于清华大学,微软区块链领域全球最有价值专家 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 //版权所有(c)2011-2018比特币核心开发者 //根据MIT软件许可证分发,请参见随附的 //文件复制或http://www.opensource.org/licenses/mit-license.php。 #include <qt/transactiontablemodel.h> #include <qt/addresstablemodel.h> #include <qt/guiconstants.h> #include <qt/guiutil.h> #include <qt/optionsmodel.h> #include <qt/platformstyle.h> #include <qt/transactiondesc.h> #include <qt/transactionrecord.h> #include <qt/walletmodel.h> #include <core_io.h> #include <interfaces/handler.h> #include <interfaces/node.h> #include <sync.h> #include <uint256.h> #include <util/system.h> #include <validation.h> #include <QColor> #include <QDateTime> #include <QDebug> #include <QIcon> #include <QList> //金额列右对齐,包含数字 static int column_alignments[] = { /*:AlignLeft qt::AlignvCenter,/*状态*/ qt::AlignLeft qt::AlignvCenter,/*仅监视*/ /*:AlignLeft qt::AlignvCenter,/*日期*/ qt::AlignLeft qt::AlignvCenter,/*类型*/ /*:AlignLeft qt::AlignvCenter,/*地址*/ qt::AlignRight qt::AlignvCenter/*数量*/ }; //Tx型列表排序/二进制搜索的比较运算符 struct TxLessThan { bool operator()(const TransactionRecord &a, const TransactionRecord &b) const { return a.hash < b.hash; } bool operator()(const TransactionRecord &a, const uint256 &b) const { return a.hash < b; } bool operator()(const uint256 &a, const TransactionRecord &b) const { return a < b.hash; } }; //私有实施 class TransactionTablePriv { public: explicit TransactionTablePriv(TransactionTableModel *_parent) : parent(_parent) { } TransactionTableModel *parent; /*钱包的本地缓存。 *根据定义,它与cwallet的顺序相同。 *按sha256排序。 **/ QList<TransactionRecord> cachedWallet; /*从核心重新查询整个钱包。 **/ void refreshWallet(interfaces::Wallet& wallet) { qDebug() << "TransactionTablePriv::refreshWallet"; cachedWallet.clear(); { for (const auto& wtx : wallet.getWalletTxs()) { if (TransactionRecord::showTransaction()) { cachedWallet.append(TransactionRecord::decomposeTransaction(wtx)); } } } } /*逐步更新钱包模型,以同步钱包模型 和核心的那个。 调用已添加、删除或更改的事务。 **/ void updateWallet(interfaces::Wallet& wallet, const uint256 &hash, int status, bool showTransaction) { qDebug() << "TransactionTablePriv::updateWallet: " + QString::fromStdString(hash.ToString()) + " " + QString::number(status); //在模型中查找此事务的边界 QList<TransactionRecord>::iterator lower = qLowerBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); QList<TransactionRecord>::iterator upper = qUpperBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); int lowerIndex = (lower - cachedWallet.begin()); int upperIndex = (upper - cachedWallet.begin()); bool inModel = (lower != upper); if(status == CT_UPDATED) { if(showTransaction && !inModel) /*tus=ct_new;/*不在模型中,但要显示,视为新的*/ 如果(!)ShowTransaction和InModel) status=ct_deleted;/*在模型中,但要隐藏,视为已删除*/ } qDebug() << " inModel=" + QString::number(inModel) + " Index=" + QString::number(lowerIndex) + "-" + QString::number(upperIndex) + " showTransaction=" + QString::number(showTransaction) + " derivedStatus=" + QString::number(status); switch(status) { case CT_NEW: if(inModel) { qWarning() << "TransactionTablePriv::updateWallet: Warning: Got CT_NEW, but transaction is already in model"; break; } if(showTransaction) { //在钱包中查找交易 interfaces::WalletTx wtx = wallet.getWalletTx(hash); if(!wtx.tx) { qWarning() << "TransactionTablePriv::updateWallet: Warning: Got CT_NEW, but transaction is not in wallet"; break; } //添加--在正确位置插入 QList<TransactionRecord> toInsert = TransactionRecord::decomposeTransaction(wtx); /*!to insert.isEmpty())/*仅当要插入的内容时*/ { parent->beginInsertRows(qmodelIndex(),lowerindex,lowerindex+toinsert.size()-1); int insert_idx=lowerindex; 用于(const transactionrecord&rec:toinsert) { cachedWallet.insert(插入_idx,rec); 插入_idx+=1; } parent->endinsertrows(); } } 断裂; 删除的案例: 如果(!)内模) { qwarning()<“transactionTablepriv::updateWallet:warning:got ct_deleted,but transaction is not in model”; 断裂; } //已删除--从表中删除整个事务 parent->beginremoverws(qmodelindex(),lowerindex,upperindex-1); cachedWallet.erase(下,上); parent->endremoves(); 断裂; 案例CT更新: //其他更新——不做任何事情,状态更新将处理此问题,并且只计算 //可见事务。 对于(int i=lowerindex;i<upperindex;i++) transactionrecord*rec=&cachedwallet[i]; rec->status.needsupdate=true; } 断裂; } } int siz() { 返回cachedWallet.size(); } 交易记录*索引(接口::Wallet&Wallet,int IDX) { 如果(idx>=0&&idx<cachedWallet.size()) { transactionrecord*rec=&cachedwallet[idx]; //预先获取所需的锁。这样就避免了图形用户界面 //如果核心持有锁的时间更长,则会卡住- //例如,在钱包重新扫描期间。 / / //如果需要状态更新(自上次检查以来出现块), //从钱包更新此交易的状态。否则, //只需重新使用缓存状态。 接口::wallettxstatus wtx; int数字块; Int64阻塞时间; if(wallet.trygettxstatus(rec->hash,wtx,numblocks,block_time)&&rec->statusupdateeneeded(numblocks)); rec->updateStatus(wtx,numblocks,block_time); } 返回记录; } 返回null pTR; } qString描述(interfaces::node&node,interfaces::wallet&wallet,transactionrecord*rec,int unit) { 返回事务描述::tohtml(节点、钱包、记录、单位); } qstring gettxhex(接口::wallet&wallet,transactionrecord*rec) { auto tx=wallet.gettx(rec->hash); 如果(Tx){ std::string strhex=encodehextx(*tx); 返回qstring::fromstdstring(strhex); } 返回qString(); } }; TransactionTableModel::TransactionTableModel(const platformStyle*_platformStyle,walletModel*父级): QabstractTableModel(父级) 墙模型(父) priv(新交易表priv(this)), fprocessingQueuedTransactions(假), 平台样式(_PlatformStyle) { 列<<qString()<<qString()<<tr(“日期”)<<tr(“类型”)<<tr(“标签”)<<bitcoinUnits::getAmountColumnTitle(walletModel->getOptionsModel()->getDisplayUnit()); priv->refreshwallet(walletmodel->wallet()); Connect(walletModel->getOptionsModel(),&OptionsModel::DisplayUnitChanged,this,&TransactionTableModel::UpdateDisplayUnit); subscriptOCoreginals(); } TransactionTableModel::~TransactionTableModel()。 { 取消订阅coresignals(); 删除PRIV; } /**将列标题更新为“amount(displayUnit)”,并发出headerDataChanged()信号,以便表头作出反应。*/ void TransactionTableModel::updateAmountColumnTitle() { columns[Amount] = BitcoinUnits::getAmountColumnTitle(walletModel->getOptionsModel()->getDisplayUnit()); Q_EMIT headerDataChanged(Qt::Horizontal,Amount,Amount); } void TransactionTableModel::updateTransaction(const QString &hash, int status, bool showTransaction) { uint256 updated; updated.SetHex(hash.toStdString()); priv->updateWallet(walletModel->wallet(), updated, status, showTransaction); } void TransactionTableModel::updateConfirmations() { //自上次投票以来,出现了一些障碍。 //失效状态(确认数量)和(可能)描述 //对于所有行。qt足够智能,只实际请求 //可见行。 Q_EMIT dataChanged(index(0, Status), index(priv->size()-1, Status)); Q_EMIT dataChanged(index(0, ToAddress), index(priv->size()-1, ToAddress)); } int TransactionTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int TransactionTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QString TransactionTableModel::formatTxStatus(const TransactionRecord *wtx) const { QString status; switch(wtx->status.status) { case TransactionStatus::OpenUntilBlock: status = tr("Open for %n more block(s)","",wtx->status.open_for); break; case TransactionStatus::OpenUntilDate: status = tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx->status.open_for)); break; case TransactionStatus::Unconfirmed: status = tr("Unconfirmed"); break; case TransactionStatus::Abandoned: status = tr("Abandoned"); break; case TransactionStatus::Confirming: status = tr("Confirming (%1 of %2 recommended confirmations)").arg(wtx->status.depth).arg(TransactionRecord::RecommendedNumConfirmations); break; case TransactionStatus::Confirmed: status = tr("Confirmed (%1 confirmations)").arg(wtx->status.depth); break; case TransactionStatus::Conflicted: status = tr("Conflicted"); break; case TransactionStatus::Immature: status = tr("Immature (%1 confirmations, will be available after %2)").arg(wtx->status.depth).arg(wtx->status.depth + wtx->status.matures_in); break; case TransactionStatus::NotAccepted: status = tr("Generated but not accepted"); break; } return status; } QString TransactionTableModel::formatTxDate(const TransactionRecord *wtx) const { if(wtx->time) { return GUIUtil::dateTimeStr(wtx->time); } return QString(); } /*在通讯簿中查找地址,如果找到,则返回标签(地址) 否则只需返回(地址) **/ QString TransactionTableModel::lookupAddress(const std::string &address, bool tooltip) const { QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(address)); QString description; if(!label.isEmpty()) { description += label; } if(label.isEmpty() || tooltip) { description += QString(" (") + QString::fromStdString(address) + QString(")"); } return description; } QString TransactionTableModel::formatTxType(const TransactionRecord *wtx) const { switch(wtx->type) { case TransactionRecord::RecvWithAddress: return tr("Received with"); case TransactionRecord::RecvFromOther: return tr("Received from"); case TransactionRecord::SendToAddress: case TransactionRecord::SendToOther: return tr("Sent to"); case TransactionRecord::SendToSelf: return tr("Payment to yourself"); case TransactionRecord::Generated: return tr("Mined"); default: return QString(); } } QVariant TransactionTableModel::txAddressDecoration(const TransactionRecord *wtx) const { switch(wtx->type) { case TransactionRecord::Generated: return QIcon(":/icons/tx_mined"); case TransactionRecord::RecvWithAddress: case TransactionRecord::RecvFromOther: return QIcon(":/icons/tx_input"); case TransactionRecord::SendToAddress: case TransactionRecord::SendToOther: return QIcon(":/icons/tx_output"); default: return QIcon(":/icons/tx_inout"); } } QString TransactionTableModel::formatTxToAddress(const TransactionRecord *wtx, bool tooltip) const { QString watchAddress; if (tooltip) { //通过添加“(仅监视)”标记涉及仅监视地址的事务。 watchAddress = wtx->involvesWatchAddress ? QString(" (") + tr("watch-only") + QString(")") : ""; } switch(wtx->type) { case TransactionRecord::RecvFromOther: return QString::fromStdString(wtx->address) + watchAddress; case TransactionRecord::RecvWithAddress: case TransactionRecord::SendToAddress: case TransactionRecord::Generated: return lookupAddress(wtx->address, tooltip) + watchAddress; case TransactionRecord::SendToOther: return QString::fromStdString(wtx->address) + watchAddress; case TransactionRecord::SendToSelf: default: return tr("(n/a)") + watchAddress; } } QVariant TransactionTableModel::addressColor(const TransactionRecord *wtx) const { //以不太明显的颜色显示不带标签的地址 switch(wtx->type) { case TransactionRecord::RecvWithAddress: case TransactionRecord::SendToAddress: case TransactionRecord::Generated: { QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(wtx->address)); if(label.isEmpty()) return COLOR_BAREADDRESS; } break; case TransactionRecord::SendToSelf: return COLOR_BAREADDRESS; default: break; } return QVariant(); } QString TransactionTableModel::formatTxAmount(const TransactionRecord *wtx, bool showUnconfirmed, BitcoinUnits::SeparatorStyle separators) const { QString str = BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), wtx->credit + wtx->debit, false, separators); if(showUnconfirmed) { if(!wtx->status.countsForBalance) { str = QString("[") + str + QString("]"); } } return QString(str); } QVariant TransactionTableModel::txStatusDecoration(const TransactionRecord *wtx) const { switch(wtx->status.status) { case TransactionStatus::OpenUntilBlock: case TransactionStatus::OpenUntilDate: return COLOR_TX_STATUS_OPENUNTILDATE; case TransactionStatus::Unconfirmed: return QIcon(":/icons/transaction_0"); case TransactionStatus::Abandoned: return QIcon(":/icons/transaction_abandoned"); case TransactionStatus::Confirming: switch(wtx->status.depth) { case 1: return QIcon(":/icons/transaction_1"); case 2: return QIcon(":/icons/transaction_2"); case 3: return QIcon(":/icons/transaction_3"); case 4: return QIcon(":/icons/transaction_4"); default: return QIcon(":/icons/transaction_5"); }; case TransactionStatus::Confirmed: return QIcon(":/icons/transaction_confirmed"); case TransactionStatus::Conflicted: return QIcon(":/icons/transaction_conflicted"); case TransactionStatus::Immature: { int total = wtx->status.depth + wtx->status.matures_in; int part = (wtx->status.depth * 4 / total) + 1; return QIcon(QString(":/icons/transaction_%1").arg(part)); } case TransactionStatus::NotAccepted: return QIcon(":/icons/transaction_0"); default: return COLOR_BLACK; } } QVariant TransactionTableModel::txWatchonlyDecoration(const TransactionRecord *wtx) const { if (wtx->involvesWatchAddress) return QIcon(":/icons/eye"); else return QVariant(); } QString TransactionTableModel::formatTooltip(const TransactionRecord *rec) const { QString tooltip = formatTxStatus(rec) + QString("\n") + formatTxType(rec); if(rec->type==TransactionRecord::RecvFromOther || rec->type==TransactionRecord::SendToOther || rec->type==TransactionRecord::SendToAddress || rec->type==TransactionRecord::RecvWithAddress) { tooltip += QString(" ") + formatTxToAddress(rec, true); } return tooltip; } QVariant TransactionTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); TransactionRecord *rec = static_cast<TransactionRecord*>(index.internalPointer()); switch(role) { case RawDecorationRole: switch(index.column()) { case Status: return txStatusDecoration(rec); case Watchonly: return txWatchonlyDecoration(rec); case ToAddress: return txAddressDecoration(rec); } break; case Qt::DecorationRole: { QIcon icon = qvariant_cast<QIcon>(index.data(RawDecorationRole)); return platformStyle->TextColorIcon(icon); } case Qt::DisplayRole: switch(index.column()) { case Date: return formatTxDate(rec); case Type: return formatTxType(rec); case ToAddress: return formatTxToAddress(rec, false); case Amount: return formatTxAmount(rec, true, BitcoinUnits::separatorAlways); } break; case Qt::EditRole: //编辑角色用于排序,因此返回未格式化的值 switch(index.column()) { case Status: return QString::fromStdString(rec->status.sortKey); case Date: return rec->time; case Type: return formatTxType(rec); case Watchonly: return (rec->involvesWatchAddress ? 1 : 0); case ToAddress: return formatTxToAddress(rec, true); case Amount: return qint64(rec->credit + rec->debit); } break; case Qt::ToolTipRole: return formatTooltip(rec); case Qt::TextAlignmentRole: return column_alignments[index.column()]; case Qt::ForegroundRole: //对放弃的交易使用“危险”颜色 if(rec->status.status == TransactionStatus::Abandoned) { return COLOR_TX_STATUS_DANGER; } //未确认(但不未成熟),因为交易是灰色的 if(!rec->status.countsForBalance && rec->status.status != TransactionStatus::Immature) { return COLOR_UNCONFIRMED; } if(index.column() == Amount && (rec->credit+rec->debit) < 0) { return COLOR_NEGATIVE; } if(index.column() == ToAddress) { return addressColor(rec); } break; case TypeRole: return rec->type; case DateRole: return QDateTime::fromTime_t(static_cast<uint>(rec->time)); case WatchonlyRole: return rec->involvesWatchAddress; case WatchonlyDecorationRole: return txWatchonlyDecoration(rec); case LongDescriptionRole: return priv->describe(walletModel->node(), walletModel->wallet(), rec, walletModel->getOptionsModel()->getDisplayUnit()); case AddressRole: return QString::fromStdString(rec->address); case LabelRole: return walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(rec->address)); case AmountRole: return qint64(rec->credit + rec->debit); case TxHashRole: return rec->getTxHash(); case TxHexRole: return priv->getTxHex(walletModel->wallet(), rec); case TxPlainTextRole: { QString details; QDateTime date = QDateTime::fromTime_t(static_cast<uint>(rec->time)); QString txLabel = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(rec->address)); details.append(date.toString("M/d/yy HH:mm")); details.append(" "); details.append(formatTxStatus(rec)); details.append(". "); if(!formatTxType(rec).isEmpty()) { details.append(formatTxType(rec)); details.append(" "); } if(!rec->address.empty()) { if(txLabel.isEmpty()) details.append(tr("(no label)") + " "); else { details.append("("); details.append(txLabel); details.append(") "); } details.append(QString::fromStdString(rec->address)); details.append(" "); } details.append(formatTxAmount(rec, false, BitcoinUnits::separatorNever)); return details; } case ConfirmedRole: return rec->status.countsForBalance; case FormattedAmountRole: //用于复制/导出,因此不包括分隔符 return formatTxAmount(rec, false, BitcoinUnits::separatorNever); case StatusRole: return rec->status.status; } return QVariant(); } QVariant TransactionTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole) { return columns[section]; } else if (role == Qt::TextAlignmentRole) { return column_alignments[section]; } else if (role == Qt::ToolTipRole) { switch(section) { case Status: return tr("Transaction status. Hover over this field to show number of confirmations."); case Date: return tr("Date and time that the transaction was received."); case Type: return tr("Type of transaction."); case Watchonly: return tr("Whether or not a watch-only address is involved in this transaction."); case ToAddress: return tr("User-defined intent/purpose of the transaction."); case Amount: return tr("Amount removed from or added to balance."); } } } return QVariant(); } QModelIndex TransactionTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); TransactionRecord *data = priv->index(walletModel->wallet(), row); if(data) { return createIndex(row, column, priv->index(walletModel->wallet(), row)); } return QModelIndex(); } void TransactionTableModel::updateDisplayUnit() { //发出datachanged以使用当前单位更新amount列 updateAmountColumnTitle(); Q_EMIT dataChanged(index(0, Amount), index(priv->size()-1, Amount)); } //排队通知以显示非冻结进度对话框,例如用于重新扫描 struct TransactionNotification { public: TransactionNotification() {} TransactionNotification(uint256 _hash, ChangeType _status, bool _showTransaction): hash(_hash), status(_status), showTransaction(_showTransaction) {} void invoke(QObject *ttm) { QString strHash = QString::fromStdString(hash.GetHex()); qDebug() << "NotifyTransactionChanged: " + strHash + " status= " + QString::number(status); QMetaObject::invokeMethod(ttm, "updateTransaction", Qt::QueuedConnection, Q_ARG(QString, strHash), Q_ARG(int, status), Q_ARG(bool, showTransaction)); } private: uint256 hash; ChangeType status; bool showTransaction; }; static bool fQueueNotifications = false; static std::vector< TransactionNotification > vQueueNotifications; static void NotifyTransactionChanged(TransactionTableModel *ttm, const uint256 &hash, ChangeType status) { //在钱包中查找交易 //确定是否显示事务(在这里确定,以便在GUI线程中不需要重新锁定) bool showTransaction = TransactionRecord::showTransaction(); TransactionNotification notification(hash, status, showTransaction); if (fQueueNotifications) { vQueueNotifications.push_back(notification); return; } notification.invoke(ttm); } static void ShowProgress(TransactionTableModel *ttm, const std::string &title, int nProgress) { if (nProgress == 0) fQueueNotifications = true; if (nProgress == 100) { fQueueNotifications = false; if (vQueueNotifications.size() > 10) //防止气球垃圾邮件,最多显示10个气球 QMetaObject::invokeMethod(ttm, "setProcessingQueuedTransactions", Qt::QueuedConnection, Q_ARG(bool, true)); for (unsigned int i = 0; i < vQueueNotifications.size(); ++i) { if (vQueueNotifications.size() - i <= 10) QMetaObject::invokeMethod(ttm, "setProcessingQueuedTransactions", Qt::QueuedConnection, Q_ARG(bool, false)); vQueueNotifications[i].invoke(ttm); } std::vector<TransactionNotification >().swap(vQueueNotifications); //清楚的 } } void TransactionTableModel::subscribeToCoreSignals() { //将信号连接到钱包 m_handler_transaction_changed = walletModel->wallet().handleTransactionChanged(std::bind(NotifyTransactionChanged, this, std::placeholders::_1, std::placeholders::_2)); m_handler_show_progress = walletModel->wallet().handleShowProgress(std::bind(ShowProgress, this, std::placeholders::_1, std::placeholders::_2)); } void TransactionTableModel::unsubscribeFromCoreSignals() { //断开钱包信号 m_handler_transaction_changed->disconnect(); m_handler_show_progress->disconnect(); }
31.592258
172
0.628247
yinchengtsinghua
97562bbcc8ce6931c6929edab6d5e82527117d3a
4,330
cpp
C++
test/MutationTest.cpp
ATsahikian/PeProtector
4e005ea636a5679b82c9e58e09a0de53618896c5
[ "MIT" ]
43
2016-07-30T13:50:21.000Z
2021-06-17T22:45:00.000Z
test/MutationTest.cpp
ATsahikian/pe-protector
4e005ea636a5679b82c9e58e09a0de53618896c5
[ "MIT" ]
null
null
null
test/MutationTest.cpp
ATsahikian/pe-protector
4e005ea636a5679b82c9e58e09a0de53618896c5
[ "MIT" ]
16
2016-09-08T09:10:27.000Z
2020-06-14T00:30:59.000Z
#define BOOST_TEST_MODULE mutation test #include <boost/test/included/unit_test.hpp> #include "pe-protector/Mutation.h" using namespace NPeProtector; BOOST_AUTO_TEST_SUITE(MutationTest); // method for testing mutateCommands with Mov instruction BOOST_AUTO_TEST_CASE(testMutateCommandsMov) { // create command for testing "MOV EAX, EBX" SOperand operand1; operand1.mType = NOperand::REG32; operand1.mRegister = NRegister::EAX; SOperand operand2; operand2.mType = NOperand::REG32; operand2.mRegister = NRegister::EBX; SInstruction instruction{ NPrefix::NON, NInstruction::MOV, {operand1, operand2}}; SCommand movCommand; movCommand.mType = NCommand::INSTRUCTION; movCommand.mInstruction = instruction; std::vector<SCommand> commands = {movCommand}; // pass command "MOV EAX, EBX" mutateCommands(commands); // create instruction "PUSH EBX" SCommand pushCommand; pushCommand.mType = NCommand::INSTRUCTION; pushCommand.mInstruction.mType = NInstruction::PUSH; pushCommand.mInstruction.mOperands.push_back(operand2); // create instruction "POP EAX" SCommand popCommand; popCommand.mType = NCommand::INSTRUCTION; popCommand.mInstruction.mType = NInstruction::POP; popCommand.mInstruction.mOperands.push_back(operand1); std::vector<SCommand> expectedResult = {pushCommand, popCommand}; // compare results BOOST_TEST(expectedResult[0].mType == commands[0].mType); BOOST_TEST(expectedResult[0].mInstruction.mType == commands[0].mInstruction.mType); BOOST_TEST(expectedResult[0].mInstruction.mOperands[0].mType == commands[0].mInstruction.mOperands[0].mType); BOOST_TEST(expectedResult[0].mInstruction.mOperands[0].mRegister == commands[0].mInstruction.mOperands[0].mRegister); BOOST_TEST(expectedResult[1].mType == commands[1].mType); BOOST_TEST(expectedResult[1].mInstruction.mType == commands[1].mInstruction.mType); BOOST_TEST(expectedResult[1].mInstruction.mOperands[0].mType == commands[1].mInstruction.mOperands[0].mType); BOOST_TEST(expectedResult[1].mInstruction.mOperands[0].mRegister == commands[1].mInstruction.mOperands[0].mRegister); } // method for testing mutateCommands with Push instruction BOOST_AUTO_TEST_CASE(testMutateCommandsPush) { // create instruction "PUSH EAX" SOperand operand1; operand1.mType = NOperand::REG32; operand1.mRegister = NRegister::EAX; SInstruction instruction{NPrefix::NON, NInstruction::PUSH, {operand1}}; SCommand pushCommand; pushCommand.mType = NCommand::INSTRUCTION; pushCommand.mInstruction = instruction; std::vector<SCommand> commands = {pushCommand}; // pass instruction "PUSH EAX" mutateCommands(commands); // create instruction "SUB ESP, 4" SCommand subCommand; subCommand.mType = NCommand::INSTRUCTION; subCommand.mInstruction.mType = NInstruction::SUB; SOperand espOperand; espOperand.mType = NOperand::REG32; espOperand.mRegister = NRegister::ESP; subCommand.mInstruction.mOperands.push_back(espOperand); SOperand constOperand; constOperand.mType = NOperand::CONSTANT; constOperand.mConstant.mValue = 4; subCommand.mInstruction.mOperands.push_back(constOperand); // create instruction "MOV DWORD PTR [ESP], EAX" SCommand movCommand; movCommand.mType = NCommand::INSTRUCTION; movCommand.mInstruction.mType = NInstruction::MOV; SOperand memOperand; memOperand.mType = NOperand::MEM32; memOperand.mMemory.mRegisters.push_back(NRegister::ESP); movCommand.mInstruction.mOperands.push_back(memOperand); movCommand.mInstruction.mOperands.push_back(operand1); std::vector<SCommand> expectedResult = {subCommand, movCommand}; // compare results BOOST_TEST(expectedResult[0].mType == commands[0].mType); BOOST_TEST(expectedResult[0].mInstruction.mType == commands[0].mInstruction.mType); BOOST_TEST(expectedResult[0].mInstruction.mOperands[0].mType == commands[0].mInstruction.mOperands[0].mType); BOOST_TEST(expectedResult[1].mType == commands[1].mType); BOOST_TEST(expectedResult[1].mInstruction.mType == commands[1].mInstruction.mType); BOOST_TEST(expectedResult[1].mInstruction.mOperands[0].mType == commands[1].mInstruction.mOperands[0].mType); } BOOST_AUTO_TEST_SUITE_END();
34.365079
73
0.748037
ATsahikian
9759ce0c8aec21542ab1727ba287d9376bdd192c
606
cpp
C++
src/vkfw_core/gfx/vk/pipeline/ComputePipeline.cpp
dasmysh/VulkanFramework_Lib
baeaeb3158d23187f2ffa5044e32d8a5145284aa
[ "MIT" ]
null
null
null
src/vkfw_core/gfx/vk/pipeline/ComputePipeline.cpp
dasmysh/VulkanFramework_Lib
baeaeb3158d23187f2ffa5044e32d8a5145284aa
[ "MIT" ]
null
null
null
src/vkfw_core/gfx/vk/pipeline/ComputePipeline.cpp
dasmysh/VulkanFramework_Lib
baeaeb3158d23187f2ffa5044e32d8a5145284aa
[ "MIT" ]
null
null
null
/** * @file ComputePipeline.cpp * @author Sebastian Maisch <sebastian.maisch@googlemail.com> * @date 2016.10.30 * * @brief Implementation of a vulkan compute pipeline object. */ #include "gfx/vk/pipeline/ComputePipeline.h" #include "gfx/vk/LogicalDevice.h" #include "core/resources/ShaderManager.h" namespace vkfw_core::gfx { ComputePipeline::ComputePipeline(const std::string& shaderStageId, gfx::LogicalDevice* device) : Resource(shaderStageId, device) { throw std::runtime_error("NOT YET IMPLEMENTED!"); } ComputePipeline::~ComputePipeline() = default; }
25.25
100
0.709571
dasmysh
975cebfc63316babaaa98c51f6a47676e5c47673
169
cpp
C++
Generic/VSC.cpp
jbat100/VirtualSoundControl
f84ba15bba4bfce579c185e04df0e1be4f419cd7
[ "MIT" ]
null
null
null
Generic/VSC.cpp
jbat100/VirtualSoundControl
f84ba15bba4bfce579c185e04df0e1be4f419cd7
[ "MIT" ]
null
null
null
Generic/VSC.cpp
jbat100/VirtualSoundControl
f84ba15bba4bfce579c185e04df0e1be4f419cd7
[ "MIT" ]
null
null
null
#include "VSC.h" #include <boost/date_time/posix_time/posix_time.hpp> VSC::Time VSC::CurrentTime() { return boost::posix_time::microsec_clock::universal_time(); }
18.777778
63
0.739645
jbat100
975e930eb1006c6956faf01e14b61bb51426f222
6,452
hpp
C++
include/cbr_drivers/v4l2_driver.hpp
yamaha-bps/cbr_drivers
64e971c0a7e79c414e81fe2ac32e6360adb266eb
[ "MIT" ]
null
null
null
include/cbr_drivers/v4l2_driver.hpp
yamaha-bps/cbr_drivers
64e971c0a7e79c414e81fe2ac32e6360adb266eb
[ "MIT" ]
null
null
null
include/cbr_drivers/v4l2_driver.hpp
yamaha-bps/cbr_drivers
64e971c0a7e79c414e81fe2ac32e6360adb266eb
[ "MIT" ]
null
null
null
// Copyright Yamaha 2021 // MIT License // https://github.com/yamaha-bps/cbr_drivers/blob/master/LICENSE #ifndef CBR_DRIVERS__V4L2_DRIVER_HPP_ #define CBR_DRIVERS__V4L2_DRIVER_HPP_ #include <linux/videodev2.h> #include <atomic> #include <functional> #include <memory> #include <mutex> #include <string> #include <thread> #include <utility> #include <vector> #include <iostream> namespace cbr { class V4L2Driver { public: /** * Helper structures for interfacing with the driver */ struct buffer_t { void * pos; // memory location of buffer std::size_t len; // size in bytes }; struct format_t { std::string format; uint32_t width, height; float fps; }; enum class ctrl_type { INTEGER = V4L2_CTRL_TYPE_INTEGER, BOOLEAN = V4L2_CTRL_TYPE_BOOLEAN, MENU = V4L2_CTRL_TYPE_MENU }; struct ival_t { int32_t minimum; int32_t maximum; int32_t step; }; struct menu_entry_t { uint32_t index; std::string name; }; struct ctrl_t { uint32_t id; ctrl_type type; std::string name; int32_t def; // default value ival_t ival; // only populated for INTEGER, BOOLEAN std::vector<menu_entry_t> menu; // ony populated for MENU }; /** * @brief v4l2 driver for capturing image streams * * This driver is flexible in terms of management: a user can supply a callback * that is called on frames containing new buffers, and also custom allocation and * de-allocation functions for allocating said buffers. * * If no allocation functions are provided malloc()/free() is used. * * @param device the v4l object (default /dev/video0) * @param n_buf the number of buffers to use (default 4) */ explicit V4L2Driver(std::string device = "/dev/video0", uint32_t n_buf = 4); V4L2Driver(const V4L2Driver &) = delete; V4L2Driver & operator=(const V4L2Driver & other) = delete; V4L2Driver(V4L2Driver &&) = delete; V4L2Driver & operator=(V4L2Driver &&) = delete; ~V4L2Driver(); /** * @brief Set the callback * * NOTE: the callback should return quickly or frames will be missed * * The callback should have signature * void(const uint8_t *, const v4l2_pix_format &) * and is called on every new frame. */ template<typename T> void set_callback(T && cb) { cb_ = std::forward<T>(cb); } /** * @brief Set a custom allocator * * NOTE: Use only in conjuction with set_custom_deallocator * * The allocator should have signature * void *(std::size_t) * * The returned pointer is freed with the custom deallocator */ template<typename T> void set_custom_allocator(T && cb) { custom_alloc_ = std::forward<T>(cb); } /** * @brief Set a custom deallocator * * NOTE: Use only in conjuction with set_custom_allocator * * The deallocator should have signature * void(void *, std::size_t) */ template<typename T> void set_custom_deallocator(T && cb) { custom_dealloc_ = std::forward<T>(cb); } /** * @brief Initialize the driver and start capturing */ bool start(); /** * @brief Stop capturing and de-initialize the driver */ void stop(); /** * @brief Get current fps */ float get_fps(); /** * @brief List all formats supported by the device */ std::vector<format_t> list_formats(); /** * @brief Get active video format */ v4l2_pix_format get_format(); /** * @brief Request a format from v4l2 * * @param width desired frame pixel width * @param height desired frame pixel height * @param fps desired fps * @param fourcc desired image format in fourcc format (must be string with four characters) */ bool set_format(uint32_t width, uint32_t height, uint32_t fps, std::string fourcc = "YUYV"); /** * @brief List controls for the device */ std::vector<ctrl_t> list_controls(); /** * @brief Get control value for the device * * @param id control identifier * @returns the value of the control */ std::optional<int32_t> get_control(uint32_t id); /** * @brief Set control for the device * * @param id control identifier * @param value desired value for control * * @return the new value of the control (should be equal to value) */ bool set_control(uint32_t id, int32_t value); /** * @brief One-way uvc write * @param unit uvc unit (device-specific) * @param control_selector uvc control selector (device-specific) * @param buf buffer to send over UVC (length 384 for USB3, length 64 for USB2) */ bool uvc_set(uint8_t unit, uint8_t control_selector, std::vector<uint8_t> & buf); /** * @brief Two-way uvc communication (write followed by read) * @param unit uvc unit (device-specific) * @param control_selector uvc control selector (device-specific) * @param buf buffer to send over UVC (length 384 for USB3, length 64 for USB2) * * The result is written into buf in accordance with the device protocol */ bool uvc_set_get(uint8_t unit, uint8_t control_selector, std::vector<uint8_t> & buf); protected: /** * @brief Internal method to read the current frame format from V4L2 */ bool update_format(); /** * @brief Internal method for capturing frames */ bool capture_frame(); /** * @brief Internal method that runs in the streaming thread */ void streaming_fcn(); /** * @brief Wrapper around system ioctl call */ int xioctl(uint64_t request, void * arg); protected: uint32_t n_buf_; std::atomic<bool> running_{false}; std::mutex fd_mtx_; int fd_{0}; // file descriptor handle // user buffers that v4l writes into std::vector<buffer_t> buffers_{}; // current device configuration v4l2_pix_format fmt_cur_{}; float fps_{}; std::thread streaming_thread_; std::optional<std::function<void(const uint8_t *, const std::chrono::nanoseconds &, const v4l2_pix_format &)>> cb_{std::nullopt}; std::optional<std::function<void *(std::size_t)>> custom_alloc_{std::nullopt}; std::optional<std::function<void(void *, std::size_t)>> custom_dealloc_{std::nullopt}; }; /** * @brief Convert fourcc code to string */ inline static std::string fourcc_to_str(uint32_t fourcc) { std::string ret(' ', 4); for (uint32_t i = 0; i < 4; ++i) { ret[i] = ((fourcc >> (i * 8)) & 0xFF); } return ret; } } // namespace cbr #endif // CBR_DRIVERS__V4L2_DRIVER_HPP_
23.720588
94
0.6677
yamaha-bps
975ed7bf6d419192ca9632a124ac2c327956a8d4
3,797
cpp
C++
tests/ModulesFactoryTest.cpp
transdz/mesos-command-modules
5eba42137e33a1001fd1e1de9a2086f60eebe5bb
[ "Apache-2.0" ]
3
2018-05-18T19:06:27.000Z
2020-07-07T17:17:51.000Z
tests/ModulesFactoryTest.cpp
transdz/mesos-command-modules
5eba42137e33a1001fd1e1de9a2086f60eebe5bb
[ "Apache-2.0" ]
15
2018-04-25T17:41:36.000Z
2019-11-20T16:06:20.000Z
tests/ModulesFactoryTest.cpp
transdz/mesos-command-modules
5eba42137e33a1001fd1e1de9a2086f60eebe5bb
[ "Apache-2.0" ]
5
2018-04-03T09:12:29.000Z
2022-02-21T11:37:04.000Z
#include "ModulesFactory.hpp" #include <gtest/gtest.h> #include "CommandHook.hpp" #include "CommandIsolator.hpp" using namespace criteo::mesos; // *************************************** // **************** Hook ***************** // *************************************** TEST(ModulesFactoryTest, should_create_hook_with_correct_parameters) { ::mesos::Parameters parameters; auto var = parameters.add_parameter(); var->set_key("module_name"); var->set_value("test"); var = parameters.add_parameter(); var->set_key("hook_slave_run_task_label_decorator_command"); var->set_value("command_slave_run_task_label_decorator"); var = parameters.add_parameter(); var->set_key("hook_slave_executor_environment_decorator_command"); var->set_value("command_slave_executor_environment_decorator"); var = parameters.add_parameter(); var->set_key("hook_slave_remove_executor_hook_command"); var->set_value("command_slave_remove_executor_hook"); std::unique_ptr<CommandHook> hook( dynamic_cast<CommandHook*>(createHook(parameters))); ASSERT_EQ(hook->runTaskLabelCommand().get(), Command("command_slave_run_task_label_decorator", 30)); ASSERT_EQ(hook->executorEnvironmentCommand().get(), Command("command_slave_executor_environment_decorator", 30)); ASSERT_EQ(hook->removeExecutorCommand().get(), Command("command_slave_remove_executor_hook", 30)); } TEST(ModulesFactoryTest, should_create_hook_with_empty_parameters) { ::mesos::Parameters parameters; auto var = parameters.add_parameter(); var->set_key("module_name"); var->set_value("test"); var = parameters.add_parameter(); var->set_key("hook_slave_executor_environment_decorator_command"); var->set_value("command_slave_executor_environment_decorator"); std::unique_ptr<CommandHook> hook( dynamic_cast<CommandHook*>(createHook(parameters))); ASSERT_TRUE(hook->runTaskLabelCommand().isNone()); ASSERT_EQ(hook->executorEnvironmentCommand().get(), Command("command_slave_executor_environment_decorator", 30)); ASSERT_TRUE(hook->removeExecutorCommand().isNone()); } // *************************************** // ************** Isolator *************** // *************************************** TEST(ModulesFactoryTest, should_create_isolator_with_correct_parameters) { ::mesos::Parameters parameters; auto var = parameters.add_parameter(); var->set_key("module_name"); var->set_value("test"); var = parameters.add_parameter(); var->set_key("isolator_prepare_command"); var->set_value("command_prepare"); var = parameters.add_parameter(); var->set_key("isolator_isolate_command"); var->set_value("command_isolate"); var = parameters.add_parameter(); var->set_key("isolator_cleanup_command"); var->set_value("command_cleanup"); std::unique_ptr<CommandIsolator> isolator( dynamic_cast<CommandIsolator*>(createIsolator(parameters))); ASSERT_EQ(isolator->prepareCommand().get(), Command("command_prepare", 30)); ASSERT_EQ(isolator->isolateCommand().get(), Command("command_isolate", 30)); ASSERT_EQ(isolator->cleanupCommand().get(), Command("command_cleanup", 30)); } TEST(ModulesFactoryTest, should_create_isolator_with_empty_parameters) { ::mesos::Parameters parameters; auto var = parameters.add_parameter(); var->set_key("module_name"); var->set_value("test"); var = parameters.add_parameter(); var->set_key("isolator_prepare_command"); var->set_value("command_prepare"); std::unique_ptr<CommandIsolator> isolator( dynamic_cast<CommandIsolator*>(createIsolator(parameters))); ASSERT_EQ(isolator->prepareCommand().get(), Command("command_prepare", 30)); ASSERT_TRUE(isolator->cleanupCommand().isNone()); ASSERT_TRUE(isolator->isolateCommand().isNone()); }
35.485981
78
0.709244
transdz
975fadcee50dd19822b817bae9019daf61fc3ee1
788
cc
C++
examples/omnet_module/src/AvensClient.cc
Hyodar/pairsim-cpp
86c1613b9bc2b0043e468abfe59fc1355619164c
[ "MIT" ]
null
null
null
examples/omnet_module/src/AvensClient.cc
Hyodar/pairsim-cpp
86c1613b9bc2b0043e468abfe59fc1355619164c
[ "MIT" ]
null
null
null
examples/omnet_module/src/AvensClient.cc
Hyodar/pairsim-cpp
86c1613b9bc2b0043e468abfe59fc1355619164c
[ "MIT" ]
null
null
null
#include "./XPlaneModel.h" #include "PairsimClient.h" Define_Module(PairsimClient); PairsimClient::PairsimClient() { tickTimeout = nullptr; } PairsimClient::~PairsimClient() { cancelAndDelete(tickTimeout); } void PairsimClient::initialize() { tickTimeout = new cMessage("tick"); client.setServerAddr("tcp://localhost:4001"); client.setTickDuration(std::chrono::seconds(1)); client.setModel(std::make_shared<XPlaneModel>(this)); EV << "Setup completed." << std::endl; client.setup(); scheduleAt(simTime() + (static_cast<double>(client.getTickDuration().count())) / 1000, tickTimeout); } void PairsimClient::handleMessage(cMessage *msg) { client.tick(); scheduleAt(simTime() + ((double) client.getTickDuration().count()) / 1000, msg); }
24.625
104
0.694162
Hyodar
9765efe8e7544ab882e9e5264173796a133f3e0d
2,114
hpp
C++
include/felspar/coro/cancellable.hpp
Felspar/coro
67028cc10d7f66edc75229d4f4207cd8f6b82147
[ "BSL-1.0" ]
27
2021-02-15T00:02:12.000Z
2022-03-24T04:34:17.000Z
include/felspar/coro/cancellable.hpp
Felspar/coro
67028cc10d7f66edc75229d4f4207cd8f6b82147
[ "BSL-1.0" ]
2
2021-02-23T01:04:19.000Z
2022-03-24T04:38:10.000Z
include/felspar/coro/cancellable.hpp
Felspar/coro
67028cc10d7f66edc75229d4f4207cd8f6b82147
[ "BSL-1.0" ]
1
2022-02-20T09:41:09.000Z
2022-02-20T09:41:09.000Z
#pragma once #include <felspar/coro/coroutine.hpp> namespace felspar::coro { /** * Wait at the suspension point until resumed from an external location. */ class cancellable { coroutine_handle<> continuation = {}; bool signalled = false; void resume_if_needed() { if (continuation) { std::exchange(continuation, {}).resume(); } } public: /// Used externally to cancel the controlled coroutine void cancel() { signalled = true; resume_if_needed(); } bool cancelled() const noexcept { return signalled; } /// Wrap an awaitable so that an early resumption can be signalled template<typename A> auto signal_or(A coro_awaitable) { struct awaitable { A a; cancellable &b; bool await_ready() const noexcept { return b.signalled or a.await_ready(); } auto await_suspend(coroutine_handle<> h) noexcept { /// `h` is the coroutine making use of the `cancellable` b.continuation = h; return a.await_suspend(h); } auto await_resume() -> decltype(std::declval<A>().await_resume()) { if (b.signalled) { return {}; } else { return a.await_resume(); } } }; return awaitable{std::move(coro_awaitable), *this}; } /// This can be directly awaited until signalled auto operator co_await() { struct awaitable { cancellable &b; bool await_ready() const noexcept { return b.signalled; } auto await_suspend(coroutine_handle<> h) noexcept { b.continuation = h; } auto await_resume() noexcept {} }; return awaitable{*this}; } }; }
28.958904
76
0.487228
Felspar
97660134541a53225eb378fe906c3d3842bd97d8
9,027
hpp
C++
src/common/channel/codec/redis_reply.hpp
vorjdux/ardb
8d32d36243dc2a8cbdc218f4218aa988fbcb5eae
[ "BSD-3-Clause" ]
1,513
2015-01-02T17:36:20.000Z
2022-03-21T00:10:17.000Z
src/common/channel/codec/redis_reply.hpp
vorjdux/ardb
8d32d36243dc2a8cbdc218f4218aa988fbcb5eae
[ "BSD-3-Clause" ]
335
2015-01-02T21:48:21.000Z
2022-01-31T23:10:46.000Z
src/common/channel/codec/redis_reply.hpp
vorjdux/ardb
8d32d36243dc2a8cbdc218f4218aa988fbcb5eae
[ "BSD-3-Clause" ]
281
2015-01-08T01:23:41.000Z
2022-03-26T12:31:41.000Z
/* *Copyright (c) 2013-2013, yinqiwen <yinqiwen@gmail.com> *All rights reserved. * *Redistribution and use in source and binary forms, with or without *modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * *THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" *AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE *IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS *BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR *CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF *SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS *INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN *CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) *ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF *THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef REDIS_REPLY_HPP_ #define REDIS_REPLY_HPP_ #include "common.hpp" #include "types.hpp" #include <deque> #include <vector> #include <string> #define REDIS_REPLY_STRING 1 #define REDIS_REPLY_ARRAY 2 #define REDIS_REPLY_INTEGER 3 #define REDIS_REPLY_NIL 4 #define REDIS_REPLY_STATUS 5 #define REDIS_REPLY_ERROR 6 #define REDIS_REPLY_DOUBLE 1001 #define FIRST_CHUNK_FLAG 0x01 #define LAST_CHUNK_FLAG 0x02 #define STORAGE_ENGINE_ERR_OFFSET -100000 namespace ardb { namespace codec { enum ErrorCode { //STATUS_OK = 0, ERR_ENTRY_NOT_EXIST = -1000, ERR_INVALID_INTEGER_ARGS = -1001, ERR_INVALID_FLOAT_ARGS = -1002, ERR_INVALID_SYNTAX = -1003, ERR_AUTH_FAILED = -1004, ERR_NOTPERFORMED = -1005, ERR_STRING_EXCEED_LIMIT = -1006, ERR_NOSCRIPT = -1007, ERR_BIT_OFFSET_OUTRANGE = -1008, ERR_BIT_OUTRANGE = -1009, ERR_CORRUPTED_HLL_OBJECT = -1010, ERR_INVALID_HLL_STRING = -1011, ERR_SCORE_NAN = -1012, ERR_EXEC_ABORT = -1013, ERR_UNSUPPORT_DIST_UNIT = -1014, ERR_NOREPLICAS = -1015, ERR_READONLY_SLAVE = -1016, ERR_MASTER_DOWN = -1017, ERR_LOADING = -1018, ERR_NOTSUPPORTED = -1019, ERR_INVALID_ARGS = -1020, ERR_KEY_EXIST = -1021, ERR_WRONG_TYPE = -1022, ERR_OUTOFRANGE = -1023, }; enum StatusCode { STATUS_OK = 1000, STATUS_PONG = 1001, STATUS_QUEUED = 1002, STATUS_NOKEY = 1003, }; struct RedisDumpFileChunk { int64 len; uint32 flag; std::string chunk; RedisDumpFileChunk() : len(0), flag(0) { } bool IsLastChunk() { return (flag & LAST_CHUNK_FLAG) == (LAST_CHUNK_FLAG); } bool IsFirstChunk() { return (flag & FIRST_CHUNK_FLAG) == (FIRST_CHUNK_FLAG); } }; class RedisReplyPool; struct RedisReply { private: public: int type; std::string str; /* * If the type is REDIS_REPLY_STRING, and the str's length is large, * the integer value also used to identify chunk state. */ int64_t integer; std::deque<RedisReply*>* elements; RedisReplyPool* pool; //use object pool if reply is array with hundreds of elements RedisReply(); RedisReply(uint64 v); RedisReply(double v); RedisReply(const std::string& v); bool IsErr() const { return type == REDIS_REPLY_ERROR; } bool IsNil() const { return type == REDIS_REPLY_NIL; } bool IsString() const { return type == REDIS_REPLY_STRING; } bool IsArray() const { return type == REDIS_REPLY_ARRAY; } const std::string& Status(); const std::string& Error(); int64_t ErrCode() const { return integer; } void SetEmpty() { Clear(); type = 0; } double GetDouble(); const std::string& GetString() const { return str; } int64 GetInteger() const { return integer; } void SetDouble(double v); void SetInteger(int64_t v) { type = REDIS_REPLY_INTEGER; integer = v; } void SetString(const Data& v) { Clear(); if (!v.IsNil()) { type = REDIS_REPLY_STRING; v.ToString(str); } } void SetString(const std::string& v) { Clear(); type = REDIS_REPLY_STRING; str = v; } void SetErrCode(int err) { Clear(); type = REDIS_REPLY_ERROR; integer = err; } void SetErrorReason(const std::string& reason) { Clear(); type = REDIS_REPLY_ERROR; str = reason; } void SetStatusCode(int status) { Clear(); type = REDIS_REPLY_STATUS; integer = status; } void SetStatusString(const char* v) { Clear(); type = REDIS_REPLY_STATUS; str.assign(v); } void SetStatusString(const std::string& v) { Clear(); type = REDIS_REPLY_STATUS; str = v; } void SetPool(RedisReplyPool* pool); bool IsPooled() { return pool != NULL; } RedisReply& AddMember(bool tail = true); void ReserveMember(int64_t num); size_t MemberSize(); RedisReply& MemberAt(uint32 i); void Clear(); void Clone(const RedisReply& r) { Clear(); type = r.type; integer = r.integer; str = r.str; if (r.elements != NULL && !r.elements->empty()) { for (uint32 i = 0; i < r.elements->size(); i++) { RedisReply& rr = AddMember(); rr.Clone(*(r.elements->at(i))); } } } virtual ~RedisReply(); }; class RedisReplyPool { private: uint32 m_max_size; uint32 m_cursor; std::vector<RedisReply> elements; std::deque<RedisReply> pending; public: RedisReplyPool(uint32 size = 5); void SetMaxSize(uint32 size); RedisReply& Allocate(); void Clear(); }; typedef std::vector<RedisReply*> RedisReplyArray; void reply_status_string(int code, std::string& str); void reply_error_string(int code, std::string& str); void clone_redis_reply(RedisReply& src, RedisReply& dst); uint64_t living_reply_count(); } } #endif /* REDIS_REPLY_HPP_ */
32.825455
100
0.484657
vorjdux
976ba55f7c4e4a84dc80156378219097dd50d09b
952
cpp
C++
Medium/1286_Iterator_For_Combination.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
1
2021-03-15T10:02:10.000Z
2021-03-15T10:02:10.000Z
Medium/1286_Iterator_For_Combination.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
null
null
null
Medium/1286_Iterator_For_Combination.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
null
null
null
class CombinationIterator { private: int len, mask; string s; public: CombinationIterator(string characters, int combinationLength) : s(characters), len(combinationLength) { mask = (1 << characters.length()) - 1; } string next() { while(mask && __builtin_popcount(mask) != len) { mask--; } string next_combination; for(int i = 0; i < s.length(); i++) { if(mask & (1 << (s.length() - i - 1))) { next_combination.push_back(s[i]); } } mask--; return next_combination; } bool hasNext() { while(mask && __builtin_popcount(mask) != len) { mask--; } return mask; } }; /** * Your CombinationIterator object will be instantiated and called as such: * CombinationIterator* obj = new CombinationIterator(characters, combinationLength); * string param_1 = obj->next(); * bool param_2 = obj->hasNext(); */
28.848485
107
0.578782
ShehabMMohamed
976ca940c560635702dfc2c725418346a5e9e5de
3,196
cxx
C++
Examples/InSar/BaselineComputation.cxx
jmichel-otb/otb-insar
b6f8a7d80547ffdcf7c4d2359505ce68107cdb85
[ "Apache-2.0" ]
1
2022-02-16T03:48:29.000Z
2022-02-16T03:48:29.000Z
Examples/InSar/BaselineComputation.cxx
jmichel-otb/otb-insar
b6f8a7d80547ffdcf7c4d2359505ce68107cdb85
[ "Apache-2.0" ]
null
null
null
Examples/InSar/BaselineComputation.cxx
jmichel-otb/otb-insar
b6f8a7d80547ffdcf7c4d2359505ce68107cdb85
[ "Apache-2.0" ]
null
null
null
/*========================================================================= Copyright 2011 Emmanuel Christophe Contributed to ORFEO Toolbox under license Apache 2 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. =========================================================================*/ // Command line: // // ./bin/BaselineComputation ~/project/Images/TSX1_SAR__SSC______HS_S_SRA_20090212T204239_20090212T204240/TSX1_SAR__SSC______HS_S_SRA_20090212T204239_20090212T204240.xml ~/project/Images/TSX1_SAR__SSC______HS_S_SRA_20090223T204240_20090223T204241/TSX1_SAR__SSC______HS_S_SRA_20090223T204240_20090223T204241.xml #include <iomanip> #include "otbImage.h" #include "otbImageFileReader.h" #include "otbBaselineCalculator.h" #include "otbLengthOrientationBaselineFunctor.h" #include "otbPlatformPositionToBaselineCalculator.h" int main(int argc, char* argv[]) { if (argc != 3) { std::cerr << "Usage: " << argv[0] << " masterImageFile slaveImageFile" << std::endl; return EXIT_FAILURE; } const unsigned int Dimension = 2 ; typedef std::complex<double> PixelType; typedef otb::Image<PixelType,Dimension> ImageType; typedef otb::ImageFileReader<ImageType> ReaderType; ReaderType::Pointer master = ReaderType::New(); ReaderType::Pointer slave = ReaderType::New(); master->SetFileName(argv[1]); slave->SetFileName(argv[2]); master->UpdateOutputInformation(); slave->UpdateOutputInformation(); typedef otb::Functor::LengthOrientationBaselineFunctor BaselineFunctorType; typedef otb::BaselineCalculator<BaselineFunctorType> BaselineCalculatorType; typedef BaselineCalculatorType::PlateformPositionToBaselineCalculatorType PlateformPositionToBaselineCalculatorType; BaselineCalculatorType::Pointer baselineCalculator = BaselineCalculatorType::New(); BaselineCalculatorType::PlateformPositionToBaselinePointer plateformPositionToBaseline = PlateformPositionToBaselineCalculatorType::New(); plateformPositionToBaseline->SetMasterPlateform(master->GetOutput()->GetImageKeywordlist()); plateformPositionToBaseline->SetSlavePlateform(slave->GetOutput()->GetImageKeywordlist()); baselineCalculator->SetPlateformPositionToBaselineCalculator(plateformPositionToBaseline); baselineCalculator->Compute(otb::Functor::LengthOrientationBaselineFunctor::Length); double row = 0; double col = 0; std::cout << "(row,col) : " << row << ", " << col << " -> Baseline : "; std::cout << baselineCalculator->EvaluateBaseline(row,col)<< std::endl; row = 1000; col = 1000; std::cout << "(row,col) : " << row << ", " << col << " -> Baseline : "; std::cout << baselineCalculator->EvaluateBaseline(row,col)<< std::endl; }
39.45679
310
0.731852
jmichel-otb
977424df8367635d711cef34f5ced409cc8ceeca
38,699
cpp
C++
src/saiga/opengl/glbinding/source/gl/functions-patches.cpp
no33fewi/saiga
edc873e34cd59eaf8c4a12dc7f909b4dd5e5fb68
[ "MIT" ]
114
2017-08-13T22:37:32.000Z
2022-03-25T12:28:39.000Z
src/saiga/opengl/glbinding/source/gl/functions-patches.cpp
no33fewi/saiga
edc873e34cd59eaf8c4a12dc7f909b4dd5e5fb68
[ "MIT" ]
7
2019-10-14T18:19:11.000Z
2021-06-11T09:41:52.000Z
src/saiga/opengl/glbinding/source/gl/functions-patches.cpp
no33fewi/saiga
edc873e34cd59eaf8c4a12dc7f909b4dd5e5fb68
[ "MIT" ]
18
2017-08-14T01:22:05.000Z
2022-03-12T12:35:07.000Z
#include <glbinding/gl/functions.h> #include <vector> #include <glbinding/gl/functions-patches.h> namespace gl { void glConvolutionParameteri(GLenum target, GLenum pname, GLenum params) { glConvolutionParameteri(target, pname, static_cast<GLint>(params)); } void glConvolutionParameteriEXT(GLenum target, GLenum pname, GLenum params) { glConvolutionParameteriEXT(target, pname, static_cast<GLint>(params)); } void glFogi(GLenum pname, GLenum param) { glFogi(pname, static_cast<GLint>(param)); } void glFogiv(GLenum pname, const GLenum* params) { glFogiv(pname, reinterpret_cast<const GLint*>(params)); } void glGetBufferParameteriv(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetBufferParameteriv(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetBufferParameterivARB(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetBufferParameterivARB(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetBufferParameteriv(GLenum target, GLenum pname, GLenum* params) { glGetBufferParameteriv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetBufferParameterivARB(GLenum target, GLenum pname, GLenum* params) { glGetBufferParameterivARB(target, pname, reinterpret_cast<GLint*>(params)); } void glGetConvolutionParameteriv(GLenum target, GLenum pname, GLenum* params) { glGetConvolutionParameteriv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetConvolutionParameterivEXT(GLenum target, GLenum pname, GLenum* params) { glGetConvolutionParameterivEXT(target, pname, reinterpret_cast<GLint*>(params)); } void glGetIntegerv(GLenum pname, GLenum* data) { glGetIntegerv(pname, reinterpret_cast<GLint*>(data)); } void glGetIntegeri_v(GLenum target, GLuint index, GLenum* data) { glGetIntegeri_v(target, index, reinterpret_cast<GLint*>(data)); } void glGetFramebufferAttachmentParameteriv(GLenum target, GLenum attachment, GLenum pname, GLenum* params) { glGetFramebufferAttachmentParameteriv(target, attachment, pname, reinterpret_cast<GLint*>(params)); } void glGetFramebufferAttachmentParameterivEXT(GLenum target, GLenum attachment, GLenum pname, GLenum* params) { glGetFramebufferAttachmentParameterivEXT(target, attachment, pname, reinterpret_cast<GLint*>(params)); } void glGetFramebufferParameteriv(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetFramebufferParameteriv(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetFramebufferParameterivEXT(GLuint framebuffer, GLenum pname, GLboolean* params) { GLint params_; glGetFramebufferParameterivEXT(framebuffer, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetMinmaxParameteriv(GLenum target, GLenum pname, GLenum* params) { glGetMinmaxParameteriv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetMinmaxParameterivEXT(GLenum target, GLenum pname, GLenum* params) { glGetMinmaxParameterivEXT(target, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedBufferParameteriv(GLuint buffer, GLenum pname, GLboolean* params) { GLint params_; glGetNamedBufferParameteriv(buffer, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetNamedBufferParameterivEXT(GLuint buffer, GLenum pname, GLboolean* params) { GLint params_; glGetNamedBufferParameterivEXT(buffer, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetNamedBufferParameteriv(GLuint buffer, GLenum pname, GLenum* params) { glGetNamedBufferParameteriv(buffer, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedBufferParameterivEXT(GLuint buffer, GLenum pname, GLenum* params) { glGetNamedBufferParameterivEXT(buffer, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedFramebufferAttachmentParameteriv(GLuint framebuffer, GLenum attachment, GLenum pname, GLenum* params) { glGetNamedFramebufferAttachmentParameteriv(framebuffer, attachment, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedFramebufferAttachmentParameterivEXT(GLuint framebuffer, GLenum attachment, GLenum pname, GLenum* params) { glGetNamedFramebufferAttachmentParameterivEXT(framebuffer, attachment, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedFramebufferParameteriv(GLuint framebuffer, GLenum pname, GLboolean* param) { GLint params_; glGetNamedFramebufferParameteriv(framebuffer, pname, &params_); param[0] = static_cast<GLboolean>(params_ != 0); } void glGetNamedFramebufferParameterivEXT(GLuint framebuffer, GLenum pname, GLboolean* params) { GLint params_; glGetNamedFramebufferParameterivEXT(framebuffer, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetNamedProgramivEXT(GLuint program, GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetNamedProgramivEXT(program, target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetNamedProgramivEXT(GLuint program, GLenum target, GLenum pname, GLenum* params) { glGetNamedProgramivEXT(program, target, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedRenderbufferParameteriv(GLuint renderbuffer, GLenum pname, GLenum* params) { glGetNamedRenderbufferParameteriv(renderbuffer, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedRenderbufferParameterivEXT(GLuint renderbuffer, GLenum pname, GLenum* params) { glGetNamedRenderbufferParameterivEXT(renderbuffer, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedStringivARB(GLint namelen, const GLchar* name, GLenum pname, GLenum* params) { glGetNamedStringivARB(namelen, name, pname, reinterpret_cast<GLint*>(params)); } void glGetObjectParameterivARB(GLhandleARB obj, GLenum pname, GLboolean* params) { GLint params_; glGetObjectParameterivARB(obj, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetObjectParameterivARB(GLhandleARB obj, GLenum pname, GLenum* params) { glGetObjectParameterivARB(obj, pname, reinterpret_cast<GLint*>(params)); } void glGetProgramiv(GLuint program, GLenum pname, GLboolean* params) { GLint params_; glGetProgramiv(program, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetProgramivARB(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetProgramivARB(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetProgramiv(GLuint program, GLenum pname, GLenum* params) { glGetProgramiv(program, pname, reinterpret_cast<GLint*>(params)); } void glGetProgramivARB(GLenum target, GLenum pname, GLenum* params) { glGetProgramivARB(target, pname, reinterpret_cast<GLint*>(params)); } void glGetProgramResourceiv(GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum* props, GLsizei bufSize, GLsizei* length, GLenum* params) { glGetProgramResourceiv(program, programInterface, index, propCount, props, bufSize, length, reinterpret_cast<GLint*>(params)); } void glGetQueryIndexediv(GLenum target, GLuint index, GLenum pname, GLboolean* params) { GLint params_; glGetQueryIndexediv(target, index, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetQueryObjectiv(GLuint id, GLenum pname, GLboolean* params) { GLint params_; glGetQueryObjectiv(id, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetQueryObjectivARB(GLuint id, GLenum pname, GLboolean* params) { GLint params_; glGetQueryObjectivARB(id, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetQueryiv(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetQueryiv(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetQueryivARB(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetQueryivARB(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetRenderbufferParameteriv(GLenum target, GLenum pname, GLenum* params) { glGetRenderbufferParameteriv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetRenderbufferParameterivEXT(GLenum target, GLenum pname, GLenum* params) { glGetRenderbufferParameterivEXT(target, pname, reinterpret_cast<GLint*>(params)); } void glGetSamplerParameterIiv(GLuint sampler, GLenum pname, GLenum* params) { glGetSamplerParameterIiv(sampler, pname, reinterpret_cast<GLint*>(params)); } void glGetSamplerParameteriv(GLuint sampler, GLenum pname, GLenum* params) { glGetSamplerParameteriv(sampler, pname, reinterpret_cast<GLint*>(params)); } void glGetShaderiv(GLuint shader, GLenum pname, GLboolean* params) { GLint params_; glGetShaderiv(shader, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetShaderiv(GLuint shader, GLenum pname, GLenum* params) { glGetShaderiv(shader, pname, reinterpret_cast<GLint*>(params)); } void glGetTexEnviv(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetTexEnviv(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTexEnviv(GLenum target, GLenum pname, GLenum* params) { glGetTexEnviv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetTexGeniv(GLenum coord, GLenum pname, GLenum* params) { glGetTexGeniv(coord, pname, reinterpret_cast<GLint*>(params)); } void glGetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLboolean* params) { GLint params_; glGetTexLevelParameteriv(target, level, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLenum* params) { glGetTexLevelParameteriv(target, level, pname, reinterpret_cast<GLint*>(params)); } void glGetTexParameterIiv(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetTexParameterIiv(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTexParameterIivEXT(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetTexParameterIivEXT(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTexParameteriv(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetTexParameteriv(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTexParameterIiv(GLenum target, GLenum pname, GLenum* params) { glGetTexParameterIiv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetTexParameterIivEXT(GLenum target, GLenum pname, GLenum* params) { glGetTexParameterIivEXT(target, pname, reinterpret_cast<GLint*>(params)); } void glGetTexParameteriv(GLenum target, GLenum pname, GLenum* params) { glGetTexParameteriv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetTextureLevelParameteriv(GLuint texture, GLint level, GLenum pname, GLboolean* params) { GLint params_; glGetTextureLevelParameteriv(texture, level, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTextureLevelParameterivEXT(GLuint texture, GLenum target, GLint level, GLenum pname, GLboolean* params) { GLint params_; glGetTextureLevelParameterivEXT(texture, target, level, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTextureLevelParameteriv(GLuint texture, GLint level, GLenum pname, GLenum* params) { glGetTextureLevelParameteriv(texture, level, pname, reinterpret_cast<GLint*>(params)); } void glGetTextureLevelParameterivEXT(GLuint texture, GLenum target, GLint level, GLenum pname, GLenum* params) { glGetTextureLevelParameterivEXT(texture, target, level, pname, reinterpret_cast<GLint*>(params)); } void glGetTextureParameterIiv(GLuint texture, GLenum pname, GLboolean* params) { GLint params_; glGetTextureParameterIiv(texture, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTextureParameterIivEXT(GLuint texture, GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetTextureParameterIivEXT(texture, target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTextureParameteriv(GLuint texture, GLenum pname, GLboolean* params) { GLint params_; glGetTextureParameteriv(texture, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTextureParameterivEXT(GLuint texture, GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetTextureParameterivEXT(texture, target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTextureParameterIiv(GLuint texture, GLenum pname, GLenum* params) { glGetTextureParameterIiv(texture, pname, reinterpret_cast<GLint*>(params)); } void glGetTextureParameterIivEXT(GLuint texture, GLenum target, GLenum pname, GLenum* params) { glGetTextureParameterIivEXT(texture, target, pname, reinterpret_cast<GLint*>(params)); } void glGetTextureParameteriv(GLuint texture, GLenum pname, GLenum* params) { glGetTextureParameteriv(texture, pname, reinterpret_cast<GLint*>(params)); } void glGetTextureParameterivEXT(GLuint texture, GLenum target, GLenum pname, GLenum* params) { glGetTextureParameterivEXT(texture, target, pname, reinterpret_cast<GLint*>(params)); } void glGetTransformFeedbackiv(GLuint xfb, GLenum pname, GLboolean* param) { GLint params_; glGetTransformFeedbackiv(xfb, pname, &params_); param[0] = static_cast<GLboolean>(params_ != 0); } void glGetVertexArrayIndexediv(GLuint vaobj, GLuint index, GLenum pname, GLboolean* param) { GLint params_; glGetVertexArrayIndexediv(vaobj, index, pname, &params_); param[0] = static_cast<GLboolean>(params_ != 0); } void glGetVertexArrayIndexediv(GLuint vaobj, GLuint index, GLenum pname, GLenum* param) { glGetVertexArrayIndexediv(vaobj, index, pname, reinterpret_cast<GLint*>(param)); } void glGetVertexAttribIiv(GLuint index, GLenum pname, GLboolean* params) { GLint params_; glGetVertexAttribIiv(index, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetVertexAttribIivEXT(GLuint index, GLenum pname, GLboolean* params) { GLint params_; glGetVertexAttribIivEXT(index, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetVertexAttribiv(GLuint index, GLenum pname, GLboolean* params) { GLint params_; glGetVertexAttribiv(index, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetVertexAttribivARB(GLuint index, GLenum pname, GLboolean* params) { GLint params_; glGetVertexAttribivARB(index, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetVertexAttribIiv(GLuint index, GLenum pname, GLenum* params) { glGetVertexAttribIiv(index, pname, reinterpret_cast<GLint*>(params)); } void glGetVertexAttribIivEXT(GLuint index, GLenum pname, GLenum* params) { glGetVertexAttribIivEXT(index, pname, reinterpret_cast<GLint*>(params)); } void glGetVertexAttribiv(GLuint index, GLenum pname, GLenum* params) { glGetVertexAttribiv(index, pname, reinterpret_cast<GLint*>(params)); } void glGetVertexAttribivARB(GLuint index, GLenum pname, GLenum* params) { glGetVertexAttribivARB(index, pname, reinterpret_cast<GLint*>(params)); } void glLightModeli(GLenum pname, GLenum param) { glLightModeli(pname, static_cast<GLint>(param)); } void glLightModeliv(GLenum pname, const GLenum* params) { glLightModeliv(pname, reinterpret_cast<const GLint*>(params)); } void glMultiTexImage1DEXT(GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void* pixels) { glMultiTexImage1DEXT(texunit, target, level, static_cast<GLint>(internalformat), width, border, format, type, pixels); } void glMultiTexImage2DEXT(GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels) { glMultiTexImage2DEXT(texunit, target, level, static_cast<GLint>(internalformat), width, height, border, format, type, pixels); } void glMultiTexImage3DEXT(GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void* pixels) { glMultiTexImage3DEXT(texunit, target, level, static_cast<GLint>(internalformat), width, height, depth, border, format, type, pixels); } void glNamedFramebufferParameteri(GLuint framebuffer, GLenum pname, GLboolean param) { glNamedFramebufferParameteri(framebuffer, pname, static_cast<GLint>(param)); } void glNamedFramebufferParameteriEXT(GLuint framebuffer, GLenum pname, GLboolean param) { glNamedFramebufferParameteriEXT(framebuffer, pname, static_cast<GLint>(param)); } void glPixelStorei(GLenum pname, GLboolean param) { glPixelStorei(pname, static_cast<GLint>(param)); } void glPixelTransferi(GLenum pname, GLboolean param) { glPixelTransferi(pname, static_cast<GLint>(param)); } void glPointParameteri(GLenum pname, GLenum param) { glPointParameteri(pname, static_cast<GLint>(param)); } void glPointParameteriv(GLenum pname, const GLenum* params) { glPointParameteriv(pname, reinterpret_cast<const GLint*>(params)); } void glProgramParameteri(GLuint program, GLenum pname, GLboolean value) { glProgramParameteri(program, pname, static_cast<GLint>(value)); } void glProgramParameteriARB(GLuint program, GLenum pname, GLboolean value) { glProgramParameteriARB(program, pname, static_cast<GLint>(value)); } void glProgramParameteriEXT(GLuint program, GLenum pname, GLboolean value) { glProgramParameteriEXT(program, pname, static_cast<GLint>(value)); } void glProgramUniform1i(GLuint program, GLint location, GLboolean v0) { glProgramUniform1i(program, location, static_cast<GLint>(v0)); } void glProgramUniform1iEXT(GLuint program, GLint location, GLboolean v0) { glProgramUniform1iEXT(program, location, static_cast<GLint>(v0)); } void glProgramUniform1iv(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 1 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform1iv(program, location, count, data.data()); } void glProgramUniform1ivEXT(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 1 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform1ivEXT(program, location, count, data.data()); } void glProgramUniform2i(GLuint program, GLint location, GLboolean v0, GLboolean v1) { glProgramUniform2i(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glProgramUniform2iEXT(GLuint program, GLint location, GLboolean v0, GLboolean v1) { glProgramUniform2iEXT(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glProgramUniform2iv(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 2 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform2iv(program, location, count, data.data()); } void glProgramUniform2ivEXT(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 2 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform2ivEXT(program, location, count, data.data()); } void glProgramUniform3i(GLuint program, GLint location, GLboolean v0, GLboolean v1, GLboolean v2) { glProgramUniform3i(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glProgramUniform3iEXT(GLuint program, GLint location, GLboolean v0, GLboolean v1, GLboolean v2) { glProgramUniform3iEXT(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glProgramUniform3iv(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 3 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform3iv(program, location, count, data.data()); } void glProgramUniform3ivEXT(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 3 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform3ivEXT(program, location, count, data.data()); } void glProgramUniform4i(GLuint program, GLint location, GLboolean v0, GLboolean v1, GLboolean v2, GLboolean v3) { glProgramUniform4i(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glProgramUniform4iEXT(GLuint program, GLint location, GLboolean v0, GLboolean v1, GLboolean v2, GLboolean v3) { glProgramUniform4iEXT(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glProgramUniform4iv(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 4 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform4iv(program, location, count, data.data()); } void glProgramUniform4ivEXT(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 4 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform4ivEXT(program, location, count, data.data()); } void glProgramUniform1i(GLuint program, GLint location, GLenum v0) { glProgramUniform1i(program, location, static_cast<GLint>(v0)); } void glProgramUniform1iEXT(GLuint program, GLint location, GLenum v0) { glProgramUniform1iEXT(program, location, static_cast<GLint>(v0)); } void glProgramUniform1iv(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform1iv(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform1ivEXT(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform1ivEXT(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform2i(GLuint program, GLint location, GLenum v0, GLenum v1) { glProgramUniform2i(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glProgramUniform2iEXT(GLuint program, GLint location, GLenum v0, GLenum v1) { glProgramUniform2iEXT(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glProgramUniform2iv(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform2iv(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform2ivEXT(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform2ivEXT(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform3i(GLuint program, GLint location, GLenum v0, GLenum v1, GLenum v2) { glProgramUniform3i(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glProgramUniform3iEXT(GLuint program, GLint location, GLenum v0, GLenum v1, GLenum v2) { glProgramUniform3iEXT(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glProgramUniform3iv(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform3iv(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform3ivEXT(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform3ivEXT(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform4i(GLuint program, GLint location, GLenum v0, GLenum v1, GLenum v2, GLenum v3) { glProgramUniform4i(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glProgramUniform4iEXT(GLuint program, GLint location, GLenum v0, GLenum v1, GLenum v2, GLenum v3) { glProgramUniform4iEXT(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glProgramUniform4iv(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform4iv(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform4ivEXT(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform4ivEXT(program, location, count, reinterpret_cast<const GLint*>(value)); } void glSamplerParameterIiv(GLuint sampler, GLenum pname, const GLenum* param) { glSamplerParameterIiv(sampler, pname, reinterpret_cast<const GLint*>(param)); } void glSamplerParameteri(GLuint sampler, GLenum pname, GLenum param) { glSamplerParameteri(sampler, pname, static_cast<GLint>(param)); } void glSamplerParameteriv(GLuint sampler, GLenum pname, const GLenum* param) { glSamplerParameteriv(sampler, pname, reinterpret_cast<const GLint*>(param)); } void glTexEnvi(GLenum target, GLenum pname, GLboolean param) { glTexEnvi(target, pname, static_cast<GLint>(param)); } void glTexEnviv(GLenum target, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTexEnviv(target, pname, &params_); } void glTexEnvi(GLenum target, GLenum pname, GLenum param) { glTexEnvi(target, pname, static_cast<GLint>(param)); } void glTexEnviv(GLenum target, GLenum pname, const GLenum* params) { glTexEnviv(target, pname, reinterpret_cast<const GLint*>(params)); } void glTexGeni(GLenum coord, GLenum pname, GLenum param) { glTexGeni(coord, pname, static_cast<GLint>(param)); } void glTexGeniv(GLenum coord, GLenum pname, const GLenum* params) { glTexGeniv(coord, pname, reinterpret_cast<const GLint*>(params)); } void glTexImage1D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void* pixels) { glTexImage1D(target, level, static_cast<GLint>(internalformat), width, border, format, type, pixels); } void glTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels) { glTexImage2D(target, level, static_cast<GLint>(internalformat), width, height, border, format, type, pixels); } void glTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void* pixels) { glTexImage3D(target, level, static_cast<GLint>(internalformat), width, height, depth, border, format, type, pixels); } void glTextureImage1DEXT(GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void* pixels) { glTextureImage1DEXT(texture, target, level, static_cast<GLint>(internalformat), width, border, format, type, pixels); } void glTextureImage2DEXT(GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels) { glTextureImage2DEXT(texture, target, level, static_cast<GLint>(internalformat), width, height, border, format, type, pixels); } void glTextureImage3DEXT(GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void* pixels) { glTextureImage3DEXT(texture, target, level, static_cast<GLint>(internalformat), width, height, depth, border, format, type, pixels); } void glTexParameterIiv(GLenum target, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTexParameterIiv(target, pname, &params_); } void glTexParameterIivEXT(GLenum target, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTexParameterIivEXT(target, pname, &params_); } void glTexParameteri(GLenum target, GLenum pname, GLboolean param) { glTexParameteri(target, pname, static_cast<GLint>(param)); } void glTexParameteriv(GLenum target, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTexParameteriv(target, pname, &params_); } void glTexParameterIiv(GLenum target, GLenum pname, const GLenum* params) { glTexParameterIiv(target, pname, reinterpret_cast<const GLint*>(params)); } void glTexParameterIivEXT(GLenum target, GLenum pname, const GLenum* params) { glTexParameterIivEXT(target, pname, reinterpret_cast<const GLint*>(params)); } void glTexParameteri(GLenum target, GLenum pname, GLenum param) { glTexParameteri(target, pname, static_cast<GLint>(param)); } void glTexParameteriv(GLenum target, GLenum pname, const GLenum* params) { glTexParameteriv(target, pname, reinterpret_cast<const GLint*>(params)); } void glTextureParameterIiv(GLuint texture, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTextureParameterIiv(texture, pname, &params_); } void glTextureParameterIivEXT(GLuint texture, GLenum target, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTextureParameterIivEXT(texture, target, pname, &params_); } void glTextureParameteri(GLuint texture, GLenum pname, GLboolean param) { glTextureParameteri(texture, pname, static_cast<GLint>(param)); } void glTextureParameteriEXT(GLuint texture, GLenum target, GLenum pname, GLboolean param) { glTextureParameteriEXT(texture, target, pname, static_cast<GLint>(param)); } void glTextureParameteriv(GLuint texture, GLenum pname, const GLboolean* param) { GLint params_ = static_cast<GLint>(param[0]); glTextureParameteriv(texture, pname, &params_); } void glTextureParameterivEXT(GLuint texture, GLenum target, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTextureParameterivEXT(texture, target, pname, &params_); } void glTextureParameterIiv(GLuint texture, GLenum pname, const GLenum* params) { glTextureParameterIiv(texture, pname, reinterpret_cast<const GLint*>(params)); } void glTextureParameterIivEXT(GLuint texture, GLenum target, GLenum pname, const GLenum* params) { glTextureParameterIivEXT(texture, target, pname, reinterpret_cast<const GLint*>(params)); } void glTextureParameteri(GLuint texture, GLenum pname, GLenum param) { glTextureParameteri(texture, pname, static_cast<GLint>(param)); } void glTextureParameteriEXT(GLuint texture, GLenum target, GLenum pname, GLenum param) { glTextureParameteriEXT(texture, target, pname, static_cast<GLint>(param)); } void glTextureParameteriv(GLuint texture, GLenum pname, const GLenum* param) { glTextureParameteriv(texture, pname, reinterpret_cast<const GLint*>(param)); } void glTextureParameterivEXT(GLuint texture, GLenum target, GLenum pname, const GLenum* params) { glTextureParameterivEXT(texture, target, pname, reinterpret_cast<const GLint*>(params)); } void glUniform1i(GLint location, GLboolean v0) { glUniform1i(location, static_cast<GLint>(v0)); } void glUniform1iARB(GLint location, GLboolean v0) { glUniform1iARB(location, static_cast<GLint>(v0)); } void glUniform1iv(GLint location, GLsizei count, const GLboolean* value) { const auto size = 1 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform1iv(location, count, data.data()); } void glUniform1ivARB(GLint location, GLsizei count, const GLboolean* value) { const auto size = 1 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform1ivARB(location, count, data.data()); } void glUniform2i(GLint location, GLboolean v0, GLboolean v1) { glUniform2i(location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glUniform2iARB(GLint location, GLboolean v0, GLboolean v1) { glUniform2iARB(location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glUniform2iv(GLint location, GLsizei count, const GLboolean* value) { const auto size = 2 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform2iv(location, count, data.data()); } void glUniform2ivARB(GLint location, GLsizei count, const GLboolean* value) { const auto size = 2 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform2ivARB(location, count, data.data()); } void glUniform3i(GLint location, GLboolean v0, GLboolean v1, GLboolean v2) { glUniform3i(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glUniform3iARB(GLint location, GLboolean v0, GLboolean v1, GLboolean v2) { glUniform3iARB(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glUniform3iv(GLint location, GLsizei count, const GLboolean* value) { const auto size = 3 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform3iv(location, count, data.data()); } void glUniform3ivARB(GLint location, GLsizei count, const GLboolean* value) { const auto size = 3 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform3ivARB(location, count, data.data()); } void glUniform4i(GLint location, GLboolean v0, GLboolean v1, GLboolean v2, GLboolean v3) { glUniform4i(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glUniform4iARB(GLint location, GLboolean v0, GLboolean v1, GLboolean v2, GLboolean v3) { glUniform4iARB(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glUniform4iv(GLint location, GLsizei count, const GLboolean* value) { const auto size = 4 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform4iv(location, count, data.data()); } void glUniform4ivARB(GLint location, GLsizei count, const GLboolean* value) { const auto size = 4 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform4ivARB(location, count, data.data()); } void glUniform1i(GLint location, GLenum v0) { glUniform1i(location, static_cast<GLint>(v0)); } void glUniform1iARB(GLint location, GLenum v0) { glUniform1iARB(location, static_cast<GLint>(v0)); } void glUniform1iv(GLint location, GLsizei count, const GLenum* value) { glUniform1iv(location, count, reinterpret_cast<const GLint*>(value)); } void glUniform1ivARB(GLint location, GLsizei count, const GLenum* value) { glUniform1ivARB(location, count, reinterpret_cast<const GLint*>(value)); } void glUniform2i(GLint location, GLenum v0, GLenum v1) { glUniform2i(location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glUniform2iARB(GLint location, GLenum v0, GLenum v1) { glUniform2iARB(location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glUniform2iv(GLint location, GLsizei count, const GLenum* value) { glUniform2iv(location, count, reinterpret_cast<const GLint*>(value)); } void glUniform2ivARB(GLint location, GLsizei count, const GLenum* value) { glUniform2ivARB(location, count, reinterpret_cast<const GLint*>(value)); } void glUniform3i(GLint location, GLenum v0, GLenum v1, GLenum v2) { glUniform3i(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glUniform3iARB(GLint location, GLenum v0, GLenum v1, GLenum v2) { glUniform3iARB(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glUniform3iv(GLint location, GLsizei count, const GLenum* value) { glUniform3iv(location, count, reinterpret_cast<const GLint*>(value)); } void glUniform3ivARB(GLint location, GLsizei count, const GLenum* value) { glUniform3ivARB(location, count, reinterpret_cast<const GLint*>(value)); } void glUniform4i(GLint location, GLenum v0, GLenum v1, GLenum v2, GLenum v3) { glUniform4i(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glUniform4iARB(GLint location, GLenum v0, GLenum v1, GLenum v2, GLenum v3) { glUniform4iARB(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glUniform4iv(GLint location, GLsizei count, const GLenum* value) { glUniform4iv(location, count, reinterpret_cast<const GLint*>(value)); } } // namespace gl
29.86034
120
0.733404
no33fewi
97747fcdd08eedf08f3e44b1c0025a9411d18f4a
9,657
cpp
C++
test/actionsTest/actionForm.cpp
perara-libs/FakeInput
13d7b260634c33ced95d9e3b37780705e4036ab5
[ "MIT" ]
40
2016-11-18T06:14:47.000Z
2022-03-16T14:36:21.000Z
test/actionsTest/actionForm.cpp
perara-libs/FakeInput
13d7b260634c33ced95d9e3b37780705e4036ab5
[ "MIT" ]
null
null
null
test/actionsTest/actionForm.cpp
perara-libs/FakeInput
13d7b260634c33ced95d9e3b37780705e4036ab5
[ "MIT" ]
9
2017-01-23T01:49:41.000Z
2020-11-05T13:09:56.000Z
/** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka <uiii.dev@gmail.com> * * 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 "actionForm.hpp" #include <QHBoxLayout> #include <QVBoxLayout> #include <QLabel> #include <QStackedWidget> #include "keyboard.hpp" #include "mouse.hpp" #include "system.hpp" Q_DECLARE_METATYPE(FakeInput::KeyType); Q_DECLARE_METATYPE(FakeInput::MouseButton); Q_ENUMS(FakeInput::KeyType); Q_ENUMS(FakeInput::MouseButton); ActionForm::ActionForm(QWidget* parent): QWidget(parent) { QVBoxLayout* vbox = new QVBoxLayout(this); actionType_ = new QComboBox(this); actionType_->addItem("press & release key"); actionType_->addItem("click mouse button"); actionType_->addItem("move mouse"); actionType_->addItem("rotate wheel"); actionType_->addItem("run command"); actionType_->addItem("wait"); QWidget* keyOptions_ = new QWidget(); QWidget* mouseButtonOptions_ = new QWidget(); QWidget* mouseMotionOptions_ = new QWidget(); QWidget* mouseWheelOptions_ = new QWidget(); QWidget* commandOptions_ = new QWidget(); QWidget* waitOptions_ = new QWidget(); QHBoxLayout* keyHBox = new QHBoxLayout(); QHBoxLayout* mouseButtonHBox = new QHBoxLayout(); QHBoxLayout* mouseMotionHBox = new QHBoxLayout(); QHBoxLayout* mouseWheelHBox = new QHBoxLayout(); QHBoxLayout* commandHBox = new QHBoxLayout(); QHBoxLayout* waitHBox = new QHBoxLayout(); keySelector_ = new QComboBox(); keySelector_->addItem("A", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_A)); keySelector_->addItem("B", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_B)); keySelector_->addItem("C", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_C)); keySelector_->addItem("D", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_D)); keySelector_->addItem("E", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_E)); keySelector_->addItem("F", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_F)); keySelector_->addItem("G", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_G)); keySelector_->addItem("H", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_H)); keySelector_->addItem("I", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_I)); keySelector_->addItem("J", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_J)); keySelector_->addItem("K", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_K)); keySelector_->addItem("L", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_L)); keySelector_->addItem("M", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_M)); keySelector_->addItem("N", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_N)); keySelector_->addItem("O", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_O)); keySelector_->addItem("P", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_P)); keySelector_->addItem("Q", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_Q)); keySelector_->addItem("R", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_R)); keySelector_->addItem("S", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_S)); keySelector_->addItem("T", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_T)); keySelector_->addItem("U", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_U)); keySelector_->addItem("V", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_V)); keySelector_->addItem("W", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_W)); keySelector_->addItem("X", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_X)); keySelector_->addItem("Y", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_Y)); keySelector_->addItem("Z", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_Z)); mouseButtonSelector_ = new QComboBox(); mouseButtonSelector_->addItem("Left", QVariant::fromValue<FakeInput::MouseButton>(FakeInput::Mouse_Left)); mouseButtonSelector_->addItem("Middle", QVariant::fromValue<FakeInput::MouseButton>(FakeInput::Mouse_Middle)); mouseButtonSelector_->addItem("Right", QVariant::fromValue<FakeInput::MouseButton>(FakeInput::Mouse_Right)); QLabel* xLabel = new QLabel("dx: "); QLabel* yLabel = new QLabel("dy: "); mouseMotionX_ = new QSpinBox(); mouseMotionX_->setSingleStep(50); mouseMotionX_->setMinimum(-10000); mouseMotionX_->setMaximum(10000); mouseMotionY_ = new QSpinBox(); mouseMotionY_->setSingleStep(50); mouseMotionY_->setMinimum(-10000); mouseMotionY_->setMaximum(10000); mouseWheelDirection_ = new QComboBox(); mouseWheelDirection_->addItem("Up"); mouseWheelDirection_->addItem("Down"); command_ = new QLineEdit(); QLabel* timeLabel = new QLabel("miliseconds: "); waitTime_ = new QSpinBox(); waitTime_->setSingleStep(50); waitTime_->setMaximum(10000); keyHBox->addWidget(keySelector_); mouseButtonHBox->addWidget(mouseButtonSelector_); mouseMotionHBox->addWidget(xLabel); mouseMotionHBox->addWidget(mouseMotionX_); mouseMotionHBox->addWidget(yLabel); mouseMotionHBox->addWidget(mouseMotionY_); mouseWheelHBox->addWidget(mouseWheelDirection_); commandHBox->addWidget(command_); waitHBox->addWidget(timeLabel); waitHBox->addWidget(waitTime_); keyOptions_->setLayout(keyHBox); mouseButtonOptions_->setLayout(mouseButtonHBox); mouseMotionOptions_->setLayout(mouseMotionHBox); mouseWheelOptions_->setLayout(mouseWheelHBox); commandOptions_->setLayout(commandHBox); waitOptions_->setLayout(waitHBox); QStackedWidget* stack = new QStackedWidget(this); stack->addWidget(keyOptions_); stack->addWidget(mouseButtonOptions_); stack->addWidget(mouseMotionOptions_); stack->addWidget(mouseWheelOptions_); stack->addWidget(commandOptions_); stack->addWidget(waitOptions_); vbox->addWidget(actionType_); vbox->addWidget(stack); vbox->addStretch(1); setLayout(vbox); connect(actionType_, SIGNAL(currentIndexChanged(int)), stack, SLOT(setCurrentIndex(int))); } QString ActionForm::addActionToSequence(FakeInput::ActionSequence& sequence) { QString infoText = ""; switch(actionType_->currentIndex()) { case 0: { FakeInput::KeyType keyType = keySelector_->itemData(keySelector_->currentIndex()).value<FakeInput::KeyType>(); FakeInput::Key key(keyType); sequence.press(key).release(key); infoText = actionType_->currentText(); infoText.append(": "); infoText.append(key.name().c_str()); break; } case 1: { FakeInput::MouseButton mouseButton = mouseButtonSelector_ ->itemData(mouseButtonSelector_->currentIndex()) .value<FakeInput::MouseButton>(); sequence.press(mouseButton).release(mouseButton); infoText = actionType_->currentText(); infoText.append(": "); infoText.append(mouseButtonSelector_->currentText()); break; } case 2: { sequence.moveMouse( mouseMotionX_->text().toInt(), mouseMotionY_->text().toInt() ); infoText = actionType_->currentText(); infoText.append(": [ dx: "); infoText.append(mouseMotionX_->text()); infoText.append(" ; dy: "); infoText.append(mouseMotionY_->text()); infoText.append(" ]"); break; } case 3: { infoText = actionType_->currentText(); infoText.append(": "); if(mouseWheelDirection_->currentIndex() == 0) { sequence.wheelUp(); infoText.append("Up"); } else { sequence.wheelDown(); infoText.append("Down"); } break; } case 4: { sequence.runCommand(command_->text().toAscii().data()); infoText = actionType_->currentText(); infoText.append(": "); infoText.append(command_->text()); break; } case 5: { sequence.wait(waitTime_->text().toInt()); infoText = actionType_->currentText(); infoText.append(": "); infoText.append(waitTime_->text()); break; } default: break; } return infoText; }
40.57563
122
0.678264
perara-libs
977517e8392b771d384ba89083fc3b3c82cb0e5d
1,058
cpp
C++
src/Compiler/code_gen/builders/array_initializer_list_expression_builder.cpp
joakimthun/Elsa
3be901149c1102d190dda1c7f3340417f03666c7
[ "MIT" ]
16
2015-10-12T14:24:45.000Z
2021-07-20T01:56:04.000Z
src/Compiler/code_gen/builders/array_initializer_list_expression_builder.cpp
haifenghuang/Elsa
3be901149c1102d190dda1c7f3340417f03666c7
[ "MIT" ]
null
null
null
src/Compiler/code_gen/builders/array_initializer_list_expression_builder.cpp
haifenghuang/Elsa
3be901149c1102d190dda1c7f3340417f03666c7
[ "MIT" ]
2
2017-11-12T01:39:09.000Z
2021-07-20T01:56:09.000Z
#include "array_initializer_list_expression_builder.h" #include "../vm_expression_visitor.h" namespace elsa { namespace compiler { void ArrayInitializerListExpressionBuilder::build(VMProgram* program, VMExpressionVisitor* visitor, ArrayInitializerListExpression* expression) { program->emit(OpCode::iconst); auto size = expression->get_values().size(); program->emit(static_cast<int>(size)); program->emit(OpCode::new_arr); auto type = expression->get_type()->get_struct_declaration_expression()->get_generic_type(); program->emit(static_cast<int>(type->get_vm_type())); auto local_index = visitor->current_scope()->create_new_local(); program->emit(OpCode::s_local); program->emit(static_cast<int>(local_index)); for (const auto& exp : expression->get_values()) { program->emit(OpCode::l_local); program->emit(static_cast<int>(local_index)); exp->accept(visitor); program->emit(OpCode::a_ele); } program->emit(OpCode::l_local); program->emit(static_cast<int>(local_index)); } } }
27.128205
145
0.721172
joakimthun
977b9dcb68ea985497728997aedecb96580026b4
8,291
cpp
C++
solver.cpp
sapirp/systemPrograming-task3B
f84f4a6021537bb1e3049035a30de20640b87847
[ "MIT" ]
null
null
null
solver.cpp
sapirp/systemPrograming-task3B
f84f4a6021537bb1e3049035a30de20640b87847
[ "MIT" ]
null
null
null
solver.cpp
sapirp/systemPrograming-task3B
f84f4a6021537bb1e3049035a30de20640b87847
[ "MIT" ]
null
null
null
#include<iostream> #include "solver.hpp" using namespace solver; using namespace std; double RealVariable::solveEquation(RealVariable& eq){ if(eq.a==0 && eq.b==0) throw std::exception(); if(!eq.power){ return -eq.c/eq.b; } else{ double SquareRoot = eq.b*eq.b - 4*eq.a*eq.c; double solveEq; if(SquareRoot>=0) { solveEq = (-eq.b + sqrt(SquareRoot)) / (2*eq.a); } else { throw std::exception(); } return solveEq; } } double solver::solve(RealVariable& eq){ return eq.solveEquation(eq); } RealVariable& RealVariable::copy (RealVariable& rv){ this->a=rv.a; this->b=rv.b; this->c=rv.c; this->power=rv.power; return *this; } //opertor + RealVariable& solver::operator+ (RealVariable& rv , double num){ RealVariable *rvCopy= new RealVariable(); rvCopy->copy(rv); rvCopy->c=rv.c+num; return *rvCopy; } RealVariable& solver::operator+ (double num , RealVariable& rv){ return (rv + num); } RealVariable& solver::operator+ (RealVariable& rv1 , RealVariable& rv2){ RealVariable* rvCopy=new RealVariable(); rvCopy->a=rv1.a+rv2.a; rvCopy->b=rv1.b+rv2.b; rvCopy->c=rv1.c+rv2.c; rvCopy->power= rv1.power? rv1.power : rv2.power; return *rvCopy; } //opertor - RealVariable& solver::operator- (RealVariable& rv , double num){ RealVariable* rvCopy=new RealVariable(); rvCopy->copy(rv); rvCopy->c=rv.c-num; return *rvCopy; } RealVariable& solver::operator- (double num , RealVariable& rv){ return (rv - num); } RealVariable& solver::operator- (RealVariable& rv1 , RealVariable& rv2){ RealVariable* rvCopy=new RealVariable(); rvCopy->a=rv1.a-rv2.a; rvCopy->b=rv1.b-rv2.b; rvCopy->c=rv1.c-rv2.c; rvCopy->power = rv1.power ? rv1.power : rv2.power; return *rvCopy; } //opertor * RealVariable& solver::operator* (RealVariable& rv , double num){ return (num * rv); } RealVariable& solver::operator* (double num , RealVariable& rv){ cout<< "op * : a=" << rv.a <<" b=" << rv.b <<"c="<<rv.c<<endl; RealVariable* rvCopy=new RealVariable(); rvCopy->copy(rv); if(rv.power) { rvCopy->a*=num; } else if(rv.b==0){ rvCopy->b=num; } else rvCopy->b*=num; return *rvCopy; } RealVariable& solver::operator* (RealVariable& rv1 , RealVariable& rv2){ if(rv1.power || rv2.power) throw std::exception(); RealVariable *rvCopy= new RealVariable(); rvCopy->copy(rv1); if(rv1.a != 0 && rv2.a !=0) rvCopy->a=rv1.a*rv2.a; rvCopy->a=rv1.a+rv2.a; rvCopy->power=true; return *rvCopy; } //opertor / RealVariable& solver::operator/ (RealVariable& rv , double num){ if(num==0) throw std::exception(); RealVariable *rvCopy= new RealVariable(); rvCopy->a=rv.a/num; rvCopy->b=rv.b/num; rvCopy->c=rv.c/num; rvCopy->power=rv.power; return *rvCopy; } RealVariable& solver::operator/ (double num , RealVariable& rv){ RealVariable *rvCopy= new RealVariable(); rvCopy->a=num/rv.a; rvCopy->b=num/rv.b; rvCopy->c=num/rv.c; rvCopy->power=rv.power; return *rvCopy; } //operator ^ RealVariable& solver::operator^ (RealVariable& rv, const int num){ if (num != 2 || rv.power) throw std::exception(); RealVariable *rvCopy= new RealVariable(); rvCopy->copy(rv); rvCopy->a=rv.b; rvCopy->power=true; rvCopy->b=0; return *rvCopy; } //opertor == RealVariable& solver::operator== (RealVariable& rv , double num){ RealVariable *rvCopy= new RealVariable(); rvCopy->copy(rv); if(num>0) rvCopy->c-=num; else rvCopy->c+=-num; return *rvCopy; } RealVariable& solver::operator== (double num , RealVariable& rv){ cout<< "operator ==: a=" << rv.a << "b=" <<rv.b <<"c=" << rv.c<< endl; return (rv == num); } RealVariable& solver::operator== (RealVariable& rv1 , RealVariable& rv2){ RealVariable* rvCopy = new RealVariable(); *rvCopy=rv1-rv2; return *rvCopy; } //complex variable std::complex<double> ComplexVariable::solveEquation(ComplexVariable& eq){ if(eq.a==std::complex<double>(0.0,0.0) && eq.b==std::complex<double>(0.0,0.0)) throw std::exception(); if(!eq.power){ return -eq.c/eq.b; } if (eq.b==std::complex<double>(0.0,0.0) && power){ std::complex<double> c=-eq.c/eq.a; return sqrt(c); } else{ std::complex<double> SquareRoot = sqrt(eq.b*eq.b - 4.0 *eq.a*eq.c); std::complex<double> solveEq= (-eq.b + SquareRoot) / (2.0*eq.a); return solveEq; } } std::complex<double> solver::solve(ComplexVariable& eq){ return eq.solveEquation(eq); } ComplexVariable& ComplexVariable::copy (ComplexVariable& cv){ this->a=cv.a; this->b=cv.b; this->c=cv.c; this->power=cv.power; return *this; } //operator + ComplexVariable& solver::operator+ (ComplexVariable& cv , complex<double> num){ ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->copy(cv); cvCopy->c=cv.c+num; return *cvCopy; } ComplexVariable& solver::operator+ (complex<double> num, ComplexVariable& cv ){ return (cv + num); } ComplexVariable& solver::operator+ (ComplexVariable& cv1, ComplexVariable& cv2 ){ ComplexVariable* cvCopy=new ComplexVariable(); cvCopy->a=cv1.a+cv2.a; cvCopy->b=cv1.b+cv2.b; cvCopy->c=cv1.c+cv2.c; cvCopy->power=cv1.power? cv1.power : cv2.power; return *cvCopy; } //operator - ComplexVariable& solver::operator- (ComplexVariable& cv , complex<double> num){ ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->copy(cv); cvCopy->c=cv.c-num; return *cvCopy; } ComplexVariable& solver::operator- (complex<double> num, ComplexVariable& cv ){ return (cv - num); } ComplexVariable& solver::operator- (ComplexVariable& cv1, ComplexVariable& cv2 ){ ComplexVariable* cvCopy=new ComplexVariable(); cvCopy->a=cv1.a-cv2.a; cvCopy->b=cv1.b-cv2.b; cvCopy->c=cv1.c-cv2.c; cvCopy->power = cv1.power ? cv1.power : cv2.power; return *cvCopy; } //operator * ComplexVariable& solver::operator* (ComplexVariable& cv1, ComplexVariable& cv2 ){ if(cv1.power || cv2.power) throw std::exception(); ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->copy(cv1); if(cv1.a != std::complex(0.0,0.0) && cv2.a !=std::complex(0.0,0.0)) cvCopy->a=cv1.a*cv2.a; cvCopy->a=cv1.a+cv2.a; cvCopy->power=true; return *cvCopy; } ComplexVariable& solver::operator* (complex<double> c , ComplexVariable& cv ){ ComplexVariable* cvCopy=new ComplexVariable(); cvCopy->copy(cv); if(cv.power) { cvCopy->a*=c; } else if(cv.b==std::complex(0.0,0.0)){ cvCopy->b=c; } else cvCopy->b*=c; return *cvCopy; } ComplexVariable& solver::operator* (ComplexVariable& cv , complex<double> c ){ return (c * cv); } //operator / ComplexVariable& solver::operator/ (complex<double> c , ComplexVariable& cv ){ ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->a=c/cv.a; cvCopy->b=c/cv.b; cvCopy->c=c/cv.c; cvCopy->power=cv.power; return *cvCopy; } ComplexVariable& solver::operator/ (ComplexVariable& cv , complex<double> c ){ ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->a=cv.a/c; cvCopy->b=cv.b/c; cvCopy->c=cv.c/c; cvCopy->power=cv.power; return *cvCopy; } ComplexVariable& solver::operator^ (ComplexVariable& cv, const int num){ if (num != 2) throw std::exception(); ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->copy(cv); cvCopy->a=cv.b; cvCopy->b=std::complex<double>(0.0,0.0);; cvCopy->power=true; return *cvCopy; } //operator == ComplexVariable& solver::operator== (ComplexVariable& cv , double num){ ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->copy(cv); if(num>0) cvCopy->c-=num; else cvCopy->c+=-num; return *cvCopy; } ComplexVariable& solver::operator== (double num, ComplexVariable& cv ){ return (cv == num); } ComplexVariable& solver::operator== (ComplexVariable& cv1, ComplexVariable& cv2 ){ ComplexVariable* cvCopy = new ComplexVariable(); *cvCopy=cv1-cv2; return *cvCopy; }
25.589506
102
0.624894
sapirp
977fc28e9f8f2c462a97235442bee7fc1b39503f
1,523
cpp
C++
cppcheck/data/c_files/35.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
2
2022-03-23T12:16:20.000Z
2022-03-31T06:19:40.000Z
cppcheck/data/c_files/35.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
null
null
null
cppcheck/data/c_files/35.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
null
null
null
bool Plugin::LoadNaClModuleCommon(nacl::DescWrapper* wrapper, NaClSubprocess* subprocess, const Manifest* manifest, bool should_report_uma, ErrorInfo* error_info, pp::CompletionCallback init_done_cb, pp::CompletionCallback crash_cb) { ServiceRuntime* new_service_runtime = new ServiceRuntime(this, manifest, should_report_uma, init_done_cb, crash_cb); subprocess->set_service_runtime(new_service_runtime); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon (service_runtime=%p)\n", static_cast<void*>(new_service_runtime))); if (NULL == new_service_runtime) { error_info->SetReport(ERROR_SEL_LDR_INIT, "sel_ldr init failure " + subprocess->description()); return false; } bool service_runtime_started = new_service_runtime->Start(wrapper, error_info, manifest_base_url()); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon (service_runtime_started=%d)\n", service_runtime_started)); if (!service_runtime_started) { return false; } // Try to start the Chrome IPC-based proxy. const PPB_NaCl_Private* ppb_nacl = GetNaclInterface(); if (ppb_nacl->StartPpapiProxy(pp_instance())) { using_ipc_proxy_ = true; // We need to explicitly schedule this here. It is normally called in // response to starting the SRPC proxy. CHECK(init_done_cb.pp_completion_callback().func != NULL); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon, started ipc proxy.\n")); pp::Module::Get()->core()->CallOnMainThread(0, init_done_cb, PP_OK); } return true; }
37.146341
77
0.74327
awsm-research
97800b9046f54f846dc4fdb8d5c33f66a9b324f2
1,770
cpp
C++
atcoder/abc/abc_114/c.cpp
hsmtknj/programming-contest
b0d7f8a2d12fb031d3a802e6a4769cd6d2defcab
[ "MIT" ]
null
null
null
atcoder/abc/abc_114/c.cpp
hsmtknj/programming-contest
b0d7f8a2d12fb031d3a802e6a4769cd6d2defcab
[ "MIT" ]
null
null
null
atcoder/abc/abc_114/c.cpp
hsmtknj/programming-contest
b0d7f8a2d12fb031d3a802e6a4769cd6d2defcab
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> void dfs753(std::vector<int> &list, int N, std::string s); int main() { int N; int cnt = 0; std::cin >> N; // find number including only 7, 5, 3 std::vector<int> list; dfs753(list, N, ""); // find answer for (int i = 0; i < list.size(); i++) { int cnt3 = 0; int cnt5 = 0; int cnt7 = 0; int cnt_others = 0; std::string s; s = std::to_string(list[i]); for (int j = 0; j < s.length(); j++) { int n_target_digit = (s[j] - '0'); if (n_target_digit == 3) { cnt3++; } else if (n_target_digit == 5) { cnt5++; } else if (n_target_digit == 7) { cnt7++; } else { cnt_others++; } } if (cnt3 > 0 && cnt5 > 0 && cnt7 > 0 && cnt_others == 0) { cnt++; } } std::cout << cnt << std::endl; return 0; } void dfs753(std::vector<int> &list, int N, std::string s) { std::string s_tmp; int n_tmp; if (s.length() <= 8) { s_tmp = s + '3'; n_tmp = std::stoi(s_tmp); if (n_tmp <= N) { list.push_back(n_tmp); dfs753(list, N, s_tmp); } s_tmp = s + '5'; n_tmp = std::stoi(s_tmp); if (n_tmp <= N) { list.push_back(n_tmp); dfs753(list, N, s_tmp); } s_tmp = s + '7'; n_tmp = std::stoi(s_tmp); if (n_tmp <= N) { list.push_back(n_tmp); dfs753(list, N, s_tmp); } } };
19.450549
64
0.388136
hsmtknj
978137d0c0dbfb68443bae856077cccbb6774a70
758
hpp
C++
Firmware/service_providers/headers/ih/sp_ibattery_service.hpp
ValentiWorkLearning/GradWork
70bb5a629df056a559bae3694b47a2e5dc98c23b
[ "MIT" ]
39
2019-10-23T12:06:16.000Z
2022-01-26T04:28:29.000Z
Firmware/service_providers/headers/ih/sp_ibattery_service.hpp
ValentiWorkLearning/GradWork
70bb5a629df056a559bae3694b47a2e5dc98c23b
[ "MIT" ]
20
2020-03-21T20:21:46.000Z
2021-11-19T14:34:03.000Z
Firmware/service_providers/headers/ih/sp_ibattery_service.hpp
ValentiWorkLearning/GradWork
70bb5a629df056a559bae3694b47a2e5dc98c23b
[ "MIT" ]
7
2019-10-18T09:44:10.000Z
2021-06-11T13:05:16.000Z
#pragma once #include "utils/SimpleSignal.hpp" #include <chrono> namespace ServiceProviders::BatteryService::Settings { using namespace std::chrono_literals; constexpr std::chrono::seconds MeasurmentPeriod = 1s; constexpr std::uint8_t MinBatteryLevel = 0; constexpr std::uint8_t MaxBatteryLevel = 100; } // namespace ServiceProviders::BatteryService::Settings namespace ServiceProviders::BatteryService { class IBatteryLevelAppService { public: virtual ~IBatteryLevelAppService() = default; public: virtual std::chrono::seconds getMeasurmentPeriod() const noexcept = 0; virtual void startBatteryMeasure() noexcept = 0; Simple::Signal<void(std::uint8_t)> onBatteryLevelChangedSig; }; } // namespace ServiceProviders::BatteryService
22.294118
74
0.779683
ValentiWorkLearning
97833df0227057c09fa51fbf52d1ba81477f4cff
5,366
hpp
C++
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/msw/proto/spp/packer.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/msw/proto/spp/packer.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/msw/proto/spp/packer.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
#pragma once #include <limits> #include <exception> #include <functional> #include <type_traits> #include <msw/config.hpp> #include <msw/buffer.hpp> #include <msw/noncopyable.hpp> #include <msw/throw_runtime_error.hpp> namespace msw { namespace spp { template <typename SizeType = wbyte> struct packer : noncopyable { typedef SizeType size_type ; typedef std::function<void(range<byte>)> packet_ready ; static_assert(std::numeric_limits<size_type>::is_integer && std::is_unsigned<size_type>::value, "SizeType must be only unsigned integer type"); explicit packer(packet_ready packet_ready, size<byte> buffer_capacity = msw::KB * 64, size<byte> offset = 0) : offset_ ( offset ) , buf_ ( 0, buffer_capacity ) , last_packet_len_ ( 0 ) , packet_ready_ ( packet_ready ) {} ~packer() { if (!std::uncaught_exception()) flush(); } template <typename ...T> void add_packet(T&& ...v) { flush(); put_packet(std::forward<T>(v)...); zzz_flush(); } template <typename ...T> void add_packet_silent(T&& ...v) { flush(); put_packet_silent(std::forward<T>(v)...); zzz_flush(); } template <typename ...Ts> void put_packet(Ts&& ...vs) { zzz_add_header(); put_to_last_packet(std::forward<Ts>(vs)...); } template <typename ...Ts> void put_packet_silent(Ts&& ...vs) { zzz_add_header_silent(); put_to_last_packet_silent(std::forward<Ts>(vs)...); } void put_to_last_packet(range<byte const> block) { auto const max_block_size = size<byte>(std::numeric_limits<size_type>::max()); if ((size<byte>(last_packet_len_) + block.size()) > max_block_size) msw::throw_runtime_error("large block: ", last_packet_len_ , " + ", block.size(), " (max permissible size: ", max_block_size, ")"); if (buf_.empty()) zzz_add_header(); zzz_add_last_packet_len(static_cast<size_type>(block.size().count())); buf_.push_back(block); } template <typename T> void put_to_last_packet(T&& v) { #ifdef MSW_ODD_STD_FORWARD put_to_last_packet(make_range<byte const>(v)); #else put_to_last_packet(make_range<byte const>(std::forward<T>(v))); #endif } template <typename T, typename ...Ts> void put_to_last_packet(T&& v, Ts&& ...vs) { put_to_last_packet(std::forward<T>(v)); put_to_last_packet(std::forward<Ts>(vs)...); } void put_to_last_packet_silent(range<byte const> block) { MSW_ASSERT((size<byte>(last_packet_len_) + block.size()) <= size<byte>(std::numeric_limits<size_type>::max())); if (buf_.empty()) zzz_add_header_silent(); zzz_add_last_packet_len(static_cast<size_type>(block.size().count())); buf_.push_back_silent(block); } template <typename T> void put_to_last_packet_silent(T&& v) { put_to_last_packet_silent(make_range<byte const>(std::forward<T>(v))); } template <typename T, typename ...Ts> void put_to_last_packet_silent(T&& v, Ts&& ...vs) { put_to_last_packet_silent(std::forward<T>(v)); put_to_last_packet_silent(std::forward<Ts>(vs)...); } size<byte> packet_size() const { return buf_.size(); } size<byte> capacity() const { return buf_.capacity(); } size<byte> offset() const { return offset_; } bool empty() const { return buf_.empty(); } void flush() { if (buf_.has_items()) zzz_flush(); } void reset() { buf_.clear(); last_packet_len_ = 0; } private: void zzz_flush() { packet_ready_(buf_.all()); last_packet_len_ = 0; buf_.clear(); } void zzz_add_header() { if (buf_.empty()) buf_.resize(offset_); buf_.push_back(size_type(0)); last_packet_len_ = 0; } void zzz_add_header_silent() { if (buf_.empty()) buf_.resize(offset_); buf_.push_back_silent(size_type(0)); last_packet_len_ = 0; } void zzz_add_last_packet_len(size_type len) { size_type& packet_len = buf_.back(last_packet_len_ + sizeof(size_type)).template front<size_type>(); last_packet_len_ += len; packet_len += len; MSW_ASSERT(packet_len == last_packet_len_); } size<byte> const offset_ ; buffer<byte> buf_ ; size_type last_packet_len_ ; packet_ready packet_ready_ ; }; typedef packer<byte> packer_8 ; typedef packer<wbyte> packer_16 ; typedef packer<qbyte> packer_32 ; }}
30.488636
151
0.533545
yklishevich
9791022486471675cd10515f685393c43850bd56
134
cpp
C++
src/examples/01_module/01_hello_world/hello.cpp
acc-cosc-1337-summer-2020-classroom/acc-cosc-1337-summer-2020-justinpesz
44adcb5fb1a307c6b5f59b4235fe83a7eb363002
[ "MIT" ]
null
null
null
src/examples/01_module/01_hello_world/hello.cpp
acc-cosc-1337-summer-2020-classroom/acc-cosc-1337-summer-2020-justinpesz
44adcb5fb1a307c6b5f59b4235fe83a7eb363002
[ "MIT" ]
null
null
null
src/examples/01_module/01_hello_world/hello.cpp
acc-cosc-1337-summer-2020-classroom/acc-cosc-1337-summer-2020-justinpesz
44adcb5fb1a307c6b5f59b4235fe83a7eb363002
[ "MIT" ]
null
null
null
#include "hello.h" double calculate_paycheck(double num1, double num2) { auto payrate = num1 / num2; return payrate; }
13.4
51
0.664179
acc-cosc-1337-summer-2020-classroom
97a2bce42566f20ad356ce2a39e84587bb5959a0
4,287
cc
C++
src/webpage.cc
mistydew/RSSearch
52e597aeb495fe35f2f6069741ef19c9d0bfe2bb
[ "MIT" ]
2
2019-03-13T14:47:16.000Z
2019-07-22T09:17:43.000Z
src/webpage.cc
mistydew/RSSearch
52e597aeb495fe35f2f6069741ef19c9d0bfe2bb
[ "MIT" ]
null
null
null
src/webpage.cc
mistydew/RSSearch
52e597aeb495fe35f2f6069741ef19c9d0bfe2bb
[ "MIT" ]
1
2019-07-22T09:17:44.000Z
2019-07-22T09:17:44.000Z
/// /// @file webpage.cc /// @author mistydew(mistydew@qq.com) /// @date 2017-12-02 15:36:06 /// #include "webpage.h" #include "configuration.h" #include "wordsegmentation.h" #include <queue> #include <sstream> namespace md { WebPage::WebPage(const std::string & doc) { std::cout << "WebPage(const std::string &)" << std::endl; _topWords.reserve(TOPK); processDoc(doc); } WebPage::~WebPage() { std::cout << "~WebPage()" << std::endl; } std::string WebPage::getDocTitle() { return _docTitle; } std::string WebPage::getDocUrl() { return _docUrl; } std::string WebPage::summary(const std::vector<std::string> & queryWords) { std::vector<std::string> summaryVec; std::istringstream iss(_docContent); std::string line; while (iss >> line) { for (auto & word : queryWords) { if (line.find(word) != std::string::npos) { summaryVec.push_back(line); break; } } if (summaryVec.size() > 6) break; } std::string summary; for (auto & line : summaryVec) { summary.append(line).append("\n"); } return summary; } void WebPage::processDoc(const std::string & doc) { std::cout << "process document..." << std::endl; std::string begId = "<docid>"; std::string endId = "</docid>"; std::string begUrl = "<url>"; std::string endUrl = "</url>"; std::string begTitle = "<title>"; std::string endTitle = "</title>"; std::string begContent = "<content>"; std::string endContent = "</content>"; std::string::size_type bpos = doc.find(begId); std::string::size_type epos = doc.find(endId); std::string docId = doc.substr(bpos + begId.size(), epos - bpos - begId.size()); _docId = str2uint(docId); bpos = doc.find(begUrl); epos = doc.find(endUrl); _docUrl = doc.substr(bpos + begUrl.size(), epos - bpos - begUrl.size()); bpos = doc.find(begTitle); epos = doc.find(endTitle); _docTitle = doc.substr(bpos + begTitle.size(), epos - bpos - begTitle.size()); bpos = doc.find(begContent); epos = doc.find(endContent); _docContent = doc.substr(bpos + begContent.size(), epos - bpos - begContent.size()); #if 0 std::cout << _docId << std::endl; std::cout << _docUrl << std::endl; std::cout << _docTitle << std::endl; std::cout << _docContent << std::endl; #endif statistic(); calcTopK(); std::cout << "process completed" << std::endl; } void WebPage::statistic() { std::vector<std::string> words; WordSegmentation::getInstance()->cut(_docContent, words); std::size_t nBytes; for (auto & word : words) { if(0 == Configuration::getInstance()->getStopWord().count(word)) { nBytes = nBytesUTF8Code(word[0]); if (0 == nBytes) { word = processWords(word); if ("" == word) continue; } ++_wordsMap[word]; } } #if 0 for (auto & map : _wordsMap) { std::cout << map.first << " " << map.second << std::endl; } #endif } std::string WebPage::processWords(const std::string & word) { std::string temp; for (std::string::size_type idx = 0; idx != word.size(); ++idx) { if (isalpha(word[idx])) { if (isupper(word[idx])) temp += word[idx] + 32; else temp += word[idx]; } } return temp; } void WebPage::calcTopK() { std::priority_queue<std::pair<std::string, std::size_t>, std::vector<std::pair<std::string, std::size_t> >, WordFreqCompare> wordFreqQue(_wordsMap.begin(), _wordsMap.end()); while (!wordFreqQue.empty()) { _topWords.push_back(wordFreqQue.top().first); if (_topWords.size() >= TOPK) break; wordFreqQue.pop(); } #if 0 std::cout << "top words:" << std::endl; for (auto & top : _topWords) { std::cout << top << std::endl; } #endif } std::ostream & operator<<(std::ostream & os, const WebPage & rhs) { os << rhs._docId << std::endl << rhs._docTitle << std::endl << rhs._docUrl << std::endl << rhs._docContent; return os; } } // end of namespace md
24.637931
128
0.559132
mistydew
97a453e833e798b0117112d4759e7c3e46460faf
606
cpp
C++
test/src/algorithm/suffix.cpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
9
2020-07-04T16:46:13.000Z
2022-01-09T21:59:31.000Z
test/src/algorithm/suffix.cpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
null
null
null
test/src/algorithm/suffix.cpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
1
2021-05-23T13:37:40.000Z
2021-05-23T13:37:40.000Z
#include "test.hpp" #include "test/numbers.hpp" #include "jln/mp/smp/algorithm/suffix.hpp" TEST_SUITE_BEGIN() TEST() { using namespace jln::mp; using namespace ut::ints; test_pack2<suffix, int>(); ut::same<list<>, emp::suffix<list<>, int>>(); ut::same<list<_0, int>, emp::suffix<seq_0, int>>(); test_context<suffix<int>, smp::suffix<int>>() .test<list<>>() .test<list<_0, int>, _0>() .test<list<_0, int, _1, int>, _0, _1>() .test<list<_0, int, _1, int, _2, int>, _0, _1, _2>() ; ut::not_invocable<smp::suffix<void, bad_function>, _1, _1, _1>(); } TEST_SUITE_END()
20.896552
67
0.612211
jonathanpoelen
97aa1b3005b136dd27e3bffc6af997679b487c9f
4,727
cpp
C++
Assignment 3/AVL_TreeOperations.cpp
Raghav1806/Data-Structures-CSL-201-
2e4e3c67e3ff28ac6a9e1f06fe12a2864b17d177
[ "MIT" ]
null
null
null
Assignment 3/AVL_TreeOperations.cpp
Raghav1806/Data-Structures-CSL-201-
2e4e3c67e3ff28ac6a9e1f06fe12a2864b17d177
[ "MIT" ]
null
null
null
Assignment 3/AVL_TreeOperations.cpp
Raghav1806/Data-Structures-CSL-201-
2e4e3c67e3ff28ac6a9e1f06fe12a2864b17d177
[ "MIT" ]
null
null
null
// program for basic operations in AVL Tree #include <iostream> #include <cstdlib> using namespace std; struct Node{ int data; struct Node *left; struct Node *right; int height; }*root; struct Node *createNewNode(int x){ struct Node *newptr = new Node; newptr->data = x; newptr->left = NULL; newptr->right = NULL; newptr->height = 1; return newptr; } void inorder(struct Node *root){ if(root == NULL) return; else{ inorder(root->left); cout << root->data << " "; inorder(root->right); } cout << "\n"; } int max(int a, int b){ if(a >= b) return a; else return b; } int height(struct Node *root){ if(root == NULL) return 0; else return root->height; } int getBalance(struct Node *root){ if(root == NULL) return 0; else return height(root->left) - height(root->right); } struct Node *rightRotate(struct Node *y){ struct Node *x = y->left; struct Node *T2 = x->right; // perform rotation x->right = y; y->left = T2; // update heights y->height = max(height(y->left), height(y->right)) + 1; x->height = max(height(x->left), height(x->right)) + 1; // return new root return x; } struct Node *leftRotate(struct Node *x){ struct Node *y = x->right; struct Node *T2 = y->left; // perform rotation y->left = x; x->right = T2; // update heights x->height = max(height(x->left), height(x->right)) + 1; y->height = max(height(y->left), height(y->right)) + 1; // return new root return y; } struct Node *insertAVL(struct Node *root, int data){ int balance; // perform normal BST insertion if(root == NULL) return createNewNode(data); if(data <= root->data) root->left = insertAVL(root->left, data); else if(data > root->data) root->right = insertAVL(root->right, data); // update the height of ancestor node root->height = 1 + max(height(root->left),height(root->right)); // get the balance factor of this ancestor node balance = getBalance(root); // if this node is unbalanced, then 4 cases are possible // left left case if(balance > 1 && data < root->left->data) return leftRotate(root); // right right case if(balance > 1 && data > root->right->data) return rightRotate(root); // left right case if(balance > 1 && data > root->left->data){ root->left = leftRotate(root->left); return rightRotate(root); } // right left case if(balance < -1 && data < root->right->data){ root->right = rightRotate(root->right); return leftRotate(root); } // return the unchanged pointers return root; } struct Node *minValueNode(struct Node *root){ struct Node *curr = root; // loop down to find smallest node while(curr->left != NULL) curr = curr->left; return curr; } struct Node *deleteAVL(struct Node *root, int data){ int balance; // perform standard BST delete if(root == NULL) return root; // if the key is in left subtree if(data < root->data) root->left = deleteAVL(root->left, data); // if the key is in right subtree if(data > root->data) root->right = deleteAVL(root->right, data); // if this is the node to be deleted else{ // node with only one child or no child if(root->left == NULL){ struct Node *temp = root->right; free(root); return temp; } else if(root->right == NULL){ struct Node *temp = root->left; free(root); return temp; } // node with two children struct Node *temp = minValueNode(root->right); // copy the inorder successor's content to this node root->data = temp->data; // delete the inorder successor root->right = deleteAVL(root->right,temp->data); } // return root; // update the height of current node root->height = 1 + max(height(root->left), height(root->right)); // get the balanced factor from this node (bottomm up manner) balance = getBalance(root); // if this node is unbalanced, there are 4 possible cases // left left case if(balance > 1 && getBalance(root->left) >= 0) return rightRotate(root); // right right case if(balance < -1 && getBalance(root->right) <= 0) return leftRotate(root); // left right case if(balance > 1 && getBalance(root->left) < 0){ root->left = leftRotate(root->left); return rightRotate(root); } // right left case if(balance < -1 && getBalance(root->right) > 0){ root->right = rightRotate(root->right); return leftRotate(root); } return root; } int main(){ root = NULL; int size, i; cout << "Enter the size of array\n"; cin >> size; int A[size]; cout << "Enter the elements of array\n"; for(i = 0; i < size; i++){ cin >> A[i]; if(A[i] > 0) root = insertAVL(root, A[i]); else if(A[i] < 0){ A[i] = -1*A[i]; root = deleteAVL(root, A[i]); } } cout << "The inorder traversal of tree is\n"; inorder(root); return 0; }
19.861345
65
0.642268
Raghav1806
97ab322573a6865d8a85ff34c4ad426f4104757c
1,381
cpp
C++
IOCP4Http/IOCP/PerSocketContext.cpp
Joyce-Qu/IOCPServer-Client-
b1c1a76e6bffe3b67340614ba8e36e197198302e
[ "MIT" ]
42
2019-11-13T06:39:31.000Z
2021-12-28T18:55:27.000Z
IOCP4Http/IOCP/PerSocketContext.cpp
124327288/IOCPServer
b1c1a76e6bffe3b67340614ba8e36e197198302e
[ "MIT" ]
null
null
null
IOCP4Http/IOCP/PerSocketContext.cpp
124327288/IOCPServer
b1c1a76e6bffe3b67340614ba8e36e197198302e
[ "MIT" ]
31
2019-11-14T09:58:15.000Z
2022-03-25T08:30:41.000Z
#include <ws2tcpip.h> #include <assert.h> #include "Network.h" #include "PerIoContext.h" #include "PerSocketContext.h" #include <iostream> using namespace std; ListenContext::ListenContext(short port, const std::string& ip) { SecureZeroMemory(&m_addr, sizeof(SOCKADDR_IN)); m_addr.sin_family = AF_INET; inet_pton(AF_INET, ip.c_str(), &m_addr.sin_addr); //m_addr.sin_addr.s_addr = inet_addr(ip.c_str()); m_addr.sin_port = htons(port); m_socket = Network::socket(); assert(SOCKET_ERROR != m_socket); } ClientContext::ClientContext(const SOCKET& socket) : m_socket(socket), m_recvIoCtx(new RecvIoContext()) , m_sendIoCtx(new IoContext(PostType::SEND)) , m_nPendingIoCnt(0) { SecureZeroMemory(&m_addr, sizeof(SOCKADDR_IN)); InitializeCriticalSection(&m_csLock); } ClientContext::~ClientContext() { delete m_recvIoCtx; delete m_sendIoCtx; m_recvIoCtx = nullptr; m_sendIoCtx = nullptr; LeaveCriticalSection(&m_csLock); } void ClientContext::reset() { assert(0 == m_nPendingIoCnt); assert(m_outBufQueue.empty()); SecureZeroMemory(&m_addr, sizeof(SOCKADDR_IN)); m_nLastHeartbeatTime = GetTickCount(); } void ClientContext::appendToBuffer(PBYTE pInBuf, size_t len) { m_inBuf.write((PBYTE)pInBuf, len); } void ClientContext::appendToBuffer(const std::string& inBuf) { m_inBuf.write(inBuf); }
24.660714
63
0.717596
Joyce-Qu
97ad3e092974dd1d58c4f30432cd174a86fdc87e
2,333
cpp
C++
Engine/Renderer/Gfx/src/GfxCamera.cpp
LiangYue1981816/AresEngine
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
[ "BSD-2-Clause" ]
3
2018-12-08T16:32:05.000Z
2020-06-02T11:07:15.000Z
Engine/Renderer/Gfx/src/GfxCamera.cpp
LiangYue1981816/AresEngine
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
[ "BSD-2-Clause" ]
null
null
null
Engine/Renderer/Gfx/src/GfxCamera.cpp
LiangYue1981816/AresEngine
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
[ "BSD-2-Clause" ]
1
2019-09-12T00:26:05.000Z
2019-09-12T00:26:05.000Z
#include "GfxHeader.h" CGfxCamera::CGfxCamera(void) { } CGfxCamera::~CGfxCamera(void) { } void CGfxCamera::SetScissor(float x, float y, float width, float height) { m_camera.setScissor(x, y, width, height); } void CGfxCamera::SetViewport(float x, float y, float width, float height) { m_camera.setViewport(x, y, width, height); } void CGfxCamera::SetPerspective(float fovy, float aspect, float zNear, float zFar) { m_camera.setPerspective(fovy, aspect, zNear, zFar); } void CGfxCamera::SetOrtho(float left, float right, float bottom, float top, float zNear, float zFar) { m_camera.setOrtho(left, right, bottom, top, zNear, zFar); } void CGfxCamera::SetLookat(float eyex, float eyey, float eyez, float centerx, float centery, float centerz, float upx, float upy, float upz) { m_camera.setLookat(glm::vec3(eyex, eyey, eyez), glm::vec3(centerx, centery, centerz), glm::vec3(upx, upy, upz)); } const glm::camera& CGfxCamera::GetCamera(void) const { return m_camera; } const glm::vec4& CGfxCamera::GetScissor(void) const { return m_camera.scissor; } const glm::vec4& CGfxCamera::GetViewport(void) const { return m_camera.viewport; } const glm::vec3& CGfxCamera::GetPosition(void) const { return m_camera.position; } const glm::vec3& CGfxCamera::GetForwardDirection(void) const { return m_camera.forward; } const glm::vec3& CGfxCamera::GetUpDirection(void) const { return m_camera.up; } const glm::mat4& CGfxCamera::GetProjectionMatrix(void) const { return m_camera.projectionMatrix; } const glm::mat4& CGfxCamera::GetViewMatrix(void) const { return m_camera.viewMatrix; } const glm::mat4& CGfxCamera::GetViewInverseMatrix(void) const { return m_camera.viewInverseMatrix; } const glm::mat4& CGfxCamera::GetViewInverseTransposeMatrix(void) const { return m_camera.viewInverseTransposeMatrix; } glm::vec3 CGfxCamera::WorldToScreen(const glm::vec3& world) const { return m_camera.worldToScreen(world); } glm::vec3 CGfxCamera::ScreenToWorld(const glm::vec3& screen) const { return m_camera.screenToWorld(screen); } bool CGfxCamera::IsVisible(const glm::vec3& vertex) const { return m_camera.visible(vertex); } bool CGfxCamera::IsVisible(const glm::aabb& aabb) const { return m_camera.visible(aabb); } bool CGfxCamera::IsVisible(const glm::sphere& sphere) const { return m_camera.visible(sphere); }
20.646018
140
0.753536
LiangYue1981816
97adcb71b727d993f3f48ec0c431b358a65b8a0a
1,349
hpp
C++
Yannq/Basis/Basis.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
Yannq/Basis/Basis.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
Yannq/Basis/Basis.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
#pragma once //! \defgroup Basis Basis for a spin-1/2 system #include "BasisJz.hpp" #include "BasisFull.hpp" #include <iterator> #include <type_traits> #include <tbb/concurrent_vector.h> #include <tbb/parallel_for_each.h> #include <tbb/parallel_sort.h> /** * Enable if Iterable is not random access iterable */ template<class BasisType> tbb::concurrent_vector<uint32_t> parallelConstructBasis(BasisType&& basis, std::forward_iterator_tag) { tbb::concurrent_vector<uint32_t> res; tbb::parallel_for_each(basis.begin(), basis.end(), [&](uint32_t elt) { res.emplace_back(elt); }); tbb::parallel_sort(res.begin(), res.end()); return res; } template<class BasisType> tbb::concurrent_vector<uint32_t> parallelConstructBasis(BasisType&& basis, std::random_access_iterator_tag) { tbb::concurrent_vector<uint32_t> res(basis.size(), 0u); tbb::parallel_for(std::size_t(0u), basis.size(), [&](std::size_t idx) { res[idx] = basis[idx]; }); return res; } template<class BasisType> inline tbb::concurrent_vector<uint32_t> parallelConstructBasis(BasisType&& basis) { using DecayedBasisType = typename std::decay<BasisType>::type; using IteratorType = typename std::result_of<decltype(&DecayedBasisType::begin)(BasisType)>::type; return parallelConstructBasis(basis, typename std::iterator_traits<IteratorType>::iterator_category()); }
28.702128
107
0.75315
cecri
97af8f553fd0ca2d14f6905218236556ec82f11a
5,132
tcc
C++
include/lvr2/util/ClusterBiMap.tcc
uos/lvr
9bb03a30441b027c39db967318877e03725112d5
[ "BSD-3-Clause" ]
38
2019-06-19T15:10:35.000Z
2022-02-16T03:08:24.000Z
include/lvr2/util/ClusterBiMap.tcc
jtpils/lvr2
b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce
[ "BSD-3-Clause" ]
9
2019-06-19T16:19:51.000Z
2021-09-17T08:31:25.000Z
include/lvr2/util/ClusterBiMap.tcc
jtpils/lvr2
b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce
[ "BSD-3-Clause" ]
13
2019-04-16T11:50:32.000Z
2020-11-26T07:47:44.000Z
/** * Copyright (c) 2018, University Osnabrück * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University Osnabrück nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL University Osnabrück 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. */ /* * ClusterBiMap.tcc * * @date 17.06.2017 * @author Johan M. von Behren <johan@vonbehren.eu> */ #include <algorithm> using std::remove; namespace lvr2 { template <typename HandleT> Cluster<HandleT>& ClusterBiMap<HandleT>::getC(ClusterHandle clusterHandle) { return m_cluster[clusterHandle]; } template <typename HandleT> const Cluster<HandleT>& ClusterBiMap<HandleT>::getCluster(ClusterHandle clusterHandle) const { return m_cluster[clusterHandle]; } template <typename HandleT> const Cluster<HandleT>& ClusterBiMap<HandleT>::operator[](ClusterHandle clusterHandle) const { return m_cluster[clusterHandle]; } template <typename HandleT> ClusterHandle ClusterBiMap<HandleT>::createCluster() { ClusterHandle newHandle(m_cluster.size()); m_cluster.push(Cluster<HandleT>()); return newHandle; } template <typename HandleT> void ClusterBiMap<HandleT>::removeCluster(ClusterHandle clusterHandle) { auto cluster = getC(clusterHandle); // Substract number of handles in removed cluster from number of all handles in set m_numHandles -= cluster.handles.size(); // Remove handles in cluster from cluster map for (auto handle: cluster.handles) { m_clusterMap.erase(handle); } // Remove cluster m_cluster.erase(clusterHandle); } template <typename HandleT> ClusterHandle ClusterBiMap<HandleT>::addToCluster(ClusterHandle clusterHandle, HandleT handle) { getC(clusterHandle).handles.push_back(handle); m_clusterMap.insert(handle, clusterHandle); ++m_numHandles; return clusterHandle; } template <typename HandleT> ClusterHandle ClusterBiMap<HandleT>::removeFromCluster(ClusterHandle clusterHandle, HandleT handle) { auto& handles = getC(clusterHandle).handles; handles.erase(remove(handles.begin(), handles.end(), handle), handles.end()); m_clusterMap.erase(handle); --m_numHandles; return clusterHandle; } template <typename HandleT> ClusterHandle ClusterBiMap<HandleT>::getClusterH(HandleT handle) const { return m_clusterMap[handle]; } template <typename HandleT> OptionalClusterHandle ClusterBiMap<HandleT>::getClusterOf(HandleT handle) const { auto maybe = m_clusterMap.get(handle); if (maybe) { return *maybe; } return OptionalClusterHandle(); } template <typename HandleT> size_t ClusterBiMap<HandleT>::numCluster() const { return m_cluster.numUsed(); } template <typename HandleT> size_t ClusterBiMap<HandleT>::numHandles() const { return m_numHandles; } template <typename HandleT> void ClusterBiMap<HandleT>::reserve(size_t newCap) { m_cluster.reserve(newCap); m_clusterMap.reserve(newCap); } template<typename HandleT> ClusterBiMapIterator<HandleT>& ClusterBiMapIterator<HandleT>::operator++() { ++m_iterator; return *this; } template<typename HandleT> bool ClusterBiMapIterator<HandleT>::operator==(const ClusterBiMapIterator& other) const { return m_iterator == other.m_iterator; } template<typename HandleT> bool ClusterBiMapIterator<HandleT>::operator!=(const ClusterBiMapIterator& other) const { return m_iterator != other.m_iterator; } template<typename HandleT> ClusterHandle ClusterBiMapIterator<HandleT>::operator*() const { return *m_iterator; } template <typename HandleT> ClusterBiMapIterator<HandleT> ClusterBiMap<HandleT>::begin() const { return m_cluster.begin(); } template <typename HandleT> ClusterBiMapIterator<HandleT> ClusterBiMap<HandleT>::end() const { return m_cluster.end(); } } // namespace lvr2
27.891304
99
0.75039
uos
b632914d2592fde88b55410d451e1a343d27e425
8,097
cpp
C++
sdl1/VisualBoyAdvance/src/win32/AccelEditor.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/VisualBoyAdvance/src/win32/AccelEditor.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/VisualBoyAdvance/src/win32/AccelEditor.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
// VisualBoyAdvance - Nintendo Gameboy/GameboyAdvance (TM) emulator. // Copyright (C) 1999-2003 Forgotten // Copyright (C) 2004 Forgotten and the VBA development team // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2, or(at your option) // any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // AccelEditor.cpp : implementation file // #include "stdafx.h" #include "vba.h" #include "AccelEditor.h" #include "CmdAccelOb.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // AccelEditor dialog AccelEditor::AccelEditor(CWnd* pParent /*=NULL*/) : ResizeDlg(AccelEditor::IDD, pParent) { //{{AFX_DATA_INIT(AccelEditor) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT mgr = theApp.winAccelMgr; } void AccelEditor::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(AccelEditor) DDX_Control(pDX, IDC_CURRENTS, m_currents); DDX_Control(pDX, IDC_ALREADY_AFFECTED, m_alreadyAffected); DDX_Control(pDX, IDC_COMMANDS, m_commands); DDX_Control(pDX, IDC_EDIT_KEY, m_key); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(AccelEditor, CDialog) //{{AFX_MSG_MAP(AccelEditor) ON_BN_CLICKED(ID_OK, OnOk) ON_LBN_SELCHANGE(IDC_COMMANDS, OnSelchangeCommands) ON_BN_CLICKED(IDC_RESET, OnReset) ON_BN_CLICKED(IDC_ASSIGN, OnAssign) ON_BN_CLICKED(ID_CANCEL, OnCancel) ON_BN_CLICKED(IDC_REMOVE, OnRemove) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // AccelEditor message handlers BOOL AccelEditor::OnInitDialog() { CDialog::OnInitDialog(); DIALOG_SIZER_START( sz ) DIALOG_SIZER_ENTRY( IDC_STATIC1, DS_MoveX) DIALOG_SIZER_ENTRY( IDC_STATIC2, DS_MoveY) DIALOG_SIZER_ENTRY( IDC_STATIC3, DS_MoveX | DS_MoveY) DIALOG_SIZER_ENTRY( IDC_ALREADY_AFFECTED, DS_MoveY) DIALOG_SIZER_ENTRY( ID_OK, DS_MoveX) DIALOG_SIZER_ENTRY( ID_CANCEL, DS_MoveX) DIALOG_SIZER_ENTRY( IDC_ASSIGN, DS_MoveX) DIALOG_SIZER_ENTRY( IDC_REMOVE, DS_MoveX) DIALOG_SIZER_ENTRY( IDC_RESET, DS_MoveX) DIALOG_SIZER_ENTRY( IDC_CLOSE, DS_MoveY) DIALOG_SIZER_ENTRY( IDC_COMMANDS, DS_SizeX | DS_SizeY) DIALOG_SIZER_ENTRY( IDC_CURRENTS, DS_MoveX | DS_SizeY) DIALOG_SIZER_ENTRY( IDC_EDIT_KEY, DS_MoveX | DS_MoveY) DIALOG_SIZER_END() SetData(sz, TRUE, HKEY_CURRENT_USER, "Software\\Emulators\\VisualBoyAdvance\\Viewer\\AccelEditor", NULL); InitCommands(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void AccelEditor::InitCommands() { m_commands.ResetContent(); m_alreadyAffected.SetWindowText(""); POSITION pos = mgr.m_mapAccelString.GetStartPosition(); while(pos != NULL) { CString command; WORD wID; mgr.m_mapAccelString.GetNextAssoc(pos, command, wID); int index = m_commands.AddString(command); m_commands.SetItemData(index, wID); } // Update the currents accels associated with the selected command if (m_commands.SetCurSel(0) != LB_ERR) OnSelchangeCommands(); } void AccelEditor::OnCancel() { EndDialog(FALSE); } void AccelEditor::OnOk() { EndDialog(TRUE); } void AccelEditor::OnSelchangeCommands() { // Check if some commands exist. int index = m_commands.GetCurSel(); if (index == LB_ERR) return; WORD wIDCommand = LOWORD(m_commands.GetItemData(index)); m_currents.ResetContent(); CCmdAccelOb* pCmdAccel; if (mgr.m_mapAccelTable.Lookup(wIDCommand, pCmdAccel)) { CAccelsOb* pAccel; CString szBuffer; POSITION pos = pCmdAccel->m_Accels.GetHeadPosition(); // Add the keys to the 'currents keys' listbox. while (pos != NULL) { pAccel = pCmdAccel->m_Accels.GetNext(pos); pAccel->GetString(szBuffer); index = m_currents.AddString(szBuffer); // and a pointer to the accel object. m_currents.SetItemData(index, (DWORD_PTR)pAccel); } } // Init the key editor // m_pKey->ResetKey(); } void AccelEditor::OnReset() { mgr.Default(); InitCommands(); // update the listboxes. } void AccelEditor::OnAssign() { // Control if it's not already affected CCmdAccelOb* pCmdAccel; CAccelsOb* pAccel; WORD wIDCommand; POSITION pos; WORD wKey; bool bCtrl, bAlt, bShift; if (!m_key.GetAccelKey(wKey, bCtrl, bAlt, bShift)) return; // no valid key, abort int count = m_commands.GetCount(); int index; for (index = 0; index < count; index++) { wIDCommand = LOWORD(m_commands.GetItemData(index)); mgr.m_mapAccelTable.Lookup(wIDCommand, pCmdAccel); pos = pCmdAccel->m_Accels.GetHeadPosition(); while (pos != NULL) { pAccel = pCmdAccel->m_Accels.GetNext(pos); if (pAccel->IsEqual(wKey, bCtrl, bAlt, bShift)) { // the key is already affected (in the same or other command) m_alreadyAffected.SetWindowText(pCmdAccel->m_szCommand); m_key.SetSel(0, -1); return; // abort } } } // OK, we can add the accel key in the currently selected group index = m_commands.GetCurSel(); if (index == LB_ERR) return; // Get the object who manage the accels list, associated to the command. wIDCommand = LOWORD(m_commands.GetItemData(index)); if (mgr.m_mapAccelTable.Lookup(wIDCommand, pCmdAccel) != TRUE) return; BYTE cVirt = 0; if (bCtrl) cVirt |= FCONTROL; if (bAlt) cVirt |= FALT; if (bShift) cVirt |= FSHIFT; cVirt |= FVIRTKEY; // Create the new key... pAccel = new CAccelsOb(cVirt, wKey, false); ASSERT(pAccel != NULL); // ...and add in the list. pCmdAccel->m_Accels.AddTail(pAccel); // Update the listbox. CString szBuffer; pAccel->GetString(szBuffer); index = m_currents.AddString(szBuffer); m_currents.SetItemData(index, (DWORD_PTR)pAccel); // Reset the key editor. m_key.ResetKey(); } void AccelEditor::OnRemove() { // Some controls int indexCurrent = m_currents.GetCurSel(); if (indexCurrent == LB_ERR) return; // 2nd part. int indexCmd = m_commands.GetCurSel(); if (indexCmd == LB_ERR) return; // Ref to the ID command WORD wIDCommand = LOWORD(m_commands.GetItemData(indexCmd)); // Run through the accels,and control if it can be deleted. CCmdAccelOb* pCmdAccel; if (mgr.m_mapAccelTable.Lookup(wIDCommand, pCmdAccel) == TRUE) { CAccelsOb* pAccel; CAccelsOb* pAccelCurrent = (CAccelsOb*)(m_currents.GetItemData(indexCurrent)); CString szBuffer; POSITION pos = pCmdAccel->m_Accels.GetHeadPosition(); POSITION PrevPos; while (pos != NULL) { PrevPos = pos; pAccel = pCmdAccel->m_Accels.GetNext(pos); if (pAccel == pAccelCurrent) { if (!pAccel->m_bLocked) { // not locked, so we delete the key pCmdAccel->m_Accels.RemoveAt(PrevPos); delete pAccel; // and update the listboxes/key editor/static text m_currents.DeleteString(indexCurrent); m_key.ResetKey(); m_alreadyAffected.SetWindowText(""); return; } else { systemMessage(0,"Unable to remove this\naccelerator (Locked)"); return; } } } systemMessage(0,"internal error (CAccelDlgHelper::Remove : pAccel unavailable)"); return; } systemMessage(0,"internal error (CAccelDlgHelper::Remove : Lookup failed)"); }
27.824742
85
0.681116
pdpdds
b63479c43fe8c989fc03537f6a2975891c2d8806
124
hpp
C++
include/litmus/details/verbosity.hpp
JessyDL/litmus
156814116d83ee7884c76adda327bf7a9ef0cb14
[ "MIT" ]
1
2021-04-03T00:18:45.000Z
2021-04-03T00:18:45.000Z
include/litmus/details/verbosity.hpp
JessyDL/litmus
156814116d83ee7884c76adda327bf7a9ef0cb14
[ "MIT" ]
null
null
null
include/litmus/details/verbosity.hpp
JessyDL/litmus
156814116d83ee7884c76adda327bf7a9ef0cb14
[ "MIT" ]
null
null
null
#pragma once namespace litmus { enum class verbosity_t { NONE = 0, COMPACT = 1, NORMAL = 2, DETAILED = 3 }; }
10.333333
23
0.596774
JessyDL
b63514f9432f7c5ca3f8514c9e50581e878cb984
1,005
hpp
C++
DifferentialEvolution/DifferentialEvolution.hpp
nottu/LinearSVM
7f5ce05b0691e03a12377dd1f177768f59a91e30
[ "MIT" ]
null
null
null
DifferentialEvolution/DifferentialEvolution.hpp
nottu/LinearSVM
7f5ce05b0691e03a12377dd1f177768f59a91e30
[ "MIT" ]
null
null
null
DifferentialEvolution/DifferentialEvolution.hpp
nottu/LinearSVM
7f5ce05b0691e03a12377dd1f177768f59a91e30
[ "MIT" ]
null
null
null
// // Created by Javier Peralta on 5/31/18. // #ifndef SVM_DIFFERENTIALEVOLUTION_HPP #define SVM_DIFFERENTIALEVOLUTION_HPP #include "../Data.hpp" #include "../OptimizationProblem.hpp" class DifferentialEvolution { public: friend class Individual; class Individual; private: unsigned max_evals; unsigned num_vars; double __cr, __F; OptimizationProblem *__problem; bool minimize; std::vector<Individual> population; std::vector<int> get_parent_idx(); public: DifferentialEvolution(std::vector<Individual> &pop, unsigned max_evals, double cr, double F, OptimizationProblem *problem, ProblemType type = ProblemType::MINIMIZE); Individual getBest(); bool iterate(); }; class DifferentialEvolution::Individual{ friend class DifferentialEvolution; protected: vect data; double value; public: vect get_data(); double get_value(); void set_value(double val); explicit Individual(vect &dat); Individual(vect &dat, double val); }; #endif //SVM_DIFFERENTIALEVOLUTION_HPP
22.840909
167
0.759204
nottu
b637fe4d30b266db56418882aa4a463fc1d8b7cc
1,704
hpp
C++
actan_tools/core/sensors.hpp
oliver-peoples/ACTAN
5ed78c8e88232dab92fb934d0f85c007d4e98596
[ "Unlicense" ]
null
null
null
actan_tools/core/sensors.hpp
oliver-peoples/ACTAN
5ed78c8e88232dab92fb934d0f85c007d4e98596
[ "Unlicense" ]
null
null
null
actan_tools/core/sensors.hpp
oliver-peoples/ACTAN
5ed78c8e88232dab92fb934d0f85c007d4e98596
[ "Unlicense" ]
null
null
null
#ifndef ACTAN_TOOLS_SENSORS_HPP #define ACTAN_TOOLS_SENSORS_HPP #if defined(__float128) #define depth_level __float128 #elif defined(_Float128) #define depth_level _Float128 #else #define depth_level long double #endif #include <hmath/core.hpp> namespace actan { namespace sensor { class Sensor { private: hmath::DualQuaternion<depth_level> mounting_position = { 1,0,0,0,1,0,0,0 }; public: Sensor(); ~Sensor(); void setMountingPosition(hmath::DualQuaternion<depth_level>); void setMountingPosition(hmath::Vector3<depth_level>, hmath::Quaternion<depth_level>); void setMountingPosition(hmath::Quaternion<depth_level>, hmath::Vector3<depth_level>); }; class InertialSensor : public Sensor { private: hmath::Vector3<depth_level> angular_rates_limit, raw_acc_limits; hmath::Vector3<depth_level> latest_angular_rates, latest_raw_acceleration; public: InertialSensor(); ~InertialSensor(); }; class PinholeCamera : public Sensor { private: depth_level focal_length, aperture; public: PinholeCamera(); ~PinholeCamera(); }; } class AHRS : public sensor::InertialSensor { private: hmath::Quaternion<depth_level> orientation; hmath::Vector3<depth_level> free_acceleration; public: AHRS(); ~AHRS(); template<typename T> void setOrientation(hmath::Vector3<T>); template<typename T> void setFreeAcceleration(hmath::Vector3<T>); }; } #endif
24.342857
98
0.619131
oliver-peoples
b64307fb369aa01cc588abc7842c0b68c5383a69
61,868
cpp
C++
src/modules/rppi_filter_operations.cpp
shobana-mcw/rpp
e4a5eb622b9abd0a5a936bf7174a84a5e2470b59
[ "MIT" ]
26
2019-09-04T17:48:41.000Z
2022-02-23T17:04:24.000Z
src/modules/rppi_filter_operations.cpp
shobana-mcw/rpp
e4a5eb622b9abd0a5a936bf7174a84a5e2470b59
[ "MIT" ]
57
2019-09-06T21:37:34.000Z
2022-03-09T02:13:46.000Z
src/modules/rppi_filter_operations.cpp
shobana-mcw/rpp
e4a5eb622b9abd0a5a936bf7174a84a5e2470b59
[ "MIT" ]
24
2019-09-04T23:12:07.000Z
2022-03-30T02:06:22.000Z
#include <rppi_filter_operations.h> #include <rppdefs.h> #include "rppi_validate.hpp" #ifdef HIP_COMPILE #include <hip/rpp_hip_common.hpp> #include "hip/hip_declarations.hpp" #elif defined(OCL_COMPILE) #include <cl/rpp_cl_common.hpp> #include "cl/cl_declarations.hpp" #endif //backend #include <stdio.h> #include <iostream> #include <fstream> #include <chrono> using namespace std::chrono; #include "cpu/host_filter_operations.hpp" /******************** box_filter ********************/ RppStatus rppi_box_filter_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { box_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { box_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_box_filter_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { box_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { box_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_box_filter_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { box_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { box_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_box_filter_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); box_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_box_filter_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); box_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_box_filter_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); box_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; } /******************** sobel_filter ********************/ RppStatus rppi_sobel_filter_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *sobelType, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); copy_param_uint(sobelType, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { sobel_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { sobel_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_sobel_filter_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *sobelType, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); copy_param_uint(sobelType, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { sobel_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { sobel_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_sobel_filter_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *sobelType, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); copy_param_uint(sobelType, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { sobel_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { sobel_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_sobel_filter_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *sobelType, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); sobel_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), sobelType, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_sobel_filter_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *sobelType, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); sobel_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), sobelType, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_sobel_filter_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *sobelType, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); sobel_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), sobelType, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; } /******************** median_filter ********************/ RppStatus rppi_median_filter_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { median_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { median_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_median_filter_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { median_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { median_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_median_filter_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { median_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { median_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_median_filter_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); median_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_median_filter_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); median_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_median_filter_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); median_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; } /******************** custom_convolution ********************/ /******************** non_max_suppression ********************/ RppStatus rppi_non_max_suppression_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { non_max_suppression_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { non_max_suppression_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_non_max_suppression_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { non_max_suppression_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { non_max_suppression_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_non_max_suppression_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { non_max_suppression_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { non_max_suppression_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_non_max_suppression_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); non_max_suppression_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_non_max_suppression_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); non_max_suppression_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_non_max_suppression_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); non_max_suppression_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; } /******************** gaussian_filter ********************/ RppStatus rppi_gaussian_filter_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32f *stdDev, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); copy_param_float(stdDev, rpp::deref(rppHandle), paramIndex++); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { gaussian_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { gaussian_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_gaussian_filter_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32f *stdDev, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); copy_param_float(stdDev, rpp::deref(rppHandle), paramIndex++); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { gaussian_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { gaussian_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_gaussian_filter_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32f *stdDev, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); copy_param_float(stdDev, rpp::deref(rppHandle), paramIndex++); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { gaussian_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { gaussian_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_gaussian_filter_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32f *stdDev, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); gaussian_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), stdDev, kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_gaussian_filter_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32f *stdDev, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); gaussian_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), stdDev, kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_gaussian_filter_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32f *stdDev, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); gaussian_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), stdDev, kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; } /******************** nonlinear_filter ********************/ RppStatus rppi_nonlinear_filter_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { median_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { median_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_nonlinear_filter_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { median_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { median_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_nonlinear_filter_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { median_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { median_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_nonlinear_filter_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); median_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_nonlinear_filter_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); median_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_nonlinear_filter_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); median_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; } // ********************************** custom convolution *************************************** RppStatus rppi_custom_convolution_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, RppPtr_t kernel, RppiSize *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); #ifdef OCL_COMPILE { custom_convolution_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize[0], rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { custom_convolution_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize[0], rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_custom_convolution_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, RppPtr_t kernel, RppiSize *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); #ifdef OCL_COMPILE { custom_convolution_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize[0], rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { custom_convolution_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize[0], rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_custom_convolution_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, RppPtr_t kernel, RppiSize *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); #ifdef OCL_COMPILE { custom_convolution_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize[0], rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { custom_convolution_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize[0], rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_custom_convolution_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, RppPtr_t kernel, RppiSize *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); custom_convolution_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_custom_convolution_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, RppPtr_t kernel, RppiSize *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); custom_convolution_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_custom_convolution_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, RppPtr_t kernel, RppiSize *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); custom_convolution_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; }
37.816626
101
0.457749
shobana-mcw
b6440496a92b62f842701964c833da19c16803e3
906
cpp
C++
src/parser/transform/statement/transform_transaction.cpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-04-22T05:41:54.000Z
2021-04-22T05:41:54.000Z
src/parser/transform/statement/transform_transaction.cpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
null
null
null
src/parser/transform/statement/transform_transaction.cpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-12-12T10:24:57.000Z
2021-12-12T10:24:57.000Z
#include "guinsoodb/parser/statement/transaction_statement.hpp" #include "guinsoodb/parser/transformer.hpp" namespace guinsoodb { unique_ptr<TransactionStatement> Transformer::TransformTransaction(guinsoodb_libpgquery::PGNode *node) { auto stmt = reinterpret_cast<guinsoodb_libpgquery::PGTransactionStmt *>(node); D_ASSERT(stmt); switch (stmt->kind) { case guinsoodb_libpgquery::PG_TRANS_STMT_BEGIN: case guinsoodb_libpgquery::PG_TRANS_STMT_START: return make_unique<TransactionStatement>(TransactionType::BEGIN_TRANSACTION); case guinsoodb_libpgquery::PG_TRANS_STMT_COMMIT: return make_unique<TransactionStatement>(TransactionType::COMMIT); case guinsoodb_libpgquery::PG_TRANS_STMT_ROLLBACK: return make_unique<TransactionStatement>(TransactionType::ROLLBACK); default: throw NotImplementedException("Transaction type %d not implemented yet", stmt->kind); } } } // namespace guinsoodb
39.391304
104
0.825607
GuinsooLab
b6474bdf4746d833e16134adc8dfd774567d6580
4,735
cpp
C++
tools/extras/irstlm/src/doc.cpp
scscscscscsc/kaldi-trunk
aa9a8143e0fee12d85562ccc1d06e0e99f630029
[ "Apache-2.0" ]
4
2016-06-05T14:19:32.000Z
2016-06-07T09:21:10.000Z
tools/extras/irstlm/src/doc.cpp
MistSC/kaldi-trunk
aa9a8143e0fee12d85562ccc1d06e0e99f630029
[ "Apache-2.0" ]
null
null
null
tools/extras/irstlm/src/doc.cpp
MistSC/kaldi-trunk
aa9a8143e0fee12d85562ccc1d06e0e99f630029
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** IrstLM: IRST Language Model Toolkit, compile LM Copyright (C) 2006 Marcello Federico, ITC-irst Trento, Italy This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ******************************************************************************/ #include <math.h> #include <assert.h> #include "util.h" #include "mfstream.h" #include "mempool.h" #include "htable.h" #include "dictionary.h" #include "n_gram.h" #include "doc.h" using namespace std; doc::doc(dictionary* d,char* docfname) { dict=d; n=0; m=0; V=new int[dict->size()]; N=new int[dict->size()]; T=new int[dict->size()]; cd=-1; dfname=docfname; df=NULL; binary=false; }; doc::~doc() { delete [] V; delete [] N; delete [] T; } int doc::open() { df=new mfstream(dfname,ios::in); char header[100]; df->getline(header,100); if (sscanf(header,"DoC %d",&n) && n>0) binary=true; else if (sscanf(header,"%d",&n) && n>0) binary=false; else { exit_error(IRSTLM_ERROR_DATA, "doc::open() error: wrong header\n"); } cerr << "opening: " << n << (binary?" bin-":" txt-") << "docs\n"; cd=-1; return 1; } int doc::reset() { cd=-1; m=0; df->close(); delete df; open(); return 1; } int doc::read() { if (cd >=(n-1)) return 0; m=0; for (int i=0; i<dict->size(); i++) N[i]=0; if (binary) { df->read((char *)&m,sizeof(int)); df->read((char *)V,m * sizeof(int)); df->read((char *)T,m * sizeof(int)); for (int i=0; i<m; i++) { N[V[i]]=T[i]; } } else { int eod=dict->encode(dict->EoD()); int bod=dict->encode(dict->BoD()); ngram ng(dict); while((*df) >> ng) { if (ng.size>0) { if (*ng.wordp(1)==bod) { ng.size=0; continue; } if (*ng.wordp(1)==eod) { ng.size=0; break; } N[*ng.wordp(1)]++; if (N[*ng.wordp(1)]==1)V[m++]=*ng.wordp(1); } } } cd++; return 1; } int doc::savernd(char* fname,int num) { assert((df!=NULL) && (cd==-1)); srand(100); mfstream out(fname,ios::out); out << "DoC\n"; out.write((const char*) &n,sizeof(int)); cerr << "n=" << n << "\n"; //first select num random docs char taken[n]; int r; for (int i=0; i<n; i++) taken[i]=0; for (int d=0; d<num; d++) { while((r=(rand() % n)) && taken[r]) {}; cerr << "random document found " << r << "\n"; taken[r]++; reset(); for (int i=0; i<=r; i++) read(); out.write((const char *)&m,sizeof(int)); out.write((const char*) V,m * sizeof(int)); for (int i=0; i<m; i++) out.write((const char*) &N[V[i]],sizeof(int)); } //write the rest of files reset(); for (int d=0; d<n; d++) { read(); if (!taken[d]) { out.write((const char*)&m,sizeof(int)); out.write((const char*)V,m * sizeof(int)); for (int i=0; i<m; i++) out.write((const char*)&N[V[i]],sizeof(int)); } else { cerr << "do not save doc " << d << "\n"; } } //out.close(); reset(); return 1; } int doc::save(char* fname) { assert((df!=NULL) && (cd==-1)); mfstream out(fname,ios::out); out << "DoC "<< n << "\n"; for (int d=0; d<n; d++) { read(); out.write((const char*)&m,sizeof(int)); out.write((const char*)V,m * sizeof(int)); for (int i=0; i<m; i++) out.write((const char*)&N[V[i]],sizeof(int)); } //out.close(); reset(); return 1; } int doc::save(char* fname, int bsz) { assert((df!=NULL) && (cd==-1)); char name[100]; int i=0; while (cd < (n-1)) { // at least one document sprintf(name,"%s.%d",fname,++i); mfstream out(name,ios::out); int csz=(cd+bsz)<n?bsz:(n-cd-1); out << "DoC "<< csz << "\n"; for (int d=0; d<csz; d++) { read(); out.write((const char*)&m,sizeof(int)); out.write((const char*)V,m * sizeof(int)); for (int i=0; i<m; i++) out.write((const char*)&N[V[i]],sizeof(int)); } out.close(); } reset(); return 1; }
19.729167
79
0.530729
scscscscscsc
b64993be7464496ca9e61403286e83785c0c32b5
8,796
cpp
C++
source/variables/Variant.cpp
alijenabi/RelationBasedSoftware
f26f163d8d3e74e134a33512ae49fb24edb8b3b7
[ "MIT" ]
2
2021-08-06T19:40:34.000Z
2021-09-06T23:07:47.000Z
source/variables/Variant.cpp
alijenabi/RelationBasedSoftware
f26f163d8d3e74e134a33512ae49fb24edb8b3b7
[ "MIT" ]
null
null
null
source/variables/Variant.cpp
alijenabi/RelationBasedSoftware
f26f163d8d3e74e134a33512ae49fb24edb8b3b7
[ "MIT" ]
null
null
null
// // Variant.cpp // Relation-Based Simulator (RBS) // // Created by Ali Jenabidehkordi on 19.08.18. // Copyright © 2018 Ali Jenabidehkordi. All rights reserved. // #include "Variant.h" namespace rbs::variables { Variant::Variant() : p_id{ TypeID::None } , p_value{} { } Variant::Variant(const Variant &other) = default; Variant::Variant(Variant &&other) { p_id = std::move(other.p_id); p_value = std::move(other.p_value); } bool Variant::hasValue() const { return p_id != TypeID::None; } bool Variant::isEmpty() const { return p_id == TypeID::None; } void Variant::clear() { p_id = TypeID::None; } bool Variant::operator==(const Variant &other) const { if( p_id == other.p_id ) { switch (p_id) { case TypeID::None: return true; case TypeID::Vector1D: return std::get<space::Vector<1> >(p_value) == std::get<space::Vector<1> >(other.p_value); case TypeID::Vector2D: return std::get<space::Vector<2> >(p_value) == std::get<space::Vector<2> >(other.p_value); case TypeID::Vector3D: return std::get<space::Vector<3> >(p_value) == std::get<space::Vector<3> >(other.p_value); case TypeID::Point1D: return std::get<space::Point<1> >(p_value) == std::get<space::Point<1> >(other.p_value); case TypeID::Point2D: return std::get<space::Point<2> >(p_value) == std::get<space::Point<2> >(other.p_value); case TypeID::Point3D: return std::get<space::Point<3> >(p_value) == std::get<space::Point<3> >(other.p_value); case TypeID::Index1D: return std::get<space::Index<1> >(p_value) == std::get<space::Index<1> >(other.p_value); case TypeID::Index2D: return std::get<space::Index<2> >(p_value) == std::get<space::Index<2> >(other.p_value); case TypeID::Index3D: return std::get<space::Index<3> >(p_value) == std::get<space::Index<3> >(other.p_value); case TypeID::LongDouble: return std::get<long double>(p_value) == std::get<double>(other.p_value); case TypeID::Double: return std::get<double>(p_value) == std::get<double>(other.p_value); case TypeID::Float: return std::get<float>(p_value) == std::get<float>(other.p_value); case TypeID::UnsignedLongLong: return std::get<unsigned long long>(p_value) == std::get<unsigned long long>(other.p_value); case TypeID::UnsignedLong: return std::get<unsigned long>(p_value) == std::get<unsigned long>(other.p_value); case TypeID::UnsignedInt: return std::get<unsigned int>(p_value) == std::get<unsigned int>(other.p_value); case TypeID::UnsignedShort: return std::get<unsigned short>(p_value) == std::get<unsigned short>(other.p_value); case TypeID::UnsignedChar: return std::get<unsigned char>(p_value) == std::get<unsigned char>(other.p_value); case TypeID::LongLong: return std::get<long long>(p_value) == std::get<long long>(other.p_value); case TypeID::Long: return std::get<long>(p_value) == std::get<long>(other.p_value); case TypeID::Int: return std::get<int>(p_value) == std::get<int>(other.p_value); case TypeID::Short: return std::get<short>(p_value) == std::get<short>(other.p_value); case TypeID::Char: return std::get<char>(p_value) == std::get<char>(other.p_value); case TypeID::Bool: return std::get<bool>(p_value) == std::get<bool>(other.p_value); case TypeID::String: return std::get<std::string>(p_value) == std::get<std::string>(other.p_value); default: throw std::out_of_range("The type of the Variant is not recognized."); } } return false; } bool Variant::operator!=(const Variant &other) const { return !operator==(other); } variables::Variant::operator std::string() const { std::string ans = "Variant:{"; if(isEmpty()) { ans = ans + "empty"; } else { ans = ans + "type: " + type_to_string() + ", value: " + value_to_string(); } return ans + "}"; } std::string Variant::value_to_string() const { switch (p_id) { case TypeID::None: return "uninitialized"; case TypeID::Vector1D: return std::string(std::get<space::Vector<1> >(p_value)); case TypeID::Vector2D: return std::string(std::get<space::Vector<2> >(p_value)); case TypeID::Vector3D: return std::string(std::get<space::Vector<3> >(p_value)); case TypeID::Point1D: return std::string(std::get<space::Point<1> >(p_value)); case TypeID::Point2D: return std::string(std::get<space::Point<2> >(p_value)); case TypeID::Point3D: return std::string(std::get<space::Point<3> >(p_value)); case TypeID::Index1D: return std::string(std::get<space::Index<1> >(p_value)); case TypeID::Index2D: return std::string(std::get<space::Index<2> >(p_value)); case TypeID::Index3D: return std::string(std::get<space::Index<3> >(p_value)); case TypeID::LongDouble: return std::to_string(std::get<long double>(p_value)); case TypeID::Double: return std::to_string(std::get<double>(p_value)); case TypeID::Float: return std::to_string(std::get<float>(p_value)); case TypeID::UnsignedLongLong: return std::to_string(std::get<unsigned long long>(p_value)); case TypeID::UnsignedLong: return std::to_string(std::get<unsigned long>(p_value)); case TypeID::UnsignedInt: return std::to_string(std::get<unsigned int>(p_value)); case TypeID::UnsignedShort: return std::to_string(std::get<unsigned short>(p_value)); case TypeID::UnsignedChar: return std::to_string(std::get<unsigned char>(p_value)); case TypeID::LongLong: return std::to_string(std::get<long long>(p_value)); case TypeID::Long: return std::to_string(std::get<long>(p_value)); case TypeID::Int: return std::to_string(std::get<int>(p_value)); case TypeID::Short: return std::to_string(std::get<short>(p_value)); case TypeID::Char: return std::to_string(std::get<char>(p_value)); case TypeID::Bool: return std::to_string(std::get<bool>(p_value)); case TypeID::String: return std::get<std::string>(p_value); default: throw std::out_of_range("The type of the Variant is not recognized."); } } std::string Variant::type_to_string() const { switch (p_id) { case TypeID::None: return "none"; case TypeID::Vector1D: return "space::Vector<1>"; case TypeID::Vector2D: return "space::Vector<2>"; case TypeID::Vector3D: return "space::Vector<3>"; case TypeID::Point1D: return "space::Point<1>"; case TypeID::Point2D: return "space::Point<2>"; case TypeID::Point3D: return "space::Point<3>"; case TypeID::Index1D: return "space::Index<1>"; case TypeID::Index2D: return "space::Index<2>"; case TypeID::Index3D: return "space::Index<3>"; case TypeID::LongDouble: return "long double"; case TypeID::Double: return "double"; case TypeID::Float: return "float"; case TypeID::UnsignedLongLong: return "unsigned long long"; case TypeID::UnsignedLong: return "unsigned long"; case TypeID::UnsignedInt: return "unsigned int"; case TypeID::UnsignedShort: return "unsigned short"; case TypeID::UnsignedChar: return "unsigned char"; case TypeID::LongLong: return "long long"; case TypeID::Long: return "long"; case TypeID::Int: return "int"; case TypeID::Short: return "short"; case TypeID::Char: return "char"; case TypeID::Bool: return "bool"; case TypeID::String: return "std::string"; default: throw std::out_of_range("The type of the Variant is not recognized."); } } std::size_t Variant::index() const { return static_cast<std::size_t>(p_id) - 1; } void Variant::swap(Variant &other) { std::swap(p_id, other.p_id); std::swap(p_value, other.p_value); } Variant &Variant::operator =(Variant other) { swap(other); return *this; } std::ostream &operator <<(std::ostream &out, const Variant &variant) { return out << std::string(variant); } } // namespace rbs::variant
52.357143
135
0.593565
alijenabi
b649f164b0f698ac856b600e19c2c775a25ace8b
2,575
cpp
C++
imctrans/cpp/assets/tests/test_InlineMessage.cpp
paulosousadias/imctrans
cfa2a12ea577d9aa214c2bbb23f3561e8b50ee8f
[ "Apache-2.0" ]
null
null
null
imctrans/cpp/assets/tests/test_InlineMessage.cpp
paulosousadias/imctrans
cfa2a12ea577d9aa214c2bbb23f3561e8b50ee8f
[ "Apache-2.0" ]
1
2019-05-23T18:36:57.000Z
2019-05-23T18:58:32.000Z
imctrans/cpp/assets/tests/test_InlineMessage.cpp
paulosousadias/imctrans
cfa2a12ea577d9aa214c2bbb23f3561e8b50ee8f
[ "Apache-2.0" ]
6
2018-11-22T18:10:58.000Z
2020-06-26T16:55:35.000Z
//*************************************************************************** // Copyright 2017 OceanScan - Marine Systems & Technology, Lda. * //*************************************************************************** // 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. * //*************************************************************************** // Author: Ricardo Martins * //*************************************************************************** // IMC headers. #include <IMC/Base/InlineMessage.hpp> #include <IMC/Spec/EulerAngles.hpp> // Catch headers. #define CATCH_CONFIG_MAIN #include "catch.hpp" TEST_CASE("opsOnNull") { IMC::InlineMessage<IMC::EulerAngles> imsg; REQUIRE_THROWS_AS(imsg.get(), std::runtime_error); REQUIRE(imsg.getSerializationSize() == 2); } TEST_CASE("serializeNull") { uint8_t bfr[128]; IMC::InlineMessage<IMC::EulerAngles> imsg; REQUIRE(imsg.serialize(bfr) == 2); } TEST_CASE("equalOperatorBothNull") { IMC::InlineMessage<IMC::EulerAngles> a; IMC::InlineMessage<IMC::EulerAngles> b; REQUIRE(a == b); } TEST_CASE("equalOperatorOneNull") { IMC::EulerAngles msg; IMC::InlineMessage<IMC::EulerAngles> a; a.set(msg); IMC::InlineMessage<IMC::EulerAngles> b; REQUIRE(a != b); } TEST_CASE("getNull") { IMC::InlineMessage<IMC::EulerAngles> imsg; REQUIRE_THROWS(imsg.get()); } TEST_CASE("getId") { IMC::InlineMessage<IMC::EulerAngles> imsg; REQUIRE(imsg.getId() == IMC::Message::nullId()); IMC::EulerAngles msg; imsg.set(msg); REQUIRE(imsg.getId() == msg.getId()); } TEST_CASE("setByPointerCompareDereference") { IMC::InlineMessage<IMC::EulerAngles> imsg; IMC::EulerAngles msg; imsg.set(&msg); REQUIRE(*imsg == msg); }
32.1875
77
0.528155
paulosousadias
b64a0ca2541b8c7a1eb67199fe1d100f536c2f4d
10,723
cpp
C++
ToolKit/ReportControl/XTPReportColumns.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
2
2018-03-30T06:40:08.000Z
2022-02-23T12:40:13.000Z
ToolKit/ReportControl/XTPReportColumns.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
null
null
null
ToolKit/ReportControl/XTPReportColumns.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
1
2020-08-11T05:48:02.000Z
2020-08-11T05:48:02.000Z
// XTPReportColumns.cpp : implementation of the CXTPReportColumns class. // // This file is a part of the XTREME REPORTCONTROL MFC class library. // (c)1998-2011 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Common/XTPPropExchange.h" #include "XTPReportControl.h" #include "XTPReportHeader.h" #include "XTPReportColumn.h" #include "XTPReportColumns.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CXTPReportColumns CXTPReportColumns::CXTPReportColumns(CXTPReportControl* pControl) : m_pControl(pControl) { m_pGroupsOrder = new CXTPReportColumnOrder(this); m_pSortOrder = new CXTPReportColumnOrder(this); m_pTreeColumn = NULL; } CXTPReportColumns::~CXTPReportColumns() { Clear(); if (m_pGroupsOrder) m_pGroupsOrder->InternalRelease(); if (m_pSortOrder) m_pSortOrder->InternalRelease(); } void CXTPReportColumns::Clear() { // array cleanup for (int nColumn = GetCount() - 1; nColumn >= 0; nColumn--) { CXTPReportColumn* pColumn = m_arrColumns.GetAt(nColumn); if (pColumn) pColumn->InternalRelease(); } m_arrColumns.RemoveAll(); m_pSortOrder->Clear(); m_pGroupsOrder->Clear(); // clear variables which could be references to those values if (m_pControl && (m_pControl->GetColumns() == this)) m_pControl->SetFocusedColumn(NULL); } int CXTPReportColumnOrder::GetCount() const { return (int) m_arrColumns.GetSize(); } void CXTPReportColumns::Add(CXTPReportColumn* pColumn) { pColumn->m_pColumns = this; m_arrColumns.Add(pColumn); GetReportHeader()->OnColumnsChanged(xtpReportColumnOrderChanged | xtpReportColumnAdded, pColumn); } CXTPReportHeader* CXTPReportColumns::GetReportHeader() const { return m_pControl->GetReportHeader(); } void CXTPReportColumns::Remove(CXTPReportColumn* pColumn) { m_pGroupsOrder->Remove(pColumn); m_pSortOrder->Remove(pColumn); int nIndex = IndexOf(pColumn); if (nIndex != -1) { m_arrColumns.RemoveAt(nIndex); pColumn->InternalRelease(); GetReportHeader()->OnColumnsChanged(xtpReportColumnOrderChanged | xtpReportColumnRemoved, pColumn); } } int CXTPReportColumns::IndexOf(const CXTPReportColumn* pColumn) const { // array cleanup for (int nColumn = GetCount() - 1; nColumn >= 0; nColumn--) { if (m_arrColumns.GetAt(nColumn) == pColumn) return nColumn; } return -1; } void CXTPReportColumns::ResetSortOrder() { m_pSortOrder->Clear(); } void CXTPReportColumns::SetSortColumn(CXTPReportColumn* pColumn, BOOL bIncreasing) { ResetSortOrder(); m_pSortOrder->Add(pColumn, bIncreasing); } int CXTPReportColumns::ChangeColumnOrder(int nNewOrder, int nItemIndex) { if (nNewOrder < 0 || nItemIndex < 0) return -1; CXTPReportColumn* pColumn = GetAt(nItemIndex); if (pColumn) { if (nNewOrder == nItemIndex) return nNewOrder; if (nNewOrder > nItemIndex) nNewOrder--; m_arrColumns.RemoveAt(nItemIndex); m_arrColumns.InsertAt(nNewOrder, pColumn); } return nNewOrder; } int CXTPReportColumns::GetVisibleColumnsCount() const { int nVisibleCount = 0; int nCount = GetCount(); for (int nColumn = 0; nColumn < nCount; nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); if (pColumn && pColumn->IsVisible()) nVisibleCount++; } return nVisibleCount; } void CXTPReportColumns::GetVisibleColumns(CXTPReportColumns& arrColumns) const { int nCount = GetCount(); for (int nColumn = 0; nColumn < nCount; nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); if (pColumn && pColumn->IsVisible()) { arrColumns.m_arrColumns.Add(pColumn); pColumn->InternalAddRef(); } } } CXTPReportColumn* CXTPReportColumns::Find(int nItemIndex) const { for (int nColumn = 0; nColumn < GetCount(); nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); if (pColumn->GetItemIndex() == nItemIndex) return pColumn; } return NULL; } CXTPReportColumn* CXTPReportColumns::Find(const CString& strInternalName) const { for (int nColumn = 0; nColumn < GetCount(); nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); if (pColumn->GetInternalName() == strInternalName) return pColumn; } return NULL; } void CXTPReportColumns::InsertSortColumn(CXTPReportColumn* pColumn) { if (m_pSortOrder->IndexOf(pColumn) == -1) m_pSortOrder->Add(pColumn); } CXTPReportColumn* CXTPReportColumns::GetVisibleAt(int nIndex) const { for (int nColumn = 0; nColumn < GetCount(); nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); if (!pColumn->IsVisible()) continue; if (nIndex == 0) return pColumn; nIndex--; } return NULL; } CXTPReportColumn* CXTPReportColumns::GetFirstVisibleColumn() const { for (int nColumn = 0; nColumn < GetCount(); nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); if (pColumn->IsVisible()) return pColumn; } return NULL; } CXTPReportColumn* CXTPReportColumns::GetLastVisibleColumn() const { for (int nColumn = GetCount() - 1; nColumn >= 0; nColumn--) { CXTPReportColumn* pColumn = GetAt(nColumn); if (pColumn->IsVisible()) return pColumn; } return NULL; } void CXTPReportColumns::DoPropExchange(CXTPPropExchange* pPX) { int nItemIndex; CString strInternalName; if (pPX->IsStoring()) { int nCount = GetCount(); CXTPPropExchangeEnumeratorPtr pEnumerator(pPX->GetEnumerator(_T("Column"))); POSITION pos = pEnumerator->GetPosition(nCount, FALSE); for (int nColumn = 0; nColumn < nCount; nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); CXTPPropExchangeSection secColumn(pEnumerator->GetNext(pos)); nItemIndex = pColumn->GetItemIndex(); strInternalName = pColumn->GetInternalName(); PX_Int(&secColumn, _T("ItemIndex"), nItemIndex); PX_String(&secColumn, _T("InternalName"), strInternalName); pColumn->DoPropExchange(&secColumn); } } else { CXTPPropExchangeEnumeratorPtr pEnumerator(pPX->GetEnumerator(_T("Column"))); POSITION pos = pEnumerator->GetPosition(0, FALSE); CXTPReportColumn tmpColumn(0, _T(""), 0); int i = 0; while (pos) { CXTPPropExchangeSection secColumn(pEnumerator->GetNext(pos)); CXTPReportColumn* pColumn = NULL; PX_Int(&secColumn, _T("ItemIndex"), nItemIndex, -1); if (pPX->GetSchema() > _XTP_SCHEMA_110) { PX_String(&secColumn, _T("InternalName"), strInternalName); if (!strInternalName.IsEmpty()) { pColumn = Find(strInternalName); // column data is exists but column is not in the collection. if (!pColumn) { // just read data to skeep (to be safe for array serialization) tmpColumn.DoPropExchange(&secColumn); continue; } } } if (!pColumn) pColumn = Find(nItemIndex); if (!pColumn) AfxThrowArchiveException(CArchiveException::badIndex); pColumn->DoPropExchange(&secColumn); ChangeColumnOrder(i, IndexOf(pColumn)); i++; } } CXTPPropExchangeSection secGroupsOrder(pPX->GetSection(_T("GroupsOrder"))); m_pGroupsOrder->DoPropExchange(&secGroupsOrder); CXTPPropExchangeSection secSortOrder(pPX->GetSection(_T("SortOrder"))); m_pSortOrder->DoPropExchange(&secSortOrder); } ///////////////////////////////////////////////////////////////////////////// // CXTPReportColumnOrder CXTPReportColumnOrder::CXTPReportColumnOrder(CXTPReportColumns* pColumns) : m_pColumns(pColumns) { } CXTPReportColumn* CXTPReportColumnOrder::GetAt(int nIndex) { if (nIndex >= 0 && nIndex < GetCount()) return m_arrColumns.GetAt(nIndex); else return NULL; } int CXTPReportColumnOrder::InsertAt(int nIndex, CXTPReportColumn* pColumn) { if (nIndex < 0) return -1; if (nIndex >= GetCount()) nIndex = GetCount(); int nPrevIndex = IndexOf(pColumn); if (nPrevIndex != -1) { if (nPrevIndex == nIndex) return nIndex; if (nIndex > nPrevIndex) nIndex--; if (nIndex == nPrevIndex) return nIndex; // change order m_arrColumns.RemoveAt(nPrevIndex); } m_arrColumns.InsertAt(nIndex, pColumn); return nIndex; } int CXTPReportColumnOrder::Add(CXTPReportColumn* pColumn, BOOL bSortIncreasing) { pColumn->m_bSortIncreasing = bSortIncreasing; return (int) m_arrColumns.Add(pColumn); } int CXTPReportColumnOrder::Add(CXTPReportColumn* pColumn) { return (int) m_arrColumns.Add(pColumn); } void CXTPReportColumnOrder::Clear() { m_arrColumns.RemoveAll(); } int CXTPReportColumnOrder::IndexOf(const CXTPReportColumn* pColumn) { int nCount = GetCount(); for (int i = 0; i < nCount; i++) { if (GetAt(i) == pColumn) return i; } return -1; } void CXTPReportColumnOrder::RemoveAt(int nIndex) { if (nIndex >= 0 && nIndex < GetCount()) m_arrColumns.RemoveAt(nIndex); } void CXTPReportColumnOrder::Remove(CXTPReportColumn* pColumn) { int nCount = GetCount(); for (int i = 0; i < nCount; i++) { if (GetAt(i) == pColumn) { m_arrColumns.RemoveAt(i); break; } } } void CXTPReportColumnOrder::DoPropExchange(CXTPPropExchange* pPX) { if (pPX->IsStoring()) { int nCount = GetCount(); PX_Int(pPX, _T("Count"), nCount, 0); for (int i = 0; i < nCount; i++) { CXTPReportColumn* pColumn = GetAt(i); if (pColumn) { int nItemIndex = pColumn->GetItemIndex(); CString strInternalName = pColumn->GetInternalName(); CString strParamName; strParamName.Format(_T("Column%i"), i); PX_Int(pPX, strParamName, nItemIndex, 0); strParamName.Format(_T("InternalName%i"), i); PX_String(pPX, strParamName, strInternalName); } } } else { Clear(); int nCount = 0; PX_Int(pPX, _T("Count"), nCount, 0); for (int i = 0; i < nCount; i++) { int nItemIndex = 0; CString strParamName; strParamName.Format(_T("Column%i"), i); PX_Int(pPX, strParamName, nItemIndex, 0); CXTPReportColumn* pColumn = NULL; if (pPX->GetSchema() > _XTP_SCHEMA_110) { strParamName.Format(_T("InternalName%i"), i); CString strInternalName; PX_String(pPX, strParamName, strInternalName); if (!strInternalName.IsEmpty()) pColumn = m_pColumns->Find(strInternalName); } if (!pColumn) pColumn = m_pColumns->Find(nItemIndex); if (pColumn) Add(pColumn); } } }
22.246888
101
0.69654
11Zero
b64aa8d9436b0552bbce48e8c47f37dbf5e429c0
1,248
cpp
C++
depth_breadth_search/leetcode_dfs/366_find_leaves_of_bianry_tree.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:19.000Z
2020-10-12T19:18:19.000Z
depth_breadth_search/leetcode_dfs/366_find_leaves_of_bianry_tree.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
null
null
null
depth_breadth_search/leetcode_dfs/366_find_leaves_of_bianry_tree.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:04.000Z
2020-10-12T19:18:04.000Z
// // 366_find_leaves_of_bianry_tree.cpp // leetcode_dfs // // Created by Hadley on 26.08.20. // Copyright © 2020 Hadley. All rights reserved. // #include <iostream> #include <fstream> #include <stdio.h> #include <algorithm> #include <iostream> #include <vector> #include <string> #include <unordered_map> #include <stack> #include <cstring> #include <queue> #include <functional> #include <numeric> #include <map> #include <filesystem> #include <dirent.h> using namespace std; //Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class Solution { public: int dfs(TreeNode* root){ if(!root)return 0; int l=dfs(root->left)+1; int r=dfs(root->right)+1; int index=max(l,r)-1; if(index>=res.size())res.push_back({}); res[index].push_back(root->val); return max(l,r); } vector<vector<int>> findLeaves(TreeNode* root) { dfs(root); return res; } private: vector<vector<int>>res; };
22.285714
91
0.634615
Hadleyhzy
b64be8ad8172ca61b4bd07a4e0923083f1e615f6
601
cpp
C++
Game/Source/Entity.cpp
Paideieitor/PlatformerGame
e00602171807c694b0c5f4afac50157ce9cd23b1
[ "MIT" ]
null
null
null
Game/Source/Entity.cpp
Paideieitor/PlatformerGame
e00602171807c694b0c5f4afac50157ce9cd23b1
[ "MIT" ]
null
null
null
Game/Source/Entity.cpp
Paideieitor/PlatformerGame
e00602171807c694b0c5f4afac50157ce9cd23b1
[ "MIT" ]
null
null
null
#include "Collisions.h" #include "Entity.h" Entity::Entity(EntityType type, fPoint position, bool flip, Player* parent) { this->type = type; this->position = position; this->flip = flip; this->parent = parent; toDelete = false; toRemove = false; flip = false; } Entity::~Entity() { } bool Entity::Update(float dt) { return true; } void Entity::Collision(Collider* c1, Collider* c2) { } void Entity::UIEvent(Element* element, ElementData&) { } fPoint Entity::GetDrawPosition(iPoint size) { fPoint output = position; output.x -= size.x / 2; output.y -= size.y / 2; return output; }
14.309524
75
0.678869
Paideieitor
b6551c3c68b0bc35a21af4fd16c77fa72cfc1c35
1,413
hpp
C++
src/snabl/bset.hpp
codr4life/snabl
b1c8a69e351243a3ae73d69754971d540c224733
[ "MIT" ]
22
2018-08-27T15:28:10.000Z
2022-02-13T08:18:00.000Z
src/snabl/bset.hpp
codr4life/snabl
b1c8a69e351243a3ae73d69754971d540c224733
[ "MIT" ]
3
2018-08-27T01:44:51.000Z
2020-06-28T20:07:42.000Z
src/snabl/bset.hpp
codr4life/snabl
b1c8a69e351243a3ae73d69754971d540c224733
[ "MIT" ]
2
2018-08-26T18:55:47.000Z
2018-09-29T01:04:36.000Z
#ifndef SNABL_BSET_HPP #define SNABL_BSET_HPP #include "snabl/cmp.hpp" #include "snabl/std.hpp" #include "snabl/types.hpp" namespace snabl { template <typename KeyT, typename ValT> struct BSet { using Vals = vector<ValT>; Vals vals; KeyT ValT::*key_ptr; BSet(KeyT ValT::*key_ptr): key_ptr(key_ptr) { } BSet(KeyT ValT::*key_ptr, const Vals &source): vals(source), key_ptr(key_ptr) { } I64 find(const KeyT &key, I64 min, ValT **found=nullptr) const { I64 max = vals.size(); while (min < max) { const I64 i = (max+min) / 2; const ValT &v(vals[i]); const KeyT &k = v.*key_ptr; switch (cmp(key, k)) { case Cmp::LT: max = i; break; case Cmp::EQ: if (found) { *found = const_cast<ValT *>(&v); } return i; case Cmp::GT: min = i+1; break; } } return min; } ValT *find(const KeyT &key) const { ValT *found(nullptr); find(key, 0, &found); return found; } template <typename...ArgsT> ValT *emplace(const KeyT &key, ArgsT &&...args) { ValT *found(nullptr); const I64 i(find(key, 0, &found)); if (found) { return nullptr; } return &*vals.emplace(vals.begin()+i, forward<ArgsT>(args)...); } void clear() { vals.clear(); } }; } #endif
22.428571
69
0.530078
codr4life
b65aed50316ad423ff5b0889dbc0247d96bbee14
865
cpp
C++
src/lfilesaver/server/util/DefaultStatsProvider.cpp
yamadapc/filesaver
9665cb30615530fb4aeeb775efb92092c7a51eb1
[ "MIT" ]
28
2019-09-09T08:13:25.000Z
2022-02-09T06:20:31.000Z
src/lfilesaver/server/util/DefaultStatsProvider.cpp
yamadapc/filesaver
9665cb30615530fb4aeeb775efb92092c7a51eb1
[ "MIT" ]
2
2020-05-26T02:06:42.000Z
2021-04-08T08:16:03.000Z
src/lfilesaver/server/util/DefaultStatsProvider.cpp
yamadapc/filesaver
9665cb30615530fb4aeeb775efb92092c7a51eb1
[ "MIT" ]
1
2020-06-09T23:40:04.000Z
2020-06-09T23:40:04.000Z
// // Created by Pedro Tacla Yamada on 14/7/20. // #include "DefaultStatsProvider.h" namespace filesaver::server { static const double MILLISECONDS_IN_SECOND = 1000.; DefaultStatsProvider::DefaultStatsProvider (services::stats::ThroughputTracker* throughputTracker, services::FileSizeService* fileSizeService) : m_throughputTracker (throughputTracker), m_fileSizeService (fileSizeService) { } Stats DefaultStatsProvider::getStats () { auto totalFiles = m_fileSizeService->getTotalFiles (); auto millisecondsElapsed = m_throughputTracker->getElapsedMilliseconds (); double filesPerSecond = MILLISECONDS_IN_SECOND * (static_cast<double> (totalFiles) / static_cast<double> (millisecondsElapsed)); return {filesPerSecond, millisecondsElapsed, totalFiles}; } } // namespace filesaver::server
30.892857
112
0.738728
yamadapc
b65b8a8657c4a8f38124f9ad71297f1732e7f9ad
396
cpp
C++
source/ShaderAST/Expr/ExprModulo.cpp
Praetonus/ShaderWriter
1c5b3961e3e1b91cb7158406998519853a4add07
[ "MIT" ]
148
2018-10-11T16:51:37.000Z
2022-03-26T13:55:08.000Z
source/ShaderAST/Expr/ExprModulo.cpp
Praetonus/ShaderWriter
1c5b3961e3e1b91cb7158406998519853a4add07
[ "MIT" ]
30
2019-11-30T11:43:07.000Z
2022-01-25T21:09:47.000Z
source/ShaderAST/Expr/ExprModulo.cpp
Praetonus/ShaderWriter
1c5b3961e3e1b91cb7158406998519853a4add07
[ "MIT" ]
8
2020-04-17T13:18:30.000Z
2021-11-20T06:24:44.000Z
/* See LICENSE file in root folder */ #include "ShaderAST/Expr/ExprModulo.hpp" #include "ShaderAST/Expr/ExprVisitor.hpp" namespace ast::expr { Modulo::Modulo( type::TypePtr type , ExprPtr lhs , ExprPtr rhs ) : Binary{ std::move( type ) , std::move( lhs ) , std::move( rhs ) , Kind::eModulo } { } void Modulo::accept( VisitorPtr vis ) { vis->visitModuloExpr( this ); } }
15.84
41
0.643939
Praetonus
b65c5929e2e4a41de1bc85f2e30e137110bcc2d8
1,487
cpp
C++
cpp/app.cpp
yorung/dx12playground
760bbd9b3dedf26a4c00219628c58721a70d4446
[ "MIT" ]
2
2016-06-16T14:00:40.000Z
2020-04-26T12:11:34.000Z
cpp/app.cpp
yorung/dx12playground
760bbd9b3dedf26a4c00219628c58721a70d4446
[ "MIT" ]
null
null
null
cpp/app.cpp
yorung/dx12playground
760bbd9b3dedf26a4c00219628c58721a70d4446
[ "MIT" ]
null
null
null
#include "stdafx.h" App app; App::App() { } void App::Draw() { const IVec2 scrSize = systemMisc.GetScreenSize(); constexpr float f = 1000; constexpr float n = 1; const float aspect = (float)scrSize.x / scrSize.y; Mat proj = perspectiveLH(45.0f * (float)M_PI / 180.0f, aspect, n, f); matrixMan.Set(MatrixMan::PROJ, proj); rt.BeginRenderToThis(); triangle.Draw(); skyMan.Draw(); rsPostProcess.Apply(); deviceMan.SetRenderTarget(); afBindTextureToBindingPoint(rt.GetTexture(), 0); afDraw(PT_TRIANGLESTRIP, 4); fontMan.Render(); } void App::Init() { GoMyDir(); triangle.Create(); // skyMan.Create("yangjae_row.dds", "sky_photosphere"); skyMan.Create("yangjae.dds", "sky_photosphere"); // skyMan.Create("C:\\Program Files (x86)\\Microsoft DirectX SDK (August 2009)\\Samples\\Media\\Lobby\\LobbyCube.dds", "sky_cubemap"); fontMan.Init(); const IVec2 scrSize = systemMisc.GetScreenSize(); rt.Init(scrSize, AFF_R8G8B8A8_UNORM, AFF_D32_FLOAT_S8_UINT); SamplerType sampler = AFST_POINT_CLAMP; rsPostProcess.Create("vivid", 0, nullptr, BM_NONE, DSM_DISABLE, CM_DISABLE, 1, &sampler); } void App::Destroy() { deviceMan.Flush(); triangle.Destroy(); skyMan.Destroy(); fontMan.Destroy(); rsPostProcess.Destroy(); rt.Destroy(); } void App::Update() { matrixMan.Set(MatrixMan::VIEW, devCamera.CalcViewMatrix()); fps.Update(); fontMan.DrawString(Vec2(20, 40), 20, SPrintf("FPS: %f", fps.Get())); }
23.234375
135
0.677875
yorung
b65ddc6dec39b505392574d96c345095e856a9ef
6,408
cpp
C++
src/physics/operators/nonlinear_solid_operators.cpp
joshessman-llnl/serac
1365a8f9ca372f0c50008b4b8f5f718955e4b80c
[ "BSD-3-Clause" ]
null
null
null
src/physics/operators/nonlinear_solid_operators.cpp
joshessman-llnl/serac
1365a8f9ca372f0c50008b4b8f5f718955e4b80c
[ "BSD-3-Clause" ]
null
null
null
src/physics/operators/nonlinear_solid_operators.cpp
joshessman-llnl/serac
1365a8f9ca372f0c50008b4b8f5f718955e4b80c
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019, Lawrence Livermore National Security, LLC and // other Serac Project Developers. See the top-level LICENSE file for // details. // // SPDX-License-Identifier: (BSD-3-Clause) #include "physics/operators/nonlinear_solid_operators.hpp" #include "infrastructure/logger.hpp" #include "numerics/expr_template_ops.hpp" namespace serac { NonlinearSolidQuasiStaticOperator::NonlinearSolidQuasiStaticOperator(std::unique_ptr<mfem::ParNonlinearForm> H_form, const BoundaryConditionManager& bcs) : mfem::Operator(H_form->FESpace()->GetTrueVSize()), H_form_(std::move(H_form)), bcs_(bcs) { } // compute: y = H(x,p) void NonlinearSolidQuasiStaticOperator::Mult(const mfem::Vector& k, mfem::Vector& y) const { // Apply the nonlinear form H_form_->Mult(k, y); H_form_->Mult(k, y); y.SetSubVector(bcs_.allEssentialDofs(), 0.0); } // Compute the Jacobian from the nonlinear form mfem::Operator& NonlinearSolidQuasiStaticOperator::GetGradient(const mfem::Vector& x) const { auto& grad = dynamic_cast<mfem::HypreParMatrix&>(H_form_->GetGradient(x)); bcs_.eliminateAllEssentialDofsFromMatrix(grad); return grad; } // destructor NonlinearSolidQuasiStaticOperator::~NonlinearSolidQuasiStaticOperator() {} NonlinearSolidDynamicOperator::NonlinearSolidDynamicOperator(std::unique_ptr<mfem::ParNonlinearForm> H_form, std::unique_ptr<mfem::ParBilinearForm> S_form, std::unique_ptr<mfem::ParBilinearForm> M_form, const BoundaryConditionManager& bcs, EquationSolver& newton_solver, const serac::LinearSolverParameters& lin_params) : mfem::TimeDependentOperator(M_form->ParFESpace()->TrueVSize() * 2), M_form_(std::move(M_form)), S_form_(std::move(S_form)), H_form_(std::move(H_form)), newton_solver_(newton_solver), bcs_(bcs), lin_params_(lin_params), z_(height / 2) { // Assemble the mass matrix and eliminate the fixed DOFs M_mat_.reset(M_form_->ParallelAssemble()); bcs_.eliminateAllEssentialDofsFromMatrix(*M_mat_); M_inv_ = EquationSolver(H_form_->ParFESpace()->GetComm(), lin_params); auto M_prec = std::make_unique<mfem::HypreSmoother>(); M_inv_.linearSolver().iterative_mode = false; M_prec->SetType(mfem::HypreSmoother::Jacobi); M_inv_.SetPreconditioner(std::move(M_prec)); M_inv_.SetOperator(*M_mat_); // Construct the reduced system operator and initialize the newton solver with // it reduced_oper_ = std::make_unique<NonlinearSolidReducedSystemOperator>(*H_form_, *S_form_, *M_form_, bcs); newton_solver_.SetOperator(*reduced_oper_); } void NonlinearSolidDynamicOperator::Mult(const mfem::Vector& vx, mfem::Vector& dvx_dt) const { // Create views to the sub-vectors v, x of vx, and dv_dt, dx_dt of dvx_dt int sc = height / 2; mfem::Vector v(vx.GetData() + 0, sc); mfem::Vector x(vx.GetData() + sc, sc); mfem::Vector dv_dt(dvx_dt.GetData() + 0, sc); mfem::Vector dx_dt(dvx_dt.GetData() + sc, sc); z_ = *H_form_ * x; S_form_->TrueAddMult(v, z_); z_.SetSubVector(bcs_.allEssentialDofs(), 0.0); dv_dt = M_inv_ * -z_; dx_dt = v; } void NonlinearSolidDynamicOperator::ImplicitSolve(const double dt, const mfem::Vector& vx, mfem::Vector& dvx_dt) { int sc = height / 2; mfem::Vector v(vx.GetData() + 0, sc); mfem::Vector x(vx.GetData() + sc, sc); mfem::Vector dv_dt(dvx_dt.GetData() + 0, sc); mfem::Vector dx_dt(dvx_dt.GetData() + sc, sc); // By eliminating kx from the coupled system: // kv = -M^{-1}*[H(x + dt*kx) + S*(v + dt*kv)] // kx = v + dt*kv // we reduce it to a nonlinear equation for kv, represented by the // m_reduced_oper. This equation is solved with the m_newton_solver // object (using m_J_solver and m_J_prec internally). reduced_oper_->SetParameters(dt, &v, &x); mfem::Vector zero; // empty vector is interpreted as zero r.h.s. by NewtonSolver dv_dt = newton_solver_ * zero; SLIC_WARNING_IF(!newton_solver_.nonlinearSolver().GetConverged(), "Newton solver did not converge."); dx_dt = v + (dt * dv_dt); } // destructor NonlinearSolidDynamicOperator::~NonlinearSolidDynamicOperator() {} NonlinearSolidReducedSystemOperator::NonlinearSolidReducedSystemOperator(const mfem::ParNonlinearForm& H_form, const mfem::ParBilinearForm& S_form, mfem::ParBilinearForm& M_form, const BoundaryConditionManager& bcs) : mfem::Operator(M_form.ParFESpace()->TrueVSize()), M_form_(M_form), S_form_(S_form), H_form_(H_form), dt_(0.0), v_(nullptr), x_(nullptr), w_(height), z_(height), bcs_(bcs) { } void NonlinearSolidReducedSystemOperator::SetParameters(double dt, const mfem::Vector* v, const mfem::Vector* x) { dt_ = dt; v_ = v; x_ = x; } void NonlinearSolidReducedSystemOperator::Mult(const mfem::Vector& k, mfem::Vector& y) const { // compute: y = H(x + dt*(v + dt*k)) + M*k + S*(v + dt*k) w_ = *v_ + (dt_ * k); z_ = *x_ + (dt_ * w_); y = H_form_ * z_; M_form_.TrueAddMult(k, y); S_form_.TrueAddMult(w_, y); y.SetSubVector(bcs_.allEssentialDofs(), 0.0); } mfem::Operator& NonlinearSolidReducedSystemOperator::GetGradient(const mfem::Vector& k) const { // Form the gradient of the complete nonlinear operator auto localJ = std::unique_ptr<mfem::SparseMatrix>(Add(1.0, M_form_.SpMat(), dt_, S_form_.SpMat())); w_ = *v_ + (dt_ * k); z_ = *x_ + (dt_ * w_); // No boundary conditions imposed here localJ->Add(dt_ * dt_, H_form_.GetLocalGradient(z_)); jacobian_.reset(M_form_.ParallelAssemble(localJ.get())); // Eliminate the fixed boundary DOFs bcs_.eliminateAllEssentialDofsFromMatrix(*jacobian_); return *jacobian_; } NonlinearSolidReducedSystemOperator::~NonlinearSolidReducedSystemOperator() {} } // namespace serac
38.142857
116
0.637953
joshessman-llnl
b662f049c445959516d9d4dbcce5744975b15c84
2,387
cpp
C++
Source/Editctrl/window.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
2
2022-02-11T11:59:44.000Z
2022-02-16T20:33:25.000Z
Source/Editctrl/window.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
null
null
null
Source/Editctrl/window.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
null
null
null
#include "all.h" #include "ectrl_i.h" void DrawLineColumn(int x, int y); //---------------------------- C_window::C_window(): scroll_x(0), scroll_y(0), overwrite(false), hwnd(NULL), redraw(true) { undo[0].Add(C_undo_element::MARK); } //---------------------------- void C_window::Activate(){ SetFocus(hwnd); } //---------------------------- bool C_window::Save(){ if(doc.unnamed){ //prompt for name char buf[257]; strcpy(buf, doc.title); OPENFILENAME of; memset(&of, 0, sizeof(of)); of.lStructSize = sizeof(of); //of.hwndOwner = hwnd_main; of.hInstance = ec->hi; of.lpstrFile = buf; of.nMaxFile = sizeof(buf)-1; of.lpstrFileTitle = buf; of.nMaxFileTitle = sizeof(buf)-1; of.lpstrInitialDir = NULL; of.Flags = OFN_OVERWRITEPROMPT; if(!GetSaveFileName(&of)) return false; doc.SetTitle(buf); doc.modified = true; doc.unnamed = false; } if(!doc.Write()) return false; //parse undo buffer and change all FILEMODIFY elements to NOP { for(int i=UNDO_BUFFER_ELEMENTS; i--; ){ if(undo[0].elements[i] && undo[0].elements[i]->id==C_undo_element::FILEMODIFY){ undo[0].elements[i]->id = C_undo_element::NOP; } } } SetWindowText(ec->hwnd, doc.title); return true; } //---------------------------- bool C_window::SetScrollPos(int x, int y, int undo_buff){ if(scroll_x!=x || scroll_y!=y){ //add position into undo buffer undo[undo_buff].Add(C_undo_element::SCROLL, scroll_x, scroll_y); scroll_x = x; scroll_y = y; doc.redraw = true; cursor.redraw = true; //setup scroll-bar SCROLLINFO si; si.cbSize = sizeof(si); si.fMask = SIF_RANGE | SIF_POS; si.nMin = 0; si.nMax = doc.linenum; si.nPos = scroll_y; SetScrollInfo(hwnd, SB_VERT, &si, true); return true; } return false; } //---------------------------- /* C_str C_window::ExtractFilename() const{ dword i = doc.title.Size(); while(i && doc.title[i-1]!='\\') --i; if(ec->read_only) return C_fstr("%s [read-only]", (const char*)doc.title + i); return &doc.title[i]; } */ //----------------------------
22.308411
91
0.51571
mice777
b668260f577763c195ed675b033a0508f6143c98
2,095
hpp
C++
ODFAEG/include/odfaeg/Graphics/particleSystemUpdater.hpp
Mechap/ODFAEG
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
[ "Zlib" ]
null
null
null
ODFAEG/include/odfaeg/Graphics/particleSystemUpdater.hpp
Mechap/ODFAEG
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
[ "Zlib" ]
1
2020-02-14T14:19:44.000Z
2020-12-04T17:39:17.000Z
ODFAEG/include/odfaeg/Graphics/particleSystemUpdater.hpp
Mechap/ODFAEG
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
[ "Zlib" ]
2
2021-05-23T13:45:28.000Z
2021-07-24T13:36:13.000Z
#ifndef ODFAEG_PARTICLES_UPDATER_HPP #define ODFAEG_PARTICLES_UPDATER_HPP #include "../Physics/particuleSystem.h" #include "../Graphics/world.h" #include "export.hpp" /** *\namespace odfaeg * the namespace of the Opensource Development Framework Adapted for Every Games. */ namespace odfaeg { namespace graphic { /** * \file entitiesUpdater.h * \class EntitiesUpdater * \brief update all the entities in the world which are in the current view with a thread. * \author Duroisin.L * \version 1.0 * \date 1/02/2014 */ class ODFAEG_CORE_API ParticleSystemUpdater : public core::EntitySystem { public : ParticleSystemUpdater() : EntitySystem() {} /** * \fn void onUpdate () * \brief update all the entities which are in the current view. */ void addParticleSystem(Entity* ps) { particleSystems.push_back(ps); } void removeParticleSystem (Entity* ps) { std::vector<Entity*>::iterator it; for (it = particleSystems.begin(); it != particleSystems.end();) { if (*it == ps) { it = particleSystems.erase(it); } else { it++; } } } std::vector<Entity*> getParticleSystems() { return particleSystems; } void onUpdate () { for (unsigned int i = 0; i < particleSystems.size(); i++) { //std::cout<<"update particle"<<std::endl; particleSystems[i]->update(); if (odfaeg::core::Application::app != nullptr) particleSystems[i]->update(odfaeg::core::Application::app->getClock("LoopTime").getElapsedTime()); } //World::changeVisibleEntity(nullptr, nullptr); } private : std::vector<Entity*> particleSystems; }; } } #endif
35.508475
122
0.521718
Mechap
b6688abaa85db28771b30ef347123aa7d8eef7b2
589
cpp
C++
Chapter07/Source_Code/fifth.cpp
ngdzu/CPP-Reactive-Programming
e1a19feb40be086d47227587b8ed3d509b7518ca
[ "MIT" ]
98
2018-07-03T08:55:31.000Z
2022-03-21T22:16:58.000Z
Chapter07/Source_Code/fifth.cpp
ngdzu/CPP-Reactive-Programming
e1a19feb40be086d47227587b8ed3d509b7518ca
[ "MIT" ]
1
2020-11-30T10:38:58.000Z
2020-12-15T06:56:20.000Z
Chapter07/Source_Code/fifth.cpp
ngdzu/CPP-Reactive-Programming
e1a19feb40be086d47227587b8ed3d509b7518ca
[ "MIT" ]
54
2018-07-06T02:09:27.000Z
2021-11-10T08:42:50.000Z
#include "rxcpp/rx.hpp" #include "rxcpp/rx-test.hpp" #include <iostream> #include <array> int main() { auto values = rxcpp::observable<>::range(1); // infinite (until overflow) stream of integers auto s1 = values. take(3). map([](int prime) { return std::make_tuple("1:", prime);}); auto s2 = values. take(3). map([](int prime) { return std::make_tuple("2:", prime);}); s1. concat(s2). subscribe(rxcpp::util::apply_to( [](const char* s, int p) { printf("%s %d\n", s, p); })); }
19.633333
93
0.521222
ngdzu
b66c3580439d08af4319f8072336ef728b6ec2b6
7,276
cpp
C++
gme/src/v20180711/model/CreateAppRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
gme/src/v20180711/model/CreateAppRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
gme/src/v20180711/model/CreateAppRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/gme/v20180711/model/CreateAppRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Gme::V20180711::Model; using namespace std; CreateAppRequest::CreateAppRequest() : m_appNameHasBeenSet(false), m_projectIdHasBeenSet(false), m_engineListHasBeenSet(false), m_regionListHasBeenSet(false), m_realtimeSpeechConfHasBeenSet(false), m_voiceMessageConfHasBeenSet(false), m_voiceFilterConfHasBeenSet(false), m_tagsHasBeenSet(false) { } string CreateAppRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_appNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AppName"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_appName.c_str(), allocator).Move(), allocator); } if (m_projectIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ProjectId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_projectId, allocator); } if (m_engineListHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "EngineList"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_engineList.begin(); itr != m_engineList.end(); ++itr) { d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } if (m_regionListHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RegionList"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_regionList.begin(); itr != m_regionList.end(); ++itr) { d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } if (m_realtimeSpeechConfHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RealtimeSpeechConf"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_realtimeSpeechConf.ToJsonObject(d[key.c_str()], allocator); } if (m_voiceMessageConfHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "VoiceMessageConf"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_voiceMessageConf.ToJsonObject(d[key.c_str()], allocator); } if (m_voiceFilterConfHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "VoiceFilterConf"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_voiceFilterConf.ToJsonObject(d[key.c_str()], allocator); } if (m_tagsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Tags"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_tags.begin(); itr != m_tags.end(); ++itr, ++i) { d[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(d[key.c_str()][i], allocator); } } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string CreateAppRequest::GetAppName() const { return m_appName; } void CreateAppRequest::SetAppName(const string& _appName) { m_appName = _appName; m_appNameHasBeenSet = true; } bool CreateAppRequest::AppNameHasBeenSet() const { return m_appNameHasBeenSet; } uint64_t CreateAppRequest::GetProjectId() const { return m_projectId; } void CreateAppRequest::SetProjectId(const uint64_t& _projectId) { m_projectId = _projectId; m_projectIdHasBeenSet = true; } bool CreateAppRequest::ProjectIdHasBeenSet() const { return m_projectIdHasBeenSet; } vector<string> CreateAppRequest::GetEngineList() const { return m_engineList; } void CreateAppRequest::SetEngineList(const vector<string>& _engineList) { m_engineList = _engineList; m_engineListHasBeenSet = true; } bool CreateAppRequest::EngineListHasBeenSet() const { return m_engineListHasBeenSet; } vector<string> CreateAppRequest::GetRegionList() const { return m_regionList; } void CreateAppRequest::SetRegionList(const vector<string>& _regionList) { m_regionList = _regionList; m_regionListHasBeenSet = true; } bool CreateAppRequest::RegionListHasBeenSet() const { return m_regionListHasBeenSet; } RealtimeSpeechConf CreateAppRequest::GetRealtimeSpeechConf() const { return m_realtimeSpeechConf; } void CreateAppRequest::SetRealtimeSpeechConf(const RealtimeSpeechConf& _realtimeSpeechConf) { m_realtimeSpeechConf = _realtimeSpeechConf; m_realtimeSpeechConfHasBeenSet = true; } bool CreateAppRequest::RealtimeSpeechConfHasBeenSet() const { return m_realtimeSpeechConfHasBeenSet; } VoiceMessageConf CreateAppRequest::GetVoiceMessageConf() const { return m_voiceMessageConf; } void CreateAppRequest::SetVoiceMessageConf(const VoiceMessageConf& _voiceMessageConf) { m_voiceMessageConf = _voiceMessageConf; m_voiceMessageConfHasBeenSet = true; } bool CreateAppRequest::VoiceMessageConfHasBeenSet() const { return m_voiceMessageConfHasBeenSet; } VoiceFilterConf CreateAppRequest::GetVoiceFilterConf() const { return m_voiceFilterConf; } void CreateAppRequest::SetVoiceFilterConf(const VoiceFilterConf& _voiceFilterConf) { m_voiceFilterConf = _voiceFilterConf; m_voiceFilterConfHasBeenSet = true; } bool CreateAppRequest::VoiceFilterConfHasBeenSet() const { return m_voiceFilterConfHasBeenSet; } vector<Tag> CreateAppRequest::GetTags() const { return m_tags; } void CreateAppRequest::SetTags(const vector<Tag>& _tags) { m_tags = _tags; m_tagsHasBeenSet = true; } bool CreateAppRequest::TagsHasBeenSet() const { return m_tagsHasBeenSet; }
27.456604
104
0.708356
suluner
b66fd0f8780dc04af689585987afb0d94d5036cc
421
cpp
C++
docker/cytnx/src/utils/is.cpp
j9263178/Cytnx
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
[ "Apache-2.0" ]
11
2020-04-14T15:45:42.000Z
2022-03-31T14:37:03.000Z
docker/cytnx/src/utils/is.cpp
j9263178/Cytnx
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
[ "Apache-2.0" ]
38
2019-08-02T15:15:51.000Z
2022-03-04T19:07:02.000Z
docker/cytnx/src/utils/is.cpp
j9263178/Cytnx
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
[ "Apache-2.0" ]
7
2019-07-17T07:50:55.000Z
2021-07-03T06:44:52.000Z
#include "utils/is.hpp" namespace cytnx{ bool is(const Tensor &L, const Tensor &R){ return (L._impl == R._impl); } bool is(const Storage &L, const Storage &R){ return (L._impl == R._impl); } bool is(const Bond &L, const Bond &R){ return (L._impl == R._impl); } bool is(const Symmetry &L, const Symmetry &R){ return (L._impl == R._impl); } }
17.541667
50
0.534442
j9263178
b6743871ee08c8b53fa206d97ec911fbcce81f84
307
cpp
C++
kmerInput/Statistic.cpp
Lw-Cui/kmer-exp
cc9df6339c6a07d63483e6a6dd8f2c13e9865b0e
[ "MIT" ]
null
null
null
kmerInput/Statistic.cpp
Lw-Cui/kmer-exp
cc9df6339c6a07d63483e6a6dd8f2c13e9865b0e
[ "MIT" ]
null
null
null
kmerInput/Statistic.cpp
Lw-Cui/kmer-exp
cc9df6339c6a07d63483e6a6dd8f2c13e9865b0e
[ "MIT" ]
null
null
null
#include <cstring> #include <map> #include <cstdio> using namespace std; int main() { map<int, int> count; int num; while (scanf("%*s%d", &num) != EOF) count[num]++; for (map<int, int>::iterator p = count.begin(); p != count.end(); p++) printf("%5d: %10d\n", p->first, p->second); return 0; }
18.058824
48
0.586319
Lw-Cui
b67541f04f69aeaa74a34629e928bf51df5a3ca3
273
hpp
C++
include/cpu/cpu.hpp
anthony-benavente/chip8emu
5ffe96ac252d15bfe0242fc6e1a550844510b31b
[ "MIT" ]
null
null
null
include/cpu/cpu.hpp
anthony-benavente/chip8emu
5ffe96ac252d15bfe0242fc6e1a550844510b31b
[ "MIT" ]
null
null
null
include/cpu/cpu.hpp
anthony-benavente/chip8emu
5ffe96ac252d15bfe0242fc6e1a550844510b31b
[ "MIT" ]
null
null
null
#ifndef CPU_H #define CPU_H #include "program/program.hpp" class Cpu { public: bool drawFlag; Cpu() : drawFlag(false) {} virtual void emulateCycle() = 0; virtual unsigned char getPixel(int x, int y) = 0; virtual void loadProgram(program_t *program) = 0; }; #endif
16.058824
50
0.703297
anthony-benavente
b679acd2c820753b72efd9f2494a17c0b9797a10
250
cpp
C++
Game/Client/WXClient/Network/PacketHandler/CGAskActiveTimeUpdateHandler.cpp
hackerlank/SourceCode
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
[ "MIT" ]
4
2021-07-31T13:56:01.000Z
2021-11-13T02:55:10.000Z
Game/Client/WXClient/Network/PacketHandler/CGAskActiveTimeUpdateHandler.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
null
null
null
Game/Client/WXClient/Network/PacketHandler/CGAskActiveTimeUpdateHandler.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
7
2021-08-31T14:34:23.000Z
2022-01-19T08:25:58.000Z
#include "StdAfx.h" #include "CGAskActiveTimeUpdate.h" uint CGAskActiveTimeUpdateHandler::Execute( CGAskActiveTimeUpdate* pPacket, Player* pPlayer ) { __ENTER_FUNCTION return PACKET_EXE_CONTINUE ; __LEAVE_FUNCTION return PACKET_EXE_ERROR ; }
17.857143
93
0.808
hackerlank
b67a171f12c52a9659fcb57e4c506286c0195d73
1,337
cpp
C++
Source/KPokemon_DX11/KSpriteEffect.cpp
jiwonchoidd/PokemonDP_DX11
828ef195c7c66b4c5489944e930acee96940c816
[ "BSD-2-Clause" ]
1
2022-03-25T08:55:53.000Z
2022-03-25T08:55:53.000Z
Source/KPokemon_DX11/KSpriteEffect.cpp
jiwonchoidd/PokemonDP_DX11
828ef195c7c66b4c5489944e930acee96940c816
[ "BSD-2-Clause" ]
null
null
null
Source/KPokemon_DX11/KSpriteEffect.cpp
jiwonchoidd/PokemonDP_DX11
828ef195c7c66b4c5489944e930acee96940c816
[ "BSD-2-Clause" ]
null
null
null
#include "KSpriteEffect.h" bool KSpriteEffect::Init(ID3D11DeviceContext* context, std::wstring vs, std::wstring ps, std::wstring tex, std::wstring mask) { m_pContext = context; m_Current_Index=0; m_Timer=0.0f; m_bEnd = false; m_Color = { 1,1,1,1 }; m_cbData.vLightDir = m_Color; K2DAsset::CreateObject_Mask(vs,ps,tex,mask); return true; } bool KSpriteEffect::Frame() { if (m_bEnd) { Reset(); return false; } else { m_Change_Time = m_pSprite->m_anim_time / m_pSprite->m_anim_array.size(); m_Timer += g_fSecPerFrame; if (m_Timer >= m_Change_Time) { m_Current_Index++; if (m_Current_Index >= m_pSprite->m_anim_array.size()) { m_Current_Index = 0; } m_Timer -= m_Change_Time; SetRectSource(m_pSprite->m_anim_array[m_Current_Index]); /*SetRectDraw({ 0,0, m_pSprite->m_anim_array[m_Current_Index].right, m_pSprite->m_anim_array[m_Current_Index].bottom });*/ AddPosition(KVector2(0, 0)); if (m_Current_Index == m_pSprite->m_anim_array.size()-1) { m_bEnd = true; } } m_cbData.vLightDir= m_Color; } return true; } bool KSpriteEffect::Render(ID3D11DeviceContext* pContext) { KObject::Render(pContext); return true; } bool KSpriteEffect::Release() { KObject::Release(); return true; } void KSpriteEffect::Reset() { m_Current_Index = 0; m_Timer = 0.0f; }
19.955224
125
0.694091
jiwonchoidd
b67d83c5ba68070fd07f4d78be656de6227e3c02
1,291
cpp
C++
src/main/cpp/lemon/test/runner.cpp
lemonkit/lemon
ad34410586659fc650898b60d7e168797a3d9e5b
[ "MIT" ]
1
2018-01-12T05:13:58.000Z
2018-01-12T05:13:58.000Z
src/main/cpp/lemon/test/runner.cpp
lemonkit/lemon
ad34410586659fc650898b60d7e168797a3d9e5b
[ "MIT" ]
null
null
null
src/main/cpp/lemon/test/runner.cpp
lemonkit/lemon
ad34410586659fc650898b60d7e168797a3d9e5b
[ "MIT" ]
null
null
null
#include <iostream> #include <lemon/log/log.hpp> #include <lemon/test/unit.hpp> #include <lemon/test/macro.hpp> #include <lemon/test/runner.hpp> namespace lemon {namespace test{ runner& runner::instance() { static runner global; return global; } void runner::run() { runner::instance().done(); } void runner::done() { auto & logger = log::get("test"); for(auto unit : _units) { try { unit->run(); lemonI(logger,"test(%s) ... ok",unit->name().c_str()); } catch(const assert & e) { lemonE(logger,"test(%s) -- failed\n\terr :%s\n\tfile :%s(%d)",unit->name().c_str(),e.what(),e.file().c_str(),e.lines()); } catch(const std::exception &e) { lemonE(logger,"test(%s) -- failed\n\terr :%s\n\tfile :%s(%d)",unit->name().c_str(),e.what(),unit->file().c_str(),unit->lines()); } catch(...) { lemonE(logger, "test(%s) -- failed\n\terr :unknown exception\n\tfile :%s(%d)", unit->name().c_str(), unit->file().c_str(), unit->lines()); } } } void runner::add(runnable *unit) { _units.push_back(unit); } }}
23.053571
144
0.490318
lemonkit
b67ea9453867e82b38a780ba2df51899ae01d5ea
10,108
hpp
C++
include/GlobalNamespace/BeatmapDataSO_-GetBeatmapDataAsync-d__2.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/BeatmapDataSO_-GetBeatmapDataAsync-d__2.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/BeatmapDataSO_-GetBeatmapDataAsync-d__2.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: BeatmapDataSO #include "GlobalNamespace/BeatmapDataSO.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: System.Runtime.CompilerServices.IAsyncStateMachine #include "System/Runtime/CompilerServices/IAsyncStateMachine.hpp" // Including type: System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1 #include "System/Runtime/CompilerServices/AsyncTaskMethodBuilder_1.hpp" // Including type: BeatmapDifficulty #include "GlobalNamespace/BeatmapDifficulty.hpp" // Including type: System.Runtime.CompilerServices.TaskAwaiter`1 #include "System/Runtime/CompilerServices/TaskAwaiter_1.hpp" // Including type: System.Runtime.CompilerServices.TaskAwaiter #include "System/Runtime/CompilerServices/TaskAwaiter.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: IReadonlyBeatmapData class IReadonlyBeatmapData; // Forward declaring type: EnvironmentInfoSO class EnvironmentInfoSO; // Forward declaring type: PlayerSpecificSettings class PlayerSpecificSettings; } // Forward declaring namespace: BeatmapSaveDataVersion3 namespace BeatmapSaveDataVersion3 { // Forward declaring type: BeatmapSaveData class BeatmapSaveData; } // Completed forward declares #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2, "", "BeatmapDataSO/<GetBeatmapDataAsync>d__2"); // Type namespace: namespace GlobalNamespace { // WARNING Size may be invalid! // Autogenerated type: BeatmapDataSO/<GetBeatmapDataAsync>d__2 // [TokenAttribute] Offset: FFFFFFFF // [CompilerGeneratedAttribute] Offset: FFFFFFFF struct BeatmapDataSO::$GetBeatmapDataAsync$d__2/*, public ::System::ValueType, public ::System::Runtime::CompilerServices::IAsyncStateMachine*/ { public: public: // public System.Int32 <>1__state // Size: 0x4 // Offset: 0x0 int $$1__state; // Field size check static_assert(sizeof(int) == 0x4); // public System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1<IReadonlyBeatmapData> <>t__builder // Size: 0xFFFFFFFF // Offset: 0x8 ::System::Runtime::CompilerServices::AsyncTaskMethodBuilder_1<::GlobalNamespace::IReadonlyBeatmapData*> $$t__builder; // public BeatmapDifficulty beatmapDifficulty // Size: 0x4 // Offset: 0x20 ::GlobalNamespace::BeatmapDifficulty beatmapDifficulty; // Field size check static_assert(sizeof(::GlobalNamespace::BeatmapDifficulty) == 0x4); // public System.Single beatsPerMinute // Size: 0x4 // Offset: 0x24 float beatsPerMinute; // Field size check static_assert(sizeof(float) == 0x4); // public System.Boolean loadingForDesignatedEnvironment // Size: 0x1 // Offset: 0x28 bool loadingForDesignatedEnvironment; // Field size check static_assert(sizeof(bool) == 0x1); // public EnvironmentInfoSO environmentInfo // Size: 0x8 // Offset: 0x30 ::GlobalNamespace::EnvironmentInfoSO* environmentInfo; // Field size check static_assert(sizeof(::GlobalNamespace::EnvironmentInfoSO*) == 0x8); // public PlayerSpecificSettings playerSpecificSettings // Size: 0x8 // Offset: 0x38 ::GlobalNamespace::PlayerSpecificSettings* playerSpecificSettings; // Field size check static_assert(sizeof(::GlobalNamespace::PlayerSpecificSettings*) == 0x8); // public BeatmapDataSO <>4__this // Size: 0x8 // Offset: 0x40 ::GlobalNamespace::BeatmapDataSO* $$4__this; // Field size check static_assert(sizeof(::GlobalNamespace::BeatmapDataSO*) == 0x8); // private BeatmapDataSO/<>c__DisplayClass2_0 <>8__1 // Size: 0x8 // Offset: 0x48 ::GlobalNamespace::BeatmapDataSO::$$c__DisplayClass2_0* $$8__1; // Field size check static_assert(sizeof(::GlobalNamespace::BeatmapDataSO::$$c__DisplayClass2_0*) == 0x8); // private System.Runtime.CompilerServices.TaskAwaiter`1<BeatmapSaveDataVersion3.BeatmapSaveData> <>u__1 // Size: 0xFFFFFFFF // Offset: 0x50 ::System::Runtime::CompilerServices::TaskAwaiter_1<::BeatmapSaveDataVersion3::BeatmapSaveData*> $$u__1; // private System.Runtime.CompilerServices.TaskAwaiter <>u__2 // Size: 0x8 // Offset: 0x58 ::System::Runtime::CompilerServices::TaskAwaiter $$u__2; // Field size check static_assert(sizeof(::System::Runtime::CompilerServices::TaskAwaiter) == 0x8); public: // Creating value type constructor for type: $GetBeatmapDataAsync$d__2 constexpr $GetBeatmapDataAsync$d__2(int $$1__state_ = {}, ::System::Runtime::CompilerServices::AsyncTaskMethodBuilder_1<::GlobalNamespace::IReadonlyBeatmapData*> $$t__builder_ = {}, ::GlobalNamespace::BeatmapDifficulty beatmapDifficulty_ = {}, float beatsPerMinute_ = {}, bool loadingForDesignatedEnvironment_ = {}, ::GlobalNamespace::EnvironmentInfoSO* environmentInfo_ = {}, ::GlobalNamespace::PlayerSpecificSettings* playerSpecificSettings_ = {}, ::GlobalNamespace::BeatmapDataSO* $$4__this_ = {}, ::GlobalNamespace::BeatmapDataSO::$$c__DisplayClass2_0* $$8__1_ = {}, ::System::Runtime::CompilerServices::TaskAwaiter_1<::BeatmapSaveDataVersion3::BeatmapSaveData*> $$u__1_ = {}, ::System::Runtime::CompilerServices::TaskAwaiter $$u__2_ = {}) noexcept : $$1__state{$$1__state_}, $$t__builder{$$t__builder_}, beatmapDifficulty{beatmapDifficulty_}, beatsPerMinute{beatsPerMinute_}, loadingForDesignatedEnvironment{loadingForDesignatedEnvironment_}, environmentInfo{environmentInfo_}, playerSpecificSettings{playerSpecificSettings_}, $$4__this{$$4__this_}, $$8__1{$$8__1_}, $$u__1{$$u__1_}, $$u__2{$$u__2_} {} // Creating interface conversion operator: operator ::System::ValueType operator ::System::ValueType() noexcept { return *reinterpret_cast<::System::ValueType*>(this); } // Creating interface conversion operator: operator ::System::Runtime::CompilerServices::IAsyncStateMachine operator ::System::Runtime::CompilerServices::IAsyncStateMachine() noexcept { return *reinterpret_cast<::System::Runtime::CompilerServices::IAsyncStateMachine*>(this); } // Get instance field reference: public System.Int32 <>1__state int& dyn_$$1__state(); // Get instance field reference: public System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1<IReadonlyBeatmapData> <>t__builder ::System::Runtime::CompilerServices::AsyncTaskMethodBuilder_1<::GlobalNamespace::IReadonlyBeatmapData*>& dyn_$$t__builder(); // Get instance field reference: public BeatmapDifficulty beatmapDifficulty ::GlobalNamespace::BeatmapDifficulty& dyn_beatmapDifficulty(); // Get instance field reference: public System.Single beatsPerMinute float& dyn_beatsPerMinute(); // Get instance field reference: public System.Boolean loadingForDesignatedEnvironment bool& dyn_loadingForDesignatedEnvironment(); // Get instance field reference: public EnvironmentInfoSO environmentInfo ::GlobalNamespace::EnvironmentInfoSO*& dyn_environmentInfo(); // Get instance field reference: public PlayerSpecificSettings playerSpecificSettings ::GlobalNamespace::PlayerSpecificSettings*& dyn_playerSpecificSettings(); // Get instance field reference: public BeatmapDataSO <>4__this ::GlobalNamespace::BeatmapDataSO*& dyn_$$4__this(); // Get instance field reference: private BeatmapDataSO/<>c__DisplayClass2_0 <>8__1 ::GlobalNamespace::BeatmapDataSO::$$c__DisplayClass2_0*& dyn_$$8__1(); // Get instance field reference: private System.Runtime.CompilerServices.TaskAwaiter`1<BeatmapSaveDataVersion3.BeatmapSaveData> <>u__1 ::System::Runtime::CompilerServices::TaskAwaiter_1<::BeatmapSaveDataVersion3::BeatmapSaveData*>& dyn_$$u__1(); // Get instance field reference: private System.Runtime.CompilerServices.TaskAwaiter <>u__2 ::System::Runtime::CompilerServices::TaskAwaiter& dyn_$$u__2(); // private System.Void MoveNext() // Offset: 0x136D500 void MoveNext(); // private System.Void SetStateMachine(System.Runtime.CompilerServices.IAsyncStateMachine stateMachine) // Offset: 0x136D868 void SetStateMachine(::System::Runtime::CompilerServices::IAsyncStateMachine* stateMachine); }; // BeatmapDataSO/<GetBeatmapDataAsync>d__2 // WARNING Not writing size check since size may be invalid! } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2::MoveNext // Il2CppName: MoveNext template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2::*)()>(&GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2::MoveNext)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2), "MoveNext", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2::SetStateMachine // Il2CppName: SetStateMachine template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2::*)(::System::Runtime::CompilerServices::IAsyncStateMachine*)>(&GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2::SetStateMachine)> { static const MethodInfo* get() { static auto* stateMachine = &::il2cpp_utils::GetClassFromName("System.Runtime.CompilerServices", "IAsyncStateMachine")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2), "SetStateMachine", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{stateMachine}); } };
58.767442
1,111
0.757618
RedBrumbler
b68060e67087fb74d7b0d88cd62ff5cce855465a
1,237
hpp
C++
src/graphics/TypeNames.hpp
Sam-Belliveau/MKS66-Graphics-Library
4ccf04f977a15007e32bdb5a238704eaaff0c895
[ "MIT" ]
null
null
null
src/graphics/TypeNames.hpp
Sam-Belliveau/MKS66-Graphics-Library
4ccf04f977a15007e32bdb5a238704eaaff0c895
[ "MIT" ]
null
null
null
src/graphics/TypeNames.hpp
Sam-Belliveau/MKS66-Graphics-Library
4ccf04f977a15007e32bdb5a238704eaaff0c895
[ "MIT" ]
null
null
null
#pragma once /** * Copyright (c) 2022 Sam Belliveau * * 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. */ #include <cstdint> namespace SPGL { /* Floats */ using Float80 = long double; using Float64 = double; using Float32 = float; using Float = Float64; using FloatMax = Float80; /* Integers */ using Size = std::size_t; using UIntMax = std::uintmax_t; using IntMax = std::intmax_t; using UInt64 = std::uint64_t; using Int64 = std::int64_t; using UInt32 = std::uint32_t; using Int32 = std::int32_t; using UInt16 = std::uint16_t; using Int16 = std::int16_t; using UInt8 = std::uint8_t; using Int8 = std::int8_t; }
26.891304
81
0.689572
Sam-Belliveau
b683049cc1444a2f3f1fc814d6788c56abee532f
32,602
cpp
C++
src/shape.cpp
yenyi/kicadPcb
f624156f59829554cb9fbf9b0438e7b84a42ee94
[ "BSD-3-Clause" ]
6
2020-02-08T07:29:42.000Z
2020-11-25T03:09:13.000Z
src/shape.cpp
yenyi/kicadPcb
f624156f59829554cb9fbf9b0438e7b84a42ee94
[ "BSD-3-Clause" ]
2
2019-12-23T17:19:41.000Z
2020-01-09T00:10:50.000Z
src/shape.cpp
yenyi/kicadPcb
f624156f59829554cb9fbf9b0438e7b84a42ee94
[ "BSD-3-Clause" ]
5
2020-10-16T23:59:42.000Z
2021-04-28T05:49:22.000Z
#include "shape.h" points_2d rotateShapeCoordsByAngles(const points_2d &shape, double instAngle, double padAngle) { auto cords = points_2d{}; auto rads = fmod((instAngle + padAngle) * -M_PI / 180, 2 * M_PI); auto s = sin(rads); auto c = cos(rads); for (auto &p : shape) { auto px = double(c * p.m_x - s * p.m_y); auto py = double(s * p.m_x + c * p.m_y); cords.push_back(point_2d{px, py}); } return cords; } points_2d roundrect_to_shape_coords(const point_2d &size, const double &ratio) { double legalRatio = 0.5; if (ratio < 0.5) { legalRatio = ratio; } auto cords = points_2d{}; auto width = size.m_x / 2; auto height = size.m_y / 2; auto radius = std::min(width, height) * legalRatio * 2; auto deltaWidth = width - radius; auto deltaHeight = height - radius; auto point = point_2d{}; for (int i = 0; i < 10; ++i) { //10 points point.m_x = deltaWidth + radius * cos(-9 * i * M_PI / 180); point.m_y = -deltaHeight + radius * sin(-9 * i * M_PI / 180); //std::cout << point.m_x << " " << point.m_y << std::endl; cords.push_back(point); } for (int i = 10; i < 20; ++i) { //10 points point.m_x = -deltaWidth + radius * cos(-9 * i * M_PI / 180); point.m_y = -deltaHeight + radius * sin(-9 * i * M_PI / 180); //std::cout << point.m_x << " " << point.m_y << std::endl; cords.push_back(point); } for (int i = 20; i < 30; ++i) { //10 points point.m_x = -deltaWidth + radius * cos(-9 * i * M_PI / 180); point.m_y = deltaHeight + radius * sin(-9 * i * M_PI / 180); //std::cout << point.m_x << " " << point.m_y << std::endl; cords.push_back(point); } for (int i = 30; i < 40; ++i) { //10 points point.m_x = deltaWidth + radius * cos(-9 * i * M_PI / 180); point.m_y = deltaHeight + radius * sin(-9 * i * M_PI / 180); //std::cout << point.m_x << " " << point.m_y << std::endl; cords.push_back(point); } point.m_x = deltaWidth + radius * cos(0 * M_PI / 180); point.m_y = -deltaHeight + radius * sin(0 * M_PI / 180); //std::cout << point.m_x << " " << point.m_y << std::endl; cords.push_back(point); return cords; } // Ongoing work // TODO: all coords must be in CW (follow the rules of Boost Polygon of Rings) // TODO: parameters for #points to Circle points_2d shape_to_coords(const point_2d &size, const point_2d &pos, const padShape shape, const double a1, const double a2, const double ratio, const int pointsPerCircle) { auto coords = points_2d{}; switch (shape) { case padShape::CIRCLE: { auto radius = size.m_x / 2; auto point = point_2d{}; double angleShift = 360.0 / (double)pointsPerCircle; for (int i = 0; i < pointsPerCircle; ++i) { point.m_x = pos.m_x + radius * cos(-angleShift * i * M_PI / 180); point.m_y = pos.m_y + radius * sin(-angleShift * i * M_PI / 180); coords.push_back(point); } // Closed the loop point.m_x = pos.m_x + radius * cos(0 * M_PI / 180); point.m_y = pos.m_y + radius * sin(0 * M_PI / 180); coords.push_back(point); break; } // case padShape::OVAL: // { // auto width = size.m_x / 2; // auto height = size.m_y / 2; // auto point = point_2d{}; // double angleShift = 360.0 / (double)pointsPerCircle; // for (int i = 0; i < pointsPerCircle; ++i) // { // point.m_x = pos.m_x + width * cos(-angleShift * i * M_PI / 180); // point.m_y = pos.m_y + height * sin(-angleShift * i * M_PI / 180); // coords.push_back(point); // } // // Closed the loop // point.m_x = pos.m_x + width * cos(0 * M_PI / 180); // point.m_y = pos.m_y + height * sin(0 * M_PI / 180); // coords.push_back(point); // break; // } case padShape::OVAL: case padShape::ROUNDRECT: { double legalRatio = 0.5; if (ratio < 0.5) { legalRatio = ratio; } if (shape == padShape::OVAL) { // OVAL is the roundrect with ratio = 0.5 legalRatio = 0.5; } auto width = size.m_x / 2; auto height = size.m_y / 2; auto radius = std::min(width, height) * legalRatio * 2; auto deltaWidth = width - radius; auto deltaHeight = height - radius; auto point = point_2d{}; int pointsPerCorner = pointsPerCircle / 4; double angleShift = 360.0 / (double)(pointsPerCorner * 4); for (int i = 0; i < pointsPerCorner; ++i) { point.m_x = pos.m_x + deltaWidth + radius * cos(-angleShift * i * M_PI / 180); point.m_y = pos.m_y - deltaHeight + radius * sin(-angleShift * i * M_PI / 180); coords.push_back(point); } for (int i = pointsPerCorner; i < 2 * pointsPerCorner; ++i) { point.m_x = pos.m_x - deltaWidth + radius * cos(-angleShift * i * M_PI / 180); point.m_y = pos.m_y - deltaHeight + radius * sin(-angleShift * i * M_PI / 180); coords.push_back(point); } for (int i = 2 * pointsPerCorner; i < 3 * pointsPerCorner; ++i) { point.m_x = pos.m_x - deltaWidth + radius * cos(-angleShift * i * M_PI / 180); point.m_y = pos.m_y + deltaHeight + radius * sin(-angleShift * i * M_PI / 180); coords.push_back(point); } for (int i = 3 * pointsPerCorner; i < 4 * pointsPerCorner; ++i) { point.m_x = pos.m_x + deltaWidth + radius * cos(-angleShift * i * M_PI / 180); point.m_y = pos.m_y + deltaHeight + radius * sin(-angleShift * i * M_PI / 180); coords.push_back(point); } // Closed the loop point.m_x = pos.m_x + deltaWidth + radius * cos(0 * M_PI / 180); point.m_y = pos.m_y - deltaHeight + radius * sin(0 * M_PI / 180); coords.push_back(point); break; } default: case padShape::TRAPEZOID: case padShape::RECT: { auto width = size.m_x / 2; auto height = size.m_y / 2; auto point = point_2d{}; point.m_x = pos.m_x + width; point.m_y = pos.m_y + height; coords.push_back(point); point.m_y = pos.m_y - height; coords.push_back(point); point.m_x = pos.m_x - width; coords.push_back(point); point.m_y = pos.m_y + height; coords.push_back(point); // Closed the loop point.m_x = pos.m_x + width; point.m_y = pos.m_y + height; coords.push_back(point); break; } } return rotateShapeCoordsByAngles(coords, a1, a2); } void printPolygon(const points_2d &coord) { std::cout << "Polygon("; for (size_t i = 0; i < coord.size(); ++i) { std::cout << coord[i]; if (i < coord.size() - 1) std::cout << ", "; } std::cout << ")" << std::endl; } void printPolygon(const polygon_t &poly) { std::cout << "Polygon("; for (auto it = boost::begin(bg::exterior_ring(poly)); it != boost::end(bg::exterior_ring(poly)); ++it) { auto x = bg::get<0>(*it); auto y = bg::get<1>(*it); //use the coordinates... std::cout << "(" << x << ", " << y << ")"; if (++it == boost::end(bg::exterior_ring(poly))) { break; } else { std::cout << ", "; } --it; } std::cout << ")" << std::endl; } void printPoint(point_2d &p) { std::cout << "Point({" << p.m_x << "," << p.m_y << "})" << std::endl; } void testShapeToCoords() { // points_2d circle32 = shape_to_coords(point_2d{10, 10}, point_2d{20, 20}, padShape::CIRCLE, 0, 0, 0, 32); // printPolygon(circle32); // points_2d circle48 = shape_to_coords(point_2d{10, 10}, point_2d{20, 20}, padShape::CIRCLE, 0, 0, 0, 48); // printPolygon(circle48); // points_2d oval32 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::OVAL, 0, 0, 0, 32); // printPolygon(oval32); // points_2d oval48 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::OVAL, 0, 0, 0, 48); // printPolygon(oval48); points_2d rr32 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.5, 32); printPolygon(rr32); points_2d rr48 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.5, 48); printPolygon(rr48); points_2d rr3208 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.8, 32); printPolygon(rr3208); points_2d rr4803 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.3, 48); printPolygon(rr4803); points_2d rr4003 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.3, 40); printPolygon(rr4003); points_2d rr4005 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.5, 40); printPolygon(rr4005); points_2d rr4008 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.8, 40); printPolygon(rr4008); // points_2d rrr4008 = roundrect_to_shape_coords(point_2d{16, 10}, 0.8); // printPolygon(rrr4008); // points_2d rrr4005 = roundrect_to_shape_coords(point_2d{16, 10}, 0.5); // printPolygon(rrr4005); // points_2d rrr4003 = roundrect_to_shape_coords(point_2d{16, 10}, 0.3); // printPolygon(rrr4003); // points_2d rect = shape_to_coords(point_2d{10, 10}, point_2d{10, 5}, padShape::RECT, 0, 0, 0, 48); // printPolygon(rect); // points_2d trapezoid = shape_to_coords(point_2d{15, 15}, point_2d{-5, -10}, padShape::TRAPEZOID, 0, 0, 0, 48); // printPolygon(trapezoid); } ///////////////////////////////// // [1] [0] // |--------| // | s | // | | // |________| // [2] [3] ///////////////////////////////// points_2d segment_to_rect(const points_2d &point, const double &w) { auto cords = points_2d{}; auto p = point_2d{}; auto width = w / 2; //vertical if (point[0].m_x == point[1].m_x) { if (point[0].m_y > point[1].m_y) { p.m_x = point[0].m_x + width; p.m_y = point[0].m_y + width; cords.push_back(p); p.m_x = point[0].m_x - width; cords.push_back(p); p.m_x = point[0].m_x - width; p.m_y = point[0].m_y - width; cords.push_back(p); p.m_x = point[0].m_x - width; cords.push_back(p); } else { p.m_x = point[0].m_x + width; p.m_y = point[1].m_y + width; cords.push_back(p); p.m_x = point[0].m_x - width; cords.push_back(p); p.m_x = point[0].m_x - width; p.m_y = point[0].m_y - width; cords.push_back(p); p.m_x = point[0].m_x + width; cords.push_back(p); } } //horizontal else if (point[0].m_y == point[1].m_y) { if (point[0].m_x > point[1].m_x) { p.m_x = point[0].m_x + width; p.m_y = point[0].m_y + width; cords.push_back(p); p.m_x = point[1].m_x - width; cords.push_back(p); p.m_y = point[0].m_y - width; cords.push_back(p); p.m_x = point[0].m_x + width; cords.push_back(p); } else { p.m_x = point[1].m_x + width; p.m_y = point[0].m_y + width; cords.push_back(p); p.m_x = point[0].m_x - width; cords.push_back(p); p.m_y = point[0].m_y - width; cords.push_back(p); p.m_x = point[1].m_x + width; cords.push_back(p); } } //45degree else if ((point[0].m_x > point[1].m_x) && (point[0].m_y > point[1].m_y)) { p.m_x = point[0].m_x + sqrt(2) * width; p.m_y = point[0].m_y; cords.push_back(p); p.m_x = point[0].m_x; p.m_y = point[0].m_y + sqrt(2) * width; cords.push_back(p); p.m_x = point[1].m_x - sqrt(2) * width; p.m_y = point[1].m_y; cords.push_back(p); p.m_x = point[1].m_x; p.m_y = point[1].m_y + sqrt(2) * width; cords.push_back(p); } else if ((point[0].m_x < point[1].m_x) && (point[0].m_y < point[1].m_y)) { p.m_x = point[1].m_x + sqrt(2) * width; p.m_y = point[1].m_y; cords.push_back(p); p.m_x = point[1].m_x; p.m_y = point[1].m_y + sqrt(2) * width; cords.push_back(p); p.m_x = point[0].m_x - sqrt(2) * width; p.m_y = point[0].m_y; cords.push_back(p); p.m_x = point[0].m_x; p.m_y = point[0].m_y + sqrt(2) * width; cords.push_back(p); } //135degree else if ((point[1].m_x < point[0].m_x) && (point[1].m_y > point[0].m_y)) { p.m_x = point[1].m_x; p.m_y = point[1].m_y + sqrt(2) * width; cords.push_back(p); p.m_x = point[1].m_x - sqrt(2) * width; p.m_y = point[1].m_y; cords.push_back(p); p.m_x = point[0].m_x; p.m_y = point[0].m_y - sqrt(2) * width; cords.push_back(p); p.m_x = point[0].m_x + sqrt(2) * width; p.m_y = point[0].m_y; cords.push_back(p); } else if ((point[1].m_x > point[0].m_x) && (point[1].m_y < point[0].m_y)) { p.m_x = point[0].m_x; p.m_y = point[0].m_y + sqrt(2) * width; cords.push_back(p); p.m_x = point[0].m_x - sqrt(2) * width; p.m_y = point[0].m_y; cords.push_back(p); p.m_x = point[1].m_x; p.m_y = point[1].m_y - sqrt(2) * width; cords.push_back(p); p.m_x = point[1].m_x + sqrt(2) * width; p.m_y = point[1].m_y; cords.push_back(p); } return cords; } points_2d via_to_circle(const point_2d &pos, const double &size) { auto radius = size / 2; auto coords = points_2d{}; auto point = point_2d{}; for (int i = 0; i < 40; ++i) { //40 points point.m_x = pos.m_x + radius * cos(-9 * i * M_PI / 180); point.m_y = pos.m_y + radius * sin(-9 * i * M_PI / 180); coords.push_back(point); } point.m_x = pos.m_x + radius * cos(0 * M_PI / 180); point.m_y = pos.m_y + radius * sin(0 * M_PI / 180); coords.push_back(point); return coords; } points_2d viaToOctagon(const double &size, const point_2d &pos, const double &clearance) { auto _size = point_2d{size / 2, size / 2}; auto coords = points_2d{}; auto point = point_2d{}; double r = _size.m_x + clearance; //[0] point.m_x = pos.m_x + r * tan(22.5 * M_PI / 180); point.m_y = pos.m_y + r; coords.push_back(point); //[1] point.m_x = pos.m_x + r; point.m_y = pos.m_y + r * tan(22.5 * M_PI / 180); coords.push_back(point); //[2] point.m_x = pos.m_x + r; point.m_y = pos.m_y - r * tan(22.5 * M_PI / 180); coords.push_back(point); //[3] point.m_x = pos.m_x + r * tan(22.5 * M_PI / 180); point.m_y = pos.m_y - r; coords.push_back(point); //[4] point.m_x = pos.m_x - r * tan(22.5 * M_PI / 180); point.m_y = pos.m_y - r; coords.push_back(point); //[5] point.m_x = pos.m_x - r; point.m_y = pos.m_y - r * tan(22.5 * M_PI / 180); coords.push_back(point); //[6] point.m_x = pos.m_x - r; point.m_y = pos.m_y + r * tan(22.5 * M_PI / 180); coords.push_back(point); //[7] point.m_x = pos.m_x - r * tan(22.5 * M_PI / 180); point.m_y = pos.m_y + r; coords.push_back(point); return coords; } ///////////////////////////////// // [7] [0] // [6] /------\ [1] // | pin | // [5] \______/ [2] // [4] [3] ///////////////////////////////// //RELATIVE COORDS TO PIN!! points_2d pinShapeToOctagon(const point_2d &size, const point_2d &pos, const double &clearance, const double &instAngle, const double &pinAngle, padShape type) { auto coords = points_2d{}; auto point = point_2d{}; if (type == padShape::CIRCLE) { //[0] point.m_x = (size.m_x / 2 + clearance) * tan(22.5 * M_PI / 180); point.m_y = size.m_y / 2 + clearance; coords.push_back(point); //[1] point.m_x = size.m_x / 2 + clearance; point.m_y = (size.m_y / 2 + clearance) * tan(22.5 * M_PI / 180); coords.push_back(point); //[2] point.m_x = size.m_x / 2 + clearance; point.m_y = (-size.m_y / 2 - clearance) * tan(22.5 * M_PI / 180); coords.push_back(point); //[3] point.m_x = (size.m_x / 2 + clearance) * tan(22.5 * M_PI / 180); point.m_y = -size.m_y / 2 - clearance; coords.push_back(point); //[4] point.m_x = (-size.m_x / 2 - clearance) * tan(22.5 * M_PI / 180); point.m_y = -size.m_y / 2 - clearance; coords.push_back(point); //[5] point.m_x = -size.m_x / 2 - clearance; point.m_y = (-size.m_y / 2 - clearance) * tan(22.5 * M_PI / 180); coords.push_back(point); //[6] point.m_x = -size.m_x / 2 - clearance; point.m_y = (size.m_y / 2 + clearance) * tan(22.5 * M_PI / 180); coords.push_back(point); //[7] point.m_x = (-size.m_x / 2 - clearance) * tan(22.5 * M_PI / 180); point.m_y = size.m_y / 2 + clearance; coords.push_back(point); } else { //[0] point.m_x = size.m_x / 2 + (clearance * tan(22.5 * M_PI / 180)); point.m_y = size.m_y / 2 + clearance; coords.push_back(point); //[1] point.m_x = size.m_x / 2 + clearance; point.m_y = size.m_y / 2 + (clearance * tan(22.5 * M_PI / 180)); coords.push_back(point); //[2] point.m_x = size.m_x / 2 + clearance; point.m_y = -size.m_y / 2 - (clearance * tan(22.5 * M_PI / 180)); coords.push_back(point); //[3] point.m_x = size.m_x / 2 + (clearance * tan(22.5 * M_PI / 180)); point.m_y = -size.m_y / 2 - clearance; coords.push_back(point); //[4] point.m_x = -size.m_x / 2 - (clearance * tan(22.5 * M_PI / 180)); point.m_y = -size.m_y / 2 - clearance; coords.push_back(point); //[5] point.m_x = -size.m_x / 2 - clearance; point.m_y = -size.m_y / 2 - (clearance * tan(22.5 * M_PI / 180)); coords.push_back(point); //[6] point.m_x = -size.m_x / 2 - clearance; point.m_y = size.m_y / 2 + (clearance * tan(22.5 * M_PI / 180)); coords.push_back(point); //[7] point.m_x = -size.m_x / 2 - (clearance * tan(22.5 * M_PI / 180)); point.m_y = size.m_y / 2 + clearance; coords.push_back(point); } return rotateShapeCoordsByAngles(coords, instAngle, pinAngle); } points_2d segmentToOctagon(const points_2d &point, const double &w, const double &clearance) { auto cords = points_2d{}; auto p = point_2d{}; auto width = w / 2; //vertical if (point[0].m_x == point[1].m_x) { if (point[0].m_y > point[1].m_y) { p.m_x = point[0].m_x + width + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y + width + clearance; cords.push_back(p); p.m_x = point[0].m_x + width + clearance; p.m_y = point[0].m_y + width + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x + width + clearance; p.m_y = point[1].m_y - width - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x + width + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y - width - clearance; cords.push_back(p); p.m_x = point[1].m_x - width - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y - width - clearance; cords.push_back(p); p.m_x = point[1].m_x - width - clearance; p.m_y = point[1].m_y - width - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x - width - clearance; p.m_y = point[0].m_y + width + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x - width - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y + width + clearance; cords.push_back(p); } else { p.m_x = point[1].m_x + width + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y + width + clearance; cords.push_back(p); p.m_x = point[1].m_x + width + clearance; p.m_y = point[1].m_y + width + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x + width + clearance; p.m_y = point[0].m_y - width - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x + width + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y - width - clearance; cords.push_back(p); p.m_x = point[0].m_x - width - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y - width - clearance; cords.push_back(p); p.m_x = point[0].m_x - width - clearance; p.m_y = point[0].m_y - width - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x - width - clearance; p.m_y = point[1].m_y + width + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x - width - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y + width + clearance; cords.push_back(p); } } //horizontal else if (point[0].m_y == point[1].m_y) { if (point[0].m_x > point[1].m_x) { p.m_x = point[0].m_x + width + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y + width + clearance; cords.push_back(p); p.m_x = point[0].m_x + width + clearance; p.m_y = point[0].m_y + width + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x + width + clearance; p.m_y = point[0].m_y - width - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x + width + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y - width - clearance; cords.push_back(p); p.m_x = point[1].m_x - width - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y - width - clearance; cords.push_back(p); p.m_x = point[1].m_x - width - clearance; p.m_y = point[1].m_y - width - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x - width - clearance; p.m_y = point[1].m_y + width + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x - width - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y + width + clearance; cords.push_back(p); } else { p.m_x = point[1].m_x + width + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y + width + clearance; cords.push_back(p); p.m_x = point[1].m_x + width + clearance; p.m_y = point[1].m_y + width + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x + width + clearance; p.m_y = point[1].m_y - width - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x + width + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y - width - clearance; cords.push_back(p); p.m_x = point[0].m_x - width - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y - width - clearance; cords.push_back(p); p.m_x = point[0].m_x - width - clearance; p.m_y = point[0].m_y - width - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x - width - clearance; p.m_y = point[0].m_y + width + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x - width - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y + width + clearance; cords.push_back(p); } } //45degree else if ((point[0].m_x > point[1].m_x) && (point[0].m_y > point[1].m_y)) { p.m_x = point[0].m_x + sqrt(2) * width + clearance; p.m_y = point[0].m_y + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x + sqrt(2) * width + clearance; p.m_y = point[0].m_y - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); //2 p.m_x = point[1].m_x + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y - sqrt(2) * width - clearance; cords.push_back(p); //3 p.m_x = point[1].m_x - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y - sqrt(2) * width - clearance; cords.push_back(p); p.m_x = point[1].m_x - sqrt(2) * width - clearance; p.m_y = point[1].m_y - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x - sqrt(2) * width - clearance; p.m_y = point[1].m_y + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y + sqrt(2) * width + clearance; cords.push_back(p); p.m_x = point[0].m_x + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y + sqrt(2) * width + clearance; cords.push_back(p); } else if ((point[0].m_x < point[1].m_x) && (point[0].m_y < point[1].m_y)) { p.m_x = point[1].m_x + sqrt(2) * width + clearance; p.m_y = point[1].m_y + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x + sqrt(2) * width + clearance; p.m_y = point[1].m_y - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); //2 p.m_x = point[0].m_x + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y - sqrt(2) * width - clearance; cords.push_back(p); //3 p.m_x = point[0].m_x - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y - sqrt(2) * width - clearance; cords.push_back(p); p.m_x = point[0].m_x - sqrt(2) * width - clearance; p.m_y = point[0].m_y - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x - sqrt(2) * width - clearance; p.m_y = point[0].m_y + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y + sqrt(2) * width + clearance; cords.push_back(p); p.m_x = point[1].m_x + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y + sqrt(2) * width + clearance; cords.push_back(p); } //135degree else if ((point[1].m_x < point[0].m_x) && (point[1].m_y > point[0].m_y)) { p.m_x = point[1].m_x - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y + sqrt(2) * width + clearance; cords.push_back(p); p.m_x = point[1].m_x + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y + sqrt(2) * width + clearance; cords.push_back(p); p.m_x = point[0].m_x + sqrt(2) * width + clearance; p.m_y = point[0].m_y + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x + sqrt(2) * width + clearance; p.m_y = point[0].m_y - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y - sqrt(2) * width - clearance; cords.push_back(p); p.m_x = point[0].m_x - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y - sqrt(2) * width - clearance; cords.push_back(p); p.m_x = point[1].m_x - sqrt(2) * width - clearance; p.m_y = point[1].m_y - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x - sqrt(2) * width - clearance; p.m_y = point[1].m_y + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); } else if ((point[1].m_x > point[0].m_x) && (point[1].m_y < point[0].m_y)) { p.m_x = point[0].m_x - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y + sqrt(2) * width + clearance; cords.push_back(p); p.m_x = point[0].m_x + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y + sqrt(2) * width + clearance; cords.push_back(p); p.m_x = point[1].m_x + sqrt(2) * width + clearance; p.m_y = point[1].m_y + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x + sqrt(2) * width + clearance; p.m_y = point[1].m_y - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y - sqrt(2) * width - clearance; cords.push_back(p); p.m_x = point[1].m_x - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y - sqrt(2) * width - clearance; cords.push_back(p); p.m_x = point[0].m_x - sqrt(2) * width - clearance; p.m_y = point[0].m_y - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x - sqrt(2) * width - clearance; p.m_y = point[0].m_y + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); } return cords; } points_2d segmentToRelativeOctagon(const points_2d &point, const double &w, const double &clearance) { auto coord = relativeStartEndPointsForSegment(point); return segmentToOctagon(coord, w, clearance); } points_2d viaToRelativeOctagon(const double &size, const double &clearance) { auto _size = point_2d{size / 2, size / 2}; auto coords = points_2d{}; auto point = point_2d{}; //[0] point.m_x = (_size.m_x + clearance) * tan(22.5 * M_PI / 180); point.m_y = _size.m_y + clearance; coords.push_back(point); //[1] point.m_x = _size.m_x + clearance; point.m_y = (_size.m_y + clearance) * tan(22.5 * M_PI / 180); coords.push_back(point); //[2] point.m_x = _size.m_x + clearance; point.m_y = -1 * (_size.m_y + clearance) * tan(22.5 * M_PI / 180); coords.push_back(point); //[3] point.m_x = (_size.m_x + clearance) * tan(22.5 * M_PI / 180); point.m_y = -1 * _size.m_y - clearance; coords.push_back(point); //[4] point.m_x = -1 * (_size.m_x + clearance) * tan(22.5 * M_PI / 180); point.m_y = -1 * _size.m_y - clearance; coords.push_back(point); //[5] point.m_x = -1 * _size.m_x - clearance; point.m_y = -1 * (_size.m_y + clearance) * tan(22.5 * M_PI / 180); coords.push_back(point); //[6] point.m_x = -1 * _size.m_x - clearance; point.m_y = (_size.m_y + clearance) * tan(22.5 * M_PI / 180); coords.push_back(point); //[7] point.m_x = -1 * (_size.m_x + clearance) * tan(22.5 * M_PI / 180); point.m_y = _size.m_y + clearance; coords.push_back(point); return coords; } points_2d relativeStartEndPointsForSegment(const points_2d &p) { auto pRelative = point_2d{}; auto coords = points_2d{}; pRelative.m_x = (p[0].m_x - p[1].m_x) / 2; pRelative.m_y = (p[0].m_y - p[1].m_y) / 2; coords.push_back(pRelative); pRelative.m_x = (p[1].m_x - p[0].m_x) / 2; pRelative.m_y = (p[1].m_y - p[0].m_y) / 2; coords.push_back(pRelative); return coords; }
33.995829
171
0.518833
yenyi
b687f2f402173eb1b7d32c6a6085eb022306d9a1
17,558
cc
C++
src/driver/parser.cc
cforall/resolv-proto
4eb7c0b9f4e75b940205e808e14fa57f13541246
[ "BSD-3-Clause" ]
2
2019-05-13T10:26:02.000Z
2019-05-13T15:04:42.000Z
src/driver/parser.cc
cforall/resolv-proto
4eb7c0b9f4e75b940205e808e14fa57f13541246
[ "BSD-3-Clause" ]
null
null
null
src/driver/parser.cc
cforall/resolv-proto
4eb7c0b9f4e75b940205e808e14fa57f13541246
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2015 University of Waterloo // // The contents of this file are covered under the licence agreement in // the file "LICENCE" distributed with this repository. #include "parser.h" #include <cstdlib> #include <iostream> #include <string> #include "args.h" #include "parser_common.h" #include "ast/decl.h" #include "ast/expr.h" #include "ast/forall.h" #include "ast/input_expr_visitor.h" #include "ast/type.h" #include "data/clock.h" #include "data/debug.h" #include "data/list.h" #include "data/mem.h" #include "data/option.h" #include "data/stats.h" #include "resolver/func_table.h" #include "resolver/resolver.h" /// Parses a name (lowercase alphanumeric ASCII string starting with a /// lowercase letter), returning true, storing result into ret, and /// incrementing token if so. token must not be null. bool parse_name(char const *&token, std::string& ret) { const char *end = token; if ( ('a' <= *end && *end <= 'z') || '_' == *end || '$' == *end ) ++end; else return false; while ( ('A' <= *end && *end <= 'Z') || ('a' <= *end && *end <= 'z') || ('0' <= *end && *end <= '9') || '_' == *end ) ++end; ret.assign( token, (end-token) ); token = end; return true; } /// Parses a named type name (hash followed by ASCII alphanumeric string /// starting with a letter or underscore), returning true, storing result /// (not including hash) into ret, and incrementing token if so. /// token must not be null bool parse_named_type(char const *&token, std::string& ret) { const char *end = token; if ( ! match_char(end, '#') ) return false; if ( ('A' <= *end && *end <= 'Z') || ('a' <= *end && *end <= 'z') || '_' == *end || '$' == *end ) ++end; else return false; while ( ('A' <= *end && *end <= 'Z') || ('a' <= *end && *end <= 'z') || ('0' <= *end && *end <= '9') || '_' == *end ) ++end; ret.assign( token+1, (end-token-1) ); token = end; return true; } /// Parses a polymorphic type name (lowercase alphanumeric ASCII string /// starting with an uppercase letter), returning true, storing result into /// ret, and incrementing token if so. token must not be null. bool parse_poly_type(char const *&token, std::string& ret) { const char *end = token; if ( 'A' <= *end && *end <= 'Z' ) ++end; else return false; while ( ('A' <= *end && *end <= 'Z') || ('a' <= *end && *end <= 'z') || ('0' <= *end && *end <= '9') || '_' == *end ) ++end; ret.assign( token, (end-token) ); token = end; return true; } /// Parses a type name, returning true, appending the result into out, and /// incrementing token if so. Concrete types will be canonicalized according /// to types and polymorphic types according to forall. token must not be null. bool parse_type(char const *&token, Resolver& resolver, Args& args, CanonicalTypeMap& types, unique_ptr<Forall>& forall, List<Type>& out); /// Parses an angle-bracket surrounded type list for the paramters of a generic named type bool parse_generic_params(char const *&token, Resolver& resolver, Args& args, CanonicalTypeMap& types, unique_ptr<Forall>& forall, List<Type>& out) { const char *end = token; if ( ! match_char(end, '<') ) return false; match_whitespace(end); if ( ! parse_type(end, resolver, args, types, forall, out) ) return false; while ( match_whitespace(end) ) { if ( ! parse_type(end, resolver, args, types, forall, out) ) break; } if ( ! match_char(end, '>') ) return false; token = end; return true; } /// Parses a function type, returning true, appending the result into out, and /// incrementing token if so. Concrete types will be canonicalized according /// to types and polymorphic types according to forall. token must not be null bool parse_func_type(const char*& token, Resolver& resolver, Args& args, CanonicalTypeMap& types, unique_ptr<Forall>& forall, List<Type>& out ) { List<Type> returns, params; const char* end = token; // match opening token if ( ! match_char(end, '[') ) return false; match_whitespace(end); // match return types while ( parse_type(end, resolver, args, types, forall, returns) ) { match_whitespace(end); } // match split token if ( ! match_char(end, ':') ) return false; match_whitespace(end); // match parameters while ( parse_type(end, resolver, args, types, forall, params) ) { match_whitespace(end); } // match closing token if ( ! match_char(end, ']') ) return false; match_whitespace(end); out.push_back( new FuncType{ move(params), move(returns) } ); token = end; return true; } bool parse_type(char const *&token, Resolver& resolver, Args& args, CanonicalTypeMap& types, unique_ptr<Forall>& forall, List<Type>& out) { int t; std::string n; if ( parse_int(token, t) ) { auto it = get_canon<ConcType>( types, t ); if ( it.second && ! args.metrics_only() ) resolver.addType( it.first ); out.push_back( it.first ); return true; } else if ( parse_named_type(token, n) ) { List<Type> params; parse_generic_params( token, resolver, args, types, forall, params ); auto it = get_canon( types, n, move(params) ); if ( it.second && ! args.metrics_only() ) resolver.addType( it.first ); out.push_back( it.first ); return true; } else if ( parse_poly_type(token, n) ) { if ( ! forall ) { forall.reset( new Forall{} ); } out.push_back( forall->add( n ) ); return true; } else if ( parse_func_type(token, resolver, args, types, forall, out) ) { return true; } else return false; } /// Parses a type assertion, returning true and adding the assertion into /// binding if so. Concrete types will be canonicalized according to types. /// token must not be null. bool parse_assertion(char const *&token, Resolver& resolver, Args& args, CanonicalTypeMap& types, unique_ptr<Forall>& forall) { const char* end = token; // look for type assertion if ( ! match_char(end, '|') ) return false; // parse return types List<Type> returns; match_whitespace(end); while ( parse_type(end, resolver, args, types, forall, returns) ) { match_whitespace(end); } std::string name; // try for variable assertion if ( match_char(end, '&') ) { if ( ! parse_name(end, name) ) return false; if ( ! forall ) { forall.reset( new Forall{} ); } forall->addAssertion( new VarDecl{ name, move(returns) } ); token = end; return true; } // function assertion -- parse name if ( ! parse_name(end, name) ) return false; // parse parameters List<Type> params; match_whitespace(end); while ( parse_type(end, resolver, args, types, forall, params) ) { match_whitespace(end); } if ( ! forall ) { forall.reset( new Forall{} ); } forall->addAssertion( new FuncDecl{ name, move(params), move(returns) } ); token = end; return true; } /// Parses a declaration from line; returns true and adds the declaration to /// funcs if found; will fail if given a valid func that does not consume the /// whole line. line must not be null. bool parse_decl( char const *line, Resolver& resolver, CanonicalTypeMap& types, Args& args, Metrics& metrics ) { List<Type> returns; std::string name; std::string tag = ""; unique_ptr<Forall> forall; // parse return types match_whitespace(line); while ( parse_type(line, resolver, args, types, forall, returns) ) { match_whitespace(line); } // check for variable decl if ( ! returns.empty() && match_char(line, '&') ) { if ( ! parse_name(line, name) ) return false; // optionally parse tag if ( match_char(line, '-') ) { if ( ! parse_name(line, tag) ) return false; } // check line consumed if ( ! is_blank(line) ) return false; if ( ! args.metrics_only() ) { resolver.addDecl( new VarDecl{ name, tag, move(returns) } ); } metrics.mark_decl( name ); return true; } // parse function decl List<Type> params; if ( ! parse_name(line, name) ) return false; // optionally parse tag if ( match_char(line, '-') ) { // might have been subsequent negative-valued type if ( ! parse_name(line, tag) ) { --line; } } // parse parameters match_whitespace(line); while ( parse_type(line, resolver, args, types, forall, params) ) { match_whitespace(line); } // parse type assertions while ( parse_assertion(line, resolver, args, types, forall) ); // check line consumed if ( ! is_empty(line) ) return false; // complete declaration if ( forall ) { metrics.mark_decl( name, forall->assertions().size() ); } else { metrics.mark_decl( name ); } if ( ! args.metrics_only() ) { resolver.addDecl( new FuncDecl{ name, tag, move(params), move(returns), move(forall) } ); } return true; } /// Parses a concrete type name, returning true, appending the result into out, and /// incrementing token if so. Concrete types will be canonicalized according /// to types and polymorphic types forbidden. token must not be null. bool parse_conc_type(char const *&token, Resolver& resolver, Args& args, CanonicalTypeMap& types, List<Type>& out); /// Parses an angle-bracket surrounded type list for the paramters of a concrete generic named type bool parse_conc_generic_params(char const *&token, Resolver& resolver, Args& args, CanonicalTypeMap& types, List<Type>& out) { const char *end = token; if ( ! match_char(end, '<') ) return false; match_whitespace(end); if ( ! parse_conc_type(end, resolver, args, types, out) ) return false; while ( match_whitespace(end) ) { if ( ! parse_conc_type(end, resolver, args, types, out) ) break; } if ( ! match_char(end, '>') ) return false; token = end; return true; } bool parse_conc_type(char const *&token, Resolver& resolver, Args& args, CanonicalTypeMap& types, List<Type>& out) { int t; std::string n; if ( parse_int(token, t) ) { // ConcType auto it = get_canon<ConcType>( types, t ); if ( it.second && ! args.metrics_only() ) resolver.addType( it.first ); out.push_back( it.first ); return true; } else if ( parse_named_type(token, n) ) { // concrete NamedType List<Type> params; parse_conc_generic_params( token, resolver, args, types, params ); auto it = get_canon( types, n, move(params) ); if ( it.second && ! args.metrics_only() ) resolver.addType( it.first ); out.push_back( it.first ); return true; } else if ( match_char(token, '[') ) { // concrete FuncType match_whitespace(token); // match return types List<Type> returns; while ( parse_conc_type(token, resolver, args, types, returns) ) { match_whitespace(token); } // match split token if ( ! match_char(token, ':') ) return false; match_whitespace(token); // match parameters List<Type> params; while ( parse_conc_type(token, resolver, args, types, params) ) { match_whitespace(token); } // match closing token if ( ! match_char(token, ']') ) return false; match_whitespace(token); // return type out.push_back( new FuncType{ move(params), move(returns) } ); return true; } else return false; } /// Parses a subexpression; returns true and adds the expression to exprs if found. /// line must not be null. bool parse_subexpr( char const *&token, List<Expr>& exprs, Resolver& resolver, Args& args, Metrics& metrics, CanonicalTypeMap& types ) { const char *end = token; // Check for a concrete type expression List<Type> cty; if ( parse_conc_type( end, resolver, args, types, cty ) ) { exprs.push_back( new ValExpr( cty.front() ) ); metrics.mark_sub(); token = end; return true; } // Check for name expression if ( match_char(end, '&') ) { std::string name; if ( ! parse_name(end, name) ) return false; match_whitespace(end); exprs.push_back( new NameExpr( name ) ); metrics.mark_sub(); token = end; return true; } // Check for function call std::string name; if ( ! parse_name(end, name) ) return false; match_whitespace(end); if ( ! match_char(end, '(') ) return false; // Read function args metrics.start_subs(); List<Expr> eargs; match_whitespace(end); while ( parse_subexpr(end, eargs, resolver, args, metrics, types) ) { match_whitespace(end); } metrics.end_subs(); // Find closing bracket if ( ! match_char(end, ')') ) return false; match_whitespace(end); exprs.push_back( new FuncExpr( name, move(eargs) ) ); metrics.mark_sub(); token = end; return true; } /// Per-instance input metrics struct InputMetrics { unsigned max_depth = 0; unsigned max_params = 0; unsigned n_subexprs = 0; unsigned max_overloads = 0; }; /// Calculates metrics on input expression class InputExprMetrics : public InputExprVisitor<InputExprMetrics, InputMetrics> { const Metrics& ftab; public: using Super = InputExprVisitor<InputExprMetrics, InputMetrics>; using Super::visit; InputExprMetrics(const Metrics& ftab) : ftab(ftab) {} bool visit( const ValExpr*, InputMetrics& m ) { ++m.max_depth; ++m.n_subexprs; return true; } bool visit( const NameExpr* e, InputMetrics& m ) { ++m.max_depth; ++m.n_subexprs; // update max overloads unsigned n_decls = ftab.n_decls_for( e->name() ); if ( n_decls > m.max_overloads ) { m.max_overloads = n_decls; } return true; } bool visit( const FuncExpr* e, InputMetrics & m ) { ++m.n_subexprs; // update max params unsigned n_params = e->args().size(); if ( n_params > m.max_params ) { m.max_params = n_params; } // update max depth unsigned local_d = ++m.max_depth; unsigned max_d = local_d; for ( const Expr* arg : e->args() ) { visit( arg, m ); if ( m.max_depth > max_d ) { max_d = m.max_depth; } m.max_depth = local_d; } m.max_depth = max_d; // update max overloads unsigned n_decls = ftab.n_decls_for( e->name() ); if ( n_decls > m.max_overloads ) { m.max_overloads = n_decls; } return true; } }; /// Parses an expression from line; returns true and adds the expression to /// exprs if found; will fail if given a valid expr that does not consume the /// whole line. line must not be null. bool parse_expr( unsigned n, char const *line, Resolver& resolver, Args& args, Metrics& metrics, CanonicalTypeMap& types ) { match_whitespace(line); List<Expr> exprs; if ( parse_subexpr(line, exprs, resolver, args, metrics, types) && is_empty(line) ) { assume( exprs.size() == 1, "successful expression parse results in single expression" ); if ( ! args.metrics_only() ) { if ( args.per_prob() ) { volatile std::clock_t start, end; InputMetrics m = InputExprMetrics{metrics}( exprs[0] ); args.out() << n << "," << m.max_depth << "," << m.max_params << "," << m.n_subexprs << "," << m.max_overloads << ","; #ifdef RP_STATS crnt_pass = Resolve; #endif start = std::clock(); resolver.addExpr( exprs[0] ); end = std::clock(); #ifdef RP_STATS crnt_pass = Parse; #endif args.out() << "," << (end-start)/*microseconds*/ << std::endl; } else { #ifdef RP_STATS crnt_pass = Resolve; #endif resolver.addExpr( exprs[0] ); #ifdef RP_STATS crnt_pass = Parse; #endif } } metrics.mark_expr(); return true; } else { metrics.reset_expr(); return false; } } /// Mode for echo_line -- declarations are echoed for Filtered verbosity, expressions are not enum EchoMode { EXPR, DECL }; /// Echos line if in appropriate mode void echo_line( std::string& line, Args& args, EchoMode mode = EXPR ) { if ( args.verbosity() == Args::Verbosity::Verbose || ( args.verbosity() == Args::Verbosity::Filtered && mode == DECL ) ) { args.out() << line << std::endl; } } /// Parses a scope from a series of lines (excluding opening "{" line if in block), /// continuing until end-of-input or terminating "}" line is found. /// Prints an error and exits if invalid declaration or expression found void parse_block( std::istream& in, unsigned& n, unsigned& scope, Resolver& resolver, CanonicalTypeMap& types, Args& args, Metrics& metrics ) { std::string line; // parse declarations and delimiter while ( std::getline( in, line ) ) { ++n; if ( is_blank( line ) ) { echo_line( line, args, DECL ); continue; } // break when finished declarations if ( line_matches( line, "%%" ) ) { echo_line( line, args, DECL ); break; } bool ok = parse_decl( line.data(), resolver, types, args, metrics ); if ( ! ok ) { std::cerr << "Invalid declaration [" << n << "]: \"" << line << "\"" << std::endl; std::exit(1); } echo_line( line, args, DECL ); } while ( std::getline( in, line ) ) { ++n; if ( is_blank( line ) ) { echo_line( line, args ); continue; } // break when finished block if ( line_matches( line, "}" ) ) { --scope; resolver.endScope(); metrics.end_lex_scope(); break; } // recurse when starting new block if ( line_matches( line, "{" ) ) { ++scope; resolver.beginScope(); metrics.begin_lex_scope(); parse_block( in, n, scope, resolver, types, args, metrics ); continue; } // parse and resolve expression if ( args.line_nos() ) { args.out() << n << ": " << std::flush; } bool ok = parse_expr( n, line.data(), resolver, args, metrics, types ); if ( ! ok ) { std::cerr << "Invalid expression [" << n << "]: \"" << line << "\"" << std::endl; std::exit(1); } echo_line( line, args ); } } void run_input( std::istream& in, Resolver& resolver, Args& args, Metrics& metrics ) { CanonicalTypeMap types; unsigned n = 0, scope = 0; parse_block(in, n, scope, resolver, types, args, metrics); if ( scope != 0 ) { std::cerr << "Unmatched braces" << std::endl; std::exit(1); } }
28.319355
99
0.650644
cforall
b692bd9f43bf79f36ad69388ce178bf388749810
873
cpp
C++
examples/priority_queue.cpp
miachm/STL-Threadsafe
08b2d9e7f487121088a817071d1d42b2736996e9
[ "Apache-2.0" ]
9
2017-07-25T23:22:54.000Z
2021-07-06T06:24:46.000Z
examples/priority_queue.cpp
miachm/STL-Threadsafe
08b2d9e7f487121088a817071d1d42b2736996e9
[ "Apache-2.0" ]
null
null
null
examples/priority_queue.cpp
miachm/STL-Threadsafe
08b2d9e7f487121088a817071d1d42b2736996e9
[ "Apache-2.0" ]
3
2020-12-11T03:02:35.000Z
2021-08-22T17:01:28.000Z
#include <iostream> #include <thread> #include "priority_queue-threadsafe.hpp" int main(){ std::threadsafe::priority_queue<int> bids; std::thread producer([&]{ int randomBids[20] = {3,19,11,2,4,12,1,20,14,5,18,10,15,8,17,6,16,7,9,13}; for (int i = 0;i < 20;i++){ bids.push(randomBids[i]); std::this_thread::sleep_for(std::chrono::milliseconds(1)); } }); try{ int out; while (true){ bids.wait_pop(out,std::chrono::milliseconds(100)); std::cout << "Checking new bids" << std::endl; std::cout << "\tBid: " << out << std::endl; while (bids.try_pop(out)){ std::cout << "\tBid: " << out << std::endl; } std::cout << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(3)); } } catch (std::threadsafe::Time_Expired e){ std::cout << "No more bids coming, shutting down..." << std::endl; } producer.join(); }
22.973684
76
0.610538
miachm
b699379d09377d60e623f06ea2d6dbdfac24156e
2,339
cpp
C++
day2/main.cpp
fardragon/AdventOfCode2021
16f31bcf2e7ff3a1c943e6dfb8b9e791f029dbea
[ "MIT" ]
1
2021-12-02T14:11:37.000Z
2021-12-02T14:11:37.000Z
day2/main.cpp
fardragon/AdventOfCode2021
16f31bcf2e7ff3a1c943e6dfb8b9e791f029dbea
[ "MIT" ]
null
null
null
day2/main.cpp
fardragon/AdventOfCode2021
16f31bcf2e7ff3a1c943e6dfb8b9e791f029dbea
[ "MIT" ]
null
null
null
#include "shared.hpp" #include <iostream> #include <numeric> #include <chrono> std::uint32_t SolvePart1(const std::vector<std::pair<std::string, std::uint16_t>> &input); std::uint32_t SolvePart2(const std::vector<std::pair<std::string, std::uint16_t>> &input); //std::uint16_t SolvePart2(const std::vector<uint16_t> &input); int main(int argc, char **argv) { if (argc < 2) { throw std::runtime_error("Not enough input arguments"); } const auto begin = std::chrono::steady_clock::now(); const auto lines = LoadLines(argv[1]); const auto input = LinesToStrUint16(lines); const auto beginSolving = std::chrono::steady_clock::now(); const auto part1Result = SolvePart1(input); const auto part2Result = SolvePart2(input); const auto end = std::chrono::steady_clock::now(); const auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count(); const auto elapsedSolving = std::chrono::duration_cast<std::chrono::microseconds>(end - beginSolving).count(); std::cout << "Part 1 result: " << part1Result << "\r\n"; std::cout << "Part 2 result: " << part2Result << "\r\n"; std::cout << "Time: " << elapsed << "us \r\n"; std::cout << "Time (without reading and parsing): " << elapsedSolving << "us \r\n"; return 0; } std::uint32_t SolvePart1(const std::vector<std::pair<std::string, std::uint16_t>> &input) { std::uint32_t position{}, depth{}; for (const auto &[command, argument]: input) { switch(command.front()) { case 'f': { //forward position += argument; break; } case 'u': { // up depth -= argument; break; } case 'd': { // down depth += argument; break; } default: throw std::runtime_error("Invalid command"); } } return position * depth; } std::uint32_t SolvePart2(const std::vector<std::pair<std::string, std::uint16_t>> &input) { std::uint32_t position{}, depth{}; std::int32_t aim{}; for (const auto &[command, argument]: input) { switch(command.front()) { case 'f': { //forward position += argument; depth += (aim * argument); break; } case 'u': { // up aim -= argument; break; } case 'd': { // down aim += argument; break; } default: throw std::runtime_error("Invalid command"); } } return position * depth; }
22.066038
111
0.626764
fardragon
b6a26a510f6b78583d7ef149fb455db65ac8d300
458
hpp
C++
tools/stopwatch.hpp
matumoto1234/library
a2c80516a8afe5876696c139fe0e837d8a204f69
[ "Unlicense" ]
2
2021-06-24T11:21:08.000Z
2022-03-15T05:57:25.000Z
tools/stopwatch.hpp
matumoto1234/library
a2c80516a8afe5876696c139fe0e837d8a204f69
[ "Unlicense" ]
102
2021-10-30T21:30:00.000Z
2022-03-26T18:39:47.000Z
tools/stopwatch.hpp
matumoto1234/library
a2c80516a8afe5876696c139fe0e837d8a204f69
[ "Unlicense" ]
null
null
null
#pragma once #include "./base.hpp" #include <chrono> namespace tools { struct Stopwatch { chrono::high_resolution_clock::time_point start; Stopwatch() { restart(); } void restart() { start = chrono::high_resolution_clock::now(); } chrono::milliseconds::rep elapsed() { auto end = chrono::high_resolution_clock::now(); return chrono::duration_cast<chrono::milliseconds>(end - start).count(); } }; } // namespace tools
22.9
78
0.665939
matumoto1234
b6a95c64cfaa3b62665f75129a8ddd8523dfcb24
1,402
hpp
C++
src/ivorium_graphics/Rendering/Shader.hpp
ivorne/ivorium
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
[ "Apache-2.0" ]
3
2021-02-26T02:59:09.000Z
2022-02-08T16:44:21.000Z
src/ivorium_graphics/Rendering/Shader.hpp
ivorne/ivorium
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
[ "Apache-2.0" ]
null
null
null
src/ivorium_graphics/Rendering/Shader.hpp
ivorne/ivorium
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
[ "Apache-2.0" ]
null
null
null
#pragma once #include "../OpenGL/GlTexture.hpp" #include "../OpenGL/GlProgram.hpp" #include "../OpenGL/gl.h" #include "GlSystem.hpp" #include <ivorium_systems/ivorium_systems.hpp> #include <ivorium_core/ivorium_core.hpp> namespace iv { /** To create shader using VirtualResourceProvider method, construct it from a path which has fragment shader source at path+".frag" and vertex shader source at path+".vert". */ class Shader { public: ClientMarker cm; Shader( Instance * inst, ResourcePath const & path ); ~Shader(); Instance * instance() const; void status( iv::TableDebugView * view ); //--------------------- loading ---------------------- void LoadProgram(); void BindAttribute( GLuint location, const char * attrib_name ); void PositionAttributeName( const char * name ); void LinkProgram(); void UnloadProgram(); void DropProgram(); //--------------------- usage ------ GlProgram const * gl_program() const; GLint GetUniformLocation( const char * name ) const; private: Instance * inst; ResourcePath _src_path; GlProgram _gl_program; }; }
29.208333
174
0.524964
ivorne
b6b4d64f46c26a28f0216235aade202182e0cfe5
15,740
cpp
C++
src/Organism.cpp
Sn0wFox/ot3-pro2017
889dcbb1ad0203a916e7431c6525fded49ef57dd
[ "MIT" ]
1
2017-11-13T07:23:52.000Z
2017-11-13T07:23:52.000Z
src/Organism.cpp
Sn0wFox/ot3-pro2017
889dcbb1ad0203a916e7431c6525fded49ef57dd
[ "MIT" ]
null
null
null
src/Organism.cpp
Sn0wFox/ot3-pro2017
889dcbb1ad0203a916e7431c6525fded49ef57dd
[ "MIT" ]
null
null
null
// // Created by arrouan on 28/09/16. // #include "Organism.h" #include "DNA.h" #include "Common.h" #include <map> void Organism::translate_RNA() { RNA* current_rna = nullptr; for (auto it = dna_->bp_list_.begin(); it != dna_->bp_list_.end(); it++) { if ((*it)->type_ == (int)BP::BP_Type::START_RNA) { current_rna = new RNA((*it)->binding_pattern_, (*it)->concentration_); } else if ((*it)->type_ == (int)BP::BP_Type::END_RNA) { if (current_rna != nullptr) { rna_list_.push_back(current_rna); current_rna = nullptr; } } else if (current_rna != nullptr) { current_rna->bp_list_.push_back(new BP((*it))); } } } void Organism::translate_protein() { float binding_pattern = -1; int rna_id = 0; for ( auto it = rna_list_.begin(); it != rna_list_.end(); it++ ) { for (auto it_j = (*it)->bp_list_.begin(); it_j < (*it)->bp_list_.end(); it_j++) { if ((*it_j)->type_ == (int) BP::BP_Type::START_PROTEIN) { binding_pattern = (*it_j)->binding_pattern_; } else if ((*it_j)->type_ == (int) BP::BP_Type::END_PROTEIN) { binding_pattern = -1; } else if (((*it_j)->type_ == (int) BP::BP_Type::PROTEIN_BLOCK) && (binding_pattern != -1)) { bool current_float = false; // true == next value if op arith else float bool first_value = true; // current_value is initialized or not float current_value = -1; int current_arith_op = -1; for (auto it_k = (*it_j)->protein_block_->bp_prot_list_.begin(); it_k < (*it_j)->protein_block_->bp_prot_list_.end(); it_k++) { if ((*it_k)->type_ == (int) BP_Protein::BP_Protein_Type::ARITHMETIC_OPERATOR) { if (current_float) { current_arith_op = (*it_k)->op_; current_float = false; } } else if ((*it_k)->type_ == (int) BP_Protein::BP_Protein_Type::FLOAT_NUMBER) { if ((!current_float) && first_value) { current_value = (*it_k)->number_; current_float = true; first_value = false; } else if ((!current_float) && (!first_value)) { float value = (*it_k)->number_; current_float = true; if (current_arith_op == (int) BP_Protein::Arithmetic_Operator_Type::ADD) { current_value+=value; } else if (current_arith_op == (int) BP_Protein::Arithmetic_Operator_Type::MODULO) { current_value=std::fmod(current_value,value); } else if (current_arith_op == (int) BP_Protein::Arithmetic_Operator_Type::MULTIPLY) { current_value*=value; } else if (current_arith_op == (int) BP_Protein::Arithmetic_Operator_Type::POWER) { current_value=std::pow(current_value,value); } } } } int type = -1; if (current_value < 0.8) { type = (int) Protein::Protein_Type::FITNESS; } else if (current_value >= 0.8 && current_value < 0.9) { type = (int) Protein::Protein_Type::TF; } else if (current_value >= 0.9 && current_value < 0.95) { type = (int) Protein::Protein_Type::POISON; } else if (current_value >= 0.95 && current_value < 1.0) { type = (int) Protein::Protein_Type::ANTIPOISON; } Protein* prot = new Protein(type,binding_pattern,current_value); prot->concentration_ = (*it)->concentration_base_; if ( protein_list_map_.find(current_value) == protein_list_map_.end() ) { protein_list_map_[current_value] = prot; if (type == (int) Protein::Protein_Type::FITNESS) { protein_fitness_list_.push_back(prot); } else if (type == (int) Protein::Protein_Type::TF) { protein_TF_list_.push_back(prot); } else if (type == (int) Protein::Protein_Type::POISON) { protein_poison_list_.push_back(prot); } else if (type == (int) Protein::Protein_Type::ANTIPOISON) { protein_antipoison_list_.push_back(prot); } } else { protein_list_map_[current_value]->concentration_+=(*it)->concentration_base_; delete prot; } rna_produce_protein_.push_back(current_value); } } rna_id++; } } void Organism::translate_pump() { bool within_pump = false; for ( auto it = rna_list_.begin(); it != rna_list_.end(); it++ ) { for (auto it_j = (*it)->bp_list_.begin(); it_j < (*it)->bp_list_.end(); it_j++) { if ((*it_j)->type_ == (int) BP::BP_Type::START_PUMP) { within_pump = true; } else if ((*it_j)->type_ == (int) BP::BP_Type::END_PUMP) { within_pump = false; } else if (((*it_j)->type_ == (int) BP::BP_Type::PUMP_BLOCK) && (within_pump)) { for (auto it_k=(*it_j)->pump_block_->bp_pump_list_.begin(); it_k < (*it_j)->pump_block_-> bp_pump_list_.end(); it_k++) { Pump* pump = new Pump((*it_k)->in_out_,(*it_k)->start_range_, (*it_k)->end_range_,(*it_k)->speed_); pump_list_.push_back(pump); } } } } } void Organism::translate_move() { bool within_move = false; for ( auto it = rna_list_.begin(); it != rna_list_.end(); it++ ) { for (auto it_j = (*it)->bp_list_.begin(); it_j < (*it)->bp_list_.end(); it_j++) { if ((*it_j)->type_ == (int) BP::BP_Type::START_MOVE) { within_move = true; } else if ((*it_j)->type_ == (int) BP::BP_Type::END_MOVE) { within_move = false; } else if (((*it_j)->type_ == (int) BP::BP_Type::MOVE_BLOCK) && (within_move)) { for (auto it_k=(*it_j)->move_block_-> bp_move_list_.begin(); it_k < (*it_j)->move_block_-> bp_move_list_.end(); it_k++) { Move* move = new Move((*it_k)->distance_,(*it_k)->retry_); move_list_.push_back(move); } } } } } void Organism::compute_next_step() { // Activate Pump activate_pump(); // Compute protein concentration for X steps compute_protein_concentration(); } void Organism::activate_pump() { for (auto it = pump_list_.begin(); it != pump_list_.end(); it++) { if ((*it)->in_out_) { for (auto prot : protein_list_map_) { if ((*it)->start_range_ >= prot.second->value_ && (*it)->end_range_ <= prot.second->value_) { float remove = prot.second->concentration_*((*it)->speed_/100); prot.second->concentration_ -= remove; if ( gridcell_->protein_list_map_.find(prot.second->value_) == gridcell_->protein_list_map_.end() ) { Protein* prot_n = new Protein(prot.second->type_, prot.second->binding_pattern_, prot.second->value_); prot_n->concentration_ = remove; gridcell_->protein_list_map_[prot.second->value_] = prot_n; } else { gridcell_->protein_list_map_[prot.second->value_]->concentration_ += remove; } } } } else { for (auto prot : gridcell_->protein_list_map_) { if ((*it)->start_range_ >= prot.first && (*it)->end_range_ <= prot.first) { float remove = prot.second->concentration_*((*it)->speed_/100); prot.second->concentration_ -= remove; if ( protein_list_map_.find(prot.first) == protein_list_map_.end() ) { Protein* prot_n = new Protein(prot.second->type_, prot.second->binding_pattern_, prot.second->value_); prot_n->concentration_ = remove; protein_list_map_[prot_n->value_] = prot_n; } else { protein_list_map_[prot.first]->concentration_ += remove; } } } } } } void Organism::init_organism() { translate_RNA(); translate_protein(); translate_pump(); translate_move(); } void Organism::compute_protein_concentration() { current_concentration_compute(); delta_concentration_compute(); } // TODO: the critical call everyone ! void Organism::delta_concentration_compute() { for (int rna_id = 0; rna_id < rna_produce_protein_.size(); rna_id++) { rna_list_[rna_id]->current_concentration_ -= Common::Protein_Degradation_Rate * protein_list_map_[rna_produce_protein_[rna_id]]->concentration_; rna_list_[rna_id]->current_concentration_ *= 1/(Common::Protein_Degradation_Step); protein_list_map_[rna_produce_protein_[rna_id]]->concentration_+=rna_list_[rna_id]->current_concentration_; } } bool Organism::dying_or_not() { // Compute if dying or not double concentration_sum = 0; for (auto prot : protein_fitness_list_) { concentration_sum+=prot->concentration_; } for (auto prot : protein_TF_list_) { concentration_sum+=prot->concentration_; } if (concentration_sum > 10.0 && concentration_sum <= 0.0) { return true; } double poison=0,antipoison=0; for (auto prot : protein_poison_list_) { poison+=prot->concentration_; } for (auto prot : protein_antipoison_list_) { antipoison+=prot->concentration_; } if (poison-antipoison>0.1) { return true; } std::binomial_distribution<int> dis_death(1024,Common::Random_Death); int death_number = dis_death(gridcell_->float_gen_); bool death = (bool) death_number % 2; return death; } void Organism::try_to_move() { for (auto it = move_list_.begin(); it != move_list_.end(); it++) { if ((*it)->distance_ > 0) { bool move = false; int retry = 0; std::uniform_int_distribution<uint32_t> dis_distance(0,(*it)->distance_); while (retry < (*it)->retry_ && !move) { int x_offset=dis_distance(gridcell_->float_gen_); int y_offset=dis_distance(gridcell_->float_gen_); int new_x,new_y; if (gridcell_->x_+x_offset >= gridcell_->world_->width_) { new_x = gridcell_->world_->width_-1; } else { new_x = gridcell_->x_+x_offset; } if (gridcell_->y_+y_offset >= gridcell_->world_->height_) { new_y = gridcell_->world_->height_-1; } else { new_y = gridcell_->y_+y_offset; } if (gridcell_->world_->grid_cell_[new_x*gridcell_->world_->width_+new_y]->organism_ != nullptr) { move = true; move_success_++; gridcell_->world_->grid_cell_[new_x*gridcell_->world_->width_+new_y]->organism_ = this; gridcell_ = gridcell_->world_->grid_cell_[new_x*gridcell_->world_->width_+new_y]; gridcell_->organism_ = nullptr; } } } } } void Organism::compute_fitness() { life_duration_++; for (int i = 0; i < Common::Metabolic_Error_Precision; i++) metabolic_error[i] = 0.0; for (auto prot : protein_fitness_list_) { //.begin(); it != protein_fitness_list_.end(); it++) { int index = prot->value_*Common::Metabolic_Error_Precision; float concentration = prot->concentration_; for (int j = index - Common::Metabolic_Error_Protein_Spray; j <= index + Common::Metabolic_Error_Protein_Spray; j++) { if (j < Common::Metabolic_Error_Precision && j >= 0) { if (j < index) { metabolic_error[j] += (index - j) * Common::Metabolic_Error_Protein_Slope * concentration; } else if (j > index) { metabolic_error[j] += (j - index) * Common::Metabolic_Error_Protein_Slope * concentration; } else { metabolic_error[j] += concentration; } } } } sum_metabolic_error = 0; for (int i = 0; i < Common::Metabolic_Error_Precision; i++) { sum_metabolic_error+=std::abs(gridcell_->environment_target[i]-metabolic_error[i]); } sum_metabolic_error=sum_metabolic_error/Common::Metabolic_Error_Precision; fitness_ = std::exp(-Common::Fitness_Selection_Pressure*sum_metabolic_error); } void Organism::mutate() { old = this; std::binomial_distribution<int> dis_switch(dna_->bp_list_.size(),Common::Mutation_Rate); std::binomial_distribution<int> dis_insertion(dna_->bp_list_.size(),Common::Mutation_Rate); std::binomial_distribution<int> dis_deletion(dna_->bp_list_.size(),Common::Mutation_Rate); std::binomial_distribution<int> dis_duplication(dna_->bp_list_.size(),Common::Mutation_Rate); std::binomial_distribution<int> dis_modification(dna_->bp_list_.size(),Common::Mutation_Rate); int nb_switch = dis_switch(gridcell_->float_gen_); int nb_insertion = dis_insertion(gridcell_->float_gen_); int nb_deletion = dis_deletion(gridcell_->float_gen_); int nb_duplication = dis_duplication(gridcell_->float_gen_); int nb_modification = dis_modification(gridcell_->float_gen_); std::uniform_int_distribution<uint32_t> dis_position(0,dna_->bp_list_.size()); for (int i = 0; i < nb_deletion; i++) { int deletion_pos = dis_position(gridcell_->float_gen_); while (deletion_pos >= dna_->bp_list_.size()) { deletion_pos = dis_position(gridcell_->float_gen_); } dna_->bp_list_.erase(dna_->bp_list_.begin() + deletion_pos); } for (int i = 0; i < nb_switch; i++) { int switch_pos_1 = dis_position(gridcell_->float_gen_); while (switch_pos_1 >= dna_->bp_list_.size()) { switch_pos_1 = dis_position(gridcell_->float_gen_); } int switch_pos_2 = dis_position(gridcell_->float_gen_); while (switch_pos_2 >= dna_->bp_list_.size()) { switch_pos_2 = dis_position(gridcell_->float_gen_); } BP* tmp = dna_->bp_list_[switch_pos_1]; dna_->bp_list_[switch_pos_1] = dna_->bp_list_[switch_pos_2]; dna_->bp_list_[switch_pos_2] = tmp; } for (int i = 0; i < nb_duplication; i++) { int duplication_pos = dis_position(gridcell_->float_gen_); while (duplication_pos >= dna_->bp_list_.size()) { duplication_pos = dis_position(gridcell_->float_gen_); } int where_to_duplicate = dis_position(gridcell_->float_gen_); while (where_to_duplicate >= dna_->bp_list_.size()) { where_to_duplicate = dis_position(gridcell_->float_gen_); } dna_->bp_list_.insert(dna_->bp_list_.begin()+where_to_duplicate, new BP(dna_->bp_list_[duplication_pos])); } for (int i = 0; i < nb_insertion; i++) { int insertion_pos = dis_position(gridcell_->float_gen_); while (insertion_pos >= dna_->bp_list_.size()) { insertion_pos = dis_position(gridcell_->float_gen_); } dna_->insert_a_BP(insertion_pos,gridcell_); } for (int i = 0; i < nb_modification; i++) { int modification_pos = dis_position(gridcell_->float_gen_); while (modification_pos >= dna_->bp_list_.size()) { modification_pos = dis_position(gridcell_->float_gen_); } dna_->modify_bp(modification_pos,gridcell_); } } Organism* Organism::divide() { Organism* new_org = new Organism(this); return new_org; } Organism::Organism(Organism* organism) { dna_ = new DNA(organism->dna_); for(auto prot : organism->protein_list_map_) { Protein* new_prot = new Protein(prot.second); new_prot->concentration_ = new_prot->concentration_/2; prot.second->concentration_ = prot.second->concentration_/2; } } Organism::~Organism() { for (auto rna : rna_list_) delete rna; delete dna_; rna_produce_protein_.clear(); for (auto prot : protein_list_map_) { delete prot.second; } protein_fitness_list_.clear(); protein_TF_list_.clear(); protein_poison_list_.clear(); protein_antipoison_list_.clear(); protein_list_map_.clear(); for (auto pump : pump_list_) { delete pump; } pump_list_.clear(); for (auto move : move_list_) { delete move; } move_list_.clear(); }
33.99568
148
0.621283
Sn0wFox
b6b5fe4613ca8b0c02dd1317846a4aa778714896
8,263
cxx
C++
Temporary/itkDijkstrasAlgorithm.cxx
KevinScholtes/ANTsX
5462269c0c32e5d65560bae4014c5a05cb02588d
[ "BSD-3-Clause" ]
null
null
null
Temporary/itkDijkstrasAlgorithm.cxx
KevinScholtes/ANTsX
5462269c0c32e5d65560bae4014c5a05cb02588d
[ "BSD-3-Clause" ]
null
null
null
Temporary/itkDijkstrasAlgorithm.cxx
KevinScholtes/ANTsX
5462269c0c32e5d65560bae4014c5a05cb02588d
[ "BSD-3-Clause" ]
1
2019-10-06T07:31:58.000Z
2019-10-06T07:31:58.000Z
/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) =========================================================================*/ #ifndef _itkDijkstrasAlgorithm_cxx_ #define _itkDijkstrasAlgorithm_cxx_ #include "itkDijkstrasAlgorithm.h" namespace itk { template <typename TGraphSearchNode> DijkstrasAlgorithm<TGraphSearchNode>::DijkstrasAlgorithm() { m_Graph = GraphType::New(); m_QS = DijkstrasAlgorithmQueue<TGraphSearchNode>::New(); m_MaxCost = vnl_huge_val(m_MaxCost); // not defined for unsigned char this->m_TotalCost = 0; }; template <typename TGraphSearchNode> void DijkstrasAlgorithm<TGraphSearchNode>::SetGraphSize(GraphSizeType Sz) { for( int i = 0; i < GraphDimension; i++ ) { m_GraphSize[i] = Sz[i]; } } template <typename TGraphSearchNode> void DijkstrasAlgorithm<TGraphSearchNode>::InitializeGraph() { m_GraphRegion.SetSize( m_GraphSize ); m_Graph->SetLargestPossibleRegion( m_GraphRegion ); m_Graph->SetRequestedRegion( m_GraphRegion ); m_Graph->SetBufferedRegion( m_GraphRegion ); m_Graph->Allocate(); GraphIteratorType GraphIterator( m_Graph, m_GraphRegion ); GraphIterator.GoToBegin(); NodeLocationType loc; while( !GraphIterator.IsAtEnd() ) { typename GraphSearchNode<PixelType, CoordRep, GraphDimension>::Pointer G = nullptr; GraphIterator.Set(G); ++GraphIterator; /* m_GraphIndex = GraphIterator.GetIndex(); //std::cout << " allocating " << m_GraphIndex << std::endl; ///GraphSearchNode<PixelType,CoordRep,GraphDimension>::Pointer G= G=TGraphSearchNode::New(); G->SetUnVisited(); G->SetTotalCost(m_MaxCost); for (int i=0; i<GraphDimension; i++) loc[i]=m_GraphIndex[i]; G->SetLocation(loc); G->SetPredecessor(nullptr); m_Graph->SetPixel(m_GraphIndex,G);*/ m_Graph->SetPixel( GraphIterator.GetIndex(), nullptr); // USE IF POINTER IMAGE defines visited } m_SearchFinished = false; } template <typename TGraphSearchNode> void DijkstrasAlgorithm<TGraphSearchNode>::InitializeQueue() { int n = m_QS->m_SourceNodes.size(); GraphIteratorType GraphIterator( m_Graph, m_GraphRegion ); m_GraphSize = m_Graph->GetLargestPossibleRegion().GetSize(); GraphIterator.GoToBegin(); m_GraphIndex = GraphIterator.GetIndex(); NodeLocationType loc; // make sure the graph contains the right pointers for( int i = 0; i < n; i++ ) { typename GraphSearchNode<PixelType, CoordRep, GraphDimension>::Pointer G = m_QS->m_SourceNodes[i]; G->SetPredecessor(G); m_QS->m_Q.push(G); loc = G->GetLocation(); for( int d = 0; d < GraphDimension; d++ ) { m_GraphIndex[d] = (long int)(loc[d] + 0.5); } m_Graph->SetPixel(m_GraphIndex, G); } for( int i = 0; i < m_QS->m_SinkNodes.size(); i++ ) { typename GraphSearchNode<PixelType, CoordRep, GraphDimension>::Pointer G = m_QS->m_SinkNodes[i]; G->SetPredecessor(nullptr); loc = G->GetLocation(); for( int d = 0; d < GraphDimension; d++ ) { m_GraphIndex[d] = (long)loc[d]; } m_Graph->SetPixel(m_GraphIndex, G); } m_SearchFinished = false; if( m_EdgeTemplate.empty() ) { InitializeEdgeTemplate(); } } template <typename TGraphSearchNode> void DijkstrasAlgorithm<TGraphSearchNode>::InitializeEdgeTemplate (vector<unsigned int> UserEdgeTemplate, unsigned int R) { for( int i = 0; i < GraphDimension; i++ ) { m_Radius[i] = R; } m_EdgeTemplate = UserEdgeTemplate; } template <typename TGraphSearchNode> void DijkstrasAlgorithm<TGraphSearchNode>::InitializeEdgeTemplate() { int MaxIndex = 1; for( int i = 0; i < GraphDimension; i++ ) { m_Radius[i] = 1; } for( int i = 0; i < GraphDimension; i++ ) { MaxIndex = MaxIndex * (2 * m_Radius[i] + 1); } MaxIndex = MaxIndex - 1; // int Center = MaxIndex/2; for( unsigned int i = 0; i <= MaxIndex; i++ ) { // if (i != Center) m_EdgeTemplate.insert(m_EdgeTemplate.end(), i); } } /** * Compute the local cost using Manhattan distance. */ template <typename TGraphSearchNode> typename DijkstrasAlgorithm<TGraphSearchNode>:: PixelType DijkstrasAlgorithm<TGraphSearchNode>::LocalCost() { return 1.0; // manhattan distance }; template <typename TGraphSearchNode> bool DijkstrasAlgorithm<TGraphSearchNode>::TerminationCondition() { if( !m_QS->m_SinkNodes.empty() ) { if( m_NeighborNode == m_QS->m_SinkNodes[0] && !m_SearchFinished ) { m_SearchFinished = true; m_NeighborNode->SetPredecessor(m_CurrentNode); } } else { m_SearchFinished = true; } return m_SearchFinished; } template <typename TGraphSearchNode> void DijkstrasAlgorithm<TGraphSearchNode>::SearchEdgeSet() { // std::cout << " SES 0 " << std::endl; GraphNeighborhoodIteratorType GHood(m_Radius, m_Graph, m_Graph->GetRequestedRegion() ); GraphNeighborhoodIndexType GNI; // std::cout << " SES 1 " << std::endl; for( unsigned int i = 0; i < GraphDimension; i++ ) { // std::cout << " SES 2 " << std::endl; GNI[i] = (long)(m_CurrentNode->GetLocation()[i] + 0.5); } // std::cout << " SES 3 " << std::endl; GHood.SetLocation(GNI); for( unsigned int dd = 0; dd < GraphDimension; dd++ ) { if( GNI[dd] < 2 || GNI[dd] > (unsigned long)(m_GraphSize[dd] - 2) ) { return; } } for( unsigned int i = 0; i < m_EdgeTemplate.size(); i++ ) { // std::cout << " SES 4 " << std::endl; // std::cout << " ET " << m_EdgeTemplate[i] << " RAD " << m_Radius << " ind " << // GHood.GetIndex(m_EdgeTemplate[i]) // << std::endl; if( !GHood.GetPixel(m_EdgeTemplate[i]) ) // std::cout << " OK " << std::endl; // /else { // std::cout << " NOT OK " <<std::endl; GraphNeighborhoodIndexType ind = GHood.GetIndex(m_EdgeTemplate[i]); typename TGraphSearchNode::Pointer G = TGraphSearchNode::New(); G->SetUnVisited(); G->SetTotalCost(m_MaxCost); NodeLocationType loc; for( int j = 0; j < GraphDimension; j++ ) { loc[j] = ind[j]; } G->SetLocation(loc); G->SetPredecessor(m_CurrentNode); m_Graph->SetPixel(ind, G); } m_NeighborNode = GHood.GetPixel(m_EdgeTemplate[i]); // std::cout << "DA i " << i << " position " << m_NeighborNode->GetLocation() << endl; this->TerminationCondition(); if( !m_SearchFinished && m_CurrentNode != m_NeighborNode && !m_NeighborNode->GetDelivered() ) { m_NewCost = m_CurrentCost + LocalCost(); CheckNodeStatus(); } } } template <typename TGraphSearchNode> void DijkstrasAlgorithm<TGraphSearchNode>::CheckNodeStatus() // checks a graph neighbor's status { if( !m_NeighborNode->GetVisited() ) { // set the cost and put into the queue m_NeighborNode->SetTotalCost(m_NewCost); m_NeighborNode->SetPredecessor(m_CurrentNode); m_NeighborNode->SetVisited(); m_QS->m_Q.push(m_NeighborNode); } else if( m_NewCost < m_NeighborNode->GetTotalCost() ) { m_NeighborNode->SetTotalCost(m_NewCost); m_NeighborNode->SetPredecessor(m_CurrentNode); m_QS->m_Q.push(m_NeighborNode); } } template <typename TGraphSearchNode> void DijkstrasAlgorithm<TGraphSearchNode>::FindPath() { if( m_QS->m_SourceNodes.empty() ) { std::cout << "ERROR !! DID NOT SET SOURCE!!\n"; return; } while( !m_SearchFinished && !m_QS->m_Q.empty() ) { m_CurrentNode = m_QS->m_Q.top(); m_CurrentCost = m_CurrentNode->GetTotalCost(); m_QS->m_Q.pop(); if( !m_CurrentNode->GetDelivered() ) { m_QS->IncrementTimer(); this->SearchEdgeSet(); this->m_TotalCost += m_CurrentNode->GetTotalCost(); // if ( (m_CurrentNode->GetTimer() % 1.e5 ) == 0) // std::cout << " searched " << m_CurrentNode->GetTimer() << " \n"; } m_CurrentNode->SetDelivered(); } // end of while m_NumberSearched = (unsigned long) m_QS->GetTimer(); std::cout << "Done with find path " << " Q size " << m_QS->m_Q.size() << " num searched " << m_NumberSearched << " \n"; return; } } // end namespace itk #endif
29.510714
102
0.634394
KevinScholtes
b6b9685cab98a2ba3d1d8883d8142265d8a14a78
1,601
hpp
C++
libbio/include/bio/crypto/crypto_Sha256.hpp
biosphere-switch/libbio
7c892ff1e0f47e4612f3b66fdf043216764dfd1b
[ "MIT" ]
null
null
null
libbio/include/bio/crypto/crypto_Sha256.hpp
biosphere-switch/libbio
7c892ff1e0f47e4612f3b66fdf043216764dfd1b
[ "MIT" ]
null
null
null
libbio/include/bio/crypto/crypto_Sha256.hpp
biosphere-switch/libbio
7c892ff1e0f47e4612f3b66fdf043216764dfd1b
[ "MIT" ]
null
null
null
#pragma once #include <bio/mem/mem_Memory.hpp> namespace bio::crypto { // Grabbed from libnx, hardware-accelerated impl class Sha256Context { public: static constexpr u64 HashSize = 0x20; static constexpr u64 HashSize32 = HashSize / sizeof(u32); static constexpr u64 BlockSize = 0x40; static constexpr u32 InitialHash[HashSize32] = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, }; private: u32 intermediate_hash[HashSize32]; u8 block[BlockSize]; u64 bits_consumed; u64 num_buffered; bool finalized; void EnsureFinalized(); void ProcessBlocks(const u8 *buf, u64 num_blocks); public: Sha256Context() : intermediate_hash(), block(), bits_consumed(0), num_buffered(0), finalized(false) { mem::Copy(this->intermediate_hash, InitialHash, HashSize); } void Update(const void *buf, u64 size); inline void GetHash(void *out_dest) { this->EnsureFinalized(); auto dest32 = reinterpret_cast<u32*>(out_dest); for(u32 i = 0; i < HashSize32; i++) { dest32[i] = __builtin_bswap32(this->intermediate_hash[i]); } } }; inline void CalculateSha256(const void *buf, u64 size, void *out) { Sha256Context ctx; ctx.Update(buf, size); ctx.GetHash(out); } }
29.648148
113
0.564022
biosphere-switch
b6baf75f42c6a0f942ec07d8a30159d3dc2b9ad6
935
hpp
C++
libraries/plugins/apis/account_by_key_api/include/delta/plugins/account_by_key_api/account_by_key_api.hpp
yashbhavsar007/Delta-Blockchain
602dd5335d2cd51303e953e4c233c8f099da0b07
[ "MIT" ]
null
null
null
libraries/plugins/apis/account_by_key_api/include/delta/plugins/account_by_key_api/account_by_key_api.hpp
yashbhavsar007/Delta-Blockchain
602dd5335d2cd51303e953e4c233c8f099da0b07
[ "MIT" ]
null
null
null
libraries/plugins/apis/account_by_key_api/include/delta/plugins/account_by_key_api/account_by_key_api.hpp
yashbhavsar007/Delta-Blockchain
602dd5335d2cd51303e953e4c233c8f099da0b07
[ "MIT" ]
null
null
null
#pragma once #include <delta/plugins/json_rpc/utility.hpp> #include <delta/protocol/types.hpp> #include <fc/optional.hpp> #include <fc/variant.hpp> #include <fc/vector.hpp> namespace delta { namespace plugins { namespace account_by_key { namespace detail { class account_by_key_api_impl; } struct get_key_references_args { std::vector< delta::protocol::public_key_type > keys; }; struct get_key_references_return { std::vector< std::vector< delta::protocol::account_name_type > > accounts; }; class account_by_key_api { public: account_by_key_api(); ~account_by_key_api(); DECLARE_API( (get_key_references) ) private: std::unique_ptr< detail::account_by_key_api_impl > my; }; } } } // delta::plugins::account_by_key FC_REFLECT( delta::plugins::account_by_key::get_key_references_args, (keys) ) FC_REFLECT( delta::plugins::account_by_key::get_key_references_return, (accounts) )
20.326087
77
0.735829
yashbhavsar007
b6bc263a733e9f6bbb8635aa9d1df83ca167e057
2,191
cpp
C++
libs/RFType/TypeDatabase.cpp
max-delta/retrofit-public
5447fd6399fd74ffbb75494c103940751000db12
[ "X11" ]
3
2019-10-27T22:32:44.000Z
2020-05-21T04:00:46.000Z
libs/RFType/TypeDatabase.cpp
max-delta/retrofit-public
5447fd6399fd74ffbb75494c103940751000db12
[ "X11" ]
null
null
null
libs/RFType/TypeDatabase.cpp
max-delta/retrofit-public
5447fd6399fd74ffbb75494c103940751000db12
[ "X11" ]
null
null
null
#include "stdafx.h" #include "TypeDatabase.h" #include "core/macros.h" #include "core/meta/LazyInitSingleton.h" #include "core_rftype/Identifier.h" #include "rftl/memory" namespace RF::rftype { /////////////////////////////////////////////////////////////////////////////// bool TypeDatabase::RegisterNewClassByName( char const* name, reflect::ClassInfo const& classInfo ) { RF_ASSERT( name != nullptr ); if( IsValidClassName( name ) == false ) { RF_DBGFAIL(); return false; } size_t nameLen = strnlen( name, 1024 ); math::HashVal64 const hash = math::StableHashBytes( name, nameLen ); bool const registerSuccess = RegisterNewClassByHash( hash, name, classInfo ); return registerSuccess; } reflect::ClassInfo const* TypeDatabase::GetClassInfoByName( char const* name ) const { size_t nameLen = strnlen( name, 1024 ); math::HashVal64 const hash = math::StableHashBytes( name, nameLen ); return GetClassInfoByHash( hash ); } reflect::ClassInfo const* TypeDatabase::GetClassInfoByHash( math::HashVal64 const& hash ) const { ClassInfoByHash::const_iterator const iter = mClassInfoByHash.find( hash ); if( iter == mClassInfoByHash.end() ) { return nullptr; } RF_ASSERT( iter->second.mClassInfo != nullptr ); return iter->second.mClassInfo; } TypeDatabase& TypeDatabase::GetGlobalMutableInstance() { return GetOrCreateGlobalInstance(); } TypeDatabase const& TypeDatabase::GetGlobalInstance() { return GetOrCreateGlobalInstance(); } /////////////////////////////////////////////////////////////////////////////// bool TypeDatabase::RegisterNewClassByHash( math::HashVal64 const& hash, char const* name, reflect::ClassInfo const& classInfo ) { if( mClassInfoByHash.count( hash ) != 0 ) { return false; } StoredClassInfo& newStorage = mClassInfoByHash[hash]; newStorage.mName = name; newStorage.mClassInfo = &classInfo; return true; } bool TypeDatabase::IsValidClassName( char const* name ) { return IsValidIdentifier( name ); } TypeDatabase& TypeDatabase::GetOrCreateGlobalInstance() { return GetOrInitFunctionStaticScopedSingleton<TypeDatabase>(); } /////////////////////////////////////////////////////////////////////////////// }
22.357143
127
0.664537
max-delta
b6bd8fd53c78a5c0df38d175650861eff65c98dc
608
hpp
C++
libs/opencl/include/sge/opencl/context/error_callback_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/opencl/include/sge/opencl/context/error_callback_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/opencl/include/sge/opencl/context/error_callback_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_OPENCL_CONTEXT_ERROR_CALLBACK_TYPE_HPP_INCLUDED #define SGE_OPENCL_CONTEXT_ERROR_CALLBACK_TYPE_HPP_INCLUDED #include <sge/opencl/binary_error_data.hpp> #include <sge/opencl/error_information_string.hpp> namespace sge::opencl::context { using error_callback_type = void(sge::opencl::error_information_string const &, sge::opencl::binary_error_data const &); } #endif
28.952381
96
0.771382
cpreh
b6bfb73351dc46f7693a02b53a3be53b5f550e1b
745
hpp
C++
app/src/main/cpp/common/src/common/Mesh.hpp
pehg/Break_it_all
dab56d82dd4541a710f16b1e6f61ee214059a1a9
[ "MIT" ]
null
null
null
app/src/main/cpp/common/src/common/Mesh.hpp
pehg/Break_it_all
dab56d82dd4541a710f16b1e6f61ee214059a1a9
[ "MIT" ]
null
null
null
app/src/main/cpp/common/src/common/Mesh.hpp
pehg/Break_it_all
dab56d82dd4541a710f16b1e6f61ee214059a1a9
[ "MIT" ]
null
null
null
// // Created by simonppg on 4/22/19. // #ifndef BREAK_IT_ALL_MESH_HPP #define BREAK_IT_ALL_MESH_HPP #include "Camera.hpp" using glm::vec3; #define NUM_ARRAY_ELEMENTS(a) (sizeof(a) / sizeof(*a)) #define INDEX_BUFFER_SIZE(numIndices) ((GLsizeiptr)((numIndices) * (sizeof(GLushort)))) #define VERTEX_BUFFER_SIZE(numIndices) ((GLsizeiptr)((numIndices) * (sizeof(float) * 6))) #define ONE 1 #define TWO 2 class Mesh { public: Mesh(float *pDouble, int i); Mesh(float *vertex, int v_size, short *indices, int i_size); int type; float *vertex; short *indices; int numVertices; int numIndices; unsigned int vbo; // vertex buffer object unsigned int iab; // index array buffer }; #endif //BREAK_IT_ALL_MESH_HPP
22.575758
89
0.702013
pehg
b6c58b4a719ddc165a4c06e1369168ee4029fd34
1,138
cpp
C++
src/db/db_impl.cpp
rickard1117/PidanDB
6955f6913cb404a0f09a5e44c07f36b0729c0a78
[ "MIT" ]
7
2020-08-01T04:09:15.000Z
2021-08-08T17:26:19.000Z
src/db/db_impl.cpp
rickard1117/PidanDB
6955f6913cb404a0f09a5e44c07f36b0729c0a78
[ "MIT" ]
null
null
null
src/db/db_impl.cpp
rickard1117/PidanDB
6955f6913cb404a0f09a5e44c07f36b0729c0a78
[ "MIT" ]
2
2020-09-16T02:29:52.000Z
2020-09-28T10:51:38.000Z
#include "db/db_impl.h" namespace pidan { Status DBImpl::Put(const Slice &key, const Slice &value) { Transaction *txn = txn_manager_.BeginWriteTransaction(); DataHeader *dh = new DataHeader(txn); DataHeader *old_dh = nullptr; auto result = index_.InsertUnique(key, dh, &old_dh); if (!result) { delete dh; if (!old_dh->Put(txn, value)) { txn_manager_.Abort(txn); return Status::FAIL_BY_ACTIVE_TXN; } } else { result = dh->Put(txn, value); assert(result); } txn_manager_.Commit(txn); return Status::SUCCESS; } Status DBImpl::Get(const Slice &key, std::string *val) { Transaction txn = txn_manager_.BeginReadTransaction(); DataHeader *dh = nullptr; if (!index_.Lookup(key, &dh)) { txn_manager_.Abort(&txn); return Status::KEY_NOT_EXIST; } bool not_found; if (!dh->Select(&txn, val, &not_found)) { return Status::FAIL_BY_ACTIVE_TXN; } if (not_found) { return Status::KEY_NOT_EXIST; } return Status::SUCCESS; } Status PidanDB::Open(const std::string &name, PidanDB **dbptr) { *dbptr = new DBImpl(); return Status::SUCCESS; } } // namespace pidan
23.708333
64
0.665202
rickard1117
b6c7c92e3bfa79f0066631365f7853bef96538d9
670
cpp
C++
binary tree/flattenTreeToLinkedList.cpp
Gooner1886/DSA-101
44092e10ad39bebbf7da93e897927106d5a45ae7
[ "MIT" ]
20
2022-01-04T19:36:14.000Z
2022-03-21T15:35:09.000Z
binary tree/flattenTreeToLinkedList.cpp
Gooner1886/DSA-101
44092e10ad39bebbf7da93e897927106d5a45ae7
[ "MIT" ]
null
null
null
binary tree/flattenTreeToLinkedList.cpp
Gooner1886/DSA-101
44092e10ad39bebbf7da93e897927106d5a45ae7
[ "MIT" ]
null
null
null
// Leetcode - 114 - Flatten Binary Tree to Linked List void solve(TreeNode *root, vector<int> &preorder) { root->left = NULL; root->right = NULL; for (int i = 1; i < preorder.size(); i++) { root->right = new TreeNode(preorder[i]); root = root->right; } } void preorderTraversal(TreeNode *root, vector<int> &preorder) { if (!root) return; preorder.push_back(root->val); preorderTraversal(root->left, preorder); preorderTraversal(root->right, preorder); } void flatten(TreeNode *root) { if (!root) return; vector<int> preorder; preorderTraversal(root, preorder); solve(root, preorder); }
23.928571
61
0.623881
Gooner1886
b6c9ac73c37b5204639c27d37f0655122c11a714
8,505
hpp
C++
Vesper/Vesper/BSSRDFs/IrradianceTree.hpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
6
2017-09-14T03:26:49.000Z
2021-09-18T05:40:59.000Z
Vesper/Vesper/BSSRDFs/IrradianceTree.hpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
null
null
null
Vesper/Vesper/BSSRDFs/IrradianceTree.hpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <array> #include <vector> #include <CrispCore/Math/BoundingBox.hpp> #include "Spectrums/Spectrum.hpp" namespace crisp { struct SurfacePoint { SurfacePoint() {} SurfacePoint(const glm::vec3& p, const glm::vec3& n, float a) : p(p) , n(n) , area(a) , rayEpsilon(Ray3::Epsilon) { } glm::vec3 p; glm::vec3 n; float area; float rayEpsilon; }; struct PoissonCheck { PoissonCheck(float maxDist, const glm::vec3& point) : maxDist2(maxDist * maxDist) , failed(false) , p(point) { } bool operator()(const SurfacePoint& point) { glm::vec3 diff = point.p - p; if (glm::dot(diff, diff) < maxDist2) { failed = true; return false; } return true; } float maxDist2; bool failed; glm::vec3 p; }; struct IrradiancePoint { IrradiancePoint() {} IrradiancePoint(const SurfacePoint& surfPt, const Spectrum& spectrum) : p(surfPt.p) , n(surfPt.n) , e(spectrum) , area(surfPt.area) , rayEpsilon(surfPt.rayEpsilon) { } glm::vec3 p; glm::vec3 n; Spectrum e; float area; float rayEpsilon; }; struct IrradianceNode { glm::vec3 p; bool isLeaf; Spectrum e; float sumArea; std::array<std::unique_ptr<IrradianceNode>, 8> children; std::array<IrradiancePoint*, 8> irrPts; IrradianceNode() : isLeaf(true) , sumArea(0.0f) { for (int i = 0; i < 8; i++) { irrPts[i] = nullptr; children[i] = nullptr; } } inline BoundingBox3 getChildBound(int child, const BoundingBox3& bounds, const glm::vec3& mid) { BoundingBox3 bound; bound.min.x = (child & 4) ? mid.x : bounds.min.x; bound.min.y = (child & 2) ? mid.y : bounds.min.y; bound.min.z = (child & 1) ? mid.z : bounds.min.z; bound.max.x = (child & 4) ? bounds.max.x : mid.x; bound.max.y = (child & 2) ? bounds.max.y : mid.y; bound.max.z = (child & 1) ? bounds.max.z : mid.z; return bound; } void insert(const BoundingBox3& nodeBounds, IrradiancePoint* point) { glm::vec3 mid = nodeBounds.getCenter(); if (isLeaf) { for (int i = 0; i < 8; i++) { if (!irrPts[i]) { irrPts[i] = point; return; } } isLeaf = false; IrradiancePoint* localPts[8]; for (int i = 0; i < 8; i++) { localPts[i] = irrPts[i]; children[i] = nullptr; } for (int i = 0; i < 8; i++) { IrradiancePoint* currPt = localPts[i]; int child = (currPt->p.x > mid.x ? 4 : 0) + (currPt->p.y > mid.y ? 2 : 0) + (currPt->p.z > mid.z ? 1 : 0); if (children[child] == nullptr) children[child] = std::make_unique<IrradianceNode>(); BoundingBox3 childBounds = getChildBound(child, nodeBounds, mid); children[child]->insert(childBounds, currPt); } int child = (point->p.x > mid.x ? 4 : 0) + (point->p.y > mid.y ? 2 : 0) + (point->p.z > mid.z ? 1 : 0); if (children[child] == nullptr) children[child] = std::make_unique<IrradianceNode>(); BoundingBox3 childBounds = getChildBound(child, nodeBounds, mid); children[child]->insert(childBounds, point); } } Spectrum getLeafIrradiance() { Spectrum sum(0.0f); if (isLeaf) { for (int i = 0; i < irrPts.size(); i++) { if (!irrPts[i]) break; sum += irrPts[i]->e; } } else { for (int i = 0; i < children.size(); i++) { if (!children[i]) continue; sum += children[i]->getLeafIrradiance(); } } return sum; } Spectrum getTotalIrradiance() { Spectrum sum(0.0f); if (isLeaf) { for (int i = 0; i < irrPts.size(); i++) { if (!irrPts[i]) break; sum += irrPts[i]->e; } } else { for (int i = 0; i < children.size(); i++) { if (!children[i]) continue; sum += children[i]->getLeafIrradiance(); } sum += e; } return sum; } void initHierarchy() { if (isLeaf) { float weightSum = 0.0f; size_t i; for (i = 0; i < 8; i++) { if (!irrPts[i]) break; float weight = irrPts[i]->e.getLuminance(); e += irrPts[i]->e; p += weight * irrPts[i]->p; weightSum += weight; sumArea += irrPts[i]->area; } if (weightSum > 0.0f) p /= weightSum; if (i > 0) e /= static_cast<float>(i); } else { float weightSum = 0.0f; size_t numChildren = 0; for (uint32_t i = 0; i < 8; i++) { if (!children[i]) continue; ++numChildren; children[i]->initHierarchy(); float weight = children[i]->e.getLuminance(); e += children[i]->e; p += weight * children[i]->p; weightSum += weight; sumArea += children[i]->sumArea; } if (weightSum > 0.0f) p /= weightSum; if (numChildren > 0) e /= static_cast<float>(numChildren); } } template <typename Func> Spectrum Mo(const BoundingBox3& nodeBounds, const glm::vec3& pt, Func& func, float maxError) { glm::vec3 diff = pt - p; float sqrDist = glm::dot(diff, diff); float distanceWeight = sumArea / sqrDist; if (distanceWeight < maxError && !nodeBounds.contains(pt)) return func(sqrDist) * e * sumArea; Spectrum mo = 0.0f; if (isLeaf) { for (int i = 0; i < 8; i++) { if (!irrPts[i]) break; glm::vec3 diffC = irrPts[i]->p - pt; float cSqrDist = glm::dot(diffC, diffC); mo += func(cSqrDist) * irrPts[i]->e * irrPts[i]->area; } } else { glm::vec3 mid = nodeBounds.getCenter(); for (int child = 0; child < 8; child++) { if (!children[child]) continue; BoundingBox3 childBounds = getChildBound(child, nodeBounds, mid); mo += children[child]->Mo(childBounds, pt, func, maxError); } } return mo; } }; struct IrradianceTree { std::unique_ptr<IrradianceNode> root; BoundingBox3 boundingBox; }; }
28.444816
102
0.388595
FallenShard
b6d63ff87ed03714a1fa7cf95cc74d0f65869208
3,577
cpp
C++
android-30/android/widget/SimpleAdapter.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-30/android/widget/SimpleAdapter.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/widget/SimpleAdapter.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../JIntArray.hpp" #include "../../JArray.hpp" #include "../content/Context.hpp" #include "../content/res/Resources_Theme.hpp" #include "../view/View.hpp" #include "../view/ViewGroup.hpp" #include "./Filter.hpp" #include "./ImageView.hpp" #include "./TextView.hpp" #include "../../JObject.hpp" #include "../../JString.hpp" #include "./SimpleAdapter.hpp" namespace android::widget { // Fields // QJniObject forward SimpleAdapter::SimpleAdapter(QJniObject obj) : android::widget::BaseAdapter(obj) {} // Constructors SimpleAdapter::SimpleAdapter(android::content::Context arg0, JObject arg1, jint arg2, JArray arg3, JIntArray arg4) : android::widget::BaseAdapter( "android.widget.SimpleAdapter", "(Landroid/content/Context;Ljava/util/List;I[Ljava/lang/String;[I)V", arg0.object(), arg1.object(), arg2, arg3.object<jarray>(), arg4.object<jintArray>() ) {} // Methods jint SimpleAdapter::getCount() const { return callMethod<jint>( "getCount", "()I" ); } android::view::View SimpleAdapter::getDropDownView(jint arg0, android::view::View arg1, android::view::ViewGroup arg2) const { return callObjectMethod( "getDropDownView", "(ILandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;", arg0, arg1.object(), arg2.object() ); } android::content::res::Resources_Theme SimpleAdapter::getDropDownViewTheme() const { return callObjectMethod( "getDropDownViewTheme", "()Landroid/content/res/Resources$Theme;" ); } android::widget::Filter SimpleAdapter::getFilter() const { return callObjectMethod( "getFilter", "()Landroid/widget/Filter;" ); } JObject SimpleAdapter::getItem(jint arg0) const { return callObjectMethod( "getItem", "(I)Ljava/lang/Object;", arg0 ); } jlong SimpleAdapter::getItemId(jint arg0) const { return callMethod<jlong>( "getItemId", "(I)J", arg0 ); } android::view::View SimpleAdapter::getView(jint arg0, android::view::View arg1, android::view::ViewGroup arg2) const { return callObjectMethod( "getView", "(ILandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;", arg0, arg1.object(), arg2.object() ); } JObject SimpleAdapter::getViewBinder() const { return callObjectMethod( "getViewBinder", "()Landroid/widget/SimpleAdapter$ViewBinder;" ); } void SimpleAdapter::setDropDownViewResource(jint arg0) const { callMethod<void>( "setDropDownViewResource", "(I)V", arg0 ); } void SimpleAdapter::setDropDownViewTheme(android::content::res::Resources_Theme arg0) const { callMethod<void>( "setDropDownViewTheme", "(Landroid/content/res/Resources$Theme;)V", arg0.object() ); } void SimpleAdapter::setViewBinder(JObject arg0) const { callMethod<void>( "setViewBinder", "(Landroid/widget/SimpleAdapter$ViewBinder;)V", arg0.object() ); } void SimpleAdapter::setViewImage(android::widget::ImageView arg0, jint arg1) const { callMethod<void>( "setViewImage", "(Landroid/widget/ImageView;I)V", arg0.object(), arg1 ); } void SimpleAdapter::setViewImage(android::widget::ImageView arg0, JString arg1) const { callMethod<void>( "setViewImage", "(Landroid/widget/ImageView;Ljava/lang/String;)V", arg0.object(), arg1.object<jstring>() ); } void SimpleAdapter::setViewText(android::widget::TextView arg0, JString arg1) const { callMethod<void>( "setViewText", "(Landroid/widget/TextView;Ljava/lang/String;)V", arg0.object(), arg1.object<jstring>() ); } } // namespace android::widget
23.688742
125
0.689405
YJBeetle
b6d962121987bcab856a0318aa250dcd1a68fb2d
1,552
cpp
C++
src/lib/classification/poset_classification/extension.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
15
2016-10-27T15:18:28.000Z
2022-02-09T11:13:07.000Z
src/lib/classification/poset_classification/extension.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
4
2019-12-09T11:49:11.000Z
2020-07-30T17:34:45.000Z
src/lib/classification/poset_classification/extension.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
15
2016-06-10T20:05:30.000Z
2020-12-18T04:59:19.000Z
// extension.cpp // // Anton Betten // Dec 19, 2011 #include "foundations/foundations.h" #include "group_actions/group_actions.h" #include "classification/classification.h" using namespace std; namespace orbiter { namespace classification { extension::extension() { pt = -1; orbit_len = 0; type = EXTENSION_TYPE_UNPROCESSED; data = 0; data1 = 0; data2 = 0; } extension::~extension() { } int extension::get_pt() { return pt; } void extension::set_pt(int pt) { extension::pt = pt; } int extension::get_type() { return type; } void extension::set_type(int type) { extension::type = type; } int extension::get_orbit_len() { return orbit_len; } void extension::set_orbit_len(int orbit_len) { extension::orbit_len = orbit_len; } int extension::get_data() { return data; } void extension::set_data(int data) { extension::data = data; } int extension::get_data1() { return data1; } void extension::set_data1(int data1) { extension::data1 = data1; } int extension::get_data2() { return data2; } void extension::set_data2(int data2) { extension::data2 = data2; } void print_extension_type(ostream &ost, int t) { if (t == EXTENSION_TYPE_UNPROCESSED) { ost << " unprocessed"; } else if (t == EXTENSION_TYPE_EXTENSION) { ost << " extension"; } else if (t == EXTENSION_TYPE_FUSION) { ost << " fusion"; } else if (t == EXTENSION_TYPE_PROCESSING) { ost << " processing"; } else if (t == EXTENSION_TYPE_NOT_CANONICAL) { ost << " not canonical"; } else { ost << "type=" << t; } } }}
13.37931
46
0.664948
abetten
b6e5b96b3b9a80bf364e304c2adacf3ba49033fd
554
hpp
C++
chratos/chratos_node/daemon.hpp
chratos-system/chratos
caf1b608a21ccc7b13726a64497036ab53f837b3
[ "BSD-2-Clause" ]
2
2018-09-10T16:28:16.000Z
2020-02-13T17:44:43.000Z
chratos/chratos_node/daemon.hpp
chratos-system/chratos
caf1b608a21ccc7b13726a64497036ab53f837b3
[ "BSD-2-Clause" ]
null
null
null
chratos/chratos_node/daemon.hpp
chratos-system/chratos
caf1b608a21ccc7b13726a64497036ab53f837b3
[ "BSD-2-Clause" ]
2
2018-08-27T13:00:56.000Z
2018-10-16T21:54:13.000Z
#include <chratos/node/node.hpp> #include <chratos/node/rpc.hpp> namespace chratos_daemon { class daemon { public: void run (boost::filesystem::path const &); }; class daemon_config { public: daemon_config (boost::filesystem::path const &); bool deserialize_json (bool &, boost::property_tree::ptree &); void serialize_json (boost::property_tree::ptree &); bool upgrade_json (unsigned, boost::property_tree::ptree &); bool rpc_enable; chratos::rpc_config rpc; chratos::node_config node; bool opencl_enable; chratos::opencl_config opencl; }; }
22.16
63
0.749097
chratos-system
b6eb39ef45bc5c2f56339e4c9849eee6c477b6e3
1,711
cxx
C++
src/converter/fix_helper.cxx
abdelkaderamar/fix2xml
fa781b747a8e40ed4c2d3dee8294fb51654f7428
[ "MIT" ]
1
2019-09-26T12:08:19.000Z
2019-09-26T12:08:19.000Z
src/converter/fix_helper.cxx
abdelkaderamar/fix2xml
fa781b747a8e40ed4c2d3dee8294fb51654f7428
[ "MIT" ]
null
null
null
src/converter/fix_helper.cxx
abdelkaderamar/fix2xml
fa781b747a8e40ed4c2d3dee8294fb51654f7428
[ "MIT" ]
1
2020-12-11T04:11:44.000Z
2020-12-11T04:11:44.000Z
#include "fix_helper.hxx" #include <quickfix/FixFieldNumbers.h> #include <algorithm> #include <functional> #include <vector> namespace fix2xml { using namespace std; //----------------------------------------------------------------------------- void msg_to_list(const FIX::Message &fix_msg, const FIX::DataDictionary &fix_dict, multiset<string> &fields_set, list<multiset<string>> &ls) { ls.push_back(fieldmap_to_list(fix_msg.getHeader(), fix_dict, ls)); fields_set = fieldmap_to_list(fix_msg, fix_dict, ls); } //----------------------------------------------------------------------------- multiset<string> fieldmap_to_list(const FIX::FieldMap &fix_msg, const FIX::DataDictionary &fix_dict, list<multiset<string>> &ls) { // Insert all the fields that are not NumInGroup in the multiset fields_set multiset<string> fields_set; for (auto it = fix_msg.begin(); it != fix_msg.end(); ++it) { if (it->getField() == FIX::FIELD::MsgType) continue; FIX::TYPE::Type fix_type; if (fix_dict.getFieldType(it->getField(), fix_type) && (fix_type == FIX::TYPE::NumInGroup)) continue; fields_set.insert(it->getString()); } // For each group insert its fields (as multiset) in the list ls for (auto it = fix_msg.g_begin(); it != fix_msg.g_end(); ++it) { const vector<FIX::FieldMap *> &groups = it->second; for (size_t i = 0; i < groups.size(); ++i) { ls.push_back(fieldmap_to_list(*groups[i], fix_dict, ls)); } } return fields_set; } //----------------------------------------------------------------------------- } // end namespace fix2xml
34.22
79
0.548802
abdelkaderamar
b6f2464ac1f220f4d92948ee29510bccaf768fc8
2,030
cpp
C++
DS/DS/graph/bellman_ford.cpp
puneet222/Data-Structures
c5c460739c7423cce53685c5557c97c70ca1d171
[ "Apache-2.0" ]
null
null
null
DS/DS/graph/bellman_ford.cpp
puneet222/Data-Structures
c5c460739c7423cce53685c5557c97c70ca1d171
[ "Apache-2.0" ]
null
null
null
DS/DS/graph/bellman_ford.cpp
puneet222/Data-Structures
c5c460739c7423cce53685c5557c97c70ca1d171
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<stdio.h> #include<queue> #include<malloc.h> #include<limits.h> using namespace std ; struct graph{ int v ; int e ; int **wgh ; } ; struct graph *weightMatrix(int vertices , int edges) { struct graph *g = new graph ; g -> v = vertices ; g -> e = edges ; g -> wgh = (int **)malloc(sizeof(int *)*(g -> v)) ; for (int i = 0; i < g -> v; ++i) { g -> wgh[i] = (int *)malloc(sizeof(int)*(g -> v)) ; } int u , v ; for(u = 0 ; u < g -> v ; u++) { for(v = 0 ; v < g -> v ; v++) { g -> wgh[u][v] = 0 ; } } for (int i = 0; i < g -> e; ++i) { printf("Enter the vertices u and v such that there is an edge u -> v is there : "); cin >> u >> v ; int w ; cout << "\nEnter the weight of the edge : " ; cin >> w ; g -> wgh[u][v] = w ; } return g ; } void printGraph(struct graph *g) { int u , v ; for(u = 0 ; u < g -> v ; u++) { for(v = 0 ; v < g -> v ; v++) { printf(" %d ", g -> wgh[u][v]); } printf("\n"); } } void shortestpath(struct graph *g , int * distance , int *path , int s) { queue <int> Q ; int qarr[g -> v] ; for (int i = 0; i < g -> v; ++i) { distance[i] = INT_MAX ; qarr[i] = 0 ; } distance[s] = 0 ; Q.push(s) ; qarr[s] = 1 ; while(!Q.empty()) { int v = Q.front() ; Q.pop() ; qarr[v] = 0 ; for (int i = 0; i < g -> v; ++i) { if(g -> wgh[v][i]) { int dnew = distance[v] + g -> wgh[v][i] ; if(distance[i] > dnew) { distance[i] = dnew ; path[i] = v ; if(qarr[i] == 0) { Q.push(i) ; qarr[i] == 1 ; } } } } } } int main() { int v , e ; printf("Enter number of vertices and edges in the graph : "); scanf("%d%d" , &v , &e) ; struct graph *g = weightMatrix(v , e) ; printGraph(g); int distance[g -> v] ; int path[g -> v] ; int s ; printf("Enter the source from where you want to find the shortest path to all other nodes : "); cin >> s ; shortestpath(g , distance , path , s) ; for (int i = 0; i < g -> v; ++i) { printf(" %d ", distance[i]); } }
17.964602
96
0.484236
puneet222
b6f7f2f06130d095c5b2a916d993ecd6bd4f62f6
833
cpp
C++
机试/动态规划/leetcode123.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
机试/动态规划/leetcode123.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
机试/动态规划/leetcode123.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
class Solution { public: int maxProfit(vector<int>& prices) { if(prices.size() == 0){ return 0; } int len = prices.size(); vector<vector<int>> dp(len, vector<int>(5)); dp[0][0] = 0; dp[0][1] = -prices[0]; dp[0][2] = 0; dp[0][3] = -prices[0]; dp[0][4] = 0; for(int i = 1; i < prices.size(); i++){ dp[i][0] = dp[i-1][0]; //初始状态 dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i]); //第一次买入 dp[i][2] = max(dp[i-1][2], dp[i-1][1] + prices[i]); //第一次卖出 dp[i][3] = max(dp[i-1][3], dp[i-1][2] - prices[i]);//第二次买入 dp[i][4] = max(dp[i-1][4], dp[i-1][3] + prices[i]);//第二次卖出 } return max(max( max(dp[len-1][0], dp[len-1][1]), max(dp[len-1][2], dp[len-1][3]) ), dp[len-1][4]); } };
36.217391
105
0.421369
codehuanglei
b6fb19c28ec6bab8291643f67434843fb09d55bf
3,231
cpp
C++
docs/tests/graph.cpp
nyorain/tokonoma
b3a4264ef4f9f40487c2f3280812bf7513b914bb
[ "MIT" ]
23
2019-07-11T14:47:39.000Z
2021-12-24T09:56:24.000Z
docs/tests/graph.cpp
nyorain/tokonoma
b3a4264ef4f9f40487c2f3280812bf7513b914bb
[ "MIT" ]
null
null
null
docs/tests/graph.cpp
nyorain/tokonoma
b3a4264ef4f9f40487c2f3280812bf7513b914bb
[ "MIT" ]
4
2021-04-06T18:20:43.000Z
2022-01-15T09:20:45.000Z
#include "bugged.hpp" #include <deferred/graph.hpp> TEST(basic) { FrameGraph graph; auto& pass1 = graph.addPass(); vk::Image img1; vk::Image img2; auto& out1 = pass1.addOut(syncScopeFlex, img1); auto& out2 = pass1.addOut(syncScopeFlex, img2); auto scope2 = SyncScope { vk::PipelineStageBits::computeShader, vk::ImageLayout::shaderReadOnlyOptimal, vk::AccessBits::shaderRead, }; auto& pass2 = graph.addPass(); pass2.addIn(out1, scope2); auto scope3 = SyncScope { vk::PipelineStageBits::fragmentShader, vk::ImageLayout::shaderReadOnlyOptimal, vk::AccessBits::shaderRead, }; auto& pass3 = graph.addPass(); pass3.addIn(out1, scope3); pass3.addIn(out2, scope3); graph.compute(); // test auto& order = graph.order(); EXPECT(graph.check(), true); EXPECT(order.size(), 3u); EXPECT(order[0].pass, &pass1); EXPECT(order[1].pass, &pass2); EXPECT(order[2].pass, &pass3); EXPECT(order[0].barriers.size(), 0u); EXPECT(order[1].barriers.size(), 0u); EXPECT(order[2].barriers.size(), 0u); EXPECT(graph.check(), true); } TEST(outOfOrder) { FrameGraph graph; vk::Image img1; vk::Image img2; auto& pass1 = graph.addPass(); auto& pass3 = graph.addPass(); auto& pass2 = graph.addPass(); auto scope2 = SyncScope { vk::PipelineStageBits::computeShader, vk::ImageLayout::general, vk::AccessBits::shaderRead | vk::AccessBits::shaderWrite }; auto scope3 = SyncScope { vk::PipelineStageBits::fragmentShader, vk::ImageLayout::shaderReadOnlyOptimal, vk::AccessBits::shaderRead, }; auto& out1 = pass1.addOut(syncScopeFlex, img1); auto& out2 = pass1.addOut(syncScopeFlex, img2); pass3.addIn(out2, scope3); auto& out3 = pass2.addInOut(out1, scope2); pass3.addIn(out3, scope3); graph.compute(); // test EXPECT(graph.check(), true); auto& order = graph.order(); EXPECT(order.size(), 3u); EXPECT(order[0].pass, &pass1); EXPECT(order[1].pass, &pass2); EXPECT(order[2].pass, &pass3); EXPECT(order[0].barriers.size(), 0u); EXPECT(order[1].barriers.size(), 0u); EXPECT(order[2].barriers.size(), 1u); auto& b = order[2].barriers[0]; EXPECT(b.src, scope2); EXPECT(b.dst, scope3); EXPECT(b.target, &out3); EXPECT(graph.check(), true); } TEST(cycle) { FrameGraph graph; vk::Image img1; auto& pass = graph.addPass(); auto& out = pass.addOut(syncScopeFlex, img1); pass.addIn(out, syncScopeFlex); EXPECT(graph.check(), false); } TEST(cycle2) { FrameGraph graph; vk::Image img1; vk::Image img2; auto& pass1 = graph.addPass(); auto& pass2 = graph.addPass(); auto& out1 = pass1.addOut(syncScopeFlex, img1); pass2.addIn(out1, syncScopeFlex); auto& out2 = pass2.addOut(syncScopeFlex, img2); pass1.addIn(out2, syncScopeFlex); EXPECT(graph.check(), false); } TEST(badDep) { FrameGraph graph; vk::Image img1; auto& pass1 = graph.addPass(); auto& out1 = pass1.addOut(syncScopeFlex, img1); auto scope2 = SyncScope { vk::PipelineStageBits::computeShader, vk::ImageLayout::general, vk::AccessBits::shaderRead | vk::AccessBits::shaderWrite }; auto& pass2 = graph.addPass(); auto& out2 = pass2.addInOut(out1, scope2); auto& pass3 = graph.addPass(); pass3.addIn(out1, syncScopeFlex); pass3.addIn(out2, syncScopeFlex); EXPECT(graph.check(), false); }
23.078571
58
0.692974
nyorain
8e088785a57c9cdd56c5d1336d4b561c74e6883d
5,064
cxx
C++
TOF/TOFbase/AliTOFRawMap.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
TOF/TOFbase/AliTOFRawMap.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
TOF/TOFbase/AliTOFRawMap.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ ///////////////////////////////////////////////////////////////////////// // // // AliTOFRawMap class // // // // It enables fast check if the TDC channel was already engaged // // for a measurement. // // The index of a AliTOFrawData is saved in the each rawdatamap "cell" // // (there is an offset +1, because the index can be zero and // // zero means empty cell. // // // ///////////////////////////////////////////////////////////////////////// #include "TClonesArray.h" #include "AliLog.h" #include "AliTOFGeometry.h" #include "AliTOFRawMap.h" ClassImp(AliTOFRawMap) AliTOFRawMap::AliTOFRawMap(): TObject(), fNtrm(-1), fNtrmChain(-1), fNtdc(-1), fNtdcChannel(-1), fRawData(0x0), fMaxIndex(-1), fRawMap(0x0) { // // Default ctor // } //////////////////////////////////////////////////////////////////////// AliTOFRawMap::AliTOFRawMap(TClonesArray *dig)://, AliTOFGeometry *tofGeom: TObject(), fNtrm(AliTOFGeometry::NTRM()+2), fNtrmChain(AliTOFGeometry::NChain()), fNtdc(AliTOFGeometry::NTdc()), fNtdcChannel(AliTOFGeometry::NCh()), fRawData(dig), fMaxIndex(-1), fRawMap(0x0) { // // ctor // // of course, these constants must not be hardwired // change later fMaxIndex = fNtrm*fNtrmChain*fNtdc*fNtdcChannel; fRawMap = new Int_t[fMaxIndex]; Clear(); } //////////////////////////////////////////////////////////////////////// AliTOFRawMap::~AliTOFRawMap() { // // Destructor // if (fRawMap) delete[] fRawMap; } //////////////////////////////////////////////////////////////////////// void AliTOFRawMap::Clear(const char *) { // // Clear hitmap // memset(fRawMap,0,sizeof(int)*fMaxIndex); } //////////////////////////////////////////////////////////////////////// Int_t AliTOFRawMap::CheckedIndex(const Int_t * const slot) const { // // Return checked indices for vol // Int_t index = slot[0]*fNtrmChain*fNtdc*fNtdcChannel + // TRM slot[1]*fNtdc*fNtdcChannel + // TRM chain slot[2]*fNtdcChannel + // TDC slot[3]; // TDC channel if (index >= fMaxIndex) { AliError("CheckedIndex - input outside bounds"); return -1; } else { return index; } } //////////////////////////////////////////////////////////////////////// void AliTOFRawMap::SetHit(Int_t *slot, Int_t idigit) { // // Assign digit to pad vol // // 0 means empty pad, we need to shift indeces by 1 fRawMap[CheckedIndex(slot)]=idigit+1; } //////////////////////////////////////////////////////////////////////// void AliTOFRawMap::SetHit(Int_t *slot) { // // Assign last digit to channel slot // // 0 means empty pad, we need to shift indeces by 1 fRawMap[CheckedIndex(slot)]=fRawData->GetLast()+1; } //////////////////////////////////////////////////////////////////////// Int_t AliTOFRawMap::GetHitIndex(Int_t *slot) const { // // Get contents of channel slot // // 0 means empty pad, we need to shift indeces by 1 return fRawMap[CheckedIndex(slot)]-1; } //////////////////////////////////////////////////////////////////////// TObject* AliTOFRawMap::GetHit(Int_t *slot) const { // // Get pointer to object at alot // return 0 if vol out of bounds Int_t index = GetHitIndex(slot); return (index <0) ? 0 : fRawData->UncheckedAt(index); } //////////////////////////////////////////////////////////////////////// FlagType AliTOFRawMap::TestHit(Int_t *slot) const { // // Check if hit cell is empty, used or unused // Int_t inf = fRawMap[CheckedIndex(slot)]; if (inf > 0) { return kUsed; } else if (inf == 0) { return kEmpty; } else { return kUnused; } }
28.772727
76
0.463073
AllaMaevskaya
8e09c3050af11576e808b35c4254aa250b22992a
3,437
cpp
C++
Trees/BinaryTree/foldablebinarytree/foldablebinarytree.cpp
UltraProton/Placement-Prepration
cc70f174c4410c254ce0469737a884fffdc81164
[ "MIT" ]
null
null
null
Trees/BinaryTree/foldablebinarytree/foldablebinarytree.cpp
UltraProton/Placement-Prepration
cc70f174c4410c254ce0469737a884fffdc81164
[ "MIT" ]
3
2020-05-08T18:02:51.000Z
2020-05-09T08:37:35.000Z
Trees/BinaryTree/foldablebinarytree/foldablebinarytree.cpp
UltraProton/PlacementPrep
cc70f174c4410c254ce0469737a884fffdc81164
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; /* You would want to remove below 3 lines if your compiler supports bool, true and false */ #define bool int #define true 1 #define false 0 /* A binary tree node has data, pointer to left child and a pointer to right child */ struct node { int data; struct node* left; struct node* right; node(int x){ data = x; left = right = NULL; } }; /* converts a tree to its mrror image */ void mirror(struct node* node); /* returns true if structure of two trees a and b is same Only structure is considered for comparison, not data! */ bool isStructSame(struct node *a, struct node *b); /* Returns true if the given tree is foldable */ bool isFoldable(struct node *root); /* UTILITY FUNCTIONS */ /* Change a tree so that the roles of the left and right pointers are swapped at every node. See http://www.geeksforgeeks.org/?p=662 for details */ void mirror(struct node* node) { if (node==NULL) return; else { struct node* temp; /* do the subtrees */ mirror(node->left); mirror(node->right); /* swap the pointers in this node */ temp = node->left; node->left = node->right; node->right = temp; } } void insert(struct node *root,int n1,int n2,char lr) { if(root==NULL) return; if(root->data==n1) { switch(lr) { case 'L': root->left=new node(n2); break; case 'R': root->right=new node(n2); break; } } else { insert(root->left,n1,n2,lr); insert(root->right,n1,n2,lr); } } /* Driver program to test mirror() */ int main(void) { /* The constructed binary tree is 1 / \ 2 3 \ / 4 5 */ int t,k; cin>>t; while(t--) { int n; cin>>n; struct node *root=NULL; while(n--) { char lr; int n1,n2; cin>>n1>>n2; cin>>lr; if(root==NULL) { root=new node(n1); switch(lr){ case 'L': root->left=new node(n2); break; case 'R': root->right=new node(n2); break; } } else { insert(root,n1,n2,lr); } } if(isFoldable(root) == 1) { cout<<"Yes"<<endl; } else { cout<<"No"<<endl; } getchar(); } return 0; } /*This is a function problem.You only need to complete the function given below*/ /* Returns true if the given tree is foldable */ /* A binary tree node has data, pointer to left child and a pointer to right child */ bool is_structurally_symmetric(struct node *a ,struct node *b){ if(!a && !b){ return true; } if(!a || !b){ return false; } bool l_ans= is_structurally_symmetric(a->left,b->right); bool r_ans= is_structurally_symmetric(a->right, b->left); if(l_ans && r_ans){ return true; } else{ return false; } } bool isFoldable(struct node *root){ // if(root){ // bool x= is_structurally_symmetric(root->left, root->right); // bool l_ans= isFoldable(root->left); // bool r_ans= isFoldable(root->right); // if(l_ans && r_ans){ // return true; // } // else{ // return false; // } // } // return false; bool ans= is_structurally_symmetric(root->left, root->right); return ans; }
21.347826
81
0.551644
UltraProton
8e0a7e06d8dc19dff9e3ddc30d095372b9ce0452
26
cpp
C++
tests/environment.cpp
TheQuantumPhysicist/HttpRpcRelay
810d9ed8907b4c769faa432ba7f829445b8d6f9f
[ "MIT" ]
null
null
null
tests/environment.cpp
TheQuantumPhysicist/HttpRpcRelay
810d9ed8907b4c769faa432ba7f829445b8d6f9f
[ "MIT" ]
null
null
null
tests/environment.cpp
TheQuantumPhysicist/HttpRpcRelay
810d9ed8907b4c769faa432ba7f829445b8d6f9f
[ "MIT" ]
null
null
null
#include "environment.h"
13
25
0.730769
TheQuantumPhysicist
8e0b9590dd090921dfd51bf8831426402488f77c
1,115
hpp
C++
src/volt/gpu/d3d12/d3d12.hpp
voltengine/volt
fbefe2e0a8e461b6130ffe926870c4848bd6e7d1
[ "MIT" ]
null
null
null
src/volt/gpu/d3d12/d3d12.hpp
voltengine/volt
fbefe2e0a8e461b6130ffe926870c4848bd6e7d1
[ "MIT" ]
null
null
null
src/volt/gpu/d3d12/d3d12.hpp
voltengine/volt
fbefe2e0a8e461b6130ffe926870c4848bd6e7d1
[ "MIT" ]
null
null
null
#pragma once #include <volt/gpu/enums.hpp> namespace volt::gpu::d3d12 { extern std::unordered_map<HRESULT, std::string> result_messages; extern std::unordered_map<command_types, D3D12_COMMAND_LIST_TYPE> command_list_types; template<command_types T> constexpr D3D12_COMMAND_LIST_TYPE command_list_type; template<> constexpr D3D12_COMMAND_LIST_TYPE command_list_type<command_type::rasterization> = D3D12_COMMAND_LIST_TYPE_DIRECT; template<> constexpr D3D12_COMMAND_LIST_TYPE command_list_type<command_type::compute> = D3D12_COMMAND_LIST_TYPE_COMPUTE; template<> constexpr D3D12_COMMAND_LIST_TYPE command_list_type<command_type::copy> = D3D12_COMMAND_LIST_TYPE_COPY; extern std::unordered_map<memory_type, D3D12_HEAP_TYPE> heap_types; } #define VOLT_D3D12_CHECK(expression, message)\ {\ ::HRESULT result = expression;\ VOLT_ASSERT(result == S_OK, message + ('\n' + ::volt::gpu::d3d12::result_messages[result]))\ } #ifdef VOLT_GPU_DEBUG #define VOLT_D3D12_DEBUG_CHECK(expression, message) VOLT_D3D12_CHECK(expression, message) #else #define VOLT_D3D12_DEBUG_CHECK(expression, message) expression; #endif
30.135135
114
0.821525
voltengine
8e0f910636ef878151394c403e6a3de3879d1de8
401
cpp
C++
exemplos/5_Repeticao/soma-ate-0.cpp
danielgs83/cpe-unb
f958d2a4899a8d4d5c1465637d1d1b10610661e4
[ "CC0-1.0" ]
1
2022-02-04T17:16:50.000Z
2022-02-04T17:16:50.000Z
exemplos/5_Repeticao/soma-ate-0.cpp
danielgs83/cpe-unb
f958d2a4899a8d4d5c1465637d1d1b10610661e4
[ "CC0-1.0" ]
null
null
null
exemplos/5_Repeticao/soma-ate-0.cpp
danielgs83/cpe-unb
f958d2a4899a8d4d5c1465637d1d1b10610661e4
[ "CC0-1.0" ]
null
null
null
#include <iostream> using namespace std; int main() { int soma, parcela; soma = 0; cout << "numero a ser somado (0 para sair): "; cin >> parcela; //leitura do primeiro numero while (parcela != 0) { soma += parcela; //acumula cout << "numero a ser somado (0 para sair): "; cin >> parcela; //leitura do proximo numero } cout << "Soma: " << soma << endl; return 0; }
17.434783
50
0.586035
danielgs83
8e11f514fbf9d3a021bc436e68abee51dd29ae11
3,955
cpp
C++
tests/TestWord.cpp
SergioRosello/OSO
bbd3c6a95b1c2388732babc6a540c07034cce026
[ "MIT" ]
1
2019-10-14T07:25:32.000Z
2019-10-14T07:25:32.000Z
tests/TestWord.cpp
SergioRosello/OSO
bbd3c6a95b1c2388732babc6a540c07034cce026
[ "MIT" ]
null
null
null
tests/TestWord.cpp
SergioRosello/OSO
bbd3c6a95b1c2388732babc6a540c07034cce026
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "../include/Selection.h" namespace OSO { // The fixture for testing class Foo. class WordTest : public ::testing::Test { protected: // You can remove any or all of the following functions if its body // is empty. WordTest() { // You can do set-up work for each test here. } ~WordTest() override { // You can do clean-up work that doesn't throw exceptions here. } // If the constructor and destructor are not enough for setting up // and cleaning up each test, you can define the following methods: void SetUp() override { // Code here will be called immediately after the constructor (right // before each test). } void TearDown() override { // Code here will be called immediately after each test (right // before the destructor). } // Objects declared here can be used by all tests in the test suite for Foo. }; TEST_F(WordTest, CheckWordSizeIsCorrect) { Cell firstLetter = Cell(Coordinates(0, 3), 'H'); Cell secondLetter = Cell(Coordinates(0, 2), 'O'); Cell thirdLetter = Cell(Coordinates(0, 1), 'L'); Cell lastLetter = Cell(Coordinates(0, 0), 'A'); Selection word = Selection(firstLetter, lastLetter); EXPECT_EQ(word.GetSize(), 4); } TEST_F(WordTest, CheckWordOrientationSizeIsCorrect) { // North Cell firstNorthLetter = Cell(Coordinates(0, 2), 'O'); Cell secondNorthLetter = Cell(Coordinates(0, 1), 'S'); Cell thirdNorthLetter = Cell(Coordinates(0, 0), 'O'); Selection northWord = Selection(firstNorthLetter, thirdNorthLetter); EXPECT_EQ(northWord.GetSize(), 3); // North-East Cell firstNorthEastLetter = Cell(Coordinates(0, 2), 'O'); Cell secondNorthEastLetter = Cell(Coordinates(1, 2), 'S'); Cell thirdNorthEastLetter = Cell(Coordinates(2, 0), 'O'); Selection northEastWord = Selection(firstNorthEastLetter, thirdNorthEastLetter); EXPECT_EQ(northEastWord.GetSize(), 3); // East Cell firstEastLetter = Cell(Coordinates(0, 0), 'O'); Cell secondEastLetter = Cell(Coordinates(1, 0), 'S'); Cell thirdEastLetter = Cell(Coordinates(2, 0), 'O'); Selection eastWord = Selection(firstEastLetter, thirdEastLetter); EXPECT_EQ(eastWord.GetSize(), 3); // South-East Cell firstSouthEastLetter = Cell(Coordinates(0, 0), 'O'); Cell secondSouthEastLetter = Cell(Coordinates(1, 1), 'S'); Cell thirdSouthEastLetter = Cell(Coordinates(2, 2), 'O'); Selection southEastWord = Selection(firstSouthEastLetter, thirdSouthEastLetter); EXPECT_EQ(southEastWord.GetSize(), 3); // South Cell firstSouthLetter = Cell(Coordinates(0, 0), 'O'); Cell secondSouthLetter = Cell(Coordinates(0, 1), 'S'); Cell thirdSouthLetter = Cell(Coordinates(0, 2), 'O'); Selection southWord = Selection(firstSouthLetter, thirdSouthLetter); EXPECT_EQ(southWord.GetSize(), 3); // Sout-West Cell firstSouthWestLetter = Cell(Coordinates(2, 0), 'O'); Cell secondSouthWestLetter = Cell(Coordinates(1, 1), 'S'); Cell thirdSouthWestLetter = Cell(Coordinates(0, 2), 'O'); Selection southWestWord = Selection(firstSouthWestLetter, thirdSouthWestLetter); EXPECT_EQ(southWestWord.GetSize(), 3); // West Cell firstWestLetter = Cell(Coordinates(2, 0), 'O'); Cell secondWestLetter = Cell(Coordinates(1, 0), 'S'); Cell thirdWestLetter = Cell(Coordinates(0, 0), 'O'); Selection westWord = Selection(firstWestLetter, thirdWestLetter); EXPECT_EQ(westWord.GetSize(), 3); // North-West Cell firstNorthWestLetter = Cell(Coordinates(2, 2), 'O'); Cell secondNorthWestLetter = Cell(Coordinates(1, 1), 'S'); Cell thirdNorthWestLetter = Cell(Coordinates(0, 0), 'O'); Selection northWestWord = Selection(firstNorthWestLetter, thirdNorthWestLetter); EXPECT_EQ(northWestWord.GetSize(), 3); } } // namespace
34.692982
84
0.672566
SergioRosello
8e162cb1124cae1e7130e2f70a1789d04925c119
448
cc
C++
example/linux/flutter/generated_plugin_registrant.cc
jainris/flutter_audio_desktop
63d5823facbab34358875c6722874f950eb10393
[ "MIT" ]
50
2020-09-13T12:13:40.000Z
2022-02-26T03:36:45.000Z
example/linux/flutter/generated_plugin_registrant.cc
jainris/flutter_audio_desktop
63d5823facbab34358875c6722874f950eb10393
[ "MIT" ]
28
2020-09-23T05:29:26.000Z
2021-03-17T11:21:11.000Z
example/linux/flutter/generated_plugin_registrant.cc
jainris/flutter_audio_desktop
63d5823facbab34358875c6722874f950eb10393
[ "MIT" ]
16
2020-09-14T07:12:29.000Z
2021-10-13T23:52:12.000Z
// // Generated file. Do not edit. // #include "generated_plugin_registrant.h" #include <flutter_audio_desktop/flutter_audio_desktop_plugin.h> void fl_register_plugins(FlPluginRegistry* registry) { g_autoptr(FlPluginRegistrar) flutter_audio_desktop_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterAudioDesktopPlugin"); flutter_audio_desktop_plugin_register_with_registrar(flutter_audio_desktop_registrar); }
32
89
0.841518
jainris
8e1788ea9d52b0333d00766225789530cdb08ec7
19,774
hpp
C++
library/grammar/string.hpp
grandquista/chimera
2a5326afc866d878517f2b0f5df2bf6cba20f4eb
[ "MIT" ]
2
2017-12-14T07:05:06.000Z
2021-02-07T03:31:27.000Z
library/grammar/string.hpp
grandquista/chimera
2a5326afc866d878517f2b0f5df2bf6cba20f4eb
[ "MIT" ]
149
2018-08-06T13:14:46.000Z
2019-11-19T02:00:56.000Z
library/grammar/string.hpp
grandquista/chimera
2a5326afc866d878517f2b0f5df2bf6cba20f4eb
[ "MIT" ]
null
null
null
// Copyright (c) 2017 Adam Grandquist <grandquista@gmail.com> // // 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. //! parse definitions for string tokens. #pragma once #include <algorithm> #include <cstdint> #include <numeric> #include <string> #include <string_view> #include <gsl/gsl> #include <tao/pegtl.hpp> #include <tao/pegtl/contrib/unescape.hpp> #include "asdl/asdl.hpp" #include "grammar/exprfwd.hpp" #include "grammar/flags.hpp" #include "grammar/oper.hpp" #include "grammar/rules.hpp" #include "grammar/whitespace.hpp" #include "object/object.hpp" namespace chimera { namespace library { namespace grammar { namespace token { using namespace std::literals; struct StringHolder : rules::VariantCapture<object::Object> { std::string string; template <typename String> void apply(String &&in) { string.append(std::forward<String>(in)); } }; struct LiteralChar : plus<not_one<'\0', '{', '}'>> {}; template <> struct Action<LiteralChar> { template <typename Input, typename Top> static void apply(const Input &in, Top &&top) { top.apply(in.string()); } }; template <flags::Flag Option> using FExpression = sor<list_tail<sor<ConditionalExpression<Option>, StarExpr<Option>>, Comma<Option>>, YieldExpr<Option>>; struct Conversion : one<'a', 'r', 's'> {}; template <> struct Action<Conversion> { template <typename Input, typename Top> static void apply(const Input &in, Top &&top) { asdl::FormattedValue formattedValue{ top.template pop<asdl::ExprImpl>(), asdl::FormattedValue::STR, {}}; switch (in.peek_char()) { case 'a': formattedValue.conversion = asdl::FormattedValue::ASCII; break; case 'r': formattedValue.conversion = asdl::FormattedValue::REPR; break; case 's': formattedValue.conversion = asdl::FormattedValue::STR; break; default: break; } top.push(std::move(formattedValue)); } }; template <flags::Flag Option> struct FormatSpec; template <flags::Flag Option> using ReplacementField = if_must<LBrt<Option>, FExpression<Option>, opt<one<'!'>, Conversion>, opt<one<':'>, FormatSpec<Option>>, RBrt<Option>>; template <flags::Flag Option> struct FormatSpec : star<sor<LiteralChar, one<0>, ReplacementField<Option>>> {}; template <flags::Flag Option> struct Action<FormatSpec<Option>> { template <typename Top> static void apply0(Top &&top) { auto formatSpec = top.template pop<asdl::ExprImpl>(); auto expr = top.template pop<asdl::ExprImpl>(); if (std::holds_alternative<asdl::FormattedValue>(*expr.value)) { std::get<asdl::FormattedValue>(*expr.value).format_spec = std::move(formatSpec); top.push(std::move(expr)); } else { top.push(asdl::FormattedValue{std::move(expr), asdl::FormattedValue::STR, std::move(formatSpec)}); } } }; struct LeftFLiteral : String<'{', '{'> {}; template <> struct Action<LeftFLiteral> { template <typename Top> static void apply0(Top &&top) { top.apply("{"sv); } }; struct RightFLiteral : String<'}', '}'> {}; template <> struct Action<RightFLiteral> { template <typename Top> static void apply0(Top &&top) { top.apply("}"sv); } }; struct FLiteral : plus<sor<LiteralChar, LeftFLiteral, RightFLiteral>> { using Transform = StringHolder; }; template <> struct Action<FLiteral> { template <typename Top> static void apply0(Top &&top) { top.push(object::Object(object::String(top.string), {})); } }; template <flags::Flag Option> using FString = must<star<sor<FLiteral, ReplacementField<Option>>>, eof>; template <typename Chars> struct SingleChars : plus<Chars> {}; template <typename Chars> struct Action<SingleChars<Chars>> { template <typename Input, typename Top> static void apply(const Input &in, Top &&top) { top.apply(in.string()); } }; template <unsigned Len> struct Hexseq : rep<Len, ranges<'0', '9', 'a', 'f', 'A', 'F'>> {}; template <unsigned Len> struct Action<Hexseq<Len>> { template <typename Input, typename Top> static void apply(const Input &in, Top &&top) { std::string string; if (tao::pegtl::unescape::utf8_append_utf32( string, tao::pegtl::unescape::unhex_string<std::uint32_t>( in.begin(), in.end()))) { top.apply(std::move(string)); } } }; template <char Open, unsigned Len> using UTF = seq<one<Open>, Hexseq<Len>>; struct Octseq : seq<range<'0', '7'>, rep_opt<2, range<'0', '7'>>> {}; template <> struct Action<Octseq> { template <typename Input, typename Top> static void apply(const Input &in, Top &&top) { std::string string; if (tao::pegtl::unescape::utf8_append_utf32( string, std::accumulate( in.begin(), in.end(), std::uint32_t(0), [](const auto init, const auto c) { return (init << 2) | static_cast<std::uint32_t>(c - '0'); }))) { top.apply(std::move(string)); } } }; struct EscapeControl : one<'a', 'b', 'f', 'n', 'r', 't', 'v'> {}; template <> struct Action<EscapeControl> { template <typename Input, typename Top> static void apply(const Input &in, Top &&top) { switch (in.peek_char()) { case 'a': top.apply("\a"sv); break; case 'b': top.apply("\b"sv); break; case 'f': top.apply("\f"sv); break; case 'n': top.apply("\n"sv); break; case 'r': top.apply("\r"sv); break; case 't': top.apply("\t"sv); break; case 'v': top.apply("\v"sv); break; default: Expects(false); } } }; template <typename Chars> struct EscapeIgnore : seq<Chars> {}; template <typename Chars> struct Action<EscapeIgnore<Chars>> { template <typename Input, typename Top> static void apply(const Input &in, Top &&top) { top.apply(R"(\)"sv); top.apply(in.string()); } }; using Escape = one<'\\'>; using XEscapeseq = UTF<'x', 2>; template <typename Chars, typename... Escapes> using Escapeseq = sor<Escapes..., XEscapeseq, Octseq, Eol, EscapeControl, EscapeIgnore<Chars>>; template <typename Chars, typename... Escapes> using Item = seq<if_then_else<Escape, Escapeseq<Chars, Escapes...>, SingleChars<minus<Chars, Escape>>>, discard>; template <typename Chars> using RawItem = if_then_else<Escape, Chars, Chars>; template <typename Triple, typename Chars, typename... Escapes> using Long = if_must< Triple, until<Triple, Item<seq<not_at<Triple>, Chars>, Escapes...>>>; template <typename Triple, typename Chars> struct LongRaw : if_must<Triple, until<Triple, RawItem<seq<not_at<Triple>, Chars>>>> {}; template <typename Triple, typename Chars> struct Action<LongRaw<Triple, Chars>> { template <typename Input, typename Top> static void apply(const Input &in, Top &&top) { std::string_view view(in.begin(), in.size()); view.remove_prefix(3); view.remove_suffix(3); top.apply(view); } }; template <typename Quote, typename Chars, typename... Escapes> using Short = if_must<Quote, until<Quote, Item<minus<seq<not_at<Quote>, Chars>, Eol>, Escapes...>>>; template <typename Quote, typename Chars> struct ShortRaw : if_must<Quote, until<Quote, RawItem<minus<seq<not_at<Quote>, Chars>, Eol>>>> {}; template <typename Quote, typename Chars> struct Action<ShortRaw<Quote, Chars>> { template <typename Input, typename Top> static void apply(const Input &in, Top &&top) { std::string_view view(in.begin(), in.size()); view.remove_prefix(1); view.remove_suffix(1); top.apply(view); } }; using TripleSingle = rep<3, one<'\''>>; using TripleDouble = rep<3, one<'"'>>; using Single = one<'\''>; using Double = one<'"'>; template <typename Chars> using Raw = sor<LongRaw<TripleDouble, Chars>, LongRaw<TripleSingle, Chars>, ShortRaw<Double, Chars>, ShortRaw<Single, Chars>>; template <typename Chars, typename... Escapes> using Escaped = sor<Long<TripleDouble, Chars, Escapes...>, Long<TripleSingle, Chars, Escapes...>, Short<Double, Chars, Escapes...>, Short<Single, Chars, Escapes...>>; using UTF16Escape = UTF<'u', 4>; using UTF32Escape = UTF<'U', 8>; struct UName : star<not_one<'}'>> {}; template <> struct Action<UName> { template <typename Input, typename Top> static void apply(const Input &in, Top &&top) { top.apply(in.string()); } }; using UNameEscape = if_must<String<'N', '{'>, UName, one<'}'>>; template <typename Prefix, typename RawPrefix, typename Chars, typename... Escapes> using StringImpl = sor<seq<RawPrefix, Raw<Chars>>, seq<Prefix, Escaped<Chars, Escapes...>>>; using BytesPrefix = one<'b', 'B'>; using BytesRawPrefix = sor<seq<one<'r', 'R'>, one<'b', 'B'>>, seq<one<'b', 'B'>, one<'r', 'R'>>>; template <flags::Flag Option> struct Bytes : plus<Token<Option, StringImpl<BytesPrefix, BytesRawPrefix, range<0, 0b1111111>>>> { struct Transform : rules::VariantCapture<object::Object> { object::Bytes bytes; template <typename String> void apply(String &&in) { for (const auto &byte : in) { bytes.emplace_back(static_cast<std::uint8_t>(byte)); } } }; }; template <flags::Flag Option> struct Action<Bytes<Option>> { template <typename Top> static void apply0(Top &&top) { top.push(object::Object(std::move(top.bytes), {})); } }; using StrPrefix = opt<one<'u', 'U'>>; using StrRawPrefix = one<'r', 'R'>; template <flags::Flag Option> struct DocString : plus<Token<Option, StringImpl<StrPrefix, StrRawPrefix, any, UTF16Escape, UTF32Escape, UNameEscape>>> { using Transform = StringHolder; }; template <flags::Flag Option> struct Action<DocString<Option>> { template <typename Top> static void apply0(Top &&top) { top.push(object::Object(object::String(top.string), {})); } }; using JoinedStrPrefix = one<'f', 'F'>; using JoinedStrRawPrefix = sor<seq<one<'r', 'R'>, one<'f', 'F'>>, seq<one<'f', 'F'>, one<'r', 'R'>>>; struct PartialString : plus<StringImpl<StrPrefix, StrRawPrefix, any, UTF16Escape, UTF32Escape, UNameEscape>> { struct Transform { std::string string; template <typename Outer> void success(Outer &&outer) { outer.push(std::move(string)); } template <typename String> void apply(String &&in) { string.append(std::forward<String>(in)); } }; }; template <flags::Flag Option> struct FormattedString : seq<StringImpl<JoinedStrPrefix, JoinedStrRawPrefix, any, UTF16Escape, UTF32Escape, UNameEscape>> { struct Transform : rules::Stack<asdl::ExprImpl> { std::string string; template <typename Outer> void success(Outer &&outer) { if (auto s = size(); s > 0) { asdl::JoinedStr joinedStr; joinedStr.values.reserve(s); transform<asdl::ExprImpl>(std::back_inserter(joinedStr.values)); outer.push(std::move(joinedStr)); } } template <typename String> void apply(String &&in) { string.append(std::forward<String>(in)); } }; }; template <flags::Flag Option> struct Action<FormattedString<Option>> { template <typename Input, typename Top> static void apply(const Input &in, Top &&top) { auto result = tao::pegtl::parse_nested< FString<flags::list<flags::DISCARD, flags::IMPLICIT>>, Action, Normal>(in, tao::pegtl::memory_input<>(top.string.c_str(), top.string.size(), "<f_string>"), std::forward<Top>(top)); Ensures(result); } }; template <flags::Flag Option> struct JoinedStrOne : plus<Token<Option, sor<PartialString, FormattedString<Option>>>> { using Transform = rules::VariantCapture<std::string, asdl::JoinedStr>; }; template <flags::Flag Option> struct Action<JoinedStrOne<Option>> { using State = std::variant<std::string, asdl::JoinedStr>; struct Visitor { auto operator()(std::string &&value, std::string &&element) { value.append(element); return State{std::move(value)}; } auto operator()(std::string &&value, asdl::JoinedStr &&joinedStr) { joinedStr.values.emplace( joinedStr.values.begin(), object::Object(object::String(value), {})); return State{std::move(joinedStr)}; } auto operator()(asdl::JoinedStr &&value, std::string &&element) { value.values.emplace_back( object::Object(object::String(element), {})); return State{std::move(value)}; } auto operator()(asdl::JoinedStr &&value, asdl::JoinedStr &&joinedStr) { std::move(joinedStr.values.begin(), joinedStr.values.end(), std::back_inserter(value.values)); return State{std::move(value)}; } }; template <typename Top> static void apply0(Top &&top) { State value; for (auto &&element : top.vector()) { value = std::visit(Visitor{}, std::move(value), std::move(element)); } std::visit(top, std::move(value)); } }; template <flags::Flag Option> struct JoinedStr : seq<JoinedStrOne<Option>> { struct Transform : rules::Stack<std::string, asdl::JoinedStr, object::Object> { struct Push { using State = std::variant<asdl::JoinedStr, object::Object>; State operator()(std::string && /*value*/) { Expects(false); } auto operator()(asdl::JoinedStr &&value) { return State{std::move(value)}; } auto operator()(object::Object &&value) { return State{std::move(value)}; } }; template <typename Outer> void success(Outer &&outer) { std::visit(outer, std::visit(Push{}, pop())); } }; }; template <flags::Flag Option> struct Action<JoinedStr<Option>> { struct Push { using State = std::variant<asdl::JoinedStr, object::Object>; auto operator()(std::string &&value) { return State{object::Object(object::String(value), {})}; } auto operator()(asdl::JoinedStr &&value) { return State{std::move(value)}; } auto operator()(object::Object &&value) { return State{std::move(value)}; } }; template <typename Top> static void apply0(Top &&top) { std::visit(top, std::visit(Push{}, top.pop())); } }; } // namespace token template <flags::Flag Option> struct DocString : seq<token::DocString<Option>, sor<NEWLINE, at<Eolf>>> { using Transform = rules::ReshapeCapture<asdl::DocString, object::Object>; }; template <flags::Flag Option> struct STRING : sor<token::Bytes<Option>, token::JoinedStr<Option>> {}; } // namespace grammar } // namespace library } // namespace chimera
40.02834
80
0.51148
grandquista
8e19451dbab2934f8cf55793fc1999021ad77ba2
23,113
cxx
C++
TUHKMgen/AliGenUHKM.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
TUHKMgen/AliGenUHKM.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
TUHKMgen/AliGenUHKM.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
///////////////////////////////////////////////////////////////////////////// // Generator using UHKM 3.0 as an external generator. // // ( only the HYDJET++ part is implemented for a moment) // // temporary link: // // http://lav01.sinp.msu.ru/~igor/hydjet++/hydjet++.txt // // The main UHKM options are accessable through this interface. // // Uses the TUHKMgen implementation of TGenerator. // // Author of the first implementation: Sergey Zaporozhets // // (zaporozh@sunhe.jinr.ru) // // Futhers modifications were made by // // Ionut Cristian Arsene (i.c.arsene@fys.uio.no) // // & Malinina Liudmila(malinina@lav01.sinp.msu.ru) using as an example // // AliGenTherminator.cxx created by Adam Kisiel // // // //////////////////////////////////////////////////////////////////////////// #include <iostream> #include <string> #include "TUHKMgen.h" #ifndef DATABASE_PDG #include "DatabasePDG.h" #endif #ifndef PARTICLE_PDG #include "ParticlePDG.h" #endif #include <TLorentzVector.h> #include <TPDGCode.h> #include <TParticle.h> #include <TClonesArray.h> #include <TMCProcess.h> #include <TDatabasePDG.h> #include <TSystem.h> #include "AliGenUHKM.h" #include "AliRun.h" #include "AliConst.h" #include "AliDecayer.h" #include "AliGenEventHeader.h" #include "AliGenHijingEventHeader.h" #include "AliLog.h" using namespace std; ClassImp(AliGenUHKM) //_______________________________________ AliGenUHKM::AliGenUHKM() :AliGenMC(), fTrials(0), fUHKMgen(0), fHydjetParams(), fStableFlagged(0) { // Default constructor setting up default reasonable parameter values // for central Pb+Pb collisions at 5.5TeV // LHC fHydjetParams.fSqrtS=5500; //LHC fHydjetParams.fAw=207;//Pb-Pb fHydjetParams.fBmin=0.; fHydjetParams.fBmax=0.5; //0-5% centrality fHydjetParams.fT = 0.170; fHydjetParams.fMuB = 0.0; fHydjetParams.fMuS = 0.0; fHydjetParams.fMuI3 = 0.0; fHydjetParams.fThFO = 0.130; fHydjetParams.fMu_th_pip = 0.0; fHydjetParams.fSeed=0; fHydjetParams.fTau=10.; fHydjetParams.fSigmaTau=3.; fHydjetParams.fR=11.; fHydjetParams.fYlmax=4.0; fHydjetParams.fUmax=1.1; fHydjetParams.fDelta=0.; fHydjetParams.fEpsilon=0.; fHydjetParams.fWeakDecay=0; //>=0 on ,-1 off fHydjetParams.fEtaType=1;//gaus fHydjetParams.fCorrS=1.; fHydjetParams.fNhsel=2; fHydjetParams.fIshad=1; fHydjetParams.fPtmin=7.0; fHydjetParams.fT0=0.8; fHydjetParams.fTau0=0.1; fHydjetParams.fNf=0; fHydjetParams.fIenglu=0; fHydjetParams.fIanglu=0; /* RHIC fHydjetParams.fSqrtS=200; //RHIC fHydjetParams.fAw=197;//Au-Au fHydjetParams.fBmin=0.; fHydjetParams.fBmax=0.5; //0-5% centrality fHydjetParams.fT = 0.165; fHydjetParams.fMuB = 0.0285; fHydjetParams.fMuS = 0.007; fHydjetParams.fMuI3 = -0.001; fHydjetParams.fThFO = 0.100; fHydjetParams.fMu_th_pip = 0.053; fHydjetParams.fSeed=0; fHydjetParams.fTau=8.; fHydjetParams.fSigmaTau=2.; fHydjetParams.fR=10.; fHydjetParams.fYlmax=3.3; fHydjetParams.fUmax=1.1; fHydjetParams.fDelta=0.; fHydjetParams.fEpsilon=0.; fHydjetParams.fWeakDecay=0; //>=0 on ,-1 off fHydjetParams.fEtaType=1;//gaus fHydjetParams.fCorrS=1.; fHydjetParams.fNhsel=2; fHydjetParams.fIshad=0; fHydjetParams.fPtmin=3.4; fHydjetParams.fT0=0.3; fHydjetParams.fTau0=0.4; fHydjetParams.fNf=2; fHydjetParams.fIenglu=0; fHydjetParams.fIanglu=0; */ strncpy(fParticleFilename, Form("%s/TUHKMgen/UHKM/particles.data", gSystem->Getenv("ALICE_ROOT")), 255); strncpy(fDecayFilename, Form("%s/TUHKMgen/UHKM/tabledecay.txt", gSystem->Getenv("ALICE_ROOT")), 255); for(Int_t i=0; i<500; i++) { fStableFlagPDG[i] = 0; fStableFlagStatus[i] = kFALSE; } fStableFlagged = 0; } //_______________________________________ AliGenUHKM::AliGenUHKM(Int_t npart) :AliGenMC(npart), fTrials(0), fUHKMgen(0), fHydjetParams(), fStableFlagged(0) { // Constructor specifying the size of the particle table // and setting up default reasonable parameter values // for central Pb+Pb collisions at 5.5TeV fName = "UHKM"; fTitle= "Particle Generator using UHKM 3.0"; fNprimaries = 0; //LHC fHydjetParams.fSqrtS=5500; //LHC fHydjetParams.fAw=207;//Pb-Pb fHydjetParams.fBmin=0.; fHydjetParams.fBmax=0.5; //0-5% centrality fHydjetParams.fT = 0.170; fHydjetParams.fMuB = 0.0; fHydjetParams.fMuS = 0.0; fHydjetParams.fMuI3 = 0.0; fHydjetParams.fThFO = 0.130; fHydjetParams.fMu_th_pip = 0.0; fHydjetParams.fSeed=0; fHydjetParams.fTau=10.; fHydjetParams.fSigmaTau=3.; fHydjetParams.fR=11.; fHydjetParams.fYlmax=4.0; fHydjetParams.fUmax=1.1; fHydjetParams.fDelta=0.; fHydjetParams.fEpsilon=0.; fHydjetParams.fWeakDecay=0; //>=0 on ,-1 off fHydjetParams.fEtaType=1;//gaus fHydjetParams.fCorrS=1.; fHydjetParams.fNhsel=2; fHydjetParams.fIshad=1; fHydjetParams.fPtmin=7.0; fHydjetParams.fT0=0.8; fHydjetParams.fTau0=0.1; fHydjetParams.fNf=0; fHydjetParams.fIenglu=0; fHydjetParams.fIanglu=0; /*RHIC fHydjetParams.fSqrtS=200; //RHIC fHydjetParams.fAw=197;//Au-Au fHydjetParams.fBmin=0.; fHydjetParams.fBmax=0.5; //0-5% centrality fHydjetParams.fT = 0.165; fHydjetParams.fMuB = 0.0285; fHydjetParams.fMuS = 0.007; fHydjetParams.fMuI3 = -0.001; fHydjetParams.fThFO = 0.100; fHydjetParams.fMu_th_pip = 0.053; fHydjetParams.fSeed=0; fHydjetParams.fTau=8.; fHydjetParams.fSigmaTau=2.; fHydjetParams.fR=10.; fHydjetParams.fYlmax=3.3; fHydjetParams.fUmax=1.1; fHydjetParams.fDelta=0.; fHydjetParams.fEpsilon=0.; fHydjetParams.fWeakDecay=0;//>=0 on ,-1 off fHydjetParams.fEtaType=1;//gaus fHydjetParams.fCorrS=1.; fHydjetParams.fNhsel=2; fHydjetParams.fIshad=1; fHydjetParams.fPtmin=3.4; fHydjetParams.fT0=0.3; fHydjetParams.fTau0=0.4; fHydjetParams.fNf=2; fHydjetParams.fIenglu=0; fHydjetParams.fIanglu=0; */ strncpy(fParticleFilename, Form("%s/TUHKMgen/UHKM/particles.data", gSystem->Getenv("ALICE_ROOT")), 255); strncpy(fDecayFilename, Form("%s/TUHKMgen/UHKM/tabledecay.txt", gSystem->Getenv("ALICE_ROOT")), 255); for(Int_t i=0; i<500; i++) { fStableFlagPDG[i] = 0; fStableFlagStatus[i] = kFALSE; } fStableFlagged = 0; } //__________________________________________ AliGenUHKM::~AliGenUHKM() { // Destructor, do nothing // delete fParticles; } void AliGenUHKM::SetAllParametersRHIC() { // Set reasonable default parameters for 0-5% central Au+Au collisions // at 200 GeV at RHIC SetEcms(200.0); // RHIC top energy SetAw(197); // Au+Au SetBmin(0.0); // 0% SetBmax(0.5); // 5% SetChFrzTemperature(0.165); // T_ch = 165 MeV SetMuB(0.0285); // mu_B = 28.5 MeV SetMuS(0.007); // mu_S = 7 MeV SetMuQ(-0.001); // mu_Q = -1 MeV SetThFrzTemperature(0.100); // T_th = 100 MeV SetMuPionThermal(0.053); // mu_th_pion = 53 MeV SetSeed(0); // use UNIX time SetTauB(8.0); // tau = 8 fm/c SetSigmaTau(2.0); // sigma_tau = 2 fm/c SetRmaxB(10.0); // fR = 10 fm SetYlMax(3.3); // fYmax = 3.3 SetEtaRMax(1.1); // Umax = 1.1 SetMomAsymmPar(0.0); // delta = 0.0 SetCoordAsymmPar(0.0); // epsilon = 0.0 // SetFlagWeakDecay(0); // weak decay on (<0 off !!!) SetEtaType(1); // gaus distributed with fYmax dispersion (0 means boost invariant) SetGammaS(1.0); // gammaS = 1.0 (no strangeness canonical suppresion) SetPyquenNhsel(2); // hydro on, jets on, jet quenching on SetPyquenShad(1); // shadowing on (0 off) SetPyquenPtmin(3.4); // ptmin = 3.4 GeV/c SetPyquenT0(0.3); // T0 = 300 MeV SetPyquenTau0(0.4); // tau0 = 0.4 fm/c SetPyquenNf(2); // 2 flavours SetPyquenIenglu(0); // radiative and collisional energy loss SetPyquenIanglu(0); // small gluon angular distribution } void AliGenUHKM::SetAllParametersLHC() { // Set reasonable default parameters for 0-5% central Pb+Pb collisions // at 5.5 TeV at LHC SetEcms(5500.0); // LHC SetAw(207); // Pb+Pb SetBmin(0.0); // 0% SetBmax(0.5); // 5% SetChFrzTemperature(0.170); // T_ch = 170 MeV SetMuB(0.0); // mu_B = 0 MeV SetMuS(0.0); // mu_S = 0 MeV SetMuQ(0.0); // mu_Q = 0 MeV SetThFrzTemperature(0.130); // T_th = 130 MeV SetMuPionThermal(0.0); // mu_th_pion = 0 MeV SetSeed(0); // use UNIX time SetTauB(10.0); // tau = 10 fm/c SetSigmaTau(3.0); // sigma_tau = 3 fm/c SetRmaxB(11.0); // fR = 11 fm SetYlMax(4.0); // fYmax = 4.0 SetEtaRMax(1.1); // Umax = 1.1 SetMomAsymmPar(0.0); // delta = 0.0 SetCoordAsymmPar(0.0); // epsilon = 0.0 // SetFlagWeakDecay(0); // weak decay on (<0 off !!!) SetEtaType(1); // gaus distributed with fYmax dispersion (0 means boost invariant) SetGammaS(1.0); // gammaS = 1.0 (no strangeness canonical suppresion) SetPyquenNhsel(2); // hydro on, jets on, jet quenching on SetPyquenShad(1); // shadowing on (0 off) SetPyquenPtmin(7.0); // ptmin = 7.0 GeV/c SetPyquenT0(0.8); // T0 = 800 MeV SetPyquenTau0(0.1); // tau0 = 0.4 fm/c SetPyquenNf(0); // 0 flavours SetPyquenIenglu(0); // radiative and collisional energy loss SetPyquenIanglu(0); // small gluon angular distribution } //_________________________________________ void AliGenUHKM::Init() { // Initialization of the TGenerator::TUHKMgen interface object. // Model input parameters are transmited to the TUHKMgen object which forwards them // further to the model. // HYDJET++ is initialized (average multiplicities are calculated, particle species definitions and decay // channels are loaded, etc.) SetMC(new TUHKMgen()); fUHKMgen = (TUHKMgen*) fMCEvGen; SetAllParameters(); AliGenMC::Init(); fUHKMgen->Initialize(); CheckPDGTable(); fUHKMgen->Print(); } //________________________________________ void AliGenUHKM::Generate() { // Generate one HYDJET++ event, get the output and push particles further // to AliRoot's stack Float_t polar[3] = {0,0,0}; Float_t origin[3] = {0,0,0}; Float_t origin0[3] = {0,0,0}; Float_t time0 = 0.; Float_t p[3]; Float_t v[3]; Float_t mass=0.0, energy=0.0; Vertex(); for(Int_t j=0; j<3; j++) origin0[j] = fVertex[j]; time0 = fTime; // Generate the event and import particles fUHKMgen->GenerateEvent(); fUHKMgen->ImportParticles(&fParticles,"All"); Int_t np = fParticles.GetEntriesFast(); Int_t nt = 0; // Handle the IDs of particles on the stack Int_t* idsOnStack = new Int_t[np]; Int_t* newPos = new Int_t[np]; for(Int_t i=0; i<np; i++) { newPos[i] = i; idsOnStack[i] = -1; } // Generate a random phi used to rotate the whole event Double_t eventRotation = gRandom->Rndm()*TMath::Pi(); TParticle *iparticle; Double_t partMomPhi=0.0, partPt=0.0; Double_t partVtxPhi=0.0, partVtxR=0.0; //_________ Loop for particles in the stack for(Int_t i=0; i<np; i++) { iparticle = (TParticle*)fParticles.At(i); Int_t kf = iparticle->GetPdgCode(); Bool_t hasMother = (iparticle->GetFirstMother() >= 0); Bool_t hasDaughter = (iparticle->GetNDaughters() > 0); if(hasDaughter) { // This particle has decayed // It will not be tracked // Add it only once with coordinates not // smeared with primary vertex position // rotate the direction of the particle partMomPhi = TMath::ATan2(iparticle->Py(), iparticle->Px()); partPt = TMath::Hypot(iparticle->Px(), iparticle->Py()); p[0] = partPt*TMath::Cos(partMomPhi+eventRotation); p[1] = partPt*TMath::Sin(partMomPhi+eventRotation); p[2] = iparticle->Pz(); mass = TDatabasePDG::Instance()->GetParticle(kf)->Mass(); energy = sqrt(mass*mass + p[0]*p[0] + p[1]*p[1] + p[2]*p[2]); // rotate the freezeout point partVtxPhi = TMath::ATan2(iparticle->Vy(), iparticle->Vx()); partVtxR = TMath::Hypot(iparticle->Vx(), iparticle->Vy()); v[0] = partVtxR*TMath::Cos(partVtxPhi + eventRotation); v[1] = partVtxR*TMath::Cos(partVtxPhi + eventRotation); v[2] = iparticle->Vz(); Float_t time = iparticle->T(); Int_t imo = -1; if(hasMother) { imo = iparticle->GetFirstMother(); //index of mother particle in fParticles } // if has mother Bool_t trackFlag = kFALSE; // tFlag is kFALSE --> do not track the particle PushTrack(trackFlag, (imo>=0 ? idsOnStack[imo] : imo), kf, p[0], p[1], p[2], energy, v[0], v[1], v[2], time, polar[0], polar[1], polar[2], (hasMother ? kPDecay : kPNoProcess), nt); idsOnStack[i] = nt; fNprimaries++; KeepTrack(nt); } else { // This is a final state particle // It will be tracked // Add it TWICE to the stack !!! // First time with event-wide coordinates (for femtoscopy) - // this one will not be tracked // Second time with event-wide c0ordinates and vertex smearing // this one will be tracked // rotate the direction of the particle partMomPhi = TMath::ATan2(iparticle->Py(), iparticle->Px()); partPt = TMath::Hypot(iparticle->Px(), iparticle->Py()); p[0] = partPt*TMath::Cos(partMomPhi+eventRotation); p[1] = partPt*TMath::Sin(partMomPhi+eventRotation); p[2] = iparticle->Pz(); energy = sqrt(mass*mass + p[0]*p[0] + p[1]*p[1] + p[2]*p[2]); // rotate the freezeout point partVtxPhi = TMath::ATan2(iparticle->Vy(), iparticle->Vx()); partVtxR = TMath::Hypot(iparticle->Vx(), iparticle->Vy()); v[0] = partVtxR*TMath::Cos(partVtxPhi + eventRotation); v[1] = partVtxR*TMath::Cos(partVtxPhi + eventRotation); v[2] = iparticle->Vz(); Int_t type = iparticle->GetStatusCode(); // 1-from jet / 0-from hydro Int_t coeffT=1; if(type==1) coeffT=-1; //to separate particles from jets Int_t imo = -1; if(hasMother) { imo = iparticle->GetFirstMother(); } // if has mother Bool_t trackFlag = kFALSE; // tFlag = kFALSE --> do not track this one, its for femtoscopy PushTrack(trackFlag, (imo>=0 ? idsOnStack[imo] : imo), kf, p[0], p[1], p[2], energy, v[0], v[1], v[2], (iparticle->T())*coeffT, // freeze-out time is negative if the particle comes from jet polar[0], polar[1], polar[2], hasMother ? kPDecay:kPNoProcess, nt); idsOnStack[i] = nt; fNprimaries++; KeepTrack(nt); origin[0] = origin0[0]+v[0]; origin[1] = origin0[1]+v[1]; origin[2] = origin0[2]+v[2]; Float_t time = time0+iparticle->T(); imo = nt; trackFlag = fTrackIt; // Track this particle, unless otherwise specified by fTrackIt PushTrack(trackFlag, imo, kf, p[0], p[1], p[2], energy, origin[0], origin[1], origin[2], time, polar[0], polar[1], polar[2], hasMother ? kPDecay:kPNoProcess, nt); fNprimaries++; KeepTrack(nt); } } SetHighWaterMark(fNprimaries); TArrayF eventVertex; eventVertex.Set(3); eventVertex[0] = origin0[0]; eventVertex[1] = origin0[1]; eventVertex[2] = origin0[2]; Float_t eventTime = time0; // Builds the event header, to be called after each event AliGenEventHeader* header = new AliGenHijingEventHeader("UHKM"); Double_t b = 0.; Double_t npart = 0; Double_t nbin = 0; fUHKMgen->GetCentrality(b, npart, nbin); printf("********** %13.3f %13.3f %13.3f \n", b, npart, nbin); ((AliGenHijingEventHeader*) header)->SetNProduced(fNprimaries); ((AliGenHijingEventHeader*) header)->SetPrimaryVertex(eventVertex); ((AliGenHijingEventHeader*) header)->SetInteractionTime(eventTime); ((AliGenHijingEventHeader*) header)->SetImpactParameter(b); ((AliGenHijingEventHeader*) header)->SetTotalEnergy(0.0); ((AliGenHijingEventHeader*) header)->SetHardScatters(0); ((AliGenHijingEventHeader*) header)->SetParticipants(Int_t(npart), 0); ((AliGenHijingEventHeader*) header)->SetCollisions(Int_t(nbin), 0, 0, 0); ((AliGenHijingEventHeader*) header)->SetSpectators(0, 0, 0, 0); ((AliGenHijingEventHeader*) header)->SetReactionPlaneAngle(0);//evrot); header->SetPrimaryVertex(fVertex); header->SetInteractionTime(fTime); AddHeader(header); fCollisionGeometry = (AliGenHijingEventHeader*) header; delete [] idsOnStack; delete [] newPos; } void AliGenUHKM::Copy(TObject &) const { Fatal("Copy","Not implemented!\n"); } void AliGenUHKM::SetAllParameters() { // Forward all input parameters to the TGenerator::TUHKMgen object fUHKMgen->SetEcms(fHydjetParams.fSqrtS); fUHKMgen->SetBmin(fHydjetParams.fBmin); fUHKMgen->SetBmax(fHydjetParams.fBmax); fUHKMgen->SetAw(fHydjetParams.fAw); fUHKMgen->SetSeed(fHydjetParams.fSeed); fUHKMgen->SetChFrzTemperature(fHydjetParams.fT); fUHKMgen->SetMuB(fHydjetParams.fMuB); fUHKMgen->SetMuS(fHydjetParams.fMuS); fUHKMgen->SetMuQ(fHydjetParams.fMuI3); fUHKMgen->SetTauB(fHydjetParams.fTau); fUHKMgen->SetThFrzTemperature(fHydjetParams.fThFO); fUHKMgen->SetMuPionThermal(fHydjetParams.fMu_th_pip); fUHKMgen->SetSigmaTau(fHydjetParams.fSigmaTau); fUHKMgen->SetRmaxB(fHydjetParams.fR); fUHKMgen->SetYlMax(fHydjetParams.fYlmax); fUHKMgen->SetEtaRMax(fHydjetParams.fUmax); fUHKMgen->SetMomAsymmPar(fHydjetParams.fDelta); fUHKMgen->SetCoordAsymmPar(fHydjetParams.fEpsilon); fUHKMgen->SetGammaS(fHydjetParams.fCorrS); fUHKMgen->SetEtaType(fHydjetParams.fEtaType); fUHKMgen->SetFlagWeakDecay(fHydjetParams.fWeakDecay); //PYQUEN parameters fUHKMgen->SetPyquenNhsel(fHydjetParams.fNhsel); fUHKMgen->SetPyquenShad(fHydjetParams.fIshad); fUHKMgen->SetPyquenPtmin(fHydjetParams.fPtmin); fUHKMgen->SetPyquenT0(fHydjetParams.fT0); fUHKMgen->SetPyquenTau0(fHydjetParams.fTau0); fUHKMgen->SetPyquenNf(fHydjetParams.fNf); fUHKMgen->SetPyquenIenglu(fHydjetParams.fIenglu); fUHKMgen->SetPyquenIanglu(fHydjetParams.fIanglu); fUHKMgen->SetPDGParticleFile(fParticleFilename); fUHKMgen->SetPDGDecayFile(fDecayFilename); // fUHKMgen->SetUseCharmParticles(fUseCharmParticles); // fUHKMgen->SetMinimumWidth(fMinWidth); // fUHKMgen->SetMaximumWidth(fMaxWidth); // fUHKMgen->SetMinimumMass(fMinMass); // fUHKMgen->SetMaximumMass(fMaxMass); // cout << "AliGenUHKM::Init() no. stable flagged particles = " << fStableFlagged << endl; for(Int_t i=0; i<fStableFlagged; i++) { // cout << "AliGenUHKM::Init() flag no. " << i // << " PDG = " << fStableFlagPDG[i] // << " flag = " << fStableFlagStatus[i] << endl; fUHKMgen->SetPDGParticleStable(fStableFlagPDG[i], fStableFlagStatus[i]); } cout<<" Print all parameters "<<endl; cout<<" SqrtS = "<<fHydjetParams.fSqrtS<<endl; cout<<" Bmin = "<< fHydjetParams.fBmin<<endl; cout<<" Bmax= "<<fHydjetParams.fBmax<<endl; cout<<" Aw= "<<fHydjetParams.fAw<<endl; cout<<" Seed= "<<fHydjetParams.fSeed<<endl; cout<<" ---Stat-model parameters----------- "<<endl; cout<<" ChFrzTemperature= "<<fHydjetParams.fT<<endl; cout<<" MuB= "<<fHydjetParams.fMuB<<endl; cout<<" MuS= "<<fHydjetParams.fMuS<<endl; cout<<" MuQ= "<<fHydjetParams.fMuI3<<endl; cout<<" TauB= "<<fHydjetParams.fTau<<endl; cout<<" ThFrzTemperature= "<<fHydjetParams.fThFO<<endl; cout<<" MuPionThermal= "<<fHydjetParams.fMu_th_pip<<endl; cout<<"-----Volume parameters -------------- "<<endl; cout<<" SigmaTau= "<<fHydjetParams.fSigmaTau<<endl; cout<<" RmaxB= "<<fHydjetParams.fR<<endl; cout<<" YlMax= "<<fHydjetParams.fYlmax<<endl; cout<<" EtaRMax= "<<fHydjetParams.fUmax<<endl; cout<<" MomAsymmPar= "<<fHydjetParams.fDelta<<endl; cout<<" CoordAsymmPar= "<<fHydjetParams.fEpsilon<<endl; cout<<" --------Flags------ "<<endl; cout<<" GammaS= "<<fHydjetParams.fCorrS<<endl; cout<<" EtaType= "<<fHydjetParams.fEtaType<<endl; cout<<" FlagWeakDecay= "<<fHydjetParams.fWeakDecay<<endl; cout<<"----PYQUEN parameters---"<<endl; cout<<" Nhsel= "<<fHydjetParams.fNhsel<<endl; cout<<" Shad= "<<fHydjetParams.fIshad<<endl; cout<<" Ptmin= "<<fHydjetParams.fPtmin<<endl; cout<<" T0= "<<fHydjetParams.fT0<<endl; cout<<" Tau0= "<<fHydjetParams.fTau0<<endl; cout<<" Nf= "<<fHydjetParams.fNf<<endl; cout<<" Ienglu= "<<fHydjetParams.fIenglu<<endl; cout<<" Ianglu= "<<fHydjetParams.fIanglu<<endl; // cout<<"----PDG table parameters---"<<endl; // cout<<" UseCharmParticles= "<<fUseCharmParticles<<endl; // cout<<" MinimumWidth= "<<fMinWidth<<endl; // cout<<" MaximumWidth= "<<fMaxWidth<<endl; // cout<<" MinimumMass= "<<fMinMass<<endl; // cout<<" MaximumMass= "<<fMaxMass<<endl; // cout << "AliGenUHKM::SetAllParameters() OUT" << endl; } // add the additional PDG codes from UHKM(SHARE table) to ROOT's table void AliGenUHKM::CheckPDGTable() { // Add temporarely all particle definitions from HYDJET++ which miss in the ROOT's PDG tables // to the TDatabasePDG table. DatabasePDG *uhkmPDG = fUHKMgen->PDGInfo(); // UHKM's PDG table TParticlePDG *rootTestParticle; ParticlePDG *uhkmTestParticle; // loop over all particles in the SHARE table for(Int_t i=0; i<uhkmPDG->GetNParticles(); i++) { // get a particle specie uhkmTestParticle = uhkmPDG->GetPDGParticleByIndex(i); // check if this code exists in ROOT's table rootTestParticle = TDatabasePDG::Instance()->GetParticle(uhkmTestParticle->GetPDG()); if(!rootTestParticle) { // if not then add it to the ROOT's PDG database TDatabasePDG::Instance()->AddParticle(uhkmTestParticle->GetName(), uhkmTestParticle->GetName(), uhkmTestParticle->GetMass(), uhkmTestParticle->GetElectricCharge(), (uhkmTestParticle->GetWidth()<1e-10 ? kTRUE : kFALSE), uhkmTestParticle->GetWidth(), (Int_t(uhkmTestParticle->GetBaryonNumber())==0 ? "meson" : "baryon"), uhkmTestParticle->GetPDG()); if(uhkmTestParticle->GetWidth()<1e-10) cout << uhkmTestParticle->GetPDG() << " with mass " << TDatabasePDG::Instance()->GetParticle(uhkmTestParticle->GetPDG())->Mass() << TDatabasePDG::Instance()->GetParticle(uhkmTestParticle->GetPDG())->Width() << endl; } } // end for }
35.287023
109
0.637304
AllaMaevskaya
8e19f72fb5aa9c9e2c6dcc6fd006fdb906053580
321
cpp
C++
CodeChef/Begginer-Problems/FACTRL2.cpp
annukamat/My-Competitive-Journey
adb13a5723483cde13e5f3859b3a7ad840b86c97
[ "MIT" ]
7
2018-11-08T11:39:27.000Z
2020-09-10T17:50:57.000Z
CodeChef/Begginer-Problems/FACTRL2.cpp
annukamat/My-Competitive-Journey
adb13a5723483cde13e5f3859b3a7ad840b86c97
[ "MIT" ]
null
null
null
CodeChef/Begginer-Problems/FACTRL2.cpp
annukamat/My-Competitive-Journey
adb13a5723483cde13e5f3859b3a7ad840b86c97
[ "MIT" ]
2
2019-09-16T14:34:03.000Z
2019-10-12T19:24:00.000Z
#include <iostream> #include <vector> using namespace std; long long int fact(int n){ if(n==1 || n==0){ return 1; }else{ return n*fact(n-1); } } int main(){ int t,n; cin>>t; vector<int>a; while(t--){ cin>>n; cout<<fact(n)<<"\n"; } return 0; }
13.956522
28
0.457944
annukamat