hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
e063649cb9f2f51b43d201ae2b3a4d068105ad40
675
cpp
C++
Problems/234. Palindrome Linked List/pointers_array.cpp
uSlashVlad/MyLeetCode
3d5e8e347716beb0ffadb538c92eceb42ab7fcf9
[ "MIT" ]
1
2022-01-29T01:52:58.000Z
2022-01-29T01:52:58.000Z
Problems/234. Palindrome Linked List/pointers_array.cpp
uSlashVlad/MyLeetCode
3d5e8e347716beb0ffadb538c92eceb42ab7fcf9
[ "MIT" ]
null
null
null
Problems/234. Palindrome Linked List/pointers_array.cpp
uSlashVlad/MyLeetCode
3d5e8e347716beb0ffadb538c92eceb42ab7fcf9
[ "MIT" ]
null
null
null
#include "../includes.hpp" using namespace std; struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; class Solution { public: bool isPalindrome(ListNode *head) { std::vector<int> v = {head->val}; while (head->next != nullptr) { head = head->next; v.push_back(head->val); } int l = v.size(); for (int i = 0; i < l / 2; i++) { if (v[i] != v[l - i - 1]) return false; } return true; } };
19.285714
59
0.472593
uSlashVlad
e06d9cd70b869e3329ab4b524dd76112e04aa3d9
6,439
cpp
C++
src/Settings/Constants.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
12
2020-09-07T11:19:10.000Z
2022-02-17T17:40:19.000Z
src/Settings/Constants.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
110
2020-09-02T15:29:24.000Z
2022-03-09T09:50:01.000Z
src/Settings/Constants.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
3
2021-05-21T13:24:31.000Z
2022-02-11T14:43:12.000Z
/** * Definition of OptionConstants constants. */ #include "DREAM/Settings/OptionConstants.hpp" using namespace DREAM; /** * NAMES OF UNKNOWN QUANTITIES */ const char *OptionConstants::UQTY_E_FIELD = "E_field"; const char *OptionConstants::UQTY_F_HOT = "f_hot"; const char *OptionConstants::UQTY_F_RE = "f_re"; const char *OptionConstants::UQTY_ION_SPECIES = "n_i"; const char *OptionConstants::UQTY_ION_SPECIES_ABL = "n_i_abl"; const char *OptionConstants::UQTY_I_P = "I_p"; const char *OptionConstants::UQTY_I_WALL = "I_wall"; const char *OptionConstants::UQTY_J_HOT = "j_hot"; const char *OptionConstants::UQTY_J_OHM = "j_ohm"; const char *OptionConstants::UQTY_J_RE = "j_re"; const char *OptionConstants::UQTY_J_TOT = "j_tot"; const char *OptionConstants::UQTY_N_ABL = "n_abl"; const char *OptionConstants::UQTY_N_COLD = "n_cold"; const char *OptionConstants::UQTY_N_HOT = "n_hot"; const char *OptionConstants::UQTY_N_RE = "n_re"; const char *OptionConstants::UQTY_N_RE_NEG = "n_re_neg"; const char *OptionConstants::UQTY_N_TOT = "n_tot"; const char *OptionConstants::UQTY_NI_DENS = "N_i"; const char *OptionConstants::UQTY_POL_FLUX = "psi_p"; const char *OptionConstants::UQTY_PSI_EDGE = "psi_edge"; const char *OptionConstants::UQTY_Q_HOT = "q_hot"; const char *OptionConstants::UQTY_PSI_TRANS = "psi_trans"; const char *OptionConstants::UQTY_PSI_WALL = "psi_wall"; const char *OptionConstants::UQTY_S_PARTICLE = "S_particle"; const char *OptionConstants::UQTY_T_ABL = "T_abl"; const char *OptionConstants::UQTY_T_COLD = "T_cold"; const char *OptionConstants::UQTY_TAU_COLL = "tau_coll"; const char *OptionConstants::UQTY_V_LOOP_TRANS = "V_loop_trans"; const char *OptionConstants::UQTY_V_LOOP_WALL = "V_loop_w"; const char *OptionConstants::UQTY_V_P = "v_p"; const char *OptionConstants::UQTY_W_ABL = "W_abl"; const char *OptionConstants::UQTY_W_COLD = "W_cold"; const char *OptionConstants::UQTY_W_HOT = "W_hot"; const char *OptionConstants::UQTY_WI_ENER = "W_i"; const char *OptionConstants::UQTY_X_P = "x_p"; const char *OptionConstants::UQTY_Y_P = "Y_p"; /** * DESCRIPTIONS OF UNKNOWN QUANTITIES */ const char *OptionConstants::UQTY_E_FIELD_DESC = "Parallel electric field <E*B>/sqrt(<B^2>) [V/m]"; const char *OptionConstants::UQTY_F_HOT_DESC = "Hot electron distribution function [m^-3]"; const char *OptionConstants::UQTY_F_RE_DESC = "Runaway electron distribution function [m^-3]"; const char *OptionConstants::UQTY_ION_SPECIES_DESC = "Ion density [m^-3]"; const char *OptionConstants::UQTY_ION_SPECIES_ABL_DESC = "Flux surface averaged density of ablated but not yet equilibrated ions [m^-3]"; const char *OptionConstants::UQTY_I_P_DESC = "Total toroidal plasma current [A]"; const char *OptionConstants::UQTY_I_WALL_DESC = "Wall current [A]"; const char *OptionConstants::UQTY_J_HOT_DESC = "Hot electron parallel current density j_||*Bmin/B [A/m^2]"; const char *OptionConstants::UQTY_J_OHM_DESC = "Ohmic current density j_||*Bmin/B [A/m^2]"; const char *OptionConstants::UQTY_J_RE_DESC = "Runaway electron current density j_||*Bmin/B [A/m^2]"; const char *OptionConstants::UQTY_J_TOT_DESC = "Total current density j_||*Bmin/B [A/m^2]"; const char *OptionConstants::UQTY_N_ABL_DESC = "Flux surface averaged density of ablated but not yet equilibrated electrons [m^-3]"; const char *OptionConstants::UQTY_N_COLD_DESC = "Cold electron density [m^-3]"; const char *OptionConstants::UQTY_N_HOT_DESC = "Hot electron density [m^-3]"; const char *OptionConstants::UQTY_N_RE_DESC = "Runaway electron density <n> [m^-3]"; const char *OptionConstants::UQTY_N_RE_NEG_DESC = "Runaway electron density in negative direction <n> [m^-3]"; const char *OptionConstants::UQTY_N_TOT_DESC = "Total electron density [m^-3]"; const char *OptionConstants::UQTY_NI_DENS_DESC = "Total ion density of each species [m^-3]"; const char *OptionConstants::UQTY_POL_FLUX_DESC = "Poloidal magnetic flux normalized to major radius R0 [Vs/m]"; const char *OptionConstants::UQTY_PSI_EDGE_DESC = "Poloidal magnetic flux at plasma edge (r=rmax) normalized to major radius R0 [Vs/m]"; const char *OptionConstants::UQTY_Q_HOT_DESC = "Hot out going heat flux density in all directions [J/(s m^2)]"; const char *OptionConstants::UQTY_PSI_TRANS_DESC = "Poloidal magnetic flux at transformer normalized to major radius R0 [Vs/m]"; const char *OptionConstants::UQTY_PSI_WALL_DESC = "Poloidal magnetic flux on tokamak wall (r=rwall) normalized to major radius R0 [Vs/m]"; const char *OptionConstants::UQTY_S_PARTICLE_DESC = "Rate at which cold-electron density is added [m^-3 s^-1]"; const char *OptionConstants::UQTY_T_ABL_DESC = "Ablated but not equilibrated electron temperature [eV]"; const char *OptionConstants::UQTY_T_COLD_DESC = "Cold electron temperature [eV]"; const char *OptionConstants::UQTY_TAU_COLL_DESC = "Time-integrated relativistic collision frequency for analytic hottail formula"; const char *OptionConstants::UQTY_V_LOOP_TRANS_DESC = "Loop voltage applied at transformer normalized to major radius R0 [V/m]"; const char *OptionConstants::UQTY_V_LOOP_WALL_DESC = "Loop voltage on tokamak wall normalized to major radius R0 [V/m]"; const char *OptionConstants::UQTY_V_P_DESC = "Pellet shard velocities (Cartesian) [m/s]"; const char *OptionConstants::UQTY_W_ABL_DESC = "Flux surface averaged ablated but not equilibrated electron energy density (3n_abl T_abl/2) [J/m^3]"; const char *OptionConstants::UQTY_W_COLD_DESC = "Cold electron energy density (3nT/2) [J/m^3]"; const char *OptionConstants::UQTY_W_HOT_DESC = "Hot electron energy density [J/m^3]"; const char *OptionConstants::UQTY_WI_ENER_DESC = "Total ion energy density (3N_iT_i/2) of each species [J/m^3]"; const char *OptionConstants::UQTY_X_P_DESC = "Pellet shard coordinates (Cartesian) [m]"; const char *OptionConstants::UQTY_Y_P_DESC = "Pellet shard radii to the power of 5/3 [m^(5/3)]";
72.348315
156
0.702283
chalmersplasmatheory
e06f56385da1f7fcf39d2e6691a2cddca6855a08
5,221
cpp
C++
src/tests/test_lift.cpp
victimsnino/ReactivePlusPlus
bb187cc52936bce7c1ef4899d7dbb9c970cef291
[ "MIT" ]
1
2022-03-19T20:15:50.000Z
2022-03-19T20:15:50.000Z
src/tests/test_lift.cpp
victimsnino/ReactivePlusPlus
bb187cc52936bce7c1ef4899d7dbb9c970cef291
[ "MIT" ]
12
2022-03-22T21:18:14.000Z
2022-03-30T05:37:58.000Z
src/tests/test_lift.cpp
victimsnino/ReactivePlusPlus
bb187cc52936bce7c1ef4899d7dbb9c970cef291
[ "MIT" ]
null
null
null
// ReactivePlusPlus library // // Copyright Aleksey Loginov 2022 - present. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/victimsnino/ReactivePlusPlus // #include "copy_count_tracker.hpp" #include "mock_observer.hpp" #include <catch2/catch_test_macros.hpp> #include <rpp/observables.hpp> #include <rpp/sources/create.hpp> #include <rpp/subscribers.hpp> #include <rpp/observables/dynamic_observable.hpp> #include <rpp/observers/state_observer.hpp> SCENARIO("Observable can be lifted") { auto verifier = copy_count_tracker{}; auto validate = [&](auto observable) { WHEN("Call lift") { int calls_internal = 0; auto new_observable = observable.template lift<int>([&calls_internal](int val, const auto& sub) { ++calls_internal; sub.on_next(val); }); AND_WHEN("subscribe unsubscribed subscriber") { int calls_external = 0; auto subscriber = rpp::specific_subscriber{[&](int) { ++calls_external; }}; subscriber.unsubscribe(); new_observable.subscribe(subscriber); THEN("No any calls obtained") { CHECK(calls_internal == 0); CHECK(calls_external == 0); } } } WHEN("Call lift with exception") { auto new_observable = observable.template lift<int>([](int, const auto& ) { throw std::runtime_error{""}; }); AND_WHEN("subscribe subscriber") { auto mock = mock_observer<int>{}; new_observable.subscribe(mock); THEN("subscriber obtais on error") { CHECK(mock.get_total_on_next_count() == 0); CHECK(mock.get_on_error_count() == 1); CHECK(mock.get_on_completed_count() == 0); } } } WHEN("Call lift as lvalue") { auto initial_copy_count = verifier.get_copy_count(); auto initial_move_count = verifier.get_move_count(); auto new_observable = observable.lift([](rpp::dynamic_subscriber<double> sub) { return rpp::dynamic_subscriber{sub.get_subscription(), [sub](int val) { sub.on_next(static_cast<double>(val) / 2); }}; }); THEN("On subscribe obtain modified values") { std::vector<double> obtained_values{}; new_observable.subscribe([&](double v) { obtained_values.push_back(v); }); CHECK(obtained_values == std::vector{5.0, 2.5}); } if constexpr (!std::is_same_v<decltype(observable), rpp::dynamic_observable<int>>) { AND_THEN("One copy to lambda + one move to new observable") { CHECK(verifier.get_copy_count() == initial_copy_count +1); CHECK(verifier.get_move_count() == initial_move_count +1); } } } WHEN("Call lift as rvalue") { auto initial_copy_count = verifier.get_copy_count(); auto initial_move_count = verifier.get_move_count(); auto new_observable = std::move(observable).lift([](rpp::dynamic_subscriber<double> sub) { return rpp::specific_subscriber{sub.get_subscription(), [sub](int val) { sub.on_next(static_cast<double>(val) / 2); }}; }); THEN("On subscribe obtain modified values") { std::vector<double> obtained_values{}; new_observable.subscribe([&](double v) { obtained_values.push_back(v); }); CHECK(obtained_values == std::vector{5.0, 2.5}); } if constexpr (!std::is_same_v<decltype(observable), rpp::dynamic_observable<int>>) { AND_THEN("One move to lambda + one move to new observable") { CHECK(verifier.get_copy_count() == initial_copy_count); CHECK(verifier.get_move_count() == initial_move_count +2); } } } }; auto observable = rpp::observable::create<int>([verifier](const auto& sub) { sub.on_next(10); sub.on_next(5); sub.on_completed(); }); GIVEN("Observable") validate(observable); GIVEN("DynamicObservable") validate(observable.as_dynamic()); }
36.256944
107
0.500287
victimsnino
e070bf8609cf27f34b95d773ab77e70c6157a017
17,355
cpp
C++
src/zyre/zyre.cpp
staroy/gyro
3cc048af5605cf4aad50812733cebe1e0232c2f9
[ "MIT" ]
null
null
null
src/zyre/zyre.cpp
staroy/gyro
3cc048af5605cf4aad50812733cebe1e0232c2f9
[ "MIT" ]
null
null
null
src/zyre/zyre.cpp
staroy/gyro
3cc048af5605cf4aad50812733cebe1e0232c2f9
[ "MIT" ]
null
null
null
#include "zyre.hpp" #include "auth.h" #include <iostream> #include <boost/filesystem.hpp> #include "misc_log_ex.h" #include "sodium.h" #undef MONERO_DEFAULT_LOG_CATEGORY #define MONERO_DEFAULT_LOG_CATEGORY "zyre.cc" namespace zyre { void *server::ctx_ = nullptr; server::server( const std::string& name, const std::vector<std::string>& groups, const std::string& pin) : name_(name) , glist_(groups) , pin_(pin) , verbose_(false) { if(!ctx_) ctx_ = zsys_init(); terminated_ = false; for(const auto& g : groups) groups_[g] = 0; } void server::start() { thread_ = std::thread(std::bind(&server::run, this)); } void server::stop() { terminated_ = true; } void server::join() { thread_.join(); } void server::run() { std::set<std::string> scripts; zyre_t *node = zyre_new( name_.c_str() ); if (!node) { MLOG_RED(el::Level::Warning, "Could not create new zyre node"); return; } if(!pin_.empty()) { zyre_set_zap_domain(node, ("zap-" + name_).c_str()); zcert_t *cert = pin_to_cert(pin_); zyre_set_zcert(node, cert); zyre_set_header(node, "X-PUBLICKEY", "%s", zcert_public_txt(cert)); if(verbose_) zyre_set_verbose(node); zcert_destroy(&cert); } zyre_start(node); for(const auto& g : groups_) zyre_join(node, g.first.c_str()); // connection from inproc clients zsock_t *inproc = zsock_new_router((inproc_ZYRE "-" + name_).c_str()); zpoller_t *poller = zpoller_new(zyre_socket(node), inproc, NULL); while(!terminated_) { void *which = zpoller_wait(poller, 100); try { if(which == inproc) { zmsg_t *msg = zmsg_recv(which); if (!msg) { MLOG_RED(el::Level::Error, "Interrupted zyre node"); break; } zframe_t *src = zmsg_pop(msg); zframe_t *op = zmsg_pop(msg); if(zframe_streq(op, S_JOIN)) { char *name = zmsg_popstr(msg); auto s = scripts.find(name); if(s == scripts.end()) scripts.insert(name); zstr_free(&name); } else if(zframe_streq(op, S_LEAVE)) { char *name = zmsg_popstr(msg); auto s = scripts.find(name); if(s != scripts.end()) scripts.erase(s); zstr_free(&name); } else if(zframe_streq(op, JOIN)) { char *name = zmsg_popstr(msg); auto g = groups_.find(name); if(g == groups_.end()) { groups_[name] = 1; zyre_join(node, name); } else g->second++; zstr_free(&name); } else if(zframe_streq(op, LEAVE)) { char *name = zmsg_popstr(msg); auto g = groups_.find(name); if(g != groups_.end()) { if(g->second == 1) { groups_.erase(g); zyre_leave(node, name); } if(g->second > 1) g->second--; } zstr_free(&name); } else if(zframe_streq(op, inproc_SHOUT) || zframe_streq(op, inproc_WHISPER)) { zframe_t *dst = zmsg_pop(msg); zmsg_prepend(msg, &src); zmsg_prepend(msg, &op); zmsg_prepend(msg, &dst); zmsg_send(&msg, inproc); } else if(zframe_streq(op, SHOUT)) { char *group = zmsg_popstr(msg); zmsg_prepend(msg, &src); zyre_shout(node, group, &msg); zstr_free(&group); } else if(zframe_streq(op, WHISPER)) { char *peer = zmsg_popstr(msg); zmsg_prepend(msg, &src); zyre_whisper(node, peer, &msg); zstr_free(&peer); } else { MLOG_RED(el::Level::Error, "E: invalid message to zyre actor src=" << zframe_strdup(src) << " op=" << zframe_strdup(op)); } zmsg_destroy (&msg); } else if(which == zyre_socket(node)) { zmsg_t *msg = zmsg_recv(which); zframe_t *event = zmsg_first(msg); if(zframe_streq(event, SHOUT) || zframe_streq(event, WHISPER)) { //MLOG_GREEN(el::Level::Info, "zframe_streq(event, SHOUT) || zframe_streq(event, WHISPER) == true"); for(const auto& s : scripts) { zmsg_t *m = zmsg_dup(msg); zframe_t *n = zframe_from(s.c_str()); zmsg_prepend(m, &n); zmsg_send(&m, inproc); } } zmsg_destroy(&msg); } } catch(const std::exception& e) { MLOG_RED(el::Level::Error, e.what()); } catch(...) { MLOG_RED(el::Level::Error, "unqnow"); } } zpoller_destroy(&poller); zyre_stop (node); zclock_sleep (100); zyre_destroy (&node); zsock_destroy(&inproc); } zcert_t *server::pin_to_cert(const std::string& pin) { uint8_t salt[crypto_pwhash_scryptsalsa208sha256_SALTBYTES] = { 128,165, 28,003,132,201,031,250,142,184,186,024, 8,167,68,075, 053,231,105,160,230,167,144,201,176,158, 68,162,78,128,68,109 }; uint8_t seed[crypto_box_SEEDBYTES]; if(0 != ::crypto_pwhash_scryptsalsa208sha256( seed, crypto_box_SEEDBYTES, pin.c_str(), pin.length(), salt, crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_INTERACTIVE, crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_INTERACTIVE)) { MLOG_RED(el::Level::Error, "Could not create seed"); return nullptr; } uint8_t pk[crypto_box_PUBLICKEYBYTES]; uint8_t sk[crypto_box_SECRETKEYBYTES]; if(0 != ::crypto_box_seed_keypair(pk, sk, seed)) { MLOG_RED(el::Level::Error, "Could not create certificate"); return nullptr; } return zcert_new_from(pk, sk); } std::atomic<uint64_t> client::cookie_n_; client::client( boost::asio::io_service& ios, const std::string& name, const server& srv) : ios_(ios) , name_(name) , dev_(srv.name()) , zyre_sock_(zmq_socket(server::ctx(), ZMQ_DEALER)) , zyre_(ios, zyre_sock_) , reply_timeout_(3) // 3 sec { zyre_.set_option(azmq::socket::identity(name_.data(), name_.size())); zyre_.connect((inproc_ZYRE "-" + dev_).c_str()); } void client::s_join(const std::string& name) { if(ios_.stopped()) return; std::array<boost::asio::const_buffer, 2> data = {{ boost::asio::buffer(S_JOIN, sizeof(S_JOIN)-1), boost::asio::buffer(name.data(), name.size()) }}; zyre_.send(data); } void client::s_leave(const std::string& name) { if(ios_.stopped()) return; std::array<boost::asio::const_buffer, 2> data = {{ boost::asio::buffer(S_LEAVE, sizeof(S_LEAVE)-1), boost::asio::buffer(name.data(), name.size()) }}; zyre_.send(data); } void client::join(const std::string& name) { if(ios_.stopped()) return; for(const auto& g : groups_) if(g == name) return; std::array<boost::asio::const_buffer, 2> data = {{ boost::asio::buffer(JOIN, sizeof(JOIN)-1), boost::asio::buffer(name.data(), name.size()) }}; zyre_.send(data); groups_.push_back(name); } void client::leave(const std::string& name) { if(ios_.stopped()) return; for(auto it=groups_.begin(); it<groups_.end(); it++) if(*it == name) { std::array<boost::asio::const_buffer, 2> data = {{ boost::asio::buffer(LEAVE, sizeof(LEAVE)-1), boost::asio::buffer(name.data(), name.size()) }}; zyre_.send(data); groups_.erase(it); } } #define ERROR_SHORT_EVENT "error short event" void client::start() { zyre_.async_receive( [&](boost::system::error_code const& e, azmq::message& msg, size_t bc) { if(!ios_.stopped()) { try { if(e) throw std::runtime_error(e.message()); if(!msg.more() || bc == 0) throw std::runtime_error(ERROR_SHORT_EVENT); azmq::message_vector vec; boost::system::error_code ec; zyre_.receive_more(vec, 0, ec); if(ec) throw std::runtime_error(ec.message()); bool is_shout = false; bool is_whisper = false; bool is_local = false; std::string op = msg.string(); /*std::string v0 = vec[0].string(); std::string v1 = vec[1].string(); std::string v2 = vec[2].string(); std::string v3 = vec[3].string(); std::string v4 = vec[4].string(); std::string v5 = vec[5].string(); ZLOG(ERROR) << (std::string() + + "op=" + op + "\n" + "v0=" + v0 + "\n" + "v1=" + v1 + "\n" + "v2=" + v2 + "\n" + "v3=" + v3 + "\n" + "v4=" + v4 + "\n" + "v5=" + v5 + "\n");*/ if(op == SHOUT) is_shout = true; if(op == inproc_SHOUT) { is_shout = true; is_local = true; } if(op == WHISPER) is_whisper = true; if(op == inproc_WHISPER) { is_whisper = true; is_local = true; } size_t peer = size_t(-1), name = size_t(-1), group = size_t(-1), src = size_t(-1), cmd = size_t(-1), data = size_t(-1), n = 0; if(!is_local) { peer = n; n++; name = n; n++; if(is_shout) { group = n; n++; } src = n; n++; } else { peer = n; n++; } if (is_shout || is_whisper) { if(n+5 > vec.size()) throw std::runtime_error(ERROR_SHORT_EVENT); uint64_t ver_major = 0; uint64_t ver_minor = 0; msgpack::unpack(static_cast<const char *>(vec[n].data()), vec[n].size()) .get().convert(ver_major); n++; msgpack::unpack(static_cast<const char *>(vec[n].data()), vec[n].size()) .get().convert(ver_minor); n++; uint64_t cookie = 0; msgpack::unpack(static_cast<const char *>(vec[n].data()), vec[n].size()) .get().convert(cookie); n++; cmd = n; n++; data = n; n++; /*MLOG_RED(el::Level::Warning, (std::string("CLIENT ") + name_ + " RECEIVED\n" + "op=" + op + "\n" + "peer=" + vec[peer].string() + "\n" + "src=" + (src == size_t(-1) ? "" : vec[src].string()) + "\n" + "cmd=" + vec[cmd].string() + "\n" + "ver_major=" + std::to_string(ver_major) + "\n" + "ver_minor=" + std::to_string(ver_minor) + "\n" + "cookie=" + std::to_string(cookie)));*/ if(ver_minor == VER_MINOR && ver_major == VER_MAJOR) { std::string cmd_s = vec[cmd].string(); if(cmd_s == REPLY) { const auto& ri = reply_.find(cookie); if(ri != reply_.end()) ri->second.f(vec[data].string()); } else { const auto& f1 = meth_r_.find(cmd_s); if(f1 != meth_r_.end()) { std::string dd = vec[data].string(); f1->second(vec[data].string(), [&](const std::string& res){ do_send( is_local ? inproc_WHISPER : WHISPER, is_local ? sizeof(inproc_WHISPER)-1 : sizeof(WHISPER)-1, static_cast<const char*>(vec[peer].data()), vec[peer].size(), REPLY, sizeof(REPLY)-1, res.data(), res.size(), cookie); }); } else { const auto& f2 = meth_.find(cmd_s); if(f2 != meth_.end()) f2->second(vec[data].string()); } } } else { MLOG_RED(el::Level::Error, (std::string("CLIENT ") + name_ + " RECEIVED\n" + "Error version: name: " + (name == size_t(-1) ? "" : vec[name].string()) + "\n" + "peer: " + (peer == size_t(-1) ? "" : vec[peer].string()) + "\n" + "group: " + (group == size_t(-1) ? "" : vec[group].string()) + "\n" + "src: " + (src == size_t(-1) ? "" : vec[src].string()) + "\n" + "cmd: " + (cmd == size_t(-1) ? "" : vec[cmd].string()) + "\n" + "ver_major: " + std::to_string(ver_major) + "\n" + "ver_minor: " + std::to_string(ver_minor) + "\n" + "cookie: " + std::to_string(cookie) + "\n" + "cmd: " + (cmd == size_t(-1) ? "" : vec[cmd].string()))); return; } } // remove timeout replyes std::vector<std::map<uint64_t, r_info_t>::iterator> r_timeout; for(auto it=reply_.begin(); it!=reply_.end(); it++) if(it->second.t < time(nullptr)) r_timeout.push_back(it); for(auto it : r_timeout) reply_.erase(it); } catch(const std::exception& e) { MLOG_RED(el::Level::Error, e.what()); } catch(...) { MLOG_RED(el::Level::Error, "unqnow"); } start(); } }); } void client::stop() { if(zyre_sock_) { zmq_close(zyre_sock_); zyre_sock_ = nullptr; } } uint64_t client::do_send( const char *zyre_action_p, size_t zyre_action_sz, const char *peer_or_group_p, size_t peer_or_group_sz, const char *cmd_p, size_t cmd_sz, const char *params_p, size_t params_sz, uint64_t cookie) { if(ios_.stopped()) return cookie; std::stringstream ss_v1; msgpack::pack(ss_v1, uint64_t(VER_MAJOR)); std::string v1 = ss_v1.str(); std::stringstream ss_v2; msgpack::pack(ss_v2, uint64_t(VER_MINOR)); std::string v2 = ss_v2.str(); if(cookie == COOKIE_NEXT) { cookie_n_++; cookie = cookie_n_; } std::stringstream ss_cookie; msgpack::pack(ss_cookie, cookie); std::string cookie_s = ss_cookie.str(); std::array<boost::asio::const_buffer, 7> buf = {{ boost::asio::buffer(zyre_action_p, zyre_action_sz), boost::asio::buffer(peer_or_group_p, peer_or_group_sz), boost::asio::buffer(v1.data(), v1.size()), boost::asio::buffer(v2.data(), v2.size()), boost::asio::buffer(cookie_s.data(), cookie_s.size()), boost::asio::buffer(cmd_p, cmd_sz), boost::asio::buffer(params_p, params_sz) }}; boost::system::error_code ec; zyre_.send(buf, 0, ec); if(ec) throw std::runtime_error(ec.message()); return cookie; } void client::do_send(const std::string& zyre_action, const std::string& group, const std::string& cmd, const std::string& pars) { do_send( zyre_action.data(), zyre_action.size(), group.data(), group.size(), cmd.data(), cmd.size(), pars.data(), pars.size(), COOKIE_NEXT); } void client::do_send_r(const std::string& zyre_action, const std::string& group, const std::string& cmd, const func_t& r, const std::string& pars) { uint64_t cookie = do_send( zyre_action.data(), zyre_action.size(), group.data(), group.size(), cmd.data(), cmd.size(), pars.data(), pars.size(), COOKIE_NEXT); reply_[cookie] = { time(nullptr) + reply_timeout_, r }; } void client::do_send(const char *zyre_action, const char *group, char *cmd, const char *pars_p, size_t pars_sz) { do_send( zyre_action, strlen(zyre_action), group, strlen(group), cmd, strlen(cmd), pars_p, pars_sz, COOKIE_NEXT); } void client::do_send_r(const char *zyre_action, const char *group, char *cmd, const func_t& r, const char *pars_p, size_t pars_sz) { uint64_t cookie = do_send( zyre_action, strlen(zyre_action), group, strlen(group), cmd, strlen(cmd), pars_p, pars_sz, COOKIE_NEXT); reply_[cookie] = { time(nullptr) + reply_timeout_, r }; } void client::on(const std::string& cmd, const func_t& f) { meth_[cmd] = f; } void client::on_r(const std::string& cmd, const func_r_t& f) { meth_r_[cmd] = f; } }
29.666667
148
0.492711
staroy
e0748d77b416cedd619686df8638e1e61c33663c
26,624
cpp
C++
Source/FemPhysicsLinear.cpp
MihaiF/SolidFEM
58e08130e2f31be3b056c387ed03aab3b0b3db38
[ "BSD-3-Clause" ]
3
2020-05-19T10:59:01.000Z
2022-02-04T08:59:32.000Z
Source/FemPhysicsLinear.cpp
MihaiF/SolidFEM
58e08130e2f31be3b056c387ed03aab3b0b3db38
[ "BSD-3-Clause" ]
null
null
null
Source/FemPhysicsLinear.cpp
MihaiF/SolidFEM
58e08130e2f31be3b056c387ed03aab3b0b3db38
[ "BSD-3-Clause" ]
1
2019-11-08T16:14:53.000Z
2019-11-08T16:14:53.000Z
/* BSD 3-Clause License Copyright (c) 2019, Mihai Francu All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "FemPhysicsLinear.h" #include "MeshFactory.h" #include "TetrahedralMesh.h" #include <Engine/Profiler.h> #pragma warning( disable : 4244) // for double-float conversions #pragma warning( disable : 4267) // for size_t-uint conversions // References: // [Weber] Weber, D. et al., Interactive deformable models with quadratic bases in Bernstein-Bezier form // TODO: add Rayleigh damping namespace FEM_SYSTEM { FemPhysicsLinear::FemPhysicsLinear(const std::vector<Tet>& tetrahedra, const std::vector<Node>& nodes, const FemConfig& config) : FemPhysicsBase(config) , mOrder(config.mOrder) , mUseLumpedMass(true) { ASSERT(tetrahedra.size() != 0); ASSERT(nodes.size() != 0); CreateMeshAndDofs(tetrahedra, nodes); mElementVolumes.resize(GetNumElements()); mBarycentricJacobians.resize(GetNumElements()); for (uint32 e = 0; e < GetNumElements(); e++) { ComputeBarycentricJacobian(e, mBarycentricJacobians[e].y); } if (mSimType > ST_QUASI_STATIC) AssembleMassMatrix(); mBodyForces.resize(GetNumFreeNodes()); ComputeBodyForces(mBodyForces); } void FemPhysicsLinear::CreateMeshAndDofs(const std::vector<Tet>& tetrahedra, const std::vector<Node>& nodes) { #ifdef LOG_TIMES Printf(("----- FemPhysicsAnyOrderCorotationalElasticity for order " + std::to_string(order) + "\n").c_str()); #endif // LOG_TIMES // 1. Build the higher order mesh/convert to a TetrahedralMesh instance // use the linear mesh stored as an array of Tetrahedron in the base class StridedVector<uint32> stridedVec(&(tetrahedra[0].idx[0]), (uint)tetrahedra.size(), sizeof(Tet)); double mesh_time; TetrahedralMesh<uint32>* tetMesh = nullptr; { MEASURE_TIME_P("mesh_time", mesh_time); tetMesh = MeshFactory::MakeMesh<TetrahedralMesh<uint32>>(mOrder, nodes.size(), stridedVec, tetrahedra.size()); mTetMesh.reset(tetMesh); } std::vector<Vector3R> points(nodes.size()); std::vector<Vector3R> points0(nodes.size()); double other_time = 0; { MEASURE_TIME_P("other_time", other_time); // 2. Compute the interpolated positions // copy over the node positions of the linear mesh to a linear array // TODO: could use a strided vector instead for (uint32 i = 0; i < nodes.size(); i++) { points[i] = nodes[i].pos; points0[i] = nodes[i].pos0; } } std::vector<Vector3R> interpolatedPositions(GetNumNodes()); std::vector<Vector3R> interpolatedPositions0(GetNumNodes()); double interpolate_time; { MEASURE_TIME_P("interpolate_time", interpolate_time); // interpolate the mesh node positions (for the given order) // the first resulting nodes are the same as in the linear mesh MeshFactory::Interpolate<TetrahedralMesh<uint32>, Vector3R>(*tetMesh, &points[0], &interpolatedPositions[0]); MeshFactory::Interpolate<TetrahedralMesh<uint32>, Vector3R>(*tetMesh, &points0[0], &interpolatedPositions0[0]); } std::vector<bool> fixed(GetNumNodes(), false); double other_time2 = 0; { MEASURE_TIME_P("other_time2", other_time2); // 3. Mark all boundary nodes // initialize the fixed flags array for (uint32 i = 0; i < nodes.size(); i++) { fixed[i] = nodes[i].invMass == 0; } } other_time += other_time2; double boundary_time = 0; { MEASURE_TIME_P("boundary_time", boundary_time); // 3.5 Check the higher order nodes and ensure that the expected leftmost cantilever nodes are marked fixed if (mOrder > 1) { for (uint32 e = 0; e < GetNumElements(); e++) { // TODO These are hacky solutions, need supported iterators from the mesh class.. // First check all edge nodes std::tuple<int, int> edge_pairs[]{ std::make_tuple(0, 1), std::make_tuple(0, 2), std::make_tuple(0, 3), std::make_tuple(1, 2), std::make_tuple(1, 3), std::make_tuple(2, 3) }; int no_nodes_pr_edge = mTetMesh->GetNodesPerEdge(mOrder); int edge_startidx = 4; for (int i = 0; i < 6; i++) { int c1, c2; std::tie(c1, c2) = edge_pairs[i]; uint32 gidx_c1 = mTetMesh->GetGlobalIndex(e, c1); uint32 gidx_c2 = mTetMesh->GetGlobalIndex(e, c2); //if (nodes[gidx_c1].invMass == 0 && nodes[gidx_c2].invMass == 0) if (fixed[gidx_c1] && fixed[gidx_c2]) { for (int j = 0; j < no_nodes_pr_edge; j++) { int edge_lidx = edge_startidx + i * no_nodes_pr_edge + j; uint32 gidx_edgej = mTetMesh->GetGlobalIndex(e, edge_lidx); fixed[gidx_edgej] = true; } } } // Then check all face nodes, if any std::tuple<int, int, int> face_pairs[]{ std::make_tuple(0, 1, 2), std::make_tuple(0, 1, 3), std::make_tuple(0, 2, 3), std::make_tuple(1, 2, 3) }; int no_nodes_pr_face = mTetMesh->GetNodesPerFace(mOrder); int face_startidx = 4 + no_nodes_pr_edge * 6; for (int i = 0; i < 4; i++) { int c1, c2, c3; std::tie(c1, c2, c3) = face_pairs[i]; uint32 gidx_c1 = mTetMesh->GetGlobalIndex(e, c1); uint32 gidx_c2 = mTetMesh->GetGlobalIndex(e, c2); uint32 gidx_c3 = mTetMesh->GetGlobalIndex(e, c3); if (fixed[gidx_c1] && fixed[gidx_c2] && fixed[gidx_c3]) { for (int j = 0; j < no_nodes_pr_face; j++) { int face_lidx = face_startidx + i * no_nodes_pr_face + j; uint32 gidx_facej = mTetMesh->GetGlobalIndex(e, face_lidx); fixed[gidx_facej] = true; } } } } } } // 4. Create a index-mapping from mesh-global-index to index into the mReferencePosition and mDeformedPositions vectors // - this is too allow all of the fixed nodes to be listed first in the two vectors. double other_time3 = 0; { MEASURE_TIME_P("other_time3", other_time3); #ifdef USE_CONSTRAINT_BCS // create the reference positions - first ones are the fixed ones mReferencePositions.resize(GetNumNodes()); mReshuffleMap.resize(GetNumNodes()); mReshuffleMapInv.resize(GetNumNodes()); for (uint32 i = 0; i < GetNumNodes(); i++) { mReferencePositions[i] = interpolatedPositions0[i]; mReshuffleMap[i] = i; mReshuffleMapInv[i] = i; } // create a mapping with the fixed nodes first for (uint32 i = 0; i < fixed.size(); i++) { if (fixed[i]) { AddDirichletBC(i, AXIS_X | AXIS_Y | AXIS_Z); } } mNumBCs = 0; #else // create a mapping with the fixed nodes first mReshuffleMapInv.clear(); for (uint32 i = 0; i < fixed.size(); i++) { if (fixed[i]) mReshuffleMapInv.push_back(i); } mNumBCs = mReshuffleMapInv.size(); for (uint32 i = 0; i < fixed.size(); i++) { if (!fixed[i]) mReshuffleMapInv.push_back(i); } // create the reference positions - first ones are the fixed ones mReferencePositions.resize(GetNumNodes()); mReshuffleMap.resize(GetNumNodes()); for (uint32 i = 0; i < GetNumNodes(); i++) { uint32 idx = mReshuffleMapInv[i]; mReferencePositions[i] = interpolatedPositions0[idx]; mReshuffleMap[idx] = i; } #endif // 5. Copy the mReferencePositions into mDeformedPositions, to initialize it // - note that mDeformedPositions does not contain the boundary/fixed nodes. // create a vector of deformed positions (dofs) // the first mNumBCs nodes are fixed so we only consider the remaining ones mDeformedPositions.resize(GetNumFreeNodes()); for (uint32 i = 0; i < GetNumFreeNodes(); i++) { uint32 idx = mReshuffleMapInv[i + mNumBCs]; mDeformedPositions[i] = interpolatedPositions[idx]; } // 6. Initialize the velocities vector, note that it does not consider the fixed nodes either // velocities should be zero by construction mVelocities.resize(GetNumFreeNodes()); for (uint32 i = mNumBCs; i < nodes.size(); i++) { int idx = mReshuffleMapInv[i]; mVelocities[i - mNumBCs] = nodes[idx].vel; } // initialize initial displacements vector (mostly for non-zero displacements) mInitialDisplacements.resize(mNumBCs); for (uint32 i = 0; i < mNumBCs; i++) { int idx = mReshuffleMapInv[i]; mInitialDisplacements[i] = interpolatedPositions[idx] - interpolatedPositions0[idx]; } } other_time += other_time3; } void FemPhysicsLinear::UpdatePositions(std::vector<Node>& nodes) { // re-interpolate the current positions on the potentially high-order mesh std::vector<Vector3R> points(nodes.size()); //double other_time; { //MEASURE_TIME_P("other_time", other_time); // 2. Compute the interpolated positions // copy over the node positions of the linear mesh to a linear array // TODO: could use a strided vector instead for (uint32 i = 0; i < nodes.size(); i++) { points[i] = nodes[i].pos; } } std::vector<Vector3R> interpolatedPositions(GetNumNodes()); //double interpolate_time; { //MEASURE_TIME_P("interpolate_time", interpolate_time); // interpolate the mesh node positions (for the given order) // the first resulting nodes are the same as in the linear mesh //MeshFactory::Interpolate(*mTetMesh, &points[0], &interpolatedPositions[0]); interpolatedPositions = points; } for (uint32 i = 0; i < GetNumNodes(); i++) { int idx = mReshuffleMapInv[i]; if (i < mNumBCs) mInitialDisplacements[i] = interpolatedPositions[idx] - mReferencePositions[i]; } } void FemPhysicsLinear::ComputeBarycentricJacobian(uint32 i, Vector3R y[4]) { uint32 i0 = mTetMesh->GetGlobalIndex(i, 0); uint32 i1 = mTetMesh->GetGlobalIndex(i, 1); uint32 i2 = mTetMesh->GetGlobalIndex(i, 2); uint32 i3 = mTetMesh->GetGlobalIndex(i, 3); const Vector3R& x0 = mReferencePositions[mReshuffleMap[i0]]; const Vector3R& x1 = mReferencePositions[mReshuffleMap[i1]]; const Vector3R& x2 = mReferencePositions[mReshuffleMap[i2]]; const Vector3R& x3 = mReferencePositions[mReshuffleMap[i3]]; Vector3R d1 = x1 - x0; Vector3R d2 = x2 - x0; Vector3R d3 = x3 - x0; Matrix3R mat(d1, d2, d3); // this is the reference shape matrix Dm [Sifakis][Teran] Matrix3R X = mat.GetInverse(); // Dm^-1 real vol = (mat.Determinant()) / 6.f; // volume of the tet mElementVolumes[i] = vol; // compute the gradient of the shape functions [Erleben][Mueller] y[1] = X[0]; y[2] = X[1]; y[3] = X[2]; y[0] = y[1] + y[2] + y[3]; y[0].Flip(); } real FemPhysicsLinear::GetTotalVolume() const { real totalVol = 0; for (uint32 e = 0; e < GetNumElements(); e++) { uint32 i0 = mTetMesh->GetGlobalIndex(e, 0); uint32 i1 = mTetMesh->GetGlobalIndex(e, 1); uint32 i2 = mTetMesh->GetGlobalIndex(e, 2); uint32 i3 = mTetMesh->GetGlobalIndex(e, 3); const Vector3R& x0 = GetDeformedPosition(i0); const Vector3R& x1 = GetDeformedPosition(i1); const Vector3R& x2 = GetDeformedPosition(i2); const Vector3R& x3 = GetDeformedPosition(i3); Vector3R d1 = x1 - x0; Vector3R d2 = x2 - x0; Vector3R d3 = x3 - x0; Matrix3R mat(d1, d2, d3); // this is the spatial shape matrix Ds [Sifakis][Teran] real vol = abs(mat.Determinant()) / 6.f; // volume of the tet totalVol += vol; } return totalVol; } void FemPhysicsLinear::ComputeStrainJacobian(uint32 i, Matrix3R Bn[4], Matrix3R Bs[4]) { Vector3R* y = mBarycentricJacobians[i].y; // compute the Cauchy strain Jacobian matrix according to [Mueller]: B = de/dx for (int j = 0; j < 4; j++) { Bn[j] = Matrix3R(y[j]); // diagonal matrix Bs[j] = Symm(y[j]); } } // compute local mass matrix (using linear shape functions) void ComputeLocalMassMatrix(real density, uint32 numLocalNodes, EigenMatrix& Mlocal) { // this is actually wrong for (i,i) terms - see ComputeLocalMassMatrixBB1 ASSERT(numLocalNodes == 4); real massDiv = density / 20.f; for (size_t i = 0; i < numLocalNodes; i++) { size_t offsetI = i * 3; for (size_t j = 0; j < numLocalNodes; j++) { size_t offsetJ = j * 3; // build a diagonal matrix for (size_t k = 0; k < 3; k++) Mlocal(offsetI + k, offsetJ + k) = (i == j) ? 2 * massDiv : massDiv; } } //std::cout << "Mlocal" << std::endl << Mlocal << std::endl; } void ComputeLocalMassMatrixLumped(real density, uint32 numLocalNodes, EigenMatrix& Mlocal) { // this is actually wrong for (i,i) terms - see ComputeLocalMassMatrixBB1 ASSERT(numLocalNodes == 4); // 4x4 identity blocks times the total mass / 20 real massDiv = density / 4.0; for (size_t i = 0; i < numLocalNodes * 3; i++) { Mlocal(i, i) = massDiv; } } // // compute local mass matrix using any order Bernstein-Bezier shape functions void FemPhysicsLinear::ComputeLocalMassMatrixBB(real density, uint32 numLocalNodes, EigenMatrix& Mlocal) { int *i_ijkl, *j_mnop; size_t i, j, k; real factor = density * (1.f / Binom(2 * mOrder + 3, 3)); for (i = 0; i < numLocalNodes; i++) { i_ijkl = mTetMesh->GetIJKL(i); for (j = 0; j < numLocalNodes; j++) { j_mnop = mTetMesh->GetIJKL(j); real mass = factor * G(i_ijkl, j_mnop, mOrder); for (k = 0; k < 3; k++) { Mlocal(i * 3 + k, j * 3 + k) = mass; } } } } // compute local mass matrix using quadratic Bernstein-Bezier shape functions void FemPhysicsLinear::ComputeLocalMassMatrixBB2(real density, uint32 numLocalNodes, EigenMatrix& Mlocal) { ASSERT(numLocalNodes == 10); for (size_t i = 0; i < numLocalNodes; i++) { size_t offsetI = i * 3; auto multiIndexI = mTetMesh->GetIJKL(i); for (size_t j = 0; j < numLocalNodes; j++) { //if (i != j) continue; auto multiIndexJ = mTetMesh->GetIJKL(j); uint32 c1 = Combinations(multiIndexI[0] + multiIndexJ[0], multiIndexI[0]); uint32 c2 = Combinations(multiIndexI[1] + multiIndexJ[1], multiIndexI[1]); uint32 c3 = Combinations(multiIndexI[2] + multiIndexJ[2], multiIndexI[2]); uint32 c4 = Combinations(multiIndexI[3] + multiIndexJ[3], multiIndexI[3]); real massDiv = c1 * c2 * c3 * c4 * density / 210.f; //real massDiv = density * ComputeMultiIndexSumFactor(2, multiIndexI, multiIndexJ) / 10.f; // build a diagonal matrix size_t offsetJ = j * 3; for (size_t k = 0; k < 3; k++) Mlocal(offsetI + k, offsetJ + k) = massDiv; } } } // assemble the global mass matrix void FemPhysicsLinear::AssembleMassMatrix() { // compute the local mass matrix first size_t numLocalNodes = GetNumLocalNodes(); size_t numLocalDofs = NUM_POS_COMPONENTS * numLocalNodes; // !NOTE assumed to be constant/equal for all tetrahedrons (except for the volume) -> true for linear rest shapes and subparametric formulation EigenMatrix Mlocal(numLocalDofs, numLocalDofs); Mlocal.setZero(); if (mOrder == 1 && mUseLumpedMass) ComputeLocalMassMatrixLumped(mDensity, numLocalNodes, Mlocal); else ComputeLocalMassMatrixBB(mDensity, numLocalNodes, Mlocal); size_t numNodes = GetNumFreeNodes(); size_t numDofs = numNodes * 3; EigenMatrix M(numDofs, numDofs); M.setZero(); for (size_t i = 0; i < GetNumElements(); i++) { real vol = mElementVolumes[i]; // for every local node there corresponds a 3x3 block matrix // we go through all of these blocks so that we know what the current pair is for (size_t j = 0; j < numLocalNodes; j++) { for (size_t k = 0; k < numLocalNodes; k++) { size_t jGlobal = mReshuffleMap[mTetMesh->GetGlobalIndex(i, j)]; size_t kGlobal = mReshuffleMap[mTetMesh->GetGlobalIndex(i, k)]; // do not add to the global matrix if at least one of the nodes is fixed if (jGlobal < mNumBCs || kGlobal < mNumBCs) continue; // add the local 3x3 matrix to the global matrix int jOffset = (jGlobal - mNumBCs) * NUM_POS_COMPONENTS; int kOffset = (kGlobal - mNumBCs) * NUM_POS_COMPONENTS; for (size_t x = 0; x < NUM_POS_COMPONENTS; x++) { for (size_t y = 0; y < NUM_POS_COMPONENTS; y++) { M.coeffRef(jOffset + x, kOffset + y) += vol * Mlocal(j * NUM_POS_COMPONENTS + x, k * NUM_POS_COMPONENTS + y); } } } } } mMassMatrix = M.sparseView(); } // compute the contribution of gravity (as a force distribution) to the current forces (using BB shape functions) void FemPhysicsLinear::ComputeBodyForces(Vector3Array& f) { Vector3R flocal = mDensity * mGravity * (1.f / Binom(mOrder + 3, 3)); for (size_t e = 0; e < GetNumElements(); e++) { // We note that the body force is constant across the element. real vol = mElementVolumes[e]; Vector3R bforce = vol * flocal; for (size_t i = 0; i < GetNumLocalNodes(); i++) { size_t globalI = mReshuffleMap[mTetMesh->GetGlobalIndex(e, i)]; if (globalI < mNumBCs) continue; int offset = (globalI - mNumBCs); f[offset] += bforce; } } } void FemPhysicsLinear::ComputeDeformationGradient(uint32 e, Matrix3R& F) const { // compute deformed/spatial shape matrix Ds [Sifakis] uint32 i0 = mTetMesh->GetGlobalIndex(e, 0); uint32 i1 = mTetMesh->GetGlobalIndex(e, 1); uint32 i2 = mTetMesh->GetGlobalIndex(e, 2); uint32 i3 = mTetMesh->GetGlobalIndex(e, 3); // TODO: avoid calling virtual function const Vector3R& x0 = GetDeformedPosition(i0); const Vector3R& x1 = GetDeformedPosition(i1); const Vector3R& x2 = GetDeformedPosition(i2); const Vector3R& x3 = GetDeformedPosition(i3); Vector3R d1 = x1 - x0; Vector3R d2 = x2 - x0; Vector3R d3 = x3 - x0; Matrix3R Ds(d1, d2, d3); Matrix3R X(mBarycentricJacobians[e].y[1], mBarycentricJacobians[e].y[2], mBarycentricJacobians[e].y[3]); // compute deformation gradient F = Ds * !X; } // computes the local stiffness matrix using Bernstein-Bezier polynomials given the Lame parameters void FemPhysicsLinear::ComputeLocalStiffnessMatrixBB(uint32 elementidx, real mu, real lambda, EigenMatrix& Klocal) { uint32 numLocalNodes = GetNumLocalNodes(); uint32 NUM_POS_COMPONENTS = 3; Klocal = EigenMatrix(numLocalNodes * NUM_POS_COMPONENTS, numLocalNodes * NUM_POS_COMPONENTS); Vector3R* barycentric_over_x = mBarycentricJacobians[elementidx].y; real common_factor = (3.f * mOrder * mElementVolumes[elementidx]) / (4.f * mOrder * mOrder - 1.f); for (uint32 i = 0; i < GetNumLocalNodes(); i++) { int *i_ijkl = mTetMesh->GetIJKL(i); int ijkl_c[4]{ 0 }; memcpy(ijkl_c, i_ijkl, 4 * sizeof(int)); for (uint32 j = 0; j < GetNumLocalNodes(); j++) { int *j_mnop = mTetMesh->GetIJKL(j); int mnop_d[4]{ 0 }; memcpy(mnop_d, j_mnop, 4 * sizeof(int)); for (uint32 a = 0; a < NUM_POS_COMPONENTS; a++) { for (uint32 b = 0; b < NUM_POS_COMPONENTS; b++) { real sum1 = 0; for (int c = 0; c < 4; c++) { ijkl_c[c] -= 1; for (int d = 0; d < 4; d++) { mnop_d[d] -= 1; sum1 += barycentric_over_x[c][a] * barycentric_over_x[d][b] * ComputeMultiIndexSumFactor(mOrder - 1, ijkl_c, mnop_d); mnop_d[d] += 1; } ijkl_c[c] += 1; } real sum2 = 0; for (int c = 0; c < 4; c++) { ijkl_c[c] -= 1; for (int d = 0; d < 4; d++) { mnop_d[d] -= 1; sum2 += barycentric_over_x[c][b] * barycentric_over_x[d][a] * ComputeMultiIndexSumFactor(mOrder - 1, ijkl_c, mnop_d); mnop_d[d] += 1; } ijkl_c[c] += 1; } real sum3 = 0; if (a == b) { for (int c = 0; c < 4; c++) { ijkl_c[c] -= 1; for (int d = 0; d < 4; d++) { mnop_d[d] -= 1; real Gv = ComputeMultiIndexSumFactor(mOrder - 1, ijkl_c, mnop_d); for (int k = 0; k < 3; k++) { sum3 += barycentric_over_x[c][k] * barycentric_over_x[d][k] * Gv; } mnop_d[d] += 1; } ijkl_c[c] += 1; } } real V_ij_ab = lambda * common_factor * sum1; real U_ij_ab = mu * common_factor * sum2; real W_ij_ab = mu * common_factor * sum3; real K_ij_ab = V_ij_ab + U_ij_ab + W_ij_ab; Klocal(i * NUM_POS_COMPONENTS + a, j * NUM_POS_COMPONENTS + b) = K_ij_ab; } } } } } void FemPhysicsLinear::SetBoundaryConditionsSurface(const std::vector<uint32>& triangleList, real pressure) { mAppliedPressure = pressure; mTractionSurface.clear(); for (uint32 i = 0; i < triangleList.size(); i += 3) { int idx1 = mReshuffleMap[triangleList[i]] - mNumBCs; int idx2 = mReshuffleMap[triangleList[i + 1]] - mNumBCs; int idx3 = mReshuffleMap[triangleList[i + 2]] - mNumBCs; if (idx1 >= 0 && idx2 >= 0 && idx3 >= 0) { mTractionSurface.push_back(idx1); mTractionSurface.push_back(idx2); mTractionSurface.push_back(idx3); } } } void FemPhysicsLinear::AssembleTractionStiffnessMatrixFD() { uint32 numNodes = GetNumFreeNodes(); uint32 numDofs = numNodes * 3; mTractionStiffnessMatrix.resize(numDofs, numDofs); mTractionStiffnessMatrix.setZero(); // current pressure forces ComputeTractionForces(); EigenVector fp0 = GetEigenVector(mTractionForces); real eps = 1e-6; for (uint32 j = 0; j < numDofs; j++) { mDeformedPositions[j / 3][j % 3] += eps; ComputeTractionForces(); EigenVector fp = GetEigenVector(mTractionForces); auto dfp = (1.0 / eps) * (fp - fp0); for (uint32 i = 0; i < numDofs; i++) { mTractionStiffnessMatrix(i, j) = dfp(i); } mDeformedPositions[j / 3][j % 3] -= eps; } } void FemPhysicsLinear::ComputeTractionForces() { if (mTractionSurface.empty()) return; if (mUseImplicitPressureForces) { uint32 numDofs = GetNumFreeNodes() * NUM_POS_COMPONENTS; mTractionStiffnessMatrix.resize(numDofs, numDofs); mTractionStiffnessMatrix.setZero(); } // accumulate forces mTractionForces.resize(GetNumFreeNodes()); for (uint32 i = 0; i < mTractionForces.size(); i++) mTractionForces[i].SetZero(); auto computeForce = [&](const Vector3R& p1, const Vector3R& p2, const Vector3R& p3)->Vector3R { Vector3R a = p2 - p1; Vector3R b = p3 - p1; Vector3R normal = cross(a, b); real area = 0.5f * normal.Length(); normal.Normalize(); Vector3R traction = mAppliedPressure * normal; Vector3R force = (area / 3.0f) * traction; return force; }; // go through all inner boundary triangles for (uint32 t = 0; t < mTractionSurface.size() / 3; t++) { int base = t * 3; // global (shuffled) indices of nodes uint32 i1 = mTractionSurface[base]; uint32 i2 = mTractionSurface[base + 1]; uint32 i3 = mTractionSurface[base + 2]; // compute triangle area and normal const Vector3R& p1 = mDeformedPositions[i1]; const Vector3R& p2 = mDeformedPositions[i2]; const Vector3R& p3 = mDeformedPositions[i3]; // apply traction to triangle nodes Vector3R force = computeForce(p1, p2, p3); mTractionForces[i1] += force; mTractionForces[i2] += force; mTractionForces[i3] += force; if (mUseImplicitPressureForces) { // compute local stiffness matrix Matrix3R K[3]; Vector3R a = p2 - p1; Vector3R b = p3 - p1; a.Scale(mAppliedPressure / 6.0f); b.Scale(mAppliedPressure / 6.0f); K[2] = Matrix3R::Skew(a); K[1] = Matrix3R::Skew(-b); K[0] = -K[1] - K[2]; // finite difference approximation - for verification purposes //real dx = 1e-4f; //real invDx = 1.f / dx; //Vector3R dfdx = invDx * (computeForce(p1, p2, p3 + Vector3R(dx, 0, 0)) - force); //Vector3R dfdy = invDx * (computeForce(p1, p2, p3 + Vector3R(0, dx, 0)) - force); //Vector3R dfdz = invDx * (computeForce(p1, p2, p3 + Vector3R(0, 0, dx)) - force); //Matrix3 K2(dfdx, dfdy, dfdz); //dfdx = invDx * (computeForce(p1, p2 + Vector3R(dx, 0, 0), p3) - force); //dfdy = invDx * (computeForce(p1, p2 + Vector3R(0, dx, 0), p3) - force); //dfdz = invDx * (computeForce(p1, p2 + Vector3R(0, 0, dx), p3) - force); //Matrix3 K1(dfdx, dfdy, dfdz); //dfdx = invDx * (computeForce(p1 + Vector3R(dx, 0, 0), p2, p3) - force); //dfdy = invDx * (computeForce(p1 + Vector3R(0, dx, 0), p2, p3) - force); //dfdz = invDx * (computeForce(p1 + Vector3R(0, 0, dx), p2, p3) - force); //Matrix3 K0(dfdx, dfdy, dfdz); // assemble global stiffness matrix for (uint32 x = 0; x < 3; x++) { for (uint32 y = 0; y < 3; y++) { mTractionStiffnessMatrix(i1 * 3 + x, i1 * 3 + y) += K[0](x, y); mTractionStiffnessMatrix(i1 * 3 + x, i2 * 3 + y) += K[1](x, y); mTractionStiffnessMatrix(i1 * 3 + x, i3 * 3 + y) += K[2](x, y); mTractionStiffnessMatrix(i2 * 3 + x, i1 * 3 + y) += K[0](x, y); mTractionStiffnessMatrix(i2 * 3 + x, i2 * 3 + y) += K[1](x, y); mTractionStiffnessMatrix(i2 * 3 + x, i3 * 3 + y) += K[2](x, y); mTractionStiffnessMatrix(i3 * 3 + x, i1 * 3 + y) += K[0](x, y); mTractionStiffnessMatrix(i3 * 3 + x, i2 * 3 + y) += K[1](x, y); mTractionStiffnessMatrix(i3 * 3 + x, i3 * 3 + y) += K[2](x, y); } } } } } EigenVector FemPhysicsLinear::ComputeLoadingForces() { // add the gravity forces EigenVector f = GetEigenVector(mBodyForces); // add boundary traction forces ComputeTractionForces(); if (mTractionForces.size() > 0) { f += GetEigenVector(mTractionForces); } f *= mForceFraction; // slow application of forces return f; } } // namespace FEM_SYSTEM
33.829733
145
0.654485
MihaiF
2fdd9b4502588839b2fc890eccd9542edf134894
625
cpp
C++
hash/hash_test.cpp
hjinlin/toft
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
[ "BSD-3-Clause" ]
264
2015-01-03T11:50:17.000Z
2022-03-17T02:38:34.000Z
hash/hash_test.cpp
hjinlin/toft
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
[ "BSD-3-Clause" ]
12
2015-04-27T15:17:34.000Z
2021-05-01T04:31:18.000Z
hash/hash_test.cpp
hjinlin/toft
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
[ "BSD-3-Clause" ]
128
2015-02-07T18:13:10.000Z
2022-02-21T14:24:14.000Z
// Copyright (c) 2013, The Toft Authors. All rights reserved. // Author: Ye Shunping <yeshunping@gmail.com> #include <string> #include "toft/hash/hash.h" #include "thirdparty/gtest/gtest.h" namespace toft { TEST(HashUnittest, Fingerprint) { const std::string& url = "http://app.kid.qq.com/exam/5528/5528_103392.htm"; uint64_t hash_value = Fingerprint64(url); EXPECT_EQ(hash_value, 17105673616436300159UL); std::string str = Fingerprint64ToString(hash_value); EXPECT_EQ(str, "7F09753F868F63ED"); uint64_t hash2 = StringToFingerprint64(str); EXPECT_EQ(hash_value, hash2); } } // namespace toft
29.761905
79
0.7264
hjinlin
2fddce6a0d5df9e95639c4bfb13c1be6925b3aa3
2,011
hpp
C++
labs/parallel_merge/helper.hpp
amirsojoodi/gpu-algorithms-labs
27993d0f40822d7195ada79645ca1ed7dd875803
[ "NCSA" ]
23
2019-01-15T23:13:22.000Z
2022-03-18T05:25:11.000Z
labs/parallel_merge/helper.hpp
amirsojoodi/gpu-algorithms-labs
27993d0f40822d7195ada79645ca1ed7dd875803
[ "NCSA" ]
9
2019-01-15T22:25:02.000Z
2021-07-15T16:59:49.000Z
labs/parallel_merge/helper.hpp
amirsojoodi/gpu-algorithms-labs
27993d0f40822d7195ada79645ca1ed7dd875803
[ "NCSA" ]
19
2019-01-22T17:09:00.000Z
2022-03-10T11:57:05.000Z
#pragma once #define CATCH_CONFIG_CPP11_TO_STRING #define CATCH_CONFIG_COLOUR_ANSI #define CATCH_CONFIG_MAIN #include "common/catch.hpp" #include "common/fmt.hpp" #include "common/utils.hpp" #include "assert.h" #include "stdint.h" #include "stdio.h" #include "stdlib.h" #include "string.h" #include <algorithm> #include <random> #include <string> #include <chrono> #include <cuda.h> static bool verify(const std::vector<float> &ref_sol, const std::vector<float> &sol) { for (size_t i = 0; i < ref_sol.size(); i++) { INFO("Merge results differ from reference solution."); REQUIRE(ref_sol[i] == sol[i]); } return true; } static std::chrono::time_point<std::chrono::high_resolution_clock> now() { return std::chrono::high_resolution_clock::now(); } #define CUDA_RUNTIME(stmt) checkCuda(stmt, __FILE__, __LINE__); void checkCuda(cudaError_t result, const char *file, const int line) { if (result != cudaSuccess) { LOG(critical, std::string(fmt::format("{}@{}: CUDA Runtime Error: {}\n", file, line, cudaGetErrorString(result)))); exit(-1); } } void generate_input(std::vector<float> &A_h, const std::pair<float, float> &A_range, std::vector<float> &B_h, const std::pair<float, float> &B_range) { std::random_device rd; //Will be used to obtain a seed for the random number engine std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd() std::uniform_real_distribution<float> dis_A(A_range.first, A_range.second); std::uniform_real_distribution<float> dis_B(B_range.first, B_range.second); std::generate(A_h.begin(), A_h.end(), std::bind(dis_A, std::ref(gen))); std::generate(B_h.begin(), B_h.end(), std::bind(dis_B, std::ref(gen))); std::sort(A_h.begin(), A_h.end()); std::sort(B_h.begin(), B_h.end()); } static void print_vector(const std::vector<float> vec) { for (const auto &elem : vec) { std::cout << elem << ' '; } std::cout << "" << '\n'; }
30.469697
151
0.663352
amirsojoodi
2fdf0ec1e8a7781618bdc3ca01cfa62307675cde
410
cpp
C++
tests/doc/vector3d/vector3d-3.cpp
jmintser/chemfiles
fb1ed5ee47790cc004468e5484954e2b3d1adff2
[ "BSD-3-Clause" ]
116
2015-11-05T01:18:13.000Z
2022-02-20T06:33:47.000Z
tests/doc/vector3d/vector3d-3.cpp
jmintser/chemfiles
fb1ed5ee47790cc004468e5484954e2b3d1adff2
[ "BSD-3-Clause" ]
307
2015-10-08T09:22:46.000Z
2022-03-28T13:42:51.000Z
tests/doc/vector3d/vector3d-3.cpp
Luthaf/Chemharp
d41036ff5645954bd691f868f066c760560eee13
[ "BSD-3-Clause" ]
57
2015-10-22T06:45:40.000Z
2022-03-27T17:33:05.000Z
// Chemfiles, a modern library for chemistry file reading and writing // Copyright (C) Guillaume Fraux and contributors -- BSD license #include <catch.hpp> #include <chemfiles.hpp> using namespace chemfiles; #undef assert #define assert CHECK TEST_CASE() { // [example] auto u = Vector3D(1.5, 2.0, -3.0); assert(u[0] == 1.5); assert(u[1] == 2.0); assert(u[2] == -3.0); // [example] }
22.777778
69
0.639024
jmintser
2fe400e50fb276b4251a23540e03497e989f210e
616
cpp
C++
Dynamic Programming/Knapsnack.cpp
aviral243/interviewbit-solutions-1
7b4bda68b2ff2916263493f40304b20fade16c9a
[ "MIT" ]
null
null
null
Dynamic Programming/Knapsnack.cpp
aviral243/interviewbit-solutions-1
7b4bda68b2ff2916263493f40304b20fade16c9a
[ "MIT" ]
null
null
null
Dynamic Programming/Knapsnack.cpp
aviral243/interviewbit-solutions-1
7b4bda68b2ff2916263493f40304b20fade16c9a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int maximiseProfit(vector<int> &p, vector<int> &w, int m) { int n = w.size(); vector<int> ans(n, 0); vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0)); for (int i = 1; i < n + 1; i++) for (int j = 1; j < m + 1; j++) if (w[i - 1] > j) dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); else dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - w[i - 1]] + p[i - 1]); return dp[n][m]; } int main() { vector<int> p{60, 100, 120}; vector<int> w{10, 20, 30}; int m = 50; int v2 = maximiseProfit(p, w, m); cout << v2; return 0; }
21.241379
73
0.477273
aviral243
2fe57690a55e66d9578c20a9c04b5aafec7e0c30
253
cpp
C++
problemas-resolvidos/neps-academy/programacao-basica-competicoes-c++/c++/Raizes.cpp
Ramo-UERJ/competitive-programming
7f2b821862853a7ebc1de5454914bcc9ea626083
[ "MIT" ]
null
null
null
problemas-resolvidos/neps-academy/programacao-basica-competicoes-c++/c++/Raizes.cpp
Ramo-UERJ/competitive-programming
7f2b821862853a7ebc1de5454914bcc9ea626083
[ "MIT" ]
1
2020-07-29T13:23:25.000Z
2020-07-29T13:23:25.000Z
problemas-resolvidos/neps-academy/programacao-basica-competicoes-c++/c++/Raizes.cpp
ieee-uerj/competitive-programming
7f2b821862853a7ebc1de5454914bcc9ea626083
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> using namespace std; int main(){ int N; double x; cin >> N; cout.precision(4); cout.setf(ios::fixed); for (int i =0; i < N; i++){ cin >> x; cout << sqrt(x) << endl; } }
11.5
31
0.490119
Ramo-UERJ
2fe6891ff90c388888df3ff5931d7343b3d09b48
3,670
cpp
C++
src/foundation/Buffer.cpp
ma-bo/lua-poco
b19a38c42ff6bcd06a4fda2a5aff826056735678
[ "BSD-3-Clause" ]
16
2015-10-15T16:38:32.000Z
2022-01-29T16:20:14.000Z
src/foundation/Buffer.cpp
ma-bo/lua-poco
b19a38c42ff6bcd06a4fda2a5aff826056735678
[ "BSD-3-Clause" ]
2
2016-08-11T22:14:31.000Z
2016-08-12T16:02:20.000Z
src/foundation/Buffer.cpp
ma-bo/lua-poco
b19a38c42ff6bcd06a4fda2a5aff826056735678
[ "BSD-3-Clause" ]
8
2015-07-17T09:15:56.000Z
2021-05-20T06:49:57.000Z
/// Mutable buffers. // A module that implements mutable buffers for use with memoryostream and memoryistream. // Note: buffer userdata are copyable between threads. // @module buffer #include <iostream> #include "Buffer.h" #include <Poco/Exception.h> int luaopen_poco_buffer(lua_State* L) { LuaPoco::BufferUserdata::registerBuffer(L); return LuaPoco::loadConstructor(L, LuaPoco::BufferUserdata::Buffer); } namespace LuaPoco { const char* POCO_BUFFER_METATABLE_NAME = "Poco.Buffer.metatable"; BufferUserdata::BufferUserdata(size_t size) : mBuffer(size), mCapacity(size) { } BufferUserdata::~BufferUserdata() { } bool BufferUserdata::copyToState(lua_State *L) { registerBuffer(L); BufferUserdata* bud = new(lua_newuserdata(L, sizeof *bud)) BufferUserdata(mCapacity); setupPocoUserdata(L, bud, POCO_BUFFER_METATABLE_NAME); bud->mCapacity = mCapacity; std::memcpy(bud->mBuffer.begin(), mBuffer.begin(), mCapacity); return true; } // register metatable for this class bool BufferUserdata::registerBuffer(lua_State* L) { struct CFunctions methods[] = { { "__gc", metamethod__gc }, { "__tostring", metamethod__tostring }, { "clear", clear }, { "size", size }, { "data", data }, { NULL, NULL } }; setupUserdataMetatable(L, POCO_BUFFER_METATABLE_NAME, methods); return true; } /// constructs a new buffer userdata. // @param init number specifying the size of the empty buffer in bytes, or a string // of bytes that will be used to initialize the buffer of the same size as the string. // @return userdata or nil. (error) // @return error message // @function new int BufferUserdata::Buffer(lua_State* L) { int rv = 0; int top = lua_gettop(L); int firstArg = lua_istable(L, 1) ? 2 : 1; luaL_checkany(L, firstArg); size_t dataSize = 0; const char* dataInit = NULL; if (lua_type(L, firstArg) == LUA_TSTRING) dataInit = luaL_checklstring(L, firstArg, &dataSize); else dataSize = static_cast<size_t>(luaL_checknumber(L, firstArg)); try { BufferUserdata* bud = new(lua_newuserdata(L, sizeof *bud)) BufferUserdata(dataSize); setupPocoUserdata(L, bud, POCO_BUFFER_METATABLE_NAME); if (dataInit) std::memcpy(bud->mBuffer.begin(), dataInit, dataSize); rv = 1; } catch (const Poco::Exception& e) { rv = pushPocoException(L, e); } catch (...) { rv = pushUnknownException(L); } return rv; } /// // @type buffer // metamethod infrastructure int BufferUserdata::metamethod__tostring(lua_State* L) { BufferUserdata* bud = checkPrivateUserdata<BufferUserdata>(L, 1); lua_pushfstring(L, "Poco.Buffer (%p)", static_cast<void*>(bud)); return 1; } // userdata methods /// Sets all bytes of the buffer to '\0'. // @function clear int BufferUserdata::clear(lua_State* L) { BufferUserdata* bud = checkPrivateUserdata<BufferUserdata>(L, 1); std::memset(bud->mBuffer.begin(), '\0', bud->mBuffer.size()); return 0; } /// Gets the capacity of the buffer. // @return number indicating the capacity of the buffer. // @function size int BufferUserdata::size(lua_State* L) { BufferUserdata* bud = checkPrivateUserdata<BufferUserdata>(L, 1); lua_pushinteger(L, bud->mCapacity); return 1; } /// Gets the entire buffer as a string. // @return string containing all bytes of the buffer. // @function data int BufferUserdata::data(lua_State* L) { BufferUserdata* bud = checkPrivateUserdata<BufferUserdata>(L, 1); lua_pushlstring(L, bud->mBuffer.begin(), bud->mCapacity); return 1; } } // LuaPoco
26.402878
99
0.677384
ma-bo
2ff7457bf2fe4d2d3c0bc27af0930303fb70b26b
432
cpp
C++
libfairygui/proj.ios_mac/libfairygui MAC/libfairygui_MAC.cpp
umair6/FairyGUI-cocos2dx
7b21889a48b6ff5878b407c2a484670ebd8a4549
[ "MIT" ]
308
2017-10-15T14:26:45.000Z
2022-03-22T09:06:57.000Z
libfairygui/proj.ios_mac/libfairygui MAC/libfairygui_MAC.cpp
umair6/FairyGUI-cocos2dx
7b21889a48b6ff5878b407c2a484670ebd8a4549
[ "MIT" ]
73
2017-10-25T06:41:57.000Z
2022-03-21T06:49:38.000Z
libfairygui/proj.ios_mac/libfairygui MAC/libfairygui_MAC.cpp
umair6/FairyGUI-cocos2dx
7b21889a48b6ff5878b407c2a484670ebd8a4549
[ "MIT" ]
108
2017-11-01T08:22:00.000Z
2021-11-19T10:29:29.000Z
/* * libfairygui_MAC.cpp * libfairygui MAC * * Created by ytom on 17/11/9. * * */ #include <iostream> #include "libfairygui_MAC.hpp" #include "libfairygui_MACPriv.hpp" void libfairygui_MAC::HelloWorld(const char * s) { libfairygui_MACPriv *theObj = new libfairygui_MACPriv; theObj->HelloWorldPriv(s); delete theObj; }; void libfairygui_MACPriv::HelloWorldPriv(const char * s) { std::cout << s << std::endl; };
16.615385
57
0.699074
umair6
2ff8a072db190083a0bd4de78330e881d25a0bf3
239
cpp
C++
src/autowiring/CallExtractor.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
87
2015-01-18T00:43:06.000Z
2022-02-11T17:40:50.000Z
src/autowiring/CallExtractor.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
274
2015-01-03T04:50:49.000Z
2021-03-08T09:01:09.000Z
src/autowiring/CallExtractor.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
15
2015-09-30T20:58:43.000Z
2020-12-19T21:24:56.000Z
// Copyright (C) 2012-2018 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include "CallExtractor.h" #include "AutoPacket.h" using namespace autowiring; CESetup<>::CESetup(AutoPacket& packet) : pshr(packet.GetContext()) {}
21.727273
65
0.732218
CaseyCarter
2fff5d5a1f67ca52bd17486a69e8e7b2188919cf
4,437
cpp
C++
CPM/SlabSpectrumCode.cpp
FrancisKhan/ALMOST
06e36666ca18aa06167baac3123dbbe913f74b5d
[ "MIT" ]
5
2020-12-20T15:37:59.000Z
2021-03-18T18:11:17.000Z
CPM/SlabSpectrumCode.cpp
FrancisKhan/ALMOST
06e36666ca18aa06167baac3123dbbe913f74b5d
[ "MIT" ]
null
null
null
CPM/SlabSpectrumCode.cpp
FrancisKhan/ALMOST
06e36666ca18aa06167baac3123dbbe913f74b5d
[ "MIT" ]
null
null
null
#include "BaseSpectrumCode.h" #include "SlabSpectrumCode.h" #include "numeric_tools.h" #include <boost/math/special_functions/expint.hpp> #include <iostream> using namespace Eigen; using namespace Numerics; using namespace PrintFuncs; using namespace boost::math; std::pair<Tensor3d, Tensor4d> SlabSpectrumCode::calcTracks() { Tensor4d tau = Tensor4d(m_cells, m_cells, m_rays, m_energies); tau.setZero(); Tensor3d zz(m_cells, m_cells, m_rays); zz.setZero(); std::vector<double> delta(m_radii.size() - 1, 0.0); for(size_t i = 0; i < delta.size(); i++) { delta[i] = m_radii[i + 1] - m_radii[i]; } for(int h = 0; h < m_energies; h++) for(int i = 0; i < m_cells; i++) for(int j = i; j < m_cells; j++) { if (i == j) tau(i, j, 0, h) = delta[i] * m_totalXS(h, i); else { if (i == 0) tau(i, j, 0, h) = delta[j] * m_totalXS(h, j) + tau(0, j - 1, 0, h); else tau(i, j, 0, h) = delta[j] * m_totalXS(h, j) + tau(0, j - 1, 0, h) - tau(0, i - 1, 0, h); } } for(int h = 0; h < m_energies; h++) for(int i = 0; i < m_cells; i++) for(int j = i; j < m_cells; j++) { if (i != j) tau(i, j, 0, h) -= delta[j] * m_totalXS(h, j) + delta[i] * m_totalXS(h, i); if (tau(i, j, 0, h) < 0.0) tau(i, j, 0, h) = 0.0; out.print(TraceLevel::TRACE, "Tau: {:3d} {:3d} {:3d} {:5.4f}", h, i, j, tau(i, j, 0, h)); } std::pair<Tensor3d, Tensor4d> trackData = std::make_pair(zz, tau); return trackData; } Tensor3d SlabSpectrumCode::calcCPs(std::pair<Tensor3d, Tensor4d> &trackData) { Tensor4d tau = trackData.second; Tensor3d gcpm = Tensor3d(m_cells, m_cells, m_energies); gcpm.setZero(); Tensor3d CSet1(m_cells, m_cells, m_cells); Tensor3d CSet2(m_cells, m_cells, m_cells); MatrixXd P = MatrixXd::Zero(m_cells, m_cells); for(int h = 0; h < m_energies; h++) { for(int i = 0; i < m_cells; i++) for(int j = i; j < m_cells; j++) { if (j == i) P(i, j) = 1.0 - (1.0 / (2.0 * tau(i, i, 0, h))) * (1.0 - 2.0 * expint(3, tau(i, i, 0, h))); else P(i, j) = (1.0 / (2.0 * tau(i, i, 0, h))) * (expint(3, tau(i, j, 0, h)) - expint(3, tau(i, j, 0, h) + tau(i, i, 0, h)) - expint(3, tau(i, j, 0, h) + tau(j, j, 0, h)) + expint(3, tau(i, j, 0, h) + tau(j, j, 0, h) + tau(i, i, 0, h))); } for(int i = 0; i < m_cells; i++) for(int j = i + 1; j < m_cells; j++) P(j, i) = P(i, j) * (m_totalXS(h, i) / m_totalXS(h, j)) * (m_volumes(i) / m_volumes(j)); for(int i = 0; i < m_cells; i++) for(int j = 0; j < m_cells; j++) gcpm(i, j, h) = P(i, j); } out.print(TraceLevel::INFO, "P matrix (vacuum BC)"); printMatrix(gcpm, out, TraceLevel::INFO, "Group"); return gcpm; } void SlabSpectrumCode::applyBoundaryConditions(Tensor3d &gcpm) { for(int h = 0; h < m_energies; h++) { out.print(TraceLevel::INFO, "Apply boundary conditions Group {}", h + 1); double albedo = m_solverData.getAlbedo()[0]; VectorXd Pis = VectorXd::Zero(m_cells); VectorXd psi = VectorXd::Zero(m_cells); Pis.setZero(); psi.setZero(); for(int i = 0; i < m_cells; i++) { for(int j = 0; j < m_cells; j++) { gcpm(i, j, h) /= m_totalXS(h, j); //reduced } } for(int i = 0; i < m_cells; i++) { for(int j = 0; j < m_cells; j++) { Pis(i) += gcpm(i, j, h) * m_totalXS(h, j); } Pis(i) = 1.0 - Pis(i); psi(i) = (4.0 * m_volumes(i) / m_surface) * Pis(i); out.print(TraceLevel::INFO, "Cell n: {} Pis: {:7.6e} psi [cm]: {:7.6e}", i, Pis(i), psi(i)); } double Pss = 0.0; for(int i = 0; i < m_cells; i++) { Pss += psi(i) * m_totalXS(h, i); } Pss = 1.0 - Pss; out.print(TraceLevel::INFO, "Pss [cm2]: {:7.6e} \n", Pss); for(int i = 0; i < m_cells; i++) { for(int j = 0; j < m_cells; j++) { gcpm(i, j, h) += Pis(i) * psi(j) * (albedo / (1.0 - Pss * albedo)); gcpm(i, j, h) *= m_totalXS(h, j); } } } out.print(TraceLevel::INFO, "P matrix (white BC)"); printMatrix(gcpm, out, TraceLevel::INFO, "Group"); for(int h = 0; h < m_energies; h++) { for(int i = 0; i < m_cells; i++) { for(int j = 0; j < m_cells; j++) { gcpm(i, j, h) /= m_totalXS(h, j); } } } }
26.254438
103
0.506874
FrancisKhan
6402960a16739f7901cfd5a7baac7cf3bb5ff7bc
5,847
cc
C++
cpp/normalize.cc
streamcorpus/streamcorpus-filter
7687aa25260d95b861efa63d7369e6dcd6bb20a4
[ "MIT" ]
1
2015-11-13T15:48:23.000Z
2015-11-13T15:48:23.000Z
cpp/normalize.cc
streamcorpus/streamcorpus-filter
7687aa25260d95b861efa63d7369e6dcd6bb20a4
[ "MIT" ]
null
null
null
cpp/normalize.cc
streamcorpus/streamcorpus-filter
7687aa25260d95b861efa63d7369e6dcd6bb20a4
[ "MIT" ]
null
null
null
#include <assert.h> #include <ctype.h> #include <stddef.h> #include "normalize.h" // icu //#include <normalizer2.h> #if HAVE_ICU #include <unicode/normalizer2.h> #include <unicode/unistr.h> #include <unicode/utypes.h> #include <vector> #include <iostream> using std::vector; using std::cerr; using std::endl; using icu::Normalizer2; using icu::UnicodeString; static const Normalizer2* norm = NULL; // strip accents, lowercase // offsets could be weird, e.g. there's a 'fi' glyph that will expand into "fi" int lesserUnicodeString(const icu::UnicodeString& in, icu::UnicodeString* out, vector<size_t>* offsets, bool squashSpace ) { if (norm == NULL) { UErrorCode uerr = U_ZERO_ERROR; norm = icu::Normalizer2::getInstance(NULL, "nfkc", UNORM2_DECOMPOSE, uerr); if ((norm == NULL) || U_FAILURE(uerr)) { cerr << u_errorName(uerr) << endl; return -1; } } bool wasSpace = true; int32_t len = in.countChar32(); for (int32_t i = 0; i < len; i++) { UChar32 c = in.char32At(i); if (norm->isInert(c)) { if (u_isspace(c)) { if (wasSpace) { // drop redundant space continue; } wasSpace = true; // fall through to outputting the first space normally c = ' '; } else { wasSpace = false; } if (out != NULL) { (*out) += u_tolower(c); } if (offsets != NULL) { offsets->push_back(i); } } else { UnicodeString texpand; norm->getDecomposition(c, texpand); int32_t exlen = texpand.countChar32(); for (int32_t xi = 0; xi < exlen; xi++) { UChar32 xc = texpand.char32At(xi); if (u_getCombiningClass(xc) == 0) { if (u_isspace(xc)) { if (wasSpace) { // drop redundant space continue; } wasSpace = true; // fall through to outputting the first space normally xc = ' '; } else { wasSpace = false; } if (out != NULL) { (*out) += u_tolower(xc); } if (offsets != NULL) { offsets->push_back(i); } } } } } return 0; } int lesserUTF8String(const std::string& in, std::string* out, vector<size_t>* offsets, vector<size_t>* sourceByteToUCharIndex) { // We reach into the utf8 decoding manually here so that we can // track byte offsets. int errout = 0; UnicodeString raw; vector<int32_t> rawOffsets; // maps utf32 pos to utf8 byte offset { int32_t pos = 0; int32_t length = in.size(); const uint8_t* utf8 = (const uint8_t*)in.data(); UChar32 c; while (pos < length) { int32_t prevpos = pos; U8_NEXT(utf8, pos, length, c); if (((int32_t)c) < 0) { // report that there was an error, but try to process as much data as possible errout = -1; break; } if (offsets != NULL) { rawOffsets.push_back(prevpos); } if (sourceByteToUCharIndex != NULL) { int32_t sbipos = prevpos; while (sbipos < pos) { sourceByteToUCharIndex->push_back(raw.length()); sbipos++; } } raw += c; } } vector<size_t> uuoffsets; // maps intermediate utf32 to source utf32 UnicodeString cooked; int decomposeErr = lesserUnicodeString(raw, &cooked, (offsets != NULL) ? &uuoffsets : NULL); if (decomposeErr != 0) { errout = decomposeErr; } // convert back to UTF8, write out final offset mapping { uint8_t u8buf[5] = {'\0','\0','\0','\0','\0'}; int32_t pos; int32_t capacity = 5; UChar32 c; UBool err; int32_t cookedlen = cooked.countChar32(); for (int32_t i = 0; i < cookedlen; i++) { c = cooked.char32At(i); pos = 0; U8_APPEND(u8buf, pos, capacity, c, err); u8buf[pos] = '\0'; (*out) += (char*)u8buf; if (offsets != NULL) { // map offset all the way back through source size_t offset = rawOffsets[uuoffsets[i]]; for (int32_t oi = 0; oi < pos; oi++) { // every output byte gets a source offset offsets->push_back(offset); } } } } return errout; } #else #warning "compliing without ICU, which makes unicode possible. you should really go get ICU. http://icu-project.org/" #endif /* HAVE_ICU */ enum State { initial = 0, normal, space, lastState }; // semi-depricated. ICU library is preferred for unicode handling. // orig: original text // len: length of that text // offsets: size_t[len] for offsets output // out: char[len] for normalized text output size_t normalize(const char* orig, size_t len, size_t* offsets, char* out) { size_t outi = 0; State state = initial; for (size_t i = 0; i < len; i++) { char c = orig[i]; if (isspace(c) || (c == '.')) { switch (state) { case initial: // drop leading space, remain in initial state break; case normal: // transition into a run of space, emit one space state = space; out[outi] = ' '; offsets[outi] = i; outi++; break; case space: // drop redundant space break; case lastState: default: assert(0); // never get here } } else { state = normal; out[outi] = tolower(orig[i]); offsets[outi] = i; outi++; } } return outi; } int normalize(const std::string& orig, std::string* out, std::vector<size_t>* offsets, vector<size_t>* sourceByteToUCharIndex) { #if HAVE_ICU return lesserUTF8String(orig, out, offsets, sourceByteToUCharIndex); #else // fall back to ye olde C and ASCII way size_t origlen = orig.size(); char* tmpout = new char[origlen]; size_t* offsetA = new size_t[origlen]; size_t outlen = normalize(orig.data(), origlen, offsetA, tmpout); (*out) = std::string(tmpout, outlen); if (offsets != NULL) { for (int i = 0; i < outlen; i++) { offsets->push_back(offsetA[i]); } } delete [] tmpout; delete [] offsetA; return 0; #endif }
24.880851
128
0.601676
streamcorpus
6408e3aa3f1b0a96ed2553fffb6042fbcf4c2c49
5,304
cpp
C++
src/test/SlamManagerTest.cpp
AlexeyMerzlyakov/lpslam
e473de4f53c49d2fc3cc123758d0ac987afdabbd
[ "Apache-2.0" ]
4
2021-05-27T21:42:46.000Z
2022-03-07T04:47:13.000Z
src/test/SlamManagerTest.cpp
AlexeyMerzlyakov/lpslam
e473de4f53c49d2fc3cc123758d0ac987afdabbd
[ "Apache-2.0" ]
1
2021-11-17T08:42:43.000Z
2021-12-07T03:11:11.000Z
src/test/SlamManagerTest.cpp
AlexeyMerzlyakov/lpslam
e473de4f53c49d2fc3cc123758d0ac987afdabbd
[ "Apache-2.0" ]
2
2021-09-05T11:02:12.000Z
2021-11-16T01:17:23.000Z
#include "Manager/SlamManager.h" #include "Interface/LpSlamTypes.h" #include <gtest/gtest.h> #include <string> #include <sstream> using namespace LpSlam; // make sure providing wrong json config is handled // properly TEST(slam_manager, read_config_file) { const std::string testJsonConfigFile = "lpgf_unitttest_config_file.json"; { // no config provided SlamManager fm; ASSERT_FALSE(fm.readConfigurationFile("does_not_exist.json")); } { SlamManager fm; nlohmann::json j_test_datasource = { {"datasources", { { { "type", "FileSource" }} } } }; { std::ofstream o(testJsonConfigFile); o << std::setw(4) << j_test_datasource << std::endl; o.close(); } ASSERT_TRUE(fm.readConfigurationFile(testJsonConfigFile)); } { SlamManager fm; { std::ofstream o(testJsonConfigFile); o << std::setw(4) << "datasources {{" << std::endl; o.close(); } // syntax error in Json ASSERT_FALSE(fm.readConfigurationFile(testJsonConfigFile)); } { SlamManager fm; nlohmann::json j_test_datasource = { {"datasources", { { { "type", "FileSource" }, { "configuration", { { "file_names" , "blah"} } } } } } }; { std::ofstream o(testJsonConfigFile); o << std::setw(4) << j_test_datasource << std::endl; o.close(); } ASSERT_TRUE(fm.readConfigurationFile(testJsonConfigFile)); } } TEST(slam_manager, read_camera_calibration) { const std::string testJsonConfigFile = "lpgf_unitttest_config_file.json"; { SlamManager fm; nlohmann::json j_test_datasource = { {"cameras", { { { "number", 0 }, { "model", "fisheye" }, { "fx", 1.0}, { "fy", 2.0}, { "cx", 3.0}, { "cy", 4.0}, { "distortion", {10.0, 11.0, 12.0, 13.0 }}, { "resolution_x", 320}, { "resolution_y", 240} }, { { "number", 1 }, { "model", "perspective" }, { "fx", 21.0}, { "fy", 22.0}, { "cx", 23.0}, { "cy", 24.0}, { "distortion", {110.0, 111.0, 112.0, 113.0, 114.0}}, { "resolution_x", 320}, { "resolution_y", 240} } } }}; { std::ofstream o(testJsonConfigFile); o << std::setw(4) << j_test_datasource << std::endl; o.close(); } ASSERT_TRUE(fm.readConfigurationFile(testJsonConfigFile)); ASSERT_TRUE(fm.getCameraConfiguration(0).has_value()); ASSERT_TRUE(fm.getCameraConfiguration(1).has_value()); auto cam0 = fm.getCameraConfiguration(0).value(); auto cam1 = fm.getCameraConfiguration(1).value(); ASSERT_EQ(cam0.distortion_function, LpSlamCameraDistortionFunction_Fisheye); ASSERT_NEAR(cam0.f_x, 1.0, 0.001); ASSERT_NEAR(cam0.f_y, 2.0, 0.001); ASSERT_NEAR(cam0.c_x, 3.0, 0.001); ASSERT_NEAR(cam0.c_y, 4.0, 0.001); ASSERT_NEAR(cam0.dist[0], 10.0, 0.001); ASSERT_NEAR(cam0.dist[1], 11.0, 0.001); ASSERT_NEAR(cam0.dist[2], 12.0, 0.001); ASSERT_NEAR(cam0.dist[3], 13.0, 0.001); ASSERT_EQ(cam1.distortion_function, LpSlamCameraDistortionFunction_Pinhole); ASSERT_NEAR(cam1.f_x, 21.0, 0.001); ASSERT_NEAR(cam1.f_y, 22.0, 0.001); ASSERT_NEAR(cam1.c_x, 23.0, 0.001); ASSERT_NEAR(cam1.c_y, 24.0, 0.001); ASSERT_NEAR(cam1.dist[0], 110.0, 0.001); ASSERT_NEAR(cam1.dist[1], 111.0, 0.001); ASSERT_NEAR(cam1.dist[2], 112.0, 0.001); ASSERT_NEAR(cam1.dist[3], 113.0, 0.001); ASSERT_NEAR(cam1.dist[4], 114.0, 0.001); } // too many parameters in distortion { SlamManager fm; nlohmann::json j_test_datasource = { {"cameras", { { { "number", 0 }, { "model", "fisheye" }, { "fx", 1.0}, { "fy", 2.0}, { "cx", 3.0}, { "cy", 4.0}, { "distortion", {10.0, 11.0, 12.0, 13.0, 34.0, 23.02, 2.3 }}, } }}}; { std::ofstream o(testJsonConfigFile); o << std::setw(4) << j_test_datasource << std::endl; o.close(); } ASSERT_FALSE(fm.readConfigurationFile(testJsonConfigFile)); } // unknown camera model { SlamManager fm; nlohmann::json j_test_datasource = { {"cameras", { { { "number", 0 }, { "model", "what_!?" }, { "fx", 1.0}, { "fy", 2.0}, { "cx", 3.0}, { "cy", 4.0}, { "distortion", {10.0, 11.0, 12.0}}, } }}}; { std::ofstream o(testJsonConfigFile); o << std::setw(4) << j_test_datasource << std::endl; o.close(); } ASSERT_FALSE(fm.readConfigurationFile(testJsonConfigFile)); } }
26.787879
84
0.49227
AlexeyMerzlyakov
6409e68ce5c1b3308fd36d1367609cc3a1ac8fbb
392
hpp
C++
include/clpp/map_access.hpp
Robbepop/clpp
7723bb68c55d861ac2135ccf84d3c5b92b2b2b50
[ "MIT" ]
5
2015-09-08T01:59:26.000Z
2018-11-26T10:19:29.000Z
include/clpp/map_access.hpp
Robbepop/clpp
7723bb68c55d861ac2135ccf84d3c5b92b2b2b50
[ "MIT" ]
6
2015-11-29T03:00:11.000Z
2015-11-29T03:11:52.000Z
include/clpp/map_access.hpp
Robbepop/clpp
7723bb68c55d861ac2135ccf84d3c5b92b2b2b50
[ "MIT" ]
null
null
null
#ifndef CLPP_MAP_ACCESS_HPP #define CLPP_MAP_ACCESS_HPP #include "clpp/detail/common.hpp" namespace cl { enum class MapAccess : cl_map_flags { read = CL_MAP_READ , write = CL_MAP_WRITE , readWrite = CL_MAP_READ | CL_MAP_WRITE #if defined(CL_VERSION_1_2) , writeInvalidateRegion = CL_MAP_WRITE_INVALIDATE_REGION #endif }; } #endif
21.777778
58
0.67602
Robbepop
640f35f24e39299c8c63bb8978e717a69721bccb
430
cpp
C++
archive_cppthreads/thread_creation.cpp
kumar-parveen/csbits
a18c099dbde45a4e0dff0bced9986623b81089a6
[ "MIT" ]
1
2020-06-14T07:14:45.000Z
2020-06-14T07:14:45.000Z
archive_cppthreads/thread_creation.cpp
kumar-parveen/csbits
a18c099dbde45a4e0dff0bced9986623b81089a6
[ "MIT" ]
null
null
null
archive_cppthreads/thread_creation.cpp
kumar-parveen/csbits
a18c099dbde45a4e0dff0bced9986623b81089a6
[ "MIT" ]
null
null
null
#include<iostream> #include<thread> using namespace std; void fun(){ cout<< "fun function" << endl; } class FunObject{ public: void operator()() const { cout << "Fun Object" << endl; } }; int main(){ cout << endl; thread t1(fun); FunObject obj; thread t2(obj); thread t3([]{ cout<< "lambda function" << endl;}); t1.join(); t2.join(); t3.join(); cout << endl; };
13.4375
54
0.534884
kumar-parveen
64159169c4f39ed755abc04c639bfdef54164353
8,465
hpp
C++
Source/System/ResourceManager.hpp
gunstarpl/Perim-Game-07-2015
58efdee1857f5cccad909d5c2a76f2d6871657e6
[ "Unlicense", "MIT" ]
null
null
null
Source/System/ResourceManager.hpp
gunstarpl/Perim-Game-07-2015
58efdee1857f5cccad909d5c2a76f2d6871657e6
[ "Unlicense", "MIT" ]
null
null
null
Source/System/ResourceManager.hpp
gunstarpl/Perim-Game-07-2015
58efdee1857f5cccad909d5c2a76f2d6871657e6
[ "Unlicense", "MIT" ]
null
null
null
#pragma once #include "Precompiled.hpp" #include "Resource.hpp" // // Resource Manager // namespace System { // Resource pool interface. class ResourcePoolInterface { protected: ResourcePoolInterface() { } public: virtual ~ResourcePoolInterface() { } virtual void ReleaseUnused() = 0; }; // Resource pool class. template<typename Type> class ResourcePool : public ResourcePoolInterface { public: // Validate resource type. static_assert(std::is_base_of<Resource, Type>::value, "Not a resource type."); // Type declarations. typedef std::shared_ptr<Type> ResourcePtr; typedef std::unordered_map<std::string, ResourcePtr> ResourceList; typedef typename ResourceList::value_type ResourceListPair; public: ResourcePool(ResourceManager& resourceManager); ~ResourcePool(); // Sets the default resource. void SetDefault(std::shared_ptr<const Type> resource); // Gets the default resource. std::shared_ptr<const Type> GetDefault() const; // Loads a resource. std::shared_ptr<const Type> Load(std::string filename); // Releases unused resources. void ReleaseUnused(); // Releases all resources. void ReleaseAll(); private: // Resource manager reference. ResourceManager& m_resourceManager; // List of resources. ResourceList m_resources; // Default resource. std::shared_ptr<const Type> m_default; }; template<typename Type> ResourcePool<Type>::ResourcePool(ResourceManager& resourceManager) : m_resourceManager(resourceManager), m_default(std::make_shared<Type>(&m_resourceManager)) { } template<typename Type> ResourcePool<Type>::~ResourcePool() { // Release all resources. this->ReleaseAll(); } template<typename Type> void ResourcePool<Type>::SetDefault(std::shared_ptr<const Type> resource) { m_default = resource; } template<typename Type> std::shared_ptr<const Type> ResourcePool<Type>::GetDefault() const { return m_default; } template<typename Type> std::shared_ptr<const Type> ResourcePool<Type>::Load(std::string filename) { // Find the resource. auto it = m_resources.find(filename); if(it != m_resources.end()) return it->second; // Create and load the new resource instance. std::shared_ptr<Type> resource = std::make_shared<Type>(&m_resourceManager); if(!resource->Load(filename)) return m_default; // Add resource to the list. auto result = m_resources.emplace(filename, std::move(resource)); assert(result.second == true); // Return resource pointer. return result.first->second; } template<typename Type> void ResourcePool<Type>::ReleaseUnused() { // Release unused resources. auto it = m_resources.begin(); while(it != m_resources.end()) { if(it->second.unique()) { // Take out filename string to print it later. std::string filename = std::move(it->first); // Release the resource. it = m_resources.erase(it); // Print log message. Log() << "Released a resource loaded from \"" << filename << "\" file."; } else { ++it; } } } template<typename Type> void ResourcePool<Type>::ReleaseAll() { // Release all resources. auto it = m_resources.begin(); while(it != m_resources.end()) { // Take out filename string to print it later. std::string filename = std::move(it->first); // Release the resource. it = m_resources.erase(it); // Print log message. Log() << "Released a resource loaded from \"" << filename << "\" file."; } assert(m_resources.empty()); } // Resource manager class. class ResourceManager { public: // Type declarations. typedef std::unique_ptr<ResourcePoolInterface> ResourcePoolPtr; typedef std::unordered_map<std::type_index, ResourcePoolPtr> ResourcePoolList; typedef ResourcePoolList::value_type ResourcePoolPair; public: ResourceManager(); ~ResourceManager(); // Restores instance to it's original state. void Cleanup(); // Initializes the component system. bool Initialize(Context& context); // Releases unused resources. void ReleaseUnused(); // Loads a resource. template<typename Type> std::shared_ptr<const Type> Load(std::string filename); // Sets the default resource. template<typename Type> void SetDefault(std::shared_ptr<const Type> default); // Gets the default resource. template<typename Type> std::shared_ptr<const Type> GetDefault() const; // Gets a resource pool. template<typename Type> ResourcePool<Type>* GetPool(); private: // Creates a resource pool. template<typename Type> ResourcePool<Type>* CreatePool(); private: // Resource pools. ResourcePoolList m_pools; // Initialization state. bool m_initialized; }; template<typename Type> std::shared_ptr<const Type> ResourceManager::Load(std::string filename) { if(!m_initialized) return nullptr; // Validate resource type. static_assert(std::is_base_of<Resource, Type>::value, "Not a resource type."); // Get the resource pool. ResourcePool<Type>* pool = this->GetPool<Type>(); assert(pool != nullptr); // Delegate to the resource pool. return pool->Load(filename); } template<typename Type> void ResourceManager::SetDefault(std::shared_ptr<const Type> default) { if(!m_initialized) return; // Validate resource type. static_assert(std::is_base_of<Resource, Type>::value, "Not a resource type."); // Get the resource pool. ResourcePool<Type>* pool = this->GetPool<Type>(); assert(pool != nullptr); // Set the default resource. pool->SetDefault(default); } template<typename Type> std::shared_ptr<const Type> ResourceManager::GetDefault() const { if(!m_initialized) return nullptr; // Validate resource type. static_assert(std::is_base_of<Resource, Type>::value, "Not a resource type."); // Get the resource pool. ResourcePool<Type>* pool = this->GetPool<Type>(); assert(pool != nullptr); // Return the default resource. return pool->GetDefault(); } template<typename Type> ResourcePool<Type>* ResourceManager::CreatePool() { assert(m_initialized); // Validate resource type. static_assert(std::is_base_of<Resource, Type>::value, "Not a resource type."); // Create and add a pool to the collection. auto pool = std::make_unique<ResourcePool<Type>>(*this); auto pair = ResourcePoolPair(typeid(Type), std::move(pool)); auto result = m_pools.insert(std::move(pair)); assert(result.second == true); // Return created pool. return reinterpret_cast<ResourcePool<Type>*>(result.first->second.get()); } template<typename Type> ResourcePool<Type>* ResourceManager::GetPool() { if(!m_initialized) return nullptr; // Validate resource type. static_assert(std::is_base_of<Resource, Type>::value, "Not a resource type."); // Find pool by resource type. auto it = m_pools.find(typeid(Type)); if(it == m_pools.end()) { // Create a new resource pool. return this->CreatePool<Type>(); } // Cast and return the pointer that we already know is a resource pool. return reinterpret_cast<ResourcePool<Type>*>(it->second.get()); } };
27.21865
88
0.588305
gunstarpl
6416a341f41a586e5ddd2a1d022eb53d11351671
7,409
cpp
C++
src/mongo/db/pipeline/document.cpp
spencerjackson/mongo
51c46e71c9f310fc91168c0945ffa6cfc00d380b
[ "Apache-2.0" ]
null
null
null
src/mongo/db/pipeline/document.cpp
spencerjackson/mongo
51c46e71c9f310fc91168c0945ffa6cfc00d380b
[ "Apache-2.0" ]
null
null
null
src/mongo/db/pipeline/document.cpp
spencerjackson/mongo
51c46e71c9f310fc91168c0945ffa6cfc00d380b
[ "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2011 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "pch.h" #include <boost/functional/hash.hpp> #undef assert #define assert MONGO_assert #include "db/jsobj.h" #include "db/pipeline/document.h" #include "db/pipeline/value.h" #include "util/mongoutils/str.h" namespace mongo { using namespace mongoutils; string Document::idName("_id"); intrusive_ptr<Document> Document::createFromBsonObj(BSONObj *pBsonObj) { intrusive_ptr<Document> pDocument(new Document(pBsonObj)); return pDocument; } Document::Document(BSONObj *pBsonObj): vFieldName(), vpValue() { BSONObjIterator bsonIterator(pBsonObj->begin()); while(bsonIterator.more()) { BSONElement bsonElement(bsonIterator.next()); string fieldName(bsonElement.fieldName()); intrusive_ptr<const Value> pValue( Value::createFromBsonElement(&bsonElement)); vFieldName.push_back(fieldName); vpValue.push_back(pValue); } } void Document::toBson(BSONObjBuilder *pBuilder) { const size_t n = vFieldName.size(); for(size_t i = 0; i < n; ++i) vpValue[i]->addToBsonObj(pBuilder, vFieldName[i]); } intrusive_ptr<Document> Document::create(size_t sizeHint) { intrusive_ptr<Document> pDocument(new Document(sizeHint)); return pDocument; } Document::Document(size_t sizeHint): vFieldName(), vpValue() { if (sizeHint) { vFieldName.reserve(sizeHint); vpValue.reserve(sizeHint); } } intrusive_ptr<Document> Document::clone() { const size_t n = vFieldName.size(); intrusive_ptr<Document> pNew(Document::create(n)); for(size_t i = 0; i < n; ++i) pNew->addField(vFieldName[i], vpValue[i]); return pNew; } Document::~Document() { } FieldIterator *Document::createFieldIterator() { return new FieldIterator(intrusive_ptr<Document>(this)); } intrusive_ptr<const Value> Document::getValue(const string &fieldName) { /* For now, assume the number of fields is small enough that iteration is ok. Later, if this gets large, we can create a map into the vector for these lookups. Note that because of the schema-less nature of this data, we always have to look, and can't assume that the requested field is always in a particular place as we would with a statically compilable reference. */ const size_t n = vFieldName.size(); for(size_t i = 0; i < n; ++i) { if (fieldName.compare(vFieldName[i]) == 0) return vpValue[i]; } return(intrusive_ptr<const Value>()); } void Document::addField(const string &fieldName, const intrusive_ptr<const Value> &pValue) { uassert(15945, str::stream() << "cannot add undefined field " << fieldName << " to document", pValue->getType() != Undefined); vFieldName.push_back(fieldName); vpValue.push_back(pValue); } void Document::setField(size_t index, const string &fieldName, const intrusive_ptr<const Value> &pValue) { /* special case: should this field be removed? */ if (!pValue.get()) { vFieldName.erase(vFieldName.begin() + index); vpValue.erase(vpValue.begin() + index); return; } /* make sure we have a valid value */ uassert(15968, str::stream() << "cannot set undefined field " << fieldName << " to document", pValue->getType() != Undefined); /* set the indicated field */ vFieldName[index] = fieldName; vpValue[index] = pValue; } intrusive_ptr<const Value> Document::getField(const string &fieldName) const { const size_t n = vFieldName.size(); for(size_t i = 0; i < n; ++i) { if (fieldName.compare(vFieldName[i]) == 0) return vpValue[i]; } /* if we got here, there's no such field */ return intrusive_ptr<const Value>(); } size_t Document::getApproximateSize() const { size_t size = sizeof(Document); const size_t n = vpValue.size(); for(size_t i = 0; i < n; ++i) size += vpValue[i]->getApproximateSize(); return size; } size_t Document::getFieldIndex(const string &fieldName) const { const size_t n = vFieldName.size(); size_t i = 0; for(; i < n; ++i) { if (fieldName.compare(vFieldName[i]) == 0) break; } return i; } void Document::hash_combine(size_t &seed) const { const size_t n = vFieldName.size(); for(size_t i = 0; i < n; ++i) { boost::hash_combine(seed, vFieldName[i]); vpValue[i]->hash_combine(seed); } } int Document::compare(const intrusive_ptr<Document> &rL, const intrusive_ptr<Document> &rR) { const size_t lSize = rL->vFieldName.size(); const size_t rSize = rR->vFieldName.size(); for(size_t i = 0; true; ++i) { if (i >= lSize) { if (i >= rSize) return 0; // documents are the same length return -1; // left document is shorter } if (i >= rSize) return 1; // right document is shorter const int nameCmp = rL->vFieldName[i].compare(rR->vFieldName[i]); if (nameCmp) return nameCmp; // field names are unequal const int valueCmp = Value::compare(rL->vpValue[i], rR->vpValue[i]); if (valueCmp) return valueCmp; // fields are unequal } /* NOTREACHED */ assert(false); return 0; } /* ----------------------- FieldIterator ------------------------------- */ FieldIterator::FieldIterator(const intrusive_ptr<Document> &pTheDocument): pDocument(pTheDocument), index(0) { } bool FieldIterator::more() const { return (index < pDocument->vFieldName.size()); } pair<string, intrusive_ptr<const Value> > FieldIterator::next() { assert(more()); pair<string, intrusive_ptr<const Value> > result( pDocument->vFieldName[index], pDocument->vpValue[index]); ++index; return result; } }
33.224215
83
0.563369
spencerjackson
64171fc4727f307a00e40a612cc01bc22fc6d847
2,088
hpp
C++
renderer/msd_renderer.hpp
msdmazarei/cpp-msd-freetype
ae4c79512ea6c9fba686235e9dd2dd03bd791a6f
[ "BSD-2-Clause" ]
null
null
null
renderer/msd_renderer.hpp
msdmazarei/cpp-msd-freetype
ae4c79512ea6c9fba686235e9dd2dd03bd791a6f
[ "BSD-2-Clause" ]
null
null
null
renderer/msd_renderer.hpp
msdmazarei/cpp-msd-freetype
ae4c79512ea6c9fba686235e9dd2dd03bd791a6f
[ "BSD-2-Clause" ]
null
null
null
#ifndef _MSD_RENDERER_H_ #define _MSD_RENDERER_H_ #include <hb-ft.h> #include <mupdf/fitz.h> #include <png++/png.hpp> #include <vector> typedef unsigned char BYTE; typedef unsigned int uint; // typedef struct ImagePixel_ { // BYTE C; // R, G, B; // } ImagePixel; typedef struct glyph_position_ { hb_codepoint_t gid; double x, y; int bitmap_width; int bitmap_height; int metrics_height; int metrics_width; int metrics_horiBearingY; int bitmap_left; float x_advancing; } glyph_position; typedef struct TextBitmap_ { png::image<png::gray_pixel> bitmap; uint base_line; } TextBitmap; typedef png::image<png::rgba_pixel> RGBAImage; typedef struct TextImage_ { RGBAImage image; uint base_line; } TextImage; class TextRenderer { private: BYTE *font_buffer; unsigned long font_buffer_len; unsigned int font_size; FT_Library ft_library; FT_Face ft_face; FT_Error ft_error; fz_context *ctx; hb_font_t *hb_font; std::vector<glyph_position> get_glyphs(char *text, unsigned int len); // template <typename pixel> // void TextRenderer::copy_to_target_image(png::image<pixel> &target_image, // BYTE *graybitmap, uint x_offset, // uint y_offset, uint gwidth, // uint gheight); // void copy_to_target_image(ImagePixel *target, ImagePixel *glyph_bitmap, // uint16_t x_offset, uint16_t y_offset, // uint16_t gwidth, uint16_t gheight, // uint16_t image_width, uint16_t image_height); public: TextRenderer(BYTE *buffer, unsigned long len); ~TextRenderer() { if (ctx) fz_drop_context(ctx); } void set_font_size(unsigned int font_size); TextBitmap render(char *text, unsigned int text_len, bool ltr); static RGBAImage colorizeBitmap(png::image<png::gray_pixel> &src, png::rgba_pixel &foreground_color, png::rgba_pixel &background_color); }; #endif
27.473684
77
0.645115
msdmazarei
641a3c3bce9823d835bca8504751b151b026a358
219
hpp
C++
el/types/void.hpp
Xikeb/elSandbox
f0d2474672016a87aae9720b6ee9346904f21cd2
[ "MIT" ]
null
null
null
el/types/void.hpp
Xikeb/elSandbox
f0d2474672016a87aae9720b6ee9346904f21cd2
[ "MIT" ]
null
null
null
el/types/void.hpp
Xikeb/elSandbox
f0d2474672016a87aae9720b6ee9346904f21cd2
[ "MIT" ]
null
null
null
#pragma once namespace el { namespace impl { template<typename ...Ts> struct void_t { using type = void; }; } // impl template<typename ...Ts> using void_t = typename el::impl::void_t<Ts...>::type; } // el
18.25
55
0.630137
Xikeb
6426306a3b5cbb8437d7b249319a250084f0de32
17,941
cxx
C++
Programs/ThirionRegistration/mimxThirionRegistrationPrimary.cxx
Piyusha23/IAFEMesh
e91b34c9eaa9c8ecc4ebb5d16f4c13f330d75c9f
[ "BSD-4-Clause-UC" ]
null
null
null
Programs/ThirionRegistration/mimxThirionRegistrationPrimary.cxx
Piyusha23/IAFEMesh
e91b34c9eaa9c8ecc4ebb5d16f4c13f330d75c9f
[ "BSD-4-Clause-UC" ]
null
null
null
Programs/ThirionRegistration/mimxThirionRegistrationPrimary.cxx
Piyusha23/IAFEMesh
e91b34c9eaa9c8ecc4ebb5d16f4c13f330d75c9f
[ "BSD-4-Clause-UC" ]
null
null
null
#include <iostream> #include <string> #include <fstream> #include <stdio.h> #include "itkImage.h" #include "itkExceptionObject.h" #include "itkBrains2MaskImageIOFactory.h" #include "ThirionRegistration.h" #include <metaCommand.h> //This function prints the valid pixel types. void PrintDataTypeStrings(void) { //Prints the Input and output data type strings. std::cout << "UCHAR" << std::endl; std::cout << "SHORT" << std::endl; std::cout << "USHORT" << std::endl; std::cout << "INT" << std::endl; std::cout << "FLOAT" << std::endl; } //This function compares strings. int CompareNoCase( const std::string &s, const std::string& s2 ) { //Compare strings. std::string::const_iterator p = s.begin(); std::string::const_iterator p2 = s2.begin(); while ( p != s.end() && p2 != s2.end() ) { if ( toupper(*p) != toupper(*p2) ) return (toupper(*p) < toupper(*p2)) ? -1 : 1; p++; p2++; } return ( s2.size() == s.size() ) ? 0 : (s.size() < s2.size()) ? -1 : 1; } // This function calls the Thirion registration filter setting all the parameters. template < class InPixelType, class OutPixelType > void ThirionFunction (MetaCommand command) { const std::string InputFilename(command.GetValueAsString("InputFilename", "filename")); const std::string OutputFilename(command.GetValueAsString("OutputFilename", "filename")); const std::string TargetFilename(command.GetValueAsString("TargetFilename", "filename")); const std::string ParameterFilename(command. GetValueAsString("ParameterFilename","filename")); const std::string OutputDeformationFilename(command. GetValueAsString("OutputDeformationFieldname","filename")); const std::string CheckerboardFilename(command. GetValueAsString("CheckerboardFilename","filename")); const std::string CheckerboardPattern(command. GetValueAsString("CheckerPattern","PatternArray")); const std::string DisplacementPrefix(command. GetValueAsString("DisplacementField","filename")); int MedianFilterRadius(command.GetValueAsInt("Median","radius")); std::cerr << "InputFilename " << InputFilename << std::endl << "OutputFilename " << OutputFilename << std::endl << "TargetFilename " << TargetFilename << std::endl << "ParameterFilename " << ParameterFilename << std::endl << "OutputDeformationFilename " << OutputDeformationFilename << std::endl << "CheckerboardFilename " << CheckerboardFilename << std::endl << "CheckerboardPattern " << CheckerboardPattern << std::endl << "DisplacementPrefix " << DisplacementPrefix << std::endl << "MedianFilterRadius" << MedianFilterRadius << std::endl; const int dims =3; typedef itk::Image<InPixelType, dims> ImageType; typedef itk::Image<float, dims> RealImageType; typedef itk::Image<OutPixelType, dims> OutputImageType; typedef itk::Image< itk::Vector<float, 3>, 3> DeformationFieldType; typename DeformationFieldType::Pointer initialDeformationField; // // If optional initial transform is given, will use this transform to generate // a deformation field to prime the thirion demons registration. std::string initialTransformFilename(command.GetValueAsString("InitialTransform","filename")); //Need to explicity register the B2MaskIOFactory itk::Brains2MaskImageIOFactory::RegisterOneFactory (); //Thirion Registration application filter. typedef itk::ThirionRegistration < ImageType, RealImageType, OutputImageType > AppType; //Set the parameters for the filter. typename AppType::Pointer app = AppType::New (); if(initialTransformFilename != "" ) { app->SetInitialTransformFileName(initialTransformFilename); } app->SetParameterFileName (ParameterFilename.c_str ()); app->SetTheMovingImageFileName (InputFilename.c_str ()); app->SetTheFixedImageFileName (TargetFilename.c_str ()); app->SetWarpedImageName (OutputFilename.c_str ()); app->SetMedianFilterRadius(MedianFilterRadius); //Set the other optional arguments if specified by the user. if (DisplacementPrefix != "") { app->SetDisplacementBaseName (DisplacementPrefix.c_str ()); } if (OutputDeformationFilename != "") { app->SetDeformationFieldOutputName (OutputDeformationFilename.c_str ()); } if (CheckerboardFilename != "") { app->SetCheckerBoardFileName (CheckerboardFilename.c_str ()); if (CheckerboardPattern != "") { unsigned int array[3] = { command.GetValueAsInt ("CheckerPattern", "XPattern"), command.GetValueAsInt ("CheckerPattern", "YPattern"), command.GetValueAsInt ("CheckerPattern", "ZPattern") }; app->SetCheckerBoardPattern (array); } } if (command.GetValueAsBool ("Normalize", "norm")) { std::string normalize = "ON"; app->SetOutNormalized (normalize.c_str ()); } if (command.GetValueAsBool ("DEBUG", "debug")) { std::string debug = "ON"; app->SetOutDebug (debug.c_str ()); } //If Making BOBF option is specified Initialize its parameters if (command.GetValueAsBool ("BOBF", "bobf")) { if ((command.GetValueAsString ("BOBFTargetMaskname", "tgmask") == "") || (command. GetValueAsString ("BOBFTemplateMaskname", "tmpgmask") == "")) { std::cout << "Error: If BOBF option is set then the target mask name and template mask file name should be specified. \n"; exit(-1); } app->SetBOBFTargetMask (command. GetValueAsString ("BOBFTargetMaskname", "tgmask").c_str ()); app->SetBOBFTemplateMask (command. GetValueAsString ("BOBFTemplateMaskname", "tmpgmask").c_str ()); app->SetLower (command.GetValueAsInt ("BOBFLtshd", "ltshd")); app->SetUpper (command.GetValueAsInt ("BOBFUtshd", "utshd")); typename ImageType::SizeType radius; radius[0] = command.GetValueAsInt ("BOBFNeighX", "nbdx"); // Radius along X radius[1] = command.GetValueAsInt ("BOBFNeighY", "nbdy"); // Radius along Y radius[2] = command.GetValueAsInt ("BOBFNeighZ", "nbdz"); // Radius along Z app->SetRadius (radius); typename ImageType::IndexType seed; seed[0] = command.GetValueAsInt ("BOBFSeedX", "seedx"); // Seed in X dimension; seed[1] = command.GetValueAsInt ("BOBFSeedY", "seedy"); // Seed in Y dimension; seed[2] = command.GetValueAsInt ("BOBFSeedZ", "seedz"); // Seed in Z dimension; app->SetSeed (seed); } std::cout << "Setting Default PixelValue: " << command.GetValueAsInt ("BOBFBgnd", "bgnd") << "."<<std::endl; app->SetDefaultPixelValue (command.GetValueAsInt ("BOBFBgnd", "bgnd")); std::cout << "Running Thirion Registration" << std::endl; try { app->Execute (); } catch (itk::ExceptionObject & err) { std::cout << "Caught an ITK exception: " << std::endl; std::cout << err << " " << __FILE__ << " " << __LINE__ << std::endl; throw err; } catch (...) { std:: cout << "Caught a non-ITK exception " << __FILE__ << " " << __LINE__ << std::endl; } return ; } //This function processes the output data type. template < class PixelType > void ProcessOutputType (MetaCommand command) { const std::string OutType (command. GetValueAsString ("OutputPixelType", "PixelType")); if (command.GetValueAsString ("OutputPixelType", "PixelType") != "") { // process the string for the data type if (CompareNoCase (OutType.c_str (), std::string ("UCHAR")) == 0) { ThirionFunction < PixelType, unsigned char > (command); } else if (CompareNoCase (OutType.c_str (), std::string ("SHORT")) == 0) { ThirionFunction < PixelType, short > (command); } else if (CompareNoCase (OutType.c_str (), std::string ("USHORT")) == 0) { ThirionFunction < PixelType, unsigned short > (command); } else if (CompareNoCase (OutType.c_str (), std::string ("INT")) == 0) { ThirionFunction < PixelType, int > (command); } else if (CompareNoCase (OutType.c_str (), std::string ("FLOAT")) == 0) { ThirionFunction < PixelType, float > (command); } else { std::cout << "Error. Invalid data type for -outtype! Use one of these:" << std::endl; PrintDataTypeStrings (); exit (-1); } } else { ThirionFunction < PixelType, float > (command); } } int ThrionRegistrationPrimary(int argc, char *argv[]) { MetaCommand command; //Moving image filename. command.SetOption("InputFilename","input",true,"InputFile name"); command.AddOptionField("InputFilename","filename",MetaCommand::STRING,true); //Output image filename. command.SetOption("OutputFilename","output",true,"OutputFile name"); command.AddOptionField("OutputFilename","filename",MetaCommand::STRING,true); //Target image filename. command.SetOption("TargetFilename","target",true,"TargetFile name"); command.AddOptionField("TargetFilename","filename",MetaCommand::STRING,true); //Parameter filename containing histogram parameters and number of resolution levels. command.SetOption("ParameterFilename","p",true,"ParameterFile name"); command.AddOptionField("ParameterFilename","filename",MetaCommand::STRING,true); command.SetOption("InputPixelType","intype",true,"InputPixel Type UCHAR|SHORT|USHORT|INT|FLOAT"); command.AddOptionField("InputPixelType","PixelType",MetaCommand::STRING,true); //The images will be written in this type. The default is input pixel type. command.SetOption("OutputPixelType","outtype",false,"OutputPixel Type UCHAR|SHORT|USHORT|INT|FLOAT"); command.AddOptionField("OutputPixelType","PixelType",MetaCommand::STRING,false); //The prefix of the displacementfield to be written. X,Y,Z displacement fields will be written with the prefix added to them. command.SetOption("DisplacementField","dispfields",false,"DisplacementField Prefix"); command.AddOptionField("DisplacementField","Prefix",MetaCommand::STRING,false); //Checkerboard option gives the checker image of the fixed image and the output image. command.SetOption("CheckerboardFilename","checkerbd",false,"CheckerFile name"); command.AddOptionField("CheckerboardFilename","filename",MetaCommand::STRING,false); //Checker patterns for the checker board image. command.SetOption("CheckerPattern","cbpattern",false,"CheckerBoard Pattern"); command.AddOptionField("CheckerPattern","XPattern",MetaCommand::INT,false,"4"); command.AddOptionField("CheckerPattern","YPattern",MetaCommand::INT,false,"4"); command.AddOptionField("CheckerPattern","ZPattern",MetaCommand::INT,false,"4"); //Writes the deformation field to the filename specified by this option. command.SetOption("OutputDeformationFieldname","defwrite",false,"Deformation Field Output."); command.AddOptionField("OutputDeformationFieldname","filename",MetaCommand::STRING,false); //This option allows to warp and write the normalized images to output. In normalized images the image values are shfit-scaled to be between 0 and 1 command.SetOption("Normalize","norm",false,"Warp Normalized Images."); command.AddOptionField("Normalize","norm",MetaCommand::FLAG,false); //This Option helps you to write the images after each step command.SetOption("DEBUG","debug",false,"Write intermediate Images."); command.AddOptionField("DEBUG","debug",MetaCommand::FLAG,false); //Make BOBF images. command.SetOption("BOBF","bobf",false,"Make BOBF Images (use -debug flag to view results)"); command.AddOptionField("BOBF","bobf",MetaCommand::FLAG,false); //BOBF Fixed Mask filename. command.SetOption("BOBFTargetMaskname","tgmask",false,"Target Mask name to perform BOBF"); command.AddOptionField("BOBFTargetMaskname","tgmask",MetaCommand::STRING, false); //BOBF Moving Mask filename. command.SetOption("BOBFTemplateMaskname","tmpmask",false,"Template Mask name to perform BOBF"); command.AddOptionField("BOBFTemplateMaskname","tmpgmask",MetaCommand::STRING, false); //Lower Threshold for the BOBF command.SetOption("BOBFLtshd","ltshd",false,"Lower Threshold for performing BOBF. Default 0"); command.AddOptionField("BOBFLtshd","ltshd",MetaCommand::INT,false,"0"); //Backgrnd Replace Value for the BOBF command.SetOption("BOBFBgnd","bgnd",false,"Background fill with this value Default 0"); command.AddOptionField("BOBFBgnd","bgnd",MetaCommand::INT,false,"0"); //Upper Threshold for the BOBF command.SetOption("BOBFUtshd","utshd",false,"Upper Threshold for performing BOBF. Default 70"); command.AddOptionField("BOBFUtshd","utshd",MetaCommand::INT,false,"70"); //Seed X for BOBF command.SetOption("BOBFSeedX","seedx",false,"Seed X for BOBF. Default 0"); command.AddOptionField("BOBFSeedX","seedx",MetaCommand::INT,false,"0"); //Seed Y for BOBF command.SetOption("BOBFSeedY","seedy",false,"Seed Y for BOBF. Default 0"); command.AddOptionField("BOBFSeedY","seedy",MetaCommand::INT,false,"0"); //Seed Z for BOBF command.SetOption("BOBFSeedZ","seedz",false,"Seed Z for BOBF. Default 0"); command.AddOptionField("BOBFSeedZ","seedz",MetaCommand::INT,false,"0"); //X Neighborhood to be included for BOBF command.SetOption("BOBFNeighX","nbdx",false,"X Neighborhood to be included for BOBF. Default 1"); command.AddOptionField("BOBFNeighX","nbdx",MetaCommand::INT,false,"1"); //Y Neighborhood to be included for BOBF command.SetOption("BOBFNeighY","nbdy",false,"Y Neighborhood to be included for BOBF. Default 1"); command.AddOptionField("BOBFNeighY","nbdy",MetaCommand::INT,false,"1"); //Z Neighborhood to be included for BOBF command.SetOption("BOBFNeighZ","nbdz",false,"Z Neighborhood to be included for BOBF. Default 1"); command.AddOptionField("BOBFNeighZ","nbdz",MetaCommand::INT,false,"1"); command.SetOption("Median","median",false,"Apply median filter to input images"); command.AddOptionField("Median","radius",MetaCommand::INT,false,"0"); command.SetOption("InitialTransform","InitialTransform",false,"Initial Transform for registration"); command.AddOptionField("InitialTransform","filename",MetaCommand::STRING,false,""); if (!command.Parse(argc,argv)) { return 1; } std::cout << "Running as: \n"; for(int i=0; i<argc; i++) { std::cout << " " << argv[i]; } std::cout << std::endl; //Test if the input data type is valid const std::string PixelType(command.GetValueAsString("InputPixelType","PixelType")); if ( command.GetValueAsString("InputPixelType","PixelType") != "") { // check to see if valid type if (( CompareNoCase( PixelType.c_str(), std::string("UCHAR" ) ) ) && ( CompareNoCase( PixelType.c_str(), std::string("SHORT" ) ) ) && ( CompareNoCase( PixelType.c_str(), std::string("USHORT") ) ) && ( CompareNoCase( PixelType.c_str(), std::string("INT" ) ) ) && ( CompareNoCase( PixelType.c_str(), std::string("FLOAT" ) ) ) ) { std::cout << "Error. Invalid data type string specified with -intype!" << std::endl; std::cout << "Use one of the following:" << std::endl; PrintDataTypeStrings(); exit(-1); } } const std::string OutPixelType(command.GetValueAsString("OutputPixelType", "PixelType" )); if ( command.GetValueAsString("OutputPixelType","PixelType" ) != "") { // check to see if valid type if( ( CompareNoCase( OutPixelType.c_str(), std::string("UCHAR" ) ) ) && ( CompareNoCase( OutPixelType.c_str(), std::string("SHORT") ) ) && ( CompareNoCase( OutPixelType.c_str(), std::string("USHORT") ) ) && ( CompareNoCase( OutPixelType.c_str(), std::string("INT" ) ) ) && ( CompareNoCase( OutPixelType.c_str(), std::string("FLOAT" ) ) ) ) { std::cout << "Error. Invalid data type string specified with -intype!" << std::endl; std::cout << "Use one of the following:" << std::endl; PrintDataTypeStrings(); exit(-1); } } //Call the process output data type function based on the input data type. const std::string InType(command.GetValueAsString("InputPixelType", "PixelType")); if (CompareNoCase (InType, std::string ("UCHAR")) == 0) { ProcessOutputType < unsigned char > (command); } else if (CompareNoCase (InType, std::string ("SHORT")) == 0) { ProcessOutputType < short > (command); } else if (CompareNoCase (InType, std::string ("USHORT")) == 0) { ProcessOutputType < unsigned short > (command); } else if (CompareNoCase (InType, std::string ("INT")) == 0) { ProcessOutputType < int > (command); } else if (CompareNoCase (InType, std::string ("FLOAT")) == 0) { ProcessOutputType < float > (command); } else { std::cout << "Error. Invalid data type for -intype! Use one of these:" << std::endl; PrintDataTypeStrings (); exit (-1); } return 0; }
41.530093
157
0.643777
Piyusha23
6426db6d2a533df9a3b75ea5d593d82079b85a8a
11,704
cpp
C++
src/graphics/scene/BoardRenderable.cpp
petuzk/Warcaby
2102493199c7edf9ea752dfcb374435d5b9049fd
[ "MIT" ]
null
null
null
src/graphics/scene/BoardRenderable.cpp
petuzk/Warcaby
2102493199c7edf9ea752dfcb374435d5b9049fd
[ "MIT" ]
null
null
null
src/graphics/scene/BoardRenderable.cpp
petuzk/Warcaby
2102493199c7edf9ea752dfcb374435d5b9049fd
[ "MIT" ]
null
null
null
#include "inc/graphics/scene/BoardRenderable.hpp" #include "src/game/board/Board_template.cpp" #include "src/graphics/scene/CheckerRenderable_template.cpp" rl::Model BoardRenderable::rlModel = { 0 }; int BoardRenderable::shaderHlFromLoc[SHADER_MAX_HIGHLIGHTS]; int BoardRenderable::shaderHlToLoc[SHADER_MAX_HIGHLIGHTS]; int BoardRenderable::shaderHlColorLoc[SHADER_MAX_HIGHLIGHTS]; const rl::Vector3 BoardRenderable::CAMERA_TARGET = { 0.0f, 0.5f, 0.0f }; BoardRenderable::BoardRenderable(): Renderable(Renderable::T3D), Updatable(Priority::PBoardRenderable) { if (rlModel.meshCount == 0) { // Generacja modeli planszy static constexpr float width = 9.0f; static constexpr float height = 1.0f; static constexpr float length = 9.0f; rl::Mesh topMesh = rl::GenMeshPlane(width, length, 5, 5); rl::Mesh sideMesh = { 0 }; sideMesh.vboId = new unsigned int[7]; sideMesh.vertexCount = 16; sideMesh.triangleCount = 8; float vertices[] = { -width/2, -height, length/2, width/2, -height, length/2, width/2, 0, length/2, -width/2, 0, length/2, -width/2, -height, -length/2, -width/2, 0, -length/2, width/2, 0, -length/2, width/2, -height, -length/2, width/2, -height, -length/2, width/2, 0, -length/2, width/2, 0, length/2, width/2, -height, length/2, -width/2, -height, -length/2, -width/2, -height, length/2, -width/2, 0, length/2, -width/2, 0, -length/2 }; float texcoords[] = { 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, }; float normals[] = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,-1.0f, 0.0f, 0.0f,-1.0f, 0.0f, 0.0f,-1.0f, 0.0f, 0.0f,-1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f }; sideMesh.vertices = new float[sideMesh.vertexCount * 3]; std::memcpy(sideMesh.vertices, vertices, sideMesh.vertexCount*3*sizeof(float)); sideMesh.texcoords = new float[sideMesh.vertexCount * 2]; std::memcpy(sideMesh.texcoords, texcoords, sideMesh.vertexCount*2*sizeof(float)); sideMesh.normals = new float[sideMesh.vertexCount * 3]; std::memcpy(sideMesh.normals, normals, sideMesh.vertexCount*3*sizeof(float)); sideMesh.indices = new unsigned short[sideMesh.triangleCount * 3]; for (int i = 0, k = 0; i < sideMesh.triangleCount*3; i+=6, k+=4) { sideMesh.indices[i+0] = k; sideMesh.indices[i+1] = k+1; sideMesh.indices[i+2] = k+2; sideMesh.indices[i+3] = k; sideMesh.indices[i+4] = k+2; sideMesh.indices[i+5] = k+3; } rl::rlLoadMesh(&sideMesh, false); // kolejny "bezpiecznik" -- obraz się nie załaduje gdy zmienimy rozmiar planszy a nie dodamy odpowiedniego obrazu rl::Texture2D topAlbedoTex = rl::LoadTexture(rl::TextFormat("resources/images/board/%dx%d_top_albedo.png", BoardConst::SIZE, BoardConst::SIZE)); rl::Texture2D topNormalTex = rl::LoadTexture(rl::TextFormat("resources/images/board/%dx%d_top_normal.png", BoardConst::SIZE, BoardConst::SIZE)); rl::Texture2D sideAlbedoTex = rl::LoadTexture("resources/images/board/side_albedo.png"); rl::Texture2D sideNormalTex = rl::LoadTexture("resources/images/board/side_normal.png"); rl::Shader shader = ShaderProvider::getInstance()->loadShader("resources/shaders/base.vs", "resources/shaders/board.fs"); shader.locs[rl::LOC_MAP_ALBEDO] = rl::GetShaderLocation(shader, "albedoSampler"); shader.locs[rl::LOC_MAP_NORMAL] = rl::GetShaderLocation(shader, "normalsSampler"); for (int i = 0; i < SHADER_MAX_HIGHLIGHTS; i++) { shaderHlFromLoc[i] = rl::GetShaderLocation(shader, rl::TextFormat("hlSquares[%d].from", i)); shaderHlToLoc[i] = rl::GetShaderLocation(shader, rl::TextFormat("hlSquares[%d].to", i)); shaderHlColorLoc[i] = rl::GetShaderLocation(shader, rl::TextFormat("hlSquares[%d].color", i)); } rlModel.transform = rl::MatrixIdentity(); rlModel.meshCount = 2; rlModel.meshes = new rl::Mesh[rlModel.meshCount]; rlModel.meshes[0] = topMesh; rlModel.meshes[1] = sideMesh; rlModel.materialCount = 2; rlModel.materials = new rl::Material[rlModel.materialCount]; rlModel.materials[0] = rl::LoadMaterialDefault(); rlModel.materials[0].shader = shader; rlModel.materials[0].maps[rl::MAP_ALBEDO].texture = topAlbedoTex; rlModel.materials[0].maps[rl::MAP_NORMAL].texture = topNormalTex; rlModel.materials[1] = rl::LoadMaterialDefault(); rlModel.materials[1].shader = shader; rlModel.materials[1].maps[rl::MAP_ALBEDO].texture = sideAlbedoTex; rlModel.materials[1].maps[rl::MAP_NORMAL].texture = sideNormalTex; rlModel.meshMaterial = new int[rlModel.meshCount]; rlModel.meshMaterial[0] = 0; rlModel.meshMaterial[1] = 1; } reset(); } void BoardRenderable::reset() { ifState = NONE; inputEnabled = true; delayedShaderUpdate = false; Board::reset<CheckerRenderable<CheckerMan>>(); } void BoardRenderable::setInputEnabled(bool en) { inputEnabled = en; if (!inputEnabled) { prevPointed = Square(); updateShaderColor(0); } else { delayedShaderUpdate = true; } } void BoardRenderable::draw() { rl::DrawModel(rlModel, (rl::Vector3){ 0.0f, 0.0f, 0.0f }, 1.0f, rl::WHITE); } void BoardRenderable::requestMoveFor(HumanPlayer* player, std::shared_ptr<PlayerMoveSequence> sequence) { updateShaderColor(0); delayedShaderUpdate = true; moveForPlayer = player; moveSequence = sequence; prevPointed = selectedMoveSquare = reSelectedCheckerSquare = Square(); if (sequence->getOriginsForNextMove().size() > 1) { ifState = SELECT_CHECKER; possibleMoves.clear(); selectedCheckerSquare = Square(); } else { Square start = sequence->getOriginsForNextMove().at(0); std::shared_ptr<Checker> c = at(start); if (c == nullptr || c->getSide() != player->getSide()) throw std::logic_error("bad move selection origin"); ifState = SELECT_MOVE; possibleMoves = c->getPossibleMoves(this, moveSequence); selectedCheckerSquare = start; } Camera::getInstance()->moveToSide(player->getSide()); } void BoardRenderable::update() { if (ifState == NONE || !inputEnabled) { return; } bool updateShader = delayedShaderUpdate; delayedShaderUpdate = false; Square pointed = getPointedSquare(); if (pointed != prevPointed) { prevPointed = pointed; std::shared_ptr<Checker> c = at(pointed); if (ifState == SELECT_CHECKER) { if ((c == nullptr || c->getSide() != moveForPlayer->getSide())) { if (selectedCheckerSquare) { selectedCheckerSquare = Square(); possibleMoves.clear(); updateShader = true; } } else { selectedCheckerSquare = pointed; if (moveSequence->isOriginForNextMove(selectedCheckerSquare)) { possibleMoves = c->getPossibleMoves(this, moveSequence); } else { possibleMoves.clear(); } updateShader = true; } } else if (ifState == SELECT_MOVE) { if (c == nullptr) { Square newSelectedMoveSquare = Square(); for (PlayerMove& move: possibleMoves) { Square dest = move.getDestination(); if (pointed == dest) { newSelectedMoveSquare = dest; break; } } if (selectedMoveSquare != newSelectedMoveSquare || reSelectedCheckerSquare) { reSelectedCheckerSquare = Square(); selectedMoveSquare = newSelectedMoveSquare; updateShader = true; } } else { if (c->getSide() != moveForPlayer->getSide()) { if (reSelectedCheckerSquare) { reSelectedCheckerSquare = Square(); updateShader = true; } } else if (moveSequence->isOriginForNextMove(pointed)) { reSelectedCheckerSquare = pointed; updateShader = true; } } } } if (rl::IsMouseButtonPressed(rl::MOUSE_LEFT_BUTTON)) { if (ifState == SELECT_CHECKER) { if (selectedCheckerSquare && moveSequence->isOriginForNextMove(selectedCheckerSquare)) { ifState = SELECT_MOVE; } } else if (ifState == SELECT_MOVE) { if (reSelectedCheckerSquare) { selectedCheckerSquare = reSelectedCheckerSquare; possibleMoves = at(selectedCheckerSquare)->getPossibleMoves(this, moveSequence); updateShader = true; } else { for (PlayerMove& move: possibleMoves) { if (selectedMoveSquare == move.getDestination()) { ifState = NONE; /* Jeżeli zastąpić to `updateShader = true;` i `break;`, to w efekcie końcowym wywołanie * Player::respond() doprowadzi do kolejnego wywołania BoardRenderable::requestMoveFor(), * które zmieni ifState oraz inne zmienne stanu, i wtedy wywołanie updateShaderData() niżej * narysuje te zmiany przed rozpoczęciem animacji. */ updateShaderData(); moveForPlayer->respond(move); return; } } } } } if (updateShader) { updateShaderData(); } } void BoardRenderable::updateShaderPos(int i, Square sq) { float xpos = sq.col() / 9.0f + 1.0f / 18.0f; float zpos = (BoardConst::SIZE - sq.row() - 1) / 9.0f + 1.0f / 18.0f; rl::SetShaderValue(rlModel.materials[0].shader, shaderHlFromLoc[i], (float[2]){ xpos, zpos }, rl::UNIFORM_VEC2); rl::SetShaderValue(rlModel.materials[0].shader, shaderHlToLoc[i], (float[2]){ xpos + 1.0f/9.0f, zpos + 1.0f/9.0f }, rl::UNIFORM_VEC2); } void BoardRenderable::updateShaderColor(int i, rl::Color c) { float color[4] = { c.r / 255.0f, c.g / 255.0f, c.b / 255.0f, c.a / 255.0f }; rl::SetShaderValue(rlModel.materials[0].shader, shaderHlColorLoc[i], &color, rl::UNIFORM_VEC4); } void BoardRenderable::updateShaderData() { int i = 0, size = possibleMoves.size(); if (SHADER_MAX_HIGHLIGHTS < size) // sytuacja (prawdopodobnie) niemożliwa size = SHADER_MAX_HIGHLIGHTS; rl::Shader shader = rlModel.materials[0].shader; if (ifState == NONE) { updateShaderColor(0); } else if (ifState == SELECT_CHECKER) { if (!selectedCheckerSquare) { updateShaderColor(0); } else { updateShaderPos(0, selectedCheckerSquare); if (size == 0) { updateShaderColor(0, rl::RED); // maroon, orange } else { updateShaderColor(0, rl::GREEN); //lime, darkgreen for ( ; i < size; i++) { updateShaderPos(i + 1, possibleMoves[i].getDestination()); updateShaderColor(i + 1, rl::BROWN); } } if (i + 1 < SHADER_MAX_HIGHLIGHTS) { updateShaderColor(i + 1); } } } else if (ifState == SELECT_MOVE) { updateShaderPos(0, selectedCheckerSquare); updateShaderColor(0, rl::GREEN); for ( ; i < size; i++) { Square dest = possibleMoves[i].getDestination(); updateShaderPos(i + 1, dest); updateShaderColor(i + 1, dest == selectedMoveSquare ? rl::BEIGE : rl::BROWN); } if (i + 1 < SHADER_MAX_HIGHLIGHTS && reSelectedCheckerSquare) { updateShaderPos(i + 1, reSelectedCheckerSquare); updateShaderColor(i + 1, rl::GREEN); i++; } if (i + 1 < SHADER_MAX_HIGHLIGHTS) { updateShaderColor(i + 1); } } } Square BoardRenderable::getPointedSquare() { static const rl::Vector3 triangles[] = { { -4.0f, 0.0f, -4.0f }, { 4.0f, 0.0f, 4.0f }, { 4.0f, 0.0f, -4.0f }, { -4.0f, 0.0f, -4.0f }, { -4.0f, 0.0f, 4.0f }, { 4.0f, 0.0f, 4.0f }, }; rl::Ray ray = Camera::getInstance()->getMouseRay(); rl::RayHitInfo hitInfo; for (int i = 0; i < 6; i += 3) { hitInfo = rl::GetCollisionRayTriangle(ray, triangles[i], triangles[i+1], triangles[i+2]); if (hitInfo.hit) { int xsq = hitInfo.position.x + 4.0f; int zsq = hitInfo.position.z + 4.0f; return Square(xsq, BoardConst::SIZE - zsq - 1); } } return Square(); }
30.558747
146
0.66285
petuzk
6428afc1bf1c0257688956df9929ef74b371df01
936
cpp
C++
libs/options/src/options/option_name_comparison.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/options/src/options/option_name_comparison.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/options/src/options/option_name_comparison.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <fcppt/strong_typedef_comparison.hpp> #include <fcppt/options/option_name.hpp> #include <fcppt/options/option_name_comparison.hpp> #include <fcppt/config/external_begin.hpp> #include <utility> #include <fcppt/config/external_end.hpp> bool fcppt::options::operator==( fcppt::options::option_name const &_left, fcppt::options::option_name const &_right ) { return _left.name_ == _right.name_ && _left.is_short_ == _right.is_short_; } bool fcppt::options::operator<( fcppt::options::option_name const &_left, fcppt::options::option_name const &_right ) { return std::make_pair( _left.name_, _left.is_short_ ) < std::make_pair( _right.name_, _right.is_short_ ); }
19.5
61
0.711538
pmiddend
642b4cbccd243e294bc48caca7b79bb1dd960dc3
33,871
cpp
C++
src/Graphics/Isosurface.cpp
llGuy/Ondine
325c2d3ea5bd5ef5456b0181c53ad227571fada3
[ "MIT" ]
1
2022-01-24T18:15:56.000Z
2022-01-24T18:15:56.000Z
src/Graphics/Isosurface.cpp
llGuy/Ondine
325c2d3ea5bd5ef5456b0181c53ad227571fada3
[ "MIT" ]
null
null
null
src/Graphics/Isosurface.cpp
llGuy/Ondine
325c2d3ea5bd5ef5456b0181c53ad227571fada3
[ "MIT" ]
null
null
null
#include "Math.hpp" #include "Terrain.hpp" #include "Isosurface.hpp" namespace Ondine::Graphics { const glm::vec3 Isosurface::NORMALIZED_CUBE_VERTICES[8] = { glm::vec3(-0.5f, -0.5f, -0.5f), glm::vec3(+0.5f, -0.5f, -0.5f), glm::vec3(-0.5f, +0.5f, -0.5f), glm::vec3(+0.5f, +0.5f, -0.5f), glm::vec3(-0.5f, -0.5f, +0.5f), glm::vec3(+0.5f, -0.5f, +0.5f), glm::vec3(-0.5f, +0.5f, +0.5f), glm::vec3(+0.5f, +0.5f, +0.5f), }; const glm::ivec3 Isosurface::NORMALIZED_CUBE_VERTEX_INDICES[8] = { glm::ivec3(0, 0, 0), glm::ivec3(1, 0, 0), glm::ivec3(0, 1, 0), glm::ivec3(1, 1, 0), glm::ivec3(0, 0, 1), glm::ivec3(1, 0, 1), glm::ivec3(0, 1, 1), glm::ivec3(1, 1, 1), }; void Isosurface::init(const QuadTree &quadTree, VulkanContext &graphicsContext) { mGPUVerticesAllocator.init( 10000, (VulkanBufferFlagBits)VulkanBufferFlag::VertexBuffer, graphicsContext); mIsoGroups.init(1000); mIsoGroupIndices.init(); mVertexPool = (IsoVertex *)malloc( sizeof(IsoVertex) * 10000 * 4096); auto maxUpdateCount = quadTree.mDimensions * quadTree.mDimensions * 2; mFullUpdates = new IsoGroup *[maxUpdateCount]; mTransitionUpdates = new IsoGroup *[maxUpdateCount]; mFullUpdateCount = 0; mTransitionUpdateCount = 0; } void Isosurface::bindToTerrain(const Terrain &terrain) { mScale = terrain.mTerrainScale; mSurfaceDensity = {30000}; } void Isosurface::prepareForUpdate(QuadTree &quadTree, Terrain &terrain) { mScale = terrain.mTerrainScale; // Generates normals for updated chunks only terrain.generateVoxelNormals(); /* Step #1: Figure out which chunk groups to delete and to create Step #2: Figure out which chunk groups to update the meshes for Step #3: Figure out which chunk groups contained modified chunks Step #4: Update those damn chunk groups (BONUS) Make step #2 distinguish between chunk groups which require just mesh transitions or everything to be updated */ // Step #1 for (auto deletion : quadTree.mDiffDelete) { QuadTree::Node *node = deletion.node; glm::ivec2 offset = {node->offsetx, node->offsety}; // How many chunks does this node encompass int width = pow(2, quadTree.mMaxLOD - node->level); for (int z = offset.y; z < offset.y + width; ++z) { for (int x = offset.x; x < offset.x + width; ++x) { glm::ivec2 offset = quadTreeCoordsToChunk(quadTree, {x, z}); IsoGroup *lowest = getFirstFlatIsoGroup(offset); if (lowest) { mFlatIsoGroupIndices.remove(hashFlatChunkCoord(offset)); while (lowest) { // Delete the chunk group auto nextKey = lowest->next; freeIsoGroup(lowest); if (nextKey == INVALID_CHUNK_INDEX) { break; } else { lowest = mIsoGroups[nextKey]; } } } } } } // Step #2 for (auto addition : quadTree.mDiffAdd) { QuadTree::Node *node = addition.node; auto deepestNodes = quadTree.getDeepestNodesUnder(node); for (auto nodeInfo : deepestNodes) { glm::ivec2 offset = quadTreeCoordsToChunk(quadTree, nodeInfo.offset); int width = pow(2, quadTree.mMaxLOD - nodeInfo.level); // Generate chunk groups for (int z = offset.y; z < offset.y + width; ++z) { for (int x = offset.x; x < offset.x + width; ++x) { // For now we assume that the terrain doesn't get modified Chunk *current = terrain.getFirstFlatChunk(glm::ivec2(x, z)); while (current) { glm::ivec3 groupCoord = getIsoGroupCoord( quadTree, current->chunkCoord); IsoGroup *group = getIsoGroup(groupCoord); group->level = nodeInfo.level; current->chunkGroupKey = group->key; int stride = (int)pow(2, quadTree.mMaxLOD - nodeInfo.level); float width = stride; glm::vec3 chunkCoordOffset = (glm::vec3)( current->chunkCoord - groupCoord); glm::vec3 start = (float)CHUNK_DIM * (chunkCoordOffset / width); for (int z = 0 ; z < CHUNK_DIM / stride; ++z) { for (int y = 0 ; y < CHUNK_DIM / stride; ++y) { for (int x = 0 ; x < CHUNK_DIM / stride; ++x) { glm::ivec3 coord = glm::ivec3(x, y, z); uint32_t dstVIndex = getVoxelIndex(coord + (glm::ivec3)start); uint32_t srcVIndex = getVoxelIndex(coord * stride); group->voxels[dstVIndex] = current->voxels[srcVIndex]; } } } // Need to add transition updates for neighbouring chunk groups if (!group->pushedToFullUpdates) { mFullUpdates[mFullUpdateCount++] = group; group->pushedToFullUpdates = 1; } if (current->next == INVALID_CHUNK_INDEX) { current = nullptr; } else { current = terrain.mLoadedChunks[current->next]; } } } } } } for (auto addition : quadTree.mDiffAdd) { QuadTree::Node *node = addition.node; int width = pow(2, quadTree.mMaxLOD - node->level); glm::ivec2 qtCoord = {node->offsetx, node->offsety}; glm::ivec2 chunkCoord = quadTreeCoordsToChunk(quadTree, qtCoord); int components[] = { // Z, Z, X, X 2, 2, 0, 0 }; glm::ivec2 offsets[] = { {-1, 0}, {width, 0}, {0, -1}, {0, width} }; glm::ivec2 nav[] = { {0, 1}, {0, 1}, {1, 0}, {1, 0} }; // Check neighbouring chunk groups for (int i = 0; i < 4; ++i) { glm::ivec2 adjNodeCoord = qtCoord + offsets[i]; auto adjNodeInfo = quadTree.getNodeInfo((glm::vec2)adjNodeCoord); if (adjNodeInfo.exists && !adjNodeInfo.wasDiffed) { // (hmmm?) Transitions only need to be done for nodes with lower LOD glm::ivec2 adjChunkCoord = quadTreeCoordsToChunk( quadTree, adjNodeInfo.offset); int comp3D = components[i]; int comp2D = comp3D / 2; while ( adjChunkCoord[comp2D] < chunkCoord[comp2D] + width && adjNodeInfo.exists) { int adjWidth = pow(2, quadTree.mMaxLOD - adjNodeInfo.level); // Do something IsoGroup *lowest = getFirstFlatIsoGroup(adjChunkCoord); while (lowest) { if (!lowest->pushedToFullUpdates && !lowest->pushedToTransitionUpdates) { lowest->pushedToTransitionUpdates = 1; mTransitionUpdates[mTransitionUpdateCount++] = lowest; } auto nextKey = lowest->next; if (nextKey == INVALID_CHUNK_INDEX) { break; } else { lowest = mIsoGroups[nextKey]; } } adjChunkCoord[comp2D] += adjWidth; adjNodeCoord[comp2D] += adjWidth; adjNodeInfo = quadTree.getNodeInfo((glm::vec2)adjNodeCoord); } } } } // For isogroups containing updated chunks, make sure to update voxel values for (int i = 0; i < terrain.mUpdatedChunks.size; ++i) { Chunk *chunk = terrain.mLoadedChunks[terrain.mUpdatedChunks[i]]; glm::ivec3 groupCoord = getIsoGroupCoord( quadTree, chunk->chunkCoord); IsoGroup *group = getIsoGroup(groupCoord); if (!group->pushedToFullUpdates) { mFullUpdates[mFullUpdateCount++] = group; group->pushedToFullUpdates = 1; glm::vec2 quadTreeCoord = glm::vec2(groupCoord.x, groupCoord.z) + glm::vec2(glm::pow(2.0f, quadTree.mMaxLOD - 1)); auto nodeInfo = quadTree.getNodeInfo(quadTreeCoord); group->level = nodeInfo.level; chunk->chunkGroupKey = group->key; int stride = (int)pow(2, quadTree.mMaxLOD - nodeInfo.level); float width = stride; glm::vec3 chunkCoordOffset = (glm::vec3)( chunk->chunkCoord - groupCoord); glm::vec3 start = (float)CHUNK_DIM * (chunkCoordOffset / width); for (int z = 0 ; z < CHUNK_DIM / stride; ++z) { for (int y = 0 ; y < CHUNK_DIM / stride; ++y) { for (int x = 0 ; x < CHUNK_DIM / stride; ++x) { glm::ivec3 coord = glm::ivec3(x, y, z); uint32_t dstVIndex = getVoxelIndex(coord + (glm::ivec3)start); uint32_t srcVIndex = getVoxelIndex(coord * stride); group->voxels[dstVIndex] = chunk->voxels[srcVIndex]; } } } } } terrain.clearUpdatedChunks(); quadTree.clearDiff(); Voxel surfaceDensity = {(uint16_t)30000}; uint32_t vertexCounter = 0; for (int i = 0; i < mFullUpdateCount; ++i) { IsoGroup *group = mFullUpdates[i]; uint32_t groupVertexCount = generateVertices( {terrain, quadTree, *group}, mVertexPool + vertexCounter); group->vertexCount = groupVertexCount; group->verticesMem = mVertexPool + vertexCounter; vertexCounter += groupVertexCount; groupVertexCount = generateTransVoxelVertices( {terrain, quadTree, *group}, mVertexPool + vertexCounter); group->transVoxelVertexCount = groupVertexCount; group->transVerticesMem = mVertexPool + vertexCounter; vertexCounter += groupVertexCount; } for (int i = 0; i < mTransitionUpdateCount; ++i) { IsoGroup *group = mTransitionUpdates[i]; uint32_t groupVertexCount = generateTransVoxelVertices( {terrain, quadTree, *group}, mVertexPool + vertexCounter); group->transVoxelVertexCount = groupVertexCount; group->transVerticesMem = mVertexPool + vertexCounter; vertexCounter += groupVertexCount; } } void Isosurface::syncWithGPU(const VulkanCommandBuffer &commandBuffer) { if (mFullUpdateCount) { for (int i = 0; i < mFullUpdateCount; ++i) { IsoGroup *group = mFullUpdates[i]; group->pushedToFullUpdates = 0; group->pushedToTransitionUpdates = 0; if (group->vertices.size()) { // This chunk already has allocated memory mGPUVerticesAllocator.free(group->vertices); } if (group->transVoxelVertices.size()) { // This chunk already has allocated memory mGPUVerticesAllocator.free(group->transVoxelVertices); } if (group->vertexCount) { auto slot = mGPUVerticesAllocator.allocate( sizeof(IsoVertex) * group->vertexCount); slot.write( commandBuffer, group->verticesMem, sizeof(IsoVertex) * group->vertexCount); group->vertices = slot; } else { group->vertices = {}; } if (group->transVoxelVertexCount) { auto slot = mGPUVerticesAllocator.allocate( sizeof(IsoVertex) * group->transVoxelVertexCount); slot.write( commandBuffer, group->transVerticesMem, sizeof(IsoVertex) * group->transVoxelVertexCount); group->transVoxelVertices = slot; } else { group->transVoxelVertices = {}; } } mFullUpdateCount = 0; mGPUVerticesAllocator.debugLogState(); } if (mTransitionUpdateCount) { for (int i = 0; i < mTransitionUpdateCount; ++i) { IsoGroup *group = mTransitionUpdates[i]; group->pushedToFullUpdates = 0; group->pushedToTransitionUpdates = 0; if (group->transVoxelVertices.size()) { // This chunk already has allocated memory mGPUVerticesAllocator.free(group->transVoxelVertices); } if (group->transVoxelVertexCount) { auto slot = mGPUVerticesAllocator.allocate( sizeof(IsoVertex) * group->transVoxelVertexCount); slot.write( commandBuffer, group->transVerticesMem, sizeof(IsoVertex) * group->transVoxelVertexCount); group->transVoxelVertices = slot; } else { group->transVoxelVertices = {}; } } mTransitionUpdateCount = 0; mGPUVerticesAllocator.debugLogState(); } } uint32_t Isosurface::hashIsoGroupCoord(const glm::ivec3 &coord) const { struct { union { struct { uint32_t padding: 2; uint32_t x: 10; uint32_t y: 10; uint32_t z: 10; }; uint32_t value; }; } hasher; hasher.value = 0; hasher.x = *(uint32_t *)(&coord.x); hasher.y = *(uint32_t *)(&coord.y); hasher.z = *(uint32_t *)(&coord.z); return (uint32_t)hasher.value; } glm::ivec3 Isosurface::getIsoGroupCoord( const QuadTree &quadTree, const glm::ivec3 &chunkCoord) const { glm::ivec2 quadTreeCoord = glm::ivec2(chunkCoord.x, chunkCoord.z) + glm::ivec2(glm::pow(2, quadTree.maxLOD() - 1)); QuadTree::NodeInfo node = quadTree.getNodeInfo(quadTreeCoord); node.offset -= glm::vec2(glm::pow(2.0f, quadTree.maxLOD() - 1)); glm::ivec3 coord = glm::ivec3(node.offset.x, chunkCoord.y, node.offset.y); // Round down the nearest 2^node.level int width = pow(2, quadTree.maxLOD() - node.level); coord.y = (int)(glm::floor( (float)coord.y / (float)width)) * width; return coord; } IsoGroup *Isosurface::getIsoGroup(const glm::ivec3 &coord) { uint32_t hash = hashIsoGroupCoord(coord); uint32_t *index = mIsoGroupIndices.get(hash); if (index) { // Chunk was already added return mIsoGroups[*index]; } else { IsoGroup *group = flAlloc<IsoGroup>(); auto key = mIsoGroups.add(group); zeroMemory(group); group->coord = coord; group->key = key; mIsoGroupIndices.insert(hash, key); addToFlatIsoGroupIndices(group); return group; } } void Isosurface::freeIsoGroup(IsoGroup *group) { uint32_t hash = hashIsoGroupCoord(group->coord); mIsoGroupIndices.remove(hash); if (group->vertices.size()) { mGPUVerticesAllocator.free(group->vertices); } if (group->transVoxelVertices.size()) { mGPUVerticesAllocator.free(group->transVoxelVertices); } mIsoGroups.remove(group->key); // This is temporary - TODO: Add pre-allocated space for chunk groups flFree(group); } glm::ivec2 Isosurface::quadTreeCoordsToChunk( const QuadTree &quadTree, glm::ivec2 offset) const { return offset - glm::ivec2(pow(2, quadTree.maxLOD() - 1)); } // One unit in offset = chunk coord. The origin of the quadtree is at 0,0 glm::ivec2 Isosurface::quadTreeCoordsToWorld( const QuadTree &quadTree, glm::ivec2 offset) const { offset -= glm::ivec2(pow(2, quadTree.maxLOD() - 1)); offset *= CHUNK_DIM * mScale; return offset; } glm::vec2 Isosurface::worldToQuadTreeCoords( const QuadTree &quadTree, glm::vec2 offset) const { offset /= (CHUNK_DIM * mScale); offset += glm::vec2(glm::pow(2.0f, quadTree.maxLOD() - 1)); return offset; } void Isosurface::addToFlatIsoGroupIndices(IsoGroup *group) { int x = group->coord.x, z = group->coord.z; uint32_t hash = hashFlatChunkCoord(glm::ivec2(x, z)); uint32_t *index = mFlatIsoGroupIndices.get(hash); if (index) { IsoGroup *head = mIsoGroups[*index]; group->next = head->key; *index = group->key; } else { mFlatIsoGroupIndices.insert(hash, group->key); group->next = INVALID_CHUNK_INDEX; } } IsoGroup *Isosurface::getFirstFlatIsoGroup(glm::ivec2 flatCoord) { uint32_t hash = hashFlatChunkCoord(flatCoord); uint32_t *index = mFlatIsoGroupIndices.get(hash); if (index) { return mIsoGroups[*index]; } else { return nullptr; } } uint32_t Isosurface::generateVertices( GenIsoGroupVerticesParams params, IsoVertex *meshVertices) { const auto &terrain = params.terrain; const auto &quadTree = params.quadTree; const auto &group = params.group; int groupSize = pow(2, quadTree.mMaxLOD - group.level); int stride = groupSize; // glm::ivec3 groupCoord = group.coord + glm::ivec3( // pow(2, mQuadTree.mMaxLOD - 1)); glm::ivec3 groupStart = group.coord * (int)CHUNK_DIM; // TODO: Optimise the getVoxel operation auto getVoxel = [&terrain, &groupSize, &groupStart]( uint32_t x, uint32_t y, uint32_t z) { return terrain.getVoxel(groupStart + glm::ivec3(x, y, z) * groupSize); }; auto getVoxelLOD = [&terrain, &groupSize, &groupStart, &stride]( uint32_t x, uint32_t y, uint32_t z, // Offset uint32_t ox, uint32_t oy, uint32_t oz) { return terrain.getVoxel( groupStart + glm::ivec3(x, y, z) * groupSize + glm::ivec3(ox, oy, oz) * stride / 2); }; uint32_t vertexCount = 0; for (uint32_t z = 1; z < CHUNK_DIM - 1; ++z) { for (uint32_t y = 1; y < CHUNK_DIM - 1; ++y) { for (uint32_t x = 1; x < CHUNK_DIM - 1; ++x) { Voxel voxelValues[8] = { group.voxels[getVoxelIndex(x, y, z)], group.voxels[getVoxelIndex(x + 1, y, z)], group.voxels[getVoxelIndex(x, y + 1, z)], group.voxels[getVoxelIndex(x + 1, y + 1, z)], group.voxels[getVoxelIndex(x, y, z + 1)], group.voxels[getVoxelIndex(x + 1, y, z + 1)], group.voxels[getVoxelIndex(x, y + 1, z + 1)], group.voxels[getVoxelIndex(x + 1, y + 1, z + 1)], }; updateVoxelCell( voxelValues, glm::ivec3(x, y, z), meshVertices, vertexCount); } } } return vertexCount; } uint32_t Isosurface::generateTransVoxelVertices( GenIsoGroupVerticesParams params, IsoVertex *meshVertices) { const auto &terrain = params.terrain; const auto &quadTree = params.quadTree; const auto &group = params.group; uint32_t vertexCount = 0; glm::ivec3 groupCoord = group.coord + glm::ivec3( pow(2, quadTree.mMaxLOD - 1)); updateIsoGroupFace( params, 0, 1, // Inner axis is X, outer axis is Y 2, 1, // We are updating the positive Z face meshVertices, vertexCount); updateIsoGroupFace( params, 0, 1, // Inner axis is X, outer axis is Y 2, 0, // We are updating the negative Z face meshVertices, vertexCount); updateIsoGroupFace( params, 1, 2, // Inner axis is Y, outer axis is Z 0, 1, // We are updating the positive X face meshVertices, vertexCount); updateIsoGroupFace( params, 1, 2, // Inner axis is Y, outer axis is Z 0, 0, // We are updating the negative X face meshVertices, vertexCount); updateIsoGroupFace( params, 0, 2, // Inner axis is x, outer axis is Z 1, 1, // We are updating the positive Y face meshVertices, vertexCount); updateIsoGroupFace( params, 0, 2, // Inner axis is X, outer axis is Z 1, 0, // We are updating the negative Y face meshVertices, vertexCount); return vertexCount; } void Isosurface::updateIsoGroupFace( GenIsoGroupVerticesParams params, uint32_t primaryAxis, uint32_t secondAxis, uint32_t faceAxis, uint32_t side, IsoVertex *meshVertices, uint32_t &vertexCount) { const auto &terrain = params.terrain; const auto &quadTree = params.quadTree; const auto &group = params.group; int groupSize = pow(2, quadTree.mMaxLOD - group.level); glm::ivec3 groupStart = group.coord * (int)CHUNK_DIM; int stride = groupSize; glm::ivec3 groupCoordOffset = glm::ivec3(0); groupCoordOffset[faceAxis] = (int)side * 2 - 1; glm::ivec3 adjacentCoord = group.coord + glm::ivec3( pow(2, quadTree.mMaxLOD - 1)); if (side == 1) { adjacentCoord += groupCoordOffset * groupSize; } else { adjacentCoord += groupCoordOffset; } QuadTree::NodeInfo adjacentNode = quadTree.getNodeInfo( glm::vec2(adjacentCoord.x, adjacentCoord.z)); if (adjacentNode.exists) { static const glm::ivec3 offsets[8] = { {0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {1, 1, 0}, {0, 0, 1}, {1, 0, 1}, {0, 1, 1}, {1, 1, 1}, }; auto getVoxel = [&terrain, &groupSize, &groupStart]( uint32_t x, uint32_t y, uint32_t z) { return terrain.getVoxel(groupStart + glm::ivec3(x, y, z) * groupSize); }; auto getVoxelLOD = [&terrain, &groupSize, &groupStart, &stride]( uint32_t x, uint32_t y, uint32_t z, // Offset uint32_t ox, uint32_t oy, uint32_t oz) { return terrain.getVoxel( groupStart + glm::ivec3(x, y, z) * groupSize + glm::ivec3(ox, oy, oz) * stride / 2); }; if (adjacentNode.level <= group.level) { uint32_t d2 = (CHUNK_DIM - 1) * side; for (uint32_t d1 = 0; d1 < CHUNK_DIM; ++d1) { for (uint32_t d0 = 0; d0 < CHUNK_DIM; ++d0) { Voxel voxelValues[8] = {}; for (int i = 0; i < 8; ++i) { glm::ivec3 voxelCoord = {}; voxelCoord[primaryAxis] = d0 + offsets[i][primaryAxis]; voxelCoord[secondAxis] = d1 + offsets[i][secondAxis]; voxelCoord[faceAxis] = d2 + offsets[i][faceAxis]; voxelValues[i] = getVoxel(voxelCoord.x, voxelCoord.y, voxelCoord.z); } glm::ivec3 coord = {}; coord[primaryAxis] = d0; coord[secondAxis] = d1; coord[faceAxis] = d2; updateVoxelCell(voxelValues, coord, meshVertices, vertexCount); } } } else { static const glm::ivec4 transOffsets[9] = { {0,0,0,0}, {0,0,1,0}, {1,0,0,0}, {0,0,0,1}, {0,0,1,1}, {1,0,0,1}, {0,1,0,0}, {0,1,1,0}, {1,1,0,0} }; uint32_t d2 = (CHUNK_DIM - 1) * side; for (uint32_t d1 = 0; d1 < CHUNK_DIM; ++d1) { for (uint32_t d0 = 0; d0 < CHUNK_DIM; ++d0) { Voxel voxelValues[8] = {}; for (int i = 0; i < 8; ++i) { glm::ivec3 voxelCoord = {}; voxelCoord[primaryAxis] = d0 + offsets[i][primaryAxis]; voxelCoord[secondAxis] = d1 + offsets[i][secondAxis]; voxelCoord[faceAxis] = d2 + offsets[i][faceAxis]; voxelValues[i] = getVoxel(voxelCoord.x, voxelCoord.y, voxelCoord.z); } Voxel transVoxels[13] = {}; for (int i = 0; i < 9; ++i) { glm::ivec3 voxelCoord = {}; voxelCoord[primaryAxis] = d0 + transOffsets[i][0]; voxelCoord[secondAxis] = d1 + transOffsets[i][1]; voxelCoord[faceAxis] = d2 + side; glm::ivec3 halfCoord = {}; halfCoord[primaryAxis] = transOffsets[i][2]; halfCoord[secondAxis] = transOffsets[i][3]; transVoxels[i] = getVoxelLOD( voxelCoord.x, voxelCoord.y, voxelCoord.z, halfCoord.x, halfCoord.y, halfCoord.z); } for (int i = 0; i < 4; ++i) { glm::ivec3 voxelCoord = {}; voxelCoord[primaryAxis] = d0 + offsets[i][0]; voxelCoord[secondAxis] = d1 + offsets[i][1]; voxelCoord[faceAxis] = d2 + side; transVoxels[i + 9] = getVoxel(voxelCoord.x, voxelCoord.y, voxelCoord.z); } static const int CUBE_AXIS_BITS[3][2][4] = { {{0, 2, 4, 6}, {1, 3, 5, 7}}, {{0, 1, 4, 5}, {2, 3, 6, 7}}, {{0, 1, 2, 3}, {4, 5, 6, 7}} }; for (int i = 0; i < 4; ++i) { transVoxels[i + 9].normalX = transVoxels[i + 9].normalX * 0.875 + voxelValues[CUBE_AXIS_BITS[faceAxis][(1 - side)][i]].normalX * 0.125; transVoxels[i + 9].normalY = transVoxels[i + 9].normalY * 0.875 + voxelValues[CUBE_AXIS_BITS[faceAxis][(1 - side)][i]].normalY * 0.125; transVoxels[i + 9].normalZ = transVoxels[i + 9].normalZ * 0.875 + voxelValues[CUBE_AXIS_BITS[faceAxis][(1 - side)][i]].normalZ * 0.125; voxelValues[CUBE_AXIS_BITS[faceAxis][side][i]].normalX = transVoxels[i + 9].normalX; voxelValues[CUBE_AXIS_BITS[faceAxis][side][i]].normalY = transVoxels[i + 9].normalY; voxelValues[CUBE_AXIS_BITS[faceAxis][side][i]].normalZ = transVoxels[i + 9].normalZ; } glm::ivec3 coord = {}; coord[primaryAxis] = d0; coord[secondAxis] = d1; coord[faceAxis] = d2; glm::ivec3 axis = {}; axis[faceAxis] = side * 2 - 1; updateTransVoxelCell( voxelValues, transVoxels, axis, coord, meshVertices, vertexCount); } } } } } #include "Transvoxel.inc" void Isosurface::updateVoxelCell( Voxel *voxels, const glm::ivec3 &coord, IsoVertex *meshVertices, uint32_t &vertexCount) { uint8_t bitCombination = 0; for (uint32_t i = 0; i < 8; ++i) { bool isOverSurface = (voxels[i].density > mSurfaceDensity.density); bitCombination |= isOverSurface << i; } if (bitCombination == 0 || bitCombination == 0xFF) { return; } uint8_t cellClassIdx = regularCellClass[bitCombination]; const RegularCellData &cellData = regularCellData[cellClassIdx]; glm::vec3 vertices[8] = {}; for (uint32_t i = 0; i < 8; ++i) { vertices[i] = NORMALIZED_CUBE_VERTICES[i] + glm::vec3(0.5f) + glm::vec3(coord); } IsoVertex *verts = STACK_ALLOC(IsoVertex, cellData.GetVertexCount()); for (int i = 0; i < cellData.GetVertexCount(); ++i) { uint16_t nibbles = regularVertexData[bitCombination][i]; if (nibbles == 0x0) { // Finished break; } uint8_t v0 = (nibbles >> 4) & 0xF; uint8_t v1 = nibbles & 0xF; float surfaceLevelF = (float)mSurfaceDensity.density; float voxelValue0 = (float)voxels[v0].density; float voxelValue1 = (float)voxels[v1].density; if (voxelValue0 > voxelValue1) { float tmp = voxelValue0; voxelValue0 = voxelValue1; voxelValue1 = tmp; uint8_t tmpV = v0; v0 = v1; v1 = tmpV; } float interpolatedVoxelValues = lerp(voxelValue0, voxelValue1, surfaceLevelF); glm::vec3 vertex = interpolate( vertices[v0], vertices[v1], interpolatedVoxelValues); glm::vec3 normal0 = glm::vec3( voxels[v0].normalX, voxels[v0].normalY, voxels[v0].normalZ) / 1000.0f; glm::vec3 normal1 = glm::vec3( voxels[v1].normalX, voxels[v1].normalY, voxels[v1].normalZ) / 1000.0f; glm::vec3 normal = interpolate( normal0, normal1, interpolatedVoxelValues); if (glm::dot(normal, normal) != 0.0f) { normal = glm::normalize(normal); } verts[i] = {vertex, normal}; } for (int i = 0; i < cellData.GetTriangleCount() * 3; ++i) { int vertexIndex = cellData.vertexIndex[i]; meshVertices[vertexCount++] = verts[vertexIndex]; } } void Isosurface::updateTransVoxelCell( Voxel *voxels, Voxel *transVoxels, const glm::ivec3 &axis, const glm::ivec3 &coord, IsoVertex *meshVertices, uint32_t &vertexCount) { const float percentTrans = 0.125f; { // Normal mesh creation uint8_t bitCombination = 0; for (uint32_t i = 0; i < 8; ++i) { bool isOverSurface = (voxels[i].density > mSurfaceDensity.density); bitCombination |= isOverSurface << i; } if (bitCombination == 0 || bitCombination == 0xFF) { return; } uint8_t cellClassIdx = regularCellClass[bitCombination]; const RegularCellData &cellData = regularCellData[cellClassIdx]; glm::vec3 vertices[8] = {}; for (uint32_t i = 0; i < 8; ++i) { vertices[i] = NORMALIZED_CUBE_VERTICES[i] + glm::vec3(0.5f) + glm::vec3(coord); } if (axis.x == -1) { vertices[0].x += percentTrans; vertices[2].x += percentTrans; vertices[4].x += percentTrans; vertices[6].x += percentTrans; } else if (axis.x == 1) { vertices[1].x -= percentTrans; vertices[3].x -= percentTrans; vertices[5].x -= percentTrans; vertices[7].x -= percentTrans; } else if (axis.z == -1) { vertices[0].z += percentTrans; vertices[1].z += percentTrans; vertices[2].z += percentTrans; vertices[3].z += percentTrans; } else if (axis.z == 1) { vertices[4].z -= percentTrans; vertices[5].z -= percentTrans; vertices[6].z -= percentTrans; vertices[7].z -= percentTrans; } IsoVertex *verts = STACK_ALLOC(IsoVertex, cellData.GetVertexCount()); for (int i = 0; i < cellData.GetVertexCount(); ++i) { uint16_t nibbles = regularVertexData[bitCombination][i]; if (nibbles == 0x0) { // Finished break; } uint8_t v0 = (nibbles >> 4) & 0xF; uint8_t v1 = nibbles & 0xF; float surfaceLevelF = (float)mSurfaceDensity.density; float voxelValue0 = (float)voxels[v0].density; float voxelValue1 = (float)voxels[v1].density; if (voxelValue0 > voxelValue1) { float tmp = voxelValue0; voxelValue0 = voxelValue1; voxelValue1 = tmp; uint8_t tmpV = v0; v0 = v1; v1 = tmpV; } float interpolatedVoxelValues = lerp(voxelValue0, voxelValue1, surfaceLevelF); glm::vec3 vertex = interpolate( vertices[v0], vertices[v1], interpolatedVoxelValues); glm::vec3 normal0 = glm::vec3( voxels[v0].normalX, voxels[v0].normalY, voxels[v0].normalZ) / 1000.0f; glm::vec3 normal1 = glm::vec3( voxels[v1].normalX, voxels[v1].normalY, voxels[v1].normalZ) / 1000.0f; glm::vec3 normal = interpolate( normal0, normal1, interpolatedVoxelValues); verts[i] = {vertex, normal}; } for (int i = 0; i < cellData.GetTriangleCount() * 3; ++i) { int vertexIndex = cellData.vertexIndex[i]; meshVertices[vertexCount++] = verts[vertexIndex]; } } { // Transvoxel mesh creation uint32_t bitCombination = 0; bitCombination |= (transVoxels[0].density > mSurfaceDensity.density) << 0; bitCombination |= (transVoxels[1].density > mSurfaceDensity.density) << 1; bitCombination |= (transVoxels[2].density > mSurfaceDensity.density) << 2; bitCombination |= (transVoxels[3].density > mSurfaceDensity.density) << 7; bitCombination |= (transVoxels[4].density > mSurfaceDensity.density) << 8; bitCombination |= (transVoxels[5].density > mSurfaceDensity.density) << 3; bitCombination |= (transVoxels[6].density > mSurfaceDensity.density) << 6; bitCombination |= (transVoxels[7].density > mSurfaceDensity.density) << 5; bitCombination |= (transVoxels[8].density > mSurfaceDensity.density) << 4; if (bitCombination == 0 || bitCombination == 511) { return; } int detailed0, detailed1, nonDetailed, nonDetailedBit; if (axis.x == -1) { detailed0 = 1, detailed1 = 2, nonDetailed = 0, nonDetailedBit = 0; } else if (axis.x == 1) { detailed0 = 1, detailed1 = 2, nonDetailed = 0, nonDetailedBit = 1; } else if (axis.z == -1) { detailed0 = 0, detailed1 = 1, nonDetailed = 2, nonDetailedBit = 0; } else if (axis.z == 1) { detailed0 = 0, detailed1 = 1, nonDetailed = 2, nonDetailedBit = 1; } glm::vec3 vertices[13] = {}; uint32_t counter = 0; for (int d1 = 0; d1 < 3; ++d1) { for (int d0 = 0; d0 < 3; ++d0) { vertices[counter][detailed0] = (float)d0 * 0.5f; vertices[counter][detailed1] = (float)d1 * 0.5f; vertices[counter][nonDetailed] = (float)nonDetailedBit; vertices[counter] += glm::vec3(coord); ++counter; } } for (int d1 = 0; d1 < 2; ++d1) { for (int d0 = 0; d0 < 2; ++d0) { vertices[counter][detailed0] = (float)d0; vertices[counter][detailed1] = (float)d1; vertices[counter][nonDetailed] = (float)(nonDetailedBit ^ 1); vertices[counter] += glm::vec3(coord); ++counter; } } if (nonDetailedBit) { if (axis[nonDetailed] == 1) { for (int i = 9; i < 13; ++i) { vertices[i][nonDetailed] += (1.0f - percentTrans); } } } else { if (axis[nonDetailed] == -1) { for (int i = 9; i < 13; ++i) { vertices[i][nonDetailed] -= (1.0f - percentTrans); } } } uint8_t cellClassIdx = transitionCellClass[bitCombination]; const TransitionCellData &cellData = transitionCellData[cellClassIdx & 0x7F]; IsoVertex *verts = STACK_ALLOC(IsoVertex, cellData.GetVertexCount()); for (int i = 0; i < cellData.GetVertexCount(); ++i) { uint16_t nibbles = transitionVertexData[bitCombination][i]; if (nibbles == 0x0) { break; } uint8_t v0 = (nibbles >> 4) & 0xF; uint8_t v1 = nibbles & 0xF; float surfaceLevelF = (float)mSurfaceDensity.density; float voxelValue0 = (float)transVoxels[v0].density; float voxelValue1 = (float)transVoxels[v1].density; if (voxelValue0 > voxelValue1) { float tmp = voxelValue0; voxelValue0 = voxelValue1; voxelValue1 = tmp; uint8_t tmpV = v0; v0 = v1; v1 = tmpV; } float interpolatedVoxelValues = lerp(voxelValue0, voxelValue1, surfaceLevelF); glm::vec3 vertex = interpolate( vertices[v0], vertices[v1], interpolatedVoxelValues); glm::vec3 normal0 = glm::vec3( transVoxels[v0].normalX, transVoxels[v0].normalY, transVoxels[v0].normalZ) / 1000.0f; glm::vec3 normal1 = glm::vec3( transVoxels[v1].normalX, transVoxels[v1].normalY, transVoxels[v1].normalZ) / 1000.0f; glm::vec3 normal = interpolate( normal0, normal1, interpolatedVoxelValues); if (glm::dot(normal, normal) != 0.0f) { normal = glm::normalize(normal); } verts[i] = {vertex, normal}; } if (cellClassIdx & 0x80) { for (int i = cellData.GetTriangleCount() * 3 - 1; i >= 0; --i) { int vertexIndex = cellData.vertexIndex[i]; glm::vec3 diff = verts[vertexIndex].position - (glm::vec3)coord; meshVertices[vertexCount++] = verts[vertexIndex]; } } else { for (int i = 0; i < cellData.GetTriangleCount() * 3; ++i) { int vertexIndex = cellData.vertexIndex[i]; glm::vec3 diff = verts[vertexIndex].position - (glm::vec3)coord; meshVertices[vertexCount++] = verts[vertexIndex]; } } } } NumericMap<IsoGroup *> &Isosurface::isoGroups() { return mIsoGroups; } }
30.107556
147
0.602994
llGuy
642f552caf8360f1efc2230731e1409502dc5304
2,383
hh
C++
preprocessor/preprocessor-src/src/preprocessor/cxx_ast.hh
fabianmcg/wavedag
e975792aef4423de6cf43af6bfde44ef89a5db0d
[ "MIT" ]
1
2021-01-10T09:04:38.000Z
2021-01-10T09:04:38.000Z
preprocessor/preprocessor-src/src/preprocessor/cxx_ast.hh
fabianmcg/wavedag
e975792aef4423de6cf43af6bfde44ef89a5db0d
[ "MIT" ]
null
null
null
preprocessor/preprocessor-src/src/preprocessor/cxx_ast.hh
fabianmcg/wavedag
e975792aef4423de6cf43af6bfde44ef89a5db0d
[ "MIT" ]
null
null
null
#ifndef __PREPROCESSOR_CXX_AST_HH__ #define __PREPROCESSOR_CXX_AST_HH__ #include <pragma-parser.hh> #include "../clang/clang-wrapper.hh" #include "../util.hh" #include "util.hh" #include "types.hh" #include "pragma.hh" namespace __preprocessor__ { namespace __cxx__ { enum class variable_list_mode_e { NAMES, NAMES_TYPES }; using variable_list_mode_t=variable_list_mode_e; std::vector<for_statement_t> for_statements(const clang_ast_t& ast,clang_ast_node_t* root=nullptr); std::vector<for_statement_t> for_statements(const std::vector<std::string>& src,const clang_ast_t& ast,clang_ast_node_t* root=nullptr); void remove_unexposed(clang_ast_t &ast,clang_ast_node_t *root=nullptr); variable_t variable_type(const clang_ast_node_t& node); template <variable_list_mode_t mode=variable_list_mode_t::NAMES_TYPES,std::enable_if_t<mode==variable_list_mode_t::NAMES_TYPES,int> = 0> std::set<std::pair<std::string,variable_t>> variable_list(const clang_ast_t& ast,clang_ast_node_t* root=nullptr) { std::set<std::pair<std::string,variable_t>> variables; auto visitor=[&variables](const clang_ast_node_t& node,size_t depth) { variable_t type=variable_type(node); if(type!=NOT_VAR) variables.insert(std::make_pair(std::get<std::string>(node.value),type)); }; ast.traverse(visitor,root); return variables; } template <variable_list_mode_t mode=variable_list_mode_t::NAMES_TYPES,std::enable_if_t<mode==variable_list_mode_t::NAMES,int> = 0> std::set<std::string> variable_list(const clang_ast_t& ast,clang_ast_node_t* root=nullptr) { std::set<std::string> variables; auto visitor=[&variables](const clang_ast_node_t& node,size_t depth) { variable_t type=variable_type(node); if(type!=NOT_VAR) variables.insert(std::get<std::string>(node.value)); }; ast.traverse(visitor,root); return variables; } std::pair<std::map<clang_ast_node_t*,size_t>,std::vector<clang_ast_node_t*>> pragma_code_blocks(const std::vector<pragma_ast_node_t*>& pragma_translation,const clang_ast_t& ast,clang_ast_node_t* root=nullptr); std::vector<std::string> pragma_identifier_list(const clang_ast_t& ast,clang_ast_node_t* root=nullptr); std::string remove_tasks(const std::vector<std::string>& src,const std::vector<pragma_ast_node_t*>& pragma_translation,const std::vector<clang_ast_node_t*>& cxx_translation,const clang_ast_t& ast,clang_ast_node_t* root=nullptr,bool leave=false); } } #endif
45.826923
245
0.793538
fabianmcg
642f9f56efd39702aaeb2e9844c3c9b8cbafc274
839
cc
C++
src/ops/softmax.cc
Parkchanjun/CTranslate2
62e3af774e0ba23e052e242c263dcbc00cd6c0c6
[ "MIT" ]
null
null
null
src/ops/softmax.cc
Parkchanjun/CTranslate2
62e3af774e0ba23e052e242c263dcbc00cd6c0c6
[ "MIT" ]
null
null
null
src/ops/softmax.cc
Parkchanjun/CTranslate2
62e3af774e0ba23e052e242c263dcbc00cd6c0c6
[ "MIT" ]
null
null
null
#include "ctranslate2/ops/softmax.h" #include "../device_dispatch.h" namespace ctranslate2 { namespace ops { LogSoftMax::LogSoftMax() : SoftMax(/*log=*/true) { } SoftMax::SoftMax(bool log) : _log(log) { } void SoftMax::operator()(const StorageView& x, StorageView& y) const { operator()(x, nullptr, y); } void SoftMax::operator()(const StorageView& x, const StorageView& lengths, StorageView& y) const { operator()(x, &lengths, y); } void SoftMax::operator()(const StorageView& x, const StorageView* lengths, StorageView& y) const { PROFILE_FUN; if (lengths && lengths->dim(0) == 1) // Disable masking when batch size is 1. lengths = nullptr; y.resize_as(x); DEVICE_DISPATCH(x.device(), (compute<D, float>(x, lengths, y))); } } }
24.676471
102
0.615018
Parkchanjun
6431948ead17245979c8032bcb8a3317bc86acfc
13,539
cpp
C++
lib/CubeSolver/TableManager.cpp
C-minus-minus/Cubebert
bef38d5ba9baa884b32710c058ca4d18d6734ecf
[ "MIT" ]
null
null
null
lib/CubeSolver/TableManager.cpp
C-minus-minus/Cubebert
bef38d5ba9baa884b32710c058ca4d18d6734ecf
[ "MIT" ]
null
null
null
lib/CubeSolver/TableManager.cpp
C-minus-minus/Cubebert
bef38d5ba9baa884b32710c058ca4d18d6734ecf
[ "MIT" ]
null
null
null
#include "TableManager.h" TableManager* TableManager::instance = NULL; TableManager::TableManager() { this->generatePhase1MoveTables(); this->generatePhase1PruningTables(); this->generatePhase2MoveTables(); this->generatePhase2PruningTables(); } TableManager* TableManager::getInstance() { if (TableManager::instance == NULL) { TableManager::instance = new TableManager(); } return TableManager::instance; } void TableManager::generatePhase1EdgeMoveTable(StickerCube* cube, int coord, int depth) { if (this->phase1EdgeMoveTable[coord][0] == -1) { for (int move = 0; move < CubeConstants::PHASE_1_MOVE_COUNT; move++) { cube->applyMove(CubeConstants::PHASE_1_MOVES[move]); int newCoord = cube->getPhase1EdgeCoordinate(); phase1EdgeMoveTable[coord][move] = newCoord; generatePhase1EdgeMoveTable(cube, newCoord, depth + 1); cube->applyMove(CubeConstants::PHASE_1_ANTIMOVES[move]); } } } void TableManager::generatePhase1CornerMoveTable(StickerCube* cube, int coord, int depth) { if (this->phase1CornerMoveTable[coord][0] == -1) { for (int move = 0; move < CubeConstants::PHASE_1_MOVE_COUNT; move++) { cube->applyMove(CubeConstants::PHASE_1_MOVES[move]); int newCoord = cube->getPhase1CornerCoordinate(); this->phase1CornerMoveTable[coord][move] = newCoord; this->generatePhase1CornerMoveTable(cube, newCoord, depth + 1); cube->applyMove(CubeConstants::PHASE_1_ANTIMOVES[move]); } } } void TableManager::generatePhase1UdsliceMoveTable(StickerCube* cube, int coord, int depth) { if (this->phase1UdsliceMoveTable[coord][0] == -1) { for (int move = 0; move < CubeConstants::PHASE_1_MOVE_COUNT; move++) { cube->applyMove(CubeConstants::PHASE_1_MOVES[move]); int newCoord = cube->getPhase1UdsliceCoordinate(); this->phase1UdsliceMoveTable[coord][move] = newCoord; this->generatePhase1UdsliceMoveTable(cube, newCoord, depth + 1); cube->applyMove(CubeConstants::PHASE_1_ANTIMOVES[move]); } } } void TableManager::generatePhase2EdgeMoveTable() { for (int coord = 0; coord < CubeConstants::PHASE_2_MAX_EDGE_COORDINATE; coord++) { StickerCube* stickerCube = StickerCube::fromEdgePermutation(coord); for (int move = 0; move < CubeConstants::PHASE_2_MOVE_COUNT; move++) { stickerCube->applyMove(CubeConstants::PHASE_2_MOVES[move]); this->phase2EdgeMoveTable[coord][move] = stickerCube->getPhase2EdgeCoordinate(); stickerCube->applyMove(CubeConstants::PHASE_2_ANTIMOVES[move]); } delete stickerCube; } } void TableManager::generatePhase2CornerMoveTable() { for (int coord = 0; coord < CubeConstants::PHASE_2_MAX_CORNER_COORDINATE; coord++) { StickerCube* stickerCube = StickerCube::fromCornerPermutation(coord); for (int move = 0; move < CubeConstants::PHASE_2_MOVE_COUNT; move++) { stickerCube->applyMove(CubeConstants::PHASE_2_MOVES[move]); this->phase2CornerMoveTable[coord][move] = stickerCube->getPhase2CornerCoordinate(); stickerCube->applyMove(CubeConstants::PHASE_2_ANTIMOVES[move]); } } } void TableManager::generatePhase2UdsliceMoveTable() { for (int coord = 0; coord < CubeConstants::PHASE_2_MAX_UDSLICE_COORDINATE; coord++) { StickerCube* stickerCube = StickerCube::fromUDSlice(coord); for (int move = 0; move < CubeConstants::PHASE_2_MOVE_COUNT; move++) { stickerCube->applyMove(CubeConstants::PHASE_2_MOVES[move]); this->phase2UdsliceMoveTable[coord][move] = stickerCube->getPhase2UdsliceCoordinate(); stickerCube->applyMove(CubeConstants::PHASE_2_ANTIMOVES[move]); } } } void TableManager::generatePhase1MoveTables() { // Allocate memory for tables this->phase1EdgeMoveTable = new int*[CubeConstants::PHASE_1_MAX_EDGE_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_1_MAX_EDGE_COORDINATE; i++) { this->phase1EdgeMoveTable[i] = new int[CubeConstants::PHASE_1_MOVE_COUNT]; for (int a = 0; a < CubeConstants::PHASE_1_MOVE_COUNT; a++) { this->phase1EdgeMoveTable[i][a] = -1; } } this->phase1CornerMoveTable = new int*[CubeConstants::PHASE_1_MAX_CORNER_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_1_MAX_CORNER_COORDINATE; i++) { this->phase1CornerMoveTable[i] = new int[CubeConstants::PHASE_1_MOVE_COUNT]; for (int a = 0; a < CubeConstants::PHASE_1_MOVE_COUNT; a++) { this->phase1CornerMoveTable[i][a] = -1; } } this->phase1UdsliceMoveTable = new int*[CubeConstants::PHASE_1_MAX_UDSLICE_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_1_MAX_UDSLICE_COORDINATE; i++) { this->phase1UdsliceMoveTable[i] = new int[CubeConstants::PHASE_1_MOVE_COUNT]; for (int a = 0; a < CubeConstants::PHASE_1_MOVE_COUNT; a++) { this->phase1UdsliceMoveTable[i][a] = -1; } } //// populate tables with -1 to start //int** tables[] = {this->phase1EdgeMoveTable, this->phase1CornerMoveTable, this->phase1UdsliceMoveTable}; //const int maxCoordinateLength = 3; //const int maxCoordinate[] = { // CubeConstants::PHASE_1_MAX_EDGE_COORDINATE, // CubeConstants::PHASE_1_MAX_CORNER_COORDINATE, // CubeConstants::PHASE_1_MAX_UDSLICE_COORDINATE //}; //for (int move = 0; move < CubeConstants::PHASE_1_MOVE_COUNT; move++) { // for (int table = 0; table < maxCoordinateLength; table++) { // for (int coord = 0; coord < maxCoordinate[table]; coord++) { // tables[table][coord][move] = -1; // } // } //} // Generate move tables using DFS StickerCube* solvedCube = new StickerCube(); this->generatePhase1UdsliceMoveTable(solvedCube, 0, 0); this->generatePhase1EdgeMoveTable(solvedCube, 0, 0); this->generatePhase1CornerMoveTable(solvedCube, 0, 0); } void TableManager::generatePhase2MoveTables() { this->phase2EdgeMoveTable = new int*[CubeConstants::PHASE_2_MAX_EDGE_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_2_MAX_EDGE_COORDINATE; i++) { this->phase2EdgeMoveTable[i] = new int[CubeConstants::PHASE_2_MOVE_COUNT]; for (int a = 0; a < CubeConstants::PHASE_2_MOVE_COUNT; a++) { this->phase2EdgeMoveTable[i][a] = -1; } } this->phase2CornerMoveTable = new int*[CubeConstants::PHASE_2_MAX_CORNER_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_2_MAX_CORNER_COORDINATE; i++) { this->phase2CornerMoveTable[i] = new int[CubeConstants::PHASE_2_MOVE_COUNT]; for (int a = 0; a < CubeConstants::PHASE_2_MOVE_COUNT; a++) { this->phase2CornerMoveTable[i][a] = -1; } } this->phase2UdsliceMoveTable = new int*[CubeConstants::PHASE_2_MAX_UDSLICE_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_2_MAX_UDSLICE_COORDINATE; i++) { this->phase2UdsliceMoveTable[i] = new int[CubeConstants::PHASE_2_MOVE_COUNT] ; for (int a = 0; a < CubeConstants::PHASE_2_MOVE_COUNT; a++) { this->phase2UdsliceMoveTable[i][a] = -1; } } /* for (int move = 0; move < CubeConstants::PHASE_2_MOVE_COUNT; move++) { int** tables[] = {this->phase2EdgeMoveTable, this->phase2CornerMoveTable, this->phase2UdsliceMoveTable}; const int maxCoordinateSize = 3; int maxCoordinate[] = { CubeConstants::PHASE_2_MAX_EDGE_COORDINATE, CubeConstants::PHASE_2_MAX_CORNER_COORDINATE, CubeConstants::PHASE_2_MAX_UDSLICE_COORDINATE }; for (int table = 0; table < maxCoordinateSize; table++) { for (int coord = 0; coord < maxCoordinate[table]; coord++) { tables[table][coord][move] = -1; } } }*/ this->generatePhase2EdgeMoveTable(); this->generatePhase2CornerMoveTable(); this->generatePhase2UdsliceMoveTable(); } void TableManager::generatePhase1EdgePruningTable() { this->phase1EdgePruningTable = new int[CubeConstants::PHASE_1_MAX_EDGE_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_1_MAX_EDGE_COORDINATE; i++) { this->phase1EdgePruningTable[i] = -1; } std::queue<SearchNode*> que; que.emplace(new SearchNode(0, 0)); while (!que.empty()) { SearchNode* curr = que.front(); que.pop(); if (this->phase1EdgePruningTable[curr->value] == -1) { this->phase1EdgePruningTable[curr->value] = curr->depth; for (int move = 0; move < CubeConstants::PHASE_1_MOVE_COUNT; move++) { int coord = this->phase1EdgeMoveTable[curr->value][move]; que.emplace(new SearchNode(curr->depth + 1, coord)); } } } } void TableManager::generatePhase1CornerPruningTable() { this->phase1CornerPruningTable = new int[CubeConstants::PHASE_1_MAX_CORNER_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_1_MAX_CORNER_COORDINATE; i++) { this->phase1CornerPruningTable[i] = -1; } std::queue<SearchNode*> que; que.emplace(new SearchNode(0, 0)); while (!que.empty()) { SearchNode* curr = que.front(); que.pop(); if (this->phase1CornerPruningTable[curr->value] == -1) { this->phase1CornerPruningTable[curr->value] = curr->depth; for (int move = 0; move < CubeConstants::PHASE_1_MOVE_COUNT; move++) { int coord = this->phase1CornerMoveTable[curr->value][move]; que.emplace(new SearchNode(curr->depth + 1, coord)); } } } } void TableManager::generatePhase1UDSlicePruningTable() { this->phase1UdslicePruningTable = new int[CubeConstants::PHASE_1_MAX_UDSLICE_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_1_MAX_UDSLICE_COORDINATE; i++) { this->phase1UdslicePruningTable[i] = -1; } std::queue<SearchNode*> que; que.emplace(new SearchNode(0, 0)); while (!que.empty()) { SearchNode* curr = que.front(); que.pop(); if (this->phase1UdslicePruningTable[curr->value] == -1) { this->phase1UdslicePruningTable[curr->value] = curr->depth; for (int move = 0; move < CubeConstants::PHASE_1_MOVE_COUNT; move++) { int coord = this->phase1UdsliceMoveTable[curr->value][move]; que.emplace(new SearchNode(curr->depth + 1, coord)); } } } } void TableManager::generatePhase2EdgePruningTable() { this->phase2EdgePruningTable = new int[CubeConstants::PHASE_2_MAX_EDGE_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_2_MAX_EDGE_COORDINATE; i++) { this->phase2EdgePruningTable[i] = -1; } std::queue<SearchNode*> que; que.emplace(new SearchNode(0, 0)); while (!que.empty()) { SearchNode* curr = que.front(); que.pop(); if (this->phase2EdgePruningTable[curr->value] == -1) { this->phase2EdgePruningTable[curr->value] = curr->depth; for (int move = 0; move < CubeConstants::PHASE_2_MOVE_COUNT; move++) { int coord = this->phase2EdgeMoveTable[curr->value][move]; que.emplace(new SearchNode(curr->depth + 1, coord)); } } } } void TableManager::generatePhase2CornerPruningTable() { this->phase2CornerPruningTable = new int[CubeConstants::PHASE_2_MAX_CORNER_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_2_MAX_CORNER_COORDINATE; i++) { this->phase2CornerPruningTable[i] = -1; } std::queue<SearchNode*> que; que.emplace(new SearchNode(0, 0)); while (!que.empty()) { SearchNode* curr = que.front(); que.pop(); if (this->phase2CornerPruningTable[curr->value] == -1) { this->phase2CornerPruningTable[curr->value] = curr->depth; for (int move = 0; move < CubeConstants::PHASE_2_MOVE_COUNT; move++) { int coord = this->phase2CornerMoveTable[curr->value][move]; que.emplace(new SearchNode(curr->depth + 1, coord)); } } } } void TableManager::generatePhase2UDSlicePruningTable() { this->phase2UdslicePruningTable = new int[CubeConstants::PHASE_2_MAX_UDSLICE_COORDINATE]; for (int i = 0; i < CubeConstants::PHASE_2_MAX_UDSLICE_COORDINATE; i++) { this->phase2UdslicePruningTable[i] = -1; } std::queue<SearchNode*> que; que.emplace(new SearchNode(0, 0)); while (!que.empty()) { SearchNode* curr = que.front(); que.pop(); if (this->phase2UdslicePruningTable[curr->value] == -1) { this->phase2UdslicePruningTable[curr->value] = curr->depth; for (int move = 0; move < CubeConstants::PHASE_2_MOVE_COUNT; move++) { int coord = this->phase2UdsliceMoveTable[curr->value][move]; que.emplace(new SearchNode(curr->depth + 1, coord)); } } } } void TableManager::generatePhase1PruningTables() { this->generatePhase1EdgePruningTable(); this->generatePhase1CornerPruningTable(); this->generatePhase1UDSlicePruningTable(); } void TableManager::generatePhase2PruningTables() { this->generatePhase2EdgePruningTable(); this->generatePhase2CornerPruningTable(); this->generatePhase2UDSlicePruningTable(); }
41.658462
112
0.646872
C-minus-minus
6432871bdc57b9574fd2a55cd84adf8e68b56258
317
cpp
C++
LeetCode/Problems/Algorithms/#96_UniqueBinarySearchTrees_sol4_catalan_numbers_O(N)_time_O(1)_extra_space.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#96_UniqueBinarySearchTrees_sol4_catalan_numbers_O(N)_time_O(1)_extra_space.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#96_UniqueBinarySearchTrees_sol4_catalan_numbers_O(N)_time_O(1)_extra_space.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { private: long long comb(int n, int k){ long long res = 1; for(int i = 1; i <= k; ++i){ res *= (n - k + i); res /= i; } return res; } public: int numTrees(int n) { return comb(2 * n, n) / (n + 1); } };
19.8125
41
0.37224
Tudor67
643327a34be9fdcd3335fe2b06e0f66cb2b32bb2
1,027
cpp
C++
Commom/BaseFrame.cpp
chungmin99/Medial-IPC
e5c7a2ed81f28bab6ad96eab61eb61213cb3089d
[ "MIT" ]
7
2021-10-30T16:48:31.000Z
2022-02-14T04:47:56.000Z
Commom/BaseFrame.cpp
chungmin99/Medial-IPC
e5c7a2ed81f28bab6ad96eab61eb61213cb3089d
[ "MIT" ]
null
null
null
Commom/BaseFrame.cpp
chungmin99/Medial-IPC
e5c7a2ed81f28bab6ad96eab61eb61213cb3089d
[ "MIT" ]
4
2021-08-31T00:24:49.000Z
2022-02-06T09:10:48.000Z
#include "BaseFrame.h" void BaseFrameConstraint::freeFrame() { select_frame.clear(); } void BaseFrameConstraint::setFrame(BaseFrame * f) { select_frame.append(f); } void BaseFrameConstraint::constrainTranslation(qglviewer::Vec& translation, qglviewer::Frame* const frame) { for (QList<localFrame*>::iterator it = select_frame.begin(), end = select_frame.end(); it != end; ++it) { (*it)->translate(translation); } } void BaseFrameConstraint::constrainRotation(qglviewer::Quaternion& rotation, qglviewer::Frame* const frame) { const qglviewer::Vec worldAxis = frame->inverseTransformOf(rotation.axis()); const qglviewer::Vec pos = frame->position(); const float angle = rotation.angle(); for (QList<localFrame*>::iterator it = select_frame.begin(), end = select_frame.end(); it != end; ++it) { qglviewer::Quaternion qVertex((*it)->transformOf(worldAxis), angle); (*it)->rotate(qVertex); qglviewer::Quaternion qWorld(worldAxis, angle); (*it)->setPosition(pos + qWorld.rotate((*it)->position() - pos)); } }
31.121212
107
0.719572
chungmin99
64333d1253de18a6251fbf26d6f9ce4649e87df2
9,548
cc
C++
src/xpath.cc
CodeCat-maker/cxml
e5912f997a050ffd26e40faaea14558456f6e119
[ "MIT" ]
115
2022-02-16T14:27:04.000Z
2022-03-29T23:05:24.000Z
src/xpath.cc
CodeCat-maker/cxml
e5912f997a050ffd26e40faaea14558456f6e119
[ "MIT" ]
null
null
null
src/xpath.cc
CodeCat-maker/cxml
e5912f997a050ffd26e40faaea14558456f6e119
[ "MIT" ]
1
2022-03-12T01:36:51.000Z
2022-03-12T01:36:51.000Z
#include "xpath.hpp" using std::cout; using std::endl; using std::__1::pair; using std::__1::queue; typedef queue<pair<string, string> > qpss; qpss queue_option; //储存操作类型和名称 int XPATH_PARSE_STATUE = XPATH_PARSE_SUCCESS; //child 子 //genera 后 const string options[] = { "get_parent_node", // /.. 选择父元素 ✅ "get_this_node", // /. 选择当前元素 ✅ "get_all_nodes", // /* 匹配任意元素 "get_node_from_genera_by_name", // //name 选择当前元素后代元素中的name元素 ✅ "get_node_from_child_by_name", // /name 选择当前元素子代元素中的name元素 ✅ "get_node_by_array_and_name", // /name[n] 选择当前元素下第n个name元素 ✅ "get_node_by_attr_and_name", // /name[@attr] 属性筛选,选择有attr属性的元素 ✅ "get_node_by_attrValue_and_name", // /name[@attr=value] 属性筛选,选择attr属性的值为value的name元素(属性值不加分号) ✅ "get_text_from_this", // /text() 返回当前元素中的文本 ✅ "get_texts_from_genera", // //text() 返回当前元素以及它所有后代元素中的文本 ✅ "get_attr_from_this", // /@attr 返回当前元素attr属性的值 ✅ "get_all_attr" // @* 匹配任意属性}; }; // string转int constexpr unsigned int str2int(const char *str, int h = 0) { return !str[h] ? 5381 : (str2int(str, h + 1) * 33) ^ str[h]; } pair<string, string> parse_option(const string op) { pair<string, string> ret; //取后代 if (op.find("//") < maxLength) { if (op.find("text()") < maxLength) { ret = {options[9], op.substr(2)}; } else { ret = {options[3], op.substr(2)}; } } else { //取子代 if (op.find("..") < maxLength) { ret = {options[0], ""}; } else if (op.find(".") < maxLength) { ret = {options[1], ""}; } else if (op.find("[") < maxLength) { if (op.find("@") < maxLength) { if (op.find("=") < maxLength) { ret = {options[7], op.substr(1)}; } else { ret = {options[6], op.substr(1)}; } } else { ret = {options[5], op.substr(1)}; } } else if (op.find("@") < maxLength) { ret = {options[10], op.substr(1)}; } else if (op.find("text()") < maxLength) { ret = {options[8], op.substr(1)}; } else { ret = {options[4], op.substr(1)}; } } //cout << ret.first << " " << ret.second << endl; return ret; } //返回父节点 CXMLNode *xpath_get_parent_node(CXMLNode *root) { return root->parent; } //返回当前节点 CXMLNode *xpath_get_this_node(CXMLNode *root) { return root; } //获取当前节点文本 string xpath_get_text_from_this(CXMLNode *root) { return root->text->content; } //获取当前节点后节点的所有文本 string xpath_get_texts_from_genera(CXMLNode *root) { pair<CXMLNode *, bool> d; queue<CXMLNode *> q; q.push(root); string ret; while (!q.empty()) { auto p = q.front(); q.pop(); for (auto m : p->children) { auto t = m->text; ret += t->content + " "; q.push(m); } } return ret; } //根据属性 值 名称 来选择节点 CXMLNode *xpath_get_node_by_attrValue_and_name(const string name, CXMLNode *root) { string attr_name = name.substr(name.find("@") + 1, name.find("=") - name.find("@") - 1); string value_name = name.substr(name.find("=") + 1, name.find("]") - name.find("=") - 1); string node_name = name.substr(0, name.find("[")); //cout << attr_name << " " << node_name << " " << value_name << endl; for (auto child : root->children) { CXMLNode_attr *att = child->attr; if (child->name == node_name) { for (auto item : att->attributes) { if (item.first == attr_name && item.second == value_name) { return child; } } } } return nullptr; } //根据属性 in过程 选择节点 CXMLNode *xpath_get_node_by_attr_and_name(const string name, CXMLNode *root) { string attr_name = name.substr(name.find("@") + 1, name.find("]") - name.find("@") - 1); string node_name = name.substr(0, name.find("[")); for (auto child : root->children) { CXMLNode_attr *att = child->attr; if (child->name == node_name) { for (auto item : att->attributes) { if (item.first == attr_name) return child; } } } return nullptr; } // 通过数组选择与名字相同的节点 CXMLNode *xpath_get_node_by_array_and_name(const string name, CXMLNode *root) { int j = *(name.substr(name.find("[") + 1, name.find("]") - name.find("[")).c_str()) - '0'; string tmp_name = name.substr(0, name.find("[")); cout << tmp_name << " " << j << " " << endl; int i = 0; for (auto child : root->children) { //cout << child->name << endl; if (child->name == tmp_name) { i++; if (i == j) return child; } } return nullptr; } //选择当前元素子代元素中的name元素 CXMLNode *xpath_get_node_from_child_by_name(const string name, CXMLNode *root) { if (root->children.size() == 0) return nullptr; for (auto child : root->children) { if (child->name == name) return child; } return nullptr; } map<CXMLNode *, bool> used; //选择当前元素后代元素中的name元素 CXMLNode *xpath_get_node_from_genera_by_name(const string name, CXMLNode *root) { if (root->name == name) { return root; } for (auto m : root->children) { if (used.count(m) == 0) { used.insert({m, true}); CXMLNode *result = xpath_get_node_from_genera_by_name(name, m); if (result != nullptr) return result; used.erase(m); } } return nullptr; } string xpath_get_attr_from_this(const string name, CXMLNode *root) { string attr_name = name.substr(name.find("@") + 1); string ret; CXMLNode_attr *a = root->attr; for (auto m : a->attributes) { if (m.first == attr_name) return m.second; } return ret; } //将操作入队 双指针算法入队 bool get_xpath_option(const string exp) { int l(0), r(0); int len = 0; while (len <= exp.length()) { if ((exp[len] == '/')) { if (exp[len + 1] == '/') r = l + 2; else r = l + 1; while (r <= exp.length()) { if (exp[r] == '/') break; r++; } string tmp_option = exp.substr(l, r - l); //cout << tmp_option << " "; queue_option.push(parse_option(tmp_option)); } len = r; l = r; } //string name = exp.substr(0, len); return true; } //处理xpath操作 bool do_xpath_option(CXMLNode *root, CXMLNode_result *result) { CXMLNode *node = root; string ret_text; while (queue_option.empty() == false) { pair<string, string> op = queue_option.front(); queue_option.pop(); string option = op.first; string name = op.second; //cout << option << " " << name << endl; switch (str2int(option.c_str())) { case str2int("get_node_from_genera_by_name"): node = xpath_get_node_from_genera_by_name(name, node); result->element = node; break; case str2int("get_node_from_child_by_name"): node = xpath_get_node_from_child_by_name(name, node); result->element = node; break; case str2int("get_node_by_array_and_name"): node = xpath_get_node_by_array_and_name(name, node); result->element = node; break; case str2int("get_node_by_attr_and_name"): node = xpath_get_node_by_attr_and_name(name, node); result->element = node; break; case str2int("get_node_by_attrValue_and_name"): node = xpath_get_node_by_attrValue_and_name(name, node); result->element = node; break; case str2int("get_text_from_this"): ret_text = xpath_get_text_from_this(node); result->text = ret_text; return true; case str2int("get_texts_from_genera"): ret_text = xpath_get_texts_from_genera(node); result->text = ret_text; return true; case str2int("get_this_node"): node = xpath_get_this_node(node); result->element = node; break; case str2int("get_parent_node"): node = xpath_get_parent_node(node); result->element = node; break; case str2int("get_attr_from_this"): ret_text = xpath_get_attr_from_this(name, node); result->text = ret_text; return true; default: return false; } } return true; } //返回xpath解析内容 const CXMLNode_result *xpath(const string exp, CXMLNode *root) { const char *ptr = exp.c_str(); CXMLNode_result *ret = new CXMLNode_result(); try { get_xpath_option(exp); do_xpath_option(root, ret); } catch (const std::exception &e) { XPATH_PARSE_STATUE = XPATH_SYNTAX_ERROR; return nullptr; } return ret; }
27.436782
99
0.519271
CodeCat-maker
643b7784377b8f0ae60b4559ec236685c8aa8cb7
4,700
cc
C++
src/compiler/cpp_cb_plugin.cc
jinq0123/grpc_cb
1b3058528d66dd6777a3248550a3d87f6b9e1b7f
[ "Apache-2.0" ]
43
2016-11-02T15:19:00.000Z
2021-08-19T08:46:24.000Z
src/compiler/cpp_cb_plugin.cc
jinq0123/grpc_cb
1b3058528d66dd6777a3248550a3d87f6b9e1b7f
[ "Apache-2.0" ]
2
2018-02-09T09:06:37.000Z
2018-08-18T01:26:13.000Z
src/compiler/cpp_cb_plugin.cc
jinq0123/grpc_cb
1b3058528d66dd6777a3248550a3d87f6b9e1b7f
[ "Apache-2.0" ]
19
2016-12-04T08:49:27.000Z
2022-03-29T07:30:59.000Z
/* * * Copyright 2015, Google Inc. * 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 Google Inc. 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. * */ // Generates cpp_cb gRPC service interface out of Protobuf IDL. // #include <memory> #include "config.h" #include "cpp_generator_helpers.h" #include "cpp_cb_generator.h" class CppcbGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { public: CppcbGrpcGenerator() {} virtual ~CppcbGrpcGenerator() {} virtual bool Generate(const grpc::protobuf::FileDescriptor *file, const grpc::string &parameter, grpc::protobuf::compiler::GeneratorContext *context, grpc::string *error) const { if (file->options().cc_generic_services()) { *error = "cpp grpc proto compiler plugin does not work with generic " "services. To generate cpp grpc APIs, please set \"" "cc_generic_service = false\"."; return false; } grpc_cpp_cb_generator::Parameters generator_parameters; if (!parameter.empty()) { std::vector<grpc::string> parameters_list = grpc_generator::tokenize(parameter, ","); for (auto parameter_string = parameters_list.begin(); parameter_string != parameters_list.end(); parameter_string++) { std::vector<grpc::string> param = grpc_generator::tokenize(*parameter_string, "="); if (param[0] == "services_namespace") { generator_parameters.services_namespace = param[1]; } else { *error = grpc::string("Unknown parameter: ") + *parameter_string; return false; } } } grpc::string file_name = grpc_generator::StripProto(file->name()); grpc::string header_code = grpc_cpp_cb_generator::GetHeaderPrologue(file, generator_parameters) + grpc_cpp_cb_generator::GetHeaderIncludes(file, generator_parameters) + grpc_cpp_cb_generator::GetHeaderServices(file, generator_parameters) + grpc_cpp_cb_generator::GetHeaderEpilogue(file, generator_parameters); std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> header_output( context->Open(file_name + ".grpc_cb.pb.h")); grpc::protobuf::io::CodedOutputStream header_coded_out( header_output.get()); header_coded_out.WriteRaw(header_code.data(), header_code.size()); grpc::string source_code = grpc_cpp_cb_generator::GetSourcePrologue(file, generator_parameters) + grpc_cpp_cb_generator::GetSourceIncludes(file, generator_parameters) + grpc_cpp_cb_generator::GetSourceDescriptors(file, generator_parameters) + grpc_cpp_cb_generator::GetSourceServices(file, generator_parameters) + grpc_cpp_cb_generator::GetSourceEpilogue(file, generator_parameters); std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> source_output( context->Open(file_name + ".grpc_cb.pb.cc")); grpc::protobuf::io::CodedOutputStream source_coded_out( source_output.get()); source_coded_out.WriteRaw(source_code.data(), source_code.size()); return true; } }; int main(int argc, char *argv[]) { CppcbGrpcGenerator generator; return grpc::protobuf::compiler::PluginMain(argc, argv, &generator); }
41.59292
81
0.709787
jinq0123
6443612b8ba3bf6d37f5479b2f9fb701af73de00
12,834
inl
C++
Library/Sources/Stroika/Foundation/Containers/Concrete/Mapping_LinkedList.inl
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
28
2015-09-22T21:43:32.000Z
2022-02-28T01:35:01.000Z
Library/Sources/Stroika/Foundation/Containers/Concrete/Mapping_LinkedList.inl
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
98
2015-01-22T03:21:27.000Z
2022-03-02T01:47:00.000Z
Library/Sources/Stroika/Foundation/Containers/Concrete/Mapping_LinkedList.inl
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
4
2019-02-21T16:45:25.000Z
2022-02-18T13:40:04.000Z
/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #ifndef _Stroika_Foundation_Containers_Concrete_Mapping_LinkedList_inl_ #define _Stroika_Foundation_Containers_Concrete_Mapping_LinkedList_inl_ /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../../Memory/BlockAllocated.h" #include "../Private/IteratorImplHelper.h" #include "../Private/PatchingDataStructures/LinkedList.h" namespace Stroika::Foundation::Containers::Concrete { using Traversal::IteratorOwnerID; /* ******************************************************************************** ******** Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::IImplRepBase_ ******** ******************************************************************************** */ template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> class Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::IImplRepBase_ : public Mapping<KEY_TYPE, MAPPED_VALUE_TYPE>::_IRep { private: using inherited = typename Mapping<KEY_TYPE, MAPPED_VALUE_TYPE>::_IRep; #if qCompilerAndStdLib_TemplateTypenameReferenceToBaseOfBaseClassMemberNotFound_Buggy protected: using _APPLY_ARGTYPE = typename inherited::_APPLY_ARGTYPE; using _APPLYUNTIL_ARGTYPE = typename inherited::_APPLYUNTIL_ARGTYPE; #endif }; /* ******************************************************************************** *********** Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Rep_*************** ******************************************************************************** */ template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> template <typename KEY_EQUALS_COMPARER> class Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Rep_ : public IImplRepBase_, public Memory::UseBlockAllocationIfAppropriate<Rep_<KEY_EQUALS_COMPARER>> { private: using inherited = IImplRepBase_; public: using _IterableRepSharedPtr = typename Iterable<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::_IterableRepSharedPtr; using _MappingRepSharedPtr = typename inherited::_MappingRepSharedPtr; using _APPLY_ARGTYPE = typename inherited::_APPLY_ARGTYPE; using _APPLYUNTIL_ARGTYPE = typename inherited::_APPLYUNTIL_ARGTYPE; using KeyEqualsCompareFunctionType = typename Mapping<KEY_TYPE, MAPPED_VALUE_TYPE>::KeyEqualsCompareFunctionType; public: Rep_ (const KEY_EQUALS_COMPARER& keyEqualsComparer) : fKeyEqualsComparer_{keyEqualsComparer} { } Rep_ (const Rep_& from) = delete; Rep_ (Rep_* from, IteratorOwnerID forIterableEnvelope) : inherited () , fKeyEqualsComparer_{from->fKeyEqualsComparer_} , fData_{&from->fData_, forIterableEnvelope} { RequireNotNull (from); } public: nonvirtual Rep_& operator= (const Rep_&) = delete; private: KEY_EQUALS_COMPARER fKeyEqualsComparer_; // Iterable<T>::_IRep overrides public: virtual _IterableRepSharedPtr Clone (IteratorOwnerID forIterableEnvelope) const override { // const cast because though cloning LOGICALLY makes no changes in reality we have to patch iterator lists return Iterable<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSmartPtr<Rep_> (const_cast<Rep_*> (this), forIterableEnvelope); } virtual Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>> MakeIterator (IteratorOwnerID suggestedOwner) const override { Rep_* NON_CONST_THIS = const_cast<Rep_*> (this); // logically const, but non-const cast cuz re-using iterator API return Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>> (Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSmartPtr<IteratorRep_> (suggestedOwner, &NON_CONST_THIS->fData_)); } virtual size_t GetLength () const override { return fData_.GetLength (); } virtual bool IsEmpty () const override { return fData_.IsEmpty (); } virtual void Apply (_APPLY_ARGTYPE doToElement) const override { // empirically faster (vs2k13) to lock once and apply (even calling stdfunc) than to // use iterator (which currently implies lots of locks) with this->_Apply () fData_.Apply (doToElement); } virtual Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>> FindFirstThat (_APPLYUNTIL_ARGTYPE doToElement, IteratorOwnerID suggestedOwner) const override { shared_lock<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; using RESULT_TYPE = Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>; using SHARED_REP_TYPE = Traversal::IteratorBase::PtrImplementationTemplate<IteratorRep_>; auto iLink = fData_.FindFirstThat (doToElement); if (iLink == nullptr) { return RESULT_TYPE::GetEmptyIterator (); } Rep_* NON_CONST_THIS = const_cast<Rep_*> (this); // logically const, but non-const cast cuz re-using iterator API SHARED_REP_TYPE resultRep = Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSmartPtr<IteratorRep_> (suggestedOwner, &NON_CONST_THIS->fData_); resultRep->fIterator.SetCurrentLink (iLink); // because Iterator<T> locks rep (non recursive mutex) - this CTOR needs to happen outside CONTAINER_LOCK_HELPER_START() return RESULT_TYPE (move (resultRep)); } // Mapping<KEY_TYPE, MAPPED_VALUE_TYPE>::_IRep overrides public: virtual KeyEqualsCompareFunctionType GetKeyEqualsComparer () const override { return KeyEqualsCompareFunctionType{fKeyEqualsComparer_}; } virtual _MappingRepSharedPtr CloneEmpty (IteratorOwnerID forIterableEnvelope) const override { if (fData_.HasActiveIterators ()) { // const cast because though cloning LOGICALLY makes no changes in reality we have to patch iterator lists auto r = Iterable<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSmartPtr<Rep_> (const_cast<Rep_*> (this), forIterableEnvelope); r->fData_.RemoveAll (); return r; } else { return Iterable<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::template MakeSmartPtr<Rep_> (fKeyEqualsComparer_); } } virtual Iterable<KEY_TYPE> Keys () const override { return this->_Keys_Reference_Implementation (); } virtual Iterable<MAPPED_VALUE_TYPE> MappedValues () const override { return this->_Values_Reference_Implementation (); } virtual bool Lookup (ArgByValueType<KEY_TYPE> key, optional<MAPPED_VALUE_TYPE>* item) const override { shared_lock<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; for (typename DataStructures::LinkedList<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::ForwardIterator it (&fData_); it.More (nullptr, true);) { if (fKeyEqualsComparer_ (it.Current ().fKey, key)) { if (item != nullptr) { *item = it.Current ().fValue; } return true; } } if (item != nullptr) { *item = nullopt; } return false; } virtual bool Add (ArgByValueType<KEY_TYPE> key, ArgByValueType<MAPPED_VALUE_TYPE> newElt, AddReplaceMode addReplaceMode) override { using Traversal::kUnknownIteratorOwnerID; lock_guard<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; for (typename DataStructureImplType_::ForwardIterator it (kUnknownIteratorOwnerID, &fData_); it.More (nullptr, true);) { if (fKeyEqualsComparer_ (it.Current ().fKey, key)) { switch (addReplaceMode) { case AddReplaceMode::eAddReplaces: fData_.SetAt (it, KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>{key, newElt}); break; case AddReplaceMode::eAddIfMissing: break; default: AssertNotReached (); } return false; } } fData_.Append (KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>{key, newElt}); return true; } virtual void Remove (ArgByValueType<KEY_TYPE> key) override { using Traversal::kUnknownIteratorOwnerID; lock_guard<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; for (typename DataStructureImplType_::ForwardIterator it (kUnknownIteratorOwnerID, &fData_); it.More (nullptr, true);) { if (fKeyEqualsComparer_ (it.Current ().fKey, key)) { fData_.RemoveAt (it); return; } } } virtual void Remove (const Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>& i) override { lock_guard<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; const typename Iterator<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>::IRep& ir = i.ConstGetRep (); AssertMember (&ir, IteratorRep_); auto& mir = dynamic_cast<const IteratorRep_&> (ir); fData_.RemoveAt (mir.fIterator); } #if qDebug virtual void AssertNoIteratorsReferenceOwner (IteratorOwnerID oBeingDeleted) const override { shared_lock<const Debug::AssertExternallySynchronizedLock> critSec{fData_}; fData_.AssertNoIteratorsReferenceOwner (oBeingDeleted); } #endif private: using DataStructureImplType_ = Private::PatchingDataStructures::LinkedList<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>>; using IteratorRep_ = Private::IteratorImplHelper_<KeyValuePair<KEY_TYPE, MAPPED_VALUE_TYPE>, DataStructureImplType_>; private: DataStructureImplType_ fData_; }; /* ******************************************************************************** *************** Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE> **************** ******************************************************************************** */ template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> inline Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Mapping_LinkedList () : Mapping_LinkedList{equal_to<KEY_TYPE>{}} { AssertRepValidType_ (); } template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> template <typename KEY_EQUALS_COMPARER, enable_if_t<Common::IsPotentiallyComparerRelation<KEY_TYPE, KEY_EQUALS_COMPARER> ()>*> Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Mapping_LinkedList (const KEY_EQUALS_COMPARER& keyEqualsComparer) : inherited (inherited::template MakeSmartPtr<Rep_<KEY_EQUALS_COMPARER>> (keyEqualsComparer)) { AssertRepValidType_ (); } template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> template <typename CONTAINER_OF_ADDABLE, enable_if_t<Configuration::IsIterable_v<CONTAINER_OF_ADDABLE> and not is_convertible_v<const CONTAINER_OF_ADDABLE*, const Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>*>>*> inline Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Mapping_LinkedList (const CONTAINER_OF_ADDABLE& src) : Mapping_LinkedList{} { this->AddAll (src); AssertRepValidType_ (); } template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> template <typename COPY_FROM_ITERATOR_KEYVALUE> Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::Mapping_LinkedList (COPY_FROM_ITERATOR_KEYVALUE start, COPY_FROM_ITERATOR_KEYVALUE end) : Mapping_LinkedList{} { this->AddAll (start, end); AssertRepValidType_ (); } template <typename KEY_TYPE, typename MAPPED_VALUE_TYPE> inline void Mapping_LinkedList<KEY_TYPE, MAPPED_VALUE_TYPE>::AssertRepValidType_ () const { #if qDebug typename inherited::template _SafeReadRepAccessor<IImplRepBase_> tmp{this}; // for side-effect of AssertMemeber #endif } } #endif /* _Stroika_Foundation_Containers_Concrete_Mapping_LinkedList_inl_ */
49.361538
219
0.62576
SophistSolutions
64454fd1135bdb44d4768d9b00c52a088fc94d15
1,192
cpp
C++
codeSpace/Leetcode_684.cpp
chen810/study-code
79cac459595aee422fecbe281705b0ec7a7a08d2
[ "MIT" ]
1
2020-10-18T14:08:21.000Z
2020-10-18T14:08:21.000Z
codeSpace/Leetcode_684.cpp
chen810/study-code
79cac459595aee422fecbe281705b0ec7a7a08d2
[ "MIT" ]
null
null
null
codeSpace/Leetcode_684.cpp
chen810/study-code
79cac459595aee422fecbe281705b0ec7a7a08d2
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: int Find(vector<int>& parent, int index) { // 返回parent[index]的值,顺便更新最新节点的分组 if (parent[index] != index) { // 如果被分组过则进行再次分组 parent[index] = Find(parent, parent[index]); // } return parent[index]; } void Union(vector<int>&parent, int index1, int index2){ // 两个分组合一 parent[Find(parent, index1)] = Find(parent, index2); } vector<int> findRedundantConnection(vector<vector<int>>& edges) { int n = edges.size(); // n条边 vector<int> parent(n + 1); // n个节点 for (int i = 1; i <= n; ++i) { // 初始单独分组 parent[i] = i; } for (auto& i : edges) { // 寻找冲突 int node1 = i[0], node2 = i[1]; if (Find(parent, node1) != Find(parent, node2)) { Union(parent, node1, node2); } else { return i; // 返回冲突 } } return vector<int>{}; } }; int main() { vector<vector<int>> p{ {1,2},{1,3},{2,3} }; Solution t; auto q = t.findRedundantConnection(p); cout << q[0] << "," << q[1] << endl; }
31.368421
80
0.500839
chen810
64464fa0b3a914b63f3f8afdbb01377de8561fbb
5,852
cpp
C++
tests/test_nsg_multi_merge_index.cpp
liql2007/nsg
e47c8228aaeaa0ad83fb195150f742bd7e43e712
[ "MIT" ]
null
null
null
tests/test_nsg_multi_merge_index.cpp
liql2007/nsg
e47c8228aaeaa0ad83fb195150f742bd7e43e712
[ "MIT" ]
null
null
null
tests/test_nsg_multi_merge_index.cpp
liql2007/nsg
e47c8228aaeaa0ad83fb195150f742bd7e43e712
[ "MIT" ]
null
null
null
// // Created by liql2007 on 2020/12/23. // #include <cassert> #include <memory> #include <efanna2e/index_nsg.h> #include <faiss/Clustering.h> #include <efanna2e/test_helper.h> namespace { void loadDocIds(const PartInfo& part, std::vector<unsigned>& docIds) { std::ifstream in(part.idPath.c_str(), std::ios::binary); docIds.resize(part.vecNum); in.read((char*)docIds.data(), docIds.size() * sizeof(unsigned)); if (in.bad()) { std::cerr << "read doc id failed" << std::endl; in.close(); exit(-1); } in.close(); } void mergeNsgEdge(const PartInfo& part, const efanna2e::IndexNSG& partIndex, efanna2e::IndexNSG& index) { std::vector<unsigned> docIds; loadDocIds(part, docIds); auto& graph = index.graph(); const auto& partGraph = partIndex.graph(); auto dim = index.GetDimension(); auto isExist = [](const std::vector<unsigned> vec, unsigned v) { for (auto vi : vec) { if (vi == v) { return true; } } return false; }; #pragma omp parallel for for (size_t i = 0; i < partGraph.size(); ++i) { auto gid = docIds[i]; auto& neighbors = graph[gid]; if (neighbors.empty()) { // first add auto partVecPtr = partIndex.getData() + i * dim; auto vecPtr = const_cast<float*>(index.getData() + gid * dim); std::memcpy(vecPtr, partVecPtr, dim * sizeof(float)); } neighbors.reserve(neighbors.size() + partGraph[i].size()); for (auto partVecId : partGraph[i]) { auto partGid = docIds[partVecId]; if (!isExist(neighbors, partGid)) { neighbors.push_back(partGid); } } } auto& eps = index.getEps(); auto& partEps = partIndex.getEps(); for (auto partDocId : partEps) { auto partGid = docIds[partDocId]; if (!isExist(eps, partGid)) { eps.push_back(partGid); } } } void pruneEdge(unsigned R, efanna2e::IndexNSG& index) { std::cout << "prune edge" << std::endl; efanna2e::DistanceL2 distance; auto& graph = index.graph(); auto data = index.getData(); auto dim = index.GetDimension(); #pragma omp parallel for for (size_t id = 0; id < graph.size(); ++id) { auto& neighbors = graph[id]; if (neighbors.size() < R) { continue; } auto vec = data + id * dim; std::vector<efanna2e::Neighbor> pool(neighbors.size()); for (unsigned i = 0; i < neighbors.size(); ++i) { auto nid = neighbors[i]; assert(nid != id); auto nVec = data + nid * dim; pool[i].id = nid; pool[i].distance = distance.compare(vec, nVec, dim); } std::sort(pool.begin(), pool.end()); unsigned resultSize = 1; unsigned checkIndex = 1; while(++checkIndex < pool.size() && resultSize < R) { auto &p = pool[checkIndex]; bool occlude = false; for (unsigned t = 0; t < resultSize; t++) { if (p.id == pool[t].id) { occlude = true; break; } float djk = distance.compare(data + dim * (size_t)pool[t].id, data + dim * (size_t)p.id, (unsigned)dim); #ifdef SSG float cos_ij = (p.distance + pool[t].distance - djk) / 2 / sqrt(p.distance * pool[t].distance); if (cos_ij > efanna2e::cosinThreshold) { occlude = true; break; } #else if (djk < p.distance /* dik */) { occlude = true; break; } #endif } if (!occlude) pool[resultSize++] = p; } neighbors.resize(resultSize); for (unsigned i = 0; i < resultSize; ++i) { neighbors[i] = pool[i].id; } } } void statisticAndSet(efanna2e::IndexNSG& index) { unsigned max = 0, min = 1e6; double avg = 0; auto& graph = index.graph(); for (size_t i = 0; i < graph.size(); i++) { auto size = graph[i].size(); max = max < size ? size : max; min = min > size ? size : min; avg += size; } index.setWidth(max); avg /= index.getVecNum(); printf("Degree Statistics: Max = %d, Min = %d, Avg = %.3lf\n", max, min, avg); } } int main(int argc, char** argv) { if (argc != 3) { std::cout << argv[0] << " multi_index_dir R" << std::endl; exit(-1); } auto multi_index_path = argv[1]; unsigned R = (unsigned)atoi(argv[2]); Partitions parts; parts.deserialize(multi_index_path); efanna2e::IndexNSG index(parts.dim, parts.totalVecNum, efanna2e::L2, nullptr); float* vecData = new float[parts.totalVecNum * parts.dim]; index.graph().resize(parts.totalVecNum); index.setData(vecData); auto bb = std::chrono::high_resolution_clock::now(); auto partCount = parts.partInfos.size(); double avgDegree = 0; for (unsigned i = 0; i < partCount; ++i) { std::cout << "** Merge NSG: " << i + 1 << std::endl; const auto& part = parts.partInfos[i]; float* partVecData = NULL; unsigned pointNum, dim; load_data(part.docPath.c_str(), partVecData, pointNum, dim); assert(pointNum == part.vecNum); assert(dim == parts.dim); std::unique_ptr<float[]>holder(partVecData); efanna2e::IndexNSG partIndex(dim, pointNum, efanna2e::L2, nullptr); partIndex.Load(part.nsgPath.c_str()); partIndex.setData(partVecData); avgDegree += partIndex.getAvgDegree(); mergeNsgEdge(part, partIndex, index); } std::cout << "part index avg degree: " << avgDegree / partCount << "\n"; statisticAndSet(index); pruneEdge(R, index); // efanna2e::Parameters paras; // paras.Set<unsigned>("L", R); // index.tree_grow(paras); statisticAndSet(index); auto ee = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> diff = ee - bb; std::cout << "merge time: " << diff.count() << "\n"; index.Save(parts.getMergedNsgPath().c_str()); // save_data(parts.getMergedVecPath().c_str(), vecData, parts.totalVecNum, parts.dim); return 0; }
30.010256
88
0.596206
liql2007
644ac7f0f8b1fa90a8d6437f8f2a24c85481dce2
12,424
cpp
C++
check_fever_app/Palettes.cpp
Myzhar/Lepton3_Jetson
f6ecce258484b47e102da7239c942662520dd2bc
[ "MIT" ]
45
2020-06-08T00:23:55.000Z
2021-12-23T08:38:17.000Z
check_fever_app/Palettes.cpp
Myzhar/Lepton3_Jetson
f6ecce258484b47e102da7239c942662520dd2bc
[ "MIT" ]
12
2020-07-11T13:46:06.000Z
2022-03-23T11:38:56.000Z
check_fever_app/Palettes.cpp
Myzhar/Lepton3_Jetson
f6ecce258484b47e102da7239c942662520dd2bc
[ "MIT" ]
12
2020-06-08T02:27:54.000Z
2022-01-12T09:52:45.000Z
#include "Palettes.h" #include <math.h> #include <iostream> using namespace std; uint8_t colormap_byr[LUT_SIZE_8*3]; uint8_t colormap_bry[LUT_SIZE_8*3]; uint8_t colormap_bgyr[LUT_SIZE_8*3]; uint8_t colormap_whitehot[LUT_SIZE_8*3]; uint8_t colormap_blackhot[LUT_SIZE_8*3]; uint8_t colormap_whitehotBYR[LUT_SIZE_8*3]; uint8_t colormap_whitehotBRY[LUT_SIZE_8*3]; const uint8_t* palettes[PALETTES_COUNT] = { colormap_byr, colormap_bry, colormap_bgyr, colormap_whitehot, colormap_blackhot, colormap_whitehotBYR, colormap_whitehotBRY }; // From http://www.andrewnoske.com/wiki/Code_-_heatmaps_and_color_gradients void getHeatMapColorBYR(double value, double& red, double& green, double& blue) { const int NUM_COLORS = 3; static double color[NUM_COLORS][3] = { {0,0,1}, {1,1,0}, {1,0,0} }; // A static array of 3 colors: (blue, yellow, red) using {r,g,b} for each. int idx1; // |-- Our desired color will be between these two indexes in "color". int idx2; // | double fractBetween = 0; // Fraction between "idx1" and "idx2" where our value is. if(value <= 0) // accounts for an input <=0 { idx1 = idx2 = 0; } else if(value >= 1) // accounts for an input >=0 { idx1 = idx2 = NUM_COLORS-1; } else { value = value * (NUM_COLORS-1); // Will multiply value by NUM_COLORS (-1). idx1 = floor(value); // Our desired color will be after this index. idx2 = idx1+1; // ... and before this index (inclusive). fractBetween = value - static_cast<double>(idx1); // Distance between the two indexes (0-1). } red = (color[idx2][0] - color[idx1][0])*fractBetween + color[idx1][0]; green = (color[idx2][1] - color[idx1][1])*fractBetween + color[idx1][1]; blue = (color[idx2][2] - color[idx1][2])*fractBetween + color[idx1][2]; } void getHeatMapColorBRY(double value, double& red, double& green, double& blue) { const int NUM_COLORS = 3; static double color[NUM_COLORS][3] = { {0,0,1}, {1,0,0}, {1,1,0} }; // A static array of 3 colors: (blue, red, yellow ) using {r,g,b} for each. int idx1; // |-- Our desired color will be between these two indexes in "color". int idx2; // | double fractBetween = 0; // Fraction between "idx1" and "idx2" where our value is. if(value <= 0) // accounts for an input <=0 { idx1 = idx2 = 0; } else if(value >= 1) // accounts for an input >=0 { idx1 = idx2 = NUM_COLORS-1; } else { value = value * (NUM_COLORS-1); // Will multiply value by NUM_COLORS (-1). idx1 = floor(value); // Our desired color will be after this index. idx2 = idx1+1; // ... and before this index (inclusive). fractBetween = value - static_cast<double>(idx1); // Distance between the two indexes (0-1). } red = (color[idx2][0] - color[idx1][0])*fractBetween + color[idx1][0]; green = (color[idx2][1] - color[idx1][1])*fractBetween + color[idx1][1]; blue = (color[idx2][2] - color[idx1][2])*fractBetween + color[idx1][2]; } void getHeatMapColorBGYR(double value, double& red, double& green, double& blue) { const int NUM_COLORS = 4; static double color[NUM_COLORS][3] = { {0,0,1}, {0,1,0}, {1,1,0}, {1,0,0} }; // A static array of 4 colors: (blue, green, yellow, red) using {r,g,b} for each. int idx1; // |-- Our desired color will be between these two indexes in "color". int idx2; // | double fractBetween = 0; // Fraction between "idx1" and "idx2" where our value is. if(value <= 0) // accounts for an input <=0 { idx1 = idx2 = 0; } else if(value >= 1) // accounts for an input >=0 { idx1 = idx2 = NUM_COLORS-1; } else { value = value * (NUM_COLORS-1); // Will multiply value by NUM_COLORS (-1). idx1 = floor(value); // Our desired color will be after this index. idx2 = idx1+1; // ... and before this index (inclusive). fractBetween = value - static_cast<double>(idx1); // Distance between the two indexes (0-1). } red = (color[idx2][0] - color[idx1][0])*fractBetween + color[idx1][0]; green = (color[idx2][1] - color[idx1][1])*fractBetween + color[idx1][1]; blue = (color[idx2][2] - color[idx1][2])*fractBetween + color[idx1][2]; } void getHeatMapColorWhiteHot(double value, double& red, double& green, double& blue) { const int NUM_COLORS = 2; static double color[NUM_COLORS][3] = { {0,0,0}, {1,1,1} }; // A static array of 2 colors: (black, white) using {r,g,b} for each. int idx1; // |-- Our desired color will be between these two indexes in "color". int idx2; // | double fractBetween = 0; // Fraction between "idx1" and "idx2" where our value is. if(value <= 0) // accounts for an input <=0 { idx1 = idx2 = 0; } else if(value >= 1) // accounts for an input >=0 { idx1 = idx2 = NUM_COLORS-1; } else { value = value * (NUM_COLORS-1); // Will multiply value by NUM_COLORS (-1). idx1 = floor(value); // Our desired color will be after this index. idx2 = idx1+1; // ... and before this index (inclusive). fractBetween = value - static_cast<double>(idx1); // Distance between the two indexes (0-1). } red = (color[idx2][0] - color[idx1][0])*fractBetween + color[idx1][0]; green = (color[idx2][1] - color[idx1][1])*fractBetween + color[idx1][1]; blue = (color[idx2][2] - color[idx1][2])*fractBetween + color[idx1][2]; } void getHeatMapColorBlackHot(double value, double& red, double& green, double& blue) { const int NUM_COLORS = 2; static double color[NUM_COLORS][3] = { {1,1,1}, {0,0,0} }; // A static array of 2 colors: (black, white) using {r,g,b} for each. int idx1; // |-- Our desired color will be between these two indexes in "color". int idx2; // | double fractBetween = 0; // Fraction between "idx1" and "idx2" where our value is. if(value <= 0) // accounts for an input <=0 { idx1 = idx2 = 0; } else if(value >= 1) // accounts for an input >=0 { idx1 = idx2 = NUM_COLORS-1; } else { value = value * (NUM_COLORS-1); // Will multiply value by NUM_COLORS (-1). idx1 = floor(value); // Our desired color will be after this index. idx2 = idx1+1; // ... and before this index (inclusive). fractBetween = value - static_cast<double>(idx1); // Distance between the two indexes (0-1). } red = (color[idx2][0] - color[idx1][0])*fractBetween + color[idx1][0]; green = (color[idx2][1] - color[idx1][1])*fractBetween + color[idx1][1]; blue = (color[idx2][2] - color[idx1][2])*fractBetween + color[idx1][2]; } void getHeatMapColorWhiteHotBYR(double value, double& red, double& green, double& blue) { const int NUM_COLORS = 5; static double color[NUM_COLORS][3] = { {0,0,0}, {0,0,1}, {1,1,0}, {1,0,0}, {1,1,1} }; // A static array of 5 colors: (black, blue, yellow, red, white) using {r,g,b} for each. int idx1; // |-- Our desired color will be between these two indexes in "color". int idx2; // | double fractBetween = 0; // Fraction between "idx1" and "idx2" where our value is. if(value <= 0) // accounts for an input <=0 { idx1 = idx2 = 0; } else if(value >= 1) // accounts for an input >=0 { idx1 = idx2 = NUM_COLORS-1; } else { value = value * (NUM_COLORS-1); // Will multiply value by NUM_COLORS (-1). idx1 = floor(value); // Our desired color will be after this index. idx2 = idx1+1; // ... and before this index (inclusive). fractBetween = value - static_cast<double>(idx1); // Distance between the two indexes (0-1). } red = (color[idx2][0] - color[idx1][0])*fractBetween + color[idx1][0]; green = (color[idx2][1] - color[idx1][1])*fractBetween + color[idx1][1]; blue = (color[idx2][2] - color[idx1][2])*fractBetween + color[idx1][2]; } void getHeatMapColorWhiteHotBRY(double value, double& red, double& green, double& blue) { const int NUM_COLORS = 5; static double color[NUM_COLORS][3] = { {0,0,0}, {0,0,1}, {1,0,0}, {1,1,0}, {1,1,1} }; // A static array of 5 colors: (black, blue, red, yellow, white) using {r,g,b} for each. int idx1; // |-- Our desired color will be between these two indexes in "color". int idx2; // | double fractBetween = 0; // Fraction between "idx1" and "idx2" where our value is. if(value <= 0) // accounts for an input <=0 { idx1 = idx2 = 0; } else if(value >= 1) // accounts for an input >=0 { idx1 = idx2 = NUM_COLORS-1; } else { value = value * (NUM_COLORS-1); // Will multiply value by NUM_COLORS (-1). idx1 = floor(value); // Our desired color will be after this index. idx2 = idx1+1; // ... and before this index (inclusive). fractBetween = value - static_cast<double>(idx1); // Distance between the two indexes (0-1). } red = (color[idx2][0] - color[idx1][0])*fractBetween + color[idx1][0]; green = (color[idx2][1] - color[idx1][1])*fractBetween + color[idx1][1]; blue = (color[idx2][2] - color[idx1][2])*fractBetween + color[idx1][2]; } void createColorMaps() { double r,g,b; uint8_t r8,g8,b8; for( int i=0; i<LUT_SIZE_8; i++ ) { double val = static_cast<double>(i)/LUT_SIZE_8; // >>>>> BLU YELLOW RED getHeatMapColorBYR( val, r,g,b ); r8=static_cast<uint8_t>(r*255+0.5); g8=static_cast<uint8_t>(g*255+0.5); b8=static_cast<uint8_t>(b*255+0.5); colormap_byr[i*3+0] = r8; colormap_byr[i*3+1] = g8; colormap_byr[i*3+2] = b8; // <<<<< BLU YELLOW RED // >>>>> BLU RED YELLOW getHeatMapColorBRY( val, r,g,b ); r8=static_cast<uint8_t>(r*255+0.5); g8=static_cast<uint8_t>(g*255+0.5); b8=static_cast<uint8_t>(b*255+0.5); colormap_bry[i*3+0] = r8; colormap_bry[i*3+1] = g8; colormap_bry[i*3+2] = b8; // <<<<< BLU RED YELLOW // >>>>> BLU GREEN YELLOW RED getHeatMapColorBGYR( val, r,g,b ); r8=static_cast<uint8_t>(r*255+0.5); g8=static_cast<uint8_t>(g*255+0.5); b8=static_cast<uint8_t>(b*255+0.5); colormap_bgyr[i*3+0] = r8; colormap_bgyr[i*3+1] = g8; colormap_bgyr[i*3+2] = b8; // <<<<< BLU GREEN YELLOW RED // >>>>> WhiteHot getHeatMapColorWhiteHot( val, r,g,b ); r8=static_cast<uint8_t>(r*255+0.5); g8=static_cast<uint8_t>(g*255+0.5); b8=static_cast<uint8_t>(b*255+0.5); colormap_whitehot[i*3+0] = r8; colormap_whitehot[i*3+1] = g8; colormap_whitehot[i*3+2] = b8; // <<<<< WhiteHot // >>>>> BlackHot getHeatMapColorBlackHot( val, r,g,b ); r8=static_cast<uint8_t>(r*255+0.5); g8=static_cast<uint8_t>(g*255+0.5); b8=static_cast<uint8_t>(b*255+0.5); colormap_blackhot[i*3+0] = r8; colormap_blackhot[i*3+1] = g8; colormap_blackhot[i*3+2] = b8; // <<<<< BlackHot // >>>>> WhiteHot BYR getHeatMapColorWhiteHotBYR( val, r,g,b ); r8=static_cast<uint8_t>(r*255+0.5); g8=static_cast<uint8_t>(g*255+0.5); b8=static_cast<uint8_t>(b*255+0.5); colormap_whitehotBYR[i*3+0] = r8; colormap_whitehotBYR[i*3+1] = g8; colormap_whitehotBYR[i*3+2] = b8; // <<<<< WhiteHot BYR // >>>>> WhiteHot BRY getHeatMapColorWhiteHotBRY( val, r,g,b ); r8=static_cast<uint8_t>(r*255+0.5); g8=static_cast<uint8_t>(g*255+0.5); b8=static_cast<uint8_t>(b*255+0.5); colormap_whitehotBRY[i*3+0] = r8; colormap_whitehotBRY[i*3+1] = g8; colormap_whitehotBRY[i*3+2] = b8; // <<<<< WhiteHot BRY } }
36.327485
103
0.568496
Myzhar
64531ec75fc0932a0b58d98458c71676e618c134
1,196
hpp
C++
Libraries/Zilch/Delegate.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
3
2022-02-11T10:34:33.000Z
2022-02-24T17:44:17.000Z
Libraries/Zilch/Delegate.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
Libraries/Zilch/Delegate.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
// MIT Licensed (see LICENSE.md). #pragma once #ifndef ZILCH_DELEGATE_HPP # define ZILCH_DELEGATE_HPP namespace Zilch { // Invalid constants const size_t InvalidOpcodeLocation = (size_t)-1; // A delegate is a simple type that consists of an index for a function, as well // as the this pointer object class ZeroShared Delegate { public: // Constructor Delegate(); // Are two handles the exact same? bool operator==(const Delegate& rhs) const; bool operator==(Zero::NullPointerType) const; // Are two handles different? bool operator!=(const Delegate& rhs) const; bool operator!=(Zero::NullPointerType) const; // Hashes a handle (generally used by hashable containers) size_t Hash() const; // Checks if the value stored within the delegate is null (no function // pointer) bool IsNull() const; bool IsNotNull() const; // Invokes a delegate, automatically passing in the 'this' handle Any Invoke(const Array<Any>& arguments = Array<Any>()); public: // The function we run when invoking this delegate Function* BoundFunction; // The handle for the delegate Handle ThisHandle; }; typedef const Delegate& DelegateParam; } // namespace Zilch #endif
23.45098
80
0.727425
RyanTylerRae
6453a16d758ec757b3e1189d39f2c331d592f321
950
cpp
C++
31.05/run.cpp
NoizuHika/SOP
2ecfde6fba607f161a8e03ae353e36ea39c847e5
[ "MIT" ]
null
null
null
31.05/run.cpp
NoizuHika/SOP
2ecfde6fba607f161a8e03ae353e36ea39c847e5
[ "MIT" ]
null
null
null
31.05/run.cpp
NoizuHika/SOP
2ecfde6fba607f161a8e03ae353e36ea39c847e5
[ "MIT" ]
null
null
null
#include <iostream> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <string.h> pid_t cpid; void handler(int i){ kill(cpid, i); } auto main(int argc, char *argv[]) -> int { cpid = fork(); if (cpid == -1) { perror("fork"); exit(EXIT_FAILURE); } if (cpid == 0) { execvp(argv[1], argv+1); perror("execve"); exit(EXIT_FAILURE); } struct sigaction act{}; act.sa_handler = handler; sigaction(SIGTERM, &act, nullptr); signal(SIGINT, SIG_IGN); int status = 0; waitpid(cpid, &status, 0); if (WIFEXITED(status)) { std::cout << "Child PID is " << cpid << " proccess, status: " << WEXITSTATUS(status) << "\n"; } if (WIFSIGNALED(status)) { std::cout << "Procces: " << cpid << " killed by signal: " << WTERMSIG(status) << "\n" << strsignal(WTERMSIG(status)) << "\n"; } return 0; }
19.387755
97
0.572632
NoizuHika
6455ce89933bc8b63399ceed4c1c0619cd9cbc2e
917
hpp
C++
android-28/android/media/MediaCodecList.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/media/MediaCodecList.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-30/android/media/MediaCodecList.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../../JObject.hpp" class JArray; namespace android::media { class MediaCodecInfo; } namespace android::media { class MediaFormat; } class JString; namespace android::media { class MediaCodecList : public JObject { public: // Fields static jint ALL_CODECS(); static jint REGULAR_CODECS(); // QJniObject forward template<typename ...Ts> explicit MediaCodecList(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} MediaCodecList(QJniObject obj); // Constructors MediaCodecList(jint arg0); // Methods static jint getCodecCount(); static android::media::MediaCodecInfo getCodecInfoAt(jint arg0); JString findDecoderForFormat(android::media::MediaFormat arg0) const; JString findEncoderForFormat(android::media::MediaFormat arg0) const; JArray getCodecInfos() const; }; } // namespace android::media
22.365854
155
0.730643
YJBeetle
645f0d1be2c6c4cf36ba6c144b211fc7a7f912cb
231
cpp
C++
variant/variant.cpp
danielkrupinski/cpp-playground
0b02de70bfdbbc7ebb073180972b382231a198d4
[ "MIT" ]
1
2018-07-23T21:15:11.000Z
2018-07-23T21:15:11.000Z
variant/variant.cpp
danielkrupinski/cpp-playground
0b02de70bfdbbc7ebb073180972b382231a198d4
[ "MIT" ]
null
null
null
variant/variant.cpp
danielkrupinski/cpp-playground
0b02de70bfdbbc7ebb073180972b382231a198d4
[ "MIT" ]
3
2018-11-10T05:39:00.000Z
2019-12-08T12:14:19.000Z
#include <iostream> #include <variant> int main() { std::variant<int, double> v = 20; std::cout << "v = " << std::get<int>(v) << '\n'; v = 33.33; std::cout << "v = " << std::get<double>(v) << '\n'; return 0; }
19.25
55
0.480519
danielkrupinski
64601ce7b4662e1beb8705ca8f670deef7141456
1,248
cpp
C++
nets/analyses/largestComponent.cpp
CxAalto/lcelib
dceea76e3f18696a2fa7c8287e1a537fbf493474
[ "0BSD" ]
1
2017-01-24T01:35:43.000Z
2017-01-24T01:35:43.000Z
nets/analyses/largestComponent.cpp
CxAalto/lcelib
dceea76e3f18696a2fa7c8287e1a537fbf493474
[ "0BSD" ]
null
null
null
nets/analyses/largestComponent.cpp
CxAalto/lcelib
dceea76e3f18696a2fa7c8287e1a537fbf493474
[ "0BSD" ]
null
null
null
/* largestComponent.cpp 2006 Jun 14 Author: Lauri Kovanen Reads a network from standard input and writes out largest component. The nodes will be re-indexed from 0 to N, where N is the size of the largest component. To compile: g++ -O -Wall largestComponent.cpp -o largestComponent To run: cat net.edg | ./largestComponent > net_largest.edg (net.edg is a file where each row contains the values EDGE TAIL EDGECHARACTERISTIC (EDGECHARACTERISTIC for example edge weight) */ //#define DEBUG // for debugging code to be run #define NDEBUG // to turn assertions off #include "../../Containers.H" #include "../../Nets.H" #include "../NetExtras.H" typedef float EdgeData; typedef SymmNet<EdgeData> NetType; int main(int argc, char* argv[]) { std::auto_ptr<NetType> netPointer(readNet2<NetType>(1,0)); NetType& net = *netPointer; // Create a reference for easier handling of net. std::auto_ptr<NetType> netPointer2(findLargestComponent<NetType>(net)); NetType& net2 = *netPointer2; // Create a reference for easier handling of net. outputEdgesAndWeights(net2); }
28.363636
82
0.642628
CxAalto
6462566d2243de74364fc34516a1934d95a5552e
627
cpp
C++
src/macro/macro39.cpp
chennachaos/stabfem
b3d1f44c45e354dc930203bda22efc800c377c6f
[ "MIT" ]
null
null
null
src/macro/macro39.cpp
chennachaos/stabfem
b3d1f44c45e354dc930203bda22efc800c377c6f
[ "MIT" ]
null
null
null
src/macro/macro39.cpp
chennachaos/stabfem
b3d1f44c45e354dc930203bda22efc800c377c6f
[ "MIT" ]
null
null
null
#include "Macro.h" #include "MacroQueue.h" extern MacroQueue macroQueue; int macro39(Macro &macro) { if (!macro) { macro.name = "stop"; macro.type = "ctrl"; macro.what = "stop macro queue execution"; macro.sensitivity[INTER] = true; macro.sensitivity[BATCH] = true; macro.sensitivity[PRE] = true; return 0; } //-------------------------------------------------------------------------------------------------- return macroQueue.macCmd.n + 1; //-------------------------------------------------------------------------------------------------- }
20.9
101
0.392344
chennachaos
6463d3a33ec0f14890570283641e453098957267
4,546
cpp
C++
Program/DefragIPv4.cpp
CapBuran/PCAPFilter_Faster
94058c53f3ce861d017580c853543893e9b88096
[ "Unlicense" ]
1
2020-07-16T09:03:43.000Z
2020-07-16T09:03:43.000Z
Program/DefragIPv4.cpp
CapBuran/PCAPFilter_Faster
94058c53f3ce861d017580c853543893e9b88096
[ "Unlicense" ]
1
2021-07-02T09:00:05.000Z
2021-07-02T09:00:05.000Z
Program/DefragIPv4.cpp
CapBuran/PCAPFilter_Faster
94058c53f3ce861d017580c853543893e9b88096
[ "Unlicense" ]
1
2019-10-25T14:42:50.000Z
2019-10-25T14:42:50.000Z
#include <cstring> #include "UInts.h" #include "DefragIPv4.h" #include "FilterTCPHeader.h" #include "FilterUDPHeader.h" #include "FilterSCTPHeader.h" struct HashForDefragRowsIVv4 { uint32_t src_addr; /**< source address */ uint32_t dst_addr; /**< destination address */ uint32_t network_id; uint16_t packet_id; HashForDefragRowsIVv4(uint16_t NetworkID, const FilterTraffic::ip4_header* IPv4) : network_id(NetworkID) , packet_id(IPv4->packet_id) , src_addr(IPv4->src_addr.ip_32) , dst_addr(IPv4->dst_addr.ip_32) { } bool operator<(const HashForDefragRowsIVv4& other) const { uint64_t S1 = packet_id + (static_cast<uint64_t>(network_id) << 32); uint64_t S2 = other.packet_id + (static_cast<uint64_t>(other.network_id) << 32); uint64_t S3 = src_addr + (static_cast<uint64_t>(dst_addr) << 32); uint64_t S4 = other.src_addr + (static_cast<uint64_t>(other.dst_addr) << 32); if (S1 == S2) return S1 < S2; else return S3 < S4; } }; struct DefragRowIPv4 { struct BeginEndFragment { uint16_t Begin; uint16_t Size; BeginEndFragment() : Begin(0) , Size(0) { } }; uint16_t MaxFragment; uint16_t CounterFragment; uint16_t StartIPv4; char summData[64 * 1024 - 64]; BeginEndFragment Fragments[256]; DefragRowIPv4() { MaxFragment = 0; CounterFragment = 0; StartIPv4 = 0; } bool IsContainsFragment(uint16_t Begin) const { for (uint16_t i = 0; i < CounterFragment; i++) { const BeginEndFragment& fragments = Fragments[i]; if (fragments.Begin == Begin) { return fragments.Size > 0; } } return false; } void AddFragment(uint16_t Begin, uint16_t Size, const char* Data) { if (IsContainsFragment(Begin)) return; BeginEndFragment& fragments = Fragments[CounterFragment++]; fragments.Begin = Begin; fragments.Size = Size; memcpy(&summData[StartIPv4 + (fragments.Begin << 3)], Data, Size << 3); } bool IsBuild() const { if (CounterFragment < 2) return false; uint16_t FindNextBegin = 0; for (uint16_t i = 0; i < CounterFragment; i++) { bool IsFind = false; for (uint16_t j = 0; j < CounterFragment; j++) { const BeginEndFragment& fragments = Fragments[j]; if (fragments.Begin == FindNextBegin) { IsFind = true; FindNextBegin = fragments.Begin + fragments.Size; break; } } if (!IsFind) return false; } return true; } DefragData Build(const char *Frame, uint32_t LengthFrame, const FilterTraffic::ip4_header* IPv4) { const uint16_t lenIP((IPv4->version_ihl & 0x0f) << 2); const uint16_t LengthIPData(Swap16(IPv4->total_length) - lenIP); StartIPv4 = static_cast<uint16_t>(reinterpret_cast<const char*>(IPv4) - Frame) + lenIP; if(CounterFragment == 0) memcpy(&summData[0], Frame, StartIPv4); const uint16_t fragment_offset = Swap16(IPv4->fragment_offset); if (IPv4->packet_id != 0) { uint16_t fragment_offset_begin = fragment_offset & 0x1FFF; if (!(fragment_offset & 0x2000)) { MaxFragment = fragment_offset_begin + (LengthIPData >> 3); } AddFragment(fragment_offset_begin, LengthIPData >> 3, reinterpret_cast<const char*>(IPv4) + lenIP); if (IsBuild()) { FilterTraffic::ip4_header* IPv4Build = reinterpret_cast<FilterTraffic::ip4_header*>(&summData[StartIPv4 - lenIP]); IPv4Build->total_length = Swap16(MaxFragment << 3); IPv4Build->fragment_offset = 0; IPv4Build->packet_id = 0; return DefragData( &summData[0], &summData[StartIPv4], (MaxFragment << 3) + StartIPv4, (MaxFragment << 3)); } } else { return DefragData(Frame, reinterpret_cast<const char*>(IPv4) + lenIP, LengthFrame, LengthIPData); } return DefragData(); } }; typedef std::map<HashForDefragRowsIVv4, DefragRowIPv4> typeDefragDataIPv4; static typeDefragDataIPv4 DefragDataIPv4; DefragData DefragIP::AddIPv4(uint32_t NetworkID, const char *Frame, uint32_t LengthFrame, const FilterTraffic::ip4_header* IPv4) { HashForDefragRowsIVv4 Packet(NetworkID, IPv4); return DefragDataIPv4[Packet].Build(Frame, LengthFrame, IPv4); } void DefragIP::EraseIPv4(uint32_t NetworkID, const FilterTraffic::ip4_header * IPv4) { HashForDefragRowsIVv4 Packet(NetworkID, IPv4); auto it_find = DefragDataIPv4.find(Packet); if (it_find != DefragDataIPv4.end()) { DefragDataIPv4.erase(it_find); } }
27.551515
128
0.66498
CapBuran
6464adb75fb222dc90ec6bfe9ea78ef820615f78
537
hpp
C++
Jagerts.Felcp.Xml/XmlFile.hpp
Jagreaper/Project-Felcp
195d5de4230fe98e53d862c5c69b986344bc2cf5
[ "MIT" ]
null
null
null
Jagerts.Felcp.Xml/XmlFile.hpp
Jagreaper/Project-Felcp
195d5de4230fe98e53d862c5c69b986344bc2cf5
[ "MIT" ]
null
null
null
Jagerts.Felcp.Xml/XmlFile.hpp
Jagreaper/Project-Felcp
195d5de4230fe98e53d862c5c69b986344bc2cf5
[ "MIT" ]
null
null
null
#pragma once #include "Jagerts.Felcp.Xml/XmlAttribute.hpp" #include "Jagerts.Felcp.Xml/XmlElement.hpp" namespace Jagerts::Felcp::Xml { class JAGERTS_FELCP_XML_API XmlFile { public: const std::vector<XmlElement>* GetElements() const; const std::vector<XmlElement> GetElements(const std::string name) const; void AddElement(const XmlElement& element); static void FromString(const std::string& string, XmlFile* file); void ToString(std::string* string); void Clear(); private: std::vector<XmlElement> _elements; }; }
24.409091
74
0.746741
Jagreaper
6466c2ba3ef7685dfcb8c2baaf3b8f52262d5218
1,681
cpp
C++
src/main.cpp
astojanov/Clover
80d6cb248737ab786300623a4678b4ab91e78fc2
[ "Apache-2.0" ]
63
2018-05-29T13:20:21.000Z
2022-01-01T23:41:04.000Z
src/main.cpp
astojanov/Clover
80d6cb248737ab786300623a4678b4ab91e78fc2
[ "Apache-2.0" ]
1
2018-10-23T11:49:33.000Z
2018-10-24T09:11:55.000Z
src/main.cpp
astojanov/Clover
80d6cb248737ab786300623a4678b4ab91e78fc2
[ "Apache-2.0" ]
5
2018-07-02T11:06:51.000Z
2021-02-27T09:18:05.000Z
#include <CloverBase.h> #include "../lib/cxxopts.h" #include "../lib/sysinfo.h" #include "../test/search/00_search.h" #include "../test/performance/00_test.h" #include "../test/validate/00_validate.h" #include "../test/accuracy/00_accuracy.h" int main (int argc, const char* argv[]) { // // Parse the option and perform different tests // try { cxxopts::Options options(argv[0], " - example command line options"); options.positional_help("[optional args]").show_positional_help(); options.add_options() ("a,accuracy", "Start the tests for accuracy") ("g,grid", "Start the grid search for hyperparameter optimization") ("v,validate", "Start the tests for validation") ("p,performance", "Start the tests for performance") ("h,help", "Print help") ; options.parse_positional({"input", "output", "positional"}); auto result = options.parse(argc, argv); if (result.count("help")) { std::cout << options.help({"", "Group"}) << std::endl; exit(0); } print_compiler_and_system_info(); CloverBase::initializeLibraries(); if (result.count("a")) { test_accuracy(); } if (result.count("g")) { search(argc, argv); } if (result.count("v")) { validate(argc, argv); } if (result.count("p")) { test(argc, argv); } } catch (const cxxopts::OptionException& e) { std::cout << "error parsing options: " << e.what() << std::endl; exit(1); } return 0; }
29.491228
83
0.544914
astojanov
646901913c75ef2579be714d0486d519d3421045
4,844
hpp
C++
projects/merge_sort_multithreading/merge_sort.hpp
ItsKarlito/OperatingSystems
258e884a8484d3b5e5b7ead2507234db6de50cc1
[ "MIT" ]
4
2021-02-03T22:53:24.000Z
2021-02-10T02:01:24.000Z
projects/merge_sort_multithreading/merge_sort.hpp
ItsKarlito/OperatingSystems
258e884a8484d3b5e5b7ead2507234db6de50cc1
[ "MIT" ]
3
2021-04-03T23:08:14.000Z
2021-04-06T04:09:16.000Z
projects/merge_sort_multithreading/merge_sort.hpp
ItsKarlito/OperatingSystems
258e884a8484d3b5e5b7ead2507234db6de50cc1
[ "MIT" ]
4
2021-02-03T22:59:33.000Z
2021-04-29T21:52:11.000Z
#ifndef MERGE_SORT_H_ #define MERGE_SORT_H_ #include <iostream> #include <fstream> #include <sstream> #include <utility> #include <thread> #include <cstring> #include <functional> template <typename Type> class MergeSort { private: typedef std::function<void(const std::string)> report_callback_t; report_callback_t report_callback; //Send message to output file regarding thread status inline void report_thread_start_(std::thread &t, const std::thread::id i) { std::ostringstream ss; ss << "Thread " << i << " started\n"; this->report(ss.str()); ss.clear(); } inline void report_thread_finish_(std::thread &t, const std::thread::id i) { std::ostringstream ss; ss << "Thread " << i << " finished "; this->report(ss.str()); ss.clear(); } public: //Initialize the output text file MergeSort(report_callback_t report_callback = nullptr) : report_callback(report_callback) {} void sort_main(Type *arr, size_t size) { //Start the parent thread of merge sort if (size > 0) { std::thread parent(&MergeSort::sort, this, arr, 0, size - 1); std::thread::id parent_id = parent.get_id(); report_thread_start_(parent, parent_id); parent.join(); report_thread_finish_(parent, parent_id); print_array(arr, 0, size - 1); } else throw std::runtime_error("ERROR: Sorting size cannot be lower than 1"); } private: //Sort for specific segment of array void sort(Type *arr, int start, int end) { //Check if arr is divisible if (start >= end) return; //Divide arr into two segments, and sort each int m = start + (end - start) / 2; //Start the first thread which will deal with 1st half of given array //wait for first thread to finish before moving on std::thread first(&MergeSort::sort, this, arr, start, m); std::thread::id first_id = first.get_id(); report_thread_start_(first, first_id); first.join(); report_thread_finish_(first, first_id); print_array(arr, start, m); //Start the second thread which will deal with 2nd half of given array //wait for second thread to finish before moving on std::thread second(&MergeSort::sort, this, arr, m + 1, end); std::thread::id second_id = second.get_id(); report_thread_start_(second, second_id); second.join(); report_thread_finish_(second, second_id); print_array(arr, m + 1, end); //Merge both segments into one. The end result will //be on the same location as arr merge(arr, start, m, m + 1, end); } //Merge two segments into arr void merge( Type *arr, int start_l, int end_l, int start_r, int end_r) { //left segment right segment //[start_l ... end_l][start_r ... end_r] //Represents current index on arr int i = start_l; //Represent current index on the left //segment (i_l) and right segment (r_l) int i_l = 0; int i_r = 0; //Left and right segment sizes int size_l = end_l - start_l + 1; int size_r = end_r - start_r + 1; //Copy the contents of the left and right segments //into arr_l and arr_r respectively int arr_l[size_l] = {0}; int arr_r[size_r] = {0}; memcpy(arr_l, &arr[start_l], size_l * sizeof(Type)); memcpy(arr_r, &arr[start_r], size_r * sizeof(Type)); while (i_l < size_l && i_r < size_r) { //If current element on the left array //is bigger than the current element on //the right one, copy it on arr and increment i_l if (arr_l[i_l] <= arr_r[i_r]) arr[i] = arr_l[i_l++]; //Otherwise, do the same but with arr_r and i_r else arr[i] = arr_r[i_r++]; //Increment i i++; } //Make sure there are no data left to be added while (i_l < size_l) arr[i++] = arr_l[i_l++]; while (i_r < size_r) arr[i++] = arr_r[i_r++]; } //print contents of an array between indeces start and end void print_array(Type *arr, int start, int end) { //Iterate between indeces start and end std::ostringstream ss; for (int i = start; i <= end; i++) { ss << arr[i] << ", "; } ss << "\n"; this->report(ss.str()); } void report(const std::string msg) { if (this->report_callback == nullptr) return; this->report_callback(msg); } }; #endif
29.005988
96
0.568538
ItsKarlito
64699087791dd1465eeccdb7a35c098fab238824
9,233
cpp
C++
src/QtPhonemes/Phonemes/nVoiceFeature.cpp
Vladimir-Lin/QtPhonemes
1c1b4f4aa99bbadab5ca25dce1fc64c8ee70202d
[ "MIT" ]
null
null
null
src/QtPhonemes/Phonemes/nVoiceFeature.cpp
Vladimir-Lin/QtPhonemes
1c1b4f4aa99bbadab5ca25dce1fc64c8ee70202d
[ "MIT" ]
null
null
null
src/QtPhonemes/Phonemes/nVoiceFeature.cpp
Vladimir-Lin/QtPhonemes
1c1b4f4aa99bbadab5ca25dce1fc64c8ee70202d
[ "MIT" ]
null
null
null
#include <qtphonemes.h> enum { V_NAME = 1 , V_LANGUAGE , V_GENDER , V_TRANSLATOR , V_PHONEMES , V_DICTIONARY , V_FORMANT , V_PITCH , V_ECHO , V_FLUTTER , V_ROUGHNESS , V_CLARITY , V_TONE , V_VOICING , V_BREATH , V_BREATHW , V_WORDGAP , V_INTONATION , V_TUNES , V_STRESSLENGTH , V_STRESSAMP , V_STRESSADD , V_DICTRULES , V_STRESSRULE , V_STRESSOPT , V_CHARSET , V_NUMBERS , V_OPTION , V_MBROLA , V_KLATT , V_FAST , V_SPEED , V_DICTMIN , V_ALPHABET2 , V_REPLACE , V_CONSONANTS } ; N::VoiceFeature:: VoiceFeature (void) : Name ("" ) , Appear ("" ) , Language ("" ) , Priority (0 ) , Gender (1 ) , Age (20 ) , Variant (0 ) , XX1 (0 ) , Score (0 ) , Spare (NULL) { } N::VoiceFeature::~VoiceFeature (void) { } QString N::VoiceFeature::Strip(QString Line) { if (Line.length()<=0) return "" ; int length = Line.toUtf8().size() ; char * p = new char[length+1] ; memset(p,0,length+1) ; p <= Line ; ////////////////////////////////////////////////////// if (p[0]=='#') { delete [] p ; return "" ; } ; ////////////////////////////////////////////////////// length = strlen(p) ; while ( (--length > 0) && isspace ( p [ length ] ) ) { p[length] = 0 ; } ; ////////////////////////////////////////////////////// char * cm = NULL ; if ( ( cm = strstr(p,"//")) != NULL) *cm = 0 ; QString X(p) ; delete [] p ; return X ; } bool N::VoiceFeature::Parse(int control) { if (Data.size()<=0) return false ; QString S = QString::fromUtf8(Data) ; QStringList L = S.split('\n') ; bool T = ( ( control & 2 ) == 2 ) ; L = File::PurifyLines(L) ; foreach (S,L) { S = Strip(S) ; if (S.length()>0) Assign ( S , T ) ; } ; return true ; } bool N::VoiceFeature::Assign(QString Line,bool toneOnly) { QStringList P = Line.split(' ') ; if (P.count()<1) return false ; int key ; key = Acoustics::Lookup(Speak::KeywordTable,P[0]) ; if (key<=0) return false ; /////////////////////////////////////////////////////////////////////// switch ( key ) { case V_NAME : setName ( Line , toneOnly ) ; break ; case V_LANGUAGE : setLanguage ( Line ) ; break ; case V_GENDER : setGender ( Line ) ; break ; case V_TRANSLATOR : setTranslator ( Line ) ; break ; case V_PHONEMES : setPhoneme ( Line ) ; break ; case V_DICTIONARY : setDictionary ( Line ) ; break ; case V_FORMANT : break ; case V_PITCH : break ; case V_ECHO : break ; case V_FLUTTER : break ; case V_ROUGHNESS : break ; case V_CLARITY : break ; case V_TONE : break ; case V_VOICING : break ; case V_BREATH : break ; case V_BREATHW : break ; case V_WORDGAP : break ; case V_INTONATION : break ; case V_TUNES : break ; case V_STRESSLENGTH : break ; case V_STRESSAMP : break ; case V_STRESSADD : break ; case V_DICTRULES : break ; case V_STRESSRULE : break ; case V_STRESSOPT : break ; case V_CHARSET : break ; case V_NUMBERS : break ; case V_OPTION : break ; case V_MBROLA : break ; case V_KLATT : break ; case V_FAST : break ; case V_SPEED : break ; case V_DICTMIN : break ; case V_ALPHABET2 : break ; case V_REPLACE : break ; case V_CONSONANTS : break ; default : break ; } ; return true ; } void N::VoiceFeature::setName(QString Line,bool toneOnly) { QString N = Line.simplified() ; QStringList L = N .split(' ') ; if (toneOnly ) return ; if (L.count()<2) return ; Name = L[1] ; } void N::VoiceFeature::setLanguage(QString Line) { QString N = Line.simplified() ; QStringList L = N .split(' ') ; if (L.count()<2) return ; if (Language.length()<=0) { Language = L[1] ; Phoneme = L[1] ; Translator = L[1] ; Dictionary = L[1] ; } ; if (!Languages.contains(L[1])) { Languages << L[1] ; } ; if (L.count()<3) return ; Priority = L[2].toInt() ; } void N::VoiceFeature::setTranslator(QString Line) { QString N = Line.simplified() ; QStringList L = N .split(' ') ; if (L.count()<2) return ; Translator = L[1] ; } void N::VoiceFeature::setPhoneme(QString Line) { QString N = Line.simplified() ; QStringList L = N .split(' ') ; if (L.count()<2) return ; Phoneme = L[1] ; } void N::VoiceFeature::setDictionary(QString Line) { QString N = Line.simplified() ; QStringList L = N .split(' ') ; if (L.count()<2) return ; Dictionary = L[1] ; } void N::VoiceFeature::setGender(QString Line) { QString N = Line.simplified() ; QStringList L = N .split(' ') ; if (L.count()<3) return ; Gender = Acoustics::Lookup(Speak::MnemonicGender,L[1]) ; Age = L[2].toInt() ; } bool N::VoiceFeature::is(QString name) { return ( Name.toLower() == name.toLower() ) ; } QStringList N::VoiceFeature::PossiblePhonemes (void) { QStringList phonemes ; QString S ; if (Phoneme.length()>0) { phonemes << Phoneme ; } ; foreach (S,Languages) { if (!phonemes.contains(S)) { phonemes << S ; } ; } ; return phonemes ; } QStringList N::VoiceFeature::PossibleDictionary (void) { QStringList dictionary ; QString S ; if (Dictionary.length()>0) { dictionary << Phoneme ; } ; foreach (S,Languages) { if (!dictionary.contains(S)) { dictionary << S ; } ; } ; return dictionary ; }
38.152893
78
0.326654
Vladimir-Lin
646bfbef46c795868be2925c38363bf8a1d8eb6d
12,440
cpp
C++
Source/Components/ttn-esp32-dev/src/hal/hal_esp32.cpp
ContextQuickie/TTGO-T-Beam
0428cd2b12914f3c59da58e113c08b7a19d72f6c
[ "Apache-2.0" ]
6
2020-01-12T01:15:22.000Z
2020-09-16T11:11:49.000Z
Source/Components/ttn-esp32-dev/src/hal/hal_esp32.cpp
ContextQuickie/TTGO-T-Beam
0428cd2b12914f3c59da58e113c08b7a19d72f6c
[ "Apache-2.0" ]
null
null
null
Source/Components/ttn-esp32-dev/src/hal/hal_esp32.cpp
ContextQuickie/TTGO-T-Beam
0428cd2b12914f3c59da58e113c08b7a19d72f6c
[ "Apache-2.0" ]
2
2020-01-12T01:15:26.000Z
2020-06-04T22:26:54.000Z
/******************************************************************************* * * ttn-esp32 - The Things Network device library for ESP-IDF / SX127x * * Copyright (c) 2018-2019 Manuel Bleichenbacher * * Licensed under MIT License * https://opensource.org/licenses/MIT * * Hardware abstraction layer to run LMIC on a ESP32 using ESP-IDF. *******************************************************************************/ #include "../lmic/lmic.h" #include "../hal/hal_esp32.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "driver/gpio.h" #include "driver/spi_master.h" #include "driver/timer.h" #include "esp_log.h" #define LMIC_UNUSED_PIN 0xff #define NOTIFY_BIT_DIO 1 #define NOTIFY_BIT_TIMER 2 #define NOTIFY_BIT_WAKEUP 4 static const char* const TAG = "ttn_hal"; HAL_ESP32 ttn_hal; TaskHandle_t HAL_ESP32::lmicTask = nullptr; uint32_t HAL_ESP32::dioInterruptTime = 0; uint8_t HAL_ESP32::dioNum = 0; // ----------------------------------------------------------------------------- // Constructor HAL_ESP32::HAL_ESP32() : rssiCal(10), nextAlarm(0) { } // ----------------------------------------------------------------------------- // I/O void HAL_ESP32::configurePins(spi_host_device_t spi_host, uint8_t nss, uint8_t rxtx, uint8_t rst, uint8_t dio0, uint8_t dio1) { spiHost = spi_host; pinNSS = (gpio_num_t)nss; pinRxTx = (gpio_num_t)rxtx; pinRst = (gpio_num_t)rst; pinDIO0 = (gpio_num_t)dio0; pinDIO1 = (gpio_num_t)dio1; // Until the background process has been started, use the current task // for supporting calls like `hal_waitUntil()`. lmicTask = xTaskGetCurrentTaskHandle(); } void IRAM_ATTR HAL_ESP32::dioIrqHandler(void *arg) { dioInterruptTime = hal_ticks(); dioNum = (u1_t)(long)arg; BaseType_t higherPrioTaskWoken = pdFALSE; xTaskNotifyFromISR(lmicTask, NOTIFY_BIT_DIO, eSetBits, &higherPrioTaskWoken); if (higherPrioTaskWoken) portYIELD_FROM_ISR(); } void HAL_ESP32::ioInit() { // pinNSS and pinDIO0 and pinDIO1 are required ASSERT(pinNSS != LMIC_UNUSED_PIN); ASSERT(pinDIO0 != LMIC_UNUSED_PIN); ASSERT(pinDIO1 != LMIC_UNUSED_PIN); gpio_pad_select_gpio(pinNSS); gpio_set_level(pinNSS, 0); gpio_set_direction(pinNSS, GPIO_MODE_OUTPUT); if (pinRxTx != LMIC_UNUSED_PIN) { gpio_pad_select_gpio(pinRxTx); gpio_set_level(pinRxTx, 0); gpio_set_direction(pinRxTx, GPIO_MODE_OUTPUT); } if (pinRst != LMIC_UNUSED_PIN) { gpio_pad_select_gpio(pinRst); gpio_set_level(pinRst, 0); gpio_set_direction(pinRst, GPIO_MODE_OUTPUT); } // DIO pins with interrupt handlers gpio_pad_select_gpio(pinDIO0); gpio_set_direction(pinDIO0, GPIO_MODE_INPUT); gpio_set_intr_type(pinDIO0, GPIO_INTR_POSEDGE); gpio_pad_select_gpio(pinDIO1); gpio_set_direction(pinDIO1, GPIO_MODE_INPUT); gpio_set_intr_type(pinDIO1, GPIO_INTR_POSEDGE); ESP_LOGI(TAG, "IO initialized"); } void hal_pin_rxtx(u1_t val) { if (ttn_hal.pinRxTx == LMIC_UNUSED_PIN) return; gpio_set_level(ttn_hal.pinRxTx, val); } void hal_pin_rst(u1_t val) { if (ttn_hal.pinRst == LMIC_UNUSED_PIN) return; if (val == 0 || val == 1) { // drive pin gpio_set_level(ttn_hal.pinRst, val); gpio_set_direction(ttn_hal.pinRst, GPIO_MODE_OUTPUT); } else { // keep pin floating gpio_set_level(ttn_hal.pinRst, val); gpio_set_direction(ttn_hal.pinRst, GPIO_MODE_INPUT); } } s1_t hal_getRssiCal (void) { return ttn_hal.rssiCal; } ostime_t hal_setModuleActive (bit_t val) { return 0; } bit_t hal_queryUsingTcxo(void) { return false; } uint8_t hal_getTxPowerPolicy(u1_t inputPolicy, s1_t requestedPower, u4_t frequency) { return LMICHAL_radio_tx_power_policy_paboost; } // ----------------------------------------------------------------------------- // SPI void HAL_ESP32::spiInit() { // init device spi_device_interface_config_t spiConfig; memset(&spiConfig, 0, sizeof(spiConfig)); spiConfig.mode = 1; spiConfig.clock_speed_hz = CONFIG_TTN_SPI_FREQ; spiConfig.command_bits = 0; spiConfig.address_bits = 8; spiConfig.spics_io_num = pinNSS; spiConfig.queue_size = 1; spiConfig.cs_ena_posttrans = 2; esp_err_t ret = spi_bus_add_device(spiHost, &spiConfig, &spiHandle); ESP_ERROR_CHECK(ret); ESP_LOGI(TAG, "SPI initialized"); } void hal_spi_write(u1_t cmd, const u1_t *buf, size_t len) { ttn_hal.spiWrite(cmd, buf, len); } void HAL_ESP32::spiWrite(uint8_t cmd, const uint8_t *buf, size_t len) { memset(&spiTransaction, 0, sizeof(spiTransaction)); spiTransaction.addr = cmd; spiTransaction.length = 8 * len; spiTransaction.tx_buffer = buf; esp_err_t err = spi_device_transmit(spiHandle, &spiTransaction); ESP_ERROR_CHECK(err); } void hal_spi_read(u1_t cmd, u1_t *buf, size_t len) { ttn_hal.spiRead(cmd, buf, len); } void HAL_ESP32::spiRead(uint8_t cmd, uint8_t *buf, size_t len) { memset(buf, 0, len); memset(&spiTransaction, 0, sizeof(spiTransaction)); spiTransaction.addr = cmd; spiTransaction.length = 8 * len; spiTransaction.rxlength = 8 * len; spiTransaction.tx_buffer = buf; spiTransaction.rx_buffer = buf; esp_err_t err = spi_device_transmit(spiHandle, &spiTransaction); ESP_ERROR_CHECK(err); } // ----------------------------------------------------------------------------- // TIME /* * LIMIC uses a 32 bit time system (ostime_t) counting ticks. In this * implementation each tick is 16µs. It will wrap arounnd every 19 hours. * * The ESP32 has a 64 bit timer counting microseconds. It will wrap around * every 584,000 years. So we don't need to bother. * * Based on this timer, future callbacks can be scheduled. This is used to * schedule the next LMIC job. */ // Convert LMIC tick time (ostime_t) to ESP absolute time. // `osTime` is assumed to be somewhere between one hour in the past and // 18 hours into the future. int64_t HAL_ESP32::osTimeToEspTime(int64_t espNow, uint32_t osTime) { int64_t espTime; uint32_t osNow = (uint32_t)(espNow >> 4); // unsigned difference: // 0x00000000 - 0xefffffff: future (0 to about 18 hours) // 0xf0000000 - 0xffffffff: past (about 1 to 0 hours) uint32_t osDiff = osTime - osNow; if (osDiff < 0xf0000000) { espTime = espNow + (((int64_t)osDiff) << 4); } else { // one's complement instead of two's complement: // off by 1 µs and ignored osDiff = ~osDiff; espTime = espNow - (((int64_t)osDiff) << 4); } return espTime; } void HAL_ESP32::timerInit() { esp_timer_create_args_t timerConfig = { .callback = &timerCallback, .arg = nullptr, .dispatch_method = ESP_TIMER_TASK, .name = "lmic_job" }; esp_err_t err = esp_timer_create(&timerConfig, &timer); ESP_ERROR_CHECK(err); ESP_LOGI(TAG, "Timer initialized"); } void HAL_ESP32::setNextAlarm(int64_t time) { nextAlarm = time; } void HAL_ESP32::armTimer(int64_t espNow) { if (nextAlarm == 0) return; int64_t timeout = nextAlarm - esp_timer_get_time(); if (timeout < 0) timeout = 10; esp_timer_start_once(timer, timeout); } void HAL_ESP32::disarmTimer() { esp_timer_stop(timer); } void HAL_ESP32::timerCallback(void *arg) { xTaskNotify(lmicTask, NOTIFY_BIT_TIMER, eSetBits); } // Wait for the next external event. Either: // - scheduled timer due to scheduled job or waiting for a given time // - wake up event from the client code // - I/O interrupt (DIO0 or DIO1 pin) bool HAL_ESP32::wait(WaitKind waitKind) { TickType_t ticksToWait = waitKind == CHECK_IO ? 0 : portMAX_DELAY; while (true) { uint32_t bits = ulTaskNotifyTake(pdTRUE, ticksToWait); if (bits == 0) return false; if ((bits & NOTIFY_BIT_WAKEUP) != 0) { if (waitKind != WAIT_FOR_TIMER) { disarmTimer(); return true; } } else if ((bits & NOTIFY_BIT_TIMER) != 0) { disarmTimer(); setNextAlarm(0); if (waitKind != CHECK_IO) return true; } else // IO interrupt { if (waitKind != WAIT_FOR_TIMER) disarmTimer(); enterCriticalSection(); radio_irq_handler_v2(dioNum, dioInterruptTime); leaveCriticalSection(); if (waitKind != WAIT_FOR_TIMER) return true; } } } // Gets current time in LMIC ticks u4_t hal_ticks() { // LMIC tick unit: 16µs // esp_timer unit: 1µs return (u4_t)(esp_timer_get_time() >> 4); } // Wait until the specified time. // Called if the LMIC code needs to wait for a precise time. // All other events are ignored and will be served later. void hal_waitUntil(u4_t time) { ttn_hal.waitUntil(time); } void HAL_ESP32::waitUntil(uint32_t osTime) { int64_t espNow = esp_timer_get_time(); int64_t espTime = osTimeToEspTime(espNow, osTime); setNextAlarm(espTime); armTimer(espNow); wait(WAIT_FOR_TIMER); } // Called by client code to wake up LMIC to do something, // e.g. send a submitted messages. void HAL_ESP32::wakeUp() { xTaskNotify(lmicTask, NOTIFY_BIT_WAKEUP, eSetBits); } // Check if the specified time has been reached or almost reached. // Otherwise, save it as alarm time. // LMIC calls this function with the scheduled time of the next job // in the queue. If the job is not due yet, LMIC will go to sleep. u1_t hal_checkTimer(uint32_t time) { return ttn_hal.checkTimer(time); } uint8_t HAL_ESP32::checkTimer(u4_t osTime) { int64_t espNow = esp_timer_get_time(); int64_t espTime = osTimeToEspTime(espNow, osTime); int64_t diff = espTime - espNow; if (diff < 100) return 1; // timer has expired or will expire very soon setNextAlarm(espTime); return 0; } // Go to sleep until next event. // Called when LMIC is not busy and not job is due to be executed. void hal_sleep() { ttn_hal.sleep(); } void HAL_ESP32::sleep() { if (wait(CHECK_IO)) return; armTimer(esp_timer_get_time()); wait(WAIT_FOR_ANY_EVENT); } // ----------------------------------------------------------------------------- // IRQ void hal_disableIRQs() { // nothing to do as interrupt handlers post message to queue // and don't access any shared data structures } void hal_enableIRQs() { // nothing to do as interrupt handlers post message to queue // and don't access any shared data structures } // ----------------------------------------------------------------------------- // Synchronization between application code and background task void HAL_ESP32::initCriticalSection() { mutex = xSemaphoreCreateRecursiveMutex(); } void HAL_ESP32::enterCriticalSection() { xSemaphoreTakeRecursive(mutex, portMAX_DELAY); } void HAL_ESP32::leaveCriticalSection() { xSemaphoreGiveRecursive(mutex); } // ----------------------------------------------------------------------------- void HAL_ESP32::lmicBackgroundTask(void* pvParameter) { os_runloop(); } void hal_init_ex(const void *pContext) { ttn_hal.init(); } void HAL_ESP32::init() { // configure radio I/O and interrupt handler ioInit(); // configure radio SPI spiInit(); // configure timer and alarm callback timerInit(); } void HAL_ESP32::startLMICTask() { xTaskCreate(lmicBackgroundTask, "ttn_lmic", 1024 * 4, nullptr, CONFIG_TTN_BG_TASK_PRIO, &lmicTask); // enable interrupts gpio_isr_handler_add(pinDIO0, dioIrqHandler, (void *)0); gpio_isr_handler_add(pinDIO1, dioIrqHandler, (void *)1); } // ----------------------------------------------------------------------------- // Fatal failure static hal_failure_handler_t* custom_hal_failure_handler = nullptr; void hal_set_failure_handler(const hal_failure_handler_t* const handler) { custom_hal_failure_handler = handler; } void hal_failed(const char *file, u2_t line) { if (custom_hal_failure_handler != nullptr) (*custom_hal_failure_handler)(file, line); ESP_LOGE(TAG, "LMIC failed and stopped: %s:%d", file, line); // go to sleep forever while (true) { vTaskDelay(portMAX_DELAY); } }
25.336049
125
0.634405
ContextQuickie
646d04406fc159189be354eb08f5239cef0d8e9a
919
cpp
C++
CodeForces/747/Servers.cpp
seeva92/Competitive-Programming
69061c5409bb806148616fe7d86543e94bf76edd
[ "Apache-2.0" ]
null
null
null
CodeForces/747/Servers.cpp
seeva92/Competitive-Programming
69061c5409bb806148616fe7d86543e94bf76edd
[ "Apache-2.0" ]
null
null
null
CodeForces/747/Servers.cpp
seeva92/Competitive-Programming
69061c5409bb806148616fe7d86543e94bf76edd
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> typedef long long ll; const int mod = 1e9 + 7; const int MAX = 1e5 + 7; using namespace std; typedef vector<int> vi; int server[107]; class Servers { int n, q, t, k, d; public: void solve() { memset(server, 0, sizeof server); cin >> n >> q; for (int i = 0; i < q; i++) { cin >> t >> k >> d; int cnt = 0; for (int j = 1; j <= n && cnt < k; j++) { if (server[j] < t) cnt++; } if (cnt == k) { int sum = 0; for (int j = 1; j <= n && cnt > 0; j++) { if (server[j] < t) { server[j] = t + d - 1; cnt--; sum += j; } } cout << sum << '\n'; } else { cout << -1 << '\n'; } } } }; int main() { #ifndef ONLINE_JUDGE freopen("/Users/seeva92/Workspace/Contests/1.txt", "r", stdin); freopen("/Users/seeva92/Workspace/Contests/2.txt", "w", stdout); #endif ios::sync_with_stdio(false); cin.tie(0); Servers s; s.solve(); }
19.553191
65
0.508161
seeva92
646d2e1498ddee8460f419b5cd6cd15be5a62592
2,461
cpp
C++
Problem Solving Paradigm/Greedy/Classical, Usually Easier/10037.cpp
joe-stifler/uHunt
02465ea9868403691e4f0aaa6ddde730afa11f47
[ "MIT" ]
3
2019-05-22T00:36:23.000Z
2021-03-22T12:23:18.000Z
Problem Solving Paradigm/Greedy/Classical, Usually Easier/10037.cpp
joe-stifler/uHunt
02465ea9868403691e4f0aaa6ddde730afa11f47
[ "MIT" ]
null
null
null
Problem Solving Paradigm/Greedy/Classical, Usually Easier/10037.cpp
joe-stifler/uHunt
02465ea9868403691e4f0aaa6ddde730afa11f47
[ "MIT" ]
null
null
null
/*------------------------------------------------*/ // Uva Problem No: 10037 // Problem Name: Bridge // Type: Classical, Usually Easier (Greedy) // Autor: Joe Stifler // Data: 2018-06-10 02:10:56 // Runtime: 0.000s // Universidade: Unicamp /*------------------------------------------------*/ #include <bits/stdc++.h> using namespace std; int main() { int t; scanf("%d", &t); int caso = 0; while(t--) { int n; scanf("%d", &n); vector<int> vals; while(n--) { int v; scanf("%d", &v); vals.push_back(v); } sort(vals.begin(), vals.end()); int i; int cont = 0; int total = 0; int count = 0; vector<int> res; int a, b; int A = vals[0], B = vals[1]; for (i = vals.size() - 1; i > 2; i -= 2) { a = vals[i]; b = vals[i-1]; int t1 = a + b + 2 * A; int t2 = a + A + 2 * B; if (t1 < t2) { total += t1; res.push_back(A); res.push_back(b); res.push_back(A); res.push_back(A); res.push_back(a); res.push_back(A); } else { total += t2; res.push_back(A); res.push_back(B); res.push_back(A); res.push_back(b); res.push_back(a); res.push_back(B); } } if (caso != 0) printf("\n"); if (vals.size() == 1) printf("%d\n%d\n", vals[0], vals[0]); else { if (vals.size() % 2 == 0) { total += vals[1]; res.push_back(vals[0]); res.push_back(vals[1]); } else { total += vals[2] + vals[0] + vals[1]; res.push_back(vals[0]); res.push_back(vals[1]); res.push_back(vals[0]); res.push_back(vals[0]); res.push_back(vals[2]); } printf("%d\n", total); for (int i = 0; i < res.size(); i++) { if (i % 3 == 2) printf("\n"); else if (i % 3 == 1) printf(" "); printf("%d", res[i]); if (i % 3 == 2) printf("\n"); } printf("\n"); } caso++; } return 0; }
23.663462
53
0.354328
joe-stifler
646d6ac6da554b57f9fbf52f495fd49a166fc805
2,053
cpp
C++
user/tests/unit/tools/string.cpp
zsoltmazlo/indoor-controller2
5fde9f40b30d087af03f6cccdb97821719941955
[ "MIT" ]
1
2019-02-24T07:13:51.000Z
2019-02-24T07:13:51.000Z
user/tests/unit/tools/string.cpp
zsoltmazlo/indoor-controller2
5fde9f40b30d087af03f6cccdb97821719941955
[ "MIT" ]
1
2018-05-29T19:27:53.000Z
2018-05-29T19:27:53.000Z
user/tests/unit/tools/string.cpp
zsoltmazlo/indoor-controller2
5fde9f40b30d087af03f6cccdb97821719941955
[ "MIT" ]
null
null
null
#include "string.h" #include "catch.h" #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/trim_all.hpp> #include <boost/algorithm/hex.hpp> // test::RegExpMatcher test::RegExpMatcher::RegExpMatcher(const std::string &expr) { try { r_.assign(expr); } catch (const boost::regex_error&) { CATCH_WARN("test::RegExpMatcher: Invalid expression: " << expr); } } test::RegExpMatcher::RegExpMatcher(const std::string &str, const std::string &expr) : RegExpMatcher(expr) { if (!match(str)) { r_ = boost::regex(); // Invalidate matcher } } bool test::RegExpMatcher::match(const std::string &str) { try { if (r_.empty()) { return false; } boost::smatch m; if (!boost::regex_match(str, m, r_)) { return false; } s_ = str; m_ = m; return true; } catch (boost::regex_error&) { return false; } } std::string test::RegExpMatcher::at(size_t i) const { i += 1; // Skip string matching whole expression if (i >= m_.size()) { return std::string(); } return m_.str(i); } size_t test::RegExpMatcher::size() const { if (m_.empty()) { return 0; } return m_.size() - 1; } // test:: std::string test::trim(const std::string &str) { return boost::algorithm::trim_all_copy(str, std::locale::classic()); } std::string test::toLowerCase(const std::string &str) { return boost::algorithm::to_lower_copy(str, std::locale::classic()); } std::string test::toUpperCase(const std::string &str) { return boost::algorithm::to_upper_copy(str, std::locale::classic()); } std::string test::toHex(const std::string &str) { std::string s = boost::algorithm::hex(str); boost::algorithm::to_lower(s, std::locale::classic()); return s; } std::string test::fromHex(const std::string &str) { try { return boost::algorithm::unhex(str); } catch (const boost::algorithm::hex_decode_error&) { return std::string(); } }
24.73494
85
0.604968
zsoltmazlo
647a97d00c436bf7284b0feb179637e7a10c7714
8,111
cpp
C++
src/physics/bumper.cpp
ArneDJ/terranova
533e9e5687d464153418f73a1d811f57e7c572b9
[ "CC0-1.0" ]
null
null
null
src/physics/bumper.cpp
ArneDJ/terranova
533e9e5687d464153418f73a1d811f57e7c572b9
[ "CC0-1.0" ]
null
null
null
src/physics/bumper.cpp
ArneDJ/terranova
533e9e5687d464153418f73a1d811f57e7c572b9
[ "CC0-1.0" ]
null
null
null
#include <iostream> #include <memory> #include <vector> #include <glm/glm.hpp> #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include <glm/mat4x4.hpp> #include <glm/gtc/type_ptr.hpp> #include "../geometry/transform.h" #include "../geometry/geometry.h" #include "physical.h" #include "bumper.h" namespace fysx { class ClosestNotMe : public btCollisionWorld::ClosestRayResultCallback { public: ClosestNotMe(btCollisionObject *body) : btCollisionWorld::ClosestRayResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0)) { me = body; } virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult &rayResult, bool normalInWorldSpace) { if (rayResult.m_collisionObject == me) { return 1.0; } return ClosestRayResultCallback::addSingleResult(rayResult, normalInWorldSpace); } protected: btCollisionObject *me; }; class BumperConvexCallback : public btCollisionWorld::ClosestConvexResultCallback { public: BumperConvexCallback(btCollisionObject* me, const btVector3& up, btScalar minSlopeDot) : btCollisionWorld::ClosestConvexResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0)), m_me(me), m_up(up), m_minSlopeDot(minSlopeDot) { } virtual btScalar addSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace) { if (convexResult.m_hitCollisionObject == m_me) return btScalar(1.0); if (!convexResult.m_hitCollisionObject->hasContactResponse()) return btScalar(1.0); btVector3 hitNormalWorld; if (normalInWorldSpace) { hitNormalWorld = convexResult.m_hitNormalLocal; } else { ///need to transform normal into worldspace hitNormalWorld = convexResult.m_hitCollisionObject->getWorldTransform().getBasis() * convexResult.m_hitNormalLocal; } /* btScalar dotUp = m_up.dot(hitNormalWorld); if (dotUp < m_minSlopeDot) { return btScalar(1.0); } */ return ClosestConvexResultCallback::addSingleResult(convexResult, normalInWorldSpace); } protected: btCollisionObject *m_me; const btVector3 m_up = btVector3(0, 1, 0); btScalar m_minSlopeDot; }; struct Trace { float fraction = 1.f; // time completed, 1.0 = didn't hit anything glm::vec3 endpos; // final position glm::vec3 normal; // surface normal at impact }; static const float V_GRAVITY = 9.81F; static const float TERMINAL_VELOCITY = 55.F; Trace trace_movement(btPairCachingGhostObject *object, const btConvexShape *shape, const btDynamicsWorld *world, const glm::vec3 &origin, const glm::vec3 &destination) { Trace trace = {}; trace.fraction = 1.f; trace.endpos = origin; glm::vec3 sweep_direction = origin - destination; btTransform start = object->getWorldTransform(); btTransform end = start; end.setOrigin(vec3_to_bt(destination)); BumperConvexCallback callback(object, vec3_to_bt(sweep_direction), 0.45); callback.m_collisionFilterGroup = object->getBroadphaseHandle()->m_collisionFilterGroup; callback.m_collisionFilterMask = object->getBroadphaseHandle()->m_collisionFilterMask; object->convexSweepTest(shape, start, end, callback, world->getDispatchInfo().m_allowedCcdPenetration); glm::vec3 direction = destination - origin; if (callback.hasHit() && object->hasContactResponse()) { glm::vec3 hitpoint = bt_to_vec3(callback.m_hitPointWorld); trace.fraction = callback.m_closestHitFraction; trace.normal = bt_to_vec3(callback.m_hitNormalWorld); trace.endpos = origin + (trace.fraction * direction); } return trace; } glm::vec3 hit_to_velocity(const glm::vec3 &velocity, const glm::vec3 &normal) { glm::vec3 velocity_normalized = glm::normalize(velocity); glm::vec3 undesired_motion = normal * glm::dot(velocity_normalized, normal); glm::vec3 desired_motion = velocity_normalized - undesired_motion; return desired_motion * glm::length(velocity); } Bumper::Bumper(const glm::vec3 &origin, float radius, float length) { float height = length - (2.f * radius); if (height < 0.f) { height = 0.f; } shape = std::make_unique<btCapsuleShape>(radius, height); btTransform t; t.setIdentity(); t.setOrigin(vec3_to_bt(origin)); ghost_object = std::make_unique<btPairCachingGhostObject>(); ghost_object->setWorldTransform(t); ghost_object->setCollisionShape(shape.get()); ghost_object->setCollisionFlags(btCollisionObject::CF_CHARACTER_OBJECT); transform = std::make_unique<geom::Transform>(); transform->position = origin; } void Bumper::update(const btDynamicsWorld *world, float delta) { const glm::vec3 start_position = bt_to_vec3(ghost_object->getWorldTransform().getOrigin()); glm::vec3 displacement = speed * delta * walk_direction; collide_and_slide(world, displacement); apply_gravity(world, delta); const glm::vec3 end_position = bt_to_vec3(ghost_object->getWorldTransform().getOrigin()); update_fallen_distance(start_position, end_position); } void Bumper::sync_transform() { btTransform t = ghost_object->getWorldTransform(); transform->position = fysx::bt_to_vec3(t.getOrigin()); } void Bumper::teleport(const glm::vec3 &position) { btTransform t; t.setIdentity (); t.setOrigin(fysx::vec3_to_bt(position)); ghost_object->setWorldTransform(t); } void Bumper::apply_gravity(const btDynamicsWorld *world, float delta) { glm::vec3 gravity = { 0.f, -V_GRAVITY, 0.f }; if (!on_ground) { gravity.y = -sqrtf(6.f * V_GRAVITY * fallen_distance); if (fabs(gravity.y) > TERMINAL_VELOCITY) { gravity.y = -TERMINAL_VELOCITY; } // in case fallen distance was 0 (start of fall) if (!gravity.y) { gravity.y = -V_GRAVITY; } } gravity.y *= delta; // find closest ground collision const glm::vec3 origin = bt_to_vec3(ghost_object->getWorldTransform().getOrigin()); glm::vec3 destination = origin + gravity; Trace trace = trace_movement(ghost_object.get(), shape.get(), world, origin, destination); on_ground = (trace.fraction < 1.f); if (on_ground) { // stick on ground if not in air glm::vec3 moved = glm::normalize(gravity) * (trace.fraction * glm::length(gravity - 0.1f)); destination = origin + moved; on_ground = true; } teleport(destination); } void Bumper::apply_velocity(const glm::vec3 &velocity) { glm::vec3 current_position = bt_to_vec3(ghost_object->getWorldTransform().getOrigin()); teleport(current_position + velocity); } void Bumper::collide_and_slide(const btDynamicsWorld *world, const glm::vec3 &displacement) { // no motion early exit if (glm::length(displacement) < 1e-6f) { return; } static const float CLIP_OFFSET = 0.01F; const glm::vec3 origin = bt_to_vec3(ghost_object->getWorldTransform().getOrigin()); glm::vec3 position = origin; glm::vec3 start = origin; glm::vec3 end = origin + displacement; glm::vec3 motion = displacement; for (int i = 0; i < 4; i++) { if (glm::length(motion) < 1e-6f) { return; } // find collision with convex sweep Trace trace = trace_movement(ghost_object.get(), shape.get(), world, start, end); // hit nothing early exit if (trace.fraction >= 1.f) { position = end; break; } // we must have hit something // find the position right before the collision occurs glm::vec3 moved = glm::normalize(motion) * (trace.fraction * glm::length(motion) - CLIP_OFFSET); start += moved; // update last visited position position = start; // remaining motion glm::vec3 remainder = end - start; // slide remaining motion along hit normal glm::vec3 direction = glm::normalize(remainder); float d = glm::dot(direction, trace.normal); glm::vec3 slide = direction - (d * trace.normal); motion = glm::length(remainder) * slide; end = start + motion; } motion = position - origin; // to avoid occilations somewhat lerp with original position if (glm::dot(glm::normalize(motion), glm::normalize(displacement)) <= 0.f) { position = glm::mix(origin, position, 0.25f); } teleport(position); } void Bumper::update_fallen_distance(const glm::vec3 &start, const glm::vec3 &end) { if (on_ground) { fallen_distance = 0.f; } else { fallen_distance += glm::distance(start.y, end.y); } } void Bumper::set_scale(float scale) { shape->setLocalScaling(btVector3(scale, scale, scale)); } };
28.36014
167
0.730983
ArneDJ
647d7f80f6dc2b07d4806f34a1e1eb3b1bd9375c
10,374
cpp
C++
modules/attention_segmentation/src/SVMTrainModel.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
2
2021-02-22T11:36:33.000Z
2021-07-20T11:31:08.000Z
modules/attention_segmentation/src/SVMTrainModel.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
null
null
null
modules/attention_segmentation/src/SVMTrainModel.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
3
2018-10-19T10:39:23.000Z
2021-04-07T13:39:03.000Z
/**************************************************************************** ** ** Copyright (C) 2017 TU Wien, ACIN, Vision 4 Robotics (V4R) group ** Contact: v4r.acin.tuwien.ac.at ** ** This file is part of V4R ** ** V4R is distributed under dual licenses - GPLv3 or closed source. ** ** GNU General Public License Usage ** V4R is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published ** by the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** V4R is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** Please review the following information to ensure the GNU General Public ** License requirements will be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** ** Commercial License Usage ** If GPL is not suitable for your project, you must purchase a commercial ** license to use V4R. Licensees holding valid commercial V4R licenses may ** use this file in accordance with the commercial license agreement ** provided with the Software or, alternatively, in accordance with the ** terms contained in a written agreement between you and TU Wien, ACIN, V4R. ** For licensing terms and conditions please contact office<at>acin.tuwien.ac.at. ** ** ** The copyright holder additionally grants the author(s) of the file the right ** to use, copy, modify, merge, publish, distribute, sublicense, and/or ** sell copies of their contributions without any restrictions. ** ****************************************************************************/ /** * @file SVMTrainModel.cpp * @author Andreas Richtsfeld * @date August 2011 * @version 0.1 * @brief Trains svm. */ #include "v4r/attention_segmentation/SVMTrainModel.h" #define Malloc(type, n) (type *)malloc((n) * sizeof(type)) namespace svm { void SVMTrainModel::print_null(const char *s) { (void)s; } void SVMTrainModel::exit_input_error(int line_num) { fprintf(stderr, "Wrong input format at line %d\n", line_num); exit(1); } char *SVMTrainModel::readline(FILE *input) { int len; if (fgets(line, max_line_len, input) == NULL) return nullptr; while (strrchr(line, '\n') == NULL) { max_line_len *= 2; line = (char *)realloc(line, max_line_len); len = (int)strlen(line); if (fgets(line + len, max_line_len - len, input) == NULL) break; } return line; } SVMTrainModel::SVMTrainModel() { // default values param.svm_type = C_SVC; param.kernel_type = RBF; param.degree = 3; param.gamma = 0; // 1/num_features param.coef0 = 0; param.nu = 0.5; param.cache_size = 100; param.C = 1; param.eps = 1e-3; param.p = 0.1; param.shrinking = 1; param.probability = 0; param.nr_weight = 0; param.weight_label = nullptr; param.weight = nullptr; cross_validation = 0; line = nullptr; void (*print_func)(const char *) = nullptr; // default printing to stdout svm_set_print_string_function(print_func); have_input_file_name = false; have_model_file_name = false; } void SVMTrainModel::setSVMType(int _svm_type) { param.svm_type = _svm_type; } void SVMTrainModel::setKernelType(int _kernel_type) { param.kernel_type = _kernel_type; } void SVMTrainModel::setDegree(int _degree) { param.degree = _degree; } void SVMTrainModel::setGamma(double _gamma) { param.gamma = _gamma; } void SVMTrainModel::setCoef0(double _coef0) { param.coef0 = _coef0; } void SVMTrainModel::setNu(double _nu) { param.nu = _nu; } void SVMTrainModel::setCacheSize(double _cache_size) { param.cache_size = _cache_size; } void SVMTrainModel::setC(double _C) { param.C = _C; } void SVMTrainModel::setEps(double _eps) { param.eps = _eps; } void SVMTrainModel::setP(double _p) { param.p = _p; } void SVMTrainModel::setShrinking(int _shrinking) { param.shrinking = _shrinking; } void SVMTrainModel::setProbability(int _probability) { param.probability = _probability; } void SVMTrainModel::setCrossValidation(int _nr_fold) { cross_validation = 0; if (_nr_fold > 0) { cross_validation = 1; nr_fold = _nr_fold; } } // for class i weight _weight void SVMTrainModel::setWeight(int _i, float _weight) { ++param.nr_weight; param.weight_label = (int *)realloc(param.weight_label, sizeof(int) * param.nr_weight); param.weight = (double *)realloc(param.weight, sizeof(double) * param.nr_weight); param.weight_label[param.nr_weight - 1] = _i; param.weight[param.nr_weight - 1] = _weight; } void SVMTrainModel::setInputFileName(std::string _input_file_name) { have_input_file_name = true; std::strcpy(input_file_name, _input_file_name.c_str()); // input_file_name = _input_file_name.c_str(); } void SVMTrainModel::setModelFileName(std::string _model_file_name) { have_model_file_name = true; std::strcpy(model_file_name, _model_file_name.c_str()); // model_file_name = _model_file_name.c_str(); } void SVMTrainModel::setNoPrint(bool _no_print) { if (_no_print) { void (*print_func)(const char *) = &SVMTrainModel::print_null; svm_set_print_string_function(print_func); } else { void (*print_func)(const char *) = nullptr; // default printing to stdout svm_set_print_string_function(print_func); } } int SVMTrainModel::train(double &RecRate, std::vector<int> &ConfusionTable) { if ((!have_input_file_name) || (!have_model_file_name)) { fprintf(stderr, "ERROR: Set Input and Model files first!\n"); exit(1); } const char *error_msg; readProblem(input_file_name); error_msg = svm_check_parameter(&prob, &param); if (error_msg) { fprintf(stderr, "ERROR: %s\n", error_msg); exit(1); } if (cross_validation) { do_cross_validation(RecRate, ConfusionTable); } else { model = svm_train(&prob, &param); if (svm_save_model(model_file_name, model)) { fprintf(stderr, "can't save model to file %s\n", model_file_name); exit(1); } svm_free_and_destroy_model(&model); } svm_destroy_param(&param); free(prob.y); free(prob.x); free(x_space); free(line); return 0; } void SVMTrainModel::do_cross_validation(double &RecRate, std::vector<int> &ConfusionTable) { int i; int total_correct = 0; double total_error = 0; double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0; double *target = Malloc(double, prob.l); svm_cross_validation(&prob, &param, nr_fold, target); if (param.svm_type == EPSILON_SVR || param.svm_type == NU_SVR) { for (i = 0; i < prob.l; i++) { double y = prob.y[i]; double v = target[i]; total_error += (v - y) * (v - y); sumv += v; sumy += y; sumvv += v * v; sumyy += y * y; sumvy += v * y; } printf("Cross Validation Mean squared error = %g\n", total_error / prob.l); printf("Cross Validation Squared correlation coefficient = %g\n", ((prob.l * sumvy - sumv * sumy) * (prob.l * sumvy - sumv * sumy)) / ((prob.l * sumvv - sumv * sumv) * (prob.l * sumyy - sumy * sumy))); } else { ConfusionTable.at(0) = 0; ConfusionTable.at(1) = 0; ConfusionTable.at(2) = 0; ConfusionTable.at(3) = 0; for (i = 0; i < prob.l; i++) { if (target[i] == prob.y[i]) { ++total_correct; if (target[i] == 0) { ConfusionTable.at(0) += 1; } else { ConfusionTable.at(3) += 1; } } else { if (target[i] == 0) { ConfusionTable.at(2) += 1; } else { ConfusionTable.at(1) += 1; } } } // printf("Cross Validation Accuracy = %g%%\n",100.0*total_correct/prob.l); RecRate = 100.0 * total_correct / prob.l; } free(target); } // read in a problem (in svmlight format) void SVMTrainModel::readProblem(const char *filename) { int elements, max_index, inst_max_index, i, j; FILE *fp = fopen(filename, "r"); char *endptr; char *idx, *val, *label; if (fp == nullptr) { fprintf(stderr, "can't open input file %s\n", filename); exit(1); } prob.l = 0; elements = 0; max_line_len = 1024; line = Malloc(char, max_line_len); while (readline(fp) != nullptr) { char *p = strtok(line, " \t"); // label // features while (1) { p = strtok(nullptr, " \t"); if (p == nullptr || *p == '\n') // check '\n' as ' ' may be after the last feature break; ++elements; } ++elements; ++prob.l; } rewind(fp); prob.y = Malloc(double, prob.l); prob.x = Malloc(struct svm_node *, prob.l); x_space = Malloc(struct svm_node, elements); max_index = 0; j = 0; for (i = 0; i < prob.l; i++) { inst_max_index = -1; // strtol gives 0 if wrong format, and precomputed kernel has <index> start from 0 readline(fp); prob.x[i] = &x_space[j]; label = strtok(line, " \t\n"); if (label == nullptr) // empty line exit_input_error(i + 1); prob.y[i] = strtod(label, &endptr); if (endptr == label || *endptr != '\0') exit_input_error(i + 1); while (true) { idx = strtok(nullptr, ":"); val = strtok(nullptr, " \t"); if (val == nullptr) break; errno = 0; x_space[j].index = (int)strtol(idx, &endptr, 10); if (endptr == idx || errno != 0 || *endptr != '\0' || x_space[j].index <= inst_max_index) exit_input_error(i + 1); else inst_max_index = x_space[j].index; errno = 0; x_space[j].value = strtod(val, &endptr); if (endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr))) exit_input_error(i + 1); ++j; } if (inst_max_index > max_index) max_index = inst_max_index; x_space[j++].index = -1; } if (param.gamma == 0 && max_index > 0) param.gamma = 1.0 / max_index; if (param.kernel_type == PRECOMPUTED) for (i = 0; i < prob.l; i++) { if (prob.x[i][0].index != 0) { fprintf(stderr, "Wrong input format: first column must be 0:sample_serial_number\n"); exit(1); } if ((int)prob.x[i][0].value <= 0 || (int)prob.x[i][0].value > max_index) { fprintf(stderr, "Wrong input format: sample_serial_number out of range\n"); exit(1); } } fclose(fp); } } // namespace svm
27.737968
108
0.632639
v4r-tuwien
647f6feab95a24cb98315ef067c6de194d0bc65d
1,400
cpp
C++
PocketNN/Main.cpp
jaewoosong/pocketnn
68f95401e8681483f764b063a6b886967d228a7f
[ "MIT" ]
9
2022-02-16T19:15:55.000Z
2022-03-21T10:44:51.000Z
PocketNN/Main.cpp
jaewoosong/pocketnn
68f95401e8681483f764b063a6b886967d228a7f
[ "MIT" ]
null
null
null
PocketNN/Main.cpp
jaewoosong/pocketnn
68f95401e8681483f764b063a6b886967d228a7f
[ "MIT" ]
1
2022-03-09T12:24:25.000Z
2022-03-09T12:24:25.000Z
#include "pktnn_examples.h" int main() { // There are 3 examples // 1) very simple integer BP: example_fc_int_bp_very_simple(); // 2) fc mnist integer DFA: example_fc_int_dfa_mnist(); // 3) fc fashion mnist integer DFA: example_fc_int_dfa_fashion_mnist(); // CAUTION: // MNIST and Fashion-MNIST datasets should be downloaded in advance // and put into ./dataset/ directory with following filenames. // (1) MNIST (http://yann.lecun.com/exdb/mnist/) // Already downloaded in advance because MNIST website allows making copies. // ("Please refrain from accessing these files from automated scripts with high frequency. Make copies!") // ./dataset/mnist/train-labels.idx1-ubyte // ./dataset/mnist/train-images.idx3-ubyte // ./dataset/mnist/t10k-labels.idx1-ubyte // ./dataset/mnist/t10k-images.idx3-ubyte // (2) Fashion-MNIST (https://github.com/zalandoresearch/fashion-mnist) // Already downloaded in advance because Fashion-MNIST uses MIT License which allows distribution. // ./dataset/fashion_mnist/train-labels-idx1-ubyte // ./dataset/fashion_mnist/train-images-idx3-ubyte // ./dataset/fashion_mnist/t10k-labels-idx1-ubyte // ./dataset/fashion_mnist/t10k-images-idx3-ubyte // (Please download the files from the link.) example_fc_int_dfa_mnist(); return 0; }
43.75
110
0.689286
jaewoosong
647fa93ac7caedbb6b8d09ff15b5c2def11e1613
446
cpp
C++
d1eq.cpp
fluier/math
626ab4f0cd92e1c0ac9f7172d80cc202100e3673
[ "MIT" ]
null
null
null
d1eq.cpp
fluier/math
626ab4f0cd92e1c0ac9f7172d80cc202100e3673
[ "MIT" ]
null
null
null
d1eq.cpp
fluier/math
626ab4f0cd92e1c0ac9f7172d80cc202100e3673
[ "MIT" ]
null
null
null
/* * d1eq.cpp * * Created on: Apr 4, 2017 * Author: constantin */ #include "d1eq.h" d1eq::d1eq(float a, float b, float c):_a(a),_b(b),_c(c) { } d1eq::~d1eq() { // TODO Auto-generated destructor stub } bool d1eq::belong(float x, float y) { const float thresh = 0.000001; float aux = _a*x + _b*y - _c; if(-thresh < aux || aux < thresh){ return true; } return false; } float d1eq::fdx(float x) { return (_c - _a * x)/_b; }
14.866667
57
0.589686
fluier
6482ac1f37f2f984af16d4dc08d678ce8b1ae9f2
107
hpp
C++
native/copy.hpp
G07cha/node-libpng
e89f4ef762e255b2c839185341e61af138956b04
[ "MIT" ]
20
2018-03-22T08:37:33.000Z
2021-12-14T13:17:19.000Z
native/copy.hpp
G07cha/node-libpng
e89f4ef762e255b2c839185341e61af138956b04
[ "MIT" ]
43
2018-03-21T09:46:04.000Z
2021-12-14T13:13:54.000Z
native/copy.hpp
G07cha/node-libpng
e89f4ef762e255b2c839185341e61af138956b04
[ "MIT" ]
8
2018-07-05T06:56:47.000Z
2021-01-16T11:25:36.000Z
#ifndef COPY_HPP #define COPY_HPP #include <nan.h> NAN_METHOD(copy); NAN_MODULE_INIT(InitCopy); #endif
9.727273
26
0.757009
G07cha
64842b87ba3bd11e3ac3f897a099165bed6567b5
1,322
hpp
C++
kernel/include/io/io.hpp
Eospp/Eospp
bc231908aaf34dfc2f790a259487253a4151be16
[ "MIT" ]
18
2022-01-21T18:19:37.000Z
2022-03-15T05:26:32.000Z
kernel/include/io/io.hpp
Eospp/Eospp
bc231908aaf34dfc2f790a259487253a4151be16
[ "MIT" ]
null
null
null
kernel/include/io/io.hpp
Eospp/Eospp
bc231908aaf34dfc2f790a259487253a4151be16
[ "MIT" ]
3
2022-01-22T14:24:04.000Z
2022-02-23T10:19:11.000Z
#pragma once #include <type.hpp> namespace eospp::io { inline estd::uint8_t in_byte(estd::uint16_t port) { estd::uint8_t v; asm volatile("inb %[v] %[port]" : [v] "=a"(v) : [port] "dN"(port) : "memory"); return v; } inline void out_byte(estd::uint16_t _port, estd::uint8_t _data) { asm volatile("outb %[data],%[port]" : : [port] "dN"(_port), [data] "a"(_data):); } inline estd::uint16_t in_word(estd::uint16_t port) { estd::uint16_t v; asm volatile("inb %[v] %[port]" : [v] "=a"(v) : [port] "dN"(port) : "memory"); return v; } inline void out_word(estd::uint16_t port, estd::uint16_t data) { asm volatile("outw %[data] %[port]" : : [port] "dN"(port), [data] "a"(data)); } inline estd::uint32_t in_dword(estd::uint16_t port) { estd::uint32_t v; asm volatile("inl %[v] %[port]" : [v] "=a"(v) : [port] "dN"(port) : "memory"); return v; } inline void out_dword(estd::uint16_t port, estd::uint32_t data) { __asm__ __volatile__("outl %[data] %[port]" : : [port] "dN"(port), [data] "a"(data)); } } // namespace eospp::io
26.44
65
0.484115
Eospp
6485801304be1490f9b980ae1ef03f2fe9151097
18,463
cpp
C++
NavimeshExporter/src/interface.cpp
noodle1983/recastnavigation
f4804a183bb3ab3387e78d11696591651b0e6bd8
[ "Zlib" ]
null
null
null
NavimeshExporter/src/interface.cpp
noodle1983/recastnavigation
f4804a183bb3ab3387e78d11696591651b0e6bd8
[ "Zlib" ]
null
null
null
NavimeshExporter/src/interface.cpp
noodle1983/recastnavigation
f4804a183bb3ab3387e78d11696591651b0e6bd8
[ "Zlib" ]
1
2022-02-09T11:50:25.000Z
2022-02-09T11:50:25.000Z
#include "interface.h" #include "MeshParser.hpp" using namespace nd; #include "nd_header.h" namespace nd{ #include "Detour/DetourCommon.h" #include "Detour/DetourNavMesh.h" #include "Detour/DetourNavMeshBuilder.cpp" template<class T> inline T rcMin(T a, T b) { return a < b ? a : b; } inline unsigned int nextPow2(unsigned int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } inline unsigned int ilog2(unsigned int v) { unsigned int r; unsigned int shift; r = (v > 0xffff) << 4; v >>= r; shift = (v > 0xff) << 3; v >>= shift; r |= shift; shift = (v > 0xf) << 2; v >>= shift; r |= shift; shift = (v > 0x3) << 1; v >>= shift; r |= shift; r |= (v >> 1); return r; } } #include <cstring> #include <memory> using namespace std; //[StructLayout(LayoutKind.Sequential)] //class MyClass { // ... //} struct NavimeshTileData{ float* verts; int vertCount; // per vertice/edge data unsigned short* triangles; unsigned short* neis; int triangleIndexCount; // per triangle data short* polyFlags; char* polyAreaTypes; // portal count short portalCount; bool buildBvTree; int tileX; int tileY; int tileLayer; unsigned int userId; float walkableHeight; float walkableRadius; float walkableClimb; float bmin[3]; float bmax[3]; }; const float BvQuantFactor = 1; static int createBVTree(NavimeshTileData* tileData, dtBVNode* nodes, int /*nnodes*/) { // Build tree const int polyCount = tileData->triangleIndexCount/3; BVItem* items = (BVItem*)dtAlloc(sizeof(BVItem)*polyCount, DT_ALLOC_TEMP); float* tbmin = tileData->bmin; for (int i = 0; i < polyCount; i++) { BVItem& it = items[i]; it.i = i; float bmin[3]; float bmax[3]; const unsigned short* p = &tileData->triangles[i*3]; dtVcopy(bmin, &tileData->verts[p[0] * 3]); dtVcopy(bmax, &tileData->verts[p[0] * 3]); for (int j = 1; j < 3; ++j) { dtVmin(bmin, &tileData->verts[p[j] * 3]); dtVmax(bmax, &tileData->verts[p[j] * 3]); } it.bmin[0] = (unsigned short)dtMathFloorf((bmin[0]-tbmin[0])*BvQuantFactor); it.bmin[1] = (unsigned short)dtMathFloorf((bmin[1]-tbmin[1])*BvQuantFactor); it.bmin[2] = (unsigned short)dtMathFloorf((bmin[2]-tbmin[2])*BvQuantFactor); it.bmax[0] = (unsigned short)dtMathCeilf((bmax[0]-tbmin[0])*BvQuantFactor); it.bmax[1] = (unsigned short)dtMathCeilf((bmax[1]-tbmin[1])*BvQuantFactor); it.bmax[2] = (unsigned short)dtMathCeilf((bmax[2]-tbmin[2])*BvQuantFactor); } int curNode = 0; subdivide(items, polyCount, 0, polyCount, curNode, nodes); dtFree(items); return curNode; } bool dumpSoloTileData(NavimeshTileData* tileData, unsigned char** outData, int* outDataSize) { if (tileData->vertCount >= 0xffff) return false; if (!tileData->vertCount || !tileData->verts) return false; if (!tileData->triangleIndexCount || !tileData->triangles) return false; int storedOffMeshConCount = 0; int offMeshConLinkCount = 0; // Off-mesh connectionss are stored as polygons, adjust values. const int polyCount = tileData->triangleIndexCount/3; const int totPolyCount = tileData->triangleIndexCount/3 + storedOffMeshConCount; const int totVertCount = tileData->vertCount + storedOffMeshConCount*2; const int portalCount = tileData->portalCount; //const int edgeCount = tileData->triangleIndexCount; const int maxLinkCount = tileData->triangleIndexCount + tileData->portalCount*2 + offMeshConLinkCount*2; int uniqueDetailVertCount = 0; int detailTriCount = tileData->triangleIndexCount/3; // Calculate data size const int headerSize = dtAlign4(sizeof(dtMeshHeader)); const int vertsSize = dtAlign4(sizeof(float)*3*totVertCount); const int polysSize = dtAlign4(sizeof(dtPoly)*totPolyCount); const int linksSize = dtAlign4(sizeof(dtLink)*maxLinkCount); const int detailMeshesSize = dtAlign4(sizeof(dtPolyDetail)*polyCount); const int detailVertsSize = dtAlign4(sizeof(float)*3*uniqueDetailVertCount); const int detailTrisSize = dtAlign4(sizeof(unsigned char)*4*detailTriCount); const int bvTreeSize = tileData->buildBvTree ? dtAlign4(sizeof(dtBVNode)*polyCount*2) : 0; const int offMeshConsSize = dtAlign4(sizeof(dtOffMeshConnection)*storedOffMeshConCount); const int dataSize = headerSize + vertsSize + polysSize + linksSize + detailMeshesSize + detailVertsSize + detailTrisSize + bvTreeSize + offMeshConsSize; unsigned char* data = (unsigned char*)dtAlloc(sizeof(unsigned char)*dataSize, DT_ALLOC_PERM); if (!data) { return false; } memset(data, 0, dataSize); unsigned char* d = data; dtMeshHeader* header = dtGetThenAdvanceBufferPointer<dtMeshHeader>(d, headerSize); float* navVerts = dtGetThenAdvanceBufferPointer<float>(d, vertsSize); dtPoly* navPolys = dtGetThenAdvanceBufferPointer<dtPoly>(d, polysSize); d += linksSize; // Ignore links; just leave enough space for them. They'll be created on load. dtPolyDetail* navDMeshes = dtGetThenAdvanceBufferPointer<dtPolyDetail>(d, detailMeshesSize); float* navDVerts = dtGetThenAdvanceBufferPointer<float>(d, detailVertsSize); unsigned char* navDTris = dtGetThenAdvanceBufferPointer<unsigned char>(d, detailTrisSize); dtBVNode* navBvtree = dtGetThenAdvanceBufferPointer<dtBVNode>(d, bvTreeSize); dtOffMeshConnection* offMeshCons = dtGetThenAdvanceBufferPointer<dtOffMeshConnection>(d, offMeshConsSize); // Store header header->magic = DT_NAVMESH_MAGIC; header->version = DT_NAVMESH_VERSION; header->x = tileData->tileX; header->y = tileData->tileY; header->layer = tileData->tileLayer; header->userId = tileData->userId; header->polyCount = totPolyCount; header->vertCount = totVertCount; header->maxLinkCount = maxLinkCount; dtVcopy(header->bmin, tileData->bmin); dtVcopy(header->bmax, tileData->bmax); header->detailMeshCount = polyCount; header->detailVertCount = uniqueDetailVertCount; header->detailTriCount = detailTriCount; header->bvQuantFactor = BvQuantFactor; // limited scene max length to 0xffff header->offMeshBase = polyCount; header->walkableHeight = tileData->walkableHeight; header->walkableRadius = tileData->walkableRadius; header->walkableClimb = tileData->walkableClimb; header->offMeshConCount = storedOffMeshConCount; header->bvNodeCount = tileData->buildBvTree ? polyCount*2 : 0; const int offMeshVertsBase = tileData->vertCount; const int offMeshPolyBase = polyCount; // Store vertices // Mesh vertices memcpy(navVerts, tileData->verts, sizeof(tileData->verts[0]) * tileData->vertCount); // Store polygons // Mesh polys for (int i = 0; i < polyCount; ++i) { dtPoly* p = &navPolys[i]; p->vertCount = 3; p->flags = tileData->polyFlags[i]; p->areaAndtype = tileData->polyAreaTypes[i]; for(int j = 0; j < p->vertCount; j++){ p->verts[j] = tileData->triangles[i*3 + j]; p->neis[j] = tileData->neis[i*3 + j]; } } // Store detail meshes and vertices. // The nav polygon vertices are stored as the first vertices on each mesh. // We compress the mesh data by skipping them and using the navmesh coordinates. // Create dummy detail mesh by triangulating polys. int tbase = 0; for (int i = 0; i < polyCount; ++i) { dtPolyDetail& dtl = navDMeshes[i]; const int nv = navPolys[i].vertCount; dtl.vertBase = 0; dtl.vertCount = 0; dtl.triBase = (unsigned int)tbase; dtl.triCount = (unsigned char)(nv-2); // Triangulate polygon (local indices). for (int j = 2; j < nv; ++j) { unsigned char* t = &navDTris[tbase*4]; t[0] = 0; t[1] = (unsigned char)(j-1); t[2] = (unsigned char)j; // Bit for each edge that belongs to poly boundary. t[3] = (1<<2); if (j == 2) t[3] |= (1<<0); if (j == nv-1) t[3] |= (1<<4); tbase++; } } // Store and create BVtree. if (tileData->buildBvTree) { createBVTree(tileData, navBvtree, 2*polyCount); } *outData = data; *outDataSize = dataSize; return true; } static const int NAVMESHSET_MAGIC = 'M'<<24 | 'S'<<16 | 'E'<<8 | 'T'; //'MSET'; static const int NAVMESHSET_VERSION = 1; struct NavMeshSetHeader { int magic; int version; int numTiles; dtNavMeshParams params; }; struct NavMeshTileHeader { dtTileRef tileRef; int dataSize; }; void saveAll(const char* path, const dtNavMesh* mesh) { if (!mesh) return; FILE* fp = fopen(path, "wb"); if (!fp) return; // Store header. NavMeshSetHeader header; header.magic = NAVMESHSET_MAGIC; header.version = NAVMESHSET_VERSION; header.numTiles = 0; for (int i = 0; i < mesh->getMaxTiles(); ++i) { const dtMeshTile* tile = mesh->getTile(i); if (!tile || !tile->header || !tile->dataSize) continue; header.numTiles++; } memcpy(&header.params, mesh->getParams(), sizeof(dtNavMeshParams)); fwrite(&header, sizeof(NavMeshSetHeader), 1, fp); // Store tiles. for (int i = 0; i < mesh->getMaxTiles(); ++i) { const dtMeshTile* tile = mesh->getTile(i); if (!tile || !tile->header || !tile->dataSize) continue; NavMeshTileHeader tileHeader; tileHeader.tileRef = mesh->getTileRef(tile); tileHeader.dataSize = tile->dataSize; fwrite(&tileHeader, sizeof(tileHeader), 1, fp); fwrite(tile->data, tile->dataSize, 1, fp); } fclose(fp); } static char* dupstr(const char* str) { if (str == nullptr) { return nullptr; } int len = (int)strlen(str) + 1; char* ret = new char[len]; if (len > 1) { memcpy(ret, str, len - 1); } ret[len - 1] = 0; return ret; } char* exportDetourFormatFile(const char* detourMeshPath, const char* detourBinPath){ auto mesh = parseMesh(detourMeshPath); if (mesh == nullptr) { return dupstr("failed to parse the detour mesh file!"); } shared_ptr<Mesh> meshDeletor(mesh); auto& vertices = mesh->vertices; auto& vi = mesh->triangles; auto& trianglesFlag = mesh->trianglesFlag; auto& trianglesAreaType = mesh->trianglesAreaType; auto& lineNeis = mesh->lineNeis; if (vertices.size() == 0 || vi.size() == 0) { return dupstr("empty mesh!"); } struct NavimeshTileData tileData; memset(&tileData, 0, sizeof(NavimeshTileData)); tileData.verts = vertices.data(); tileData.vertCount = (int)vertices.size(); float* bmin = tileData.bmin; float* bmax = tileData.bmax; dtVcopy(bmin, tileData.verts); dtVcopy(bmax, tileData.verts); for(int i = 0; i < tileData.vertCount/3; i++){ float* base = &tileData.verts[i*3]; dtVmin(bmin, base); dtVmax(bmax, base); } // per vertice/edge data tileData.triangles = vi.data(); tileData.triangleIndexCount = (int)vi.size(); using Edge2Triangle = map<uint64_t, vector<unsigned short>>; Edge2Triangle edge2triangle; auto make_line = [](uint64_t a, uint64_t b){ return a > b ? ((b<<32) | a) : ((a<<32) | b); }; for(unsigned short i = 0; i < vi.size()/3; i++){ unsigned short* base = &vi[i * 3]; uint64_t line1 = make_line(base[0], base[1]); edge2triangle[line1].push_back(i); uint64_t line2 = make_line(base[1], base[2]); edge2triangle[line2].push_back(i); uint64_t line3 = make_line(base[2], base[0]); edge2triangle[line3].push_back(i); } VerticeIndexes edgeInfo; VerticeIndexes flagsInfo; using CharVector = vector<char>; CharVector areaTypesInfo; for(unsigned short i = 0; i < vi.size()/3; i++){ flagsInfo.push_back(trianglesFlag[i]); areaTypesInfo.push_back(trianglesAreaType[i]); unsigned short* base = &vi[i * 3]; for(int j = 0; j < 3; j++){ uint64_t line = make_line(base[j], base[(j+1)%3]); if(edge2triangle[line].size() == 1){ edgeInfo.push_back(0); }else{ unsigned short otherPolyRef = edge2triangle[line][0] == i ? edge2triangle[line][1] : edge2triangle[line][0]; edgeInfo.push_back(otherPolyRef + 1); } } } tileData.neis = edgeInfo.data(); // per triangle data tileData.polyFlags = (short*)flagsInfo.data(); tileData.polyAreaTypes = areaTypesInfo.data(); // portal count tileData.portalCount = 0; tileData.buildBvTree = true; tileData.tileX = 0; tileData.tileY = 0; tileData.tileLayer = 0; tileData.userId = 0; tileData.walkableHeight = 0; tileData.walkableRadius = 0; tileData.walkableClimb = 0; unsigned char* outData = NULL; int outDataSize = 0; bool ret = dumpSoloTileData(&tileData, &outData, &outDataSize); if(ret){ dtNavMesh* navMesh = dtAllocNavMesh(); if (!navMesh) { dtFree(outData); return dupstr("Could not create Detour navmesh"); } shared_ptr<dtNavMesh> navMeshDeletor(navMesh, [](auto p) {dtFreeNavMesh(p); }); dtStatus status = navMesh->init(outData, outDataSize, DT_TILE_FREE_DATA); if (dtStatusFailed(status)) { dtFree(outData); return dupstr("Could not init Detour navmesh"); } saveAll(detourBinPath, navMesh); } return nullptr; } unsigned char* buildTileMesh(TiledMesh* mesh, int& dataSize){ auto& vertices = mesh->vertices; auto& vi = mesh->triangles; auto& trianglesFlag = mesh->trianglesFlag; auto& trianglesAreaType = mesh->trianglesAreaType; auto& lineNeis = mesh->lineNeis; auto tx = mesh->tx; auto ty = mesh->ty; struct NavimeshTileData tileData; memset(&tileData, 0, sizeof(NavimeshTileData)); tileData.verts = vertices.data(); tileData.vertCount = (int)vertices.size(); float* bmin = tileData.bmin; float* bmax = tileData.bmax; dtVcopy(bmin, tileData.verts); dtVcopy(bmax, tileData.verts); for(int i = 0; i < tileData.vertCount/3; i++){ float* base = &tileData.verts[i*3]; dtVmin(bmin, base); dtVmax(bmax, base); } // per vertice/edge data tileData.triangles = vi.data(); tileData.triangleIndexCount = (int)vi.size(); using Edge2Triangle = map<uint64_t, vector<unsigned short>>; Edge2Triangle edge2triangle; auto make_line = [](uint64_t a, uint64_t b){ return a > b ? ((b<<32) | a) : ((a<<32) | b); }; for(unsigned short i = 0; i < vi.size()/3; i++){ unsigned short* base = &vi[i * 3]; uint64_t line1 = make_line(base[0], base[1]); edge2triangle[line1].push_back(i); uint64_t line2 = make_line(base[1], base[2]); edge2triangle[line2].push_back(i); uint64_t line3 = make_line(base[2], base[0]); edge2triangle[line3].push_back(i); } VerticeIndexes edgeInfo; VerticeIndexes flagsInfo; using CharVector = vector<char>; CharVector areaTypesInfo; CharVector typeInfo; short portalCount = 0; for(unsigned short i = 0; i < vi.size()/3; i++){ flagsInfo.push_back(trianglesFlag[i]); areaTypesInfo.push_back(trianglesAreaType[i]); unsigned short* base = &vi[i * 3]; unsigned short* lineNeisBase = &lineNeis[i * 3]; for(int j = 0; j < 3; j++){ uint64_t line = make_line(base[j], base[(j+1)%3]); if (lineNeisBase[j] & DT_EXT_LINK) { edgeInfo.push_back(lineNeisBase[j]); portalCount++; } else if(edge2triangle[line].size() == 1){ edgeInfo.push_back(0); }else{ unsigned short otherPolyRef = edge2triangle[line][0] == i ? edge2triangle[line][1] : edge2triangle[line][0]; edgeInfo.push_back(otherPolyRef + 1); } } } tileData.neis = edgeInfo.data(); // per triangle data tileData.polyFlags = (short*)flagsInfo.data(); tileData.polyAreaTypes = areaTypesInfo.data(); // portal count tileData.portalCount = portalCount; tileData.buildBvTree = true; tileData.tileX = tx; tileData.tileY = ty; tileData.tileLayer = 0; tileData.userId = 0; tileData.walkableHeight = 0; tileData.walkableRadius = 0; tileData.walkableClimb = 0; unsigned char* outData = NULL; bool ret = dumpSoloTileData(&tileData, &outData, &dataSize); return outData; } char* exportTiledDetourFormatFile(const char* detourMeshPath, const char* detourBinPath) { auto mesh = parseMesh(detourMeshPath); if (mesh == nullptr) { return dupstr("failed to parse the detour mesh file!"); } shared_ptr<Mesh> meshDeletor(mesh); if (mesh->tiledMeshList.size() <= 1) { return exportDetourFormatFile(detourMeshPath, detourBinPath); } dtNavMesh* navMesh = dtAllocNavMesh(); if (!navMesh) { return dupstr("Could not create Detour navmesh"); } shared_ptr<dtNavMesh> navMeshDeletor(navMesh, [](auto p) {dtFreeNavMesh(p); }); dtNavMeshParams params; dtVcopy(params.orig, mesh->bmin.data()); params.tileWidth = mesh->tileWidth; params.tileHeight = mesh->tileHeight; int tileBits = ilog2(nextPow2(mesh->tw* mesh->th)); if (tileBits > 14) { return dupstr("too many tiles!"); } int polyBits = 22 - tileBits; params.maxTiles = 1 << tileBits; params.maxPolys = 1 << polyBits; dtStatus status = navMesh->init(&params); if (dtStatusFailed(status)) { return dupstr("Could not init Detour navmesh"); } for (auto & tiledMesh : mesh->tiledMeshList) { int polyCount = (int)tiledMesh.triangles.size() / 3; if (polyCount > params.maxPolys) { return dupstr("too many polys in a tile!"); } if (tiledMesh.vertices.size() == 0 || tiledMesh.triangles.size() == 0) { continue; } int dataSize = 0; unsigned char* data = buildTileMesh(&tiledMesh, dataSize); if (data) { // Remove any previous data (navmesh owns and deletes the data). navMesh->removeTile(navMesh->getTileRefAt(tiledMesh.tx, tiledMesh.ty, 0), 0, 0); // Let the navmesh own the data. dtStatus status = navMesh->addTile(data, dataSize, DT_TILE_FREE_DATA, 0, 0); if (dtStatusFailed(status)) { dtFree(data); } } } saveAll(detourBinPath, navMesh); return nullptr; }
32.22164
125
0.642203
noodle1983
6487238a009c9c402ee97317f3263003af34ff8b
1,603
cpp
C++
PGRIsland/source/CSplineSceneNode.cpp
ngohongs/pgr-island
48aa8e688ff1204cca51976c255ba378840b0565
[ "CC-BY-4.0" ]
null
null
null
PGRIsland/source/CSplineSceneNode.cpp
ngohongs/pgr-island
48aa8e688ff1204cca51976c255ba378840b0565
[ "CC-BY-4.0" ]
null
null
null
PGRIsland/source/CSplineSceneNode.cpp
ngohongs/pgr-island
48aa8e688ff1204cca51976c255ba378840b0565
[ "CC-BY-4.0" ]
null
null
null
//---------------------------------------------------------------------------------------- /** * \file CSplineSceneNode.cpp * \author Hong Son Ngo * \date 2021/05/05 * \brief Scene node of an object that moves along a Catmull-Rom spline * * Modification of a scene node for drawing a moving object * */ //---------------------------------------------------------------------------------------- #include "../include/CSplineSceneNode.h" #include "../include/CGameState.h" CSplineSceneNode::CSplineSceneNode(const CShaderProgram& program, const CCatmulRomSpline& spline, const float& slow) :CSceneNode(program), MSpline(spline), MSlow(slow) { // initial position glm::vec3 point = MSpline.GetSplineLoopPoint(MTime); glm::vec3 gradient = MSpline.GetSplineLoopGradient(MTime); SetPosition(point); SetDirection(glm::normalize(gradient)); } void CSplineSceneNode::Update(const float& deltaTime) { if (MTimeSet && MTime > MTimeToLive) { MTimeSet = false; MTimeToLive = 0.0f; SetOn(false); } MTime += deltaTime / MSlow; for (const auto& node : MSceneNodes) node->Update(deltaTime); // Move and rotate the object if (MTime >= (float) MSpline.GetControlPointSize()) MTime -= MSpline.GetControlPointSize(); glm::vec3 point = MSpline.GetSplineLoopPoint(MTime); glm::vec3 gradient = MSpline.GetSplineLoopGradient(MTime); SetPosition(glm::vec3(point.x, point.y, point.z)); SetDirection(glm::normalize(glm::vec3(gradient.x, 0.0f, gradient.z))); }
34.106383
117
0.587648
ngohongs
52cd664783f2002408f0b8d6caea2520c03a1f1c
13,299
cpp
C++
source/common/application.cpp
Abdelrahman-Shahda/Graphics-Project
3d86a24d34c871a20ae2d09ad3a41a6d3621a073
[ "MIT" ]
null
null
null
source/common/application.cpp
Abdelrahman-Shahda/Graphics-Project
3d86a24d34c871a20ae2d09ad3a41a6d3621a073
[ "MIT" ]
null
null
null
source/common/application.cpp
Abdelrahman-Shahda/Graphics-Project
3d86a24d34c871a20ae2d09ad3a41a6d3621a073
[ "MIT" ]
null
null
null
#include "application.hpp" #include <sstream> #include <iostream> #include <string> #include <iomanip> #include <ctime> // Include the Dear ImGui implementation headers #define IMGUI_IMPL_OPENGL_LOADER_GLAD2 #include <imgui_impl/imgui_impl_glfw.h> #include <imgui_impl/imgui_impl_opengl3.h> #if !defined(NDEBUG) // If NDEBUG (no debug) is not defined, enable OpenGL debug messages #define ENABLE_OPENGL_DEBUG_MESSAGES #endif #include "texture/screenshot.h" // This function will be used to log errors thrown by GLFW void glfw_error_callback(int error, const char* description){ std::cerr << "GLFW Error: " << error << ": " << description << std::endl; } // This function will be used to log OpenGL debug messages void GLAPIENTRY opengl_callback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) { std::string _source; std::string _type; std::string _severity; // What is the source of the message switch (source) { case GL_DEBUG_SOURCE_API: _source = "API"; break; case GL_DEBUG_SOURCE_WINDOW_SYSTEM: _source = "WINDOW SYSTEM"; break; case GL_DEBUG_SOURCE_SHADER_COMPILER: _source = "SHADER COMPILER"; break; case GL_DEBUG_SOURCE_THIRD_PARTY: _source = "THIRD PARTY"; break; case GL_DEBUG_SOURCE_APPLICATION: _source = "APPLICATION"; break; case GL_DEBUG_SOURCE_OTHER: default: _source = "UNKNOWN"; break; } // What is the type of the message (error, warning, etc). switch (type) { case GL_DEBUG_TYPE_ERROR: _type = "ERROR"; break; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: _type = "DEPRECATED BEHAVIOR"; break; case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: _type = "UDEFINED BEHAVIOR"; break; case GL_DEBUG_TYPE_PORTABILITY: _type = "PORTABILITY"; break; case GL_DEBUG_TYPE_PERFORMANCE: _type = "PERFORMANCE"; break; case GL_DEBUG_TYPE_OTHER: _type = "OTHER"; break; case GL_DEBUG_TYPE_MARKER: _type = "MARKER"; break; default: _type = "UNKNOWN"; break; } // How severe is the message switch (severity) { case GL_DEBUG_SEVERITY_HIGH: _severity = "HIGH"; break; case GL_DEBUG_SEVERITY_MEDIUM: _severity = "MEDIUM"; break; case GL_DEBUG_SEVERITY_LOW: _severity = "LOW"; break; case GL_DEBUG_SEVERITY_NOTIFICATION: _severity = "NOTIFICATION"; break; default: _severity = "UNKNOWN"; break; } std::cout << "OpenGL Debug Message " << id << " (type: " << _type << ") of " << _severity << " raised from " << _source << ": " << message << std::endl; } void GraphicsProject::Application::configureOpenGL() { // Request that OpenGL is 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // Only enable core functionalities (disable features from older OpenGL versions that were removed in 3.3) glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Enable forward compatibility with newer OpenGL versions by removing deprecated functionalities // This is necessary for some platforms glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); //Make window size fixed (User can't resize it) glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); //Set Number of sample used in MSAA (0 = Disabled) glfwWindowHint(GLFW_SAMPLES, 0); //Enable Double Buffering glfwWindowHint(GLFW_DOUBLEBUFFER, GLFW_TRUE); //Set the bit-depths of the frame buffer glfwWindowHint(GLFW_RED_BITS, 8); glfwWindowHint(GLFW_GREEN_BITS, 8); glfwWindowHint(GLFW_BLUE_BITS, 8); glfwWindowHint(GLFW_ALPHA_BITS, 8); //Set Bits for Depth Buffer glfwWindowHint(GLFW_DEPTH_BITS, 24); //Set Bits for Stencil Buffer glfwWindowHint(GLFW_STENCIL_BITS, 8); //Set the refresh rate of the window (GLFW_DONT_CARE = Run as fast as possible) glfwWindowHint(GLFW_REFRESH_RATE, GLFW_DONT_CARE); } GraphicsProject::WindowConfiguration GraphicsProject::Application::getWindowConfiguration() { return {"OpenGL Application", {1280, 720}, false }; } // This is the main class function that run the whole application (Initialize, Game loop, House cleaning). int GraphicsProject::Application::run() { // Set the function to call when an error occurs. glfwSetErrorCallback(glfw_error_callback); // Initialize GLFW and exit if it failed if(!glfwInit()){ std::cerr << "Failed to Initialize GLFW" << std::endl; return -1; } configureOpenGL(); // This function sets OpenGL window hints. auto win_config = getWindowConfiguration(); // Returns the WindowConfiguration current struct instance. // Create a window with the given "WindowConfiguration" attributes. // If it should be fullscreen, monitor should point to one of the monitors (e.g. primary monitor), otherwise it should be null GLFWmonitor* monitor = win_config.isFullscreen ? glfwGetPrimaryMonitor() : nullptr; // The last parameter "share" can be used to share the resources (OpenGL objects) between multiple windows. window = glfwCreateWindow(win_config.size.x, win_config.size.y, win_config.title, monitor, nullptr); if(!window) { std::cerr << "Failed to Create Window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); // Tell GLFW to make the context of our window the main context on the current thread. gladLoadGL(glfwGetProcAddress); // Load the OpenGL functions from the driver // Print information about the OpenGL context std::cout << "VENDOR : " << glGetString(GL_VENDOR) << std::endl; std::cout << "RENDERER : " << glGetString(GL_RENDERER) << std::endl; std::cout << "VERSION : " << glGetString(GL_VERSION) << std::endl; std::cout << "GLSL VERSION : " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; #if defined(ENABLE_OPENGL_DEBUG_MESSAGES) // if we have OpenGL debug messages enabled, set the message callback glDebugMessageCallback(opengl_callback, nullptr); // Then enable debug output glEnable(GL_DEBUG_OUTPUT); // Then make the output synchronized to the OpenGL commands. // This will make sure that OpenGL and the main thread are synchronized such that message callback is called as soon // as the command causing it is called. This is useful for debugging but slows down the code execution. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); #endif setupCallbacks(); keyboard.enable(window); mouse.enable(window); // Start the ImGui context and set dark style (just my preference :D) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); ImGui::StyleColorsDark(); // Initialize ImGui for GLFW and OpenGL ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplOpenGL3_Init("#version 330 core"); // Call onInitialize if the application needs to do some custom initialization (such as file loading, object creation, etc). onInitialize(); // The time at which the last frame started. But there was no frames yet, so we'll just pick the current time. double last_frame_time = glfwGetTime(); while(!glfwWindowShouldClose(window)){ glfwPollEvents(); // Read all the user events and call relevant callbacks. // Start a new ImGui frame ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); onImmediateGui(io); // Call to run any required Immediate GUI. // If ImGui is using the mouse or keyboard, then we don't want the captured events to affect our keyboard and mouse objects. // For example, if you're focusing on an input and writing "W", the keyboard object shouldn't record this event. keyboard.setEnabled(!io.WantCaptureKeyboard, window); mouse.setEnabled(!io.WantCaptureMouse, window); // Render the ImGui commands we called (this doesn't actually draw to the screen yet. ImGui::Render(); // Just in case ImGui changed the OpenGL viewport (the portion of the window to which we render the geometry), // we set it back to cover the whole window auto frame_buffer_size = getFrameBufferSize(); glViewport(0, 0, frame_buffer_size.x, frame_buffer_size.y); // Get the current time (the time at which we are starting the current frame). double current_frame_time = glfwGetTime(); // Call onDraw, in which we will draw the current frame, and send to it the time difference between the last and current frame onDraw(current_frame_time - last_frame_time); last_frame_time = current_frame_time; // Then update the last frame start time (this frame is now the last frame) #if defined(ENABLE_OPENGL_DEBUG_MESSAGES) // Since ImGui causes many messages to be thrown, we are temporarily disabling the debug messages till we render the ImGui glDisable(GL_DEBUG_OUTPUT); glDisable(GL_DEBUG_OUTPUT_SYNCHRONOUS); #endif ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); // Render the ImGui to the framebuffer #if defined(ENABLE_OPENGL_DEBUG_MESSAGES) // Re-enable the debug messages glEnable(GL_DEBUG_OUTPUT); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); #endif // If F12 is pressed, take a screenshot if(keyboard.justPressed(GLFW_KEY_F12)){ glViewport(0, 0, frame_buffer_size.x, frame_buffer_size.y); std::stringstream stream; auto time = std::time(nullptr); auto localtime = std::localtime(&time); stream << "screenshots/screenshot-" << std::put_time(localtime, "%Y-%m-%d-%H-%M-%S") << ".png"; if(GraphicsProject::screenshot_png(stream.str())){ std::cout << "Screenshot saved to: " << stream.str() << std::endl; } else { std::cerr << "Failed to save a Screenshot" << std::endl; } } //Close program if escape key is pressed if (keyboard.justPressed(GLFW_KEY_ESCAPE)) break; // Swap the frame buffers glfwSwapBuffers(window); // Update the keyboard and mouse data keyboard.update(); mouse.update(); } // Call for cleaning up onDestroy(); // Shutdown ImGui & destroy the context ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); // Destroy the window glfwDestroyWindow(window); // And finally terminate GLFW glfwTerminate(); return 0; // Good bye } // Sets-up the window callback functions from GLFW to our (Mouse/Keyboard) classes. void GraphicsProject::Application::setupCallbacks() { // We use GLFW to store a pointer to "this" window instance. glfwSetWindowUserPointer(window, this); // The pointer is then retrieved in the callback function. // The second parameter to "glfwSet---Callback" is a function pointer. // It is replaced by an inline function -lambda expression- as it is not needed to create // a seperate function for it. // In the inline function we retrieve the window instance and use it to set our (Mouse/Keyboard) classes values. // Keyboard callbacks glfwSetKeyCallback(window, [](GLFWwindow* window, int key, int scancode, int action, int mods){ auto* app = static_cast<Application*>(glfwGetWindowUserPointer(window)); if(app){ app->getKeyboard().keyEvent(key, scancode, action, mods); app->onKeyEvent(key, scancode, action, mods); } }); // mouse position callbacks glfwSetCursorPosCallback(window, [](GLFWwindow* window, double x_position, double y_position){ auto* app = static_cast<Application*>(glfwGetWindowUserPointer(window)); if(app){ app->getMouse().CursorMoveEvent(x_position, y_position); app->onCursorMoveEvent(x_position, y_position); } }); // mouse position callbacks glfwSetCursorEnterCallback(window, [](GLFWwindow* window, int entered){ auto* app = static_cast<Application*>(glfwGetWindowUserPointer(window)); if(app){ app->onCursorEnterEvent(entered); } }); // mouse button position callbacks glfwSetMouseButtonCallback(window, [](GLFWwindow* window, int button, int action, int mods){ auto* app = static_cast<Application*>(glfwGetWindowUserPointer(window)); if(app){ app->getMouse().MouseButtonEvent(button, action, mods); app->onMouseButtonEvent(button, action, mods); } }); // mouse scroll callbacks glfwSetScrollCallback(window, [](GLFWwindow* window, double x_offset, double y_offset){ auto* app = static_cast<Application*>(glfwGetWindowUserPointer(window)); if(app){ app->getMouse().ScrollEvent(x_offset, y_offset); app->onScrollEvent(x_offset, y_offset); } }); }
39.936937
149
0.67366
Abdelrahman-Shahda
52d0f8f31cae4ba2e77ea436a36c49f554fb99ba
12,665
cpp
C++
src/kirby.cpp
sarietta/kdceditor
52069434e7945bf5651bdd497b78aa08ab168778
[ "MIT" ]
47
2015-03-08T02:34:24.000Z
2022-02-15T00:02:25.000Z
src/kirby.cpp
sarietta/kdceditor
52069434e7945bf5651bdd497b78aa08ab168778
[ "MIT" ]
7
2015-03-11T20:12:31.000Z
2020-05-11T11:58:07.000Z
src/kirby.cpp
sarietta/kdceditor
52069434e7945bf5651bdd497b78aa08ab168778
[ "MIT" ]
8
2015-03-08T13:12:08.000Z
2022-01-10T01:38:25.000Z
/* This code is released under the terms of the MIT license. See COPYING.txt for details. */ #include "kirby.h" #include <QString> const int fgPaletteBase[] = {0xD4A9, 0xD8ED, 0xD8ED}; const int waterBase[][3] = {{0xA444, 0xE030, 0xE030}, {0xA46E, 0xE05A, 0xE05A}}; const int paletteTable[] = {0x80D425, 0x80D869, 0x80D869}; const int waterTable[][3] = {{0x8484AF, 0x8484AF, 0x8484AF}, {0x8484F1, 0x8484F1, 0x8484F1}}; const int backgroundTable[][3] = {{0x80D0AF, 0x80D517, 0x80D517}, {0x80D304, 0x80D748, 0x80D748}, {0x80D324, 0x80D768, 0x80D768}, {0x84CD23, 0x84CD42, 0x84CD42}}; const int musicTable[] = {0x80C533, 0x80C99D, 0x80C99D}; const int newMusicAddr[] = {0x80F440, 0x80F950, 0x80F950}; // first dimension is indexed by game number (0 = kirby, 1 = sts) const char* courseNames[][224 / 8] = { // KDC / Kirby Bowl courses { "1P Course 1", "1P Course 2", "1P Course 3", "1P Course 4", "1P Course 5", "1P Course 6", "1P Course 7", "1P Course 8", "1P Extra Course 1", "1P Extra Course 2", "1P Extra Course 3", "1P Extra Course 4", "1P Extra Course 5", "1P Extra Course 6", "1P Extra Course 7", "1P Extra Course 8", "2P Course 1", "2P Course 2", "2P Course 3", "2P Course 4", "Demo Course 1", "Demo Course 2", "Demo Course 3 / Test Course", "Test Course", "2P Extra Course 1", "2P Extra Course 2", "2P Extra Course 3", "2P Extra Course 4" }, // Special Tee Shot courses { "Beginner Course", "Amateur Course", "Professional Course", "Master Course", "Extra Course 1", "Extra Course 2", "Extra Course 3", "Extra Course 4", "Gold Course" } }; const bg_t bgNames[] = { {"Background 1 (clouds)", {0x8290, 0xC290, 0xC290}, {0x92BEB1, 0x90A836, 0x90A836}, {0x94AC83, 0x928000, 0x92855B}, {0xCD33, 0xCD52, 0xCD52}}, {"Background 2 (stars & moon)", {0x83D0, 0xC3D0, 0xC3D0}, {0x92D18C, 0x90B1B2, 0x90B1B2}, {0x94EDAB, 0x8EFB5F, 0x8EFB5F}, {0xCECA, 0xCEE9, 0xCEE9}}, {"Background 3 (waterfalls)", {0x8330, 0xC330, 0xC330}, {0x93A043, 0x90ED83, 0x90ED83}, {0x94967D, 0x91E7A2, 0x91EE62}, {0xCE79, 0xCE98, 0xCE98}}, {"Background 4 (jigsaw)", {0x82E0, 0xC2E0, 0xC2E0}, {0x93E286, 0x91AD5B, 0x91B41B}, {0x93D5F8, 0x91A0CD, 0x91A78D}, {0xCE64, 0xCE83, 0xCE83}}, {"Background 5 (candy)", {0x8380, 0xC380, 0xC380}, {0x92AB0F, 0x909494, 0x909494}, {0x93FA68, 0x91E20F, 0x91E8CF}, {0xCFAE, 0xCFCD, 0xCFCD}}, {"Background 6 (ocean)", {0x85E0, 0xC5E0, 0xC5E0}, {0x9398A1, 0x90E5E1, 0x90E5E1}, {0x94DA7C, 0x92B347, 0x92B8A2}, {0xCFF3, 0xD012, 0xD012}} /* something here (the GFX?) gets loaded to a different address than normal so it's not usable with the rest of the course BGs {"Background 7 (diamonds)", {0xD368, 0}, {0x93EEC0, 0}, {0x9798EF, 0}, {0xD12D, 0}}, */ }; const char* paletteNames[] = { "Course 1 (blue)", "Course 2 (green)", "Course 3 (purple)", "Course 4 (pink)", "Course 5 (tan)", "Course 6 (beige)", "Course 7 (grey)", "Course 8 (red)", "Extra course 7/8 (dark grey)", "Demo course (teal)" }; const StringMap musicNames ({ {0x7e, "7E: (none)"}, {0x80, "80: Epilogue"}, {0x82, "82: Title"}, {0x83, "83: Opening demo (JP only)"}, {0x84, "84: High scores"}, {0x85, "85: Space Valley (course 2/7b)"}, {0x86, "86: Over Water (course 1b)"}, {0x87, "87: The Tricky Stuff (course 5b)"}, {0x88, "88: Castles of Cake (course 6)"}, {0x89, "89: Green Fields (course 5a/7a)"}, {0x8a, "8A: The First Hole (course 1a/3)"}, {0x8b, "8B: Iceberg Ocean (course 8)"}, {0x8c, "8C: Last Hole"}, {0x8d, "8D: Jigsaw Plains (course 4)"}, {0x8f, "8F: Continue?"}, {0x92, "92: Final score"}, {0x93, "93: 2P course select"}, {0x94, "94: Eyecatch"}, {0x95, "95: Main menu"}, {0x96, "96: 1P course select"}, {0x97, "97: Scorecard"}, {0x9a, "9A: Demo play"}, {0x9b, "9B: Dedede 1"}, {0x9c, "9C: Dedede 2"}, {0x9f, "9F: Game over"} }); const StringMap kirbyGeometry ({ {0, "00: None"}, {1, "01: Flat"}, {2, "02: Four slopes up towards center"}, // this type is unusable // {3, "03: Four slopes down into ground"}, {4, "04: Slope down towards south"}, {5, "05: Slope down towards east"}, {6, "06: Slope down towards north"}, {7, "07: Slope down towards west"}, {8, "08: Slopes down towards south and east (inner)"}, {9, "09: Slopes down towards north and east (inner)"}, {10, "0A: Slopes down towards north and west (inner)"}, {11, "0B: Slopes down towards south and west (inner)"}, {12, "0C: Slopes down towards south and east (outer)"}, {13, "0D: Slopes down towards north and east (outer)"}, {14, "0E: Slopes down towards north and west (outer)"}, {15, "0F: Slopes down towards south and west (outer)"}, {16, "10: Slope down towards southeast (top)"}, {17, "11: Slope down towards northeast (top)"}, {18, "12: Slope down towards northwest (top)"}, {19, "13: Slope down towards southwest (top)"}, {20, "14: Slope down towards southeast (bottom)"}, {21, "15: Slope down towards northeast (bottom)"}, {22, "16: Slope down towards northwest (bottom)"}, {23, "17: Slope down towards southwest (bottom)"}, {24, "18: Slope down towards southeast (middle)"}, {25, "19: Slope down towards northeast (middle)"}, {26, "1A: Slope down towards northwest (middle)"}, {27, "1B: Slope down towards southwest (middle)"} }); const StringMap kirbyObstacles ({ {0x00, "00: None"}, {0x02, "02: Whispy Woods"}, {0x04, "04: Sand trap"}, {0x05, "05: Spike pit"}, /* hole can't be placed independently in KDC (unless it can be placed on obstacle layer w/ correct palette somehow) {0x08, "08: Hole"}, */ {0x0c, "0C: Kirby"}, {0x0d, "0D: King Dedede (course 24-1 only)"}, {0x10, "10: Current (south)"}, {0x11, "11: Current (east)"}, {0x12, "12: Current (north)"}, {0x13, "13: Current (west)"}, {0x14, "14: Arrow (south)"}, {0x15, "15: Arrow (east)"}, {0x16, "16: Arrow (north)"}, {0x17, "17: Arrow (west)"}, {0x18, "18: Booster (south)"}, {0x19, "19: Booster (east)"}, {0x1a, "1A: Booster (north)"}, {0x1b, "1B: Booster (west)"}, {0x1c, "1C: Air vent (north-south)"}, {0x1d, "1D: Air vent (east-west)"}, {0x20, "20: Bounce (use with tile 04)"}, {0x21, "21: Bounce (use with tile 05)"}, {0x22, "22: Bounce (use with tile 06)"}, {0x23, "23: Bounce (use with tile 07)"}, {0x24, "24: Bounce"}, {0x28, "28: Bumper (north to south)"}, {0x29, "29: Bumper (east to west)"}, {0x2a, "2A: Bumper (south to west)"}, {0x2b, "2B: Bumper (north to west)"}, {0x2c, "2C: Bumper (north to east)"}, {0x2d, "2D: Bumper (south to east)"}, {0x30, "30: Conveyor belt (south)"}, {0x31, "31: Conveyor belt (east)"}, {0x32, "32: Conveyor belt (north)"}, {0x33, "33: Conveyor belt (west)"}, {0x34, "34: Conveyor belt (north, use with tile 04)"}, {0x35, "35: Conveyor belt (south, use with tile 04)"}, {0x36, "36: Conveyor belt (west, use with tile 05)"}, {0x37, "37: Conveyor belt (east, use with tile 05)"}, {0x38, "38: Conveyor belt (south, use with tile 06)"}, {0x39, "39: Conveyor belt (north, use with tile 06)"}, {0x3a, "3A: Conveyor belt (east, use with tile 07)"}, {0x3b, "3B: Conveyor belt (west, use with tile 07)"}, {0x40, "40: Waddle Dee"}, {0x41, "41: Rocky"}, {0x42, "42: Waddle Doo"}, {0x43, "43: Flamer"}, {0x44, "44: Spiney"}, {0x45, "45: Twister"}, {0x46, "46: Wheelie"}, {0x47, "47: Sparky"}, {0x48, "48: Starman"}, {0x49, "49: Chilly"}, {0x4a, "4A: Broom Hatter"}, {0x4b, "4B: Squishy"}, {0x4c, "4C: Kabu"}, {0x4d, "4D: Gaspar"}, {0x4e, "4E: Pumpkin"}, {0x4f, "4F: UFO"}, {0x50, "50: Gaspar (higher)"}, {0x51, "51: Pumpkin (higher)"}, {0x52, "52: UFO (higher)"}, {0x57, "57: Transformer"}, {0x58, "58: Mr. Bright switch"}, {0x59, "59: Mr. Shine switch"}, {0x5a, "5A: Rotating space switch (off)"}, {0x5b, "5B: Rotating space switch (on)"}, {0x5c, "5C: Water switch (on)"}, {0x5d, "5D: Water switch (off)"}, {0x61, "61: Water hazard"}, {0x64, "64: Water hazard (use with tile 04)"}, {0x65, "65: Water hazard (use with tile 05)"}, {0x66, "66: Water hazard (use with tile 06)"}, {0x67, "67: Water hazard (use with tile 07)"}, {0x68, "68: Water hazard (use with tile 08)"}, {0x69, "69: Water hazard (use with tile 09)"}, {0x6a, "6A: Water hazard (use with tile 0A)"}, {0x6b, "6B: Water hazard (use with tile 0B)"}, {0x6c, "6C: Water hazard (use with tile 0C)"}, {0x6d, "6D: Water hazard (use with tile 0D)"}, {0x6e, "6E: Water hazard (use with tile 0E)"}, {0x6f, "6F: Water hazard (use with tile 0F)"}, /* Most of these are not used in KDC. */ {0x70, "70: Rotating space (clockwise, always on)"}, {0x71, "71: Rotating space (counterclockwise, always on)"}, {0x72, "72: Rotating space (clockwise, always on, slow)"}, {0x73, "73: Rotating space (counterclockwise, always on, slow)"}, {0x74, "74: Rotating space (clockwise, switch)"}, {0x75, "75: Rotating space (counterclockwise, switch)"}, {0x76, "76: Rotating space (clockwise, switch, slow)"}, {0x77, "77: Rotating space (counterclockwise, switch, slow)"}, {0x78, "78: Rotating space (clockwise, switch-opposite)"}, {0x79, "79: Rotating space (counterclockwise, switch-opposite)"}, {0x7a, "7A: Rotating space (clockwise, switch-opposite, slow)"}, {0x7b, "7B: Rotating space (counterclockwise, switch-opposite, slow)"}, {0x80, "80: Gordo (moves south, faces south)"}, {0x81, "81: Gordo (moves east, faces south)"}, {0x82, "82: Gordo (moves north, faces south)"}, {0x83, "83: Gordo (moves west, faces south)"}, {0x84, "84: Gordo (moves south, faces east)"}, {0x85, "85: Gordo (moves east, faces east)"}, {0x86, "86: Gordo (moves north, faces east)"}, {0x87, "87: Gordo (moves west, faces east)"}, {0x88, "88: Gordo (moves south, faces north)"}, {0x89, "89: Gordo (moves east, faces north)"}, {0x8a, "8A: Gordo (moves north, faces north)"}, {0x8b, "8B: Gordo (moves west, faces north)"}, {0x8c, "8C: Gordo (moves south, faces west)"}, {0x8d, "8D: Gordo (moves east, faces west)"}, {0x8e, "8E: Gordo (moves north, faces west)"}, {0x8f, "8F: Gordo (moves west, faces west)"}, {0x90, "90: Gordo (moves up/down, faces south)"}, {0x91, "91: Gordo (moves up/down, faces east)"}, {0x92, "92: Gordo (moves up/down, faces north)"}, {0x93, "93: Gordo (moves up/down, faces west)"}, {0x94, "94: Gordo (moves down/up, faces south)"}, {0x95, "95: Gordo (moves down/up, faces east)"}, {0x96, "96: Gordo (moves down/up, faces north)"}, {0x97, "97: Gordo (moves down/up, faces west)"}, {0x98, "98: Gordo path (north-south)"}, {0x99, "99: Gordo path (east-west)"}, {0x9a, "9A: Gordo path (northwest corner)"}, {0x9b, "9B: Gordo path (southwest corner)"}, {0x9c, "9C: Gordo path (southeast corner)"}, {0x9d, "9D: Gordo path (northeast corner)"}, {0x9e, "9E: Gordo endpoint (south)"}, {0x9f, "9F: Gordo endpoint (east)"}, {0xa0, "A0: Gordo endpoint (north)"}, {0xa1, "A1: Gordo endpoint (west)"}, {0xac, "AC: Kracko (no lightning)"}, {0xad, "AD: Kracko (lightning 1)"}, {0xae, "AE: Kracko (lightning 2)"}, {0xb0, "B0: Blue warp 1 (south)"}, {0xb1, "B1: Blue warp 1 (east)"}, {0xb2, "B2: Blue warp 1 (north)"}, {0xb3, "B3: Blue warp 1 (west)"}, {0xb4, "B4: Blue warp 2 (south)"}, {0xb5, "B5: Blue warp 2 (east)"}, {0xb6, "B6: Blue warp 2 (north)"}, {0xb7, "B7: Blue warp 2 (west)"}, {0xb8, "B8: Red warp 1"}, {0xb9, "B9: Red warp 2"}, {0xc0, "C0: Starting line (west end)"}, {0xc1, "C1: Starting line"}, {0xc2, "C2: Starting line (east end)"}, {0xc3, "C3: Kirby (course 24-1 only)"}, });
33.773333
78
0.563364
sarietta
52d51c076b115f9530be3973503725334d1f2e78
428
cpp
C++
Dev Skill/vector.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
Dev Skill/vector.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
Dev Skill/vector.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> #include <iterator> using namespace std; int main() { vector <int> v; vector <int>:: iterator it; v.push_back(20); v.push_back(2); v.push_back(50); cout<<v.size()<<endl; for(auto x: v) cout<<x<<endl; sort(v.begin(), v.end()); it = v.begin(); for(; it != v.end();it++) cout<<*it<<'\t'; }
17.833333
32
0.509346
Sohelr360
52d6d4152980983d93ae0d34dd7adc7b0f081d3e
5,728
cpp
C++
include/eigenvec_centrality.cpp
masatoshihanai/HyInfluenceMin
40b01947e1e1785806582eb6791310aeeee3d7c5
[ "MIT" ]
null
null
null
include/eigenvec_centrality.cpp
masatoshihanai/HyInfluenceMin
40b01947e1e1785806582eb6791310aeeee3d7c5
[ "MIT" ]
null
null
null
include/eigenvec_centrality.cpp
masatoshihanai/HyInfluenceMin
40b01947e1e1785806582eb6791310aeeee3d7c5
[ "MIT" ]
null
null
null
/* * Copyright (c) 2020 Masatoshi Hanai * * This software is released under MIT License. * See LICENSE. * */ #include "hygraph.hpp" #include "external/Eigen/Core" #include "external/Eigen/Dense" #include "external/Eigen/Eigenvalues" #include "wtime.hpp" class EigenVectorCentrality { public: void getTopK(HyGraph& hygraph, HyIDSet& topK, uint64_t k) { #ifdef HAS_OMP Eigen::initParallel(); #endif if (hygraph.numHyEdges() > 500000) { std::cout << "!!! Too big data for Eigen !!! Skip computation " << std::endl; return; } // todo fix to include repeat interval std::string bFileName = hygraph.fName_ + std::to_string(TIME_UNIT_HOUR) + "-eigenvec.bin"; std::vector<std::pair<HyEdgeID, double>> idValuePairs(hygraph.numHyEdges()); std::ifstream ifs(bFileName); if (ifs.is_open()) { std::cout << "Eigen vector exists. Read from file " << std::endl; ifs.read((char*)&idValuePairs[0], (sizeof(HyEdgeID) + sizeof(double) * idValuePairs.size())); ifs.close(); } else { ifs.close(); std::cout << "Build Matrix" << std::endl; Eigen::MatrixXd mmT(hygraph.numHyEdges(), hygraph.numHyEdges()); { Eigen::MatrixXd m(hygraph.numHyEdges(), hygraph.numVert()); for (uint64_t i = 0; i < hygraph.numHyEdges(); ++i) { for (auto v: hygraph.getHyEdge(i).vertices_) { m(i, v) = 1.0; } } auto mT = m.transpose(); mmT = m * mT; } double start = getTime(); uint64_t numItr = 100; Eigen::Vector<double, Eigen::Dynamic> v_prev = Eigen::Vector<double, Eigen::Dynamic>::Random( mmT.cols()).cwiseAbs(); Eigen::Vector<double, Eigen::Dynamic> v = Eigen::Vector<double, Eigen::Dynamic>(mmT.cols()); std::cout << "Start Power Method" << std::endl; for (uint64_t i = 0; i < numItr; ++i) { v.swap(mmT * v_prev); v.normalize(); v_prev.swap(v); std::cout << "\r Iteration " << i << " : " << (getTime() - start) << std::flush; } std::cout << std::endl; for (uint i = 0; i < idValuePairs.size(); ++i) { idValuePairs.at(i).first = i; idValuePairs.at(i).second = v(i); } std::sort(idValuePairs.begin(), idValuePairs.end(), [](std::pair<HyEdgeID, double> &l, std::pair<HyEdgeID, double> &r) { return l.second > r.second; }); double end = getTime(); std::cout << "Execution Time for Eigen Centrality: " << end - start << std::endl; std::cout << "Write result to " << bFileName << std::endl; std::ofstream file; file.open(bFileName, std::ios::out | std::ios::binary); file.write((char*) &idValuePairs[0], (sizeof(HyEdgeID) + sizeof(double))*idValuePairs.size()); file.close(); } for (uint i = 0; i < k; ++i) { // std::cout << "i: " << i << " " << idValuePairs.at(i).first << " " << idValuePairs.at(i).second << std::endl; topK.insert(idValuePairs.at(i).first); } } }; //int main(int argc, char** argv) { // int size = std::atol(argv[1]); // std::cout << "test EigenVector size " << size << std::endl; // //// Eigen::MatrixXd mmt = Eigen::MatrixXd::Random(size,size); // //// /* (12*7) vector */ // Eigen::MatrixXd m = Eigen::MatrixXd(12,7); // m << // 1,1,0,0,1,0,0, // 1,0,0,1,1,0,0, // 0,1,1,0,1,0,0, // 0,0,1,1,1,0,0, // 1,1,0,0,0,1,0, // 1,0,1,0,0,1,0, // 1,0,0,1,0,1,0, // 0,1,0,1,0,1,0, // 1,0,0,1,0,0,1, // 1,0,1,0,0,0,1, // 0,1,0,1,0,0,1, // 0,1,1,0,0,0,1; // // auto mt = m.transpose(); // std::cout << "m is" << std::endl; // std::cout << m << std::endl; // std::cout << std::endl; // // std::cout << "transpose(m) is " << std::endl; // std::cout << mt << std::endl; // std::cout << std::endl; // // std::cout << "m * transpose(m) is " << std::endl; // std::cout << (m*mt) << std::endl; // std::cout << std::endl; // auto mmt = m*mt; // // // Exact method // Eigen::EigenSolver<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>> s(mmt); // auto eval = s.eigenvalues(); // std::cout << "eigen value \n" << eval << std::endl; // std::cout << eval(0) << std::endl; //// for (auto x: eval) { //// std::cout << x << std::endl; //// } // // auto evec = s.eigenvectors(); // std::cout << "eigen vector \n";// << evec << std::endl; // // for (int i = 0; i < 12; ++i) { // std::cout << evec(i,0).real() / evec(0,0).real() << std::endl; // } // // // Power method // clock_t start = clock(); // uint64_t numItr = 100; // // std::cout << "mmt size" << mmt.cols() << std::endl; // Eigen::Vector<double, Eigen::Dynamic> v_prev = Eigen::Vector<double, Eigen::Dynamic>::Random(mmt.cols()).cwiseAbs(); // Eigen::Vector<double, Eigen::Dynamic> v = Eigen::Vector<double, Eigen::Dynamic>(mmt.cols()); // // for (uint64_t i = 0; i < numItr; ++i) { // v.swap(mmt*v_prev); // v.normalize(); // v_prev.swap(v); // } // clock_t end = clock(); // std::cout << "power method's eigen vector \n" << std::endl; // std::cout << v << std::endl; // // std::vector<std::pair<HyEdgeID, double>> idValuePairs(mmt.cols()); // for (uint i = 0; i < idValuePairs.size(); ++i) { // idValuePairs.at(i).first = i; // idValuePairs.at(i).second = v(i); // } // // std::sort(idValuePairs.begin(), idValuePairs.end(), [](std::pair<HyEdgeID, double>& l, std::pair<HyEdgeID, double>& r) { // return l.second > r.second; // }); // // for (auto x: idValuePairs) { // std::cout << "id " << x.first << " val " << x.second << std::endl; // } // // // std::cout << "time to compute for " << size*size << " " << (double) (end - start)/CLOCKS_PER_SEC << std::endl; //}
31.822222
124
0.54574
masatoshihanai
52d75adeb5daa16d9dc557cdd2dbbb63e45668c3
1,089
cpp
C++
codeforces/A - Vasya and Petya's Game/Wrong answer on test 4.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/A - Vasya and Petya's Game/Wrong answer on test 4.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/A - Vasya and Petya's Game/Wrong answer on test 4.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Sep/02/2018 12:39 * solution_verdict: Wrong answer on test 4 language: GNU C++14 * run_time: 15 ms memory_used: 0 KB * problem: https://codeforces.com/contest/576/problem/A ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6; bool is_prime(int x) { for(int i=2;i<x;i++) if(x%i==0)return false; return true; } int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n,cnt=0;cin>>n; for(int i=2;i<=n;i++) { if(is_prime(i)) { cnt++; if(i*i<=n)cnt++; } } cout<<cnt<<endl; for(int i=2;i<=n;i++) { if(is_prime(i)) { cout<<i<<" "; if(i*i<=n)cout<<i*i<<" "; } } cout<<endl; return 0; }
27.225
111
0.380165
kzvd4729
52d7c710466ec69daf41255227b15079e72792b6
4,108
cpp
C++
src/LittleCrusaderAsi/modcore/modLoader.cpp
TheRedDaemon/LittleCrusaderAsi
da98790f68422d359dc93c198e2a79ec60719007
[ "MIT" ]
4
2020-11-30T21:53:57.000Z
2022-03-18T05:14:48.000Z
src/LittleCrusaderAsi/modcore/modLoader.cpp
TheRedDaemon/LittleCrusaderAsi
da98790f68422d359dc93c198e2a79ec60719007
[ "MIT" ]
3
2020-10-22T20:40:04.000Z
2021-10-05T14:24:22.000Z
src/LittleCrusaderAsi/modcore/modLoader.cpp
TheRedDaemon/LittleCrusaderAsi
da98790f68422d359dc93c198e2a79ec60719007
[ "MIT" ]
null
null
null
#include "modLoader.h" namespace modcore { ModLoader::ModLoader(HMODULE ownModule) { // set own Module handle ModMan::handle = ownModule; // will load config and what ever is required at the start std::unordered_map<ModID, Json> modConfigs{}; try { std::ifstream configStream("modConfig.json"); // reading config from file if (!configStream.good()) { throw std::exception("Unable to load config file. Does it exist?"); } Json modConfig = Json::parse(configStream); for (auto& pair : modConfig.items()) { ModID key{ ModManager::GetEnumByName(pair.key()) }; if (!key) { LOG(WARNING) << "No mod registration for name '" << pair.key() << "' found."; continue; // ignore } modConfigs[key] = pair.value(); } } catch (const Json::parse_error& o_O) { LOG(ERROR) << "Config parse error: " << o_O.what(); throw; } catch (const std::exception& o_O) { LOG(ERROR) << "Error during config load: " << o_O.what(); throw; } LOG(INFO) << "Configuration loaded."; fillAndOrderModVector(modConfigs); LOG(INFO) << "Mods loaded."; // end by calling initialze on every mod: int initializedMods{ 0 }; for (Mod* modPtr : ModMan::orderedMods) { if (modPtr->callInitialize()) { ++initializedMods; } } LOG(INFO) << initializedMods << " of " << ModMan::orderedMods.size() << " mods initialized."; } void ModLoader::dllThreadAttachEvent() { // at the first attach event, fire this event to the mods for (Mod* modPtr : ModMan::orderedMods) { modPtr->threadAttachAfterModAttachEvent(); } } // will run backwards over mods and call cleanUp // destruction will be handled by smart pointers ModLoader::~ModLoader() { // call cleanUp in reverse dependency order (is this reverse order?) for (int i = ModMan::orderedMods.size() - 1; i >= 0; i--) { ModMan::orderedMods.at(i)->cleanUp(); } LOG(INFO) << "Cleaned up mods."; } void ModLoader::fillAndOrderModVector(const std::unordered_map<ModID, Json> &modConfigs) { // normaly, the mod will run over all configs and add them for (const auto& config : modConfigs) { fulfillDependencies(modConfigs, config.first, config.second); } } void ModLoader::fulfillDependencies( const std::unordered_map<ModID, Json> &modConfigs, ModID neededMod, const Json &config) { if (auto it{ ModMan::loadedMods.find(neededMod) }; it != ModMan::loadedMods.end()) { if (!(it->second.mod)) { throw std::exception(("Cylic dependency reference encountered! Dependency with id '" + neededMod->getName() + "' was already requested.").c_str()); } // no else, if mod inside, everything is okay } else { // create mod entry: ModMan::loadedMods[neededMod]; // create mod only if needed, otherwise unused creates auto nextMod{ (neededMod->getValue())(config) }; std::vector<ModID> deps{ nextMod->getDependencies() }; if (!deps.empty()) { for (ModID dep : deps) { if (modConfigs.find(dep) != modConfigs.end()) { fulfillDependencies(modConfigs, dep, modConfigs.at(dep)); } else { // trying to call build in stuff (without external config?) fulfillDependencies(modConfigs, dep, nullptr); } // add, that this mod wanted this dependency ModMan::loadedMods[dep].modsThatNeedThis.push_back(neededMod); } } // if no dependency, it can be added // at this point, either everything is fulfilled or it broke anyway ModMan::loadedMods[neededMod].mod = nextMod; ModMan::orderedMods.push_back(&(*nextMod)); } } }
29.553957
98
0.570837
TheRedDaemon
52d7c7ca54a0eea33deb1efc16581a75f216be5d
907
hpp
C++
telnetpp/include/telnetpp/detail/negotiation_router.hpp
CalielOfSeptem/septem
fe7a615eb6c279d3746ee78de8864b5e07bf7e3e
[ "MIT" ]
1
2017-03-30T14:31:33.000Z
2017-03-30T14:31:33.000Z
telnetpp/include/telnetpp/detail/negotiation_router.hpp
HoraceWeebler/septem
fe7a615eb6c279d3746ee78de8864b5e07bf7e3e
[ "MIT" ]
null
null
null
telnetpp/include/telnetpp/detail/negotiation_router.hpp
HoraceWeebler/septem
fe7a615eb6c279d3746ee78de8864b5e07bf7e3e
[ "MIT" ]
null
null
null
#pragma once #include "telnetpp/detail/router.hpp" #include "telnetpp/negotiation.hpp" #include "telnetpp/element.hpp" #include <vector> namespace telnetpp { namespace detail { struct negotiation_router_key_from_message_policy { static negotiation key_from_message(negotiation const &neg) { return neg; } }; //* ========================================================================= /// \brief A structure that can route incoming negotiations to their /// associated options. /// /// This can be used as a multiplexer between incoming /// negotiations and the set of supported client and server options. /// ========================================================================= class negotiation_router : public router< negotiation, negotiation, std::vector<telnetpp::token>, detail::negotiation_router_key_from_message_policy > { }; }}
25.194444
77
0.597574
CalielOfSeptem
52d83c9b2ec6636a204b2cefb02ac76c8129cd33
544
cpp
C++
src/lib/lib_ruben/ruben.cpp
rpasquay/scratch
6c8076f9ab208cbd60e60ceaf0223c3170312c0d
[ "MIT" ]
5
2018-12-04T09:30:00.000Z
2021-08-21T08:50:09.000Z
src/lib/lib_ruben/ruben.cpp
rpasquay/scratch
6c8076f9ab208cbd60e60ceaf0223c3170312c0d
[ "MIT" ]
null
null
null
src/lib/lib_ruben/ruben.cpp
rpasquay/scratch
6c8076f9ab208cbd60e60ceaf0223c3170312c0d
[ "MIT" ]
3
2018-12-05T10:36:01.000Z
2020-07-10T13:48:46.000Z
#include <sstream> #include "scratch/lib_ruben/ruben.hpp" #include "scratch/lib_ruben/exceptions.hpp" scratch::ruben::Ruben::Ruben() : rubens_secret(42) {} unsigned int scratch::ruben::Ruben::get_secrect() const { return rubens_secret; } void scratch::ruben::Ruben::set_secrect(const unsigned int secret) { rubens_secret = secret; } void scratch::ruben::Ruben::throw_secrect() const { std::stringstream msg; msg << "My secret number is " << rubens_secret << "." << std::endl; throw SecretException(msg.str().c_str()); }
27.2
71
0.700368
rpasquay
52d89693da7154c6e0a7248b94cd96063e8dd01b
9,099
cxx
C++
bpkg/cfg-unlink.cxx
build2/bpkg
bd939839b44d90d027517e447537dd52539269ff
[ "MIT" ]
19
2018-05-30T12:01:25.000Z
2022-01-29T21:37:23.000Z
bpkg/cfg-unlink.cxx
build2/bpkg
bd939839b44d90d027517e447537dd52539269ff
[ "MIT" ]
2
2019-03-18T22:31:45.000Z
2020-07-28T06:44:03.000Z
bpkg/cfg-unlink.cxx
build2/bpkg
bd939839b44d90d027517e447537dd52539269ff
[ "MIT" ]
1
2019-02-04T02:58:14.000Z
2019-02-04T02:58:14.000Z
// file : bpkg/cfg-unlink.cxx -*- C++ -*- // license : MIT; see accompanying LICENSE file #include <bpkg/cfg-unlink.hxx> #include <bpkg/package.hxx> #include <bpkg/package-odb.hxx> #include <bpkg/database.hxx> #include <bpkg/diagnostics.hxx> using namespace std; namespace bpkg { static int cfg_unlink_config (const cfg_unlink_options& o, cli::scanner& args) try { tracer trace ("cfg_unlink_config"); dir_path c (o.directory ()); l4 ([&]{trace << "configuration: " << c;}); database mdb (c, trace, true /* pre_attach */); transaction t (mdb); // Find the configuration to be unlinked. // // Note that we exclude the current configuration from the search. // database& udb (o.name_specified () ? mdb.find_attached (o.name (), false) : o.id_specified () ? mdb.find_attached (o.id (), false) : o.uuid_specified () ? mdb.find_attached (o.uuid (), false) : mdb.find_attached ( normalize (dir_path (args.next ()), "specified linked configuration"), false)); l4 ([&]{trace << "unlink configuration: " << udb.config;}); bool priv (udb.private_ ()); // If the configuration being unlinked contains any prerequisites of // packages in other configurations, make sure that they will stay // resolvable for their dependents after the configuration is unlinked // (see _selected_package_ref::to_ptr() for the resolution details). // // Specifically, if the configuration being unlinked is private, make sure // it doesn't contain any prerequisites of any dependents in any other // configurations (since we will remove it). Otherwise, do not consider // those dependent configurations which will still be linked with the // unlinked configuration (directly or indirectly through some different // path). // // So, for example, for the following link chain where cfg1 contains a // dependent of a prerequisite in cfg3, unlinking cfg3 from cfg2 will // result with the "cfg3 still depends on cfg1" error. // // cfg1 (target) -> cfg2 (target) -> cfg3 (host) // { // Note: needs to come before the subsequent unlinking. // // Also note that this call also verifies integrity of the implicit // links of the configuration being unlinked, which we rely upon below. // linked_databases dcs (udb.dependent_configs ()); // Unlink the configuration in the in-memory model, so we can evaluate // if the dependent configurations are still linked with it. // // Note that we don't remove the backlink here, since this is not // required for the check. // if (!priv) { linked_configs& ls (mdb.explicit_links ()); auto i (find_if (ls.begin (), ls.end (), [&udb] (const linked_config& lc) { return lc.db == udb; })); assert (i != ls.end ()); // By definition. ls.erase (i); } // Now go through the packages configured in the unlinked configuration // and check it they have some dependents in other configurations which // now unable to resolve them as prerequisites. Issue diagnostics and // fail if that's the case. // using query = query<selected_package>; for (shared_ptr<selected_package> sp: pointer_result ( udb.query<selected_package> (query::state == "configured"))) { for (auto i (dcs.begin_linked ()); i != dcs.end (); ++i) { database& db (*i); odb::result<package_dependent> ds ( query_dependents (db, sp->name, udb)); // Skip the dependent configuration if it doesn't contain any // dependents of the package. // if (ds.empty ()) continue; // Skip the dependent configuration if it is still (potentially // indirectly) linked with the unlinked configuration. // if (!priv) { linked_databases cs (db.dependency_configs ()); if (find_if (cs.begin (), cs.end (), [&udb] (const database& db) { return db == udb; }) != cs.end ()) continue; } diag_record dr (fail); dr << "configuration " << db.config_orig << " still depends on " << (priv ? "private " : "") << "configuration " << udb.config_orig << info << "package " << sp->name << udb << " has dependents:"; for (const package_dependent& pd: ds) { dr << info << "package " << pd.name << db; if (pd.constraint) dr << " on " << sp->name << " " << *pd.constraint; } } } } // Now unlink the configuration for real, in the database. // // Specifically, load the current and the being unlinked configurations // and remove their respective explicit and implicit links. // { using query = query<configuration>; // Explicit link. // shared_ptr<configuration> uc ( mdb.query_one<configuration> (query::uuid == udb.uuid.string ())); // The integrity of the current configuration explicit links is verified // by the database constructor. // assert (uc != nullptr); // Implicit backlink. // shared_ptr<configuration> cc ( udb.query_one<configuration> (query::uuid == mdb.uuid.string ())); // The integrity of the implicit links of the configuration being // unlinked is verified by the above dependent_configs() call. // assert (cc != nullptr); // If the backlink turns out to be explicit, then, unless the // configuration being unlinked is private, we just turn the explicit // link into an implicit one rather then remove the direct and back // links. // if (cc->expl && !priv) { info << "configurations " << udb.config_orig << " and " << mdb.config_orig << " are mutually linked, turning the link " << "to " << udb.config_orig << " into implicit backlink"; uc->expl = false; mdb.update (uc); } else { mdb.erase (uc); udb.erase (cc); } } t.commit (); // If the unlinked configuration is private, then detach its database and // remove its directory. But first, stash the directory path for the // subsequent removal and diagnostics. // dir_path ud (udb.config); if (priv) { mdb.detach_all (); rm_r (ud); } if (verb && !o.no_result ()) text << "unlinked " << (priv ? "and removed " : "") << "configuration " << ud; return 0; } catch (const invalid_path& e) { fail << "invalid path: '" << e.path << "'" << endf; } static int cfg_unlink_dangling (const cfg_unlink_options& o, cli::scanner&) { tracer trace ("cfg_unlink_dangling"); dir_path c (o.directory ()); l4 ([&]{trace << "configuration: " << c;}); database db (c, trace, false /* pre_attach */); transaction t (db); using query = query<configuration>; size_t count (0); for (auto& c: db.query<configuration> (query::id != 0 && !query::expl)) { if (!exists (c.effective_path (db.config))) { if (verb > 1) text << "removing dangling implicit backlink " << c.path; db.erase (c); ++count; } } t.commit (); if (verb && !o.no_result ()) text << "removed " << count << " dangling implicit backlink(s)"; return 0; } int cfg_unlink (const cfg_unlink_options& o, cli::scanner& args) { // Verify that the unlink mode is specified unambiguously. // // Points to the mode, if any is specified and NULL otherwise. // const char* mode (nullptr); // If the mode is specified, then check that it hasn't been specified yet // and set it, if that's the case, or fail otherwise. // auto verify = [&mode] (const char* m, bool specified) { if (specified) { if (mode == nullptr) mode = m; else fail << "both " << mode << " and " << m << " specified"; } }; verify ("--dangling", o.dangling ()); verify ("--name", o.name_specified ()); verify ("--id", o.id_specified ()); verify ("--uuid", o.uuid_specified ()); verify ("directory argument", args.more ()); if (mode == nullptr) fail << "expected configuration to unlink or --dangling option" << info << "run 'bpkg help cfg-unlink' for more information"; return o.dangling () ? cfg_unlink_dangling (o, args) : cfg_unlink_config (o, args); } }
31.054608
79
0.560611
build2
52d94feb5eca1106ba8a092a4391590ca1a176a8
2,490
cpp
C++
Solutions/Count Complete Tree Nodes/main.cpp
Crayzero/LeetCodeProgramming
b10ebe22c0de1501722f0f5c934c0c1902a26789
[ "MIT" ]
1
2015-04-13T10:58:30.000Z
2015-04-13T10:58:30.000Z
Solutions/Count Complete Tree Nodes/main.cpp
Crayzero/LeetCodeProgramming
b10ebe22c0de1501722f0f5c934c0c1902a26789
[ "MIT" ]
null
null
null
Solutions/Count Complete Tree Nodes/main.cpp
Crayzero/LeetCodeProgramming
b10ebe22c0de1501722f0f5c934c0c1902a26789
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x): val(x), left(NULL), right(NULL) {} }; class Solution { public: int countNodes(TreeNode* root) { int level = 0; for(TreeNode *p = root; p; level++, p = p->left); if (level <= 1) return pow(2, level-1); int cnt = 0; int cur_level = 1; cnt = pow(2, level - cur_level - 1); int tot = 0; while(1) { if (cnt == 1) { return pow(2, level-1) -1 + tot + (root->left ? 1 : 0) + (root->right ? 1 : 0); } TreeNode *left = root->left; TreeNode *tmp = left; cur_level++; if (cur_level == level) tmp = root; for(int i = cur_level; i < level-1 && tmp; ++i) { tmp = tmp->right; } cout<<tmp->val<<endl; if (tmp == NULL) return pow(2, level - 1) + tot -1; if (tmp->left == NULL && tmp->right == NULL) { cnt /= 2; root = root->left; } else if (tmp->right == NULL) { tot += cnt - 1; return pow(2, level - 1) -1 + tot; } else { tot += cnt; cnt /= 2; root = root->right; } cout<<" "<<tot<<endl; } cout<<cnt<<endl; return pow(2, level-1) - 1 + cnt; } }; int main() { TreeNode *a1 = new TreeNode(1); TreeNode *a2 = new TreeNode(2); TreeNode *a3 = new TreeNode(3); TreeNode *a4 = new TreeNode(4); TreeNode *a5 = new TreeNode(5); TreeNode *a6 = new TreeNode(6); TreeNode *a7 = new TreeNode(7); TreeNode *a8 = new TreeNode(8); TreeNode *a9 = new TreeNode(9); TreeNode *a10 = new TreeNode(10); TreeNode *a11 = new TreeNode(11); TreeNode *a12 = new TreeNode(12); TreeNode *a13 = new TreeNode(13); TreeNode *a14 = new TreeNode(14); TreeNode *a15 = new TreeNode(15); a1->left = a2; a1->right = a3; a2->left = a4; a2->right = a5; a3->left = a6; a3->right = a7; a4->left = a8; //a4->right = a9; //a5->left = a10; //a5->right = a11; //a6->left = a12; //a6->right = a13; //a7->left = a14; //a7->right = a15; Solution s; cout<<s.countNodes(a1); return 0; }
26.489362
95
0.45743
Crayzero
52daa4e79485287f41e303cec8808154406be5cf
4,235
cpp
C++
wled00/Effect/snowflake/Solid.cpp
mdraper81/WLED
408696ef02f7b2dd66300a6a2ddb67a74d037b88
[ "MIT" ]
null
null
null
wled00/Effect/snowflake/Solid.cpp
mdraper81/WLED
408696ef02f7b2dd66300a6a2ddb67a74d037b88
[ "MIT" ]
null
null
null
wled00/Effect/snowflake/Solid.cpp
mdraper81/WLED
408696ef02f7b2dd66300a6a2ddb67a74d037b88
[ "MIT" ]
null
null
null
#include "Solid.h" namespace Effect { namespace Snowflake { /* ** ============================================================================ ** Constructor ** ============================================================================ */ Solid::Solid(NeoPixelWrapper* pixelWrapper, Data* effectData) : BaseSnowFlake(pixelWrapper, effectData) { } /* ** ============================================================================ ** Destructor ** ============================================================================ */ Solid::~Solid() { } /* ** ============================================================================ ** Run the current effect ** ============================================================================ */ bool Solid::runEffect(uint32_t delta) { incrementRunningTime(delta); updateEffectData(); // Process the effect to shift the colors of the LEDs for (int armIndex = 0; armIndex < mNumberOfArms; ++armIndex) { processArm(armIndex); } } /* ** ============================================================================ ** Process the LEDs in the arm with the given index. This will set the correct ** colors for the LEDs for this arm ** ============================================================================ */ void Solid::processArm(int armIndex) { // Turn on the correct number of LEDs in the arm for where we are in the // effect (what tick we are on). const uint16_t armStartingAddress = getStartingAddressForArmIndex(armIndex); for (int armAddressIndex = 0; armAddressIndex < mArmLength; ++armAddressIndex) { uint16_t address = armStartingAddress + armAddressIndex; const int effectOffset = armAddressIndex; setPixelColorFromPalette(address, effectOffset); } processSmallChevron(armIndex); processLargeChevron(armIndex); } /* ** ============================================================================ ** Process the LEDs in the small chevron for the arm with the given index. ** This will set the correct colors for the LEDs in this chevron. ** ============================================================================ */ void Solid::processSmallChevron(int armIndex) { const uint8_t numTicksToProcess = getNumberOfTicksForSmallChevron(); const uint16_t smallChevronStartingAddress_Left = getStartingAddressForSmallChevron(armIndex, true); const uint16_t smallChevronStartingAddress_Right = getStartingAddressForSmallChevron(armIndex, false); for (uint8_t chevronAddressIndex = 0; chevronAddressIndex < numTicksToProcess; ++chevronAddressIndex) { const uint16_t leftAddress = smallChevronStartingAddress_Left + chevronAddressIndex; const uint16_t rightAddress = smallChevronStartingAddress_Right + chevronAddressIndex; const int effectOffset = mSmallChevronPosition + chevronAddressIndex; setPixelColorFromPalette(leftAddress, effectOffset); setPixelColorFromPalette(rightAddress, effectOffset); } } /* ** ============================================================================ ** Process the LEDs in the large chevron for the arm with the given index. ** This will set the correct colors for the LEDs in this chevron. ** ============================================================================ */ void Solid::processLargeChevron(int armIndex) { const uint8_t numTicksToProcess = getNumberOfTicksForLargeChevron(); const uint16_t largeChevronStartingAddress_Left = getStartingAddressForLargeChevron(armIndex, true); const uint16_t largeChevronStartingAddress_Right = getStartingAddressForLargeChevron(armIndex, false); for (uint8_t chevronAddressIndex = 0; chevronAddressIndex < numTicksToProcess; ++chevronAddressIndex) { const uint16_t leftAddress = largeChevronStartingAddress_Left + chevronAddressIndex; const uint16_t rightAddress = largeChevronStartingAddress_Right + chevronAddressIndex; const int effectOffset = mArmLength + chevronAddressIndex; setPixelColorFromPalette(leftAddress, effectOffset); setPixelColorFromPalette(rightAddress, effectOffset); } } } // namespace Effect::Snowflake } // namespace Effect
37.477876
106
0.577568
mdraper81
52dba18fa461cee3687767207b5b9b83251f7800
25,585
hpp
C++
include/System/Collections/ArrayList.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/System/Collections/ArrayList.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/System/Collections/ArrayList.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ICloneable #include "System/ICloneable.hpp" // Including type: System.Collections.IList #include "System/Collections/IList.hpp" // Including type: System.Int32 #include "System/Int32.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: System::Collections namespace System::Collections { // Skipping declaration: ICollection because it is already included! // Forward declaring type: IEnumerator class IEnumerator; } // Forward declaring namespace: System namespace System { // Forward declaring type: Array class Array; // Forward declaring type: Type class Type; } // Completed forward declares // Type namespace: System.Collections namespace System::Collections { // Forward declaring type: ArrayList class ArrayList; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::Collections::ArrayList); DEFINE_IL2CPP_ARG_TYPE(::System::Collections::ArrayList*, "System.Collections", "ArrayList"); // Type namespace: System.Collections namespace System::Collections { // Size: 0x28 #pragma pack(push, 1) // Autogenerated type: System.Collections.ArrayList // [TokenAttribute] Offset: FFFFFFFF // [DebuggerTypeProxyAttribute] Offset: 57D850 // [DebuggerDisplayAttribute] Offset: 57D850 // [DefaultMemberAttribute] Offset: 57D850 // [ComVisibleAttribute] Offset: 57D850 class ArrayList : public ::Il2CppObject/*, public ::System::ICloneable, public ::System::Collections::IList*/ { public: // Nested type: ::System::Collections::ArrayList::ReadOnlyArrayList class ReadOnlyArrayList; // Nested type: ::System::Collections::ArrayList::ArrayListEnumeratorSimple class ArrayListEnumeratorSimple; // Nested type: ::System::Collections::ArrayList::ArrayListDebugView class ArrayListDebugView; #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private System.Object[] _items // Size: 0x8 // Offset: 0x10 ::ArrayW<::Il2CppObject*> items; // Field size check static_assert(sizeof(::ArrayW<::Il2CppObject*>) == 0x8); // private System.Int32 _size // Size: 0x4 // Offset: 0x18 int size; // Field size check static_assert(sizeof(int) == 0x4); // private System.Int32 _version // Size: 0x4 // Offset: 0x1C int version; // Field size check static_assert(sizeof(int) == 0x4); // private System.Object _syncRoot // Size: 0x8 // Offset: 0x20 ::Il2CppObject* syncRoot; // Field size check static_assert(sizeof(::Il2CppObject*) == 0x8); public: // Creating interface conversion operator: operator ::System::ICloneable operator ::System::ICloneable() noexcept { return *reinterpret_cast<::System::ICloneable*>(this); } // Creating interface conversion operator: operator ::System::Collections::IList operator ::System::Collections::IList() noexcept { return *reinterpret_cast<::System::Collections::IList*>(this); } // static field const value: static private System.Int32 _defaultCapacity static constexpr const int _defaultCapacity = 4; // Get static field: static private System.Int32 _defaultCapacity static int _get__defaultCapacity(); // Set static field: static private System.Int32 _defaultCapacity static void _set__defaultCapacity(int value); // Get static field: static private readonly System.Object[] emptyArray static ::ArrayW<::Il2CppObject*> _get_emptyArray(); // Set static field: static private readonly System.Object[] emptyArray static void _set_emptyArray(::ArrayW<::Il2CppObject*> value); // Get instance field reference: private System.Object[] _items ::ArrayW<::Il2CppObject*>& dyn__items(); // Get instance field reference: private System.Int32 _size int& dyn__size(); // Get instance field reference: private System.Int32 _version int& dyn__version(); // Get instance field reference: private System.Object _syncRoot ::Il2CppObject*& dyn__syncRoot(); // public System.Void set_Capacity(System.Int32 value) // Offset: 0xDEA178 void set_Capacity(int value); // public System.Int32 get_Count() // Offset: 0xDEA298 int get_Count(); // public System.Boolean get_IsReadOnly() // Offset: 0xDEA2A0 bool get_IsReadOnly(); // public System.Object get_SyncRoot() // Offset: 0xDEA2A8 ::Il2CppObject* get_SyncRoot(); // public System.Object get_Item(System.Int32 index) // Offset: 0xDEA31C ::Il2CppObject* get_Item(int index); // public System.Void set_Item(System.Int32 index, System.Object value) // Offset: 0xDEA3D0 void set_Item(int index, ::Il2CppObject* value); // public System.Void .ctor(System.Int32 capacity) // Offset: 0xDE9E68 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ArrayList* New_ctor(int capacity) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<ArrayList*, creationType>(capacity))); } // public System.Void .ctor(System.Collections.ICollection c) // Offset: 0xDE9FCC template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ArrayList* New_ctor(::System::Collections::ICollection* c) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<ArrayList*, creationType>(c))); } // static private System.Void .cctor() // Offset: 0xDEB24C static void _cctor(); // public System.Int32 Add(System.Object value) // Offset: 0xDEA4C8 int Add(::Il2CppObject* value); // public System.Void AddRange(System.Collections.ICollection c) // Offset: 0xDEA5D4 void AddRange(::System::Collections::ICollection* c); // public System.Void Clear() // Offset: 0xDEA5F0 void Clear(); // public System.Object Clone() // Offset: 0xDEA634 ::Il2CppObject* Clone(); // public System.Boolean Contains(System.Object item) // Offset: 0xDEA6CC bool Contains(::Il2CppObject* item); // public System.Void CopyTo(System.Array array) // Offset: 0xDEA7A0 void CopyTo(::System::Array* array); // public System.Void CopyTo(System.Array array, System.Int32 arrayIndex) // Offset: 0xDEA7B4 void CopyTo(::System::Array* array, int arrayIndex); // public System.Void CopyTo(System.Int32 index, System.Array array, System.Int32 arrayIndex, System.Int32 count) // Offset: 0xDEA854 void CopyTo(int index, ::System::Array* array, int arrayIndex, int count); // private System.Void EnsureCapacity(System.Int32 min) // Offset: 0xDEA57C void EnsureCapacity(int min); // public System.Collections.IEnumerator GetEnumerator() // Offset: 0xDEA920 ::System::Collections::IEnumerator* GetEnumerator(); // public System.Int32 IndexOf(System.Object value) // Offset: 0xDEA980 int IndexOf(::Il2CppObject* value); // public System.Void Insert(System.Int32 index, System.Object value) // Offset: 0xDEA994 void Insert(int index, ::Il2CppObject* value); // public System.Void InsertRange(System.Int32 index, System.Collections.ICollection c) // Offset: 0xDEAAD0 void InsertRange(int index, ::System::Collections::ICollection* c); // static public System.Collections.ArrayList ReadOnly(System.Collections.ArrayList list) // Offset: 0xDEAD40 static ::System::Collections::ArrayList* ReadOnly(::System::Collections::ArrayList* list); // public System.Void Remove(System.Object obj) // Offset: 0xDEADE8 void Remove(::Il2CppObject* obj); // public System.Void RemoveAt(System.Int32 index) // Offset: 0xDEAE38 void RemoveAt(int index); // public System.Void RemoveRange(System.Int32 index, System.Int32 count) // Offset: 0xDEAF24 void RemoveRange(int index, int count); // public System.Object[] ToArray() // Offset: 0xDEB0A4 ::ArrayW<::Il2CppObject*> ToArray(); // public System.Array ToArray(System.Type type) // Offset: 0xDEB118 ::System::Array* ToArray(::System::Type* type); // public System.Void .ctor() // Offset: 0xDDE338 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ArrayList* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<ArrayList*, creationType>())); } }; // System.Collections.ArrayList #pragma pack(pop) static check_size<sizeof(ArrayList), 32 + sizeof(::Il2CppObject*)> __System_Collections_ArrayListSizeCheck; static_assert(sizeof(ArrayList) == 0x28); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Collections::ArrayList::set_Capacity // Il2CppName: set_Capacity template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(int)>(&System::Collections::ArrayList::set_Capacity)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "set_Capacity", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::get_Count // Il2CppName: get_Count template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Collections::ArrayList::*)()>(&System::Collections::ArrayList::get_Count)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "get_Count", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::get_IsReadOnly // Il2CppName: get_IsReadOnly template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Collections::ArrayList::*)()>(&System::Collections::ArrayList::get_IsReadOnly)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "get_IsReadOnly", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::get_SyncRoot // Il2CppName: get_SyncRoot template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::Collections::ArrayList::*)()>(&System::Collections::ArrayList::get_SyncRoot)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "get_SyncRoot", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::get_Item // Il2CppName: get_Item template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::Collections::ArrayList::*)(int)>(&System::Collections::ArrayList::get_Item)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "get_Item", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::set_Item // Il2CppName: set_Item template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(int, ::Il2CppObject*)>(&System::Collections::ArrayList::set_Item)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "set_Item", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index, value}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::Collections::ArrayList::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::Collections::ArrayList::_cctor // Il2CppName: .cctor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&System::Collections::ArrayList::_cctor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::Add // Il2CppName: Add template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Collections::ArrayList::*)(::Il2CppObject*)>(&System::Collections::ArrayList::Add)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "Add", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::AddRange // Il2CppName: AddRange template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(::System::Collections::ICollection*)>(&System::Collections::ArrayList::AddRange)> { static const MethodInfo* get() { static auto* c = &::il2cpp_utils::GetClassFromName("System.Collections", "ICollection")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "AddRange", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{c}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::Clear // Il2CppName: Clear template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)()>(&System::Collections::ArrayList::Clear)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "Clear", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::Clone // Il2CppName: Clone template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::Collections::ArrayList::*)()>(&System::Collections::ArrayList::Clone)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "Clone", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::Contains // Il2CppName: Contains template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Collections::ArrayList::*)(::Il2CppObject*)>(&System::Collections::ArrayList::Contains)> { static const MethodInfo* get() { static auto* item = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "Contains", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{item}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::CopyTo // Il2CppName: CopyTo template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(::System::Array*)>(&System::Collections::ArrayList::CopyTo)> { static const MethodInfo* get() { static auto* array = &::il2cpp_utils::GetClassFromName("System", "Array")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "CopyTo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{array}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::CopyTo // Il2CppName: CopyTo template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(::System::Array*, int)>(&System::Collections::ArrayList::CopyTo)> { static const MethodInfo* get() { static auto* array = &::il2cpp_utils::GetClassFromName("System", "Array")->byval_arg; static auto* arrayIndex = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "CopyTo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{array, arrayIndex}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::CopyTo // Il2CppName: CopyTo template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(int, ::System::Array*, int, int)>(&System::Collections::ArrayList::CopyTo)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* array = &::il2cpp_utils::GetClassFromName("System", "Array")->byval_arg; static auto* arrayIndex = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* count = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "CopyTo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index, array, arrayIndex, count}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::EnsureCapacity // Il2CppName: EnsureCapacity template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(int)>(&System::Collections::ArrayList::EnsureCapacity)> { static const MethodInfo* get() { static auto* min = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "EnsureCapacity", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{min}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::GetEnumerator // Il2CppName: GetEnumerator template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::IEnumerator* (System::Collections::ArrayList::*)()>(&System::Collections::ArrayList::GetEnumerator)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "GetEnumerator", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::IndexOf // Il2CppName: IndexOf template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Collections::ArrayList::*)(::Il2CppObject*)>(&System::Collections::ArrayList::IndexOf)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "IndexOf", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::Insert // Il2CppName: Insert template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(int, ::Il2CppObject*)>(&System::Collections::ArrayList::Insert)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "Insert", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index, value}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::InsertRange // Il2CppName: InsertRange template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(int, ::System::Collections::ICollection*)>(&System::Collections::ArrayList::InsertRange)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* c = &::il2cpp_utils::GetClassFromName("System.Collections", "ICollection")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "InsertRange", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index, c}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::ReadOnly // Il2CppName: ReadOnly template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::ArrayList* (*)(::System::Collections::ArrayList*)>(&System::Collections::ArrayList::ReadOnly)> { static const MethodInfo* get() { static auto* list = &::il2cpp_utils::GetClassFromName("System.Collections", "ArrayList")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "ReadOnly", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{list}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::Remove // Il2CppName: Remove template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(::Il2CppObject*)>(&System::Collections::ArrayList::Remove)> { static const MethodInfo* get() { static auto* obj = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "Remove", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{obj}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::RemoveAt // Il2CppName: RemoveAt template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(int)>(&System::Collections::ArrayList::RemoveAt)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "RemoveAt", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::RemoveRange // Il2CppName: RemoveRange template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Collections::ArrayList::*)(int, int)>(&System::Collections::ArrayList::RemoveRange)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* count = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "RemoveRange", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index, count}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::ToArray // Il2CppName: ToArray template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::ArrayW<::Il2CppObject*> (System::Collections::ArrayList::*)()>(&System::Collections::ArrayList::ToArray)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "ToArray", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::ToArray // Il2CppName: ToArray template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Array* (System::Collections::ArrayList::*)(::System::Type*)>(&System::Collections::ArrayList::ToArray)> { static const MethodInfo* get() { static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Collections::ArrayList*), "ToArray", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type}); } }; // Writing MetadataGetter for method: System::Collections::ArrayList::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
53.976793
201
0.726715
RedBrumbler
52de456b0a33cf85a396d5029c3b997356632176
2,343
cpp
C++
Sources/Core/Input/InputEventHandler.cpp
VladimirBalun/RacingWorld
c7e600c5899e3ea78f50bd2f8cd915437bad7789
[ "Apache-2.0" ]
70
2019-02-02T15:43:38.000Z
2022-03-09T13:58:27.000Z
Sources/Core/Input/InputEventHandler.cpp
VladimirBalun/RacingWorld
c7e600c5899e3ea78f50bd2f8cd915437bad7789
[ "Apache-2.0" ]
19
2019-03-27T05:57:30.000Z
2019-07-07T16:07:05.000Z
Sources/Core/Input/InputEventHandler.cpp
VladimirBalun/RacingWorld
c7e600c5899e3ea78f50bd2f8cd915437bad7789
[ "Apache-2.0" ]
32
2019-03-07T12:22:40.000Z
2022-03-18T01:12:56.000Z
/* * Copyright 2018 Vladimir Balun * * 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 "PrecompiledHeader.hpp" #include "InputEventHandler.hpp" #include "MouseState.hpp" #include "KeyboardState.hpp" #include "../Helpers/Debug.hpp" #include "../Helpers/Macroses.hpp" void Core::Input::onInputError(const int error, const char* description) noexcept { LOG_WARNING(STR("Input error:" + STR(description))); } void Core::Input::onMouseMoveEvent(GLFWwindow* window, double x_pos, double y_pos) noexcept { g_mouse_state.setPosition(static_cast<int>(x_pos), static_cast<int>(y_pos)); } void Core::Input::onMouseClickEvent(GLFWwindow* window, int button, int action, int mods) noexcept { } void Core::Input::onKeyboardEvent(GLFWwindow* window, const int key, const int scan_code, const int action, const int mods) noexcept { KeyboardState& keyboard_state = KeyboardState::getInstance(); if (key == GLFW_KEY_W && action == GLFW_PRESS) { keyboard_state.pressKeyW(); return; } if (key == GLFW_KEY_S && action == GLFW_PRESS) { keyboard_state.pressKeyS(); return; } if (key == GLFW_KEY_A && action == GLFW_PRESS) { keyboard_state.pressKeyA(); return; } if (key == GLFW_KEY_D && action == GLFW_PRESS) { keyboard_state.pressKeyD(); return; } if (key == GLFW_KEY_W && action == GLFW_RELEASE) { keyboard_state.releaseKeyW(); return; } if (key == GLFW_KEY_S && action == GLFW_RELEASE) { keyboard_state.releaseKeyS(); return; } if (key == GLFW_KEY_A && action == GLFW_RELEASE) { keyboard_state.releaseKeyA(); return; } if (key == GLFW_KEY_D && action == GLFW_RELEASE) { keyboard_state.releaseKeyD(); } }
28.228916
132
0.662825
VladimirBalun
52e27ab59559a2c1d72582938a321ad0209f744e
539
hpp
C++
src/util/timer.hpp
StuffByDavid/Base
d37713fcf48655cb49032c576a1586c135e2e83d
[ "MIT" ]
null
null
null
src/util/timer.hpp
StuffByDavid/Base
d37713fcf48655cb49032c576a1586c135e2e83d
[ "MIT" ]
null
null
null
src/util/timer.hpp
StuffByDavid/Base
d37713fcf48655cb49032c576a1586c135e2e83d
[ "MIT" ]
null
null
null
#pragma once #include <chrono> // high_resolution_clock namespace Base { class Timer { public: EXPORT Timer(const string& name); /* Timer functionality */ EXPORT void stop(); EXPORT void print() const; EXPORT void stopAndPrint(); /* Get the time elapsed in milliseconds. */ double getDuration() const { return time; } private: std::chrono::_V2::high_resolution_clock::time_point startTime, endTime; double time; string name; }; }
20.730769
79
0.597403
StuffByDavid
52f655c89606cb8b53d542d8aec1dc7d4d87826a
13,682
cpp
C++
src/chromecast_finder.cpp
p2004a/pulseaudio-chromecast-sink
c62d2a8defb6a5819369624351441f4c972b1b98
[ "BSD-3-Clause" ]
1
2016-06-15T15:13:43.000Z
2016-06-15T15:13:43.000Z
src/chromecast_finder.cpp
p2004a/pulseaudio-chromecast-sink
c62d2a8defb6a5819369624351441f4c972b1b98
[ "BSD-3-Clause" ]
null
null
null
src/chromecast_finder.cpp
p2004a/pulseaudio-chromecast-sink
c62d2a8defb6a5819369624351441f4c972b1b98
[ "BSD-3-Clause" ]
1
2019-12-24T02:43:37.000Z
2019-12-24T02:43:37.000Z
/* chromecast_finder.cpp -- This file is part of pulseaudio-chromecast-sink * Copyright (C) 2016 Marek Rusinowski * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <functional> #include <map> #include <memory> #include <string> #include <unordered_map> #include <asio/io_service.hpp> #include <asio/ip/tcp.hpp> #include <spdlog/spdlog.h> #include <avahi-client/client.h> #include <avahi-client/lookup.h> #include <avahi-common/error.h> #include <avahi-common/malloc.h> #include <avahi-common/simple-watch.h> #include "chromecast_finder.h" #include "defer.h" ChromecastFinder::ChromecastFinder(asio::io_service& io_service_, const char* logger_name) : io_service(io_service_), poll(io_service) { logger = spdlog::get(logger_name); } ChromecastFinder::~ChromecastFinder() { assert(avahi_client == nullptr && "Tried to destruct running instance of ChromecastFinder"); } void ChromecastFinder::start() { assert(update_handler != nullptr); poll.get_strand().post([this] { start_discovery(); }); } void ChromecastFinder::stop() { poll.get_strand().dispatch([this]() { logger->trace("(ChromecastFinder) Stopping"); if (stopped) { logger->trace("(ChromecastFinder) Already stopped!"); return; } stopped = true; while (!resolvers.empty()) { auto resolverId = resolvers.begin()->first; remove_resolver(resolverId); } if (avahi_browser != nullptr) { logger->trace("(ChromecastFinder) Freeing avahi_browser"); avahi_service_browser_free(avahi_browser); avahi_browser = nullptr; } if (avahi_client != nullptr) { logger->trace("(ChromecastFinder) Freeing avahi_client"); avahi_client_free(avahi_client); avahi_client = nullptr; } logger->debug("(ChromecastFinder) Stopped running"); }); } void ChromecastFinder::start_discovery() { stopped = false; int error; avahi_client = avahi_client_new(poll.get_pool(), AVAHI_CLIENT_NO_FAIL, ChromecastFinder::client_callback, this, &error); if (stopped) { avahi_client = nullptr; return; } if (!avahi_client) { report_error("Couldn't create avahi client: " + std::string(avahi_strerror(error))); } } void ChromecastFinder::client_callback(AvahiClient* c, AvahiClientState state, void* data) { ChromecastFinder* cf = static_cast<ChromecastFinder*>(data); if (cf->avahi_client != c) { cf->avahi_client = c; } assert(c); switch (state) { case AVAHI_CLIENT_S_RUNNING: cf->logger->info("(ChromecastFinder) Connected to Avahi server"); cf->avahi_browser = avahi_service_browser_new(cf->avahi_client, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, "_googlecast._tcp", "local", static_cast<AvahiLookupFlags>(0), ChromecastFinder::browse_callback, cf); if (!cf->avahi_browser) { cf->report_error("Failed to create service browser: " + cf->get_avahi_error()); } break; case AVAHI_CLIENT_S_REGISTERING: case AVAHI_CLIENT_S_COLLISION: break; case AVAHI_CLIENT_CONNECTING: cf->logger->info("(ChromecastFinder) Connecting to Avahi server..."); break; case AVAHI_CLIENT_FAILURE: if (avahi_client_errno(cf->avahi_client) == AVAHI_ERR_DISCONNECTED) { cf->logger->info("(ChromecastFinder) Avahi server disconnected"); cf->stop(); cf->start_discovery(); } else { cf->report_error("Server connection failure: " + cf->get_avahi_error()); } break; } } void ChromecastFinder::browse_callback(AvahiServiceBrowser* b, AvahiIfIndex interface, AvahiProtocol protocol, AvahiBrowserEvent event, const char* name, const char* type, const char* domain, AvahiLookupResultFlags, void* data) { ChromecastFinder* cf = static_cast<ChromecastFinder*>(data); assert(b); /* Called whenever a new services becomes available on the LAN or is removed from the LAN */ switch (event) { case AVAHI_BROWSER_FAILURE: cf->report_error("Browser failure: " + cf->get_avahi_error()); break; case AVAHI_BROWSER_NEW: { cf->logger->debug( "(ChromecastFinder) (Browser) New service discovered name: {} interface: {}, " "protocol: {}", name, interface, protocol); AvahiServiceResolver* resolver = avahi_service_resolver_new( cf->avahi_client, interface, protocol, name, type, domain, AVAHI_PROTO_UNSPEC, static_cast<AvahiLookupFlags>(0), ChromecastFinder::resolve_callback, cf); if (!resolver) { cf->report_error("Failed to create service resolver: " + cf->get_avahi_error()); } else { cf->add_resolver(ResolverId(interface, protocol, name), resolver); } break; } case AVAHI_BROWSER_REMOVE: { cf->logger->debug( "(ChromecastFinder) (Browser) Service dissapeared name: '{}' interface: {}, " "protocol: {}", name, interface, protocol); cf->remove_resolver(ResolverId(interface, protocol, name)); break; } case AVAHI_BROWSER_ALL_FOR_NOW: case AVAHI_BROWSER_CACHE_EXHAUSTED: break; } } asio::ip::tcp::endpoint ChromecastFinder::avahiAddresToAsioEndpoint(const AvahiAddress* address, uint16_t port) { char addr_str[AVAHI_ADDRESS_STR_MAX]; avahi_address_snprint(addr_str, sizeof(addr_str), address); return asio::ip::tcp::endpoint(asio::ip::address::from_string(addr_str), port); } std::map<std::string, std::string> ChromecastFinder::avahiDNSStringListToMap( AvahiStringList* node) { std::map<std::string, std::string> result; for (; node; node = node->next) { size_t eq_pos; for (eq_pos = 0; eq_pos < node->size; ++eq_pos) { if (node->text[eq_pos] == '=') { break; } } if (eq_pos == node->size) { logger->warn( "(ChromecastFinder) Avahi DNS string element didn't contain equal sign, " "ignoring"); continue; } result.insert({std::string((char*)node->text, eq_pos), std::string((char*)node->text + eq_pos + 1, node->size - eq_pos - 1)}); } return result; }; void ChromecastFinder::resolve_callback(AvahiServiceResolver* r, AvahiIfIndex interface, AvahiProtocol protocol, AvahiResolverEvent event, const char* name, const char* /*type*/, const char* /*domain*/, const char* /*host_name*/, const AvahiAddress* address, uint16_t port, AvahiStringList* txt, AvahiLookupResultFlags, void* data) { assert(r); ChromecastFinder* cf = static_cast<ChromecastFinder*>(data); switch (event) { case AVAHI_RESOLVER_FAILURE: cf->logger->error( "(ChromecastFinder) (Resolver) Failed to resolve service name: '{}' interface: " "{} protocol: " "{}: {}", name, interface, protocol, cf->get_avahi_error()); break; case AVAHI_RESOLVER_FOUND: { cf->logger->debug( "(ChromecastFinder) (Resolver) Resolved service name: '{}' interface: {} " "protocol: {}", name, interface, protocol); auto endpoint = cf->avahiAddresToAsioEndpoint(address, port); auto dns = cf->avahiDNSStringListToMap(txt); std::string chromecast_name(name); cf->chromecasts_update(r, name, endpoint, dns); break; } } } void ChromecastFinder::report_error(const std::string& message) { if (error_handler) { error_handler(message); } else { throw ChromecastFinderException(message); } } std::string ChromecastFinder::get_avahi_error() const { return avahi_strerror(avahi_client_errno(avahi_client)); } void ChromecastFinder::remove_resolver(ResolverId id) { logger->trace("(ChromecastFinder) Remove resolver: {} {} {}", id.name, id.interface, id.protocol); auto resolver_it = resolvers.find(id); assert(resolver_it != resolvers.end()); AvahiServiceResolver* resolver = resolver_it->second; avahi_service_resolver_free(resolver); resolvers.erase(resolver_it); chromecasts_remove(resolver); } void ChromecastFinder::add_resolver(ResolverId id, AvahiServiceResolver* resolver) { logger->trace("(ChromecastFinder) Add resolver: {} {} {}", id.name, id.interface, id.protocol); bool inserted = resolvers.insert({id, resolver}).second; assert(inserted); } void ChromecastFinder::chromecasts_update(AvahiServiceResolver* resolver, const std::string& name, const asio::ip::tcp::endpoint& endpoint, const std::map<std::string, std::string>& dns) { bool added = false, updated = false; InternalChromecastInfo* chromecast; auto chromecast_it = chromecasts.find(name); if (chromecast_it == chromecasts.end()) { chromecast = new InternalChromecastInfo(); chromecast->name = name; chromecasts.emplace(name, std::unique_ptr<InternalChromecastInfo>(chromecast)); added = true; } else { chromecast = chromecast_it->second.get(); } if (dns != chromecast->dns) { chromecast->dns = dns; updated = true; } bool set_endpoint = false; if (resolver_to_chromecast.find(resolver) == resolver_to_chromecast.end()) { resolver_to_chromecast[resolver] = chromecast; set_endpoint = true; } else { auto curr_endpoint = chromecast->endpoints[resolver]; if (curr_endpoint != endpoint) { auto endpoint_count_it = chromecast->endpoint_count.find(curr_endpoint); if (--endpoint_count_it->second == 0) { chromecast->endpoint_count.erase(endpoint_count_it); updated = true; } set_endpoint = true; } } if (set_endpoint) { chromecast->endpoints[resolver] = endpoint; auto endpoint_count_it = chromecast->endpoint_count.find(endpoint); if (endpoint_count_it == chromecast->endpoint_count.end()) { chromecast->endpoint_count[endpoint] = 1; updated = true; } else { endpoint_count_it->second += 1; } } if (added || updated) { send_update(added ? UpdateType::NEW : UpdateType::UPDATE, chromecast); } } void ChromecastFinder::chromecasts_remove(AvahiServiceResolver* resolver) { auto resolver_to_chromecast_it = resolver_to_chromecast.find(resolver); if (resolver_to_chromecast_it == resolver_to_chromecast.end()) { // This is possible when someone calls ChromecastFinder::stop after resolver was registered // but before it resolved service. return; } bool updated = false; auto chromecast = resolver_to_chromecast_it->second; resolver_to_chromecast.erase(resolver_to_chromecast_it); auto endpoints_it = chromecast->endpoints.find(resolver); auto endpoint_count_it = chromecast->endpoint_count.find(endpoints_it->second); if (--endpoint_count_it->second == 0) { chromecast->endpoint_count.erase(endpoint_count_it); updated = true; } chromecast->endpoints.erase(endpoints_it); if (chromecast->endpoints.empty()) { send_update(UpdateType::REMOVE, chromecast); chromecasts.erase(chromecast->name); } else if (updated) { send_update(UpdateType::UPDATE, chromecast); } } void ChromecastFinder::send_update(UpdateType type, InternalChromecastInfo* chromecast) const { static const char* update_name[] = {"NEW", "UPDATE", "REMOVE"}; logger->trace("(ChromecastFinder) Sending update {} {}", chromecast->name, update_name[static_cast<int>(type)]); ChromecastInfo info; info.name = chromecast->name; info.dns = chromecast->dns; for (const auto& elem : chromecast->endpoint_count) { info.endpoints.insert(elem.first); } update_handler(type, info); }
38.111421
100
0.606783
p2004a
52fc19fd562a3f56481bd6de6ebb572def1d146e
6,759
cpp
C++
cpp/bmpshow.cpp
jerrythomas/cui-toolkit
5b9970e3c01ec17de6a2e9922ad211b7e3ac6a94
[ "MIT" ]
null
null
null
cpp/bmpshow.cpp
jerrythomas/cui-toolkit
5b9970e3c01ec17de6a2e9922ad211b7e3ac6a94
[ "MIT" ]
null
null
null
cpp/bmpshow.cpp
jerrythomas/cui-toolkit
5b9970e3c01ec17de6a2e9922ad211b7e3ac6a94
[ "MIT" ]
null
null
null
#include <string.h> #include <stdio.h> #include <pixel.h> #include <kbd.h> struct ColorMap { byte blu; byte grn; byte red; byte gry; }; struct BmpHeader { char Type[2]; //type of file ; must be ascii "BM" dword Size; // Size of file word Reserved1; //reserved fiels must be 0 word Reserved2; // ----------do------------ dword OffBits; //specifies offset in bytes fo start of bitmap data }; struct BmpInfo { dword Size; //Size of bitmapinfostructure 40 bytes dword Width; //Width of bitmap in pixels dword Height; //Height of Bitmap in pixels word Planes; //image planes( 1) word BitCount; //BitsPerPixel (1,4,8 or 24) dword Compression; //Compression used dword SizeImage; // Size of image in bytes dword XPelsPerMeter; // Horizontal resolution in pixels per meter dword YPelsPerMeter; // Vertical resolution in pixels per meter dword ClrUsed; // Number of color indexes in the color table dword ClrImportant; // Number of color indexes considered important for displaying bitmap }; class Bmp { private : BmpHeader bf; BmpInfo bi; ColorMap *co; char *BmpFile; word swImage; int ColMapSize; byte xScl,yScl; word X,Y; dword Width,Height; byte TotPix; byte BitMask; public : Bmp(char *FileName); Bmp(); ~Bmp(); private : void ShowBW(); void Show16(); void Show256(); public : void Capture(int x,int y,int w,int h); void SaveAs(char *F); void Show(int x,int y); void Scale(byte x,byte y); void Spec(); }; Bmp::Bmp() { bf.Type[0] = 'B'; bf.Type[1] = 'M'; bf.Size = 56; bf.Reserved1 = 0; bf.Reserved2 = 0; bf.OffBits = 56; swImage = 0; bi.Size = 40; BmpFile = (char*)NULL; xScl =yScl = 1; } Bmp::Bmp(char *FileName) { FILE *f; swImage = 0x00; xScl = yScl = 1; f = fopen(FileName,"r"); if (f != (FILE*)NULL) { fread((char*)&bf,sizeof(bf),1,f); if (bf.Type[0] == 'B' && bf.Type[1] == 'M') { fread((char*)&bi,sizeof(bi),1,f); BmpFile = new char[strlen(FileName)+1]; strcpy(BmpFile,FileName); swImage = 0x10; BitMask = 0; for(TotPix=0;TotPix<bi.BitCount;TotPix++) BitMask |= (1<<TotPix); TotPix = 8/bi.BitCount; Width = bi.Width; Width += (bi.BitCount==1) ? (32-bi.Width%32)%32:(8-bi.Width%8)%8; ColMapSize=(bf.OffBits-54)/4; co = new ColorMap[ColMapSize]; fread((char*)co,sizeof(ColorMap),ColMapSize,f); } } fclose(f); } Bmp::~Bmp() { if (BmpFile != (char*)NULL) delete BmpFile; if (co != (ColorMap*)NULL) delete co; } void Bmp::Show16() { int x,y,Pix; char dummy; FILE *f=fopen(BmpFile,"rb"); for (x=0;x<bf.OffBits;x++) fread(&dummy,sizeof(char),1,f); x=y=0; byte scl=1; if (bi.BitCount==1) { scl=15; //loadcolormap } if (swImage==0x10) do { fread(&dummy,sizeof(char),1,f); for (int k=0;k<TotPix;k++) { Pix = scl*((dummy>>((TotPix-1-k)*bi.BitCount))&BitMask); if (x<bi.Width) for(int i=0;i<xScl;i++) for (int j=0;j<yScl;j++) SetPixel(X+x*xScl+i,Y+(bi.Height-y)*yScl+j,Pix); x++; if (x==Width) { x=0;y++;} } } while((y<bi.Height) && !feof(f)); fclose(f); } void Bmp::Show(int x,int y) { X = x; Y = y; for (int i=0 ; i< ColMapSize;i++) { RGBHue[i].red = co[i].red>>2; RGBHue[i].blu = co[i].blu>>2; RGBHue[i].grn = co[i].grn>>2; } SetPalette(RGBHue); Show16(); } void Bmp::Capture(int x,int y,int w,int h) { bf.Type[0] = 'B'; bf.Type[1] = 'M'; bf.Size = 56; bf.Reserved1 = 0; bf.Reserved2 = 0; bf.OffBits = 56; swImage = 0; bi.Size = 40; bi.Width = w; bi.Height = h; bi.BitCount = 8; bi.Planes = 1; bi.Compression = 0; bi.SizeImage = w*h; ColMapSize = 256; if (co) delete co; co = new ColorMap[256]; for (int i=0 ; i< ColMapSize;i++) { co[i].red = RGBHue[i].red<<2; co[i].blu = RGBHue[i].blu<<2; co[i].grn = RGBHue[i].grn<<2; } xScl =yScl = 1; X = x; Y = y; } void Bmp::SaveAs(char *F) { byte Pix; int x,y; char dummy; if (BmpFile != (char*)NULL) delete BmpFile; BmpFile = new char [strlen(F)+1]; strcpy(BmpFile,F); FILE *f=fopen(BmpFile,"wb"); fwrite(&bf,sizeof(bf),1,f); fwrite((char*)&bi,sizeof(bi),1,f); fwrite((char*)co,sizeof(ColorMap),ColMapSize,f); BitMask = 0; for(TotPix=0;TotPix<bi.BitCount;TotPix++) BitMask |= (1<<TotPix); TotPix = 8/bi.BitCount; Width = bi.Width; Width += (bi.BitCount==1) ? (32-bi.Width%32)%32:(8-bi.Width%8)%8; y=0; byte buffer[1024]; do { for (x=0;x<bi.Width;x++) buffer[x] = GetPixel(X+x,Y+bi.Height-y); fwrite(buffer,sizeof(char),bi.Width,f); y++; } while(y<bi.Height); fclose(f); } void Bmp::Scale(byte x,byte y) { xScl = (x>0) ? x:1; yScl = (y>0) ? y:1; } void Bmp::Spec() { gPrintf(600,510,"\n File Name %s",BmpFile); gPrintf(600,520,"\nbfType %c%c ",bf.Type[0],bf.Type[1]); gPrintf(600,530,"\nbfSize %u ",bf.Size); gPrintf(600,540,"\nbfReserved1 %d ",bf.Reserved1); gPrintf(600,550,"\nbfReserved2 %d ",bf.Reserved2); gPrintf(600,560,"\nbfOffBits %u ",bf.OffBits); gPrintf(600,570,"\n head Size %u %u %u",sizeof(bf),sizeof(bi),sizeof(BmpHeader)); gPrintf(600,580,"\nColMapSize %d ",ColMapSize); gPrintf(600,590,"\n\nBMP InfoStructure\n"); gPrintf(600,600,"\nbiSize %u",bi.Size); gPrintf(600,610,"\nbiWidth %u",bi.Width); gPrintf(600,620,"\nbiHeight %u",bi.Height); gPrintf(600,630,"\nbiPlanes %u",bi.Planes); gPrintf(600,640,"\nbiBitCount %u",bi.BitCount); gPrintf(600,650,"\nbiCompression %u",bi.Compression); gPrintf(600,660,"\nbiSizeImage %u",bi.SizeImage); gPrintf(600,670,"\nbiXPelsPerMeter %u",bi.XPelsPerMeter); gPrintf(600,680,"\nbiYPelsPerMeter %u",bi.YPelsPerMeter); gPrintf(600,690,"\nbiClrUsed %u",bi.ClrUsed); gPrintf(600,700,"\nbiClrImportant %u\n",bi.ClrImportant); } /*main()//int argc,char **argv) { Bmp A("C:\\windows\\setup.bmp"); Bmp B; ModeSearch(VgaCo1024x768x256); A.Spec(); A.Show(10,10); GetKey(); CloseGraph(); return 0; }*/
24.578182
96
0.536322
jerrythomas
52fedf855cee29964159c06128a9cbbb260055d4
4,121
hpp
C++
src/fft_plan.hpp
MartinK84/riesling
3deb01ef6ec4a03ecbd5cf694d37f20de063dbae
[ "MIT" ]
null
null
null
src/fft_plan.hpp
MartinK84/riesling
3deb01ef6ec4a03ecbd5cf694d37f20de063dbae
[ "MIT" ]
null
null
null
src/fft_plan.hpp
MartinK84/riesling
3deb01ef6ec4a03ecbd5cf694d37f20de063dbae
[ "MIT" ]
null
null
null
#pragma once #include "fft_plan.h" #include "tensorOps.h" namespace FFT { template <int TRank, int FRank> Plan<TRank, FRank>::Plan(Tensor &workspace, Log &log, long const nThreads) : dims_{workspace.dimensions()} , log_{log} , threaded_{nThreads > 1} { plan(workspace, nThreads); } template <int TRank, int FRank> Plan<TRank, FRank>::Plan(TensorDims const &dims, Log &log, long const nThreads) : dims_{dims} , log_{log} , threaded_{nThreads > 1} { Tensor ws(dims); plan(ws, nThreads); } template <int TRank, int FRank> void Plan<TRank, FRank>::plan(Tensor &ws, long const nThreads) { std::array<int, FRank> sizes; int N = 1; int Nvox = 1; // Process the two different kinds of dimensions - howmany / FFT { constexpr int FStart = TRank - FRank; int ii = 0; for (; ii < FStart; ii++) { N *= ws.dimension(ii); } for (; ii < TRank; ii++) { int const sz = ws.dimension(ii); Nvox *= sz; sizes[ii - FStart] = sz; phase_[ii - FStart] = FFT::Phase(sz); // Prep FFT phase factors } } scale_ = 1. / sqrt(Nvox); auto ptr = reinterpret_cast<fftwf_complex *>(ws.data()); log_.info(FMT_STRING("Planning {} {} FFTs with {} threads"), N, fmt::join(sizes, "x"), nThreads); // FFTW is row-major. Reverse dims as per // http://www.fftw.org/fftw3_doc/Column_002dmajor-Format.html#Column_002dmajor-Format std::reverse(sizes.begin(), sizes.end()); auto const start = log_.now(); fftwf_plan_with_nthreads(nThreads); forward_plan_ = fftwf_plan_many_dft( FRank, sizes.data(), N, ptr, nullptr, N, 1, ptr, nullptr, N, 1, FFTW_FORWARD, FFTW_MEASURE); reverse_plan_ = fftwf_plan_many_dft( FRank, sizes.data(), N, ptr, nullptr, N, 1, ptr, nullptr, N, 1, FFTW_BACKWARD, FFTW_MEASURE); if (forward_plan_ == NULL) { log_.fail("Could not create forward FFT plan"); } if (reverse_plan_ == NULL) { log_.fail("Could not create reverse FFT plan"); } log_.debug("FFT planning took {}", log_.toNow(start)); } template <int TRank, int FRank> Plan<TRank, FRank>::~Plan() { fftwf_destroy_plan(forward_plan_); fftwf_destroy_plan(reverse_plan_); } template <int TRank, int FRank> float Plan<TRank, FRank>::scale() const { return scale_; } template <int TRank, int FRank> void Plan<TRank, FRank>::applyPhase(Tensor &x, float const scale, bool const forward) const { constexpr int FStart = TRank - FRank; for (long ii = 0; ii < FRank; ii++) { Eigen::array<long, TRank> rsh, brd; for (long in = 0; in < TRank; in++) { rsh[in] = 1; brd[in] = x.dimension(in); } rsh[FStart + ii] = phase_[ii].dimension(0); brd[FStart + ii] = 1; if (threaded_) { if (forward) { x.device(Threads::GlobalDevice()) = x * phase_[ii].reshape(rsh).broadcast(brd); } else { x.device(Threads::GlobalDevice()) = x / phase_[ii].reshape(rsh).broadcast(brd); } } else { if (forward) { x = x * phase_[ii].reshape(rsh).broadcast(brd); } else { x = x / phase_[ii].reshape(rsh).broadcast(brd); } } } if (scale != 1.f) { if (threaded_) { x.device(Threads::GlobalDevice()) = x * x.constant(scale); } else { x = x * x.constant(scale); } } } template <int TRank, int FRank> void Plan<TRank, FRank>::forward(Tensor &x) const { for (long ii = 0; ii < TRank; ii++) { assert(x.dimension(ii) == dims_[ii]); } auto const start = log_.now(); applyPhase(x, 1.f, true); auto ptr = reinterpret_cast<fftwf_complex *>(x.data()); fftwf_execute_dft(forward_plan_, ptr, ptr); applyPhase(x, scale_, true); log_.debug("Forward FFT: {}", log_.toNow(start)); } template <int TRank, int FRank> void Plan<TRank, FRank>::reverse(Tensor &x) const { for (long ii = 0; ii < TRank; ii++) { assert(x.dimension(ii) == dims_[ii]); } auto start = log_.now(); applyPhase(x, scale_, false); auto ptr = reinterpret_cast<fftwf_complex *>(x.data()); fftwf_execute_dft(reverse_plan_, ptr, ptr); applyPhase(x, 1.f, false); log_.debug("Reverse FFT: {}", log_.toNow(start)); } } // namespace FFT
27.657718
99
0.626062
MartinK84
52ff3b850aa6f5584cbb5655594d55cdc14475a1
546
cpp
C++
Source/ActorPool/Private/PoolActor.cpp
Othereum/ActorPool
b5a8a874120017ddb09503fb3eafdb49e5b98363
[ "MIT" ]
6
2020-03-10T02:17:43.000Z
2022-03-25T10:27:29.000Z
Source/ActorPool/Private/PoolActor.cpp
Othereum/ActorPool
b5a8a874120017ddb09503fb3eafdb49e5b98363
[ "MIT" ]
null
null
null
Source/ActorPool/Private/PoolActor.cpp
Othereum/ActorPool
b5a8a874120017ddb09503fb3eafdb49e5b98363
[ "MIT" ]
null
null
null
// Copyright 2019 Seokjin Lee. All Rights Reserved. #include "PoolActor.h" #include "ActorPool.h" void APoolActor::Release(const bool bForce) { if (!bActivated && !bForce) return; SetActorTickEnabled(false); SetActorEnableCollision(false); SetActorHiddenInGame(true); bActivated = false; Pool->Release(this); OnReleased(); } void APoolActor::Activate(const bool bForce) { if (bActivated && !bForce) return; SetActorTickEnabled(true); SetActorEnableCollision(true); SetActorHiddenInGame(false); bActivated = true; OnActivated(); }
21
51
0.752747
Othereum
5e03f7f5683221fdaf0da88c1063cbb1fe849053
3,898
cpp
C++
src/protocol/http/uri.cpp
cysme/pump
d91cfdf3e09ebca1e90f0c1395a3b3fba1158a0c
[ "Apache-2.0" ]
2
2020-07-16T04:57:40.000Z
2020-11-24T10:33:48.000Z
src/protocol/http/uri.cpp
jimi36/pump
d91cfdf3e09ebca1e90f0c1395a3b3fba1158a0c
[ "Apache-2.0" ]
2
2020-12-23T09:40:16.000Z
2021-03-03T09:49:36.000Z
src/protocol/http/uri.cpp
cysme/pump
d91cfdf3e09ebca1e90f0c1395a3b3fba1158a0c
[ "Apache-2.0" ]
3
2020-11-24T10:33:35.000Z
2021-04-19T01:53:24.000Z
/* * Copyright (C) 2015-2018 ZhengHaiTao <ming8ren@163.com> * * 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 "pump/utils.h" #include "pump/protocol/http/uri.h" namespace pump { namespace protocol { namespace http { const std::string ut_strings[] = { "", "http", "https", "ws", "wss" }; std::string get_ut_string(int32_t ut) { return ut_strings[ut]; } bool parse_url(const std::string &url, int32_t &ut, std::string &host, std::string &path, std::map<std::string, std::string> &params) { std::string sut; { auto result = split_string(url, "[:]"); if (result.size() >= 2) { sut = result[0]; } else { sut = "https"; } } const block_t *p = url.c_str(); for (ut = URI_HTTP; ut < URI_END; ut++) { if (pump_strncasecmp(ut_strings[ut].c_str(), sut.c_str(), sut.size()) == 0) { p += ut_strings[ut].size(); break; } } if (ut == URI_END) { return false; } if (memcmp(p, "://", 3) != 0) { return false; } p += 3; const block_t *end = strstr(p, "/"); if (!end) { host.assign(p); path.assign("/"); return true; } host.assign(p, end); p = end; end = strstr(p, "?"); if (!end) { path.assign(p); return true; } path.assign(p, end); p = end + 1; std::string new_params; std::string raw_params(p); if (!url_decode(raw_params, new_params)) { return false; } auto kvs = split_string(new_params, "[=&]"); uint32_t cnt = (uint32_t)kvs.size(); if (cnt % 2 != 0) { return false; } for (uint32_t i = 0; i < cnt; i += 2) { params[kvs[i]] = kvs[i + 1]; } return true; } uri::uri() noexcept : ut_(UIR_NONE) { } uri::uri(const std::string &url) noexcept { parse(url); } void uri::reset() { ut_ = UIR_NONE; host_ = ""; path_ = ""; params_.clear(); } bool uri::parse(const std::string &url) { return parse_url(url, ut_, host_, path_, params_); } bool uri::get_param(const std::string &key, std::string &value) const { auto it = params_.find(key); if (it == params_.end()) { return false; } value = it->second; return true; } std::string uri::to_url() const { if (ut_ == UIR_NONE || ut_ == URI_END) { return std::string(); } std::string url; url = get_ut_string(ut_) + "://" + host_ + path_; std::vector<std::string> tmps; for (auto p : params_) { tmps.push_back(p.first + "=" + p.second); } if (!tmps.empty()) { url += "?" + join_strings(tmps, "&"); } std::string en_url; if (!url_encode(url, en_url)) { return std::string(); } return en_url; } } // namespace http } // namespace protocol } // namespace pump
24.670886
89
0.485121
cysme
5e0515da923a93bda2aa216137c981d4fb85206b
319
cpp
C++
Iniciante/URI 1013.cpp
wellmoot/UriOnlineJuge
8b367207f4544daae81f954f53b797b8a82d2133
[ "MIT" ]
null
null
null
Iniciante/URI 1013.cpp
wellmoot/UriOnlineJuge
8b367207f4544daae81f954f53b797b8a82d2133
[ "MIT" ]
null
null
null
Iniciante/URI 1013.cpp
wellmoot/UriOnlineJuge
8b367207f4544daae81f954f53b797b8a82d2133
[ "MIT" ]
null
null
null
#include <iostream> #include <stdlib.h> using namespace std; int main() { int a, b, c, maiorab, maiobc, maior; cin >> a >> b >> c; maiorab = (a + b + abs(a - b))/2; maiobc = (b + c + abs(b - c))/2; maior = (maiorab + maiobc + abs(maiorab - maiobc))/2; cout << maior << " eh o maior" << endl; }
24.538462
57
0.526646
wellmoot
5e060af528ae5dc70e1960cc003e7edfade4e194
5,779
cc
C++
src/vt/elm/elm_id_bits.cc
rbuch/vt
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
[ "BSD-3-Clause" ]
26
2019-11-26T08:36:15.000Z
2022-02-15T17:13:21.000Z
src/vt/elm/elm_id_bits.cc
rbuch/vt
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
[ "BSD-3-Clause" ]
1,215
2019-09-09T14:31:33.000Z
2022-03-30T20:20:14.000Z
src/vt/elm/elm_id_bits.cc
rbuch/vt
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
[ "BSD-3-Clause" ]
12
2019-09-08T00:03:05.000Z
2022-02-23T21:28:35.000Z
/* //@HEADER // ***************************************************************************** // // elm_id_bits.cc // DARMA/vt => Virtual Transport // // Copyright 2019-2021 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. // // 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 copyright holder 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. // // Questions? Contact darma@sandia.gov // // ***************************************************************************** //@HEADER */ #include "vt/elm/elm_id_bits.h" #include "vt/utils/bits/bits_common.h" #include "vt/objgroup/common.h" #include "vt/objgroup/proxy/proxy_bits.h" #include "vt/vrt/collection/balance/node_stats.h" namespace vt { namespace elm { /*static*/ ElementIDStruct ElmIDBits::createCollection( bool migratable, NodeType curr_node ) { auto const seq_id = theNodeStats()->getNextElm(); auto const home_node = theContext()->getNode(); return createCollectionImpl(migratable, seq_id, home_node, curr_node); } /*static*/ ElementIDStruct ElmIDBits::createCollectionImpl( bool migratable, ElementIDType seq_id, NodeType home_node, NodeType curr_node ) { ElementIDType ret = 0; setCollectionID(ret, migratable, seq_id, home_node); return ElementIDStruct{ret, curr_node}; } /*static*/ ElementIDStruct ElmIDBits::createObjGroup( ObjGroupProxyType proxy, NodeType node ) { ElementIDType ret = 0; setObjGroup(ret, proxy, node); auto const this_node = theContext()->getNode(); return ElementIDStruct{ret, this_node}; } /*static*/ ElementIDStruct ElmIDBits::createBareHandler(NodeType node) { ElementIDType ret = 0; BitPackerType::setField<eElmIDProxyBitsObjGroup::Control, num_control_bits>( ret, BareHandler ); constexpr auto num_node_bits = BitCounterType<NodeType>::value; BitPackerType::setField<eElmIDProxyBitsNonObjGroup::Node, num_node_bits>( ret, node ); return ElementIDStruct{ret, node}; } /*static*/ void ElmIDBits::setObjGroup( ElementIDType& id, ObjGroupProxyType proxy, NodeType node ) { BitPackerType::setField<eElmIDProxyBitsObjGroup::Control, num_control_bits>( id, ObjGroup ); objgroup::proxy::ObjGroupProxy::setNode(proxy, node); constexpr auto proxy_bits = BitCounterType<ObjGroupProxyType>::value - 2; BitPackerType::setField<eElmIDProxyBitsObjGroup::ObjGroupID, proxy_bits>( id, proxy ); } /*static*/ void ElmIDBits::setCollectionID( ElementIDType& id, bool migratable, ElementIDType seq_id, NodeType node ) { BitPackerType::setField<eElmIDProxyBitsNonObjGroup::Control2, num_control_bits>( id, migratable ? CollectionMigratable : CollectionNonMigratable ); constexpr auto num_node_bits = BitCounterType<NodeType>::value; BitPackerType::setField<eElmIDProxyBitsNonObjGroup::Node, num_node_bits>( id, node ); BitPackerType::setField<eElmIDProxyBitsNonObjGroup::ID, elm_id_num_bits>( id, seq_id ); } /*static*/ eElmIDControlBits ElmIDBits::getControlBits(ElementIDType id) { auto const n = num_control_bits; auto r = BitPackerType::getField<eElmIDProxyBitsObjGroup::Control, n, int>(id); return static_cast<eElmIDControlBits>(r); } /*static*/ bool ElmIDBits::isMigratable(ElementIDType id) { auto const ctrl = getControlBits(id); return not ( ctrl == BareHandler or ctrl == ObjGroup or ctrl == CollectionNonMigratable ); } /*static*/ NodeType ElmIDBits::getNode(ElementIDType id) { auto const ctrl = getControlBits(id); if (ctrl == ObjGroup) { auto const proxy = ElmIDBits::getObjGroupProxy(id, true); return objgroup::proxy::ObjGroupProxy::getNode(proxy); } else { constexpr auto num_node_bits = BitCounterType<NodeType>::value; return BitPackerType::getField< eElmIDProxyBitsNonObjGroup::Node, num_node_bits, NodeType >(id); } } /*static*/ ObjGroupProxyType ElmIDBits::getObjGroupProxy( ElementIDType id, bool include_node ) { constexpr auto proxy_bits = BitCounterType<ObjGroupProxyType>::value - 2; auto proxy = BitPackerType::getField< eElmIDProxyBitsObjGroup::ObjGroupID, proxy_bits, ObjGroupProxyType >(id); if (not include_node) { objgroup::proxy::ObjGroupProxy::setNode(proxy, 0); } return proxy; } }} /* end namespace vt::elm */
36.808917
82
0.725731
rbuch
5e06b9b826daed5b9762f2d3de78e595b74df6a1
1,313
hpp
C++
osm2pgsql/src/pgsql-helper.hpp
traitor6789/osm-tile-server
bddcfabee825c0e176d2037cad9c6cf06895beb8
[ "Apache-2.0" ]
null
null
null
osm2pgsql/src/pgsql-helper.hpp
traitor6789/osm-tile-server
bddcfabee825c0e176d2037cad9c6cf06895beb8
[ "Apache-2.0" ]
null
null
null
osm2pgsql/src/pgsql-helper.hpp
traitor6789/osm-tile-server
bddcfabee825c0e176d2037cad9c6cf06895beb8
[ "Apache-2.0" ]
null
null
null
#ifndef OSM2PGSQL_PGSQL_HELPER_HPP #define OSM2PGSQL_PGSQL_HELPER_HPP /** * SPDX-License-Identifier: GPL-2.0-or-later * * This file is part of osm2pgsql (https://osm2pgsql.org/). * * Copyright (C) 2006-2022 by the osm2pgsql developer community. * For a full list of authors see the git log. */ #include "osmtypes.hpp" #include <string> class pg_conn_t; class pg_result_t; /** * Iterate over the result from a pgsql query and generate a list of all the * ids from the first column. * * \param result The result to iterate over. * \returns A list of ids. */ idlist_t get_ids_from_result(pg_result_t const &result); idlist_t get_ids_from_db(pg_conn_t const *db_connection, char const *stmt, osmid_t id); void create_geom_check_trigger(pg_conn_t *db_connection, std::string const &schema, std::string const &table, std::string const &geom_column); void drop_geom_check_trigger(pg_conn_t *db_connection, std::string const &schema, std::string const &table); void analyze_table(pg_conn_t const &db_connection, std::string const &schema, std::string const &name); #endif // OSM2PGSQL_PGSQL_HELPER_HPP
28.543478
77
0.647372
traitor6789
5e09b2450d47e1d64e3ffd18f678a7a25bab70cf
707
cpp
C++
Code/Score/Score.cpp
4rlenrey/JumpHigh
af5f24c8b8fd2c46bb80f3b3e9755b419964d3da
[ "MIT" ]
8
2020-09-23T19:32:48.000Z
2022-01-18T16:43:47.000Z
Code/Score/Score.cpp
Haranoi17/JumpHigh
3cd5e47fb991d828e0843cf3bfb05511d2da7f9e
[ "MIT" ]
null
null
null
Code/Score/Score.cpp
Haranoi17/JumpHigh
3cd5e47fb991d828e0843cf3bfb05511d2da7f9e
[ "MIT" ]
5
2020-09-23T19:32:51.000Z
2022-03-11T06:18:07.000Z
#include "Score/Score.h" #include "GameObject/GameObject.hpp" #include <string> #include <SFML/Graphics.hpp> sf::Font Score::font; Score::Score(GameObject& player, sf::View& viev) : _playerS{player}, _viewS{viev} { _score = 0; text.setString("0"); text.setFont(font); text.setPosition(100, 500); text.setCharacterSize(35); text.setStyle(sf::Text::Bold); text.setFillColor(sf::Color::White); } void Score::update() { s = "Score: "; s.append(std::to_string(_score)); if (_score < -(_playerS.getPosition().y)) _score = -(_playerS.getPosition().y); text.setString(s); text.setPosition(10, _viewS.getCenter().y - 350); }
22.806452
56
0.618105
4rlenrey
5e0ab6796a85c1e80e991c232a4bdef1807a280e
1,353
cpp
C++
codeforces/C - Fly/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/C - Fly/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/C - Fly/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Jul/27/2018 15:45 * solution_verdict: Accepted language: GNU C++14 * run_time: 31 ms memory_used: 200 KB * problem: https://codeforces.com/contest/1011/problem/C ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e3; int n; double pay,a[N+2],b[N+2]; bool ok(double xx) { xx-=((pay+xx)/a[1]); if(xx<0.0)return false; for(int i=2;i<=n;i++) { xx-=((pay+xx)/b[i]); if(xx<0.0)return false; xx-=((pay+xx)/a[i]); if(xx<0.0)return false; } xx-=((pay+xx)/b[1]); if(xx<0.0)return false; return true; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin>>n>>pay; for(int i=1;i<=n;i++) cin>>a[i]; for(int i=1;i<=n;i++) cin>>b[i]; double lo=0.0,hi=1000000000.0+100.0,md; for(int i=1;i<=100;i++) { md=(lo+hi)/2.0; if(ok(md))hi=md; else lo=md; } if(md>1000000000.0)cout<<-1<<endl; else cout<<setprecision(10)<<fixed<<md<<endl; return 0; }
28.787234
111
0.424242
kzvd4729
5e0b663a20e9d6da64d139f638dac59a3d3933af
1,483
cpp
C++
src/rewrite_pooling.cpp
pruthvistony/AMDMIGraphX
cf85b4c65d89b634fc50d586385c73839bb59bd0
[ "MIT" ]
null
null
null
src/rewrite_pooling.cpp
pruthvistony/AMDMIGraphX
cf85b4c65d89b634fc50d586385c73839bb59bd0
[ "MIT" ]
null
null
null
src/rewrite_pooling.cpp
pruthvistony/AMDMIGraphX
cf85b4c65d89b634fc50d586385c73839bb59bd0
[ "MIT" ]
null
null
null
#include <migraphx/rewrite_pooling.hpp> #include <migraphx/instruction.hpp> #include <migraphx/iterator_for.hpp> #include <migraphx/op/pooling.hpp> #include <migraphx/op/reshape.hpp> #include <migraphx/op/reduce_mean.hpp> #include <migraphx/program.hpp> namespace migraphx { inline namespace MIGRAPHX_INLINE_NS { void rewrite_pooling::apply(program& prog) const { for(auto ins : iterator_for(prog)) { if(ins->name() != "pooling") continue; if(ins->get_shape().lens().size() != 4) continue; if(ins->inputs().empty()) continue; auto&& s = ins->inputs().front()->get_shape(); if(not s.standard()) continue; auto&& op = any_cast<op::pooling>(ins->get_operator()); if(op.mode != "average") continue; if(op.padding[0] != 0 and op.padding[1] != 0) continue; if(op.stride[0] != 1 and op.stride[1] != 1) continue; if(s.lens()[2] != op.lengths[0] and s.lens()[3] != op.lengths[1]) continue; std::int64_t n = s.lens()[0]; std::int64_t c = s.lens()[1]; auto reshape = prog.insert_instruction(ins, op::reshape{{n * c, -1}}, ins->inputs().front()); auto pooling = prog.insert_instruction(ins, op::reduce_mean{{1}}, reshape); prog.replace_instruction(ins, op::reshape{{n, c, 1, 1}}, pooling); } } } // namespace MIGRAPHX_INLINE_NS } // namespace migraphx
32.955556
90
0.582603
pruthvistony
5e0bbd8b606f5f0fefed96f290e420d702ea993e
470
cpp
C++
sk4d/src/c/sk4d_svgcanvas.cpp
skia4delphi/skia
64806a3b12c226fb57d6befc4c0df5443533d220
[ "BSD-3-Clause" ]
5
2022-02-12T07:52:56.000Z
2022-03-10T23:55:51.000Z
sk4d/src/c/sk4d_svgcanvas.cpp
skia4delphi/skia
64806a3b12c226fb57d6befc4c0df5443533d220
[ "BSD-3-Clause" ]
null
null
null
sk4d/src/c/sk4d_svgcanvas.cpp
skia4delphi/skia
64806a3b12c226fb57d6befc4c0df5443533d220
[ "BSD-3-Clause" ]
2
2022-02-12T07:52:59.000Z
2022-03-03T03:06:23.000Z
/* * Copyright (c) 2011-2022 Google LLC. * Copyright (c) 2021-2022 Skia4Delphi Project. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/c/sk4d_svgcanvas.h" #include "src/c/sk4d_mapping.h" sk_canvas_t* sk4d_svgcanvas_make(const sk_rect_t* bounds, sk_wstream_t* w_stream, uint32_t flags) { return ToCanvas(SkSVGCanvas::Make(AsRect(*bounds), AsWStream(w_stream), flags).release()); }
31.333333
99
0.738298
skia4delphi
5e158800f0164ed23a9b6094b72b761bd164f377
1,710
cpp
C++
examples/example3.cpp
mambaru/wjson
48de30f1247564ab16c93fc824a14b182145ff90
[ "MIT" ]
21
2016-09-29T10:25:12.000Z
2020-07-07T23:19:51.000Z
examples/example3.cpp
mambaru/wjson
48de30f1247564ab16c93fc824a14b182145ff90
[ "MIT" ]
10
2016-11-17T09:09:35.000Z
2021-10-03T11:47:18.000Z
examples/example3.cpp
mambaru/wjson
48de30f1247564ab16c93fc824a14b182145ff90
[ "MIT" ]
6
2016-09-29T12:05:06.000Z
2022-02-17T13:05:18.000Z
#include <wjson/json.hpp> #include <iostream> #include <cstring> int main() { const char* english = "\"hello world!\""; const char* russian = "\"\\u041F\\u0440\\u0438\\u0432\\u0435\\u0442\\u0020\\u043C\\u0438\\u0440\\u0021\""; const char* chinese = "\"\\u4E16\\u754C\\u4F60\\u597D!\""; typedef char str_t[128]; typedef ::wjson::value< std::string, 128 >::serializer sser_t; typedef ::wjson::value< std::vector<char> >::serializer vser_t; typedef ::wjson::value< str_t >::serializer aser_t; std::string sstr; std::vector<char> vstr; str_t astr={'\0'}; // Десериализация sser_t()( sstr, english, english + std::strlen(english), fas_nullptr); vser_t()( vstr, russian, russian + std::strlen(russian), fas_nullptr); aser_t()( astr, chinese, chinese + std::strlen(chinese), fas_nullptr); // Результат std::cout << "English: " << sstr << "\tfrom JSON: " << english << std::endl; std::cout << "Russian: " << std::string(vstr.begin(), vstr.end() ) << "\tfrom JSON: " << russian << std::endl; std::cout << "Chinese: " << astr << "\tfrom JSON: " << chinese << std::endl; // Сериализация english в stdout std::cout << std::endl << "English JSON: "; sser_t()( sstr, std::ostream_iterator<char>( std::cout) ); std::cout << "\tfrom: " << sstr; // Сериализация russian в stdout std::cout << std::endl << "Russian JSON: "; vser_t()( vstr, std::ostream_iterator<char>( std::cout) ); std::cout << "\tfrom: " << std::string(vstr.begin(), vstr.end() ); // Сериализация chinese в stdout std::cout << std::endl << "Chinese JSON: "; aser_t()( astr, std::ostream_iterator<char>( std::cout) ); std::cout << "\tfrom: " << astr; std::cout << std::endl; }
37.173913
112
0.615205
mambaru
5e15f4b108695d25722984aff32f1d1168600923
4,833
cpp
C++
src/hardware/encoders/quadraturecounter.cpp
Bormachine-Learning/embedded
165daf847fe9c2a7bcc17c7aee4c5e28b3cf4055
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/hardware/encoders/quadraturecounter.cpp
Bormachine-Learning/embedded
165daf847fe9c2a7bcc17c7aee4c5e28b3cf4055
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/hardware/encoders/quadraturecounter.cpp
Bormachine-Learning/embedded
165daf847fe9c2a7bcc17c7aee4c5e28b3cf4055
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/** Copyright 2019 Bosch Engineering Center Cluj and BFMC organizers 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 quadratureencoder.cpp * @author RBRO/PJ-IU * @brief * @version 0.1 * @date 2018-10-23 * * @copyright Copyright (c) 2018 * */ #include <hardware/encoders/quadraturecounter.hpp> namespace hardware::drivers{ CQuadratureCounter_TIM4 *CQuadratureCounter_TIM4::m_instance = 0; CQuadratureCounter_TIM4::CQuadratureCounter_TIM4_Destroyer CQuadratureCounter_TIM4::m_destroyer; /** * @brief Setter function for the singelton object. * * @param pSingObj - singleton object address */ void CQuadratureCounter_TIM4::CQuadratureCounter_TIM4_Destroyer::SetSingleton(CQuadratureCounter_TIM4* pSingObj){ m_singleton = pSingObj; } /** * @brief Destroy the singelton object. * */ CQuadratureCounter_TIM4::CQuadratureCounter_TIM4_Destroyer::~CQuadratureCounter_TIM4_Destroyer(){ delete m_singleton; } /** * @brief * It verifies the existence of the singleton object. It creates a new instance when it's necessary and return the address of instance. * It initializes all parameter by appling method 'initialize'. * * @return The address of the singleton object */ CQuadratureCounter_TIM4* CQuadratureCounter_TIM4::Instance(){ if(!CQuadratureCounter_TIM4::m_instance){ CQuadratureCounter_TIM4::m_instance = new CQuadratureCounter_TIM4; m_instance->initialize(); CQuadratureCounter_TIM4::m_destroyer.SetSingleton(m_instance); } return CQuadratureCounter_TIM4::m_instance; } /** * @brief Initialize the parameter of the object. * * It configures all register, for timer TIM4 decodes the quadrature encoder signal. */ void CQuadratureCounter_TIM4::initialize(){ //PB6 PB7 aka D10 MORPHO_PB7 // Enable clock for GPIOA RCC->AHB1ENR |= RCC_AHB1ENR_GPIOBEN; //stm32f4xx.h GPIOB->MODER |= GPIO_MODER_MODER6_1 | GPIO_MODER_MODER7_1; //PB6 & PB7 as Alternate Function /*!< GPIO port mode register, Address offset: 0x00 */ GPIOB->OTYPER |= GPIO_OTYPER_OT_6 | GPIO_OTYPER_OT_7; //PB6 & PB7 as Inputs /*!< GPIO port output type register, Address offset: 0x04 */ GPIOB->OSPEEDR |= GPIO_OSPEEDER_OSPEEDR6 | GPIO_OSPEEDER_OSPEEDR7; //Low speed /*!< GPIO port output speed register, Address offset: 0x08 */ GPIOB->PUPDR |= GPIO_PUPDR_PUPDR6_1 | GPIO_PUPDR_PUPDR7_1; //Pull Down /*!< GPIO port pull-up/pull-down register, Address offset: 0x0C */ GPIOB->AFR[0] |= 0x22000000; //AF02 for PB6 & PB7 /*!< GPIO alternate function registers, Address offset: 0x20-0x24 */ GPIOB->AFR[1] |= 0x00000000; //nibbles here refer to gpio8..15 /*!< GPIO alternate function registers, Address offset: 0x20-0x24 */ // configure TIM4 as Encoder input // Enable clock for TIM4 // __TIM4_CLK_ENABLE(); RCC->APB1ENR |= RCC_APB1ENR_TIM4EN; TIM4->CR1 = 0x0001; // CEN(Counter ENable)='1' < TIM control register 1 TIM4->SMCR = TIM_ENCODERMODE_TI12; // < TIM slave mode control register //TIM_ENCODERMODE_TI1 input 1 edges trigger count //TIM_ENCODERMODE_TI2 input 2 edges trigger count //TIM_ENCODERMODE_TI12 all edges trigger count TIM4->CCMR1 = 0xF1F1; // CC1S='01' CC2S='01' < TIM capture/compare mode register 1 //0xF nibble sets up filter TIM4->CCMR2 = 0x0000; // < TIM capture/compare mode register 2 TIM4->CCER = TIM_CCER_CC1E | TIM_CCER_CC2E; // < TIM capture/compare enable register TIM4->PSC = 0x0000; // Prescaler = (0+1) < TIM prescaler TIM4->ARR = 0xffff; // reload at 0xfffffff < TIM auto-reload register TIM4->CNT = 0x0000; //reset the counter before we use it } /** * @brief Get the position of encoder. * * It returns the last counted value by the timer. * */ int16_t CQuadratureCounter_TIM4::getCount(){ return TIM4->CNT; } /** * @brief Reset the value of the counter to zero value. */ void CQuadratureCounter_TIM4::reset(){ TIM4->CNT = 0; } }; // namespace hardware::drivers
38.357143
178
0.671633
Bormachine-Learning
5e18d4c6e941dd29af5ab99b246c9dfd9e63beb2
12,511
cpp
C++
src/ompl/base/spaces/src/ClothoidStateSpace.cpp
tigerk0430/DesiredOrientationRRT
c62a9cf2c472380937d0a0ab379b5f9140767f51
[ "BSD-3-Clause" ]
2
2018-07-08T11:56:04.000Z
2019-02-14T12:14:35.000Z
src/ompl/base/spaces/src/ClothoidStateSpace.cpp
edward0im/DesiredOrientationRRT
c62a9cf2c472380937d0a0ab379b5f9140767f51
[ "BSD-3-Clause" ]
1
2019-08-03T03:42:55.000Z
2019-08-03T03:42:55.000Z
src/ompl/base/spaces/src/ClothoidStateSpace.cpp
edward0im/DesiredOrientationRRT
c62a9cf2c472380937d0a0ab379b5f9140767f51
[ "BSD-3-Clause" ]
2
2018-06-11T00:49:39.000Z
2018-10-03T07:09:30.000Z
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Rice University * 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 Rice University 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: Seho Shin */ #include "ompl/base/spaces/ClothoidStateSpace.h" #include "ompl/base/SpaceInformation.h" #include "ompl/util/Exception.h" #include <queue> #include <boost/math/constants/constants.hpp> #include "ompl/tools/config/MagicConstants.h" #include <cstring> using namespace std; using namespace ompl::base; namespace { const double twopi = 2. * boost::math::constants::pi<double>(); const double pi = boost::math::constants::pi<double>(); const double CLOTHOID_ZERO = -1e-9; //[0~2pi] double conv2pi(double x){ x = fmod(x,twopi); if (x < 0) x += twopi; return x; } //[-pi,pi] double convpi(double x){ x = fmod(x + pi,twopi); if (x < 0) x += twopi; return x - pi; } inline double mod2pi(double x) { if (x<0 && x>CLOTHOID_ZERO) return 0; return x - twopi * floor(x / twopi); } }; ompl::base::State* ompl::base::ClothoidStateSpace::allocState() const { StateType *state = new StateType(); allocStateComponents(state); return state; } void ompl::base::ClothoidStateSpace::freeState(State *state) const { CompoundStateSpace::freeState(state); } void ompl::base::ClothoidStateSpace::registerProjections() { class ClothoidDefaultProjection : public ProjectionEvaluator { public: ClothoidDefaultProjection(const StateSpace *space) : ProjectionEvaluator(space) { } virtual unsigned int getDimension() const { return 2; } virtual void defaultCellSizes() { cellSizes_.resize(2); bounds_ = space_->as<ClothoidStateSpace>()->getBounds(); cellSizes_[0] = (bounds_.high[0] - bounds_.low[0]) / magic::PROJECTION_DIMENSION_SPLITS; cellSizes_[1] = (bounds_.high[1] - bounds_.low[1]) / magic::PROJECTION_DIMENSION_SPLITS; //cellSizes_[2] = (bounds_.high[2] - bounds_.low[2]) / magic::PROJECTION_DIMENSION_SPLITS; } virtual void project(const State *state, EuclideanProjection &projection) const { memcpy(&projection(0), state->as<ClothoidStateSpace::StateType>()->as<RealVectorStateSpace::StateType>(0)->values, 2* sizeof(double)); } }; registerDefaultProjection(ProjectionEvaluatorPtr(dynamic_cast<ProjectionEvaluator*>(new ClothoidDefaultProjection(this)))); } double ompl::base::ClothoidStateSpace::distance(const State *state1, const State *state2) const { double W0 = weight_[0]; double W1 = weight_[1]; double W2 = weight_[2]; const StateType *s1 = static_cast<const StateType*>(state1); const StateType *s2 = static_cast<const StateType*>(state2); double x1 = s1->getX(), y1 = s1->getY(), th1 = s1->getYaw(); double x2 = s2->getX(), y2 = s2->getY(), th2 = s2->getYaw(); if( x1 == x2 && y1 == y2 && th1 == th2 ) return 0.; if( !CheckRange(s1, s2) ) return 99999.0; if (isReversable_) { ClothoidPath pathForward = clothoid(state1, state2); ClothoidPath pathReverse = clothoid(state2, state1); //When searching in the forward direction, it should be compared with the // curvature of the first node of the candidate clothoid. double clothoid_k = pathForward.k_; double clothoid_l = pathForward.length(); double costF = W0*clothoid_l + W1*fabs(s1->getK()-clothoid_k); //When searching in the reverse direction, it should be compared with //the curvature of the last node of the candidate clothoid. clothoid_k = pathReverse.k_+pathReverse.dk_*pathReverse.l_; clothoid_l = pathReverse.length(); double costR = W2*(W0*clothoid_l + W1*fabs(s1->getK()-clothoid_k)); return std::min(costF, costR); } else { ClothoidPath path = clothoid(state1, state2); return W0*path.length()+W1*fabs(s1->getK()-path.k_); } } void ompl::base::ClothoidStateSpace::interpolate(const State *from, const State *to, const double t, State *state) const { bool firstTime = true; Clothoid::ClothoidCurve cc; ClothoidPath path(cc); interpolate(from, to, t, firstTime, path, state); } void ompl::base::ClothoidStateSpace::interpolate(const State *from, const State *to, const double t, bool &firstTime, ClothoidPath &path, State *state) const { if (firstTime) { if (t>=1.) { if (to != state) copyState(state, to); return; } if (t<=0.) { if (from != state) copyState(state, from); return; } path = clothoid(from, to); if (isReversable_) // should be true in vehicle case - commented by shinsh { double W0 = weight_[0]; double W1 = weight_[1]; double W2 = weight_[2]; ClothoidPath path2(clothoid(to, from)); const StateType *s1 = static_cast<const StateType*>(from); double costF = W0*path.length()+W1*fabs(s1->getK()-path.k_); double rev_k = path2.k_+path2.dk_*path2.l_; double costR = (W0*path2.length()+W1*fabs(s1->getK()-rev_k))*W2; if (costR < costF) { path2.reverse_ = true; path = path2; } } firstTime = false; } //const StateType *s1 = static_cast<const StateType*>(from); //const StateType *s2 = static_cast<const StateType*>(to); //cout << s1->getX() << " " << s1->getY() << " " <<s1->getYaw()<< endl; //cout << s2->getX() << " " << s2->getY() << " " <<s2->getYaw()<< endl; interpolate(from, path, t, state); } void ompl::base::ClothoidStateSpace::interpolate(const State *from, const ClothoidPath &path, double t, State *state) const { StateType *s = allocState()->as<StateType>(); double seg = t * path.length(); Clothoid::valueType theta; Clothoid::valueType kappa; Clothoid::valueType x; Clothoid::valueType y; if (path.reverse_) { seg = path.length()-seg; path.cc_.eval(seg, theta, kappa, x, y); // state->as<StateType>()->setYaw(conv2pi(conv2pi(theta)-pi)); } else { path.cc_.eval(seg, theta, kappa, x, y); } state->as<StateType>()->setX(x); state->as<StateType>()->setY(y); getSubspace(1)->enforceBounds(s->as<SO2StateSpace::StateType>(1)); state->as<StateType>()->setYaw(theta); state->as<StateType>()->setK(kappa); freeState(s); //cout << x << " " << y << " " <<theta << endl; //getchar(); } ompl::base::ClothoidStateSpace::ClothoidPath ompl::base::ClothoidStateSpace::clothoid(const State *state1, const State *state2) const { Clothoid::ClothoidCurve cc; const StateType *s1 = static_cast<const StateType*>(state1); const StateType *s2 = static_cast<const StateType*>(state2); double x1 = s1->getX(), y1 = s1->getY(), th1 = convpi(s1->getYaw()); double x2 = s2->getX(), y2 = s2->getY(), th2 = convpi(s2->getYaw()); // cout << x1 << " " << y1 << " " << th1 << " " << x2 <<" " << y2 << " " << // th2 << endl; cc.setup_G1(x1, y1, th1, x2, y2, th2); ompl::base::ClothoidStateSpace::ClothoidPath path(cc); return path; } bool ompl::base::ClothoidStateSpace::CheckRange(const State *state1, const State *state2) const { const StateType *s1 = static_cast<const StateType*>(state1); const StateType *s2 = static_cast<const StateType*>(state2); double x1 = s1->getX(), y1 = s1->getY(); double x2 = s2->getX(), y2 = s2->getY(); if( sqrt( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)) < 1.0 ) { return false; } else { return true; } } void ompl::base::ClothoidMotionValidator::defaultSettings() { stateSpace_ = dynamic_cast<ClothoidStateSpace*>(si_->getStateSpace().get()); if (!stateSpace_) throw Exception("No state space for motion validator"); } bool ompl::base::ClothoidMotionValidator::checkMotion(const State *s1, const State *s2, std::pair<State*, double> &lastValid) const { /* assume motion starts in a valid configuration so s1 is valid */ if( !stateSpace_->CheckRange(s1, s2) ) return false; bool result = true, firstTime = true; Clothoid::ClothoidCurve cc; ClothoidStateSpace::ClothoidPath path(cc); int nd = stateSpace_->validSegmentCount(s1, s2); nd = 30; if (nd > 1) { /* temporary storage for the checked state */ State *test = si_->allocState(); for (int j = 1 ; j < nd ; ++j) { stateSpace_->interpolate(s1, s2, (double)j / (double)nd, firstTime, path, test); if (!si_->isValid(test)) { lastValid.second = (double)(j - 1) / (double)nd; if (lastValid.first) stateSpace_->interpolate(s1, s2, lastValid.second, firstTime, path, lastValid.first); result = false; break; } } si_->freeState(test); } if (result) if (!si_->isValid(s2)) { lastValid.second = (double)(nd - 1) / (double)nd; if (lastValid.first) stateSpace_->interpolate(s1, s2, lastValid.second, firstTime, path, lastValid.first); result = false; } if (result) valid_++; else invalid_++; return result; } bool ompl::base::ClothoidMotionValidator::checkMotion(const State *s1, const State *s2) const { /* assume motion starts in a valid configuration so s1 is valid */ if( !stateSpace_->CheckRange(s1, s2) ) return false; // if (!si_->isValid(s2)) // return false; bool result = true, firstTime = true; Clothoid::ClothoidCurve cc; ClothoidStateSpace::ClothoidPath path(cc); int nd = stateSpace_->validSegmentCount(s1, s2); nd = 30; /* initialize the queue of test positions */ std::queue< std::pair<int, int> > pos; if (nd >= 2) { pos.push(std::make_pair(1, nd - 1)); /* temporary storage for the checked state */ State *test = si_->allocState(); /* repeatedly subdivide the path segment in the middle (and check the middle) */ while (!pos.empty()) { std::pair<int, int> x = pos.front(); int mid = (x.first + x.second) / 2; stateSpace_->interpolate(s1, s2, (double)mid / (double)nd, firstTime, path, test); if (!si_->isValid(test)) { result = false; break; } pos.pop(); if (x.first < mid) pos.push(std::make_pair(x.first, mid - 1)); if (x.second > mid) pos.push(std::make_pair(mid + 1, x.second)); } si_->freeState(test); } if (result) valid_++; else invalid_++; return result; }
30.002398
131
0.612101
tigerk0430
5e1f2bdb10af46655c7ae0d0e833e37590f2da07
4,584
cpp
C++
archive/stan/src/test/unit/lang/generator/generate_var_type_test.cpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
archive/stan/src/test/unit/lang/generator/generate_var_type_test.cpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
archive/stan/src/test/unit/lang/generator/generate_var_type_test.cpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
null
null
null
#include <stan/lang/ast_def.cpp> #include <stan/lang/generator.hpp> #include <test/unit/lang/utility.hpp> #include <gtest/gtest.h> #include <iostream> #include <sstream> TEST(langGenerator, genRealVars) { using stan::lang::scope; using stan::lang::transformed_data_origin; using stan::lang::function_argument_origin; scope td_origin = transformed_data_origin; scope fun_origin = function_argument_origin; std::stringstream o; o.str(std::string()); stan::lang::generate_real_var_type(td_origin, true, o); EXPECT_EQ(1, count_matches("local_scalar_t__", o.str())); o.str(std::string()); stan::lang::generate_real_var_type(td_origin, false, o); EXPECT_EQ(1, count_matches("double", o.str())); o.str(std::string()); stan::lang::generate_real_var_type(fun_origin, true, o); EXPECT_EQ(1, count_matches("local_scalar_t__", o.str())); o.str(std::string()); stan::lang::generate_real_var_type(fun_origin, false, o); EXPECT_EQ(1, count_matches("local_scalar_t__", o.str())); } TEST(langGenerator, genArrayVars) { using stan::lang::bare_expr_type; using stan::lang::int_type; using stan::lang::double_type; using stan::lang::vector_type; using stan::lang::row_vector_type; using stan::lang::matrix_type; using stan::lang::scope; using stan::lang::transformed_data_origin; using stan::lang::function_argument_origin; scope td_origin = transformed_data_origin; scope fun_origin = function_argument_origin; std::stringstream ssReal; std::stringstream o; ssReal.str(std::string()); stan::lang::generate_real_var_type(td_origin, true, ssReal); o.str(std::string()); stan::lang::generate_bare_type(bare_expr_type(double_type()),ssReal.str(),o); EXPECT_EQ(1, count_matches("local_scalar_t__", o.str())); ssReal.str(std::string()); stan::lang::generate_real_var_type(td_origin, false, ssReal); o.str(std::string()); stan::lang::generate_bare_type(bare_expr_type(double_type()),ssReal.str(),o); EXPECT_EQ(1, count_matches("double", o.str())); ssReal.str(std::string()); stan::lang::generate_real_var_type(fun_origin, true, ssReal); o.str(std::string()); stan::lang::generate_bare_type(bare_expr_type(double_type()),ssReal.str(),o); EXPECT_EQ(1, count_matches("local_scalar_t__", o.str())); ssReal.str(std::string()); o.str(std::string()); stan::lang::generate_real_var_type(fun_origin, false, ssReal); stan::lang::generate_bare_type(bare_expr_type(double_type()),ssReal.str(),o); EXPECT_EQ(1, count_matches("local_scalar_t__", o.str())); ssReal.str(std::string()); o.str(std::string()); stan::lang::generate_bare_type(bare_expr_type(int_type()), ssReal.str(), o); EXPECT_EQ(1, count_matches("int", o.str())); ssReal.str(std::string()); stan::lang::generate_real_var_type(td_origin, false, ssReal); o.str(std::string()); stan::lang::generate_bare_type(bare_expr_type(vector_type()),ssReal.str(),o); EXPECT_EQ(1, count_matches("Eigen::Matrix<double, Eigen::Dynamic, 1>", o.str())); ssReal.str(std::string()); stan::lang::generate_real_var_type(td_origin, true, ssReal); o.str(std::string()); stan::lang::generate_bare_type(bare_expr_type(vector_type()), ssReal.str(), o); EXPECT_EQ(1, count_matches("Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, 1>", o.str())); ssReal.str(std::string()); stan::lang::generate_real_var_type(td_origin, false, ssReal); o.str(std::string()); stan::lang::generate_bare_type(bare_expr_type(row_vector_type()), ssReal.str(), o); EXPECT_EQ(1, count_matches("Eigen::Matrix<double, 1, Eigen::Dynamic>", o.str())); ssReal.str(std::string()); stan::lang::generate_real_var_type(td_origin, true, ssReal); o.str(std::string()); stan::lang::generate_bare_type(bare_expr_type(row_vector_type()), ssReal.str(), o); EXPECT_EQ(1, count_matches("Eigen::Matrix<local_scalar_t__, 1, Eigen::Dynamic>", o.str())); ssReal.str(std::string()); stan::lang::generate_real_var_type(td_origin, false, ssReal); o.str(std::string()); stan::lang::generate_bare_type(bare_expr_type(matrix_type()), ssReal.str(), o); EXPECT_EQ(1, count_matches("Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>", o.str())); ssReal.str(std::string()); stan::lang::generate_real_var_type(td_origin, true, ssReal); o.str(std::string()); stan::lang::generate_bare_type(bare_expr_type(matrix_type()), ssReal.str(), o); EXPECT_EQ(1, count_matches("Eigen::Matrix<local_scalar_t__, Eigen::Dynamic, Eigen::Dynamic>", o.str())); }
40.928571
107
0.701134
alashworth
5e2b5db8d93beff17ec7b4da13672621d6220061
115
cpp
C++
Test.cpp
KaikiasVind/CellBadger
c21adf5feec7766decfd4d89a110364d4bdfbc46
[ "MIT" ]
null
null
null
Test.cpp
KaikiasVind/CellBadger
c21adf5feec7766decfd4d89a110364d4bdfbc46
[ "MIT" ]
null
null
null
Test.cpp
KaikiasVind/CellBadger
c21adf5feec7766decfd4d89a110364d4bdfbc46
[ "MIT" ]
null
null
null
#include "Test.h" #include <QDebug> Test::Test() { } void Test::on_finished() { qDebug() << "Finished."; }
8.846154
28
0.573913
KaikiasVind
5e2f3a8738055071a9123ebfcca4d9e39eb96f24
708
cpp
C++
test/concurrent/test_stack_lockfree_elim_hp_stress.cpp
clearlycloudy/concurrent
243246f3244cfaf7ffcbfc042c69980d96f988e4
[ "MIT" ]
9
2019-05-14T01:07:08.000Z
2020-11-12T01:46:11.000Z
test/concurrent/test_stack_lockfree_elim_hp_stress.cpp
clearlycloudy/concurrent
243246f3244cfaf7ffcbfc042c69980d96f988e4
[ "MIT" ]
null
null
null
test/concurrent/test_stack_lockfree_elim_hp_stress.cpp
clearlycloudy/concurrent
243246f3244cfaf7ffcbfc042c69980d96f988e4
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include <thread> #include <vector> #include <iostream> #include <mutex> #include <set> #include "catch.hpp" #include "stack_lockfree_elim.hpp" #include "stress_pool.hpp" using namespace std; TEST_CASE( "stack_lockfree_total_simple stress", "[stress]" ) { using container_type = stack_lockfree_elim<int, trait_reclamation::hp>; container_type p; unsigned int num_threads = std::thread::hardware_concurrency()/2; bool force_put_get = true; stress_pool::stress_put_get_int<container_type, container_type::mem_reclam>( num_threads, p, force_put_get ); assert(p.check_elimination()); }
30.782609
113
0.748588
clearlycloudy
5e308377c063b426e6c5949b3a447edd4a5a4046
84
hpp
C++
TosVolume/Utils.hpp
laoo/tcmdtos
6aa91f2e2bfe462cda8f74b5170bc52136157915
[ "MIT" ]
null
null
null
TosVolume/Utils.hpp
laoo/tcmdtos
6aa91f2e2bfe462cda8f74b5170bc52136157915
[ "MIT" ]
null
null
null
TosVolume/Utils.hpp
laoo/tcmdtos
6aa91f2e2bfe462cda8f74b5170bc52136157915
[ "MIT" ]
null
null
null
void extractNameExt( std::string_view src, std::array<char, 11> & nameExt );
16.8
77
0.666667
laoo
5e35b935f136f8713a74dcdeb293837b99eebafe
432
cc
C++
src/sampler/halton_sampler.cc
BlurryLight/DiRender
1ea55ff8a10bb76993ce9990b200ee8ed173eb3e
[ "MIT" ]
20
2020-06-28T03:55:40.000Z
2022-03-08T06:00:31.000Z
src/sampler/halton_sampler.cc
BlurryLight/DiRender
1ea55ff8a10bb76993ce9990b200ee8ed173eb3e
[ "MIT" ]
null
null
null
src/sampler/halton_sampler.cc
BlurryLight/DiRender
1ea55ff8a10bb76993ce9990b200ee8ed173eb3e
[ "MIT" ]
1
2020-06-29T08:47:21.000Z
2020-06-29T08:47:21.000Z
// // Created by zhong on 2021/3/30. // #include "halton_sampler.hh" float DR::HaltonSampler::get_1d() { return h1.get(); } float DR::HaltonSampler::get_1d(float min, float max) { return (max - min) * h1.get() + min; } std::pair<float, float> DR::HaltonSampler::get_2d() { return {get_1d(), get_1d()}; } std::pair<float, float> DR::HaltonSampler::get_2d(float min, float max) { return {get_1d(min, max), get_1d(min, max)}; }
27
73
0.659722
BlurryLight
5e3b8f1ef82ff88cc2daf33ed3faa50c2eabf18f
4,800
cpp
C++
plugins/deadreckoningorientation/org_osvr_filter_deadreckoningrotation.cpp
ethanpeng/OSVR-Core
59405fc1b1a25aea051dfbba0be5171fa19b8b30
[ "Apache-2.0" ]
369
2015-03-08T03:12:41.000Z
2022-02-08T22:15:39.000Z
plugins/deadreckoningorientation/org_osvr_filter_deadreckoningrotation.cpp
ethanpeng/OSVR-Core
59405fc1b1a25aea051dfbba0be5171fa19b8b30
[ "Apache-2.0" ]
486
2015-03-09T13:29:00.000Z
2020-10-16T00:41:26.000Z
plugins/deadreckoningorientation/org_osvr_filter_deadreckoningrotation.cpp
ethanpeng/OSVR-Core
59405fc1b1a25aea051dfbba0be5171fa19b8b30
[ "Apache-2.0" ]
166
2015-03-08T12:03:56.000Z
2021-12-03T13:56:21.000Z
/** @file @brief Analysis plugin that performs predictive tracking for the orientation if a specified tracker and is provided a prediction interval. @date 2016 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2016 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include <osvr/PluginKit/PluginKit.h> #include <osvr/PluginKit/TrackerInterfaceC.h> #include <osvr/VRPNServer/VRPNDeviceRegistration.h> #include <osvr/Util/StringLiteralFileToString.h> #include <vrpn_Tracker_Filter.h> // Generated JSON header file #include "org_osvr_filter_deadreckoningrotation_json.h" // Library/third-party includes #include <json/value.h> #include <json/reader.h> // Standard includes #include <iostream> #include <chrono> #include <thread> // Anonymous namespace to avoid symbol collision namespace { class DeadReckoningRotation { public: DeadReckoningRotation(OSVR_PluginRegContext ctx, std::string const &name, std::string const &input, int numSensors, double predictMS) { /// Register the VRPN device that we will be using. osvr::vrpnserver::VRPNDeviceRegistration reg(ctx); std::string decoratedName = reg.useDecoratedName(name); std::string localInput = "*" + input; reg.registerDevice(new vrpn_Tracker_DeadReckoning_Rotation( decoratedName, reg.getVRPNConnection(), localInput, numSensors, predictMS)); reg.setDeviceDescriptor(osvr::util::makeString( org_osvr_filter_deadreckoningrotation_json)); // Build a new Json entry that has the correct number of // sensors in it, rather than the default of 1. { Json::Reader reader; Json::Value filterJson; if (!reader.parse( osvr::util::makeString( org_osvr_filter_deadreckoningrotation_json), filterJson)) { throw std::logic_error("Faulty JSON file for Dead " "Reckoning Rotation Filter - should not " "be possible!"); } filterJson["interfaces"]["tracker"]["count"] = numSensors; // Corresponding filter reg.setDeviceDescriptor(filterJson.toStyledString()); } } OSVR_ReturnCode update() { // Nothing to do here - everything happens in a callback. return OSVR_RETURN_SUCCESS; } private: osvr::pluginkit::DeviceToken m_dev; OSVR_TrackerDeviceInterface m_trackerOut; }; class DeadReckoningRotationConstructor { public: /// @brief This is the required signature for a device instantiation /// callback. OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx, const char *params) { // Read the JSON data from parameters. Json::Value root; if (params) { Json::Reader r; if (!r.parse(params, root)) { std::cerr << "Could not parse parameters!" << std::endl; } } // Get the name we should use for the device if (!root.isMember("name")) { std::cerr << "Error: got configuration, but no name specified." << std::endl; return OSVR_RETURN_FAILURE; } std::string name = root["name"].asString(); // Get the input device we should use to listen to if (!root.isMember("input")) { std::cerr << "Error: got configuration, but no input specified." << std::endl; return OSVR_RETURN_FAILURE; } std::string input = root["input"].asString(); int numSensors = root.get("numSensors", 1).asInt(); double predictMS = root.get("predictMilliSeconds", 32).asDouble(); // OK, now that we have our parameters, create the device. osvr::pluginkit::registerObjectForDeletion( ctx, new DeadReckoningRotation(ctx, name, input, numSensors, predictMS * 1e-3)); return OSVR_RETURN_SUCCESS; } }; } // namespace OSVR_PLUGIN(com_osvr_example_Configured) { /// Tell the core we're available to create a device object. osvr::pluginkit::registerDriverInstantiationCallback( ctx, "DeadReckoningRotationTracker", new DeadReckoningRotationConstructor); return OSVR_RETURN_SUCCESS; }
33.103448
90
0.66
ethanpeng
5e3d40285aa66f0d6d58feb9f7fcc4ac2dc511f9
1,046
cpp
C++
UnitTest/TestVoronoi.cpp
ArchRobison/Voromoeba
608aeebd03f955a2180d05f310de6097c3df0c69
[ "Apache-2.0" ]
null
null
null
UnitTest/TestVoronoi.cpp
ArchRobison/Voromoeba
608aeebd03f955a2180d05f310de6097c3df0c69
[ "Apache-2.0" ]
1
2021-06-28T16:24:46.000Z
2021-06-29T13:40:23.000Z
UnitTest/TestVoronoi.cpp
ArchRobison/Voromoeba
608aeebd03f955a2180d05f310de6097c3df0c69
[ "Apache-2.0" ]
null
null
null
#include "Voronoi.h" #include "Region.h" void TestVoronoi() { NimblePixel pixels[100][100]; NimblePixMap window( 100, 100, 32, pixels, sizeof(pixels[100]) ); ConvexRegion r; r.makeRectangle(Point(10,20),Point(90,80)); SetRegionClip(0,0,window.width(),window.height()); CompoundRegion region; region.build(&r,&r+1); for( int trial=0; trial<1000; ++trial ) { static Ant ants[N_ANT_MAX]; NimblePixel color[N_ANT_MAX]; Ant* a = ants; a->assignFirstBookend(); ++a; size_t n = 100; for( size_t k=0; k<n; ) { float x = RandomFloat(100); float y = RandomFloat(100); float dx = RandomFloat(0.001f); float dy = RandomFloat(0.0f); a->assign(Point(x,y),color[k]); ++a; ++k; a->assign(Point(x+dx,y+dy),color[k]); ++a; ++k; } a->assignLastBookend(); ++a; DrawVoronoi( window, region, ants, a ); } }
29.055556
70
0.510516
ArchRobison
5e3fb88c4f84c26de00af844b0df133df3c636cd
7,365
hpp
C++
src/PE/utils/ordinals_lookup_tables/comctl32_dll_lookup.hpp
mkomet/LIEF
27547aec3314177d374293130b1fd00b4487139a
[ "Apache-2.0" ]
null
null
null
src/PE/utils/ordinals_lookup_tables/comctl32_dll_lookup.hpp
mkomet/LIEF
27547aec3314177d374293130b1fd00b4487139a
[ "Apache-2.0" ]
null
null
null
src/PE/utils/ordinals_lookup_tables/comctl32_dll_lookup.hpp
mkomet/LIEF
27547aec3314177d374293130b1fd00b4487139a
[ "Apache-2.0" ]
null
null
null
/* Copyright 2017 - 2021 R. Thomas * Copyright 2017 - 2021 Quarkslab * * 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 LIEF_PE_COMCTL32_DLL_LOOKUP_H_ #define LIEF_PE_COMCTL32_DLL_LOOKUP_H_ #include <map> namespace LIEF { namespace PE { static const std::map<uint32_t, const char*> comctl32_dll_lookup { { 0x0191, "AddMRUStringW" }, { 0x00cf, "AttachScrollBars" }, { 0x00d2, "CCEnableScrollBar" }, { 0x00d1, "CCGetScrollInfo" }, { 0x00d0, "CCSetScrollInfo" }, { 0x0190, "CreateMRUListW" }, { 0x0008, "CreateMappedBitmap" }, { 0x000c, "CreatePropertySheetPage" }, { 0x0013, "CreatePropertySheetPageA" }, { 0x0014, "CreatePropertySheetPageW" }, { 0x0015, "CreateStatusWindow" }, { 0x0006, "CreateStatusWindowA" }, { 0x0016, "CreateStatusWindowW" }, { 0x0007, "CreateToolbar" }, { 0x0017, "CreateToolbarEx" }, { 0x0010, "CreateUpDownControl" }, { 0x014b, "DPA_Clone" }, { 0x0148, "DPA_Create" }, { 0x0154, "DPA_CreateEx" }, { 0x0151, "DPA_DeleteAllPtrs" }, { 0x0150, "DPA_DeletePtr" }, { 0x0149, "DPA_Destroy" }, { 0x0182, "DPA_DestroyCallback" }, { 0x0181, "DPA_EnumCallback" }, { 0x014c, "DPA_GetPtr" }, { 0x014d, "DPA_GetPtrIndex" }, { 0x015b, "DPA_GetSize" }, { 0x014a, "DPA_Grow" }, { 0x014e, "DPA_InsertPtr" }, { 0x0009, "DPA_LoadStream" }, { 0x000b, "DPA_Merge" }, { 0x000a, "DPA_SaveStream" }, { 0x0153, "DPA_Search" }, { 0x014f, "DPA_SetPtr" }, { 0x0152, "DPA_Sort" }, { 0x0157, "DSA_Clone" }, { 0x0140, "DSA_Create" }, { 0x0147, "DSA_DeleteAllItems" }, { 0x0146, "DSA_DeleteItem" }, { 0x0141, "DSA_Destroy" }, { 0x0184, "DSA_DestroyCallback" }, { 0x0183, "DSA_EnumCallback" }, { 0x0142, "DSA_GetItem" }, { 0x0143, "DSA_GetItemPtr" }, { 0x015c, "DSA_GetSize" }, { 0x0144, "DSA_InsertItem" }, { 0x0145, "DSA_SetItem" }, { 0x015a, "DSA_Sort" }, { 0x019d, "DefSubclassProc" }, { 0x0018, "DestroyPropertySheetPage" }, { 0x00ce, "DetachScrollBars" }, { 0x0019, "DllGetVersion" }, { 0x001a, "DllInstall" }, { 0x000f, "DrawInsert" }, { 0x00c9, "DrawScrollBar" }, { 0x001b, "DrawShadowText" }, { 0x00c8, "DrawSizeBox" }, { 0x001c, "DrawStatusText" }, { 0x0005, "DrawStatusTextA" }, { 0x001d, "DrawStatusTextW" }, { 0x0193, "EnumMRUListW" }, { 0x001e, "FlatSB_EnableScrollBar" }, { 0x001f, "FlatSB_GetScrollInfo" }, { 0x0020, "FlatSB_GetScrollPos" }, { 0x0021, "FlatSB_GetScrollProp" }, { 0x0022, "FlatSB_GetScrollPropPtr" }, { 0x0023, "FlatSB_GetScrollRange" }, { 0x0024, "FlatSB_SetScrollInfo" }, { 0x0025, "FlatSB_SetScrollPos" }, { 0x0026, "FlatSB_SetScrollProp" }, { 0x0027, "FlatSB_SetScrollRange" }, { 0x0028, "FlatSB_ShowScrollBar" }, { 0x0098, "FreeMRUList" }, { 0x0004, "GetEffectiveClientRect" }, { 0x0029, "GetMUILanguage" }, { 0x019b, "GetWindowSubclass" }, { 0x002a, "HIMAGELIST_QueryInterface" }, { 0x00cd, "HandleScrollCmd" }, { 0x002b, "ImageList_Add" }, { 0x002c, "ImageList_AddIcon" }, { 0x002d, "ImageList_AddMasked" }, { 0x002e, "ImageList_BeginDrag" }, { 0x002f, "ImageList_CoCreateInstance" }, { 0x0030, "ImageList_Copy" }, { 0x0031, "ImageList_Create" }, { 0x0032, "ImageList_Destroy" }, { 0x0033, "ImageList_DestroyShared" }, { 0x0034, "ImageList_DragEnter" }, { 0x0035, "ImageList_DragLeave" }, { 0x0036, "ImageList_DragMove" }, { 0x0037, "ImageList_DragShowNolock" }, { 0x0038, "ImageList_Draw" }, { 0x0039, "ImageList_DrawEx" }, { 0x003a, "ImageList_DrawIndirect" }, { 0x003b, "ImageList_Duplicate" }, { 0x003c, "ImageList_EndDrag" }, { 0x003d, "ImageList_GetBkColor" }, { 0x003e, "ImageList_GetDragImage" }, { 0x003f, "ImageList_GetFlags" }, { 0x0040, "ImageList_GetIcon" }, { 0x0041, "ImageList_GetIconSize" }, { 0x0042, "ImageList_GetImageCount" }, { 0x0043, "ImageList_GetImageInfo" }, { 0x0044, "ImageList_GetImageRect" }, { 0x0045, "ImageList_LoadImage" }, { 0x0046, "ImageList_LoadImageA" }, { 0x004b, "ImageList_LoadImageW" }, { 0x004c, "ImageList_Merge" }, { 0x004d, "ImageList_Read" }, { 0x004e, "ImageList_ReadEx" }, { 0x004f, "ImageList_Remove" }, { 0x0050, "ImageList_Replace" }, { 0x0051, "ImageList_ReplaceIcon" }, { 0x0052, "ImageList_Resize" }, { 0x0053, "ImageList_SetBkColor" }, { 0x0054, "ImageList_SetDragCursorImage" }, { 0x0055, "ImageList_SetFilter" }, { 0x0056, "ImageList_SetFlags" }, { 0x0057, "ImageList_SetIconSize" }, { 0x0058, "ImageList_SetImageCount" }, { 0x0059, "ImageList_SetOverlayImage" }, { 0x005a, "ImageList_Write" }, { 0x005b, "ImageList_WriteEx" }, { 0x0011, "InitCommonControls" }, { 0x005c, "InitCommonControlsEx" }, { 0x005d, "InitMUILanguage" }, { 0x005e, "InitializeFlatSB" }, { 0x000e, "LBItemFromPt" }, { 0x017c, "LoadIconMetric" }, { 0x017d, "LoadIconWithScaleDown" }, { 0x000d, "MakeDragList" }, { 0x0002, "MenuHelp" }, { 0x005f, "PropertySheet" }, { 0x0060, "PropertySheetA" }, { 0x0061, "PropertySheetW" }, { 0x018a, "QuerySystemGestureStatus" }, { 0x0062, "RegisterClassNameW" }, { 0x019c, "RemoveWindowSubclass" }, { 0x00cc, "ScrollBar_Menu" }, { 0x00cb, "ScrollBar_MouseMove" }, { 0x019a, "SetWindowSubclass" }, { 0x0003, "ShowHideMenuCtl" }, { 0x00ca, "SizeBoxHwnd" }, { 0x00ec, "Str_SetPtrW" }, { 0x0158, "TaskDialog" }, { 0x0159, "TaskDialogIndirect" }, { 0x0063, "UninitializeFlatSB" }, { 0x0064, "_TrackMouseEvent" }, }; } } #endif
40.690608
75
0.536456
mkomet
1e0f74496a38e7872122501fe6bf09da1fe91d49
10,227
cc
C++
src/common/chemistry/tests_unit/chemistry_activity_coefficients.cc
ajkhattak/amanzi
fed8cae6af3f9dfa5984381d34b98401c3b47655
[ "RSA-MD" ]
1
2021-02-23T18:34:47.000Z
2021-02-23T18:34:47.000Z
src/common/chemistry/tests_unit/chemistry_activity_coefficients.cc
ajkhattak/amanzi
fed8cae6af3f9dfa5984381d34b98401c3b47655
[ "RSA-MD" ]
null
null
null
src/common/chemistry/tests_unit/chemistry_activity_coefficients.cc
ajkhattak/amanzi
fed8cae6af3f9dfa5984381d34b98401c3b47655
[ "RSA-MD" ]
null
null
null
#include <cstdlib> #include <cmath> #include <iostream> #include <typeinfo> #include <vector> #include "UnitTest++.h" #include "species.hh" #include "aqueous_equilibrium_complex.hh" #include "activity_model_factory.hh" #include "activity_model_unit.hh" #include "activity_model_debye_huckel.hh" #include "activity_model.hh" #include "chemistry_exception.hh" /***************************************************************************** * Common testing code *****************************************************************************/ namespace ac = Amanzi::AmanziChemistry; class ActivityModelTest { public: ActivityModelTest(); ~ActivityModelTest(); void RunTest(const std::string name, double* gamma); void set_activity_model_name(const std::string name) { activity_model_name_ = name; }; std::string activity_model_name(void) const { return activity_model_name_; }; double ionic_strength(void) { return activity_model_->ionic_strength(); }; double tolerance(void) { return tolerance_; }; protected: ac::ActivityModelFactory amf_; private: double tolerance_; ac::ActivityModel* activity_model_; std::string activity_model_name_; ac::SpeciesArray species_; ac::Species H_p; ac::Species OH_m; ac::Species Ca_pp; ac::Species SO4_mm; ac::Species Al_ppp; ac::Species PO4_mmm; std::vector<ac::AqueousEquilibriumComplex> aqueous_complexes_; Teuchos::RCP<Amanzi::VerboseObject> vo_; }; ActivityModelTest::ActivityModelTest() : amf_(), tolerance_(1.0e-5), activity_model_name_(""), H_p(0, "H+", 1.0, 1.0079, 9.0), OH_m(1, "OH-", -1.0, 17.0073, 3.5), Ca_pp(2, "Ca++", 2.0, 40.0780, 6.0), SO4_mm(3, "SO4--", -2.0, 96.0636, 4.0), Al_ppp(4, "Al+++", 3.0, 26.9815, 9.0), PO4_mmm(5, "PO4---", -3.0, 94.9714, 4.0) { // set concentrations to get ionic strength of 0.025 H_p.update(0.0005); OH_m.update(0.0015); Ca_pp.update(0.001); SO4_mm.update(0.002); Al_ppp.update(0.003); PO4_mmm.update(0.001); species_.push_back(H_p); species_.push_back(OH_m); species_.push_back(Ca_pp); species_.push_back(SO4_mm); species_.push_back(Al_ppp); species_.push_back(PO4_mmm); // TODO(bandre): should add some aqueous complexes to test ionic strength.... aqueous_complexes_.clear(); Teuchos::ParameterList plist; vo_ = Teuchos::rcp(new Amanzi::VerboseObject("Chemistry", plist)); } ActivityModelTest::~ActivityModelTest() { delete activity_model_; } void ActivityModelTest::RunTest(const std::string name, double * gamma) { int index = -1; for (std::vector<ac::Species>::iterator primary = species_.begin(); primary != species_.end(); primary++) { if (primary->name() == name) { index = primary->identifier(); } } *gamma = -1.0; // final value should always be > 0 ac::ActivityModel::ActivityModelParameters parameters; parameters.database_filename = ""; parameters.pitzer_jfunction = ""; activity_model_ = amf_.Create(activity_model_name(), parameters, species_, aqueous_complexes_, vo_.ptr()); activity_model_->CalculateIonicStrength(species_, aqueous_complexes_); *gamma = activity_model_->Evaluate(species_.at(index)); } /*! @namespace Amanzi::AmanziChemistry::unit_tests::ActivityModel @details Unit tests for the activity model base class, Amanzi::AmanziChemistry::ActivityModel @test ActivityModel */ SUITE(amanzi_chemistry_unit_tests_ActivityModel) { /*! @class Amanzi::AmanziChemistry::unit_tests::ActivityModel::ActivityModel_IonicStrength @brief ActivityModel_IonicStrength @details Test that a the ionic strength is calculated correctly for an arbitrary choice of 6 ions with charge of +-1, +-2, +-3. Adjust concentrations to yield an ionic strength of 0.025. @test ActivityModel::CalculateIonicStrength() */ TEST_FIXTURE(ActivityModelTest, ActivityModel_IonicStrength) { set_activity_model_name(ac::ActivityModelFactory::unit); double gamma; RunTest("H+", &gamma); // std::cout << "ionic strength: " << ionic_strength() << std::endl; CHECK_CLOSE(0.025, ionic_strength(), tolerance()); } } // end SUITE(amanzi_chemistry_unit_tests_ActivityModel) /*! @namespace Amanzi::AmanziChemistry::unit_tests::ActivityModelUnit @details Unit tests for class ActivityModelUnit. - Unit activity coefficients are always 1.0 regardless of species @f[ \gamma_i = 1.0 @f] @test ActivityModelUnit */ SUITE(amanzi_chemistry_unit_tests_ActivityModelUnit) { /*! @brief ActivityModelUnit_H @class Amanzi::AmanziChemistry::unit_tests::ActivityModelUnit::ActivityModelUnit_H @details Test calculation of unit activity coefficient for @f$ H^{+} @f$ @test ActivityModelUnit::Evaluate() */ TEST_FIXTURE(ActivityModelTest, ActivityModelUnit_H) { set_activity_model_name(ac::ActivityModelFactory::unit); double gamma; RunTest("H+", &gamma); CHECK_EQUAL(1.0, gamma); } /*! @brief ActivityModelUnit_OH @class Amanzi::AmanziChemistry::unit_tests::ActivityModelUnit::ActivityModelUnit_OH @details Test calculation of unit activity coefficient for @f$ OH^{+} @f$ @test ActivityModelUnit::Evaluate() */ TEST_FIXTURE(ActivityModelTest, ActivityModelUnit_OH) { set_activity_model_name(ac::ActivityModelFactory::unit); double gamma; RunTest("OH-", &gamma); CHECK_EQUAL(1.0, gamma); } /*! @brief ActivityModelUnit_Ca @class Amanzi::AmanziChemistry::unit_tests::ActivityModelUnit::ActivityModelUnit_Ca @details Test calculation of unit activity coefficient for @f$ Ca^{+2} @f$ @test ActivityModelUnit::Evaluate() */ TEST_FIXTURE(ActivityModelTest, ActivityModelUnit_Ca) { set_activity_model_name(ac::ActivityModelFactory::unit); double gamma; RunTest("Ca++", &gamma); CHECK_EQUAL(1.0, gamma); } /*! @brief ActivityModelUnit_SO4 @class Amanzi::AmanziChemistry::unit_tests::ActivityModelUnit::ActivityModelUnit_SO4 @details Test calculation of unit activity coefficient for @f$ SO4^{-2} @f$ @test ActivityModelUnit::Evaluate() */ TEST_FIXTURE(ActivityModelTest, ActivityModelUnit_SO4) { set_activity_model_name(ac::ActivityModelFactory::unit); double gamma; RunTest("SO4--", &gamma); CHECK_EQUAL(1.0, gamma); } /*! @brief ActivityModelUnit_Al @class Amanzi::AmanziChemistry::unit_tests::ActivityModelUnit::ActivityModelUnit_Al @details Test calculation of unit activity coefficient for @f$ Al^{+3} @f$ @test ActivityModelUnit::Evaluate() */ TEST_FIXTURE(ActivityModelTest, ActivityModelUnit_Al) { set_activity_model_name(ac::ActivityModelFactory::unit); double gamma; RunTest("Al+++", &gamma); CHECK_EQUAL(1.0, gamma); } /*! @brief ActivityModelUnit_PO4 @class Amanzi::AmanziChemistry::unit_tests::ActivityModelUnit::ActivityModelUnit_PO4 @details Test calculation of unit activity coefficient for @f$ PO4^{-3} @f$ @test ActivityModelUnit::Evaluate() */ TEST_FIXTURE(ActivityModelTest, ActivityModelUnit_PO4) { set_activity_model_name(ac::ActivityModelFactory::unit); double gamma; RunTest("PO4---", &gamma); CHECK_EQUAL(1.0, gamma); } } // end SUITE(amanzi_chemistry_unit_tests_ActivityModelUnit) /*! @namespace Amanzi::AmanziChemistry::unit_tests::ActivityModelDebyeHuckel @details Test the calculation of the Debye-Huckel B-dot activity coefficients is correct. @f[ \log \gamma _{i} = - \frac{A_{\gamma} z_{i}^{2} \sqrt{ \bar{I} }} {1+ \mathring{a_i} B_{\gamma } \sqrt{\bar{I}}} + \dot{B} \bar{I} @f] - Debye-Huckel: check first two digits of activity coefficients at 25C with Langmuir, 1997, Aqueous Environmental Geochemistry, Table 4.1 and 4.2, pg 130-131. Note, code uses slightly different debyeA and debyeB parameters. - source for higher number of sig figs? - For temperature dependance, run 5-10 temperature values, then store results in a vector and use CHECK_ARRAY_CLOSE(). Source for temperature dependance? @test ActivityModelDebyHuckel */ SUITE(amanzi_chemistry_unit_tests_ActivityModelDebyeHuckel) { /*! @brief ActivityModelDebyeHuckel_H @class Amanzi::AmanziChemistry::unit_tests::ActivityModelDebyeHuckel::ActivityModelDebyeHuckel_H @details Test calculation of Debye-Huckel activity coefficient for @f$ H^{+} @f$ @test ActivityModelDebyeHuckel::Evaluate() */ TEST_FIXTURE(ActivityModelTest, ActivityModelDebyeHuckel_H) { set_activity_model_name(ac::ActivityModelFactory::debye_huckel); double gamma; RunTest("H+", &gamma); CHECK_CLOSE(0.88, gamma, 1.0e-2); } /*! @brief ActivityModelDebyeHuckel_OH @class Amanzi::AmanziChemistry::unit_tests::ActivityModelDebyeHuckel::ActivityModelDebyeHuckel_OH @details Test calculation of Debye-Huckel activity coefficient for @f$ OH^{-} @f$ @test ActivityModelDebyeHuckel::Evaluate() */ TEST_FIXTURE(ActivityModelTest, ActivityModelDebyeHuckel_OH) { set_activity_model_name(ac::ActivityModelFactory::debye_huckel); double gamma; RunTest("OH-", &gamma); CHECK_CLOSE(0.855, gamma, 1.0e-2); } TEST_FIXTURE(ActivityModelTest, ActivityModelDebyeHuckel_Ca) { set_activity_model_name(ac::ActivityModelFactory::debye_huckel); double gamma; RunTest("Ca++", &gamma); CHECK_CLOSE(0.57, gamma, 1.0e-2); } TEST_FIXTURE(ActivityModelTest, ActivityModelDebyeHuckel_SO4) { set_activity_model_name(ac::ActivityModelFactory::debye_huckel); double gamma; RunTest("SO4--", &gamma); CHECK_CLOSE(0.545, gamma, 1.0e-2); } TEST_FIXTURE(ActivityModelTest, ActivityModelDebyeHuckel_Al) { set_activity_model_name(ac::ActivityModelFactory::debye_huckel); double gamma; RunTest("Al+++", &gamma); CHECK_CLOSE(0.325, gamma, 1.0e-2); } TEST_FIXTURE(ActivityModelTest, ActivityModelDebyeHuckel_PO4) { set_activity_model_name(ac::ActivityModelFactory::debye_huckel); double gamma; RunTest("PO4---", &gamma); CHECK_CLOSE(0.25, gamma, 1.0e-2); } } // end SUITE(amanzi_chemistry_unit_tests_ActivityModelDebyeHuckel)
29.387931
101
0.702748
ajkhattak
1e10392a08dcf5a84d92bab4b98c0f1ec3e19d67
10,742
cpp
C++
tests/Cardano/AddressTests.cpp
alicedapp/wallet-core
532034af30cc5a8f677c7f7b0d182e8198cf698d
[ "MIT" ]
null
null
null
tests/Cardano/AddressTests.cpp
alicedapp/wallet-core
532034af30cc5a8f677c7f7b0d182e8198cf698d
[ "MIT" ]
null
null
null
tests/Cardano/AddressTests.cpp
alicedapp/wallet-core
532034af30cc5a8f677c7f7b0d182e8198cf698d
[ "MIT" ]
2
2020-01-08T14:28:22.000Z
2020-01-21T15:46:52.000Z
// Copyright © 2017-2020 Trust Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "Cardano/Address.h" #include "Cardano/Signer.h" #include "HDWallet.h" #include "HexCoding.h" #include "PrivateKey.h" #include <gtest/gtest.h> using namespace TW; using namespace TW::Cardano; using namespace std; TEST(CardanoAddress, Validation) { // valid V2 address ASSERT_TRUE(Address::isValid("Ae2tdPwUPEZ18ZjTLnLVr9CEvUEUX4eW1LBHbxxxJgxdAYHrDeSCSbCxrvx")); ASSERT_TRUE(Address::isValid("Ae2tdPwUPEZ6RUCnjGHFqi59k5WZLiv3HoCCNGCW8SYc5H9srdTzn1bec4W")); // valid V1 address ASSERT_TRUE(Address::isValid("DdzFFzCqrhssmYoG5Eca1bKZFdGS8d6iag1mU4wbLeYcSPVvBNF2wRG8yhjzQqErbg63N6KJA4DHqha113tjKDpGEwS5x1dT2KfLSbSJ")); ASSERT_TRUE(Address::isValid("DdzFFzCqrht7HGoJ87gznLktJGywK1LbAJT2sbd4txmgS7FcYLMQFhawb18ojS9Hx55mrbsHPr7PTraKh14TSQbGBPJHbDZ9QVh6Z6Di")); // invalid checksum ASSERT_FALSE(Address::isValid("Ae2tdPwUPEZ18ZjTLnLVr9CEvUEUX4eW1LBHbxxxJgxdAYHrDeSCSbCxrvm")); // random ASSERT_FALSE(Address::isValid("hasoiusaodiuhsaijnnsajnsaiussai")); // empty ASSERT_FALSE(Address::isValid("")); } TEST(CardanoAddress, FromString) { { auto address = Address("Ae2tdPwUPEZ18ZjTLnLVr9CEvUEUX4eW1LBHbxxxJgxdAYHrDeSCSbCxrvx"); ASSERT_EQ(address.string(), "Ae2tdPwUPEZ18ZjTLnLVr9CEvUEUX4eW1LBHbxxxJgxdAYHrDeSCSbCxrvx"); } { auto address = Address("DdzFFzCqrhssmYoG5Eca1bKZFdGS8d6iag1mU4wbLeYcSPVvBNF2wRG8yhjzQqErbg63N6KJA4DHqha113tjKDpGEwS5x1dT2KfLSbSJ"); ASSERT_EQ(address.string(), "DdzFFzCqrhssmYoG5Eca1bKZFdGS8d6iag1mU4wbLeYcSPVvBNF2wRG8yhjzQqErbg63N6KJA4DHqha113tjKDpGEwS5x1dT2KfLSbSJ"); } } TEST(CardanoAddress, MnemonicToAddress) { { // Test from cardano-crypto.js; Test wallet auto mnemonic = "cost dash dress stove morning robust group affair stomach vacant route volume yellow salute laugh"; auto wallet = HDWallet(mnemonic, ""); PrivateKey masterPrivKey = wallet.getMasterKey(TWCurve::TWCurveED25519Extended); PrivateKey masterPrivKeyExt = wallet.getMasterKeyExtension(TWCurve::TWCurveED25519Extended); ASSERT_EQ("a018cd746e128a0be0782b228c275473205445c33b9000a33dd5668b430b5744", hex(masterPrivKey.bytes)); ASSERT_EQ("26877cfe435fddda02409b839b7386f3738f10a30b95a225f4b720ee71d2505b", hex(masterPrivKeyExt.bytes)); { string addr = wallet.deriveAddress(TWCoinType::TWCoinTypeCardano); ASSERT_EQ("Ae2tdPwUPEZ6RUCnjGHFqi59k5WZLiv3HoCCNGCW8SYc5H9srdTzn1bec4W", addr); } { PrivateKey privKey0 = wallet.getKey(DerivationPath("m/44'/1815'/0'/0/0")); PublicKey pubKey0 = privKey0.getPublicKey(TWPublicKeyTypeED25519Extended); Address addr0 = Address(pubKey0); ASSERT_EQ("Ae2tdPwUPEZ6RUCnjGHFqi59k5WZLiv3HoCCNGCW8SYc5H9srdTzn1bec4W", addr0.string()); } { PrivateKey privKey1 = wallet.getKey(DerivationPath("m/44'/1815'/0'/0/1")); PublicKey pubKey1 = privKey1.getPublicKey(TWPublicKeyTypeED25519Extended); Address addr1 = Address(pubKey1); ASSERT_EQ("Ae2tdPwUPEZ7dnds6ZyhQdmgkrDFFPSDh8jG9RAhswcXt1bRauNw5jczjpV", addr1.string()); } { PrivateKey privKey1 = wallet.getKey(DerivationPath("m/44'/1815'/0'/0/2")); PublicKey pubKey1 = privKey1.getPublicKey(TWPublicKeyTypeED25519Extended); Address addr1 = Address(pubKey1); ASSERT_EQ("Ae2tdPwUPEZ8LAVy21zj4BF97iWxKCmPv12W6a18zLX3V7rZDFFVgqUBkKw", addr1.string()); } } { // Tested agains AdaLite auto mnemonicPlay1 = "youth away raise north opinion slice dash bus soldier dizzy bitter increase saddle live champion"; auto wallet = HDWallet(mnemonicPlay1, ""); string addr = wallet.deriveAddress(TWCoinType::TWCoinTypeCardano); ASSERT_EQ("Ae2tdPwUPEZJYT9g1JgQWtLveUHavyRxQGi6hVzoQjct7yyCLGgk3pCyx7h", addr); } { // Tested agains AdaLite auto mnemonicPlay2 = "return custom two home gain guilt kangaroo supply market current curtain tomorrow heavy blue robot"; auto wallet = HDWallet(mnemonicPlay2, ""); string addr = wallet.deriveAddress(TWCoinType::TWCoinTypeCardano); ASSERT_EQ("Ae2tdPwUPEZLtJx7LA2XZ3zzwonH9x9ieX3dMzaTBD3TfXuKczjMSjTecr1", addr); } { // AdaLite Demo phrase, 12-word. AdaLite uses V1 for it, in V2 it produces different addresses. // In AdaLite V1 addr0 is DdzFFzCqrht7HGoJ87gznLktJGywK1LbAJT2sbd4txmgS7FcYLMQFhawb18ojS9Hx55mrbsHPr7PTraKh14TSQbGBPJHbDZ9QVh6Z6Di auto mnemonicALDemo = "civil void tool perfect avocado sweet immense fluid arrow aerobic boil flash"; auto wallet = HDWallet(mnemonicALDemo, ""); string addr = wallet.deriveAddress(TWCoinType::TWCoinTypeCardano); ASSERT_EQ("Ae2tdPwUPEZJbLcD8iLgN7hVGvq66WdR4zocntRekSP97Ds3MvCfmEDjJYu", addr); } } TEST(CardanoAddress, KeyHash) { auto xpub = parse_hex("e6f04522f875c1563682ca876ddb04c2e2e3ae718e3ff9f11c03dd9f9dccf69869272d81c376382b8a87c21370a7ae9618df8da708d1a9490939ec54ebe43000"); auto hash = Address::keyHash(xpub); ASSERT_EQ("a1eda96a9952a56c983d9f49117f935af325e8a6c9d38496e945faa8", hex(hash)); } TEST(CardanoAddress, FromPublicKey) { { // caradano-crypto.js test auto publicKey = PublicKey(parse_hex("e6f04522f875c1563682ca876ddb04c2e2e3ae718e3ff9f11c03dd9f9dccf69869272d81c376382b8a87c21370a7ae9618df8da708d1a9490939ec54ebe43000"), TWPublicKeyTypeED25519Extended); auto address = Address(publicKey); ASSERT_EQ(address.string(), "Ae2tdPwUPEZCxt4UV1Uj2AMMRvg5pYPypqZowVptz3GYpK4pkcvn3EjkuNH"); } { // Adalite test account addr0 auto publicKey = PublicKey(parse_hex("57fd54be7b38bb8952782c2f59aa276928a4dcbb66c8c62ce44f9d623ecd5a03bf36a8fa9f5e11eb7a852c41e185e3969d518e66e6893c81d3fc7227009952d4"), TWPublicKeyTypeED25519Extended); auto address = Address(publicKey); ASSERT_EQ(address.string(), "Ae2tdPwUPEZ6RUCnjGHFqi59k5WZLiv3HoCCNGCW8SYc5H9srdTzn1bec4W"); } { // Adalite test account addr1 auto publicKey = PublicKey(parse_hex("25af99056d600f7956312406bdd1cd791975bb1ae91c9d034fc65f326195fcdb247ee97ec351c0820dd12de4ca500232f73a35fe6f86778745bcd57f34d1048d"), TWPublicKeyTypeED25519Extended); auto address = Address(publicKey); ASSERT_EQ(address.string(), "Ae2tdPwUPEZ7dnds6ZyhQdmgkrDFFPSDh8jG9RAhswcXt1bRauNw5jczjpV"); } { // Play1 addr0 auto publicKey = PublicKey(parse_hex("7cee0f30b9d536a786547dd77b35679b6830e945ffde768eb4f2a061b9dba016e513fa1290da1d22e83a41f17eed72d4489483b561fff36b9555ffdb91c430e2"), TWPublicKeyTypeED25519Extended); auto address = Address(publicKey); ASSERT_EQ(address.string(), "Ae2tdPwUPEZJYT9g1JgQWtLveUHavyRxQGi6hVzoQjct7yyCLGgk3pCyx7h"); } } TEST(CardanoAddress, FromPrivateKey) { { // mnemonic Test, addr0 auto privateKey = PrivateKey( parse_hex("b0884d248cb301edd1b34cf626ba6d880bb3ae8fd91b4696446999dc4f0b5744"), parse_hex("309941d56938e943980d11643c535e046653ca6f498c014b88f2ad9fd6e71eff"), parse_hex("bf36a8fa9f5e11eb7a852c41e185e3969d518e66e6893c81d3fc7227009952d4") ); auto publicKey = privateKey.getPublicKey(TWPublicKeyTypeED25519Extended); ASSERT_EQ(hex(publicKey.bytes), "57fd54be7b38bb8952782c2f59aa276928a4dcbb66c8c62ce44f9d623ecd5a03bf36a8fa9f5e11eb7a852c41e185e3969d518e66e6893c81d3fc7227009952d4"); auto address = Address(publicKey); ASSERT_EQ(address.string(), "Ae2tdPwUPEZ6RUCnjGHFqi59k5WZLiv3HoCCNGCW8SYc5H9srdTzn1bec4W"); } { // mnemonic Play1, addr0 auto privateKey = PrivateKey( parse_hex("a089c9423100960440ccd5b7adbd202d1ab1993a7bb30fc88b287d94016df247"), parse_hex("da86a87f08fb15de1431a6c0ccd5ebf51c3bee81f7eaf714801bbbe4d903154a"), parse_hex("e513fa1290da1d22e83a41f17eed72d4489483b561fff36b9555ffdb91c430e2") ); auto publicKey = privateKey.getPublicKey(TWPublicKeyTypeED25519Extended); ASSERT_EQ(hex(publicKey.bytes), "7cee0f30b9d536a786547dd77b35679b6830e945ffde768eb4f2a061b9dba016e513fa1290da1d22e83a41f17eed72d4489483b561fff36b9555ffdb91c430e2"); auto address = Address(publicKey); ASSERT_EQ(address.string(), "Ae2tdPwUPEZJYT9g1JgQWtLveUHavyRxQGi6hVzoQjct7yyCLGgk3pCyx7h"); } { // from cardano-crypto.js test auto privateKey = PrivateKey( parse_hex("d809b1b4b4c74734037f76aace501730a3fe2fca30b5102df99ad3f7c0103e48"), parse_hex("d54cde47e9041b31f3e6873d700d83f7a937bea746dadfa2c5b0a6a92502356c"), parse_hex("69272d81c376382b8a87c21370a7ae9618df8da708d1a9490939ec54ebe43000") ); auto publicKey = privateKey.getPublicKey(TWPublicKeyTypeED25519Extended); ASSERT_EQ(hex(publicKey.bytes), "e6f04522f875c1563682ca876ddb04c2e2e3ae718e3ff9f11c03dd9f9dccf69869272d81c376382b8a87c21370a7ae9618df8da708d1a9490939ec54ebe43000"); auto address = Address(publicKey); ASSERT_EQ(address.string(), "Ae2tdPwUPEZCxt4UV1Uj2AMMRvg5pYPypqZowVptz3GYpK4pkcvn3EjkuNH"); } } TEST(CardanoAddress, PrivateKeyExtended) { // check extended key lengths, private key 3x32 bytes, public key 64 bytes auto privateKeyExt = PrivateKey( parse_hex("b0884d248cb301edd1b34cf626ba6d880bb3ae8fd91b4696446999dc4f0b5744"), parse_hex("309941d56938e943980d11643c535e046653ca6f498c014b88f2ad9fd6e71eff"), parse_hex("bf36a8fa9f5e11eb7a852c41e185e3969d518e66e6893c81d3fc7227009952d4") ); auto publicKeyExt = privateKeyExt.getPublicKey(TWPublicKeyTypeED25519Extended); ASSERT_EQ(64, publicKeyExt.bytes.size()); // Non-extended: both are 32 bytes. auto privateKeyNonext = PrivateKey( parse_hex("b0884d248cb301edd1b34cf626ba6d880bb3ae8fd91b4696446999dc4f0b5744") ); auto publicKeyNonext = privateKeyNonext.getPublicKey(TWPublicKeyTypeED25519); ASSERT_EQ(32, publicKeyNonext.bytes.size()); } TEST(CardanoAddress, FromStringNegativeInvalidString) { try { auto address = Address("__INVALID_ADDRESS__"); } catch (...) { return; } FAIL() << "Expected exception!"; } TEST(CardanoAddress, FromStringNegativeBadChecksum) { try { auto address = Address("Ae2tdPwUPEZ18ZjTLnLVr9CEvUEUX4eW1LBHbxxxJgxdAYHrDeSCSbCxrvm"); } catch (...) { return; } FAIL() << "Expected exception!"; }
50.196262
210
0.756191
alicedapp
1e1e9e92763ae05ea620dcc4d1a2933f0a45c678
7,886
cpp
C++
libnavi/src/BinderClient.cpp
rm-medina/agl-service-navigation
b9fa50ad33af4c3425d7198beaa63b783da2f62c
[ "Apache-2.0" ]
null
null
null
libnavi/src/BinderClient.cpp
rm-medina/agl-service-navigation
b9fa50ad33af4c3425d7198beaa63b783da2f62c
[ "Apache-2.0" ]
null
null
null
libnavi/src/BinderClient.cpp
rm-medina/agl-service-navigation
b9fa50ad33af4c3425d7198beaa63b783da2f62c
[ "Apache-2.0" ]
4
2017-12-12T03:59:55.000Z
2019-03-12T19:47:26.000Z
// Copyright 2017 AW SOFTWARE CO.,LTD // Copyright 2017 AISIN AW CO.,LTD #include <cstring> #include "BinderClient.h" #include "JsonRequestGenerator.h" #include "JsonResponseAnalyzer.h" #include "traces.h" /** * @brief constructor */ BinderClient::BinderClient() : navicoreListener(nullptr) { requestMng = new RequestManage(); } /** * @brief Destructor */ BinderClient::~BinderClient() { delete requestMng; } /** * @brief Connect with the Binder server */ bool BinderClient::ConnectServer(std::string url, naviapi::NavicoreListener* listener) { this->navicoreListener = listener; if( !requestMng->Connect(url.c_str(), this)) { TRACE_ERROR("cannot connect to binding service.\n"); return false; } return true; } /** * @brief Call Genivi's GetPosition via Binder and get the result */ void BinderClient::NavicoreGetPosition(const std::vector< int32_t >& valuesToReturn) { // Check if it is connected if( requestMng->IsConnect() ) { // JSON request generation std::string req_json = JsonRequestGenerator::CreateRequestGetPosition(valuesToReturn); // Send request if( requestMng->CallBinderAPI(API_NAME, VERB_GETPOSITION, req_json.c_str()) ) { TRACE_DEBUG("navicore_getposition success.\n"); } else { TRACE_ERROR("navicore_getposition failed.\n"); } } } /** * @brief Get route handle */ void BinderClient::NavicoreGetAllRoutes() { // Check if it is connected if( requestMng->IsConnect() ) { // JSON request generation std::string req_json = JsonRequestGenerator::CreateRequestGetAllRoutes(); // Send request if( requestMng->CallBinderAPI(API_NAME, VERB_GETALLROUTES, req_json.c_str()) ) { TRACE_DEBUG("navicore_getallroutes success.\n"); } else { TRACE_ERROR("navicore_getallroutes failed.\n"); } } } /** * @brief Generate route handle */ void BinderClient::NavicoreCreateRoute(const uint32_t& sessionHandle) { // Check if it is connected if( requestMng->IsConnect() ) { // JSON request generation uint32_t session = requestMng->GetSessionHandle(); std::string req_json = JsonRequestGenerator::CreateRequestCreateRoute(&session); // Send request if( requestMng->CallBinderAPI(API_NAME, VERB_CREATEROUTE, req_json.c_str()) ) { TRACE_DEBUG("navicore_createroute success.\n"); } else { TRACE_ERROR("navicore_createroute failed.\n"); } } } /** * @brief Pause demo */ void BinderClient::NavicorePauseSimulation(const uint32_t& sessionHandle) { // Check if it is connected if( requestMng->IsConnect() ) { // JSON request generation uint32_t session = requestMng->GetSessionHandle(); std::string req_json = JsonRequestGenerator::CreateRequestPauseSimulation(&session); // Send request if( requestMng->CallBinderAPI(API_NAME, VERB_PAUSESIMULATION, req_json.c_str()) ) { TRACE_DEBUG("navicore_pausesimulationmode success.\n"); } else { TRACE_ERROR("navicore_pausesimulationmode failed.\n"); } } } /** * @brief Simulation mode setting */ void BinderClient::NavicoreSetSimulationMode(const uint32_t& sessionHandle, const bool& activate) { // Check if it is connected if( requestMng->IsConnect() ) { // JSON request generation uint32_t session = requestMng->GetSessionHandle(); std::string req_json = JsonRequestGenerator::CreateRequestSetSimulationMode(&session, &activate); // Send request if( requestMng->CallBinderAPI(API_NAME, VERB_SETSIMULATIONMODE, req_json.c_str()) ) { TRACE_DEBUG("navicore_setsimulationmode success.\n"); } else { TRACE_ERROR("navicore_setsimulationmode failed.\n"); } } } /** * @brief Delete route information */ void BinderClient::NavicoreCancelRouteCalculation(const uint32_t& sessionHandle, const uint32_t& routeHandle) { // Check if it is connected if( requestMng->IsConnect() ) { // JSON request generation uint32_t session = requestMng->GetSessionHandle(); std::string req_json = JsonRequestGenerator::CreateRequestCancelRouteCalculation(&session, &routeHandle); // Send request if( requestMng->CallBinderAPI(API_NAME, VERB_CANCELROUTECALCULATION, req_json.c_str()) ) { TRACE_DEBUG("navicore_cancelroutecalculation success.\n"); } else { TRACE_ERROR("navicore_cancelroutecalculation failed.\n"); } } } /** * @brief Destination setting */ void BinderClient::NavicoreSetWaypoints(const uint32_t& sessionHandle, const uint32_t& routeHandle, const bool& startFromCurrentPosition, const std::vector<naviapi::Waypoint>& waypointsList) { // Check if it is connected if( requestMng->IsConnect() ) { // JSON request generation uint32_t session = requestMng->GetSessionHandle(); uint32_t route = requestMng->GetRouteHandle(); std::string req_json = JsonRequestGenerator::CreateRequestSetWaypoints(&session, &route, &startFromCurrentPosition, &waypointsList); // Send request if( requestMng->CallBinderAPI(API_NAME, VERB_SETWAYPOINTS, req_json.c_str()) ) { TRACE_DEBUG("navicore_setwaypoints success.\n"); } else { TRACE_ERROR("navicore_setwaypoints failed.\n"); } } } /** * @brief Route calculation processing */ void BinderClient::NavicoreCalculateRoute(const uint32_t& sessionHandle, const uint32_t& routeHandle) { // Check if it is connected if( requestMng->IsConnect() ) { // JSON request generation uint32_t session = requestMng->GetSessionHandle(); uint32_t route = requestMng->GetRouteHandle(); std::string req_json = JsonRequestGenerator::CreateRequestCalculateroute(&session, &route); // Send request if( requestMng->CallBinderAPI(API_NAME, VERB_CALCULATEROUTE, req_json.c_str()) ) { TRACE_DEBUG("navicore_calculateroute success.\n"); } else { TRACE_ERROR("navicore_calculateroute failed.\n"); } } } /** * @brief Retrieve session information * @return Map of session information */ void BinderClient::NavicoreGetAllSessions() { // Check if it is connected if( requestMng->IsConnect() ) { // JSON request generation std::string req_json = JsonRequestGenerator::CreateRequestGetAllSessions(); // Send request if( requestMng->CallBinderAPI(API_NAME, VERB_GETALLSESSIONS, req_json.c_str()) ) { TRACE_DEBUG("navicore_getallsessions success.\n"); } else { TRACE_ERROR("navicore_getallsessions failed.\n"); } } } void BinderClient::OnReply(struct json_object* reply) { struct json_object* requestObject = nullptr; json_object_object_get_ex(reply, "request", &requestObject); struct json_object* infoObject = nullptr; json_object_object_get_ex(requestObject, "info", &infoObject); const char* info = json_object_get_string(infoObject); char tmpVerb[256]; strcpy(tmpVerb, info); // Create a new JSON response const char* json_str = json_object_to_json_string_ext(reply, JSON_C_TO_STRING_PRETTY); std::string response_json = std::string( json_str ); if (strcmp(VERB_GETALLSESSIONS, tmpVerb) == 0) { std::map<uint32_t, std::string> ret = JsonResponseAnalyzer::AnalyzeResponseGetAllSessions(response_json); // keep session handle requestMng->SetSessionHandle( ret.begin()->first ); this->navicoreListener->getAllSessions_reply(ret); } else if (strcmp(VERB_GETPOSITION, tmpVerb) == 0) { std::map< int32_t, naviapi::variant > ret = JsonResponseAnalyzer::AnalyzeResponseGetPosition(response_json); this->navicoreListener->getPosition_reply(ret); } else if (strcmp(VERB_GETALLROUTES, tmpVerb) == 0) { std::vector< uint32_t > ret = JsonResponseAnalyzer::AnalyzeResponseGetAllRoutes(response_json); // route handle if(ret.size() > 0) { requestMng->SetRouteHandle(ret[0]); } this->navicoreListener->getAllRoutes_reply(ret); } else if (strcmp(VERB_CREATEROUTE, tmpVerb) == 0) { uint32_t ret = JsonResponseAnalyzer::AnalyzeResponseCreateRoute(response_json); // keep route handle requestMng->SetRouteHandle(ret); this->navicoreListener->createRoute_reply(ret); } }
24.955696
190
0.731676
rm-medina