hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
42875ddf68b8e6e231f1c34c497127cff79de585
3,214
hpp
C++
src/Engine/Renderer/Renderers/DebugRender.hpp
david49az/Radium-Engine
2600039e5c0658057b8b35f79222a332feceb026
[ "Apache-2.0" ]
1
2021-02-03T17:47:04.000Z
2021-02-03T17:47:04.000Z
src/Engine/Renderer/Renderers/DebugRender.hpp
david49az/Radium-Engine
2600039e5c0658057b8b35f79222a332feceb026
[ "Apache-2.0" ]
null
null
null
src/Engine/Renderer/Renderers/DebugRender.hpp
david49az/Radium-Engine
2600039e5c0658057b8b35f79222a332feceb026
[ "Apache-2.0" ]
null
null
null
#pragma once #include <Engine/RaEngine.hpp> #include <memory> #include <vector> #include <Core/Containers/VectorArray.hpp> #include <Core/Types.hpp> #include <Core/Utils/Color.hpp> #include <Core/Utils/Singleton.hpp> namespace Ra { namespace Engine { class ShaderProgram; class AttribArrayDisplayable; } // namespace Engine } // namespace Ra namespace Ra { namespace Engine { /** This allow to draw debug objects. * @todo : port this to a more Radium-style code */ class RA_ENGINE_API DebugRender final { RA_SINGLETON_INTERFACE( DebugRender ); public: DebugRender(); ~DebugRender(); void initialize(); void render( const Core::Matrix4& view, const Core::Matrix4& proj ); void addLine( const Core::Vector3& from, const Core::Vector3& to, const Core::Utils::Color& color ); void addPoint( const Core::Vector3& p, const Core::Utils::Color& color ); void addPoints( const Core::Vector3Array& p, const Core::Utils::Color& color ); void addPoints( const Core::Vector3Array& p, const Core::Vector4Array& colors ); void addMesh( const std::shared_ptr<AttribArrayDisplayable>& mesh, const Core::Transform& transform = Core::Transform::Identity() ); // Shortcuts void addCross( const Core::Vector3& position, Scalar size, const Core::Utils::Color& color ); void addSphere( const Core::Vector3& center, Scalar radius, const Core::Utils::Color& color ); void addCircle( const Core::Vector3& center, const Core::Vector3& normal, Scalar radius, const Core::Utils::Color& color ); void addFrame( const Core::Transform& transform, Scalar size ); void addTriangle( const Core::Vector3& p0, const Core::Vector3& p1, const Core::Vector3& p2, const Core::Utils::Color& color ); void addAABB( const Core::Aabb& box, const Core::Utils::Color& color ); void addOBB( const Core::Aabb& box, const Core::Transform& transform, const Core::Utils::Color& color ); private: struct Line { Line( const Core::Vector3& la, const Core::Vector3& lb, const Core::Utils::Color& lcol ) : a {la}, b {lb}, col {lcol} {} Core::Vector3 a, b; Core::Utils::Color col; }; struct Point { Core::Vector3 p; Core::Vector3 c; }; struct DbgMesh { std::shared_ptr<AttribArrayDisplayable> mesh; Core::Transform transform; }; void renderLines( const Core::Matrix4f& view, const Core::Matrix4f& proj ); void renderPoints( const Core::Matrix4f& view, const Core::Matrix4f& proj ); void renderMeshes( const Core::Matrix4f& view, const Core::Matrix4f& proj ); private: // these shaders are owned by the manager, just keep a raw copy, since the // manager is available during whole execution. const ShaderProgram* m_lineProg {nullptr}; const ShaderProgram* m_pointProg {nullptr}; const ShaderProgram* m_meshProg {nullptr}; std::vector<Line> m_lines; std::vector<DbgMesh> m_meshes; std::vector<Point> m_points; }; } // namespace Engine } // namespace Ra
30.903846
99
0.645924
david49az
42890423d5897e251f75e70707da5a09267a9f97
332
cpp
C++
Codechef/C++/Solubility (SOLBLTY).cpp
abdzitter/Daily-Coding-DS-ALGO-Practice
26ddbf7a3673608039a07d26d812fce31b69871a
[ "MIT" ]
289
2021-05-15T22:56:03.000Z
2022-03-28T23:13:25.000Z
Codechef/C++/Solubility (SOLBLTY).cpp
abdzitter/Daily-Coding-DS-ALGO-Practice
26ddbf7a3673608039a07d26d812fce31b69871a
[ "MIT" ]
1,812
2021-05-09T13:49:58.000Z
2022-01-15T19:27:17.000Z
Codechef/C++/Solubility (SOLBLTY).cpp
abdzitter/Daily-Coding-DS-ALGO-Practice
26ddbf7a3673608039a07d26d812fce31b69871a
[ "MIT" ]
663
2021-05-09T16:57:58.000Z
2022-03-27T14:15:07.000Z
#include <bits/stdc++.h> using namespace std; #define int long long int #define endl "\n" int32_t main() { int t; cin >> t; while (t--) { int p, x, y; cin >> p >> x >> y; int ans = 0; ans = x + (100 - p) * y; ans = ans * 10; cout << ans << endl; } return 0; }
16.6
32
0.430723
abdzitter
4289fc2aa5fd2402e2a86bec3fa4524c70cf973e
4,556
cpp
C++
rtc_stack/utils/Worker.cpp
anjisuan783/media_lib
c09c7d48f495a803df79e39cf837bbcb1320ceb8
[ "MIT" ]
9
2022-01-07T03:10:45.000Z
2022-03-31T03:29:02.000Z
rtc_stack/utils/Worker.cpp
anjisuan783/mia
c09c7d48f495a803df79e39cf837bbcb1320ceb8
[ "MIT" ]
16
2021-12-17T08:32:57.000Z
2022-03-10T06:16:14.000Z
rtc_stack/utils/Worker.cpp
anjisuan783/media_lib
c09c7d48f495a803df79e39cf837bbcb1320ceb8
[ "MIT" ]
1
2022-02-21T15:47:21.000Z
2022-02-21T15:47:21.000Z
#include "./Worker.h" #include <algorithm> #include <memory> #include "myrtc/api/default_task_queue_factory.h" #include "myrtc/rtc_base/to_queued_task.h" namespace wa { bool ScheduledTaskReference::isCancelled() { return cancelled_; } void ScheduledTaskReference::cancel() { cancelled_ = true; } //////////////////////////////////////////////////////////////////////////////// //Worker //////////////////////////////////////////////////////////////////////////////// Worker::Worker(webrtc::TaskQueueFactory* factory, int id, std::shared_ptr<Clock> the_clock) : factory_(factory), id_(id), clock_{the_clock} { } void Worker::task(Task t) { task_queue_->PostTask(webrtc::ToQueuedTask(std::forward<Task>(t))); } void Worker::task(Task t, const rtc::Location& r) { task_queue_->PostTask(webrtc::ToQueuedTask(std::forward<Task>(t), r)); } void Worker::start(const std::string& name) { auto promise = std::make_shared<std::promise<void>>(); start(promise, name); promise->get_future().wait(); } void Worker::start(std::shared_ptr<std::promise<void>> start_promise, const std::string& name) { auto pQueue = factory_->CreateTaskQueue(name, webrtc::TaskQueueFactory::Priority::NORMAL); task_queue_base_ = pQueue.get(); task_queue_ = std::move(std::make_unique<rtc::TaskQueue>(std::move(pQueue))); task_queue_->PostTask([start_promise] { start_promise->set_value(); }); } void Worker::close() { closed_ = true; task_queue_ = nullptr; task_queue_base_ = nullptr; } std::shared_ptr<ScheduledTaskReference> Worker::scheduleFromNow(Task t, duration delta) { rtc::Location l; return scheduleFromNow(std::forward<Task>(t), delta, l); } std::shared_ptr<ScheduledTaskReference> Worker::scheduleFromNow(Task t, duration delta, const rtc::Location& l) { auto id = std::make_shared<ScheduledTaskReference>(); task_queue_->PostDelayedTask( webrtc::ToQueuedTask(std::forward<std::function<void()>>( [f = std::forward<Task>(t), id]() { if (!id->isCancelled()) { f(); } }), l), ClockUtils::durationToMs(delta)); return id; } void Worker::scheduleEvery(ScheduledTask f, duration period) { rtc::Location l; scheduleEvery(std::forward<ScheduledTask>(f), period, period, l); } void Worker::scheduleEvery(ScheduledTask f, duration period, const rtc::Location& l) { scheduleEvery(std::forward<ScheduledTask>(f), period, period, l); } void Worker::scheduleEvery(ScheduledTask&& t, duration period, duration next_delay, const rtc::Location& location) { time_point start = clock_->now(); scheduleFromNow([this_ptr = shared_from_this(), start, period, next_delay, f = std::forward<ScheduledTask>(t), clock = clock_, location]() { if (f()) { duration clock_skew = clock->now() - start - next_delay; duration delay = std::max(period - clock_skew, duration(0)); this_ptr->scheduleEvery( std::forward<ScheduledTask>(const_cast<ScheduledTask&>(f)), period, delay, location); } }, next_delay, location); } void Worker::unschedule(std::shared_ptr<ScheduledTaskReference> id) { id->cancel(); } //////////////////////////////////////////////////////////////////////////////// //ThreadPool //////////////////////////////////////////////////////////////////////////////// static std::unique_ptr<webrtc::TaskQueueFactory> g_task_queue_factory = webrtc::CreateDefaultTaskQueueFactory(); ThreadPool::ThreadPool(unsigned int num_workers) { workers_.reserve(num_workers); for (unsigned int index = 0; index < num_workers; ++index) { workers_.push_back( std::make_shared<Worker>(g_task_queue_factory.get(), index)); } } ThreadPool::~ThreadPool() { close(); } std::shared_ptr<Worker> ThreadPool::getLessUsedWorker() { std::shared_ptr<Worker> chosen_worker = workers_.front(); for (auto worker : workers_) { if (chosen_worker.use_count() > worker.use_count()) { chosen_worker = worker; } } return chosen_worker; } void ThreadPool::start(const std::string& name) { std::vector<std::shared_ptr<std::promise<void>>> promises(workers_.size()); int index = 0; for (auto worker : workers_) { promises[index] = std::make_shared<std::promise<void>>(); worker->start(promises[index++], name); } for (auto promise : promises) { promise->get_future().wait(); } } void ThreadPool::close() { for (auto worker : workers_) { worker->close(); } } } //namespace wa
28.298137
92
0.628402
anjisuan783
428b536e834ccef6abc90d9128f9c7ae8b192e75
15,383
cpp
C++
test/unit_tests/test_duration.cpp
slavslav/sydevs
3106c38d327be652638bd8bd75dbe02c938800e5
[ "Apache-2.0" ]
26
2018-04-24T23:47:58.000Z
2021-05-27T16:56:27.000Z
test/unit_tests/test_duration.cpp
slavslav/sydevs
3106c38d327be652638bd8bd75dbe02c938800e5
[ "Apache-2.0" ]
2
2018-08-13T23:49:55.000Z
2020-03-27T21:09:47.000Z
test/unit_tests/test_duration.cpp
slavslav/sydevs
3106c38d327be652638bd8bd75dbe02c938800e5
[ "Apache-2.0" ]
9
2018-08-29T20:12:31.000Z
2021-06-09T12:08:51.000Z
#include <catch2/catch.hpp> #include <sydevs/core/string_builder.h> #include <sydevs/core/quantity.h> namespace sydevs { TEST_CASE("test duration constructors") { CHECK(!duration().valid()); CHECK(duration(0).multiplier() == 0); CHECK(duration(0).precision() == unit); CHECK(duration(100).multiplier() == 100); CHECK(duration(100).precision() == unit); CHECK(duration(-100).multiplier() == -100); CHECK(duration(-100).precision() == unit); CHECK(duration(100, nano).multiplier() == 100); CHECK(duration(100, nano).precision() == nano); CHECK(duration(-100, nano).multiplier() == -100); CHECK(duration(-100, nano).precision() == nano); CHECK(duration(quantity_limit - 1).multiplier() == quantity_limit - 1); CHECK(duration(quantity_limit - 1).finite()); CHECK(!duration(quantity_limit).finite()); CHECK(!duration(quantity_limit + 1).finite()); CHECK(duration(1 - quantity_limit).multiplier() == 1 - quantity_limit); CHECK(duration(1 - quantity_limit).finite()); CHECK(!duration(quantity_limit).finite()); CHECK(!duration(-1 - quantity_limit).finite()); } TEST_CASE("test duration literals") { CHECK(0_s == duration(0)); CHECK((0_s).multiplier() == 0); CHECK((0_s).precision() == unit); CHECK(0_us == duration(0)); CHECK((0_us).multiplier() == 0); CHECK((0_us).precision() == micro); CHECK(0_Ms == duration(0)); CHECK((0_Ms).multiplier() == 0); CHECK((0_Ms).precision() == mega); CHECK(1_s == duration(1, unit)); CHECK(1_min == duration(60, unit)); CHECK(1_hr == duration(3600, unit)); CHECK(1_day == duration(86400, unit)); CHECK(1_yr == duration(31536000, unit)); CHECK(1_ys == duration(1, yocto)); CHECK(1_zs == duration(1, zepto)); CHECK(1_as == duration(1, atto)); CHECK(1_fs == duration(1, femto)); CHECK(1_ps == duration(1, pico)); CHECK(1_ns == duration(1, nano)); CHECK(1_us == duration(1, micro)); CHECK(1_ms == duration(1, milli)); CHECK(1_s == duration(1, unit)); CHECK(1_ks == duration(1, kilo)); CHECK(1_Ms == duration(1, mega)); CHECK(1_Gs == duration(1, giga)); CHECK(1_Ts == duration(1, tera)); CHECK(1_Ps == duration(1, peta)); CHECK(1_Es == duration(1, exa)); CHECK(1_Zs == duration(1, zetta)); CHECK(1_Ys == duration(1, yotta)); CHECK(5_min == duration(300, unit)); CHECK(7_day == duration(604800, unit)); CHECK(999999999999999_s == duration(999999999999999, unit)); CHECK(999999999999999_us == duration(999999999999999, micro)); CHECK(1000000000000000_s == duration::inf()); CHECK(1000000000000000_us == duration::inf()); CHECK(-999999999999999_s == duration(-999999999999999, unit)); CHECK(-999999999999999_us == duration(-999999999999999, micro)); CHECK(-1000000000000000_s == -duration::inf()); CHECK(-1000000000000000_us == -duration::inf()); } TEST_CASE("test non-operator duration methods with duration return values") { CHECK((5_s).refined().multiplier() == 5000000000000); CHECK((5_s).refined().precision() == pico); CHECK((5_s).refined().fixed() == false); CHECK((5_s).coarsened().multiplier() == 5); CHECK((5_s).coarsened().precision() == unit); CHECK((5_s).coarsened().fixed() == false); CHECK((5_s).refined().coarsened().multiplier() == 5); CHECK((5_s).refined().coarsened().precision() == unit); CHECK((5_s).refined().coarsened().fixed() == false); CHECK((5_s).fixed_at(nano).multiplier() == 5000000000); CHECK((5_s).fixed_at(nano).precision() == nano); CHECK((5_s).fixed_at(nano).fixed() == true); CHECK((83000_us).fixed_at(milli).multiplier() == 83); CHECK((83000_us).fixed_at(milli).precision() == milli); CHECK((83000_us).fixed_at(milli).fixed() == true); CHECK((83123_us).fixed_at(milli).multiplier() == 83); CHECK((83123_us).fixed_at(milli).precision() == milli); CHECK((83123_us).fixed_at(milli).fixed() == true); CHECK((5_s).rescaled(nano).multiplier() == 5000000000); CHECK((5_s).rescaled(nano).precision() == nano); CHECK((5_s).rescaled(nano).fixed() == false); CHECK((83000_us).rescaled(milli).multiplier() == 83); CHECK((83000_us).rescaled(milli).precision() == milli); CHECK((83000_us).rescaled(milli).fixed() == false); CHECK((83123_us).rescaled(milli).multiplier() == 83); CHECK((83123_us).rescaled(milli).precision() == milli); CHECK((83123_us).rescaled(milli).fixed() == false); CHECK((83000_us).fixed_at(milli).unfixed().multiplier() == 83); CHECK((83000_us).fixed_at(milli).unfixed().precision() == milli); CHECK((83000_us).fixed_at(milli).unfixed().fixed() == false); CHECK((83123_us).fixed_at(milli).unfixed().multiplier() == 83); CHECK((83123_us).fixed_at(milli).unfixed().precision() == milli); CHECK((83123_us).fixed_at(milli).unfixed().fixed() == false); } TEST_CASE("test duration base-1000 floating-point addition") { CHECK((3_hr + 45_s) == 10845_s); CHECK((3_hr + 45_s).precision() == unit); CHECK((3_hr + 45_s).refined() == 10845000000000_ns); CHECK((3_hr + 45_s).refined().precision() == nano); CHECK((3_hr + 45_s).coarsened() == 10845_s); CHECK((3_hr + 45_s).coarsened().precision() == unit); CHECK((3_hr + 45_s).refined().coarsened() == 10845_s); CHECK((3_hr + 45_s).refined().coarsened().precision() == unit); CHECK(((1_s).rescaled(milli) + (1_s).rescaled(micro)) == 2000000_us); CHECK(((1_s).rescaled(milli) + (1_s).rescaled(micro)).precision() == micro); CHECK(!((1_s).fixed_at(milli) + (1_s).fixed_at(micro)).valid()); CHECK(((47_ms).rescaled(pico) + 1_yr) == 31536000047000_us); CHECK(((47_ms).rescaled(pico) + 1_yr).precision() == micro); CHECK(((47_ms).rescaled(femto) + 1_yr) == 31536000047000_us); CHECK(((47_ms).rescaled(femto) + 1_yr).precision() == micro); CHECK((47_ms).rescaled(atto) == +duration::inf()); CHECK(((47_ms).rescaled(atto) + 1_yr) == +duration::inf()); CHECK((1_yr + (47_ms).rescaled(atto)) == +duration::inf()); CHECK(((47_us).rescaled(atto) + 1_yr) == 31536000000047_us); CHECK(((47_us).rescaled(atto) + 1_yr).precision() == micro); CHECK((1_yr + (47_us).rescaled(atto)) == 31536000000047_us); CHECK((1_yr + (47_us).rescaled(atto)).precision() == micro); CHECK((500000000000000_Ms + 500000000000000_Ms) == 1000000000000_Gs); CHECK((500000000000000_Ms + 500000000000000_Ms).precision() == giga); CHECK(((500000000000000_Ms).fixed_at(mega) + (500000000000000_Ms).fixed_at(mega)) == +duration::inf()); CHECK(((500000000000000_Ms).fixed_at(mega) + (500000000000000_Ms).fixed_at(mega)).precision() == unit); } TEST_CASE("test duration negation base-1000 floating-point subtraction") { CHECK(-1_min == -60_s); CHECK((-1_min).precision() == unit); CHECK((5_min - 1_hr) == -3300_s); CHECK((5_min - 1_hr).precision() == unit); CHECK(((47_ms).rescaled(atto) - 1_yr) == +duration::inf()); CHECK((1_yr - (47_ms).rescaled(atto)) == -duration::inf()); CHECK(((47_us).rescaled(atto) - 1_yr) == -31535999999953_us); CHECK(((47_us).rescaled(atto) - 1_yr).precision() == micro); CHECK((1_yr - (47_us).rescaled(atto)) == +31535999999953_us); CHECK((1_yr - (47_us).rescaled(atto)).precision() == micro); CHECK((-duration::inf()) == -duration::inf()); CHECK(!(duration::inf() - duration::inf()).valid()); CHECK((1_s - 1_s).precision() == unit); CHECK((1_ms - 1_ms).precision() == milli); CHECK((1_us - 1_us).precision() == micro); CHECK((1_ks - 1_ks).precision() == kilo); } TEST_CASE("test duration multiplication by number") { CHECK((1_hr*3) == 10800_s); CHECK((1_hr*3).precision() == unit); CHECK((3*1_hr) == 10800_s); CHECK((3*1_hr).precision() == unit); CHECK((1_hr*1000000000000000.0) == 3600000000000_Ms); CHECK((1_hr*1000000000000000.0).precision() == mega); CHECK((1_hr*0.000000000000001) == 3600000000000_ys); CHECK((1_hr*0.000000000000001).precision() == yocto); CHECK(((1_hr).fixed_at(unit)*3) == 10800_s); CHECK(((1_hr).fixed_at(unit)*3).precision() == unit); CHECK(((1_hr).fixed_at(unit)*1000000000000000.0) == +duration::inf()); CHECK(((1_hr).fixed_at(unit)*0.000000000000001) == 0_s); CHECK(((1_hr).fixed_at(unit)*0.000000000000001).precision() == unit); } TEST_CASE("test duration division by number") { CHECK((1_hr/3) == 1200_s); CHECK((1_hr/3).precision() == unit); CHECK((1_hr/1000000000000000.0) == 3600_fs); CHECK((1_hr/1000000000000000.0).precision() == femto); CHECK((1_hr/0.000000000000001) == 3600000000000_Ms); CHECK((1_hr/0.000000000000001).precision() == mega); CHECK(((1_hr).fixed_at(unit)/3) == 1200_s); CHECK(((1_hr).fixed_at(unit)/3).precision() == unit); CHECK(((1_hr).fixed_at(unit)/1000000000000000.0) == 0_s); CHECK(((1_hr).fixed_at(unit)/1000000000000000.0).precision() == unit); CHECK(((1_hr).fixed_at(unit)/0.000000000000001) == +duration::inf()); } TEST_CASE("test duration-duration division") { CHECK((1_hr/1_min) == 60); CHECK((1_hr/2_s) == 1800); CHECK((1_min/1_hr) == Approx(0.0166667)); CHECK((5_s/1_ns) == Approx(5e+09)); CHECK((1_ns/1_s) == Approx(1e-09)); } TEST_CASE("test duration-duration comparisons") { CHECK((1_ns == 1_s) == false); CHECK((1_s == 1_ns) == false); CHECK((1_ns == 1_ns) == true); CHECK((1_ns != 1_s) == true); CHECK((1_s != 1_ns) == true); CHECK((1_ns != 1_ns) == false); CHECK((1_ns < 1_s) == true); CHECK((1_s < 1_ns) == false); CHECK((1_ns < 1_ns) == false); CHECK((1_ns > 1_s) == false); CHECK((1_s > 1_ns) == true); CHECK((1_ns > 1_ns) == false); CHECK((1_ns <= 1_s) == true); CHECK((1_s <= 1_ns) == false); CHECK((1_ns <= 1_ns) == true); CHECK((1_ns >= 1_s) == false); CHECK((1_s >= 1_ns) == true); CHECK((1_ns >= 1_ns) == true); } TEST_CASE("test duration add/subtract/multiply/divide assignment operations") { auto dt = 1_hr; SECTION("add assignment") { CHECK((dt += 1_min) == 3660_s); CHECK(dt == 3660_s); CHECK(dt.precision() == unit); } SECTION("subtract assignment") { CHECK((dt -= 1_min) == 3540_s); CHECK(dt == 3540_s); CHECK(dt.precision() == unit); } SECTION("multiply assignment") { CHECK((dt *= 3.14159) == 11309724_ms); CHECK(dt == 11309724_ms); CHECK(dt.precision() == milli); } SECTION("divide assignment") { CHECK((dt /= 4) == 900_s); CHECK(dt == 900_s); CHECK(dt.precision() == unit); } } TEST_CASE("test max_duration") { CHECK(duration::max(unit) == 999999999999999_s); CHECK(duration::max(yocto) == 999999999999999_ys); } TEST_CASE("test duration addition and subtraction with both fixed and unfixed operands") { CHECK(((1_s).fixed_at(micro) + (1_s).rescaled(nano)) == 2000000_us); CHECK(((1_s).fixed_at(micro) + (1_s).rescaled(nano)).precision() == micro); CHECK(((1_s).fixed_at(nano) + (1_s).rescaled(micro)) == 2000000000_ns); CHECK(((1_s).fixed_at(nano) + (1_s).rescaled(micro)).precision() == nano); CHECK(((1_s).rescaled(micro) + (1_s).fixed_at(nano)) == 2000000000_ns); CHECK(((1_s).rescaled(micro) + (1_s).fixed_at(nano)).precision() == nano); CHECK(((1_s).rescaled(nano) + (1_s).fixed_at(micro)) == 2000000_us); CHECK(((1_s).rescaled(nano) + (1_s).fixed_at(micro)).precision() == micro); CHECK(((2_s).fixed_at(micro) - (1_s).rescaled(nano)) == 1000000_us); CHECK(((2_s).fixed_at(micro) - (1_s).rescaled(nano)).precision() == micro); CHECK(((2_s).fixed_at(nano) - (1_s).rescaled(micro)) == 1000000000_ns); CHECK(((2_s).fixed_at(nano) - (1_s).rescaled(micro)).precision() == nano); CHECK(((2_s).rescaled(micro) - (1_s).fixed_at(nano)) == 1000000000_ns); CHECK(((2_s).rescaled(micro) - (1_s).fixed_at(nano)).precision() == nano); CHECK(((2_s).rescaled(nano) - (1_s).fixed_at(micro)) == 1000000_us); CHECK(((2_s).rescaled(nano) - (1_s).fixed_at(micro)).precision() == micro); } TEST_CASE("test duration with assorted operations") { CHECK((string_builder() << (2_s).fixed_at(unit) + (3_s).fixed_at(unit)).str() == "5_s"); CHECK((string_builder() << (2_s).fixed_at(unit) - (3_s).fixed_at(unit)).str() == "-1_s"); CHECK((string_builder() << 5*(100_s).fixed_at(unit)).str() == "500_s"); CHECK((string_builder() << (1.0/5.0)*(100_s).fixed_at(unit)).str() == "20_s"); CHECK((string_builder() << (100_s).fixed_at(unit)*(1.0/5.0)).str() == "20_s"); CHECK((string_builder() << (100_s).fixed_at(unit)/5.0).str() == "20_s"); CHECK((string_builder() << (100_s).fixed_at(unit)/8.0).str() == "13_s"); CHECK(2_s > 1000_ms); CHECK(2_s < 3000_ms); CHECK(-8_ps < -7_ps); CHECK(1_s == 1000_ms); CHECK(1_s == 1000000_us); CHECK(1000_ms == 1000000_us); CHECK(((500_ms).fixed_at(milli) + (500_ms).fixed_at(milli)) == 1_s); CHECK((string_builder() << (500_ms).fixed_at(milli) + (500_ms).fixed_at(milli)).str() == "1000_ms"); CHECK((string_builder() << (999999999999999_Ms).fixed_at(mega) + (1_Ms).fixed_at(mega)).str() == "duration::inf()"); CHECK((string_builder() << -1000000*(1000000000_fs).fixed_at(femto)).str() == "-duration::inf()"); CHECK((string_builder() << 3_s + 475_ms).str() == "3475_ms"); CHECK((string_builder() << 1_ks + 1_us).str() == "1000000001_us"); CHECK((string_builder() << 500_ps - 1_ns).str() == "-500_ps"); CHECK((string_builder() << (1.0/3.0)*(1_s)).str() == "333333333333333_fs"); CHECK((string_builder() << (1.0/3.0)*(1000_ms)).str() == "333333333333333_fs"); CHECK((string_builder() << 1000_ms/3.0).str() == "333333333333333_fs"); CHECK((string_builder() << (1.0/3.0)*(1000000_us)).str() == "333333333333333_fs"); CHECK((string_builder() << (999999999999999_Ms) + (1_Ms)).str() == "1000000000000_Gs"); CHECK((string_builder() << -1000000*(1000000000_fs)).str() == "-1000000000000_ps"); CHECK((10_ms/250_us) == Approx(40.0)); CHECK(((-100_s)/900_s) == Approx(-1.0/9.0)); CHECK(((123_ms)/1_s) == Approx(0.123)); CHECK(((123_ms)/1_ms) == 123); CHECK(((123_ms)/0_s) == std::numeric_limits<float64>::infinity()); CHECK(duration::inf().precision() == unit); CHECK(-duration::inf().precision() == unit); CHECK(duration(0, unit).precision() == unit); CHECK(duration(0, milli).precision() == milli); CHECK(duration(0, micro).precision() == micro); CHECK((string_builder() << (1_min + 40_s).fixed_at(micro)/8.0).str() == "12500000_us"); CHECK((string_builder() << (1_min + 40_s).fixed_at(milli)/8.0).str() == "12500_ms"); CHECK((string_builder() << (1_min + 40_s).fixed_at(unit)/8.0).str() == "13_s"); CHECK((string_builder() << (1_min + 40_s).rescaled(micro)/8.0).str() == "12500000_us"); CHECK((string_builder() << (1_min + 40_s).rescaled(milli)/8.0).str() == "12500_ms"); CHECK((string_builder() << (1_min + 40_s).rescaled(unit)/8.0).str() == "12500_ms"); CHECK((string_builder() << (4_s + 10_ms)).str() == "4010_ms"); CHECK((string_builder() << (4_s + 10_ms)/4).str() == "1002500_us"); CHECK((string_builder() << (4_s + 10_ms).fixed_at(milli)/4).str() == "1003_ms"); CHECK((string_builder() << (4_s + 10_ms).fixed_at(micro)/4).str() == "1002500_us"); } } // namespace
45.646884
120
0.62075
slavslav
429707e171dda3277947c6ae92f83456590edfbc
29,271
cc
C++
src/JobMaker.cc
ganibc/btcpool
360c90900922edab95c4759e8da7158dd12382b5
[ "MIT" ]
1
2018-05-29T13:13:47.000Z
2018-05-29T13:13:47.000Z
src/JobMaker.cc
ganibc/btcpool
360c90900922edab95c4759e8da7158dd12382b5
[ "MIT" ]
null
null
null
src/JobMaker.cc
ganibc/btcpool
360c90900922edab95c4759e8da7158dd12382b5
[ "MIT" ]
1
2019-02-28T06:20:07.000Z
2019-02-28T06:20:07.000Z
/* The MIT License (MIT) Copyright (c) [2016] [BTC.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 "JobMaker.h" #include <iostream> #include <stdlib.h> #include <glog/logging.h> #include <librdkafka/rdkafka.h> #include <hash.h> #include <script/script.h> #include <uint256.h> #include <util.h> #include <utilstrencodings.h> #ifdef INCLUDE_BTC_KEY_IO_H // #include <key_io.h> // IsValidDestinationString for bch is not in this file. #endif #include "utilities_js.hpp" #include "Utils.h" #include "BitcoinUtils.h" /////////////////////////////////// JobMaker ///////////////////////////////// JobMaker::JobMaker(shared_ptr<JobMakerHandler> handler, const string &kafkaBrokers, const string& zookeeperBrokers) : handler_(handler), running_(true), zkLocker_(zookeeperBrokers.c_str()), kafkaBrokers_(kafkaBrokers), kafkaProducer_(kafkaBrokers.c_str(), handler->def().jobTopic_.c_str(), RD_KAFKA_PARTITION_UA) { } JobMaker::~JobMaker() { } void JobMaker::stop() { if (!running_) { return; } running_ = false; LOG(INFO) << "stop jobmaker"; } bool JobMaker::init() { /* get lock from zookeeper */ try { if (handler_->def().zookeeperLockPath_.empty()) { LOG(ERROR) << "zookeeper lock path is empty!"; return false; } zkLocker_.getLock(handler_->def().zookeeperLockPath_.c_str()); } catch(const ZookeeperException &zooex) { LOG(ERROR) << zooex.what(); return false; } /* setup kafka producer */ { map<string, string> options; // set to 1 (0 is an illegal value here), deliver msg as soon as possible. options["queue.buffering.max.ms"] = "1"; if (!kafkaProducer_.setup(&options)) { LOG(ERROR) << "kafka producer setup failure"; return false; } if (!kafkaProducer_.checkAlive()) { LOG(ERROR) << "kafka producer is NOT alive"; return false; } } /* setup kafka consumers */ if (!handler_->initConsumerHandlers(kafkaBrokers_, kafkaConsumerHandlers_)) { return false; } return true; } void JobMaker::consumeKafkaMsg(rd_kafka_message_t *rkmessage, JobMakerConsumerHandler &consumerHandler) { // check error if (rkmessage->err) { if (rkmessage->err == RD_KAFKA_RESP_ERR__PARTITION_EOF) { // Reached the end of the topic+partition queue on the broker. return; } LOG(ERROR) << "consume error for topic " << rd_kafka_topic_name(rkmessage->rkt) << "[" << rkmessage->partition << "] offset " << rkmessage->offset << ": " << rd_kafka_message_errstr(rkmessage); if (rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION || rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_TOPIC) { LOG(FATAL) << "consume fatal"; stop(); } return; } // set json string LOG(INFO) << "received " << consumerHandler.kafkaTopic_ << " message len: " << rkmessage->len; string msg((const char *)rkmessage->payload, rkmessage->len); if (consumerHandler.messageProcessor_(msg)) { LOG(INFO) << "handleMsg returns true, new stratum job"; produceStratumJob(); } } void JobMaker::produceStratumJob() { const string jobMsg = handler_->makeStratumJobMsg(); if (!jobMsg.empty()) { LOG(INFO) << "new " << handler_->def().jobTopic_ << " job: " << jobMsg; kafkaProducer_.produce(jobMsg.data(), jobMsg.size()); } lastJobTime_ = time(nullptr); // save send timestamp to file, for monitor system if (!handler_->def().fileLastJobTime_.empty()) { // TODO: fix Y2K38 issue writeTime2File(handler_->def().fileLastJobTime_.c_str(), (uint32_t)lastJobTime_); } } void JobMaker::runThreadKafkaConsume(JobMakerConsumerHandler &consumerHandler) { const int32_t timeoutMs = 1000; while (running_) { rd_kafka_message_t *rkmessage; rkmessage = consumerHandler.kafkaConsumer_->consumer(timeoutMs); if (rkmessage == nullptr) /* timeout */ { continue; } consumeKafkaMsg(rkmessage, consumerHandler); /* Return message to rdkafka */ rd_kafka_message_destroy(rkmessage); // Don't add any sleep() here. // Kafka will not skip any message during your sleep(), you will received // all messages from your beginning offset to the latest in any case. // So sleep() will cause unexpected delay before consumer a new message. // If the producer's speed is faster than the sleep() here, the consumption // will be delayed permanently and the latest message will never be received. // At the same time, there is not a busy waiting. // KafkaConsumer::consumer(timeoutMs) will return after `timeoutMs` millisecond // if no new messages. You can increase `timeoutMs` if you want. } } void JobMaker::run() { // running consumer threads for (JobMakerConsumerHandler &consumerhandler : kafkaConsumerHandlers_) { kafkaConsumerWorkers_.push_back(std::make_shared<thread>(std::bind(&JobMaker::runThreadKafkaConsume, this, consumerhandler))); } // produce stratum job regularly // the stratum job producing will also be triggered by consumer threads while (running_) { sleep(1); if (time(nullptr) - lastJobTime_ > handler_->def().jobInterval_) { produceStratumJob(); } } // wait consumer threads exit for (auto pWorker : kafkaConsumerWorkers_) { if (pWorker->joinable()) { LOG(INFO) << "wait for worker " << pWorker->get_id() << "exiting"; pWorker->join(); LOG(INFO) << "worker exited"; } } } ////////////////////////////////GwJobMakerHandler////////////////////////////////// bool GwJobMakerHandler::initConsumerHandlers(const string &kafkaBrokers, vector<JobMakerConsumerHandler> &handlers) { JobMakerConsumerHandler handler = { /* kafkaTopic_ = */ def_.rawGwTopic_, /* kafkaConsumer_ = */ std::make_shared<KafkaConsumer>(kafkaBrokers.c_str(), def_.rawGwTopic_.c_str(), 0/* partition */), /* messageProcessor_ = */ std::bind(&GwJobMakerHandler::processMsg, this, std::placeholders::_1) }; // init kafka consumer { map<string, string> consumerOptions; consumerOptions["fetch.wait.max.ms"] = "5"; if (!handler.kafkaConsumer_->setup(RD_KAFKA_OFFSET_TAIL(1), &consumerOptions)) { LOG(ERROR) << "kafka consumer " << def_.rawGwTopic_ << " setup failure"; return false; } if (!handler.kafkaConsumer_->checkAlive()) { LOG(FATAL) << "kafka consumer " << def_.rawGwTopic_ << " is NOT alive"; return false; } } handlers.push_back(handler); return true; } ////////////////////////////////JobMakerHandlerEth////////////////////////////////// bool JobMakerHandlerEth::processMsg(const string &msg) { shared_ptr<RskWork> rskWork = make_shared<RskWorkEth>(); if (rskWork->initFromGw(msg)) { previousRskWork_ = currentRskWork_; currentRskWork_ = rskWork; DLOG(INFO) << "currentRskBlockJson: " << msg; } else { LOG(ERROR) << "eth initFromGw failed " << msg; return false; } clearTimeoutMsg(); if (nullptr == previousRskWork_ && nullptr == currentRskWork_) { LOG(ERROR) << "no current work" << msg; return false; } //first job if (nullptr == previousRskWork_ && currentRskWork_ != nullptr) return true; // Check if header changes so the new workpackage is really new return currentRskWork_->getBlockHash() != previousRskWork_->getBlockHash(); } void JobMakerHandlerEth::clearTimeoutMsg() { const uint32_t now = time(nullptr); if(currentRskWork_ != nullptr && currentRskWork_->getCreatedAt() + def_.maxJobDelay_ < now) currentRskWork_ = nullptr; if(previousRskWork_ != nullptr && previousRskWork_->getCreatedAt() + def_.maxJobDelay_ < now) previousRskWork_ = nullptr; } string JobMakerHandlerEth::makeStratumJobMsg() { if (nullptr == currentRskWork_) return ""; if (0 == currentRskWork_->getRpcAddress().length()) return ""; RskWorkEth *currentRskBlockJson = dynamic_cast<RskWorkEth*>(currentRskWork_.get()); if (nullptr == currentRskBlockJson) return ""; const string request = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBlockByNumber\",\"params\":[\"pending\", false],\"id\":2}"; string response; bool res = bitcoindRpcCall(currentRskBlockJson->getRpcAddress().c_str(), currentRskBlockJson->getRpcUserPwd().c_str(), request.c_str(), response); if (!res) LOG(ERROR) << "get pending block failed"; StratumJobEth sjob; if (!sjob.initFromGw(*currentRskBlockJson, response)) { LOG(ERROR) << "init stratum job message from gw str fail"; return ""; } return sjob.serializeToJson(); } ////////////////////////////////JobMakerHandlerSia////////////////////////////////// JobMakerHandlerSia::JobMakerHandlerSia() : time_(0) { } bool JobMakerHandlerSia::processMsg(const string &msg) { JsonNode j; if (!JsonNode::parse(msg.c_str(), msg.c_str() + msg.length(), j)) { LOG(ERROR) << "deserialize sia work failed " << msg; return false; } if (!validate(j)) return false; string header = j["hHash"].str(); if (header == header_) return false; header_ = move(header); time_ = j["created_at_ts"].uint32(); return processMsg(j); } bool JobMakerHandlerSia::processMsg(JsonNode &j) { target_ = j["target"].str(); return true; } bool JobMakerHandlerSia::validate(JsonNode &j) { // check fields are valid if (j.type() != Utilities::JS::type::Obj || j["created_at_ts"].type() != Utilities::JS::type::Int || j["rpcAddress"].type() != Utilities::JS::type::Str || j["rpcUserPwd"].type() != Utilities::JS::type::Str || j["target"].type() != Utilities::JS::type::Str || j["hHash"].type() != Utilities::JS::type::Str) { LOG(ERROR) << "work format not expected"; return false; } // check timestamp if (j["created_at_ts"].uint32() + def_.maxJobDelay_ < time(nullptr)) { LOG(ERROR) << "too old sia work: " << date("%F %T", j["created_at_ts"].uint32()); return false; } return true; } string JobMakerHandlerSia::makeStratumJobMsg() { if (0 == header_.size() || 0 == target_.size()) return ""; const string jobIdStr = Strings::Format("%08x%08x", (uint32_t)time(nullptr), djb2(header_.c_str())); assert(jobIdStr.length() == 16); size_t pos; uint64 jobId = stoull(jobIdStr, &pos, 16); return Strings::Format("{\"created_at_ts\":%u" ",\"jobId\":%" PRIu64 "" ",\"target\":\"%s\"" ",\"hHash\":\"%s\"" "}", time_, jobId, target_.c_str(), header_.c_str()); } ///////////////////////////////////JobMakerHandlerBytom////////////////////////////////// bool JobMakerHandlerBytom::processMsg(JsonNode &j) { seed_ = j["sHash"].str(); return true; } bool JobMakerHandlerBytom::validate(JsonNode &j) { // check fields are valid if (j.type() != Utilities::JS::type::Obj || j["created_at_ts"].type() != Utilities::JS::type::Int || j["rpcAddress"].type() != Utilities::JS::type::Str || j["rpcUserPwd"].type() != Utilities::JS::type::Str || j["hHash"].type() != Utilities::JS::type::Str) { LOG(ERROR) << "work format not expected"; return false; } // check timestamp if (j["created_at_ts"].uint32() + def_.maxJobDelay_ < time(nullptr)) { LOG(ERROR) << "too old bytom work: " << date("%F %T", j["created_at_ts"].uint32()); return false; } return true; } string JobMakerHandlerBytom::makeStratumJobMsg() { if (0 == header_.size() || 0 == seed_.size()) return ""; const string jobIdStr = Strings::Format("%08x%08x", (uint32_t)time(nullptr), djb2(header_.c_str())); assert(jobIdStr.length() == 16); size_t pos; uint64 jobId = stoull(jobIdStr, &pos, 16); return Strings::Format("{\"created_at_ts\":%u" ",\"jobId\":%" PRIu64 "" ",\"sHash\":\"%s\"" ",\"hHash\":\"%s\"" "}", time_, jobId, seed_.c_str(), header_.c_str()); } ////////////////////////////////JobMakerHandlerBitcoin////////////////////////////////// JobMakerHandlerBitcoin::JobMakerHandlerBitcoin() : currBestHeight_(0), lastJobSendTime_(0), isLastJobEmptyBlock_(false), previousRskWork_(nullptr), currentRskWork_(nullptr), isRskUpdate_(false) { } bool JobMakerHandlerBitcoin::init(const GbtJobMakerDefinition &def) { def_ = def; // select chain if (def_.testnet_) { SelectParams(CBaseChainParams::TESTNET); LOG(WARNING) << "using bitcoin testnet3"; } else { SelectParams(CBaseChainParams::MAIN); } LOG(INFO) << "Block Version: " << std::hex << def_.blockVersion_; LOG(INFO) << "Coinbase Info: " << def_.coinbaseInfo_; LOG(INFO) << "Payout Address: " << def_.payoutAddr_; // check pool payout address if (!IsValidDestinationString(def_.payoutAddr_)) { LOG(ERROR) << "invalid pool payout address"; return false; } poolPayoutAddr_ = DecodeDestination(def_.payoutAddr_); // notify policy for RSK RskWork::setIsCleanJob(def_.rskNotifyPolicy_ != 0); return true; } bool JobMakerHandlerBitcoin::initConsumerHandlers(const string &kafkaBrokers, vector<JobMakerConsumerHandler> &handlers) { const int32_t consumeLatestN = 20; // // consumer for RawGbt, offset: latest N messages // { kafkaRawGbtConsumer_ = std::make_shared<KafkaConsumer>(kafkaBrokers.c_str(), def_.rawGbtTopic_.c_str(), 0/* partition */); map<string, string> consumerOptions; consumerOptions["fetch.wait.max.ms"] = "5"; if (!kafkaRawGbtConsumer_->setup(RD_KAFKA_OFFSET_TAIL(consumeLatestN), &consumerOptions)) { LOG(ERROR) << "kafka consumer rawgbt setup failure"; return false; } if (!kafkaRawGbtConsumer_->checkAlive()) { LOG(ERROR) << "kafka consumer rawgbt is NOT alive"; return false; } handlers.push_back({ def_.rawGbtTopic_, kafkaRawGbtConsumer_, std::bind(&JobMakerHandlerBitcoin::processRawGbtMsg, this, std::placeholders::_1) }); } // // consumer for aux block // { kafkaAuxPowConsumer_ = std::make_shared<KafkaConsumer>(kafkaBrokers.c_str(), def_.auxPowTopic_.c_str(), 0/* partition */); map<string, string> consumerOptions; consumerOptions["fetch.wait.max.ms"] = "5"; if (!kafkaAuxPowConsumer_->setup(RD_KAFKA_OFFSET_TAIL(1), &consumerOptions)) { LOG(ERROR) << "kafka consumer aux pow setup failure"; return false; } if (!kafkaAuxPowConsumer_->checkAlive()) { LOG(ERROR) << "kafka consumer aux pow is NOT alive"; return false; } handlers.push_back({ def_.auxPowTopic_, kafkaAuxPowConsumer_, std::bind(&JobMakerHandlerBitcoin::processAuxPowMsg, this, std::placeholders::_1) }); } // // consumer for RSK messages // { kafkaRskGwConsumer_ = std::make_shared<KafkaConsumer>(kafkaBrokers.c_str(), def_.rskRawGwTopic_.c_str(), 0/* partition */); map<string, string> consumerOptions; consumerOptions["fetch.wait.max.ms"] = "5"; if (!kafkaRskGwConsumer_->setup(RD_KAFKA_OFFSET_TAIL(1), &consumerOptions)) { LOG(ERROR) << "kafka consumer rawgw block setup failure"; return false; } if (!kafkaRskGwConsumer_->checkAlive()) { LOG(ERROR) << "kafka consumer rawgw block is NOT alive"; return false; } handlers.push_back({ def_.rskRawGwTopic_, kafkaRskGwConsumer_, std::bind(&JobMakerHandlerBitcoin::processRskGwMsg, this, std::placeholders::_1) }); } // sleep 3 seconds, wait for the latest N messages transfer from broker to client sleep(3); /* pre-consume some messages for initialization */ // // consume the latest AuxPow message // { rd_kafka_message_t *rkmessage; rkmessage = kafkaAuxPowConsumer_->consumer(1000/* timeout ms */); if (rkmessage != nullptr && !rkmessage->err) { string msg((const char *)rkmessage->payload, rkmessage->len); processAuxPowMsg(msg); rd_kafka_message_destroy(rkmessage); } } // // consume the latest RSK getwork message // { rd_kafka_message_t *rkmessage; rkmessage = kafkaRskGwConsumer_->consumer(1000/* timeout ms */); if (rkmessage != nullptr && !rkmessage->err) { string msg((const char *)rkmessage->payload, rkmessage->len); processRskGwMsg(msg); rd_kafka_message_destroy(rkmessage); } } // // consume the latest N RawGbt messages // LOG(INFO) << "consume latest rawgbt messages from kafka..."; for (int32_t i = 0; i < consumeLatestN; i++) { rd_kafka_message_t *rkmessage; rkmessage = kafkaRawGbtConsumer_->consumer(5000/* timeout ms */); if (rkmessage == nullptr || rkmessage->err) { break; } string msg((const char *)rkmessage->payload, rkmessage->len); processRawGbtMsg(msg); rd_kafka_message_destroy(rkmessage); } LOG(INFO) << "consume latest rawgbt messages done"; return true; } bool JobMakerHandlerBitcoin::addRawGbt(const string &msg) { JsonNode r; if (!JsonNode::parse(msg.c_str(), msg.c_str() + msg.size(), r)) { LOG(ERROR) << "parse rawgbt message to json fail"; return false; } if (r["created_at_ts"].type() != Utilities::JS::type::Int || r["block_template_base64"].type() != Utilities::JS::type::Str || r["gbthash"].type() != Utilities::JS::type::Str) { LOG(ERROR) << "invalid rawgbt: missing fields"; return false; } const uint256 gbtHash = uint256S(r["gbthash"].str()); for (const auto &itr : lastestGbtHash_) { if (gbtHash == itr) { LOG(ERROR) << "duplicate gbt hash: " << gbtHash.ToString(); return false; } } const uint32_t gbtTime = r["created_at_ts"].uint32(); const int64_t timeDiff = (int64_t)time(nullptr) - (int64_t)gbtTime; if (labs(timeDiff) >= 60) { LOG(WARNING) << "rawgbt diff time is more than 60, ignore it"; return false; // time diff too large, there must be some problems, so ignore it } if (labs(timeDiff) >= 3) { LOG(WARNING) << "rawgbt diff time is too large: " << timeDiff << " seconds"; } const string gbt = DecodeBase64(r["block_template_base64"].str()); assert(gbt.length() > 64); // valid gbt string's len at least 64 bytes JsonNode nodeGbt; if (!JsonNode::parse(gbt.c_str(), gbt.c_str() + gbt.length(), nodeGbt)) { LOG(ERROR) << "parse gbt message to json fail"; return false; } assert(nodeGbt["result"]["height"].type() == Utilities::JS::type::Int); const uint32_t height = nodeGbt["result"]["height"].uint32(); assert(nodeGbt["result"]["transactions"].type() == Utilities::JS::type::Array); const bool isEmptyBlock = nodeGbt["result"]["transactions"].array().size() == 0; { ScopeLock sl(lock_); if (!rawgbtMap_.empty()) { const uint64_t bestKey = rawgbtMap_.rbegin()->first; const uint32_t bestTime = gbtKeyGetTime(bestKey); const uint32_t bestHeight = gbtKeyGetHeight(bestKey); const bool bestIsEmpty = gbtKeyIsEmptyBlock(bestKey); // To prevent the job's block height ups and downs // when the block height of two bitcoind is not synchronized. // The block height downs must past twice the time of stratumJobInterval_ // without the higher height GBT received. if (height < bestHeight && !bestIsEmpty && gbtTime - bestTime < 2 * def_.jobInterval_) { LOG(WARNING) << "skip low height GBT. height: " << height << ", best height: " << bestHeight << ", elapsed time after best GBT: " << (gbtTime - bestTime) << "s"; return false; } } const uint64_t key = makeGbtKey(gbtTime, isEmptyBlock, height); if (rawgbtMap_.find(key) == rawgbtMap_.end()) { rawgbtMap_.insert(std::make_pair(key, gbt)); } else { LOG(ERROR) << "key already exist in rawgbtMap: " << key; } } lastestGbtHash_.push_back(gbtHash); while (lastestGbtHash_.size() > 20) { lastestGbtHash_.pop_front(); } LOG(INFO) << "add rawgbt, height: "<< height << ", gbthash: " << r["gbthash"].str().substr(0, 16) << "..., gbtTime(UTC): " << date("%F %T", gbtTime) << ", isEmpty:" << isEmptyBlock; return true; } bool JobMakerHandlerBitcoin::findBestRawGbt(bool isRskUpdate, string &bestRawGbt) { static uint64_t lastSendBestKey = 0; ScopeLock sl(lock_); // clean expired gbt first clearTimeoutGbt(); clearTimeoutRskGw(); if (rawgbtMap_.size() == 0) { LOG(WARNING) << "RawGbt Map is empty"; return false; } bool isFindNewHeight = false; bool needUpdateEmptyBlockJob = false; // rawgbtMap_ is sorted gbt by (timestamp + height + emptyFlag), // so the last item is the newest/best item. // @see makeGbtKey() const uint64_t bestKey = rawgbtMap_.rbegin()->first; const uint32_t bestHeight = gbtKeyGetHeight(bestKey); const bool currentGbtIsEmpty = gbtKeyIsEmptyBlock(bestKey); // if last job is an empty block job, we need to // send a new non-empty job as quick as possible. if (bestHeight == currBestHeight_ && isLastJobEmptyBlock_ && !currentGbtIsEmpty) { needUpdateEmptyBlockJob = true; LOG(INFO) << "--------update last empty block job--------"; } if (!needUpdateEmptyBlockJob && !isRskUpdate && bestKey == lastSendBestKey) { LOG(WARNING) << "bestKey is the same as last one: " << lastSendBestKey; return false; } // The height cannot reduce in normal. // However, if there is indeed a height reduce, // isReachTimeout() will allow the new job sending. if (bestHeight > currBestHeight_) { LOG(INFO) << ">>>> found new best height: " << bestHeight << ", curr: " << currBestHeight_ << " <<<<"; isFindNewHeight = true; } if (isFindNewHeight || needUpdateEmptyBlockJob || isRskUpdate || isReachTimeout()) { lastSendBestKey = bestKey; currBestHeight_ = bestHeight; bestRawGbt = rawgbtMap_.rbegin()->second.c_str(); return true; } return false; } bool JobMakerHandlerBitcoin::isReachTimeout() { uint32_t intervalSeconds = def_.jobInterval_; if (lastJobSendTime_ + intervalSeconds <= time(nullptr)) { return true; } return false; } void JobMakerHandlerBitcoin::clearTimeoutGbt() { // Maps (and sets) are sorted, so the first element is the smallest, // and the last element is the largest. const uint32_t ts_now = time(nullptr); for (auto itr = rawgbtMap_.begin(); itr != rawgbtMap_.end(); ) { const uint32_t ts = gbtKeyGetTime(itr->first); const bool isEmpty = gbtKeyIsEmptyBlock(itr->first); const uint32_t height = gbtKeyGetHeight(itr->first); // gbt expired time const uint32_t expiredTime = ts + (isEmpty ? def_.emptyGbtLifeTime_ : def_.gbtLifeTime_); if (expiredTime > ts_now) { // not expired ++itr; } else { // remove expired gbt LOG(INFO) << "remove timeout rawgbt: " << date("%F %T", ts) << "|" << ts << ", height:" << height << ", isEmptyBlock:" << (isEmpty ? 1 : 0); // c++11: returns an iterator to the next element in the map itr = rawgbtMap_.erase(itr); } } } void JobMakerHandlerBitcoin::clearTimeoutRskGw() { RskWork currentRskWork; RskWork previousRskWork; { ScopeLock sl(rskWorkAccessLock_); if (previousRskWork_ == nullptr || currentRskWork_ == nullptr) { return; } const uint32_t ts_now = time(nullptr); currentRskWork = *currentRskWork_; if(currentRskWork.getCreatedAt() + 120u < ts_now) { delete currentRskWork_; currentRskWork_ = nullptr; } previousRskWork = *previousRskWork_; if(previousRskWork.getCreatedAt() + 120u < ts_now) { delete previousRskWork_; previousRskWork_ = nullptr; } } } bool JobMakerHandlerBitcoin::triggerRskUpdate() { RskWork currentRskWork; RskWork previousRskWork; { ScopeLock sl(rskWorkAccessLock_); if (previousRskWork_ == nullptr || currentRskWork_ == nullptr) { return false; } currentRskWork = *currentRskWork_; previousRskWork = *previousRskWork_; } bool notify_flag_update = def_.rskNotifyPolicy_ == 1 && currentRskWork.getNotifyFlag(); bool different_block_hashUpdate = def_.rskNotifyPolicy_ == 2 && (currentRskWork.getBlockHash() != previousRskWork.getBlockHash()); return notify_flag_update || different_block_hashUpdate; } bool JobMakerHandlerBitcoin::processRawGbtMsg(const string &msg) { return addRawGbt(msg); } bool JobMakerHandlerBitcoin::processAuxPowMsg(const string &msg) { // set json string { ScopeLock sl(auxJsonLock_); latestAuxPowJson_ = msg; DLOG(INFO) << "latestAuxPowJson: " << latestAuxPowJson_; } // auxpow message will nerver triggered a stratum job updating return false; } bool JobMakerHandlerBitcoin::processRskGwMsg(const string &rawGetWork) { // set json string { ScopeLock sl(rskWorkAccessLock_); RskWork *rskWork = new RskWork(); if(rskWork->initFromGw(rawGetWork)) { if (previousRskWork_ != nullptr) { delete previousRskWork_; previousRskWork_ = nullptr; } previousRskWork_ = currentRskWork_; currentRskWork_ = rskWork; DLOG(INFO) << "currentRskBlockJson: " << rawGetWork; } else { delete rskWork; } } isRskUpdate_ = triggerRskUpdate(); return isRskUpdate_; } string JobMakerHandlerBitcoin::makeStratumJob(const string &gbt) { string latestAuxPowJson; { ScopeLock sl(auxJsonLock_); latestAuxPowJson = latestAuxPowJson_; } RskWork currentRskBlockJson; { ScopeLock sl(rskWorkAccessLock_); if (currentRskWork_ != nullptr) { currentRskBlockJson = *currentRskWork_; } } StratumJob sjob; if (!sjob.initFromGbt(gbt.c_str(), def_.coinbaseInfo_, poolPayoutAddr_, def_.blockVersion_, latestAuxPowJson, currentRskBlockJson)) { LOG(ERROR) << "init stratum job message from gbt str fail"; return ""; } const string jobMsg = sjob.serializeToJson(); // set last send time // TODO: fix Y2K38 issue lastJobSendTime_ = (uint32_t)time(nullptr); // is an empty block job isLastJobEmptyBlock_ = sjob.isEmptyBlock(); LOG(INFO) << "--------producer stratum job, jobId: " << sjob.jobId_ << ", height: " << sjob.height_ << "--------"; LOG(INFO) << "sjob: " << jobMsg; return jobMsg; } string JobMakerHandlerBitcoin::makeStratumJobMsg() { string bestRawGbt; if (!findBestRawGbt(isRskUpdate_, bestRawGbt)) { return ""; } isRskUpdate_ = false; return makeStratumJob(bestRawGbt); } uint64_t JobMakerHandlerBitcoin::makeGbtKey(uint32_t gbtTime, bool isEmptyBlock, uint32_t height) { assert(height < 0x7FFFFFFFU); // // gbtKey: // ----------------------------------------------------------------------------------------- // | 32 bits | 31 bits | 1 bit | // | xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx | xxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx | x | // | gbtTime | height | nonEmptyFlag | // ----------------------------------------------------------------------------------------- // use nonEmptyFlag (aka: !isEmptyBlock) so the key of a non-empty block // will large than the key of an empty block. // return (((uint64_t)gbtTime) << 32) | (((uint64_t)height) << 1) | ((uint64_t)(!isEmptyBlock)); } uint32_t JobMakerHandlerBitcoin::gbtKeyGetTime(uint64_t gbtKey) { return (uint32_t)(gbtKey >> 32); } uint32_t JobMakerHandlerBitcoin::gbtKeyGetHeight(uint64_t gbtKey) { return (uint32_t)((gbtKey >> 1) & 0x7FFFFFFFULL); } bool JobMakerHandlerBitcoin::gbtKeyIsEmptyBlock(uint64_t gbtKey) { return !((bool)(gbtKey & 1ULL)); }
30.909187
148
0.633084
ganibc
429bea5784defe29e1b8e7814008c928eec35630
532
cpp
C++
COURSE_WHITE/WEEK_2/FUNCTION/Maximizator/main.cpp
diekaltesonne/c-plus-plus-modern-development
d569bd20465e76aab97111bcd316cd02ebca41dd
[ "MIT" ]
null
null
null
COURSE_WHITE/WEEK_2/FUNCTION/Maximizator/main.cpp
diekaltesonne/c-plus-plus-modern-development
d569bd20465e76aab97111bcd316cd02ebca41dd
[ "MIT" ]
null
null
null
COURSE_WHITE/WEEK_2/FUNCTION/Maximizator/main.cpp
diekaltesonne/c-plus-plus-modern-development
d569bd20465e76aab97111bcd316cd02ebca41dd
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; /* *Напишите функцию UpdateIfGreater, которая принимает два целочисленных аргумента: first и second. *Если first оказался больше second, Ваша функция должна записывать в second значение параметра first. * При этом указанная функция не должна ничего возвращать, а изменение параметра second должно быть видно на вызывающей стороне. */ //void UpdateIfgreater(int & a, int& b ); int main() { return 0; } void UpdateIfGreater(int a, int& b) { if (a > b) { b = a; } }
24.181818
128
0.714286
diekaltesonne
429d0615f39c89daee4ce5a114d49518a0210c93
2,191
cpp
C++
code/core/chattablabel.cpp
detrax/gobby
21160017e1f7ffe1123d80acadac88a22bd7f838
[ "ISC" ]
542
2015-01-03T21:43:38.000Z
2022-03-26T11:43:54.000Z
code/core/chattablabel.cpp
detrax/gobby
21160017e1f7ffe1123d80acadac88a22bd7f838
[ "ISC" ]
116
2015-01-14T08:08:43.000Z
2021-08-03T19:24:46.000Z
code/core/chattablabel.cpp
detrax/gobby
21160017e1f7ffe1123d80acadac88a22bd7f838
[ "ISC" ]
60
2015-01-03T21:43:42.000Z
2022-03-19T12:04:52.000Z
/* Gobby - GTK-based collaborative text editor * Copyright (C) 2008-2015 Armin Burgmeier <armin@arbur.net> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "core/chattablabel.hpp" Gobby::ChatTabLabel::ChatTabLabel(Folder& folder, ChatSessionView& view, bool always_show_close_button): TabLabel(folder, view, always_show_close_button ? "chat" : "network-idle"), m_always_show_close_button(always_show_close_button) { if(!m_always_show_close_button) m_button.hide(); // Only show when disconnected InfChatBuffer* buffer = INF_CHAT_BUFFER( inf_session_get_buffer(INF_SESSION(view.get_session()))); m_add_message_handle = g_signal_connect_after( G_OBJECT(buffer), "add-message", G_CALLBACK(on_add_message_static), this); } Gobby::ChatTabLabel::~ChatTabLabel() { InfChatBuffer* buffer = INF_CHAT_BUFFER( inf_session_get_buffer(INF_SESSION(m_view.get_session()))); g_signal_handler_disconnect(buffer, m_add_message_handle); } void Gobby::ChatTabLabel::on_notify_subscription_group() { InfSession* session = INF_SESSION(m_view.get_session()); if(inf_session_get_subscription_group(session) != NULL && !m_always_show_close_button) { m_button.hide(); } else { m_button.show(); } } void Gobby::ChatTabLabel::on_changed(InfUser* author) { if(!m_changed) { InfSession* session = INF_SESSION(m_view.get_session()); if(inf_session_get_status(session) == INF_SESSION_RUNNING) set_changed(); } }
31.753623
75
0.74806
detrax
42a78b36f1ed4f5b61e6d008cc12cbd9eb5cb7b9
1,087
cpp
C++
C++/010_Regular_Expression_Matching.cpp
stephenkid/LeetCode-Sol
8cb429652e0741ca4078b6de5f9eeaddcb8607a8
[ "MIT" ]
1,958
2015-01-30T01:19:03.000Z
2022-03-17T03:34:47.000Z
src/main/cpp/010_Regular_Expression_Matching.cpp
TechnoBlogger14o3/LeetCode-Sol-Res
04621f21a76fab29909c1fa04a37417257a88f63
[ "MIT" ]
135
2016-03-03T04:53:10.000Z
2022-03-03T21:14:37.000Z
src/main/cpp/010_Regular_Expression_Matching.cpp
TechnoBlogger14o3/LeetCode-Sol-Res
04621f21a76fab29909c1fa04a37417257a88f63
[ "MIT" ]
914
2015-01-27T22:27:22.000Z
2022-03-05T04:25:10.000Z
//10. Regular Expression Matching /* '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). The function prototype should be: bool isMatch(const char *s, const char *p) Some examples: isMatch("aa","a") → false isMatch("aa","aa") → true isMatch("aaa","aa") → false isMatch("aa", "a*") → true isMatch("aa", ".*") → true isMatch("ab", ".*") → true isMatch("aab", "c*a*b") → true Tag: Dynamic Programming, Backtracking, String Author: Xinyu Liu */ #include <iostream> #include <string> using namespace std; class Solution{ public: bool isMatch(string s, string p){ if (p.empty()) return s.empty(); if (p[1] == '*') return ((!s.empty() && (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1),p))|| isMatch(s,p.substr(2))); else return (!s.empty() && (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1),p.substr(1))); } }; void main(){ string s ("aaa"); string p ("a*"); Solution sol; bool b = sol.isMatch(s,p); }
22.183673
118
0.581417
stephenkid
42a8d987cbe42d8674866946c625ae148a31e200
730
cpp
C++
tests/data_structure/test_quad_tree.cpp
mitthy/TCC
4c48eb11cafd50334c5faef93edc5f03bc7fc171
[ "MIT" ]
null
null
null
tests/data_structure/test_quad_tree.cpp
mitthy/TCC
4c48eb11cafd50334c5faef93edc5f03bc7fc171
[ "MIT" ]
null
null
null
tests/data_structure/test_quad_tree.cpp
mitthy/TCC
4c48eb11cafd50334c5faef93edc5f03bc7fc171
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "geometricks/data_structure/quad_tree.hpp" #include <tuple> #include <type_traits> struct element_t { int x, y, hw, hh; }; namespace geometricks { namespace rectangle_customization { template<> struct make_rectangle<element_t> { static constexpr geometricks::rectangle _( const element_t& value ) { return { value.x, value.y, value.hw, value.hh }; } }; } } TEST( TestQuadTree, TestCreation ) { geometricks::quad_tree<std::tuple<int,int,int,int>> tree{ geometricks::rectangle{ -1000, -1000, 2000, 2000 } }; for( int i = 0; i < 256; ++i ) { tree.insert( std::make_tuple( ( i + 5 ) * 2, ( i + 5 ) * 2, 10, 10 ) ); } }
21.470588
113
0.610959
mitthy
42a8e775526ada85918d187049907b4bfbaa8ac9
13,240
hpp
C++
src/xpcc/architecture/platform/cortex_m3/stm32/stm32f4/sdio/sdio_hal.hpp
walmis/xpcc
1d87c4434530c6aeac923f57d379aeaf32e11e1e
[ "BSD-3-Clause" ]
null
null
null
src/xpcc/architecture/platform/cortex_m3/stm32/stm32f4/sdio/sdio_hal.hpp
walmis/xpcc
1d87c4434530c6aeac923f57d379aeaf32e11e1e
[ "BSD-3-Clause" ]
null
null
null
src/xpcc/architecture/platform/cortex_m3/stm32/stm32f4/sdio/sdio_hal.hpp
walmis/xpcc
1d87c4434530c6aeac923f57d379aeaf32e11e1e
[ "BSD-3-Clause" ]
null
null
null
/* * sdio.hpp * * Created on: Apr 20, 2015 * Author: walmis */ #ifndef SRC_XPCC_ARCHITECTURE_PLATFORM_CORTEX_M3_STM32_STM32F4_SDIO_SDIO_HPP_ #define SRC_XPCC_ARCHITECTURE_PLATFORM_CORTEX_M3_STM32_STM32F4_SDIO_SDIO_HPP_ #include "../../../stm32.hpp" namespace xpcc { namespace stm32 { /* ---------------------- SDIO registers bit mask ------------------------ */ /* --- CLKCR Register ---*/ /* CLKCR register clear mask */ #define CLKCR_CLEAR_MASK ((uint32_t)0xFFFF8100) /* --- PWRCTRL Register ---*/ /* SDIO PWRCTRL Mask */ #define PWR_PWRCTRL_MASK ((uint32_t)0xFFFFFFFC) /* --- DCTRL Register ---*/ /* SDIO DCTRL Clear Mask */ #define DCTRL_CLEAR_MASK ((uint32_t)0xFFFFFF08) /* --- CMD Register ---*/ /* CMD Register clear mask */ #define CMD_CLEAR_MASK ((uint32_t)0xFFFFF800) /* SDIO RESP Registers Address */ #define SDIO_RESP_ADDR ((uint32_t)(SDIO_BASE + 0x14)) /* ------------ SDIO registers bit address in the alias region ----------- */ #define SDIO_OFFSET (SDIO_BASE - PERIPH_BASE) #define SDIO_CPSM_Disable ((uint32_t)0x00000000) #define SDIO_CPSM_Enable ((uint32_t)0x00000400) /* --- CLKCR Register ---*/ /* Alias word address of CLKEN bit */ #define CLKCR_OFFSET (SDIO_OFFSET + 0x04) #define CLKEN_BitNumber 0x08 #define CLKCR_CLKEN_BB (PERIPH_BB_BASE + (CLKCR_OFFSET * 32) + (CLKEN_BitNumber * 4)) /* --- CMD Register ---*/ /* Alias word address of SDIOSUSPEND bit */ #define CMD_OFFSET (SDIO_OFFSET + 0x0C) #define SDIOSUSPEND_BitNumber 0x0B #define CMD_SDIOSUSPEND_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (SDIOSUSPEND_BitNumber * 4)) /* Alias word address of ENCMDCOMPL bit */ #define ENCMDCOMPL_BitNumber 0x0C #define CMD_ENCMDCOMPL_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (ENCMDCOMPL_BitNumber * 4)) /* Alias word address of NIEN bit */ #define NIEN_BitNumber 0x0D #define CMD_NIEN_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (NIEN_BitNumber * 4)) /* Alias word address of ATACMD bit */ #define ATACMD_BitNumber 0x0E #define CMD_ATACMD_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (ATACMD_BitNumber * 4)) /* --- DCTRL Register ---*/ /* Alias word address of DMAEN bit */ #define DCTRL_OFFSET (SDIO_OFFSET + 0x2C) #define DMAEN_BitNumber 0x03 #define DCTRL_DMAEN_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (DMAEN_BitNumber * 4)) /* Alias word address of RWSTART bit */ #define RWSTART_BitNumber 0x08 #define DCTRL_RWSTART_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWSTART_BitNumber * 4)) /* Alias word address of RWSTOP bit */ #define RWSTOP_BitNumber 0x09 #define DCTRL_RWSTOP_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWSTOP_BitNumber * 4)) /* Alias word address of RWMOD bit */ #define RWMOD_BitNumber 0x0A #define DCTRL_RWMOD_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWMOD_BitNumber * 4)) /* Alias word address of SDIOEN bit */ #define SDIOEN_BitNumber 0x0B #define DCTRL_SDIOEN_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (SDIOEN_BitNumber * 4)) class SDIO_HAL { public: enum class ClockEdge { Rising = ((uint32_t) 0x00000000), Falling = ((uint32_t) 0x00002000) }; enum class ClockFlags { None = 0x00, Bypass = 0x400, PowerSave = 0x200 }; enum class BusWidth { _1b = 0x00, _4b = 0x800, _8b = 0x1000 }; enum class HardwareFlowControl { Disable = 0x00, Enable = 0x4000 }; enum class PowerState { Off = 0x00, On = 0x03 }; /** @defgroup SDIO_Interrupt_sources * @{ */ enum Interrupt { CCRCFAIL = ((uint32_t) 0x00000001), DCRCFAIL = ((uint32_t) 0x00000002), CTIMEOUT = ((uint32_t) 0x00000004), DTIMEOUT = ((uint32_t) 0x00000008), TXUNDERR = ((uint32_t) 0x00000010), RXOVERR = ((uint32_t) 0x00000020), CMDREND = ((uint32_t) 0x00000040), CMDSENT = ((uint32_t) 0x00000080), DATAEND = ((uint32_t) 0x00000100), STBITERR = ((uint32_t) 0x00000200), DBCKEND = ((uint32_t) 0x00000400), CMDACT = ((uint32_t) 0x00000800), TXACT = ((uint32_t) 0x00001000), RXACT = ((uint32_t) 0x00002000), TXFIFOHE = ((uint32_t) 0x00004000), RXFIFOHF = ((uint32_t) 0x00008000), TXFIFOF = ((uint32_t) 0x00010000), RXFIFOF = ((uint32_t) 0x00020000), TXFIFOE = ((uint32_t) 0x00040000), RXFIFOE = ((uint32_t) 0x00080000), TXDAVL = ((uint32_t) 0x00100000), RXDAVL = ((uint32_t) 0x00200000), SDIOIT = ((uint32_t) 0x00400000), CEATAEND = ((uint32_t) 0x00800000) }; #define IS_SDIO_IT(IT) ((((IT) & (uint32_t)0xFF000000) == 0x00) && ((IT) != (uint32_t)0x00)) /** * @} */ /** @defgroup SDIO_Command_Index * @{ */ #define IS_SDIO_CMD_INDEX(INDEX) ((INDEX) < 0x40) enum class ResponseType { None = 0, Short = 0x40, Long = 0xC0 }; /** @defgroup SDIO_Wait_Interrupt_State * @{ */ enum class SDIOWait { NoWait = 0, WaitIT = 0x100, WaitPend = 0x200 }; enum class CPSM { Disable = 0x00, Enable = 0x400 }; enum class SDIOResp { RESP1 = ((uint32_t) 0x00000000), RESP2 = ((uint32_t) 0x00000004), RESP3 = ((uint32_t) 0x00000008), RESP4 = ((uint32_t) 0x0000000C) }; enum class DataBlockSize { _1b = ((uint32_t) 0x00000000), _2b = ((uint32_t) 0x00000010), _4b = ((uint32_t) 0x00000020), _8b = ((uint32_t) 0x00000030), _16b = ((uint32_t) 0x00000040), _32b = ((uint32_t) 0x00000050), _64b = ((uint32_t) 0x00000060), _128b = ((uint32_t) 0x00000070), _256b = ((uint32_t) 0x00000080), _512b = ((uint32_t) 0x00000090), _1024b = ((uint32_t) 0x000000A0), _2048b = ((uint32_t) 0x000000B0), _4096b = ((uint32_t) 0x000000C0), _8192b = ((uint32_t) 0x000000D0), _16384b = ((uint32_t) 0x000000E0) }; enum class TransferDir { ToCard = 0x00, ToSDIO = 0x02 }; enum class TransferMode { Block = 0x0, Stream = 0x04 }; enum class DPSM { Disable = 0, Enable = 1 }; enum ReadWaitMode { CLK = 0x0, DATA2 = 0x01 }; static inline void init() { RCC->APB2ENR |= RCC_APB2ENR_SDIOEN; uint32_t tmpreg; /* Get the SDIO CLKCR value */ tmpreg = SDIO->CLKCR; /* Clear CLKDIV, PWRSAV, BYPASS, WIDBUS, NEGEDGE, HWFC_EN bits */ tmpreg &= CLKCR_CLEAR_MASK; /* Set CLKDIV bits according to SDIO_ClockDiv value */ /* Set PWRSAV bit according to SDIO_ClockPowerSave value */ /* Set BYPASS bit according to SDIO_ClockBypass value */ /* Set WIDBUS bits according to SDIO_BusWide value */ /* Set NEGEDGE bits according to SDIO_ClockEdge value */ /* Set HWFC_EN bits according to SDIO_HardwareFlowControl value */ tmpreg |= (uint32_t) ClockFlags::None | (uint32_t) BusWidth::_1b | (uint32_t) ClockEdge::Rising | (uint32_t) HardwareFlowControl::Disable; /* Write to SDIO CLKCR */ SDIO->CLKCR = tmpreg; } static inline void setClockFlags(ClockFlags flags) { SDIO->CLKCR &= ~((1 << 9) | (1 << 10)); SDIO->CLKCR |= (uint32_t) flags; } static inline void setClockEdge(ClockEdge edge) { SDIO->CLKCR &= ~((1 << 13)); SDIO->CLKCR |= (uint32_t) edge; } static inline void setClockDiv(uint8_t div) { SDIO->CLKCR &= ~0xFF; SDIO->CLKCR |= (uint32_t) div; } static inline void setBusWidth(BusWidth bw) { SDIO->CLKCR &= ~((1 << 11) | (1 << 12)); SDIO->CLKCR |= (uint32_t) bw; } static inline void setHardwareFlowControl(HardwareFlowControl fc) { SDIO->CLKCR &= ~((1 << 14)); SDIO->CLKCR |= (uint32_t) fc; } static inline void setClockState(bool state) { *(__IO uint32_t *) CLKCR_CLKEN_BB = (uint32_t) state; } static inline void setPowerState(PowerState state = PowerState::On) { SDIO->POWER = (uint32_t) state; } static inline PowerState getPowerState() { return (PowerState) SDIO->POWER; } static inline void sendCommand(uint32_t argument, uint32_t cmdindex, ResponseType resptype, SDIOWait wait = SDIOWait::NoWait) { uint32_t tmpreg; /*---------------------------- SDIO ARG Configuration ------------------------*/ /* Set the SDIO Argument value */ SDIO->ARG = argument; /*---------------------------- SDIO CMD Configuration ------------------------*/ /* Get the SDIO CMD value */ tmpreg = SDIO->CMD; /* Clear CMDINDEX, WAITRESP, WAITINT, WAITPEND, CPSMEN bits */ tmpreg &= CMD_CLEAR_MASK; /* Set CMDINDEX bits according to SDIO_CmdIndex value */ /* Set WAITRESP bits according to SDIO_Response value */ /* Set WAITINT and WAITPEND bits according to SDIO_Wait value */ /* Set CPSMEN bits according to SDIO_CPSM value */ tmpreg |= ((uint32_t) cmdindex & SDIO_CMD_CMDINDEX) | ((uint32_t) resptype & SDIO_CMD_WAITRESP) | (uint32_t) wait | SDIO_CPSM_Enable; /* Write to SDIO CMD */ SDIO->CMD = tmpreg; } static inline uint8_t getCommandResponse() { return (uint8_t) (SDIO->RESPCMD); } static inline uint32_t getResponse(SDIOResp resp) { __IO uint32_t tmp = 0; tmp = SDIO_RESP_ADDR + (uint32_t) resp; return (*(__IO uint32_t *) tmp); } static inline void startDataTransaction(TransferDir dir, uint32_t length, TransferMode mode = TransferMode::Block, DataBlockSize bs = DataBlockSize::_512b, uint32_t timeout = 0xFFFFFFFF) { uint32_t tmpreg; /* Set the SDIO Data TimeOut value */ SDIO->DTIMER = timeout; /*---------------------------- SDIO DLEN Configuration -----------------------*/ /* Set the SDIO DataLength value */ SDIO->DLEN = length; /*---------------------------- SDIO DCTRL Configuration ----------------------*/ /* Get the SDIO DCTRL value */ tmpreg = SDIO->DCTRL; /* Clear DEN, DTMODE, DTDIR and DBCKSIZE bits */ tmpreg &= DCTRL_CLEAR_MASK; /* Set DEN bit according to SDIO_DPSM value */ /* Set DTMODE bit according to SDIO_TransferMode value */ /* Set DTDIR bit according to SDIO_TransferDir value */ /* Set DBCKSIZE bits according to SDIO_DataBlockSize value */ tmpreg |= (uint32_t) bs | (uint32_t) dir | (uint32_t) mode | 0x01; /* Write to SDIO DCTRL */ SDIO->DCTRL = tmpreg; } static inline void resetDataPath() { SDIO->DCTRL = 0; } static inline void resetCommandPath() { SDIO->CMD = 0; } static inline uint32_t getDataCounter(void) { return SDIO->DCOUNT; } static inline uint32_t readData(void) { return SDIO->FIFO; } static inline void writeData(uint32_t Data) { SDIO->FIFO = Data; } static inline uint32_t getFIFOCount(void) { return SDIO->FIFOCNT; } /** * @brief Starts the SD I/O Read Wait operation. * @param NewState: new state of the Start SDIO Read Wait operation. * This parameter can be: ENABLE or DISABLE. * @retval None */ static inline void startSDIOReadWait(bool NewState) { *(__IO uint32_t *) DCTRL_RWSTART_BB = (uint32_t) NewState; } /** * @brief Stops the SD I/O Read Wait operation. * @param NewState: new state of the Stop SDIO Read Wait operation. * This parameter can be: ENABLE or DISABLE. * @retval None */ static inline void stopSDIOReadWait(bool NewState) { *(__IO uint32_t *) DCTRL_RWSTOP_BB = (uint32_t) NewState; } /** * @brief Sets one of the two options of inserting read wait interval. * @param SDIO_ReadWaitMode: SD I/O Read Wait operation mode. * This parameter can be: * @arg SDIO_ReadWaitMode_CLK: Read Wait control by stopping SDIOCLK * @arg SDIO_ReadWaitMode_DATA2: Read Wait control using SDIO_DATA2 * @retval None */ static inline void setSDIOReadWaitMode(ReadWaitMode SDIO_ReadWaitMode) { *(__IO uint32_t *) DCTRL_RWMOD_BB = (uint32_t) SDIO_ReadWaitMode; } /** * @brief Enables or disables the SD I/O Mode Operation. * @param NewState: new state of SDIO specific operation. * This parameter can be: ENABLE or DISABLE. * @retval None */ static inline void setSDIOOperation(bool NewState) { *(__IO uint32_t *) DCTRL_SDIOEN_BB = (uint32_t) NewState; } /** * @brief Enables or disables the SD I/O Mode suspend command sending. * @param NewState: new state of the SD I/O Mode suspend command. * This parameter can be: ENABLE or DISABLE. * @retval None */ static inline void sendSDIOSuspendCmd(bool NewState) { *(__IO uint32_t *) CMD_SDIOSUSPEND_BB = (uint32_t) NewState; } /** * @brief Enables or disables the SDIO DMA request. * @param NewState: new state of the selected SDIO DMA request. * This parameter can be: ENABLE or DISABLE. * @retval None */ static inline void DMACmd(bool enable) { *(__IO uint32_t *) DCTRL_DMAEN_BB = (uint32_t) enable; } static inline void setInterruptMask(Interrupt it) { SDIO->MASK = (uint32_t) it; } static inline void interruptConfig(Interrupt it, bool NewState) { if (NewState) { /* Enable the SDIO interrupts */ SDIO->MASK |= (uint32_t) it; } else { /* Disable the SDIO interrupts */ SDIO->MASK &= ~(uint32_t) it; } } static inline uint32_t getInterruptFlags() { return SDIO->STA; } static inline bool getInterruptStatus(Interrupt it) { if ((SDIO->STA & (uint32_t) it)) { return true; } else { return false; } } static inline void clearInterrupt(Interrupt it) { SDIO->ICR = (uint32_t) it; } }; ENUM_CLASS_FLAG(SDIO_HAL::Interrupt); } } #endif /* SRC_XPCC_ARCHITECTURE_PLATFORM_CORTEX_M3_STM32_STM32F4_SDIO_SDIO_HPP_ */
28.908297
115
0.656193
walmis
42a9208251f39477bf054939e4474f914c29221c
18,316
cpp
C++
rclcpp/src/rclcpp/time_source.cpp
RTI-BDI/rclcpp
c29a916429285362d4d8072b698b6c200d1d2a37
[ "Apache-2.0" ]
1
2022-02-28T21:29:12.000Z
2022-02-28T21:29:12.000Z
rclcpp/src/rclcpp/time_source.cpp
stokekld/rclcpp
025cd5ccc8202a52f7c7a3f037d8faf46f7dc3f3
[ "Apache-2.0" ]
null
null
null
rclcpp/src/rclcpp/time_source.cpp
stokekld/rclcpp
025cd5ccc8202a52f7c7a3f037d8faf46f7dc3f3
[ "Apache-2.0" ]
null
null
null
// Copyright 2017 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include <string> #include <utility> #include <vector> #include "builtin_interfaces/msg/time.hpp" #include "rcl/time.h" #include "rclcpp/clock.hpp" #include "rclcpp/exceptions.hpp" #include "rclcpp/logging.hpp" #include "rclcpp/node.hpp" #include "rclcpp/parameter_client.hpp" #include "rclcpp/parameter_events_filter.hpp" #include "rclcpp/time.hpp" #include "rclcpp/time_source.hpp" namespace rclcpp { class ClocksState final { public: ClocksState() : logger_(rclcpp::get_logger("rclcpp")) { } // An internal method to use in the clock callback that iterates and enables all clocks void enable_ros_time() { if (ros_time_active_) { // already enabled no-op return; } // Local storage ros_time_active_ = true; // Update all attached clocks to zero or last recorded time std::lock_guard<std::mutex> guard(clock_list_lock_); auto time_msg = std::make_shared<builtin_interfaces::msg::Time>(); if (last_msg_set_) { time_msg = std::make_shared<builtin_interfaces::msg::Time>(last_msg_set_->clock); } for (auto it = associated_clocks_.begin(); it != associated_clocks_.end(); ++it) { set_clock(time_msg, true, *it); } } // An internal method to use in the clock callback that iterates and disables all clocks void disable_ros_time() { if (!ros_time_active_) { // already disabled no-op return; } // Local storage ros_time_active_ = false; // Update all attached clocks std::lock_guard<std::mutex> guard(clock_list_lock_); for (auto it = associated_clocks_.begin(); it != associated_clocks_.end(); ++it) { auto msg = std::make_shared<builtin_interfaces::msg::Time>(); set_clock(msg, false, *it); } } // Check if ROS time is active bool is_ros_time_active() const { return ros_time_active_; } // Attach a clock void attachClock(rclcpp::Clock::SharedPtr clock) { if (clock->get_clock_type() != RCL_ROS_TIME) { throw std::invalid_argument("Cannot attach clock to a time source that's not a ROS clock"); } std::lock_guard<std::mutex> guard(clock_list_lock_); associated_clocks_.push_back(clock); // Set the clock to zero unless there's a recently received message auto time_msg = std::make_shared<builtin_interfaces::msg::Time>(); if (last_msg_set_) { time_msg = std::make_shared<builtin_interfaces::msg::Time>(last_msg_set_->clock); } set_clock(time_msg, ros_time_active_, clock); } // Detach a clock void detachClock(rclcpp::Clock::SharedPtr clock) { std::lock_guard<std::mutex> guard(clock_list_lock_); auto result = std::find(associated_clocks_.begin(), associated_clocks_.end(), clock); if (result != associated_clocks_.end()) { associated_clocks_.erase(result); } else { RCLCPP_ERROR(logger_, "failed to remove clock"); } } // Internal helper function used inside iterators static void set_clock( const builtin_interfaces::msg::Time::SharedPtr msg, bool set_ros_time_enabled, rclcpp::Clock::SharedPtr clock) { std::lock_guard<std::mutex> clock_guard(clock->get_clock_mutex()); // Do change if (!set_ros_time_enabled && clock->ros_time_is_active()) { auto ret = rcl_disable_ros_time_override(clock->get_clock_handle()); if (ret != RCL_RET_OK) { rclcpp::exceptions::throw_from_rcl_error( ret, "Failed to disable ros_time_override_status"); } } else if (set_ros_time_enabled && !clock->ros_time_is_active()) { auto ret = rcl_enable_ros_time_override(clock->get_clock_handle()); if (ret != RCL_RET_OK) { rclcpp::exceptions::throw_from_rcl_error( ret, "Failed to enable ros_time_override_status"); } } auto ret = rcl_set_ros_time_override( clock->get_clock_handle(), rclcpp::Time(*msg).nanoseconds()); if (ret != RCL_RET_OK) { rclcpp::exceptions::throw_from_rcl_error( ret, "Failed to set ros_time_override_status"); } } // Internal helper function void set_all_clocks( const builtin_interfaces::msg::Time::SharedPtr msg, bool set_ros_time_enabled) { std::lock_guard<std::mutex> guard(clock_list_lock_); for (auto it = associated_clocks_.begin(); it != associated_clocks_.end(); ++it) { set_clock(msg, set_ros_time_enabled, *it); } } // Cache the last clock message received void cache_last_msg(std::shared_ptr<const rosgraph_msgs::msg::Clock> msg) { last_msg_set_ = msg; } private: // Store (and update on node attach) logger for logging. Logger logger_; // A lock to protect iterating the associated_clocks_ field. std::mutex clock_list_lock_; // A vector to store references to associated clocks. std::vector<rclcpp::Clock::SharedPtr> associated_clocks_; // Local storage of validity of ROS time // This is needed when new clocks are added. bool ros_time_active_{false}; // Last set message to be passed to newly registered clocks std::shared_ptr<const rosgraph_msgs::msg::Clock> last_msg_set_; }; class TimeSource::NodeState final { public: NodeState(const rclcpp::QoS & qos, bool use_clock_thread) : use_clock_thread_(use_clock_thread), logger_(rclcpp::get_logger("rclcpp")), qos_(qos) { } ~NodeState() { if ( node_base_ || node_topics_ || node_graph_ || node_services_ || node_logging_ || node_clock_ || node_parameters_) { detachNode(); } } // Check if a clock thread will be used bool get_use_clock_thread() { return use_clock_thread_; } // Set whether a clock thread will be used void set_use_clock_thread(bool use_clock_thread) { use_clock_thread_ = use_clock_thread; } // Check if the clock thread is joinable bool clock_thread_is_joinable() { return clock_executor_thread_.joinable(); } // Attach a node to this time source void attachNode( rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base_interface, rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr node_topics_interface, rclcpp::node_interfaces::NodeGraphInterface::SharedPtr node_graph_interface, rclcpp::node_interfaces::NodeServicesInterface::SharedPtr node_services_interface, rclcpp::node_interfaces::NodeLoggingInterface::SharedPtr node_logging_interface, rclcpp::node_interfaces::NodeClockInterface::SharedPtr node_clock_interface, rclcpp::node_interfaces::NodeParametersInterface::SharedPtr node_parameters_interface) { node_base_ = node_base_interface; node_topics_ = node_topics_interface; node_graph_ = node_graph_interface; node_services_ = node_services_interface; node_logging_ = node_logging_interface; node_clock_ = node_clock_interface; node_parameters_ = node_parameters_interface; // TODO(tfoote): Update QOS logger_ = node_logging_->get_logger(); // Though this defaults to false, it can be overridden by initial parameter values for the // node, which may be given by the user at the node's construction or even by command-line // arguments. rclcpp::ParameterValue use_sim_time_param; const std::string use_sim_time_name = "use_sim_time"; if (!node_parameters_->has_parameter(use_sim_time_name)) { use_sim_time_param = node_parameters_->declare_parameter( use_sim_time_name, rclcpp::ParameterValue(false)); } else { use_sim_time_param = node_parameters_->get_parameter(use_sim_time_name).get_parameter_value(); } if (use_sim_time_param.get_type() == rclcpp::PARAMETER_BOOL) { if (use_sim_time_param.get<bool>()) { parameter_state_ = SET_TRUE; clocks_state_.enable_ros_time(); create_clock_sub(); } } else { RCLCPP_ERROR( logger_, "Invalid type '%s' for parameter 'use_sim_time', should be 'bool'", rclcpp::to_string(use_sim_time_param.get_type()).c_str()); throw std::invalid_argument("Invalid type for parameter 'use_sim_time', should be 'bool'"); } // TODO(tfoote) use parameters interface not subscribe to events via topic ticketed #609 parameter_subscription_ = rclcpp::AsyncParametersClient::on_parameter_event( node_topics_, [this](std::shared_ptr<const rcl_interfaces::msg::ParameterEvent> event) { if (node_base_ != nullptr) { this->on_parameter_event(event); } // Do nothing if node_base_ is nullptr because it means the TimeSource is now // without an attached node }); } // Detach the attached node void detachNode() { // destroy_clock_sub() *must* be first here, to ensure that the executor // can't possibly call any of the callbacks as we are cleaning up. destroy_clock_sub(); clocks_state_.disable_ros_time(); parameter_subscription_.reset(); node_base_.reset(); node_topics_.reset(); node_graph_.reset(); node_services_.reset(); node_logging_.reset(); node_clock_.reset(); node_parameters_.reset(); } void attachClock(std::shared_ptr<rclcpp::Clock> clock) { clocks_state_.attachClock(std::move(clock)); } void detachClock(std::shared_ptr<rclcpp::Clock> clock) { clocks_state_.detachClock(std::move(clock)); } private: ClocksState clocks_state_; // Dedicated thread for clock subscription. bool use_clock_thread_; std::thread clock_executor_thread_; // Preserve the node reference rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base_{nullptr}; rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr node_topics_{nullptr}; rclcpp::node_interfaces::NodeGraphInterface::SharedPtr node_graph_{nullptr}; rclcpp::node_interfaces::NodeServicesInterface::SharedPtr node_services_{nullptr}; rclcpp::node_interfaces::NodeLoggingInterface::SharedPtr node_logging_{nullptr}; rclcpp::node_interfaces::NodeClockInterface::SharedPtr node_clock_{nullptr}; rclcpp::node_interfaces::NodeParametersInterface::SharedPtr node_parameters_{nullptr}; // Store (and update on node attach) logger for logging. Logger logger_; // QoS of the clock subscription. rclcpp::QoS qos_; // The subscription for the clock callback using SubscriptionT = rclcpp::Subscription<rosgraph_msgs::msg::Clock>; std::shared_ptr<SubscriptionT> clock_subscription_{nullptr}; std::mutex clock_sub_lock_; rclcpp::CallbackGroup::SharedPtr clock_callback_group_; rclcpp::executors::SingleThreadedExecutor::SharedPtr clock_executor_; std::promise<void> cancel_clock_executor_promise_; // The clock callback itself void clock_cb(std::shared_ptr<const rosgraph_msgs::msg::Clock> msg) { if (!clocks_state_.is_ros_time_active() && SET_TRUE == this->parameter_state_) { clocks_state_.enable_ros_time(); } // Cache the last message in case a new clock is attached. clocks_state_.cache_last_msg(msg); auto time_msg = std::make_shared<builtin_interfaces::msg::Time>(msg->clock); if (SET_TRUE == this->parameter_state_) { clocks_state_.set_all_clocks(time_msg, true); } } // Create the subscription for the clock topic void create_clock_sub() { std::lock_guard<std::mutex> guard(clock_sub_lock_); if (clock_subscription_) { // Subscription already created. return; } rclcpp::SubscriptionOptions options; options.qos_overriding_options = rclcpp::QosOverridingOptions( { rclcpp::QosPolicyKind::Depth, rclcpp::QosPolicyKind::Durability, rclcpp::QosPolicyKind::History, rclcpp::QosPolicyKind::Reliability, }); if (use_clock_thread_) { clock_callback_group_ = node_base_->create_callback_group( rclcpp::CallbackGroupType::MutuallyExclusive, false ); options.callback_group = clock_callback_group_; rclcpp::ExecutorOptions exec_options; exec_options.context = node_base_->get_context(); clock_executor_ = std::make_shared<rclcpp::executors::SingleThreadedExecutor>(exec_options); if (!clock_executor_thread_.joinable()) { cancel_clock_executor_promise_ = std::promise<void>{}; clock_executor_thread_ = std::thread( [this]() { auto future = cancel_clock_executor_promise_.get_future(); clock_executor_->add_callback_group(clock_callback_group_, node_base_); clock_executor_->spin_until_future_complete(future); } ); } } clock_subscription_ = rclcpp::create_subscription<rosgraph_msgs::msg::Clock>( node_parameters_, node_topics_, "/clock", qos_, [this](std::shared_ptr<const rosgraph_msgs::msg::Clock> msg) { // We are using node_base_ as an indication if there is a node attached. // Only call the clock_cb if that is the case. if (node_base_ != nullptr) { clock_cb(msg); } }, options ); } // Destroy the subscription for the clock topic void destroy_clock_sub() { std::lock_guard<std::mutex> guard(clock_sub_lock_); if (clock_executor_thread_.joinable()) { cancel_clock_executor_promise_.set_value(); clock_executor_->cancel(); clock_executor_thread_.join(); clock_executor_->remove_callback_group(clock_callback_group_); } clock_subscription_.reset(); } // Parameter Event subscription using ParamSubscriptionT = rclcpp::Subscription<rcl_interfaces::msg::ParameterEvent>; std::shared_ptr<ParamSubscriptionT> parameter_subscription_; // Callback for parameter updates void on_parameter_event(std::shared_ptr<const rcl_interfaces::msg::ParameterEvent> event) { // Filter out events on 'use_sim_time' parameter instances in other nodes. if (event->node != node_base_->get_fully_qualified_name()) { return; } // Filter for only 'use_sim_time' being added or changed. rclcpp::ParameterEventsFilter filter(event, {"use_sim_time"}, {rclcpp::ParameterEventsFilter::EventType::NEW, rclcpp::ParameterEventsFilter::EventType::CHANGED}); for (auto & it : filter.get_events()) { if (it.second->value.type != ParameterType::PARAMETER_BOOL) { RCLCPP_ERROR(logger_, "use_sim_time parameter cannot be set to anything but a bool"); continue; } if (it.second->value.bool_value) { parameter_state_ = SET_TRUE; clocks_state_.enable_ros_time(); create_clock_sub(); } else { parameter_state_ = SET_FALSE; destroy_clock_sub(); clocks_state_.disable_ros_time(); } } // Handle the case that use_sim_time was deleted. rclcpp::ParameterEventsFilter deleted(event, {"use_sim_time"}, {rclcpp::ParameterEventsFilter::EventType::DELETED}); for (auto & it : deleted.get_events()) { (void) it; // if there is a match it's already matched, don't bother reading it. // If the parameter is deleted mark it as unset but don't change state. parameter_state_ = UNSET; } } // An enum to hold the parameter state enum UseSimTimeParameterState {UNSET, SET_TRUE, SET_FALSE}; UseSimTimeParameterState parameter_state_; }; TimeSource::TimeSource( std::shared_ptr<rclcpp::Node> node, const rclcpp::QoS & qos, bool use_clock_thread) : TimeSource(qos, use_clock_thread) { attachNode(node); } TimeSource::TimeSource( const rclcpp::QoS & qos, bool use_clock_thread) : constructed_use_clock_thread_(use_clock_thread), constructed_qos_(qos) { node_state_ = std::make_shared<NodeState>(qos, use_clock_thread); } void TimeSource::attachNode(rclcpp::Node::SharedPtr node) { node_state_->set_use_clock_thread(node->get_node_options().use_clock_thread()); attachNode( node->get_node_base_interface(), node->get_node_topics_interface(), node->get_node_graph_interface(), node->get_node_services_interface(), node->get_node_logging_interface(), node->get_node_clock_interface(), node->get_node_parameters_interface()); } void TimeSource::attachNode( rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base_interface, rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr node_topics_interface, rclcpp::node_interfaces::NodeGraphInterface::SharedPtr node_graph_interface, rclcpp::node_interfaces::NodeServicesInterface::SharedPtr node_services_interface, rclcpp::node_interfaces::NodeLoggingInterface::SharedPtr node_logging_interface, rclcpp::node_interfaces::NodeClockInterface::SharedPtr node_clock_interface, rclcpp::node_interfaces::NodeParametersInterface::SharedPtr node_parameters_interface) { node_state_->attachNode( std::move(node_base_interface), std::move(node_topics_interface), std::move(node_graph_interface), std::move(node_services_interface), std::move(node_logging_interface), std::move(node_clock_interface), std::move(node_parameters_interface)); } void TimeSource::detachNode() { node_state_.reset(); node_state_ = std::make_shared<NodeState>( constructed_qos_, constructed_use_clock_thread_); } void TimeSource::attachClock(std::shared_ptr<rclcpp::Clock> clock) { node_state_->attachClock(std::move(clock)); } void TimeSource::detachClock(std::shared_ptr<rclcpp::Clock> clock) { node_state_->detachClock(std::move(clock)); } bool TimeSource::get_use_clock_thread() { return node_state_->get_use_clock_thread(); } void TimeSource::set_use_clock_thread(bool use_clock_thread) { node_state_->set_use_clock_thread(use_clock_thread); } bool TimeSource::clock_thread_is_joinable() { return node_state_->clock_thread_is_joinable(); } TimeSource::~TimeSource() { } } // namespace rclcpp
33.001802
100
0.71473
RTI-BDI
42ad3848e22a63e1e8823742916de5544ff84725
1,730
hh
C++
grasp/Grasp.hh
el-cangrejo/grasp
492dd14928b0072beecf752075b712db96f06834
[ "MIT" ]
70
2018-10-17T17:37:22.000Z
2022-02-28T15:19:47.000Z
grasp/Grasp.hh
el-cangrejo/grasp
492dd14928b0072beecf752075b712db96f06834
[ "MIT" ]
3
2020-12-08T13:02:17.000Z
2022-02-22T11:59:00.000Z
grasp/Grasp.hh
el-cangrejo/grasp
492dd14928b0072beecf752075b712db96f06834
[ "MIT" ]
17
2018-10-29T04:09:45.000Z
2022-03-19T11:34:55.000Z
/*! \file grasp/Grasp.hh \brief Grasp representation \author João Borrego : jsbruglie */ #ifndef _GRASP_HH_ #define _GRASP_HH_ // Gazebo #include <gazebo/gazebo_client.hh> // Open YAML config files #include "yaml-cpp/yaml.h" // Debug streams #include "debug.hh" /// \brief Grasp representation class class Grasp { // Public attributes /// Grasp candidate name public: int id; /// Homogenous transform matrix from gripper to object reference frame public: ignition::math::Matrix4d t_gripper_object; /// Grasp success metric public: double metric {false}; /// \brief Deafult constructor public: Grasp(int id_=0); /// \brief Constructor /// \param t_gripper_object_ Transform matrix from gripper to object frame /// \param id Grasp identifier public: Grasp(ignition::math::Matrix4d t_gripper_object_, int id_=0); /// \brief Load set of grasps from file /// \param file_name Input file name /// \param robot Target robot name /// \param object_name Target object name /// \param grasps Set of grasps retrieved from file public: static void loadFromYml( const std::string & file_name, const std::string & robot, const std::string & object_name, std::vector<Grasp> & grasps); /// \brief Export set of grasps to file /// \param file_name Output file name /// \param robot Target robot name /// \param object_name Target object name /// \param grasps Set of grasps to export to file public: static void writeToYml( const std::string & file_name, const std::string & robot, const std::string & object_name, const std::vector<Grasp> & grasps); }; #endif
27.903226
78
0.666474
el-cangrejo
42b16212868354cd93abf75113e378f0054ddfd3
3,500
cpp
C++
encoderlame.cpp
napcode/appstream
f4e5452e2f3cc68899a3a1e7033435a56d8a7c79
[ "MIT" ]
null
null
null
encoderlame.cpp
napcode/appstream
f4e5452e2f3cc68899a3a1e7033435a56d8a7c79
[ "MIT" ]
null
null
null
encoderlame.cpp
napcode/appstream
f4e5452e2f3cc68899a3a1e7033435a56d8a7c79
[ "MIT" ]
null
null
null
#include "encoderlame.h" EncoderLame::EncoderLame(EncoderConfig c) : Encoder(c) { } EncoderLame::~EncoderLame() { if (_lgf) { lame_close(_lgf); _lgf = 0; } delete[] _buffer; } bool EncoderLame::init() { if (isInitialized()) return true; int rc; _lgf = lame_init(); /* emit message(QString::number(_config.numInChannels)); emit message(QString::number(_config.sampleRateIn)); emit message(QString::number(_config.sampleRateOut)); emit message(QString::number(_config.bitRate)); */ lame_set_num_channels(_lgf, _config.numInChannels); lame_set_in_samplerate(_lgf, _config.sampleRateIn); lame_set_out_samplerate(_lgf, _config.sampleRateOut); if (_config.mode == EncoderConfig::CBR) lame_set_brate(_lgf, _config.quality); else if (_config.mode == EncoderConfig::VBR) { lame_set_VBR(_lgf, vbr_mtrh); lame_set_VBR_quality(_lgf, 10.0 - 10 * _config.quality); } if ((rc = lame_init_params(_lgf)) < 0) { emit error("unable to init lame"); emit error("Channels " + QString::number(_config.numInChannels)); emit error("RateIn " + QString::number(_config.sampleRateIn)); emit error("RateOut " + QString::number(_config.sampleRateOut)); emit error("BitRate " + QString::number(_config.quality)); return false; } else { _initialized = true; emit message("Lame initialized"); emit message("Version: " + getVersion()); } // default output buffer size. see lame.h resize(DSP_BLOCKSIZE); return true; } void EncoderLame::setup() { // nothing to do here } void EncoderLame::encode(sample_t* buffer, uint32_t samples) { int rc; if (samples == 0 || !isInitialized()) return; if (_allocedFrames < samples) resize(samples); if (_config.numInChannels == 2) rc = lame_encode_buffer_interleaved_ieee_double(_lgf, buffer, samples / _config.numInChannels, reinterpret_cast<unsigned char*>(_buffer), _bufferSize); else if (_config.numInChannels == 1) rc = lame_encode_buffer_ieee_double(_lgf, buffer, buffer, samples, reinterpret_cast<unsigned char*>(_buffer), _bufferSize); else { emit error("Lame can't handle more than 2 channels."); assert(0); } if (rc >= 0) _bufferValid = rc; else { _bufferValid = 0; handleRC(rc); } } void EncoderLame::finalize() { } void EncoderLame::handleRC(int rc) const { switch (rc) { case -1: emit error("Lame: out buffer to small"); break; case -2: emit error("Lame: unable to allocate memory"); break; case -3: emit error("Lame: init not called. Should never happen."); break; case -4: emit error("Lame: psycho acoustic problem occurred"); break; default: emit error("Lame: unknown error occurred. "); } } void EncoderLame::resize(uint32_t newSize) { delete[] _buffer; _allocedFrames = newSize; // default output buffer size. see lame.h _bufferSize = 1.25 * _allocedFrames + 7200; _buffer = new char[_bufferSize]; } QString EncoderLame::getVersion() const { QString info; if (!isInitialized()) { emit error("lame is not initialized. Can't get version info."); return info; } QString lame_version(get_lame_version()); return lame_version; }
27.559055
159
0.624571
napcode
42b21efa257618345907a5b16591432d070d102a
19,630
cpp
C++
apiwznm/PnlWznmCarDetail.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
3
2020-09-20T16:24:48.000Z
2021-12-01T19:44:51.000Z
apiwznm/PnlWznmCarDetail.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
apiwznm/PnlWznmCarDetail.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
/** * \file PnlWznmCarDetail.cpp * API code for job PnlWznmCarDetail (implementation) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 5 Dec 2020 */ // IP header --- ABOVE #include "PnlWznmCarDetail.h" using namespace std; using namespace Sbecore; using namespace Xmlio; /****************************************************************************** class PnlWznmCarDetail::VecVDo ******************************************************************************/ uint PnlWznmCarDetail::VecVDo::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "butsaveclick") return BUTSAVECLICK; if (s == "butjtieditclick") return BUTJTIEDITCLICK; if (s == "butmdlviewclick") return BUTMDLVIEWCLICK; if (s == "butreuviewclick") return BUTREUVIEWCLICK; if (s == "butjobviewclick") return BUTJOBVIEWCLICK; return(0); }; string PnlWznmCarDetail::VecVDo::getSref( const uint ix ) { if (ix == BUTSAVECLICK) return("ButSaveClick"); if (ix == BUTJTIEDITCLICK) return("ButJtiEditClick"); if (ix == BUTMDLVIEWCLICK) return("ButMdlViewClick"); if (ix == BUTREUVIEWCLICK) return("ButReuViewClick"); if (ix == BUTJOBVIEWCLICK) return("ButJobViewClick"); return(""); }; /****************************************************************************** class PnlWznmCarDetail::ContIac ******************************************************************************/ PnlWznmCarDetail::ContIac::ContIac( const uint numFPupJti , const uint numFPupRet , const string& TxfAvl , const string& TxfAct ) : Block() { this->numFPupJti = numFPupJti; this->numFPupRet = numFPupRet; this->TxfAvl = TxfAvl; this->TxfAct = TxfAct; mask = {NUMFPUPJTI, NUMFPUPRET, TXFAVL, TXFACT}; }; bool PnlWznmCarDetail::ContIac::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContIacWznmCarDetail"); else basefound = checkXPath(docctx, basexpath); string itemtag = "ContitemIacWznmCarDetail"; if (basefound) { if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFPupJti", numFPupJti)) add(NUMFPUPJTI); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFPupRet", numFPupRet)) add(NUMFPUPRET); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxfAvl", TxfAvl)) add(TXFAVL); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxfAct", TxfAct)) add(TXFACT); }; return basefound; }; void PnlWznmCarDetail::ContIac::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "ContIacWznmCarDetail"; string itemtag; if (shorttags) itemtag = "Ci"; else itemtag = "ContitemIacWznmCarDetail"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeUintAttr(wr, itemtag, "sref", "numFPupJti", numFPupJti); writeUintAttr(wr, itemtag, "sref", "numFPupRet", numFPupRet); writeStringAttr(wr, itemtag, "sref", "TxfAvl", TxfAvl); writeStringAttr(wr, itemtag, "sref", "TxfAct", TxfAct); xmlTextWriterEndElement(wr); }; set<uint> PnlWznmCarDetail::ContIac::comm( const ContIac* comp ) { set<uint> items; if (numFPupJti == comp->numFPupJti) insert(items, NUMFPUPJTI); if (numFPupRet == comp->numFPupRet) insert(items, NUMFPUPRET); if (TxfAvl == comp->TxfAvl) insert(items, TXFAVL); if (TxfAct == comp->TxfAct) insert(items, TXFACT); return(items); }; set<uint> PnlWznmCarDetail::ContIac::diff( const ContIac* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {NUMFPUPJTI, NUMFPUPRET, TXFAVL, TXFACT}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWznmCarDetail::ContInf ******************************************************************************/ PnlWznmCarDetail::ContInf::ContInf( const string& TxtSrf , const string& TxtTit , const string& TxtMdl , const string& TxtReu , const string& TxtJob ) : Block() { this->TxtSrf = TxtSrf; this->TxtTit = TxtTit; this->TxtMdl = TxtMdl; this->TxtReu = TxtReu; this->TxtJob = TxtJob; mask = {TXTSRF, TXTTIT, TXTMDL, TXTREU, TXTJOB}; }; bool PnlWznmCarDetail::ContInf::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContInfWznmCarDetail"); else basefound = checkXPath(docctx, basexpath); string itemtag = "ContitemInfWznmCarDetail"; if (basefound) { if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxtSrf", TxtSrf)) add(TXTSRF); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxtTit", TxtTit)) add(TXTTIT); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxtMdl", TxtMdl)) add(TXTMDL); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxtReu", TxtReu)) add(TXTREU); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxtJob", TxtJob)) add(TXTJOB); }; return basefound; }; set<uint> PnlWznmCarDetail::ContInf::comm( const ContInf* comp ) { set<uint> items; if (TxtSrf == comp->TxtSrf) insert(items, TXTSRF); if (TxtTit == comp->TxtTit) insert(items, TXTTIT); if (TxtMdl == comp->TxtMdl) insert(items, TXTMDL); if (TxtReu == comp->TxtReu) insert(items, TXTREU); if (TxtJob == comp->TxtJob) insert(items, TXTJOB); return(items); }; set<uint> PnlWznmCarDetail::ContInf::diff( const ContInf* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {TXTSRF, TXTTIT, TXTMDL, TXTREU, TXTJOB}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWznmCarDetail::StatApp ******************************************************************************/ PnlWznmCarDetail::StatApp::StatApp( const uint ixWznmVExpstate ) : Block() { this->ixWznmVExpstate = ixWznmVExpstate; mask = {IXWZNMVEXPSTATE}; }; bool PnlWznmCarDetail::StatApp::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); string srefIxWznmVExpstate; bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatAppWznmCarDetail"); else basefound = checkXPath(docctx, basexpath); string itemtag = "StatitemAppWznmCarDetail"; if (basefound) { if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "srefIxWznmVExpstate", srefIxWznmVExpstate)) { ixWznmVExpstate = VecWznmVExpstate::getIx(srefIxWznmVExpstate); add(IXWZNMVEXPSTATE); }; }; return basefound; }; set<uint> PnlWznmCarDetail::StatApp::comm( const StatApp* comp ) { set<uint> items; if (ixWznmVExpstate == comp->ixWznmVExpstate) insert(items, IXWZNMVEXPSTATE); return(items); }; set<uint> PnlWznmCarDetail::StatApp::diff( const StatApp* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {IXWZNMVEXPSTATE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWznmCarDetail::StatShr ******************************************************************************/ PnlWznmCarDetail::StatShr::StatShr( const bool ButSaveAvail , const bool ButSaveActive , const bool TxtSrfActive , const bool PupJtiActive , const bool ButJtiEditAvail , const bool TxtTitActive , const bool TxtMdlActive , const bool ButMdlViewAvail , const bool ButMdlViewActive , const bool TxtReuActive , const bool ButReuViewAvail , const bool ButReuViewActive , const bool TxtJobActive , const bool ButJobViewAvail , const bool ButJobViewActive , const bool TxfAvlActive , const bool TxfActActive ) : Block() { this->ButSaveAvail = ButSaveAvail; this->ButSaveActive = ButSaveActive; this->TxtSrfActive = TxtSrfActive; this->PupJtiActive = PupJtiActive; this->ButJtiEditAvail = ButJtiEditAvail; this->TxtTitActive = TxtTitActive; this->TxtMdlActive = TxtMdlActive; this->ButMdlViewAvail = ButMdlViewAvail; this->ButMdlViewActive = ButMdlViewActive; this->TxtReuActive = TxtReuActive; this->ButReuViewAvail = ButReuViewAvail; this->ButReuViewActive = ButReuViewActive; this->TxtJobActive = TxtJobActive; this->ButJobViewAvail = ButJobViewAvail; this->ButJobViewActive = ButJobViewActive; this->TxfAvlActive = TxfAvlActive; this->TxfActActive = TxfActActive; mask = {BUTSAVEAVAIL, BUTSAVEACTIVE, TXTSRFACTIVE, PUPJTIACTIVE, BUTJTIEDITAVAIL, TXTTITACTIVE, TXTMDLACTIVE, BUTMDLVIEWAVAIL, BUTMDLVIEWACTIVE, TXTREUACTIVE, BUTREUVIEWAVAIL, BUTREUVIEWACTIVE, TXTJOBACTIVE, BUTJOBVIEWAVAIL, BUTJOBVIEWACTIVE, TXFAVLACTIVE, TXFACTACTIVE}; }; bool PnlWznmCarDetail::StatShr::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatShrWznmCarDetail"); else basefound = checkXPath(docctx, basexpath); string itemtag = "StatitemShrWznmCarDetail"; if (basefound) { if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButSaveAvail", ButSaveAvail)) add(BUTSAVEAVAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButSaveActive", ButSaveActive)) add(BUTSAVEACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TxtSrfActive", TxtSrfActive)) add(TXTSRFACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "PupJtiActive", PupJtiActive)) add(PUPJTIACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButJtiEditAvail", ButJtiEditAvail)) add(BUTJTIEDITAVAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TxtTitActive", TxtTitActive)) add(TXTTITACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TxtMdlActive", TxtMdlActive)) add(TXTMDLACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButMdlViewAvail", ButMdlViewAvail)) add(BUTMDLVIEWAVAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButMdlViewActive", ButMdlViewActive)) add(BUTMDLVIEWACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TxtReuActive", TxtReuActive)) add(TXTREUACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButReuViewAvail", ButReuViewAvail)) add(BUTREUVIEWAVAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButReuViewActive", ButReuViewActive)) add(BUTREUVIEWACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TxtJobActive", TxtJobActive)) add(TXTJOBACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButJobViewAvail", ButJobViewAvail)) add(BUTJOBVIEWAVAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButJobViewActive", ButJobViewActive)) add(BUTJOBVIEWACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TxfAvlActive", TxfAvlActive)) add(TXFAVLACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TxfActActive", TxfActActive)) add(TXFACTACTIVE); }; return basefound; }; set<uint> PnlWznmCarDetail::StatShr::comm( const StatShr* comp ) { set<uint> items; if (ButSaveAvail == comp->ButSaveAvail) insert(items, BUTSAVEAVAIL); if (ButSaveActive == comp->ButSaveActive) insert(items, BUTSAVEACTIVE); if (TxtSrfActive == comp->TxtSrfActive) insert(items, TXTSRFACTIVE); if (PupJtiActive == comp->PupJtiActive) insert(items, PUPJTIACTIVE); if (ButJtiEditAvail == comp->ButJtiEditAvail) insert(items, BUTJTIEDITAVAIL); if (TxtTitActive == comp->TxtTitActive) insert(items, TXTTITACTIVE); if (TxtMdlActive == comp->TxtMdlActive) insert(items, TXTMDLACTIVE); if (ButMdlViewAvail == comp->ButMdlViewAvail) insert(items, BUTMDLVIEWAVAIL); if (ButMdlViewActive == comp->ButMdlViewActive) insert(items, BUTMDLVIEWACTIVE); if (TxtReuActive == comp->TxtReuActive) insert(items, TXTREUACTIVE); if (ButReuViewAvail == comp->ButReuViewAvail) insert(items, BUTREUVIEWAVAIL); if (ButReuViewActive == comp->ButReuViewActive) insert(items, BUTREUVIEWACTIVE); if (TxtJobActive == comp->TxtJobActive) insert(items, TXTJOBACTIVE); if (ButJobViewAvail == comp->ButJobViewAvail) insert(items, BUTJOBVIEWAVAIL); if (ButJobViewActive == comp->ButJobViewActive) insert(items, BUTJOBVIEWACTIVE); if (TxfAvlActive == comp->TxfAvlActive) insert(items, TXFAVLACTIVE); if (TxfActActive == comp->TxfActActive) insert(items, TXFACTACTIVE); return(items); }; set<uint> PnlWznmCarDetail::StatShr::diff( const StatShr* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {BUTSAVEAVAIL, BUTSAVEACTIVE, TXTSRFACTIVE, PUPJTIACTIVE, BUTJTIEDITAVAIL, TXTTITACTIVE, TXTMDLACTIVE, BUTMDLVIEWAVAIL, BUTMDLVIEWACTIVE, TXTREUACTIVE, BUTREUVIEWAVAIL, BUTREUVIEWACTIVE, TXTJOBACTIVE, BUTJOBVIEWAVAIL, BUTJOBVIEWACTIVE, TXFAVLACTIVE, TXFACTACTIVE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWznmCarDetail::Tag ******************************************************************************/ PnlWznmCarDetail::Tag::Tag( const string& Cpt , const string& CptSrf , const string& CptTit , const string& CptMdl , const string& CptReu , const string& CptJob , const string& CptAvl , const string& CptAct ) : Block() { this->Cpt = Cpt; this->CptSrf = CptSrf; this->CptTit = CptTit; this->CptMdl = CptMdl; this->CptReu = CptReu; this->CptJob = CptJob; this->CptAvl = CptAvl; this->CptAct = CptAct; mask = {CPT, CPTSRF, CPTTIT, CPTMDL, CPTREU, CPTJOB, CPTAVL, CPTACT}; }; bool PnlWznmCarDetail::Tag::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "TagWznmCarDetail"); else basefound = checkXPath(docctx, basexpath); string itemtag = "TagitemWznmCarDetail"; if (basefound) { if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "Cpt", Cpt)) add(CPT); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptSrf", CptSrf)) add(CPTSRF); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptTit", CptTit)) add(CPTTIT); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptMdl", CptMdl)) add(CPTMDL); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptReu", CptReu)) add(CPTREU); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptJob", CptJob)) add(CPTJOB); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptAvl", CptAvl)) add(CPTAVL); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptAct", CptAct)) add(CPTACT); }; return basefound; }; /****************************************************************************** class PnlWznmCarDetail::DpchAppData ******************************************************************************/ PnlWznmCarDetail::DpchAppData::DpchAppData( const string& scrJref , ContIac* contiac , const set<uint>& mask ) : DpchAppWznm(VecWznmVDpch::DPCHAPPWZNMCARDETAILDATA, scrJref) { if (find(mask, ALL)) this->mask = {SCRJREF, CONTIAC}; else this->mask = mask; if (find(this->mask, CONTIAC) && contiac) this->contiac = *contiac; }; string PnlWznmCarDetail::DpchAppData::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(CONTIAC)) ss.push_back("contiac"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWznmCarDetail::DpchAppData::writeXML( xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchAppWznmCarDetailData"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wznm"); if (has(SCRJREF)) writeString(wr, "scrJref", scrJref); if (has(CONTIAC)) contiac.writeXML(wr); xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlWznmCarDetail::DpchAppDo ******************************************************************************/ PnlWznmCarDetail::DpchAppDo::DpchAppDo( const string& scrJref , const uint ixVDo , const set<uint>& mask ) : DpchAppWznm(VecWznmVDpch::DPCHAPPWZNMCARDETAILDO, scrJref) { if (find(mask, ALL)) this->mask = {SCRJREF, IXVDO}; else this->mask = mask; this->ixVDo = ixVDo; }; string PnlWznmCarDetail::DpchAppDo::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(IXVDO)) ss.push_back("ixVDo"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWznmCarDetail::DpchAppDo::writeXML( xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchAppWznmCarDetailDo"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wznm"); if (has(SCRJREF)) writeString(wr, "scrJref", scrJref); if (has(IXVDO)) writeString(wr, "srefIxVDo", VecVDo::getSref(ixVDo)); xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlWznmCarDetail::DpchEngData ******************************************************************************/ PnlWznmCarDetail::DpchEngData::DpchEngData() : DpchEngWznm(VecWznmVDpch::DPCHENGWZNMCARDETAILDATA) { feedFPupJti.tag = "FeedFPupJti"; feedFPupRet.tag = "FeedFPupRet"; }; string PnlWznmCarDetail::DpchEngData::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(CONTIAC)) ss.push_back("contiac"); if (has(CONTINF)) ss.push_back("continf"); if (has(FEEDFPUPJTI)) ss.push_back("feedFPupJti"); if (has(FEEDFPUPRET)) ss.push_back("feedFPupRet"); if (has(STATAPP)) ss.push_back("statapp"); if (has(STATSHR)) ss.push_back("statshr"); if (has(TAG)) ss.push_back("tag"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWznmCarDetail::DpchEngData::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchEngWznmCarDetailData"); else basefound = checkXPath(docctx, basexpath); if (basefound) { if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) add(SCRJREF); if (contiac.readXML(docctx, basexpath, true)) add(CONTIAC); if (continf.readXML(docctx, basexpath, true)) add(CONTINF); if (feedFPupJti.readXML(docctx, basexpath, true)) add(FEEDFPUPJTI); if (feedFPupRet.readXML(docctx, basexpath, true)) add(FEEDFPUPRET); if (statapp.readXML(docctx, basexpath, true)) add(STATAPP); if (statshr.readXML(docctx, basexpath, true)) add(STATSHR); if (tag.readXML(docctx, basexpath, true)) add(TAG); } else { contiac = ContIac(); continf = ContInf(); feedFPupJti.clear(); feedFPupRet.clear(); statapp = StatApp(); statshr = StatShr(); tag = Tag(); }; };
32.5
277
0.670301
mpsitech
42b2b194989dff2b2dd44420dd2d5941c206551b
3,702
hpp
C++
src/integration/IntegrationNSphere.hpp
FrancoisGaits/utk
8c408dd79635f98c46ed075c098f15e23972aad0
[ "BSD-2-Clause-FreeBSD" ]
44
2018-01-09T19:56:29.000Z
2022-03-03T06:38:54.000Z
src/integration/IntegrationNSphere.hpp
FrancoisGaits/utk
8c408dd79635f98c46ed075c098f15e23972aad0
[ "BSD-2-Clause-FreeBSD" ]
16
2018-01-29T18:01:42.000Z
2022-03-31T07:01:09.000Z
src/integration/IntegrationNSphere.hpp
FrancoisGaits/utk
8c408dd79635f98c46ed075c098f15e23972aad0
[ "BSD-2-Clause-FreeBSD" ]
12
2018-03-14T00:24:14.000Z
2022-03-03T06:40:07.000Z
/* * Hélène Perrier helene.perrier@liris.cnrs.fr * and David Coeurjolly david.coeurjolly@liris.cnrs.fr * * Copyright (c) 2018 CNRS Université de Lyon * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the UTK project. */ #ifndef _UTK_INTEGRATION_DISK_ND_ #define _UTK_INTEGRATION_DISK_ND_ #include "../io/messageStream.hpp" #include "../pointsets/Pointset.hpp" #include <cmath> #include <array> namespace utk { class IntegrationNSphere { public: IntegrationNSphere() { m_radius = 0.25; } void setRadius(double arg_radius) { m_radius = arg_radius; } template<unsigned int D, typename T, typename P> bool compute(const Pointset<D, T, P>& arg_pointset, double& integration_value, double& analytic_value) { if(m_radius <= 0 && m_radius >= 0.5) { ERROR("IntegrationNSphere::compute radius must be in ]0, 0.5["); return false; } std::array<double, D> nd_domain_extent; for(unsigned int d=0; d<D; d++) { nd_domain_extent[d] = (arg_pointset.domain.pMax.pos() - arg_pointset.domain.pMin.pos())[d]; if(nd_domain_extent[d] == 0) { WARNING("IntegrationNSphere::compute domain extent is 0 on at least one dimension, scaling might fail"); } if(nd_domain_extent[d] < 0) { ERROR("IntegrationNSphere::compute domain extent is negative on at least one dimension"); return false; } } analytic_value = analyticIntegrand(D); integration_value = 0; for(uint i=0; i<arg_pointset.size(); i++) { Point<D, double> pt; for(unsigned int d=0; d<D; d++) pt.pos()[d] = -0.5 + (arg_pointset[i].pos() - arg_pointset.domain.pMin.pos())[d] / nd_domain_extent[d]; integration_value += sampleIntegrand<D>(pt); } integration_value /= (double)arg_pointset.size(); return true; } double analyticIntegrand(uint dim) { double num = pow(M_PI, (double)dim/2.0); double denom = tgamma(((double)dim/2.0) + 1); return (num/denom)*pow(m_radius, dim); } template<uint D> double sampleIntegrand(Point<D, double>& pt) { double l = pt.pos().length(); if(l < m_radius) return 1; return 0; } double m_radius; }; }//end namespace #endif
32.473684
105
0.700702
FrancoisGaits
42b5735b3471a7446cdf2188bd48234ed6b3765c
3,014
hpp
C++
libbitcoin/include/bitcoin/constants.hpp
mousewu/bcclient
64ee1f6f8337103d40a4a0c3dfb73cabcd09a04c
[ "MIT" ]
8
2019-05-31T01:37:08.000Z
2021-10-19T05:52:45.000Z
libbitcoin/include/bitcoin/constants.hpp
mousewu/bcclient
64ee1f6f8337103d40a4a0c3dfb73cabcd09a04c
[ "MIT" ]
3
2017-12-18T17:27:09.000Z
2018-01-15T16:50:05.000Z
libbitcoin/include/bitcoin/constants.hpp
mousewu/bcclient
64ee1f6f8337103d40a4a0c3dfb73cabcd09a04c
[ "MIT" ]
5
2018-01-09T15:05:55.000Z
2020-12-17T13:27:25.000Z
/* * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBBITCOIN_CONSTANTS_HPP #define LIBBITCOIN_CONSTANTS_HPP #include <cstdint> #include <bitcoin/utility/big_number.hpp> namespace libbitcoin { constexpr uint32_t protocol_version = 60000; constexpr uint64_t block_reward = 50; // 210000 ~ 4 years / 10 minutes constexpr uint64_t reward_interval = 210000; constexpr size_t coinbase_maturity = 100; #ifdef ENABLE_TESTNET constexpr uint32_t protocol_port = 18333; #else constexpr uint32_t protocol_port = 8333; #endif // Threshold for nLockTime: below this value it is // interpreted as block number, otherwise as UNIX timestamp. // Tue Nov 5 00:53:20 1985 UTC constexpr uint32_t locktime_threshold = 500000000; constexpr uint64_t max_money_recursive(uint64_t current) { return (current > 0) ? current + max_money_recursive(current >> 1) : 0; } constexpr uint64_t coin_price(uint64_t value=1) { return value * 100000000; } constexpr uint64_t max_money() { return reward_interval * max_money_recursive(coin_price(block_reward)); } const hash_digest null_hash{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; const short_hash null_short_hash{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; constexpr uint32_t max_bits = 0x1d00ffff; big_number max_target(); uint32_t magic_value(); constexpr uint32_t max_index = std::numeric_limits<uint32_t>::max(); // Every two weeks we readjust target constexpr uint64_t target_timespan = 14 * 24 * 60 * 60; // Aim for blocks every 10 mins constexpr uint64_t target_spacing = 10 * 60; // Two weeks worth of blocks = readjust interval = 2016 constexpr uint64_t readjustment_interval = target_timespan / target_spacing; #ifdef ENABLE_TESTNET // Block 514 is the first block after Feb 15 2014. // Testnet started bip16 before mainnet. constexpr uint32_t bip16_switchover_timestamp = 1333238400; constexpr uint32_t bip16_switchover_height = 514; #else // April 1 2012 constexpr uint32_t bip16_switchover_timestamp = 1333238400; constexpr uint32_t bip16_switchover_height = 173805; #endif } // namespace libbitcoin #endif
31.395833
76
0.736231
mousewu
42b713a94aed7da16b1cf74cfd6e5e60937a2e40
5,781
cc
C++
tensorflow_io/core/azure/azfs/azfs_client.cc
pshiko/io
a1793e6b41ed7a8db572249aba15a8e513a348a5
[ "Apache-2.0" ]
1
2020-01-20T17:48:31.000Z
2020-01-20T17:48:31.000Z
tensorflow_io/core/azure/azfs/azfs_client.cc
pshiko/io
a1793e6b41ed7a8db572249aba15a8e513a348a5
[ "Apache-2.0" ]
null
null
null
tensorflow_io/core/azure/azfs/azfs_client.cc
pshiko/io
a1793e6b41ed7a8db572249aba15a8e513a348a5
[ "Apache-2.0" ]
null
null
null
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_io/core/azure/azfs/azfs_client.h" #include "logging.h" namespace tensorflow { namespace io { /// \brief Splits a Azure path to a account, container and object. /// /// For example, /// "az://account-name.blob.core.windows.net/container/path/to/file.txt" gets /// split into "account-name", "container" and "path/to/file.txt". Status ParseAzBlobPath(StringPiece fname, bool empty_object_ok, std::string *account, std::string *container, std::string *object) { if (!account || !object) { return errors::Internal("account and object cannot be null."); } StringPiece scheme, accountp, objectp; io::ParseURI(fname, &scheme, &accountp, &objectp); if (scheme != "az") { return errors::InvalidArgument( "Azure Blob Storage path doesn't start with 'az://': ", fname); } // Consume blob.core.windows.net if it exists absl::ConsumeSuffix(&accountp, kAzBlobEndpoint); if (accountp.empty() || accountp.compare(".") == 0) { return errors::InvalidArgument( "Azure Blob Storage path doesn't contain a account name: ", fname); } *account = std::string(accountp); absl::ConsumePrefix(&objectp, "/"); auto pos = objectp.find('/'); if (pos == std::string::npos) { *container = objectp.data(); *object = ""; } else { *container = std::string(objectp.substr(0, pos)); *object = std::string(objectp.substr(pos + 1)); } return Status::OK(); } std::string errno_to_string() { switch (errno) { /* common errors */ case invalid_parameters: return "invalid_parameters"; /* client level */ case client_init_fail: return "client_init_fail"; case client_already_init: return "client_already_init"; case client_not_init: return "client_not_init"; /* container level */ case container_already_exists: return "container_already_exists"; case container_not_exists: return "container_not_exists"; case container_name_invalid: return "container_name_invalid"; case container_create_fail: return "container_create_fail"; case container_delete_fail: return "container_delete_fail"; /* blob level */ case blob__already_exists: return "blob__already_exists"; case blob_not_exists: return "blob_not_exists"; case blob_name_invalid: return "blob_name_invalid"; case blob_delete_fail: return "blob_delete_fail"; case blob_list_fail: return "blob_list_fail"; case blob_copy_fail: return "blob_copy_fail"; case blob_no_content_range: return "blob_no_content_range"; /* unknown error */ case unknown_error: default: return "unknown_error - " + std::to_string(errno); } } std::shared_ptr<azure::storage_lite::storage_credential> get_credential( const std::string &account) { const auto key = std::getenv("TF_AZURE_STORAGE_KEY"); if (key != nullptr) { return std::make_shared<azure::storage_lite::shared_key_credential>(account, key); } else { return std::make_shared<azure::storage_lite::anonymous_credential>(); } } azure::storage_lite::blob_client_wrapper CreateAzBlobClientWrapper( const std::string &account) { azure::storage_lite::logger::set_logger( [](azure::storage_lite::log_level level, const std::string &log_msg) { switch (level) { case azure::storage_lite::log_level::info: _TF_LOG_INFO << log_msg; break; case azure::storage_lite::log_level::error: case azure::storage_lite::log_level::critical: _TF_LOG_ERROR << log_msg; break; case azure::storage_lite::log_level::warn: _TF_LOG_WARNING << log_msg; break; case azure::storage_lite::log_level::trace: case azure::storage_lite::log_level::debug: default: break; } }); const auto use_dev_account = std::getenv("TF_AZURE_USE_DEV_STORAGE"); if (use_dev_account != nullptr) { auto storage_account = azure::storage_lite::storage_account::development_storage_account(); auto blob_client = std::make_shared<azure::storage_lite::blob_client>(storage_account, 10); azure::storage_lite::blob_client_wrapper blob_client_wrapper(blob_client); return blob_client_wrapper; } const auto use_http_env = std::getenv("TF_AZURE_STORAGE_USE_HTTP"); const auto use_https = use_http_env == nullptr; const auto blob_endpoint = std::string(std::getenv("TF_AZURE_STORAGE_BLOB_ENDPOINT") ?: ""); auto credentials = get_credential(account); auto storage_account = std::make_shared<azure::storage_lite::storage_account>( account, credentials, use_https, blob_endpoint); auto blob_client = std::make_shared<azure::storage_lite::blob_client>(storage_account, 10); azure::storage_lite::blob_client_wrapper blob_client_wrapper(blob_client); return blob_client_wrapper; } } // namespace io } // namespace tensorflow
34.207101
80
0.669953
pshiko
42b976415bed9557543a9e1dd17c9c84c33fe02a
593
cpp
C++
03/exam03.cpp
Sadik326-ctrl/computer_programming
cbae264ffa04fc487008fa6a0a32e0a1a316e01e
[ "MIT" ]
null
null
null
03/exam03.cpp
Sadik326-ctrl/computer_programming
cbae264ffa04fc487008fa6a0a32e0a1a316e01e
[ "MIT" ]
null
null
null
03/exam03.cpp
Sadik326-ctrl/computer_programming
cbae264ffa04fc487008fa6a0a32e0a1a316e01e
[ "MIT" ]
null
null
null
// Demonstration of compound assignments #include <iostream> #include <iomanip> using namespace std; int main() { float x, y; cout << "\n Please enter a starting value: cin >> x; "; cout << "\n Please enter the increment value: "; cin >> y; x += y; cout << "\n And now multiplication! "; cout << "\n Please enter a factor: "; cin >> y; x *= y; cout << "\n Finally division."; cout << "\n Please supply a divisor: "; cin >> y; x /= y; cout << "\n And this is " << "your current lucky number: " // without digits after // the decimal point: << fixed << setprecision(0) << x << endl; return 0; }
19.766667
48
0.625632
Sadik326-ctrl
42b9e0ae70299b5c0c42b2aa5b291bf768be26c4
485
cpp
C++
Part_Fourteen/BasePtrDerivedObj.cpp
ayushpareek179/CPP-course
b2b8b8d2dd06cd772e3c9838abd5b841237bb306
[ "MIT" ]
null
null
null
Part_Fourteen/BasePtrDerivedObj.cpp
ayushpareek179/CPP-course
b2b8b8d2dd06cd772e3c9838abd5b841237bb306
[ "MIT" ]
null
null
null
Part_Fourteen/BasePtrDerivedObj.cpp
ayushpareek179/CPP-course
b2b8b8d2dd06cd772e3c9838abd5b841237bb306
[ "MIT" ]
null
null
null
//To depict pointer to a derived class objeof base class type #include <iostream> using namespace std; class parent { public: void func() { cout<<"Base's function\n"; } }; class child:public parent { public: void meth() { cout<<"Derived's function\n"; } }; int main() { child c; //parent* pa = &c; - Works as well parent* p = new child(); p->func(); //p->meth() - doesn't work //c.meth(); - works return 0; }
16.724138
61
0.548454
ayushpareek179
42bbfc1363eb5582eaffb6b99a570e8fb7d41497
1,641
hpp
C++
release/include/mlclient/mlclient.hpp
adamfowleruk/mlcplusplus
bd8b47b8e92c7f66a22ecfe98353f3e8a621802d
[ "Apache-2.0" ]
4
2016-04-21T06:27:40.000Z
2017-01-20T12:10:54.000Z
release/include/mlclient/mlclient.hpp
marklogic/mlcplusplus
bd8b47b8e92c7f66a22ecfe98353f3e8a621802d
[ "Apache-2.0" ]
239
2015-11-26T23:10:33.000Z
2017-01-03T23:48:23.000Z
release/include/mlclient/mlclient.hpp
marklogic-community/mlcplusplus
bd8b47b8e92c7f66a22ecfe98353f3e8a621802d
[ "Apache-2.0" ]
3
2017-11-01T15:52:51.000Z
2021-12-02T05:22:49.000Z
/* * Copyright (c) MarkLogic Corporation. 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. */ #pragma once #ifndef MLCLIENT_HPP #define MLCLIENT_HPP #include <memory> #include <vector> #include <map> //#include "mlclient/ext/easylogging++.h" #ifdef _WIN32 #ifdef MLCLIENT_EXPORTS #define MLCLIENT_API __declspec(dllexport) #else #define MLCLIENT_API __declspec(dllimport) #endif #include <ostream> #include <sstream> #include <string> /* namespace mlclient { MLCLIENT_API el::base::type::StoragePointer sharedLoggingRepository(); } */ #else #define MLCLIENT_API #endif namespace mlclient { typedef std::map<std::string,std::string> StringMap; typedef std::vector<std::string> SearchSuggestionSet; typedef std::vector<std::string> StringList; // note: this implementation does not disable this overload for array types template<typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } } // end namespace mlclient #endif /* defined(MLCLIENT_HPP) */
26.047619
78
0.718464
adamfowleruk
42bf6c136b9f6b914ccb85044ba0132dc453ba41
470
cpp
C++
bzoj/1261.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
3
2017-09-17T09:12:50.000Z
2018-04-06T01:18:17.000Z
bzoj/1261.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
bzoj/1261.cpp
swwind/code
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
[ "WTFPL" ]
null
null
null
#include <bits/stdc++.h> #define ll long long using namespace std; int a[5050], len, n; int mul(int val){ for(int i = 1; i <= len; i++) a[i]*=val; for(int i = 1; i <= len; i++){ a[i+1]+=a[i]/10; a[i]%=10; } if(a[len+1])len++; } int main(){ scanf("%d", &n); a[len=1]=1; while(n > 4) mul(3), n-=3; mul(n); printf("%d\n", len); if(len > 100) for(int i = 0; i < 100; i++) putchar(a[len-i]+'0'); else for(int i = len; i; i--) putchar(a[i]+'0'); return 0; }
19.583333
66
0.510638
swwind
42ca18dbe7063fba14cb1e1702ba8e4dbc5225ac
9,112
cc
C++
tensorflow/lite/experimental/micro/examples/micro_speech/micro_features/filterbank_util.cc
uve/tensorflow
e08079463bf43e5963acc41da1f57e95603f8080
[ "Apache-2.0" ]
null
null
null
tensorflow/lite/experimental/micro/examples/micro_speech/micro_features/filterbank_util.cc
uve/tensorflow
e08079463bf43e5963acc41da1f57e95603f8080
[ "Apache-2.0" ]
null
null
null
tensorflow/lite/experimental/micro/examples/micro_speech/micro_features/filterbank_util.cc
uve/tensorflow
e08079463bf43e5963acc41da1f57e95603f8080
[ "Apache-2.0" ]
null
null
null
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/experimental/micro/examples/micro_speech/micro_features/filterbank_util.h" #include <assert.h> #include <math.h> #include "tensorflow/lite/experimental/micro/examples/micro_speech/micro_features/static_alloc.h" #define kFilterbankIndexAlignment 4 #define kFilterbankChannelBlockSize 4 void FilterbankFillConfigWithDefaults(struct FilterbankConfig* config) { config->num_channels = 32; config->lower_band_limit = 125.0f; config->upper_band_limit = 7500.0f; config->output_scale_shift = 7; } static float FreqToMel(float freq) { return 1127.0 * log(1.0 + (freq / 700.0)); } static void CalculateCenterFrequencies(const int num_channels, const float lower_frequency_limit, const float upper_frequency_limit, float* center_frequencies) { assert(lower_frequency_limit >= 0.0f); assert(upper_frequency_limit > lower_frequency_limit); const float mel_low = FreqToMel(lower_frequency_limit); const float mel_hi = FreqToMel(upper_frequency_limit); const float mel_span = mel_hi - mel_low; const float mel_spacing = mel_span / (static_cast<float>(num_channels)); int i; for (i = 0; i < num_channels; ++i) { center_frequencies[i] = mel_low + (mel_spacing * (i + 1)); } } static void QuantizeFilterbankWeights(const float float_weight, int16_t* weight, int16_t* unweight) { *weight = floor(float_weight * (1 << kFilterbankBits) + 0.5); *unweight = floor((1.0 - float_weight) * (1 << kFilterbankBits) + 0.5); } int FilterbankPopulateState(tflite::ErrorReporter* error_reporter, const struct FilterbankConfig* config, struct FilterbankState* state, int sample_rate, int spectrum_size) { state->num_channels = config->num_channels; const int num_channels_plus_1 = config->num_channels + 1; // How should we align things to index counts given the byte alignment? const int index_alignment = (kFilterbankIndexAlignment < sizeof(int16_t) ? 1 : kFilterbankIndexAlignment / sizeof(int16_t)); STATIC_ALLOC_ENSURE_ARRAY_SIZE( state->channel_frequency_starts, (num_channels_plus_1 * sizeof(*state->channel_frequency_starts))); STATIC_ALLOC_ENSURE_ARRAY_SIZE( state->channel_weight_starts, (num_channels_plus_1 * sizeof(*state->channel_weight_starts))); STATIC_ALLOC_ENSURE_ARRAY_SIZE( state->channel_widths, (num_channels_plus_1 * sizeof(*state->channel_widths))); STATIC_ALLOC_ENSURE_ARRAY_SIZE(state->work, (num_channels_plus_1 * sizeof(*state->work))); float center_mel_freqs[kFeatureSliceSize + 1]; STATIC_ALLOC_ENSURE_ARRAY_SIZE( center_mel_freqs, (num_channels_plus_1 * sizeof(*center_mel_freqs))); int16_t actual_channel_starts[kFeatureSliceSize + 1]; STATIC_ALLOC_ENSURE_ARRAY_SIZE( actual_channel_starts, (num_channels_plus_1 * sizeof(*actual_channel_starts))); int16_t actual_channel_widths[kFeatureSliceSize + 1]; STATIC_ALLOC_ENSURE_ARRAY_SIZE( actual_channel_widths, (num_channels_plus_1 * sizeof(*actual_channel_widths))); CalculateCenterFrequencies(num_channels_plus_1, config->lower_band_limit, config->upper_band_limit, center_mel_freqs); // Always exclude DC. const float hz_per_sbin = 0.5 * sample_rate / (static_cast<float>(spectrum_size) - 1); state->start_index = 1.5 + config->lower_band_limit / hz_per_sbin; state->end_index = 0; // Initialized to zero here, but actually set below. // For each channel, we need to figure out what frequencies belong to it, and // how much padding we need to add so that we can efficiently multiply the // weights and unweights for accumulation. To simplify the multiplication // logic, all channels will have some multiplication to do (even if there are // no frequencies that accumulate to that channel) - they will be directed to // a set of zero weights. int chan_freq_index_start = state->start_index; int weight_index_start = 0; int needs_zeros = 0; int chan; for (chan = 0; chan < num_channels_plus_1; ++chan) { // Keep jumping frequencies until we overshoot the bound on this channel. int freq_index = chan_freq_index_start; while (FreqToMel((freq_index)*hz_per_sbin) <= center_mel_freqs[chan]) { ++freq_index; } const int width = freq_index - chan_freq_index_start; actual_channel_starts[chan] = chan_freq_index_start; actual_channel_widths[chan] = width; if (width == 0) { // This channel doesn't actually get anything from the frequencies, it's // always zero. We need then to insert some 'zero' weights into the // output, and just redirect this channel to do a single multiplication at // this point. For simplicity, the zeros are placed at the beginning of // the weights arrays, so we have to go and update all the other // weight_starts to reflect this shift (but only once). state->channel_frequency_starts[chan] = 0; state->channel_weight_starts[chan] = 0; state->channel_widths[chan] = kFilterbankChannelBlockSize; if (!needs_zeros) { needs_zeros = 1; int j; for (j = 0; j < chan; ++j) { state->channel_weight_starts[j] += kFilterbankChannelBlockSize; } weight_index_start += kFilterbankChannelBlockSize; } } else { // How far back do we need to go to ensure that we have the proper // alignment? const int aligned_start = (chan_freq_index_start / index_alignment) * index_alignment; const int aligned_width = (chan_freq_index_start - aligned_start + width); const int padded_width = (((aligned_width - 1) / kFilterbankChannelBlockSize) + 1) * kFilterbankChannelBlockSize; state->channel_frequency_starts[chan] = aligned_start; state->channel_weight_starts[chan] = weight_index_start; state->channel_widths[chan] = padded_width; weight_index_start += padded_width; } chan_freq_index_start = freq_index; } // Allocate the two arrays to store the weights - weight_index_start contains // the index of what would be the next set of weights that we would need to // add, so that's how many weights we need to allocate. STATIC_ALLOC_ENSURE_ARRAY_SIZE( state->weights, (weight_index_start * sizeof(*state->weights))); for (int i = 0; i < weight_index_start; ++i) { state->weights[i] = 0; } STATIC_ALLOC_ENSURE_ARRAY_SIZE( state->unweights, (weight_index_start * sizeof(*state->unweights))); for (int i = 0; i < weight_index_start; ++i) { state->unweights[i] = 0; } // Next pass, compute all the weights. Since everything has been memset to // zero, we only need to fill in the weights that correspond to some frequency // for a channel. const float mel_low = FreqToMel(config->lower_band_limit); for (chan = 0; chan < num_channels_plus_1; ++chan) { int frequency = actual_channel_starts[chan]; const int num_frequencies = actual_channel_widths[chan]; const int frequency_offset = frequency - state->channel_frequency_starts[chan]; const int weight_start = state->channel_weight_starts[chan]; const float denom_val = (chan == 0) ? mel_low : center_mel_freqs[chan - 1]; int j; for (j = 0; j < num_frequencies; ++j, ++frequency) { const float weight = (center_mel_freqs[chan] - FreqToMel(frequency * hz_per_sbin)) / (center_mel_freqs[chan] - denom_val); // Make the float into an integer for the weights (and unweights). const int weight_index = weight_start + frequency_offset + j; QuantizeFilterbankWeights(weight, state->weights + weight_index, state->unweights + weight_index); } if (frequency > state->end_index) { state->end_index = frequency; } } if (state->end_index >= spectrum_size) { error_reporter->Report("Filterbank end_index is above spectrum size."); return 0; } return 1; }
42.779343
101
0.674056
uve
42cc99107701f2f6cd3ea17c5e1ebb7147bd583b
340
cpp
C++
Proyecto_Final-Jorge_Pastor_V2/Trabajo de informatica/Trabajo_InformaticaI/propietarios.cpp
jorgepastor5/Spaceships-shop-manager
51ec0aad6042f4a247a4d385c7ff4ab9233f7c35
[ "MIT" ]
null
null
null
Proyecto_Final-Jorge_Pastor_V2/Trabajo de informatica/Trabajo_InformaticaI/propietarios.cpp
jorgepastor5/Spaceships-shop-manager
51ec0aad6042f4a247a4d385c7ff4ab9233f7c35
[ "MIT" ]
null
null
null
Proyecto_Final-Jorge_Pastor_V2/Trabajo de informatica/Trabajo_InformaticaI/propietarios.cpp
jorgepastor5/Spaceships-shop-manager
51ec0aad6042f4a247a4d385c7ff4ab9233f7c35
[ "MIT" ]
null
null
null
#include <iostream> #include <string.h> #include "propietarios.h" #include <aplicacion.h> #include <naves.h> using namespace std; propietarios::propietarios(){ } void propietarios::setPlaneta(string planeta){ this->planeta = planeta; } string propietarios::getPlaneta(){ return planeta; } propietarios::~propietarios(){ }
12.592593
46
0.714706
jorgepastor5
42cd05326a8fba4bdf024c553065cb2b6aaab797
1,716
cpp
C++
model/src/ConstraintBlockImpl.cpp
mballance-sf/open-ps
a5ed44ce30bfe59462801ca7de4361d16950bcd2
[ "Apache-2.0" ]
null
null
null
model/src/ConstraintBlockImpl.cpp
mballance-sf/open-ps
a5ed44ce30bfe59462801ca7de4361d16950bcd2
[ "Apache-2.0" ]
null
null
null
model/src/ConstraintBlockImpl.cpp
mballance-sf/open-ps
a5ed44ce30bfe59462801ca7de4361d16950bcd2
[ "Apache-2.0" ]
null
null
null
/* * ConstraintBlockImpl.cpp * * * Copyright 2016 Mentor Graphics Corporation * All Rights Reserved Worldwide * * 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. * * Created on: May 4, 2016 * Author: ballance */ #include "ConstraintBlockImpl.h" ConstraintBlockImpl::ConstraintBlockImpl(const std::string &name) : BaseItemImpl(IBaseItem::TypeConstraint), NamedItemImpl(name) { } ConstraintBlockImpl::~ConstraintBlockImpl() { // TODO Auto-generated destructor stub } void ConstraintBlockImpl::add(IConstraint *c) { if (c) { c->setParent(this); m_constraints.push_back(c); } } void ConstraintBlockImpl::add(const std::vector<IConstraint *> &cl) { std::vector<IConstraint *>::const_iterator it; for (it=cl.begin(); it!=cl.end(); it++) { (*it)->setParent(this); m_constraints.push_back(*it); } } IBaseItem *ConstraintBlockImpl::clone() const { ConstraintBlockImpl *ret = new ConstraintBlockImpl(getName()); for (std::vector<IConstraint *>::const_iterator it=getConstraints().begin(); it!=getConstraints().end(); it++) { ret->add(dynamic_cast<IConstraint *>((*it)->clone())); } return ret; }
26.4
78
0.685897
mballance-sf
42ce15e3ef1c818c6fa7f3164b3ea50efac752c3
720
cpp
C++
0-100/7/main.cpp
KevinEsh/LeetCode-Problems
7e29509ad1cdc907bbba339f82e89f9e210e8249
[ "MIT" ]
null
null
null
0-100/7/main.cpp
KevinEsh/LeetCode-Problems
7e29509ad1cdc907bbba339f82e89f9e210e8249
[ "MIT" ]
null
null
null
0-100/7/main.cpp
KevinEsh/LeetCode-Problems
7e29509ad1cdc907bbba339f82e89f9e210e8249
[ "MIT" ]
null
null
null
#include <string> #include <iostream> #include <algorithm> #define lower -2147483648 #define upper 2147483647 class Solution { public: int reverse(int x) { std::string sx = x < 0 ? "-" : ""; sx += std::to_string(abs(x)); if (x < 0) { std::reverse(sx.begin() + 1, sx.end()); } else { std::reverse(sx.begin(), sx.end()); } long long lx = stol(sx); if (lower <= lx && lx <= upper) { return (int)lx; } return 0; } }; int main() { Solution model = Solution(); int reversed = model.reverse(-124265343); std::cout << reversed << std::endl; return 0; }
16.744186
51
0.475
KevinEsh
42d20121235ebecbae7e13193478f3f5503966f2
619
cpp
C++
max_profit.cpp
shirishbahirat/algorithm
ec743d4c16ab4f429f22bd6f71540341b3905b3b
[ "Apache-2.0" ]
null
null
null
max_profit.cpp
shirishbahirat/algorithm
ec743d4c16ab4f429f22bd6f71540341b3905b3b
[ "Apache-2.0" ]
null
null
null
max_profit.cpp
shirishbahirat/algorithm
ec743d4c16ab4f429f22bd6f71540341b3905b3b
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: int maxProfit(vector<int> &prices) { int minprice = 0x7FFFFFFF; int maxprofit = 0; for (int i = 0; i < prices.size(); i++) { if (prices[i] < minprice) minprice = prices[i]; else if (prices[i] - minprice > maxprofit) maxprofit = prices[i] - minprice; } return maxprofit; } }; int main(int argc, char const *argv[]) { Solution *obj = new Solution(); vector<int> prices = {7, 1, 5, 3, 6, 4}; int profit = obj->maxProfit(prices); cout << profit << endl; return 0; }
18.205882
48
0.588045
shirishbahirat
42d36a7ff407d996315af2f45511739d597bc098
8,305
hpp
C++
SDK/PUBG_GameplayTasks_classes.hpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
7
2019-03-06T11:04:52.000Z
2019-07-10T20:00:51.000Z
SDK/PUBG_GameplayTasks_classes.hpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
null
null
null
SDK/PUBG_GameplayTasks_classes.hpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
10
2019-03-06T11:53:46.000Z
2021-02-18T14:01:11.000Z
#pragma once // PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "PUBG_GameplayTasks_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // Class GameplayTasks.GameplayTaskResource // 0x0010 (0x0040 - 0x0030) class UGameplayTaskResource : public UObject { public: int ManualResourceID; // 0x0030(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, Config, DisableEditOnInstance, IsPlainOldData) int8_t AutoResourceID; // 0x0034(0x0001) (ZeroConstructor, IsPlainOldData) unsigned char UnknownData00[0x3]; // 0x0035(0x0003) MISSED OFFSET unsigned char bManuallySetID : 1; // 0x0038(0x0001) (Edit, DisableEditOnInstance) unsigned char UnknownData01[0x7]; // 0x0039(0x0007) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTaskResource"); return ptr; } }; // Class GameplayTasks.GameplayTask // 0x0040 (0x0070 - 0x0030) class UGameplayTask : public UObject { public: unsigned char UnknownData00[0x8]; // 0x0030(0x0008) MISSED OFFSET struct FName InstanceName; // 0x0038(0x0008) (ZeroConstructor, IsPlainOldData) unsigned char UnknownData01[0x2]; // 0x0040(0x0002) MISSED OFFSET ETaskResourceOverlapPolicy ResourceOverlapPolicy; // 0x0042(0x0001) (ZeroConstructor, Config, IsPlainOldData) unsigned char UnknownData02[0x25]; // 0x0043(0x0025) MISSED OFFSET class UGameplayTask* ChildTask; // 0x0068(0x0008) (ZeroConstructor, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTask"); return ptr; } void ReadyForActivation(); void GenericGameplayTaskDelegate__DelegateSignature(); void EndTask(); }; // Class GameplayTasks.GameplayTaskOwnerInterface // 0x0000 (0x0030 - 0x0030) class UGameplayTaskOwnerInterface : public UInterface { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTaskOwnerInterface"); return ptr; } }; // Class GameplayTasks.GameplayTask_ClaimResource // 0x0000 (0x0070 - 0x0070) class UGameplayTask_ClaimResource : public UGameplayTask { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTask_ClaimResource"); return ptr; } void ReadyForActivation(); void GenericGameplayTaskDelegate__DelegateSignature(); void EndTask(); }; // Class GameplayTasks.GameplayTask_SpawnActor // 0x0040 (0x00B0 - 0x0070) class UGameplayTask_SpawnActor : public UGameplayTask { public: struct FScriptMulticastDelegate SUCCESS; // 0x0070(0x0010) (ZeroConstructor, InstancedReference, BlueprintAssignable) struct FScriptMulticastDelegate DidNotSpawn; // 0x0080(0x0010) (ZeroConstructor, InstancedReference, BlueprintAssignable) unsigned char UnknownData00[0x18]; // 0x0090(0x0018) MISSED OFFSET class UClass* ClassToSpawn; // 0x00A8(0x0008) (ZeroConstructor, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTask_SpawnActor"); return ptr; } class UGameplayTask_SpawnActor* STATIC_SpawnActor(TScriptInterface<class UGameplayTaskOwnerInterface>* TaskOwner, struct FVector* SpawnLocation, struct FRotator* SpawnRotation, class UClass** Class, bool* bSpawnOnlyOnAuthority); void FinishSpawningActor(class UObject** WorldContextObject, class AActor** SpawnedActor); bool BeginSpawningActor(class UObject** WorldContextObject, class AActor** SpawnedActor); }; // Class GameplayTasks.GameplayTask_TimeLimitedExecution // 0x0030 (0x00A0 - 0x0070) class UGameplayTask_TimeLimitedExecution : public UGameplayTask { public: struct FScriptMulticastDelegate OnFinished; // 0x0070(0x0010) (ZeroConstructor, InstancedReference, BlueprintAssignable) struct FScriptMulticastDelegate OnTimeExpired; // 0x0080(0x0010) (ZeroConstructor, InstancedReference, BlueprintAssignable) unsigned char UnknownData00[0x10]; // 0x0090(0x0010) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTask_TimeLimitedExecution"); return ptr; } void TaskFinishDelegate__DelegateSignature(); }; // Class GameplayTasks.GameplayTask_WaitDelay // 0x0018 (0x0088 - 0x0070) class UGameplayTask_WaitDelay : public UGameplayTask { public: struct FScriptMulticastDelegate OnFinish; // 0x0070(0x0010) (ZeroConstructor, InstancedReference, BlueprintAssignable) unsigned char UnknownData00[0x8]; // 0x0080(0x0008) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTask_WaitDelay"); return ptr; } class UGameplayTask_WaitDelay* STATIC_TaskWaitDelay(TScriptInterface<class UGameplayTaskOwnerInterface>* TaskOwner, float* Time, unsigned char* Priority); void TaskDelayDelegate__DelegateSignature(); }; // Class GameplayTasks.GameplayTasksComponent // 0x0070 (0x0260 - 0x01F0) class UGameplayTasksComponent : public UActorComponent { public: unsigned char UnknownData00[0x8]; // 0x01F0(0x0008) MISSED OFFSET TArray<class UGameplayTask*> SimulatedTasks; // 0x01F8(0x0010) (Net, ZeroConstructor) TArray<class UGameplayTask*> TaskPriorityQueue; // 0x0208(0x0010) (ZeroConstructor) unsigned char UnknownData01[0x10]; // 0x0218(0x0010) MISSED OFFSET TArray<class UGameplayTask*> TickingTasks; // 0x0228(0x0010) (ZeroConstructor) unsigned char UnknownData02[0x8]; // 0x0238(0x0008) MISSED OFFSET struct FScriptMulticastDelegate OnClaimedResourcesChange; // 0x0240(0x0010) (BlueprintVisible, ZeroConstructor, InstancedReference) unsigned char UnknownData03[0x10]; // 0x0250(0x0010) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTasksComponent"); return ptr; } void OnRep_SimulatedTasks(); EGameplayTaskRunResult STATIC_K2_RunGameplayTask(TScriptInterface<class UGameplayTaskOwnerInterface>* TaskOwner, class UGameplayTask** Task, unsigned char* Priority, TArray<class UClass*>* AdditionalRequiredResources, TArray<class UClass*>* AdditionalClaimedResources); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
43.710526
270
0.586635
realrespecter
42d3a2f68e017ecba874aac3207ad55e3241fd65
981
cpp
C++
src/sharding/hasher.cpp
oystr-foss/proxy-load-balancer
14a58a1db4a189f27d0671cb89cfa4a06bd8b415
[ "BSL-1.0" ]
9
2020-10-06T16:36:11.000Z
2021-07-25T15:06:25.000Z
src/sharding/hasher.cpp
oystr-foss/proxy-load-balancer
14a58a1db4a189f27d0671cb89cfa4a06bd8b415
[ "BSL-1.0" ]
null
null
null
src/sharding/hasher.cpp
oystr-foss/proxy-load-balancer
14a58a1db4a189f27d0671cb89cfa4a06bd8b415
[ "BSL-1.0" ]
null
null
null
// // Created by realngnx on 11/06/2021. // #include <openssl/sha.h> #include <openssl/md5.h> #include "./hasher.hpp" long Digest::to_md5_hash(std::string key) { const char * hashed = reinterpret_cast<const char *>(md5(key)); return calculate_hash(hashed); } long Digest::to_sha256_hash(std::string key) { const char * hashed = reinterpret_cast<const char *>(sha256(key)); return calculate_hash(hashed); } long Digest::calculate_hash(const char *hashed) { long hash = 0; for (int i = 0; i < 4; i++) { hash <<= 8; hash |= ((int) hashed[i]) & 0xFF; } return hash; } const unsigned char * Digest::sha256(const std::string &key) { char const *c = key.c_str(); return SHA256(reinterpret_cast<const unsigned char *>(c), key.length(), nullptr); } const unsigned char * Digest::md5(const std::string &key) { char const *c = key.c_str(); return MD5(reinterpret_cast<const unsigned char *>(c), key.length(), nullptr); }
25.815789
85
0.64526
oystr-foss
42d504427440ff4dcf5cf5f7baa66f1310cf7b39
917
cpp
C++
AddIn/DemoAddIn/cpp/DemoAddIn/EdgeBarDialog.cpp
XelaNimed/Samples
2b509c985d99b53a9de1e2fb377a5a54dae43987
[ "MIT" ]
34
2015-06-08T05:10:28.000Z
2022-02-08T20:15:42.000Z
AddIn/DemoAddIn/cpp/DemoAddIn/EdgeBarDialog.cpp
kabircosta/Samples
3ffe1b268d49ec63686078d5c4f4d6eccb8f6f5f
[ "MIT" ]
1
2019-04-03T06:32:23.000Z
2019-04-03T06:32:23.000Z
AddIn/DemoAddIn/cpp/DemoAddIn/EdgeBarDialog.cpp
kabircosta/Samples
3ffe1b268d49ec63686078d5c4f4d6eccb8f6f5f
[ "MIT" ]
44
2015-03-26T17:29:45.000Z
2021-12-29T03:41:29.000Z
// EdgeBarDialog.cpp : implementation file // #include "stdafx.h" #include "DemoAddIn.h" #include "EdgeBarDialog.h" #include "afxdialogex.h" // CEdgeBarDialog dialog IMPLEMENT_DYNAMIC(CEdgeBarDialog, CDialogEx) CEdgeBarDialog::CEdgeBarDialog(CWnd* pParent /*=NULL*/) : CDialogEx(CEdgeBarDialog::IDD, pParent) { } CEdgeBarDialog::~CEdgeBarDialog() { } void CEdgeBarDialog::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_LIST1, m_listView); } BEGIN_MESSAGE_MAP(CEdgeBarDialog, CDialogEx) ON_WM_SIZE() END_MESSAGE_MAP() // CEdgeBarDialog message handlers void CEdgeBarDialog::OnSize(UINT nType, int cx, int cy) { CDialogEx::OnSize(nType, cx, cy); // TODO: Add your message handler code here RECT rect; // Get the dialog rectangle. GetClientRect(&rect); // Resize CListCtrl. if (m_listView.m_hWnd != NULL) { m_listView.MoveWindow(&rect, TRUE); } }
16.981481
55
0.742639
XelaNimed
42da23d3f9b47e5504e83b1de7b6fb30fa6face1
6,368
cpp
C++
analysis_pipelines/scripts/scVILP/scripts/PerfectPhy/tools/convert.cpp
ProSolo/benchmarking_prosolo
60fc1fcc990be9eedcdf024670fa81e68c0d3e2f
[ "MIT" ]
2
2020-04-29T02:56:42.000Z
2021-03-04T21:17:15.000Z
analysis_pipelines/scripts/scVILP/scripts/PerfectPhy/tools/convert.cpp
ProSolo/benchmarking_prosolo
60fc1fcc990be9eedcdf024670fa81e68c0d3e2f
[ "MIT" ]
null
null
null
analysis_pipelines/scripts/scVILP/scripts/PerfectPhy/tools/convert.cpp
ProSolo/benchmarking_prosolo
60fc1fcc990be9eedcdf024670fa81e68c0d3e2f
[ "MIT" ]
null
null
null
#include<vector> #include<fstream> #include<iostream> #include<cctype> using namespace std; enum ArgError { ERROR = -1, QUIT = 0, NONE = 1 }; ArgError handleArguments(int argc, char** argv, char &dummychar, string &index, string &mapfile ) { const char* helpmessage = "Usage: ./convert.out [option] \n" "\n" "Options:\n" "-h, --help Displays this message then quits.\n" "-dummy CHAR Set CHAR as a dummy state (outputs -1).\n" "-index I Set index of dataset as I (default is 1).\n" "-mapfile FILE Writes the state mapping to FILE\n"; string arg; for (int i = 1; i < argc; i++) { if (argv[i][0] != '-') { cerr << "Bad argument: " << argv[i] << " is not a flag" << endl; return ERROR; } arg = argv[i]; if (arg.compare("-dummy") == 0) { if (argc > i + 1) { dummychar = argv[i+1][0]; if (!isgraph(dummychar)) { cerr << "Bad argument: dummy character must be graphical" << endl; return ERROR; } i++; } else { cerr << "Bad argument: " << arg << " must precede a character" << endl; return ERROR; } } else if (arg.compare("-index") == 0) { if (argc > i + 1) { index = argv[i+1]; for (unsigned int j = 0; j < index.size(); j++) if ( !( isdigit(index[j]) || (j == 0 && index[j] == '-' && index.size() > 1) ) ) { cerr << "Bad argument: index must be an integer, not " << index << endl; return ERROR; } i++; } else { cerr << "Bad argument: " << arg << " must precede an integer" << endl; return ERROR; } } else if (arg.compare("-mapfile") == 0) { if (argc > i + 1) { mapfile = argv[i+1]; i++; } else { cerr << "Bad argument: " << arg << " must precede a filename" << endl; return ERROR; } } else if (arg.compare("-h") == 0 || arg.compare("--help") == 0) { cout << helpmessage; return QUIT; } else { cerr << "Bad argument: " << arg << " is not a valid flag" << endl; return ERROR; } } return NONE; } class Mapping { private: char c; int n; public: Mapping(char in, int out):c(in), n(out) {} void printTo(ostream& outf) const { outf << c << ' ' << n << ' '; } }; #define readinto(var) do {\ cin >> var;\ if (!cin) {\ cerr << "Input error: " << #var << " could not be read" << endl;\ cerr << "Expected input:" << endl << "n m" << endl << "(n rows of: (10-char name) (m matrix cells...) )" << endl;\ return -1;\ }\ } while(false) int main(int argc, char** argv) { char dummychar = '\0'; string index; string mapfile; #define NAMEWIDTH 10 // improve io speed since not using C streams ios_base::sync_with_stdio(false); ArgError argerr = handleArguments(argc, argv, dummychar, index, mapfile); if (argerr != NONE) return argerr; if (index.empty()) index = "1"; bool outputmap = (mapfile.size() > 0); // read size of matrix int n, m; readinto(n); readinto(m); vector<vector<int> > data(n, vector<int>(m)); for (int i = 0; i < n; i++) { vector<int>& row = data[i]; char cell; // skip over the 10-character name cin >> noskipws; while (cin.get() != '\n'); cin.ignore(NAMEWIDTH); cin >> skipws; for (int j = 0; j < m; j++) { int& mcell = row[j]; // skip over spaces between cells //while (cin.peek() == ' ') // cin.get(c); readinto(cell); if (cell == dummychar) mcell = -1; else mcell = cell; } } // convert to multistate numbers without gaps vector<int> stateMap; vector<vector<Mapping> > allmaps; if (outputmap) { allmaps.resize(m); for(int j = 0; j < m; j++) allmaps[j].reserve(n); } for (int j = 0; j < m; j++) { for (int i = 0; i < n; i++) { int& cell = data[i][j]; if (cell == -1) continue; int k, statecount = stateMap.size(); for (k = 0; k < statecount; k++) if (stateMap[k] == cell) { cell = k; break; } if (k == statecount) { if (outputmap) allmaps[j].push_back(Mapping(cell, k)); stateMap.push_back(cell); cell = k; } } stateMap.clear(); } if (outputmap) { // write mapping to mapfile ofstream outf(mapfile.c_str()); outf << index << endl << m; if (dummychar != '\0') { outf << ' '; Mapping(dummychar, -1).printTo(outf); } outf << endl; for (int j = 0; j < m; j++) { const vector<Mapping>& row = allmaps[j]; outf << (int) row.size() << " "; for (unsigned int k = 0; k < row.size(); k++) row[k].printTo(outf); outf << endl; } } // write data to stdout cout << index << endl << n << ' ' << m << endl; for (int i = 0; i < n; i++) { const vector<int>& row = data[i]; for (int j = 0; j < m; j++) cout << row[j] << ' '; cout << endl; } return 0; } #undef readinto
26.533333
126
0.400911
ProSolo
42dc5e85be449bb356e0607f71257bb5befcd199
1,198
cpp
C++
test/unit/math/prim/fun/svd_V_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/prim/fun/svd_V_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/prim/fun/svd_V_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
#include <stan/math/prim.hpp> #include <gtest/gtest.h> #include <test/unit/util.hpp> #include <stdexcept> TEST(MathMatrixPrimMat, svd_V) { using stan::math::matrix_d; using stan::math::svd_V; // Values generated using R base::svd matrix_d m00(0, 0); EXPECT_THROW(svd_V(m00), std::invalid_argument); matrix_d m11(1, 1); m11 << 5; matrix_d m11_V(1, 1); m11_V << 1; EXPECT_MATRIX_FLOAT_EQ(m11_V, svd_V(m11)); matrix_d m22(2, 2); m22 << 1, 9, -4, 2; matrix_d m22_V(2, 2); m22_V << 0.014701114509569043, 0.999891932776825976, 0.999891932776825976, -0.014701114509569043; EXPECT_MATRIX_FLOAT_EQ(m22_V, svd_V(m22)); matrix_d m23(2, 3); m23 << 1, 3, -5, 7, 9, -11; matrix_d m23_V(3, 2); m23_V << -0.41176240532160857, 0.81473005032163681, -0.56383954240865775, 0.12417046246885260, 0.71591667949570703, 0.56638912538393127; EXPECT_MATRIX_FLOAT_EQ(m23_V, svd_V(m23)); matrix_d m32(3, 2); m32 << 1, 3, -5, 7, 9, -11; matrix_d m32_V(2, 2); m32_V << -0.60622380392317887, 0.79529409626685355, 0.79529409626685355, 0.60622380392317887; EXPECT_MATRIX_FLOAT_EQ( m32_V, svd_V(m32)); // R's SVD returns different signs than Eigen. }
27.860465
76
0.682805
LaudateCorpus1
42ddfb6b787055c1ca8ab033ae14936586fa5e59
2,590
cpp
C++
src/schemas/project/mutations/CreateTrade.cpp
BlockChain-Station/enjin-cpp-sdk
3af1cd001d7e660787bbfb2e2414a96f5a95a228
[ "Apache-2.0" ]
12
2021-09-28T14:37:22.000Z
2022-03-04T17:54:11.000Z
src/schemas/project/mutations/CreateTrade.cpp
BlockChain-Station/enjin-cpp-sdk
3af1cd001d7e660787bbfb2e2414a96f5a95a228
[ "Apache-2.0" ]
null
null
null
src/schemas/project/mutations/CreateTrade.cpp
BlockChain-Station/enjin-cpp-sdk
3af1cd001d7e660787bbfb2e2414a96f5a95a228
[ "Apache-2.0" ]
8
2021-11-05T18:56:55.000Z
2022-01-10T11:14:24.000Z
/* Copyright 2021 Enjin Pte. Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "enjinsdk/project/CreateTrade.hpp" #include "RapidJsonUtils.hpp" namespace enjin::sdk::project { CreateTrade::CreateTrade() : graphql::AbstractGraphqlRequest("enjin.sdk.project.CreateTrade") { } std::string CreateTrade::serialize() const { rapidjson::Document document(rapidjson::kObjectType); utils::join_serialized_object_to_document(document, ProjectTransactionRequestArguments::serialize()); if (asking_assets.has_value()) { utils::set_array_member_from_type_vector<models::Trade>(document, "askingAssets", asking_assets.value()); } if (offering_assets.has_value()) { utils::set_array_member_from_type_vector<models::Trade>(document, "offeringAssets", offering_assets.value()); } if (recipient_address.has_value()) { utils::set_string_member(document, "recipientAddress", recipient_address.value()); } return utils::document_to_string(document); } CreateTrade& CreateTrade::set_asking_assets(std::vector<models::Trade> assets) { asking_assets = assets; return *this; } CreateTrade& CreateTrade::set_offering_assets(std::vector<models::Trade> assets) { offering_assets = assets; return *this; } CreateTrade& CreateTrade::set_recipient_address(const std::string& recipient_address) { CreateTrade::recipient_address = recipient_address; return *this; } bool CreateTrade::operator==(const CreateTrade& rhs) const { return static_cast<const graphql::AbstractGraphqlRequest&>(*this) == static_cast<const graphql::AbstractGraphqlRequest&>(rhs) && static_cast<const ProjectTransactionRequestArguments<CreateTrade>&>(*this) == static_cast<const ProjectTransactionRequestArguments<CreateTrade>&>(rhs) && asking_assets == rhs.asking_assets && offering_assets == rhs.offering_assets && recipient_address == rhs.recipient_address; } bool CreateTrade::operator!=(const CreateTrade& rhs) const { return !(rhs == *this); } }
35.479452
117
0.72973
BlockChain-Station
42e605a1f750beaaa3612e31308570d2f47beb89
35
cpp
C++
CacheSystem/StandardInitFunctions.cpp
kivzcu/HrdDataCacheSystem
cff2e3bd40a43bd374c7b16648daaf761dc3826a
[ "Apache-2.0" ]
null
null
null
CacheSystem/StandardInitFunctions.cpp
kivzcu/HrdDataCacheSystem
cff2e3bd40a43bd374c7b16648daaf761dc3826a
[ "Apache-2.0" ]
3
2017-11-01T08:40:08.000Z
2018-02-05T07:49:18.000Z
CacheSystem/StandardInitFunctions.cpp
kivzcu/HrdDataCacheSystem
cff2e3bd40a43bd374c7b16648daaf761dc3826a
[ "Apache-2.0" ]
1
2021-02-16T13:14:23.000Z
2021-02-16T13:14:23.000Z
#include "StandardInitFunctions.h"
17.5
34
0.828571
kivzcu
42ec31f75b4445181baf206aa4b8e13eeccd87df
4,472
cpp
C++
deps/MAC_SDK/Source/MACDll/WinampSettingsDlg.cpp
jjzhang166/mous
54a219712970bd6fabbac85102e1615babb69c41
[ "BSD-2-Clause" ]
75
2015-04-26T11:22:07.000Z
2022-02-12T17:18:37.000Z
deps/MAC_SDK/Source/MACDll/WinampSettingsDlg.cpp
aliakbarRashidi/mous
54a219712970bd6fabbac85102e1615babb69c41
[ "BSD-2-Clause" ]
7
2016-05-31T21:56:01.000Z
2019-09-15T06:25:28.000Z
deps/MAC_SDK/Source/MACDll/WinampSettingsDlg.cpp
aliakbarRashidi/mous
54a219712970bd6fabbac85102e1615babb69c41
[ "BSD-2-Clause" ]
19
2015-09-23T01:50:15.000Z
2022-02-12T17:18:41.000Z
#include "stdafx.h" #include "MACDll.h" #include "WinampSettingsDlg.h" #include ".\winampsettingsdlg.h" IMPLEMENT_DYNAMIC(CWinampSettingsDlg, CDialog) CWinampSettingsDlg::CWinampSettingsDlg(CWnd * pParent) : CDialog(CWinampSettingsDlg::IDD, pParent) { m_hwndParent = NULL; GetModuleFileName(AfxGetInstanceHandle(), m_strSettingsFilename.GetBuffer(MAX_PATH), MAX_PATH); m_strSettingsFilename.ReleaseBuffer(); m_strSettingsFilename = m_strSettingsFilename.Left(m_strSettingsFilename.GetLength() - 3) + _T("ini"); LoadSettings(); } CWinampSettingsDlg::~CWinampSettingsDlg() { } void CWinampSettingsDlg::DoDataExchange(CDataExchange * pDX) { CDialog::DoDataExchange(pDX); DDX_Check(pDX, IGNORE_BITSTREAM_ERRORS_CHECK, m_bIgnoreBitstreamErrors); DDX_Check(pDX, SUPPRESS_SILENCE_CHECK, m_bSuppressSilence); DDX_Check(pDX, SCALE_OUTPUT_CHECK, m_bScaleOutput); DDX_Text(pDX, FILE_DISPLAY_METHOD_EDIT, m_strFileDisplayMethod); DDX_Control(pDX, THREAD_PRIORITY_SLIDER, m_ctrlThreadPrioritySlider); } BEGIN_MESSAGE_MAP(CWinampSettingsDlg, CDialog) END_MESSAGE_MAP() BOOL CWinampSettingsDlg::LoadSettings() { GetPrivateProfileString(_T("Plugin Settings"), _T("File Display Method"), _T("%1 - %2"), m_strFileDisplayMethod.GetBuffer(1024), 1023, m_strSettingsFilename); m_strFileDisplayMethod.ReleaseBuffer(); m_nThreadPriority = GetPrivateProfileInt(_T("Plugin Settings"), _T("Thread Priority)"), THREAD_PRIORITY_HIGHEST, m_strSettingsFilename); m_bScaleOutput = GetPrivateProfileInt(_T("Plugin Settings"), _T("Scale Output"), FALSE, m_strSettingsFilename); m_bIgnoreBitstreamErrors = GetPrivateProfileInt(_T("Plugin Settings"), _T("Ignore Bitstream Errors"), FALSE, m_strSettingsFilename); m_bSuppressSilence = GetPrivateProfileInt(_T("Plugin Settings"), _T("Suppress Silence"), FALSE, m_strSettingsFilename); return TRUE; } BOOL CWinampSettingsDlg::SaveSettings() { CString strTemp; WritePrivateProfileString(_T("Plugin Settings"), _T("File Display Method"), m_strFileDisplayMethod, m_strSettingsFilename); strTemp.Format(_T("%d"), m_nThreadPriority); WritePrivateProfileString(_T("Plugin Settings"), _T("Thread Priority"), strTemp, m_strSettingsFilename); strTemp.Format(_T("%d"), m_bScaleOutput); WritePrivateProfileString(_T("Plugin Settings"), _T("Scale Output"), strTemp, m_strSettingsFilename); strTemp.Format(_T("%d"), m_bIgnoreBitstreamErrors); WritePrivateProfileString(_T("Plugin Settings"), _T("Ignore Bitstream Errors"), strTemp, m_strSettingsFilename); strTemp.Format(_T("%d"), m_bSuppressSilence); WritePrivateProfileString(_T("Plugin Settings"), _T("Suppress Silence"), strTemp, m_strSettingsFilename); return TRUE; } BOOL CWinampSettingsDlg::Show(HWND hwndParent) { m_hwndParent = hwndParent; DoModal(); return TRUE; } BOOL CWinampSettingsDlg::OnInitDialog() { CDialog::OnInitDialog(); m_ctrlThreadPrioritySlider.SetRange(0, 4); m_ctrlThreadPrioritySlider.SetPos(GetSliderFromThreadPriority()); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CWinampSettingsDlg::OnOK() { UpdateData(TRUE); m_nThreadPriority = GetThreadPriorityFromSlider(); SaveSettings(); CDialog::OnOK(); } int CWinampSettingsDlg::GetSliderFromThreadPriority() { int nSlider = 4; switch (m_nThreadPriority) { case THREAD_PRIORITY_LOWEST: nSlider = 0; break; case THREAD_PRIORITY_BELOW_NORMAL: nSlider = 1; break; case THREAD_PRIORITY_NORMAL: nSlider = 2; break; case THREAD_PRIORITY_ABOVE_NORMAL: nSlider = 3; break; case THREAD_PRIORITY_HIGHEST: nSlider = 4; break; } return nSlider; } int CWinampSettingsDlg::GetThreadPriorityFromSlider() { int nThreadPriority = THREAD_PRIORITY_HIGHEST; switch (m_ctrlThreadPrioritySlider.GetPos()) { case 0: nThreadPriority = THREAD_PRIORITY_LOWEST; break; case 1: nThreadPriority = THREAD_PRIORITY_BELOW_NORMAL; break; case 2: nThreadPriority = THREAD_PRIORITY_NORMAL; break; case 3: nThreadPriority = THREAD_PRIORITY_ABOVE_NORMAL; break; case 4: nThreadPriority = THREAD_PRIORITY_HIGHEST; break; } return nThreadPriority; }
35.776
163
0.727862
jjzhang166
42ee21d925bf2c58bc145b5c191e40d71ac631a0
22,748
cpp
C++
vlc_linux/vlc-3.0.16/modules/demux/adaptive/Streams.cpp
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
vlc_linux/vlc-3.0.16/modules/demux/adaptive/Streams.cpp
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
vlc_linux/vlc-3.0.16/modules/demux/adaptive/Streams.cpp
Brook1711/biubiu_Qt6
5c4d22a1d1beef63bc6c7738dce6c477c4642803
[ "MIT" ]
null
null
null
/* * Streams.cpp ***************************************************************************** * Copyright (C) 2014 - VideoLAN and VLC authors * * This program 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "Streams.hpp" #include "logic/AbstractAdaptationLogic.h" #include "http/HTTPConnection.hpp" #include "http/HTTPConnectionManager.h" #include "playlist/BaseAdaptationSet.h" #include "playlist/BaseRepresentation.h" #include "playlist/SegmentChunk.hpp" #include "plumbing/SourceStream.hpp" #include "plumbing/CommandsQueue.hpp" #include "tools/FormatNamespace.hpp" #include "tools/Debug.hpp" #include <vlc_demux.h> #include <algorithm> using namespace adaptive; using namespace adaptive::http; AbstractStream::AbstractStream(demux_t * demux_) { p_realdemux = demux_; format = StreamFormat::UNKNOWN; currentChunk = NULL; eof = false; valid = true; disabled = false; discontinuity = false; needrestart = false; inrestart = false; demuxfirstchunk = false; segmentTracker = NULL; demuxersource = NULL; demuxer = NULL; fakeesout = NULL; notfound_sequence = 0; last_buffer_status = buffering_lessthanmin; vlc_mutex_init(&lock); } bool AbstractStream::init(const StreamFormat &format_, SegmentTracker *tracker, AbstractConnectionManager *conn) { /* Don't even try if not supported or already init */ if((unsigned)format_ == StreamFormat::UNSUPPORTED || demuxersource) return false; demuxersource = new (std::nothrow) BufferedChunksSourceStream( VLC_OBJECT(p_realdemux), this ); if(demuxersource) { CommandsFactory *factory = new (std::nothrow) CommandsFactory(); if(factory) { CommandsQueue *commandsqueue = new (std::nothrow) CommandsQueue(factory); if(commandsqueue) { fakeesout = new (std::nothrow) FakeESOut(p_realdemux->out, commandsqueue); if(fakeesout) { /* All successfull */ fakeesout->setExtraInfoProvider( this ); const Role & streamRole = tracker->getStreamRole(); if(streamRole.isDefault() && streamRole.autoSelectable()) fakeesout->setPriority(ES_PRIORITY_MIN + 10); else if(!streamRole.autoSelectable()) fakeesout->setPriority(ES_PRIORITY_NOT_DEFAULTABLE); format = format_; segmentTracker = tracker; segmentTracker->registerListener(this); segmentTracker->notifyBufferingState(true); connManager = conn; fakeesout->setExpectedTimestamp(segmentTracker->getPlaybackTime()); declaredCodecs(); return true; } delete commandsqueue; commandsqueue = NULL; } else { delete factory; } } delete demuxersource; } return false; } AbstractStream::~AbstractStream() { delete currentChunk; if(segmentTracker) segmentTracker->notifyBufferingState(false); delete segmentTracker; delete demuxer; delete demuxersource; delete fakeesout; vlc_mutex_destroy(&lock); } void AbstractStream::prepareRestart(bool b_discontinuity) { if(demuxer) { /* Enqueue Del Commands for all current ES */ demuxer->drain(); fakeEsOut()->resetTimestamps(); /* Enqueue Del Commands for all current ES */ fakeEsOut()->scheduleAllForDeletion(); if(b_discontinuity) fakeEsOut()->schedulePCRReset(); fakeEsOut()->commandsQueue()->Commit(); /* ignoring demuxer's own Del commands */ fakeEsOut()->commandsQueue()->setDrop(true); delete demuxer; fakeEsOut()->commandsQueue()->setDrop(false); demuxer = NULL; } } void AbstractStream::setLanguage(const std::string &lang) { language = lang; } void AbstractStream::setDescription(const std::string &desc) { description = desc; } mtime_t AbstractStream::getPCR() const { vlc_mutex_locker locker(const_cast<vlc_mutex_t *>(&lock)); if(!valid || disabled) return VLC_TS_INVALID; return fakeEsOut()->commandsQueue()->getPCR(); } mtime_t AbstractStream::getMinAheadTime() const { if(!segmentTracker) return 0; return segmentTracker->getMinAheadTime(); } mtime_t AbstractStream::getFirstDTS() const { vlc_mutex_locker locker(const_cast<vlc_mutex_t *>(&lock)); if(!valid || disabled) return VLC_TS_INVALID; mtime_t dts = fakeEsOut()->commandsQueue()->getFirstDTS(); if(dts == VLC_TS_INVALID) dts = fakeEsOut()->commandsQueue()->getPCR(); return dts; } int AbstractStream::esCount() const { return fakeEsOut()->esCount(); } bool AbstractStream::seekAble() const { bool restarting = fakeEsOut()->restarting(); bool draining = fakeEsOut()->commandsQueue()->isDraining(); bool eof = fakeEsOut()->commandsQueue()->isEOF(); msg_Dbg(p_realdemux, "demuxer %p, fakeesout restarting %d, " "discontinuity %d, commandsqueue draining %d, commandsqueue eof %d", static_cast<void *>(demuxer), restarting, discontinuity, draining, eof); if(!valid || restarting || discontinuity || (!eof && draining)) { msg_Warn(p_realdemux, "not seekable"); return false; } else { return true; } } bool AbstractStream::isSelected() const { return fakeEsOut()->hasSelectedEs(); } bool AbstractStream::reactivate(mtime_t basetime) { vlc_mutex_locker locker(&lock); if(setPosition(basetime, false)) { setDisabled(false); return true; } else { eof = true; /* can't reactivate */ return false; } } bool AbstractStream::startDemux() { if(demuxer) return false; demuxersource->Reset(); demuxer = createDemux(format); if(!demuxer && format != StreamFormat()) msg_Err(p_realdemux, "Failed to create demuxer %p %s", (void *)demuxer, format.str().c_str()); demuxfirstchunk = true; return !!demuxer; } bool AbstractStream::restartDemux() { bool b_ret = true; if(!demuxer) { fakeesout->recycleAll(); b_ret = startDemux(); } else if(demuxer->needsRestartOnSeek()) { inrestart = true; /* Push all ES as recycling candidates */ fakeEsOut()->recycleAll(); /* Restart with ignoring es_Del pushes to queue when terminating demux */ fakeEsOut()->commandsQueue()->setDrop(true); demuxer->destroy(); fakeEsOut()->commandsQueue()->setDrop(false); b_ret = demuxer->create(); inrestart = false; } else { fakeEsOut()->commandsQueue()->Commit(); } return b_ret; } void AbstractStream::setDisabled(bool b) { if(disabled != b) segmentTracker->notifyBufferingState(!b); disabled = b; } bool AbstractStream::isValid() const { vlc_mutex_locker locker(const_cast<vlc_mutex_t *>(&lock)); return valid; } bool AbstractStream::isDisabled() const { vlc_mutex_locker locker(const_cast<vlc_mutex_t *>(&lock)); return disabled; } bool AbstractStream::decodersDrained() { return fakeEsOut()->decodersDrained(); } AbstractStream::buffering_status AbstractStream::getLastBufferStatus() const { return last_buffer_status; } mtime_t AbstractStream::getDemuxedAmount(mtime_t from) const { return fakeEsOut()->commandsQueue()->getDemuxedAmount(from); } AbstractStream::buffering_status AbstractStream::bufferize(mtime_t nz_deadline, unsigned i_min_buffering, unsigned i_extra_buffering) { last_buffer_status = doBufferize(nz_deadline, i_min_buffering, i_extra_buffering); return last_buffer_status; } AbstractStream::buffering_status AbstractStream::doBufferize(mtime_t nz_deadline, mtime_t i_min_buffering, mtime_t i_extra_buffering) { vlc_mutex_lock(&lock); /* Ensure it is configured */ if(!segmentTracker || !connManager || !valid) { vlc_mutex_unlock(&lock); return AbstractStream::buffering_end; } /* Disable streams that are not selected (alternate streams) */ if(esCount() && !isSelected() && !fakeEsOut()->restarting()) { setDisabled(true); segmentTracker->reset(); fakeEsOut()->commandsQueue()->Abort(false); msg_Dbg(p_realdemux, "deactivating %s stream %s", format.str().c_str(), description.c_str()); vlc_mutex_unlock(&lock); return AbstractStream::buffering_end; } if(fakeEsOut()->commandsQueue()->isDraining()) { vlc_mutex_unlock(&lock); return AbstractStream::buffering_suspended; } segmentTracker->setStartPosition(); /* Reached end of live playlist */ if(!segmentTracker->bufferingAvailable()) { vlc_mutex_unlock(&lock); return AbstractStream::buffering_suspended; } if(!demuxer) { format = segmentTracker->getCurrentFormat(); if(!startDemux()) { /* If demux fails because of probing failure / wrong format*/ if(discontinuity) { msg_Dbg( p_realdemux, "Draining on format change" ); prepareRestart(); discontinuity = false; fakeEsOut()->commandsQueue()->setDraining(); vlc_mutex_unlock(&lock); return AbstractStream::buffering_ongoing; } valid = false; /* Prevent further retries */ fakeEsOut()->commandsQueue()->setEOF(true); vlc_mutex_unlock(&lock); return AbstractStream::buffering_end; } } const int64_t i_total_buffering = i_min_buffering + i_extra_buffering; mtime_t i_demuxed = fakeEsOut()->commandsQueue()->getDemuxedAmount(nz_deadline); segmentTracker->notifyBufferingLevel(i_min_buffering, i_demuxed, i_total_buffering); if(i_demuxed < i_total_buffering) /* not already demuxed */ { mtime_t nz_extdeadline = fakeEsOut()->commandsQueue()->getBufferingLevel() + (i_total_buffering - i_demuxed) / 4; nz_deadline = std::max(nz_deadline, nz_extdeadline); /* need to read, demuxer still buffering, ... */ vlc_mutex_unlock(&lock); Demuxer::Status demuxStatus = demuxer->demux(nz_deadline); vlc_mutex_lock(&lock); if(demuxStatus != Demuxer::Status::STATUS_SUCCESS) { if(discontinuity || needrestart) { msg_Dbg(p_realdemux, "Restarting demuxer"); prepareRestart(discontinuity); if(discontinuity) { msg_Dbg(p_realdemux, "Draining on discontinuity"); fakeEsOut()->commandsQueue()->setDraining(); discontinuity = false; } needrestart = false; vlc_mutex_unlock(&lock); return AbstractStream::buffering_ongoing; } fakeEsOut()->commandsQueue()->setEOF(true); vlc_mutex_unlock(&lock); return AbstractStream::buffering_end; } i_demuxed = fakeEsOut()->commandsQueue()->getDemuxedAmount(nz_deadline); segmentTracker->notifyBufferingLevel(i_min_buffering, i_demuxed, i_total_buffering); } vlc_mutex_unlock(&lock); if(i_demuxed < i_total_buffering) /* need to read more */ { if(i_demuxed < i_min_buffering) return AbstractStream::buffering_lessthanmin; /* high prio */ return AbstractStream::buffering_ongoing; } return AbstractStream::buffering_full; } AbstractStream::status AbstractStream::dequeue(mtime_t nz_deadline, mtime_t *pi_pcr) { vlc_mutex_locker locker(&lock); *pi_pcr = nz_deadline; if(fakeEsOut()->commandsQueue()->isDraining()) { AdvDebug(mtime_t pcrvalue = fakeEsOut()->commandsQueue()->getPCR(); mtime_t dtsvalue = fakeEsOut()->commandsQueue()->getFirstDTS(); msg_Dbg(p_realdemux, "Stream %s pcr %" PRId64 " dts %" PRId64 " deadline %" PRId64 " [DRAINING]", description.c_str(), pcrvalue, dtsvalue, nz_deadline)); *pi_pcr = fakeEsOut()->commandsQueue()->Process(p_realdemux->out, VLC_TS_0 + nz_deadline); if(!fakeEsOut()->commandsQueue()->isEmpty()) return AbstractStream::status_demuxed; if(!fakeEsOut()->commandsQueue()->isEOF()) { fakeEsOut()->commandsQueue()->Abort(true); /* reset buffering level and flags */ return AbstractStream::status_discontinuity; } } if(!valid || disabled || fakeEsOut()->commandsQueue()->isEOF()) { *pi_pcr = nz_deadline; return AbstractStream::status_eof; } mtime_t bufferingLevel = fakeEsOut()->commandsQueue()->getBufferingLevel(); AdvDebug(mtime_t pcrvalue = fakeEsOut()->commandsQueue()->getPCR(); mtime_t dtsvalue = fakeEsOut()->commandsQueue()->getFirstDTS(); msg_Dbg(p_realdemux, "Stream %s pcr %" PRId64 " dts %" PRId64 " deadline %" PRId64 " buflevel %" PRId64, description.c_str(), pcrvalue, dtsvalue, nz_deadline, bufferingLevel)); if(nz_deadline + VLC_TS_0 <= bufferingLevel) /* demuxed */ { *pi_pcr = fakeEsOut()->commandsQueue()->Process( p_realdemux->out, VLC_TS_0 + nz_deadline ); return AbstractStream::status_demuxed; } return AbstractStream::status_buffering; } std::string AbstractStream::getContentType() { if (currentChunk == NULL && !eof) { const bool b_restarting = fakeEsOut()->restarting(); currentChunk = segmentTracker->getNextChunk(!b_restarting, connManager); } if(currentChunk) return currentChunk->getContentType(); else return std::string(); } block_t * AbstractStream::readNextBlock() { if (currentChunk == NULL && !eof) { const bool b_restarting = fakeEsOut()->restarting(); currentChunk = segmentTracker->getNextChunk(!b_restarting, connManager); } if(discontinuity && demuxfirstchunk) { /* clear up discontinuity on demux start (discontinuity on start segment bug) */ discontinuity = false; } if(discontinuity || needrestart) { msg_Info(p_realdemux, "Encountered discontinuity"); /* Force stream/demuxer to end for this call */ return NULL; } if(currentChunk == NULL) { eof = true; return NULL; } const bool b_segment_head_chunk = (currentChunk->getBytesRead() == 0); block_t *block = currentChunk->readBlock(); if(block == NULL) { if(currentChunk->getRequestStatus() == RequestStatus::NotFound && ++notfound_sequence < 3) { discontinuity = true; } delete currentChunk; currentChunk = NULL; return NULL; } else notfound_sequence = 0; demuxfirstchunk = false; if (currentChunk->isEmpty()) { delete currentChunk; currentChunk = NULL; } block = checkBlock(block, b_segment_head_chunk); return block; } bool AbstractStream::setPosition(mtime_t time, bool tryonly) { if(!seekAble()) return false; bool b_needs_restart = demuxer ? demuxer->needsRestartOnSeek() : true; bool ret = segmentTracker->setPositionByTime(time, b_needs_restart, tryonly); if(!tryonly && ret) { // clear eof flag before restartDemux() to prevent readNextBlock() fail eof = false; demuxfirstchunk = true; notfound_sequence = 0; if(b_needs_restart) { if(currentChunk) delete currentChunk; currentChunk = NULL; needrestart = false; fakeEsOut()->resetTimestamps(); mtime_t seekMediaTime = segmentTracker->getPlaybackTime(true); fakeEsOut()->setExpectedTimestamp(seekMediaTime); if( !restartDemux() ) { msg_Info(p_realdemux, "Restart demux failed"); eof = true; valid = false; ret = false; } else { fakeEsOut()->commandsQueue()->setEOF(false); } } else fakeEsOut()->commandsQueue()->Abort( true ); // in some cases, media time seek != sent dts // es_out_Control(p_realdemux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, // VLC_TS_0 + time); } return ret; } bool AbstractStream::getMediaPlaybackTimes(mtime_t *start, mtime_t *end, mtime_t *length, mtime_t *mediaStart, mtime_t *demuxStart) const { return (segmentTracker->getMediaPlaybackRange(start, end, length) && fakeEsOut()->getStartTimestamps(mediaStart, demuxStart)); } void AbstractStream::runUpdates() { if(valid && !disabled) segmentTracker->updateSelected(); } void AbstractStream::fillExtraFMTInfo( es_format_t *p_fmt ) const { if(!p_fmt->psz_language && !language.empty()) p_fmt->psz_language = strdup(language.c_str()); if(!p_fmt->psz_description && !description.empty()) p_fmt->psz_description = strdup(description.c_str()); } AbstractDemuxer * AbstractStream::createDemux(const StreamFormat &format) { AbstractDemuxer *ret = newDemux( VLC_OBJECT(p_realdemux), format, (es_out_t *)fakeEsOut(), demuxersource ); if(ret && !ret->create()) { delete ret; ret = NULL; } else fakeEsOut()->commandsQueue()->Commit(); return ret; } AbstractDemuxer *AbstractStream::newDemux(vlc_object_t *p_obj, const StreamFormat &format, es_out_t *out, AbstractSourceStream *source) const { AbstractDemuxer *ret = NULL; switch((unsigned)format) { case StreamFormat::MP4: ret = new Demuxer(p_obj, "mp4", out, source); break; case StreamFormat::MPEG2TS: ret = new Demuxer(p_obj, "ts", out, source); break; default: case StreamFormat::UNSUPPORTED: break; } return ret; } void AbstractStream::trackerEvent(const SegmentTrackerEvent &event) { switch(event.type) { case SegmentTrackerEvent::DISCONTINUITY: discontinuity = true; break; case SegmentTrackerEvent::FORMATCHANGE: /* Check if our current demux is still valid */ if(*event.u.format.f != format || format == StreamFormat(StreamFormat::UNKNOWN)) { /* Format has changed between segments, we need to drain and change demux */ msg_Info(p_realdemux, "Changing stream format %s -> %s", format.str().c_str(), event.u.format.f->str().c_str()); format = *event.u.format.f; /* This is an implict discontinuity */ discontinuity = true; } break; case SegmentTrackerEvent::SWITCHING: if(demuxer && !inrestart) { if(!demuxer->bitstreamSwitchCompatible() || (event.u.switching.next && !event.u.switching.next->getAdaptationSet()->isBitSwitchable())) needrestart = true; } break; case SegmentTrackerEvent::SEGMENT_CHANGE: if(demuxer && demuxer->needsRestartOnEachSegment() && !inrestart) { needrestart = true; } break; default: break; } } static void add_codec_string_from_fourcc(vlc_fourcc_t fourcc, std::list<std::string> &codecs) { std::string codec; codec.insert(0, reinterpret_cast<const char *>(&fourcc), 4); codecs.push_back(codec); } void AbstractStream::declaredCodecs() { const std::string & streamDesc = segmentTracker->getStreamDescription(); const std::string & streamLang = segmentTracker->getStreamLanguage(); std::list<std::string> codecs = segmentTracker->getCurrentCodecs(); if(codecs.empty()) { const StreamFormat format = segmentTracker->getCurrentFormat(); switch(format) { case StreamFormat::TTML: add_codec_string_from_fourcc(VLC_CODEC_TTML, codecs); break; case StreamFormat::WEBVTT: add_codec_string_from_fourcc(VLC_CODEC_WEBVTT, codecs); break; default: break; } } for(std::list<std::string>::const_iterator it = codecs.begin(); it != codecs.end(); ++it) { FormatNamespace fnsp(*it); es_format_t fmt; es_format_Init(&fmt, fnsp.getFmt()->i_cat, fnsp.getFmt()->i_codec); es_format_Copy(&fmt, fnsp.getFmt()); if(!streamLang.empty()) fmt.psz_language = strdup(streamLang.c_str()); if(!streamDesc.empty()) fmt.psz_description = strdup(streamDesc.c_str()); fakeEsOut()->declareEs( &fmt ); es_format_Clean(&fmt); } } FakeESOut::LockedFakeEsOut AbstractStream::fakeEsOut() { return fakeesout->WithLock(); } FakeESOut::LockedFakeEsOut AbstractStream::fakeEsOut() const { return fakeesout->WithLock(); }
30.61642
117
0.603833
Brook1711
0cd31c2d57119c4b743b42991bf7b19b70237050
915
cpp
C++
src/boost/archive/yaml_oarchive.cpp
rwols/yaml-archive
4afec73e557c15350c5e068c010f4e378edc95ef
[ "BSL-1.0" ]
1
2018-01-27T23:35:21.000Z
2018-01-27T23:35:21.000Z
src/boost/archive/yaml_oarchive.cpp
rwols/yaml-archive
4afec73e557c15350c5e068c010f4e378edc95ef
[ "BSL-1.0" ]
2
2019-08-17T05:37:36.000Z
2019-08-17T22:57:26.000Z
src/boost/archive/yaml_oarchive.cpp
rwols/yaml-archive
4afec73e557c15350c5e068c010f4e378edc95ef
[ "BSL-1.0" ]
1
2021-03-19T11:53:53.000Z
2021-03-19T11:53:53.000Z
/** @file * * @brief Defines narrow concrete output archives. * * @author Raoul Wols * * @date 2017 * * @copyright See LICENSE.md * */ #if (defined _MSC_VER) && (_MSC_VER == 1200) #pragma warning(disable : 4786) // too long name, harmless warning #endif #define BOOST_ARCHIVE_SOURCE #include <boost/archive/detail/archive_serializer_map.hpp> #include <boost/archive/yaml_oarchive.hpp> #include <boost/serialization/config.hpp> // explicitly instantiate for this type of yaml stream #include <boost/archive/impl/archive_serializer_map.ipp> #include <boost/archive/impl/basic_yaml_oarchive.ipp> #include <boost/archive/impl/yaml_oarchive_impl.ipp> namespace boost { namespace archive { template class detail::archive_serializer_map<yaml_oarchive>; template class basic_yaml_oarchive<yaml_oarchive>; template class yaml_oarchive_impl<yaml_oarchive>; } // namespace archive } // namespace boost
25.416667
66
0.76612
rwols
0cd88d993983b62868af471659f79d4d06a7acfd
1,513
cpp
C++
course1/Laba2/G/main.cpp
flydzen/ITMO_algo
ea251dca0fddb0d4d212377c6785cdc3667ece89
[ "MIT" ]
null
null
null
course1/Laba2/G/main.cpp
flydzen/ITMO_algo
ea251dca0fddb0d4d212377c6785cdc3667ece89
[ "MIT" ]
null
null
null
course1/Laba2/G/main.cpp
flydzen/ITMO_algo
ea251dca0fddb0d4d212377c6785cdc3667ece89
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <cmath> #include <algorithm> #define ui unsigned int #define ull unsigned long long #define us unsigned long long #pragma GCC optimize("03") using namespace std; ui cur = 0; ui a, b; inline ui nextRand24() { cur = cur * a + b; return cur >> 8; } inline ui nextRand32() { return (nextRand24() << 8) ^ nextRand24(); } inline ui digit(ui num, ui i) { return (num >> (i * 8) & 0xFF); } void lsd(vector<ui> &v) { ui k = 256; ui m = 4; ui n = v.size(); vector<ui> nV(n); for (ui i = 0; i < m; i++) { vector<ui> c(k); for (ui j = 0; j < n; j++) { c[digit(v[j], i)]++; } ui count = 0; for (ui j = 0; j < k; j++) { ui temp = c[j]; c[j] = count; count += temp; } for (ui j = 0; j < n; j++) { ui d = digit(v[j], i); nV[c[d]] = v[j]; c[d]++; } v = nV; } } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); ui t, n; cin >> t >> n; for (ui i = 0; i < t; i++) { cin >> a >> b; vector<ui> vec(n); for (ui j = 0; j < n; j++) { vec[j] = nextRand32(); } lsd(vec); unsigned long long summ = 0; for (ui ij = 0; ij < n; ij++) { summ += (unsigned long long) (ij + 1) * vec[(size_t) ij]; } cout << summ << endl; vec.clear(); } return 0; }
20.173333
69
0.432254
flydzen
0cd9c66e0780db9a044edb30d4d606f462b86e57
3,313
cpp
C++
src/BlockEntities/ChestEntity.cpp
planetx/MCServer
4e119b522409af682e62ed38f4d22ddd9da40170
[ "Apache-2.0" ]
null
null
null
src/BlockEntities/ChestEntity.cpp
planetx/MCServer
4e119b522409af682e62ed38f4d22ddd9da40170
[ "Apache-2.0" ]
null
null
null
src/BlockEntities/ChestEntity.cpp
planetx/MCServer
4e119b522409af682e62ed38f4d22ddd9da40170
[ "Apache-2.0" ]
null
null
null
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "ChestEntity.h" #include "../Item.h" #include "../Entities/Player.h" #include "../UI/Window.h" cChestEntity::cChestEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World, BLOCKTYPE a_Type) : super(a_Type, a_BlockX, a_BlockY, a_BlockZ, ContentsWidth, ContentsHeight, a_World), m_NumActivePlayers(0) { } cChestEntity::~cChestEntity() { cWindow * Window = GetWindow(); if (Window != nullptr) { Window->OwnerDestroyed(); } } void cChestEntity::SendTo(cClientHandle & a_Client) { // The chest entity doesn't need anything sent to the client when it's created / gets in the viewdistance // All the actual handling is in the cWindow UI code that gets called when the chest is rclked UNUSED(a_Client); } void cChestEntity::UsedBy(cPlayer * a_Player) { // If the window is not created, open it anew: cWindow * Window = GetWindow(); if (Window == nullptr) { OpenNewWindow(); Window = GetWindow(); } // Open the window for the player: if (Window != nullptr) { if (a_Player->GetWindow() != Window) { a_Player->OpenWindow(Window); } } // This is rather a hack // Instead of marking the chunk as dirty upon chest contents change, we mark it dirty now // We cannot properly detect contents change, but such a change doesn't happen without a player opening the chest first. // The few false positives aren't much to worry about int ChunkX, ChunkZ; cChunkDef::BlockToChunk(m_PosX, m_PosZ, ChunkX, ChunkZ); m_World->MarkChunkDirty(ChunkX, ChunkZ, true); } void cChestEntity::OpenNewWindow(void) { // TODO: cats are an obstruction if ((GetPosY() + 1 < cChunkDef::Height) && cBlockInfo::IsSolid(GetWorld()->GetBlock(GetPosX(), GetPosY() + 1, GetPosZ()))) { // Obstruction, don't open return; } // Callback for opening together with neighbor chest: class cOpenDouble : public cChestCallback { cChestEntity * m_ThisChest; public: cOpenDouble(cChestEntity * a_ThisChest) : m_ThisChest(a_ThisChest) { } virtual bool Item(cChestEntity * a_Chest) override { if ((a_Chest->GetPosY() + 1 < cChunkDef::Height) && cBlockInfo::IsSolid(a_Chest->GetWorld()->GetBlock(a_Chest->GetPosX(), a_Chest->GetPosY() + 1, a_Chest->GetPosZ()))) { // Obstruction, don't open return false; } // The primary chest should eb the one with lesser X or Z coord: cChestEntity * Primary = a_Chest; cChestEntity * Secondary = m_ThisChest; if ( (Primary->GetPosX() > Secondary->GetPosX()) || (Primary->GetPosZ() > Secondary->GetPosZ()) ) { std::swap(Primary, Secondary); } m_ThisChest->OpenWindow(new cChestWindow(Primary, Secondary)); return false; } } ; // Scan neighbors for adjacent chests: cOpenDouble OpenDbl(this); if ( m_World->DoWithChestAt(m_PosX - 1, m_PosY, m_PosZ, OpenDbl) || m_World->DoWithChestAt(m_PosX + 1, m_PosY, m_PosZ, OpenDbl) || m_World->DoWithChestAt(m_PosX, m_PosY, m_PosZ - 1, OpenDbl) || m_World->DoWithChestAt(m_PosX, m_PosY, m_PosZ + 1, OpenDbl) ) { // The double-chest window has been opened in the callback return; } // There is no chest neighbor, open a single-chest window: OpenWindow(new cChestWindow(this)); }
23.167832
170
0.689104
planetx
0cda2408e86a3258194a2c3882c045b4c93525bc
28,716
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Packages/SystemUI/src/elastos/droid/systemui/recents/views/RecentsView.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Packages/SystemUI/src/elastos/droid/systemui/recents/views/RecentsView.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Packages/SystemUI/src/elastos/droid/systemui/recents/views/RecentsView.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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 "elastos/droid/systemui/recents/model/RecentsTaskLoader.h" #include "elastos/droid/systemui/recents/model/TaskGrouping.h" #include "elastos/droid/systemui/recents/views/RecentsView.h" #include "elastos/droid/systemui/recents/views/TaskStackView.h" #include "elastos/droid/systemui/recents/misc/Utilities.h" #include "elastos/droid/systemui/recents/Constants.h" #include "Elastos.Droid.Net.h" #include "Elastos.Droid.Provider.h" #include <elastos/droid/view/LayoutInflater.h> using Elastos::Droid::Animation::ITimeInterpolator; using Elastos::Droid::App::CActivityOptionsHelper; using Elastos::Droid::App::IActivityOptionsHelper; using Elastos::Droid::App::CTaskStackBuilderHelper; using Elastos::Droid::App::ITaskStackBuilderHelper; using Elastos::Droid::App::ITaskStackBuilder; using Elastos::Droid::App::EIID_IActivityOptionsOnAnimationStartedListener; using Elastos::Droid::Content::IComponentName; using Elastos::Droid::Content::CIntent; using Elastos::Droid::Content::IIntent; using Elastos::Droid::Content::Pm::IPackageManager; using Elastos::Droid::Graphics::CBitmapHelper; using Elastos::Droid::Graphics::BitmapConfig_ALPHA_8; using Elastos::Droid::Graphics::BitmapConfig_ARGB_8888; using Elastos::Droid::Graphics::IBitmap; using Elastos::Droid::Graphics::IBitmapHelper; using Elastos::Droid::Graphics::CCanvas; using Elastos::Droid::Graphics::ICanvas; using Elastos::Droid::Graphics::CRect; using Elastos::Droid::Graphics::IRect; using Elastos::Droid::Net::CUriHelper; using Elastos::Droid::Net::IUriHelper; using Elastos::Droid::Net::IUri; using Elastos::Droid::Os::CUserHandle; using Elastos::Droid::Os::IUserHandle; using Elastos::Droid::Provider::ISettings; using Elastos::Droid::View::LayoutInflater; using Elastos::Droid::SystemUI::Recents::Model::EIID_IPackageCallbacks; using Elastos::Droid::SystemUI::Recents::Model::RecentsTaskLoader; using Elastos::Droid::SystemUI::Recents::Model::TaskGrouping; using Elastos::Droid::SystemUI::Recents::Misc::Utilities; namespace Elastos { namespace Droid { namespace SystemUI { namespace Recents { namespace Views { //-------------------------------------------------------------- // RecentsView::OnAnimationStartedRunnable //-------------------------------------------------------------- RecentsView::OnAnimationStartedRunnable::OnAnimationStartedRunnable( /* [in] */ SystemServicesProxy* ssp) : mSsp(ssp) {} ECode RecentsView::OnAnimationStartedRunnable::Run() { mSsp->LockCurrentTask(); return NOERROR; } //-------------------------------------------------------------- // RecentsView::OnAnimationStartedListener //-------------------------------------------------------------- CAR_INTERFACE_IMPL(RecentsView::OnAnimationStartedListener, Object, IActivityOptionsOnAnimationStartedListener) RecentsView::OnAnimationStartedListener::OnAnimationStartedListener( /* [in] */ SystemServicesProxy* ssp, /* [in] */ RecentsView* host) : mHost(host) , mTriggered(FALSE) , mSsp(ssp) {} // @Override ECode RecentsView::OnAnimationStartedListener::OnAnimationStarted() { if (!mTriggered) { AutoPtr<Runnable> runnable = new OnAnimationStartedRunnable(mSsp); Boolean res; mHost->PostDelayed(runnable, 350, &res); mTriggered = TRUE; } return NOERROR; } RecentsView::LaunchRunnable::LaunchRunnable( /* [in] */ ITask* task, /* [in] */ IActivityOptions* launchOpts, /* [in] */ Boolean lockToTask, /* [in] */ RecentsView* host) : mTask(task) , mLaunchOpts(launchOpts) , mLockToTask(lockToTask) , mHost(host) {} // @Override ECode RecentsView::LaunchRunnable::Run() { Task* task = (Task*)mTask.Get(); AutoPtr<SystemServicesProxy> ssp; RecentsTaskLoader::GetInstance()->GetSystemServicesProxy((SystemServicesProxy**)&ssp); if (task->mIsActive) { // Bring an active task to the foreground ssp->MoveTaskToFront(task->mKey->mId, mLaunchOpts); } else { AutoPtr<IContext> context; mHost->GetContext((IContext**)&context); if (ssp->StartActivityFromRecents(context, task->mKey->mId, task->mActivityLabel, mLaunchOpts)) { if (mLaunchOpts == NULL && mLockToTask) { ssp->LockCurrentTask(); } } else { // Dismiss the task and return the user to home if we fail to // launch the task mHost->OnTaskViewDismissed(task); if (mHost->mCb != NULL) { mHost->mCb->OnTaskLaunchFailed(); } } } return NOERROR; } //-------------------------------------------------------------- // RecentsView //-------------------------------------------------------------- CAR_INTERFACE_IMPL_3(RecentsView, FrameLayout, IRecentsView, ITaskStackViewCallbacks, IPackageCallbacks) RecentsView::RecentsView() : mAlreadyLaunchingTask(FALSE) { } ECode RecentsView::constructor( /* [in] */ IContext* context) { return FrameLayout::constructor(context); } ECode RecentsView::constructor( /* [in] */ IContext* context, /* [in] */ IAttributeSet* attrs) { return constructor(context, attrs, 0); } ECode RecentsView::constructor( /* [in] */ IContext* context, /* [in] */ IAttributeSet* attrs, /* [in] */ Int32 defStyleAttr) { return constructor(context, attrs, defStyleAttr, 0); } ECode RecentsView::constructor( /* [in] */ IContext* context, /* [in] */ IAttributeSet* attrs, /* [in] */ Int32 defStyleAttr, /* [in] */ Int32 defStyleRes) { FAIL_RETURN(FrameLayout::constructor(context, attrs, defStyleAttr, defStyleRes)); mConfig = RecentsConfiguration::GetInstance(); LayoutInflater::From(context, (ILayoutInflater**)&mInflater); return NOERROR; } /** Sets the callbacks */ ECode RecentsView::SetCallbacks( /* [in] */ IRecentsViewCallbacks* cb) { mCb = cb; return NOERROR; } /** Sets the debug overlay */ ECode RecentsView::SetDebugOverlay( /* [in] */ DebugOverlayView* overlay) { mDebugOverlay = overlay; return NOERROR; } /** Set/get the bsp root node */ ECode RecentsView::SetTaskStacks( /* [in] */ IList* stacks) { // Remove all TaskStackViews (but leave the search bar) Int32 childCount; GetChildCount(&childCount); for (Int32 i = childCount - 1; i >= 0; i--) { AutoPtr<IView> v; GetChildAt(i, (IView**)&v); if (v != mSearchBar) { RemoveViewAt(i); } } // Create and add all the stacks for this partition of space. mStacks = stacks; Int32 numStacks; mStacks->GetSize(&numStacks); for (Int32 i = 0; i < numStacks; i++) { AutoPtr<IInterface> item; mStacks->Get(i, (IInterface**)&item); AutoPtr<ITaskStack> stack = ITaskStack::Probe(item); AutoPtr<IContext> context; GetContext((IContext**)&context); AutoPtr<TaskStackView> stackView = new TaskStackView(); stackView->constructor(context, stack); stackView->SetCallbacks((ITaskStackViewCallbacks*)this); // Enable debug mode drawing if (mConfig->mDebugModeEnabled) { stackView->SetDebugOverlay(mDebugOverlay); } AddView(stackView); } // Reset the launched state mAlreadyLaunchingTask = FALSE; return NOERROR; } /** Removes all the task stack views from this recents view. */ ECode RecentsView::RemoveAllTaskStacks() { Int32 childCount; GetChildCount(&childCount); for (Int32 i = childCount - 1; i >= 0; i--) { AutoPtr<IView> v; GetChildAt(i, (IView**)&v); if (v != mSearchBar) { RemoveViewAt(i); } } return NOERROR; } /** Launches the focused task from the first stack if possible */ Boolean RecentsView::LaunchFocusedTask() { // Get the first stack view Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); if (child != mSearchBar) { AutoPtr<TaskStackView> stackView = (TaskStackView*)ITaskStackView::Probe(child); AutoPtr<TaskStack> stack = stackView->mStack; // Iterate the stack views and try and find the focused task Int32 taskCount; stackView->GetChildCount(&taskCount); for (Int32 j = 0; j < taskCount; j++) { AutoPtr<IView> v; stackView->GetChildAt(j, (IView**)&v); AutoPtr<TaskView> tv = (TaskView*)ITaskView::Probe(v); AutoPtr<ITask> task = tv->GetTask(); if (tv->IsFocusedTask()) { OnTaskViewClicked(stackView, tv, stack, task, FALSE); return TRUE; } } } } return FALSE; } /** Launches the task that Recents was launched from, if possible */ Boolean RecentsView::LaunchPreviousTask() { // Get the first stack view Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); if (child != mSearchBar) { AutoPtr<TaskStackView> stackView = (TaskStackView*)ITaskStackView::Probe(child); AutoPtr<TaskStack> stack = stackView->mStack; AutoPtr<IArrayList> tasks = stack->GetTasks(); // Find the launch task in the stack Boolean isEmpty; tasks->IsEmpty(&isEmpty); if (!isEmpty) { Int32 taskCount; tasks->GetSize(&taskCount); for (Int32 j = 0; j < taskCount; j++) { AutoPtr<IInterface> item; tasks->Get(j, (IInterface**)&item); AutoPtr<Task> task = (Task*)ITask::Probe(item); if (task->mIsLaunchTarget) { AutoPtr<ITaskView> tv = stackView->GetChildViewForTask(task); OnTaskViewClicked(stackView, tv, stack, task, FALSE); return TRUE; } } } } } return FALSE; } /** Requests all task stacks to start their enter-recents animation */ ECode RecentsView::StartEnterRecentsAnimation( /* [in] */ ViewAnimation::TaskViewEnterContext* ctx) { Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); if (child != mSearchBar) { AutoPtr<TaskStackView> stackView = (TaskStackView*)ITaskStackView::Probe(child); stackView->StartEnterRecentsAnimation(ctx); } } return NOERROR; } /** Requests all task stacks to start their exit-recents animation */ ECode RecentsView::StartExitToHomeAnimation( /* [in] */ ViewAnimation::TaskViewExitContext* ctx) { Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); if (child != mSearchBar) { AutoPtr<TaskStackView> stackView = (TaskStackView*)ITaskStackView::Probe(child); stackView->StartExitToHomeAnimation(ctx); } } // Notify of the exit animation return mCb->OnExitToHomeAnimationTriggered(); } /** Adds the search bar */ ECode RecentsView::SetSearchBar( /* [in] */ IView* searchBar) { // Create the search bar (and hide it if we have no recent tasks) if (Constants::DebugFlags::App::EnableSearchLayout) { // Remove the previous search bar if one exists Int32 index; if (mSearchBar != NULL && (IndexOfChild(mSearchBar, &index), index > -1)) { RemoveView(mSearchBar); } // Add the new search bar if (searchBar != NULL) { mSearchBar = searchBar; AddView(mSearchBar); } } return NOERROR; } /** Returns whether there is currently a search bar */ Boolean RecentsView::HasSearchBar() { return mSearchBar != NULL; } /** Sets the visibility of the search bar */ ECode RecentsView::SetSearchBarVisibility( /* [in] */ Int32 visibility) { if (mSearchBar != NULL) { mSearchBar->SetVisibility(visibility); // Always bring the search bar to the top mSearchBar->BringToFront(); } return NOERROR; } /** * This is called with the full size of the window since we are handling our own insets. */ // @Override ECode RecentsView::OnMeasure( /* [in] */ Int32 widthMeasureSpec, /* [in] */ Int32 heightMeasureSpec) { Int32 width = MeasureSpec::GetSize(widthMeasureSpec); Int32 height = MeasureSpec::GetSize(heightMeasureSpec); // Get the search bar bounds and measure the search bar layout if (mSearchBar != NULL) { AutoPtr<IRect> searchBarSpaceBounds; CRect::New((IRect**)&searchBarSpaceBounds); Int32 top; mConfig->mSystemInsets->GetTop(&top); mConfig->GetSearchBarBounds(width, height, top, searchBarSpaceBounds); Int32 width, height; searchBarSpaceBounds->GetWidth(&width); searchBarSpaceBounds->GetHeight(&height); mSearchBar->Measure(MeasureSpec::MakeMeasureSpec(width, MeasureSpec::EXACTLY), MeasureSpec::MakeMeasureSpec(height, MeasureSpec::EXACTLY)); } AutoPtr<IRect> taskStackBounds; CRect::New((IRect**)&taskStackBounds); Int32 top, right; mConfig->mSystemInsets->GetTop(&top); mConfig->mSystemInsets->GetRight(&right); mConfig->GetTaskStackBounds(width, height, top, right, taskStackBounds); // Measure each TaskStackView with the full width and height of the window since the // transition view is a child of that stack view Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); Int32 visibility; if (child != mSearchBar && (child->GetVisibility(&visibility), visibility != GONE)) { AutoPtr<TaskStackView> tsv = (TaskStackView*)ITaskStackView::Probe(child); // Set the insets to be the top/left inset + search bounds tsv->SetStackInsetRect(taskStackBounds); tsv->Measure(widthMeasureSpec, heightMeasureSpec); } } SetMeasuredDimension(width, height); return NOERROR; } /** * This is called with the full size of the window since we are handling our own insets. */ // @Override ECode RecentsView::OnLayout( /* [in] */ Boolean changed, /* [in] */ Int32 left, /* [in] */ Int32 top, /* [in] */ Int32 right, /* [in] */ Int32 bottom) { // Get the search bar bounds so that we lay it out if (mSearchBar != NULL) { AutoPtr<IRect> searchBarSpaceBounds; CRect::New((IRect**)&searchBarSpaceBounds); Int32 top; mConfig->mSystemInsets->GetTop(&top); Int32 width, height; GetMeasuredWidth(&width); GetMeasuredHeight(&height); mConfig->GetSearchBarBounds(width, height, top, searchBarSpaceBounds); Int32 left, right, bottom; searchBarSpaceBounds->GetLeft(&left); searchBarSpaceBounds->GetRight(&right); searchBarSpaceBounds->GetTop(&top); searchBarSpaceBounds->GetBottom(&bottom); mSearchBar->Layout(left, top, right, bottom); } // Layout each TaskStackView with the full width and height of the window since the // transition view is a child of that stack view Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); Int32 visibility; if (child != mSearchBar && (child->GetVisibility(&visibility), visibility != GONE)) { Int32 width, height; child->GetMeasuredWidth(&width); child->GetMeasuredHeight(&height); child->Layout(left, top, left + width, top + height); } } return NOERROR; } // @Override ECode RecentsView::OnApplyWindowInsets( /* [in] */ IWindowInsets* insets, /* [out] */ IWindowInsets** outInsets) { VALIDATE_NOT_NULL(outInsets); // Update the configuration with the latest system insets and trigger a relayout AutoPtr<IRect> rect; insets->GetSystemWindowInsets((IRect**)&rect); mConfig->UpdateSystemInsets(rect); RequestLayout(); return insets->ConsumeSystemWindowInsets(outInsets); } /** Notifies each task view of the user interaction. */ ECode RecentsView::OnUserInteraction() { // Get the first stack view Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); if (child != mSearchBar) { AutoPtr<TaskStackView> stackView = (TaskStackView*)ITaskStackView::Probe(child); stackView->OnUserInteraction(); } } return NOERROR; } /** Focuses the next task in the first stack view */ ECode RecentsView::FocusNextTask( /* [in] */ Boolean forward) { // Get the first stack view Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); if (child != mSearchBar) { AutoPtr<TaskStackView> stackView = (TaskStackView*)ITaskStackView::Probe(child); stackView->FocusNextTask(forward); break; } } return NOERROR; } /** Dismisses the focused task. */ ECode RecentsView::DismissFocusedTask() { // Get the first stack view Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); if (child != mSearchBar) { AutoPtr<TaskStackView> stackView = (TaskStackView*)ITaskStackView::Probe(child); stackView->DismissFocusedTask(); break; } } return NOERROR; } /** Unfilters any filtered stacks */ Boolean RecentsView::UnfilterFilteredStacks() { if (mStacks != NULL) { // Check if there are any filtered stacks and unfilter them before we back out of Recents Boolean stacksUnfiltered = FALSE; Int32 numStacks; mStacks->GetSize(&numStacks); for (Int32 i = 0; i < numStacks; i++) { AutoPtr<IInterface> item; mStacks->Get(i, (IInterface**)&item); AutoPtr<TaskStack> stack = (TaskStack*)ITaskStack::Probe(item); if (stack->HasFilteredTasks()) { stack->UnfilterTasks(); stacksUnfiltered = TRUE; } } return stacksUnfiltered; } return FALSE; } /**** TaskStackView.TaskStackCallbacks Implementation ****/ // @Override ECode RecentsView::OnTaskViewClicked( /* [in] */ ITaskStackView* _stackView, /* [in] */ ITaskView* _tv, /* [in] */ ITaskStack* stack, /* [in] */ ITask* _task, /* [in] */ Boolean lockToTask) { TaskStackView* stackView = (TaskStackView*)_stackView; TaskView* tv = (TaskView*)_tv; Task* task = (Task*)_task; // Notify any callbacks of the launching of a new task if (mCb != NULL) { mCb->OnTaskViewClicked(); } // Skip if we are already launching tasks if (mAlreadyLaunchingTask) { return NOERROR; } mAlreadyLaunchingTask = TRUE; // Upfront the processing of the thumbnail AutoPtr<TaskViewTransform> transform = new TaskViewTransform(); AutoPtr<IView> sourceView; Int32 offsetX = 0; Int32 offsetY = 0; Float stackScroll = stackView->GetScroller()->GetStackScroll(); if (tv == NULL) { // If there is no actual task view, then use the stack view as the source view // and then offset to the expected transform rect, but bound this to just // outside the display rect (to ensure we don't animate from too far away) sourceView = stackView; transform = stackView->GetStackAlgorithm()->GetStackTransform(task, stackScroll, transform, NULL); transform->mRect->GetLeft(&offsetX); mConfig->mDisplayRect->GetHeight(&offsetY); } else { sourceView = tv->mThumbnailView; transform = stackView->GetStackAlgorithm()->GetStackTransform(task, stackScroll, transform, NULL); } // Compute the thumbnail to scale up from AutoPtr<RecentsTaskLoader> rtl = RecentsTaskLoader::GetInstance(); AutoPtr<SystemServicesProxy> ssp; rtl->GetSystemServicesProxy((SystemServicesProxy**)&ssp); AutoPtr<IActivityOptions> opts; Int32 w, h; if (task->mThumbnail != NULL && (task->mThumbnail->GetWidth(&w), w > 0) && (task->mThumbnail->GetHeight(&h), h > 0)) { AutoPtr<IBitmapHelper> bHelper; CBitmapHelper::AcquireSingleton((IBitmapHelper**)&bHelper); AutoPtr<IBitmap> b; if (tv != NULL) { // Disable any focused state before we draw the header if (tv->IsFocusedTask()) { tv->UnsetFocusedTask(); } Float scale; tv->GetScaleX(&scale); tv->mHeaderView->GetMeasuredWidth(&w); tv->mHeaderView->GetMeasuredHeight(&h); Int32 fromHeaderWidth = (Int32) (w * scale); Int32 fromHeaderHeight = (Int32) (h * scale); bHelper->CreateBitmap(fromHeaderWidth, fromHeaderHeight, BitmapConfig_ARGB_8888, (IBitmap**)&b); if (Constants::DebugFlags::App::EnableTransitionThumbnailDebugMode) { b->EraseColor(0xFFff0000); } else { AutoPtr<ICanvas> c; CCanvas::New(b, (ICanvas**)&c); Float scaleX, scaleY; tv->GetScaleX(&scaleX); tv->GetScaleY(&scaleY); c->Scale(scaleX, scaleY); tv->mHeaderView->Draw(c); c->SetBitmap(NULL); } } else { // Notify the system to skip the thumbnail layer by using an ALPHA_8 bitmap bHelper->CreateBitmap(1, 1, BitmapConfig_ALPHA_8, (IBitmap**)&b); } AutoPtr<IActivityOptionsOnAnimationStartedListener> animStartedListener; if (lockToTask) { animStartedListener = new OnAnimationStartedListener(ssp, this); } AutoPtr<IActivityOptionsHelper> aoHelper; CActivityOptionsHelper::AcquireSingleton((IActivityOptionsHelper**)&aoHelper); transform->mRect->GetWidth(&w); transform->mRect->GetHeight(&h); aoHelper->MakeThumbnailAspectScaleUpAnimation( sourceView, b, offsetX, offsetY, w, h, animStartedListener, (IActivityOptions**)&opts); } AutoPtr<Runnable> launchRunnable = new LaunchRunnable(task, opts, lockToTask, this); Boolean res; // Launch the app right away if there is no task view, otherwise, animate the icon out first if (tv == NULL) { Post(launchRunnable, &res); } else { AutoPtr<TaskGrouping> tg = (TaskGrouping*)(task->mGroup).Get(); if (!tg->IsFrontMostTask(task)) { // For affiliated tasks that are behind other tasks, we must animate the front cards // out of view before starting the task transition stackView->StartLaunchTaskAnimation(tv, launchRunnable, lockToTask); } else { // Otherwise, we can start the task transition immediately stackView->StartLaunchTaskAnimation(tv, NULL, lockToTask); PostDelayed(launchRunnable, 17, &res); } } return NOERROR; } // @Override ECode RecentsView::OnTaskViewAppInfoClicked( /* [in] */ ITask* _t) { Task* t = (Task*)_t; // Create a new task stack with the application info details activity AutoPtr<IIntent> baseIntent = t->mKey->mBaseIntent; AutoPtr<IUriHelper> uriHelper; CUriHelper::AcquireSingleton((IUriHelper**)&uriHelper); AutoPtr<IComponentName> componet; baseIntent->GetComponent((IComponentName**)&componet); String pkgName; componet->GetPackageName(&pkgName); AutoPtr<IUri> uri; uriHelper->FromParts(String("package"), pkgName, String(NULL), (IUri**)&uri); AutoPtr<IIntent> intent; CIntent::New(ISettings::ACTION_APPLICATION_DETAILS_SETTINGS, uri, (IIntent**)&intent); AutoPtr<IContext> context; GetContext((IContext**)&context); AutoPtr<IPackageManager> pm; context->GetPackageManager((IPackageManager**)&pm); componet = NULL; intent->ResolveActivity(pm, (IComponentName**)&componet); intent->SetComponent(componet); AutoPtr<ITaskStackBuilderHelper> tsbHelper; CTaskStackBuilderHelper::AcquireSingleton((ITaskStackBuilderHelper**)&tsbHelper); AutoPtr<ITaskStackBuilder> taskStackBuilder; tsbHelper->Create(context, (ITaskStackBuilder**)&taskStackBuilder); taskStackBuilder->AddNextIntentWithParentStack(intent); AutoPtr<IUserHandle> userHandle; CUserHandle::New(t->mKey->mUserId, (IUserHandle**)&userHandle); taskStackBuilder->StartActivities(NULL, userHandle); return NOERROR; } // @Override ECode RecentsView::OnTaskViewDismissed( /* [in] */ ITask* taskObj) { Task* t = (Task*)taskObj; // Remove any stored data from the loader. We currently don't bother notifying the views // that the data has been unloaded because at the point we call onTaskViewDismissed(), the views // either don't need to be updated, or have already been removed. AutoPtr<RecentsTaskLoader> loader = RecentsTaskLoader::GetInstance(); loader->DeleteTaskData(t, FALSE); // Remove the old task from activity manager AutoPtr<SystemServicesProxy> ssp; loader->GetSystemServicesProxy((SystemServicesProxy**)&ssp); ssp->RemoveTask(t->mKey->mId, Utilities::IsDocument(t->mKey->mBaseIntent)); return NOERROR; } // @Override ECode RecentsView::OnAllTaskViewsDismissed() { return mCb->OnAllTaskViewsDismissed(); } // @Override ECode RecentsView::OnTaskStackFilterTriggered() { // Hide the search bar if (mSearchBar != NULL) { AutoPtr<IViewPropertyAnimator> animate; mSearchBar->Animate((IViewPropertyAnimator**)&animate); animate->Alpha(0.0f); animate->SetStartDelay(0); animate->SetInterpolator(ITimeInterpolator::Probe(mConfig->mFastOutSlowInInterpolator)); animate->SetDuration(mConfig->mFilteringCurrentViewsAnimDuration); animate->WithLayer(); animate->Start(); } return NOERROR; } // @Override ECode RecentsView::OnTaskStackUnfilterTriggered() { // Show the search bar if (mSearchBar != NULL) { AutoPtr<IViewPropertyAnimator> animate; mSearchBar->Animate((IViewPropertyAnimator**)&animate); animate->Alpha(1.0f); animate->SetStartDelay(0); animate->SetInterpolator(ITimeInterpolator::Probe(mConfig->mFastOutSlowInInterpolator)); animate->SetDuration(mConfig->mFilteringNewViewsAnimDuration); animate->WithLayer(); animate->Start(); } return NOERROR; } /**** RecentsPackageMonitor.PackageCallbacks Implementation ****/ // @Override ECode RecentsView::OnComponentRemoved( /* [in] */ IHashSet* cns) { // Propagate this event down to each task stack view Int32 childCount; GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; GetChildAt(i, (IView**)&child); if (child != mSearchBar) { AutoPtr<TaskStackView> stackView = (TaskStackView*)ITaskStackView::Probe(child); stackView->OnComponentRemoved(cns); } } return NOERROR; } } // namespace Views } // namespace Recents } // namespace SystemUI } // namespace Droid } // namespace Elastos
34.555957
111
0.632296
jingcao80
0cda9a014ed43d1a287d252950ea53b778b22bfa
5,656
cpp
C++
src/libv/ui/component/stretch.cpp
cpplibv/libv
293e382f459f0acbc540de8ef6283782b38d2e63
[ "Zlib" ]
2
2018-04-11T03:07:03.000Z
2019-03-29T15:24:12.000Z
src/libv/ui/component/stretch.cpp
cpplibv/libv
293e382f459f0acbc540de8ef6283782b38d2e63
[ "Zlib" ]
null
null
null
src/libv/ui/component/stretch.cpp
cpplibv/libv
293e382f459f0acbc540de8ef6283782b38d2e63
[ "Zlib" ]
1
2021-06-13T06:39:06.000Z
2021-06-13T06:39:06.000Z
// Project: libv.ui, File: src/libv/ui/component/stretch.cpp, Author: Császár Mátyás [Vader] // hpp #include <libv/ui/component/stretch.hpp> // pro #include <libv/ui/context/context_layout.hpp> #include <libv/ui/context/context_render.hpp> #include <libv/ui/context/context_style.hpp> #include <libv/ui/context/context_ui.hpp> #include <libv/ui/core_component.hpp> #include <libv/ui/property_access_context.hpp> #include <libv/ui/shader/shader_image.hpp> #include <libv/ui/style.hpp> #include <libv/ui/texture_2D.hpp> namespace libv { namespace ui { // ------------------------------------------------------------------------------------------------- struct CoreStretch : CoreComponent { friend class Stretch; [[nodiscard]] inline auto handler() { return Stretch{this}; } private: template <typename T> static void access_properties(T& ctx); struct Properties { PropertyR<Color> bg_color; PropertyL<Texture2D_view> bg_image; PropertyR<ShaderImage_view> bg_shader; } property; public: using CoreComponent::CoreComponent; private: virtual void doStyle(ContextStyle& ctx) override; virtual libv::vec3f doLayout1(const ContextLayout1& environment) override; virtual void doRender(Renderer& r) override; }; // ------------------------------------------------------------------------------------------------- template <typename T> void CoreStretch::access_properties(T& ctx) { ctx.property( [](auto& c) -> auto& { return c.property.bg_color; }, Color(1, 1, 1, 1), pgr::appearance, pnm::bg_color, "Background color" ); ctx.property( [](auto& c) -> auto& { return c.property.bg_image; }, [](auto& u) { return u.fallbackTexture2D(); }, pgr::appearance, pnm::bg_image, "Background image" ); ctx.property( [](auto& c) -> auto& { return c.property.bg_shader; }, [](auto& u) { return u.shaderImage(); }, pgr::appearance, pnm::bg_shader, "Background shader" ); } // ------------------------------------------------------------------------------------------------- void CoreStretch::doStyle(ContextStyle& ctx) { PropertyAccessContext<CoreStretch> setter{*this, ctx.component, ctx.style, context()}; access_properties(setter); CoreComponent::access_properties(setter); } libv::vec3f CoreStretch::doLayout1(const ContextLayout1& environment) { (void) environment; const auto dynamic_size_image = property.bg_image()->size().cast<float>() + padding_size(); return {dynamic_size_image, 0.f}; } void CoreStretch::doRender(Renderer& r) { // y3 12--13--14--15 // | / | / | / | // y2 8---9---10--11 // | / | / | / | // y1 4---5---6---7 // | / | / | / | // y0 0---1---2---3 // // x0 x1 x2 x3 const auto border_pos = min(cast<float>(property.bg_image()->size()), layout_size2()) * 0.5f; const auto border_tex = min(layout_size2() / max(cast<float>(property.bg_image()->size()), 1.0f) * 0.5f, 0.5f); const auto p0 = libv::vec2f{0.0f, 0.0f}; const auto p1 = border_pos; const auto p2 = layout_size2() - border_pos; const auto p3 = layout_size2(); const auto t0 = libv::vec2f{0.0f, 0.0f}; const auto t1 = border_tex; const auto t2 = 1.0f - border_tex; const auto t3 = libv::vec2f{1.0f, 1.0f}; const auto color = property.bg_color(); r.begin_triangles(); r.vertex({p0.x, p0.y, 0}, {t0.x, t0.y}, color); r.vertex({p1.x, p0.y, 0}, {t1.x, t0.y}, color); r.vertex({p2.x, p0.y, 0}, {t2.x, t0.y}, color); r.vertex({p3.x, p0.y, 0}, {t3.x, t0.y}, color); r.vertex({p0.x, p1.y, 0}, {t0.x, t1.y}, color); r.vertex({p1.x, p1.y, 0}, {t1.x, t1.y}, color); r.vertex({p2.x, p1.y, 0}, {t2.x, t1.y}, color); r.vertex({p3.x, p1.y, 0}, {t3.x, t1.y}, color); r.vertex({p0.x, p2.y, 0}, {t0.x, t2.y}, color); r.vertex({p1.x, p2.y, 0}, {t1.x, t2.y}, color); r.vertex({p2.x, p2.y, 0}, {t2.x, t2.y}, color); r.vertex({p3.x, p2.y, 0}, {t3.x, t2.y}, color); r.vertex({p0.x, p3.y, 0}, {t0.x, t3.y}, color); r.vertex({p1.x, p3.y, 0}, {t1.x, t3.y}, color); r.vertex({p2.x, p3.y, 0}, {t2.x, t3.y}, color); r.vertex({p3.x, p3.y, 0}, {t3.x, t3.y}, color); r.index_strip({4, 0, 5, 1, 6, 2, 7, 3}); r.index_strip({3, 8}); // jump r.index_strip({8, 4, 9, 5, 10, 6, 11, 7}); r.index_strip({7, 12}); // jump r.index_strip({12, 8, 13, 9, 14, 10, 15, 11}); r.end(property.bg_image(), property.bg_shader()); } // ------------------------------------------------------------------------------------------------- Stretch::Stretch(std::string name) : ComponentHandler<CoreStretch, EventHostGeneral<Stretch>>(std::move(name)) { } Stretch::Stretch(GenerateName_t gen, const std::string_view type) : ComponentHandler<CoreStretch, EventHostGeneral<Stretch>>(gen, type) { } Stretch::Stretch(core_ptr core) noexcept : ComponentHandler<CoreStretch, EventHostGeneral<Stretch>>(core) { } // ------------------------------------------------------------------------------------------------- void Stretch::color(Color value) { AccessProperty::manual(self(), self().property.bg_color, value); } const Color& Stretch::color() const noexcept { return self().property.bg_color(); } void Stretch::image(Texture2D_view value) { AccessProperty::manual(self(), self().property.bg_image, std::move(value)); } const Texture2D_view& Stretch::image() const noexcept { return self().property.bg_image(); } void Stretch::shader(ShaderImage_view value) { AccessProperty::manual(self(), self().property.bg_shader, std::move(value)); } const ShaderImage_view& Stretch::shader() const noexcept { return self().property.bg_shader(); } // ------------------------------------------------------------------------------------------------- } // namespace ui } // namespace libv
31.248619
112
0.589993
cpplibv
0cdc4adfc3c3e4b1e3bb1b9f8b4fc7a464efd0c3
4,792
cc
C++
src/telephony/telephony_instance.cc
izaman/tizen-extensions-crosswalk
e1373788f4e4e271e39b0fee66c26210e40dd86f
[ "Apache-2.0", "BSD-3-Clause" ]
10
2015-01-16T16:14:35.000Z
2018-12-25T16:01:43.000Z
src/telephony/telephony_instance.cc
liyingzh/tizen-extensions-crosswalk
5957945effafff02a507c35a4b7b4d5ee6ca14c1
[ "Apache-2.0", "BSD-3-Clause" ]
35
2015-01-04T02:11:22.000Z
2015-09-22T08:43:45.000Z
src/telephony/telephony_instance.cc
liyingzh/tizen-extensions-crosswalk
5957945effafff02a507c35a4b7b4d5ee6ca14c1
[ "Apache-2.0", "BSD-3-Clause" ]
14
2015-02-03T04:38:19.000Z
2022-01-20T10:38:01.000Z
// Copyright (c) 2014 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "telephony/telephony_instance.h" #include <string> #include "common/picojson.h" #include "telephony/telephony_backend_ofono.h" #include "tizen/tizen.h" namespace { const char kCmdGetServices[] = "getServices"; const char kCmdSetDefaultService[] = "setDefaultService"; const char kCmdSetServiceEnabled[] = "setServiceEnabled"; const char kCmdGetCalls[] = "getCalls"; const char kCmdDial[] = "dial"; const char kCmdAccept[] = "accept"; const char kCmdDisconnect[] = "disconnect"; const char kCmdHold[] = "hold"; const char kCmdResume[] = "resume"; const char kCmdDeflect[] = "deflect"; const char kCmdTransfer[] = "transfer"; const char kCmdSplit[] = "split"; const char kCmdSendTones[] = "sendTones"; const char kCmdStartTone[] = "startTone"; const char kCmdStopTone[] = "stopTone"; const char kCmdGetEmergencyNumbers[] = "getEmergencyNumbers"; const char kCmdEmergencyDial[] = "emergencyDial"; const char kCmdCreateConference[] = "createConference"; const char kCmdGetParticipants[] = "getParticipants"; const char kCmdEnableNotifications[] = "enableNotifications"; const char kCmdDisableNotifications[] = "disableNotifications"; } // namespace TelephonyInstance::TelephonyInstance() : backend_(new TelephonyBackend(this)) { } TelephonyInstance::~TelephonyInstance() { delete backend_; } void TelephonyInstance::HandleMessage(const char* msg) { picojson::value v; std::string err; picojson::parse(v, msg, msg + strlen(msg), &err); if (!err.empty()) { std::cerr << "Error: ignoring empty message.\n"; return; } if (!backend_) { SendErrorReply(v, NO_MODIFICATION_ALLOWED_ERR, "Telephony backend not initialized."); return; } std::string cmd = v.get("cmd").to_str(); if (cmd == kCmdGetServices) { backend_->GetServices(v); } else if (cmd == kCmdSetDefaultService) { backend_->SetDefaultService(v); } else if (cmd == kCmdSetServiceEnabled) { backend_->SetServiceEnabled(v); } else if (cmd == kCmdEnableNotifications) { backend_->EnableSignalHandlers(); } else if (cmd == kCmdDisableNotifications) { backend_->DisableSignalHandlers(); } else if (cmd == kCmdGetCalls) { backend_->GetCalls(v); } else if (cmd == kCmdDial) { backend_->DialCall(v); } else if (cmd == kCmdAccept) { backend_->AcceptCall(v); } else if (cmd == kCmdDisconnect) { backend_->DisconnectCall(v); } else if (cmd == kCmdHold) { backend_->HoldCall(v); } else if (cmd == kCmdResume) { backend_->ResumeCall(v); } else if (cmd == kCmdDeflect) { backend_->DeflectCall(v); } else if (cmd == kCmdTransfer) { backend_->TransferCall(v); } else if (cmd == kCmdSendTones) { backend_->SendTones(v); } else if (cmd == kCmdStartTone) { backend_->StartTone(v); } else if (cmd == kCmdStopTone) { backend_->StopTone(v); } else if (cmd == kCmdGetEmergencyNumbers) { backend_->GetEmergencyNumbers(v); } else if (cmd == kCmdEmergencyDial) { backend_->EmergencyDial(v); } else if (cmd == kCmdCreateConference) { backend_->CreateConference(v); } else if (cmd == kCmdGetParticipants) { backend_->GetConferenceParticipants(v); } else if (cmd == kCmdSplit) { backend_->SplitCall(v); } else { std::cout << "Ignoring unknown command: " << cmd; } } void TelephonyInstance::HandleSyncMessage(const char* message) { } void TelephonyInstance::SendErrorReply(const picojson::value& msg, const int error_code, const char* error_msg) { picojson::value::object reply; reply["promiseId"] = msg.get("promiseId"); reply["cmd"] = msg.get("cmd"); reply["isError"] = picojson::value(true); reply["errorCode"] = picojson::value(static_cast<double>(error_code)); reply["errorMessage"] = error_msg ? picojson::value(error_msg) : msg.get("cmd"); picojson::value v(reply); PostMessage(v.serialize().c_str()); } void TelephonyInstance::SendSuccessReply(const picojson::value& msg, const picojson::value& value) { picojson::value::object reply; reply["promiseId"] = msg.get("promiseId"); reply["cmd"] = msg.get("cmd"); reply["isError"] = picojson::value(false); reply["returnValue"] = value; picojson::value v(reply); PostMessage(v.serialize().c_str()); } void TelephonyInstance::SendSuccessReply(const picojson::value& msg) { picojson::value::object reply; reply["promiseId"] = msg.get("promiseId"); reply["cmd"] = msg.get("cmd"); reply["isError"] = picojson::value(false); picojson::value v(reply); PostMessage(v.serialize().c_str()); } void TelephonyInstance::SendNotification(const picojson::value& msg) { PostMessage(msg.serialize().c_str()); }
32.378378
79
0.692613
izaman
0cdf589e598c31402e68e86595e88ef22d2c8193
9,280
cpp
C++
SwapChain/Driver/OpenGL/src/Win32/SwapChain.cpp
Gpinchon/OCRA
341bb07facc616f1f8a27350054d1e86f022d7c6
[ "Apache-2.0" ]
null
null
null
SwapChain/Driver/OpenGL/src/Win32/SwapChain.cpp
Gpinchon/OCRA
341bb07facc616f1f8a27350054d1e86f022d7c6
[ "Apache-2.0" ]
null
null
null
SwapChain/Driver/OpenGL/src/Win32/SwapChain.cpp
Gpinchon/OCRA
341bb07facc616f1f8a27350054d1e86f022d7c6
[ "Apache-2.0" ]
null
null
null
#include <GL/Win32/SwapChain.hpp> #include <GL/Win32/PresentGeometry.hpp> #include <GL/Win32/PresentPixels.hpp> #include <GL/Win32/PresentShader.hpp> #include <GL/Win32/PresentTexture.hpp> #include <GL/Surface.hpp> #include <GL/Win32/Error.hpp> #include <GL/Win32/OpenGL.hpp> #include <GL/Device.hpp> #include <GL/Image/Format.hpp> #include <GL/Image/Image.hpp> #include <GL/Queue/Queue.hpp> #include <GL/Queue/Semaphore.hpp> #include <GL/Queue/Fence.hpp> #include <GL/Common/BufferOffset.hpp> #include <GL/glew.h> #include <GL/wglew.h> #include <iostream> #include <sstream> namespace OCRA::SwapChain::Win32 { void GLAPIENTRY MessageCallback( GLenum source, GLenum type, GLenum id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) { if (type == GL_DEBUG_TYPE_ERROR) { std::stringstream ss{}; ss << "GL CALLBACK : **GL ERROR * *\n" << " type = " << type << "\n" << " severity = " << severity << "\n" << " message = " << message; std::cerr << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } static inline auto CreateImages(const Device::Handle& a_Device, const Info& a_Info) { std::vector<Image::Handle> images; auto win32SwapChain = std::static_pointer_cast<SwapChain::Win32::Impl>(a_Info.oldSwapchain); for (auto i = 0u; i < a_Info.imageCount; ++i) { Image::Handle image; if (win32SwapChain != nullptr) { const auto& imageInfo = win32SwapChain->images.at(i)->info; const bool canRecycle = imageInfo.extent.width == a_Info.imageExtent.width && imageInfo.extent.height == a_Info.imageExtent.height && imageInfo.arrayLayers == a_Info.imageArrayLayers && imageInfo.format == a_Info.imageFormat; if (canRecycle) image = win32SwapChain->images.at(i); } if (image == nullptr) { Image::Info imageInfo{}; imageInfo.type = Image::Type::Image2D; imageInfo.extent.width = a_Info.imageExtent.width; imageInfo.extent.height = a_Info.imageExtent.height; imageInfo.mipLevels = 1; imageInfo.arrayLayers = a_Info.imageArrayLayers; imageInfo.format = a_Info.imageFormat; image = Image::Create(a_Device, imageInfo); } images.push_back(image); } return images; } Impl::Impl(const Device::Handle& a_Device, const Info& a_Info) : SwapChain::Impl(a_Device, a_Info) , images(CreateImages(a_Device, a_Info)) { const auto pixelSize = GetPixelSize(info.imageFormat); if (info.oldSwapchain != nullptr && !info.oldSwapchain->retired) { auto win32SwapChain = std::static_pointer_cast<SwapChain::Win32::Impl>(info.oldSwapchain); win32SwapChain->workerThread.Wait(); hdc = win32SwapChain->hdc; hglrc = win32SwapChain->hglrc; presentShader.swap(win32SwapChain->presentShader); info.oldSwapchain->Retire(); info.oldSwapchain.reset(); } else { hdc = GetDC(HWND(a_Info.surface->nativeWindow)); OpenGL::Win32::Initialize(); const int attribIList[] = { WGL_DRAW_TO_WINDOW_ARB, true, WGL_SUPPORT_OPENGL_ARB, true, WGL_DOUBLE_BUFFER_ARB, true, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, WGL_COLORSPACE_EXT, WGL_COLORSPACE_SRGB_EXT, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_COLOR_BITS_ARB, pixelSize, 0 }; int32_t pixelFormat = 0; uint32_t pixelFormatNbr = 0; WIN32_CHECK_ERROR(wglChoosePixelFormatARB(HDC(hdc), attribIList, nullptr, 1, &pixelFormat, &pixelFormatNbr)); WIN32_CHECK_ERROR(pixelFormat != 0); WIN32_CHECK_ERROR(pixelFormatNbr != 0); WIN32_CHECK_ERROR(SetPixelFormat(HDC(hdc), pixelFormat, nullptr)); hglrc = OpenGL::Win32::CreateContext(hdc); } workerThread.PushCommand([this, pixelSize] { WIN32_CHECK_ERROR(wglMakeCurrent(HDC(hdc), HGLRC(hglrc))); if (info.presentMode == PresentMode::Immediate) { WIN32_CHECK_ERROR(wglSwapIntervalEXT(0)); } else WIN32_CHECK_ERROR(wglSwapIntervalEXT(1)); #ifdef _DEBUG glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback(MessageCallback, 0); #endif _DEBUG if (presentTexture == nullptr) { presentTexture.reset(new PresentTexture(images.front())); presentTexture->Bind(); } if (presentShader == nullptr) { presentShader.reset(new PresentShader); presentShader->Bind(); } if (presentGeometry == nullptr) { presentGeometry.reset(new PresentGeometry); presentGeometry->Bind(); } if (!WGLEW_NV_copy_image && presentPixels == nullptr) { static bool warningPrinted = false; if (!warningPrinted) { std::cerr << "SwapChain : WGL_NV_copy_image unavailable, using slower path\n"; warningPrinted = true; } const auto transferBufferSize = info.imageExtent.width * info.imageExtent.height * pixelSize / 8; presentPixels.reset(new PresentPixels(transferBufferSize)); presentPixels->Bind(); } glViewport(0, 0, presentTexture->extent.width, presentTexture->extent.height); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glActiveTexture(GL_TEXTURE0); glBindSampler(0, presentTexture->samplerHandle); }, false); } Impl::~Impl() { retired = true; workerThread.PushCommand([this] { presentTexture.reset(); presentShader.reset(); presentGeometry.reset(); presentPixels.reset(); wglMakeCurrent(nullptr, nullptr); }, true); if (hdc != nullptr) ReleaseDC(HWND(info.surface->nativeWindow), HDC(hdc)); if (hglrc != nullptr) wglDeleteContext(HGLRC(hglrc)); } void Impl::Retire() { SwapChain::Impl::Retire(); workerThread.PushCommand([this] { presentShader.reset(); presentTexture.reset(); presentGeometry.reset(); presentPixels.reset(); wglMakeCurrent(nullptr, nullptr); }, true); images.clear(); hdc = nullptr; hglrc = nullptr; } void Impl::Present(const Queue::Handle& a_Queue) { assert(!retired); if (WGLEW_NV_copy_image) { PresentNV(a_Queue); } else { PresentGL(a_Queue); } } void Impl::PresentNV(const Queue::Handle& a_Queue) { const auto& image = images.at(backBufferIndex); const auto extent = image->info.extent; a_Queue->PushCommand([this, extent] { const auto& image = images.at(backBufferIndex); auto sync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); glClientWaitSync(sync, 0, 1000); glDeleteSync(sync); WIN32_CHECK_ERROR(wglCopyImageSubDataNV( nullptr, image->handle, image->target, //use current context 0, 0, 0, 0, HGLRC(hglrc), presentTexture->handle, presentTexture->target, 0, 0, 0, 0, extent.width, extent.height, 1)); }, true); workerThread.PushCommand([this, extent] { presentGeometry->Draw(); WIN32_CHECK_ERROR(SwapBuffers(HDC(hdc))); }, info.presentMode != PresentMode::Immediate); backBufferIndex = (backBufferIndex + 1) % info.imageCount; } void Impl::PresentGL(const Queue::Handle& a_Queue) { const auto& image = images.at(backBufferIndex); const auto extent = image->info.extent; a_Queue->PushCommand([this, extent] { const auto& image = images.at(backBufferIndex); glBindTexture(image->target, image->handle); glGetTexImage( image->target, 0, image->dataFormat, image->dataType, presentPixels->GetPtr()); glBindTexture(image->target, 0); }, true); workerThread.PushCommand([this, extent] { presentPixels->Flush(); glTexSubImage2D( presentTexture->target, 0, 0, 0, extent.width, extent.height, presentTexture->dataFormat, presentTexture->dataType, BUFFER_OFFSET(presentPixels->offset)); presentGeometry->Draw(); WIN32_CHECK_ERROR(SwapBuffers(HDC(hdc))); }, info.presentMode != PresentMode::Immediate); backBufferIndex = (backBufferIndex + 1) % info.imageCount; } //TODO: implement a timeout Image::Handle Impl::AcquireNextImage( const std::chrono::nanoseconds& a_Timeout, const Queue::Semaphore::Handle& a_Semaphore, const Queue::Fence::Handle& a_Fence) { workerThread.Wait(); //We do not need to synchronize with the GPU for real here if (a_Semaphore != nullptr) { if (a_Semaphore->type == Queue::Semaphore::Type::Binary) std::static_pointer_cast<Queue::Semaphore::Binary>(a_Semaphore)->SignalNoSync(); else throw std::runtime_error("Cannot wait on Timeline Semaphores when presenting"); } if (a_Fence != nullptr) a_Fence->SignalNoSync(); return images.at(backBufferIndex); } }
35.968992
117
0.628017
Gpinchon
0ce1fd51fe99bd2aef16c916c6ba9c7326bd2b23
521
cpp
C++
codeforces/1475A.cpp
LordRonz/cp-solutions
d95eabbdbf6a04fba912f4e8be203b180af7f46d
[ "WTFPL" ]
2
2021-04-19T06:20:11.000Z
2021-05-04T14:30:00.000Z
codeforces/1475A.cpp
LordRonz/cp-solutions
d95eabbdbf6a04fba912f4e8be203b180af7f46d
[ "WTFPL" ]
2
2022-03-01T09:28:46.000Z
2022-03-02T09:52:33.000Z
codeforces/1475A.cpp
LordRonz/cp-solutions
d95eabbdbf6a04fba912f4e8be203b180af7f46d
[ "WTFPL" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define MAX(a,b,c) max(a,max(b,c)) #define MIN(a,b,c) min(a,min(b,c)) #define MP make_pair #define FOR(x, a, b) for(int x = a; x < b; ++x) typedef pair<int, int> pii; //0xACCE97ED; int main() { long long unsigned n, t; scanf("%lld", &t); while(t--) { scanf("%lld", &n); if(n & 1) { puts("YES"); continue; } long long unsigned div = 3; while(n > 1) { if(n & 1) { puts("YES"); break; } n >>= 1; } if(n == 1) puts("NO"); } return 0; }
16.806452
47
0.527831
LordRonz
0ce83d17e36b56392ae66bdda1e9e462aede0061
865
cpp
C++
PAT/Advanced Level/Simulation_Math/1148 Werewolf.cpp
MuZi-lh/AlgorithmExecise
88411f52ad65ef002ed8bcbcffc402f64985958f
[ "MulanPSL-1.0" ]
null
null
null
PAT/Advanced Level/Simulation_Math/1148 Werewolf.cpp
MuZi-lh/AlgorithmExecise
88411f52ad65ef002ed8bcbcffc402f64985958f
[ "MulanPSL-1.0" ]
null
null
null
PAT/Advanced Level/Simulation_Math/1148 Werewolf.cpp
MuZi-lh/AlgorithmExecise
88411f52ad65ef002ed8bcbcffc402f64985958f
[ "MulanPSL-1.0" ]
null
null
null
#include<iostream> #include<vector> using namespace std; int N; vector<int> p(100); bool tellingTruth(int a, int b, int t) { return (abs(p[t]) != a && abs(p[t]) != b && p[t] > 0) || (p[t] == -a || p[t] == -b); } // a, b are wolf, // assume a, b don't point at themselves // a tell a truth, b tell a lie bool legal(int a, int b) { int cnt = 0; if (tellingTruth(a, b, a) && !tellingTruth(a, b, b)) { for (int k = 1;k <= N;k++) { if (k != b && !tellingTruth(a, b, k)) { cnt++; } } if (cnt == 1) return true; } return false; } // positive for human and negtive for wolf int main() { cin >> N; for (int i = 1; i <= N; i++) { cin >> p[i]; } for (int i = 1; i <= N - 1; i++) { for (int j = i + 1;j <= N;j++) { if (legal(i, j) || legal(j, i)) { cout << i << ' ' << j; return 0; } } } cout << "No Solution"; return 0; }
18.804348
85
0.491329
MuZi-lh
0ce92d47507b7639fa18ea1fb22e4d36ef08339a
9,890
cpp
C++
Source/Game/GameState/IntroState/IntroState.cpp
Crazykingjammy/bkbotz
6cdaa4164ff02e40f2909982f6dacad161c7d6cf
[ "Unlicense" ]
null
null
null
Source/Game/GameState/IntroState/IntroState.cpp
Crazykingjammy/bkbotz
6cdaa4164ff02e40f2909982f6dacad161c7d6cf
[ "Unlicense" ]
null
null
null
Source/Game/GameState/IntroState/IntroState.cpp
Crazykingjammy/bkbotz
6cdaa4164ff02e40f2909982f6dacad161c7d6cf
[ "Unlicense" ]
null
null
null
#include "../GameState.h" CIntroGameState* CIntroGameState::pInstance = 0; void CIntroGameState::Initalize(Game* game) { //Get the Pointer to the game. pGame = game; ////////////////////////////////////////////////////////////////////////// // Lights Setup ////////////////////////////////////////////////////////////////////////// //Set up Lights here pRenderInterface->Light[0].m_Active = true; pRenderInterface->Light[0].m_MyBody.centerPosition.y = 10.0f; pRenderInterface->Light[0].m_Specular = 0.0f; pRenderInterface->Light[0].m_Diffuse = EXColor(0.6f,0.65f,0.65f,1.0f); pRenderInterface->Light[0].m_Ambient = EXColor(0.1f,0.1f,0.1f,1.0f); pRenderInterface->Light[0].m_Attenuation2 = 0.0000002f; ////////////////////////////////////////////////////////////////////////// // Lights Setup ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Camera Setup ////////////////////////////////////////////////////////////////////////// Camera0 = new CFreeCamera; Camera1 = new CFreeCamera; Camera0->m_LinearSpeed = 5.0f; Camera0->m_MyBody.centerPosition.y += 24.035156f; Camera0->m_MyBody.centerPosition.x -= 35.638084f; Camera0->m_MyBody.centerPosition.z -= 26.376434f; Camera1->m_MyBody.centerPosition.z = -10.0f; pRenderInterface->SetActiveCamera(Camera0); //pRenderInterface-> ////////////////////////////////////////////////////////////////////////// // Camera Setup ////////////////////////////////////////////////////////////////////////// m_2DScene.Set2DWorld((float)pGame->Window.WindowWidth,(float)pGame->Window.WindowHeight); m_2DScene.sceneGravity.MakeZero(); ////////////////////////////////////////////////////////////////////////// // Object Setup ////////////////////////////////////////////////////////////////////////// pRenderInterface->SetWorld("Models/MenuWorld.X"); Ship = new CBall; strcpy(Ship->m_ModelName,"Models/MenuShip.X"); Ship->m_MyBody.centerPosition.y += 7.0f; //pRenderInterface->AddObject(Ship); //Ship->m_MyBodyIndex = m_Scene.AddBody(&Ship->m_MyBody); Battle = new CLabel("Textures/MenuIcon_1.bmp"); pRenderInterface->AddLabel(Battle); Battle->m_MyBody.centerPosition.x += (float)(pGame->Window.WindowWidth / 3); Battle->m_MyBody.centerPosition.y += (float) (pGame->Window.WindowHeight / 3); Battle->m_MyBody.radius = 10.0f; Battle->m_MyBody.mass = 1.0f; Battle->m_MyBodyIndex = m_2DScene.AddBody(&Battle->m_MyBody); Credits = new CLabel("Textures/MenuIcon_3.bmp"); pRenderInterface->AddLabel(Credits); Credits->m_MyBody.centerPosition.x += 300.0f; Credits->m_MyBody.centerPosition.y += 450.0f; Credits->m_MyBody.radius = 10.0f; Credits->m_MyBody.mass = 1.0f; Credits->m_MyBodyIndex = m_2DScene.AddBody(&Credits->m_MyBody); Exit = new CLabel("Textures/MenuIcon_4.bmp"); pRenderInterface->AddLabel(Exit); Exit->m_MyBody.centerPosition.x += 600.0f; Exit->m_MyBody.centerPosition.y += 450.0f; Exit->m_MyBody.radius = 10.0f;; Exit->m_MyBody.mass = 1.0f; Exit->m_MyBodyIndex = m_2DScene.AddBody(&Exit->m_MyBody); Soccer = new CLabel("Textures/MenuIcon_2.bmp"); pRenderInterface->AddLabel(Soccer); Soccer->m_MyBody.centerPosition.x += 600.0f; Soccer->m_MyBody.centerPosition.y += 150.0f; Soccer->m_MyBody.radius = 10.0f;; Soccer->m_MyBodyIndex = m_2DScene.AddBody(&Soccer->m_MyBody); Soccer->m_MyBody.mass = 1.0f; Me = new CLabel("Textures/MenuIcon_0.bmp"); pRenderInterface->AddLabel(Me); Me->m_MyBody.isNapping = false; Me->m_MyBody.centerPosition.x += (float)(pGame->Window.WindowWidth/2); Me->m_MyBody.centerPosition.y += (float)(pGame->Window.WindowHeight/2); Me->m_MyBody.mass = 10.0f; Me->m_MyBody.radius = 64.0f;; Me->m_MyBodyIndex = m_2DScene.AddBody(&Me->m_MyBody); //strcpy(Me->m_Text, "B"); GameText = new CLabel("Textures/jamtext.bmp"); pRenderInterface->AddLabel(GameText); GameText->m_MyBody.centerPosition.x = 280.0f; GameText->m_MyBody.centerPosition.y = 30.0f; ////////////////////////////////////////////////////////////////////////// // Object Setup ////////////////////////////////////////////////////////////////////////// //Numbers MeForce = 27000.0f * 4.0f; m_InputFreq = 0.05f; CurrentSelection = 0; //Create the Scene pRenderInterface->CreateScene(); } void CIntroGameState::Update(float timeDelta) { //m_Scene.Simulate(); m_2DScene.Simulate(); Camera0->LookAt(pRenderInterface->m_World); cout << Me->m_MyBody.centerPosition.x << ' ' << Me->m_MyBody.centerPosition.y << ' ' << Me->m_MyBody.centerPosition.z<< endl; //Pull toward the middle. Battle->m_MyBody.gravityForce = CVector3f(400.0f, 300.0f, 0.0f) - Battle->m_MyBody.centerPosition; Battle->m_MyBody.gravityForce.Normalize(); Battle->m_MyBody.gravityForce *= 5.8f; Credits->m_MyBody.gravityForce = CVector3f(400.0f, 300.0f, 0.0f) - Credits->m_MyBody.centerPosition; Credits->m_MyBody.gravityForce.Normalize(); Credits->m_MyBody.gravityForce *= 5.8f; Soccer->m_MyBody.gravityForce = CVector3f(400.0f, 300.0f, 0.0f) - Soccer->m_MyBody.centerPosition; Soccer->m_MyBody.gravityForce.Normalize(); Soccer->m_MyBody.gravityForce *= 5.8f; Exit->m_MyBody.gravityForce = CVector3f(400.0f, 300.0f, 0.0f) - Exit->m_MyBody.centerPosition; Exit->m_MyBody.gravityForce.Normalize(); Exit->m_MyBody.gravityForce *= 5.8f; //Check for controls. if (m_InputTimer.GetElapsedSeconds() >= m_InputFreq) { Controls(); Me->m_Rotation += 0.01f; // Me->m_MyBody.velocityVec.Magnitude(); Me->m_MyBody.Add2Force( (CVector3f((float)(pGame->Window.WindowWidth/2), (float)(pGame->Window.WindowHeight/2), 0.0f) - Me->m_MyBody.centerPosition) * 750.0f ); m_InputTimer.Reset(); } CollisionDetection(); //attach cam to the player. Camera1->m_MyBody.centerPosition = Ship->m_MyBody.centerPosition; //Move camera Camera1->m_MyBody.centerPosition.y += 4.51f; Camera1->m_MyBody.centerPosition.x -= 0.51f; Camera1->m_MyBody.centerPosition.z -= 3.3f; switch(CurrentSelection) { char test[128]; case BATTLE: { sprintf(test, "Battle Game"); strcpy(GameText->m_Text,test); if (pInput->Controller1JoyPress(0)) { ChangeState(pGame,CBattleGameState::GetInstance()); return; } break; } case SOCCER: { sprintf(test, "Soccer Game"); strcpy(GameText->m_Text,test); if (pInput->Controller1JoyPress(0)) { ChangeState(pGame, CSoccerGameState::GetInstance()); return; } break; } case EXIT: { sprintf(test, "Exit Game"); strcpy(GameText->m_Text,test); if (pInput->Controller1JoyPress(0)) { //Only place this should be getting called :_D PostQuitMessage(0); } break; } case CREDITS: { sprintf(test, "Game Credits"); strcpy(GameText->m_Text,test); if (pInput->Controller1JoyPress(0)) { ChangeState(pGame, CJukeBoxState::GetInstance()); return; } break; } } } void CIntroGameState::Shutdown() { //Destroy teh modles and reset the scene. pRenderInterface->DestroyScene(); m_Scene.ClearScene(); m_2DScene.ClearScene(); delete Camera0; delete Camera1; delete Ship; delete Exit; delete Soccer; delete Battle; delete Credits; //Clean Me Up. if(pInstance) delete pInstance; pInstance = 0; } void CIntroGameState::Controls() { //Get input States. pInput->SetAllStates(); if (pInput->Controller1JoyPress(1)) { Me->m_MyBody.velocityVec.MakeZero(); } // timer >= inpout time // do this if(GetAsyncKeyState('W')) pRenderInterface->m_ActiveCamera->MoveUp(); if(GetAsyncKeyState('S')) pRenderInterface->m_ActiveCamera->MoveDown(); if(GetAsyncKeyState('A')) pRenderInterface->m_ActiveCamera->MoveLeft(); if(GetAsyncKeyState('D')) pRenderInterface->m_ActiveCamera->MoveRight(); if(GetAsyncKeyState('C')) pRenderInterface->m_ActiveCamera->MoveFoward(); if(GetAsyncKeyState('V')) pRenderInterface->m_ActiveCamera->MoveBackward(); if(GetAsyncKeyState('F')) pRenderInterface->m_ActiveCamera->LookLeft(); if(GetAsyncKeyState('H')) pRenderInterface->m_ActiveCamera->LookRight(); if(GetAsyncKeyState('T')) pRenderInterface->m_ActiveCamera->LookUp(); if(GetAsyncKeyState('G')) pRenderInterface->m_ActiveCamera->LookDown(); if(pInput->Controller1JoyY() < -200) { Me->m_MyBody.Add2Force( CVector3f(0.0f,-1.0f,0.0f) * (MeForce ) ); } if(pInput->Controller1JoyY() > 200) { Me->m_MyBody.Add2Force( CVector3f(0.0f,1.0f,0.0f) * MeForce ); } if(pInput->Controller1JoyX() < -200) { Me->m_MyBody.Add2Force( CVector3f(-1.0f,0.0f,0.0f) * MeForce ); } if(pInput->Controller1JoyX() > 200) { Me->m_MyBody.Add2Force( CVector3f(1.0f,0.0f,0.0f) * MeForce ); } if(GetAsyncKeyState('P')) pRenderInterface->SetActiveCamera(Camera1); if(GetAsyncKeyState('L')) pRenderInterface->SetActiveCamera(Camera0); } void CIntroGameState::CollisionDetection() { if(m_2DScene.HaveTheTwoBodiesCollided(Battle->m_MyBodyIndex,Me->m_MyBodyIndex)) { CurrentSelection = BATTLE; Camera0->m_MyBody.centerPosition.y = 24.035156f; Camera0->m_MyBody.centerPosition.x = -35.638084f; Camera0->m_MyBody.centerPosition.z = -26.376434f; } if(m_2DScene.HaveTheTwoBodiesCollided(Soccer->m_MyBodyIndex,Me->m_MyBodyIndex)) { CurrentSelection = SOCCER; } if(m_2DScene.HaveTheTwoBodiesCollided(Exit->m_MyBodyIndex,Me->m_MyBodyIndex)) { CurrentSelection = EXIT; Camera0->m_MyBody.centerPosition.y = 23.254128f; Camera0->m_MyBody.centerPosition.x = -58.199429f; Camera0->m_MyBody.centerPosition.z = 19.165016f; } if(m_2DScene.HaveTheTwoBodiesCollided(Credits->m_MyBodyIndex,Me->m_MyBodyIndex)) { CurrentSelection = CREDITS; } } CIntroGameState* CIntroGameState::GetInstance() { //If there is no instance if(pInstance == 0) pInstance = new CIntroGameState; //We Create One return pInstance; //Return the Instance. }
25.101523
163
0.649848
Crazykingjammy
0ceb7006ab85f69b90b7333e5938e9e2b3c84aab
126
cpp
C++
ZF/ZFUIKit/zfsrc/ZFUIKit/protocol/ZFProtocolZFUIView.cpp
ZFFrameworkDist/ZFFramework
6b498e7b95ee6d6aaa28d8369eef8c2ff94daaf7
[ "MIT" ]
57
2016-06-12T11:05:55.000Z
2021-05-22T13:12:17.000Z
ZF/ZFUIKit/zfsrc/ZFUIKit/protocol/ZFProtocolZFUIView.cpp
ZFFrameworkDist/ZFFramework
6b498e7b95ee6d6aaa28d8369eef8c2ff94daaf7
[ "MIT" ]
null
null
null
ZF/ZFUIKit/zfsrc/ZFUIKit/protocol/ZFProtocolZFUIView.cpp
ZFFrameworkDist/ZFFramework
6b498e7b95ee6d6aaa28d8369eef8c2ff94daaf7
[ "MIT" ]
20
2016-05-26T04:47:37.000Z
2020-12-13T01:39:39.000Z
#include "ZFProtocolZFUIView.h" ZF_NAMESPACE_GLOBAL_BEGIN ZFPROTOCOL_INTERFACE_REGISTER(ZFUIView) ZF_NAMESPACE_GLOBAL_END
14
39
0.880952
ZFFrameworkDist
0ced71d029ec7f52b67c86ddfcffcb90d56d756d
9,437
cpp
C++
C++/vbHmmModel_GaussDiffusion.cpp
okamoto-kenji/varBayes-HMM
77afe3c336c9e1ebeb115ca4f0b2bc25060556bd
[ "MIT" ]
7
2016-03-31T06:59:00.000Z
2019-11-01T06:35:57.000Z
C++/vbHmmModel_GaussDiffusion.cpp
okamoto-kenji/varBayes-HMM
77afe3c336c9e1ebeb115ca4f0b2bc25060556bd
[ "MIT" ]
null
null
null
C++/vbHmmModel_GaussDiffusion.cpp
okamoto-kenji/varBayes-HMM
77afe3c336c9e1ebeb115ca4f0b2bc25060556bd
[ "MIT" ]
null
null
null
/* * vbHmmModel_GaussDiffusion.c * Model-specific functions for VB-HMM-GAUSS-DIFFUSION. * * Created by OKAMOTO Kenji, SAKO Yasushi and RIKEN * Copyright 2011-2018 * Cellular Informatics Laboratory, Advance Science Institute, RIKEN, Japan. * All rights reserved. * * Ver. 1.0.0 * Last modified on 2018.11.26 */ #include <iostream> #include <cstdlib> #include <fstream> #include <string> #include "vbHmm_GaussDiffusion.h" ////////// conditions vbHmmCond_GaussDiff::vbHmmCond_GaussDiff() : vbHmmCond() { } vbHmmCond_GaussDiff::vbHmmCond_GaussDiff(const vbHmmCond_GaussDiff &other) : vbHmmCond( other ) { // do not copy } vbHmmCond_GaussDiff::~vbHmmCond_GaussDiff() { } ////////// model vbHmmModel_GaussDiff::vbHmmModel_GaussDiff() : vbHmmModel() { avgDlt = NULL; avgLnDlt = NULL; uAArr = NULL; uBArr = NULL; aDlt = NULL; bDlt = NULL; NiR = NULL; RiR = NULL; } vbHmmModel_GaussDiff::vbHmmModel_GaussDiff(const vbHmmModel_GaussDiff &other) : vbHmmModel(other) { // do not copy avgDlt = NULL; avgLnDlt = NULL; uAArr = NULL; uBArr = NULL; aDlt = NULL; bDlt = NULL; NiR = NULL; RiR = NULL; } vbHmmModel_GaussDiff::~vbHmmModel_GaussDiff(){ delete avgDlt; delete avgLnDlt; delete uAArr; delete uBArr; delete aDlt; delete bDlt; delete NiR; delete RiR; } vbHmmModel *vbHmmModel_GaussDiff::newInstance(){ return new vbHmmModel_GaussDiff(); } void vbHmmModel_GaussDiff::setSNo( int _sNo ){ vbHmmModel::setSNo( _sNo ); avgDlt = new Vec1D( sNo ); avgLnDlt = new Vec1D( sNo ); uAArr = new Vec1D( sNo ); uBArr = new Vec1D( sNo ); aDlt = new Vec1D( sNo ); bDlt = new Vec1D( sNo ); NiR = new Vec1D( sNo ); RiR = new Vec1D( sNo ); } void vbHmmModel_GaussDiff::initialize_modelParams( vbHmmCond *c, vbHmmData *d ){ // hyper parameter for p( delta(k) ) int i; for( i = 0 ; i < sNo ; i++ ){ uAArr->p[i] = 1.0; uBArr->p[i] = 0.0005; } } double vbHmmModel_GaussDiff::pTilde_xn_zn( vbHmmTrace *_t, int n, int i ){ double val; vbHmmTrace_GaussDiff *t = (vbHmmTrace_GaussDiff*)_t; val = avgLnDlt->p[i] - log(2.0); val -= log( t->xn->p[n] ) + avgDlt->p[i] * pow( t->xn->p[n], 2.0) / 4.0; return exp(val); } void vbHmmModel_GaussDiff::calcStatsVars( vbHmmData *d ){ int i, j, r, n; double *NiRp = NiR->p, *RiRp = RiR->p, *NiiRp = NiiR->p, **NijRp = NijR->p, *z1iRp = z1iR->p; double **gmMat, ***xiMat; vbHmmTrace_GaussDiff *t; for( i = 0 ; i < sNo ; i++ ){ NiRp[i] = 1e-10; RiRp[i] = 1e-10; NiiRp[i] = 1e-10; for( j = 0 ; j < sNo ; j++ ){ NijRp[i][j] = 1e-10; } // j z1iRp[i] = 1e-10; } // i for( r = 0 ; r < R ; r++ ){ t = (vbHmmTrace_GaussDiff*)d->traces[r]; gmMat = ivs[r]->gmMat->p; xiMat = ivs[r]->xiMat->p; for( i = 0 ; i < sNo ; i++ ){ z1iRp[i] += gmMat[0][i]; for( n = 0 ; n < t->N ; n++ ){ NiRp[i] += gmMat[n][i]; RiRp[i] += gmMat[n][i] * pow( t->xn->p[n], 2.0 ); for( j = 0 ; j < sNo ; j++ ){ NiiRp[i] += xiMat[n][i][j]; NijRp[i][j] += xiMat[n][i][j]; } // j } // n } // i } // r } int vbHmmModel_GaussDiff::maximization_modelVars( int s ){ aDlt->p[s] = uAArr->p[s] + NiR->p[s]; bDlt->p[s] = uBArr->p[s] + RiR->p[s] / 4.0; avgDlt->p[s] = aDlt->p[s] / bDlt->p[s]; try{ avgLnDlt->p[s] = psi( aDlt->p[s] ) - log( bDlt->p[s] ); }catch (int status){ return status; } return 0; } double vbHmmModel_GaussDiff::varLowerBound_modelTerm( vbHmmData *d ){ int s; double lnp = 0.0; double lnq = - sNo / 2.0; for( s = 0 ; s < sNo ; s++ ){ try{ lnp += - lnGamma(uAArr->p[s]) + uAArr->p[s] * log(uBArr->p[s]); }catch (int status){ return numeric_limits<float>::quiet_NaN(); } lnp += (uAArr->p[s] - 1.0) * avgLnDlt->p[s] - uBArr->p[s] * avgDlt->p[s]; try{ lnq = - lnGamma(aDlt->p[s]) + aDlt->p[s] * log(bDlt->p[s]); }catch (int status){ return numeric_limits<float>::quiet_NaN(); } lnq += (aDlt->p[s] - 1.0) * avgLnDlt->p[s] - aDlt->p[s]; } return lnp - lnq; } void vbHmmModel_GaussDiff::reorderParameters( vbHmmData *d ){ int r, n; int i, j; Vec1I index( sNo ); Vec1D store( sNo ); Mat2D s2D( sNo, sNo ); // index indicates order of avgDlt values (0=biggest avgDlt -- sNo=smallest avgDlt). for( i = 0 ; i < sNo ; i++ ){ index.p[i] = sNo - 1; for( j = 0 ; j < sNo ; j++ ){ if( j != i ){ if( avgDlt->p[i] < avgDlt->p[j] ){ index.p[i]--; } else if( avgDlt->p[i] == avgDlt->p[j] ){ if( j > i ) { index.p[i]--; } } } } } for( i = 0 ; i < sNo ; i++ ){ store.p[index.p[i]] = avgPi->p[i]; } for( i = 0 ; i < sNo ; i++ ){ avgPi->p[i] = store.p[i]; } for( i = 0 ; i < sNo ; i++ ){ store.p[index.p[i]] = avgLnPi->p[i]; } for( i = 0 ; i < sNo ; i++ ){ avgLnPi->p[i] = store.p[i]; } for( i = 0 ; i < sNo ; i++ ){ store.p[index.p[i]] = avgDlt->p[i]; } for( i = 0 ; i < sNo ; i++ ){ avgDlt->p[i] = store.p[i]; } for( i = 0 ; i < sNo ; i++ ){ store.p[index.p[i]] = avgLnDlt->p[i]; } for( i = 0 ; i < sNo ; i++ ){ avgLnDlt->p[i] = store.p[i]; } for( j = 0 ; j < sNo ; j++ ){ for( i = 0 ; i < sNo ; i++ ){ s2D.p[index.p[i]][index.p[j]] = avgA->p[i][j]; } } for( j = 0 ; j < sNo ; j++ ){ for( i = 0 ; i < sNo ; i++ ){ avgA->p[i][j] = s2D.p[i][j]; } } for( j = 0 ; j < sNo ; j++ ){ for( i = 0 ; i < sNo ; i++ ){ s2D.p[index.p[i]][index.p[j]] = avgLnA->p[i][j]; } } for( j = 0 ; j < sNo ; j++ ){ for( i = 0 ; i < sNo ; i++ ){ avgLnA->p[i][j] = s2D.p[i][j]; } } for( i = 0 ; i < sNo ; i++ ){ store.p[index.p[i]] = NiR->p[i]; } for( i = 0 ; i < sNo ; i++ ){ NiR->p[i] = store.p[i]; } for( r = 0 ; r < R ; r++ ){ for( n = 0 ; n < ivs[r]->N ; n++ ){ for( i = 0 ; i < sNo ; i++ ){ store.p[index.p[i]] = ivs[r]->gmMat->p[n][i]; } for( i = 0 ; i < sNo ; i++ ){ ivs[r]->gmMat->p[n][i] = store.p[i]; } } } for( r = 0 ; r < R ; r++ ){ for( n = 0 ; n < ivs[r]->N ; n++ ){ for( j = 0 ; j < sNo ; j++ ){ for( i = 0 ; i < sNo ; i++ ){ s2D.p[index.p[i]][index.p[j]] = ivs[r]->xiMat->p[n][i][j]; } } for( j = 0 ; j < sNo ; j++ ){ for( i = 0 ; i < sNo ; i++ ){ ivs[r]->xiMat->p[n][i][j] = s2D.p[i][j]; } } } } } void vbHmmModel_GaussDiff::outputResults( vbHmmData *d, fstream *logFS ){ int i, j; char str[1024]; *logFS << " results: K = " << sNo << endl; *logFS << " delta: ( " << avgDlt->p[0]; for( i = 1 ; i < sNo ; i++ ){ sprintf(str, ", %g", avgDlt->p[i]); *logFS << str; } *logFS << " )" << endl; *logFS << " pi: ( " << avgPi->p[0]; for( i = 1 ; i < sNo ; i++ ){ sprintf(str, ", %g", avgPi->p[i]); *logFS << str; } *logFS << " )" << endl; *logFS << " A_matrix: ["; for( i = 0 ; i < sNo ; i++ ){ sprintf(str, " ( %g", avgA->p[i][0]); *logFS << str; for( j = 1 ; j < sNo ; j++ ){ sprintf(str, ", %g", avgA->p[i][j]); *logFS << str; } *logFS << ")"; } *logFS << " ]" << endl << endl; char fn[1024]; fstream fs; int n; sprintf( fn, "%s.param%03d", d->name.c_str(), sNo ); fs.open( fn, ios::out ); if( fs.is_open() ){ fs << "delta, pi"; for( i = 0 ; i < sNo ; i++ ){ sprintf(str, ", A%dx", i); fs << str; } fs << endl; for( i = 0 ; i < sNo ; i++ ){ sprintf(str, "%g, %g", avgDlt->p[i], avgPi->p[i]); fs << str; for( j = 0 ; j < sNo ; j++ ){ sprintf(str, ", %g", avgA->p[j][i]); fs << str; } fs << endl; } fs.close(); } sprintf( fn, "%s.Lq%03d", d->name.c_str(), sNo ); fs.open( fn, ios::out ); if( fs.is_open() ){ for( n = 0 ; n < iteration ; n++ ){ sprintf( str, "%24.20e", LqArr->p[n] ); fs << str << endl; } fs.close(); } int r; sprintf( fn, "%s.maxS%03d", d->name.c_str(), sNo ); int flag = 0; fs.open( fn, ios::out ); if( fs.is_open() ){ n = 0; do{ flag = 1; for( r = 0 ; r < R ; r++ ){ if( r > 0 ){ fs << ","; } if( n < d->traces[r]->N ){ sprintf( str, "%d", ivs[r]->stateTraj->p[n] ); fs << str; } flag &= (n >= (d->traces[r]->N - 1)); } fs << endl; n++; }while( !flag ); fs.close(); } } //
27.51312
115
0.431175
okamoto-kenji
0ceec0ab0c087f9fc39b6c4401450aa24901d4d8
16,362
cpp
C++
fkie_iop_client_global_waypoint_driver/src/urn_jaus_jss_mobility_GlobalWaypointDriverClient/GlobalWaypointDriverClient_ReceiveFSM.cpp
fkie/iop_jaus_mobility_clients
acad91e9a525ac40be64865a11c8d6b702a0a9f3
[ "BSD-3-Clause" ]
1
2018-07-29T10:13:55.000Z
2018-07-29T10:13:55.000Z
fkie_iop_client_global_waypoint_driver/src/urn_jaus_jss_mobility_GlobalWaypointDriverClient/GlobalWaypointDriverClient_ReceiveFSM.cpp
fkie/iop_jaus_mobility_clients
acad91e9a525ac40be64865a11c8d6b702a0a9f3
[ "BSD-3-Clause" ]
1
2019-11-20T14:32:31.000Z
2019-11-21T11:00:20.000Z
fkie_iop_client_global_waypoint_driver/src/urn_jaus_jss_mobility_GlobalWaypointDriverClient/GlobalWaypointDriverClient_ReceiveFSM.cpp
fkie/iop_jaus_mobility_clients
acad91e9a525ac40be64865a11c8d6b702a0a9f3
[ "BSD-3-Clause" ]
null
null
null
#include <fkie_iop_ocu_slavelib/Slave.h> #include <fkie_iop_component/iop_config.h> #include "urn_jaus_jss_mobility_GlobalWaypointDriverClient/GlobalWaypointDriverClient_ReceiveFSM.h" #include <gps_common/conversions.h> using namespace JTS; using namespace iop::ocu; namespace urn_jaus_jss_mobility_GlobalWaypointDriverClient { GlobalWaypointDriverClient_ReceiveFSM::GlobalWaypointDriverClient_ReceiveFSM(urn_jaus_jss_core_Transport::Transport_ReceiveFSM* pTransport_ReceiveFSM, urn_jaus_jss_core_EventsClient::EventsClient_ReceiveFSM* pEventsClient_ReceiveFSM, urn_jaus_jss_core_AccessControlClient::AccessControlClient_ReceiveFSM* pAccessControlClient_ReceiveFSM, urn_jaus_jss_core_ManagementClient::ManagementClient_ReceiveFSM* pManagementClient_ReceiveFSM) { /* * If there are other variables, context must be constructed last so that all * class variables are available if an EntryAction of the InitialState of the * statemachine needs them. */ context = new GlobalWaypointDriverClient_ReceiveFSMContext(*this); this->pTransport_ReceiveFSM = pTransport_ReceiveFSM; this->pEventsClient_ReceiveFSM = pEventsClient_ReceiveFSM; this->pAccessControlClient_ReceiveFSM = pAccessControlClient_ReceiveFSM; this->pManagementClient_ReceiveFSM = pManagementClient_ReceiveFSM; p_travel_speed = 1.0; p_tf_frame_world = "/world"; p_utm_zone = "32U"; p_wp_tolerance = 1.0; p_has_access = false; p_hz = 0.0; } GlobalWaypointDriverClient_ReceiveFSM::~GlobalWaypointDriverClient_ReceiveFSM() { delete context; } void GlobalWaypointDriverClient_ReceiveFSM::setupNotifications() { pManagementClient_ReceiveFSM->registerNotification("Receiving_Ready", ieHandler, "InternalStateChange_To_GlobalWaypointDriverClient_ReceiveFSM_Receiving_Ready", "ManagementClient_ReceiveFSM"); pManagementClient_ReceiveFSM->registerNotification("Receiving", ieHandler, "InternalStateChange_To_GlobalWaypointDriverClient_ReceiveFSM_Receiving_Ready", "ManagementClient_ReceiveFSM"); registerNotification("Receiving_Ready", pManagementClient_ReceiveFSM->getHandler(), "InternalStateChange_To_ManagementClient_ReceiveFSM_Receiving_Ready", "GlobalWaypointDriverClient_ReceiveFSM"); registerNotification("Receiving", pManagementClient_ReceiveFSM->getHandler(), "InternalStateChange_To_ManagementClient_ReceiveFSM_Receiving", "GlobalWaypointDriverClient_ReceiveFSM"); iop::Config cfg("~GlobalWaypointDriverClient"); cfg.param("travel_speed", p_travel_speed, p_travel_speed); cfg.param("tf_frame_world", p_tf_frame_world, p_tf_frame_world); cfg.param("utm_zone", p_utm_zone, p_utm_zone); cfg.param("waypoint_tolerance", p_wp_tolerance, p_wp_tolerance); cfg.param("hz", p_hz, p_hz, false, false); //ROS_INFO_NAMED("GlobalWaypointDriverClient", " waypoint_tolerance: %.2f", p_wp_tolerance); //create ROS subscriber // p_sub_path = cfg.subscribe<nav_msgs::Path>("cmd_path", 1, &GlobalWaypointDriverClient_ReceiveFSM::pCmdPath, this); p_sub_pose = cfg.subscribe<geometry_msgs::PoseStamped>("cmd_pose", 1, &GlobalWaypointDriverClient_ReceiveFSM::pCmdPose, this); p_sub_fix = cfg.subscribe<sensor_msgs::NavSatFix>("cmd_fix", 1, &GlobalWaypointDriverClient_ReceiveFSM::pCmdFix, this); p_sub_speed = cfg.subscribe<std_msgs::Float32>("cmd_speed", 1, &GlobalWaypointDriverClient_ReceiveFSM::pCmdSpeed, this); p_pub_path = cfg.advertise<nav_msgs::Path>("global_waypoint", 5, true); p_sub_geopose = cfg.subscribe<geographic_msgs::GeoPoseStamped>("cmd_geopose", 1, &GlobalWaypointDriverClient_ReceiveFSM::pCmdGeoPose, this); // initialize the control layer, which handles the access control staff Slave &slave = Slave::get_instance(*(jausRouter->getJausAddress())); slave.add_supported_service(*this, "urn:jaus:jss:mobility:GlobalWaypointDriver", 1, 0); } void GlobalWaypointDriverClient_ReceiveFSM::control_allowed(std::string service_uri, JausAddress component, unsigned char authority) { if (service_uri.compare("urn:jaus:jss:mobility:GlobalWaypointDriver") == 0) { p_remote_addr = component; p_has_access = true; } else { ROS_WARN_STREAM("[GlobalWaypointDriverClient] unexpected control allowed for " << service_uri << " received, ignored!"); } } void GlobalWaypointDriverClient_ReceiveFSM::enable_monitoring_only(std::string service_uri, JausAddress component) { p_remote_addr = component; } void GlobalWaypointDriverClient_ReceiveFSM::access_deactivated(std::string service_uri, JausAddress component) { p_has_access = false; p_remote_addr = JausAddress(0); } void GlobalWaypointDriverClient_ReceiveFSM::create_events(std::string service_uri, JausAddress component, bool by_query) { if (by_query) { if (p_hz > 0) { ROS_INFO_NAMED("GlobalWaypointDriverClient", "create QUERY timer to get global waypoint from %s with %.2fHz", component.str().c_str(), p_hz); p_query_timer = p_nh.createTimer(ros::Duration(1.0 / p_hz), &GlobalWaypointDriverClient_ReceiveFSM::pQueryCallback, this); } else { ROS_WARN_NAMED("GlobalWaypointDriverClient", "invalid hz %.2f for QUERY timer to get global waypoint from %s", p_hz, component.str().c_str()); } } else { ROS_INFO_NAMED("GlobalWaypointDriverClient", "create EVENT to get global waypoint from %s with %.2fHz", component.str().c_str(), p_hz); pEventsClient_ReceiveFSM->create_event(*this, component, p_query_global_waypoint_msg, p_hz); sendJausMessage(p_query_global_waypoint_msg, component); } } void GlobalWaypointDriverClient_ReceiveFSM::cancel_events(std::string service_uri, JausAddress component, bool by_query) { if (by_query) { p_query_timer.stop(); } else { ROS_INFO_NAMED("GlobalWaypointDriverClient", "cancel EVENT for global waypoint by %s", component.str().c_str()); pEventsClient_ReceiveFSM->cancel_event(*this, component, p_query_global_waypoint_msg); } } void GlobalWaypointDriverClient_ReceiveFSM::pQueryCallback(const ros::TimerEvent& event) { if (p_remote_addr.get() != 0) { sendJausMessage(p_query_global_waypoint_msg, p_remote_addr); } } void GlobalWaypointDriverClient_ReceiveFSM::event(JausAddress sender, unsigned short query_msg_id, unsigned int reportlen, const unsigned char* reportdata) { ReportGlobalWaypoint report; report.decode(reportdata); Receive::Body::ReceiveRec transport_data; transport_data.setSrcSubsystemID(sender.getSubsystemID()); transport_data.setSrcNodeID(sender.getNodeID()); transport_data.setSrcComponentID(sender.getComponentID()); handleReportGlobalWaypointAction(report, transport_data); } void GlobalWaypointDriverClient_ReceiveFSM::handleReportGlobalWaypointAction(ReportGlobalWaypoint msg, Receive::Body::ReceiveRec transportData) { JausAddress sender = transportData.getAddress(); double lat, lon, alt = 0.0; double roll, pitch, yaw = 0.0; ReportGlobalWaypoint::Body::GlobalWaypointRec *wprec = msg.getBody()->getGlobalWaypointRec(); lat = wprec->getLatitude(); lon = wprec->getLongitude(); if (wprec->isAltitudeValid()) { alt = wprec->getAltitude(); } if (wprec->isRollValid()) { roll = wprec->getRoll(); } if (wprec->isPitchValid()) { pitch = wprec->getPitch(); } if (wprec->isYawValid()) { yaw = wprec->getYaw(); } if (wprec->isWaypointToleranceValid()) { } ROS_DEBUG_NAMED("GlobalWaypointDriverClient", "globalWaypointAction from %s - lat: %.2f, lon: %.2f", sender.str().c_str(), lat, lon); ROS_DEBUG_NAMED("GlobalWaypointDriverClient", " alt: %.2f, roll: %.2f, pitch: %.2f, yaw: %.2f", alt, roll, pitch, yaw); nav_msgs::Path path; path.header.stamp = ros::Time::now(); path.header.frame_id = this->p_tf_frame_world; if (lat > -90.0 && lon > -180.0 && lat < 90.0 && lon < 180.0) { double northing, easting; std::string zone; gps_common::LLtoUTM(lat, lon, northing, easting, zone); tf::Quaternion quat = tf::createQuaternionFromRPY(roll, pitch, yaw); geometry_msgs::PoseStamped pose; pose.header = path.header; pose.pose.position.x = easting; pose.pose.position.y = northing; pose.pose.position.z = alt; pose.pose.orientation.x = quat.x(); pose.pose.orientation.y = quat.y(); pose.pose.orientation.z = quat.z(); pose.pose.orientation.w = quat.w(); path.poses.push_back(pose); } this->p_pub_path.publish(path); } void GlobalWaypointDriverClient_ReceiveFSM::handleReportTravelSpeedAction(ReportTravelSpeed msg, Receive::Body::ReceiveRec transportData) { JausAddress sender = transportData.getAddress(); p_travel_speed = msg.getBody()->getTravelSpeedRec()->getSpeed(); ROS_DEBUG_NAMED("GlobalWaypointDriverClient", "currentReportTravelSpeedAction from %s, speed: %.2f", sender.str().c_str(), p_travel_speed); } void GlobalWaypointDriverClient_ReceiveFSM::pCmdPath(const nav_msgs::Path::ConstPtr& msg) { if (p_has_access) { SetGlobalWaypoint cmd; geometry_msgs::PointStamped point_out; bool transformed = false; float speed = p_travel_speed; if (msg->poses.size() > 0) { try { geometry_msgs::PoseStamped pose_in = msg->poses[0]; if (pose_in.header.frame_id.empty()) { pose_in.header = msg->header; } tfListener.waitForTransform(p_tf_frame_world, pose_in.header.frame_id, pose_in.header.stamp, ros::Duration(0.3)); geometry_msgs::PoseStamped pose_out; tfListener.transformPose(p_tf_frame_world, pose_in, pose_out); double lat, lon = 0; gps_common::UTMtoLL(pose_out.pose.position.y, pose_out.pose.position.x, p_utm_zone.c_str(), lat, lon); cmd.getBody()->getGlobalWaypointRec()->setLatitude(lat); cmd.getBody()->getGlobalWaypointRec()->setLongitude(lon); cmd.getBody()->getGlobalWaypointRec()->setAltitude(pose_out.pose.position.z); double roll, pitch, yaw; tf::Quaternion quat(pose_out.pose.orientation.x, pose_out.pose.orientation.y, pose_out.pose.orientation.z, pose_out.pose.orientation.w); tf::Matrix3x3(quat).getRPY(roll, pitch, yaw); if (!isnan(yaw)) { cmd.getBody()->getGlobalWaypointRec()->setRoll(roll); cmd.getBody()->getGlobalWaypointRec()->setPitch(pitch); cmd.getBody()->getGlobalWaypointRec()->setYaw(yaw); } transformed = true; } catch (tf::TransformException &ex) { printf ("Failure %s\n", ex.what()); //Print exception which was caught speed = 0.0; } } else { speed = 0.0; } SetTravelSpeed cmd_speed; ROS_INFO_NAMED("GlobalWaypointDriverClient", "set speed to %.2f on %s", speed, p_remote_addr.str().c_str()); cmd_speed.getBody()->getTravelSpeedRec()->setSpeed(speed); sendJausMessage(cmd_speed, p_remote_addr); if (transformed || msg->poses.size() == 0) { ROS_INFO_NAMED("GlobalWaypointDriverClient", "send Waypoint from Path [lat: %.2f, lon: %.2f] to %s", cmd.getBody()->getGlobalWaypointRec()->getLatitude(), cmd.getBody()->getGlobalWaypointRec()->getLongitude(), p_remote_addr.str().c_str()); sendJausMessage(cmd, p_remote_addr); } } } void GlobalWaypointDriverClient_ReceiveFSM::pCmdPose(const geometry_msgs::PoseStamped::ConstPtr& msg) { if (p_has_access) { SetGlobalWaypoint cmd; geometry_msgs::PointStamped point_out; SetTravelSpeed cmd_speed; float speed = p_travel_speed; try { geometry_msgs::PoseStamped pose_in = *msg; tfListener.waitForTransform(p_tf_frame_world, pose_in.header.frame_id, pose_in.header.stamp, ros::Duration(0.3)); geometry_msgs::PoseStamped pose_out; tfListener.transformPose(p_tf_frame_world, pose_in, pose_out); double lat, lon = 0; gps_common::UTMtoLL(pose_out.pose.position.y, pose_out.pose.position.x, p_utm_zone.c_str(), lat, lon); cmd.getBody()->getGlobalWaypointRec()->setLatitude(lat); cmd.getBody()->getGlobalWaypointRec()->setLongitude(lon); cmd.getBody()->getGlobalWaypointRec()->setAltitude(pose_out.pose.position.z); double roll, pitch, yaw; tf::Quaternion quat(pose_out.pose.orientation.x, pose_out.pose.orientation.y, pose_out.pose.orientation.z, pose_out.pose.orientation.w); tf::Matrix3x3(quat).getRPY(roll, pitch, yaw); if (!isnan(yaw)) { cmd.getBody()->getGlobalWaypointRec()->setRoll(roll); cmd.getBody()->getGlobalWaypointRec()->setPitch(pitch); cmd.getBody()->getGlobalWaypointRec()->setYaw(yaw); } ROS_INFO_NAMED("GlobalWaypointDriverClient", "set speed to %.2f on %s", speed, p_remote_addr.str().c_str()); cmd_speed.getBody()->getTravelSpeedRec()->setSpeed(speed); sendJausMessage(cmd_speed, p_remote_addr); ROS_INFO_NAMED("GlobalWaypointDriverClient", "send Waypoint from Pose [lat: %.2f, lon: %.2f] to %s", cmd.getBody()->getGlobalWaypointRec()->getLatitude(), cmd.getBody()->getGlobalWaypointRec()->getLongitude(), p_remote_addr.str().c_str()); sendJausMessage(cmd, p_remote_addr); } catch (tf::TransformException &ex) { printf ("Failure %s\n", ex.what()); //Print exception which was caught speed = 0.0; ROS_INFO_NAMED("GlobalWaypointDriverClient", "set speed to %.2f on %s", speed, p_remote_addr.str().c_str()); cmd_speed.getBody()->getTravelSpeedRec()->setSpeed(speed); sendJausMessage(cmd_speed, p_remote_addr); } } } void GlobalWaypointDriverClient_ReceiveFSM::pCmdFix(const sensor_msgs::NavSatFix::ConstPtr& msg) { if (p_has_access) { SetGlobalWaypoint cmd; SetTravelSpeed cmd_speed; float speed = p_travel_speed; try { cmd.getBody()->getGlobalWaypointRec()->setLatitude(msg->latitude); cmd.getBody()->getGlobalWaypointRec()->setLongitude(msg->longitude); cmd.getBody()->getGlobalWaypointRec()->setAltitude(msg->altitude); ROS_INFO_NAMED("GlobalWaypointDriverClient", "set speed to %.2f on %s", speed, p_remote_addr.str().c_str()); cmd_speed.getBody()->getTravelSpeedRec()->setSpeed(speed); sendJausMessage(cmd_speed, p_remote_addr); ROS_INFO_NAMED("GlobalWaypointDriverClient", "send Waypoint from NavSatFix [lat: %.2f, lon: %.2f] to %s", cmd.getBody()->getGlobalWaypointRec()->getLatitude(), cmd.getBody()->getGlobalWaypointRec()->getLongitude(), p_remote_addr.str().c_str()); sendJausMessage(cmd, p_remote_addr); } catch (tf::TransformException &ex) { printf ("Failure %s\n", ex.what()); //Print exception which was caught speed = 0.0; ROS_INFO_NAMED("GlobalWaypointDriverClient", "set speed to %.2f on %s", speed, p_remote_addr.str().c_str()); cmd_speed.getBody()->getTravelSpeedRec()->setSpeed(speed); sendJausMessage(cmd_speed, p_remote_addr); } } } void GlobalWaypointDriverClient_ReceiveFSM::pCmdGeoPose(const geographic_msgs::GeoPoseStamped::ConstPtr& msg) { if (p_has_access) { SetGlobalWaypoint cmd; SetTravelSpeed cmd_speed; float speed = p_travel_speed; try { cmd.getBody()->getGlobalWaypointRec()->setLatitude(msg->pose.position.latitude); cmd.getBody()->getGlobalWaypointRec()->setLongitude(msg->pose.position.longitude); cmd.getBody()->getGlobalWaypointRec()->setAltitude(msg->pose.position.altitude); double roll, pitch, yaw; tf::Quaternion quat(msg->pose.orientation.x, msg->pose.orientation.y, msg->pose.orientation.z, msg->pose.orientation.w); tf::Matrix3x3(quat).getRPY(roll, pitch, yaw); if (!isnan(yaw)) { cmd.getBody()->getGlobalWaypointRec()->setRoll(roll); cmd.getBody()->getGlobalWaypointRec()->setPitch(pitch); cmd.getBody()->getGlobalWaypointRec()->setYaw(yaw); } ROS_INFO_NAMED("GlobalWaypointDriverClient", "set speed to %.2f on %s", speed, p_remote_addr.str().c_str()); cmd_speed.getBody()->getTravelSpeedRec()->setSpeed(speed); sendJausMessage(cmd_speed, p_remote_addr); ROS_INFO_NAMED("GlobalWaypointDriverClient", "send Waypoint from Pose [lat: %.2f, lon: %.2f] to %s", cmd.getBody()->getGlobalWaypointRec()->getLatitude(), cmd.getBody()->getGlobalWaypointRec()->getLongitude(), p_remote_addr.str().c_str()); sendJausMessage(cmd, p_remote_addr); } catch (tf::TransformException &ex) { printf ("Failure %s\n", ex.what()); //Print exception which was caught speed = 0.0; ROS_INFO_NAMED("GlobalWaypointDriverClient", "set speed to %.2f on %s", speed, p_remote_addr.str().c_str()); cmd_speed.getBody()->getTravelSpeedRec()->setSpeed(speed); sendJausMessage(cmd_speed, p_remote_addr); } } } void GlobalWaypointDriverClient_ReceiveFSM::pCmdSpeed(const std_msgs::Float32::ConstPtr& msg) { if (p_has_access) { p_travel_speed = msg->data; SetTravelSpeed cmd; ROS_DEBUG_NAMED("GlobalWaypointDriverClient", "set speed to %.2f on %s", p_travel_speed, p_remote_addr.str().c_str()); cmd.getBody()->getTravelSpeedRec()->setSpeed(p_travel_speed); sendJausMessage(cmd, p_remote_addr); } } };
44.827397
432
0.758159
fkie
0cef17fdf29ff342913dc7ee4c7eed5b7ee51f26
26,760
cc
C++
test/SudokuGridPointTest.cc
KroneckerDeIta/Sudoku
d14d501178e0744f998444b58c991be3aed296ef
[ "MIT" ]
null
null
null
test/SudokuGridPointTest.cc
KroneckerDeIta/Sudoku
d14d501178e0744f998444b58c991be3aed296ef
[ "MIT" ]
null
null
null
test/SudokuGridPointTest.cc
KroneckerDeIta/Sudoku
d14d501178e0744f998444b58c991be3aed296ef
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////////////////// /// \brief Implementation of tests for SudokuGridPoint. /// \author anon //////////////////////////////////////////////////////////////////////////////////////////////////// #include <boost/shared_ptr.hpp> #include "src/SudokuGridPoint.h" #include "SudokuGridPointTest.h" #include "utilities/src/CheckIfVectorsEqual.h" CPPUNIT_TEST_SUITE_REGISTRATION( sudoku::SudokuGridPointTest ); // Define some ordinates. const short negativeX(-1); const short negativeY(-1); const short validX(1); const short validY(2); const short tooLargeX(9); const short tooLargeY(9); // Define some values. const short zeroValue(0); const short validValue(3); const short tooLargeValue(10); namespace sudoku { //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfXNegative() { testFields_.x = negativeX; try { (void)createSubject(); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Cannot specify a negative x ordinate.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfYNegative() { testFields_.y = negativeY; try { (void)createSubject(); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Cannot specify a negative y ordinate.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfXTooLarge() { testFields_.x = tooLargeX; try { (void)createSubject(); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Cannot specify an x ordinate > 8.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfYTooLarge() { testFields_.y = tooLargeY; try { (void)createSubject(); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Cannot specify an y ordinate > 8.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfValueZero() { testFields_.value = zeroValue; try { (void)createSubject(); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Cannot specify value <= 0.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfValueTooLarge() { testFields_.value = tooLargeValue; try { (void)createSubject(); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Cannot specify a value > 9.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testGetX() { CPPUNIT_ASSERT_EQUAL( validX, subject_->getX() ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testGetY() { CPPUNIT_ASSERT_EQUAL( validY, subject_->getY() ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testGetValue() { CPPUNIT_ASSERT_EQUAL( validValue, subject_->getValue() ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfValueInPossibleValuesZero() { std::vector<short> possibleValues = {8, 9, 0}; try { (void)createSubject(possibleValues); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Cannot specify a possible value <= 0.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfValueInPossibleValuesTooLarge() { std::vector<short> possibleValues = {8, 9, 10}; try { (void)createSubject(possibleValues); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Cannot specify a possible value > 9.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfValueInPossibleValuesRepeated() { std::vector<short> possibleValues = {1, 3, 3}; try { (void)createSubject(possibleValues); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Possible values has repeated values.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testExceptionThrownIfPossibleValuesEmpty() { std::vector<short> possibleValues = {}; try { (void)createSubject(possibleValues); // Should not reach here! CPPUNIT_ASSERT(false); } catch ( std::invalid_argument &e ) { CPPUNIT_ASSERT( e.what() == std::string("Possible values cannot be empty.") ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testGetPossibleValues() { std::vector<short> possibleValues = {1, 2, 3}; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); CPPUNIT_ASSERT( std::equal(possibleValues.begin(), possibleValues.end(), s->getPossibleValues().begin() ) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRemoveValueFromPossibleValuesForSameXY() { std::vector<short> possibleValues = {1, 2, 3}; std::vector<short> possibleValuesRemoved = {1, 3}; const short testX = 1; const short testY = 2; const short testValue = 2; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // First check method returns that value could be removed, but it wasn't the last one. CPPUNIT_ASSERT_EQUAL( static_cast<short>(1), s->removePossibleValue(testX, testY, testValue) ); // Now check values. CPPUNIT_ASSERT( std::equal(possibleValuesRemoved.begin(), possibleValuesRemoved.end(), s->getPossibleValues().begin() ) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRemoveValueFromPossibleValuesFailedDueToXYNotInRowColOrBox() { std::vector<short> possibleValues = {1, 2, 3}; const short testX = 2; const short testY = 3; const short testValue = 2; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // First check method returns that value could not be removed. CPPUNIT_ASSERT_EQUAL( static_cast<short>(2), s->removePossibleValue(testX, testY, testValue) ); // Now check values to make sure nothing was removed. CPPUNIT_ASSERT( std::equal(possibleValues.begin(), possibleValues.end(), s->getPossibleValues().begin() ) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRemoveOneValueFromTwoFromPossibleValues() { std::vector<short> possibleValues = {1, 2}; std::vector<short> removedPossibleValues = {1}; const short testValue = 2; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // Test that value returned is zero. CPPUNIT_ASSERT_EQUAL( static_cast<short>(0), s->getValue() ); // First check method returns that value could be removed, but it wasn't the last possible value. CPPUNIT_ASSERT_EQUAL( static_cast<short>(1), s->removePossibleValue(testFields_.x, testFields_.y, testValue) ); // Check there is one value left in the possible values. CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(removedPossibleValues, s->getPossibleValues())); // Then check the value, it should be 0 still. CPPUNIT_ASSERT_EQUAL( static_cast<short>(0), s->getValue() ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRemoveOneValueFromOneFromPossibleValues() { std::vector<short> possibleValues = {2}; std::vector<short> emptyVector; const short testValue = 2; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // Test that value returned is zero. It has not been guessed yet. CPPUNIT_ASSERT_EQUAL( static_cast<short>(0), s->getValue() ); // First check method returns that value could be removed, and that it was the last one. CPPUNIT_ASSERT_EQUAL( static_cast<short>(0), s->removePossibleValue(testFields_.x, testFields_.y, testValue) ); // Check there is are no values left. CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(emptyVector, s->getPossibleValues())); // Then check the value, it should be a guess - 2 in our case. CPPUNIT_ASSERT_EQUAL( static_cast<short>(2), s->getValue() ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRemoveValueWhenInitialValueWasGiven() { // Give some values inside the same box. const short testX = 0; const short testY = 0; const short testValue = 2; // Check that method returns that no value was removed. CPPUNIT_ASSERT_EQUAL( static_cast<short>(2), subject_->removePossibleValue(testX, testY, testValue) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRestorePossibleValue() { std::vector<short> possibleValues = {1, 2, 3}; const short testX = 2; const short testY = 1; const short testValue = 2; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // Remove value. s->removePossibleValue(testX, testY, testValue); // Restore the value that was just removed. CPPUNIT_ASSERT( s->restorePossibleValue(testX, testY, testValue) ); std::vector<short> returnValues(s->getPossibleValues()); CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(possibleValues, returnValues) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRestorePossibleValueFailsIfXDifferentFromOneRecorded() { std::vector<short> possibleValues = {1, 2, 3}; std::vector<short> removedPossibleValues = {1, 3}; const short testX = 2; const short otherX = 3; const short testY = 1; const short testValue = 2; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // Remove value. s->removePossibleValue(testX, testY, testValue); // Test that restoring not possible as input x is different. CPPUNIT_ASSERT( ! s->restorePossibleValue(otherX, testY, testValue) ); std::vector<short> returnValues(s->getPossibleValues()); CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(removedPossibleValues, returnValues) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRestorePossibleValueFailsIfYDifferentFromOneRecorded() { std::vector<short> possibleValues = {1, 2, 3}; std::vector<short> removedPossibleValues = {1, 3}; const short testX = 2; const short testY = 1; const short otherY = 2; const short testValue = 2; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // Remove value. s->removePossibleValue(testX, testY, testValue); // Test that restoring not possible as input x is different. CPPUNIT_ASSERT( ! s->restorePossibleValue(testX, otherY, testValue) ); std::vector<short> returnValues(s->getPossibleValues()); CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(removedPossibleValues, returnValues) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRestorePossibleValueThatIsAlreadyInPossibleValues() { std::vector<short> possibleValues = {1, 2, 3}; const short testX = 2; const short testY = 1; const short testValue = 1; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // Check restoring a value that was not removed before returns false. CPPUNIT_ASSERT( ! s->restorePossibleValue(testX, testY, testValue) ); std::vector<short> returnValues(s->getPossibleValues()); CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(possibleValues, returnValues) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRestorePossibleValueWhenInitialValueWasGiven() { const short testX = 2; const short testY = 1; const short testValue = 1; CPPUNIT_ASSERT( ! subject_->restorePossibleValue(testX, testY, testValue) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRestorePossibleValueThatWasAddedToGuessedValues() { std::vector<short> possibleValues = {1, 2}; std::vector<short> removedPossibleValues = {1}; const short testX(2); const short testY(2); const short testValue1 = 1; const short testValue2 = 2; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // Remove a value that is still in the possible values. s->removePossibleValue(testX, testY, testValue1); s->removePossibleValue(testFields_.x, testFields_.y, testValue2); // Make sure 2 has been added as a guess. CPPUNIT_ASSERT_EQUAL( static_cast<short>(2), s->getValue() ); // Restore the value 1 now though. s->restorePossibleValue(testX, testY , testValue1); // Should return 0 as the value, if 1 has been restored. CPPUNIT_ASSERT_EQUAL( static_cast<short>(0), s->getValue() ); std::vector<short> returnValues(s->getPossibleValues()); CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(removedPossibleValues, returnValues) ); // Finally restore 2 as well. s->restorePossibleValue(testFields_.x, testFields_.y, testValue2); returnValues = s->getPossibleValues(); // Check we have what we originally had. CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(possibleValues, returnValues) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testGetValueWhenOneValuePassedToConstructor() { std::vector<short> possibleValues = {1}; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // Check value is set. CPPUNIT_ASSERT_EQUAL( static_cast<short>(0), s->getValue() ); // Check possible values vector is empty. CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(possibleValues, s->getPossibleValues()) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testEqualityOfTwoSudokuGridPointObjects() { boost::shared_ptr<SudokuGridPoint> sInitial(createSubject()); std::vector<short> possibleValuesOne1 = {1}; boost::shared_ptr<SudokuGridPoint> sOnePossible1(createSubject(possibleValuesOne1)); std::vector<short> possibleValuesOne2 = {2}; boost::shared_ptr<SudokuGridPoint> sOnePossible2(createSubject(possibleValuesOne2)); std::vector<short> possibleValuesTwo = {1, 2}; boost::shared_ptr<SudokuGridPoint> sTwoPossibles(createSubject(possibleValuesTwo)); CPPUNIT_ASSERT( *sInitial == *subject_ ); CPPUNIT_ASSERT( ! (*sOnePossible1 == *subject_) ); CPPUNIT_ASSERT( *sOnePossible1 == *sOnePossible2 ); CPPUNIT_ASSERT( ! (*sOnePossible1 == *sTwoPossibles) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testLessThanOfSudokuGridPointObjects() { boost::shared_ptr<SudokuGridPoint> sInitial(createSubject()); std::vector<short> possibleValuesOne1 = {1}; boost::shared_ptr<SudokuGridPoint> sOnePossible1(createSubject(possibleValuesOne1)); std::vector<short> possibleValuesOne2 = {2}; boost::shared_ptr<SudokuGridPoint> sOnePossible2(createSubject(possibleValuesOne2)); std::vector<short> possibleValuesTwo = {1, 2}; boost::shared_ptr<SudokuGridPoint> sTwoPossibles(createSubject(possibleValuesTwo)); CPPUNIT_ASSERT( ! (*sInitial < *subject_) ); CPPUNIT_ASSERT( *subject_ < *sOnePossible1 ); CPPUNIT_ASSERT( ! (*sOnePossible1 < *subject_) ); CPPUNIT_ASSERT( ! (*sOnePossible1 < *sOnePossible2) ); CPPUNIT_ASSERT( *sOnePossible1 < *sTwoPossibles ); CPPUNIT_ASSERT( ! (*sTwoPossibles < *sOnePossible1) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testNotEqualOperatorSudokuGridPointObjects() { boost::shared_ptr<SudokuGridPoint> sInitial(createSubject()); std::vector<short> possibleValuesOne1 = {1}; boost::shared_ptr<SudokuGridPoint> sOnePossible1(createSubject(possibleValuesOne1)); std::vector<short> possibleValuesOne2 = {2}; boost::shared_ptr<SudokuGridPoint> sOnePossible2(createSubject(possibleValuesOne2)); std::vector<short> possibleValuesTwo = {1, 2}; boost::shared_ptr<SudokuGridPoint> sTwoPossibles(createSubject(possibleValuesTwo)); CPPUNIT_ASSERT( ! (*sInitial != *subject_) ); CPPUNIT_ASSERT( *subject_ != *sOnePossible1 ); CPPUNIT_ASSERT( ! (*sOnePossible1 != *sOnePossible2) ); CPPUNIT_ASSERT( *sOnePossible1 != *sTwoPossibles ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testLessThanOrEqualToOperatorSudokuGridPointObjects() { boost::shared_ptr<SudokuGridPoint> sInitial(createSubject()); std::vector<short> possibleValuesOne1 = {1}; boost::shared_ptr<SudokuGridPoint> sOnePossible1(createSubject(possibleValuesOne1)); std::vector<short> possibleValuesOne2 = {2}; boost::shared_ptr<SudokuGridPoint> sOnePossible2(createSubject(possibleValuesOne2)); std::vector<short> possibleValuesTwo = {1, 2}; boost::shared_ptr<SudokuGridPoint> sTwoPossibles(createSubject(possibleValuesTwo)); CPPUNIT_ASSERT( *sInitial <= *subject_ ); CPPUNIT_ASSERT( *subject_ <= *sOnePossible1 ); CPPUNIT_ASSERT( ! (*sOnePossible1 <= *subject_) ); CPPUNIT_ASSERT( *sOnePossible1 <= *sOnePossible2 ); CPPUNIT_ASSERT( *sOnePossible1 <= *sTwoPossibles ); CPPUNIT_ASSERT( ! (*sTwoPossibles <= *sOnePossible1) ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testGreaterThanOperatorSudokuGridPointObjects() { boost::shared_ptr<SudokuGridPoint> sInitial(createSubject()); std::vector<short> possibleValuesOne1 = {1}; boost::shared_ptr<SudokuGridPoint> sOnePossible1(createSubject(possibleValuesOne1)); std::vector<short> possibleValuesOne2 = {2}; boost::shared_ptr<SudokuGridPoint> sOnePossible2(createSubject(possibleValuesOne2)); std::vector<short> possibleValuesTwo = {1, 2}; boost::shared_ptr<SudokuGridPoint> sTwoPossibles(createSubject(possibleValuesTwo)); CPPUNIT_ASSERT( ! (*sInitial > *subject_) ); CPPUNIT_ASSERT( ! (*subject_ > *sOnePossible1) ); CPPUNIT_ASSERT( *sOnePossible1 > *subject_ ); CPPUNIT_ASSERT( ! (*sOnePossible1 > *sOnePossible2) ); CPPUNIT_ASSERT( ! (*sOnePossible1 > *sTwoPossibles) ); CPPUNIT_ASSERT( *sTwoPossibles > *sOnePossible1 ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testGreaterThanOrEqualToOperatorSudokuGridPointObjects() { boost::shared_ptr<SudokuGridPoint> sInitial(createSubject()); std::vector<short> possibleValuesOne1 = {1}; boost::shared_ptr<SudokuGridPoint> sOnePossible1(createSubject(possibleValuesOne1)); std::vector<short> possibleValuesOne2 = {2}; boost::shared_ptr<SudokuGridPoint> sOnePossible2(createSubject(possibleValuesOne2)); std::vector<short> possibleValuesTwo = {1, 2}; boost::shared_ptr<SudokuGridPoint> sTwoPossibles(createSubject(possibleValuesTwo)); CPPUNIT_ASSERT( *sInitial >= *subject_ ); CPPUNIT_ASSERT( ! (*subject_ >= *sOnePossible1) ); CPPUNIT_ASSERT( *sOnePossible1 >= *subject_ ); CPPUNIT_ASSERT( *sOnePossible1 >= *sOnePossible2 ); CPPUNIT_ASSERT( ! (*sOnePossible1 >= *sTwoPossibles) ); CPPUNIT_ASSERT( *sTwoPossibles >= *sOnePossible1 ); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testGetAffectedGridPoints() { std::vector<std::pair<short, short> > myVecX1Y2 = { {1, 0}, {1, 1}, {1, 3}, {1, 4}, {1, 5}, {1, 6}, {1, 7}, {1, 8}, {0, 2}, {2, 2}, {3, 2}, {4, 2}, {5, 2}, {6, 2}, {7, 2}, {8, 2}, {0, 0}, {0, 1}, {2, 0}, {2, 1} }; testFields_.x = 1; testFields_.y = 2; boost::shared_ptr<SudokuGridPoint> subjectX1Y2(createSubject()); std::vector<std::pair<short, short> > myVecX4Y4 = { {4, 0}, {4, 1}, {4, 2}, {4, 3}, {4, 5}, {4, 6}, {4, 7}, {4, 8}, {0, 4}, {1, 4}, {2, 4}, {3, 4}, {5, 4}, {6, 4}, {7, 4}, {8, 4}, {3, 3}, {3, 5}, {5, 3}, {5, 5} }; testFields_.x = 4; testFields_.y = 4; boost::shared_ptr<SudokuGridPoint> subjectX4Y4(createSubject()); std::vector<std::pair<short, short> > myVecX6Y5 = { {6, 0}, {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 6}, {6, 7}, {6, 8}, {0, 5}, {1, 5}, {2, 5}, {3, 5}, {4, 5}, {5, 5}, {7, 5}, {8, 5}, {7, 3}, {7, 4}, {8, 3}, {8, 4} }; testFields_.x = 6; testFields_.y = 5; boost::shared_ptr<SudokuGridPoint> subjectX6Y5(createSubject()); CPPUNIT_ASSERT( (utilities::checkIfVectorsEqual<std::pair<short, short> >( subjectX1Y2->getAffectedGridPoints(), myVecX1Y2 ))); CPPUNIT_ASSERT( (utilities::checkIfVectorsEqual<std::pair<short, short> >( subjectX4Y4->getAffectedGridPoints(), myVecX4Y4 ))); CPPUNIT_ASSERT( (utilities::checkIfVectorsEqual<std::pair<short, short> >( subjectX6Y5->getAffectedGridPoints(), myVecX6Y5 ))); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testSudokuGridPointsShallowEqualsMethod() { std::vector<short> testPossibleValues1 = {1, 2}; std::vector<short> testPossibleValues2 = {1, 3}; const short testX1(5); const short testX2(6); const short testY1(6); const short testY2(7); const short testValue1(8); const short testValue2(4); testFields_.x = testX1; testFields_.y = testY1; testFields_.value = testValue1; boost::shared_ptr<SudokuGridPoint> s1(createSubject()); boost::shared_ptr<SudokuGridPoint> s2(createSubject()); boost::shared_ptr<SudokuGridPoint> s3(createSubject(testPossibleValues1)); boost::shared_ptr<SudokuGridPoint> s4(createSubject(testPossibleValues1)); boost::shared_ptr<SudokuGridPoint> s5(createSubject(testPossibleValues2)); testFields_.x = testX2; testFields_.y = testY1; testFields_.value = testValue1; boost::shared_ptr<SudokuGridPoint> s6(createSubject()); testFields_.x = testX1; testFields_.y = testY2; testFields_.value = testValue1; boost::shared_ptr<SudokuGridPoint> s7(createSubject()); testFields_.x = testX1; testFields_.y = testY1; testFields_.value = testValue2; boost::shared_ptr<SudokuGridPoint> s8(createSubject()); // Not all possible combinations. But enough for TDD. CPPUNIT_ASSERT(s1->shallowEquals(*s2)); CPPUNIT_ASSERT(s3->shallowEquals(*s4)); CPPUNIT_ASSERT(! s1->shallowEquals(*s3)); CPPUNIT_ASSERT(! s3->shallowEquals(*s5)); CPPUNIT_ASSERT(! s1->shallowEquals(*s6)); CPPUNIT_ASSERT(! s1->shallowEquals(*s7)); CPPUNIT_ASSERT(! s1->shallowEquals(*s8)); } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::testRemoveFromOnePossibleValueButNotSameGridPoint() { std::vector<short> possibleValues = {2}; // Same box as SudokuGridPoint's. const short testX(0); const short testY(0); const short testValue = 2; boost::shared_ptr<SudokuGridPoint> s = createSubject(possibleValues); // First check method returns that value could not be removed, since it was the last value and // the x and y are not the same as the SudokuGridPoint's. CPPUNIT_ASSERT_EQUAL( static_cast<short>(3), s->removePossibleValue(testX, testY, testValue) ); // Check the possible values are the same. CPPUNIT_ASSERT( utilities::checkIfVectorsEqual<short>(possibleValues, s->getPossibleValues())); // Then check the value, it should be the same, i.e. 0. CPPUNIT_ASSERT_EQUAL( static_cast<short>(0), s->getValue() ); } //////////////////////////////////////////////////////////////////////////////////////////////////// boost::shared_ptr<SudokuGridPoint> SudokuGridPointTest::createSubject() { boost::shared_ptr<SudokuGridPoint> subject(new SudokuGridPoint( testFields_.x, testFields_.y, testFields_.value )); return subject; } //////////////////////////////////////////////////////////////////////////////////////////////////// boost::shared_ptr<SudokuGridPoint> SudokuGridPointTest::createSubject( const std::vector<short>& possibleValues) { boost::shared_ptr<SudokuGridPoint> subject(new SudokuGridPoint( testFields_.x, testFields_.y, possibleValues )); return subject; } //////////////////////////////////////////////////////////////////////////////////////////////////// void SudokuGridPointTest::setUp() { testFields_.x = validX; testFields_.y = validY; testFields_.value = validValue; subject_ = createSubject(); } } // End of namespace sudoku.
35.775401
100
0.600673
KroneckerDeIta
0cf2f397849efc524d2c82873c589cc900e91101
14,286
cpp
C++
src/ui/screens/viewfilescreen.cpp
hrxcodes/cbftp
bf2784007dcc4cc42775a2d40157c51b80383f81
[ "MIT" ]
8
2019-04-30T00:37:00.000Z
2022-02-03T13:35:31.000Z
src/ui/screens/viewfilescreen.cpp
Xtravaganz/cbftp
31a3465e2cd539f6cf35a5d9a0bb9c5c2f639cd5
[ "MIT" ]
2
2019-11-19T12:46:13.000Z
2019-12-20T22:13:57.000Z
src/ui/screens/viewfilescreen.cpp
Xtravaganz/cbftp
31a3465e2cd539f6cf35a5d9a0bb9c5c2f639cd5
[ "MIT" ]
9
2020-01-15T02:38:36.000Z
2022-02-15T20:05:20.000Z
#include "viewfilescreen.h" #include "transfersscreen.h" #include "../ui.h" #include "../menuselectoption.h" #include "../resizableelement.h" #include "../menuselectadjustableline.h" #include "../menuselectoptiontextbutton.h" #include "../termint.h" #include "../misc.h" #include "../../transferstatus.h" #include "../../globalcontext.h" #include "../../sitelogicmanager.h" #include "../../sitelogic.h" #include "../../transfermanager.h" #include "../../localstorage.h" #include "../../localfilelist.h" #include "../../filelist.h" #include "../../file.h" #include "../../externalfileviewing.h" #include "../../core/types.h" class CommandOwner; namespace ViewFileState { enum { NO_SLOTS_AVAILABLE, TOO_LARGE_FOR_INTERNAL, NO_DISPLAY, CONNECTING, DOWNLOADING, LOADING_VIEWER, VIEWING_EXTERNAL, VIEWING_INTERNAL }; } namespace { enum KeyScopes { KEYSCOPE_VIEWING_INTERNAL, KEYSCOPE_VIEWING_EXTERNAL }; enum KeyAction { KEYACTION_ENCODING, KEYACTION_KILL, KEYACTION_KILL_ALL }; } ViewFileScreen::ViewFileScreen(Ui* ui) : UIWindow(ui, "ViewFileScreen") { keybinds.addScope(KEYSCOPE_VIEWING_INTERNAL, "During internal viewing"); keybinds.addScope(KEYSCOPE_VIEWING_EXTERNAL, "During external viewing"); keybinds.addBind('c', KEYACTION_BACK_CANCEL, "Return"); keybinds.addBind(KEY_UP, KEYACTION_UP, "Navigate up", KEYSCOPE_VIEWING_INTERNAL); keybinds.addBind(KEY_DOWN, KEYACTION_DOWN, "Navigate down", KEYSCOPE_VIEWING_INTERNAL); keybinds.addBind(KEY_PPAGE, KEYACTION_PREVIOUS_PAGE, "Next page", KEYSCOPE_VIEWING_INTERNAL); keybinds.addBind(KEY_NPAGE, KEYACTION_NEXT_PAGE, "Previous page", KEYSCOPE_VIEWING_INTERNAL); keybinds.addBind('e', KEYACTION_ENCODING, "Switch encoding", KEYSCOPE_VIEWING_INTERNAL); keybinds.addBind('k', KEYACTION_KILL, "Kill external viewer", KEYSCOPE_VIEWING_EXTERNAL); } ViewFileScreen::~ViewFileScreen() { } void ViewFileScreen::initialize() { rawcontents.clear(); x = 0; y = 0; ymax = 0; xmax = 0; externallyviewable = false; legendupdated = false; pid = 0; autoupdate = true; ts.reset(); } void ViewFileScreen::initialize(unsigned int row, unsigned int col, const std::string & site, const std::string & file, const std::shared_ptr<FileList>& fl) { initialize(); deleteafter = true; this->site = site; this->file = file; filelist = fl; sitelogic = global->getSiteLogicManager()->getSiteLogic(site); size = filelist->getFile(file)->getSize(); state = ViewFileState::CONNECTING; if (global->getExternalFileViewing()->isViewable(file)) { if (!global->getExternalFileViewing()->hasDisplay()) { state = ViewFileState::NO_DISPLAY; } externallyviewable = true; } else { if (size > MAXOPENSIZE) { state = ViewFileState::TOO_LARGE_FOR_INTERNAL; } } if (state == ViewFileState::CONNECTING) { requestid = sitelogic->requestOneIdle(ui); } if (state == ViewFileState::DOWNLOADING) { if (!ts) { state = ViewFileState::NO_SLOTS_AVAILABLE; } else { } } init(row, col); } void ViewFileScreen::initialize(unsigned int row, unsigned int col, const Path & dir, const std::string & file) { initialize(); deleteafter = false; path = dir / file; this->file = file; size = global->getLocalStorage()->getFileSize(path); state = ViewFileState::LOADING_VIEWER; if (global->getExternalFileViewing()->isViewable(file)) { if (!global->getExternalFileViewing()->hasDisplay()) { state = ViewFileState::NO_DISPLAY; } externallyviewable = true; } else { if (size > MAXOPENSIZE) { state = ViewFileState::TOO_LARGE_FOR_INTERNAL; } } init(row, col); } void ViewFileScreen::redraw() { ui->erase(); switch (state) { case ViewFileState::NO_SLOTS_AVAILABLE: ui->printStr(1, 1, "No download slots available at " + site + "."); break; case ViewFileState::TOO_LARGE_FOR_INTERNAL: ui->printStr(1, 1, file + " is too large to download and open in the internal viewer."); ui->printStr(2, 1, "The maximum file size for internal viewing is set to " + std::to_string(MAXOPENSIZE) + " bytes."); break; case ViewFileState::NO_DISPLAY: ui->printStr(1, 1, file + " cannot be opened in an external viewer."); ui->printStr(2, 1, "The DISPLAY environment variable is not set."); break; case ViewFileState::CONNECTING: if (sitelogic->requestReady(requestid)) { sitelogic->finishRequest(requestid); const Path & temppath = global->getLocalStorage()->getTempPath(); std::shared_ptr<LocalFileList> localfl = global->getLocalStorage()->getLocalFileList(temppath); ts = global->getTransferManager()->suggestDownload(file, sitelogic, filelist, localfl); if (!!ts) { state = ViewFileState::DOWNLOADING; ts->setAwaited(true); path = temppath / file; expectbackendpush = true; } else { state = ViewFileState::NO_SLOTS_AVAILABLE; redraw(); } } else { ui->printStr(1, 1, "Awaiting slot..."); } break; case ViewFileState::DOWNLOADING: switch(ts->getState()) { case TRANSFERSTATUS_STATE_IN_PROGRESS: ui->printStr(1, 1, "Downloading from " + site + "..."); printTransferInfo(); break; case TRANSFERSTATUS_STATE_FAILED: ui->printStr(1, 1, "Download of " + file + " from " + site + " failed."); autoupdate = false; break; case TRANSFERSTATUS_STATE_SUCCESSFUL: loadViewer(); break; } break; case ViewFileState::LOADING_VIEWER: loadViewer(); break; case ViewFileState::VIEWING_EXTERNAL: viewExternal(); break; case ViewFileState::VIEWING_INTERNAL: viewInternal(); break; } } void ViewFileScreen::update() { if (pid) { if (!global->getExternalFileViewing()->stillViewing(pid)) { ui->returnToLast(); } else if (!legendupdated) { legendupdated = true; ui->update(); ui->setLegend(); } } else { redraw(); if ((state == ViewFileState::VIEWING_INTERNAL || state == ViewFileState::VIEWING_EXTERNAL) && !legendupdated) { legendupdated = true; ui->update(); ui->setLegend(); } } } bool ViewFileScreen::keyPressed(unsigned int ch) { int scope = getCurrentScope(); int action = keybinds.getKeyAction(ch, scope); switch(action) { case KEYACTION_BACK_CANCEL: ui->returnToLast(); return true; case KEYACTION_DOWN: if (goDown()) { goDown(); ui->setInfo(); ui->redraw(); } return true; case KEYACTION_UP: if (goUp()) { goUp(); ui->setInfo(); ui->redraw(); } return true; case KEYACTION_NEXT_PAGE: for (unsigned int i = 0; i < row / 2; i++) { goDown(); } ui->setInfo(); ui->redraw(); return true; case KEYACTION_PREVIOUS_PAGE: for (unsigned int i = 0; i < row / 2; i++) { goUp(); } ui->setInfo(); ui->redraw(); return true; case KEYACTION_KILL: if (pid) { global->getExternalFileViewing()->killProcess(pid); } return true; case KEYACTION_ENCODING: if (state == ViewFileState::VIEWING_INTERNAL) { if (encoding == encoding::ENCODING_CP437) { encoding = encoding::ENCODING_CP437_DOUBLE; } else if (encoding == encoding::ENCODING_CP437_DOUBLE) { encoding = encoding::ENCODING_ISO88591; } else if (encoding == encoding::ENCODING_ISO88591) { encoding = encoding::ENCODING_UTF8; } else { encoding = encoding::ENCODING_CP437; } translate(); ui->redraw(); ui->setInfo(); } return true; } return false; } void ViewFileScreen::loadViewer() { if (externallyviewable) { if (!pid) { if (deleteafter) { pid = global->getExternalFileViewing()->viewThenDelete(path); } else { pid = global->getExternalFileViewing()->view(path); } } state = ViewFileState::VIEWING_EXTERNAL; viewExternal(); } else { Core::BinaryData tmpdata = global->getLocalStorage()->getFileContent(path); if (deleteafter) { global->getLocalStorage()->requestDelete(path); } std::string extension = File::getExtension(file); encoding = encoding::guessEncoding(tmpdata); unsigned int tmpdatalen = tmpdata.size(); if (tmpdatalen > 0) { std::string current; for (unsigned int i = 0; i < tmpdatalen; i++) { if (tmpdata[i] == '\n') { rawcontents.push_back(current); current.clear(); } else { current += tmpdata[i]; } } if (current.length() > 0) { rawcontents.push_back(current); } translate(); } autoupdate = false; state = ViewFileState::VIEWING_INTERNAL; viewInternal(); } } void ViewFileScreen::viewExternal() { ui->printStr(1, 1, "Opening " + file + " with: " + global->getExternalFileViewing()->getViewApplication(file)); ui->printStr(3, 1, "Press 'k' to kill this external viewer instance."); ui->printStr(4, 1, "You can always press 'K' to kill ALL external viewers."); } void ViewFileScreen::viewInternal() { if (ymax <= row) { y = 0; } while (ymax > row && y + row > ymax) { --y; } ymax = rawcontents.size(); for (unsigned int i = 0; i < ymax; i++) { if (translatedcontents[i].length() > xmax) { xmax = translatedcontents[i].length(); } } for (unsigned int i = 0; i < row && i < ymax; i++) { std::basic_string<unsigned int> & line = translatedcontents[y + i]; for (unsigned int j = 0; j < line.length() && j < col - 2; j++) { ui->printChar(i, j + 1, line[j]); } } printSlider(ui, row, col - 1, ymax, y); } std::string ViewFileScreen::getLegendText() const { return keybinds.getLegendSummary(getCurrentScope()); } std::string ViewFileScreen::getInfoLabel() const { return "VIEW FILE: " + file; } std::string ViewFileScreen::getInfoText() const { if (state == ViewFileState::VIEWING_INTERNAL) { std::string enc; switch (encoding) { case encoding::ENCODING_CP437: enc = "CP437"; break; case encoding::ENCODING_CP437_DOUBLE: enc = "Double CP437"; break; case encoding::ENCODING_ISO88591: enc = "ISO-8859-1"; break; case encoding::ENCODING_UTF8: enc = "UTF-8"; break; } unsigned int end = ymax < y + row ? ymax : y + row; return "Line " + std::to_string(y) + "-" + std::to_string(end) + "/" + std::to_string(ymax) + " Encoding: " + enc; } else { return ""; } } void ViewFileScreen::translate() { translatedcontents.clear(); for (unsigned int i = 0; i < rawcontents.size(); i++) { std::basic_string<unsigned int> current; if (encoding == encoding::ENCODING_CP437_DOUBLE) { current = encoding::doublecp437toUnicode(rawcontents[i]); } else if (encoding == encoding::ENCODING_CP437) { current = encoding::cp437toUnicode(rawcontents[i]); } else if (encoding == encoding::ENCODING_ISO88591) { current = encoding::toUnicode(rawcontents[i]); } else { current = encoding::utf8toUnicode(rawcontents[i]); } translatedcontents.push_back(current); } } bool ViewFileScreen::goDown() { if (y + row < ymax) { y++; return true; } return false; } bool ViewFileScreen::goUp() { if (y > 0) { y--; return true; } return false; } void ViewFileScreen::printTransferInfo() { TransferDetails td = TransfersScreen::formatTransferDetails(ts); unsigned int y = 3; MenuSelectOption table; std::shared_ptr<MenuSelectAdjustableLine> msal = table.addAdjustableLine(); std::shared_ptr<MenuSelectOptionTextButton> msotb; msotb = table.addTextButtonNoContent(y, 1, "transferred", "TRANSFERRED"); msal->addElement(msotb, 4, RESIZE_CUTEND); msotb = table.addTextButtonNoContent(y, 3, "filename", "FILENAME"); msal->addElement(msotb, 2, RESIZE_CUTEND); msotb = table.addTextButtonNoContent(y, 6, "remaining", "LEFT"); msal->addElement(msotb, 5, RESIZE_REMOVE); msotb = table.addTextButtonNoContent(y, 7, "speed", "SPEED"); msal->addElement(msotb, 6, RESIZE_REMOVE); msotb = table.addTextButtonNoContent(y, 8, "progress", "DONE"); msal->addElement(msotb, 7, RESIZE_REMOVE); y++; msal = table.addAdjustableLine(); msotb = table.addTextButtonNoContent(y, 1, "transferred", td.transferred); msal->addElement(msotb, 4, RESIZE_CUTEND); msotb = table.addTextButtonNoContent(y, 10, "filename", ts->getFile()); msal->addElement(msotb, 2, RESIZE_WITHLAST3); msotb = table.addTextButtonNoContent(y, 60, "remaining", td.timeremaining); msal->addElement(msotb, 5, RESIZE_REMOVE); msotb = table.addTextButtonNoContent(y, 40, "speed", td.speed); msal->addElement(msotb, 6, RESIZE_REMOVE); msotb = table.addTextButtonNoContent(y, 50, "progress", td.progress); msal->addElement(msotb, 7, RESIZE_REMOVE); table.adjustLines(col - 3); for (unsigned int i = 0; i < table.size(); i++) { std::shared_ptr<ResizableElement> re = std::static_pointer_cast<ResizableElement>(table.getElement(i)); if (re->isVisible()) { if (re->getIdentifier() == "transferred") { std::string labeltext = re->getLabelText(); bool highlight = table.getLineIndex(table.getAdjustableLine(re)) == 1; int charswithhighlight = highlight ? labeltext.length() * ts->getProgress() / 100 : 0; ui->printStr(re->getRow(), re->getCol(), labeltext.substr(0, charswithhighlight), true); ui->printStr(re->getRow(), re->getCol() + charswithhighlight, labeltext.substr(charswithhighlight)); } else { ui->printStr(re->getRow(), re->getCol(), re->getLabelText()); } } } } int ViewFileScreen::getCurrentScope() const { if (state == ViewFileState::VIEWING_EXTERNAL) { return KEYSCOPE_VIEWING_EXTERNAL; } if (state == ViewFileState::VIEWING_INTERNAL) { return KEYSCOPE_VIEWING_INTERNAL; } return KEYSCOPE_ALL; }
29.395062
158
0.635167
hrxcodes
0cf47a1d8c1d0f3b8941f22a174d4530afc93b7d
1,063
hpp
C++
alignment/files/ReaderAgglomerateImpl.hpp
ggraham/blasr_libcpp
4abef36585bbb677ebc4acb9d4e44e82331d59f7
[ "RSA-MD" ]
4
2015-07-03T11:59:54.000Z
2018-05-17T00:03:22.000Z
alignment/files/ReaderAgglomerateImpl.hpp
ggraham/blasr_libcpp
4abef36585bbb677ebc4acb9d4e44e82331d59f7
[ "RSA-MD" ]
79
2015-06-29T18:07:21.000Z
2018-09-19T13:38:39.000Z
alignment/files/ReaderAgglomerateImpl.hpp
ggraham/blasr_libcpp
4abef36585bbb677ebc4acb9d4e44e82331d59f7
[ "RSA-MD" ]
19
2015-06-23T08:43:29.000Z
2021-04-28T18:37:47.000Z
#ifndef _BLASR_READER_AGGLOMERATE_IMPL_HPP_ #define _BLASR_READER_AGGLOMERATE_IMPL_HPP_ template <typename T_Sequence> int ReaderAgglomerate::GetNext(T_Sequence &seq, int &randNum) { randNum = rand(); return GetNext(seq); } template <typename T_Sequence> int ReadChunkByNReads(ReaderAgglomerate &reader, std::vector<T_Sequence> &reads, int maxNReads) { T_Sequence seq; int nReads = 0; while (nReads < maxNReads) { if (reader.GetNext(seq)) { reads.push_back(seq); ++nReads; } else { break; } } return nReads; } template <typename T_Sequence> int ReadChunkBySize(ReaderAgglomerate &reader, std::vector<T_Sequence> &reads, int maxMemorySize) { T_Sequence seq; int nReads = 0; int totalStorage = 0; while (totalStorage < maxMemorySize) { if (reader.GetNext(seq)) { reads.push_back(seq); totalStorage += seq.GetStorageSize(); nReads++; } else { break; } } return nReads; } #endif
23.108696
97
0.627469
ggraham
0cf54ce58b46f3ba5654eef039f7fb86939d2e7e
375
cpp
C++
GameEngine/CoreEngine/CoreEngine/src/DrawSceneOperation.cpp
mettaursp/SuddenlyGames
e2ff1c2771d4ca54824650e4f1a33a527536ca61
[ "Apache-2.0" ]
1
2021-01-17T13:05:20.000Z
2021-01-17T13:05:20.000Z
GameEngine/CoreEngine/CoreEngine/src/DrawSceneOperation.cpp
suddenly-games/SuddenlyGames
e2ff1c2771d4ca54824650e4f1a33a527536ca61
[ "Apache-2.0" ]
null
null
null
GameEngine/CoreEngine/CoreEngine/src/DrawSceneOperation.cpp
suddenly-games/SuddenlyGames
e2ff1c2771d4ca54824650e4f1a33a527536ca61
[ "Apache-2.0" ]
null
null
null
#include "DrawSceneOperation.h" #include "Graphics.h" namespace GraphicsEngine { void DrawSceneOperation::Configure(const std::shared_ptr<Scene>& scene) { CurrentScene = scene; } void DrawSceneOperation::Render() { Graphics::SetClearColor(RGBA(0x000000FF)); Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); CurrentScene.lock()->Draw(); } }
18.75
72
0.749333
mettaursp
0cf5ce639d384338dff908e988df159507695c82
1,062
cc
C++
src/MsPhy.cc
CN-UPB/koi-simulator
ca4ddc5019f423a8e901ebed25b44dc5fa165cf0
[ "Apache-2.0" ]
null
null
null
src/MsPhy.cc
CN-UPB/koi-simulator
ca4ddc5019f423a8e901ebed25b44dc5fa165cf0
[ "Apache-2.0" ]
null
null
null
src/MsPhy.cc
CN-UPB/koi-simulator
ca4ddc5019f423a8e901ebed25b44dc5fa165cf0
[ "Apache-2.0" ]
null
null
null
/* * MsPhy.cc * * Created on: Jul 1, 2013 * Author: Sascha Schmerling */ #include "MsPhy.h" #include "KoiData_m.h" #include "MessageTypes.h" Define_Module(MsPhy); void MsPhy::initialize() { } void MsPhy::handleMessage(omnetpp::cMessage *msg) { //currently it only forward the packets if(msg->arrivedOn("fromMac")) { switch(msg->getKind()){ case MessageType::transInfo: send(msg,"toMsChannel"); break; case MessageType::koidata:{ KoiData *packet = dynamic_cast<KoiData*>(msg); switch(packet->getMessageDirection()){ case MessageDirection::up: send(msg, "toChannel"); break; case MessageDirection::d2dDown: case MessageDirection::d2dUp: send(msg,"toMs",packet->getDest()); break; } } break; case MessageType::longTermSinrEst: send(msg,"toMsChannel"); break; } if(msg->isName("MCS_FILE")){ send(msg,"toMsChannel"); } } else if(msg->arrivedOn("fromChannel")) { //ev << "Forwarding packet/packets to the mac layer" << endl; send(msg, "toMac"); } }
21.673469
63
0.63936
CN-UPB
0cf7d3785efe69b943c01dc937f7f1bc78493d04
625
cpp
C++
Framework/Sources/o2/Utils/Memory/Allocators/StackAllocator.cpp
zenkovich/o2
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
[ "MIT" ]
181
2015-12-09T08:53:36.000Z
2022-03-26T20:48:39.000Z
Framework/Sources/o2/Utils/Memory/Allocators/StackAllocator.cpp
zenkovich/o2
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
[ "MIT" ]
29
2016-04-22T08:24:04.000Z
2022-03-06T07:06:28.000Z
Framework/Sources/o2/Utils/Memory/Allocators/StackAllocator.cpp
zenkovich/o2
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
[ "MIT" ]
13
2018-04-24T17:12:04.000Z
2021-11-12T23:49:53.000Z
#include "o2/stdafx.h" #include "StackAllocator.h" namespace o2 { StackAllocator::StackAllocator(size_t capacity, IAllocator* baseAllocator /*= DefaultAllocator::GetInstance()*/): mBaseAllocator(baseAllocator) { mInitialCapacity = capacity; Initialize(); } StackAllocator::~StackAllocator() { Clear(); } void StackAllocator::Clear() { mBaseAllocator->Deallocate(mStack); mStack = nullptr; mStackEnd = nullptr; mTop = nullptr; } void StackAllocator::Initialize() { mStack = (std::byte*)mBaseAllocator->Allocate(mInitialCapacity); mTop = mStack; mStackEnd = mStack + mInitialCapacity; } }
18.939394
114
0.7168
zenkovich
0cf8c2b80d2677099864c77f7693963551133504
11,450
cpp
C++
back-end/llvm-translator/llvm-translator-qemu-2.3/tcg-llvm-offline/tcg-llvm-offline.cpp
zheli-1/crete-dev
a226c245f51347b88ba9a95448a694bf1997a080
[ "BSD-2-Clause-FreeBSD" ]
52
2016-11-03T06:48:16.000Z
2021-03-30T07:22:41.000Z
back-end/llvm-translator/llvm-translator-qemu-2.3/tcg-llvm-offline/tcg-llvm-offline.cpp
zheli-1/crete-dev
a226c245f51347b88ba9a95448a694bf1997a080
[ "BSD-2-Clause-FreeBSD" ]
46
2016-11-16T02:07:38.000Z
2020-04-01T06:17:33.000Z
back-end/llvm-translator/llvm-translator-qemu-2.3/tcg-llvm-offline/tcg-llvm-offline.cpp
zheli-1/crete-dev
a226c245f51347b88ba9a95448a694bf1997a080
[ "BSD-2-Clause-FreeBSD" ]
13
2016-11-06T00:41:27.000Z
2020-06-01T07:18:48.000Z
#include "tcg-llvm-offline.h" #include <boost/archive/binary_iarchive.hpp> #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <string> #include <stdlib.h> #include <iostream> #include <fstream> #include "tcg.h" #if defined(TCG_LLVM_OFFLINE) #include "tcg-llvm.h" #endif // defined(TCG_LLVM_OFFLINE) using namespace std; extern "C" { #if !defined(TCG_LLVM_OFFLINE) struct TCGHelperInfo; extern const TCGHelperInfo all_helpers[]; extern TCGOpDef tcg_op_defs[]; uint64_t helpers_size = 0; uint64_t opc_defs_size = 0; #endif // !defined(TCG_LLVM_OFFLINE) } #if !defined(TCG_LLVM_OFFLINE) void TCGLLVMOfflineContext::dump_tlo_tb_pc(const uint64_t pc) { m_tlo_tb_pc.push_back(pc); } void TCGLLVMOfflineContext::dump_tcg_ctx(const TCGContext& tcg_ctx) { m_tcg_ctx.push_back(tcg_ctx); } void TCGLLVMOfflineContext::dump_tcg_temp(const vector<TCGTemp>& tcg_temp) { m_tcg_temps.push_back(tcg_temp); } void TCGLLVMOfflineContext::dump_tcg_helper_name(const TCGContext &tcg_ctx) { for (uint64_t i = 0; i < helpers_size; ++i) { uint64_t helper_addr = (uint64_t)all_helpers[i].func; string helper_name(all_helpers[i].name); assert(helper_addr); assert(!helper_name.empty()); m_helper_names.insert(make_pair(helper_addr, helper_name)); } } void TCGLLVMOfflineContext::dump_tlo_tb_inst_count(const uint64_t inst_count) { m_tlo_tb_inst_count.push_back(inst_count); } void TCGLLVMOfflineContext::dump_tbExecSequ(uint64_t pc, uint64_t unique_tb_num) { m_tbExecSequ.push_back(make_pair(pc, unique_tb_num)); } void TCGLLVMOfflineContext::dump_cpuState_size(uint64_t cpuState_size) { m_cpuState_size = cpuState_size; } #endif // #if !defined(TCG_LLVM_OFFLINE) uint64_t TCGLLVMOfflineContext::get_tlo_tb_pc(const uint64_t tb_index) const { return m_tlo_tb_pc[tb_index]; } const TCGContext& TCGLLVMOfflineContext::get_tcg_ctx(const uint64_t tb_index) const { return m_tcg_ctx[tb_index]; } const vector<TCGTemp>& TCGLLVMOfflineContext::get_tcg_temp(const uint64_t tb_index) const { return m_tcg_temps[tb_index]; } const map<uint64_t, string> TCGLLVMOfflineContext::get_helper_names() const { return m_helper_names; } uint64_t TCGLLVMOfflineContext::get_tlo_tb_inst_count(const uint64_t tb_index) const { return m_tlo_tb_inst_count[tb_index]; } vector<pair<uint64_t, uint64_t> > TCGLLVMOfflineContext::get_tbExecSequ() const { return m_tbExecSequ; } uint64_t TCGLLVMOfflineContext::get_cpuState_size() const { return m_cpuState_size; } void TCGLLVMOfflineContext::print_info() { cout << dec << "m_tlo_tb_pc.size() = " << m_tlo_tb_pc.size() << endl << "m_helper_names.size() = " << m_helper_names.size() << endl << endl; cout << dec << "sizeof (m_tlo_tb_pc) = " << sizeof(m_tlo_tb_pc)<< endl << "sizeof(m_helper_names) = " << sizeof(m_tcg_ctx) << "sizeof(m_tcg_temps) = " << sizeof(m_tcg_temps) << "sizeof(m_helper_names) = " << sizeof(m_helper_names) << endl << endl; cout << "pc values: "; uint64_t j = 0; for(vector<uint64_t>::iterator it = m_tlo_tb_pc.begin(); it != m_tlo_tb_pc.end(); ++it) { cout << "tb-" << dec << j++ << ": pc = 0x" << hex << (*it) << endl; } } void TCGLLVMOfflineContext::dump_verify() { assert(m_tlo_tb_pc.size() == m_tcg_ctx.size()); assert(m_tlo_tb_pc.size() == m_tcg_temps.size()); } uint64_t TCGLLVMOfflineContext::get_size() { return (uint64_t)m_tlo_tb_pc.size(); } #if defined(TCG_LLVM_OFFLINE) extern "C" { #include "config.h" #include "exec-all.h" } #include <boost/exception/all.hpp> #include <boost/filesystem.hpp> #include <sstream> #include <stdio.h> #define CRETE_DEBUG FILE *logfile; int loglevel; TCGContext tcg_ctx; uint16_t gen_opc_buf[OPC_BUF_SIZE]; TCGArg gen_opparam_buf[OPPARAM_BUF_SIZE]; target_ulong gen_opc_pc[OPC_BUF_SIZE]; uint16_t gen_opc_icount[OPC_BUF_SIZE]; uint8_t gen_opc_instr_start[OPC_BUF_SIZE]; std::string crete_data_dir; enum CreteFileType { CRETE_FILE_TYPE_LLVM_LIB, CRETE_FILE_TYPE_LLVM_TEMPLATE, }; static void crete_set_data_dir(const char* data_dir) { namespace fs = boost::filesystem; fs::path dpath(data_dir); if(!fs::exists(dpath)) { throw std::runtime_error("failed to find data directory: " + dpath.string()); } crete_data_dir = dpath.parent_path().string(); // crete_data_dir = "."; } static std::string crete_find_file(CreteFileType type, const char *name) { namespace fs = boost::filesystem; fs::path fpath = crete_data_dir; switch(type) { case CRETE_FILE_TYPE_LLVM_LIB: //#if defined(TARGET_X86_64) // fpath /= "../x86_64-softmmu/"; //#else // fpath /= "../i386-softmmu/"; //#endif // defined(TARGET_X86_64) break; case CRETE_FILE_TYPE_LLVM_TEMPLATE: // fpath /= "../runtime-dump/"; break; } fpath /= name; if(!fs::exists(fpath)) { throw std::runtime_error("failed to find file: " + fpath.string()); } return fpath.string(); } static void dump_tcg_op_defs() { char file_name[] = "translator-op-def.txt"; FILE *f = fopen(file_name, "w"); assert(f); for(uint32_t i = 0; i < tcg_op_defs_max; ++i) { fprintf(f, "opc = %d, name = %s\n", i, tcg_op_defs[i].name); } fclose(f); } const char * get_helper_name(uint64_t func_addr) { assert(tcg_llvm_ctx); string func_name = tcg_llvm_ctx->get_crete_helper_name(func_addr); char * ret = (char *) malloc(func_name.length() + 1); strcpy(ret, func_name.c_str()); cerr << "func_name = " << ret << ", func_addr = 0x" << hex << func_addr << ", ret = 0x" << (uint64_t) ret << endl; return ret; } void x86_llvm_translator() { namespace fs = boost::filesystem; #if defined(CRETE_DEBUG) cerr<< "this is the new main function from tcg-llvm-offline.\n" << endl; cerr<< "sizeof(TCGContext_temp) = 0x" << hex << sizeof(TCGContext_temp) << "sizeof(TCGArg) = 0x" << sizeof(TCGArg) << endl << ", OPPARAM_BUF_SIZE = 0x" << OPPARAM_BUF_SIZE << ", OPC_BUF_SIZE = 0x" << OPC_BUF_SIZE << ", MAX_OPC_PARAM = 0x" << MAX_OPC_PARAM << endl; dump_tcg_op_defs(); #endif //1. initialize llvm dependencies tcg_llvm_ctx = tcg_llvm_initialize(); assert(tcg_llvm_ctx); tcg_linkWithLibrary(tcg_llvm_ctx, crete_find_file(CRETE_FILE_TYPE_LLVM_LIB, "bc_crete_ops.bc").c_str()); #if defined(TARGET_X86_64) tcg_linkWithLibrary(tcg_llvm_ctx, crete_find_file(CRETE_FILE_TYPE_LLVM_LIB, "crete-qemu-2.3-op-helper-x86_64.bc").c_str()); #elif defined(TARGET_I386) tcg_linkWithLibrary(tcg_llvm_ctx, crete_find_file(CRETE_FILE_TYPE_LLVM_LIB, "crete-qemu-2.3-op-helper-i386.bc").c_str()); #else #error CRETE: Only I386 and x64 supported! #endif // defined(TARGET_X86_64) || defined(TARGET_I386) stringstream ss; uint64_t streamed_count = 0; for(;;) { ss.str(string()); ss << "dump_tcg_llvm_offline." << streamed_count++ << ".bin"; if(!fs::exists(ss.str())){ cerr << ss.str() << " not found\n"; break; } cerr << ss.str() << " being found\n"; //2. initialize tcg_llvm_ctx_offline TCGLLVMOfflineContext temp_tcg_llvm_offline_ctx; ifstream ifs(ss.str().c_str()); boost::archive::binary_iarchive ia(ifs); ia >> temp_tcg_llvm_offline_ctx; temp_tcg_llvm_offline_ctx.dump_verify(); #if defined(CRETE_DEBUG) temp_tcg_llvm_offline_ctx.print_info(); #endif if(streamed_count == 1){ tcg_llvm_ctx->crete_init_helper_names(temp_tcg_llvm_offline_ctx.get_helper_names()); tcg_llvm_ctx->crete_set_cpuState_size(temp_tcg_llvm_offline_ctx.get_cpuState_size()); } tcg_llvm_ctx->crete_add_tbExecSequ(temp_tcg_llvm_offline_ctx.get_tbExecSequ()); //3. Translate TranslationBlock temp_tb = {}; TCGContext *s = &tcg_ctx; for(uint64_t i = 0; i < temp_tcg_llvm_offline_ctx.get_size(); ++i) { //3.1 update temp_tb temp_tb.pc = (target_long)temp_tcg_llvm_offline_ctx.get_tlo_tb_pc(i); //3.2 update tcg_ctx const TCGContext temp_tcg_ctx = temp_tcg_llvm_offline_ctx.get_tcg_ctx(i); memcpy((void *)s, (void *)&temp_tcg_ctx, sizeof(TCGContext)); //3.3 update gen_opc_buf and gen_opparam_buf for(uint64_t j = 0; j < OPC_BUF_SIZE; ++j) { gen_opc_buf[j] = (uint16_t)temp_tcg_ctx.gen_op_buf[j].opc; } for(uint64_t j = 0; j < OPPARAM_BUF_SIZE; ++j) { gen_opparam_buf[j] = (TCGArg)temp_tcg_ctx.gen_opparam_buf[j]; } // 3.4 update tcg-temp const vector<TCGTemp> temp_tcg_temp = temp_tcg_llvm_offline_ctx.get_tcg_temp(i); assert( temp_tcg_temp.size() == s->nb_temps); for(uint64_t j = 0; j < s->nb_temps; ++j) s->temps[j].assign(temp_tcg_temp[j]); // generate offline-tbir.txt uint64_t tb_inst_count = temp_tcg_llvm_offline_ctx.get_tlo_tb_inst_count(i); static unsigned long long tbir_count = 0; char file_name[] = "offline-tbir.txt"; FILE *f = fopen(file_name, "a"); assert(f); fprintf(f, "qemu-ir-tb-%llu-%llu: tb_inst_count = %llu\n", tbir_count++, temp_tb.pc, tb_inst_count); tcg_dump_ops_file(s, f); fprintf(f, "\n"); fclose(f); //3.5 generate llvm bitcode cerr << "tcg_llvm_ctx->generateCode(s, &temp_tb) will be invoked." << endl; temp_tb.tcg_llvm_context = NULL; temp_tb.llvm_function = NULL; tcg_llvm_ctx->generateCode(s, &temp_tb); cerr<< "tcg_llvm_ctx->generateCode(s, &temp_tb) is done." << endl; assert(temp_tb.tcg_llvm_context != NULL); assert(temp_tb.llvm_function != NULL); } { //process crete_CPUStateSynctable(); ss.str(string()); ss << "dump_sync_cpu_states." << streamed_count-1 << ".bin"; tcg_llvm_ctx->generate_llvm_cpuStateSyncTables(ss.str()); } { //process dump_new_sync_memos(); ss.str(string()); ss << "dump_new_sync_memos." << streamed_count-1 << ".bin"; tcg_llvm_ctx->generate_llvm_MemorySyncTables(ss.str()); } } //4. generate main function tcg_llvm_ctx->generate_crete_main(); //5. Write out the translated llvm bitcode to file in the current folder fs::path bitcode_path = fs::current_path() / "dump_llvm_offline.bc"; tcg_llvm_ctx->writeBitCodeToFile(bitcode_path.string()); cerr << "offline translator is done.\n" << endl; //6. cleanup // delete tcg_llvm_offline_ctx; } int main(int argc, char **argv) { crete_set_data_dir(argv[0]); try { x86_llvm_translator(); } catch(...) { cerr << "Exception Info: \n" << boost::current_exception_diagnostic_information() << endl; return -1; } return 0; } #endif // defined(TCG_LLVM_OFFLINE)
27.261905
101
0.645764
zheli-1
0cfbaf0a959029b4d8b6049e04f2cde0db0e6df7
9,803
cpp
C++
C++GP16/final/client/Client.cpp
dhanak/competitive-coding
9e28298f8c646f169b7389d0ef20f99c5ef68f00
[ "MIT" ]
null
null
null
C++GP16/final/client/Client.cpp
dhanak/competitive-coding
9e28298f8c646f169b7389d0ef20f99c5ef68f00
[ "MIT" ]
null
null
null
C++GP16/final/client/Client.cpp
dhanak/competitive-coding
9e28298f8c646f169b7389d0ef20f99c5ef68f00
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Client.h" #include <sstream> #define SERVER_PORT 4242 CLIENT::CLIENT() { #ifdef WIN32 mConnectionSocket = INVALID_SOCKET; #else mConnectionSocket = -1; #endif mDistCache.LoadFromFile("distcache.bin"); } CLIENT::~CLIENT() { #ifdef WIN32 if( mConnectionSocket != INVALID_SOCKET ) { closesocket( mConnectionSocket ); } WSACleanup(); #else if (mConnectionSocket!=-1) { close(mConnectionSocket); } #endif } bool CLIENT::LinkDead() { #ifdef WIN32 return mConnectionSocket==INVALID_SOCKET; #else return mConnectionSocket == -1; #endif } bool CLIENT::Init() { #ifdef WIN32 static int wsa_startup_done = 0; if (!wsa_startup_done) { wsa_startup_done = 1; WSADATA WSAData; if( WSAStartup( 0x101,&WSAData ) != 0 ) { std::cout << "Error: Cannot start windows sockets!" << std::endl; return false; } } #endif #pragma warning(push) #pragma warning(disable:4996) unsigned long addr = inet_addr( strIPAddress.c_str() ); #pragma warning(pop) sockaddr_in ServerSocketAddress; ServerSocketAddress.sin_addr.s_addr = addr; ServerSocketAddress.sin_family = AF_INET; ServerSocketAddress.sin_port = htons( SERVER_PORT ); mConnectionSocket = socket( AF_INET, SOCK_STREAM, 0 ); #ifdef WIN32 if( mConnectionSocket == INVALID_SOCKET ) #else if (mConnectionSocket == -1 ) #endif { std::cout << "Error: Cannot open a socket!" << std::endl; return false; } if ( connect( mConnectionSocket,(struct sockaddr*)&ServerSocketAddress, sizeof( ServerSocketAddress ) ) ) { std::cout << "Error: Cannot connect to " << strIPAddress << "!" << std::endl; #ifdef WIN32 closesocket( mConnectionSocket ); #else close( mConnectionSocket ); #endif return false; } SendMessage("login " + GetPassword()); bReceivedFirstPing = false; return true; } void CLIENT::ConnectionClosed() { std::cout<<"Connection closed"<<std::endl; #ifdef WIN32 mConnectionSocket = INVALID_SOCKET; #else mConnectionSocket = -1; #endif } void CLIENT::SendMessage( std::string aMessage ) { if (LinkDead()) return; if (aMessage.length()==0) return; if (aMessage[aMessage.length()-1]!='\n') aMessage+="\n"; if (NeedDebugLog() && mDebugLog.is_open()) { mDebugLog<<"Sent: "<<aMessage; } int SentBytes = send( mConnectionSocket, aMessage.c_str(), int(aMessage.size()), 0 ); if (SentBytes!=aMessage.size()) { #ifdef WIN32 closesocket( mConnectionSocket ); #else close( mConnectionSocket ); #endif ConnectionClosed(); } } void CLIENT::ParsePlayers(std::vector<std::string> &ServerResponse) { Players.clear(); if (ServerResponse[0].substr(0, 7)=="players") { int count = atoi(ServerResponse[0].substr(8).c_str()); Players.resize(count); int r; for(r=0;r<count;r++) { std::stringstream ss; ss<<ServerResponse[r+1]; ss>>Players[r].id; ss>>Players[r].match_wins; ss>>Players[r].elo_points; char str[31]; ss.getline(str, 30); str[30]=0; Players[r].name = str; } } } void CLIENT::Run() { if (NeedDebugLog()) { mDebugLog.open("debug.log", std::ofstream::out | std::ofstream::app); } std::string strLastLineRemaining; std::vector<std::string> LastServerResponse; int last_connect_try_time = GetTickCount(); for(;;) { if (LinkDead()) { LastServerResponse.clear(); strLastLineRemaining = ""; Init(); } if (LinkDead()) { #ifdef WIN32 Sleep(1000); #else sleep(1); #endif continue; } const size_t ReceiveBufferSize = 1<<16; char ReceiveBuffer[ ReceiveBufferSize+1 ] = {0}; int ReceivedBytesCount = recv( mConnectionSocket, ReceiveBuffer, ReceiveBufferSize, 0 ); if( ReceivedBytesCount == 0 || ReceivedBytesCount == -1) { // connection is closed or failed #ifdef WIN32 closesocket( mConnectionSocket ); #else close( mConnectionSocket ); #endif ConnectionClosed(); continue; } ReceiveBuffer[ReceivedBytesCount]=0; char *line_start = ReceiveBuffer; for(;;) { char *s = strchr(line_start, '\n'); if (!s) { strLastLineRemaining = line_start; break; } else { std::string alma=strLastLineRemaining; *s=0; alma+=line_start; line_start = s+1; strLastLineRemaining = ""; if (alma=="fail") { std::cout<<"Login failed :("<<std::endl; } else if (alma=="ping") { SendMessage(std::string("pong")); if (!bReceivedFirstPing) { std::cout<<"Login OK"<<std::endl; SendMessage(std::string("opponent ")+GetPreferredOpponents()); bReceivedFirstPing = true; } else { time_t tt; time(&tt); struct tm *tm = localtime(&tt); char str[20]; sprintf(str, "%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec); std::cout<<"PING "<<str<<std::endl; } } else { LastServerResponse.push_back(alma); if (alma==".") { if (LastServerResponse.front().substr(0, 7)=="players") { ParsePlayers(LastServerResponse); } else { if (NeedDebugLog() && mDebugLog.is_open()) { for(unsigned int i=0;i<LastServerResponse.size();i++) mDebugLog<<LastServerResponse[i]<<std::endl; } std::string strResponse = HandleServerResponse(LastServerResponse); if (!strResponse.empty()) { SendMessage(strResponse); } } LastServerResponse.clear(); } } } } } } std::string CLIENT::HandleServerResponse(std::vector<std::string> &ServerResponse) { mParser.Parse(ServerResponse); if (mParser.w!=0 && mDistCache.mDistMap.empty()) { mDistCache.CreateFromParser(mParser); mDistCache.SaveToFile("distcache.bin"); } std::stringstream ss; if (mParser.match_result==PARSER::ONGOING) { ss << "tick "<<mParser.tick<<"\n"; Process(); ss<<command_buffer.str(); for(std::map<int, CLIENT::CMD>::iterator it=mUnitTarget.begin();it!=mUnitTarget.end();) { bool cmd_done = false; MAP_OBJECT *q = NULL; for(std::vector<MAP_OBJECT>::iterator p=mParser.Units.begin(); p!=mParser.Units.end();p++) { if (p->id==it->first) { q=&*p; break; } } if (q==NULL) { cmd_done = true; } else if (it->second.c == CLIENT::CMD_MOVE) { if (q->pos==it->second.pos) cmd_done = true; else { POS t = mDistCache.GetNextTowards(q->pos, it->second.pos); if (!t.IsValid()) { cmd_done = true; } else { if (t==it->second.pos) cmd_done = true; ss<<"queen_move "<<it->first<<" "<<t.x<<" "<<t.y<<"\n"; } } } else if (it->second.c == CLIENT::CMD_SPAWN) { bool do_spawn = false; if (q->pos==it->second.pos) do_spawn = true; else { POS t = mDistCache.GetNextTowards(q->pos, it->second.pos); if (!t.IsValid()) cmd_done = true; else if (t==it->second.pos) do_spawn = true; else { ss<<"queen_move "<<it->first<<" "<<t.x<<" "<<t.y<<"\n"; } } if (do_spawn) { ss<<"queen_spawn "<<it->first<<" "<<it->second.pos.x<<" "<<it->second.pos.y<<"\n"; cmd_done = true; } } else if (it->second.c == CLIENT::CMD_ATTACK) { MAP_OBJECT *t = NULL; POS t_pos; std::vector<MAP_OBJECT>::iterator p; for(p=mParser.Units.begin(); p!=mParser.Units.end();p++) { if (p->id==it->second.target_id) { t=&*p; t_pos = p->pos; break; } } if (t==NULL) for(p=mParser.CreepTumors.begin();p!=mParser.CreepTumors.end();p++) { if (p->id==it->second.target_id) { t=&*p; t_pos=p->pos; break; } } if (t==NULL) { if (mParser.EnemyHatchery.id==it->second.target_id) { t=&mParser.EnemyHatchery; t_pos=mParser.EnemyHatchery.pos; // find closest point of hatchery: int i; for (i = 0; i<HATCHERY_SIZE - 1; i++) if (q->pos.y>t_pos.y) t_pos.y++; for (i = 0; i<HATCHERY_SIZE - 1; i++) if (q->pos.x>t_pos.x) t_pos.x++; } } if (t==NULL) cmd_done = true; else { bool do_attack = false; if (q->pos==t_pos) do_attack = true; else { POS next_pos = mDistCache.GetNextTowards(q->pos, t_pos); if (!next_pos.IsValid()) { cmd_done=true; } else if (next_pos==t_pos) do_attack = true; else { ss<<"queen_move "<<it->first<<" "<<next_pos.x<<" "<<next_pos.y<<"\n"; } } if (do_attack) ss<<"queen_attack "<<it->first<<" "<<it->second.target_id<<"\n"; } } std::map<int, CLIENT::CMD>::iterator it2=it; it2++; if (cmd_done) { mUnitTarget.erase(it); } it=it2; } command_buffer.str(std::string()); ss<<"."; } else { mUnitTarget.clear(); MatchEnd(); ss<<"."; } return ss.str(); } int main(int argc, char* argv[]) { std::cout.sync_with_stdio(false); std::string server_address; if (argc<2) { server_address = "10.112.1.185"; std::cout<<"using default server address: " + server_address <<std::endl; } else { server_address = argv[1]; } CLIENT *pClient = CreateClient(); /* for debugging: */ std::ifstream debug_file("test.txt"); if (debug_file.is_open()) { std::string line; std::vector<std::string> full; while (std::getline(debug_file, line)) { full.push_back(line); } std::string resp = pClient->DebugResponse(full); std::cout<<"response: "<<resp <<std::endl; } /**/ pClient->strIPAddress = server_address; if (!pClient->Init()) { std::cout<<"Connection failed"<<std::endl; } else { pClient->Run(); } delete pClient; return 0; }
23.678744
154
0.590227
dhanak
0cfccad6f6a10830ec180e7329b70e016084a9ec
241
hpp
C++
corex/src/corex/core/events/game_events.hpp
seanballais/gwo-visualization
470561c603236d6a858b78a8585fd0bae71612a5
[ "MIT" ]
null
null
null
corex/src/corex/core/events/game_events.hpp
seanballais/gwo-visualization
470561c603236d6a858b78a8585fd0bae71612a5
[ "MIT" ]
null
null
null
corex/src/corex/core/events/game_events.hpp
seanballais/gwo-visualization
470561c603236d6a858b78a8585fd0bae71612a5
[ "MIT" ]
null
null
null
#ifndef COREX_CORE_EVENTS_GAME_EVENTS_HPP #define COREX_CORE_EVENTS_GAME_EVENTS_HPP namespace corex::core { struct GameTimeWarpEvent { float timeWarpFactor; }; struct GameTimerStatusEvent { bool isPlaying; }; } #endif
13.388889
41
0.755187
seanballais
490922b8449248ae20f988401452233f96ebe02d
922
hpp
C++
src/app/validator-manager.hpp
mimo31/fluid-sim
481c3e5a5456350bccb8795aa119a3487dff3021
[ "MIT" ]
1
2020-11-26T17:20:28.000Z
2020-11-26T17:20:28.000Z
src/app/validator-manager.hpp
mimo31/brandy0
481c3e5a5456350bccb8795aa119a3487dff3021
[ "MIT" ]
null
null
null
src/app/validator-manager.hpp
mimo31/brandy0
481c3e5a5456350bccb8795aa119a3487dff3021
[ "MIT" ]
null
null
null
/** * validator-manager.hpp * * Author: Viktor Fukala * Created on 2021/01/16 */ #ifndef VALIDATOR_MANAGER_HPP #define VALIDATOR_MANAGER_HPP #include "func.hpp" #include "vec.hpp" namespace brandy0 { /** * Container for arbitrarily many bool(void) callbacks. * Callbacks (a.k.a. validators) can be dynamically added and it can be queries whether they all evaluate to true. * Meant primarily for user input validation -- each entry can have its validator and the form can be submitted only if all validators evaluate to true. */ class ValidatorManager { private: /// Vector of all registered validators vec<BoolFunc> validators; public: /** * Registers a new validator * @param validator validator to register */ void plug(const BoolFunc& validator); /** * @return true iff all currently registered validators evaluate to true */ bool isAllValid() const; }; } #endif // VALIDATOR_MANAGER_HPP
22.487805
152
0.736443
mimo31
490a0b2c5d3f200f97d3a3bb3d45a66064b53d8d
2,408
cpp
C++
utilities/Socket.cpp
JKowalsky/ftp-client
daa81b546b399907cdd77bc639ad61a3b17b5939
[ "MIT" ]
null
null
null
utilities/Socket.cpp
JKowalsky/ftp-client
daa81b546b399907cdd77bc639ad61a3b17b5939
[ "MIT" ]
null
null
null
utilities/Socket.cpp
JKowalsky/ftp-client
daa81b546b399907cdd77bc639ad61a3b17b5939
[ "MIT" ]
null
null
null
/* * File: Socket.cpp * Author: kowalsky * * Created on November 30, 2014, 4:49 PM */ #include "Socket.h" Socket::Socket(int port) : port(port), clientFd(NULL_FD), serverFd(NULL_FD) { } Socket::~Socket() { if (clientFd != NULL_FD) close(clientFd); if (serverFd != NULL_FD) close(serverFd); } int Socket::getClientSocket(char ipName[]) { return getClientSocket(ipName, 0, false); } int Socket::getClientSocket(char ipName[], int sndbufsize, bool nodelay) { // Get the host entry corresponding to ipName struct hostent* host = gethostbyname(ipName); if (host == NULL) { perror("Cannot find hostname."); return NULL_FD; } // Fill in the structure "sendSockAddr" with the address of the server. sockaddr_in sendSockAddr; bzero((char*) &sendSockAddr, sizeof ( sendSockAddr)); sendSockAddr.sin_family = AF_INET; // Address Family Internet sendSockAddr.sin_addr.s_addr = inet_addr(inet_ntoa(*(struct in_addr*) *host->h_addr_list)); sendSockAddr.sin_port = htons(port); // Open a TCP socket (an Internet strem socket). if ((clientFd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("Cannot open a client TCP socket."); return NULL_FD; } // Set the rcvbuf option if (sndbufsize > 0) { cout << sndbufsize << endl; if (setsockopt(clientFd, SOL_SOCKET, SO_SNDBUF, (char *) &sndbufsize, sizeof ( sndbufsize)) < 0) { perror("setsockopt SO_SNDBUF failed"); return NULL_FD; } } // Set the nodelay option if (nodelay == true) { int on = 1; if (setsockopt(clientFd, IPPROTO_TCP, TCP_NODELAY, (char *) &on, sizeof ( int)) < 0) { perror("setsockopt TCP_NODELAY failed"); return NULL_FD; } } // Connect to the server. while (connect(clientFd, (sockaddr*) & sendSockAddr, sizeof ( sendSockAddr)) < 0); // Connected return clientFd; } int Socket::pollRecvFrom() { struct pollfd pfd[1]; pfd[0].fd = clientFd; // declare I'll check the data availability of sd pfd[0].events = POLLRDNORM; // declare I'm interested in only reading from sd // check it for 2 seconds and return a positive number if sd is readable, // otherwise return 0 or a negative number return poll( pfd, 1, 1000 ); }
27.678161
79
0.616694
JKowalsky
490b9fb710f1e9195b51c1e5af31415cecfc6a0f
1,996
cpp
C++
test/test_crossentropyloss_layer.cpp
sdadia/deep-learning-and-optimization
b44be79de116e2d4b203452a161641519f18f580
[ "MIT" ]
1
2018-10-02T15:29:14.000Z
2018-10-02T15:29:14.000Z
test/test_crossentropyloss_layer.cpp
sdadia/deep-learning-and-optimization
b44be79de116e2d4b203452a161641519f18f580
[ "MIT" ]
null
null
null
test/test_crossentropyloss_layer.cpp
sdadia/deep-learning-and-optimization
b44be79de116e2d4b203452a161641519f18f580
[ "MIT" ]
null
null
null
#include "crossentropyloss_layer.hpp" #include "common.hpp" #include "gtest/gtest.h" #include "gmock/gmock.h" #include <glog/logging.h> TEST(CrossEntropyLossLayer, CheckNumInputs) { // if zero inputs, then a problem will occour std::vector<dtensor_t> input(2); std::vector<dtensor_t> labels(2); dpl::CrossEntropyLossLayer p; p.setUp(input, labels); } TEST(CrossEntropyLossLayer, forward) { // input, label, and true value dtensor_t p1{123, 456, 789}, p2{1, -2, 0}, p3 {0.5,-1, 0}; dtensor_t l1{1,0,0}, l2{0,1,0}, l3{0,0,1}; dtensor_t t1{0.0,0.0,1.0}, t2{0.705384,0.035119, 0.259496}, t3{0.546549,0.121951,0.331498}; std::vector<dtensor_t> input{p1,p2,p3}, labels{l1,l2,l3}, true_values{t1,t2,t3}; dpl::CrossEntropyLossLayer p; p.setUp(input, labels); auto output = p.forward(); for(uint_t i=0; i<output.size(); i++) { auto output_raw_data = output[i].raw_data(); auto true_value_raw_data = true_values[i].raw_data(); EXPECT_TRUE(AreFloatingPointArraysEqual(output_raw_data, true_value_raw_data, output[i].size())); } } TEST(CrossEntropyLossLayer, backward) { // input, label, and true value dtensor_t p1{123, 456, 789}, p2{1, -2, 0}, p3 {0.5,-1, 0}; dtensor_t l1{1,0,0}, l2{0,1,0}, l3{0,0,1}; dtensor_t t1{0.0,0.0,1.0}, t2{0.705384,0.035119, 0.259496}, t3{0.546549,0.121951,0.331498}; //dtensor_t g1{} std::vector<dtensor_t> input{p1,p2,p3}, labels{l1,l2,l3}, true_values{t1,t2,t3}; dpl::CrossEntropyLossLayer p; p.setUp(input, labels); auto output = p.forward(); for(uint_t i=0; i<output.size(); i++) { auto output_raw_data = output[i].raw_data(); auto true_value_raw_data = true_values[i].raw_data(); EXPECT_TRUE(AreFloatingPointArraysEqual(output_raw_data, true_value_raw_data, output[i].size())); } } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
25.922078
105
0.648798
sdadia
490ead04603ff489afc8802626c59b089b8e5a47
2,791
cpp
C++
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Table_RobotoCondensed_Bold_42_4bpp.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Table_RobotoCondensed_Bold_42_4bpp.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/generated/fonts/src/Table_RobotoCondensed_Bold_42_4bpp.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
#include <touchgfx/Font.hpp> #ifndef NO_USING_NAMESPACE_TOUCHGFX using namespace touchgfx; #endif FONT_LOCATION_FLASH_PRAGMA KEEP extern const touchgfx::GlyphNode glyphs_RobotoCondensed_Bold_42_4bpp[] FONT_LOCATION_FLASH_ATTRIBUTE = { { 0, 2, 0, 0, 0, 0, 1, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 0, 48, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 300, 49, 12, 30, 30, 3, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 480, 50, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 780, 51, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 1080, 52, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 1380, 53, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 1680, 54, 18, 30, 30, 2, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 1950, 55, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 2250, 56, 18, 30, 30, 2, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 2520, 57, 19, 30, 30, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 2820, 65, 25, 30, 30, 0, 25, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 3210, 66, 20, 30, 30, 2, 24, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 3510, 67, 22, 30, 30, 1, 24, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 3840, 68, 20, 30, 30, 2, 24, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 4140, 69, 18, 30, 30, 2, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 4410, 70, 17, 30, 30, 2, 20, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 4680, 71, 22, 30, 30, 1, 25, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 5010, 74, 19, 30, 30, 0, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 5310, 76, 18, 30, 30, 2, 20, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 5580, 77, 28, 30, 30, 2, 32, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 6000, 78, 22, 30, 30, 2, 26, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 6330, 79, 23, 30, 30, 1, 25, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 6690, 80, 21, 30, 30, 2, 24, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 7020, 82, 21, 30, 30, 2, 23, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 7350, 83, 21, 30, 30, 1, 23, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 7680, 84, 21, 30, 30, 1, 23, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 8010, 85, 20, 30, 30, 2, 24, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 8310, 86, 24, 30, 30, 0, 24, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0}, { 8670, 89, 23, 30, 30, 0, 23, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4|0} };
66.452381
109
0.58402
ramkumarkoppu
490fbeba6c6750fd5f4936f931923bec5b4fc099
1,940
hpp
C++
caffe/include/caffe/layers/sparse_hypercolumn_extractor_layer.hpp
gustavla/autocolorizer
79d4ce1054d35c06bdfcc93236b71e161e082ebb
[ "BSD-3-Clause" ]
234
2016-04-04T15:12:24.000Z
2022-03-14T12:55:09.000Z
caffe/include/caffe/layers/sparse_hypercolumn_extractor_layer.hpp
TrinhQuocNguyen/autocolorize
79d4ce1054d35c06bdfcc93236b71e161e082ebb
[ "BSD-3-Clause" ]
20
2016-04-05T12:44:04.000Z
2022-02-22T06:02:17.000Z
caffe/include/caffe/layers/sparse_hypercolumn_extractor_layer.hpp
TrinhQuocNguyen/autocolorize
79d4ce1054d35c06bdfcc93236b71e161e082ebb
[ "BSD-3-Clause" ]
71
2016-07-12T15:28:16.000Z
2021-12-16T12:22:57.000Z
#ifndef CAFFE_SPARSE_HYPERCOLUMN_LAYER_HPP #define CAFFE_SPARSE_HYPERCOLUMN_LAYER_HPP #include <string> #include <utility> #include <vector> #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/layer.hpp" namespace caffe { /** * \ingroup ttic * @brief This extracts locations of hypercolumns. It should be faster, and * more importantly use less memory, than the original, since you do not need * separate upscaling layers. It does the bilinear upscaling by itself. * * @author Gustav Larsson */ template <typename Dtype> class SparseHypercolumnExtractorLayer : public Layer<Dtype> { public: explicit SparseHypercolumnExtractorLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "SparseHypercolumnExtractor"; } virtual inline int MinBottomBlobs() const { return 2; } virtual inline int ExactNumTopBlobs() const { return 1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); int num_layers_; int num_channels_; // in the entire hypercolumn int num_locations_; vector<Dtype> offsets_h_; vector<Dtype> offsets_w_; vector<Dtype> scales_; vector<Dtype> activation_mults_; vector<int> channel_offsets_; }; } // namespace caffe #endif // CAFFE_SPARSE_HYPERCOLUMN_LAYER_HPP
32.333333
82
0.737629
gustavla
49108ddf6d4c6c7194aeb7664774efa5285a70e3
2,316
cpp
C++
src/level/button/pressureButton.cpp
kirbyUK/duo
85155fcce81086ea39593750f042a8f518f09804
[ "MIT" ]
null
null
null
src/level/button/pressureButton.cpp
kirbyUK/duo
85155fcce81086ea39593750f042a8f518f09804
[ "MIT" ]
null
null
null
src/level/button/pressureButton.cpp
kirbyUK/duo
85155fcce81086ea39593750f042a8f518f09804
[ "MIT" ]
null
null
null
/* Copyright (c) 2014, Alex Kerr * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "pressureButton.h" #include <iostream> #ifndef ASSETS #define ASSETS "./assets" #endif #ifdef _WIN32 const std::string PressureButton::BUTTON_PATHS[2] = { (((std::string)ASSETS) + ((std::string)"\\sprites\\p_button.png")), (((std::string)ASSETS) + ((std::string)"\\sprites\\p_button2.png")) }; #else const std::string PressureButton::BUTTON_PATHS[2] = { (((std::string)ASSETS) + ((std::string)"/sprites/p_button.png")), (((std::string)ASSETS) + ((std::string)"/sprites/p_button2.png")) }; #endif sf::Image PressureButton::_images[2]; //The colour to remove in the images and replace with transparency: const sf::Color PressureButton::COLOUR_MASK(0, 255, 0); bool PressureButton::init() { for(unsigned int i = 0; i < 2; i++) { if(! _images[i].loadFromFile(BUTTON_PATHS[i])) { std::cerr << "Unable to load '" << BUTTON_PATHS[i] << "'.\n"; return false; } else //If it loads fine, remove the green background: _images[i].createMaskFromColor(COLOUR_MASK); } return true; } PressureButton::PressureButton(sf::Vector2f buttonPos, sf::Vector2f blockPos, Block* block) { _texture.loadFromImage(_images[0]); _sprite.setTexture(_texture); _sprite.setPosition(buttonPos); _block = block; _blockPos[0] = _block->_shape.getPosition(); _blockPos[1] = blockPos; } void PressureButton::_handlePressed(bool isPlayerOnTop) { if(isPlayerOnTop) { _block->_shape.setPosition(_blockPos[1]); _texture.update(_images[1]); } else { _block->_shape.setPosition(_blockPos[0]); _texture.update(_images[0]); } }
28.592593
78
0.71848
kirbyUK
491093ebf494376d05903c57abe5e9bd5b9b74f5
1,476
cpp
C++
Codes/CodeForces/E/1265E_2.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
3
2019-07-20T07:26:31.000Z
2020-08-06T09:31:09.000Z
Codes/CodeForces/E/1265E_2.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
null
null
null
Codes/CodeForces/E/1265E_2.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
4
2019-06-20T18:43:32.000Z
2020-10-07T16:45:23.000Z
/* Author : Qazi Fahim Farhan (@fahimfarhan) */ /* May the CodeForces be with you! */ #include <iostream> // #include <sstream> // #include <cstdio> // #include <cmath> // #include <cstring> // #include <cctype> // #include <string> #include <vector> // #include <list> // #include <set> // #include <map> // #include <queue> // #include <stack> // #include <algorithm> // #include <functional> #include <iomanip> // std::setprecision using namespace std; #define PI 2*acos(0) //typedef long long ll ll; #define ll long long int // other popular ones=> ll64_t, ull64_t => use for 10^18 const ll MOD = 119 << 23 | 1; ll inv(ll input){ ll ret = 1; ll k = MOD - 2; ll a = input; while (k) { /* code */ if( (k&1) == 1){ ret = ((ret * a) % MOD); } a = ((a*a) % MOD); k = k>>1; } return ret; } int main(int argc, char const *argv[]) { /* code */ // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); /* std::cout << std::fixed; std::cout << std::setprecision(10); cout << num1 << endl; */ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll n, m; m = inv(100); cin>>n; ll p[n+1]; for(ll i=0; i<n; i++){ cin>>p[i]; p[i] = ((p[i] * m)%MOD); } ll E = inv(p[0]); for(ll i=1; i<n; i++){ E = (E+1)*inv(p[i]); E = E%MOD; } cout<<E<<"\n"; return 0; }
17.783133
56
0.496612
fahimfarhan
49154a3892486e9327bda6161d73774316183cd2
6,039
cpp
C++
qtmultimedia/src/plugins/android/src/mediacapture/qandroidcameraimageprocessingcontrol.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
qtmultimedia/src/plugins/android/src/mediacapture/qandroidcameraimageprocessingcontrol.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
qtmultimedia/src/plugins/android/src/mediacapture/qandroidcameraimageprocessingcontrol.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qandroidcameraimageprocessingcontrol.h" #include "qandroidcamerasession.h" #include "androidcamera.h" QT_BEGIN_NAMESPACE QAndroidCameraImageProcessingControl::QAndroidCameraImageProcessingControl(QAndroidCameraSession *session) : QCameraImageProcessingControl() , m_session(session) , m_whiteBalanceMode(QCameraImageProcessing::WhiteBalanceAuto) { connect(m_session, SIGNAL(opened()), this, SLOT(onCameraOpened())); } bool QAndroidCameraImageProcessingControl::isParameterSupported(ProcessingParameter parameter) const { return parameter == QCameraImageProcessingControl::WhiteBalancePreset && m_session->camera() && !m_supportedWhiteBalanceModes.isEmpty(); } bool QAndroidCameraImageProcessingControl::isParameterValueSupported(ProcessingParameter parameter, const QVariant &value) const { return parameter == QCameraImageProcessingControl::WhiteBalancePreset && m_session->camera() && m_supportedWhiteBalanceModes.contains(value.value<QCameraImageProcessing::WhiteBalanceMode>()); } QVariant QAndroidCameraImageProcessingControl::parameter(ProcessingParameter parameter) const { if (parameter != QCameraImageProcessingControl::WhiteBalancePreset) return QVariant(); return QVariant::fromValue(m_whiteBalanceMode); } void QAndroidCameraImageProcessingControl::setParameter(ProcessingParameter parameter, const QVariant &value) { if (parameter != QCameraImageProcessingControl::WhiteBalancePreset) return; QCameraImageProcessing::WhiteBalanceMode mode = value.value<QCameraImageProcessing::WhiteBalanceMode>(); if (m_session->camera()) setWhiteBalanceModeHelper(mode); else m_whiteBalanceMode = mode; } void QAndroidCameraImageProcessingControl::setWhiteBalanceModeHelper(QCameraImageProcessing::WhiteBalanceMode mode) { QString wb = m_supportedWhiteBalanceModes.value(mode, QString()); if (!wb.isEmpty()) { m_session->camera()->setWhiteBalance(wb); m_whiteBalanceMode = mode; } } void QAndroidCameraImageProcessingControl::onCameraOpened() { m_supportedWhiteBalanceModes.clear(); QStringList whiteBalanceModes = m_session->camera()->getSupportedWhiteBalance(); for (int i = 0; i < whiteBalanceModes.size(); ++i) { const QString &wb = whiteBalanceModes.at(i); if (wb == QLatin1String("auto")) { m_supportedWhiteBalanceModes.insert(QCameraImageProcessing::WhiteBalanceAuto, QStringLiteral("auto")); } else if (wb == QLatin1String("cloudy-daylight")) { m_supportedWhiteBalanceModes.insert(QCameraImageProcessing::WhiteBalanceCloudy, QStringLiteral("cloudy-daylight")); } else if (wb == QLatin1String("daylight")) { m_supportedWhiteBalanceModes.insert(QCameraImageProcessing::WhiteBalanceSunlight, QStringLiteral("daylight")); } else if (wb == QLatin1String("fluorescent")) { m_supportedWhiteBalanceModes.insert(QCameraImageProcessing::WhiteBalanceFluorescent, QStringLiteral("fluorescent")); } else if (wb == QLatin1String("incandescent")) { m_supportedWhiteBalanceModes.insert(QCameraImageProcessing::WhiteBalanceTungsten, QStringLiteral("incandescent")); } else if (wb == QLatin1String("shade")) { m_supportedWhiteBalanceModes.insert(QCameraImageProcessing::WhiteBalanceShade, QStringLiteral("shade")); } else if (wb == QLatin1String("twilight")) { m_supportedWhiteBalanceModes.insert(QCameraImageProcessing::WhiteBalanceSunset, QStringLiteral("twilight")); } else if (wb == QLatin1String("warm-fluorescent")) { m_supportedWhiteBalanceModes.insert(QCameraImageProcessing::WhiteBalanceFlash, QStringLiteral("warm-fluorescent")); } } if (!m_supportedWhiteBalanceModes.contains(m_whiteBalanceMode)) m_whiteBalanceMode = QCameraImageProcessing::WhiteBalanceAuto; setWhiteBalanceModeHelper(m_whiteBalanceMode); } QT_END_NAMESPACE
44.733333
115
0.674946
wgnet
4915cc1fa9aa0126e6c28cde54d0f51ccd180fa1
2,171
hpp
C++
src/SudokuGraph.hpp
luiz787/alg1-tp3
3c1e54b023ddb269bce557681cf574aca18b3a87
[ "MIT" ]
null
null
null
src/SudokuGraph.hpp
luiz787/alg1-tp3
3c1e54b023ddb269bce557681cf574aca18b3a87
[ "MIT" ]
null
null
null
src/SudokuGraph.hpp
luiz787/alg1-tp3
3c1e54b023ddb269bce557681cf574aca18b3a87
[ "MIT" ]
null
null
null
#ifndef ALG1_TP3_SUDOKUGRAPH_HPP #define ALG1_TP3_SUDOKUGRAPH_HPP #include <cstdint> #include <list> #include <vector> #include <set> #include "Vertice.hpp" class SudokuGraph { private: std::vector<Vertice*> vertices; const uint32_t quadrantColumnWidth; const uint32_t quadrantRowHeight; const uint32_t amountOfColumns; const uint32_t amountOfRows; void addEdgesToVerticesInSameColumn(Vertice *vertice); void addEdgesToVerticesInSameRow(Vertice *vertice); void addEdgesToVerticesInSameQuadrant(Vertice *vertice); uint32_t getVerticeColumn(uint32_t verticeIndex) const; uint32_t getVerticeRow(uint32_t verticeIndex) const; void printAnswer(uint32_t totalColoredVertices) const; void removeAssignedColorFromNeighbors(Vertice *vertice); void assignColorToSaturatedVertices(uint32_t &totalColoredVertices, uint32_t &verticesThatGainedColorsInCurrentIteration); void assignColorToExhaustedUnits(uint32_t &totalColoredVertices, uint32_t &verticesThatGainedColorsInCurrentIteration); void tryToAssignColorByCheckingRowExhaustion(Vertice *vertice, uint32_t &totalColoredVertices, uint32_t &verticesThatGainedColorsInCurrentIteration); void tryToAssignColorByCheckingColumnExhaustion(Vertice *vertice, uint32_t &totalColoredVertices, uint32_t &verticesThatGainedColorsInCurrentIteration); void tryToAssignColorByCheckingQuadrantExhaustion(Vertice *vertice, uint32_t &totalColoredVertices, uint32_t &verticesThatGainedColorsInCurrentIteration); void assignColorToVerticeIfPossible(Vertice *currentVertice, const std::set<Vertice *> &unassignedNeighbors, uint32_t &totalColoredVertices, uint32_t &verticesThatGainedColorsInCurrentIteration); public: SudokuGraph(uint32_t columns, uint32_t rows, const std::vector<Vertice *> &vertices); ~SudokuGraph(); void solve(); }; #endif
40.962264
112
0.702441
luiz787
4918a085c092ae79048cbc9d2b6693d185013b3b
5,921
hpp
C++
build/include/lcmtypes/drake/lcmt_viewer_draw.hpp
ericmanzi/double_pendulum_lqr
76bba3091295abb7d412c4a3156258918f280c96
[ "BSD-3-Clause" ]
null
null
null
build/include/lcmtypes/drake/lcmt_viewer_draw.hpp
ericmanzi/double_pendulum_lqr
76bba3091295abb7d412c4a3156258918f280c96
[ "BSD-3-Clause" ]
null
null
null
build/include/lcmtypes/drake/lcmt_viewer_draw.hpp
ericmanzi/double_pendulum_lqr
76bba3091295abb7d412c4a3156258918f280c96
[ "BSD-3-Clause" ]
null
null
null
/** THIS IS AN AUTOMATICALLY GENERATED FILE. DO NOT MODIFY * BY HAND!! * * Generated by lcm-gen **/ #include <lcm/lcm_coretypes.h> #ifndef __drake_lcmt_viewer_draw_hpp__ #define __drake_lcmt_viewer_draw_hpp__ #include <vector> namespace drake { class lcmt_viewer_draw { public: int64_t timestamp; int32_t num_links; std::vector< std::string > link_name; std::vector< int32_t > robot_num; std::vector< std::vector< float > > position; std::vector< std::vector< float > > quaternion; public: inline int encode(void *buf, int offset, int maxlen) const; inline int getEncodedSize() const; inline int decode(const void *buf, int offset, int maxlen); inline static int64_t getHash(); inline static const char* getTypeName(); // LCM support functions. Users should not call these inline int _encodeNoHash(void *buf, int offset, int maxlen) const; inline int _getEncodedSizeNoHash() const; inline int _decodeNoHash(const void *buf, int offset, int maxlen); inline static int64_t _computeHash(const __lcm_hash_ptr *p); }; int lcmt_viewer_draw::encode(void *buf, int offset, int maxlen) const { int pos = 0, tlen; int64_t hash = getHash(); tlen = __int64_t_encode_array(buf, offset + pos, maxlen - pos, &hash, 1); if(tlen < 0) return tlen; else pos += tlen; tlen = this->_encodeNoHash(buf, offset + pos, maxlen - pos); if (tlen < 0) return tlen; else pos += tlen; return pos; } int lcmt_viewer_draw::decode(const void *buf, int offset, int maxlen) { int pos = 0, thislen; int64_t msg_hash; thislen = __int64_t_decode_array(buf, offset + pos, maxlen - pos, &msg_hash, 1); if (thislen < 0) return thislen; else pos += thislen; if (msg_hash != getHash()) return -1; thislen = this->_decodeNoHash(buf, offset + pos, maxlen - pos); if (thislen < 0) return thislen; else pos += thislen; return pos; } int lcmt_viewer_draw::getEncodedSize() const { return 8 + _getEncodedSizeNoHash(); } int64_t lcmt_viewer_draw::getHash() { static int64_t hash = _computeHash(NULL); return hash; } const char* lcmt_viewer_draw::getTypeName() { return "lcmt_viewer_draw"; } int lcmt_viewer_draw::_encodeNoHash(void *buf, int offset, int maxlen) const { int pos = 0, tlen; tlen = __int64_t_encode_array(buf, offset + pos, maxlen - pos, &this->timestamp, 1); if(tlen < 0) return tlen; else pos += tlen; tlen = __int32_t_encode_array(buf, offset + pos, maxlen - pos, &this->num_links, 1); if(tlen < 0) return tlen; else pos += tlen; for (int a0 = 0; a0 < this->num_links; a0++) { char* __cstr = (char*) this->link_name[a0].c_str(); tlen = __string_encode_array(buf, offset + pos, maxlen - pos, &__cstr, 1); if(tlen < 0) return tlen; else pos += tlen; } tlen = __int32_t_encode_array(buf, offset + pos, maxlen - pos, &this->robot_num[0], this->num_links); if(tlen < 0) return tlen; else pos += tlen; for (int a0 = 0; a0 < this->num_links; a0++) { tlen = __float_encode_array(buf, offset + pos, maxlen - pos, &this->position[a0][0], 3); if(tlen < 0) return tlen; else pos += tlen; } for (int a0 = 0; a0 < this->num_links; a0++) { tlen = __float_encode_array(buf, offset + pos, maxlen - pos, &this->quaternion[a0][0], 4); if(tlen < 0) return tlen; else pos += tlen; } return pos; } int lcmt_viewer_draw::_decodeNoHash(const void *buf, int offset, int maxlen) { int pos = 0, tlen; tlen = __int64_t_decode_array(buf, offset + pos, maxlen - pos, &this->timestamp, 1); if(tlen < 0) return tlen; else pos += tlen; tlen = __int32_t_decode_array(buf, offset + pos, maxlen - pos, &this->num_links, 1); if(tlen < 0) return tlen; else pos += tlen; this->link_name.resize(this->num_links); for (int a0 = 0; a0 < this->num_links; a0++) { int32_t __elem_len; tlen = __int32_t_decode_array(buf, offset + pos, maxlen - pos, &__elem_len, 1); if(tlen < 0) return tlen; else pos += tlen; if(__elem_len > maxlen - pos) return -1; this->link_name[a0].assign(((const char*)buf) + offset + pos, __elem_len - 1); pos += __elem_len; } this->robot_num.resize(this->num_links); if(this->num_links) { tlen = __int32_t_decode_array(buf, offset + pos, maxlen - pos, &this->robot_num[0], this->num_links); if(tlen < 0) return tlen; else pos += tlen; } this->position.resize(this->num_links); for (int a0 = 0; a0 < this->num_links; a0++) { this->position[a0].resize(3); if(3) { tlen = __float_decode_array(buf, offset + pos, maxlen - pos, &this->position[a0][0], 3); if(tlen < 0) return tlen; else pos += tlen; } } this->quaternion.resize(this->num_links); for (int a0 = 0; a0 < this->num_links; a0++) { this->quaternion[a0].resize(4); if(4) { tlen = __float_decode_array(buf, offset + pos, maxlen - pos, &this->quaternion[a0][0], 4); if(tlen < 0) return tlen; else pos += tlen; } } return pos; } int lcmt_viewer_draw::_getEncodedSizeNoHash() const { int enc_size = 0; enc_size += __int64_t_encoded_array_size(NULL, 1); enc_size += __int32_t_encoded_array_size(NULL, 1); for (int a0 = 0; a0 < this->num_links; a0++) { enc_size += this->link_name[a0].size() + 4 + 1; } enc_size += __int32_t_encoded_array_size(NULL, this->num_links); enc_size += this->num_links * __float_encoded_array_size(NULL, 3); enc_size += this->num_links * __float_encoded_array_size(NULL, 4); return enc_size; } int64_t lcmt_viewer_draw::_computeHash(const __lcm_hash_ptr *) { int64_t hash = 0x20a785ff2d97a122LL; return (hash<<1) + ((hash>>63)&1); } } #endif
31.494681
109
0.630468
ericmanzi
49198bef6748357995d737585a3a125683391cd6
5,281
cpp
C++
src/commands.cpp
rhoot/pantryman
4df649b811f8321efe49893ed69fefb03b0977d6
[ "0BSD" ]
7
2021-01-30T01:27:24.000Z
2021-11-14T20:32:01.000Z
src/commands.cpp
rhoot/pantryman
4df649b811f8321efe49893ed69fefb03b0977d6
[ "0BSD" ]
null
null
null
src/commands.cpp
rhoot/pantryman
4df649b811f8321efe49893ed69fefb03b0977d6
[ "0BSD" ]
null
null
null
// // Copyright (c) 2018 Johan Sköld // License: https://opensource.org/licenses/ISC // #include "commands.hpp" #include "config.hpp" #include <cassert> #include <cstring> #include <algorithm> namespace pm { HostCommand::HostCommand() { } HostCommands::HostCommands() : m_buffer{PM_CONFIG_COMMAND_BUFFER_SIZE} { } bool HostCommands::nextCommand(HostCommand* cmd) { if (!m_buffer.beginRead()) { return false; } cmd->type = m_buffer.read<HostCommand::Type>(); switch (cmd->type) { case HostCommand::CREATE_WINDOW: { cmd->createWindow.handle = m_buffer.read<WindowHandle>(); cmd->createWindow.width = m_buffer.read<uint16_t>(); cmd->createWindow.height = m_buffer.read<uint16_t>(); cmd->createWindow.state = m_buffer.read<WindowState>(); cmd->createWindow.style = m_buffer.read<WindowStyle>(); const uint16_t titleLen = m_buffer.read<uint16_t>(); m_buffer.read(cmd->createWindow.title, 1, titleLen); cmd->createWindow.title[titleLen] = 0; break; } case HostCommand::DESTROY_WINDOW: cmd->windowHandle = m_buffer.read<WindowHandle>(); break; case HostCommand::EXECUTE: cmd->execute.function = m_buffer.read<ExecuteFn>(); cmd->execute.userPointer = m_buffer.read<void*>(); break; case HostCommand::SET_CALLBACK: cmd->callback.index = m_buffer.read<uint16_t>(); cmd->callback.function = m_buffer.read<ExecuteFn>(); cmd->callback.userPointer = m_buffer.read<void*>(); break; case HostCommand::SET_WINDOW_SIZE: cmd->windowSize.handle = m_buffer.read<WindowHandle>(); cmd->windowSize.width = m_buffer.read<uint16_t>(); cmd->windowSize.height = m_buffer.read<uint16_t>(); break; case HostCommand::SET_WINDOW_STATE: cmd->windowState.handle = m_buffer.read<WindowHandle>(); cmd->windowState.state = m_buffer.read<WindowState>(); break; case HostCommand::SET_WINDOW_STYLE: cmd->windowStyle.handle = m_buffer.read<WindowHandle>(); cmd->windowStyle.style = m_buffer.read<WindowStyle>(); break; case HostCommand::STOP: break; default: assert(!"invalid command type"); _Exit(1); } m_buffer.endRead(); return true; } void HostCommands::sendCreateWindow(WindowHandle handle, const WindowParams& params) { uint16_t titleLen = uint16_t(std::strlen(params.title)); if (titleLen > MAX_WINDOW_TITLE_LEN) { titleLen = MAX_WINDOW_TITLE_LEN; } m_buffer.beginWrite(); m_buffer.write(HostCommand::CREATE_WINDOW); m_buffer.write(handle); m_buffer.write(params.width); m_buffer.write(params.height); m_buffer.write(params.state); m_buffer.write(params.style); m_buffer.write(titleLen); m_buffer.write(params.title, 1, titleLen); m_buffer.endWrite(); } void HostCommands::sendDestroyWindow(WindowHandle handle) { m_buffer.beginWrite(); m_buffer.write(HostCommand::DESTROY_WINDOW); m_buffer.write(handle); m_buffer.endWrite(); } void HostCommands::sendExecute(ExecuteFn function, void* userPointer) { m_buffer.beginWrite(); m_buffer.write(HostCommand::EXECUTE); m_buffer.write(function); m_buffer.write(userPointer); m_buffer.endWrite(); } void HostCommands::sendSetCallback(uint16_t index, ExecuteFn function, void* userPointer) { m_buffer.beginWrite(); m_buffer.write(HostCommand::SET_CALLBACK); m_buffer.write(index); m_buffer.write(function); m_buffer.write(userPointer); m_buffer.endWrite(); } void HostCommands::sendSetWindowSize(WindowHandle handle, uint16_t width, uint16_t height) { m_buffer.beginWrite(); m_buffer.write(HostCommand::SET_WINDOW_SIZE); m_buffer.write(handle); m_buffer.write(width); m_buffer.write(height); m_buffer.endWrite(); } void HostCommands::sendSetWindowState(WindowHandle handle, WindowState state) { m_buffer.beginWrite(); m_buffer.write(HostCommand::SET_WINDOW_STATE); m_buffer.write(handle); m_buffer.write(state); m_buffer.endWrite(); } void HostCommands::sendSetWindowStyle(WindowHandle handle, WindowStyle style) { m_buffer.beginWrite(); m_buffer.write(HostCommand::SET_WINDOW_STYLE); m_buffer.write(handle); m_buffer.write(style); m_buffer.endWrite(); } void HostCommands::sendStop() { m_buffer.beginWrite(); m_buffer.write(HostCommand::STOP); m_buffer.endWrite(); } } // namespace pm
30.005682
94
0.589093
rhoot
491c7e635e7a39b17f3b6f7ca37a096e82866725
738
cpp
C++
UnLive2DAsset/Source/UnLive2DAsset/Private/UnLive2DMotion.cpp
Monocluar/UnLive2D
f4e255d3d5c12ebd56f6b248c65db7ffb7f58571
[ "MIT" ]
null
null
null
UnLive2DAsset/Source/UnLive2DAsset/Private/UnLive2DMotion.cpp
Monocluar/UnLive2D
f4e255d3d5c12ebd56f6b248c65db7ffb7f58571
[ "MIT" ]
null
null
null
UnLive2DAsset/Source/UnLive2DAsset/Private/UnLive2DMotion.cpp
Monocluar/UnLive2D
f4e255d3d5c12ebd56f6b248c65db7ffb7f58571
[ "MIT" ]
null
null
null
#include "UnLive2DMotion.h" #include "Misc/FileHelper.h" #if WITH_EDITOR bool UUnLive2DMotion::LoadLive2DMotionData(const FString& ReadMotionPath, EUnLive2DMotionGroup InMotionGroupType, int32 InMotionCount, float FadeInTime, float FadeOutTime) { const bool ReadSuc = FFileHelper::LoadFileToArray(MotionData.MotionByteData, *ReadMotionPath); MotionData.FadeInTime = FadeInTime; MotionData.FadeOutTime = FadeOutTime; MotionData.MotionCount = InMotionCount; MotionData.MotionGroupType = InMotionGroupType; return ReadSuc; } void UUnLive2DMotion::SetLive2DMotionData(FUnLive2DMotionData& InMotionData) { MotionData = InMotionData; } #endif const FUnLive2DMotionData* UUnLive2DMotion::GetMotionData() { return &MotionData; }
23.806452
171
0.817073
Monocluar
491d4d9781e754486e2d6adee12d3b075a0aa0c8
734
hpp
C++
src/interfaces/json_storage.hpp
aahmed-2/telemetry
7e098e93ef0974739459d296f99ddfab54722c23
[ "Apache-2.0" ]
4
2019-11-14T10:41:34.000Z
2021-12-09T23:54:52.000Z
src/interfaces/json_storage.hpp
aahmed-2/telemetry
7e098e93ef0974739459d296f99ddfab54722c23
[ "Apache-2.0" ]
2
2021-10-04T20:12:53.000Z
2021-12-14T18:13:03.000Z
src/interfaces/json_storage.hpp
aahmed-2/telemetry
7e098e93ef0974739459d296f99ddfab54722c23
[ "Apache-2.0" ]
2
2021-08-05T11:17:03.000Z
2021-12-13T15:22:48.000Z
#pragma once #include <boost/serialization/strong_typedef.hpp> #include <nlohmann/json.hpp> #include <filesystem> #include <optional> #include <string> namespace interfaces { class JsonStorage { public: BOOST_STRONG_TYPEDEF(std::filesystem::path, FilePath) BOOST_STRONG_TYPEDEF(std::filesystem::path, DirectoryPath) virtual ~JsonStorage() = default; virtual void store(const FilePath& subPath, const nlohmann::json& data) = 0; virtual bool remove(const FilePath& subPath) = 0; virtual bool exist(const FilePath& path) const = 0; virtual std::optional<nlohmann::json> load(const FilePath& subPath) const = 0; virtual std::vector<FilePath> list() const = 0; }; } // namespace interfaces
24.466667
80
0.719346
aahmed-2
491db81b8315955dbd6a8777eb20a33854432efc
107,574
cc
C++
sandboxed_api/sandbox2/syscall_defs.cc
oshogbo/sandboxed-api
8e82b900f4d873219b3abfa2fd06ecbd416edefd
[ "Apache-2.0" ]
1,562
2019-03-07T10:02:53.000Z
2022-03-31T17:43:05.000Z
sandboxed_api/sandbox2/syscall_defs.cc
oshogbo/sandboxed-api
8e82b900f4d873219b3abfa2fd06ecbd416edefd
[ "Apache-2.0" ]
70
2019-03-19T01:02:49.000Z
2022-03-30T17:26:53.000Z
sandboxed_api/sandbox2/syscall_defs.cc
oshogbo/sandboxed-api
8e82b900f4d873219b3abfa2fd06ecbd416edefd
[ "Apache-2.0" ]
181
2019-03-18T19:41:30.000Z
2022-03-29T13:08:26.000Z
#include "sandboxed_api/sandbox2/syscall_defs.h" #include <cstdint> #include <type_traits> #include <glog/logging.h> #include "absl/algorithm/container.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "sandboxed_api/config.h" #include "sandboxed_api/sandbox2/util.h" namespace sandbox2 { // Type of a given syscall argument. Used with argument conversion routines. enum ArgType { kGen = 1, kInt, kPath, kHex, kOct, kSocketCall, kSocketCallPtr, kSignal, kString, kAddressFamily, kSockaddr, kSockmsghdr, kCloneFlag, }; // Single syscall definition struct SyscallTable::Entry { // Returns the number of arguments which given syscall takes. int GetNumArgs() const { if (num_args < 0 || num_args > syscalls::kMaxArgs) { return syscalls::kMaxArgs; } return num_args; } static std::string GetArgumentDescription(uint64_t value, ArgType type, pid_t pid); std::vector<std::string> GetArgumentsDescription( const uint64_t values[syscalls::kMaxArgs], pid_t pid) const; static constexpr bool BySyscallNr(const SyscallTable::Entry& a, const SyscallTable::Entry& b) { return a.nr < b.nr; } int nr; absl::string_view name; int num_args; std::array<ArgType, syscalls::kMaxArgs> arg_types; }; std::string SyscallTable::Entry::GetArgumentDescription(uint64_t value, ArgType type, pid_t pid) { std::string ret = absl::StrFormat("%#x", value); switch (type) { case kOct: absl::StrAppendFormat(&ret, " [\\0%o]", value); break; case kPath: if (auto path_or = util::ReadCPathFromPid(pid, value); path_or.ok()) { absl::StrAppendFormat(&ret, " ['%s']", absl::CHexEscape(path_or.value())); } else { absl::StrAppend(&ret, " [unreadable path]"); } break; case kInt: absl::StrAppendFormat(&ret, " [%d]", value); break; default: break; } return ret; } absl::string_view SyscallTable::GetName(int syscall) const { auto it = absl::c_lower_bound( data_, syscall, [](const SyscallTable::Entry& entry, int syscall) { return entry.nr < syscall; }); if (it == data_.end() || it->nr != syscall) { return ""; } return it->name; } namespace { template <typename... ArgTypes> constexpr SyscallTable::Entry MakeEntry(int nr, absl::string_view name, ArgTypes... arg_types) { static_assert(sizeof...(arg_types) <= syscalls::kMaxArgs, "Too many arguments for syscall"); return {nr, name, sizeof...(arg_types), {arg_types...}}; } struct UnknownArguments {}; constexpr SyscallTable::Entry MakeEntry(int nr, absl::string_view name, UnknownArguments) { return {nr, name, -1, {kGen, kGen, kGen, kGen, kGen, kGen}}; } } // namespace std::vector<std::string> SyscallTable::GetArgumentsDescription( int syscall, const uint64_t values[], pid_t pid) const { static SyscallTable::Entry kInvalidEntry = MakeEntry(-1, "", UnknownArguments()); auto it = absl::c_lower_bound( data_, syscall, [](const SyscallTable::Entry& entry, int syscall) { return entry.nr < syscall; }); const auto& entry = it != data_.end() && it->nr == syscall ? *it : kInvalidEntry; int num_args = entry.GetNumArgs(); std::vector<std::string> rv; rv.reserve(num_args); for (int i = 0; i < num_args; ++i) { rv.push_back(SyscallTable::Entry::GetArgumentDescription( values[i], entry.arg_types[i], pid)); } return rv; } namespace { // TODO(C++20) Use std::is_sorted template <typename Container, typename Compare> constexpr bool IsSorted(const Container& container, Compare comp) { auto it = std::begin(container); if (it == std::end(container)) { return true; } auto last = it; for (++it; it != std::end(container); ++it) { if (!comp(*last, *it)) { return false; } last = it; } return true; } // Syscall description table for Linux x86_64 constexpr std::array kSyscallDataX8664 = { // clang-format off MakeEntry(0, "read", kInt, kHex, kInt), MakeEntry(1, "write", kInt, kHex, kInt), MakeEntry(2, "open", kPath, kHex, kOct), MakeEntry(3, "close", kInt), MakeEntry(4, "stat", kPath, kGen), MakeEntry(5, "fstat", kInt, kHex), MakeEntry(6, "lstat", kPath, kGen), MakeEntry(7, "poll", kGen, kInt, kInt), MakeEntry(8, "lseek", kInt, kInt, kInt), MakeEntry(9, "mmap", kHex, kInt, kHex, kHex, kInt, kInt), MakeEntry(10, "mprotect", kHex, kInt, kHex), MakeEntry(11, "munmap", kHex, kInt), MakeEntry(12, "brk", kInt), MakeEntry(13, "rt_sigaction", kSignal, kHex, kHex, kInt), MakeEntry(14, "rt_sigprocmask", kInt, kHex, kHex, kInt), MakeEntry(15, "rt_sigreturn"), MakeEntry(16, "ioctl", kInt, kInt, kHex), MakeEntry(17, "pread64", kInt, kHex, kInt, kInt), MakeEntry(18, "pwrite64", kInt, kHex, kInt, kInt), MakeEntry(19, "readv", kInt, kHex, kInt), MakeEntry(20, "writev", kInt, kHex, kInt), MakeEntry(21, "access", kPath, kOct), MakeEntry(22, "pipe", kHex), MakeEntry(23, "select", kInt, kHex, kHex, kHex, kHex), MakeEntry(24, "sched_yield"), MakeEntry(25, "mremap", kHex, kInt, kInt, kInt, kHex), MakeEntry(26, "msync", kHex, kInt, kInt), MakeEntry(27, "mincore", kHex, kInt, kHex), MakeEntry(28, "madvise", kHex, kInt, kInt), MakeEntry(29, "shmget", kInt, kInt, kHex), MakeEntry(30, "shmat", kInt, kHex, kHex), MakeEntry(31, "shmctl", kInt, kInt, kHex), MakeEntry(32, "dup", kInt), MakeEntry(33, "dup2", kInt, kInt), MakeEntry(34, "pause"), MakeEntry(35, "nanosleep", kHex, kHex), MakeEntry(36, "getitimer", kInt, kHex), MakeEntry(37, "alarm", kInt), MakeEntry(38, "setitimer", kInt, kHex, kHex), MakeEntry(39, "getpid"), MakeEntry(40, "sendfile", kInt, kInt, kHex, kInt), MakeEntry(41, "socket", kAddressFamily, kInt, kInt), MakeEntry(42, "connect", kInt, kSockaddr, kInt), MakeEntry(43, "accept", kInt, kSockaddr, kHex), MakeEntry(44, "sendto", kInt, kHex, kInt, kHex, kSockaddr, kInt), MakeEntry(45, "recvfrom", kInt, kHex, kInt, kHex, kSockaddr, kHex), MakeEntry(46, "sendmsg", kInt, kSockmsghdr, kHex), MakeEntry(47, "recvmsg", kInt, kHex, kInt), MakeEntry(48, "shutdown", kInt, kInt), MakeEntry(49, "bind", kInt, kSockaddr, kInt), MakeEntry(50, "listen", kInt, kInt), MakeEntry(51, "getsockname", kInt, kSockaddr, kHex), MakeEntry(52, "getpeername", kInt, kSockaddr, kHex), MakeEntry(53, "socketpair", kAddressFamily, kInt, kInt, kHex), MakeEntry(54, "setsockopt", kInt, kInt, kInt, kHex, kHex), MakeEntry(55, "getsockopt", kInt, kInt, kInt, kHex, kInt), MakeEntry(56, "clone", kCloneFlag, kHex, kHex, kHex, kHex), MakeEntry(57, "fork"), MakeEntry(58, "vfork"), MakeEntry(59, "execve", kPath, kHex, kHex), MakeEntry(60, "exit", kInt), MakeEntry(61, "wait4", kInt, kHex, kHex, kHex), MakeEntry(62, "kill", kInt, kSignal), MakeEntry(63, "uname", kInt), MakeEntry(64, "semget", kInt, kInt, kHex), MakeEntry(65, "semop", kInt, kHex, kInt), MakeEntry(66, "semctl", kInt, kInt, kInt, kHex), MakeEntry(67, "shmdt", kHex), MakeEntry(68, "msgget", kInt, kHex), MakeEntry(69, "msgsnd", kInt, kHex, kInt, kHex), MakeEntry(70, "msgrcv", kInt, kHex, kInt, kInt, kHex), MakeEntry(71, "msgctl", kInt, kInt, kHex), MakeEntry(72, "fcntl", kInt, kInt, kHex), MakeEntry(73, "flock", kInt, kInt), MakeEntry(74, "fsync", kInt), MakeEntry(75, "fdatasync", kInt), MakeEntry(76, "truncate", kPath, kInt), MakeEntry(77, "ftruncate", kInt, kInt), MakeEntry(78, "getdents", kInt, kHex, kInt), MakeEntry(79, "getcwd", kHex, kInt), MakeEntry(80, "chdir", kPath), MakeEntry(81, "fchdir", kInt), MakeEntry(82, "rename", kPath, kPath), MakeEntry(83, "mkdir", kPath, kOct), MakeEntry(84, "rmdir", kPath), MakeEntry(85, "creat", kPath, kOct), MakeEntry(86, "link", kPath, kPath), MakeEntry(87, "unlink", kPath), MakeEntry(88, "symlink", kPath, kPath), MakeEntry(89, "readlink", kPath, kHex, kInt), MakeEntry(90, "chmod", kPath, kOct), MakeEntry(91, "fchmod", kInt, kOct), MakeEntry(92, "chown", kPath, kInt, kInt), MakeEntry(93, "fchown", kInt, kInt, kInt), MakeEntry(94, "lchown", kPath, kInt, kInt), MakeEntry(95, "umask", kHex), MakeEntry(96, "gettimeofday", kHex, kHex), MakeEntry(97, "getrlimit", kInt, kHex), MakeEntry(98, "getrusage", kInt, kHex), MakeEntry(99, "sysinfo", kHex), MakeEntry(100, "times", kHex), MakeEntry(101, "ptrace", kInt, kInt, kHex, kHex), MakeEntry(102, "getuid"), MakeEntry(103, "syslog", kInt, kHex, kInt), MakeEntry(104, "getgid"), MakeEntry(105, "setuid", kInt), MakeEntry(106, "setgid", kInt), MakeEntry(107, "geteuid"), MakeEntry(108, "getegid"), MakeEntry(109, "setpgid", kInt, kInt), MakeEntry(110, "getppid"), MakeEntry(111, "getpgrp"), MakeEntry(112, "setsid"), MakeEntry(113, "setreuid", kInt, kInt), MakeEntry(114, "setregid", kInt, kInt), MakeEntry(115, "getgroups", kInt, kHex), MakeEntry(116, "setgroups", kInt, kHex), MakeEntry(117, "setresuid", kInt, kInt, kInt), MakeEntry(118, "getresuid", kHex, kHex, kHex), MakeEntry(119, "setresgid", kInt, kInt, kInt), MakeEntry(120, "getresgid", kHex, kHex, kHex), MakeEntry(121, "getpgid", kInt), MakeEntry(122, "setfsuid", kInt), MakeEntry(123, "setfsgid", kInt), MakeEntry(124, "getsid", kInt), MakeEntry(125, "capget", kHex, kHex), MakeEntry(126, "capset", kHex, kHex), MakeEntry(127, "rt_sigpending", kHex, kInt), MakeEntry(128, "rt_sigtimedwait", kHex, kHex, kHex, kInt), MakeEntry(129, "rt_sigqueueinfo", kInt, kSignal, kHex), MakeEntry(130, "rt_sigsuspend", kHex, kInt), MakeEntry(131, "sigaltstack", kHex, kHex), MakeEntry(132, "utime", kPath, kHex), MakeEntry(133, "mknod", kPath, kOct, kHex), MakeEntry(134, "uselib", kPath), MakeEntry(135, "personality", kHex), MakeEntry(136, "ustat", kHex, kHex), MakeEntry(137, "statfs", kPath, kHex), MakeEntry(138, "fstatfs", kInt, kHex), MakeEntry(139, "sysfs", kInt, kInt, kInt), MakeEntry(140, "getpriority", kInt, kInt), MakeEntry(141, "setpriority", kInt, kInt, kInt), MakeEntry(142, "sched_setparam", kInt, kHex), MakeEntry(143, "sched_getparam", kInt, kHex), MakeEntry(144, "sched_setscheduler", kInt, kInt, kHex), MakeEntry(145, "sched_getscheduler", kInt), MakeEntry(146, "sched_get_priority_max", kInt), MakeEntry(147, "sched_get_priority_min", kInt), MakeEntry(148, "sched_rr_get_interval", kInt, kHex), MakeEntry(149, "mlock", kInt, kInt), MakeEntry(150, "munlock", kInt, kInt), MakeEntry(151, "mlockall", kHex), MakeEntry(152, "munlockall"), MakeEntry(153, "vhangup"), MakeEntry(154, "modify_ldt", kInt, kHex, kInt), MakeEntry(155, "pivot_root", kPath, kPath), MakeEntry(156, "_sysctl", kHex), MakeEntry(157, "prctl", kInt, kHex, kHex, kHex, kHex), MakeEntry(158, "arch_prctl", kInt, kHex), MakeEntry(159, "adjtimex", kHex), MakeEntry(160, "setrlimit", kInt, kHex), MakeEntry(161, "chroot", kPath), MakeEntry(162, "sync"), MakeEntry(163, "acct", kPath), MakeEntry(164, "settimeofday", kHex, kHex), MakeEntry(165, "mount", kPath, kPath, kString, kHex, kGen), MakeEntry(166, "umount2", kPath, kHex), MakeEntry(167, "swapon", kPath, kHex), MakeEntry(168, "swapoff", kPath), MakeEntry(169, "reboot", kInt, kHex, kHex, kGen), MakeEntry(170, "sethostname", kString, kInt), MakeEntry(171, "setdomainname", kString, kInt), MakeEntry(172, "iopl", kInt), MakeEntry(173, "ioperm", kInt, kInt, kInt), MakeEntry(174, "create_module", kString, kInt), MakeEntry(175, "init_module", kGen, kInt, kString), MakeEntry(176, "delete_module", kString, kHex), MakeEntry(177, "get_kernel_syms", kHex), MakeEntry(178, "query_module", kString, kInt, kGen, kInt, kGen), MakeEntry(179, "quotactl", kInt, kPath, kInt, kGen), MakeEntry(180, "nfsservctl", kInt, kGen, kGen), MakeEntry(181, "getpmsg", UnknownArguments()), MakeEntry(182, "putpmsg", UnknownArguments()), MakeEntry(183, "afs_syscall", UnknownArguments()), MakeEntry(184, "tuxcall", UnknownArguments()), MakeEntry(185, "security", UnknownArguments()), MakeEntry(186, "gettid"), MakeEntry(187, "readahead", kInt, kInt, kInt), MakeEntry(188, "setxattr", kPath, kString, kGen, kInt, kHex), MakeEntry(189, "lsetxattr", kPath, kString, kGen, kInt, kHex), MakeEntry(190, "fsetxattr", kInt, kString, kGen, kInt, kHex), MakeEntry(191, "getxattr", kPath, kString, kGen, kInt), MakeEntry(192, "lgetxattr", kPath, kString, kGen, kInt), MakeEntry(193, "fgetxattr", kInt, kString, kGen, kInt), MakeEntry(194, "listxattr", kPath, kGen, kInt), MakeEntry(195, "llistxattr", kPath, kGen, kInt), MakeEntry(196, "flistxattr", kInt, kGen, kInt), MakeEntry(197, "removexattr", kPath, kString), MakeEntry(198, "lremovexattr", kPath, kString), MakeEntry(199, "fremovexattr", kInt, kString), MakeEntry(200, "tkill", kInt, kSignal), MakeEntry(201, "time", kHex), MakeEntry(202, "futex", kGen, kInt, kInt, kGen, kGen, kInt), MakeEntry(203, "sched_setaffinity", kInt, kInt, kHex), MakeEntry(204, "sched_getaffinity", kInt, kInt, kHex), MakeEntry(205, "set_thread_area", kHex), MakeEntry(206, "io_setup", kInt, kHex), MakeEntry(207, "io_destroy", kInt), MakeEntry(208, "io_getevents", kInt, kInt, kInt, kHex, kHex), MakeEntry(209, "io_submit", kInt, kInt, kHex), MakeEntry(210, "io_cancel", kInt, kHex, kHex), MakeEntry(211, "get_thread_area", kHex), MakeEntry(212, "lookup_dcookie", kInt, kString, kInt), MakeEntry(213, "epoll_create", kInt), MakeEntry(214, "epoll_ctl_old", UnknownArguments()), MakeEntry(215, "epoll_wait_old", UnknownArguments()), MakeEntry(216, "remap_file_pages", kGen, kInt, kInt, kInt, kHex), MakeEntry(217, "getdents64", kInt, kHex, kInt), MakeEntry(218, "set_tid_address", kHex), MakeEntry(219, "restart_syscall"), MakeEntry(220, "semtimedop", kInt, kHex, kInt, kHex), MakeEntry(221, "fadvise64", kInt, kInt, kInt, kInt), MakeEntry(222, "timer_create", kInt, kHex, kHex), MakeEntry(223, "timer_settime", kInt, kHex, kHex, kHex), MakeEntry(224, "timer_gettime", kInt, kHex), MakeEntry(225, "timer_getoverrun", kInt), MakeEntry(226, "timer_delete", kInt), MakeEntry(227, "clock_settime", kInt, kHex), MakeEntry(228, "clock_gettime", kInt, kHex), MakeEntry(229, "clock_getres", kInt, kHex), MakeEntry(230, "clock_nanosleep", kInt, kHex, kHex, kHex), MakeEntry(231, "exit_group", kInt), MakeEntry(232, "epoll_wait", kInt, kHex, kInt, kInt), MakeEntry(233, "epoll_ctl", kInt, kInt, kInt, kHex), MakeEntry(234, "tgkill", kInt, kInt, kSignal), MakeEntry(235, "utimes", kPath, kHex), MakeEntry(236, "vserver", UnknownArguments()), MakeEntry(237, "mbind", kGen, kInt, kInt, kHex, kInt, kHex), MakeEntry(238, "set_mempolicy", kInt, kHex, kInt), MakeEntry(239, "get_mempolicy", kInt, kHex, kInt, kInt, kHex), MakeEntry(240, "mq_open", kString, kHex, kOct, kHex), MakeEntry(241, "mq_unlink", kString), MakeEntry(242, "mq_timedsend", kHex, kHex, kInt, kInt, kHex), MakeEntry(243, "mq_timedreceive", kHex, kHex, kInt, kHex, kHex), MakeEntry(244, "mq_notify", kHex, kHex), MakeEntry(245, "mq_getsetattr", kHex, kHex, kHex), MakeEntry(246, "kexec_load", kHex, kInt, kHex, kHex), MakeEntry(247, "waitid", kInt, kInt, kHex, kInt, kHex), MakeEntry(248, "add_key", kString, kString, kGen, kInt, kInt), MakeEntry(249, "request_key", kString, kString, kHex, kInt), MakeEntry(250, "keyctl", kInt, kInt, kInt, kInt, kInt), MakeEntry(251, "ioprio_set", kInt, kInt, kInt), MakeEntry(252, "ioprio_get", kInt, kInt), MakeEntry(253, "inotify_init"), MakeEntry(254, "inotify_add_watch", kInt, kPath, kHex), MakeEntry(255, "inotify_rm_watch", kInt, kInt), MakeEntry(256, "migrate_pages", kInt, kInt, kHex, kHex), MakeEntry(257, "openat", kInt, kPath, kHex, kOct), MakeEntry(258, "mkdirat", kInt, kPath, kOct), MakeEntry(259, "mknodat", kInt, kPath, kOct, kHex), MakeEntry(260, "fchownat", kInt, kPath, kInt, kInt, kHex), MakeEntry(261, "futimesat", kInt, kPath, kHex), MakeEntry(262, "newfstatat", kInt, kPath, kHex, kHex), MakeEntry(263, "unlinkat", kInt, kPath, kHex), MakeEntry(264, "renameat", kInt, kPath, kInt, kPath), MakeEntry(265, "linkat", kInt, kPath, kInt, kPath, kHex), MakeEntry(266, "symlinkat", kPath, kInt, kPath), MakeEntry(267, "readlinkat", kInt, kPath, kHex, kInt), MakeEntry(268, "fchmodat", kInt, kPath, kOct), MakeEntry(269, "faccessat", kInt, kPath, kInt, kHex), MakeEntry(270, "pselect6", kInt, kHex, kHex, kHex, kHex), MakeEntry(271, "ppoll", kHex, kInt, kHex, kHex, kInt), MakeEntry(272, "unshare", kHex), MakeEntry(273, "set_robust_list", kHex, kInt), MakeEntry(274, "get_robust_list", kInt, kHex, kHex), MakeEntry(275, "splice", kInt, kHex, kInt, kHex, kInt, kHex), MakeEntry(276, "tee", kInt, kInt, kInt, kHex), MakeEntry(277, "sync_file_range", kInt, kInt, kInt, kHex), MakeEntry(278, "vmsplice", kInt, kHex, kInt, kInt), MakeEntry(279, "move_pages", kInt, kInt, kHex, kHex, kHex, kHex), MakeEntry(280, "utimensat", kInt, kPath, kHex, kHex), MakeEntry(281, "epoll_pwait", kInt, kHex, kInt, kInt, kHex, kInt), MakeEntry(282, "signalfd", kInt, kHex, kHex), MakeEntry(283, "timerfd_create", kInt, kHex), MakeEntry(284, "eventfd", kInt), MakeEntry(285, "fallocate", kInt, kOct, kInt, kInt), MakeEntry(286, "timerfd_settime", kInt, kHex, kHex, kHex), MakeEntry(287, "timerfd_gettime", kInt, kHex), MakeEntry(288, "accept4", kInt, kHex, kHex, kInt), MakeEntry(289, "signalfd4", kInt, kHex, kHex, kHex), MakeEntry(290, "eventfd2", kInt, kHex), MakeEntry(291, "epoll_create1", kHex), MakeEntry(292, "dup3", kInt, kInt, kHex), MakeEntry(293, "pipe2", kHex, kHex), MakeEntry(294, "inotify_init1", kHex), MakeEntry(295, "preadv", kInt, kHex, kInt, kInt, kInt), MakeEntry(296, "pwritev", kInt, kHex, kInt, kInt, kInt), MakeEntry(297, "rt_tgsigqueueinfo", kInt, kInt, kInt, kHex), MakeEntry(298, "perf_event_open", kHex, kInt, kInt, kInt, kHex), MakeEntry(299, "recvmmsg", kInt, kHex, kInt, kHex, kHex), MakeEntry(300, "fanotify_init", kHex, kHex), MakeEntry(301, "fanotify_mark", kInt, kHex, kHex, kInt, kPath), MakeEntry(302, "prlimit64", kInt, kInt, kHex, kHex), MakeEntry(303, "name_to_handle_at", kInt, kPath, kHex, kHex, kHex), MakeEntry(304, "open_by_handle_at", kInt, kHex, kHex), MakeEntry(305, "clock_adjtime", kInt, kHex), MakeEntry(306, "syncfs", kInt), MakeEntry(307, "sendmmsg", kInt, kHex, kInt, kHex), MakeEntry(308, "setns", kInt, kHex), MakeEntry(309, "getcpu", kHex, kHex, kHex), MakeEntry(310, "process_vm_readv", kInt, kHex, kInt, kHex, kInt, kInt), MakeEntry(311, "process_vm_writev", kInt, kHex, kInt, kHex, kInt, kInt), MakeEntry(312, "kcmp", kInt, kInt, kInt, kInt, kInt), MakeEntry(313, "finit_module", kInt, kString, kHex), MakeEntry(314, "sched_setattr", kInt, kHex, kHex), MakeEntry(315, "sched_getattr", kInt, kHex, kInt, kHex), MakeEntry(316, "renameat2", kInt, kPath, kInt, kPath, kHex), MakeEntry(317, "seccomp", kInt, kHex, kHex), MakeEntry(318, "getrandom", kGen, kInt, kHex), MakeEntry(319, "memfd_create", kString, kHex), MakeEntry(320, "kexec_file_load", kInt, kInt, kInt, kString, kHex), MakeEntry(321, "bpf", kInt, kHex, kInt), MakeEntry(322, "execveat", kInt, kPath, kHex, kHex, kHex), MakeEntry(323, "userfaultfd", kHex), MakeEntry(324, "membarrier", kInt, kHex), MakeEntry(325, "mlock2", kHex, kInt, kHex), MakeEntry(326, "copy_file_range", kInt, kHex, kInt, kHex, kInt, kHex), MakeEntry(327, "preadv2", kInt, kHex, kInt, kInt, kInt, kHex), MakeEntry(328, "pwritev2", kInt, kHex, kInt, kInt, kInt, kHex), MakeEntry(329, "pkey_mprotect", kInt, kInt, kHex, kInt), MakeEntry(330, "pkey_alloc", kInt, kInt), MakeEntry(331, "pkey_free", kInt), MakeEntry(332, "statx", kInt, kPath, kHex, kHex, kHex), MakeEntry(333, "io_pgetevents", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(334, "rseq", kHex, kInt, kHex, kHex), // clang-format on }; static_assert(IsSorted(kSyscallDataX8664, SyscallTable::Entry::BySyscallNr), "Syscalls should be sorted"); constexpr std::array kSyscallDataX8632 = { // clang-format off MakeEntry(0, "restart_syscall", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(1, "exit", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(2, "fork", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(3, "read", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(4, "write", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(5, "open", kPath, kHex, kOct, kHex, kHex, kHex), MakeEntry(6, "close", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(7, "waitpid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(8, "creat", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(9, "link", kPath, kPath, kHex, kHex, kHex, kHex), MakeEntry(10, "unlink", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(11, "execve", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(12, "chdir", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(13, "time", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(14, "mknod", kPath, kOct, kHex, kHex, kHex, kHex), MakeEntry(15, "chmod", kPath, kOct, kHex, kHex, kHex, kHex), MakeEntry(16, "lchown", kPath, kInt, kInt, kHex, kHex, kHex), MakeEntry(17, "break", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(18, "oldstat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(19, "lseek", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(20, "getpid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(21, "mount", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(22, "umount", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(23, "setuid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(24, "getuid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(25, "stime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(26, "ptrace", kHex, kHex, kHex, kHex), MakeEntry(27, "alarm", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(28, "oldfstat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(29, "pause", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(30, "utime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(31, "stty", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(32, "gtty", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(33, "access", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(34, "nice", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(35, "ftime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(36, "sync", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(37, "kill", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(38, "rename", kPath, kPath, kHex, kHex, kHex, kHex), MakeEntry(39, "mkdir", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(40, "rmdir", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(41, "dup", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(42, "pipe", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(43, "times", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(44, "prof", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(45, "brk", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(46, "setgid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(47, "getgid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(48, "signal", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(49, "geteuid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(50, "getegid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(51, "acct", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(52, "umount2", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(53, "lock", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(54, "ioctl", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(55, "fcntl", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(56, "mpx", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(57, "setpgid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(58, "ulimit", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(59, "oldolduname", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(60, "umask", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(61, "chroot", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(62, "ustat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(63, "dup2", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(64, "getppid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(65, "getpgrp", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(66, "setsid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(67, "sigaction", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(68, "sgetmask", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(69, "ssetmask", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(70, "setreuid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(71, "setregid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(72, "sigsuspend", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(73, "sigpending", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(74, "sethostname", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(75, "setrlimit", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(76, "getrlimit", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(77, "getrusage", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(78, "gettimeofday", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(79, "settimeofday", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(80, "getgroups", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(81, "setgroups", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(82, "select", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(83, "symlink", kPath, kPath, kHex, kHex, kHex, kHex), MakeEntry(84, "oldlstat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(85, "readlink", kPath, kHex, kInt, kHex, kHex, kHex), MakeEntry(86, "uselib", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(87, "swapon", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(88, "reboot", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(89, "readdir", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(90, "mmap", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(91, "munmap", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(92, "truncate", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(93, "ftruncate", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(94, "fchmod", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(95, "fchown", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(96, "getpriority", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(97, "setpriority", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(98, "profil", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(99, "statfs", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(100, "fstatfs", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(101, "ioperm", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(102, "socketcall", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(103, "syslog", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(104, "setitimer", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(105, "getitimer", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(106, "stat", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(107, "lstat", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(108, "fstat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(109, "olduname", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(110, "iopl", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(111, "vhangup", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(112, "idle", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(113, "vm86old", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(114, "wait4", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(115, "swapoff", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(116, "sysinfo", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(117, "ipc", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(118, "fsync", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(119, "sigreturn", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(120, "clone", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(121, "setdomainname", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(122, "uname", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(123, "modify_ldt", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(124, "adjtimex", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(125, "mprotect", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(126, "sigprocmask", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(127, "create_module", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(128, "init_module", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(129, "delete_module", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(130, "get_kernel_syms", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(131, "quotactl", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(132, "getpgid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(133, "fchdir", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(134, "bdflush", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(135, "sysfs", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(136, "personality", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(137, "afs_syscall", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(138, "setfsuid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(139, "setfsgid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(140, "_llseek", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(141, "getdents", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(142, "_newselect", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(143, "flock", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(144, "msync", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(145, "readv", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(146, "writev", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(147, "getsid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(148, "fdatasync", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(149, "_sysctl", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(150, "mlock", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(151, "munlock", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(152, "mlockall", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(153, "munlockall", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(154, "sched_setparam", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(155, "sched_getparam", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(156, "sched_setscheduler", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(157, "sched_getscheduler", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(158, "sched_yield", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(159, "sched_get_priority_max", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(160, "sched_get_priority_min", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(161, "sched_rr_get_interval", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(162, "nanosleep", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(163, "mremap", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(164, "setresuid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(165, "getresuid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(166, "vm86", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(167, "query_module", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(168, "poll", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(169, "nfsservctl", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(170, "setresgid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(171, "getresgid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(172, "prctl", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(173, "rt_sigreturn", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(174, "rt_sigaction", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(175, "rt_sigprocmask", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(176, "rt_sigpending", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(177, "rt_sigtimedwait", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(178, "rt_sigqueueinfo", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(179, "rt_sigsuspend", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(180, "pread64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(181, "pwrite64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(182, "chown", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(183, "getcwd", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(184, "capget", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(185, "capset", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(186, "sigaltstack", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(187, "sendfile", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(188, "getpmsg", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(189, "putpmsg", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(190, "vfork", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(191, "ugetrlimit", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(192, "mmap2", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(193, "truncate64", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(194, "ftruncate64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(195, "stat64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(196, "lstat64", kPath, kHex, kHex, kHex, kHex, kHex), MakeEntry(197, "fstat64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(198, "lchown32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(199, "getuid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(200, "getgid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(201, "geteuid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(202, "getegid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(203, "setreuid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(204, "setregid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(205, "getgroups32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(206, "setgroups32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(207, "fchown32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(208, "setresuid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(209, "getresuid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(210, "setresgid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(211, "getresgid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(212, "chown32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(213, "setuid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(214, "setgid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(215, "setfsuid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(216, "setfsgid32", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(217, "pivot_root", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(218, "mincore", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(219, "madvise", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(220, "getdents64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(221, "fcntl64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(222, "unused1-222", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(223, "unused2-223", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(224, "gettid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(225, "readahead", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(226, "setxattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(227, "lsetxattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(228, "fsetxattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(229, "getxattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(230, "lgetxattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(231, "fgetxattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(232, "listxattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(233, "llistxattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(234, "flistxattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(235, "removexattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(236, "lremovexattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(237, "fremovexattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(238, "tkill", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(239, "sendfile64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(240, "futex", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(241, "sched_setaffinity", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(242, "sched_getaffinity", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(243, "set_thread_area", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(244, "get_thread_area", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(245, "io_setup", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(246, "io_destroy", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(247, "io_getevents", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(248, "io_submit", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(249, "io_cancel", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(250, "fadvise64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(251, "251-old_sys_set_zone_reclaim", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(252, "exit_group", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(253, "lookup_dcookie", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(254, "epoll_create", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(255, "epoll_ctl", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(256, "epoll_wait", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(257, "remap_file_pages", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(258, "set_tid_address", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(259, "timer_create", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(260, "timer_settime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(261, "timer_gettime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(262, "timer_getoverrun", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(263, "timer_delete", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(264, "clock_settime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(265, "clock_gettime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(266, "clock_getres", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(267, "clock_nanosleep", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(268, "statfs64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(269, "fstatfs64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(270, "tgkill", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(271, "utimes", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(272, "fadvise64_64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(273, "vserver", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(274, "mbind", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(275, "get_mempolicy", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(276, "set_mempolicy", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(277, "mq_open", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(278, "mq_unlink", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(279, "mq_timedsend", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(280, "mq_timedreceive", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(281, "mq_notify", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(282, "mq_getsetattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(283, "kexec_load", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(284, "waitid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(285, "285-old_sys_setaltroot", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(286, "add_key", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(287, "request_key", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(288, "keyctl", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(289, "ioprio_set", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(290, "ioprio_get", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(291, "inotify_init", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(292, "inotify_add_watch", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(293, "inotify_rm_watch", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(294, "migrate_pages", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(295, "openat", kHex, kPath, kOct, kHex, kHex, kHex), MakeEntry(296, "mkdirat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(297, "mknodat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(298, "fchownat", kHex, kPath, kHex, kHex, kHex, kHex), MakeEntry(299, "futimesat", kHex, kPath, kHex, kHex, kHex, kHex), MakeEntry(300, "fstatat64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(301, "unlinkat", kHex, kPath, kHex, kHex, kHex, kHex), MakeEntry(302, "renameat", kHex, kPath, kHex, kPath, kHex, kHex), MakeEntry(303, "linkat", kHex, kPath, kHex, kPath, kHex, kHex), MakeEntry(304, "symlinkat", kPath, kHex, kPath, kHex, kHex, kHex), MakeEntry(305, "readlinkat", kHex, kPath, kHex, kHex, kHex, kHex), MakeEntry(306, "fchmodat", kHex, kPath, kHex, kHex, kHex, kHex), MakeEntry(307, "faccessat", kHex, kPath, kHex, kHex, kHex, kHex), MakeEntry(308, "pselect6", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(309, "ppoll", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(310, "unshare", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(311, "set_robust_list", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(312, "get_robust_list", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(313, "splice", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(314, "sync_file_range", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(315, "tee", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(316, "vmsplice", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(317, "move_pages", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(318, "getcpu", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(319, "epoll_pwait", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(320, "utimensat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(321, "signalfd", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(322, "timerfd_create", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(323, "eventfd", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(324, "fallocate", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(325, "timerfd_settime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(326, "timerfd_gettime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(327, "signalfd4", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(328, "eventfd2", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(329, "epoll_create1", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(330, "dup3", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(331, "pipe2", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(332, "inotify_init1", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(333, "preadv", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(334, "pwritev", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(335, "rt_tgsigqueueinfo", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(336, "perf_event_open", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(337, "recvmmsg", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(338, "fanotify_init", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(339, "fanotify_mark", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(340, "prlimit64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(341, "name_to_handle_at", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(342, "open_by_handle_at", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(343, "clock_adjtime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(344, "syncfs", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(345, "sendmmsg", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(346, "setns", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(347, "process_vm_readv", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(348, "process_vm_writev", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(349, "kcmp", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(350, "finit_module", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(351, "sched_setattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(352, "sched_getattr", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(353, "renameat2", kHex, kPath, kHex, kPath, kHex, kHex), MakeEntry(354, "seccomp", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(355, "getrandom", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(356, "memfd_create", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(357, "bpf", kHex, kHex, kHex, kHex, kHex, kHex), // clang-format on }; static_assert(IsSorted(kSyscallDataX8632, SyscallTable::Entry::BySyscallNr), "Syscalls should be sorted"); // http://lxr.free-electrons.com/source/arch/powerpc/include/uapi/asm/unistd.h // Note: PPC64 syscalls can have up to 7 register arguments, but nobody is // using the 7th argument - probably for x64 compatibility reasons. constexpr std::array kSyscallDataPPC64LE = { // clang-format off MakeEntry(0, "restart_syscall", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(1, "exit", kInt, kGen, kGen, kGen, kGen, kGen), MakeEntry(2, "fork", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(3, "read", kInt, kHex, kInt), MakeEntry(4, "write", kInt, kHex, kInt, kGen, kGen, kGen), MakeEntry(5, "open", kPath, kHex, kOct, kGen, kGen, kGen), MakeEntry(6, "close", kInt, kGen, kGen, kGen, kGen, kGen), MakeEntry(7, "waitpid", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(8, "creat", kPath, kOct, kGen, kGen, kGen, kGen), MakeEntry(9, "link", kPath, kPath, kGen, kGen, kGen, kGen), MakeEntry(10, "unlink", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(11, "execve", kPath, kHex, kHex, kGen, kGen, kGen), MakeEntry(12, "chdir", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(13, "time", kHex, kGen, kGen, kGen, kGen, kGen), MakeEntry(14, "mknod", kPath, kOct, kHex, kGen, kGen, kGen), MakeEntry(15, "chmod", kPath, kOct, kGen, kGen, kGen, kGen), MakeEntry(16, "lchown", kPath, kInt, kInt, kGen, kGen, kGen), MakeEntry(17, "break", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(18, "oldstat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(19, "lseek", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(20, "getpid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(21, "mount", kPath, kPath, kString, kHex, kGen, kGen), MakeEntry(22, "umount", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(23, "setuid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(24, "getuid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(25, "stime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(26, "ptrace", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(27, "alarm", kInt, kGen, kGen, kGen, kGen, kGen), MakeEntry(28, "oldfstat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(29, "pause", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(30, "utime", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(31, "stty", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(32, "gtty", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(33, "access", kPath, kHex, kGen, kGen, kGen, kGen), MakeEntry(34, "nice", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(35, "ftime", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(36, "sync", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(37, "kill", kInt, kSignal, kGen, kGen, kGen, kGen), MakeEntry(38, "rename", kPath, kPath, kGen, kGen, kGen, kGen), MakeEntry(39, "mkdir", kPath, kOct, kGen, kGen, kGen, kGen), MakeEntry(40, "rmdir", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(41, "dup", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(42, "pipe", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(43, "times", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(44, "prof", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(45, "brk", kHex, kGen, kGen, kGen, kGen, kGen), MakeEntry(46, "setgid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(47, "getgid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(48, "signal", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(49, "geteuid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(50, "getegid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(51, "acct", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(52, "umount2", kPath, kHex, kGen, kGen, kGen, kGen), MakeEntry(53, "lock", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(54, "ioctl", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(55, "fcntl", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(56, "mpx", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(57, "setpgid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(58, "ulimit", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(59, "oldolduname", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(60, "umask", kHex, kGen, kGen, kGen, kGen, kGen), MakeEntry(61, "chroot", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(62, "ustat", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(63, "dup2", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(64, "getppid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(65, "getpgrp", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(66, "setsid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(67, "sigaction", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(68, "sgetmask", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(69, "ssetmask", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(70, "setreuid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(71, "setregid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(72, "sigsuspend", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(73, "sigpending", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(74, "sethostname", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(75, "setrlimit", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(76, "getrlimit", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(77, "getrusage", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(78, "gettimeofday", kHex, kHex, kGen, kGen, kGen, kGen), MakeEntry(79, "settimeofday", kHex, kHex, kGen, kGen, kGen, kGen), MakeEntry(80, "getgroups", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(81, "setgroups", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(82, "select", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(83, "symlink", kPath, kPath, kGen, kGen, kGen, kGen), MakeEntry(84, "oldlstat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(85, "readlink", kPath, kGen, kInt, kGen, kGen, kGen), MakeEntry(86, "uselib", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(87, "swapon", kPath, kHex, kGen, kGen, kGen, kGen), MakeEntry(88, "reboot", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(89, "readdir", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(90, "mmap", kHex, kInt, kHex, kHex, kInt, kInt), MakeEntry(91, "munmap", kHex, kHex, kGen, kGen, kGen, kGen), MakeEntry(92, "truncate", kPath, kInt, kGen, kGen, kGen, kGen), MakeEntry(93, "ftruncate", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(94, "fchmod", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(95, "fchown", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(96, "getpriority", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(97, "setpriority", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(98, "profil", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(99, "statfs", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(100, "fstatfs", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(101, "ioperm", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(102, "socketcall", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(103, "syslog", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(104, "setitimer", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(105, "getitimer", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(106, "stat", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(107, "lstat", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(108, "fstat", kInt, kHex, kGen, kGen, kGen, kGen), MakeEntry(109, "olduname", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(110, "iopl", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(111, "vhangup", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(112, "idle", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(113, "vm86", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(114, "wait4", kInt, kHex, kHex, kHex, kGen, kGen), MakeEntry(115, "swapoff", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(116, "sysinfo", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(117, "ipc", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(118, "fsync", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(119, "sigreturn", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(120, "clone", kCloneFlag, kHex, kHex, kHex, kHex, kGen), MakeEntry(121, "setdomainname", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(122, "uname", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(123, "modify_ldt", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(124, "adjtimex", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(125, "mprotect", kHex, kHex, kHex, kGen, kGen, kGen), MakeEntry(126, "sigprocmask", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(127, "create_module", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(128, "init_module", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(129, "delete_module", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(130, "get_kernel_syms", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(131, "quotactl", kInt, kPath, kInt, kGen, kGen, kGen), MakeEntry(132, "getpgid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(133, "fchdir", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(134, "bdflush", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(135, "sysfs", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(136, "personality", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(137, "afs_syscall", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(138, "setfsuid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(139, "setfsgid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(140, "_llseek", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(141, "getdents", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(142, "_newselect", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(143, "flock", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(144, "msync", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(145, "readv", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(146, "writev", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(147, "getsid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(148, "fdatasync", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(149, "_sysctl", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(150, "mlock", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(151, "munlock", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(152, "mlockall", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(153, "munlockall", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(154, "sched_setparam", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(155, "sched_getparam", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(156, "sched_setscheduler", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(157, "sched_getscheduler", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(158, "sched_yield", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(159, "sched_get_priority_max", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(160, "sched_get_priority_min", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(161, "sched_rr_get_interval", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(162, "nanosleep", kHex, kHex, kGen, kGen, kGen, kGen), MakeEntry(163, "mremap", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(164, "setresuid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(165, "getresuid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(166, "query_module", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(167, "poll", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(168, "nfsservctl", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(169, "setresgid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(170, "getresgid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(171, "prctl", kInt, kHex, kHex, kHex, kHex, kGen), MakeEntry(172, "rt_sigreturn", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(173, "rt_sigaction", kSignal, kHex, kHex, kInt, kGen, kGen), MakeEntry(174, "rt_sigprocmask", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(175, "rt_sigpending", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(176, "rt_sigtimedwait", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(177, "rt_sigqueueinfo", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(178, "rt_sigsuspend", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(179, "pread64", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(180, "pwrite64", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(181, "chown", kPath, kInt, kInt, kGen, kGen, kGen), MakeEntry(182, "getcwd", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(183, "capget", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(184, "capset", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(185, "sigaltstack", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(186, "sendfile", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(187, "getpmsg", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(188, "putpmsg", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(189, "vfork", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(190, "ugetrlimit", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(191, "readahead", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(192, "mmap2", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(193, "truncate64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(194, "ftruncate64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(195, "stat64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(196, "lstat64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(197, "fstat64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(198, "pciconfig_read", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(199, "pciconfig_write", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(200, "pciconfig_iobase", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(201, "multiplexer", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(202, "getdents64", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(203, "pivot_root", kPath, kPath, kGen, kGen, kGen, kGen), MakeEntry(204, "fcntl64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(205, "madvise", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(206, "mincore", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(207, "gettid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(208, "tkill", kInt, kSignal, kGen, kGen, kGen, kGen), MakeEntry(209, "setxattr", kPath, kString, kGen, kInt, kHex, kGen), MakeEntry(210, "lsetxattr", kPath, kString, kGen, kInt, kHex, kGen), MakeEntry(211, "fsetxattr", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(212, "getxattr", kPath, kString, kGen, kInt, kGen, kGen), MakeEntry(213, "lgetxattr", kPath, kString, kGen, kInt, kGen, kGen), MakeEntry(214, "fgetxattr", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(215, "listxattr", kPath, kGen, kInt, kGen, kGen, kGen), MakeEntry(216, "llistxattr", kPath, kGen, kInt, kGen, kGen, kGen), MakeEntry(217, "flistxattr", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(218, "removexattr", kPath, kString, kGen, kGen, kGen, kGen), MakeEntry(219, "lremovexattr", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(220, "fremovexattr", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(221, "futex", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(222, "sched_setaffinity", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(223, "sched_getaffinity", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(225, "tuxcall", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(226, "sendfile64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(227, "io_setup", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(228, "io_destroy", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(229, "io_getevents", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(230, "io_submit", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(231, "io_cancel", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(232, "set_tid_address", kHex, kGen, kGen, kGen, kGen, kGen), MakeEntry(233, "fadvise64", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(234, "exit_group", kInt, kGen, kGen, kGen, kGen, kGen), MakeEntry(235, "lookup_dcookie", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(236, "epoll_create", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(237, "epoll_ctl", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(238, "epoll_wait", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(239, "remap_file_pages", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(240, "timer_create", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(241, "timer_settime", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(242, "timer_gettime", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(243, "timer_getoverrun", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(244, "timer_delete", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(245, "clock_settime", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(246, "clock_gettime", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(247, "clock_getres", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(248, "clock_nanosleep", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(249, "swapcontext", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(250, "tgkill", kInt, kInt, kSignal, kGen, kGen, kGen), MakeEntry(251, "utimes", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(252, "statfs64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(253, "fstatfs64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(254, "fadvise64_64", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(255, "rtas", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(256, "sys_debug_setcontext", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(258, "migrate_pages", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(259, "mbind", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(260, "get_mempolicy", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(261, "set_mempolicy", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(262, "mq_open", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(263, "mq_unlink", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(264, "mq_timedsend", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(265, "mq_timedreceive", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(266, "mq_notify", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(267, "mq_getsetattr", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(268, "kexec_load", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(269, "add_key", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(270, "request_key", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(271, "keyctl", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(272, "waitid", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(273, "ioprio_set", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(274, "ioprio_get", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(275, "inotify_init", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(276, "inotify_add_watch", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(277, "inotify_rm_watch", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(278, "spu_run", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(279, "spu_create", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(280, "pselect6", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(281, "ppoll", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(282, "unshare", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(283, "splice", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(284, "tee", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(285, "vmsplice", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(286, "openat", kGen, kPath, kOct, kHex, kGen, kGen), MakeEntry(287, "mkdirat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(288, "mknodat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(289, "fchownat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(290, "futimesat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(291, "newfstatat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(292, "unlinkat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(293, "renameat", kGen, kPath, kGen, kPath, kGen, kGen), MakeEntry(294, "linkat", kGen, kPath, kGen, kPath, kGen, kGen), MakeEntry(295, "symlinkat", kPath, kGen, kPath, kGen, kGen, kGen), MakeEntry(296, "readlinkat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(297, "fchmodat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(298, "faccessat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(299, "get_robust_list", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(300, "set_robust_list", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(301, "move_pages", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(302, "getcpu", kHex, kHex, kHex, kGen, kGen, kGen), MakeEntry(303, "epoll_pwait", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(304, "utimensat", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(305, "signalfd", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(306, "timerfd_create", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(307, "eventfd", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(308, "sync_file_range2", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(309, "fallocate", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(310, "subpage_prot", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(311, "timerfd_settime", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(312, "timerfd_gettime", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(313, "signalfd4", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(314, "eventfd2", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(315, "epoll_create1", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(316, "dup3", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(317, "pipe2", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(318, "inotify_init1", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(319, "perf_event_open", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(320, "preadv", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(321, "pwritev", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(322, "rt_tgsigqueueinfo", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(323, "fanotify_init", kHex, kHex, kInt, kGen, kGen, kGen), MakeEntry(324, "fanotify_mark", kInt, kHex, kInt, kPath, kGen, kGen), MakeEntry(325, "prlimit64", kInt, kInt, kHex, kHex, kGen, kGen), MakeEntry(326, "socket", kAddressFamily, kInt, kInt, kGen, kGen, kGen), MakeEntry(327, "bind", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(328, "connect", kInt, kSockaddr, kInt, kGen, kGen, kGen), MakeEntry(329, "listen", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(330, "accept", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(331, "getsockname", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(332, "getpeername", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(333, "socketpair", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(334, "send", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(335, "sendto", kInt, kGen, kInt, kHex, kSockaddr, kInt), MakeEntry(336, "recv", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(337, "recvfrom", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(338, "shutdown", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(339, "setsockopt", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(340, "getsockopt", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(341, "sendmsg", kInt, kSockmsghdr, kHex, kGen, kGen, kGen), MakeEntry(342, "recvmsg", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(343, "recvmmsg", kInt, kHex, kHex, kHex, kGen, kGen), MakeEntry(344, "accept4", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(345, "name_to_handle_at", kInt, kGen, kHex, kHex, kHex, kGen), MakeEntry(346, "open_by_handle_at", kInt, kHex, kHex, kGen, kGen, kGen), MakeEntry(347, "clock_adjtime", kInt, kHex, kGen, kGen, kGen, kGen), MakeEntry(348, "syncfs", kInt, kGen, kGen, kGen, kGen, kGen), MakeEntry(349, "sendmmsg", kInt, kHex, kInt, kHex, kGen, kGen), MakeEntry(350, "setns", kInt, kHex, kGen, kGen, kGen, kGen), MakeEntry(351, "process_vm_readv", kInt, kHex, kInt, kHex, kInt, kInt), MakeEntry(352, "process_vm_writev", kInt, kHex, kInt, kHex, kInt, kInt), MakeEntry(353, "finit_module", kInt, kPath, kHex, kGen, kGen, kGen), MakeEntry(354, "kcmp", kInt, kInt, kInt, kHex, kHex, kGen), MakeEntry(355, "sched_setattr", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(356, "sched_getattr", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(357, "renameat2", kGen, kPath, kGen, kPath, kGen, kGen), MakeEntry(358, "seccomp", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(359, "getrandom", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(360, "memfd_create", kGen, kGen, kGen, kGen, kGen, kGen), MakeEntry(361, "bpf", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(362, "execveat", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(363, "switch_endian", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(364, "userfaultfd", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(365, "membarrier", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(378, "mlock2", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(379, "copy_file_range", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(380, "preadv2", kHex, kHex, kHex, kHex, kHex, kHex), MakeEntry(381, "pwritev2", kHex, kHex, kHex, kHex, kHex, kHex), // clang-format on }; static_assert(IsSorted(kSyscallDataPPC64LE, SyscallTable::Entry::BySyscallNr), "Syscalls should be sorted"); // TODO(cblichmann): Confirm the entries in this list. // https://github.com/torvalds/linux/blob/v5.8/include/uapi/asm-generic/unistd.h constexpr std::array kSyscallDataArm64 = { // clang-format off MakeEntry(0, "io_setup", UnknownArguments()), MakeEntry(1, "io_destroy", UnknownArguments()), MakeEntry(2, "io_submit", UnknownArguments()), MakeEntry(3, "io_cancel", UnknownArguments()), MakeEntry(4, "io_getevents", UnknownArguments()), MakeEntry(5, "setxattr", kPath, kString, kGen, kInt, kHex, kGen), MakeEntry(6, "lsetxattr", kPath, kString, kGen, kInt, kHex, kGen), MakeEntry(7, "fsetxattr", UnknownArguments()), MakeEntry(8, "getxattr", kPath, kString, kGen, kInt, kGen, kGen), MakeEntry(9, "lgetxattr", kPath, kString, kGen, kInt, kGen, kGen), MakeEntry(10, "fgetxattr", UnknownArguments()), MakeEntry(11, "listxattr", kPath, kGen, kInt, kGen, kGen, kGen), MakeEntry(12, "llistxattr", kPath, kGen, kInt, kGen, kGen, kGen), MakeEntry(13, "flistxattr", UnknownArguments()), MakeEntry(14, "removexattr", kPath, kString, kGen, kGen, kGen, kGen), MakeEntry(15, "lremovexattr", UnknownArguments()), MakeEntry(16, "fremovexattr", UnknownArguments()), MakeEntry(17, "getcwd", UnknownArguments()), MakeEntry(18, "lookup_dcookie", UnknownArguments()), MakeEntry(19, "eventfd2", UnknownArguments()), MakeEntry(20, "epoll_create1", UnknownArguments()), MakeEntry(21, "epoll_ctl", UnknownArguments()), MakeEntry(22, "epoll_pwait", UnknownArguments()), MakeEntry(23, "dup", UnknownArguments()), MakeEntry(24, "dup3", UnknownArguments()), MakeEntry(25, "fcntl", UnknownArguments()), MakeEntry(26, "inotify_init1", UnknownArguments()), MakeEntry(27, "inotify_add_watch", UnknownArguments()), MakeEntry(28, "inotify_rm_watch", UnknownArguments()), MakeEntry(29, "ioctl", UnknownArguments()), MakeEntry(30, "ioprio_set", UnknownArguments()), MakeEntry(31, "ioprio_get", UnknownArguments()), MakeEntry(32, "flock", UnknownArguments()), MakeEntry(33, "mknodat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(34, "mkdirat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(35, "unlinkat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(36, "symlinkat", kPath, kGen, kPath, kGen, kGen, kGen), MakeEntry(37, "linkat", kGen, kPath, kGen, kPath, kGen, kGen), MakeEntry(38, "renameat", kGen, kPath, kGen, kPath, kGen, kGen), MakeEntry(39, "umount2", kPath, kHex, kGen, kGen, kGen, kGen), MakeEntry(40, "mount", kPath, kPath, kString, kHex, kGen, kGen), MakeEntry(41, "pivot_root", kPath, kPath, kGen, kGen, kGen, kGen), MakeEntry(42, "nfsservctl", UnknownArguments()), MakeEntry(43, "statfs", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(44, "fstatfs", UnknownArguments()), MakeEntry(45, "truncate", kPath, kInt, kGen, kGen, kGen, kGen), MakeEntry(46, "ftruncate", UnknownArguments()), MakeEntry(47, "fallocate", UnknownArguments()), MakeEntry(48, "faccessat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(49, "chdir", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(50, "fchdir", UnknownArguments()), MakeEntry(51, "chroot", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(52, "fchmod", UnknownArguments()), MakeEntry(53, "fchmodat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(54, "fchownat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(55, "fchown", UnknownArguments()), MakeEntry(56, "openat", kGen, kPath, kOct, kHex, kGen, kGen), MakeEntry(57, "close", kInt, kGen, kGen, kGen, kGen, kGen), MakeEntry(58, "vhangup", UnknownArguments()), MakeEntry(59, "pipe2", UnknownArguments()), MakeEntry(60, "quotactl", kInt, kPath, kInt, kGen, kGen, kGen), MakeEntry(61, "getdents64", UnknownArguments()), MakeEntry(62, "lseek", UnknownArguments()), MakeEntry(63, "read", kInt, kHex, kInt, kGen, kGen, kGen), MakeEntry(64, "write", kInt, kHex, kInt, kGen, kGen, kGen), MakeEntry(65, "readv", UnknownArguments()), MakeEntry(66, "writev", UnknownArguments()), MakeEntry(67, "pread64", UnknownArguments()), MakeEntry(68, "pwrite64", UnknownArguments()), MakeEntry(69, "preadv", UnknownArguments()), MakeEntry(70, "pwritev", UnknownArguments()), MakeEntry(71, "sendfile", UnknownArguments()), MakeEntry(72, "pselect6", UnknownArguments()), MakeEntry(73, "ppoll", UnknownArguments()), MakeEntry(74, "signalfd4", UnknownArguments()), MakeEntry(75, "vmsplice", UnknownArguments()), MakeEntry(76, "splice", UnknownArguments()), MakeEntry(77, "tee", UnknownArguments()), MakeEntry(78, "readlinkat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(79, "newfstatat", kGen, kPath, kGen, kGen, kGen, kGen), MakeEntry(80, "fstat", kInt, kHex, kGen, kGen, kGen, kGen), MakeEntry(81, "sync", UnknownArguments()), MakeEntry(82, "fsync", UnknownArguments()), MakeEntry(83, "fdatasync", UnknownArguments()), MakeEntry(84, "sync_file_range", UnknownArguments()), MakeEntry(85, "timerfd_create", UnknownArguments()), MakeEntry(86, "timerfd_settime", UnknownArguments()), MakeEntry(87, "timerfd_gettime", UnknownArguments()), MakeEntry(88, "utimensat", UnknownArguments()), MakeEntry(89, "acct", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(90, "capget", UnknownArguments()), MakeEntry(91, "capset", UnknownArguments()), MakeEntry(92, "personality", UnknownArguments()), MakeEntry(93, "exit", kInt, kGen, kGen, kGen, kGen, kGen), MakeEntry(94, "exit_group", kInt, kGen, kGen, kGen, kGen, kGen), MakeEntry(95, "waitid", UnknownArguments()), MakeEntry(96, "set_tid_address", kHex, kGen, kGen, kGen, kGen, kGen), MakeEntry(97, "unshare", UnknownArguments()), MakeEntry(98, "futex", UnknownArguments()), MakeEntry(99, "set_robust_list", UnknownArguments()), MakeEntry(100, "get_robust_list", UnknownArguments()), MakeEntry(101, "nanosleep", kHex, kHex, kGen, kGen, kGen, kGen), MakeEntry(102, "getitimer", UnknownArguments()), MakeEntry(103, "setitimer", UnknownArguments()), MakeEntry(104, "kexec_load", UnknownArguments()), MakeEntry(105, "init_module", UnknownArguments()), MakeEntry(106, "delete_module", UnknownArguments()), MakeEntry(107, "timer_create", UnknownArguments()), MakeEntry(108, "timer_gettime", UnknownArguments()), MakeEntry(109, "timer_getoverrun", UnknownArguments()), MakeEntry(110, "timer_settime", UnknownArguments()), MakeEntry(111, "timer_delete", UnknownArguments()), MakeEntry(112, "clock_settime", UnknownArguments()), MakeEntry(113, "clock_gettime", UnknownArguments()), MakeEntry(114, "clock_getres", UnknownArguments()), MakeEntry(115, "clock_nanosleep", UnknownArguments()), MakeEntry(116, "syslog", UnknownArguments()), MakeEntry(117, "ptrace", UnknownArguments()), MakeEntry(118, "sched_setparam", UnknownArguments()), MakeEntry(119, "sched_setscheduler", UnknownArguments()), MakeEntry(120, "sched_getscheduler", UnknownArguments()), MakeEntry(121, "sched_getparam", UnknownArguments()), MakeEntry(122, "sched_setaffinity", UnknownArguments()), MakeEntry(123, "sched_getaffinity", UnknownArguments()), MakeEntry(124, "sched_yield", UnknownArguments()), MakeEntry(125, "sched_get_priority_max", UnknownArguments()), MakeEntry(126, "sched_get_priority_min", UnknownArguments()), MakeEntry(127, "sched_rr_get_interval", UnknownArguments()), MakeEntry(128, "restart_syscall", UnknownArguments()), MakeEntry(129, "kill", kInt, kSignal, kGen, kGen, kGen, kGen), MakeEntry(130, "tkill", kInt, kSignal, kGen, kGen, kGen, kGen), MakeEntry(131, "tgkill", kInt, kInt, kSignal, kGen, kGen, kGen), MakeEntry(132, "sigaltstack", UnknownArguments()), MakeEntry(133, "rt_sigsuspend", UnknownArguments()), MakeEntry(134, "rt_sigaction", kSignal, kHex, kHex, kInt, kGen, kGen), MakeEntry(135, "rt_sigprocmask", UnknownArguments()), MakeEntry(136, "rt_sigpending", UnknownArguments()), MakeEntry(137, "rt_sigtimedwait", UnknownArguments()), MakeEntry(138, "rt_sigqueueinfo", UnknownArguments()), MakeEntry(139, "rt_sigreturn", UnknownArguments()), MakeEntry(140, "setpriority", UnknownArguments()), MakeEntry(141, "getpriority", UnknownArguments()), MakeEntry(142, "reboot", UnknownArguments()), MakeEntry(143, "setregid", UnknownArguments()), MakeEntry(144, "setgid", UnknownArguments()), MakeEntry(145, "setreuid", UnknownArguments()), MakeEntry(146, "setuid", UnknownArguments()), MakeEntry(147, "setresuid", UnknownArguments()), MakeEntry(148, "getresuid", UnknownArguments()), MakeEntry(149, "setresgid", UnknownArguments()), MakeEntry(150, "getresgid", UnknownArguments()), MakeEntry(151, "setfsuid", UnknownArguments()), MakeEntry(152, "setfsgid", UnknownArguments()), MakeEntry(153, "times", UnknownArguments()), MakeEntry(154, "setpgid", UnknownArguments()), MakeEntry(155, "getpgid", UnknownArguments()), MakeEntry(156, "getsid", UnknownArguments()), MakeEntry(157, "setsid", UnknownArguments()), MakeEntry(158, "getgroups", UnknownArguments()), MakeEntry(159, "setgroups", UnknownArguments()), MakeEntry(160, "uname", UnknownArguments()), MakeEntry(161, "sethostname", UnknownArguments()), MakeEntry(162, "setdomainname", UnknownArguments()), MakeEntry(163, "getrlimit", UnknownArguments()), MakeEntry(164, "setrlimit", UnknownArguments()), MakeEntry(165, "getrusage", UnknownArguments()), MakeEntry(166, "umask", kHex, kGen, kGen, kGen, kGen, kGen), MakeEntry(167, "prctl", kInt, kHex, kHex, kHex, kHex, kGen), MakeEntry(168, "getcpu", kHex, kHex, kHex, kGen, kGen, kGen), MakeEntry(169, "gettimeofday", kHex, kHex, kGen, kGen, kGen, kGen), MakeEntry(170, "settimeofday", kHex, kHex, kGen, kGen, kGen, kGen), MakeEntry(171, "adjtimex", UnknownArguments()), MakeEntry(172, "getpid", UnknownArguments()), MakeEntry(173, "getppid", UnknownArguments()), MakeEntry(174, "getuid", UnknownArguments()), MakeEntry(175, "geteuid", UnknownArguments()), MakeEntry(176, "getgid", UnknownArguments()), MakeEntry(177, "getegid", UnknownArguments()), MakeEntry(178, "gettid", UnknownArguments()), MakeEntry(179, "sysinfo", UnknownArguments()), MakeEntry(180, "mq_open", UnknownArguments()), MakeEntry(181, "mq_unlink", UnknownArguments()), MakeEntry(182, "mq_timedsend", UnknownArguments()), MakeEntry(183, "mq_timedreceive", UnknownArguments()), MakeEntry(184, "mq_notify", UnknownArguments()), MakeEntry(185, "mq_getsetattr", UnknownArguments()), MakeEntry(186, "msgget", UnknownArguments()), MakeEntry(187, "msgctl", UnknownArguments()), MakeEntry(188, "msgrcv", UnknownArguments()), MakeEntry(189, "msgsnd", UnknownArguments()), MakeEntry(190, "semget", UnknownArguments()), MakeEntry(191, "semctl", UnknownArguments()), MakeEntry(192, "semtimedop", UnknownArguments()), MakeEntry(193, "semop", UnknownArguments()), MakeEntry(194, "shmget", UnknownArguments()), MakeEntry(195, "shmctl", UnknownArguments()), MakeEntry(196, "shmat", UnknownArguments()), MakeEntry(197, "shmdt", UnknownArguments()), MakeEntry(198, "socket", kAddressFamily, kInt, kInt, kGen, kGen, kGen), MakeEntry(199, "socketpair", UnknownArguments()), MakeEntry(200, "bind", UnknownArguments()), MakeEntry(201, "listen", UnknownArguments()), MakeEntry(202, "accept", UnknownArguments()), MakeEntry(203, "connect", kInt, kSockaddr, kInt, kGen, kGen, kGen), MakeEntry(204, "getsockname", UnknownArguments()), MakeEntry(205, "getpeername", UnknownArguments()), MakeEntry(206, "sendto", kInt, kGen, kInt, kHex, kSockaddr, kInt), MakeEntry(207, "recvfrom", UnknownArguments()), MakeEntry(208, "setsockopt", UnknownArguments()), MakeEntry(209, "getsockopt", UnknownArguments()), MakeEntry(210, "shutdown", UnknownArguments()), MakeEntry(211, "sendmsg", kInt, kSockmsghdr, kHex, kGen, kGen, kGen), MakeEntry(212, "recvmsg", UnknownArguments()), MakeEntry(213, "readahead", UnknownArguments()), MakeEntry(214, "brk", kHex, kGen, kGen, kGen, kGen, kGen), MakeEntry(215, "munmap", kHex, kHex, kGen, kGen, kGen, kGen), MakeEntry(216, "mremap", UnknownArguments()), MakeEntry(217, "add_key", UnknownArguments()), MakeEntry(218, "request_key", UnknownArguments()), MakeEntry(219, "keyctl", UnknownArguments()), MakeEntry(220, "clone", kCloneFlag, kHex, kHex, kHex, kHex, kGen), MakeEntry(221, "execve", kPath, kHex, kHex, kGen, kGen, kGen), MakeEntry(222, "mmap", kHex, kInt, kHex, kHex, kInt, kInt), MakeEntry(223, "fadvise64", UnknownArguments()), MakeEntry(224, "swapon", kPath, kHex, kGen, kGen, kGen, kGen), MakeEntry(225, "swapoff", kPath, kGen, kGen, kGen, kGen, kGen), MakeEntry(226, "mprotect", kHex, kHex, kHex, kGen, kGen, kGen), MakeEntry(227, "msync", UnknownArguments()), MakeEntry(228, "mlock", UnknownArguments()), MakeEntry(229, "munlock", UnknownArguments()), MakeEntry(230, "mlockall", UnknownArguments()), MakeEntry(231, "munlockall", UnknownArguments()), MakeEntry(232, "mincore", UnknownArguments()), MakeEntry(233, "madvise", UnknownArguments()), MakeEntry(234, "remap_file_pages", UnknownArguments()), MakeEntry(235, "mbind", UnknownArguments()), MakeEntry(236, "get_mempolicy", UnknownArguments()), MakeEntry(237, "set_mempolicy", UnknownArguments()), MakeEntry(238, "migrate_pages", UnknownArguments()), MakeEntry(239, "move_pages", UnknownArguments()), MakeEntry(240, "rt_tgsigqueueinfo", UnknownArguments()), MakeEntry(241, "perf_event_open", UnknownArguments()), MakeEntry(242, "accept4", UnknownArguments()), MakeEntry(243, "recvmmsg", kInt, kHex, kHex, kHex, kGen, kGen), MakeEntry(260, "wait4", kInt, kHex, kHex, kHex, kGen, kGen), MakeEntry(261, "prlimit64", kInt, kInt, kHex, kHex, kGen, kGen), MakeEntry(262, "fanotify_init", kHex, kHex, kInt, kGen, kGen, kGen), MakeEntry(263, "fanotify_mark", kInt, kHex, kInt, kPath, kGen, kGen), MakeEntry(264, "name_to_handle_at", kInt, kGen, kHex, kHex, kHex, kGen), MakeEntry(265, "open_by_handle_at", kInt, kHex, kHex, kGen, kGen, kGen), MakeEntry(266, "clock_adjtime", kInt, kHex, kGen, kGen, kGen, kGen), MakeEntry(267, "syncfs", kInt, kGen, kGen, kGen, kGen, kGen), MakeEntry(268, "setns", kInt, kHex, kGen, kGen, kGen, kGen), MakeEntry(269, "sendmmsg", kInt, kHex, kInt, kHex, kGen, kGen), MakeEntry(270, "process_vm_readv", kInt, kHex, kInt, kHex, kInt, kInt), MakeEntry(271, "process_vm_writev", kInt, kHex, kInt, kHex, kInt, kInt), MakeEntry(272, "kcmp", kInt, kInt, kInt, kHex, kHex, kGen), MakeEntry(273, "finit_module", kInt, kPath, kHex, kGen, kGen, kGen), MakeEntry(274, "sched_setattr", UnknownArguments()), MakeEntry(275, "sched_getattr", UnknownArguments()), MakeEntry(276, "renameat2", kGen, kPath, kGen, kPath, kGen, kGen), MakeEntry(277, "seccomp", UnknownArguments()), MakeEntry(278, "getrandom", UnknownArguments()), MakeEntry(279, "memfd_create", UnknownArguments()), // clang-format on }; static_assert(IsSorted(kSyscallDataArm64, SyscallTable::Entry::BySyscallNr), "Syscalls should be sorted"); constexpr std::array kSyscallDataArm32 = { // clang-format off MakeEntry(0, "restart_syscall", kGen, kGen, kGen, kGen), MakeEntry(1, "exit", kHex, kHex, kHex, kHex), MakeEntry(2, "fork", kGen, kGen, kGen, kGen), MakeEntry(3, "read", kInt, kHex, kInt), MakeEntry(4, "write", kHex, kHex, kHex, kHex), MakeEntry(5, "open", kPath, kHex, kOct), MakeEntry(6, "close", kHex, kHex, kHex, kHex), MakeEntry(8, "creat", kPath, kHex, kHex, kHex), MakeEntry(9, "link", kPath, kPath), MakeEntry(10, "unlink", kPath), MakeEntry(11, "execve", kPath, kHex, kHex), MakeEntry(12, "chdir", kPath), MakeEntry(14, "mknod", kPath, kOct, kHex), MakeEntry(15, "chmod", kPath, kOct), MakeEntry(16, "lchown", kPath, kInt, kInt), MakeEntry(19, "lseek", kGen, kGen, kGen, kGen), MakeEntry(20, "getpid", kGen, kGen, kGen, kGen), MakeEntry(21, "mount", kHex, kHex, kHex, kHex), MakeEntry(23, "setuid", kGen, kGen, kGen, kGen), MakeEntry(24, "getuid", kGen, kGen, kGen, kGen), MakeEntry(26, "ptrace", kGen, kGen, kGen), MakeEntry(29, "pause", kGen, kGen, kGen, kGen), MakeEntry(33, "access", kPath, kHex), MakeEntry(34, "nice", kHex, kHex, kHex, kHex), MakeEntry(36, "sync", kGen, kGen, kGen, kGen), MakeEntry(37, "kill", kHex, kHex, kHex, kHex), MakeEntry(38, "rename", kPath, kPath), MakeEntry(39, "mkdir", kPath, kHex, kHex, kHex), MakeEntry(40, "rmdir", kHex, kHex, kHex, kHex), MakeEntry(41, "dup", kGen, kGen, kGen, kGen), MakeEntry(42, "pipe", kGen, kGen, kGen, kGen), MakeEntry(43, "times", kGen, kGen, kGen, kGen), MakeEntry(45, "brk", kHex), MakeEntry(46, "setgid", kGen, kGen, kGen, kGen), MakeEntry(47, "getgid", kGen, kGen, kGen, kGen), MakeEntry(49, "geteuid", kGen, kGen, kGen, kGen), MakeEntry(50, "getegid", kGen, kGen, kGen, kGen), MakeEntry(51, "acct", kHex, kHex, kHex, kHex), MakeEntry(52, "umount2", kHex, kHex, kHex, kHex), MakeEntry(54, "ioctl", kGen, kGen, kGen, kGen), MakeEntry(55, "fcntl", kGen, kGen, kGen, kGen), MakeEntry(57, "setpgid", kGen, kGen, kGen, kGen), MakeEntry(60, "umask", kHex), MakeEntry(61, "chroot", kHex, kHex, kHex, kHex), MakeEntry(62, "ustat", kGen, kGen, kGen, kGen), MakeEntry(63, "dup2", kGen, kGen), MakeEntry(64, "getppid", kGen, kGen, kGen, kGen), MakeEntry(65, "getpgrp", kGen, kGen, kGen, kGen), MakeEntry(66, "setsid", kGen, kGen, kGen, kGen), MakeEntry(67, "sigaction", kHex, kHex, kHex, kHex), MakeEntry(70, "setreuid", kGen, kGen, kGen, kGen), MakeEntry(71, "setregid", kGen, kGen, kGen, kGen), MakeEntry(72, "sigsuspend", kHex, kHex, kHex, kHex), MakeEntry(73, "sigpending", kHex, kHex, kHex, kHex), MakeEntry(74, "sethostname", kGen, kGen, kGen, kGen), MakeEntry(75, "setrlimit", kGen, kGen, kGen, kGen), MakeEntry(77, "getrusage", kGen, kGen, kGen, kGen), MakeEntry(78, "gettimeofday", kHex, kHex), MakeEntry(79, "settimeofday", kHex, kHex), MakeEntry(80, "getgroups", kGen, kGen, kGen, kGen), MakeEntry(81, "setgroups", kGen, kGen, kGen, kGen), MakeEntry(83, "symlink", kPath, kPath), MakeEntry(85, "readlink", kPath, kGen, kInt), MakeEntry(86, "uselib", kPath), MakeEntry(87, "swapon", kHex, kHex, kHex, kHex), MakeEntry(88, "reboot", kGen, kGen, kGen, kGen), MakeEntry(91, "munmap", kHex, kHex), MakeEntry(92, "truncate", kPath, kHex, kHex, kHex), MakeEntry(93, "ftruncate", kGen, kGen, kGen, kGen), MakeEntry(94, "fchmod", kGen, kGen, kGen, kGen), MakeEntry(95, "fchown", kGen, kGen, kGen, kGen), MakeEntry(96, "getpriority", kGen, kGen, kGen, kGen), MakeEntry(97, "setpriority", kGen, kGen, kGen, kGen), MakeEntry(99, "statfs", kPath, kGen, kGen, kGen), MakeEntry(100, "fstatfs", kGen, kGen, kGen, kGen), MakeEntry(103, "syslog", kGen, kGen, kGen, kGen), MakeEntry(104, "setitimer", kGen, kGen, kGen, kGen), MakeEntry(105, "getitimer", kGen, kGen, kGen, kGen), MakeEntry(106, "stat", kPath, kGen), MakeEntry(107, "lstat", kPath, kGen), MakeEntry(108, "fstat", kHex, kHex, kHex, kHex), MakeEntry(111, "vhangup", kGen, kGen, kGen, kGen), MakeEntry(114, "wait4", kHex, kHex, kHex, kHex), MakeEntry(115, "swapoff", kHex, kHex, kHex, kHex), MakeEntry(116, "sysinfo", kGen, kGen, kGen, kGen), MakeEntry(118, "fsync", kGen, kGen, kGen, kGen), MakeEntry(119, "sigreturn", kHex, kHex, kHex, kHex), MakeEntry(120, "clone", kCloneFlag, kHex, kHex, kHex), MakeEntry(121, "setdomainname", kGen, kGen, kGen, kGen), MakeEntry(122, "uname", kGen, kGen, kGen, kGen), MakeEntry(124, "adjtimex", kGen, kGen, kGen, kGen), MakeEntry(125, "mprotect", kHex, kHex, kHex), MakeEntry(126, "sigprocmask", kHex, kHex, kHex, kHex), MakeEntry(128, "init_module", kGen, kGen, kGen, kGen), MakeEntry(129, "delete_module", kGen, kGen, kGen, kGen), MakeEntry(131, "quotactl", kHex, kHex, kHex, kHex), MakeEntry(132, "getpgid", kGen, kGen, kGen, kGen), MakeEntry(133, "fchdir", kGen, kGen, kGen, kGen), MakeEntry(134, "bdflush", kHex, kHex, kHex, kHex), MakeEntry(135, "sysfs", kGen, kGen, kGen, kGen), MakeEntry(136, "personality", kGen, kGen, kGen, kGen), MakeEntry(138, "setfsuid", kGen, kGen, kGen, kGen), MakeEntry(139, "setfsgid", kGen, kGen, kGen, kGen), MakeEntry(140, "_llseek", kHex, kHex, kHex, kHex), MakeEntry(141, "getdents", kGen, kGen, kGen, kGen), MakeEntry(142, "_newselect", kHex, kHex, kHex, kHex), MakeEntry(143, "flock", kGen, kGen, kGen, kGen), MakeEntry(144, "msync", kGen, kGen, kGen, kGen), MakeEntry(145, "readv", kGen, kGen, kGen, kGen), MakeEntry(146, "writev", kGen, kGen, kGen, kGen), MakeEntry(147, "getsid", kGen, kGen, kGen, kGen), MakeEntry(148, "fdatasync", kGen, kGen, kGen, kGen), MakeEntry(149, "_sysctl", kGen, kGen, kGen, kGen), MakeEntry(150, "mlock", kGen, kGen, kGen, kGen), MakeEntry(151, "munlock", kGen, kGen, kGen, kGen), MakeEntry(152, "mlockall", kGen, kGen, kGen, kGen), MakeEntry(153, "munlockall", kGen, kGen, kGen, kGen), MakeEntry(154, "sched_setparam", kGen, kGen, kGen, kGen), MakeEntry(155, "sched_getparam", kGen, kGen, kGen, kGen), MakeEntry(156, "sched_setscheduler", kGen, kGen, kGen, kGen), MakeEntry(157, "sched_getscheduler", kGen, kGen, kGen, kGen), MakeEntry(158, "sched_yield", kGen, kGen, kGen, kGen), MakeEntry(159, "sched_get_priority_max", kGen, kGen, kGen, kGen), MakeEntry(160, "sched_get_priority_min", kGen, kGen, kGen, kGen), MakeEntry(161, "sched_rr_get_interval", kGen, kGen, kGen, kGen), MakeEntry(162, "nanosleep", kHex, kHex), MakeEntry(163, "mremap", kGen, kGen, kGen, kGen), MakeEntry(164, "setresuid", kGen, kGen, kGen, kGen), MakeEntry(165, "getresuid", kGen, kGen, kGen, kGen), MakeEntry(168, "poll", kGen, kGen, kGen, kGen), MakeEntry(169, "nfsservctl", kGen, kGen, kGen, kGen), MakeEntry(170, "setresgid", kGen, kGen, kGen, kGen), MakeEntry(171, "getresgid", kGen, kGen, kGen, kGen), MakeEntry(172, "prctl", kHex, kHex, kHex, kHex), MakeEntry(173, "rt_sigreturn", kGen, kGen, kGen, kGen), MakeEntry(174, "rt_sigaction", kHex, kHex, kHex, kHex), MakeEntry(175, "rt_sigprocmask", kGen, kGen, kGen, kGen), MakeEntry(176, "rt_sigpending", kGen, kGen, kGen, kGen), MakeEntry(177, "rt_sigtimedwait", kGen, kGen, kGen, kGen), MakeEntry(178, "rt_sigqueueinfo", kGen, kGen, kGen, kGen), MakeEntry(179, "rt_sigsuspend", kGen, kGen, kGen, kGen), MakeEntry(180, "pread64", kGen, kGen, kGen, kGen), MakeEntry(181, "pwrite64", kGen, kGen, kGen, kGen), MakeEntry(182, "chown", kHex, kHex, kHex, kHex), MakeEntry(183, "getcwd", kGen, kGen, kGen, kGen), MakeEntry(184, "capget", kGen, kGen, kGen, kGen), MakeEntry(185, "capset", kGen, kGen, kGen, kGen), MakeEntry(186, "sigaltstack", kGen, kGen, kGen, kGen), MakeEntry(187, "sendfile", kGen, kGen, kGen, kGen), MakeEntry(190, "vfork", kGen, kGen, kGen, kGen), MakeEntry(191, "ugetrlimit", kHex, kHex, kHex, kHex), MakeEntry(192, "mmap2", kHex, kHex, kHex, kHex), MakeEntry(193, "truncate64", kHex, kHex, kHex, kHex), MakeEntry(194, "ftruncate64", kHex, kHex, kHex, kHex), MakeEntry(195, "stat64", kHex, kHex, kHex, kHex), MakeEntry(196, "lstat64", kHex, kHex, kHex, kHex), MakeEntry(197, "fstat64", kHex, kHex, kHex, kHex), MakeEntry(198, "lchown32", kHex, kHex, kHex, kHex), MakeEntry(199, "getuid32", kHex, kHex, kHex, kHex), MakeEntry(200, "getgid32", kHex, kHex, kHex, kHex), MakeEntry(201, "geteuid32", kHex, kHex, kHex, kHex), MakeEntry(202, "getegid32", kHex, kHex, kHex, kHex), MakeEntry(203, "setreuid32", kHex, kHex, kHex, kHex), MakeEntry(204, "setregid32", kHex, kHex, kHex, kHex), MakeEntry(205, "getgroups32", kHex, kHex, kHex, kHex), MakeEntry(206, "setgroups32", kHex, kHex, kHex, kHex), MakeEntry(207, "fchown32", kHex, kHex, kHex, kHex), MakeEntry(208, "setresuid32", kHex, kHex, kHex, kHex), MakeEntry(209, "getresuid32", kHex, kHex, kHex, kHex), MakeEntry(210, "setresgid32", kHex, kHex, kHex, kHex), MakeEntry(211, "getresgid32", kHex, kHex, kHex, kHex), MakeEntry(212, "chown32", kHex, kHex, kHex, kHex), MakeEntry(213, "setuid32", kHex, kHex, kHex, kHex), MakeEntry(214, "setgid32", kHex, kHex, kHex, kHex), MakeEntry(215, "setfsuid32", kHex, kHex, kHex, kHex), MakeEntry(216, "setfsgid32", kHex, kHex, kHex, kHex), MakeEntry(217, "getdents64", kGen, kGen, kGen, kGen), MakeEntry(218, "pivot_root", kHex, kHex, kHex, kHex), MakeEntry(219, "mincore", kGen, kGen, kGen, kGen), MakeEntry(220, "madvise", kGen, kGen, kGen, kGen), MakeEntry(221, "fcntl64", kHex, kHex, kHex, kHex), MakeEntry(224, "gettid", kGen, kGen, kGen, kGen), MakeEntry(225, "readahead", kGen, kGen, kGen, kGen), MakeEntry(226, "setxattr", kHex, kHex, kHex, kHex), MakeEntry(227, "lsetxattr", kHex, kHex, kHex, kHex), MakeEntry(228, "fsetxattr", kGen, kGen, kGen, kGen), MakeEntry(229, "getxattr", kHex, kHex, kHex, kHex), MakeEntry(230, "lgetxattr", kHex, kHex, kHex, kHex), MakeEntry(231, "fgetxattr", kGen, kGen, kGen, kGen), MakeEntry(232, "listxattr", kHex, kHex, kHex, kHex), MakeEntry(233, "llistxattr", kHex, kHex, kHex, kHex), MakeEntry(234, "flistxattr", kGen, kGen, kGen, kGen), MakeEntry(235, "removexattr", kHex, kHex, kHex, kHex), MakeEntry(236, "lremovexattr", kGen, kGen, kGen, kGen), MakeEntry(237, "fremovexattr", kGen, kGen, kGen, kGen), MakeEntry(238, "tkill", kHex, kHex, kHex, kHex), MakeEntry(239, "sendfile64", kHex, kHex, kHex, kHex), MakeEntry(240, "futex", kGen, kGen, kGen, kGen), MakeEntry(241, "sched_setaffinity", kGen, kGen, kGen, kGen), MakeEntry(242, "sched_getaffinity", kGen, kGen, kGen, kGen), MakeEntry(243, "io_setup", kGen, kGen, kGen, kGen), MakeEntry(244, "io_destroy", kGen, kGen, kGen, kGen), MakeEntry(245, "io_getevents", kGen, kGen, kGen, kGen), MakeEntry(246, "io_submit", kGen, kGen, kGen, kGen), MakeEntry(247, "io_cancel", kGen, kGen, kGen, kGen), MakeEntry(248, "exit_group", kHex, kHex, kHex, kHex), MakeEntry(249, "lookup_dcookie", kGen, kGen, kGen, kGen), MakeEntry(250, "epoll_create", kGen, kGen, kGen, kGen), MakeEntry(251, "epoll_ctl", kGen, kGen, kGen, kGen), MakeEntry(252, "epoll_wait", kGen, kGen, kGen, kGen), MakeEntry(253, "remap_file_pages", kGen, kGen, kGen, kGen), MakeEntry(256, "set_tid_address", kHex), MakeEntry(257, "timer_create", kGen, kGen, kGen, kGen), MakeEntry(258, "timer_settime", kGen, kGen, kGen, kGen), MakeEntry(259, "timer_gettime", kGen, kGen, kGen, kGen), MakeEntry(260, "timer_getoverrun", kGen, kGen, kGen, kGen), MakeEntry(261, "timer_delete", kGen, kGen, kGen, kGen), MakeEntry(262, "clock_settime", kGen, kGen, kGen, kGen), MakeEntry(263, "clock_gettime", kGen, kGen, kGen, kGen), MakeEntry(264, "clock_getres", kGen, kGen, kGen, kGen), MakeEntry(265, "clock_nanosleep", kGen, kGen, kGen, kGen), MakeEntry(266, "statfs64", kHex, kHex, kHex, kHex), MakeEntry(267, "fstatfs64", kHex, kHex, kHex, kHex), MakeEntry(268, "tgkill", kHex, kHex, kHex, kHex), MakeEntry(269, "utimes", kGen, kGen, kGen, kGen), MakeEntry(271, "pciconfig_iobase", kHex, kHex, kHex, kHex), MakeEntry(272, "pciconfig_read", kHex, kHex, kHex, kHex), MakeEntry(273, "pciconfig_write", kHex, kHex, kHex, kHex), MakeEntry(274, "mq_open", kGen, kGen, kGen, kGen), MakeEntry(275, "mq_unlink", kGen, kGen, kGen, kGen), MakeEntry(276, "mq_timedsend", kGen, kGen, kGen, kGen), MakeEntry(277, "mq_timedreceive", kGen, kGen, kGen, kGen), MakeEntry(278, "mq_notify", kGen, kGen, kGen, kGen), MakeEntry(279, "mq_getsetattr", kGen, kGen, kGen, kGen), MakeEntry(280, "waitid", kGen, kGen, kGen, kGen), MakeEntry(281, "socket", kAddressFamily, kInt, kInt), MakeEntry(282, "bind", kGen, kGen, kGen, kGen), MakeEntry(283, "connect", kInt, kSockaddr, kInt), MakeEntry(284, "listen", kGen, kGen, kGen, kGen), MakeEntry(285, "accept", kGen, kGen, kGen, kGen), MakeEntry(286, "getsockname", kGen, kGen, kGen, kGen), MakeEntry(287, "getpeername", kGen, kGen, kGen, kGen), MakeEntry(288, "socketpair", kGen, kGen, kGen, kGen), MakeEntry(289, "send", kHex, kHex, kHex, kHex), MakeEntry(290, "sendto", kInt, kGen, kInt, kHex), MakeEntry(291, "recv", kHex, kHex, kHex, kHex), MakeEntry(292, "recvfrom", kGen, kGen, kGen, kGen), MakeEntry(293, "shutdown", kGen, kGen, kGen, kGen), MakeEntry(294, "setsockopt", kGen, kGen, kGen, kGen), MakeEntry(295, "getsockopt", kGen, kGen, kGen, kGen), MakeEntry(296, "sendmsg", kInt, kSockmsghdr, kHex), MakeEntry(297, "recvmsg", kGen, kGen, kGen, kGen), MakeEntry(298, "semop", UnknownArguments()), MakeEntry(299, "semget", UnknownArguments()), MakeEntry(300, "semctl", UnknownArguments()), MakeEntry(301, "msgsnd", UnknownArguments()), MakeEntry(302, "msgrcv", UnknownArguments()), MakeEntry(303, "msgget", UnknownArguments()), MakeEntry(304, "msgctl", UnknownArguments()), MakeEntry(305, "shmat", UnknownArguments()), MakeEntry(306, "shmdt", UnknownArguments()), MakeEntry(307, "shmget", UnknownArguments()), MakeEntry(308, "shmctl", UnknownArguments()), MakeEntry(309, "add_key", kGen, kGen, kGen, kGen), MakeEntry(310, "request_key", kGen, kGen, kGen, kGen), MakeEntry(311, "keyctl", kGen, kGen, kGen, kGen), MakeEntry(312, "semtimedop", UnknownArguments()), MakeEntry(313, "vserver", kHex, kHex, kHex, kHex), MakeEntry(314, "ioprio_set", kGen, kGen, kGen, kGen), MakeEntry(315, "ioprio_get", kGen, kGen, kGen, kGen), MakeEntry(316, "inotify_init", kGen, kGen, kGen, kGen), MakeEntry(317, "inotify_add_watch", kGen, kGen, kGen, kGen), MakeEntry(318, "inotify_rm_watch", kGen, kGen, kGen, kGen), MakeEntry(319, "mbind", kGen, kGen, kGen, kGen), MakeEntry(320, "get_mempolicy", kGen, kGen, kGen, kGen), MakeEntry(321, "set_mempolicy", kGen, kGen, kGen, kGen), MakeEntry(322, "openat", kGen, kPath, kOct, kHex), MakeEntry(323, "mkdirat", kGen, kPath), MakeEntry(324, "mknodat", kGen, kPath), MakeEntry(325, "fchownat", kGen, kPath), MakeEntry(326, "futimesat", kGen, kPath), MakeEntry(327, "fstatat64", kHex, kHex, kHex, kHex), MakeEntry(328, "unlinkat", kGen, kPath), MakeEntry(329, "renameat", kGen, kPath, kGen, kPath), MakeEntry(330, "linkat", kGen, kPath, kGen, kPath), MakeEntry(331, "symlinkat", kPath, kGen, kPath), MakeEntry(332, "readlinkat", kGen, kPath), MakeEntry(333, "fchmodat", kGen, kPath), MakeEntry(334, "faccessat", kGen, kPath), MakeEntry(335, "pselect6", kGen, kGen, kGen, kGen), MakeEntry(336, "ppoll", kGen, kGen, kGen, kGen), MakeEntry(337, "unshare", kGen, kGen, kGen, kGen), MakeEntry(338, "set_robust_list", kGen, kGen), MakeEntry(339, "get_robust_list", kGen, kGen, kGen, kGen), MakeEntry(340, "splice", kGen, kGen, kGen, kGen), MakeEntry(342, "tee", kGen, kGen, kGen, kGen), MakeEntry(343, "vmsplice", kGen, kGen, kGen, kGen), MakeEntry(344, "move_pages", kGen, kGen, kGen, kGen), MakeEntry(345, "getcpu", kHex, kHex, kHex), MakeEntry(346, "epoll_pwait", kGen, kGen, kGen, kGen), MakeEntry(347, "kexec_load", kGen, kGen, kGen, kGen), MakeEntry(348, "utimensat", kGen, kGen, kGen, kGen), MakeEntry(349, "signalfd", kGen, kGen, kGen, kGen), MakeEntry(350, "timerfd_create", kGen, kGen, kGen, kGen), MakeEntry(351, "eventfd", kGen, kGen, kGen, kGen), MakeEntry(352, "fallocate", kGen, kGen, kGen, kGen), MakeEntry(353, "timerfd_settime", kGen, kGen, kGen, kGen), MakeEntry(354, "timerfd_gettime", kGen, kGen, kGen, kGen), MakeEntry(355, "signalfd4", kGen, kGen, kGen, kGen), MakeEntry(356, "eventfd2", kGen, kGen, kGen, kGen), MakeEntry(357, "epoll_create1", kGen, kGen, kGen, kGen), MakeEntry(358, "dup3", kGen, kGen, kGen), MakeEntry(359, "pipe2", kGen, kGen, kGen, kGen), MakeEntry(360, "inotify_init1", kGen, kGen, kGen, kGen), MakeEntry(361, "preadv", kGen, kGen, kGen, kGen), MakeEntry(362, "pwritev", kGen, kGen, kGen, kGen), MakeEntry(363, "rt_tgsigqueueinfo", kGen, kGen, kGen, kGen), MakeEntry(364, "perf_event_open", kGen, kGen, kGen, kGen), MakeEntry(365, "recvmmsg", kHex, kHex, kHex, kHex), MakeEntry(366, "accept4", kGen, kGen, kGen, kGen), MakeEntry(367, "fanotify_init", kHex, kHex, kHex, kHex), MakeEntry(368, "fanotify_mark", kHex, kHex, kHex, kHex), MakeEntry(369, "prlimit64", kHex, kHex, kHex, kHex), MakeEntry(370, "name_to_handle_at", kHex, kHex, kHex, kHex), MakeEntry(371, "open_by_handle_at", kHex, kHex, kHex, kHex), MakeEntry(372, "clock_adjtime", kHex, kHex, kHex, kHex), MakeEntry(373, "syncfs", kHex, kHex, kHex, kHex), MakeEntry(374, "sendmmsg", kHex, kHex, kHex, kHex), MakeEntry(375, "setns", kHex, kHex, kHex, kHex), MakeEntry(376, "process_vm_readv", kHex, kHex, kHex, kHex), MakeEntry(377, "process_vm_writev", kHex, kHex, kHex, kHex), MakeEntry(378, "kcmp", kHex, kHex, kHex, kHex), MakeEntry(379, "finit_module", kHex, kHex, kHex, kHex), MakeEntry(380, "sched_setattr", kGen, kGen, kGen, kGen), MakeEntry(381, "sched_getattr", kGen, kGen, kGen, kGen), MakeEntry(382, "renameat2", kGen, kPath, kGen, kPath), MakeEntry(383, "seccomp", kGen, kGen, kGen, kGen), MakeEntry(384, "getrandom", kGen, kGen, kGen, kGen), MakeEntry(385, "memfd_create", kGen, kGen, kGen, kGen), MakeEntry(386, "bpf", kHex, kHex, kHex, kHex), MakeEntry(387, "execveat", kHex, kHex, kHex, kHex), MakeEntry(388, "userfaultfd", kHex), MakeEntry(389, "membarrier", kHex, kHex), MakeEntry(390, "mlock2", kHex, kHex, kHex, kHex), MakeEntry(391, "copy_file_range", kHex, kHex, kHex, kHex), MakeEntry(392, "preadv2", kHex, kHex, kHex, kHex), MakeEntry(393, "pwritev2", kHex, kHex, kHex, kHex), MakeEntry(400, "migrate_pages", kGen, kGen, kGen, kGen), MakeEntry(401, "kexec_file_load", kGen, kGen, kGen, kGen), MakeEntry(0xf0001, "ARM_breakpoint", kHex, kHex, kHex, kHex), MakeEntry(0xf0002, "ARM_cacheflush", kHex, kHex, kHex, kHex), MakeEntry(0xf0003, "ARM_usr26", kHex, kHex, kHex, kHex), MakeEntry(0xf0004, "ARM_usr32", kHex, kHex, kHex, kHex), MakeEntry(0xf0005, "ARM_set_tls", kHex, kHex, kHex, kHex), // clang-format on }; static_assert(IsSorted(kSyscallDataArm32, SyscallTable::Entry::BySyscallNr), "Syscalls should be sorted"); } // namespace SyscallTable SyscallTable::get(sapi::cpu::Architecture arch) { switch (arch) { case sapi::cpu::kX8664: return SyscallTable(kSyscallDataX8664); case sapi::cpu::kX86: return SyscallTable(kSyscallDataX8632); case sapi::cpu::kPPC64LE: return SyscallTable(kSyscallDataPPC64LE); case sapi::cpu::kArm64: return SyscallTable(kSyscallDataArm64); case sapi::cpu::kArm: return SyscallTable(kSyscallDataArm32); default: return SyscallTable(); } } } // namespace sandbox2
56.291994
80
0.652844
oshogbo
4920e34b4bc7e375aef545fb49136ef9e39dd7f1
34,971
cpp
C++
src/pvrt/PVRTMatrixF.cpp
aunali1/sauerbraten-ios
247de70e6889d424b041ce08627aa446caaef46c
[ "Cube", "Zlib" ]
1
2019-10-25T05:46:42.000Z
2019-10-25T05:46:42.000Z
src/pvrt/PVRTMatrixF.cpp
aunali1/sauerbraten-ios
247de70e6889d424b041ce08627aa446caaef46c
[ "Cube", "Zlib" ]
1
2015-05-24T01:30:20.000Z
2015-05-24T01:30:20.000Z
src/pvrt/PVRTMatrixF.cpp
aunali1/sauerbraten-ios
247de70e6889d424b041ce08627aa446caaef46c
[ "Cube", "Zlib" ]
null
null
null
/****************************************************************************** @File PVRTMatrixF.cpp @Title @Copyright Copyright (C) 1999 - 2008 by Imagination Technologies Limited. @Platform ANSI compatible @Description Set of mathematical functions involving matrices, vectors and quaternions. The general matrix format used is directly compatible with, for example, both DirectX and OpenGL. For the reasons why, read this: http://research.microsoft.com/~hollasch/cgindex/math/matrix/column-vec.html ******************************************************************************/ #include "PVRTGlobal.h" //#include "PVRTContext.h" #include <math.h> #include <string.h> #include "PVRTFixedPoint.h" // Only needed for trig function float lookups #include "PVRTMatrix.h" /**************************************************************************** ** Constants ****************************************************************************/ static const PVRTMATRIXf c_mIdentity = { { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } }; /**************************************************************************** ** Functions ****************************************************************************/ /*!*************************************************************************** @Function PVRTMatrixIdentityF @Output mOut Set to identity @Description Reset matrix to identity matrix. *****************************************************************************/ void PVRTMatrixIdentityF(PVRTMATRIXf &mOut) { mOut.f[ 0]=1.0f; mOut.f[ 4]=0.0f; mOut.f[ 8]=0.0f; mOut.f[12]=0.0f; mOut.f[ 1]=0.0f; mOut.f[ 5]=1.0f; mOut.f[ 9]=0.0f; mOut.f[13]=0.0f; mOut.f[ 2]=0.0f; mOut.f[ 6]=0.0f; mOut.f[10]=1.0f; mOut.f[14]=0.0f; mOut.f[ 3]=0.0f; mOut.f[ 7]=0.0f; mOut.f[11]=0.0f; mOut.f[15]=1.0f; } /*!*************************************************************************** @Function PVRTMatrixMultiplyF @Output mOut Result of mA x mB @Input mA First operand @Input mB Second operand @Description Multiply mA by mB and assign the result to mOut (mOut = p1 * p2). A copy of the result matrix is done in the function because mOut can be a parameter mA or mB. *****************************************************************************/ void PVRTMatrixMultiplyF( PVRTMATRIXf &mOut, const PVRTMATRIXf &mA, const PVRTMATRIXf &mB) { PVRTMATRIXf mRet; /* Perform calculation on a dummy matrix (mRet) */ mRet.f[ 0] = mA.f[ 0]*mB.f[ 0] + mA.f[ 1]*mB.f[ 4] + mA.f[ 2]*mB.f[ 8] + mA.f[ 3]*mB.f[12]; mRet.f[ 1] = mA.f[ 0]*mB.f[ 1] + mA.f[ 1]*mB.f[ 5] + mA.f[ 2]*mB.f[ 9] + mA.f[ 3]*mB.f[13]; mRet.f[ 2] = mA.f[ 0]*mB.f[ 2] + mA.f[ 1]*mB.f[ 6] + mA.f[ 2]*mB.f[10] + mA.f[ 3]*mB.f[14]; mRet.f[ 3] = mA.f[ 0]*mB.f[ 3] + mA.f[ 1]*mB.f[ 7] + mA.f[ 2]*mB.f[11] + mA.f[ 3]*mB.f[15]; mRet.f[ 4] = mA.f[ 4]*mB.f[ 0] + mA.f[ 5]*mB.f[ 4] + mA.f[ 6]*mB.f[ 8] + mA.f[ 7]*mB.f[12]; mRet.f[ 5] = mA.f[ 4]*mB.f[ 1] + mA.f[ 5]*mB.f[ 5] + mA.f[ 6]*mB.f[ 9] + mA.f[ 7]*mB.f[13]; mRet.f[ 6] = mA.f[ 4]*mB.f[ 2] + mA.f[ 5]*mB.f[ 6] + mA.f[ 6]*mB.f[10] + mA.f[ 7]*mB.f[14]; mRet.f[ 7] = mA.f[ 4]*mB.f[ 3] + mA.f[ 5]*mB.f[ 7] + mA.f[ 6]*mB.f[11] + mA.f[ 7]*mB.f[15]; mRet.f[ 8] = mA.f[ 8]*mB.f[ 0] + mA.f[ 9]*mB.f[ 4] + mA.f[10]*mB.f[ 8] + mA.f[11]*mB.f[12]; mRet.f[ 9] = mA.f[ 8]*mB.f[ 1] + mA.f[ 9]*mB.f[ 5] + mA.f[10]*mB.f[ 9] + mA.f[11]*mB.f[13]; mRet.f[10] = mA.f[ 8]*mB.f[ 2] + mA.f[ 9]*mB.f[ 6] + mA.f[10]*mB.f[10] + mA.f[11]*mB.f[14]; mRet.f[11] = mA.f[ 8]*mB.f[ 3] + mA.f[ 9]*mB.f[ 7] + mA.f[10]*mB.f[11] + mA.f[11]*mB.f[15]; mRet.f[12] = mA.f[12]*mB.f[ 0] + mA.f[13]*mB.f[ 4] + mA.f[14]*mB.f[ 8] + mA.f[15]*mB.f[12]; mRet.f[13] = mA.f[12]*mB.f[ 1] + mA.f[13]*mB.f[ 5] + mA.f[14]*mB.f[ 9] + mA.f[15]*mB.f[13]; mRet.f[14] = mA.f[12]*mB.f[ 2] + mA.f[13]*mB.f[ 6] + mA.f[14]*mB.f[10] + mA.f[15]*mB.f[14]; mRet.f[15] = mA.f[12]*mB.f[ 3] + mA.f[13]*mB.f[ 7] + mA.f[14]*mB.f[11] + mA.f[15]*mB.f[15]; /* Copy result in pResultMatrix */ mOut = mRet; } /*!*************************************************************************** @Function Name PVRTMatrixTranslationF @Output mOut Translation matrix @Input fX X component of the translation @Input fY Y component of the translation @Input fZ Z component of the translation @Description Build a transaltion matrix mOut using fX, fY and fZ. *****************************************************************************/ void PVRTMatrixTranslationF( PVRTMATRIXf &mOut, const float fX, const float fY, const float fZ) { mOut.f[ 0]=1.0f; mOut.f[ 4]=0.0f; mOut.f[ 8]=0.0f; mOut.f[12]=fX; mOut.f[ 1]=0.0f; mOut.f[ 5]=1.0f; mOut.f[ 9]=0.0f; mOut.f[13]=fY; mOut.f[ 2]=0.0f; mOut.f[ 6]=0.0f; mOut.f[10]=1.0f; mOut.f[14]=fZ; mOut.f[ 3]=0.0f; mOut.f[ 7]=0.0f; mOut.f[11]=0.0f; mOut.f[15]=1.0f; } /*!*************************************************************************** @Function Name PVRTMatrixScalingF @Output mOut Scale matrix @Input fX X component of the scaling @Input fY Y component of the scaling @Input fZ Z component of the scaling @Description Build a scale matrix mOut using fX, fY and fZ. *****************************************************************************/ void PVRTMatrixScalingF( PVRTMATRIXf &mOut, const float fX, const float fY, const float fZ) { mOut.f[ 0]=fX; mOut.f[ 4]=0.0f; mOut.f[ 8]=0.0f; mOut.f[12]=0.0f; mOut.f[ 1]=0.0f; mOut.f[ 5]=fY; mOut.f[ 9]=0.0f; mOut.f[13]=0.0f; mOut.f[ 2]=0.0f; mOut.f[ 6]=0.0f; mOut.f[10]=fZ; mOut.f[14]=0.0f; mOut.f[ 3]=0.0f; mOut.f[ 7]=0.0f; mOut.f[11]=0.0f; mOut.f[15]=1.0f; } /*!*************************************************************************** @Function Name PVRTMatrixRotationXF @Output mOut Rotation matrix @Input fAngle Angle of the rotation @Description Create an X rotation matrix mOut. *****************************************************************************/ void PVRTMatrixRotationXF( PVRTMATRIXf &mOut, const float fAngle) { float fCosine, fSine; /* Precompute cos and sin */ #if defined(BUILD_DX9) || defined(BUILD_D3DM) fCosine = (float)PVRTFCOS(-fAngle); fSine = (float)PVRTFSIN(-fAngle); #else fCosine = (float)PVRTFCOS(fAngle); fSine = (float)PVRTFSIN(fAngle); #endif /* Create the trigonometric matrix corresponding to X Rotation */ mOut.f[ 0]=1.0f; mOut.f[ 4]=0.0f; mOut.f[ 8]=0.0f; mOut.f[12]=0.0f; mOut.f[ 1]=0.0f; mOut.f[ 5]=fCosine; mOut.f[ 9]=fSine; mOut.f[13]=0.0f; mOut.f[ 2]=0.0f; mOut.f[ 6]=-fSine; mOut.f[10]=fCosine; mOut.f[14]=0.0f; mOut.f[ 3]=0.0f; mOut.f[ 7]=0.0f; mOut.f[11]=0.0f; mOut.f[15]=1.0f; } /*!*************************************************************************** @Function Name PVRTMatrixRotationYF @Output mOut Rotation matrix @Input fAngle Angle of the rotation @Description Create an Y rotation matrix mOut. *****************************************************************************/ void PVRTMatrixRotationYF( PVRTMATRIXf &mOut, const float fAngle) { float fCosine, fSine; /* Precompute cos and sin */ #if defined(BUILD_DX9) || defined(BUILD_D3DM) fCosine = (float)PVRTFCOS(-fAngle); fSine = (float)PVRTFSIN(-fAngle); #else fCosine = (float)PVRTFCOS(fAngle); fSine = (float)PVRTFSIN(fAngle); #endif /* Create the trigonometric matrix corresponding to Y Rotation */ mOut.f[ 0]=fCosine; mOut.f[ 4]=0.0f; mOut.f[ 8]=-fSine; mOut.f[12]=0.0f; mOut.f[ 1]=0.0f; mOut.f[ 5]=1.0f; mOut.f[ 9]=0.0f; mOut.f[13]=0.0f; mOut.f[ 2]=fSine; mOut.f[ 6]=0.0f; mOut.f[10]=fCosine; mOut.f[14]=0.0f; mOut.f[ 3]=0.0f; mOut.f[ 7]=0.0f; mOut.f[11]=0.0f; mOut.f[15]=1.0f; } /*!*************************************************************************** @Function Name PVRTMatrixRotationZF @Output mOut Rotation matrix @Input fAngle Angle of the rotation @Description Create an Z rotation matrix mOut. *****************************************************************************/ void PVRTMatrixRotationZF( PVRTMATRIXf &mOut, const float fAngle) { float fCosine, fSine; /* Precompute cos and sin */ #if defined(BUILD_DX9) || defined(BUILD_D3DM) fCosine = (float)PVRTFCOS(-fAngle); fSine = (float)PVRTFSIN(-fAngle); #else fCosine = (float)PVRTFCOS(fAngle); fSine = (float)PVRTFSIN(fAngle); #endif /* Create the trigonometric matrix corresponding to Z Rotation */ mOut.f[ 0]=fCosine; mOut.f[ 4]=fSine; mOut.f[ 8]=0.0f; mOut.f[12]=0.0f; mOut.f[ 1]=-fSine; mOut.f[ 5]=fCosine; mOut.f[ 9]=0.0f; mOut.f[13]=0.0f; mOut.f[ 2]=0.0f; mOut.f[ 6]=0.0f; mOut.f[10]=1.0f; mOut.f[14]=0.0f; mOut.f[ 3]=0.0f; mOut.f[ 7]=0.0f; mOut.f[11]=0.0f; mOut.f[15]=1.0f; } /*!*************************************************************************** @Function Name PVRTMatrixTransposeF @Output mOut Transposed matrix @Input mIn Original matrix @Description Compute the transpose matrix of mIn. *****************************************************************************/ void PVRTMatrixTransposeF( PVRTMATRIXf &mOut, const PVRTMATRIXf &mIn) { PVRTMATRIXf mTmp; mTmp.f[ 0]=mIn.f[ 0]; mTmp.f[ 4]=mIn.f[ 1]; mTmp.f[ 8]=mIn.f[ 2]; mTmp.f[12]=mIn.f[ 3]; mTmp.f[ 1]=mIn.f[ 4]; mTmp.f[ 5]=mIn.f[ 5]; mTmp.f[ 9]=mIn.f[ 6]; mTmp.f[13]=mIn.f[ 7]; mTmp.f[ 2]=mIn.f[ 8]; mTmp.f[ 6]=mIn.f[ 9]; mTmp.f[10]=mIn.f[10]; mTmp.f[14]=mIn.f[11]; mTmp.f[ 3]=mIn.f[12]; mTmp.f[ 7]=mIn.f[13]; mTmp.f[11]=mIn.f[14]; mTmp.f[15]=mIn.f[15]; mOut = mTmp; } /*!*************************************************************************** @Function PVRTMatrixInverseF @Output mOut Inversed matrix @Input mIn Original matrix @Description Compute the inverse matrix of mIn. The matrix must be of the form : A 0 C 1 Where A is a 3x3 matrix and C is a 1x3 matrix. *****************************************************************************/ void PVRTMatrixInverseF( PVRTMATRIXf &mOut, const PVRTMATRIXf &mIn) { PVRTMATRIXf mDummyMatrix; double det_1; double pos, neg, temp; /* Calculate the determinant of submatrix A and determine if the the matrix is singular as limited by the double precision floating-point data representation. */ pos = neg = 0.0; temp = mIn.f[ 0] * mIn.f[ 5] * mIn.f[10]; if (temp >= 0.0) pos += temp; else neg += temp; temp = mIn.f[ 4] * mIn.f[ 9] * mIn.f[ 2]; if (temp >= 0.0) pos += temp; else neg += temp; temp = mIn.f[ 8] * mIn.f[ 1] * mIn.f[ 6]; if (temp >= 0.0) pos += temp; else neg += temp; temp = -mIn.f[ 8] * mIn.f[ 5] * mIn.f[ 2]; if (temp >= 0.0) pos += temp; else neg += temp; temp = -mIn.f[ 4] * mIn.f[ 1] * mIn.f[10]; if (temp >= 0.0) pos += temp; else neg += temp; temp = -mIn.f[ 0] * mIn.f[ 9] * mIn.f[ 6]; if (temp >= 0.0) pos += temp; else neg += temp; det_1 = pos + neg; /* Is the submatrix A singular? */ if ((det_1 == 0.0) || (PVRTABS(det_1 / (pos - neg)) < 1.0e-15)) { /* Matrix M has no inverse */ #ifndef BADA _RPT0(_CRT_WARN, "Matrix has no inverse : singular matrix\n"); #endif return; } else { /* Calculate inverse(A) = adj(A) / det(A) */ det_1 = 1.0 / det_1; mDummyMatrix.f[ 0] = ( mIn.f[ 5] * mIn.f[10] - mIn.f[ 9] * mIn.f[ 6] ) * (float)det_1; mDummyMatrix.f[ 1] = - ( mIn.f[ 1] * mIn.f[10] - mIn.f[ 9] * mIn.f[ 2] ) * (float)det_1; mDummyMatrix.f[ 2] = ( mIn.f[ 1] * mIn.f[ 6] - mIn.f[ 5] * mIn.f[ 2] ) * (float)det_1; mDummyMatrix.f[ 4] = - ( mIn.f[ 4] * mIn.f[10] - mIn.f[ 8] * mIn.f[ 6] ) * (float)det_1; mDummyMatrix.f[ 5] = ( mIn.f[ 0] * mIn.f[10] - mIn.f[ 8] * mIn.f[ 2] ) * (float)det_1; mDummyMatrix.f[ 6] = - ( mIn.f[ 0] * mIn.f[ 6] - mIn.f[ 4] * mIn.f[ 2] ) * (float)det_1; mDummyMatrix.f[ 8] = ( mIn.f[ 4] * mIn.f[ 9] - mIn.f[ 8] * mIn.f[ 5] ) * (float)det_1; mDummyMatrix.f[ 9] = - ( mIn.f[ 0] * mIn.f[ 9] - mIn.f[ 8] * mIn.f[ 1] ) * (float)det_1; mDummyMatrix.f[10] = ( mIn.f[ 0] * mIn.f[ 5] - mIn.f[ 4] * mIn.f[ 1] ) * (float)det_1; /* Calculate -C * inverse(A) */ mDummyMatrix.f[12] = - ( mIn.f[12] * mDummyMatrix.f[ 0] + mIn.f[13] * mDummyMatrix.f[ 4] + mIn.f[14] * mDummyMatrix.f[ 8] ); mDummyMatrix.f[13] = - ( mIn.f[12] * mDummyMatrix.f[ 1] + mIn.f[13] * mDummyMatrix.f[ 5] + mIn.f[14] * mDummyMatrix.f[ 9] ); mDummyMatrix.f[14] = - ( mIn.f[12] * mDummyMatrix.f[ 2] + mIn.f[13] * mDummyMatrix.f[ 6] + mIn.f[14] * mDummyMatrix.f[10] ); /* Fill in last row */ mDummyMatrix.f[ 3] = 0.0f; mDummyMatrix.f[ 7] = 0.0f; mDummyMatrix.f[11] = 0.0f; mDummyMatrix.f[15] = 1.0f; } /* Copy contents of dummy matrix in pfMatrix */ mOut = mDummyMatrix; } /*!*************************************************************************** @Function PVRTMatrixInverseExF @Output mOut Inversed matrix @Input mIn Original matrix @Description Compute the inverse matrix of mIn. Uses a linear equation solver and the knowledge that M.M^-1=I. Use this fn to calculate the inverse of matrices that PVRTMatrixInverse() cannot. *****************************************************************************/ void PVRTMatrixInverseExF( PVRTMATRIXf &mOut, const PVRTMATRIXf &mIn) { PVRTMATRIXf mTmp; float *ppfRows[4]; float pfRes[4]; float pfIn[20]; int i, j; for(i = 0; i < 4; ++i) ppfRows[i] = &pfIn[i * 5]; /* Solve 4 sets of 4 linear equations */ for(i = 0; i < 4; ++i) { for(j = 0; j < 4; ++j) { ppfRows[j][0] = c_mIdentity.f[i + 4 * j]; memcpy(&ppfRows[j][1], &mIn.f[j * 4], 4 * sizeof(float)); } PVRTMatrixLinearEqSolveF(pfRes, (float**)ppfRows, 4); for(j = 0; j < 4; ++j) { mTmp.f[i + 4 * j] = pfRes[j]; } } mOut = mTmp; } /*!*************************************************************************** @Function PVRTMatrixLookAtLHF @Output mOut Look-at view matrix @Input vEye Position of the camera @Input vAt Point the camera is looking at @Input vUp Up direction for the camera @Description Create a look-at view matrix. *****************************************************************************/ void PVRTMatrixLookAtLHF( PVRTMATRIXf &mOut, const PVRTVECTOR3f &vEye, const PVRTVECTOR3f &vAt, const PVRTVECTOR3f &vUp) { PVRTVECTOR3f f, vUpActual, s, u; PVRTMATRIXf t; f.x = vEye.x - vAt.x; f.y = vEye.y - vAt.y; f.z = vEye.z - vAt.z; PVRTMatrixVec3NormalizeF(f, f); PVRTMatrixVec3NormalizeF(vUpActual, vUp); PVRTMatrixVec3CrossProductF(s, f, vUpActual); PVRTMatrixVec3CrossProductF(u, s, f); mOut.f[ 0] = s.x; mOut.f[ 1] = u.x; mOut.f[ 2] = -f.x; mOut.f[ 3] = 0; mOut.f[ 4] = s.y; mOut.f[ 5] = u.y; mOut.f[ 6] = -f.y; mOut.f[ 7] = 0; mOut.f[ 8] = s.z; mOut.f[ 9] = u.z; mOut.f[10] = -f.z; mOut.f[11] = 0; mOut.f[12] = 0; mOut.f[13] = 0; mOut.f[14] = 0; mOut.f[15] = 1; PVRTMatrixTranslationF(t, -vEye.x, -vEye.y, -vEye.z); PVRTMatrixMultiplyF(mOut, t, mOut); } /*!*************************************************************************** @Function PVRTMatrixLookAtRHF @Output mOut Look-at view matrix @Input vEye Position of the camera @Input vAt Point the camera is looking at @Input vUp Up direction for the camera @Description Create a look-at view matrix. *****************************************************************************/ void PVRTMatrixLookAtRHF( PVRTMATRIXf &mOut, const PVRTVECTOR3f &vEye, const PVRTVECTOR3f &vAt, const PVRTVECTOR3f &vUp) { PVRTVECTOR3f f, vUpActual, s, u; PVRTMATRIXf t; f.x = vAt.x - vEye.x; f.y = vAt.y - vEye.y; f.z = vAt.z - vEye.z; PVRTMatrixVec3NormalizeF(f, f); PVRTMatrixVec3NormalizeF(vUpActual, vUp); PVRTMatrixVec3CrossProductF(s, f, vUpActual); PVRTMatrixVec3CrossProductF(u, s, f); mOut.f[ 0] = s.x; mOut.f[ 1] = u.x; mOut.f[ 2] = -f.x; mOut.f[ 3] = 0; mOut.f[ 4] = s.y; mOut.f[ 5] = u.y; mOut.f[ 6] = -f.y; mOut.f[ 7] = 0; mOut.f[ 8] = s.z; mOut.f[ 9] = u.z; mOut.f[10] = -f.z; mOut.f[11] = 0; mOut.f[12] = 0; mOut.f[13] = 0; mOut.f[14] = 0; mOut.f[15] = 1; PVRTMatrixTranslationF(t, -vEye.x, -vEye.y, -vEye.z); PVRTMatrixMultiplyF(mOut, t, mOut); } /*!*************************************************************************** @Function PVRTMatrixPerspectiveFovLHF @Output mOut Perspective matrix @Input fFOVy Field of view @Input fAspect Aspect ratio @Input fNear Near clipping distance @Input fFar Far clipping distance @Input bRotate Should we rotate it ? (for upright screens) @Description Create a perspective matrix. *****************************************************************************/ void PVRTMatrixPerspectiveFovLHF( PVRTMATRIXf &mOut, const float fFOVy, const float fAspect, const float fNear, const float fFar, const bool bRotate) { float f, n, fRealAspect; if (bRotate) fRealAspect = 1.0f / fAspect; else fRealAspect = fAspect; // cotangent(a) == 1.0f / tan(a); f = 1.0f / (float)PVRTFTAN(fFOVy * 0.5f); n = 1.0f / (fFar - fNear); mOut.f[ 0] = f / fRealAspect; mOut.f[ 1] = 0; mOut.f[ 2] = 0; mOut.f[ 3] = 0; mOut.f[ 4] = 0; mOut.f[ 5] = f; mOut.f[ 6] = 0; mOut.f[ 7] = 0; mOut.f[ 8] = 0; mOut.f[ 9] = 0; mOut.f[10] = fFar * n; mOut.f[11] = 1; mOut.f[12] = 0; mOut.f[13] = 0; mOut.f[14] = -fFar * fNear * n; mOut.f[15] = 0; if (bRotate) { PVRTMATRIXf mRotation, mTemp = mOut; PVRTMatrixRotationZF(mRotation, 90.0f*PVRT_PIf/180.0f); PVRTMatrixMultiplyF(mOut, mTemp, mRotation); } } /*!*************************************************************************** @Function PVRTMatrixPerspectiveFovRHF @Output mOut Perspective matrix @Input fFOVy Field of view @Input fAspect Aspect ratio @Input fNear Near clipping distance @Input fFar Far clipping distance @Input bRotate Should we rotate it ? (for upright screens) @Description Create a perspective matrix. *****************************************************************************/ void PVRTMatrixPerspectiveFovRHF( PVRTMATRIXf &mOut, const float fFOVy, const float fAspect, const float fNear, const float fFar, const bool bRotate) { float f, n, fRealAspect; if (bRotate) fRealAspect = 1.0f / fAspect; else fRealAspect = fAspect; // cotangent(a) == 1.0f / tan(a); f = 1.0f / (float)PVRTFTAN(fFOVy * 0.5f); n = 1.0f / (fNear - fFar); mOut.f[ 0] = f / fRealAspect; mOut.f[ 1] = 0; mOut.f[ 2] = 0; mOut.f[ 3] = 0; mOut.f[ 4] = 0; mOut.f[ 5] = f; mOut.f[ 6] = 0; mOut.f[ 7] = 0; mOut.f[ 8] = 0; mOut.f[ 9] = 0; mOut.f[10] = (fFar + fNear) * n; mOut.f[11] = -1; mOut.f[12] = 0; mOut.f[13] = 0; mOut.f[14] = (2 * fFar * fNear) * n; mOut.f[15] = 0; if (bRotate) { PVRTMATRIXf mRotation, mTemp = mOut; PVRTMatrixRotationZF(mRotation, -90.0f*PVRT_PIf/180.0f); PVRTMatrixMultiplyF(mOut, mTemp, mRotation); } } /*!*************************************************************************** @Function PVRTMatrixOrthoLHF @Output mOut Orthographic matrix @Input w Width of the screen @Input h Height of the screen @Input zn Near clipping distance @Input zf Far clipping distance @Input bRotate Should we rotate it ? (for upright screens) @Description Create an orthographic matrix. *****************************************************************************/ void PVRTMatrixOrthoLHF( PVRTMATRIXf &mOut, const float w, const float h, const float zn, const float zf, const bool bRotate) { mOut.f[ 0] = 2 / w; mOut.f[ 1] = 0; mOut.f[ 2] = 0; mOut.f[ 3] = 0; mOut.f[ 4] = 0; mOut.f[ 5] = 2 / h; mOut.f[ 6] = 0; mOut.f[ 7] = 0; mOut.f[ 8] = 0; mOut.f[ 9] = 0; mOut.f[10] = 1 / (zf - zn); mOut.f[11] = zn / (zn - zf); mOut.f[12] = 0; mOut.f[13] = 0; mOut.f[14] = 0; mOut.f[15] = 1; if (bRotate) { PVRTMATRIXf mRotation, mTemp = mOut; PVRTMatrixRotationZF(mRotation, -90.0f*PVRT_PIf/180.0f); PVRTMatrixMultiplyF(mOut, mRotation, mTemp); } } /*!*************************************************************************** @Function PVRTMatrixOrthoRHF @Output mOut Orthographic matrix @Input w Width of the screen @Input h Height of the screen @Input zn Near clipping distance @Input zf Far clipping distance @Input bRotate Should we rotate it ? (for upright screens) @Description Create an orthographic matrix. *****************************************************************************/ void PVRTMatrixOrthoRHF( PVRTMATRIXf &mOut, const float w, const float h, const float zn, const float zf, const bool bRotate) { mOut.f[ 0] = 2 / w; mOut.f[ 1] = 0; mOut.f[ 2] = 0; mOut.f[ 3] = 0; mOut.f[ 4] = 0; mOut.f[ 5] = 2 / h; mOut.f[ 6] = 0; mOut.f[ 7] = 0; mOut.f[ 8] = 0; mOut.f[ 9] = 0; mOut.f[10] = 1 / (zn - zf); mOut.f[11] = zn / (zn - zf); mOut.f[12] = 0; mOut.f[13] = 0; mOut.f[14] = 0; mOut.f[15] = 1; if (bRotate) { PVRTMATRIXf mRotation, mTemp = mOut; PVRTMatrixRotationZF(mRotation, -90.0f*PVRT_PIf/180.0f); PVRTMatrixMultiplyF(mOut, mRotation, mTemp); } } /*!*************************************************************************** @Function PVRTMatrixVec3LerpF @Output vOut Result of the interpolation @Input v1 First vector to interpolate from @Input v2 Second vector to interpolate form @Input s Coefficient of interpolation @Description This function performs the linear interpolation based on the following formula: V1 + s(V2-V1). *****************************************************************************/ void PVRTMatrixVec3LerpF( PVRTVECTOR3f &vOut, const PVRTVECTOR3f &v1, const PVRTVECTOR3f &v2, const float s) { vOut.x = v1.x + s * (v2.x - v1.x); vOut.y = v1.y + s * (v2.y - v1.y); vOut.z = v1.z + s * (v2.z - v1.z); } /*!*************************************************************************** @Function PVRTMatrixVec3DotProductF @Input v1 First vector @Input v2 Second vector @Return Dot product of the two vectors. @Description This function performs the dot product of the two supplied vectors. *****************************************************************************/ float PVRTMatrixVec3DotProductF( const PVRTVECTOR3f &v1, const PVRTVECTOR3f &v2) { return (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); } /*!*************************************************************************** @Function PVRTMatrixVec3CrossProductF @Output vOut Cross product of the two vectors @Input v1 First vector @Input v2 Second vector @Description This function performs the cross product of the two supplied vectors. *****************************************************************************/ void PVRTMatrixVec3CrossProductF( PVRTVECTOR3f &vOut, const PVRTVECTOR3f &v1, const PVRTVECTOR3f &v2) { PVRTVECTOR3f result; /* Perform calculation on a dummy VECTOR (result) */ result.x = v1.y * v2.z - v1.z * v2.y; result.y = v1.z * v2.x - v1.x * v2.z; result.z = v1.x * v2.y - v1.y * v2.x; /* Copy result in pOut */ vOut = result; } /*!*************************************************************************** @Function PVRTMatrixVec3NormalizeF @Output vOut Normalized vector @Input vIn Vector to normalize @Description Normalizes the supplied vector. *****************************************************************************/ void PVRTMatrixVec3NormalizeF( PVRTVECTOR3f &vOut, const PVRTVECTOR3f &vIn) { float f; double temp; temp = (double)(vIn.x * vIn.x + vIn.y * vIn.y + vIn.z * vIn.z); temp = 1.0 / sqrt(temp); f = (float)temp; vOut.x = vIn.x * f; vOut.y = vIn.y * f; vOut.z = vIn.z * f; } /*!*************************************************************************** @Function PVRTMatrixVec3LengthF @Input vIn Vector to get the length of @Return The length of the vector @Description Gets the length of the supplied vector. *****************************************************************************/ float PVRTMatrixVec3LengthF( const PVRTVECTOR3f &vIn) { double temp; temp = (double)(vIn.x * vIn.x + vIn.y * vIn.y + vIn.z * vIn.z); return (float) sqrt(temp); } /*!*************************************************************************** @Function PVRTMatrixQuaternionIdentityF @Output qOut Identity quaternion @Description Sets the quaternion to (0, 0, 0, 1), the identity quaternion. *****************************************************************************/ void PVRTMatrixQuaternionIdentityF( PVRTQUATERNIONf &qOut) { qOut.x = 0; qOut.y = 0; qOut.z = 0; qOut.w = 1; } /*!*************************************************************************** @Function PVRTMatrixQuaternionRotationAxisF @Output qOut Rotation quaternion @Input vAxis Axis to rotate around @Input fAngle Angle to rotate @Description Create quaternion corresponding to a rotation of fAngle radians around submitted vector. *****************************************************************************/ void PVRTMatrixQuaternionRotationAxisF( PVRTQUATERNIONf &qOut, const PVRTVECTOR3f &vAxis, const float fAngle) { float fSin, fCos; fSin = (float)PVRTFSIN(fAngle * 0.5f); fCos = (float)PVRTFCOS(fAngle * 0.5f); /* Create quaternion */ qOut.x = vAxis.x * fSin; qOut.y = vAxis.y * fSin; qOut.z = vAxis.z * fSin; qOut.w = fCos; /* Normalise it */ PVRTMatrixQuaternionNormalizeF(qOut); } /*!*************************************************************************** @Function PVRTMatrixQuaternionToAxisAngleF @Input qIn Quaternion to transform @Output vAxis Axis of rotation @Output fAngle Angle of rotation @Description Convert a quaternion to an axis and angle. Expects a unit quaternion. *****************************************************************************/ void PVRTMatrixQuaternionToAxisAngleF( const PVRTQUATERNIONf &qIn, PVRTVECTOR3f &vAxis, float &fAngle) { float fCosAngle, fSinAngle; double temp; /* Compute some values */ fCosAngle = qIn.w; temp = 1.0f - fCosAngle*fCosAngle; fAngle = (float)PVRTFACOS(fCosAngle)*2.0f; fSinAngle = (float)sqrt(temp); /* This is to avoid a division by zero */ if ((float)fabs(fSinAngle)<0.0005f) fSinAngle = 1.0f; /* Get axis vector */ vAxis.x = qIn.x / fSinAngle; vAxis.y = qIn.y / fSinAngle; vAxis.z = qIn.z / fSinAngle; } /*!*************************************************************************** @Function PVRTMatrixQuaternionSlerpF @Output qOut Result of the interpolation @Input qA First quaternion to interpolate from @Input qB Second quaternion to interpolate from @Input t Coefficient of interpolation @Description Perform a Spherical Linear intERPolation between quaternion A and quaternion B at time t. t must be between 0.0f and 1.0f *****************************************************************************/ void PVRTMatrixQuaternionSlerpF( PVRTQUATERNIONf &qOut, const PVRTQUATERNIONf &qA, const PVRTQUATERNIONf &qB, const float t) { float fCosine, fAngle, A, B; /* Parameter checking */ if (t<0.0f || t>1.0f) { #ifndef BADA _RPT0(_CRT_WARN, "PVRTMatrixQuaternionSlerp : Bad parameters\n"); #endif qOut.x = 0; qOut.y = 0; qOut.z = 0; qOut.w = 1; return; } /* Find sine of Angle between Quaternion A and B (dot product between quaternion A and B) */ fCosine = qA.w*qB.w + qA.x*qB.x + qA.y*qB.y + qA.z*qB.z; if (fCosine < 0) { PVRTQUATERNIONf qi; /* <http://www.magic-software.com/Documentation/Quaternions.pdf> "It is important to note that the quaternions q and -q represent the same rotation... while either quaternion will do, the interpolation methods require choosing one over the other. "Although q1 and -q1 represent the same rotation, the values of Slerp(t; q0, q1) and Slerp(t; q0,-q1) are not the same. It is customary to choose the sign... on q1 so that... the angle between q0 and q1 is acute. This choice avoids extra spinning caused by the interpolated rotations." */ qi.x = -qB.x; qi.y = -qB.y; qi.z = -qB.z; qi.w = -qB.w; PVRTMatrixQuaternionSlerpF(qOut, qA, qi, t); return; } fCosine = PVRT_MIN(fCosine, 1.0f); fAngle = (float)PVRTFACOS(fCosine); /* Avoid a division by zero */ if (fAngle==0.0f) { qOut = qA; return; } /* Precompute some values */ A = (float)(PVRTFSIN((1.0f-t)*fAngle) / PVRTFSIN(fAngle)); B = (float)(PVRTFSIN(t*fAngle) / PVRTFSIN(fAngle)); /* Compute resulting quaternion */ qOut.x = A * qA.x + B * qB.x; qOut.y = A * qA.y + B * qB.y; qOut.z = A * qA.z + B * qB.z; qOut.w = A * qA.w + B * qB.w; /* Normalise result */ PVRTMatrixQuaternionNormalizeF(qOut); } /*!*************************************************************************** @Function PVRTMatrixQuaternionNormalizeF @Modified quat Vector to normalize @Description Normalize quaternion. *****************************************************************************/ void PVRTMatrixQuaternionNormalizeF(PVRTQUATERNIONf &quat) { float fMagnitude; double temp; /* Compute quaternion magnitude */ temp = quat.w*quat.w + quat.x*quat.x + quat.y*quat.y + quat.z*quat.z; fMagnitude = (float)sqrt(temp); /* Divide each quaternion component by this magnitude */ if (fMagnitude!=0.0f) { fMagnitude = 1.0f / fMagnitude; quat.x *= fMagnitude; quat.y *= fMagnitude; quat.z *= fMagnitude; quat.w *= fMagnitude; } } /*!*************************************************************************** @Function PVRTMatrixRotationQuaternionF @Output mOut Resulting rotation matrix @Input quat Quaternion to transform @Description Create rotation matrix from submitted quaternion. Assuming the quaternion is of the form [X Y Z W]: | 2 2 | | 1 - 2Y - 2Z 2XY - 2ZW 2XZ + 2YW 0 | | | | 2 2 | M = | 2XY + 2ZW 1 - 2X - 2Z 2YZ - 2XW 0 | | | | 2 2 | | 2XZ - 2YW 2YZ + 2XW 1 - 2X - 2Y 0 | | | | 0 0 0 1 | *****************************************************************************/ void PVRTMatrixRotationQuaternionF( PVRTMATRIXf &mOut, const PVRTQUATERNIONf &quat) { const PVRTQUATERNIONf *pQ; #if defined(BUILD_DX9) || defined(BUILD_D3DM) PVRTQUATERNIONf qInv; qInv.x = -quat.x; qInv.y = -quat.y; qInv.z = -quat.z; qInv.w = quat.w; pQ = &qInv; #else pQ = &quat; #endif /* Fill matrix members */ mOut.f[0] = 1.0f - 2.0f*pQ->y*pQ->y - 2.0f*pQ->z*pQ->z; mOut.f[1] = 2.0f*pQ->x*pQ->y - 2.0f*pQ->z*pQ->w; mOut.f[2] = 2.0f*pQ->x*pQ->z + 2.0f*pQ->y*pQ->w; mOut.f[3] = 0.0f; mOut.f[4] = 2.0f*pQ->x*pQ->y + 2.0f*pQ->z*pQ->w; mOut.f[5] = 1.0f - 2.0f*pQ->x*pQ->x - 2.0f*pQ->z*pQ->z; mOut.f[6] = 2.0f*pQ->y*pQ->z - 2.0f*pQ->x*pQ->w; mOut.f[7] = 0.0f; mOut.f[8] = 2.0f*pQ->x*pQ->z - 2*pQ->y*pQ->w; mOut.f[9] = 2.0f*pQ->y*pQ->z + 2.0f*pQ->x*pQ->w; mOut.f[10] = 1.0f - 2.0f*pQ->x*pQ->x - 2*pQ->y*pQ->y; mOut.f[11] = 0.0f; mOut.f[12] = 0.0f; mOut.f[13] = 0.0f; mOut.f[14] = 0.0f; mOut.f[15] = 1.0f; } /*!*************************************************************************** @Function PVRTMatrixQuaternionMultiplyF @Output qOut Resulting quaternion @Input qA First quaternion to multiply @Input qB Second quaternion to multiply @Description Multiply quaternion A with quaternion B and return the result in qOut. *****************************************************************************/ void PVRTMatrixQuaternionMultiplyF( PVRTQUATERNIONf &qOut, const PVRTQUATERNIONf &qA, const PVRTQUATERNIONf &qB) { PVRTVECTOR3f CrossProduct; /* Compute scalar component */ qOut.w = (qA.w*qB.w) - (qA.x*qB.x + qA.y*qB.y + qA.z*qB.z); /* Compute cross product */ CrossProduct.x = qA.y*qB.z - qA.z*qB.y; CrossProduct.y = qA.z*qB.x - qA.x*qB.z; CrossProduct.z = qA.x*qB.y - qA.y*qB.x; /* Compute result vector */ qOut.x = (qA.w * qB.x) + (qB.w * qA.x) + CrossProduct.x; qOut.y = (qA.w * qB.y) + (qB.w * qA.y) + CrossProduct.y; qOut.z = (qA.w * qB.z) + (qB.w * qA.z) + CrossProduct.z; /* Normalize resulting quaternion */ PVRTMatrixQuaternionNormalizeF(qOut); } /*!*************************************************************************** @Function PVRTMatrixLinearEqSolveF @Input pSrc 2D array of floats. 4 Eq linear problem is 5x4 matrix, constants in first column @Input nCnt Number of equations to solve @Output pRes Result @Description Solves 'nCnt' simultaneous equations of 'nCnt' variables. pRes should be an array large enough to contain the results: the values of the 'nCnt' variables. This fn recursively uses Gaussian Elimination. *****************************************************************************/ void PVRTMatrixLinearEqSolveF( float * const pRes, float ** const pSrc, // 2D array of floats. 4 Eq linear problem is 5x4 matrix, constants in first column. const int nCnt) { int i, j, k; float f; #if 0 /* Show the matrix in debug output */ _RPT1(_CRT_WARN, "LinearEqSolve(%d)\n", nCnt); for(i = 0; i < nCnt; ++i) { _RPT1(_CRT_WARN, "%.8f |", pSrc[i][0]); for(j = 1; j <= nCnt; ++j) _RPT1(_CRT_WARN, " %.8f", pSrc[i][j]); _RPT0(_CRT_WARN, "\n"); } #endif if(nCnt == 1) { #ifndef BADA _ASSERT(pSrc[0][1] != 0); #endif pRes[0] = pSrc[0][0] / pSrc[0][1]; return; } // Loop backwards in an attempt avoid the need to swap rows i = nCnt; while(i) { --i; if(pSrc[i][nCnt] != 0) { // Row i can be used to zero the other rows; let's move it to the bottom if(i != (nCnt-1)) { for(j = 0; j <= nCnt; ++j) { // Swap the two values f = pSrc[nCnt-1][j]; pSrc[nCnt-1][j] = pSrc[i][j]; pSrc[i][j] = f; } } // Now zero the last columns of the top rows for(j = 0; j < (nCnt-1); ++j) { #ifndef BADA _ASSERT(pSrc[nCnt-1][nCnt] != 0); #endif f = pSrc[j][nCnt] / pSrc[nCnt-1][nCnt]; // No need to actually calculate a zero for the final column for(k = 0; k < nCnt; ++k) { pSrc[j][k] -= f * pSrc[nCnt-1][k]; } } break; } } // Solve the top-left sub matrix PVRTMatrixLinearEqSolveF(pRes, pSrc, nCnt - 1); // Now calc the solution for the bottom row f = pSrc[nCnt-1][0]; for(k = 1; k < nCnt; ++k) { f -= pSrc[nCnt-1][k] * pRes[k-1]; } #ifndef BADA _ASSERT(pSrc[nCnt-1][nCnt] != 0); #endif f /= pSrc[nCnt-1][nCnt]; pRes[nCnt-1] = f; #if 0 { float fCnt; /* Verify that the result is correct */ fCnt = 0; for(i = 1; i <= nCnt; ++i) fCnt += pSrc[nCnt-1][i] * pRes[i-1]; _ASSERT(abs(fCnt - pSrc[nCnt-1][0]) < 1e-3); } #endif } /***************************************************************************** End of file (PVRTMatrixF.cpp) *****************************************************************************/
30.436031
132
0.528552
aunali1
49221953ee2738b15d33786523097b56f7c985b5
384
cpp
C++
fre_check.cpp
1432junaid/cpp
8faf7ac856a50937f3a563dc8d23ee8e205a489c
[ "MIT" ]
null
null
null
fre_check.cpp
1432junaid/cpp
8faf7ac856a50937f3a563dc8d23ee8e205a489c
[ "MIT" ]
null
null
null
fre_check.cpp
1432junaid/cpp
8faf7ac856a50937f3a563dc8d23ee8e205a489c
[ "MIT" ]
null
null
null
#include<iostream> #include<cstring> using namespace std; int main(){ char *city = "lucknow junction"; char *c = "lucknow"; int hash[26]= {0}; int len = strlen(city); for(int i = 0; i<len ; i++){ if(city[i] >= 97 && city[i] <= 122) hash[city[i] - 'a']++; } for(int i=0; i<26;i++){ if(hash[i]>0){ cout<<char(i+'a')<<" "<<hash[i]<<endl; } } // if(len) return 0; }
17.454545
42
0.533854
1432junaid
49267adedbd3f62879ef3c4aa4e7a8c28800caa1
6,300
cpp
C++
src/libs/qlib/qdmvideoout.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
null
null
null
src/libs/qlib/qdmvideoout.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
null
null
null
src/libs/qlib/qdmvideoout.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
1
2021-01-03T16:16:47.000Z
2021-01-03T16:16:47.000Z
/* * QDMVideoOut - definition/implementation * 13-11-99: Support for VL65 interface * NOTES: * - Generated by mkclass * BUGS: * - Same bugs apply as for QDMVideoIn; event handling of VL was changed * to generate events for all paths in one place. Need to demultiplex. * (C) 01-01-98 MarketGraph/RVG */ #include <qlib/dmvideoout.h> #include <qlib/dmbpool.h> #include <qlib/app.h> #include <qlib/debug.h> DEBUG_ENABLE #undef DBG_CLASS #define DBG_CLASS "QDMVideoOut" QDMVideoOut::QDMVideoOut() : QDMObject() { QVideoServer *vs; int x,y; DBG_C("ctor") vs=app->GetVideoServer(); // Nodes from video to memory srcNode=new QVideoNode(vs,VL_SRC,VL_MEM,VL_ANY); drnNode=new QVideoNode(vs,VL_DRN,VL_VIDEO,VL_ANY); // Create path pathOut=new QVideoPath(vs,VL_ANY,srcNode,drnNode); // Setup hardware if(!pathOut->Setup(VL_SHARE,VL_SHARE)) { qerr("QDMVideoOut: can't setup input path"); } // Default control values SetTiming(VL_TIMING_625_CCIR601); //SetPacking(VL_PACKING_YVYU_422_8); SetPacking(VL_PACKING_ABGR_8); //drnNode->SetControl(VL_CAP_TYPE,VL_CAPTURE_NONINTERLEAVED); //srcNode->SetControl(VL_CAP_TYPE,VL_CAPTURE_INTERLEAVED); SetCaptureType(VL_CAPTURE_INTERLEAVED); SetFormat(VL_FORMAT_RGB); //srcNode->SetControl(VL_FORMAT,VL_FORMAT_RGB); drnNode->SetControl(VL_SYNC,VL_SYNC_INTERNAL); //srcNode->GetXYControl(VL_SIZE,&x,&y); //SetZoomSize(x,y); //drnNode->SetControl(VL_ORIGIN,0,16); // ?? //drnNode->SetControl(VL_ZOOM,1,1); //srcNode->SetControl(VL_TIMING,VL_TIMING_625_CCIR601); //drnNode->SetControl(VL_CAP_TYPE,VL_CAPTURE_INTERLEAVED); SetLayout(VL_LAYOUT_GRAPHICS); // Debug //qdbg(" video in transfer size=%d\n",pathOut->GetTransferSize()); drnNode->GetXYControl(VL_SIZE,&x,&y); //qdbg(" video in size: %dx%d\n",x,y); } QDMVideoOut::~QDMVideoOut() { delete pathOut; delete drnNode; delete srcNode; } /******* * POOL * *******/ void QDMVideoOut::AddConsumerParams(QDMBPool *pool) // Get necessary params to use this input object { #ifdef USE_VL_65 vlDMGetParams(app->GetVideoServer()->GetSGIServer(), pathOut->GetSGIPath(),drnNode->GetSGINode(), pool->GetCreateParams()->GetDMparams()); #else vlDMPoolGetParams(app->GetVideoServer()->GetSGIServer(), pathOut->GetSGIPath(),drnNode->GetSGINode(), pool->GetCreateParams()->GetDMparams()); #endif qdbg("QDMVideoOut:GetPoolParams; buffersize=%d\n", pool->GetCreateParams()->GetInt(DM_BUFFER_SIZE)); } void QDMVideoOut::RegisterPool(QDMBPool *pool) { if(vlDMPoolRegister(app->GetVideoServer()->GetSGIServer(), pathOut->GetSGIPath(),drnNode->GetSGINode(),pool->GetDMbufferpool())<0) qerr("QDMVideoOut: can't register pool"); } /******* * INFO * *******/ int QDMVideoOut::GetFD() { #ifdef USE_VL_65 //return drnNode->GetFD(); return srcNode->GetFD(); #else return pathOut->GetFD(); #endif } void QDMVideoOut::GetSize(int *w,int *h) { drnNode->GetXYControl(VL_SIZE,w,h); } int QDMVideoOut::GetTransferSize() { if(!pathOut)return 0; return pathOut->GetTransferSize(); } void QDMVideoOut::SetSize(int w,int h) { //drnNode->SetControl(VL_SIZE,w,h); srcNode->SetControl(VL_SIZE,w,h); } void QDMVideoOut::SetZoomSize(int w,int h) { drnNode->SetControl(VL_MVP_ZOOMSIZE,w,h); } void QDMVideoOut::SetOffset(int x,int y) { drnNode->SetControl(VL_SIZE,x,y); } void QDMVideoOut::SetOrigin(int x,int y) { drnNode->SetControl(VL_ORIGIN,x,y); } void QDMVideoOut::SetLayout(int n) { srcNode->SetControl(VL_LAYOUT,n); } void QDMVideoOut::SetFormat(int n) { srcNode->SetControl(VL_FORMAT,n); } void QDMVideoOut::SetPacking(int n) { srcNode->SetControl(VL_PACKING,n); } void QDMVideoOut::SetCaptureType(int n) { srcNode->SetControl(VL_CAP_TYPE,n); } void QDMVideoOut::SetTiming(int n) { drnNode->SetControl(VL_TIMING,n); } void QDMVideoOut::SetGenlock(bool b) { drnNode->SetControl(VL_SYNC,b?VL_SYNC_GENLOCK:VL_SYNC_INTERNAL); } void QDMVideoOut::Start() // Start transferring { #ifdef FUTURE VLTransferDescriptor xferDesc; #endif pathOut->SelectEvents( VLTransferCompleteMask | VLStreamBusyMask | VLStreamPreemptedMask | VLAdvanceMissedMask | VLStreamAvailableMask | VLSyncLostMask | VLStreamStartedMask | VLStreamStoppedMask | VLSequenceLostMask | VLControlChangedMask | VLTransferCompleteMask | VLTransferFailedMask | //VLEvenVerticalRetraceMask | //VLOddVerticalRetraceMask | //VLFrameVerticalRetraceMask | VLDeviceEventMask | VLDefaultSourceMask | VLControlRangeChangedMask | VLControlPreemptedMask | VLControlAvailableMask | VLDefaultDrainMask | VLStreamChangedMask | VLTransferError); /*pathOut->SelectEvents(VLTransferCompleteMask| VLTransferFailedMask| VLStreamPreemptedMask| VLDeviceEventMask);*/ #ifdef FUTURE xferDesc.mode=VL_TRANSFER_MODE_CONTINUOUS; xferDesc.count=1; xferDesc.delay=0; xferDesc.trigger=VLTriggerImmediate; #endif pathOut->BeginTransfer(); } void QDMVideoOut::GetEvent(VLEvent *event) // This is actually not advised to use under USE_VL_65 // Use QVideoServer's event handling functions; this function // will return events for ANY video path, not just the video out path (!) { #ifdef USE_VL_65 if(vlPending(app->GetVideoServer()->GetSGIServer())<=0) return /*FALSE*/; if(vlNextEvent(app->GetVideoServer()->GetSGIServer(),event)!=DM_SUCCESS) #else if(vlEventRecv(app->GetVideoServer()->GetSGIServer(), pathOut->GetSGIPath(),event)!=DM_SUCCESS) #endif { qerr("QDMVideoOut:GetEvent failed vlEventRecv"); return; } } void QDMVideoOut::Send(DMbuffer buf) { #ifdef USE_VL_65 if(vlDMBufferPutValid(app->GetVideoServer()->GetSGIServer(), pathOut->GetSGIPath(),drnNode->GetSGINode(),buf)!=0) #else if(vlDMBufferSend(app->GetVideoServer()->GetSGIServer(), pathOut->GetSGIPath(),buf)!=0) #endif { qerr("QDMVideoOut::Send(buf) failed; %s",vlStrError(vlGetErrno())); } }
27.272727
75
0.685079
3dhater
492baaf94ed04edfec0954b99b40d808fec4c397
3,165
cpp
C++
src/daemon/CmdListener.cpp
klx99/Elastos.Service.CarrierGroup
a1922402af66308178f048352ab6038f4c2d848b
[ "MIT" ]
null
null
null
src/daemon/CmdListener.cpp
klx99/Elastos.Service.CarrierGroup
a1922402af66308178f048352ab6038f4c2d848b
[ "MIT" ]
null
null
null
src/daemon/CmdListener.cpp
klx99/Elastos.Service.CarrierGroup
a1922402af66308178f048352ab6038f4c2d848b
[ "MIT" ]
null
null
null
#include "CmdListener.hpp" #include <vector> #include <Carrier.hpp> #include <CmdParser.hpp> #include <DateTime.hpp> #include <ErrCode.hpp> #include <GroupCmdParser.hpp> #include <Log.hpp> #include <OptParser.hpp> namespace elastos { /* =========================================== */ /* === static variables initialize =========== */ /* =========================================== */ /* =========================================== */ /* === static function implement ============= */ /* =========================================== */ /* =========================================== */ /* === class public function implement ====== */ /* =========================================== */ int CmdListener::config(std::weak_ptr<Carrier> carrier) { this->carrier = carrier; this->cmdParser = CmdParser::Factory::Create(); int rc = this->cmdParser->config(carrier); CHECK_ERROR(rc); return 0; } void CmdListener::onError(int errCode) { Log::D(Log::TAG, "%s errCode=%d", __PRETTY_FUNCTION__, errCode); } void CmdListener::onStatusChanged(const std::string& userId, Status status) { Log::D(Log::TAG, "%s", __PRETTY_FUNCTION__); } void CmdListener::onFriendRequest(const std::string& friendCode, const std::string& summary) { Log::D(Log::TAG, "%s", __PRETTY_FUNCTION__); auto cmdline = CmdParser::Cmd::AddFriend + " " + friendCode + " " + summary; int rc = cmdParser->parse(carrier, cmdline, friendCode, 0); if(rc < 0) { onError(rc); return; } return; } void CmdListener::onFriendStatusChanged(const std::string& friendCode, Status status) { Log::D(Log::TAG, "%s", __PRETTY_FUNCTION__); bool isGroup = !OptParser::GetInstance()->isManager(); if(isGroup && status == Status::Online) { int rc = cmdParser->parse(carrier, GroupCmdParser::Cmd::ForwardMessage, friendCode, DateTime::CurrentNS()); CHECK_RETVAL(rc); } } void CmdListener::onReceivedMessage(const std::string& friendCode, int64_t timestamp, const std::vector<uint8_t>& message) { Log::D(Log::TAG, "%s", __PRETTY_FUNCTION__); std::string cmdline = std::string{message.begin(), message.end()}; // ignore hyper return receipt if(cmdline == "{\"command\":\"messageSeen\"}") { return; } if(cmdline.find_first_of('/') != 0) { // if not a command, exec as forward. cmdline = GroupCmdParser::Cmd::ForwardMessage + " " + cmdline; } int rc = cmdParser->parse(carrier, cmdline, friendCode, timestamp); CHECK_RETVAL(rc); } /* =========================================== */ /* === class protected function implement === */ /* =========================================== */ /* =========================================== */ /* === class private function implement ===== */ /* =========================================== */ } // namespace elastos
29.305556
80
0.484044
klx99
492e26e67ca7f81605a361d64d4f8a44e9a0e845
847
cpp
C++
HW2/Part2/Question4/main.cpp
Coslate/Data_Structures
d839e2d24c15b1ba20c772fc232b1a98b1b6dedf
[ "MIT" ]
null
null
null
HW2/Part2/Question4/main.cpp
Coslate/Data_Structures
d839e2d24c15b1ba20c772fc232b1a98b1b6dedf
[ "MIT" ]
null
null
null
HW2/Part2/Question4/main.cpp
Coslate/Data_Structures
d839e2d24c15b1ba20c772fc232b1a98b1b6dedf
[ "MIT" ]
null
null
null
//main.cpp #include <iostream> #include <Stack.h> #include <solution.h> #include <cstring> std::vector<std::vector<bool>> tmp_maze; std::vector<std::vector<bool>> maze; int rows=0; int cols=0; int m = 0, p = 0; std::string input_maze = "NO-INPUT"; int main(int argc, char*argv[]){ if(argc < 3){ std::cerr<<"Error: There should be at least one input argument like ./main -input_maze arg1."<<std::endl; return EXIT_FAILURE; } if( (argc > 1) && (strcmp(argv[1], "-input_maze") == 0)){ input_maze = argv[2]; } ReadFile(input_maze, tmp_maze, rows, cols); std::cout<<"> Initialization..."<<std::endl; AugmentedMazeBuildWall(tmp_maze, maze, rows, cols, m, p); PrintMatrix("maze", maze, rows+2, cols+2); std::cout<<"> Path..."<<std::endl; Path(maze, m, p); return EXIT_SUCCESS; }
24.2
113
0.612751
Coslate
492e48c335a5776954c066f04cfc5aaf40673a54
69
cpp
C++
JPMorgan/JPMorgan.cpp
awoimbee/superberniebros
728531ad82817b8f9778d8fc72b2c72f1a90ae0b
[ "MIT" ]
2
2020-06-30T06:15:57.000Z
2020-06-30T06:25:12.000Z
JPMorgan/JPMorgan.cpp
awoimbee/superberniebros
728531ad82817b8f9778d8fc72b2c72f1a90ae0b
[ "MIT" ]
null
null
null
JPMorgan/JPMorgan.cpp
awoimbee/superberniebros
728531ad82817b8f9778d8fc72b2c72f1a90ae0b
[ "MIT" ]
1
2022-03-02T18:45:13.000Z
2022-03-02T18:45:13.000Z
// // Created by Eli Winkelman on 6/13/17. // #include "JPMorgan.h"
11.5
39
0.637681
awoimbee
4932ae43ff6878714d2571b92108f6a202b5473d
2,095
cpp
C++
MAX/library/test/Core/Transformer/AgentTransferManagerTransformerTest.cpp
isabella232/max-toolkit
6fc0b416efa064094ffc98daf6ee8755c3ec73fe
[ "Apache-2.0" ]
4
2021-09-10T18:35:11.000Z
2022-01-07T11:33:10.000Z
MAX/library/test/Core/Transformer/AgentTransferManagerTransformerTest.cpp
alexa/max-toolkit
6fc0b416efa064094ffc98daf6ee8755c3ec73fe
[ "Apache-2.0" ]
1
2022-02-08T19:22:12.000Z
2022-02-08T20:42:28.000Z
MAX/library/test/Core/Transformer/AgentTransferManagerTransformerTest.cpp
isabella232/max-toolkit
6fc0b416efa064094ffc98daf6ee8755c3ec73fe
[ "Apache-2.0" ]
3
2021-09-20T22:11:32.000Z
2022-02-08T17:26:53.000Z
/* * Copyright Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 "Core/Transformer/AgentTransferManagerTransformer.h" #include "Agent/AgentTransferManager.h" #include "MultiAgentExperience/Agent/Agent.h" #include "Core/Mocks/MockAgentStoreInterface.h" #include "Integration/TestAgent.h" #include <gmock/gmock.h> #include <memory> namespace multiAgentExperience { namespace library { namespace core { namespace transformer { namespace test { using namespace ::testing; class AgentTransferManagerTransformerTest : public ::testing::Test { protected: std::shared_ptr<AgentTransferManagerTransformer> m_transformer; std::shared_ptr<MockAgentStoreInterface> m_mockAgentStore; virtual void SetUp() override { m_mockAgentStore = std::make_shared<NiceMock<MockAgentStoreInterface>>(); auto agentTransferManager = std::make_shared<agent::AgentTransferManager>(); m_transformer = std::make_shared<AgentTransferManagerTransformer>( multiAgentExperience::actor::ActorId("agent"), agentTransferManager, m_mockAgentStore); } }; TEST_F(AgentTransferManagerTransformerTest, test_invoke_agent_invokes_the_agent) { auto id = actor::ActorId("id"); auto agent = std::make_shared<library::test::TestAgent>(id); EXPECT_CALL(*m_mockAgentStore, getAgentById(id)).WillRepeatedly(Return(agent)); m_transformer->invokeAgent(agent->getId()); ASSERT_TRUE(agent->wasTransferredTo()); } } // namespace test } // namespace transformer } // namespace core } // namespace library } // namespace multiAgentExperience
32.734375
99
0.75179
isabella232
4933ed9f9d4110a5473f465f757547973d61aa35
1,027
cpp
C++
python/popart._internal.ir/bindings/transforms/mergeexchange.cpp
graphcore/popart
15ce5b098638dc34a4d41ae2a7621003458df798
[ "MIT" ]
61
2020-07-06T17:11:46.000Z
2022-03-12T14:42:51.000Z
python/popart._internal.ir/bindings/transforms/mergeexchange.cpp
graphcore/popart
15ce5b098638dc34a4d41ae2a7621003458df798
[ "MIT" ]
1
2021-02-25T01:30:29.000Z
2021-11-09T11:13:14.000Z
python/popart._internal.ir/bindings/transforms/mergeexchange.cpp
graphcore/popart
15ce5b098638dc34a4d41ae2a7621003458df798
[ "MIT" ]
6
2020-07-15T12:33:13.000Z
2021-11-07T06:55:00.000Z
// Copyright (c) 2021 Graphcore Ltd. All rights reserved. #include "bindings/transforms/autodiff.hpp" #include "bindings/transforms/transform.hpp" #include <pybind11/cast.h> #include <pybind11/functional.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <popart/graph.hpp> #include <popart/transforms/mergeexchange.hpp> #include <popart/transforms/transform.hpp> namespace py = pybind11; namespace popart { namespace _internal { namespace ir { namespace transforms { void bindMergeExchange(py::module &m) { py::class_<MergeExchange, Transform, PyTransform<MergeExchange>>( m, "MergeExchange") .def(py::init<>()) .def("id", &MergeExchange::id) .def("apply", &MergeExchange::apply) .def("applyToOps", &MergeExchange::applyToOps, py::return_value_policy::reference) .def("getId", &MergeExchange::getId) .def("getName", &MergeExchange::getName); } } // namespace transforms } // namespace ir } // namespace _internal } // namespace popart
26.333333
67
0.701071
graphcore
49349850ebfb8542f3cc77a64fea0828cdd3fc4b
443
cpp
C++
PAT/PAT Basic/1016.cpp
Accelerator404/Algorithm-Demonstration
e40a499c23a56d363c743c76ac967d9c4247a4be
[ "Apache-2.0" ]
1
2019-09-18T23:45:27.000Z
2019-09-18T23:45:27.000Z
PAT/PAT Basic/1016.cpp
Accelerator404/Algorithm-Demonstration
e40a499c23a56d363c743c76ac967d9c4247a4be
[ "Apache-2.0" ]
null
null
null
PAT/PAT Basic/1016.cpp
Accelerator404/Algorithm-Demonstration
e40a499c23a56d363c743c76ac967d9c4247a4be
[ "Apache-2.0" ]
1
2019-09-18T23:45:28.000Z
2019-09-18T23:45:28.000Z
#include <iostream> #include <string> using namespace std; //PAT Basic No.1016 “部分A+B” int P(string K, int Dk) { int count = 0; for (int i = 0; i < K.length(); ++i) if (K.at(i) - '0' == Dk) count++; if (count == 0) return 0; else { string Pk(count, Dk + '0'); return strtol(Pk.c_str(), nullptr, 10); } } int main() { int Da,Db; string A, B; cin >> A >> Da >> B >> Db; cout << P(A, Da) + P(B, Db) << endl;; return 0; }
16.407407
41
0.532731
Accelerator404
49388536df90b4ec85bfc27343dc87a9fb12632d
870
cc
C++
src/util/rename.cc
matt-gretton-dann/gd-posix-apps
3abf398269203883c8e13511d811c7d6f0cb1cf8
[ "Apache-2.0" ]
null
null
null
src/util/rename.cc
matt-gretton-dann/gd-posix-apps
3abf398269203883c8e13511d811c7d6f0cb1cf8
[ "Apache-2.0" ]
164
2020-12-30T11:35:34.000Z
2021-05-24T12:58:26.000Z
src/util/rename.cc
matt-gretton-dann/gd-posix-apps
3abf398269203883c8e13511d811c7d6f0cb1cf8
[ "Apache-2.0" ]
null
null
null
/** \file src/util/rename.cc * \brief Platform independent version of rename() * \author Copyright 2021, Matthew Gretton-Dann * SPDX-License-Identifier: Apache-2.0 */ #include "util/file.hh" #ifdef _WIN32 # include "util/utils.hh" # include <Windows.h> # include <cerrno> # include <cstddef> extern "C" void __support_log(char const* format, ...); // NOLINT auto GD::Util::rename(char const* _old, char const* _new) __NOEXCEPT -> int { BOOL success = ::ReplaceFileA(_new, _old, nullptr, 0, nullptr, nullptr); if (success == 0) { errno = EINVAL; DWORD error = ::GetLastError(); __support_log("ReplaceFileA(%s, %s) failed: %lx\n", _new, _old, error); return -1; } return 0; } #else # include <cstdio> auto GD::Util::rename(char const* _old, char const* _new) __NOEXCEPT -> int { return ::rename(_old, _new); } #endif
24.166667
75
0.652874
matt-gretton-dann
4938c2f3c1232ac88668257f33deb437724fcb0e
35,222
cpp
C++
src/mat_vec_fns_II.cpp
zzalscv2/FFEA
da8a09dadb1b3978a3d230dc79d9b163d7889242
[ "Apache-2.0" ]
null
null
null
src/mat_vec_fns_II.cpp
zzalscv2/FFEA
da8a09dadb1b3978a3d230dc79d9b163d7889242
[ "Apache-2.0" ]
null
null
null
src/mat_vec_fns_II.cpp
zzalscv2/FFEA
da8a09dadb1b3978a3d230dc79d9b163d7889242
[ "Apache-2.0" ]
1
2021-04-03T16:08:21.000Z
2021-04-03T16:08:21.000Z
// // This file is part of the FFEA simulation package // // Copyright (c) by the Theory and Development FFEA teams, // as they appear in the README.md file. // // FFEA is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // FFEA 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 FFEA. If not, see <http://www.gnu.org/licenses/>. // // To help us fund FFEA development, we humbly ask that you cite // the research papers on the package. // #include "mat_vec_fns_II.h" #include <iostream> using std::cout; using std::endl; ///////////////// SECTION 0 //////////////////// //////// Constants and scalar functions /////// //////////////////////////////////////////////// // /// check whether two scalars have the same sign template <class t_scalar> bool sameSign(t_scalar a, t_scalar b){ // return a <= ffea_const::zero == b <= ffea_const::zero; if (a*b >= 0) return true; return false; } /** Given 3 integers n0, n1, n2 * return the index missing in the list [0,1,2,3] */ int getMissingNode(int n0, int n1, int n2) { if ((n0 == 0) || (n1 == 0) || (n2 ==0)) { if ((n0 == 1) || (n1 == 1) || (n2 ==1)) { if ((n0 == 2) || (n1 == 2) || (n2 ==2)) { return 3; } else { return 2; } } else { return 1; } } else { return 0; } } /** Given 1 integers iN, * return the index missing indices of the list [0,1,2,3] */ void getRestOfNodes(int iN, int &iO0, int &iO1, int &iO2) { if (iN == 0) { iO0 = 1; iO1 = 2; iO2 = 3; } else if (iN == 1) { iO0 = 0; iO1 = 2; iO2 = 3; } else if (iN == 2) { iO0 = 0; iO1 = 1; iO2 = 3; } else { iO0 = 0; iO1 = 1; iO2 = 2; } } /** Given 1 integers iN, * return the index missing indices of the list [0,1,2,3] */ void getMissingPair(int in0, int in1, int &on0, int &on1) { for (int i=0; i<4; i++) { if ((i != in0) && (i != in1)) { on0 = i; on1 = getMissingNode(in0, in1, on0); break; } } } ////////////////// SECTION 1 /////////////////////// /// Basic operations for arr3, i. e., scalar v[3]// //////////////////////////////////////////////////// /** Add vectors vecA and vecB into res. */ /** res can also be vecA or vecB */ template <class t_scalar, class brr3> void arr3arr3Add(arr3_view<t_scalar,brr3> vecA, arr3_view<t_scalar,brr3> vecB, arr3_view<t_scalar,brr3> res){ for (int i=0; i<3; i++) { res[i] = vecA[i] + vecB[i]; } } /** res = vecA - vecB */ /** res can be either vecA or vecB */ // void arr3arr3Substract(arr3 &vecA, arr3 &vecB, arr3 &res){ // template <class brr3> void arr3arr3Substract(brr3 &vecA, brr3 &vecB, brr3 &res){ template <class t_scalar, class brr3> void arr3arr3Substract(arr3_view<t_scalar,brr3> vecA, arr3_view<t_scalar,brr3> vecB, arr3_view<t_scalar,brr3> res){ for (int i=0; i<3; i++) { res[i] = vecA[i] - vecB[i]; } } /** w = u x v */ /** (w != u) && (w != v) */ // void arr3arr3VectorProduct(arr3 (&u), arr3 (&v), arr3 (&w)){ template <class t_scalar, class brr3> void arr3arr3VectorProduct(arr3_view<t_scalar,brr3> u, arr3_view<t_scalar,brr3> v, arr3_view<t_scalar,brr3> w){ w[0] = u[1]*v[2] - v[1]*u[2]; w[1] = -u[0]*v[2] + v[0]*u[2]; w[2] = u[0]*v[1] - v[0]*u[1]; } /** return the dot product for arrays vecA and vecB */ // scalar arr3arr3DotProduct(arr3 &vecA, arr3 &vecB) { template <class t_scalar, class brr3> t_scalar arr3arr3DotProduct(arr3_view<t_scalar,brr3> vecA, arr3_view<t_scalar,brr3> vecB) { t_scalar result = 0.0; for (int i=0; i<3; i++) { // cout << "vecA[" << i << "]: " << vecA[i] << " vecB[" << i << "]: " << vecB[i] << endl; result += vecA[i] * vecB[i]; } return result; } /** Normalise vector arr3 e */ template <class t_scalar, class brr3> void arr3Normalise(arr3_view<t_scalar,brr3> e){ t_scalar norm = 0.0; for (int i=0; i<3; i++) { norm += e[i]*e[i]; } norm = sqrt(norm); for (int i=0; i<3; i++) { e[i] /= norm; } } /** get the normalised vector of arr3 e into arr3 n */ // template <class t_scalar, class brr3> void arr3Normalise2(brr3 &e, brr3 &n){ template <class t_scalar, class brr3> void arr3Normalise2(arr3_view<t_scalar,brr3> e, arr3_view<t_scalar,brr3> n){ t_scalar norm = 0.0; for (int i=0; i<3; i++) { norm += e[i]*e[i]; } if (norm == 0.0) throw -1; norm = sqrt(norm); for (int i=0; i<3; i++) { n[i] = e[i]/norm; } } /** resize vector u, given scalar f */ template <class t_scalar, class brr3> void arr3Resize(t_scalar f, arr3_view<t_scalar,brr3> u){ for (int i=0; i<3; i++) { u[i] = f*u[i]; } } /** resize vector u into vector v, given scalar f */ template <class t_scalar, class brr3> void arr3Resize2(t_scalar f, arr3_view<t_scalar,brr3> u, arr3_view<t_scalar,brr3> v){ #pragma omp simd for (int i=0; i<3; i++) { v[i] = f*u[i]; } } /** Given a scalar f, change v so that v += f*u */ template <class t_scalar, class brr3> void arr3Resize3(t_scalar f, arr3_view<t_scalar,brr3> u, arr3_view<t_scalar,brr3> v){ #pragma omp simd for (int i=0; i<3; i++) { v[i] += f*u[i]; } } /** cp arr3 u into arr3 v */ template <class t_scalar, class brr3> void arr3Store(arr3_view<t_scalar,brr3> u, arr3_view<t_scalar,brr3> v){ #pragma omp simd for (int i=0; i<3; i++) { v[i] = u[i]; } } /** return the distance from vecA to vecB */ template <class t_scalar, class brr3> t_scalar arr3arr3Distance(arr3_view<t_scalar,brr3> vecA, arr3_view<t_scalar,brr3> vecB){ t_scalar d=0.0; for (int i=0; i<3; i++){ d += (vecA[i] - vecB[i])*(vecA[i] - vecB[i]); } return sqrt(d); } /** Return the length of a vector v */ template <class t_scalar, class brr3> t_scalar mag(arr3_view<t_scalar,brr3> v) { t_scalar s=0.0; #pragma omp simd reduction(+:s) for (int i=0; i<3; i++) { s += v[i] * v[i]; } return sqrt(s); } /** Return the squared length of a vector v */ template <class t_scalar, class brr3> t_scalar mag2(arr3_view<t_scalar,brr3> v) { t_scalar s=0.0; for (int i=0; i<3; i++) { s += v[i] * v[i]; } return s; } template <class brr3> void arr3Initialise(brr3 &v){ for (int i=0; i<3; i++) { v[i] = ffea_const::zero; } } template <class t_scalar, class brr3> t_scalar detByRows(arr3_view<t_scalar,brr3> a, arr3_view<t_scalar,brr3> b, arr3_view<t_scalar,brr3> c){ t_scalar det = 0; det = a[0] * (b[1] * c[2] - b[2] * c[1]); det += a[1] * (b[2] * c[0] - b[0] * c[2]); det += a[2] * (b[0] * c[1] - b[1] * c[0]); return det; } template <class t_scalar, class brr3> t_scalar detByCols(arr3_view<t_scalar,brr3> a, arr3_view<t_scalar,brr3> b, arr3_view<t_scalar,brr3> c){ t_scalar det = 0; det = a[0] * (b[1] * c[2] - b[2] * c[1]); det += b[0] * (c[1] * a[2] - c[2] * a[1]); det += c[0] * (a[1] * b[2] - a[2] * b[1]); return det; } //////////////////////////////////////////////// ////////////// END OF SECTION 1 //////////////// //////////////////////////////////////////////// ///////////////// SECTION 2 //////////////////// ////// Geometric functions for arr3 types ////// //////////////////////////////////////////////// /** t = unit(vecA - vecB) */ /** t can be either vecA or vecB */ // void tangent(arr3 &vecA, arr3 &vecB, arr3 &t){ template <class t_scalar, class brr3> void tangent(brr3 &vecA, brr3 &vecB, brr3 &t){ t_scalar w=0; for (int i=0; i<3; i++) { t[i] = vecA[i] - vecB[i]; w += t[i] * t[i]; } w = sqrt(w); for (int i=0; i<3; i++) { t[i] /= w; } } /** w = unit(u x v) */ /** (w != u) && (w != v) */ template <class t_scalar, class brr3> void getUnitNormal(brr3 &u, brr3 &v, brr3 &w){ w[0] = u[1]*v[2] - v[1]*u[2]; w[1] = -u[0]*v[2] + v[0]*u[2]; w[2] = u[0]*v[1] - v[0]*u[1]; t_scalar l; l = sqrt( w[0]*w[0] + w[1]*w[1] + w[2]*w[2] ); for (int i=0; i<3; i++) { w[i] /= l; } } /** calculate the normal vector n to the plane defined by the three points */ template <class t_scalar, class brr3> void getNormal(brr3 &v1, brr3 &v2, brr3 &v3, brr3 &n){ brr3 pl1, pl2; arr3arr3Substract<t_scalar,brr3>(v2, v1, pl1); arr3arr3Substract<t_scalar,brr3>(v3, v1, pl2); getUnitNormal<t_scalar,brr3>(pl1, pl2, n); } /* Given the face formed by tetA[0]:tetA[1]:tetA[2] * get n, the normal to a face pointing inwards. */ template <class t_scalar, class brr3> void getNormalInwards(brr3 (&tetA)[4], int n0, int n1, int n2, brr3 (&n)){ // pl1 and pl2 are the unit vectors (tetA[n1] - tetA[n0]) and (tetA[n2] - tetA[n0]), brr3 pl1, pl2, aux; arr3arr3Substract<t_scalar,brr3>(tetA[n1], tetA[n0], pl1); arr3arr3Substract<t_scalar,brr3>(tetA[n2], tetA[n0], pl2); // n is a unit vector normal to the face: arr3arr3VectorProduct<t_scalar,brr3>(pl1, pl2, aux); arr3Normalise2<t_scalar,brr3>(aux, n); // but it must be inwards, i. e., on the same side of the plane than n3. int n3 = getMissingNode(n0, n1, n2); arr3arr3Add<t_scalar,brr3>(aux, tetA[n0], aux); t_scalar d = - arr3arr3DotProduct<t_scalar,brr3>(n, tetA[n0]); t_scalar t1 = arr3arr3DotProduct<t_scalar,brr3>(tetA[n3], n) + d; t_scalar t2 = arr3arr3DotProduct<t_scalar,brr3>(aux, n) + d; if (!sameSign(t1,t2)) arr3Resize<t_scalar,brr3>(ffea_const::mOne, n); } /** Given the face formed by f0, f1, and f2, * and knowing the remaining p3 for a tetrahedron, * get n, the normal to a face pointing inwards. */ template <class t_scalar, class brr3> void getNormalInwards(brr3 &f0, brr3 &f1, brr3 &f2, brr3 &p3, brr3 (&n)){ // pl1 and pl2 are the unit vectors (tetA[n1] - tetA[n0]) and (tetA[n2] - tetA[n0]), brr3 pl1, pl2, aux; arr3arr3Substract<t_scalar,brr3>(f1, f0, pl1); arr3arr3Substract<t_scalar,brr3>(f2, f0, pl2); // n is a unit vector normal to the face: arr3arr3VectorProduct<t_scalar,brr3>(pl1, pl2, aux); arr3Normalise2<t_scalar,brr3>(aux, n); // but it must be inwards, i. e., on the same side of the plane than n3. arr3arr3Add<t_scalar,brr3>(aux, f0, aux); t_scalar d = - arr3arr3DotProduct<t_scalar,brr3>(n, f0); t_scalar t1 = arr3arr3DotProduct<t_scalar,brr3>(p3, n) + d; t_scalar t2 = arr3arr3DotProduct<t_scalar,brr3>(aux, n) + d; if (!sameSign(t1,t2)) arr3Resize<t_scalar,brr3>(ffea_const::mOne, n); } /** check if points vec and test are at the same side * of the plane formed by p1, p2 and p3 */ template <class t_scalar, class brr3> bool sameSidePlane(brr3 &vec, brr3 &test, brr3 &p1, brr3 &p2, brr3 &p3){ brr3 pl1, pl2, n; arr3arr3Substract<t_scalar,brr3>(p2, p1, pl1); arr3arr3Substract<t_scalar,brr3>(p3, p1, pl2); arr3arr3VectorProduct<t_scalar,brr3>(pl1, pl2, n); arr3Normalise<t_scalar,brr3>(n); t_scalar d = - arr3arr3DotProduct<t_scalar,brr3>(n, p1); t_scalar t1 = arr3arr3DotProduct<t_scalar,brr3>(vec, n) + d; t_scalar t2 = arr3arr3DotProduct<t_scalar,brr3>(test, n) + d; // if ((t1 * t2) >= 0 ) return true; // cout << "t1: " << t1 << " t2: " << t2 << endl; if (sameSign(t1,t2)) return true; else return false; } /** Given 4 co-planar points, check if ip and p1 lay on the same side * of the of the line formed by p2 and p3. * More specifically we check whether pl23 x pl21 and pl23 x pl2e * are parallel or antiparallel. */ template <class t_scalar, class brr3> bool sameSideLine(brr3 &e, brr3 &p1, brr3 &p2, brr3 &p3) { // if (!samePlane(e, p1, p2, p3)) cout << "alarm" << endl; brr3 pl23, pl21, pl2e, v1, ve; arr3arr3Substract<t_scalar,brr3>(p3, p2, pl23); arr3arr3Substract<t_scalar,brr3>(p1, p2, pl21); arr3arr3Substract<t_scalar,brr3>(e, p2, pl2e); arr3arr3VectorProduct<t_scalar,brr3>(pl21, pl23, v1); arr3arr3VectorProduct<t_scalar,brr3>(pl2e, pl23, ve); if (arr3arr3DotProduct<t_scalar,brr3>(v1,ve) >= 0) return true; return false; } /** check whether vector vec is in tetrahedron B. */ /** more specifically, it will be there if * for each plane of the tetrahedron, * the point is on the same side as the remaining vertex */ template <class t_scalar,class brr3> bool nodeInTet(brr3 &vec, brr3 (tet)[4]){ if (!sameSidePlane<t_scalar,brr3>(vec, tet[0], tet[1], tet[2], tet[3])) return false; if (!sameSidePlane<t_scalar,brr3>(vec, tet[1], tet[2], tet[3], tet[0])) return false; if (!sameSidePlane<t_scalar,brr3>(vec, tet[2], tet[3], tet[0], tet[1])) return false; if (!sameSidePlane<t_scalar,brr3>(vec, tet[3], tet[0], tet[1], tet[2])) return false; return true; } template <class t_scalar,class brr3> bool nodeInTet(brr3 &vec, brr3 &tet0, brr3 &tet1, brr3 &tet2, brr3 &tet3){ if (!sameSidePlane<t_scalar,brr3>(vec, tet0, tet1, tet2, tet3)) return false; if (!sameSidePlane<t_scalar,brr3>(vec, tet1, tet2, tet3, tet0)) return false; if (!sameSidePlane<t_scalar,brr3>(vec, tet2, tet3, tet0, tet1)) return false; if (!sameSidePlane<t_scalar,brr3>(vec, tet3, tet0, tet1, tet2)) return false; return true; } /** find the intersection point of the line that passes through the points e1 and e2, * and the plane defined by points p1, p2 and p3. * \warning {this function should be called ONLY in the case * that intersection is known to occur.} */ template <class t_scalar, class brr3> void linePlaneIntersectionPoint(brr3 &ip, brr3 &e1, brr3 &e2, brr3 &p1, brr3 &p2, brr3 &p3) { // v is the vector of the line L(t) = e1 + v*t brr3 v; arr3arr3Substract<t_scalar,brr3>(e2, e1, v); // now we need the unit vector that defines the plane, pn: brr3 pl1, pl2, pn; arr3arr3Substract<t_scalar,brr3>(p2, p1, pl1); arr3arr3Substract<t_scalar,brr3>(p3, p2, pl2); getUnitNormal<t_scalar,brr3>(pl1, pl2, pn); // the plane is defined through: ax + by + cz + d = 0; // (a,b,c) = pn // so to find d we simply: t_scalar d = - arr3arr3DotProduct<t_scalar,brr3>(pn, p1); // now find t and the point: t_scalar t = - (arr3arr3DotProduct<t_scalar,brr3>(pn, e1) + d) / arr3arr3DotProduct<t_scalar,brr3>(pn, v); arr3Resize<t_scalar,brr3>(t, v); arr3arr3Add<t_scalar,brr3>(e1, v, ip); } /** Return true and * the intersection point of the line that passes through the points e1 and e2 * and the plane defined by points p1, p2, p3 if this intersection actually occurs, * and false otherwise. * \warning p1, p2, and p3 are assumed to be non-colinear. */ template <class t_scalar, class brr3> bool safeLinePlaneIntersectionPoint(brr3 &ip, brr3 &e1, brr3 &e2, brr3 &p1, brr3 &p2, brr3 &p3) { // v is the vector of the line L(t) = e1 + v*t brr3 v; arr3arr3Substract<t_scalar,brr3>(e2, e1, v); // now we need the unit vector that defines the plane, pn: brr3 pl1, pl2, pn; arr3arr3Substract<t_scalar,brr3>(p2, p1, pl1); arr3arr3Substract<t_scalar,brr3>(p3, p2, pl2); getUnitNormal<t_scalar,brr3>(pl1, pl2, pn); // CHECK! scalar pnv = arr3arr3DotProduct<t_scalar,brr3>(pn, v); if ( abs(pnv) < ffea_const::threeErr ) return false; // the line won't intersect the plane! // the plane is defined through: ax + by + cz + d = 0; // (a,b,c) = pn // so to find d we simply: t_scalar d = - arr3arr3DotProduct<t_scalar,brr3>(pn, p1); // now find t and the point: t_scalar t = - (arr3arr3DotProduct<t_scalar,brr3>(pn, e1) + d) / arr3arr3DotProduct<t_scalar,brr3>(pn, v); arr3Resize<t_scalar,brr3>(t, v); arr3arr3Add<t_scalar,brr3>(e1, v, ip); return true; } /** Return true and * the intersection point ip of the line that passes through the points e1 and e2 * and face defined by points p1, p2, p3 if this intersection actually occurs, * and false otherwise. * \warning p1, p2, and p3 are assumed to be non-colinear. */ template <class t_scalar,class brr3> bool lineFaceIntersectionPoint(brr3 (&ip), brr3 (&e1), brr3 (&e2), brr3 (&p1), brr3 (&p2), brr3 (&p3)){ // look for the intersection point... if it exists if ( not safeLinePlaneIntersectionPoint<t_scalar,brr3>(ip, e1, e2, p1, p2, p3)) return false; // and finally check whether this point ip belongs to the triangular face: if ( (isPointInFace<t_scalar,brr3>(ip, p1, p2, p3)) ) return true; return false; } /** Check whether point ip is * inside of the three half-planes formed by the triangle's edges p1, p2, p3. */ template <class t_scalar, class brr3> bool isPointInFace(brr3 &ip, brr3 &p1, brr3 &p2, brr3 &p3) { if (! sameSideLine<t_scalar,brr3>(ip, p1, p2, p3) ) return false; if (! sameSideLine<t_scalar,brr3>(ip, p3, p1, p2) ) return false; if (! sameSideLine<t_scalar,brr3>(ip, p2, p3, p1) ) return false; return true; } /** Check whether an edge and a plane intersect, * and return the intersection point ip and true if found, false otherwise. * more specifically check that both: * - both ends of the edge (e1 and e2) are on different sides * of the plane defined by the vectors (tet[f2] - tet[f1]) and (tet[f3] - tet[f1]). * - the intersection of a line is a point in the plane */ // bool intersectionPoint(arr3 &(ip), arr3 (&e1), arr3 (&e2), arr3 (&tet)[4], int f1, int f2, int f3){ template <class t_scalar,class brr3> bool intersectionPoint(brr3 &(ip), brr3 (&e1), brr3 (&e2), brr3 (&tet)[4], int f1, int f2, int f3){ // check it e1 and e2 are on the same side of the plane: if ( sameSidePlane<t_scalar,brr3>(e1, e2, tet[f1], tet[f2], tet[f3]) ) return false; // given that they are on different sides of the plane look for the intersection point. linePlaneIntersectionPoint<t_scalar,brr3>(ip, e1, e2, tet[f1], tet[f2], tet[f3]); // and finally check whether this point ip belongs to the triangular face: if ( (isPointInFace<t_scalar,brr3>(ip, tet[f1], tet[f2], tet[f3])) ) return true; return false; } /** Check whether an edge and a plane intersect, * and return the intersection point ip and true if found, false otherwise. * more specifically check that both: * - both ends of the edge (e1 and e2) are on different sides * of the plane defined by the vectors (f2 - f1) and (f3 - f1). * - the intersection of a line is a point in the plane */ template <class t_scalar,class brr3> bool intersectionPoint(brr3 &ip, brr3 &e1, brr3 &e2, brr3 &f1, brr3 &f2, brr3 &f3){ // check it e1 and e2 are on the same side of the plane: if ( sameSidePlane<t_scalar,brr3>(e1, e2, f1, f2, f3) ) return false; // given that they are on different sides of the plane look for the intersection point. linePlaneIntersectionPoint<t_scalar,brr3>(ip, e1, e2, f1, f2, f3); // and finally check whether this point ip belongs to the triangular face: if ( (isPointInFace<t_scalar,brr3>(ip, f1, f2, f3)) ) return true; return false; } template <class t_scalar, class brr3> void intersectingPointToLine(arr3_view<t_scalar,brr3> p0, arr3_view<t_scalar,brr3> p1, arr3_view<t_scalar,brr3> p2p1, arr3_view<t_scalar,brr3> p3) { brr3 p0p1, cp3p0, v2, v1v2; t_scalar c; arr3arr3Substract<t_scalar,brr3>(p0, p1, p0p1); arr3arr3VectorProduct<t_scalar,brr3>(p0p1, p2p1, v2); // CHECK! if the cross product is null, then distance is zero, and p3 is p0 itself. if (mag<t_scalar,brr3>(v2) < ffea_const::threeErr) { arr3Store(p0, p3); return; } // get cp3p0, the vector to (or from) to the line p2p1: arr3arr3VectorProduct<t_scalar,brr3>(p2p1, v2, cp3p0); // now calculate c, the amount of cp3p0 from p0 to the intersection point p3. arr3arr3VectorProduct<t_scalar,brr3>(p2p1, cp3p0, v1v2); c = detByRows<t_scalar, brr3>(p0p1, p2p1, v1v2); c /= ( v1v2[0]*v1v2[0] + v1v2[1]*v1v2[1] + v1v2[2]*v1v2[2]); // and finally calculate the intersection point: arr3Resize<t_scalar,brr3>(c, cp3p0); arr3arr3Add<t_scalar,brr3>(p0, cp3p0, p3); /* // CHECKS START HERE! // brr3 p3p0; arr3arr3Substract<t_scalar,brr3>(p3, p0, p3p0); c = mag<t_scalar,brr3>(p3p0); // check the distance: t_scalar d = distanceFromPointToLine<t_scalar, brr3>(p0, p1, p2); if (abs (d - abs(c)) > ffea_const::threeErr) { cout << "something is wrong: d = " << d << " differs from c = " << c << endl; } */ return; } template <class t_scalar, class brr3> void intersectingPointToLine(vector3 &p0, arr3_view<t_scalar,brr3> p1, arr3_view<t_scalar,brr3> p2p1, arr3_view<t_scalar,brr3> p3) { brr3 p0p1, cp3p0, v2, v1v2; t_scalar c; // arr3arr3Substract<t_scalar,brr3>(p2, p1, p2p1); // arr3arr3Substract<t_scalar,brr3>(p0, p1, p0p1); p0p1[0] = p0.x - p1[0]; p0p1[1] = p0.y - p1[1]; p0p1[2] = p0.z - p1[2]; arr3arr3VectorProduct<t_scalar,brr3>(p0p1, p2p1, v2); // CHECK! if the cross product is null, then distance is zero, and p3 is p0 itself. if (mag<t_scalar,brr3>(v2) < ffea_const::threeErr) { // arr3Store(p0, p3); p3[0] = p0.x; p3[1] = p0.y; p3[2] = p0.z; return; } // get cp3p0, the vector to (or from) to the line p2p1: arr3arr3VectorProduct<t_scalar,brr3>(p2p1, v2, cp3p0); // now calculate c, the amount of cp3p0 from p0 to the intersection point p3. arr3arr3VectorProduct<t_scalar,brr3>(p2p1, cp3p0, v1v2); c = detByRows<t_scalar, brr3>(p0p1, p2p1, v1v2); c /= ( v1v2[0]*v1v2[0] + v1v2[1]*v1v2[1] + v1v2[2]*v1v2[2]); // and finally calculate the intersection point: arr3Resize<t_scalar,brr3>(c, cp3p0); p3[0] = p0.x + cp3p0[0]; p3[1] = p0.y + cp3p0[1]; p3[2] = p0.z + cp3p0[2]; /* // CHECKS START HERE! // brr3 p3p0; arr3arr3Substract<t_scalar,brr3>(p3, p0, p3p0); c = mag<t_scalar,brr3>(p3p0); // check the distance: t_scalar d = distanceFromPointToLine<t_scalar, brr3>(p0, p1, p2); if (abs (d - c) > ffea_const::threeErr) { cout << "something is wrong: d = " << d << " differs from c = " << c << endl; } */ return; } template <class t_scalar, class brr3> t_scalar distanceFromPointToLine(arr3_view<t_scalar,brr3> p0, arr3_view<t_scalar,brr3> p1, arr3_view<t_scalar,brr3> p2) { brr3 p2p1, p0p1, p0p2, tmp1; arr3arr3Substract<t_scalar,brr3>(p2, p1, p2p1); arr3arr3Substract<t_scalar,brr3>(p0, p2, p0p2); arr3arr3Substract<t_scalar,brr3>(p0, p1, p0p1); arr3arr3VectorProduct<t_scalar,brr3>(p0p1, p0p2, tmp1); scalar d = mag<t_scalar,brr3>(tmp1) / mag<t_scalar,brr3>(p2p1); return d; } /* template <class t_scalar, class brr3> t_scalar getTetrahedraVolume(arr3_view<t_scalar,brr3> p0, arr3_view<t_scalar,brr3> p1, arr3_view<t_scalar,brr3> p2, arr3_view<t_scalar,brr3> p3){ scalar v = 0; v += detByCols<scalar,arr3>(p1, p2, p3); v -= detByCols<scalar,arr3>(p0, p2, p3); v += detByCols<scalar,arr3>(p0, p1, p3); v -= detByCols<scalar,arr3>(p0, p1, p2); return v/6.; }*/ template <class t_scalar, class brr3> t_scalar getTetrahedraVolume(arr3_view<t_scalar,brr3> p0, arr3_view<t_scalar,brr3> p1, arr3_view<t_scalar,brr3> p2, arr3_view<t_scalar,brr3> p3){ return (p1[0] - p0[0])*( (p1[1] - p2[1])*(p2[2] - p3[2]) - (p2[1] - p3[1])*(p1[2] - p2[2]) ) + (p2[0] - p1[0])*( (p2[1] - p3[1])*(p0[2] - p1[2]) - (p0[1] - p1[1])*(p2[2] - p3[2]) ) + (p3[0] - p2[0])*( (p0[1] - p1[1])*(p1[2] - p2[2]) - (p1[1] - p2[1])*(p0[2] - p1[2]) ); } template <class brr3> void getTetrahedraCM(brr3 &p1, brr3 &p2, brr3 &p3, brr3 &p4, brr3 &c){ for (int i=0; i<3; i++){ c[i] = 0.25 * (p1[i] + p2[i] + p3[i] + p4[i]); } } template <class t_scalar, class brr3, class brr4> void getLocalCoordinatesForLinTet(arr3_view<t_scalar,brr3> t0, arr3_view<t_scalar,brr3> t1, arr3_view<t_scalar,brr3> t2, arr3_view<t_scalar,brr3> t3, arr3_view<t_scalar,brr3> p, brr4 &phi){ phi[0] = getTetrahedraVolume(p, t1, t2, t3); phi[1] = - getTetrahedraVolume(p, t0, t2, t3); phi[2] = getTetrahedraVolume(p, t0, t1, t3); phi[3] = - getTetrahedraVolume(p, t0, t1, t2); t_scalar v = getTetrahedraVolume(t0, t1, t2, t3); for (int i=0; i<4; i++) { phi[i] /= v; } /* // CHECK!! for the time: arr3 tmp, pc; arr3Initialise<arr3>(pc); // WT*? arr3Resize2<scalar,arr3>(phi[0], t0, tmp); arr3arr3Add<scalar,arr3>(pc, tmp, pc); arr3Resize2<scalar,arr3>(phi[1], t1, tmp); arr3arr3Add<scalar,arr3>(pc, tmp, pc); arr3Resize2<scalar,arr3>(phi[2], t2, tmp); arr3arr3Add<scalar,arr3>(pc, tmp, pc); arr3Resize2<scalar,arr3>(phi[3], t3, tmp); arr3arr3Add<scalar,arr3>(pc, tmp, pc); arr3arr3Substract<scalar,arr3>(p, pc, tmp); if (mag<scalar,arr3>(tmp) > 1e-6) { cout << "local coordinates were not correctly calculated!" << endl; cout << "p: " << p[0] << ", " << p[1] << ", " << p[2] << endl; cout << "pc: " << pc[0] << ", " << pc[1] << ", " << pc[2] << endl; cout << "diff: " << mag<scalar,arr3>(tmp) << endl; } */ } //////////////////////////////////////////////// ////////////// END OF SECTION 2 //////////////// //////////////////////////////////////////////// ///////////////// SECTION 3 //////////////////// /// Transition functions from vector3 to arr3 // //////////////////////////////////////////////// template <class brr3> void vec3Vec3SubsToArr3(vector3 &u, vector3 &v, brr3 (&w)){ w[0] = u.x - v.x; w[1] = u.y - v.y; w[2] = u.z - v.z; } void vec3Arr3SubsToArr3(vector3 &u, arr3 (&v), arr3 (&w)){ w[0] = u.x - v[0]; w[1] = u.y - v[1]; w[2] = u.z - v[2]; } void arr3Vec3SubsToArr3(arr3 (&u), vector3 &v, arr3 (&w)){ w[0] = u[0] - v.x; w[1] = u[1] - v.y; w[2] = u[2] - v.z; } void vec3Arr3AddToArr3(vector3 &u, arr3 (&v), arr3 (&w)){ w[0] = u.x + v[0]; w[1] = u.y + v[1]; w[2] = u.z + v[2]; } void vec3ResizeToArr3(scalar f, vector3 &u, arr3 (&v)){ v[0] = f*u.x; v[1] = f*u.y; v[2] = f*u.z; } scalar vec3Arr3DotProduct(vector3 &u, arr3 &v) { scalar s; s = u.x * v[0]; s += u.y * v[1]; s += u.z * v[2]; return s; } //////////////////////////////////////////////// ////////////// END OF SECTION 3 //////////////// //////////////////////////////////////////////// ///////////////// SECTION 4 //////////////////// // // // // Instantiate templates // // // // // //////////////////////////////////////////////// template bool sameSign<scalar>(scalar a, scalar b); template void arr3arr3Add<scalar, arr3>(arr3_view<scalar,arr3> vecA, arr3_view<scalar,arr3> vecB, arr3_view<scalar,arr3> res); template void arr3arr3Substract<scalar,arr3>(arr3_view<scalar,arr3> vecA, arr3_view<scalar,arr3> vecB, arr3_view<scalar,arr3> res); template void arr3arr3VectorProduct<scalar,arr3>(arr3_view<scalar,arr3> u, arr3_view<scalar,arr3> v, arr3_view<scalar,arr3> w); template scalar arr3arr3DotProduct<scalar,arr3>(arr3_view<scalar,arr3> vecA, arr3_view<scalar,arr3> vecB); template void arr3Normalise<scalar,arr3>(arr3_view<scalar,arr3> e); template void arr3Normalise2<scalar,arr3>(arr3_view<scalar,arr3> e, arr3_view<scalar,arr3> n); template void arr3Resize<scalar,arr3>(scalar f, arr3_view<scalar,arr3> u); template void arr3Resize2<scalar,arr3> (scalar f, arr3_view<scalar,arr3> u, arr3_view<scalar,arr3> v); template void arr3Resize3<scalar,arr3> (scalar f, arr3_view<scalar,arr3> u, arr3_view<scalar,arr3> v); template void arr3Store<scalar,arr3>(arr3_view<scalar,arr3> u, arr3_view<scalar,arr3> v); template scalar arr3arr3Distance<scalar,arr3>(arr3_view<scalar,arr3> vecA, arr3_view<scalar,arr3> vecB); template scalar mag<scalar,arr3>(arr3_view<scalar,arr3> v); template scalar mag2<scalar,arr3>(arr3_view<scalar,arr3> v); template void arr3Initialise<arr3>(arr3 &v); template scalar detByRows<scalar,arr3>(arr3_view<scalar,arr3> a, arr3_view<scalar,arr3> b, arr3_view<scalar,arr3> c); template scalar detByCols<scalar,arr3>(arr3_view<scalar,arr3> a, arr3_view<scalar,arr3> b, arr3_view<scalar,arr3> c); #ifndef USE_DOUBLE template bool sameSign<geoscalar>(geoscalar a, geoscalar b); template void arr3arr3Add<geoscalar, grr3>(arr3_view<geoscalar,grr3> vecA, arr3_view<geoscalar,grr3> vecB, arr3_view<geoscalar,grr3> res); template void arr3arr3Substract<geoscalar,grr3>(arr3_view<geoscalar,grr3> vecA, arr3_view<geoscalar,grr3> vecB, arr3_view<geoscalar,grr3> res); template void arr3arr3VectorProduct<geoscalar,grr3>(arr3_view<geoscalar,grr3> u, arr3_view<geoscalar,grr3> v, arr3_view<geoscalar,grr3> w); template geoscalar arr3arr3DotProduct<geoscalar,grr3>(arr3_view<geoscalar,grr3> vecA, arr3_view<geoscalar,grr3> vecB); template void arr3Normalise<geoscalar,grr3>(arr3_view<geoscalar,grr3> e); template void arr3Normalise2<geoscalar,grr3>(arr3_view<geoscalar,grr3> e, arr3_view<geoscalar,grr3> n); template void arr3Resize<geoscalar,grr3>(geoscalar f, arr3_view<geoscalar,grr3> u); template void arr3Resize2<geoscalar,grr3> (geoscalar f, arr3_view<geoscalar,grr3> u, arr3_view<geoscalar,grr3> v); template void arr3Resize3<geoscalar,grr3> (geoscalar f, arr3_view<geoscalar,grr3> u, arr3_view<geoscalar,grr3> v); template void arr3Store<geoscalar,grr3>(arr3_view<geoscalar,grr3> u, arr3_view<geoscalar,grr3> v); template geoscalar arr3arr3Distance<geoscalar,grr3>(arr3_view<geoscalar,grr3> vecA, arr3_view<geoscalar,grr3> vecB); template geoscalar mag<geoscalar,grr3>(arr3_view<geoscalar,grr3> v); template geoscalar mag2<geoscalar,grr3>(arr3_view<geoscalar,grr3> v); template void arr3Initialise<grr3>(grr3 &v); template geoscalar detByRows<geoscalar,grr3>(arr3_view<geoscalar,grr3> a, arr3_view<geoscalar,grr3> b, arr3_view<geoscalar,grr3> c); template geoscalar detByCols<geoscalar,grr3>(arr3_view<geoscalar,grr3> a, arr3_view<geoscalar,grr3> b, arr3_view<geoscalar,grr3> c); #endif template void tangent<scalar,arr3>(arr3 &vecA, arr3 &vecB, arr3 &t); template void getUnitNormal<scalar,arr3>(arr3 &u, arr3 &v, arr3 &w); template void getNormal<scalar,arr3>(arr3 &v1, arr3 &v2, arr3 &v3, arr3 &n); template void getNormalInwards<scalar,arr3>(arr3 (&tetA)[4], int n0, int n1, int n2, arr3 (&n)); template void getNormalInwards<scalar,arr3>(arr3 &f0, arr3 &f1, arr3 &f2, arr3 &p3, arr3 (&n)); template bool sameSidePlane<scalar,arr3>(arr3 &vec, arr3 &test, arr3 &p1, arr3 &p2, arr3 &p3); template bool sameSideLine<scalar,arr3>(arr3 &e, arr3 &p1, arr3 &p2, arr3 &p3); template bool nodeInTet<scalar,arr3>(arr3 &vec, arr3 (tet)[4]); template bool nodeInTet<scalar,grr3>(arr3 &vec, arr3 &tet0, arr3 &tet1, arr3 &tet2, arr3 &tet3); template void linePlaneIntersectionPoint<scalar,arr3>(arr3 &ip, arr3 &e1, arr3 &e2, arr3 &p1, arr3 &p2, arr3 &p3); template bool safeLinePlaneIntersectionPoint<scalar,arr3>(arr3 &ip, arr3 &e1, arr3 &e2, arr3 &p1, arr3 &p2, arr3 &p3); template bool lineFaceIntersectionPoint<scalar,arr3>(arr3 (&ip), arr3 (&e1), arr3 (&e2), arr3 (&p1), arr3 (&p2), arr3 (&p3)); template bool isPointInFace<scalar,arr3>(arr3 &ip, arr3 &p1, arr3 &p2, arr3 &p3); template bool intersectionPoint<scalar,arr3>(arr3 &(ip), arr3 (&e1), arr3 (&e2), arr3 (&tet)[4], int f1, int f2, int f3); template bool intersectionPoint<scalar,arr3>(arr3 &ip, arr3 &e1, arr3 &e2, arr3 &f1, arr3 &f2, arr3 &f3); // template void intersectingPointToLine<scalar, arr3>(arr3 &p0, arr3 &p1, arr3 &p2, arr3 &p3); template void intersectingPointToLine<scalar, arr3>(arr3_view<scalar, arr3> p0, arr3_view<scalar,arr3> p1, arr3_view<scalar,arr3> p2p1, arr3_view<scalar,arr3> p3); template void intersectingPointToLine<scalar, arr3>(vector3 &p0, arr3_view<scalar,arr3> p1, arr3_view<scalar,arr3> p2p1, arr3_view<scalar,arr3> p3); template scalar distanceFromPointToLine<scalar,arr3>(arr3_view<scalar, arr3> p0, arr3_view<scalar, arr3> p1, arr3_view<scalar, arr3> p2); template scalar getTetrahedraVolume<scalar,arr3>(arr3_view<scalar,arr3> p0, arr3_view<scalar,arr3> p1, arr3_view<scalar,arr3> p2, arr3_view<scalar,arr3> p3); template void getTetrahedraCM<arr3>(arr3 &p1, arr3 &p2, arr3 &p3, arr3 &p4, arr3 &c); template void getLocalCoordinatesForLinTet<scalar,arr3,arr4>(arr3_view<scalar,arr3> t0, arr3_view<scalar,arr3> t1, arr3_view<scalar,arr3> t2, arr3_view<scalar,arr3> t3, arr3_view<scalar,arr3> p, arr4 &phi); ////////////// template void vec3Vec3SubsToArr3<arr3>(vector3 &u, vector3 &v, arr3 (&w)); #ifndef USE_DOUBLE template void tangent<geoscalar,grr3>(grr3 &vecA, grr3 &vecB, grr3 &t); template void getUnitNormal<geoscalar,grr3>(grr3 &u, grr3 &v, grr3 &w); template void getNormal<geoscalar,grr3>(grr3 &v1, grr3 &v2, grr3 &v3, grr3 &n); template void getNormalInwards<geoscalar,grr3>(grr3 (&tetA)[4], int n0, int n1, int n2, grr3 (&n)); template void getNormalInwards<geoscalar,grr3>(grr3 &f0, grr3 &f1, grr3 &f2, grr3 &p3, grr3 (&n)); template bool sameSidePlane<geoscalar,grr3>(grr3 &vec, grr3 &test, grr3 &p1, grr3 &p2, grr3 &p3); template bool sameSideLine<geoscalar,grr3>(grr3 &e, grr3 &p1, grr3 &p2, grr3 &p3); template bool nodeInTet<geoscalar,grr3>(grr3 &vec, grr3 (tet)[4]); template bool nodeInTet<geoscalar,grr3>(grr3 &vec, grr3 &tet0, grr3 &tet1, grr3 &tet2, grr3 &tet3); template void linePlaneIntersectionPoint<geoscalar,grr3>(grr3 &ip, grr3 &e1, grr3 &e2, grr3 &p1, grr3 &p2, grr3 &p3); template bool safeLinePlaneIntersectionPoint<geoscalar,grr3>(grr3 &ip, grr3 &e1, grr3 &e2, grr3 &p1, grr3 &p2, grr3 &p3); template bool lineFaceIntersectionPoint<geoscalar,grr3>(grr3 (&ip), grr3 (&e1), grr3 (&e2), grr3 (&p1), grr3 (&p2), grr3 (&p3)); template bool isPointInFace<geoscalar,grr3>(grr3 &ip, grr3 &p1, grr3 &p2, grr3 &p3); template bool intersectionPoint<geoscalar,grr3>(grr3 &(ip), grr3 (&e1), grr3 (&e2), grr3 (&tet)[4], int f1, int f2, int f3); template bool intersectionPoint<geoscalar,grr3>(grr3 &ip, grr3 &e1, grr3 &e2, grr3 &f1, grr3 &f2, grr3 &f3); template void intersectingPointToLine<geoscalar, grr3>(arr3_view<geoscalar, grr3> p0, arr3_view<geoscalar,grr3> p1, arr3_view<geoscalar,grr3> p2p1, arr3_view<geoscalar,grr3> p3); template void intersectingPointToLine<geoscalar, grr3>(vector3 &p0, arr3_view<geoscalar,grr3> p1, arr3_view<geoscalar,grr3> p2p1, arr3_view<geoscalar,grr3> p3); template geoscalar distanceFromPointToLine<geoscalar,grr3>(arr3_view<geoscalar, grr3> p0, arr3_view<geoscalar, grr3> p1, arr3_view<geoscalar, grr3> p2); template geoscalar getTetrahedraVolume<geoscalar,grr3>(arr3_view<geoscalar,grr3> p0, arr3_view<geoscalar,grr3> p1, arr3_view<geoscalar,grr3> p2, arr3_view<geoscalar,grr3> p3); template void getTetrahedraCM<grr3>(grr3 &p1, grr3 &p2, grr3 &p3, grr3 &p4, grr3 &c); template void getLocalCoordinatesForLinTet<geoscalar,grr3,grr4>(arr3_view<geoscalar,grr3> t0, arr3_view<geoscalar,grr3> t1, arr3_view<geoscalar,grr3> t2, arr3_view<geoscalar,grr3> t3, arr3_view<geoscalar,grr3> p, grr4 &phi); template void vec3Vec3SubsToArr3<grr3>(vector3 &u, vector3 &v, grr3 (&w)); #endif
36.843096
239
0.640622
zzalscv2
493a4227a94f21bab9b11ee133da6af36d8f41a0
66,031
cpp
C++
FrameWorkCode/slpNPatternDict.cpp
ayushbits/udaan-post-editing
499303a641598978d89cf0210776e80d98d2212a
[ "BSD-3-Clause" ]
1
2022-01-25T19:27:55.000Z
2022-01-25T19:27:55.000Z
FrameWorkCode/slpNPatternDict.cpp
ayushbits/udaan-post-editing
499303a641598978d89cf0210776e80d98d2212a
[ "BSD-3-Clause" ]
null
null
null
FrameWorkCode/slpNPatternDict.cpp
ayushbits/udaan-post-editing
499303a641598978d89cf0210776e80d98d2212a
[ "BSD-3-Clause" ]
null
null
null
#include <string> #include <sstream> #include <fstream> #include <iostream> #include <map> #include <set> #include <vector> #include <algorithm> #include <iterator> #include <vector> #include <QMessageBox> #include <iostream> #include "qdebug.h" #include "qtextstream.h" #include <cassert> #include <cmath> #include <string> #include <unordered_map> #include <QFile> #include "eddis.h" #include "slpNPatternDict.h" //#include <boost/serialization/map.hpp> //#include <boost/serialization/vector.hpp> //#include <boost/serialization/serialization.hpp> //#include <boost/serialization/unordered_map.hpp> //#include <boost/archive/text_iarchive.hpp> //#include <boost/archive/text_oarchive.hpp> //#include "toFromslp1.h" using namespace std; bool HinFlag = 0, SanFlag = 1; string slpNPatternDict :: ReplaceString(string subject, const string& search, const string& replace) { size_t pos=0; while((pos=subject.find(search, pos)) != string::npos) { subject.replace(pos, search.length(),replace); pos+=1; } return subject; } string slpNPatternDict :: ReplaceStringRestricted(string subject, const string& search, const string& replace) { size_t pos=0; char c; string replace_new=replace+"a"; // replace_new=replace_new+m; //cout<<"here "<<subject<<endl; while((pos=subject.find(search, pos)) != string::npos) { if(pos == subject.size()) break; //cout << subject<< " "<<pos <<" "<<subject.size()<< endl; if( subject.size() == pos + 3) c=subject.at(pos+2); else c=subject.at(pos+3); //CHANGE TO 3 IF EVERYTHING DOES NOT WORK if(c=='A' || c=='i' || c=='I' || c=='u' || c=='U' || c=='f' || c=='F' || c=='x' || c=='X' || c=='e' || c=='E' || c=='o' || c=='O') subject.replace(pos, search.length(),replace); else subject.replace(pos, search.length(),replace_new); pos+=1; } //cout<<"here21 "<<subject<<endl; return subject; } void slpNPatternDict :: loadFileCSV(map<string, vector<int>>& synonym, vector<vector<string>>& synrows, const string filename){ QString fn = QString::fromStdString(filename); QFile file(fn); if (!file.open(QIODevice::ReadOnly)) { qDebug() << file.errorString(); return; } QTextStream in(&file); QStringList wordList; int j = 0; while (!in.atEnd()) { QString line = in.readLine(); QList<QString> L = line.split(','); qDebug() << L.first() << endl; vector<string> V; synrows.push_back(V); for(int i=0 ; i < L.size(); i++){ string S = L[i].toUtf8().constData(); if(S != "" && j){ S.erase(remove(S.begin(), S.end(), ' '), S.end()); if(S.substr(0, 1) == "\""){ S = S.substr(1, S.size()-1); } if(S.substr(S.size()-1, 1) == "\""){ S = S.substr(0, S.size()-1); } cout << S << endl; synrows[j].push_back(S); synonym[S].push_back(j); } } cout << j << endl; j++; } } string slpNPatternDict :: toDev(string s) { //Hin:- if (HinFlag){ string vowel_dn[]={"अ","आ","इ","ई","उ","ऊ","ऋ","ए","ऐ","ओ","औ","ऑ","ं","ः","ँ","ॅ"}; string vowel_dn_joiner[]={"","ा","ि","ी","ु","ू","ृ","े","ै","ो","ौ","ॉ"}; string vowel_slp1[]={"a","A","i","I","u","U","f","e","E","o","O","Z","M","H","~","*"}; string consonants_dn[]={"क","ख","ग","घ","ङ","च","छ","ज","झ","ञ","ट","ठ","ड","ढ","ण","त","थ","द","ध","न","प","फ","ब","भ","म","य","र","ल","व","श","ष","स","ह","क़","ख़","ग़","ज़","ड़","ढ़","ऩ","फ़","य़","ऱ","ळ"}; string consonants_dn_halanta[]={"क्","ख्","ग्","घ्","ङ्","च्","छ्","ज्","झ्","ञ्","ट्","ठ्","ड्","ढ्","ण्","त्","थ्","द्","ध्","न्","प्","फ्","ब्","भ्","म्","य्","र्","ल्","व्","श्","ष्","स्","ह्","क़्","ख़्","ग़्","ज़्","ड़्","ढ़्","ऩ्","फ़्","य़्","ऱ्","ळ्"}; string consonants_slp1[]={"k","K","g","G","N","c","C","j","J","Y","w","W","q","Q","R","t","T","d","D","n","p","P","b","B","m","y","r","l","v","S","z","s","h","@","#","$","F","x","X","%","^","&","V","L"}; string no_dn[]={"०","१","२","३","४","५","६","७","८","९","॥","।","–","—"}; string no_slp1[]={"0","1","2","3","4","5","6","7","8","9","||","|","-","-"}; for(int i=0;i<44;i++) { s=ReplaceString(s,consonants_slp1[i],consonants_dn_halanta[i]); } for(int i=0;i<12;i++) { s=ReplaceString(s,"्"+vowel_slp1[i],vowel_dn_joiner[i]); } for(int i=0;i<16;i++) { s=ReplaceString(s,vowel_slp1[i],vowel_dn[i]); } for(int i=0;i<13;i++) { s=ReplaceString(s,no_slp1[i],no_dn[i]); } } else if(SanFlag ){ string vowel_dn[]={"अ","आ","इ","ई","उ","ऊ","ऋ","ॠ","ऌ","ॡ","ए","ऐ","ओ","औ","ं","ः","ँ","ᳲ","ᳳ","ऽ","ॐ"}; string vowel_dn_joiner[]={"","ा","ि","ी","ु","ू","ृ","ॄ","ॢ","ॣ","े","ै","ो","ौ"}; //string consonants_dn[]={"क","ख","ग","घ","ङ","च","छ","ज","झ","ञ","ट","ठ","ड","ढ","ण","त","थ","द","ध","न","प","फ","ब","भ","म","य","र","ल","व","श","ष","स","ह","ळ"}; string consonants_dn_halanta[]={"क्","ख्","ग्","घ्","ङ्","च्","छ्","ज्","झ्","ञ्","ट्","ठ्","ड्","ढ्","ण्","त्","थ्","द्","ध्","न्","प्","फ्","ब्","भ्","म्","य्","र्","ल्","व्","श्","ष्","स्","ह्","ळ्"}; string vowel_slp1[]={"a","A","i","I","u","U","f","F","x","X","e","E","o","O","M","H","~","Z","V","$","%"}; string consonants_slp1[]={"k","K","g","G","N","c","C","j","J","Y","w","W","q","Q","R","t","T","d","D","n","p","P","b","B","m","y","r","l","v","S","z","s","h","L"}; string numbers_etc_dn[]={"॥","।","॰","ऽ","‘","’","“","”","ॐ","१","२","३","४","५","६","७","८","९","०"}; string numbers_eng[]={"||","|","^0","$","-'","'","-\"","\"","%","1","2","3","4","5","6","7","8","9","0"}; for(int i=0;i<34;i++) { s=ReplaceString(s,consonants_slp1[i],consonants_dn_halanta[i]); } //cout << "here1 " << s <<endl; for(int i=0;i<14;i++) { s=ReplaceString(s,"्"+vowel_slp1[i],vowel_dn_joiner[i]); } //cout << "here2 " << s <<endl; for(int i=0;i<21;i++) { s=ReplaceString(s,vowel_slp1[i],vowel_dn[i]); } //cout << "here3 " << s <<endl; for(unsigned int i=0;i<(sizeof(numbers_etc_dn)/sizeof(numbers_etc_dn[0]));i++) { s=ReplaceString(s,numbers_eng[i],numbers_etc_dn[i]); } //cout << "here3 " << s <<endl; //cout<<s<<endl; } return s; } string slpNPatternDict :: toslp1(string s) { //Hin:- if (HinFlag){ string vowel_dn[]={"अ","आ","इ","ई","उ","ऊ","ऋ","ए","ऐ","ओ","औ","ऑ","ं","ः","ँ","ॅ"}; string vowel_dn_joiner[]={"ा","ि","ी","ु","ू","ृ","े","ै","ो","ौ","ॉ"}; string vowel_slp1[]={"a","A","i","I","u","U","f","e","E","o","O","Z","M","H","*","~"}; string consonants_dn[]={"क","ख","ग","घ","ङ","च","छ","ज","झ","ञ","ट","ठ","ड","ढ","ण","त","थ","द","ध","न","प","फ","ब","भ","म","य","र","ल","व","श","ष","स","ह","क़","ख़","ग़","ज़","ड़","ढ़","ऩ","फ़","य़","ऱ","ळ"}; string consonants_dn_halanta[]={"क्","ख्","ग्","घ्","ङ्","च्","छ्","ज्","झ्","ञ्","ट्","ठ्","ड्","ढ्","ण्","त्","थ्","द्","ध्","न्","प्","फ्","ब्","भ्","म्","य्","र्","ल्","व्","श्","ष्","स्","ह्","क़्","ख़्","ग़्","ज़्","ड़्","ढ़्","ऩ्","फ़्","य़्","ऱ्","ळ्"}; string consonants_slp1[]={"k","K","g","G","N","c","C","j","J","Y","w","W","q","Q","R","t","T","d","D","n","p","P","b","B","m","y","r","l","v","S","z","s","h","@","#","$","F","x","X","%","^","&","V","L"}; string no_dn[]={"०","१","२","३","४","५","६","७","८","९","॥","।","–","—"}; string no_slp1[]={"0","1","2","3","4","5","6","7","8","9","||","|","-","-"}; for(int i=0;i<44;i++) { s=ReplaceString(s,consonants_dn_halanta[i],consonants_slp1[i]); } for(int i=0;i<11;i++) { s=ReplaceString(s,vowel_dn_joiner[i],vowel_slp1[i+1]); } for(int i=0;i<16;i++) { s=ReplaceString(s,vowel_dn[i],vowel_slp1[i]); } for(int i=0;i<43;i++) { s=ReplaceStringRestricted(s,consonants_dn[i],consonants_slp1[i]); } for(int i=0;i<14;i++) { s=ReplaceString(s,no_dn[i],no_slp1[i]); } } else if(SanFlag){ //San:- string vowel_dn[]={"अ","आ","इ","ई","उ","ऊ","ऋ","ॠ","ऌ","ॡ","ए","ऐ","ओ","औ","ं","ः","ँ","ᳲ","ᳳ"}; string vowel_dn_joiner[]={"ा","ि","ी","ु","ू","ृ","ॄ","ॢ","ॣ","े","ै","ो","ौ"}; string consonants_dn[]={"क","ख","ग","घ","ङ","च","छ","ज","झ","ञ","ट","ठ","ड","ढ","ण","त","थ","द","ध","न","प","फ","ब","भ","म","य","र","ल","व","श","ष","स","ह","ळ"}; string consonants_dn_halanta[]={"क्","ख्","ग्","घ्","ङ्","च्","छ्","ज्","झ्","ञ्","ट्","ठ्","ड्","ढ्","ण्","त्","थ्","द्","ध्","न्","प्","फ्","ब्","भ्","म्","य्","र्","ल्","व्","श्","ष्","स्","ह्","ळ्"}; string vowel_slp1[]={"a","A","i","I","u","U","f","F","x","X","e","E","o","O","M","H","~","Z","V"}; string consonants_slp1[]={"k","K","g","G","N","c","C","j","J","Y","w","W","q","Q","R","t","T","d","D","n","p","P","b","B","m","y","r","l","v","S","z","s","h","L"}; //cout<<s<<endl; size_t pos = 0; while((pos=s.find("ॆ", pos)) != string::npos) s.replace(pos, 3,"े"); pos = 0; while((pos=s.find("ऎ", pos)) != string::npos) s.replace(pos, 3,"एे"); size_t pos1 = 0; while((pos1=s.find("ॊ", pos1)) != string::npos) s.replace(pos1, 3,"ो"); //cout<<s<<endl; pos1 = 0; //cout<<s<<" "<<s.find("ऴ्", pos1)<<endl; while((pos1=s.find("ऴ्", pos1)) != string::npos)//"ळ" is valid, dot below "ळ" is invalid char {s.replace(pos1, 6,"ळ्"); } //cout<<s<<endl; pos1 = 0; //cout<<s<<" "<<s.find("ऴ", pos1)<<endl; while((pos1=s.find("ऴ", pos1)) != string::npos)//"ळ" is valid, dot below "ळ" is invalid char {s.replace(pos1, 6,"ळ"); } //cout<<s<<endl; for(int i=0;i<34;i++) { s=ReplaceString(s,consonants_dn_halanta[i],consonants_slp1[i]); } for(int i=0;i<13;i++) { s=ReplaceString(s,vowel_dn_joiner[i],vowel_slp1[i+1]); } for(int i=0;i<19;i++) { s=ReplaceString(s,vowel_dn[i],vowel_slp1[i]); } //cout<<"here "<< s<<endl; for(int i=0;i<34;i++) { //cout<< i << " " << consonants_dn[i] << " " << consonants_slp1[i] << endl; s=ReplaceStringRestricted(s,consonants_dn[i],consonants_slp1[i]); } //cout<<"here1 "<< s<<endl; //cout<<s<<"…"<<s.find("…", pos1)<<endl; string numbers_etc_dn[]={"॥","।","॰","ऽ","‘","’","“","”","ॐ","१","२","३","४","५","६","७","८","९","०"}; string numbers_eng[]={"||","|","^0","$","-'","'","-\"","\"","%","1","2","3","4","5","6","7","8","9","0"}; for(uint i=0;i<(sizeof(numbers_etc_dn)/sizeof(numbers_etc_dn[0]));i++) { s=ReplaceString(s,numbers_etc_dn[i],numbers_eng[i]); } } //ifSanflag over return s; } void slpNPatternDict :: printmapinDev(map<string,int> m1){ /*std::ofstream ss1("ppi.bin"); boost::archive::text_oarchive oarch1(ss1); oarch1 << PatWInst;*/ for( map<string,int>::const_iterator eptr=m1.begin(); eptr!=m1.end(); eptr++) cout << toDev(eptr->first) << endl; } void slpNPatternDict :: printmap(map<string,int>& m1){ /*std::ofstream ss1("ppi.bin"); boost::archive::text_oarchive oarch1(ss1); oarch1 << PatWInst;*/ for( map<string,int>::const_iterator eptr=m1.begin(); eptr!=m1.end(); eptr++) cout << (eptr->first) << endl; } void slpNPatternDict :: printmapstrstr(map<string,string>& m1){ /*std::ofstream ss1("ppi.bin"); boost::archive::text_oarchive oarch1(ss1); oarch1 << PatWInst;*/ for( map<string,string>::const_iterator eptr=m1.begin(); eptr!=m1.end(); eptr++) cout << (eptr->first) << " " <<(eptr->second) << endl; } void slpNPatternDict :: printmapWFreq(map<string,int>& m1){ /*std::ofstream ss1("ppi.bin"); boost::archive::text_oarchive oarch1(ss1); oarch1 << PatWInst;*/ for( map<string,int>::const_iterator eptr=m1.begin(); eptr!=m1.end(); eptr++) cout << (eptr->first) << " " <<(eptr->second) << endl; } void slpNPatternDict :: loadCwordsPair(string wordL,string wordR, map<string, string>& CPair,map<string,int>& Dict,map<string,int>& PWords){ if ((Dict[wordL] ==0) && (PWords[wordL] == 0)) CPair[wordL] = wordR; } void loadCPair(string filename, map<string, string>& CPair,map<string,int>& Dict, map<string,int>& PWords){ ifstream myfile(filename); slpNPatternDict slnp; if (myfile.is_open()) { string str1, str2; while (myfile >> str1 ) {myfile >> str2; slnp.loadCwordsPair(slnp.toslp1(str1),slnp.toslp1(str2),CPair,Dict,PWords);} cout <<"CPairs " << CPair.size() << " loaded" << endl; } else cout <<"Error:" << filename << "CPair NOT there/loaded" << endl; } void slpNPatternDict :: loadCwordsPairs(string wordL,string wordR, map<string, set<string> >& CPairs,map<string,int>& Dict,map<string,int>& PWords) { //cout<< "hello"<<wordR<<endl; std::replace(wordR.begin(), wordR.end(), ',', ' '); stringstream ss(wordR); string setwords; set<string> setstring; while (ss >> setwords) { //cout << setwords << endl; setstring.insert(setwords); } //set<string> wordRs = wordR; CPairs[wordL] = setstring; } void slpNPatternDict :: loadCPairs(string filename, map<string, set<string> >& CPairs,map<string,int>& Dict, map<string,int>& PWords) { ifstream myfile(filename); if (myfile.is_open()) { string line; while(getline(myfile, line)) { //cout << "String 1"<<line<<endl; //!Making CPair formatting into Correct format upto max extent QString line1 = QString::fromStdString(line); line1.replace(" ","\t"); //dealing with incorrect format QStringList m = line1.split("\t"); if(m[1] == "") { //continue; QMessageBox::information(0, "File Error", "Make sure CPair contains correct file format\nIncorrect_Word(tab)Correct_Word"); break; } line = line1.toStdString(); // Vector of string to save tokens vector <string> tokens; // stringstream class check1 stringstream check1(line); string intermediate; // Tokenizing w.r.t. space 'tab' while(getline(check1, intermediate, '\t')) { tokens.push_back(intermediate); } // Printing the token vector for(int i = 0; i < tokens.size(); i++) { string str1 = tokens[0]; string str2 = tokens[1]; loadCwordsPairs(toslp1(str1),toslp1(str2),CPairs,Dict,PWords); } } cout <<"CPairs " << CPairs.size() << " loaded" << endl; } else cout <<"Error:" << filename << "CPair NOT there/loaded" << endl; } void slpNPatternDict :: loadMapNV(string fileName, map<string,int>& OCRWords, vector<string>& vec, string GBook){ ifstream myfile(fileName); if (myfile.is_open()) { string str1; while (myfile >> str1 ) { str1 = toslp1(str1); OCRWords[str1] = OCRWords[str1] + 1;vec.push_back(str1);} cout <<GBook <<" " <<OCRWords.size() <<" Words Loaded in mapNvector" << endl; } else cout <<"Error:" << GBook<< "Words NOT Loaded in mapNvector" << endl; } int slpNPatternDict :: minIG(int a, int b){ if(a>b)return b; else return a;} int slpNPatternDict :: maxIG(int a, int b){ if(a<b)return b; else return a;} void slpNPatternDict :: loadMapPWords(vector<string>& vGBook,vector<string>& vIBook, map<string,int>& PWords){ int vGsz = vGBook.size(), vIsz = vIBook.size(); int win = vGsz - vIsz; if(win<0) win = -1*win; // search for a word(pre space, post space as well) in Indsenz within win sized window in GDocs and if found then add to PWords for(int t = 0; t < vIsz;t++){ for(int t1 = maxIG(t-win,0); t1 < min(t+win,vGsz); t1++){ string s1 = vIBook[t]; //(vGBook[t1].find(s1) != string::npos) || (vGBook[t1] == s1) if( (vGBook[t1].find(s1) != string::npos)|| (vGBook[t1].find(s1 + " ") != string::npos) || (vGBook[t1].find(" " + s1) != string::npos)) {PWords[s1]++; break;} } } cout << PWords.size() << " words loaded in PWords" << endl; } string slpNPatternDict :: findDictEntries1(string s1, map<string, int>& m2, map<string, int>& m1, int size) { //unordered_ if((s1.size() == 0) || (s1 == "")) return ""; //cout << "s1 "<< s1 << endl; //cout << s1 << endl; //rAmaAnand for(size_t j =0; j < s1.size() ; j++){ //- i +1 j= 0:8 for(size_t i = s1.size() - j; i > 0; i--){// j0 i = 9:1 rAmaAnand rAmaAnan rAmaAna.. , j1 8:2 string str = s1.substr(j,i); //&&((str.size() >= 3)|| ( (str.size()==2) && (str[1] != 'a') &&( size< 3) ) || ((str.size() ==1)&&( size< 2) ) )) //cout << "str "<< str << endl; if((m2[str]>0)||(m1[str]>0)) { //cout << "here "<< str << "L " << s1.substr(0,j) << "R " << s1.substr(j+i,s1.size()-i) << endl; //colorFlag = !colorFlag; //string strcolor = color[colorFlag];// << endl; //cout << "str "<< str << endl; return findDictEntries1(s1.substr(0,j),m2,m1,size) + "<font color=\'" + "green" + "\'>" + toDev(str) + "</font>" + findDictEntries1(s1.substr(j+i,s1.size()-i),m2,m1,size); } } } //cout << "here2 "<< str << "sd"<< endl; return ("<font color=\'red\'>" + toDev(s1) + "</font>"); } string slpNPatternDict :: findDictEntries(string s1, map<string, int>& m2, map<string, int>& m1, int size) { //unordered_ m2["rAma"]++; m2["rAm"]++; string s = findDictEntries1(s1,m2,m1, size); string vowel_dn[]={"आ","इ","ई","उ","ऊ","ऋ","ॠ","ऌ","ॡ","ए","ऐ","ओ","औ"}; string vowel_dn_joiner[]={"ा","ि","ी","ु","ू","ृ","ॄ","ॢ","ॣ","े","ै","ो","ौ"}; //cout << s << endl; size_t t1 = s.find("\'>"); string sL = s.substr(0,t1+3); string sR = s.substr(t1+3,s.size()-t1-3); //cout << sL << " " << sR << endl; for(size_t t =0; t< 12; t++){ string tofind = "\'>" + vowel_dn[t]; while((sR.find(tofind) != string::npos)){ //cout << s << endl; cout << s.find(tofind) << endl; sR.replace(sR.find(tofind),tofind.size(), "\'>" + vowel_dn_joiner[t]); //cout << s << endl; } } return sL + sR; } bool slpNPatternDict :: hasM40PerAsci(string word1){ if(SanFlag||HinFlag){ string asc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; size_t sz = word1.size(); double cnt = 0; for(size_t t =0; t < sz; t++){ if(asc.find(word1.substr(t,1)) != string::npos) cnt ++; if (cnt/(0.4) >= sz) return 1; } } return 0; } bool slpNPatternDict :: hasNoAsci(string word1){ string asc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; size_t sz = word1.size(); for(size_t t =0; t < sz; t++){ if(asc.find(word1.substr(t,1)) != string::npos) {return 0; } } return 1; } void slpNPatternDict :: loadMap(string fileName, map<string,int>& OCRWords, string GBook){ size_t szp = OCRWords.size(); ifstream myfile(fileName); if (myfile.is_open()) { string str1; while (myfile >> str1 ) { if(!hasM40PerAsci(str1)) {str1 = toslp1(str1); /*cout <<str1<<endl;*/ OCRWords[str1] = OCRWords[str1] + 1;}} cout << GBook <<" " <<OCRWords.size() - szp<<" Words Loaded" << endl; } else cout <<"Error:" << GBook<< "Words NOT Loaded" << endl; } // ADDED FOR FEATYRE EXTRACTION bool slpNPatternDict :: insertPatternstoMap(string str, map<string,int>& TPWordsP, size_t& count ,size_t& count6){ //map<string,int >& PWordsP size_t sz = str.size(); if(sz == 0) return 1; for(size_t i = 0; i < (sz+1); i++){ string s1 = str.substr(0,i); if (s1.size()<9) count6++; TPWordsP[s1]++; count++;//PWordsP[s1]++; } return insertPatternstoMap(str.substr(1,sz-1),TPWordsP,count,count6);//PWordsP } // ADDED FOR FEATYRE EXTRACTION //loadPWordsPatternstoTrie(TPWordsP,PWordsP,PWords); size_t slpNPatternDict :: loadDictPatternstoMap(map<string,int >& TPWordsP, map<string,int >& PWords,size_t& count6){ // arg1(strt from 0) ,map<string,int >& PWordsP size_t count = 0,maxsiz = 0; for( map<string,int >::const_iterator ptr=PWords.begin(); ptr!=PWords.end(); ptr++) { insertPatternstoMap(ptr->first, TPWordsP,count,count6); if (ptr->first.size() > maxsiz) maxsiz = ptr->first.size(); } cout << count <<" patterns loaded " << endl; //cout << "m2 size " << m2.size() << endl; return maxsiz; } // ADDED FOR FEATYRE EXTRACTION bool slpNPatternDict :: getNgramFeaturesinVect(string str,map<string,int>& Dict,vector<bool>& vb,vector<size_t>& vbf, size_t& count){ size_t sz = str.size(); //cout<<sz<<endl; if(sz == 1) return 1; for(size_t i = 2; i < (sz+1); i++){ string s1 = str.substr(0,i); //cout<<s1<<endl; if(s1.size() < 9){ if (Dict[s1]>0){vb.push_back(1); vbf.push_back(Dict[s1]);} else {vb.push_back(0); vbf.push_back(0);} count++; } //cout << vb[count]<<endl; } return getNgramFeaturesinVect(str.substr(1,sz-1),Dict,vb,vbf, count);//PWordsP } // ADDED FOR FEATYRE EXTRACTION //https://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c bool slpNPatternDict :: endsWith(const std::string& s, const std::string& suffix) { return s.size() >= suffix.size() && s.substr(s.size() - suffix.size()) == suffix; } // ADDED FOR FEATYRE EXTRACTION std::vector<std::string> slpNPatternDict :: split(const std::string& s, const std::string& delimiter, const bool& removeEmptyEntries) { std::vector<std::string> tokens; for (size_t start = 0, end; start < s.length(); start = end + delimiter.length()) { size_t position = s.find(delimiter, start); end = position != string::npos ? position : s.length(); std::string token = s.substr(start, end - start); if (!removeEmptyEntries || !token.empty()) { tokens.push_back(token); } } if (!removeEmptyEntries && (s.empty() || endsWith(s, delimiter))) { tokens.push_back(""); } return tokens; } //ADDED FOR ERROR DETECTION REPORT bool slpNPatternDict :: searchS1inGVec(string s1,size_t iocrdone,vector<string>& gocr,size_t winig){ for(int t1 = maxIG(iocrdone-winig,0); t1 < min(iocrdone+winig,gocr.size()); t1++){ if (s1 == gocr[t1]) return 1; } return 0; } string slpNPatternDict :: findDictEntries(string s1, map<string, int>& m2, map<string, int>& m1) {//unordered_ if((s1.size() == 0) || (s1 == "")) return ""; //cout << s1 << endl; for(size_t i = s1.size(); i > 0; i --){ for(size_t j =0; j < s1.size() - i +1; j++){ string str = s1.substr(j,i); if((m1[str]>0) ) { //cout << "here "<< str << "L " << s1.substr(0,j) << "R " << s1.substr(j+i,s1.size()-i) << endl; return findDictEntries(s1.substr(0,j),m2,m1) + "<font color=\'" + "green" + "\'>" + toDev(str) + "</font>" + findDictEntries(s1.substr(j+i,s1.size()-i),m2,m1); } else if(m2[str]>4) {//cout << "here "<< str << "L " << s1.substr(0,j) << "R " << s1.substr(j+i,s1.size()-i) << endl; return findDictEntries(s1.substr(0,j),m2,m1) + "<font color=\'" + "cyan" + "\'>" + toDev(str) + "</font>" + findDictEntries(s1.substr(j+i,s1.size()-i),m2,m1); } } } //cout << "here2 "<< str << "sd"<< endl; return ("<font color=\'red\'>" + toDev(s1) + "</font>");//("#" + s1 + "#");// } void slpNPatternDict :: find_and_replace(string& source, string const& find, string const& replace) { for(string::size_type i = 0; (i = source.find(find, i)) != string::npos;) { source.replace(i, find.length(), replace); i += replace.length(); } } string slpNPatternDict :: find_and_replace_oddInstancesblue(string source) { string find = "green"; string replace = "blue"; for(string::size_type i = 0; (i = source.find(find, i)) != string::npos;) { source.replace(i, find.length(), replace); //cout << source << endl; if ( replace == "blue") replace = "green"; else replace = "blue"; i += replace.length(); } return source; } string slpNPatternDict :: find_and_replace_oddInstancesorange(string source) { string find = "cyan"; string replace = "orange"; for(string::size_type i = 0; (i = source.find(find, i)) != string::npos;) { source.replace(i, find.length(), replace); //cout << source << endl; if ( replace == "orange") replace = "cyan"; else replace = "orange"; i += replace.length(); } return source; } using namespace std; void slpNPatternDict :: allignlcsnew(string& str1,string& str2,string& str3){ string str1new, str2new; size_t t1 = 0; size_t t2 =0; size_t t3 =0; string s1,s2,s3; // while1 // a) addition if s1 == s3, and s2 differs add space to s1n, append t2 only so that we can reach close to s1 == s3 == s2 // b) deletion if s2 == s3, and s1 differs add space to s2n, append t1 only so that we can reach close to s2 == s3 == s1 // substitution if s1 != s2 != s3 s1n += s1, s2n += s2 append t1 and t2 // nothing if s1 == s2 == s3 s1n += s1, s2n += s2 append t1 and t2 and t3; if t3 == str3.size() Up3Flag = 1 break; // if Up3Flag find which is smaller, add spaces in end of smaller smallstr = min(str1.size() - t1,str2.size() - t2); while(1){ s1 = str1.substr(t1,1); s2 = str2.substr(t2,1); s3 = str3.substr(t3,1); //a) add //cout << t1 << " " << t2 << " " << t3<< endl; //cout << s1 << " " << s2 << " " << s3<< endl; if((s1 == s3) && (s2 != s3)) {str1new += " "; str2new += s2; t2++; /*cout << "a growing str1new " << str1new <<endl;*/ } if((s2 == s3) && (s1 != s3)) {str2new += " "; str1new += s1; t1++; /*cout << "d growing str2new " << str2new <<endl;*/ } // b) if((s2 != s3) && (s1 != s3)) {str1new += s1; str2new += s2; t1++; t2++; /*cout << "s growing str12new " << str1new<<" " <<str2new <<endl;*/ } //c) if((s2 == s3) && (s1 == s3)) {str1new += s1; str2new += s2; t1++; t2++;t3++; /*cout << "n growing str12new " << str1new<<" " <<str2new <<endl;*/ if(t3 == str3.size()) {break;}} //d) } //cout << " " << str1new << " " << str2new << endl; uint max = str1.size() ; if(max < str2.size() ) max = str2.size() ; //cout << t1 << " " << t2 << " " << max<< endl; while(1) { if((t1>=max) && (t2>=max)) break; if(t1<str1.size()) s1 = str1.substr(t1,1); else s1 = " "; if(t2<str2.size()) s2 = str2.substr(t2,1); else s2 = " "; //cout << t1 << " " << t2 << " " << max<< endl; //cout << s1 << " " << s2 << " " << endl; if(t1 < max) str1new += s1; else str1new += " "; if(t2 < max) str2new += s2; else str2new += " "; t1++; t2++; } str1 = str1new; str2 = str2new; } typedef std::vector<int> lengths; /* The "members" type is used as a sparse set for LCS calculations. Given a sequence, xs, and members, m, then if m[i] is true, xs[i] is in the LCS. */ typedef std::vector<bool> members; /* Fill the LCS sequence from the members of a sequence, xs x - an iterator into the sequence xs xs_in_lcs - members of xs lcs - an output results iterator */ template <typename it, typename ot> void slpNPatternDict :: set_lcs(it x, members const & xs_in_lcs, ot lcs) { for (members::const_iterator xs_in = xs_in_lcs.begin(); xs_in != xs_in_lcs.end(); ++xs_in, ++x) { if (*xs_in) { *lcs++ = *x; } } } /* Calculate LCS row lengths given iterator ranges into two sequences. On completion, `lens` holds LCS lengths in the final row. */ template <typename it> void slpNPatternDict :: lcs_lens(it xlo, it xhi, it ylo, it yhi, lengths & lens) { // Two rows of workspace. // Careful! We need the 1 for the leftmost column. lengths curr(1 + distance(ylo, yhi), 0); lengths prev(curr); for (it x = xlo; x != xhi; ++x) { swap(prev, curr); int i = 0; for (it y = ylo; y != yhi; ++y, ++i) { curr[i + 1] = *x == *y ? prev[i] + 1 : std::max(curr[i], prev[i + 1]); } } swap(lens, curr); } /* Recursive LCS calculation. See Hirschberg for the theory! This is a divide and conquer algorithm. In the recursive case, we split the xrange in two. Then, by calculating lengths of LCSes from the start and end corners of the [xlo, xhi] x [ylo, yhi] grid, we determine where the yrange should be split. xo is the origin (element 0) of the xs sequence xlo, xhi is the range of xs being processed ylo, yhi is the range of ys being processed Parameter xs_in_lcs holds the members of xs in the LCS. */ template <typename it> void slpNPatternDict :: calculate_lcs(it xo, it xlo, it xhi, it ylo, it yhi, members & xs_in_lcs) { unsigned const nx = distance(xlo, xhi); if (nx == 0) { // empty range. all done } else if (nx == 1) { // single item in x range. // If it's in the yrange, mark its position in the LCS xs_in_lcs[distance(xo, xlo)] = find(ylo, yhi, *xlo) != yhi; } else { // split the xrange it xmid = xlo + nx / 2; // Find LCS lengths at xmid, working from both ends of the range lengths ll_b, ll_e; std::reverse_iterator<it> hix(xhi), midx(xmid), hiy(yhi), loy(ylo); lcs_lens(xlo, xmid, ylo, yhi, ll_b); lcs_lens(hix, midx, hiy, loy, ll_e); // Find the optimal place to split the y range lengths::const_reverse_iterator e = ll_e.rbegin(); int lmax = -1; it y = ylo, ymid = ylo; for (lengths::const_iterator b = ll_b.begin(); b != ll_b.end(); ++b, ++e) { if (*b + *e > lmax) { lmax = *b + *e; ymid = y; } // Care needed here! // ll_b and ll_e contain one more value than the range [ylo, yhi) // As b and e range over dereferenceable values of ll_b and ll_e, // y ranges over iterator positions [ylo, yhi] _including_ yhi. // That's fine, y is used to split [ylo, yhi), we do not // dereference it. However, y cannot go beyond ++yhi. if (y != yhi) { ++y; } } // Split the range and recurse calculate_lcs(xo, xlo, xmid, ylo, ymid, xs_in_lcs); calculate_lcs(xo, xmid, xhi, ymid, yhi, xs_in_lcs); } } // Calculate an LCS of (xs, ys), returning the result in an_lcs. template <typename seq> void slpNPatternDict :: lcs(seq const & xs, seq const & ys, seq & an_lcs) { members xs_in_lcs(xs.size(), false); calculate_lcs(xs.begin(), xs.begin(), xs.end(), ys.begin(), ys.end(), xs_in_lcs); set_lcs(xs.begin(), xs_in_lcs, back_inserter(an_lcs)); } bool slpNPatternDict :: isNonVowel(string ocrp){ string a = "aeiouAEIOU"; for(size_t t =0; t< a.size(); t ++){ if (ocrp == a.substr(t,1)) return 0; } return 1; } string slpNPatternDict :: removeSpaces(string input) { string output; int length = input.length(); for (int i = 0; i < length; i++) { if(input[i] != ' ') output+= input[i]; } return output; } void slpNPatternDict :: findConfisions(string ocr, string correct, vector<string>& vec){ //vector<string> vec; //ocrp = “”; correctp = “”; // for( t = 0 t< s.size) // load ocrp correctp if t > 0 with substr(t-1,1) //ocr == “”; correct = “” // while(s1 != s2) ocr += s1; correct += s2; t++;// s1 s2 are chars from each word // of ocrp == “”load ocrnext in ocrp wiht substr(t,1) // subss add if ocr != “” :- // if ocrp is a non-vowel vec.push_back(ocrp+ocr, correctp+correct) else vec.push_back(ocr, correct) //ocrp = s1; correctp = s2; size_t sz = ocr.size(); string ocrp = ""; size_t t = 0; while(1){ string ocrn =""; string correctn =""; string s1 = ocr.substr(t,1), s2 = correct.substr(t,1); //cout << "t = " << t << " " << sz << endl; // deletion if(s2 == " ") { while(s1 != s2) {ocrn += s1; correctn += s2; t++; if(t >= sz) break; s1 = ocr.substr(t,1); s2 = correct.substr(t,1);} if(ocrp != "") vec.push_back(removeSpaces(ocrp+ocrn) + " " + removeSpaces(ocrp+correctn)); else if(t < sz) vec.push_back(removeSpaces(ocrn + s1) + " " + removeSpaces(correctn + s1)); else vec.push_back(removeSpaces(ocrn) + " " + removeSpaces(correctn)); } // addition else if(s1 == " ") { while(s1 != s2) {ocrn += s1; correctn += s2; t++; if(t >= sz) break; s1 = ocr.substr(t,1); s2 = correct.substr(t,1);} if((ocrp != "")&&(isNonVowel(ocrp))) vec.push_back(removeSpaces(ocrp+ocrn) + " " + removeSpaces(ocrp+correctn)); else if(t < sz) vec.push_back(removeSpaces(ocrn + s1) + " " + removeSpaces(correctn + s1)); else vec.push_back(removeSpaces(ocrn) + " " + removeSpaces(correctn)); } else if(s1 != s2) { while(s1 != s2) {ocrn += s1; correctn += s2; t++; if(t >= sz) break; s1 = ocr.substr(t,1); s2 = correct.substr(t,1);} if((ocrp != "")&&(isNonVowel(ocrp))) vec.push_back(removeSpaces(ocrp+ocrn) + " " + removeSpaces(ocrp+correctn));/*else if(t < sz) cout << "s " << ocrn + s1 << " " << correctn + s1<< endl;*/ else vec.push_back(removeSpaces(ocrn) + " " + removeSpaces(correctn)); } else t++; ocrp = s1; if(t >= sz) break; } //return vec; } void slpNPatternDict :: findConfisionsNindex(string ocr, string correct, vector<string>& vec, vector<int>& vind){ //vector<string> vec; //ocrp = “”; correctp = “”; // for( t = 0 t< s.size) // load ocrp correctp if t > 0 with substr(t-1,1) //ocr == “”; correct = “” // while(s1 != s2) ocr += s1; correct += s2; t++;// s1 s2 are chars from each word // of ocrp == “”load ocrnext in ocrp wiht substr(t,1) // subss add if ocr != “” :- // if ocrp is a non-vowel vec.push_back(ocrp+ocr, correctp+correct) else vec.push_back(ocr, correct) //ocrp = s1; correctp = s2; size_t sz = ocr.size(); string ocrp = ""; size_t t = 0; int s1p; while(1){ string ocrn =""; string correctn =""; string s1 = ocr.substr(t,1), s2 = correct.substr(t,1); int s1t = t; //cout << "t = " << t << " " << sz << endl; // deletion if(s2 == " ") { while(s1 != s2) {ocrn += s1; correctn += s2; t++; if(t >= sz) break; s1 = ocr.substr(t,1); s2 = correct.substr(t,1);} if(ocrp != "") {vec.push_back(removeSpaces(ocrp+ocrn) + " " + removeSpaces(ocrp+correctn)); vind.push_back(s1p);}else if(t < sz) {vec.push_back(removeSpaces(ocrn + s1) + " " + removeSpaces(correctn + s1)); vind.push_back(s1t);} else {vec.push_back(removeSpaces(ocrn) + " " + removeSpaces(correctn)); vind.push_back(s1t);} } // addition else if(s1 == " ") { while(s1 != s2) {ocrn += s1; correctn += s2; t++; if(t >= sz) break; s1 = ocr.substr(t,1); s2 = correct.substr(t,1);} if((ocrp != "")&&(isNonVowel(ocrp))) {vec.push_back(removeSpaces(ocrp+ocrn) + " " + removeSpaces(ocrp+correctn)); vind.push_back(s1p);} else if(t < sz) {vec.push_back(removeSpaces(ocrn + s1) + " " + removeSpaces(correctn + s1)); vind.push_back(s1t);} else {vec.push_back(removeSpaces(ocrn) + " " + removeSpaces(correctn)); vind.push_back(s1t);} } else if(s1 != s2) { while(s1 != s2) {ocrn += s1; correctn += s2; t++; if(t >= sz) break; s1 = ocr.substr(t,1); s2 = correct.substr(t,1);} if((ocrp != "")&&(isNonVowel(ocrp))) {vec.push_back(removeSpaces(ocrp+ocrn) + " " + removeSpaces(ocrp+correctn)); vind.push_back(s1p);}/*else if(t < sz) cout << "s " << ocrn + s1 << " " << correctn + s1<< endl;*/ else {vec.push_back(removeSpaces(ocrn) + " " + removeSpaces(correctn)); vind.push_back(s1t);} } else {t++;} ocrp = s1; s1p = s1t; if(t >= sz) break; } //return vec; } void slpNPatternDict :: removeEndCommonSpaces(string& str1, string& str2){ size_t t = str1.size(); string s1 = str1.substr(t-1,1), s2 = str1.substr(t-1,1); while((s1 == " ") && (s2 == " ")) {str1 = str1.substr(0,t-1); str2 = str2.substr(0,t-1); t = str1.size(); s1 = str1.substr(t-1,1), s2 = str1.substr(t-1,1);} } /* vector<string> findConfisionsPair(string str1, string str2){ string str3; lcs(str1,str2,str3); allignlcsnew(str1,str2,str3); removeEndCommonSpaces(str1,str2); vector<string> vec = findConfisions(str1,str2); return vec; }*/ void slpNPatternDict :: appendConfusionsPairs(string str1, string str2, vector<string>& vec){ str1 = "@" + toslp1(str1) + "#"; str2 = "@" + toslp1(str2) + "#"; string str3; lcs(str1,str2,str3); allignlcsnew(str1,str2,str3); removeEndCommonSpaces(str1,str2); findConfisions(str1,str2,vec); //return vec; } string slpNPatternDict :: appendConfusionsPairsNindex(string str1, string str2, vector<string>& vec, vector<int>& vecind){ str1 = "@" + toslp1(str1) + "#"; str2 = "@" + toslp1(str2) + "#"; string str3; lcs(str1,str2,str3); allignlcsnew(str1,str2,str3); removeEndCommonSpaces(str1,str2); findConfisionsNindex(str1,str2,vec,vecind); return str1; //return vec; } void slpNPatternDict :: loadvectomap(vector<string> ConfP, map<string,int>& ConfPmap){ for(size_t t = 0; t<ConfP.size(); t++) ConfPmap[ConfP[t]]++; } void slpNPatternDict :: printvecstr(vector<string> ConfP){ for(size_t t = 0; t<ConfP.size(); t++) cout << ConfP[t] << endl; } void slpNPatternDict :: printvecint(vector<int> ConfP){ for(size_t t = 0; t<ConfP.size(); t++) cout << ConfP[t] << endl; } //loadConfusions("1kECPairs",ConfPmap) void slpNPatternDict :: loadConfusions(string fileName,map<string,int>& ConfPmap){ vector<string> ConfP; string str1, str2; ifstream myfile(fileName); if (myfile.is_open()) { while(myfile >> str1){ myfile >> str2; appendConfusionsPairs((str1),(str2),ConfP);//toslp1 //cout << str1 << " " << str2 << endl; //vec.clear(); } cout << ConfP.size() << " Confusions Loaded" << endl;} else cout <<"Error Confusions NOT Loaded" << endl; loadvectomap(ConfP,ConfPmap); } void slpNPatternDict :: loadConfusions2(string fileName1,string fileName2,map<string,int>& ConfPmap){ vector<string> ConfP; string str1, str2; ifstream myfile(fileName1); ifstream myfile2(fileName2); if ((myfile.is_open()) && (myfile2.is_open())) { while(myfile >> str1){ myfile2 >> str2; appendConfusionsPairs((str1),(str2),ConfP);//toslp1 //cout << str1 << " " << str2 << endl; //vec.clear(); } cout <<ConfP.size() << " Confusions Loaded" << endl;} else cout <<"Error Confusions NOT Loaded" << endl; loadvectomap(ConfP,ConfPmap); } void slpNPatternDict :: loadConfusionsFont(vector<string> fileName1,vector<string> fileName2,map<string,int>& ConfPmap){ vector<string> ConfP; if (fileName1.size() > 0) { for(size_t i =0;i < fileName1.size(); i++ ){ appendConfusionsPairs(fileName1[i],fileName2[i],ConfP);//toslp1 } cout << ConfP.size() << " Confusions Loaded from" << fileName1.size() <<" pairs"<< endl;} else cout <<"Error Confusions NOT Loaded" << endl; loadvectomap(ConfP,ConfPmap); } void slpNPatternDict :: generateCorrectionPairs(vector<string> &wrong,vector<string> &right,string localFilenameI,string localFilenameC){ vector<string> vecpI, vecpC; std::ifstream sIpage(localFilenameI); if (!(sIpage.is_open())) {cout << "cannot open inds/corrected file" <<endl; return;} // break the while loop for page_no string localstr; map<string, bool> isEngOrNOT; while(sIpage >> localstr) vecpI.push_back(toslp1(localstr)); sIpage.close(); std::ifstream sCpage(localFilenameC); while(sCpage >> localstr) { vecpC.push_back(toslp1(localstr)); sIpage.close(); if(hasM40PerAsci(localstr)) isEngOrNOT[toslp1(localstr)] = 1;} int sizew = wrong.size(); // if 1st word is wrong generate suggestions int vGsz = vecpC.size(), vIsz = vecpI.size(); //if (vGsz >vIsz ) mapTyping[page_no] = vGsz - vIsz; //cout << vGsz << " " << vIsz << endl; int win = vGsz - vIsz; if(win<0) win = -1*win; win = maxIG(win,5); //cout << win << endl; //float WER = 0; // search for a word(pre space, post space as well) in Indsenz within win sized window in GDocs and if found then add to PWords for(int t = 0; t < vIsz;t++){ size_t minedit = 1000; string s1 = vecpI[t]; //(vGBook[t1].find(s1) != string::npos) || (vGBook[t1] == s1) string sC; for(int t1 = maxIG(t-win,0); t1 < min(t+win,vGsz); t1++){ string sCt1 = vecpC[t1]; eddis e; size_t mineditIC = e.editDist(s1,sCt1); if(mineditIC < minedit) {minedit = mineditIC; sC = sCt1; } if (sCt1 == s1) {/*WER++;*/ break;} } if((s1 != sC) && (/*isEngOrNOT[sC] != */1)) {wrong.push_back(s1); right.push_back(sC); /*cout << s1 <<" " << sC << endl;*/} } cout << wrong.size() - sizew << " new correction pairs loaded" << endl; } void slpNPatternDict :: generatePairs(vector<string> &wrong,vector<string> &right,string localFilenameI,string localFilenameC){ vector<string> vecpI, vecpC; std::ifstream sIpage(localFilenameI); if (!(sIpage.is_open())) {cout << "cannot open inds/corrected file" <<endl; return;} // break the while loop for page_no string localstr; map<string, bool> isEngOrNOT; while(sIpage >> localstr) vecpI.push_back(toslp1(localstr)); sIpage.close(); std::ifstream sCpage(localFilenameC); while(sCpage >> localstr) { vecpC.push_back(toslp1(localstr)); sIpage.close(); if(hasM40PerAsci(localstr)) isEngOrNOT[toslp1(localstr)] = 1;} int sizew = wrong.size(); // if 1st word is wrong generate suggestions int vGsz = vecpC.size(), vIsz = vecpI.size(); //if (vGsz >vIsz ) mapTyping[page_no] = vGsz - vIsz; //cout << vGsz << " " << vIsz << endl; int win = vGsz - vIsz; if(win<0) win = -1*win; win = maxIG(win,5); //cout << win << endl; //float WER = 0; // search for a word(pre space, post space as well) in Indsenz within win sized window in GDocs and if found then add to PWords for(int t = 0; t < vIsz;t++){ size_t minedit = 1000,minediti; string s1 = vecpI[t]; //(vGBook[t1].find(s1) != string::npos) || (vGBook[t1] == s1) string sC; for(int t1 = maxIG(t-win,0); t1 < min(t+win,vGsz); t1++){ string sCt1 = vecpC[t1]; eddis e; size_t mineditIC = e.editDist(s1,sCt1); if(mineditIC < minedit) {minedit = mineditIC; sC = sCt1; minediti = t1; } if (sCt1 == s1) {/*WER++;*/ sC = s1; vecpC[t1] = ""; break;} /*size_t szt = sCt1.find(s1); size_t sCt1sz = sCt1.size(); if((szt != string::npos) && (szt == 0)){/WER++;/ sC = s1; vecpC[t1] = sCt1.substr(s1.size(),sCt1sz - s1.size()); break;} if((szt != string::npos) && (szt == sCt1sz - s1.size())){ sC = s1; vecpC[t1] = sCt1.substr(0,sCt1sz - s1.size()); break;} */ } if(sC != s1) vecpC[minediti] = ""; if( (/*isEngOrNOT[sC] != */1)) {wrong.push_back(s1); right.push_back(sC); /*cout << s1 <<" " << sC << endl;*/} //(s1 != sC) && } cout << wrong.size() - sizew << " new correction pairs loaded" << endl; if(wrong.size() != right.size()) cout <<"ERROR (wrong.size() != right.size() ) "<<endl; } void slpNPatternDict :: generatePairsIEROCR(string localFilenameI,string localFilenameC, string Rep, string Repy){ vector<string> vecpI, vecpC; std::ofstream repPair(Rep); std::ofstream repPairy(Repy); std::ifstream sIpage(localFilenameI); if (!(sIpage.is_open())) {cout << "cannot open inds/corrected file" <<endl; return;} // break the while loop for page_no string localstr; map<string, bool> isEngOrNOT; while(sIpage >> localstr) vecpI.push_back(toslp1(localstr)); sIpage.close(); std::ifstream sCpage(localFilenameC); while(sCpage >> localstr) { vecpC.push_back(toslp1(localstr)); sIpage.close(); if(hasM40PerAsci(localstr)) isEngOrNOT[toslp1(localstr)] = 1;} //int sizew = wrong.size(); // if 1st word is wrong generate suggestions int vGsz = vecpC.size(), vIsz = vecpI.size(); //if (vGsz >vIsz ) mapTyping[page_no] = vGsz - vIsz; //cout << vGsz << " " << vIsz << endl; int win = vGsz - vIsz; if(win<0) win = -1*win; win = maxIG(win,20); //cout << win << endl; //float WER = 0; // search for a word(pre space, post space as well) in Indsenz within win sized window in GDocs and if found then add to PWords for(int t = 0; t < vIsz;t++){ size_t minedit = 1000,minediti; string s1 = vecpI[t]; //(vGBook[t1].find(s1) != string::npos) || (vGBook[t1] == s1) string sC; for(int t1 = maxIG(t-win,0); t1 < min(t+win,vGsz); t1++){ string sCt1 = vecpC[t1]; eddis e; size_t mineditIC = e.editDist(s1,sCt1); if(mineditIC < minedit) {minedit = mineditIC; sC = sCt1; minediti = t1; } if (sCt1 == s1) {/*WER++;*/ sC = s1; vecpC[t1] = ""; break;} /*size_t szt = sCt1.find(s1); size_t sCt1sz = sCt1.size(); if((szt != string::npos) && (szt == 0)){/WER++;/ sC = s1; vecpC[t1] = sCt1.substr(s1.size(),sCt1sz - s1.size()); break;} if((szt != string::npos) && (szt == sCt1sz - s1.size())){ sC = s1; vecpC[t1] = sCt1.substr(0,sCt1sz - s1.size()); break;} */ } if( (/*isEngOrNOT[sC] != */1) && (sC != "")) { repPair << s1 << endl; repPairy << sC << endl; } } repPairy.close(); repPair.close(); sIpage.close();sCpage.close(); } void slpNPatternDict :: generatePairsSpaced(vector<string> &wrong,vector<string> &right,string localFilenameI,string localFilenameC){ vector<string> vecpI, vecpC; std::ifstream sIpage(localFilenameI); if (!(sIpage.is_open())) {cout << "cannot open inds/corrected file" <<endl; return;} // break the while loop for page_no string localstr; map<string, bool> isEngOrNOT; while(sIpage >> localstr) vecpI.push_back(toslp1(localstr)); sIpage.close(); std::ifstream sCpage(localFilenameC); while(sCpage >> localstr) { vecpC.push_back(toslp1(localstr)); sIpage.close(); if(hasM40PerAsci(localstr)) isEngOrNOT[toslp1(localstr)] = 1;} int sizew = wrong.size(); // if 1st word is wrong generate suggestions int vGsz = vecpC.size(), vIsz = vecpI.size(); //if (vGsz >vIsz ) mapTyping[page_no] = vGsz - vIsz; //cout << vGsz << " " << vIsz << endl; int win = vGsz - vIsz; if(win<0) win = -1*win; win = maxIG(win,5); //cout << win << endl; //float WER = 0; // search for a word(pre space, post space as well) in Indsenz within win sized window in GDocs and if found then add to PWords for(int t = 0; t < vIsz;t++){ size_t minedit = 1000,minediti; string s1 = vecpI[t]; //(vGBook[t1].find(s1) != string::npos) || (vGBook[t1] == s1) string sC; for(int t1 = maxIG(t-win,0); t1 < min(t+win,vGsz); t1++){ string sCt1 = vecpC[t1]; eddis e; size_t mineditIC = e.editDist(s1,sCt1); if(mineditIC < minedit) {minedit = mineditIC; sC = sCt1; minediti = t1; } if (sCt1 == s1) {/*WER++;*/ sC = s1; vecpC[t1] = ""; break;} /*size_t szt = sCt1.find(s1); size_t sCt1sz = sCt1.size(); if((szt != string::npos) && (szt == 0)){/WER++;/ sC = s1; vecpC[t1] = sCt1.substr(s1.size(),sCt1sz - s1.size()); break;} if((szt != string::npos) && (szt == sCt1sz - s1.size())){ sC = s1; vecpC[t1] = sCt1.substr(0,sCt1sz - s1.size()); break;} */ } if(sC != s1) {vecpC[minediti] = "";} if( (/*isEngOrNOT[sC] != */1)) {wrong.push_back(s1); right.push_back(sC); /*cout << s1 <<" " << sC << endl;*/} else {wrong.push_back(s1); right.push_back("");}//(s1 != sC) && } cout << wrong.size() - sizew << " new correction pairs loaded" << endl; if(wrong.size() != right.size()) cout <<"ERROR (wrong.size() != right.size() ) "<<endl; } void slpNPatternDict :: loadCPair(string fileName1,string fileName2,map<string,string>& CPair){ string str1, str2; ifstream myfile(fileName1); ifstream myfile2(fileName2); if ((myfile.is_open()) && (myfile2.is_open())) { while(myfile >> str1){ myfile2 >> str2; CPair[str1] = str2;//toslp1 //cout << str1 << " " << str2 << endl; //vec.clear(); } cout <<CPair.size() << " CPairs Loaded" << endl;} else cout <<"Error CPairs NOT Loaded" << endl; //loadvectomap(ConfP,ConfPmap); } void slpNPatternDict :: loadTopConfusions(map<string,int>& ConfPmap,map<string, string>& TopConfusions,map<string, int>& TopConfusionsMask){ map<string, int> TopSuggFreq; for(map<string, int >::const_iterator it = ConfPmap.begin(); it != ConfPmap.end(); ++it) { //std::cout << it->first << " " << it->second<< "\n"; string rule = it->first; istringstream s(rule);string l,r; s>>l; s>>r; //if(TopSuggFreq[l] < it->second){ TopSuggFreq[l] = it->second; TopConfusions[l] = r; TopConfusionsMask[l] ++; //} l.clear(); r.clear(); } } std::string slpNPatternDict :: tokenize(const std::string& s) { if (!s.size()) { return ""; } std::stringstream ss; ss << s[0]; for (uint i = 1; i < s.size(); i++) { ss << ' ' << s[i]; } return ss.str(); } // print only rules in Pattern Miner's Rule Input form void slpNPatternDict :: printConfusionRulesmap(map<string,int>& ConfPmap){ map<string,vector<string> > rulesCorrectFormat; // print the Map rule and correct the format for(map<string, int >::const_iterator it = ConfPmap.begin(); it != ConfPmap.end(); ++it) { //std::cout << it->first << " " << it->second<< "\n"; string rule = it->first; istringstream s(rule); string l,r; s>>l; s>>r; if((l.size() < 3) && (r.size() < 3)) rulesCorrectFormat[r].push_back(l); } //file.close(); // print in correct format for( map<string,vector<string> >::const_iterator ptr=rulesCorrectFormat.begin(); ptr!=rulesCorrectFormat.end(); ptr++) { string s = (ptr->first); cout << tokenize(s) << " -> "; for( vector<string>::const_iterator eptr=ptr->second.begin(); eptr!=ptr->second.end(); eptr++){ string s1 = *eptr; cout << tokenize(s1) << " ! "; } cout << endl; } } //for choosing best out of nearest suggestions:- int slpNPatternDict :: loadWConfusionsNindex1(string str1,string str2,map<string,int>& ConfPmap,vector<string>& wordConfusions,vector<int>& wCindex){ string str1New = appendConfusionsPairsNindex(str1,str2,wordConfusions,wCindex); int szold = wordConfusions.size();// more confusions more szold //filter confusions:- //cout<< str1New << endl; for(size_t t = 0; t<wordConfusions.size(); t++) { if(ConfPmap[wordConfusions[t]]>0) {/*cout << wCindex[t] << " "<< toDev(wordConfusions[t]) << endl;*/} else {wordConfusions.erase(wordConfusions.begin() + t); wCindex.erase(wCindex.begin() + t); t--;}} return (szold - wordConfusions.size());// more confusions are Indsenz OCR Confusions, less will be difference } // for alligning OCR Pair words string slpNPatternDict :: loadWConfusionsNindex(string str1,string str2,map<string,int>& ConfPmap,vector<string>& wordConfusions,vector<int>& wCindex){ string str1New = appendConfusionsPairsNindex(str1,str2,wordConfusions,wCindex); //filter confusions:- //cout<< str1New << endl; for(size_t t = 0; t<wordConfusions.size(); t++) { if(ConfPmap[wordConfusions[t]]>0) {/*cout << wCindex[t] << " "<< toDev(wordConfusions[t]) << endl;*/} else {wordConfusions.erase(wordConfusions.begin() + t); wCindex.erase(wCindex.begin() + t); t--;}} return str1New; } void slpNPatternDict :: replacestrcnf(string& newstring,size_t i,string cnfn) { istringstream s(cnfn); string lhs,rhs; s >> lhs; s >> rhs; newstring = newstring.replace(i,lhs.length(),rhs); } // parts from SamasBreakComb.hpp bool slpNPatternDict :: endswithHalanta(string str) { if (str.size() <= 2) return 1; //ALSO INCLUDING ONE/TWO CHARS if (str.size() >= 4) return 0; //ignoring Words with Halanta having more than 4 chars string lastchar = str.substr(str.size()-1,1); string str1 = "aeiouAEIOUH"; for(size_t i = 0; i < str1.size(); i++) { if(str1.substr(i,1) == lastchar) return 0; } return 1; } void slpNPatternDict :: removeEndSpaces(string& str1){ size_t t = str1.size(); string s1 = str1.substr(t-1,1); //cout << "1 s1 " << s1<< endl; while((s1 == " ")) {str1 = str1.substr(0,t-1); t = str1.size(); s1 = str1.substr(t-1,1);} //cout << "2 s1 " << s1<< endl; s1 = str1.substr(0,1); //cout << "3 s1 " << s1<< endl; while((s1 == " ")) {str1 = str1.substr(1,t-1); t = str1.size(); s1 = str1.substr(0,1);} //cout << "4 s1 " << s1<< endl; } // parts from SamasBreakComb.hpp // samas corrector.h starts string slpNPatternDict :: deletePoornaVirams(string input){ string out; for(size_t t = 0; t < input.size(); t++){ string s; s += input[t]; if( s != "|") out += s; } return out; } /* applicable when trieeditdisone is used as searchTrie will give str as output, else it give vector<string> string SamasBreakLRCorrect(string s1, unordered_map<string, int>& m1, unordered_map<string, int>& PWordsNew) { if((s1.size() == 0) || (s1 == "")) return ""; if((m1[s1]>0)||PWordsNew[s1]>0) return " " + s1 + " "; //cout << "s1 "<< s1 << endl; for(size_t i = s1.size(); i > 0; i --){// DASOAHAM 8 for(size_t j =0; j < s1.size() - i+1; j++){ // i determinze size of substring string str = s1.substr(j,i);// i = 8, j = 0:0 DASOAHAM ; i = 7, j = 0:1 DASOAHA ASOAHAM..... ;i =1, j = 0:7 D A S O A H A M // checking str //cout <<"str outside " << str << endl; if((m1[str]>0)||PWordsNew[str]>0) { //cout << "here "<< str << " L " << s1.substr(0,j) << "R " << s1.substr(j+i,s1.size()-i) << endl; //cout <<"str inside " << str << endl; //cout <<"left "<< s1.substr(0,j) << " nearest "<< searchTrie(s1.substr(0,j)) << endl; //cout <<"right "<< s1.substr(j+i,s1.size()-i) << " nearest "<< searchTrie(s1.substr(j+i,s1.size()-i)) << endl; return deletePoornaVirams(searchTrie(s1.substr(0,j)) + (str) + searchTrie(s1.substr(j+i,s1.size()-i)) ); } } } return ""; // //return ((s1));//("#" + s1 + "#");// }*/ size_t slpNPatternDict :: cntSamas(string in, string& out){ out = ""; size_t cnt = 0; string word; removeEndSpaces(in); istringstream s(in); while(s >> word) {out += word + " "; cnt ++; /*cout << cnt << " " << word << " " << out << endl;*/} if(endswithHalanta(word)) cnt++; return cnt; } string slpNPatternDict :: SamasLR(string s1, map<string, int>& m1) {//, map<string, int>& PWordsNew if((s1.size() == 0) || (s1 == "")) return ""; if((m1[s1]>0)) return " " + s1 + " ";//||PWordsNew[s1]>0 //cout << "s1 "<< s1 << endl; for(size_t i = s1.size(); i > 0; i --){// DASOAHAM 8 for(size_t j =0; j < s1.size() - i+1; j++){ // i determinze size of substring string str = s1.substr(j,i);// i = 8, j = 0:0 DASOAHAM ; i = 7, j = 0:1 DASOAHA ASOAHAM..... ;i =1, j = 0:7 D A S O A H A M // checking str //cout <<"str outside " << str << endl; if((m1[str]>0)) {//||PWordsNew[str]>0 //cout << "here "<< str << " L " << s1.substr(0,j) << "R " << s1.substr(j+i,s1.size()-i) << endl; //cout <<"str inside " << str << endl; //cout <<"left "<< s1.substr(0,j) << " nearest "<< searchTrie(s1.substr(0,j)) << endl; //cout <<"right "<< s1.substr(j+i,s1.size()-i) << " nearest "<< searchTrie(s1.substr(j+i,s1.size()-i)) << endl; return (SamasLR(s1.substr(0,j),m1) + " " + (str)+ " " + SamasLR(s1.substr(j+i,s1.size()-i),m1) ); //,PWordsNew,PWordsNew } } } return (" #" + s1 + "# "); // //return ((s1));//("#" + s1 + "#");// } string slpNPatternDict :: SamasRL(string s1, map<string, int>& m1) { //, map<string, int>& PWordsNew if((s1.size() == 0) || (s1 == "")) return ""; if((m1[s1]>0)) return " " + s1 + " ";//||PWordsNew[s1]>0 //cout << "s1 "<< s1 << endl; for(size_t i = s1.size(); i > 0; i --){// DASOAHAM 8 for(size_t j =0; j < s1.size() - i+1; j++){ // i determinze size of substring //cout << s1.size() << " " << j << endl; size_t jd =s1.size() - i - j; string str = s1.substr(jd,i); if((m1[str]>0)) {//||PWordsNew[str]>0 //cout << "here "<< str << " L " << s1.substr(0,j) << "R " << s1.substr(j+i,s1.size()-i) << endl; //cout <<"str inside " << str << endl; //cout <<"left "<< s1.substr(0,j) << " nearest "<< searchTrie(s1.substr(0,j)) << endl; //cout <<"right "<< s1.substr(j+i,s1.size()-i) << " nearest "<< searchTrie(s1.substr(j+i,s1.size()-i)) << endl; return (SamasRL(s1.substr(0,jd),m1) + " " + (str)+ " " + SamasRL(s1.substr(jd+i,s1.size()-i),m1) );//,PWordsNew,PWordsNew } } } return (" #" + s1 + "# "); // //return ((s1));//("#" + s1 + "#");// } // samas corrector.h ends // str1cnt = minsize_t(cntSamas(SamasLR(toslp1(str1),Dict,SmasWords),partsLR), cntSamas(SamasRL(toslp1(str1),Dict,SmasWords),partsRL),FlagLR); size_t slpNPatternDict :: minsize_t(size_t a,size_t b,bool& FlagLR){ if (b < a) {FlagLR = 0; return b;} else {FlagLR =1; return a;} } //print2OCRSugg("RemGOCR",ConfPmap,Dict,SmasWords) string slpNPatternDict :: print2OCRSugg(string str1, string str2, map<string,int>& ConfPmap,map<string,int>& Dict){//,map<string,int> SmasWords //cout << "generating Pair Sugg for "<<str1<< " ";//<<"suggestion for " << endl if((str2 == "") || (str2 == " ") || (str2 == " ")) {/*cout << "no suggestion" << endl;*/ return "";} string partsLR,partsRL; string twoOCRsugg = str1; bool FlagLR,Flag1stSuggGenerated; Flag1stSuggGenerated =1; //Flag1stSuggGenerated :- if cnt 8 for str1 and <=8 for a suggestion then look for cnt <8 hence forth size_t str1cnt = minsize_t(cntSamas(SamasLR(toslp1(str1),Dict),partsLR), cntSamas(SamasRL(toslp1(str1),Dict),partsRL),FlagLR);//,SmasWords,SmasWords vector<string> wordConfusions; vector<int> wCindex; string str1New = loadWConfusionsNindex(str1,str2,ConfPmap,wordConfusions,wCindex); //cout << str1New << endl; printvecint(wCindex); printvecstr(wordConfusions); //apply confusions wordConfusions.size() .. 2 1 // lcs can give index of confusions say left are 3 6 9 // we need to try 3 6 9, 3 6, 6 9 ,3 9, 3 , 6 ,9 if any dec no of parts through min(samasLR,samasRL) stop and give suggestion //cout << str1New << endl; size_t sz = wordConfusions.size(); //cout << sz<< endl; size_t max = pow(2,sz) - 1; for(size_t i =max; i > 0; i--){ size_t mask = pow(2,sz-1); string newstring = str1New; for(size_t j =sz; j > 0; j--){ //generate new string using mask say 101 i.e. 210 :- if((mask & i) != 0){ replacestrcnf(newstring,wCindex[log2(mask)],wordConfusions[log2(mask)]);} mask = mask >> 1 ; } string newstring1 = removeSpaces(newstring.substr(1,newstring.size()-2)); size_t cntSamasNew; if(FlagLR) cntSamasNew = cntSamas(SamasRL(newstring1,Dict),partsRL); // ,SmasWords else cntSamasNew = cntSamas(SamasLR(newstring1,Dict),partsLR); // ,SmasWords //cout << cntSamasNew <<" "<< str1cnt<< endl; //Flag1stSuggGenerated :- if cnt 8 for str1 and <=8 for a suggestion then look for cnt <8 hence forth if(Flag1stSuggGenerated){if(cntSamasNew <= str1cnt) {twoOCRsugg = (newstring1); str1cnt = cntSamasNew; Flag1stSuggGenerated = 0;}} else {if(cntSamasNew < str1cnt) {twoOCRsugg = (newstring1); str1cnt = cntSamasNew;}} } //cout << toDev(twoOCRsugg)<<endl; wordConfusions.clear(); wCindex.clear(); return twoOCRsugg; //break; } string slpNPatternDict :: bestIG(string s1,string s2,map<string, int>& m1){ string s11 = s1; string s21 = s2; s1 = toslp1(s1); s2=toslp1(s2); string RL1 = SamasRL(s1,m1); string RLout1; size_t cRL1 = cntSamas(RL1,RLout1); string RL2 = SamasRL(s2,m1); string RLout2; size_t cRL2 = cntSamas(RL2,RLout2); string LR1 = SamasLR(s1,m1); string LRout1; size_t cLR1 = cntSamas(LR1,LRout1); string LR2 = SamasLR(s2,m1); string LRout2; size_t cLR2 = cntSamas(LR2,LRout2); bool lolz; if(minsize_t(cRL1,cLR1,lolz) < minsize_t(cRL2,cLR2,lolz)) return s11; else return s21; } //Sandhi Top Confusions void slpNPatternDict :: loadSandhiRules(string fileName, map<string, vector<string>>& SRules){ ifstream s(fileName); string sR1,sRl1, sRr1; while(s>>sR1) {s>>sRl1; s>>sRr1; SRules[sR1].push_back(sRl1 + " " + sRr1);} } void slpNPatternDict :: printSandhiRUles(map<string,vector<string> >& SRules){ for( map<string,vector<string> >::const_iterator ptr=SRules.begin(); ptr!=SRules.end(); ptr++) { string s = (ptr->first); cout << (s) << " -> "; for( vector<string>::const_iterator eptr=ptr->second.begin(); eptr!=ptr->second.end(); eptr++){ string s1 = *eptr; cout << (s1) << " | "; } cout << endl; } } bool slpNPatternDict :: SamasCheck(string OCRNew, map<string, int>& Dict){ if (OCRNew == "") return 1; if (Dict[OCRNew] > 0) return 1; //cout << endl<< "heres " << OCRNew << endl; size_t sz = OCRNew.size(); for(size_t ts = sz ; ts > 0; ts--){// Bapyopetam Bapy 0 4 10 string s1 = OCRNew.substr(0,ts); string rem = OCRNew.substr(ts,sz-ts); //cout << "s1 " << s1 << " rem " << rem << endl; if((Dict[s1] > 0) &&(s1.size() >3) &&(rem.size() >3))/*try && rem.size >3*/ return SamasCheck(rem,Dict); // apply ending with a to aH, ending with consonants say c to ca etc // if not 1st leftstarting with a to remove a } return 0; } bool slpNPatternDict :: SandhiCheck(string OCRNew, map<string, int>& Dict,map<string, vector<string>>& SRules){ // Sandhi Check //if (OCRNew == "") return 1; if (Dict[OCRNew] > 0) return 1; //cout << endl<< "hereS " << OCRNew << endl; size_t sz = OCRNew.size(); for(size_t ts = sz ; ts > 0; ts--){// Bapyopetam Bapy 0 4 10 string s1 = OCRNew.substr(0,ts); string rem = OCRNew.substr(ts,sz-ts); //cout << "S1 " << s1 << " " << ts << " " << sz << endl; if( (s1.size() >3)&&(rem.size() >2)){ //as r of S -> l+r will be added to rem //cout << "s1 " << s1 << endl; // applying o -> a u Sandhi rules i.e. k =1 for o, k = 2 for yu in yu -> yu -> i u | I u | size_t k = 1; vector<string> v = SRules[s1.substr(ts-k,k)]; size_t vsz = v.size(); //cout << " vsz " << vsz << endl; if(vsz > 0) { bool SandhiFlag = 0; for(size_t vt =0; vt < vsz; vt++) { istringstream s(v[vt]); string l,r; s>>l; s>>r; string s1new = s1.substr(0,s1.size()-1)+l; if((Dict[s1new] > 0) ){ //cout << "found " << s1new << endl; SandhiFlag = (SandhiFlag | SamasCheck(r+rem,Dict)); } else { SandhiFlag = (SandhiFlag | (SandhiCheck(s1new,Dict,SRules) & SamasCheck(r+rem,Dict)) | (SamasCheck(s1new,Dict) & SamasCheck(r+rem,Dict)));} //else }// for return SandhiFlag; }// if vsz >0 } } return 0; } //Sandhi rules // OCR Word = BApyopetam string slpNPatternDict :: generatePossibilitesNsuggest(string OCRWord,map<string,string>& TopConfusions,map<string,int>& TopConfusionsMask,map<string, int>& Dict, map<string, vector<string>>& SRules){ string OCRWordOrig = OCRWord; size_t sz = OCRWord.size() + 2; // one confusion one sandhi at a time size_t tSandhi = 0; for( size_t t2 =1; t2 < 4 ; t2++){ for( size_t t =0; t <sz- t2 + 1 ; t++){ OCRWord = "@" + OCRWordOrig + "#"; // apply a confusion string OCRNew = OCRWord; //cout << "OCRWord " << OCRWord << endl; size_t tc = t; while( tc < sz - t2 + 1) { string s1 = OCRWord.substr(tc,t2); //cout << s1<< " "<< tc << " " << t2 << endl; if (TopConfusionsMask[s1] > 0) { OCRNew = OCRWord; OCRNew.replace(tc,s1.size(),TopConfusions[s1]); t = tc; break; } else tc++; } //cout << "OCRWord1 " << OCRNew << endl; // apply Samas s OCRNew = OCRNew.substr(0,OCRNew.size()-1); OCRNew = OCRNew.substr(1,OCRNew.size()-1); //cout << "OCRWord2 " << OCRNew << endl; if (SamasCheck(OCRNew, Dict)) return OCRNew; // apply Sandhi S Rules if (SandhiCheck(OCRNew, Dict,SRules)) return OCRNew; } } return ""; }
41.321026
356
0.550408
ayushbits
493e6aa31a226a2337839854bbb7f925721783ea
1,602
cpp
C++
tests/DBCParserTest.cpp
aiekick/dbcppp
8f433e7b3ce5ee11aa6061ba82ba3cc4ddbbbfbe
[ "MIT" ]
93
2019-12-26T08:35:22.000Z
2022-03-29T07:30:30.000Z
tests/DBCParserTest.cpp
Raufoon/dbcppp
f6db52bbca5a2272804ccdd8e38955e5b6cd7abd
[ "MIT" ]
54
2020-02-26T23:12:09.000Z
2022-03-13T18:21:20.000Z
tests/DBCParserTest.cpp
ozzdemir/dbcppp
c7ea82b799c3dd945b399c75a6cf38fff6d61a4e
[ "MIT" ]
26
2020-02-01T00:46:10.000Z
2022-03-29T12:40:37.000Z
#include <fstream> #include <iomanip> #include <filesystem> #include "dbcppp/Network.h" #include "dbcppp/Network2Functions.h" #include "Config.h" #include "Catch2.h" TEST_CASE("DBCParserTest", "[]") { std::size_t i = 0; for (const auto& dbc_file : std::filesystem::directory_iterator(std::filesystem::path(TEST_FILES_PATH) / "dbc")) { //BOOST_TEST_CHECKPOINT("DBCParserTest: Testing file '" + dbc_file.path().string() + "'"); if (dbc_file.path().extension() != ".dbc") { continue; } std::cout << "Testing DBC grammar with file: " << dbc_file.path() << std::endl; auto dbc_file_tmp = dbc_file.path().string() + ".tmp"; std::unique_ptr<dbcppp::INetwork> spec; std::unique_ptr<dbcppp::INetwork> test; { std::ifstream dbc(dbc_file.path()); spec = dbcppp::INetwork::LoadDBCFromIs(dbc); std::ofstream tmp_dbc(dbc_file_tmp); bool open = tmp_dbc.is_open(); using namespace dbcppp::Network2DBC; tmp_dbc << std::setprecision(10); tmp_dbc << *spec << std::endl; } { std::ifstream dbc(dbc_file_tmp); test = dbcppp::INetwork::LoadDBCFromIs(dbc); REQUIRE(test); } auto error_msg = "Failed for " + std::to_string(i) + "th file ('" + dbc_file.path().string() + "')"; if (*spec != *test) { std::cout << error_msg << std::endl; } REQUIRE(*spec == *test); std::filesystem::remove(dbc_file_tmp); i++; } }
31.411765
116
0.553059
aiekick
493fd10a81981d0e507a93a416dd54a150223854
3,692
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/content/CIntentHelper.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/content/CIntentHelper.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/content/CIntentHelper.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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 "elastos/droid/content/CIntentHelper.h" #include "elastos/droid/ext/frameworkdef.h" namespace Elastos { namespace Droid { namespace Content { CAR_INTERFACE_IMPL(CIntentHelper, Singleton, IIntentHelper) CAR_SINGLETON_IMPL(CIntentHelper) ECode CIntentHelper::CreateChooser( /* [in] */ IIntent* target, /* [in] */ ICharSequence* title, /* [out] */ IIntent** intent) { VALIDATE_NOT_NULL(intent) AutoPtr<IIntent> it = Intent::CreateChooser(target, title); *intent = it; REFCOUNT_ADD(*intent) return NOERROR; } ECode CIntentHelper::MakeMainActivity( /* [in] */ IComponentName* mainActivity, /* [out] */ IIntent** intent) { VALIDATE_NOT_NULL(intent) AutoPtr<IIntent> it = Intent::MakeMainActivity(mainActivity); *intent = it; REFCOUNT_ADD(*intent) return NOERROR; } ECode CIntentHelper::MakeMainSelectorActivity( /* [in] */ const String& selectorAction, /* [in] */ const String& selectorCategory, /* [out] */ IIntent** intent) { VALIDATE_NOT_NULL(intent) AutoPtr<IIntent> it = Intent::MakeMainSelectorActivity(selectorAction, selectorCategory); *intent = it; REFCOUNT_ADD(*intent) return NOERROR; } ECode CIntentHelper::MakeRestartActivityTask( /* [in] */ IComponentName* mainActivity, /* [out] */ IIntent** intent) { VALIDATE_NOT_NULL(intent) AutoPtr<IIntent> it = Intent::MakeRestartActivityTask(mainActivity); *intent = it; REFCOUNT_ADD(*intent) return NOERROR; } ECode CIntentHelper::GetIntent( /* [in] */ const String& uri, /* [out] */ IIntent** intent) { return Intent::GetIntent(uri, intent); } ECode CIntentHelper::ParseUri( /* [in] */ const String& uri, /* [in] */ Int32 flags, /* [out] */ IIntent** intent) { return Intent::ParseUri(uri, flags, intent); } ECode CIntentHelper::GetIntentOld( /* [in] */ const String& uri, /* [out] */ IIntent** intent) { return Intent::GetIntentOld(uri, intent); } ECode CIntentHelper::ParseIntent( /* [in] */ IResources* resources, /* [in] */ IXmlPullParser* parser, /* [in] */ IAttributeSet* attrs, /* [out] */ IIntent** intent) { return Intent::ParseIntent(resources, parser, attrs, intent); } ECode CIntentHelper::RestoreFromXml( /* [in] */ IXmlPullParser* in, /* [out] */ IIntent** intent) { VALIDATE_NOT_NULL(intent) AutoPtr<IIntent> temp = Intent::RestoreFromXml(in); *intent = temp; REFCOUNT_ADD(*intent) return NOERROR; } ECode CIntentHelper::NormalizeMimeType( /* [in] */ const String& type, /* [out] */ String* mimeType) { VALIDATE_NOT_NULL(mimeType) *mimeType = Intent::NormalizeMimeType(type); return NOERROR; } ECode CIntentHelper::IsAccessUriMode( /* [in] */ Int32 modeFlags, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = Intent::IsAccessUriMode(modeFlags); return NOERROR; } } } }
26.753623
93
0.647887
jingcao80
494023c248b5d96d68510482a00fbafad820c649
19,717
cpp
C++
aby3-DB_tests/PermutaitonTests.cpp
vincehong/aby3
1a5277b37249545e967fc58a9235666a2453c104
[ "MIT" ]
121
2019-06-25T01:35:50.000Z
2022-03-24T12:53:17.000Z
aby3-DB_tests/PermutaitonTests.cpp
vincehong/aby3
1a5277b37249545e967fc58a9235666a2453c104
[ "MIT" ]
33
2020-01-21T16:47:09.000Z
2022-01-23T12:41:22.000Z
aby3-DB_tests/PermutaitonTests.cpp
vincehong/aby3
1a5277b37249545e967fc58a9235666a2453c104
[ "MIT" ]
36
2019-09-05T08:35:09.000Z
2022-01-14T11:57:22.000Z
#include <cryptoTools/Network/IOService.h> #include <cryptoTools/Network/Session.h> #include <cryptoTools/Network/Channel.h> #include <cryptoTools/Common/Matrix.h> #include <aby3-DB/OblvPermutation.h> #include <aby3-DB/OblvSwitchNet.h> #include <cryptoTools/Crypto/PRNG.h> #include "PermutaitonTests.h" #include <iomanip> using namespace oc; void Perm3p_overwrite_Test() { IOService ios; Session s01(ios, "127.0.0.1", SessionMode::Server, "01"); Session s10(ios, "127.0.0.1", SessionMode::Client, "01"); Session s02(ios, "127.0.0.1", SessionMode::Server, "02"); Session s20(ios, "127.0.0.1", SessionMode::Client, "02"); Session s12(ios, "127.0.0.1", SessionMode::Server, "12"); Session s21(ios, "127.0.0.1", SessionMode::Client, "12"); Channel chl01 = s01.addChannel(); Channel chl10 = s10.addChannel(); Channel chl02 = s02.addChannel(); Channel chl20 = s20.addChannel(); Channel chl12 = s12.addChannel(); Channel chl21 = s21.addChannel(); int rows = 1 << 16; int bytes = 16; std::vector<u32> perm(rows); for (u32 i = 0; i < perm.size(); ++i) perm[i] = i; PRNG prng(OneBlock); std::random_shuffle(perm.begin(), perm.end(), prng); Matrix<u8> mtx(rows, bytes); Matrix<u8> s1(rows, bytes); Matrix<u8> s2(rows, bytes); prng.get(mtx.data(), mtx.size()); //std::cout << std::endl; //for (u32 i = 0; i < mtx.rows(); ++i) //{ // std::cout << i << " -> " << perm[i] << " : "; // for (u32 j = 0; j < mtx.cols(); ++j) // { // std::cout << " " << std::hex << int(mtx(i, j)); // } // std::cout << std::endl; //} //auto t0 = std::thread([&]() { OblvPermutation p; auto perm2 = perm; p.program(chl02, chl01, perm2, prng, s1, "test"); }//); //std::cout << std::endl; //auto t1 = std::thread([&]() { OblvPermutation p; p.send(chl10, chl12, mtx, "test"); }//); //std::cout << std::endl; OblvPermutation p; p.recv(chl20, chl21, s2, rows, "test"); //t0.join(); //t1.join(); //std::cout << std::endl; //for (u32 i = 0; i < mtx.rows(); ++i) //{ // std::cout << i << " : "; // for (u32 j = 0; j < mtx.cols(); ++j) // { // std::cout << " " << std::hex << int(s1(i, j) ^ s2(i, j)); // } // std::cout << std::endl; //} bool failed = false; for (u32 i = 0; i < mtx.rows(); ++i) { for (u32 j = 0; j < mtx.cols(); ++j) { auto val = s1(perm[i], j) ^ s2(perm[i], j); if (mtx(i, j) != val) { std::cout << "mtx(" << i << ", " << j << ") != s1(" << perm[i] << ", " << j << ") ^ s2(" << perm[i] << ", " << j << ")" << std::endl; std::cout << " " << int(mtx(i, j)) << " != " << int(s1(perm[i], j)) << " ^ " << int(s2(perm[i], j)) << std::endl; std::cout << " " << int(mtx(i, j)) << " != " << int(s1(perm[i], j) ^ s2(perm[i], j)) << std::endl; failed = true; } } } if (failed) throw std::runtime_error(LOCATION); } void Perm3p_additive_Test() { IOService ios; Session s01(ios, "127.0.0.1", SessionMode::Server, "01"); Session s10(ios, "127.0.0.1", SessionMode::Client, "01"); Session s02(ios, "127.0.0.1", SessionMode::Server, "02"); Session s20(ios, "127.0.0.1", SessionMode::Client, "02"); Session s12(ios, "127.0.0.1", SessionMode::Server, "12"); Session s21(ios, "127.0.0.1", SessionMode::Client, "12"); Channel chl01 = s01.addChannel(); Channel chl10 = s10.addChannel(); Channel chl02 = s02.addChannel(); Channel chl20 = s20.addChannel(); Channel chl12 = s12.addChannel(); Channel chl21 = s21.addChannel(); int rows = 100; int bytes = 16; std::vector<u32> perm(rows); for (u32 i = 0; i < perm.size(); ++i) perm[i] = i; PRNG prng(OneBlock); std::random_shuffle(perm.begin(), perm.end(), prng); Matrix<u8> mtx(rows, bytes); Matrix<u8> s1(rows, bytes); Matrix<u8> s2(rows, bytes); prng.get(mtx.data(), mtx.size()); prng.get(s1.data(), s1.size()); s2 = s1; //std::cout << std::endl; //for (u32 i = 0; i < mtx.rows(); ++i) //{ // std::cout << i << " -> " << perm[i] << " : "; // for (u32 j = 0; j < mtx.cols(); ++j) // { // std::cout << " " << std::hex << int(mtx(i, j)); // } // std::cout << std::endl; //} //auto t0 = std::thread([&]() { OblvPermutation p; auto perm2 = perm; p.program(chl02, chl01, perm2, prng, s1, "test", OutputType::Additive); }//); //std::cout << std::endl; //auto t1 = std::thread([&]() { OblvPermutation p; p.send(chl10, chl12, mtx, "test"); }//); //std::cout << std::endl; OblvPermutation p; p.recv(chl20, chl21, s2, rows, "test", OutputType::Additive); //t0.join(); //t1.join(); //std::cout << std::endl; //for (u32 i = 0; i < mtx.rows(); ++i) //{ // std::cout << i << " : "; // for (u32 j = 0; j < mtx.cols(); ++j) // { // std::cout << " " << std::hex << int(s1(i, j) ^ s2(i, j)); // } // std::cout << std::endl; //} bool failed = false; for (u32 i = 0; i < mtx.rows(); ++i) { for (u32 j = 0; j < mtx.cols(); ++j) { auto val = s1(perm[i], j) ^ s2(perm[i], j); if (mtx(i, j) != val) { std::cout << "mtx(" << i << ", " << j << ") != s1(" << perm[i] << ", " << j << ") ^ s2(" << perm[i] << ", " << j << ")" << std::endl; std::cout << " " << int(mtx(i, j)) << " != " << int(s1(perm[i], j)) << " ^ " << int(s2(perm[i], j)) << std::endl; std::cout << " " << int(mtx(i, j)) << " != " << int(s1(perm[i], j) ^ s2(perm[i], j)) << std::endl; failed = true; } } } if (failed) throw std::runtime_error(LOCATION); } void Perm3p_subset_Test() { IOService ios; Session s01(ios, "127.0.0.1", SessionMode::Server, "01"); Session s10(ios, "127.0.0.1", SessionMode::Client, "01"); Session s02(ios, "127.0.0.1", SessionMode::Server, "02"); Session s20(ios, "127.0.0.1", SessionMode::Client, "02"); Session s12(ios, "127.0.0.1", SessionMode::Server, "12"); Session s21(ios, "127.0.0.1", SessionMode::Client, "12"); Channel chl01 = s01.addChannel(); Channel chl10 = s10.addChannel(); Channel chl02 = s02.addChannel(); Channel chl20 = s20.addChannel(); Channel chl12 = s12.addChannel(); Channel chl21 = s21.addChannel(); int rows = 100; int destRows = 50; int bytes = 2; std::vector<u32> perm(rows, -1); for (u32 i = 0; i < destRows; ++i) perm[i] = i; PRNG prng(OneBlock); std::random_shuffle(perm.begin(), perm.end(), prng); Matrix<u8> mtx(rows, bytes); Matrix<u8> s1(destRows, bytes); Matrix<u8> s2(destRows, bytes); prng.get(mtx.data(), mtx.size()); //std::cout << std::endl; //for (u32 i = 0; i < mtx.rows(); ++i) //{ // std::cout << i << " -> " << perm[i] << " : "; // for (u32 j = 0; j < mtx.cols(); ++j) // { // std::cout << " " << std::hex << int(mtx(i, j)); // } // std::cout << std::endl; //} //auto t0 = std::thread([&]() { OblvPermutation p; auto perm2 = perm; p.program(chl02, chl01, perm2, prng, s1, "test"); }//); //std::cout << std::endl; //auto t1 = std::thread([&]() { OblvPermutation p; p.send(chl10, chl12, mtx, "test"); }//); //std::cout << std::endl; OblvPermutation p; p.recv(chl20, chl21, s2, rows, "test"); //t0.join(); //t1.join(); //std::cout << std::endl; //for (u32 i = 0; i < mtx.rows(); ++i) //{ // std::cout << i << " : "; // for (u32 j = 0; j < mtx.cols(); ++j) // { // std::cout << " " << std::hex << int(s1(i, j) ^ s2(i, j)); // } // std::cout << std::endl; //} bool failed = false; for (u32 i = 0; i < rows; ++i) { if (perm[i] != -1) { auto s = perm[i]; for (u32 j = 0; j < bytes; ++j) { auto val = s1(s, j) ^ s2(s, j); if (mtx(i, j) != val) { std::cout << "mtx(" << i << ", " << j << ") != s1(" << s << ", " << j << ") ^ s2(" << s << ", " << j << ")" << std::endl; std::cout << " " << int(mtx(i, j)) << " != " << int(s1(s, j)) << " ^ " << int(s2(s, j)) << std::endl; std::cout << " " << int(mtx(i, j)) << " != " << int(s1(s, j) ^ s2(s, j)) << std::endl; failed = true; } } } } if (failed) throw std::runtime_error(LOCATION); } void switch_select_test() { IOService ios; Session s01(ios, "127.0.0.1", SessionMode::Server, "01"); Session s10(ios, "127.0.0.1", SessionMode::Client, "01"); Session s02(ios, "127.0.0.1", SessionMode::Server, "02"); Session s20(ios, "127.0.0.1", SessionMode::Client, "02"); Session s12(ios, "127.0.0.1", SessionMode::Server, "12"); Session s21(ios, "127.0.0.1", SessionMode::Client, "12"); Channel chl01 = s01.addChannel(); Channel chl10 = s10.addChannel(); Channel chl02 = s02.addChannel(); Channel chl20 = s20.addChannel(); Channel chl12 = s12.addChannel(); Channel chl21 = s21.addChannel(); int trials = 100; int srcSize = 40; int destSize = 20; int bytes = 1; Matrix<u8> src(srcSize, bytes); Matrix<u8> dest0(destSize, bytes), dest1(destSize, bytes); for (auto t = 9; t < trials; ++t) { PRNG prng(toBlock(t)); prng.get(src.data(), src.size()); //for (auto i = 0; i < src.rows(); ++i) //{ // std::cout << "s[" << i << "] = "; // for (auto j = 0; j < src.cols(); ++j) // { // std::cout << " " << std::setw(2) << std::hex << int(src(i, j)); // } // std::cout << std::endl << std::dec; //} OblvSwitchNet::Program prog; prog.init(srcSize, destSize); for (u64 i = 0; i < destSize; ++i) { prog.addSwitch(prng.get<u32>() % srcSize, (u32)i); //std::cout << "switch[" << i << "] = " << prog.mSrcDests[i][0] << " -> " << prog.mSrcDests[i][1] << std::endl; } auto t0 = std::thread([&]() { OblvSwitchNet snet("test"); snet.programSelect(chl02, chl01, prog, prng, dest0); }); auto t1 = std::thread([&]() { OblvSwitchNet snet("test"); snet.sendSelect(chl10, chl12, src); }); auto t2 = std::thread([&]() { OblvSwitchNet snet("test"); snet.recvSelect(chl20, chl21, dest1, srcSize); }); t0.join(); t1.join(); t2.join(); auto last = -1; bool print = false; if (print) std::cout << std::endl; bool failed = false; for (u64 i = 0; i < prog.mSrcDests.size(); ++i) { auto s = prog.mSrcDests[i].mSrc; if (s != last) { for (auto j = 0; j < bytes; ++j) { if ((dest0(i, j) ^ dest1(i, j)) != src(s, j)) { failed = true; } } if (print) { std::cout << "d[" << i << "] = "; for (auto j = 0; j < bytes; ++j) { if ((dest0(i, j) ^ dest1(i, j)) != src(s, j)) std::cout << Color::Red; std::cout << ' ' << std::setw(2) << std::hex << int(dest0(i, j) ^ dest1(i, j)) << ColorDefault; } std::cout << "\ns[" << i << "] = "; for (auto j = 0; j < bytes; ++j) std::cout << ' ' << std::setw(2) << std::hex << int(src(s, j)); std::cout << std::endl << std::dec; } last = s; } } if (failed) throw std::runtime_error(""); } } void switch_duplicate_test() { IOService ios; Session s01(ios, "127.0.0.1", SessionMode::Server, "01"); Session s10(ios, "127.0.0.1", SessionMode::Client, "01"); Session s02(ios, "127.0.0.1", SessionMode::Server, "02"); Session s20(ios, "127.0.0.1", SessionMode::Client, "02"); Session s12(ios, "127.0.0.1", SessionMode::Server, "12"); Session s21(ios, "127.0.0.1", SessionMode::Client, "12"); Channel chl01 = s01.addChannel(); Channel chl10 = s10.addChannel(); Channel chl02 = s02.addChannel(); Channel chl20 = s20.addChannel(); Channel chl12 = s12.addChannel(); Channel chl21 = s21.addChannel(); int trials = 100; int srcSize = 50; int destSize = srcSize /2; int bytes = 1; Matrix<u8> src(srcSize, bytes); Matrix<u8> dest0(destSize, bytes), dest1(destSize, bytes); for (auto t = 0; t < trials; ++t) { PRNG prng(toBlock(t)); prng.get(src.data(), src.size()); //for (auto i = 0; i < src.rows(); ++i) //{ // std::cout << "s[" << i << "] = "; // for (auto j = 0; j < src.cols(); ++j) // { // std::cout << " " << std::setw(2) << std::hex << int(src(i, j)); // } // std::cout << std::endl << std::dec; //} OblvSwitchNet::Program prog; prog.init(srcSize, destSize); for (u64 i = 0; i < destSize; ++i) { prog.addSwitch(prng.get<u32>() % srcSize, (u32)i); //prog.addSwitch(0, i); //std::cout << "switch[" << i << "] = " << prog.mSrcDests[i][0] << " -> " << prog.mSrcDests[i][1] << std::endl; } auto t0 = std::thread([&]() { setThreadName("t0"); OblvSwitchNet snet("test"); snet.programSelect(chl02, chl01, prog, prng, dest0); snet.programDuplicate(chl02, chl01, prog, prng, dest0); }); auto t1 = std::thread([&]() { setThreadName("t1"); OblvSwitchNet snet("test"); snet.sendSelect(chl10, chl12, src); snet.helpDuplicate(chl10, destSize, bytes); }); auto t2 = std::thread([&]() { setThreadName("t2"); OblvSwitchNet snet("test"); snet.recvSelect(chl20, chl21, dest1, srcSize); PRNG prng2(toBlock(585643)); snet.sendDuplicate(chl20, prng2, dest1); }); t0.join(); t1.join(); t2.join(); bool print = false; if (print) std::cout << std::endl; bool failed = false; for (u64 i = 0; i < prog.mSrcDests.size(); ++i) { auto s = prog.mSrcDests[i].mSrc; for (auto j = 0; j < bytes; ++j) { if ((dest0(i, j) ^ dest1(i, j)) != src(s, j)) { failed = true; } } if (print) { std::cout << "d[" << i << "] = "; for (auto j = 0; j < bytes; ++j) { if ((dest0(i, j) ^ dest1(i, j)) != src(s, j)) std::cout << Color::Red; std::cout << ' ' << std::setw(2) << std::hex << int(dest0(i, j) ^ dest1(i, j)) << ColorDefault; } std::cout << "\ns[" << i << "] = "; for (auto j = 0; j < bytes; ++j) std::cout << ' ' << std::setw(2) << std::hex << int(src(s, j)); std::cout << std::endl << std::dec; } } if (failed) throw std::runtime_error(""); } } void switch_full_test() { IOService ios; Session s01(ios, "127.0.0.1", SessionMode::Server, "01"); Session s10(ios, "127.0.0.1", SessionMode::Client, "01"); Session s02(ios, "127.0.0.1", SessionMode::Server, "02"); Session s20(ios, "127.0.0.1", SessionMode::Client, "02"); Session s12(ios, "127.0.0.1", SessionMode::Server, "12"); Session s21(ios, "127.0.0.1", SessionMode::Client, "12"); Channel chl01 = s01.addChannel(); Channel chl10 = s10.addChannel(); Channel chl02 = s02.addChannel(); Channel chl20 = s20.addChannel(); Channel chl12 = s12.addChannel(); Channel chl21 = s21.addChannel(); int trials = 100; int srcSize = 50; int destSize = srcSize / 2; int bytes = 1; Matrix<u8> src(srcSize, bytes); Matrix<u8> dest0(destSize, bytes), dest1(destSize, bytes); for (auto t = 0; t < trials; ++t) { PRNG prng(toBlock(t)); prng.get(src.data(), src.size()); //for (auto i = 0; i < src.rows(); ++i) //{ // std::cout << "s[" << i << "] = "; // for (auto j = 0; j < src.cols(); ++j) // { // std::cout << " " << std::setw(2) << std::hex << int(src(i, j)); // } // std::cout << std::endl << std::dec; //} OblvSwitchNet::Program prog; prog.init(srcSize, destSize); for (u64 i = 0; i < destSize; ++i) { prog.addSwitch(prng.get<u32>() % srcSize, (u32)i); //prog.addSwitch(0, i); //std::cout << "switch[" << i << "] = " << prog.mSrcDests[i][0] << " -> " << prog.mSrcDests[i][1] << std::endl; } auto t0 = std::thread([&]() { setThreadName("t0"); OblvSwitchNet snet("test"); snet.program(chl02, chl01, prog, prng, dest0); }); auto t1 = std::thread([&]() { setThreadName("t1"); OblvSwitchNet snet("test"); snet.sendRecv(chl10, chl12, src, dest1); }); auto t2 = std::thread([&]() { setThreadName("t2"); OblvSwitchNet snet("test"); PRNG prng2(toBlock(44444)); snet.help(chl20, chl21, prng2, destSize, srcSize, bytes); }); t0.join(); t1.join(); t2.join(); bool print = false; if (print) std::cout << std::endl; bool failed = false; for (u64 i = 0; i < prog.mSrcDests.size(); ++i) { auto s = prog.mSrcDests[i].mSrc; auto d = prog.mSrcDests[i].mDest; for (auto j = 0; j < bytes; ++j) { if ((dest0(d, j) ^ dest1(d, j)) != src(s, j)) { failed = true; } } if (print) { std::cout << "d[" << d << "] = "; for (auto j = 0; j < bytes; ++j) { if ((dest0(d, j) ^ dest1(d, j)) != src(s, j)) std::cout << Color::Red; std::cout << ' ' << std::setw(2) << std::hex << int(dest0(i, j) ^ dest1(i, j)) << ColorDefault; } std::cout << "\ns[" << s << "] = "; for (auto j = 0; j < bytes; ++j) std::cout << ' ' << std::setw(2) << std::hex << int(src(s, j)); std::cout << std::endl << std::dec; } } if (failed) throw std::runtime_error(""); } }
28.95301
149
0.4417
vincehong
4940c95479a0bf4cba16f33b2ea42b63ea8fff66
484
cpp
C++
mod04/ex03/Ice.cpp
paozer/piscine_cpp
449d4a60b3c50c7ba6d94e38a7b632b5f447a438
[ "Unlicense" ]
null
null
null
mod04/ex03/Ice.cpp
paozer/piscine_cpp
449d4a60b3c50c7ba6d94e38a7b632b5f447a438
[ "Unlicense" ]
null
null
null
mod04/ex03/Ice.cpp
paozer/piscine_cpp
449d4a60b3c50c7ba6d94e38a7b632b5f447a438
[ "Unlicense" ]
2
2021-01-31T13:52:11.000Z
2021-05-19T18:36:17.000Z
#include "Ice.hpp" /* CONSTRUCTION DESTRUCTION */ Ice::Ice() : AMateria("ice") {} Ice::~Ice() {} Ice::Ice(const Ice& other) : AMateria("ice") { *this = other; } Ice& Ice::operator=(const Ice& other) { AMateria::operator=(other); return *this; } /* MEMBER FUNCTIONS */ void Ice::use(ICharacter& target) { AMateria::use(target); std::cout << "* shoots an ice bolt at " << target.getName() << " *" << std::endl; } AMateria* Ice::clone() const { return new Ice(); }
20.166667
85
0.60124
paozer
4942e2b43f35c35e90cd20df07c2e4609f1c64b5
571
hpp
C++
Labs/AI/TicTacToe/src/SuperHeader.hpp
jadnohra/jad-pre-2015-dabblings
368cbd39c6371b3e48b0c67d9a83fc20eee41346
[ "MIT" ]
null
null
null
Labs/AI/TicTacToe/src/SuperHeader.hpp
jadnohra/jad-pre-2015-dabblings
368cbd39c6371b3e48b0c67d9a83fc20eee41346
[ "MIT" ]
null
null
null
Labs/AI/TicTacToe/src/SuperHeader.hpp
jadnohra/jad-pre-2015-dabblings
368cbd39c6371b3e48b0c67d9a83fc20eee41346
[ "MIT" ]
null
null
null
#ifndef __SuperHeader_hpp #define __SuperHeader_hpp #include <stdlib.h> #include <tchar.h> #include <assert.h> #include <algorithm> #define NOMINMAX #ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later. #define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. #endif #include "windows.h" #ifdef _DEBUG inline void softAssert(bool cond) { if (!cond) DebugBreak(); } #else inline void softAssert(bool cond) { } #endif #endif
16.794118
105
0.66725
jadnohra
494363cf5e51c77fae1c46c961b84dfed7424c3c
2,230
hpp
C++
include/Aether/Screen.hpp
NightYoshi370/Aether
87d2b81f5d3143e39c363a9c81c195d440d7a4e8
[ "MIT" ]
1
2021-02-04T07:27:46.000Z
2021-02-04T07:27:46.000Z
libs/Aether/include/Aether/Screen.hpp
tkgstrator/SeedHack
227566d993bdea7a2851a8fc664b539186509697
[ "MIT" ]
null
null
null
libs/Aether/include/Aether/Screen.hpp
tkgstrator/SeedHack
227566d993bdea7a2851a8fc664b539186509697
[ "MIT" ]
null
null
null
#ifndef AETHER_SCREEN_HPP #define AETHER_SCREEN_HPP #include "Aether/base/Container.hpp" #include <unordered_map> namespace Aether { /** * @brief A class that represents a screen layout * Stores all screen elements for a specific screen. */ class Screen : public Container { private: /** @brief Mappings for button presses to callback functions */ std::unordered_map<Button, std::function<void()> > pressFuncs; /** @brief Mappings for button releases to callback functions */ std::unordered_map<Button, std::function<void()> > releaseFuncs; public: /** * @brief Construct a new Screen object */ Screen(); /** * @brief Callback function when the screen is loaded */ virtual void onLoad(); /** * @brief Callback function when the screen is unloaded */ virtual void onUnload(); /** * @brief Assigns callback function for button press * @note Setting a button callback will block the event from * going to any other elements * * @param btn button to assign callback to * @param func function to assign as callback for button press */ void onButtonPress(Button btn, std::function<void()> func); /** * @brief Assigns callback function for button release * @note Setting a button callback will block the event from * going to any other elements * * @param btn button to assign callback to * @param func function to assign as callback for button release */ void onButtonRelease(Button btn, std::function<void()> func); /** * @brief Attempt event handling for an event that occured * * @param event event to handle * @return true if event was handled * @return false if event was not handled */ bool handleEvent(InputEvent *event); }; }; #endif
33.283582
76
0.54843
NightYoshi370
4948220c7d9e62f081bb794035cc497751a9a6c2
1,338
cpp
C++
main/choose-and-swap/choose-and-swap.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/choose-and-swap/choose-and-swap.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/choose-and-swap/choose-and-swap.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
#include <iostream> #include <string> #include <unordered_set> namespace { bool get_swappable_chars(const std::string& s, char& high, char& low) { constexpr auto none = '\0'; high = low = none; if (s.size() < 2u) return true; const auto istop = s.size() - 1u; std::unordered_set<char> noswap; for (std::string::size_type i {0u}; i != istop; ++i) { if (noswap.find(s[i]) != noswap.end()) continue; for (auto j = i; ++j != s.size(); ) { if (s[i] > s[j] && noswap.find(s[j]) == noswap.end() && (s[j] < low || low == none)) low = s[j]; } if (low != none) { high = s[i]; return true; } noswap.insert(s[i]); } return false; } void swap_chars(std::string& s, const char first, const char second) { for (char& c : s) { if (c == first) c = second; else if (c == second) c = first; } } } int main() { auto t = 0; for (std::cin >> t; t > 0; --t) { std::string s; std::cin >> s; char high, low; if (get_swappable_chars(s, high, low)) swap_chars(s, high, low); std::cout << s << '\n'; } }
23.892857
73
0.434978
EliahKagan
4948f63c5fa04d8ea292d283e330409a91d25e3a
1,360
hpp
C++
inc/sexpr-ident.hpp
ryanvbissell/dslang
65379ca7bbefff0161d11343b742ac58452d37e7
[ "BSD-2-Clause" ]
null
null
null
inc/sexpr-ident.hpp
ryanvbissell/dslang
65379ca7bbefff0161d11343b742ac58452d37e7
[ "BSD-2-Clause" ]
null
null
null
inc/sexpr-ident.hpp
ryanvbissell/dslang
65379ca7bbefff0161d11343b742ac58452d37e7
[ "BSD-2-Clause" ]
null
null
null
// vim: set tabstop=2 softtabstop=2 shiftwidth=2 expandtab : /* * Copyright (c) 2014-2017, Ryan V. Bissell * All rights reserved. * * SPDX-License-Identifier: BSD-2-Clause * See the enclosed "LICENSE" file for exact license terms. */ #ifndef DSLANG_SEXPR_IDENT_HPP #define DSLANG_SEXPR_IDENT_HPP #include "sexpr.hpp" #include <string> namespace DSL { class Dialect; namespace detail { class SexprIdent CX_FINAL : public Sexpr { friend class CX::IntrusivePtr<SexprIdent>; public: SexprIdent(Context* sc, char const** input); std::string Write() const; /* static bool Match(Dialect const& dialect, char const* text); static Sexpr::Type Skip(Dialect const& dialect, char const** input); static SEXPR Parse(Dialect const& dialect, char const** input); */ protected: Type type() const override { return Sexpr::Type::IDENT; } Sexpr const* transmute(char const** input) const override; Sexpr const* eval(SexprEnv const* env) const override; private: std::string name_; virtual ~SexprIdent(); }; bool SexprIdent__Match(char const* text); Sexpr::Type SexprIdent__Skip(char const** input); Sexpr const* SexprIdent__Parse(Context* sc, char const** input); } // namespace detail using SexprIDENT = CX::IntrusivePtr<detail::SexprIdent>; } // namespace DSL #endif // DSLANG_SEXPR_IDENT_HPP
21.935484
72
0.710294
ryanvbissell
494fb36c2c886326770309f15d09cb54105344e4
1,363
cpp
C++
C++(Adv_CompSci)/AdvCompSci/quiz2nd6weeks.cpp
zacswolf/CompSciProjects
9dc8ff4969d852d6c649c427032e16f068003658
[ "MIT" ]
1
2016-09-12T16:10:12.000Z
2016-09-12T16:10:12.000Z
C++(Adv_CompSci)/AdvCompSci/quiz2nd6weeks.cpp
zaccool30/CompSciProjects
9dc8ff4969d852d6c649c427032e16f068003658
[ "MIT" ]
null
null
null
C++(Adv_CompSci)/AdvCompSci/quiz2nd6weeks.cpp
zaccool30/CompSciProjects
9dc8ff4969d852d6c649c427032e16f068003658
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <stdlib.h> using namespace std; class Manufacturer{ public: Manufacturer() { cout<< "E \n"; } Manufacturer(char code) { cout<< "D " << code << endl; } }; class LCDPanel: public Manufacturer{ public: LCDPanel(): Manufacturer('F') { cout<< "C \n"; } }; class Backlight: public Manufacturer{ public: Backlight() { Manufacturer('G'); cout << "B \n"; } }; class Display: public Backlight, public LCDPanel{ public: Display() : Backlight(){ cout << "A \n"; } }; class Record{ public: int value; }; class Rock { int hardness; int size; public: Rock() { cout << "Rock contructed" << endl; } }; int main(){ int a [] = { 16, 2, 77, 40, 12071 }; int a_length = sizeof(a) / sizeof(int); //cout << a_length << endl; int foo[] = {2, 4, 6, 8, 10}; int length = 4; for (int i=0; i <= length; i++){ //cout << i << " " << endl; } //Display h; Record** rec = new Record*[10]; for(int i=0; i< 10; i++) { rec[i] = new Record(); rec[i]->value = 0; } for (int i=0; i < 10; i++){ delete rec[i]; } delete[] rec; Rock stone; Rock *boulder; boulder = new Rock(); return 0; }
13.362745
50
0.487161
zacswolf
4953016766edc08efab4acd6241229c0075c519d
3,474
cpp
C++
depends/acransac/conditioning.cpp
mmrwizard/RenderMatch-1
a427138e6823675eaa76c693bc31a28566b4dcd8
[ "MIT" ]
null
null
null
depends/acransac/conditioning.cpp
mmrwizard/RenderMatch-1
a427138e6823675eaa76c693bc31a28566b4dcd8
[ "MIT" ]
null
null
null
depends/acransac/conditioning.cpp
mmrwizard/RenderMatch-1
a427138e6823675eaa76c693bc31a28566b4dcd8
[ "MIT" ]
1
2020-05-12T08:19:14.000Z
2020-05-12T08:19:14.000Z
// Copyright (c) 2010 libmv authors. // // 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. // Copyright (c) 2012, 2013 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "conditioning.hpp" namespace openMVG { // HZ 4.4.4 pag.109 void PreconditionerFromPoints(const Mat &points, Mat3 *T) { Vec mean, variance; MeanAndVarianceAlongRows(points, &mean, &variance); double xfactor = sqrt(2.0 / variance(0)); double yfactor = sqrt(2.0 / variance(1)); // If variance is equal to 0.0 set scaling factor to identity. // -> Else it will provide nan value (because division by 0). if (variance(0) < 1e-8) xfactor = mean(0) = 1.0; if (variance(1) < 1e-8) yfactor = mean(1) = 1.0; *T << xfactor, 0, -xfactor * mean(0), 0, yfactor, -yfactor * mean(1), 0, 0, 1; } void PreconditionerFromPoints(int width, int height, Mat3 *T) { // Build the normalization matrix double dNorm = 1.0 / sqrt(static_cast<double>(width * height)); (*T) = Mat3::Identity(); (*T)(0, 0) = (*T)(1, 1) = dNorm; (*T)(0, 2) = -.5f * width * dNorm; (*T)(1, 2) = -.5 * height * dNorm; } void ApplyTransformationToPoints(const Mat &points, const Mat3 &T, Mat *transformed_points) { const Mat::Index n = points.cols(); transformed_points->resize(2, n); for (Mat::Index i = 0; i < n; ++i) { Vec3 in, out; in << points(0, i), points(1, i), 1; out = T * in; (*transformed_points)(0, i) = out(0) / out(2); (*transformed_points)(1, i) = out(1) / out(2); } } void NormalizePoints(const Mat &points, Mat *normalized_points, Mat3 *T, int width, int height) { PreconditionerFromPoints(width, height, T); ApplyTransformationToPoints(points, *T, normalized_points); } void NormalizePoints(const Mat &points, Mat *normalized_points, Mat3 *T) { PreconditionerFromPoints(points, T); ApplyTransformationToPoints(points, *T, normalized_points); } // Denormalize the results. See HZ page 109. void UnnormalizerT::Unnormalize(const Mat3 &T1, const Mat3 &T2, Mat3 *H) { *H = T2.transpose() * (*H) * T1; } // Denormalize the results. See HZ page 109. void UnnormalizerI::Unnormalize(const Mat3 &T1, const Mat3 &T2, Mat3 *H) { *H = T2.inverse() * (*H) * T1; } } // namespace openMVG
39.477273
109
0.678181
mmrwizard
4953051a9c59971d6ec2529ea8a90a8789ebb2eb
5,339
cpp
C++
src/utils.cpp
molendijk/InfoClock
98719495800cd930d51c495e83b08ddf9b99fc5b
[ "MIT" ]
null
null
null
src/utils.cpp
molendijk/InfoClock
98719495800cd930d51c495e83b08ddf9b99fc5b
[ "MIT" ]
null
null
null
src/utils.cpp
molendijk/InfoClock
98719495800cd930d51c495e83b08ddf9b99fc5b
[ "MIT" ]
null
null
null
/* * utils.cpp * * Created on: 04.01.2017 * Author: Bartosz Bielawski */ #include <time.h> #include <stdio.h> #include <vector> #include <memory> #include "utils.h" #include "config.h" #include "Client.h" #include "Arduino.h" #include "FS.h" #include "DataStore.h" #include "WiFiUdp.h" #include "SyslogSender.h" #include "ESP8266WiFi.h" #include "tasks_utils.h" #include "LambdaTask.hpp" extern "C" { #include "user_interface.h" } uint16_t operator"" _s(long double seconds) {return seconds * 1000 / MS_PER_CYCLE;} uint16_t operator"" _s(unsigned long long int seconds) {return seconds * 1000 / MS_PER_CYCLE;} static char dateTimeBuffer[] = "1970-01-01T00:00:00"; static uint32_t startUpTime = 0; uint32_t getUpTime() { return time(nullptr) - startUpTime; } String getTime() { time_t now = time(nullptr); if (now == 0) { return "??:??:??"; } //this saves the first timestamp when it was nonzero (it's near start-up time) if (startUpTime == 0) { startUpTime = now; } String r; char localBuffer[10]; auto lt = localtime(&now); snprintf(localBuffer, sizeof(localBuffer), "%02d:%02d:%02d", lt->tm_hour, lt->tm_min, lt->tm_sec); r = localBuffer; return r; } static const std::vector<const char*> dayNames{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; //static const std::vector<const char*> dayNames{"Nd", "Pn", "Wt", "Sr", "Cz", "Pt", "Sb"}; String getDate() { time_t now = time(nullptr); String r; if (now == 0) { return r; } char localBuffer[20]; auto lt = localtime(&now); snprintf(localBuffer, sizeof(localBuffer), "%s %02d/%02d", dayNames[lt->tm_wday], lt->tm_mday, lt->tm_mon+1); r = localBuffer; return r; } static time_t previousDateTime = 0; const char* getDateTime() { time_t now = time(nullptr); if (now == previousDateTime) return dateTimeBuffer; auto lt = localtime(&now); snprintf(dateTimeBuffer, 32, "%04d-%02d-%02dT%02d:%02d:%02d", lt->tm_year-100+2000, lt->tm_mon+1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec); previousDateTime = now; return dateTimeBuffer; } const static char UUID_FORMAT[] PROGMEM = "%08x-%04x-4%03x-8%03x-%04x%08x"; static char UUID[36]; const char* generateRandomUUID() { uint32_t r1 = os_random(); uint32_t r2 = os_random(); uint32_t r3 = os_random(); uint32_t r4 = os_random(); sprintf_P(UUID, UUID_FORMAT, r1, r2 >> 16, r2 & 0xFFF, r3 >> 20, r3 & 0xFFFF, r4); return UUID; } void logPPrintf(char* format, ...) { char localBuffer[256]; va_list argList; va_start(argList, format); Serial.printf("%s-%09u - ", getDateTime(), ESP.getCycleCount()); vsnprintf(localBuffer, sizeof(localBuffer), format, argList); Serial.println(localBuffer); va_end(argList); } void logPrintfX(const String& app, const String& format, ...) { char localBuffer[256]; String a(app); va_list argList; va_start(argList, format); uint32_t bytes = snprintf(localBuffer, sizeof(localBuffer), "%s - %s: ", getDateTime(), a.c_str()); vsnprintf(localBuffer+bytes, sizeof(localBuffer)-bytes, format.c_str(), argList); Serial.println(localBuffer); syslogSend(app, localBuffer+bytes); va_end(argList); } bool checkFileSystem() { bool alreadyFormatted = SPIFFS.begin(); if (not alreadyFormatted) SPIFFS.format(); SPIFFS.end(); return alreadyFormatted; } void readConfigFromFlash() { SPIFFS.begin(); auto dir = SPIFFS.openDir(F("/config")); while (dir.next()) { auto f = dir.openFile("r"); auto value = f.readStringUntil('\n'); //skip the /config/ part of the path auto name = dir.fileName().substring(8); DataStore::value(name) = value; //logPrintf(F("RCFF: %s = %s"), name.c_str(), value.c_str()); } } String readConfigWithDefault(const String& name, const String& def) { auto v = readConfig(name); return v.length() != 0 ? v: def; } String readConfig(const String& name) { static bool once = true; if (once) { readConfigFromFlash(); once = false; } return DataStore::value(name); } void writeConfig(const String& name, const String& value) { auto f = SPIFFS.open(String(F("/config/")) +name, "w+"); f.print(value); f.print('\n'); f.close(); DataStore::value(name) = value; } int32_t getTimeZone() { return readConfig("timezone").toInt(); } int32_t timezone = 0; static const char uptimeFormat[] PROGMEM = "%dd%dh%dm%ds"; String dataSource(const char* name) { String result; if (DataStore::hasValue(name)) { result = DataStore::value(name); if (result) return result; } if (strcmp(name, "heap") == 0) return String(ESP.getFreeHeap()) + " B"; if (strcmp(name, "version") == 0) return versionString; if (strcmp(name, "essid") == 0) return WiFi.SSID(); if (strcmp(name, "mac") == 0) return WiFi.macAddress(); if (strcmp(name, "uptime") == 0) { uint32_t ut = getUpTime(); uint32_t d = ut / (24 * 3600); ut -= d * 24 * 3600; uint32_t h = ut / 3600; ut -= h * 3600; uint32_t m = ut / 60; ut -= m * 60; uint32_t s = ut; char buf[64]; snprintf_P(buf, sizeof(buf), uptimeFormat, d, h, m, s); return String(buf); } return "?"; } void rebootClock() { getDisplayTask().pushMessage("Rebooting...", 5_s, false); logPrintfX(F("WS"), F("Rebooting in 5 seconds...")); LambdaTask* lt = new LambdaTask([](){ESP.restart();}); addTask(lt, TaskDescriptor::ENABLED); lt->sleep(5_s); }
19.067857
100
0.65649
molendijk
495489fcb847b90b12ad90cef1f5bc51d903b3c3
691
cpp
C++
test/unit/api/terminal.cpp
jfalcou/nucog
186808bec04af4f1138bc5362510fffbe690fdd3
[ "MIT" ]
1
2022-02-13T20:11:06.000Z
2022-02-13T20:11:06.000Z
test/unit/api/terminal.cpp
jfalcou/nucog
186808bec04af4f1138bc5362510fffbe690fdd3
[ "MIT" ]
null
null
null
test/unit/api/terminal.cpp
jfalcou/nucog
186808bec04af4f1138bc5362510fffbe690fdd3
[ "MIT" ]
null
null
null
//================================================================================================== /** NuCoG - Numerical Code Generator Copyright : NuCoG Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #include "test.hpp" #include <nucog/expr/terminal.hpp> TTS_CASE( "Check terminal properties" ) { using namespace nucog::literal; auto s1 = $(x_); TTS_EQUAL( s1.arity(), 0 ); TTS_EQUAL( s1.tag() , nucog::tags::terminal_{} ); TTS_EQUAL( s1.value(), "x_"_sym ); TTS_EQUAL( s1.value().str(), "x_" ); }
31.409091
100
0.413893
jfalcou
495848907d3023ec87db4db2dde46671f499404e
3,311
cpp
C++
src/chess/Loc.cpp
owengage/chess
777ba282c66ce750a1f1604483b14a99b0122eba
[ "Unlicense" ]
null
null
null
src/chess/Loc.cpp
owengage/chess
777ba282c66ce750a1f1604483b14a99b0122eba
[ "Unlicense" ]
null
null
null
src/chess/Loc.cpp
owengage/chess
777ba282c66ce750a1f1604483b14a99b0122eba
[ "Unlicense" ]
null
null
null
#include <chess/Loc.h> #include <perf/StackVector.h> #include <unordered_map> using chess::LocInvalid; using chess::Loc; using chess::Sign; namespace { std::vector<Loc> create_all_locs() { std::vector<Loc> all; all.reserve(static_cast<std::size_t>(Loc::board_size)); for (int y = 0; y < Loc::side_size; ++y) { for (int x = 0; x < Loc::side_size; ++x) { all.emplace_back(x, y); } } return all; } perf::StackVector<Loc, Loc::side_size> generate_direction(Loc origin, Sign x, Sign y) { auto locs = perf::StackVector<Loc, 8>{}; auto sign_to_hops = [](Sign sign, int start) { switch (sign) { case Sign::positive: return Loc::side_size - 1 - start; case Sign::none: return Loc::side_size - 1; case Sign::negative: return start; } }; auto max_hops_x = sign_to_hops(x, origin.x()); auto max_hops_y = sign_to_hops(y, origin.y()); auto max_hops = std::min(max_hops_x, max_hops_y); auto hop = static_cast<int>(y)*Loc::side_size + static_cast<int>(x); auto current = origin.index(); for (int i = 0; i < max_hops; ++i) { current += hop; locs.push_back(Loc{current}); } return locs; } std::size_t direction_lookup_index(Loc loc, Sign x, Sign y) { auto loc_part = loc.index() << 4; auto x_part = (static_cast<int>(x) + 1) << 2; auto y_part = (static_cast<int>(y) + 1); return loc_part | x_part | y_part; } static constexpr std::size_t direction_lookup_size = (64 << 4) + (2 << 2) + 2 + 1; std::array<perf::StackVector<Loc, 8>, direction_lookup_size> generate_direction_lookup_map() { std::array<perf::StackVector<Loc, 8>, direction_lookup_size> map; std::array<Sign, 3> signs = {Sign::positive, Sign::none, Sign::negative}; for (auto loc : Loc::all_squares()) { for (auto x : signs) { for (auto y : signs) { auto key = direction_lookup_index(loc, x, y); auto value = generate_direction(loc, x, y); map[key] = value; } } } return map; } auto direction_lookup = generate_direction_lookup_map(); } LocInvalid::LocInvalid(int x, int y) : std::runtime_error{"Invalid Loc m_x=" + std::to_string(x) + ", y=" + std::to_string(y)} {} std::vector<Loc> Loc::row(int y) { std::vector<Loc> locs; locs.reserve(side_size); for (int i = 0; i < side_size; ++i) { locs.emplace_back(i, y); } return locs; } std::vector<Loc> const& Loc::all_squares() { static std::vector<Loc> all = create_all_locs(); return all; } perf::StackVector<Loc, Loc::side_size> Loc::direction(Loc origin, Sign x, Sign y) { return direction_lookup[direction_lookup_index(origin, x, y)]; } bool chess::operator==(Loc lhs, Loc rhs) { return lhs.m_index == rhs.m_index; } bool chess::operator!=(Loc lhs, Loc rhs) { return !(lhs == rhs); }
26.488
126
0.536998
owengage
4958a96e54b627eab4400680cdac314ae51a30c0
9,803
cpp
C++
src/stellar/stellar.arg_parser.cpp
marehr/dream_stellar
03ffc33cba4336d585108a22c8e166d0fbd7ac4b
[ "BSD-3-Clause" ]
null
null
null
src/stellar/stellar.arg_parser.cpp
marehr/dream_stellar
03ffc33cba4336d585108a22c8e166d0fbd7ac4b
[ "BSD-3-Clause" ]
16
2021-11-12T16:42:35.000Z
2022-01-11T15:28:23.000Z
src/stellar/stellar.arg_parser.cpp
marehr/dream_stellar
03ffc33cba4336d585108a22c8e166d0fbd7ac4b
[ "BSD-3-Clause" ]
null
null
null
#include <stellar/app/stellar.arg_parser.hpp> #include <seqan/seq_io.h> namespace stellar { namespace app { /////////////////////////////////////////////////////////////////////////////// // Parses options from command line parser and writes them into options object ArgumentParser::ParseResult _parseOptions(ArgumentParser const & parser, StellarOptions & options) { getArgumentValue(options.databaseFile, parser, 0); getArgumentValue(options.queryFile, parser, 1); // output options getOptionValue(options.outputFile, parser, "out"); getOptionValue(options.disabledQueriesFile, parser, "outDisabled"); getOptionValue(options.noRT, parser, "no-rt"); CharString tmp = options.outputFile; toLower(tmp); if (endsWith(tmp, ".gff")) options.outputFormat = "gff"; else if (endsWith(tmp, ".txt")) options.outputFormat = "txt"; // main options getOptionValue(options.qGram, parser, "kmer"); getOptionValue(options.minLength, parser, "minLength"); getOptionValue(options.epsilon, parser, "epsilon"); getOptionValue(options.xDrop, parser, "xDrop"); getOptionValue(options.alphabet, parser, "alphabet"); getOptionValue(options.threadCount, parser, "threads"); if (isSet(parser, "forward") && !isSet(parser, "reverse")) options.reverse = false; if (!isSet(parser, "forward") && isSet(parser, "reverse")) options.forward = false; CharString verificationMethod; getOptionValue(verificationMethod, parser, "verification"); if (verificationMethod == to_string(StellarVerificationMethod{AllLocal{}})) options.verificationMethod = StellarVerificationMethod{AllLocal{}}; else if (verificationMethod == to_string(StellarVerificationMethod{BestLocal{}})) options.verificationMethod = StellarVerificationMethod{BestLocal{}}; else if (verificationMethod == to_string(StellarVerificationMethod{BandedGlobal{}})) options.verificationMethod = StellarVerificationMethod{BandedGlobal{}}; else if (verificationMethod == to_string(StellarVerificationMethod{BandedGlobalExtend{}})) options.verificationMethod = StellarVerificationMethod{BandedGlobalExtend{}}; else { std::cerr << "Invalid parameter value: Please choose one of the --verification={exact, bestLocal, bandedGlobal, bandedGlobalExtend}" << std::endl; return ArgumentParser::PARSE_ERROR; } getOptionValue(options.disableThresh, parser, "disableThresh"); getOptionValue(options.numMatches, parser, "numMatches"); getOptionValue(options.compactThresh, parser, "sortThresh"); getOptionValue(options.maxRepeatPeriod, parser, "repeatPeriod"); getOptionValue(options.minRepeatLength, parser, "repeatLength"); getOptionValue(options.qgramAbundanceCut, parser, "abundanceCut"); getOptionValue(options.verbose, parser, "verbose"); if (isSet(parser, "kmer") && options.qGram >= 1 / options.epsilon) { std::cerr << "Invalid parameter value: Please choose q-gram length lower than 1/epsilon." << std::endl; return ArgumentParser::PARSE_ERROR; } if (options.numMatches > options.compactThresh) { std::cerr << "Invalid parameter values: Please choose numMatches <= sortThresh." << std::endl; return ArgumentParser::PARSE_ERROR; } return ArgumentParser::PARSE_OK; } /////////////////////////////////////////////////////////////////////////////// // Set-Up of Argument Parser void _setParser(ArgumentParser & parser) { setShortDescription(parser, "the SwifT Exact LocaL AligneR"); setDate(parser, SEQAN_DATE); setVersion(parser, SEQAN_APP_VERSION " [" SEQAN_REVISION "]"); setCategory(parser, "Local Alignment"); addUsageLine(parser, "[\\fIOPTIONS\\fP] <\\fIFASTA FILE 1\\fP> <\\fIFASTA FILE 2\\fP>"); addDescription(parser, "STELLAR implements the SWIFT filter algorithm (Rasmussen et al., 2006) " "and a verification step for the SWIFT hits that applies local alignment, " "gapped X-drop extension, and extraction of the longest epsilon-match."); addDescription(parser, "Input to STELLAR are two files, each containing one or more sequences " "in FASTA format. Each sequence from file 1 will be compared to each " "sequence in file 2. The sequences from file 1 are used as database, the " "sequences from file 2 as queries."); addDescription(parser, "(c) 2010-2012 by Birte Kehr"); addArgument(parser, ArgParseArgument(ArgParseArgument::INPUT_FILE, "FASTA FILE 1")); setValidValues(parser, 0, "fa fasta"); // allow only fasta files as input addArgument(parser, ArgParseArgument(ArgParseArgument::INPUT_FILE, "FASTA FILE 2")); setValidValues(parser, 1, "fa fasta"); // allow only fasta files as input // Add threads option. addOption(parser, ArgParseOption("t", "threads", "Specify the number of threads to use.", ArgParseOption::INTEGER)); setMinValue(parser, "threads", "1"); setDefaultValue(parser, "threads", "1"); addSection(parser, "Main Options"); addOption(parser, ArgParseOption("e", "epsilon", "Maximal error rate (max 0.25).", ArgParseArgument::DOUBLE)); setDefaultValue(parser, "e", "0.05"); setMinValue(parser, "e", "0.0000001"); setMaxValue(parser, "e", "0.25"); addOption(parser, ArgParseOption("l", "minLength", "Minimal length of epsilon-matches.", ArgParseArgument::INTEGER)); setDefaultValue(parser, "l", "100"); setMinValue(parser, "l", "0"); addOption(parser, ArgParseOption("f", "forward", "Search only in forward strand of database.")); addOption(parser, ArgParseOption("r", "reverse", "Search only in reverse complement of database.")); addOption(parser, ArgParseOption("a", "alphabet", "Alphabet type of input sequences (dna, rna, dna5, rna5, protein, char).", ArgParseArgument::STRING)); setValidValues(parser, "a", "dna dna5 rna rna5 protein char"); addOption(parser, ArgParseOption("v", "verbose", "Set verbosity mode.")); addSection(parser, "Filtering Options"); addOption(parser, ArgParseOption("k", "kmer", "Length of the q-grams (max 32).", ArgParseArgument::INTEGER)); setMinValue(parser, "k", "1"); setMaxValue(parser, "k", "32"); addOption(parser, ArgParseOption("rp", "repeatPeriod", "Maximal period of low complexity repeats to be filtered.", ArgParseArgument::INTEGER)); setDefaultValue(parser, "rp", "1"); addOption(parser, ArgParseOption("rl", "repeatLength", "Minimal length of low complexity repeats to be filtered.", ArgParseArgument::INTEGER)); setDefaultValue(parser, "rl", "1000"); addOption(parser, ArgParseOption("c", "abundanceCut", "k-mer overabundance cut ratio.", ArgParseArgument::DOUBLE)); setDefaultValue(parser, "c", "1"); setMinValue(parser, "c", "0"); setMaxValue(parser, "c", "1"); addSection(parser, "Verification Options"); addOption(parser, ArgParseOption("x", "xDrop", "Maximal x-drop for extension.", ArgParseArgument::DOUBLE)); setDefaultValue(parser, "x", "5"); addOption(parser, ArgParseOption("vs", "verification", "Verification strategy: exact or bestLocal or bandedGlobal", ArgParseArgument::STRING)); //addHelpLine(parser, "exact = compute and extend all local alignments in SWIFT hits"); //addHelpLine(parser, "bestLocal = compute and extend only best local alignment in SWIFT hits"); //addHelpLine(parser, "bandedGlobal = banded global alignment on SWIFT hits"); setDefaultValue(parser, "vs", "exact"); setValidValues(parser, "vs", "exact bestLocal bandedGlobal"); addOption(parser, ArgParseOption("dt", "disableThresh", "Maximal number of verified matches before disabling verification for one query " "sequence (default infinity).", ArgParseArgument::INTEGER)); setMinValue(parser, "dt", "0"); addOption(parser, ArgParseOption("n", "numMatches", "Maximal number of kept matches per query and database. If STELLAR finds more matches, " "only the longest ones are kept.", ArgParseArgument::INTEGER)); setDefaultValue(parser, "n", "50"); addOption(parser, ArgParseOption("s", "sortThresh", "Number of matches triggering removal of duplicates. Choose a smaller value for saving " "space.", ArgParseArgument::INTEGER)); setDefaultValue(parser, "s", "500"); addSection(parser, "Output Options"); addOption(parser, ArgParseOption("o", "out", "Name of output file.", ArgParseArgument::OUTPUT_FILE)); setValidValues(parser, "o", "gff txt"); setDefaultValue(parser, "o", "stellar.gff"); addOption(parser, ArgParseOption("od", "outDisabled", "Name of output file for disabled query sequences.", ArgParseArgument::OUTPUT_FILE)); setValidValues(parser, "outDisabled", seqan::SeqFileOut::getFileExtensions()); setDefaultValue(parser, "od", "stellar.disabled.fasta"); addOption(parser, ArgParseOption("no-rt", "suppress-runtime-printing", "Suppress printing running time.")); hideOption(parser, "no-rt"); addTextSection(parser, "References"); addText(parser, "Kehr, B., Weese, D., Reinert, K.: STELLAR: fast and exact local alignments. BMC Bioinformatics, " "12(Suppl 9):S15, 2011."); } } // namespace stellar::app } // namespace stellar
50.530928
154
0.656738
marehr
4958e0e4495d1dcfdd543aa69b57e04b3080d15d
542
cpp
C++
leetcode/1328. Break a Palindrome/s1.cpp
joycse06/LeetCode-1
ad105bd8c5de4a659c2bbe6b19f400b926c82d93
[ "Fair" ]
1
2021-02-11T01:23:10.000Z
2021-02-11T01:23:10.000Z
leetcode/1328. Break a Palindrome/s1.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
1
2021-08-08T18:44:24.000Z
2021-08-08T18:44:24.000Z
leetcode/1328. Break a Palindrome/s1.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
1
2021-03-25T17:11:14.000Z
2021-03-25T17:11:14.000Z
// OJ: https://leetcode.com/problems/break-a-palindrome/ // Author: github.com/lzl124631x // Time: O(N) // Space: O(1) class Solution { public: string breakPalindrome(string palindrome) { int N = palindrome.size(), end = N / 2; for (int i = 0; i < end; ++i) { if (palindrome[i] != 'a') { palindrome[i] = 'a'; return palindrome; } } if (N > 1) { palindrome[N - 1] = 'b'; return palindrome; } return ""; } };
25.809524
56
0.46679
joycse06
495ad89e432ab9f0af10b5534737b962cd0de0d5
441
cpp
C++
class/constructors.cpp
Abhilekhgautam/Cpp-college
3101cb061e36eee9d42226a8cfaf86ad5c695ef2
[ "CC0-1.0" ]
1
2021-07-22T08:38:25.000Z
2021-07-22T08:38:25.000Z
class/constructors.cpp
Abhilekhgautam/Cpp-college
3101cb061e36eee9d42226a8cfaf86ad5c695ef2
[ "CC0-1.0" ]
null
null
null
class/constructors.cpp
Abhilekhgautam/Cpp-college
3101cb061e36eee9d42226a8cfaf86ad5c695ef2
[ "CC0-1.0" ]
null
null
null
/* A c++ program to describe "objects are destroyed int reverse order of their creation"*/ #include<iostream> class Table{ public: Table(){std::cout<<"Object Created"<<'\n';} ~Table(){std::cout<<"Object Destoyed"<<'\n';} }; void f(int i) { Table aa; Table bb; if(i>0){ //cc will be created after bb and destroyed before dd is created Table cc; } Table dd; } int main(){ f(1); return 0; }
17.64
90
0.589569
Abhilekhgautam
495d1ce5531b5f88d17985d2c1a900531e11b56a
484
cpp
C++
src/core/test/src/net/test_Socket.cpp
SimpleTalkCpp/libsita
e0c13f16cebf799f0d57b8345d21de7407f59e2b
[ "MIT" ]
2
2021-03-19T13:19:27.000Z
2021-04-03T17:42:30.000Z
src/core/test/src/net/test_Socket.cpp
SimpleTalkCpp/libsita
e0c13f16cebf799f0d57b8345d21de7407f59e2b
[ "MIT" ]
null
null
null
src/core/test/src/net/test_Socket.cpp
SimpleTalkCpp/libsita
e0c13f16cebf799f0d57b8345d21de7407f59e2b
[ "MIT" ]
null
null
null
#include <sita_core/base/UnitTest.h> #include <sita_core/net/Socket.h> namespace sita { class Test_Socket : public UnitTestBase { public: void test_resolveIPv4() { Vector<int> a; IPv4 ip; ip.resolve("localhost"); SITA_DUMP_VAR(ip); SITA_TEST_CHECK(ip == IPv4(127,0,0,1)); SITA_TEST_CHECK_SLIENT(ip == IPv4(127,0,0,1)); } }; } // namespace void test_Socket() { using namespace sita; SITA_TEST_CASE(Test_Socket, test_resolveIPv4()); }
17.925926
50
0.663223
SimpleTalkCpp