hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
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
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
a49b4ad00d39fadcc9127ff747a740350a8e2ffc
25,608
cpp
C++
middleware/queue/unittest/isolated/source/test_group_database.cpp
tompis/casual
d838716c7052a906af8a19e945a496acdc7899a2
[ "MIT" ]
null
null
null
middleware/queue/unittest/isolated/source/test_group_database.cpp
tompis/casual
d838716c7052a906af8a19e945a496acdc7899a2
[ "MIT" ]
null
null
null
middleware/queue/unittest/isolated/source/test_group_database.cpp
tompis/casual
d838716c7052a906af8a19e945a496acdc7899a2
[ "MIT" ]
null
null
null
//! //! test_server_database.cpp //! //! Created on: Jun 6, 2014 //! Author: Lazan //! #include <gtest/gtest.h> #include "queue/group/database.h" #include "common/file.h" #include "common/exception.h" #include "common/environment.h" namespace casual { namespace queue { namespace local { namespace { /* common::file::scoped::Path file() { return common::file::scoped::Path{ "unittest_queue_server_database.db"}; } */ std::string file() { return ":memory:"; } static const common::transaction::ID nullId{}; common::message::queue::enqueue::Request message( const group::Queue& queue, const common::transaction::ID& trid = nullId) { common::message::queue::enqueue::Request result; result.queue = queue.id; result.trid = trid; result.message.id = common::uuid::make(); result.message.reply = "someQueue"; result.message.type = common::buffer::type::binary(); common::range::copy( common::uuid::string( common::uuid::make()), std::back_inserter(result.message.payload)); result.message.avalible = std::chrono::time_point_cast< std::chrono::microseconds>( common::platform::clock_type::now()); //result.message.timestamp = common::platform::clock_type::now(); return result; } common::message::queue::dequeue::Request request( const group::Queue& queue, const common::transaction::ID& trid = nullId) { common::message::queue::dequeue::Request result; result.queue = queue.id; result.trid = trid; return result; } } // <unnamed> } // local TEST( casual_queue_group_database, create_database) { auto path = local::file(); group::Database database( path, "test_group"); } TEST( casual_queue_group_database, create_queue) { auto path = local::file(); group::Database database( path, "test_group"); database.update( { group::Queue{ "unittest_queue"}}, {}); auto queues = database.queues(); // there is always an error-queue, and a global error-queue ASSERT_TRUE( queues.size() == 3); EXPECT_TRUE( queues.at( 0).name == "test_group.group.error") << "queues.at( 0).name: " << queues.at( 0).name; EXPECT_TRUE( queues.at( 1).name == "unittest_queue.error"); EXPECT_TRUE( queues.at( 2).name == "unittest_queue"); EXPECT_TRUE( queues.at( 2).count == 0) << "count: " << queues.at( 2).count; EXPECT_TRUE( queues.at( 2).size == 0); EXPECT_TRUE( queues.at( 2).uncommitted == 0); } TEST( casual_queue_group_database, remove_queue) { auto path = local::file(); group::Database database( path, "test_group"); auto queue = database.update( {group::Queue{ "unittest_queue"}}, {}); database.update( {}, { queue.at( 0).id}); EXPECT_TRUE( database.queues().size() == 1) << database.queues().size(); } TEST( casual_queue_group_database, update_queue) { auto path = local::file(); group::Database database( path, "test_group"); auto queue = database.update( { group::Queue{ "unittest_queue"}}, {}); queue.at( 0).name = "foo-bar"; database.update( { queue.at( 0)}, {}); auto queues = database.queues(); ASSERT_TRUE( queues.size() == 3) << queues.size(); EXPECT_TRUE( queues.at( 0).name.find_first_of( ".group.error") != std::string::npos); EXPECT_TRUE( queues.at( 1).name == "foo-bar.error"); EXPECT_TRUE( queues.at( 2).name == "foo-bar"); } TEST( casual_queue_group_database, create_queue_on_disc_and_open_again) { common::file::scoped::Path path{ common::file::name::unique( common::environment::directory::temporary() + "/", "unittest_queue_server_database.db") }; { group::Database database( path, "test_group"); database.create( group::Queue{ "unittest_queue"}); } { // // open again // group::Database database( path, "test_group"); auto queues = database.queues(); // there is always a error-queue, and a global error-queue ASSERT_TRUE( queues.size() == 3); //EXPECT_TRUE( queues.at( 0).name == "unittest_queue_server_database-error-queue") << queues.at( 0).name; EXPECT_TRUE( queues.at( 1).name == "unittest_queue.error"); EXPECT_TRUE( queues.at( 2).name == "unittest_queue"); } } TEST( casual_queue_group_database, create_5_queue_on_disc_and_open_again) { common::file::scoped::Path path{ common::file::name::unique( common::environment::directory::temporary() + "/", "unittest_queue_server_database.db") }; { group::Database database( path, "test_group"); for( int index = 1; index <= 5; ++index) { database.create( group::Queue{ "unittest_queue_" + std::to_string( index)}); } } { // // open again // group::Database database( path, "test_group"); auto queues = database.queues(); // there is always a error-queue, and a global error-queue ASSERT_TRUE( queues.size() == 5 * 2 + 1); //EXPECT_TRUE( queues.at( 0).name == "unittest_queue_server_database-error-queue") << queues.at( 0).name; EXPECT_TRUE( queues.at( 1).name == "unittest_queue_1.error") << queues.at( 1).name; EXPECT_TRUE( queues.at( 2).name == "unittest_queue_1") << queues.at( 2).name; } } TEST( casual_queue_group_database, create_100_queues) { auto path = local::file(); group::Database database( path, "test_group"); { auto writer = sql::database::scoped::write( database); auto count = 0; while( count++ < 100) { database.create( group::Queue{ "unittest_queue" + std::to_string( count)}); } } auto queues = database.queues(); // there is always an error-queue for each queue, and a global error-queue ASSERT_TRUE( queues.size() == 201) << "size: " << queues.size(); EXPECT_TRUE( queues.at( 1).name == "unittest_queue1.error") << queues.at( 200).name; } TEST( casual_queue_group_database, enqueue_one_message) { auto path = local::file(); group::Database database( path, "test_group"); auto queue = database.create( group::Queue{ "unittest_queue"}); auto message = local::message( queue); EXPECT_NO_THROW({ EXPECT_TRUE( static_cast< bool>( database.enqueue( message).id)); }); } TEST( casual_queue_group_database, enqueue_one_message__get_queue_info) { auto path = local::file(); group::Database database( path, "test_group"); auto queue = database.create( group::Queue{ "unittest_queue"}); auto message = local::message( queue); EXPECT_NO_THROW({ database.enqueue( message); }); auto queues = database.queues(); ASSERT_TRUE( queues.size() == 3); EXPECT_TRUE( queues.at( 2).name == "unittest_queue"); EXPECT_TRUE( queues.at( 2).count == 1) << " queues.at( 2).count: " << queues.at( 2).count; EXPECT_TRUE( queues.at( 2).size == message.message.payload.size()); } TEST( casual_queue_group_database, enqueue_one_message__get_message_info) { auto path = local::file(); group::Database database( path, "test_group"); auto queue = database.create( group::Queue{ "unittest_queue"}); auto message = local::message( queue); EXPECT_NO_THROW({ database.enqueue( message); }); auto messages = database.messages( queue.id); ASSERT_TRUE( messages.size() == 1); EXPECT_TRUE( messages.at( 0).id == message.message.id); } TEST( casual_queue_group_database, dequeue_one_message) { auto path = local::file(); group::Database database( path, "test_group"); auto queue = database.create( group::Queue{ "unittest_queue"}); auto origin = local::message( queue); database.enqueue( origin); auto fetched = database.dequeue( local::request( queue)); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); EXPECT_TRUE( origin.message.type == fetched.message.at( 0).type); EXPECT_TRUE( origin.message.reply == fetched.message.at( 0).reply); EXPECT_TRUE( origin.message.payload == fetched.message.at( 0).payload); EXPECT_TRUE( origin.message.avalible == fetched.message.at( 0).avalible); } TEST( casual_queue_group_database, enqueue_deque__info__expect__count_0__size_0) { auto path = local::file(); group::Database database( path, "test_group"); auto queue = database.create( group::Queue{ "enqueue_deque__info__expect__count_0__size_0"}); auto origin = local::message( queue); database.enqueue( origin); auto fetched = database.dequeue( local::request( queue)); EXPECT_TRUE( fetched.message.size() == 1); auto queues = database.queues(); ASSERT_TRUE( queues.at( 2).id == queue.id); EXPECT_TRUE( queues.at( 2).count == 0) << " queues.at( 2).count: " << queues.at( 2).count; EXPECT_TRUE( queues.at( 2).size == 0); } TEST( casual_queue_group_database, dequeue_message__from_id) { auto path = local::file(); group::Database database( path, "test_group"); auto queue = database.create( group::Queue{ "dequeue_message__from_id"}); auto origin = local::message( queue); database.enqueue( origin); auto reqest = local::request( queue); reqest.selector.id = origin.message.id; auto fetched = database.dequeue( reqest); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); EXPECT_TRUE( origin.message.type == fetched.message.at( 0).type); EXPECT_TRUE( origin.message.reply == fetched.message.at( 0).reply); EXPECT_TRUE( origin.message.avalible == fetched.message.at( 0).avalible); } TEST( casual_queue_group_database, dequeue_message__from_properties) { auto path = local::file(); group::Database database( path, "test_group"); auto queue = database.create( group::Queue{ "unittest_queue"}); auto origin = local::message( queue); origin.message.properties = "some: properties"; database.enqueue( origin); auto reqest = local::request( queue); reqest.selector.properties = origin.message.properties; auto fetched = database.dequeue( reqest); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); EXPECT_TRUE( origin.message.type == fetched.message.at( 0).type); EXPECT_TRUE( origin.message.reply == fetched.message.at( 0).reply); EXPECT_TRUE( origin.message.payload == fetched.message.at( 0).payload); EXPECT_TRUE( origin.message.avalible == fetched.message.at( 0).avalible); } TEST( casual_queue_group_database, dequeue_message__from_non_existent_properties__expect_0_messages) { auto path = local::file(); group::Database database( path, "test_group"); auto queue = database.create( group::Queue{ "unittest_queue"}); auto origin = local::message( queue); origin.message.properties = "some: properties"; database.enqueue( origin); auto reqest = local::request( queue); reqest.selector.properties = "some other properties"; auto fetched = database.dequeue( reqest); EXPECT_TRUE( fetched.message.size() == 0); } TEST( casual_queue_group_database, dequeue_100_message) { auto path = local::file(); group::Database database( path, "test_group"); auto queue = database.create( group::Queue{ "unittest_queue"}); using message_type = decltype( local::message( queue)); std::vector< message_type > messages; auto count = 0; while( count++ < 100) { auto m = local::message( queue); m.message.type.name = std::to_string( count); messages.push_back( std::move( m)); } { auto writer = sql::database::scoped::write( database); common::range::for_each( messages, [&]( const message_type& m){ database.enqueue( m);}); } auto writer = sql::database::scoped::write( database); common::range::for_each( messages,[&]( const message_type& origin){ auto fetched = database.dequeue( local::request( queue)); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); EXPECT_TRUE( origin.message.type == fetched.message.at( 0).type) << "origin.type: " << origin.message.type << " fetched.type; " << fetched.message.at( 0).type; EXPECT_TRUE( origin.message.reply == fetched.message.at( 0).reply); EXPECT_TRUE( origin.message.payload == fetched.message.at( 0).payload); EXPECT_TRUE( origin.message.avalible == fetched.message.at( 0).avalible); //EXPECT_TRUE( origin.message.timestamp <= fetched.timestamp) << "origin: " << origin.timestamp.time_since_epoch().count() << " fetched: " << fetched.timestamp.time_since_epoch().count(); }); } TEST( casual_queue_group_database, enqueue_one_message_in_transaction) { auto path = local::file(); group::Database database( path, "test_group"); auto queue = database.create( group::Queue{ "unittest_queue"}); common::transaction::ID xid = common::transaction::ID::create(); auto origin = local::message( queue, xid); { database.enqueue( origin); // // Message should not be available. // EXPECT_TRUE( database.dequeue( local::request( queue)).message.empty()); // // Not even within the same transaction // EXPECT_TRUE( database.dequeue( local::request( queue, xid)).message.empty()); database.commit( xid); } { common::transaction::ID xid = common::transaction::ID::create(); auto fetched = database.dequeue( local::request( queue, xid)); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); EXPECT_TRUE( origin.message.type == fetched.message.at( 0).type); EXPECT_TRUE( origin.message.reply == fetched.message.at( 0).reply); EXPECT_TRUE( origin.message.avalible == fetched.message.at( 0).avalible); } } TEST( casual_queue_group_database, dequeue_one_message_in_transaction) { auto path = local::file(); group::Database database( path, "test_group"); auto queue = database.create( group::Queue{ "unittest_queue"}); auto origin = local::message( queue); database.enqueue( origin); { common::transaction::ID xid = common::transaction::ID::create(); auto fetched = database.dequeue( local::request( queue, xid)); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); database.commit( xid); } // // Should be empty // EXPECT_TRUE( database.dequeue( local::request( queue)).message.empty()); } TEST( casual_queue_group_database, dequeue_group_error_queue__rollback__expect__message_not_moved) { auto path = local::file(); group::Database database( path, "test_group"); group::Queue group_queue; group_queue.id = database.error(); auto origin = local::message( group_queue); database.enqueue( origin); { common::transaction::ID xid = common::transaction::ID::create(); auto fetched = database.dequeue( local::request( group_queue, xid)); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); database.rollback( xid); } // // Message should still be there // auto queues = database.queues(); ASSERT_TRUE( queues.at( 0).id == database.error()); EXPECT_TRUE( queues.at( 0).count == 1); EXPECT_TRUE( queues.at( 0).size == origin.message.payload.size()); auto fetched = database.dequeue( local::request( group_queue)); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); } TEST( casual_queue_group_database, deque_in_transaction__info__expect__count_0__size_0) { auto path = local::file(); group::Database database( path, "test_group"); auto queue = database.create( group::Queue{ "unittest_queue"}); auto origin = local::message( queue); database.enqueue( origin); { common::transaction::ID xid = common::transaction::ID::create(); auto fetched = database.dequeue( local::request( queue, xid)); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); database.commit( xid); } auto queues = database.queues(); ASSERT_TRUE( queues.at( 2).id == queue.id); EXPECT_TRUE( queues.at( 2).count == 0) << " queues.at( 2).count: " << queues.at( 2).count; EXPECT_TRUE( queues.at( 2).size == 0); } TEST( casual_queue_group_database, enqueue_one_message_in_transaction_rollback) { auto path = local::file(); group::Database database( path, "test_group"); auto queue = database.create( group::Queue{ "unittest_queue"}); common::transaction::ID xid = common::transaction::ID::create(); auto origin = local::message( queue, xid); database.enqueue( origin); database.rollback( xid); // // Should be empty // //local::print( database.queues()); EXPECT_TRUE( database.dequeue( local::request( queue)).message.empty()); } TEST( casual_queue_group_database, enqueue_one_message_in_transaction_rollback__info__expect__count_0__size_0) { auto path = local::file(); group::Database database( path, "test_group"); auto queue = database.create( group::Queue{ "unittest_queue"}); common::transaction::ID xid = common::transaction::ID::create(); auto origin = local::message( queue, xid); database.enqueue( origin); database.rollback( xid); auto queues = database.queues(); ASSERT_TRUE( queues.at( 2).id == queue.id); EXPECT_TRUE( queues.at( 2).count == 0) << " queues.at( 2).count: " << queues.at( 2).count; EXPECT_TRUE( queues.at( 2).size == 0); } TEST( casual_queue_group_database, enqueue_dequeue_one_message_in_transaction_rollback) { auto path = local::file(); group::Database database( path, "test_group"); auto queue = database.create( group::Queue{ "unittest_queue"}); auto origin = local::message( queue); { common::transaction::ID xid = common::transaction::ID::create(); database.enqueue( origin); database.commit( xid); auto queues = database.queues(); ASSERT_TRUE( queues.at( 2).id == queue.id); EXPECT_TRUE( queues.at( 2).count == 1) << " queues.at( 2).count: " << queues.at( 2).count; EXPECT_TRUE( queues.at( 2).size == origin.message.payload.size()); } { common::transaction::ID xid = common::transaction::ID::create(); auto fetched = database.dequeue( local::request( queue, xid)); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); database.rollback( xid); auto affected = database.affected(); EXPECT_TRUE( affected == 1) << "affected: " << affected; EXPECT_TRUE( database.dequeue( local::request( queue, xid)).message.empty()); } // // Should be in error queue // { auto queues = database.queues(); ASSERT_TRUE( queues.at( 1).id == queue.error); EXPECT_TRUE( queues.at( 1).count == 1) << " queues.at( 2).count: " << queues.at( 1).count; EXPECT_TRUE( queues.at( 1).size == origin.message.payload.size()); common::transaction::ID xid = common::transaction::ID::create(); auto errorQ = queue; errorQ.id = queue.error; auto fetched = database.dequeue( local::request( errorQ, xid)); ASSERT_TRUE( fetched.message.size() == 1) << "errorQ.id; " << errorQ.id << " queue.id: " << queue.id; EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); database.rollback( xid); } // // Should be in global error queue // { auto queues = database.queues(); ASSERT_TRUE( queues.at( 0).id == database.error()); EXPECT_TRUE( queues.at( 0).count == 1); EXPECT_TRUE( queues.at( 0).size == origin.message.payload.size()); common::transaction::ID xid = common::transaction::ID::create(); auto errorQ = queue; errorQ.id = database.error(); auto fetched = database.dequeue( local::request( errorQ, xid)); database.commit( xid); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); } // // All queues should have count = 0 and size = 0 // auto queues = database.queues(); ASSERT_TRUE( queues.at( 0).id == database.error()); EXPECT_TRUE( queues.at( 0).count == 0); EXPECT_TRUE( queues.at( 0).size == 0); ASSERT_TRUE( queues.at( 1).id == queue.error); EXPECT_TRUE( queues.at( 1).count == 0); EXPECT_TRUE( queues.at( 1).size == 0); ASSERT_TRUE( queues.at( 2).id == queue.id); EXPECT_TRUE( queues.at( 2).count == 0); EXPECT_TRUE( queues.at( 2).size == 0); } TEST( casual_queue_group_database, dequeue_100_message_in_transaction) { auto path = local::file(); group::Database database( path, "test_group"); auto queue = database.create( group::Queue{ "unittest_queue"}); using message_type = decltype( local::message( queue)); std::vector< message_type > messages; messages.reserve( 100); { common::transaction::ID xid = common::transaction::ID::create(); auto count = 0; while( count++ < 100) { auto m = local::message( queue, xid); m.message.type.subname = std::to_string( count); database.enqueue( m); messages.push_back( std::move( m)); } database.commit( xid); } common::transaction::ID xid = common::transaction::ID::create(); common::range::for_each( messages,[&]( const message_type& origin){ auto fetched = database.dequeue( local::request( queue, xid)); ASSERT_TRUE( fetched.message.size() == 1); EXPECT_TRUE( origin.message.id == fetched.message.at( 0).id); EXPECT_TRUE( origin.message.type == fetched.message.at( 0).type) << "origin.type: " << origin.message.type << " fetched.type; " << fetched.message.at( 0).type; EXPECT_TRUE( origin.message.reply == fetched.message.at( 0).reply); EXPECT_TRUE( origin.message.avalible == fetched.message.at( 0).avalible); //EXPECT_TRUE( origin.message.timestamp <= fetched.timestamp) << "origin: " << origin.timestamp.time_since_epoch().count() << " fetched: " << fetched.timestamp.time_since_epoch().count(); }); database.commit( xid); EXPECT_TRUE( database.dequeue( local::request( queue)).message.empty()); } } // queue } // casual
33.562254
199
0.572048
[ "vector" ]
a49cd24e2c439b5e7b2215b12fa21a8d570cf6aa
10,785
cpp
C++
Enging/Game/d3dApp.cpp
Inyuan/StrikeEngine
50e6b52e4bc5e6a7954ef9fd7c1ef691c5eb1d58
[ "MIT" ]
1
2021-08-14T12:19:17.000Z
2021-08-14T12:19:17.000Z
Enging/Game/d3dApp.cpp
Inyuan/StrokeEngine
50e6b52e4bc5e6a7954ef9fd7c1ef691c5eb1d58
[ "MIT" ]
null
null
null
Enging/Game/d3dApp.cpp
Inyuan/StrokeEngine
50e6b52e4bc5e6a7954ef9fd7c1ef691c5eb1d58
[ "MIT" ]
null
null
null
//*************************************************************************************** // d3dApp.cpp by Frank Luna (C) 2015 All Rights Reserved. //*************************************************************************************** #include "d3dApp.h" #include <WindowsX.h> using Microsoft::WRL::ComPtr; using namespace std; using namespace DirectX; D3DApp* D3DApp::mApp = nullptr; D3DApp* D3DApp::GetApp() { return mApp; } D3DApp::D3DApp(HWND hwnd) : mhMainWnd(hwnd) { // Only one D3DApp can be constructed. assert(mApp == nullptr); mApp = this; } D3DApp::~D3DApp() { if (md3dDevice != nullptr) FlushCommandQueue(); } //HINSTANCE D3DApp::AppInst()const{ return mhAppInst;} HWND D3DApp::MainWnd()const { return mhMainWnd; } float D3DApp::AspectRatio()const { return static_cast<float>(mClientWidth) / mClientHeight; } bool D3DApp::Get4xMsaaState()const { return md3dinf->m4xMsaaState; } void D3DApp::Set4xMsaaState(bool value) { if (md3dinf->m4xMsaaState != value) { md3dinf->m4xMsaaState = value; // Recreate the swapchain and buffers with new multisample settings. CreateSwapChain(); OnResize(mClientWidth, mClientHeight); } } int D3DApp::Run() { mTimer.Tick(); if (!mAppPaused) { CalculateFrameStats(); Update(mTimer); Draw(mTimer); } else { Sleep(100); } return 0; } bool D3DApp::Initialize(int width, int height) { mClientWidth = width; mClientHeight = height; if (!InitDirect3D()) return false; shadowPass = new ShadowPass(md3dinf); basePass = new BasePass(md3dinf); lightPass = new LightPass(md3dinf); profilePass = new ProfilePass(md3dinf); mixPass = new MixPass(md3dinf); // Do the initial resize code. OnResize(width, height); shadowPass->Initialize(); basePass->Initialize(); lightPass->Initialize(); profilePass->Initialize(); mixPass->Initialize(); return true; } void D3DApp::OnResize(int width, int height) { mClientWidth = width; mClientHeight = height; assert(md3dDevice); assert(mSwapChain); assert(mDirectCmdListAlloc); // Flush before changing any resources. FlushCommandQueue(); ThrowIfFailed(mCommandList->Reset(mDirectCmdListAlloc.Get(), nullptr)); // Release the previous resources we will be recreating. for (int i = 0; i < SwapChainBufferCount; ++i) md3dinf->mSwapChainBuffer[i].Reset(); // Resize the swap chain. ThrowIfFailed(mSwapChain->ResizeBuffers( SwapChainBufferCount, mClientWidth, mClientHeight, md3dinf->mBackBufferFormat, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH)); md3dinf->mCurrBackBuffer = 0; CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHeapHandle(md3dinf->mRtvHeap->GetCPUDescriptorHandleForHeapStart()); for (UINT i = 0; i < SwapChainBufferCount; i++) { ThrowIfFailed(mSwapChain->GetBuffer(i, IID_PPV_ARGS(&md3dinf->mSwapChainBuffer[i]))); md3dDevice->CreateRenderTargetView(md3dinf->mSwapChainBuffer[i].Get(), nullptr, rtvHeapHandle); rtvHeapHandle.Offset(1, md3dinf->mRtvDescriptorSize); } md3dinf->mClientWidth = mClientWidth; md3dinf->mClientHeight = mClientHeight; md3dinf->OnResize(); shadowPass->OnResize(); basePass->OnResize(); lightPass->OnResize(); profilePass->OnResize(); mixPass->OnResize(); // Execute the resize commands. ThrowIfFailed(mCommandList->Close()); ID3D12CommandList* cmdsLists[] = { mCommandList.Get() }; mCommandQueue->ExecuteCommandLists(_countof(cmdsLists), cmdsLists); // Wait until resize is complete. FlushCommandQueue(); mTimer.Reset(); } bool D3DApp::InitDirect3D() { #if defined(DEBUG) || defined(_DEBUG) // Enable the D3D12 debug layer. { ComPtr<ID3D12Debug> debugController; ThrowIfFailed(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController))); debugController->EnableDebugLayer(); } #endif ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&mdxgiFactory))); // Try to create hardware device. HRESULT hardwareResult = D3D12CreateDevice( nullptr, // default adapter D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&md3dDevice)); // Fallback to WARP device. if (FAILED(hardwareResult)) { ComPtr<IDXGIAdapter> pWarpAdapter; ThrowIfFailed(mdxgiFactory->EnumWarpAdapter(IID_PPV_ARGS(&pWarpAdapter))); ThrowIfFailed(D3D12CreateDevice( pWarpAdapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&md3dDevice))); } ThrowIfFailed(md3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&mFence))); // Check 4X MSAA quality support for our back buffer format. // All Direct3D 11 capable devices support 4X MSAA for all render // target formats, so we only need to check quality support. #ifdef _DEBUG LogAdapters(); #endif CreateCommandObjects(); md3dinf = new D3DINF(md3dDevice.Get(), mCommandList.Get()); md3dinf->mRtvDescriptorSize = md3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); md3dinf->mDsvDescriptorSize = md3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV); md3dinf->mCbvSrvUavDescriptorSize = md3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS msQualityLevels; msQualityLevels.Format = md3dinf->mBackBufferFormat; msQualityLevels.SampleCount = 4; msQualityLevels.Flags = D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE; msQualityLevels.NumQualityLevels = 0; ThrowIfFailed(md3dDevice->CheckFeatureSupport( D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &msQualityLevels, sizeof(msQualityLevels))); md3dinf->m4xMsaaQuality = msQualityLevels.NumQualityLevels; assert(md3dinf->m4xMsaaQuality > 0 && "Unexpected MSAA quality level."); CreateSwapChain(); return true; } void D3DApp::CreateCommandObjects() { D3D12_COMMAND_QUEUE_DESC queueDesc = {}; queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; ThrowIfFailed(md3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&mCommandQueue))); ThrowIfFailed(md3dDevice->CreateCommandAllocator( D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(mDirectCmdListAlloc.GetAddressOf()))); ThrowIfFailed(md3dDevice->CreateCommandList( 0, D3D12_COMMAND_LIST_TYPE_DIRECT, mDirectCmdListAlloc.Get(), // Associated command allocator nullptr, // Initial PipelineStateObject IID_PPV_ARGS(mCommandList.GetAddressOf()))); // Start off in a closed state. This is because the first time we refer // to the command list we will Reset it, and it needs to be closed before // calling Reset. mCommandList->Close(); } void D3DApp::CreateSwapChain() { // Release the previous swapchain we will be recreating. mSwapChain.Reset(); DXGI_SWAP_CHAIN_DESC sd; sd.BufferDesc.Width = md3dinf->mClientWidth; sd.BufferDesc.Height = md3dinf->mClientHeight; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferDesc.Format = md3dinf->mBackBufferFormat; sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; sd.SampleDesc.Count = md3dinf->m4xMsaaState ? 4 : 1; sd.SampleDesc.Quality = md3dinf->m4xMsaaState ? (md3dinf->m4xMsaaQuality - 1) : 0; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.BufferCount = SwapChainBufferCount; sd.OutputWindow = mhMainWnd; sd.Windowed = true; sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; // Note: Swap chain uses queue to perform flush. ThrowIfFailed(mdxgiFactory->CreateSwapChain( mCommandQueue.Get(), &sd, mSwapChain.GetAddressOf())); } void D3DApp::FlushCommandQueue() { // Advance the fence value to mark commands up to this fence point. mCurrentFence++; // Add an instruction to the command queue to set a new fence point. Because we // are on the GPU timeline, the new fence point won't be set until the GPU finishes // processing all the commands prior to this Signal(). ThrowIfFailed(mCommandQueue->Signal(mFence.Get(), mCurrentFence)); // Wait until the GPU has completed commands up to this fence point. if (mFence->GetCompletedValue() < mCurrentFence) { HANDLE eventHandle = CreateEventEx(nullptr, false, false, EVENT_ALL_ACCESS); // Fire event when GPU hits current fence. ThrowIfFailed(mFence->SetEventOnCompletion(mCurrentFence, eventHandle)); // Wait until the GPU hits current fence event is fired. WaitForSingleObject(eventHandle, INFINITE); CloseHandle(eventHandle); } } void D3DApp::CalculateFrameStats() { // Code computes the average frames per second, and also the // average time it takes to render one frame. These stats // are appended to the window caption bar. static int frameCnt = 0; static float timeElapsed = 0.0f; frameCnt++; // Compute averages over one second period. if ((mTimer.TotalTime() - timeElapsed) >= 1.0f) { float fps = (float)frameCnt; // fps = frameCnt / 1 float mspf = 1000.0f / fps; wstring fpsStr = to_wstring(fps); wstring mspfStr = to_wstring(mspf); wstring windowText = mMainWndCaption + L" fps: " + fpsStr + L" mspf: " + mspfStr; SetWindowText(mhMainWnd, windowText.c_str()); // Reset for next average. frameCnt = 0; timeElapsed += 1.0f; } } void D3DApp::LogAdapters() { UINT i = 0; IDXGIAdapter* adapter = nullptr; std::vector<IDXGIAdapter*> adapterList; while (mdxgiFactory->EnumAdapters(i, &adapter) != DXGI_ERROR_NOT_FOUND) { DXGI_ADAPTER_DESC desc; adapter->GetDesc(&desc); std::wstring text = L"***Adapter: "; text += desc.Description; text += L"\n"; OutputDebugString(text.c_str()); adapterList.push_back(adapter); ++i; } for (size_t i = 0; i < adapterList.size(); ++i) { LogAdapterOutputs(adapterList[i]); ReleaseCom(adapterList[i]); } } void D3DApp::LogAdapterOutputs(IDXGIAdapter* adapter) { UINT i = 0; IDXGIOutput* output = nullptr; while (adapter->EnumOutputs(i, &output) != DXGI_ERROR_NOT_FOUND) { DXGI_OUTPUT_DESC desc; output->GetDesc(&desc); std::wstring text = L"***Output: "; text += desc.DeviceName; text += L"\n"; OutputDebugString(text.c_str()); LogOutputDisplayModes(output, mBackBufferFormat); ReleaseCom(output); ++i; } } void D3DApp::LogOutputDisplayModes(IDXGIOutput* output, DXGI_FORMAT format) { UINT count = 0; UINT flags = 0; // Call with nullptr to get list count. output->GetDisplayModeList(format, flags, &count, nullptr); std::vector<DXGI_MODE_DESC> modeList(count); output->GetDisplayModeList(format, flags, &count, &modeList[0]); for (auto& x : modeList) { UINT n = x.RefreshRate.Numerator; UINT d = x.RefreshRate.Denominator; std::wstring text = L"Width = " + std::to_wstring(x.Width) + L" " + L"Height = " + std::to_wstring(x.Height) + L" " + L"Refresh = " + std::to_wstring(n) + L"/" + std::to_wstring(d) + L"\n"; ::OutputDebugString(text.c_str()); } }
25.801435
122
0.728883
[ "render", "vector" ]
a4a5bb40d2c43176f0f3c4e2231bc3593fff0840
10,425
hh
C++
firmware/src/MightyBoard/shared/Menu_locales.hh
jake-b/Sailfish-MightyBoardFirmware
1db488ffe24a34f41e9fbe469210cf5d9fd38c99
[ "AAL" ]
null
null
null
firmware/src/MightyBoard/shared/Menu_locales.hh
jake-b/Sailfish-MightyBoardFirmware
1db488ffe24a34f41e9fbe469210cf5d9fd38c99
[ "AAL" ]
null
null
null
firmware/src/MightyBoard/shared/Menu_locales.hh
jake-b/Sailfish-MightyBoardFirmware
1db488ffe24a34f41e9fbe469210cf5d9fd38c99
[ "AAL" ]
null
null
null
#ifndef __MENU__LOCALES__ #define __MENU__LOCALES__ #include <avr/pgmspace.h> #include <string.h> #include "Model.hh" const static PROGMEM prog_uchar ON_CELCIUS_MSG[] = "/ C"; const static PROGMEM prog_uchar CELCIUS_MSG[] = "C "; const static PROGMEM prog_uchar BLANK_CHAR_MSG[] = " "; const static PROGMEM prog_uchar BLANK_CHAR_4_MSG[] = " "; const static PROGMEM prog_uchar CLEAR_MSG[] = " "; // Note: RepG is adding an extra disable axes on the end.... // so check the last four bytes and remove the last two // if they are 137, 31, 137, 31 #if defined(ZYYX_3D_PRINTER) #if defined(ZYYX_LEVEL_SCRIPT) #define LEVEL_PLATE const static uint8_t LevelPlate[] PROGMEM = { \ 137,8,153,0,0,0,0,82,101,112,71,32,66,117,105,108,\ 100,0,150,0,255,145,0,127,145,1,127,145,2,64,145,3,\ 127,145,4,127,132,3,125,1,0,0,20,0,131,4,77,1,\ 0,0,20,0,140,0,0,0,0,0,0,0,0,0,0,0,\ 0,0,0,0,0,0,0,0,0,155,0,0,0,0,0,0,\ 0,0,208,7,0,0,0,0,0,0,0,0,0,0,183,11,\ 0,0,24,0,0,160,64,224,1,149,0,0,0,0,84,104,\ 105,115,32,119,105,122,97,114,100,32,119,105,108,108,32,114,\ 101,115,0,149,1,0,0,0,116,111,114,101,32,102,97,99,\ 116,111,114,121,32,99,97,108,105,98,114,97,0,149,1,0,\ 0,0,116,105,111,110,32,111,102,32,116,104,101,32,98,117,\ 105,108,100,112,108,97,0,149,7,0,0,0,116,101,44,32,\ 112,114,101,115,115,32,109,105,100,98,117,116,116,111,110,0,\ 149,0,0,0,0,80,108,101,97,115,101,32,114,101,109,111,\ 118,101,32,97,110,121,32,112,108,0,149,1,0,0,0,97,\ 115,116,105,99,32,114,101,115,105,100,117,101,32,111,110,32,\ 116,104,101,0,149,1,0,0,0,32,112,114,105,110,116,32,\ 104,101,97,100,32,110,111,122,122,108,101,44,32,0,149,7,\ 0,0,0,112,114,101,115,115,32,109,105,100,98,117,116,116,\ 111,110,0,149,0,0,0,0,97,100,106,117,115,116,32,98,\ 117,105,108,100,112,108,97,116,101,32,116,111,0,149,1,0,\ 0,0,32,108,111,119,101,115,116,32,112,111,115,105,116,105,\ 111,110,32,111,110,32,0,149,1,0,0,0,97,108,108,32,\ 51,32,112,111,105,110,116,115,32,119,105,116,104,32,116,104,\ 0,149,7,0,0,0,101,32,116,111,111,108,44,32,112,114,\ 101,115,115,32,109,105,100,98,116,110,0,131,4,238,2,0,\ 0,20,0,140,0,0,0,0,0,0,0,0,0,0,0,0,\ 0,0,0,0,0,0,0,0,155,0,0,0,0,0,0,0,\ 0,208,7,0,0,0,0,0,0,0,0,0,0,183,11,0,\ 0,24,0,0,160,64,224,1,149,0,0,0,0,70,105,110,\ 100,105,110,103,32,116,104,101,32,104,105,103,104,101,115,116,\ 32,0,149,3,0,0,0,112,111,105,110,116,46,46,46,0,\ 155,0,0,0,0,39,178,255,255,208,7,0,0,0,0,0,\ 0,0,0,0,0,76,17,0,0,24,0,0,97,67,128,12,\ 155,0,0,0,0,39,178,255,255,0,0,0,0,0,0,0,\ 0,0,0,0,0,53,5,0,0,24,0,0,160,64,213,0,\ 155,0,0,0,0,39,178,255,255,208,7,0,0,0,0,0,\ 0,0,0,0,0,183,11,0,0,24,0,0,160,64,224,1,\ 155,195,194,255,255,0,0,0,0,208,7,0,0,0,0,0,\ 0,0,0,0,0,152,13,0,0,24,87,35,143,67,128,12,\ 155,195,194,255,255,0,0,0,0,0,0,0,0,0,0,0,\ 0,0,0,0,0,53,5,0,0,24,0,0,160,64,213,0,\ 155,195,194,255,255,0,0,0,0,208,7,0,0,0,0,0,\ 0,0,0,0,0,183,11,0,0,24,0,0,160,64,224,1,\ 155,195,194,255,255,0,0,0,0,144,1,0,0,0,0,0,\ 0,0,0,0,0,53,5,0,0,24,0,0,128,64,213,0,\ 149,0,0,0,0,65,100,106,117,115,116,32,98,97,99,107,\ 32,108,101,102,116,32,112,111,115,0,149,1,0,0,0,105,\ 116,105,111,110,32,106,117,115,116,32,117,110,116,105,108,32,\ 76,69,68,0,149,1,0,0,0,32,108,105,103,104,116,115,\ 44,32,116,104,101,110,32,112,114,101,115,115,32,0,149,7,\ 0,0,0,109,105,100,98,117,116,116,111,110,0,155,195,194,\ 255,255,0,0,0,0,208,7,0,0,0,0,0,0,0,0,\ 0,0,183,11,0,0,24,0,0,128,64,224,1,155,0,0,\ 0,0,0,0,0,0,208,7,0,0,0,0,0,0,0,0,\ 0,0,76,17,0,0,24,0,0,49,67,128,12,155,0,0,\ 0,0,0,0,0,0,144,1,0,0,0,0,0,0,0,0,\ 0,0,53,5,0,0,24,0,0,128,64,213,0,149,0,0,\ 0,0,65,100,106,117,115,116,32,98,97,99,107,32,114,105,\ 103,104,116,32,112,111,0,149,1,0,0,0,115,105,116,105,\ 111,110,32,106,117,115,116,32,117,110,116,105,108,32,76,69,\ 0,149,1,0,0,0,68,32,108,105,103,104,116,115,44,32,\ 116,104,101,110,32,112,114,101,115,115,0,149,7,0,0,0,\ 32,109,105,100,98,117,116,116,111,110,0,155,0,0,0,0,\ 0,0,0,0,208,7,0,0,0,0,0,0,0,0,0,0,\ 183,11,0,0,24,0,0,128,64,224,1,155,0,0,0,0,\ 39,178,255,255,208,7,0,0,0,0,0,0,0,0,0,0,\ 76,17,0,0,24,0,0,97,67,128,12,155,0,0,0,0,\ 39,178,255,255,144,1,0,0,0,0,0,0,0,0,0,0,\ 53,5,0,0,24,0,0,128,64,213,0,149,0,0,0,0,\ 65,100,106,117,115,116,32,102,114,111,110,116,32,112,111,115,\ 105,116,105,111,0,149,1,0,0,0,110,32,106,117,115,116,\ 32,117,110,116,105,108,32,76,69,68,32,108,105,103,0,149,\ 1,0,0,0,104,116,115,44,32,116,104,101,110,32,112,114,\ 101,115,115,32,109,105,100,98,0,149,7,0,0,0,117,116,\ 116,111,110,0,155,0,0,0,0,39,178,255,255,208,7,0,\ 0,0,0,0,0,0,0,0,0,183,11,0,0,24,0,0,\ 128,64,224,1,132,3,125,1,0,0,20,0,149,0,0,0,\ 0,86,101,114,105,102,121,105,110,103,32,99,97,108,105,98,\ 114,97,116,105,111,0,149,3,0,0,0,110,32,114,101,115,\ 117,108,116,46,46,46,0,131,4,238,2,0,0,20,0,140,\ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\ 0,0,0,0,143,8,155,0,0,0,0,0,0,0,0,208,\ 7,0,0,0,0,0,0,0,0,0,0,53,5,0,0,24,\ 0,0,160,64,213,0,155,195,194,255,255,0,0,0,0,208,\ 7,0,0,0,0,0,0,0,0,0,0,76,17,0,0,24,\ 0,0,49,67,128,12,131,4,238,2,0,0,20,0,143,16,\ 139,195,194,255,255,0,0,0,0,208,7,0,0,0,0,0,\ 0,0,0,0,0,128,0,0,0,155,0,0,0,0,39,178,\ 255,255,208,7,0,0,0,0,0,0,0,0,0,0,152,13,\ 0,0,24,87,35,143,67,128,12,131,4,238,2,0,0,20,\ 0,143,24,139,0,0,0,0,39,178,255,255,160,15,0,0,\ 0,0,0,0,0,0,0,0,128,0,0,0,144,8,137,31,\ 150,100,255,154,0,137,31}; #define LEVEL_PLATE_LEN 1495 //93 rader x16 bytes + 7 #else #define LEVEL_PLATE const static uint8_t LevelPlate[] PROGMEM = { 137,31}; #define LEVEL_PLATE_LEN 2 #endif // ZYYX_LEVEL_SCRIPT #else // ZYYX_3D_PRINTER #define LEVEL_PLATE const static uint8_t LevelPlate[] PROGMEM = { 137, 8, 153, 0, 0, 0, 0, 82, 101, 112, 71, 32, 66, 117, 105, 108, 100, 0, 150, 0, 255, 132, 3, 105, 1, 0, 0, 20, 0, 131, 4, 136, 0, 0, 0, 20, 0, 140, 0, 0, 0, 0, 0, 0, 0, 0, 48, 248, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 155, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 165, 28, 0, 0, 24, 0, 0, 160, 64, 149, 4, 131, 4, 220, 5, 0, 0, 20, 0, 144, 31, 139, 0, 0, 0, 0, 0, 0, 0, 0, 160, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 155, 0, 0, 0, 0, 0, 0, 0, 0, 164, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 165, 28, 0, 0, 24, 10, 215, 35, 60, 149, 4, 155, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 160, 15, 0, 0, 24, 246, 40, 32, 65, 128, 2, 137, 27, 149, 0, 0, 0, 0, 66, 121, 32, 104, 97, 110, 100, 32, 109, 111, 118, 101, 32, 116, 104, 101, 32, 101, 120, 45, 0, 149, 1, 0, 0, 0, 116, 114, 117, 100, 101, 114, 32, 116, 111, 32, 100, 105, 102, 102, 101, 114, 101, 110, 116, 32, 0, 149, 1, 0, 0, 0, 112, 111, 115, 105, 116, 105, 111, 110, 115, 32, 111, 118, 101, 114, 32, 116, 104, 101, 32, 32, 0, 149, 7, 0, 0, 0, 98, 117, 105, 108, 100, 32, 112, 108, 97, 116, 102, 111, 114, 109, 46, 46, 46, 46, 0, 149, 0, 0, 0, 0, 65, 100, 106, 117, 115, 116, 32, 116, 104, 101, 32, 115, 112, 97, 99, 105, 110, 103, 32, 32, 0, 149, 1, 0, 0, 0, 98, 101, 116, 119, 101, 101, 110, 32, 116, 104, 101, 32, 101, 120, 116, 114, 117, 100, 101, 114, 0, 149, 1, 0, 0, 0, 110, 111, 122, 122, 108, 101, 32, 97, 110, 100, 32, 112, 108, 97, 116, 102, 111, 114, 109, 32, 0, 149, 7, 0, 0, 0, 119, 105, 116, 104, 32, 116, 104, 101, 32, 107, 110, 111, 98, 115, 46, 46, 46, 0, 149, 0, 0, 0, 0, 117, 110, 100, 101, 114, 32, 116, 104, 101, 32, 112, 108, 97, 116, 102, 111, 114, 109, 32, 32, 0, 149, 1, 0, 0, 0, 97, 110, 100, 32, 97, 32, 115, 104, 101, 101, 116, 32, 111, 102, 32, 112, 97, 112, 101, 114, 0, 149, 1, 0, 0, 0, 112, 108, 97, 99, 101, 100, 32, 98, 101, 116, 119, 101, 101, 110, 32, 116, 104, 101, 32, 32, 0, 149, 7, 0, 0, 0, 112, 108, 97, 116, 102, 111, 114, 109, 32, 97, 110, 100, 32, 116, 104, 101, 46, 46, 46, 0, 149, 0, 0, 0, 0, 110, 111, 122, 122, 108, 101, 46, 32, 87, 104, 101, 110, 32, 121, 111, 117, 32, 97, 114, 101, 0, 149, 1, 0, 0, 0, 100, 111, 110, 101, 44, 32, 112, 114, 101, 115, 115, 32, 116, 104, 101, 32, 32, 32, 32, 32, 0, 149, 7, 0, 0, 0, 99, 101, 110, 116, 101, 114, 32, 98, 117, 116, 116, 111, 110, 46, 0, 137, 31 }; #define LEVEL_PLATE_LEN 571 #endif // ZYYX_3D_PRINTER #if defined(MODEL_REPLICATOR) #if defined(ZYYX_3D_PRINTER) const static PROGMEM prog_uchar SPLASH1_MSG[] = " ZYYX 3D Printer "; #elif defined(AZTEEG_X3) const static PROGMEM prog_uchar SPLASH1_MSG[] = "Sailfish Azteeg X3 "; #elif defined(FF_CREATOR) const static PROGMEM prog_uchar SPLASH1_MSG[] = "Sailfish FF Creator "; #elif defined(FF_CREATOR_X) const static PROGMEM prog_uchar SPLASH1_MSG[] = "Sailfish FF CreatorX"; #elif defined(WANHAO_DUP4) const static PROGMEM prog_uchar SPLASH1_MSG[] = "Wanhao Duplicator 4 "; #elif defined(CORE_XY_STEPPER) const static PROGMEM prog_uchar SPLASH1_MSG[] = "Sailfish Rep CoreXYs"; #elif defined(CORE_XY) const static PROGMEM prog_uchar SPLASH1_MSG[] = "Sailfish Rep1 CoreXY"; #elif defined(CORE_XYZ) const static PROGMEM prog_uchar SPLASH1_MSG[] = "Sailfish R1 CoreXYZ "; #else const static PROGMEM prog_uchar SPLASH1_MSG[] = "Sailfish Replicator1"; #endif #elif defined(MODEL_REPLICATOR2) #ifdef SINGLE_EXTRUDER const static PROGMEM prog_uchar SPLASH1_MSG[] = "Sailfish Replicator2"; #else const static PROGMEM prog_uchar SPLASH1_MSG[] = " Sailfish Rep 2X "; #endif #else #warning "*** Compiling without MODEL_x defined ***" const static PROGMEM prog_uchar SPLASH1_MSG[] = " Sailfish "; #endif #if !defined(HEATERS_ON_STEROIDS) || defined(ZYYX_3D_PRINTER) || defined(FF_CREATOR) || defined(FF_CREATOR_X) || defined(WANHAO_DUP4) const static PROGMEM prog_uchar SPLASH2_MSG[] = "--- Thing 32084 ----"; #else const static PROGMEM prog_uchar SPLASH2_MSG[] = "-- Heater Special --"; #endif #if defined(__AVR_ATmega2560__) const static PROGMEM prog_uchar SPLASH3_MSG[] = "ATmega 2560 " DATE_STR; #else const static PROGMEM prog_uchar SPLASH3_MSG[] = "ATmega 1280 " DATE_STR; #endif const static PROGMEM prog_uchar SPLASH4_MSG[] = "Sailfish v" VERSION_STR " r" SVN_VERSION_STR; #include "locale.hh" #endif // __MENU__LOCALES__
56.967213
2,974
0.602974
[ "model", "3d" ]
a4a71b2d7cf17d1216a237f7dd4d1a9c5483f35a
4,156
cpp
C++
src/editor/Widgets/PropertyEditor.cpp
tedvalson/NovelTea
f731951f25936cb7f5ff23e543e0301c1b5bfe82
[ "MIT" ]
null
null
null
src/editor/Widgets/PropertyEditor.cpp
tedvalson/NovelTea
f731951f25936cb7f5ff23e543e0301c1b5bfe82
[ "MIT" ]
null
null
null
src/editor/Widgets/PropertyEditor.cpp
tedvalson/NovelTea
f731951f25936cb7f5ff23e543e0301c1b5bfe82
[ "MIT" ]
null
null
null
#include "PropertyEditor.hpp" #include "EditorUtils.hpp" #include "ui_PropertyEditor.h" #include <QToolButton> #include <QInputDialog> #include <QMessageBox> #include <QMenu> #include <iostream> PropertyEditor::PropertyEditor(QWidget *parent) : QWidget(parent) , ui(new Ui::PropertyEditor) , m_menuAdd(new QMenu) , m_variantManager(new QtVariantPropertyManager) , m_variantFactory(new QtVariantEditorFactory) , m_value(sj::Object()) { ui->setupUi(this); ui->propertyBrowser->setFactoryForManager(m_variantManager, m_variantFactory); ui->propertyBrowser->setPropertiesWithoutValueMarked(true); m_menuAdd->addAction(ui->actionAddTextProperty); m_menuAdd->addAction(ui->actionAddNumberProperty); m_menuAdd->addAction(ui->actionAddBooleanProperty); // Attach the menu to the Add toolbutton ui->actionAddProperty->setMenu(m_menuAdd); auto buttonAdd = static_cast<QToolButton*>(ui->toolBar->widgetForAction(ui->actionAddProperty)); buttonAdd->setPopupMode(QToolButton::InstantPopup); connect(m_variantManager, &QtVariantPropertyManager::valueChanged, this, &PropertyEditor::update); } PropertyEditor::~PropertyEditor() { delete m_variantFactory; delete m_variantManager; delete m_menuAdd; delete ui; } void PropertyEditor::setValue(sj::JSON value) { if (getValue() != value) { if (value.JSONType() != json::Class::Object) return; QtVariantProperty *prop; ui->propertyBrowser->clear(); m_variantManager->clear(); for (auto &item : value.ObjectRange()) { auto &jval = item.second; auto val = QVariant(); auto type = QVariant::String; if (jval.JSONType() == json::Class::String) { val = EditorUtils::escape(QString::fromStdString(jval.ToString())); } else if (jval.JSONType() == json::Class::Boolean) { type = QVariant::Bool; val = jval.ToBool(); } else if (jval.JSONType() == json::Class::Floating || jval.JSONType() == json::Class::Integral) { type = QVariant::Double; val = static_cast<double>(jval.ToFloat()); } else continue; prop = m_variantManager->addProperty(type, QString::fromStdString(item.first)); prop->setValue(val); ui->propertyBrowser->addProperty(prop); } m_value = value; emit valueChanged(value); } } sj::JSON PropertyEditor::getValue() const { return m_value; } void PropertyEditor::addProperty(int type) { auto propName = QInputDialog::getText(this, "Add Property", "Property Name:"); if (!propName.isEmpty()) { for (auto &prop : ui->propertyBrowser->properties()) if (propName == prop->propertyName()) { QMessageBox::critical(this, "Duplicate Property Name", "A property with that name already exists."); return; } QtVariantProperty *prop; prop = m_variantManager->addProperty(type, propName); ui->propertyBrowser->addProperty(prop); update(); } } void PropertyEditor::addProperty(int type, const QString &name, const QVariant &value) { QtVariantProperty *prop; prop = m_variantManager->addProperty(type, name); prop->setValue(value); ui->propertyBrowser->addProperty(prop); } void PropertyEditor::update() { m_value = sj::Object(); for (auto &prop : ui->propertyBrowser->properties()) { auto name = prop->propertyName().toStdString(); auto type = m_variantManager->valueType(prop); auto value = m_variantManager->value(prop); if (type == QVariant::String) m_value[name] = EditorUtils::unescape(value.toString()).toStdString(); else if (type == QVariant::Double) m_value[name] = value.toDouble(); else if (type == QVariant::Bool) m_value[name] = value.toBool(); } emit valueChanged(m_value); } void PropertyEditor::on_actionRemoveProperty_triggered() { ui->propertyBrowser->removeProperty(ui->propertyBrowser->currentItem()->property()); update(); } void PropertyEditor::on_actionAddTextProperty_triggered() { addProperty(QVariant::String); } void PropertyEditor::on_actionAddNumberProperty_triggered() { addProperty(QVariant::Double); } void PropertyEditor::on_actionAddBooleanProperty_triggered() { addProperty(QVariant::Bool); } void PropertyEditor::on_propertyBrowser_currentItemChanged(QtBrowserItem *item) { ui->actionRemoveProperty->setEnabled(item); }
26.812903
104
0.731954
[ "object" ]
a4ac01d40a4fa65c38f9f97538d345d792fa7179
605
hpp
C++
include/alg/watershed.hpp
InsaneHamster/ihamster
0f09e7eec3dff68ba7c2e899b03fd75940d3e242
[ "MIT" ]
1
2018-01-28T14:10:26.000Z
2018-01-28T14:10:26.000Z
include/alg/watershed.hpp
InsaneHamster/ihamster
0f09e7eec3dff68ba7c2e899b03fd75940d3e242
[ "MIT" ]
null
null
null
include/alg/watershed.hpp
InsaneHamster/ihamster
0f09e7eec3dff68ba7c2e899b03fd75940d3e242
[ "MIT" ]
null
null
null
#pragma once #include <cmn/fwd.hpp> #include <cmn/point.hpp> #include <alg/seg_object.hpp> namespace alg { //on input image in format rgba8 //on output: binary masks of found images. ready to pass to pattern matching //on ouput optionally: colored image to output for debug or other purposes. void watershed( std::vector< seg_object_t > * objects, cmn::image_pt * colored, cmn::image_pt const & img ); //img_lab - f32 CIE L*a*b* format void watershed2( std::vector< seg_object_t > * objects, cmn::image_pt * colored, cmn::image_pt const & img_lab ); void watershed_test(); void watershed2_test(); }
28.809524
113
0.733884
[ "vector" ]
8a54d60b53db9f12f1023420928cb7348f211e21
8,835
cpp
C++
ouzel/graphics/Texture.cpp
keima97/ouzel
e6673e678b4739235371a15ae3863942b692c5fb
[ "BSD-2-Clause" ]
null
null
null
ouzel/graphics/Texture.cpp
keima97/ouzel
e6673e678b4739235371a15ae3863942b692c5fb
[ "BSD-2-Clause" ]
null
null
null
ouzel/graphics/Texture.cpp
keima97/ouzel
e6673e678b4739235371a15ae3863942b692c5fb
[ "BSD-2-Clause" ]
null
null
null
// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include <algorithm> #include "Texture.h" #include "Renderer.h" #include "Image.h" #include "core/Engine.h" #include "utils/Utils.h" #include "math/MathUtils.h" namespace ouzel { namespace graphics { Texture::Texture() { } Texture::~Texture() { } void Texture::free() { levels.clear(); uploadData.levels.clear(); } bool Texture::init(const Size2& newSize, bool newDynamic, bool newMipmaps, bool newRenderTarget) { free(); size = newSize; dynamic = newDynamic; mipmaps = newMipmaps; renderTarget = newRenderTarget; mipMapsGenerated = false; dirty = true; sharedEngine->getRenderer()->scheduleUpdate(shared_from_this()); return true; } bool Texture::initFromFile(const std::string& newFilename, bool newDynamic, bool newMipmaps) { free(); filename = newFilename; Image image; if (!image.initFromFile(filename)) { return false; } return initFromBuffer(image.getData(), image.getSize(), newDynamic, newMipmaps); } bool Texture::initFromBuffer(const std::vector<uint8_t>& newData, const Size2& newSize, bool newDynamic, bool newMipmaps) { free(); dynamic = newDynamic; mipmaps = newMipmaps; renderTarget = false; if (!calculateData(newData, newSize)) { return false; } dirty = true; sharedEngine->getRenderer()->scheduleUpdate(shared_from_this()); return true; } bool Texture::setData(const std::vector<uint8_t>& newData, const Size2& newSize) { if (!dynamic) { return false; } if (newSize.v[0] <= 0.0f || newSize.v[1] <= 0.0f) { return false; } if (!calculateData(newData, newSize)) { return false; } dirty = true; sharedEngine->getRenderer()->scheduleUpdate(shared_from_this()); return true; } static void imageRgba8Downsample2x2(uint32_t width, uint32_t height, uint32_t pitch, const uint8_t* src, uint8_t* dst) { const uint32_t dstwidth = width / 2; const uint32_t dstheight = height / 2; if (dstwidth == 0 || dstheight == 0) { return; } for (uint32_t y = 0, ystep = pitch * 2; y < dstheight; ++y, src += ystep) { const uint8_t* rgba = src; for (uint32_t x = 0; x < dstwidth; ++x, rgba += 8, dst += 4) { float pixels = 0.0f; float r = 0, g = 0, b = 0, a = 0; if (rgba[3] > 0) { r += powf(rgba[0], 2.2f); g += powf(rgba[1], 2.2f); b += powf(rgba[2], 2.2f); pixels += 1.0f; } a = rgba[3]; if (rgba[7] > 0) { r += powf(rgba[4], 2.2f); g += powf(rgba[5], 2.2f); b += powf(rgba[6], 2.2f); pixels += 1.0f; } a += rgba[7]; if (rgba[pitch+3]) { r += powf(rgba[pitch+0], 2.2f); g += powf(rgba[pitch+1], 2.2f); b += powf(rgba[pitch+2], 2.2f); pixels += 1.0f; } a += rgba[pitch+3]; if (rgba[pitch+7] > 0) { r += powf(rgba[pitch+4], 2.2f); g += powf(rgba[pitch+5], 2.2f); b += powf(rgba[pitch+6], 2.2f); pixels += 1.0f; } a += rgba[pitch+7]; if (pixels > 0.0f) { r /= pixels; g /= pixels; b /= pixels; } else { r = g = b = 0; } a *= 0.25f; r = powf(r, 1.0f / 2.2f); g = powf(g, 1.0f / 2.2f); b = powf(b, 1.0f / 2.2f); dst[0] = (uint8_t)r; dst[1] = (uint8_t)g; dst[2] = (uint8_t)b; dst[3] = (uint8_t)a; } } } bool Texture::calculateData(const std::vector<uint8_t>& newData, const Size2& newSize) { levels.clear(); size = newSize; uint32_t newWidth = static_cast<uint32_t>(newSize.v[0]); uint32_t newHeight = static_cast<uint32_t>(newSize.v[1]); uint32_t pitch = newWidth * 4; levels.push_back({ newSize, pitch, newData }); mipMapsGenerated = mipmaps && (sharedEngine->getRenderer()->isNPOTTexturesSupported() || (isPOT(newWidth) && isPOT(newHeight))); if (mipMapsGenerated) { uint32_t bufferSize = newWidth * newHeight * 4; if (newWidth == 1) { bufferSize *= 2; } if (newHeight == 1) { bufferSize *= 2; } std::vector<uint8_t> mipMapData(bufferSize); std::copy(newData.begin(), newData.begin() + static_cast<std::vector<uint8_t>::difference_type>(newWidth * newHeight * 4), mipMapData.begin()); while (newWidth >= 2 && newHeight >= 2) { imageRgba8Downsample2x2(newWidth, newHeight, pitch, mipMapData.data(), mipMapData.data()); newWidth >>= 1; newHeight >>= 1; Size2 mipMapSize = Size2(static_cast<float>(newWidth), static_cast<float>(newHeight)); pitch = newWidth * 4; levels.push_back({ mipMapSize, pitch, mipMapData }); } if (newWidth > newHeight) { for (; newWidth >= 2;) { std::copy(mipMapData.begin(), mipMapData.begin() + static_cast<std::vector<uint8_t>::difference_type>(newWidth * 4), mipMapData.begin() + static_cast<std::vector<uint8_t>::difference_type>(newWidth * 4)); imageRgba8Downsample2x2(newWidth, 2, pitch, mipMapData.data(), mipMapData.data()); newWidth >>= 1; Size2 mipMapSize = Size2(static_cast<float>(newWidth), static_cast<float>(newHeight)); pitch = newWidth * 4; levels.push_back({ mipMapSize, pitch, mipMapData }); } } else { for (; newHeight >= 2;) { uint32_t* src = reinterpret_cast<uint32_t*>(mipMapData.data()); for (int32_t i = static_cast<int32_t>(newHeight) - 1; i >= 0; --i) { src[i * 2] = src[i]; src[i * 2 + 1] = src[i]; } imageRgba8Downsample2x2(2, newHeight, 8, mipMapData.data(), mipMapData.data()); newHeight >>= 1; Size2 mipMapSize = Size2(static_cast<float>(newWidth), static_cast<float>(newHeight)); levels.push_back({ mipMapSize, pitch, mipMapData }); } } } return true; } void Texture::update() { uploadData.size = size; uploadData.dynamic = dynamic; uploadData.mipmaps = mipMapsGenerated; uploadData.dirty = dirty; uploadData.renderTarget = renderTarget; uploadData.levels = std::move(levels); dirty = false; } } // namespace graphics } // namespace ouzel
31.109155
140
0.41811
[ "vector" ]
8a58646d747a9b7be54c5bf0202ca082cf11372d
5,482
cpp
C++
source/Kai/Array.cpp
ioquatix/kai
4f8d00cd05b4123b6389f8dc3187ec1421b4f2da
[ "Unlicense", "MIT" ]
4
2016-07-19T08:53:09.000Z
2021-08-03T10:06:41.000Z
source/Kai/Array.cpp
ioquatix/kai
4f8d00cd05b4123b6389f8dc3187ec1421b4f2da
[ "Unlicense", "MIT" ]
null
null
null
source/Kai/Array.cpp
ioquatix/kai
4f8d00cd05b4123b6389f8dc3187ec1421b4f2da
[ "Unlicense", "MIT" ]
null
null
null
// // Array.cpp // This file is part of the "Kai" project, and is released under the MIT license. // // Created by Samuel Williams on 21/09/10. // Copyright 2010 Orion Transfer Ltd. All rights reserved. // // #include "Array.hpp" #include "Cell.hpp" #include "Frame.hpp" #include "Number.hpp" #include "Table.hpp" #include "Symbol.hpp" #include "Function.hpp" namespace Kai { const char * const Array::NAME = "Array"; Array::Array() { } Array::~Array() { } Ref<Symbol> Array::identity(Frame * frame) const { return frame->sym(NAME); } void Array::mark(Memory::Traversal * traversal) const { for (ConstIteratorT a = _value.begin(); a != _value.end(); a++) { traversal->traverse(*a); } } ComparisonResult Array::compare(const Object * other) const { return derived_compare(this, other); } ComparisonResult Array::compare(const Array * other) const { std::size_t lhs = _value.size(), rhs = other->_value.size(); if (lhs < rhs) return ASCENDING; else if (lhs > rhs) return DESCENDING; ConstIteratorT a = _value.begin(); ConstIteratorT b = other->_value.begin(); for (; a != _value.end(); a++, b++) { ComparisonResult result = (*a)->compare(*b); if (result != 0) return result; } return EQUAL; } void Array::to_code(Frame * frame, StringStreamT & buffer, MarkedT & marks, std::size_t indentation) const { if (marks.find(this) != marks.end()) { buffer << "(Array@" << this << " ...)"; } else { marks.insert(this); buffer << "(Array@" << this; for (ConstIteratorT a = _value.begin(); a != _value.end(); a++) { if (*a) { buffer << " "; (*a)->to_code(frame, buffer, marks, indentation); } else { buffer << " nil"; } } buffer << ")"; } } Ref<Object> Array::new_ (Frame * frame) { Array * array = new(frame) Array(); Cell * items = frame->unwrap()->tail().as<Cell>(); while (items) { array->_value.push_back(items->head()); items = items->tail().as<Cell>(); } return array; } Ref<Object> Array::minimum(Frame * frame) { return NULL; } Ref<Object> Array::maximum(Frame * frame) { return NULL; } Ref<Object> Array::at(Frame * frame) { Array * self = NULL; Integer * _offset = NULL; frame->extract()(self, "self")(_offset, "offset"); std::size_t offset = _offset->value().to_size(); if (offset < self->_value.size()) { return self->_value[offset]; } else { throw RangeError("Index out of bounds", _offset, frame); } } Ref<Object> Array::push_back(Frame * frame) { Array * self = NULL; ArgumentExtractor arguments = frame->extract()(self, "self"); while (arguments) { Object * item = NULL; arguments = arguments(item, "item", false); self->_value.push_back(item); } return self; } Ref<Object> Array::pop_back(Frame * frame) { Array * self = NULL; frame->extract()(self); if (self->_value.size() == 0) return NULL; Object * object = self->_value.back(); self->_value.pop_back(); return object; } Ref<Object> Array::push_front(Frame * frame) { Array * self = NULL; ArgumentExtractor arguments = frame->extract()(self); while (arguments) { Object * item = nullptr; arguments = arguments(item, "item", false); self->_value.push_front(item); } return self; } Ref<Object> Array::pop_front(Frame * frame) { Array * self = NULL; frame->extract()(self); if (self->_value.size() == 0) return NULL; Object * object = self->_value.front(); self->_value.pop_front(); return object; } Ref<Object> Array::append(Frame * frame) { return NULL; } Ref<Object> Array::prepend(Frame * frame) { return NULL; } Ref<Object> Array::insert(Frame * frame) { return NULL; } Ref<Object> Array::includes(Frame * frame) { return NULL; } Ref<Object> Array::each(Frame * frame) { Array * self; Object * callback; frame->extract()(self, "self")(callback, "callback"); for (IteratorT a = self->_value.begin(); a != self->_value.end(); a++) { Cell * message = Cell::create(frame)(callback)(*a); frame->call(message); } return self; } Ref<Object> Array::collect(Frame * frame) { Array * self = NULL; Object * function = NULL; frame->extract()(self)(function); Array * result = new(frame) Array(); for (IteratorT a = self->_value.begin(); a != self->_value.end(); a++) { Cell * message = Cell::create(frame)(function)(*a); Ref<Object> v = frame->call(message); result->_value.push_back(v); } return result; } Ref<Object> Array::select(Frame * frame) { return NULL; } Ref<Object> Array::find(Frame * frame) { return NULL; } void Array::import(Frame * frame) { Table * prototype = new(frame) Table; prototype->update(frame->sym("push-back!"), KAI_BUILTIN_FUNCTION(Array::push_back)); prototype->update(frame->sym("pop-back!"), KAI_BUILTIN_FUNCTION(Array::pop_back)); prototype->update(frame->sym("push-front!"), KAI_BUILTIN_FUNCTION(Array::push_front)); prototype->update(frame->sym("pop-front!"), KAI_BUILTIN_FUNCTION(Array::pop_front)); prototype->update(frame->sym("at"), KAI_BUILTIN_FUNCTION(Array::at)); prototype->update(frame->sym("each"), KAI_BUILTIN_FUNCTION(Array::each)); prototype->update(frame->sym("new"), KAI_BUILTIN_FUNCTION(Array::new_)); frame->update(frame->sym("Array"), prototype); } }
21.084615
107
0.615651
[ "object" ]
8a5cd3a00bf00ecb89688072eefc427ad4d627d2
20,073
cpp
C++
GAPortfolioSelection_PC/GAPortfolioSelection_PC/GAPortfolioSelection_PC.cpp
JinyuShi/Select-and-Optimize-a-S-P-500-Investment-Portfolio-by-Genetic-Algorithm
ea33c28511e0e2f32889e4281308d8e105621d5b
[ "MIT" ]
null
null
null
GAPortfolioSelection_PC/GAPortfolioSelection_PC/GAPortfolioSelection_PC.cpp
JinyuShi/Select-and-Optimize-a-S-P-500-Investment-Portfolio-by-Genetic-Algorithm
ea33c28511e0e2f32889e4281308d8e105621d5b
[ "MIT" ]
null
null
null
GAPortfolioSelection_PC/GAPortfolioSelection_PC/GAPortfolioSelection_PC.cpp
JinyuShi/Select-and-Optimize-a-S-P-500-Investment-Portfolio-by-Genetic-Algorithm
ea33c28511e0e2f32889e4281308d8e105621d5b
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <map> #include <fstream> #include <vector> #include <stdio.h> #include <algorithm> #include "curl_easy.h" #include "curl_form.h" #include "curl_ios.h" #include "curl_exception.h" #include "json/json.h" #include <sqlite3.h> #include "MarketDataLogic.h" #include "DatabaseLogic.h" #include "Stock.h" #include "Portfolio.h" #include "GALogic.h" #include "Utility.h" #define NUM_OF_STOCKS 505 using namespace std; int main(void) { //seed the random number generator srand((int)time(NULL)); //open database const char * stockDB_name = "Stocks.db"; sqlite3 * stockDB = NULL; if (OpenDatabase(stockDB_name, stockDB) == -1) return -1; //initiate required containers to store stock symbols, stocks, and target portfolio vector<string> Symbol; map<string, Stock> Stocks; Portfolio target_portfolio; //get symbols of all stocks string spy_select_table = "SELECT * FROM SP500;"; if (GetStockSymbol(spy_select_table.c_str(), stockDB, Symbol) == -1) return -1; //get trade of SPY Stock SPY("SPY"); string trade_select_table = "SELECT * FROM Stock_SPY;"; if (GetTrade(trade_select_table.c_str(), stockDB, SPY) == -1) return -1; bool done = true; while (done) { string input; cout << "Please select a option number: " << endl << endl << "1: Retrieve SP500 Stock Symbol " << endl << "2: Retrieve Stock Fundamental Data and Save to Database " << endl << "3: Retrieve Stock Trade Data and Save to Database " << endl << "4: Retrieve Risk Free Rate Data and Save to Database " << endl << "5: Construct All Stock Objects " << endl << "6: Create First Generation and Populate 1000 Generations" << endl << "7: Back Testing " << endl << "8: Probation Testing " << endl << "9: Exit " << endl << endl; cin >> input; int option = stoi(input); if (option == 1) { int count = 0; Json::Value json_SPY_All_holdings; ifstream fin("SPY_All_Holdings.txt"); string keys[] = { "Symbol", "Name", "Weight", "Sector", "Shares" }; string line; while (getline(fin, line, '\r')) { const char *begin = line.c_str(); int index = 0; while (const char *end = strchr(begin, ',')) { string column(begin, end - begin); begin = end + 1; json_SPY_All_holdings[count][keys[index++]] = column; } string column(begin); json_SPY_All_holdings[count++][keys[index]] = column; } string spy_drop_table = "DROP TABLE IF EXISTS SP500;"; if (DropTable(spy_drop_table.c_str(), stockDB) == -1) return -1; string spy_create_table = "CREATE TABLE SP500 (id INT PRIMARY KEY NOT NULL, symbol CHAR(20) NOT NULL, name CHAR(20) NOT NULL, sector CHAR(20) NOT NULL, weight REAL NOT NULL, shares INT NOT NULL);"; if (CreateTable(spy_create_table.c_str(), stockDB) == -1) return -1; if (PopulateSPYTable(json_SPY_All_holdings, stockDB) == -1) return -1; string spy_select_table = "SELECT * FROM SP500;"; if (GetStockSymbol(spy_select_table.c_str(), stockDB, Symbol) == -1) return -1; } else if (option == 2) { int count = 1; std::string stockDB_drop_table = "DROP TABLE IF EXISTS Fundamental;"; if (DropTable(stockDB_drop_table.c_str(), stockDB) == -1) return -1; string stockDB_create_table = "CREATE TABLE Fundamental (id INT PRIMARY KEY NOT NULL, symbol CHAR(20) NOT NULL, PERatio REAL NOT NULL, DividendYield REAL NOT NULL, Beta REAL NOT NULL, High_52Week REAL NOT NULL, Low_52Week REAL NOT NULL, MA_50Day REAL NOT NULL, MA_200Day REAL NOT NULL);"; if (CreateTable(stockDB_create_table.c_str(), stockDB) == -1) return -1; for (vector<string>::iterator it = Symbol.begin(); it != Symbol.end(); it++) { cout << *it << endl; string stockfundamental_data_request = "https://eodhistoricaldata.com/api/fundamentals/" + *it + ".US?api_token=5ba84ea974ab42.45160048"; Json::Value stockfundamental_root; if (RetrieveMarketData(stockfundamental_data_request, stockfundamental_root) == -1) return -1; if (PopulateFundamentalTable(stockfundamental_root, count, *it, stockDB) == -1) return -1; count++; } } else if (option == 3) { //Populate Stock_SPY Table std::string stockDB_drop_table = "DROP TABLE IF EXISTS Stock_SPY;"; if (DropTable(stockDB_drop_table.c_str(), stockDB) == -1) return -1; string stockDB_create_table = "CREATE TABLE Stock_SPY (id INT PRIMARY KEY NOT NULL, symbol CHAR(20) NOT NULL, date CHAR(20) NOT NULL, open REAL NOT NULL, high REAL NOT NULL, low REAL NOT NULL, close REAL NOT NULL, adjusted_close REAL NOT NULL, volume INT NOT NULL);"; if (CreateTable(stockDB_create_table.c_str(), stockDB) == -1) return -1; string stockDB_data_request = "https://eodhistoricaldata.com/api/eod/SPY.USfrom=2008-01-01&to=2019-07-31&api_token=5ba84ea974ab42.45160048&period=d&fmt=json"; Json::Value stockDB_root; // will contains the root value after parsing. if (RetrieveMarketData(stockDB_data_request, stockDB_root) == -1) return -1; if (PopulateStockTable(stockDB_root, "Stock_SPY", stockDB) == -1) return -1; string stockDB_select_table = "SELECT * FROM Stock_SPY;"; if (DisplayTable(stockDB_select_table.c_str(), stockDB) == -1) return -1; for (vector<string>::iterator it = Symbol.begin(); it != Symbol.end(); it++) { string stockDB_symbol = "Stock_" + *it; if (stockDB_symbol == "Stock_BRK-B") stockDB_symbol = "Stock_BRK_B"; else if (stockDB_symbol == "Stock_BF-B") stockDB_symbol = "Stock_BF_B"; std::string stockDB_drop_table = "DROP TABLE IF EXISTS " + stockDB_symbol + ";"; if (DropTable(stockDB_drop_table.c_str(), stockDB) == -1) return -1; string stockDB_create_table = "CREATE TABLE " + stockDB_symbol + "(id INT PRIMARY KEY NOT NULL," + "symbol CHAR(20) NOT NULL," + "date CHAR(20) NOT NULL," + "open REAL NOT NULL," + "high REAL NOT NULL," + "low REAL NOT NULL," + "close REAL NOT NULL," + "adjusted_close REAL NOT NULL," + "volume INT NOT NULL);"; if (CreateTable(stockDB_create_table.c_str(), stockDB) == -1) return -1; if (stockDB_symbol != "Stock_MSI") { string stock_url_common = "https://eodhistoricaldata.com/api/eod/"; string stock_start_date = "2008-01-01"; string stock_end_date = "2019-07-31"; string api_token = ""; string stockDB_data_request = stock_url_common + *it + ".US?" + "from=" + stock_start_date + "&to=" + stock_end_date + "&api_token=" + api_token + "&period=d&fmt=json"; Json::Value stockDB_root; // will contains the root value after parsing. if (RetrieveMarketData(stockDB_data_request, stockDB_root) == -1) return -1; if (PopulateStockTable(stockDB_root, stockDB_symbol, stockDB) == -1) return -1; } else { // MSI's trading has several months gap, still want to keep it string stock_url_common = "https://eodhistoricaldata.com/api/eod/"; string stock_start_date1 = "2008-01-01"; string stock_end_date1 = "2017-11-20"; string stock_start_date2 = "2018-01-02"; string stock_end_date2 = "2019-07-31"; string api_token = ""; string stockDB_data_request1 = stock_url_common + *it + ".US?" + "from=" + stock_start_date1 + "&to=" + stock_end_date1 + "&api_token=" + api_token + "&period=d&fmt=json"; string stockDB_data_request2 = stock_url_common + *it + ".US?" + "from=" + stock_start_date2 + "&to=" + stock_end_date2 + "&api_token=" + api_token + "&period=d&fmt=json"; Json::Value stockDB_root1; Json::Value stockDB_root2; if (RetrieveMarketData(stockDB_data_request1, stockDB_root1) == -1) return -1; if (RetrieveMarketData(stockDB_data_request2, stockDB_root2) == -1) return -1; if (PopulateMSITable(stockDB_root1, stockDB_root2, stockDB_symbol, stockDB) == -1) return -1; } string stockDB_select_table = "SELECT * FROM " + stockDB_symbol + ";"; if (DisplayTable(stockDB_select_table.c_str(), stockDB) == -1) return -1; } } else if (option == 4) { std::string riskfreereturn_drop_table = "DROP TABLE IF EXISTS RiskFreeReturn;"; if (DropTable(riskfreereturn_drop_table.c_str(), stockDB) == -1) return -1; string riskfreereturn_create_table = "CREATE TABLE RiskFreeReturn (id INT PRIMARY KEY NOT NULL, date CHAR(20) NOT NULL, adjusted_close REAL NOT NULL);"; if (CreateTable(riskfreereturn_create_table.c_str(), stockDB) == -1) return -1; string riskfreereturn_data_request = "https://eodhistoricaldata.com/api/eod/TNX.INDX?from=2008-01-01&to=2019-07-31&api_token=5ba84ea974ab42.45160048&period=d&fmt=json"; Json::Value riskfreereturn_root; if (RetrieveMarketData(riskfreereturn_data_request, riskfreereturn_root) == -1) return -1; if (PopulateRiskFreeReturnTable(riskfreereturn_root, stockDB) == -1) return -1; } else if (option == 5) { for (vector<string>::iterator it = Symbol.begin(); it != Symbol.end(); it++) { Stocks.insert({ *it,Stock(*it) }); } string fundamental_select_table = "SELECT * FROM Fundamental;"; string riskfreereturn_select_table = "SELECT * FROM RiskFreeReturn;"; string weight_select_table = "SELECT * FROM SP500;"; int count = 1; for (map<string, Stock>::iterator it = Stocks.begin(); it != Stocks.end(); it++) { if (GetFundamental(fundamental_select_table.c_str(), stockDB, it->second) == -1) return -1; if (GetWeight(weight_select_table.c_str(), stockDB, it->second) == -1) return -1; string stockDB_symbol = "Stock_" + it->first; if (stockDB_symbol == "Stock_BRK-B") stockDB_symbol = "Stock_BRK_B"; else if (stockDB_symbol == "Stock_BF-B") stockDB_symbol = "Stock_BF_B"; string trade_select_table = "SELECT * FROM " + stockDB_symbol + ";"; if (GetTrade(trade_select_table.c_str(), stockDB, it->second) == -1) return -1; if (GetRiskfreerates(riskfreereturn_select_table.c_str(), stockDB, it->second) == -1) return -1; (it->second).addDailyReturns(); cout << "Constructed the Stock " << it->first << endl; } } else if (option == 6) { Population population = GetFirstGeneration(Symbol, Stocks); cout << "Created the First Generation" << endl; //sort population by fitness score with descending order std::sort(population.begin(), population.end(), sortByFitness); int generation_number = 1; vector<pair<int, int>> portfolio_pool; cout << "Strat Populating 1000 Generations" << endl; while (generation_number < 40) { cout << "Start Generation " << generation_number + 1 << endl; Population temp; portfolio_pool = Selection(); cout << "Selection done" << endl; //keep the top 2 portfolios temp.push_back(population[0]); cout << "Portfolio 1: " << temp[0]; temp.push_back(population[1]); cout << "Portfolio 2: " << temp[1]; int count = 3; for (vector<pair<int, int>>::iterator it = portfolio_pool.begin(); it != portfolio_pool.end(); it++) { Portfolio p1 = population[it->first]; Portfolio p2 = population[it->second]; //crossover two portfolios Crossover(p1, p2, Stocks); cout << "Portfolio " << count << ": " << p1; temp.push_back(p1); count++; cout << "Portfolio " << count << ": " << p2; temp.push_back(p2); count++; } //mutate the population cout << "Mutating the Population" << endl; Mutate(temp, Symbol, Stocks); cout << "Mutated the Population" << endl; population = temp; //sort the population std::sort(population.begin(), population.end(), sortByFitness); generation_number++; cout << "Finish Generation " << generation_number << endl; if (population[0].fitness == population[99].fitness) { generation_number = MAX_ALLOWABLE_GENERATIONS; cout << "All portfolios have the same fitness number. Population ends!" << endl; } } target_portfolio = population[0]; cout << "The Best Portfolio: " << target_portfolio; vector<string> portfolio_symbol = target_portfolio.GetSymbols(); //insert the symbols of portfolio's stocks into table char portfolio_insert_table[512]; sprintf_s(portfolio_insert_table, "INSERT INTO Best_Portfolios (stock_1, stock_2, stock_3,stock_4,stock_5,stock_6,stock_7,stock_8,stock_9,stock_10 VALUES(\"%s\", \"%s\", \"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")", portfolio_symbol[0].c_str(), portfolio_symbol[1].c_str(), portfolio_symbol[2].c_str(), portfolio_symbol[3].c_str(), portfolio_symbol[4].c_str(), portfolio_symbol[5].c_str(), portfolio_symbol[6].c_str(), portfolio_symbol[7].c_str(), portfolio_symbol[8].c_str(), portfolio_symbol[9].c_str()); if (InsertTable(portfolio_insert_table, stockDB) == -1) return -1; } else if (option == 7) { // the mondays and fridays from 2018-12-31 to 2019-07-01 string buy_day[] = { "2018-12-31","2019-01-07","2019-01-14","2019-01-22","2019-01-28","2019-02-04","2019-02-11","2019-02-19","2019-02-25","2019-03-04","2019-03-11","2019-03-18","2019-03-25","2019-04-01","2019-04-08","2019-04-15","2019-04-22","2019-04-29","2019-05-06","2019-05-13","2019-05-20","2019-05-28","2019-06-03","2019-06-10","2019-06-17","2019-06-24" }; string sell_day[] = { "2019-01-04","2019-01-11","2019-01-18","2019-01-25","2019-02-01","2019-02-08","2019-02-15","2019-02-22","2019-03-01","2019-03-08","2019-03-15","2019-03-22","2019-03-29","2019-04-05","2019-04-12","2019-04-18","2019-04-26","2019-05-03","2019-05-10","2019-05-17","2019-05-24","2019-05-31","2019-06-07","2019-06-14","2019-06-21","2019-06-28" }; vector<string>target_symbol; vector<Stock> target_stock; string portfolio_select_table = "SELECT * FROM Best_Portfolios;"; if (GetPortfolio(portfolio_select_table.c_str(), stockDB, target_symbol) == -1) return -1; for (vector<string>::iterator it = target_symbol.begin(); it != target_symbol.end(); it++) { string weight_select_table = "SELECT * FROM SP500;"; Stock temp = Stock(*it); if (GetWeight(weight_select_table.c_str(), stockDB, temp) == -1) return -1; string stockDB_symbol = "Stock_" + *it; if (stockDB_symbol == "Stock_BRK-B") stockDB_symbol = "Stock_BRK_B"; else if (stockDB_symbol == "Stock_BF-B") stockDB_symbol = "Stock_BF_B"; string trade_select_table = "SELECT * FROM " + stockDB_symbol + ";"; if (GetTrade(trade_select_table.c_str(), stockDB, temp) == -1) return -1; cout << "Constructed the Stock " << *it << endl; target_stock.push_back(temp); } target_portfolio = Portfolio(target_symbol, target_stock); vector<float> Weeks; vector<float> SPY_Weeks; vector<Stock> stocks = target_portfolio.GetStocks(); for (int n = 0; n < (int)(sizeof(buy_day) / sizeof(*buy_day)); n++) { float end_price1 = 0.0; float end_price2 = 0.0; for (vector<Stock>::iterator it = stocks.begin(); it != stocks.end(); it++) { float number = 0.0; vector<Trade> trades = it->gettrade(); for (vector<Trade>::iterator itr = trades.begin(); itr != trades.end(); itr++) { if (itr->getDate() == buy_day[n]) { number = 1000000 * it->weight / itr->getClose(); } else if (itr->getDate() == sell_day[n] && number != 0.0) { end_price1 += number * itr->getClose(); } } } Weeks.push_back(end_price1-1000000); float number = 0.0; vector<Trade> spy_trade = SPY.gettrade(); for (vector<Trade>::iterator itr = spy_trade.begin(); itr != spy_trade.end(); itr++) { if (itr->getDate() == buy_day[n]) { number = 1000000 / itr->getClose(); } else if (itr->getDate() == sell_day[n] && number != 0.0) { end_price2 = number * itr->getClose(); } } SPY_Weeks.push_back(end_price2-1000000); } float earning1 = 0.0; float earning2 = 0.0; //display header cout.width(20); cout.setf(ios::left); cout << "Weeks "; cout.width(20); cout.setf(ios::left); cout << "This Portfolio "; cout.width(20); cout.setf(ios::left); cout<<"SPY Portfolio "; cout.width(20); cout.setf(ios::left); cout << "beats or not "; cout.width(20); cout.setf(ios::left); cout << "Current Position Compared to SPY" << endl; //display backtesting result for (int n = 0; n < Weeks.size(); n++) { cout.width(20); cout.setf(ios::left); cout << "Week " + to_string(n + 1); cout.width(20); cout.setf(ios::left); cout << Weeks[n]; cout.width(20); cout.setf(ios::left); cout << SPY_Weeks[n]; cout.width(20); cout.setf(ios::left); cout << bool(Weeks[n] >= SPY_Weeks[n]); earning1 += Weeks[n]; earning2 += SPY_Weeks[n]; cout.width(20); cout.setf(ios::left); cout << earning1 - earning2 << endl; } cout.width(20); cout.setf(ios::left); cout << "Final position "; cout.width(20); cout.setf(ios::left); cout << earning1; cout.width(20); cout.setf(ios::left); cout << earning2; cout.width(20); cout.setf(ios::left); cout << bool(earning1 >= earning2); cout.width(20); cout.setf(ios::left); cout << earning1 - earning2 << endl; } else if (option == 8) { string July_Monday[] = { "2019-07-01", "2019-07-08" ,"2019-07-15","2019-07-22" }; string July_Friday[] = { "2019-07-05" ,"2019-07-12" ,"2019-07-19","2019-07-26" }; vector<float> Weeks; vector<float> SPY_Weeks; vector<Stock> stocks = target_portfolio.GetStocks(); for (int n = 0; n < (int)(sizeof(July_Monday) / sizeof(*July_Monday)); n++) { float end_price = 0.0; float end_price2 = 0.0; for (vector<Stock>::iterator it = stocks.begin(); it != stocks.end(); it++) { float number = 0.0; vector<Trade> trades = it->gettrade(); for (vector<Trade>::iterator itr = trades.begin(); itr != trades.end(); itr++) { if (itr->getDate() == July_Monday[n]) { number = 1000000 * it->weight / itr->getClose(); } else if (itr->getDate() == July_Friday[n] && number != 0.0) { end_price += number * itr->getClose(); } } } Weeks.push_back(end_price-1000000); float number = 0.0; vector<Trade> spy_trade = SPY.gettrade(); for (vector<Trade>::iterator itr = spy_trade.begin(); itr != spy_trade.end(); itr++) { if (itr->getDate() == July_Monday[n]) { number = 1000000 / itr->getClose(); } else if (itr->getDate() == July_Friday[n] && number != 0.0) { end_price2 = number * itr->getClose(); } } SPY_Weeks.push_back(end_price2-1000000); } float earning1 = 0.0; float earning2 = 0.0; //display header cout.width(20); cout.setf(ios::left); cout << "Weeks "; cout.width(20); cout.setf(ios::left); cout << "This Portfolio "; cout.width(20); cout.setf(ios::left); cout << "SPY Portfolio "; cout.width(20); cout.setf(ios::left); cout << "beats or not "; cout.width(20); cout.setf(ios::left); cout << "Current Position Compared to SPY" << endl; //display probation test result for (int n = 0; n < Weeks.size(); n++) { cout.width(20); cout.setf(ios::left); cout << "Week " + to_string(n + 1); cout.width(20); cout.setf(ios::left); cout << Weeks[n]; cout.width(20); cout.setf(ios::left); cout << SPY_Weeks[n]; cout.width(20); cout.setf(ios::left); cout << bool(Weeks[n] >= SPY_Weeks[n]); earning1 += Weeks[n]; earning2 += SPY_Weeks[n]; cout.width(20); cout.setf(ios::left); cout << earning1 - earning2 << endl; } cout.width(20); cout.setf(ios::left); cout << "Final position "; cout.width(20); cout.setf(ios::left); cout << earning1; cout.width(20); cout.setf(ios::left); cout << earning2; cout.width(20); cout.setf(ios::left); cout << bool(earning1 >= earning2); cout.width(20); cout.setf(ios::left); cout << earning1 - earning2 << endl; } else if (option == 9) { done = false; } else { cout << "Wrong Option! Please input option number from 1 to 8." << endl; } } // Close Database CloseDatabase(stockDB); system("pause"); return 0; }
39.358824
522
0.641957
[ "vector" ]
8a63d526e35a1cfe6337310de58dd5194c07ef37
2,627
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/webkit/ConsoleMessage.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/webkit/ConsoleMessage.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/webkit/ConsoleMessage.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/webkit/ConsoleMessage.h" namespace Elastos { namespace Droid { namespace Webkit { CAR_INTERFACE_IMPL(ConsoleMessage, Object, IConsoleMessage); ConsoleMessage::ConsoleMessage() : mLevel(0) , mLineNumber(0) { } ConsoleMessage::ConsoleMessage( /* [in] */ const String& message, /* [in] */ const String& sourceId, /* [in] */ Int32 lineNumber, /* [in] */ /*MessageLevel*/Int32 msgLevel) { Init(message, sourceId, lineNumber, msgLevel); } ECode ConsoleMessage::constructor( /* [in] */ const String& message, /* [in] */ const String& sourceId, /* [in] */ Int32 lineNumber, /* [in] */ Elastos::Droid::Webkit::MessageLevel msgLevel) { Init(message, sourceId, lineNumber, msgLevel); return NOERROR; } void ConsoleMessage::Init( /* [in] */ const String& message, /* [in] */ const String& sourceId, /* [in] */ Int32 lineNumber, /* [in] */ /*MessageLevel*/Int32 msgLevel) { mMessage = message; mSourceId = sourceId; mLineNumber = lineNumber; mLevel = msgLevel; } ECode ConsoleMessage::MessageLevel( /* [out] */ /*MessageLevel*/Int32* level) { VALIDATE_NOT_NULL(level); *level = mLevel; return NOERROR; } ECode ConsoleMessage::Message( /* [out] */ String* message) { VALIDATE_NOT_NULL(message); *message = mMessage; return NOERROR; } ECode ConsoleMessage::SourceId( /* [out] */ String* id) { VALIDATE_NOT_NULL(id); *id = mSourceId; return NOERROR; } ECode ConsoleMessage::LineNumber( /* [out] */ Int32* number) { VALIDATE_NOT_NULL(number); *number = mLineNumber; return NOERROR; } ECode ConsoleMessage::ToString( /* [out] */ String* info) { VALIDATE_NOT_NULL(info); *info = "ConsoleMessage"; return NOERROR; } } // namespace Webkit } // namespace Droid } // namespace Elastos
25.259615
75
0.629616
[ "object" ]
8a68657b5b44c9bdb78c687ed0e5da53e3d2486d
6,160
cpp
C++
Floating Pixels Esp32Pixel/src/main.cpp
Mechatronikwelt/Swimming-Pixels
29745a4aecc5fb29e80226956ffc704837cedd17
[ "Unlicense" ]
null
null
null
Floating Pixels Esp32Pixel/src/main.cpp
Mechatronikwelt/Swimming-Pixels
29745a4aecc5fb29e80226956ffc704837cedd17
[ "Unlicense" ]
null
null
null
Floating Pixels Esp32Pixel/src/main.cpp
Mechatronikwelt/Swimming-Pixels
29745a4aecc5fb29e80226956ffc704837cedd17
[ "Unlicense" ]
null
null
null
//----------------------------------------------- // Program: Swimming Pixel Slave (ESP32) // File: Main // Karlsruhe University of Applied Science // Authors: Patrick Rodinger, Lukas Reimold // Current Status: Release (22.04.2020) //------------------------------------------------ #include <WiFi.h> #include <MQTT.h> #include <SPI.h> #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #include "CPixel.h" //-------------------Creating pixel with position parameters---------------------- CPixel pixel(0.75,0.75); //-----------------------Defines for OLED display--------------------------------- #define SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 64 // OLED display height, in pixels // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins) #define OLED_RESET false // Reset pin # (or -1 if sharing Arduino reset pin) Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); //------------------------Defines for Neo-Pixel ring ------------------------------ #define LED_PIN 18 // Which pin on the Arduino is connected to the NeoPixels? // On a Trinket or Gemma we suggest changing this to 1: #define LED_COUNT 15 // How many NeoPixels are attached to the Arduino? Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800); //---------------------------Defines Wifi Connection ------------------------------ const char ssid[] = "ObiWlanKenobi"; // Enter hotspot name const char pass[] = "12344321"; // Enter hotspot password const char MQTT_BROKER_ADDRESS[] = "192.168.137.1"; //Enter the IPv4-Adress of the MQTT Broker WiFiClient net; MQTTClient client(25000); //sets maximum message-size to ~25kB //-------------------------------Defines MQTT topics------------------------------ const char TOPIC_PIXEL_RGB_COORDS[] = "pixel/rgbCoords"; const char TOPIC_PIXEL_POSITION[] = "pixel/position"; //-----------------------------Function Prototypes---------------------------------- ///Function to set every LED of the NeoPixel to one color void setEveryPixelColor(int * pColor); //Function to establish connection to WiFi and MQTT void connect(); //Function gets called on receiving a message via MQTT void messageReceived(String &topic, String &input); //-----------------------------Display-Helper-Functions---------------------------------- void clearDisplay() { display.clearDisplay(); display.setCursor(0,0); } void printlnAndDisplay(String msg) { display.println(msg); display.display(); } void printAndDisplay(String msg) { display.print(msg); display.display(); } void updateDisplay() { clearDisplay(); display.println("Connected to Broker."); display.println(""); display.println("Current position: "); display.println(pixel.getPositionString()); display.println(""); display.println("Current color: "); display.println(pixel.getColorString()); display.println(""); display.display(); } void log(String message) { Serial.println(message.c_str()); } //-----------------------gets called on startup-------------------- void setup() { Serial.begin(115200); //------------------------OLED-Display-------------------------- if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x64 Serial.println(F("SSD1306 allocation failed")); for(;;); // Don't proceed, loop forever } clearDisplay(); display.setTextSize(1); display.setTextColor(WHITE); //------------------------Neo Pixel------------------------------- strip.begin(); strip.show(); //--------------------WIFI & MQTT Connection---------------------------- client.begin(MQTT_BROKER_ADDRESS, net); //Set the IP address directly. client.onMessage(messageReceived); //Set wich function to call on receiving a MQTT message connect(); //connect to WiFi and MQTT } void loop() { client.loop(); // function to check for new message arrivals if (!client.connected()) { // in case of connection loss, the client reconnects connect(); updateDisplay(); } delay(500); } //Sets every LED of the Neo Pixel strip to one color void setEveryPixelColor(int * pColor) { for( int i=0; i<LED_COUNT; i++) { strip.setPixelColor(i , pColor[0], pColor[1], pColor[2]); // (Led-number, Color) } strip.show(); } void messageReceived(String &topic, String &input) { //-----------------------if clauses between topics---------------------------------- if (topic == TOPIC_PIXEL_RGB_COORDS) pixel.updateColor(input); //updates color inside pixel object else if(topic == TOPIC_PIXEL_POSITION) // topic to test different position parameters (ireleveant in release version) pixel.setPosition(input); setEveryPixelColor(pixel.getColor()); // function to update neo pixel strip updateDisplay(); } void connect() { // Checking WiFi-Connection int i=0; log("Checking wifi"); clearDisplay(); printlnAndDisplay("Checking wifi"); WiFi.begin(ssid, pass); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); printAndDisplay("."); i++; if ( i== 20) { clearDisplay(); display.println("Checking wifi"); i=0; } } log("\nConnected!"); display.println(""); printlnAndDisplay("Connected!"); delay(2000); //--------------------Connection to Broker--------------- log("\nConnecting to Broker"); clearDisplay(); printlnAndDisplay("Connecting to Broker"); while (!client.connect(WiFi.macAddress().c_str(), "try", "try")) { Serial.print("."); printAndDisplay("."); i++; if ( i== 20) { clearDisplay(); display.println("Connecting to Broker"); i=0; } } log("\nConnected!"); display.println(""); printlnAndDisplay("Connected!"); delay(2000); //---------------Subscribe to Topics-------------------- client.subscribe(TOPIC_PIXEL_RGB_COORDS); client.subscribe(TOPIC_PIXEL_POSITION); updateDisplay(); }
30.8
137
0.578084
[ "object" ]
8a725bacf37d30bc869ab6c504eae0e596804bbe
16,837
cpp
C++
src/Layers/xrRender/ModelPool.cpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
2
2015-02-23T10:43:02.000Z
2015-06-11T14:45:08.000Z
src/Layers/xrRender/ModelPool.cpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
17
2022-01-25T08:58:23.000Z
2022-03-28T17:18:28.000Z
src/Layers/xrRender/ModelPool.cpp
clayne/xray-16
32ebf81a252c7179e2824b2874f911a91e822ad1
[ "OML", "Linux-OpenIB" ]
1
2015-06-05T20:04:00.000Z
2015-06-05T20:04:00.000Z
#include "stdafx.h" #include "ModelPool.h" #ifndef _EDITOR #include "xrEngine/IGame_Persistent.h" #include "xrCore/FMesh.hpp" #include "FHierrarhyVisual.h" #include "SkeletonAnimated.h" #include "FVisual.h" #include "FProgressive.h" #include "FSkinned.h" #include "FLOD.h" #include "FTreeVisual.h" #include "ParticleGroup.h" #include "ParticleEffect.h" #else #include "FMesh.h" #include "FVisual.h" #include "FProgressive.h" #include "ParticleEffect.h" #include "ParticleGroup.h" #include "FSkinned.h" #include "FHierrarhyVisual.h" #include "SkeletonAnimated.h" #include "IGame_Persistent.h" #endif dxRender_Visual* CModelPool::Instance_Create(u32 type) { dxRender_Visual* V = nullptr; // Check types switch (type) { case MT_NORMAL: // our base visual V = xr_new<Fvisual>(); break; case MT_HIERRARHY: V = xr_new<FHierrarhyVisual>(); break; case MT_PROGRESSIVE: // dynamic-resolution visual V = xr_new<FProgressive>(); break; case MT_SKELETON_ANIM: V = xr_new<CKinematicsAnimated>(); break; case MT_SKELETON_RIGID: V = xr_new<CKinematics>(); break; case MT_SKELETON_GEOMDEF_PM: V = xr_new<CSkeletonX_PM>(); break; case MT_SKELETON_GEOMDEF_ST: V = xr_new<CSkeletonX_ST>(); break; case MT_PARTICLE_EFFECT: V = xr_new<PS::CParticleEffect>(); break; case MT_PARTICLE_GROUP: V = xr_new<PS::CParticleGroup>(); break; #ifndef _EDITOR case MT_LOD: V = xr_new<FLOD>(); break; case MT_TREE_ST: V = xr_new<FTreeVisual_ST>(); break; case MT_TREE_PM: V = xr_new<FTreeVisual_PM>(); break; #endif default: FATAL("Unknown visual type"); break; } R_ASSERT(V); V->Type = type; return V; } dxRender_Visual* CModelPool::Instance_Duplicate(dxRender_Visual* V) { R_ASSERT(V); dxRender_Visual* N = Instance_Create(V->Type); N->Copy(V); N->Spawn(); // inc ref counter for (xr_vector<ModelDef>::iterator I = Models.begin(); I != Models.end(); ++I) if (I->model == V) { I->refs++; break; } return N; } dxRender_Visual* CModelPool::Instance_Load(const char* N, BOOL allow_register) { dxRender_Visual* V; string_path fn; string_path name; // Add default ext if no ext at all if (nullptr == strext(N)) strconcat(sizeof(name), name, N, ".ogf"); else xr_strcpy(name, sizeof(name), N); // Load data from MESHES or LEVEL if (!FS.exist(N)) { if (!FS.exist(fn, "$level$", name)) if (!FS.exist(fn, "$game_meshes$", name)) { #ifdef _EDITOR Msg("! Can't find model file '%s'.", name); return 0; #else xrDebug::Fatal(DEBUG_INFO, "Can't find model file '%s'.", name); #endif } } else { xr_strcpy(fn, N); } // Actual loading #ifdef DEBUG if (bLogging) Msg("- Uncached model loading: %s", fn); #endif // DEBUG IReader* data = FS.r_open(fn); ogf_header H; data->r_chunk_safe(OGF_HEADER, &H, sizeof(H)); V = Instance_Create(H.type); V->Load(N, data, 0); FS.r_close(data); g_pGamePersistent->RegisterModel(V); // Registration if (allow_register) Instance_Register(N, V); return V; } dxRender_Visual* CModelPool::Instance_Load(LPCSTR name, IReader* data, BOOL allow_register) { dxRender_Visual* V; ogf_header H; data->r_chunk_safe(OGF_HEADER, &H, sizeof(H)); V = Instance_Create(H.type); V->Load(name, data, 0); // Registration if (allow_register) Instance_Register(name, V); return V; } void CModelPool::Instance_Register(LPCSTR N, dxRender_Visual* V) { // Registration ModelDef M; M.name = N; M.model = V; Models.push_back(M); } void CModelPool::Destroy() { // Pool Pool.clear(); // Registry while (!Registry.empty()) { REGISTRY_IT it = Registry.begin(); dxRender_Visual* V = (dxRender_Visual*)it->first; #ifdef _DEBUG Msg("ModelPool: Destroy object: '%s'", *V->dbg_name); #endif DeleteInternal(V, TRUE); } // Base/Reference xr_vector<ModelDef>::iterator I = Models.begin(); xr_vector<ModelDef>::iterator E = Models.end(); for (; I != E; ++I) { I->model->Release(); xr_delete(I->model); } Models.clear(); // cleanup motions container g_pMotionsContainer->clean(false); } CModelPool::CModelPool() { bLogging = TRUE; bForceDiscard = FALSE; bAllowChildrenDuplicate = TRUE; g_pMotionsContainer = xr_new<motions_container>(); } CModelPool::~CModelPool() { Destroy(); xr_delete(g_pMotionsContainer); } dxRender_Visual* CModelPool::Instance_Find(LPCSTR N) { dxRender_Visual* Model = nullptr; xr_vector<ModelDef>::iterator I; for (I = Models.begin(); I != Models.end(); ++I) { if (I->name[0] && (0 == xr_strcmp(*I->name, N))) { Model = I->model; break; } } return Model; } dxRender_Visual* CModelPool::Create(const char* name, IReader* data) { #ifdef _EDITOR if (!name || !name[0]) return 0; #endif string_path low_name; VERIFY(xr_strlen(name) < sizeof(low_name)); xr_strcpy(low_name, name); xr_strlwr(low_name); if (strext(low_name)) *strext(low_name) = 0; // Msg ("-CREATE %s",low_name); // 0. Search POOL POOL_IT it = Pool.find(low_name); if (it != Pool.end()) { // 1. Instance found dxRender_Visual* Model = it->second; Model->Spawn(); Pool.erase(it); return Model; } else { // 1. Search for already loaded model (reference, base model) dxRender_Visual* Base = Instance_Find(low_name); if (nullptr == Base) { // 2. If not found bAllowChildrenDuplicate = FALSE; if (data) Base = Instance_Load(low_name, data, TRUE); else Base = Instance_Load(low_name, TRUE); bAllowChildrenDuplicate = TRUE; #ifdef _EDITOR if (!Base) return 0; #endif } // 3. If found - return (cloned) reference dxRender_Visual* Model = Instance_Duplicate(Base); Registry.insert(std::make_pair(Model, low_name)); return Model; } } dxRender_Visual* CModelPool::CreateChild(LPCSTR name, IReader* data) { string256 low_name; VERIFY(xr_strlen(name) < 256); xr_strcpy(low_name, name); xr_strlwr(low_name); if (strext(low_name)) *strext(low_name) = 0; // 1. Search for already loaded model dxRender_Visual* Base = Instance_Find(low_name); //. if (0==Base) Base = Instance_Load(name,data,FALSE); if (nullptr == Base) { if (data) Base = Instance_Load(low_name, data, FALSE); else Base = Instance_Load(low_name, FALSE); } dxRender_Visual* Model = bAllowChildrenDuplicate ? Instance_Duplicate(Base) : Base; return Model; } extern bool ENGINE_API g_bRendering; void CModelPool::DeleteInternal(dxRender_Visual*& V, BOOL bDiscard) { VERIFY(!g_bRendering); if (!V) return; V->Depart(); if (bDiscard || bForceDiscard) { Discard(V, TRUE); } else { // REGISTRY_IT it = Registry.find(V); if (it != Registry.end()) { // Registry entry found - move it to pool Pool.insert(std::make_pair(it->second, V)); } else { // Registry entry not-found - just special type of visual / particles / etc. xr_delete(V); } } V = nullptr; } void CModelPool::Delete(dxRender_Visual*& V, BOOL bDiscard) { if (nullptr == V) return; if (g_bRendering) { VERIFY(!bDiscard); ModelsToDelete.push_back(V); } else { DeleteInternal(V, bDiscard); } V = nullptr; } void CModelPool::DeleteQueue() { for (u32 it = 0; it < ModelsToDelete.size(); it++) DeleteInternal(ModelsToDelete[it]); ModelsToDelete.clear(); } void CModelPool::Discard(dxRender_Visual*& V, BOOL b_complete) { // REGISTRY_IT it = Registry.find(V); if (it != Registry.end()) { // Pool - OK // Base const shared_str& name = it->second; xr_vector<ModelDef>::iterator I = Models.begin(); xr_vector<ModelDef>::iterator I_e = Models.end(); for (; I != I_e; ++I) { if (I->name == name) { if (b_complete || strchr(*name, '#')) { VERIFY(I->refs > 0); I->refs--; if (0 == I->refs) { bForceDiscard = TRUE; I->model->Release(); xr_delete(I->model); Models.erase(I); bForceDiscard = FALSE; } break; } else { if (I->refs > 0) I->refs--; break; } } } // Registry xr_delete(V); //. xr_free (name); Registry.erase(it); } else { // Registry entry not-found - just special type of visual / particles / etc. xr_delete(V); } V = nullptr; } void CModelPool::Prefetch() { Logging(FALSE); // prefetch visuals string256 section; strconcat(sizeof(section), section, "prefetch_visuals_", g_pGamePersistent->m_game_params.m_game_type); const CInifile::Sect& sect = pSettings->r_section(section); for (auto I = sect.Data.cbegin(); I != sect.Data.cend(); ++I) { const CInifile::Item& item = *I; dxRender_Visual* V = Create(item.first.c_str()); Delete(V, FALSE); } Logging(TRUE); } void CModelPool::ClearPool(BOOL b_complete) { POOL_IT _I = Pool.begin(); POOL_IT _E = Pool.end(); for (; _I != _E; ++_I) { Discard(_I->second, b_complete); } Pool.clear(); } dxRender_Visual* CModelPool::CreatePE(PS::CPEDef* source) { PS::CParticleEffect* V = (PS::CParticleEffect*)Instance_Create(MT_PARTICLE_EFFECT); V->Compile(source); return V; } dxRender_Visual* CModelPool::CreatePG(PS::CPGDef* source) { PS::CParticleGroup* V = (PS::CParticleGroup*)Instance_Create(MT_PARTICLE_GROUP); V->Compile(source); return V; } void CModelPool::dump() { Log("--- model pool --- begin:"); u32 sz = 0; u32 k = 0; for (xr_vector<ModelDef>::iterator I = Models.begin(); I != Models.end(); ++I) { CKinematics* K = PCKinematics(I->model); if (K) { u32 cur = K->mem_usage(false); sz += cur; Msg("#%3d: [%3d/%5d Kb] - %s", k++, I->refs, cur / 1024, I->name.c_str()); } } Msg("--- models: %d, mem usage: %d Kb ", k, sz / 1024); sz = 0; k = 0; int free_cnt = 0; for (REGISTRY_IT it = Registry.begin(); it != Registry.end(); ++it) { CKinematics* K = PCKinematics((dxRender_Visual*)it->first); VERIFY(K); if (K) { u32 cur = K->mem_usage(true); sz += cur; bool b_free = (Pool.find(it->second) != Pool.end()); if (b_free) ++free_cnt; Msg("#%3d: [%s] [%5d Kb] - %s", k++, (b_free) ? "free" : "used", cur / 1024, it->second.c_str()); } } Msg("--- instances: %d, free %d, mem usage: %d Kb ", k, free_cnt, sz / 1024); Log("--- model pool --- end."); } void CModelPool::memory_stats(u32& vb_mem_video, u32& vb_mem_system, u32& ib_mem_video, u32& ib_mem_system) { vb_mem_video = 0; vb_mem_system = 0; ib_mem_video = 0; ib_mem_system = 0; xr_vector<ModelDef>::iterator it = Models.begin(); xr_vector<ModelDef>::const_iterator en = Models.end(); for (; it != en; ++it) { dxRender_Visual* ptr = it->model; Fvisual* vis_ptr = dynamic_cast<Fvisual*>(ptr); if (vis_ptr == nullptr) continue; ib_mem_video += vis_ptr->m_fast->p_rm_Indices->GetVideoMemoryUsage(); ib_mem_system += vis_ptr->m_fast->p_rm_Indices->GetSystemMemoryUsage(); vb_mem_video += vis_ptr->m_fast->p_rm_Vertices->GetVideoMemoryUsage(); vb_mem_system += vis_ptr->m_fast->p_rm_Vertices->GetSystemMemoryUsage(); } } #ifdef _EDITOR IC bool _IsBoxVisible(dxRender_Visual* visual, const Fmatrix& transform) { Fbox bb; bb.xform(visual->vis.box, transform); return GEnv.Render->occ_visible(bb); } IC bool _IsValidShader(dxRender_Visual* visual, u32 priority, bool strictB2F) { if (visual->shader) return (priority == visual->shader->E[0]->flags.iPriority) && (strictB2F == visual->shader->E[0]->flags.bStrictB2F); return false; } void CModelPool::Render( dxRender_Visual* m_pVisual, const Fmatrix& mTransform, int priority, bool strictB2F, float m_fLOD) { // render visual xr_vector<dxRender_Visual *>::iterator I, E; switch (m_pVisual->Type) { case MT_SKELETON_ANIM: case MT_SKELETON_RIGID: { if (_IsBoxVisible(m_pVisual, mTransform)) { CKinematics* pV = dynamic_cast<CKinematics*>(m_pVisual); VERIFY(pV); if (fis_zero(m_fLOD, EPS) && pV->m_lod) { if (_IsValidShader(pV->m_lod, priority, strictB2F)) { RCache.set_Shader(pV->m_lod->shader ? pV->m_lod->shader : EDevice.m_WireShader); RCache.set_xform_world(mTransform); pV->m_lod->Render(1.f); } } else { I = pV->children.begin(); E = pV->children.end(); for (; I != E; I++) { if (_IsValidShader(*I, priority, strictB2F)) { RCache.set_Shader((*I)->shader ? (*I)->shader : EDevice.m_WireShader); RCache.set_xform_world(mTransform); (*I)->Render(m_fLOD); } } } } } break; case MT_HIERRARHY: { if (_IsBoxVisible(m_pVisual, mTransform)) { FHierrarhyVisual* pV = dynamic_cast<FHierrarhyVisual*>(m_pVisual); VERIFY(pV); I = pV->children.begin(); E = pV->children.end(); for (; I != E; I++) { if (_IsValidShader(*I, priority, strictB2F)) { RCache.set_Shader((*I)->shader ? (*I)->shader : EDevice.m_WireShader); RCache.set_xform_world(mTransform); (*I)->Render(m_fLOD); } } } } break; case MT_PARTICLE_GROUP: { PS::CParticleGroup* pG = dynamic_cast<PS::CParticleGroup*>(m_pVisual); VERIFY(pG); // if (_IsBoxVisible(m_pVisual,mTransform)) { RCache.set_xform_world(mTransform); for (PS::CParticleGroup::SItemVecIt i_it = pG->items.begin(); i_it != pG->items.end(); i_it++) { xr_vector<dxRender_Visual*> visuals; i_it->GetVisuals(visuals); for (xr_vector<dxRender_Visual*>::iterator it = visuals.begin(); it != visuals.end(); it++) Render(*it, Fidentity, priority, strictB2F, m_fLOD); } } } break; case MT_PARTICLE_EFFECT: { // if (_IsBoxVisible(m_pVisual,mTransform)) { if (_IsValidShader(m_pVisual, priority, strictB2F)) { RCache.set_Shader(m_pVisual->shader ? m_pVisual->shader : EDevice.m_WireShader); RCache.set_xform_world(mTransform); m_pVisual->Render(m_fLOD); } } } break; default: if (_IsBoxVisible(m_pVisual, mTransform)) { if (_IsValidShader(m_pVisual, priority, strictB2F)) { RCache.set_Shader(m_pVisual->shader ? m_pVisual->shader : EDevice.m_WireShader); RCache.set_xform_world(mTransform); m_pVisual->Render(m_fLOD); } } break; } } void CModelPool::RenderSingle(dxRender_Visual* m_pVisual, const Fmatrix& mTransform, float m_fLOD) { for (int p = 0; p < 4; p++) { Render(m_pVisual, mTransform, p, false, m_fLOD); Render(m_pVisual, mTransform, p, true, m_fLOD); } } void CModelPool::OnDeviceDestroy() { Destroy(); } #endif
27.025682
109
0.556572
[ "render", "object", "model", "transform", "3d" ]
8a7e50ace56c61f58d890ee8519812abb57f0c1a
1,827
cxx
C++
ants/lib/LOCAL_SmoothImage.cxx
xemio/ANTsPy
ef610318e217bb04d3850d480c2e51df695d56c0
[ "Apache-2.0" ]
338
2017-09-01T06:47:54.000Z
2022-03-31T12:11:46.000Z
ants/lib/LOCAL_SmoothImage.cxx
xemio/ANTsPy
ef610318e217bb04d3850d480c2e51df695d56c0
[ "Apache-2.0" ]
306
2017-08-30T20:05:07.000Z
2022-03-31T16:20:44.000Z
ants/lib/LOCAL_SmoothImage.cxx
xemio/ANTsPy
ef610318e217bb04d3850d480c2e51df695d56c0
[ "Apache-2.0" ]
115
2017-09-08T11:53:17.000Z
2022-03-27T05:53:39.000Z
#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <exception> #include <algorithm> #include <vector> #include "itkDiscreteGaussianImageFilter.h" #include "LOCAL_antsImage.h" namespace py = pybind11; template <typename ImageType> py::capsule smoothImage( py::capsule ants_inimg, std::vector<double> sigma, bool sigmaInPhysicalCoordinates, unsigned int kernelwidth) { typedef typename ImageType::Pointer ImagePointerType; typename ImageType::Pointer inimg = as< ImageType >( ants_inimg ); typedef itk::DiscreteGaussianImageFilter< ImageType, ImageType > discreteGaussianImageFilterType; typename discreteGaussianImageFilterType::Pointer filter = discreteGaussianImageFilterType::New(); const unsigned int ImageDimension = ImageType::ImageDimension; if ( !sigmaInPhysicalCoordinates ) { filter->SetUseImageSpacingOff(); } else { filter->SetUseImageSpacingOn(); } if ( sigma.size() == 1 ) { filter->SetVariance( sigma[0] * sigma[0]); } else if ( sigma.size() == ImageDimension ) { typename discreteGaussianImageFilterType::ArrayType varianceArray; for( unsigned int d = 0; d < ImageDimension; d++ ) { varianceArray[d] = sigma[d] * sigma[d]; } filter->SetVariance( varianceArray ); } filter->SetMaximumKernelWidth(kernelwidth); filter->SetMaximumError( 0.01f ); filter->SetInput( inimg ); filter->Update(); py::capsule ants_outimg = wrap<ImageType>( filter->GetOutput() ); return ants_outimg; } PYBIND11_MODULE(SmoothImage, m) { m.def("SmoothImage2D", &smoothImage<itk::Image<float, 2>>); m.def("SmoothImage3D", &smoothImage<itk::Image<float, 3>>); m.def("SmoothImage4D", &smoothImage<itk::Image<float, 4>>); }
28.107692
100
0.679803
[ "vector" ]
8a7e7c4968fd3bd9cfe57cbdd809dad9f8739da8
940
hpp
C++
Server/include/OperationStatusHandlers/TCPOperationStatusHandler.hpp
arokasprz100/Proxy_server
5393613dd2b744814d1151d2aee93767d67646bd
[ "MIT" ]
3
2020-05-18T02:05:34.000Z
2020-05-18T04:42:46.000Z
Server/include/OperationStatusHandlers/TCPOperationStatusHandler.hpp
arokasprz100/Proxy_server
5393613dd2b744814d1151d2aee93767d67646bd
[ "MIT" ]
null
null
null
Server/include/OperationStatusHandlers/TCPOperationStatusHandler.hpp
arokasprz100/Proxy_server
5393613dd2b744814d1151d2aee93767d67646bd
[ "MIT" ]
1
2019-06-08T17:07:58.000Z
2019-06-08T17:07:58.000Z
/** * @file TCPOperationStatusHandler.hpp * @brief This file contains the definition of the plain HTTP connection to proxy handler. */ #ifndef TCPOperationStatusHandler_hpp #define TCPOperationStatusHandler_hpp #include "../Client.hpp" /** * @class TCPOperationStatusHandler */ class TCPOperationStatusHandler final { public: /** * This member function implements handling of client plain HTTP to proxy connection. * @param client Given client object from the Server's std::vector of clients. * @see Client * @param operationStatus Value returned by either send() or recv() call. * @param clientConnectionPollFD Appropriate iterator to the position of the pollfd struct in the main server class' std::vector on which poll() function is used. */ static void handle(Client& client, int operationStatus, std::vector<pollfd>::iterator clientConnectionPollFD); }; #endif // TCPOperationStatusHandler_hpp
33.571429
164
0.755319
[ "object", "vector" ]
8a7eec3e9fa06cc67cea3de4a59ac26106bc4001
1,019
cpp
C++
1062_Talent_and_Virtue/1062_Talent_and_Virtue/1062_Talent_and_Virtue.cpp
Iluvata/PAT-Advanced-Level-Practice
08a02e82eef30c81ed9ef8e4f327f7b2a9535582
[ "MIT" ]
2
2020-10-17T12:26:42.000Z
2021-11-12T08:47:10.000Z
1062_Talent_and_Virtue/1062_Talent_and_Virtue/1062_Talent_and_Virtue.cpp
Iluvata/PAT-Advanced-Level-Practice
08a02e82eef30c81ed9ef8e4f327f7b2a9535582
[ "MIT" ]
1
2020-10-19T11:31:55.000Z
2020-10-19T11:31:55.000Z
1062_Talent_and_Virtue/1062_Talent_and_Virtue/1062_Talent_and_Virtue.cpp
Iluvata/PAT-Advanced-Level-Practice
08a02e82eef30c81ed9ef8e4f327f7b2a9535582
[ "MIT" ]
1
2020-10-18T01:08:34.000Z
2020-10-18T01:08:34.000Z
// 1062_Talent_and_Virtue.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include "pch.h" #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int n, l, h; struct Grade { string id; int r; int v; int t; }; bool cmp(Grade &g1, Grade &g2) { if (g1.r == g2.r) { if (g1.v + g1.t == g2.v + g2.t) { if (g1.v == g2.v) { return g1.id < g2.id; } return g1.v > g2.v; } return g1.v + g1.t > g2.v + g2.t; } return g1.r < g2.r; } int main() { vector<Grade> rank; cin >> n >> l >> h; Grade g; for (int i = 0; i < n; ++i) { cin >> g.id >> g.v >> g.t; if (g.t >= l && g.v >= l) { if (g.t >= h && g.v >= h) { g.r = 1; } else if (g.v >= h) { g.r = 2; } else if (g.v >= g.t) { g.r = 3; } else { g.r = 4; } rank.push_back(g); } } cout << rank.size() << endl; sort(rank.begin(), rank.end(), cmp); for (int i = 0; i < rank.size(); ++i) { cout << rank[i].id << " " << rank[i].v << " " << rank[i].t << endl; } }
16.174603
69
0.473013
[ "vector" ]
8a839a7c99d8dbfa5e778fa77572e63a8a0f3087
1,531
cpp
C++
Graph/Network Flow/Variants/Angry Programmer.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
3
2017-08-12T06:09:39.000Z
2018-09-16T02:31:27.000Z
Graph/Network Flow/Variants/Angry Programmer.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
null
null
null
Graph/Network Flow/Variants/Angry Programmer.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector <int> vi; #define inf (int)1e9 int n, m, f, mf, s, t, res[105][105]; vi p; void augment(int v, int minEdge){ if(v == s) f = minEdge; else if(p[v] != -1){ augment(p[v], min(minEdge, res[p[v]][v])); res[p[v]][v] -= f; res[v][p[v]] += f; } } void EdmondKarp(){ mf = 0; while(true){ f = 0; p.assign(105, -1); queue <int> q; q.push(s); bitset <105> visited; visited.set(s); while(!q.empty()){ int u = q.front(); q.pop(); if(u == t) break; for(int v=0; v<=2*n; v++){ if(res[u][v] > 0 && !visited.test(v)){ visited.set(v); q.push(v); p[v] = u; } } } augment(t, inf); if(!f) break; mf += f; } } int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); int u, v, w; while(cin >> n >> m, n||m){ memset(res, 0, sizeof res); s = 0; t = n-1; res[0][n] = inf; for(int i=0; i<n-2; i++){ cin >> u >> v; u--; res[u][u+n] = v; } for(int i=0; i<m; i++){ cin >> u >> v >> w; u--; v--; res[u+n][v] = w; res[v+n][u] = w; } res[n-1][n+n-1] = inf; EdmondKarp(); cout << mf << "\n"; } return 0; }
24.301587
54
0.397126
[ "vector" ]
8a882e04458b98652045e4d974a2c8a44d593933
1,313
hpp
C++
src/modules/timesync/server.hpp
DerangedMonkeyNinja/openperf
cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16
[ "Apache-2.0" ]
20
2019-12-04T01:28:52.000Z
2022-03-17T14:09:34.000Z
src/modules/timesync/server.hpp
DerangedMonkeyNinja/openperf
cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16
[ "Apache-2.0" ]
115
2020-02-04T21:29:54.000Z
2022-02-17T13:33:51.000Z
src/modules/timesync/server.hpp
DerangedMonkeyNinja/openperf
cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16
[ "Apache-2.0" ]
16
2019-12-03T16:41:18.000Z
2021-11-06T04:44:11.000Z
#ifndef _OP_TIMESYNC_SERVER_HPP_ #define _OP_TIMESYNC_SERVER_HPP_ #include <memory> #include <variant> #include "core/op_core.h" #include "timesync/api.hpp" #include "timesync/clock.hpp" #include "timesync/source_ntp.hpp" #include "timesync/source_system.hpp" namespace openperf::timesync::api { class server { public: /* * Since time sources hook into the event loop, they are * neither movable nor copyable. Hence, we have to store * them as pointers. */ using time_source = std::variant<std::unique_ptr<source::system>, std::unique_ptr<source::ntp>>; server(void* context, core::event_loop& loop); reply_msg handle_request(const request_time_counters&); reply_msg handle_request(const request_time_keeper&); reply_msg handle_request(const request_time_sources&); reply_msg handle_request(const request_time_source_add&); reply_msg handle_request(const request_time_source_del&); private: core::event_loop& m_loop; std::unique_ptr<clock> m_clock; std::unique_ptr<void, op_socket_deleter> m_socket; std::map<std::string, time_source> m_sources; std::vector<std::unique_ptr<counter::timecounter>> m_timecounters; }; } // namespace openperf::timesync::api #endif /* _OP_TIMESYNC_SERVER_HPP_ */
27.93617
70
0.722011
[ "vector" ]
8a889d8b2085e7eb0ba7faabff9d72e76fcc6cdc
938
cpp
C++
Algorithms/1958.Check_if_Move_is_Legal.cpp
metehkaya/LeetCode
52f4a1497758c6f996d515ced151e8783ae4d4d2
[ "MIT" ]
2
2020-07-20T06:40:22.000Z
2021-11-20T01:23:26.000Z
Problems/LeetCode/Problems/1958.Check_if_Move_is_Legal.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
Problems/LeetCode/Problems/1958.Check_if_Move_is_Legal.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<char>> ar; bool f(int r , int c , int dr , int dc , char color , char other) { bool var = false; r += dr; c += dc; while(r >= 0 && r < 8 && c >= 0 && c < 8 && ar[r][c] == other) var = true , r += dr , c += dc; if(!var) return false; if(r < 0 || r >= 8 || c < 0 || c >= 8) return false; return (ar[r][c] == color); } bool checkMove(vector<vector<char>>& board, int r, int c, char color) { ar = board; char other = (color == 'W') ? 'B' : 'W'; bool ans = false; if(f(r,c,0,1,color,other) || f(r,c,0,-1,color,other) || f(r,c,1,0,color,other) || f(r,c,-1,0,color,other)) ans = true; if(f(r,c,1,1,color,other) || f(r,c,1,-1,color,other) || f(r,c,-1,1,color,other) || f(r,c,-1,-1,color,other)) ans = true; return ans; } };
36.076923
116
0.444563
[ "vector" ]
8a8ba32ff974b4eafcd6182c449f2fd77c0d8b0d
4,438
cpp
C++
benchmark/benchmark_tf.cpp
xuqiang/cuBERT
8255916d4ca5d11d41d7cac46f7642a582e14111
[ "MIT" ]
486
2019-03-13T05:31:43.000Z
2022-03-31T05:16:45.000Z
benchmark/benchmark_tf.cpp
copperdong/cuBERT
4ed413dc20a9e22be30f9fa2c4b5e5f227be912a
[ "MIT" ]
44
2019-03-28T04:54:53.000Z
2021-04-09T01:30:12.000Z
benchmark/benchmark_tf.cpp
copperdong/cuBERT
4ed413dc20a9e22be30f9fa2c4b5e5f227be912a
[ "MIT" ]
82
2019-03-14T01:53:57.000Z
2022-03-24T14:24:30.000Z
#include <random> #include <chrono> #include <iostream> #include <cmath> #include <fstream> #include "tensorflow/c/c_api.h" const int max_batch_size = 128; const int batch_size = 128; const int seq_length = 32; const int hidden_size = 768; // define model output const int output_size = batch_size * hidden_size; const char* output_name = "bert/pooler/dense/Tanh"; TF_Output t_inputs[3]; TF_Output t_output; TF_Graph* graph; TF_Session* session; void tf_open(const char *filename) { std::ifstream input(filename, std::ios::binary); std::string str(std::istreambuf_iterator<char>{input}, {}); input.close(); TF_Status* status = TF_NewStatus(); TF_SessionOptions* opts = TF_NewSessionOptions(); TF_ImportGraphDefOptions* gopts = TF_NewImportGraphDefOptions(); TF_Buffer* buffer = TF_NewBufferFromString(str.c_str(), str.length()); graph = TF_NewGraph(); TF_GraphImportGraphDef(graph, buffer, gopts, status); session = TF_NewSession(graph, opts, status); t_inputs[0] = {TF_GraphOperationByName(graph, "input_ids"), 0}; t_inputs[1] = {TF_GraphOperationByName(graph, "input_mask"), 0}; t_inputs[2] = {TF_GraphOperationByName(graph, "segment_ids"), 0}; t_output = {TF_GraphOperationByName(graph, output_name), 0}; TF_DeleteBuffer(buffer); TF_DeleteImportGraphDefOptions(gopts); TF_DeleteSessionOptions(opts); TF_DeleteStatus(status); } void tf_compute(TF_Tensor *input_ids, TF_Tensor *input_mask, TF_Tensor *segment_ids, TF_Tensor **output) { TF_Tensor* input_values[3] = {input_ids, input_mask, segment_ids}; TF_Status* status = TF_NewStatus(); TF_SessionRun(session, nullptr, t_inputs, input_values, 3, &t_output, output, 1, nullptr, 0, nullptr, status); TF_DeleteStatus(status); } void tf_close() { TF_Status* status = TF_NewStatus(); TF_DeleteSession(session, status); TF_DeleteGraph(graph); TF_DeleteStatus(status); } void random_input(std::default_random_engine& e, TF_Tensor* tf_input_ids, TF_Tensor* tf_input_mask, TF_Tensor* tf_segment_ids, size_t length) { std::uniform_int_distribution<int> id_dist(0, 21120); std::uniform_int_distribution<int> zo_dist(0, 1); for (int i = 0; i < length; ++i) { ((int64_t*) TF_TensorData(tf_input_ids))[i] = id_dist(e); ((int64_t*) TF_TensorData(tf_input_mask))[i] = zo_dist(e); ((int64_t*) TF_TensorData(tf_segment_ids))[i] = zo_dist(e); } } void benchmark(TF_Tensor* tf_input_ids, TF_Tensor* tf_input_mask, TF_Tensor* tf_segment_ids, std::ofstream& result) { TF_Tensor* output; auto start = std::chrono::high_resolution_clock::now(); tf_compute(tf_input_ids, tf_input_mask, tf_segment_ids, &output); auto finish = std::chrono::high_resolution_clock::now(); long long milli = std::chrono::duration_cast<std::chrono::milliseconds>(finish - start).count(); std::cout << "TF: " << milli << "ms" << std::endl; for (int j = 0; j < output_size; ++j) { result << ((float*) TF_TensorData(output))[j] << std::endl; } TF_DeleteTensor(output); } int main() { std::default_random_engine e(0); // tensorflow int64_t dims[2] = {batch_size, seq_length}; TF_Tensor* tf_input_ids = TF_AllocateTensor(TF_INT64, dims, 2, sizeof(int64_t) * dims[0] * dims[1]); TF_Tensor* tf_input_mask = TF_AllocateTensor(TF_INT64, dims, 2, sizeof(int64_t) * dims[0] * dims[1]); TF_Tensor* tf_segment_ids = TF_AllocateTensor(TF_INT64, dims, 2, sizeof(int64_t) * dims[0] * dims[1]); std::cout << TF_Version() << std::endl; tf_open("bert_frozen_seq32.pb"); std::ofstream result("tfBERT.txt"); std::cout << "=== warm_up ===" << std::endl; for (int i = 0; i < 10; ++i) { random_input(e, tf_input_ids, tf_input_mask, tf_segment_ids, batch_size * seq_length); benchmark(tf_input_ids, tf_input_mask, tf_segment_ids, result); } std::cout << "=== benchmark ===" << std::endl; for (int i = 0; i < 10; ++i) { random_input(e, tf_input_ids, tf_input_mask, tf_segment_ids, batch_size * seq_length); benchmark(tf_input_ids, tf_input_mask, tf_segment_ids, result); } TF_DeleteTensor(tf_segment_ids); TF_DeleteTensor(tf_input_mask); TF_DeleteTensor(tf_input_ids); result.close(); tf_close(); }
34.403101
112
0.669671
[ "model" ]
8a923b5c74dd9359b33f9347fa7c06d4c79d0f77
626
cpp
C++
LuaKitProject/src/Projects/jni/java_weak_ref.cpp
andrewvmail/luakit
edbadd7824bd17b6a430d8323f255d404498c27a
[ "MIT" ]
321
2018-06-17T03:52:46.000Z
2022-03-18T02:34:52.000Z
LuaKitProject/src/Projects/jni/java_weak_ref.cpp
andrewvmail/luakit
edbadd7824bd17b6a430d8323f255d404498c27a
[ "MIT" ]
19
2018-06-26T10:37:45.000Z
2020-12-09T03:16:45.000Z
LuaKitProject/src/Projects/jni/java_weak_ref.cpp
andrewvmail/luakit
edbadd7824bd17b6a430d8323f255d404498c27a
[ "MIT" ]
58
2018-06-21T10:43:03.000Z
2022-03-29T12:42:11.000Z
#include "java_weak_ref.h" #include "JniEnvWrapper.h" #include "base/logging.h" java_weak_ref::java_weak_ref(jobject obj) : weak_ref_(NULL) { JniEnvWrapper env; if (env->IsSameObject(obj, NULL)) { LOG(INFO) << "java object is null"; } else { weak_ref_ = env->NewWeakGlobalRef(obj); if(env->IsSameObject(weak_ref_, NULL)) { LOG(ERROR) << "new weak global ref failed"; } } } java_weak_ref::~java_weak_ref() { JniEnvWrapper env; if (!env->IsSameObject(weak_ref_, NULL)) { env->DeleteWeakGlobalRef(weak_ref_); } }
25.04
62
0.592652
[ "object" ]
8a9b62f65f54a3e11aae943cd7a5425e85f79fb5
7,276
cpp
C++
src/qt/btcu/leasingmodel.cpp
newcodepusher/bu
309652ccff4992fd8265900cde6d3aaeb9c86dad
[ "MIT" ]
null
null
null
src/qt/btcu/leasingmodel.cpp
newcodepusher/bu
309652ccff4992fd8265900cde6d3aaeb9c86dad
[ "MIT" ]
null
null
null
src/qt/btcu/leasingmodel.cpp
newcodepusher/bu
309652ccff4992fd8265900cde6d3aaeb9c86dad
[ "MIT" ]
null
null
null
// Copyright (c) 2020 The BTCU developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "qt/btcu/leasingmodel.h" #include "uint256.h" #include "bitcoinunits.h" #include "guiutil.h" #include "addressbook.h" #include "addresstablemodel.h" #include "transactionrecord.h" #include "walletmodel.h" #include <iostream> struct Leasing { Leasing() = default; CKeyID leaserKeyID; QString leaserAddress; bool isLeaser = false; CKeyID ownerKeyID; QString ownerAddress; bool isOwner = false; /// Map of txId --> index num for P2L utxos std::map<std::string, int> p2lUtxos; /// Map of txId --> index num for leasing reward utxos std::map<std::string, int> lrUtxos; /// Sum of all leasing to this owner address CAmount cachedTotalAmount = 0; /// Sum of all leasing rewards CAmount cachedTotalReward = 0; }; struct LeasingModel::Impl { Impl(AddressTableModel* addressTableModel): pAddressTableModel(addressTableModel) { } ~Impl() = default; AddressTableModel* pAddressTableModel = nullptr; /** * List with all of the grouped leasings received by this wallet */ std::map<CKeyID, Leasing> cachedLeasings; CAmount cachedAmount = 0; CAmount cachedReward = 0; bool parseP2L(const COutput& utxo, Leasing& leasing) { txnouttype type; std::vector<CTxDestination> addresses; int nRequired; const auto& out = utxo.tx->vout[utxo.i]; if (!ExtractDestinations(out.scriptPubKey, type, addresses, nRequired) || type != TX_LEASE || addresses.size() != 2) return error("%s : Error extracting P2L destinations for utxo: %s-%d", __func__, utxo.tx->GetHash().GetHex(), utxo.i); leasing.leaserKeyID = boost::get<CKeyID>(addresses[0]); leasing.leaserAddress = QString::fromStdString(CBTCUAddress(leasing.leaserKeyID, CChainParams::LEASING_ADDRESS).ToString()); leasing.isLeaser = pwalletMain->HaveKey(leasing.leaserKeyID); leasing.ownerKeyID = boost::get<CKeyID>(addresses[1]); leasing.ownerAddress = QString::fromStdString(CBTCUAddress(leasing.ownerKeyID, CChainParams::PUBKEY_ADDRESS).ToString()); leasing.isOwner = pwalletMain->HaveKey(leasing.ownerKeyID); return true; } bool parseLR(const COutput& utxo, Leasing& leasing) { txnouttype type; std::vector<CTxDestination> addresses; int nRequired; const auto& out = utxo.tx->vout[utxo.i]; if (!ExtractDestinations(out.scriptPubKey, type, addresses, nRequired) || type != TX_LEASINGREWARD || addresses.size() != 1) return error("%s : Error extracting LR destination for utxo: %s-%d", __func__, utxo.tx->GetHash().GetHex(), utxo.i);; leasing.ownerKeyID = boost::get<CKeyID>(addresses[0]); leasing.ownerAddress = QString::fromStdString(CBTCUAddress(leasing.ownerKeyID, CChainParams::PUBKEY_ADDRESS).ToString()); leasing.isOwner = true; return true; } void refresh() { cachedLeasings.clear(); cachedAmount = 0; // First get all of the p2l utxo inside the wallet std::vector<COutput> utxoP2LList; pwalletMain->GetAvailableP2LCoins(utxoP2LList, false); // Second get all of leasing rewards utxo inside the wallet std::vector<COutput> utxoLRList; pwalletMain->GetAvailableLeasingRewards(utxoLRList); for (const auto& utxo : utxoP2LList) { Leasing leasing; if (!this->parseP2L(utxo, leasing)) continue; const auto& out = utxo.tx->vout[utxo.i]; const auto& txID = utxo.tx->GetHash().GetHex(); if (leasing.isLeaser) { auto itr = cachedLeasings.emplace(leasing.leaserKeyID, leasing).first; (*itr).second.cachedTotalAmount += out.nValue; (*itr).second.p2lUtxos.emplace(txID, utxo.i); } if (leasing.isOwner) { auto itr = cachedLeasings.emplace(leasing.ownerKeyID, leasing).first; (*itr).second.cachedTotalAmount += out.nValue; (*itr).second.p2lUtxos.emplace(txID, utxo.i); } cachedAmount += out.nValue; } // Loop over each COutput into a Leasing for (const auto& utxo : utxoLRList) { Leasing leasing; if (!parseLR(utxo, leasing)) continue; const auto& out = utxo.tx->vout[utxo.i]; const auto& txID = utxo.tx->GetHash().GetHex(); auto itr = cachedLeasings.emplace(leasing.ownerKeyID, leasing).first; (*itr).second.cachedTotalReward += out.nValue; (*itr).second.lrUtxos.emplace(txID, utxo.i); cachedReward += out.nValue; } } }; LeasingModel::LeasingModel( AddressTableModel* addressTableModel, QObject *parent ) : QAbstractTableModel(parent), pImpl(new Impl(addressTableModel)) { } LeasingModel::~LeasingModel() = default; void LeasingModel::updateLeasingList() { refresh(); QMetaObject::invokeMethod(this, "emitDataSetChanged", Qt::QueuedConnection); } CAmount LeasingModel::getTotalAmount() const { return pImpl->cachedAmount; } CAmount LeasingModel::getTotalReward() const { return pImpl->cachedReward; } void LeasingModel::emitDataSetChanged() { Q_EMIT dataChanged( index(0, 0, QModelIndex()), index(pImpl->cachedLeasings.size(), COLUMN_COUNT, QModelIndex()) ); } void LeasingModel::refresh() { pImpl->refresh(); } int LeasingModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return pImpl->cachedLeasings.size(); } int LeasingModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return COLUMN_COUNT; } QVariant LeasingModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); int row = index.row(); auto itr = pImpl->cachedLeasings.begin(); std::advance(itr, row); const Leasing& rec = (*itr).second; if (role == Qt::DisplayRole || role == Qt::EditRole) { switch (index.column()) { case ADDRESS: if (rec.isLeaser) return rec.leaserAddress; else return rec.ownerAddress; case ADDRESS_LABEL: if (rec.isLeaser) return pImpl->pAddressTableModel->labelForAddress(rec.leaserAddress); else return pImpl->pAddressTableModel->labelForAddress(rec.ownerAddress); case TOTAL_AMOUNT: return GUIUtil::formatBalance(rec.cachedTotalAmount); case TOTAL_REWARD: return GUIUtil::formatBalance(rec.cachedTotalReward); case IS_LEASER: return rec.isLeaser; } } return QVariant(); } void LeasingModel::removeRowAndEmitDataChanged(const int idx) { beginRemoveRows(QModelIndex(), idx, idx); endRemoveRows(); Q_EMIT dataChanged( index(idx, 0, QModelIndex()), index(idx, COLUMN_COUNT, QModelIndex()) ); }
31.227468
132
0.634689
[ "vector" ]
8aa32f671c687dbfe71ae298b49e97e24769ece7
562
cpp
C++
pixie/2dEngine/TextureAnimator.cpp
martonantoni/pixie
ab750d25d12f8420e68e1cb393a75b1f0a0c1056
[ "MIT" ]
null
null
null
pixie/2dEngine/TextureAnimator.cpp
martonantoni/pixie
ab750d25d12f8420e68e1cb393a75b1f0a0c1056
[ "MIT" ]
null
null
null
pixie/2dEngine/TextureAnimator.cpp
martonantoni/pixie
ab750d25d12f8420e68e1cb393a75b1f0a0c1056
[ "MIT" ]
null
null
null
#include "StdAfx.h" void cTextureAnimator::Activated(cPixieObject &Object) { } cPixieObjectAnimator::eAnimateResult cTextureAnimator::Animate(cPixieObject &Object) { auto Elapsed=gFrameTime-GetStartTime(); auto Frame=(Elapsed*mFramesPerSec)/1000; if(Frame!=mPreviousFrame) { mPreviousFrame=Frame; Object.SetStringProperty(cPixieObject::Property_Texture, mTextureNames[std::min<size_t>(mTextureNames.size()-1, Frame)]); if(Frame>=mTextureNames.size()) return cPixieObjectAnimator::AnimationDone; } return cPixieObjectAnimator::AnimationActive; }
28.1
123
0.791815
[ "object" ]
8aa4d51cc1898bccdcd589240a947ad875220678
14,024
cc
C++
auth/src/auth.cc
gwaldvogel/firebase-cpp-sdk
ae8c32e63165de9ff13f74694e8c9104a36915ee
[ "Apache-2.0" ]
193
2019-03-18T16:30:43.000Z
2022-03-30T17:39:32.000Z
auth/src/auth.cc
gwaldvogel/firebase-cpp-sdk
ae8c32e63165de9ff13f74694e8c9104a36915ee
[ "Apache-2.0" ]
647
2019-03-18T20:50:41.000Z
2022-03-31T18:32:33.000Z
auth/src/auth.cc
gwaldvogel/firebase-cpp-sdk
ae8c32e63165de9ff13f74694e8c9104a36915ee
[ "Apache-2.0" ]
86
2019-04-21T09:40:38.000Z
2022-03-26T20:48:37.000Z
/* * Copyright 2016 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "auth/src/include/firebase/auth.h" #include <assert.h> #include <stdio.h> #include <algorithm> #include <cstdint> #include <map> #include <string> #include "app/src/assert.h" #include "app/src/cleanup_notifier.h" #include "app/src/include/firebase/app.h" #include "app/src/include/firebase/future.h" #include "app/src/include/firebase/internal/common.h" #include "app/src/include/firebase/internal/platform.h" #include "app/src/include/firebase/version.h" #include "app/src/mutex.h" #include "app/src/semaphore.h" #include "app/src/util.h" #include "auth/src/common.h" #include "auth/src/data.h" // Workaround MSVC's incompatible libc headers. #if FIREBASE_PLATFORM_WINDOWS #define snprintf _snprintf #endif // FIREBASE_PLATFORM_WINDOWS // Register the module initializer. FIREBASE_APP_REGISTER_CALLBACKS(auth, { return ::firebase::kInitResultSuccess; }, { // Nothing to tear down. }); namespace firebase { namespace auth { DEFINE_FIREBASE_VERSION_STRING(FirebaseAuth); // The global map of Apps to Auths. Each App can have at most one Auth, // and an Auth requires an App. So, the user acquires the Auth via an App // reference. // TODO(jsanmiya): Ensure all the Auths are destroyed on shutdown. std::map<App*, Auth*> g_auths; Mutex* g_auths_mutex = new Mutex(); // static Auth* Auth::GetAuth(App* app, InitResult* init_result_out) { MutexLock lock(*g_auths_mutex); // Return the Auth if it already exists. Auth* existing_auth = FindAuth(app); if (existing_auth) { if (init_result_out != nullptr) *init_result_out = kInitResultSuccess; return existing_auth; } // Create the platform dependent version of Auth. void* auth_impl = CreatePlatformAuth(app); if (!auth_impl) return nullptr; // Create a new Auth and initialize. Auth* auth = new Auth(app, auth_impl); LogDebug("Creating Auth %p for App %p", auth, app); // Stick it in the global map so we remember it, and can delete it on // shutdown. g_auths[app] = auth; if (init_result_out) *init_result_out = kInitResultSuccess; return auth; } // static Auth* Auth::FindAuth(App* app) { MutexLock lock(*g_auths_mutex); // Return the Auth if it already exists. std::map<App*, Auth*>::iterator it = g_auths.find(app); if (it != g_auths.end()) { return it->second; } return nullptr; } // Auth uses the pimpl mechanism to hide internal data types from the interface. Auth::Auth(App* app, void* auth_impl) : auth_data_(new AuthData) { FIREBASE_ASSERT(app != nullptr && auth_impl != nullptr); auth_data_->app = app; auth_data_->auth = this; auth_data_->auth_impl = auth_impl; InitPlatformAuth(auth_data_); std::string* future_id = &auth_data_->future_api_id; static const char* kApiIdentifier = "Auth"; future_id->reserve(strlen(kApiIdentifier) + 16 /* hex characters in the pointer */ + 1 /* null terminator */); snprintf(&((*future_id)[0]), future_id->capacity(), "%s0x%016llx", kApiIdentifier, static_cast<unsigned long long>( // NOLINT reinterpret_cast<intptr_t>(this))); // Cleanup this object if app is destroyed. CleanupNotifier* notifier = CleanupNotifier::FindByOwner(app); assert(notifier); notifier->RegisterObject(this, [](void* object) { Auth* auth = reinterpret_cast<Auth*>(object); LogWarning( "Auth object 0x%08x should be deleted before the App 0x%08x it " "depends upon.", static_cast<int>(reinterpret_cast<intptr_t>(auth)), static_cast<int>(reinterpret_cast<intptr_t>(auth->auth_data_->app))); auth->DeleteInternal(); }); } void Auth::DeleteInternal() { MutexLock lock(*g_auths_mutex); if (!auth_data_) return; { MutexLock destructing_lock(auth_data_->desctruting_mutex); auth_data_->destructing = true; } CleanupNotifier* notifier = CleanupNotifier::FindByOwner(auth_data_->app); assert(notifier); notifier->UnregisterObject(this); int num_auths_remaining = 0; { // Remove `this` from the g_auths map. // The mapping is 1:1, so we should only ever delete one. for (auto it = g_auths.begin(); it != g_auths.end(); ++it) { if (it->second == this) { LogDebug("Deleting Auth %p for App %p", this, it->first); g_auths.erase(it); break; } } num_auths_remaining = g_auths.size(); } auth_data_->ClearListeners(); // If this is the last Auth instance to be cleaned up, also clean up data for // Credentials. if (num_auths_remaining == 0) { CleanupCredentialFutureImpl(); } // Destroy the platform-specific object. DestroyPlatformAuth(auth_data_); // Delete the pimpl data. delete auth_data_; auth_data_ = nullptr; } Auth::~Auth() { DeleteInternal(); } // Always non-nullptr since set in constructor. App& Auth::app() { FIREBASE_ASSERT(auth_data_ != nullptr); return *auth_data_->app; } template <typename T> static bool PushBackIfMissing(const T& entry, std::vector<T>* v) { auto it = std::find(v->begin(), v->end(), entry); if (it != v->end()) return false; v->push_back(entry); return true; } // Store a unique listener of type T in a listener_vector and unique auth // object in auth_vector. Both vectors must be in sync, i.e addition must // either succeed or fail otherwise this method asserts. // Return whether the listener is added. template <typename T> static bool AddListener(T listener, std::vector<T>* listener_vector, Auth* auth, std::vector<Auth*>* auth_vector) { // Add to array of listeners if not already there. const bool listener_added = PushBackIfMissing(listener, listener_vector); // Add auth to array of Auths if not already there. const bool auth_added = PushBackIfMissing(auth, auth_vector); // The listener and Auth should either point at each other or not point // at each other. FIREBASE_ASSERT_RETURN(false, listener_added == auth_added); (void)auth_added; return listener_added; } void Auth::AddAuthStateListener(AuthStateListener* listener) { if (!auth_data_) return; // Would have to lock mutex till the method ends to protect on race // conditions. MutexLock lock(auth_data_->listeners_mutex); bool added = AddListener(listener, &auth_data_->listeners, this, &listener->auths_); // If the listener is registered successfully and persistent cache has been // loaded, trigger OnAuthStateChanged() immediately. Otherwise, wait until // the cache is loaded, through AuthStateListener event. // NOTE: This should be called synchronously or current_user() for desktop // implementation may not work. if (added && !auth_data_->persistent_cache_load_pending) { listener->OnAuthStateChanged(this); } } void Auth::AddIdTokenListener(IdTokenListener* listener) { if (!auth_data_) return; // Would have to lock mutex till the method ends to protect on race // conditions. MutexLock lock(auth_data_->listeners_mutex); bool added = AddListener(listener, &auth_data_->id_token_listeners, this, &listener->auths_); // AddListener is valid even if the listener is already registered. // This makes sure that we only increase the reference count if a listener // was actually added. if (added) { // If the listener is registered successfully and persistent cache has been // loaded, trigger OnAuthStateChanged() immediately. Otherwise, wait until // the cache is loaded, through AuthStateListener event if (!auth_data_->persistent_cache_load_pending) { listener->OnIdTokenChanged(this); } EnableTokenAutoRefresh(auth_data_); } } template <typename T> static bool ReplaceEntryWithBack(const T& entry, std::vector<T>* v) { auto it = std::find(v->begin(), v->end(), entry); if (it == v->end()) return false; // If it's not already the back element, move/copy the back element onto it. if (&(*it) != &(v->back())) { #if defined(FIREBASE_USE_MOVE_OPERATORS) *it = std::move(v->back()); #else *it = v->back(); #endif // defined(FIREBASE_USE_MOVE_OPERATORS) } v->pop_back(); return true; } // Remove a listener of type T from listener_vector and unique auth object in // auth_vector. Both vectors must be in sync, i.e addition must either // succeed or fail otherwise this method asserts. template <typename T> static void RemoveListener(T listener, std::vector<T>* listener_vector, Auth* auth, std::vector<Auth*>* auth_vector, Mutex* mutex) { MutexLock lock(*mutex); // Remove `listener` from our vector of listeners. ReplaceEntryWithBack(listener, listener_vector); // Remove this Auth from the listener's vector of Auths. // This ensures the listener doesn't try to unregister itself again when it is // destroyed. ReplaceEntryWithBack(auth, auth_vector); } void Auth::RemoveAuthStateListener(AuthStateListener* listener) { if (!auth_data_) return; RemoveListener(listener, &auth_data_->listeners, this, &listener->auths_, &auth_data_->listeners_mutex); } void Auth::RemoveIdTokenListener(IdTokenListener* listener) { if (!auth_data_) return; int listener_count = auth_data_->id_token_listeners.size(); RemoveListener(listener, &auth_data_->id_token_listeners, this, &listener->auths_, &auth_data_->listeners_mutex); // RemoveListener is valid even if the listener is not registered. // This makes sure that we only decrease the reference count if a listener // was actually removed. if (auth_data_->id_token_listeners.size() < listener_count) { DisableTokenAutoRefresh(auth_data_); } } AuthStateListener::~AuthStateListener() { // Removing the listener edits the auths list, hence the while loop. while (!auths_.empty()) { (*auths_.begin())->RemoveAuthStateListener(this); } } IdTokenListener::~IdTokenListener() { // Removing the listener edits the auths list, hence the while loop. while (!auths_.empty()) { (*auths_.begin())->RemoveIdTokenListener(this); } } template <typename T> static inline bool VectorContains(const T& entry, const std::vector<T>& v) { return std::find(v.begin(), v.end(), entry) != v.end(); } // Generate a method that notifies a vector of listeners using listeners_method. #define AUTH_NOTIFY_LISTENERS(notify_method_name, notification_name, \ listeners_vector, notification_method) \ void notify_method_name(AuthData* auth_data) { \ MutexLock lock(auth_data->listeners_mutex); \ \ /* Auth should have loaded persistent cache if exists when the listener */ \ /* event is triggered for the first time. */ \ auth_data->persistent_cache_load_pending = false; \ \ /* Make a copy of the listener list in case it gets modified during */ \ /* notification_method(). Note that modification is possible because */ \ /* the same thread is allowed to reaquire the `listeners_mutex` */ \ /* multiple times. */ \ auto listeners = auth_data->listeners_vector; \ LogDebug(notification_name " changed. Notifying %d listeners.", \ listeners.size()); \ \ for (auto it = listeners.begin(); it != listeners.end(); ++it) { \ /* Skip any listeners that have been removed in notification_method() */ \ /* on earlier iterations of this loop. */ \ auto* listener = *it; \ if (!VectorContains(listener, auth_data->listeners_vector)) { \ continue; \ } \ \ /* Notify the listener. */ \ listener->notification_method(auth_data->auth); \ } \ } AUTH_NOTIFY_LISTENERS(NotifyAuthStateListeners, "Auth state", listeners, OnAuthStateChanged); AUTH_NOTIFY_LISTENERS(NotifyIdTokenListeners, "ID token", id_token_listeners, OnIdTokenChanged); AUTH_RESULT_FN(Auth, FetchProvidersForEmail, Auth::FetchProvidersResult) AUTH_RESULT_FN(Auth, SignInWithCustomToken, User*) AUTH_RESULT_FN(Auth, SignInWithCredential, User*) AUTH_RESULT_FN(Auth, SignInAndRetrieveDataWithCredential, SignInResult) AUTH_RESULT_FN(Auth, SignInAnonymously, User*) AUTH_RESULT_FN(Auth, SignInWithEmailAndPassword, User*) AUTH_RESULT_FN(Auth, CreateUserWithEmailAndPassword, User*) AUTH_RESULT_FN(Auth, SendPasswordResetEmail, void) } // namespace auth } // namespace firebase
37.597855
80
0.647675
[ "object", "vector" ]
8ab16ef7ea2688cf39c2e4b228a326a7784d48a7
11,902
cpp
C++
tests/doctests/token_exchange_action_tests.cpp
JackDiSalvatore/eosio.contracts-token-exchange
5b78a49629d0fd2bf94d4f5cebffcd596b70c174
[ "MIT" ]
1
2022-01-07T09:51:17.000Z
2022-01-07T09:51:17.000Z
tests/doctests/token_exchange_action_tests.cpp
JackDiSalvatore/eosio.contracts-token-exchange
5b78a49629d0fd2bf94d4f5cebffcd596b70c174
[ "MIT" ]
null
null
null
tests/doctests/token_exchange_action_tests.cpp
JackDiSalvatore/eosio.contracts-token-exchange
5b78a49629d0fd2bf94d4f5cebffcd596b70c174
[ "MIT" ]
null
null
null
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest.h" #include <eosio/testing/tester.hpp> #include <eosio/chain/abi_serializer.hpp> #include <eosio/chain/resource_limits.hpp> #include "../contracts.hpp" #include "../eosio.system_tester.hpp" using namespace eosio::chain; using namespace eosio::testing; using namespace fc; using mvo = fc::mutable_variant_object; // #ifndef TESTER // #ifdef NON_VALIDATING_TEST // #define TESTER tester // #else // #define TESTER validating_tester // #endif // #endif #define CONTRACT_ACCOUNT name("exchange") namespace eosio { namespace chain { // Add this in symbol.hpp (line 172) inline bool operator== (const extended_symbol& lhs, const extended_symbol& rhs) { return ( lhs.sym.value() | (uint128_t(lhs.contract.value) << 64) ) == ( rhs.sym.value() | (uint128_t(rhs.contract.value) << 64) ); } inline bool operator!= (const extended_symbol& lhs, const extended_symbol& rhs) { return ( lhs.sym.value() | (uint128_t(lhs.contract.value) << 64) ) != ( rhs.sym.value() | (uint128_t(rhs.contract.value) << 64) ); } inline bool operator< (const extended_symbol& lhs, const extended_symbol& rhs) { return ( lhs.sym.value() | (uint128_t(lhs.contract.value) << 64) ) < ( rhs.sym.value() | (uint128_t(rhs.contract.value) << 64) ); } inline bool operator> (const extended_symbol& lhs, const extended_symbol& rhs) { return ( lhs.sym.value() | (uint128_t(lhs.contract.value) << 64) ) > ( rhs.sym.value() | (uint128_t(rhs.contract.value) << 64) ); } } } namespace eosio_system { class exchange_tester : public eosio_system_tester { public: friend inline bool operator< (const extended_symbol& lhs, const extended_symbol& rhs); static name exchange_account; exchange_tester() { deploy_contract(); } abi_serializer deploy_code(name account, const std::vector<uint8_t>& wasm, const std::vector<char>& abiname) { set_code(account, wasm); set_abi(account, abiname.data()); produce_blocks(); const auto& accnt = control->db().get<account_object, by_name>(account); abi_serializer abi_ser; abi_def abi; REQUIRE(abi_serializer::to_abi(accnt.abi, abi)); abi_ser.set_abi(abi, abi_serializer_max_time); return abi_ser; } void deploy_contract() { // create_account(exchange_account); create_account_with_resources(exchange_account, config::system_account_name, 1000000); produce_blocks(2); deploy_code(exchange_account, contracts::exchange_wasm(), contracts::exchange_abi()); eos_token = token(this, name("eosio.token"), asset(10000000000000, symbol(4,"EOS"))); eos_token.issue(name("eosio.token"), asset(10000000000000, symbol(4,"EOS"))); add_code_permission(exchange_account); } action_result push_action_ex(account_name actor, const name& code, const action_name& acttype, const variant_object& data) { return base_tester::push_action(get_action(code, acttype, {permission_level{actor, config::active_name}}, data), uint64_t(actor)); } action_result push_action_ex(const std::vector<permission_level>& perms, const name& code, const action_name& acttype, const variant_object& data, const std::vector<permission_level>& signers) { signed_transaction trx; trx.actions.emplace_back(get_action(code, acttype, perms, data)); set_transaction_headers(trx); for (const auto& auth : signers) { trx.sign(get_private_key(auth.actor, auth.permission.to_string()), control->get_chain_id()); } try { // print_action_console(push_transaction(trx)); push_transaction(trx); } catch (const fc::exception& ex) { edump((ex.to_detail_string())); return error(ex.top_message()); // top_message() is assumed by many tests; otherwise they fail // return error(ex.to_detail_string()); } produce_block(); BOOST_REQUIRE_EQUAL(true, chain_has_transaction(trx.id())); return success(); } /* * Helper Functions */ void add_code_permission(name account) { const auto priv_key = this->get_private_key(account.to_string(), "active"); const auto pub_key = priv_key.get_public_key(); this->set_authority(account, name("active"), authority(1, {key_weight{pub_key, 1}}, {{permission_level{account, name("eosio.code")}, 1}}), "owner"); } transaction make_transaction(const fc::variants& actions) { variant pretty_trx = fc::mutable_variant_object()("expiration", "2020-01-01T00:30")("ref_block_num", 2)("ref_block_prefix", 3)( "max_net_usage_words", 0)("max_cpu_usage_ms", 0)("delay_sec", 0)("actions", actions); transaction trx; abi_serializer::from_variant(pretty_trx, trx, get_resolver(), abi_serializer_max_time); return trx; } transaction make_transaction(vector<action>&& actions) { transaction trx; trx.actions = std::move(actions); set_transaction_headers(trx); return trx; } transaction make_transaction_with_data(account_name code, name action, const vector<permission_level>& perms, const fc::variant& data) { return make_transaction({fc::mutable_variant_object()("account", code)("name", action)("authorization", perms)("data", data)}); } /* * Contract Actions */ action_result transfer(name from, name to, const asset& amount, std::string memo) { return push_action_ex(from, name("eosio.token"), name("transfer"), mutable_variant_object()("from", from)("to", to)("quantity", amount)("memo", memo)); } /* * TABLES */ abi_serializer get_serializer() { const auto& acnt = control->get_account(CONTRACT_ACCOUNT); auto abi = acnt.get_abi(); return abi_serializer(abi, abi_serializer_max_time); } std::map<extended_symbol, int64_t> get_exchange_account_balance(account_name acc) { std::map<extended_symbol, int64_t> balances; vector<char> data = get_row_by_account(CONTRACT_ACCOUNT, acc, name("exaccounts"), acc); if ( data.empty() ) { CHECK( 1 == 1); return balances; } else { auto var = get_serializer().binary_to_variant("exaccount", data, abi_serializer_max_time); auto owner = var["owner"].as<name>(); CHECK( owner == name("alice")); // auto balance2 = var["balances"]; // CHECK( balance2 == variant() ); // CHECK( balance2 == mvo()("key", "eosio.token")("value", "2000") ); auto balance = var["balances"].as<vector<fc::variant>>(); CHECK( balance.size() == 1); struct tmp_struct{ extended_symbol key; int64 value; }; std::vector<variant> p2; auto x = balance[0].as<tmp_struct>(); // std::vector<pair<extended_symbol, int64_t>> my_vector{balance.size()}; // std::transform(balance.begin(), balance.end(), my_vector.begin(), [](auto &v) { return v.template as<pair<extended_symbol, int64_t>>();}); // CHECK( my_vector.begin()->second == 20000); // CHECK(balance.begin()->second == 20000); // balances.insert(balance_vector.begin(), balance_vector.end()); return balances; } } /* * eosio.token Contract Interface */ struct token { exchange_tester* tester_; name issuer_; symbol sym_; token() {} token(exchange_tester* tester, name issuer, asset max_supply) : tester_(tester) , issuer_(issuer) , sym_(max_supply.get_symbol()) { create_currency(name("eosio.token"), issuer_, max_supply); } void create_currency( name contract, name issuer, asset maxsupply ) { tester_->push_action_ex(issuer, name("eosio.token"), name("create"), mutable_variant_object()("issuer", issuer)("maximum_supply", maxsupply)); } void issue(name to, asset quantity, std::string memo = "") { tester_->push_action_ex(issuer_, name("eosio.token"), name("issue"), mutable_variant_object()("to", to)("quantity", quantity)("memo", memo)); } void open(name owner, name ram_payer) { REQUIRE(tester_->push_action_ex(ram_payer, name("eosio.token"), name("open"), mutable_variant_object()("owner", owner)("symbol", sym_)("ram_payer", ram_payer)) == tester_->success()); } abi_serializer get_serializer() { const auto& acnt = tester_->control->get_account(name("eosio.token")); auto abi = acnt.get_abi(); return abi_serializer(abi, abi_serializer_max_time); } asset get_account_balance(account_name acc) { auto symbol_code = sym_.to_symbol_code().value; vector<char> data = tester_->get_row_by_account(name("eosio.token"), acc, name("accounts"), symbol_code); return data.empty() ? asset(0, sym_) : get_serializer().binary_to_variant("account", data, abi_serializer_max_time)["balance"].as<asset>(); } asset get_supply() { auto symbol_code = sym_.to_symbol_code().value; vector<char> data = tester_->get_row_by_account(name("eosio.token"), symbol_code, name("stat"), symbol_code); return data.empty() ? asset(0, sym_) : get_serializer().binary_to_variant("currency_stats", data, abi_serializer_max_time)["supply"].as<asset>(); } }; token eos_token; }; name exchange_tester::exchange_account = CONTRACT_ACCOUNT; } // namespace eosio_system TEST_CASE_FIXTURE(eosio_system::exchange_tester, "deposit") try { GIVEN("alice has 5 EOS") { create_account_with_resources(name("alice"), config::system_account_name, 1000000); transfer(name("eosio.token"), name("alice"), asset(50000, symbol(4,"EOS")), "memo"); REQUIRE(eos_token.get_account_balance(name("alice")) == asset(50000, symbol(4,"EOS"))); WHEN("alice deposits 2 EOS into the exchange") { CHECK(success() == transfer(name("alice"), exchange_account, asset(20000, symbol(4,"EOS")), "eosio.token")); THEN("alice would have 2 EOS in her exchange account") { CHECK(eos_token.get_account_balance(name("alice")) == asset(30000, symbol(4,"EOS"))); CHECK(eos_token.get_account_balance(exchange_account) == asset(20000, symbol(4,"EOS"))); extended_symbol return_sym; return_sym.sym = symbol(4, "EOS"); return_sym.contract = name("eosio.token"); std::map<extended_symbol, int64_t> return_balance; return_balance.emplace(return_sym, 20000); std::map<extended_symbol, int64_t> alice_ex_balance = get_exchange_account_balance(name("alice")); } } } } FC_LOG_AND_RETHROW() TEST_CASE_FIXTURE(eosio_system::exchange_tester, "withdraw") try { } FC_LOG_AND_RETHROW()
39.151316
153
0.599143
[ "vector", "transform" ]
8ab53800308e0f27af83fddd98b1c0281b053803
2,210
cpp
C++
days/Day10.cpp
willkill07/AdventOfCode2021
06e62cd8a8c7f1e99374075b7302f6dcfb770bb0
[ "Apache-2.0" ]
12
2021-12-02T01:44:53.000Z
2022-02-02T17:22:23.000Z
days/Day10.cpp
willkill07/AdventOfCode2021
06e62cd8a8c7f1e99374075b7302f6dcfb770bb0
[ "Apache-2.0" ]
null
null
null
days/Day10.cpp
willkill07/AdventOfCode2021
06e62cd8a8c7f1e99374075b7302f6dcfb770bb0
[ "Apache-2.0" ]
1
2021-12-03T04:25:32.000Z
2021-12-03T04:25:32.000Z
#include <algorithm> #include <bitset> #include <cctype> #include <limits> #include <memory> #include <numeric> #include <ranges> #include <vector> #include <scn/all.h> #include "AdventDay.hpp" #include "Day10.hpp" namespace detail { using namespace day10; using Day = AdventDay<id, parsed, result1, result2>; } using detail::Day; template <> Day::parsed_type Day::parse(std::string const& filename) { scn::basic_mapped_file<char> file{filename.c_str()}; Day::parsed_type result; result.reserve(150); auto const end = file.end(); for (auto iter = file.begin(); iter < end; ) { auto end_of_line = std::find(iter, end, '\n'); result.emplace_back(iter, end_of_line); iter = end_of_line + 1; } return result; } auto const matches = detail::matches(); auto const scores = detail::scores(); auto const illegal_values = detail::illegal_values(); inline bool opening(char a) { return a == '{' or a == '(' or a == '[' or a == '<'; } template <> template <bool solve_part2> Day::answer<solve_part2> Day::solve(Day::parsed_type const& data, Day::opt_answer) { std::vector<char> stack; stack.reserve(128); std::conditional_t<solve_part2, std::vector<unsigned long>, unsigned long> result{}; if constexpr (solve_part2) { result.reserve(data.size()); } for (auto&& line : data) { for (auto c : line) { if (opening(c)) { stack.push_back(c); } else { auto const top = stack.back(); stack.pop_back(); if (matches[c >> 4] != top) { if constexpr (not solve_part2) { result += illegal_values[c >> 4]; } stack.clear(); break; } } } if constexpr (solve_part2) { if (not stack.empty()) { unsigned long sum{0}; for (char c : stack | std::views::reverse) { sum = 5 * sum + scores[c >> 4]; } result.push_back(sum); stack.clear(); } } } if constexpr (solve_part2) { auto middle = std::next(std::begin(result), std::size(result) / 2); std::ranges::nth_element(result, middle); return *middle; } else { return result; } } INSTANTIATE(Day, true); INSTANTIATE(Day, false);
23.763441
86
0.604977
[ "vector" ]
8ac3a5d7adb76be838a50331d16278803e571391
30,355
cpp
C++
inetcore/setup/ieak5/brandll/rsopadm.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/setup/ieak5/brandll/rsopadm.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/setup/ieak5/brandll/rsopadm.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "precomp.h" // The following bug may be due to having CHICAGO_PRODUCT set in sources. // This file and all rsop??.cpp files need to have WINVER defined at at least 500 // BUGBUG: (andrewgu) no need to say how bad this is! #undef WINVER #define WINVER 0x0501 #include <userenv.h> #include "RSoP.h" //#include "wbemtime.h" #include "utils.h" #include <tchar.h> typedef BOOL (*PFNREGFILECALLBACK)(BOOL bHKCU, LPTSTR lpKeyName, LPTSTR lpValueName, DWORD dwType, DWORD dwDataLength, LPBYTE lpData, REGHASHTABLE *pHashTable); #define MAX_KEYNAME_SIZE 2048 #define MAX_VALUENAME_SIZE 512 const MAX_LENGTH = 100; // Length of stringized guid HRESULT SystemTimeToWbemTime(SYSTEMTIME& sysTime, _bstr_t &xbstrWbemTime); extern SAFEARRAY *CreateSafeArray(VARTYPE vtType, long nElements, long nDimensions = 1); /////////////////////////////////////////////////////////// // CheckSlash() - from nt\ds\security\gina\userenv\utils\util.c // // Purpose: Checks for an ending slash and adds one if // it is missing. // // Parameters: lpDir - directory // // Return: Pointer to the end of the string // // Comments: // // History: Date Author Comment // 6/19/95 ericflo Created /////////////////////////////////////////////////////////// LPTSTR CheckSlash (LPTSTR lpDir) { LPTSTR lpEnd; lpEnd = lpDir + lstrlen(lpDir); if (*(lpEnd - 1) != TEXT('\\')) { *lpEnd = TEXT('\\'); lpEnd++; *lpEnd = TEXT('\0'); } return lpEnd; } /////////////////////////////////////////////////////////// // IsUNCPath() - from nt\ds\security\gina\userenv\utils\util.c // // Purpose: Is the given path a UNC path // // Parameters: lpPath - Path to check // // Return: TRUE if the path is UNC // FALSE if not // // Comments: // // History: Date Author Comment // 6/21/96 ericflo Ported /////////////////////////////////////////////////////////// BOOL IsUNCPath(LPCTSTR lpPath) { if ((!lpPath) || (!lpPath[0]) && (!lpPath[1])) return FALSE; if (lpPath[0] == TEXT('\\') && lpPath[1] == TEXT('\\')) { return(TRUE); } return(FALSE); } /////////////////////////////////////////////////////////// // MakePathUNC() // // Purpose: Makes the given path UNC s.t. it can be accessed from a remote machine.. // if the path contains %systemroot% expanded then it substitutes // \\machname\admin$ otherwise \\machname\<driveletter>$ // // Parameters: lpPath - Input Path (needs to be absolute) // szComputerName - Name of the computer on which this is the local path // // Return: Path if it was fone successfully // NULL if not // // Comments: /////////////////////////////////////////////////////////// LPTSTR MakePathUNC(LPTSTR pwszFile, LPTSTR szComputerName) { MACRO_LI_PrologEx_C(PIF_STD_C, MakePathUNC) LPTSTR szUNCPath = NULL; TCHAR szSysRoot[MAX_PATH]; DWORD dwSysLen; LPTSTR lpEnd = NULL; OutD(LI1(TEXT("Entering with <%s>"), pwszFile ? pwszFile : TEXT("NULL"))); szUNCPath = (LPTSTR)LocalAlloc(LPTR, sizeof(TCHAR)*(lstrlen(pwszFile)+lstrlen(szComputerName)+3+lstrlen(TEXT("admin$"))+1)); if (!szUNCPath) return NULL; if (!pwszFile || !*pwszFile) { OutD(LI0(TEXT("lpFile is NULL, setting lpResult to a null string"))); *szUNCPath = TEXT('\0'); return szUNCPath; } if (IsUNCPath(pwszFile)) { lstrcpy(szUNCPath, pwszFile); return szUNCPath; } lstrcpy(szUNCPath, TEXT("\\\\")); lstrcat(szUNCPath, szComputerName); // // If the first part of lpFile is the expanded value of %SystemRoot% // if (!ExpandEnvironmentStrings (TEXT("%SystemRoot%"), szSysRoot, MAX_PATH)) { OutD(LI1(TEXT("ExpandEnvironmentString failed with error %d, setting szSysRoot to %systemroot% "), GetLastError())); LocalFree((HLOCAL)szUNCPath); return NULL; } dwSysLen = lstrlen(szSysRoot); lpEnd = CheckSlash(szUNCPath); // // if the prefix is the same as expanded systemroot then.. // if (((DWORD)lstrlen(pwszFile) > dwSysLen) && (CompareString (LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, szSysRoot, dwSysLen, pwszFile, dwSysLen) == CSTR_EQUAL)) { lstrcat(szUNCPath, TEXT("admin$")); lstrcat(szUNCPath, pwszFile+dwSysLen); } else { if (pwszFile[1] != TEXT(':')) { OutD(LI1(TEXT("Input path %s is not an absolute path"), pwszFile)); lstrcpy(szUNCPath, pwszFile); return szUNCPath; } lpEnd[0] = pwszFile[0]; lpEnd[1] = TEXT('$'); lpEnd[2] = TEXT('\0'); lstrcat(szUNCPath, pwszFile+2); } OutD(LI1(TEXT("Returning a UNCPath of %s"), szUNCPath)); return szUNCPath; } /////////////////////////////////////////////////////////// // AllocAdmFileInfo() // // Purpose: Allocates a new struct for ADMFILEINFO // // Parameters: pwszFile - File name // pwszGPO - Gpo // pftWrite - Last write time /////////////////////////////////////////////////////////// ADMFILEINFO *AllocAdmFileInfo(WCHAR *pwszFile, WCHAR *pwszGPO, FILETIME *pftWrite) { MACRO_LI_PrologEx_C(PIF_STD_C, AllocAdmFileInfo) ADMFILEINFO *pAdmFileInfo = (ADMFILEINFO *) LocalAlloc( LPTR, sizeof(ADMFILEINFO) ); if ( pAdmFileInfo == NULL ) { OutD(LI0(TEXT("Failed to allocate memory."))); return NULL; } pAdmFileInfo->pwszFile = (WCHAR *) LocalAlloc( LPTR, (lstrlen(pwszFile) + 1) * sizeof(WCHAR) ); if ( pAdmFileInfo->pwszFile == NULL ) { OutD(LI0(TEXT("Failed to allocate memory."))); LocalFree( pAdmFileInfo ); return NULL; } pAdmFileInfo->pwszGPO = (WCHAR *) LocalAlloc( LPTR, (lstrlen(pwszGPO) + 1) * sizeof(WCHAR) ); if ( pAdmFileInfo->pwszGPO == NULL ) { OutD(LI0(TEXT("Failed to allocate memory."))); LocalFree( pAdmFileInfo->pwszFile ); LocalFree( pAdmFileInfo ); return NULL; } lstrcpy( pAdmFileInfo->pwszFile, pwszFile ); lstrcpy( pAdmFileInfo->pwszGPO, pwszGPO ); pAdmFileInfo->ftWrite = *pftWrite; return pAdmFileInfo; } /////////////////////////////////////////////////////////// // FreeAdmFileInfo() // // Purpose: Deletes a ADMFILEINFO struct // // Parameters: pAdmFileInfo - Struct to delete // pftWrite - Last write time /////////////////////////////////////////////////////////// void FreeAdmFileInfo( ADMFILEINFO *pAdmFileInfo ) { if ( pAdmFileInfo ) { LocalFree( pAdmFileInfo->pwszFile ); LocalFree( pAdmFileInfo->pwszGPO ); LocalFree( pAdmFileInfo ); } } /////////////////////////////////////////////////////////// // FreeAdmFileCache() - taken from gpreg.cpp in nt\ds\security\gina\userenv\policy // // Purpose: Frees Adm File list // // Parameters: pAdmFileCache - List of Adm files to free /////////////////////////////////////////////////////////// void FreeAdmFileCache( ADMFILEINFO *pAdmFileCache ) { ADMFILEINFO *pNext; while ( pAdmFileCache ) { pNext = pAdmFileCache->pNext; FreeAdmFileInfo( pAdmFileCache ); pAdmFileCache = pNext; } } /////////////////////////////////////////////////////////// // AddAdmFile() - taken from gpreg.cpp in nt\ds\security\gina\userenv\policy // // Purpose: Prepends to list of Adm files // // Parameters: pwszFile - File path // pwszGPO - Gpo // pftWrite - Last write time // ppAdmFileCache - List of Adm files processed /////////////////////////////////////////////////////////// BOOL AddAdmFile(WCHAR *pwszFile, WCHAR *pwszGPO, FILETIME *pftWrite, WCHAR *szComputerName, ADMFILEINFO **ppAdmFileCache) { MACRO_LI_PrologEx_C(PIF_STD_C, AddAdmFile) LPWSTR wszLongPath; LPWSTR pwszUNCPath; OutD(LI1(TEXT("Adding File name <%s> to the Adm list."), pwszFile)); if ((szComputerName) && (*szComputerName) && (!IsUNCPath(pwszFile))) { wszLongPath = MakePathUNC(pwszFile, szComputerName); if (!wszLongPath) { OutD(LI1(TEXT("Failed to Make the path UNC with error %d."), GetLastError())); return FALSE; } pwszUNCPath = wszLongPath; } else pwszUNCPath = pwszFile; ADMFILEINFO *pAdmInfo = AllocAdmFileInfo(pwszUNCPath, pwszGPO, pftWrite); if ( pAdmInfo == NULL ) return FALSE; pAdmInfo->pNext = *ppAdmFileCache; *ppAdmFileCache = pAdmInfo; return TRUE; } /////////////////////////////////////////////////////////// // Function: SystemTimeToWbemTime // // Description: // // Parameters: // // Return: // // History: 12/08/99 leonardm Created. /////////////////////////////////////////////////////////// #define WBEM_TIME_STRING_LENGTH 25 HRESULT SystemTimeToWbemTime(SYSTEMTIME& sysTime, _bstr_t &xbstrWbemTime) { WCHAR *xTemp = new WCHAR[WBEM_TIME_STRING_LENGTH + 1]; if(!xTemp) return E_OUTOFMEMORY; int nRes = wsprintf(xTemp, L"%04d%02d%02d%02d%02d%02d.000000+000", sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond); if(nRes != WBEM_TIME_STRING_LENGTH) return E_FAIL; xbstrWbemTime = xTemp; if(!xbstrWbemTime) return E_OUTOFMEMORY; return S_OK; } /////////////////////////////////////////////////////////// // ParseRegistryFile() // // Purpose: Parses a registry.pol file // // Parameters: lpRegistry - Path to registry file (.INF) // pfnRegFileCallback - Callback function // pHashTable - Hash table for registry keys // // // Return: TRUE if successful // FALSE if an error occurs /////////////////////////////////////////////////////////// BOOL ParseRegistryFile (LPTSTR lpRegistry, PFNREGFILECALLBACK pfnRegFileCallback, REGHASHTABLE *pHashTable) { MACRO_LI_PrologEx_C(PIF_STD_C, ParseRegistryFile) BOOL bRet = FALSE; __try { OutD(LI1(TEXT("Entering with <%s>."), lpRegistry)); // // Allocate buffers to hold the keyname, valuename, and data // LPWSTR lpValueName = NULL; LPBYTE lpData = NULL; INT iType; DWORD dwType = REG_SZ, dwDataLength, dwValue = 0; BOOL bHKCU = TRUE; UINT nErrLine = 0; HINF hInfAdm = NULL; LPWSTR lpKeyName = (LPWSTR) LocalAlloc (LPTR, MAX_KEYNAME_SIZE * sizeof(WCHAR)); if (!lpKeyName) { OutD(LI1(TEXT("Failed to allocate memory with %d"), GetLastError())); goto Exit; } lpValueName = (LPWSTR) LocalAlloc (LPTR, MAX_VALUENAME_SIZE * sizeof(WCHAR)); if (!lpValueName) { OutD(LI1(TEXT("Failed to allocate memory with %d"), GetLastError())); goto Exit; } // Get the AddReg.Hkcu section for the registry strings. nErrLine = 0; hInfAdm = SetupOpenInfFile(lpRegistry, NULL, INF_STYLE_WIN4, &nErrLine); if (INVALID_HANDLE_VALUE != hInfAdm) { for (int iSection = 0; iSection < 2; iSection++) { OutD(LI1(TEXT("Reading section #%d."), iSection)); bHKCU = (1 == iSection) ? TRUE : FALSE; // Get the first line in this section. INFCONTEXT infContext; BOOL bLineFound = SetupFindFirstLine(hInfAdm, bHKCU ? TEXT("AddRegSection.HKCU") : TEXT("AddRegSection.HKLM"), NULL, &infContext); DWORD dwReqSize = 0; while (bLineFound) { // Read the data // ********************************** // Process the registry setting line. // Read the keyname ZeroMemory(lpKeyName, MAX_KEYNAME_SIZE); dwReqSize = 0; if (!SetupGetStringField(&infContext, 2, lpKeyName, MAX_KEYNAME_SIZE, &dwReqSize)) { if (dwReqSize >= MAX_KEYNAME_SIZE) OutD(LI0(TEXT("Keyname exceeded max size"))); else OutD(LI1(TEXT("Failed to read keyname from line, error %d."), GetLastError())); goto Exit; } // Read the valuename ZeroMemory(lpValueName, MAX_VALUENAME_SIZE); dwReqSize = 0; if (!SetupGetStringField(&infContext, 3, lpValueName, MAX_VALUENAME_SIZE, &dwReqSize)) { if (dwReqSize >= MAX_VALUENAME_SIZE) OutD(LI0(TEXT("Valuename exceeded max size"))); else { OutD(LI1(TEXT("Failed to read valuename from line, error %d."), GetLastError())); } goto Exit; } // Read the type if (!SetupGetIntField(&infContext, 4, &iType)) { OutD(LI1(TEXT("Failed to read type from line, error %d."), GetLastError())); goto Exit; } lpData = NULL; dwDataLength = 0; if (0 == iType) { dwType = REG_SZ; // Allocate memory for data dwReqSize = 0; if (!SetupGetStringField(&infContext, 5, NULL, 0, &dwReqSize)) { OutD(LI1(TEXT("Failed to get size of string value from line, error %d."), GetLastError())); goto Exit; } if (dwReqSize > 0) { lpData = (LPBYTE)LocalAlloc(LPTR, dwReqSize * sizeof(TCHAR)); if (!lpData) { OutD(LI1(TEXT("Failed to allocate memory for data with %d"), GetLastError())); goto Exit; } // Read string data dwDataLength = dwReqSize; dwReqSize = 0; if (!SetupGetStringField(&infContext, 5, (LPTSTR)lpData, dwDataLength, &dwReqSize)) { OutD(LI1(TEXT("Failed to get size of string value from line, error %d."), GetLastError())); goto Exit; } // convert to wide char string so the reader of the data doesn't have to guess // whether the data was written in ansi or unicode. if (NULL != lpData && dwDataLength > 0) { _bstr_t bstrData = (LPTSTR)lpData; dwDataLength = bstrData.length() * sizeof(WCHAR); } } else OutD(LI0(TEXT("Error. Size of string data is 0."))); } else if (0x10001 == iType) { dwType = REG_DWORD; // Read numeric data dwDataLength = sizeof(dwValue); dwValue = 0; dwReqSize = 0; if (!SetupGetBinaryField(&infContext, 5, (PBYTE)&dwValue, dwDataLength, &dwReqSize)) { OutD(LI1(TEXT("Failed to get DWORD value from line, error %d."), GetLastError())); goto Exit; } lpData = (LPBYTE)&dwValue; } else { OutD(LI1(TEXT("Invalid type (%lX)."), dwType)); goto Exit; } if (NULL != lpData) { // Call the callback function if (!pfnRegFileCallback (bHKCU, lpKeyName, lpValueName, dwType, dwDataLength, lpData, pHashTable )) { OutD(LI0(TEXT("Callback function returned false."))); goto Exit; } } if (0 == iType && lpData) LocalFree (lpData); lpData = NULL; // ********************************** // Move to the next line in the INF file. bLineFound = SetupFindNextLine(&infContext, &infContext); } } bRet = TRUE; } else OutD(LI1(TEXT("Error %d opening INF file,"), GetLastError())); Exit: // Finished OutD(LI0(TEXT("Leaving."))); if (lpData) LocalFree(lpData); if (lpKeyName) LocalFree(lpKeyName); if (lpValueName) LocalFree(lpValueName); } __except(TRUE) { OutD(LI0(TEXT("Exception in ParseRegistryFile."))); } return bRet; } /////////////////////////////////////////////////////////// // SetRegistryValue() // // Purpose: Callback from ParseRegistryFile that sets // registry policies // // Parameters: lpKeyName - Key name // lpValueName - Value name // dwType - Registry data type // lpData - Registry data // pwszGPO - Gpo // pwszSOM - Sdou that the Gpo is linked to // pHashTable - Hash table for registry keys // // Return: TRUE if successful // FALSE if an error occurs /////////////////////////////////////////////////////////// BOOL SetRegistryValue (BOOL bHKCU, LPTSTR lpKeyName, LPTSTR lpValueName, DWORD dwType, DWORD dwDataLength, LPBYTE lpData, REGHASHTABLE *pHashTable) { MACRO_LI_PrologEx_C(PIF_STD_C, SetRegistryValue) BOOL bRet = FALSE; __try { BOOL bUseValueName = FALSE; // // Save registry value // bRet = AddRegHashEntry( pHashTable, REG_ADDVALUE, bHKCU, lpKeyName, lpValueName, dwType, dwDataLength, lpData, NULL, NULL, bUseValueName ? lpValueName : TEXT(""), TRUE ); if (bRet) { switch (dwType) { case REG_SZ: case REG_EXPAND_SZ: OutD(LI2(TEXT("%s => %s [OK]"), lpValueName, (LPTSTR)lpData)); break; case REG_DWORD: OutD(LI2(TEXT("%s => %d [OK]"), lpValueName, *((LPDWORD)lpData))); break; case REG_NONE: break; default: OutD(LI1(TEXT("%s was set successfully"), lpValueName)); break; } } else { pHashTable->hrError = HRESULT_FROM_WIN32(GetLastError()); OutD(LI2(TEXT("Failed AddRegHashEntry for value <%s> with %d"), lpValueName, pHashTable->hrError)); } } __except(TRUE) { OutD(LI0(TEXT("Exception in SetRegistryValue."))); } return bRet; } /////////////////////////////////////////////////////////// HRESULT CRSoPGPO::StoreADMSettings(LPWSTR wszGPO, LPWSTR wszSOM) { MACRO_LI_PrologEx_C(PIF_STD_C, StoreADMSettings) HRESULT hr = E_FAIL; BOOL bContinue = TRUE; __try { OutD(LI0(TEXT("\r\nEntered StoreADMSettings function."))); // Setup hash table REGHASHTABLE *pHashTable = AllocHashTable(); if (NULL == pHashTable) { bContinue = FALSE; hr = HRESULT_FROM_WIN32(GetLastError()); } WCHAR pwszFile[MAX_PATH]; LPWSTR pwszEnd = NULL; if (bContinue) { // convert the INS file path to a wide char string _bstr_t bstrINSFile = m_szINSFile; StrCpyW(pwszFile, (LPWSTR)bstrINSFile); PathRemoveFileSpec(pwszFile); // Log Adm data pwszEnd = pwszFile + lstrlen(pwszFile); lstrcpy(pwszEnd, L"\\*.adm"); // Remember end point so that the actual Adm filename can be // easily concatenated. pwszEnd = pwszEnd + lstrlen( L"\\" ); } HANDLE hFindFile = NULL; WIN32_FIND_DATA findData; ZeroMemory(&findData, sizeof(findData)); if (bContinue) { // // Enumerate all Adm files // hFindFile = FindFirstFile( pwszFile, &findData); if (INVALID_HANDLE_VALUE == hFindFile) bContinue = FALSE; } ADMFILEINFO *pAdmFileCache = NULL; if (bContinue) { WIN32_FILE_ATTRIBUTE_DATA attrData; TCHAR szComputerName[3*MAX_COMPUTERNAME_LENGTH + 1]; do { DWORD dwSize = 3*MAX_COMPUTERNAME_LENGTH + 1; if (!GetComputerName(szComputerName, &dwSize)) { OutD(LI1(TEXT("ProcessGPORegistryPolicy: Couldn't get the computer Name with error %d."), GetLastError())); szComputerName[0] = TEXT('\0'); } if ( !(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) { lstrcpy( pwszEnd, findData.cFileName); WCHAR wszRegDataFile[MAX_PATH]; StrCpyW(wszRegDataFile, pwszFile); PathRenameExtension(wszRegDataFile, TEXT(".INF")); if (ParseRegistryFile(wszRegDataFile, SetRegistryValue, pHashTable)) { ZeroMemory (&attrData, sizeof(attrData)); if ( GetFileAttributesEx (pwszFile, GetFileExInfoStandard, &attrData ) != 0 ) { if (!AddAdmFile( pwszFile, wszGPO, &attrData.ftLastWriteTime, szComputerName, &pAdmFileCache ) ) { OutD(LI0(TEXT("ProcessGPORegistryPolicy: AddAdmFile failed."))); if (pHashTable->hrError == S_OK) pHashTable->hrError = HRESULT_FROM_WIN32(GetLastError()); hr = pHashTable->hrError; } } } else OutD(LI0(TEXT("ProcessGPORegistryPolicy: ParseRegistryFile failed."))); } // if findData & file_attr_dir } while ( FindNextFile(hFindFile, &findData) );// do FindClose(hFindFile); } // if hfindfile // // Log registry data to Cimom database // if (!LogRegistryRsopData(pHashTable, wszGPO, wszSOM)) { OutD(LI0(TEXT("ProcessGPOs: Error when logging Registry Rsop data. Continuing."))); if (pHashTable->hrError == S_OK) pHashTable->hrError = HRESULT_FROM_WIN32(GetLastError()); hr = pHashTable->hrError; } if (!LogAdmRsopData(pAdmFileCache)) { OutD(LI0(TEXT("ProcessGPOs: Error when logging Adm Rsop data. Continuing."))); if (pHashTable->hrError == S_OK) pHashTable->hrError = HRESULT_FROM_WIN32(GetLastError()); hr = pHashTable->hrError; } FreeHashTable(pHashTable); FreeAdmFileCache(pAdmFileCache); } __except(TRUE) { OutD(LI0(TEXT("Exception in StoreADMSettings."))); } OutD(LI0(TEXT("Exiting StoreADMSettings function.\r\n"))); return hr; } /////////////////////////////////////////////////////////// // LogAdmRsopData() // // Purpose: Logs Rsop ADM template data to Cimom database // // Parameters: pAdmFileCache - List of adm file to log // pWbemServices - Namespace pointer // // Return: True if successful /////////////////////////////////////////////////////////// BOOL CRSoPGPO::LogAdmRsopData(ADMFILEINFO *pAdmFileCache) { MACRO_LI_PrologEx_C(PIF_STD_C, LogAdmRsopData) BOOL bRet = TRUE; __try { // if ( !DeleteInstances( L"RSOP_AdministrativeTemplateFile", pWbemServices ) ) // return FALSE; // Create & populate RSOP_IEAdministrativeTemplateFile _bstr_t bstrClass = L"RSOP_IEAdministrativeTemplateFile"; ComPtr<IWbemClassObject> pATF = NULL; HRESULT hr = CreateRSOPObject(bstrClass, &pATF); if (SUCCEEDED(hr)) { while ( pAdmFileCache ) { //------------------------------------------------ // name _bstr_t bstrName = pAdmFileCache->pwszFile; hr = PutWbemInstancePropertyEx(L"name", bstrName, pATF); //------------------------------------------------ // GPOID hr = PutWbemInstancePropertyEx(L"GPOID", pAdmFileCache->pwszGPO, pATF); //------------------------------------------------ // lastWriteTime SYSTEMTIME sysTime; if (!FileTimeToSystemTime( &pAdmFileCache->ftWrite, &sysTime )) OutD(LI1(TEXT("FileTimeToSystemTime failed with 0x%x" ), GetLastError() )); else { _bstr_t bstrTime; HRESULT hr = SystemTimeToWbemTime(sysTime, bstrTime); if(FAILED(hr) || bstrTime.length() <= 0) OutD(LI1(TEXT("Call to SystemTimeToWbemTime failed. hr=0x%08X"),hr)); else { hr = PutWbemInstancePropertyEx(L"lastWriteTime", bstrTime, pATF); if ( FAILED(hr) ) OutD(LI1(TEXT("Put failed with 0x%x" ), hr )); } } // // Commit all above properties by calling PutInstance, semisynchronously // BSTR bstrObjPath = NULL; hr = PutWbemInstance(pATF, bstrClass, &bstrObjPath); pAdmFileCache = pAdmFileCache->pNext; } } else bRet = FALSE; OutD(LI0(TEXT("Successfully logged Adm data" ))); } __except(TRUE) { OutD(LI0(TEXT("Exception in LogAdmRsopData."))); } return bRet; } /////////////////////////////////////////////////////////// // LogRegistryRsopData() // // Purpose: Logs registry Rsop data to Cimom database // // Parameters: dwFlags - Gpo Info flags // pHashTable - Hash table with registry policy data // pWbemServices - Namespace pointer for logging // // Return: True if successful /////////////////////////////////////////////////////////// BOOL CRSoPGPO::LogRegistryRsopData(REGHASHTABLE *pHashTable, LPWSTR wszGPOID, LPWSTR wszSOMID) { MACRO_LI_PrologEx_C(PIF_STD_C, LogRegistryRsopData) BOOL bRet = FALSE; __try { _bstr_t bstrGPOID = wszGPOID; _bstr_t bstrSOMID = wszSOMID; // if ( !DeleteInstances( L"RSOP_RegistryPolicySetting", pWbemServices ) ) // return FALSE; // Create & populate RSOP_IERegistryPolicySetting _bstr_t bstrClass = L"RSOP_IERegistryPolicySetting"; ComPtr<IWbemClassObject> pRPS = NULL; HRESULT hr = CreateRSOPObject(bstrClass, &pRPS); if (SUCCEEDED(hr)) { for ( DWORD i=0; i<HASH_TABLE_SIZE; i++ ) { REGKEYENTRY *pKeyEntry = pHashTable->aHashTable[i]; while ( pKeyEntry ) { WCHAR *pwszKeyName = pKeyEntry->pwszKeyName; REGVALUEENTRY *pValueEntry = pKeyEntry->pValueList; while ( pValueEntry ) { DWORD dwOrder = 1; WCHAR *pwszValueName = pValueEntry->pwszValueName; REGDATAENTRY *pDataEntry = pValueEntry->pDataList; while ( pDataEntry ) { // Write RSOP_PolicySetting keys out //------------------------------------------------ // precedence OutD(LI2(TEXT("Storing property 'precedence' in %s, value = %lx"), (BSTR)bstrClass, m_dwPrecedence)); hr = PutWbemInstancePropertyEx(L"precedence", (long)m_dwPrecedence, pRPS); //------------------------------------------------ // id GUID guid; hr = CoCreateGuid( &guid ); if ( FAILED(hr) ) { OutD(LI0(TEXT("Failed to obtain guid" ))); return FALSE; } WCHAR wszId[MAX_LENGTH]; StringFromGUID2(guid, wszId, sizeof(wszId)); _bstr_t xId( wszId ); if ( !xId ) { OutD(LI0(TEXT("Failed to allocate memory" ))); return FALSE; } hr = PutWbemInstancePropertyEx(L"id", xId, pRPS); if ( FAILED(hr) ) return FALSE; //------------------------------------------------ // currentUser hr = PutWbemInstancePropertyEx(L"currentUser", pKeyEntry->bHKCU ? true : false, pRPS); if ( FAILED(hr) ) return FALSE; //------------------------------------------------ // deleted hr = PutWbemInstancePropertyEx(L"deleted", pDataEntry->bDeleted ? true : false, pRPS); if ( FAILED(hr) ) return FALSE; //------------------------------------------------ // name _bstr_t xName( pwszValueName ); hr = PutWbemInstancePropertyEx(L"name", xName, pRPS); if ( FAILED(hr) ) return FALSE; //------------------------------------------------ // valueName hr = PutWbemInstancePropertyEx(L"valueName", xName, pRPS); if ( FAILED(hr) ) return FALSE; //------------------------------------------------ // registryKey _bstr_t xKey( pwszKeyName ); hr = PutWbemInstancePropertyEx(L"registryKey", xKey, pRPS); if ( FAILED(hr) ) return FALSE; //------------------------------------------------ // GPOID hr = PutWbemInstancePropertyEx(L"GPOID", bstrGPOID, pRPS); if ( FAILED(hr) ) return FALSE; //------------------------------------------------ // SOMID hr = PutWbemInstancePropertyEx(L"SOMID", bstrSOMID, pRPS); if ( FAILED(hr) ) return FALSE; //------------------------------------------------ // command _bstr_t xCommand( pDataEntry->pwszCommand ); hr = PutWbemInstancePropertyEx(L"command", xCommand, pRPS); if ( FAILED(hr) ) return FALSE; //------------------------------------------------ // valueType hr = PutWbemInstancePropertyEx(L"valueType", (long)pDataEntry->dwValueType, pRPS); if ( FAILED(hr) ) return FALSE; //------------------------------------------------ // value // Create a SAFEARRAY from our array of bstr connection names SAFEARRAY *psa = NULL; if (pDataEntry->dwDataLen > 0) { psa = CreateSafeArray(VT_UI1, pDataEntry->dwDataLen); if (NULL == psa) { OutD(LI0(TEXT("Failed to allocate memory" ))); return FALSE; } } for (DWORD iElem = 0; iElem < pDataEntry->dwDataLen; iElem++) { hr = SafeArrayPutElement(psa, (LONG*)&iElem, (void*)&pDataEntry->pData[iElem]); if ( FAILED( hr ) ) { OutD(LI1(TEXT("Failed to SafeArrayPutElement with 0x%x" ), hr )); return FALSE; } } VARIANT var; var.vt = VT_ARRAY | VT_UI1; var.parray = psa; hr = PutWbemInstancePropertyEx(L"value", &var, pRPS); if ( FAILED(hr) ) return FALSE; OutD(LI0(TEXT("<<object>>"))); // // Commit all above properties by calling PutInstance, semisynchronously // BSTR bstrObjPath = NULL; hr = PutWbemInstance(pRPS, bstrClass, &bstrObjPath); if ( FAILED(hr) ) return FALSE; pDataEntry = pDataEntry->pNext; dwOrder++; } pValueEntry = pValueEntry->pNext; } // while pValueEntry pKeyEntry = pKeyEntry->pNext; } // while pKeyEntry } // for bRet = TRUE; } OutD(LI0(TEXT("LogRegistry RsopData: Successfully logged registry Rsop data" ))); } __except(TRUE) { OutD(LI0(TEXT("Exception in LogRegistryRsopData."))); } return bRet; }
29.442289
126
0.542579
[ "object" ]
e9d2dc79ad5ddc8bcda25ec30bb9bd53d474c6e3
440
cpp
C++
cpp/tests/GasStationTest.cpp
qianbinbin/leetcode
915cecab0c940cd13847683ec55b17b77eb0f39b
[ "MIT" ]
4
2018-03-05T02:27:16.000Z
2021-03-15T14:19:44.000Z
cpp/tests/GasStationTest.cpp
qianbinbin/leetcode
915cecab0c940cd13847683ec55b17b77eb0f39b
[ "MIT" ]
null
null
null
cpp/tests/GasStationTest.cpp
qianbinbin/leetcode
915cecab0c940cd13847683ec55b17b77eb0f39b
[ "MIT" ]
2
2018-07-22T10:32:10.000Z
2018-10-20T03:14:28.000Z
#include "GasStation.h" #include "gtest/gtest.h" #include <string> using namespace lcpp; TEST(GasStation, Solution134_1) { std::vector<int> Gas1{1, 2, 3, 4, 5}, Cost1{3, 4, 5, 1, 2}; const int Expected1 = 3; EXPECT_EQ(Expected1, Solution134_1().canCompleteCircuit(Gas1, Cost1)); std::vector<int> Gas2{2, 3, 4}, Cost2{3, 4, 3}; const int Expected2 = -1; EXPECT_EQ(Expected2, Solution134_1().canCompleteCircuit(Gas2, Cost2)); }
29.333333
72
0.690909
[ "vector" ]
e9d37bc7302842732034b95a5f53f5c294177dc8
5,423
cc
C++
src/RpcChannel.cc
sroycode/zqrpc
aa2eee8b794f71998e0861f40f0a4e9895d2c527
[ "MIT" ]
6
2015-01-08T17:09:43.000Z
2022-01-28T01:45:57.000Z
src/RpcChannel.cc
sroycode/zqrpc
aa2eee8b794f71998e0861f40f0a4e9895d2c527
[ "MIT" ]
null
null
null
src/RpcChannel.cc
sroycode/zqrpc
aa2eee8b794f71998e0861f40f0a4e9895d2c527
[ "MIT" ]
3
2016-03-04T10:54:42.000Z
2022-01-28T01:45:59.000Z
/** * @project zqrpc * @file src/RpcChannel.cc * @author S Roychowdhury <sroycode @ gmail DOT com> * @version 0.1 * * @section LICENSE * * Copyright (c) 2014 S Roychowdhury * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @section DESCRIPTION * * RpcChannel.cc : Channel Implementation * */ #include <google/protobuf/descriptor.h> #include "zqrpc/RpcHeaders.hh" #include "zqrpc/RpcChannel.hh" #include <boost/format.hpp> #include <boost/lexical_cast.hpp> #include <deque> #include <vector> #include <cstdio> #include <cstdlib> #include <climits> zqrpc::RpcChannel::RpcChannel(zmq::context_t* context, const char* url) : context_(context), socket_(context,ZMQ_DEALER,boost::lexical_cast<std::string>(boost::this_thread::get_id())), url_(url), nextreply_(0) { socket_.connect(url); } zqrpc::RpcChannel::~RpcChannel() { Close(); } void zqrpc::RpcChannel::ZSendMethod(const google::protobuf::MethodDescriptor* method, zqrpc::ZController* controller, const google::protobuf::Message* request) { try { std::string opcode=std::string(method->full_name()); std::string buffer; if (! request->SerializeToString(&buffer) ) throw zqrpc::ZError(ZEC_INVALIDHEADER); typedef std::vector<std::string> FramesT; std::string myid = boost::lexical_cast<std::string>(boost::this_thread::get_id()); std::string nextid = boost::lexical_cast<std::string>(++nextreply_); FramesT frames; frames.push_back(""); frames.push_back(nextid); frames.push_back(opcode); frames.push_back(buffer); bool status = socket_.Send<FramesT>(frames); if (!status) throw zmq::error_t(); // OK controller->rcode_ = ZRC_WORKING; controller->reqno_ = replylist_.size(); replylist_[nextreply_]=controller; } catch (zqrpc::ZError& e) { controller->zerror_.reset(ZEC_INVALIDHEADER); controller->rcode_ = ZRC_ERROR; } catch (zqrpc::RetryException& e) { controller->zerror_.reset(ZEC_CONNECTIONERROR); controller->rcode_ = ZRC_ERROR; } catch (zmq::error_t& e) { controller->zerror_.reset(ZEC_CONNECTIONERROR); controller->rcode_ = ZRC_ERROR; } catch (std::exception& e) { controller->zerror_.reset(ZEC_CLIENTERROR); controller->rcode_ = ZRC_ERROR; } } void zqrpc::RpcChannel::ZRecvMethod(ZController* controller, google::protobuf::Message* response, long timeout) { // TODO: handle -1 , bad hack to make it 60 secs if (timeout<=0) timeout=60000; // The Loop below keeps polling and taking in data const long start = zqrpc::mstime(); bool toget=false; typedef std::vector<std::string> FramesT; FramesT frames; do { // check if we need to poll // if there is toget we poll and get the data anyway for whosoever // if not toget we check if our controller has got its data , if so break if (!toget && controller->rcode_ != ZRC_WORKING) break; long elapsed = zqrpc::mstime() - start; // if time elapsed is more than timeout if (elapsed > timeout) break; if (!toget) toget = socket_.Poll(timeout-elapsed); // if toget is false we have spent all the wait time if (!toget) break; // we have action typedef std::vector<std::string> FramesT; try { frames = socket_.NonBlockingRecv<FramesT>(); } catch (zqrpc::RetryException& e) { // no more data , set toget false and loop toget=false; continue; } // discard bad data , but toget remains true hence loop if (frames.size() !=4) continue; // BLANK ID ERRORCODE DATA // data looks ok std::size_t nextid = boost::lexical_cast<std::size_t>(frames[1]); // check if nextid is rogue , reject and loop if (nextid > nextreply_) continue; // get the associated controller pointer zqrpc::RpcChannel::ReplyListT::iterator it = replylist_.find(nextid); if (it==replylist_.end()) continue; zqrpc::ZController* othercon = it->second; int error = atoi(frames.at(2).c_str()); if (error) { othercon->zerror_ = zqrpc::ZError(static_cast<zqrpc::ErrorCodeE>(error),frames.at(4).c_str()); othercon->rcode_ = ZRC_ERROR; } else { othercon->payload_ = frames.at(3); othercon->rcode_ = ZRC_READY; } replylist_.erase(it); } while(true); if (controller->rcode_==ZRC_READY) response->ParseFromString(controller->payload_); } void zqrpc::RpcChannel::Close() { socket_.disconnect(url_); socket_.close(); }
33.68323
97
0.699797
[ "vector" ]
e9d58e00c588bb88e92550eac1e19c8c268eec30
1,642
cpp
C++
assignment2.cpp
krisf01/Computer-Systems-and-C-Programming
e6c3f464bcd12e06c86b57ce7bc12aacc03e423a
[ "MIT" ]
null
null
null
assignment2.cpp
krisf01/Computer-Systems-and-C-Programming
e6c3f464bcd12e06c86b57ce7bc12aacc03e423a
[ "MIT" ]
null
null
null
assignment2.cpp
krisf01/Computer-Systems-and-C-Programming
e6c3f464bcd12e06c86b57ce7bc12aacc03e423a
[ "MIT" ]
null
null
null
#include<iostream> #include<string> #define SIZE 100 using namespace std; class Array { //declare pointer to array int *arr; int size; public: Array(); int setVale(int index,int val); int operator[](int index) const; int getCapacity(); //destroctor ~Array(); }; Array::~Array() { delete[]arr; } //default constructor Array::Array() { //allocate memory for array arr = new int[SIZE]; //initialize array with zeors for (int i = 0; i < 100; i++) arr[i] = 0; size = 0; } int Array::getCapacity() { return SIZE; } int Array::setVale(int index,int val) { if (index >= 0 && index < SIZE) { arr[index] = val; if(arr[index]) size++; return 0; } else return - 1; } int Array::operator[](int index) const { return arr[index]; } int main() { //declare Array object Array arr; string index,value; int i, val, count = 0;; std::string::size_type sz; char choice; do { cout << "Input an index and a value to store[Q to quit]: "; cin >> index; if (index == "q" || index == "Q") break; cin >> value; if (index >= "a" && index <= "z") i = 0; else i = stoi(index, &sz); val = stoi(value, &sz); if (arr.setVale(i, val) >= 0) count++; } while (1); cout << "You stored these many values: " << count << endl; cout << "The index-value pair are: \n"; for (int i = 0; i < arr.getCapacity(); i++) { if (arr[i] > 0) cout << i << "=>" << arr[i] << endl; } }
17.655914
67
0.504263
[ "object" ]
e9d7fd68ca2f30dd3f90fe9aea47267867420672
1,974
cpp
C++
test/unit/module/real/combinatorial/fibonacci.cpp
leha-bot/eve
30e7a7f6bcc5cf524a6c2cc624234148eee847be
[ "MIT" ]
340
2020-09-16T21:12:48.000Z
2022-03-28T15:40:33.000Z
test/unit/module/real/combinatorial/fibonacci.cpp
leha-bot/eve
30e7a7f6bcc5cf524a6c2cc624234148eee847be
[ "MIT" ]
383
2020-09-17T06:56:35.000Z
2022-03-13T15:58:53.000Z
test/unit/module/real/combinatorial/fibonacci.cpp
leha-bot/eve
30e7a7f6bcc5cf524a6c2cc624234148eee847be
[ "MIT" ]
28
2021-02-27T23:11:23.000Z
2022-03-25T12:31:29.000Z
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #include "test.hpp" #include <eve/constant/valmin.hpp> #include <eve/constant/valmax.hpp> #include <eve/constant/nan.hpp> #include <eve/function/dec.hpp> #include <eve/function/inc.hpp> #include <eve/function/fibonacci.hpp> #include <eve/function/converter.hpp> #include <eve/logical.hpp> #include <cmath> //================================================================================================== // Types tests //================================================================================================== EVE_TEST_TYPES( "Check return types of eve::fibonacci" , eve::test::simd::ieee_reals) <typename T>(eve::as<T>) { using i_t = eve::as_integer_t<T, unsigned>; using elt_t = eve::element_type_t<T>; TTS_EXPR_IS(eve::fibonacci(i_t(), T(), T()), T); TTS_EXPR_IS(eve::fibonacci(std::uint8_t(), T(), T()), T); TTS_EXPR_IS(eve::fibonacci(i_t(), elt_t(), T()), T); TTS_EXPR_IS(eve::fibonacci(i_t(), T(), elt_t()), T); TTS_EXPR_IS(eve::fibonacci(i_t(), elt_t(), elt_t()), T); TTS_EXPR_IS(eve::fibonacci(std::uint8_t(), elt_t(), elt_t()), elt_t); }; //================================================================================================== // Test for corner-cases values //================================================================================================== EVE_TEST_TYPES( "Check corner-cases behavior of eve::fibonacci on wide" , eve::test::simd::ieee_reals ) <typename T>(eve::as<T>) { using eve::as; using i_t = eve::as_integer_t<T, unsigned>; TTS_EQUAL(eve::fibonacci(9u, T(1), T(1)) , T(55)); TTS_EQUAL(eve::fibonacci(i_t(9), T(1), T(1)) , T(55)); };
38.705882
100
0.457953
[ "vector" ]
e9f61fa589947d2cbecb494d0ed1b64a4030632b
20,209
cpp
C++
mwa29_a9/shapes_a6.cpp
jetblack87/cs537
8ed7b4ef8247b025d025c911cef0fb6df5b1fcd1
[ "Apache-2.0" ]
null
null
null
mwa29_a9/shapes_a6.cpp
jetblack87/cs537
8ed7b4ef8247b025d025c911cef0fb6df5b1fcd1
[ "Apache-2.0" ]
null
null
null
mwa29_a9/shapes_a6.cpp
jetblack87/cs537
8ed7b4ef8247b025d025c911cef0fb6df5b1fcd1
[ "Apache-2.0" ]
null
null
null
#include "Angel.h" #include "mat.h" #include "vec.h" #include <stdio.h> #include <string> #include <vector> typedef vec3 color3; typedef vec4 color4; typedef vec4 point4; //-------------------------------------------------------------------------- //---- CONSTANTS ------------------------------------------------------ //-------------------------------------------------------------------------- const char *TITLE = "mwa29 - CS537 assignment 6"; const int DEBUG_MAX_FACES = 1500; const char KEY_EYE_UP = 'q'; const char KEY_EYE_DOWN = 'Q'; const char KEY_EYE_CLOSE = 'w'; const char KEY_EYE_FAR = 'W'; const char KEY_DELTAUP = 'e'; const char KEY_DELTADOWN = 'E'; const char KEY_STOP = 'r'; const char KEY_START = 'R'; const char KEY_LIGHT_UP = 'a'; const char KEY_LIGHT_DOWN = 'A'; const char KEY_LIGHT_CLOSE = 's'; const char KEY_LIGHT_FAR = 'S'; const char KEY_LIGHT_LEFT = 'd'; const char KEY_LIGHT_RIGHT = 'D'; const double DELTA_DELTA = 0.001; const double DEFAULT_DELTA = 0.1; const char SMF_TYPE_VERTEX = 'v'; const char SMF_TYPE_FACE = 'f'; const int BOUNDING_BOX_INDEX_LEFT = 0; const int BOUNDING_BOX_INDEX_RIGHT = 1; const int BOUNDING_BOX_INDEX_BOTTOM = 2; const int BOUNDING_BOX_INDEX_TOP = 3; const int BOUNDING_BOX_INDEX_NEAR = 4; const int BOUNDING_BOX_INDEX_FAR = 5; const int BOUNDING_BOX_SIZE = 6; const color4 DEFAULT_COLOR = color4(0.0, 1.0, 0.0, 1.0); // MENU ITEMS const int PARALLEL_PROJECTION = 0; const int PERSPECTIVE_PROJECTION = 1; const int PHONG_SHADING = 2; const int GOURAUD_SHADING = 3; const int BRASS_MATERIAL = 4; const int RED_PLASTIC_MATERIAL = 5; const int GREEN_RUBBER_MATERIAL = 6; const double EYE_DELTA = 0.25; const double MAX_EYE_THETA = 360; const double MIN_EYE_THETA = 0; const double MAX_EYE_PHI = 180; const double MIN_EYE_PHI = -180; const double MAX_LIGHT_THETA = 360; const double MIN_LIGHT_THETA = 0; const double MAX_LIGHT_PHI = 180; const double MIN_LIGHT_PHI = -180; const color4 BRASS_AMBIENT(0.329412, 0.223529, 0.027451, 1.0); const color4 BRASS_DIFFUSE(0.780392, 0.568627, 0.113725, 1.0); const color4 BRASS_SPECULAR(0.992157, 0.941176, 0.807843, 1.0); const float BRASS_SHININESS = 0.21794872; const color4 RED_PLASTIC_AMBIENT(0.0, 0.0, 0.0, 1.0); const color4 RED_PLASTIC_DIFFUSE(0.5, 0.0, 0.0, 1.0); const color4 RED_PLASTIC_SPECULAR(0.7, 0.6, 0.6, 1.0); const float RED_PLASTIC_SHININESS = 0.25; const color4 GREEN_RUBBER_AMBIENT(0.0, 0.05, 0.0, 1.0); const color4 GREEN_RUBBER_DIFFUSE(0.4, 0.5, 0.4, 1.0); const color4 GREEN_RUBBER_SPECULAR(0.04, 0.7, 0.04, 1.0); const float GREEN_RUBBER_SHININESS = 0.078125; //-------------------------------------------------------------------------- //---- GLOBALS ------------------------------------------------------ //-------------------------------------------------------------------------- bool debug = false; int mainWindow; int menu; int w = 600, h = 600; double t = 0; // the time variable double dt = DEFAULT_DELTA; // the delta for time increment double light_dt = 0.01; double eye_radius = 0.0; double eye_theta = 0.0; double eye_phi = 0.0; GLint ModelView_loc; GLint Projection_loc; std::vector<vec3> points; std::vector<vec4> vertices; std::vector<vec4> normals; std::vector<vec3> faces; std::vector<color4> colors; std::string smf_path("models/lo-sphere.smf"); double bounding_box[BOUNDING_BOX_SIZE] = {-1.0, 1.0, -1.0, 1.0, -1.0, 1.0}; int current_projection = PARALLEL_PROJECTION; int current_shading = PHONG_SHADING; // Initialize shader lighting parameters point4 light0_position( 0.0, 0.0, -1.0, 0.0 ); color4 light0_ambient( 0.2, 0.2, 0.2, 1.0 ); color4 light0_diffuse( 1.0, 1.0, 1.0, 1.0 ); color4 light0_specular( 1.0, 1.0, 1.0, 1.0 ); point4 light1_position( 0.0, 0.0, 1.0, 0.0 ); color4 light1_ambient( 0.2, 0.2, 0.2, 1.0 ); color4 light1_diffuse( 1.0, 1.0, 1.0, 1.0 ); color4 light1_specular( 1.0, 1.0, 1.0, 1.0 ); double light1_radius = 0.0; double light1_theta = 0.0; double light1_phi = 0.0; color4 material_ambient = BRASS_AMBIENT; color4 material_diffuse = BRASS_DIFFUSE; color4 material_specular = BRASS_SPECULAR; float material_shininess = BRASS_SHININESS; //-------------------------------------------------------------------------- void parse_smf(std::string file_path, std::vector<vec3> &vertices, std::vector<vec3> &faces) { if (debug) { printf("[DEBUG] Parsing smf file: %s\n", file_path.c_str()); } FILE * file; file = fopen (file_path.c_str(),"r"); if (NULL != file) { char line[1000]; while (fgets ( line, sizeof line, file ) != NULL) { if (SMF_TYPE_VERTEX == line[0]) { double first; double second; double third; sscanf(line, "v %lf %lf %lf\n", &first, &second, &third); vertices.push_back(vec3(first, second, third)); } else if (SMF_TYPE_FACE == line[0]) { int first; int second; int third; sscanf(line, "f %d %d %d\n", &first, &second, &third); faces.push_back(vec3(first, second, third)); } } fclose (file); } if (debug) { printf("[DEBUG] Parse complete.\n"); } } std::vector<vec4> get_vertices(std::vector<vec3> points, std::vector<vec3> faces) { if (debug) { printf("[DEBUG] Getting vertices.\n"); } std::vector<vec4> vertices; for (uint i = 0; i < faces.size(); i++) { vertices.push_back(vec4(points.at(faces.at(i).x - 1), 1.0)); vertices.push_back(vec4(points.at(faces.at(i).y - 1), 1.0)); vertices.push_back(vec4(points.at(faces.at(i).z - 1), 1.0)); } if (debug) { printf("[DEBUG] Vertices gotten: %u.\n", (uint) vertices.size()); } return vertices; } std::vector<vec4> get_normals(std::vector<vec3> points, std::vector<vec3> faces) { std::vector<vec4> normals; for (uint i = 0; i < faces.size(); i++) { vec4 p0 = points.at(faces.at(i).x - 1); vec4 p1 = points.at(faces.at(i).y - 1); vec4 p2 = points.at(faces.at(i).z - 1); vec4 u = p1 - p0; vec4 v = p2 - p0; vec3 normal = normalize( cross(u, v) ); normals.push_back(normal); normals.push_back(normal); normals.push_back(normal); } return normals; } double min_double(double one, double two) { if (one < two) { return one; } else { return two; } } double max_double(double one, double two) { if (one > two) { return one; } else { return two; } } void calculate_bounding_box(std::vector<vec3> points) { if(debug) { printf("[DEBUG] Calculating bounding box.\n"); } double min_num = 5000.0; double max_num = -5000.0; for (uint i = 0; i < points.size(); i++) { vec3 p = points.at(i); min_num = min_double(p.x, min_num); max_num = max_double(p.x, max_num); min_num = min_double(p.y, min_num); max_num = max_double(p.y, max_num); min_num = min_double(p.z, min_num); max_num = max_double(p.z, max_num); } min_num = min_double(-1.0, min_num); // don't go lower than -1 max_num = max_double( 1.0, max_num); // don't go higher than 1 bounding_box[BOUNDING_BOX_INDEX_LEFT] = min_num; bounding_box[BOUNDING_BOX_INDEX_RIGHT] = max_num; bounding_box[BOUNDING_BOX_INDEX_BOTTOM] = min_num; bounding_box[BOUNDING_BOX_INDEX_TOP] = max_num; bounding_box[BOUNDING_BOX_INDEX_NEAR] = min_num; bounding_box[BOUNDING_BOX_INDEX_FAR] = max_num; if (debug) { printf("[DEBUG] Bounding box calculated\n"); for (int i = 0; i < BOUNDING_BOX_SIZE; i++) { printf("[DEBUG] %f\n", bounding_box[i]); } } } void read_smf ( void ) { parse_smf(smf_path, points, faces); if (debug && faces.size() > DEBUG_MAX_FACES) { printf("[DEBUG] Number of faces (%u) are greater than '%d', disabling DEBUG \n", (uint) faces.size(), DEBUG_MAX_FACES); debug = false; } vertices = get_vertices(points, faces); normals = get_normals(points, faces); calculate_bounding_box(points); if (debug) { printf("[DEBUG] printing points.\n"); for(uint i = 0; i < points.size(); i++) { printf("[DEBUG] %f, %f, %f\n", points.at(i).x, points.at(i).y, points.at(i).z); } printf("[DEBUG] printing faces.\n"); for(uint i = 0; i < faces.size(); i++) { printf("[DEBUG] %f, %f, %f\n", faces.at(i).x, faces.at(i).y, faces.at(i).z); } printf("[DEBUG] printing vertices.\n"); for(uint i = 0; i < vertices.size(); i++) { printf("[DEBUG] %f, %f, %f\n", vertices.at(i).x, vertices.at(i).y, vertices.at(i).z); if (2 == i % 3) { printf("\n"); } } printf("[DEBUG] printing colors.\n"); for(uint i = 0; i < colors.size(); i++) { printf("[DEBUG] %f, %f, %f\n", colors.at(i).x, colors.at(i).y, colors.at(i).z); } } } void init( void ) { // Create a vertex array object GLuint vao[1]; glGenVertexArrays( 1, vao ); glBindVertexArray( vao[0] ); // Create and initialize a buffer object GLuint buffer; glGenBuffers( 1, &buffer ); glBindBuffer( GL_ARRAY_BUFFER, buffer ); glBufferData( GL_ARRAY_BUFFER, (vertices.size()*sizeof(vec4)) + (colors.size()*sizeof(color4)) + (normals.size()*sizeof(vec4)), NULL, GL_STATIC_DRAW ); //load data separately glBufferSubData(GL_ARRAY_BUFFER, 0, vertices.size()*sizeof(vec4), &vertices[0]); glBufferSubData(GL_ARRAY_BUFFER, vertices.size()*sizeof(vec4), colors.size()*sizeof(color4), &colors[0]); glBufferSubData(GL_ARRAY_BUFFER, vertices.size()*sizeof(vec4) + colors.size()*sizeof(color4), normals.size()*sizeof(vec4), &normals[0]); // Load shaders and use the resulting shader program // GLuint program = InitShader( "vshdrcube.glsl", "fshdrcube.glsl" ); GLuint program; if (current_shading == GOURAUD_SHADING) { program = InitShader( "vshader53_a6.glsl", "fshader53_a6.glsl" ); } else { program = InitShader( "vshader56_a6.glsl", "fshader56_a6.glsl" ); } glUseProgram( program ); // Initialize the vertex position attribute from the vertex shader GLuint vPosition_loc = glGetAttribLocation(program, "vPosition"); glEnableVertexAttribArray(vPosition_loc); glVertexAttribPointer(vPosition_loc, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0)); GLuint vColor_loc = glGetAttribLocation(program, "vColor"); glEnableVertexAttribArray(vColor_loc); glVertexAttribPointer(vColor_loc, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(vertices.size()*sizeof(vec4))); GLuint vNormal_loc = glGetAttribLocation(program, "vNormal"); glEnableVertexAttribArray(vNormal_loc); glVertexAttribPointer(vNormal_loc, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(normals.size()*sizeof(vec4))); glUniform4fv( glGetUniformLocation(program, "MaterialAmbient"), 1, material_ambient); glUniform4fv( glGetUniformLocation(program, "MaterialDiffuse"), 1, material_diffuse); glUniform4fv( glGetUniformLocation(program, "MaterialSpecular"), 1, material_specular); // Light0 glUniform4fv( glGetUniformLocation(program, "Light0Position"), 1, light0_position); glUniform4fv( glGetUniformLocation(program, "Light0Ambient"), 1, light0_ambient); glUniform4fv( glGetUniformLocation(program, "Light0Diffuse"), 1, light0_diffuse); glUniform4fv( glGetUniformLocation(program, "Light0Specular"), 1, light0_specular); // Light1 glUniform4fv( glGetUniformLocation(program, "Light1Position"), 1, light1_position); glUniform4fv( glGetUniformLocation(program, "Light1Ambient"), 1, light1_ambient); glUniform4fv( glGetUniformLocation(program, "Light1Diffuse"), 1, light1_diffuse); glUniform4fv( glGetUniformLocation(program, "Light1Specular"), 1, light1_specular); glUniform1f( glGetUniformLocation(program, "Shininess"), material_shininess ); // Retrieve transformation uniform variable locations ModelView_loc = glGetUniformLocation( program, "ModelView" ); Projection_loc = glGetUniformLocation( program, "Projection" ); glEnable( GL_DEPTH_TEST ); glShadeModel(GL_FLAT); glClearColor( 0.75, 0.75, 0.75, 1.0 ); } void adjust_light1( void ) { mat4 light1_transform(1.0); vec4 centroid((bounding_box[BOUNDING_BOX_INDEX_LEFT] + bounding_box[BOUNDING_BOX_INDEX_RIGHT]) / 2, (bounding_box[BOUNDING_BOX_INDEX_BOTTOM] + bounding_box[BOUNDING_BOX_INDEX_TOP]) / 2, (bounding_box[BOUNDING_BOX_INDEX_NEAR] + bounding_box[BOUNDING_BOX_INDEX_FAR]) / 2); light1_transform = Translate(-centroid) * light1_transform; light1_transform = Translate(0.0,0.0,light1_radius) * light1_transform; light1_transform = RotateX(light1_phi) * light1_transform; light1_transform = RotateY(light1_theta) * light1_transform; light1_transform = Translate(centroid) * light1_transform; light1_position = light1_transform * light1_position; } vec4 get_eye( void ) { vec4 eye(0.0, 0.0, 1.0, 1.0); mat4 eye_transform(1.0); vec4 centroid((bounding_box[BOUNDING_BOX_INDEX_LEFT] + bounding_box[BOUNDING_BOX_INDEX_RIGHT]) / 2, (bounding_box[BOUNDING_BOX_INDEX_BOTTOM] + bounding_box[BOUNDING_BOX_INDEX_TOP]) / 2, (bounding_box[BOUNDING_BOX_INDEX_NEAR] + bounding_box[BOUNDING_BOX_INDEX_FAR]) / 2); eye_transform = Translate(-centroid) * eye_transform; eye_transform = Translate(0.0,0.0,eye_radius) * eye_transform; eye_transform = RotateX(eye_phi) * eye_transform; eye_transform = RotateY(eye_theta) * eye_transform; eye_transform = Translate(centroid) * eye_transform; return eye_transform * eye; } vec4 get_eye_at( void ) { return vec4((bounding_box[BOUNDING_BOX_INDEX_LEFT] + bounding_box[BOUNDING_BOX_INDEX_RIGHT]) / 2, (bounding_box[BOUNDING_BOX_INDEX_BOTTOM] + bounding_box[BOUNDING_BOX_INDEX_TOP]) / 2, (bounding_box[BOUNDING_BOX_INDEX_NEAR] + bounding_box[BOUNDING_BOX_INDEX_FAR]) / 2, 1.0); } vec4 get_up( vec4 eye ) { if (PARALLEL_PROJECTION == current_projection) { return vec4(eye.x, 1.0, eye.z, 1.0); } else { return vec4(eye.x, -1.0, eye.z, 1.0); } } void display( void ) { glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // LookAt(eye, at, up) vec4 eye = get_eye(); vec4 eye_at = get_eye_at(); vec4 eye_up = get_up(eye); mat4 model_view = LookAt(eye, eye_at, eye_up); mat4 projection; if (PARALLEL_PROJECTION == current_projection) { //Ortho(left, right, bottom, top, near, far); projection = Ortho(bounding_box[BOUNDING_BOX_INDEX_LEFT] - bounding_box[BOUNDING_BOX_INDEX_RIGHT], bounding_box[BOUNDING_BOX_INDEX_RIGHT], bounding_box[BOUNDING_BOX_INDEX_BOTTOM] - bounding_box[BOUNDING_BOX_INDEX_TOP], bounding_box[BOUNDING_BOX_INDEX_TOP], bounding_box[BOUNDING_BOX_INDEX_NEAR] - bounding_box[BOUNDING_BOX_INDEX_FAR], bounding_box[BOUNDING_BOX_INDEX_FAR]); } else { projection = Frustum(bounding_box[BOUNDING_BOX_INDEX_LEFT] - bounding_box[BOUNDING_BOX_INDEX_RIGHT], bounding_box[BOUNDING_BOX_INDEX_RIGHT], bounding_box[BOUNDING_BOX_INDEX_BOTTOM] - bounding_box[BOUNDING_BOX_INDEX_TOP], bounding_box[BOUNDING_BOX_INDEX_TOP], bounding_box[BOUNDING_BOX_INDEX_NEAR] - bounding_box[BOUNDING_BOX_INDEX_FAR], bounding_box[BOUNDING_BOX_INDEX_FAR]); } glUniformMatrix4fv(ModelView_loc, 1, GL_TRUE, model_view); glUniformMatrix4fv(Projection_loc, 1, GL_TRUE, projection); glDrawArrays( GL_TRIANGLES, 0, vertices.size() ); glFlush(); glutSwapBuffers(); } void myidle ( void ) { t += dt; eye_theta += dt; if (eye_theta > MAX_EYE_THETA) { eye_theta = MIN_EYE_THETA; } glutPostRedisplay(); } void keyboard( unsigned char key, int x, int y ) { switch (key) { case KEY_EYE_UP: eye_phi += EYE_DELTA; break; case KEY_EYE_DOWN: eye_phi -= EYE_DELTA; break; case KEY_EYE_CLOSE: eye_radius += EYE_DELTA; break; case KEY_EYE_FAR: eye_radius -= EYE_DELTA; break; case KEY_DELTAUP: dt += DELTA_DELTA; break; case KEY_DELTADOWN: dt -= DELTA_DELTA; break; case KEY_STOP: glutIdleFunc(NULL); break; case KEY_START: glutIdleFunc(myidle); break; case KEY_LIGHT_UP: light1_phi += light_dt; break; case KEY_LIGHT_DOWN: light1_phi -= light_dt; break; case KEY_LIGHT_CLOSE: light1_radius += light_dt; break; case KEY_LIGHT_FAR: light1_radius -= light_dt; break; case KEY_LIGHT_LEFT: light1_theta += light_dt; break; case KEY_LIGHT_RIGHT: light1_theta -= light_dt; break; } if (debug) { printf("keyboard '%c' - light1_phi=%f, light1_radius=%f, light1_theta=%f\n", key, light1_phi, light1_radius, light1_theta); } if (eye_phi < MIN_EYE_PHI) { eye_phi = MIN_EYE_PHI; } if (eye_phi > MAX_EYE_PHI) { eye_phi = MAX_EYE_PHI; } if (light1_theta < MIN_LIGHT_THETA) { light1_theta = MAX_LIGHT_THETA; } if (light1_theta > MAX_LIGHT_THETA) { light1_theta = MIN_LIGHT_THETA; } if (light1_phi < MIN_LIGHT_PHI) { light1_phi = MIN_LIGHT_PHI; } if (light1_phi > MAX_LIGHT_PHI) { light1_phi = MAX_LIGHT_PHI; } adjust_light1(); init(); glutPostWindowRedisplay(mainWindow); } void processMenuEvents(int menuChoice) { switch (menuChoice) { case PARALLEL_PROJECTION: current_projection = PARALLEL_PROJECTION; break; case PERSPECTIVE_PROJECTION: current_projection = PERSPECTIVE_PROJECTION; break; case PHONG_SHADING: current_shading = PHONG_SHADING; init(); break; case GOURAUD_SHADING: current_shading = GOURAUD_SHADING; init(); break; case BRASS_MATERIAL: material_ambient = BRASS_AMBIENT; material_diffuse = BRASS_DIFFUSE; material_specular = BRASS_SPECULAR; material_shininess = BRASS_SHININESS; init(); break; case RED_PLASTIC_MATERIAL: material_ambient = RED_PLASTIC_AMBIENT; material_diffuse = RED_PLASTIC_DIFFUSE; material_specular = RED_PLASTIC_SPECULAR; material_shininess = RED_PLASTIC_SHININESS; init(); break; case GREEN_RUBBER_MATERIAL: material_ambient = GREEN_RUBBER_AMBIENT; material_diffuse = GREEN_RUBBER_DIFFUSE; material_specular = GREEN_RUBBER_SPECULAR; material_shininess = GREEN_RUBBER_SHININESS; init(); break; } } void setupMenu ( void ) { glutCreateMenu(processMenuEvents); glutAddMenuEntry("Parallel projection", PARALLEL_PROJECTION); glutAddMenuEntry("Perspective projection", PERSPECTIVE_PROJECTION); glutAddMenuEntry("Phong shading", PHONG_SHADING); glutAddMenuEntry("Gouraud shading", GOURAUD_SHADING); glutAddMenuEntry("Brass material", BRASS_MATERIAL); glutAddMenuEntry("Red Plastic material", RED_PLASTIC_MATERIAL); glutAddMenuEntry("Green Rubber material", GREEN_RUBBER_MATERIAL); glutAttachMenu(GLUT_RIGHT_BUTTON); } void printHelp ( void ) { printf("%s\n", TITLE); printf("Use right-click menu to change perspective.\n"); printf("Keyboard options:\n"); printf("%c - move eye up\n", KEY_EYE_UP); printf("%c - move eye down\n" , KEY_EYE_DOWN); printf("%c - move eye closer\n", KEY_EYE_CLOSE); printf("%c - move eye farther\n", KEY_EYE_FAR); printf("%c - spin eye faster\n", KEY_DELTAUP); printf("%c - spin eye slower\n", KEY_DELTADOWN); printf("%c - stop movement\n", KEY_STOP); printf("%c - start movement\n", KEY_START); printf("%c - move light up\n", KEY_LIGHT_UP); printf("%c - move light down\n", KEY_LIGHT_DOWN); printf("%c - move light closer\n", KEY_LIGHT_CLOSE); printf("%c - move light farther\n", KEY_LIGHT_FAR); printf("%c - move light right\n", KEY_LIGHT_LEFT); printf("%c - move light left\n", KEY_LIGHT_RIGHT); } int main( int argc, char **argv ) { if (argc > 1) { smf_path = std::string(argv[1]); } if (debug) { printf("[DEBUG] Filepath: %s\n", smf_path.c_str()); } printHelp(); glutInit( &argc, argv ); glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH ); glutInitWindowPosition(100,100); glutInitWindowSize( w, h ); mainWindow = glutCreateWindow( (std::string(TITLE) + " " + smf_path).c_str() ); glewExperimental=GL_TRUE; glewInit(); read_smf(); init(); setupMenu(); glutDisplayFunc ( display ); glutKeyboardFunc( keyboard ); glutIdleFunc ( myidle ); glEnable(GL_DEPTH_TEST); glutMainLoop(); return 0; }
28.911302
123
0.672473
[ "object", "vector" ]
e9f7851c5a0e123b4664bce10b37a1c870bef314
685
cpp
C++
Online Judges/SPOJ/TOPOSORT/3500621_AC_80ms_7270kB.cpp
moni-roy/COPC
f5918304815413c18574ef4af2e23a604bd9f704
[ "MIT" ]
4
2017-02-20T17:41:14.000Z
2019-07-15T14:15:34.000Z
Online Judges/SPOJ/TOPOSORT/3500621_AC_80ms_7270kB.cpp
moni-roy/COPC
f5918304815413c18574ef4af2e23a604bd9f704
[ "MIT" ]
null
null
null
Online Judges/SPOJ/TOPOSORT/3500621_AC_80ms_7270kB.cpp
moni-roy/COPC
f5918304815413c18574ef4af2e23a604bd9f704
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int n,p,ok[1000001],x,y; vector<int>as,sv[11010]; int main() { //cin>>n>>p; scanf("%d%d",&n,&p); for(int i=0;i<p;i++) { //cin>>x>>y; scanf("%d%d",&x,&y); sv[x].push_back(y); ok[y]++; } priority_queue<int>q; for(int i=1;i<=n;i++) { if(ok[i]==0) q.push(-1*i); } while(!q.empty()) { int u=-1*q.top(); q.pop(); as.push_back(u); for(int i=0;i<(int)sv[u].size();i++) { int v=sv[u][i]; ok[v]--; if(ok[v]==0) q.push(-1*v); } } if((int)as.size()!=n) puts("Sandro fails."); else { for(int i=0;i<(int)as.size();i++) { if(i==0) printf("%d",as[i]); else printf(" %d",as[i]); } puts(""); } }
15.568182
45
0.486131
[ "vector" ]
e9fa594ceb5b4a46201ebcfac63a907e6989e98a
14,442
cpp
C++
example/ch9_backgroundAVG.cpp
gdijaejung/Learning-OpenCV
20942678b467e4ce6053ed2f9c59f852affa4a24
[ "MIT" ]
null
null
null
example/ch9_backgroundAVG.cpp
gdijaejung/Learning-OpenCV
20942678b467e4ce6053ed2f9c59f852affa4a24
[ "MIT" ]
null
null
null
example/ch9_backgroundAVG.cpp
gdijaejung/Learning-OpenCV
20942678b467e4ce6053ed2f9c59f852affa4a24
[ "MIT" ]
null
null
null
// Background average sample code done with averages and done with codebooks // // Files are ch9_backgroundAVG.cpp // ch9_AvgBackground.cpp and .h // cv_yuv_codebook.cpp and .h // // As of the writing of this book, the cv_yuv_codebook files are going to be a permanent part of // OpenCV (with improved interface). But I wrote this before that so to speak. This code can then // be cleaned up and would be be good to do with sliders. // As it is, you can compare the AVG method of background subtraction with the codebook method. // // NOTE: To get the keyboard to work, you *have* to have one of the video windows be active // and NOT the consule window. // // Gary Bradski Oct 3, 2008. // /* *************** License:************************** Oct. 3, 2008 Right to use this code in any way you want without warrenty, support or any guarentee of it working. BOOK: It would be nice if you cited it: Learning OpenCV: Computer Vision with the OpenCV Library by Gary Bradski and Adrian Kaehler Published by O'Reilly Media, October 3, 2008 AVAILABLE AT: http://www.amazon.com/Learning-OpenCV-Computer-Vision-Library/dp/0596516134 Or: http://oreilly.com/catalog/9780596516130/ ISBN-10: 0596516134 or: ISBN-13: 978-0596516130 OTHER OPENCV SITES: * The source code is on sourceforge at: http://sourceforge.net/projects/opencvlibrary/ * The OpenCV wiki page (As of Oct 1, 2008 this is down for changing over servers, but should come back): http://opencvlibrary.sourceforge.net/ * An active user group is at: http://tech.groups.yahoo.com/group/OpenCV/ * The minutes of weekly OpenCV development meetings are at: http://pr.willowgarage.com/wiki/OpenCV ************************************************** */ #include "cv.h" #include "highgui.h" #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include "ch9_AvgBackground.h" #include "cv_yuv_codebook.h" //VARIABLES for CODEBOOK METHOD: codeBook *cB; //This will be our linear model of the image, a vector //of lengh = height*width int maxMod[CHANNELS]; //Add these (possibly negative) number onto max // level when code_element determining if new pixel is foreground int minMod[CHANNELS]; //Subract these (possible negative) number from min //level code_element when determining if pixel is foreground unsigned cbBounds[CHANNELS]; //Code Book bounds for learning bool ch[CHANNELS]; //This sets what channels should be adjusted for background bounds int nChannels = CHANNELS; int imageLen = 0; uchar *pColor; //YUV pointer void help() { printf("\nLearn background and find foreground using simple average and average difference learning method:\n" "\nUSAGE:\n ch9_background startFrameCollection# endFrameCollection# [movie filename, else from camera]\n" "If from AVI, then optionally add HighAvg, LowAvg, HighCB_Y LowCB_Y HighCB_U LowCB_U HighCB_V LowCB_V\n\n" "***Keep the focus on the video windows, NOT the consol***\n\n" "INTERACTIVE PARAMETERS:\n" "\tESC,q,Q - quit the program\n" "\th - print this help\n" "\tp - pause toggle\n" "\ts - single step\n" "\tr - run mode (single step off)\n" "=== AVG PARAMS ===\n" "\t- - bump high threshold UP by 0.25\n" "\t= - bump high threshold DOWN by 0.25\n" "\t[ - bump low threshold UP by 0.25\n" "\t] - bump low threshold DOWN by 0.25\n" "=== CODEBOOK PARAMS ===\n" "\ty,u,v- only adjust channel 0(y) or 1(u) or 2(v) respectively\n" "\ta - adjust all 3 channels at once\n" "\tb - adjust both 2 and 3 at once\n" "\ti,o - bump upper threshold up,down by 1\n" "\tk,l - bump lower threshold up,down by 1\n" ); } // //USAGE: ch9_background startFrameCollection# endFrameCollection# [movie filename, else from camera] //If from AVI, then optionally add HighAvg, LowAvg, HighCB_Y LowCB_Y HighCB_U LowCB_U HighCB_V LowCB_V // int main(int argc, char** argv) { IplImage* rawImage = 0, *yuvImage = 0; //yuvImage is for codebook method IplImage *ImaskAVG = 0,*ImaskAVGCC = 0; IplImage *ImaskCodeBook = 0,*ImaskCodeBookCC = 0; CvCapture* capture = 0; int startcapture = 1; int endcapture = 30; int c,n; maxMod[0] = 3; //Set color thresholds to default values minMod[0] = 10; maxMod[1] = 1; minMod[1] = 1; maxMod[2] = 1; minMod[2] = 1; float scalehigh = HIGH_SCALE_NUM; float scalelow = LOW_SCALE_NUM; if(argc < 3) { printf("ERROR: Too few parameters\n"); help(); }else{ if(argc == 3){ printf("Capture from Camera\n"); capture = cvCaptureFromCAM( 0 ); } else { printf("Capture from file %s\n",argv[3]); // capture = cvCaptureFromFile( argv[3] ); capture = cvCreateFileCapture( argv[3] ); if(!capture) { printf("Couldn't open %s\n",argv[3]); return -1;} } if(isdigit(argv[1][0])) { //Start from of background capture startcapture = atoi(argv[1]); printf("startcapture = %d\n",startcapture); } if(isdigit(argv[2][0])) { //End frame of background capture endcapture = atoi(argv[2]); printf("endcapture = %d\n"); } if(argc > 4){ //See if parameters are set from command line //FOR AVG MODEL if(argc >= 5){ if(isdigit(argv[4][0])){ scalehigh = (float)atoi(argv[4]); } } if(argc >= 6){ if(isdigit(argv[5][0])){ scalelow = (float)atoi(argv[5]); } } //FOR CODEBOOK MODEL, CHANNEL 0 if(argc >= 7){ if(isdigit(argv[6][0])){ maxMod[0] = atoi(argv[6]); } } if(argc >= 8){ if(isdigit(argv[7][0])){ minMod[0] = atoi(argv[7]); } } //Channel 1 if(argc >= 9){ if(isdigit(argv[8][0])){ maxMod[1] = atoi(argv[8]); } } if(argc >= 10){ if(isdigit(argv[9][0])){ minMod[1] = atoi(argv[9]); } } //Channel 2 if(argc >= 11){ if(isdigit(argv[10][0])){ maxMod[2] = atoi(argv[10]); } } if(argc >= 12){ if(isdigit(argv[11][0])){ minMod[2] = atoi(argv[11]); } } } } //MAIN PROCESSING LOOP: bool pause = false; bool singlestep = false; if( capture ) { cvNamedWindow( "Raw", 1 ); cvNamedWindow( "AVG_ConnectComp",1); cvNamedWindow( "ForegroundCodeBook",1); cvNamedWindow( "CodeBook_ConnectComp",1); cvNamedWindow( "ForegroundAVG",1); int i = -1; for(;;) { if(!pause){ // if( !cvGrabFrame( capture )) // break; // rawImage = cvRetrieveFrame( capture ); rawImage = cvQueryFrame( capture ); ++i;//count it // printf("%d\n",i); if(!rawImage) break; //REMOVE THIS FOR GENERAL OPERATION, JUST A CONVIENIENCE WHEN RUNNING WITH THE SMALL tree.avi file if(i == 56){ pause = 1; printf("\n\nVideo paused for your convienience at frame 50 to work with demo\n" "You may adjust parameters, single step or continue running\n\n"); help(); } } if(singlestep){ pause = true; } //First time: if(0 == i) { printf("\n . . . wait for it . . .\n"); //Just in case you wonder why the image is white at first //AVG METHOD ALLOCATION AllocateImages(rawImage); scaleHigh(scalehigh); scaleLow(scalelow); ImaskAVG = cvCreateImage( cvGetSize(rawImage), IPL_DEPTH_8U, 1 ); ImaskAVGCC = cvCreateImage( cvGetSize(rawImage), IPL_DEPTH_8U, 1 ); cvSet(ImaskAVG,cvScalar(255)); //CODEBOOK METHOD ALLOCATION: yuvImage = cvCloneImage(rawImage); ImaskCodeBook = cvCreateImage( cvGetSize(rawImage), IPL_DEPTH_8U, 1 ); ImaskCodeBookCC = cvCreateImage( cvGetSize(rawImage), IPL_DEPTH_8U, 1 ); cvSet(ImaskCodeBook,cvScalar(255)); imageLen = rawImage->width*rawImage->height; cB = new codeBook [imageLen]; for(int f = 0; f<imageLen; f++) { cB[f].numEntries = 0; } for(int nc=0; nc<nChannels;nc++) { cbBounds[nc] = 10; //Learning bounds factor } ch[0] = true; //Allow threshold setting simultaneously for all channels ch[1] = true; ch[2] = true; } //If we've got an rawImage and are good to go: if( rawImage ) { cvCvtColor( rawImage, yuvImage, CV_BGR2YCrCb );//YUV For codebook method //This is where we build our background model if( !pause && i >= startcapture && i < endcapture ){ //LEARNING THE AVERAGE AND AVG DIFF BACKGROUND accumulateBackground(rawImage); //LEARNING THE CODEBOOK BACKGROUND pColor = (uchar *)((yuvImage)->imageData); for(int c=0; c<imageLen; c++) { cvupdateCodeBook(pColor, cB[c], cbBounds, nChannels); pColor += 3; } } //When done, create the background model if(i == endcapture){ createModelsfromStats(); } //Find the foreground if any if(i >= endcapture) { //FIND FOREGROUND BY AVG METHOD: backgroundDiff(rawImage,ImaskAVG); cvCopy(ImaskAVG,ImaskAVGCC); cvconnectedComponents(ImaskAVGCC); //FIND FOREGROUND BY CODEBOOK METHOD uchar maskPixelCodeBook; pColor = (uchar *)((yuvImage)->imageData); //3 channel yuv image uchar *pMask = (uchar *)((ImaskCodeBook)->imageData); //1 channel image for(int c=0; c<imageLen; c++) { maskPixelCodeBook = cvbackgroundDiff(pColor, cB[c], nChannels, minMod, maxMod); *pMask++ = maskPixelCodeBook; pColor += 3; } //This part just to visualize bounding boxes and centers if desired cvCopy(ImaskCodeBook,ImaskCodeBookCC); cvconnectedComponents(ImaskCodeBookCC); } //Display cvShowImage( "Raw", rawImage ); cvShowImage( "AVG_ConnectComp",ImaskAVGCC); cvShowImage( "ForegroundAVG",ImaskAVG); cvShowImage( "ForegroundCodeBook",ImaskCodeBook); cvShowImage( "CodeBook_ConnectComp",ImaskCodeBookCC); //USER INPUT: c = cvWaitKey(10)&0xFF; //End processing on ESC, q or Q if(c == 27 || c == 'q' | c == 'Q') break; //Else check for user input switch(c) { case 'h': help(); break; case 'p': pause ^= 1; break; case 's': singlestep = 1; pause = false; break; case 'r': pause = false; singlestep = false; break; //AVG BACKROUND PARAMS case '-': if(i > endcapture){ scalehigh += 0.25; printf("AVG scalehigh=%f\n",scalehigh); scaleHigh(scalehigh); } break; case '=': if(i > endcapture){ scalehigh -= 0.25; printf("AVG scalehigh=%f\n",scalehigh); scaleHigh(scalehigh); } break; case '[': if(i > endcapture){ scalelow += 0.25; printf("AVG scalelow=%f\n",scalelow); scaleLow(scalelow); } break; case ']': if(i > endcapture){ scalelow -= 0.25; printf("AVG scalelow=%f\n",scalelow); scaleLow(scalelow); } break; //CODEBOOK PARAMS case 'y': case '0': ch[0] = 1; ch[1] = 0; ch[2] = 0; printf("CodeBook YUV Channels active: "); for(n=0; n<nChannels; n++) printf("%d, ",ch[n]); printf("\n"); break; case 'u': case '1': ch[0] = 0; ch[1] = 1; ch[2] = 0; printf("CodeBook YUV Channels active: "); for(n=0; n<nChannels; n++) printf("%d, ",ch[n]); printf("\n"); break; case 'v': case '2': ch[0] = 0; ch[1] = 0; ch[2] = 1; printf("CodeBook YUV Channels active: "); for(n=0; n<nChannels; n++) printf("%d, ",ch[n]); printf("\n"); break; case 'a': //All case '3': ch[0] = 1; ch[1] = 1; ch[2] = 1; printf("CodeBook YUV Channels active: "); for(n=0; n<nChannels; n++) printf("%d, ",ch[n]); printf("\n"); break; case 'b': //both u and v together ch[0] = 0; ch[1] = 1; ch[2] = 1; printf("CodeBook YUV Channels active: "); for(n=0; n<nChannels; n++) printf("%d, ",ch[n]); printf("\n"); break; case 'i': //modify max classification bounds (max bound goes higher) for(n=0; n<nChannels; n++){ if(ch[n]) maxMod[n] += 1; printf("%.4d,",maxMod[n]); } printf(" CodeBook High Side\n"); break; case 'o': //modify max classification bounds (max bound goes lower) for(n=0; n<nChannels; n++){ if(ch[n]) maxMod[n] -= 1; printf("%.4d,",maxMod[n]); } printf(" CodeBook High Side\n"); break; case 'k': //modify min classification bounds (min bound goes lower) for(n=0; n<nChannels; n++){ if(ch[n]) minMod[n] += 1; printf("%.4d,",minMod[n]); } printf(" CodeBook Low Side\n"); break; case 'l': //modify min classification bounds (min bound goes higher) for(n=0; n<nChannels; n++){ if(ch[n]) minMod[n] -= 1; printf("%.4d,",minMod[n]); } printf(" CodeBook Low Side\n"); break; } } } cvReleaseCapture( &capture ); cvDestroyWindow( "Raw" ); cvDestroyWindow( "ForegroundAVG" ); cvDestroyWindow( "AVG_ConnectComp"); cvDestroyWindow( "ForegroundCodeBook"); cvDestroyWindow( "CodeBook_ConnectComp"); DeallocateImages(); if(yuvImage) cvReleaseImage(&yuvImage); if(ImaskAVG) cvReleaseImage(&ImaskAVG); if(ImaskAVGCC) cvReleaseImage(&ImaskAVGCC); if(ImaskCodeBook) cvReleaseImage(&ImaskCodeBook); if(ImaskCodeBookCC) cvReleaseImage(&ImaskCodeBookCC); delete [] cB; } else{ printf("\n\nDarn, Something wrong with the parameters\n\n"); help(); } return 0; }
32.093333
111
0.564949
[ "vector", "model" ]
e9fc5f9ea1facf179262a84d31a286c3601b285c
5,816
cpp
C++
librtt/Display/Rtt_ContainerObject.cpp
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
1,968
2018-12-30T21:14:22.000Z
2022-03-31T23:48:16.000Z
librtt/Display/Rtt_ContainerObject.cpp
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
303
2019-01-02T19:36:43.000Z
2022-03-31T23:52:45.000Z
librtt/Display/Rtt_ContainerObject.cpp
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
254
2019-01-02T19:05:52.000Z
2022-03-30T06:32:28.000Z
////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: support@coronalabs.com // ////////////////////////////////////////////////////////////////////////////// #include "Core/Rtt_Build.h" #include "Display/Rtt_ContainerObject.h" #include "Display/Rtt_BitmapMask.h" #include "Display/Rtt_BitmapPaint.h" #include "Display/Rtt_Display.h" #include "Display/Rtt_TextureFactory.h" #include "Renderer/Rtt_Renderer.h" #include "Renderer/Rtt_Uniform.h" #include "Rtt_LuaProxyVTable.h" #include "Rtt_Resource.h" #include "Rtt_Runtime.h" // ---------------------------------------------------------------------------- namespace Rtt { // ---------------------------------------------------------------------------- ContainerObject::ContainerObject( Rtt_Allocator* pAllocator, StageObject *canvas, Real width, Real height ) : Super( pAllocator, canvas ), fContainerMask( NULL ), fContainerMaskUniform( NULL ), fWidth( width ), fHeight( height ) { Invalidate( kContainerFlag ); SetProperty( kIsAnchorChildren, true ); SetObjectDesc( "ContainerObject" ); // for introspection } ContainerObject::~ContainerObject() { QueueRelease( fContainerMaskUniform ); Rtt_DELETE( fContainerMask ); } void ContainerObject::Initialize( Display& display ) { if ( Rtt_VERIFY( NULL == fContainerMask ) ) { // PlatformBitmap *maskBitmap = display.GetTextureFactory().GetContainerMaskBitmap(); // BitmapPaint *paint = // BitmapPaint::NewBitmap( display.GetTextureFactory(), maskBitmap, true ); SharedPtr< TextureResource > resource = display.GetTextureFactory().GetContainerMask(); BitmapPaint *paint = Rtt_NEW( display.GetAllocator(), BitmapPaint( resource ) ); fContainerMask = Rtt_NEW( library.GetAllocator(), BitmapMask( paint, fWidth, fHeight ) ); fContainerMaskUniform = Rtt_NEW( Allocator(), Uniform( Allocator(), Uniform::kMat3 ) ); } } bool ContainerObject::UpdateTransform( const Matrix& parentToDstSpace ) { bool shouldUpdate = Super::UpdateTransform( parentToDstSpace ); if ( shouldUpdate || ! IsValid( kContainerFlag ) ) { Rtt_ASSERT( fContainerMaskUniform ); Matrix dstToMask; // Initialize container mask transform, so that the resulting // container bounds are rendered with the correct anchoring/registration. Transform& maskTransform = fContainerMask->GetTransform(); maskTransform.SetIdentity(); maskTransform.Invalidate(); // If the transform does not include the offset, we need to include it here if ( ShouldOffsetClip() ) { Vertex2 offset = GetAnchorOffset(); maskTransform.Translate( offset.x, offset.y ); } // First, initialize using standard mask that maps UV to (0,0) (1,1) CalculateMaskMatrix( dstToMask, GetSrcToDstMatrix(), * fContainerMask ); // Then, append transforms which map UV to (0.25,0.25) (0.75,0.75) // This subregion is the portion of the mask that's white. // Outside of that region, mask is black (border). // NOTE: Recall that mask bits are from NewBufferBitmap() dstToMask.Scale( Rtt_REAL_HALF, Rtt_REAL_HALF ); dstToMask.Translate( Rtt_REAL_FOURTH, Rtt_REAL_FOURTH ); dstToMask.ToGLMatrix3x3( reinterpret_cast< Real * >( fContainerMaskUniform->GetData() ) ); fContainerMaskUniform->Invalidate(); } return shouldUpdate; } void ContainerObject::Draw( Renderer& renderer ) const { if ( ShouldDraw() && ( fWidth > Rtt_REAL_0 && fHeight > Rtt_REAL_0 ) ) { Rtt_ASSERT( ! IsDirty() ); Rtt_ASSERT( ! IsOffScreen() ); const BitmapMask *mask = fContainerMask; if ( mask ) { Texture *texture = const_cast< BitmapPaint * >( mask->GetPaint() )->GetTexture(); Uniform *uniform = const_cast< Uniform * >( fContainerMaskUniform ); renderer.PushMask( texture, uniform ); } Super::Draw( renderer ); if ( mask ) { renderer.PopMask(); } } } void ContainerObject::GetSelfBounds( Rect& rect ) const { GetSelfBoundsForAnchor( rect ); // The self bounds is based on the clipping bounds, // so only offset here if the transform does not include the offset // since we need to include the offset somewhere. if ( ShouldOffsetClip() ) { Real dx = -( fWidth * GetInternalAnchorX() ); Real dy = -( fHeight * GetInternalAnchorY() ); rect.Translate( dx, dy ); } } // NOTE: This is what is used to calculate the anchor offset lengths void ContainerObject::GetSelfBoundsForAnchor( Rect& rect ) const { rect.Initialize( Rtt_RealDiv2( fWidth ), Rtt_RealDiv2( fHeight ) ); } bool ContainerObject::HitTest( Real contentX, Real contentY ) { BuildStageBounds(); return StageBounds().HitTest( contentX, contentY ); } bool ContainerObject::CanCull() const { return true; } void ContainerObject::SetSelfBounds( Real width, Real height ) { if ( ! Rtt_RealEqual( width, fWidth ) || ! Rtt_RealEqual( height, fHeight ) ) { if ( !( width < Rtt_REAL_0 ) ) // (width >= 0) { fWidth = width; } if ( !( height < Rtt_REAL_0 ) ) // (height >= 0) { fHeight = height; } fContainerMask->SetSelfBounds( width, height ); // TODO: Also kGeometryFlag? Invalidate( kContainerFlag | kTransformFlag ); // TODO: // * For pure groups: If children invalidate stagebounds and anchorChildren is true, then invalidate transform const_cast< Transform& >( GetTransform() ).Invalidate(); } } bool ContainerObject::ShouldOffsetClip() const { // Only offset here if we do not offset the transform return ( ! ShouldOffsetWithAnchor() && ! IsAnchorOffsetZero() ); } // ---------------------------------------------------------------------------- } // namespace Rtt // ----------------------------------------------------------------------------
27.563981
112
0.65784
[ "transform" ]
180116dd344de4a6a0ae8e3aa71f72edd3ad45ae
11,063
cpp
C++
Applications/C3Edit/C3Edit.cpp
keelanstuart/Celerity
57ad7ccd2fbb661868680df43cae2d76ec80104b
[ "MIT" ]
1
2022-02-11T03:06:33.000Z
2022-02-11T03:06:33.000Z
Applications/C3Edit/C3Edit.cpp
keelanstuart/Celerity
57ad7ccd2fbb661868680df43cae2d76ec80104b
[ "MIT" ]
null
null
null
Applications/C3Edit/C3Edit.cpp
keelanstuart/Celerity
57ad7ccd2fbb661868680df43cae2d76ec80104b
[ "MIT" ]
null
null
null
// C3Edit.cpp : Defines the class behaviors for the application. // #include "pch.h" #include "framework.h" #include "afxwinappex.h" #include "afxdialogex.h" #include "C3Edit.h" #include "C3EditFrame.h" #include "C3EditDoc.h" #include "C3EditView.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // C3EditApp BEGIN_MESSAGE_MAP(C3EditApp, CWinAppEx) ON_COMMAND(ID_APP_ABOUT, &C3EditApp::OnAppAbout) ON_COMMAND(ID_FILE_NEW_FRAME, &C3EditApp::OnFileNewFrame) ON_COMMAND(ID_FILE_NEW, &C3EditApp::OnFileNew) // Standard file based document commands ON_COMMAND(ID_FILE_OPEN, &CWinAppEx::OnFileOpen) END_MESSAGE_MAP() bool CreateDirectories(const TCHAR *dir) { if (!dir || !*dir) return false; if (PathFileExists(dir)) return true; if (PathIsRoot(dir)) return false; bool ret = true; TCHAR _dir[MAX_PATH], *d = _dir; _tcscpy_s(_dir, dir); while (d && *(d++)) { if (*d == _T('/')) *d = _T('\\'); } PathRemoveFileSpec(_dir); // it's a network path and this is the network device... don't try to create it and don't try to go any further if (!_tcscmp(_dir, _T("\\\\")) || !_tcscmp(_dir, _T("//"))) return true; ret &= CreateDirectories(_dir); ret &= (CreateDirectory(dir, NULL) ? true : false); return ret; } // C3EditApp construction C3EditApp::C3EditApp() noexcept { m_C3 = nullptr; m_Config = nullptr; SetAppID(_T("Celerity.C3Edit")); } // The one and only C3EditApp object C3EditApp theApp; // C3EditApp initialization BOOL C3EditApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinAppEx::InitInstance(); m_C3 = c3::System::Create(0); if (!m_C3) return FALSE; PWSTR appdata = nullptr; if (SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_CREATE, NULL, &appdata) == S_OK) { TCHAR *appdatat; CONVERT_WCS2TCS(appdata, appdatat); CoTaskMemFree(appdata); m_AppDataRoot = appdatat; std::replace(m_AppDataRoot.begin(), m_AppDataRoot.end(), _T('\\'), _T('/')); std::transform(m_AppDataRoot.begin(), m_AppDataRoot.end(), m_AppDataRoot.begin(), tolower); m_AppDataRoot += _T("/Celerity/C3Edit/"); CreateDirectories(m_AppDataRoot.c_str()); } tstring cfgpath = m_AppDataRoot; cfgpath += _T("C3Edit.config"); m_Config = m_C3->CreateConfiguration(cfgpath.c_str()); theApp.m_C3->GetLog()->Print(_T("Mapping file types... ")); c3::FileMapper *pfm = m_C3->GetFileMapper(); tstring resroot; resroot = _T("assets/textures"); pfm->AddMapping(_T("tga"), resroot.c_str()); pfm->AddMapping(_T("png"), resroot.c_str()); pfm->AddMapping(_T("jpg"), resroot.c_str()); resroot.insert(0, m_AppDataRoot.c_str()); CreateDirectories(resroot.c_str()); pfm->AddMapping(_T("tga"), resroot.c_str()); pfm->AddMapping(_T("png"), resroot.c_str()); pfm->AddMapping(_T("jpg"), resroot.c_str()); resroot = _T("assets/models"); pfm->AddMapping(_T("fbx"), resroot.c_str()); pfm->AddMapping(_T("gltf"), resroot.c_str()); pfm->AddMapping(_T("obj"), resroot.c_str()); pfm->AddMapping(_T("3ds"), resroot.c_str()); resroot.insert(0, m_AppDataRoot.c_str()); CreateDirectories(resroot.c_str()); pfm->AddMapping(_T("fbx"), resroot.c_str()); pfm->AddMapping(_T("gltf"), resroot.c_str()); pfm->AddMapping(_T("obj"), resroot.c_str()); pfm->AddMapping(_T("3ds"), resroot.c_str()); resroot = _T("assets/shaders"); pfm->AddMapping(_T("vsh"), resroot.c_str()); pfm->AddMapping(_T("fsh"), resroot.c_str()); pfm->AddMapping(_T("gsh"), resroot.c_str()); resroot.insert(0, m_AppDataRoot.c_str()); CreateDirectories(resroot.c_str()); pfm->AddMapping(_T("vsh"), resroot.c_str()); pfm->AddMapping(_T("fsh"), resroot.c_str()); pfm->AddMapping(_T("gsh"), resroot.c_str()); theApp.m_C3->GetLog()->Print(_T("done\n")); c3::Factory *pf = m_C3->GetFactory(); if (!pf) return FALSE; tstring protopaths = m_Config->GetString(_T("resources.prototypes.paths"), _T("./;./Resources;./Resources/Prototypes")); protopaths += _T(";"); protopaths += m_AppDataRoot; pfm->SetMappingsFromDelimitedStrings( m_Config->GetString(_T("resources.prototypes.extensions"), _T("c3proto")), protopaths.c_str(), _T(';')); for (size_t q = 0; q < pfm->GetNumPaths(_T("c3proto")); q++) { tstring ppath = pfm->GetPath(_T("c3proto"), q); ppath.append(_T("*.c3proto")); WIN32_FIND_DATA fd; HANDLE hff = FindFirstFile(ppath.c_str(), &fd); if (hff != INVALID_HANDLE_VALUE) { do { FILE *protof; if (!_tfopen_s(&protof, fd.cFileName, _T("r, css=UTF-8"))) { int f = _fileno(protof); #pragma warning(disable: 4312) HANDLE h = (f > 0) ? (HANDLE)f : INVALID_HANDLE_VALUE; #pragma warning(default: 4312) genio::IInputStream *pis = genio::IInputStream::Create(h); pf->LoadPrototypes(pis); pis->Release(); } } while (FindNextFile(hff, &fd)); FindClose(hff); } } c3::PluginManager *ppm = m_C3->GetPluginManager(); if (!ppm) return FALSE; tstring plugpath = m_AppDataRoot; plugpath += _T("plugins"); CreateDirectories(plugpath.c_str()); ppm->DiscoverPlugins(plugpath.c_str()); // scan in app data ppm->DiscoverPlugins(); // scan locally EnableTaskbarInteraction(FALSE); // AfxInitRichEdit2() is required to use RichEdit control // AfxInitRichEdit2(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Celerity\\C3Edit")); LoadStdProfileSettings(4); // Load standard INI file options (including MRU) InitContextMenuManager(); InitShellManager(); InitKeyboardManager(); InitTooltipManager(); CMFCToolTipInfo ttParams; ttParams.m_bVislManagerTheme = TRUE; theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL, RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams); // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views CMultiDocTemplate* pDocTemplate; pDocTemplate = new CMultiDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(C3EditDoc), RUNTIME_CLASS(C3EditFrame), // main SDI frame window RUNTIME_CLASS(C3EditView)); if (!pDocTemplate) return FALSE; m_pDocTemplate = pDocTemplate; AddDocTemplate(pDocTemplate); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Enable DDE Execute open EnableShellOpen(); RegisterShellFileTypes(TRUE); // Dispatch commands specified on the command line. Will return FALSE if // app was launched with /RegServer, /Register, /Unregserver or /Unregister. if (!ProcessShellCommand(cmdInfo)) return FALSE; // The one and only window has been initialized, so show and update it m_pMainWnd->ShowWindow(SW_SHOW); m_C3->SetOwner(m_pMainWnd->GetSafeHwnd()); m_pMainWnd->UpdateWindow(); // call DragAcceptFiles only if there's a suffix // In an SDI app, this should occur after ProcessShellCommand // Enable drag/drop open m_pMainWnd->DragAcceptFiles(); return TRUE; } // C3EditApp message handlers // CAboutDlg dialog used for App About class CAboutDlg : public CDialogEx { public: CAboutDlg() noexcept; // Dialog Data #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() noexcept : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // App command to run the dialog void C3EditApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } // C3EditApp customization load/save methods void C3EditApp::PreLoadState() { BOOL bNameValid; CString strName; bNameValid = strName.LoadString(IDS_EDIT_MENU); ASSERT(bNameValid); GetContextMenuManager()->AddMenu(strName, IDR_POPUP_EDIT); bNameValid = strName.LoadString(IDS_EXPLORER); ASSERT(bNameValid); GetContextMenuManager()->AddMenu(strName, IDR_POPUP_EXPLORER); } void C3EditApp::LoadCustomState() { } void C3EditApp::SaveCustomState() { } // C3EditApp message handlers void C3EditApp::OnFileNewFrame() { ASSERT(m_pDocTemplate != nullptr); CDocument* pDoc = nullptr; CFrameWnd* pFrame = nullptr; // Create a new instance of the document referenced // by the m_pDocTemplate member. if (m_pDocTemplate != nullptr) pDoc = m_pDocTemplate->CreateNewDocument(); if (pDoc != nullptr) { // If creation worked, use create a new frame for // that document. pFrame = m_pDocTemplate->CreateNewFrame(pDoc, nullptr); if (pFrame != nullptr) { // Set the title, and initialize the document. // If document initialization fails, clean-up // the frame window and document. m_pDocTemplate->SetDefaultTitle(pDoc); if (!pDoc->OnNewDocument()) { pFrame->DestroyWindow(); pFrame = nullptr; } else { // Otherwise, update the frame m_pDocTemplate->InitialUpdateFrame(pFrame, pDoc, TRUE); } } } // If we failed, clean up the document and show a // message to the user. if (pFrame == nullptr || pDoc == nullptr) { delete pDoc; AfxMessageBox(AFX_IDP_FAILED_TO_CREATE_DOC); } } void C3EditApp::OnFileNew() { CDocument* pDoc = nullptr; CFrameWnd* pFrame; pFrame = DYNAMIC_DOWNCAST(CFrameWnd, CWnd::GetActiveWindow()); if (pFrame != nullptr) pDoc = pFrame->GetActiveDocument(); if (pFrame == nullptr || pDoc == nullptr) { // if it's the first document, create as normal CWinApp::OnFileNew(); } else { // Otherwise, see if we have to save modified, then // ask the document to reinitialize itself. if (!pDoc->SaveModified()) return; CDocTemplate* pTemplate = pDoc->GetDocTemplate(); ASSERT(pTemplate != nullptr); if (pTemplate != nullptr) pTemplate->SetDefaultTitle(pDoc); pDoc->OnNewDocument(); } } int C3EditApp::ExitInstance() { m_Config->Release(); m_C3->Release(); return CWinAppEx::ExitInstance(); }
25.848131
122
0.683992
[ "object", "transform" ]
1801a31915607f9d35925778e32e40ed033b3cf5
9,900
cpp
C++
src/fnt/text_shaper.cpp
cpp-niel/cdv
9aa310c6fe66dbc7f224ace3a3d4212ca6f0ed4a
[ "MIT" ]
1
2020-08-09T01:05:30.000Z
2020-08-09T01:05:30.000Z
src/fnt/text_shaper.cpp
cpp-niel/cdv
9aa310c6fe66dbc7f224ace3a3d4212ca6f0ed4a
[ "MIT" ]
null
null
null
src/fnt/text_shaper.cpp
cpp-niel/cdv
9aa310c6fe66dbc7f224ace3a3d4212ca6f0ed4a
[ "MIT" ]
null
null
null
#include <cdv/fnt/text_shaper.hpp> #include <fnt/freetype_error.hpp> #include <fnt/mfl_font_face.hpp> #include <fontconfig/fontconfig.h> #include <harfbuzz/hb-ft.h> #include <mfl/layout.hpp> #include <range/v3/algorithm/count.hpp> namespace cdv::fnt { namespace { using namespace units_literals; template <typename T> concept font_position = std::is_same_v<T, hb_position_t> || std::is_same_v<T, FT_F26Dot6>; pixels fixpoint_26_6_to_pixels(const font_position auto pos) { return pixels(static_cast<double>(pos) / 64.0); } using pattern_ptr = std::unique_ptr<FcPattern, decltype(&FcPatternDestroy)>; pattern_ptr create_font_config_pattern(const font_properties& properties, const points size) { // clang-format off return pattern_ptr(FcPatternBuild(nullptr, FC_FAMILY, FcTypeString, properties.family.c_str(), FC_SLANT, FcTypeInteger, static_cast<int>(properties.slant), FC_WEIGHT, FcTypeInteger, static_cast<int>(properties.weight), FC_WIDTH, FcTypeInteger, static_cast<int>(properties.stretch), FC_SIZE, FcTypeDouble, size.value(), nullptr), FcPatternDestroy); // clang-format on } void fontconfig_substitute(_FcConfig* fc_config, FcPattern* pattern, const font_properties& properties) { FcDefaultSubstitute(pattern); if (!FcConfigSubstitute(fc_config, pattern, FcMatchPattern)) throw std::runtime_error(fmt::format( "fontconfig failed to perform substitution due to allocation failure. Requested font was {}", properties)); } std::pair<std::string, int> fontconfig_match(_FcConfig* fc_config, FcPattern* pattern, const font_properties& properties) { FcResult res = FcResultNoMatch; const auto font = pattern_ptr(FcFontMatch(fc_config, pattern, &res), FcPatternDestroy); if (font) { FcChar8* file_name = nullptr; if (FcPatternGetString(font.get(), FC_FILE, 0, &file_name) != FcResultMatch) throw std::runtime_error(fmt::format("Could not get filename for font {}", properties)); int face_index = 0; if (FcPatternGetInteger(font.get(), FC_INDEX, 0, &face_index) != FcResultMatch) { throw std::runtime_error(fmt::format( "Could not get index for font '{}'. The initial request was for {}", file_name, properties)); } return {reinterpret_cast<char*>(file_name), face_index}; } throw std::runtime_error(fmt::format("fontconfig failed to find a match for {}", properties)); } std::pair<std::string, int> fontconfig_select_face(_FcConfig* fc_config, const font_properties& properties, const points size) { const auto pat = create_font_config_pattern(properties, size); fontconfig_substitute(fc_config, pat.get(), properties); return fontconfig_match(fc_config, pat.get(), properties); } std::pair<std::vector<shaped_glyph>, pixel_pos> shape_normal_text(const std::string& text, const pixels x_offset, freetype::face_t* ft_face) { using hb_buffer_ptr = std::unique_ptr<hb_buffer_t, decltype(&hb_buffer_destroy)>; const auto hb_buffer = hb_buffer_ptr(hb_buffer_create(), hb_buffer_destroy); hb_buffer_set_direction(hb_buffer.get(), HB_DIRECTION_LTR); hb_buffer_set_script(hb_buffer.get(), HB_SCRIPT_LATIN); hb_buffer_set_language(hb_buffer.get(), hb_language_from_string("en", -1)); hb_buffer_add_utf8(hb_buffer.get(), text.c_str(), static_cast<int>(text.length()), 0, static_cast<int>(text.length())); const auto hb_font = std::unique_ptr<hb_font_t, decltype(&hb_font_destroy)>( hb_ft_font_create_referenced(ft_face), hb_font_destroy); hb_shape(hb_font.get(), hb_buffer.get(), nullptr, 0); pixel_pos extents{}; unsigned int num_glyphs = 0; hb_glyph_position_t* glyph_pos = hb_buffer_get_glyph_positions(hb_buffer.get(), &num_glyphs); hb_glyph_info_t* glyph_info = hb_buffer_get_glyph_infos(hb_buffer.get(), &num_glyphs); auto x = x_offset; std::vector<shaped_glyph> glyphs(num_glyphs); for (auto i = 0u; i < num_glyphs; ++i) { glyphs[i].index = glyph_info[i].codepoint; glyphs[i].pos.x = x + fixpoint_26_6_to_pixels(glyph_pos[i].x_offset); glyphs[i].pos.y = -fixpoint_26_6_to_pixels(glyph_pos[i].y_offset); x += fixpoint_26_6_to_pixels(glyph_pos[i].x_advance); extents.x += fixpoint_26_6_to_pixels(glyph_pos[i].x_advance); FT_Load_Glyph(ft_face, glyph_info[i].codepoint, FT_LOAD_DEFAULT); extents.y = std::max(extents.y, fixpoint_26_6_to_pixels(ft_face->glyph->metrics.height)); } return {glyphs, extents}; } } text_shaper::text_shaper() : fc_config_(FcInitLoadConfigAndFonts()) { if (!FcConfigAppFontAddDir(fc_config_, reinterpret_cast<const FcChar8*>(CDV_DATA_DIR "/fonts/ttf"))) throw std::runtime_error("Failed to add cdv font directory to fontconfig"); select_face({.family = "sans-serif"}, 12_pt); } void text_shaper::select_face(const font_properties& properties, const points size) { auto [file_name, face_index] = fontconfig_select_face(fc_config_, properties, size); face_ = &freetype_.face(file_name, face_index); } shaped_text text_shaper::shape(const std::string& text, const points size, const dots_per_inch dpi) const { freetype::set_size(face_, size, dpi); shaped_text result; if (ranges::count(text, '$') < 2) { auto [glyphs, extents] = shape_normal_text(text, 0_px, face_); result.runs_.emplace_back( shaped_text_run{.font_size = size, .freetype_face = face_, .glyphs = std::move(glyphs)}); result.extents_ = extents; return result; } pixel_pos total_extents{}; auto substring_start = 0ul; while (substring_start < text.length()) { auto substring_end = text.find('$', substring_start + 1); if ((substring_end != std::string::npos) and (text[substring_start] == '$') and (text[substring_end] == '$')) { substring_end += 1; // include the closing '$' in the substring const auto substring = text.substr(substring_start, substring_end - substring_start); const auto extents = shape_mathematical_formula(substring, size, total_extents.x, dpi, result); total_extents = {total_extents.x + extents.x, std::max(total_extents.y, extents.y)}; } else { const auto substring = text.substr(substring_start, substring_end - substring_start); auto [glyphs, extents] = shape_normal_text(substring, total_extents.x, face_); result.runs_.emplace_back( shaped_text_run{.font_size = size, .freetype_face = face_, .glyphs = std::move(glyphs)}); total_extents = {total_extents.x + extents.x, std::max(total_extents.y, extents.y)}; } substring_start = substring_end; } result.extents_ = total_extents; return result; } pixel_pos text_shaper::shape_mathematical_formula(const std::string& text, const points size, const pixels x_offset, const dots_per_inch dpi, shaped_text& result) const { const auto create_font_face = [&](const mfl::font_family family) { return std::make_unique<mfl_font_face>(family, freetype_); }; auto elements = mfl::layout(text.substr(1, text.length() - 2), size, create_font_face); if (elements.error) throw std::runtime_error(*elements.error); for (const auto glyph : elements.glyphs) { shaped_text_run run; if (!elements.lines.empty()) { run.lines.reserve(elements.lines.size()); for (const auto line : elements.lines) { shaped_line l; l.min.x = x_offset + mfl::points_to_pixels(line.x, dpi); l.min.y = -mfl::points_to_pixels(line.y, dpi); l.max.x = l.min.x + mfl::points_to_pixels(line.length, dpi); l.max.y = l.min.y - mfl::points_to_pixels(line.thickness, dpi); run.lines.push_back(l); } elements.lines.clear(); } run.font_size = glyph.size; run.freetype_face = &freetype_.face(glyph.family); const auto x = x_offset + mfl::points_to_pixels(glyph.x, dpi); const auto y = -mfl::points_to_pixels(glyph.y, dpi); run.glyphs.emplace_back(shaped_glyph{.index = glyph.index, .pos = pixel_pos{x, y}}); result.runs_.emplace_back(std::move(run)); } return {mfl::points_to_pixels(elements.width, dpi), mfl::points_to_pixels(elements.height, dpi)}; } }
46.261682
120
0.587778
[ "shape", "vector" ]
180845c99cb15ce97a7257581cbb5782486a58d8
14,377
cpp
C++
tests/src/array.cpp
dhurum/sjparser
1881c050e8c6752ecaf2c41d5115ffb489efc711
[ "MIT" ]
1
2021-04-12T05:22:35.000Z
2021-04-12T05:22:35.000Z
tests/src/array.cpp
dhurum/sjparser
1881c050e8c6752ecaf2c41d5115ffb489efc711
[ "MIT" ]
null
null
null
tests/src/array.cpp
dhurum/sjparser
1881c050e8c6752ecaf2c41d5115ffb489efc711
[ "MIT" ]
null
null
null
/******************************************************************************* Copyright (c) 2016-2017 Denis Tikhomirov <dvtikhomirov@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *******************************************************************************/ #include <gtest/gtest.h> #include <map> #include "sjparser/sjparser.h" using namespace SJParser; TEST(Array, Empty) { std::string buf(R"([])"); std::vector<bool> values; auto elementCb = [&](const bool &value) { values.push_back(value); return true; }; Parser parser{Array{Value<bool>{elementCb}}}; ASSERT_NO_THROW(parser.parse(buf)); ASSERT_NO_THROW(parser.finish()); ASSERT_EQ(0, values.size()); ASSERT_TRUE(parser.parser().isSet()); ASSERT_TRUE(parser.parser().isEmpty()); } TEST(Array, Null) { std::string buf(R"(null)"); std::vector<bool> values; auto elementCb = [&](const bool &value) { values.push_back(value); return true; }; Parser parser{Array{Value<bool>{elementCb}}}; ASSERT_NO_THROW(parser.parse(buf)); ASSERT_NO_THROW(parser.finish()); ASSERT_EQ(0, values.size()); ASSERT_FALSE(parser.parser().isSet()); ASSERT_TRUE(parser.parser().isEmpty()); } TEST(Array, Reset) { std::string buf(R"([true])"); std::vector<bool> values; auto elementCb = [&](const bool &value) { values.push_back(value); return true; }; Parser parser{Array{Value<bool>{elementCb}}}; ASSERT_NO_THROW(parser.parse(buf)); ASSERT_NO_THROW(parser.finish()); ASSERT_EQ(1, values.size()); ASSERT_EQ(true, values[0]); ASSERT_TRUE(parser.parser().isSet()); ASSERT_FALSE(parser.parser().isEmpty()); buf = R"(null)"; ASSERT_NO_THROW(parser.parse(buf)); ASSERT_NO_THROW(parser.finish()); ASSERT_FALSE(parser.parser().isSet()); ASSERT_TRUE(parser.parser().isEmpty()); } TEST(Array, ArrayOfBooleans) { std::string buf(R"([true, false])"); std::vector<bool> values; auto elementCb = [&](const bool &value) { values.push_back(value); return true; }; Parser parser{Array{Value<bool>{elementCb}}}; ASSERT_NO_THROW(parser.parse(buf)); ASSERT_NO_THROW(parser.finish()); ASSERT_EQ(2, values.size()); ASSERT_EQ(true, values[0]); ASSERT_EQ(false, values[1]); ASSERT_TRUE(parser.parser().isSet()); } TEST(Array, ArrayOfIntegers) { std::string buf(R"([10, 11])"); std::vector<int64_t> values; auto elementCb = [&](const int64_t &value) { values.push_back(value); return true; }; Parser parser{Array{Value<int64_t>{elementCb}}}; ASSERT_NO_THROW(parser.parse(buf)); ASSERT_NO_THROW(parser.finish()); ASSERT_EQ(2, values.size()); ASSERT_EQ(10, values[0]); ASSERT_EQ(11, values[1]); ASSERT_TRUE(parser.parser().isSet()); } TEST(Array, ArrayOfDoubles) { std::string buf(R"([10.5, 11.2])"); std::vector<double> values; auto elementCb = [&](const double &value) { values.push_back(value); return true; }; Parser parser{Array{Value<double>{elementCb}}}; ASSERT_NO_THROW(parser.parse(buf)); ASSERT_NO_THROW(parser.finish()); ASSERT_EQ(2, values.size()); ASSERT_EQ(10.5, values[0]); ASSERT_EQ(11.2, values[1]); ASSERT_TRUE(parser.parser().isSet()); } TEST(Array, ArrayOfStrings) { std::string buf(R"(["value1", "value2"])"); std::vector<std::string> values; auto elementCb = [&](const std::string &value) { values.push_back(value); return true; }; Parser parser{Array{Value<std::string>{elementCb}}}; ASSERT_NO_THROW(parser.parse(buf)); ASSERT_NO_THROW(parser.finish()); ASSERT_EQ(2, values.size()); ASSERT_EQ("value1", values[0]); ASSERT_EQ("value2", values[1]); ASSERT_TRUE(parser.parser().isSet()); } TEST(Array, ArrayWithNull) { std::string buf(R"([null])"); std::vector<bool> values; auto elementCb = [&](const bool &value) { values.push_back(value); return true; }; Parser parser{Array{Value<bool>{elementCb}}}; ASSERT_NO_THROW(parser.parse(buf)); ASSERT_NO_THROW(parser.finish()); ASSERT_EQ(0, values.size()); ASSERT_TRUE(parser.parser().isSet()); } TEST(Array, ArrayWithNullAndValues) { std::string buf(R"([null, true, null, false])"); std::vector<bool> values; auto elementCb = [&](const bool &value) { values.push_back(value); return true; }; Parser parser{Array{Value<bool>{elementCb}}}; ASSERT_NO_THROW(parser.parse(buf)); ASSERT_NO_THROW(parser.finish()); ASSERT_EQ(2, values.size()); ASSERT_EQ(true, values[0]); ASSERT_EQ(false, values[1]); ASSERT_TRUE(parser.parser().isSet()); } TEST(Array, UnexpectedBoolean) { std::string buf(R"(true)"); auto elementCb = [&](const bool &) { return true; }; Parser parser{Array{Value<bool>{elementCb}}}; try { parser.parse(buf); FAIL() << "No exception thrown"; } catch (ParsingError &e) { ASSERT_FALSE(parser.parser().isSet()); ASSERT_EQ("Unexpected token boolean", e.sjparserError()); ASSERT_EQ( R"(parse error: client cancelled parse via callback return value true (right here) ------^ )", e.parserError()); } catch (...) { FAIL() << "Invalid exception thrown"; } } TEST(Array, UnexpectedInteger) { std::string buf(R"(10)"); auto elementCb = [&](const int64_t &) { return true; }; Parser parser{Array{Value<int64_t>{elementCb}}}; ASSERT_NO_THROW(parser.parse(buf)); try { parser.finish(); FAIL() << "No exception thrown"; } catch (ParsingError &e) { ASSERT_FALSE(parser.parser().isSet()); ASSERT_EQ("Unexpected token integer", e.sjparserError()); ASSERT_EQ( R"(parse error: client cancelled parse via callback return value 10 (right here) ------^ )", e.parserError()); } catch (...) { FAIL() << "Invalid exception thrown"; } } TEST(Array, UnexpectedDouble) { std::string buf(R"(10.5)"); auto elementCb = [&](const double &) { return true; }; Parser parser{Array{Value<double>{elementCb}}}; ASSERT_NO_THROW(parser.parse(buf)); try { parser.finish(); FAIL() << "No exception thrown"; } catch (ParsingError &e) { ASSERT_FALSE(parser.parser().isSet()); ASSERT_EQ("Unexpected token double", e.sjparserError()); ASSERT_EQ( R"(parse error: client cancelled parse via callback return value 10.5 (right here) ------^ )", e.parserError()); } catch (...) { FAIL() << "Invalid exception thrown"; } } TEST(Array, UnexpectedString) { std::string buf(R"("value")"); auto elementCb = [&](const std::string &) { return true; }; Parser parser{Array{Value<std::string>{elementCb}}}; try { parser.parse(buf); FAIL() << "No exception thrown"; } catch (ParsingError &e) { ASSERT_FALSE(parser.parser().isSet()); ASSERT_EQ("Unexpected token string", e.sjparserError()); ASSERT_EQ( R"(parse error: client cancelled parse via callback return value "value" (right here) ------^ )", e.parserError()); } catch (...) { FAIL() << "Invalid exception thrown"; } } TEST(Array, ArrayOfObjects) { std::string buf( R"([{"key": "value", "key2": 10}, {"key": "value2", "key2": 20}])"); struct ObjectStruct { std::string member1; int64_t member2; }; std::vector<ObjectStruct> values; using ObjectParser = Object<Value<std::string>, Value<int64_t>>; auto objectCb = [&](ObjectParser &parser) { values.push_back({parser.pop<0>(), parser.pop<1>()}); return true; }; Parser parser{Array{Object{std::tuple{Member{"key", Value<std::string>{}}, Member{"key2", Value<int64_t>{}}}, objectCb}}}; ASSERT_NO_THROW(parser.parse(buf)); ASSERT_NO_THROW(parser.finish()); ASSERT_EQ(2, values.size()); ASSERT_EQ("value", values[0].member1); ASSERT_EQ(10, values[0].member2); ASSERT_EQ("value2", values[1].member1); ASSERT_EQ(20, values[1].member2); } TEST(Array, UnexpectedMapStart) { std::string buf(R"({})"); Parser parser{Array{Value<bool>{}}}; try { parser.parse(buf); FAIL() << "No exception thrown"; } catch (ParsingError &e) { ASSERT_FALSE(parser.parser().isSet()); ASSERT_EQ("Unexpected token map start", e.sjparserError()); ASSERT_EQ( R"(parse error: client cancelled parse via callback return value {} (right here) ------^ )", e.parserError()); } catch (...) { FAIL() << "Invalid exception thrown"; } } TEST(Array, ArrayWithUnexpectedType) { std::string buf(R"([true])"); auto elementCb = [&](const std::string &) { return true; }; Parser parser{Array{Value<std::string>{elementCb}}}; try { parser.parse(buf); FAIL() << "No exception thrown"; } catch (ParsingError &e) { ASSERT_FALSE(parser.parser().isSet()); ASSERT_EQ("Unexpected token boolean", e.sjparserError()); ASSERT_EQ( R"(parse error: client cancelled parse via callback return value [true] (right here) ------^ )", e.parserError()); } catch (...) { FAIL() << "Invalid exception thrown"; } } TEST(Array, ArrayWithElementCallbackError) { std::string buf(R"([true, false])"); auto elementCb = [&](const bool &) { return false; }; Parser parser{Array{Value<bool>{elementCb}}}; try { parser.parse(buf); FAIL() << "No exception thrown"; } catch (ParsingError &e) { ASSERT_FALSE(parser.parser().isSet()); ASSERT_EQ("Callback returned false", e.sjparserError()); ASSERT_EQ( R"(parse error: client cancelled parse via callback return value [true, false] (right here) ------^ )", e.parserError()); } catch (...) { FAIL() << "Invalid exception thrown"; } } TEST(Array, ArrayWithCallback) { std::string buf(R"([true, false])"); std::vector<bool> values; bool callback_called = false; auto elementCb = [&](const bool &value) { values.push_back(value); return true; }; auto arrayCb = [&](Array<Value<bool>> &) { callback_called = true; return true; }; Parser parser{Array{Value<bool>{elementCb}, arrayCb}}; ASSERT_NO_THROW(parser.parse(buf)); ASSERT_NO_THROW(parser.finish()); ASSERT_EQ(2, values.size()); ASSERT_EQ(true, values[0]); ASSERT_EQ(false, values[1]); ASSERT_EQ(true, callback_called); ASSERT_TRUE(parser.parser().isSet()); } TEST(Array, ArrayWithCallbackError) { std::string buf(R"([true, false])"); auto elementCb = [&](const bool &) { return true; }; Parser parser{Array{Value<bool>{elementCb}}}; auto arrayCb = [&](decltype(parser)::ParserType &) { return false; }; parser.parser().setFinishCallback(arrayCb); try { parser.parse(buf); FAIL() << "No exception thrown"; } catch (ParsingError &e) { ASSERT_TRUE(parser.parser().isSet()); ASSERT_EQ("Callback returned false", e.sjparserError()); ASSERT_EQ( R"(parse error: client cancelled parse via callback return value [true, false] (right here) ------^ )", e.parserError()); } catch (...) { FAIL() << "Invalid exception thrown"; } } TEST(Array, ArrayOfArrays) { std::string buf(R"([[true, true], [false, false]])"); std::vector<std::vector<bool>> values; std::vector<bool> tmp_values; auto elementCb = [&](const bool &value) { tmp_values.push_back(value); return true; }; auto innerArrayCb = [&](Array<Value<bool>> &) { values.push_back(tmp_values); tmp_values.clear(); return true; }; Parser parser{Array{Array{Value<bool>{elementCb}, innerArrayCb}}}; ASSERT_NO_THROW(parser.parse(buf)); ASSERT_NO_THROW(parser.finish()); ASSERT_EQ(2, values.size()); ASSERT_EQ(2, values[0].size()); ASSERT_EQ(true, values[0][0]); ASSERT_EQ(true, values[0][1]); ASSERT_EQ(2, values[1].size()); ASSERT_EQ(false, values[1][0]); ASSERT_EQ(false, values[1][1]); } TEST(Array, ArrayWithParserReference) { std::string buf(R"([[13, 15, 16]])"); SArray sarray{Value<int64_t>{}}; Parser parser{Array{sarray}}; ASSERT_NO_THROW(parser.parse(buf)); ASSERT_NO_THROW(parser.finish()); ASSERT_EQ(3, sarray.get().size()); ASSERT_EQ(13, sarray.get()[0]); ASSERT_EQ(15, sarray.get()[1]); ASSERT_EQ(16, sarray.get()[2]); ASSERT_EQ(&(parser.parser().parser()), &sarray); } // Just check if the constructor compiles TEST(Array, ArrayWithArrayReference) { Array array{Value<int64_t>{}}; Parser parser{Array{array}}; ASSERT_EQ(&(parser.parser().parser()), &array); } TEST(Array, MoveAssignment) { std::string buf(R"([10, 11])"); std::vector<int64_t> values; auto elementCb = [&](const int64_t &value) { values.push_back(value); return true; }; auto array_parser_src = Array{Value<int64_t>{elementCb}}; auto array_parser = Array{Value<int64_t>{}}; array_parser = std::move(array_parser_src); Parser parser{array_parser}; ASSERT_NO_THROW(parser.parse(buf)); ASSERT_NO_THROW(parser.finish()); ASSERT_EQ(2, values.size()); ASSERT_EQ(10, values[0]); ASSERT_EQ(11, values[1]); ASSERT_TRUE(parser.parser().isSet()); }
25.267135
80
0.625861
[ "object", "vector" ]
1815ccc5becb0622a547a0d6e320b47a2d1752f3
5,212
cpp
C++
src/mrp/snmp-engine/main.cpp
fredsongyu/mmitss-az
62fb59a9e5a19f62a1096971f3cc0ecc04599106
[ "Apache-2.0" ]
10
2018-12-05T14:48:59.000Z
2022-02-17T02:10:51.000Z
src/mrp/snmp-engine/main.cpp
fredsongyu/mmitss-az
62fb59a9e5a19f62a1096971f3cc0ecc04599106
[ "Apache-2.0" ]
null
null
null
src/mrp/snmp-engine/main.cpp
fredsongyu/mmitss-az
62fb59a9e5a19f62a1096971f3cc0ecc04599106
[ "Apache-2.0" ]
8
2018-11-16T06:38:25.000Z
2022-03-09T18:22:59.000Z
/*************************************************************************************** © 2019 Arizona Board of Regents on behalf of the University of Arizona with rights granted for USDOT OSADP distribution with the Apache 2.0 open source license. *************************************************************************************** main.cpp (SnmpEngine) Created by: Niraj Vasant Altekar University of Arizona College of Engineering This code was developed under the supervision of Professor Larry Head in the Systems and Industrial Engineering Department. *************************************************************************************** Description: ------------ This is a wrapper application for the SnmpEngine class. Once started, the applciation waits for the messages over UDP socket. The received message is parsed into a JSON and its type is identified. Based on the message type, appropriate methods from the SnmpEngine class are called to process and execute the SnmpGet or SnmpSet request in the target SNMP device. ***************************************************************************************/ # include <iostream> # include <fstream> # include "json/json.h" # include "UdpSocket.h" # include "SnmpEngine.h" int main() { std::string setCustomMibsCommand = "export MIBS=ALL"; system(setCustomMibsCommand.c_str()); Json::Value jsonObject_config; std::ifstream configJson("/nojournal/bin/mmitss-phase3-master-config.json"); string configJsonString((std::istreambuf_iterator<char>(configJson)), std::istreambuf_iterator<char>()); Json::CharReaderBuilder builder; Json::CharReader * reader = builder.newCharReader(); std::string errors{}; reader->parse(configJsonString.c_str(), configJsonString.c_str() + configJsonString.size(), &jsonObject_config, &errors); delete reader; configJson.close(); // Read the network config for the SnmpEngine applciation std::string ascIp = jsonObject_config["SignalController"]["IpAddress"].asString(); int ascNtcipPort = jsonObject_config["SignalController"]["NtcipPort"].asUInt(); // Open a UDP socket for receiving messages from other clients for SnmpSet or SnmpGet UdpSocket snmpEngineSocket(static_cast<short unsigned int>(jsonObject_config["PortNumber"]["SnmpEngine"].asInt())); // Variables to store the received message and its type char receiveBuffer[10240]{}; std::string msgType; // Variables to store the JSON object and JSON strings to be received Json::Value receivedJson; std::string receivedOid{}; // Variables to store the JSON object and JSON strings to be sent Json::Value sendingJson; Json::StreamWriterBuilder writeBuilder; writeBuilder["commentStyle"] = "None"; writeBuilder["indentation"] = ""; std::string sendingJsonString{}; // Variables to store the SNMP requests related information int value{}; int snmpResponse{}; // Variables to store the network information of request senders - Used for SnmpGet requests. std::string senderIp{}; short unsigned int senderPort{}; // Instantiate an object opf SnmpEngine class SnmpEngine snmp(ascIp, ascNtcipPort); // Creator another reader Json::CharReader * inputReader = builder.newCharReader(); while(true) { snmpEngineSocket.receiveData(receiveBuffer, sizeof(receiveBuffer)); std::string jsonString(receiveBuffer); inputReader->parse(jsonString.c_str(), jsonString.c_str() + jsonString.size(), &receivedJson, &errors); // Parse the message type and OID for set or get request msgType = receivedJson["MsgType"].asString(); receivedOid = receivedJson["OID"].asString(); if(msgType=="SnmpSetRequest") { value = receivedJson["Value"].asInt(); // Process the SNMP set request for given OID and given value snmpResponse = snmp.processSnmpRequest("set", receivedOid, value); } else if(msgType=="SnmpGetRequest") { // Stored the netowork information of the requestor so that the // values received by SnmpGet call can be returned back senderIp = snmpEngineSocket.getSenderIP(); senderPort = snmpEngineSocket.getSenderPort(); // SnmpGet request do not require any value to be provided initially // This value is filled after getting the response from the target SNMP device value=0; // Process the SnmpGet request snmpResponse = snmp.processSnmpRequest("get", receivedOid, value); // Formulate the JSOn string to send back to the requestor sendingJson["MsgType"] = "SnmpGetResponse"; sendingJson["OID"] = receivedOid; sendingJson["Value"] = snmpResponse; sendingJsonString = Json::writeString(writeBuilder, sendingJson); // Send the response to the requestor snmpEngineSocket.sendData(senderIp, senderPort, sendingJsonString); } } delete inputReader; snmpEngineSocket.closeSocket(); return 0; }
40.403101
133
0.642172
[ "object" ]
1817753059981c91c2c86ec848e9a54dee9c91aa
20,533
hpp
C++
oss_src/graphlab/engine/warp_graph_broadcast.hpp
parquette/ParFrame
0522aa6afdf529b3e91505b70e918f1500aae886
[ "BSD-3-Clause" ]
null
null
null
oss_src/graphlab/engine/warp_graph_broadcast.hpp
parquette/ParFrame
0522aa6afdf529b3e91505b70e918f1500aae886
[ "BSD-3-Clause" ]
null
null
null
oss_src/graphlab/engine/warp_graph_broadcast.hpp
parquette/ParFrame
0522aa6afdf529b3e91505b70e918f1500aae886
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (C) 2015 Dato, Inc. * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ /* * Copyright (c) 2009 Carnegie Mellon University. * 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. * * For more about this software visit: * * http://www.graphlab.ml.cmu.edu * */ #ifndef GRAPHLAB_WARP_GRAPH_BROADCAST_HPP #define GRAPHLAB_WARP_GRAPH_BROADCAST_HPP #include <boost/bind.hpp> #include <graphlab/util/generics/conditional_combiner_wrapper.hpp> #include <fiber/fiber_group.hpp> #include <fiber/fiber_control.hpp> #include <fiber/fiber_remote_request.hpp> #include <logger/assertions.hpp> #include <rpc/dc.hpp> #include <graphlab/engine/warp_event_log.hpp> #include <graphlab/macros_def.hpp> namespace graphlab { namespace warp { namespace warp_impl { template <typename EngineType, typename GraphType> struct broadcast_neighborhood_impl { typedef typename EngineType::context_type context_type; typedef typename GraphType::vertex_type vertex_type; typedef typename GraphType::vertex_data_type vertex_data_type; typedef typename GraphType::edge_type edge_type; typedef typename GraphType::local_vertex_type local_vertex_type; typedef typename GraphType::local_edge_type local_edge_type; typedef typename GraphType::vertex_record vertex_record; /**************************************************************************/ /* */ /* Basic MapReduce Neighborhood Implementation */ /* */ /**************************************************************************/ /* * The master calls basic_mapreduce_neighborhood. * Which then issues calls to basic_local_mapper on each machine with a replica. */ static void basic_local_broadcast_neighborhood(context_type& context, edge_dir_type edge_direction, void(*broadcast_fn)(context_type& context, edge_type edge, vertex_type other), vertex_id_type vid) { GraphType& graph(context.graph); lvid_type lvid = graph.local_vid(vid); local_vertex_type local_vertex(context.graph.l_vertex(lvid)); if(edge_direction == IN_EDGES || edge_direction == ALL_EDGES) { foreach(local_edge_type local_edge, local_vertex.in_edges()) { edge_type edge(local_edge); vertex_type other(local_edge.source()); lvid_type a = edge.source().local_id(), b = edge.target().local_id(); graph.get_lock_manager()[std::min(a,b)].lock(); graph.get_lock_manager()[std::max(a,b)].lock(); broadcast_fn(context, edge, other); graph.get_lock_manager()[a].unlock(); graph.get_lock_manager()[b].unlock(); } } // do out edges if(edge_direction == OUT_EDGES || edge_direction == ALL_EDGES) { foreach(local_edge_type local_edge, local_vertex.out_edges()) { edge_type edge(local_edge); vertex_type other(local_edge.target()); lvid_type a = edge.source().local_id(), b = edge.target().local_id(); graph.get_lock_manager()[std::min(a,b)].lock(); graph.get_lock_manager()[std::max(a,b)].lock(); broadcast_fn(context, edge, other); graph.get_lock_manager()[a].unlock(); graph.get_lock_manager()[b].unlock(); } } } static void basic_local_broadcast_neighborhood_from_remote(std::pair<size_t, size_t> objid, edge_dir_type edge_direction, size_t broadcast_ptr, vertex_id_type vid, vertex_data_type& vdata) { EngineType* engine = reinterpret_cast<EngineType*>(distributed_control::get_instance()->get_registered_object(objid.first)); GraphType* graph = reinterpret_cast<GraphType*>(distributed_control::get_instance()->get_registered_object(objid.second)); vertex_type vertex(graph->l_vertex(graph->local_vid(vid))); context_type context(*engine, *graph, vertex); vertex.data() = vdata; // cast the mappers and combiners back into their pointer types void(*broadcast_fn)(context_type&, edge_type edge, vertex_type other) = reinterpret_cast<void(*)(context_type&, edge_type, vertex_type)>(broadcast_ptr); basic_local_broadcast_neighborhood( context, edge_direction, broadcast_fn, vid); } static void basic_broadcast_neighborhood(context_type& context, typename GraphType::vertex_type current, edge_dir_type edge_direction, void(*broadcast_fn)(context_type& context, edge_type edge, vertex_type other)) { // get a reference to the graph GraphType& graph = current.graph_ref; // get the object ID of the graph std::pair<size_t, size_t> objid(context.engine.get_rpc_obj_id(), graph.get_rpc_obj_id()); typename GraphType::vertex_record vrecord = graph.l_get_vertex_record(current.local_id()); // make sure we are running on a master vertex ASSERT_EQ(vrecord.owner, distributed_control::get_instance_procid()); // create num-mirrors worth of requests std::vector<request_future<void > > requests(vrecord.num_mirrors()); size_t ctr = 0; foreach(procid_t proc, vrecord.mirrors()) { // issue the communication requests[ctr] = fiber_remote_request(proc, basic_local_broadcast_neighborhood_from_remote, objid, edge_direction, reinterpret_cast<size_t>(broadcast_fn), current.id(), current.data()); ++ctr; } // compute the local tasks basic_local_broadcast_neighborhood(context, edge_direction, broadcast_fn, current.id()); // now, wait for everyone for (size_t i = 0;i < requests.size(); ++i) { requests[i](); } } }; template <typename EngineType, typename GraphType, typename ExtraArg> struct broadcast_neighborhood_impl2 { typedef typename EngineType::context_type context_type; typedef typename GraphType::vertex_type vertex_type; typedef typename GraphType::vertex_data_type vertex_data_type; typedef typename GraphType::edge_type edge_type; typedef typename GraphType::local_vertex_type local_vertex_type; typedef typename GraphType::local_edge_type local_edge_type; typedef typename GraphType::vertex_record vertex_record; /**************************************************************************/ /* */ /* Extended MapReduce Neighborhood Implementation */ /* */ /**************************************************************************/ /* * The master calls extended_mapreduce_neighborhood. * Which then issues calls to extended_local_mapper on each machine with a replica. * The extended mapreduce neighborhood allows the mapper and combiner to take * an optional argument */ static void extended_local_broadcast_neighborhood(context_type& context, edge_dir_type edge_direction, void(*broadcast_fn)(context_type& context, edge_type edge, vertex_type other, const ExtraArg extra), vertex_id_type vid, const ExtraArg extra) { GraphType& graph(context.graph); lvid_type lvid = graph.local_vid(vid); local_vertex_type local_vertex(graph.l_vertex(lvid)); if(edge_direction == IN_EDGES || edge_direction == ALL_EDGES) { foreach(local_edge_type local_edge, local_vertex.in_edges()) { edge_type edge(local_edge); vertex_type other(local_edge.source()); lvid_type a = edge.source().local_id(), b = edge.target().local_id(); graph.get_lock_manager()[std::min(a,b)].lock(); graph.get_lock_manager()[std::max(a,b)].lock(); broadcast_fn(context, edge, other, extra); graph.get_lock_manager()[a].unlock(); graph.get_lock_manager()[b].unlock(); } } // do out edges if(edge_direction == OUT_EDGES || edge_direction == ALL_EDGES) { foreach(local_edge_type local_edge, local_vertex.out_edges()) { edge_type edge(local_edge); vertex_type other(local_edge.target()); lvid_type a = edge.source().local_id(), b = edge.target().local_id(); graph.get_lock_manager()[std::min(a,b)].lock(); graph.get_lock_manager()[std::max(a,b)].lock(); broadcast_fn(context, edge, other, extra); graph.get_lock_manager()[a].unlock(); graph.get_lock_manager()[b].unlock(); } } } static void extended_local_broadcast_neighborhood_from_remote(std::pair<size_t, size_t> objid, edge_dir_type edge_direction, size_t broadcast_ptr, vertex_id_type vid, vertex_data_type& vdata, const ExtraArg extra) { EngineType* engine = reinterpret_cast<EngineType*>(distributed_control::get_instance()->get_registered_object(objid.first)); GraphType* graph = reinterpret_cast<GraphType*>(distributed_control::get_instance()->get_registered_object(objid.second)); vertex_type vertex(graph->l_vertex(graph->local_vid(vid))); context_type context(*engine, *graph, vertex); vertex.data() = vdata; // cast the mappers and combiners back into their pointer types void(*broadcast_fn)(context_type&, edge_type edge, vertex_type other, const ExtraArg) = reinterpret_cast<void(*)(context_type&, edge_type, vertex_type, const ExtraArg)>(broadcast_ptr); extended_local_broadcast_neighborhood( context, edge_direction, broadcast_fn, vid, extra); } static void extended_broadcast_neighborhood(context_type& context, typename GraphType::vertex_type current, edge_dir_type edge_direction, void(*broadcast_fn)(context_type& context, edge_type edge, vertex_type other, const ExtraArg extra), const ExtraArg extra) { // get a reference to the graph GraphType& graph = current.graph_ref; // get the object ID of the graph std::pair<size_t, size_t> objid(context.engine.get_rpc_obj_id(), graph.get_rpc_obj_id()); typename GraphType::vertex_record vrecord = graph.l_get_vertex_record(current.local_id()); // make sure we are running on a master vertex ASSERT_EQ(vrecord.owner, distributed_control::get_instance_procid()); // create num-mirrors worth of requests std::vector<request_future<void> > requests(vrecord.num_mirrors()); size_t ctr = 0; foreach(procid_t proc, vrecord.mirrors()) { // issue the communication requests[ctr] = fiber_remote_request(proc, extended_local_broadcast_neighborhood_from_remote, objid, edge_direction, reinterpret_cast<size_t>(broadcast_fn), current.id(), current.data(), extra); ++ctr; } // compute the local tasks extended_local_broadcast_neighborhood(context, edge_direction, broadcast_fn, current.id(), extra); // now, wait for everyone for (size_t i = 0;i < requests.size(); ++i) { requests[i](); } } }; } // namespace warp::warp_impl /** * \ingroup warp * * the broadcast_neighborhood function allows a parallel transformation of the * neighborhood of a vertex to be performed and also provides a warp_engine * context. . This is a blocking operation, and * will not return until the distributed computation is complete. When run * inside a fiber, to hide latency, the system will automatically context * switch to evaluate some other fiber which is ready to run. This function * is functionally similar to the transform_neighborhood function, but requires * a \ref graphlab::warp_engine "warp_engine" * context to be provided. The warp_engine context will also be passed on to * the transform function. * * Abstractly, the computation accomplishes the following: * * \code * foreach(edge in neighborhood of current vertex) { * transform_fn(context, edge, opposite vertex) * } * \endcode * * \attention It is important that the transform_fn should only make * modifications to the edge data, and not the data on either of the vertices. * * \attention Unlike the transform_neighborhood function, this call actually * performs synchronization, so the value of both vertex endpoints are * correct. * * Here is an example which schedules all vertices on out edges. * * \code * void schedule(engine_type::context& context, * graph_type::edge_type edge, * graph_type::vertex_type other) { * context.signal(other); * } * * * void update_function(engine_type::context& context, * graph_type::vertex_type vertex) { * warp::broadcast_neighborhood(context, * vertex, * OUT_EDGES, * schedule); * } * * \endcode * * * An overload is provided which allows you to pass an additional arbitrary * argument to the broadcast. * * \param current The vertex to map reduce the neighborhood over * \param edge_direction To run over all IN_EDGES, OUT_EDGES or ALL_EDGES * \param transform_fn The transform function to run on all the selected edges. * * \see warp_engine * \see warp::parfor_all_vertices * \see warp::map_reduce_neighborhood * \see warp::transform_neighborhood */ template <typename ContextType, typename VertexType> void broadcast_neighborhood(ContextType& context, VertexType current, edge_dir_type edge_direction, void (*broadcast_fn)(ContextType& context, typename VertexType::graph_type::edge_type edge, VertexType other)) { INCREMENT_EVENT(EVENT_WARP_BROADCAST_COUNT, 1); warp_impl:: broadcast_neighborhood_impl<typename ContextType::engine_type, typename VertexType::graph_type>:: basic_broadcast_neighborhood(context, current, edge_direction, broadcast_fn); context.set_synchronized(); } /** * \ingroup warp * * the broadcast_neighborhood function allows a parallel transformation of the * neighborhood of a vertex to be performed and also provides a warp_engine * context. . This is a blocking operation, and * will not return until the distributed computation is complete. When run * inside a fiber, to hide latency, the system will automatically context * switch to evaluate some other fiber which is ready to run. This function * is functionally similar to the transform_neighborhood function, but requires * a \ref graphlab::warp_engine "warp_engine" * context to be provided. The \ref graphlab::warp_engine::context * "warp_engine context" will also be passed on to * the transform function. * * This is the more general overload of the broadcast_neighborhood function * which allows an additional arbitrary extra argument to be passed along * to the transform function * * Abstractly, the computation accomplishes the following: * * \code * foreach(edge in neighborhood of current vertex) { * transform_fn(context, edge, opposite vertex, extraarg) * } * \endcode * * \attention It is important that the transform_fn should only make * modifications to the edge data, and not the data on either of the vertices. * * \attention Unlike the transform_neighborhood function, this call actually * performs synchronization, so the value of both vertex endpoints are * correct. * * Here is an example which schedules all vertices on out edges with a * particular value * \code * void schedule(engine_type::context& context, * graph_type::edge_type edge, * graph_type::vertex_type other, * int value) { * if (edge.data() == value) context.signal(other); * } * * * void update_function(engine_type::context& context, * graph_type::vertex_type vertex) { * // schedule all neighbors connected to an out edge * // with value 10 * warp::broadcast_neighborhood(context, * vertex, * OUT_EDGES, * int(10), * schedule)); * } * * \endcode * * \param current The vertex to map reduce the neighborhood over * \param edge_direction To run over all IN_EDGES, OUT_EDGES or ALL_EDGES * \param extra An additional argument to be passed to the broadcast * \param transform_fn The transform function to run on all the selected edges. * * \see warp_engine * \see warp::parfor_all_vertices() * \see warp::map_reduce_neighborhood() * \see warp::transform_neighborhood() */ template <typename ContextType, typename ExtraArg, typename VertexType> void broadcast_neighborhood(ContextType& context, VertexType current, edge_dir_type edge_direction, void(*broadcast_fn)(ContextType& context, typename VertexType::graph_type::edge_type edge, VertexType other, const ExtraArg extra), const ExtraArg extra) { INCREMENT_EVENT(EVENT_WARP_BROADCAST_COUNT, 1); warp_impl:: broadcast_neighborhood_impl2<typename ContextType::engine_type, typename VertexType::graph_type, ExtraArg>:: extended_broadcast_neighborhood(context, current, edge_direction, broadcast_fn, extra); context.set_synchronized(); } } // namespace warp } // namespace graphlab #include <graphlab/macros_undef.hpp> #endif
43.046122
146
0.594555
[ "object", "vector", "transform" ]
1817ff49429b18e409301c18eabfb5e366c5331e
439
cpp
C++
TouchMindLib/touchmind/prop/LineStyle.cpp
yohei-yoshihara/TouchMind
3ad878aacde7322ae7c4f94d462e0a2d4a24d3fa
[ "MIT" ]
15
2015-07-10T05:03:27.000Z
2021-06-08T08:24:46.000Z
TouchMindLib/touchmind/prop/LineStyle.cpp
yohei-yoshihara/TouchMind
3ad878aacde7322ae7c4f94d462e0a2d4a24d3fa
[ "MIT" ]
null
null
null
TouchMindLib/touchmind/prop/LineStyle.cpp
yohei-yoshihara/TouchMind
3ad878aacde7322ae7c4f94d462e0a2d4a24d3fa
[ "MIT" ]
10
2015-01-04T01:23:56.000Z
2020-12-29T11:35:47.000Z
#include "stdafx.h" #include "touchmind/prop/LineStyle.h" std::wostream &touchmind::operator<<(std::wostream &os, const touchmind::LINE_STYLE &lineStyle) { switch (lineStyle) { case LINE_STYLE_UNSPECIFIED: os << L"UNSPECIFIED"; break; case LINE_STYLE_SOLID: os << L"SOLID"; break; case LINE_STYLE_DASHED: os << L"DASHED"; break; case LINE_STYLE_DOTTED: os << L"DOTTED"; break; } return os; }
20.904762
97
0.658314
[ "solid" ]
181aae6aac16844c9fd9a807cdc8a56fc9967527
2,300
cpp
C++
Map.cpp
whiskermrr/PathFinder
8f2fcb42c0b9fcd783b8fdefb85dc51610f2934e
[ "MIT" ]
null
null
null
Map.cpp
whiskermrr/PathFinder
8f2fcb42c0b9fcd783b8fdefb85dc51610f2934e
[ "MIT" ]
null
null
null
Map.cpp
whiskermrr/PathFinder
8f2fcb42c0b9fcd783b8fdefb85dc51610f2934e
[ "MIT" ]
null
null
null
#include "Map.h" Map::Map(std::string fileName) { std::fstream file("resources/" + fileName); this->width = 0; this->height = 0; this->startNode = nullptr; this->endNode = nullptr; if (file.is_open()) { char x; while (!file.eof()) { file >> x; if (isdigit(x)) { Vector2int coords; coords.x = width; coords.y = height; Node* node = new Node(coords, x - '0'); nodesMap.push_back(node); width++; } if (file.peek() == '\n') { height++; width = 0; } } height++; } } Node* Map::findNodeOnMap(Vector2int coords) { for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (this->nodesMap.at(i * width + j)->coords == coords) return this->nodesMap.at(i * width + j); } } return nullptr; } void Map::render(sf::RenderWindow* window) { for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { window->draw(*this->nodesMap.at(i * width + j)); } } } unsigned int Map::getWidth() { return this->width; } unsigned int Map::getHeight() { return this->height; } std::vector<Node*>& Map::getNodesMap() { return this->nodesMap; } void Map::setStart(float x, float y) { for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { Node* node = this->nodesMap.at(i * width + j); if (node->getGlobalBounds().contains(x, y) && !node->isWall()) { if (this->startNode != nullptr) startNode->loadTexture("floor.png"); if (this->startNode == node) return; this->startNode = node; this->startNode->loadTexture("start.png"); } } } } void Map::setEnd(float x, float y) { for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { Node* node = this->nodesMap.at(i * width + j); if (node->getGlobalBounds().contains(x, y) && !node->isWall()) { if (this->endNode != nullptr) endNode->loadTexture("floor.png"); if (this->endNode == node) return; this->endNode = node; this->endNode->loadTexture("end.png"); } } } } Node* Map::getStartNode() { return this->startNode; } Node* Map::getEndNode() { return this->endNode; } Map::~Map() { for (std::vector<Node*>::iterator it = nodesMap.begin(); it != nodesMap.end(); ++it) { delete (*it); } nodesMap.clear(); }
16.083916
85
0.560435
[ "render", "vector" ]
182a3e186e744c6d9936086de2343d782bbd3230
813
hpp
C++
Typon/src/quote_loader.hpp
ihsuy/Typon
55aa2d82ed3aecf10b88891e5b962daf5944b6f3
[ "MIT" ]
65
2019-03-06T15:47:27.000Z
2022-03-05T09:14:29.000Z
Typon/src/quote_loader.hpp
ihsuy/Typon
55aa2d82ed3aecf10b88891e5b962daf5944b6f3
[ "MIT" ]
null
null
null
Typon/src/quote_loader.hpp
ihsuy/Typon
55aa2d82ed3aecf10b88891e5b962daf5944b6f3
[ "MIT" ]
5
2019-04-11T01:15:04.000Z
2021-11-21T18:57:47.000Z
#ifndef quote_loader_hpp #define quote_loader_hpp #include "tools.hpp" #include <fstream> #include <sstream> #include <vector> using namespace std; struct quote_loader { const string quote_relative_path = "/quotes/"; string quote_dir; const int ID_RANGE; // default read-in quote file format string quote_format = ".txt"; quote_loader(const int& id_range, const string& specified_quote_dir = ""); // get total number of quote files in my_path and load them to quote_order void load_quoteDatabase_info(vector<int>& quote_order, int& quoteDatabase_size, bool& isDemo); string load_quote(const int& id, const int& len = 0); void clear_trailing_spaces(string& quote); }; #endif /* quote_loader_hpp */
24.636364
78
0.665437
[ "vector" ]
182b657968c4745bbdf1aa007e33bbeb91106af6
48,553
cxx
C++
pandatool/src/egg-optchar/eggOptchar.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
pandatool/src/egg-optchar/eggOptchar.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
pandatool/src/egg-optchar/eggOptchar.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file eggOptchar.cxx * @author drose * @date 2003-07-18 */ #include "eggOptchar.h" #include "eggOptcharUserData.h" #include "vertexMembership.h" #include "eggJointData.h" #include "eggSliderData.h" #include "eggCharacterCollection.h" #include "eggCharacterData.h" #include "eggBackPointer.h" #include "eggGroupNode.h" #include "eggPrimitive.h" #include "eggVertexPool.h" #include "eggTable.h" #include "eggGroup.h" #include "eggAnimPreload.h" #include "string_utils.h" #include "dcast.h" #include "pset.h" #include "compose_matrix.h" #include "fftCompressor.h" #include <algorithm> using std::cout; using std::setw; using std::string; /** * */ EggOptchar:: EggOptchar() { add_path_replace_options(); add_path_store_options(); add_normals_options(); add_transform_options(); add_fixrest_option(); set_program_brief("optimizes character models and animations in .egg files"); set_program_description ("egg-optchar performs basic optimizations of a character model " "and its associated animations, primarily by analyzing the " "animation tables and removing unneeded joints and/or morphs. " "It can also perform basic restructuring operations on the " "character hierarchy."); add_option ("ls", "", 0, "List the joint hierarchy instead of performing any operations.", &EggOptchar::dispatch_none, &_list_hierarchy); add_option ("lsv", "", 0, "List the joint hierarchy along with an indication of the properties " "each joint.", &EggOptchar::dispatch_none, &_list_hierarchy_v); add_option ("lsp", "", 0, "List the existing joint hierarchy as a series of -p joint,parent " "commands, suitable for pasting into an egg-optchar command line.", &EggOptchar::dispatch_none, &_list_hierarchy_p); add_option ("keep", "joint[,joint...]", 0, "Keep the named joints (or sliders) in the character, even if they do " "not appear to be needed by the animation.", &EggOptchar::dispatch_vector_string_comma, nullptr, &_keep_components); add_option ("drop", "joint[,joint...]", 0, "Removes the named joints or sliders, even if they appear to be needed.", &EggOptchar::dispatch_vector_string_comma, nullptr, &_drop_components); add_option ("expose", "joint[,joint...]", 0, "Expose the named joints by flagging them with a DCS attribute, so " "each one can be found in the scene graph when the character is loaded, " "and objects can be parented to it. This implies -keep.", &EggOptchar::dispatch_vector_string_comma, nullptr, &_expose_components); add_option ("suppress", "joint[,joint...]", 0, "The opposite of suppress, this prevents the named joints from " "being created with an implicit DCS attribute, even if they contain " "rigid geometry. The default is to create an implicit node for any " "joint that contains rigid geometry, to take advantage of display " "list and/or vertex buffer caching. This does not imply -keep.", &EggOptchar::dispatch_vector_string_comma, nullptr, &_suppress_components); add_option ("flag", "node[,node...][=name]", 0, "Assign the indicated name to the geometry within the given nodes. " "This will make the geometry visible as a node in the resulting " "character model when it is loaded in the scene graph (normally, " "the node hierarchy is suppressed when loading characters). This " "is different from -expose in that it reveals geometry rather than " "joints; the revealed node can be hidden or its attributes changed " "at runtime, but it will be animated by its vertices, not the node, so " "objects parented to this node will not inherit its animation.", &EggOptchar::dispatch_flag_groups, nullptr, &_flag_groups); add_option ("defpose", "anim.egg,frame", 0, "Specify the model's default pose. The pose is taken " "from the indicated frame of the named animation file (which must " "also be named separately on the command line). The " "pose will be held by the model in " "the absence of any animation, and need not be the same " "pose in which the model was originally skinned.", &EggOptchar::dispatch_string, nullptr, &_defpose); add_option ("preload", "", 0, "Add an <AnimPreload> entry for each animation to the model file(s). " "This can be used at runtime to support asynchronous " "loading and binding of animation channels.", &EggOptchar::dispatch_none, &_preload); add_option ("zero", "joint[,hprxyzijkabc]", 0, "Zeroes out the animation channels for the named joint. If " "a subset of the component letters hprxyzijkabc is included, the " "operation is restricted to just those components; otherwise the " "entire transform is cleared.", &EggOptchar::dispatch_name_components, nullptr, &_zero_channels); add_option ("keepall", "", 0, "Keep all joints and sliders in the character, except those named " "explicitly by -drop.", &EggOptchar::dispatch_none, &_keep_all); add_option ("p", "joint,parent", 0, "Moves the named joint under the named parent joint. Use " "\"-p joint,\" to reparent a joint to the root. The joint transform " "is recomputed appropriately under its new parent so that the animation " "is not affected (the effect is similar to NodePath::wrt_reparent_to).", &EggOptchar::dispatch_vector_string_pair, nullptr, &_reparent_joints); add_option ("new", "joint,source", 0, "Creates a new joint under the named parent joint. The new " "joint will inherit the same net transform as its parent.", &EggOptchar::dispatch_vector_string_pair, nullptr, &_new_joints); add_option ("rename", "joint,newjoint", 0, "Renames the indicated joint, if present, to the given name.", &EggOptchar::dispatch_vector_string_pair, nullptr, &_rename_joints); if (FFTCompressor::is_compression_available()) { add_option ("optimal", "", 0, "Computes the optimal joint hierarchy for the character by analyzing " "all of the joint animation and reparenting joints to minimize " "transformations. This can repair skeletons that have been flattened " "or whose hierarchy was otherwise damaged in conversion; it can also " "detect joints that are constrained to follow other joints and should " "therefore be parented to the master joints. The result is a file " "from which more joints may be successfully removed, that generally " "compresses better and with fewer artifacts. However, this is a " "fairly expensive operation.", &EggOptchar::dispatch_none, &_optimal_hierarchy); } add_option ("q", "quantum", 0, "Quantize joint membership values to the given unit. This is " "the smallest significant change in joint membership. There can " "be a significant performance (and memory utilization) runtime " "benefit for eliminating small differences in joint memberships " "between neighboring vertices. The default is 0.01; specifying " "0 means to preserve the original values.", &EggOptchar::dispatch_double, nullptr, &_vref_quantum); add_option ("qa", "quantum[,hprxyzijkabc]", 0, "Quantizes animation channels to the given unit. This rounds each " "of the named components of all joints to the nearest multiple of unit. " "There is no performance benefit, and little compression benefit, " "for doing this; and this may introduce visible artifacts to the " "animation. However, sometimes it is a useful tool for animation " "analysis and comparison. This option may be repeated several times " "to quantize different channels by a different amount.", &EggOptchar::dispatch_double_components, nullptr, &_quantize_anims); add_option ("dart", "[default, sync, nosync, or structured]", 0, "change the dart value in the given eggs", &EggOptchar::dispatch_string, nullptr, &_dart_type); _optimal_hierarchy = false; _vref_quantum = 0.01; } /** * */ void EggOptchar:: run() { // We have to apply the user-specified reparent requests first, before we // even analyze the joints. This is because reparenting the joints may // change their properties. if (apply_user_reparents()) { nout << "Reparenting hierarchy.\n"; // So we'll have to call do_reparent() twice. It seems wasteful, but it // really is necessary, and it's not that bad. do_reparent(); } if (!_zero_channels.empty()) { zero_channels(); } int num_characters = _collection->get_num_characters(); int ci; // Now we can analyze the joints for their properties. for (ci = 0; ci < num_characters; ci++) { EggCharacterData *char_data = _collection->get_character(ci); analyze_joints(char_data->get_root_joint(), 0); analyze_sliders(char_data); } if (_list_hierarchy || _list_hierarchy_v) { for (ci = 0; ci < num_characters; ci++) { EggCharacterData *char_data = _collection->get_character(ci); nout << "Character: " << char_data->get_name() << "\n"; list_joints(char_data->get_root_joint(), 0, _list_hierarchy_v); list_scalars(char_data, _list_hierarchy_v); nout << char_data->get_num_joints() << " joints.\n"; } } else if (_list_hierarchy_p) { for (ci = 0; ci < num_characters; ci++) { EggCharacterData *char_data = _collection->get_character(ci); nout << "Character: " << char_data->get_name() << "\n"; int col = 0; list_joints_p(char_data->get_root_joint(), col); // A newline to cout is needed after the above call. cout << "\n"; nout << char_data->get_num_joints() << " joints.\n"; } } else { // The meat of the program: determine which joints are to be removed, and // then actually remove them. determine_removed_components(); move_vertices(); if (process_joints()) { do_reparent(); } // We currently do not implement optimizing morph sliders. Need to add // this at some point; it's quite easy. Identity and empty morph sliders // can simply be removed, while static sliders need to be applied to the // vertices and then removed. rename_joints(); // Quantize the vertex memberships. We call this even if _vref_quantum is // 0, because this also normalizes the vertex memberships. quantize_vertices(); // Also quantize the animation channels, if the user so requested. quantize_channels(); // flag all the groups as the user requested. if (!_flag_groups.empty()) { Eggs::iterator ei; for (ei = _eggs.begin(); ei != _eggs.end(); ++ei) { do_flag_groups(*ei); } } // Add the AnimPreload entries. if (_preload) { do_preload(); } // Finally, set the default poses. It's important not to do this until // after we have adjusted all of the transforms for the various joints. if (!_defpose.empty()) { do_defpose(); } if (!_dart_type.empty()) { Eggs::iterator ei; for (ei = _eggs.begin(); ei != _eggs.end(); ++ei) { change_dart_type(*ei, _dart_type); } } write_eggs(); } } /** * Does something with the additional arguments on the command line (after all * the -options have been parsed). Returns true if the arguments are good, * false otherwise. */ bool EggOptchar:: handle_args(ProgramBase::Args &args) { if (_list_hierarchy || _list_hierarchy_v || _list_hierarchy_p) { _read_only = true; } return EggCharacterFilter::handle_args(args); } /** * Standard dispatch function for an option that takes a pair of string * parameters. The data pointer is to StringPairs vector; the pair will be * pushed onto the end of the vector. */ bool EggOptchar:: dispatch_vector_string_pair(const string &opt, const string &arg, void *var) { StringPairs *ip = (StringPairs *)var; vector_string words; tokenize(arg, words, ","); if (words.size() == 2) { StringPair sp; sp._a = words[0]; sp._b = words[1]; ip->push_back(sp); } else { nout << "-" << opt << " requires a pair of strings separated by a comma.\n"; return false; } return true; } /** * Accepts a name optionally followed by a comma and some of the nine standard * component letters, * * The data pointer is to StringPairs vector; the pair will be pushed onto the * end of the vector. */ bool EggOptchar:: dispatch_name_components(const string &opt, const string &arg, void *var) { StringPairs *ip = (StringPairs *)var; vector_string words; tokenize(arg, words, ","); StringPair sp; if (words.size() == 1) { sp._a = words[0]; } else if (words.size() == 2) { sp._a = words[0]; sp._b = words[1]; } else { nout << "-" << opt << " requires a pair of strings separated by a comma.\n"; return false; } if (sp._b.empty()) { sp._b = matrix_component_letters; } else { for (string::const_iterator si = sp._b.begin(); si != sp._b.end(); ++si) { if (strchr(matrix_component_letters, *si) == nullptr) { nout << "Not a standard matrix component: \"" << *si << "\"\n" << "-" << opt << " requires a joint name followed by a set " << "of component names. The standard component names are \"" << matrix_component_letters << "\".\n"; return false; } } } ip->push_back(sp); return true; } /** * Accepts a double value optionally followed by a comma and some of the nine * standard component letters, * * The data pointer is to a DoubleStrings vector; the pair will be pushed onto * the end of the vector. */ bool EggOptchar:: dispatch_double_components(const string &opt, const string &arg, void *var) { DoubleStrings *ip = (DoubleStrings *)var; vector_string words; tokenize(arg, words, ","); bool valid_double = false; DoubleString sp; if (words.size() == 1) { valid_double = string_to_double(words[0], sp._a); } else if (words.size() == 2) { valid_double = string_to_double(words[0], sp._a); sp._b = words[1]; } else { nout << "-" << opt << " requires a numeric value followed by a string.\n"; return false; } if (!valid_double) { nout << "-" << opt << " requires a numeric value followed by a string.\n"; return false; } if (sp._b.empty()) { sp._b = matrix_component_letters; } else { for (string::const_iterator si = sp._b.begin(); si != sp._b.end(); ++si) { if (strchr(matrix_component_letters, *si) == nullptr) { nout << "Not a standard matrix component: \"" << *si << "\"\n" << "-" << opt << " requires a joint name followed by a set " << "of component names. The standard component names are \"" << matrix_component_letters << "\".\n"; return false; } } } ip->push_back(sp); return true; } /** * Accepts a set of comma-delimited group names followed by an optional name * separated with an equal sign. * * The data pointer is to a FlagGroups object. */ bool EggOptchar:: dispatch_flag_groups(const string &opt, const string &arg, void *var) { FlagGroups *ip = (FlagGroups *)var; vector_string words; tokenize(arg, words, ","); if (words.empty()) { nout << "-" << opt << " requires a series of words separated by a comma.\n"; return false; } FlagGroupsEntry entry; // Check for an equal sign in the last word. This marks the name to assign. string &last_word = words.back(); size_t equals = last_word.rfind('='); if (equals != string::npos) { entry._name = last_word.substr(equals + 1); last_word = last_word.substr(0, equals); } else { // If there's no equal sign, the default is to name all groups after the // group itself. We leave the name empty to indicate that. } // Convert the words to GlobPatterns. vector_string::const_iterator si; for (si = words.begin(); si != words.end(); ++si) { const string &word = (*si); entry._groups.push_back(GlobPattern(word)); } ip->push_back(entry); return true; } /** * Flag all joints and sliders that should be removed for optimization * purposes. */ void EggOptchar:: determine_removed_components() { typedef pset<string> Names; Names keep_names; Names drop_names; Names expose_names; Names suppress_names; Names names_used; vector_string::const_iterator si; for (si = _keep_components.begin(); si != _keep_components.end(); ++si) { keep_names.insert(*si); } for (si = _drop_components.begin(); si != _drop_components.end(); ++si) { drop_names.insert(*si); } for (si = _expose_components.begin(); si != _expose_components.end(); ++si) { keep_names.insert(*si); expose_names.insert(*si); } for (si = _suppress_components.begin(); si != _suppress_components.end(); ++si) { suppress_names.insert(*si); } // We always keep the root joint, which has no name. keep_names.insert(""); int num_characters = _collection->get_num_characters(); for (int ci = 0; ci < num_characters; ci++) { EggCharacterData *char_data = _collection->get_character(ci); int num_components = char_data->get_num_components(); nout << char_data->get_name() << " has " << num_components << " components.\n"; for (int i = 0; i < num_components; i++) { EggComponentData *comp_data = char_data->get_component(i); nassertv(comp_data != nullptr); EggOptcharUserData *user_data = DCAST(EggOptcharUserData, comp_data->get_user_data()); nassertv(user_data != nullptr); const string &name = comp_data->get_name(); if (suppress_names.find(name) != suppress_names.end()) { // If this component is not dropped, it will not be implicitly // exposed. names_used.insert(name); user_data->_flags |= EggOptcharUserData::F_suppress; } if (drop_names.find(name) != drop_names.end()) { // Remove this component by user request. names_used.insert(name); user_data->_flags |= EggOptcharUserData::F_remove; } else if (_keep_all || keep_names.find(name) != keep_names.end()) { // Keep this component. names_used.insert(name); if (expose_names.find(name) != expose_names.end()) { // In fact, expose it. user_data->_flags |= EggOptcharUserData::F_expose; } } else { // Remove this component if it's unanimated or empty. if ((user_data->_flags & (EggOptcharUserData::F_static | EggOptcharUserData::F_empty)) != 0) { if ((user_data->_flags & (EggOptcharUserData::F_top | EggOptcharUserData::F_empty)) == EggOptcharUserData::F_top) { // Actually, we can't remove it if it's a top joint, unless it's // also empty. That's because vertices that are partially // assigned to this joint would then have no joint to represent // the same partial assignment, and they would then appear to be // wholly assigned to their other joint, which would be incorrect. } else { // But joints that aren't top joints (or that are empty) are o.k. // to remove. user_data->_flags |= EggOptcharUserData::F_remove; } } } } } // Go back and tell the user about component names we didn't use, just to be // helpful. for (si = _keep_components.begin(); si != _keep_components.end(); ++si) { const string &name = (*si); if (names_used.find(name) == names_used.end()) { nout << "No such component: " << name << "\n"; } } for (si = _drop_components.begin(); si != _drop_components.end(); ++si) { const string &name = (*si); if (names_used.find(name) == names_used.end()) { nout << "No such component: " << name << "\n"; } } for (si = _expose_components.begin(); si != _expose_components.end(); ++si) { const string &name = (*si); if (names_used.find(name) == names_used.end()) { nout << "No such component: " << name << "\n"; } } for (si = _suppress_components.begin(); si != _suppress_components.end(); ++si) { const string &name = (*si); if (names_used.find(name) == names_used.end()) { nout << "No such component: " << name << "\n"; } } } /** * Moves the vertices from joints that are about to be removed into the first * suitable parent. This might result in fewer joints being removed (because * the parent might suddenly no longer be empty). */ void EggOptchar:: move_vertices() { int num_characters = _collection->get_num_characters(); for (int ci = 0; ci < num_characters; ci++) { EggCharacterData *char_data = _collection->get_character(ci); int num_joints = char_data->get_num_joints(); for (int i = 0; i < num_joints; i++) { EggJointData *joint_data = char_data->get_joint(i); EggOptcharUserData *user_data = DCAST(EggOptcharUserData, joint_data->get_user_data()); if ((user_data->_flags & EggOptcharUserData::F_empty) == 0 && (user_data->_flags & EggOptcharUserData::F_remove) != 0) { // This joint has vertices, but is scheduled to be removed; find a // suitable home for its vertices. EggJointData *best_joint = find_best_vertex_joint(joint_data->get_parent()); joint_data->move_vertices_to(best_joint); // Now we can't remove the joint. if (best_joint != nullptr) { EggOptcharUserData *best_user_data = DCAST(EggOptcharUserData, best_joint->get_user_data()); best_user_data->_flags &= ~(EggOptcharUserData::F_empty | EggOptcharUserData::F_remove); } } } } } /** * Effects the actual removal of joints flagged for removal by reparenting the * hierarchy appropriately. Returns true if any joints are removed, false * otherwise. */ bool EggOptchar:: process_joints() { bool removed_any = false; int num_characters = _collection->get_num_characters(); for (int ci = 0; ci < num_characters; ci++) { EggCharacterData *char_data = _collection->get_character(ci); int num_joints = char_data->get_num_joints(); int num_static = 0; int num_empty = 0; int num_identity = 0; int num_other = 0; int num_kept = 0; for (int i = 0; i < num_joints; i++) { EggJointData *joint_data = char_data->get_joint(i); EggOptcharUserData *user_data = DCAST(EggOptcharUserData, joint_data->get_user_data()); if ((user_data->_flags & EggOptcharUserData::F_remove) != 0) { // This joint will be removed, so reparent it to nothing. joint_data->reparent_to(nullptr); // Determine what kind of node it is we're removing, for the user's // information. if ((user_data->_flags & EggOptcharUserData::F_identity) != 0) { num_identity++; } else if ((user_data->_flags & EggOptcharUserData::F_static) != 0) { num_static++; } else if ((user_data->_flags & EggOptcharUserData::F_empty) != 0) { num_empty++; } else { num_other++; } removed_any = true; } else { // This joint will be preserved, but maybe its parent will change. EggJointData *best_parent = find_best_parent(joint_data->get_parent()); joint_data->reparent_to(best_parent); if ((user_data->_flags & EggOptcharUserData::F_expose) != 0) { joint_data->expose(); } else if ((user_data->_flags & EggOptcharUserData::F_suppress) != 0) { joint_data->expose(EggGroup::DC_none); } num_kept++; } } if (num_joints == num_kept) { nout << char_data->get_name() << ": keeping " << num_joints << " joints.\n"; } else { nout << setw(5) << num_joints << " original joints in " << char_data->get_name() << "\n"; if (num_identity != 0) { nout << setw(5) << num_identity << " identity joints\n"; } if (num_static != 0) { nout << setw(5) << num_static << " unanimated joints\n"; } if (num_empty != 0) { nout << setw(5) << num_empty << " empty joints\n"; } if (num_other != 0) { nout << setw(5) << num_other << " other joints\n"; } nout << " ----\n" << setw(5) << num_kept << " joints remaining\n\n"; } } return removed_any; } /** * Searches for the first joint at this level or above that is not scheduled * to be removed. This is the joint that the first child of this joint should * be reparented to. */ EggJointData *EggOptchar:: find_best_parent(EggJointData *joint_data) const { EggOptcharUserData *user_data = DCAST(EggOptcharUserData, joint_data->get_user_data()); if ((user_data->_flags & EggOptcharUserData::F_remove) != 0) { // Keep going. if (joint_data->get_parent() != nullptr) { return find_best_parent(joint_data->get_parent()); } } // This is the one! return joint_data; } /** * Searches for the first joint at this level or above that is not static. * This is the joint that the vertices of this joint should be moved into. */ EggJointData *EggOptchar:: find_best_vertex_joint(EggJointData *joint_data) const { if (joint_data == nullptr) { return nullptr; } EggOptcharUserData *user_data = DCAST(EggOptcharUserData, joint_data->get_user_data()); if ((user_data->_flags & EggOptcharUserData::F_static) != 0) { // Keep going. return find_best_vertex_joint(joint_data->get_parent()); } // This is the one! return joint_data; } /** * Reparents all the joints that the user suggested on the command line. * Returns true if any operations were performed, false otherwise. */ bool EggOptchar:: apply_user_reparents() { bool did_anything = false; int num_characters = _collection->get_num_characters(); // First, get the new joints. StringPairs::const_iterator spi; for (spi = _new_joints.begin(); spi != _new_joints.end(); ++spi) { const StringPair &p = (*spi); for (int ci = 0; ci < num_characters; ci++) { EggCharacterData *char_data = _collection->get_character(ci); EggJointData *node_a = char_data->find_joint(p._a); EggJointData *node_b = char_data->get_root_joint(); if (!p._b.empty()) { node_b = char_data->find_joint(p._b); } if (node_b == nullptr) { nout << "No joint named " << p._b << " in " << char_data->get_name() << ".\n"; } else if (node_a != nullptr) { nout << "Joint " << p._a << " already exists in " << char_data->get_name() << ".\n"; } else { nout << "Creating new joint " << p._a << " in " << char_data->get_name() << ".\n"; node_a = char_data->make_new_joint(p._a, node_b); did_anything = true; } } } // Now get the user reparents. for (spi = _reparent_joints.begin(); spi != _reparent_joints.end(); ++spi) { const StringPair &p = (*spi); for (int ci = 0; ci < num_characters; ci++) { EggCharacterData *char_data = _collection->get_character(ci); EggJointData *node_a = char_data->find_joint(p._a); EggJointData *node_b = char_data->get_root_joint(); if (!p._b.empty()) { node_b = char_data->find_joint(p._b); } if (node_b == nullptr) { nout << "No joint named " << p._b << " in " << char_data->get_name() << ".\n"; } else if (node_a == nullptr) { nout << "No joint named " << p._a << " in " << char_data->get_name() << ".\n"; } else { node_a->reparent_to(node_b); did_anything = true; } } } if (_optimal_hierarchy) { did_anything = true; for (int ci = 0; ci < num_characters; ci++) { EggCharacterData *char_data = _collection->get_character(ci); nout << "Computing optimal hierarchy for " << char_data->get_name() << ".\n"; char_data->choose_optimal_hierarchy(); nout << "Done computing optimal hierarchy for " << char_data->get_name() << ".\n"; } } return did_anything; } /** * Zeroes out the channels specified by the user on the command line. * * Returns true if any operation was performed, false otherwise. */ bool EggOptchar:: zero_channels() { bool did_anything = false; int num_characters = _collection->get_num_characters(); StringPairs::const_iterator spi; for (spi = _zero_channels.begin(); spi != _zero_channels.end(); ++spi) { const StringPair &p = (*spi); for (int ci = 0; ci < num_characters; ci++) { EggCharacterData *char_data = _collection->get_character(ci); EggJointData *joint_data = char_data->find_joint(p._a); if (joint_data == nullptr) { nout << "No joint named " << p._a << " in " << char_data->get_name() << ".\n"; } else { joint_data->zero_channels(p._b); did_anything = true; } } } return did_anything; } /** * Quantizes the channels specified by the user on the command line. * * Returns true if any operation was performed, false otherwise. */ bool EggOptchar:: quantize_channels() { bool did_anything = false; int num_characters = _collection->get_num_characters(); DoubleStrings::const_iterator spi; for (spi = _quantize_anims.begin(); spi != _quantize_anims.end(); ++spi) { const DoubleString &p = (*spi); for (int ci = 0; ci < num_characters; ci++) { EggCharacterData *char_data = _collection->get_character(ci); EggJointData *joint_data = char_data->get_root_joint(); if (joint_data != nullptr) { joint_data->quantize_channels(p._b, p._a); did_anything = true; } } } return did_anything; } /** * Recursively walks the joint hierarchy for a particular character, * indentifying properties of each joint. */ void EggOptchar:: analyze_joints(EggJointData *joint_data, int level) { PT(EggOptcharUserData) user_data = new EggOptcharUserData; joint_data->set_user_data(user_data); if (level == 1) { // The child joints of the root joint are deemed "top" joints. These may // not be removed unless they are empty (because their vertices have no // joint to be moved into). user_data->_flags |= EggOptcharUserData::F_top; } // Analyze the table of matrices for this joint, checking to see if they're // all the same across all frames, or if any of them are different; also // look for empty joints (that control no vertices). int num_mats = 0; bool different_mat = false; bool has_vertices = false; int num_models = joint_data->get_num_models(); int i; for (i = 0; i < num_models; i++) { if (joint_data->has_model(i)) { EggBackPointer *model = joint_data->get_model(i); if (model->has_vertices()) { has_vertices = true; } int num_frames = joint_data->get_num_frames(i); int f; for (f = 0; f < num_frames && !different_mat; f++) { LMatrix4d mat = joint_data->get_frame(i, f); num_mats++; if (num_mats == 1) { // This is the first matrix. user_data->_static_mat = mat; } else { // This is a second or later matrix. if (!mat.almost_equal(user_data->_static_mat, 0.0001)) { // It's different than the first one. different_mat = true; } } } } } if (!different_mat) { // All the mats are the same for this joint. user_data->_flags |= EggOptcharUserData::F_static; if (num_mats == 0 || user_data->_static_mat.almost_equal(LMatrix4d::ident_mat(), 0.0001)) { // It's not only static, but it's the identity matrix. user_data->_flags |= EggOptcharUserData::F_identity; } } if (!has_vertices) { // There are no vertices in this joint. user_data->_flags |= EggOptcharUserData::F_empty; } int num_children = joint_data->get_num_children(); for (i = 0; i < num_children; i++) { analyze_joints(joint_data->get_child(i), level + 1); } } /** * Linearly walks the slider list for a particular character, indentifying * properties of each slider. */ void EggOptchar:: analyze_sliders(EggCharacterData *char_data) { int num_sliders = char_data->get_num_sliders(); for (int si = 0; si < num_sliders; si++) { EggSliderData *slider_data = char_data->get_slider(si); PT(EggOptcharUserData) user_data = new EggOptcharUserData; slider_data->set_user_data(user_data); // Analyze the table of values for this slider, checking to see if they're // all the same across all frames, or if any of them are different; also // look for empty sliders (that control no vertices). int num_values = 0; bool different_value = false; bool has_vertices = false; int num_models = slider_data->get_num_models(); for (int i = 0; i < num_models; i++) { if (slider_data->has_model(i)) { EggBackPointer *model = slider_data->get_model(i); if (model->has_vertices()) { has_vertices = true; } int num_frames = slider_data->get_num_frames(i); int f; for (f = 0; f < num_frames && !different_value; f++) { double value = slider_data->get_frame(i, f); num_values++; if (num_values == 1) { // This is the first value. user_data->_static_value = value; } else { // This is a second or later value. if (!IS_THRESHOLD_EQUAL(value, user_data->_static_value, 0.0001)) { // It's different than the first one. different_value = true; } } } } } if (!different_value) { // All the values are the same for this slider. user_data->_flags |= EggOptcharUserData::F_static; if (num_values == 0 || IS_THRESHOLD_ZERO(user_data->_static_value, 0.0001)) { // It's not only static, but it's the identity value. user_data->_flags |= EggOptcharUserData::F_identity; } } if (!has_vertices) { // There are no vertices in this slider. user_data->_flags |= EggOptcharUserData::F_empty; } } } /** * Outputs a list of the joint hierarchy. */ void EggOptchar:: list_joints(EggJointData *joint_data, int indent_level, bool verbose) { // Don't list the root joint, which is artificially created when the // character is loaded. Instead, list each child as it is encountered. int num_children = joint_data->get_num_children(); for (int i = 0; i < num_children; i++) { EggJointData *child_data = joint_data->get_child(i); describe_component(child_data, indent_level, verbose); list_joints(child_data, indent_level + 2, verbose); } } /** * Outputs a list of the joint hierarchy as a series of -p joint,parent * commands. */ void EggOptchar:: list_joints_p(EggJointData *joint_data, int &col) { // As above, don't list the root joint. int num_children = joint_data->get_num_children(); static const int max_col = 72; for (int i = 0; i < num_children; i++) { EggJointData *child_data = joint_data->get_child(i); // We send output to cout instead of nout to avoid the word-wrapping, and // also to allow the user to redirect this easily to a file. string text = string(" -p ") + child_data->get_name() + string(",") + joint_data->get_name(); if (col == 0) { cout << " " << text; col = 4 + text.length(); } else { col += text.length(); if (col >= max_col) { cout << " \\\n " << text; col = 4 + text.length(); } else { cout << text; } } list_joints_p(child_data, col); } } /** * Outputs a list of the scalars. */ void EggOptchar:: list_scalars(EggCharacterData *char_data, bool verbose) { int num_sliders = char_data->get_num_sliders(); for (int si = 0; si < num_sliders; si++) { EggSliderData *slider_data = char_data->get_slider(si); describe_component(slider_data, 0, verbose); } } /** * Describes one particular slider or joint. */ void EggOptchar:: describe_component(EggComponentData *comp_data, int indent_level, bool verbose) { // We use cout instead of nout so the user can easily redirect this to a // file. indent(cout, indent_level) << comp_data->get_name(); if (verbose) { EggOptcharUserData *user_data = DCAST(EggOptcharUserData, comp_data->get_user_data()); if (user_data->is_identity()) { cout << " (identity)"; } else if (user_data->is_static()) { cout << " (static)"; } if (user_data->is_empty()) { cout << " (empty)"; } if (user_data->is_top()) { cout << " (top)"; } } cout << "\n"; } /** * Performs all of the queued up reparenting operations. */ void EggOptchar:: do_reparent() { bool all_ok = true; int num_characters = _collection->get_num_characters(); for (int ci = 0; ci < num_characters; ci++) { EggCharacterData *char_data = _collection->get_character(ci); if (!char_data->do_reparent()) { all_ok = false; } } if (!all_ok) { exit(1); } } /** * Walks through all of the loaded egg files, looking for vertices whose joint * memberships are then quantized according to _vref_quantum. */ void EggOptchar:: quantize_vertices() { Eggs::iterator ei; for (ei = _eggs.begin(); ei != _eggs.end(); ++ei) { quantize_vertices(*ei); } } /** * Recursively walks through the indicated egg hierarchy, looking for vertices * whose joint memberships are then quantized according to _vref_quantum. */ void EggOptchar:: quantize_vertices(EggNode *egg_node) { if (egg_node->is_of_type(EggVertexPool::get_class_type())) { EggVertexPool *vpool = DCAST(EggVertexPool, egg_node); EggVertexPool::iterator vi; for (vi = vpool->begin(); vi != vpool->end(); ++vi) { quantize_vertex(*vi); } } else if (egg_node->is_of_type(EggGroupNode::get_class_type())) { EggGroupNode *group = DCAST(EggGroupNode, egg_node); EggGroupNode::iterator ci; for (ci = group->begin(); ci != group->end(); ++ci) { quantize_vertices(*ci); } } } /** * Quantizes the indicated vertex's joint membership. */ void EggOptchar:: quantize_vertex(EggVertex *egg_vertex) { if (egg_vertex->gref_size() == 0) { // Never mind on this vertex. return; } // First, get a copy of the existing membership. VertexMemberships memberships; EggVertex::GroupRef::const_iterator gi; double net_membership = 0.0; for (gi = egg_vertex->gref_begin(); gi != egg_vertex->gref_end(); ++gi) { EggGroup *group = (*gi); double membership = group->get_vertex_membership(egg_vertex); memberships.push_back(VertexMembership(group, membership)); net_membership += membership; } nassertv(net_membership != 0.0); // Now normalize all the memberships so the net membership is 1.0, and then // quantize the result (if the user so requested). double factor = 1.0 / net_membership; net_membership = 0.0; VertexMemberships::iterator mi; VertexMemberships::iterator largest = memberships.begin(); for (mi = memberships.begin(); mi != memberships.end(); ++mi) { if ((*largest) < (*mi)) { // Remember the largest membership value, so we can readjust it at the // end. largest = mi; } double value = (*mi)._membership * factor; if (_vref_quantum != 0.0) { value = floor(value / _vref_quantum + 0.5) * _vref_quantum; } (*mi)._membership = value; net_membership += value; } // The the largest membership value gets corrected again by the roundoff // error. (*largest)._membership += 1.0 - net_membership; // Finally, walk back through and apply these computed values to the vertex. for (mi = memberships.begin(); mi != memberships.end(); ++mi) { (*mi)._group->set_vertex_membership(egg_vertex, (*mi)._membership); } } /** * Recursively walks the indicated egg hierarchy, looking for groups that * match one of the group names in _flag_groups, and renaming geometry * appropriately. */ void EggOptchar:: do_flag_groups(EggGroupNode *egg_group) { bool matched = false; string name; FlagGroups::const_iterator fi; for (fi = _flag_groups.begin(); fi != _flag_groups.end() && !matched; ++fi) { const FlagGroupsEntry &entry = (*fi); Globs::const_iterator si; for (si = entry._groups.begin(); si != entry._groups.end() && !matched; ++si) { if ((*si).matches(egg_group->get_name())) { matched = true; if (!entry._name.empty()) { name = entry._name; } else { name = egg_group->get_name(); } } } } if (matched) { // Ok, this group matched one of the user's command-line renames. Rename // all the primitives in this group and below to the indicated name; this // will expose the primitives through the character loader. rename_primitives(egg_group, name); } // Now recurse on children. EggGroupNode::iterator gi; for (gi = egg_group->begin(); gi != egg_group->end(); ++gi) { EggNode *child = (*gi); if (child->is_of_type(EggGroupNode::get_class_type())) { EggGroupNode *group = DCAST(EggGroupNode, child); do_flag_groups(group); } } } /** * Rename all the joints named with the -rename command-line option. */ void EggOptchar:: rename_joints() { for (StringPairs::iterator spi = _rename_joints.begin(); spi != _rename_joints.end(); ++spi) { const StringPair &sp = (*spi); int num_characters = _collection->get_num_characters(); int ci; for (ci = 0; ci < num_characters; ++ci) { EggCharacterData *char_data = _collection->get_character(ci); EggJointData *joint = char_data->find_joint(sp._a); if (joint != nullptr) { nout << "Renaming joint " << sp._a << " to " << sp._b << "\n"; joint->set_name(sp._b); int num_models = joint->get_num_models(); for (int mn = 0; mn < num_models; ++mn) { if (joint->has_model(mn)) { EggBackPointer *model = joint->get_model(mn); model->set_name(sp._b); } } } else { nout << "Couldn't find joint " << sp._a << "\n"; } } } } /** * Recursively walks the indicated egg hierarchy, renaming geometry to the * indicated name. */ void EggOptchar:: change_dart_type(EggGroupNode *egg_group, const string &new_dart_type) { EggGroupNode::iterator gi; for (gi = egg_group->begin(); gi != egg_group->end(); ++gi) { EggNode *child = (*gi); if (child->is_of_type(EggGroupNode::get_class_type())) { EggGroupNode *group = DCAST(EggGroupNode, child); if (child->is_of_type(EggGroup::get_class_type())) { EggGroup *gr = DCAST(EggGroup, child); EggGroup::DartType dt = gr->get_dart_type(); if(dt != EggGroup::DT_none) { EggGroup::DartType newDt = gr->string_dart_type(new_dart_type); gr->set_dart_type(newDt); } } change_dart_type(group, new_dart_type); } } } /** * Recursively walks the indicated egg hierarchy, renaming geometry to the * indicated name. */ void EggOptchar:: rename_primitives(EggGroupNode *egg_group, const string &name) { EggGroupNode::iterator gi; for (gi = egg_group->begin(); gi != egg_group->end(); ++gi) { EggNode *child = (*gi); if (child->is_of_type(EggGroupNode::get_class_type())) { EggGroupNode *group = DCAST(EggGroupNode, child); rename_primitives(group, name); } else if (child->is_of_type(EggPrimitive::get_class_type())) { child->set_name(name); } } } /** * Generates the preload tables for each model. */ void EggOptchar:: do_preload() { // First, build up the list of AnimPreload entries, one for each animation // file. PT(EggGroup) anim_group = new EggGroup("preload"); int num_characters = _collection->get_num_characters(); int ci; for (ci = 0; ci < num_characters; ++ci) { EggCharacterData *char_data = _collection->get_character(ci); int num_models = char_data->get_num_models(); for (int mn = 0; mn < num_models; ++mn) { EggNode *root = char_data->get_model_root(mn); if (root->is_of_type(EggTable::get_class_type())) { // This model represents an animation. EggData *data = char_data->get_egg_data(mn); string basename = data->get_egg_filename().get_basename_wo_extension(); PT(EggAnimPreload) anim_preload = new EggAnimPreload(basename); int mi = char_data->get_model_index(mn); anim_preload->set_num_frames(char_data->get_num_frames(mi)); double frame_rate = char_data->get_frame_rate(mi); if (frame_rate != 0.0) { anim_preload->set_fps(frame_rate); } anim_group->add_child(anim_preload); } } } // Now go back through and copy the preload tables into each of the model // files. for (ci = 0; ci < num_characters; ++ci) { EggCharacterData *char_data = _collection->get_character(ci); int num_models = char_data->get_num_models(); for (int mn = 0; mn < num_models; ++mn) { EggNode *root = char_data->get_model_root(mn); if (root->is_of_type(EggGroup::get_class_type())) { // This is a model file. Copy in the table. EggGroup *model_root = DCAST(EggGroup, root); EggGroup::const_iterator ci; for (ci = anim_group->begin(); ci != anim_group->end(); ++ci) { EggAnimPreload *anim_preload = DCAST(EggAnimPreload, *ci); PT(EggAnimPreload) new_anim_preload = new EggAnimPreload(*anim_preload); model_root->add_child(new_anim_preload); } } } } } /** * Sets the initial pose for the character(s). */ void EggOptchar:: do_defpose() { // Split out the defpose parameter. Filename egg_filename; size_t comma = _defpose.find(','); egg_filename = _defpose.substr(0, comma); string frame_str; if (comma != string::npos) { frame_str = _defpose.substr(comma + 1); } frame_str = trim(frame_str); int frame = 0; if (!frame_str.empty()) { if (!string_to_int(frame_str, frame)) { nout << "Invalid integer in -defpose: " << frame_str << "\n"; return; } } // Now find the named animation file in our egg list. int egg_index = -1; int num_eggs = _collection->get_num_eggs(); int i; // First, look for an exact match. for (i = 0; i < num_eggs && egg_index == -1; ++i) { if (_collection->get_egg(i)->get_egg_filename() == egg_filename) { egg_index = i; } } // Then, look for an inexact match. string egg_basename = egg_filename.get_basename_wo_extension(); for (i = 0; i < num_eggs && egg_index == -1; ++i) { if (_collection->get_egg(i)->get_egg_filename().get_basename_wo_extension() == egg_basename) { egg_index = i; } } if (egg_index == -1) { // No joy. nout << "Egg file " << egg_filename << " named in -defpose, but does not appear on command line.\n"; return; } EggData *egg_data = _collection->get_egg(egg_index); if (_collection->get_num_models(egg_index) == 0) { nout << "Egg file " << egg_filename << " does not include any model or animation.\n"; return; } // Now get the first model (or animation) named by this egg file. int mi = _collection->get_first_model_index(egg_index); EggCharacterData *ch = _collection->get_character_by_model_index(mi); EggJointData *root_joint = ch->get_root_joint(); int anim_index = -1; for (i = 0; i < ch->get_num_models() && anim_index == -1; ++i) { if (ch->get_egg_data(i) == egg_data) { anim_index = i; } } // This couldn't possibly fail, since we already checked this above. nassertv(anim_index != -1); // Now we can recursively apply the default pose to the hierarchy. root_joint->apply_default_pose(anim_index, frame); } int main(int argc, char *argv[]) { EggOptchar prog; prog.parse_command_line(argc, argv); prog.run(); return 0; }
31.879842
125
0.640681
[ "geometry", "object", "vector", "model", "transform", "3d" ]
18378bea7aa503736985e97ef99d48b848984464
2,471
cpp
C++
eip/src/v3/model/DisassociatePublicipsRequest.cpp
huaweicloud/huaweicloud-sdk-cpp-v3
d3b5e07b0ee8367d1c7f6dad17be0212166d959c
[ "Apache-2.0" ]
5
2021-03-03T08:23:43.000Z
2022-02-16T02:16:39.000Z
eip/src/v3/model/DisassociatePublicipsRequest.cpp
ChenwxJay/huaweicloud-sdk-cpp-v3
f821ec6d269b50203e0c1638571ee1349c503c41
[ "Apache-2.0" ]
null
null
null
eip/src/v3/model/DisassociatePublicipsRequest.cpp
ChenwxJay/huaweicloud-sdk-cpp-v3
f821ec6d269b50203e0c1638571ee1349c503c41
[ "Apache-2.0" ]
7
2021-02-26T13:53:35.000Z
2022-03-18T02:36:43.000Z
#include "huaweicloud/eip/v3/model/DisassociatePublicipsRequest.h" namespace HuaweiCloud { namespace Sdk { namespace Eip { namespace V3 { namespace Model { DisassociatePublicipsRequest::DisassociatePublicipsRequest() { publicipId_ = ""; publicipIdIsSet_ = false; bodyIsSet_ = false; } DisassociatePublicipsRequest::~DisassociatePublicipsRequest() = default; void DisassociatePublicipsRequest::validate() { } web::json::value DisassociatePublicipsRequest::toJson() const { web::json::value val = web::json::value::object(); if(publicipIdIsSet_) { val[utility::conversions::to_string_t("publicip_id")] = ModelBase::toJson(publicipId_); } if(bodyIsSet_) { val[utility::conversions::to_string_t("body")] = ModelBase::toJson(body_); } return val; } bool DisassociatePublicipsRequest::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("publicip_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("publicip_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setPublicipId(refVal); } } if(val.has_field(utility::conversions::to_string_t("body"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("body")); if(!fieldValue.is_null()) { DisassociatePublicipsRequestBody refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setBody(refVal); } } return ok; } std::string DisassociatePublicipsRequest::getPublicipId() const { return publicipId_; } void DisassociatePublicipsRequest::setPublicipId(const std::string& value) { publicipId_ = value; publicipIdIsSet_ = true; } bool DisassociatePublicipsRequest::publicipIdIsSet() const { return publicipIdIsSet_; } void DisassociatePublicipsRequest::unsetpublicipId() { publicipIdIsSet_ = false; } DisassociatePublicipsRequestBody DisassociatePublicipsRequest::getBody() const { return body_; } void DisassociatePublicipsRequest::setBody(const DisassociatePublicipsRequestBody& value) { body_ = value; bodyIsSet_ = true; } bool DisassociatePublicipsRequest::bodyIsSet() const { return bodyIsSet_; } void DisassociatePublicipsRequest::unsetbody() { bodyIsSet_ = false; } } } } } }
21.301724
102
0.691623
[ "object", "model" ]
183c537e42360f3f78bdeb0656dbc4ace9f23bbb
3,659
cpp
C++
Services/quiz.cpp
AStepaniuk/GasTraining
c831a224f4c6f70b98a1bff2c94b36685ed932bb
[ "MIT" ]
null
null
null
Services/quiz.cpp
AStepaniuk/GasTraining
c831a224f4c6f70b98a1bff2c94b36685ed932bb
[ "MIT" ]
null
null
null
Services/quiz.cpp
AStepaniuk/GasTraining
c831a224f4c6f70b98a1bff2c94b36685ed932bb
[ "MIT" ]
null
null
null
#include "quiz.h" #include <algorithm> #include "turngeometry.h" #include "randomgenerator.h" namespace QuizImpl { bool arePipesEqual(const Pipeline* pipeline1, const Pipeline* pipeline2) { if (pipeline1 == pipeline2) { return true; } if (pipeline1->pressure != pipeline2->pressure) { return false; } return true; } bool areSectionsEqual(const PipeSection* section1, const PipeSection* section2) { if (section1 == section2) { return true; } if (!arePipesEqual(section1->pipeline, section2->pipeline)) { return false; } if (section1->material != section2->material) { return false; } if (section1->diameter != section2->diameter) { return false; } return true; } bool areNodesEqual(const Node* node1, const Node* node2) { if (node1 == node2) { return true; } if (!areSectionsEqual(node1->section, node2->section)) { return false; } if (node1->type != node2->type) { return false; } if (node1->type == NodeType::Turn) { const auto geometry1 = TurnGeometry::Calculate(*node1); const auto geometry2 = TurnGeometry::Calculate(*node2); if (geometry1.picketTurnAngle != geometry2.picketTurnAngle) { return false; } int angleMin1 = geometry1.picketAngle1 < geometry1.picketAngle2 ? geometry1.picketAngle1 : geometry1.picketAngle2; int angleMin2 = geometry2.picketAngle1 < geometry2.picketAngle2 ? geometry2.picketAngle1 : geometry2.picketAngle2; if (angleMin1 != angleMin2) { return false; } } return true; } bool arePicketsEqual(const Picket& picket1, const Picket& picket2) { const auto node1 = picket1.node; const auto node2 = picket2.node; return areNodesEqual(node1, node2); } } using namespace QuizImpl; Quiz::Quiz(Model* model, QObject *parent) : QObject(parent) , model { model } { } void Quiz::Start() { unplayed.clear(); for (int i = 0; i < model->getPickets().size(); ++i) { unplayed.push_back(i); } activePicket = getNextActivePicket(); emit activePicketChanged(activePicket); } void Quiz::checkGuess(size_t guess) { if (activePicket < 0) { return; } const auto& actualPicket = model->getPickets()[activePicket]; const auto& guessedPicket = model->getPickets()[guess]; if (arePicketsEqual(actualPicket, guessedPicket)) { emit guessSucceeded(activePicket, guess); } else { emit guessFailed(activePicket, guess); } activePicket = getNextActivePicket(); if (activePicket >= 0) { emit activePicketChanged(activePicket); } else { emit quizEnd(); } } int Quiz::getNextActivePicket() { if (!unplayed.empty()) { const auto next = RandomGenerator::Get(unplayed.size()-1); const auto res = unplayed[next]; unplayed.erase(unplayed.begin() + next); return res; } else { return -1; } }
21.397661
84
0.520087
[ "model" ]
18419a00a20c3bcdc04123e8858e3a5c9ecd4fd7
1,633
cpp
C++
unit_tests/wind_energy/actuator/test_disk_functions.cpp
alhs6577/amr-wind
8dea2fbab479a2c75d54c9b0b1e04021a1da7d21
[ "BSD-3-Clause" ]
null
null
null
unit_tests/wind_energy/actuator/test_disk_functions.cpp
alhs6577/amr-wind
8dea2fbab479a2c75d54c9b0b1e04021a1da7d21
[ "BSD-3-Clause" ]
null
null
null
unit_tests/wind_energy/actuator/test_disk_functions.cpp
alhs6577/amr-wind
8dea2fbab479a2c75d54c9b0b1e04021a1da7d21
[ "BSD-3-Clause" ]
null
null
null
#include "gtest/gtest.h" #include "amr-wind/wind_energy/actuator/disk/disk_ops.H" namespace amr_wind { namespace actuator { namespace disk { class TestComputeDiskPoints : public ::testing::TestWithParam<vs::Vector> {}; TEST_P(TestComputeDiskPoints, disk_translation_x_aligned) { DiskBaseData data; data.center = GetParam(); data.normal_vec = {1.0, 0.0, 0.0}; data.num_vel_pts_r = 2; data.num_vel_pts_t = 2; data.diameter = 2.0; const amrex::Real dr = data.diameter * 0.5 / data.num_vel_pts_r; VecList points(4); VecList gold_points(4); const amrex::Real eps = 3.0 * vs::DTraits<amrex::Real>::eps(); gold_points[0] = vs::Vector{0.0, 0.5 * dr, 0.0} + data.center; gold_points[1] = vs::Vector{0.0, -0.5 * dr, 0.0} + data.center; gold_points[2] = vs::Vector{0.0, 1.5 * dr, 0.0} + data.center; gold_points[3] = vs::Vector{0.0, -1.5 * dr, 0.0} + data.center; ops::base::compute_disk_points(data, points, data.normal_vec, 0, 0); for (int i = 0; i < points.size(); ++i) { EXPECT_NEAR(gold_points[i].x(), points[i].x(), eps); EXPECT_NEAR(gold_points[i].y(), points[i].y(), eps); EXPECT_NEAR(gold_points[i].z(), points[i].z(), eps); } } INSTANTIATE_TEST_SUITE_P( ChangeCenters, TestComputeDiskPoints, testing::Values( vs::Vector{0, 0, 0}, vs::Vector{1, 0, 0}, vs::Vector{0, 1, 0}, vs::Vector{0, 0, 1}, vs::Vector{1, 1, 1}, vs::Vector{-1, 0, 0}, vs::Vector{-1, -1, -1}, vs::Vector{1000.0, 30.0, 5.0})); } // namespace disk } // namespace actuator } // namespace amr_wind
32.019608
73
0.606246
[ "vector" ]
18484cacb5010bfe91ded71b19e0bc35a99d5e9e
512
cpp
C++
boboleetcode/Play-Leetcode-master/0509-Fibonacci-Number/cpp-0509/main2.cpp
yaominzh/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
2
2021-03-25T05:26:55.000Z
2021-04-20T03:33:24.000Z
boboleetcode/Play-Leetcode-master/0509-Fibonacci-Number/cpp-0509/main2.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
6
2019-12-04T06:08:32.000Z
2021-05-10T20:22:47.000Z
boboleetcode/Play-Leetcode-master/0509-Fibonacci-Number/cpp-0509/main2.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
null
null
null
/// Source : https://leetcode.com/problems/fibonacci-number/ /// Author : liuyubobobo /// Time : 2019-01-09 #include <iostream> #include <vector> using namespace std; /// Dynamic Programming /// Time Complexity: O(n) /// Space Complexity: O(n) class Solution { public: int fib(int N) { vector<int> dp(N + 1, -1); dp[0] = 0; dp[1] = 1; for(int i = 2; i <= N; i ++) dp[i] = dp[i - 1] + dp[i - 2]; return dp[N]; } }; int main() { return 0; }
16.516129
60
0.519531
[ "vector" ]
184ce318db4251e73e7eacdd08a4f5a65be4b42d
6,711
hpp
C++
src/PluginHDF5/HDFImporter.hpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
4
2016-06-03T18:41:43.000Z
2020-04-17T20:28:58.000Z
src/PluginHDF5/HDFImporter.hpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
null
null
null
src/PluginHDF5/HDFImporter.hpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
null
null
null
/* * Copyright (c) 2014-2022 The Voxie 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. */ #pragma once #include <VoxieBackend/Data/TomographyRawData2DAccessor.hpp> #include <PluginHDF5/CT/DataFiles.hpp> #include <PluginHDF5/CT/rawdatafiles.hpp> #include <PluginHDF5/CT/typefiles.hpp> #include <VoxieClient/Exception.hpp> #include <VoxieBackend/IO/Operation.hpp> #include <VoxieBackend/Data/VolumeDataVoxel.hpp> #include <QtCore/QFile> #include <QtCore/QFileInfo> #include <QtWidgets/QBoxLayout> #include <QtWidgets/QDialog> #include <QtWidgets/QLabel> #include <QtWidgets/QPushButton> #include <QtWidgets/QSpinBox> #include <QtWidgets/QTreeWidget> #include <QtWidgets/QTreeWidgetItemIterator> #include <hdf5.h> #include <VoxieBackend/IO/Importer.hpp> using namespace vx; class #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 7 // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80947 // https://stackoverflow.com/questions/44390898/gcc-6-x-warning-about-lambda-visibility // Needed on Debian stretch / gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516 // Not needed on Ubuntu bionic / gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0 __attribute__((visibility("default"))) #endif HDFImporter : public vx::io::Importer { Q_OBJECT Q_DISABLE_COPY(HDFImporter) public: static QVector3D toQVector(Math::Vector3<double> vec) { return QVector3D(vec.x(), vec.y(), vec.z()); } static QVector3D toQVector(Math::DiagMatrix3<double> vec) { return QVector3D(vec.m11(), vec.m22(), vec.m33()); } static DataType convertHDF5TypeToDataType(HDF5::DataType type); private: // Can throw arbitrary exceptions static QSharedPointer<Data> loadVoxelData( const HDF5::File& file, const QSharedPointer<vx::io::Operation>& op); // Can throw arbitrary exceptions static QSharedPointer<Data> loadRawData( const HDF5::File& file, const QSharedPointer<vx::io::Operation>& op); template <class Type> static QSharedPointer<VolumeDataVoxel> createGenericVolume( HDF5::File file, DataType typeToUse, const QSharedPointer<vx::io::Operation>& op) { QSharedPointer<VolumeDataVoxel> voxelData; std::shared_ptr<VolumeGen<Type, true>> volume = HDF5::matlabDeserialize<VolumeGen<Type, true>>(file); Math::Vector3<size_t> size = getSize(*volume); // create and fill the voxel data object voxelData = VolumeDataVoxel::createVolume(size.x(), size.y(), size.z(), typeToUse); voxelData->performInGenericContext([&](auto& data) { size_t shape[3] = {size.x(), size.y(), size.z()}; ptrdiff_t stridesBytes[3] = { (ptrdiff_t)(sizeof(Type)), (ptrdiff_t)(size.x() * sizeof(Type)), (ptrdiff_t)(size.x() * size.y() * sizeof(Type))}; Math::ArrayView<Type, 3> view((Type*)data.getData(), shape, stridesBytes); /*should be float even if half or integer type is used for volume data*/ loadAndTransformTo<Type>(*volume, view, [op](size_t pos, size_t count) { op->throwIfCancelled(); op->updateProgress(1.0 * pos / count); }); // read meta data if (volume->GridOrigin) voxelData->setOrigin(toQVector(*volume->GridOrigin)); else voxelData->setOrigin(QVector3D(0, 0, 0)); if (volume->GridSpacing) voxelData->setSpacing(toQVector(*volume->GridSpacing)); else voxelData->setSpacing(QVector3D(1, 1, 1)); }); return voxelData; } public: explicit HDFImporter(); ~HDFImporter(); QSharedPointer<vx::OperationResultImport> import( const QString& fileName, bool doCreateNode, const QMap<QString, QVariant>& properties) override; }; class TomographyRawData2DAccessorHDF5 : public TomographyRawData2DAccessor { Q_OBJECT REFCOUNTEDOBJ_DECL(TomographyRawData2DAccessorHDF5) HDF5::File file; std::shared_ptr<RawGen<float, true>> raw; uint64_t numberOfImages_; QJsonObject metadata_; QList<QJsonObject> availableImageKinds_; QList<QString> availableStreams_; QList<QString> availableGeometryTypes_; vx::VectorSizeT2 imageSize_; std::vector<double> angles; QMap<uint64_t, QJsonObject> perImageMetadata_; TomographyRawData2DAccessorHDF5(const HDF5::File& file); virtual ~TomographyRawData2DAccessorHDF5(); // Allow the ctor to be called using create() friend class vx::RefCountedObject; public: uint64_t numberOfImages(const QString& stream) override; QJsonObject metadata() const override { return metadata_; } QList<QJsonObject> availableImageKinds() const override { return availableImageKinds_; } QList<QString> availableStreams() override { return availableStreams_; } bool hasStream(const QString& stream) override { return stream == ""; } QList<QString> availableGeometryTypes() override { return availableGeometryTypes_; } vx::VectorSizeT2 imageSize(const QString& stream, uint64_t id) override; QJsonObject getPerImageMetadata(const QString& stream, uint64_t id) override; QJsonObject getGeometryData(const QString& geometryType) override; QString readImages(const QJsonObject& imageKind, const QList<std::tuple<QString, quint64>>& images, const std::tuple<quint64, quint64>& inputRegionStart, const QSharedPointer<TomographyRawData2DRegular>& output, qulonglong firstOutputImageId, const std::tuple<quint64, quint64>& outputRegionStart, const std::tuple<quint64, quint64>& regionSize, bool allowIncompleteData = false) override; QList<QSharedPointer<SharedMemory>> getSharedMemorySections() override; };
37.283333
91
0.717479
[ "object", "shape", "vector" ]
4c7b575790a37cd3d5eff5d8a4febafb783f65c5
5,218
cpp
C++
RegExMove.cpp
IanEmmons/CmdLineUtil
bd20d59d4d9fcc0d7d82a3031106d56ad10aad16
[ "BSD-3-Clause" ]
null
null
null
RegExMove.cpp
IanEmmons/CmdLineUtil
bd20d59d4d9fcc0d7d82a3031106d56ad10aad16
[ "BSD-3-Clause" ]
null
null
null
RegExMove.cpp
IanEmmons/CmdLineUtil
bd20d59d4d9fcc0d7d82a3031106d56ad10aad16
[ "BSD-3-Clause" ]
null
null
null
#include "RegExMove.h" #include "main.h" #include <boost/algorithm/string/predicate.hpp> #include <boost/format.hpp> #include <vector> namespace b = ::boost; namespace balg = ::boost::algorithm; namespace fs = ::std::filesystem; using ::std::cout; using ::std::endl; using ::std::ostream; using ::std::regex; using ::std::regex_error; using ::std::string; using ::std::vector; #if !defined(CMDLINEUTIL_TEST_MODE) int main(int argCount, const char*const*const argList) { return commonMain<RegExMove>(argCount, argList); } #endif int RegExMove::usage(ostream& out, const string& progName, const char* pMsg) { int exitCode = EXIT_SUCCESS; if (pMsg != nullptr && *pMsg != '\0') { exitCode = EXIT_FAILURE; out << endl << pMsg << endl; } out << "\n" "Usage: " << progName << " [-i] [-d] [-dd] [-r] [-v] [-y] <rootdir> <regex> <replacement>\n" "\n" "Renames a collection of files using a regular expression search-and-replace.\n" "Uses ECMAScript regular expression syntax.\n" "\n" " -i Perform a case-insensitive search.\n" "\n" " -d Rename directories as well as files.\n" "\n" " -dd Rename only directories.\n" "\n" " -r Search recursively within subdirectories of <rootdir> for\n" " matching files.\n" "\n" " -v Verbose output.\n" "\n" " -y (Potentially Dangerous) Causes renamed files to overwrite existing\n" " files of the same name without prompting.\n" "\n" " <rootdir> The directory to search for files to rename.\n" "\n" " <regex> The regular expression that selects the files whose name is\n" " to be changed.\n" "\n" " <replacement> The substitution expression that gives the files their\n" " new names.\n" << endl; return exitCode; } RegExMove::RegExMove(::gsl::span<const char*const> args) : m_caseSensitive(true), m_renameDirectories(false), m_renameFiles(true), m_recursiveSearch(false), m_verboseOutput(false), m_allowOverwriteOnNameCollision(false), m_rootDir(), m_patternStr(), m_pattern(), m_replacement() { vector<string> posArgs; // positional arguments for (auto pArg : args) { if (isIEqual(pArg, "-?") || isIEqual(pArg, "-h") || isIEqual(pArg, "-help")) { throw CmdLineError(); } else if (isIEqual(pArg, "-i")) { m_caseSensitive = false; } else if (isIEqual(pArg, "-d")) { m_renameDirectories = true; } else if (isIEqual(pArg, "-dd")) { m_renameDirectories = true; m_renameFiles = false; } else if (isIEqual(pArg, "-r")) { m_recursiveSearch = true; } else if (isIEqual(pArg, "-v")) { m_verboseOutput = true; } else if (isIEqual(pArg, "-y")) { m_allowOverwriteOnNameCollision = true; } else { posArgs.push_back(pArg); } } if (posArgs.size() < 3) { throw CmdLineError("All of the arguments <rootdir>, <regex>, and " "<replacement> are required"); } else if (posArgs.size() > 3) { throw CmdLineError("Only three positional arguments are accepted: " "<rootdir>, <regex>, and <replacement>"); } m_rootDir = posArgs[0]; if (!exists(m_rootDir)) { throw CmdLineError(b::format("The directory \"%1%\" does not exist") % posArgs[0]); } else if (!is_directory(m_rootDir)) { throw CmdLineError(b::format("\"%1%\" is not a directory") % posArgs[0]); } try { m_patternStr = posArgs[1]; if (!balg::starts_with(m_patternStr, "^")) { m_patternStr = '^' + m_patternStr; } if (!balg::ends_with(m_patternStr, "$")) { m_patternStr += '$'; } regex::flag_type flags = m_caseSensitive ? regex::ECMAScript : regex::ECMAScript | regex::icase; m_pattern.assign(m_patternStr, flags); } catch (regex_error const& ex) { throw CmdLineError(b::format("\"%1%\" is not a valid regular expression (%2%)") % posArgs[1] % ex.what()); } m_replacement = posArgs[2]; } template <typename DirIter> void RegExMove::processDirectoryEntries() const { DirIter end; for (DirIter it(m_rootDir); it != end; ++it) { processDirectoryEntry(*it); } } int RegExMove::run() const { if (m_recursiveSearch) { processDirectoryEntries<fs::directory_iterator>(); } else { processDirectoryEntries<fs::recursive_directory_iterator>(); } return EXIT_SUCCESS; } void RegExMove::processDirectoryEntry(DirEntry const& dirEntry) const { switch (dirEntry.status().type()) { case fs::file_type::directory: if (m_renameDirectories) { renamePath(dirEntry.path()); } break; case fs::file_type::regular: if (m_renameFiles) { renamePath(dirEntry.path()); } break; default: // Do nothing break; } } void RegExMove::renamePath(Path const& p) const { string lastSegment = p.filename().string(); if (regex_match(lastSegment, m_pattern)) { string result = regex_replace(lastSegment, m_pattern, m_replacement); Path newPath(p.parent_path()); newPath /= result; if (!exists(newPath)) { rename(p, newPath); if (m_verboseOutput) { cout << b::format("\"%1%\" --> \"%2%\"") % p % result << endl; } } else if (m_allowOverwriteOnNameCollision) { rename(p, newPath); cout << b::format("\"%1%\" overwrote \"%2%\"") % p % result << endl; } else { cout << b::format("\"%1%\" skipped -- \"%2%\" exists") % p % result << endl; } } }
21.832636
94
0.6468
[ "vector" ]
4c7f73f2bbb38505fa6d9260438c17b818fddca4
6,364
hpp
C++
day08/day08.hpp
adrn/advent-of-code
d36c274b5e8ed872ea302113bf8f772b666fb694
[ "MIT" ]
2
2021-12-01T17:42:56.000Z
2021-12-02T02:26:26.000Z
day08/day08.hpp
adrn/advent-of-code
d36c274b5e8ed872ea302113bf8f772b666fb694
[ "MIT" ]
null
null
null
day08/day08.hpp
adrn/advent-of-code
d36c274b5e8ed872ea302113bf8f772b666fb694
[ "MIT" ]
null
null
null
#include <string> #include <iostream> #include <fstream> #include <vector> #include <tuple> #include <map> #include "helpers.hpp" std::map<int, std::string> digit_to_signal = { {0, "abcefg"}, {1, "cf"}, {2, "acdeg"}, {3, "acdfg"}, {4, "bcdf"}, {5, "abdfg"}, {6, "abcefg"}, {7, "acf"}, {8, "abcdefg"}, {9, "abcdfg"}, }; typedef std::vector<std::string> EncodedDigits; std::tuple<std::vector<EncodedDigits>, std::vector<EncodedDigits>> parse_file(std::string filename) { std::cout << "Loading data file at " << filename << std::endl; std::ifstream datafile (filename); std::vector<EncodedDigits> signal_patterns; std::vector<EncodedDigits> outputs; std::string line; if (datafile.is_open()) { while(std::getline(datafile, line)) { auto splitsies = split_string(line, "|"); auto pattern = split_string(splitsies[0], " "); for (auto &elem : pattern) std::sort(elem.begin(), elem.end()); signal_patterns.push_back(pattern); auto output = split_string(splitsies[1], " "); for (auto &elem : output) std::sort(elem.begin(), elem.end()); outputs.push_back(output); } datafile.close(); } else { std::cout << "ERROR: failed to open data file" << std::endl; } return {signal_patterns, outputs}; } std::map<int, int> get_unique_length_digit_map() { // First, find the unique numbers by length: std::vector<int> digit_signal_lengths; for (auto const& [key, val] : digit_to_signal) digit_signal_lengths.push_back(val.length()); // print_vector1d(digit_signal_lengths); std::map<int, int> length_counts; int i, shit; for (i=0; i < digit_signal_lengths.size(); i++) length_counts[digit_signal_lengths[i]] = 0; for (i=0; i < digit_signal_lengths.size(); i++) length_counts[digit_signal_lengths[i]] += 1; std::map<int, int> unq_map; for (i=0; i < digit_signal_lengths.size(); i++) { auto len = digit_signal_lengths[i]; if (length_counts[len] == 1) unq_map[len] = i; } return unq_map; } std::map<std::string, int> get_decoder(EncodedDigits signal_patterns) { std::map<std::string, int> decoder; std::map<int, std::string> encoder; auto unq_digit_map = get_unique_length_digit_map(); for (auto &elem : signal_patterns) { if (unq_digit_map.find(elem.size()) != unq_digit_map.end()) { decoder[elem] = unq_digit_map[elem.size()]; encoder[unq_digit_map[elem.size()]] = elem; } } // 1, 4, 7, 8 identified std::string intersect1, intersect2, intersect4, intersect7, intersect8; // Identify 9 from intersection with 4 and 7: for (auto &pattern : signal_patterns) { intersect4 = ""; intersect7 = ""; std::set_intersection(encoder[4].begin(), encoder[4].end(), pattern.begin(), pattern.end(), std::back_inserter(intersect4)); std::set_intersection(encoder[7].begin(), encoder[7].end(), pattern.begin(), pattern.end(), std::back_inserter(intersect7)); if ((intersect4.size() == 4) && (intersect7.size() == 3) && (decoder.find(pattern) == decoder.end())) { decoder[pattern] = 9; encoder[9] = pattern; } } // 1, 4, 7, 8, 9 identified // Identify 0 from intersection with 1 and 8: for (auto &pattern : signal_patterns) { intersect1 = ""; intersect8 = ""; std::set_intersection(encoder[1].begin(), encoder[1].end(), pattern.begin(), pattern.end(), std::back_inserter(intersect1)); std::set_intersection(encoder[8].begin(), encoder[8].end(), pattern.begin(), pattern.end(), std::back_inserter(intersect8)); if ((intersect1.size() == 2) && (intersect8.size() == 6) && (decoder.find(pattern) == decoder.end())) { decoder[pattern] = 0; encoder[0] = pattern; } } // 0, 1, 4, 7, 8, 9 identified // Identify 2 from intersection with 4 for (auto &pattern : signal_patterns) { intersect4 = ""; std::set_intersection(encoder[4].begin(), encoder[4].end(), pattern.begin(), pattern.end(), std::back_inserter(intersect4)); if ((intersect4.size() == 2) && (decoder.find(pattern) == decoder.end())) { decoder[pattern] = 2; encoder[2] = pattern; } } // 0, 1, 2, 4, 7, 8, 9 identified // Identify 3 from intersection with 2 and 1 for (auto &pattern : signal_patterns) { intersect1 = ""; intersect2 = ""; std::set_intersection(encoder[1].begin(), encoder[1].end(), pattern.begin(), pattern.end(), std::back_inserter(intersect1)); std::set_intersection(encoder[2].begin(), encoder[2].end(), pattern.begin(), pattern.end(), std::back_inserter(intersect2)); if ((intersect1.size() == 2) && (intersect2.size() == 4) && (decoder.find(pattern) == decoder.end())) { decoder[pattern] = 3; encoder[3] = pattern; } } // 0, 1, 2, 3, 4, 7, 8, 9 identified // Identify 5 from intersection with 8 for (auto &pattern : signal_patterns) { intersect8 = ""; std::set_intersection(encoder[8].begin(), encoder[8].end(), pattern.begin(), pattern.end(), std::back_inserter(intersect8)); if ((intersect8.size() == 5) && (decoder.find(pattern) == decoder.end())) { decoder[pattern] = 5; encoder[5] = pattern; } } // 0, 1, 2, 3, 4, 5, 7, 8, 9 identified // Identify 6 as the last one for (auto &pattern : signal_patterns) { if (decoder.find(pattern) == decoder.end()) { decoder[pattern] = 6; encoder[6] = pattern; } } return decoder; }
34.586957
83
0.534098
[ "vector" ]
4c8142b13ea002e8fea1c91399a04c59fb7e891b
2,033
cpp
C++
RawBinary.cpp
mshockwave/MIPS-R3000-CPU-Simulator
ef90317990ed4b340ce063c5a6876152afc0d65b
[ "Apache-2.0" ]
null
null
null
RawBinary.cpp
mshockwave/MIPS-R3000-CPU-Simulator
ef90317990ed4b340ce063c5a6876152afc0d65b
[ "Apache-2.0" ]
null
null
null
RawBinary.cpp
mshockwave/MIPS-R3000-CPU-Simulator
ef90317990ed4b340ce063c5a6876152afc0d65b
[ "Apache-2.0" ]
null
null
null
#include "RawBinary.h" #include "Utils.h" #include <fstream> extern "C" { #include <sys/mman.h> }; RawBinary::RawBinary(std::string instFilePath, std::string dataFilePath) { DEBUG_BLOCK { Log::D("Instructions Read") << "Start Time(ms): " << getCurrentTimeMs() << std::endl; }; FILE* instFile = fopen(instFilePath.c_str(), "rb"); FILE* dataFile = fopen(dataFilePath.c_str(), "rb"); if(instFile == NULL || dataFile == NULL){ throw "Error reading instruction or data file"; } int instFd = fileno(instFile), dataFd = fileno(dataFile); //Get file size in order to improve vector performance long inst_file_size = get_file_size(instFd), data_file_size = get_file_size(dataFd); auto map_instr = (byte_t*)mmap(NULL, static_cast<size_t>(inst_file_size), PROT_READ, MAP_PRIVATE, instFd, 0); mRawInstructions = raw_container_t::Wrap(map_instr, static_cast<size_t>(inst_file_size)); raw_container_t::release_callback_t inst_cb = [](raw_container_t& self)->void { int ret = munmap(self.content(), self.size()); DEBUG_BLOCK{ if(ret){ Log::D("RawBinary") << "Error unmap instruction part" << std::endl; }else{ Log::D("RawBinary") << "Release instruction mmap!" << std::endl; } }; }; mRawInstructions->SetReleaseCallback(inst_cb); auto map_data = (byte_t*)mmap(NULL, static_cast<size_t>(data_file_size), PROT_READ, MAP_PRIVATE, dataFd, 0); mRawData = raw_container_t::Wrap(map_data, static_cast<size_t>(data_file_size)); raw_container_t::release_callback_t data_cb = [](raw_container_t& self)->void { int ret = munmap(self.content(), self.size()); DEBUG_BLOCK { if(ret){ Log::D("RawBinary") << "Error unmap data part" << std::endl; }else{ Log::D("RawBinary") << "Release data mmap!" << std::endl; } }; }; mRawData->SetReleaseCallback(data_cb); }
36.963636
113
0.617806
[ "vector" ]
4c978503ee3c0af3693bc9ddf1805232ae3750b4
843
cpp
C++
armplanning_test/planarmpath.cpp
Boberito25/ButlerBot
959f961bbc8c43be0ccb533dd2e2af5c55b0cc2a
[ "BSD-3-Clause" ]
null
null
null
armplanning_test/planarmpath.cpp
Boberito25/ButlerBot
959f961bbc8c43be0ccb533dd2e2af5c55b0cc2a
[ "BSD-3-Clause" ]
1
2015-06-08T19:55:40.000Z
2015-06-08T19:55:40.000Z
armplanning_test/planarmpath.cpp
Boberito25/ButlerBot
959f961bbc8c43be0ccb533dd2e2af5c55b0cc2a
[ "BSD-3-Clause" ]
null
null
null
#include "astar.cpp" #include <Eigen/Dense> #include "forward_kinematics.h" #include <vector> #include <stdio.h> int main(int argc, char** argv ) { std::cout << "Start Program\n"; Astar planner; configState start; start.theta[0] = 0; start.theta[1] = 0; start.theta[2] = 0; start.theta[3] = 0; start.theta[4] = 0; configState target; target.theta[0] = 0; target.theta[1] = 12; target.theta[2] = 12; target.theta[3] = 0; target.theta[4] = 0; wsState* actarget = fk(&target); std::cout << "Start Running\n"; clock_t startTime = clock(); std::vector<configState*> path = planner.run(&start, actarget); float secsElapsed = (float)(clock() - startTime)/CLOCKS_PER_SEC; printf("Runtime %f\n",secsElapsed); for(int i = 0; i < path.size(); i++){ configstate_tostring(path.at(i)); } return 0; }
21.075
66
0.635824
[ "vector" ]
4c98d55d1a89ae97813cb888c63f8eda5e8b85f4
2,543
cpp
C++
Data Structures and Algorithms/PA4/Hash.cpp
colegarien/school_projects
98147b463164aa2f26a5db3e209623e33bde6982
[ "MIT" ]
null
null
null
Data Structures and Algorithms/PA4/Hash.cpp
colegarien/school_projects
98147b463164aa2f26a5db3e209623e33bde6982
[ "MIT" ]
null
null
null
Data Structures and Algorithms/PA4/Hash.cpp
colegarien/school_projects
98147b463164aa2f26a5db3e209623e33bde6982
[ "MIT" ]
null
null
null
//------------------------ // Cole Garien // Data Struct & Algo // MW 5:45 // PA4 //------------------------ #include <iostream> #include <vector> #include <cmath> #include "Hash.h" using namespace std; // return number of attempts int Hash::QuadraticProbing(int val, int c1, int c2){ // the intial place to try and insert int base = hashFunc(val); // track num of attempts int attempts = 0; // first place to look int index = base; // havent found the value bool inserted = false; do{ // if the current index is deleted then insert if(table[index].deleted){ table[index].value = val; table[index].deleted = false; inserted = true; // if found the same value then delete it }else if(table[index].value == val){ table[index].deleted = true; inserted = true; // if the current spot is filled, find the next spot }else{ // move to next spot index = base + jumpSize(attempts + 1,c1,c2); // if next index is outside of array then wrap it back in while(index >= table.size()){ index -= table.size(); } } // an attempt has been completed attempts++; // only try 99 times or until the value is found }while(attempts < 99 && !inserted); // return attempts it took return attempts; } // returns number of attempts int Hash::DoubleHashing(int val, int R){ // first place to look int base = hashFunc(val); int attempts = 0; // start here int index = base; // havent found anything bool inserted = false; do{ // if spot has nothing then insert if(table[index].deleted){ table[index].value = val; table[index].deleted = false; inserted = true; // if spot has same value, delete }else if(table[index].value == val){ table[index].deleted = true; inserted = true; // look for another spot }else{ // use doubleHash index =(attempts+1) * doubleHash(val,R); // if spot is outside of array then wrap it back in while(index >= table.size()){ index -= table.size(); } } // another attempt complete attempts++; // run for 99 attempts or till inserted }while(attempts < 99 && !inserted); // return number of tries return attempts; } // constructor Hash::Hash(int size){ table.resize(size); for(int i = 0; i < table.size(); i++){ table[i].deleted = true; } } // hashes the value int Hash::hashFunc(int k){ return k%table.size(); } // the double hash function int Hash::doubleHash(int k, int R){ return R - (k%R); } // find the jumpsize for the Quadratic probing int Hash::jumpSize(int i, int c1, int c2){ return ((c1*i)+(c2*i*i)); }
22.90991
60
0.642548
[ "vector" ]
4c9e1cc84c83d1c2c1d94c4a880a0f8f7353cc89
3,883
cpp
C++
lib/lexer/Lexer.cpp
federico-terzi/ninx
ff760a481fc6c16ab06fe106c0f2051125f1b9c6
[ "MIT" ]
2
2020-08-18T23:12:52.000Z
2021-11-15T11:29:19.000Z
lib/lexer/Lexer.cpp
federico-terzi/ninx
ff760a481fc6c16ab06fe106c0f2051125f1b9c6
[ "MIT" ]
15
2018-12-29T20:33:14.000Z
2019-02-03T15:13:47.000Z
lib/lexer/Lexer.cpp
federico-terzi/ninx
ff760a481fc6c16ab06fe106c0f2051125f1b9c6
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2018 Federico Terzi 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 "Lexer.h" #include "token/Text.h" #include "token/Limiter.h" #include "token/Keyword.h" #include "token/Variable.h" using namespace ninx::lexer::token; ninx::lexer::Lexer::Lexer(std::istream &stream) : Lexer(stream, "unknown_origin") {} ninx::lexer::Lexer::Lexer(std::istream &stream, std::string origin) : stream{stream}, origin{origin}, reader{Reader{stream, origin}} { } std::vector<std::unique_ptr<Token>> ninx::lexer::Lexer::generate() { std::vector<std::unique_ptr<Token>> tokens; while(true) { int next_limiter = reader.get_next_limiter(); if (next_limiter == -1) { // EOF break; } if (next_limiter > 0) { // A limiter was found switch (next_limiter) { case '@': // Keyword beginning { bool lateSelectorFound = false; int trailing_spaces; auto keywordToken = std::make_unique<Keyword>(reader.get_line_number(), reader.read_identifier(trailing_spaces, '?', lateSelectorFound)); if (lateSelectorFound) { keywordToken->set_late(true); } tokens.push_back(std::move(keywordToken)); break; } case '$': // Variable beginning { int trailing_spaces; auto variableToken = std::make_unique<Variable>(reader.get_line_number(), reader.read_identifier(trailing_spaces)); variableToken->set_trailing_spaces(trailing_spaces); tokens.push_back(std::move(variableToken)); break; } default: // Other limiters, mark them as generic limiters { auto limiterToken = std::make_unique<Limiter>(reader.get_line_number(), static_cast<char>(next_limiter)); tokens.push_back(std::move(limiterToken)); } } }else{ // A limiter was not found, it is a simple text auto token = std::make_unique<Text>(reader.get_line_number(), reader.read_until_limiter()); // Only add non-empty tokens if (!token->is_empty()) { tokens.push_back(std::move(token)); } } } if (verbose) { for (auto &token : tokens) { std::cout << *token << std::endl; } } return std::move(tokens); } bool ninx::lexer::Lexer::is_verbose() const { return verbose; } void ninx::lexer::Lexer::set_verbose(bool verbose) { Lexer::verbose = verbose; }
37.336538
157
0.599021
[ "vector" ]
4ca1ceb561a827df3098e38416487ef5f7f63fe6
6,503
cpp
C++
NeuralNetwork/Sources/NeuralNetwork/ANetworkData.cpp
sousav/DeepNetwork
8931c05d5d703477325b0c3d7d5fd2c75658bc6b
[ "MIT" ]
null
null
null
NeuralNetwork/Sources/NeuralNetwork/ANetworkData.cpp
sousav/DeepNetwork
8931c05d5d703477325b0c3d7d5fd2c75658bc6b
[ "MIT" ]
null
null
null
NeuralNetwork/Sources/NeuralNetwork/ANetworkData.cpp
sousav/DeepNetwork
8931c05d5d703477325b0c3d7d5fd2c75658bc6b
[ "MIT" ]
null
null
null
/** * @Author: Victor Sousa <vicostudio> * @Date: 29/04/2018 20:10:29 * @Email: victor.sousa@epitech.eu * @Last modified by: vicostudio * @Last modified time: 29/04/2018 20:27:50 */ #include "ANetworkData.hpp" Neural::ANetworkData::ANetworkData(const std::vector<unsigned> &topology, double recentAverageSmoothingFactor) { this->_recentAverageError = 1; this->_recentAverageSmoothingFactor = recentAverageSmoothingFactor; unsigned numLayers = topology.size(); for (unsigned layerNum = 0; layerNum < numLayers; ++layerNum) { this->_layers.emplace_back(); unsigned numOutputs = layerNum == topology.size() - 1 ? 0 : topology[layerNum + 1]; // We have a new layer, now fill it with neurons for (unsigned neuronNum = 0; neuronNum <= topology[layerNum]; ++neuronNum) { this->_layers.back().push_back(Neuron(numOutputs, neuronNum)); } this->_layers.back().back().setOutputVal(1.0); //bias neuron } } Neural::ANetworkData::~ANetworkData() { } Neural::ANetworkData::ANetworkData(const ANetworkData &data) { loadFrom(data); } Neural::ANetworkData &Neural::ANetworkData::operator =(const ANetworkData &data) { loadFrom(data); return *this; } void Neural::ANetworkData::loadFrom(const ANetworkData &data) { this->_layers = data._layers; this->_error = data._error; this->_recentAverageError = data._recentAverageError; this->_recentAverageSmoothingFactor = data._recentAverageSmoothingFactor; } void Neural::ANetworkData::loadFrom(const std::string &filepath) { std::ifstream file; file.open(filepath.c_str()); if (file) { std::vector<unsigned>topology = readTopology(file); std::vector<double>error = readError(file); if (error.size() != 3) throw Neural::InvalidSavingFile("Your saving file " + filepath + " contains incorrect error information"); ANetworkData newData(topology, error[2]); newData._error = error[0]; newData._recentAverageError = error[1]; *this = newData; while (!file.eof()) { std::vector<unsigned> coord; Neural::INeuron::Connection data{}; readNextNeuron(file, coord, data); if (coord.empty()) break; this->_layers[coord[0]][coord[1]].setConnection(coord[2], data); } file.close(); } else { throw Neural::InvalidSavingFile("Your saving file " + filepath + " could not be found"); } } void Neural::ANetworkData::saveTo(const std::string &filepath) const { std::ofstream file; file.open(filepath.c_str()); if (!file) throw Neural::InvalidSavingFile("The file in which you are trying to save could not be created.."); file << "topology:"; for (auto const& layer: this->_layers) { file << " " << layer.size() - 1; } file << std::endl; file << "error: " << this->_error << " " << this->_recentAverageError << " " << this->_recentAverageSmoothingFactor << std::endl; unsigned i = 0; for (auto const& layer: this->_layers) { if (i == this->_layers.size() - 1) break; int j = 0; for (auto const& neuron: layer) { std::vector<Neural::INeuron::Connection> connections = neuron.getConnection(); unsigned k = 0; for (auto const &connection: connections) { file << i << " " << j << " " << k << " " << connection.weight << " " << connection.deltaWeight << std::endl; k++; } j++; } i++; } file.close(); } std::vector<unsigned> Neural::ANetworkData::readTopology(std::ifstream &file) const { std::vector<unsigned> topology; std::string line; std::string label; getline(file, line); std::stringstream ss(line); ss >> label; if (file.eof() || label != "topology:") { throw Neural::InvalidTrainingFile("You training file does not contain a topology brief"); } while (!ss.eof()) { unsigned n; ss >> n; topology.push_back(n); } return topology; } std::vector<double> Neural::ANetworkData::readError(std::ifstream &file) const { std::vector<double> error; std::string line; std::string label; getline(file, line); std::stringstream ss(line); ss >> label; if (file.eof() || label != "error:") { throw Neural::InvalidTrainingFile("You training file does not contain an error brief"); } while (!ss.eof()) { double n; ss >> n; error.push_back(n); } return error; } void Neural::ANetworkData::readNextNeuron(std::ifstream &file, std::vector<unsigned> &coord, Neural::INeuron::Connection &data) const { std::string line; getline(file, line); if (line.empty()) return; std::stringstream ss(line); for (int i = 0; i < 3; i++) { if (ss.eof()) throw Neural::InvalidTrainingFile("You training file does not contain enough information for one of its neuron"); unsigned n; ss >> n; coord.push_back(n); } if (ss.eof()) throw Neural::InvalidTrainingFile("You training file does not contain enough information for one of its neuron"); ss >> data.weight; if (ss.eof()) throw Neural::InvalidTrainingFile("You training file does not contain enough information for one of its neuron"); ss >> data.deltaWeight; } double Neural::ANetworkData::getRecentAverageError(void) const { return this->_recentAverageError; } std::vector<Neural::Layer> const & Neural::ANetworkData::getLayer() const { return this->_layers; } unsigned Neural::ANetworkData::getLayerCount() const { return this->_layers.size(); } unsigned Neural::ANetworkData::getInputCount() const { return (this->_layers.empty() ? 0 : this->_layers.front().size() - 1); } unsigned Neural::ANetworkData::getOutputCount() const { return (this->_layers.empty() ? 0 : this->_layers.back().size() - 1); } unsigned Neural::ANetworkData::getNeuronCount() const { unsigned total = 0; for (auto const &layer: this->_layers) { total += layer.size(); } return total; } unsigned Neural::ANetworkData::getConnectionCount() const { unsigned total = 0; for (auto const &layer: this->_layers) { for (auto const &neuron: layer) { total += neuron.getConnectionCount(); } } return total; }
31.264423
135
0.616946
[ "vector" ]
4ca2488749954eebaab79328877a19510d41f34f
3,692
hpp
C++
include/derecho/objectstore/Object.hpp
xinzheyang/derecho-unified
b5e79638fcf667cdba42a78fe1404db4235cd462
[ "BSD-3-Clause" ]
null
null
null
include/derecho/objectstore/Object.hpp
xinzheyang/derecho-unified
b5e79638fcf667cdba42a78fe1404db4235cd462
[ "BSD-3-Clause" ]
null
null
null
include/derecho/objectstore/Object.hpp
xinzheyang/derecho-unified
b5e79638fcf667cdba42a78fe1404db4235cd462
[ "BSD-3-Clause" ]
null
null
null
#ifndef OBJECT_HPP #define OBJECT_HPP #include <chrono> #include <iostream> #include <map> #include <memory> #include <string.h> #include <string> #include <time.h> #include <vector> #include <optional> #include <tuple> #include <derecho/conf/conf.hpp> #include <derecho/core/derecho.hpp> #include <derecho/mutils-serialization/SerializationSupport.hpp> #include <derecho/persistent/Persistent.hpp> using std::cout; using std::endl; using namespace persistent; using namespace std::chrono_literals; namespace objectstore { class Blob : public mutils::ByteRepresentable { public: char* bytes; std::size_t size; // constructor - copy to own the data Blob(const char* const b, const decltype(size) s); // copy constructor - copy to own the data Blob(const Blob& other); // move constructor - accept the memory from another object Blob(Blob&& other); // default constructor - no data at all Blob(); // destructor virtual ~Blob(); // move evaluator: Blob& operator=(Blob&& other); // copy evaluator: Blob& operator=(const Blob& other); // serialization/deserialization supports std::size_t to_bytes(char* v) const; std::size_t bytes_size() const; void post_object(const std::function<void(char const* const, std::size_t)>& f) const; void ensure_registered(mutils::DeserializationManager&) {} static std::unique_ptr<Blob> from_bytes(mutils::DeserializationManager*, const char* const v); // from_bytes_noalloc() implementation borrowed from mutils-serialization. mutils::context_ptr<Blob> from_bytes_noalloc( mutils::DeserializationManager* ctx, const char* const v, mutils::context_ptr<Blob> = mutils::context_ptr<Blob>{}); }; using OID = uint64_t; #define INV_OID (0xffffffffffffffffLLU) class Object : public mutils::ByteRepresentable { public: mutable std::tuple<persistent::version_t,uint64_t> ver; // object version OID oid; // object_id Blob blob; // the object bool operator==(const Object& other); bool is_valid() const; // constructor 0 : copy constructor Object(const OID& _oid, const Blob& _blob); // constructor 0.5 : copy constructor Object(const std::tuple<persistent::version_t,uint64_t> _ver, const OID& _oid, const Blob& _blob); // constructor 1 : copy consotructor Object(const uint64_t _oid, const char* const _b, const std::size_t _s); // constructor 1.5 : copy constructor Object(const std::tuple<persistent::version_t,uint64_t> _ver, const uint64_t _oid, const char* const _b, const std::size_t _s); // TODO: we need a move version for the deserializer. // constructor 2 : move constructor Object(Object&& other); // constructor 3 : copy constructor Object(const Object& other); // constructor 4 : default invalid constructor Object(); DEFAULT_SERIALIZATION_SUPPORT(Object, ver, oid, blob); }; inline std::ostream& operator<<(std::ostream& out, const Blob& b) { out << "[size:" << b.size << ", data:" << std::hex; if(b.size > 0) { uint32_t i = 0; for(i = 0; i < 8 && i < b.size; i++) { out << " " << b.bytes[i]; } if(i < b.size) { out << "..."; } } out << std::dec << "]"; return out; } inline std::ostream& operator<<(std::ostream& out, const Object& o) { out << "Object{ver: 0x" << std::hex << std::get<0>(o.ver) << std::dec << ", ts: " << std::get<1>(o.ver) << ", id:" << o.oid << ", data:" << o.blob << "}"; return out; } } // namespace objectstore #endif //OBJECT_HPP
27.759398
131
0.640033
[ "object", "vector" ]
4ca74ed193ab5bdef5a39805aa46961e10c9520d
908
cpp
C++
pressdatafilter.cpp
futr/sensorreader
52e17ef7b4352071951b55ec9e4594a06881d70a
[ "MIT" ]
null
null
null
pressdatafilter.cpp
futr/sensorreader
52e17ef7b4352071951b55ec9e4594a06881d70a
[ "MIT" ]
null
null
null
pressdatafilter.cpp
futr/sensorreader
52e17ef7b4352071951b55ec9e4594a06881d70a
[ "MIT" ]
null
null
null
#include "pressdatafilter.h" PressDataFilter::PressDataFilter(QObject *parent) : AbstractDataFilter(parent) { m_fileName = "pressure.csv"; m_filterName = "PressFilter"; m_filterID = ID_LPS331AP; } bool PressDataFilter::parseAndSave(unsigned int step, QByteArray data) { // データー処理 QTextStream out( &m_file ); QVector<double> v = parseToVector( step, data ); out << (unsigned int)v[0] << "," << QString().sprintf( "%.6e", v[1] ) << '\n'; return true; } QVector<double> PressDataFilter::parseToVector(unsigned int step, QByteArray data) { // Parse to vector qint32 val; QVector<double> ret; val = qFromLittleEndian<qint32>( (uchar *)data.data() ); ret << step << (double)val / 4096; return ret; } void PressDataFilter::makeHeader() { // ヘッダ作成 QTextStream out( &m_file ); out << "time[100us],pressure[hPa]" << '\n'; }
21.116279
82
0.63326
[ "vector" ]
4caca4a79d8312b36fbb57207ce270f0cae41af9
4,790
cpp
C++
app/main.cpp
jenadzi/pointcloud-raster
1c97f8aaedfa567ac068312797cc11fe76fa582d
[ "MIT" ]
null
null
null
app/main.cpp
jenadzi/pointcloud-raster
1c97f8aaedfa567ac068312797cc11fe76fa582d
[ "MIT" ]
null
null
null
app/main.cpp
jenadzi/pointcloud-raster
1c97f8aaedfa567ac068312797cc11fe76fa582d
[ "MIT" ]
1
2021-09-09T21:56:16.000Z
2021-09-09T21:56:16.000Z
#include <iostream> #include <pointcloud_raster/raster/pointcloud_rasterizer.hpp> #ifdef WITH_LAS #include <pointcloud_raster/io/las/las_reader.hpp> #endif #include <pointcloud_raster/io/txt/txt_reader.hpp> #include <pointcloud_raster/io/ply/ply_reader.hpp> int main(int argc, char *argv[]) { if (argc < 4) { std::cout << "Usage: ./pointcloud_raster_app input_cloud format output_dir" << std::endl; std::cout << " - input cloud is the path to the file to raster" << std::endl; #ifdef WITH_LAS std::cout << " - format can be TXT, PLY or LAS" << std::endl; #else std::cout << " - format can be TXT or PLY" << std::endl; #endif std::cout << " - raster viewpoint, can be TOP, SIDE, FRONT, PERSPECTIVE or ALL" << std::endl; std::cout << " - output prefix for results. Parent folder should exist" << std::endl; std::cout << " - (optional) max width for raster" << std::endl; std::cout << " - (optional) max color value, per channel (default 255)" << std::endl; std::cout << " Example: ./pointcloud_raster_app input.las LAS ALL output/screenshot 2048 " << std::endl; return EXIT_FAILURE; } const std::string pointcloudFile(argv[1]); std::string pointcloudFormat(argv[2]); std::transform(pointcloudFormat.begin(), pointcloudFormat.end(), pointcloudFormat.begin(), ::toupper); std::string rasterViewPreset(argv[3]); std::transform(rasterViewPreset.begin(), rasterViewPreset.end(), rasterViewPreset.begin(), ::toupper); std::vector<std::pair<std::string, pointcloud_raster::ViewPointPreset>> viewPresets; if (rasterViewPreset == "TOP" || rasterViewPreset == "ALL") viewPresets.push_back({"top", pointcloud_raster::ViewPointPreset::TOP}); if (rasterViewPreset == "SIDE" || rasterViewPreset == "ALL") viewPresets.push_back({"side", pointcloud_raster::ViewPointPreset::SIDE}); if (rasterViewPreset == "FRONT" || rasterViewPreset == "ALL") viewPresets.push_back({"front", pointcloud_raster::ViewPointPreset::FRONT}); if (rasterViewPreset == "PERSPECTIVE" || rasterViewPreset == "ALL") viewPresets.push_back({"perspective", pointcloud_raster::ViewPointPreset::FRONT_ISOMETRIC}); const int rasterSize = argc >= 6 ? std::stoi(argv[5]) : 1024; const int pointcloudMaxColor = argc >= 7 ? std::stoi(argv[6]) : 255; std::cout << "Rasterizing " << pointcloudFile << " format " << rasterViewPreset << " size " << rasterSize << " pointcloud max color " << pointcloudMaxColor << std::endl; pointcloud_raster::raster::PointcloudRasterizer rasterizer; rasterizer.SetMaxPointColor(pointcloudMaxColor); for (const auto &[suffix, viewProfile] : viewPresets) { pointcloud_raster::raster::PointcloudRasterizer::RasterOptions rasterOptions; rasterOptions.rasterViewPointPreset = viewProfile; rasterOptions.rasterSize = {rasterSize, rasterSize}; rasterizer.AddOutputRaster(rasterOptions); } if (pointcloudFormat == "LAS") #ifdef WITH_LAS rasterizer.AddInputProvider(new pointcloud_raster::io::LASReader(pointcloudFile)); #else { std::cerr << "LAS support is not available" << std::endl; return EXIT_FAILURE; } #endif else if (pointcloudFormat == "TXT") rasterizer.AddInputProvider(new pointcloud_raster::io::TXTReader(pointcloudFile)); else if (pointcloudFormat == "PLY") rasterizer.AddInputProvider(new pointcloud_raster::io::PLYReader(pointcloudFile)); else { std::cerr << "Unknown format " << pointcloudFormat << std::endl; return EXIT_FAILURE; } if (!rasterizer.Rasterize()) { std::cerr << "Rasterization failed" << std::endl; return EXIT_FAILURE; } if (viewPresets.size() != rasterizer.GetRasterImages().size()) { std::cerr << "Error: Number of resulting rasters is not the same as given input configurations." << "Given " << viewPresets.size() << " vs generated " << rasterizer.GetRasterImages().size() << std::endl; return EXIT_FAILURE; } #ifdef POINTCLOUD_RASTER_PNG_SUPPORT { auto rasterImageIterator = rasterizer.GetRasterImages().begin(); for (const auto &[suffix, viewProfile] : viewPresets) { const std::string pngFile = std::string(argv[4]) + "_" + suffix + ".png"; std::cout << "Saving image " << pngFile << std::endl; if (!rasterImageIterator->SaveAsPNG(pngFile)) std::cerr << "Error saving image" << std::endl; rasterImageIterator++; } } #else std::cerr << "Library built without PNG support. No outputs bill be saved." << std::endl; #endif return EXIT_SUCCESS; }
43.545455
112
0.651566
[ "vector", "transform" ]
4cba9c6bb4bc715b769406dda9dc07ad7c9037b6
3,811
cxx
C++
tests/core/moneta/traits/members_test.cxx
madera/Moneta
4c0da911bceb511d7d1133699b0d85216bb63d74
[ "BSL-1.0" ]
2
2015-10-09T12:11:54.000Z
2016-01-20T15:34:33.000Z
tests/core/moneta/traits/members_test.cxx
madera/Moneta
4c0da911bceb511d7d1133699b0d85216bb63d74
[ "BSL-1.0" ]
5
2015-07-04T20:31:32.000Z
2015-07-04T20:44:58.000Z
tests/core/moneta/traits/members_test.cxx
madera/Moneta
4c0da911bceb511d7d1133699b0d85216bb63d74
[ "BSL-1.0" ]
null
null
null
// [===========================================================================] // [ M o n e t a ] // [---------------------------------------------------------------------------] // [ ] // [ Copyright (C) 2005-2015 ] // [ Rodrigo Madera <madera@acm.org> ] // [ ] // [---------------------------------------------------------------------------] // [ Distributed under the Boost Software License, Version 1.0 ] // [ Read accompanying LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt ] // [===========================================================================] #include "pch.hxx" #include "../model/Person.hxx" #include "../model/tree/A.hxx" #include <boost/mpl/at.hpp> inline void static_test() { BOOST_MPL_ASSERT(( boost::is_same< boost::mpl::at_c<moneta::traits::members<Person>::type, 0>::type, MONETA_MEMBER(Person, int, ID) > )); BOOST_MPL_ASSERT(( boost::is_same< boost::mpl::at_c<moneta::traits::members<Person>::type, 1>::type, MONETA_MEMBER(Person, std::string, Name) > )); BOOST_MPL_ASSERT(( boost::is_same< boost::mpl::at_c<moneta::traits::members<Person>::type, 2>::type, MONETA_MEMBER(Person, double, Height) > )); BOOST_MPL_ASSERT(( boost::is_same< boost::mpl::at_c<moneta::traits::members<Person>::type, 3>::type, MONETA_MEMBER(Person, int, Ratings) > )); // // member_inequality_test // BOOST_MPL_ASSERT_NOT(( boost::is_same< MONETA_MEMBER(Person, int, ID), MONETA_MEMBER(Person, int, Ratings) > )); BOOST_MPL_ASSERT((moneta::traits::is_first_member<MONETA_MEMBER(Person, int, ID)>)); BOOST_MPL_ASSERT_NOT((moneta::traits::is_first_member<MONETA_MEMBER(Person, int, Ratings)>)); BOOST_MPL_ASSERT_NOT((moneta::traits::is_last_member<MONETA_MEMBER(Person, int, ID)>)); BOOST_MPL_ASSERT((moneta::traits::is_last_member<MONETA_MEMBER(Person, int, Ratings)>)); BOOST_MPL_ASSERT_NOT((moneta::traits::is_member_entity<MONETA_MEMBER(A, int, f)>)); BOOST_MPL_ASSERT_NOT((moneta::traits::is_member_entity<MONETA_MEMBER(A, int, g)>)); BOOST_MPL_ASSERT ((moneta::traits::is_member_entity<MONETA_MEMBER(A, B , b)>)); BOOST_MPL_ASSERT_NOT((moneta::traits::is_member_entity<MONETA_MEMBER(A, int, h)>)); BOOST_MPL_ASSERT ((moneta::traits::is_first_non_entity_member<MONETA_MEMBER(A, int, f)>)); BOOST_MPL_ASSERT_NOT((moneta::traits::is_first_non_entity_member<MONETA_MEMBER(A, int, g)>)); BOOST_MPL_ASSERT_NOT((moneta::traits::is_first_non_entity_member<MONETA_MEMBER(A, int, h)>)); BOOST_MPL_ASSERT_NOT((moneta::traits::is_last_non_entity_member<MONETA_MEMBER(A, int, f)>)); BOOST_MPL_ASSERT_NOT((moneta::traits::is_last_non_entity_member<MONETA_MEMBER(A, int, g)>)); BOOST_MPL_ASSERT ((moneta::traits::is_last_non_entity_member<MONETA_MEMBER(A, int, h)>)); BOOST_MPL_ASSERT((moneta::traits::is_first_entity_member<MONETA_MEMBER(A, B, b)>)); BOOST_MPL_ASSERT((moneta::traits:: is_last_entity_member<MONETA_MEMBER(A, B, b)>)); BOOST_MPL_ASSERT_NOT((moneta::traits::is_first_entity_member<MONETA_MEMBER(A, int, f)>)); BOOST_MPL_ASSERT_NOT((moneta::traits::is_first_entity_member<MONETA_MEMBER(A, int, g)>)); BOOST_MPL_ASSERT_NOT((moneta::traits::is_first_entity_member<MONETA_MEMBER(A, int, h)>)); BOOST_MPL_ASSERT_NOT((moneta::traits:: is_last_entity_member<MONETA_MEMBER(A, int, f)>)); BOOST_MPL_ASSERT_NOT((moneta::traits:: is_last_entity_member<MONETA_MEMBER(A, int, g)>)); BOOST_MPL_ASSERT_NOT((moneta::traits:: is_last_entity_member<MONETA_MEMBER(A, int, h)>)); }
43.306818
94
0.608239
[ "model" ]
4cd84062b3c4ed40a0667d5e75f8fcec770b36fb
16,088
hpp
C++
inc/vmath/core/vector.hpp
kernan/vmath
6c28e7e731a2ea47a7b66b5dd4170283e84f1e02
[ "MIT" ]
1
2018-09-15T13:56:26.000Z
2018-09-15T13:56:26.000Z
inc/vmath/core/vector.hpp
kernan/math
6c28e7e731a2ea47a7b66b5dd4170283e84f1e02
[ "MIT" ]
7
2016-07-05T19:11:09.000Z
2017-05-08T21:19:58.000Z
inc/vmath/core/vector.hpp
kernan/vmath
6c28e7e731a2ea47a7b66b5dd4170283e84f1e02
[ "MIT" ]
1
2018-11-06T21:00:34.000Z
2018-11-06T21:00:34.000Z
#ifndef VMATH_CORE_VECTOR_HPP #define VMATH_CORE_VECTOR_HPP #include <array> #include <cstddef> #include <ostream> #include <type_traits> #include <vmath/core/swizzle/swizzle2.hpp> #include <vmath/core/swizzle/swizzle3.hpp> #include <vmath/core/swizzle/swizzle4.hpp> #include <vmath/core/swizzle/swizzle_gen.hpp> namespace vmath { namespace core { /*! * \brief Definition of the components available in a generic vector * \tparam T Storage type * \tparam N Number of vector elements */ template<typename T, std::size_t N> class VectorComponents { public: std::array<T, N> data; /*! * \brief Construct a zero vector component */ VectorComponents() : data() {} /*! * \brief Construct a vector componet from an array * \param[in] data Array to convert to a vector component */ explicit VectorComponents(const std::array<T, N>& data) : data(data) {} /*! * \brief Copy constructor * \param[in] other Vector component object to copy */ VectorComponents(const VectorComponents<T, N>& other) = default; /*! * \brief Copy assignment operator * \param[in] other Vector component object to copy * \return Reference to self */ VectorComponents<T, N>& operator=(const VectorComponents<T, N>& other) = default; /*! * \brief Move constructor * \param[in] other Vector component object to move */ VectorComponents(VectorComponents<T, N>&& other) = default; /*! * \brief Move assignment operator * \param[in] other Vector component object to move * \return Reference to self */ VectorComponents<T, N>& operator=(VectorComponents<T, N>&& other) = default; }; /*! * \brief Vector component specialization for 2-dimensional vectors * \tparam T Storage type */ template<typename T> class VectorComponents<T, 2> { public: union { std::array<T, 2> data; // axis coords struct { T x, y; }; VMATH_CORE_SWIZZLE_GEN_SWIZZLE2_FOR_VECTOR2(T, x, y) VMATH_CORE_SWIZZLE_GEN_SWIZZLE3_FOR_VECTOR2(T, x, y) VMATH_CORE_SWIZZLE_GEN_SWIZZLE4_FOR_VECTOR2(T, x, y) // texture coords struct { T s, t; }; VMATH_CORE_SWIZZLE_GEN_SWIZZLE2_FOR_VECTOR2(T, s, t) VMATH_CORE_SWIZZLE_GEN_SWIZZLE3_FOR_VECTOR2(T, s, t) VMATH_CORE_SWIZZLE_GEN_SWIZZLE4_FOR_VECTOR2(T, s, t) // color values struct { T r, g; }; VMATH_CORE_SWIZZLE_GEN_SWIZZLE2_FOR_VECTOR2(T, r, g) VMATH_CORE_SWIZZLE_GEN_SWIZZLE3_FOR_VECTOR2(T, r, g) VMATH_CORE_SWIZZLE_GEN_SWIZZLE4_FOR_VECTOR2(T, r, g) }; /*! * \brief Construct a zero 2-dimensional vector component */ VectorComponents() : x(), y() {} /*! * \brief Construct a 2-dimensional vector component from an array * \param[in] data Array to convert to a vector component */ explicit VectorComponents(const std::array<T, 2>& data) : data(data) {} /*! * \brief Construct a 2-dimensional vector component by value * \param[in] x X coordinate value * \param[in] y Y coordinate value */ VectorComponents(const T x, const T y) : x(x), y(y) {} /*! * \brief Copy constructor * \param[in] other 2-dimensional vector component to copy */ VectorComponents(const VectorComponents<T, 2>& other) = default; /*! * \brief Copy assignment operator * \param[in] other 2-dimensional vector component to copy * \return Reference to self */ VectorComponents<T, 2>& operator=(const VectorComponents<T, 2>& other) = default; /*! * \brief Move constructor * \param[in] other 2-dimensional vector component to move */ VectorComponents(VectorComponents<T, 2>&& other) = default; /*! * \brief Move assignment operator * \param[in] other 2-dimensional vector component to move * \return Reference to self */ VectorComponents<T, 2>& operator=(VectorComponents<T, 2>&& other) = default; }; /*! * \brief Vector component specialization for 3-dimensional vectors * \tparam T Storage type */ template<typename T> class VectorComponents<T, 3> { public: union { std::array<T, 3> data; // axis coords struct { T x, y, z; }; VMATH_CORE_SWIZZLE_GEN_SWIZZLE2_FOR_VECTOR3(T, x, y, z) VMATH_CORE_SWIZZLE_GEN_SWIZZLE3_FOR_VECTOR3(T, x, y, z) VMATH_CORE_SWIZZLE_GEN_SWIZZLE4_FOR_VECTOR3(T, x, y, z) // texture coords struct { T s, t, p; }; VMATH_CORE_SWIZZLE_GEN_SWIZZLE2_FOR_VECTOR3(T, s, t, p) VMATH_CORE_SWIZZLE_GEN_SWIZZLE3_FOR_VECTOR3(T, s, t, p) VMATH_CORE_SWIZZLE_GEN_SWIZZLE4_FOR_VECTOR3(T, s, t, p) // color values struct { T r, g, b; }; VMATH_CORE_SWIZZLE_GEN_SWIZZLE2_FOR_VECTOR3(T, r, g, b) VMATH_CORE_SWIZZLE_GEN_SWIZZLE3_FOR_VECTOR3(T, r, g, b) VMATH_CORE_SWIZZLE_GEN_SWIZZLE4_FOR_VECTOR3(T, r, g, b) }; /*! * \brief Construct a zero 3-dimensional vector component */ VectorComponents() : x(), y(), z() {} /*! * \brief Construct a 3-dimensional vector component from an array */ explicit VectorComponents(const std::array<T, 3>& data) : data(data) {} /*! * \brief Construct a 3-dimensional vector component by value * \param[in] x X coordinate value * \param[in] y Y coordinate value * \param[in] z Z coordinate value */ VectorComponents(const T x, const T y, const T z) : x(x), y(y), z(z) {} /*! * \brief Constructor a 3-dimensional vector component by extending a * 2-dimensional one * \param[in] vec 2-dimensional vector component * \param[in] z Z coordinate value */ VectorComponents(const VectorComponents<T, 2>& vec, const T z) : x(vec.x), y(vec.y), z(z) {} /*! * \brief Copy constructor * \param[in] other 3-dimensional vector component to copy */ VectorComponents(const VectorComponents<T, 3>& other) = default; /*! * \brief Copy assignment operator * \param[in] other 3-dimensional vector component to copy * \return Reference to self */ VectorComponents<T, 3>& operator=(const VectorComponents<T, 3>& other) = default; /*! * \brief Move constructor * \param[in] other 3-dimensional vector component to move */ VectorComponents(VectorComponents<T, 3>&& other) = default; /*! * \brief Move assignment operator * \param[in] other 3-dimensional vector component to move * \return Reference to self */ VectorComponents<T, 3>& operator=(VectorComponents<T, 3>&& other) = default; }; /*! * \brief Vector component specialization for 4-dimensional vectors * \tparam T Storage type */ template<typename T> class VectorComponents<T, 4> { public: union { std::array<T, 4> data; // axis coords struct { T x, y, z, w; }; VMATH_CORE_SWIZZLE_GEN_SWIZZLE2_FOR_VECTOR4(T, x, y, z, w) VMATH_CORE_SWIZZLE_GEN_SWIZZLE3_FOR_VECTOR4(T, x, y, z, w) VMATH_CORE_SWIZZLE_GEN_SWIZZLE4_FOR_VECTOR4(T, x, y, z, w) // texture coords struct { T s, t, p, q; }; VMATH_CORE_SWIZZLE_GEN_SWIZZLE2_FOR_VECTOR4(T, s, t, p, q) VMATH_CORE_SWIZZLE_GEN_SWIZZLE3_FOR_VECTOR4(T, s, t, p, q) VMATH_CORE_SWIZZLE_GEN_SWIZZLE4_FOR_VECTOR4(T, s, t, p, q) // color values struct { T r, g, b, a; }; VMATH_CORE_SWIZZLE_GEN_SWIZZLE2_FOR_VECTOR4(T, r, g, b, a) VMATH_CORE_SWIZZLE_GEN_SWIZZLE3_FOR_VECTOR4(T, r, g, b, a) VMATH_CORE_SWIZZLE_GEN_SWIZZLE4_FOR_VECTOR4(T, r, g, b, a) }; /*! * \brief Construct a zero 4-dimensional vector component */ VectorComponents() : x(), y(), z(), w() {} /*! * \brief Construct a 4-dimensional vector component from an array * \param[in] data Array to convert to a vector component */ explicit VectorComponents(const std::array<T, 4>& data) : data(data) {} /*! * \brief Construct a 4-dimensional vector component by value * \param[in] x X coordinate value * \param[in] y Y coordinate value * \param[in] z Z coordinate value * \param[in] w W coordinate value */ VectorComponents(const T x, const T y, const T z, const T w) : x(x), y(y), z(z), w(w) {} /*! * \brief Construct a 4-dimensional vector component by extending a * 2-dimensional one * \param[in] vec 2-dimensional vector component * \param[in] z Z coordinate value * \param[in] w W coordinate value */ VectorComponents(const VectorComponents<T, 2>& vec, const T z, const T w) : x(vec.x), y(vec.y), z(z), w(w) {} /*! * \brief Construct a 4-dimensional vector component by extending a * 3-dimensional one * \param[in] vec 3-dimensional vector component * \param[in] w W coordinate value */ VectorComponents(const VectorComponents<T, 3>& vec, const T w) : x(vec.x), y(vec.y), z(vec.z), w(w) {} /*! * \brief Copy constructor * \param[in] other 4-dimensional vector component to copy */ VectorComponents(const VectorComponents<T, 4>& other) = default; /*! * \brief Copy assignment operator * \param[in] other 4-dimensional vector component to copy * \return Reference to self */ VectorComponents<T, 4>& operator=(const VectorComponents<T, 4>& other) = default; /*! * \brief Move constructor * \param[in] other 4-dimensional vector component to move */ VectorComponents(VectorComponents<T, 4>&& other) = default; /*! * \brief Move assignment operator * \param[in] other 4-dimensional vector component to move * \return Reference to self */ VectorComponents<T, 4>& operator=(VectorComponents<T, 4>&& other) = default; }; /*! * \brief A vector with generic size and type * \tparam T Storage type * \tparam N Number of vector elements */ template<typename T, std::size_t N> class Vector : public VectorComponents<T, N> { public: using VectorComponents<T, N>::VectorComponents; /*! * \brief Destructor */ ~Vector() = default; /*! * \brief Access a vector element using an index * \param[in] idx Location of element to access * \return Accessed element */ T operator[](const std::size_t) const; /*! * \brief Access and modify a vector element by index * \param[in] idx Location of element to access * \return Modified element */ T& operator[](const std::size_t); /*! * \brief Vector negation operator * \return The vector negated */ Vector<T, N> operator-() const; /*! * \brief Component-wise addition assignment operator * \param[in] v Vector to add * \return Reference to self */ Vector<T, N>& operator+=(const Vector<T, N>& v); friend Vector<T, N> operator+(Vector<T, N> lhs, const Vector<T, N>& rhs) { return lhs += rhs; } /*! * \brief Component-wise subtraction assignment operator * \param[in] v Vector to subtract * \return Reference to self */ Vector<T, N>& operator-=(const Vector<T, N>& v); friend Vector<T, N> operator-(Vector<T, N> lhs, const Vector<T, N>& rhs) { return lhs -= rhs; } /*! * \brief Component-wise multiplication assignment operator * \param[in] v Vector to multiply * \return Reference to self */ Vector<T, N>& operator*=(const Vector<T, N>& v); friend Vector<T, N> operator*(Vector<T, N> lhs, const Vector<T, N>& rhs) { return lhs *= rhs; } /*! * \brief Component-wise division assignment operator * \param[in] v Vector to divide by * \return Reference to self */ Vector<T, N>& operator/=(const Vector<T, N>& v); friend Vector<T, N> operator/(Vector<T, N> lhs, const Vector<T, N>& rhs) { return lhs /= rhs; } /*! * \brief Scalar multiplication assignment operator * \param[in] s Scalar to multiply by * \return Reference to self */ Vector<T, N>& operator*=(const T s); friend Vector<T, N> operator*(Vector<T, N> v, const T s) { return v *= s; } /*! * \brief Scalar division assignment operator * \param[in] s Scalar to divide by * \return Reference to self */ Vector<T, N>& operator/=(const T s); friend Vector<T, N> operator/(Vector<T, N> v, const T s) { return v /= s; } /*! * \brief Calculate the vector magnitude * \return Vector magnitude */ T mag() const; /*! * \brief Calculate the vector magnitude squared * \return Vector magnitude squared */ T mag2() const; /*! * \brief Calculate the vector normal * \return The vector normal */ Vector<T, N> normal() const; /*! * \brief Normalize the vector * \return Reference to self */ Vector<T, N>& normalize(); /*! * \brief Check vector equality * \param[in] other Vector to check equality with * \return True if equal, else false */ bool equals(const Vector<T, N>& other) const; /*! * \brief Check vector equality * \param[in] other Vector to check equality with * \param[in] ulp The desired floating point precision in ULPs * \return True if equal, else false */ template<typename U = T, typename = typename std::enable_if<std::is_floating_point<U>::value>::type> bool equals(const Vector<T, N>& other, const int ulp) const; friend bool operator==(const Vector<T, N>& lhs, const Vector<T, N>& rhs) { return lhs.equals(rhs); } friend bool operator!=(const Vector<T, N>& lhs, const Vector<T, N>& rhs) { return !(lhs.equals(rhs)); } /*! * \brief Calculate the inner vector product (dot product) * \param[in] v1 Vector to take dot product of * \param[in] v2 Vector to take dot product of * \return Vector dot product */ static T dot(const Vector<T, N>& v1, const Vector<T, N>& v2); /*! * \brief Calculate the reflection direction * \param[in] incident Incident vector * \param[in] surface_normal Surface normal vector * \return Reflection of incident over the normal */ static Vector<T, N> reflect(const Vector<T, N>& incident, const Vector<T, N>& surface_normal); /*! * \brief Calculate the refraction direction * \param[in] incident Incident vector * \param[in] surface_normal Surface normal vector * \param[in] eta Ratio of refraction * \return Refraction of the indedent over the normal */ static Vector<T, N> refract(const Vector<T, N>& incident, const Vector<T, N>& surface_normal, const T eta); /*! * \brief Linearly interpolate between two vectors * \param[in] start Start vector * \param[in] end End vector * \param[in] t Value to interpolate by * \return Interpolated vector */ static Vector<T, N> lerp(const Vector<T, N>& start, const Vector<T, N>& end, const T t); /*! * \brief Calculate the outer vector product (cross product) of a * 2-dimensional vector * \tparam U Used to determine if this is a 2-dimensional vector * \param[in] v1 Vector to take outer product of * \param[in] v2 Vector to take outer product of * \return 2-dimensional vector cross product */ template<typename U = T, typename = typename std::enable_if<N == 2, U>::type> static T cross(const Vector<T, N>& v1, const Vector<T, N>& v2); /*! * \brief Calculate the outer vector product (cross product) of a * 3-dimensional vector * \tparam U Used to determine if this is a 3-dimensional vector * \param[in] v1 Vector to take outer product of * \param[in] v2 Vector to take outer product of * \return 3-dimensional vector cross product */ template<typename U = T, typename = typename std::enable_if<N == 3, U>::type> static Vector<T, N> cross(const Vector<T, N>& v1, const Vector<T, N>& v2); friend std::ostream& operator<<(std::ostream& os, const Vector<T, N>& vec) { os << "<"; for (std::size_t i = 0; i < N; i++) { if (i > 0) { os << ","; } os << vec.data[i]; } os << ">"; return os; } }; } } #include <vmath/core/vector.inl> #ifndef VMATH_HEADER_ONLY extern template class vmath::core::Vector<float, 2>; extern template class vmath::core::Vector<float, 3>; extern template class vmath::core::Vector<float, 4>; extern template class vmath::core::Vector<double, 2>; extern template class vmath::core::Vector<double, 3>; extern template class vmath::core::Vector<double, 4>; extern template class vmath::core::Vector<long double, 2>; extern template class vmath::core::Vector<long double, 3>; extern template class vmath::core::Vector<long double, 4>; extern template class vmath::core::Vector<bool, 2>; extern template class vmath::core::Vector<bool, 3>; extern template class vmath::core::Vector<bool, 4>; extern template class vmath::core::Vector<int, 2>; extern template class vmath::core::Vector<int, 3>; extern template class vmath::core::Vector<int, 4>; extern template class vmath::core::Vector<unsigned int, 2>; extern template class vmath::core::Vector<unsigned int, 3>; extern template class vmath::core::Vector<unsigned int, 4>; #endif #endif
29.304189
110
0.685356
[ "object", "vector" ]
4cda9fccc5588d6e8c3ff01bddb687455d5d6586
1,579
cpp
C++
aws-cpp-sdk-ec2/source/model/ImportInstanceRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-ec2/source/model/ImportInstanceRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-ec2/source/model/ImportInstanceRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/ec2/model/ImportInstanceRequest.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> using namespace Aws::EC2::Model; using namespace Aws::Utils; ImportInstanceRequest::ImportInstanceRequest() : m_descriptionHasBeenSet(false), m_diskImagesHasBeenSet(false), m_dryRun(false), m_dryRunHasBeenSet(false), m_launchSpecificationHasBeenSet(false), m_platform(PlatformValues::NOT_SET), m_platformHasBeenSet(false) { } Aws::String ImportInstanceRequest::SerializePayload() const { Aws::StringStream ss; ss << "Action=ImportInstance&"; if(m_descriptionHasBeenSet) { ss << "Description=" << StringUtils::URLEncode(m_description.c_str()) << "&"; } if(m_diskImagesHasBeenSet) { unsigned diskImagesCount = 1; for(auto& item : m_diskImages) { item.OutputToStream(ss, "DiskImage.", diskImagesCount, ""); diskImagesCount++; } } if(m_dryRunHasBeenSet) { ss << "DryRun=" << std::boolalpha << m_dryRun << "&"; } if(m_launchSpecificationHasBeenSet) { m_launchSpecification.OutputToStream(ss, "LaunchSpecification"); } if(m_platformHasBeenSet) { ss << "Platform=" << PlatformValuesMapper::GetNameForPlatformValues(m_platform) << "&"; } ss << "Version=2016-11-15"; return ss.str(); } void ImportInstanceRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const { uri.SetQueryString(SerializePayload()); }
23.567164
91
0.69981
[ "model" ]
4cdf2a8009fb45342264ad18305c685e451b06c7
1,103
cpp
C++
test/unit_tests/common/adt/vec_ptr_test.cpp
mbeckem/tiro
b3d729fce46243f25119767c412c6db234c2d938
[ "MIT" ]
10
2020-01-23T20:41:19.000Z
2021-12-28T20:24:44.000Z
test/unit_tests/common/adt/vec_ptr_test.cpp
mbeckem/tiro
b3d729fce46243f25119767c412c6db234c2d938
[ "MIT" ]
22
2021-03-25T16:22:08.000Z
2022-03-17T12:50:38.000Z
test/unit_tests/common/adt/vec_ptr_test.cpp
mbeckem/tiro
b3d729fce46243f25119767c412c6db234c2d938
[ "MIT" ]
null
null
null
#include <catch2/catch.hpp> #include "common/adt/vec_ptr.hpp" namespace tiro::test { TEST_CASE("VecPtr basic operations", "[vec_ptr]") { std::vector<int> vec{1, 2, 3}; VecPtr v0(vec, 0); REQUIRE(v0.valid()); REQUIRE(v0.get() == &vec[0]); REQUIRE(*v0 == 1); REQUIRE(v0 == v0); VecPtr v2(vec, 2); REQUIRE(v2.valid()); REQUIRE(v2.get() == &vec[2]); REQUIRE(*v2 == 3); REQUIRE(!(v0 == v2)); REQUIRE(v0 != v2); REQUIRE(v0 < v2); REQUIRE(!(v0 > v2)); REQUIRE(v0 <= v2); REQUIRE(!(v0 >= v2)); } TEST_CASE("Invalid VecPtr behaviour", "[vec_ptr]") { VecPtr<int, std::vector<int>> invalid1 = nullptr; VecPtr<int, std::vector<int>> invalid2; REQUIRE(!invalid1.valid()); REQUIRE(!invalid2.valid()); REQUIRE(invalid1.get() == nullptr); REQUIRE(invalid2.get() == nullptr); REQUIRE(invalid1 == invalid2); REQUIRE(!(invalid1 != invalid2)); REQUIRE(!(invalid1 < invalid2)); REQUIRE(!(invalid1 > invalid2)); REQUIRE(invalid1 >= invalid2); REQUIRE(invalid1 <= invalid2); } } // namespace tiro::test
22.979167
53
0.587489
[ "vector" ]
4ce03236647174caa227160ffa5dad3091b3211a
33,174
cpp
C++
src/mpepc/evaluation/social_norm_results.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
3
2020-03-05T23:56:14.000Z
2021-02-17T19:06:50.000Z
src/mpepc/evaluation/social_norm_results.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-07T01:23:47.000Z
2021-03-07T01:23:47.000Z
src/mpepc/evaluation/social_norm_results.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-03T07:54:16.000Z
2021-03-03T07:54:16.000Z
/* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ /** @file * @author Collin Johnson * * social_norm_results is a program to pull information from one or more MPEPC logs and produce plots and figures that * evaluate the success of the social norms planning vs. regular MPEPC. * * social_norm_results requires specifying a file with the logs to process -- one per line -- format: * * 'social'/'regular' log_name local_topo_map * * The produced results are: * * - Plot of the histogram over normalized dist for path travel * - Plot of the histogram over normalized dist for area transitions * - File containing: * - stats for path interactions * - stats for place interactions * - stats for overall interactions * * Results are produced for social vs. regular logs. */ #include "core/angle_functions.h" #include "hssh/local_topological/areas/serialization.h" #include "hssh/local_topological/local_topo_map.h" #include "math/t_test.h" #include "math/z_test.h" #include "mpepc/evaluation/interaction.h" #include "mpepc/evaluation/mpepc_log.h" #include "mpepc/evaluation/social_force.h" #include "mpepc/evaluation/utils.h" #include "mpepc/social/social_norm_utils.h" #include "mpepc/social/topo_situation.h" #include "mpepc/training/agent_state.h" #include "utils/command_line.h" #include "utils/histogram.h" #include "utils/histogram_2d.h" #include "utils/serialized_file_io.h" #include <algorithm> #include <boost/accumulators/framework/accumulator_set.hpp> #include <boost/accumulators/statistics/max.hpp> #include <boost/accumulators/statistics/mean.hpp> #include <boost/accumulators/statistics/median.hpp> #include <boost/accumulators/statistics/min.hpp> #include <boost/accumulators/statistics/stats.hpp> #include <boost/accumulators/statistics/variance.hpp> #include <boost/range/algorithm_ext.hpp> #include <boost/range/as_array.hpp> #include <boost/tuple/tuple.hpp> #include <cstdlib> #include <gnuplot-iostream.h> #include <iostream> using namespace vulcan; using namespace vulcan::mpepc; using namespace boost::accumulators; using StatsAcc = accumulator_set<double, stats<tag::min, tag::max, tag::mean, tag::variance, tag::median>>; const std::string kDistArg("max-dist"); const std::string kConeArg("cone-angle"); const std::string kLogsArg("logs"); const std::string kTrainArg("train"); const int kNumHistBins = 20; struct StatResults { std::string name; double min; double max; double mean; double stdDev; double median; }; struct SituationResults { TopoSituationResponse situation; StatsAcc forceAcc; StatsAcc blameAcc; StatsAcc distPassingAcc; StatsAcc speedPassingAcc; int leftPassCount = 0; int rightPassCount = 0; }; struct VersionResults { utils::Histogram pathDist; utils::Histogram gwyDist; utils::Histogram2D pathInteractions; utils::Histogram pathDistAgent; utils::Histogram gwyDistAgent; std::vector<SituationResults> situations; SituationResults pathResults; SituationResults oncomingResults; SituationResults overtakingResults; SituationResults beingPassedResults; std::string basename; std::string version; VersionResults(void) : pathDist(0.0, 1.0, kNumHistBins) , gwyDist(0.0, 1.0, kNumHistBins) , pathInteractions(0.0, 1.0, 0.0, 1.0, kNumHistBins) , pathDistAgent(0.0, 1.0, kNumHistBins) , gwyDistAgent(0.0, 1.0, kNumHistBins) { } }; struct OverallResults { VersionResults socialResults; VersionResults regularResults; MotionObs agentObsPath; MotionObs agentObsTrans; }; void add_distance_results(const ResultsLog& log, VersionResults& results); void add_interaction_results(const ResultsLog& log, double maxDistance, double ignoreConeAngle, VersionResults& results); void add_motion_interaction_results(const std::vector<interaction_t>& interactions, const hssh::LocalTopoMap& topoMap, VersionResults& results); void add_social_forces_results(const std::vector<interaction_t>& interactions, VersionResults& results); std::vector<passing_object_t> prune_passing_events(const std::vector<passing_object_t>& passes); void accumulate_pass_results(const std::vector<passing_object_t>& passes, SituationResults& results); StatResults populate_stat_results(StatsAcc& acc, const std::string& name); void produce_results(OverallResults& results); void produce_path_dist_results(OverallResults& results); void produce_gwy_dist_results(OverallResults& results); void produce_interaction_results(VersionResults& results); void produce_situation_results(SituationResults& results, const std::string& name); SituationResults* find_situation(const interaction_t& interaction, std::vector<SituationResults>& situations); void draw_dist_result_histogram(utils::Histogram& regularHist, utils::Histogram& socialHist, const std::string& name); void histogram_analysis(utils::Histogram& regularHist, utils::Histogram& socialHist, utils::Histogram& trainingHist, const std::string& name); void draw_interaction_histogram(utils::Histogram2D& hist, const std::string& title, double maxCbrange); void passing_analysis(SituationResults& regularPass, SituationResults& socialPass, const std::string& name); double kl_divergence(const utils::Histogram& from, const utils::Histogram& to); std::ostream& operator<<(std::ostream& out, const StatResults& results); int main(int argc, char** argv) { std::vector<utils::command_line_argument_t> args = { {kDistArg, "Maximum distance for an interaction (meters)", true, "5"}, {kConeArg, "Half angle of the ignore cone behind the robot (degrees)", true, "30"}, {kLogsArg, "File containing the logs to process", false, ""}, {kTrainArg, "Base name for training *obs and .situ file", false, ""}}; utils::CommandLine cmdLine(argc, argv, args); if (!cmdLine.verify()) { cmdLine.printHelp(); exit(EXIT_FAILURE); } double maxDistance = std::strtod(cmdLine.argumentValue(kDistArg).c_str(), 0); double ignoreConeAngle = wrap_to_pi(std::strtod(cmdLine.argumentValue(kConeArg).c_str(), 0) * M_PI / 180.0); ignoreConeAngle = angle_diff_abs(M_PI, ignoreConeAngle); auto logs = load_results_logs(cmdLine.argumentValue(kLogsArg)); OverallResults allResults; allResults.socialResults.basename = cmdLine.argumentValue(kLogsArg); allResults.socialResults.version = version_to_public_name(MPEPCVersion::social); allResults.regularResults.basename = cmdLine.argumentValue(kLogsArg); allResults.regularResults.version = version_to_public_name(MPEPCVersion::regular); for (auto& log : logs) { VersionResults* results = nullptr; switch (log.version) { case MPEPCVersion::regular: results = &allResults.regularResults; break; case MPEPCVersion::social: results = &allResults.socialResults; break; case MPEPCVersion::unknown: std::cerr << "ERROR: Unknown MPEPC version for log.\n"; break; } if (results) { add_distance_results(log, *results); add_interaction_results(log, maxDistance, ignoreConeAngle, *results); } } // Load training observations auto trainName = cmdLine.argumentValue(kTrainArg); // Check if there are .mobs for the log auto observations = load_motion_observations(trainName + ".pobs"); for (auto& areaToObs : observations) { boost::push_back(allResults.agentObsPath, boost::as_array(areaToObs.second)); } observations = load_motion_observations(trainName + ".tobs"); for (auto& areaToObs : observations) { boost::push_back(allResults.agentObsTrans, boost::as_array(areaToObs.second)); } std::cout << "Found " << allResults.agentObsPath.size() << " path observations and " << allResults.agentObsTrans.size() << " transition observations.\n"; produce_results(allResults); return 0; } void add_distance_results(const ResultsLog& log, VersionResults& results) { MPEPCLog logData(log.logName); const int64_t kChunkDurationUs = 5000000; // Process the log in chunks to ensure we don't run out of memory trying to load the big planning logs for (int64_t startTimeUs = 0; startTimeUs < logData.durationUs(); startTimeUs += kChunkDurationUs) { logData.loadTimeRange(startTimeUs, startTimeUs + (kChunkDurationUs * 2)); for (auto& state : boost::make_iterator_range(logData.beginMotionState(startTimeUs), logData.endMotionState(startTimeUs + kChunkDurationUs))) { auto agent = create_agent_for_robot(state, log.map); // If about to transition, process as a gateway distance if (is_about_to_transition(agent, log.map, 0.25)) { auto distance = normalized_position_gateway(agent, log.map); if (distance >= 0.0) { results.gwyDist.addValue(distance); } } // If on a path, also a path distance here if (log.map.pathSegmentWithId(agent.areaId)) { auto distance = normalized_position_path(agent, log.map); if (distance >= 0.0) { results.pathDist.addValue(distance); } } } } } void add_interaction_results(const ResultsLog& log, double maxDistance, double ignoreConeAngle, VersionResults& results) { MPEPCLog logData(log.logName); // TODO: Make lateral bins a parameter? auto interactions = find_interactions(logData, log.map, 3, maxDistance, ignoreConeAngle); add_motion_interaction_results(interactions, log.map, results); add_social_forces_results(interactions, results); } void add_motion_interaction_results(const std::vector<interaction_t>& interactions, const hssh::LocalTopoMap& topoMap, VersionResults& results) { // For every other agent in the environment that the robot interacts with, save the results of their behavior for (auto& interaction : interactions) { double robotDistance = normalized_position_path(interaction.robotAgent, topoMap); for (auto& agent : interaction.agents) { double vel = std::sqrt(std::pow(agent.state.xVel, 2.0) + std::pow(agent.state.yVel, 2.0)); if ((vel < 0.25) || (vel > 2.0)) { continue; } // If about to transition, process as a gateway distance if (is_about_to_transition(agent, topoMap, 0.25)) { auto distance = normalized_position_gateway(agent, topoMap); if (distance >= 0.0) { results.gwyDistAgent.addValue(distance); } } // If on a path, also a path distance if (topoMap.pathSegmentWithId(agent.areaId)) { auto distance = normalized_position_path(agent, topoMap); if (distance >= 0.0) { results.pathDistAgent.addValue(distance); results.pathInteractions.addValue(distance, robotDistance); } } } } } void add_social_forces_results(const std::vector<interaction_t>& interactions, VersionResults& results) { social_forces_params_t params; // Use defaults, which are taken from Ferrer's paper. auto forces = trajectory_social_forces(interactions, params); std::vector<passing_object_t> pathPasses; std::vector<passing_object_t> oncomingPasses; std::vector<passing_object_t> overtakingPasses; std::vector<passing_object_t> beingPassedPasses; for (std::size_t n = 0; n < forces.size(); ++n) { auto& f = forces[n]; auto& interaction = interactions[n]; SituationResults* situResults = find_situation(interaction, results.situations); if (f.isInteracting && interaction.pathSituation) { results.pathResults.forceAcc(f.force); results.pathResults.blameAcc(f.blame); if (situResults) { situResults->forceAcc(f.force); situResults->blameAcc(f.blame); } } // Find the closest passing object auto minIt = std::min_element(f.passingObj.begin(), f.passingObj.end(), [](const auto& lhs, const auto& rhs) { return lhs.passingDist < rhs.passingDist; }); bool isPassing = minIt != f.passingObj.end(); if (isPassing && interaction.pathSituation) { // Account for all passes boost::push_back(pathPasses, boost::as_array(f.passingObj)); auto bins = interaction.pathSituation->situation(); std::size_t towardCount = std::count_if(bins.begin(), bins.end(), [](PathSituation::BinState state) { return state == PathSituation::toward; }); // If someone is coming toward us, then it is an oncoming pass if (towardCount > 0) { boost::push_back(oncomingPasses, boost::as_array(f.passingObj)); results.oncomingResults.forceAcc(f.force); results.oncomingResults.blameAcc(f.blame); } // Otherwise, the relative speed determine who was doing the passing else if (minIt->passingSpeed > 0.0) // Robot was overtaking the agent { boost::push_back(overtakingPasses, boost::as_array(f.passingObj)); results.overtakingResults.forceAcc(f.force); results.overtakingResults.blameAcc(f.blame); } // Robot is being passed else { boost::push_back(beingPassedPasses, boost::as_array(f.passingObj)); results.beingPassedResults.forceAcc(f.force); results.beingPassedResults.blameAcc(f.blame); } if (situResults) { situResults->distPassingAcc(minIt->passingDist); situResults->speedPassingAcc(minIt->passingSpeed); } } } pathPasses = prune_passing_events(pathPasses); accumulate_pass_results(pathPasses, results.pathResults); std::cout << "Found " << pathPasses.size() << " path passes.\n"; oncomingPasses = prune_passing_events(oncomingPasses); accumulate_pass_results(oncomingPasses, results.oncomingResults); std::cout << "Found " << oncomingPasses.size() << " oncoming passes.\n"; overtakingPasses = prune_passing_events(overtakingPasses); accumulate_pass_results(overtakingPasses, results.overtakingResults); std::cout << "Found " << overtakingPasses.size() << " overtaking passes.\n"; beingPassedPasses = prune_passing_events(beingPassedPasses); accumulate_pass_results(beingPassedPasses, results.beingPassedResults); std::cout << "Found " << beingPassedPasses.size() << " being passed passes.\n"; } std::vector<passing_object_t> prune_passing_events(const std::vector<passing_object_t>& passes) { std::vector<passing_object_t> pruned; for (auto passIt = passes.begin(); passIt < passes.end();) // increment happens internally { // Find the first object not near the auto passEnd = std::find_if(passIt, passes.end(), [passIt](const auto& pass) { return pass.id != passIt->id; }); // Find the closest point during passing auto minIt = std::min_element(passIt, passEnd, [](const auto& lhs, const auto& rhs) { return lhs.passingDist < rhs.passingDist; }); auto totalDist = std::accumulate(passIt, passEnd, 0.0, [](double total, const auto& pass) { return total + pass.passingDist; }); // Create a summarized view of the pass, where we consider the mean of the passing distance, since boundary // estimation is noisy and imprecise passing_object_t obj = *minIt; obj.passingDist = totalDist / std::distance(passIt, passEnd); pruned.push_back(obj); passIt = passEnd; // increment the search } return pruned; } void accumulate_pass_results(const std::vector<passing_object_t>& passes, SituationResults& results) { for (auto& pass : passes) { results.distPassingAcc(pass.passingDist); results.speedPassingAcc(pass.passingSpeed); if (pass.passingSide == math::RectSide::left) { ++results.leftPassCount; } else if (pass.passingSide == math::RectSide::right) { ++results.rightPassCount; } } } StatResults populate_stat_results(StatsAcc& acc, const std::string& name) { StatResults results; results.name = name; results.min = min(acc); results.max = max(acc); results.mean = mean(acc); results.stdDev = std::sqrt(variance(acc)); results.median = median(acc); return results; } void produce_results(OverallResults& results) { produce_path_dist_results(results); produce_gwy_dist_results(results); produce_interaction_results(results.socialResults); produce_interaction_results(results.regularResults); passing_analysis(results.regularResults.pathResults, results.socialResults.pathResults, "Analysis of All Passing"); passing_analysis(results.regularResults.oncomingResults, results.socialResults.oncomingResults, "Analysis of Oncoming Passing"); passing_analysis(results.regularResults.overtakingResults, results.socialResults.overtakingResults, "Analysis of Overtaking Passing"); results.regularResults.pathInteractions.normalize(); results.socialResults.pathInteractions.normalize(); double maxInteraction = std::max(results.regularResults.pathInteractions.max(), results.socialResults.pathInteractions.max()); draw_interaction_histogram(results.regularResults.pathInteractions, results.regularResults.version + " Robot-Pedestrian Path Interaction Locations", maxInteraction); draw_interaction_histogram(results.socialResults.pathInteractions, results.socialResults.version + " Robot-Pedestrian Path Interaction Locations", maxInteraction); } void produce_path_dist_results(OverallResults& results) { utils::Histogram trainingData(0.0, 1.0, kNumHistBins); for (auto& obs : results.agentObsPath) { trainingData.addValue(obs.normDist); } draw_dist_result_histogram(results.regularResults.pathDist, results.socialResults.pathDist, "Distribution of Lateral Path Position"); // Draw twice because it often fails the first time, since it is the first Gnuplot instance to open draw_dist_result_histogram(results.regularResults.pathDist, results.socialResults.pathDist, "Distribution of Lateral Path Position"); histogram_analysis(results.regularResults.pathDist, results.socialResults.pathDist, trainingData, "Analysis of Path Distance"); if ((results.regularResults.pathDistAgent.numValues() > 0) && (results.socialResults.pathDistAgent.numValues() > 0)) { std::cout << "Found " << results.regularResults.pathDistAgent.numValues() << " regular path agents and " << results.socialResults.pathDistAgent.numValues() << " social path agents.\n"; draw_dist_result_histogram(results.regularResults.pathDistAgent, results.socialResults.pathDistAgent, "Distribution of Lateral Path Position for Pedestrians"); histogram_analysis(results.regularResults.pathDistAgent, results.socialResults.pathDistAgent, trainingData, "Analysis of Agent Path Distance"); } } void produce_gwy_dist_results(OverallResults& results) { utils::Histogram trainingData(0.0, 1.0, kNumHistBins); if (!results.agentObsTrans.empty()) { for (auto& obs : results.agentObsTrans) { trainingData.addValue(obs.normDist); } } draw_dist_result_histogram(results.regularResults.gwyDist, results.socialResults.gwyDist, "Distribution of Lateral Transition Position"); histogram_analysis(results.regularResults.gwyDist, results.socialResults.gwyDist, trainingData, "Analysis of Transition Distance"); if ((results.regularResults.gwyDistAgent.numValues() > 0) && (results.socialResults.gwyDistAgent.numValues() > 0)) { std::cout << "Found " << results.regularResults.gwyDistAgent.numValues() << " regular gateway agents and " << results.socialResults.gwyDistAgent.numValues() << " social gateway agents.\n"; draw_dist_result_histogram(results.regularResults.gwyDistAgent, results.socialResults.gwyDistAgent, "Distribution of Lateral Transition Position for Pedestrians"); histogram_analysis(results.regularResults.gwyDistAgent, results.socialResults.gwyDistAgent, trainingData, "Analysis of Agent Transition Distance"); } } void produce_interaction_results(VersionResults& results) { produce_situation_results(results.pathResults, results.version + " path passing"); produce_situation_results(results.oncomingResults, results.version + " oncoming passing"); produce_situation_results(results.overtakingResults, results.version + " overtaking passing"); produce_situation_results(results.beingPassedResults, results.version + " being passed passing"); // for(auto& situation : results.situations) // { // std::cout << results.version << " -- " << situation.situation << " :" // << " count: " << count(situation.forceAcc) << "\n" // << populate_stat_results(situation.forceAcc, "Force") << '\n' // << populate_stat_results(situation.blameAcc, "Blame") << '\n'; // // if(count(situation.distPassingAcc) > 0) // { // std::cout << "Passing count: " << count(situation.distPassingAcc) << '\n' // << populate_stat_results(situation.distPassingAcc, "Passing Distance (m)") << '\n' // << populate_stat_results(situation.speedPassingAcc, "Passing Speed (m/s)") << '\n'; // } // } } void produce_situation_results(SituationResults& results, const std::string& name) { auto forceStats = populate_stat_results(results.forceAcc, "Force"); auto blameStats = populate_stat_results(results.blameAcc, "Blame"); auto distPassingStats = populate_stat_results(results.distPassingAcc, "Passing Distance (m)"); auto speedPassingStats = populate_stat_results(results.speedPassingAcc, "Passing Speed (m/s)"); std::cout << "\n========== " << name << " ==========\n\n" << forceStats << '\n' << blameStats << '\n'; if (count(results.distPassingAcc) > 0) { std::cout << "Passing count:" << count(results.distPassingAcc) << '\n' << distPassingStats << '\n' << speedPassingStats << '\n'; } int totalPass = results.leftPassCount + results.rightPassCount; if (totalPass > 0) { std::cout << "Left pass %: " << (results.leftPassCount / static_cast<double>(totalPass)) << '\n' << "Right pass %: " << (results.rightPassCount / static_cast<double>(totalPass)) << '\n'; } } SituationResults* find_situation(const interaction_t& interaction, std::vector<SituationResults>& situations) { if (!interaction.pathSituation && !interaction.placeSituation) { return nullptr; } // See if this situation matches something already for (auto& s : situations) { if (interaction.pathSituation && s.situation.isResponseForSituation(*interaction.pathSituation)) { return &s; } else if (interaction.placeSituation && s.situation.isResponseForSituation(*interaction.placeSituation)) { return &s; } } // Otherwise, add a new situation SituationResults r; std::vector<double> nullDist(2, 0.5); // don't actually care about these if (interaction.pathSituation) { r.situation = TopoSituationResponse(*interaction.pathSituation, nullDist); } else { assert(interaction.placeSituation); r.situation = TopoSituationResponse(*interaction.placeSituation, nullDist); } situations.push_back(r); return &situations.back(); } void draw_dist_result_histogram(utils::Histogram& regularHist, utils::Histogram& socialHist, const std::string& name) { Gnuplot plot; plot << "set yrange [0:25]\n"; plot << "set xrange [0:1]\n"; plot << "set style fill solid border lc black\n"; plot << "set title '" << name << "'\n"; plot << "set xlabel 'Normalized Dist'\n"; plot << "set ylabel '% of trajectory'\n"; std::vector<uint32_t> rawColors = { (255U << 24) | (135U << 16) | (206U << 8) | (235U), (255U << 24) | (255U << 16) | (99U << 8) | (71U), (255U << 24) | (106U << 16) | (90U << 8) | (205U), }; std::vector<std::string> colors; for (auto& c : rawColors) { std::ostringstream str; str << '#' << std::hex << ((c >> 16) & 0xFF) << ((c >> 8) & 0xFF) << (c & 0xFF); colors.push_back(str.str()); } const std::string lineStyle(" lw 2 pi 1 ps 1"); plot << "plot " << "'-' using 2:1 with lp lt 5 lc rgb \"" << colors[0] << "\"" << lineStyle << " title '" << version_to_public_name(MPEPCVersion::regular) << "'" << ", '-' using 2:1 with lp lt 7 dt 2 lc rgb \"" << colors[1] << "\"" << lineStyle << " title '" << version_to_public_name(MPEPCVersion::social) << "'"; plot << std::endl; // Data is col 1 = value, col 2 = tic value std::vector<double> regularVals; std::vector<double> socialVals; std::vector<double> xtics; regularHist.normalize(); for (auto& bin : regularHist) { regularVals.push_back(bin.count * 100); xtics.push_back(bin.minValue); } socialHist.normalize(); xtics.clear(); for (auto& bin : socialHist) { socialVals.push_back(bin.count * 100); xtics.push_back(bin.minValue); } plot.send1d(boost::make_tuple(regularVals, xtics)); plot.send1d(boost::make_tuple(socialVals, xtics)); sleep(1); } void histogram_analysis(utils::Histogram& regularHist, utils::Histogram& socialHist, utils::Histogram& trainingHist, const std::string& name) { regularHist.normalize(); socialHist.normalize(); trainingHist.normalize(); auto regularDist = regularHist.toGaussian(); auto socialDist = socialHist.toGaussian(); math::t_test_sample_t sampleRegular = {regularDist.mean(), regularDist.variance(), static_cast<int>(regularHist.numValues())}; math::t_test_sample_t sampleSocial = {socialDist.mean(), socialDist.variance(), static_cast<int>(socialHist.numValues())}; auto tTest = math::independent_t_test(sampleSocial, sampleRegular, 0.05); std::cout << "\n\n===== " << name << " =====\n" << "KLD to regular: " << kl_divergence(trainingHist, regularHist) << '\n' << "KLD to social: " << kl_divergence(trainingHist, socialHist) << '\n' << "Regular dist (mean, var): " << regularDist.mean() << ',' << regularDist.variance() << '\n' << "Social dist (mean, var): " << socialDist.mean() << ',' << socialDist.variance() << '\n'; // A value being greater than another here means it moves to the right of the other std::cout << "T-test results:\n" << "Num samples: Social: " << sampleSocial.numSamples << " Regular: " << sampleRegular.numSamples << '\n' << "Dists are different: " << tTest.areDifferent << " p-value:" << tTest.pValueDifferent << " t-value: " << tTest.tValue << '\n' << "Social right of regular: " << tTest.isGreater << " p-value: " << tTest.pValueGreater << " t-value: " << tTest.tValue << '\n' << "Social left of regular: " << tTest.isLess << " p-value: " << tTest.pValueLess << " t-value: " << tTest.tValue << '\n'; std::cout << "====================\n\n"; } void draw_interaction_histogram(utils::Histogram2D& hist, const std::string& title, double maxCbrange) { hist.plot(title, "Pedestrian Normalized Path Distance", "Robot Normalized Path Distance", maxCbrange); } void passing_analysis(SituationResults& regularPass, SituationResults& socialPass, const std::string& name) { std::cout << "\n\n===== " << name << " =====\n"; math::z_test_sample_t regular = {regularPass.leftPassCount, regularPass.leftPassCount + regularPass.rightPassCount}; math::z_test_sample_t social = {socialPass.leftPassCount, socialPass.leftPassCount + socialPass.rightPassCount}; auto zTest = math::binomial_proportion_z_test(social, regular, 0.05); // A value being greater than another here means it moves to the right of the other std::cout << "Z-test results:\n" << "Num samples: Social: " << social.numSamples << " Regular: " << regular.numSamples << '\n' << "Dists are different: " << zTest.areDifferent << " p-value:" << zTest.pValueDifferent << " z-value: " << zTest.zValue << '\n' << "Social more left passes: " << zTest.isGreater << " p-value: " << zTest.pValueGreater << " z-value: " << zTest.zValue << '\n' << "Social more right passes: " << zTest.isLess << " p-value: " << zTest.pValueLess << " z-value: " << zTest.zValue << '\n'; std::cout << "====================\n\n"; math::t_test_sample_t sampleRegular = {mean(regularPass.distPassingAcc), variance(regularPass.distPassingAcc), static_cast<int>(count(regularPass.distPassingAcc))}; math::t_test_sample_t sampleSocial = {mean(socialPass.distPassingAcc), variance(socialPass.distPassingAcc), static_cast<int>(count(socialPass.distPassingAcc))}; auto tTest = math::independent_t_test(sampleSocial, sampleRegular, 0.05); // A value being greater than another here means it moves to the right of the other std::cout << "T-test results for passing distance:\n" << "Num samples: Social: " << sampleSocial.numSamples << " Regular: " << sampleRegular.numSamples << '\n' << "Dists are different: " << tTest.areDifferent << " p-value:" << tTest.pValueDifferent << " t-value: " << tTest.tValue << '\n' << "Social passes further: " << tTest.isGreater << " p-value: " << tTest.pValueGreater << " t-value: " << tTest.tValue << '\n' << "Social passes closer: " << tTest.isLess << " p-value: " << tTest.pValueLess << " t-value: " << tTest.tValue << '\n'; std::cout << "====================\n\n"; } double kl_divergence(const utils::Histogram& from, const utils::Histogram& to) { assert(from.size() == to.size()); const double kMinProb = 1e-4; double kld = 0.0; for (std::size_t n = 0; n < from.size(); ++n) { double fromProb = std::max(from.bin(n).count, kMinProb); double toProb = std::max(to.bin(n).count, kMinProb); kld += toProb * std::log(toProb / fromProb); } return kld; } std::ostream& operator<<(std::ostream& out, const StatResults& results) { out << std::fixed << std::setprecision(3) << results.name << '\t' << results.min << '\t' << results.max << '\t' << results.mean << '\t' << results.stdDev << '\t' << results.median; return out; }
39.968675
120
0.633116
[ "object", "vector", "solid" ]
4cef7c07bc74d0a95c4f556af229491e4ee3278d
6,104
hpp
C++
cpp/include/raft/common/detail/nvtx.hpp
kaatish/raft
f487da7f2585e60f0a11aef43ce17c990cc6145a
[ "Apache-2.0" ]
65
2020-04-25T12:05:44.000Z
2022-03-26T03:45:26.000Z
cpp/include/raft/common/detail/nvtx.hpp
kaatish/raft
f487da7f2585e60f0a11aef43ce17c990cc6145a
[ "Apache-2.0" ]
527
2019-06-21T06:07:23.000Z
2022-03-31T23:13:52.000Z
cpp/include/raft/common/detail/nvtx.hpp
kaatish/raft
f487da7f2585e60f0a11aef43ce17c990cc6145a
[ "Apache-2.0" ]
78
2020-04-28T02:43:10.000Z
2022-02-07T08:13:32.000Z
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <rmm/cuda_stream_view.hpp> namespace raft::common::nvtx::detail { #ifdef NVTX_ENABLED #include <cstdint> #include <cstdlib> #include <mutex> #include <nvToolsExt.h> #include <string> #include <type_traits> #include <unordered_map> /** * @brief An internal struct to store associated state with the color * generator */ struct color_gen_state { /** collection of all tagged colors generated so far */ static inline std::unordered_map<std::string, uint32_t> all_colors_; /** mutex for accessing the above map */ static inline std::mutex map_mutex_; /** saturation */ static inline constexpr float kS = 0.9f; /** value */ static inline constexpr float kV = 0.85f; /** golden ratio */ static inline constexpr float kPhi = 1.61803f; /** inverse golden ratio */ static inline constexpr float kInvPhi = 1.f / kPhi; }; // all h, s, v are in range [0, 1] // Ref: http://en.wikipedia.org/wiki/HSL_and_HSV#Converting_to_RGB inline auto hsv2rgb(float h, float s, float v) -> uint32_t { uint32_t out = 0xff000000u; if (s <= 0.0f) { return out; } // convert hue from [0, 1] range to [0, 360] float h_deg = h * 360.f; if (0.f > h_deg || h_deg >= 360.f) h_deg = 0.f; h_deg /= 60.f; int h_range = static_cast<int>(h_deg); float h_mod = h_deg - h_range; float x = v * (1.f - s); float y = v * (1.f - (s * h_mod)); float z = v * (1.f - (s * (1.f - h_mod))); float r, g, b; switch (h_range) { case 0: r = v; g = z; b = x; break; case 1: r = y; g = v; b = x; break; case 2: r = x; g = v; b = z; break; case 3: r = x; g = y; b = v; break; case 4: r = z; g = x; b = v; break; case 5: default: r = v; g = x; b = y; break; } out |= (uint32_t(r * 256.f) << 16); out |= (uint32_t(g * 256.f) << 8); out |= uint32_t(b * 256.f); return out; } /** * @brief Helper method to generate 'visually distinct' colors. * Inspired from https://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/ * However, if an associated tag is passed, it will look up in its history for * any generated color against this tag and if found, just returns it, else * generates a new color, assigns a tag to it and stores it for future usage. * Such a thing is very useful for nvtx markers where the ranges associated * with a specific tag should ideally get the same color for the purpose of * visualizing it on nsight-systems timeline. * @param tag look for any previously generated colors with this tag or * associate the currently generated color with it * @return returns 32b RGB integer with alpha channel set of 0xff */ inline auto generate_next_color(const std::string& tag) -> uint32_t { // std::unordered_map<std::string, uint32_t> color_gen_state::all_colors_; // std::mutex color_gen_state::map_mutex_; std::lock_guard<std::mutex> guard(color_gen_state::map_mutex_); if (!tag.empty()) { auto itr = color_gen_state::all_colors_.find(tag); if (itr != color_gen_state::all_colors_.end()) { return itr->second; } } auto h = static_cast<float>(rand()) / static_cast<float>(RAND_MAX); h += color_gen_state::kInvPhi; if (h >= 1.f) h -= 1.f; auto rgb = hsv2rgb(h, color_gen_state::kS, color_gen_state::kV); if (!tag.empty()) { color_gen_state::all_colors_[tag] = rgb; } return rgb; } template <typename Domain, typename = Domain> struct domain_store { /* If `Domain::name` does not exist, this default instance is used and throws the error. */ static_assert(sizeof(Domain) != sizeof(Domain), "Type used to identify a domain must contain a static member 'char const* name'"); static inline nvtxDomainHandle_t const kValue = nullptr; }; template <typename Domain> struct domain_store< Domain, /* Check if there exists `Domain::name` */ std::enable_if_t< std::is_same<char const*, typename std::decay<decltype(Domain::name)>::type>::value, Domain>> { static inline nvtxDomainHandle_t const kValue = nvtxDomainCreateA(Domain::name); }; template <typename Domain> inline void push_range_name(const char* name) { nvtxEventAttributes_t event_attrib = {0}; event_attrib.version = NVTX_VERSION; event_attrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE; event_attrib.colorType = NVTX_COLOR_ARGB; event_attrib.color = generate_next_color(name); event_attrib.messageType = NVTX_MESSAGE_TYPE_ASCII; event_attrib.message.ascii = name; nvtxDomainRangePushEx(domain_store<Domain>::kValue, &event_attrib); } template <typename Domain, typename... Args> inline void push_range(const char* format, Args... args) { if constexpr (sizeof...(args) > 0) { int length = std::snprintf(nullptr, 0, format, args...); assert(length >= 0); std::vector<char> buf(length + 1); std::snprintf(buf.data(), length + 1, format, args...); push_range_name<Domain>(buf.data()); } else { push_range_name<Domain>(format); } } template <typename Domain> inline void pop_range() { nvtxDomainRangePop(domain_store<Domain>::kValue); } #else // NVTX_ENABLED template <typename Domain, typename... Args> inline void push_range(const char* format, Args... args) { } template <typename Domain> inline void pop_range() { } #endif // NVTX_ENABLED } // namespace raft::common::nvtx::detail
29.921569
99
0.663008
[ "vector" ]
e07a057e6c3a9264eb102d4a082a43ccfa0a6b0f
1,998
hh
C++
src/RK/computeRKVolumes.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/RK/computeRKVolumes.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/RK/computeRKVolumes.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//------------------------------------------------------------------------------ // Compute the moments necessary for RK corrections. //------------------------------------------------------------------------------ #ifndef __Spheral__computeRKVolumes__ #define __Spheral__computeRKVolumes__ #include <vector> #include "RKCorrectionParams.hh" #include "Geometry/CellFaceFlag.hh" namespace Spheral { template<typename Dimension> class ConnectivityMap; template<typename Dimension> class TableKernel; template<typename Dimension, typename DataType> class FieldList; template<typename Dimension> class Boundary; template<typename Dimension> void computeRKVolumes(const ConnectivityMap<Dimension>& connectivityMap, const TableKernel<Dimension>& W, const FieldList<Dimension, typename Dimension::Vector>& position, const FieldList<Dimension, typename Dimension::Scalar>& mass, const FieldList<Dimension, typename Dimension::Scalar>& massDensity, const FieldList<Dimension, typename Dimension::SymTensor>& H, const FieldList<Dimension, typename Dimension::SymTensor>& damage, const std::vector<typename Dimension::FacetedVolume>& facetedBoundaries, const std::vector<std::vector<typename Dimension::FacetedVolume>>& facetedHoles, const std::vector<Boundary<Dimension>*>& boundaryConditions, const RKVolumeType volumeType, FieldList<Dimension, int>& surfacePoint, FieldList<Dimension, typename Dimension::Vector>& deltaCentroid, FieldList<Dimension, std::vector<typename Dimension::Vector>>& etaVoidPoints, FieldList<Dimension, typename Dimension::FacetedVolume>& cells, FieldList<Dimension, std::vector<CellFaceFlag>>& cellFaceFlags, FieldList<Dimension, typename Dimension::Scalar>& volume); } // end namespace Spheral #endif
48.731707
97
0.643143
[ "geometry", "vector" ]
e07c2f6a951cfde70145093f3959da77fcbb0eeb
4,729
hpp
C++
viennacl/tools/matrix_generation.hpp
ddemidov/viennacl-dev
0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef
[ "MIT" ]
2
2016-08-23T17:05:21.000Z
2016-08-23T17:06:24.000Z
viennacl/tools/matrix_generation.hpp
ddemidov/viennacl-dev
0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef
[ "MIT" ]
null
null
null
viennacl/tools/matrix_generation.hpp
ddemidov/viennacl-dev
0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef
[ "MIT" ]
null
null
null
#ifndef VIENNACL_TOOLS_MATRIX_GENERATION_HPP_ #define VIENNACL_TOOLS_MATRIX_GENERATION_HPP_ /* ========================================================================= Copyright (c) 2010-2014, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. Portions of this software are copyright by UChicago Argonne, LLC. ----------------- ViennaCL - The Vienna Computing Library ----------------- Project Head: Karl Rupp rupp@iue.tuwien.ac.at (A list of authors and contributors can be found in the PDF manual) License: MIT (X11), see file LICENSE in the base directory ============================================================================= */ /** @file viennacl/tools/matrix_generation.hpp @brief Helper routines for generating sparse matrices */ #include <string> #include <fstream> #include <sstream> #include "viennacl/forwards.h" #include "viennacl/meta/result_of.hpp" #include "viennacl/tools/adapter.hpp" #include <vector> #include <map> namespace viennacl { namespace tools { /** @brief Generates a sparse matrix obtained from a simple finite-difference discretization of the Laplace equation on the unit square (2d). * * @tparam MatrixType An uBLAS-compatible matrix type supporting .clear(), .resize(), and operator()-access * @param A A sparse matrix object from ViennaCL, total number of unknowns will be points_x*points_y * @param points_x Number of points in x-direction * @param points_y Number of points in y-direction */ template<typename MatrixType> void generate_fdm_laplace(MatrixType & A, vcl_size_t points_x, vcl_size_t points_y) { typedef typename MatrixType::value_type ScalarType; vcl_size_t total_unknowns = points_x * points_y; A.clear(); A.resize(total_unknowns, total_unknowns, false); for (vcl_size_t i=0; i<points_x; ++i) { for (vcl_size_t j=0; j<points_y; ++j) { vcl_size_t row = i + j * points_x; A(row, row) = 4.0; if (i > 0) { vcl_size_t col = (i-1) + j * points_x; A(row, col) = -1.0; } if (j > 0) { vcl_size_t col = i + (j-1) * points_x; A(row, col) = -1.0; } if (i < points_x-1) { vcl_size_t col = (i+1) + j * points_x; A(row, col) = -1.0; } if (j < points_y-1) { vcl_size_t col = i + (j+1) * points_x; A(row, col) = -1.0; } } } } template<typename NumericT> void generate_fdm_laplace(viennacl::compressed_matrix<NumericT> & A, vcl_size_t points_x, vcl_size_t points_y) { // Assemble into temporary matrix on CPU, then copy over: std::vector< std::map<unsigned int, NumericT> > temp_A; viennacl::tools::sparse_matrix_adapter<NumericT> adapted_A(temp_A); generate_fdm_laplace(adapted_A, points_x, points_y); viennacl::copy(temp_A, A); } template<typename NumericT> void generate_fdm_laplace(viennacl::coordinate_matrix<NumericT> & A, vcl_size_t points_x, vcl_size_t points_y) { // Assemble into temporary matrix on CPU, then copy over: std::vector< std::map<unsigned int, NumericT> > temp_A; viennacl::tools::sparse_matrix_adapter<NumericT> adapted_A(temp_A); generate_fdm_laplace(adapted_A, points_x, points_y); viennacl::copy(temp_A, A); } template<typename NumericT> void generate_fdm_laplace(viennacl::ell_matrix<NumericT> & A, vcl_size_t points_x, vcl_size_t points_y) { // Assemble into temporary matrix on CPU, then copy over: std::vector< std::map<unsigned int, NumericT> > temp_A; viennacl::tools::sparse_matrix_adapter<NumericT> adapted_A(temp_A); generate_fdm_laplace(adapted_A, points_x, points_y); viennacl::copy(temp_A, A); } template<typename NumericT> void generate_fdm_laplace(viennacl::sliced_ell_matrix<NumericT> & A, vcl_size_t points_x, vcl_size_t points_y) { // Assemble into temporary matrix on CPU, then copy over: std::vector< std::map<unsigned int, NumericT> > temp_A; viennacl::tools::sparse_matrix_adapter<NumericT> adapted_A(temp_A); generate_fdm_laplace(adapted_A, points_x, points_y); viennacl::copy(temp_A, A); } template<typename NumericT> void generate_fdm_laplace(viennacl::hyb_matrix<NumericT> & A, vcl_size_t points_x, vcl_size_t points_y) { // Assemble into temporary matrix on CPU, then copy over: std::vector< std::map<unsigned int, NumericT> > temp_A; viennacl::tools::sparse_matrix_adapter<NumericT> adapted_A(temp_A); generate_fdm_laplace(adapted_A, points_x, points_y); viennacl::copy(temp_A, A); } } //namespace tools } //namespace viennacl #endif
31.738255
141
0.661239
[ "object", "vector" ]
e07dd790308b1c3e6061be936f67303512051251
3,519
cc
C++
jsp/rcm_denoising/horny_toad/tests/test_polar.cc
jeffsp/kaggle_denoising
ad0e86a34c8c0c98c95e3ec3fe791a6b75154a27
[ "MIT" ]
1
2015-06-04T14:34:01.000Z
2015-06-04T14:34:01.000Z
jsp/rcm_denoising/horny_toad/tests/test_polar.cc
jeffsp/kaggle_denoising
ad0e86a34c8c0c98c95e3ec3fe791a6b75154a27
[ "MIT" ]
null
null
null
jsp/rcm_denoising/horny_toad/tests/test_polar.cc
jeffsp/kaggle_denoising
ad0e86a34c8c0c98c95e3ec3fe791a6b75154a27
[ "MIT" ]
null
null
null
/// @file test_polar.cc /// @brief test polar /// @author Jeff Perry <jeffsp@gmail.com> /// @version 1.0 /// @date 2013-01-14 #include "horny_toad/about_equal.h" #include "horny_toad/pi.h" #include "horny_toad/polar.h" #include "horny_toad/verify.h" #include <iostream> #include <vector> using namespace std; using namespace horny_toad; int main () { try { double r, th; double x, y; cart2pol (1.0, 0.0, r, th); pol2cart (r, th, x, y); VERIFY (about_equal (r, 1.0)); VERIFY (about_equal (th, 0*PI()/4)); VERIFY (about_equal (x, 1.0)); VERIFY (about_equal (y, 0.0)); cart2pol (1.0, 1.0, r, th); pol2cart (r, th, x, y); VERIFY (about_equal (r, sqrt (2.0))); VERIFY (about_equal (th, 1*PI()/4)); VERIFY (about_equal (x, 1.0)); VERIFY (about_equal (y, 1.0)); cart2pol (0.0, 1.0, r, th); pol2cart (r, th, x, y); VERIFY (about_equal (r, 1.0)); VERIFY (about_equal (th, 2*PI()/4)); VERIFY (about_equal (x, 0.0)); VERIFY (about_equal (y, 1.0)); cart2pol (-1.0, 1.0, r, th); pol2cart (r, th, x, y); VERIFY (about_equal (r, sqrt (2.0))); VERIFY (about_equal (th, 3*PI()/4)); VERIFY (about_equal (x, -1.0)); VERIFY (about_equal (y, 1.0)); cart2pol (-1.0, 0.0, r, th); pol2cart (r, th, x, y); VERIFY (about_equal (r, 1.0)); VERIFY (about_equal (th, 4*PI()/4)); VERIFY (about_equal (x, -1.0)); VERIFY (about_equal (y, 0.0)); cart2pol (-1.0, -1.0, r, th); pol2cart (r, th, x, y); VERIFY (about_equal (r, sqrt (2.0))); VERIFY (about_equal (th, -3*PI()/4)); VERIFY (about_equal (x, -1.0)); VERIFY (about_equal (y, -1.0)); cart2pol (0.0, -1.0, r, th); pol2cart (r, th, x, y); VERIFY (about_equal (r, 1.0)); VERIFY (about_equal (th, -2*PI()/4)); VERIFY (about_equal (x, 0.0)); VERIFY (about_equal (y, -1.0)); cart2pol (1.0, -1.0, r, th); pol2cart (r, th, x, y); VERIFY (about_equal (r, sqrt (2.0))); VERIFY (about_equal (th, -1*PI()/4)); VERIFY (about_equal (x, 1.0)); VERIFY (about_equal (y, -1.0)); vector<double> phi (1); phi[0] = PI()/3; vector<double> cx; hyper2cart (1.0, phi, cx); // 1st dimension is the y axis VERIFY (about_equal (cx[0], 0.5)); VERIFY (about_equal (cx[1], 0.866)); phi.resize (2); phi[0] = PI()/3; phi[1] = PI()/3; hyper2cart (1.0, phi, cx); VERIFY (about_equal (cx[0], 0.5)); // 2st dimension is the z axis VERIFY (about_equal (cx[1], 0.866/2)); // 3rd dimension is the x axis VERIFY (about_equal (cx[2], 0.75)); // should be a unit vector VERIFY (about_equal (sqrt (cx[0]*cx[0]+cx[1]*cx[1]+cx[2]*cx[2]), 1.0)); phi[0] = PI()/2; phi[1] = 0.0; hyper2cart (1.0, phi, cx); VERIFY (about_equal (cx[0], 0.0)); VERIFY (about_equal (cx[1], 1.0)); VERIFY (about_equal (cx[2], 0.0)); phi[0] = PI()*13/17; phi[1] = PI()*17/19; hyper2cart (1.0, phi, cx); // should be a unit vector VERIFY (about_equal (sqrt (cx[0]*cx[0]+cx[1]*cx[1]+cx[2]*cx[2]), 1.0)); return 0; } catch (const exception &e) { cerr << e.what () << endl; return -1; } }
32.284404
79
0.498153
[ "vector" ]
e08747d76725c5b6d598c9c201a6a0a55c724232
5,139
cpp
C++
RiptideRecorder/Macro.cpp
ironmig/RiptideRecorder
6e7a42a800157e6f1e6cc4ac812ff6f4ade52257
[ "MIT" ]
1
2015-04-12T04:37:59.000Z
2015-04-12T04:37:59.000Z
RiptideRecorder/Macro.cpp
ironmig/RiptideRecorder
6e7a42a800157e6f1e6cc4ac812ff6f4ade52257
[ "MIT" ]
null
null
null
RiptideRecorder/Macro.cpp
ironmig/RiptideRecorder
6e7a42a800157e6f1e6cc4ac812ff6f4ade52257
[ "MIT" ]
null
null
null
/* * Macro.cpp * * Created on: Apr 4, 2015 * Author: kma1660 */ #include "Macro.h" #include "Commands/RecordCommand.h" #include "Commands/PlayBackCommand.h" #include "Commands/PlayBackFileCommand.h" #include "Commands/RecordFileCommand.h" Macro::Macro(std::vector<Device*> devices) { Values = Vals{}; for(std::vector<Device*>::iterator dev = devices.begin(); dev != devices.end(); dev++) { Values.insert( std::pair<Device*,std::vector<float> >(*dev,std::vector<float>()) ); } subsystems = std::vector<Subsystem * >(); length = 0; position = 0; } Macro::Macro(std::vector<Device*> devices,std::vector<Subsystem* > s) : Macro(devices) { Values = Vals{}; for(std::vector<Device*>::iterator dev = devices.begin(); dev != devices.end(); dev++) { Values.insert( std::pair<Device*,std::vector<float> >(*dev,std::vector<float>()) ); } subsystems = s; length = 0; position = 0; } //Removes in memory loaded recording and resets playback to position zero void Macro::Reset() { for (valsIt it = Values.begin(); it != Values.end(); it++) { it->second = std::vector<float> (); } length = 0; PlayReset(); } //Resets position to zero so play back will start over void Macro::PlayReset() { position = 0; } //Records an instant of all devices void Macro::Record() { for (valsIt it = Values.begin(); it != Values.end(); it++) { it->second.push_back(it->first->get()); } length++; } //Plays back one instant of devices and increments play back position void Macro::PlayBack() { if (position >= length) return; for (valsIt it = Values.begin(); it != Values.end(); it++) { if (position >= it->second.size()) { it->first->set(0); continue; } it->first->set(it->second[position]); } position++; } //Writes the current in memory recording to the file at filename in CSV format, blocks void Macro::WriteFile(std::string filename) { std::ofstream file; file.open(filename.c_str()); if (file.is_open()) { //Writes the heading line with the device names, so can be matched on file readback for (valsIt it = Values.begin(); it != Values.end(); it++) { file << it->first->GetName(); if (it != --Values.end()) file << ","; } file << "\n"; //Writes a new line for the in memory values at each recorded instant in the order the heading establishes for (unsigned int i = 0; i<length;i++) { for (valsIt it = Values.begin(); it != Values.end(); it++) { if (i >= it->second.size()) { file << 0; } else file << it->second[i]; if (it != --Values.end()) file << ","; } file << "\n"; } file.close(); } } //Resets the in memory recording and replaces it with the recording located at the file at filename void Macro::ReadFile(std::string filename) { std::ifstream file; file.open(filename.c_str()); if (file.is_open()) { std::string line; std::string delimiter = ","; std::string token; size_t pos = 0; Reset(); std::vector<Device*> list; //Get the first line to establish the list of devices std::getline(file,line); while ((pos = line.find(delimiter)) != std::string::npos) { token = line.substr(0, pos); list.push_back(NULL); for (valsIt it = Values.begin(); it != Values.end(); it++) if (token == it->first->GetName()) { list.back() = it->first; break; }; line.erase(0, pos + delimiter.length()); } //Grab last list.push_back(NULL); for (valsIt it = Values.begin(); it != Values.end(); it++) if (line == it->first->GetName()) { list.back() = it->first; break; }; //Now, for each line append value to each device unsigned int i; length = 0; while (std::getline(file,line)) { length++; i = 0; while ((pos = line.find(delimiter)) != std::string::npos) { token = line.substr(0, pos); line.erase(0, pos + delimiter.length()); if (i >= list.size()) break; //break from loop if this line has more cols than first line if (list[i] != NULL) Values[list[i]].push_back( (float) std::atof(token.c_str()) ); i++; } //Grab last if (i >= list.size()) break; //break from loop if this line has more cols than first line if (list[i] != NULL) Values[list[i]].push_back( (float) std::atof(line.c_str())); } } } //returns true if all in memory recorded instants have been played back using PlayBack() bool Macro::IsFinished() { return position >= length; } //returns a command that will play back all recorded instants (starting at 0) in memory then finish Command* Macro::NewPlayCommand() { return new PlayBackCommand(this); } //Same as NewPlayCommand(), but on command run resets in memory recording this recording at file at FileName Command* Macro::NewPlayFileCommand(std::string FileName) { return new PlayBackFileCommand(this,FileName); } //returns a command that will record a new instant from all sensors into memory until it is manually canceled Command* Macro::NewRecordCommand() { return new RecordCommand(this); } //same as NewRecordCommand(), but writes in memory recording to file at FileName when command is finished Command* Macro::NewRecordFileCommand(std::string FileName) { return new RecordFileCommand(this,FileName); }
31.722222
109
0.653435
[ "vector" ]
e08dac56a325d5475c4dc115c2f421fd2f9369a8
963
cpp
C++
Leetcode Practice Set/1.two-sum.cpp
MiracleShadow/Use-Cpp-practice-algorithm
c61116cd5516de9242100ed0c0ec48c79e9d17b5
[ "MIT" ]
1
2019-01-19T10:33:39.000Z
2019-01-19T10:33:39.000Z
Leetcode Practice Set/1.two-sum.cpp
MiracleShadow/Use-Cpp-practice-algorithm
c61116cd5516de9242100ed0c0ec48c79e9d17b5
[ "MIT" ]
null
null
null
Leetcode Practice Set/1.two-sum.cpp
MiracleShadow/Use-Cpp-practice-algorithm
c61116cd5516de9242100ed0c0ec48c79e9d17b5
[ "MIT" ]
null
null
null
/* * @lc app=leetcode.cn id=1 lang=cpp * * [1] 两数之和 * * https://leetcode-cn.com/problems/two-sum/description/ * * algorithms * Easy (43.78%) * Total Accepted: 219.4K * Total Submissions: 501.1K * Testcase Example: '[2,7,11,15]\n9' * * 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 * * 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 * * 示例: * * 给定 nums = [2, 7, 11, 15], target = 9 * * 因为 nums[0] + nums[1] = 2 + 7 = 9 * 所以返回 [0, 1] * * */ static const auto SpeedUp = []{ ios::sync_with_stdio(false); cin.tie(NULL); return 0; }(); class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> mp; for(int i = 0; i < nums.size(); ++i) { if(mp.find(target - nums[i]) != mp.end()) { return {mp[target - nums[i]], i}; } mp.insert(make_pair(nums[i], i)); } return {}; } };
21.4
65
0.534787
[ "vector" ]
e08e60419c3d9f05c35db76c5790cb1f4c17841f
659
cpp
C++
ABC135/ABC135C.cpp
tayoon/AtCoder
1d7c2a290cf881233259e5a71e17fb28f2f683df
[ "MIT" ]
null
null
null
ABC135/ABC135C.cpp
tayoon/AtCoder
1d7c2a290cf881233259e5a71e17fb28f2f683df
[ "MIT" ]
null
null
null
ABC135/ABC135C.cpp
tayoon/AtCoder
1d7c2a290cf881233259e5a71e17fb28f2f683df
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector <long long> a(n+1, 0); vector <long long> b(n+1, 0); for (int i = 0; i < n+1; i++) cin >> a[i]; for (int i = 0; i < n; i++) cin >> b[i]; long long next = 0, cnt = 0; for (int i = 0; i < n+1; i++) { if (a[i] >= next) { a[i] -= next; cnt += next; } else { cnt += a[i]; a[i] = 0; } next = 0; if (a[i] >= b[i]) { cnt += b[i]; } else { cnt += a[i]; next += b[i] - a[i]; } } cout << cnt << endl; }
19.969697
46
0.338392
[ "vector" ]
e09717c47987a342166282ea7a29d0ecb268a1ca
11,377
hpp
C++
include/Proyecto26/HttpBase.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/Proyecto26/HttpBase.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/Proyecto26/HttpBase.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: Proyecto26 namespace Proyecto26 { // Forward declaring type: RequestHelper class RequestHelper; // Forward declaring type: RequestException class RequestException; // Forward declaring type: ResponseHelper class ResponseHelper; } // Forward declaring namespace: System::Collections namespace System::Collections { // Forward declaring type: IEnumerator class IEnumerator; } // Forward declaring namespace: System namespace System { // Forward declaring type: Action`2<T1, T2> template<typename T1, typename T2> class Action_2; // Forward declaring type: Action`3<T1, T2, T3> template<typename T1, typename T2, typename T3> class Action_3; } // Forward declaring namespace: UnityEngine::Networking namespace UnityEngine::Networking { // Forward declaring type: UnityWebRequest class UnityWebRequest; } // Completed forward declares // Type namespace: Proyecto26 namespace Proyecto26 { // Forward declaring type: HttpBase class HttpBase; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::Proyecto26::HttpBase); DEFINE_IL2CPP_ARG_TYPE(::Proyecto26::HttpBase*, "Proyecto26", "HttpBase"); // Type namespace: Proyecto26 namespace Proyecto26 { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: Proyecto26.HttpBase // [TokenAttribute] Offset: FFFFFFFF class HttpBase : public ::Il2CppObject { public: // Nested type: ::Proyecto26::HttpBase::$CreateRequestAndRetry$d__0 class $CreateRequestAndRetry$d__0; // Nested type: ::Proyecto26::HttpBase::$$c__DisplayClass5_0_1<TResponse> template<typename TResponse> class $$c__DisplayClass5_0_1; // Nested type: ::Proyecto26::HttpBase::$$c__DisplayClass6_0_1<TResponse> template<typename TResponse> class $$c__DisplayClass6_0_1; // static public System.Collections.IEnumerator CreateRequestAndRetry(Proyecto26.RequestHelper options, System.Action`2<Proyecto26.RequestException,Proyecto26.ResponseHelper> callback) // Offset: 0x19422A0 static ::System::Collections::IEnumerator* CreateRequestAndRetry(::Proyecto26::RequestHelper* options, ::System::Action_2<::Proyecto26::RequestException*, ::Proyecto26::ResponseHelper*>* callback); // static private UnityEngine.Networking.UnityWebRequest CreateRequest(Proyecto26.RequestHelper options) // Offset: 0x1942318 static ::UnityEngine::Networking::UnityWebRequest* CreateRequest(::Proyecto26::RequestHelper* options); // static private Proyecto26.RequestException CreateException(Proyecto26.RequestHelper options, UnityEngine.Networking.UnityWebRequest request) // Offset: 0x19424F0 static ::Proyecto26::RequestException* CreateException(::Proyecto26::RequestHelper* options, ::UnityEngine::Networking::UnityWebRequest* request); // static private System.Void DebugLog(System.Boolean debugEnabled, System.Object message, System.Boolean isError) // Offset: 0x194243C static void DebugLog(bool debugEnabled, ::Il2CppObject* message, bool isError); // static public System.Collections.IEnumerator DefaultUnityWebRequest(Proyecto26.RequestHelper options, System.Action`2<Proyecto26.RequestException,Proyecto26.ResponseHelper> callback) // Offset: 0x1942600 static ::System::Collections::IEnumerator* DefaultUnityWebRequest(::Proyecto26::RequestHelper* options, ::System::Action_2<::Proyecto26::RequestException*, ::Proyecto26::ResponseHelper*>* callback); // static public System.Collections.IEnumerator DefaultUnityWebRequest(Proyecto26.RequestHelper options, System.Action`3<Proyecto26.RequestException,Proyecto26.ResponseHelper,TResponse> callback) // Offset: 0xFFFFFFFFFFFFFFFF template<class TResponse> static ::System::Collections::IEnumerator* DefaultUnityWebRequest(::Proyecto26::RequestHelper* options, ::System::Action_3<::Proyecto26::RequestException*, ::Proyecto26::ResponseHelper*, TResponse>* callback) { static auto ___internal__logger = ::Logger::get().WithContext("::Proyecto26::HttpBase::DefaultUnityWebRequest"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("Proyecto26", "HttpBase", "DefaultUnityWebRequest", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TResponse>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(options), ::il2cpp_utils::ExtractType(callback)}))); static auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TResponse>::get()})); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IEnumerator*, false>(static_cast<Il2CppObject*>(nullptr), ___generic__method, options, callback); } // static public System.Collections.IEnumerator DefaultUnityWebRequest(Proyecto26.RequestHelper options, System.Action`3<Proyecto26.RequestException,Proyecto26.ResponseHelper,TResponse[]> callback) // Offset: 0xFFFFFFFFFFFFFFFF template<class TResponse> static ::System::Collections::IEnumerator* DefaultUnityWebRequest_(::Proyecto26::RequestHelper* options, ::System::Action_3<::Proyecto26::RequestException*, ::Proyecto26::ResponseHelper*, ::ArrayW<TResponse>>* callback) { static auto ___internal__logger = ::Logger::get().WithContext("::Proyecto26::HttpBase::DefaultUnityWebRequest"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("Proyecto26", "HttpBase", "DefaultUnityWebRequest", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TResponse>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(options), ::il2cpp_utils::ExtractType(callback)}))); static auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TResponse>::get()})); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IEnumerator*, false>(static_cast<Il2CppObject*>(nullptr), ___generic__method, options, callback); } }; // Proyecto26.HttpBase #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: Proyecto26::HttpBase::CreateRequestAndRetry // Il2CppName: CreateRequestAndRetry template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::IEnumerator* (*)(::Proyecto26::RequestHelper*, ::System::Action_2<::Proyecto26::RequestException*, ::Proyecto26::ResponseHelper*>*)>(&Proyecto26::HttpBase::CreateRequestAndRetry)> { static const MethodInfo* get() { static auto* options = &::il2cpp_utils::GetClassFromName("Proyecto26", "RequestHelper")->byval_arg; static auto* callback = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`2"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("Proyecto26", "RequestException"), ::il2cpp_utils::GetClassFromName("Proyecto26", "ResponseHelper")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(Proyecto26::HttpBase*), "CreateRequestAndRetry", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{options, callback}); } }; // Writing MetadataGetter for method: Proyecto26::HttpBase::CreateRequest // Il2CppName: CreateRequest template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Networking::UnityWebRequest* (*)(::Proyecto26::RequestHelper*)>(&Proyecto26::HttpBase::CreateRequest)> { static const MethodInfo* get() { static auto* options = &::il2cpp_utils::GetClassFromName("Proyecto26", "RequestHelper")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Proyecto26::HttpBase*), "CreateRequest", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{options}); } }; // Writing MetadataGetter for method: Proyecto26::HttpBase::CreateException // Il2CppName: CreateException template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Proyecto26::RequestException* (*)(::Proyecto26::RequestHelper*, ::UnityEngine::Networking::UnityWebRequest*)>(&Proyecto26::HttpBase::CreateException)> { static const MethodInfo* get() { static auto* options = &::il2cpp_utils::GetClassFromName("Proyecto26", "RequestHelper")->byval_arg; static auto* request = &::il2cpp_utils::GetClassFromName("UnityEngine.Networking", "UnityWebRequest")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Proyecto26::HttpBase*), "CreateException", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{options, request}); } }; // Writing MetadataGetter for method: Proyecto26::HttpBase::DebugLog // Il2CppName: DebugLog template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(bool, ::Il2CppObject*, bool)>(&Proyecto26::HttpBase::DebugLog)> { static const MethodInfo* get() { static auto* debugEnabled = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; static auto* message = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; static auto* isError = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Proyecto26::HttpBase*), "DebugLog", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{debugEnabled, message, isError}); } }; // Writing MetadataGetter for method: Proyecto26::HttpBase::DefaultUnityWebRequest // Il2CppName: DefaultUnityWebRequest template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::IEnumerator* (*)(::Proyecto26::RequestHelper*, ::System::Action_2<::Proyecto26::RequestException*, ::Proyecto26::ResponseHelper*>*)>(&Proyecto26::HttpBase::DefaultUnityWebRequest)> { static const MethodInfo* get() { static auto* options = &::il2cpp_utils::GetClassFromName("Proyecto26", "RequestHelper")->byval_arg; static auto* callback = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`2"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("Proyecto26", "RequestException"), ::il2cpp_utils::GetClassFromName("Proyecto26", "ResponseHelper")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(Proyecto26::HttpBase*), "DefaultUnityWebRequest", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{options, callback}); } }; // Writing MetadataGetter for method: Proyecto26::HttpBase::DefaultUnityWebRequest // Il2CppName: DefaultUnityWebRequest // Cannot write MetadataGetter for generic methods! // Writing MetadataGetter for method: Proyecto26::HttpBase::DefaultUnityWebRequest_ // Il2CppName: DefaultUnityWebRequest // Cannot write MetadataGetter for generic methods!
70.664596
348
0.766107
[ "object", "vector" ]
e09b841281670613ba67b85d5b629f7bb47bb000
3,748
cxx
C++
src/lib/Hists/GCRFit.cxx
fermi-lat/calibGenCAL
9b207d7ba56031f5ecd7aab544e68a6dedc7d776
[ "BSD-3-Clause" ]
null
null
null
src/lib/Hists/GCRFit.cxx
fermi-lat/calibGenCAL
9b207d7ba56031f5ecd7aab544e68a6dedc7d776
[ "BSD-3-Clause" ]
null
null
null
src/lib/Hists/GCRFit.cxx
fermi-lat/calibGenCAL
9b207d7ba56031f5ecd7aab544e68a6dedc7d776
[ "BSD-3-Clause" ]
null
null
null
// $Header: /nfs/slac/g/glast/ground/cvs/calibGenCAL/src/lib/Hists/GCRFit.cxx,v 1.4 2008/04/21 20:32:32 fewtrell Exp $ /** @file @author Zachary Fewtrell */ // LOCAL INCLUDES #include "GCRFit.h" #include "GCRHists.h" #include "HistIdx.h" #include "MPDHists.h" #include "src/lib/Util/CGCUtil.h" #include "src/lib/Util/ROOTUtil.h" #include "src/lib/Specs/CalResponse.h" // GLAST INCLUDES #include "CalUtil/CalDefs.h" // EXTLIB INCLUDES #include "TDirectory.h" #include "TTree.h" #include "TF1.h" // STD INCLUDES #include <string> #include <iostream> #include <cassert> #include <stdexcept> #include <ostream> #include <algorithm> using namespace std; using namespace CalUtil; namespace calibGenCAL { namespace GCRFit { /// return mevPerDAC constant for given particle z & CIDAC peak /// \parm z atomic # of particle static float evalMevPerDAC(const unsigned char z, const float cidac) { return (float)z*z*CalResponse::CsIMuonPeak / cidac; } static float defaultMPD(DiodeNum diode) { const float defaultMPD[DiodeNum::N_VALS] = {.36,25}; return defaultMPD[diode.val()]; } static float defaultDACPeak(DiodeNum diode, unsigned char z) { return z*z*CalResponse::CsIMuonPeak/defaultMPD(diode); } /// tools for fitting GCR hists w/ simple gaussian shape namespace GCRFitGaus { /// used as ptr for each entry in tuple class TupleData { public: unsigned char diode; unsigned char inferredZ; float peak; float width; /// num histogram entries unsigned nEntries; float mevPerDAC; /// basic print out friend ostream& operator<< (ostream &stream, const TupleData &tupleData); }; ostream& operator<< (ostream &stream, const TupleData &td) { stream << "fit_result: diode: " << DiodeNum(td.diode) << " z: " << (unsigned)td.inferredZ << " peak: " << td.peak << " width: " << td.width << " nEntries: " << td.nEntries << " mpd: " << td.mevPerDAC << endl; return stream; } /// generate ROOT tuple for fit parms static TTree *genTuple(TDirectory *const writeFile, const std::string &tupleName, TupleData &tupleData) { TTree *tuple = new TTree(tupleName.c_str(), tupleName.c_str()); assert(tuple != 0); if (!tuple->Branch("diode", &tupleData.diode, "diode/b") || !tuple->Branch("peak", &tupleData.peak, "peak/F")|| !tuple->Branch("width", &tupleData.width, "width/F")|| !tuple->Branch("nEntries", &tupleData.nEntries, "width/i")|| !tuple->Branch("mevPerDAC", &tupleData.mevPerDAC, "mevPerDAC/F")) throw runtime_error("Unable to create TTree branches for " + tupleName); // set desired directory for tuple tuple->SetDirectory(writeFile); return tuple; } } // namespace GCRFitGaus void gcrFitGaus(GCRHists &histCol, CalMPD &calMPD, TDirectory *const writeFile, const std::string &tupleName) { } // gcrFitGaus } // namespace GCRFit } // namespace calibGenCAL
29.511811
118
0.529616
[ "shape" ]
e09c95336259c79ddebc56ec02f24b3421fef3e0
1,593
cpp
C++
cppLibs/cmdParse.cpp
Justist/justLibraries
fdf9dea2291b600c6e46ab2356321e01fb8ca547
[ "Apache-2.0" ]
null
null
null
cppLibs/cmdParse.cpp
Justist/justLibraries
fdf9dea2291b600c6e46ab2356321e01fb8ca547
[ "Apache-2.0" ]
null
null
null
cppLibs/cmdParse.cpp
Justist/justLibraries
fdf9dea2291b600c6e46ab2356321e01fb8ca547
[ "Apache-2.0" ]
null
null
null
#include "cmdParse.hpp" CMDParse::CMDParse(int argc, char* argv[], std::string commands) { parseCommands(commands); parseArguments(argc, argv); } CMDParse::CMDParse() { std::cout << R"( Usage: It is highly preferable to use the cmdp::parse() command, as defined in the header. This requires argc, argv, and a string of acceptable commands, comma-separated. Same goes for this class btw, so if you intend on using this class only, please give the same input and try again. )"; } CMDParse::~CMDParse() { } void CMDParse::parseArguments(unsigned int argc, char* argv[]) { std::string arg = ""; for(unsigned int i = 1; i < argc; i++) { arg = argv[i]; if(std::find(acceptedCommands.begin(), acceptedCommands.end(), arg) != acceptedCommands.end()) { args.push_back(argv[++i]); } } } void CMDParse::parseCommands(std::string commands) { for(std::string c : split(commands, ',')) { if(c.length() == 1) { acceptedCommands.push_back("-" + c); } else { acceptedCommands.push_back("--" + c); } } } std::vector<std::string> CMDParse::split(const std::string &s, char delim) { /* * Splits a string based on a certain delimiter and returns * the splitted elements in a vector. * Copied from https://stackoverflow.com/a/27511119/1762311 */ std::stringstream ss(s); std::string item; std::vector<std::string> elems; while (std::getline(ss, item, delim)) { //elems.push_back(item); elems.push_back(std::move(item)); } return elems; }
27.947368
76
0.625235
[ "vector" ]
e0ab760a2742f00d9f46efbc163cc88839acd2ca
6,866
cpp
C++
booserver/timetable_screen_builder.cpp
sundersb/booserver
c91dcdd33af3aba590d177f50dafe994a16ba24b
[ "BSD-2-Clause" ]
1
2019-03-03T04:40:07.000Z
2019-03-03T04:40:07.000Z
booserver/timetable_screen_builder.cpp
sundersb/booserver
c91dcdd33af3aba590d177f50dafe994a16ba24b
[ "BSD-2-Clause" ]
null
null
null
booserver/timetable_screen_builder.cpp
sundersb/booserver
c91dcdd33af3aba590d177f50dafe994a16ba24b
[ "BSD-2-Clause" ]
null
null
null
#include "timetable_screen_builder.h" #include "date.h" #include "png_files.h" #include <iostream> #include <sstream> #include <cstring> #include <assert.h> TimetableScreenBuilder::TimetableScreenBuilder(const Options &options): canvas(options.getWidth(), options.getHeight()), background(nullptr), line_height(options.getHeight() / options.getLines()), title_width(options.getWidth() / 5), study_width(options.getWidth() / 14), day_width((options.getWidth() - title_width - study_width) / 7), testing(options.isTesting()), hasbgr(false), color_clear(options.getClearColor()), title_face(options.getTitleFace()), header_back(options.getHeaderBack()), header_face(options.getHeaderFace()), line_odd(options.getLineOdd()), line_even(options.getLineEven()), line_face(options.getLineFace()), counter_face(options.getCounterFace()), font_file(options.getFontFile()), title_name(options.getTitleName()), title_study(options.getTitleStudy()), title_no_time(options.getTitleNoTime()), title_testing(options.getTitleTesting()), bg_image_file(options.getBackgroundImageFile()) { weekdays[0] = options.getTitleMonday(); weekdays[1] = options.getTitileTuesday(); weekdays[2] = options.getTitleWednesday(); weekdays[3] = options.getTitleThursday(); weekdays[4] = options.getTitleFryday(); weekdays[5] = options.getTitleSaturday(); weekdays[6] = options.getTitleSunday(); } bool TimetableScreenBuilder::init(void) { if (!canvas.init()) return false; canvas.clear(color_clear); hasbgr = !bg_image_file.empty() && png::drawPNG(bg_image_file, canvas); background = new unsigned char [canvas.getSize()]; memmove(background, canvas.getPixels(), canvas.getSize()); int fsize = line_height; return font_title.init(font_file, fsize, 72) && font_caption.init(font_file, fsize * 3 / 5, 72) && font_text.init(font_file, fsize / 2, 72); } TimetableScreenBuilder::~TimetableScreenBuilder() { delete [] background; } image::Canvas& TimetableScreenBuilder::getCanvas(void) { return canvas; } const unsigned char* TimetableScreenBuilder::getPixels(void) const { return canvas.getPixels(); } unsigned char* TimetableScreenBuilder::getPixels(void) { return canvas.getPixels(); } int TimetableScreenBuilder::getWidth(void) const { return canvas.getWidth(); } int TimetableScreenBuilder::getHeight(void) const { return canvas.getHeight(); } int TimetableScreenBuilder::getSize(void) const { return canvas.getSize(); } int getTodaysWeekday(void) { DateTime wstart; wstart.setNow(); wstart.fromUTC(); return wstart.getWeekDay(); } void TimetableScreenBuilder::build(const Profiles &ps, int page, int pageCount) { int y = ps.size() * 3 + 1; //y = std::accumulate(ps.begin(), ps.end(), y, [](auto const &p) { return p.getDoctors().size(); } ); for (const timetable::Profile &profile : ps) y += profile.getDoctors().size(); // Center timetables vertically y = (canvas.getHeight() - y * line_height) / (ps.size() + 1); // Vertical distance between timetable profiles int dy = y; canvas.copy(background); int twd = getTodaysWeekday(); for (const timetable::Profile &profile : ps) { const std::vector<timetable::Doctor> &ds = profile.getDoctors(); int len = ds.size(); image::Rect rect = { 0, y, canvas.getWidth() - 1, y + line_height * 2}; if (hasbgr) canvas.fillBoxBlended(color_clear, rect, 0xbb); canvas.textOut(profile.getTitle(), font_title, title_face, rect, true); // Make sure we'll make no overflow assert(y + line_height * (len + 3) < canvas.getHeight()); // Box rect.y0 = y + line_height * 2; rect.y1 = rect.y0 + line_height * (len + 1); canvas.fillBox(line_even, rect); // Header rect.y0 = y + line_height * 2 + 1; rect.y1 = y + line_height * 3 - 1; canvas.fillBox(header_back, rect); // Line stripes rect.y0 = y + line_height * 3 + 1; rect.y1 = y + line_height * 4 - 1; for (int i = 0; i < len; i += 2) { canvas.fillBox(line_odd, rect); rect.y0 += line_height * 2; rect.y1 += line_height * 2; } // Columns rect.y0 = y + line_height * 2; rect.y1 = rect.y0 + line_height * (len + 1); canvas.vertical(line_even, title_width, rect.y0, rect.y1); canvas.vertical(line_even, title_width + study_width, rect.y0, rect.y1); for (int i = 1; i < 7; ++i) { canvas.vertical(line_even, title_width + study_width + i * day_width, rect.y0, rect.y1); } // Today rect.y0 = y + line_height * 2 + 1; rect.y1 = y + line_height * (len + 3) - 1; rect.x0 = title_width + study_width + twd * day_width + 1; rect.x1 = rect.x0 + day_width - 2; canvas.fillBoxBlended(line_odd, rect, 0xa0); // Table titles // Doctor rect.y0 = y + line_height * 2 + 1; rect.y1 = y + line_height * 3 - 1; rect.x0 = 3; rect.x1 = title_width - 1; canvas.textOut(title_name, font_caption, header_face, rect, true); // Study rect.x0 = title_width + 1; rect.x1 = title_width + study_width - 1; canvas.textOut(title_study, font_caption, header_face, rect, true); // Weekday names rect.x0 = title_width + study_width; rect.x1 = rect.x0 + day_width; for(const std::string &wd : weekdays) { canvas.textOut(wd, font_caption, header_face, rect, true); rect.x0 += day_width; rect.x1 += day_width; } // Doctors rect.y0 = y + line_height * 3 + 1; rect.y1 = y + line_height * 4 - 1; for (const timetable::Doctor &doc : ds) { rect.x0 = line_height / 4; rect.x1 = title_width - 1; canvas.textOut(doc.getName(), font_text, line_face, rect, false); rect.x0 = title_width; rect.x1 = title_width + study_width; canvas.textOut(doc.getStudy(), font_text, line_face, rect, true); rect.x0 = title_width + study_width; rect.x1 = rect.x0 + day_width; for (int i = 0; i < 7; ++i) { const timetable::ReceiptTime &r = doc[(timetable::Weekdays)i]; if (r.blocked) { canvas.textOut(title_no_time, font_text, line_face, rect, true); } else { canvas.textOut(r.title, font_text, line_face, rect, true); } rect.x0 += day_width; rect.x1 += day_width; } rect.y0 += line_height; rect.y1 += line_height; } y += line_height * (len + 3) + dy; } std::ostringstream pager; if (testing) { pager << "*** " << title_testing << " *** " << page << " / " << pageCount << " *** " << title_testing << " ***"; } else { pager << page << " / " << pageCount; } image::Rect rect = { 0, canvas.getHeight() - line_height, canvas.getWidth() - 1, canvas.getHeight() - 1 }; canvas.textOut(pager.str(), font_caption, counter_face, rect, true); }
31.934884
134
0.642587
[ "vector" ]
e0b100f8376b942cd691e95a1c1d7c2bbc287137
1,612
cpp
C++
misc/algos/shellsort.cpp
k-kapp/ShortCppProblems
d7825b60c0d44b5c8108636bcf4765057b1a1e7d
[ "Apache-2.0" ]
null
null
null
misc/algos/shellsort.cpp
k-kapp/ShortCppProblems
d7825b60c0d44b5c8108636bcf4765057b1a1e7d
[ "Apache-2.0" ]
null
null
null
misc/algos/shellsort.cpp
k-kapp/ShortCppProblems
d7825b60c0d44b5c8108636bcf4765057b1a1e7d
[ "Apache-2.0" ]
null
null
null
/* This is my implementation of the shellsort algorithm */ #include <iostream> #include <vector> #include <random> #include "test_utils.h" using namespace std; template<typename Iterator, typename Comparator> void sort_sublist(Iterator begin, Iterator end, Comparator comp, int h) { int list_end = 0; Iterator curr_ins = next(begin, list_end + h); while (distance(curr_ins, end) > 0) { int insert_idx = 0; for (Iterator curr_check = begin; insert_idx <= list_end; advance(curr_check, h), insert_idx += h) { if (comp(*curr_ins, *curr_check)) { break; } } if (insert_idx <= list_end) { Iterator new_ins = curr_ins; while (new_ins != next(begin, insert_idx)) { swap(*new_ins, *next(new_ins, -h)); advance(new_ins, -h); } } advance(curr_ins, h); list_end += h; } } template<typename Iterator, typename Comparator, typename Container> void shellsort(Iterator begin, Iterator end, Comparator comp, Container h_vals) { if (begin == end) return; for (auto h_iter = h_vals.begin(); h_iter != h_vals.end(); advance(h_iter, 1)) { for (int i = 0; i < *h_iter; i++) { sort_sublist(next(begin, i), end, comp, *h_iter); } } } int main(int argc, char * argv []) { vector<int> my_vec = generate_randoms<vector<int> >(250); vector<int> h_vals = {6, 4, 1}; shellsort(my_vec.begin(), my_vec.end(), less<int>(), h_vals); for (auto &val : my_vec) { cout << val << " "; } cout << endl; if (sorted(my_vec, less_equal<int>())) { cout << "Sorting OK" << endl; } else { cout << "Array not sorted" << endl; } return EXIT_SUCCESS; }
18.744186
100
0.641439
[ "vector" ]
e0b2c69ab3e9df843a6078ce8710dd8cd3ecdff0
20,773
cpp
C++
geograph3d/test_data.cpp
legion-zver/geograph3d
ce4b3cf27fa6b5d35b34d8ca055ed3e61d943e5b
[ "MIT" ]
5
2016-10-01T15:43:33.000Z
2021-11-12T11:29:49.000Z
geograph3d/test_data.cpp
legion-zver/geograph3d
ce4b3cf27fa6b5d35b34d8ca055ed3e61d943e5b
[ "MIT" ]
null
null
null
geograph3d/test_data.cpp
legion-zver/geograph3d
ce4b3cf27fa6b5d35b34d8ca055ed3e61d943e5b
[ "MIT" ]
null
null
null
#include "test_data.hpp" #include "jute.hpp" using namespace GeoGraph3D; #define FLOOR_HEIGHT 0.03f; //#define DEBUG_TEST_TRANSITIONS void FillGraphExample01(Graph* graph) { if(graph != NULL) { Roads roads; std::string jsonRoads = "{\"0\":[[{\"lat\":55.776253774269,\"lng\":37.655278220773},{\"lat\":55.776278853811,\"lng\":37.655394896865}],[{\"lat\":55.77626037415,\"lng\":37.655214853585},{\"lat\":55.776306761854,\"lng\":37.655435800552}],[{\"lat\":55.776328258577,\"lng\":37.655305378139},{\"lat\":55.776262636966,\"lng\":37.655350640416}],[{\"lat\":55.77670897488,\"lng\":37.654993906617},{\"lat\":55.776295447785,\"lng\":37.655281573534}],[{\"lat\":55.776296202057,\"lng\":37.655261792243},{\"lat\":55.776310721778,\"lng\":37.655330523849}],[{\"lat\":55.776309213236,\"lng\":37.655254416168},{\"lat\":55.77632392152,\"lng\":37.655321471393}],[{\"lat\":55.776317321649,\"lng\":37.655205465853},{\"lat\":55.776332218498,\"lng\":37.655271850526}],[{\"lat\":55.776632228505,\"lng\":37.655327171087},{\"lat\":55.776577544264,\"lng\":37.655072361231}],[{\"lat\":55.776617708904,\"lng\":37.655151486397},{\"lat\":55.77659413811,\"lng\":37.655168250203}],[{\"lat\":55.776572264402,\"lng\":37.654974795878},{\"lat\":55.776596966606,\"lng\":37.65508711338}],[{\"lat\":55.776581692726,\"lng\":37.654983848333},{\"lat\":55.776568870204,\"lng\":37.65499189496}],[{\"lat\":55.776642788212,\"lng\":37.654953338206},{\"lat\":55.776676918673,\"lng\":37.655109241605}],[{\"lat\":55.776700866548,\"lng\":37.654918134212},{\"lat\":55.776639582587,\"lng\":37.654960714281}],[{\"lat\":55.776733488432,\"lng\":37.655066996813},{\"lat\":55.776672015957,\"lng\":37.655109576881}],[{\"lat\":55.776689364027,\"lng\":37.654993571341},{\"lat\":55.776702563641,\"lng\":37.655004970729}]],\"2\":[[{\"lat\":55.775980538208,\"lng\":37.655193731189},{\"lat\":55.776082742673,\"lng\":37.655125334859},{\"lat\":55.776097451043,\"lng\":37.655194401741}],[{\"lat\":55.776083496949,\"lng\":37.655710726976},{\"lat\":55.776194375288,\"lng\":37.655634284019},{\"lat\":55.776178535545,\"lng\":37.655559852719}],[{\"lat\":55.776171747081,\"lng\":37.655123323202},{\"lat\":55.77675668201,\"lng\":37.654733397067},{\"lat\":55.776784778277,\"lng\":37.654754854739},{\"lat\":55.776882077943,\"lng\":37.654687799513},{\"lat\":55.776870952605,\"lng\":37.65463784337},{\"lat\":55.776819097179,\"lng\":37.654674053192}],[{\"lat\":55.776241140207,\"lng\":37.655438482761},{\"lat\":55.776365972096,\"lng\":37.655353322625},{\"lat\":55.776384074573,\"lng\":37.655308395624},{\"lat\":55.776468552684,\"lng\":37.655252069235},{\"lat\":55.776493066388,\"lng\":37.655205130577},{\"lat\":55.776814383046,\"lng\":37.654980830848},{\"lat\":55.776825508399,\"lng\":37.654930539429},{\"lat\":55.776893203276,\"lng\":37.654882594943},{\"lat\":55.776904705737,\"lng\":37.654937580228},{\"lat\":55.776872083996,\"lng\":37.654959708452}],[{\"lat\":55.77675064791,\"lng\":37.654705569148},{\"lat\":55.776818908613,\"lng\":37.655001282692}],[{\"lat\":55.776765544593,\"lng\":37.654751166701},{\"lat\":55.776737825444,\"lng\":37.654783353209}],[{\"lat\":55.776804954778,\"lng\":37.65492182225},{\"lat\":55.776778555615,\"lng\":37.654969766736},{\"lat\":55.776820228571,\"lng\":37.654983177781}],[{\"lat\":55.776387468786,\"lng\":37.655321806669},{\"lat\":55.776319584462,\"lng\":37.65500664711}],[{\"lat\":55.776388977325,\"lng\":37.655294314027},{\"lat\":55.776312418888,\"lng\":37.655347287655}],[{\"lat\":55.77638860019,\"lng\":37.654957026243},{\"lat\":55.776458370065,\"lng\":37.65527755022}],[{\"lat\":55.77635729799,\"lng\":37.654980495572},{\"lat\":55.776426690786,\"lng\":37.655297666788}],[{\"lat\":55.776349378152,\"lng\":37.65526548028},{\"lat\":55.776462895674,\"lng\":37.655185684562}],[{\"lat\":55.776368234906,\"lng\":37.65498585999},{\"lat\":55.776311664617,\"lng\":37.655073031783},{\"lat\":55.776340326907,\"lng\":37.655081748962},{\"lat\":55.77640783406,\"lng\":37.655003294349}],[{\"lat\":55.776437250548,\"lng\":37.65514343977},{\"lat\":55.776354280909,\"lng\":37.655203789473}],[{\"lat\":55.776424050845,\"lng\":37.655136063695},{\"lat\":55.776450450247,\"lng\":37.65517629683},{\"lat\":55.776447056039,\"lng\":37.6552862674}],[{\"lat\":55.776393880077,\"lng\":37.654962390661},{\"lat\":55.776358429395,\"lng\":37.655215859413}],[{\"lat\":55.776417639559,\"lng\":37.65505425632},{\"lat\":55.776335424148,\"lng\":37.655108571053}],[{\"lat\":55.776426690786,\"lng\":37.655100524426},{\"lat\":55.776343343989,\"lng\":37.655157521367}],[{\"lat\":55.776384074573,\"lng\":37.655313760042},{\"lat\":55.776410474002,\"lng\":37.654948309064}],[{\"lat\":55.776408588329,\"lng\":37.655071020126},{\"lat\":55.77641613102,\"lng\":37.655020728707},{\"lat\":55.776400291367,\"lng\":37.654961720109}]],\"1\":[[{\"lat\":55.776173255629,\"lng\":37.655146121979},{\"lat\":55.776245665842,\"lng\":37.655516266823}],[{\"lat\":55.776132524825,\"lng\":37.655159533024},{\"lat\":55.776209460752,\"lng\":37.65555113554}],[{\"lat\":55.776099336731,\"lng\":37.655183672905},{\"lat\":55.776177781271,\"lng\":37.655569911003}],[{\"lat\":55.776204935113,\"lng\":37.655167579651},{\"lat\":55.776265276918,\"lng\":37.655459940434}],[{\"lat\":55.776201918021,\"lng\":37.655154168606},{\"lat\":55.77609782818,\"lng\":37.655215859413}],[{\"lat\":55.776266785462,\"lng\":37.655481398106},{\"lat\":55.776158170151,\"lng\":37.65555113554}],[{\"lat\":55.776290922157,\"lng\":37.65541434288},{\"lat\":55.776070674263,\"lng\":37.65555113554},{\"lat\":55.77609782818,\"lng\":37.655349969864},{\"lat\":55.776259242742,\"lng\":37.655253410339}],[{\"lat\":55.776241140207,\"lng\":37.655178308487},{\"lat\":55.776022400586,\"lng\":37.655304372311},{\"lat\":55.776105370932,\"lng\":37.6553606987}],[{\"lat\":55.776227563301,\"lng\":37.655159533024},{\"lat\":55.776287905071,\"lng\":37.655451893806}],[{\"lat\":55.776316567378,\"lng\":37.655041515827},{\"lat\":55.776373891931,\"lng\":37.655323147774}],[{\"lat\":55.776352772369,\"lng\":37.655009329319},{\"lat\":55.776419148097,\"lng\":37.655304372311}],[{\"lat\":55.776417639559,\"lng\":37.654782682657},{\"lat\":55.776515694408,\"lng\":37.655239999294}],[{\"lat\":55.776521728545,\"lng\":37.654891312122},{\"lat\":55.776571510136,\"lng\":37.655138075352}],[{\"lat\":55.77658357839,\"lng\":37.654848396778},{\"lat\":55.776628834313,\"lng\":37.655092477798}],[{\"lat\":55.776633359902,\"lng\":37.654818892479},{\"lat\":55.776681632823,\"lng\":37.655057609081}],[{\"lat\":55.776690683989,\"lng\":37.654775977135},{\"lat\":55.776741973889,\"lng\":37.655025422573}],[{\"lat\":55.776749516516,\"lng\":37.6547062397},{\"lat\":55.776806840431,\"lng\":37.654977142811}],[{\"lat\":55.776796280769,\"lng\":37.65467941761},{\"lat\":55.776853604616,\"lng\":37.65495300293}],[{\"lat\":55.776823434181,\"lng\":37.654714286327},{\"lat\":55.776863410002,\"lng\":37.654903382063}],[{\"lat\":55.776845307748,\"lng\":37.654700875282},{\"lat\":55.776886037808,\"lng\":37.6548846066}],[{\"lat\":55.776865672783,\"lng\":37.654691487551},{\"lat\":55.776909419859,\"lng\":37.654903382063},{\"lat\":55.776845307748,\"lng\":37.654947638512}],[{\"lat\":55.776889809107,\"lng\":37.654674053192},{\"lat\":55.776929030601,\"lng\":37.654849737883}],[{\"lat\":55.776834748097,\"lng\":37.65489667654},{\"lat\":55.776995405348,\"lng\":37.654792070389}],[{\"lat\":55.776814383046,\"lng\":37.654829621315},{\"lat\":55.77723676711,\"lng\":37.654545307159},{\"lat\":55.777241292629,\"lng\":37.65446215868},{\"lat\":55.777571654079,\"lng\":37.654243558645}],[{\"lat\":55.776398782828,\"lng\":37.654982507229},{\"lat\":55.776462141406,\"lng\":37.655260115862}],[{\"lat\":55.776805331908,\"lng\":37.654786705971},{\"lat\":55.776910928378,\"lng\":37.654715627432},{\"lat\":55.776913945416,\"lng\":37.654668688774},{\"lat\":55.776960709472,\"lng\":37.654631137848}],[{\"lat\":55.777530170489,\"lng\":37.654008865356},{\"lat\":55.777002947926,\"lng\":37.654361575842},{\"lat\":55.777070831059,\"lng\":37.654661983252},{\"lat\":55.777141731095,\"lng\":37.654716968536},{\"lat\":55.777252606423,\"lng\":37.654645889997},{\"lat\":55.777297861569,\"lng\":37.654678076506},{\"lat\":55.777612383379,\"lng\":37.65446215868}],[{\"lat\":55.77714550237,\"lng\":37.654715627432},{\"lat\":55.77710326407,\"lng\":37.654628455639},{\"lat\":55.777076110854,\"lng\":37.654311954975}],[{\"lat\":55.777042923563,\"lng\":37.654333412647},{\"lat\":55.777071585316,\"lng\":37.654649913311}],[{\"lat\":55.776925259306,\"lng\":37.654794752598},{\"lat\":55.776825696964,\"lng\":37.654863148928}],[{\"lat\":55.776807594693,\"lng\":37.654700875282},{\"lat\":55.776307516125,\"lng\":37.655056267977}],[{\"lat\":55.776827205486,\"lng\":37.654798775911},{\"lat\":55.776234351755,\"lng\":37.655225247145}],[{\"lat\":55.776837010879,\"lng\":37.654841691256},{\"lat\":55.776250191476,\"lng\":37.655278891325}],[{\"lat\":55.776274328181,\"lng\":37.655324488878},{\"lat\":55.776111405132,\"lng\":37.655437141657}],[{\"lat\":55.776852850355,\"lng\":37.654915452003},{\"lat\":55.7763595608,\"lng\":37.655297666788}]]}"; auto root = jute::parser::parse(jsonRoads); unsigned int currentNodeId = 0; // Перебор этажей, в данном примере у нас их 3 (так как в либе json нет метода получения ключей))) for(int floor = 0; floor < root.size(); floor++) { //if (floor == 2) { auto objRoads = root[std::to_string(floor)]; // Перебор дорог for(int i=0; i<objRoads.size(); i++) { auto objNodes = objRoads[i]; std::vector<Node*> road; for(int j=0; j<objNodes.size(); j++) { auto objNode = objNodes[j]; double lat = objNode["lat"].as_double(); double lng = objNode["lng"].as_double(); road.push_back(new Node(currentNodeId++, lat, lng, floor)); } roads.AddRoad(road); } //} } roads.FillGraph(graph); } } struct TransitionInfo { unsigned int FromID; unsigned int ToID; }; void AddTransitionsExample01(Graph* graph) { if(graph != NULL) { std::string jsonString = "[{\"transitionId\":90,\"transitionTypeId\":8,\"directionTypeId\":3,\"shoppingCenterId\":57,\"shopId\":0,\"transitionShopId\":0,\"name\":\"\u0412\u044b\u0445\u043e\u0434\",\"floor\":1,\"radius\":100,\"transitionFrom\":0,\"transitionTo\":0,\"location\":{\"lat\":\"55.777013507532\",\"lng\":\"37.6546834409237\"}},{\"transitionId\":93,\"transitionTypeId\":8,\"directionTypeId\":3,\"shoppingCenterId\":57,\"shopId\":0,\"transitionShopId\":0,\"name\":\"\u0412\u0445\u043e\u0434\",\"floor\":1,\"radius\":100,\"transitionFrom\":0,\"transitionTo\":0,\"location\":{\"lat\":\"55.7759997722792\",\"lng\":\"37.6555082201958\"}},{\"transitionId\":97,\"transitionTypeId\":1,\"directionTypeId\":3,\"shoppingCenterId\":57,\"shopId\":0,\"transitionShopId\":0,\"name\":\"\u041b\u0435\u0441\u0442\u043d\u0438\u0446\u043001\",\"floor\":0,\"radius\":284,\"transitionFrom\":0,\"transitionTo\":105,\"location\":{\"lat\":\"55.7766808785588\",\"lng\":\"37.6550978422165\"}},{\"transitionId\":98,\"transitionTypeId\":1,\"directionTypeId\":3,\"shoppingCenterId\":57,\"shopId\":0,\"transitionShopId\":0,\"name\":\"\u041b\u0435\u0441\u043d\u0438\u0446\u043002\",\"floor\":0,\"radius\":284,\"transitionFrom\":0,\"transitionTo\":104,\"location\":{\"lat\":\"55.7766499537255\",\"lng\":\"37.6549516618252\"}},{\"transitionId\":99,\"transitionTypeId\":1,\"directionTypeId\":3,\"shoppingCenterId\":57,\"shopId\":0,\"transitionShopId\":0,\"name\":\"\u041b\u0435\u0441\u0442\u043d\u0438\u0446\u043003\",\"floor\":0,\"radius\":246,\"transitionFrom\":0,\"transitionTo\":106,\"location\":{\"lat\":\"55.7766114862155\",\"lng\":\"37.6552279293537\"}},{\"transitionId\":100,\"transitionTypeId\":1,\"directionTypeId\":3,\"shoppingCenterId\":57,\"shopId\":0,\"transitionShopId\":0,\"name\":\"\u041b\u0435\u0441\u0442\u043d\u0438\u0446\u043004\",\"floor\":0,\"radius\":359,\"transitionFrom\":0,\"transitionTo\":107,\"location\":{\"lat\":\"55.7764221651724\",\"lng\":\"37.6551447808742\"}},{\"transitionId\":101,\"transitionTypeId\":1,\"directionTypeId\":3,\"shoppingCenterId\":57,\"shopId\":0,\"transitionShopId\":0,\"name\":\"\u041b\u0435\u0441\u0442\u043d\u0438\u0446\u043005\",\"floor\":0,\"radius\":171,\"transitionFrom\":0,\"transitionTo\":108,\"location\":{\"lat\":\"55.7762905450208\",\"lng\":\"37.6553526520729\"}},{\"transitionId\":102,\"transitionTypeId\":1,\"directionTypeId\":3,\"shoppingCenterId\":57,\"shopId\":0,\"transitionShopId\":0,\"name\":\"\u041b\u0435\u0441\u0442\u043d\u0438\u0446\u043007\",\"floor\":0,\"radius\":171,\"transitionFrom\":0,\"transitionTo\":109,\"location\":{\"lat\":\"55.7762796080827\",\"lng\":\"37.6552849262953\"}},{\"transitionId\":104,\"transitionTypeId\":2,\"directionTypeId\":3,\"shoppingCenterId\":57,\"shopId\":0,\"transitionShopId\":0,\"name\":\"\u041b\u0435\u0441\u0442\u043d\u0438\u0446\u043012\",\"floor\":1,\"radius\":322,\"transitionFrom\":98,\"transitionTo\":110,\"location\":{\"lat\":\"55.7768339938356\",\"lng\":\"37.6546646654606\"}},{\"transitionId\":105,\"transitionTypeId\":2,\"directionTypeId\":3,\"shoppingCenterId\":57,\"shopId\":0,\"transitionShopId\":0,\"name\":\"\u041b\u0435\u0441\u0442\u043d\u0438\u0446\u043011\",\"floor\":1,\"radius\":284,\"transitionFrom\":97,\"transitionTo\":111,\"location\":{\"lat\":\"55.7768792494673\",\"lng\":\"37.6549355685711\"}},{\"transitionId\":106,\"transitionTypeId\":1,\"directionTypeId\":3,\"shoppingCenterId\":57,\"shopId\":0,\"transitionShopId\":0,\"name\":\"\u041b\u0435\u0441\u0442\u043d\u0438\u0446\u043013\",\"floor\":1,\"radius\":265,\"transitionFrom\":99,\"transitionTo\":112,\"location\":{\"lat\":\"55.7768272054864\",\"lng\":\"37.6552198827267\"}},{\"transitionId\":107,\"transitionTypeId\":1,\"directionTypeId\":3,\"shoppingCenterId\":57,\"shopId\":0,\"transitionShopId\":0,\"name\":\"\u041b\u0435\u0441\u0442\u043d\u0438\u0446\u043013\",\"floor\":1,\"radius\":265,\"transitionFrom\":100,\"transitionTo\":0,\"location\":{\"lat\":\"55.7764425304284\",\"lng\":\"37.6548470556736\"}},{\"transitionId\":108,\"transitionTypeId\":1,\"directionTypeId\":3,\"shoppingCenterId\":57,\"shopId\":0,\"transitionShopId\":0,\"name\":\"\u041b\u0435\u0441\u043d\u0438\u0446\u043014\",\"floor\":1,\"radius\":246,\"transitionFrom\":101,\"transitionTo\":113,\"location\":{\"lat\":\"55.7762856422558\",\"lng\":\"37.6553821563721\"}},{\"transitionId\":109,\"transitionTypeId\":1,\"directionTypeId\":3,\"shoppingCenterId\":57,\"shopId\":0,\"transitionShopId\":0,\"name\":\"\u041b\u0435\u0441\u0442\u043d\u0438\u0446\u043015\",\"floor\":1,\"radius\":265,\"transitionFrom\":102,\"transitionTo\":114,\"location\":{\"lat\":\"55.7762396316624\",\"lng\":\"37.6551756262779\"}},{\"transitionId\":110,\"transitionTypeId\":1,\"directionTypeId\":3,\"shoppingCenterId\":57,\"shopId\":0,\"transitionShopId\":0,\"name\":\"\u041b\u0435\u0441\u0442\u043d\u0438\u0446\u043022\",\"floor\":2,\"radius\":416,\"transitionFrom\":104,\"transitionTo\":0,\"location\":{\"lat\":\"55.7768585073093\",\"lng\":\"37.6546465605497\"}},{\"transitionId\":111,\"transitionTypeId\":1,\"directionTypeId\":3,\"shoppingCenterId\":57,\"shopId\":0,\"transitionShopId\":0,\"name\":\"\u041b\u0435\u0441\u0442\u043d\u0438\u0446\u043021\",\"floor\":2,\"radius\":397,\"transitionFrom\":105,\"transitionTo\":0,\"location\":{\"lat\":\"55.7769037629125\",\"lng\":\"37.6549228280783\"}},{\"transitionId\":112,\"transitionTypeId\":1,\"directionTypeId\":3,\"shoppingCenterId\":57,\"shopId\":0,\"transitionShopId\":0,\"name\":\"\u041b\u0435\u0441\u0442\u043d\u0438\u0446\u043033\",\"floor\":2,\"radius\":454,\"transitionFrom\":106,\"transitionTo\":0,\"location\":{\"lat\":\"55.7767155746841\",\"lng\":\"37.6551709324122\"}},{\"transitionId\":113,\"transitionTypeId\":1,\"directionTypeId\":3,\"shoppingCenterId\":57,\"shopId\":0,\"transitionShopId\":0,\"name\":\"\u041b\u0435\u0441\u0442\u043d\u0438\u0446\u043034\",\"floor\":2,\"radius\":341,\"transitionFrom\":108,\"transitionTo\":0,\"location\":{\"lat\":\"55.7761691071227\",\"lng\":\"37.655511572957\"}},{\"transitionId\":114,\"transitionTypeId\":1,\"directionTypeId\":3,\"shoppingCenterId\":57,\"shopId\":0,\"transitionShopId\":0,\"name\":\"\u041b\u0435\u0441\u0442\u043d\u0438\u0446\u043035\",\"floor\":2,\"radius\":359,\"transitionFrom\":109,\"transitionTo\":0,\"location\":{\"lat\":\"55.7761121594067\",\"lng\":\"37.6552715152502\"}}]"; auto root = jute::parser::parse(jsonString); std::vector<TransitionInfo> forNextEdges; #ifdef DEBUG_TEST_TRANSITIONS printf("Transition layerId: %d\n", layerId); #endif unsigned int crossLayerId = graph->GetMaxNodeID()+1; unsigned int layerId = crossLayerId+root.size()+1000; for(int i=0; i<root.size(); i++) { auto transition = root[i]; auto transitionId = transition["transitionId"].as_int(); auto name = transition["name"].as_string(); auto floor = transition["floor"].as_int(); auto location = transition["location"]; if(transition.get_type() == jute::JOBJECT) { double lat = location["lat"].as_double(); double lng = location["lng"].as_double(); // Поиск точек рядом на этаже Node* nereast = graph->GenNewNearestNodeInEdges(crossLayerId+i, lat, lng, floor); //graph->GetNearestNode(lat, lng, floor); if(nereast != NULL) { // Присоединяем переход к ближайшей ноде Node *node = graph->AddNode((unsigned int)(layerId+transitionId), name, lat, lng, floor); if(node != NULL) { // Два направления graph->AddEdge(nereast->GetID(), node->GetID()); graph->AddEdge(node->GetID(), nereast->GetID()); // Добавляем в очередь переходы между этажами auto transitionFrom = transition["transitionFrom"].as_int(); auto transitionTo = transition["transitionTo"].as_int(); if(transitionFrom > 0) { TransitionInfo infoForward; infoForward.FromID = (unsigned int)layerId+transitionFrom; infoForward.ToID = (unsigned int)layerId+transitionId; forNextEdges.push_back(infoForward); // В обратную сторону TransitionInfo infoBackward; infoBackward.FromID = (unsigned int)layerId+transitionId; infoBackward.ToID = (unsigned int)layerId+transitionFrom; forNextEdges.push_back(infoBackward); } if(transitionTo > 0) { TransitionInfo infoForward; infoForward.FromID = (unsigned int)layerId+transitionId; infoForward.ToID = (unsigned int)layerId+transitionTo; forNextEdges.push_back(infoForward); // В обратную сторону TransitionInfo infoBackward; infoBackward.FromID = (unsigned int)layerId+transitionTo; infoBackward.ToID = (unsigned int)layerId+transitionId; forNextEdges.push_back(infoBackward); } } else { printf("Error Add Transition\n"); } } else { printf("Error Find Nearest Node For Transition\n"); } } } //Перебираем очередь for(int j=0;j<forNextEdges.size();j++) { #ifdef DEBUG_TEST_TRANSITIONS Node *from = graph->GetNode(forNextEdges[j].FromID); Node *to =graph->GetNode(forNextEdges[j].ToID); if(from != NULL && to != NULL) { printf("Add Transition Edge: level %d (id_%d) -> level %d (id_%d))\n", from->GetLevel(), from->GetID(), to->GetLevel(), to->GetID()); } else { printf("Error Add Transition Edge (%d -> %d)\n", forNextEdges[j].FromID, forNextEdges[j].ToID); } #endif graph->AddEdge(forNextEdges[j].FromID, forNextEdges[j].ToID); } } }
153.874074
8,804
0.618158
[ "vector" ]
e0cb43ad3cd6fa5fe3f0d4bbfb7da60c102019cd
5,305
hh
C++
register/include/ignition/plugin/Register.hh
scpeters-test/ign-plugin
94482af3e9b2cc1cbb7c2dbeb2c7846f8283f0f6
[ "Apache-2.0" ]
10
2020-04-15T16:59:32.000Z
2022-03-18T20:36:17.000Z
register/include/ignition/plugin/Register.hh
scpeters-test/ign-plugin
94482af3e9b2cc1cbb7c2dbeb2c7846f8283f0f6
[ "Apache-2.0" ]
47
2020-05-04T15:07:18.000Z
2022-03-18T20:53:54.000Z
register/include/ignition/plugin/Register.hh
scpeters-test/ign-plugin
94482af3e9b2cc1cbb7c2dbeb2c7846f8283f0f6
[ "Apache-2.0" ]
11
2020-05-05T22:04:44.000Z
2022-03-18T13:59:46.000Z
/* * Copyright (C) 2017 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef IGNITION_PLUGIN_REGISTER_HH_ #define IGNITION_PLUGIN_REGISTER_HH_ #include <ignition/plugin/detail/Register.hh> // ------------- Add a set of plugins or a set of interfaces ------------------ /// \brief Add a plugin and interface from this shared library. /// /// This macro can be put in any namespace and may be called any number of /// times. It can be called multiple times on the same plugin class in order to /// register multiple interfaces, e.g.: /// /// \code /// IGNITION_ADD_PLUGIN(PluginClass, Interface1) /// IGNITION_ADD_PLUGIN(PluginClass, Interface2) /// /// /* Some other code */ /// /// IGNITION_ADD_PLUGIN(PluginClass, Interface3) /// \endcode /// /// Or you can list multiple interfaces in a single call to the macro, e.g.: /// /// \code /// IGNITION_ADD_PLUGIN(PluginClass, Interface1, Interface2, Interface3) /// \endcode /// /// If your library has multiple translation units (.cpp files) and you want to /// register plugins in multiple translation units, use this /// ignition/plugin/Register.hh header in ONE of the translation units, and then /// the ignition/plugin/RegisterMore.hh header in all of the rest of the /// translation units. #define IGNITION_ADD_PLUGIN(PluginClass, ...) \ DETAIL_IGNITION_ADD_PLUGIN(PluginClass, __VA_ARGS__) /// \brief Add an alias for one of your plugins. /// /// This macro can be put in any namespace and may be called any number of /// times. It can be called multiple times on the same plugin class in order to /// register multiple aliases, e.g.: /// /// \code /// IGNITION_ADD_PLUGIN_ALIAS(PluginClass, "PluginClass") /// IGNITION_ADD_PLUGIN_ALIAS(PluginClass, "SomeOtherName", "Yet another name") /// IGNOTION_ADD_PLUGIN_ALIAS(AnotherPluginClass, "Foo", "Bar", "Baz") /// \endcode /// /// You can give the same alias to multiple plugins, but then that alias can no /// longer be used to instantiate any plugin. /// /// If you give a plugin an alias string that matches the demangled symbol name /// of another plugin, then the Loader will always prefer to instantiate the /// plugin whose symbol name matches that string. #define IGNITION_ADD_PLUGIN_ALIAS(PluginClass, ...) \ DETAIL_IGNITION_ADD_PLUGIN_ALIAS(PluginClass, __VA_ARGS__) /// \brief Add a plugin factory. /// /// A plugin factory is a plugin that is able to generate objects that implement /// some interface. These objects can be passed off to a consumer, and as long /// as the object is alive, it will ensure that the shared library of the plugin /// remains loaded. The objects are handed off with a std::unique_ptr, so the /// raw pointer can be released from its std::unique_ptr and passed into any /// memory management system the consumer prefers. /// /// The inputs and output of a factory are defined using the /// ignition::plugin::Factory class in the ignition/plugin/Factory.hh header. /// /// The first argument of this macro should be the class that implements the /// factory's output interface. The second argument should be the factory /// definition. /// /// NOTE: If your factory has any input arguments, then you must define it /// outside of this macro, or else you will get a compilation error. This /// happens because macros will parse the commas between your template arguments /// as separators for the macro arguments. For example: /// /// \code /// class MyBase /// { /// public: virtual double SomeFunction() = 0; /// }; /// /// class MyType : public MyBase /// { /// public: MyType(double value); /// public: double SomeFunction() override; /// }; /// /// /* BAD! Will not compile: /// IGNITION_ADD_FACTORY(MyType, ignition::plugin::Factory<MyBase, double>); /// */ /// /// // Instead do this: /// using MyFactory = ignition::plugin::Factory<MyBase, double>; /// IGNITION_ADD_FACTORY(MyType, MyFactory); /// \endcode #define IGNITION_ADD_FACTORY(ProductType, FactoryType) \ DETAIL_IGNITION_ADD_FACTORY(ProductType, FactoryType) /// \brief Add an alias for a factory. /// /// This will do the same as IGNITION_ADD_FACTORY(), but you may also add in /// any number of strings which can then be used as aliases for this factory. /// For example: /// /// \code /// IGNITION_ADD_FACTORY_ALIAS(MyType, MyFactory, "Foo", "My favorite factory") /// \endcode /// /// This macro can be called any number of times for the same factory or for /// different factories. If you call this macro, you do not need to call /// IGNITION_ADD_FACTORY(), but there is nothing wrong with calling both (except /// it might imperceptibly increase your compile time). #define IGNITION_ADD_FACTORY_ALIAS(ProductType, FactoryType, ...) \ DETAIL_IGNITION_ADD_FACTORY_ALIAS(ProductType, FactoryType, __VA_ARGS__) #endif
37.624113
80
0.728746
[ "object" ]
e0cf7c05e8fa4a450b2c668d6281df30a729f54f
5,947
hpp
C++
Modules/ExampleModule/include/CommonTypes.hpp
pv6/smart-refinement-tool
1221a0a22ec0fc868cf922267fd0af73697025ea
[ "BSD-3-Clause" ]
null
null
null
Modules/ExampleModule/include/CommonTypes.hpp
pv6/smart-refinement-tool
1221a0a22ec0fc868cf922267fd0af73697025ea
[ "BSD-3-Clause" ]
null
null
null
Modules/ExampleModule/include/CommonTypes.hpp
pv6/smart-refinement-tool
1221a0a22ec0fc868cf922267fd0af73697025ea
[ "BSD-3-Clause" ]
null
null
null
#ifndef ANNOTATIONCOMMONTYPES_H #define ANNOTATIONCOMMONTYPES_H #include <array> #include <algorithm> #include <utility> #include <memory> #include <unordered_map> #include <functional> #include <vector> #include <fstream> static std::vector<std::string> UseCaseNames = { "ForegroundBackgroundClean", "SmartBrushLevelSet", "SmartBrushFastMarching", "SmartBrushFastMarching3D", "IntelligentScissors", "MagicWand", "Escultor", "LSMPropagation", "ChanVesePropagation", "SmartRefinement" }; enum AUXVOLUMERENDERING { GRADIENT, RESAMPLED }; enum Orientation { ZX, ZY, XY }; enum TOOLS { FBCLEAN, SMARTBRUSH_LS, SMARTBRUSH_FM, SMARTBRUSH_FM3D, INTELLIGENT_SCISSORS, MAGICWAND, ESCULTOR, PROPAGATION2D, CHANVESE_PROPAGATION2D, SMARTREFINEMENT, TOOLS_COUNT }; //! Types of filters enum INTENSITY_FILTERTYPE { NO_FILTER = 0, FILTER_GAUSS, FILTER_MEDIAN, FILTER_ANISO, FILTER_COUNT, FILTER_GRADIENT }; //! Mesh modification modes enum MESH_MODIF_MODE { MESH_MODIF_MODE_EXPANSION = 0, MESH_MODIF_MODE_SHRINKING, MESH_MODIF_MODE_COUNT }; //! Position of a Voxel typedef std::array<int, 3> VoxelPosition; //! Bounding box in 3D - two corner VoxelPosition points typedef std::array<VoxelPosition, 2> BBox3D; //! Position of a Pixel in the slice typedef std::array<int, 2> PixelPosition; //! Bounding box in 2D - two corner PixelPosition points typedef std::array<PixelPosition, 2> BBox2D; //! 2D-Matrix with padding template<typename T> struct Matrix2D { //! X-dimension int sizeX; //! Y-dimension int sizeY; //! Memory keeper T * data; //! Pointer to array that represents matrix T * arr; //! Zero-constructor Matrix2D() { sizeX = sizeY = 0; data = arr = nullptr; } //! Move constructor Matrix2D(Matrix2D<T> &&other) { sizeX = other.sizeX; sizeY = other.sizeY; data = other.data; arr = other.arr; other.arr = nullptr; other.data = nullptr; } //! Copy constructor - make a deep copy Matrix2D(const Matrix2D<T> &other) { sizeX = other.sizeX; sizeY = other.sizeY; const size_t allocSize = (sizeX + 2) * (sizeY + 2); data = new T[allocSize]{ 0 }; if (!data) { data = nullptr; return; } //std::memcpy(data, other.data, allocSize * sizeof(T)); std::copy(other.data, other.data + allocSize, data); arr = data + sizeX + 1; } /*! * \brief Constructor with memory allocation * \param x width of area * \param y height of area */ Matrix2D(const int x, const int y) : sizeX(x), sizeY(y) { data = new T[(x + 2) * (y + 2)]{ 0 }; std::fill(&data[0], &data[(x + 2) * (y + 2) - 1], static_cast<T>(0)); arr = data + x + 1; } //! Move assignment void operator = (Matrix2D<T>&& other) { sizeX = other.sizeX; sizeY = other.sizeY; data = other.data; arr = other.arr; other.arr = nullptr; other.data = nullptr; } /*! * \brief Fill matrix elements with certain value * \param value Value to fill with */ void fill(T value) { std::fill(&data[0], &data[(sizeX + 2) * (sizeY + 2) - 1], value); } /*! * \brief Fill matrix padding with certain value * \param Value to fill with */ void fillPadding(T paddingValue) { // Fill top padding std::fill(data, data + sizeX + 1, paddingValue); // Fill side padding elements row by row int curIndex = sizeX + 2; for (int i = 0; i < sizeY; i++) { // Fill left-most element data[curIndex] = paddingValue; curIndex += sizeX + 1; // Fill right-most element data[curIndex] = paddingValue; curIndex += 1; } // Fill bottom padding std::fill(data + curIndex, data + curIndex + sizeX + 1, paddingValue); } /*! * \brief Replace current cell with a new value * \param x x-index * \param y y-index * \param value value to be set into cell */ void set(const int x, const int y, const T &value) { arr[getIndex(x, y)] = value; } /*! * \brief Get value of a cell * \param x x-index * \param y y-index */ T get(const int x, const int y) const { return arr[getIndex(x, y)]; } /*! * \brief Iterate through every cell * \param func Functor */ void each(std::function<void(T&)> func) { const int size = (sizeX + 2) * (sizeY + 2); for (int i = 0; i < size; i++) { func(data[i]); } } /*! * \brief Iterate through every cell * \param func Functor */ void each(std::function<void(const T&)> func) const { const int size = (sizeX + 2) * (sizeY + 2); for (int i = 0; i < size; i++) { func(data[i]); } } /* * \brief Export matrix to file by fstream * \param file Output fstream */ void toFile(std::fstream &file) const { file.write((char*)data, sizeof(T) * (sizeX + 2) * (sizeY + 2)); } /* * \brief Export matrix to file by name * \param file Output file name */ void toFile(const std::string &name) const { auto file = std::fstream(name, std::ios::out | std::ios::binary); toFile(file); file.close(); } //! Destructor ~Matrix2D() { if (data != nullptr) delete[] data; data = nullptr; } private: /*! * \brief Get index in data array according to padding * \param x x-index * \param y y-index */ inline int getIndex(const int x, const int y) const { // return y * sizeX + x; const int pad = 2 * (y + 1); return y * sizeX + x + pad; } }; #endif // SMARTBRUSHLEVELSET_H
22.612167
78
0.571717
[ "mesh", "vector", "3d" ]
e0f0ce8e296db8a51cb9f76ef5ca46766a5279fe
11,685
cpp
C++
src/RTL/Component/Importing/CIFXShaderLitTextureDecoder.cpp
alemuntoni/u3d
7907b907464a2db53dac03fdc137dcb46d447513
[ "Apache-2.0" ]
44
2016-05-06T00:47:11.000Z
2022-02-11T06:51:37.000Z
src/RTL/Component/Importing/CIFXShaderLitTextureDecoder.cpp
alemuntoni/u3d
7907b907464a2db53dac03fdc137dcb46d447513
[ "Apache-2.0" ]
3
2016-06-27T12:37:31.000Z
2021-03-24T12:39:48.000Z
src/RTL/Component/Importing/CIFXShaderLitTextureDecoder.cpp
alemuntoni/u3d
7907b907464a2db53dac03fdc137dcb46d447513
[ "Apache-2.0" ]
15
2016-02-28T11:08:30.000Z
2021-06-01T03:32:01.000Z
//*************************************************************************** // // Copyright (c) 2001 - 2006 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //*************************************************************************** /** @file CIFXShaderLitTextureDecoder2.cpp Implementation of the CIFXShaderLitTextureDecoder. The CIFXShaderLitTextureDecoder is used by the CIFXLoadManager to load shader resources into the scene graph's shader resource palette. CIFXMaterialLoader exposes the IFXDecoderX interface to the CIFXLoadManager for this purpose. */ #include "CIFXShaderLitTextureDecoder.h" #include "IFXCoreCIDs.h" #include "IFXSceneGraph.h" #include "IFXPalette.h" #include "IFXBlockTypes.h" #include "IFXCheckX.h" // Constructor CIFXShaderLitTextureDecoder::CIFXShaderLitTextureDecoder() : IFXDEFINEMEMBER(m_pShaderLitTexture), IFXDEFINEMEMBER(m_pCoreServices), IFXDEFINEMEMBER(m_pDataBlockQueueX), IFXDEFINEMEMBER(m_pBitStreamX) { m_uRefCount = 0; m_uLoadId = 0; m_eShaderMode = IFX_SHADER_STANDARD; } // Destructor CIFXShaderLitTextureDecoder::~CIFXShaderLitTextureDecoder() { } // IFXUnknown U32 CIFXShaderLitTextureDecoder::AddRef() { return ++m_uRefCount; } U32 CIFXShaderLitTextureDecoder::Release() { if ( 1 == m_uRefCount ) { delete this; return 0; } return --m_uRefCount; } IFXRESULT CIFXShaderLitTextureDecoder::QueryInterface( IFXREFIID interfaceId, void** ppInterface ) { IFXRESULT rc = IFX_OK; if ( ppInterface ) { if ( interfaceId == IID_IFXDecoderX ) { *ppInterface = ( IFXDecoderX* ) this; this->AddRef(); } else if ( interfaceId == IID_IFXUnknown ) { *ppInterface = ( IFXUnknown* ) this; this->AddRef(); } else { *ppInterface = NULL; rc = IFX_E_UNSUPPORTED; } } else { rc = IFX_E_INVALID_POINTER; } return rc; } // IFXDecoderX // Initialize and get a reference to the core services object void CIFXShaderLitTextureDecoder::InitializeX(const IFXLoadConfig &lc) { // Initialize the data block queue IFXRELEASE(m_pDataBlockQueueX); IFXCHECKX(IFXCreateComponent( CID_IFXDataBlockQueueX, IID_IFXDataBlockQueueX, (void**)&m_pDataBlockQueueX )); // Store the core services pointer lc.m_pCoreServices->AddRef(); IFXRELEASE(m_pCoreServices); m_pCoreServices = lc.m_pCoreServices; m_uLoadId = lc.m_loadId; m_bExternal = lc.m_external; } // Provide next block of data to the loader void CIFXShaderLitTextureDecoder::PutNextBlockX( IFXDataBlockX &rDataBlockX ) { if(NULL == m_pDataBlockQueueX) { IFXCHECKX(IFX_E_NOT_INITIALIZED); } m_pDataBlockQueueX->AppendBlockX( rDataBlockX ); if (NULL == m_pShaderLitTexture) { U32 uBlockType; rDataBlockX.GetBlockTypeX(uBlockType); IFXDECLARELOCAL(IFXUnknown,pObject); IFXCHECKX(IFXCreateComponent( CID_IFXShaderLitTexture, IID_IFXUnknown, (void**)&pObject )); IFXDECLARELOCAL(IFXMarker,pMarker ); IFXCHECKX(pObject->QueryInterface( IID_IFXMarker, (void**)&pMarker )); IFXDECLARELOCAL(IFXSceneGraph,pSceneGraph); IFXCHECKX(m_pCoreServices->GetSceneGraph( IID_IFXSceneGraph, (void**)&pSceneGraph )); IFXCHECKX(pMarker->SetSceneGraph( pSceneGraph )); pMarker->SetExternalFlag(m_bExternal); pMarker->SetPriority(rDataBlockX.GetPriorityX(), FALSE, FALSE); IFXDECLARELOCAL( IFXBitStreamX, pBitStreamX ); IFXCHECKX(IFXCreateComponent( CID_IFXBitStreamX, IID_IFXBitStreamX, (void**)&pBitStreamX )); pBitStreamX->SetDataBlockX( rDataBlockX ); IFXString sBlockName; pBitStreamX->ReadIFXStringX( sBlockName ); IFXDECLARELOCAL(IFXNameMap, pNameMap); m_pCoreServices->GetNameMap(IID_IFXNameMap, (void**)&pNameMap); IFXCHECKX(pNameMap->Map(m_uLoadId, IFXSceneGraph::SHADER, sBlockName)); IFXDECLARELOCAL(IFXPalette,pSGPalette); IFXCHECKX(pSceneGraph->GetPalette( IFXSceneGraph::SHADER, &pSGPalette )); U32 uResourceID; IFXRESULT iResultPaletteFind = pSGPalette->Find( &sBlockName, &uResourceID ); if ( IFX_E_CANNOT_FIND == iResultPaletteFind ) { IFXCHECKX(pSGPalette->Add( &sBlockName, &uResourceID )); } IFXCHECKX(pSGPalette->SetResourcePtr( uResourceID, pObject )); IFXRELEASE( m_pShaderLitTexture ); IFXCHECKX(pObject->QueryInterface( IID_IFXShaderLitTexture, (void**)&m_pShaderLitTexture)); } } void CIFXShaderLitTextureDecoder::TransferX(IFXRESULT &rWarningPartialTransfer) { if(NULL == m_pCoreServices || NULL == m_pShaderLitTexture) { IFXCHECKX(IFX_E_NOT_INITIALIZED); } // For each data block in the list BOOL bDone = FALSE; while (FALSE == bDone) { // Get the next data block IFXDECLARELOCAL(IFXDataBlockX,pDataBlockX); m_pDataBlockQueueX->GetNextBlockX( pDataBlockX, bDone); if(pDataBlockX) { // Determine the block type U32 uBlockType = 0; pDataBlockX->GetBlockTypeX( uBlockType ); // Process the data block switch ( uBlockType ) { case BlockType_ResourceLitTextureShaderU3D: DecodeShaderLitTextureU3DX( *pDataBlockX ); break; default: IFXCHECKX(IFX_E_UNSUPPORTED); break; } // end switch (uBlockType) } } rWarningPartialTransfer = IFX_OK; } // Private methods void CIFXShaderLitTextureDecoder::DecodeShaderLitTextureU3DX(IFXDataBlockX &rDataBlockX) { U32 id = 0; // Get the scene graph IFXDECLARELOCAL(IFXSceneGraph,pSceneGraph); IFXCHECKX(m_pCoreServices->GetSceneGraph(IID_IFXSceneGraph, (void**)&pSceneGraph)); // Get the shader resource palette IFXDECLARELOCAL(IFXPalette,pShaderPalette); IFXCHECKX(pSceneGraph->GetPalette( IFXSceneGraph::SHADER, &pShaderPalette)); // Get the material resource palette IFXDECLARELOCAL(IFXPalette,pMaterialResourcePalette); IFXCHECKX(pSceneGraph->GetPalette( IFXSceneGraph::MATERIAL, &pMaterialResourcePalette)); // Get the texture resource palette IFXDECLARELOCAL(IFXPalette,pTextureResourcePalette); IFXCHECKX(pSceneGraph->GetPalette( IFXSceneGraph::TEXTURE, &pTextureResourcePalette)); // Create the bitstream and set up { IFXRELEASE(m_pBitStreamX); IFXCHECKX(IFXCreateComponent( CID_IFXBitStreamX, IID_IFXBitStreamX, (void**)&m_pBitStreamX )); m_pBitStreamX->SetDataBlockX( rDataBlockX ); } // 1. Decode the shader name IFXString sName; m_pBitStreamX->ReadIFXStringX(sName); IFXDECLARELOCAL(IFXNameMap, pNameMap); m_pCoreServices->GetNameMap(IID_IFXNameMap, (void**)&pNameMap); IFXCHECKX(pNameMap->Map(m_uLoadId, IFXSceneGraph::SHADER, sName)); U32 uVal = 0; F32 fVal = 0; // 2. Shader attributes U32 m_pBitStreamX->ReadU32X( uVal ); IFXCHECKX(m_pShaderLitTexture->SetLightingEnabled( uVal & 0x00000001 )); IFXCHECKX(m_pShaderLitTexture->SetAlphaTestEnabled( (uVal & 0x00000002) >> 1 )); IFXCHECKX(m_pShaderLitTexture->GetRenderMaterial().SetUseVertexColors( (uVal & 0x00000004) >> 2 )); // 3. Alpha Test Reference m_pBitStreamX->ReadF32X( fVal ); IFXCHECKX(m_pShaderLitTexture->GetRenderBlend().SetReference( fVal )); // 4. Alpha Test Compare Function m_pBitStreamX->ReadU32X( uVal ); IFXCHECKX(m_pShaderLitTexture->GetRenderBlend().SetTestFunc( (IFXenum)uVal )); // 5. Color Buffer Blend Function m_pBitStreamX->ReadU32X( uVal ); IFXCHECKX(m_pShaderLitTexture->GetRenderBlend().SetBlendFunc( (IFXenum)uVal )); // 6. Shader Render Pass Enables m_pBitStreamX->ReadU32X( uVal ); // Setting this value does not return an IFXRESULT m_pShaderLitTexture->SetRenderPassFlags( uVal ); // 7. Decode the shader channels U32 uChannels = 0; m_pBitStreamX->ReadU32X( uChannels ); IFXCHECKX(m_pShaderLitTexture->SetChannels( uChannels )); // 8. Alpha texture channels U32 m_pBitStreamX->ReadU32X( uVal ); IFXCHECKX(m_pShaderLitTexture->SetAlphaTextureChannels( uVal )); // 9. Decode the material name (optional) m_pBitStreamX->ReadIFXStringX(sName); IFXCHECKX(pNameMap->Map(m_uLoadId, IFXSceneGraph::MATERIAL, sName)); // 9.1 Look for a material with the same name in the material palette IFXRESULT iFindResult = pMaterialResourcePalette->Find(&sName, &id); if (IFXFAILURE(iFindResult)) { // If not found, add the material to the palette IFXCHECKX(pMaterialResourcePalette->Add(&sName, &id)); } /* Should not need to create the material; adding to the palette is enough */ // 9.2 Link to the material IFXCHECKX(m_pShaderLitTexture->SetMaterialID(id)); // Texture layers: U8 u8Value = 0 ; IFXMatrix4x4 matrix ; U32 i; for ( i = 0; i < IFX_MAX_TEXUNITS; i++) { if (uChannels & (1 << i) ) { // Decode the texture name (optional) m_pBitStreamX->ReadIFXStringX(sName); IFXCHECKX(pNameMap->Map(m_uLoadId, IFXSceneGraph::TEXTURE, sName)); // Look for a texture with the same name in the texture palette IFXRESULT iFindResult = pTextureResourcePalette->Find(&sName, &id); if (IFXFAILURE(iFindResult)) { // Add the texture name to the palette if not found IFXCHECKX(pTextureResourcePalette->Add(&sName, &id)); } // Should not need to create the texture object; adding to the palette is enough // Link to the texture IFXCHECKX(m_pShaderLitTexture->SetTextureID( i, id )); // Decode the texture intensity m_pBitStreamX->ReadF32X( fVal ); IFXCHECKX(m_pShaderLitTexture->SetTextureIntensity( i, fVal )); // Decode the texture blend function m_pBitStreamX->ReadU8X(u8Value); IFXCHECKX(m_pShaderLitTexture->SetBlendFunction( i, (IFXShaderLitTexture::BlendFunction)u8Value )); // Decode the texture blend source m_pBitStreamX->ReadU8X(u8Value); IFXCHECKX(m_pShaderLitTexture->SetBlendSource( i, (IFXShaderLitTexture::BlendSource)u8Value )); // Decode the texture blend constant m_pBitStreamX->ReadF32X(fVal); IFXCHECKX(m_pShaderLitTexture->SetBlendConstant( i, fVal )); // Decode the texture texture mode m_pBitStreamX->ReadU8X(u8Value); IFXCHECKX(m_pShaderLitTexture->SetTextureMode( i, (IFXShaderLitTexture::TextureMode)u8Value )); // Decode the texture texture transform F32* pElement = matrix.Raw(); U32 ii; for ( ii = 0; ii < 16 ; ii++) m_pBitStreamX->ReadF32X(pElement[ii]); IFXCHECKX(m_pShaderLitTexture->SetTextureTransform(i, &matrix)); // Decode the texture wrap transform pElement = matrix.Raw(); for ( ii = 0; ii < 16 ; ii++) m_pBitStreamX->ReadF32X(pElement[ii]); IFXCHECKX(m_pShaderLitTexture->SetWrapTransform(i, &matrix)); // Decode the texture repeat value m_pBitStreamX->ReadU8X(u8Value); IFXCHECKX(m_pShaderLitTexture->SetTextureRepeat( i, u8Value )); } } } IFXRESULT IFXAPI_CALLTYPE CIFXShaderLitTextureDecoder_Factory( IFXREFIID interfaceId, void** ppInterface ) { IFXRESULT rc = IFX_OK; if ( ppInterface ) { // Create the CIFXLoadManager component. CIFXShaderLitTextureDecoder *pComponent = new CIFXShaderLitTextureDecoder; if ( pComponent ) { // Perform a temporary AddRef for our usage of the component. pComponent->AddRef(); // Attempt to obtain a pointer to the requested interface. rc = pComponent->QueryInterface( interfaceId, ppInterface ); // Perform a Release since our usage of the component is now // complete. Note: If the QI fails, this will cause the // component to be destroyed. pComponent->Release(); } else { rc = IFX_E_OUT_OF_MEMORY; } } else { rc = IFX_E_INVALID_POINTER; } IFXRETURN(rc); }
30.994695
110
0.737612
[ "render", "object", "transform" ]
804232431c755706a7e66fc0f5b4c7a529e8bb5d
3,765
hpp
C++
src/geometry.hpp
haskelladdict/mcell_ng
6a84b1fc39bc1bb8cd9bd19e249a6381a24c5eb5
[ "BSD-3-Clause" ]
null
null
null
src/geometry.hpp
haskelladdict/mcell_ng
6a84b1fc39bc1bb8cd9bd19e249a6381a24c5eb5
[ "BSD-3-Clause" ]
null
null
null
src/geometry.hpp
haskelladdict/mcell_ng
6a84b1fc39bc1bb8cd9bd19e249a6381a24c5eb5
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2015 Markus Dittrich // Licensed under BSD license, see LICENSE file for details #ifndef GEOMETRY_HPP #define GEOMETRY_HPP #include <array> #include <memory> #include "molecules.hpp" #include "species.hpp" #include "util.hpp" #include "vector.hpp" namespace geom { // this epsilon is used for geometrical comparison. Anything smaller than that // is assumed to be identical. // FIXME: This is currently chosen arbitrarily and requires more thinking. const double EPSILON = 1e-12; const double EPSILON_2 = 1e-24; // MeshProp describe properties of MeshElements. Each MeshElement can only have // one of MeshProp. Transparent, absorptive, and reflective mesh elements are // transparent, absorptive, and reflective toward diffusing volume molecules, // respectively. Translucent meshes have a certain probability of letting a // molecule through. enum class MeshProp { transparent , absorptive , reflective , translucent }; // MeshElement describes a single triangle on a mesh. It consists of the // triangle vertices and also the triangles uv and normal vectors. class MeshElement { public: MeshElement(const Vec3& a, const Vec3& b, const Vec3& c, MeshProp prop = MeshProp::transparent); Vec3 a, b, c; // triangle vertices Vec3 u, v; // triangle vectors Vec3 n; // normal vector Vec3 n_norm; // normalized normal vector - precomputed for efficiency MeshProp prop; // properties of this element }; using Mesh = Rvector<MeshElement>; // create_rectangle is a helper function for generating a rectangular geometry // primitive. This function returns a vector with pointers to all MeshElements. //Mesh create_rectangle(const Vec3& llc, const Vec3& urc, MeshPropPtr prop = nullptr); // intersect tests for ray triangle intersections. Possible return values are // 0: triangle and ray segment intersect, in this case hitPoint contains the // location of the intersection point // 1: triangle and ray intersect but ray segment does not reach the triangle // 2: triangle and ray do not intersect // 3: ray and triangle are co-planar // 4: triangle is degenerate int intersect(const Vec3& p0, const Vec3& disp, const MeshElement* m, Vec3* hitPoint); // Tet describes a tetrahedron consisting of four triangular MeshElements via // indices m1 .. m4 into the Mesh vector of MeshElements. In addition, a Tet // knows the indices t1 .. t4 to its neighboring Tet elements. A Tet index of // unset indicates that there is no neighboring Tet and we're thus at the // edge of the model geometry. // NOTE: Since MeshElements are shared between up to two Tets, they can either // be oriented with their normal to the outside or with their normal to the // inside (indicated by o1, o2, ... o4). If they are oriented normal in we have // to take that into account when checking for collisions. struct Tet { const static size_t unset = std::numeric_limits<size_t>::max(); Tet(size_t i) : ID(i) {} // our index size_t ID; // indices of MeshElements std::array<size_t, 4> m{{unset, unset, unset, unset}}; // indices of neighboring Tets std::array<size_t, 4> t{{unset, unset, unset, unset}}; // orientation of MeshElements with respect to Tet; // 1 indicates normal out, -1 normal in std::array<int, 4> o{{0, 0, 0, 0 }}; }; using Tets = Rvector<Tet>; using TetMeshes = std::array<const MeshElement*, 4>; // tetFaces lists the indices of all triangles that make up the four // faces of a tet const Rvector<Rvector<size_t>> tetFaces{Rvector<size_t>{0, 2, 1} ,Rvector<size_t>{0, 1, 3} ,Rvector<size_t>{1, 2, 3} ,Rvector<size_t>{2, 0, 3}}; } #endif
33.026316
86
0.706242
[ "mesh", "geometry", "vector", "model" ]
8043876f27d679f259102d401ff9fe88b15eb496
9,341
cpp
C++
demos/rlPlanDemo/ConfigurationSpaceScene.cpp
mcx/rl
aa6eb334b5279ece8523258957b70e3b8c0c42ce
[ "BSD-2-Clause" ]
null
null
null
demos/rlPlanDemo/ConfigurationSpaceScene.cpp
mcx/rl
aa6eb334b5279ece8523258957b70e3b8c0c42ce
[ "BSD-2-Clause" ]
null
null
null
demos/rlPlanDemo/ConfigurationSpaceScene.cpp
mcx/rl
aa6eb334b5279ece8523258957b70e3b8c0c42ce
[ "BSD-2-Clause" ]
null
null
null
// // Copyright (c) 2009, Markus Rickert // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include <QGraphicsSceneMouseEvent> #include <QPainter> #include "ConfigurationModel.h" #include "ConfigurationSpaceScene.h" #include "ConfigurationSpaceThread.h" #include "MainWindow.h" #include "Thread.h" #include "Viewer.h" ConfigurationSpaceScene::ConfigurationSpaceScene(QObject* parent) : QGraphicsScene(parent), axis(), delta(), maximum(), minimum(), model(nullptr), range(), steps(), collisions(true), configuration(nullptr), data(), edges(nullptr), image(), path(nullptr), thread(new ConfigurationSpaceThread(this)) { this->axis[0] = 0; this->axis[1] = 1; this->delta[0] = 1; this->delta[1] = 1; this->thread->scene = this; this->configuration = this->addEllipse(-3, -3, 6, 6, QPen(Qt::NoPen), QBrush((QColor(247, 127, 7)))); this->configuration->setFlag(QGraphicsItem::ItemIgnoresTransformations); this->configuration->setVisible(false); this->configuration->setZValue(4); this->edges = this->createItemGroup(QList<QGraphicsItem*>()); this->edges->setZValue(2); QPen pathPen(QColor(55, 176, 55), 2); pathPen.setCosmetic(true); this->path = this->addPath(QPainterPath(), pathPen); this->path->setZValue(3); QObject::connect( this->thread, SIGNAL(addCollision(const int&, const int&, const unsigned char&)), this, SLOT(addCollision(const int&, const int&, const unsigned char&)) ); QObject::connect(this->thread, SIGNAL(finished()), this, SIGNAL(evalFinished())); } ConfigurationSpaceScene::~ConfigurationSpaceScene() { this->thread->stop(); } void ConfigurationSpaceScene::addCollision(const int& x, const int& y, const unsigned char& rgb) { this->data[y * this->steps[0] + x] = rgb; this->invalidate( this->minimum[0] + x * this->delta[0], this->minimum[1] + y * this->delta[1], this->delta[0], this->delta[1], QGraphicsScene::BackgroundLayer ); } void ConfigurationSpaceScene::clear() { this->reset(); this->resetCollisions(); } void ConfigurationSpaceScene::drawBackground(QPainter* painter, const QRectF& rect) { painter->fillRect(rect, this->palette().color(QPalette::Window)); if (this->collisions) { QRectF target = rect.intersected(this->sceneRect()); QRectF source( (target.x() - this->minimum[0]) / this->delta[0], (target.y() - this->minimum[1]) / this->delta[1], target.width() / this->delta[0], target.height() / this->delta[1] ); painter->drawImage(target, image, source, Qt::NoFormatConversion); } } void ConfigurationSpaceScene::drawConfiguration(const rl::math::Vector& q) { this->configuration->setPos( q(this->axis[0]), q(this->axis[1]) ); } void ConfigurationSpaceScene::drawConfigurationEdge(const rl::math::Vector& u, const rl::math::Vector& v, const bool& free) { QGraphicsLineItem* line = this->addLine( u(this->axis[0]), u(this->axis[1]), v(this->axis[0]), v(this->axis[1]), QPen(QBrush(QColor(96, 96, 96)), 0) ); this->edges->addToGroup(line); } void ConfigurationSpaceScene::drawConfigurationVertex(const rl::math::Vector& q, const bool& free) { } void ConfigurationSpaceScene::drawConfigurationPath(const rl::plan::VectorList& path) { this->resetPath(); if (path.empty()) { return; } QPainterPath painterPath; painterPath.moveTo(path.front()(this->axis[0]), path.front()(this->axis[1])); for (rl::plan::VectorList::const_iterator i = ++path.begin(); i != path.end(); ++i) { painterPath.lineTo((*i)(this->axis[0]), (*i)(this->axis[1])); } this->path->setPath(painterPath); } void ConfigurationSpaceScene::drawLine(const rl::math::Vector& xyz0, const rl::math::Vector& xyz1) { } void ConfigurationSpaceScene::drawPoint(const rl::math::Vector& xyz) { } void ConfigurationSpaceScene::drawSphere(const rl::math::Vector& center, const rl::math::Real& radius) { } void ConfigurationSpaceScene::drawSweptVolume(const rl::plan::VectorList& path) { } void ConfigurationSpaceScene::drawWork(const rl::math::Transform& t) { } void ConfigurationSpaceScene::drawWorkEdge(const rl::math::Vector& u, const rl::math::Vector& v) { } void ConfigurationSpaceScene::drawWorkPath(const rl::plan::VectorList& path) { } void ConfigurationSpaceScene::drawWorkVertex(const rl::math::Vector& q) { } void ConfigurationSpaceScene::eval() { if (nullptr == this->model) { return; } if (this->model->getDofPosition() < 2) { return; } this->resetCollisions(); this->thread->start(); } void ConfigurationSpaceScene::init() { this->clear(); if (nullptr == this->model) { return; } if (this->model->getDofPosition() < 2) { return; } rl::math::Vector maximum = this->model->getMaximum(); rl::math::Vector minimum = this->model->getMinimum(); this->maximum[0] = maximum(this->axis[0]); this->maximum[1] = maximum(this->axis[1]); this->minimum[0] = minimum(this->axis[0]); this->minimum[1] = minimum(this->axis[1]); this->range[0] = std::abs(this->maximum[0] - this->minimum[0]); this->range[1] = std::abs(this->maximum[1] - this->minimum[1]); this->steps[0] = static_cast<int>(std::ceil(this->range[0] / this->delta[0])); this->steps[1] = static_cast<int>(std::ceil(this->range[1] / this->delta[1])); this->configuration->setPos( (*MainWindow::instance()->q)(this->axis[0]), (*MainWindow::instance()->q)(this->axis[1]) ); this->data.assign(this->steps[0] * this->steps[1], 128); #if QT_VERSION >= 0x050500 this->image = QImage(this->data.data(), this->steps[0], this->steps[1], this->steps[0], QImage::Format_Grayscale8); #else this->image = QImage(this->data.data(), this->steps[0], this->steps[1], this->steps[0], QImage::Format_Indexed8); QVector<QRgb> colors; colors.reserve(256); for (int i = 0; i < 256; ++i) { colors.push_back(qRgb(i, i, i)); } this->image.setColorTable(colors); #endif this->setSceneRect(this->minimum[0], this->minimum[1], this->range[0], this->range[1]); } void ConfigurationSpaceScene::mouseMoveEvent(QGraphicsSceneMouseEvent* mouseEvent) { this->mousePressEvent(mouseEvent); } void ConfigurationSpaceScene::mousePressEvent(QGraphicsSceneMouseEvent* mouseEvent) { if (nullptr == this->model) { return; } if (this->model->getDofPosition() < 2) { return; } if (Qt::LeftButton == mouseEvent->buttons()) { if (!MainWindow::instance()->thread->isRunning()) { qreal x = qBound(this->minimum[0], mouseEvent->scenePos().x(), this->maximum[0]); qreal y = qBound(this->minimum[1], mouseEvent->scenePos().y(), this->maximum[1]); (*MainWindow::instance()->q)(this->axis[0]) = x; (*MainWindow::instance()->q)(this->axis[1]) = y; MainWindow::instance()->configurationModel->invalidate(); this->drawConfiguration(*MainWindow::instance()->q); MainWindow::instance()->viewer->drawConfiguration(*MainWindow::instance()->q); } } } void ConfigurationSpaceScene::reset() { this->thread->stop(); this->resetEdges(); this->resetLines(); this->resetPath(); } void ConfigurationSpaceScene::resetCollisions() { std::fill(this->data.begin(), this->data.end(), 128); this->invalidate(this->sceneRect(), QGraphicsScene::BackgroundLayer); } void ConfigurationSpaceScene::resetEdges() { qDeleteAll(this->edges->childItems()); } void ConfigurationSpaceScene::resetLines() { } void ConfigurationSpaceScene::resetPath() { this->path->setPath(QPainterPath()); } void ConfigurationSpaceScene::resetPoints() { } void ConfigurationSpaceScene::resetSpheres() { } void ConfigurationSpaceScene::resetVertices() { } void ConfigurationSpaceScene::showMessage(const std::string& message) { } void ConfigurationSpaceScene::toggleCollisions(const bool& doOn) { this->collisions = doOn; this->invalidate(this->sceneRect(), QGraphicsScene::BackgroundLayer); } void ConfigurationSpaceScene::toggleConfiguration(const bool& doOn) { this->configuration->setVisible(doOn); } void ConfigurationSpaceScene::toggleConfigurationEdges(const bool& doOn) { this->edges->setVisible(doOn); } void ConfigurationSpaceScene::togglePathEdges(const bool& doOn) { this->path->setVisible(doOn); }
23.411028
118
0.703779
[ "vector", "model", "transform" ]
80468ca8801de0b47a2abfe48bc6f4bae44afc2a
624
cpp
C++
src/bounce/renderer/ctor.cpp
cbosoft/bounce
f63e5ad1aabe201debf7a9a73525e93973c34932
[ "MIT" ]
null
null
null
src/bounce/renderer/ctor.cpp
cbosoft/bounce
f63e5ad1aabe201debf7a9a73525e93973c34932
[ "MIT" ]
null
null
null
src/bounce/renderer/ctor.cpp
cbosoft/bounce
f63e5ad1aabe201debf7a9a73525e93973c34932
[ "MIT" ]
null
null
null
#include <bounce/renderer/renderer.hpp> /** * Construct Renderer. Set most things to zero. Create an empty fallback Texture called "null". * * This creates the Renderer object, but it still needs to be initialised by calling the Renderer#init method. This is * done in Game#setup. */ Renderer::Renderer() : game(nullptr) , window_size({0, 0}) , _window_scale({1, 1}) , aspect_ratio(1.0) , window(nullptr) , _screen_effect("default") , vbuf(0) , varr(0) , fbo(0) , txt(0) , qbuf(0) , qarr(0) , _max_fps(1) , _min_mspf(1) , _actual_fps(1) { this->set_max_fps(60); this->textures["null"] = new Texture(nullptr); }
22.285714
118
0.684295
[ "object" ]
805e2df712d989bf92ed69f39985192542aff378
10,968
cpp
C++
src/demo/grasp_poses_visualizer_demo.cpp
NateWright/MoveItGrasps
10330ff38c72075035a69ed754fa9ed40a7c846b
[ "BSD-3-Clause" ]
55
2019-03-14T01:45:28.000Z
2022-03-27T16:39:36.000Z
src/demo/grasp_poses_visualizer_demo.cpp
NateWright/MoveItGrasps
10330ff38c72075035a69ed754fa9ed40a7c846b
[ "BSD-3-Clause" ]
49
2019-03-28T21:17:51.000Z
2021-11-16T09:29:27.000Z
src/demo/grasp_poses_visualizer_demo.cpp
NateWright/MoveItGrasps
10330ff38c72075035a69ed754fa9ed40a7c846b
[ "BSD-3-Clause" ]
39
2019-04-02T02:51:27.000Z
2022-03-25T09:23:30.000Z
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2015, University of Colorado, Boulder * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Univ of CO, Boulder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Andy McEvoy Desc: Creates a vizualization of all the poses used in the grasping pipeline */ #include <rviz_visual_tools/rviz_visual_tools.h> #include <moveit_grasps/two_finger_grasp_generator.h> #include <moveit_grasps/two_finger_grasp_data.h> #include <string> #include <vector> namespace moveit_grasps { // Size and location for randomly generated cuboids static const double CUBOID_MIN_SIZE = 0.01; static const double CUBOID_MAX_SIZE = 0.02; static const double CUBOID_WORKSPACE_MIN_X = 0.3; static const double CUBOID_WORKSPACE_MAX_X = 0.5; static const double CUBOID_WORKSPACE_MIN_Y = -0.125; static const double CUBOID_WORKSPACE_MAX_Y = 0.125; static const double CUBOID_WORKSPACE_MIN_Z = 0.3; static const double CUBOID_WORKSPACE_MAX_Z = 0.6; class GraspPosesVisualizer { public: // Constructor explicit GraspPosesVisualizer(bool verbose, const std::string name) : nh_("~"), name_(name) { // get arm parameters nh_.param("ee_group_name", ee_group_name_, std::string("hand")); nh_.param("planning_group_name", planning_group_name_, std::string("panda_arm")); ROS_INFO_STREAM_NAMED("init", "End Effector: " << ee_group_name_); ROS_INFO_STREAM_NAMED("init", "Planning Group: " << planning_group_name_); // set up rviz visual_tools_ = std::make_shared<moveit_visual_tools::MoveItVisualTools>("world", "/rviz_visual_tools"); visual_tools_->loadMarkerPub(); visual_tools_->loadRobotStatePub("/display_robot_state"); visual_tools_->loadTrajectoryPub("/display_planned_path"); visual_tools_->loadSharedRobotState(); visual_tools_->getSharedRobotState()->setToDefaultValues(); visual_tools_->enableBatchPublishing(); visual_tools_->deleteAllMarkers(); visual_tools_->removeAllCollisionObjects(); visual_tools_->hideRobot(); visual_tools_->trigger(); const moveit::core::JointModelGroup* ee_jmg = visual_tools_->getRobotModel()->getJointModelGroup(ee_group_name_); // Load grasp data grasp_data_ = std::make_shared<TwoFingerGraspData>(nh_, ee_group_name_, visual_tools_->getRobotModel()); ROS_ASSERT_MSG(grasp_data_->loadGraspData(nh_, ee_group_name_), "Failed to load Grasp Data parameters."); // load grasp generator grasp_generator_ = std::make_shared<moveit_grasps::TwoFingerGraspGenerator>(visual_tools_, verbose); // initialize cuboid size depth_ = CUBOID_MIN_SIZE; width_ = CUBOID_MIN_SIZE; height_ = CUBOID_MIN_SIZE; // Seed random srand(ros::Time::now().toSec()); ROS_INFO_STREAM_NAMED(name_, "\n************* \nStarting Vizualization" << "\n*************"); ROS_INFO_STREAM_NAMED(name_, "generating random cuboid"); generateRandomCuboid(cuboid_pose_, depth_, width_, height_); Eigen::Isometry3d display_pose; bool text = false; rviz_visual_tools::scales text_size = rviz_visual_tools::MEDIUM; // SHOW OBJECT POSE ROS_INFO_STREAM_NAMED(name_, "Publishing random cube"); visual_tools_->publishCuboid(cuboid_pose_, depth_, width_, height_, rviz_visual_tools::TRANSLUCENT_DARK); visual_tools_->publishAxis(cuboid_pose_, 0.05, 0.005); geometry_msgs::Pose cuboid_text_pose(cuboid_pose_); cuboid_text_pose.position.z += 0.05; visual_tools_->publishText(cuboid_text_pose, "Object Pose", rviz_visual_tools::WHITE, text_size, text); visual_tools_->trigger(); ROS_INFO_STREAM_NAMED(name_, "Generating grasps"); grasp_candidates_.clear(); moveit_grasps::TwoFingerGraspCandidateConfig grasp_generator_config = moveit_grasps::TwoFingerGraspCandidateConfig(); grasp_generator_config.disableAll(); grasp_generator_config.enable_face_grasps_ = true; grasp_generator_config.generate_y_axis_grasps_ = true; grasp_generator_->setGraspCandidateConfig(grasp_generator_config); grasp_generator_->generateGrasps(visual_tools_->convertPose(cuboid_pose_), depth_, width_, height_, grasp_data_, grasp_candidates_); // SHOW GRASP POSE visual_tools_->prompt("Press 'next' to show an example eef and grasp pose"); ROS_INFO_STREAM_NAMED(name_, "Showing the grasp pose"); Eigen::Isometry3d eef_mount_grasp_pose = visual_tools_->convertPose(grasp_candidates_.front()->grasp_.grasp_pose.pose); visual_tools_->publishAxis(eef_mount_grasp_pose, 0.05, 0.005); Eigen::Isometry3d grasp_text_pose(eef_mount_grasp_pose); grasp_text_pose.translation().z() += 0.03; visual_tools_->publishText(grasp_text_pose, "Grasp Pose", rviz_visual_tools::WHITE, text_size, text); visual_tools_->publishSphere(eef_mount_grasp_pose.translation(), rviz_visual_tools::LIME_GREEN, 0.01); visual_tools_->trigger(); // SHOW EE GRASP POSE ROS_INFO_STREAM_NAMED(name_, "Showing tcp grasp pose"); Eigen::Isometry3d tcp_grasp_pose = eef_mount_grasp_pose * grasp_data_->tcp_to_eef_mount_.inverse(); visual_tools_->publishAxis(tcp_grasp_pose, 0.05, 0.005); Eigen::Isometry3d tcp_text_pose(tcp_grasp_pose); tcp_text_pose.translation().z() += 0.03; visual_tools_->publishText(tcp_text_pose, "TCP Pose", rviz_visual_tools::WHITE, text_size, text); visual_tools_->publishSphere(tcp_grasp_pose.translation(), rviz_visual_tools::GREEN, 0.01); visual_tools_->trigger(); visual_tools_->prompt("Press 'next' to visualize the grasp max and min depth"); // SHOW grasp_max_depth ROS_INFO_STREAM_NAMED(name_, "Showing grasp_max_depth"); Eigen::Vector3d palm_vector = -tcp_grasp_pose.translation() + eef_mount_grasp_pose.translation(); palm_vector.normalize(); Eigen::Vector3d max_grasp_depth_point = tcp_grasp_pose.translation() + palm_vector * (grasp_data_->grasp_max_depth_ - grasp_data_->grasp_min_depth_); Eigen::Vector3d min_grasp_depth_point = tcp_grasp_pose.translation(); visual_tools_->publishLine(min_grasp_depth_point, max_grasp_depth_point, rviz_visual_tools::GREY); Eigen::Isometry3d min_depth_eef_pose = eef_mount_grasp_pose; visual_tools_->publishEEMarkers(min_depth_eef_pose, ee_jmg, grasp_data_->pre_grasp_posture_.points[0].positions, rviz_visual_tools::TRANSLUCENT_DARK, "test_eef"); visual_tools_->trigger(); visual_tools_->prompt("Press 'next' to visualize the pre-grasp, grasp, lift, and retreat poses"); EigenSTL::vector_Isometry3d grasp_waypoints; GraspGenerator::getGraspWaypoints(grasp_candidates_.front(), grasp_waypoints); visual_tools_->publishAxisLabeled(grasp_waypoints[0], "pregrasp", rviz_visual_tools::SMALL); visual_tools_->publishAxisLabeled(grasp_waypoints[1], "grasp", rviz_visual_tools::SMALL); visual_tools_->publishAxisLabeled(grasp_waypoints[2], "lifted", rviz_visual_tools::SMALL); visual_tools_->publishAxisLabeled(grasp_waypoints[3], "retreat", rviz_visual_tools::SMALL); visual_tools_->trigger(); ros::Duration(0.5).sleep(); } void generateRandomCuboid(geometry_msgs::Pose& cuboid_pose, double& l, double& w, double& h) { // Size l = rviz_visual_tools::RvizVisualTools::dRand(CUBOID_MIN_SIZE, CUBOID_MAX_SIZE); w = rviz_visual_tools::RvizVisualTools::dRand(CUBOID_MIN_SIZE, CUBOID_MAX_SIZE); h = rviz_visual_tools::RvizVisualTools::dRand(CUBOID_MIN_SIZE, CUBOID_MAX_SIZE); ROS_INFO_STREAM_NAMED("random_cuboid", "Size = " << l << ", " << w << ", " << h); // Position rviz_visual_tools::RandomPoseBounds pose_bounds(CUBOID_WORKSPACE_MIN_X, CUBOID_WORKSPACE_MAX_X, CUBOID_WORKSPACE_MIN_Y, CUBOID_WORKSPACE_MAX_Y, CUBOID_WORKSPACE_MIN_Z, CUBOID_WORKSPACE_MAX_Z); // Orientation visual_tools_->generateRandomPose(cuboid_pose, pose_bounds); ROS_INFO_STREAM_NAMED("random_cuboid", "Position = " << cuboid_pose.position.x << ", " << cuboid_pose.position.y << ", " << cuboid_pose.position.z); ROS_INFO_STREAM_NAMED("random_cuboid", "Quaternion = " << cuboid_pose.orientation.x << ", " << cuboid_pose.orientation.y << ", " << cuboid_pose.orientation.z); } private: ros::NodeHandle nh_; std::string name_; // cuboid dimensions double depth_; double width_; double height_; geometry_msgs::Pose cuboid_pose_; moveit_grasps::TwoFingerGraspGeneratorPtr grasp_generator_; moveit_visual_tools::MoveItVisualToolsPtr visual_tools_; std::vector<GraspCandidatePtr> grasp_candidates_; moveit_grasps::TwoFingerGraspDataPtr grasp_data_; // TODO(mcevoyandy): read in from param // arm description std::string ee_group_name_; std::string planning_group_name_; }; // class } // namespace moveit_grasps int main(int argc, char** argv) { const std::string name = "grasp_poses_visualizer_demo"; ros::init(argc, argv, name); ROS_INFO_STREAM_NAMED(name, "Grasp Poses Visualizer"); bool verbose = false; moveit_grasps::GraspPosesVisualizer visualizer(verbose, name); return 0; }
45.891213
117
0.719001
[ "object", "vector" ]
80600272e6355968643289dd18de0940abbb6850
91,076
cpp
C++
src/mongo/s/query/async_results_merger_test.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/s/query/async_results_merger_test.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/s/query/async_results_merger_test.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2018-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * 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 * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the Server Side Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mongo/platform/basic.h" #include "mongo/s/query/async_results_merger.h" #include <memory> #include "mongo/db/json.h" #include "mongo/db/pipeline/change_stream_constants.h" #include "mongo/db/pipeline/resume_token.h" #include "mongo/db/query/cursor_response.h" #include "mongo/db/query/getmore_command_gen.h" #include "mongo/executor/task_executor.h" #include "mongo/s/catalog/type_shard.h" #include "mongo/s/client/shard_registry.h" #include "mongo/s/query/results_merger_test_fixture.h" #include "mongo/unittest/death_test.h" #include "mongo/unittest/unittest.h" namespace mongo { namespace { LogicalSessionId parseSessionIdFromCmd(BSONObj cmdObj) { return LogicalSessionId::parse(IDLParserErrorContext("lsid"), cmdObj["lsid"].Obj()); } BSONObj makePostBatchResumeToken(Timestamp clusterTime) { auto pbrt = ResumeToken::makeHighWaterMarkToken(clusterTime, ResumeTokenData::kDefaultTokenVersion) .toDocument() .toBson(); invariant(pbrt.firstElement().type() == BSONType::String); return pbrt; } BSONObj makeResumeToken(Timestamp clusterTime, UUID uuid, BSONObj docKey) { ResumeTokenData data; data.clusterTime = clusterTime; data.uuid = uuid; data.eventIdentifier = Value(Document{docKey}); return ResumeToken(data).toDocument().toBson(); } using AsyncResultsMergerTest = ResultsMergerTestFixture; TEST_F(AsyncResultsMergerTest, SingleShardUnsorted) { std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 5, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); // Before any requests are scheduled, ARM is not ready to return results. ASSERT_FALSE(arm->ready()); ASSERT_FALSE(arm->remotesExhausted()); // Schedule requests. auto readyEvent = unittest::assertGet(arm->nextEvent()); // Before any responses are delivered, ARM is not ready to return results. ASSERT_FALSE(arm->ready()); ASSERT_FALSE(arm->remotesExhausted()); // Shard responds; the handleBatchResponse callbacks are run and ARM's remotes get updated. std::vector<CursorResponse> responses; std::vector<BSONObj> batch = {fromjson("{_id: 1}"), fromjson("{_id: 2}"), fromjson("{_id: 3}")}; responses.emplace_back(kTestNss, CursorId(0), batch); scheduleNetworkResponses(std::move(responses)); // Now that the responses have been delivered, ARM is ready to return results. ASSERT_TRUE(arm->ready()); // Because the response contained a cursorId of 0, ARM marked the remote as exhausted. ASSERT_TRUE(arm->remotesExhausted()); // ARM returns the correct results. executor()->waitForEvent(readyEvent); ASSERT_BSONOBJ_EQ(fromjson("{_id: 1}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 2}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 3}"), *unittest::assertGet(arm->nextReady()).getResult()); // After returning all the buffered results, ARM returns EOF immediately because the cursor was // exhausted. ASSERT_TRUE(arm->ready()); ASSERT_TRUE(unittest::assertGet(arm->nextReady()).isEOF()); } TEST_F(AsyncResultsMergerTest, SingleShardSorted) { BSONObj findCmd = fromjson("{find: 'testcoll', sort: {_id: 1}}"); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 5, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors), findCmd); // Before any requests are scheduled, ARM is not ready to return results. ASSERT_FALSE(arm->ready()); ASSERT_FALSE(arm->remotesExhausted()); // Schedule requests. auto readyEvent = unittest::assertGet(arm->nextEvent()); // Before any responses are delivered, ARM is not ready to return results. ASSERT_FALSE(arm->ready()); ASSERT_FALSE(arm->remotesExhausted()); // Shard responds; the handleBatchResponse callbacks are run and ARM's remotes get updated. std::vector<CursorResponse> responses; std::vector<BSONObj> batch = {fromjson("{$sortKey: [5]}"), fromjson("{$sortKey: [6]}")}; responses.emplace_back(kTestNss, CursorId(0), batch); scheduleNetworkResponses(std::move(responses)); // Now that the responses have been delivered, ARM is ready to return results. ASSERT_TRUE(arm->ready()); // Because the response contained a cursorId of 0, ARM marked the remote as exhausted. ASSERT_TRUE(arm->remotesExhausted()); // ARM returns all results in order. executor()->waitForEvent(readyEvent); ASSERT_BSONOBJ_EQ(fromjson("{$sortKey: [5]}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{$sortKey: [6]}"), *unittest::assertGet(arm->nextReady()).getResult()); // After returning all the buffered results, ARM returns EOF immediately because the cursor was // exhausted. ASSERT_TRUE(arm->ready()); ASSERT_TRUE(unittest::assertGet(arm->nextReady()).isEOF()); } TEST_F(AsyncResultsMergerTest, MultiShardUnsorted) { std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 5, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[1], kTestShardHosts[1], CursorResponse(kTestNss, 6, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); // Before any requests are scheduled, ARM is not ready to return results. ASSERT_FALSE(arm->ready()); ASSERT_FALSE(arm->remotesExhausted()); // Schedule requests. auto readyEvent = unittest::assertGet(arm->nextEvent()); // Before any responses are delivered, ARM is not ready to return results. ASSERT_FALSE(arm->ready()); ASSERT_FALSE(arm->remotesExhausted()); // First shard responds; the handleBatchResponse callback is run and ARM's remote gets updated. std::vector<CursorResponse> responses; std::vector<BSONObj> batch1 = { fromjson("{_id: 1}"), fromjson("{_id: 2}"), fromjson("{_id: 3}")}; responses.emplace_back(kTestNss, CursorId(0), batch1); scheduleNetworkResponses(std::move(responses)); // ARM is ready to return first result. ASSERT_TRUE(arm->ready()); // ARM is not exhausted, because second shard has yet to respond. ASSERT_FALSE(arm->remotesExhausted()); // ARM returns results from first shard immediately. executor()->waitForEvent(readyEvent); ASSERT_BSONOBJ_EQ(fromjson("{_id: 1}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 2}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 3}"), *unittest::assertGet(arm->nextReady()).getResult()); // There are no further buffered results, so ARM is not ready. ASSERT_FALSE(arm->ready()); // Make next event to be signaled. readyEvent = unittest::assertGet(arm->nextEvent()); // Second shard responds; the handleBatchResponse callback is run and ARM's remote gets updated. responses.clear(); std::vector<BSONObj> batch2 = { fromjson("{_id: 4}"), fromjson("{_id: 5}"), fromjson("{_id: 6}")}; responses.emplace_back(kTestNss, CursorId(0), batch2); scheduleNetworkResponses(std::move(responses)); // ARM is ready to return remaining results. ASSERT_TRUE(arm->ready()); ASSERT_TRUE(arm->remotesExhausted()); // ARM returns results from second shard immediately. executor()->waitForEvent(readyEvent); ASSERT_BSONOBJ_EQ(fromjson("{_id: 4}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 5}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 6}"), *unittest::assertGet(arm->nextReady()).getResult()); // After returning all the buffered results, the ARM returns EOF immediately because both shards // cursors were exhausted. ASSERT_TRUE(arm->ready()); ASSERT_TRUE(unittest::assertGet(arm->nextReady()).isEOF()); } TEST_F(AsyncResultsMergerTest, MultiShardSorted) { BSONObj findCmd = fromjson("{find: 'testcoll', sort: {_id: 1}}"); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 5, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[1], kTestShardHosts[1], CursorResponse(kTestNss, 6, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors), findCmd); // Before any requests are scheduled, ARM is not ready to return results. ASSERT_FALSE(arm->ready()); ASSERT_FALSE(arm->remotesExhausted()); // Schedule requests. auto readyEvent = unittest::assertGet(arm->nextEvent()); // Before any responses are delivered, ARM is not ready to return results. ASSERT_FALSE(arm->ready()); ASSERT_FALSE(arm->remotesExhausted()); // First shard responds; the handleBatchResponse callback is run and ARM's remote gets updated. std::vector<CursorResponse> responses; std::vector<BSONObj> batch1 = {fromjson("{$sortKey: [5]}"), fromjson("{$sortKey: [6]}")}; responses.emplace_back(kTestNss, CursorId(0), batch1); scheduleNetworkResponses(std::move(responses)); // ARM is not ready to return results until receiving responses from all remotes. ASSERT_FALSE(arm->ready()); // ARM is not exhausted, because second shard has yet to respond. ASSERT_FALSE(arm->remotesExhausted()); // Second shard responds; the handleBatchResponse callback is run and ARM's remote gets updated. responses.clear(); std::vector<BSONObj> batch2 = {fromjson("{$sortKey: [3]}"), fromjson("{$sortKey: [9]}")}; responses.emplace_back(kTestNss, CursorId(0), batch2); scheduleNetworkResponses(std::move(responses)); // Now that all remotes have responded, ARM is ready to return results. ASSERT_TRUE(arm->ready()); ASSERT_TRUE(arm->remotesExhausted()); // ARM returns all results in sorted order. executor()->waitForEvent(readyEvent); ASSERT_BSONOBJ_EQ(fromjson("{$sortKey: [3]}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{$sortKey: [5]}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{$sortKey: [6]}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{$sortKey: [9]}"), *unittest::assertGet(arm->nextReady()).getResult()); // After returning all the buffered results, the ARM returns EOF immediately because both shards // cursors were exhausted. ASSERT_TRUE(arm->ready()); ASSERT_TRUE(unittest::assertGet(arm->nextReady()).isEOF()); } TEST_F(AsyncResultsMergerTest, MultiShardMultipleGets) { std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 5, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[1], kTestShardHosts[1], CursorResponse(kTestNss, 6, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); // Before any requests are scheduled, ARM is not ready to return results. ASSERT_FALSE(arm->ready()); ASSERT_FALSE(arm->remotesExhausted()); // Schedule requests. auto readyEvent = unittest::assertGet(arm->nextEvent()); // First shard responds; the handleBatchResponse callback is run and ARM's remote gets updated. std::vector<CursorResponse> responses; std::vector<BSONObj> batch1 = { fromjson("{_id: 1}"), fromjson("{_id: 2}"), fromjson("{_id: 3}")}; responses.emplace_back(kTestNss, CursorId(5), batch1); scheduleNetworkResponses(std::move(responses)); // ARM is ready to return first result. ASSERT_TRUE(arm->ready()); // ARM is not exhausted, because second shard has yet to respond and first shard's response did // not contain cursorId=0. ASSERT_FALSE(arm->remotesExhausted()); // ARM returns results from first shard immediately. executor()->waitForEvent(readyEvent); ASSERT_BSONOBJ_EQ(fromjson("{_id: 1}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 2}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 3}"), *unittest::assertGet(arm->nextReady()).getResult()); // There are no further buffered results, so ARM is not ready. ASSERT_FALSE(arm->ready()); // Make next event to be signaled. readyEvent = unittest::assertGet(arm->nextEvent()); // Second shard responds; the handleBatchResponse callback is run and ARM's remote gets updated. responses.clear(); std::vector<BSONObj> batch2 = { fromjson("{_id: 4}"), fromjson("{_id: 5}"), fromjson("{_id: 6}")}; responses.emplace_back(kTestNss, CursorId(0), batch2); scheduleNetworkResponses(std::move(responses)); // ARM is ready to return second shard's results. ASSERT_TRUE(arm->ready()); // ARM is not exhausted, because first shard's response did not contain cursorId=0. ASSERT_FALSE(arm->remotesExhausted()); // ARM returns results from second shard immediately. executor()->waitForEvent(readyEvent); ASSERT_BSONOBJ_EQ(fromjson("{_id: 4}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 5}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 6}"), *unittest::assertGet(arm->nextReady()).getResult()); // ARM is not ready to return results until further results are obtained from first shard. ASSERT_FALSE(arm->ready()); // Make next event to be signaled. readyEvent = unittest::assertGet(arm->nextEvent()); // First shard returns remainder of results. responses.clear(); std::vector<BSONObj> batch3 = { fromjson("{_id: 7}"), fromjson("{_id: 8}"), fromjson("{_id: 9}")}; responses.emplace_back(kTestNss, CursorId(0), batch3); scheduleNetworkResponses(std::move(responses)); // ARM is ready to return remaining results. ASSERT_TRUE(arm->ready()); ASSERT_TRUE(arm->remotesExhausted()); // ARM returns remaining results immediately. executor()->waitForEvent(readyEvent); ASSERT_BSONOBJ_EQ(fromjson("{_id: 7}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 8}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 9}"), *unittest::assertGet(arm->nextReady()).getResult()); // After returning all the buffered results, the ARM returns EOF immediately because both shards // cursors were exhausted. ASSERT_TRUE(arm->ready()); ASSERT_TRUE(unittest::assertGet(arm->nextReady()).isEOF()); } TEST_F(AsyncResultsMergerTest, CompoundSortKey) { BSONObj findCmd = fromjson("{find: 'testcoll', sort: {a: -1, b: 1}}"); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 5, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[1], kTestShardHosts[1], CursorResponse(kTestNss, 6, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[2], kTestShardHosts[2], CursorResponse(kTestNss, 7, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors), findCmd); // Schedule requests. ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // Deliver responses. std::vector<CursorResponse> responses; std::vector<BSONObj> batch1 = {fromjson("{$sortKey: [5, 9]}"), fromjson("{$sortKey: [4, 20]}")}; responses.emplace_back(kTestNss, CursorId(0), batch1); std::vector<BSONObj> batch2 = {fromjson("{$sortKey: [10, 11]}"), fromjson("{$sortKey: [4, 4]}")}; responses.emplace_back(kTestNss, CursorId(0), batch2); std::vector<BSONObj> batch3 = {fromjson("{$sortKey: [10, 12]}"), fromjson("{$sortKey: [5, 9]}")}; responses.emplace_back(kTestNss, CursorId(0), batch3); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); // ARM returns all results in sorted order. ASSERT_TRUE(arm->ready()); ASSERT_TRUE(arm->remotesExhausted()); ASSERT_BSONOBJ_EQ(fromjson("{$sortKey: [10, 11]}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{$sortKey: [10, 12]}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{$sortKey: [5, 9]}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{$sortKey: [5, 9]}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{$sortKey: [4, 4]}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{$sortKey: [4, 20]}"), *unittest::assertGet(arm->nextReady()).getResult()); // After returning all the buffered results, the ARM returns EOF immediately because both shards // cursors were exhausted. ASSERT_TRUE(arm->ready()); ASSERT_TRUE(unittest::assertGet(arm->nextReady()).isEOF()); } TEST_F(AsyncResultsMergerTest, SortedButNoSortKey) { BSONObj findCmd = fromjson("{find: 'testcoll', sort: {a: -1, b: 1}}"); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors), findCmd); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // Parsing the batch results in an error because the sort key is missing. std::vector<CursorResponse> responses; std::vector<BSONObj> batch1 = {fromjson("{a: 2, b: 1}"), fromjson("{a: 1, b: 2}")}; responses.emplace_back(kTestNss, CursorId(1), batch1); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); auto statusWithNext = arm->nextReady(); ASSERT(!statusWithNext.isOK()); ASSERT_EQ(statusWithNext.getStatus().code(), ErrorCodes::InternalError); // Required to kill the 'arm' on error before destruction. auto killFuture = arm->kill(operationContext()); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, HasFirstBatch) { std::vector<BSONObj> firstBatch = { fromjson("{_id: 1}"), fromjson("{_id: 2}"), fromjson("{_id: 3}")}; std::vector<RemoteCursor> cursors; cursors.push_back(makeRemoteCursor( kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 5, std::move(firstBatch)))); auto arm = makeARMFromExistingCursors(std::move(cursors)); // Because there was firstBatch, ARM is immediately ready to return results. ASSERT_TRUE(arm->ready()); // Because the cursorId was not zero, ARM is not exhausted. ASSERT_FALSE(arm->remotesExhausted()); // ARM returns the correct results. ASSERT_BSONOBJ_EQ(fromjson("{_id: 1}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 2}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 3}"), *unittest::assertGet(arm->nextReady()).getResult()); // Now that the firstBatch results have been returned, ARM must wait for further results. ASSERT_FALSE(arm->ready()); // Schedule requests. auto readyEvent = unittest::assertGet(arm->nextEvent()); // Before any responses are delivered, ARM is not ready to return results. ASSERT_FALSE(arm->ready()); ASSERT_FALSE(arm->remotesExhausted()); // Shard responds; the handleBatchResponse callbacks are run and ARM's remotes get updated. std::vector<CursorResponse> responses; std::vector<BSONObj> batch = {fromjson("{_id: 4}"), fromjson("{_id: 5}"), fromjson("{_id: 6}")}; responses.emplace_back(kTestNss, CursorId(0), batch); scheduleNetworkResponses(std::move(responses)); // Now that the responses have been delivered, ARM is ready to return results. ASSERT_TRUE(arm->ready()); // Because the response contained a cursorId of 0, ARM marked the remote as exhausted. ASSERT_TRUE(arm->remotesExhausted()); // ARM returns the correct results. executor()->waitForEvent(readyEvent); ASSERT_BSONOBJ_EQ(fromjson("{_id: 4}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 5}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 6}"), *unittest::assertGet(arm->nextReady()).getResult()); // After returning all the buffered results, ARM returns EOF immediately because the cursor was // exhausted. ASSERT_TRUE(arm->ready()); ASSERT_TRUE(unittest::assertGet(arm->nextReady()).isEOF()); } TEST_F(AsyncResultsMergerTest, OneShardHasInitialBatchOtherShardExhausted) { std::vector<BSONObj> firstBatch = { fromjson("{_id: 1}"), fromjson("{_id: 2}"), fromjson("{_id: 3}")}; std::vector<RemoteCursor> cursors; cursors.push_back(makeRemoteCursor( kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 5, std::move(firstBatch)))); cursors.push_back( makeRemoteCursor(kTestShardIds[1], kTestShardHosts[1], CursorResponse(kTestNss, 0, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); // Because there was firstBatch, ARM is immediately ready to return results. ASSERT_TRUE(arm->ready()); // Because one of the remotes' cursorId was not zero, ARM is not exhausted. ASSERT_FALSE(arm->remotesExhausted()); // ARM returns the correct results. ASSERT_BSONOBJ_EQ(fromjson("{_id: 1}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 2}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 3}"), *unittest::assertGet(arm->nextReady()).getResult()); // Now that the firstBatch results have been returned, ARM must wait for further results. ASSERT_FALSE(arm->ready()); // Schedule requests. auto readyEvent = unittest::assertGet(arm->nextEvent()); // Before any responses are delivered, ARM is not ready to return results. ASSERT_FALSE(arm->ready()); ASSERT_FALSE(arm->remotesExhausted()); // Shard responds; the handleBatchResponse callbacks are run and ARM's remotes get updated. std::vector<CursorResponse> responses; std::vector<BSONObj> batch = {fromjson("{_id: 4}"), fromjson("{_id: 5}"), fromjson("{_id: 6}")}; responses.emplace_back(kTestNss, CursorId(0), batch); scheduleNetworkResponses(std::move(responses)); // Now that the responses have been delivered, ARM is ready to return results. ASSERT_TRUE(arm->ready()); // Because the response contained a cursorId of 0, ARM marked the remote as exhausted. ASSERT_TRUE(arm->remotesExhausted()); // ARM returns the correct results. executor()->waitForEvent(readyEvent); ASSERT_BSONOBJ_EQ(fromjson("{_id: 4}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 5}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 6}"), *unittest::assertGet(arm->nextReady()).getResult()); // After returning all the buffered results, ARM returns EOF immediately because the cursor was // exhausted. ASSERT_TRUE(arm->ready()); ASSERT_TRUE(unittest::assertGet(arm->nextReady()).isEOF()); } TEST_F(AsyncResultsMergerTest, StreamResultsFromOneShardIfOtherDoesntRespond) { std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[1], kTestShardHosts[1], CursorResponse(kTestNss, 2, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // Both shards respond with the first batch. std::vector<CursorResponse> responses; std::vector<BSONObj> batch1 = {fromjson("{_id: 1}"), fromjson("{_id: 2}")}; responses.emplace_back(kTestNss, CursorId(1), batch1); std::vector<BSONObj> batch2 = {fromjson("{_id: 3}"), fromjson("{_id: 4}")}; responses.emplace_back(kTestNss, CursorId(2), batch2); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 1}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 2}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 3}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 4}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_FALSE(arm->ready()); readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // When we ask the shards for their next batch, the first shard responds and the second shard // never responds. responses.clear(); std::vector<BSONObj> batch3 = {fromjson("{_id: 5}"), fromjson("{_id: 6}")}; responses.emplace_back(kTestNss, CursorId(1), batch3); scheduleNetworkResponses(std::move(responses)); blackHoleNextRequest(); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 5}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 6}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_FALSE(arm->ready()); readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // We can continue to return results from first shard, while second shard remains unresponsive. responses.clear(); std::vector<BSONObj> batch4 = {fromjson("{_id: 7}"), fromjson("{_id: 8}")}; responses.emplace_back(kTestNss, CursorId(0), batch4); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 7}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 8}"), *unittest::assertGet(arm->nextReady()).getResult()); auto killFuture = arm->kill(operationContext()); executor()->shutdown(); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, ErrorOnMismatchedCursorIds) { std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 123, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); std::vector<CursorResponse> responses; std::vector<BSONObj> batch = {fromjson("{_id: 4}"), fromjson("{_id: 5}"), fromjson("{_id: 6}")}; responses.emplace_back(kTestNss, CursorId(456), batch); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); ASSERT(!arm->nextReady().isOK()); // Required to kill the 'arm' on error before destruction. auto killFuture = arm->kill(operationContext()); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, BadResponseReceivedFromShard) { std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 123, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[1], kTestShardHosts[1], CursorResponse(kTestNss, 456, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[2], kTestShardHosts[2], CursorResponse(kTestNss, 789, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); std::vector<BSONObj> batch1 = {fromjson("{_id: 1}"), fromjson("{_id: 2}")}; BSONObj response1 = CursorResponse(kTestNss, CursorId(123), batch1) .toBSON(CursorResponse::ResponseType::SubsequentResponse); BSONObj response2 = fromjson("{foo: 'bar'}"); std::vector<BSONObj> batch3 = {fromjson("{_id: 4}"), fromjson("{_id: 5}")}; BSONObj response3 = CursorResponse(kTestNss, CursorId(789), batch3) .toBSON(CursorResponse::ResponseType::SubsequentResponse); scheduleNetworkResponseObjs({response1, response2, response3}); runReadyCallbacks(); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); auto statusWithNext = arm->nextReady(); ASSERT(!statusWithNext.isOK()); // Required to kill the 'arm' on error before destruction. auto killFuture = arm->kill(operationContext()); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, ErrorReceivedFromShard) { std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[1], kTestShardHosts[1], CursorResponse(kTestNss, 2, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[2], kTestShardHosts[2], CursorResponse(kTestNss, 3, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); std::vector<CursorResponse> responses; std::vector<BSONObj> batch1 = {fromjson("{_id: 1}"), fromjson("{_id: 2}")}; responses.emplace_back(kTestNss, CursorId(1), batch1); std::vector<BSONObj> batch2 = {fromjson("{_id: 3}"), fromjson("{_id: 4}")}; responses.emplace_back(kTestNss, CursorId(2), batch2); scheduleNetworkResponses(std::move(responses)); scheduleErrorResponse({ErrorCodes::BadValue, "bad thing happened"}); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); auto statusWithNext = arm->nextReady(); ASSERT(!statusWithNext.isOK()); ASSERT_EQ(statusWithNext.getStatus().code(), ErrorCodes::BadValue); ASSERT_EQ(statusWithNext.getStatus().reason(), "bad thing happened"); // Required to kill the 'arm' on error before destruction. auto killFuture = arm->kill(operationContext()); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, ErrorCantScheduleEventBeforeLastSignaled) { std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); // Error to call nextEvent()() before the previous event is signaled. ASSERT_NOT_OK(arm->nextEvent().getStatus()); std::vector<CursorResponse> responses; std::vector<BSONObj> batch = {fromjson("{_id: 1}"), fromjson("{_id: 2}")}; responses.emplace_back(kTestNss, CursorId(0), batch); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 1}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 2}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_TRUE(unittest::assertGet(arm->nextReady()).isEOF()); // Required to kill the 'arm' on error before destruction. auto killFuture = arm->kill(operationContext()); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, NextEventAfterTaskExecutorShutdown) { std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); executor()->shutdown(); ASSERT_EQ(ErrorCodes::ShutdownInProgress, arm->nextEvent().getStatus()); auto killFuture = arm->kill(operationContext()); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, KillAfterTaskExecutorShutdownWithOutstandingBatches) { std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); // Make a request to the shard that will never get answered. ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); blackHoleNextRequest(); // Executor shuts down before a response is received. executor()->shutdown(); auto killFuture = arm->kill(operationContext()); killFuture.wait(); // Ensure that the executor finishes all of the outstanding callbacks before the ARM is freed. executor()->join(); } TEST_F(AsyncResultsMergerTest, KillNoBatchesRequested) { std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); ASSERT_FALSE(arm->ready()); auto killFuture = arm->kill(operationContext()); assertKillCusorsCmdHasCursorId(getNthPendingRequest(0u).cmdObj, 1); // Killed cursors are considered ready, but return an error when you try to receive the next // doc. ASSERT_TRUE(arm->ready()); ASSERT_NOT_OK(arm->nextReady().getStatus()); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, KillAllRemotesExhausted) { std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[1], kTestShardHosts[1], CursorResponse(kTestNss, 2, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[2], kTestShardHosts[2], CursorResponse(kTestNss, 3, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); std::vector<CursorResponse> responses; std::vector<BSONObj> batch1 = {fromjson("{_id: 1}"), fromjson("{_id: 2}")}; responses.emplace_back(kTestNss, CursorId(0), batch1); std::vector<BSONObj> batch2 = {fromjson("{_id: 3}"), fromjson("{_id: 4}")}; responses.emplace_back(kTestNss, CursorId(0), batch2); std::vector<BSONObj> batch3 = {fromjson("{_id: 3}"), fromjson("{_id: 4}")}; responses.emplace_back(kTestNss, CursorId(0), batch3); scheduleNetworkResponses(std::move(responses)); auto killFuture = arm->kill(operationContext()); // ARM shouldn't schedule killCursors on anything since all of the remotes are exhausted. ASSERT_FALSE(networkHasReadyRequests()); ASSERT_TRUE(arm->ready()); ASSERT_NOT_OK(arm->nextReady().getStatus()); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, KillNonExhaustedCursorWithoutPendingRequest) { std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[1], kTestShardHosts[1], CursorResponse(kTestNss, 2, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[2], kTestShardHosts[2], CursorResponse(kTestNss, 123, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); std::vector<CursorResponse> responses; std::vector<BSONObj> batch1 = {fromjson("{_id: 1}"), fromjson("{_id: 2}")}; responses.emplace_back(kTestNss, CursorId(0), batch1); std::vector<BSONObj> batch2 = {fromjson("{_id: 3}"), fromjson("{_id: 4}")}; responses.emplace_back(kTestNss, CursorId(0), batch2); // Cursor 3 is not exhausted. std::vector<BSONObj> batch3 = {fromjson("{_id: 3}"), fromjson("{_id: 4}")}; responses.emplace_back(kTestNss, CursorId(123), batch3); scheduleNetworkResponses(std::move(responses)); auto killFuture = arm->kill(operationContext()); // ARM should schedule killCursors on cursor 123 assertKillCusorsCmdHasCursorId(getNthPendingRequest(0u).cmdObj, 123); ASSERT_TRUE(arm->ready()); ASSERT_NOT_OK(arm->nextReady().getStatus()); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, KillTwoOutstandingBatches) { std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[1], kTestShardHosts[1], CursorResponse(kTestNss, 2, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[2], kTestShardHosts[2], CursorResponse(kTestNss, 3, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); std::vector<CursorResponse> responses; std::vector<BSONObj> batch1 = {fromjson("{_id: 1}"), fromjson("{_id: 2}")}; responses.emplace_back(kTestNss, CursorId(0), batch1); scheduleNetworkResponses(std::move(responses)); // Kill event will only be signalled once the callbacks for the pending batches have run. auto killFuture = arm->kill(operationContext()); // Check that the ARM kills both batches. assertKillCusorsCmdHasCursorId(getNthPendingRequest(0u).cmdObj, 2); assertKillCusorsCmdHasCursorId(getNthPendingRequest(1u).cmdObj, 3); // Run the callbacks which were canceled. runReadyCallbacks(); // Ensure that we properly signal those waiting for more results to be ready. executor()->waitForEvent(readyEvent); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, NextEventErrorsAfterKill) { std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); std::vector<CursorResponse> responses; std::vector<BSONObj> batch1 = {fromjson("{_id: 1}"), fromjson("{_id: 2}")}; responses.emplace_back(kTestNss, CursorId(1), batch1); scheduleNetworkResponses(std::move(responses)); auto killFuture = arm->kill(operationContext()); // Attempting to schedule more network operations on a killed arm is an error. ASSERT_NOT_OK(arm->nextEvent().getStatus()); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, KillCalledTwice) { std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); auto killFuture1 = arm->kill(operationContext()); auto killFuture2 = arm->kill(operationContext()); killFuture1.wait(); killFuture2.wait(); } TEST_F(AsyncResultsMergerTest, KillCursorCmdHasNoTimeout) { std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); auto* opCtx = operationContext(); opCtx->setDeadlineAfterNowBy(Microseconds::zero(), ErrorCodes::MaxTimeMSExpired); auto killFuture = arm->kill(opCtx); ASSERT_EQ(executor::RemoteCommandRequestBase::kNoTimeout, getNthPendingRequest(0u).timeout); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, TailableBasic) { BSONObj findCmd = fromjson("{find: 'testcoll', tailable: true}"); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 123, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors), findCmd); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); std::vector<CursorResponse> responses; std::vector<BSONObj> batch1 = {fromjson("{_id: 1}"), fromjson("{_id: 2}")}; responses.emplace_back(kTestNss, CursorId(123), batch1); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 1}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 2}"), *unittest::assertGet(arm->nextReady()).getResult()); // In the tailable case, we expect EOF after every batch. ASSERT_TRUE(arm->ready()); ASSERT_TRUE(unittest::assertGet(arm->nextReady()).isEOF()); ASSERT_FALSE(arm->remotesExhausted()); ASSERT_FALSE(arm->ready()); readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); responses.clear(); std::vector<BSONObj> batch2 = {fromjson("{_id: 3}")}; responses.emplace_back(kTestNss, CursorId(123), batch2); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); ASSERT_FALSE(arm->remotesExhausted()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 3}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_TRUE(unittest::assertGet(arm->nextReady()).isEOF()); ASSERT_FALSE(arm->remotesExhausted()); auto killFuture = arm->kill(operationContext()); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, TailableEmptyBatch) { BSONObj findCmd = fromjson("{find: 'testcoll', tailable: true}"); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 123, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors), findCmd); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // Remote responds with an empty batch and a non-zero cursor id. std::vector<CursorResponse> responses; std::vector<BSONObj> batch; responses.emplace_back(kTestNss, CursorId(123), batch); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); // After receiving an empty batch, the ARM should return boost::none, but remotes should not be // marked as exhausted. ASSERT_TRUE(arm->ready()); ASSERT_TRUE(unittest::assertGet(arm->nextReady()).isEOF()); ASSERT_FALSE(arm->remotesExhausted()); auto killFuture = arm->kill(operationContext()); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, TailableExhaustedCursor) { BSONObj findCmd = fromjson("{find: 'testcoll', tailable: true}"); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 123, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors), findCmd); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // Remote responds with an empty batch and a zero cursor id. std::vector<CursorResponse> responses; std::vector<BSONObj> batch; responses.emplace_back(kTestNss, CursorId(0), batch); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); // Afterwards, the ARM should return boost::none and remote cursors should be marked as // exhausted. ASSERT_TRUE(arm->ready()); ASSERT_TRUE(unittest::assertGet(arm->nextReady()).isEOF()); ASSERT_TRUE(arm->remotesExhausted()); } TEST_F(AsyncResultsMergerTest, GetMoreBatchSizes) { BSONObj findCmd = fromjson("{find: 'testcoll', batchSize: 3}"); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors), findCmd); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); std::vector<CursorResponse> responses; std::vector<BSONObj> batch1 = {fromjson("{_id: 1}"), fromjson("{_id: 2}")}; responses.emplace_back(kTestNss, CursorId(1), batch1); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 1}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 2}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_FALSE(arm->ready()); responses.clear(); std::vector<BSONObj> batch2 = {fromjson("{_id: 3}")}; responses.emplace_back(kTestNss, CursorId(0), batch2); readyEvent = unittest::assertGet(arm->nextEvent()); BSONObj scheduledCmd = getNthPendingRequest(0).cmdObj; auto cmd = GetMoreCommandRequest::parse({"getMore"}, scheduledCmd.addField(BSON("$db" << "anydbname") .firstElement())); ASSERT_EQ(*cmd.getBatchSize(), 1LL); ASSERT_EQ(cmd.getCommandParameter(), 1LL); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 3}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_TRUE(unittest::assertGet(arm->nextReady()).isEOF()); } TEST_F(AsyncResultsMergerTest, AllowPartialResults) { BSONObj findCmd = fromjson("{find: 'testcoll', allowPartialResults: true}"); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 97, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[1], kTestShardHosts[1], CursorResponse(kTestNss, 98, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[2], kTestShardHosts[2], CursorResponse(kTestNss, 99, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors), findCmd); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // An error occurs with the first host. scheduleErrorResponse({ErrorCodes::AuthenticationFailed, "authentication failed"}); ASSERT_FALSE(arm->ready()); // Instead of propagating the error, we should be willing to return results from the two // remaining shards. std::vector<CursorResponse> responses; std::vector<BSONObj> batch1 = {fromjson("{_id: 1}")}; responses.emplace_back(kTestNss, CursorId(98), batch1); std::vector<BSONObj> batch2 = {fromjson("{_id: 2}")}; responses.emplace_back(kTestNss, CursorId(99), batch2); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 1}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 2}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_FALSE(arm->ready()); readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // Now the second host becomes unreachable. We should still be willing to return results from // the third shard. scheduleErrorResponse({ErrorCodes::AuthenticationFailed, "authentication failed"}); ASSERT_FALSE(arm->ready()); responses.clear(); std::vector<BSONObj> batch3 = {fromjson("{_id: 3}")}; responses.emplace_back(kTestNss, CursorId(99), batch3); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 3}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_FALSE(arm->ready()); readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // Once the last reachable shard indicates that its cursor is closed, we're done. responses.clear(); std::vector<BSONObj> batch4 = {}; responses.emplace_back(kTestNss, CursorId(0), batch4); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); ASSERT_TRUE(unittest::assertGet(arm->nextReady()).isEOF()); } TEST_F(AsyncResultsMergerTest, AllowPartialResultsSingleNode) { BSONObj findCmd = fromjson("{find: 'testcoll', allowPartialResults: true}"); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 98, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors), findCmd); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); std::vector<CursorResponse> responses; std::vector<BSONObj> batch = {fromjson("{_id: 1}"), fromjson("{_id: 2}")}; responses.emplace_back(kTestNss, CursorId(98), batch); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 1}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 2}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_FALSE(arm->ready()); readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // The lone host involved in this query returns an error. This should simply cause us to return // EOF. scheduleErrorResponse({ErrorCodes::AuthenticationFailed, "authentication failed"}); ASSERT_TRUE(arm->ready()); ASSERT_TRUE(unittest::assertGet(arm->nextReady()).isEOF()); } TEST_F(AsyncResultsMergerTest, AllowPartialResultsOnRetriableErrorNoRetries) { BSONObj findCmd = fromjson("{find: 'testcoll', allowPartialResults: true}"); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[2], kTestShardHosts[2], CursorResponse(kTestNss, 2, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors), findCmd); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // First host returns single result std::vector<CursorResponse> responses; std::vector<BSONObj> batch = {fromjson("{_id: 1}")}; responses.emplace_back(kTestNss, CursorId(0), batch); scheduleNetworkResponses(std::move(responses)); // From the second host we get a network (retriable) error. scheduleErrorResponse({ErrorCodes::HostUnreachable, "host unreachable"}); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 1}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->remotesExhausted()); ASSERT_TRUE(arm->ready()); } TEST_F(AsyncResultsMergerTest, ReturnsErrorOnRetriableError) { BSONObj findCmd = fromjson("{find: 'testcoll', sort: {_id: 1}}"); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); cursors.push_back( makeRemoteCursor(kTestShardIds[2], kTestShardHosts[2], CursorResponse(kTestNss, 2, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors), findCmd); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // Both hosts return network (retriable) errors. scheduleErrorResponse({ErrorCodes::HostUnreachable, "host unreachable"}); scheduleErrorResponse({ErrorCodes::HostUnreachable, "host unreachable"}); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); auto statusWithNext = arm->nextReady(); ASSERT(!statusWithNext.isOK()); ASSERT_EQ(statusWithNext.getStatus().code(), ErrorCodes::HostUnreachable); ASSERT_EQ(statusWithNext.getStatus().reason(), "host unreachable"); // Required to kill the 'arm' on error before destruction. auto killFuture = arm->kill(operationContext()); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, GetMoreCommandRequestIncludesMaxTimeMS) { BSONObj findCmd = fromjson("{find: 'testcoll', tailable: true, awaitData: true}"); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 123, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors), findCmd); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); std::vector<CursorResponse> responses; std::vector<BSONObj> batch1 = {fromjson("{_id: 1}")}; responses.emplace_back(kTestNss, CursorId(123), batch1); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 1}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_FALSE(arm->ready()); readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_OK(arm->setAwaitDataTimeout(Milliseconds(789))); // Pending getMore request should already have been scheduled without the maxTimeMS. BSONObj expectedCmdObj = BSON("getMore" << CursorId(123) << "collection" << "testcoll"); ASSERT_BSONOBJ_EQ(getNthPendingRequest(0).cmdObj, expectedCmdObj); ASSERT_FALSE(arm->ready()); responses.clear(); std::vector<BSONObj> batch2 = {fromjson("{_id: 2}")}; responses.emplace_back(kTestNss, CursorId(123), batch2); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 2}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_FALSE(arm->ready()); readyEvent = unittest::assertGet(arm->nextEvent()); // The next getMore request should include the maxTimeMS. expectedCmdObj = BSON("getMore" << CursorId(123) << "collection" << "testcoll" << "maxTimeMS" << 789); ASSERT_BSONOBJ_EQ(getNthPendingRequest(0).cmdObj, expectedCmdObj); // Clean up. responses.clear(); std::vector<BSONObj> batch3 = {fromjson("{_id: 3}")}; responses.emplace_back(kTestNss, CursorId(0), batch3); scheduleNetworkResponses(std::move(responses)); } DEATH_TEST_REGEX_F( AsyncResultsMergerTest, SortedTailableInvariantsIfInitialBatchHasNoPostBatchResumeToken, R"#(Invariant failure.*_promisedMinSortKeys.empty\(\) || _promisedMinSortKeys.size\(\) == _remotes.size\(\))#") { AsyncResultsMergerParams params; params.setNss(kTestNss); UUID uuid = UUID::gen(); std::vector<RemoteCursor> cursors; // Create one cursor whose initial response has a postBatchResumeToken. auto pbrtFirstCursor = makePostBatchResumeToken(Timestamp(1, 5)); auto firstDocSortKey = makeResumeToken(Timestamp(1, 4), uuid, BSON("_id" << 1)); auto firstCursorResponse = fromjson( str::stream() << "{_id: {clusterTime: {ts: Timestamp(1, 4)}, uuid: '" << uuid.toString() << "', documentKey: {_id: 1}}, $sortKey: [{_data: '" << firstDocSortKey.firstElement().String() << "'}]}"); cursors.push_back(makeRemoteCursor( kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 123, {firstCursorResponse}, boost::none, pbrtFirstCursor))); // Create a second cursor whose initial batch has no PBRT. cursors.push_back( makeRemoteCursor(kTestShardIds[1], kTestShardHosts[1], CursorResponse(kTestNss, 456, {}))); params.setRemotes(std::move(cursors)); params.setTailableMode(TailableModeEnum::kTailableAndAwaitData); params.setSort(change_stream_constants::kSortSpec); auto arm = std::make_unique<AsyncResultsMerger>(operationContext(), executor(), std::move(params)); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // We should be dead by now. MONGO_UNREACHABLE; } DEATH_TEST_REGEX_F(AsyncResultsMergerTest, SortedTailableCursorInvariantsIfOneOrMoreRemotesHasEmptyPostBatchResumeToken, R"#(Invariant failure.*!response.getPostBatchResumeToken\(\)->isEmpty\(\))#") { AsyncResultsMergerParams params; params.setNss(kTestNss); UUID uuid = UUID::gen(); std::vector<RemoteCursor> cursors; BSONObj pbrtFirstCursor; auto firstDocSortKey = makeResumeToken(Timestamp(1, 4), uuid, BSON("_id" << 1)); auto firstCursorResponse = fromjson( str::stream() << "{_id: {clusterTime: {ts: Timestamp(1, 4)}, uuid: '" << uuid.toString() << "', documentKey: {_id: 1}}, $sortKey: [{_data: '" << firstDocSortKey.firstElement().String() << "'}]}"); cursors.push_back(makeRemoteCursor( kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 123, {firstCursorResponse}, boost::none, pbrtFirstCursor))); params.setRemotes(std::move(cursors)); params.setTailableMode(TailableModeEnum::kTailableAndAwaitData); params.setSort(change_stream_constants::kSortSpec); auto arm = std::make_unique<AsyncResultsMerger>(operationContext(), executor(), std::move(params)); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_TRUE(arm->ready()); // We should be dead by now. MONGO_UNREACHABLE; } TEST_F(AsyncResultsMergerTest, SortedTailableCursorNotReadyIfRemoteHasLowerPostBatchResumeToken) { AsyncResultsMergerParams params; params.setNss(kTestNss); UUID uuid = UUID::gen(); std::vector<RemoteCursor> cursors; auto pbrtFirstCursor = makePostBatchResumeToken(Timestamp(1, 5)); auto firstDocSortKey = makeResumeToken(Timestamp(1, 4), uuid, BSON("_id" << 1)); auto firstCursorResponse = fromjson( str::stream() << "{_id: {clusterTime: {ts: Timestamp(1, 4)}, uuid: '" << uuid.toString() << "', documentKey: {_id: 1}}, $sortKey: [{data: '" << firstDocSortKey.firstElement().String() << "'}]}"); cursors.push_back(makeRemoteCursor( kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 123, {firstCursorResponse}, boost::none, pbrtFirstCursor))); auto tooLowPBRT = makePostBatchResumeToken(Timestamp(1, 2)); cursors.push_back(makeRemoteCursor(kTestShardIds[1], kTestShardHosts[1], CursorResponse(kTestNss, 456, {}, boost::none, tooLowPBRT))); params.setRemotes(std::move(cursors)); params.setTailableMode(TailableModeEnum::kTailableAndAwaitData); params.setSort(change_stream_constants::kSortSpec); auto arm = std::make_unique<AsyncResultsMerger>(operationContext(), executor(), std::move(params)); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // Clean up the cursors. std::vector<CursorResponse> responses; responses.emplace_back(kTestNss, CursorId(0), std::vector<BSONObj>{}); scheduleNetworkResponses(std::move(responses)); auto killFuture = arm->kill(operationContext()); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, SortedTailableCursorNewShardOrderedAfterExisting) { AsyncResultsMergerParams params; params.setNss(kTestNss); UUID uuid = UUID::gen(); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 123, {}))); params.setRemotes(std::move(cursors)); params.setTailableMode(TailableModeEnum::kTailableAndAwaitData); params.setSort(change_stream_constants::kSortSpec); auto arm = std::make_unique<AsyncResultsMerger>(operationContext(), executor(), std::move(params)); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // Schedule one response with an oplog timestamp in it. std::vector<CursorResponse> responses; auto firstDocSortKey = makeResumeToken(Timestamp(1, 4), uuid, BSON("_id" << 1)); auto pbrtFirstCursor = makePostBatchResumeToken(Timestamp(1, 6)); auto firstCursorResponse = fromjson( str::stream() << "{_id: {clusterTime: {ts: Timestamp(1, 4)}, uuid: '" << uuid.toString() << "', documentKey: {_id: 1}}, $sortKey: [{_data: '" << firstDocSortKey.firstElement().String() << "'}]}"); std::vector<BSONObj> batch1 = {firstCursorResponse}; auto firstDoc = batch1.front(); responses.emplace_back(kTestNss, CursorId(123), batch1, boost::none, pbrtFirstCursor); scheduleNetworkResponses(std::move(responses)); // Should be ready now. ASSERT_TRUE(arm->ready()); // Add the new shard. auto tooLowPBRT = makePostBatchResumeToken(Timestamp(1, 3)); std::vector<RemoteCursor> newCursors; newCursors.push_back( makeRemoteCursor(kTestShardIds[1], kTestShardHosts[1], CursorResponse(kTestNss, 456, {}, boost::none, tooLowPBRT))); arm->addNewShardCursors(std::move(newCursors)); // Now shouldn't be ready, our guarantee from the new shard isn't sufficiently advanced. ASSERT_FALSE(arm->ready()); readyEvent = unittest::assertGet(arm->nextEvent()); // Schedule another response from the other shard. responses.clear(); auto secondDocSortKey = makeResumeToken(Timestamp(1, 5), uuid, BSON("_id" << 2)); auto pbrtSecondCursor = makePostBatchResumeToken(Timestamp(1, 6)); auto secondCursorResponse = fromjson( str::stream() << "{_id: {clusterTime: {ts: Timestamp(1, 5)}, uuid: '" << uuid.toString() << "', documentKey: {_id: 2}}, $sortKey: [{_data: '" << secondDocSortKey.firstElement().String() << "'}]}"); std::vector<BSONObj> batch2 = {secondCursorResponse}; auto secondDoc = batch2.front(); responses.emplace_back(kTestNss, CursorId(456), batch2, boost::none, pbrtSecondCursor); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(firstCursorResponse, *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(secondCursorResponse, *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_FALSE(arm->ready()); readyEvent = unittest::assertGet(arm->nextEvent()); // Clean up the cursors. responses.clear(); std::vector<BSONObj> batch3 = {}; responses.emplace_back(kTestNss, CursorId(0), batch3); scheduleNetworkResponses(std::move(responses)); responses.clear(); std::vector<BSONObj> batch4 = {}; responses.emplace_back(kTestNss, CursorId(0), batch4); scheduleNetworkResponses(std::move(responses)); } TEST_F(AsyncResultsMergerTest, SortedTailableCursorNewShardOrderedBeforeExisting) { AsyncResultsMergerParams params; params.setNss(kTestNss); UUID uuid = UUID::gen(); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 123, {}))); params.setRemotes(std::move(cursors)); params.setTailableMode(TailableModeEnum::kTailableAndAwaitData); params.setSort(change_stream_constants::kSortSpec); auto arm = std::make_unique<AsyncResultsMerger>(operationContext(), executor(), std::move(params)); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // Schedule one response with an oplog timestamp in it. std::vector<CursorResponse> responses; auto firstDocSortKey = makeResumeToken(Timestamp(1, 4), uuid, BSON("_id" << 1)); auto pbrtFirstCursor = makePostBatchResumeToken(Timestamp(1, 5)); auto firstCursorResponse = fromjson( str::stream() << "{_id: {clusterTime: {ts: Timestamp(1, 4)}, uuid: '" << uuid.toString() << "', documentKey: {_id: 1}}, $sortKey: [{_data: '" << firstDocSortKey.firstElement().String() << "'}]}"); std::vector<BSONObj> batch1 = {firstCursorResponse}; responses.emplace_back(kTestNss, CursorId(123), batch1, boost::none, pbrtFirstCursor); scheduleNetworkResponses(std::move(responses)); // Should be ready now. ASSERT_TRUE(arm->ready()); // Add the new shard. auto tooLowPBRT = makePostBatchResumeToken(Timestamp(1, 3)); std::vector<RemoteCursor> newCursors; newCursors.push_back( makeRemoteCursor(kTestShardIds[1], kTestShardHosts[1], CursorResponse(kTestNss, 456, {}, boost::none, tooLowPBRT))); arm->addNewShardCursors(std::move(newCursors)); // Now shouldn't be ready, our guarantee from the new shard isn't sufficiently advanced. ASSERT_FALSE(arm->ready()); readyEvent = unittest::assertGet(arm->nextEvent()); // Schedule another response from the other shard. responses.clear(); auto secondDocSortKey = makeResumeToken(Timestamp(1, 3), uuid, BSON("_id" << 2)); auto pbrtSecondCursor = makePostBatchResumeToken(Timestamp(1, 5)); auto secondCursorResponse = fromjson( str::stream() << "{_id: {clusterTime: {ts: Timestamp(1, 3)}, uuid: '" << uuid.toString() << "', documentKey: {_id: 2}}, $sortKey: [{_data: '" << secondDocSortKey.firstElement().String() << "'}]}"); std::vector<BSONObj> batch2 = {secondCursorResponse}; // The last observed time should still be later than the first shard, so we can get the data // from it. responses.emplace_back(kTestNss, CursorId(456), batch2, boost::none, pbrtSecondCursor); scheduleNetworkResponses(std::move(responses)); executor()->waitForEvent(readyEvent); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(secondCursorResponse, *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(firstCursorResponse, *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_FALSE(arm->ready()); readyEvent = unittest::assertGet(arm->nextEvent()); // Clean up the cursors. responses.clear(); std::vector<BSONObj> batch3 = {}; responses.emplace_back(kTestNss, CursorId(0), batch3); scheduleNetworkResponses(std::move(responses)); responses.clear(); std::vector<BSONObj> batch4 = {}; responses.emplace_back(kTestNss, CursorId(0), batch4); scheduleNetworkResponses(std::move(responses)); } TEST_F(AsyncResultsMergerTest, SortedTailableCursorReturnsHighWaterMarkSortKey) { AsyncResultsMergerParams params; params.setNss(kTestNss); std::vector<RemoteCursor> cursors; // Create three cursors with empty initial batches. Each batch has a PBRT. auto pbrtFirstCursor = makePostBatchResumeToken(Timestamp(1, 5)); cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 123, {}, boost::none, pbrtFirstCursor))); auto pbrtSecondCursor = makePostBatchResumeToken(Timestamp(1, 1)); cursors.push_back( makeRemoteCursor(kTestShardIds[1], kTestShardHosts[1], CursorResponse(kTestNss, 456, {}, boost::none, pbrtSecondCursor))); auto pbrtThirdCursor = makePostBatchResumeToken(Timestamp(1, 4)); cursors.push_back( makeRemoteCursor(kTestShardIds[2], kTestShardHosts[2], CursorResponse(kTestNss, 789, {}, boost::none, pbrtThirdCursor))); params.setRemotes(std::move(cursors)); params.setTailableMode(TailableModeEnum::kTailableAndAwaitData); params.setSort(change_stream_constants::kSortSpec); auto arm = std::make_unique<AsyncResultsMerger>(operationContext(), executor(), std::move(params)); // We have no results to return, so the ARM is not ready. auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // The high water mark should be the second cursor's PBRT, since it is the lowest of the three. ASSERT_BSONOBJ_EQ(arm->getHighWaterMark(), pbrtSecondCursor); // Advance the PBRT of the second cursor. It should still be the lowest. The fixture expects // each cursor to be updated in-order, so we keep the first and third PBRTs constant. pbrtSecondCursor = makePostBatchResumeToken(Timestamp(1, 3)); std::vector<BSONObj> emptyBatch = {}; scheduleNetworkResponse({kTestNss, CursorId(123), emptyBatch, boost::none, pbrtFirstCursor}); scheduleNetworkResponse({kTestNss, CursorId(456), emptyBatch, boost::none, pbrtSecondCursor}); scheduleNetworkResponse({kTestNss, CursorId(789), emptyBatch, boost::none, pbrtThirdCursor}); ASSERT_BSONOBJ_EQ(arm->getHighWaterMark(), pbrtSecondCursor); ASSERT_FALSE(arm->ready()); // Advance the second cursor again, so that it surpasses the other two. The third cursor becomes // the new high water mark. pbrtSecondCursor = makePostBatchResumeToken(Timestamp(1, 6)); scheduleNetworkResponse({kTestNss, CursorId(123), emptyBatch, boost::none, pbrtFirstCursor}); scheduleNetworkResponse({kTestNss, CursorId(456), emptyBatch, boost::none, pbrtSecondCursor}); scheduleNetworkResponse({kTestNss, CursorId(789), emptyBatch, boost::none, pbrtThirdCursor}); ASSERT_BSONOBJ_EQ(arm->getHighWaterMark(), pbrtThirdCursor); ASSERT_FALSE(arm->ready()); // Advance the third cursor such that the first cursor becomes the high water mark. pbrtThirdCursor = makePostBatchResumeToken(Timestamp(1, 7)); scheduleNetworkResponse({kTestNss, CursorId(123), emptyBatch, boost::none, pbrtFirstCursor}); scheduleNetworkResponse({kTestNss, CursorId(456), emptyBatch, boost::none, pbrtSecondCursor}); scheduleNetworkResponse({kTestNss, CursorId(789), emptyBatch, boost::none, pbrtThirdCursor}); ASSERT_BSONOBJ_EQ(arm->getHighWaterMark(), pbrtFirstCursor); ASSERT_FALSE(arm->ready()); // Clean up the cursors. std::vector<BSONObj> cleanupBatch = {}; scheduleNetworkResponse({kTestNss, CursorId(0), cleanupBatch}); scheduleNetworkResponse({kTestNss, CursorId(0), cleanupBatch}); scheduleNetworkResponse({kTestNss, CursorId(0), cleanupBatch}); } TEST_F(AsyncResultsMergerTest, SortedTailableCursorDoesNotAdvanceHighWaterMarkForIneligibleCursor) { AsyncResultsMergerParams params; params.setNss(kTestNss); std::vector<RemoteCursor> cursors; // Create three cursors with empty initial batches. Each batch has a PBRT. The third cursor is // the $changeStream opened on "config.shards" to monitor for the addition of new shards. auto pbrtFirstCursor = makePostBatchResumeToken(Timestamp(1, 5)); cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 123, {}, boost::none, pbrtFirstCursor))); auto pbrtSecondCursor = makePostBatchResumeToken(Timestamp(1, 3)); cursors.push_back( makeRemoteCursor(kTestShardIds[1], kTestShardHosts[1], CursorResponse(kTestNss, 456, {}, boost::none, pbrtSecondCursor))); auto pbrtConfigCursor = makePostBatchResumeToken(Timestamp(1, 1)); cursors.push_back(makeRemoteCursor( kTestShardIds[2], kTestShardHosts[2], CursorResponse(ShardType::ConfigNS, 789, {}, boost::none, pbrtConfigCursor))); params.setRemotes(std::move(cursors)); params.setTailableMode(TailableModeEnum::kTailableAndAwaitData); params.setSort(change_stream_constants::kSortSpec); auto arm = std::make_unique<AsyncResultsMerger>(operationContext(), executor(), std::move(params)); // We have no results to return, so the ARM is not ready. auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // For a change stream cursor on "config.shards", the first batch is not eligible to provide the // HWM. Despite the fact that 'pbrtConfigCursor' has the lowest PBRT, the ARM returns the PBRT // of 'pbrtSecondCursor' as the current high water mark. This guards against the possibility // that the user requests a start time in the future. The "config.shards" cursor must start // monitoring for shards at the current point in time, and so its initial PBRT will be lower // than that of the shards. We do not wish to return a high water mark to the client that is // earlier than the start time they specified in their request. auto initialHighWaterMark = arm->getHighWaterMark(); ASSERT_BSONOBJ_EQ(initialHighWaterMark, pbrtSecondCursor); // Advance the PBRT of the 'pbrtConfigCursor'. It is still the lowest, but is ineligible to // provide the high water mark because it is still lower than the high water mark that was // already returned. As above, the guards against the possibility that the user requested a // stream with a start point at an arbitrary point in the future. pbrtConfigCursor = makePostBatchResumeToken(Timestamp(1, 2)); scheduleNetworkResponse({kTestNss, CursorId(123), {}, boost::none, pbrtFirstCursor}); scheduleNetworkResponse({kTestNss, CursorId(456), {}, boost::none, pbrtSecondCursor}); scheduleNetworkResponse( {ShardType::ConfigNS, CursorId(789), {}, boost::none, pbrtConfigCursor}); // The high water mark has not advanced from its previous value. ASSERT_BSONOBJ_EQ(arm->getHighWaterMark(), initialHighWaterMark); ASSERT_FALSE(arm->ready()); // If the "config.shards" cursor returns a result, this document does not advance the HWM. We // consume this event internally but do not return it to the client, and its resume token is not // actually resumable. We therefore do not want to expose it to the client via the PBRT. const auto configUUID = UUID::gen(); auto configEvent = fromjson("{_id: 'shard_add_event'}"); pbrtFirstCursor = makePostBatchResumeToken(Timestamp(1, 15)); pbrtSecondCursor = makePostBatchResumeToken(Timestamp(1, 13)); pbrtConfigCursor = makeResumeToken(Timestamp(1, 11), configUUID, configEvent); configEvent = configEvent.addField(BSON("$sortKey" << BSON_ARRAY(pbrtConfigCursor)).firstElement()); scheduleNetworkResponse({kTestNss, CursorId(123), {}, boost::none, pbrtFirstCursor}); scheduleNetworkResponse({kTestNss, CursorId(456), {}, boost::none, pbrtSecondCursor}); scheduleNetworkResponse( {ShardType::ConfigNS, CursorId(789), {configEvent}, boost::none, pbrtConfigCursor}); // The config cursor has a lower sort key than the other shards, so we can retrieve the event. ASSERT_TRUE(arm->ready()); ASSERT_BSONOBJ_EQ(configEvent, *unittest::assertGet(arm->nextReady()).getResult()); readyEvent = unittest::assertGet(arm->nextEvent()); // Reading the config cursor event document does not advance the high water mark. ASSERT_BSONOBJ_EQ(arm->getHighWaterMark(), initialHighWaterMark); ASSERT_FALSE(arm->ready()); // If the next config batch is empty but the PBRT is still the resume token of the addShard // event, it does not advance the ARM's high water mark sort key. scheduleNetworkResponse({kTestNss, CursorId(123), {}, boost::none, pbrtFirstCursor}); scheduleNetworkResponse({kTestNss, CursorId(456), {}, boost::none, pbrtSecondCursor}); scheduleNetworkResponse( {ShardType::ConfigNS, CursorId(789), {}, boost::none, pbrtConfigCursor}); ASSERT_BSONOBJ_EQ(arm->getHighWaterMark(), initialHighWaterMark); ASSERT_FALSE(arm->ready()); // If none of the above criteria obtain, then the "config.shards" cursor is eligible to advance // the ARM's high water mark. The only reason we allow the config.shards cursor to participate // in advancing of the high water mark at all is so that we cannot end up in a situation where // the config cursor is always the lowest and the high water mark can therefore never advance. pbrtConfigCursor = makePostBatchResumeToken(Timestamp(1, 12)); scheduleNetworkResponse({kTestNss, CursorId(123), {}, boost::none, pbrtFirstCursor}); scheduleNetworkResponse({kTestNss, CursorId(456), {}, boost::none, pbrtSecondCursor}); scheduleNetworkResponse( {ShardType::ConfigNS, CursorId(789), {}, boost::none, pbrtConfigCursor}); ASSERT_BSONOBJ_GT(arm->getHighWaterMark(), initialHighWaterMark); ASSERT_BSONOBJ_EQ(arm->getHighWaterMark(), pbrtConfigCursor); ASSERT_FALSE(arm->ready()); // Clean up the cursors. std::vector<BSONObj> cleanupBatch = {}; scheduleNetworkResponse({kTestNss, CursorId(0), cleanupBatch}); scheduleNetworkResponse({kTestNss, CursorId(0), cleanupBatch}); scheduleNetworkResponse({kTestNss, CursorId(0), cleanupBatch}); } TEST_F(AsyncResultsMergerTest, GetMoreCommandRequestWithoutTailableCantHaveMaxTime) { BSONObj findCmd = fromjson("{find: 'testcoll'}"); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 123, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors), findCmd); ASSERT_NOT_OK(arm->setAwaitDataTimeout(Milliseconds(789))); auto killFuture = arm->kill(operationContext()); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, GetMoreCommandRequestWithoutAwaitDataCantHaveMaxTime) { BSONObj findCmd = fromjson("{find: 'testcoll', tailable: true}"); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 123, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors), findCmd); ASSERT_NOT_OK(arm->setAwaitDataTimeout(Milliseconds(789))); auto killFuture = arm->kill(operationContext()); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, ShardCanErrorInBetweenReadyAndNextEvent) { BSONObj findCmd = fromjson("{find: 'testcoll', tailable: true}"); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 123, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors), findCmd); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); scheduleErrorResponse({ErrorCodes::BadValue, "bad thing happened"}); ASSERT_EQ(ErrorCodes::BadValue, arm->nextEvent().getStatus()); // Required to kill the 'arm' on error before destruction. auto killFuture = arm->kill(operationContext()); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, KillShouldNotWaitForRemoteCommandsBeforeSchedulingKillCursors) { std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); // Before any requests are scheduled, ARM is not ready to return results. ASSERT_FALSE(arm->ready()); ASSERT_FALSE(arm->remotesExhausted()); // Schedule requests. auto readyEvent = unittest::assertGet(arm->nextEvent()); // Before any responses are delivered, ARM is not ready to return results. ASSERT_FALSE(arm->ready()); ASSERT_FALSE(arm->remotesExhausted()); // Kill the ARM while a batch is still outstanding. The callback for the outstanding batch // should be canceled. auto killFuture = arm->kill(operationContext()); // Check that the ARM will run killCursors. assertKillCusorsCmdHasCursorId(getNthPendingRequest(0u).cmdObj, 1); // Let the callback run now that it's been canceled. runReadyCallbacks(); executor()->waitForEvent(readyEvent); killFuture.wait(); } TEST_F(AsyncResultsMergerTest, GetMoresShouldNotIncludeLSIDOrTxnNumberIfNoneSpecified) { std::vector<RemoteCursor> cursors; cursors.emplace_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); // There should be no lsid txnNumber in the scheduled getMore. ASSERT_OK(arm->nextEvent().getStatus()); onCommand([&](const auto& request) { ASSERT(request.cmdObj["getMore"]); ASSERT(request.cmdObj["lsid"].eoo()); ASSERT(request.cmdObj["txnNumber"].eoo()); return CursorResponse(kTestNss, 0LL, {BSON("x" << 1)}) .toBSON(CursorResponse::ResponseType::SubsequentResponse); }); } TEST_F(AsyncResultsMergerTest, GetMoresShouldIncludeLSIDIfSpecified) { auto lsid = makeLogicalSessionIdForTest(); operationContext()->setLogicalSessionId(lsid); std::vector<RemoteCursor> cursors; cursors.emplace_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); // There should be an lsid and no txnNumber in the scheduled getMore. ASSERT_OK(arm->nextEvent().getStatus()); onCommand([&](const auto& request) { ASSERT(request.cmdObj["getMore"]); ASSERT_EQ(parseSessionIdFromCmd(request.cmdObj), lsid); ASSERT(request.cmdObj["txnNumber"].eoo()); return CursorResponse(kTestNss, 1LL, {BSON("x" << 1)}) .toBSON(CursorResponse::ResponseType::SubsequentResponse); }); // Subsequent requests still pass the lsid. ASSERT(arm->ready()); ASSERT_OK(arm->nextReady().getStatus()); ASSERT_FALSE(arm->ready()); ASSERT_OK(arm->nextEvent().getStatus()); onCommand([&](const auto& request) { ASSERT(request.cmdObj["getMore"]); ASSERT_EQ(parseSessionIdFromCmd(request.cmdObj), lsid); ASSERT(request.cmdObj["txnNumber"].eoo()); return CursorResponse(kTestNss, 0LL, {BSON("x" << 1)}) .toBSON(CursorResponse::ResponseType::SubsequentResponse); }); } TEST_F(AsyncResultsMergerTest, GetMoresShouldIncludeLSIDAndTxnNumIfSpecified) { auto lsid = makeLogicalSessionIdForTest(); operationContext()->setLogicalSessionId(lsid); const TxnNumber txnNumber = 5; operationContext()->setTxnNumber(txnNumber); std::vector<RemoteCursor> cursors; cursors.emplace_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 1, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors)); // The first scheduled getMore should pass the txnNumber the ARM was constructed with. ASSERT_OK(arm->nextEvent().getStatus()); onCommand([&](const auto& request) { ASSERT(request.cmdObj["getMore"]); ASSERT_EQ(parseSessionIdFromCmd(request.cmdObj), lsid); ASSERT_EQ(request.cmdObj["txnNumber"].numberLong(), txnNumber); return CursorResponse(kTestNss, 1LL, {BSON("x" << 1)}) .toBSON(CursorResponse::ResponseType::SubsequentResponse); }); // Subsequent requests still pass the txnNumber. ASSERT(arm->ready()); ASSERT_OK(arm->nextReady().getStatus()); ASSERT_FALSE(arm->ready()); // Subsequent getMore requests should include txnNumber. ASSERT_OK(arm->nextEvent().getStatus()); onCommand([&](const auto& request) { ASSERT(request.cmdObj["getMore"]); ASSERT_EQ(parseSessionIdFromCmd(request.cmdObj), lsid); ASSERT_EQ(request.cmdObj["txnNumber"].numberLong(), txnNumber); return CursorResponse(kTestNss, 0LL, {BSON("x" << 1)}) .toBSON(CursorResponse::ResponseType::SubsequentResponse); }); } DEATH_TEST_REGEX_F(AsyncResultsMergerTest, ConstructingARMWithTxnNumAndNoLSIDShouldCrash, R"#(Invariant failure.*params.getSessionId\(\))#") { AsyncResultsMergerParams params; OperationSessionInfoFromClient sessionInfo; sessionInfo.setTxnNumber(5); params.setOperationSessionInfo(sessionInfo); // This should trigger an invariant. ASSERT_FALSE( std::make_unique<AsyncResultsMerger>(operationContext(), executor(), std::move(params))); } DEATH_TEST_F(AsyncResultsMergerTest, ShouldFailIfAskedToPerformGetMoresWithoutAnOpCtx, "Cannot schedule a getMore without an OperationContext") { BSONObj findCmd = fromjson("{find: 'testcoll', tailable: true, awaitData: true}"); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 123, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors), findCmd); ASSERT_FALSE(arm->ready()); arm->detachFromOperationContext(); arm->scheduleGetMores().ignore(); // Should crash. } TEST_F(AsyncResultsMergerTest, ShouldNotScheduleGetMoresWithoutAnOperationContext) { BSONObj findCmd = fromjson("{find: 'testcoll', tailable: true, awaitData: true}"); std::vector<RemoteCursor> cursors; cursors.push_back( makeRemoteCursor(kTestShardIds[0], kTestShardHosts[0], CursorResponse(kTestNss, 123, {}))); auto arm = makeARMFromExistingCursors(std::move(cursors), findCmd); ASSERT_FALSE(arm->ready()); auto readyEvent = unittest::assertGet(arm->nextEvent()); ASSERT_FALSE(arm->ready()); // While detached from the OperationContext, schedule an empty batch response. Because the // response is empty and this is a tailable cursor, the ARM will need to run another getMore on // that host, but it should not schedule this without a non-null OperationContext. arm->detachFromOperationContext(); { std::vector<CursorResponse> responses; std::vector<BSONObj> emptyBatch; responses.emplace_back(kTestNss, CursorId(123), emptyBatch); scheduleNetworkResponses(std::move(responses)); } ASSERT_FALSE(arm->ready()); ASSERT_FALSE(networkHasReadyRequests()); // Tests that we haven't asked for the next batch yet. // After manually requesting the next getMore, the ARM should be ready. arm->reattachToOperationContext(operationContext()); ASSERT_OK(arm->scheduleGetMores()); // Schedule the next getMore response. { std::vector<CursorResponse> responses; std::vector<BSONObj> nonEmptyBatch = {fromjson("{_id: 1}")}; responses.emplace_back(kTestNss, CursorId(123), nonEmptyBatch); scheduleNetworkResponses(std::move(responses)); } ASSERT_TRUE(arm->ready()); ASSERT_FALSE(arm->remotesExhausted()); ASSERT_BSONOBJ_EQ(fromjson("{_id: 1}"), *unittest::assertGet(arm->nextReady()).getResult()); ASSERT_FALSE(arm->ready()); ASSERT_FALSE(arm->remotesExhausted()); auto killFuture = arm->kill(operationContext()); killFuture.wait(); } } // namespace } // namespace mongo
44.931426
117
0.693113
[ "vector" ]
80650242b3090c2c6884fe385f6c223cbc5f0c21
3,333
cpp
C++
LeetCode/Problems/Algorithms/#37_SudokuSolver.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#37_SudokuSolver.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#37_SudokuSolver.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { private: vector<vector<char>> board; vector<vector<bool>> line_vis_elem; vector<vector<bool>> col_vis_elem; vector<vector<bool>> sub_box_vis_elem; vector<short int> next_pos; void back(short int cur_pos, short int vis_cnt, bool& is_solved){ if(vis_cnt == 9 * 9){ is_solved = 1; }else{ short int i = cur_pos / 9; short int j = cur_pos % 9; short int sub_box_idx = 3 * (i / 3) + j / 3; for(short int digit = 1; !is_solved && digit <= 9; ++digit){ if(!line_vis_elem[i][digit] && !col_vis_elem[j][digit] && !sub_box_vis_elem[sub_box_idx][digit]){ board[i][j] = char(digit + '0'); line_vis_elem[i][digit] = 1; col_vis_elem[j][digit] = 1; sub_box_vis_elem[sub_box_idx][digit] = 1; back(next_pos[cur_pos], vis_cnt + 1, is_solved); line_vis_elem[i][digit] = 0; col_vis_elem[j][digit] = 0; sub_box_vis_elem[sub_box_idx][digit] = 0; } } } } public: Solution(){ line_vis_elem.resize(9, vector<bool>(10)); col_vis_elem.resize(9, vector<bool>(10)); sub_box_vis_elem.resize(9, vector<bool>(10)); next_pos.resize(9 * 9); } void solveSudoku(vector<vector<char>>& board) { // board initialization this->board = board; // mark visited digits along the lines, columns and sub-boxes for(short int i = 0; i < 9; ++i){ for(short int digit = 1; digit <= 9; ++digit){ line_vis_elem[i][digit] = 0; col_vis_elem[i][digit] = 0; sub_box_vis_elem[i][digit] = 0; } } short int vis_cnt = 0; for(short int i = 0 ; i < 9; ++i){ for(short int j = 0; j < 9; ++j){ if(board[i][j] != '.'){ short int digit = board[i][j] - '0'; short int sub_box_idx = 3 * (i / 3) + j / 3; line_vis_elem[i][digit] = 1; col_vis_elem[j][digit] = 1; sub_box_vis_elem[sub_box_idx][digit] = 1; ++vis_cnt; } } } // next position to fill fill(next_pos.begin(), next_pos.end(), -1); short int first_pos = -1; short int prev_pos = -1; for(short int i = 0; i < 9; ++i){ for(short int j = 0; j < 9; ++j){ if(board[i][j] == '.'){ short int cur_pos = 9 * i + j; if(first_pos == -1){ first_pos = cur_pos; } if(prev_pos != -1){ next_pos[prev_pos] = cur_pos; } prev_pos = cur_pos; } } } // solve bool is_solved = 0; back(first_pos, vis_cnt, is_solved); // copy the solved board board = this->board; } };
35.457447
114
0.426343
[ "vector" ]
8068381a8039e0076880a066cd49af0086116c51
2,734
cpp
C++
src/bdhost/ConfigHandler.cpp
drvcoin/drive
e92e62b9600c0bb2812216212b641e86d3677a94
[ "MIT" ]
1
2018-06-13T09:14:19.000Z
2018-06-13T09:14:19.000Z
src/bdhost/ConfigHandler.cpp
drvcoin/drive
e92e62b9600c0bb2812216212b641e86d3677a94
[ "MIT" ]
24
2018-08-21T01:28:40.000Z
2018-11-05T07:55:15.000Z
src/bdhost/ConfigHandler.cpp
drvcoin/drive
e92e62b9600c0bb2812216212b641e86d3677a94
[ "MIT" ]
3
2018-05-18T01:46:45.000Z
2018-06-05T08:35:37.000Z
/* Copyright (c) 2018 Drive Foundation 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 <sstream> #include "Options.h" #include "Util.h" #include "HttpHandlerRegister.h" #include "ConfigHandler.h" namespace bdhost { static const char PATH[] = "/api/host/Config"; REGISTER_HTTP_HANDLER(Config, PATH, new ConfigHandler()); void ConfigHandler::ProcessRequest(bdhttp::HttpContext & context) { std::string path = context.path(); if (path.size() <= sizeof(PATH) || path[sizeof(PATH) - 1] != '/') { if (path.size() == sizeof(PATH) && path == std::string(PATH) + '/') { context.writeResponse("{\"Name\":\"Config\", \"Path\":\"host://Config\", \"Type\":\"Config\"}"); } else { context.setResponseCode(404); context.writeError("Failed", "Object not found", bdhttp::ErrorCode::OBJECT_NOT_FOUND); } return; } auto pos = path.find('/', sizeof(PATH)); if (pos != std::string::npos) { context.setResponseCode(404); context.writeError("Failed", "Object not found", bdhttp::ErrorCode::OBJECT_NOT_FOUND); return; } auto action = path.substr(sizeof(PATH)); if (action == "GetStatistics") { this->OnGetStatistics(context); } else { context.setResponseCode(500); context.writeError("Failed", "Action not supported", bdhttp::ErrorCode::NOT_SUPPORTED); } } void ConfigHandler::OnGetStatistics(bdhttp::HttpContext & context) { auto availableSize = Options::size - GetReservedSpace(); std::stringstream ss; ss << "{\"AvailableSize\":" << availableSize << ",\"TotalSize\":" << Options::size << "}"; context.writeResponse(ss.str()); } }
32.547619
104
0.677762
[ "object" ]
8069cefb8aa4b4bf3197efa69373beb360359233
1,521
cpp
C++
src/geometry.cpp
LaurentValette/BulletGL
1272fa305b0e2818b98b44c481ae90d76b2f06f0
[ "MIT" ]
null
null
null
src/geometry.cpp
LaurentValette/BulletGL
1272fa305b0e2818b98b44c481ae90d76b2f06f0
[ "MIT" ]
null
null
null
src/geometry.cpp
LaurentValette/BulletGL
1272fa305b0e2818b98b44c481ae90d76b2f06f0
[ "MIT" ]
null
null
null
#include "geometry.h" Cal::Geometry::Geometry(const std::vector<glm::vec3>& vertices, const std::vector<glm::vec3>& normals) { m_vertices = vertices; m_normals = normals; // Create vertex array object glGenVertexArrays(1, &vertex_array_object); glBindVertexArray(vertex_array_object); // Create vertex buffer glGenBuffers(1, &vertex_buffer); glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(GLfloat) * 3, vertices.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, (void *)0); // Create normal buffer glGenBuffers(1, &normal_buffer); glBindBuffer(GL_ARRAY_BUFFER, normal_buffer); glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(GLfloat) * 3, normals.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, false, 0, (void *)0); } void Cal::Geometry::render(GLuint program) { glm::mat4 model = getWorldTransform(); glUniformMatrix4fv(glGetUniformLocation(program, "model"), 1, false, glm::value_ptr(model)); glBindVertexArray(vertex_array_object); glDrawArrays(GL_TRIANGLES, 0, m_vertices.size()); } Cal::Geometry::~Geometry() { m_dynamicsWorld->removeRigidBody(rigidBody); delete rigidBody; delete motionState; delete collisionShape; glDeleteBuffers(1, &vertex_buffer); glDeleteBuffers(1, &normal_buffer); glDeleteVertexArrays(1, &vertex_array_object); }
33.065217
106
0.723866
[ "geometry", "render", "object", "vector", "model" ]
8071d1a37c4d36df7177194552008717112fc4bf
15,351
cpp
C++
myglwidget.cpp
AlgoTyc/Computergrafik
ff37616e79f87971071b3ceac4090edf58f5cd6c
[ "MIT" ]
null
null
null
myglwidget.cpp
AlgoTyc/Computergrafik
ff37616e79f87971071b3ceac4090edf58f5cd6c
[ "MIT" ]
null
null
null
myglwidget.cpp
AlgoTyc/Computergrafik
ff37616e79f87971071b3ceac4090edf58f5cd6c
[ "MIT" ]
null
null
null
#include "myglwidget.h" #include <iostream> #include <QVector3D> #include <QtMath> #include <QElapsedTimer> #include <QRandomGenerator> MyGLWidget::MyGLWidget(QWidget *parent): QOpenGLWidget{parent}{ //create model gimbal= new Model(); sphere= new Model(); skybox = new Skybox(); } MyGLWidget::~MyGLWidget() { makeCurrent(); gimbal->finiGL(); glDeleteTextures(1, &gw_tex); delete gimbal; delete m_prog; delete sun_prog; sphere->finiGL(); delete sphere; delete skybox; } void MyGLWidget::initializeGL(){ //Emerald m_material[0]={QVector3D(0.0215,0.1745,0.0215), //Ambient licht QVector3D(0.07568,0.61424,0.07568), QVector3D(0.633,0.727811,0.633),0.6 }; //Gold m_material[1]={QVector3D(0.24725,0.1995,0.0745), QVector3D(0.75164,0.60648,0.22648), QVector3D(0.628281,0.555802,0.366065),0.4 }; //white rubber m_material[2]={QVector3D(0.05,0.05,0.05), QVector3D(0.5,0.5,0.5), QVector3D(0.7,0.7,0.7), 0.078125 }; //Silver m_material[3]={QVector3D(0.19225,0.19225,0.19225), QVector3D(0.50754,0.50754,0.50754), QVector3D(0.508273,0.508273,0.508273),0.4 }; ls[0]={QVector3D(2.0, 0.0, 2.0),QVector3D(1.0, 1.0, 0.0),0.8, 0.8, 1.0, 1.0, 0.22, 0.20}; ls[1]={QVector3D(0.0, 2.0, 2.0),QVector3D(0.0, 0.0, 1.0),0.8, 0.8, 1.0, 1.0, 0.22, 0.20}; ls[2]={QVector3D(0.0, 0.0, 0.0),QVector3D(1.0, 1.0, 1.0),0.1, 0.1, 0.1, 1.0, 0.7,1.8}; ls[3]={QVector3D(-2.0, 0.0, -2.0),QVector3D(0.5, 1.0, 0.5),0.8, 0.8,1.0,1.0,0.22,0.20}; ls[4]={QVector3D(0.25, -1.25, -0.25),QVector3D(1.0, 0.0, 0.0),0.8, 0.8, 1.0, 1.0, 0.22, 0.20}; skybox->init_skybox(); //initialize OGLFunctions and test bool success = initializeOpenGLFunctions(); Q_ASSERT(success); Q_UNUSED(success); //Load image QImage texImg; texImg.load(":/gimbal_wood.jpg"); Q_ASSERT(!texImg.isNull()); //Create texture object glGenTextures(1, &gw_tex); glBindTexture(GL_TEXTURE_2D, gw_tex); //Fill with pixel data glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, texImg.width(), texImg.height(), 0, GL_BGRA, GL_UNSIGNED_BYTE, texImg.bits()); //Set filtering ( interpolation ) options //Without these commands, _sampling will return black_ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); //Set wrap mode to "repeat" glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Generate Uniform Buer Object glGenBuffers(1, &uboLights); glBindBuffer(GL_UNIFORM_BUFFER, uboLights); glBufferData(GL_UNIFORM_BUFFER, NUM_LS * sizeof(LightSource), nullptr, GL_STATIC_DRAW ); // Set Buffer size, 64 Byte for each LS glBindBufferBase(GL_UNIFORM_BUFFER, 0, uboLights); glBindBuffer(GL_UNIFORM_BUFFER, 0); // Enable back face culling //glEnable(GL_CULL_FACE); //Create models gimbal->initGL(":/gimbal.obj"); sphere->initGL(":/sphere.obj"); //create shaderprogramm m_prog = new QOpenGLShaderProgram(); sun_prog = new QOpenGLShaderProgram(); // addShader() compiles and attaches shader stages for linking m_prog->addShaderFromSourceFile(QOpenGLShader::Vertex, ":/sample.vert"); m_prog->addShaderFromSourceFile(QOpenGLShader::Fragment, ":/sample.frag"); sun_prog->addCacheableShaderFromSourceFile(QOpenGLShader::Vertex,":/light.vert"); sun_prog->addCacheableShaderFromSourceFile(QOpenGLShader::Fragment,":/light.frag"); //Now link attached stages m_prog->link(); sun_prog->link(); //Abort program if any of these steps failed //Q_ASSERT(m_prog->isLinked()); Q_ASSERT(sun_prog->isLinked()); //Depth test enable for better display our model glEnable(GL_DEPTH_TEST); //Passes if the incoming depth value is less than the stored depth value. glDepthFunc(GL_LESS); } void MyGLWidget::paintGL() { QElapsedTimer timer; timer.start(); // set clear color dunkelgrau glClearColor(0.1f, 0.1f, 0.1f, 1.0f); //Erase old pixels glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT); QMatrix4x4 p_matrix; QMatrix4x4 m_matrix; QMatrix4x4 v_matrix; p_matrix.perspective(m_FOV,width()/((float)height()),m_Near,m_Far); v_matrix.translate(v_matrix.inverted()*m_CameraPos); //Bind shaderprogramm for the sun sun_prog->bind(); //Draw Light sources for(unsigned int i=0;i<NUM_LS;i++){ GLfloat rot_lights=timer.msecsSinceReference()*0.0004*(i+1); if(i==0){ m_lightPos.setX(sin(rot_lights)*15); m_lightPos.setY(2); m_lightPos.setZ(cos(rot_lights)*15); }else if (i==1) { ls[i].position.setX(sin(rot_lights)*15); ls[i].position.setY(-3); ls[i].position.setZ(-cos(rot_lights)*15); }else if (i==2) { ls[i].position.setX(0); ls[i].position.setY(0); ls[i].position.setZ(0); }else if (i==3) { ls[i].position.setX(sin(rot_lights)*15); ls[i].position.setY(-cos(rot_lights)*15); ls[i].position.setZ(cos(rot_lights)*10); }else if (i==4) { ls[i].position.setX(3); ls[i].position.setY(sin(rot_lights)*15); ls[i].position.setZ(cos(rot_lights)*15); } m_matrix.scale(0.09,0.09,0.09); m_matrix.translate(ls[i].position); // Set MVP matrix m_prog->setUniformValue(3,p_matrix*v_matrix*m_matrix); //color for they light m_prog->setUniformValue(1,ls[i].color); m_matrix.setToIdentity(); //draw light sphere->drawElements(); } //Ambient,Diffuse,Specular,Shininess for(int i=0;i<NUM_LS;i++){ ls[i].ka = ((float) m_RotA) / 360.f; ls[i].kd = ((float) m_RotB) / 360.f; ls[i].ks = ((float) m_RotC) / 360.f; } //Bind texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, skybox->handleCubeMap()); //Bind ubo glBindBuffer(GL_UNIFORM_BUFFER, uboLights); //send LS to Shader glBindBufferBase(GL_UNIFORM_BUFFER, 0, uboLights); glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(ls), ls); //Bind shaderprogramm m_prog->bind(); // write unit indices to uniforms m_prog->setUniformValue(19, 0); //Viewer positon m_prog->setUniformValue(8,m_CameraPos); //Light position m_prog->setUniformValue(9,m_lightPos); //shininess m_prog->setUniformValue(14,m_material[2].ambient); m_prog->setUniformValue(15,m_material[2].diffuse); m_prog->setUniformValue(16,m_material[2].specular); m_prog->setUniformValue(17,m_material[2].shininess); if(!activateAnimation){ if(cameraOnGimbal){ v_matrix.translate(v_matrix.inverted()*QVector3D(0.0,0.0,0.0)); v_matrix.rotate(-m_RotC,1.0,0.0,0.0); v_matrix.rotate(-m_RotB,0.0,1.0,0.0); v_matrix.rotate(-m_RotA,1.0,0.0,0.0); } //First gimbal m_matrix.scale(0.9,0.9,0.9); m_matrix.rotate(m_RotA,1.0,0.0,0.0); // Set MVP matrix m_prog->setUniformValue(3,p_matrix); m_prog->setUniformValue(4,v_matrix); m_prog->setUniformValue(5,m_matrix); m_prog->setUniformValue(20,m_matrix.normalMatrix()); //color for one Ring m_prog->setUniformValue(6,QVector4D(1.0,0.0,0.0,1.0)); //draw model gimbal->drawElements(); //Second gimbal m_matrix.scale(0.85,0.85,0.85); m_matrix.rotate(m_RotB,0.0,1.0,0.0); // Set MVP matrix m_prog->setUniformValue(3,p_matrix); m_prog->setUniformValue(4,v_matrix); m_prog->setUniformValue(5,m_matrix); m_prog->setUniformValue(20,m_matrix.normalMatrix()); //color for one Ring m_prog->setUniformValue(6,QVector4D(0.0,1.0,0.0,1.0)); //draw model gimbal->drawElements(); //Ball m_matrix.setToIdentity(); m_matrix.rotate(m_RotA,1.0,0.0,0.0); m_matrix.rotate(m_RotB,0.0,1.0,0.0); m_matrix.rotate(m_Angle,0.0,0.0,1.0); m_matrix.scale(0.05,0.05,0.05); m_matrix.translate(0.0,14.9,1.9); // Set MVP matrix m_prog->setUniformValue(3, p_matrix); m_prog->setUniformValue(4,v_matrix); m_prog->setUniformValue(5,m_matrix); m_prog->setUniformValue(17,m_matrix.normalMatrix()); //color for they sphere m_prog->setUniformValue(6,QVector4D(0.9,0.8,0.7,1.0)); //draw sphere sphere->drawElements(); //third gimbal m_matrix.setToIdentity(); m_matrix.rotate(m_RotA,1.0,0.0,0.0); m_matrix.rotate(m_RotB,0.0,1.0,0.0); m_matrix.rotate(m_RotC,1.0,0.0,0.0); m_matrix.scale(0.9,0.9,0.9); m_matrix.scale(0.85,0.85,0.85); m_matrix.scale(0.849,0.849,0.849); // Set MVP matrix m_prog->setUniformValue(3,p_matrix); m_prog->setUniformValue(4,v_matrix); m_prog->setUniformValue(5,m_matrix); m_prog->setUniformValue(20,m_matrix.normalMatrix()); //color for one Ring m_prog->setUniformValue(6,QVector4D(0.0, 0.0, 1.0,1.0)); //draw model gimbal->drawElements(); } if(activateAnimation){ if(cameraOnGimbal){ v_matrix.translate(v_matrix.inverted()*QVector3D(0.0,0.0,0.0)); } //First gimbal m_matrix.scale(0.9,0.9,0.9); GLfloat rot_first_gimbal=timer.msecsSinceReference()/-12; m_matrix.rotate(rot_first_gimbal,1.0,0.0,0.0); // Set MVP matrix m_prog->setUniformValue(3,p_matrix); m_prog->setUniformValue(4,v_matrix); m_prog->setUniformValue(5,m_matrix); m_prog->setUniformValue(20,m_matrix.normalMatrix()); //color for one Ring m_prog->setUniformValue(6,QVector4D(1.0,0.0,0.0,1.0)); //draw model gimbal->drawElements(); //Second gimbal m_matrix.scale(0.85,0.85,0.85); GLfloat rot_second_gimbal=timer.msecsSinceReference()/10; m_matrix.rotate(rot_second_gimbal,0.0,1.0,0.0); // Set MVP matrix m_prog->setUniformValue(3, p_matrix); m_prog->setUniformValue(4,v_matrix); m_prog->setUniformValue(5,m_matrix); m_prog->setUniformValue(20,m_matrix.normalMatrix()); //color for one Ring m_prog->setUniformValue(6,QVector4D(0.0,1.0,0.0,1.0)); //draw model gimbal->drawElements(); //Ball //Variable for the ball rotation GLfloat rot_bal=timer.msecsSinceReference(); m_matrix.setToIdentity(); m_matrix.rotate(rot_first_gimbal,1.0,0.0,0.0); m_matrix.rotate(rot_second_gimbal,0.0,1.0,0.0); m_matrix.rotate(rot_bal/10,0.0,0.0,1.0); m_matrix.scale(0.05,0.05,0.05); m_matrix.translate(0.0,14.9,1.9); // Set MVP matrix m_prog->setUniformValue(3, p_matrix); m_prog->setUniformValue(4,v_matrix); m_prog->setUniformValue(5,m_matrix); m_prog->setUniformValue(20,m_matrix.normalMatrix()); //color for they sphere m_prog->setUniformValue(6,QVector4D(0.9,0.8,0.7,1.0)); //draw sphere sphere->drawElements(); //third gimbal m_matrix.setToIdentity(); GLfloat rot_third_gimbal=timer.msecsSinceReference(); m_matrix.rotate(rot_first_gimbal,1.0,0.0,0.0); m_matrix.rotate(rot_second_gimbal,0.0,1.0,0.0); m_matrix.rotate(rot_third_gimbal/5,1.0,0.0,0.0); if(cameraOnGimbal){ v_matrix.rotate(-rot_third_gimbal/5,1.0,0.0,0.0); v_matrix.rotate(-rot_second_gimbal,0.0,1.0,0.0); v_matrix.rotate(-rot_first_gimbal,1.0,0.0,0.0); } m_matrix.scale(0.9,0.9,0.9); m_matrix.scale(0.85,0.85,0.85); m_matrix.scale(0.849,0.849,0.849); // Set MVP matrix m_prog->setUniformValue(3, p_matrix); m_prog->setUniformValue(4,v_matrix); m_prog->setUniformValue(5,m_matrix); m_prog->setUniformValue(20,m_matrix.normalMatrix()); //color for one Ring m_prog->setUniformValue(6,QVector4D(0.0, 0.0, 1.0,1.0)); //draw model gimbal->drawElements(); } //Draw Skybox skybox->draw(p_matrix,v_matrix); //Request next frame to be drawn update(); } void MyGLWidget::resizeGL(int w, int h) { glViewport(0, 0, w, h); } void MyGLWidget::setFOV(int value){ this->m_FOV = value; emit vCFOV(value); } void MyGLWidget::setAngle(int value){ this->m_Angle=value; emit vCAngle(value); }; void MyGLWidget::setProjectionMode(bool value){ this->m_ortho=value; emit vCProjectionMode(value); } void MyGLWidget::setNear(double value){ this->m_Near=value; emit vCNear(value); } void MyGLWidget::setFar(double value){ this->m_Far=value; emit vCFar(value); } void MyGLWidget::setRotationA(int value){ this->m_RotA= value; emit vCRotationA(value); } void MyGLWidget::setRotationB(int value){ this->m_RotB=value; emit vCRotationB(value); } void MyGLWidget::setRotationC(int value){ this->m_RotC=value; emit vCRotationC(value); } void MyGLWidget::diffNearFar(double value){ if(m_Far-m_Near<2.0f){ emit signalDiffNearFar(value); } } void MyGLWidget::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Down || event->key() == Qt::Key_S) { std::cout<<"x: "<<m_CameraPos.x()<<", y: "<<m_CameraPos.y()<<std::endl; m_CameraPos.setX(m_CameraPos.x()-0.2f); m_CameraPos.setY(m_CameraPos.y()-0.2f); std::cout<<"x: "<<m_CameraPos.x()<<", y: "<<m_CameraPos.y()<<std::endl; } else if(event->key() == Qt::Key_Up || event->key() == Qt::Key_W) { std::cout<<"x: "<<m_CameraPos.x()<<", y: "<<m_CameraPos.y()<<std::endl; m_CameraPos.setX(m_CameraPos.x()+0.2f); m_CameraPos.setY(m_CameraPos.y()+0.2f); std::cout<<"x: "<<m_CameraPos.x()<<", y: "<<m_CameraPos.y()<<std::endl; } else { QOpenGLWidget::keyPressEvent(event); } } void MyGLWidget::setAnimation(bool value){ activateAnimation=value; if(value) qDebug()<<"Animation activate!!"; else qDebug()<<"Animation desctivate!!"; emit vCAnimation(value); } void MyGLWidget::setCameraOnGimbal(bool value){ cameraOnGimbal=value; if(value) qDebug()<<"Camera on gimbal activate!!"; else qDebug()<<"Camera on gimbal desctivate!!"; emit vCCOG(value); }
30.702
133
0.59742
[ "object", "model" ]
80724c07c9638093a8a243f8d8192e8a3ae8a709
1,101
cpp
C++
leetcode/200-number-of-islands.cpp
vsmolyakov/competitive_programming
ec7891eee86b5d051bcb4d9eff056d4cafab668e
[ "MIT" ]
1
2020-04-21T05:12:34.000Z
2020-04-21T05:12:34.000Z
leetcode/200-number-of-islands.cpp
rossanag/competitive_programming
5d1bd3d00f2fa8589bdbeee07abeacceb693e930
[ "MIT" ]
null
null
null
leetcode/200-number-of-islands.cpp
rossanag/competitive_programming
5d1bd3d00f2fa8589bdbeee07abeacceb693e930
[ "MIT" ]
2
2019-08-13T21:27:05.000Z
2019-12-30T02:32:09.000Z
class Solution { public: int numIslands(vector<vector<char>>& grid) { result = 0; if (grid.size() == 0 || grid[0].size() == 0) {return 0;} num_rows = grid.size(); num_cols = grid[0].size(); for (int i = 0; i < num_rows; ++i) { for (int j = 0; j < num_cols; ++j) { if (grid[i][j] == '1') { result++; DFS(grid, i, j); } } } return result; } private: int result; int num_rows, num_cols; void DFS(vector<vector<char>>& grid, int i, int j) { grid[i][j] = '0'; if (i > 0 && grid[i-1][j] == '1') { DFS(grid, i-1, j); } if (i < num_rows - 1 && grid[i+1][j] == '1') { DFS(grid, i+1, j); } if (j > 0 && grid[i][j-1] == '1') { DFS(grid, i, j-1); } if (j < num_cols - 1 && grid[i][j+1] == '1') { DFS(grid, i, j+1); } } };
22.02
64
0.338783
[ "vector" ]
807461977912c98d7e2c5b629eca2444fc9edf9e
422
hpp
C++
include/State.hpp
naufaladrna08/flappy-bird-cpp
52bb69d53270eba72716c1a0a34ef9d3a90c0ba8
[ "MIT" ]
null
null
null
include/State.hpp
naufaladrna08/flappy-bird-cpp
52bb69d53270eba72716c1a0a34ef9d3a90c0ba8
[ "MIT" ]
null
null
null
include/State.hpp
naufaladrna08/flappy-bird-cpp
52bb69d53270eba72716c1a0a34ef9d3a90c0ba8
[ "MIT" ]
null
null
null
#ifndef __STATE_H__ #define __STATE_H__ #include <iostream> #include <SFML/Graphics.hpp> class State { public: State(sf::RenderWindow* window); ~State(); virtual void Update(const float dt) = 0; virtual void UpdateInput(sf::Event e) = 0; virtual void Render(sf::RenderTarget* target = nullptr) = 0; virtual void Init() = 0; private: sf::RenderWindow* m_window; }; #endif // __STATE_H__
20.095238
64
0.672986
[ "render" ]
80757eea17d0df34573091fe5092d7391d8d71f4
3,635
cc
C++
chrome/browser/safe_browsing/srt_global_error_win.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2015-08-13T21:04:58.000Z
2015-08-13T21:04:58.000Z
chrome/browser/safe_browsing/srt_global_error_win.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/safe_browsing/srt_global_error_win.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-03-27T11:15:39.000Z
2016-08-17T14:19:56.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/safe_browsing/srt_global_error_win.h" #include "base/callback.h" #include "base/metrics/histogram.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/global_error/global_error_service.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/google_chrome_strings.h" #include "ui/base/l10n/l10n_util.h" namespace { // The download link of the Software Removal Tool. // TODO(mad): Should we only have the bubble show up on official Chrome build? const char kSRTDownloadURL[] = "https://www.google.com/chrome/srt/"; // Enum values for the SRTPrompt histogram. Don't change order, always add // to the end, before SRT_PROMPT_MAX, of course. enum SRTPromptHistogramValue { SRT_PROMPT_SHOWN = 0, SRT_PROMPT_ACCEPTED = 1, SRT_PROMPT_DENIED = 2, SRT_PROMPT_MAX, }; void RecordSRTPromptHistogram(SRTPromptHistogramValue value) { UMA_HISTOGRAM_ENUMERATION( "SoftwareReporter.PromptUsage", value, SRT_PROMPT_MAX); } } // namespace // SRTGlobalError ------------------------------------------------------------ SRTGlobalError::SRTGlobalError(GlobalErrorService* global_error_service) : global_error_service_(global_error_service) { DCHECK(global_error_service_); } SRTGlobalError::~SRTGlobalError() { } bool SRTGlobalError::HasMenuItem() { return true; } int SRTGlobalError::MenuItemCommandID() { return IDC_SHOW_SRT_BUBBLE; } base::string16 SRTGlobalError::MenuItemLabel() { return l10n_util::GetStringUTF16(IDS_SRT_MENU_ITEM); } void SRTGlobalError::ExecuteMenuItem(Browser* browser) { // The menu item should never get executed while the bubble is shown, unless // we eventually change it to NOT close on deactivate. DCHECK(ShouldCloseOnDeactivate()); DCHECK(GetBubbleView() == NULL); ShowBubbleView(browser); } void SRTGlobalError::ShowBubbleView(Browser* browser) { RecordSRTPromptHistogram(SRT_PROMPT_SHOWN); GlobalErrorWithStandardBubble::ShowBubbleView(browser); } base::string16 SRTGlobalError::GetBubbleViewTitle() { return l10n_util::GetStringUTF16(IDS_SRT_BUBBLE_TITLE); } std::vector<base::string16> SRTGlobalError::GetBubbleViewMessages() { std::vector<base::string16> messages; messages.push_back(l10n_util::GetStringUTF16(IDS_SRT_BUBBLE_TEXT)); return messages; } base::string16 SRTGlobalError::GetBubbleViewAcceptButtonLabel() { return l10n_util::GetStringUTF16(IDS_SRT_BUBBLE_DOWNLOAD_BUTTON_TEXT); } base::string16 SRTGlobalError::GetBubbleViewCancelButtonLabel() { return l10n_util::GetStringUTF16(IDS_NO_THANKS); } void SRTGlobalError::OnBubbleViewDidClose(Browser* browser) { } void SRTGlobalError::BubbleViewAcceptButtonPressed(Browser* browser) { RecordSRTPromptHistogram(SRT_PROMPT_ACCEPTED); browser->OpenURL(content::OpenURLParams(GURL(kSRTDownloadURL), content::Referrer(), NEW_FOREGROUND_TAB, ui::PAGE_TRANSITION_LINK, false)); DismissGlobalError(); } void SRTGlobalError::BubbleViewCancelButtonPressed(Browser* browser) { RecordSRTPromptHistogram(SRT_PROMPT_DENIED); DismissGlobalError(); } bool SRTGlobalError::ShouldCloseOnDeactivate() const { return false; } void SRTGlobalError::DismissGlobalError() { global_error_service_->RemoveGlobalError(this); delete this; }
30.805085
78
0.739202
[ "vector" ]
807efafd508a42e3f5bf885479b276e2ac87ac00
11,752
cc
C++
scf.cc
recoli/MyQC
ab9170930064b742470a6da3327adb779337f41c
[ "BSD-3-Clause" ]
6
2016-10-20T16:52:27.000Z
2021-09-29T12:24:42.000Z
scf.cc
recoli/MyQC
ab9170930064b742470a6da3327adb779337f41c
[ "BSD-3-Clause" ]
null
null
null
scf.cc
recoli/MyQC
ab9170930064b742470a6da3327adb779337f41c
[ "BSD-3-Clause" ]
1
2021-09-29T12:24:43.000Z
2021-09-29T12:24:43.000Z
/***************************************************************************** This file is part of the XLQC program. Copyright (C) 2015 Xin Li <lixin.reco@gmail.com> Filename: scf.cc License: BSD 3-Clause License This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright holder or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. *****************************************************************************/ #include <cmath> #include <cstdio> #include <cstdlib> #include <string> #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include "typedef.h" #include "basis.h" #include "int_lib/cints.h" //=============================================== // matrix inner product //=============================================== double mat_inn_prod(int DIM, double **A, double **B) { double inn_prod = 0.0; int row, col; for (row = 0; row < DIM; ++ row) { for (col = 0; col < DIM; ++ col) { inn_prod += A[row][col] * B[row][col]; } } return inn_prod; } //=============================================== // GSL eigen solver for real symmetric matrix //=============================================== void my_eigen_symmv(gsl_matrix* data, int DIM, gsl_vector* eval, gsl_matrix* evec) { if ( DIM <= 0 || data[0].size1 != DIM || data[0].size2 != DIM ) { fprintf(stderr, "Error: incorrect DIM in my_eigen_symmv!\n"); exit(1); } // make a copy of 'data': 'data_cp' // NOTE: 'data_cp' will be destroyed after gsl_eigen_symmv gsl_matrix *data_cp = gsl_matrix_alloc(DIM, DIM); gsl_matrix_memcpy(data_cp, data); // diagonalize real symmetric matrix data_cp gsl_eigen_symmv_workspace *w = gsl_eigen_symmv_alloc (DIM); gsl_eigen_symmv(data_cp, eval, evec, w); gsl_eigen_symmv_free(w); gsl_eigen_symmv_sort(eval, evec, GSL_EIGEN_SORT_VAL_ASC); gsl_matrix_free(data_cp); } //=============================== // print gsl matrix //=============================== void my_print_matrix(gsl_matrix* A) { for (int row = 0; row < A->size1; ++ row) { for (int col = 0; col < A->size2; ++ col) { printf("%12.7f", gsl_matrix_get(A, row, col)); } printf("\n"); } } //=============================== // print gsl vector //=============================== void my_print_vector(gsl_vector* x) { for (int row = 0; row < x->size; ++ row) { printf("%12.7f\n", gsl_vector_get(x, row)); } } //=============================== // get core Hamiltonian //=============================== void sum_H_core(int nbasis, gsl_matrix *H_core, gsl_matrix *T, gsl_matrix *V) { for (int row = 0; row < nbasis; ++ row) { for (int col = 0; col < nbasis; ++ col) { gsl_matrix_set(H_core, row, col, gsl_matrix_get(T, row, col) + gsl_matrix_get(V, row, col)); } } } //=============================== // diagonalize overlap matrix //=============================== void diag_overlap(int nbasis, gsl_matrix *S, gsl_matrix *S_invsqrt) { // diagonalization of S // eig_S: eigenvalues // LS: eigenvectors gsl_vector *eig_S = gsl_vector_alloc(nbasis); gsl_matrix *LS = gsl_matrix_alloc(nbasis, nbasis); my_eigen_symmv(S, nbasis, eig_S, LS); // AS: diagonal matrix containing eigenvalues // AS_invsqrt: AS^-1/2 gsl_matrix *AS_invsqrt = gsl_matrix_alloc(nbasis, nbasis); gsl_matrix_set_zero(AS_invsqrt); for (int row = 0; row < nbasis; ++ row) { gsl_matrix_set(AS_invsqrt, row, row, 1.0 / sqrt(gsl_vector_get(eig_S, row))); } // S^-1/2 = LS * AS^-1/2 * LS(T) gsl_matrix *prod = gsl_matrix_alloc(nbasis, nbasis); gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, LS, AS_invsqrt, 0.0, prod); gsl_blas_dgemm (CblasNoTrans, CblasTrans, 1.0, prod, LS, 0.0, S_invsqrt); gsl_vector_free (eig_S); gsl_matrix_free (LS); gsl_matrix_free (AS_invsqrt); gsl_matrix_free (prod); } //=============================== // from Fock matrix to MO coeffcients //=============================== void Fock_to_Coef(int nbasis, gsl_matrix *Fock, gsl_matrix *S_invsqrt, gsl_matrix *Coef, gsl_vector *emo) { // F' = S^-1/2 * F * S^-1/2 gsl_matrix *Fock_p = gsl_matrix_alloc(nbasis, nbasis); gsl_matrix *prod = gsl_matrix_alloc(nbasis, nbasis); gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, S_invsqrt, Fock, 0.0, prod); gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, prod, S_invsqrt, 0.0, Fock_p); // diagonalization of Fock_p // emo: eigenvalues // Coef_p: eigenvectors gsl_matrix *Coef_p = gsl_matrix_alloc(nbasis, nbasis); my_eigen_symmv(Fock_p, nbasis, emo, Coef_p); // C = S^-1/2 * C' gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, S_invsqrt, Coef_p, 0.0, Coef); gsl_matrix_free (prod); gsl_matrix_free (Fock_p); gsl_matrix_free (Coef_p); } //=============================== // from MO coeffcients to density matrix //=============================== void Coef_to_Dens(int nbasis, int n_occ, gsl_matrix *Coef, gsl_matrix *D) { for (int row=0; row < nbasis; ++ row) { for (int col=0; col < nbasis; ++ col) { double val = 0.0; for (int m = 0; m < n_occ; ++ m) { val += gsl_matrix_get(Coef, row, m) * gsl_matrix_get(Coef, col, m); } gsl_matrix_set(D, row, col, 2.0 * val); } } } //=============================== // compute the initial SCF energy //=============================== double get_elec_ene(int nbasis, gsl_matrix *D, gsl_matrix *H_core, gsl_matrix *Fock) { double ene_elec = 0.0; for (int row = 0; row < nbasis; ++ row) { for (int col = 0; col < nbasis; ++ col) { ene_elec += 0.5 * gsl_matrix_get(D, row, col) * (gsl_matrix_get(H_core, row, col) + gsl_matrix_get(Fock, row, col)); } } return ene_elec; } //=============================== // form Fock matrix //=============================== void form_Fock(int nbasis, gsl_matrix *H_core, gsl_matrix *J, gsl_matrix *K, gsl_matrix *Fock) { for (int mu = 0; mu < nbasis; ++ mu) { for (int nu = 0; nu < nbasis; ++ nu) { gsl_matrix_set(Fock, mu, nu, gsl_matrix_get(H_core, mu, nu) + gsl_matrix_get(J, mu, nu) - 0.5 * gsl_matrix_get(K, mu, nu)); } } } // Generalized Wolfsberg-Helmholtz initial guess void init_guess_GWH(Basis *p_basis, gsl_matrix *H_core, gsl_matrix *S, gsl_matrix *Fock) { for (int mu = 0; mu < p_basis->num; ++ mu) { double Hmm = gsl_matrix_get(H_core, mu, mu); for (int nu = 0; nu < p_basis->num; ++ nu) { double Smn = gsl_matrix_get(S, mu, nu); double Hnn = gsl_matrix_get(H_core, nu, nu); double Fmn = Smn * (Hmm + Hnn) / 2.0; gsl_matrix_set(Fock, mu, nu, Fmn); } } } // DIIS void update_Fock_DIIS(int *p_diis_dim, int *p_diis_index, double *p_delta_DIIS, gsl_matrix *Fock, gsl_matrix *D_prev, gsl_matrix *S, Basis *p_basis, double ***diis_err, double ***diis_Fock) { int diis_dim = *p_diis_dim; int diis_index = *p_diis_index; double delta_DIIS; // dimension of DIIS, e.g. number of error matrices if (diis_dim < MAX_DIIS_DIM) { diis_dim = diis_index + 1; } // calculate FDS and SDF, using D_prev, Fock and S gsl_matrix *prod = gsl_matrix_alloc(p_basis->num, p_basis->num); gsl_matrix *FDS = gsl_matrix_alloc(p_basis->num, p_basis->num); gsl_matrix *SDF = gsl_matrix_alloc(p_basis->num, p_basis->num); gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, Fock, D_prev, 0.0, prod); gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, prod, S, 0.0, FDS); gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, S, D_prev, 0.0, prod); gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, prod, Fock, 0.0, SDF); gsl_matrix_free(prod); // new error matrix: e = FDS - SDF delta_DIIS = 0.0; for (int row = 0; row < p_basis->num; ++ row) { for (int col=0; col < p_basis->num; ++ col) { double err = gsl_matrix_get(FDS, row, col) - gsl_matrix_get(SDF, row, col); diis_err[diis_index][row][col] = err; diis_Fock[diis_index][row][col] = gsl_matrix_get(Fock, row, col); delta_DIIS += err * err; } } delta_DIIS = sqrt(delta_DIIS); gsl_matrix_free(FDS); gsl_matrix_free(SDF); // apply DIIS if there are two or more error matrices if (diis_dim > 1) { // construct B matrix and bb vector; B .dot. cc = bb gsl_matrix *B = gsl_matrix_alloc(diis_dim + 1, diis_dim + 1); gsl_vector *bb = gsl_vector_alloc(diis_dim + 1); for (int row = 0; row < diis_dim; ++ row) { for (int col = 0; col < diis_dim; ++ col) { gsl_matrix_set (B, row, col, mat_inn_prod(p_basis->num, diis_err[row], diis_err[col])); } } for (int idiis = 0; idiis < diis_dim; ++ idiis) { gsl_matrix_set (B, diis_dim, idiis, -1.0); gsl_matrix_set (B, idiis, diis_dim, -1.0); gsl_vector_set (bb, idiis, 0.0); } gsl_matrix_set (B, diis_dim, diis_dim, 0.0); gsl_vector_set (bb, diis_dim, -1.0); // solve matrix equation; B .dot. cc = bb int ss; gsl_vector *cc = gsl_vector_alloc (diis_dim + 1); gsl_permutation *pp = gsl_permutation_alloc (diis_dim + 1); gsl_linalg_LU_decomp (B, pp, &ss); gsl_linalg_LU_solve (B, pp, bb, cc); gsl_permutation_free (pp); // update Fock matrix gsl_matrix_set_zero (Fock); for (int idiis = 0; idiis < diis_dim; ++ idiis) { double ci = gsl_vector_get (cc, idiis); for (int row = 0; row < p_basis->num; ++ row) { for (int col = 0; col < p_basis->num; ++ col) { double Fab = gsl_matrix_get (Fock, row, col); Fab += ci * diis_Fock[idiis][row][col]; gsl_matrix_set (Fock, row, col, Fab); } } } // free matrix B and vectors bb, cc gsl_matrix_free(B); gsl_vector_free(bb); gsl_vector_free(cc); } // update DIIS index, e.g. which error matrix to be updated ++ diis_index; if (MAX_DIIS_DIM == diis_index) { diis_index = 0; } *p_diis_dim = diis_dim; *p_diis_index = diis_index; *p_delta_DIIS = delta_DIIS; }
32.464088
94
0.543057
[ "vector" ]
8085c24fcf0d9f3a191bcdca47ba6bdc2abf17db
4,591
cc
C++
homeworks/ErrorEstimatesForTraces/templates/teelaplrobinassembly.cc
padomu/NPDECODES
d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e
[ "MIT" ]
15
2019-04-29T11:28:56.000Z
2022-03-22T05:10:58.000Z
homeworks/ErrorEstimatesForTraces/templates/teelaplrobinassembly.cc
padomu/NPDECODES
d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e
[ "MIT" ]
12
2020-02-29T15:05:58.000Z
2022-02-21T13:51:07.000Z
homeworks/ErrorEstimatesForTraces/templates/teelaplrobinassembly.cc
padomu/NPDECODES
d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e
[ "MIT" ]
26
2020-01-09T15:59:23.000Z
2022-03-24T16:27:33.000Z
/** * @file * @brief NPDE homework ErrorEstimatesForTraces * @author Erick Schulz * @date 25/03/2019 * @copyright Developed at ETH Zurich */ #include "teelaplrobinassembly.h" #include <cassert> namespace ErrorEstimatesForTraces { Eigen::VectorXd solveBVP( std::shared_ptr<lf::uscalfe::FeSpaceLagrangeO1<double>> &fe_space) { // I : Creating coefficients as Lehrfem++ mesh functions // Coefficients used in the class template // ReactionDiffusionElementMatrixProvider<SCALAR,DIFF_COEFF,REACTION_COEFF> auto alpha = lf::mesh::utils::MeshFunctionGlobal( [](coord_t x) -> double { return 1.0; }); auto gamma = lf::mesh::utils::MeshFunctionGlobal( [](coord_t x) -> double { return 0.0; }); // Coefficients used in the class template // MassEdgeMatrixProvider< SCALAR, COEFF, EDGESELECTOR > auto eta = lf::mesh::utils::MeshFunctionGlobal( [](coord_t x) -> double { return 1.0; }); // Right-hand side source function f auto f = lf::mesh::utils::MeshFunctionGlobal( [](coord_t x) -> double { return std::cos(x.norm()); }); // pointer to current mesh std::shared_ptr<const lf::mesh::Mesh> mesh_p = fe_space->Mesh(); // Obtain local->global index mapping for current finite element space const lf::assemble::DofHandler &dofh{fe_space->LocGlobMap()}; // II: Instantiating finite element matrix for the Robin bilinear form // Dimension of finite element space const lf::uscalfe::size_type N_dofs(dofh.NumDofs()); // Matrix in triplet format holding Galerkin matrix, zero initially. lf::assemble::COOMatrix<double> A(N_dofs, N_dofs); // Right hand side vector Eigen::Matrix<double, Eigen::Dynamic, 1> phi(N_dofs); phi.setZero(); // has to be zero initially // III : Computing element and mass (volume integrals) matrix // Initialize object taking care of local mass (volume) computations. lf::uscalfe::ReactionDiffusionElementMatrixProvider<double, decltype(alpha), decltype(gamma)> elmat_builder(fe_space, alpha, gamma); // Invoke assembly on cells (co-dimension = 0 as first argument) // Information about the mesh and the local-to-global map is passed through // a Dofhandler object, argument 'dofh'. This function call adds triplets to // the internal COO-format representation of the sparse matrix A. lf::assemble::AssembleMatrixLocally(0, dofh, dofh, elmat_builder, A); // IV : Computing contribution from the boundary bilinear form associated to // the Robin boundary conditions. // Obtain an array of boolean flags for the edges of the mesh, 'true' // indicates that the edge lies on the boundary auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(mesh_p, 1)}; // Creating a predicate that will guarantee that the computations are carried // only on the edges of the mesh using the boundary flags auto edges_predicate = [&bd_flags](const lf::mesh::Entity &edge) -> bool { return bd_flags(edge); }; lf::uscalfe::MassEdgeMatrixProvider<double, decltype(eta), decltype(edges_predicate)> edgemat_builder(fe_space, eta, edges_predicate); // Invoke assembly on edges by specifying co-dimension = 1 lf::assemble::AssembleMatrixLocally(1, dofh, dofh, edgemat_builder, A); // V: Computing right-hand side vector // Assemble volume part of right-hand side vector depending on the source // function f. Initialize object taking care of local computations on all // cells. lf::uscalfe::ScalarLoadElementVectorProvider<double, decltype(f)> elvec_builder(fe_space, f); // Invoke assembly on cells (codim == 0) AssembleVectorLocally(0, dofh, elvec_builder, phi); // Assembly completed: Convert COO matrix A into CRS format using Eigen's // internal conversion routines. Eigen::SparseMatrix<double> A_crs = A.makeSparse(); // Solve linear system using Eigen's sparse direct elimination Eigen::SparseLU<Eigen::SparseMatrix<double>> solver; solver.compute(A_crs); LF_VERIFY_MSG(solver.info() == Eigen::Success, "LU decomposition failed"); Eigen::VectorXd sol_vec = solver.solve(phi); LF_VERIFY_MSG(solver.info() == Eigen::Success, "Solving LSE failed"); return sol_vec; } /* SAM_LISTING_BEGIN_9 */ double bdFunctionalEval( std::shared_ptr<lf::uscalfe::FeSpaceLagrangeO1<double>> &fe_space, Eigen::VectorXd &coeff_vec) { double bd_functional_val = 0; //==================== // Your code goes here //==================== return bd_functional_val; } /* SAM_LISTING_END_9 */ } // namespace ErrorEstimatesForTraces
41.736364
79
0.705729
[ "mesh", "object", "vector" ]
808aeafe0465e83e445676bfbb279f91c67a926c
32,014
cpp
C++
frameworks/bridge/js_frontend/engine/v8/v8_animation_bridge.cpp
openharmony-gitee-mirror/ace_ace_engine
78013960cdce81348d1910e466a3292605442a5e
[ "Apache-2.0" ]
null
null
null
frameworks/bridge/js_frontend/engine/v8/v8_animation_bridge.cpp
openharmony-gitee-mirror/ace_ace_engine
78013960cdce81348d1910e466a3292605442a5e
[ "Apache-2.0" ]
null
null
null
frameworks/bridge/js_frontend/engine/v8/v8_animation_bridge.cpp
openharmony-gitee-mirror/ace_ace_engine
78013960cdce81348d1910e466a3292605442a5e
[ "Apache-2.0" ]
1
2021-09-13T11:17:50.000Z
2021-09-13T11:17:50.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "frameworks/bridge/js_frontend/engine/v8/v8_animation_bridge.h" #include "base/log/event_report.h" #include "base/log/log.h" #include "base/memory/referenced.h" #include "base/utils/string_utils.h" #include "core/animation/keyframe_animation.h" #include "core/components/tween/tween_component.h" #include "frameworks/bridge/common/utils/utils.h" #include "frameworks/bridge/js_frontend/engine/v8/v8_engine.h" #include "frameworks/bridge/js_frontend/engine/v8/v8_utils.h" #include "frameworks/bridge/js_frontend/js_ace_page.h" namespace OHOS::Ace::Framework { namespace { RefPtr<JsAcePage> GetPageById(v8::Isolate* isolate, int32_t pageId) { LOGD("Enter GetPageById"); if (isolate == nullptr) { LOGE("Isolate is null."); return nullptr; } auto delegate = static_cast<RefPtr<FrontendDelegate>*>(isolate->GetData(V8EngineInstance::FRONTEND_DELEGATE)); return (*delegate)->GetPage(pageId); } inline NodeId GetCurrentNodeId(const v8::Local<v8::Context>& ctx, v8::Local<v8::Object> value) { v8::Isolate* isolate = ctx->GetIsolate(); v8::HandleScope handleScope(isolate); NodeId id = value->Get(ctx, v8::String::NewFromUtf8(isolate, "__nodeId").ToLocalChecked()) .ToLocalChecked() ->Int32Value(ctx) .ToChecked(); return id < 0 ? 0 : id; } inline int32_t GetCurrentPageId(const v8::Local<v8::Context>& ctx, v8::Local<v8::Object> value) { v8::Isolate* isolate = ctx->GetIsolate(); v8::HandleScope handleScope(isolate); int32_t id = value->Get(ctx, v8::String::NewFromUtf8(isolate, "__pageId").ToLocalChecked()) .ToLocalChecked() ->Int32Value(ctx) .ToChecked(); return id < 0 ? 0 : id; } void HandleJsAnimationContext( const v8::Local<v8::Context>& ctx, int32_t pageId, int32_t nodeId, AnimationOperation operation) { v8::Isolate* isolate = ctx->GetIsolate(); auto page = GetPageById(isolate, pageId); if (!page) { LOGE("no page found for nodeId: %{public}d", nodeId); EventReport::SendAnimationException(AnimationExcepType::ANIMATION_PAGE_ERR); return; } auto task = AceType::MakeRefPtr<V8AnimationBridgeTaskOperation>(operation); page->PushCommand(AceType::MakeRefPtr<JsCommandAnimation>(nodeId, task)); if (page->CheckPageCreated()) { auto delegate = static_cast<RefPtr<FrontendDelegate>*>(isolate->GetData(V8EngineInstance::FRONTEND_DELEGATE)); (*delegate)->TriggerPageUpdate(page->GetPageId()); } } const std::vector<std::tuple<std::string, v8::FunctionCallback, v8::FunctionCallback>> V8_ANIMATION_FUNCS = { { "playState", V8AnimationBridgeUtils::JsAnimationPlayStateGet, V8AnimationBridgeUtils::JsAnimationPlayStateSet }, { "startTime", V8AnimationBridgeUtils::JsAnimationStartTimeGet, V8AnimationBridgeUtils::JsAnimationStartTimeSet }, { "pending", V8AnimationBridgeUtils::JsAnimationPendingGet, V8AnimationBridgeUtils::JsAnimationPendingSet } }; void CallAnimationStartJs(const WeakPtr<V8AnimationBridge>& bridgeWeak, v8::Isolate* isolate) { auto bridge = bridgeWeak.Upgrade(); if (!bridge) { LOGE("Call Animation Start Js Failed. animation bridge is null."); EventReport::SendAnimationException(AnimationExcepType::ANIMATION_BRIDGE_ERR); return; } v8::HandleScope handleScope(isolate); auto animatorObject = bridge->GetJsObject(); if (animatorObject.IsEmpty()) { LOGE("Animation Object is null"); return; } auto context = bridge->GetContext(); v8::Local<v8::Value> proto = animatorObject->Get(context, v8::String::NewFromUtf8(isolate, "onstart").ToLocalChecked()).ToLocalChecked(); if (!proto->IsFunction()) { LOGE("cannot find 'CallAnimationStartJs' function from animation object, maybe no callback at all."); return; } v8::TryCatch tryCatch(isolate); v8::Local<v8::Function> jsFunc = v8::Local<v8::Function>::Cast(proto); v8::Local<v8::Value> funcRes; v8::Local<v8::Object> global = context->Global(); bool succ = jsFunc->Call(context, global, 0, {}).ToLocal(&funcRes); if (!succ) { V8Utils::JsStdDumpErrorAce(isolate, &tryCatch, JsErrorType::ANIMATION_START_ERROR); return; } } void CallAnimationFinishJs(const WeakPtr<V8AnimationBridge>& bridgeWeak, v8::Isolate* isolate, const RefPtr<JsAcePage>& page) { auto bridge = bridgeWeak.Upgrade(); if (!bridge) { LOGE("Call Animation Finish Js Failed. animation bridge is null."); EventReport::SendAnimationException(AnimationExcepType::ANIMATION_BRIDGE_ERR); return; } v8::HandleScope handleScope(isolate); auto animationObject = bridge->GetJsObject(); if (animationObject.IsEmpty()) { LOGE("Animation Object is null"); return; } auto context = bridge->GetContext(); v8::Local<v8::Value> proto = animationObject->Get(context, v8::String::NewFromUtf8(isolate, "onfinish").ToLocalChecked()).ToLocalChecked(); if (!proto->IsFunction()) { LOGE("cannot find 'CallAnimationFinishJs' function from animation object, maybe no callback at all."); return; } v8::TryCatch tryCatch(isolate); v8::Local<v8::Function> jsFunc = v8::Local<v8::Function>::Cast(proto); v8::Local<v8::Value> funcRes; v8::Local<v8::Object> global = context->Global(); bool succ = jsFunc->Call(context, global, 0, {}).ToLocal(&funcRes); if (!succ) { V8Utils::JsStdDumpErrorAce(isolate, &tryCatch, JsErrorType::ANIMATION_FINISH_ERROR, 0, page); return; } } void CallAnimationCancelJs(const WeakPtr<V8AnimationBridge>& bridgeWeak, v8::Isolate* isolate, const RefPtr<JsAcePage>& page) { auto bridge = bridgeWeak.Upgrade(); if (!bridge) { LOGE("Call Animation Cancel Js Failed. animation bridge is null."); EventReport::SendAnimationException(AnimationExcepType::ANIMATION_BRIDGE_ERR); return; } v8::HandleScope handleScope(isolate); auto animationObject = bridge->GetJsObject(); if (animationObject.IsEmpty()) { LOGE("Animation Object is null"); return; } auto context = bridge->GetContext(); v8::Local<v8::Value> proto = animationObject->Get(context, v8::String::NewFromUtf8(isolate, "oncancel").ToLocalChecked()).ToLocalChecked(); if (!proto->IsFunction()) { LOGE("cannot find 'CallAnimationCancelJs' function from animation object, maybe no callback at all."); return; } LOGD("animation oncancel event call"); v8::TryCatch tryCatch(isolate); v8::Local<v8::Function> jsFunc = v8::Local<v8::Function>::Cast(proto); v8::Local<v8::Value> funcRes; v8::Local<v8::Object> global = context->Global(); bool succ = jsFunc->Call(context, global, 0, {}).ToLocal(&funcRes); if (!succ) { V8Utils::JsStdDumpErrorAce(isolate, &tryCatch, JsErrorType::ANIMATION_CANCEL_ERROR, 0, page); return; } } void CallAnimationRepeatJs(const WeakPtr<V8AnimationBridge>& bridgeWeak, v8::Isolate* isolate, const RefPtr<JsAcePage>& page) { auto bridge = bridgeWeak.Upgrade(); if (!bridge) { LOGE("Call Animation Repeat Js Failed. animation bridge is null."); EventReport::SendAnimationException(AnimationExcepType::ANIMATION_BRIDGE_ERR); return; } v8::HandleScope handleScope(isolate); auto animationObject = bridge->GetJsObject(); if (animationObject.IsEmpty()) { LOGE("Animation Object is null"); return; } auto context = bridge->GetContext(); v8::Local<v8::Value> proto = animationObject->Get(context, v8::String::NewFromUtf8(isolate, "onrepeat").ToLocalChecked()).ToLocalChecked(); if (!proto->IsFunction()) { LOGE("cannot find 'CallAnimationRepeatJs' function from animation object, maybe no callback at all."); return; } LOGD("animation onrepeat event call"); v8::TryCatch tryCatch(isolate); v8::Local<v8::Function> jsFunc = v8::Local<v8::Function>::Cast(proto); v8::Local<v8::Value> funcRes; v8::Local<v8::Object> global = context->Global(); bool succ = jsFunc->Call(context, global, 0, {}).ToLocal(&funcRes); if (!succ) { V8Utils::JsStdDumpErrorAce(isolate, &tryCatch, JsErrorType::ANIMATION_REPEAT_ERROR, 0, page); return; } } void JsUpdatePlayState(v8::Isolate* isolate, const WeakPtr<V8AnimationBridge>& bridgeWeak, const char* state) { auto bridge = bridgeWeak.Upgrade(); if (!bridge || (isolate == nullptr)) { LOGW("Set playState to Stop failed. bridge or isolate is null."); return; } v8::HandleScope handleScope(isolate); auto ctx = bridge->GetContext(); v8::Context::Scope contextScope(ctx); auto animationContext = bridge->GetJsObject(); animationContext ->Set(ctx, v8::String::NewFromUtf8(isolate, "__playState").ToLocalChecked(), v8::String::NewFromUtf8(isolate, state).ToLocalChecked()) .ToChecked(); } void AddListenerForEventCallback(const WeakPtr<V8AnimationBridge>& bridgeWeak, const RefPtr<Animator>& animator, v8::Isolate* isolate, const RefPtr<JsAcePage>& page) { animator->AddStopListener([isolate, bridgeWeak, page] { auto delegate = static_cast<RefPtr<FrontendDelegate>*>(isolate->GetData(V8EngineInstance::FRONTEND_DELEGATE)); auto jsTaskExecutor = (*delegate)->GetAnimationJsTask(); jsTaskExecutor.PostTask([bridgeWeak, isolate, page]() mutable { LOGI("call animation onfinish event"); CallAnimationFinishJs(bridgeWeak, isolate, page); }); }); animator->AddIdleListener([isolate, bridgeWeak, page] { auto delegate = static_cast<RefPtr<FrontendDelegate>*>(isolate->GetData(V8EngineInstance::FRONTEND_DELEGATE)); auto jsTaskExecutor = (*delegate)->GetAnimationJsTask(); jsTaskExecutor.PostTask([bridgeWeak, isolate, page]() mutable { LOGI("call animation oncancel event"); CallAnimationCancelJs(bridgeWeak, isolate, page); }); }); animator->AddRepeatListener([isolate, bridgeWeak, page] { auto delegate = static_cast<RefPtr<FrontendDelegate>*>(isolate->GetData(V8EngineInstance::FRONTEND_DELEGATE)); auto jsTaskExecutor = (*delegate)->GetAnimationJsTask(); jsTaskExecutor.PostTask([bridgeWeak, isolate, page]() mutable { LOGI("call animation onrepeat event"); CallAnimationRepeatJs(bridgeWeak, isolate, page); }); }); } } // namespace V8AnimationBridge::V8AnimationBridge( const v8::Local<v8::Context>& ctx, v8::Isolate* instance, v8::Local<v8::Object> animationContext, NodeId nodeId) : instance_(instance), nodeId_(nodeId) // ??? how to dup animationContext { animationObject_.Reset(instance_, animationContext); ctx_.Reset(instance_, ctx); } void V8AnimationBridgeUtils::JsAnimationStartTimeGet(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); v8::HandleScope handleScope(isolate); auto context = isolate->GetCurrentContext(); int32_t nodeId = GetCurrentNodeId(context, info.Holder()); int32_t pageId = GetCurrentPageId(context, info.Holder()); auto page = GetPageById(isolate, pageId); if (!page) { LOGE("JsAnimationStartTimeGet: no page found for nodeId: %{public}d", nodeId); EventReport::SendAnimationException(AnimationExcepType::ANIMATION_PAGE_ERR); return; } auto domDocument = page->GetDomDocument(); if (!domDocument) { LOGE("JsAnimationStartTimeGet failed, DomDocument is null."); return; } auto domNode = domDocument->GetDOMNodeById(nodeId); if (!domNode) { LOGE("JsAnimationStartTimeGet failed, DomNode is null."); return; } auto tweenComponent = domNode->GetTweenComponent(); if (tweenComponent) { auto option = tweenComponent->GetCustomTweenOption(); auto startTime = option.GetDelay(); info.Holder() ->Set(context, v8::String::NewFromUtf8(isolate, "__startTime").ToLocalChecked(), v8::Int32::New(isolate, startTime)) .ToChecked(); } v8::Local<v8::Value> value = info.Holder()->Get(context, v8::String::NewFromUtf8(isolate, "__startTime").ToLocalChecked()).ToLocalChecked(); info.GetReturnValue().Set(value); } void V8AnimationBridgeUtils::JsAnimationStartTimeSet(const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() != 1) { LOGE("Not valid Length for info. length: %{public}d", info.Length()); return; } v8::Local<v8::Value> value = info[0]; v8::Isolate* isolate = info.GetIsolate(); v8::String::Utf8Value jsStartTime(isolate, value); if (!(*jsStartTime)) { return; } std::string startTime(*jsStartTime); auto ctx = isolate->GetCurrentContext(); int32_t nodeId = GetCurrentNodeId(ctx, info.Holder()); int32_t pageId = GetCurrentPageId(ctx, info.Holder()); auto page = GetPageById(isolate, pageId); if (!page) { LOGE("JsAnimationStartTimeSet: no page found for nodeId: %{public}d", nodeId); EventReport::SendAnimationException(AnimationExcepType::ANIMATION_PAGE_ERR); return; } auto task = AceType::MakeRefPtr<V8AnimationBridgeTaskStartTime>(startTime); page->PushCommand(AceType::MakeRefPtr<JsCommandAnimation>(nodeId, task)); } void V8AnimationBridgeUtils::JsAnimationPendingGet(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); v8::HandleScope handleScope(isolate); auto context = isolate->GetCurrentContext(); int32_t nodeId = GetCurrentNodeId(context, info.Holder()); int32_t pageId = GetCurrentPageId(context, info.Holder()); auto page = GetPageById(isolate, pageId); if (!page) { LOGE("JsAnimationPendingGet: no page found for nodeId: %{public}d", nodeId); EventReport::SendAnimationException(AnimationExcepType::ANIMATION_PAGE_ERR); return; } auto domDocument = page->GetDomDocument(); if (!domDocument) { LOGE("JsAnimationPendingGet failed, DomDocument is null."); return; } auto domNode = domDocument->GetDOMNodeById(nodeId); if (!domNode) { LOGE("JsAnimationPendingGet failed, DomNode is null."); return; } auto tweenComponent = domNode->GetTweenComponent(); if (tweenComponent) { auto controller = tweenComponent->GetAnimator(); if (controller) { info.Holder() ->Set(context, v8::String::NewFromUtf8(isolate, "__pending").ToLocalChecked(), v8::Boolean::New(isolate, controller->IsPending())) .ToChecked(); } } v8::Local<v8::Value> value = info.Holder()->Get(context, v8::String::NewFromUtf8(isolate, "__pending").ToLocalChecked()).ToLocalChecked(); info.GetReturnValue().Set(value); } void V8AnimationBridgeUtils::JsAnimationPendingSet(const v8::FunctionCallbackInfo<v8::Value>& info) {} void V8AnimationBridgeUtils::JsAnimationPlayStateGet(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); v8::HandleScope handleScope(isolate); auto context = isolate->GetCurrentContext(); v8::Local<v8::Value> value = info.Holder()->Get(context, v8::String::NewFromUtf8(isolate, "__playState").ToLocalChecked()).ToLocalChecked(); info.GetReturnValue().Set(value); } void V8AnimationBridgeUtils::JsAnimationPlayStateSet(const v8::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() != 1) { LOGE("Not valid Length for info. length: %{public}d", info.Length()); return; } v8::Local<v8::Value> value = info[0]; v8::Isolate* isolate = info.GetIsolate(); v8::String::Utf8Value jsPlayState(isolate, value); if (!(*jsPlayState)) { return; } std::string playState(*jsPlayState); AnimationOperation operation = StringToAnimationOperation(playState); auto ctx = isolate->GetCurrentContext(); int32_t nodeId = GetCurrentNodeId(ctx, info.Holder()); int32_t pageId = GetCurrentPageId(ctx, info.Holder()); auto page = GetPageById(isolate, pageId); if (!page) { LOGE("no page found for nodeId: %{public}d", nodeId); EventReport::SendAnimationException(AnimationExcepType::ANIMATION_PAGE_ERR); return; } auto task = AceType::MakeRefPtr<V8AnimationBridgeTaskOperation>(operation); page->PushCommand(AceType::MakeRefPtr<JsCommandAnimation>(nodeId, task)); } void V8AnimationBridge::JsCreateAnimation(const RefPtr<JsAcePage>& page, const std::string& param) { std::vector<std::unordered_map<std::string, std::string>> animationFrames; std::unordered_map<std::string, double> animationDoubleOptions; std::unordered_map<std::string, std::string> animationStringOptions; int32_t iterations = 0; BaseAnimationBridgeUtils::JsParseAnimationFrames(param, animationFrames); BaseAnimationBridgeUtils::JsParseAnimationOptions( param, iterations, animationDoubleOptions, animationStringOptions); auto tweenOption = TweenOption(); auto iterEasing = animationStringOptions.find(DOM_ANIMATION_EASING); if (iterEasing != animationStringOptions.end()) { tweenOption.SetCurve(CreateCurve(iterEasing->second)); } std::vector<Dimension> transformOrigin = BaseAnimationBridgeUtils::HandleTransformOrigin(animationFrames); if (transformOrigin.size() == BaseAnimationBridgeUtils::TRANSFORM_ORIGIN_DEFAULT_SIZE) { tweenOption.SetTransformOrigin(transformOrigin.front(), transformOrigin.back()); } auto iterDuration = animationDoubleOptions.find(DOM_ANIMATION_DURATION_API); if (iterDuration != animationDoubleOptions.end()) { tweenOption.SetDuration(iterDuration->second); } auto iterFill = animationStringOptions.find(DOM_ANIMATION_FILL); if (iterFill != animationStringOptions.end()) { tweenOption.SetFillMode(StringToFillMode(iterFill->second)); } auto iterDirection = animationStringOptions.find(DOM_ANIMATION_DIRECTION_API); if (iterDirection != animationStringOptions.end()) { tweenOption.SetAnimationDirection(StringToAnimationDirection(iterDirection->second)); } auto iterDelay = animationDoubleOptions.find(DOM_ANIMATION_DELAY_API); if (iterDelay != animationDoubleOptions.end()) { tweenOption.SetDelay(iterDelay->second); } tweenOption.SetIteration(iterations); if (!page) { LOGE("JsCreateAnimation failed, Page is null."); return; } auto domDocument = page->GetDomDocument(); if (!domDocument) { LOGE("JsCreateAnimation failed, DomDocument is null."); return; } auto domNode = domDocument->GetDOMNodeById(nodeId_); if (!domNode) { LOGE("JsCreateAnimation failed, DomNode is null."); return; } domNode->ParseAnimationStyle(animationFrames); domNode->TweenOptionSetKeyframes(tweenOption); if (tweenOption.IsValid()) { domNode->SetCustomAnimationStyleUpdate(true); } RefPtr<Animator> animator = AceType::MakeRefPtr<Animator>(); auto tweenComponent = domNode->GetTweenComponent(); if (!tweenComponent) { tweenComponent = AceType::MakeRefPtr<TweenComponent>( BaseAnimationBridgeUtils::COMPONENT_PREFIX + std::to_string(nodeId_), domNode->GetTag()); domNode->SetTweenComponent(tweenComponent); } LOGD("parse animate parameters for nodeId: %d", nodeId_); tweenComponent->SetAnimator(animator); BaseAnimationBridgeUtils::SetTweenComponentParams(nullptr, animationFrames, tweenComponent, tweenOption); AddListenerForEventCallback(AceType::WeakClaim(this), animator, instance_, page); domNode->GenerateComponentNode(); page->PushDirtyNode(nodeId_); } void V8AnimationBridge::SetPlayStateCallbacksWithListenerId(RefPtr<Animator>& animator) { WeakPtr<V8AnimationBridge> bridgeWeak = AceType::WeakClaim(this); animator->RemoveStopListener(finishListenerId_); finishListenerId_ = animator->AddStopListener([bridgeWeak, instance = instance_] { auto delegate = static_cast<RefPtr<FrontendDelegate>*>(instance->GetData(V8EngineInstance::FRONTEND_DELEGATE)); auto jsTaskExecutor = (*delegate)->GetAnimationJsTask(); jsTaskExecutor.PostTask([instance, bridgeWeak]() mutable { JsUpdatePlayState(instance, bridgeWeak, DOM_ANIMATION_PLAY_STATE_FINISHED); }); }); animator->RemoveIdleListener(idleListenerId_); idleListenerId_ = animator->AddIdleListener([bridgeWeak, instance = instance_] { auto delegate = static_cast<RefPtr<FrontendDelegate>*>(instance->GetData(V8EngineInstance::FRONTEND_DELEGATE)); auto jsTaskExecutor = (*delegate)->GetAnimationJsTask(); jsTaskExecutor.PostTask([instance, bridgeWeak]() mutable { JsUpdatePlayState(instance, bridgeWeak, DOM_ANIMATION_PLAY_STATE_IDLE); }); }); } void V8AnimationBridge::SetPlayStateCallbacks(RefPtr<Animator>& animator) { if (!animator) { LOGE("Set PlayState callbacks failed. animator is null."); return; } WeakPtr<V8AnimationBridge> bridgeWeak = AceType::WeakClaim(this); SetPlayStateCallbacksWithListenerId(animator); animator->ClearPauseListeners(); animator->AddPauseListener([bridgeWeak, instance = instance_] { auto delegate = static_cast<RefPtr<FrontendDelegate>*>(instance->GetData(V8EngineInstance::FRONTEND_DELEGATE)); auto jsTaskExecutor = (*delegate)->GetAnimationJsTask(); jsTaskExecutor.PostTask([instance, bridgeWeak]() mutable { JsUpdatePlayState(instance, bridgeWeak, DOM_ANIMATION_PLAY_STATE_PAUSED); }); }); animator->ClearStartListeners(); animator->AddStartListener([bridgeWeak, instance = instance_] { auto delegate = static_cast<RefPtr<FrontendDelegate>*>(instance->GetData(V8EngineInstance::FRONTEND_DELEGATE)); auto jsTaskExecutor = (*delegate)->GetAnimationJsTask(); jsTaskExecutor.PostTask([instance, bridgeWeak]() mutable { CallAnimationStartJs(bridgeWeak, instance); JsUpdatePlayState(instance, bridgeWeak, DOM_ANIMATION_PLAY_STATE_RUNNING); }); }); animator->ClearResumeListeners(); animator->AddResumeListener([bridgeWeak, instance = instance_] { auto delegate = static_cast<RefPtr<FrontendDelegate>*>(instance->GetData(V8EngineInstance::FRONTEND_DELEGATE)); auto jsTaskExecutor = (*delegate)->GetAnimationJsTask(); jsTaskExecutor.PostTask([instance, bridgeWeak]() mutable { JsUpdatePlayState(instance, bridgeWeak, DOM_ANIMATION_PLAY_STATE_RUNNING); }); }); } void V8AnimationBridgeUtils::JsAnimationPlay(const v8::FunctionCallbackInfo<v8::Value>& args) { if (args.Length() != 0) { LOGE("args length error, length: %{public}d", args.Length()); return; } v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope handleScope(isolate); auto ctx = isolate->GetCurrentContext(); int32_t nodeId = GetCurrentNodeId(ctx, args.Holder()); int32_t pageId = GetCurrentPageId(ctx, args.Holder()); HandleJsAnimationContext(ctx, pageId, nodeId, AnimationOperation::PLAY); } void V8AnimationBridgeUtils::JsAnimationFinish(const v8::FunctionCallbackInfo<v8::Value>& args) { if (args.Length() != 0) { LOGE("args length error, length: %{public}d", args.Length()); return; } v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope handleScope(isolate); auto ctx = isolate->GetCurrentContext(); int32_t nodeId = GetCurrentNodeId(ctx, args.Holder()); int32_t pageId = GetCurrentPageId(ctx, args.Holder()); HandleJsAnimationContext(ctx, pageId, nodeId, AnimationOperation::FINISH); } void V8AnimationBridgeUtils::JsAnimationPause(const v8::FunctionCallbackInfo<v8::Value>& args) { if (args.Length() != 0) { LOGE("args length error, length: %{public}d", args.Length()); return; } v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope handleScope(isolate); auto ctx = isolate->GetCurrentContext(); int32_t nodeId = GetCurrentNodeId(ctx, args.Holder()); int32_t pageId = GetCurrentPageId(ctx, args.Holder()); HandleJsAnimationContext(ctx, pageId, nodeId, AnimationOperation::PAUSE); } void V8AnimationBridgeUtils::JsAnimationCancel(const v8::FunctionCallbackInfo<v8::Value>& args) { if (args.Length() != 0) { LOGE("args length error, length: %{public}d", args.Length()); return; } v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope handleScope(isolate); auto ctx = isolate->GetCurrentContext(); int32_t nodeId = GetCurrentNodeId(ctx, args.Holder()); int32_t pageId = GetCurrentPageId(ctx, args.Holder()); HandleJsAnimationContext(ctx, pageId, nodeId, AnimationOperation::CANCEL); } void V8AnimationBridgeUtils::JsAnimationReverse(const v8::FunctionCallbackInfo<v8::Value>& args) { if (args.Length() != 0) { LOGE("args length error, length: %{public}d", args.Length()); return; } v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope handleScope(isolate); auto ctx = isolate->GetCurrentContext(); int32_t nodeId = GetCurrentNodeId(ctx, args.Holder()); int32_t pageId = GetCurrentPageId(ctx, args.Holder()); HandleJsAnimationContext(ctx, pageId, nodeId, AnimationOperation::REVERSE); } v8::Local<v8::Object> V8AnimationBridgeUtils::CreateAnimationContext( v8::Local<v8::Context>& ctx, int32_t pageId, NodeId nodeId) { const std::unordered_map<const char*, v8::Local<v8::Function>> contextTable = { { "play", v8::Function::New(ctx, JsAnimationPlay, v8::Local<v8::Value>(), 0).ToLocalChecked() }, { "finish", v8::Function::New(ctx, JsAnimationFinish, v8::Local<v8::Value>(), 0).ToLocalChecked() }, { "pause", v8::Function::New(ctx, JsAnimationPause, v8::Local<v8::Value>(), 0).ToLocalChecked() }, { "cancel", v8::Function::New(ctx, JsAnimationCancel, v8::Local<v8::Value>(), 0).ToLocalChecked() }, { "reverse", v8::Function::New(ctx, JsAnimationReverse, v8::Local<v8::Value>(), 0).ToLocalChecked() }, }; auto animationContext = v8::Object::New(ctx->GetIsolate()); for (const auto& iter : contextTable) { animationContext->Set(ctx, v8::String::NewFromUtf8(ctx->GetIsolate(), iter.first).ToLocalChecked(), iter.second) .ToChecked(); } animationContext ->Set(ctx, v8::String::NewFromUtf8(ctx->GetIsolate(), "__nodeId").ToLocalChecked(), v8::Int32::New(ctx->GetIsolate(), nodeId)) .ToChecked(); animationContext ->Set(ctx, v8::String::NewFromUtf8(ctx->GetIsolate(), "__pageId").ToLocalChecked(), v8::Int32::New(ctx->GetIsolate(), pageId)) .ToChecked(); animationContext ->Set(ctx, v8::String::NewFromUtf8(ctx->GetIsolate(), "__playState").ToLocalChecked(), v8::String::NewFromUtf8(ctx->GetIsolate(), DOM_ANIMATION_PLAY_STATE_IDLE).ToLocalChecked()) .ToChecked(); animationContext ->Set(ctx, v8::String::NewFromUtf8(ctx->GetIsolate(), "finished").ToLocalChecked(), v8::Boolean::New(ctx->GetIsolate(), 0)) .ToChecked(); for (const auto& item : V8_ANIMATION_FUNCS) { auto getterTempl = v8::FunctionTemplate::New(ctx->GetIsolate(), std::get<1>(item)); auto setterTempl = v8::FunctionTemplate::New(ctx->GetIsolate(), std::get<2>(item)); animationContext->SetAccessorProperty( v8::String::NewFromUtf8(ctx->GetIsolate(), std::get<0>(item).c_str()).ToLocalChecked(), getterTempl->GetFunction(ctx).ToLocalChecked(), setterTempl->GetFunction(ctx).ToLocalChecked()); } return animationContext; } V8AnimationBridgeTaskCreate::V8AnimationBridgeTaskCreate( const RefPtr<FrontendDelegate>& delegate, const RefPtr<V8AnimationBridge>& bridge, std::string param) : bridge_(bridge), delegate_(delegate), param_(std::move(param)) {} void V8AnimationBridgeTaskCreate::AnimationBridgeTaskFunc(const RefPtr<JsAcePage>& page, NodeId nodeId) { if (!bridge_ || !page) { LOGE("Create Animation Bridge failed. bridge or page is null."); EventReport::SendAnimationException(AnimationExcepType::ANIMATION_BRIDGE_ERR); return; } auto bridgeFree = AceType::DynamicCast<V8AnimationBridge>(page->GetAnimationBridge(nodeId)); auto sp = delegate_.Upgrade(); if (sp) { auto jsTaskExecutor = sp->GetAnimationJsTask(); if (bridgeFree) { auto weakBridge = AceType::WeakClaim(AceType::RawPtr(bridgeFree)); jsTaskExecutor.PostTask([weakBridge]() mutable { auto bridgeFree = weakBridge.Upgrade(); if (bridgeFree != nullptr) { bridgeFree.Reset(); } }); } } bridge_->JsCreateAnimation(page, param_); page->AddAnimationBridge(nodeId, bridge_); } void V8AnimationBridgeTaskOperation::AnimationBridgeTaskFunc(const RefPtr<JsAcePage>& page, NodeId nodeId) { if (!page) { LOGE("AnimationBridgeTaskFunc failed, page is nullptr."); return; } auto animationBridge = AceType::DynamicCast<V8AnimationBridge>(page->GetAnimationBridge(nodeId)); if (!animationBridge) { LOGE("no animation bridge found for nodeId: %{public}d", nodeId); EventReport::SendAnimationException(AnimationExcepType::ANIMATION_BRIDGE_ERR); return; } auto domDocument = page->GetDomDocument(); if (!domDocument) { LOGE("Animation operation failed, DomDocument is null."); return; } auto domNode = domDocument->GetDOMNodeById(nodeId); if (!domNode) { LOGE("Animation operation failed, DomNode is null."); return; } auto tweenComponent = domNode->GetTweenComponent(); if (tweenComponent) { tweenComponent->SetCustomAnimationOperation(operation_); } RefPtr<Animator> animator; if (tweenComponent) { animator = tweenComponent->GetAnimator(); } if (animator) { animationBridge->SetPlayStateCallbacks(animator); } domNode->GenerateComponentNode(); page->PushDirtyNode(nodeId); } void V8AnimationBridgeTaskStartTime::AnimationBridgeTaskFunc(const RefPtr<JsAcePage>& page, NodeId nodeId) { if (!page) { LOGE("V8AnimationBridgeTaskStartTime: Get page is error"); return; } auto domDocument = page->GetDomDocument(); if (!domDocument) { LOGE("V8AnimationBridgeTaskStartTime failed, DomDocument is null."); return; } auto domNode = domDocument->GetDOMNodeById(nodeId); if (!domNode) { LOGE("V8AnimationBridgeTaskStartTime failed, DomNode is null."); return; } auto tweenComponent = domNode->GetTweenComponent(); if (tweenComponent) { auto option = tweenComponent->GetCustomTweenOption(); option.SetDelay(StringToInt(startTime_)); tweenComponent->SetCustomTweenOption(option); } } } // namespace OHOS::Ace::Framework
42.458886
120
0.685263
[ "object", "vector" ]
8090a0af416d72f1dd4629624757424f8975598d
494
cpp
C++
leet/array/almostIncreasingSequence.cpp
peterlamar/cpp-cp-cheatsheet
23af2e893992141572005de7a438c3a2d376547e
[ "Apache-2.0" ]
null
null
null
leet/array/almostIncreasingSequence.cpp
peterlamar/cpp-cp-cheatsheet
23af2e893992141572005de7a438c3a2d376547e
[ "Apache-2.0" ]
null
null
null
leet/array/almostIncreasingSequence.cpp
peterlamar/cpp-cp-cheatsheet
23af2e893992141572005de7a438c3a2d376547e
[ "Apache-2.0" ]
null
null
null
/* For sequence = [1, 3, 2, 1], the output should be almostIncreasingSequence(sequence) = false. */ bool almostIncreasingSequence(vector<int> sequence) { int count = 0; for (int i=1; i < sequence.size(); i++){ if(sequence[i] <= sequence[i-1]) { count++; if ((i>1)&&(i+1 < sequence.size()) && (sequence[i]<=sequence[i-2]) && (sequence[i+1]<=sequence[i-1])){ return false; } } } return count == 1; }
29.058824
114
0.508097
[ "vector" ]
80928d6352c4a01ebc30d407dde16905cd4cbf35
6,700
cpp
C++
src/encoding_task.cpp
greendev5/GreenMp3Encoder
cc8f984a024f082f397b472035fde284df2aa53a
[ "Apache-2.0" ]
null
null
null
src/encoding_task.cpp
greendev5/GreenMp3Encoder
cc8f984a024f082f397b472035fde284df2aa53a
[ "Apache-2.0" ]
null
null
null
src/encoding_task.cpp
greendev5/GreenMp3Encoder
cc8f984a024f082f397b472035fde284df2aa53a
[ "Apache-2.0" ]
null
null
null
#include "encoding_task.h" #include <string.h> #include <vector> #include <lame/lame.h> #include "worker_thread.h" using namespace GMp3Enc; EncodingTask::EncodingTask( const RiffWave &wave, const std::string &mp3Destination, size_t taskId) : wave_(wave) , sourceFilePath_(wave.riffWavePath()) , mp3Destination_(mp3Destination) , taskId_(taskId) , lame_(NULL) , executor_(NULL) , taskBuffer_(NULL) , r_(EncodingSuccess) { } EncodingTask::~EncodingTask() { if (taskBuffer_) delete[] taskBuffer_; } EncodingTask* EncodingTask::create( const RiffWave &wave, const std::string &mp3Destination, size_t taskId) { if (!wave.isValid()) return NULL; return new EncodingTask(wave, mp3Destination, taskId); } EncodingTask::EncodingResult EncodingTask::encode() { r_ = EncodingSuccess; uint8_t* mp3Buffer = NULL; int32_t* pcmBuffer = NULL; int32_t* pcmBufferLeft = NULL; int32_t* pcmBufferRight = NULL; FILE *outf = fopen(mp3Destination_.c_str(), "wb"); if (!outf) { errorStr_ = "Could not open destination file"; r_ = EncodingBadDestination; return r_; } if (!initLame()) { fclose(outf); r_ = EncodingSystemError; return r_; } int frameSize = lame_get_framesize(lame_); if (frameSize <= 0) { errorStr_ = "Bad lame frame size"; fclose(outf); lame_close(lame_); lame_ = NULL; r_ = EncodingSystemError; return r_; } else if (frameSize > LAME_MAX_FRAME_SIZE) { frameSize = LAME_MAX_FRAME_SIZE; } if (!allocateBuffers(&mp3Buffer, &pcmBuffer, &pcmBufferLeft, &pcmBufferRight, frameSize)) { errorStr_ = "Failed to allocate buffers"; fclose(outf); lame_close(lame_); lame_ = NULL; r_ = EncodingSystemError; return r_; } int wb = 0; int i = 0; while (true) { size_t readSamples = 0; int numSamples = 0; bool isok = false; int *bufl = NULL; int *bufr = NULL; i++; #ifdef __linux__ if (i % 10 == 0) { if (executor_ && executor_->checkCancelationSignal()) { break; } } #endif isok = wave_.unpackReadSamples(pcmBuffer, frameSize * wave_.channelsNumber(), readSamples); if (!isok) { errorStr_ = "Failed to read PCM source"; r_ = EncodingBadSource; break; } if (!readSamples) break; numSamples = readSamples / wave_.channelsNumber(); if (wave_.channelsNumber() == 2) { int32_t *p = pcmBuffer + readSamples; for (int j = numSamples; --j >= 0;) { pcmBufferLeft[j] = *--p; pcmBufferRight[j] = *--p; } bufl = pcmBufferLeft; bufr = pcmBufferRight; } else { bufl = pcmBuffer; } wb = lame_encode_buffer_int( lame_, bufl, bufr, numSamples, mp3Buffer, MP3_SIZE); if (wb < 0) { errorStr_ = "lame processing error: " + lameErrorCodeToStr(wb); r_ = EncodingSystemError; break; } else if (wb > 0) { size_t owb = fwrite(mp3Buffer, 1, wb, outf); if (owb != wb) { errorStr_ = "Failed to write into output file"; r_ = EncodingBadDestination; break; } } } if (r_ == EncodingSuccess) { wb = lame_encode_flush( lame_, mp3Buffer, MP3_SIZE); if (wb < 0) { errorStr_ = "lame processing error: " + lameErrorCodeToStr(wb); r_ = EncodingSystemError; } else if (wb > 0) { size_t owb = fwrite(mp3Buffer, 1, wb, outf); if (owb != wb) { errorStr_ = "Failed to write into output file"; r_ = EncodingBadDestination; } } } fclose(outf); lame_close(lame_); lame_ = NULL; return r_; } void EncodingTask::setExecutor(WorkerThread *executor) { executor_ = executor; } std::string EncodingTask::sourceFilePath() const { return sourceFilePath_; } bool EncodingTask::initLame() { lame_ = lame_init(); if (!lame_) { errorStr_ = "Failed to init lame encoder."; return false; } lame_set_findReplayGain(lame_, 1); lame_set_num_samples(lame_, wave_.numSamples()); lame_set_in_samplerate(lame_, wave_.samplesPerSec()); lame_set_brate(lame_, wave_.avgBytesPerSec()); if (wave_.channelsNumber() == 1) { lame_set_num_channels(lame_, 1); lame_set_mode(lame_, MONO); } else { lame_set_num_channels(lame_, wave_.channelsNumber()); } //lame_set_VBR(lame_, vbr_mtrh); lame_set_quality(lame_, 2); // high quality if (lame_init_params(lame_) < 0) { errorStr_ = "Fatal error during lame initialization."; return false; } return true; } std::string EncodingTask::lameErrorCodeToStr(int r) { if (r >= 0) return std::string("no error"); switch (r) { case -1: return std::string("mp3buf was too small"); case -2: return std::string("malloc() problem"); case -3: return std::string("lame_init_params() not called"); case -4: return std::string("psycho acoustic problems"); default: break; } return std::string("unknown error"); } bool EncodingTask::allocateBuffers(uint8_t **mp3Buffer, int32_t **pcmBuffer, int32_t **pcmBufferLeft, int32_t **pcmBufferRight, int frameSize) { uint8_t *buf; if (executor_) { buf = executor_->internalBuffer(); if (!buf) { return false; } } else { try { taskBuffer_ = new uint8_t[ENCODING_BUFFER_SIZE]; } catch(std::bad_alloc) { taskBuffer_ = NULL; return false; } buf = taskBuffer_; } *mp3Buffer = buf; *pcmBuffer = reinterpret_cast<int32_t*>( buf + MP3_SIZE); *pcmBufferLeft = reinterpret_cast<int32_t*>( buf + MP3_SIZE + (frameSize * wave_.channelsNumber()) * sizeof(int32_t)); *pcmBufferRight = reinterpret_cast<int32_t*>( buf + MP3_SIZE + (frameSize * wave_.channelsNumber()) * sizeof(int32_t) + frameSize * sizeof(int32_t)); return true; }
24.452555
99
0.551642
[ "vector" ]
80958eac40e47ceeab8eb8b0f72fc4efafd584a1
106
cpp
C++
main.cpp
gau0522/Algorithms-DataStructures
c6a262bc582b6b2a3cd0394c25cc1efd9ed1f3ed
[ "MIT" ]
null
null
null
main.cpp
gau0522/Algorithms-DataStructures
c6a262bc582b6b2a3cd0394c25cc1efd9ed1f3ed
[ "MIT" ]
null
null
null
main.cpp
gau0522/Algorithms-DataStructures
c6a262bc582b6b2a3cd0394c25cc1efd9ed1f3ed
[ "MIT" ]
null
null
null
#include<vector> #include<iostream> #include<limits.h> using namespace std; int main() { return 0; }
11.777778
20
0.688679
[ "vector" ]
8096cbca23bdca92099551b3a067d1824dfeaf77
5,997
cpp
C++
randmio_dir_connected.cpp
devuci/bct-cpp
bbb33f476bffbb5669e051841f00c3241f4d6f69
[ "MIT" ]
null
null
null
randmio_dir_connected.cpp
devuci/bct-cpp
bbb33f476bffbb5669e051841f00c3241f4d6f69
[ "MIT" ]
null
null
null
randmio_dir_connected.cpp
devuci/bct-cpp
bbb33f476bffbb5669e051841f00c3241f4d6f69
[ "MIT" ]
null
null
null
#include "bct.h" /* * Returns a randomized graph with equivalent degree sequence to the original * weighted directed graph, and with preserved connectedness. On average, each * edge is rewired ITER times. Out-strength is preserved for weighted graphs, * while in-strength is not. */ MATRIX_T* BCT_NAMESPACE::randmio_dir_connected(const MATRIX_T* R, int ITER) { if (safe_mode) check_status(R, SQUARE | DIRECTED, "randmio_dir_connected"); gsl_rng* rng = get_rng(); // [i j]=find(R); MATRIX_T* find_R = find_ij(R); VECTOR_ID(view) i = MATRIX_ID(column)(find_R, 0); VECTOR_ID(view) j = MATRIX_ID(column)(find_R, 1); // K=length(i); int K = length(&i.vector); // ITER=K*ITER; ITER = K * ITER; MATRIX_T* _R = copy(R); // for iter=1:ITER for (int iter = 1; iter <= ITER; iter++) { // while 1 while (true) { // rewire = 1 bool rewire = true; int e1, e2; int a, b, c, d; // while 1 while (true) { // e1=ceil(K*rand); e1 = gsl_rng_uniform_int(rng, K); // e2=ceil(K*rand); e2 = gsl_rng_uniform_int(rng, K); // while (e2==e1), while (e2 == e1) { // e2=ceil(K*rand); e2 = gsl_rng_uniform_int(rng, K); } // a=i(e1); b=j(e1); a = (int)VECTOR_ID(get)(&i.vector, e1); b = (int)VECTOR_ID(get)(&j.vector, e1); // c=i(e2); d=j(e2); c = (int)VECTOR_ID(get)(&i.vector, e2); d = (int)VECTOR_ID(get)(&j.vector, e2); // if all(a~=[c d]) && all(b~=[c d]); if (a != c && a != d && b != c && b != d) { // break break; } } // if ~(R(a,d) || R(c,b)) if (fp_zero(MATRIX_ID(get)(_R, a, d)) && fp_zero(MATRIX_ID(get)(_R, c, b))) { // if ~(any([R(a,c) R(d,b) R(d,c)]) && any([R(c,a) R(b,d) R(b,a)])) VECTOR_T* _R_idx_1 = VECTOR_ID(alloc)(3); VECTOR_ID(set)(_R_idx_1, 0, MATRIX_ID(get)(_R, a, c)); VECTOR_ID(set)(_R_idx_1, 1, MATRIX_ID(get)(_R, d, b)); VECTOR_ID(set)(_R_idx_1, 2, MATRIX_ID(get)(_R, d, c)); VECTOR_T* _R_idx_2 = VECTOR_ID(alloc)(3); VECTOR_ID(set)(_R_idx_2, 0, MATRIX_ID(get)(_R, c, a)); VECTOR_ID(set)(_R_idx_2, 1, MATRIX_ID(get)(_R, b, d)); VECTOR_ID(set)(_R_idx_2, 2, MATRIX_ID(get)(_R, b, a)); bool any_R_idx_1_and_any_R_idx_2 = any(_R_idx_1) && any(_R_idx_2); VECTOR_ID(free)(_R_idx_1); VECTOR_ID(free)(_R_idx_2); if (!any_R_idx_1_and_any_R_idx_2) { // P=R([a c],:); VECTOR_T* _R_rows = VECTOR_ID(alloc)(2); VECTOR_ID(set)(_R_rows, 0, (FP_T)a); VECTOR_ID(set)(_R_rows, 1, (FP_T)c); VECTOR_T* _R_cols = sequence(0, _R->size2 - 1); MATRIX_T* P = ordinal_index(_R, _R_rows, _R_cols); VECTOR_ID(free)(_R_rows); VECTOR_ID(free)(_R_cols); // P(1,b)=0; P(1,d)=1; MATRIX_ID(set)(P, 0, b, 0.0); MATRIX_ID(set)(P, 0, d, 1.0); // P(2,d)=0; P(2,b)=1; MATRIX_ID(set)(P, 1, d, 0.0); MATRIX_ID(set)(P, 1, b, 1.0); // PN=P; MATRIX_T* PN = copy(P); // PN(1,a)=1; PN(2,c)=1; MATRIX_ID(set)(PN, 0, a, 1.0); MATRIX_ID(set)(PN, 1, c, 1.0); // while 1 while (true) { // P(1,:)=any(R(P(1,:)~=0,:),1); VECTOR_ID(view) P_row_0 = MATRIX_ID(row)(P, 0); VECTOR_T* P_row_0_neq_0 = compare_elements(&P_row_0.vector, fp_not_equal, 0.0); VECTOR_T* _R_cols = sequence(0, _R->size2 - 1); MATRIX_T* _R_idx = log_ord_index(_R, P_row_0_neq_0, _R_cols); VECTOR_ID(free)(P_row_0_neq_0); if (_R_idx != NULL) { VECTOR_T* any__R_idx = any(_R_idx, 1); MATRIX_ID(free)(_R_idx); MATRIX_ID(set_row)(P, 0, any__R_idx); VECTOR_ID(free)(any__R_idx); } else { VECTOR_ID(set_zero)(&P_row_0.vector); } // P(2,:)=any(R(P(2,:)~=0,:),1); VECTOR_ID(view) P_row_1 = MATRIX_ID(row)(P, 0); VECTOR_T* P_row_1_neq_0 = compare_elements(&P_row_1.vector, fp_not_equal, 0.0); _R_idx = log_ord_index(_R, P_row_1_neq_0, _R_cols); VECTOR_ID(free)(P_row_1_neq_0); VECTOR_ID(free)(_R_cols); if (_R_idx != NULL) { VECTOR_T* any__R_idx = any(_R_idx, 1); MATRIX_ID(free)(_R_idx); MATRIX_ID(set_row)(P, 1, any__R_idx); VECTOR_ID(free)(any__R_idx); } else { VECTOR_ID(set_zero)(&P_row_1.vector); } // P=P.*(~PN); MATRIX_T* not_PN = logical_not(PN); MATRIX_ID(mul_elements)(P, not_PN); MATRIX_ID(free)(not_PN); // PN=PN+P MATRIX_ID(add)(PN, P); // if ~all(any(P,2)) VECTOR_T* any_P = any(P, 2); bool all_any_P = all(any_P); VECTOR_ID(free)(any_P); if (!all_any_P) { // rewire=0; rewire = false; // break break; } // elseif any(PN(1,[b c])) && any(PN(2,[d a])) VECTOR_T* PN_idx_1 = VECTOR_ID(alloc)(2); VECTOR_ID(set)(PN_idx_1, 0, MATRIX_ID(get)(PN, 0, b)); VECTOR_ID(set)(PN_idx_1, 1, MATRIX_ID(get)(PN, 0, c)); VECTOR_T* PN_idx_2 = VECTOR_ID(alloc)(2); VECTOR_ID(set)(PN_idx_2, 0, MATRIX_ID(get)(PN, 1, d)); VECTOR_ID(set)(PN_idx_2, 1, MATRIX_ID(get)(PN, 1, a)); bool any_PN_idx_1_and_any_PN_idx_2 = any(PN_idx_1) && any(PN_idx_2); VECTOR_ID(free)(PN_idx_1); VECTOR_ID(free)(PN_idx_2); if (any_PN_idx_1_and_any_PN_idx_2) { // break break; } } MATRIX_ID(free)(P); MATRIX_ID(free)(PN); } // if rewire if (rewire) { // R(a,d)=R(a,b); R(a,b)=0; MATRIX_ID(set)(_R, a, d, MATRIX_ID(get)(_R, a, b)); MATRIX_ID(set)(_R, a, b, 0.0); // R(c,b)=R(c,d); R(c,d)=0; MATRIX_ID(set)(_R, c, b, MATRIX_ID(get)(_R, c, d)); MATRIX_ID(set)(_R, c, d, 0.0); // j(e1) = d; VECTOR_ID(set)(&j.vector, e1, (FP_T)d); // j(e2) = b; VECTOR_ID(set)(&j.vector, e2, (FP_T)b); // break; break; } } } } MATRIX_ID(free)(find_R); return _R; }
28.023364
85
0.54594
[ "vector" ]
80a81c21e284588a7ea60045aa6b18fd07df40a6
13,996
cpp
C++
Source/AllProjects/CIDBuild/CIDBuild_ProjectList.cpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
216
2019-03-09T06:41:28.000Z
2022-02-25T16:27:19.000Z
Source/AllProjects/CIDBuild/CIDBuild_ProjectList.cpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
9
2020-09-27T08:00:52.000Z
2021-07-02T14:27:31.000Z
Source/AllProjects/CIDBuild/CIDBuild_ProjectList.cpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
29
2019-03-09T10:12:24.000Z
2021-03-03T22:25:29.000Z
// // FILE NAME: CIDBuild_ProjectList.Cpp // // AUTHOR: Dean Roddey // // CREATED: 08/21/1998 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements the TProjectList class, which manages the list of // projects, their settings, their dependencies, etc... // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include "CIDBuild.hpp" // --------------------------------------------------------------------------- // CLASS: TProjectList // PREFIX: plist // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TProjectList: Constructors and Destructor // --------------------------------------------------------------------------- TProjectList::TProjectList() { } TProjectList::~TProjectList() { } // --------------------------------------------------------------------------- // TProjectList: Public, non-virtual methods // --------------------------------------------------------------------------- // // A quick check to see if one project depends on another. They can indicate // if it must exist, or if not existing just returns false. // tCIDLib::TBoolean TProjectList::bDependsOn(const TBldStr& strSrcProj , const TBldStr& strToCheck , const tCIDLib::TBoolean bMustExist) const { // Just pass it on to the dependenency graphi return m_depgList.bDependsOn(strSrcProj, strToCheck, bMustExist); } tCIDLib::TBoolean TProjectList::bProjectExists(const TBldStr& strToFind) const { const TProjectInfo* const pprojiTarget = pprojiFindProject(strToFind); return (pprojiTarget != 0); } tCIDLib::TVoid TProjectList::DumpProjectSettings(const TBldStr& strTarget) const { // Find the project and ask it to dump its settings const TProjectInfo* const pprojiTarget = pprojiFindProject(strTarget); if (!pprojiTarget) { stdOut << L"Project '" << strTarget << L"' was not found" << kCIDBuild::EndLn; throw tCIDBuild::EErrors::NotFound; } pprojiTarget->DumpSettings(); } tCIDLib::TVoid TProjectList::LoadFileLists() { // // Just pass this request on to each of the projects in our list. The // order does not matter here so we just do a straight iteration of // the list. // TList<TProjectInfo>::TCursor cursProjs(&m_listProjects); // If no entries, that's wierd, but nothing to do if (!cursProjs.bResetIter()) return; do { cursProjs.tCurElement().LoadFileLists(); } while (cursProjs.bNext()); } const TProjectInfo& TProjectList::projiByName(const TBldStr& strToFind) const { // Look up the project name and return its project info object const TProjectInfo* const pprojiTarget = pprojiFindProject(strToFind); if (!pprojiTarget) { stdOut << L"Project '" << strToFind << L"' was not found" << kCIDBuild::EndLn; throw tCIDBuild::EErrors::NotFound; } return *pprojiTarget; } TProjectInfo& TProjectList::projiByName(const TBldStr& strToFind) { // Look up the project name and return its project info object TProjectInfo* const pprojiTarget = pprojiFindProject(strToFind); if (!pprojiTarget) { stdOut << L"Project '" << strToFind << L"' was not found" << kCIDBuild::EndLn; throw tCIDBuild::EErrors::NotFound; } return *pprojiTarget; } tCIDLib::TVoid TProjectList::ParseProjectFile() { // Build up the path to the project file TBldStr strProjFile(facCIDBuild.strRootDir()); strProjFile.Append(L"Source", kCIDBuild::pszPathSep); strProjFile.Append(L"AllProjects", kCIDBuild::pszPathSep); strProjFile.Append(L"CIDBuild.Projects"); // Make sure it exists if (!TUtils::bExists(strProjFile)) { stdOut << L"Project file " << strProjFile << L" was not found" << kCIDBuild::EndLn; throw tCIDBuild::EErrors::FileNotFound; } if (facCIDBuild.bVerbose()) { stdOut << L"\n----------------------------------------------\n" << L"Parsing project file: " << strProjFile << L"\n" << L"----------------------------------------------" << kCIDBuild::EndLn; } // // Lets create a line spooler for the project file and go into the // line reading loop. The file format is all line oriented so we // don't need any fancy lexing here. // TLineSpooler lsplSource(strProjFile); TBldStr strReadBuf; TBldStr strProjName; tCIDBuild::TStrList listPlatfExcl; tCIDBuild::TStrList listPlatfIncl; while (kCIDLib::True) { // Get the next line. If at the end of file, then we are done if (!lsplSource.bReadLine(strReadBuf)) break; if (strReadBuf.bStartsWith(L"PROJECT=")) { // Cut off the prefix to leave the name and possibly platform incl/excl lists strReadBuf.Cut(8); strReadBuf.StripWhitespace(); // Parse this initial line info ParseInitProjLine ( strReadBuf, lsplSource.c4CurLine(), strProjName, listPlatfIncl, listPlatfExcl ); // // Create a new project info object and let it parse it's name and // and include/exclude info if present. // TProjectInfo* pprojiCur = new TProjectInfo(strProjName, listPlatfIncl, listPlatfExcl); // // If it doesn't support the current platform, then we just eat lines until // the end of this project, then we can delete it and move on. // if (!pprojiCur->bSupportsThisPlatform()) { // Remember the project name and delete this project const TBldStr strProjName = pprojiCur->strProjectName(); delete pprojiCur; // Eat the rest of this project's content (tell it not to try to expand macros) tCIDLib::TBoolean bGotEnd = kCIDLib::False; while (lsplSource.bReadLine(strReadBuf, kCIDLib::True)) { if (strReadBuf.bIEquals(L"END PROJECT")) { bGotEnd = kCIDLib::True; break; } } if (!bGotEnd) { stdOut << L"(Line " << lsplSource.c4CurLine() << L") Never found end of unsupported project (" << strProjName << L")" << kCIDBuild::EndLn; throw tCIDBuild::EErrors::UnexpectedEOF; } } else { // This one is a keeper so ask it to parse out the rest of its content pprojiCur->ParseContent(lsplSource); // // Let this new project add him/herself to the dependency graph. // This will catch any duplicate names. He will cache the index // at which he was added to the graph, which will much speed up // later work. // pprojiCur->AddToDepGraph(m_depgList); // And then add this new project to our list of projects m_listProjects.Add(pprojiCur); } } else if (strReadBuf == L"ALLPROJECTS=") { // // The settings in this block are system wide, i.e. they apply // to all projects. // facCIDBuild.ParseAllProjects(lsplSource); } else { // Dunno what this is stdOut << L"(Line " << lsplSource.c4CurLine() << L") Expected ALLPROJECTS=, or PROJECT=XXX" << kCIDBuild::EndLn; throw tCIDBuild::EErrors::FileFormat; } } // // Ok, so now lets feed all of the dependencies of each project into // the dependency graph. This will set up all of the info required to // do the actions in the correct order of dependency. // // Note that we added all of the projects themselves into the graph // during parsing above, so here we just need to add their dependencies // to the graph. They each have already cached their offset into the // graph, so we can use that index for speed. // TList<TProjectInfo>::TCursor cursProjs(&m_listProjects); if (cursProjs.bResetIter()) { do { // Get a quick ref to the next project info object const TProjectInfo& projiCur = cursProjs.tCurElement(); // Do the regular dependencies TList<TBldStr>::TCursor cursDeps(&projiCur.listDeps()); if (cursDeps.bResetIter()) { do { // // Add a dependency for this new dependent. Note that we // use the cached index into the dependency graph instead // of doing an insert by project name. // m_depgList.AddDependency(projiCur.c4DepIndex(), cursDeps.tCurElement()); } while (cursDeps.bNext()); } } while (cursProjs.bNext()); } // And ask the dependency graph to check for circular depenendies if (m_depgList.bTestCircular()) { stdOut << L"Circular dependencies not allowed in the project list" << kCIDBuild::EndLn; throw tCIDBuild::EErrors::DependError; } } tCIDLib::TVoid TProjectList::RemoveAll() { // Just flush our project info list and clear the dependency graph m_listProjects.RemoveAll(); m_depgList.Clear(); } // --------------------------------------------------------------------------- // TProjectList: Private, non-virtual methods // --------------------------------------------------------------------------- const TProjectInfo* TProjectList::pprojiFindProject(const TBldStr& strName) const { // Get a cursor for the project list TList<TProjectInfo>::TCursor cursProjs(&m_listProjects); // If no entries, that's wierd but nothing to do if (!cursProjs.bResetIter()) return 0; do { // If the project name matches the passed name, this is it if (cursProjs.tCurElement().strProjectName().bIEquals(strName)) return &cursProjs.tCurElement(); } while (cursProjs.bNext()); return 0; } TProjectInfo* TProjectList::pprojiFindProject(const TBldStr& strName) { // Get a cursor for the project list TList<TProjectInfo>::TCursor cursProjs(&m_listProjects); // If no entries, that's wierd but nothing to do if (!cursProjs.bResetIter()) return 0; do { // If the project name matches the passed name, this is it if (cursProjs.tCurElement().strProjectName().bIEquals(strName)) return &cursProjs.tCurElement(); } while (cursProjs.bNext()); return 0; } // // We get a line like: // // projname [incl1 incl2, excl1 excl2] // // So the project name and an optional list of platforms to include, followed by an optional // list of platforms to exclude. Each of the lists are space separated tokens. // tCIDLib::TVoid TProjectList::ParseInitProjLine(const TBldStr& strLine , const tCIDLib::TCard4 c4Line , TBldStr& strName , tCIDBuild::TStrList& listProjIncl , tCIDBuild::TStrList& listProjExcl) { listProjIncl.RemoveAll(); listProjExcl.RemoveAll(); // Tokenize the line on our known separators. If we get none, then obviously bad tCIDBuild::TStrList listTokens; if (!TUtils::bTokenize(strLine, L"[,]", TBldStr(), listTokens)) { stdOut << L"(Line " << c4Line << L") At least a project name is required here" << kCIDBuild::EndLn; throw tCIDBuild::EErrors::FileFormat; } tCIDBuild::TStrList::TCursor cursTokens(&listTokens); if (!cursTokens.bResetIter()) { stdOut << L"(Line " << c4Line << L") No tokens available even though some were reported" << kCIDBuild::EndLn; throw tCIDBuild::EErrors::Internal; } // The first one has to be the project name strName = cursTokens.tCurElement(); if (!TRawStr::bIsAlpha(strName.chFirst())) { stdOut << L"(Line " << c4Line << L") Project names must start with an alpha character" << kCIDBuild::EndLn; throw tCIDBuild::EErrors::FileFormat; } if (cursTokens.bNext()) { // This has to be the open bracket if (cursTokens.tCurElement() != L"[") { stdOut << L"(Line " << c4Line << L") Expected open paren or end of line" << kCIDBuild::EndLn; throw tCIDBuild::EErrors::Internal; } // Call the utils helper that parses the lists from a cursor of tokens TBldStr strError; if (!TUtils::bParseInclExclLists(cursTokens, listProjIncl, listProjExcl, strError)) { stdOut << L"(Line " << c4Line << L") " << strError << kCIDBuild::EndLn; throw tCIDBuild::EErrors::FileFormat; } } }
33.165877
98
0.547299
[ "object" ]
80ac468543dfcb1f49effcaafa158b675b842add
1,597
cpp
C++
threshsign/test/TestMisc.cpp
MaggieQi/concord-bft
8db0cfbec988e691ce592901124bee6617d64be4
[ "Apache-2.0" ]
null
null
null
threshsign/test/TestMisc.cpp
MaggieQi/concord-bft
8db0cfbec988e691ce592901124bee6617d64be4
[ "Apache-2.0" ]
null
null
null
threshsign/test/TestMisc.cpp
MaggieQi/concord-bft
8db0cfbec988e691ce592901124bee6617d64be4
[ "Apache-2.0" ]
1
2021-05-18T02:12:33.000Z
2021-05-18T02:12:33.000Z
// Concord // // Copyright (c) 2018 VMware, Inc. All Rights Reserved. // // This product is licensed to you under the Apache 2.0 license (the "License"). // You may not use this product except in compliance with the Apache 2.0 License. // // This product may include a number of subcomponents with separate copyright // notices and license terms. Your use of these subcomponents is subject to the // terms and conditions of the subcomponent's license, as noted in the // LICENSE file. #include "threshsign/Configuration.h" #include <map> #include <set> #include <vector> #include <string> #include <cassert> #include <memory> #include <algorithm> #include <stdexcept> #include "Logger.hpp" #include "Utils.h" #include "XAssert.h" #include "app/Main.h" using namespace std; void testUtils(); int AppMain(const std::vector<std::string>& args) { (void)args; testUtils(); return 0; } void testUtils() { testAssertEqual(Utils::numBits(1), 1); testAssertEqual(Utils::numBits(2), 2); testAssertEqual(Utils::numBits(3), 2); testAssertEqual(Utils::numBits(4), 3); testAssertEqual(Utils::numBits(5), 3); testAssertEqual(Utils::numBits(6), 3); testAssertEqual(Utils::numBits(7), 3); testAssertEqual(Utils::numBits(8), 4); LOG_INFO(GL, "Utils::numBits passed!"); testAssertEqual(Utils::pow2(0), 1); testAssertEqual(Utils::pow2(1), 2); testAssertEqual(Utils::pow2(2), 4); testAssertEqual(Utils::pow2(3), 8); testAssertEqual(Utils::pow2(4), 16); testAssertEqual(Utils::pow2(5), 32); LOG_INFO(GL, "Utils::pow2 passed!"); }
25.349206
81
0.691296
[ "vector" ]
80ae071233a16e528d8fd1411e6c73f07f41becb
2,017
cpp
C++
src/ColonyAutomata.cpp
aaronshappell/ColonyAutomata
c8e999c0e6cdc53534d208a6dedec686f47db273
[ "MIT" ]
null
null
null
src/ColonyAutomata.cpp
aaronshappell/ColonyAutomata
c8e999c0e6cdc53534d208a6dedec686f47db273
[ "MIT" ]
1
2017-09-10T15:04:08.000Z
2017-09-13T21:14:23.000Z
src/ColonyAutomata.cpp
aaronshappell/ColonyAutomata
c8e999c0e6cdc53534d208a6dedec686f47db273
[ "MIT" ]
null
null
null
#include <iostream> #include "ColonyAutomata.h" ColonyAutomata::ColonyAutomata(int width, int height) : window(sf::VideoMode(width, height), "Colony Automata"), width(width), height(height) { std::cout << "People memory allocated" << std::endl; people = new Person[width * height]; /* for(int r = 0; r < height; r++){ for(int c = 0; c < width; c++){ people[r * width + c].create(); } } */ pixelBuffer.create(width, height, sf::Color::White); pixelTexture.loadFromImage(pixelBuffer); pixelSprite.setTexture(pixelTexture); } ColonyAutomata::~ColonyAutomata(){ std::cout << "Deconstructing ColonyAutomata" << std::endl; delete[] people; } void ColonyAutomata::run(){ sf::Clock clock; const float targetDelta = 1.0f / 60.0f; const int updateLimit = 10; int updateCount = 0; float accumulator = 0.0f; while(window.isOpen()){ float delta = clock.restart().asSeconds(); accumulator += delta; updateCount = 0; while(accumulator >= targetDelta && updateCount < updateLimit){ //pollEvents(); pollInput(delta); update(delta); accumulator -= delta; updateCount++; } render(); std::cout << "\rfps: " << 1.0f / delta; } } void ColonyAutomata::update(float delta){ } void ColonyAutomata::render(){ window.clear(sf::Color::Black); window.draw(pixelSprite); window.display(); } void ColonyAutomata::pollInput(float delta){ if(sf::Keyboard::isKeyPressed(sf::Keyboard::W)){ pixelSprite.move(sf::Vector2f(0, -100) * delta); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::A)){ pixelSprite.move(sf::Vector2f(-100, 0) * delta); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::S)){ pixelSprite.move(sf::Vector2f(0, 100) * delta); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)){ pixelSprite.move(sf::Vector2f(100, 0) * delta); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)){ window.close(); } } void ColonyAutomata::pollEvents(){ sf::Event event; while(window.pollEvent(event)){ if(event.type == sf::Event::Closed){ window.close(); } } }
24.597561
144
0.67179
[ "render" ]