hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
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
float64
1
77k
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
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
977b9dcb68ea985497728997aedecb96580026b4
8,291
cpp
C++
solver.cpp
sapirp/systemPrograming-task3B
f84f4a6021537bb1e3049035a30de20640b87847
[ "MIT" ]
null
null
null
solver.cpp
sapirp/systemPrograming-task3B
f84f4a6021537bb1e3049035a30de20640b87847
[ "MIT" ]
null
null
null
solver.cpp
sapirp/systemPrograming-task3B
f84f4a6021537bb1e3049035a30de20640b87847
[ "MIT" ]
null
null
null
#include<iostream> #include "solver.hpp" using namespace solver; using namespace std; double RealVariable::solveEquation(RealVariable& eq){ if(eq.a==0 && eq.b==0) throw std::exception(); if(!eq.power){ return -eq.c/eq.b; } else{ double SquareRoot = eq.b*eq.b - 4*eq.a*eq.c; double solveEq; if(SquareRoot>=0) { solveEq = (-eq.b + sqrt(SquareRoot)) / (2*eq.a); } else { throw std::exception(); } return solveEq; } } double solver::solve(RealVariable& eq){ return eq.solveEquation(eq); } RealVariable& RealVariable::copy (RealVariable& rv){ this->a=rv.a; this->b=rv.b; this->c=rv.c; this->power=rv.power; return *this; } //opertor + RealVariable& solver::operator+ (RealVariable& rv , double num){ RealVariable *rvCopy= new RealVariable(); rvCopy->copy(rv); rvCopy->c=rv.c+num; return *rvCopy; } RealVariable& solver::operator+ (double num , RealVariable& rv){ return (rv + num); } RealVariable& solver::operator+ (RealVariable& rv1 , RealVariable& rv2){ RealVariable* rvCopy=new RealVariable(); rvCopy->a=rv1.a+rv2.a; rvCopy->b=rv1.b+rv2.b; rvCopy->c=rv1.c+rv2.c; rvCopy->power= rv1.power? rv1.power : rv2.power; return *rvCopy; } //opertor - RealVariable& solver::operator- (RealVariable& rv , double num){ RealVariable* rvCopy=new RealVariable(); rvCopy->copy(rv); rvCopy->c=rv.c-num; return *rvCopy; } RealVariable& solver::operator- (double num , RealVariable& rv){ return (rv - num); } RealVariable& solver::operator- (RealVariable& rv1 , RealVariable& rv2){ RealVariable* rvCopy=new RealVariable(); rvCopy->a=rv1.a-rv2.a; rvCopy->b=rv1.b-rv2.b; rvCopy->c=rv1.c-rv2.c; rvCopy->power = rv1.power ? rv1.power : rv2.power; return *rvCopy; } //opertor * RealVariable& solver::operator* (RealVariable& rv , double num){ return (num * rv); } RealVariable& solver::operator* (double num , RealVariable& rv){ cout<< "op * : a=" << rv.a <<" b=" << rv.b <<"c="<<rv.c<<endl; RealVariable* rvCopy=new RealVariable(); rvCopy->copy(rv); if(rv.power) { rvCopy->a*=num; } else if(rv.b==0){ rvCopy->b=num; } else rvCopy->b*=num; return *rvCopy; } RealVariable& solver::operator* (RealVariable& rv1 , RealVariable& rv2){ if(rv1.power || rv2.power) throw std::exception(); RealVariable *rvCopy= new RealVariable(); rvCopy->copy(rv1); if(rv1.a != 0 && rv2.a !=0) rvCopy->a=rv1.a*rv2.a; rvCopy->a=rv1.a+rv2.a; rvCopy->power=true; return *rvCopy; } //opertor / RealVariable& solver::operator/ (RealVariable& rv , double num){ if(num==0) throw std::exception(); RealVariable *rvCopy= new RealVariable(); rvCopy->a=rv.a/num; rvCopy->b=rv.b/num; rvCopy->c=rv.c/num; rvCopy->power=rv.power; return *rvCopy; } RealVariable& solver::operator/ (double num , RealVariable& rv){ RealVariable *rvCopy= new RealVariable(); rvCopy->a=num/rv.a; rvCopy->b=num/rv.b; rvCopy->c=num/rv.c; rvCopy->power=rv.power; return *rvCopy; } //operator ^ RealVariable& solver::operator^ (RealVariable& rv, const int num){ if (num != 2 || rv.power) throw std::exception(); RealVariable *rvCopy= new RealVariable(); rvCopy->copy(rv); rvCopy->a=rv.b; rvCopy->power=true; rvCopy->b=0; return *rvCopy; } //opertor == RealVariable& solver::operator== (RealVariable& rv , double num){ RealVariable *rvCopy= new RealVariable(); rvCopy->copy(rv); if(num>0) rvCopy->c-=num; else rvCopy->c+=-num; return *rvCopy; } RealVariable& solver::operator== (double num , RealVariable& rv){ cout<< "operator ==: a=" << rv.a << "b=" <<rv.b <<"c=" << rv.c<< endl; return (rv == num); } RealVariable& solver::operator== (RealVariable& rv1 , RealVariable& rv2){ RealVariable* rvCopy = new RealVariable(); *rvCopy=rv1-rv2; return *rvCopy; } //complex variable std::complex<double> ComplexVariable::solveEquation(ComplexVariable& eq){ if(eq.a==std::complex<double>(0.0,0.0) && eq.b==std::complex<double>(0.0,0.0)) throw std::exception(); if(!eq.power){ return -eq.c/eq.b; } if (eq.b==std::complex<double>(0.0,0.0) && power){ std::complex<double> c=-eq.c/eq.a; return sqrt(c); } else{ std::complex<double> SquareRoot = sqrt(eq.b*eq.b - 4.0 *eq.a*eq.c); std::complex<double> solveEq= (-eq.b + SquareRoot) / (2.0*eq.a); return solveEq; } } std::complex<double> solver::solve(ComplexVariable& eq){ return eq.solveEquation(eq); } ComplexVariable& ComplexVariable::copy (ComplexVariable& cv){ this->a=cv.a; this->b=cv.b; this->c=cv.c; this->power=cv.power; return *this; } //operator + ComplexVariable& solver::operator+ (ComplexVariable& cv , complex<double> num){ ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->copy(cv); cvCopy->c=cv.c+num; return *cvCopy; } ComplexVariable& solver::operator+ (complex<double> num, ComplexVariable& cv ){ return (cv + num); } ComplexVariable& solver::operator+ (ComplexVariable& cv1, ComplexVariable& cv2 ){ ComplexVariable* cvCopy=new ComplexVariable(); cvCopy->a=cv1.a+cv2.a; cvCopy->b=cv1.b+cv2.b; cvCopy->c=cv1.c+cv2.c; cvCopy->power=cv1.power? cv1.power : cv2.power; return *cvCopy; } //operator - ComplexVariable& solver::operator- (ComplexVariable& cv , complex<double> num){ ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->copy(cv); cvCopy->c=cv.c-num; return *cvCopy; } ComplexVariable& solver::operator- (complex<double> num, ComplexVariable& cv ){ return (cv - num); } ComplexVariable& solver::operator- (ComplexVariable& cv1, ComplexVariable& cv2 ){ ComplexVariable* cvCopy=new ComplexVariable(); cvCopy->a=cv1.a-cv2.a; cvCopy->b=cv1.b-cv2.b; cvCopy->c=cv1.c-cv2.c; cvCopy->power = cv1.power ? cv1.power : cv2.power; return *cvCopy; } //operator * ComplexVariable& solver::operator* (ComplexVariable& cv1, ComplexVariable& cv2 ){ if(cv1.power || cv2.power) throw std::exception(); ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->copy(cv1); if(cv1.a != std::complex(0.0,0.0) && cv2.a !=std::complex(0.0,0.0)) cvCopy->a=cv1.a*cv2.a; cvCopy->a=cv1.a+cv2.a; cvCopy->power=true; return *cvCopy; } ComplexVariable& solver::operator* (complex<double> c , ComplexVariable& cv ){ ComplexVariable* cvCopy=new ComplexVariable(); cvCopy->copy(cv); if(cv.power) { cvCopy->a*=c; } else if(cv.b==std::complex(0.0,0.0)){ cvCopy->b=c; } else cvCopy->b*=c; return *cvCopy; } ComplexVariable& solver::operator* (ComplexVariable& cv , complex<double> c ){ return (c * cv); } //operator / ComplexVariable& solver::operator/ (complex<double> c , ComplexVariable& cv ){ ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->a=c/cv.a; cvCopy->b=c/cv.b; cvCopy->c=c/cv.c; cvCopy->power=cv.power; return *cvCopy; } ComplexVariable& solver::operator/ (ComplexVariable& cv , complex<double> c ){ ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->a=cv.a/c; cvCopy->b=cv.b/c; cvCopy->c=cv.c/c; cvCopy->power=cv.power; return *cvCopy; } ComplexVariable& solver::operator^ (ComplexVariable& cv, const int num){ if (num != 2) throw std::exception(); ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->copy(cv); cvCopy->a=cv.b; cvCopy->b=std::complex<double>(0.0,0.0);; cvCopy->power=true; return *cvCopy; } //operator == ComplexVariable& solver::operator== (ComplexVariable& cv , double num){ ComplexVariable *cvCopy= new ComplexVariable(); cvCopy->copy(cv); if(num>0) cvCopy->c-=num; else cvCopy->c+=-num; return *cvCopy; } ComplexVariable& solver::operator== (double num, ComplexVariable& cv ){ return (cv == num); } ComplexVariable& solver::operator== (ComplexVariable& cv1, ComplexVariable& cv2 ){ ComplexVariable* cvCopy = new ComplexVariable(); *cvCopy=cv1-cv2; return *cvCopy; }
25.589506
102
0.624894
977fc28e9f8f2c462a97235442bee7fc1b39503f
1,523
cpp
C++
cppcheck/data/c_files/35.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
2
2022-03-23T12:16:20.000Z
2022-03-31T06:19:40.000Z
cppcheck/data/c_files/35.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
null
null
null
cppcheck/data/c_files/35.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
null
null
null
bool Plugin::LoadNaClModuleCommon(nacl::DescWrapper* wrapper, NaClSubprocess* subprocess, const Manifest* manifest, bool should_report_uma, ErrorInfo* error_info, pp::CompletionCallback init_done_cb, pp::CompletionCallback crash_cb) { ServiceRuntime* new_service_runtime = new ServiceRuntime(this, manifest, should_report_uma, init_done_cb, crash_cb); subprocess->set_service_runtime(new_service_runtime); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon (service_runtime=%p)\n", static_cast<void*>(new_service_runtime))); if (NULL == new_service_runtime) { error_info->SetReport(ERROR_SEL_LDR_INIT, "sel_ldr init failure " + subprocess->description()); return false; } bool service_runtime_started = new_service_runtime->Start(wrapper, error_info, manifest_base_url()); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon (service_runtime_started=%d)\n", service_runtime_started)); if (!service_runtime_started) { return false; } // Try to start the Chrome IPC-based proxy. const PPB_NaCl_Private* ppb_nacl = GetNaclInterface(); if (ppb_nacl->StartPpapiProxy(pp_instance())) { using_ipc_proxy_ = true; // We need to explicitly schedule this here. It is normally called in // response to starting the SRPC proxy. CHECK(init_done_cb.pp_completion_callback().func != NULL); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon, started ipc proxy.\n")); pp::Module::Get()->core()->CallOnMainThread(0, init_done_cb, PP_OK); } return true; }
37.146341
77
0.74327
97800b9046f54f846dc4fdb8d5c33f66a9b324f2
1,770
cpp
C++
atcoder/abc/abc_114/c.cpp
hsmtknj/programming-contest
b0d7f8a2d12fb031d3a802e6a4769cd6d2defcab
[ "MIT" ]
null
null
null
atcoder/abc/abc_114/c.cpp
hsmtknj/programming-contest
b0d7f8a2d12fb031d3a802e6a4769cd6d2defcab
[ "MIT" ]
null
null
null
atcoder/abc/abc_114/c.cpp
hsmtknj/programming-contest
b0d7f8a2d12fb031d3a802e6a4769cd6d2defcab
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> void dfs753(std::vector<int> &list, int N, std::string s); int main() { int N; int cnt = 0; std::cin >> N; // find number including only 7, 5, 3 std::vector<int> list; dfs753(list, N, ""); // find answer for (int i = 0; i < list.size(); i++) { int cnt3 = 0; int cnt5 = 0; int cnt7 = 0; int cnt_others = 0; std::string s; s = std::to_string(list[i]); for (int j = 0; j < s.length(); j++) { int n_target_digit = (s[j] - '0'); if (n_target_digit == 3) { cnt3++; } else if (n_target_digit == 5) { cnt5++; } else if (n_target_digit == 7) { cnt7++; } else { cnt_others++; } } if (cnt3 > 0 && cnt5 > 0 && cnt7 > 0 && cnt_others == 0) { cnt++; } } std::cout << cnt << std::endl; return 0; } void dfs753(std::vector<int> &list, int N, std::string s) { std::string s_tmp; int n_tmp; if (s.length() <= 8) { s_tmp = s + '3'; n_tmp = std::stoi(s_tmp); if (n_tmp <= N) { list.push_back(n_tmp); dfs753(list, N, s_tmp); } s_tmp = s + '5'; n_tmp = std::stoi(s_tmp); if (n_tmp <= N) { list.push_back(n_tmp); dfs753(list, N, s_tmp); } s_tmp = s + '7'; n_tmp = std::stoi(s_tmp); if (n_tmp <= N) { list.push_back(n_tmp); dfs753(list, N, s_tmp); } } };
19.450549
64
0.388136
978137d0c0dbfb68443bae856077cccbb6774a70
758
hpp
C++
Firmware/service_providers/headers/ih/sp_ibattery_service.hpp
ValentiWorkLearning/GradWork
70bb5a629df056a559bae3694b47a2e5dc98c23b
[ "MIT" ]
39
2019-10-23T12:06:16.000Z
2022-01-26T04:28:29.000Z
Firmware/service_providers/headers/ih/sp_ibattery_service.hpp
ValentiWorkLearning/GradWork
70bb5a629df056a559bae3694b47a2e5dc98c23b
[ "MIT" ]
20
2020-03-21T20:21:46.000Z
2021-11-19T14:34:03.000Z
Firmware/service_providers/headers/ih/sp_ibattery_service.hpp
ValentiWorkLearning/GradWork
70bb5a629df056a559bae3694b47a2e5dc98c23b
[ "MIT" ]
7
2019-10-18T09:44:10.000Z
2021-06-11T13:05:16.000Z
#pragma once #include "utils/SimpleSignal.hpp" #include <chrono> namespace ServiceProviders::BatteryService::Settings { using namespace std::chrono_literals; constexpr std::chrono::seconds MeasurmentPeriod = 1s; constexpr std::uint8_t MinBatteryLevel = 0; constexpr std::uint8_t MaxBatteryLevel = 100; } // namespace ServiceProviders::BatteryService::Settings namespace ServiceProviders::BatteryService { class IBatteryLevelAppService { public: virtual ~IBatteryLevelAppService() = default; public: virtual std::chrono::seconds getMeasurmentPeriod() const noexcept = 0; virtual void startBatteryMeasure() noexcept = 0; Simple::Signal<void(std::uint8_t)> onBatteryLevelChangedSig; }; } // namespace ServiceProviders::BatteryService
22.294118
74
0.779683
97815b3de040fd642726264a176aabf36379f628
457
cpp
C++
Algorithms/Warmup/Compare the Triplets/Solution.cpp
RAVURISREESAIHARIKRISHNA/Hackerrank
e7ec866a4d03259ed054163b1e9e536af50a1c3e
[ "MIT" ]
null
null
null
Algorithms/Warmup/Compare the Triplets/Solution.cpp
RAVURISREESAIHARIKRISHNA/Hackerrank
e7ec866a4d03259ed054163b1e9e536af50a1c3e
[ "MIT" ]
null
null
null
Algorithms/Warmup/Compare the Triplets/Solution.cpp
RAVURISREESAIHARIKRISHNA/Hackerrank
e7ec866a4d03259ed054163b1e9e536af50a1c3e
[ "MIT" ]
null
null
null
#include<iostream> // #include<conio.h> using namespace std; int main(void){ int a[3]; for(int i=0;i<=2;i++){ cin>>a[i]; } int alice,bob; alice = bob = 0; int x; for(int i=0;i<=2;i++){ cin>>x; if(x > a[i]){ bob++; continue; } if(x < a[i]){ alice++; continue; } } cout<<alice<<" "<<bob; // getch(); return 0; }
15.233333
26
0.380744
9783189e5d4c4aa02546453c02c6a066e94391d3
423
hpp
C++
src/leader/leader_factory.hpp
mrc-g/FogMon
dc040e5566d4fa6b0fca80fb46767f40f19b7c2e
[ "MIT" ]
7
2019-05-08T08:25:40.000Z
2021-06-19T10:42:56.000Z
src/leader/leader_factory.hpp
mrc-g/FogMon
dc040e5566d4fa6b0fca80fb46767f40f19b7c2e
[ "MIT" ]
5
2020-03-07T15:24:27.000Z
2022-03-12T00:49:53.000Z
src/leader/leader_factory.hpp
mrc-g/FogMon
dc040e5566d4fa6b0fca80fb46767f40f19b7c2e
[ "MIT" ]
4
2020-03-05T17:05:42.000Z
2021-11-21T16:00:56.000Z
#ifndef LEADER_FACTORY_HPP_ #define LEADER_FACTORY_HPP_ #include "leader_connections.hpp" #include "factory.hpp" #include "leader_storage.hpp" #include "server.hpp" class LeaderFactory : public Factory { public: virtual ILeaderStorage* newStorage(std::string path, Message::node node); virtual LeaderConnections* newConnections(int nThread); virtual Server* newServer(IConnections* conn, int port); }; #endif
26.4375
77
0.777778
97833df0227057c09fa51fbf52d1ba81477f4cff
5,366
hpp
C++
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/msw/proto/spp/packer.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/msw/proto/spp/packer.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/msw/proto/spp/packer.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
#pragma once #include <limits> #include <exception> #include <functional> #include <type_traits> #include <msw/config.hpp> #include <msw/buffer.hpp> #include <msw/noncopyable.hpp> #include <msw/throw_runtime_error.hpp> namespace msw { namespace spp { template <typename SizeType = wbyte> struct packer : noncopyable { typedef SizeType size_type ; typedef std::function<void(range<byte>)> packet_ready ; static_assert(std::numeric_limits<size_type>::is_integer && std::is_unsigned<size_type>::value, "SizeType must be only unsigned integer type"); explicit packer(packet_ready packet_ready, size<byte> buffer_capacity = msw::KB * 64, size<byte> offset = 0) : offset_ ( offset ) , buf_ ( 0, buffer_capacity ) , last_packet_len_ ( 0 ) , packet_ready_ ( packet_ready ) {} ~packer() { if (!std::uncaught_exception()) flush(); } template <typename ...T> void add_packet(T&& ...v) { flush(); put_packet(std::forward<T>(v)...); zzz_flush(); } template <typename ...T> void add_packet_silent(T&& ...v) { flush(); put_packet_silent(std::forward<T>(v)...); zzz_flush(); } template <typename ...Ts> void put_packet(Ts&& ...vs) { zzz_add_header(); put_to_last_packet(std::forward<Ts>(vs)...); } template <typename ...Ts> void put_packet_silent(Ts&& ...vs) { zzz_add_header_silent(); put_to_last_packet_silent(std::forward<Ts>(vs)...); } void put_to_last_packet(range<byte const> block) { auto const max_block_size = size<byte>(std::numeric_limits<size_type>::max()); if ((size<byte>(last_packet_len_) + block.size()) > max_block_size) msw::throw_runtime_error("large block: ", last_packet_len_ , " + ", block.size(), " (max permissible size: ", max_block_size, ")"); if (buf_.empty()) zzz_add_header(); zzz_add_last_packet_len(static_cast<size_type>(block.size().count())); buf_.push_back(block); } template <typename T> void put_to_last_packet(T&& v) { #ifdef MSW_ODD_STD_FORWARD put_to_last_packet(make_range<byte const>(v)); #else put_to_last_packet(make_range<byte const>(std::forward<T>(v))); #endif } template <typename T, typename ...Ts> void put_to_last_packet(T&& v, Ts&& ...vs) { put_to_last_packet(std::forward<T>(v)); put_to_last_packet(std::forward<Ts>(vs)...); } void put_to_last_packet_silent(range<byte const> block) { MSW_ASSERT((size<byte>(last_packet_len_) + block.size()) <= size<byte>(std::numeric_limits<size_type>::max())); if (buf_.empty()) zzz_add_header_silent(); zzz_add_last_packet_len(static_cast<size_type>(block.size().count())); buf_.push_back_silent(block); } template <typename T> void put_to_last_packet_silent(T&& v) { put_to_last_packet_silent(make_range<byte const>(std::forward<T>(v))); } template <typename T, typename ...Ts> void put_to_last_packet_silent(T&& v, Ts&& ...vs) { put_to_last_packet_silent(std::forward<T>(v)); put_to_last_packet_silent(std::forward<Ts>(vs)...); } size<byte> packet_size() const { return buf_.size(); } size<byte> capacity() const { return buf_.capacity(); } size<byte> offset() const { return offset_; } bool empty() const { return buf_.empty(); } void flush() { if (buf_.has_items()) zzz_flush(); } void reset() { buf_.clear(); last_packet_len_ = 0; } private: void zzz_flush() { packet_ready_(buf_.all()); last_packet_len_ = 0; buf_.clear(); } void zzz_add_header() { if (buf_.empty()) buf_.resize(offset_); buf_.push_back(size_type(0)); last_packet_len_ = 0; } void zzz_add_header_silent() { if (buf_.empty()) buf_.resize(offset_); buf_.push_back_silent(size_type(0)); last_packet_len_ = 0; } void zzz_add_last_packet_len(size_type len) { size_type& packet_len = buf_.back(last_packet_len_ + sizeof(size_type)).template front<size_type>(); last_packet_len_ += len; packet_len += len; MSW_ASSERT(packet_len == last_packet_len_); } size<byte> const offset_ ; buffer<byte> buf_ ; size_type last_packet_len_ ; packet_ready packet_ready_ ; }; typedef packer<byte> packer_8 ; typedef packer<wbyte> packer_16 ; typedef packer<qbyte> packer_32 ; }}
30.488636
151
0.533545
97836c40c9b767bee00ff4f816050487973638fa
5,084
cpp
C++
sender.cpp
dcberumen/Shared-Memory
eaf3970df962db713317de9011aa952b6b13428f
[ "MIT" ]
null
null
null
sender.cpp
dcberumen/Shared-Memory
eaf3970df962db713317de9011aa952b6b13428f
[ "MIT" ]
null
null
null
sender.cpp
dcberumen/Shared-Memory
eaf3970df962db713317de9011aa952b6b13428f
[ "MIT" ]
null
null
null
#include <sys/shm.h> #include <sys/msg.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "msg.h" /* For the message struct */ /* The size of the shared memory chunk */ #define SHARED_MEMORY_CHUNK_SIZE 1000 /* The ids for the shared memory segment and the message queue */ int shmid, msqid; /* The pointer to the shared memory */ void* sharedMemPtr; /** * Sets up the shared memory segment and message queue * @param shmid - the id of the allocated shared memory * @param msqid - the id of the shared memory */ void init(int& shmid, int& msqid, void*& sharedMemPtr) { int key; key = ftok("keyfile.txt", 'a'); if(key == -1) { perror("ftok"); exit(-1); } /* TODO: 1. Create a file called keyfile.txt containing string "Hello world" (you may do so manually or from the code). 2. Use ftok("keyfile.txt", 'a') in order to generate the key. 3. Use the key in the TODO's below. Use the same key for the queue and the shared memory segment. This also serves to illustrate the difference between the key and the id used in message queues and shared memory. The id for any System V objest (i.e. message queues, shared memory, and sempahores) is unique system-wide among all SYstem V objects. Two objects, on the other hand, may have the same key. */ /* TODO: Get the id of the shared memory segment. The size of the segment must be SHARED_MEMORY_CHUNK_SIZE */ shmid = shmget(key, SHARED_MEMORY_CHUNK_SIZE, 0644 | IPC_CREAT); if(shmid == -1) { perror("shmget"); exit(-1); } /* TODO: Attach to the shared memory */ sharedMemPtr = shmat(shmid, (void *)0, 0); if(sharedMemPtr == (void *)-1) { perror("shmat"); exit(-1); } /* TODO: Attach to the message queue */ /* Store the IDs and the pointer to the shared memory region in the corresponding parameters */ msqid = msgget(key,IPC_CREAT|0644); if(msqid == -1) { perror("msgget"); exit(-1); } } /** * Performs the cleanup functions * @param sharedMemPtr - the pointer to the shared memory * @param shmid - the id of the shared memory segment * @param msqid - the id of the message queue */ void cleanUp(const int& shmid, const int& msqid, void* sharedMemPtr) { /* TODO: Detach from shared memory */\ if (shmdt(sharedMemPtr) == -1) { perror("shmdt"); exit(1); } printf("Detatched from shared memory\n"); } /** * The main send function * @param fileName - the name of the file */ void send(const char* fileName) { /* Open the file for reading */ FILE* fp = fopen(fileName, "r"); /* A buffer to store message we will send to the receiver. */ message sndMsg; /* A buffer to store message received from the receiver. */ message recMsg; /* Was the file open? */ if(!fp) { perror("fopen"); exit(-1); } /* Read the whole file */ while(!feof(fp)) { /* Read at most SHARED_MEMORY_CHUNK_SIZE from the file and store them in shared memory. * fread will return how many bytes it has actually read (since the last chunk may be less * than SHARED_MEMORY_CHUNK_SIZE). */ if((sndMsg.size = fread(sharedMemPtr, sizeof(char), SHARED_MEMORY_CHUNK_SIZE, fp)) < 0) { perror("fread"); exit(-1); } /* TODO: Send a message to the receiver telling him that the data is ready * (message of type SENDER_DATA_TYPE) */ sndMsg.mtype = SENDER_DATA_TYPE; printf("Ready to send %d \n", sndMsg.size); if(msgsnd(msqid, &sndMsg.mtype, sndMsg.size, sndMsg.mtype) == -1) { perror("msgsnd"); exit(-1); } /* TODO: Wait until the receiver sends us a message of type RECV_DONE_TYPE telling us * that he finished saving the memory chunk. */ printf("Waiting for conformation of send\n"); recMsg.mtype = RECV_DONE_TYPE; if(msgrcv(msqid, &recMsg.mtype, 0, recMsg.mtype, 0) == -1) { perror("msgrcv"); exit(-1); } printf("Conformation recieved\n"); } /** TODO: once we are out of the above loop, we have finished sending the file. * Lets tell the receiver that we have nothing more to send. We will do this by * sending a message of type SENDER_DATA_TYPE with size field set to 0. */ sndMsg.mtype = SENDER_DATA_TYPE; if(msgsnd(msqid, &sndMsg.mtype, 0, sndMsg.mtype) == -1) { perror("msgsnd"); exit(-1); } /* Close the file */ fclose(fp); } int main(int argc, char** argv) { /* Check the command line arguments */ if(argc < 2) { fprintf(stderr, "USAGE: %s <FILE NAME>\n", argv[0]); exit(-1); } /* Connect to shared memory and the message queue */ init(shmid, msqid, sharedMemPtr); /* Send the file */ send(argv[1]); /* Cleanup */ cleanUp(shmid, msqid, sharedMemPtr); return 0; }
26.479167
111
0.608379
97839573dbebe5642e4b67d09a062c8bcb9e83d5
24,403
cpp
C++
system.cpp
YunzheZJU/GLSL_Edge
5b6a8ee1890747d2d898645594f4965d2ae114b1
[ "MIT" ]
null
null
null
system.cpp
YunzheZJU/GLSL_Edge
5b6a8ee1890747d2d898645594f4965d2ae114b1
[ "MIT" ]
null
null
null
system.cpp
YunzheZJU/GLSL_Edge
5b6a8ee1890747d2d898645594f4965d2ae114b1
[ "MIT" ]
null
null
null
// // System.cpp // Processing system display and control // Created by Yunzhe on 2017/12/4. // #include "system.h" Shader shader = Shader(); VBOPlane *plane; VBOTeapot *teapot; VBOTorus *torus; GLuint fboHandle; GLuint pass1Index; GLuint pass2Index; GLuint renderTex; GLuint fsQuad; mat4 model; mat4 view; mat4 projection; GLfloat angle = 0.0f; // Use this to control the rotation GLfloat edgeThreshold = 0.01f; // Threshold of edge detection GLfloat camera[3] = {0, 0, 5}; // Position of camera GLfloat target[3] = {0, 0, 0}; // Position of target of camera GLfloat camera_polar[3] = {5, -1.57f, 0}; // Polar coordinates of camera GLfloat camera_locator[3] = {0, -5, 10}; // Position of shadow of camera int fpsMode = 2; // 0:off, 1:on, 2:waiting int window[2] = {1280, 720}; // Window size int windowCenter[2]; // Center of this window, to be updated char message[70] = "Welcome!"; // Message string to be shown bool bMsaa = false; // Switch of multisampling anti-alias bool bCamera = true; // Switch of camera/target control bool bFocus = true; // Status of window focus bool bMouse = false; // Whether mouse postion should be moved void Idle() { glutPostRedisplay(); } void Reshape(int width, int height) { if (height == 0) { // Prevent A Divide By Zero By height = 1; // Making Height Equal One } glViewport(static_cast<GLint>(width / 2.0 - 640), static_cast<GLint>(height / 2.0 - 360), 1280, 720); window[W] = width; window[H] = height; shader.setUniform("Width", window[W]); shader.setUniform("Height", window[H]); updateWindowcenter(window, windowCenter); glMatrixMode(GL_PROJECTION); // Select The Projection Matrix glLoadIdentity(); // Reset The Projection Matrix gluPerspective(45.0f, 1.7778f, 0.1f, 30000.0f); // 1.7778 = 1280 / 720 glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix } void Redraw() { shader.use(); glBindFramebuffer(GL_FRAMEBUFFER, fboHandle); // Render scene glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); // Reset The Current Modelview Matrix // 必须定义,以在固定管线中绘制物体 gluLookAt(camera[X], camera[Y], camera[Z], target[X], target[Y], target[Z], 0, 1, 0); // Define the view matrix if (bMsaa) { glEnable(GL_MULTISAMPLE_ARB); } else { glDisable(GL_MULTISAMPLE_ARB); } angle += 0.5f; glUniformSubroutinesuiv(GL_FRAGMENT_SHADER, 1, &pass1Index); glEnable(GL_DEPTH_TEST); // Draw something here updateMVPZero(); updateMVPOne(); teapot->render(); // updateMVPTwo(); // plane->render(); updateMVPThree(); torus->render(); glFlush(); ////////////////////////////////////// glBindFramebuffer(GL_FRAMEBUFFER, 0); // Render filter Image glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, renderTex); glDisable(GL_DEPTH_TEST); glClear(GL_COLOR_BUFFER_BIT); glUniformSubroutinesuiv(GL_FRAGMENT_SHADER, 1, &pass2Index); model = mat4(1.0f); view = mat4(1.0f); projection = mat4(1.0f); updateShaderMVP(); // Render the full-screen quad glBindVertexArray(fsQuad); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); shader.disable(); // Draw crosshair and locator in fps mode, or target when in observing mode(fpsMode == 0). if (fpsMode == 0) { glDisable(GL_DEPTH_TEST); drawLocator(target, LOCATOR_SIZE); glEnable(GL_DEPTH_TEST); } else { drawCrosshair(); camera_locator[X] = camera[X]; camera_locator[Z] = camera[Z]; glDisable(GL_DEPTH_TEST); drawLocator(camera_locator, LOCATOR_SIZE); glEnable(GL_DEPTH_TEST); } // Show fps, message and other information PrintStatus(); glutSwapBuffers(); } void ProcessMouseClick(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { bMsaa = !bMsaa; cout << "LMB pressed. Switch on/off multisampling anti-alias.\n" << endl; strcpy(message, "LMB pressed. Switch on/off multisampling anti-alias."); glutPostRedisplay(); } } void ProcessMouseMove(int x, int y) { cout << "Mouse moves to (" << x << ", " << y << ")" << endl; if (fpsMode) { // Track target and reverse mouse moving to center point. if (fpsMode == 2) { // 鼠标位置居中,为确保在glutPositionWindow()之后执行 updateWindowcenter(window, windowCenter); SetCursorPos(windowCenter[X], windowCenter[Y]); glutSetCursor(GLUT_CURSOR_NONE); fpsMode = 1; return; } if (x < window[W] * 0.25) { x += window[W] * 0.5; bMouse = !bMouse; } else if (x > window[W] * 0.75) { x -= window[W] * 0.5; bMouse = !bMouse; } if (y < window[H] * 0.25) { y = static_cast<int>(window[H] * 0.25); bMouse = !bMouse; } else if (y > window[H] * 0.75) { y = static_cast<int>(window[H] * 0.75); bMouse = !bMouse; } // 将新坐标与屏幕中心的差值换算为polar的变化 camera_polar[A] = static_cast<GLfloat>((window[W] / 2 - x) * (180 / 180.0 * PI) / (window[W] / 4.0) * PANNING_PACE); // Delta pixels * 180 degrees / (1/4 width) * PANNING_PACE camera_polar[T] = static_cast<GLfloat>((window[H] / 2 - y) * (90 / 180.0 * PI) / (window[H] / 4.0) * PANNING_PACE); // Delta pixels * 90 degrees / (1/4 height) * PANNING_PACE // 移动光标 if (bMouse) { SetCursorPos(glutGet(GLUT_WINDOW_X) + x, glutGet(GLUT_WINDOW_Y) + y); bMouse = !bMouse; } // 更新摄像机目标 updateTarget(camera, target, camera_polar); } } void ProcessFocus(int state) { if (state == GLUT_LEFT) { bFocus = false; cout << "Focus is on other window." << endl; } else if (state == GLUT_ENTERED) { bFocus = true; cout << "Focus is on this window." << endl; } } void ProcessNormalKey(unsigned char k, int x, int y) { switch (k) { // 退出程序 case 27: { cout << "Bye." << endl; exit(0); } // 切换摄像机本体/焦点控制 case 'Z': case 'z': { strcpy(message, "Z pressed. Switch camera control!"); bCamera = !bCamera; break; } // 切换第一人称控制 case 'C': case 'c': { strcpy(message, "C pressed. Switch fps control!"); // 摄像机归零 cameraMakeZero(camera, target, camera_polar); if (!fpsMode) { // 调整窗口位置 int windowmaxx = glutGet(GLUT_WINDOW_X) + window[W]; int windowmaxy = glutGet(GLUT_WINDOW_Y) + window[H]; if (windowmaxx >= glutGet(GLUT_SCREEN_WIDTH) || windowmaxy >= glutGet(GLUT_SCREEN_HEIGHT)) { // glutPositionWindow()并不会立即执行! glutPositionWindow(glutGet(GLUT_SCREEN_WIDTH) - window[W], glutGet(GLUT_SCREEN_HEIGHT) - window[H]); fpsMode = 2; break; } // 鼠标位置居中 updateWindowcenter(window, windowCenter); // windowCenter[X] - window[W] * 0.25 为什么要减? SetCursorPos(windowCenter[X], windowCenter[Y]); glutSetCursor(GLUT_CURSOR_NONE); fpsMode = 1; } else { glutSetCursor(GLUT_CURSOR_RIGHT_ARROW); fpsMode = 0; } break; } // 第一人称移动/摄像机本体移动/焦点移动 case 'A': case 'a': { strcpy(message, "A pressed. Watch carefully!"); if (fpsMode) { saveCamera(camera, target, camera_polar); camera[X] -= cos(camera_polar[A]) * MOVING_PACE; camera[Z] += sin(camera_polar[A]) * MOVING_PACE; target[X] -= cos(camera_polar[A]) * MOVING_PACE; target[Z] += sin(camera_polar[A]) * MOVING_PACE; } else { if (bCamera) { camera_polar[A] -= OBSERVING_PACE * 0.1; updateCamera(camera, target, camera_polar); cout << fixed << setprecision(1) << "A pressed.\n\tPosition of camera is set to (" << camera[X] << ", " << camera[Y] << ", " << camera[Z] << ")." << endl; } else { target[X] -= OBSERVING_PACE; updatePolar(camera, target, camera_polar); cout << fixed << setprecision(1) << "A pressed.\n\tPosition of camera target is set to (" << target[X] << ", " << target[Y] << ", " << target[Z] << ")." << endl; } } break; } case 'D': case 'd': { strcpy(message, "D pressed. Watch carefully!"); if (fpsMode) { saveCamera(camera, target, camera_polar); camera[X] += cos(camera_polar[A]) * MOVING_PACE; camera[Z] -= sin(camera_polar[A]) * MOVING_PACE; target[X] += cos(camera_polar[A]) * MOVING_PACE; target[Z] -= sin(camera_polar[A]) * MOVING_PACE; } else { if (bCamera) { camera_polar[A] += OBSERVING_PACE * 0.1; updateCamera(camera, target, camera_polar); cout << fixed << setprecision(1) << "D pressed.\n\tPosition of camera is set to (" << camera[X] << ", " << camera[Y] << ", " << camera[Z] << ")." << endl; } else { target[X] += OBSERVING_PACE; updatePolar(camera, target, camera_polar); cout << fixed << setprecision(1) << "D pressed.\n\tPosition of camera target is set to (" << target[X] << ", " << target[Y] << ", " << target[Z] << ")." << endl; } } break; } case 'W': case 'w': { strcpy(message, "W pressed. Watch carefully!"); if (fpsMode) { saveCamera(camera, target, camera_polar); camera[X] -= sin(camera_polar[A]) * MOVING_PACE; camera[Z] -= cos(camera_polar[A]) * MOVING_PACE; target[X] -= sin(camera_polar[A]) * MOVING_PACE; target[Z] -= cos(camera_polar[A]) * MOVING_PACE; } else { if (bCamera) { camera[Y] += OBSERVING_PACE; cout << fixed << setprecision(1) << "W pressed.\n\tPosition of camera is set to (" << camera[X] << ", " << camera[Y] << ", " << camera[Z] << ")." << endl; } else { target[Y] += OBSERVING_PACE; updatePolar(camera, target, camera_polar); cout << fixed << setprecision(1) << "W pressed.\n\tPosition of camera target is set to (" << target[X] << ", " << target[Y] << ", " << target[Z] << ")." << endl; } } break; } case 'S': case 's': { strcpy(message, "S pressed. Watch carefully!"); if (fpsMode) { saveCamera(camera, target, camera_polar); camera[X] += sin(camera_polar[A]) * MOVING_PACE; camera[Z] += cos(camera_polar[A]) * MOVING_PACE; target[X] += sin(camera_polar[A]) * MOVING_PACE; target[Z] += cos(camera_polar[A]) * MOVING_PACE; } else { if (bCamera) { camera[Y] -= OBSERVING_PACE; cout << fixed << setprecision(1) << "S pressed.\n\tPosition of camera is set to (" << camera[X] << ", " << camera[Y] << ", " << camera[Z] << ")." << endl; strcpy(message, "S pressed. Watch carefully!"); } else { target[Y] -= OBSERVING_PACE; updatePolar(camera, target, camera_polar); cout << fixed << setprecision(1) << "S pressed.\n\tPosition of camera target is set to (" << target[X] << ", " << target[Y] << ", " << target[Z] << ")." << endl; } } break; } case 'Q': case 'q': { if (bCamera) { strcpy(message, "Q pressed. Camera is moved...nearer!"); camera_polar[R] *= 0.95; updateCamera(camera, target, camera_polar); cout << fixed << setprecision(1) << "Q pressed.\n\tPosition of camera is set to (" << camera[X] << ", " << camera[Y] << ", " << camera[Z] << ")." << endl; } else { strcpy(message, "Q pressed. Camera target is moving towards +Z!"); target[Z] += OBSERVING_PACE; updatePolar(camera, target, camera_polar); cout << fixed << setprecision(1) << "Q pressed.\n\tPosition of camera target is set to (" << target[X] << ", " << target[Y] << ", " << target[Z] << ")." << endl; } break; } case 'E': case 'e': { if (bCamera) { strcpy(message, "E pressed. Camera is moved...farther!"); camera_polar[R] *= 1.05; updateCamera(camera, target, camera_polar); cout << fixed << setprecision(1) << "E pressed.\n\tPosition of camera is set to (" << camera[X] << ", " << camera[Y] << ", " << camera[Z] << ")." << endl; } else { strcpy(message, "E pressed. Camera target is moving towards -Z!"); target[Z] -= OBSERVING_PACE; updatePolar(camera, target, camera_polar); cout << fixed << setprecision(1) << "E pressed.\n\tPosition of camera target is set to (" << target[X] << ", " << target[Y] << ", " << target[Z] << ")." << endl; } break; } // 边缘检测阈值 case '+': { cout << "+ pressed." << endl; if (edgeThreshold < EDGE_THRESHOLD_MAX) { edgeThreshold += EDGE_THRESHOLD_STEP; cout << fixed << setprecision(4) << "Threshold of edge detection is set to " << edgeThreshold << "." << endl; sprintf(message, "Threshold of edge detection is set to %.4f.", edgeThreshold); } break; } case '-': { cout << "- pressed." << endl; if (edgeThreshold > EDGE_THRESHOLD_MIX) { edgeThreshold -= EDGE_THRESHOLD_STEP; cout << fixed << setprecision(4) << "Threshold of edge detection is set to " << edgeThreshold << "." << endl; sprintf(message, "Threshold of edge detection is set to %.4f.", edgeThreshold); } break; } // 屏幕截图 case 'X': case 'x': { cout << "X pressed." << endl; if (screenshot(window[W], window[H])) { cout << "Screenshot is saved." << endl; strcpy(message, "X pressed. Screenshot is Saved."); } else { cout << "Screenshot failed." << endl; strcpy(message, "X pressed. Screenshot failed."); } break; } default: break; } } void PrintStatus() { static int frame = 0; static int currenttime; static int timebase = 0; static char fpstext[50]; char *c; char cameraPositionMessage[50]; char targetPositionMessage[50]; char cameraPolarPositonMessage[50]; frame++; currenttime = glutGet(GLUT_ELAPSED_TIME); if (currenttime - timebase > 1000) { sprintf(fpstext, "FPS:%4.2f", frame * 1000.0 / (currenttime - timebase)); timebase = currenttime; frame = 0; } sprintf(cameraPositionMessage, "Camera Position %2.1f %2.1f %2.1f", camera[X], camera[Y], camera[Z]); sprintf(targetPositionMessage, "Target Position %2.1f %2.1f %2.1f", target[X], target[Y], target[Z]); sprintf(cameraPolarPositonMessage, "Camera Polar %2.1f %2.3f %2.3f", camera_polar[R], camera_polar[A], camera_polar[T]); glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); // 不受灯光影响 glMatrixMode(GL_PROJECTION); // 选择投影矩阵 glPushMatrix(); // 保存原矩阵 glLoadIdentity(); // 装入单位矩阵 glOrtho(-window[W] / 2, window[W] / 2, -window[H] / 2, window[H] / 2, -1, 1); // 设置裁减区域 glMatrixMode(GL_MODELVIEW); // 选择Modelview矩阵 glPushMatrix(); // 保存原矩阵 glLoadIdentity(); // 装入单位矩阵 glPushAttrib(GL_LIGHTING_BIT); glRasterPos2f(20 - window[W] / 2, window[H] / 2 - 20); for (c = fpstext; *c != '\0'; c++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c); } glRasterPos2f(window[W] / 2 - 240, window[H] / 2 - 20); for (c = cameraPositionMessage; *c != '\0'; c++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, *c); } glRasterPos2f(window[W] / 2 - 240, window[H] / 2 - 55); for (c = targetPositionMessage; *c != '\0'; c++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, *c); } glRasterPos2f(window[W] / 2 - 240, window[H] / 2 - 90); for (c = cameraPolarPositonMessage; *c != '\0'; c++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, *c); } glRasterPos2f(20 - window[W] / 2, 20 - window[H] / 2); for (c = message; *c != '\0'; c++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c); } glPopAttrib(); glMatrixMode(GL_PROJECTION); // 选择投影矩阵 glPopMatrix(); // 重置为原保存矩阵 glMatrixMode(GL_MODELVIEW); // 选择Modelview矩阵 glPopMatrix(); // 重置为原保存矩阵 glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); } void initVBO() { plane = new VBOPlane(50.0f, 50.0f, 1, 1); teapot = new VBOTeapot(14, glm::mat4(1.0f)); torus = new VBOTorus(0.7f * 2, 0.3f * 2, 50, 50); } void setShader() { GLuint shaderProgram = shader.getProgram(); pass1Index = glGetSubroutineIndex(shaderProgram, GL_FRAGMENT_SHADER, "pass1"); pass2Index = glGetSubroutineIndex(shaderProgram, GL_FRAGMENT_SHADER, "pass2"); shader.setUniform("Width", window[W]); shader.setUniform("Height", window[H]); shader.setUniform("Light.Intensity", vec3(1.0f, 1.0f, 1.0f)); updateShaderMVP(); } void updateMVPZero() { view = glm::lookAt(vec3(camera[X], camera[Y], camera[Z]), vec3(target[X], target[Y], target[Z]), vec3(0.0f, 1.0f, 0.0f)); projection = glm::perspective(45.0f, 1.7778f, 0.1f, 30000.0f); shader.setUniform("Light.Position", view * vec4(0.0f, 0.0f, 10.0f, 1.0f)); shader.setUniform("EdgeThreshold", edgeThreshold); } void updateMVPOne() { model = mat4(1.0f); model = glm::translate(model, vec3(-2.0f, -1.5f, 0.0f)); model = glm::rotate(model, glm::radians(angle), vec3(0.0f, 1.0f, 0.0f)); model = glm::rotate(model, glm::radians(-90.0f), vec3(1.0f, 0.0f, 0.0f)); shader.setUniform("Material.Kd", 0.9f, 0.9f, 0.9f); shader.setUniform("Material.Ks", 0.95f, 0.95f, 0.95f); shader.setUniform("Material.Ka", 0.1f, 0.1f, 0.1f); shader.setUniform("Material.Shininess", 100.0f); updateShaderMVP(); } void updateMVPTwo() { model = mat4(1.0f); model = glm::translate(model, vec3(0.0f, -2.0f, 0.0f)); shader.setUniform("Material.Kd", 0.4f, 0.4f, 0.4f); shader.setUniform("Material.Ks", 0.0f, 0.0f, 0.0f); shader.setUniform("Material.Ka", 0.1f, 0.1f, 0.1f); shader.setUniform("Material.Shininess", 1.0f); updateShaderMVP(); } void updateMVPThree() { model = mat4(1.0f); model = glm::translate(model, vec3(2.0f, 0.0f, 0.0f)); model = glm::rotate(model, glm::radians(angle), vec3(0.0f, 1.0f, 0.0f)); model = glm::rotate(model, glm::radians(90.0f), vec3(1.0f, 0.0f, 0.0f)); shader.setUniform("Material.Kd", 0.9f, 0.5f, 0.2f); shader.setUniform("Material.Ks", 0.95f, 0.95f, 0.95f); shader.setUniform("Material.Ka", 0.1f, 0.1f, 0.1f); shader.setUniform("Material.Shininess", 100.0f); updateShaderMVP(); } void updateShaderMVP() { mat4 mv = view * model; shader.setUniform("ModelViewMatrix", mv); shader.setUniform("NormalMatrix", mat3(vec3(mv[0]), vec3(mv[1]), vec3(mv[2]))); shader.setUniform("MVP", projection * mv); } void setupFBO() { // Generate and bind the framebuffer glGenFramebuffers(1, &fboHandle); glBindFramebuffer(GL_FRAMEBUFFER, fboHandle); // Create the texture object glGenTextures(1, &renderTex); glBindTexture(GL_TEXTURE_2D, renderTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1280, 720, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); // Bind the texture to the FBO glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderTex, 0); // Create the depth buffer GLuint depthBuf; glGenRenderbuffers(1, &depthBuf); glBindRenderbuffer(GL_RENDERBUFFER, depthBuf); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, 1280, 720); // Bind the depth buffer to the FBO glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuf); // Set the targets for the fragment output variables GLenum drawBuffers[] = {GL_COLOR_ATTACHMENT0, GL_NONE}; glDrawBuffers(1, drawBuffers); GLenum result = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (result == GL_FRAMEBUFFER_COMPLETE) { cout << "Framebuffer is complete" << endl; } else { cout << "Framebuffer error: " << result << endl; } // Unbind the framebuffer, and revert to default framebuffer glBindFramebuffer(GL_FRAMEBUFFER, 0); } void setupVAO() { // Array for full-screen quad GLfloat verts[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f }; GLfloat tc[] = { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f }; // Set up the buffers unsigned int handle[2]; glGenBuffers(2, handle); glBindBuffer(GL_ARRAY_BUFFER, handle[0]); glBufferData(GL_ARRAY_BUFFER, 6 * 3 * sizeof(float), verts, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, handle[1]); glBufferData(GL_ARRAY_BUFFER, 6 * 2 * sizeof(float), tc, GL_STATIC_DRAW); // Set up the vertex array object glGenVertexArrays(1, &fsQuad); glBindVertexArray(fsQuad); glBindBuffer(GL_ARRAY_BUFFER, handle[0]); glVertexAttribPointer((GLuint) 0, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(0); // Vertex position glBindBuffer(GL_ARRAY_BUFFER, handle[1]); glVertexAttribPointer((GLuint) 2, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(2); // Texture coordinates glBindVertexArray(0); } void initShader() { try { shader.compileShader("edge.vert"); shader.compileShader("edge.frag"); shader.link(); shader.use(); } catch (GLSLProgramException &e) { cerr << e.what() << endl; exit(EXIT_FAILURE); } }
39.359677
131
0.533787
978d4b0d959ed6727d5d1d7bc48fe5a5359b0ce0
1,543
cc
C++
facebody/src/model/GenerateHumanSketchStyleRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
facebody/src/model/GenerateHumanSketchStyleRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
facebody/src/model/GenerateHumanSketchStyleRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/facebody/model/GenerateHumanSketchStyleRequest.h> using AlibabaCloud::Facebody::Model::GenerateHumanSketchStyleRequest; GenerateHumanSketchStyleRequest::GenerateHumanSketchStyleRequest() : RpcServiceRequest("facebody", "2019-12-30", "GenerateHumanSketchStyle") { setMethod(HttpRequest::Method::Post); } GenerateHumanSketchStyleRequest::~GenerateHumanSketchStyleRequest() {} std::string GenerateHumanSketchStyleRequest::getReturnType()const { return returnType_; } void GenerateHumanSketchStyleRequest::setReturnType(const std::string& returnType) { returnType_ = returnType; setBodyParameter("ReturnType", returnType); } std::string GenerateHumanSketchStyleRequest::getImageURL()const { return imageURL_; } void GenerateHumanSketchStyleRequest::setImageURL(const std::string& imageURL) { imageURL_ = imageURL; setBodyParameter("ImageURL", imageURL); }
29.673077
83
0.771225
978d96e541afbdd13cc3940ff9fd0a530b8b17a3
2,337
hpp
C++
cross.hpp
Granvallen/RoutePlanning
e420e42f5c5dd5b79d525d4c21e183b56f42b096
[ "MIT" ]
3
2019-04-10T09:06:21.000Z
2020-08-26T01:12:06.000Z
cross.hpp
Granvallen/RoutePlanning
e420e42f5c5dd5b79d525d4c21e183b56f42b096
[ "MIT" ]
null
null
null
cross.hpp
Granvallen/RoutePlanning
e420e42f5c5dd5b79d525d4c21e183b56f42b096
[ "MIT" ]
null
null
null
#ifndef CROSS_HPP #define CROSS_HPP #include <vector> #include <fstream> #include <iostream> #include <sstream> #include <string> //#include <unordered_map> #include <map> using namespace std; class Cross { public: Cross() {} //Cross(long id, long road0, long road1, long road2, long road3) : id(id) //{ // road_id[road0] = 0; road_id[road1] = 1; // road_id[road2] = 2; road_id[road3] = 3; //} Cross(long* crossinfo) { if (crossinfo) { id = crossinfo[0]; // 注意这里没路的 -1 也会放进去 把序号作为键 路id为值 road_id[0] = crossinfo[1]; road_id[1] = crossinfo[2]; road_id[2] = crossinfo[3]; road_id[3] = crossinfo[4]; } } friend ostream & operator<<(ostream &out, Cross &cross); // 由路序号得到路id long getRoadIdx(int roadid) { for (auto& i : road_id) if (i.second == roadid) return i.first; return -1; } long id; // 路口id map<long, int> road_id; // 四个连接道路的id 没路的为-1 用map可以实现路id升序 //int road_num; // 连接道路数目 bool isBlock; // 是否堵塞 private: }; ostream & operator<<(ostream &out, Cross &cross) { out << "cross id: " << cross.id << endl << "road0: " << cross.road_id[0] << endl << "road1: " << cross.road_id[1] << endl << "road2: " << cross.road_id[2] << endl << "road3: " << cross.road_id[3] << endl; return out; } class CrossList { public: CrossList() {} CrossList(string crossfile) { initCrossList(crossfile); } void initCrossList(string crossfile); Cross & operator[](long i) { return crosslist[i]; } void add(Cross& cross) { crosslist[cross.id] = cross; } void remove(long id) { crosslist.erase(id); } const map<long, Cross>& getList() { return crosslist; } map<long, Cross>::iterator begin() { return crosslist.begin(); } map<long, Cross>::iterator end() { return crosslist.end(); } private: map<long, Cross> crosslist; // 由于之后cross要按id从小到大遍历 所以用有序map }; void CrossList::initCrossList(string crossfile) { const int N = 5; ifstream cross_in(crossfile); string line; if (cross_in) while (getline(cross_in, line)) { if (line[0] == '#') continue; line = line.substr(1, line.length() - 2); istringstream iss(line); string s; long crossinfo[N]; for (int i = 0; i < N && getline(iss, s, ','); i++) crossinfo[i] = atol(s.c_str()); crosslist[crossinfo[0]] = Cross(crossinfo); } else cout << "the cross.txt open failed." << endl; } #endif
19.805085
74
0.633718
9791022486471675cd10515f685393c43850bd56
134
cpp
C++
src/examples/01_module/01_hello_world/hello.cpp
acc-cosc-1337-summer-2020-classroom/acc-cosc-1337-summer-2020-justinpesz
44adcb5fb1a307c6b5f59b4235fe83a7eb363002
[ "MIT" ]
null
null
null
src/examples/01_module/01_hello_world/hello.cpp
acc-cosc-1337-summer-2020-classroom/acc-cosc-1337-summer-2020-justinpesz
44adcb5fb1a307c6b5f59b4235fe83a7eb363002
[ "MIT" ]
null
null
null
src/examples/01_module/01_hello_world/hello.cpp
acc-cosc-1337-summer-2020-classroom/acc-cosc-1337-summer-2020-justinpesz
44adcb5fb1a307c6b5f59b4235fe83a7eb363002
[ "MIT" ]
null
null
null
#include "hello.h" double calculate_paycheck(double num1, double num2) { auto payrate = num1 / num2; return payrate; }
13.4
51
0.664179
97951e41aa7ee667fa01636589259e0bf4c56bb8
2,688
hpp
C++
bhash.hpp
logogin/bep
25ff90211924deea1c4ef07752cb826df43e2ad3
[ "BSD-3-Clause" ]
null
null
null
bhash.hpp
logogin/bep
25ff90211924deea1c4ef07752cb826df43e2ad3
[ "BSD-3-Clause" ]
null
null
null
bhash.hpp
logogin/bep
25ff90211924deea1c4ef07752cb826df43e2ad3
[ "BSD-3-Clause" ]
null
null
null
#ifndef __BHASH_HPP__ #define __BHASH_HPP__ #include <string> #include <vector> #include <map> #include <queue> #include <math.h> #include <stdlib.h> namespace bep_tool{ typedef unsigned long long int ub8; // unsigned 8-byte typedef unsigned int ub4; // unsigned 4-byte typedef unsigned char ub; // unsigned 1-byte using namespace std; struct hg_edge{ public: hg_edge(const ub4* _v){ v[0] = _v[0]; v[1] = _v[1]; v[2] = _v[2]; } hg_edge(const ub8* _v){ v[0] = (ub4)_v[0]; v[1] = (ub4)_v[1]; v[2] = (ub4)_v[2]; } int operator < (const hg_edge& a) const { return v[0] != a.v[0] ? v[0] < a.v[0] : v[1] != a.v[1] ? v[1] < a.v[1] : v[2] < a.v[2]; } int operator == (const hg_edge & a) const { return (v[0] == a.v[0]) && (v[1] == a.v[1]) && (v[2] == a.v[2]); } ub4 v[3]; }; static const double C_R = 1.3; static const ub4 NOTFOUND = -1; static const ub4 BYTEBLOCK = 8; static const ub4 INTBLOCK = 32; static const char* KEYEXT = ".key"; class bhash{ public: bhash(); ~bhash(); int build(const vector<string>& keys); // build perfect hash functions for keys int save(const char* fileName) const; // save current perfect hash function to fileName int load(const char* fileName); // load fileName to current perfect hash function ub4 lookup(const string& key) const; // lookup key and return ID or NOTFOUND ub4 lookup_wocheck(const string& key) const; // lookup key and return ID without checking unknown keys bool lookupKey(const size_t i, string& key) const; // return key which retruns i as ID ub4 size() const; // return n private: void bob_mix(ub4& a, ub4& b, ub4& c) const; void bob_hash(const ub* str, const ub4 length, const ub4 init, ub4& a, ub4& b, ub4& c) const; void bob_hash64(const ub* str, const ub4 length, const ub4 init, ub8& a, ub8& b, ub8& c) const; void bob_mix64(ub8& a, ub8& b, ub8& c) const; void clear(); ub4 lookupGVAL(const uint i) const; ub4 seed; // seed for hash functions ub4 n; // number of keys ub4 bn; // number of total buckets (output of NON-minimal perfect hashing) ub4 bn_m; // number of buckets for each hash function // rank tables ub4 rank(const uint i) const; ub4 popCount(const uint i) const; ub4* B; // store the assigned verticies ub4* levelA; // store every 256-th rank result ub* levelB; // store every 32-th rank result ub* gtable; // store g values in compressed representations ub8 keysLen; // total length of keys ub* strTable; // store original keys in raw format ub8* strOffsets; // store key's offsets }; } // bep_tool #endif // __BHASH_HPP__
26.613861
106
0.639509
97965f72395d2a44fbf70895ef4836a59b19f5e2
28,101
cpp
C++
src/Pegasus/Common/tests/OperationContext/TestOperationContext.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
null
null
null
src/Pegasus/Common/tests/OperationContext/TestOperationContext.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
null
null
null
src/Pegasus/Common/tests/OperationContext/TestOperationContext.cpp
ncultra/Pegasus-2.5
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
[ "MIT" ]
1
2022-03-07T22:54:02.000Z
2022-03-07T22:54:02.000Z
//%2005//////////////////////////////////////////////////////////////////////// // // Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development // Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems. // Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.; // IBM Corp.; EMC Corporation, The Open Group. // Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.; // IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group. // Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.; // EMC Corporation; VERITAS Software Corporation; The Open Group. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE SHALL BE INCLUDED IN // ALL COPIES OR SUBSTANTIAL PORTIONS OF THE SOFTWARE. THE SOFTWARE IS PROVIDED // "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // //============================================================================== // // Author: Chip Vincent (cvincent@us.ibm.com) // // Modified By: // Carol Ann Krug Graves, Hewlett-Packard Company(carolann_graves@hp.com) // Yi Zhou, Hewlett-Packard Company (yi_zhou@hp.com) // //%///////////////////////////////////////////////////////////////////////////// #include <Pegasus/Common/Config.h> #include <Pegasus/Common/Constants.h> #include <Pegasus/Common/CIMDateTime.h> #include <Pegasus/Common/CIMName.h> #include <Pegasus/Common/OperationContext.h> #include <Pegasus/Common/OperationContextInternal.h> #include <iostream> PEGASUS_USING_PEGASUS; PEGASUS_USING_STD; static char * verbose = 0; CIMInstance _createFilterInstance1(void) { CIMInstance filterInstance(PEGASUS_CLASSNAME_INDFILTER); // add properties filterInstance.addProperty(CIMProperty("SystemCreationClassName", String("CIM_UnitaryComputerSystem"))); filterInstance.addProperty(CIMProperty("SystemName", String("server001.acme.com"))); filterInstance.addProperty(CIMProperty("CreationClassName", PEGASUS_CLASSNAME_INDFILTER.getString())); filterInstance.addProperty(CIMProperty("Name", String("Filter1"))); filterInstance.addProperty(CIMProperty("Query", String("SELECT * FROM CIM_AlertIndication WHERE AlertType = 5"))); filterInstance.addProperty(CIMProperty("QueryLanguage", String("WQL1"))); filterInstance.addProperty(CIMProperty("SourceNamespace", String("root/PG_InterOp"))); // create keys Array<CIMKeyBinding> keys; keys.append(CIMKeyBinding("SystemCreationClassName", "CIM_UnitaryComputerSystem", CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("SystemName", "server001.acme.com", CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("CreationClassName", PEGASUS_CLASSNAME_INDFILTER.getString(), CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("Name", "Filter1", CIMKeyBinding::STRING)); // update object path CIMObjectPath objectPath = filterInstance.getPath(); objectPath.setKeyBindings(keys); filterInstance.setPath(objectPath); return(filterInstance); } CIMInstance _createHandlerInstance1(void) { CIMInstance handlerInstance(PEGASUS_CLASSNAME_INDHANDLER_CIMXML); // add properties handlerInstance.addProperty(CIMProperty("SystemCreationClassName", String("CIM_UnitaryComputerSystem"))); handlerInstance.addProperty(CIMProperty("SystemName", String("server001.acme.com"))); handlerInstance.addProperty(CIMProperty("CreationClassName", PEGASUS_CLASSNAME_INDHANDLER_CIMXML.getString())); handlerInstance.addProperty(CIMProperty("Name", String("Handler1"))); handlerInstance.addProperty(CIMProperty("Destination", String("localhost:5988/test1"))); // create keys Array<CIMKeyBinding> keys; keys.append(CIMKeyBinding("SystemCreationClassName", "CIM_UnitaryComputerSystem", CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("SystemName", "server001.acme.com", CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("CreationClassName", PEGASUS_CLASSNAME_INDHANDLER_CIMXML.getString(), CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("Name", "Handler1", CIMKeyBinding::STRING)); // update object path CIMObjectPath objectPath = handlerInstance.getPath(); objectPath.setKeyBindings(keys); handlerInstance.setPath(objectPath); return(handlerInstance); } CIMInstance _createFilterInstance2(void) { CIMInstance filterInstance(PEGASUS_CLASSNAME_INDFILTER); // add properties filterInstance.addProperty(CIMProperty("SystemCreationClassName", String("CIM_UnitaryComputerSystem"))); filterInstance.addProperty(CIMProperty("SystemName", String("server001.acme.com"))); filterInstance.addProperty(CIMProperty("CreationClassName", PEGASUS_CLASSNAME_INDFILTER.getString())); filterInstance.addProperty(CIMProperty("Name", String("Filter2"))); filterInstance.addProperty(CIMProperty("Query", String("SELECT * FROM CIM_AlertIndication WHERE AlertType = 8"))); filterInstance.addProperty(CIMProperty("QueryLanguage", String("WQL1"))); filterInstance.addProperty(CIMProperty("SourceNamespace", String("root/PG_InterOp"))); // create keys Array<CIMKeyBinding> keys; keys.append(CIMKeyBinding("SystemCreationClassName", "CIM_UnitaryComputerSystem", CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("SystemName", "server001.acme.com", CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("CreationClassName", PEGASUS_CLASSNAME_INDFILTER.getString(), CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("Name", "Filter2", CIMKeyBinding::STRING)); // update object path CIMObjectPath objectPath = filterInstance.getPath(); objectPath.setKeyBindings(keys); filterInstance.setPath(objectPath); return(filterInstance); } CIMInstance _createHandlerInstance2(void) { CIMInstance handlerInstance(PEGASUS_CLASSNAME_INDHANDLER_CIMXML); // add properties handlerInstance.addProperty(CIMProperty("SystemCreationClassName", String("CIM_UnitaryComputerSystem"))); handlerInstance.addProperty(CIMProperty("SystemName", String("server001.acme.com"))); handlerInstance.addProperty(CIMProperty("CreationClassName", PEGASUS_CLASSNAME_INDHANDLER_CIMXML.getString())); handlerInstance.addProperty(CIMProperty("Name", String("Handler2"))); handlerInstance.addProperty(CIMProperty("Destination", String("localhost:5988/test2"))); // create keys Array<CIMKeyBinding> keys; keys.append(CIMKeyBinding("SystemCreationClassName","CIM_UnitaryComputerSystem", CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("SystemName", "server001.acme.com", CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("CreationClassName", PEGASUS_CLASSNAME_INDHANDLER_CIMXML.getString(), CIMKeyBinding::STRING)); keys.append(CIMKeyBinding("Name", "Handler2", CIMKeyBinding::STRING)); // update object path CIMObjectPath objectPath = handlerInstance.getPath(); objectPath.setKeyBindings(keys); handlerInstance.setPath(objectPath); return(handlerInstance); } CIMInstance _createSubscriptionInstance1(void) { CIMInstance filterInstance1 = _createFilterInstance1(); CIMInstance handlerInstance1 = _createHandlerInstance1(); CIMInstance subscriptionInstance(PEGASUS_CLASSNAME_INDSUBSCRIPTION); // add properties subscriptionInstance.addProperty(CIMProperty("Filter", filterInstance1.getPath(), 0, PEGASUS_CLASSNAME_INDFILTER)); subscriptionInstance.addProperty(CIMProperty("Handler", handlerInstance1.getPath(), 0, PEGASUS_CLASSNAME_INDHANDLER_CIMXML)); subscriptionInstance.addProperty(CIMProperty("OnFatalErrorPolicy", Uint16(4))); subscriptionInstance.addProperty(CIMProperty("FailureTriggerTimeInterval", Uint64(60))); subscriptionInstance.addProperty(CIMProperty("SubscriptionState", Uint16(2))); subscriptionInstance.addProperty(CIMProperty("TimeOfLastStateChange", CIMDateTime::getCurrentDateTime())); subscriptionInstance.addProperty(CIMProperty("SubscriptionDuration", Uint64(86400))); subscriptionInstance.addProperty(CIMProperty("SubscriptionStartTime", CIMDateTime::getCurrentDateTime())); subscriptionInstance.addProperty(CIMProperty("SubscriptionTimeRemaining", Uint64(86400))); subscriptionInstance.addProperty(CIMProperty("RepeatNotificationPolicy", Uint16(1))); subscriptionInstance.addProperty(CIMProperty("OtherRepeatNotificationPolicy", String("AnotherPolicy"))); subscriptionInstance.addProperty(CIMProperty("RepeatNotificationInterval", Uint64(60))); subscriptionInstance.addProperty(CIMProperty("RepeatNotificationGap", Uint64(15))); subscriptionInstance.addProperty(CIMProperty("RepeatNotificationCount", Uint16(3))); // create keys Array<CIMKeyBinding> keys; keys.append(CIMKeyBinding("Filter", filterInstance1.getPath().toString(), CIMKeyBinding::REFERENCE)); keys.append(CIMKeyBinding("Handler", handlerInstance1.getPath().toString(), CIMKeyBinding::REFERENCE)); // update object path CIMObjectPath objectPath = subscriptionInstance.getPath(); objectPath.setKeyBindings(keys); subscriptionInstance.setPath(objectPath); return(subscriptionInstance); } CIMInstance _createSubscriptionInstance2(void) { CIMInstance filterInstance2 = _createFilterInstance2(); CIMInstance handlerInstance2 = _createHandlerInstance2(); CIMInstance subscriptionInstance(PEGASUS_CLASSNAME_INDSUBSCRIPTION); // add properties subscriptionInstance.addProperty(CIMProperty("Filter", filterInstance2.getPath(), 0, PEGASUS_CLASSNAME_INDFILTER)); subscriptionInstance.addProperty(CIMProperty("Handler", handlerInstance2.getPath(), 0, PEGASUS_CLASSNAME_INDHANDLER_CIMXML)); subscriptionInstance.addProperty(CIMProperty("OnFatalErrorPolicy", Uint16(2))); subscriptionInstance.addProperty(CIMProperty("FailureTriggerTimeInterval", Uint64(120))); subscriptionInstance.addProperty(CIMProperty("SubscriptionState", Uint16(2))); subscriptionInstance.addProperty(CIMProperty("TimeOfLastStateChange", CIMDateTime::getCurrentDateTime())); subscriptionInstance.addProperty(CIMProperty("SubscriptionDuration", Uint64(172800))); subscriptionInstance.addProperty(CIMProperty("SubscriptionStartTime", CIMDateTime::getCurrentDateTime())); subscriptionInstance.addProperty(CIMProperty("SubscriptionTimeRemaining", Uint64(172800))); subscriptionInstance.addProperty(CIMProperty("RepeatNotificationPolicy", Uint16(1))); subscriptionInstance.addProperty(CIMProperty("OtherRepeatNotificationPolicy", String("AnotherPolicy2"))); subscriptionInstance.addProperty(CIMProperty("RepeatNotificationInterval", Uint64(120))); subscriptionInstance.addProperty(CIMProperty("RepeatNotificationGap", Uint64(30))); subscriptionInstance.addProperty(CIMProperty("RepeatNotificationCount", Uint16(6))); // create keys Array<CIMKeyBinding> keys; keys.append(CIMKeyBinding("Filter", filterInstance2.getPath().toString(), CIMKeyBinding::REFERENCE)); keys.append(CIMKeyBinding("Handler", handlerInstance2.getPath().toString(), CIMKeyBinding::REFERENCE)); // update object path CIMObjectPath objectPath = subscriptionInstance.getPath(); objectPath.setKeyBindings(keys); subscriptionInstance.setPath(objectPath); return(subscriptionInstance); } // // IdentityContainer // void Test1(void) { if(verbose) { cout << "Test1()" << endl; } OperationContext context; { String userName("Yoda"); context.insert(IdentityContainer(userName)); IdentityContainer container = context.get(IdentityContainer::NAME); if(userName != container.getUserName()) { cout << "----- Identity Container failed" << endl; throw 0; } } context.clear(); { String userName("Yoda"); context.insert(IdentityContainer(userName)); // // This test exercises the IdentityContainer copy constructor // IdentityContainer container = context.get(IdentityContainer::NAME); if(userName != container.getUserName()) { cout << "----- Identity Container copy constructor failed" << endl; throw 0; } } context.clear(); { String userName("Yoda"); context.insert(IdentityContainer(userName)); // // This test exercises the IdentityContainer assignment operator // IdentityContainer container = IdentityContainer(" "); container = context.get(IdentityContainer::NAME); if(userName != container.getUserName()) { cout << "----- Identity Container assignment operator failed" << endl; throw 0; } } } // // SubscriptionInstanceContainer // void Test2(void) { if(verbose) { cout << "Test2()" << endl; } OperationContext context; CIMInstance subscriptionInstance = _createSubscriptionInstance1(); { context.insert(SubscriptionInstanceContainer(subscriptionInstance)); SubscriptionInstanceContainer container = context.get(SubscriptionInstanceContainer::NAME); if(!subscriptionInstance.identical(container.getInstance())) { cout << "----- Subscription Instance Container failed" << endl; throw 0; } } context.clear(); { context.insert(SubscriptionInstanceContainer(subscriptionInstance)); // // This test exercises the SubscriptionInstanceContainer copy // constructor // SubscriptionInstanceContainer container = context.get(SubscriptionInstanceContainer::NAME); if(!subscriptionInstance.identical(container.getInstance())) { cout << "----- Subscription Instance Container copy constructor failed" << endl; throw 0; } } context.clear(); { context.insert(SubscriptionInstanceContainer(subscriptionInstance)); // // This test exercises the SubscriptionInstanceContainer assignment // operator // SubscriptionInstanceContainer container = SubscriptionInstanceContainer(CIMInstance()); container = context.get(SubscriptionInstanceContainer::NAME); if(!subscriptionInstance.identical(container.getInstance())) { cout << "----- Subscription Instance Container assignment operator failed" << endl; throw 0; } } } // // SubscriptionFilterConditionContainer // void Test3(void) { if(verbose) { cout << "Test3()" << endl; } OperationContext context; { String filterCondition("AlertType = 5"); String queryLanguage("WQL1"); context.insert(SubscriptionFilterConditionContainer(filterCondition, queryLanguage)); SubscriptionFilterConditionContainer container = context.get(SubscriptionFilterConditionContainer::NAME); if((filterCondition != container.getFilterCondition()) || (queryLanguage != container.getQueryLanguage())) { cout << "----- Subscription Filter Condition Container failed" << endl; throw 0; } } context.clear(); { String filterCondition("AlertType = 5"); String queryLanguage("WQL1"); context.insert( SubscriptionFilterConditionContainer(filterCondition, queryLanguage)); // // This test exercises the SubscriptionFilterConditionContainer copy // constructor // SubscriptionFilterConditionContainer container = context.get(SubscriptionFilterConditionContainer::NAME); if((filterCondition != container.getFilterCondition()) || (queryLanguage != container.getQueryLanguage())) { cout << "----- SubscriptionFilterCondition Container copy constructor failed" << endl; throw 0; } } context.clear(); { String filterCondition("AlertType = 5"); String queryLanguage("WQL1"); context.insert( SubscriptionFilterConditionContainer(filterCondition, queryLanguage)); // // This test exercises the SubscriptionFilterConditionContainer // assignment operator // SubscriptionFilterConditionContainer container = SubscriptionFilterConditionContainer(" ", " "); container = context.get(SubscriptionFilterConditionContainer::NAME); if((filterCondition != container.getFilterCondition()) || (queryLanguage != container.getQueryLanguage())) { cout << "----- SubscriptionFilterCondition Container assignment operator failed" << endl; throw 0; } } } // // SubscriptionFilterQueryContainer // void Test4(void) { if(verbose) { cout << "Test4()" << endl; } OperationContext context; { String filterQuery("SELECT * FROM CIM_AlertIndication WHERE AlertType = 5"); String queryLanguage("WQL1"); CIMNamespaceName sourceNamespace("root/sampleprovider"); context.insert( SubscriptionFilterQueryContainer(filterQuery, queryLanguage, sourceNamespace)); SubscriptionFilterQueryContainer container = context.get(SubscriptionFilterQueryContainer::NAME); if((filterQuery != container.getFilterQuery()) || (queryLanguage != container.getQueryLanguage()) || (!(sourceNamespace == container.getSourceNameSpace()))) { cout << "----- Subscription Filter Query Container failed" << endl; throw 0; } } context.clear(); { String filterQuery("SELECT * FROM CIM_AlertIndication WHERE AlertType = 5"); String queryLanguage("WQL1"); CIMNamespaceName sourceNamespace("root/sampleprovider"); context.insert( SubscriptionFilterQueryContainer(filterQuery, queryLanguage, sourceNamespace)); // // This test exercises the SubscriptionFilterQueryContainer copy // constructor // SubscriptionFilterQueryContainer container = (SubscriptionFilterQueryContainer)context.get (SubscriptionFilterQueryContainer::NAME); if((filterQuery != container.getFilterQuery()) || (queryLanguage != container.getQueryLanguage()) || (!(sourceNamespace == container.getSourceNameSpace()))) { cout << "----- SubscriptionFilterQuery Container copy constructor failed" << endl; throw 0; } } context.clear(); { String filterQuery("SELECT * FROM CIM_AlertIndication WHERE AlertType = 5"); String queryLanguage("WQL1"); CIMNamespaceName sourceNamespace("root/sampleprovider"); CIMNamespaceName junkNamespace("root/junk"); context.insert( SubscriptionFilterQueryContainer(filterQuery, queryLanguage, sourceNamespace)); // // This test exercises the SubscriptionFilterQueryContainer // assignment operator // SubscriptionFilterQueryContainer container = SubscriptionFilterQueryContainer(" ", " ", junkNamespace); container = context.get(SubscriptionFilterQueryContainer::NAME); if((filterQuery != container.getFilterQuery()) || (queryLanguage != container.getQueryLanguage()) || (!(sourceNamespace == container.getSourceNameSpace()))) { cout << "----- SubscriptionFilterQuery Container assignment operator failed" << endl; throw 0; } } } // // SubscriptionInstanceNamesContainer // void Test5(void) { if(verbose) { cout << "Test5()" << endl; } OperationContext context; CIMInstance subscriptionInstance1 = _createSubscriptionInstance1(); CIMInstance subscriptionInstance2 = _createSubscriptionInstance2(); Array<CIMObjectPath> subscriptionInstanceNames; subscriptionInstanceNames.append(subscriptionInstance1.getPath()); subscriptionInstanceNames.append(subscriptionInstance2.getPath()); { context.insert( SubscriptionInstanceNamesContainer(subscriptionInstanceNames)); SubscriptionInstanceNamesContainer container = context.get(SubscriptionInstanceNamesContainer::NAME); Array<CIMObjectPath> returnedInstanceNames = container.getInstanceNames(); for(Uint8 i = 0, n = subscriptionInstanceNames.size(); i < n; i++) { if(!subscriptionInstanceNames[i].identical(returnedInstanceNames[i])) { cout << "----- Subscription Instance Names Container failed" << endl; throw 0; } } } context.clear(); { context.insert( SubscriptionInstanceNamesContainer(subscriptionInstanceNames)); // // This test exercises the SubscriptionInstanceNamesContainer copy // constructor // SubscriptionInstanceNamesContainer container = context.get(SubscriptionInstanceNamesContainer::NAME); Array<CIMObjectPath> returnedInstanceNames = container.getInstanceNames(); for(Uint8 i = 0, n = subscriptionInstanceNames.size(); i < n; i++) { if(!subscriptionInstanceNames[i].identical(returnedInstanceNames[i])) { cout << "----- Subscription Instance Names Container copy constructor failed" << endl; throw 0; } } } context.clear(); { context.insert( SubscriptionInstanceNamesContainer(subscriptionInstanceNames)); // // This test exercises the SubscriptionInstanceNamesContainer // assignment operator // Array<CIMObjectPath> returnedInstanceNames; SubscriptionInstanceNamesContainer container = SubscriptionInstanceNamesContainer(returnedInstanceNames); container = context.get(SubscriptionInstanceNamesContainer::NAME); returnedInstanceNames = container.getInstanceNames(); for(Uint8 i = 0, n = subscriptionInstanceNames.size(); i < n; i++) { if(!subscriptionInstanceNames[i].identical(returnedInstanceNames[i])) { cout << "----- Subscription Instance Names Container assignment operator failed" << endl; throw 0; } } } } void Test6(void) { if(verbose) { cout << "Test6()" << endl; } OperationContext context; String languageId("en-US"); context.insert(LocaleContainer(languageId)); LocaleContainer container = context.get(LocaleContainer::NAME); if(languageId != container.getLanguageId()) { cout << "----- Locale Container failed" << endl; throw 0; } } void Test7(void) { if(verbose) { cout << "Test7()" << endl; } OperationContext context; CIMInstance module("PG_ProviderModule"); CIMInstance provider("PG_Provider"); Boolean isRemoteNameSpace = true; String remoteInfo("remote_info"); context.insert(ProviderIdContainer(module, provider, isRemoteNameSpace, remoteInfo)); ProviderIdContainer container = context.get(ProviderIdContainer::NAME); if(!module.identical(container.getModule()) || !provider.identical(container.getProvider()) || (isRemoteNameSpace != container.isRemoteNameSpace()) || (remoteInfo != container.getRemoteInfo())) { cout << "----- Provider Id Container failed" << endl; throw 0; } } void Test8(void) { if(verbose) { cout << "Test8()" << endl; } OperationContext context; try { OperationContext scopeContext; scopeContext = context; scopeContext.remove(IdentityContainer::NAME); scopeContext.remove(SubscriptionInstanceContainer::NAME); scopeContext.remove(SubscriptionFilterConditionContainer::NAME); scopeContext.remove(SubscriptionFilterQueryContainer::NAME); scopeContext.remove(LocaleContainer::NAME); scopeContext.remove(ProviderIdContainer::NAME); } catch(...) { } } // // SnmpTrapOidContainer // void Test9(void) { if(verbose) { cout << "Test9()" << endl; } OperationContext context; { String snmpTrapOid ("1.3.6.1.4.1.992.2.3.9210.8400"); context.insert(SnmpTrapOidContainer(snmpTrapOid)); SnmpTrapOidContainer container = context.get(SnmpTrapOidContainer::NAME); if(snmpTrapOid != container.getSnmpTrapOid()) { cout << "----- Snmp Trap Oid Container failed" << endl; throw 0; } } context.clear(); { String snmpTrapOid ("1.3.6.1.4.1.992.2.3.9210.8400"); context.insert(SnmpTrapOidContainer(snmpTrapOid)); // // This test exercises the SnmpTrapOidContainer copy // constructor // SnmpTrapOidContainer container = context.get(SnmpTrapOidContainer::NAME); if(snmpTrapOid != container.getSnmpTrapOid()) { cout << "----- SnmpTrapOid Container copy constructor failed" << endl; throw 0; } } context.clear(); { String snmpTrapOid ("1.3.6.1.4.1.992.2.3.9210.8400"); context.insert(SnmpTrapOidContainer(snmpTrapOid)); // // This test exercises the SnmpTrapOidContainer // assignment operator // SnmpTrapOidContainer container = SnmpTrapOidContainer(" "); container = context.get(SnmpTrapOidContainer::NAME); if(snmpTrapOid != container.getSnmpTrapOid()) { cout << "----- SnmpTrapOid Container assignment operator failed" << endl; throw 0; } } } void Test10(void) { if(verbose) { cout << "Test10()" << endl; } OperationContext context; CIMClass cimClass("CachedClass"); context.insert(CachedClassDefinitionContainer(cimClass)); CachedClassDefinitionContainer container = context.get(CachedClassDefinitionContainer::NAME); if(cimClass.getClassName().getString() != container.getClass().getClassName().getString()) { cout << "----- CachedClassDefinitionContainer failed" << endl; throw 0; } } int main(int argc, char** argv) { verbose = getenv("PEGASUS_TEST_VERBOSE"); try { Test1(); Test2(); Test3(); Test4(); Test5(); Test6(); Test7(); Test8(); Test9(); Test10(); cout << argv[0] << " +++++ passed all tests" << endl; } catch(CIMException & e) { cout << argv[0] << " ----- failed with CIMException(" << e.getCode() << "):" << e.getMessage() << endl; } catch(Exception & e) { cout << argv[0] << " ----- failed with Exception:" << e.getMessage() << endl; } catch(...) { cout << argv[0] << " ----- failed with unknown exception" << endl; } return(0); }
32.078767
129
0.673891
979b9cab028edacd7d197e7a162952c35400c372
2,100
hpp
C++
android_app/app/src/main/cpp/include/zdl/DlSystem/ITensorItrImpl.hpp
csarron/MobileAccelerator
5e1b40cb2332073da6cd8a52bbba2712ae30f7bd
[ "MIT" ]
2
2021-07-25T01:10:03.000Z
2021-10-29T22:49:09.000Z
android_app/app/src/main/cpp/include/zdl/DlSystem/ITensorItrImpl.hpp
csarron/MobileAccelerator
5e1b40cb2332073da6cd8a52bbba2712ae30f7bd
[ "MIT" ]
null
null
null
android_app/app/src/main/cpp/include/zdl/DlSystem/ITensorItrImpl.hpp
csarron/MobileAccelerator
5e1b40cb2332073da6cd8a52bbba2712ae30f7bd
[ "MIT" ]
null
null
null
//============================================================================= // @@-COPYRIGHT-START-@@ // // Copyright 2015 Qualcomm Technologies, Inc. All rights reserved. // Confidential & Proprietary - Qualcomm Technologies, Inc. ("QTI") // // The party receiving this software directly from QTI (the "Recipient") // may use this software as reasonably necessary solely for the purposes // set forth in the agreement between the Recipient and QTI (the // "Agreement"). The software may be used in source code form solely by // the Recipient's employees (if any) authorized by the Agreement. Unless // expressly authorized in the Agreement, the Recipient may not sublicense, // assign, transfer or otherwise provide the source code to any third // party. Qualcomm Technologies, Inc. retains all ownership rights in and // to the software // // This notice supersedes any other QTI notices contained within the software // except copyright notices indicating different years of publication for // different portions of the software. This notice does not supersede the // application of any third party copyright notice to that third party's // code. // // @@-COPYRIGHT-END-@@ //============================================================================= #ifndef _ITENSOR_ITR_IMPL_HPP_ #define _ITENSOR_ITR_IMPL_HPP_ #include "ZdlExportDefine.hpp" #include <memory> #include <iterator> #include <vector> namespace DlSystem { class ITensorItrImpl; } class ZDL_EXPORT DlSystem::ITensorItrImpl { public: ITensorItrImpl() {} virtual ~ITensorItrImpl() {} virtual float getValue() const = 0; virtual float& getReference() = 0; virtual float& getReferenceAt(size_t idx) = 0; virtual float* dataPointer() const = 0; virtual void increment(int incVal = 1) = 0; virtual void decrement(int decVal = 1) = 0; virtual size_t getPosition() = 0; virtual std::unique_ptr<DlSystem::ITensorItrImpl> clone() = 0; private: ITensorItrImpl& operator=(const ITensorItrImpl& other) = delete; ITensorItrImpl(const ITensorItrImpl& other) = delete; }; #endif
34.42623
79
0.681905
979c6b30191b3c796513d66d784490eb5eafde41
15,492
cpp
C++
src/jc_handlers/jc_class.cpp
gavz/choupi
fb49537e9646d4797f63ca2191f3b0ddb4c6760a
[ "MIT" ]
2
2021-05-22T03:24:31.000Z
2022-01-20T14:25:25.000Z
src/jc_handlers/jc_class.cpp
gavz/choupi
fb49537e9646d4797f63ca2191f3b0ddb4c6760a
[ "MIT" ]
null
null
null
src/jc_handlers/jc_class.cpp
gavz/choupi
fb49537e9646d4797f63ca2191f3b0ddb4c6760a
[ "MIT" ]
3
2021-05-06T14:24:58.000Z
2022-01-06T07:52:27.000Z
/* ** The MIT License (MIT) ** ** Copyright (c) 2020, National Cybersecurity Agency of France (ANSSI) ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** of this software and associated documentation files (the "Software"), to deal ** in the Software without restriction, including without limitation the rights ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** copies of the Software, and to permit persons to whom the Software is ** furnished to do so, subject to the following conditions: ** ** The above copyright notice and this permission notice shall be included in ** all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ** THE SOFTWARE. ** ** Author: ** - Guillaume Bouffard <guillaume.bouffard@ssi.gouv.fr> */ #include "jc_class.hpp" #include "jc_cp.hpp" namespace jcvm { /* * The checkcast function check if a type in is compatible with the * type_out. The rule is the following one: * * - If S is a class type, then: * + If T is a class type, then S must be the same class as T, or * S must be a subclass of T; * + If T is an interface type, then S must implement interface T. * - If S is an interface type[13], then: * + If T is a class type, then T must be Object (§2.2.1.4 * Unsupported Classes); * + If T is an interface type, T must be the same interface as S * or a superinterface of S. * - If S is an array type, namely the type SC[], that is, an array of * components of type SC, then: * + If T is a class type, then T must be Object. * + If T is an array type, namely the type TC[], an array of * components of type TC, then one of the following must be true: * * TC and SC are the same primitive type (§3.1 Data Types and * Values). * * TC and SC are reference types[14] (§3.1 Data Types and Values) * with type SC assignable to TC, by these rules. * + If T is an interface type, T must be one of the interfaces * implemented by arrays. * * 13: When both S and T are arrays of reference types, this algorithm is * applied recursively using the types of the arrays, namely SC and TC. In * the recursive call, S, which was SC in the original call, may be an * interface type. This rule can only be reached in this manner. * Similarly, in the recursive call, T, which was TC in the original call, * may be an interface type. * * @param[jtype_in] the input type * @param[jtype_out] the out type * * @return TRUE if the types are compatible, else FALSE */ jbool_t Class_Handler::docheckcast(const std::pair<Package, const uint8_t *> jtype_in, const std::pair<Package, const uint8_t *> jtype_out) #if !defined(JCVM_ARRAY_SIZE_CHECK) && !defined(JCVM_DYNAMIC_CHECKS_CAP) noexcept #endif { // case 1: type_in is a class type if (IS_CLASS(jtype_in.second)) { auto jclass_in = std::make_pair( jtype_in.first, reinterpret_cast<const jc_cap_class_info *>(jtype_in.second)); // case 1.1: type_out is a class type if (IS_CLASS(jtype_out.second)) { auto jclass_out = reinterpret_cast<const jc_cap_class_info *>(jtype_out.second); // then S must be the same class as T, or S must be a subclass of T if (jclass_out->isObjectClass()) { return TRUE; } while (!jclass_in.second->isObjectClass()) { if (jclass_in.second == jclass_out) { return TRUE; } jclass_in = ConstantPool_Handler(jclass_in.first) .classref2class(jclass_in.second->super_class_ref); } return FALSE; } // case 1.2: type_out is an interface type else { if (jclass_in.second->interface_count == 0) { return FALSE; } for (uint8_t i = 0; i < jclass_in.second->interface_count; ++i) { auto implemented_interface = jclass_in.second->interfaces(i); ConstantPool_Handler cp(jclass_in.first); if (Class_Handler::checkInterfaceCast( cp.resolveClassref(implemented_interface.interface), jtype_out) == TRUE) { return TRUE; } } } } // case 2: type_in is an interface type else { // jtype_out must be Object if (IS_CLASS(jtype_out.second)) { const auto jclass_out = std::make_pair( jtype_out.first, reinterpret_cast<const jc_cap_class_info *>(jtype_out.second)); return (jclass_out.second->isObjectClass() ? TRUE : FALSE); } return Class_Handler::checkInterfaceCast(jtype_in, jtype_out); } return FALSE; } /* * Check if two interfaces (interface_in and interface_out) have a hierarchy * link together. This function returns TRUE when interface_in is the * daughter of interface_out. * * @param[interface_in] * @param[interface_out] * * @return returns TRUE when interface_in is the daughter of interface_out */ jbool_t Class_Handler::checkInterfaceCast( const std::pair<Package, const uint8_t *> interface_in, const std::pair<Package, const uint8_t *> interface_out) #if !defined(JCVM_ARRAY_SIZE_CHECK) && !defined(JCVM_DYNAMIC_CHECKS_CAP) noexcept #endif { #ifdef JCVM_DYNAMIC_CHECKS_CAP if (!IS_INTERFACE(interface_in.second) || !IS_INTERFACE(interface_out.second)) { throw Exceptions::SecurityException; } #endif /* JCVM_DYNAMIC_CHECKS_CAP */ auto superinterfaces = reinterpret_cast<const jc_cap_interface_info *>(interface_in.second) ->super_interfaces(); for (uint8_t j = 0; j < superinterfaces.size(); ++j) { const jc_cap_class_ref super_interface_in = superinterfaces.at(j); auto super_interface_ptr = ConstantPool_Handler(interface_in.first) .resolveClassref(super_interface_in); #ifdef JCVM_DYNAMIC_CHECKS_CAP if (!IS_INTERFACE(super_interface_ptr.second)) { throw Exceptions::SecurityException; } #endif /* JCVM_DYNAMIC_CHECKS_CAP */ if ((super_interface_ptr.first == interface_out.first) && (super_interface_ptr.second == interface_out.second)) { return TRUE; } } return FALSE; } /* * Get the reference to the Object class from a classref. * * @param[classref] a classref to find this ultimate class. * @return the reference to the Object class. */ std::pair<Package, const jc_cap_class_info *> Class_Handler::getObjectClassFromAnObjectRef(const jc_cap_class_ref classref) #if !defined(JCVM_ARRAY_SIZE_CHECK) && !defined(JCVM_DYNAMIC_CHECKS_CAP) noexcept #endif { ConstantPool_Handler cp_handler(this->package); auto token = cp_handler.classref2class(classref); while (!(token.second->isObjectClass())) { cp_handler.setPackage(token.first); token = cp_handler.classref2class(token.second->super_class_ref); } return token; } /** * Get a class public method offset from a class' public method token. * * @param[public_method_token] public method token to resolve. * * @return the public virtual method offset in the Method component. */ std::pair<Package, const uint16_t> Class_Handler::getPublicMethodOffset( const jc_cap_virtual_method_ref_info virtual_method_ref_info) #if !defined(JCVM_ARRAY_SIZE_CHECK) && !defined(JCVM_DYNAMIC_CHECKS_CAP) noexcept #endif { #ifdef JCVM_DYNAMIC_CHECKS_CAP if (virtual_method_ref_info.isPublicMethod()) { throw Exceptions::SecurityException; } #endif /* JCVM_DYNAMIC_CHECKS_CAP */ ConstantPool_Handler cp_handler(this->package); uint8_t method_offset = virtual_method_ref_info.token; auto token = cp_handler.classref2class(virtual_method_ref_info.class_ref); // Where is the method offset located? while (!(token.second->isObjectClass()) && (method_offset < token.second->public_method_table_base)) { // Jump to superclass cp_handler.setPackage(token.first); token = cp_handler.classref2class(token.second->super_class_ref); } #ifdef JCVM_DYNAMIC_CHECKS_CAP if (token.second->isObjectClass() && (method_offset < token.second->public_method_table_base)) { throw Exceptions::SecurityException; } #endif /* JCVM_DYNAMIC_CHECKS_CAP */ return this->doGetPublicMethodOffset(token.first, token.second, method_offset); } /** * Do get a class public method offset from a class' public method token. * * @param[package] where is located the method to resolve * @param[claz] a pointer to the class where is located the method to resolve * @param[public_method_token] public method token to resolve. * * @return the public virtual method offset in the Method component. */ std::pair<Package, const uint16_t> Class_Handler::doGetPublicMethodOffset(Package &package, const jc_cap_class_info *claz, uint8_t public_method_offset) #if !defined(JCVM_ARRAY_SIZE_CHECK) && !defined(JCVM_DYNAMIC_CHECKS_CAP) noexcept #endif { ConstantPool_Handler cp_handler(this->package); uint16_t method_offset = 0xFFFF; const JCVMArray<const uint16_t> public_virtual_method_table = claz->public_virtual_method_table(); auto token = std::make_pair(package, claz); do { uint16_t offset = public_method_offset - claz->public_method_table_base; method_offset = public_virtual_method_table.at(offset); if (method_offset == (uint16_t)0xFFFF) { #ifdef JCVM_DYNAMIC_CHECKS_CAP if (claz->isObjectClass()) { // Behaviour not expected throw Exceptions::SecurityException; } #endif /* JCVM_DYNAMIC_CHECKS_CAP */ // Jump to superclass cp_handler.setPackage(token.first); token = cp_handler.classref2class(token.second->super_class_ref); } } while (method_offset == (uint16_t)0xFFFF); return std::make_pair(token.first, method_offset); } /** * Get a class package method offset from a class' package method token. * * @param[package_method_token] package method token to resolve. * * @return the package virtual method offset in the Method component. The Cap * field is updated to executed the method to call. */ std::pair<Package, const uint16_t> Class_Handler::getPackageMethodOffset( const jc_cap_virtual_method_ref_info virtual_method_ref_info) #if !defined(JCVM_ARRAY_SIZE_CHECK) && !defined(JCVM_DYNAMIC_CHECKS_CAP) noexcept #endif { #ifdef JCVM_DYNAMIC_CHECKS_CAP if (!virtual_method_ref_info.isPublicMethod()) { throw Exceptions::SecurityException; } #endif /* JCVM_DYNAMIC_CHECKS_CAP */ ConstantPool_Handler cp_handler(this->package); uint8_t method_offset_class = virtual_method_ref_info.token; auto token = cp_handler.classref2class(virtual_method_ref_info.class_ref); // Where is the method offset located? while (!(token.second->isObjectClass()) && (method_offset_class < token.second->package_method_table_base)) { // Jump to superclass cp_handler.setPackage(token.first); token = cp_handler.classref2class(token.second->super_class_ref); } uint16_t method_offset = 0xFFFF; const jc_cap_class_info *claz = token.second; const JCVMArray<const uint16_t> package_virtual_method_table = claz->package_virtual_method_table(); do { uint16_t offset = method_offset_class - claz->package_method_table_base; method_offset = package_virtual_method_table.at(offset); if (method_offset == (uint16_t)0xFFFF) { #ifdef JCVM_DYNAMIC_CHECKS_CAP if (claz->isObjectClass()) { // Behavior not expected throw Exceptions::SecurityException; } #endif /* JCVM_DYNAMIC_CHECKS_CAP */ // Jump to superclass cp_handler.setPackage(token.first); token = cp_handler.classref2class(token.second->super_class_ref); } } while (method_offset == (uint16_t)0xFFFF); return std::make_pair(token.first, method_offset); } /** * Get a class public or package method offset from a class' method token. * * @param[method_token] method token to resolve. * * @return the public or package virtual method offset in the Method component. */ std::pair<Package, const uint16_t> Class_Handler::getMethodOffset( const jc_cap_virtual_method_ref_info virtual_method_ref_info) #if !defined(JCVM_ARRAY_SIZE_CHECK) && !defined(JCVM_DYNAMIC_CHECKS_CAP) noexcept #endif { if (virtual_method_ref_info.isPublicMethod()) { return this->getPublicMethodOffset(virtual_method_ref_info); } else { // it's a package method return this->getPackageMethodOffset(virtual_method_ref_info); } } /* * Get a class' implemented interface method offset from a class' package method * token. * * @param[class] class where the method will be resolved. * @param[interface] implemented interface. * @param[implemented_interface_method_number] implemented interface method * number. * @return the implemented interface method offset in the method component. */ std::pair<Package, const uint16_t> Class_Handler::getImplementedInterfaceMethodOffset( const jc_cap_class_ref class_ref, const jc_cap_class_ref interface, const uint8_t implemented_interface_method_number, const bool isArray) #if !defined(JCVM_ARRAY_SIZE_CHECK) && !defined(JCVM_DYNAMIC_CHECKS_CAP) noexcept #endif { ConstantPool_Handler cp_handler(this->package); auto claz = (isArray ? this->getObjectClassFromAnObjectRef(class_ref) : cp_handler.classref2class(class_ref)); for (uint16_t index = 0; index < claz.second->interface_count; ++index) { const auto &interfaces = claz.second->interfaces(index); if (HTONS(interfaces.interface.internal_classref) == interface.internal_classref) { uint8_t public_method_offset = interfaces.indexes().at(implemented_interface_method_number); if (isArray) { return this->doGetPublicMethodOffset(claz.first, claz.second, public_method_offset); } else { const jc_cap_virtual_method_ref_info method_ref = { .class_ref = class_ref, .token = public_method_offset, }; return this->getPublicMethodOffset(method_ref); } } } throw Exceptions::SecurityException; } /* * Get the instance field size for an instantiated class. * * @param[claz_index] class index used to compute the instance field size */ const uint16_t Class_Handler::getInstanceFieldsSize(const jclass_index_t claz_index) const #if !defined(JCVM_ARRAY_SIZE_CHECK) && !defined(JCVM_DYNAMIC_CHECKS_CAP) noexcept #endif { auto package = this->package; auto claz = ConstantPool_Handler(package).getClassFromClassIndex(claz_index); uint16_t instance_size = 0; do { ConstantPool_Handler cp_handler(package); instance_size += (claz->declared_instance_size & 0x00FF); auto pair = cp_handler.classref2class(claz->super_class_ref); package = pair.first; claz = pair.second; } while (!(claz->isObjectClass())); return instance_size; } } // namespace jcvm
33.173448
80
0.706106
97a2bce42566f20ad356ce2a39e84587bb5959a0
4,287
cc
C++
src/webpage.cc
mistydew/RSSearch
52e597aeb495fe35f2f6069741ef19c9d0bfe2bb
[ "MIT" ]
2
2019-03-13T14:47:16.000Z
2019-07-22T09:17:43.000Z
src/webpage.cc
mistydew/RSSearch
52e597aeb495fe35f2f6069741ef19c9d0bfe2bb
[ "MIT" ]
null
null
null
src/webpage.cc
mistydew/RSSearch
52e597aeb495fe35f2f6069741ef19c9d0bfe2bb
[ "MIT" ]
1
2019-07-22T09:17:44.000Z
2019-07-22T09:17:44.000Z
/// /// @file webpage.cc /// @author mistydew(mistydew@qq.com) /// @date 2017-12-02 15:36:06 /// #include "webpage.h" #include "configuration.h" #include "wordsegmentation.h" #include <queue> #include <sstream> namespace md { WebPage::WebPage(const std::string & doc) { std::cout << "WebPage(const std::string &)" << std::endl; _topWords.reserve(TOPK); processDoc(doc); } WebPage::~WebPage() { std::cout << "~WebPage()" << std::endl; } std::string WebPage::getDocTitle() { return _docTitle; } std::string WebPage::getDocUrl() { return _docUrl; } std::string WebPage::summary(const std::vector<std::string> & queryWords) { std::vector<std::string> summaryVec; std::istringstream iss(_docContent); std::string line; while (iss >> line) { for (auto & word : queryWords) { if (line.find(word) != std::string::npos) { summaryVec.push_back(line); break; } } if (summaryVec.size() > 6) break; } std::string summary; for (auto & line : summaryVec) { summary.append(line).append("\n"); } return summary; } void WebPage::processDoc(const std::string & doc) { std::cout << "process document..." << std::endl; std::string begId = "<docid>"; std::string endId = "</docid>"; std::string begUrl = "<url>"; std::string endUrl = "</url>"; std::string begTitle = "<title>"; std::string endTitle = "</title>"; std::string begContent = "<content>"; std::string endContent = "</content>"; std::string::size_type bpos = doc.find(begId); std::string::size_type epos = doc.find(endId); std::string docId = doc.substr(bpos + begId.size(), epos - bpos - begId.size()); _docId = str2uint(docId); bpos = doc.find(begUrl); epos = doc.find(endUrl); _docUrl = doc.substr(bpos + begUrl.size(), epos - bpos - begUrl.size()); bpos = doc.find(begTitle); epos = doc.find(endTitle); _docTitle = doc.substr(bpos + begTitle.size(), epos - bpos - begTitle.size()); bpos = doc.find(begContent); epos = doc.find(endContent); _docContent = doc.substr(bpos + begContent.size(), epos - bpos - begContent.size()); #if 0 std::cout << _docId << std::endl; std::cout << _docUrl << std::endl; std::cout << _docTitle << std::endl; std::cout << _docContent << std::endl; #endif statistic(); calcTopK(); std::cout << "process completed" << std::endl; } void WebPage::statistic() { std::vector<std::string> words; WordSegmentation::getInstance()->cut(_docContent, words); std::size_t nBytes; for (auto & word : words) { if(0 == Configuration::getInstance()->getStopWord().count(word)) { nBytes = nBytesUTF8Code(word[0]); if (0 == nBytes) { word = processWords(word); if ("" == word) continue; } ++_wordsMap[word]; } } #if 0 for (auto & map : _wordsMap) { std::cout << map.first << " " << map.second << std::endl; } #endif } std::string WebPage::processWords(const std::string & word) { std::string temp; for (std::string::size_type idx = 0; idx != word.size(); ++idx) { if (isalpha(word[idx])) { if (isupper(word[idx])) temp += word[idx] + 32; else temp += word[idx]; } } return temp; } void WebPage::calcTopK() { std::priority_queue<std::pair<std::string, std::size_t>, std::vector<std::pair<std::string, std::size_t> >, WordFreqCompare> wordFreqQue(_wordsMap.begin(), _wordsMap.end()); while (!wordFreqQue.empty()) { _topWords.push_back(wordFreqQue.top().first); if (_topWords.size() >= TOPK) break; wordFreqQue.pop(); } #if 0 std::cout << "top words:" << std::endl; for (auto & top : _topWords) { std::cout << top << std::endl; } #endif } std::ostream & operator<<(std::ostream & os, const WebPage & rhs) { os << rhs._docId << std::endl << rhs._docTitle << std::endl << rhs._docUrl << std::endl << rhs._docContent; return os; } } // end of namespace md
24.637931
128
0.559132
97a453e833e798b0117112d4759e7c3e46460faf
606
cpp
C++
test/src/algorithm/suffix.cpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
9
2020-07-04T16:46:13.000Z
2022-01-09T21:59:31.000Z
test/src/algorithm/suffix.cpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
null
null
null
test/src/algorithm/suffix.cpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
1
2021-05-23T13:37:40.000Z
2021-05-23T13:37:40.000Z
#include "test.hpp" #include "test/numbers.hpp" #include "jln/mp/smp/algorithm/suffix.hpp" TEST_SUITE_BEGIN() TEST() { using namespace jln::mp; using namespace ut::ints; test_pack2<suffix, int>(); ut::same<list<>, emp::suffix<list<>, int>>(); ut::same<list<_0, int>, emp::suffix<seq_0, int>>(); test_context<suffix<int>, smp::suffix<int>>() .test<list<>>() .test<list<_0, int>, _0>() .test<list<_0, int, _1, int>, _0, _1>() .test<list<_0, int, _1, int, _2, int>, _0, _1, _2>() ; ut::not_invocable<smp::suffix<void, bad_function>, _1, _1, _1>(); } TEST_SUITE_END()
20.896552
67
0.612211
97a6299514ba9314a3382d69e56f002a18f6cccd
1,851
cpp
C++
examples/ex_1/data_service/CDefDataProvider.cpp
vgordievskiy/boost_optional_ext
b5eed34d64506f9bc7325d81b5626f7ee6d94eb6
[ "MIT" ]
7
2020-10-12T07:01:51.000Z
2020-10-19T07:08:28.000Z
examples/ex_1/data_service/CDefDataProvider.cpp
vgordievskiy/boost_optional_ext
b5eed34d64506f9bc7325d81b5626f7ee6d94eb6
[ "MIT" ]
2
2020-10-17T20:24:19.000Z
2020-10-21T21:11:42.000Z
examples/ex_1/data_service/CDefDataProvider.cpp
vgordievskiy/boost_optional_ext
b5eed34d64506f9bc7325d81b5626f7ee6d94eb6
[ "MIT" ]
null
null
null
#include "CDefDataProvider.h" #include <chrono> #include <boost/random/random_device.hpp> #include <boost/random/uniform_real_distribution.hpp> #include <boost/random/uniform_int_distribution.hpp> #include <boost/lexical_cast.hpp> namespace services { CDefDataProvider::CDefDataProvider() {} CDefDataProvider::~CDefDataProvider() { stop(); wait(); } IDataProvider::Connection CDefDataProvider::onNewData(const FNewDataHandler& handler) { return m_newDataReady.connect(handler); } void CDefDataProvider::setNewData(const Data& data) { if (!m_newDataReady.empty()) { m_newDataReady(data); } } void CDefDataProvider::start() { m_isStopped.store(false, std::memory_order_relaxed); m_worker = std::thread([this] { boost::random::random_device rng; boost::random::uniform_real_distribution<> dist(-100.0, 100.0); boost::random::uniform_int_distribution<> errDist(1, 100); while (!m_isStopped.load(std::memory_order_relaxed)) { using namespace std::chrono_literals; auto isError = errDist(rng) % 5 == 0; if (isError) { setNewData("an error"); } else { auto newValue = dist(rng); setNewData(boost::lexical_cast<std::string>(newValue)); } std::this_thread::sleep_for(1s); } }); } void CDefDataProvider::stop() { m_isStopped.store(true, std::memory_order_relaxed); } void CDefDataProvider::wait() { if (m_worker.joinable()) { m_worker.join(); } } } // end namepsace services
24.355263
89
0.560238
97aa1b3005b136dd27e3bffc6af997679b487c9f
4,727
cpp
C++
Assignment 3/AVL_TreeOperations.cpp
Raghav1806/Data-Structures-CSL-201-
2e4e3c67e3ff28ac6a9e1f06fe12a2864b17d177
[ "MIT" ]
null
null
null
Assignment 3/AVL_TreeOperations.cpp
Raghav1806/Data-Structures-CSL-201-
2e4e3c67e3ff28ac6a9e1f06fe12a2864b17d177
[ "MIT" ]
null
null
null
Assignment 3/AVL_TreeOperations.cpp
Raghav1806/Data-Structures-CSL-201-
2e4e3c67e3ff28ac6a9e1f06fe12a2864b17d177
[ "MIT" ]
null
null
null
// program for basic operations in AVL Tree #include <iostream> #include <cstdlib> using namespace std; struct Node{ int data; struct Node *left; struct Node *right; int height; }*root; struct Node *createNewNode(int x){ struct Node *newptr = new Node; newptr->data = x; newptr->left = NULL; newptr->right = NULL; newptr->height = 1; return newptr; } void inorder(struct Node *root){ if(root == NULL) return; else{ inorder(root->left); cout << root->data << " "; inorder(root->right); } cout << "\n"; } int max(int a, int b){ if(a >= b) return a; else return b; } int height(struct Node *root){ if(root == NULL) return 0; else return root->height; } int getBalance(struct Node *root){ if(root == NULL) return 0; else return height(root->left) - height(root->right); } struct Node *rightRotate(struct Node *y){ struct Node *x = y->left; struct Node *T2 = x->right; // perform rotation x->right = y; y->left = T2; // update heights y->height = max(height(y->left), height(y->right)) + 1; x->height = max(height(x->left), height(x->right)) + 1; // return new root return x; } struct Node *leftRotate(struct Node *x){ struct Node *y = x->right; struct Node *T2 = y->left; // perform rotation y->left = x; x->right = T2; // update heights x->height = max(height(x->left), height(x->right)) + 1; y->height = max(height(y->left), height(y->right)) + 1; // return new root return y; } struct Node *insertAVL(struct Node *root, int data){ int balance; // perform normal BST insertion if(root == NULL) return createNewNode(data); if(data <= root->data) root->left = insertAVL(root->left, data); else if(data > root->data) root->right = insertAVL(root->right, data); // update the height of ancestor node root->height = 1 + max(height(root->left),height(root->right)); // get the balance factor of this ancestor node balance = getBalance(root); // if this node is unbalanced, then 4 cases are possible // left left case if(balance > 1 && data < root->left->data) return leftRotate(root); // right right case if(balance > 1 && data > root->right->data) return rightRotate(root); // left right case if(balance > 1 && data > root->left->data){ root->left = leftRotate(root->left); return rightRotate(root); } // right left case if(balance < -1 && data < root->right->data){ root->right = rightRotate(root->right); return leftRotate(root); } // return the unchanged pointers return root; } struct Node *minValueNode(struct Node *root){ struct Node *curr = root; // loop down to find smallest node while(curr->left != NULL) curr = curr->left; return curr; } struct Node *deleteAVL(struct Node *root, int data){ int balance; // perform standard BST delete if(root == NULL) return root; // if the key is in left subtree if(data < root->data) root->left = deleteAVL(root->left, data); // if the key is in right subtree if(data > root->data) root->right = deleteAVL(root->right, data); // if this is the node to be deleted else{ // node with only one child or no child if(root->left == NULL){ struct Node *temp = root->right; free(root); return temp; } else if(root->right == NULL){ struct Node *temp = root->left; free(root); return temp; } // node with two children struct Node *temp = minValueNode(root->right); // copy the inorder successor's content to this node root->data = temp->data; // delete the inorder successor root->right = deleteAVL(root->right,temp->data); } // return root; // update the height of current node root->height = 1 + max(height(root->left), height(root->right)); // get the balanced factor from this node (bottomm up manner) balance = getBalance(root); // if this node is unbalanced, there are 4 possible cases // left left case if(balance > 1 && getBalance(root->left) >= 0) return rightRotate(root); // right right case if(balance < -1 && getBalance(root->right) <= 0) return leftRotate(root); // left right case if(balance > 1 && getBalance(root->left) < 0){ root->left = leftRotate(root->left); return rightRotate(root); } // right left case if(balance < -1 && getBalance(root->right) > 0){ root->right = rightRotate(root->right); return leftRotate(root); } return root; } int main(){ root = NULL; int size, i; cout << "Enter the size of array\n"; cin >> size; int A[size]; cout << "Enter the elements of array\n"; for(i = 0; i < size; i++){ cin >> A[i]; if(A[i] > 0) root = insertAVL(root, A[i]); else if(A[i] < 0){ A[i] = -1*A[i]; root = deleteAVL(root, A[i]); } } cout << "The inorder traversal of tree is\n"; inorder(root); return 0; }
19.861345
65
0.642268
97ab322573a6865d8a85ff34c4ad426f4104757c
1,381
cpp
C++
IOCP4Http/IOCP/PerSocketContext.cpp
Joyce-Qu/IOCPServer-Client-
b1c1a76e6bffe3b67340614ba8e36e197198302e
[ "MIT" ]
42
2019-11-13T06:39:31.000Z
2021-12-28T18:55:27.000Z
IOCP4Http/IOCP/PerSocketContext.cpp
124327288/IOCPServer
b1c1a76e6bffe3b67340614ba8e36e197198302e
[ "MIT" ]
null
null
null
IOCP4Http/IOCP/PerSocketContext.cpp
124327288/IOCPServer
b1c1a76e6bffe3b67340614ba8e36e197198302e
[ "MIT" ]
31
2019-11-14T09:58:15.000Z
2022-03-25T08:30:41.000Z
#include <ws2tcpip.h> #include <assert.h> #include "Network.h" #include "PerIoContext.h" #include "PerSocketContext.h" #include <iostream> using namespace std; ListenContext::ListenContext(short port, const std::string& ip) { SecureZeroMemory(&m_addr, sizeof(SOCKADDR_IN)); m_addr.sin_family = AF_INET; inet_pton(AF_INET, ip.c_str(), &m_addr.sin_addr); //m_addr.sin_addr.s_addr = inet_addr(ip.c_str()); m_addr.sin_port = htons(port); m_socket = Network::socket(); assert(SOCKET_ERROR != m_socket); } ClientContext::ClientContext(const SOCKET& socket) : m_socket(socket), m_recvIoCtx(new RecvIoContext()) , m_sendIoCtx(new IoContext(PostType::SEND)) , m_nPendingIoCnt(0) { SecureZeroMemory(&m_addr, sizeof(SOCKADDR_IN)); InitializeCriticalSection(&m_csLock); } ClientContext::~ClientContext() { delete m_recvIoCtx; delete m_sendIoCtx; m_recvIoCtx = nullptr; m_sendIoCtx = nullptr; LeaveCriticalSection(&m_csLock); } void ClientContext::reset() { assert(0 == m_nPendingIoCnt); assert(m_outBufQueue.empty()); SecureZeroMemory(&m_addr, sizeof(SOCKADDR_IN)); m_nLastHeartbeatTime = GetTickCount(); } void ClientContext::appendToBuffer(PBYTE pInBuf, size_t len) { m_inBuf.write((PBYTE)pInBuf, len); } void ClientContext::appendToBuffer(const std::string& inBuf) { m_inBuf.write(inBuf); }
24.660714
63
0.717596
97ad3e092974dd1d58c4f30432cd174a86fdc87e
2,333
cpp
C++
Engine/Renderer/Gfx/src/GfxCamera.cpp
LiangYue1981816/AresEngine
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
[ "BSD-2-Clause" ]
3
2018-12-08T16:32:05.000Z
2020-06-02T11:07:15.000Z
Engine/Renderer/Gfx/src/GfxCamera.cpp
LiangYue1981816/AresEngine
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
[ "BSD-2-Clause" ]
null
null
null
Engine/Renderer/Gfx/src/GfxCamera.cpp
LiangYue1981816/AresEngine
c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67
[ "BSD-2-Clause" ]
1
2019-09-12T00:26:05.000Z
2019-09-12T00:26:05.000Z
#include "GfxHeader.h" CGfxCamera::CGfxCamera(void) { } CGfxCamera::~CGfxCamera(void) { } void CGfxCamera::SetScissor(float x, float y, float width, float height) { m_camera.setScissor(x, y, width, height); } void CGfxCamera::SetViewport(float x, float y, float width, float height) { m_camera.setViewport(x, y, width, height); } void CGfxCamera::SetPerspective(float fovy, float aspect, float zNear, float zFar) { m_camera.setPerspective(fovy, aspect, zNear, zFar); } void CGfxCamera::SetOrtho(float left, float right, float bottom, float top, float zNear, float zFar) { m_camera.setOrtho(left, right, bottom, top, zNear, zFar); } void CGfxCamera::SetLookat(float eyex, float eyey, float eyez, float centerx, float centery, float centerz, float upx, float upy, float upz) { m_camera.setLookat(glm::vec3(eyex, eyey, eyez), glm::vec3(centerx, centery, centerz), glm::vec3(upx, upy, upz)); } const glm::camera& CGfxCamera::GetCamera(void) const { return m_camera; } const glm::vec4& CGfxCamera::GetScissor(void) const { return m_camera.scissor; } const glm::vec4& CGfxCamera::GetViewport(void) const { return m_camera.viewport; } const glm::vec3& CGfxCamera::GetPosition(void) const { return m_camera.position; } const glm::vec3& CGfxCamera::GetForwardDirection(void) const { return m_camera.forward; } const glm::vec3& CGfxCamera::GetUpDirection(void) const { return m_camera.up; } const glm::mat4& CGfxCamera::GetProjectionMatrix(void) const { return m_camera.projectionMatrix; } const glm::mat4& CGfxCamera::GetViewMatrix(void) const { return m_camera.viewMatrix; } const glm::mat4& CGfxCamera::GetViewInverseMatrix(void) const { return m_camera.viewInverseMatrix; } const glm::mat4& CGfxCamera::GetViewInverseTransposeMatrix(void) const { return m_camera.viewInverseTransposeMatrix; } glm::vec3 CGfxCamera::WorldToScreen(const glm::vec3& world) const { return m_camera.worldToScreen(world); } glm::vec3 CGfxCamera::ScreenToWorld(const glm::vec3& screen) const { return m_camera.screenToWorld(screen); } bool CGfxCamera::IsVisible(const glm::vec3& vertex) const { return m_camera.visible(vertex); } bool CGfxCamera::IsVisible(const glm::aabb& aabb) const { return m_camera.visible(aabb); } bool CGfxCamera::IsVisible(const glm::sphere& sphere) const { return m_camera.visible(sphere); }
20.646018
140
0.753536
97adcb71b727d993f3f48ec0c431b358a65b8a0a
1,349
hpp
C++
Yannq/Basis/Basis.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
Yannq/Basis/Basis.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
Yannq/Basis/Basis.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
#pragma once //! \defgroup Basis Basis for a spin-1/2 system #include "BasisJz.hpp" #include "BasisFull.hpp" #include <iterator> #include <type_traits> #include <tbb/concurrent_vector.h> #include <tbb/parallel_for_each.h> #include <tbb/parallel_sort.h> /** * Enable if Iterable is not random access iterable */ template<class BasisType> tbb::concurrent_vector<uint32_t> parallelConstructBasis(BasisType&& basis, std::forward_iterator_tag) { tbb::concurrent_vector<uint32_t> res; tbb::parallel_for_each(basis.begin(), basis.end(), [&](uint32_t elt) { res.emplace_back(elt); }); tbb::parallel_sort(res.begin(), res.end()); return res; } template<class BasisType> tbb::concurrent_vector<uint32_t> parallelConstructBasis(BasisType&& basis, std::random_access_iterator_tag) { tbb::concurrent_vector<uint32_t> res(basis.size(), 0u); tbb::parallel_for(std::size_t(0u), basis.size(), [&](std::size_t idx) { res[idx] = basis[idx]; }); return res; } template<class BasisType> inline tbb::concurrent_vector<uint32_t> parallelConstructBasis(BasisType&& basis) { using DecayedBasisType = typename std::decay<BasisType>::type; using IteratorType = typename std::result_of<decltype(&DecayedBasisType::begin)(BasisType)>::type; return parallelConstructBasis(basis, typename std::iterator_traits<IteratorType>::iterator_category()); }
28.702128
107
0.75315
97ae7d212399106e25b982649afb6bd11642ea8e
1,528
hpp
C++
include/parser.hpp
vgracianos/frag-pathtracer
5b216781ee93ec9fe06c07d612c06fe9ae4fc670
[ "MIT" ]
3
2019-09-12T07:49:20.000Z
2021-09-07T08:07:18.000Z
include/parser.hpp
vgracianos/frag-pathtracer
5b216781ee93ec9fe06c07d612c06fe9ae4fc670
[ "MIT" ]
null
null
null
include/parser.hpp
vgracianos/frag-pathtracer
5b216781ee93ec9fe06c07d612c06fe9ae4fc670
[ "MIT" ]
1
2017-03-28T07:03:12.000Z
2017-03-28T07:03:12.000Z
#ifndef PARSER_HPP #define PARSER_HPP #include <string> #include <vector> #include <unordered_map> #include <sstream> #include <tuple> // Parser para ler o arquivo de entrada e gerar um shader class Parser { public: Parser(const std::string& file); int getLights() {return m_lights;}; std::vector<std::string> getTextures() {return m_textures;} std::string read(); private: std::string readCamera(std::ifstream& input); std::string readLights(std::ifstream& input); std::string readMaterials(std::ifstream& input); std::string readProperties(std::ifstream& input); void readObjects(std::ifstream& input, std::string& objects, std::string& materialSelection, std::string& lights); void writeMaterial(std::stringstream& ss, int id1, int id2); std::string m_file, m_root_dir; int m_lights; std::unordered_map<int, std::tuple<float,float,float> > lightColor; std::unordered_map<int, bool> isLight; std::unordered_map<int,int> typeHash, colorHash, checkerHash, texHash; std::vector<std::string> m_textures; std::stringstream externalObjects; }; // Classe simples que carrega um único shader em uma string class ShaderReader { public: ShaderReader(const std::string& path) : m_path(path) {}; std::string read(); private: std::string m_path; }; // Carregador de texturas class TextureLoader { public: void load(const std::string& path); void load(const std::vector<std::string>& textures); private: unsigned int count; }; #include "parser.inl" #endif // PARSER_HPP
26.344828
116
0.721204
97af8f553fd0ca2d14f6905218236556ec82f11a
5,132
tcc
C++
include/lvr2/util/ClusterBiMap.tcc
uos/lvr
9bb03a30441b027c39db967318877e03725112d5
[ "BSD-3-Clause" ]
38
2019-06-19T15:10:35.000Z
2022-02-16T03:08:24.000Z
include/lvr2/util/ClusterBiMap.tcc
jtpils/lvr2
b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce
[ "BSD-3-Clause" ]
9
2019-06-19T16:19:51.000Z
2021-09-17T08:31:25.000Z
include/lvr2/util/ClusterBiMap.tcc
jtpils/lvr2
b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce
[ "BSD-3-Clause" ]
13
2019-04-16T11:50:32.000Z
2020-11-26T07:47:44.000Z
/** * Copyright (c) 2018, University Osnabrück * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University Osnabrück nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL University Osnabrück BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * ClusterBiMap.tcc * * @date 17.06.2017 * @author Johan M. von Behren <johan@vonbehren.eu> */ #include <algorithm> using std::remove; namespace lvr2 { template <typename HandleT> Cluster<HandleT>& ClusterBiMap<HandleT>::getC(ClusterHandle clusterHandle) { return m_cluster[clusterHandle]; } template <typename HandleT> const Cluster<HandleT>& ClusterBiMap<HandleT>::getCluster(ClusterHandle clusterHandle) const { return m_cluster[clusterHandle]; } template <typename HandleT> const Cluster<HandleT>& ClusterBiMap<HandleT>::operator[](ClusterHandle clusterHandle) const { return m_cluster[clusterHandle]; } template <typename HandleT> ClusterHandle ClusterBiMap<HandleT>::createCluster() { ClusterHandle newHandle(m_cluster.size()); m_cluster.push(Cluster<HandleT>()); return newHandle; } template <typename HandleT> void ClusterBiMap<HandleT>::removeCluster(ClusterHandle clusterHandle) { auto cluster = getC(clusterHandle); // Substract number of handles in removed cluster from number of all handles in set m_numHandles -= cluster.handles.size(); // Remove handles in cluster from cluster map for (auto handle: cluster.handles) { m_clusterMap.erase(handle); } // Remove cluster m_cluster.erase(clusterHandle); } template <typename HandleT> ClusterHandle ClusterBiMap<HandleT>::addToCluster(ClusterHandle clusterHandle, HandleT handle) { getC(clusterHandle).handles.push_back(handle); m_clusterMap.insert(handle, clusterHandle); ++m_numHandles; return clusterHandle; } template <typename HandleT> ClusterHandle ClusterBiMap<HandleT>::removeFromCluster(ClusterHandle clusterHandle, HandleT handle) { auto& handles = getC(clusterHandle).handles; handles.erase(remove(handles.begin(), handles.end(), handle), handles.end()); m_clusterMap.erase(handle); --m_numHandles; return clusterHandle; } template <typename HandleT> ClusterHandle ClusterBiMap<HandleT>::getClusterH(HandleT handle) const { return m_clusterMap[handle]; } template <typename HandleT> OptionalClusterHandle ClusterBiMap<HandleT>::getClusterOf(HandleT handle) const { auto maybe = m_clusterMap.get(handle); if (maybe) { return *maybe; } return OptionalClusterHandle(); } template <typename HandleT> size_t ClusterBiMap<HandleT>::numCluster() const { return m_cluster.numUsed(); } template <typename HandleT> size_t ClusterBiMap<HandleT>::numHandles() const { return m_numHandles; } template <typename HandleT> void ClusterBiMap<HandleT>::reserve(size_t newCap) { m_cluster.reserve(newCap); m_clusterMap.reserve(newCap); } template<typename HandleT> ClusterBiMapIterator<HandleT>& ClusterBiMapIterator<HandleT>::operator++() { ++m_iterator; return *this; } template<typename HandleT> bool ClusterBiMapIterator<HandleT>::operator==(const ClusterBiMapIterator& other) const { return m_iterator == other.m_iterator; } template<typename HandleT> bool ClusterBiMapIterator<HandleT>::operator!=(const ClusterBiMapIterator& other) const { return m_iterator != other.m_iterator; } template<typename HandleT> ClusterHandle ClusterBiMapIterator<HandleT>::operator*() const { return *m_iterator; } template <typename HandleT> ClusterBiMapIterator<HandleT> ClusterBiMap<HandleT>::begin() const { return m_cluster.begin(); } template <typename HandleT> ClusterBiMapIterator<HandleT> ClusterBiMap<HandleT>::end() const { return m_cluster.end(); } } // namespace lvr2
27.891304
99
0.75039
97b0dacca5c6ee9cc708303355473da2f51f0703
182
cpp
C++
esmini/Hello-World_coding-example/main.cpp
angelocarbone/MoDelS
5bfee8d0b6e719c1d2445acf4e332597427ac906
[ "MIT" ]
1
2021-12-02T07:29:29.000Z
2021-12-02T07:29:29.000Z
esmini/Hello-World_coding-example/main.cpp
angelocarbone/MoDelS
5bfee8d0b6e719c1d2445acf4e332597427ac906
[ "MIT" ]
null
null
null
esmini/Hello-World_coding-example/main.cpp
angelocarbone/MoDelS
5bfee8d0b6e719c1d2445acf4e332597427ac906
[ "MIT" ]
null
null
null
#include "esminiLib.hpp" int main(int argc, char* argv[]) { SE_Init("../resources/xosc/cut-in.xosc", 0, 1, 0, 0); for (int i = 0; i < 500; i++) { SE_Step(); } return 0; }
12.133333
54
0.554945
97b267ade79d96a1ca904af4696106522121fe1f
2,273
cpp
C++
main.cpp
Triploit-org/TSS-Linux
369bcfb430d2e3fc568f5565c56f2767284b1835
[ "MIT" ]
1
2016-09-12T15:08:29.000Z
2016-09-12T15:08:29.000Z
main.cpp
Triploit-org/TSS-Linux
369bcfb430d2e3fc568f5565c56f2767284b1835
[ "MIT" ]
1
2016-09-11T17:57:21.000Z
2016-09-12T15:02:56.000Z
main.cpp
Triploit-org/TSS-Linux
369bcfb430d2e3fc568f5565c56f2767284b1835
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <sstream> #include <algorithm> #include <iterator> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include "Commands/info.h" #include "APIs/checkCommand.h" #include "APIs/existsFile.h" using namespace std; //Variablen double Version = 0.1; string System = "Linux"; char pfad[256]; string input; string hostname = "Linux"; //Variablen ende // DAS HIER DANN IN COMMANDS_H void befehl1(vector<string> args); vector<string> names; void(*befehle[2])(vector<string> args) = { &befehl1, befehl1 }; void nInit() { names.push_back("befehl1"); names.push_back("befehl2"); } void befehl1(vector<string> args) { for (int i = 0; i < args.size(); i++) { cout << "Argument " << i << " = " << args[i] << endl; } cout << "Befehl1 bendet!" << endl; return; } #define ANZ names.size(); // ENDE COMMANDS_H int shell(int argc, char const *argv[]) { string cmd = ""; while (!checkCommand(cmd, "exit")) { string input; vector<string> args; getcwd(pfad, 256); //bald wird hier der Hostname des pcs definiert std::cout << "\033[0m\033[1m\033[32m" << "[" << getenv("USER") << "@" << hostname << "]" << "$ " << "\033[0m"; getline(cin, input); if(input != "") { stringstream ss(input); string buf; while (ss >> buf) { args.push_back(buf); } cmd = args[0]; if (checkCommand(cmd, "befehl1") || checkCommand(cmd, "befehl2")) { befehl1(args); } else { if (existsFile(cmd)) { cout << "\033[0m\033[1m\033[32mStarte Datei in Shell..\033[39m.\n\n"; string executefilestr = "./"; executefilestr += cmd.c_str(); system(executefilestr.c_str()); } else { cout << "\033[031;1;31mDie Datei oder das Kommando wurde nicht gefunden!\n"; } } } } } int scriptfile(int argc, char const *argv[]) { cout << "\033[031;1;31mDie Script funktion ist noch nicht vervollständigt\n"; return 0; } int main(int argc, char const *argv[]) { info(Version, System); if (argc==1) { shell(argc, argv); } else { scriptfile(argc, argv); } return 0; }
19.42735
114
0.573251
97b5ad3f88874a5ef67632c787ae9b65005b5053
1,021
cpp
C++
Lab8/Date.cpp
RustyRaptor/CS271
3d6787a5bf6bdd69176a685124ffcfee44de2d59
[ "MIT" ]
null
null
null
Lab8/Date.cpp
RustyRaptor/CS271
3d6787a5bf6bdd69176a685124ffcfee44de2d59
[ "MIT" ]
null
null
null
Lab8/Date.cpp
RustyRaptor/CS271
3d6787a5bf6bdd69176a685124ffcfee44de2d59
[ "MIT" ]
null
null
null
// CS271 - Lab Assignment: #8 // Program name: C++ Classes // Purpose of program: Some classes in C++ // written by: Ziad Arafat // Date Written: 2020-04-12 #include "Date.h" using namespace std; unsigned int month; unsigned int day; unsigned int year; Date::Date( ) { month = 1; day = 1; year = 1980; } Date::Date( int m, int d, int y ) { month = m; day = d; year = y; } void Date::setMonth( int m ) { if (m >= 1 && m <= 12){ month = m; } } void Date::setDay( int d ) { if (d >= 1 && d <= 31){ day = d; } } void Date::setYear( int y ) { if (y >= 1980 && y <= 2100){ year = y; } } int Date::getMonth( ) { return month; } int Date::getDay( ) { return day; } int Date::getYear( ) { return year; } void Date::print( ) { cout << setfill( '0' ) << setw( 2 ) << getMonth( ) << "/" << setfill( '0' ) << setw( 2 ) << getDay( ) << "/" << setfill( '0' ) << setw( 4 ) << getYear( ) << endl; }
16.206349
63
0.481881
97b76d7ee77235cf4e0ebff11a4e2b84d1427b18
14,364
cpp
C++
admin/wmi/wbem/providers/win32provider/sessionandconnections/dll/connectiontosession.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/wmi/wbem/providers/win32provider/sessionandconnections/dll/connectiontosession.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/wmi/wbem/providers/win32provider/sessionandconnections/dll/connectiontosession.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/****************************************************************** ConnectionToSession.CPP -- C provider class implementation Copyright (c) 2000-2001 Microsoft Corporation, All Rights Reserved Description: Association between Connection To Session ******************************************************************/ #include "precomp.h" #include "ConnectionToSession.h" CConnectionToSession MyCConnectionToSession ( PROVIDER_NAME_CONNECTIONTOSESSION , Namespace ) ; /***************************************************************************** * * FUNCTION : CConnectionToSession::CConnectionToSession * * DESCRIPTION : Constructor * *****************************************************************************/ CConnectionToSession :: CConnectionToSession ( LPCWSTR lpwszName, LPCWSTR lpwszNameSpace ) : Provider ( lpwszName , lpwszNameSpace ) { } /***************************************************************************** * * FUNCTION : CConnectionToSession::~CConnectionToSession * * DESCRIPTION : Destructor * *****************************************************************************/ CConnectionToSession :: ~CConnectionToSession () { } /***************************************************************************** * * FUNCTION : CConnectionToSession::EnumerateInstances * * DESCRIPTION : Returns all the instances of this class. * *****************************************************************************/ HRESULT CConnectionToSession :: EnumerateInstances ( MethodContext *pMethodContext, long lFlags ) { HRESULT hRes = WBEM_S_NO_ERROR ; DWORD dwPropertiesReq = CONNECTIONSTOSESSION_ALL_PROPS; hRes = EnumConnectionInfo ( L"", L"", pMethodContext, dwPropertiesReq ); return hRes ; } /***************************************************************************** * * FUNCTION : CConnectionToSession::GetObject * * DESCRIPTION : Find a single instance based on the key properties for the * class. * *****************************************************************************/ HRESULT CConnectionToSession :: GetObject ( CInstance *pInstance, long lFlags , CFrameworkQuery &Query ) { HRESULT hRes = WBEM_S_NO_ERROR; CHString t_Connection ; CHString t_Session; if ( pInstance->GetCHString ( IDS_Connection , t_Connection ) == FALSE ) { hRes = WBEM_E_INVALID_PARAMETER ; } if ( SUCCEEDED ( hRes ) ) { if ( pInstance->GetCHString ( IDS_Session , t_Session ) == FALSE ) { hRes = WBEM_E_INVALID_PARAMETER ; } } if ( SUCCEEDED ( hRes ) ) { CHString t_ConnComputerName; CHString t_ConnShareName; CHString t_ConnUserName; hRes = GetConnectionsKeyVal ( t_Connection, t_ConnComputerName, t_ConnShareName, t_ConnUserName ); if ( SUCCEEDED ( hRes ) ) { CHString t_SessComputerName; CHString t_SessUserName; hRes = GetSessionKeyVal ( t_Session, t_SessComputerName, t_SessUserName ); if ( SUCCEEDED ( hRes ) ) { // now check the shares in t_Connection and t_Session should match hRes = _wcsicmp ( t_ConnComputerName, t_SessComputerName ) == 0 ? hRes : WBEM_E_NOT_FOUND; if ( SUCCEEDED ( hRes ) ) { hRes = _wcsicmp ( t_ConnUserName, t_SessUserName ) == 0 ? hRes : WBEM_E_NOT_FOUND; if ( SUCCEEDED ( hRes ) ) { #ifdef NTONLY hRes = FindAndSetNTConnection ( t_ConnShareName.GetBuffer(0), t_ConnComputerName, t_ConnUserName, 0, pInstance, NoOp ); #endif #if 0 #ifdef WIN9XONLY hRes = FindAndSet9XConnection ( t_ConnShareName, t_ConnComputerName, t_ConnUserName, 0, pInstance, NoOp ); #endif #endif } } } } } return hRes ; } #ifdef NTONLY /***************************************************************************** * * FUNCTION : CConnectionToSession::EnumNTConnectionsFromComputerToShare * * DESCRIPTION : Enumerating all the connections made from a computer to * a given share * *****************************************************************************/ HRESULT CConnectionToSession :: EnumNTConnectionsFromComputerToShare ( LPWSTR a_ComputerName, LPWSTR a_ShareName, MethodContext *pMethodContext, DWORD dwPropertiesReq ) { HRESULT hRes = WBEM_S_NO_ERROR; NET_API_STATUS t_Status = NERR_Success; DWORD dwNoOfEntriesRead = 0; DWORD dwTotalConnections = 0; DWORD dwResumeHandle = 0; CONNECTION_INFO *pBuf = NULL; CONNECTION_INFO *pTmpBuf = NULL; LPWSTR t_ComputerName = NULL; if ( a_ComputerName && a_ComputerName[0] != L'\0' ) { //let's skip the \\ chars t_ComputerName = a_ComputerName + 2; } // ShareName and Computer Name both cannot be null at the same time while ( TRUE ) { if ( a_ShareName[0] != L'\0' ) { t_Status = NetConnectionEnum( NULL, a_ShareName, 1, (LPBYTE *) &pBuf, -1, &dwNoOfEntriesRead, &dwTotalConnections, &dwResumeHandle ); } else if ( a_ComputerName[0] != L'\0' ) { t_Status = NetConnectionEnum( NULL, a_ComputerName, 1, (LPBYTE *) &pBuf, -1, &dwNoOfEntriesRead, &dwTotalConnections, &dwResumeHandle ); } if ( t_Status == NERR_Success ) { if ( dwNoOfEntriesRead == 0 ) { break; } else if ( dwNoOfEntriesRead > 0 ) { try { pTmpBuf = pBuf; for ( int i = 0; i < dwNoOfEntriesRead; i++, pTmpBuf++ ) { if (pTmpBuf->coni1_netname && pBuf->coni1_username) { CInstancePtr pInstance ( CreateNewInstance ( pMethodContext ), FALSE ); hRes = LoadInstance ( pInstance, a_ShareName, t_ComputerName ? t_ComputerName : a_ComputerName, pTmpBuf, dwPropertiesReq ); if ( SUCCEEDED ( hRes ) ) { hRes = pInstance->Commit(); if ( FAILED ( hRes ) ) { break; } } else { break; } } } } catch ( ... ) { NetApiBufferFree ( pBuf ); pBuf = NULL; throw; } NetApiBufferFree ( pBuf ); pBuf = NULL; } } else { if ( t_Status != ERROR_MORE_DATA ) { if ( t_Status == ERROR_ACCESS_DENIED ) { hRes = WBEM_E_ACCESS_DENIED; } else { if ( t_Status == ERROR_NOT_ENOUGH_MEMORY ) { hRes = WBEM_E_OUT_OF_MEMORY; } else { hRes = WBEM_E_FAILED; } } break; } } } return hRes; } #endif #if 0 #ifdef WIN9XONLY /***************************************************************************** * * FUNCTION : CConnectionToSession::Enum9XConnectionsFromComputerToShare * * DESCRIPTION : Enumerating all the connections made from a computer to * a given share * *****************************************************************************/ HRESULT CConnectionToSession :: Enum9XConnectionsFromComputerToShare ( LPWSTR a_ComputerName, LPWSTR a_ShareName, MethodContext *pMethodContext, DWORD dwPropertiesReq ) { HRESULT hRes = WBEM_S_NO_ERROR; NET_API_STATUS t_Status = NERR_Success; DWORD dwNoOfEntriesRead = 0; DWORD dwTotalConnections = 0; BOOL bFound = FALSE; CONNECTION_INFO * pBuf = NULL; CONNECTION_INFO * pTmpBuf = NULL; DWORD dwBufferSize = MAX_ENTRIES * sizeof( CONNECTION_INFO ); pBuf = ( CONNECTION_INFO *) malloc(dwBufferSize); if ( pBuf != NULL ) { try { t_Status = NetConnectionEnum( NULL, (char FAR *) ( a_ShareName ), // ShareName 1, (char *) pBuf, ( unsigned short )dwBufferSize, ( unsigned short *) &dwNoOfEntriesRead, ( unsigned short *) &dwTotalConnections ); } catch ( ... ) { free ( pBuf ); pBuf = NULL; throw; } // otherwise we are not to frr the buffer, we have use it and then free the buffer. if ( ( dwNoOfEntriesRead < dwTotalConnections ) && ( t_Status == ERROR_MORE_DATA ) ) { free ( pBuf ); pBuf = NULL; pBuf = ( CONNECTION_INFO *) malloc( dwTotalConnections ); if ( pBuf != NULL ) { try { t_Status = NetConnectionEnum( NULL, (char FAR *) ( a_ShareName ), // ShareName 1, (char *) pBuf, ( unsigned short )dwBufferSize, ( unsigned short *) &dwNoOfEntriesRead, ( unsigned short *) &dwTotalConnections ); } catch ( ... ) { free ( pBuf ); pBuf = NULL; throw; } // We need to use the buffer before we free it } else { throw CHeap_Exception ( CHeap_Exception :: E_ALLOCATION_ERROR ) ; } } // The buffer is yet to be used if ( ( t_Status == NERR_Success ) && ( dwNoOfEntriesRead == dwTotalConnections ) ) { // use the buffer first and then free if ( pBuf != NULL ) { try { pTmpBuf = pBuf; for ( int i = 0; i < dwNoOfEntriesRead; i++, pTmpBuf ++) { CInstancePtr pInstance ( CreateNewInstance ( pMethodContext ), FALSE ); hRes = LoadInstance ( pInstance, a_ShareName, a_ComputerName, pTmpBuf, dwPropertiesReq ); if ( SUCCEEDED ( hRes ) ) { hRes = pInstance->Commit(); if ( FAILED ( hRes ) ) { break; } } } } catch ( ... ) { free ( pBuf ); pBuf = NULL; throw; } // finally free the buffer free (pBuf ); pBuf = NULL; } else { throw CHeap_Exception ( CHeap_Exception :: E_ALLOCATION_ERROR ) ; } } else { hRes = WBEM_E_FAILED; } } else { throw CHeap_Exception ( CHeap_Exception :: E_ALLOCATION_ERROR ) ; } return hRes; } #endif #endif /***************************************************************************** * * FUNCTION : CConnectionToSession:: LoadInstance * * DESCRIPTION : Loading an instance with the connection to Session info * *****************************************************************************/ HRESULT CConnectionToSession :: LoadInstance ( CInstance *pInstance, LPCWSTR a_Share, LPCWSTR a_Computer, CONNECTION_INFO *pBuf, DWORD dwPropertiesReq ) { HRESULT hRes = WBEM_S_NO_ERROR; LPWSTR ObjPath = NULL; LPWSTR SessObjPath = NULL; try { CHString t_NetName ( pBuf->coni1_netname ); if ( a_Share[0] != L'\0' ) { hRes = MakeObjectPath ( ObjPath, PROVIDER_NAME_CONNECTION, IDS_ComputerName, t_NetName ); if ( SUCCEEDED ( hRes ) ) { hRes = AddToObjectPath ( ObjPath, IDS_ShareName, a_Share ); } if ( SUCCEEDED ( hRes ) ) { hRes = MakeObjectPath ( SessObjPath, PROVIDER_NAME_SESSION, IDS_ComputerName, t_NetName ); } } else { hRes = MakeObjectPath ( ObjPath, PROVIDER_NAME_CONNECTION, IDS_ComputerName, a_Computer ); if ( SUCCEEDED ( hRes ) ) { hRes = AddToObjectPath ( ObjPath, IDS_ShareName, t_NetName ); } if ( SUCCEEDED ( hRes ) ) { MakeObjectPath ( SessObjPath, PROVIDER_NAME_SESSION, IDS_ComputerName, a_Computer); } } CHString t_UserName ( pBuf->coni1_username ); if ( SUCCEEDED ( hRes ) ) { hRes = AddToObjectPath ( ObjPath, IDS_UserName, t_UserName ); } if ( SUCCEEDED ( hRes ) ) { hRes = AddToObjectPath ( SessObjPath, IDS_UserName, t_UserName ); } if ( SUCCEEDED ( hRes ) ) { if ( pInstance->SetCHString ( IDS_Connection, ObjPath ) == FALSE ) { hRes = WBEM_E_PROVIDER_FAILURE ; } } if ( SUCCEEDED ( hRes ) ) { if ( pInstance->SetCHString ( IDS_Session, SessObjPath ) == FALSE ) { hRes = WBEM_E_PROVIDER_FAILURE ; } } } catch (...) { if (SessObjPath) { delete [] SessObjPath; SessObjPath = NULL; } if (ObjPath) { delete [] ObjPath; ObjPath = NULL; } throw; } if (SessObjPath) { delete [] SessObjPath; SessObjPath = NULL; } if (ObjPath) { delete [] ObjPath; ObjPath = NULL; } return hRes; } /***************************************************************************** * * FUNCTION : CConnectionToSession::GetSessionKeyVal * * DESCRIPTION : Parsing the key to get Connection Key Value * *****************************************************************************/ HRESULT CConnectionToSession::GetSessionKeyVal ( LPCWSTR a_Key, CHString &a_ComputerName, CHString &a_UserName ) { HRESULT hRes = WBEM_S_NO_ERROR; ParsedObjectPath *t_ObjPath; CObjectPathParser t_PathParser; DWORD dwAllKeys = 0; if ( t_PathParser.Parse( a_Key, &t_ObjPath ) == t_PathParser.NoError ) { try { hRes = t_ObjPath->m_dwNumKeys != 2 ? WBEM_E_INVALID_PARAMETER : hRes; if ( SUCCEEDED ( hRes ) ) { hRes = _wcsicmp ( t_ObjPath->m_pClass, PROVIDER_NAME_SESSION ) != 0 ? WBEM_E_INVALID_PARAMETER : hRes; if ( SUCCEEDED ( hRes ) ) { for ( int i = 0; i < 2; i++ ) { if (V_VT(&t_ObjPath->m_paKeys[i]->m_vValue) == VT_BSTR) { if ( _wcsicmp ( t_ObjPath->m_paKeys[i]->m_pName, IDS_ComputerName ) == 0 ) { a_ComputerName = t_ObjPath->m_paKeys[i]->m_vValue.bstrVal; dwAllKeys |= 1; } else if ( _wcsicmp ( t_ObjPath->m_paKeys[i]->m_pName, IDS_UserName ) == 0 ) { a_UserName = t_ObjPath->m_paKeys[i]->m_vValue.bstrVal; dwAllKeys |= 2; } } } if ( dwAllKeys != 3 ) { hRes = WBEM_E_INVALID_PARAMETER; } } else { hRes = WBEM_E_INVALID_PARAMETER; } } } catch ( ... ) { delete t_ObjPath; throw; } delete t_ObjPath; } else { hRes = WBEM_E_INVALID_PARAMETER; } return hRes; }
22.8
131
0.525968
b632914d2592fde88b55410d451e1a343d27e425
8,097
cpp
C++
sdl1/VisualBoyAdvance/src/win32/AccelEditor.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/VisualBoyAdvance/src/win32/AccelEditor.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/VisualBoyAdvance/src/win32/AccelEditor.cpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
// VisualBoyAdvance - Nintendo Gameboy/GameboyAdvance (TM) emulator. // Copyright (C) 1999-2003 Forgotten // Copyright (C) 2004 Forgotten and the VBA development team // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2, or(at your option) // any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // AccelEditor.cpp : implementation file // #include "stdafx.h" #include "vba.h" #include "AccelEditor.h" #include "CmdAccelOb.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // AccelEditor dialog AccelEditor::AccelEditor(CWnd* pParent /*=NULL*/) : ResizeDlg(AccelEditor::IDD, pParent) { //{{AFX_DATA_INIT(AccelEditor) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT mgr = theApp.winAccelMgr; } void AccelEditor::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(AccelEditor) DDX_Control(pDX, IDC_CURRENTS, m_currents); DDX_Control(pDX, IDC_ALREADY_AFFECTED, m_alreadyAffected); DDX_Control(pDX, IDC_COMMANDS, m_commands); DDX_Control(pDX, IDC_EDIT_KEY, m_key); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(AccelEditor, CDialog) //{{AFX_MSG_MAP(AccelEditor) ON_BN_CLICKED(ID_OK, OnOk) ON_LBN_SELCHANGE(IDC_COMMANDS, OnSelchangeCommands) ON_BN_CLICKED(IDC_RESET, OnReset) ON_BN_CLICKED(IDC_ASSIGN, OnAssign) ON_BN_CLICKED(ID_CANCEL, OnCancel) ON_BN_CLICKED(IDC_REMOVE, OnRemove) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // AccelEditor message handlers BOOL AccelEditor::OnInitDialog() { CDialog::OnInitDialog(); DIALOG_SIZER_START( sz ) DIALOG_SIZER_ENTRY( IDC_STATIC1, DS_MoveX) DIALOG_SIZER_ENTRY( IDC_STATIC2, DS_MoveY) DIALOG_SIZER_ENTRY( IDC_STATIC3, DS_MoveX | DS_MoveY) DIALOG_SIZER_ENTRY( IDC_ALREADY_AFFECTED, DS_MoveY) DIALOG_SIZER_ENTRY( ID_OK, DS_MoveX) DIALOG_SIZER_ENTRY( ID_CANCEL, DS_MoveX) DIALOG_SIZER_ENTRY( IDC_ASSIGN, DS_MoveX) DIALOG_SIZER_ENTRY( IDC_REMOVE, DS_MoveX) DIALOG_SIZER_ENTRY( IDC_RESET, DS_MoveX) DIALOG_SIZER_ENTRY( IDC_CLOSE, DS_MoveY) DIALOG_SIZER_ENTRY( IDC_COMMANDS, DS_SizeX | DS_SizeY) DIALOG_SIZER_ENTRY( IDC_CURRENTS, DS_MoveX | DS_SizeY) DIALOG_SIZER_ENTRY( IDC_EDIT_KEY, DS_MoveX | DS_MoveY) DIALOG_SIZER_END() SetData(sz, TRUE, HKEY_CURRENT_USER, "Software\\Emulators\\VisualBoyAdvance\\Viewer\\AccelEditor", NULL); InitCommands(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void AccelEditor::InitCommands() { m_commands.ResetContent(); m_alreadyAffected.SetWindowText(""); POSITION pos = mgr.m_mapAccelString.GetStartPosition(); while(pos != NULL) { CString command; WORD wID; mgr.m_mapAccelString.GetNextAssoc(pos, command, wID); int index = m_commands.AddString(command); m_commands.SetItemData(index, wID); } // Update the currents accels associated with the selected command if (m_commands.SetCurSel(0) != LB_ERR) OnSelchangeCommands(); } void AccelEditor::OnCancel() { EndDialog(FALSE); } void AccelEditor::OnOk() { EndDialog(TRUE); } void AccelEditor::OnSelchangeCommands() { // Check if some commands exist. int index = m_commands.GetCurSel(); if (index == LB_ERR) return; WORD wIDCommand = LOWORD(m_commands.GetItemData(index)); m_currents.ResetContent(); CCmdAccelOb* pCmdAccel; if (mgr.m_mapAccelTable.Lookup(wIDCommand, pCmdAccel)) { CAccelsOb* pAccel; CString szBuffer; POSITION pos = pCmdAccel->m_Accels.GetHeadPosition(); // Add the keys to the 'currents keys' listbox. while (pos != NULL) { pAccel = pCmdAccel->m_Accels.GetNext(pos); pAccel->GetString(szBuffer); index = m_currents.AddString(szBuffer); // and a pointer to the accel object. m_currents.SetItemData(index, (DWORD_PTR)pAccel); } } // Init the key editor // m_pKey->ResetKey(); } void AccelEditor::OnReset() { mgr.Default(); InitCommands(); // update the listboxes. } void AccelEditor::OnAssign() { // Control if it's not already affected CCmdAccelOb* pCmdAccel; CAccelsOb* pAccel; WORD wIDCommand; POSITION pos; WORD wKey; bool bCtrl, bAlt, bShift; if (!m_key.GetAccelKey(wKey, bCtrl, bAlt, bShift)) return; // no valid key, abort int count = m_commands.GetCount(); int index; for (index = 0; index < count; index++) { wIDCommand = LOWORD(m_commands.GetItemData(index)); mgr.m_mapAccelTable.Lookup(wIDCommand, pCmdAccel); pos = pCmdAccel->m_Accels.GetHeadPosition(); while (pos != NULL) { pAccel = pCmdAccel->m_Accels.GetNext(pos); if (pAccel->IsEqual(wKey, bCtrl, bAlt, bShift)) { // the key is already affected (in the same or other command) m_alreadyAffected.SetWindowText(pCmdAccel->m_szCommand); m_key.SetSel(0, -1); return; // abort } } } // OK, we can add the accel key in the currently selected group index = m_commands.GetCurSel(); if (index == LB_ERR) return; // Get the object who manage the accels list, associated to the command. wIDCommand = LOWORD(m_commands.GetItemData(index)); if (mgr.m_mapAccelTable.Lookup(wIDCommand, pCmdAccel) != TRUE) return; BYTE cVirt = 0; if (bCtrl) cVirt |= FCONTROL; if (bAlt) cVirt |= FALT; if (bShift) cVirt |= FSHIFT; cVirt |= FVIRTKEY; // Create the new key... pAccel = new CAccelsOb(cVirt, wKey, false); ASSERT(pAccel != NULL); // ...and add in the list. pCmdAccel->m_Accels.AddTail(pAccel); // Update the listbox. CString szBuffer; pAccel->GetString(szBuffer); index = m_currents.AddString(szBuffer); m_currents.SetItemData(index, (DWORD_PTR)pAccel); // Reset the key editor. m_key.ResetKey(); } void AccelEditor::OnRemove() { // Some controls int indexCurrent = m_currents.GetCurSel(); if (indexCurrent == LB_ERR) return; // 2nd part. int indexCmd = m_commands.GetCurSel(); if (indexCmd == LB_ERR) return; // Ref to the ID command WORD wIDCommand = LOWORD(m_commands.GetItemData(indexCmd)); // Run through the accels,and control if it can be deleted. CCmdAccelOb* pCmdAccel; if (mgr.m_mapAccelTable.Lookup(wIDCommand, pCmdAccel) == TRUE) { CAccelsOb* pAccel; CAccelsOb* pAccelCurrent = (CAccelsOb*)(m_currents.GetItemData(indexCurrent)); CString szBuffer; POSITION pos = pCmdAccel->m_Accels.GetHeadPosition(); POSITION PrevPos; while (pos != NULL) { PrevPos = pos; pAccel = pCmdAccel->m_Accels.GetNext(pos); if (pAccel == pAccelCurrent) { if (!pAccel->m_bLocked) { // not locked, so we delete the key pCmdAccel->m_Accels.RemoveAt(PrevPos); delete pAccel; // and update the listboxes/key editor/static text m_currents.DeleteString(indexCurrent); m_key.ResetKey(); m_alreadyAffected.SetWindowText(""); return; } else { systemMessage(0,"Unable to remove this\naccelerator (Locked)"); return; } } } systemMessage(0,"internal error (CAccelDlgHelper::Remove : pAccel unavailable)"); return; } systemMessage(0,"internal error (CAccelDlgHelper::Remove : Lookup failed)"); }
27.824742
85
0.681116
b63479c43fe8c989fc03537f6a2975891c2d8806
124
hpp
C++
include/litmus/details/verbosity.hpp
JessyDL/litmus
156814116d83ee7884c76adda327bf7a9ef0cb14
[ "MIT" ]
1
2021-04-03T00:18:45.000Z
2021-04-03T00:18:45.000Z
include/litmus/details/verbosity.hpp
JessyDL/litmus
156814116d83ee7884c76adda327bf7a9ef0cb14
[ "MIT" ]
null
null
null
include/litmus/details/verbosity.hpp
JessyDL/litmus
156814116d83ee7884c76adda327bf7a9ef0cb14
[ "MIT" ]
null
null
null
#pragma once namespace litmus { enum class verbosity_t { NONE = 0, COMPACT = 1, NORMAL = 2, DETAILED = 3 }; }
10.333333
23
0.596774
b63514f9432f7c5ca3f8514c9e50581e878cb984
1,005
hpp
C++
DifferentialEvolution/DifferentialEvolution.hpp
nottu/LinearSVM
7f5ce05b0691e03a12377dd1f177768f59a91e30
[ "MIT" ]
null
null
null
DifferentialEvolution/DifferentialEvolution.hpp
nottu/LinearSVM
7f5ce05b0691e03a12377dd1f177768f59a91e30
[ "MIT" ]
null
null
null
DifferentialEvolution/DifferentialEvolution.hpp
nottu/LinearSVM
7f5ce05b0691e03a12377dd1f177768f59a91e30
[ "MIT" ]
null
null
null
// // Created by Javier Peralta on 5/31/18. // #ifndef SVM_DIFFERENTIALEVOLUTION_HPP #define SVM_DIFFERENTIALEVOLUTION_HPP #include "../Data.hpp" #include "../OptimizationProblem.hpp" class DifferentialEvolution { public: friend class Individual; class Individual; private: unsigned max_evals; unsigned num_vars; double __cr, __F; OptimizationProblem *__problem; bool minimize; std::vector<Individual> population; std::vector<int> get_parent_idx(); public: DifferentialEvolution(std::vector<Individual> &pop, unsigned max_evals, double cr, double F, OptimizationProblem *problem, ProblemType type = ProblemType::MINIMIZE); Individual getBest(); bool iterate(); }; class DifferentialEvolution::Individual{ friend class DifferentialEvolution; protected: vect data; double value; public: vect get_data(); double get_value(); void set_value(double val); explicit Individual(vect &dat); Individual(vect &dat, double val); }; #endif //SVM_DIFFERENTIALEVOLUTION_HPP
22.840909
167
0.759204
b637fe4d30b266db56418882aa4a463fc1d8b7cc
1,704
hpp
C++
actan_tools/core/sensors.hpp
oliver-peoples/ACTAN
5ed78c8e88232dab92fb934d0f85c007d4e98596
[ "Unlicense" ]
null
null
null
actan_tools/core/sensors.hpp
oliver-peoples/ACTAN
5ed78c8e88232dab92fb934d0f85c007d4e98596
[ "Unlicense" ]
null
null
null
actan_tools/core/sensors.hpp
oliver-peoples/ACTAN
5ed78c8e88232dab92fb934d0f85c007d4e98596
[ "Unlicense" ]
null
null
null
#ifndef ACTAN_TOOLS_SENSORS_HPP #define ACTAN_TOOLS_SENSORS_HPP #if defined(__float128) #define depth_level __float128 #elif defined(_Float128) #define depth_level _Float128 #else #define depth_level long double #endif #include <hmath/core.hpp> namespace actan { namespace sensor { class Sensor { private: hmath::DualQuaternion<depth_level> mounting_position = { 1,0,0,0,1,0,0,0 }; public: Sensor(); ~Sensor(); void setMountingPosition(hmath::DualQuaternion<depth_level>); void setMountingPosition(hmath::Vector3<depth_level>, hmath::Quaternion<depth_level>); void setMountingPosition(hmath::Quaternion<depth_level>, hmath::Vector3<depth_level>); }; class InertialSensor : public Sensor { private: hmath::Vector3<depth_level> angular_rates_limit, raw_acc_limits; hmath::Vector3<depth_level> latest_angular_rates, latest_raw_acceleration; public: InertialSensor(); ~InertialSensor(); }; class PinholeCamera : public Sensor { private: depth_level focal_length, aperture; public: PinholeCamera(); ~PinholeCamera(); }; } class AHRS : public sensor::InertialSensor { private: hmath::Quaternion<depth_level> orientation; hmath::Vector3<depth_level> free_acceleration; public: AHRS(); ~AHRS(); template<typename T> void setOrientation(hmath::Vector3<T>); template<typename T> void setFreeAcceleration(hmath::Vector3<T>); }; } #endif
24.342857
98
0.619131
b63d21667567b563bbfa8923303d0ee361244700
2,794
hpp
C++
src/shape/Bunker.hpp
newnone/Non-Gravitar
9d21cf7ab5ef49f6976fcaf25fa01cacbb209740
[ "MIT" ]
null
null
null
src/shape/Bunker.hpp
newnone/Non-Gravitar
9d21cf7ab5ef49f6976fcaf25fa01cacbb209740
[ "MIT" ]
null
null
null
src/shape/Bunker.hpp
newnone/Non-Gravitar
9d21cf7ab5ef49f6976fcaf25fa01cacbb209740
[ "MIT" ]
null
null
null
// MIT License // // Copyright (c) 2018 Oscar B. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #ifndef NON_GRAVITAR_BUNKER_HPP #define NON_GRAVITAR_BUNKER_HPP #include <vector> #include "ClosedShape.hpp" #include "Rectangle.hpp" #include "RoundMissile.hpp" #include "ShapeVisitor.hpp" template<typename T> using vector = std::vector<T>; namespace gvt { class Bunker: public ClosedShape { private: double mDelay{0}; vector<double> mDirections; unsigned mCurr{0}; static unsigned const constexpr WIDTH = 66; static unsigned const constexpr HEIGHT = 45; BoundingPolygon polygonFactory() const; public: Bunker(Vectord position, size_t directions); inline double width() const override; inline double height() const override; /** * Sets the missile delay, i.e. the time to wait before the next * missile is shot. */ inline void missileDelay (double delay); /** * Getter method of @c missileDelay(double). */ inline double missileDelay () const; /** * @return a @c RoundMissile instance shot by the calling @c Bunker * object, with a random velocity vector of unitary norm. */ shared_ptr<RoundMissile> shoot(double speed, long lifespan, double radius); inline unsigned directions() const; void accept (ShapeVisitor &visitor) override; bool operator==(Shape const &o) const override; }; } namespace gvt { void Bunker::missileDelay (double delay) { mDelay = delay; } double Bunker::missileDelay () const { return mDelay; } // Implementation of inline Bunker functions double Bunker::width() const { return WIDTH; } double Bunker::height() const { return HEIGHT; } unsigned Bunker::directions() const { return mDirections.size(); } } #endif
28.222222
81
0.725125
b64307fb369aa01cc588abc7842c0b68c5383a69
61,868
cpp
C++
src/modules/rppi_filter_operations.cpp
shobana-mcw/rpp
e4a5eb622b9abd0a5a936bf7174a84a5e2470b59
[ "MIT" ]
26
2019-09-04T17:48:41.000Z
2022-02-23T17:04:24.000Z
src/modules/rppi_filter_operations.cpp
shobana-mcw/rpp
e4a5eb622b9abd0a5a936bf7174a84a5e2470b59
[ "MIT" ]
57
2019-09-06T21:37:34.000Z
2022-03-09T02:13:46.000Z
src/modules/rppi_filter_operations.cpp
shobana-mcw/rpp
e4a5eb622b9abd0a5a936bf7174a84a5e2470b59
[ "MIT" ]
24
2019-09-04T23:12:07.000Z
2022-03-30T02:06:22.000Z
#include <rppi_filter_operations.h> #include <rppdefs.h> #include "rppi_validate.hpp" #ifdef HIP_COMPILE #include <hip/rpp_hip_common.hpp> #include "hip/hip_declarations.hpp" #elif defined(OCL_COMPILE) #include <cl/rpp_cl_common.hpp> #include "cl/cl_declarations.hpp" #endif //backend #include <stdio.h> #include <iostream> #include <fstream> #include <chrono> using namespace std::chrono; #include "cpu/host_filter_operations.hpp" /******************** box_filter ********************/ RppStatus rppi_box_filter_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { box_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { box_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_box_filter_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { box_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { box_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_box_filter_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { box_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { box_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_box_filter_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); box_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_box_filter_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); box_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_box_filter_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); box_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; } /******************** sobel_filter ********************/ RppStatus rppi_sobel_filter_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *sobelType, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); copy_param_uint(sobelType, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { sobel_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { sobel_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_sobel_filter_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *sobelType, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); copy_param_uint(sobelType, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { sobel_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { sobel_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_sobel_filter_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *sobelType, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); copy_param_uint(sobelType, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { sobel_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { sobel_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_sobel_filter_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *sobelType, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); sobel_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), sobelType, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_sobel_filter_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *sobelType, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); sobel_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), sobelType, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_sobel_filter_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *sobelType, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); sobel_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), sobelType, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; } /******************** median_filter ********************/ RppStatus rppi_median_filter_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { median_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { median_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_median_filter_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { median_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { median_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_median_filter_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { median_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { median_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_median_filter_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); median_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_median_filter_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); median_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_median_filter_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); median_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; } /******************** custom_convolution ********************/ /******************** non_max_suppression ********************/ RppStatus rppi_non_max_suppression_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { non_max_suppression_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { non_max_suppression_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_non_max_suppression_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { non_max_suppression_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { non_max_suppression_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_non_max_suppression_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { non_max_suppression_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { non_max_suppression_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_non_max_suppression_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); non_max_suppression_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_non_max_suppression_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); non_max_suppression_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_non_max_suppression_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); non_max_suppression_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; } /******************** gaussian_filter ********************/ RppStatus rppi_gaussian_filter_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32f *stdDev, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); copy_param_float(stdDev, rpp::deref(rppHandle), paramIndex++); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { gaussian_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { gaussian_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_gaussian_filter_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32f *stdDev, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); copy_param_float(stdDev, rpp::deref(rppHandle), paramIndex++); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { gaussian_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { gaussian_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_gaussian_filter_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32f *stdDev, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); copy_param_float(stdDev, rpp::deref(rppHandle), paramIndex++); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { gaussian_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { gaussian_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_gaussian_filter_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32f *stdDev, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); gaussian_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), stdDev, kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_gaussian_filter_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32f *stdDev, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); gaussian_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), stdDev, kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_gaussian_filter_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32f *stdDev, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); gaussian_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), stdDev, kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; } /******************** nonlinear_filter ********************/ RppStatus rppi_nonlinear_filter_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { median_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { median_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_nonlinear_filter_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { median_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { median_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_nonlinear_filter_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; Rpp32u paramIndex = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); copy_param_uint(kernelSize, rpp::deref(rppHandle), paramIndex++); #ifdef OCL_COMPILE { median_filter_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { median_filter_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_nonlinear_filter_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); median_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_nonlinear_filter_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); median_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_nonlinear_filter_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, Rpp32u *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); median_filter_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; } // ********************************** custom convolution *************************************** RppStatus rppi_custom_convolution_u8_pln1_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, RppPtr_t kernel, RppiSize *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 1, RPPI_CHN_PLANAR); #ifdef OCL_COMPILE { custom_convolution_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize[0], rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #elif defined(HIP_COMPILE) { custom_convolution_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize[0], rpp::deref(rppHandle), RPPI_CHN_PLANAR, 1); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_custom_convolution_u8_pln3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, RppPtr_t kernel, RppiSize *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PLANAR); #ifdef OCL_COMPILE { custom_convolution_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize[0], rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #elif defined(HIP_COMPILE) { custom_convolution_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize[0], rpp::deref(rppHandle), RPPI_CHN_PLANAR, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_custom_convolution_u8_pkd3_batchPD_gpu(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, RppPtr_t kernel, RppiSize *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_srcSize(srcSize, rpp::deref(rppHandle)); copy_srcMaxSize(maxSrcSize, rpp::deref(rppHandle)); copy_roi(roiPoints, rpp::deref(rppHandle)); get_srcBatchIndex(rpp::deref(rppHandle), 3, RPPI_CHN_PACKED); #ifdef OCL_COMPILE { custom_convolution_cl_batch(static_cast<cl_mem>(srcPtr), static_cast<cl_mem>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize[0], rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #elif defined(HIP_COMPILE) { custom_convolution_hip_batch(static_cast<Rpp8u*>(srcPtr), static_cast<Rpp8u*>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize[0], rpp::deref(rppHandle), RPPI_CHN_PACKED, 3); } #endif //BACKEND return RPP_SUCCESS; } RppStatus rppi_custom_convolution_u8_pln1_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, RppPtr_t kernel, RppiSize *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); custom_convolution_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 1); return RPP_SUCCESS; } RppStatus rppi_custom_convolution_u8_pln3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, RppPtr_t kernel, RppiSize *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); custom_convolution_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PLANAR, 3); return RPP_SUCCESS; } RppStatus rppi_custom_convolution_u8_pkd3_batchPD_host(RppPtr_t srcPtr, RppiSize *srcSize, RppiSize maxSrcSize, RppPtr_t dstPtr, RppPtr_t kernel, RppiSize *kernelSize, Rpp32u nbatchSize, rppHandle_t rppHandle) { RppiROI roiPoints; roiPoints.x = 0; roiPoints.y = 0; roiPoints.roiHeight = 0; roiPoints.roiWidth = 0; copy_host_roi(roiPoints, rpp::deref(rppHandle)); copy_host_maxSrcSize(maxSrcSize, rpp::deref(rppHandle)); custom_convolution_host_batch<Rpp8u>(static_cast<Rpp8u*>(srcPtr), srcSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.maxSrcSize, static_cast<Rpp8u*>(dstPtr), static_cast<Rpp32f*>(kernel), kernelSize, rpp::deref(rppHandle).GetInitHandle()->mem.mcpu.roiPoints, rpp::deref(rppHandle).GetBatchSize(), RPPI_CHN_PACKED, 3); return RPP_SUCCESS; }
37.816626
101
0.457749
b6440496a92b62f842701964c833da19c16803e3
906
cpp
C++
src/parser/transform/statement/transform_transaction.cpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-04-22T05:41:54.000Z
2021-04-22T05:41:54.000Z
src/parser/transform/statement/transform_transaction.cpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
null
null
null
src/parser/transform/statement/transform_transaction.cpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-12-12T10:24:57.000Z
2021-12-12T10:24:57.000Z
#include "guinsoodb/parser/statement/transaction_statement.hpp" #include "guinsoodb/parser/transformer.hpp" namespace guinsoodb { unique_ptr<TransactionStatement> Transformer::TransformTransaction(guinsoodb_libpgquery::PGNode *node) { auto stmt = reinterpret_cast<guinsoodb_libpgquery::PGTransactionStmt *>(node); D_ASSERT(stmt); switch (stmt->kind) { case guinsoodb_libpgquery::PG_TRANS_STMT_BEGIN: case guinsoodb_libpgquery::PG_TRANS_STMT_START: return make_unique<TransactionStatement>(TransactionType::BEGIN_TRANSACTION); case guinsoodb_libpgquery::PG_TRANS_STMT_COMMIT: return make_unique<TransactionStatement>(TransactionType::COMMIT); case guinsoodb_libpgquery::PG_TRANS_STMT_ROLLBACK: return make_unique<TransactionStatement>(TransactionType::ROLLBACK); default: throw NotImplementedException("Transaction type %d not implemented yet", stmt->kind); } } } // namespace guinsoodb
39.391304
104
0.825607
b6474bdf4746d833e16134adc8dfd774567d6580
4,735
cpp
C++
tools/extras/irstlm/src/doc.cpp
scscscscscsc/kaldi-trunk
aa9a8143e0fee12d85562ccc1d06e0e99f630029
[ "Apache-2.0" ]
4
2016-06-05T14:19:32.000Z
2016-06-07T09:21:10.000Z
tools/extras/irstlm/src/doc.cpp
MistSC/kaldi-trunk
aa9a8143e0fee12d85562ccc1d06e0e99f630029
[ "Apache-2.0" ]
null
null
null
tools/extras/irstlm/src/doc.cpp
MistSC/kaldi-trunk
aa9a8143e0fee12d85562ccc1d06e0e99f630029
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** IrstLM: IRST Language Model Toolkit, compile LM Copyright (C) 2006 Marcello Federico, ITC-irst Trento, Italy This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ******************************************************************************/ #include <math.h> #include <assert.h> #include "util.h" #include "mfstream.h" #include "mempool.h" #include "htable.h" #include "dictionary.h" #include "n_gram.h" #include "doc.h" using namespace std; doc::doc(dictionary* d,char* docfname) { dict=d; n=0; m=0; V=new int[dict->size()]; N=new int[dict->size()]; T=new int[dict->size()]; cd=-1; dfname=docfname; df=NULL; binary=false; }; doc::~doc() { delete [] V; delete [] N; delete [] T; } int doc::open() { df=new mfstream(dfname,ios::in); char header[100]; df->getline(header,100); if (sscanf(header,"DoC %d",&n) && n>0) binary=true; else if (sscanf(header,"%d",&n) && n>0) binary=false; else { exit_error(IRSTLM_ERROR_DATA, "doc::open() error: wrong header\n"); } cerr << "opening: " << n << (binary?" bin-":" txt-") << "docs\n"; cd=-1; return 1; } int doc::reset() { cd=-1; m=0; df->close(); delete df; open(); return 1; } int doc::read() { if (cd >=(n-1)) return 0; m=0; for (int i=0; i<dict->size(); i++) N[i]=0; if (binary) { df->read((char *)&m,sizeof(int)); df->read((char *)V,m * sizeof(int)); df->read((char *)T,m * sizeof(int)); for (int i=0; i<m; i++) { N[V[i]]=T[i]; } } else { int eod=dict->encode(dict->EoD()); int bod=dict->encode(dict->BoD()); ngram ng(dict); while((*df) >> ng) { if (ng.size>0) { if (*ng.wordp(1)==bod) { ng.size=0; continue; } if (*ng.wordp(1)==eod) { ng.size=0; break; } N[*ng.wordp(1)]++; if (N[*ng.wordp(1)]==1)V[m++]=*ng.wordp(1); } } } cd++; return 1; } int doc::savernd(char* fname,int num) { assert((df!=NULL) && (cd==-1)); srand(100); mfstream out(fname,ios::out); out << "DoC\n"; out.write((const char*) &n,sizeof(int)); cerr << "n=" << n << "\n"; //first select num random docs char taken[n]; int r; for (int i=0; i<n; i++) taken[i]=0; for (int d=0; d<num; d++) { while((r=(rand() % n)) && taken[r]) {}; cerr << "random document found " << r << "\n"; taken[r]++; reset(); for (int i=0; i<=r; i++) read(); out.write((const char *)&m,sizeof(int)); out.write((const char*) V,m * sizeof(int)); for (int i=0; i<m; i++) out.write((const char*) &N[V[i]],sizeof(int)); } //write the rest of files reset(); for (int d=0; d<n; d++) { read(); if (!taken[d]) { out.write((const char*)&m,sizeof(int)); out.write((const char*)V,m * sizeof(int)); for (int i=0; i<m; i++) out.write((const char*)&N[V[i]],sizeof(int)); } else { cerr << "do not save doc " << d << "\n"; } } //out.close(); reset(); return 1; } int doc::save(char* fname) { assert((df!=NULL) && (cd==-1)); mfstream out(fname,ios::out); out << "DoC "<< n << "\n"; for (int d=0; d<n; d++) { read(); out.write((const char*)&m,sizeof(int)); out.write((const char*)V,m * sizeof(int)); for (int i=0; i<m; i++) out.write((const char*)&N[V[i]],sizeof(int)); } //out.close(); reset(); return 1; } int doc::save(char* fname, int bsz) { assert((df!=NULL) && (cd==-1)); char name[100]; int i=0; while (cd < (n-1)) { // at least one document sprintf(name,"%s.%d",fname,++i); mfstream out(name,ios::out); int csz=(cd+bsz)<n?bsz:(n-cd-1); out << "DoC "<< csz << "\n"; for (int d=0; d<csz; d++) { read(); out.write((const char*)&m,sizeof(int)); out.write((const char*)V,m * sizeof(int)); for (int i=0; i<m; i++) out.write((const char*)&N[V[i]],sizeof(int)); } out.close(); } reset(); return 1; }
19.729167
79
0.530729
b64993be7464496ca9e61403286e83785c0c32b5
8,796
cpp
C++
source/variables/Variant.cpp
alijenabi/RelationBasedSoftware
f26f163d8d3e74e134a33512ae49fb24edb8b3b7
[ "MIT" ]
2
2021-08-06T19:40:34.000Z
2021-09-06T23:07:47.000Z
source/variables/Variant.cpp
alijenabi/RelationBasedSoftware
f26f163d8d3e74e134a33512ae49fb24edb8b3b7
[ "MIT" ]
null
null
null
source/variables/Variant.cpp
alijenabi/RelationBasedSoftware
f26f163d8d3e74e134a33512ae49fb24edb8b3b7
[ "MIT" ]
null
null
null
// // Variant.cpp // Relation-Based Simulator (RBS) // // Created by Ali Jenabidehkordi on 19.08.18. // Copyright © 2018 Ali Jenabidehkordi. All rights reserved. // #include "Variant.h" namespace rbs::variables { Variant::Variant() : p_id{ TypeID::None } , p_value{} { } Variant::Variant(const Variant &other) = default; Variant::Variant(Variant &&other) { p_id = std::move(other.p_id); p_value = std::move(other.p_value); } bool Variant::hasValue() const { return p_id != TypeID::None; } bool Variant::isEmpty() const { return p_id == TypeID::None; } void Variant::clear() { p_id = TypeID::None; } bool Variant::operator==(const Variant &other) const { if( p_id == other.p_id ) { switch (p_id) { case TypeID::None: return true; case TypeID::Vector1D: return std::get<space::Vector<1> >(p_value) == std::get<space::Vector<1> >(other.p_value); case TypeID::Vector2D: return std::get<space::Vector<2> >(p_value) == std::get<space::Vector<2> >(other.p_value); case TypeID::Vector3D: return std::get<space::Vector<3> >(p_value) == std::get<space::Vector<3> >(other.p_value); case TypeID::Point1D: return std::get<space::Point<1> >(p_value) == std::get<space::Point<1> >(other.p_value); case TypeID::Point2D: return std::get<space::Point<2> >(p_value) == std::get<space::Point<2> >(other.p_value); case TypeID::Point3D: return std::get<space::Point<3> >(p_value) == std::get<space::Point<3> >(other.p_value); case TypeID::Index1D: return std::get<space::Index<1> >(p_value) == std::get<space::Index<1> >(other.p_value); case TypeID::Index2D: return std::get<space::Index<2> >(p_value) == std::get<space::Index<2> >(other.p_value); case TypeID::Index3D: return std::get<space::Index<3> >(p_value) == std::get<space::Index<3> >(other.p_value); case TypeID::LongDouble: return std::get<long double>(p_value) == std::get<double>(other.p_value); case TypeID::Double: return std::get<double>(p_value) == std::get<double>(other.p_value); case TypeID::Float: return std::get<float>(p_value) == std::get<float>(other.p_value); case TypeID::UnsignedLongLong: return std::get<unsigned long long>(p_value) == std::get<unsigned long long>(other.p_value); case TypeID::UnsignedLong: return std::get<unsigned long>(p_value) == std::get<unsigned long>(other.p_value); case TypeID::UnsignedInt: return std::get<unsigned int>(p_value) == std::get<unsigned int>(other.p_value); case TypeID::UnsignedShort: return std::get<unsigned short>(p_value) == std::get<unsigned short>(other.p_value); case TypeID::UnsignedChar: return std::get<unsigned char>(p_value) == std::get<unsigned char>(other.p_value); case TypeID::LongLong: return std::get<long long>(p_value) == std::get<long long>(other.p_value); case TypeID::Long: return std::get<long>(p_value) == std::get<long>(other.p_value); case TypeID::Int: return std::get<int>(p_value) == std::get<int>(other.p_value); case TypeID::Short: return std::get<short>(p_value) == std::get<short>(other.p_value); case TypeID::Char: return std::get<char>(p_value) == std::get<char>(other.p_value); case TypeID::Bool: return std::get<bool>(p_value) == std::get<bool>(other.p_value); case TypeID::String: return std::get<std::string>(p_value) == std::get<std::string>(other.p_value); default: throw std::out_of_range("The type of the Variant is not recognized."); } } return false; } bool Variant::operator!=(const Variant &other) const { return !operator==(other); } variables::Variant::operator std::string() const { std::string ans = "Variant:{"; if(isEmpty()) { ans = ans + "empty"; } else { ans = ans + "type: " + type_to_string() + ", value: " + value_to_string(); } return ans + "}"; } std::string Variant::value_to_string() const { switch (p_id) { case TypeID::None: return "uninitialized"; case TypeID::Vector1D: return std::string(std::get<space::Vector<1> >(p_value)); case TypeID::Vector2D: return std::string(std::get<space::Vector<2> >(p_value)); case TypeID::Vector3D: return std::string(std::get<space::Vector<3> >(p_value)); case TypeID::Point1D: return std::string(std::get<space::Point<1> >(p_value)); case TypeID::Point2D: return std::string(std::get<space::Point<2> >(p_value)); case TypeID::Point3D: return std::string(std::get<space::Point<3> >(p_value)); case TypeID::Index1D: return std::string(std::get<space::Index<1> >(p_value)); case TypeID::Index2D: return std::string(std::get<space::Index<2> >(p_value)); case TypeID::Index3D: return std::string(std::get<space::Index<3> >(p_value)); case TypeID::LongDouble: return std::to_string(std::get<long double>(p_value)); case TypeID::Double: return std::to_string(std::get<double>(p_value)); case TypeID::Float: return std::to_string(std::get<float>(p_value)); case TypeID::UnsignedLongLong: return std::to_string(std::get<unsigned long long>(p_value)); case TypeID::UnsignedLong: return std::to_string(std::get<unsigned long>(p_value)); case TypeID::UnsignedInt: return std::to_string(std::get<unsigned int>(p_value)); case TypeID::UnsignedShort: return std::to_string(std::get<unsigned short>(p_value)); case TypeID::UnsignedChar: return std::to_string(std::get<unsigned char>(p_value)); case TypeID::LongLong: return std::to_string(std::get<long long>(p_value)); case TypeID::Long: return std::to_string(std::get<long>(p_value)); case TypeID::Int: return std::to_string(std::get<int>(p_value)); case TypeID::Short: return std::to_string(std::get<short>(p_value)); case TypeID::Char: return std::to_string(std::get<char>(p_value)); case TypeID::Bool: return std::to_string(std::get<bool>(p_value)); case TypeID::String: return std::get<std::string>(p_value); default: throw std::out_of_range("The type of the Variant is not recognized."); } } std::string Variant::type_to_string() const { switch (p_id) { case TypeID::None: return "none"; case TypeID::Vector1D: return "space::Vector<1>"; case TypeID::Vector2D: return "space::Vector<2>"; case TypeID::Vector3D: return "space::Vector<3>"; case TypeID::Point1D: return "space::Point<1>"; case TypeID::Point2D: return "space::Point<2>"; case TypeID::Point3D: return "space::Point<3>"; case TypeID::Index1D: return "space::Index<1>"; case TypeID::Index2D: return "space::Index<2>"; case TypeID::Index3D: return "space::Index<3>"; case TypeID::LongDouble: return "long double"; case TypeID::Double: return "double"; case TypeID::Float: return "float"; case TypeID::UnsignedLongLong: return "unsigned long long"; case TypeID::UnsignedLong: return "unsigned long"; case TypeID::UnsignedInt: return "unsigned int"; case TypeID::UnsignedShort: return "unsigned short"; case TypeID::UnsignedChar: return "unsigned char"; case TypeID::LongLong: return "long long"; case TypeID::Long: return "long"; case TypeID::Int: return "int"; case TypeID::Short: return "short"; case TypeID::Char: return "char"; case TypeID::Bool: return "bool"; case TypeID::String: return "std::string"; default: throw std::out_of_range("The type of the Variant is not recognized."); } } std::size_t Variant::index() const { return static_cast<std::size_t>(p_id) - 1; } void Variant::swap(Variant &other) { std::swap(p_id, other.p_id); std::swap(p_value, other.p_value); } Variant &Variant::operator =(Variant other) { swap(other); return *this; } std::ostream &operator <<(std::ostream &out, const Variant &variant) { return out << std::string(variant); } } // namespace rbs::variant
52.357143
135
0.593565
b649f164b0f698ac856b600e19c2c775a25ace8b
2,575
cpp
C++
imctrans/cpp/assets/tests/test_InlineMessage.cpp
paulosousadias/imctrans
cfa2a12ea577d9aa214c2bbb23f3561e8b50ee8f
[ "Apache-2.0" ]
null
null
null
imctrans/cpp/assets/tests/test_InlineMessage.cpp
paulosousadias/imctrans
cfa2a12ea577d9aa214c2bbb23f3561e8b50ee8f
[ "Apache-2.0" ]
1
2019-05-23T18:36:57.000Z
2019-05-23T18:58:32.000Z
imctrans/cpp/assets/tests/test_InlineMessage.cpp
paulosousadias/imctrans
cfa2a12ea577d9aa214c2bbb23f3561e8b50ee8f
[ "Apache-2.0" ]
6
2018-11-22T18:10:58.000Z
2020-06-26T16:55:35.000Z
//*************************************************************************** // Copyright 2017 OceanScan - Marine Systems & Technology, Lda. * //*************************************************************************** // Licensed under the Apache License, Version 2.0 (the "License"); * // you may not use this file except in compliance with the License. * // You may obtain a copy of the License at * // * // http://www.apache.org/licenses/LICENSE-2.0 * // * // Unless required by applicable law or agreed to in writing, software * // distributed under the License is distributed on an "AS IS" BASIS, * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * // See the License for the specific language governing permissions and * // limitations under the License. * //*************************************************************************** // Author: Ricardo Martins * //*************************************************************************** // IMC headers. #include <IMC/Base/InlineMessage.hpp> #include <IMC/Spec/EulerAngles.hpp> // Catch headers. #define CATCH_CONFIG_MAIN #include "catch.hpp" TEST_CASE("opsOnNull") { IMC::InlineMessage<IMC::EulerAngles> imsg; REQUIRE_THROWS_AS(imsg.get(), std::runtime_error); REQUIRE(imsg.getSerializationSize() == 2); } TEST_CASE("serializeNull") { uint8_t bfr[128]; IMC::InlineMessage<IMC::EulerAngles> imsg; REQUIRE(imsg.serialize(bfr) == 2); } TEST_CASE("equalOperatorBothNull") { IMC::InlineMessage<IMC::EulerAngles> a; IMC::InlineMessage<IMC::EulerAngles> b; REQUIRE(a == b); } TEST_CASE("equalOperatorOneNull") { IMC::EulerAngles msg; IMC::InlineMessage<IMC::EulerAngles> a; a.set(msg); IMC::InlineMessage<IMC::EulerAngles> b; REQUIRE(a != b); } TEST_CASE("getNull") { IMC::InlineMessage<IMC::EulerAngles> imsg; REQUIRE_THROWS(imsg.get()); } TEST_CASE("getId") { IMC::InlineMessage<IMC::EulerAngles> imsg; REQUIRE(imsg.getId() == IMC::Message::nullId()); IMC::EulerAngles msg; imsg.set(msg); REQUIRE(imsg.getId() == msg.getId()); } TEST_CASE("setByPointerCompareDereference") { IMC::InlineMessage<IMC::EulerAngles> imsg; IMC::EulerAngles msg; imsg.set(&msg); REQUIRE(*imsg == msg); }
32.1875
77
0.528155
b64a0ca2541b8c7a1eb67199fe1d100f536c2f4d
10,723
cpp
C++
ToolKit/ReportControl/XTPReportColumns.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
2
2018-03-30T06:40:08.000Z
2022-02-23T12:40:13.000Z
ToolKit/ReportControl/XTPReportColumns.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
null
null
null
ToolKit/ReportControl/XTPReportColumns.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
1
2020-08-11T05:48:02.000Z
2020-08-11T05:48:02.000Z
// XTPReportColumns.cpp : implementation of the CXTPReportColumns class. // // This file is a part of the XTREME REPORTCONTROL MFC class library. // (c)1998-2011 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Common/XTPPropExchange.h" #include "XTPReportControl.h" #include "XTPReportHeader.h" #include "XTPReportColumn.h" #include "XTPReportColumns.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CXTPReportColumns CXTPReportColumns::CXTPReportColumns(CXTPReportControl* pControl) : m_pControl(pControl) { m_pGroupsOrder = new CXTPReportColumnOrder(this); m_pSortOrder = new CXTPReportColumnOrder(this); m_pTreeColumn = NULL; } CXTPReportColumns::~CXTPReportColumns() { Clear(); if (m_pGroupsOrder) m_pGroupsOrder->InternalRelease(); if (m_pSortOrder) m_pSortOrder->InternalRelease(); } void CXTPReportColumns::Clear() { // array cleanup for (int nColumn = GetCount() - 1; nColumn >= 0; nColumn--) { CXTPReportColumn* pColumn = m_arrColumns.GetAt(nColumn); if (pColumn) pColumn->InternalRelease(); } m_arrColumns.RemoveAll(); m_pSortOrder->Clear(); m_pGroupsOrder->Clear(); // clear variables which could be references to those values if (m_pControl && (m_pControl->GetColumns() == this)) m_pControl->SetFocusedColumn(NULL); } int CXTPReportColumnOrder::GetCount() const { return (int) m_arrColumns.GetSize(); } void CXTPReportColumns::Add(CXTPReportColumn* pColumn) { pColumn->m_pColumns = this; m_arrColumns.Add(pColumn); GetReportHeader()->OnColumnsChanged(xtpReportColumnOrderChanged | xtpReportColumnAdded, pColumn); } CXTPReportHeader* CXTPReportColumns::GetReportHeader() const { return m_pControl->GetReportHeader(); } void CXTPReportColumns::Remove(CXTPReportColumn* pColumn) { m_pGroupsOrder->Remove(pColumn); m_pSortOrder->Remove(pColumn); int nIndex = IndexOf(pColumn); if (nIndex != -1) { m_arrColumns.RemoveAt(nIndex); pColumn->InternalRelease(); GetReportHeader()->OnColumnsChanged(xtpReportColumnOrderChanged | xtpReportColumnRemoved, pColumn); } } int CXTPReportColumns::IndexOf(const CXTPReportColumn* pColumn) const { // array cleanup for (int nColumn = GetCount() - 1; nColumn >= 0; nColumn--) { if (m_arrColumns.GetAt(nColumn) == pColumn) return nColumn; } return -1; } void CXTPReportColumns::ResetSortOrder() { m_pSortOrder->Clear(); } void CXTPReportColumns::SetSortColumn(CXTPReportColumn* pColumn, BOOL bIncreasing) { ResetSortOrder(); m_pSortOrder->Add(pColumn, bIncreasing); } int CXTPReportColumns::ChangeColumnOrder(int nNewOrder, int nItemIndex) { if (nNewOrder < 0 || nItemIndex < 0) return -1; CXTPReportColumn* pColumn = GetAt(nItemIndex); if (pColumn) { if (nNewOrder == nItemIndex) return nNewOrder; if (nNewOrder > nItemIndex) nNewOrder--; m_arrColumns.RemoveAt(nItemIndex); m_arrColumns.InsertAt(nNewOrder, pColumn); } return nNewOrder; } int CXTPReportColumns::GetVisibleColumnsCount() const { int nVisibleCount = 0; int nCount = GetCount(); for (int nColumn = 0; nColumn < nCount; nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); if (pColumn && pColumn->IsVisible()) nVisibleCount++; } return nVisibleCount; } void CXTPReportColumns::GetVisibleColumns(CXTPReportColumns& arrColumns) const { int nCount = GetCount(); for (int nColumn = 0; nColumn < nCount; nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); if (pColumn && pColumn->IsVisible()) { arrColumns.m_arrColumns.Add(pColumn); pColumn->InternalAddRef(); } } } CXTPReportColumn* CXTPReportColumns::Find(int nItemIndex) const { for (int nColumn = 0; nColumn < GetCount(); nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); if (pColumn->GetItemIndex() == nItemIndex) return pColumn; } return NULL; } CXTPReportColumn* CXTPReportColumns::Find(const CString& strInternalName) const { for (int nColumn = 0; nColumn < GetCount(); nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); if (pColumn->GetInternalName() == strInternalName) return pColumn; } return NULL; } void CXTPReportColumns::InsertSortColumn(CXTPReportColumn* pColumn) { if (m_pSortOrder->IndexOf(pColumn) == -1) m_pSortOrder->Add(pColumn); } CXTPReportColumn* CXTPReportColumns::GetVisibleAt(int nIndex) const { for (int nColumn = 0; nColumn < GetCount(); nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); if (!pColumn->IsVisible()) continue; if (nIndex == 0) return pColumn; nIndex--; } return NULL; } CXTPReportColumn* CXTPReportColumns::GetFirstVisibleColumn() const { for (int nColumn = 0; nColumn < GetCount(); nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); if (pColumn->IsVisible()) return pColumn; } return NULL; } CXTPReportColumn* CXTPReportColumns::GetLastVisibleColumn() const { for (int nColumn = GetCount() - 1; nColumn >= 0; nColumn--) { CXTPReportColumn* pColumn = GetAt(nColumn); if (pColumn->IsVisible()) return pColumn; } return NULL; } void CXTPReportColumns::DoPropExchange(CXTPPropExchange* pPX) { int nItemIndex; CString strInternalName; if (pPX->IsStoring()) { int nCount = GetCount(); CXTPPropExchangeEnumeratorPtr pEnumerator(pPX->GetEnumerator(_T("Column"))); POSITION pos = pEnumerator->GetPosition(nCount, FALSE); for (int nColumn = 0; nColumn < nCount; nColumn++) { CXTPReportColumn* pColumn = GetAt(nColumn); CXTPPropExchangeSection secColumn(pEnumerator->GetNext(pos)); nItemIndex = pColumn->GetItemIndex(); strInternalName = pColumn->GetInternalName(); PX_Int(&secColumn, _T("ItemIndex"), nItemIndex); PX_String(&secColumn, _T("InternalName"), strInternalName); pColumn->DoPropExchange(&secColumn); } } else { CXTPPropExchangeEnumeratorPtr pEnumerator(pPX->GetEnumerator(_T("Column"))); POSITION pos = pEnumerator->GetPosition(0, FALSE); CXTPReportColumn tmpColumn(0, _T(""), 0); int i = 0; while (pos) { CXTPPropExchangeSection secColumn(pEnumerator->GetNext(pos)); CXTPReportColumn* pColumn = NULL; PX_Int(&secColumn, _T("ItemIndex"), nItemIndex, -1); if (pPX->GetSchema() > _XTP_SCHEMA_110) { PX_String(&secColumn, _T("InternalName"), strInternalName); if (!strInternalName.IsEmpty()) { pColumn = Find(strInternalName); // column data is exists but column is not in the collection. if (!pColumn) { // just read data to skeep (to be safe for array serialization) tmpColumn.DoPropExchange(&secColumn); continue; } } } if (!pColumn) pColumn = Find(nItemIndex); if (!pColumn) AfxThrowArchiveException(CArchiveException::badIndex); pColumn->DoPropExchange(&secColumn); ChangeColumnOrder(i, IndexOf(pColumn)); i++; } } CXTPPropExchangeSection secGroupsOrder(pPX->GetSection(_T("GroupsOrder"))); m_pGroupsOrder->DoPropExchange(&secGroupsOrder); CXTPPropExchangeSection secSortOrder(pPX->GetSection(_T("SortOrder"))); m_pSortOrder->DoPropExchange(&secSortOrder); } ///////////////////////////////////////////////////////////////////////////// // CXTPReportColumnOrder CXTPReportColumnOrder::CXTPReportColumnOrder(CXTPReportColumns* pColumns) : m_pColumns(pColumns) { } CXTPReportColumn* CXTPReportColumnOrder::GetAt(int nIndex) { if (nIndex >= 0 && nIndex < GetCount()) return m_arrColumns.GetAt(nIndex); else return NULL; } int CXTPReportColumnOrder::InsertAt(int nIndex, CXTPReportColumn* pColumn) { if (nIndex < 0) return -1; if (nIndex >= GetCount()) nIndex = GetCount(); int nPrevIndex = IndexOf(pColumn); if (nPrevIndex != -1) { if (nPrevIndex == nIndex) return nIndex; if (nIndex > nPrevIndex) nIndex--; if (nIndex == nPrevIndex) return nIndex; // change order m_arrColumns.RemoveAt(nPrevIndex); } m_arrColumns.InsertAt(nIndex, pColumn); return nIndex; } int CXTPReportColumnOrder::Add(CXTPReportColumn* pColumn, BOOL bSortIncreasing) { pColumn->m_bSortIncreasing = bSortIncreasing; return (int) m_arrColumns.Add(pColumn); } int CXTPReportColumnOrder::Add(CXTPReportColumn* pColumn) { return (int) m_arrColumns.Add(pColumn); } void CXTPReportColumnOrder::Clear() { m_arrColumns.RemoveAll(); } int CXTPReportColumnOrder::IndexOf(const CXTPReportColumn* pColumn) { int nCount = GetCount(); for (int i = 0; i < nCount; i++) { if (GetAt(i) == pColumn) return i; } return -1; } void CXTPReportColumnOrder::RemoveAt(int nIndex) { if (nIndex >= 0 && nIndex < GetCount()) m_arrColumns.RemoveAt(nIndex); } void CXTPReportColumnOrder::Remove(CXTPReportColumn* pColumn) { int nCount = GetCount(); for (int i = 0; i < nCount; i++) { if (GetAt(i) == pColumn) { m_arrColumns.RemoveAt(i); break; } } } void CXTPReportColumnOrder::DoPropExchange(CXTPPropExchange* pPX) { if (pPX->IsStoring()) { int nCount = GetCount(); PX_Int(pPX, _T("Count"), nCount, 0); for (int i = 0; i < nCount; i++) { CXTPReportColumn* pColumn = GetAt(i); if (pColumn) { int nItemIndex = pColumn->GetItemIndex(); CString strInternalName = pColumn->GetInternalName(); CString strParamName; strParamName.Format(_T("Column%i"), i); PX_Int(pPX, strParamName, nItemIndex, 0); strParamName.Format(_T("InternalName%i"), i); PX_String(pPX, strParamName, strInternalName); } } } else { Clear(); int nCount = 0; PX_Int(pPX, _T("Count"), nCount, 0); for (int i = 0; i < nCount; i++) { int nItemIndex = 0; CString strParamName; strParamName.Format(_T("Column%i"), i); PX_Int(pPX, strParamName, nItemIndex, 0); CXTPReportColumn* pColumn = NULL; if (pPX->GetSchema() > _XTP_SCHEMA_110) { strParamName.Format(_T("InternalName%i"), i); CString strInternalName; PX_String(pPX, strParamName, strInternalName); if (!strInternalName.IsEmpty()) pColumn = m_pColumns->Find(strInternalName); } if (!pColumn) pColumn = m_pColumns->Find(nItemIndex); if (pColumn) Add(pColumn); } } }
22.246888
101
0.69654
b64aa8d9436b0552bbce48e8c47f37dbf5e429c0
1,248
cpp
C++
depth_breadth_search/leetcode_dfs/366_find_leaves_of_bianry_tree.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:19.000Z
2020-10-12T19:18:19.000Z
depth_breadth_search/leetcode_dfs/366_find_leaves_of_bianry_tree.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
null
null
null
depth_breadth_search/leetcode_dfs/366_find_leaves_of_bianry_tree.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:04.000Z
2020-10-12T19:18:04.000Z
// // 366_find_leaves_of_bianry_tree.cpp // leetcode_dfs // // Created by Hadley on 26.08.20. // Copyright © 2020 Hadley. All rights reserved. // #include <iostream> #include <fstream> #include <stdio.h> #include <algorithm> #include <iostream> #include <vector> #include <string> #include <unordered_map> #include <stack> #include <cstring> #include <queue> #include <functional> #include <numeric> #include <map> #include <filesystem> #include <dirent.h> using namespace std; //Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class Solution { public: int dfs(TreeNode* root){ if(!root)return 0; int l=dfs(root->left)+1; int r=dfs(root->right)+1; int index=max(l,r)-1; if(index>=res.size())res.push_back({}); res[index].push_back(root->val); return max(l,r); } vector<vector<int>> findLeaves(TreeNode* root) { dfs(root); return res; } private: vector<vector<int>>res; };
22.285714
91
0.634615
b64be8ad8172ca61b4bd07a4e0923083f1e615f6
601
cpp
C++
Game/Source/Entity.cpp
Paideieitor/PlatformerGame
e00602171807c694b0c5f4afac50157ce9cd23b1
[ "MIT" ]
null
null
null
Game/Source/Entity.cpp
Paideieitor/PlatformerGame
e00602171807c694b0c5f4afac50157ce9cd23b1
[ "MIT" ]
null
null
null
Game/Source/Entity.cpp
Paideieitor/PlatformerGame
e00602171807c694b0c5f4afac50157ce9cd23b1
[ "MIT" ]
null
null
null
#include "Collisions.h" #include "Entity.h" Entity::Entity(EntityType type, fPoint position, bool flip, Player* parent) { this->type = type; this->position = position; this->flip = flip; this->parent = parent; toDelete = false; toRemove = false; flip = false; } Entity::~Entity() { } bool Entity::Update(float dt) { return true; } void Entity::Collision(Collider* c1, Collider* c2) { } void Entity::UIEvent(Element* element, ElementData&) { } fPoint Entity::GetDrawPosition(iPoint size) { fPoint output = position; output.x -= size.x / 2; output.y -= size.y / 2; return output; }
14.309524
75
0.678869
b64e3db9d1c2e542b4b9ceda3ed50c6d1649a382
2,361
cpp
C++
app/src/main/cpp/XTexture.cpp
sk95120/Connrot
d19c878d99ae85eca3663c11897fc4de1772fbff
[ "Apache-2.0" ]
1
2021-11-30T04:52:16.000Z
2021-11-30T04:52:16.000Z
app/src/main/cpp/XTexture.cpp
ShiKe-And-His-Friends/Connrot
d19c878d99ae85eca3663c11897fc4de1772fbff
[ "Apache-2.0" ]
1
2019-08-27T01:34:46.000Z
2019-08-27T01:34:46.000Z
app/src/main/cpp/XTexture.cpp
sk95120/Connrot
d19c878d99ae85eca3663c11897fc4de1772fbff
[ "Apache-2.0" ]
1
2021-11-30T04:52:17.000Z
2021-11-30T04:52:17.000Z
// // Created by shike on 2/4/2020. // #include "XTexture.h" #include "XLog.h" #include "XEGL.h" #include "XShader.h" class CXTexture:public XTexture{ public: bool ifFirst; //FILE *fp; XShader sh; XTextureType type; std::mutex mux; virtual void Drop(){ if (CXTexture_DEBUG_LOG) { XLOGD("CXTexture Drop methods."); } mux.lock(); XEGL::Get()->Close(); sh.Close(); mux.unlock(); delete this; } virtual bool Init(void *win , XTextureType type){ if (CXTexture_DEBUG_LOG) { XLOGD("CXTexture Init methods. Type is %d" ,type); } mux.lock(); XEGL::Get()->Close(); sh.Close(); this->type = type; if (!win) { mux.unlock(); XLOGE("XTexture Init Failed win is null."); return false; } if (!XEGL::Get()->Init(win)) { mux.unlock(); XLOGE("XTexture Init Failed win init Fail."); return false; } sh.Init((XShaderType)type); mux.unlock(); if (CXTexture_DEBUG_LOG) { XLOGD("CXTexture Init success."); } return true; } virtual void Draw(unsigned char *data[] , int width , int height){ if (CXTexture_DEBUG_LOG) { XLOGD("CXTexture Draw methods. Data width is %d ,height is %d ,type is %d",width ,height ,type); } mux.lock(); sh.GetTexture(0 ,width ,height ,data[0]); // Y if (type == XTEXTURETYPE_YUV420P) { sh.GetTexture(1,width/2,height/2,data[1]); // U sh.GetTexture(2,width/2,height/2,data[2]); // V } else { sh.GetTexture(1 , width/2 , height/2 , data[1] , true); //UV } /*if (!ifFirst) { fp = fopen("/storage/emulated/0/1080test.yuv","wb+"); ifFirst = true; } fwrite(data[0],1,width * height,fp); fwrite(data[1],1,width * height / 4,fp); fwrite(data[2],1,width * height / 4,fp); fflush(fp); */ sh.Draw(); XEGL::Get()->Draw(); mux.unlock(); if (CXTexture_DEBUG_LOG) { XLOGD("CXTexture Draw success."); } } }; XTexture *XTexture::Create () { XLOGD("CXTexture Create."); return new CXTexture(); }
26.829545
108
0.505718
b650429032fe75db1fc85b1df81410db435fb48a
1,176
cpp
C++
Application/main.cpp
RamonPetri/DS3231
50bb67cb58f33a9962faa7c54fd6a59e9496074c
[ "BSD-2-Clause" ]
null
null
null
Application/main.cpp
RamonPetri/DS3231
50bb67cb58f33a9962faa7c54fd6a59e9496074c
[ "BSD-2-Clause" ]
null
null
null
Application/main.cpp
RamonPetri/DS3231
50bb67cb58f33a9962faa7c54fd6a59e9496074c
[ "BSD-2-Clause" ]
null
null
null
#include "DS3231.h" #include "tests.h" #include "Display.h" #include "user.h" int main( void ){ namespace target = hwlib::target; auto scl = target::pin_oc( target::pins::scl ); auto sda = target::pin_oc( target::pins::sda ); auto userStart = target::pin_in(target::pins::d50); auto userSetting = target::pin_in(target::pins::d52); auto userSave = target::pin_in(target::pins::d48); auto i2c_bus = hwlib::i2c_bus_bit_banged_scl_sda( scl, sda ); uint8_t rtcAddres = 0x68; uint8_t OledAddres = 0x3c; auto oled = hwlib::glcd_oled(i2c_bus, OledAddres); auto font = hwlib::font_default_8x8(); auto display = hwlib::terminal_from( oled, font ); unsigned char time[3]; unsigned char date[3]; //Tests TestClock(i2c_bus,rtcAddres,date,time); //TestClock.PrintTestResults(); DS3231 clock(i2c_bus,rtcAddres); Display dis(i2c_bus,rtcAddres,display,time,date); user Gui(i2c_bus, rtcAddres,userSave,userStart,userSetting,display); for(;;){ Gui.BeginSetting(); clock.get_Time(time); clock.get_Date(date); dis.Display_print_Date_Time(time,date,display); } }
34.588235
72
0.663265
b6551c3c68b0bc35a21af4fd16c77fa72cfc1c35
1,413
hpp
C++
src/snabl/bset.hpp
codr4life/snabl
b1c8a69e351243a3ae73d69754971d540c224733
[ "MIT" ]
22
2018-08-27T15:28:10.000Z
2022-02-13T08:18:00.000Z
src/snabl/bset.hpp
codr4life/snabl
b1c8a69e351243a3ae73d69754971d540c224733
[ "MIT" ]
3
2018-08-27T01:44:51.000Z
2020-06-28T20:07:42.000Z
src/snabl/bset.hpp
codr4life/snabl
b1c8a69e351243a3ae73d69754971d540c224733
[ "MIT" ]
2
2018-08-26T18:55:47.000Z
2018-09-29T01:04:36.000Z
#ifndef SNABL_BSET_HPP #define SNABL_BSET_HPP #include "snabl/cmp.hpp" #include "snabl/std.hpp" #include "snabl/types.hpp" namespace snabl { template <typename KeyT, typename ValT> struct BSet { using Vals = vector<ValT>; Vals vals; KeyT ValT::*key_ptr; BSet(KeyT ValT::*key_ptr): key_ptr(key_ptr) { } BSet(KeyT ValT::*key_ptr, const Vals &source): vals(source), key_ptr(key_ptr) { } I64 find(const KeyT &key, I64 min, ValT **found=nullptr) const { I64 max = vals.size(); while (min < max) { const I64 i = (max+min) / 2; const ValT &v(vals[i]); const KeyT &k = v.*key_ptr; switch (cmp(key, k)) { case Cmp::LT: max = i; break; case Cmp::EQ: if (found) { *found = const_cast<ValT *>(&v); } return i; case Cmp::GT: min = i+1; break; } } return min; } ValT *find(const KeyT &key) const { ValT *found(nullptr); find(key, 0, &found); return found; } template <typename...ArgsT> ValT *emplace(const KeyT &key, ArgsT &&...args) { ValT *found(nullptr); const I64 i(find(key, 0, &found)); if (found) { return nullptr; } return &*vals.emplace(vals.begin()+i, forward<ArgsT>(args)...); } void clear() { vals.clear(); } }; } #endif
22.428571
69
0.530078
b65aed50316ad423ff5b0889dbc0247d96bbee14
865
cpp
C++
src/lfilesaver/server/util/DefaultStatsProvider.cpp
yamadapc/filesaver
9665cb30615530fb4aeeb775efb92092c7a51eb1
[ "MIT" ]
28
2019-09-09T08:13:25.000Z
2022-02-09T06:20:31.000Z
src/lfilesaver/server/util/DefaultStatsProvider.cpp
yamadapc/filesaver
9665cb30615530fb4aeeb775efb92092c7a51eb1
[ "MIT" ]
2
2020-05-26T02:06:42.000Z
2021-04-08T08:16:03.000Z
src/lfilesaver/server/util/DefaultStatsProvider.cpp
yamadapc/filesaver
9665cb30615530fb4aeeb775efb92092c7a51eb1
[ "MIT" ]
1
2020-06-09T23:40:04.000Z
2020-06-09T23:40:04.000Z
// // Created by Pedro Tacla Yamada on 14/7/20. // #include "DefaultStatsProvider.h" namespace filesaver::server { static const double MILLISECONDS_IN_SECOND = 1000.; DefaultStatsProvider::DefaultStatsProvider (services::stats::ThroughputTracker* throughputTracker, services::FileSizeService* fileSizeService) : m_throughputTracker (throughputTracker), m_fileSizeService (fileSizeService) { } Stats DefaultStatsProvider::getStats () { auto totalFiles = m_fileSizeService->getTotalFiles (); auto millisecondsElapsed = m_throughputTracker->getElapsedMilliseconds (); double filesPerSecond = MILLISECONDS_IN_SECOND * (static_cast<double> (totalFiles) / static_cast<double> (millisecondsElapsed)); return {filesPerSecond, millisecondsElapsed, totalFiles}; } } // namespace filesaver::server
30.892857
112
0.738728
b65b8a8657c4a8f38124f9ad71297f1732e7f9ad
396
cpp
C++
source/ShaderAST/Expr/ExprModulo.cpp
Praetonus/ShaderWriter
1c5b3961e3e1b91cb7158406998519853a4add07
[ "MIT" ]
148
2018-10-11T16:51:37.000Z
2022-03-26T13:55:08.000Z
source/ShaderAST/Expr/ExprModulo.cpp
Praetonus/ShaderWriter
1c5b3961e3e1b91cb7158406998519853a4add07
[ "MIT" ]
30
2019-11-30T11:43:07.000Z
2022-01-25T21:09:47.000Z
source/ShaderAST/Expr/ExprModulo.cpp
Praetonus/ShaderWriter
1c5b3961e3e1b91cb7158406998519853a4add07
[ "MIT" ]
8
2020-04-17T13:18:30.000Z
2021-11-20T06:24:44.000Z
/* See LICENSE file in root folder */ #include "ShaderAST/Expr/ExprModulo.hpp" #include "ShaderAST/Expr/ExprVisitor.hpp" namespace ast::expr { Modulo::Modulo( type::TypePtr type , ExprPtr lhs , ExprPtr rhs ) : Binary{ std::move( type ) , std::move( lhs ) , std::move( rhs ) , Kind::eModulo } { } void Modulo::accept( VisitorPtr vis ) { vis->visitModuloExpr( this ); } }
15.84
41
0.643939
b65c5929e2e4a41de1bc85f2e30e137110bcc2d8
1,487
cpp
C++
cpp/app.cpp
yorung/dx12playground
760bbd9b3dedf26a4c00219628c58721a70d4446
[ "MIT" ]
2
2016-06-16T14:00:40.000Z
2020-04-26T12:11:34.000Z
cpp/app.cpp
yorung/dx12playground
760bbd9b3dedf26a4c00219628c58721a70d4446
[ "MIT" ]
null
null
null
cpp/app.cpp
yorung/dx12playground
760bbd9b3dedf26a4c00219628c58721a70d4446
[ "MIT" ]
null
null
null
#include "stdafx.h" App app; App::App() { } void App::Draw() { const IVec2 scrSize = systemMisc.GetScreenSize(); constexpr float f = 1000; constexpr float n = 1; const float aspect = (float)scrSize.x / scrSize.y; Mat proj = perspectiveLH(45.0f * (float)M_PI / 180.0f, aspect, n, f); matrixMan.Set(MatrixMan::PROJ, proj); rt.BeginRenderToThis(); triangle.Draw(); skyMan.Draw(); rsPostProcess.Apply(); deviceMan.SetRenderTarget(); afBindTextureToBindingPoint(rt.GetTexture(), 0); afDraw(PT_TRIANGLESTRIP, 4); fontMan.Render(); } void App::Init() { GoMyDir(); triangle.Create(); // skyMan.Create("yangjae_row.dds", "sky_photosphere"); skyMan.Create("yangjae.dds", "sky_photosphere"); // skyMan.Create("C:\\Program Files (x86)\\Microsoft DirectX SDK (August 2009)\\Samples\\Media\\Lobby\\LobbyCube.dds", "sky_cubemap"); fontMan.Init(); const IVec2 scrSize = systemMisc.GetScreenSize(); rt.Init(scrSize, AFF_R8G8B8A8_UNORM, AFF_D32_FLOAT_S8_UINT); SamplerType sampler = AFST_POINT_CLAMP; rsPostProcess.Create("vivid", 0, nullptr, BM_NONE, DSM_DISABLE, CM_DISABLE, 1, &sampler); } void App::Destroy() { deviceMan.Flush(); triangle.Destroy(); skyMan.Destroy(); fontMan.Destroy(); rsPostProcess.Destroy(); rt.Destroy(); } void App::Update() { matrixMan.Set(MatrixMan::VIEW, devCamera.CalcViewMatrix()); fps.Update(); fontMan.DrawString(Vec2(20, 40), 20, SPrintf("FPS: %f", fps.Get())); }
23.234375
135
0.677875
b65ddc6dec39b505392574d96c345095e856a9ef
6,408
cpp
C++
src/physics/operators/nonlinear_solid_operators.cpp
joshessman-llnl/serac
1365a8f9ca372f0c50008b4b8f5f718955e4b80c
[ "BSD-3-Clause" ]
null
null
null
src/physics/operators/nonlinear_solid_operators.cpp
joshessman-llnl/serac
1365a8f9ca372f0c50008b4b8f5f718955e4b80c
[ "BSD-3-Clause" ]
null
null
null
src/physics/operators/nonlinear_solid_operators.cpp
joshessman-llnl/serac
1365a8f9ca372f0c50008b4b8f5f718955e4b80c
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019, Lawrence Livermore National Security, LLC and // other Serac Project Developers. See the top-level LICENSE file for // details. // // SPDX-License-Identifier: (BSD-3-Clause) #include "physics/operators/nonlinear_solid_operators.hpp" #include "infrastructure/logger.hpp" #include "numerics/expr_template_ops.hpp" namespace serac { NonlinearSolidQuasiStaticOperator::NonlinearSolidQuasiStaticOperator(std::unique_ptr<mfem::ParNonlinearForm> H_form, const BoundaryConditionManager& bcs) : mfem::Operator(H_form->FESpace()->GetTrueVSize()), H_form_(std::move(H_form)), bcs_(bcs) { } // compute: y = H(x,p) void NonlinearSolidQuasiStaticOperator::Mult(const mfem::Vector& k, mfem::Vector& y) const { // Apply the nonlinear form H_form_->Mult(k, y); H_form_->Mult(k, y); y.SetSubVector(bcs_.allEssentialDofs(), 0.0); } // Compute the Jacobian from the nonlinear form mfem::Operator& NonlinearSolidQuasiStaticOperator::GetGradient(const mfem::Vector& x) const { auto& grad = dynamic_cast<mfem::HypreParMatrix&>(H_form_->GetGradient(x)); bcs_.eliminateAllEssentialDofsFromMatrix(grad); return grad; } // destructor NonlinearSolidQuasiStaticOperator::~NonlinearSolidQuasiStaticOperator() {} NonlinearSolidDynamicOperator::NonlinearSolidDynamicOperator(std::unique_ptr<mfem::ParNonlinearForm> H_form, std::unique_ptr<mfem::ParBilinearForm> S_form, std::unique_ptr<mfem::ParBilinearForm> M_form, const BoundaryConditionManager& bcs, EquationSolver& newton_solver, const serac::LinearSolverParameters& lin_params) : mfem::TimeDependentOperator(M_form->ParFESpace()->TrueVSize() * 2), M_form_(std::move(M_form)), S_form_(std::move(S_form)), H_form_(std::move(H_form)), newton_solver_(newton_solver), bcs_(bcs), lin_params_(lin_params), z_(height / 2) { // Assemble the mass matrix and eliminate the fixed DOFs M_mat_.reset(M_form_->ParallelAssemble()); bcs_.eliminateAllEssentialDofsFromMatrix(*M_mat_); M_inv_ = EquationSolver(H_form_->ParFESpace()->GetComm(), lin_params); auto M_prec = std::make_unique<mfem::HypreSmoother>(); M_inv_.linearSolver().iterative_mode = false; M_prec->SetType(mfem::HypreSmoother::Jacobi); M_inv_.SetPreconditioner(std::move(M_prec)); M_inv_.SetOperator(*M_mat_); // Construct the reduced system operator and initialize the newton solver with // it reduced_oper_ = std::make_unique<NonlinearSolidReducedSystemOperator>(*H_form_, *S_form_, *M_form_, bcs); newton_solver_.SetOperator(*reduced_oper_); } void NonlinearSolidDynamicOperator::Mult(const mfem::Vector& vx, mfem::Vector& dvx_dt) const { // Create views to the sub-vectors v, x of vx, and dv_dt, dx_dt of dvx_dt int sc = height / 2; mfem::Vector v(vx.GetData() + 0, sc); mfem::Vector x(vx.GetData() + sc, sc); mfem::Vector dv_dt(dvx_dt.GetData() + 0, sc); mfem::Vector dx_dt(dvx_dt.GetData() + sc, sc); z_ = *H_form_ * x; S_form_->TrueAddMult(v, z_); z_.SetSubVector(bcs_.allEssentialDofs(), 0.0); dv_dt = M_inv_ * -z_; dx_dt = v; } void NonlinearSolidDynamicOperator::ImplicitSolve(const double dt, const mfem::Vector& vx, mfem::Vector& dvx_dt) { int sc = height / 2; mfem::Vector v(vx.GetData() + 0, sc); mfem::Vector x(vx.GetData() + sc, sc); mfem::Vector dv_dt(dvx_dt.GetData() + 0, sc); mfem::Vector dx_dt(dvx_dt.GetData() + sc, sc); // By eliminating kx from the coupled system: // kv = -M^{-1}*[H(x + dt*kx) + S*(v + dt*kv)] // kx = v + dt*kv // we reduce it to a nonlinear equation for kv, represented by the // m_reduced_oper. This equation is solved with the m_newton_solver // object (using m_J_solver and m_J_prec internally). reduced_oper_->SetParameters(dt, &v, &x); mfem::Vector zero; // empty vector is interpreted as zero r.h.s. by NewtonSolver dv_dt = newton_solver_ * zero; SLIC_WARNING_IF(!newton_solver_.nonlinearSolver().GetConverged(), "Newton solver did not converge."); dx_dt = v + (dt * dv_dt); } // destructor NonlinearSolidDynamicOperator::~NonlinearSolidDynamicOperator() {} NonlinearSolidReducedSystemOperator::NonlinearSolidReducedSystemOperator(const mfem::ParNonlinearForm& H_form, const mfem::ParBilinearForm& S_form, mfem::ParBilinearForm& M_form, const BoundaryConditionManager& bcs) : mfem::Operator(M_form.ParFESpace()->TrueVSize()), M_form_(M_form), S_form_(S_form), H_form_(H_form), dt_(0.0), v_(nullptr), x_(nullptr), w_(height), z_(height), bcs_(bcs) { } void NonlinearSolidReducedSystemOperator::SetParameters(double dt, const mfem::Vector* v, const mfem::Vector* x) { dt_ = dt; v_ = v; x_ = x; } void NonlinearSolidReducedSystemOperator::Mult(const mfem::Vector& k, mfem::Vector& y) const { // compute: y = H(x + dt*(v + dt*k)) + M*k + S*(v + dt*k) w_ = *v_ + (dt_ * k); z_ = *x_ + (dt_ * w_); y = H_form_ * z_; M_form_.TrueAddMult(k, y); S_form_.TrueAddMult(w_, y); y.SetSubVector(bcs_.allEssentialDofs(), 0.0); } mfem::Operator& NonlinearSolidReducedSystemOperator::GetGradient(const mfem::Vector& k) const { // Form the gradient of the complete nonlinear operator auto localJ = std::unique_ptr<mfem::SparseMatrix>(Add(1.0, M_form_.SpMat(), dt_, S_form_.SpMat())); w_ = *v_ + (dt_ * k); z_ = *x_ + (dt_ * w_); // No boundary conditions imposed here localJ->Add(dt_ * dt_, H_form_.GetLocalGradient(z_)); jacobian_.reset(M_form_.ParallelAssemble(localJ.get())); // Eliminate the fixed boundary DOFs bcs_.eliminateAllEssentialDofsFromMatrix(*jacobian_); return *jacobian_; } NonlinearSolidReducedSystemOperator::~NonlinearSolidReducedSystemOperator() {} } // namespace serac
38.142857
116
0.637953
b662f049c445959516d9d4dbcce5744975b15c84
2,387
cpp
C++
Source/Editctrl/window.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
2
2022-02-11T11:59:44.000Z
2022-02-16T20:33:25.000Z
Source/Editctrl/window.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
null
null
null
Source/Editctrl/window.cpp
mice777/Insanity3D
49dc70130f786439fb0e4f91b75b6b686a134760
[ "Apache-2.0" ]
null
null
null
#include "all.h" #include "ectrl_i.h" void DrawLineColumn(int x, int y); //---------------------------- C_window::C_window(): scroll_x(0), scroll_y(0), overwrite(false), hwnd(NULL), redraw(true) { undo[0].Add(C_undo_element::MARK); } //---------------------------- void C_window::Activate(){ SetFocus(hwnd); } //---------------------------- bool C_window::Save(){ if(doc.unnamed){ //prompt for name char buf[257]; strcpy(buf, doc.title); OPENFILENAME of; memset(&of, 0, sizeof(of)); of.lStructSize = sizeof(of); //of.hwndOwner = hwnd_main; of.hInstance = ec->hi; of.lpstrFile = buf; of.nMaxFile = sizeof(buf)-1; of.lpstrFileTitle = buf; of.nMaxFileTitle = sizeof(buf)-1; of.lpstrInitialDir = NULL; of.Flags = OFN_OVERWRITEPROMPT; if(!GetSaveFileName(&of)) return false; doc.SetTitle(buf); doc.modified = true; doc.unnamed = false; } if(!doc.Write()) return false; //parse undo buffer and change all FILEMODIFY elements to NOP { for(int i=UNDO_BUFFER_ELEMENTS; i--; ){ if(undo[0].elements[i] && undo[0].elements[i]->id==C_undo_element::FILEMODIFY){ undo[0].elements[i]->id = C_undo_element::NOP; } } } SetWindowText(ec->hwnd, doc.title); return true; } //---------------------------- bool C_window::SetScrollPos(int x, int y, int undo_buff){ if(scroll_x!=x || scroll_y!=y){ //add position into undo buffer undo[undo_buff].Add(C_undo_element::SCROLL, scroll_x, scroll_y); scroll_x = x; scroll_y = y; doc.redraw = true; cursor.redraw = true; //setup scroll-bar SCROLLINFO si; si.cbSize = sizeof(si); si.fMask = SIF_RANGE | SIF_POS; si.nMin = 0; si.nMax = doc.linenum; si.nPos = scroll_y; SetScrollInfo(hwnd, SB_VERT, &si, true); return true; } return false; } //---------------------------- /* C_str C_window::ExtractFilename() const{ dword i = doc.title.Size(); while(i && doc.title[i-1]!='\\') --i; if(ec->read_only) return C_fstr("%s [read-only]", (const char*)doc.title + i); return &doc.title[i]; } */ //----------------------------
22.308411
91
0.51571
b6631e5fe03301e322585f6155b9d652a9c169a1
15,337
hpp
C++
pyoptsparse/pyNOMAD/source/nomad_src/utils.hpp
robfalck/pyoptsparse
c99f4bfe8961492d0a1879f9ecff7a2fbb3c8c1d
[ "CNRI-Python" ]
26
2020-08-25T16:16:21.000Z
2022-03-10T08:23:57.000Z
pyoptsparse/pyNOMAD/source/nomad_src/utils.hpp
robfalck/pyoptsparse
c99f4bfe8961492d0a1879f9ecff7a2fbb3c8c1d
[ "CNRI-Python" ]
90
2020-08-24T23:02:47.000Z
2022-03-29T13:48:15.000Z
pyoptsparse/pyNOMAD/source/nomad_src/utils.hpp
robfalck/pyoptsparse
c99f4bfe8961492d0a1879f9ecff7a2fbb3c8c1d
[ "CNRI-Python" ]
25
2020-08-24T19:28:24.000Z
2022-01-27T21:17:37.000Z
/*-------------------------------------------------------------------------------------*/ /* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ /* */ /* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ /* Charles Audet - Ecole Polytechnique, Montreal */ /* Gilles Couture - Ecole Polytechnique, Montreal */ /* John Dennis - Rice University, Houston */ /* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ /* Christophe Tribes - Ecole Polytechnique, Montreal */ /* */ /* funded in part by AFOSR and Exxon Mobil */ /* */ /* Author: Sebastien Le Digabel */ /* */ /* Contact information: */ /* Ecole Polytechnique de Montreal - GERAD */ /* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ /* e-mail: nomad@gerad.ca */ /* phone : 1-514-340-6053 #6928 */ /* fax : 1-514-340-5665 */ /* */ /* This program is free software: you can redistribute it and/or modify it under the */ /* terms of the GNU Lesser General Public License as published by the Free Software */ /* Foundation, either version 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License along */ /* with this program. If not, see <http://www.gnu.org/licenses/>. */ /* */ /* You can find information on the NOMAD software at www.gerad.ca/nomad */ /*-------------------------------------------------------------------------------------*/ /** \file utils.hpp \brief Utility functions (headers) \author Sebastien Le Digabel \date 2010-03-23 \see utils.cpp */ #ifndef __UTILS__ #define __UTILS__ #ifdef USE_MPI #include <mpi.h> #endif #include <cctype> #include <vector> #include <set> #include <list> #include <iomanip> #include <cmath> // use of 'access' or '_access', and getpid() or _getpid(): #ifdef _MSC_VER #include <io.h> #include <process.h> #else #include <unistd.h> #endif #include "defines.hpp" namespace NOMAD { /// Convert a string into a NOMAD::bb_input_type. /** \param s The string -- \b IN. \param bbit The NOMAD::bb_input_type -- \b OUT. \return A boolean equal to \c true if the conversion was possible. */ bool string_to_bb_input_type ( const std::string & s , NOMAD::bb_input_type & bbit ); /// Convert a string into a NOMAD::bb_output_type. /** \param s The string -- \b IN. \param bbot The NOMAD::bb_output_type -- \b OUT. \return A boolean equal to \c true if the conversion was possible. */ bool string_to_bb_output_type ( const std::string & s , NOMAD::bb_output_type & bbot ); /// Convert a string into a NOMAD::hnorm_type. /** \param s The string -- \b IN. \param hn The NOMAD::hnorm_type -- \b OUT. \return A boolean equal to \c true if the conversion was possible. */ bool string_to_hnorm_type ( const std::string & s , NOMAD::hnorm_type & hn ); /// Convert a string into a NOMAD::TGP_mode_type. /** \param s The string -- \b IN. \param m The NOMAD::TGP_mode_type -- \b OUT. \return A boolean equal to \c true if the conversion was possible. */ bool string_to_TGP_mode_type ( const std::string & s , NOMAD::TGP_mode_type & m ); /// Convert a string into a multi_formulation_type. /** \param s The string -- \b IN. \param mft The NOMAD::multi_formulation_type -- \b OUT. \return A boolean equal to \c true if the conversion was possible. */ bool string_to_multi_formulation_type ( const std::string & s , NOMAD::multi_formulation_type & mft ); /// Convert a string with format "i-j" into two integers i and j. /** If s=="*" and if n is defined, then i=0 and j=*n-1. \param s The string -- \b IN. \param i The first integer \c i -- \b OUT. \param j The second integer \c j -- \b OUT. \param n Number of variables; use \c NULL if unknown -- \b IN -- \b optional (default = \c NULL). \param check_order A boolean indicating if \c i and \c j are to be compared -- \b IN -- \b optional (default = \c true). \return A boolean equal to \c true if the conversion was possible. */ bool string_to_index_range ( const std::string & s , int & i , int & j , int * n = NULL , bool check_order = true ); /// Convert a string in {"QUADRATIC","TGP"} to a \c NOMAD::model_type. /** \param s The string -- \b IN. \param mt The NOMAD::model_type -- \b OUT. \return A boolean equal to \c true if the conversion was possible. */ bool string_to_model_type ( const std::string & s , NOMAD::model_type & mt ); /// Convert a string in {"YES","NO","Y","N","0","1","TRUE","FALSE"} to a boolean. /** \param s The string -- \b IN. \return An integer equal to \c 0 for \c false, \c 1 for \c true, and \c -1 if the conversion failed. */ int string_to_bool ( const std::string & s ); /// Interpret a list of strings as a direction type. /** \param ls The list of strings -- \b IN. \param dt The NOMAD::direction_type -- \b OUT. \return A boolean equal to \c true if the conversion was possible. */ bool strings_to_direction_type ( const std::list<std::string> & ls , NOMAD::direction_type & dt ); /// If a NOMAD::bb_output_type variable corresponds to a constraint. /** \param bbot The NOMAD::bb_output_type -- \b IN. \return A boolean equal to \c true if \c bbot corresponds to a constraint. */ bool bbot_is_constraint ( NOMAD::bb_output_type bbot ); /// If a NOMAD::direction_type variable corresponds to a MADS direction. /** \param dt The NOMAD::direction_type -- \b IN. \return A boolean equal to \c true if \c dt corresponds to a MADS direction. */ bool dir_is_mads ( NOMAD::direction_type dt ); /// If a NOMAD::direction_type variable corresponds to a GPS direction. /** \param dt The NOMAD::direction_type -- \b IN. \return A boolean equal to \c true if \c dt corresponds to a GPS direction. */ bool dir_is_gps ( NOMAD::direction_type dt ); /// If a NOMAD::direction_type variable corresponds to a LT-MADS direction. /** \param dt The NOMAD::direction_type -- \b IN. \return A boolean equal to \c true if \c dt corresponds to a LT-MADS direction. */ bool dir_is_ltmads ( NOMAD::direction_type dt ); /// If a NOMAD::direction_type variable corresponds to a random direction. /** \param dt The NOMAD::direction_type -- \b IN. \return A boolean equal to \c true if \c dt corresponds to a random direction. */ bool dir_is_random ( NOMAD::direction_type dt ); /// If a NOMAD::direction_type variable corresponds to a Ortho-MADS direction. /** \param dt The NOMAD::direction_type -- \b IN. \return A boolean equal to \c true if \c dt corresponds to a Ortho-MADS direction. */ bool dir_is_orthomads ( NOMAD::direction_type dt ); /// If a NOMAD::direction_type variable corresponds to a Ortho-MADS direction using XMesh. /** \param dt The NOMAD::direction_type -- \b IN. \return A boolean equal to \c true if \c dt corresponds to a Ortho-MADS direction using XMesh. */ bool dir_is_orthomads_xmesh ( NOMAD::direction_type dt ); /// Check if a set of directions include Ortho-MADS direction. /** \param dir_types Set of direction types -- \b IN. \return A boolean equal to \c true if at least one direction in the set is of type Ortho-MADS. */ bool dirs_have_orthomads ( const std::set<NOMAD::direction_type> & dir_types ); /// Check if a set of directions include Ortho-MADS direction using XMesh. /** \param dir_types Set of direction types -- \b IN. \return A boolean equal to \c true if at least one direction in the set is of type Ortho-MADS+XMesh. */ bool dirs_have_orthomads_xmesh ( const std::set<NOMAD::direction_type> & dir_types ); /// Check if a set of direction types include Ortho-MADS N+1 direction. /** \param dir_types Set of direction types -- \b IN. \return A boolean equal to \c true if at least one direction in the set is of type Ortho-MADS N+1. */ bool dirs_have_orthomads_np1 ( const std::set<NOMAD::direction_type> & dir_types ); /// Construct the n first prime numbers. /** \param n The integer \c n-- \b IN. \param primes An integer array of size \c n for the prime numbers; must be previously allocated -- \b OUT. */ void construct_primes ( int n , int * primes ); /// Decompose a string (sentence) into a list of strings (words). /** \param sentence The sentence -- \b IN. \param words The words -- \b OUT. */ void get_words ( const std::string & sentence , std::list<std::string> & words ); /// Check if a file exists and is executable. /** \param file_name A string corresponding to a file name -- \b IN. \return A boolean equal to \c true if the file is executable. */ bool check_exe_file ( const std::string & file_name ); /// Check if a file exists and is readable. /** \param file_name A string corresponding to a file name -- \b IN. \return A boolean equal to \c true if the file exists and is readable. */ bool check_read_file ( const std::string & file_name ); /// Get the process id (pid); useful for unique random seeds. /** \return An integer corresponding to the pid. */ int get_pid ( void ); /// Called at the beginning of NOMAD. /** \param argc Number of command line arguments. \param argv Command line arguments. */ void begin ( int argc , char ** argv ); /// Called at the end of NOMAD. void end ( void ); /// Transform an integer into a string. /** \param i The integer -- \b IN. \return The string. */ std::string itos ( int i ); /// Transform a unsigned long (size_t) into a string. /** \param i The unsigned long -- \b IN. \return The string. */ std::string itos ( size_t i ); /// Put a string into upper cases. /** \param s The string -- \b IN/OUT. */ void toupper ( std::string & s ); /// Put a list of strings into upper cases. /** \param ls The list of strings -- \b IN/OUT. */ void toupper ( std::list<std::string> & ls ); /// Convert a string into an integer. /** \param s The string -- \b IN. \param i The integer -- \b OUT. \return A boolean equal to \c true if the conversion was possible. */ bool atoi ( const std::string & s , int & i ); /// Convert a character into an integer. /** \param c The character -- \b IN. \param i The integer -- \b OUT. \return A boolean equal to \c true if the conversion was possible. */ bool atoi ( char c , int & i ); /// Search a list of string inside a string. /** \param s The string -- \b IN. \param ls The list of strings -- \b IN. \return A boolean equal to \c true if one of the string of ls is in s. */ bool string_find ( const std::string & s , const std::list<std::string> & ls ); /// Search a string into another string. /** \param s1 A string -- \b IN. \param s2 A string -- \b IN. \return A boolean equal to \c true if \c s2 is in \c s1. */ bool string_find ( const std::string & s1 , const std::string & s2 ); /// Search if a string matches an element in a list of string. /** \param s A string -- \b IN. \param ls A list of strings -- \b IN. \return A boolean equal to \c true if \c s matches an element in \c ls. */ bool string_match ( const std::string & s , const std::list<std::string> & ls ); /// SVD decomposition. /** - The \c mxn \c M matrix is decomposed into \c M=U.W.V'. \param error_msg Error message when the function returns \c false -- \b OUT. \param M The input \c mxn matrix; Will be replaced by \c U -- \b IN/OUT. \param W The output \c nxn diagonal matrix -- \b OUT. \param V The output \c nxn matrix -- \b OUT. \param m Number of rows in M -- \b IN. \param n Number of columns in M -- \b IN. \param max_mpn Maximum allowed value for \c m+n; ignored if \c <=0 -- \b IN -- \b optional (default = \c 1500). \return A boolean equal to \c true if the decomposition worked. */ bool SVD_decomposition ( std::string & error_msg , double ** M , double * W , double ** V , int m , int n , int max_mpn = 1500 ); // Get rank of a matrix using SVD decomposition /** - The \c mxn \c M matrix is decomposed into \c M=U.W.V'. The rank equals the size of W \param M The input \c mxn matrix -- \b IN. \param m Number of rows in M -- \b IN. \param n Number of columns in M -- \b IN. \return The rank>0 if the decomposition worked else 0. */ int get_rank(double **M, size_t m, size_t n); } #endif
39.528351
101
0.539936
b667ce76b759e26185617e0e079688bbd23bc02c
10,723
cpp
C++
test/systemtest/common/distributedpermission/distributed_permission_duid_transform_test/bundle_grant.cpp
openharmony-sig-ci/security_permission
50f01f7890efa8a967178b4b9553e86254854db9
[ "Apache-2.0" ]
null
null
null
test/systemtest/common/distributedpermission/distributed_permission_duid_transform_test/bundle_grant.cpp
openharmony-sig-ci/security_permission
50f01f7890efa8a967178b4b9553e86254854db9
[ "Apache-2.0" ]
null
null
null
test/systemtest/common/distributedpermission/distributed_permission_duid_transform_test/bundle_grant.cpp
openharmony-sig-ci/security_permission
50f01f7890efa8a967178b4b9553e86254854db9
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cstdio> #include <fstream> #include <sstream> #include <chrono> #include <gtest/gtest.h> #include <mutex> #include <iostream> #include <thread> #include "system_test_distributed_permission_util.h" #include "distributed_permission_kit.h" #include "bundle_info.h" #include "permission_definition.h" #include "parameter.h" #include "permission_kit.h" using namespace testing::ext; using namespace OHOS; using namespace OHOS::Security::Permission; using namespace OHOS::STPermissionUtil; using std::string; namespace { static const std::string permission_wifi = "ohos.permission.GET_WIFI_INFO"; static const std::string permission_network = "ohos.permission.GET_NETWORK_INFO"; static const std::string permission_location = "ohos.permission.LOCATION_IN_BACKGROUND"; static const std::string permission_camera = "ohos.permission.CAMERA"; static const std::string permission_microphone = "ohos.permission.MICROPHONE"; static const std::string permission_myself1 = "ohos.permission.MYPERMISSION_1"; static const std::string permission_myself2 = "ohos.permission.MYPERMISSION_2"; } // namespace class BundleGrant : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); void SetUp(); void TearDown(); }; void BundleGrant::SetUpTestCase(void) {} void BundleGrant::TearDownTestCase(void) {} void BundleGrant::SetUp(void) {} void BundleGrant::TearDown(void) {} /** * @tc.number : DPMS_BundleGrant_0100 * @tc.name : BundleGrant * @tc.desc : THIRD_INCLUDE_USE_BY_lOCAL_BUNDLE_NAME_ADD_V1 */ HWTEST_F(BundleGrant, DPMS_BundleGrant_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "BundleGrant DPMS_BundleGrant_0100 start"; STDistibutePermissionUtil::Install(THIRD_INCLUDE_USE_BY_lOCAL_HAP_NAME_ADD_V1); std::string bundleName = THIRD_INCLUDE_USE_BY_lOCAL_BUNDLE_NAME_ADD_V1; std::vector<OHOS::Security::Permission::PermissionDef> permDefList; // system grant OHOS::Security::Permission::PermissionDef permissionDef_network = {.permissionName = permission_network, .bundleName = bundleName, .grantMode = 1, .availableScope = 1 << 0, .label = "test label", .labelId = 9527, .description = "test description", .descriptionId = 9528}; OHOS::Security::Permission::PermissionDef permissionDef_wifi = {.permissionName = permission_wifi, .bundleName = bundleName, .grantMode = 1, .availableScope = 1 << 0, .label = "test label", .labelId = 9527, .description = "test description", .descriptionId = 9528}; OHOS::Security::Permission::PermissionDef permissionDef_location = {.permissionName = permission_location, .bundleName = bundleName, .grantMode = 1, .availableScope = 1 << 0, .label = "test label", .labelId = 9527, .description = "test description", .descriptionId = 9528}; // user grant OHOS::Security::Permission::PermissionDef permissionDef_camera = {.permissionName = permission_camera, .bundleName = bundleName, .grantMode = 0, .availableScope = 1 << 0, .label = "test label", .labelId = 9527, .description = "test description", .descriptionId = 9528}; OHOS::Security::Permission::PermissionDef permissionDef_microphone = {.permissionName = permission_microphone, .bundleName = bundleName, .grantMode = 0, .availableScope = 1 << 0, .label = "test label", .labelId = 9527, .description = "test description", .descriptionId = 9528}; // custom grant OHOS::Security::Permission::PermissionDef permissionDef_myself1 = {.permissionName = permission_myself1, .bundleName = bundleName, .grantMode = 1, .availableScope = 1 << 0, .label = "test label", .labelId = 9527, .description = "test description", .descriptionId = 9528}; OHOS::Security::Permission::PermissionDef permissionDef_myself2 = {.permissionName = permission_myself2, .bundleName = bundleName, .grantMode = 1, .availableScope = 1 << 0, .label = "test label", .labelId = 9527, .description = "test description", .descriptionId = 9528}; permDefList.emplace_back(permissionDef_network); permDefList.emplace_back(permissionDef_wifi); permDefList.emplace_back(permissionDef_location); permDefList.emplace_back(permissionDef_camera); permDefList.emplace_back(permissionDef_microphone); permDefList.emplace_back(permissionDef_myself1); permDefList.emplace_back(permissionDef_myself2); PermissionKit::AddDefPermissions(permDefList); // system grant std::vector<std::string> permList_system; permList_system.push_back(permission_network); permList_system.push_back(permission_wifi); permList_system.push_back(permission_location); permList_system.push_back(permission_myself1); permList_system.push_back(permission_myself2); PermissionKit::AddSystemGrantedReqPermissions(bundleName, permList_system); PermissionKit::GrantSystemGrantedPermission(bundleName, permission_network); PermissionKit::GrantSystemGrantedPermission(bundleName, permission_wifi); PermissionKit::GrantSystemGrantedPermission(bundleName, permission_location); PermissionKit::GrantSystemGrantedPermission(bundleName, permission_myself1); PermissionKit::GrantSystemGrantedPermission(bundleName, permission_myself2); // user grant std::vector<std::string> permList_user; permList_user.push_back(permission_camera); permList_user.push_back(permission_microphone); PermissionKit::AddUserGrantedReqPermissions(bundleName, permList_user, 0); PermissionKit::GrantUserGrantedPermission(bundleName, permission_camera, 0); GTEST_LOG_(INFO) << "BundleGrant DPMS_BundleGrant_0100 end"; } /** * @tc.number : DPMS_BundleGrant_0200 * @tc.name : BundleGrant * @tc.desc : SYSTEM_INCLUDE_USE_BY_lOCAL_HAP_NAME_ADD_V1 */ HWTEST_F(BundleGrant, DPMS_BundleGrant_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "BundleGrant DPMS_BundleGrant_0200 start"; std::string bundleName = SYSTEM_INCLUDE_USE_BY_lOCAL_BUNDLE_NAME_ADD_V1; std::vector<OHOS::Security::Permission::PermissionDef> permDefList; // system grant OHOS::Security::Permission::PermissionDef permissionDef_network = {.permissionName = permission_network, .bundleName = bundleName, .grantMode = 1, .availableScope = 1 << 0, .label = "test label", .labelId = 9527, .description = "test description", .descriptionId = 9528}; OHOS::Security::Permission::PermissionDef permissionDef_wifi = {.permissionName = permission_wifi, .bundleName = bundleName, .grantMode = 1, .availableScope = 1 << 0, .label = "test label", .labelId = 9527, .description = "test description", .descriptionId = 9528}; OHOS::Security::Permission::PermissionDef permissionDef_location = {.permissionName = permission_location, .bundleName = bundleName, .grantMode = 1, .availableScope = 1 << 0, .label = "test label", .labelId = 9527, .description = "test description", .descriptionId = 9528}; // user grant OHOS::Security::Permission::PermissionDef permissionDef_camera = {.permissionName = permission_camera, .bundleName = bundleName, .grantMode = 0, .availableScope = 1 << 0, .label = "test label", .labelId = 9527, .description = "test description", .descriptionId = 9528}; OHOS::Security::Permission::PermissionDef permissionDef_microphone = {.permissionName = permission_microphone, .bundleName = bundleName, .grantMode = 0, .availableScope = 1 << 0, .label = "test label", .labelId = 9527, .description = "test description", .descriptionId = 9528}; permDefList.emplace_back(permissionDef_network); permDefList.emplace_back(permissionDef_wifi); permDefList.emplace_back(permissionDef_location); permDefList.emplace_back(permissionDef_camera); permDefList.emplace_back(permissionDef_microphone); PermissionKit::AddDefPermissions(permDefList); // system grant std::vector<std::string> permList_system; permList_system.push_back(permission_network); permList_system.push_back(permission_wifi); permList_system.push_back(permission_location); PermissionKit::AddSystemGrantedReqPermissions(bundleName, permList_system); PermissionKit::GrantSystemGrantedPermission(bundleName, permission_network); PermissionKit::GrantSystemGrantedPermission(bundleName, permission_wifi); PermissionKit::GrantSystemGrantedPermission(bundleName, permission_location); // user grant std::vector<std::string> permList_user; permList_user.push_back(permission_camera); permList_user.push_back(permission_microphone); PermissionKit::AddUserGrantedReqPermissions(bundleName, permList_user, 0); PermissionKit::GrantUserGrantedPermission(bundleName, permission_camera, 0); GTEST_LOG_(INFO) << "BundleGrant DPMS_BundleGrant_0200 end"; } /** * @tc.number : DPMS_BundleGrant_0300 * @tc.name : BundleGrant * @tc.desc : THIRD_MORETHAN_MAXPERMISSION_HAP_NAME */ HWTEST_F(BundleGrant, DPMS_BundleGrant_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "BundleGrant DPMS_BundleGrant_0300 start"; STDistibutePermissionUtil::Install(THIRD_MORETHAN_MAXPERMISSION_HAP_NAME); GTEST_LOG_(INFO) << "BundleGrant DPMS_BundleGrant_0300 end"; } /** * @tc.number : DPMS_BundleGrant_0400 * @tc.name : BundleGrant * @tc.desc : THIRD_EQ_MAXPERMISSION_HAP_NAME */ HWTEST_F(BundleGrant, DPMS_BundleGrant_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "BundleGrant DPMS_BundleGrant_0400 start"; STDistibutePermissionUtil::Install(THIRD_EQ_MAXPERMISSION_HAP_NAME); GTEST_LOG_(INFO) << "BundleGrant DPMS_BundleGrant_0400 end"; }
40.617424
114
0.71687
b668260f577763c195ed675b033a0508f6143c98
2,095
hpp
C++
ODFAEG/include/odfaeg/Graphics/particleSystemUpdater.hpp
Mechap/ODFAEG
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
[ "Zlib" ]
null
null
null
ODFAEG/include/odfaeg/Graphics/particleSystemUpdater.hpp
Mechap/ODFAEG
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
[ "Zlib" ]
1
2020-02-14T14:19:44.000Z
2020-12-04T17:39:17.000Z
ODFAEG/include/odfaeg/Graphics/particleSystemUpdater.hpp
Mechap/ODFAEG
ad4bf026ee7055aaf168c5a8e3dc57baaaf42e40
[ "Zlib" ]
2
2021-05-23T13:45:28.000Z
2021-07-24T13:36:13.000Z
#ifndef ODFAEG_PARTICLES_UPDATER_HPP #define ODFAEG_PARTICLES_UPDATER_HPP #include "../Physics/particuleSystem.h" #include "../Graphics/world.h" #include "export.hpp" /** *\namespace odfaeg * the namespace of the Opensource Development Framework Adapted for Every Games. */ namespace odfaeg { namespace graphic { /** * \file entitiesUpdater.h * \class EntitiesUpdater * \brief update all the entities in the world which are in the current view with a thread. * \author Duroisin.L * \version 1.0 * \date 1/02/2014 */ class ODFAEG_CORE_API ParticleSystemUpdater : public core::EntitySystem { public : ParticleSystemUpdater() : EntitySystem() {} /** * \fn void onUpdate () * \brief update all the entities which are in the current view. */ void addParticleSystem(Entity* ps) { particleSystems.push_back(ps); } void removeParticleSystem (Entity* ps) { std::vector<Entity*>::iterator it; for (it = particleSystems.begin(); it != particleSystems.end();) { if (*it == ps) { it = particleSystems.erase(it); } else { it++; } } } std::vector<Entity*> getParticleSystems() { return particleSystems; } void onUpdate () { for (unsigned int i = 0; i < particleSystems.size(); i++) { //std::cout<<"update particle"<<std::endl; particleSystems[i]->update(); if (odfaeg::core::Application::app != nullptr) particleSystems[i]->update(odfaeg::core::Application::app->getClock("LoopTime").getElapsedTime()); } //World::changeVisibleEntity(nullptr, nullptr); } private : std::vector<Entity*> particleSystems; }; } } #endif
35.508475
122
0.521718
b6688abaa85db28771b30ef347123aa7d8eef7b2
589
cpp
C++
Chapter07/Source_Code/fifth.cpp
ngdzu/CPP-Reactive-Programming
e1a19feb40be086d47227587b8ed3d509b7518ca
[ "MIT" ]
98
2018-07-03T08:55:31.000Z
2022-03-21T22:16:58.000Z
Chapter07/Source_Code/fifth.cpp
ngdzu/CPP-Reactive-Programming
e1a19feb40be086d47227587b8ed3d509b7518ca
[ "MIT" ]
1
2020-11-30T10:38:58.000Z
2020-12-15T06:56:20.000Z
Chapter07/Source_Code/fifth.cpp
ngdzu/CPP-Reactive-Programming
e1a19feb40be086d47227587b8ed3d509b7518ca
[ "MIT" ]
54
2018-07-06T02:09:27.000Z
2021-11-10T08:42:50.000Z
#include "rxcpp/rx.hpp" #include "rxcpp/rx-test.hpp" #include <iostream> #include <array> int main() { auto values = rxcpp::observable<>::range(1); // infinite (until overflow) stream of integers auto s1 = values. take(3). map([](int prime) { return std::make_tuple("1:", prime);}); auto s2 = values. take(3). map([](int prime) { return std::make_tuple("2:", prime);}); s1. concat(s2). subscribe(rxcpp::util::apply_to( [](const char* s, int p) { printf("%s %d\n", s, p); })); }
19.633333
93
0.521222
b66acee2264e702e72c3a5d8f328a6aabaeff3be
1,780
hpp
C++
test/testutil/literals.hpp
soramitsu/kagome
d66755924477f2818fcae30ba2e65681fce34264
[ "Apache-2.0" ]
110
2019-04-03T13:39:39.000Z
2022-03-09T11:54:42.000Z
test/testutil/literals.hpp
soramitsu/kagome
d66755924477f2818fcae30ba2e65681fce34264
[ "Apache-2.0" ]
890
2019-03-22T21:33:30.000Z
2022-03-31T14:31:22.000Z
test/testutil/literals.hpp
soramitsu/kagome
d66755924477f2818fcae30ba2e65681fce34264
[ "Apache-2.0" ]
27
2019-06-25T06:21:47.000Z
2021-11-01T14:12:10.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef KAGOME_TEST_TESTUTIL_LITERALS_HPP_ #define KAGOME_TEST_TESTUTIL_LITERALS_HPP_ #include <libp2p/multi/multiaddress.hpp> #include <libp2p/multi/multihash.hpp> #include <libp2p/peer/peer_id.hpp> #include "common/blob.hpp" #include "common/buffer.hpp" #include "common/hexutil.hpp" using namespace kagome::common::literals; inline kagome::common::Hash256 operator"" _hash256(const char *c, size_t s) { kagome::common::Hash256 hash{}; std::copy_n(c, std::min(s, 32ul), hash.rbegin()); return hash; } inline std::vector<uint8_t> operator"" _v(const char *c, size_t s) { std::vector<uint8_t> chars(c, c + s); return chars; } inline std::vector<uint8_t> operator""_unhex(const char *c, size_t s) { if (s > 2 and c[0] == '0' and c[1] == 'x') return kagome::common::unhexWith0x(std::string_view(c, s)).value(); return kagome::common::unhex(std::string_view(c, s)).value(); } inline libp2p::multi::Multiaddress operator""_multiaddr(const char *c, size_t s) { return libp2p::multi::Multiaddress::create(std::string_view(c, s)).value(); } /// creates a multihash instance from a hex string inline libp2p::multi::Multihash operator""_multihash(const char *c, size_t s) { return libp2p::multi::Multihash::createFromHex(std::string_view(c, s)) .value(); } inline libp2p::peer::PeerId operator""_peerid(const char *c, size_t s) { // libp2p::crypto::PublicKey p; auto data = std::vector<uint8_t>(c, c + s); libp2p::crypto::ProtobufKey pb_key(std::move(data)); using libp2p::peer::PeerId; return PeerId::fromPublicKey(pb_key).value(); } #endif // KAGOME_TEST_TESTUTIL_LITERALS_HPP_
31.22807
79
0.688764
b66c3580439d08af4319f8072336ef728b6ec2b6
7,276
cpp
C++
gme/src/v20180711/model/CreateAppRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
gme/src/v20180711/model/CreateAppRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
gme/src/v20180711/model/CreateAppRequest.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/gme/v20180711/model/CreateAppRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Gme::V20180711::Model; using namespace std; CreateAppRequest::CreateAppRequest() : m_appNameHasBeenSet(false), m_projectIdHasBeenSet(false), m_engineListHasBeenSet(false), m_regionListHasBeenSet(false), m_realtimeSpeechConfHasBeenSet(false), m_voiceMessageConfHasBeenSet(false), m_voiceFilterConfHasBeenSet(false), m_tagsHasBeenSet(false) { } string CreateAppRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_appNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AppName"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_appName.c_str(), allocator).Move(), allocator); } if (m_projectIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ProjectId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_projectId, allocator); } if (m_engineListHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "EngineList"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_engineList.begin(); itr != m_engineList.end(); ++itr) { d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } if (m_regionListHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RegionList"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_regionList.begin(); itr != m_regionList.end(); ++itr) { d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } if (m_realtimeSpeechConfHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RealtimeSpeechConf"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_realtimeSpeechConf.ToJsonObject(d[key.c_str()], allocator); } if (m_voiceMessageConfHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "VoiceMessageConf"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_voiceMessageConf.ToJsonObject(d[key.c_str()], allocator); } if (m_voiceFilterConfHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "VoiceFilterConf"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_voiceFilterConf.ToJsonObject(d[key.c_str()], allocator); } if (m_tagsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Tags"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_tags.begin(); itr != m_tags.end(); ++itr, ++i) { d[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(d[key.c_str()][i], allocator); } } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string CreateAppRequest::GetAppName() const { return m_appName; } void CreateAppRequest::SetAppName(const string& _appName) { m_appName = _appName; m_appNameHasBeenSet = true; } bool CreateAppRequest::AppNameHasBeenSet() const { return m_appNameHasBeenSet; } uint64_t CreateAppRequest::GetProjectId() const { return m_projectId; } void CreateAppRequest::SetProjectId(const uint64_t& _projectId) { m_projectId = _projectId; m_projectIdHasBeenSet = true; } bool CreateAppRequest::ProjectIdHasBeenSet() const { return m_projectIdHasBeenSet; } vector<string> CreateAppRequest::GetEngineList() const { return m_engineList; } void CreateAppRequest::SetEngineList(const vector<string>& _engineList) { m_engineList = _engineList; m_engineListHasBeenSet = true; } bool CreateAppRequest::EngineListHasBeenSet() const { return m_engineListHasBeenSet; } vector<string> CreateAppRequest::GetRegionList() const { return m_regionList; } void CreateAppRequest::SetRegionList(const vector<string>& _regionList) { m_regionList = _regionList; m_regionListHasBeenSet = true; } bool CreateAppRequest::RegionListHasBeenSet() const { return m_regionListHasBeenSet; } RealtimeSpeechConf CreateAppRequest::GetRealtimeSpeechConf() const { return m_realtimeSpeechConf; } void CreateAppRequest::SetRealtimeSpeechConf(const RealtimeSpeechConf& _realtimeSpeechConf) { m_realtimeSpeechConf = _realtimeSpeechConf; m_realtimeSpeechConfHasBeenSet = true; } bool CreateAppRequest::RealtimeSpeechConfHasBeenSet() const { return m_realtimeSpeechConfHasBeenSet; } VoiceMessageConf CreateAppRequest::GetVoiceMessageConf() const { return m_voiceMessageConf; } void CreateAppRequest::SetVoiceMessageConf(const VoiceMessageConf& _voiceMessageConf) { m_voiceMessageConf = _voiceMessageConf; m_voiceMessageConfHasBeenSet = true; } bool CreateAppRequest::VoiceMessageConfHasBeenSet() const { return m_voiceMessageConfHasBeenSet; } VoiceFilterConf CreateAppRequest::GetVoiceFilterConf() const { return m_voiceFilterConf; } void CreateAppRequest::SetVoiceFilterConf(const VoiceFilterConf& _voiceFilterConf) { m_voiceFilterConf = _voiceFilterConf; m_voiceFilterConfHasBeenSet = true; } bool CreateAppRequest::VoiceFilterConfHasBeenSet() const { return m_voiceFilterConfHasBeenSet; } vector<Tag> CreateAppRequest::GetTags() const { return m_tags; } void CreateAppRequest::SetTags(const vector<Tag>& _tags) { m_tags = _tags; m_tagsHasBeenSet = true; } bool CreateAppRequest::TagsHasBeenSet() const { return m_tagsHasBeenSet; }
27.456604
104
0.708356
b66fd0f8780dc04af689585987afb0d94d5036cc
421
cpp
C++
docker/cytnx/src/utils/is.cpp
j9263178/Cytnx
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
[ "Apache-2.0" ]
11
2020-04-14T15:45:42.000Z
2022-03-31T14:37:03.000Z
docker/cytnx/src/utils/is.cpp
j9263178/Cytnx
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
[ "Apache-2.0" ]
38
2019-08-02T15:15:51.000Z
2022-03-04T19:07:02.000Z
docker/cytnx/src/utils/is.cpp
j9263178/Cytnx
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
[ "Apache-2.0" ]
7
2019-07-17T07:50:55.000Z
2021-07-03T06:44:52.000Z
#include "utils/is.hpp" namespace cytnx{ bool is(const Tensor &L, const Tensor &R){ return (L._impl == R._impl); } bool is(const Storage &L, const Storage &R){ return (L._impl == R._impl); } bool is(const Bond &L, const Bond &R){ return (L._impl == R._impl); } bool is(const Symmetry &L, const Symmetry &R){ return (L._impl == R._impl); } }
17.541667
50
0.534442
b6743871ee08c8b53fa206d97ec911fbcce81f84
307
cpp
C++
kmerInput/Statistic.cpp
Lw-Cui/kmer-exp
cc9df6339c6a07d63483e6a6dd8f2c13e9865b0e
[ "MIT" ]
null
null
null
kmerInput/Statistic.cpp
Lw-Cui/kmer-exp
cc9df6339c6a07d63483e6a6dd8f2c13e9865b0e
[ "MIT" ]
null
null
null
kmerInput/Statistic.cpp
Lw-Cui/kmer-exp
cc9df6339c6a07d63483e6a6dd8f2c13e9865b0e
[ "MIT" ]
null
null
null
#include <cstring> #include <map> #include <cstdio> using namespace std; int main() { map<int, int> count; int num; while (scanf("%*s%d", &num) != EOF) count[num]++; for (map<int, int>::iterator p = count.begin(); p != count.end(); p++) printf("%5d: %10d\n", p->first, p->second); return 0; }
18.058824
48
0.586319
b67541f04f69aeaa74a34629e928bf51df5a3ca3
273
hpp
C++
include/cpu/cpu.hpp
anthony-benavente/chip8emu
5ffe96ac252d15bfe0242fc6e1a550844510b31b
[ "MIT" ]
null
null
null
include/cpu/cpu.hpp
anthony-benavente/chip8emu
5ffe96ac252d15bfe0242fc6e1a550844510b31b
[ "MIT" ]
null
null
null
include/cpu/cpu.hpp
anthony-benavente/chip8emu
5ffe96ac252d15bfe0242fc6e1a550844510b31b
[ "MIT" ]
null
null
null
#ifndef CPU_H #define CPU_H #include "program/program.hpp" class Cpu { public: bool drawFlag; Cpu() : drawFlag(false) {} virtual void emulateCycle() = 0; virtual unsigned char getPixel(int x, int y) = 0; virtual void loadProgram(program_t *program) = 0; }; #endif
16.058824
50
0.703297
b679acd2c820753b72efd9f2494a17c0b9797a10
250
cpp
C++
Game/Client/WXClient/Network/PacketHandler/CGAskActiveTimeUpdateHandler.cpp
hackerlank/SourceCode
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
[ "MIT" ]
4
2021-07-31T13:56:01.000Z
2021-11-13T02:55:10.000Z
Game/Client/WXClient/Network/PacketHandler/CGAskActiveTimeUpdateHandler.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
null
null
null
Game/Client/WXClient/Network/PacketHandler/CGAskActiveTimeUpdateHandler.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
7
2021-08-31T14:34:23.000Z
2022-01-19T08:25:58.000Z
#include "StdAfx.h" #include "CGAskActiveTimeUpdate.h" uint CGAskActiveTimeUpdateHandler::Execute( CGAskActiveTimeUpdate* pPacket, Player* pPlayer ) { __ENTER_FUNCTION return PACKET_EXE_CONTINUE ; __LEAVE_FUNCTION return PACKET_EXE_ERROR ; }
17.857143
93
0.808
b67a171f12c52a9659fcb57e4c506286c0195d73
1,337
cpp
C++
Source/KPokemon_DX11/KSpriteEffect.cpp
jiwonchoidd/PokemonDP_DX11
828ef195c7c66b4c5489944e930acee96940c816
[ "BSD-2-Clause" ]
1
2022-03-25T08:55:53.000Z
2022-03-25T08:55:53.000Z
Source/KPokemon_DX11/KSpriteEffect.cpp
jiwonchoidd/PokemonDP_DX11
828ef195c7c66b4c5489944e930acee96940c816
[ "BSD-2-Clause" ]
null
null
null
Source/KPokemon_DX11/KSpriteEffect.cpp
jiwonchoidd/PokemonDP_DX11
828ef195c7c66b4c5489944e930acee96940c816
[ "BSD-2-Clause" ]
null
null
null
#include "KSpriteEffect.h" bool KSpriteEffect::Init(ID3D11DeviceContext* context, std::wstring vs, std::wstring ps, std::wstring tex, std::wstring mask) { m_pContext = context; m_Current_Index=0; m_Timer=0.0f; m_bEnd = false; m_Color = { 1,1,1,1 }; m_cbData.vLightDir = m_Color; K2DAsset::CreateObject_Mask(vs,ps,tex,mask); return true; } bool KSpriteEffect::Frame() { if (m_bEnd) { Reset(); return false; } else { m_Change_Time = m_pSprite->m_anim_time / m_pSprite->m_anim_array.size(); m_Timer += g_fSecPerFrame; if (m_Timer >= m_Change_Time) { m_Current_Index++; if (m_Current_Index >= m_pSprite->m_anim_array.size()) { m_Current_Index = 0; } m_Timer -= m_Change_Time; SetRectSource(m_pSprite->m_anim_array[m_Current_Index]); /*SetRectDraw({ 0,0, m_pSprite->m_anim_array[m_Current_Index].right, m_pSprite->m_anim_array[m_Current_Index].bottom });*/ AddPosition(KVector2(0, 0)); if (m_Current_Index == m_pSprite->m_anim_array.size()-1) { m_bEnd = true; } } m_cbData.vLightDir= m_Color; } return true; } bool KSpriteEffect::Render(ID3D11DeviceContext* pContext) { KObject::Render(pContext); return true; } bool KSpriteEffect::Release() { KObject::Release(); return true; } void KSpriteEffect::Reset() { m_Current_Index = 0; m_Timer = 0.0f; }
19.955224
125
0.694091
b67bd357593d19a2c531c0b73853cd0237def5e6
8,693
cpp
C++
geocoding/src/geocoding/RevGeocoder.cpp
farfromrefug/mobile-carto-libs
c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df
[ "BSD-3-Clause" ]
6
2018-06-27T17:43:35.000Z
2021-06-29T18:50:49.000Z
geocoding/src/geocoding/RevGeocoder.cpp
farfromrefug/mobile-carto-libs
c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df
[ "BSD-3-Clause" ]
22
2019-04-10T06:38:09.000Z
2022-01-20T08:12:02.000Z
geocoding/src/geocoding/RevGeocoder.cpp
farfromrefug/mobile-carto-libs
c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df
[ "BSD-3-Clause" ]
5
2019-03-12T10:25:20.000Z
2021-12-28T10:18:56.000Z
#include "RevGeocoder.h" #include "FeatureReader.h" #include "ProjUtils.h" #include "AddressInterpolator.h" #include <functional> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> #include <sqlite3pp.h> namespace carto { namespace geocoding { bool RevGeocoder::import(const std::shared_ptr<sqlite3pp::database>& db) { std::lock_guard<std::recursive_mutex> lock(_mutex); Database database; database.id = "db" + std::to_string(_databases.size()); database.db = db; database.bounds = getBounds(*db); database.origin = getOrigin(*db); _databases.push_back(database); return true; } std::string RevGeocoder::getLanguage() const { std::lock_guard<std::recursive_mutex> lock(_mutex); return _language; } void RevGeocoder::setLanguage(const std::string& language) { std::lock_guard<std::recursive_mutex> lock(_mutex); _language = language; _addressCache.clear(); } unsigned int RevGeocoder::getMaxResults() const { std::lock_guard<std::recursive_mutex> lock(_mutex); return _maxResults; } void RevGeocoder::setMaxResults(unsigned int maxResults) { std::lock_guard<std::recursive_mutex> lock(_mutex); _maxResults = maxResults; } bool RevGeocoder::isFilterEnabled(Address::EntityType type) const { std::lock_guard<std::recursive_mutex> lock(_mutex); return std::find(_enabledFilters.begin(), _enabledFilters.end(), type) != _enabledFilters.end(); } void RevGeocoder::setFilterEnabled(Address::EntityType type, bool enabled) { std::lock_guard<std::recursive_mutex> lock(_mutex); auto it = std::find(_enabledFilters.begin(), _enabledFilters.end(), type); if (enabled && it == _enabledFilters.end()) { _enabledFilters.push_back(type); } else if (!enabled && it != _enabledFilters.end()) { _enabledFilters.erase(it); } } std::vector<std::pair<Address, float>> RevGeocoder::findAddresses(double lng, double lat, float radius) const { std::lock_guard<std::recursive_mutex> lock(_mutex); std::vector<std::pair<Address, float>> addresses; for (const Database& database : _databases) { if (database.bounds) { // TODO: -180/180 wrapping cglib::vec2<double> lngLatMeters = wgs84Meters({ lng, lat }); cglib::vec2<double> point = database.bounds->nearest_point({ lng, lat }); cglib::vec2<double> diff = point - cglib::vec2<double>(lng, lat); double dist = cglib::length(cglib::vec2<double>(diff(0) * lngLatMeters(0), diff(1) * lngLatMeters(1))); if (dist > radius) { continue; } } _previousEntityQueryCounter = _entityQueryCounter; QuadIndex index(std::bind(&RevGeocoder::findGeometryInfo, this, std::cref(database), std::placeholders::_1, std::placeholders::_2)); std::vector<QuadIndex::Result> results = index.findGeometries(lng, lat, radius); for (const QuadIndex::Result& result : results) { float rank = 1.0f - static_cast<float>(result.second) / radius; if (rank > 0) { Address address; std::string addrKey = database.id + std::string(1, 0) + std::to_string(result.first); if (!_addressCache.read(addrKey, address)) { address.loadFromDB(*database.db, result.first, _language, [&database](const cglib::vec2<double>& pos) { return database.origin + pos; }); _addressCache.put(addrKey, address); } addresses.emplace_back(address, rank); } } } std::sort(addresses.begin(), addresses.end(), [](const std::pair<Address, float>& addrRank1, const std::pair<Address, float>& addrRank2) { return addrRank1.second > addrRank2.second; }); if (addresses.size() > _maxResults) { addresses.erase(addresses.begin() + _maxResults, addresses.end()); } return addresses; } std::vector<QuadIndex::GeometryInfo> RevGeocoder::findGeometryInfo(const Database& database, const std::vector<std::uint64_t>& quadIndices, const PointConverter& converter) const { std::string sql = "SELECT id, features, housenumbers FROM entities WHERE quadindex in ("; for (std::size_t i = 0; i < quadIndices.size(); i++) { sql += (i > 0 ? "," : "") + std::to_string(quadIndices[i]); } sql += ")"; if (!_enabledFilters.empty()) { std::string values; for (const Address::EntityType type : _enabledFilters) { values += (values.empty() ? "" : ",") + std::to_string(static_cast<int>(type)); } sql += " AND (type IN (" + values + "))"; } std::vector<QuadIndex::GeometryInfo> geomInfos; std::string queryKey = database.id + std::string(1, 0) + sql; if (_queryCache.read(queryKey, geomInfos)) { return geomInfos; } sqlite3pp::query query(*database.db, sql.c_str()); for (auto qit = query.begin(); qit != query.end(); qit++) { auto entityId = qit->get<unsigned int>(0); EncodingStream featureStream(qit->get<const void*>(1), qit->column_bytes(1)); FeatureReader featureReader(featureStream, [&database, &converter](const cglib::vec2<double>& pos) { return converter(database.origin + pos); }); if (qit->get<const void*>(2)) { EncodingStream houseNumberStream(qit->get<const void*>(2), qit->column_bytes(2)); AddressInterpolator interpolator(houseNumberStream); std::vector<std::pair<std::uint64_t, std::vector<Feature>>> idFeatures = interpolator.readAddressesAndFeatures(featureReader); for (std::size_t i = 0; i < idFeatures.size(); i++) { std::uint64_t encodedId = (idFeatures[i].first ? static_cast<std::uint64_t>(i + 1) << 32 : 0) | entityId; std::vector<std::shared_ptr<Geometry>> geometries; for (const Feature& feature : idFeatures[i].second) { if (feature.getGeometry()) { geometries.push_back(feature.getGeometry()); } } geomInfos.emplace_back(encodedId, std::make_shared<MultiGeometry>(std::move(geometries))); } } else { std::vector<std::shared_ptr<Geometry>> geometries; for (const Feature& feature : featureReader.readFeatureCollection()) { if (feature.getGeometry()) { geometries.push_back(feature.getGeometry()); } } geomInfos.emplace_back(entityId, std::make_shared<MultiGeometry>(std::move(geometries))); } } _entityQueryCounter++; _queryCache.put(queryKey, geomInfos); return geomInfos; } cglib::vec2<double> RevGeocoder::getOrigin(sqlite3pp::database& db) { sqlite3pp::query query(db, "SELECT value FROM metadata WHERE name='origin'"); for (auto qit = query.begin(); qit != query.end(); qit++) { std::string value = qit->get<const char*>(0); std::vector<std::string> origin; boost::split(origin, value, boost::is_any_of(","), boost::token_compress_off); return cglib::vec2<double>(std::stod(origin.at(0)), std::stod(origin.at(1))); } return cglib::vec2<double>(0, 0); } std::optional<cglib::bbox2<double>> RevGeocoder::getBounds(sqlite3pp::database& db) { sqlite3pp::query query(db, "SELECT value FROM metadata WHERE name='bounds'"); for (auto qit = query.begin(); qit != query.end(); qit++) { std::string value = qit->get<const char*>(0); std::vector<std::string> bounds; boost::split(bounds, value, boost::is_any_of(","), boost::token_compress_off); cglib::vec2<double> min(std::stod(bounds.at(0)), std::stod(bounds.at(1))); cglib::vec2<double> max(std::stod(bounds.at(2)), std::stod(bounds.at(3))); return cglib::bbox2<double>(min, max); } return std::optional<cglib::bbox2<double>>(); } } }
44.352041
184
0.579317
b67d83c5ba68070fd07f4d78be656de6227e3c02
1,291
cpp
C++
src/main/cpp/lemon/test/runner.cpp
lemonkit/lemon
ad34410586659fc650898b60d7e168797a3d9e5b
[ "MIT" ]
1
2018-01-12T05:13:58.000Z
2018-01-12T05:13:58.000Z
src/main/cpp/lemon/test/runner.cpp
lemonkit/lemon
ad34410586659fc650898b60d7e168797a3d9e5b
[ "MIT" ]
null
null
null
src/main/cpp/lemon/test/runner.cpp
lemonkit/lemon
ad34410586659fc650898b60d7e168797a3d9e5b
[ "MIT" ]
null
null
null
#include <iostream> #include <lemon/log/log.hpp> #include <lemon/test/unit.hpp> #include <lemon/test/macro.hpp> #include <lemon/test/runner.hpp> namespace lemon {namespace test{ runner& runner::instance() { static runner global; return global; } void runner::run() { runner::instance().done(); } void runner::done() { auto & logger = log::get("test"); for(auto unit : _units) { try { unit->run(); lemonI(logger,"test(%s) ... ok",unit->name().c_str()); } catch(const assert & e) { lemonE(logger,"test(%s) -- failed\n\terr :%s\n\tfile :%s(%d)",unit->name().c_str(),e.what(),e.file().c_str(),e.lines()); } catch(const std::exception &e) { lemonE(logger,"test(%s) -- failed\n\terr :%s\n\tfile :%s(%d)",unit->name().c_str(),e.what(),unit->file().c_str(),unit->lines()); } catch(...) { lemonE(logger, "test(%s) -- failed\n\terr :unknown exception\n\tfile :%s(%d)", unit->name().c_str(), unit->file().c_str(), unit->lines()); } } } void runner::add(runnable *unit) { _units.push_back(unit); } }}
23.053571
144
0.490318
b67dade3529bdcf9a4f95aabe4a68bc55561f546
3,298
cpp
C++
src/CBrowserRenderer.cpp
colinw7/CBrowser
d6aaaf536aa2f2bab0575439b75cf83a6d033db9
[ "MIT" ]
1
2021-12-23T02:21:28.000Z
2021-12-23T02:21:28.000Z
src/CBrowserRenderer.cpp
colinw7/CBrowser
d6aaaf536aa2f2bab0575439b75cf83a6d033db9
[ "MIT" ]
null
null
null
src/CBrowserRenderer.cpp
colinw7/CBrowser
d6aaaf536aa2f2bab0575439b75cf83a6d033db9
[ "MIT" ]
2
2017-05-04T05:38:49.000Z
2019-04-01T13:23:55.000Z
#include <CBrowserRenderer.h> #include <CBrowserWindowWidget.h> #include <CQUtil.h> #include <CQPenUtil.h> #include <CQBrushUtil.h> #include <CQFontUtil.h> #include <CQImageUtil.h> #include <QPainter> CBrowserRenderer:: CBrowserRenderer(CBrowserWindowWidget *w) : w_(w), pixmap_(0), painter_(0) { pixmap_width_ = 0; pixmap_height_ = 0; } CBrowserRenderer:: ~CBrowserRenderer() { } void CBrowserRenderer:: startDoubleBuffer(int width, int height) { if (width != pixmap_width_ || height != pixmap_height_) { pixmap_width_ = width; pixmap_height_ = height; pixmap_ = new QPixmap(pixmap_width_, pixmap_height_); pixmap_->fill(Qt::black); } if (! painter_) painter_ = new QPainter; painter_->begin(pixmap_); } void CBrowserRenderer:: endDoubleBuffer() { painter_->end(); QPainter painter(w_); painter.drawPixmap(QPoint(0, 0), *pixmap_); } void CBrowserRenderer:: clear(const CRGBA &bg) { painter_->fillRect(QRect(0, 0, pixmap_width_, pixmap_height_), QBrush(CQUtil::rgbaToColor(bg))); } void CBrowserRenderer:: drawRectangle(const CIBBox2D &bbox, const CPen &pen) { painter_->setPen(CQPenUtil::toQPen(pen)); painter_->setBrush(Qt::NoBrush); painter_->drawRect(CQUtil::toQRect(bbox)); } void CBrowserRenderer:: fillRectangle(const CIBBox2D &bbox, const CBrush &brush) { painter_->fillRect(CQUtil::toQRect(bbox), CQBrushUtil::toQBrush(brush)); } void CBrowserRenderer:: fillPolygon(const std::vector<CIPoint2D> &points, const CBrush &brush) { std::vector<QPoint> qpoints; qpoints.resize(points.size()); for (std::size_t i = 0; i < points.size(); ++i) qpoints[i] = QPoint(points[i].x, points[i].y); painter_->setPen(QPen(Qt::NoPen)); painter_->setBrush(CQBrushUtil::toQBrush(brush)); painter_->drawPolygon(&qpoints[0], qpoints.size()); } void CBrowserRenderer:: drawCircle(const CIPoint2D &c, int r, const CPen &pen) { painter_->setPen(CQPenUtil::toQPen(pen)); painter_->setBrush(Qt::NoBrush); painter_->drawEllipse(QRect(c.x - r, c.y - r, 2*r, 2*r)); } void CBrowserRenderer:: fillCircle(const CIPoint2D &c, int r, const CBrush &brush) { painter_->setPen(Qt::NoPen); painter_->setBrush(CQBrushUtil::toQBrush(brush)); painter_->drawEllipse(QRect(c.x - r, c.y - r, 2*r, 2*r)); } void CBrowserRenderer:: drawLine(const CIPoint2D &p1, const CIPoint2D &p2, const CPen &pen) { painter_->setPen(CQPenUtil::toQPen(pen)); painter_->drawLine(CQUtil::toQPoint(p1), CQUtil::toQPoint(p2)); } void CBrowserRenderer:: drawText(const CIPoint2D &p, const std::string &str, const CPen &pen, const CFontPtr &font) { painter_->setPen (CQPenUtil::toQPen(pen)); painter_->setFont(CQFontUtil::toQFont(font)); QPoint qp = CQUtil::toQPoint(p); if (font->isSubscript()) qp.setY(qp.y() + font->getCharAscent()/2); else if (font->isSuperscript()) qp.setY(qp.y() - font->getCharAscent()/2); painter_->drawText(qp, str.c_str()); } void CBrowserRenderer:: drawImage(const CIPoint2D &p, const CImagePtr &image) { drawImage(p, CQImageUtil::toQImage(image)); } void CBrowserRenderer:: drawImage(const CIPoint2D &p, const QImage &image) { if (painter_) painter_->drawImage(CQUtil::toQPoint(p), image); } void CBrowserRenderer:: setFont(CFontPtr font) { font_ = font; }
20.358025
91
0.700121
b67ea9453867e82b38a780ba2df51899ae01d5ea
10,108
hpp
C++
include/GlobalNamespace/BeatmapDataSO_-GetBeatmapDataAsync-d__2.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/BeatmapDataSO_-GetBeatmapDataAsync-d__2.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/BeatmapDataSO_-GetBeatmapDataAsync-d__2.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: BeatmapDataSO #include "GlobalNamespace/BeatmapDataSO.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: System.Runtime.CompilerServices.IAsyncStateMachine #include "System/Runtime/CompilerServices/IAsyncStateMachine.hpp" // Including type: System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1 #include "System/Runtime/CompilerServices/AsyncTaskMethodBuilder_1.hpp" // Including type: BeatmapDifficulty #include "GlobalNamespace/BeatmapDifficulty.hpp" // Including type: System.Runtime.CompilerServices.TaskAwaiter`1 #include "System/Runtime/CompilerServices/TaskAwaiter_1.hpp" // Including type: System.Runtime.CompilerServices.TaskAwaiter #include "System/Runtime/CompilerServices/TaskAwaiter.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: IReadonlyBeatmapData class IReadonlyBeatmapData; // Forward declaring type: EnvironmentInfoSO class EnvironmentInfoSO; // Forward declaring type: PlayerSpecificSettings class PlayerSpecificSettings; } // Forward declaring namespace: BeatmapSaveDataVersion3 namespace BeatmapSaveDataVersion3 { // Forward declaring type: BeatmapSaveData class BeatmapSaveData; } // Completed forward declares #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2, "", "BeatmapDataSO/<GetBeatmapDataAsync>d__2"); // Type namespace: namespace GlobalNamespace { // WARNING Size may be invalid! // Autogenerated type: BeatmapDataSO/<GetBeatmapDataAsync>d__2 // [TokenAttribute] Offset: FFFFFFFF // [CompilerGeneratedAttribute] Offset: FFFFFFFF struct BeatmapDataSO::$GetBeatmapDataAsync$d__2/*, public ::System::ValueType, public ::System::Runtime::CompilerServices::IAsyncStateMachine*/ { public: public: // public System.Int32 <>1__state // Size: 0x4 // Offset: 0x0 int $$1__state; // Field size check static_assert(sizeof(int) == 0x4); // public System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1<IReadonlyBeatmapData> <>t__builder // Size: 0xFFFFFFFF // Offset: 0x8 ::System::Runtime::CompilerServices::AsyncTaskMethodBuilder_1<::GlobalNamespace::IReadonlyBeatmapData*> $$t__builder; // public BeatmapDifficulty beatmapDifficulty // Size: 0x4 // Offset: 0x20 ::GlobalNamespace::BeatmapDifficulty beatmapDifficulty; // Field size check static_assert(sizeof(::GlobalNamespace::BeatmapDifficulty) == 0x4); // public System.Single beatsPerMinute // Size: 0x4 // Offset: 0x24 float beatsPerMinute; // Field size check static_assert(sizeof(float) == 0x4); // public System.Boolean loadingForDesignatedEnvironment // Size: 0x1 // Offset: 0x28 bool loadingForDesignatedEnvironment; // Field size check static_assert(sizeof(bool) == 0x1); // public EnvironmentInfoSO environmentInfo // Size: 0x8 // Offset: 0x30 ::GlobalNamespace::EnvironmentInfoSO* environmentInfo; // Field size check static_assert(sizeof(::GlobalNamespace::EnvironmentInfoSO*) == 0x8); // public PlayerSpecificSettings playerSpecificSettings // Size: 0x8 // Offset: 0x38 ::GlobalNamespace::PlayerSpecificSettings* playerSpecificSettings; // Field size check static_assert(sizeof(::GlobalNamespace::PlayerSpecificSettings*) == 0x8); // public BeatmapDataSO <>4__this // Size: 0x8 // Offset: 0x40 ::GlobalNamespace::BeatmapDataSO* $$4__this; // Field size check static_assert(sizeof(::GlobalNamespace::BeatmapDataSO*) == 0x8); // private BeatmapDataSO/<>c__DisplayClass2_0 <>8__1 // Size: 0x8 // Offset: 0x48 ::GlobalNamespace::BeatmapDataSO::$$c__DisplayClass2_0* $$8__1; // Field size check static_assert(sizeof(::GlobalNamespace::BeatmapDataSO::$$c__DisplayClass2_0*) == 0x8); // private System.Runtime.CompilerServices.TaskAwaiter`1<BeatmapSaveDataVersion3.BeatmapSaveData> <>u__1 // Size: 0xFFFFFFFF // Offset: 0x50 ::System::Runtime::CompilerServices::TaskAwaiter_1<::BeatmapSaveDataVersion3::BeatmapSaveData*> $$u__1; // private System.Runtime.CompilerServices.TaskAwaiter <>u__2 // Size: 0x8 // Offset: 0x58 ::System::Runtime::CompilerServices::TaskAwaiter $$u__2; // Field size check static_assert(sizeof(::System::Runtime::CompilerServices::TaskAwaiter) == 0x8); public: // Creating value type constructor for type: $GetBeatmapDataAsync$d__2 constexpr $GetBeatmapDataAsync$d__2(int $$1__state_ = {}, ::System::Runtime::CompilerServices::AsyncTaskMethodBuilder_1<::GlobalNamespace::IReadonlyBeatmapData*> $$t__builder_ = {}, ::GlobalNamespace::BeatmapDifficulty beatmapDifficulty_ = {}, float beatsPerMinute_ = {}, bool loadingForDesignatedEnvironment_ = {}, ::GlobalNamespace::EnvironmentInfoSO* environmentInfo_ = {}, ::GlobalNamespace::PlayerSpecificSettings* playerSpecificSettings_ = {}, ::GlobalNamespace::BeatmapDataSO* $$4__this_ = {}, ::GlobalNamespace::BeatmapDataSO::$$c__DisplayClass2_0* $$8__1_ = {}, ::System::Runtime::CompilerServices::TaskAwaiter_1<::BeatmapSaveDataVersion3::BeatmapSaveData*> $$u__1_ = {}, ::System::Runtime::CompilerServices::TaskAwaiter $$u__2_ = {}) noexcept : $$1__state{$$1__state_}, $$t__builder{$$t__builder_}, beatmapDifficulty{beatmapDifficulty_}, beatsPerMinute{beatsPerMinute_}, loadingForDesignatedEnvironment{loadingForDesignatedEnvironment_}, environmentInfo{environmentInfo_}, playerSpecificSettings{playerSpecificSettings_}, $$4__this{$$4__this_}, $$8__1{$$8__1_}, $$u__1{$$u__1_}, $$u__2{$$u__2_} {} // Creating interface conversion operator: operator ::System::ValueType operator ::System::ValueType() noexcept { return *reinterpret_cast<::System::ValueType*>(this); } // Creating interface conversion operator: operator ::System::Runtime::CompilerServices::IAsyncStateMachine operator ::System::Runtime::CompilerServices::IAsyncStateMachine() noexcept { return *reinterpret_cast<::System::Runtime::CompilerServices::IAsyncStateMachine*>(this); } // Get instance field reference: public System.Int32 <>1__state int& dyn_$$1__state(); // Get instance field reference: public System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1<IReadonlyBeatmapData> <>t__builder ::System::Runtime::CompilerServices::AsyncTaskMethodBuilder_1<::GlobalNamespace::IReadonlyBeatmapData*>& dyn_$$t__builder(); // Get instance field reference: public BeatmapDifficulty beatmapDifficulty ::GlobalNamespace::BeatmapDifficulty& dyn_beatmapDifficulty(); // Get instance field reference: public System.Single beatsPerMinute float& dyn_beatsPerMinute(); // Get instance field reference: public System.Boolean loadingForDesignatedEnvironment bool& dyn_loadingForDesignatedEnvironment(); // Get instance field reference: public EnvironmentInfoSO environmentInfo ::GlobalNamespace::EnvironmentInfoSO*& dyn_environmentInfo(); // Get instance field reference: public PlayerSpecificSettings playerSpecificSettings ::GlobalNamespace::PlayerSpecificSettings*& dyn_playerSpecificSettings(); // Get instance field reference: public BeatmapDataSO <>4__this ::GlobalNamespace::BeatmapDataSO*& dyn_$$4__this(); // Get instance field reference: private BeatmapDataSO/<>c__DisplayClass2_0 <>8__1 ::GlobalNamespace::BeatmapDataSO::$$c__DisplayClass2_0*& dyn_$$8__1(); // Get instance field reference: private System.Runtime.CompilerServices.TaskAwaiter`1<BeatmapSaveDataVersion3.BeatmapSaveData> <>u__1 ::System::Runtime::CompilerServices::TaskAwaiter_1<::BeatmapSaveDataVersion3::BeatmapSaveData*>& dyn_$$u__1(); // Get instance field reference: private System.Runtime.CompilerServices.TaskAwaiter <>u__2 ::System::Runtime::CompilerServices::TaskAwaiter& dyn_$$u__2(); // private System.Void MoveNext() // Offset: 0x136D500 void MoveNext(); // private System.Void SetStateMachine(System.Runtime.CompilerServices.IAsyncStateMachine stateMachine) // Offset: 0x136D868 void SetStateMachine(::System::Runtime::CompilerServices::IAsyncStateMachine* stateMachine); }; // BeatmapDataSO/<GetBeatmapDataAsync>d__2 // WARNING Not writing size check since size may be invalid! } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2::MoveNext // Il2CppName: MoveNext template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2::*)()>(&GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2::MoveNext)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2), "MoveNext", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2::SetStateMachine // Il2CppName: SetStateMachine template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2::*)(::System::Runtime::CompilerServices::IAsyncStateMachine*)>(&GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2::SetStateMachine)> { static const MethodInfo* get() { static auto* stateMachine = &::il2cpp_utils::GetClassFromName("System.Runtime.CompilerServices", "IAsyncStateMachine")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapDataSO::$GetBeatmapDataAsync$d__2), "SetStateMachine", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{stateMachine}); } };
58.767442
1,111
0.757618
b68060e67087fb74d7b0d88cd62ff5cce855465a
1,237
hpp
C++
src/graphics/TypeNames.hpp
Sam-Belliveau/MKS66-Graphics-Library
4ccf04f977a15007e32bdb5a238704eaaff0c895
[ "MIT" ]
null
null
null
src/graphics/TypeNames.hpp
Sam-Belliveau/MKS66-Graphics-Library
4ccf04f977a15007e32bdb5a238704eaaff0c895
[ "MIT" ]
null
null
null
src/graphics/TypeNames.hpp
Sam-Belliveau/MKS66-Graphics-Library
4ccf04f977a15007e32bdb5a238704eaaff0c895
[ "MIT" ]
null
null
null
#pragma once /** * Copyright (c) 2022 Sam Belliveau * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. */ #include <cstdint> namespace SPGL { /* Floats */ using Float80 = long double; using Float64 = double; using Float32 = float; using Float = Float64; using FloatMax = Float80; /* Integers */ using Size = std::size_t; using UIntMax = std::uintmax_t; using IntMax = std::intmax_t; using UInt64 = std::uint64_t; using Int64 = std::int64_t; using UInt32 = std::uint32_t; using Int32 = std::int32_t; using UInt16 = std::uint16_t; using Int16 = std::int16_t; using UInt8 = std::uint8_t; using Int8 = std::int8_t; }
26.891304
81
0.689572
b683049cc1444a2f3f1fc814d6788c56abee532f
32,602
cpp
C++
src/shape.cpp
yenyi/kicadPcb
f624156f59829554cb9fbf9b0438e7b84a42ee94
[ "BSD-3-Clause" ]
6
2020-02-08T07:29:42.000Z
2020-11-25T03:09:13.000Z
src/shape.cpp
yenyi/kicadPcb
f624156f59829554cb9fbf9b0438e7b84a42ee94
[ "BSD-3-Clause" ]
2
2019-12-23T17:19:41.000Z
2020-01-09T00:10:50.000Z
src/shape.cpp
yenyi/kicadPcb
f624156f59829554cb9fbf9b0438e7b84a42ee94
[ "BSD-3-Clause" ]
5
2020-10-16T23:59:42.000Z
2021-04-28T05:49:22.000Z
#include "shape.h" points_2d rotateShapeCoordsByAngles(const points_2d &shape, double instAngle, double padAngle) { auto cords = points_2d{}; auto rads = fmod((instAngle + padAngle) * -M_PI / 180, 2 * M_PI); auto s = sin(rads); auto c = cos(rads); for (auto &p : shape) { auto px = double(c * p.m_x - s * p.m_y); auto py = double(s * p.m_x + c * p.m_y); cords.push_back(point_2d{px, py}); } return cords; } points_2d roundrect_to_shape_coords(const point_2d &size, const double &ratio) { double legalRatio = 0.5; if (ratio < 0.5) { legalRatio = ratio; } auto cords = points_2d{}; auto width = size.m_x / 2; auto height = size.m_y / 2; auto radius = std::min(width, height) * legalRatio * 2; auto deltaWidth = width - radius; auto deltaHeight = height - radius; auto point = point_2d{}; for (int i = 0; i < 10; ++i) { //10 points point.m_x = deltaWidth + radius * cos(-9 * i * M_PI / 180); point.m_y = -deltaHeight + radius * sin(-9 * i * M_PI / 180); //std::cout << point.m_x << " " << point.m_y << std::endl; cords.push_back(point); } for (int i = 10; i < 20; ++i) { //10 points point.m_x = -deltaWidth + radius * cos(-9 * i * M_PI / 180); point.m_y = -deltaHeight + radius * sin(-9 * i * M_PI / 180); //std::cout << point.m_x << " " << point.m_y << std::endl; cords.push_back(point); } for (int i = 20; i < 30; ++i) { //10 points point.m_x = -deltaWidth + radius * cos(-9 * i * M_PI / 180); point.m_y = deltaHeight + radius * sin(-9 * i * M_PI / 180); //std::cout << point.m_x << " " << point.m_y << std::endl; cords.push_back(point); } for (int i = 30; i < 40; ++i) { //10 points point.m_x = deltaWidth + radius * cos(-9 * i * M_PI / 180); point.m_y = deltaHeight + radius * sin(-9 * i * M_PI / 180); //std::cout << point.m_x << " " << point.m_y << std::endl; cords.push_back(point); } point.m_x = deltaWidth + radius * cos(0 * M_PI / 180); point.m_y = -deltaHeight + radius * sin(0 * M_PI / 180); //std::cout << point.m_x << " " << point.m_y << std::endl; cords.push_back(point); return cords; } // Ongoing work // TODO: all coords must be in CW (follow the rules of Boost Polygon of Rings) // TODO: parameters for #points to Circle points_2d shape_to_coords(const point_2d &size, const point_2d &pos, const padShape shape, const double a1, const double a2, const double ratio, const int pointsPerCircle) { auto coords = points_2d{}; switch (shape) { case padShape::CIRCLE: { auto radius = size.m_x / 2; auto point = point_2d{}; double angleShift = 360.0 / (double)pointsPerCircle; for (int i = 0; i < pointsPerCircle; ++i) { point.m_x = pos.m_x + radius * cos(-angleShift * i * M_PI / 180); point.m_y = pos.m_y + radius * sin(-angleShift * i * M_PI / 180); coords.push_back(point); } // Closed the loop point.m_x = pos.m_x + radius * cos(0 * M_PI / 180); point.m_y = pos.m_y + radius * sin(0 * M_PI / 180); coords.push_back(point); break; } // case padShape::OVAL: // { // auto width = size.m_x / 2; // auto height = size.m_y / 2; // auto point = point_2d{}; // double angleShift = 360.0 / (double)pointsPerCircle; // for (int i = 0; i < pointsPerCircle; ++i) // { // point.m_x = pos.m_x + width * cos(-angleShift * i * M_PI / 180); // point.m_y = pos.m_y + height * sin(-angleShift * i * M_PI / 180); // coords.push_back(point); // } // // Closed the loop // point.m_x = pos.m_x + width * cos(0 * M_PI / 180); // point.m_y = pos.m_y + height * sin(0 * M_PI / 180); // coords.push_back(point); // break; // } case padShape::OVAL: case padShape::ROUNDRECT: { double legalRatio = 0.5; if (ratio < 0.5) { legalRatio = ratio; } if (shape == padShape::OVAL) { // OVAL is the roundrect with ratio = 0.5 legalRatio = 0.5; } auto width = size.m_x / 2; auto height = size.m_y / 2; auto radius = std::min(width, height) * legalRatio * 2; auto deltaWidth = width - radius; auto deltaHeight = height - radius; auto point = point_2d{}; int pointsPerCorner = pointsPerCircle / 4; double angleShift = 360.0 / (double)(pointsPerCorner * 4); for (int i = 0; i < pointsPerCorner; ++i) { point.m_x = pos.m_x + deltaWidth + radius * cos(-angleShift * i * M_PI / 180); point.m_y = pos.m_y - deltaHeight + radius * sin(-angleShift * i * M_PI / 180); coords.push_back(point); } for (int i = pointsPerCorner; i < 2 * pointsPerCorner; ++i) { point.m_x = pos.m_x - deltaWidth + radius * cos(-angleShift * i * M_PI / 180); point.m_y = pos.m_y - deltaHeight + radius * sin(-angleShift * i * M_PI / 180); coords.push_back(point); } for (int i = 2 * pointsPerCorner; i < 3 * pointsPerCorner; ++i) { point.m_x = pos.m_x - deltaWidth + radius * cos(-angleShift * i * M_PI / 180); point.m_y = pos.m_y + deltaHeight + radius * sin(-angleShift * i * M_PI / 180); coords.push_back(point); } for (int i = 3 * pointsPerCorner; i < 4 * pointsPerCorner; ++i) { point.m_x = pos.m_x + deltaWidth + radius * cos(-angleShift * i * M_PI / 180); point.m_y = pos.m_y + deltaHeight + radius * sin(-angleShift * i * M_PI / 180); coords.push_back(point); } // Closed the loop point.m_x = pos.m_x + deltaWidth + radius * cos(0 * M_PI / 180); point.m_y = pos.m_y - deltaHeight + radius * sin(0 * M_PI / 180); coords.push_back(point); break; } default: case padShape::TRAPEZOID: case padShape::RECT: { auto width = size.m_x / 2; auto height = size.m_y / 2; auto point = point_2d{}; point.m_x = pos.m_x + width; point.m_y = pos.m_y + height; coords.push_back(point); point.m_y = pos.m_y - height; coords.push_back(point); point.m_x = pos.m_x - width; coords.push_back(point); point.m_y = pos.m_y + height; coords.push_back(point); // Closed the loop point.m_x = pos.m_x + width; point.m_y = pos.m_y + height; coords.push_back(point); break; } } return rotateShapeCoordsByAngles(coords, a1, a2); } void printPolygon(const points_2d &coord) { std::cout << "Polygon("; for (size_t i = 0; i < coord.size(); ++i) { std::cout << coord[i]; if (i < coord.size() - 1) std::cout << ", "; } std::cout << ")" << std::endl; } void printPolygon(const polygon_t &poly) { std::cout << "Polygon("; for (auto it = boost::begin(bg::exterior_ring(poly)); it != boost::end(bg::exterior_ring(poly)); ++it) { auto x = bg::get<0>(*it); auto y = bg::get<1>(*it); //use the coordinates... std::cout << "(" << x << ", " << y << ")"; if (++it == boost::end(bg::exterior_ring(poly))) { break; } else { std::cout << ", "; } --it; } std::cout << ")" << std::endl; } void printPoint(point_2d &p) { std::cout << "Point({" << p.m_x << "," << p.m_y << "})" << std::endl; } void testShapeToCoords() { // points_2d circle32 = shape_to_coords(point_2d{10, 10}, point_2d{20, 20}, padShape::CIRCLE, 0, 0, 0, 32); // printPolygon(circle32); // points_2d circle48 = shape_to_coords(point_2d{10, 10}, point_2d{20, 20}, padShape::CIRCLE, 0, 0, 0, 48); // printPolygon(circle48); // points_2d oval32 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::OVAL, 0, 0, 0, 32); // printPolygon(oval32); // points_2d oval48 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::OVAL, 0, 0, 0, 48); // printPolygon(oval48); points_2d rr32 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.5, 32); printPolygon(rr32); points_2d rr48 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.5, 48); printPolygon(rr48); points_2d rr3208 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.8, 32); printPolygon(rr3208); points_2d rr4803 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.3, 48); printPolygon(rr4803); points_2d rr4003 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.3, 40); printPolygon(rr4003); points_2d rr4005 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.5, 40); printPolygon(rr4005); points_2d rr4008 = shape_to_coords(point_2d{16, 10}, point_2d{20, 20}, padShape::ROUNDRECT, 0, 0, 0.8, 40); printPolygon(rr4008); // points_2d rrr4008 = roundrect_to_shape_coords(point_2d{16, 10}, 0.8); // printPolygon(rrr4008); // points_2d rrr4005 = roundrect_to_shape_coords(point_2d{16, 10}, 0.5); // printPolygon(rrr4005); // points_2d rrr4003 = roundrect_to_shape_coords(point_2d{16, 10}, 0.3); // printPolygon(rrr4003); // points_2d rect = shape_to_coords(point_2d{10, 10}, point_2d{10, 5}, padShape::RECT, 0, 0, 0, 48); // printPolygon(rect); // points_2d trapezoid = shape_to_coords(point_2d{15, 15}, point_2d{-5, -10}, padShape::TRAPEZOID, 0, 0, 0, 48); // printPolygon(trapezoid); } ///////////////////////////////// // [1] [0] // |--------| // | s | // | | // |________| // [2] [3] ///////////////////////////////// points_2d segment_to_rect(const points_2d &point, const double &w) { auto cords = points_2d{}; auto p = point_2d{}; auto width = w / 2; //vertical if (point[0].m_x == point[1].m_x) { if (point[0].m_y > point[1].m_y) { p.m_x = point[0].m_x + width; p.m_y = point[0].m_y + width; cords.push_back(p); p.m_x = point[0].m_x - width; cords.push_back(p); p.m_x = point[0].m_x - width; p.m_y = point[0].m_y - width; cords.push_back(p); p.m_x = point[0].m_x - width; cords.push_back(p); } else { p.m_x = point[0].m_x + width; p.m_y = point[1].m_y + width; cords.push_back(p); p.m_x = point[0].m_x - width; cords.push_back(p); p.m_x = point[0].m_x - width; p.m_y = point[0].m_y - width; cords.push_back(p); p.m_x = point[0].m_x + width; cords.push_back(p); } } //horizontal else if (point[0].m_y == point[1].m_y) { if (point[0].m_x > point[1].m_x) { p.m_x = point[0].m_x + width; p.m_y = point[0].m_y + width; cords.push_back(p); p.m_x = point[1].m_x - width; cords.push_back(p); p.m_y = point[0].m_y - width; cords.push_back(p); p.m_x = point[0].m_x + width; cords.push_back(p); } else { p.m_x = point[1].m_x + width; p.m_y = point[0].m_y + width; cords.push_back(p); p.m_x = point[0].m_x - width; cords.push_back(p); p.m_y = point[0].m_y - width; cords.push_back(p); p.m_x = point[1].m_x + width; cords.push_back(p); } } //45degree else if ((point[0].m_x > point[1].m_x) && (point[0].m_y > point[1].m_y)) { p.m_x = point[0].m_x + sqrt(2) * width; p.m_y = point[0].m_y; cords.push_back(p); p.m_x = point[0].m_x; p.m_y = point[0].m_y + sqrt(2) * width; cords.push_back(p); p.m_x = point[1].m_x - sqrt(2) * width; p.m_y = point[1].m_y; cords.push_back(p); p.m_x = point[1].m_x; p.m_y = point[1].m_y + sqrt(2) * width; cords.push_back(p); } else if ((point[0].m_x < point[1].m_x) && (point[0].m_y < point[1].m_y)) { p.m_x = point[1].m_x + sqrt(2) * width; p.m_y = point[1].m_y; cords.push_back(p); p.m_x = point[1].m_x; p.m_y = point[1].m_y + sqrt(2) * width; cords.push_back(p); p.m_x = point[0].m_x - sqrt(2) * width; p.m_y = point[0].m_y; cords.push_back(p); p.m_x = point[0].m_x; p.m_y = point[0].m_y + sqrt(2) * width; cords.push_back(p); } //135degree else if ((point[1].m_x < point[0].m_x) && (point[1].m_y > point[0].m_y)) { p.m_x = point[1].m_x; p.m_y = point[1].m_y + sqrt(2) * width; cords.push_back(p); p.m_x = point[1].m_x - sqrt(2) * width; p.m_y = point[1].m_y; cords.push_back(p); p.m_x = point[0].m_x; p.m_y = point[0].m_y - sqrt(2) * width; cords.push_back(p); p.m_x = point[0].m_x + sqrt(2) * width; p.m_y = point[0].m_y; cords.push_back(p); } else if ((point[1].m_x > point[0].m_x) && (point[1].m_y < point[0].m_y)) { p.m_x = point[0].m_x; p.m_y = point[0].m_y + sqrt(2) * width; cords.push_back(p); p.m_x = point[0].m_x - sqrt(2) * width; p.m_y = point[0].m_y; cords.push_back(p); p.m_x = point[1].m_x; p.m_y = point[1].m_y - sqrt(2) * width; cords.push_back(p); p.m_x = point[1].m_x + sqrt(2) * width; p.m_y = point[1].m_y; cords.push_back(p); } return cords; } points_2d via_to_circle(const point_2d &pos, const double &size) { auto radius = size / 2; auto coords = points_2d{}; auto point = point_2d{}; for (int i = 0; i < 40; ++i) { //40 points point.m_x = pos.m_x + radius * cos(-9 * i * M_PI / 180); point.m_y = pos.m_y + radius * sin(-9 * i * M_PI / 180); coords.push_back(point); } point.m_x = pos.m_x + radius * cos(0 * M_PI / 180); point.m_y = pos.m_y + radius * sin(0 * M_PI / 180); coords.push_back(point); return coords; } points_2d viaToOctagon(const double &size, const point_2d &pos, const double &clearance) { auto _size = point_2d{size / 2, size / 2}; auto coords = points_2d{}; auto point = point_2d{}; double r = _size.m_x + clearance; //[0] point.m_x = pos.m_x + r * tan(22.5 * M_PI / 180); point.m_y = pos.m_y + r; coords.push_back(point); //[1] point.m_x = pos.m_x + r; point.m_y = pos.m_y + r * tan(22.5 * M_PI / 180); coords.push_back(point); //[2] point.m_x = pos.m_x + r; point.m_y = pos.m_y - r * tan(22.5 * M_PI / 180); coords.push_back(point); //[3] point.m_x = pos.m_x + r * tan(22.5 * M_PI / 180); point.m_y = pos.m_y - r; coords.push_back(point); //[4] point.m_x = pos.m_x - r * tan(22.5 * M_PI / 180); point.m_y = pos.m_y - r; coords.push_back(point); //[5] point.m_x = pos.m_x - r; point.m_y = pos.m_y - r * tan(22.5 * M_PI / 180); coords.push_back(point); //[6] point.m_x = pos.m_x - r; point.m_y = pos.m_y + r * tan(22.5 * M_PI / 180); coords.push_back(point); //[7] point.m_x = pos.m_x - r * tan(22.5 * M_PI / 180); point.m_y = pos.m_y + r; coords.push_back(point); return coords; } ///////////////////////////////// // [7] [0] // [6] /------\ [1] // | pin | // [5] \______/ [2] // [4] [3] ///////////////////////////////// //RELATIVE COORDS TO PIN!! points_2d pinShapeToOctagon(const point_2d &size, const point_2d &pos, const double &clearance, const double &instAngle, const double &pinAngle, padShape type) { auto coords = points_2d{}; auto point = point_2d{}; if (type == padShape::CIRCLE) { //[0] point.m_x = (size.m_x / 2 + clearance) * tan(22.5 * M_PI / 180); point.m_y = size.m_y / 2 + clearance; coords.push_back(point); //[1] point.m_x = size.m_x / 2 + clearance; point.m_y = (size.m_y / 2 + clearance) * tan(22.5 * M_PI / 180); coords.push_back(point); //[2] point.m_x = size.m_x / 2 + clearance; point.m_y = (-size.m_y / 2 - clearance) * tan(22.5 * M_PI / 180); coords.push_back(point); //[3] point.m_x = (size.m_x / 2 + clearance) * tan(22.5 * M_PI / 180); point.m_y = -size.m_y / 2 - clearance; coords.push_back(point); //[4] point.m_x = (-size.m_x / 2 - clearance) * tan(22.5 * M_PI / 180); point.m_y = -size.m_y / 2 - clearance; coords.push_back(point); //[5] point.m_x = -size.m_x / 2 - clearance; point.m_y = (-size.m_y / 2 - clearance) * tan(22.5 * M_PI / 180); coords.push_back(point); //[6] point.m_x = -size.m_x / 2 - clearance; point.m_y = (size.m_y / 2 + clearance) * tan(22.5 * M_PI / 180); coords.push_back(point); //[7] point.m_x = (-size.m_x / 2 - clearance) * tan(22.5 * M_PI / 180); point.m_y = size.m_y / 2 + clearance; coords.push_back(point); } else { //[0] point.m_x = size.m_x / 2 + (clearance * tan(22.5 * M_PI / 180)); point.m_y = size.m_y / 2 + clearance; coords.push_back(point); //[1] point.m_x = size.m_x / 2 + clearance; point.m_y = size.m_y / 2 + (clearance * tan(22.5 * M_PI / 180)); coords.push_back(point); //[2] point.m_x = size.m_x / 2 + clearance; point.m_y = -size.m_y / 2 - (clearance * tan(22.5 * M_PI / 180)); coords.push_back(point); //[3] point.m_x = size.m_x / 2 + (clearance * tan(22.5 * M_PI / 180)); point.m_y = -size.m_y / 2 - clearance; coords.push_back(point); //[4] point.m_x = -size.m_x / 2 - (clearance * tan(22.5 * M_PI / 180)); point.m_y = -size.m_y / 2 - clearance; coords.push_back(point); //[5] point.m_x = -size.m_x / 2 - clearance; point.m_y = -size.m_y / 2 - (clearance * tan(22.5 * M_PI / 180)); coords.push_back(point); //[6] point.m_x = -size.m_x / 2 - clearance; point.m_y = size.m_y / 2 + (clearance * tan(22.5 * M_PI / 180)); coords.push_back(point); //[7] point.m_x = -size.m_x / 2 - (clearance * tan(22.5 * M_PI / 180)); point.m_y = size.m_y / 2 + clearance; coords.push_back(point); } return rotateShapeCoordsByAngles(coords, instAngle, pinAngle); } points_2d segmentToOctagon(const points_2d &point, const double &w, const double &clearance) { auto cords = points_2d{}; auto p = point_2d{}; auto width = w / 2; //vertical if (point[0].m_x == point[1].m_x) { if (point[0].m_y > point[1].m_y) { p.m_x = point[0].m_x + width + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y + width + clearance; cords.push_back(p); p.m_x = point[0].m_x + width + clearance; p.m_y = point[0].m_y + width + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x + width + clearance; p.m_y = point[1].m_y - width - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x + width + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y - width - clearance; cords.push_back(p); p.m_x = point[1].m_x - width - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y - width - clearance; cords.push_back(p); p.m_x = point[1].m_x - width - clearance; p.m_y = point[1].m_y - width - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x - width - clearance; p.m_y = point[0].m_y + width + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x - width - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y + width + clearance; cords.push_back(p); } else { p.m_x = point[1].m_x + width + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y + width + clearance; cords.push_back(p); p.m_x = point[1].m_x + width + clearance; p.m_y = point[1].m_y + width + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x + width + clearance; p.m_y = point[0].m_y - width - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x + width + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y - width - clearance; cords.push_back(p); p.m_x = point[0].m_x - width - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y - width - clearance; cords.push_back(p); p.m_x = point[0].m_x - width - clearance; p.m_y = point[0].m_y - width - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x - width - clearance; p.m_y = point[1].m_y + width + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x - width - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y + width + clearance; cords.push_back(p); } } //horizontal else if (point[0].m_y == point[1].m_y) { if (point[0].m_x > point[1].m_x) { p.m_x = point[0].m_x + width + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y + width + clearance; cords.push_back(p); p.m_x = point[0].m_x + width + clearance; p.m_y = point[0].m_y + width + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x + width + clearance; p.m_y = point[0].m_y - width - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x + width + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y - width - clearance; cords.push_back(p); p.m_x = point[1].m_x - width - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y - width - clearance; cords.push_back(p); p.m_x = point[1].m_x - width - clearance; p.m_y = point[1].m_y - width - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x - width - clearance; p.m_y = point[1].m_y + width + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x - width - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y + width + clearance; cords.push_back(p); } else { p.m_x = point[1].m_x + width + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y + width + clearance; cords.push_back(p); p.m_x = point[1].m_x + width + clearance; p.m_y = point[1].m_y + width + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x + width + clearance; p.m_y = point[1].m_y - width - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x + width + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y - width - clearance; cords.push_back(p); p.m_x = point[0].m_x - width - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y - width - clearance; cords.push_back(p); p.m_x = point[0].m_x - width - clearance; p.m_y = point[0].m_y - width - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x - width - clearance; p.m_y = point[0].m_y + width + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x - width - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y + width + clearance; cords.push_back(p); } } //45degree else if ((point[0].m_x > point[1].m_x) && (point[0].m_y > point[1].m_y)) { p.m_x = point[0].m_x + sqrt(2) * width + clearance; p.m_y = point[0].m_y + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x + sqrt(2) * width + clearance; p.m_y = point[0].m_y - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); //2 p.m_x = point[1].m_x + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y - sqrt(2) * width - clearance; cords.push_back(p); //3 p.m_x = point[1].m_x - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y - sqrt(2) * width - clearance; cords.push_back(p); p.m_x = point[1].m_x - sqrt(2) * width - clearance; p.m_y = point[1].m_y - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x - sqrt(2) * width - clearance; p.m_y = point[1].m_y + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y + sqrt(2) * width + clearance; cords.push_back(p); p.m_x = point[0].m_x + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y + sqrt(2) * width + clearance; cords.push_back(p); } else if ((point[0].m_x < point[1].m_x) && (point[0].m_y < point[1].m_y)) { p.m_x = point[1].m_x + sqrt(2) * width + clearance; p.m_y = point[1].m_y + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x + sqrt(2) * width + clearance; p.m_y = point[1].m_y - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); //2 p.m_x = point[0].m_x + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y - sqrt(2) * width - clearance; cords.push_back(p); //3 p.m_x = point[0].m_x - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y - sqrt(2) * width - clearance; cords.push_back(p); p.m_x = point[0].m_x - sqrt(2) * width - clearance; p.m_y = point[0].m_y - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x - sqrt(2) * width - clearance; p.m_y = point[0].m_y + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y + sqrt(2) * width + clearance; cords.push_back(p); p.m_x = point[1].m_x + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y + sqrt(2) * width + clearance; cords.push_back(p); } //135degree else if ((point[1].m_x < point[0].m_x) && (point[1].m_y > point[0].m_y)) { p.m_x = point[1].m_x - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y + sqrt(2) * width + clearance; cords.push_back(p); p.m_x = point[1].m_x + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y + sqrt(2) * width + clearance; cords.push_back(p); p.m_x = point[0].m_x + sqrt(2) * width + clearance; p.m_y = point[0].m_y + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x + sqrt(2) * width + clearance; p.m_y = point[0].m_y - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y - sqrt(2) * width - clearance; cords.push_back(p); p.m_x = point[0].m_x - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y - sqrt(2) * width - clearance; cords.push_back(p); p.m_x = point[1].m_x - sqrt(2) * width - clearance; p.m_y = point[1].m_y - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x - sqrt(2) * width - clearance; p.m_y = point[1].m_y + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); } else if ((point[1].m_x > point[0].m_x) && (point[1].m_y < point[0].m_y)) { p.m_x = point[0].m_x - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y + sqrt(2) * width + clearance; cords.push_back(p); p.m_x = point[0].m_x + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[0].m_y + sqrt(2) * width + clearance; cords.push_back(p); p.m_x = point[1].m_x + sqrt(2) * width + clearance; p.m_y = point[1].m_y + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x + sqrt(2) * width + clearance; p.m_y = point[1].m_y - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[1].m_x + (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y - sqrt(2) * width - clearance; cords.push_back(p); p.m_x = point[1].m_x - (clearance * tan(22.5 * M_PI / 180)); p.m_y = point[1].m_y - sqrt(2) * width - clearance; cords.push_back(p); p.m_x = point[0].m_x - sqrt(2) * width - clearance; p.m_y = point[0].m_y - (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); p.m_x = point[0].m_x - sqrt(2) * width - clearance; p.m_y = point[0].m_y + (clearance * tan(22.5 * M_PI / 180)); cords.push_back(p); } return cords; } points_2d segmentToRelativeOctagon(const points_2d &point, const double &w, const double &clearance) { auto coord = relativeStartEndPointsForSegment(point); return segmentToOctagon(coord, w, clearance); } points_2d viaToRelativeOctagon(const double &size, const double &clearance) { auto _size = point_2d{size / 2, size / 2}; auto coords = points_2d{}; auto point = point_2d{}; //[0] point.m_x = (_size.m_x + clearance) * tan(22.5 * M_PI / 180); point.m_y = _size.m_y + clearance; coords.push_back(point); //[1] point.m_x = _size.m_x + clearance; point.m_y = (_size.m_y + clearance) * tan(22.5 * M_PI / 180); coords.push_back(point); //[2] point.m_x = _size.m_x + clearance; point.m_y = -1 * (_size.m_y + clearance) * tan(22.5 * M_PI / 180); coords.push_back(point); //[3] point.m_x = (_size.m_x + clearance) * tan(22.5 * M_PI / 180); point.m_y = -1 * _size.m_y - clearance; coords.push_back(point); //[4] point.m_x = -1 * (_size.m_x + clearance) * tan(22.5 * M_PI / 180); point.m_y = -1 * _size.m_y - clearance; coords.push_back(point); //[5] point.m_x = -1 * _size.m_x - clearance; point.m_y = -1 * (_size.m_y + clearance) * tan(22.5 * M_PI / 180); coords.push_back(point); //[6] point.m_x = -1 * _size.m_x - clearance; point.m_y = (_size.m_y + clearance) * tan(22.5 * M_PI / 180); coords.push_back(point); //[7] point.m_x = -1 * (_size.m_x + clearance) * tan(22.5 * M_PI / 180); point.m_y = _size.m_y + clearance; coords.push_back(point); return coords; } points_2d relativeStartEndPointsForSegment(const points_2d &p) { auto pRelative = point_2d{}; auto coords = points_2d{}; pRelative.m_x = (p[0].m_x - p[1].m_x) / 2; pRelative.m_y = (p[0].m_y - p[1].m_y) / 2; coords.push_back(pRelative); pRelative.m_x = (p[1].m_x - p[0].m_x) / 2; pRelative.m_y = (p[1].m_y - p[0].m_y) / 2; coords.push_back(pRelative); return coords; }
33.995829
171
0.518833
b686fe89416d5388886f05cde0320c1fbbec8d63
2,136
cpp
C++
poincare/src/frac_part.cpp
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
1,442
2017-08-28T19:39:45.000Z
2022-03-30T00:56:14.000Z
poincare/src/frac_part.cpp
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
1,321
2017-08-28T23:03:10.000Z
2022-03-31T19:32:17.000Z
poincare/src/frac_part.cpp
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
421
2017-08-28T22:02:39.000Z
2022-03-28T20:52:21.000Z
#include <poincare/frac_part.h> #include <poincare/layout_helper.h> #include <poincare/serialization_helper.h> #include <poincare/simplification_helper.h> #include <poincare/rational.h> #include <cmath> namespace Poincare { constexpr Expression::FunctionHelper FracPart::s_functionHelper; int FracPartNode::numberOfChildren() const { return FracPart::s_functionHelper.numberOfChildren(); } Layout FracPartNode::createLayout(Preferences::PrintFloatMode floatDisplayMode, int numberOfSignificantDigits) const { return LayoutHelper::Prefix(FracPart(this), floatDisplayMode, numberOfSignificantDigits, FracPart::s_functionHelper.name()); } int FracPartNode::serialize(char * buffer, int bufferSize, Preferences::PrintFloatMode floatDisplayMode, int numberOfSignificantDigits) const { return SerializationHelper::Prefix(this, buffer, bufferSize, floatDisplayMode, numberOfSignificantDigits, FracPart::s_functionHelper.name()); } Expression FracPartNode::shallowReduce(ReductionContext reductionContext) { return FracPart(this).shallowReduce(reductionContext); } template<typename T> Complex<T> FracPartNode::computeOnComplex(const std::complex<T> c, Preferences::ComplexFormat, Preferences::AngleUnit angleUnit) { if (c.imag() != 0) { return Complex<T>::RealUndefined(); } return Complex<T>::Builder(c.real()-std::floor(c.real())); } Expression FracPart::shallowReduce(ExpressionNode::ReductionContext reductionContext) { { Expression e = SimplificationHelper::defaultShallowReduce(*this); if (!e.isUninitialized()) { return e; } } Expression c = childAtIndex(0); if (c.type() == ExpressionNode::Type::Matrix) { return mapOnMatrixFirstChild(reductionContext); } if (c.type() != ExpressionNode::Type::Rational) { return *this; } Rational r = static_cast<Rational &>(c); IntegerDivision div = Integer::Division(r.signedIntegerNumerator(), r.integerDenominator()); assert(!div.remainder.isOverflow()); Integer rDenominator = r.integerDenominator(); Expression result = Rational::Builder(div.remainder, rDenominator); replaceWithInPlace(result); return result; } }
36.20339
143
0.767322
b687f2f402173eb1b7d32c6a6085eb022306d9a1
17,558
cc
C++
src/driver/parser.cc
cforall/resolv-proto
4eb7c0b9f4e75b940205e808e14fa57f13541246
[ "BSD-3-Clause" ]
2
2019-05-13T10:26:02.000Z
2019-05-13T15:04:42.000Z
src/driver/parser.cc
cforall/resolv-proto
4eb7c0b9f4e75b940205e808e14fa57f13541246
[ "BSD-3-Clause" ]
null
null
null
src/driver/parser.cc
cforall/resolv-proto
4eb7c0b9f4e75b940205e808e14fa57f13541246
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2015 University of Waterloo // // The contents of this file are covered under the licence agreement in // the file "LICENCE" distributed with this repository. #include "parser.h" #include <cstdlib> #include <iostream> #include <string> #include "args.h" #include "parser_common.h" #include "ast/decl.h" #include "ast/expr.h" #include "ast/forall.h" #include "ast/input_expr_visitor.h" #include "ast/type.h" #include "data/clock.h" #include "data/debug.h" #include "data/list.h" #include "data/mem.h" #include "data/option.h" #include "data/stats.h" #include "resolver/func_table.h" #include "resolver/resolver.h" /// Parses a name (lowercase alphanumeric ASCII string starting with a /// lowercase letter), returning true, storing result into ret, and /// incrementing token if so. token must not be null. bool parse_name(char const *&token, std::string& ret) { const char *end = token; if ( ('a' <= *end && *end <= 'z') || '_' == *end || '$' == *end ) ++end; else return false; while ( ('A' <= *end && *end <= 'Z') || ('a' <= *end && *end <= 'z') || ('0' <= *end && *end <= '9') || '_' == *end ) ++end; ret.assign( token, (end-token) ); token = end; return true; } /// Parses a named type name (hash followed by ASCII alphanumeric string /// starting with a letter or underscore), returning true, storing result /// (not including hash) into ret, and incrementing token if so. /// token must not be null bool parse_named_type(char const *&token, std::string& ret) { const char *end = token; if ( ! match_char(end, '#') ) return false; if ( ('A' <= *end && *end <= 'Z') || ('a' <= *end && *end <= 'z') || '_' == *end || '$' == *end ) ++end; else return false; while ( ('A' <= *end && *end <= 'Z') || ('a' <= *end && *end <= 'z') || ('0' <= *end && *end <= '9') || '_' == *end ) ++end; ret.assign( token+1, (end-token-1) ); token = end; return true; } /// Parses a polymorphic type name (lowercase alphanumeric ASCII string /// starting with an uppercase letter), returning true, storing result into /// ret, and incrementing token if so. token must not be null. bool parse_poly_type(char const *&token, std::string& ret) { const char *end = token; if ( 'A' <= *end && *end <= 'Z' ) ++end; else return false; while ( ('A' <= *end && *end <= 'Z') || ('a' <= *end && *end <= 'z') || ('0' <= *end && *end <= '9') || '_' == *end ) ++end; ret.assign( token, (end-token) ); token = end; return true; } /// Parses a type name, returning true, appending the result into out, and /// incrementing token if so. Concrete types will be canonicalized according /// to types and polymorphic types according to forall. token must not be null. bool parse_type(char const *&token, Resolver& resolver, Args& args, CanonicalTypeMap& types, unique_ptr<Forall>& forall, List<Type>& out); /// Parses an angle-bracket surrounded type list for the paramters of a generic named type bool parse_generic_params(char const *&token, Resolver& resolver, Args& args, CanonicalTypeMap& types, unique_ptr<Forall>& forall, List<Type>& out) { const char *end = token; if ( ! match_char(end, '<') ) return false; match_whitespace(end); if ( ! parse_type(end, resolver, args, types, forall, out) ) return false; while ( match_whitespace(end) ) { if ( ! parse_type(end, resolver, args, types, forall, out) ) break; } if ( ! match_char(end, '>') ) return false; token = end; return true; } /// Parses a function type, returning true, appending the result into out, and /// incrementing token if so. Concrete types will be canonicalized according /// to types and polymorphic types according to forall. token must not be null bool parse_func_type(const char*& token, Resolver& resolver, Args& args, CanonicalTypeMap& types, unique_ptr<Forall>& forall, List<Type>& out ) { List<Type> returns, params; const char* end = token; // match opening token if ( ! match_char(end, '[') ) return false; match_whitespace(end); // match return types while ( parse_type(end, resolver, args, types, forall, returns) ) { match_whitespace(end); } // match split token if ( ! match_char(end, ':') ) return false; match_whitespace(end); // match parameters while ( parse_type(end, resolver, args, types, forall, params) ) { match_whitespace(end); } // match closing token if ( ! match_char(end, ']') ) return false; match_whitespace(end); out.push_back( new FuncType{ move(params), move(returns) } ); token = end; return true; } bool parse_type(char const *&token, Resolver& resolver, Args& args, CanonicalTypeMap& types, unique_ptr<Forall>& forall, List<Type>& out) { int t; std::string n; if ( parse_int(token, t) ) { auto it = get_canon<ConcType>( types, t ); if ( it.second && ! args.metrics_only() ) resolver.addType( it.first ); out.push_back( it.first ); return true; } else if ( parse_named_type(token, n) ) { List<Type> params; parse_generic_params( token, resolver, args, types, forall, params ); auto it = get_canon( types, n, move(params) ); if ( it.second && ! args.metrics_only() ) resolver.addType( it.first ); out.push_back( it.first ); return true; } else if ( parse_poly_type(token, n) ) { if ( ! forall ) { forall.reset( new Forall{} ); } out.push_back( forall->add( n ) ); return true; } else if ( parse_func_type(token, resolver, args, types, forall, out) ) { return true; } else return false; } /// Parses a type assertion, returning true and adding the assertion into /// binding if so. Concrete types will be canonicalized according to types. /// token must not be null. bool parse_assertion(char const *&token, Resolver& resolver, Args& args, CanonicalTypeMap& types, unique_ptr<Forall>& forall) { const char* end = token; // look for type assertion if ( ! match_char(end, '|') ) return false; // parse return types List<Type> returns; match_whitespace(end); while ( parse_type(end, resolver, args, types, forall, returns) ) { match_whitespace(end); } std::string name; // try for variable assertion if ( match_char(end, '&') ) { if ( ! parse_name(end, name) ) return false; if ( ! forall ) { forall.reset( new Forall{} ); } forall->addAssertion( new VarDecl{ name, move(returns) } ); token = end; return true; } // function assertion -- parse name if ( ! parse_name(end, name) ) return false; // parse parameters List<Type> params; match_whitespace(end); while ( parse_type(end, resolver, args, types, forall, params) ) { match_whitespace(end); } if ( ! forall ) { forall.reset( new Forall{} ); } forall->addAssertion( new FuncDecl{ name, move(params), move(returns) } ); token = end; return true; } /// Parses a declaration from line; returns true and adds the declaration to /// funcs if found; will fail if given a valid func that does not consume the /// whole line. line must not be null. bool parse_decl( char const *line, Resolver& resolver, CanonicalTypeMap& types, Args& args, Metrics& metrics ) { List<Type> returns; std::string name; std::string tag = ""; unique_ptr<Forall> forall; // parse return types match_whitespace(line); while ( parse_type(line, resolver, args, types, forall, returns) ) { match_whitespace(line); } // check for variable decl if ( ! returns.empty() && match_char(line, '&') ) { if ( ! parse_name(line, name) ) return false; // optionally parse tag if ( match_char(line, '-') ) { if ( ! parse_name(line, tag) ) return false; } // check line consumed if ( ! is_blank(line) ) return false; if ( ! args.metrics_only() ) { resolver.addDecl( new VarDecl{ name, tag, move(returns) } ); } metrics.mark_decl( name ); return true; } // parse function decl List<Type> params; if ( ! parse_name(line, name) ) return false; // optionally parse tag if ( match_char(line, '-') ) { // might have been subsequent negative-valued type if ( ! parse_name(line, tag) ) { --line; } } // parse parameters match_whitespace(line); while ( parse_type(line, resolver, args, types, forall, params) ) { match_whitespace(line); } // parse type assertions while ( parse_assertion(line, resolver, args, types, forall) ); // check line consumed if ( ! is_empty(line) ) return false; // complete declaration if ( forall ) { metrics.mark_decl( name, forall->assertions().size() ); } else { metrics.mark_decl( name ); } if ( ! args.metrics_only() ) { resolver.addDecl( new FuncDecl{ name, tag, move(params), move(returns), move(forall) } ); } return true; } /// Parses a concrete type name, returning true, appending the result into out, and /// incrementing token if so. Concrete types will be canonicalized according /// to types and polymorphic types forbidden. token must not be null. bool parse_conc_type(char const *&token, Resolver& resolver, Args& args, CanonicalTypeMap& types, List<Type>& out); /// Parses an angle-bracket surrounded type list for the paramters of a concrete generic named type bool parse_conc_generic_params(char const *&token, Resolver& resolver, Args& args, CanonicalTypeMap& types, List<Type>& out) { const char *end = token; if ( ! match_char(end, '<') ) return false; match_whitespace(end); if ( ! parse_conc_type(end, resolver, args, types, out) ) return false; while ( match_whitespace(end) ) { if ( ! parse_conc_type(end, resolver, args, types, out) ) break; } if ( ! match_char(end, '>') ) return false; token = end; return true; } bool parse_conc_type(char const *&token, Resolver& resolver, Args& args, CanonicalTypeMap& types, List<Type>& out) { int t; std::string n; if ( parse_int(token, t) ) { // ConcType auto it = get_canon<ConcType>( types, t ); if ( it.second && ! args.metrics_only() ) resolver.addType( it.first ); out.push_back( it.first ); return true; } else if ( parse_named_type(token, n) ) { // concrete NamedType List<Type> params; parse_conc_generic_params( token, resolver, args, types, params ); auto it = get_canon( types, n, move(params) ); if ( it.second && ! args.metrics_only() ) resolver.addType( it.first ); out.push_back( it.first ); return true; } else if ( match_char(token, '[') ) { // concrete FuncType match_whitespace(token); // match return types List<Type> returns; while ( parse_conc_type(token, resolver, args, types, returns) ) { match_whitespace(token); } // match split token if ( ! match_char(token, ':') ) return false; match_whitespace(token); // match parameters List<Type> params; while ( parse_conc_type(token, resolver, args, types, params) ) { match_whitespace(token); } // match closing token if ( ! match_char(token, ']') ) return false; match_whitespace(token); // return type out.push_back( new FuncType{ move(params), move(returns) } ); return true; } else return false; } /// Parses a subexpression; returns true and adds the expression to exprs if found. /// line must not be null. bool parse_subexpr( char const *&token, List<Expr>& exprs, Resolver& resolver, Args& args, Metrics& metrics, CanonicalTypeMap& types ) { const char *end = token; // Check for a concrete type expression List<Type> cty; if ( parse_conc_type( end, resolver, args, types, cty ) ) { exprs.push_back( new ValExpr( cty.front() ) ); metrics.mark_sub(); token = end; return true; } // Check for name expression if ( match_char(end, '&') ) { std::string name; if ( ! parse_name(end, name) ) return false; match_whitespace(end); exprs.push_back( new NameExpr( name ) ); metrics.mark_sub(); token = end; return true; } // Check for function call std::string name; if ( ! parse_name(end, name) ) return false; match_whitespace(end); if ( ! match_char(end, '(') ) return false; // Read function args metrics.start_subs(); List<Expr> eargs; match_whitespace(end); while ( parse_subexpr(end, eargs, resolver, args, metrics, types) ) { match_whitespace(end); } metrics.end_subs(); // Find closing bracket if ( ! match_char(end, ')') ) return false; match_whitespace(end); exprs.push_back( new FuncExpr( name, move(eargs) ) ); metrics.mark_sub(); token = end; return true; } /// Per-instance input metrics struct InputMetrics { unsigned max_depth = 0; unsigned max_params = 0; unsigned n_subexprs = 0; unsigned max_overloads = 0; }; /// Calculates metrics on input expression class InputExprMetrics : public InputExprVisitor<InputExprMetrics, InputMetrics> { const Metrics& ftab; public: using Super = InputExprVisitor<InputExprMetrics, InputMetrics>; using Super::visit; InputExprMetrics(const Metrics& ftab) : ftab(ftab) {} bool visit( const ValExpr*, InputMetrics& m ) { ++m.max_depth; ++m.n_subexprs; return true; } bool visit( const NameExpr* e, InputMetrics& m ) { ++m.max_depth; ++m.n_subexprs; // update max overloads unsigned n_decls = ftab.n_decls_for( e->name() ); if ( n_decls > m.max_overloads ) { m.max_overloads = n_decls; } return true; } bool visit( const FuncExpr* e, InputMetrics & m ) { ++m.n_subexprs; // update max params unsigned n_params = e->args().size(); if ( n_params > m.max_params ) { m.max_params = n_params; } // update max depth unsigned local_d = ++m.max_depth; unsigned max_d = local_d; for ( const Expr* arg : e->args() ) { visit( arg, m ); if ( m.max_depth > max_d ) { max_d = m.max_depth; } m.max_depth = local_d; } m.max_depth = max_d; // update max overloads unsigned n_decls = ftab.n_decls_for( e->name() ); if ( n_decls > m.max_overloads ) { m.max_overloads = n_decls; } return true; } }; /// Parses an expression from line; returns true and adds the expression to /// exprs if found; will fail if given a valid expr that does not consume the /// whole line. line must not be null. bool parse_expr( unsigned n, char const *line, Resolver& resolver, Args& args, Metrics& metrics, CanonicalTypeMap& types ) { match_whitespace(line); List<Expr> exprs; if ( parse_subexpr(line, exprs, resolver, args, metrics, types) && is_empty(line) ) { assume( exprs.size() == 1, "successful expression parse results in single expression" ); if ( ! args.metrics_only() ) { if ( args.per_prob() ) { volatile std::clock_t start, end; InputMetrics m = InputExprMetrics{metrics}( exprs[0] ); args.out() << n << "," << m.max_depth << "," << m.max_params << "," << m.n_subexprs << "," << m.max_overloads << ","; #ifdef RP_STATS crnt_pass = Resolve; #endif start = std::clock(); resolver.addExpr( exprs[0] ); end = std::clock(); #ifdef RP_STATS crnt_pass = Parse; #endif args.out() << "," << (end-start)/*microseconds*/ << std::endl; } else { #ifdef RP_STATS crnt_pass = Resolve; #endif resolver.addExpr( exprs[0] ); #ifdef RP_STATS crnt_pass = Parse; #endif } } metrics.mark_expr(); return true; } else { metrics.reset_expr(); return false; } } /// Mode for echo_line -- declarations are echoed for Filtered verbosity, expressions are not enum EchoMode { EXPR, DECL }; /// Echos line if in appropriate mode void echo_line( std::string& line, Args& args, EchoMode mode = EXPR ) { if ( args.verbosity() == Args::Verbosity::Verbose || ( args.verbosity() == Args::Verbosity::Filtered && mode == DECL ) ) { args.out() << line << std::endl; } } /// Parses a scope from a series of lines (excluding opening "{" line if in block), /// continuing until end-of-input or terminating "}" line is found. /// Prints an error and exits if invalid declaration or expression found void parse_block( std::istream& in, unsigned& n, unsigned& scope, Resolver& resolver, CanonicalTypeMap& types, Args& args, Metrics& metrics ) { std::string line; // parse declarations and delimiter while ( std::getline( in, line ) ) { ++n; if ( is_blank( line ) ) { echo_line( line, args, DECL ); continue; } // break when finished declarations if ( line_matches( line, "%%" ) ) { echo_line( line, args, DECL ); break; } bool ok = parse_decl( line.data(), resolver, types, args, metrics ); if ( ! ok ) { std::cerr << "Invalid declaration [" << n << "]: \"" << line << "\"" << std::endl; std::exit(1); } echo_line( line, args, DECL ); } while ( std::getline( in, line ) ) { ++n; if ( is_blank( line ) ) { echo_line( line, args ); continue; } // break when finished block if ( line_matches( line, "}" ) ) { --scope; resolver.endScope(); metrics.end_lex_scope(); break; } // recurse when starting new block if ( line_matches( line, "{" ) ) { ++scope; resolver.beginScope(); metrics.begin_lex_scope(); parse_block( in, n, scope, resolver, types, args, metrics ); continue; } // parse and resolve expression if ( args.line_nos() ) { args.out() << n << ": " << std::flush; } bool ok = parse_expr( n, line.data(), resolver, args, metrics, types ); if ( ! ok ) { std::cerr << "Invalid expression [" << n << "]: \"" << line << "\"" << std::endl; std::exit(1); } echo_line( line, args ); } } void run_input( std::istream& in, Resolver& resolver, Args& args, Metrics& metrics ) { CanonicalTypeMap types; unsigned n = 0, scope = 0; parse_block(in, n, scope, resolver, types, args, metrics); if ( scope != 0 ) { std::cerr << "Unmatched braces" << std::endl; std::exit(1); } }
28.319355
99
0.650644
b68b1ce206b66639e3b5eaf52bcc0a8d9bd191b1
4,970
cc
C++
samples/asserts.cc
japrozs/Criterion
b67f3a2c1fae98d022b49403544c7e95a95a62ba
[ "MIT" ]
1
2022-02-16T19:47:54.000Z
2022-02-16T19:47:54.000Z
samples/asserts.cc
r3dapple/Criterion
b67f3a2c1fae98d022b49403544c7e95a95a62ba
[ "MIT" ]
10
2022-01-05T00:37:11.000Z
2022-02-06T19:24:49.000Z
samples/asserts.cc
r3dapple/Criterion
b67f3a2c1fae98d022b49403544c7e95a95a62ba
[ "MIT" ]
null
null
null
#include <criterion/criterion.h> #include <criterion/new/assert.h> #include <exception> #include <new> #include <array> #include <map> Test(asserts, base) { cr_assert(true); cr_expect(true); cr_assert(true, "Assertions may take failure messages"); cr_assert(true, "Or even %d format string %s", 1, "with parameters"); cr_expect(false, "assert is fatal, expect isn't"); cr_assert(false, "This assert runs"); cr_assert(false, "This does not"); } Test(asserts, old_school) { cr_fail("You can fail an assertion with a message from anywhere"); cr_fatal(); /* or without a message */ } Test(asserts, string) { cr_assert(zero(str, "")); cr_assert(not(zero(str, "foo"))); cr_assert(eq(str, "hello", "hello")); cr_assert(ne(str, "hello", "olleh")); cr_assert(gt(str, "hello", "hell")); cr_assert(ge(str, "hello", "hell")); cr_assert(ge(str, "hello", "hello")); cr_assert(lt(str, "hell", "hello")); cr_assert(le(str, "hell", "hello")); cr_assert(le(str, "hello", "hello")); } Test(asserts, wstring) { cr_assert(zero(wcs, L"")); cr_assert(not(zero(wcs, L"foo"))); cr_assert(eq(wcs, L"hello", L"hello")); cr_assert(ne(wcs, L"hello", L"olleh")); cr_assert(gt(wcs, L"hello", L"hell")); cr_assert(ge(wcs, L"hello", L"hell")); cr_assert(ge(wcs, L"hello", L"hello")); cr_assert(lt(wcs, L"hell", L"hello")); cr_assert(le(wcs, L"hell", L"hello")); cr_assert(le(wcs, L"hello", L"hello")); } Test(asserts, native) { cr_assert(eq(1, 1)); cr_assert(ne(1, 2)); cr_assert(lt(1, 2)); cr_assert(le(1, 2)); cr_assert(le(2, 2)); cr_assert(gt(2, 1)); cr_assert(ge(2, 1)); cr_assert(ge(2, 2)); } Test(asserts, float) { cr_assert(not(eq(dbl, 0.1 * 0.1, 0.01))); cr_assert(ieee_ulp_eq(dbl, 0.1 * 0.1, 0.01, 4)); } struct dummy_struct { char a; size_t b; }; /* We need to provide basic functions for our dummy struct */ bool operator==(const struct dummy_struct &lhs, const struct dummy_struct &rhs) { return lhs.a == rhs.a && lhs.b == rhs.b; } std::ostream &operator<<(std::ostream &s, const struct dummy_struct &val) { s << "(struct dummy_struct) { .a = " << val.a << ", .b = " << val.b << "}"; return s; } Test(asserts, array) { int arr1[] = { 1, 2, 3, 4 }; int arr2[] = { 4, 3, 2, 1 }; /* For primitive types we can compare their byte-to-byte representation */ auto mem_arr1 = criterion::memory { arr1 }; auto mem_arr2 = criterion::memory { arr2 }; cr_assert(eq(mem, mem_arr1, mem_arr1)); cr_assert(ne(mem, mem_arr1, mem_arr2)); /* Or we can use the tag[] notation */ cr_assert(eq(int[4], arr1, arr1)); cr_assert(ne(int[4], arr1, arr2)); /* The tag[] notation is mandatory to correctly compare padded types */ struct dummy_struct s1[] = { { 4, 2 }, { 2, 4 } }; struct dummy_struct s2[2]; memset(s2, 0xFF, sizeof (s2)); s2[0].a = 4; s2[0].b = 2; s2[1].a = 2; s2[1].b = 4; /* Here cr_assert(eq(mem, mem_s1, mem_s2)) would not have worked */ cr_assert(eq(type(struct dummy_struct)[2], s1, s2)); } struct array_cursor { size_t off; size_t size; const void *buf; }; static int read_array(void *cookie, void *buffer, size_t *size) { array_cursor *arr = static_cast<array_cursor*>(cookie); size_t rem = *size; if (rem > arr->size - arr->off) { rem = arr->size - arr->off; } std::memcpy(buffer, (char *) arr->buf + arr->off, rem); arr->off += rem; *size = rem; return 0; } Test(asserts, stream) { struct array_cursor arr1 = { 0, sizeof ("hello world"), "hello world", }; struct array_cursor arr2 = { 0, sizeof ("dlrow olleh"), "dlrow olleh", }; /* we can compare binary data with the general purpose stream API, by a read function, and optionally a close function. */ criterion::stream s1 = { &arr1, read_array }; criterion::stream s2 = { &arr2, read_array }; /* Note that this consumes both streams. Criterion will do the right thing if both streams are used in complex criteria by providing consistent comparison results between s1 and s2, but you can't compare either of them to any other stream without re-creating a fresh stream. */ cr_assert(ne(stream, s1, s2)); } Test(asserts, exception) { cr_expect(throw (std::runtime_error, {})); cr_assert(throw (std::invalid_argument, throw std::invalid_argument("some message"))); cr_assert(throw (std::bad_alloc, throw std::invalid_argument("some other message"))); } Test(asserts, containers) { using int_vect = std::vector<int>; cr_assert(zero(int_vect{})); int_vect v = {1, 2, 3}; cr_assert(not(zero(v))); using map = std::map<std::string, int>; map m = { {"hello", 1}, {"world", 2}, }; cr_assert(not(zero(m))); cr_assert(eq(m, m)); }
26.43617
90
0.603018
b692bd9f43bf79f36ad69388ce178bf388749810
873
cpp
C++
examples/priority_queue.cpp
miachm/STL-Threadsafe
08b2d9e7f487121088a817071d1d42b2736996e9
[ "Apache-2.0" ]
9
2017-07-25T23:22:54.000Z
2021-07-06T06:24:46.000Z
examples/priority_queue.cpp
miachm/STL-Threadsafe
08b2d9e7f487121088a817071d1d42b2736996e9
[ "Apache-2.0" ]
null
null
null
examples/priority_queue.cpp
miachm/STL-Threadsafe
08b2d9e7f487121088a817071d1d42b2736996e9
[ "Apache-2.0" ]
3
2020-12-11T03:02:35.000Z
2021-08-22T17:01:28.000Z
#include <iostream> #include <thread> #include "priority_queue-threadsafe.hpp" int main(){ std::threadsafe::priority_queue<int> bids; std::thread producer([&]{ int randomBids[20] = {3,19,11,2,4,12,1,20,14,5,18,10,15,8,17,6,16,7,9,13}; for (int i = 0;i < 20;i++){ bids.push(randomBids[i]); std::this_thread::sleep_for(std::chrono::milliseconds(1)); } }); try{ int out; while (true){ bids.wait_pop(out,std::chrono::milliseconds(100)); std::cout << "Checking new bids" << std::endl; std::cout << "\tBid: " << out << std::endl; while (bids.try_pop(out)){ std::cout << "\tBid: " << out << std::endl; } std::cout << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(3)); } } catch (std::threadsafe::Time_Expired e){ std::cout << "No more bids coming, shutting down..." << std::endl; } producer.join(); }
22.973684
76
0.610538
b699379d09377d60e623f06ea2d6dbdfac24156e
2,339
cpp
C++
day2/main.cpp
fardragon/AdventOfCode2021
16f31bcf2e7ff3a1c943e6dfb8b9e791f029dbea
[ "MIT" ]
1
2021-12-02T14:11:37.000Z
2021-12-02T14:11:37.000Z
day2/main.cpp
fardragon/AdventOfCode2021
16f31bcf2e7ff3a1c943e6dfb8b9e791f029dbea
[ "MIT" ]
null
null
null
day2/main.cpp
fardragon/AdventOfCode2021
16f31bcf2e7ff3a1c943e6dfb8b9e791f029dbea
[ "MIT" ]
null
null
null
#include "shared.hpp" #include <iostream> #include <numeric> #include <chrono> std::uint32_t SolvePart1(const std::vector<std::pair<std::string, std::uint16_t>> &input); std::uint32_t SolvePart2(const std::vector<std::pair<std::string, std::uint16_t>> &input); //std::uint16_t SolvePart2(const std::vector<uint16_t> &input); int main(int argc, char **argv) { if (argc < 2) { throw std::runtime_error("Not enough input arguments"); } const auto begin = std::chrono::steady_clock::now(); const auto lines = LoadLines(argv[1]); const auto input = LinesToStrUint16(lines); const auto beginSolving = std::chrono::steady_clock::now(); const auto part1Result = SolvePart1(input); const auto part2Result = SolvePart2(input); const auto end = std::chrono::steady_clock::now(); const auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count(); const auto elapsedSolving = std::chrono::duration_cast<std::chrono::microseconds>(end - beginSolving).count(); std::cout << "Part 1 result: " << part1Result << "\r\n"; std::cout << "Part 2 result: " << part2Result << "\r\n"; std::cout << "Time: " << elapsed << "us \r\n"; std::cout << "Time (without reading and parsing): " << elapsedSolving << "us \r\n"; return 0; } std::uint32_t SolvePart1(const std::vector<std::pair<std::string, std::uint16_t>> &input) { std::uint32_t position{}, depth{}; for (const auto &[command, argument]: input) { switch(command.front()) { case 'f': { //forward position += argument; break; } case 'u': { // up depth -= argument; break; } case 'd': { // down depth += argument; break; } default: throw std::runtime_error("Invalid command"); } } return position * depth; } std::uint32_t SolvePart2(const std::vector<std::pair<std::string, std::uint16_t>> &input) { std::uint32_t position{}, depth{}; std::int32_t aim{}; for (const auto &[command, argument]: input) { switch(command.front()) { case 'f': { //forward position += argument; depth += (aim * argument); break; } case 'u': { // up aim -= argument; break; } case 'd': { // down aim += argument; break; } default: throw std::runtime_error("Invalid command"); } } return position * depth; }
22.066038
111
0.626764
b69cadb7957bd91901a1abec8d2f2851c06e2d19
1,199
cpp
C++
vespalib/src/vespa/vespalib/io/mapped_file_input.cpp
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2018-12-30T05:42:18.000Z
2018-12-30T05:42:18.000Z
vespalib/src/vespa/vespalib/io/mapped_file_input.cpp
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2021-01-21T01:37:37.000Z
2021-01-21T01:37:37.000Z
vespalib/src/vespa/vespalib/io/mapped_file_input.cpp
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2020-09-03T11:39:52.000Z
2020-09-03T11:39:52.000Z
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "mapped_file_input.h" #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> #include <sys/mman.h> namespace vespalib { MappedFileInput::MappedFileInput(const vespalib::string &file_name) : _fd(open(file_name.c_str(), O_RDONLY)), _data((char *)MAP_FAILED), _size(0), _used(0) { struct stat info; if ((_fd != -1) && fstat(_fd, &info) == 0) { _data = static_cast<char*>(mmap(0, info.st_size, PROT_READ, MAP_SHARED, _fd, 0)); if (_data != MAP_FAILED) { _size = info.st_size; madvise(_data, _size, MADV_SEQUENTIAL); } } } MappedFileInput::~MappedFileInput() { if (valid()) { munmap(_data, _size); } if (_fd != -1) { close(_fd); } } bool MappedFileInput::valid() const { return (_data != MAP_FAILED); } Memory MappedFileInput::obtain() { return Memory((_data + _used), (_size - _used)); } Input & MappedFileInput::evict(size_t bytes) { _used += bytes; return *this; } } // namespace vespalib
21.035088
118
0.597164
b69dae11acf920c6cc1eec8c3923f0d2c294f1d5
1,470
cpp
C++
vision-project/src/pcl_conv_node/pcl_conv_node.cpp
koenichiwa/kobuki-vision
089564d4cab282f134e017f3342936ba2bc0335d
[ "MIT" ]
null
null
null
vision-project/src/pcl_conv_node/pcl_conv_node.cpp
koenichiwa/kobuki-vision
089564d4cab282f134e017f3342936ba2bc0335d
[ "MIT" ]
null
null
null
vision-project/src/pcl_conv_node/pcl_conv_node.cpp
koenichiwa/kobuki-vision
089564d4cab282f134e017f3342936ba2bc0335d
[ "MIT" ]
null
null
null
// // Created by bo on 11/17/19. // #include <message_filters/subscriber.h> #include <pcl_ros/point_cloud.h> #define ASTRA_FPS 30 #define MAX_QUEUE_SIZE 1 using namespace ros; using namespace message_filters; using namespace sensor_msgs; using namespace pcl; /** * @author Bo Sterenborg * This class converts the default ros PointCloud to the Pcl PointCloud and publishes the result. */ class PclConverter { private: message_filters::Subscriber<PointCloud2> rosPcSub; Publisher pclPub; /** * Method which takes a ros PointCloud and publishes a PCL PointCloud<PointXYZ> * @param pcl = ros' PointCloud. */ void pclCallback(const PointCloud2ConstPtr &pcl) { pcl::PointCloud<PointXYZ> pc; fromROSMsg(*pcl, pc); pclPub.publish(pc.makeShared()); } public: explicit PclConverter(NodeHandle &n) : rosPcSub(n, "/camera/depth_registered/points", MAX_QUEUE_SIZE) { typedef PointCloud<PointXYZ> PCLCloud; this->pclPub = n.advertise<PCLCloud>("/vision/point_cloud", MAX_QUEUE_SIZE); } void startConverting() { rosPcSub.registerCallback(&PclConverter::pclCallback, this); } }; int main(int argc, char **argv) { init(argc, argv, "pcl_conv_node"); NodeHandle n; Rate loopRate(ASTRA_FPS); PclConverter conv(n); conv.startConverting(); ROS_INFO("PCL Conversion node started..."); while (ok()) { spinOnce(); loopRate.sleep(); } }
24.915254
107
0.679592
b69fcc70e50199b0bb9e54a0c8a70a9541a46b7e
172
hpp
C++
Engine/Include/FishEngine/Path.hpp
ValtoGameEngines/Fish-Engine
a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9
[ "MIT" ]
240
2017-02-17T10:08:19.000Z
2022-03-25T14:45:29.000Z
Engine/Include/FishEngine/Path.hpp
ValtoGameEngines/Fish-Engine
a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9
[ "MIT" ]
2
2016-10-12T07:08:38.000Z
2017-04-05T01:56:30.000Z
Engine/Include/FishEngine/Path.hpp
yushroom/FishEngine
a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9
[ "MIT" ]
39
2017-03-02T09:40:07.000Z
2021-12-04T07:28:53.000Z
#define BOOST_FILESYSTEM_NO_DEPRECATED #include <boost/filesystem.hpp> #include <boost/filesystem/path.hpp> namespace FishEngine { using Path = boost::filesystem::path; }
21.5
38
0.796512
b6a13a7a5065dffa2991612f340a13fa50cd7192
3,157
cc
C++
src/main/cc/estimation/estimators.cc
world-federation-of-advertisers/any-sketch
728588eb4b02b6f0cd049cf8902dfa148e32560d
[ "Apache-2.0" ]
1
2021-03-29T16:50:52.000Z
2021-03-29T16:50:52.000Z
src/main/cc/estimation/estimators.cc
world-federation-of-advertisers/any-sketch
728588eb4b02b6f0cd049cf8902dfa148e32560d
[ "Apache-2.0" ]
2
2021-04-14T00:35:09.000Z
2021-07-07T13:47:47.000Z
src/main/cc/estimation/estimators.cc
world-federation-of-advertisers/any-sketch
728588eb4b02b6f0cd049cf8902dfa148e32560d
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The Cross-Media Measurement Authors // // 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 "estimation/estimators.h" #include <cmath> #include <cstdint> #include <functional> #include "absl/base/macros.h" #include "absl/functional/bind_front.h" namespace wfa::estimation { namespace { // Get the expected number of legionaries activated for given cardinality uint64_t GetExpectedActiveRegisterCount(double decay_rate, uint64_t num_of_total_registers, uint64_t cardinality) { ABSL_ASSERT(decay_rate > 1.0); ABSL_ASSERT(num_of_total_registers > 0); if (cardinality == 0) return 0; double exponential_of_decay = std::exp(decay_rate); double t = cardinality / static_cast<double>(num_of_total_registers); double negative_term = -std::expint((-decay_rate * t) / (exponential_of_decay - 1)); double positive_term = std::expint((-decay_rate * exponential_of_decay * t) / (exponential_of_decay - 1)); return (1 - (negative_term + positive_term) / decay_rate) * num_of_total_registers; } // Calculate the invert of a monotonic increasing function using binary search uint64_t InvertMonotonic(const std::function<uint64_t(uint64_t)>& function, uint64_t target) { uint64_t f0 = function(0); ABSL_ASSERT(f0 <= target); uint64_t left = 0; uint64_t right = 1; // Find a region that contains the solution while (function(right) < target) { left = right; right *= 2; } uint64_t mid = (right + left) / 2; while (right > left) { uint64_t f_mid = function(mid); if (f_mid > target) { right = mid - 1; } else { left = mid + 1; } mid = (right + left) / 2; } return mid; } double GetCardinality( std::function<uint64_t(uint64_t)> inverse_cardinality_estimator, uint64_t active_register_count) { return InvertMonotonic(inverse_cardinality_estimator, active_register_count); } } // namespace int64_t EstimateCardinalityLiquidLegions(double decay_rate, uint64_t num_of_total_registers, uint64_t active_register_count) { std::function<uint64_t(uint64_t)> get_expected_active_register_count = absl::bind_front(GetExpectedActiveRegisterCount, decay_rate, num_of_total_registers); ABSL_ASSERT(active_register_count < num_of_total_registers); return GetCardinality(get_expected_active_register_count, active_register_count); } } // namespace wfa::estimation
35.47191
79
0.679126
b6a26a510f6b78583d7ef149fb455db65ac8d300
458
hpp
C++
tools/stopwatch.hpp
matumoto1234/library
a2c80516a8afe5876696c139fe0e837d8a204f69
[ "Unlicense" ]
2
2021-06-24T11:21:08.000Z
2022-03-15T05:57:25.000Z
tools/stopwatch.hpp
matumoto1234/library
a2c80516a8afe5876696c139fe0e837d8a204f69
[ "Unlicense" ]
102
2021-10-30T21:30:00.000Z
2022-03-26T18:39:47.000Z
tools/stopwatch.hpp
matumoto1234/library
a2c80516a8afe5876696c139fe0e837d8a204f69
[ "Unlicense" ]
null
null
null
#pragma once #include "./base.hpp" #include <chrono> namespace tools { struct Stopwatch { chrono::high_resolution_clock::time_point start; Stopwatch() { restart(); } void restart() { start = chrono::high_resolution_clock::now(); } chrono::milliseconds::rep elapsed() { auto end = chrono::high_resolution_clock::now(); return chrono::duration_cast<chrono::milliseconds>(end - start).count(); } }; } // namespace tools
22.9
78
0.665939
b6a8407a1c18fbf1f8a711a92f2ee4e12327aa21
20,315
cpp
C++
ICG/src/tracker.cpp
XiaoJake/3DObjectTracking
c1fbf9241a0cd1ce450a1d6b86c67613025e1836
[ "MIT" ]
1
2022-03-17T08:17:47.000Z
2022-03-17T08:17:47.000Z
ICG/src/tracker.cpp
0smile/3DObjectTracking
c1fbf9241a0cd1ce450a1d6b86c67613025e1836
[ "MIT" ]
null
null
null
ICG/src/tracker.cpp
0smile/3DObjectTracking
c1fbf9241a0cd1ce450a1d6b86c67613025e1836
[ "MIT" ]
null
null
null
// SPDX-License-Identifier: MIT // Copyright (c) 2022 Manuel Stoiber, German Aerospace Center (DLR) #include <icg/tracker.h> namespace icg { Tracker::Tracker(const std::string &name, int n_corr_iterations, int n_update_iterations, bool synchronize_cameras, const std::chrono::milliseconds &cycle_duration, int visualization_time, int viewer_time) : name_{name}, n_corr_iterations_{n_corr_iterations}, n_update_iterations_{n_update_iterations}, synchronize_cameras_{synchronize_cameras}, cycle_duration_{cycle_duration}, visualization_time_{visualization_time}, viewer_time_{viewer_time} {} Tracker::Tracker(const std::string &name, const std::filesystem::path &metafile_path) : name_{name}, metafile_path_{metafile_path} {} bool Tracker::SetUp(bool set_up_all_objects) { set_up_ = false; if (!metafile_path_.empty()) if (!LoadMetaData()) return false; AssembleDerivedObjectPtrs(); if (set_up_all_objects) { if (!SetUpAllObjects()) return false; } else { if (!AreAllObjectsSetUp()) return false; } set_up_ = true; return true; } bool Tracker::AddOptimizer(const std::shared_ptr<Optimizer> &optimizer_ptr) { set_up_ = false; if (!AddPtrIfNameNotExists(optimizer_ptr, &optimizer_ptrs_)) { std::cerr << "Optimizer " << optimizer_ptr->name() << " already exists" << std::endl; return false; } return true; } bool Tracker::DeleteOptimizer(const std::string &name) { set_up_ = false; if (!DeletePtrIfNameExists(name, &optimizer_ptrs_)) { std::cerr << "Optimizer " << name << " not found" << std::endl; return false; } return true; } void Tracker::ClearOptimizers() { set_up_ = false; optimizer_ptrs_.clear(); } bool Tracker::AddDetector(const std::shared_ptr<Detector> &detector_ptr) { set_up_ = false; if (!AddPtrIfNameNotExists(detector_ptr, &detector_ptrs_)) { std::cerr << "Detector " << detector_ptr->name() << " already exists" << std::endl; return false; } return true; } bool Tracker::DeleteDetector(const std::string &name) { set_up_ = false; if (!DeletePtrIfNameExists(name, &detector_ptrs_)) { std::cerr << "Detector " << name << " not found" << std::endl; return false; } return true; } void Tracker::ClearDetectors() { set_up_ = false; detector_ptrs_.clear(); } bool Tracker::AddRefiner(const std::shared_ptr<Refiner> &refiner_ptr) { set_up_ = false; if (!AddPtrIfNameNotExists(refiner_ptr, &refiner_ptrs_)) { std::cerr << "Refiner " << refiner_ptr->name() << " already exists" << std::endl; return false; } return true; } bool Tracker::DeleteRefiner(const std::string &name) { set_up_ = false; if (!DeletePtrIfNameExists(name, &refiner_ptrs_)) { std::cerr << "Refiner " << name << " not found" << std::endl; return false; } return true; } void Tracker::ClearRefiners() { set_up_ = false; refiner_ptrs_.clear(); } bool Tracker::AddViewer(const std::shared_ptr<Viewer> &viewer_ptr) { set_up_ = false; if (!AddPtrIfNameNotExists(viewer_ptr, &viewer_ptrs_)) { std::cerr << "Viewer " << viewer_ptr->name() << " already exists" << std::endl; return false; } return true; } bool Tracker::DeleteViewer(const std::string &name) { set_up_ = false; if (!DeletePtrIfNameExists(name, &viewer_ptrs_)) { std::cerr << "Viewer " << name << " not found" << std::endl; return false; } return true; } void Tracker::ClearViewers() { set_up_ = false; viewer_ptrs_.clear(); } bool Tracker::AddPublisher(const std::shared_ptr<Publisher> &publisher_ptr) { set_up_ = false; if (!AddPtrIfNameNotExists(publisher_ptr, &publisher_ptrs_)) { std::cerr << "Publisher " << publisher_ptr->name() << " already exists" << std::endl; return false; } return true; } bool Tracker::DeletePublisher(const std::string &name) { set_up_ = false; if (!DeletePtrIfNameExists(name, &publisher_ptrs_)) { std::cerr << "Publisher " << name << " not found" << std::endl; return false; } return true; } void Tracker::ClearPublishers() { set_up_ = false; publisher_ptrs_.clear(); } void Tracker::set_name(const std::string &name) { name_ = name; } void Tracker::set_metafile_path(const std::filesystem::path &metafile_path) { metafile_path_ = metafile_path; set_up_ = false; } void Tracker::set_n_corr_iterations(int n_corr_iterations) { n_corr_iterations_ = n_corr_iterations; } void Tracker::set_n_update_iterations(int n_update_iterations) { n_update_iterations_ = n_update_iterations; } void Tracker::set_synchronize_cameras(bool synchronize_cameras) { synchronize_cameras_ = synchronize_cameras; } void Tracker::set_cycle_duration( const std::chrono::milliseconds &cycle_duration) { cycle_duration_ = cycle_duration; } void Tracker::set_visualization_time(int visualization_time) { visualization_time_ = visualization_time; } void Tracker::set_viewer_time(int viewer_time) { viewer_time_ = viewer_time; } bool Tracker::RunTrackerProcess(bool execute_detection, bool start_tracking) { if (!set_up_) { std::cerr << "Set up tracker " << name_ << " first" << std::endl; return false; } tracking_started_ = false; quit_tracker_process_ = false; execute_detection_ = execute_detection; start_tracking_ = start_tracking; for (int iteration = 0;; ++iteration) { auto begin{std::chrono::high_resolution_clock::now()}; if (!UpdateCameras(execute_detection_)) return false; if (execute_detection_) { if (!ExecuteDetectionCycle(iteration)) return false; tracking_started_ = false; execute_detection_ = false; } if (start_tracking_) { if (!StartModalities(iteration)) return false; tracking_started_ = true; start_tracking_ = false; } if (tracking_started_) { if (!ExecuteTrackingCycle(iteration)) return false; } if (!UpdateViewers(iteration)) return false; if (quit_tracker_process_) return true; if (!synchronize_cameras_) WaitUntilCycleEnds(begin); } return true; } void Tracker::QuitTrackerProcess() { quit_tracker_process_ = true; } void Tracker::ExecuteDetection(bool start_tracking) { execute_detection_ = true; start_tracking_ = start_tracking; } void Tracker::StartTracking() { start_tracking_ = true; } void Tracker::StopTracking() { tracking_started_ = false; } bool Tracker::ExecuteDetectionCycle(int iteration) { if (!DetectBodies()) return false; return RefinePoses(); } bool Tracker::StartModalities(int iteration) { for (auto &start_modality_renderer_ptr : start_modality_renderer_ptrs_) { if (!start_modality_renderer_ptr->StartRendering()) return false; } for (auto &modality_ptr : modality_ptrs_) { if (!modality_ptr->StartModality(iteration, 0)) return false; } return true; } bool Tracker::ExecuteTrackingCycle(int iteration) { for (int corr_iteration = 0; corr_iteration < n_corr_iterations_; ++corr_iteration) { int corr_save_idx = iteration * n_corr_iterations_ + corr_iteration; if (!CalculateCorrespondences(iteration, corr_iteration)) return false; if (!VisualizeCorrespondences(corr_save_idx)) return false; for (int update_iteration = 0; update_iteration < n_update_iterations_; ++update_iteration) { int update_save_idx = corr_save_idx * n_update_iterations_ + update_iteration; if (!CalculateGradientAndHessian(iteration, corr_iteration, update_iteration)) return false; if (!CalculateOptimization(iteration, corr_iteration, update_iteration)) return false; if (!VisualizeOptimization(update_save_idx)) return false; } } if (!CalculateResults(iteration)) return false; if (!VisualizeResults(iteration)) return false; return UpdatePublishers(iteration); } bool Tracker::DetectBodies() { for (auto &detector_ptr : detector_ptrs_) { if (!detector_ptr->DetectBody()) return false; } return true; } bool Tracker::RefinePoses() { for (auto &refiner_ptr : refiner_ptrs_) { if (!refiner_ptr->RefinePoses()) return false; } return true; } bool Tracker::UpdateCameras(bool update_all_cameras) { if (update_all_cameras) { for (auto &camera_ptr : all_camera_ptrs_) { if (!camera_ptr->UpdateImage(synchronize_cameras_)) return false; } } else { for (auto &camera_ptr : main_camera_ptrs_) { if (!camera_ptr->UpdateImage(synchronize_cameras_)) return false; } } return true; } bool Tracker::CalculateCorrespondences(int iteration, int corr_iteration) { for (auto &correspondence_renderer_ptr : correspondence_renderer_ptrs_) { if (!correspondence_renderer_ptr->StartRendering()) return false; } for (auto &modality_ptr : modality_ptrs_) { if (!modality_ptr->CalculateCorrespondences(iteration, corr_iteration)) return false; } return true; } bool Tracker::VisualizeCorrespondences(int save_idx) { bool imshow_correspondences = false; for (auto &modality_ptr : modality_ptrs_) { if (!modality_ptr->VisualizeCorrespondences(save_idx)) return false; if (modality_ptr->imshow_correspondence()) imshow_correspondences = true; } if (imshow_correspondences) { if (cv::waitKey(visualization_time_) == 'q') return false; } return true; } bool Tracker::CalculateGradientAndHessian(int iteration, int corr_iteration, int update_iteration) { for (auto &modality_ptr : modality_ptrs_) { if (!modality_ptr->CalculateGradientAndHessian(iteration, corr_iteration, update_iteration)) return false; } return true; } bool Tracker::CalculateOptimization(int iteration, int corr_iteration, int update_iteration) { for (auto &optimizer_ptr : optimizer_ptrs_) { if (!optimizer_ptr->CalculateOptimization(iteration, corr_iteration, update_iteration)) return false; } return true; } bool Tracker::VisualizeOptimization(int save_idx) { bool imshow_pose_update = false; for (auto &modality_ptr : modality_ptrs_) { if (!modality_ptr->VisualizeOptimization(save_idx)) return false; if (modality_ptr->imshow_optimization()) imshow_pose_update = true; } if (imshow_pose_update) { if (cv::waitKey(visualization_time_) == 'q') return false; } return true; } bool Tracker::CalculateResults(int iteration) { for (auto &results_renderer_ptr : results_renderer_ptrs_) { if (!results_renderer_ptr->StartRendering()) return false; } for (auto &modality_ptr : modality_ptrs_) { if (!modality_ptr->CalculateResults(iteration)) return false; } return true; } bool Tracker::VisualizeResults(int save_idx) { bool imshow_result = false; for (auto &modality_ptr : modality_ptrs_) { if (!modality_ptr->VisualizeResults(save_idx)) return false; if (modality_ptr->imshow_result()) imshow_result = true; } if (imshow_result) { if (cv::waitKey(visualization_time_) == 'q') return false; } return true; } bool Tracker::UpdatePublishers(int iteration) { for (auto &publisher_ptr : publisher_ptrs_) { if (!publisher_ptr->UpdatePublisher(iteration)) return false; } return true; } bool Tracker::UpdateViewers(int iteration) { if (!viewer_ptrs_.empty()) { for (auto &viewer_ptr : viewer_ptrs_) { viewer_ptr->UpdateViewer(iteration); } char key = cv::waitKey(viewer_time_); if (key == 'd') { execute_detection_ = true; } else if (key == 'x') { execute_detection_ = true; start_tracking_ = true; } else if (key == 't') { start_tracking_ = true; } else if (key == 's') { tracking_started_ = false; } else if (key == 'q') { quit_tracker_process_ = true; } } return true; } const std::string &Tracker::name() const { return name_; } const std::filesystem::path &Tracker::metafile_path() const { return metafile_path_; } const std::vector<std::shared_ptr<Optimizer>> &Tracker::optimizer_ptrs() const { return optimizer_ptrs_; } const std::vector<std::shared_ptr<Detector>> &Tracker::detector_ptrs() const { return detector_ptrs_; } const std::vector<std::shared_ptr<Refiner>> &Tracker::refiner_ptrs() const { return refiner_ptrs_; } const std::vector<std::shared_ptr<Viewer>> &Tracker::viewer_ptrs() const { return viewer_ptrs_; } const std::vector<std::shared_ptr<Publisher>> &Tracker::publisher_ptrs() const { return publisher_ptrs_; } const std::vector<std::shared_ptr<Modality>> &Tracker::modality_ptrs() const { return modality_ptrs_; } const std::vector<std::shared_ptr<Model>> &Tracker::model_ptrs() const { return model_ptrs_; } const std::vector<std::shared_ptr<Camera>> &Tracker::main_camera_ptrs() const { return main_camera_ptrs_; } const std::vector<std::shared_ptr<Camera>> &Tracker::all_camera_ptrs() const { return all_camera_ptrs_; } const std::vector<std::shared_ptr<RendererGeometry>> &Tracker::renderer_geometry_ptrs() const { return renderer_geometry_ptrs_; } const std::vector<std::shared_ptr<Body>> &Tracker::body_ptrs() const { return body_ptrs_; } const std::vector<std::shared_ptr<Renderer>> &Tracker::start_modality_renderer_ptrs() const { return start_modality_renderer_ptrs_; } const std::vector<std::shared_ptr<Renderer>> &Tracker::correspondence_renderer_ptrs() const { return correspondence_renderer_ptrs_; } const std::vector<std::shared_ptr<Renderer>> &Tracker::results_renderer_ptrs() const { return results_renderer_ptrs_; } int Tracker::n_corr_iterations() const { return n_corr_iterations_; } int Tracker::n_update_iterations() const { return n_update_iterations_; } bool Tracker::synchronize_cameras() const { return synchronize_cameras_; } const std::chrono::milliseconds &Tracker::cycle_duration() const { return cycle_duration_; } int Tracker::visualization_time() const { return visualization_time_; } int Tracker::viewer_time() const { return viewer_time_; } bool Tracker::set_up() const { return set_up_; } bool Tracker::LoadMetaData() { // Open file storage from yaml cv::FileStorage fs; if (!OpenYamlFileStorage(metafile_path_, &fs)) return false; // Read parameters from yaml int i_cycle_duration; ReadOptionalValueFromYaml(fs, "n_corr_iterations", &n_corr_iterations_); ReadOptionalValueFromYaml(fs, "n_update_iterations", &n_update_iterations_); ReadOptionalValueFromYaml(fs, "synchronize_cameras", &synchronize_cameras_); ReadOptionalValueFromYaml(fs, "cycle_duration", &i_cycle_duration); ReadOptionalValueFromYaml(fs, "visualization_time", &visualization_time_); ReadOptionalValueFromYaml(fs, "viewer_time", &viewer_time_); cycle_duration_ = std::chrono::milliseconds{i_cycle_duration}; fs.release(); return true; } void Tracker::WaitUntilCycleEnds( std::chrono::high_resolution_clock::time_point begin) { auto elapsed_time{std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - begin)}; if (elapsed_time < cycle_duration_) std::this_thread::sleep_for(elapsed_time - cycle_duration_); else std::cerr << "Tracker too slow: elapsed time = " << elapsed_time.count() << " ms > " << cycle_duration_.count() << " ms" << std::endl; } void Tracker::AssembleDerivedObjectPtrs() { modality_ptrs_.clear(); main_camera_ptrs_.clear(); all_camera_ptrs_.clear(); model_ptrs_.clear(); start_modality_renderer_ptrs_.clear(); results_renderer_ptrs_.clear(); correspondence_renderer_ptrs_.clear(); renderer_geometry_ptrs_.clear(); body_ptrs_.clear(); // Assemble objects from detectors for (auto &detector_ptr : detector_ptrs_) { AddPtrIfNameNotExists(detector_ptr->camera_ptr(), &all_camera_ptrs_); AddPtrsIfNameNotExists(detector_ptr->body_ptrs(), &body_ptrs_); } // Assemble required objects from refiner for (auto &refiner_ptr : refiner_ptrs_) { for (auto &optimizer_ptr : refiner_ptr->optimizer_ptrs()) { for (auto &modality_ptr : optimizer_ptr->modality_ptrs()) { AddPtrsIfNameNotExists(modality_ptr->camera_ptrs(), &all_camera_ptrs_); } } } // Assemble objects from viewers for (auto &viewer_ptr : viewer_ptrs_) { AddPtrIfNameNotExists(viewer_ptr->camera_ptr(), &main_camera_ptrs_); AddPtrIfNameNotExists(viewer_ptr->camera_ptr(), &all_camera_ptrs_); AddPtrIfNameNotExists(viewer_ptr->renderer_geometry_ptr(), &renderer_geometry_ptrs_); } // Assemble objects from optimizer for (auto &optimizer_ptr : optimizer_ptrs_) { AddPtrsIfNameNotExists(optimizer_ptr->modality_ptrs(), &modality_ptrs_); } // Assemble objects from modalities for (auto &modality_ptr : modality_ptrs_) { AddPtrsIfNameNotExists(modality_ptr->camera_ptrs(), &main_camera_ptrs_); AddPtrsIfNameNotExists(modality_ptr->camera_ptrs(), &all_camera_ptrs_); AddPtrIfNameNotExists(modality_ptr->model_ptr(), &model_ptrs_); AddPtrsIfNameNotExists(modality_ptr->start_modality_renderer_ptrs(), &start_modality_renderer_ptrs_); AddPtrsIfNameNotExists(modality_ptr->correspondence_renderer_ptrs(), &correspondence_renderer_ptrs_); AddPtrsIfNameNotExists(modality_ptr->results_renderer_ptrs(), &results_renderer_ptrs_); AddPtrIfNameNotExists(modality_ptr->body_ptr(), &body_ptrs_); } // Assemble objects from models for (auto &model_ptr : model_ptrs_) { AddPtrIfNameNotExists(model_ptr->body_ptr(), &body_ptrs_); } // Assemble objects from renderers for (auto &start_modality_renderer_ptr : start_modality_renderer_ptrs_) { AddPtrIfNameNotExists(start_modality_renderer_ptr->renderer_geometry_ptr(), &renderer_geometry_ptrs_); AddPtrsIfNameNotExists(start_modality_renderer_ptr->referenced_body_ptrs(), &body_ptrs_); } for (auto &correspondence_renderer_ptr : correspondence_renderer_ptrs_) { AddPtrIfNameNotExists(correspondence_renderer_ptr->renderer_geometry_ptr(), &renderer_geometry_ptrs_); AddPtrsIfNameNotExists(correspondence_renderer_ptr->referenced_body_ptrs(), &body_ptrs_); } for (auto results_renderer_ptr : results_renderer_ptrs_) { AddPtrIfNameNotExists(results_renderer_ptr->renderer_geometry_ptr(), &renderer_geometry_ptrs_); AddPtrsIfNameNotExists(results_renderer_ptr->referenced_body_ptrs(), &body_ptrs_); } // Assemble objects from renderer geometry for (auto &renderer_geometry_ptr : renderer_geometry_ptrs_) { AddPtrsIfNameNotExists(renderer_geometry_ptr->body_ptrs(), &body_ptrs_); } } bool Tracker::SetUpAllObjects() { return SetUpObjectPtrs(&body_ptrs_) && SetUpObjectPtrs(&renderer_geometry_ptrs_) && SetUpObjectPtrs(&all_camera_ptrs_) && SetUpObjectPtrs(&start_modality_renderer_ptrs_) && SetUpObjectPtrs(&correspondence_renderer_ptrs_) && SetUpObjectPtrs(&results_renderer_ptrs_) && SetUpObjectPtrs(&model_ptrs_) && SetUpObjectPtrs(&modality_ptrs_) && SetUpObjectPtrs(&optimizer_ptrs_) && SetUpObjectPtrs(&viewer_ptrs_) && SetUpObjectPtrs(&refiner_ptrs_) && SetUpObjectPtrs(&detector_ptrs_) && SetUpObjectPtrs(&publisher_ptrs_); } bool Tracker::AreAllObjectsSetUp() { return AreObjectPtrsSetUp(&body_ptrs_) && AreObjectPtrsSetUp(&renderer_geometry_ptrs_) && AreObjectPtrsSetUp(&all_camera_ptrs_) && AreObjectPtrsSetUp(&start_modality_renderer_ptrs_) && AreObjectPtrsSetUp(&correspondence_renderer_ptrs_) && AreObjectPtrsSetUp(&results_renderer_ptrs_) && AreObjectPtrsSetUp(&model_ptrs_) && AreObjectPtrsSetUp(&modality_ptrs_) && AreObjectPtrsSetUp(&optimizer_ptrs_) && AreObjectPtrsSetUp(&viewer_ptrs_) && AreObjectPtrsSetUp(&refiner_ptrs_) && AreObjectPtrsSetUp(&detector_ptrs_) && AreObjectPtrsSetUp(&publisher_ptrs_); } } // namespace icg
32.194929
80
0.704209
b6a95c64cfaa3b62665f75129a8ddd8523dfcb24
1,402
hpp
C++
src/ivorium_graphics/Rendering/Shader.hpp
ivorne/ivorium
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
[ "Apache-2.0" ]
3
2021-02-26T02:59:09.000Z
2022-02-08T16:44:21.000Z
src/ivorium_graphics/Rendering/Shader.hpp
ivorne/ivorium
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
[ "Apache-2.0" ]
null
null
null
src/ivorium_graphics/Rendering/Shader.hpp
ivorne/ivorium
1d876b6dcabe29b3110d3058f997e59c40cd6a2b
[ "Apache-2.0" ]
null
null
null
#pragma once #include "../OpenGL/GlTexture.hpp" #include "../OpenGL/GlProgram.hpp" #include "../OpenGL/gl.h" #include "GlSystem.hpp" #include <ivorium_systems/ivorium_systems.hpp> #include <ivorium_core/ivorium_core.hpp> namespace iv { /** To create shader using VirtualResourceProvider method, construct it from a path which has fragment shader source at path+".frag" and vertex shader source at path+".vert". */ class Shader { public: ClientMarker cm; Shader( Instance * inst, ResourcePath const & path ); ~Shader(); Instance * instance() const; void status( iv::TableDebugView * view ); //--------------------- loading ---------------------- void LoadProgram(); void BindAttribute( GLuint location, const char * attrib_name ); void PositionAttributeName( const char * name ); void LinkProgram(); void UnloadProgram(); void DropProgram(); //--------------------- usage ------ GlProgram const * gl_program() const; GLint GetUniformLocation( const char * name ) const; private: Instance * inst; ResourcePath _src_path; GlProgram _gl_program; }; }
29.208333
174
0.524964
b6ad33a4e32cc545c631d299f020d045489c281c
686
cpp
C++
src/DesignerPlugin/SARibbonPluginCollection.cpp
EMinsight/SARibbon
4c211e961dfdf3e953b4f89bdd9acf25db1e3da6
[ "MIT" ]
374
2017-12-27T01:08:45.000Z
2022-03-30T16:16:36.000Z
src/DesignerPlugin/SARibbonPluginCollection.cpp
EMinsight/SARibbon
4c211e961dfdf3e953b4f89bdd9acf25db1e3da6
[ "MIT" ]
33
2017-12-07T09:24:31.000Z
2022-03-29T07:53:51.000Z
src/DesignerPlugin/SARibbonPluginCollection.cpp
EMinsight/SARibbon
4c211e961dfdf3e953b4f89bdd9acf25db1e3da6
[ "MIT" ]
161
2017-11-24T03:12:29.000Z
2022-03-26T04:11:48.000Z
#include "SARibbonPluginCollection.h" #include "SARibbonMainWindowDesignerPlugin.h" #include "SARibbonBarDesignerPlugin.h" #include "SARibbonCategoryDesignerPlugin.h" #include "SARibbonPannelDesignerPlugin.h" using namespace SA_PLUGIN; SARibbonPluginCollection::SARibbonPluginCollection(QObject *p) : QObject(p) { m_widgets.append(new SARibbonMainWindowDesignerPlugin(this)); m_widgets.append(new SARibbonBarDesignerPlugin(this)); m_widgets.append(new SARibbonCategoryDesignerPlugin(this)); m_widgets.append(new SARibbonPannelDesignerPlugin(this)); } QList<QDesignerCustomWidgetInterface *> SARibbonPluginCollection::customWidgets() const { return (m_widgets); }
34.3
87
0.817784
b6ada5a29317a14bb626e6073fd0c5781baeabff
1,899
cpp
C++
Array/Snail Sort/main.cpp
pratikj697/hacktoberfest-competitiveprogramming
3b392edf61d2bd284bd5714af72abd76ff049340
[ "MIT" ]
22
2021-10-02T13:18:58.000Z
2021-10-13T18:27:06.000Z
Array/Snail Sort/main.cpp
pratikj697/hacktoberfest-competitiveprogramming
3b392edf61d2bd284bd5714af72abd76ff049340
[ "MIT" ]
96
2021-10-02T14:14:43.000Z
2021-10-09T06:17:33.000Z
Array/Snail Sort/main.cpp
pratikj697/hacktoberfest-competitiveprogramming
3b392edf61d2bd284bd5714af72abd76ff049340
[ "MIT" ]
112
2021-10-02T14:57:15.000Z
2021-10-15T05:45:30.000Z
#include <bits/stdc++.h> using namespace std; vector<int> snail(const vector<vector<int>> &snail_map) { vector<vector<int>> input = snail_map; //check if the vector size is greater than 1 if (input.size() > 1) { vector<int> answer; // push the first row in the answer vector for (int j = 0; j < input[0].size(); j++) { answer.push_back(input[0][j]); } // remove first row from the input input[0].erase(input[0].begin(), input[0].end()); input.erase(input.begin()); // insert the last element from other all the rows for (int j = 0; j < input.size(); j++) { answer.push_back(input[j].back()); // remove the element input[j].pop_back(); } // iterate the last row for (int j = input[input.size() - 1].size() - 1; j >= 0; j--) { answer.push_back(input[input.size() - 1][j]); } input[input.size() - 1].erase(input[input.size() - 1].begin(), input[input.size() - 1].end()); input.erase(input.end()); reverse(input.begin(), input.end()); for (int i = 0; i < input.size(); i++) { answer.push_back(input[i][0]); input[i].erase(input[i].begin()); } if (input.size() > 0) { reverse(input.begin(), input.end()); vector<int> add = snail(input); answer.insert(answer.end(), add.begin(), add.end()); } return answer; } else { return snail_map[0]; } } //main function int main() { vector<vector<int>> v = {{1, 2, 3}, {8, 9, 4}, {7, 6, 5}}; // feed the input to the function vector<int> ans = snail(v); cout << "Output" << endl; // print the final output for (int &ele : ans) { cout << ele; } }
24.662338
102
0.493418
b6b4d64f46c26a28f0216235aade202182e0cfe5
15,740
cpp
C++
src/Organism.cpp
Sn0wFox/ot3-pro2017
889dcbb1ad0203a916e7431c6525fded49ef57dd
[ "MIT" ]
1
2017-11-13T07:23:52.000Z
2017-11-13T07:23:52.000Z
src/Organism.cpp
Sn0wFox/ot3-pro2017
889dcbb1ad0203a916e7431c6525fded49ef57dd
[ "MIT" ]
null
null
null
src/Organism.cpp
Sn0wFox/ot3-pro2017
889dcbb1ad0203a916e7431c6525fded49ef57dd
[ "MIT" ]
null
null
null
// // Created by arrouan on 28/09/16. // #include "Organism.h" #include "DNA.h" #include "Common.h" #include <map> void Organism::translate_RNA() { RNA* current_rna = nullptr; for (auto it = dna_->bp_list_.begin(); it != dna_->bp_list_.end(); it++) { if ((*it)->type_ == (int)BP::BP_Type::START_RNA) { current_rna = new RNA((*it)->binding_pattern_, (*it)->concentration_); } else if ((*it)->type_ == (int)BP::BP_Type::END_RNA) { if (current_rna != nullptr) { rna_list_.push_back(current_rna); current_rna = nullptr; } } else if (current_rna != nullptr) { current_rna->bp_list_.push_back(new BP((*it))); } } } void Organism::translate_protein() { float binding_pattern = -1; int rna_id = 0; for ( auto it = rna_list_.begin(); it != rna_list_.end(); it++ ) { for (auto it_j = (*it)->bp_list_.begin(); it_j < (*it)->bp_list_.end(); it_j++) { if ((*it_j)->type_ == (int) BP::BP_Type::START_PROTEIN) { binding_pattern = (*it_j)->binding_pattern_; } else if ((*it_j)->type_ == (int) BP::BP_Type::END_PROTEIN) { binding_pattern = -1; } else if (((*it_j)->type_ == (int) BP::BP_Type::PROTEIN_BLOCK) && (binding_pattern != -1)) { bool current_float = false; // true == next value if op arith else float bool first_value = true; // current_value is initialized or not float current_value = -1; int current_arith_op = -1; for (auto it_k = (*it_j)->protein_block_->bp_prot_list_.begin(); it_k < (*it_j)->protein_block_->bp_prot_list_.end(); it_k++) { if ((*it_k)->type_ == (int) BP_Protein::BP_Protein_Type::ARITHMETIC_OPERATOR) { if (current_float) { current_arith_op = (*it_k)->op_; current_float = false; } } else if ((*it_k)->type_ == (int) BP_Protein::BP_Protein_Type::FLOAT_NUMBER) { if ((!current_float) && first_value) { current_value = (*it_k)->number_; current_float = true; first_value = false; } else if ((!current_float) && (!first_value)) { float value = (*it_k)->number_; current_float = true; if (current_arith_op == (int) BP_Protein::Arithmetic_Operator_Type::ADD) { current_value+=value; } else if (current_arith_op == (int) BP_Protein::Arithmetic_Operator_Type::MODULO) { current_value=std::fmod(current_value,value); } else if (current_arith_op == (int) BP_Protein::Arithmetic_Operator_Type::MULTIPLY) { current_value*=value; } else if (current_arith_op == (int) BP_Protein::Arithmetic_Operator_Type::POWER) { current_value=std::pow(current_value,value); } } } } int type = -1; if (current_value < 0.8) { type = (int) Protein::Protein_Type::FITNESS; } else if (current_value >= 0.8 && current_value < 0.9) { type = (int) Protein::Protein_Type::TF; } else if (current_value >= 0.9 && current_value < 0.95) { type = (int) Protein::Protein_Type::POISON; } else if (current_value >= 0.95 && current_value < 1.0) { type = (int) Protein::Protein_Type::ANTIPOISON; } Protein* prot = new Protein(type,binding_pattern,current_value); prot->concentration_ = (*it)->concentration_base_; if ( protein_list_map_.find(current_value) == protein_list_map_.end() ) { protein_list_map_[current_value] = prot; if (type == (int) Protein::Protein_Type::FITNESS) { protein_fitness_list_.push_back(prot); } else if (type == (int) Protein::Protein_Type::TF) { protein_TF_list_.push_back(prot); } else if (type == (int) Protein::Protein_Type::POISON) { protein_poison_list_.push_back(prot); } else if (type == (int) Protein::Protein_Type::ANTIPOISON) { protein_antipoison_list_.push_back(prot); } } else { protein_list_map_[current_value]->concentration_+=(*it)->concentration_base_; delete prot; } rna_produce_protein_.push_back(current_value); } } rna_id++; } } void Organism::translate_pump() { bool within_pump = false; for ( auto it = rna_list_.begin(); it != rna_list_.end(); it++ ) { for (auto it_j = (*it)->bp_list_.begin(); it_j < (*it)->bp_list_.end(); it_j++) { if ((*it_j)->type_ == (int) BP::BP_Type::START_PUMP) { within_pump = true; } else if ((*it_j)->type_ == (int) BP::BP_Type::END_PUMP) { within_pump = false; } else if (((*it_j)->type_ == (int) BP::BP_Type::PUMP_BLOCK) && (within_pump)) { for (auto it_k=(*it_j)->pump_block_->bp_pump_list_.begin(); it_k < (*it_j)->pump_block_-> bp_pump_list_.end(); it_k++) { Pump* pump = new Pump((*it_k)->in_out_,(*it_k)->start_range_, (*it_k)->end_range_,(*it_k)->speed_); pump_list_.push_back(pump); } } } } } void Organism::translate_move() { bool within_move = false; for ( auto it = rna_list_.begin(); it != rna_list_.end(); it++ ) { for (auto it_j = (*it)->bp_list_.begin(); it_j < (*it)->bp_list_.end(); it_j++) { if ((*it_j)->type_ == (int) BP::BP_Type::START_MOVE) { within_move = true; } else if ((*it_j)->type_ == (int) BP::BP_Type::END_MOVE) { within_move = false; } else if (((*it_j)->type_ == (int) BP::BP_Type::MOVE_BLOCK) && (within_move)) { for (auto it_k=(*it_j)->move_block_-> bp_move_list_.begin(); it_k < (*it_j)->move_block_-> bp_move_list_.end(); it_k++) { Move* move = new Move((*it_k)->distance_,(*it_k)->retry_); move_list_.push_back(move); } } } } } void Organism::compute_next_step() { // Activate Pump activate_pump(); // Compute protein concentration for X steps compute_protein_concentration(); } void Organism::activate_pump() { for (auto it = pump_list_.begin(); it != pump_list_.end(); it++) { if ((*it)->in_out_) { for (auto prot : protein_list_map_) { if ((*it)->start_range_ >= prot.second->value_ && (*it)->end_range_ <= prot.second->value_) { float remove = prot.second->concentration_*((*it)->speed_/100); prot.second->concentration_ -= remove; if ( gridcell_->protein_list_map_.find(prot.second->value_) == gridcell_->protein_list_map_.end() ) { Protein* prot_n = new Protein(prot.second->type_, prot.second->binding_pattern_, prot.second->value_); prot_n->concentration_ = remove; gridcell_->protein_list_map_[prot.second->value_] = prot_n; } else { gridcell_->protein_list_map_[prot.second->value_]->concentration_ += remove; } } } } else { for (auto prot : gridcell_->protein_list_map_) { if ((*it)->start_range_ >= prot.first && (*it)->end_range_ <= prot.first) { float remove = prot.second->concentration_*((*it)->speed_/100); prot.second->concentration_ -= remove; if ( protein_list_map_.find(prot.first) == protein_list_map_.end() ) { Protein* prot_n = new Protein(prot.second->type_, prot.second->binding_pattern_, prot.second->value_); prot_n->concentration_ = remove; protein_list_map_[prot_n->value_] = prot_n; } else { protein_list_map_[prot.first]->concentration_ += remove; } } } } } } void Organism::init_organism() { translate_RNA(); translate_protein(); translate_pump(); translate_move(); } void Organism::compute_protein_concentration() { current_concentration_compute(); delta_concentration_compute(); } // TODO: the critical call everyone ! void Organism::delta_concentration_compute() { for (int rna_id = 0; rna_id < rna_produce_protein_.size(); rna_id++) { rna_list_[rna_id]->current_concentration_ -= Common::Protein_Degradation_Rate * protein_list_map_[rna_produce_protein_[rna_id]]->concentration_; rna_list_[rna_id]->current_concentration_ *= 1/(Common::Protein_Degradation_Step); protein_list_map_[rna_produce_protein_[rna_id]]->concentration_+=rna_list_[rna_id]->current_concentration_; } } bool Organism::dying_or_not() { // Compute if dying or not double concentration_sum = 0; for (auto prot : protein_fitness_list_) { concentration_sum+=prot->concentration_; } for (auto prot : protein_TF_list_) { concentration_sum+=prot->concentration_; } if (concentration_sum > 10.0 && concentration_sum <= 0.0) { return true; } double poison=0,antipoison=0; for (auto prot : protein_poison_list_) { poison+=prot->concentration_; } for (auto prot : protein_antipoison_list_) { antipoison+=prot->concentration_; } if (poison-antipoison>0.1) { return true; } std::binomial_distribution<int> dis_death(1024,Common::Random_Death); int death_number = dis_death(gridcell_->float_gen_); bool death = (bool) death_number % 2; return death; } void Organism::try_to_move() { for (auto it = move_list_.begin(); it != move_list_.end(); it++) { if ((*it)->distance_ > 0) { bool move = false; int retry = 0; std::uniform_int_distribution<uint32_t> dis_distance(0,(*it)->distance_); while (retry < (*it)->retry_ && !move) { int x_offset=dis_distance(gridcell_->float_gen_); int y_offset=dis_distance(gridcell_->float_gen_); int new_x,new_y; if (gridcell_->x_+x_offset >= gridcell_->world_->width_) { new_x = gridcell_->world_->width_-1; } else { new_x = gridcell_->x_+x_offset; } if (gridcell_->y_+y_offset >= gridcell_->world_->height_) { new_y = gridcell_->world_->height_-1; } else { new_y = gridcell_->y_+y_offset; } if (gridcell_->world_->grid_cell_[new_x*gridcell_->world_->width_+new_y]->organism_ != nullptr) { move = true; move_success_++; gridcell_->world_->grid_cell_[new_x*gridcell_->world_->width_+new_y]->organism_ = this; gridcell_ = gridcell_->world_->grid_cell_[new_x*gridcell_->world_->width_+new_y]; gridcell_->organism_ = nullptr; } } } } } void Organism::compute_fitness() { life_duration_++; for (int i = 0; i < Common::Metabolic_Error_Precision; i++) metabolic_error[i] = 0.0; for (auto prot : protein_fitness_list_) { //.begin(); it != protein_fitness_list_.end(); it++) { int index = prot->value_*Common::Metabolic_Error_Precision; float concentration = prot->concentration_; for (int j = index - Common::Metabolic_Error_Protein_Spray; j <= index + Common::Metabolic_Error_Protein_Spray; j++) { if (j < Common::Metabolic_Error_Precision && j >= 0) { if (j < index) { metabolic_error[j] += (index - j) * Common::Metabolic_Error_Protein_Slope * concentration; } else if (j > index) { metabolic_error[j] += (j - index) * Common::Metabolic_Error_Protein_Slope * concentration; } else { metabolic_error[j] += concentration; } } } } sum_metabolic_error = 0; for (int i = 0; i < Common::Metabolic_Error_Precision; i++) { sum_metabolic_error+=std::abs(gridcell_->environment_target[i]-metabolic_error[i]); } sum_metabolic_error=sum_metabolic_error/Common::Metabolic_Error_Precision; fitness_ = std::exp(-Common::Fitness_Selection_Pressure*sum_metabolic_error); } void Organism::mutate() { old = this; std::binomial_distribution<int> dis_switch(dna_->bp_list_.size(),Common::Mutation_Rate); std::binomial_distribution<int> dis_insertion(dna_->bp_list_.size(),Common::Mutation_Rate); std::binomial_distribution<int> dis_deletion(dna_->bp_list_.size(),Common::Mutation_Rate); std::binomial_distribution<int> dis_duplication(dna_->bp_list_.size(),Common::Mutation_Rate); std::binomial_distribution<int> dis_modification(dna_->bp_list_.size(),Common::Mutation_Rate); int nb_switch = dis_switch(gridcell_->float_gen_); int nb_insertion = dis_insertion(gridcell_->float_gen_); int nb_deletion = dis_deletion(gridcell_->float_gen_); int nb_duplication = dis_duplication(gridcell_->float_gen_); int nb_modification = dis_modification(gridcell_->float_gen_); std::uniform_int_distribution<uint32_t> dis_position(0,dna_->bp_list_.size()); for (int i = 0; i < nb_deletion; i++) { int deletion_pos = dis_position(gridcell_->float_gen_); while (deletion_pos >= dna_->bp_list_.size()) { deletion_pos = dis_position(gridcell_->float_gen_); } dna_->bp_list_.erase(dna_->bp_list_.begin() + deletion_pos); } for (int i = 0; i < nb_switch; i++) { int switch_pos_1 = dis_position(gridcell_->float_gen_); while (switch_pos_1 >= dna_->bp_list_.size()) { switch_pos_1 = dis_position(gridcell_->float_gen_); } int switch_pos_2 = dis_position(gridcell_->float_gen_); while (switch_pos_2 >= dna_->bp_list_.size()) { switch_pos_2 = dis_position(gridcell_->float_gen_); } BP* tmp = dna_->bp_list_[switch_pos_1]; dna_->bp_list_[switch_pos_1] = dna_->bp_list_[switch_pos_2]; dna_->bp_list_[switch_pos_2] = tmp; } for (int i = 0; i < nb_duplication; i++) { int duplication_pos = dis_position(gridcell_->float_gen_); while (duplication_pos >= dna_->bp_list_.size()) { duplication_pos = dis_position(gridcell_->float_gen_); } int where_to_duplicate = dis_position(gridcell_->float_gen_); while (where_to_duplicate >= dna_->bp_list_.size()) { where_to_duplicate = dis_position(gridcell_->float_gen_); } dna_->bp_list_.insert(dna_->bp_list_.begin()+where_to_duplicate, new BP(dna_->bp_list_[duplication_pos])); } for (int i = 0; i < nb_insertion; i++) { int insertion_pos = dis_position(gridcell_->float_gen_); while (insertion_pos >= dna_->bp_list_.size()) { insertion_pos = dis_position(gridcell_->float_gen_); } dna_->insert_a_BP(insertion_pos,gridcell_); } for (int i = 0; i < nb_modification; i++) { int modification_pos = dis_position(gridcell_->float_gen_); while (modification_pos >= dna_->bp_list_.size()) { modification_pos = dis_position(gridcell_->float_gen_); } dna_->modify_bp(modification_pos,gridcell_); } } Organism* Organism::divide() { Organism* new_org = new Organism(this); return new_org; } Organism::Organism(Organism* organism) { dna_ = new DNA(organism->dna_); for(auto prot : organism->protein_list_map_) { Protein* new_prot = new Protein(prot.second); new_prot->concentration_ = new_prot->concentration_/2; prot.second->concentration_ = prot.second->concentration_/2; } } Organism::~Organism() { for (auto rna : rna_list_) delete rna; delete dna_; rna_produce_protein_.clear(); for (auto prot : protein_list_map_) { delete prot.second; } protein_fitness_list_.clear(); protein_TF_list_.clear(); protein_poison_list_.clear(); protein_antipoison_list_.clear(); protein_list_map_.clear(); for (auto pump : pump_list_) { delete pump; } pump_list_.clear(); for (auto move : move_list_) { delete move; } move_list_.clear(); }
33.99568
148
0.621283
b6b5fe4613ca8b0c02dd1317846a4aa778714896
8,263
cxx
C++
Temporary/itkDijkstrasAlgorithm.cxx
KevinScholtes/ANTsX
5462269c0c32e5d65560bae4014c5a05cb02588d
[ "BSD-3-Clause" ]
null
null
null
Temporary/itkDijkstrasAlgorithm.cxx
KevinScholtes/ANTsX
5462269c0c32e5d65560bae4014c5a05cb02588d
[ "BSD-3-Clause" ]
null
null
null
Temporary/itkDijkstrasAlgorithm.cxx
KevinScholtes/ANTsX
5462269c0c32e5d65560bae4014c5a05cb02588d
[ "BSD-3-Clause" ]
1
2019-10-06T07:31:58.000Z
2019-10-06T07:31:58.000Z
/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) =========================================================================*/ #ifndef _itkDijkstrasAlgorithm_cxx_ #define _itkDijkstrasAlgorithm_cxx_ #include "itkDijkstrasAlgorithm.h" namespace itk { template <typename TGraphSearchNode> DijkstrasAlgorithm<TGraphSearchNode>::DijkstrasAlgorithm() { m_Graph = GraphType::New(); m_QS = DijkstrasAlgorithmQueue<TGraphSearchNode>::New(); m_MaxCost = vnl_huge_val(m_MaxCost); // not defined for unsigned char this->m_TotalCost = 0; }; template <typename TGraphSearchNode> void DijkstrasAlgorithm<TGraphSearchNode>::SetGraphSize(GraphSizeType Sz) { for( int i = 0; i < GraphDimension; i++ ) { m_GraphSize[i] = Sz[i]; } } template <typename TGraphSearchNode> void DijkstrasAlgorithm<TGraphSearchNode>::InitializeGraph() { m_GraphRegion.SetSize( m_GraphSize ); m_Graph->SetLargestPossibleRegion( m_GraphRegion ); m_Graph->SetRequestedRegion( m_GraphRegion ); m_Graph->SetBufferedRegion( m_GraphRegion ); m_Graph->Allocate(); GraphIteratorType GraphIterator( m_Graph, m_GraphRegion ); GraphIterator.GoToBegin(); NodeLocationType loc; while( !GraphIterator.IsAtEnd() ) { typename GraphSearchNode<PixelType, CoordRep, GraphDimension>::Pointer G = nullptr; GraphIterator.Set(G); ++GraphIterator; /* m_GraphIndex = GraphIterator.GetIndex(); //std::cout << " allocating " << m_GraphIndex << std::endl; ///GraphSearchNode<PixelType,CoordRep,GraphDimension>::Pointer G= G=TGraphSearchNode::New(); G->SetUnVisited(); G->SetTotalCost(m_MaxCost); for (int i=0; i<GraphDimension; i++) loc[i]=m_GraphIndex[i]; G->SetLocation(loc); G->SetPredecessor(nullptr); m_Graph->SetPixel(m_GraphIndex,G);*/ m_Graph->SetPixel( GraphIterator.GetIndex(), nullptr); // USE IF POINTER IMAGE defines visited } m_SearchFinished = false; } template <typename TGraphSearchNode> void DijkstrasAlgorithm<TGraphSearchNode>::InitializeQueue() { int n = m_QS->m_SourceNodes.size(); GraphIteratorType GraphIterator( m_Graph, m_GraphRegion ); m_GraphSize = m_Graph->GetLargestPossibleRegion().GetSize(); GraphIterator.GoToBegin(); m_GraphIndex = GraphIterator.GetIndex(); NodeLocationType loc; // make sure the graph contains the right pointers for( int i = 0; i < n; i++ ) { typename GraphSearchNode<PixelType, CoordRep, GraphDimension>::Pointer G = m_QS->m_SourceNodes[i]; G->SetPredecessor(G); m_QS->m_Q.push(G); loc = G->GetLocation(); for( int d = 0; d < GraphDimension; d++ ) { m_GraphIndex[d] = (long int)(loc[d] + 0.5); } m_Graph->SetPixel(m_GraphIndex, G); } for( int i = 0; i < m_QS->m_SinkNodes.size(); i++ ) { typename GraphSearchNode<PixelType, CoordRep, GraphDimension>::Pointer G = m_QS->m_SinkNodes[i]; G->SetPredecessor(nullptr); loc = G->GetLocation(); for( int d = 0; d < GraphDimension; d++ ) { m_GraphIndex[d] = (long)loc[d]; } m_Graph->SetPixel(m_GraphIndex, G); } m_SearchFinished = false; if( m_EdgeTemplate.empty() ) { InitializeEdgeTemplate(); } } template <typename TGraphSearchNode> void DijkstrasAlgorithm<TGraphSearchNode>::InitializeEdgeTemplate (vector<unsigned int> UserEdgeTemplate, unsigned int R) { for( int i = 0; i < GraphDimension; i++ ) { m_Radius[i] = R; } m_EdgeTemplate = UserEdgeTemplate; } template <typename TGraphSearchNode> void DijkstrasAlgorithm<TGraphSearchNode>::InitializeEdgeTemplate() { int MaxIndex = 1; for( int i = 0; i < GraphDimension; i++ ) { m_Radius[i] = 1; } for( int i = 0; i < GraphDimension; i++ ) { MaxIndex = MaxIndex * (2 * m_Radius[i] + 1); } MaxIndex = MaxIndex - 1; // int Center = MaxIndex/2; for( unsigned int i = 0; i <= MaxIndex; i++ ) { // if (i != Center) m_EdgeTemplate.insert(m_EdgeTemplate.end(), i); } } /** * Compute the local cost using Manhattan distance. */ template <typename TGraphSearchNode> typename DijkstrasAlgorithm<TGraphSearchNode>:: PixelType DijkstrasAlgorithm<TGraphSearchNode>::LocalCost() { return 1.0; // manhattan distance }; template <typename TGraphSearchNode> bool DijkstrasAlgorithm<TGraphSearchNode>::TerminationCondition() { if( !m_QS->m_SinkNodes.empty() ) { if( m_NeighborNode == m_QS->m_SinkNodes[0] && !m_SearchFinished ) { m_SearchFinished = true; m_NeighborNode->SetPredecessor(m_CurrentNode); } } else { m_SearchFinished = true; } return m_SearchFinished; } template <typename TGraphSearchNode> void DijkstrasAlgorithm<TGraphSearchNode>::SearchEdgeSet() { // std::cout << " SES 0 " << std::endl; GraphNeighborhoodIteratorType GHood(m_Radius, m_Graph, m_Graph->GetRequestedRegion() ); GraphNeighborhoodIndexType GNI; // std::cout << " SES 1 " << std::endl; for( unsigned int i = 0; i < GraphDimension; i++ ) { // std::cout << " SES 2 " << std::endl; GNI[i] = (long)(m_CurrentNode->GetLocation()[i] + 0.5); } // std::cout << " SES 3 " << std::endl; GHood.SetLocation(GNI); for( unsigned int dd = 0; dd < GraphDimension; dd++ ) { if( GNI[dd] < 2 || GNI[dd] > (unsigned long)(m_GraphSize[dd] - 2) ) { return; } } for( unsigned int i = 0; i < m_EdgeTemplate.size(); i++ ) { // std::cout << " SES 4 " << std::endl; // std::cout << " ET " << m_EdgeTemplate[i] << " RAD " << m_Radius << " ind " << // GHood.GetIndex(m_EdgeTemplate[i]) // << std::endl; if( !GHood.GetPixel(m_EdgeTemplate[i]) ) // std::cout << " OK " << std::endl; // /else { // std::cout << " NOT OK " <<std::endl; GraphNeighborhoodIndexType ind = GHood.GetIndex(m_EdgeTemplate[i]); typename TGraphSearchNode::Pointer G = TGraphSearchNode::New(); G->SetUnVisited(); G->SetTotalCost(m_MaxCost); NodeLocationType loc; for( int j = 0; j < GraphDimension; j++ ) { loc[j] = ind[j]; } G->SetLocation(loc); G->SetPredecessor(m_CurrentNode); m_Graph->SetPixel(ind, G); } m_NeighborNode = GHood.GetPixel(m_EdgeTemplate[i]); // std::cout << "DA i " << i << " position " << m_NeighborNode->GetLocation() << endl; this->TerminationCondition(); if( !m_SearchFinished && m_CurrentNode != m_NeighborNode && !m_NeighborNode->GetDelivered() ) { m_NewCost = m_CurrentCost + LocalCost(); CheckNodeStatus(); } } } template <typename TGraphSearchNode> void DijkstrasAlgorithm<TGraphSearchNode>::CheckNodeStatus() // checks a graph neighbor's status { if( !m_NeighborNode->GetVisited() ) { // set the cost and put into the queue m_NeighborNode->SetTotalCost(m_NewCost); m_NeighborNode->SetPredecessor(m_CurrentNode); m_NeighborNode->SetVisited(); m_QS->m_Q.push(m_NeighborNode); } else if( m_NewCost < m_NeighborNode->GetTotalCost() ) { m_NeighborNode->SetTotalCost(m_NewCost); m_NeighborNode->SetPredecessor(m_CurrentNode); m_QS->m_Q.push(m_NeighborNode); } } template <typename TGraphSearchNode> void DijkstrasAlgorithm<TGraphSearchNode>::FindPath() { if( m_QS->m_SourceNodes.empty() ) { std::cout << "ERROR !! DID NOT SET SOURCE!!\n"; return; } while( !m_SearchFinished && !m_QS->m_Q.empty() ) { m_CurrentNode = m_QS->m_Q.top(); m_CurrentCost = m_CurrentNode->GetTotalCost(); m_QS->m_Q.pop(); if( !m_CurrentNode->GetDelivered() ) { m_QS->IncrementTimer(); this->SearchEdgeSet(); this->m_TotalCost += m_CurrentNode->GetTotalCost(); // if ( (m_CurrentNode->GetTimer() % 1.e5 ) == 0) // std::cout << " searched " << m_CurrentNode->GetTimer() << " \n"; } m_CurrentNode->SetDelivered(); } // end of while m_NumberSearched = (unsigned long) m_QS->GetTimer(); std::cout << "Done with find path " << " Q size " << m_QS->m_Q.size() << " num searched " << m_NumberSearched << " \n"; return; } } // end namespace itk #endif
29.510714
102
0.634394
b6b72c1630b812386588a73fbd70d8cc1da09715
368
cpp
C++
5 Star 30 Days Of Code/Day 2 Operators.cpp
TheCodeAlpha26/Hackerrank-Demystified
03713a8f3a05e5d6dfed6f6808b06340558e2310
[ "Apache-2.0" ]
6
2021-04-26T17:09:54.000Z
2021-07-08T17:36:16.000Z
5 Star 30 Days Of Code/Day 2 Operators.cpp
TheCodeAlpha26/Hackerrank-Demystified
03713a8f3a05e5d6dfed6f6808b06340558e2310
[ "Apache-2.0" ]
null
null
null
5 Star 30 Days Of Code/Day 2 Operators.cpp
TheCodeAlpha26/Hackerrank-Demystified
03713a8f3a05e5d6dfed6f6808b06340558e2310
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void solve(double mc, int tp, int tx) { double t=0.01*mc*(100+tx+tp); printf("%.0f",t); //.0f to set precision (to nearest integer) } int main() { double meal_cost; cin >> meal_cost; int tip_percent,tp; cin >> tip_percent>>tp; solve(meal_cost, tip_percent, tp); return 0; }
23
78
0.597826
b6b7a543f82a8096c663767628acda3aa22013b8
22,994
cpp
C++
code_reading/oceanbase-master/src/storage/ob_sstable_rowkey_helper.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/storage/ob_sstable_rowkey_helper.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/storage/ob_sstable_rowkey_helper.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
1
2020-10-18T12:59:31.000Z
2020-10-18T12:59:31.000Z
/** * Copyright (c) 2021 OceanBase * OceanBase CE is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #define USING_LOG_PREFIX STORAGE #include "ob_sstable_rowkey_helper.h" #include "lib/container/ob_fixed_array_iterator.h" #include "share/ob_get_compat_mode.h" #include "storage/ob_sstable.h" namespace oceanbase { using namespace common; using namespace blocksstable; using namespace share; using namespace share::schema; namespace storage { /* *ObRowkeyObjComparer */ // temporarily keep if in compare func // remove if to build more compare funcs array when perf critical int ObRowkeyObjComparer::sstable_number_cmp_func(const ObObj& obj1, const ObObj& obj2, const ObCompareCtx& cmp_ctx) { int cmp = 0; UNUSED(cmp_ctx); if (OB_UNLIKELY(!obj1.is_number() || !obj2.is_number())) { LOG_ERROR("unexpected error. mismatch function for comparison", K(obj1), K(obj2)); right_to_die_or_duty_to_live(); } else if (OB_LIKELY(((is_smallint_number(obj1) && is_smallint_number(obj2))))) { cmp = obj1.v_.nmb_digits_[0] - obj2.v_.nmb_digits_[0]; cmp = cmp > 0 ? ObObjCmpFuncs::CR_GT : cmp < 0 ? ObObjCmpFuncs::CR_LT : ObObjCmpFuncs::CR_EQ; } else { cmp = number::ObNumber::compare(obj1.nmb_desc_, obj1.v_.nmb_digits_, obj2.nmb_desc_, obj2.v_.nmb_digits_); } return cmp; } int ObRowkeyObjComparer::sstable_collation_free_cmp_func( const ObObj& obj1, const ObObj& obj2, const ObCompareCtx& cmp_ctx) { int cmp = 0; UNUSED(cmp_ctx); if (OB_UNLIKELY( CS_TYPE_COLLATION_FREE != obj2.get_collation_type() || obj1.get_collation_type() != obj2.get_collation_type() //|| obj1.get_type() != obj2.get_type() //|| !obj1.is_varchar_or_char() )) { STORAGE_LOG(ERROR, "unexpected error, invalid argument", K(obj1), K(obj2)); right_to_die_or_duty_to_live(); } else { const int32_t lhs_len = obj1.get_val_len(); const int32_t rhs_len = obj2.get_val_len(); const int32_t cmp_len = MIN(lhs_len, rhs_len); cmp = MEMCMP(obj1.get_string_ptr(), obj2.get_string_ptr(), cmp_len); if (0 == cmp) { if (lhs_len != rhs_len) { // in mysql mode, we should strip all trailing blanks before comparing two strings const int32_t left_len = (lhs_len > cmp_len) ? lhs_len - cmp_len : rhs_len - cmp_len; const char* ptr = (lhs_len > cmp_len) ? obj1.get_string_ptr() : obj2.get_string_ptr(); const unsigned char* uptr = reinterpret_cast<const unsigned char*>(ptr + cmp_len); // int32_t is always capable of stroing the max lenth of varchar or char for (int32_t i = 0; i < left_len; ++i) { if (*(uptr + i) != ' ') { // special behavior in mysql mode, 'a\1 < a' and 'ab > a' if (*(uptr + i) < ' ') { cmp = lhs_len > cmp_len ? ObObjCmpFuncs::CR_LT : ObObjCmpFuncs::CR_GT; } else { cmp = lhs_len > cmp_len ? ObObjCmpFuncs::CR_GT : ObObjCmpFuncs::CR_LT; } break; } } } } else { cmp = cmp > 0 ? ObObjCmpFuncs::CR_GT : ObObjCmpFuncs::CR_LT; } } return cmp; } int ObRowkeyObjComparer::sstable_oracle_collation_free_cmp_func( const ObObj& obj1, const ObObj& obj2, const ObCompareCtx& cmp_ctx) { int cmp = 0; UNUSED(cmp_ctx); if (OB_UNLIKELY( CS_TYPE_COLLATION_FREE != obj2.get_collation_type() || obj1.get_collation_type() != obj2.get_collation_type() //|| obj1.get_type() != obj2.get_type() //|| !obj1.is_varchar_or_char() )) { STORAGE_LOG(ERROR, "unexpected error, invalid argument", K(obj1), K(obj2)); right_to_die_or_duty_to_live(); } else { const int32_t lhs_len = obj1.get_val_len(); const int32_t rhs_len = obj2.get_val_len(); const int32_t cmp_len = MIN(lhs_len, rhs_len); cmp = MEMCMP(obj1.get_string_ptr(), obj2.get_string_ptr(), cmp_len); if (0 == cmp) { // in oracle mode, we should consider the trailing blanks during comparing two varchar if (obj1.is_varying_len_char_type()) { if (lhs_len != rhs_len) { cmp = lhs_len > cmp_len ? ObObjCmpFuncs::CR_GT : ObObjCmpFuncs::CR_LT; } } else { // in oracle mode, we should strip all trailing blanks before comparing two char const int32_t left_len = (lhs_len > cmp_len) ? lhs_len - cmp_len : rhs_len - cmp_len; const char* ptr = (lhs_len > cmp_len) ? obj1.get_string_ptr() : obj2.get_string_ptr(); const unsigned char* uptr = reinterpret_cast<const unsigned char*>(ptr + cmp_len); // int32_t is always capable of stroing the max lenth of varchar or char for (int32_t i = 0; i < left_len; ++i) { if (*(uptr + i) != ' ') { cmp = lhs_len > cmp_len ? ObObjCmpFuncs::CR_GT : ObObjCmpFuncs::CR_LT; break; } } } } else { cmp = cmp > 0 ? ObObjCmpFuncs::CR_GT : ObObjCmpFuncs::CR_LT; } } return cmp; } ObRowkeyObjComparer::ObRowkeyObjComparer() : cmp_func_(NULL), cmp_ctx_(ObMaxType, CS_TYPE_INVALID, false, INVALID_TZ_OFF, NULL_FIRST), is_collation_free_(false), type_(COMPARER_MYSQL) {} void ObRowkeyObjComparer::reset() { cmp_func_ = NULL; cmp_ctx_.cmp_cs_type_ = CS_TYPE_INVALID; is_collation_free_ = false; } int ObRowkeyObjComparer::init_compare_func(const ObObjMeta& obj_meta) { int ret = OB_SUCCESS; if (OB_UNLIKELY(!obj_meta.is_valid())) { ret = OB_INVALID_ARGUMENT; STORAGE_LOG(WARN, "Invalid argument to init compare func", K(obj_meta), K(ret)); } else { reset(); if (obj_meta.is_number()) { cmp_func_ = sstable_number_cmp_func; } else { ObObjTypeClass obj_tc = obj_meta.get_type_class(); if (OB_FAIL(ObObjCmpFuncs::get_cmp_func(obj_tc, obj_tc, CO_CMP, cmp_func_))) { STORAGE_LOG(WARN, "Failed to find rowkey obj cmp func", K(obj_meta), K(obj_tc), K(ret)); } else if (OB_ISNULL(cmp_func_)) { ret = OB_ERR_UNEXPECTED; STORAGE_LOG(WARN, "Failed to find rowkey cmp func", K(ret)); } } if (OB_SUCC(ret)) { cmp_ctx_.cmp_cs_type_ = obj_meta.get_collation_type(); is_collation_free_ = false; } } return ret; } int ObRowkeyObjComparer::init_compare_func_collation_free(const common::ObObjMeta& obj_meta) { int ret = OB_SUCCESS; if (OB_UNLIKELY(!obj_meta.is_valid())) { ret = OB_INVALID_ARGUMENT; STORAGE_LOG(WARN, "Invalid argument to init collation free compare func", K(obj_meta), K(ret)); } else if (obj_meta.is_collation_free_compatible()) { reset(); cmp_func_ = sstable_collation_free_cmp_func; cmp_ctx_.cmp_cs_type_ = obj_meta.get_collation_type(); is_collation_free_ = true; } else if (OB_FAIL(init_compare_func(obj_meta))) { STORAGE_LOG(WARN, "Failed to init compare func", K(obj_meta), K(ret)); } return ret; } /* *ObRowkeyObjComparerOracle */ int ObRowkeyObjComparerOracle::init_compare_func_collation_free(const common::ObObjMeta& obj_meta) { int ret = OB_SUCCESS; // TODO oracle mode need add raw type future if (OB_UNLIKELY(!obj_meta.is_valid() || !obj_meta.is_collation_free_compatible())) { ret = OB_INVALID_ARGUMENT; STORAGE_LOG(WARN, "Invalid argument to init collation free compare func", K(obj_meta), K(ret)); } else { reset(); cmp_func_ = sstable_oracle_collation_free_cmp_func; cmp_ctx_.cmp_cs_type_ = obj_meta.get_collation_type(); is_collation_free_ = true; } return ret; } /* *ObSSTableRowkeyHelper */ ObSSTableRowkeyHelper::ObSSTableRowkeyHelper() : endkeys_(), collation_free_endkeys_(), cmp_funcs_(), collation_free_cmp_funcs_(), rowkey_column_cnt_(0), column_type_array_(NULL), sstable_(nullptr), exist_collation_free_(false), use_cmp_nullsafe_(false), is_oracle_mode_(false), is_inited_(false) {} void ObSSTableRowkeyHelper::reset() { endkeys_.reset(); collation_free_endkeys_.reset(); cmp_funcs_.reset(); collation_free_cmp_funcs_.reset(); rowkey_column_cnt_ = 0; column_type_array_ = NULL; sstable_ = nullptr; exist_collation_free_ = false; use_cmp_nullsafe_ = false; is_oracle_mode_ = false; is_inited_ = false; } int ObSSTableRowkeyHelper::get_macro_block_meta( const MacroBlockId& macro_id, ObFullMacroBlockMeta& macro_meta, const int64_t schema_rowkey_column_cnt) { int ret = OB_SUCCESS; if (!macro_id.is_valid() || schema_rowkey_column_cnt <= 0) { ret = OB_INVALID_ARGUMENT; STORAGE_LOG(WARN, "Invalid argument to get macro block meta", K(macro_id), K(schema_rowkey_column_cnt), K(ret)); } else if (OB_FAIL(sstable_->get_meta(macro_id, macro_meta))) { STORAGE_LOG(WARN, "fail to get meta", K(ret), K(macro_id)); } else if (!macro_meta.is_valid()) { ret = OB_ERR_SYS; STORAGE_LOG(WARN, "Unexpected null macro meta", K(ret)); } else if (OB_ISNULL(macro_meta.meta_->endkey_) || OB_ISNULL(macro_meta.schema_->column_type_array_)) { ret = OB_ERR_SYS; STORAGE_LOG(WARN, "Unexpected null data macro endkey", K(macro_meta), K(ret)); } else if (OB_UNLIKELY(macro_meta.meta_->rowkey_column_number_ < schema_rowkey_column_cnt)) { ret = OB_ERR_UNEXPECTED; STORAGE_LOG(WARN, "Unexpected mis matched rowkey column number", K(macro_meta.meta_->rowkey_column_number_), K(schema_rowkey_column_cnt), K(ret)); } return ret; } int ObSSTableRowkeyHelper::build_macro_endkeys(const ObIArray<MacroBlockId>& macro_ids, ObIAllocator& allocator, const int64_t schema_rowkey_column_cnt, const bool need_build_collation_free) { int ret = OB_SUCCESS; if (OB_UNLIKELY(macro_ids.count() == 0 || schema_rowkey_column_cnt <= 0)) { ret = OB_INVALID_ARGUMENT; STORAGE_LOG(WARN, "Invalid argument to build macro endkeys", K(macro_ids), K(schema_rowkey_column_cnt), K(ret)); } else { int64_t macro_block_count = macro_ids.count(); ObFullMacroBlockMeta full_meta; ObStoreRowkey rowkey; endkeys_.set_allocator(&allocator); endkeys_.set_capacity(static_cast<uint32_t>(macro_block_count)); for (int64_t i = 0; OB_SUCC(ret) && i < macro_block_count; i++) { if (OB_FAIL(get_macro_block_meta(macro_ids.at(i), full_meta, schema_rowkey_column_cnt))) { STORAGE_LOG(WARN, "Failed to get macro block meta", K(i), K(ret)); } else { const ObMacroBlockMetaV2* macro_meta = full_meta.meta_; rowkey.assign(macro_meta->endkey_, macro_meta->rowkey_column_number_); // TODO consider column order if (rowkey.contains_min_or_max_obj() || (!use_cmp_nullsafe_ && rowkey.contains_null_obj())) { ret = OB_ERR_SYS; STORAGE_LOG(WARN, "Unexpected max or min macro endkey", K(rowkey), K(ret)); } else if (0 == i) { rowkey_column_cnt_ = macro_meta->rowkey_column_number_; column_type_array_ = full_meta.schema_->column_type_array_; exist_collation_free_ = false; if (need_build_collation_free) { for (int64_t i = 0; !exist_collation_free_ && i < rowkey_column_cnt_; i++) { if (column_type_array_[i].is_collation_free_compatible()) { exist_collation_free_ = true; } } if (exist_collation_free_) { collation_free_endkeys_.set_allocator(&allocator); collation_free_endkeys_.set_capacity(static_cast<uint32_t>(macro_block_count)); } } } if (OB_FAIL(ret)) { } else if (OB_FAIL(endkeys_.push_back(rowkey))) { STORAGE_LOG(WARN, "Failed to push back macroblock endkey", K(rowkey), K(ret)); } else if (exist_collation_free_) { if (OB_ISNULL(macro_meta->collation_free_endkey_)) { // defend code to check null collation free endkey for (int64_t i = 0; i < rowkey_column_cnt_; i++) { // original varchar or char should be null now if (rowkey.get_obj_ptr()[i].is_collation_free_compatible()) { ret = OB_ERR_UNEXPECTED; STORAGE_LOG(WARN, "Unexpected null collation freekey with valid rowkey", K(i), K(*macro_meta), K(ret)); } } } else { rowkey.assign(macro_meta->collation_free_endkey_, macro_meta->rowkey_column_number_); } if (OB_SUCC(ret)) { if (OB_FAIL(collation_free_endkeys_.push_back(rowkey))) { STORAGE_LOG(WARN, "Failed to push back macroblock endkey", K(rowkey), K(ret)); } } } } } if (OB_SUCC(ret)) { if (endkeys_.count() != macro_block_count || (exist_collation_free_ && collation_free_endkeys_.count() != macro_block_count)) { ret = OB_ERR_UNEXPECTED; STORAGE_LOG(WARN, "Unexpected macro block endkeys count", K(macro_block_count), K_(exist_collation_free), K(endkeys_.count()), K(collation_free_endkeys_.count()), K(ret)); } } } return ret; } template <typename T> int ObSSTableRowkeyHelper::make_rowkey_cmp_funcs(ObIAllocator& allocator) { int ret = OB_SUCCESS; if (OB_ISNULL(column_type_array_) || rowkey_column_cnt_ <= 0) { ret = OB_ERR_UNEXPECTED; STORAGE_LOG(WARN, "Unexpected null column type array or rowkey column cnt", KP_(column_type_array), K_(rowkey_column_cnt), K(ret)); } else { void* buf = NULL; T* cmp_funcs = NULL; cmp_funcs_.set_allocator(&allocator); cmp_funcs_.set_capacity(rowkey_column_cnt_); if (OB_ISNULL(buf = allocator.alloc(sizeof(T) * rowkey_column_cnt_))) { ret = OB_ALLOCATE_MEMORY_FAILED; STORAGE_LOG(WARN, "Failed to allocate memory for cmopare func", K_(rowkey_column_cnt), K(ret)); } else { cmp_funcs = reinterpret_cast<T*>(new (buf) T[rowkey_column_cnt_]); for (int64_t i = 0; OB_SUCC(ret) && i < rowkey_column_cnt_; i++) { if (OB_FAIL(cmp_funcs[i].init_compare_func(column_type_array_[i]))) { STORAGE_LOG(WARN, "Failed to init compare func", K(i), K(ret)); } else if (OB_FAIL(cmp_funcs_.push_back(&cmp_funcs[i]))) { STORAGE_LOG(WARN, "Failed to push back compare func", K(i), K(ret)); } } } if (OB_SUCC(ret) && exist_collation_free_) { collation_free_cmp_funcs_.set_allocator(&allocator); collation_free_cmp_funcs_.set_capacity(rowkey_column_cnt_); if (OB_ISNULL(buf = allocator.alloc(sizeof(T) * rowkey_column_cnt_))) { ret = OB_ALLOCATE_MEMORY_FAILED; STORAGE_LOG(WARN, "Failed to allocate memory for cmopare func", K_(rowkey_column_cnt), K(ret)); } else { cmp_funcs = reinterpret_cast<T*>(new (buf) T[rowkey_column_cnt_]); for (int64_t i = 0; OB_SUCC(ret) && i < rowkey_column_cnt_; i++) { if (column_type_array_[i].is_collation_free_compatible()) { if (OB_FAIL(cmp_funcs[i].init_compare_func_collation_free(column_type_array_[i]))) { STORAGE_LOG(WARN, "Failed to init compare func", K(i), K(ret)); } } else if (OB_FAIL(cmp_funcs[i].init_compare_func(column_type_array_[i]))) { STORAGE_LOG(WARN, "Failed to init compare func", K(i), K(ret)); } if (OB_SUCC(ret) && OB_FAIL(collation_free_cmp_funcs_.push_back(&cmp_funcs[i]))) { STORAGE_LOG(WARN, "Failed to push back compare func", K(i), K(ret)); } } } } } return ret; } int ObSSTableRowkeyHelper::init(const ObIArray<MacroBlockId>& macro_ids, const ObSSTableMeta& sstable_meta, const bool need_build_collation_free, ObSSTable* sstable, ObIAllocator& allocator) { int ret = OB_SUCCESS; reset(); if (OB_UNLIKELY(!sstable_meta.is_valid()) || OB_ISNULL(sstable)) { ret = OB_INVALID_ARGUMENT; STORAGE_LOG(WARN, "Invalid argument to init sstable rowkey helper", K(sstable_meta), KP(sstable), K(ret)); } else if (macro_ids.count() > 0) { sstable_ = sstable; ObWorker::CompatMode mode; if (OB_FAIL(ObCompatModeGetter::get_tenant_mode(extract_tenant_id(sstable_meta.index_id_), mode))) { STORAGE_LOG(WARN, "Failed to get compat mode", K(sstable_meta), K(ret)); // rewrite ret for caller deal with ret = OB_TENANT_NOT_EXIST; } else { is_oracle_mode_ = (mode == ObWorker::CompatMode::ORACLE) && !is_sys_table(sstable_meta.index_id_); use_cmp_nullsafe_ = ObTableSchema::is_index_table(static_cast<ObTableType>(sstable_meta.table_type_)) || TPKM_NEW_NO_PK == sstable_meta.table_mode_.pk_mode_; if (OB_FAIL(build_macro_endkeys( macro_ids, allocator, sstable_meta.rowkey_column_count_, need_build_collation_free))) { STORAGE_LOG(WARN, "Failed to build macro endkeys", K(ret)); } else if (OB_FAIL(build_rowkey_cmp_funcs(allocator))) { STORAGE_LOG(WARN, "Failed to build endkey cmp funcs", K(ret)); } else { is_inited_ = true; } } } return ret; } int ObSSTableRowkeyHelper::build_rowkey_cmp_funcs(ObIAllocator& allocator) { int ret = OB_SUCCESS; if (OB_ISNULL(column_type_array_) || rowkey_column_cnt_ <= 0) { ret = OB_ERR_UNEXPECTED; STORAGE_LOG(WARN, "Unexpected null column type array or rowkey column cnt", KP_(column_type_array), K_(rowkey_column_cnt), K(ret)); } else if (is_oracle_mode_ && use_cmp_nullsafe_) { ret = make_rowkey_cmp_funcs<ObRowkeyObjComparerNullsafeOracle>(allocator); } else if (is_oracle_mode_) { ret = make_rowkey_cmp_funcs<ObRowkeyObjComparerOracle>(allocator); } else if (use_cmp_nullsafe_) { ret = make_rowkey_cmp_funcs<ObRowkeyObjComparerNullsafeMysql>(allocator); } else { ret = make_rowkey_cmp_funcs<ObRowkeyObjComparer>(allocator); } return ret; } int ObSSTableRowkeyHelper::locate_block_idx_(const ObExtStoreRowkey& ext_rowkey, const int64_t cmp_rowkey_col_cnt, const bool use_lower_bound, const int64_t last_block_idx, int64_t& block_idx) { int ret = OB_SUCCESS; if (OB_UNLIKELY(cmp_rowkey_col_cnt > ext_rowkey.get_store_rowkey().get_obj_cnt())) { ret = OB_INVALID_ARGUMENT; STORAGE_LOG(WARN, "Invalid argument to locate block index", K(ext_rowkey), K(cmp_rowkey_col_cnt), K(ret)); } else { RowkeyArray* rowkey_array = NULL; const ObStoreRowkey* cmp_rowkey = NULL; RowkeyCmpFuncArray* cmp_funcs = NULL; block_idx = -1; if (!exist_collation_free_) { cmp_rowkey = &(ext_rowkey.get_store_rowkey()); rowkey_array = &endkeys_; cmp_funcs = &cmp_funcs_; } else { bool use_collation_free = false; if (OB_FAIL(ext_rowkey.check_use_collation_free(!exist_collation_free_, use_collation_free))) { STORAGE_LOG(WARN, "Fail to check use collation free, ", K(ret), K(ext_rowkey)); } else if (use_collation_free && collation_free_cmp_funcs_.count() > 0) { cmp_rowkey = &(ext_rowkey.get_collation_free_store_rowkey()); rowkey_array = &collation_free_endkeys_; cmp_funcs = &collation_free_cmp_funcs_; } else { cmp_rowkey = &(ext_rowkey.get_store_rowkey()); rowkey_array = &endkeys_; cmp_funcs = &cmp_funcs_; use_collation_free = false; } } if (OB_SUCC(ret)) { if (cmp_rowkey->get_obj_cnt() == rowkey_column_cnt_ && last_block_idx >= 0 && last_block_idx < rowkey_array->count()) { // the rowkey may be in the same macro block, so check last macro block first if (compare_nullsafe(rowkey_array->at(last_block_idx), *cmp_rowkey, *cmp_funcs) >= 0) { if (0 == last_block_idx || compare_nullsafe(rowkey_array->at(last_block_idx - 1), *cmp_rowkey, *cmp_funcs) < 0) { block_idx = last_block_idx; } } } if (-1 == block_idx) { // binary search RowkeyComparor comparor(*cmp_funcs, cmp_rowkey_col_cnt < rowkey_column_cnt_); ObStoreRowkey refine_cmp_rowkey((const_cast<ObStoreRowkey*>(cmp_rowkey))->get_obj_ptr(), cmp_rowkey_col_cnt); RowkeyArray::iterator begin = rowkey_array->begin(); RowkeyArray::iterator end = rowkey_array->end(); RowkeyArray::iterator iter; if (use_lower_bound) { iter = std::lower_bound(begin, end, &refine_cmp_rowkey, comparor); } else { iter = std::upper_bound(begin, end, &refine_cmp_rowkey, comparor); } if (iter < end) { block_idx = iter - begin; } } } } return ret; } int ObSSTableRowkeyHelper::locate_block_idx_index( const ObExtStoreRowkey& ext_rowkey, const int64_t last_block_idx, int64_t& block_idx) { int ret = OB_SUCCESS; if (OB_UNLIKELY(!is_inited_)) { ret = OB_NOT_INIT; STORAGE_LOG(WARN, "ObSSTableRowkeyHelper is not inited", K(ret)); } else if (OB_UNLIKELY(!ext_rowkey.is_range_cutoffed())) { ret = OB_INVALID_ARGUMENT; STORAGE_LOG(WARN, "ExtRowkey is not range cutted", K(ext_rowkey), K(ret)); } else if (OB_UNLIKELY(ext_rowkey.get_range_cut_pos() == 0)) { block_idx = ext_rowkey.is_range_check_min() ? 0 : -1; } else { ret = locate_block_idx_( ext_rowkey, ext_rowkey.get_range_cut_pos(), ext_rowkey.is_range_check_min(), last_block_idx, block_idx); } return ret; } int ObSSTableRowkeyHelper::locate_block_idx_table( const ObExtStoreRowkey& ext_rowkey, const int64_t last_block_idx, int64_t& block_idx) { int ret = OB_SUCCESS; if (OB_UNLIKELY(!is_inited_)) { ret = OB_NOT_INIT; STORAGE_LOG(WARN, "ObSSTableRowkeyHelper is not inited", K(ret)); } else if (OB_UNLIKELY(!ext_rowkey.is_range_cutoffed())) { ret = OB_INVALID_ARGUMENT; STORAGE_LOG(WARN, "ExtRowkey is not range cutted", K(ext_rowkey), K(ret)); } else if (OB_UNLIKELY(ext_rowkey.get_range_cut_pos() == 0)) { block_idx = ext_rowkey.is_range_check_min() ? 0 : -1; } else if (OB_UNLIKELY(ext_rowkey.get_first_null_pos() == 0)) { block_idx = is_oracle_mode_ ? -1 : 0; } else { int64_t cmp_rowkey_col_cnt = ext_rowkey.get_range_cut_pos(); bool use_lower_bound = ext_rowkey.is_range_check_min(); if (ext_rowkey.get_first_null_pos() > 0 && ext_rowkey.get_first_null_pos() < cmp_rowkey_col_cnt) { cmp_rowkey_col_cnt = ext_rowkey.get_first_null_pos(); use_lower_bound = !is_oracle_mode_; } ret = locate_block_idx_(ext_rowkey, cmp_rowkey_col_cnt, use_lower_bound, last_block_idx, block_idx); } return ret; } } // end namespace storage } // end namespace oceanbase
38.710438
119
0.670175
b6b9685cab98a2ba3d1d8883d8142265d8a14a78
1,601
hpp
C++
libbio/include/bio/crypto/crypto_Sha256.hpp
biosphere-switch/libbio
7c892ff1e0f47e4612f3b66fdf043216764dfd1b
[ "MIT" ]
null
null
null
libbio/include/bio/crypto/crypto_Sha256.hpp
biosphere-switch/libbio
7c892ff1e0f47e4612f3b66fdf043216764dfd1b
[ "MIT" ]
null
null
null
libbio/include/bio/crypto/crypto_Sha256.hpp
biosphere-switch/libbio
7c892ff1e0f47e4612f3b66fdf043216764dfd1b
[ "MIT" ]
null
null
null
#pragma once #include <bio/mem/mem_Memory.hpp> namespace bio::crypto { // Grabbed from libnx, hardware-accelerated impl class Sha256Context { public: static constexpr u64 HashSize = 0x20; static constexpr u64 HashSize32 = HashSize / sizeof(u32); static constexpr u64 BlockSize = 0x40; static constexpr u32 InitialHash[HashSize32] = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, }; private: u32 intermediate_hash[HashSize32]; u8 block[BlockSize]; u64 bits_consumed; u64 num_buffered; bool finalized; void EnsureFinalized(); void ProcessBlocks(const u8 *buf, u64 num_blocks); public: Sha256Context() : intermediate_hash(), block(), bits_consumed(0), num_buffered(0), finalized(false) { mem::Copy(this->intermediate_hash, InitialHash, HashSize); } void Update(const void *buf, u64 size); inline void GetHash(void *out_dest) { this->EnsureFinalized(); auto dest32 = reinterpret_cast<u32*>(out_dest); for(u32 i = 0; i < HashSize32; i++) { dest32[i] = __builtin_bswap32(this->intermediate_hash[i]); } } }; inline void CalculateSha256(const void *buf, u64 size, void *out) { Sha256Context ctx; ctx.Update(buf, size); ctx.GetHash(out); } }
29.648148
113
0.564022
b6baf75f42c6a0f942ec07d8a30159d3dc2b9ad6
935
hpp
C++
libraries/plugins/apis/account_by_key_api/include/delta/plugins/account_by_key_api/account_by_key_api.hpp
yashbhavsar007/Delta-Blockchain
602dd5335d2cd51303e953e4c233c8f099da0b07
[ "MIT" ]
null
null
null
libraries/plugins/apis/account_by_key_api/include/delta/plugins/account_by_key_api/account_by_key_api.hpp
yashbhavsar007/Delta-Blockchain
602dd5335d2cd51303e953e4c233c8f099da0b07
[ "MIT" ]
null
null
null
libraries/plugins/apis/account_by_key_api/include/delta/plugins/account_by_key_api/account_by_key_api.hpp
yashbhavsar007/Delta-Blockchain
602dd5335d2cd51303e953e4c233c8f099da0b07
[ "MIT" ]
null
null
null
#pragma once #include <delta/plugins/json_rpc/utility.hpp> #include <delta/protocol/types.hpp> #include <fc/optional.hpp> #include <fc/variant.hpp> #include <fc/vector.hpp> namespace delta { namespace plugins { namespace account_by_key { namespace detail { class account_by_key_api_impl; } struct get_key_references_args { std::vector< delta::protocol::public_key_type > keys; }; struct get_key_references_return { std::vector< std::vector< delta::protocol::account_name_type > > accounts; }; class account_by_key_api { public: account_by_key_api(); ~account_by_key_api(); DECLARE_API( (get_key_references) ) private: std::unique_ptr< detail::account_by_key_api_impl > my; }; } } } // delta::plugins::account_by_key FC_REFLECT( delta::plugins::account_by_key::get_key_references_args, (keys) ) FC_REFLECT( delta::plugins::account_by_key::get_key_references_return, (accounts) )
20.326087
77
0.735829
b6bc263a733e9f6bbb8635aa9d1df83ca167e057
2,191
cpp
C++
libs/RFType/TypeDatabase.cpp
max-delta/retrofit-public
5447fd6399fd74ffbb75494c103940751000db12
[ "X11" ]
3
2019-10-27T22:32:44.000Z
2020-05-21T04:00:46.000Z
libs/RFType/TypeDatabase.cpp
max-delta/retrofit-public
5447fd6399fd74ffbb75494c103940751000db12
[ "X11" ]
null
null
null
libs/RFType/TypeDatabase.cpp
max-delta/retrofit-public
5447fd6399fd74ffbb75494c103940751000db12
[ "X11" ]
null
null
null
#include "stdafx.h" #include "TypeDatabase.h" #include "core/macros.h" #include "core/meta/LazyInitSingleton.h" #include "core_rftype/Identifier.h" #include "rftl/memory" namespace RF::rftype { /////////////////////////////////////////////////////////////////////////////// bool TypeDatabase::RegisterNewClassByName( char const* name, reflect::ClassInfo const& classInfo ) { RF_ASSERT( name != nullptr ); if( IsValidClassName( name ) == false ) { RF_DBGFAIL(); return false; } size_t nameLen = strnlen( name, 1024 ); math::HashVal64 const hash = math::StableHashBytes( name, nameLen ); bool const registerSuccess = RegisterNewClassByHash( hash, name, classInfo ); return registerSuccess; } reflect::ClassInfo const* TypeDatabase::GetClassInfoByName( char const* name ) const { size_t nameLen = strnlen( name, 1024 ); math::HashVal64 const hash = math::StableHashBytes( name, nameLen ); return GetClassInfoByHash( hash ); } reflect::ClassInfo const* TypeDatabase::GetClassInfoByHash( math::HashVal64 const& hash ) const { ClassInfoByHash::const_iterator const iter = mClassInfoByHash.find( hash ); if( iter == mClassInfoByHash.end() ) { return nullptr; } RF_ASSERT( iter->second.mClassInfo != nullptr ); return iter->second.mClassInfo; } TypeDatabase& TypeDatabase::GetGlobalMutableInstance() { return GetOrCreateGlobalInstance(); } TypeDatabase const& TypeDatabase::GetGlobalInstance() { return GetOrCreateGlobalInstance(); } /////////////////////////////////////////////////////////////////////////////// bool TypeDatabase::RegisterNewClassByHash( math::HashVal64 const& hash, char const* name, reflect::ClassInfo const& classInfo ) { if( mClassInfoByHash.count( hash ) != 0 ) { return false; } StoredClassInfo& newStorage = mClassInfoByHash[hash]; newStorage.mName = name; newStorage.mClassInfo = &classInfo; return true; } bool TypeDatabase::IsValidClassName( char const* name ) { return IsValidIdentifier( name ); } TypeDatabase& TypeDatabase::GetOrCreateGlobalInstance() { return GetOrInitFunctionStaticScopedSingleton<TypeDatabase>(); } /////////////////////////////////////////////////////////////////////////////// }
22.357143
127
0.664537
b6bd8fd53c78a5c0df38d175650861eff65c98dc
608
hpp
C++
libs/opencl/include/sge/opencl/context/error_callback_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/opencl/include/sge/opencl/context/error_callback_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/opencl/include/sge/opencl/context/error_callback_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_OPENCL_CONTEXT_ERROR_CALLBACK_TYPE_HPP_INCLUDED #define SGE_OPENCL_CONTEXT_ERROR_CALLBACK_TYPE_HPP_INCLUDED #include <sge/opencl/binary_error_data.hpp> #include <sge/opencl/error_information_string.hpp> namespace sge::opencl::context { using error_callback_type = void(sge::opencl::error_information_string const &, sge::opencl::binary_error_data const &); } #endif
28.952381
96
0.771382
b6bfb73351dc46f7693a02b53a3be53b5f550e1b
745
hpp
C++
app/src/main/cpp/common/src/common/Mesh.hpp
pehg/Break_it_all
dab56d82dd4541a710f16b1e6f61ee214059a1a9
[ "MIT" ]
null
null
null
app/src/main/cpp/common/src/common/Mesh.hpp
pehg/Break_it_all
dab56d82dd4541a710f16b1e6f61ee214059a1a9
[ "MIT" ]
null
null
null
app/src/main/cpp/common/src/common/Mesh.hpp
pehg/Break_it_all
dab56d82dd4541a710f16b1e6f61ee214059a1a9
[ "MIT" ]
null
null
null
// // Created by simonppg on 4/22/19. // #ifndef BREAK_IT_ALL_MESH_HPP #define BREAK_IT_ALL_MESH_HPP #include "Camera.hpp" using glm::vec3; #define NUM_ARRAY_ELEMENTS(a) (sizeof(a) / sizeof(*a)) #define INDEX_BUFFER_SIZE(numIndices) ((GLsizeiptr)((numIndices) * (sizeof(GLushort)))) #define VERTEX_BUFFER_SIZE(numIndices) ((GLsizeiptr)((numIndices) * (sizeof(float) * 6))) #define ONE 1 #define TWO 2 class Mesh { public: Mesh(float *pDouble, int i); Mesh(float *vertex, int v_size, short *indices, int i_size); int type; float *vertex; short *indices; int numVertices; int numIndices; unsigned int vbo; // vertex buffer object unsigned int iab; // index array buffer }; #endif //BREAK_IT_ALL_MESH_HPP
22.575758
89
0.702013
b6c58b4a719ddc165a4c06e1369168ee4029fd34
1,138
cpp
C++
src/db/db_impl.cpp
rickard1117/PidanDB
6955f6913cb404a0f09a5e44c07f36b0729c0a78
[ "MIT" ]
7
2020-08-01T04:09:15.000Z
2021-08-08T17:26:19.000Z
src/db/db_impl.cpp
rickard1117/PidanDB
6955f6913cb404a0f09a5e44c07f36b0729c0a78
[ "MIT" ]
null
null
null
src/db/db_impl.cpp
rickard1117/PidanDB
6955f6913cb404a0f09a5e44c07f36b0729c0a78
[ "MIT" ]
2
2020-09-16T02:29:52.000Z
2020-09-28T10:51:38.000Z
#include "db/db_impl.h" namespace pidan { Status DBImpl::Put(const Slice &key, const Slice &value) { Transaction *txn = txn_manager_.BeginWriteTransaction(); DataHeader *dh = new DataHeader(txn); DataHeader *old_dh = nullptr; auto result = index_.InsertUnique(key, dh, &old_dh); if (!result) { delete dh; if (!old_dh->Put(txn, value)) { txn_manager_.Abort(txn); return Status::FAIL_BY_ACTIVE_TXN; } } else { result = dh->Put(txn, value); assert(result); } txn_manager_.Commit(txn); return Status::SUCCESS; } Status DBImpl::Get(const Slice &key, std::string *val) { Transaction txn = txn_manager_.BeginReadTransaction(); DataHeader *dh = nullptr; if (!index_.Lookup(key, &dh)) { txn_manager_.Abort(&txn); return Status::KEY_NOT_EXIST; } bool not_found; if (!dh->Select(&txn, val, &not_found)) { return Status::FAIL_BY_ACTIVE_TXN; } if (not_found) { return Status::KEY_NOT_EXIST; } return Status::SUCCESS; } Status PidanDB::Open(const std::string &name, PidanDB **dbptr) { *dbptr = new DBImpl(); return Status::SUCCESS; } } // namespace pidan
23.708333
64
0.665202
b6c7c92e3bfa79f0066631365f7853bef96538d9
670
cpp
C++
binary tree/flattenTreeToLinkedList.cpp
Gooner1886/DSA-101
44092e10ad39bebbf7da93e897927106d5a45ae7
[ "MIT" ]
20
2022-01-04T19:36:14.000Z
2022-03-21T15:35:09.000Z
binary tree/flattenTreeToLinkedList.cpp
Gooner1886/DSA-101
44092e10ad39bebbf7da93e897927106d5a45ae7
[ "MIT" ]
null
null
null
binary tree/flattenTreeToLinkedList.cpp
Gooner1886/DSA-101
44092e10ad39bebbf7da93e897927106d5a45ae7
[ "MIT" ]
null
null
null
// Leetcode - 114 - Flatten Binary Tree to Linked List void solve(TreeNode *root, vector<int> &preorder) { root->left = NULL; root->right = NULL; for (int i = 1; i < preorder.size(); i++) { root->right = new TreeNode(preorder[i]); root = root->right; } } void preorderTraversal(TreeNode *root, vector<int> &preorder) { if (!root) return; preorder.push_back(root->val); preorderTraversal(root->left, preorder); preorderTraversal(root->right, preorder); } void flatten(TreeNode *root) { if (!root) return; vector<int> preorder; preorderTraversal(root, preorder); solve(root, preorder); }
23.928571
61
0.623881
b6c9ac73c37b5204639c27d37f0655122c11a714
8,505
hpp
C++
Vesper/Vesper/BSSRDFs/IrradianceTree.hpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
6
2017-09-14T03:26:49.000Z
2021-09-18T05:40:59.000Z
Vesper/Vesper/BSSRDFs/IrradianceTree.hpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
null
null
null
Vesper/Vesper/BSSRDFs/IrradianceTree.hpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <array> #include <vector> #include <CrispCore/Math/BoundingBox.hpp> #include "Spectrums/Spectrum.hpp" namespace crisp { struct SurfacePoint { SurfacePoint() {} SurfacePoint(const glm::vec3& p, const glm::vec3& n, float a) : p(p) , n(n) , area(a) , rayEpsilon(Ray3::Epsilon) { } glm::vec3 p; glm::vec3 n; float area; float rayEpsilon; }; struct PoissonCheck { PoissonCheck(float maxDist, const glm::vec3& point) : maxDist2(maxDist * maxDist) , failed(false) , p(point) { } bool operator()(const SurfacePoint& point) { glm::vec3 diff = point.p - p; if (glm::dot(diff, diff) < maxDist2) { failed = true; return false; } return true; } float maxDist2; bool failed; glm::vec3 p; }; struct IrradiancePoint { IrradiancePoint() {} IrradiancePoint(const SurfacePoint& surfPt, const Spectrum& spectrum) : p(surfPt.p) , n(surfPt.n) , e(spectrum) , area(surfPt.area) , rayEpsilon(surfPt.rayEpsilon) { } glm::vec3 p; glm::vec3 n; Spectrum e; float area; float rayEpsilon; }; struct IrradianceNode { glm::vec3 p; bool isLeaf; Spectrum e; float sumArea; std::array<std::unique_ptr<IrradianceNode>, 8> children; std::array<IrradiancePoint*, 8> irrPts; IrradianceNode() : isLeaf(true) , sumArea(0.0f) { for (int i = 0; i < 8; i++) { irrPts[i] = nullptr; children[i] = nullptr; } } inline BoundingBox3 getChildBound(int child, const BoundingBox3& bounds, const glm::vec3& mid) { BoundingBox3 bound; bound.min.x = (child & 4) ? mid.x : bounds.min.x; bound.min.y = (child & 2) ? mid.y : bounds.min.y; bound.min.z = (child & 1) ? mid.z : bounds.min.z; bound.max.x = (child & 4) ? bounds.max.x : mid.x; bound.max.y = (child & 2) ? bounds.max.y : mid.y; bound.max.z = (child & 1) ? bounds.max.z : mid.z; return bound; } void insert(const BoundingBox3& nodeBounds, IrradiancePoint* point) { glm::vec3 mid = nodeBounds.getCenter(); if (isLeaf) { for (int i = 0; i < 8; i++) { if (!irrPts[i]) { irrPts[i] = point; return; } } isLeaf = false; IrradiancePoint* localPts[8]; for (int i = 0; i < 8; i++) { localPts[i] = irrPts[i]; children[i] = nullptr; } for (int i = 0; i < 8; i++) { IrradiancePoint* currPt = localPts[i]; int child = (currPt->p.x > mid.x ? 4 : 0) + (currPt->p.y > mid.y ? 2 : 0) + (currPt->p.z > mid.z ? 1 : 0); if (children[child] == nullptr) children[child] = std::make_unique<IrradianceNode>(); BoundingBox3 childBounds = getChildBound(child, nodeBounds, mid); children[child]->insert(childBounds, currPt); } int child = (point->p.x > mid.x ? 4 : 0) + (point->p.y > mid.y ? 2 : 0) + (point->p.z > mid.z ? 1 : 0); if (children[child] == nullptr) children[child] = std::make_unique<IrradianceNode>(); BoundingBox3 childBounds = getChildBound(child, nodeBounds, mid); children[child]->insert(childBounds, point); } } Spectrum getLeafIrradiance() { Spectrum sum(0.0f); if (isLeaf) { for (int i = 0; i < irrPts.size(); i++) { if (!irrPts[i]) break; sum += irrPts[i]->e; } } else { for (int i = 0; i < children.size(); i++) { if (!children[i]) continue; sum += children[i]->getLeafIrradiance(); } } return sum; } Spectrum getTotalIrradiance() { Spectrum sum(0.0f); if (isLeaf) { for (int i = 0; i < irrPts.size(); i++) { if (!irrPts[i]) break; sum += irrPts[i]->e; } } else { for (int i = 0; i < children.size(); i++) { if (!children[i]) continue; sum += children[i]->getLeafIrradiance(); } sum += e; } return sum; } void initHierarchy() { if (isLeaf) { float weightSum = 0.0f; size_t i; for (i = 0; i < 8; i++) { if (!irrPts[i]) break; float weight = irrPts[i]->e.getLuminance(); e += irrPts[i]->e; p += weight * irrPts[i]->p; weightSum += weight; sumArea += irrPts[i]->area; } if (weightSum > 0.0f) p /= weightSum; if (i > 0) e /= static_cast<float>(i); } else { float weightSum = 0.0f; size_t numChildren = 0; for (uint32_t i = 0; i < 8; i++) { if (!children[i]) continue; ++numChildren; children[i]->initHierarchy(); float weight = children[i]->e.getLuminance(); e += children[i]->e; p += weight * children[i]->p; weightSum += weight; sumArea += children[i]->sumArea; } if (weightSum > 0.0f) p /= weightSum; if (numChildren > 0) e /= static_cast<float>(numChildren); } } template <typename Func> Spectrum Mo(const BoundingBox3& nodeBounds, const glm::vec3& pt, Func& func, float maxError) { glm::vec3 diff = pt - p; float sqrDist = glm::dot(diff, diff); float distanceWeight = sumArea / sqrDist; if (distanceWeight < maxError && !nodeBounds.contains(pt)) return func(sqrDist) * e * sumArea; Spectrum mo = 0.0f; if (isLeaf) { for (int i = 0; i < 8; i++) { if (!irrPts[i]) break; glm::vec3 diffC = irrPts[i]->p - pt; float cSqrDist = glm::dot(diffC, diffC); mo += func(cSqrDist) * irrPts[i]->e * irrPts[i]->area; } } else { glm::vec3 mid = nodeBounds.getCenter(); for (int child = 0; child < 8; child++) { if (!children[child]) continue; BoundingBox3 childBounds = getChildBound(child, nodeBounds, mid); mo += children[child]->Mo(childBounds, pt, func, maxError); } } return mo; } }; struct IrradianceTree { std::unique_ptr<IrradianceNode> root; BoundingBox3 boundingBox; }; }
28.444816
102
0.388595
b6d63ff87ed03714a1fa7cf95cc74d0f65869208
3,577
cpp
C++
android-30/android/widget/SimpleAdapter.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-30/android/widget/SimpleAdapter.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/widget/SimpleAdapter.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../JIntArray.hpp" #include "../../JArray.hpp" #include "../content/Context.hpp" #include "../content/res/Resources_Theme.hpp" #include "../view/View.hpp" #include "../view/ViewGroup.hpp" #include "./Filter.hpp" #include "./ImageView.hpp" #include "./TextView.hpp" #include "../../JObject.hpp" #include "../../JString.hpp" #include "./SimpleAdapter.hpp" namespace android::widget { // Fields // QJniObject forward SimpleAdapter::SimpleAdapter(QJniObject obj) : android::widget::BaseAdapter(obj) {} // Constructors SimpleAdapter::SimpleAdapter(android::content::Context arg0, JObject arg1, jint arg2, JArray arg3, JIntArray arg4) : android::widget::BaseAdapter( "android.widget.SimpleAdapter", "(Landroid/content/Context;Ljava/util/List;I[Ljava/lang/String;[I)V", arg0.object(), arg1.object(), arg2, arg3.object<jarray>(), arg4.object<jintArray>() ) {} // Methods jint SimpleAdapter::getCount() const { return callMethod<jint>( "getCount", "()I" ); } android::view::View SimpleAdapter::getDropDownView(jint arg0, android::view::View arg1, android::view::ViewGroup arg2) const { return callObjectMethod( "getDropDownView", "(ILandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;", arg0, arg1.object(), arg2.object() ); } android::content::res::Resources_Theme SimpleAdapter::getDropDownViewTheme() const { return callObjectMethod( "getDropDownViewTheme", "()Landroid/content/res/Resources$Theme;" ); } android::widget::Filter SimpleAdapter::getFilter() const { return callObjectMethod( "getFilter", "()Landroid/widget/Filter;" ); } JObject SimpleAdapter::getItem(jint arg0) const { return callObjectMethod( "getItem", "(I)Ljava/lang/Object;", arg0 ); } jlong SimpleAdapter::getItemId(jint arg0) const { return callMethod<jlong>( "getItemId", "(I)J", arg0 ); } android::view::View SimpleAdapter::getView(jint arg0, android::view::View arg1, android::view::ViewGroup arg2) const { return callObjectMethod( "getView", "(ILandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;", arg0, arg1.object(), arg2.object() ); } JObject SimpleAdapter::getViewBinder() const { return callObjectMethod( "getViewBinder", "()Landroid/widget/SimpleAdapter$ViewBinder;" ); } void SimpleAdapter::setDropDownViewResource(jint arg0) const { callMethod<void>( "setDropDownViewResource", "(I)V", arg0 ); } void SimpleAdapter::setDropDownViewTheme(android::content::res::Resources_Theme arg0) const { callMethod<void>( "setDropDownViewTheme", "(Landroid/content/res/Resources$Theme;)V", arg0.object() ); } void SimpleAdapter::setViewBinder(JObject arg0) const { callMethod<void>( "setViewBinder", "(Landroid/widget/SimpleAdapter$ViewBinder;)V", arg0.object() ); } void SimpleAdapter::setViewImage(android::widget::ImageView arg0, jint arg1) const { callMethod<void>( "setViewImage", "(Landroid/widget/ImageView;I)V", arg0.object(), arg1 ); } void SimpleAdapter::setViewImage(android::widget::ImageView arg0, JString arg1) const { callMethod<void>( "setViewImage", "(Landroid/widget/ImageView;Ljava/lang/String;)V", arg0.object(), arg1.object<jstring>() ); } void SimpleAdapter::setViewText(android::widget::TextView arg0, JString arg1) const { callMethod<void>( "setViewText", "(Landroid/widget/TextView;Ljava/lang/String;)V", arg0.object(), arg1.object<jstring>() ); } } // namespace android::widget
23.688742
125
0.689405
b6d713da27744740cbd2a04f40d244a6afd101c4
1,887
cpp
C++
src/examples/logisticregression.cpp
jaymwong/CppNumericalSolvers
2a0f98e7c54c35325641e05c035e43cafd570808
[ "MIT" ]
2
2016-03-17T21:13:23.000Z
2021-01-10T00:53:08.000Z
src/examples/logisticregression.cpp
jaymwong/CppNumericalSolvers
2a0f98e7c54c35325641e05c035e43cafd570808
[ "MIT" ]
null
null
null
src/examples/logisticregression.cpp
jaymwong/CppNumericalSolvers
2a0f98e7c54c35325641e05c035e43cafd570808
[ "MIT" ]
1
2021-01-07T16:20:12.000Z
2021-01-07T16:20:12.000Z
#include <iostream> #include "../../include/cppoptlib/meta.h" #include "../../include/cppoptlib/problem.h" #include "../../include/cppoptlib/solver/bfgssolver.h" // to use this library just use the namespace "cppoptlib" namespace cppoptlib { // we define a new problem for optimizing the rosenbrock function // we use a templated-class rather than "auto"-lambda function for a clean architecture template<typename T> class LogisticRegression : public Problem<T> { public: using typename Problem<T>::TVector; using MatrixType = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>; const MatrixType X; const TVector y; const MatrixType XX; LogisticRegression(const MatrixType &X_, const TVector y_) : X(X_), y(y_), XX(X_.transpose()*X_) {} T value(const TVector &beta) { return (1.0/(1.0 + exp(-(X*beta).array())) - y.array()).matrix().squaredNorm(); } void gradient(const TVector &beta, TVector &grad) { const TVector p = 1.0/(1.0 + exp(-(X*beta).array())); grad = X.transpose()*(p-y); } }; } int main(int argc, char const *argv[]) { typedef double T; typedef cppoptlib::LogisticRegression<T> LogReg; typedef typename LogReg::TVector TVector; typedef typename LogReg::MatrixType MatrixType; srand((unsigned int) time(0)); // create true model TVector true_beta = TVector::Random(4); // create data MatrixType X = MatrixType::Random(50, 4); TVector y = 1.0/(1.0 + exp(-(X*true_beta).array())); // perform linear regression LogReg f(X, y); TVector beta = TVector::Random(4); std::cout << "start in " << beta.transpose() << std::endl; cppoptlib::BfgsSolver<LogReg> solver; solver.minimize(f, beta); std::cout << "result " << beta.transpose() << std::endl; std::cout << "true model " << true_beta.transpose() << std::endl; return 0; }
31.45
103
0.647589
b6d962121987bcab856a0318aa250dcd1a68fb2d
1,552
cpp
C++
src/lib/classification/poset_classification/extension.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
15
2016-10-27T15:18:28.000Z
2022-02-09T11:13:07.000Z
src/lib/classification/poset_classification/extension.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
4
2019-12-09T11:49:11.000Z
2020-07-30T17:34:45.000Z
src/lib/classification/poset_classification/extension.cpp
abetten/orbiter
5994d0868a26c37676d6aadfc66a1f1bcb715c4b
[ "RSA-MD" ]
15
2016-06-10T20:05:30.000Z
2020-12-18T04:59:19.000Z
// extension.cpp // // Anton Betten // Dec 19, 2011 #include "foundations/foundations.h" #include "group_actions/group_actions.h" #include "classification/classification.h" using namespace std; namespace orbiter { namespace classification { extension::extension() { pt = -1; orbit_len = 0; type = EXTENSION_TYPE_UNPROCESSED; data = 0; data1 = 0; data2 = 0; } extension::~extension() { } int extension::get_pt() { return pt; } void extension::set_pt(int pt) { extension::pt = pt; } int extension::get_type() { return type; } void extension::set_type(int type) { extension::type = type; } int extension::get_orbit_len() { return orbit_len; } void extension::set_orbit_len(int orbit_len) { extension::orbit_len = orbit_len; } int extension::get_data() { return data; } void extension::set_data(int data) { extension::data = data; } int extension::get_data1() { return data1; } void extension::set_data1(int data1) { extension::data1 = data1; } int extension::get_data2() { return data2; } void extension::set_data2(int data2) { extension::data2 = data2; } void print_extension_type(ostream &ost, int t) { if (t == EXTENSION_TYPE_UNPROCESSED) { ost << " unprocessed"; } else if (t == EXTENSION_TYPE_EXTENSION) { ost << " extension"; } else if (t == EXTENSION_TYPE_FUSION) { ost << " fusion"; } else if (t == EXTENSION_TYPE_PROCESSING) { ost << " processing"; } else if (t == EXTENSION_TYPE_NOT_CANONICAL) { ost << " not canonical"; } else { ost << "type=" << t; } } }}
13.37931
46
0.664948
b6dcac5b51219b3f13512b72000bd09d25593b68
3,844
cpp
C++
src/ZHTUtil.cpp
skxie/zht-eventual-consistency
49a2f102f382710212832d9426edfc21ceb7f7fd
[ "Apache-2.0" ]
1
2019-06-03T17:43:58.000Z
2019-06-03T17:43:58.000Z
src/ZHTUtil.cpp
skxie/zht-eventual-consistency
49a2f102f382710212832d9426edfc21ceb7f7fd
[ "Apache-2.0" ]
null
null
null
src/ZHTUtil.cpp
skxie/zht-eventual-consistency
49a2f102f382710212832d9426edfc21ceb7f7fd
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2020 DatasysLab@iit.edu(http://datasys.cs.iit.edu/index.html) * Director: Ioan Raicu(iraicu@cs.iit.edu) * * 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. * * This file is part of ZHT library(http://datasys.cs.iit.edu/projects/ZHT/index.html). * Tonglin Li(tli13@hawk.iit.edu) with nickname Tony, * Xiaobing Zhou(xzhou40@hawk.iit.edu) with nickname Xiaobingo, * Ke Wang(kwang22@hawk.iit.edu) with nickname KWang, * Dongfang Zhao(dzhao8@@hawk.iit.edu) with nickname DZhao, * Ioan Raicu(iraicu@cs.iit.edu). * * ZHTUtil.cpp * * Created on: Jun 25, 2013 * Author: Tony * Contributor: Xiaobingo, KWang, DZhao */ #include "ZHTUtil.h" #include "Util.h" #include "ConfHandler.h" #include <arpa/inet.h> #include <algorithm> #include <netdb.h> #include <time.h> #include "zpack.pb.h" using namespace iit::datasys::zht::dm; ZHTUtil::ZHTUtil() { } ZHTUtil::~ZHTUtil() { } HostEntity ZHTUtil::getHostEntityByKey(const string& msg) { int numOfReplica = ConfHandler::ZC_NUM_REPLICAS; ZPack zpack; zpack.ParseFromString(msg); //to debug int replicaNum = 0; /* printf("{%s}:{%s}:{%s,%s}:{%u, %u}\n", zpack.opcode().c_str(), zpack.key().c_str(), zpack.val().c_str(), zpack.newval().c_str()), zpack.replicanum(), zpack.versionnum(); */ uint64_t hascode = HashUtil::genHash(zpack.key()); size_t node_size = ConfHandler::NeighborVector.size(); int index = hascode % node_size; if(zpack.opcode() == Const::ZSC_OPC_LOOKUP && numOfReplica > 0){ /*randomly generate the index from all replicas*/ srand(time(NULL)); replicaNum = rand() % (numOfReplica + 1); //replicaNum = 1; index = (index + replicaNum) % node_size; //index = 0; int portDiff = ConfHandler::getPortDiffFromConf(); ConfEntry ce = ConfHandler::NeighborVector.at(index); //cout << "The index for lookup is " << index << endl; //cout << "The host would be served for the lookup is " << ce.name() << " " << atoi(ce.value().c_str()) + replicaNum * portDiff << endl; return buildHostEntity(ce.name(), atoi(ce.value().c_str()) + replicaNum * portDiff); } ConfEntry ce = ConfHandler::NeighborVector.at(index); return buildHostEntity(ce.name(), atoi(ce.value().c_str())); } HostEntity ZHTUtil::builtReplicaEntity (const uint& hostIndex, const uint& port){ ConfEntry ce = ConfHandler::NeighborVector.at(hostIndex); return buildHostEntity(ce.name(), atoi(ce.value().c_str()) + port); } HostEntity ZHTUtil::buildHostEntity(const string& host, const uint& port) { HostEntity he; /* struct sockaddr_in si_other; hostent *record; in_addr *address; string ip_address; record = gethostbyname(host.c_str()); address = (in_addr *) record->h_addr; ip_address = inet_ntoa(*address); memset((char *) &si_other, 0, sizeof(si_other)); si_other.sin_family = AF_INET; si_other.sin_port = htons(port); if (inet_aton(ip_address.c_str(), &si_other.sin_addr) == 0) { fprintf(stderr, "inet_aton() failed\n"); } he.si = si_other; he.host = host; he.port = port; he.valid = true; he.sock = -1;*/ he.host = host; he.port = port; he.sock = -1; return he; } const uint IdHelper::ID_LEN = 20; IdHelper::IdHelper() { } IdHelper::~IdHelper() { } uint64_t IdHelper::genId() { return HashUtil::genHash(HashUtil::randomString(62).c_str()); }
26.881119
138
0.683143
b6e141796369094324824c07eaba15be4e416bc3
2,060
cpp
C++
libbirch/libbirch/Memo.cpp
vishalbelsare/Birch
ead17b181a058250e9f5896d64954232d19e43f0
[ "Apache-2.0" ]
86
2017-10-29T15:46:41.000Z
2022-01-17T07:18:16.000Z
libbirch/libbirch/Memo.cpp
vishalbelsare/Birch
ead17b181a058250e9f5896d64954232d19e43f0
[ "Apache-2.0" ]
13
2020-09-27T03:31:57.000Z
2021-05-27T00:39:14.000Z
libbirch/libbirch/Memo.cpp
vishalbelsare/Birch
ead17b181a058250e9f5896d64954232d19e43f0
[ "Apache-2.0" ]
12
2018-08-21T12:57:18.000Z
2021-05-26T18:41:50.000Z
/** *@file */ #include "libbirch/Memo.hpp" #include "libbirch/external.hpp" #include "libbirch/memory.hpp" #include "libbirch/thread.hpp" libbirch::Memo::Memo() : keys(nullptr), values(nullptr), nentries(0), noccupied(0) { // } libbirch::Memo::~Memo() { std::free(keys); std::free(values); } libbirch::Any*& libbirch::Memo::get(Any* key) { assert(key); /* reserve a slot */ if (++noccupied > crowd()) { rehash(); } auto i = hash(key); auto k = keys[i]; while (k && k != key) { i = (i + 1) & (nentries - 1); k = keys[i]; } if (k) { --noccupied; // unreserve the slot, wasn't needed } else { keys[i] = key; values[i] = nullptr; } return values[i]; } int libbirch::Memo::hash(Any* key) const { assert(nentries > 0); return static_cast<int>(reinterpret_cast<size_t>(key) >> 6ull) & (nentries - 1); } int libbirch::Memo::crowd() const { /* the table is considered crowded if more than three-quarters of its * entries are occupied */ return (nentries >> 1) + (nentries >> 2); } void libbirch::Memo::rehash() { /* save previous table */ auto nentries1 = nentries; auto keys1 = keys; auto values1 = values; /* size of new table */ nentries = std::max(INITIAL_SIZE, 2*nentries1); /* allocate the new table */ keys = (Any**)std::malloc(nentries*sizeof(Any*)); values = (Any**)std::malloc(nentries*sizeof(Any*)); std::memset(keys, 0, nentries*sizeof(Any*)); //std::memset(values, 0, nentries*sizeof(Any*)); // ^ nullptr keys are used to indicate empty slots, while individual values // are set to nullptr on first access in get(), so need not be here */ /* copy entries from previous table */ for (int i = 0; i < nentries1; ++i) { auto key = keys1[i]; if (key) { auto j = hash(key); while (keys[j]) { j = (j + 1) & (nentries - 1); } keys[j] = key; values[j] = values1[i]; } } /* deallocate previous table */ if (nentries1 > 0) { std::free(keys1); std::free(values1); } }
21.914894
77
0.586408
b6e3bd44284375e49a0bec3135ac98997769a048
4,187
cpp
C++
src/scene.cpp
sndels/naiverend
8d2b76104fa9ea4cbff2dc95aeabebb9d506856c
[ "MIT" ]
null
null
null
src/scene.cpp
sndels/naiverend
8d2b76104fa9ea4cbff2dc95aeabebb9d506856c
[ "MIT" ]
null
null
null
src/scene.cpp
sndels/naiverend
8d2b76104fa9ea4cbff2dc95aeabebb9d506856c
[ "MIT" ]
null
null
null
#include "scene.hpp" #include "gl_core_4_1.h" #include <glm/glm.hpp> #include <iostream> #include <vector> #include "input_handler.hpp" #include "math_types.hpp" #include "model_parser.hpp" #include "imgui/imgui.h" #include "imgui/examples/opengl3_example/imgui_impl_glfw_gl3.h" using glm::vec3; using glm::mat3; using glm::mat4; using std::cerr; using std::cin; using std::endl; Scene::Scene(const float& xres, const float& yres) : res2f_(xres, yres), modelPos3f_(0.f, 0.f, 0.f), modelScale3f_(1.f), modelRotY1f_(PI_F), lightPos3f_(5.f, 7.f, -5.f) { ; } bool Scene::init() { if (!pg_.loadProgram()) return false; parseOBJ("res/head/head.obj", model_); GLenum error = glGetError(); if(error != GL_NO_ERROR) { cerr << "Error initializing scene!" << endl; cerr << "Error code: " << error << endl; cin.get(); return false; } cam_.setProj(res2f_.x, res2f_.y, 90.f, 0.1f, 10.f); cam_.setView(vec3(0.f, 0.f, -4.f), vec3(0.f, 0.f, 0.f)); return true; } void Scene::update() { InputHandler& ih = InputHandler::getIH(); // Cam control const MouseState ms = ih.getMouseState(); if (ms.state == LEFT_DOWN) cam_.rotateTrackball(ms.lastPos2f, ms.curPos2f); cam_.movePos(vec3(0.f, 0.f, ms.scrollY / 4.f)); // Model control const KeyboardState ks = ih.getKeyboardState(); vec3 modelOffset(0.f, 0.f, 0.f); if (ks.shift) { if (ks.up) modelOffset.z += 1.f; if (ks.down) modelOffset.z -= 1.f; } else { if (ks.up) modelOffset.y += 1.f; if (ks.down) modelOffset.y -= 1.f; } if (ks.left) modelOffset.x -= 1.f; if (ks.right) modelOffset.x += 1.f; if (length(modelOffset) > 0.f) modelPos3f_ += 0.05f * normalize(modelOffset); ih.reset(); } void Scene::render() { // Simple imgui-window // mousepos could be passed to imgui before event-handling and check this // to not pass mouse-events to program if hovering ImGui::GetIO().MouseDrawCursor = ImGui::IsMouseHoveringAnyWindow(); { ImGui::SliderFloat("x", &modelPos3f_.x, -2.f, 2.f); ImGui::SliderFloat("y", &modelPos3f_.y, -2.f, 2.f); ImGui::SliderFloat("z", &modelPos3f_.z, -2.f, 2.f); ImGui::Text("%.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); } pg_.bind(); mat4 translate( 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, modelPos3f_.x, modelPos3f_.y, modelPos3f_.z, 1.f ); mat4 scale(modelScale3f_.x, 0.f, 0.f, 0.f, 0.f, modelScale3f_.y, 0.f, 0.f, 0.f, 0.f, modelScale3f_.z, 0.f, 0.f, 0.f, 0.f, 1.f ); mat4 rotY(cos(modelRotY1f_), 0.f, -sin(modelRotY1f_), 0.f, 0.f, 1.f, 0.f, 0.f, sin(modelRotY1f_), 0.f, cos(modelRotY1f_), 0.f, 0.f, 0.f, 0.f, 1.f ); mat4 modelToWorld = translate * rotY * scale; mat4 viewMat = cam_.getViewMat(); mat4 projMat = cam_.getProjMat(); mat4 modelToCam = viewMat * modelToWorld; mat4 modelToClip = projMat * modelToCam; mat3 normalToCam = transpose(inverse(mat3(modelToCam[0][0], modelToCam[0][1], modelToCam[0][2], modelToCam[1][0], modelToCam[1][1], modelToCam[1][2], modelToCam[2][0], modelToCam[2][1], modelToCam[2][2] ))); mat3 worldToCam = transpose(inverse(mat3(viewMat[0][0], viewMat[0][1], viewMat[0][2], viewMat[1][0], viewMat[1][1], viewMat[1][2], viewMat[2][0], viewMat[2][1], viewMat[2][2] ))); pg_.updateModelToCam(modelToCam); pg_.updateModelToClip(modelToClip); pg_.updateNormalToCam(normalToCam); pg_.updateToLight(normalize(worldToCam * lightPos3f_)); model_.render(pg_); }
33.496
110
0.541438
b6e50918f04aefb0c3ddd2c5dde4d44ea56b5657
1,401
cpp
C++
6502/main.cpp
mavroskardia/6502
bc7a278ecc8b9f18e845240b014c6513df5e9e9e
[ "MIT" ]
1
2016-02-27T19:23:13.000Z
2016-02-27T19:23:13.000Z
6502/main.cpp
mavroskardia/6502
bc7a278ecc8b9f18e845240b014c6513df5e9e9e
[ "MIT" ]
null
null
null
6502/main.cpp
mavroskardia/6502
bc7a278ecc8b9f18e845240b014c6513df5e9e9e
[ "MIT" ]
null
null
null
#include "includes.h" int do_assembly(const char*); int do_run(const char*); int do_tests(); int main(int argc, char** argv) { int ret = 0; switch (argc) { case 2: ret = string("test").compare(argv[1]) == 0 ? do_tests() : 1; break; case 3: if (string("assemble").compare(argv[1]) == 0) ret = do_assembly(argv[2]); else if (string("run").compare(argv[1]) == 0) ret = do_run(argv[2]); break; default: cout << "usage: " << argv[0] << " <6502 assembly file>" << endl; ret = 1; } return ret; } int do_assembly(const char* filename) { int ret = 0; auto assembler = Assembler(filename); cout << "build assembler for file " << filename << endl; try { while (!assembler.eof()) { stringstream lineout; lineout << assembler.current_line_number() << ":\t"; vector<unsigned char> decoded = assembler.decodeline(); for (auto c : decoded) lineout << "0x" << hex << (int)c; cout << lineout.str() << endl; } } catch (SyntaxException se) { cerr << "Failed to assemble file: " << se.what(); ret = 1; } catch (UnknownInstruction ui) { cerr << "Failed to assemble file: " << ui.what(); ret = 1; } catch (regex_error& re) { cerr << "A regular expression failed: " << re.what() << " " << re.code() << endl; ret = 1; } return ret; } int do_run(const char* filename) { int ret = 0; Executor e; if (e.load(filename)) e.run(); return ret; }
20.602941
83
0.598858