blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
117
path
stringlengths
3
268
src_encoding
stringclasses
34 values
length_bytes
int64
6
4.23M
score
float64
2.52
5.19
int_score
int64
3
5
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
text
stringlengths
13
4.23M
download_success
bool
1 class
fbdefb118b2b1cd2ff2d1800ce5678612df2d1e7
C++
Kanazawanaoaki/atcoder_memo
/abc/abc116/abc116c2.cpp
UTF-8
1,686
2.625
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <string> #include <sstream> #include <complex> #include <vector> #include <list> #include <queue> #include <deque> #include <stack> #include <map> #include <set> using namespace std; /*hantei(int num,int *h){ int mini=100; for(int i=num;i<N;i++){ if(h[i]==0)hantei(i,h); if(h[i]<mini && h[i]>0)mini=h[i]; } }*/ int main(){ int count=0; int end=0; int N; int index1=0; int index2=0; cin >> N; int h[N]; for(int i=0;i<N;i++){ cin >> h[i]; } while(end==0){ int k=0; for(int j=0;j<N;j++){ //cout << h[i]; if(h[j]>0)k++; } //cout << endl; if(k==0)end++; for(int i=0;i<N;i++){ while(h[i]>0){ int bre=0; for(int j=i;j<N&&bre==0;j++){ if(h[j]>0)h[j]-=1; else bre++; //cout << j << h[j] << endl; } count++; //cout << count << endl; } } /*int mini=100; i=index1=index2; //cout << "index2:" << index2 << " "; for(i;i<N;i++){ if(h[i]<mini && h[i]>0)mini=h[i]; } if(mini==100){index2=0;continue;} cout << mini << endl; index2=0; i=index1; for(i;i<N;i++){ h[i] -= mini; cout << h[i]; if(h[i]==0){cout << i << endl;index2=i;} }*/ //cout << "count" << endl; //count+=mini; } cout << count <<endl; }
true
469d2e65128f48e549d773137577b3bab99fb724
C++
chetui/libvsf
/src/framework/vm.cpp
UTF-8
10,117
2.515625
3
[ "BSD-2-Clause" ]
permissive
#include "framework/vm.h" #include <map> #include "utils/log.h" using namespace std; VmSet::VmSet() { func_option_ = FuncOption::get_instance(); vm_base_ = VmBase::get_instance(); vm_cpu_usage_ = VmCpuUsage::get_instance(); vm_cache_miss_ = VmCacheMiss::get_instance(); } VmSet::~VmSet() { delete_callback(Option::OP_VM_BASE); delete_callback(Option::OP_VM_CPU_USAGE); delete_callback(Option::OP_VM_CACHE_MISS); } VmSet* VmSet::get_instance() { static VmSet vm_set; return &vm_set; } void VmSet::set_param(std::map<Option, std::map<OptionParam, OptionParamVal> > ops) { for (auto& op : ops) { switch (op.first) { case Option::OP_VM_BASE: case Option::OP_VM_CPU_USAGE: case Option::OP_VM_CACHE_MISS: if(func_option_->check_option(op.first)) delete_callback(op.first); set_param_by_option(op.first, op.second); break; default: break; } } func_option_->enable_option(ops); } void VmSet::clear_param(std::vector<Option> ops) { for (auto& op : ops) { switch (op) { case Option::OP_VM_BASE: if(func_option_->check_option(op)) { delete_callback(op); func_option_->enable_option({ { Option::OP_VM_BASE, { { OptionParam::VM_CMD, VmBase::DEFAULT_VM_CMD }, { OptionParam::LOOP_INTERVAL, VmBase::DEFAULT_INTERVAL_MS }, { OptionParam::CALLBACK, NULL } } } }); } vm_base_->clear_param(); case Option::OP_VM_CPU_USAGE: if(func_option_->check_option(op)) { delete_callback(op); func_option_->enable_option({ { Option::OP_VM_CPU_USAGE, { { OptionParam::LOOP_INTERVAL, VmCpuUsage::DEFAULT_INTERVAL_MS }, { OptionParam::CALLBACK, NULL } } } }); } vm_cpu_usage_->clear_param(); case Option::OP_VM_CACHE_MISS: if(func_option_->check_option(op)) { delete_callback(op); func_option_->enable_option({ { Option::OP_VM_CACHE_MISS, { { OptionParam::LOOP_INTERVAL, VmCacheMiss::DEFAULT_LOOP_INTERVAL_MS }, { OptionParam::SAMPLE_INTERVAL, VmCacheMiss::DEFAULT_SAMPLE_INTERVAL_MS }, { OptionParam::CALLBACK, NULL } } } }); } vm_cache_miss_->clear_param(); break; default: break; } } } void VmSet::delete_callback(Option op) { switch (op) { case Option::OP_VM_BASE: if (func_option_->check_option(Option::OP_VM_BASE)) { map<OptionParam, OptionParamVal> &param = func_option_->get_param(Option::OP_VM_BASE); for (auto & p : param) { switch(p.first) { case OptionParam::CALLBACK: delete (vm_base_callback_t*)p.second.get_pointer(); break; default: break; } } } break; case Option::OP_VM_CPU_USAGE: if (func_option_->check_option(Option::OP_VM_CPU_USAGE)) { map<OptionParam, OptionParamVal> &param = func_option_->get_param(Option::OP_VM_CPU_USAGE); for (auto & p : param) { switch(p.first) { case OptionParam::CALLBACK: delete (cpu_usage_callback_t*)p.second.get_pointer(); break; default: break; } } } break; case Option::OP_VM_CACHE_MISS: if (func_option_->check_option(Option::OP_VM_CACHE_MISS)) { map<OptionParam, OptionParamVal> &param = func_option_->get_param(Option::OP_VM_CACHE_MISS); for (auto & p : param) { switch(p.first) { case OptionParam::CALLBACK: delete (cache_miss_callback_t*)p.second.get_pointer(); break; default: break; } } } break; default: break; } } void VmSet::set_param_by_option(const Option& op, map<OptionParam, OptionParamVal>& op_param) { switch (op) { case Option::OP_VM_BASE: for (auto & p : op_param) { switch(p.first) { case OptionParam::VM_CMD: vm_base_->set_vm_cmd(p.second.get_string()); break; case OptionParam::LOOP_INTERVAL: vm_base_->set_interval(p.second.get_int()); break; case OptionParam::CALLBACK: vm_base_->set_callback(*((vm_base_callback_t*)p.second.get_pointer())); break; default: //cerr message "invalid parameter for OP_VM_BASE" break; } } break; case Option::OP_VM_CPU_USAGE: for (auto & p : op_param) { switch(p.first) { case OptionParam::LOOP_INTERVAL: vm_cpu_usage_->set_interval(p.second.get_int()); break; case OptionParam::CALLBACK: vm_cpu_usage_->set_callback(*((cpu_usage_callback_t*)p.second.get_pointer())); break; default: //cerr message "invalid parameter" break; } } break; case Option::OP_VM_CACHE_MISS: for (auto & p : op_param) { switch(p.first) { case OptionParam::LOOP_INTERVAL: vm_cache_miss_->set_loop_interval(p.second.get_int()); break; case OptionParam::SAMPLE_INTERVAL: vm_cache_miss_->set_sample_interval(p.second.get_int()); break; case OptionParam::CALLBACK: vm_cache_miss_->set_callback(*((cache_miss_callback_t*)p.second.get_pointer())); break; default: //cerr message "invalid parameter" break; } } break; default: break; } } std::set<VM> VmSet::init_vms(Host *host) { lock_guard<mutex> lock(init_vms_mutex_); //TODO check whether host is inited host = host; set<VM> vms; if (func_option_->check_option(Option::OP_VM_BASE)) { set_param_by_option(Option::OP_VM_BASE, func_option_->get_param(Option::OP_VM_BASE)); if (!vm_base_->joinable()) vm_base_->start(); } if (func_option_->check_option(Option::OP_VM_CPU_USAGE)) { set_param_by_option(Option::OP_VM_CPU_USAGE, func_option_->get_param(Option::OP_VM_CPU_USAGE)); if (!vm_cpu_usage_->joinable()) vm_cpu_usage_->start(); } if (func_option_->check_option(Option::OP_VM_CACHE_MISS)) { set_param_by_option(Option::OP_VM_CACHE_MISS, func_option_->get_param(Option::OP_VM_CACHE_MISS)); if (!vm_cache_miss_->joinable()) vm_cache_miss_->start(); } set<VmId> vm_ids = vm_base_->get_vm_ids(); for (auto& vm_id : vm_ids) vms.insert(VM(vm_id)); return vms; } VM::VM(VmId vm_id) { vm_base_ = VmBase::get_instance(); vm_cpu_usage_ = VmCpuUsage::get_instance(); vm_cache_miss_ = VmCacheMiss::get_instance(); cpu_mig_ = CpuMig::get_instance(); vm_id_ = vm_id; } //OP_VM_BASE VmId VM::vm_id() const { return vm_id_; } string VM::name() const { return vm_base_->get_name(vm_id_); } string VM::uuid() const { return vm_base_->get_uuid(vm_id_); } int VM::vsocket_num() const { return vm_base_->get_vsocket_num(vm_id_); } int VM::vcore_num() const { return vm_base_->get_vcore_num(vm_id_); } int VM::vhpthread_num() const { return vm_base_->get_vhpthread_num(vm_id_); } int VM::total_mem_size() const { return vm_base_->get_total_mem_size(vm_id_); } set<pid_t> VM::vcpu_ids() const { return vm_base_->get_vcpu_ids(vm_id_); } int VM::vcpu_num() const { return vm_base_->get_vcpu_num(vm_id_); } set<pid_t> VM::stable_vmthread_ids() const { return vm_base_->get_stable_vmthread_ids(vm_id_); } int VM::stable_vmthread_num() const { return vm_base_->get_stable_vmthread_num(vm_id_); } set<pid_t> VM::volatile_vmthread_ids() const { return vm_base_->get_volatile_vmthread_ids(vm_id_); } int VM::volatile_vmthread_num() const { return vm_base_->get_volatile_vmthread_num(vm_id_); } //OP_VM_CPU_USAGE int VM::sys_cpu_usage() const { return vm_cpu_usage_->get_sys_cpu_usage(); } int VM::cpu_usage() const { return vm_cpu_usage_->get_cpu_usage(vm_id_); } int VM::cpu_usage(pid_t vmthread_id) const { return vm_cpu_usage_->get_cpu_usage(vmthread_id); } HpthreadId VM::running_on_hpthread(pid_t vmthread_id) const { return vm_cpu_usage_->get_running_on_hpthread(vmthread_id); } //OP_VM_CACHE_MISS CacheMissData VM::cache_miss() const { return vm_cache_miss_->get_cache_miss(vm_id_); } CacheMissData VM::cache_miss(pid_t vmthread_id) const { return vm_cache_miss_->get_cache_miss(vmthread_id); } //VCPU MIG void VM::set_vcpu_mig(pid_t vmthread_id, std::set<HpthreadId> hpthread_ids) const { set<int> ids; for (auto& id : hpthread_ids) ids.insert(id.id); cpu_mig_->set_cpu_mig(vmthread_id, ids); } VM& VM::operator=(const VM &v) { vm_id_ = v.vm_id(); return *this; } bool operator<(const VM &lv, const VM &rv) { return lv.vm_id() < rv.vm_id(); }
true
d3748a1faa9b2913c3d532d4676bb1c4029bdf09
C++
GP101/DiconServer
/boostTest/boostTest/boostTest_CriticalSection RAII.cpp
UTF-8
1,196
2.84375
3
[]
no_license
#include <iostream> #include <typeinfo> #include <windows.h> #include <boost/assert.hpp> #include "KGen.h" struct KCriticalSection : public CRITICAL_SECTION { KCriticalSection( ) { InitializeCriticalSection( this ); } ~KCriticalSection( ) { DeleteCriticalSection( this ); } }; class KCriticalSectionLock { public: KCriticalSectionLock( CRITICAL_SECTION& cs ) : m_pcs( &cs ) { printf( "constructor\r\n" ); BOOST_ASSERT( m_pcs != nullptr ); EnterCriticalSection( m_pcs ); } ~KCriticalSectionLock( ) { printf( "destructor\r\n" ); if( m_pcs != nullptr ) LeaveCriticalSection( m_pcs ); } explicit operator bool() { return true; } protected: CRITICAL_SECTION* m_pcs; }; void main( ) { printf( "hello\r\n" ); KCriticalSection cs; if( KCriticalSectionLock lock = cs ) { printf( "inside if\r\n" ); } printf( "world\r\n" ); }
true
b506959f0b3bec1847ca9d2a7e9d1dd3bd73cced
C++
jayekub/glToy
/src/include/Camera.h
UTF-8
859
2.640625
3
[]
no_license
#ifndef CAMERA_H_ #define CAMERA_H_ #include "Node.h" #include "Visitor.h" #include "Vec.h" class Light; struct Camera : public Node { enum ProjectionType { FLAT, ORTHO, PERSP }; ProjectionType projection; // common params float nearClip, farClip; Vec3 position, center, up; // ortho params float width, height; // persp params float fov; // shadow cam params bool isShadowCamera; Light *light; // motion blur params double dt; void accept(Visitor *visitor) { visitor->visitCamera(this); } Camera(const char *name_) : Node(name_), projection(PERSP), nearClip(1.), farClip(1000.), position(0., 0., 0.), center(0., 0., 1.), up(0., 1., 0.), width(2.), height(2.), fov(45), isShadowCamera(false), light(NULL), dt(0.) {}; }; #endif /* CAMERA_H_ */
true
c06300a5343f8fb0b16b0702833db22c9b9f97b7
C++
fritzo/kazoo
/src/synthesis_profile.cpp
UTF-8
691
2.546875
3
[ "MIT" ]
permissive
#include "synthesis.h" using namespace Synthesis; void profile_chorus ( float duration_seconds = 10.0f, size_t num_voices = 8) { size_t T = roundi(duration_seconds * DEFAULT_SAMPLE_RATE); size_t dT = DEFAULT_FRAMES_PER_BUFFER; Chorus synth; Ids ids(num_voices); Vector<float> energies(num_voices); Vector<float4> positions(num_voices); Vector<complex> sound(dT); for (size_t t = 0; t < T; t += dT) { for (size_t i = 0; i < num_voices; ++i) { ids[i] = i; energies[i] = 1; positions[i] = float4(i,0,1,0); } sound.zero(); synth.sample(ids, energies, positions, sound); } } int main () { profile_chorus (); return 0; }
true
b559c1ae2d3b608d5f79f8402adea18c2eb53138
C++
ankit-akp/DS-Algo-Cp_Codes_CN
/RangeQuery/OrderSet - Problem.cpp
UTF-8
1,002
3.671875
4
[]
no_license
/* In this problem, you have to maintain a dynamic set of numbers which support the two fundamental operations INSERT(S,x): if x is not in S, insert x into S DELETE(S,x): if x is in S, delete x from S and the two type of queries K-TH(S) : return the k-th smallest element of S COUNT(S,x): return the number of elements of S smaller than x Input Format: Line 1: Q , the number of operations In the next Q lines, the first token of each line is a character I, D, K or C meaning that the corresponding operation is INSERT, DELETE, K-TH or COUNT, respectively, following by a whitespace and an integer which is the parameter for that operation. Constraints: 1 <= Q <= 2*10^5 -10^9 <= x <= 10^9 Output Format: For each query, print the corresponding result in a single line. In particular, for the queries K-TH, if k is larger than the number of elements in S, print the word 'invalid'. Sample Input 1: 8 I -1 I -1 I 2 C 0 K 2 D -1 K 1 K 2 Sample Output 1: 1 2 2 invalid */
true
003d1c692ac9ab932ed8ebb92d832302424d8149
C++
qualificationalitated/Start_git
/Algorithm/5000~5999/5972/5972.cpp
UTF-8
1,772
3.046875
3
[]
no_license
#include<iostream> #include<vector> #include<queue> #define HUTS 50002 #define LINE 50002 #define LIM 2147483647 using namespace std; vector<pair<int,int>> map[LINE]; int minCost[HUTS]={0,}; int dijkstra(int start){ priority_queue<pair<int,int>> pq; minCost[start]=0; pq.push({0,start}); // 시작 위치의 거리 & 지점 설정하고 while(!pq.empty()){ // 큐가 빌때까지 돕니다 // 지금 지점 선정하고 int nowHut=pq.top().second; int nowCost=pq.top().first*-1; // 최소값 선정은 -1을 곱해주자, 애초에 음수로 들어간걸 양수로 바꾸는 과정 pq.pop(); if(minCost[nowHut]<nowCost) // 이미 최대값이 갱신된경우 처리하지 않음 continue; // 지금 지점에서 연결된 모든 지점 탐색, 가중치 갱신 for (int i = 0; i < map[nowHut].size(); i++) { int nextHut = map[nowHut][i].first; int nextCost = map[nowHut][i].second + nowCost; if(nextCost<minCost[nextHut]){ minCost[nextHut] = nextCost; pq.push(make_pair(nextCost*-1, map[nowHut][i].first)); // 다익스트라에서 최소 비용 선정시 -1 곱해서, 음으로 넣어주기 // 주의! 큐에는 음으로 넣고, 처리할때는 -1 곱해서 양으로 뽑는거다. } } } return 0; } int main(){ int n,m; int A,B,C; cin>>n>>m; fill(minCost,minCost+HUTS,LIM); // 모든값을 최대값으로 갱신 while(m--){ cin>>A>>B>>C; map[A].push_back({B,C}); map[B].push_back({A,C}); } //1번 헛간부터 출발해, N번 헛간으로 가자 dijkstra(1); cout<<minCost[n]; return 0; }
true
75efa6abf599e3313389d2e2fcfbf1311b3c9fb0
C++
shieldscr/FizzBuzzCPP
/tests/FizzBuzzTest.cpp
UTF-8
298
2.703125
3
[ "MIT" ]
permissive
#include <gtest/gtest.h> #include "FizzBuzz.h" TEST(FizzBuzz, FizzBuzz_returns_number_passed) { FizzBuzz fizzBuzz = FizzBuzz(); ASSERT_EQ("1", fizzBuzz.Fizz(1)); } TEST(FizzBuzz, FizzBuzz_returns_Fizz_When_Given_3) { FizzBuzz fizzBuzz = FizzBuzz(); ASSERT_EQ("fizz", fizzBuzz.Fizz(3)); }
true
697bb5ff15266518a616a00f90e34322cf546d27
C++
adas-eye/cpp_algorithm
/chapter3/书面作业/exercise3-8.cpp
GB18030
2,348
3.8125
4
[]
no_license
#include <iostream> #include <time.h> #include <stdlib.h> using namespace std; int ToolRandInt(int min, int max) { srand((unsigned)time(NULL)); int r = rand() % (max - min + 1) + min; return r; } class CardDeck { private: int cards[52]; int currentCrd; public: //캯 CardDeck(void); //ϴ void Shuffle(void); //һ int GetCard(void); //÷0-12 13-2526-3839-51ÿɫ //һΪAΪJQK.CΪɫ ֵ void PrintCard(int c); //չʾӡ void ShowCards(void); }; CardDeck::CardDeck(void) { int length = sizeof(cards) / sizeof(cards[0]); //cout << length << endl;; for (int i = 0; i < length; i++) cards[i] = i; currentCrd = 0; Shuffle(); } void CardDeck::Shuffle(void) { int length = sizeof(cards) / sizeof(cards[0]); //cout << length << endl;; for (int j = 0; j < length; j++) { int randnumber = ToolRandInt(j, length - 1); // int tmp = cards[j]; cards[j] = cards[randnumber]; cards[randnumber] = tmp; } } int CardDeck::GetCard(void) { if (currentCrd <= 51) currentCrd += 1; else { cout << "Ѿ." << endl; return -1; } int result = cards[currentCrd - 1]; return result; } void CardDeck::PrintCard(int c) { if (0 <= c && c < 13) cout << "÷ "; else if (13 <= c && c < 26) cout << " "; else if (26 <= c && c < 39) cout << " "; else if (39 <= c && c < 52) cout << ""; else cout << "ŷΧӦ0-51֮." << endl; return; switch (c%13) { case 0: cout << "A"; case 1: cout << "2"; case 2: cout << "3"; case 3: cout << "4"; case 4: cout << "5"; case 5: cout << "6"; case 6: cout << "7"; case 7: cout << "8"; case 8: cout << "9"; case 9: cout << "10"; case 10: cout << "J"; case 11: cout << "Q"; case 12: cout << "K"; } cout << endl; } void CardDeck::ShowCards(void) { int length = sizeof(cards) / sizeof(cards[0]); for (int i = 0; i < length ; i++) { if (cards[i] >= 0) { cout << cards[i] << ", "; } } cout << endl; } //int main() //{ // CardDeck cd; // cd.ShowCards(); // cd.Shuffle(); // cd.ShowCards(); // cout << cd.GetCard() << endl; // cout << cd.GetCard() << endl; // system("pause"); //}
true
5b798e5ca0cb2715e94438c296244b78ef1e4be3
C++
jonike/Conception
/src/ConceptStream.cpp
UTF-8
310
2.53125
3
[]
no_license
#include "Main.h" ConceptStream::ConceptStream() { } ConceptStream::~ConceptStream() { } ConceptStream & ConceptStream::operator << (ConceptStream & (* Function)(ConceptStream &)) { (*Function)(*this); return *this; } ConceptStream & endl(ConceptStream & stream) { stream.NewLine(); return stream; }
true
c50e85657d4149925de92e5321a07f658ed59f21
C++
jsn0716/Software
/src/software/proto/message_translation/ssl_simulation_robot_control_test.cpp
UTF-8
4,409
2.65625
3
[ "LGPL-3.0-only" ]
permissive
#include "software/proto/message_translation/ssl_simulation_robot_control.h" #include <gtest/gtest.h> TEST(SSLSimulationProtoTest, test_create_robot_move_command_stationary) { auto move_command = createRobotMoveCommand(0, 0, 0, 0); ASSERT_TRUE(move_command); // Expect that the local velocity has some positive value, and that there is minimum // left or angular velocity EXPECT_NEAR(move_command->local_velocity().forward(), 0.0, 1e-5); EXPECT_NEAR(move_command->local_velocity().left(), 0.0, 1e-5); EXPECT_NEAR(move_command->local_velocity().angular(), 0.0, 1e-5); } TEST(SSLSimulationProtoTest, test_create_robot_move_command_forward) { auto move_command = createRobotMoveCommand(60, -60, -60, 60); ASSERT_TRUE(move_command); // Expect that the local velocity has some positive value, and that there is minimum // left or angular velocity EXPECT_GT(move_command->local_velocity().forward(), 0.1); EXPECT_NEAR(move_command->local_velocity().left(), 0.0, 1e-5); EXPECT_NEAR(move_command->local_velocity().angular(), 0.0, 1e-5); } TEST(SSLSimulationProtoTest, test_create_robot_move_command_backward) { auto move_command = createRobotMoveCommand(-60, 60, 60, -60); ASSERT_TRUE(move_command); // Expect that the local velocity has some positive value, and that there is minimum // left or angular velocity EXPECT_LT(move_command->local_velocity().forward(), -0.1); EXPECT_NEAR(move_command->local_velocity().left(), 0.0, 1e-5); EXPECT_NEAR(move_command->local_velocity().angular(), 0.0, 1e-5); } TEST(SSLSimulationProtoTest, test_create_robot_command) { auto move_command = createRobotMoveCommand(60, -60, -60, 60); auto robot_command = createRobotCommand(1, std::move(move_command), 2.0, 3.0, 4.0); ASSERT_TRUE(robot_command); ASSERT_TRUE(robot_command->has_move_command()); EXPECT_EQ(1, robot_command->id()); EXPECT_FLOAT_EQ(2.0, robot_command->kick_speed()); EXPECT_FLOAT_EQ(3.0, robot_command->kick_angle()); EXPECT_FLOAT_EQ(4.0, robot_command->dribbler_speed()); EXPECT_GT(robot_command->move_command().local_velocity().forward(), 0.1); EXPECT_NEAR(robot_command->move_command().local_velocity().left(), 0.0, 1e-5); EXPECT_NEAR(robot_command->move_command().local_velocity().angular(), 0.0, 1e-5); } TEST(SSLSimulationProtoTest, test_create_robot_command_unset_optional_fields) { auto move_command = createRobotMoveCommand(60, -60, -60, 60); auto robot_command = createRobotCommand(1, std::move(move_command), std::nullopt, std::nullopt, std::nullopt); ASSERT_TRUE(robot_command); ASSERT_TRUE(robot_command->has_move_command()); EXPECT_EQ(1, robot_command->id()); EXPECT_FALSE(robot_command->has_kick_speed()); EXPECT_FALSE(robot_command->has_kick_angle()); EXPECT_FALSE(robot_command->has_dribbler_speed()); EXPECT_GT(robot_command->move_command().local_velocity().forward(), 0.1); EXPECT_NEAR(robot_command->move_command().local_velocity().left(), 0.0, 1e-5); EXPECT_NEAR(robot_command->move_command().local_velocity().angular(), 0.0, 1e-5); ; } TEST(SSLSimulationProtoTest, test_create_robot_control) { auto move_command_1 = createRobotMoveCommand(60, -60, -60, 60); auto robot_command_1 = createRobotCommand(1, std::move(move_command_1), 2.0, 3.0, 4.0); auto move_command_2 = createRobotMoveCommand(-60, 60, 60, -60); auto robot_command_2 = createRobotCommand(2, std::move(move_command_2), 4.0, 6.0, 8.0); std::vector<std::unique_ptr<SSLSimulationProto::RobotCommand>> robot_commands = {}; robot_commands.push_back(std::move(robot_command_1)); robot_commands.push_back(std::move(robot_command_2)); auto robot_control = createRobotControl(std::move(robot_commands)); unsigned robot_id = 1; for (auto robot_command : *robot_control->mutable_robot_commands()) { // Negative sign if robot id is even float sign = robot_id % 2 == 0 ? -1.0f : 1.0f; EXPECT_EQ(robot_id, robot_command.id()); EXPECT_GT(sign * robot_command.move_command().local_velocity().forward(), 0.1); EXPECT_NEAR(robot_command.move_command().local_velocity().left(), 0.0, 1e-5); EXPECT_NEAR(robot_command.move_command().local_velocity().angular(), 0.0, 1e-5); robot_id++; } }
true
7394bb9c131362b74be15f6aaec9d2021df57e70
C++
Shadow1329/spacebattles
/SpaceBattles/Server/UserInformation.h
UTF-8
313
3.125
3
[]
no_license
#pragma once #include <string> #include <stdio.h> #include <iostream> class UserInformation { private: int ID; std::string Name; public: UserInformation(int ID, std::string Name) { this->ID = ID; this->Name = Name; } int getUserID() { return ID; }; std::string getUserName() { return Name; }; };
true
e656be43459d085994ea1e064dfa0477f98a5bfb
C++
rspiegel/cppProjects
/maze/maze.h
UTF-8
2,652
3.234375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <string.h> #include <string> #include <vector> using namespace std; class maze { private: int rows; int cols; int begin; int end; vector<char> map; public: maze() { rows=0; cols=0; begin = -1; end = -1; } void parse_board(istream& r) { r>>rows; r>>cols; char temp; for(int x=0;x<rows*cols;++x) { r>>temp; if(temp == 'B') begin = x; if(temp == 'E') end = x; map.push_back(temp); } } void print_board(ostream& w) { int count=0; for(int x=0;x<rows*cols;++x) { char temp = map[x]; // if(temp=='-' || temp=='=' || temp=='+') // w<<' '; // else if(temp=='*') // w<<'-'; // else w<<temp; if(count==(cols-1)) { w<<endl; count=0; } else count++; } } void run() { if(begin == -1) cout<<"No begin."<<endl; else if(end == -1) cout<<"No end."<<endl; else follow_path(begin); } void follow_path(int spot) { if(map[spot] == '@') return; else if(map[spot]!='B'/* && map[spot]!='+'*/) map[spot] = '='; int n = spot-cols; int e = spot+1; int w = spot-1; int s = spot+cols; int numPaths = 0; if(map[n] == 'E' || map[e] == 'E' || map[s] == 'E' || map[w] == 'E') { // tracefinal(spot); return; } if(n>0 && map[n] == '.') numPaths++; if(e>0 && map[e] == '.') numPaths++; if(s>0 && map[s] == '.') numPaths++; if(w>0 && map[w] == '.') numPaths++; if(numPaths > 1 && map[spot]!='B') map[spot] = '+'; if(numPaths == 0) { rollback(spot); } if(n>0 && map[n] == '.') follow_path(n); if(e>0 && map[e] == '.') follow_path(e); if(s>0 && map[s] == '.') follow_path(s); if(w>0 && map[w] == '.') follow_path(w); } void rollback(int spot) { if(map[spot] != '=') return; else { map[spot] = '-'; int n = spot-cols; int e = spot+1; int w = spot-1; int s = spot+cols; if(map[n] == '=') rollback(n); if(map[e] == '=') rollback(e); if(map[s] == '=') rollback(s); if(map[w] == '=') rollback(w); } } void tracefinal(int spot) { int n = spot-cols; int e = spot+1; int w = spot-1; int s = spot+cols; if(map[n] == 'B' || map[e] == 'B' || map[s] == 'B' || map[w] == 'B') { map[spot] = '*'; return; } else { if(map[spot]!='E') map[spot] = '*'; if(n>0 && (map[n] == '=' || map[n] == '+')) tracefinal(n); if(e>0 && (map[e] == '=' || map[e] == '+')) tracefinal(e); if(s>0 && (map[s] == '=' || map[s] == '+')) tracefinal(s); if(w>0 && (map[w] == '=' || map[w] == '+')) tracefinal(w); } } };
true
ad2fcefde5318519dce2307e9610974a348fa7f8
C++
ismailartun00/Tutorials
/C++/Comp315/Lesson3/sudoInheritance.cpp
UTF-8
779
3.546875
4
[]
no_license
#include <iostream> #include <string> class Vehicle{ public: std::string idnumber; virtual std::string gettype() = 0; virtual std::string idnumber(){ return idnumber; } }; class Car{ public: Car(std::string idnumber){ this->idnumber = idnumber; } virtual std::string gettype(){ return "Car"; } }; class Plane{ virtual std::string gettype(){ return "Plane"; } virtual std::string idnumber(){ return "[NA]"; } }; void printVehicle(Vehicle &v){ std::cout << v.gettype() << ": " << v.idnumber(); } int main(){ Car c1("AB 123"); Plane p; printVehicle(c1); printVehicle(p); std::cin.get(); }
true
79a5e7a03c14fdfa169ab6f360ff6f4d8c6b9e58
C++
betallcoffee/leetcode
/old/Swap Nodes In Pairs/Swap Nodes In Pairs/main.cpp
UTF-8
2,098
3.859375
4
[ "Apache-2.0" ]
permissive
// // main.cpp // Swap Nodes In Pairs // // Created by liang on 6/22/15. // Copyright (c) 2015 tina. All rights reserved. // Problem: https://leetcode.com/problems/swap-nodes-in-pairs/ //Given a linked list, swap every two adjacent nodes and return its head. // //For example, //Given 1->2->3->4, you should return the list as 2->1->4->3. // //Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. #include <iostream> using namespace std; //Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode *p = head; ListNode *q = nullptr; while (p) { ListNode *t = p->next; if (t) { p->next = t->next; t->next = p; if (q) { q->next = t; } q = p; p = p->next; if (t->next == head) { head = t; } } else { p = t; } } return head; } }; ListNode *createList(int nums[], int count) { ListNode *p = nullptr; ListNode *head = nullptr; for (int i = 0; i < count; i++) { if (p) { p->next = (ListNode *)calloc(sizeof(ListNode), 1); p = p->next; } else { p = (ListNode *)calloc(sizeof(ListNode), 1); head = p; } p->val = nums[i]; } return head; } void printList(ListNode *head) { while (head) { cout << head->val << "->"; head = head->next; } cout << endl; } int main(int argc, const char * argv[]) { Solution s; int case1[] = {1, 3, 5, 23, 87}; printList(s.swapPairs(createList(case1, sizeof(case1) / sizeof(int)))); int case2[] = {3, 5, 8, 9, 10}; printList(s.swapPairs(createList(case2, sizeof(case2) / sizeof(int)))); return 0; }
true
9816d76828ae88537a08157fb5d8352dd51106fa
C++
brandoryan/process-scheduler
/process-scheduler.cpp
UTF-8
5,612
3.265625
3
[]
no_license
#include <iostream> #include <fstream> #include <vector> #include <iterator> #include <string> using namespace std; struct process { string pid; int burst_time; int wait_time = 0; }; struct compPID { bool operator()(process const &a, process const &b) { return a.pid < b.pid; } }; struct compBT { bool operator()(process const &a, process const &b) { return a.burst_time < b.burst_time; } }; int averageWaitTime(vector<process> processes) { // Computing the average wait time for all processes int avg_wait_time = 0; int total_wait_time = 0; for(vector<process>::iterator it = processes.begin(); it != processes.end(); ++it) { total_wait_time += it->wait_time; } //cout << total_wait_time << " " << processes.size(); avg_wait_time = total_wait_time / processes.size(); return avg_wait_time; } int processesCompleted(vector<process> processes) { int total_burst_time = 0; for(vector<process>::iterator it = processes.begin(); it != processes.end(); ++it) { total_burst_time += it->burst_time; } if(total_burst_time == 0) { return true; } else { return false; } } int fcfs(vector<process> processes) { // First sorting by PID to see what process runs first since all arrive at 0 sort(processes.begin(), processes.end(), compPID()); while(!processesCompleted(processes)) { for(vector<process>::iterator it = processes.begin(); it != processes.end(); ++it) { // Add the burst time to the waiting times of the other processes for(vector<process>::iterator it2 = processes.begin(); it2 != processes.end(); ++it2) { if(it2->burst_time != 0 && it2->pid != it->pid) { it2->wait_time+=it->burst_time; } } it->burst_time = 0; } } return averageWaitTime(processes); } int sjf(vector<process> processes) { // First sorting by shortest burst time to see what process runs first sort(processes.begin(), processes.end(), compBT()); while(!processesCompleted(processes)) { for(vector<process>::iterator it = processes.begin(); it != processes.end(); ++it) { // Add the burst time to the waiting times of the other processes for(vector<process>::iterator it2 = processes.begin(); it2 != processes.end(); ++it2) { if(it2->burst_time != 0 && it2->pid != it->pid) { it2->wait_time+=it->burst_time; } } it->burst_time = 0; } } return averageWaitTime(processes); } int rr(vector<process> processes) { int time_slice = 10; //milliseconds vector<process>::iterator it = processes.begin(); while(!processesCompleted(processes)) { /* Step Checking for(vector<process>::iterator it = processes.begin(); it != processes.end(); ++it) { cout << it->pid << ": " << it->burst_time << ", " << it->wait_time << endl; } */ for(vector<process>::iterator it = processes.begin(); it != processes.end(); ++it) { // If the time slice is more than the remaining burst time if(it->burst_time-time_slice <= 0 && !processesCompleted(processes)) { // Add the burst time to the waiting times of the other processes for(vector<process>::iterator it2 = processes.begin(); it2 != processes.end(); ++it2) { if(it2->burst_time != 0 && it2->pid != it->pid) { it2->wait_time+=it->burst_time; } } // Remove the time slice from the current process it->burst_time = 0; } // If the burst time is bigger than the time slice else if(it->burst_time-time_slice > 0 && !processesCompleted(processes)){ // Add the burst time to the wait time of the other processes for(vector<process>::iterator it2 = processes.begin(); it2 != processes.end(); ++it2) { if(it2->burst_time != 0 && it2->pid != it->pid) { it2->wait_time+=time_slice; } } // Remove the time slice from the current process it->burst_time-=time_slice; } } } return averageWaitTime(processes); } int main() { ifstream infile("processes.txt"); string a; int b; vector<process> processes; while(!infile.eof()) { infile >> a >> b; process addThis; addThis.pid = a; addThis.burst_time = b; processes.push_back(addThis); } int fcfs_avg_wait = fcfs(processes); int sjf_avg_wait = sjf(processes); int rr_avg_wait = rr(processes); cout << endl; cout << "Average wait time for FCFS: " << fcfs_avg_wait << " ms" << endl; cout << "Average wait time for SJF (non-preemptive): " << sjf_avg_wait << " ms" << endl; cout << "Average wait time for RR: " << rr_avg_wait << " ms" << endl << endl; if(fcfs_avg_wait < sjf_avg_wait && fcfs_avg_wait < rr_avg_wait) { cout << "Thus, the FCFS policy results the minimum average waiting time.\n\n"; } else if(sjf_avg_wait < fcfs_avg_wait && sjf_avg_wait < rr_avg_wait) { cout << "Thus, the SJF policy results the minimum average waiting time.\n\n"; } else { cout << "Thus, the RR policy results the minimum average waiting time.\n\n"; } return 0; }
true
cc8c91f76c6ee1a00772b0e55421edc3d4eec6ba
C++
Program0/CS_100_Software_Construction_rshell
/src/header/semicolon_connector.h
UTF-8
1,104
2.890625
3
[ "BSD-3-Clause" ]
permissive
//Marlo Zeroth mzero001@ucr.edu 861309346 //Emmilio Segovia esego001@ucr.edu 861305177 /* * Emmulates the behavior of the binary ; operator in the * Bourne Again Shell. * class. */ #ifndef SEMICOLON_CONNECTOR_H #define SEMICOLON_CONNECTOR_H #include "base.h" #include "connector_b.h" class Semicolon_Connector : public Connector_B { public: // Main constructor Semicolon_Connector(Base* left, Base *right); // Destructor virtual ~Semicolon_Connector(); // Prints the contents to the command line. void print(); // Returns its contents as a string std::string to_string(); // Returns its contents as a vector std::vector<std::string> to_vector(); /* * Overrides Base execute. Returns a value > 0 if the right * child command successfuly executed, returns -1 if an exit * command was executed, or returns 0 if the right child * executedsuccessfully. If return value is > 0 then value * is the pid number of the right child execute() function. */ int execute(); }; #endif
true
74769b6f79e69d6f5a745f2e0af516d618f6bdee
C++
jc6w/CompSci-Class-Projects
/9 Card Tile Project/ola4-Campos/CardBoardGame.h
UTF-8
676
2.890625
3
[]
no_license
#ifndef CARDBOARDGAME_H #define CARDBOARDGAME_H #include "Card.h" /********************************** cardBoardGame class stores the tiles, and solves for a solution for the puzzle ***********************************/ class cardBoardGame { private: Card cardTiles[9]; //to store cards bool solved; //for knowing when the whole board is solved public: //constructor cardBoardGame() {} //import data from stdin void importEntries(string); //solver functions void solveCards(Card[9], int, int); bool compareCards(int); //other functions void swapCards(Card[9],int, int); void rotateBoard(); void printCards(); }; #endif
true
553c20709a0c1ce8e9040165f2d435335a559e13
C++
andrewlai61616/face-ball
/track.cpp
UTF-8
5,557
2.5625
3
[]
no_license
#ifndef OPENCV_HPP #include <opencv2/opencv.hpp> using namespace cv; #define OPENCV_HPP #endif #include <wiringSerial.h> #include <wiringPi.h> #include "ball_detection.hpp" #include <iostream> using namespace std; #define RESIZE_WIDTH 320 #define RESIZE_HEIGHT 240 #define PREV_DIFF_RATIO 1.3 void stop_for_a_while(int usb); void command_arduino( CENTER_PERI ball , int usb ); void close_claw(int usb); void open_claw(int usb); void wiggle(int usb); void walk_straight_and_avoid(int usb); int prev_state = -1, prev_peri = -1, ball_in_range = 0, closed_claw = 0; int main(int argc, char** argv){ VideoCapture cap(0); if(!cap.isOpened()){ printf("Cannot open webcam 0! Trying 1...\n"); cap.open(1); } if(!cap.isOpened()){ printf("Cannot open webcam! Program shutting down QQ.\n"); return -1; } if( argc != 2 ){ printf("Usage: ./out <color>\n"); return -1; } // int usb; int usb = serialOpen("/dev/ttyACM0" , 115200); if(usb == -1){ printf("Error opening USB Serial! Program is shutting down...\n"); return -1; } printf("Finished initialize!\n"); Mat frame; RNG rng(12345); Scalar color; CENTER_PERI ball; cap.read(frame); open_claw(usb); while(cap.read(frame)){ resize( frame, frame, Size(RESIZE_WIDTH, RESIZE_HEIGHT) ); ball = get_center_and_peri(frame, argv[1], RESIZE_WIDTH, RESIZE_HEIGHT); if(ball.peri){ color = Scalar( rng.uniform(0, 255), rng.uniform(0, 255), 255 ); circle(frame, Point(ball.x, ball.y), int(ball.peri*0.5/PI), color, 2, 8); if(prev_peri == -1)prev_peri = ball.peri; } cout << "(x,y) = (" << ball.x << ", " << ball.y << ")\tPeri: " << ball.peri << ""; if(closed_claw){ printf("Finished task!!!\n"); walk_straight_and_avoid(usb); }else{ if(!ball_in_range){ if(prev_peri==-1 || (prev_peri > ball.peri/PREV_DIFF_RATIO && prev_peri < ball.peri*PREV_DIFF_RATIO)){ if(ball.peri)prev_peri = ball.peri; command_arduino( ball , usb ); printf("Believe!\n"); }else{ printf("Don't believe! prev %d now %d\n", prev_peri, ball.peri); stop_for_a_while(usb); if(prev_peri > 390){ ball_in_range = 1; continue; }else{ wiggle(usb); } } }else if(!closed_claw){ close_claw(usb); closed_claw = 1; } } imshow( "RGB", frame ); waitKey(1); } return 0; } void walk_straight_and_avoid(int usb){ serialPutchar(usb , '3'); prev_state = 3; while(!serialDataAvail(usb)); while(serialDataAvail(usb)){ printf("%c\n",serialGetchar(usb)); } delay(100); stop_for_a_while(usb); delay(50); } void wiggle(int usb){ serialPutchar(usb , '1'); prev_state = 1; while(!serialDataAvail(usb)); while(serialDataAvail(usb)){ printf("%c\n",serialGetchar(usb)); } delay(30); serialPutchar(usb , '3'); prev_state = 3; while(!serialDataAvail(usb)); while(serialDataAvail(usb)){ printf("%c\n",serialGetchar(usb)); } delay(30); serialPutchar(usb , '2'); prev_state = 2; while(!serialDataAvail(usb)); while(serialDataAvail(usb)){ printf("%c\n",serialGetchar(usb)); } delay(40); stop_for_a_while(usb); } void stop_for_a_while(int usb){ if(prev_state == 0)return; serialPutchar(usb , '0'); prev_state = 0; while(!serialDataAvail(usb)); while(serialDataAvail(usb)){ printf("%c\n",serialGetchar(usb)); } } void close_claw(int usb){ printf("I'm closing my claw!\n"); serialPutchar(usb, '3'); prev_state = 3; while(!serialDataAvail(usb)); while(serialDataAvail(usb)){ printf("%c\n",serialGetchar(usb)); } delay(2000); stop_for_a_while(usb); serialPutchar(usb, '5'); prev_state = 5; while(!serialDataAvail(usb)); while(serialDataAvail(usb)){ printf("%c\n",serialGetchar(usb)); } delay(2000); stop_for_a_while(usb); /*while(1){ serialPutchar(usb, '3'); prev_state = 3; while(!serialDataAvail(usb)); while(serialDataAvail(usb)){ printf("%c\n",serialGetchar(usb)); } delay(100); stop_for_a_while(usb); delay(50); }*/ } void open_claw(int usb){ printf("I'm opening my claw.\n"); serialPutchar(usb, '6'); prev_state = 6; while(!serialDataAvail(usb)); while(serialDataAvail(usb)){ printf("%c\n",serialGetchar(usb)); } delay(1000); stop_for_a_while(usb); } void command_arduino( CENTER_PERI ball , int usb ){ // TARGET: x = width/2 , y = height/2 , peri = 100 int target_peri = 420; if(!ball.peri){ printf("\tNothing!\n"); if(prev_state == 0)return; prev_state = 0; serialPutchar(usb, '0'); }else{ /* if(ball.peri > target_peri*1.2){ //move backwards printf("\tBACK\n"); if(prev_state == 4)return; prev_state = 4; serialPutchar(usb, '4'); }else if(ball.peri < target_peri*0.8){ // move forwards }else{*/ if( ball.x > RESIZE_WIDTH/2*1.1 ){ // move left printf("\tRIGHT\n"); if(prev_state == 2)return; prev_state = 2; serialPutchar(usb, '2'); delay(50); }else if(ball.x < RESIZE_WIDTH/2*0.9){ // move right printf("\tLEFT\n"); if(prev_state == 1)return; prev_state = 1; serialPutchar(usb, '1'); delay(50); }else{ if( ball.peri < target_peri ){ // move forwards printf("\tFRONT\n"); if(prev_state == 3)return; prev_state = 3; serialPutchar(usb, '3'); delay(150); }else{ ball_in_range = 1; printf("\tSTOP!!!\n"); if(prev_state == 0)return; prev_state = 0; serialPutchar(usb, '0'); delay(150); } } // } } while(!serialDataAvail(usb)); while(serialDataAvail(usb)){ printf("%c\n",serialGetchar(usb)); } stop_for_a_while(usb); }
true
a7d7bbbb3733a408c9c10c5e8bacde44d4b3c2bd
C++
cowtony/ACM
/LintCode/c++/0428. Pow(x, n).cpp
UTF-8
554
3.375
3
[]
no_license
class Solution { public: /** * @param x: the base number * @param n: the power number * @return: the result */ double myPow(double x, int n) { double result = 1; if (n < 0) { n = -n - 1; // prevent n = -2^31 x = 1 / x; result = x; } double base = x; while (n > 0) { if (n & 1 == 1) { result *= base; } base *= base; n >>= 1; } return result; } };
true
ffba4858b5cd248df788ae00f9f4054cd3fa3a0e
C++
aghman/gardenbase-arduino
/garden_sensors/garden_sensors.ino
UTF-8
2,715
2.59375
3
[]
no_license
/* Austin Hill * Garden Base Station * Purposes: * * Read temperature and humidity from AHT20 * * Read Light readings from BH1750 * * Use Sparkfun qwiic mux to read multiple soil moisture sensors * * detect multiple soil moisture sensors * * send data readings to InfluxDB over Wifi * * All of these components need to be allowed to fail. * The goal is to keep trying and fail gracefully. */ #include <Adafruit_AHTX0.h> #include <hp_BH1750.h> // include the library #include <SparkFun_I2C_Mux_Arduino_Library.h> //Click here to get the library: http://librarymanager/All#SparkFun_I2C_Mux #include <Wire.h> QWIICMUX myMux; hp_BH1750 lightSensor; // create the temp/humidity sensor bool lightAvailable; float currentLight; void setup() { initSerial(115200); lightAvailable = initBH1750_light_sensor(); Wire.begin(); if (myMux.begin() == false) { Serial.println("Mux not detected. Freezing..."); while (1) ; } Serial.println("Mux detected"); myMux.setPort(1); //Connect master to port labeled '1' on the mux byte currentPortNumber = myMux.getPort(); Serial.print("CurrentPort: "); Serial.println(currentPortNumber); Serial.println("Begin scanning for I2C devices"); } void loop() { Serial.println(); if (lightAvailable == true) { currentLight = getLightMeasurement(); Serial.printf("lux: %f\n", currentLight); } byte nDevices = 0; for (byte address = 1; address < 127; address++) { Wire.beginTransmission(address); byte error = Wire.endTransmission(); if (error == 0) { Serial.print("I2C device found at address 0x"); if (address < 0x10) Serial.print("0"); Serial.print(address, HEX); Serial.println(); nDevices++; } else if (error == 4) { Serial.print("Unknown error at address 0x"); if (address < 0x10) Serial.print("0"); Serial.println(address, HEX); } } if (nDevices == 0) Serial.println("No I2C devices found"); else Serial.println("Done"); byte currentPortNumber = myMux.getPort(); Serial.print("CurrentPort: "); Serial.println(currentPortNumber); delay(1000); } void initSerial(int baud){ Serial.begin(baud); Serial.println(); Serial.println("Garden Base Station Initialization..."); } bool initBH1750_light_sensor(){ bool avail = lightSensor.begin(BH1750_TO_GROUND); return avail; } // getLightMeasurement - non-blocking reading of light sensor data from a BH1750 sensor. // Returns a float value, units: lux. float getLightMeasurement(){ float lux; if (lightSensor.hasValue() == true){ lux = lightSensor.getLux(); lightSensor.start(); } return lux; }
true
2c5925703d1fd2aa9ba936109d204e9b7a65352f
C++
harshitagarwal2/CS122
/LAB/Trees/bintree.cpp
UTF-8
2,620
3.984375
4
[]
no_license
#include<iostream> #include<cstdlib> #include<ctype.h> using namespace std; #include "stack.h" class Bintree;//forward decln class Node{ friend class Bintree; friend class Queue; private: int data; Node *rchild; Node *lchild; public: Node(int x =0){ data = x; rchild=NULL;lchild=NULL;} }; class Queue { Node* arr[50]; int Front; int Rear; public: Queue(){Front=Rear=-1;} bool IsEmpty(){ return Front==Rear;} bool IsFull(){return Rear==49;} void Insert(Node* item){ if (IsFull()) {cout<<"Queue Overflow";return;} arr[++Rear]=item; } Node* Delete(){ if (IsEmpty()){ cout<<"Queue Underflow";return NULL;} return (arr[Front++]); } }; class Bintree{ Node *root; public: Bintree(){root = NULL;} Node* Create(int); void CreateBinTree(); void Inorder(Node *); void Preorder(Node *); void Postorder(Node *); void Traversal(); void Levelorder(); }; Node* Bintree::Create(int item){ int x; if (item!=-1) { Node *temp = new Node(item); cout<<"Enter the lchild of "<<item<<" "; cin>>x; temp->lchild = Create(x); cout<<"Enter the rchild of "<<item<<" "; cin>>x; temp->rchild = Create(x); return temp; } return NULL; } void Bintree::CreateBinTree(){ int item; cout<<"Creating the tree : "<<endl; cin>>item; root=Create(item); } void Bintree::Inorder(Node *root){ if (root!=NULL){ Inorder(root->lchild); cout<<root->data<<" "; Inorder(root->rchild); } } void Bintree::Preorder(Node *root){ if (root!=NULL){ cout<<root->data<<" "; Preorder(root->lchild); Preorder(root->rchild); } } void Bintree::Postorder(Node *root){ if (root!=NULL){ Postorder(root->lchild); Postorder(root->rchild); cout<<root->data<<" "; } } void Bintree::Levelorder(){ Queue q; if (root!=NULL) q.Insert(root); else {cout<<"Empty Tree"; return;} while(!q.IsEmpty()){ Node *temp= q.Delete(); cout<<temp->data<<" "; if (temp->lchild) q.Insert(temp->lchild); if (temp->rchild) q.Insert(temp->rchild); } } void Bintree::Traversal(){ cout<<"\nInorder Traversal : "; Inorder(root); cout<<"\npreorder Traversal : "; Preorder(root); cout<<"\nPostorder Traversal : "; Postorder(root); } int main(){ Bintree a; a.CreateBinTree(); a.Traversal(); cout<<"Level Order Traversal : "<<endl; a.Levelorder(); return 0; }
true
2bd6302a1c1b05e0a3248ed6c7c7d00db45c0954
C++
jacoblchapman/No-MASS
/FMU/Source/Contract_Negotiation.cpp
UTF-8
3,231
3.046875
3
[ "MIT" ]
permissive
// Copyright 2016 Jacob Chapman #include <vector> #include <utility> #include <limits> #include <iostream> #include "Contract_Negotiation.hpp" Contract_Negotiation::Contract_Negotiation() { difference = 0; } void Contract_Negotiation::calcDifference(const Contract & c) { difference += (0.0 - (c.requested - c.received)) + c.suppliedLeft; } void Contract_Negotiation::insertSupply(const ContractPtr &contract) { if (contract->suppliedLeft > 0) { nodeSupply.insert(contract, contract->suppliedCost); } } void Contract_Negotiation::insertPriority(const ContractPtr &contract) { if (contract->requested > 0) { nodePriority.insert(contract, contract->priority); } } void Contract_Negotiation::submit(const Contract & c) { calcDifference(c); ContractPtr contract = std::make_shared<Contract>(c); contracts[c.buildingID][c.id] = contract; insertSupply(contract); insertPriority(contract); } double Contract_Negotiation::getDifference() const { return difference; } void Contract_Negotiation::process() { ContractPtr cs = nodeSupply.popLeftEdge(); if (cs) { while (cs) { contractsSupplied.push_back(cs); cs = nodeSupply.popLeftEdge(); } processContracts(); } } /** * @brief Assign power to the contracts * @details going slow? have you cleared the contracts? */ void Contract_Negotiation::processContracts() { ContractPtr c = nodePriority.findRightEdge(); std::vector<ContractPtr>::iterator cs = contractsSupplied.begin(); while (c && cs != contractsSupplied.end()) { double fractionalPower = c->requested - c->received; while (fractionalPower > 0 && cs != contractsSupplied.end()) { if (sameContract((*cs), c)) { cs++; continue; } double supplied = (*cs)->suppliedLeft; double suppliedCost = (*cs)->suppliedCost; if (supplied - fractionalPower > 0) { supplied = fractionalPower; (*cs)->suppliedLeft -= supplied; } else { (*cs)->suppliedLeft = 0; cs++; } c->receivedCost += suppliedCost * supplied; c->received += supplied; fractionalPower = c->requested - c->received; } c = nodePriority.findRightEdge(); } } bool Contract_Negotiation::sameContract(const ContractPtr &c1, const ContractPtr &c2) const { return ((c1->buildingID == c2->buildingID) && (c1->id == c2->id)); } const Contract Contract_Negotiation::getContract( const int buildingID, const int id) const { return *contracts.at(buildingID).at(id).get(); } double Contract_Negotiation::getReceivedPowerForContract(const int buildingID, const int id) { return getContract(buildingID, id).received; } double Contract_Negotiation::getCostOfPowerForContract(const int buildingID, const int id) { return getContract(buildingID, id).receivedCost; } void Contract_Negotiation::clear() { contracts.clear(); nodeSupply.clear(); nodePriority.clear(); contractsSupplied.clear(); difference = 0; }
true
fe7490e487fb96faad51793495e7e67ba926b037
C++
foxox/foxtracer
/foxtracer/VanDerCorputSobolSampler2D.cpp
UTF-8
817
2.625
3
[]
no_license
#include "VanDerCorputSobolSampler2D.h" VanDerCorputSobolSampler2D::~VanDerCorputSobolSampler2D(void) { } Sample2D VanDerCorputSobolSampler2D::getNextSample() { Sample2D returnme; returnme.x = static_cast<float>(VanDerCorput(this->samplenum, 0)); //equivalent to... //returnme.x = static_cast<float>(VanDerCorput2(this->samplenum)); //equivalent to... //returnme.x = static_cast<float>(radicalInverse(this->samplenum, 2)); returnme.y = static_cast<float>(Sobol2(this->samplenum, 0)); //Scale 0->1 samples to sampleRangeX/Y returnme.x *= (this->sampleRangeX.high - this->sampleRangeX.low); returnme.y *= (this->sampleRangeY.high - this->sampleRangeY.low); returnme.x += this->sampleRangeX.low; returnme.y += this->sampleRangeY.low; //increment sample counter this->samplenum++; return returnme; }
true
66a2e35697e29e50f33d56310f130468a56952b2
C++
gawainx/buptac
/272.cpp
UTF-8
1,426
2.75
3
[]
no_license
//试玩简单图问题 //邻接矩阵的方式储存 //试玩二维矩阵. #include<cstdio> #include<cstring> #include<algorithm> #include<climits> using namespace std; int g[51][51]; int dist[55]; int main(){ int T; scanf("%d",&T); while(T--){ memset(dist,0,sizeof(dist)); int N,M;//N for nodes,M for edges scanf("%d%d",&N,&M); for(int i=1;i<=N;i++){ for(int j=1;j<=N;j++){ g[i][j] = N; } g[i][i] = 0; } int x,y; for(int i=0;i<M;i++){ scanf("%d%d",&x,&y); //无向图,要双向更新 g[x][y] = 1; g[y][x] = 1; } //floyd for(int k=1;k<N+1;k++){ for(int i=1;i<N+1;i++){ for(int j=1;j<N+1;j++){ if((g[i][k]==N)||(g[k][j]==N)) continue; if((g[i][j]==N)||(g[i][j]>g[i][k]+g[k][j])) g[i][j] = g[i][k]+g[k][j]; } } } for(int i=1;i<N+1;i++){ for(int j=1;j<N+1;j++){ dist[i]+=g[i][j]; } // printf("dist i%d:%d\n",i,dist[i]); } int min=INT_MAX,mindex=-1; for(int i=1;i<N+1;i++){ if(dist[i]<min){ min = dist[i]; mindex = i; } } printf("%d\n",mindex); } }
true
e8ef3c7c5412ef347ba88c034604aaa9d906fec5
C++
itrivacchiani/ING1_ProjetIFI
/TrinomialTree.cpp
UTF-8
5,352
2.578125
3
[]
no_license
// // TrinomialTree.cpp // C++ IFI // // Created by Itri-Raphaël Vacchiani on 21/05/2016. // Copyright © 2016 Itri-Raphaël Vacchiani. All rights reserved. // #include "TrinomialTree.hpp" using namespace std; void TrinomTree::setValeur(double _T, int _N, double _S0, double _K, double _sig, double _r){ T=_T; N=_N; S0=_S0; K=_K; sig=_sig; r=_r; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////// FONCTION MAX/MIN ///////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// double TrinomTree::max(double a, double b){ return a>=b?a:b; } double TrinomTree::min(double a, double b){ return a<=b?a:b; } double TrinomTree::callPayoff(double St, double K, TrinomTree & TT) { return TT.max((St-K),0); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////// CALCUL ACTIF SS-JACENT ////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// vector<vector<double>> TrinomTree::calculActifTri(int N, double S0, double u, double d){ vector<vector<double>> S(N+1,vector<double>(2*N)); for(int n=0;n<=N;n++) { for (int i=0;i<=2*n;i++) { S[n][i]=(S0*pow(u,(i/2))*pow(d,n-(i/2))); } } return S; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////// CALCUL VOLATILITE ////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// vector<vector<double>> TrinomTree::volatiliteSmile(int N, double S0, double u, double d, double sig0,double sig, TrinomTree & TT){ vector<vector<double>> volat_smile(N+1,vector<double>(2*N)); vector<vector<double>> Sn(N+1,vector<double>(2*N)); Sn = TT.calculActifTri(N, S0, u, d); for(int n=0;n<=N;n++) { for (int i=0;i<=2*n;i++) { volat_smile[n][i]= TT.min(sig,(sig0/sqrt(Sn[n][i]))); } } return volat_smile; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////// COEFFICIENTS OPT EURO ////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// double TrinomTree::up(double T, int N, double sig, double r,TrinomTree & TT) const { double delta_t=(T/N); double d = TT.down(T, N, sig, r); return (pow(1+r*delta_t,2))/d; } double TrinomTree::down(double T, int N, double sig, double r) const { double delta_t=(T/N); return 1+(r*delta_t)-(sig*sqrt(delta_t)); } vector<vector<double>> TrinomTree::prob_p(double T, int N, vector<vector<double>> sigma, double r, TrinomTree & TT, double u, double d) const { double delta_t=(T/N); vector<vector<double>> p(N+1,vector<double>(2*N)); for (int n=0;n<=N;n++) { for (int i=0;i<=2*n;i++) { p[n][i]=(pow(sigma[n][i],2)*delta_t)/((u-d)*(u-1-(r*delta_t))); } } return p; } vector<vector<double>> TrinomTree::prob_q(double T, int N, vector<vector<double>> sigma, double r, TrinomTree & TT, double u, double d) const { double delta_t=(T/N); vector<vector<double>> q(N+1,vector<double>(2*N)); for (int n=0;n<=N;n++) { for (int i=0;i<=2*n;i++) { q[n][i]=(pow(sigma[n][i],2)*delta_t)/((u-d)*(1+(r*delta_t)-d)); } } return q; } double TrinomTree::optCETri(double S0, double u, double d, double T, double r, vector<vector<double>> p, vector<vector<double>> q, double K, double N, TrinomTree & TT){ vector<vector<double>>CE(N+1,vector<double>(2*N)); vector<vector<double>>S(N+1,vector<double>(2*N)); S=TT.calculActifTri(N,S0,u,d); double delta_t=T/N; double R=exp(r*delta_t); for (int i=0;i<=2*N;i++) { CE[N][i]=TT.callPayoff(S[N][i],K,TT); } for (int n=N-1;n>=0;n--) { for (int i=0;i<=2*n;i++) { CE[n][i]=((p[n][i]*CE[n+1][i+2])+(q[n][i]*CE[n+1][i])+((1-p[n][i]-q[n][i])*CE[n+1][i+1]))/R; } } return CE[0][0]; } void TrinomTree::optEuropSVarTri(double M, double u, double d, double T, double r, vector<vector<double>> p,vector<vector<double>> q, double K, double N, TrinomTree & TT){ vector<double>CE_Svar(M+1); ofstream fichier1("/Users/itrivacchiani/Library/Mobile Documents/com~apple~CloudDocs/GM1/Projet Semestre 2/C++ IFI/C++/CallEurop_Svar_Trinomial.txt", ios::out); for (double i=0;i<=M;i++) { CE_Svar[i]=TT.optCETri(i, u, d, T, r, p, q, K, N, TT); fichier1 << CE_Svar[i] <<endl; } fichier1.close(); }
true
f8a2a0fe36bab9ee2d0697be0a49cc682b31a33f
C++
ZhengweiLi/_LeetCode
/18_4Sum.cpp
UTF-8
1,287
3.359375
3
[]
no_license
/*Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: The solution set must not contain duplicate quadruplets. Example: Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. A solution set is: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ]*/ class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { set<vector<int>> res; sort(nums.begin(),nums.end()); for(int i=0;i<nums.size()-3;i++){ for(int j=i+1;j<nums.size()-2;j++){ if(j>i+1&&nums[j]==nums[j-1]) continue; int left=j+1,right=nums.size()-1; while(left<right){ int sum=nums[i]+nums[j]+nums[left]+nums[right]; if(sum==target){ vector<int> out{nums[i],nums[j],nums[left],nums[right]}; res.insert(out); ++left,--right; } else if(sum<target) left++; else right--; } } } return vector<vector<int>>(res.begin(),res.end()); } };
true
1b0fc573ca4c7d1b3e1bdaf878f0640c0f7d8cf0
C++
joker-yt/c-
/XX_template/s_00_exercise/non-type_template_param.cpp
UTF-8
448
3.109375
3
[]
no_license
#include <iostream> #include <typeinfo> using namespace std; class MyClass { public: MyClass() = default; ~MyClass() = default; }; template <int i> void f() { cout << typeid(i).name() << endl; return; } int main(int argc, char const *argv[]) { f<0>(); int n; float f; MyClass cl; cout << typeid(n).name() << endl; cout << typeid(f).name() << endl; cout << typeid(cl).name() << endl; return 0; }
true
56ce7d29c2ffc2d5d98baec26e57eff26b01a9b3
C++
pankajkumar9797/Data-Structures-and-Algorithms
/Algorithms/week5_dynamic_programming1/4_longest_common_subsequence_of_two_sequences/lcs2.cpp
UTF-8
980
3.234375
3
[]
no_license
#include <iostream> #include <vector> using std::vector; int lcs2(vector<int> &a, vector<int> &b) { //write your code here if (a.empty() && b.empty()) return 0; int D[a.size() + 1][b.size() + 1]; D[0][0] = 0; for (unsigned int i = 0; i < a.size() + 1; ++i) { for (int j = 0; j < b.size() + 1; ++j) { D[i][j] = 0; } } for (unsigned int i = 1; i < a.size() + 1; ++i) { for (unsigned int j = 1; j < b.size() + 1; ++j) { if (a[i - 1] == b[j - 1]) D[i][j] = D[i - 1][j - 1] + 1; else D[i][j] = std::max(D[i - 1][j], D[i][j - 1]); } } // return std::min(std::min(a.size(), b.size()), c.size()); return D[a.size()][b.size()]; } int main() { size_t n; std::cin >> n; vector<int> a(n); for (size_t i = 0; i < n; i++) { std::cin >> a[i]; } size_t m; std::cin >> m; vector<int> b(m); for (size_t i = 0; i < m; i++) { std::cin >> b[i]; } std::cout << lcs2(a, b) << std::endl; }
true
11bfa194261060cbe911d7ec8e651d72a2fe41ca
C++
N4bi/Pinball
/ModulePhysics.cpp
UTF-8
15,682
2.53125
3
[]
no_license
#include "Globals.h" #include "Application.h" #include "ModuleInput.h" #include "ModuleRender.h" #include "ModulePhysics.h" #include "p2Point.h" #include "math.h" #ifdef _DEBUG #pragma comment( lib, "Box2D/libx86/Debug/Box2D.lib" ) #else #pragma comment( lib, "Box2D/libx86/Release/Box2D.lib" ) #endif ModulePhysics::ModulePhysics(Application* app, bool start_enabled) : Module(app, start_enabled) { world = NULL; mouse_joint = NULL; debug = false; time_step = 0.0f; velocity_iter = 0; position_iter = 0.0f; } PhysBody::PhysBody(b2Body* body) : body(body), listener(NULL) { } PhysBody::~PhysBody() { body->GetWorld()->DestroyBody(body); body = NULL; listener = NULL; } // Destructor ModulePhysics::~ModulePhysics() { } bool ModulePhysics::Start() { LOG("Creating Physics 2D environment"); world = new b2World(b2Vec2(GRAVITY_X, -GRAVITY_Y)); world->SetContactListener(this); // We need this to create the mouse joint and the prismatic joint b2BodyDef bd; ground = world->CreateBody(&bd); return true; } // update_status ModulePhysics::PreUpdate() { time_step = 1.0f / 60.0f; velocity_iter = 6; position_iter = 2; world->Step(time_step,velocity_iter, position_iter); for(b2Contact* c = world->GetContactList(); c; c = c->GetNext()) { if(c->GetFixtureA()->IsSensor() && c->IsTouching()) { PhysBody* pb1 = (PhysBody*)c->GetFixtureA()->GetBody()->GetUserData(); PhysBody* pb2 = (PhysBody*)c->GetFixtureA()->GetBody()->GetUserData(); if(pb1 && pb2 && pb1->listener) pb1->listener->OnCollision(pb1, pb2); } } return UPDATE_CONTINUE; } void ModulePhysics::DestroyBody(PhysBody* body) { bodies.del(bodies.findNode(body)); delete body; } PhysBody* ModulePhysics::CreateCircle(int x, int y, int radius, bool isSensor,bool ccd) { b2BodyDef body; body.type = b2_dynamicBody; body.position.Set(PIXEL_TO_METERS(x), PIXEL_TO_METERS(y)); body.bullet = ccd; b2Body* b = world->CreateBody(&body); b2CircleShape shape; shape.m_radius = PIXEL_TO_METERS(radius); b2FixtureDef fixture; fixture.shape = &shape; fixture.density = 1.0f; fixture.isSensor = isSensor; b->CreateFixture(&fixture); PhysBody* pbody = new PhysBody(); pbody->body = b; b->SetUserData(pbody); pbody->width = pbody->height = radius; bodies.add(pbody); return pbody; } PhysBody* ModulePhysics::CreateCircleStatic(int x, int y, int radius, float density, float restitution, bool ccd, bool isSensor) { b2BodyDef body; body.type = b2_staticBody; body.position.Set(PIXEL_TO_METERS(x), PIXEL_TO_METERS(y)); body.bullet = ccd; b2Body* b = world->CreateBody(&body); b2CircleShape shape; shape.m_radius = PIXEL_TO_METERS(radius); b2FixtureDef fixture; fixture.shape = &shape; fixture.density = density; fixture.restitution = restitution; fixture.isSensor = isSensor; b->CreateFixture(&fixture); PhysBody* pbody = new PhysBody(); pbody->body = b; b->SetUserData(pbody); pbody->width = pbody->height = radius; bodies.add(pbody); return pbody; } PhysBody* ModulePhysics::CreateRectangle(int x, int y, int width, int height) { b2BodyDef body; body.type = b2_dynamicBody; body.position.Set(PIXEL_TO_METERS(x), PIXEL_TO_METERS(y)); b2Body* b = world->CreateBody(&body); b2PolygonShape box; box.SetAsBox(PIXEL_TO_METERS(width) * 0.5f, PIXEL_TO_METERS(height) * 0.5f); b2FixtureDef fixture; fixture.shape = &box; fixture.density = 1.0f; b->CreateFixture(&fixture); PhysBody* pbody = new PhysBody(); pbody->body = b; b->SetUserData(pbody); pbody->width = width * 0.5f; pbody->height = height * 0.5f; bodies.add(pbody); return pbody; } PhysBody* ModulePhysics::CreateRectangleSensor(int x, int y, int width, int height) { b2BodyDef body; body.type = b2_staticBody; body.position.Set(PIXEL_TO_METERS(x), PIXEL_TO_METERS(y)); b2Body* b = world->CreateBody(&body); b2PolygonShape box; box.SetAsBox(PIXEL_TO_METERS(width) * 0.5f, PIXEL_TO_METERS(height) * 0.5f); b2FixtureDef fixture; fixture.shape = &box; fixture.density = 1.0f; fixture.isSensor = true; b->CreateFixture(&fixture); PhysBody* pbody = new PhysBody(); pbody->body = b; b->SetUserData(pbody); pbody->width = width; pbody->height = height; bodies.add(pbody); return pbody; } PhysBody* ModulePhysics::CreateChain(int x, int y, int* points, int size) { b2BodyDef body; body.type = b2_dynamicBody; body.position.Set(PIXEL_TO_METERS(x), PIXEL_TO_METERS(y)); b2Body* b = world->CreateBody(&body); b2ChainShape shape; b2Vec2* p = new b2Vec2[size / 2]; for(uint i = 0; i < size / 2; ++i) { p[i].x = PIXEL_TO_METERS(points[i * 2 + 0]); p[i].y = PIXEL_TO_METERS(points[i * 2 + 1]); } shape.CreateLoop(p, size / 2); b2FixtureDef fixture; fixture.shape = &shape; b->CreateFixture(&fixture); delete[] p; PhysBody* pbody = new PhysBody(); pbody->body = b; b->SetUserData(pbody); pbody->width = pbody->height = 0; bodies.add(pbody); return pbody; } PhysBody* ModulePhysics::CreateChainStatic(int x, int y, int* points, int size, float density, float restitution, bool isSensor) { b2BodyDef body; body.type = b2_staticBody; body.position.Set(PIXEL_TO_METERS(x), PIXEL_TO_METERS(y)); b2Body* b = world->CreateBody(&body); b2ChainShape shape; b2Vec2* p = new b2Vec2[size / 2]; for (uint i = 0; i < size / 2; ++i) { p[i].x = PIXEL_TO_METERS(points[i * 2 + 0]); p[i].y = PIXEL_TO_METERS(points[i * 2 + 1]); } shape.CreateLoop(p, size / 2); b2FixtureDef fixture; fixture.shape = &shape; fixture.density = density; fixture.restitution = restitution; fixture.isSensor = isSensor; b->CreateFixture(&fixture); delete[] p; PhysBody* pbody = new PhysBody(); pbody->body = b; b->SetUserData(pbody); pbody->width = pbody->height = 0; bodies.add(pbody); return pbody; } PhysBody* ModulePhysics::AddWall(int x, int y, int* points, int size, float restitution) { b2BodyDef body; body.type = b2_staticBody; b2Body* b = world->CreateBody(&body); b2ChainShape shape; b2Vec2* p = new b2Vec2[size / 2]; for (uint i = 0; i < size / 2; ++i) { p[i].x = PIXEL_TO_METERS(points[i * 2 + 0]); p[i].y = PIXEL_TO_METERS(points[i * 2 + 1]); } shape.CreateLoop(p, size / 2); b2FixtureDef fixture; fixture.shape = &shape; fixture.restitution = restitution; b->CreateFixture(&fixture); delete[] p; PhysBody* pbody = new PhysBody(); pbody->body = b; b->SetUserData(pbody); pbody->width = pbody->height = 0; bodies.add(pbody); return pbody; } PhysBody* ModulePhysics::CreateFlipper(int flipper_pos_x, int flipper_pos_y, int pivot_pos_x, int pivot_pos_y, int* points, uint size, int anchorA_x, int anchorA_y, int AnchorB_x, int AnchorB_y, float lower_angle, float upper_angle, float density, float restitution, bool ccd, bool isSensor, SDL_Texture* texture) { b2Vec2 circle_pos(pivot_pos_x, pivot_pos_y); b2Vec2 flipper_pos(flipper_pos_x, flipper_pos_y); float radius = 5; //Create the pivot b2BodyDef circle_def; circle_def.position.Set(PIXEL_TO_METERS(circle_pos.x), PIXEL_TO_METERS(circle_pos.y)); circle_def.type = b2_staticBody; b2Body* circle = world->CreateBody(&circle_def); b2CircleShape circle_shape; circle_shape.m_radius = PIXEL_TO_METERS(radius); b2FixtureDef circle_fixture; circle_fixture.shape = &circle_shape; circle->CreateFixture(&circle_fixture); //Create the flipper b2BodyDef flipper_def; flipper_def.position.Set(PIXEL_TO_METERS(flipper_pos.x), PIXEL_TO_METERS(flipper_pos.y)); flipper_def.type = b2_dynamicBody; b2Body* flipper = world->CreateBody(&flipper_def); b2PolygonShape flipper_shape; b2Vec2* p = new b2Vec2[size / 2]; for (uint i = 0; i < size / 2; ++i) { p[i].x = PIXEL_TO_METERS(points[i * 2 + 0]); p[i].y = PIXEL_TO_METERS(points[i * 2 + 1]); } flipper_shape.Set(p, size / 2); b2FixtureDef box_fixture; box_fixture.shape = &flipper_shape; box_fixture.density = density; box_fixture.restitution = restitution; box_fixture.isSensor = isSensor; flipper->CreateFixture(&box_fixture); delete[] p; PhysBody* ret = new PhysBody(); ret->body = flipper; flipper->SetUserData(ret); ret->texture = texture; //JOINT //joint between the flipper and the pivot b2RevoluteJointDef revolute_joint_def; revolute_joint_def.bodyA = flipper; revolute_joint_def.bodyB = circle; revolute_joint_def.collideConnected = false; revolute_joint_def.enableLimit = true; revolute_joint_def.lowerAngle = lower_angle * DEGTORAD; revolute_joint_def.upperAngle = upper_angle * DEGTORAD; revolute_joint_def.localAnchorA.Set(PIXEL_TO_METERS(anchorA_x), PIXEL_TO_METERS(anchorA_y)); revolute_joint_def.localAnchorB.Set(PIXEL_TO_METERS(AnchorB_x), PIXEL_TO_METERS(AnchorB_y)); (b2RevoluteJoint*)world->CreateJoint(&revolute_joint_def); bodies.add(ret); return ret; } PhysBody* ModulePhysics::AddSpring(int x_box, int y_box, SDL_Texture* texture,float restitution) { b2Vec2 box_pos(x_box,y_box); //Create the box body for the spring b2BodyDef body; body.position.Set(PIXEL_TO_METERS(box_pos.x), PIXEL_TO_METERS(box_pos.y)); body.type = b2_dynamicBody; b2Body* b = world->CreateBody(&body); b2PolygonShape shape; int width = 15, height = 25; shape.SetAsBox(PIXEL_TO_METERS(width)*0.5f, PIXEL_TO_METERS(height)*0.5f); b2FixtureDef fixture; fixture.shape = &shape; fixture.density = 1.0f; fixture.friction = 0.0f; fixture.restitution = restitution; b->CreateFixture(&fixture); PhysBody* ret = new PhysBody(); ret->body = b; b->SetUserData(ret); ret->texture = texture; ret->width = width * 0.5f; ret->height = height * 0.5f; //JOINT //Joint between the box body and the ground b2Vec2 vec(b->GetPosition()); b2PrismaticJointDef jointDef; b2Vec2 worldAxis(0.0f, -1.0f); jointDef.Initialize(ground, b, vec, worldAxis); jointDef.lowerTranslation = -1.5f; jointDef.upperTranslation = 1.5f; jointDef.enableLimit = true; jointDef.maxMotorForce = 35.0f; jointDef.motorSpeed = 35.0f; jointDef.enableMotor = true; (b2PrismaticJoint*)world->CreateJoint(&jointDef); bodies.add(ret); return ret; } // update_status ModulePhysics::PostUpdate() { if(App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN) debug = !debug; if(!debug) return UPDATE_CONTINUE; b2Vec2 mouse_position(0, 0); click_body = NULL; for(b2Body* b = world->GetBodyList(); b; b = b->GetNext()) { for(b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) { switch(f->GetType()) { // Draw circles ------------------------------------------------ case b2Shape::e_circle: { b2CircleShape* shape = (b2CircleShape*)f->GetShape(); b2Vec2 pos = f->GetBody()->GetPosition(); App->renderer->DrawCircle(METERS_TO_PIXELS(pos.x), METERS_TO_PIXELS(pos.y), METERS_TO_PIXELS(shape->m_radius), 255, 255, 255); } break; // Draw polygons ------------------------------------------------ case b2Shape::e_polygon: { b2PolygonShape* polygonShape = (b2PolygonShape*)f->GetShape(); int32 count = polygonShape->GetVertexCount(); b2Vec2 prev, v; for(int32 i = 0; i < count; ++i) { v = b->GetWorldPoint(polygonShape->GetVertex(i)); if(i > 0) App->renderer->DrawLine(METERS_TO_PIXELS(prev.x), METERS_TO_PIXELS(prev.y), METERS_TO_PIXELS(v.x), METERS_TO_PIXELS(v.y), 255, 100, 100); prev = v; } v = b->GetWorldPoint(polygonShape->GetVertex(0)); App->renderer->DrawLine(METERS_TO_PIXELS(prev.x), METERS_TO_PIXELS(prev.y), METERS_TO_PIXELS(v.x), METERS_TO_PIXELS(v.y), 255, 100, 100); } break; // Draw chains contour ------------------------------------------- case b2Shape::e_chain: { b2ChainShape* shape = (b2ChainShape*)f->GetShape(); b2Vec2 prev, v; for(int32 i = 0; i < shape->m_count; ++i) { v = b->GetWorldPoint(shape->m_vertices[i]); if(i > 0) App->renderer->DrawLine(METERS_TO_PIXELS(prev.x), METERS_TO_PIXELS(prev.y), METERS_TO_PIXELS(v.x), METERS_TO_PIXELS(v.y), 100, 255, 100); prev = v; } v = b->GetWorldPoint(shape->m_vertices[0]); App->renderer->DrawLine(METERS_TO_PIXELS(prev.x), METERS_TO_PIXELS(prev.y), METERS_TO_PIXELS(v.x), METERS_TO_PIXELS(v.y), 100, 255, 100); } break; // Draw a single segment(edge) ---------------------------------- case b2Shape::e_edge: { b2EdgeShape* shape = (b2EdgeShape*)f->GetShape(); b2Vec2 v1, v2; v1 = b->GetWorldPoint(shape->m_vertex0); v1 = b->GetWorldPoint(shape->m_vertex1); App->renderer->DrawLine(METERS_TO_PIXELS(v1.x), METERS_TO_PIXELS(v1.y), METERS_TO_PIXELS(v2.x), METERS_TO_PIXELS(v2.y), 100, 100, 255); } break; } // MOUSE JOINT if (App->input->GetMouseButton(SDL_BUTTON_LEFT) == KEY_DOWN) { mouse_position.x = PIXEL_TO_METERS(App->input->GetMouseX()); mouse_position.y = PIXEL_TO_METERS(App->input->GetMouseY()); if (f->GetShape()->TestPoint(b->GetTransform(), mouse_position) == true) { click_body = f->GetBody(); LOG("body_clicked\n"); } } } } // creation of the joint if (click_body != NULL) { b2MouseJointDef def; def.bodyA = ground; def.bodyB = click_body; def.target = mouse_position; def.dampingRatio = 0.5f; def.frequencyHz = 20.0f; def.maxForce = 100.0f * click_body->GetMass(); mouse_joint = (b2MouseJoint*)world->CreateJoint(&def); } if (mouse_joint != NULL && App->input->GetMouseButton(SDL_BUTTON_LEFT) == KEY_REPEAT) { b2Vec2 posA, posB; posA = mouse_joint->GetAnchorA(); posB.x = PIXEL_TO_METERS(App->input->GetMouseX()); posB.y = PIXEL_TO_METERS(App->input->GetMouseY()); mouse_joint->SetTarget(posB); } if (mouse_joint != NULL && App->input->GetMouseButton(SDL_BUTTON_LEFT) == KEY_UP) { world->DestroyJoint(mouse_joint); mouse_joint = NULL; } return UPDATE_CONTINUE; } void ModulePhysics::PreSolve(b2Contact* contact, const b2Manifold* oldManifold) { PhysBody* physA = (PhysBody*)contact->GetFixtureA()->GetBody()->GetUserData(); PhysBody* physB = (PhysBody*)contact->GetFixtureB()->GetBody()->GetUserData(); if(physA && physA->listener != NULL) physA->listener->OnCollision(physA, physB); if(physB && physB->listener != NULL) physB->listener->OnCollision(physB, physA); } //PhysBody Utilities void PhysBody::GetPosition(int& x, int &y) const { b2Vec2 pos = body->GetPosition(); x = METERS_TO_PIXELS(pos.x) - (width); y = METERS_TO_PIXELS(pos.y) - (height); } float PhysBody::GetRotation() const { return RADTODEG * body->GetAngle(); } bool PhysBody::Contains(int x, int y) const { b2Vec2 p(PIXEL_TO_METERS(x), PIXEL_TO_METERS(y)); const b2Fixture* fixture = body->GetFixtureList(); while (fixture != NULL) { if (fixture->GetShape()->TestPoint(body->GetTransform(), p) == true) return true; fixture = fixture->GetNext(); } return false; } void PhysBody::Turn(int degrees) { body->ApplyAngularImpulse(DEGTORAD * degrees, true); } void PhysBody::Push(float x, float y) { body->ApplyForceToCenter(b2Vec2(x, y), true); } double PhysBody::GetAngle()const { return RADTODEG * body->GetAngle(); } void PhysBody::SetPosition(int x, int y) { body->SetTransform(b2Vec2(PIXEL_TO_METERS(x), PIXEL_TO_METERS(y)), 0.0f); } void PhysBody::SetAngularVelocity(float velocity) { body->SetAngularVelocity(velocity * DEGTORAD); } void PhysBody::SetLinearVelocity(int x, int y) { body->SetLinearVelocity(b2Vec2(PIXEL_TO_METERS(x), PIXEL_TO_METERS(y))); } // Called before quitting bool ModulePhysics::CleanUp() { LOG("Destroying physics world"); p2List_item<PhysBody*>* item = bodies.getFirst(); while (item != NULL) { delete item->data; item = item->next; } bodies.clear(); // Delete the whole physics world! delete world; return true; }
true
0aff30997f19bea1d999510ae4867e53cabb147a
C++
VladimirVasilijevic/Sudoku-Solver
/sudoku/ml_util/ReadMnist.cpp
UTF-8
3,405
2.875
3
[]
no_license
#include "ReadMnist.h" #include <fstream> #include <cmath> using namespace cv; using namespace std; ReadMnist::~ReadMnist() {} ReadMnist::ReadMnist(std::string filenameimages, std::string filenamelabels) : m_filenameimages(filenameimages) , m_filenamelabels(filenamelabels) {} vector<cv::Mat> ReadMnist::read_Mnist_images(std::vector<cv::Mat>& imagesData) { /*std::vector<cv::Mat> imagesData;*/ read_Mnist_Images(imagesData); return imagesData; } vector<cv::Mat> ReadMnist::read_Mnist_labels() { std::vector<cv::Mat> labelsData; read_Mnist_Label(labelsData); return labelsData; } Mat ReadMnist::read_Mnist_images() { std::vector<cv::Mat> imagesData; read_Mnist_Images(imagesData); return concatenateMat(imagesData, 255.0); } //Mat ReadMnist::read_Mnist_labels() //{ // std::vector<cv::Mat> labelsData; // read_Mnist_Label(labelsData); // return concatenateMat(labelsData, 1.0); //} void ReadMnist::read_Mnist_Images(vector<cv::Mat> &vec){ ifstream file(m_filenameimages, ios::binary); if (file.is_open()) { int magic_number = 0; int number_of_images = 0; int n_rows = 0; int n_cols = 0; file.read((char*)&magic_number, sizeof(magic_number)); magic_number = ReverseInt(magic_number); file.read((char*)&number_of_images, sizeof(number_of_images)); number_of_images = ReverseInt(number_of_images); file.read((char*)&n_rows, sizeof(n_rows)); n_rows = ReverseInt(n_rows); file.read((char*)&n_cols, sizeof(n_cols)); n_cols = ReverseInt(n_cols); for (int i = 0; i < number_of_images; ++i) { cv::Mat tp = Mat::zeros(n_rows, n_cols, CV_8UC1); for (int r = 0; r < n_rows; ++r) { for (int c = 0; c < n_cols; ++c) { unsigned char temp = 0; file.read((char*)&temp, sizeof(temp)); tp.at<uchar>(r, c) = (int)temp; } } vec.push_back(tp); } } } void ReadMnist::read_Mnist_Label(vector<cv::Mat> &mat) { ifstream file(m_filenamelabels, ios::binary); if (file.is_open()){ int magic_number = 0; int number_of_images = 0; int n_rows = 1; int n_cols = 10; file.read((char*)&magic_number, sizeof(magic_number)); magic_number = ReverseInt(magic_number); file.read((char*)&number_of_images, sizeof(number_of_images)); number_of_images = ReverseInt(number_of_images); for (int i = 0; i < number_of_images; ++i) { cv::Mat tp = Mat::zeros(n_rows, n_cols, CV_8UC1); unsigned char temp = 0; file.read((char*)&temp, sizeof(temp)); tp.at<uchar>(0, (int)temp) = 1; mat.push_back(tp); } } } Mat ReadMnist::concatenateMat(vector<Mat> &vec, double scal){ // isto za sve slike int height = vec[0].rows; int width = vec[0].cols; Mat res = Mat::zeros(height * width, static_cast<int>(vec.size()), CV_32FC1); for (int i = 0; i < vec.size(); i++){ Mat img(height, width, CV_32FC1); vec[i].convertTo(img, CV_32FC1); // reshape(int cn, int rows=0), cn is num of channels. Mat ptmat = img.reshape(0, height * width); Rect roi = cv::Rect(i, 0, ptmat.cols, ptmat.rows); Mat subView = res(roi);//ucitava matricu dimenzija roi-a ptmat.copyTo(subView);//menja se i res posto se subView pravi samo novi header za iste podatke } divide(res, scal, res); return res.t(); } int ReadMnist::ReverseInt(int i) { unsigned char ch1, ch2, ch3, ch4; ch1 = i & 255; ch2 = (i >> 8) & 255; ch3 = (i >> 16) & 255; ch4 = (i >> 24) & 255; return((int)ch1 << 24) + ((int)ch2 << 16) + ((int)ch3 << 8) + ch4; }
true
87e4c625ca4ac33f14a3fe2d878ac0afc4d5fbbd
C++
Hongyunpyo/L_study
/study/study/eight.cpp
UHC
2,926
3.640625
4
[]
no_license
#include "header.h" class Circle { int radius; public : Circle(int radius = 0) { this->radius = radius; } int getRadius() { return radius; } void setRadius(int radius) { this->radius = radius; } double getArea() { return 3.14*radius*radius; } }; class NamedCircle : public Circle { string name; public: NamedCircle(int radius, string name); void show(); }; NamedCircle::NamedCircle(int radius, string name) : Circle(radius) { this->name = name; } void NamedCircle::show() { cout << " " << getRadius() << " " << name << endl; } void eight_1_m() { NamedCircle waffle(3, "waffle"); waffle.show(); } class Point { int x, y; public: Point(int x, int y) { this->x = x; this->y = y; } int getX() { return x; } int getY() { return y; } protected: void move(int x, int y) { this->x = x; this->y = y; } }; class ColorPoint : public Point { string color; public : ColorPoint(int x, int y, string color); void setPoint(int x, int y); void setColor(string color); void show(); }; ColorPoint::ColorPoint(int x, int y, string color) : Point(x, y) { this->color = color; } void ColorPoint::setPoint(int x, int y) { move(x, y); } void ColorPoint::setColor(string color) { this->color = color; } void ColorPoint::show() { cout << color << " (" << getX() << " ," << getY() << ") ġ Դϴ." << endl; } void eight_2_m() { ColorPoint cp(5, 5, "RED"); cp.setPoint(10, 20); cp.setColor("BLUE"); cp.show(); } class BaseArray { private: int capacity; // Ҵ ޸ 뷮 int *mem; protected: BaseArray(int capacity = 100) { this->capacity = capacity; mem = new int[capacity]; } ~BaseArray() { delete[] mem; } void put(int index, int val) { mem[index] = val; } int get(int index) { return mem[index]; } int getCapacity() { return capacity; } }; class MyQueue :public BaseArray { int head, tail; int size; public : MyQueue(int num) :BaseArray(num) { head = 0, tail = -1, size = 0; }; int capacity(); int length(); void enqueue(int n); int dequeue(); }; int MyQueue::capacity() { return getCapacity(); }; int MyQueue::length() { return size; } void MyQueue::enqueue(int n) { if (size == capacity()) return; put(head, n); head++; head = head % capacity(); size++; } int MyQueue::dequeue() { if (size == 0) return -1; size--; tail++; tail = tail % capacity(); return get(tail); } void eight_3_m() { MyQueue mQ(100); int n; cout << "ť 5 Է϶>> "; for (int i = 0; i<5; i++) { cin >> n; mQ.enqueue(n); // ť } cout << "ť 뷮:" << mQ.capacity() << ", ť ũ:" << mQ.length() << endl; cout << "ť Ҹ Ͽ Ѵ>> "; while (mQ.length() != 0) { cout << mQ.dequeue() << ' '; // ť Ͽ } cout << endl << "ť ũ : " << mQ.length() << endl; } void test() { }
true
318753b4411de3b5264a6ee3df1ea72e971fe5a6
C++
Meng-Gen/USACOTraining
/numtri/main.cc
UTF-8
599
2.953125
3
[]
no_license
/* ID: plover1 TASK: numtri LANG: C++ */ #include <iostream> #include <fstream> using namespace std; int main() { ofstream fout("numtri.out"); ifstream fin("numtri.in"); int R; fin >> R; int triangles[1000][1000] = {0}; for (int i = 0; i < R; i++) { for (int j = 0; j <= i; j++) { fin >> triangles[i][j]; } } for (int i = R - 2; i >= 0; i--) { for (int j = 0; j <= i; j++) { triangles[i][j] += max(triangles[i + 1][j], triangles[i + 1][j + 1]); } } fout << triangles[0][0] << '\n'; return 0; }
true
11415d358a951b3dd45436becb6e2ead18f64e9c
C++
cpv-project/cpv-cql-driver
/include/CQLDriver/Common/Utility/MathUtils.hpp
UTF-8
304
3.09375
3
[ "MIT" ]
permissive
#pragma once #include <cstdint> namespace cql { /** The fast integer pow function */ template <class T> T powInteger(T base, std::size_t exponent) { T result(1); while (exponent > 0) { if (exponent & 1) { result *= base; } base *= base; exponent >>= 1; } return result; } }
true
f63e1c070e45a86adf3c1e2ff8a8ded8df9f185e
C++
loganpadon/Observer-Implementation
/Homework6/src/Homework6.cpp
UTF-8
1,202
3.203125
3
[]
no_license
//============================================================================ // Name : Homework6.cpp // Author : Logan Padon // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include "Subject.h" #include "BankObserver.h" #include "CreditObserver.h" #include "SchoolObserver.h" #include <iostream> #include <string> using namespace std; int main() { Subject subject; //Creates the subject BankObserver bankObserver; CreditObserver creditObserver; SchoolObserver schoolObserver; //Creates observers string FIRST_ADDRESS = "123 First Address Street"; //Should appear first, three times string SECOND_ADDRESS = "456 Second Address Street"; //Should appear second, twice subject.addObserver(bankObserver); subject.addObserver(creditObserver); subject.addObserver(schoolObserver); //Adds 3 observers to the subject subject.setAddress(FIRST_ADDRESS); //Changes address, notifies observers subject.removeObserver(schoolObserver); //Removes the last observer subject.setAddress(SECOND_ADDRESS); //Changes address, notifies observers return 0; }
true
7b531dc535f7382df68445902bfb71d81402f271
C++
SwagSoftware/Kisak-Strike
/vscript/languages/squirrel/testSqPlus2/testSqPlus2.cpp
UTF-8
47,869
2.5625
3
[ "Zlib", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// testSqPlus2.cpp // Created by John Schultz 9/21/2005 // Free for any use. // Step through the code with a debugger (setting breakpoints in functions) // to get an idea how everything works. #include <stdarg.h> #include <stdio.h> #if 0 #include <string> //#define SQPLUS_SUPPORT_STD_STRING #define SQPLUS_SUPPORT_SQ_STD_STRING #endif //#define SQPLUS_CONST_OPT #include "sqplus.h" using namespace SqPlus; void scprintfunc(HSQUIRRELVM v,const SQChar *s,...) { static SQChar temp[2048]; va_list vl; va_start(vl,s); scvsprintf( temp,s,vl); SCPUTS(temp); va_end(vl); } void newtest(void) { scprintf(_T("NewTest\n")); } SQChar * newtestR1(const SQChar * inString) { scprintf(_T("NewTestR1: %s\n"),inString); return _T("Returned String"); } struct Vector3 { static float staticVar; float x,y,z; Vector3() { x = 1.f; y = 2.f; z = 3.f; } Vector3(float _x,float _y,float _z) : x(_x), y(_y), z(_z) {} ~Vector3() { scprintf(_T("~Vector()\n")); } Vector3 Inc(Vector3 & v) { x += v.x; y += v.y; z += v.z; return *this; } // Inc Vector3 operator+(Vector3 & v) { return Vector3(x+v.x,y+v.y,z+v.z); } }; float Vector3::staticVar = 898.434f; #if 0 // It may be possible to make this method work in the future. If so, the DECLARE_INSTANCE_FUNCS() macro // would not be needed. The issue is duplicate compiler matching for const SQChar * and Push(): // Push(const SQChar * &) and Push(const SQChar *) both match. // The typeid() compiler function may not be portable to other compilers. #include <typeinfo.h> template<typename TYPE> inline const SQChar * GetTypeName(const TYPE & n) { return typeid(TYPE).name(); } template<typename TYPE> inline void Push(HSQUIRRELVM v,const TYPE & value) { CreateCopyInstance(GetTypeName(value),value); } template<typename TYPE> inline bool Match(TypeWrapper<TYPE &>,HSQUIRRELVM v,int idx) { return GetInstance<TYPE>(v,idx) != NULL; } template<typename TYPE> inline TYPE & Get(TypeWrapper<TYPE &>,HSQUIRRELVM v,int idx) { return *GetInstance<TYPE>(v,idx); } #endif DECLARE_INSTANCE_TYPE(Vector3) Vector3 Add2(Vector3 & a,Vector3 & b) { Vector3 c; c.x = a.x + b.x; c.y = a.y + b.y; c.z = a.z + b.z; return c; } // Add2 int Add(HSQUIRRELVM v) { // StackHandler sa(v); Vector3 * self = GetInstance<Vector3,true>(v,1); Vector3 * arg = GetInstance<Vector3,true>(v,2); // SquirrelObject so = sa.GetObjectHandle(1); #if 0 SQUserPointer type=0; so.GetTypeTag(&type); SQUserPointer reqType = ClassType<Vector3>::type(); if (type != reqType) { throw SquirrelError(_T("Invalid class type")); } // if #endif // Vector3 * self = (Vector3 *)so.GetInstanceUP(ClassType<Vector3>::type()); // if (!self) throw SquirrelError(_T("Invalid class type")); Vector3 tv; tv.x = arg->x + self->x; tv.y = arg->y + self->y; tv.z = arg->z + self->z; return ReturnCopy(v,tv); } struct NewTestObj { ScriptStringVar64 s1; ScriptStringVar32 s2; bool b; int val; int c1; ScriptStringVar8 c2; // 8 char plus null (max string is 8 printable chars). NewTestObj() : val(777) { s1 = _T("s1=s1"); s2 = _T("s2=s2"); c1 = 996; c2 = _T("It's a 997"); // Prints: "It's a 9", as only 8 chars in static buffer (plus null). } NewTestObj(const SQChar * _s1,int _val,bool _b) { s1 = _s1; val = _val; b = _b; s2 = _T("s2=s2"); c1 = 993; c2 = _T("It's a 998"); // Prints: "It's a 9", as only 8 chars in static buffer (plus null). } static int construct(HSQUIRRELVM v) { // StackHandler sa(v); // SquirrelObject so = sa.GetObjectHandle(1); return PostConstruct<NewTestObj>(v,new NewTestObj(),release); } // construct SQ_DECLARE_RELEASE(NewTestObj) // Required when using a custom constructor. void newtest(void) { scprintf(_T("NewTest: %d\n"),val); } SQChar * newtestR1(const SQChar * inString) { scprintf(_T("NewTestR1: Member var val is %d, function arg is %s\n"),val,inString); return _T("Returned String"); } int multiArgs(HSQUIRRELVM v) { StackHandler sa(v); SquirrelObject so = sa.GetObjectHandle(1); int paramCount = sa.GetParamCount(); int p1 = sa.GetInt(2); int p2 = sa.GetInt(3); int p3 = sa.GetInt(4); return 0; } // multiArgs int _set(HSQUIRRELVM v) { StackHandler sa(v); int paramCount = sa.GetParamCount(); const SQChar * el = sa.GetString(2); val = sa.GetInt(3); return sa.Return(val); } int _get(HSQUIRRELVM v) { StackHandler sa(v); int paramCount = sa.GetParamCount(); return sa.Return(val); } }; // Using global functions to construct and release classes. int releaseNewTestObj(SQUserPointer up,SQInteger size) { SQ_DELETE_CLASS(NewTestObj); } // releaseNewTestObj int constructNewTestObj(HSQUIRRELVM v) { StackHandler sa(v); int paramCount = sa.GetParamCount(); if (paramCount == 1) { return PostConstruct<NewTestObj>(v,new NewTestObj(),releaseNewTestObj); } else if (paramCount == 4) { return PostConstruct<NewTestObj>(v,new NewTestObj(sa.GetString(2),sa.GetInt(3),sa.GetBool(4)?true:false),releaseNewTestObj); } // if return sq_throwerror(v,_T("Invalid Constructor arguments")); } // constructNewTestObj // Using fixed args with auto-marshaling. Note that the HSQUIRRELVM must be last in the argument list (and must be present to send to PostConstruct). // SquirrelVM::GetVMPtr() could also be used with PostConstruct(): no HSQUIRRELVM argument would be required. int constructNewTestObjFixedArgs(const SQChar * s,int val,bool b,HSQUIRRELVM v) { StackHandler sa(v); int paramCount = sa.GetParamCount(); return PostConstruct<NewTestObj>(v,new NewTestObj(s,val,b),releaseNewTestObj); } // constructNewTestObj // Will be registered in a class namespace. void globalFunc(const SQChar * s,int val) { scprintf(_T("globalFunc: s: %s val: %d\n"),s,val); } // globalFunc class GlobalClass { public: void func(const SQChar * s,int val) { scprintf(_T("globalClassFunc: s: %s val: %d\n"),s,val); } // func } globalClass; struct CustomTestObj { ScriptStringVar128 name; int val; bool state; CustomTestObj() : val(0), state(false) { name = _T("empty"); } CustomTestObj(const SQChar * _name,int _val,bool _state) : val(_val), state(_state) { name = _name; } // Custom variable argument constructor static int construct(HSQUIRRELVM v) { StackHandler sa(v); int paramCount = sa.GetParamCount(); if (paramCount == 1) { return PostConstruct<CustomTestObj>(v,new CustomTestObj(),release); } if (paramCount == 4) { return PostConstruct<CustomTestObj>(v,new CustomTestObj(sa.GetString(2),sa.GetInt(3),sa.GetBool(4)?true:false),release); } // if return sq_throwerror(v,_T("Invalid Constructor arguments")); } // construct SQ_DECLARE_RELEASE(CustomTestObj) // Required when using a custom constructor. // Member function that handles variable types. int varArgTypes(HSQUIRRELVM v) { StackHandler sa(v); int paramCount = sa.GetParamCount(); if (sa.GetType(2) == OT_INTEGER) { val = sa.GetInt(2); } // if if (sa.GetType(2) == OT_STRING) { name = sa.GetString(2); } // if if (sa.GetType(3) == OT_INTEGER) { val = sa.GetInt(3); } // if if (sa.GetType(3) == OT_STRING) { name = sa.GetString(3); } // if // return sa.ThrowError(_T("varArgTypes() error")); return 0; } // varArgTypes // Member function that handles variable types and has variable return types+count. int varArgTypesAndCount(HSQUIRRELVM v) { StackHandler sa(v); int paramCount = sa.GetParamCount(); SQObjectType type1 = (SQObjectType)sa.GetType(1); // Always OT_INSTANCE SQObjectType type2 = (SQObjectType)sa.GetType(2); SQObjectType type3 = (SQObjectType)sa.GetType(3); SQObjectType type4 = (SQObjectType)sa.GetType(4); int returnCount = 0; if (paramCount == 3) { sq_pushinteger(v,val); returnCount = 1; } else if (paramCount == 4) { sq_pushinteger(v,val); sq_pushstring(v,name,-1); returnCount = 2; } // if return returnCount; } // int noArgsVariableReturn(HSQUIRRELVM v) { if (val == 123) { val++; return 0; // This will print (null). } else if (val == 124) { sq_pushinteger(v,val); // Will return int:124. val++; return 1; } else if (val == 125) { sq_pushinteger(v,val); name = _T("Case 125"); sq_pushstring(v,name,-1); val = 123; // reset return 2; } // if return 0; } // noArgsVariableReturn // Registered with func() instead of funcVarArgs(): fixed (single) return type. const SQChar * variableArgsFixedReturnType(HSQUIRRELVM v) { StackHandler sa(v); int paramCount = sa.GetParamCount(); SQObjectType type1 = (SQObjectType)sa.GetType(1); // Always OT_INSTANCE SQObjectType type2 = (SQObjectType)sa.GetType(2); SQObjectType type3 = (SQObjectType)sa.GetType(3); if (paramCount == 1) { return _T("No Args"); } else if (paramCount == 2) { return _T("One Arg"); } else if (paramCount == 3) { return _T("Two Args"); } // if return _T("More than two args"); } // variableArgsFixedReturnType void manyArgs(int i,float f,bool b,const SQChar * s) { scprintf(_T("i: %d, f: %f, b: %s, s: %s\n"),i,f,b?_T("true"):_T("false"),s); } // manyArgs float manyArgsR1(int i,float f,bool b,const SQChar * s) { manyArgs(i,f,b,s); return i+f; } // manyArgsR1 }; // === Standard (non member) function === int testFunc(HSQUIRRELVM v) { StackHandler sa(v); int paramCount = sa.GetParamCount(); scprintf(_T("testFunc: numParams[%d]\n"),paramCount); for (int i=1; i <= paramCount; i++) { scprintf(_T("param[%d]: "),i); switch(sa.GetType(i)) { case OT_TABLE: scprintf(_T("OT_TABLE[0x%x]\n"),sa.GetObjectHandle(i)); break; case OT_INTEGER: scprintf(_T("OT_INTEGER[%d]\n"),sa.GetInt(i)); break; case OT_FLOAT: scprintf(_T("OT_FLOAT[%f]\n"),sa.GetFloat(i)); break; case OT_STRING: scprintf(_T("OT_STRING[%s]\n"),sa.GetString(i)); break; default: scprintf(_T("TYPEID[%d]\n"),sa.GetType(i)); } // switch } // for return SQ_OK; } // testFunc int globalVar = 5551234; class Creature { int health; public: enum {MaxHealth=100}; Creature() : health(MaxHealth) {} int GetMaxHealth(void) { return MaxHealth; } int GetHealth(void) { return health; } void SetHealth(int newHealth) { health = newHealth; } }; DECLARE_INSTANCE_TYPE(Creature) // === BEGIN Class Instance Test === class PlayerManager { public: struct Player { ScriptStringVar64 name; void printName(void) { scprintf(_T("Player.name = %s\n"),name.s); } }; Player playerVar; // Will be accessed directly. Player players[2]; Player * GetPlayer(int player) { // Must return pointer: a returned reference will behave the same as return by value. return &players[player]; } PlayerManager() { players[0].name = _T("Player1"); players[1].name = _T("Player2"); playerVar.name = _T("PlayerVar"); } } playerManager; DECLARE_INSTANCE_TYPE(PlayerManager) DECLARE_INSTANCE_TYPE(PlayerManager::Player) PlayerManager * getPlayerManager(void) { // Must return pointer: a returned reference will behave the same as return by value. return &playerManager; } // Example from forum post question: class STestScripts {}; // Proxy class class TestScripts { public: int Var_ToBind1,Var_ToBind2; void InitScript1(void) { Var_ToBind1 = 808; RegisterGlobal(*this,&TestScripts::Test1,_T("Test1")); RegisterGlobal(*this,&TestScripts::Test2,_T("Test2")); BindVariable(&Var_ToBind1,_T("Var_ToBind1")); } // InitScript1 void InitScript2(void) { Var_ToBind2 = 909; SQClassDef<STestScripts>(_T("STestScripts")). staticFunc(*this,&TestScripts::Test1,_T("Test1")). staticFunc(*this,&TestScripts::Test2,_T("Test2")). staticVar(&Var_ToBind2,_T("Var_ToBind2")); } // InitScript2 void Test1(void) { scprintf(_T("Test1 called.\n")); } void Test2(void) { scprintf(_T("Test2 called.\n")); } } testScripts; // From forum questions #if 1 template<typename T> struct Point { Point() {} Point(T X, T Y) : X(X), Y(Y) {} T X, Y; }; template<typename T> struct Box { Box() {} Box(Point<T> UpperLeft, Point<T> LowerRight) : UpperLeft(UpperLeft), LowerRight(LowerRight) {} Point<T> UpperLeft, LowerRight; void print(void) { scprintf(_T("UL.X %f UL.Y %f LR.X %f LR.Y %f\n"),UpperLeft.X,UpperLeft.Y,LowerRight.X,LowerRight.Y); } }; template<typename T> struct Window { int id; Box<T> box; }; typedef Point<float> Pointf; typedef Box<float> Boxf; typedef Window<float> Windowf; #else struct Pointf { float X,Y; Pointf() {} Pointf(float _X, float _Y) : X(_X), Y(_Y) {} }; struct Boxf { Pointf UpperLeft,LowerRight; Boxf() {} Boxf(Pointf _UpperLeft,Pointf _LowerRight) : UpperLeft(_UpperLeft), LowerRight(_LowerRight) {} void print(void) { scprintf(_T("UL.X %f UL.Y %f LR.X %f LR.Y %f\n"),UpperLeft.X,UpperLeft.Y,LowerRight.X,LowerRight.Y); } }; struct Windowf { int id; Boxf box; }; #endif DECLARE_INSTANCE_TYPE(Pointf) DECLARE_INSTANCE_TYPE(Boxf) DECLARE_INSTANCE_TYPE(Windowf) int constructPointf(float X,float Y,HSQUIRRELVM v) { return PostConstruct<Pointf>(v,new Pointf(X,Y),ReleaseClassPtr<Pointf>::release); } // constructPointf // Must pass by reference or pointer (not copy) int constructBoxf(Pointf & UpperLeft,Pointf & LowerRight,HSQUIRRELVM v) { return PostConstruct<Boxf>(v,new Boxf(UpperLeft,LowerRight),ReleaseClassPtr<Boxf>::release); } // constructBoxf struct WindowHolder { static Windowf * currentWindow; static Windowf * getWindow(void) { return currentWindow; } // getWindow }; Windowf * WindowHolder::currentWindow = 0; // From forum post: compiler works OK. void testCompiler(void) { SquirrelObject test = SquirrelVM::CompileBuffer(_T("\ local SceneManager = getSceneManager() ; \n\ \n\ SceneManager.AddScene(\"Scene1\") ; \n\ SceneManager.AddScene(\"Scene4\") ; \n\ SceneManager.ActivateScene(\"Scene1\") ; \n\ ")); SquirrelVM::RunScript(test); } void testPointfBoxf(void) { // testCompiler(); SQClassDef<Pointf>(_T("Pointf")). staticFunc(constructPointf,_T("constructor")). var(&Pointf::X,_T("X")). var(&Pointf::Y,_T("Y")); SQClassDef<Boxf>(_T("Boxf")). staticFunc(constructBoxf,_T("constructor")). func(&Boxf::print,_T("print")). var(&Boxf::UpperLeft,_T("UpperLeft")). var(&Boxf::LowerRight,_T("LowerRight")); SQClassDef<Windowf>(_T("Windowf")). var(&Windowf::id,_T("Id")). var(&Windowf::box,_T("Box")); RegisterGlobal(WindowHolder::getWindow,_T("getWindow")); Windowf myWindow; myWindow.id = 42; myWindow.box = Boxf(Pointf(1.f,2.f),Pointf(3.f,4.f)); WindowHolder::currentWindow = &myWindow; // The createWindow() function below creates a new instance on the root table. // The instance data is a pointer to the C/C++ instance, and will not be freed // or otherwise managed. SquirrelObject test = SquirrelVM::CompileBuffer(_T("\ local MyWindow = Windowf(); \n\ MyWindow.Box = Boxf(Pointf(11.,22.),Pointf(33.,44.)); \n\ print(MyWindow.Box.LowerRight.Y); \n\ MyWindow.Box.LowerRight.Y += 1.; \n\ local MyWindow2 = Windowf(); \n\ MyWindow2 = MyWindow; \n\ print(MyWindow2.Box.LowerRight.Y); \n\ local MyBox = Boxf(Pointf(10.,20.),Pointf(30.,40.)); \n\ MyBox.UpperLeft = Pointf(1000.,1000.); \n\ MyBox.UpperLeft.X = 5000. \n\ print(MyBox.UpperLeft.X) \n\ print(MyBox.UpperLeft.Y) \n\ MyWindow2.Box = MyBox; \n\ MyWindow2.Box.print(); \n\ MyWindow2 = getWindow(); \n\ print(\"MyWindow2: \"+MyWindow2.Id); \n\ MyWindow2.Box.print(); \n\ function createWindow(name,instance) { \n\ ::rawset(name,instance); \n\ } \n\ ")); SquirrelVM::RunScript(test); Windowf window = myWindow; window.id = 54; window.box.UpperLeft.X += 1; window.box.UpperLeft.Y += 1; window.box.LowerRight.X += 1; window.box.LowerRight.Y += 1; // Create a new Window instance "NewWindow" on the root table. SquirrelFunction<void>(_T("createWindow"))(_T("NewWindow"),&window); SquirrelObject test2 = SquirrelVM::CompileBuffer(_T("\ print(\"NewWindow: \"+NewWindow.Id); \n\ NewWindow.Box.print(); \n\ ")); SquirrelVM::RunScript(test2); } // testPointfBoxf // Example debug hook: called back during script execution. SQInteger debug_hook(HSQUIRRELVM v) { SQUserPointer up; int event_type,line; const SQChar *src,*func; sq_getinteger(v,2,&event_type); sq_getstring(v,3,&src); sq_getinteger(v,4,&line); sq_getstring(v,5,&func); sq_getuserpointer(v,-1,&up); return 0; } // debug_hook // You can add functions/vars here, as well as bind globals to be accessed through this class as shown in the NameSpace example. // If the class is instantiated in script, the instance is "locked", preventing accidental changes to elements. // Thus using an instance as the namespace can be a better design for development. // If variables/constants are bound to the class and/or non-static/non-global functions, the class must be instantiated before use. struct NamespaceClass { }; // === END Class Instance Test === class TestBase { public: int x; TestBase() : x(0) { printf("Constructing TestBase[0x%x]\n",(size_t)this); } void print(void) { printf("TestBase[0x%x], x[%d]\n",(size_t)this,x); } }; DECLARE_INSTANCE_TYPE(TestBase) class TestDerivedCPP : public TestBase { public: int y; TestDerivedCPP() { x = 121; } }; typedef void (TestDerivedCPP::*TestDerivedCPP_print)(void); void testInhertianceCase(void) { SQClassDef<TestBase>(_T("TestBase")). var(&TestBase::x,_T("x")). func(&TestBase::print,_T("print")); SQClassDef<TestDerivedCPP>(_T("TestDerivedCPP")). func((TestDerivedCPP_print)&TestDerivedCPP::print,_T("print")); // Note that the constructor definition and call below is not required for this example. // (The C/C++ constructor will be called automatically). SquirrelObject testInheritance2 = SquirrelVM::CompileBuffer(_T("\ class TestDerived extends TestBase { \n\ function print() { \n\ ::TestBase.print(); \n\ ::print(\"Derived: \"+x); \n\ } \n\ constructor() { \n\ TestBase.constructor(); \n\ } \n\ } \n\ local a = TestDerived(); \n\ local b = TestDerived(); \n\ a.x = 1; \n\ b.x = 2; \n\ print(\"a.x = \"+a.x); \n\ print(\"b.x = \"+b.x); \n\ a.print(); \n\ b.print(); \n\ local c = TestDerivedCPP(); \n\ c.print(); \n\ ")); SquirrelVM::RunScript(testInheritance2); } // === BEGIN from a forum post by jkleinecke. 8/23/06 jcs === namespace Scripting { class ScriptEntity { public: ScriptEntity() { Bind(); } static void Bind() { SqPlus::SQClassDef<ScriptEntity>(_T("ScriptEntity")). var(&ScriptEntity::m_strName,_T("name")); } // Bind SqPlus::ScriptStringVar64 m_strName; }; } DECLARE_INSTANCE_TYPE_NAME(Scripting::ScriptEntity,ScriptEntity) void testScriptingTypeName(void) { try { Scripting::ScriptEntity entity ; SqPlus::BindVariable(&entity,_T("instance")); SquirrelObject sqObj = SquirrelVM::CompileBuffer(_T("instance.name = \"Testing an instance variable bind: member assignment.\"; print(instance.name);")); SquirrelVM::RunScript(sqObj); } // try catch (SquirrelError e) { scprintf(_T("testScriptingTypeName: %s\n"),e.desc); } // catch } // === END from a forum post by jkleinecke. 8/23/06 jcs === // === BEGIN Interface Test === class PureInterface { public: virtual void pureFunc1(void)=0; virtual void pureFunc2(void)=0; }; class MyImp : public PureInterface { public: PureInterface * getInterface(void) { return (PureInterface *)this; } void pureFunc1(void) { scprintf(_T("PureFunc1 called [0x%p].\n"),this); } void pureFunc2(void) { scprintf(_T("PureFunc2 called [0x%p].\n"),this); } }; class InterfaceHolder { public: PureInterface * theInterface; void setInterface(PureInterface * pureInterface) { theInterface = pureInterface; } PureInterface * getInterface(void) { return theInterface; } }; DECLARE_INSTANCE_TYPE(PureInterface) DECLARE_INSTANCE_TYPE(MyImp) DECLARE_INSTANCE_TYPE(InterfaceHolder) void testPureVirtualInterface(void) { SQClassDefNoConstructor<PureInterface>(_T("PureInterface")). func(&PureInterface::pureFunc1,_T("pureFunc1")). func(&PureInterface::pureFunc2,_T("pureFunc2")); SQClassDef<InterfaceHolder>(_T("InterfaceHolder")). func(&InterfaceHolder::setInterface,_T("setInterface")). func(&InterfaceHolder::getInterface,_T("getInterface")); SQClassDef<MyImp>(_T("MyImp")). func(&MyImp::getInterface,_T("getInterface")); MyImp myImp; SquirrelObject test = SquirrelVM::CompileBuffer(_T("ih <- InterfaceHolder();")); SquirrelVM::RunScript(test); SquirrelObject root = SquirrelVM::GetRootTable(); SquirrelObject ih = root.GetValue(_T("ih")); InterfaceHolder * ihp = (InterfaceHolder * )ih.GetInstanceUP(ClassType<InterfaceHolder>::type()); ihp->setInterface(&myImp); test = SquirrelVM::CompileBuffer(_T("\ ih.getInterface().pureFunc1(); \n\ ih.getInterface().pureFunc2(); \n\ ihp <- ih.getInterface(); \n\ ihp.pureFunc1(); \n\ ihp.pureFunc2(); \n\ myIh <- MyImp(); \n\ ih.setInterface(myIh.getInterface()); \n\ ih.getInterface().pureFunc1(); \n\ ih.getInterface().pureFunc2(); \n\ ")); SquirrelVM::RunScript(test); } // testPureVirtualInterface // === END Interface Test === void testSquirrelObjectSetGet(void) { // We can pass in arguments: // by value ('true' arg, required for constant float, int, etc., or when a copy is desired), // by reference (data will be copied to SquirrelObject and memory managed), // by pointer (no data copying: pointer is used directly in SquirrelObject; the memory will not be managed). SquirrelObject tc(5.678f); // constant argument is passed by value (even though declaration is by ref: const & results in by-value in this case), memory will be allocated and managed for the copy. float valc = tc.Get<float>(); scprintf(_T("Valc is: %f\n"),valc); float val = 1.234f; SquirrelObject t(val); // val is passed by reference, memory will be allocated, and the value copied once. float val2 = t.Get<float>(); scprintf(_T("Val2 is: %f\n"),val2); if (1) { SquirrelObject v(Vector3(1.f,2.f,3.f)); // Pass in by reference: will be copied once, with memory for new copy managed by Squirrel. Vector3 * pv = v.Get<Vector3 *>(); scprintf(_T("Vector3 is: %f %f %f\n"),pv->x,pv->y,pv->z); pv->z += 1.f; if (1) { SquirrelObject v2p(pv); // This is a pointer to v's instance (passed in by pointer: see SquirrelObject.h). // A new Squirrel Instance will be created, but the C++ instance pointer will not get freed when v2p goes out of scope (release hook will be null). pv = v2p.Get<Vector3 *>(); scprintf(_T("Vector3 is: %f %f %f\n"),pv->x,pv->y,pv->z); } // if } // if scprintf(_T("Vector3() instance has been released.\n\n")); } // testSquirrelObjectSetGet #define SQDBG_DEBUG_HOOK _T("_sqdebughook_") class TestSqPlus { public: enum {SQ_ENUM_TEST=1234321}; void init(void) { SquirrelVM::Init(); HSQUIRRELVM _v = SquirrelVM::GetVMPtr(); #if 1 sq_pushregistrytable(_v); sq_pushstring(_v,SQDBG_DEBUG_HOOK,-1); sq_pushuserpointer(_v,this); sq_newclosure(_v,debug_hook,1); sq_createslot(_v,-3); // sq_pop(_v,1); // sq_pushregistrytable(_v); sq_pushstring(_v,SQDBG_DEBUG_HOOK,-1); sq_rawget(_v,-2); sq_setdebughook(_v); sq_pop(_v,1); #endif sq_enabledebuginfo(_v,SQTrue); } // init TestSqPlus() { init(); testPureVirtualInterface(); testScriptingTypeName(); try { HSQUIRRELVM v = SquirrelVM::GetVMPtr(); SquirrelObject root = SquirrelVM::GetRootTable(); testPointfBoxf(); // Example from forum question: testScripts.InitScript1(); testScripts.InitScript2(); SquirrelObject testScriptBinding = SquirrelVM::CompileBuffer(_T("\ local testScripts = STestScripts(); \n\ testScripts.Test1(); \n\ testScripts.Test2(); \n\ print(testScripts.Var_ToBind2); \n\ Test1(); \n\ Test2(); \n\ print(Var_ToBind1); \n\ ")); SquirrelVM::RunScript(testScriptBinding); // === BEGIN Global Function binding tests === // Implemented as SquirrelVM::CreateFunction(rootTable,func,name,typeMask). CreateFunctionGlobal() binds a standard SQFUNCTION (stack args). SquirrelVM::CreateFunctionGlobal(testFunc,_T("testFunc0")); SquirrelVM::CreateFunctionGlobal(testFunc,_T("testFuncN"),_T("n")); SquirrelVM::CreateFunctionGlobal(testFunc,_T("testFuncS"),_T("s")); #if 0 SquirrelObject testStandardFuncs = SquirrelVM::CompileBuffer(_T(" testFunc0(); testFuncN(1.); testFuncS(\"Hello\"); ")); SquirrelVM::RunScript(testStandardFuncs); #endif // === Register Standard Functions using template system (function will be directly called with argument auto-marshaling) === RegisterGlobal(v,newtest,_T("test")); RegisterGlobal(v,newtestR1,_T("testR1")); // === Register Member Functions to existing classes (as opposed to instances of classes) === NewTestObj t1,t2,t3; t1.val = 123; t2.val = 456; t3.val = 789; RegisterGlobal(v,t1,&NewTestObj::newtest,_T("testObj_newtest1")); RegisterGlobal(v,t2,&NewTestObj::newtest,_T("testObj_newtest2")); // Register newtest() again with different name and object pointer. SquirrelObject tr = SquirrelVM::GetRootTable(); // Can be any object supporting closures (functions). Register(v,tr.GetObjectHandle(),t3,&NewTestObj::newtestR1,_T("testObj_newtestR1")); // Return value version. // === END Global Function binding tests === // === BEGIN Namespace examples === // Create a namespace using a table. SquirrelObject nameSpaceTable = SquirrelVM::CreateTable(); root.SetValue(_T("Namespace1"),nameSpaceTable); Register(v,nameSpaceTable.GetObjectHandle(),globalFunc,_T("namespaceFunc")); // Create a namespace using a class. If an instance is created from the class, using the instance will prevent accidental changes to the instance members. // Using the class/instance form also allows extra information to be added to the proxy class, if desired (such as vars/funcs). // NOTE: If any variables/static-variables/constants are registered to the class, it must be instantiated before use. SQClassDef<NamespaceClass>(_T("Namespace2")). staticFunc(globalFunc,_T("namespaceFunc")); SquirrelObject testNameSpace = SquirrelVM::CompileBuffer(_T("\ Namespace1.namespaceFunc(\"Hello Namespace1 (table),\",321); \n\ Namespace2.namespaceFunc(\"Hello Namespace2 (class),\",654); \n\ local Namespace3 = Namespace2(); \n\ Namespace3.namespaceFunc(\"Hello Namespace3 (instance),\",987); \n\ ")); SquirrelVM::RunScript(testNameSpace); // === END Namespace examples === // === BEGIN Class Instance tests === // Example showing two methods for registration. #if 0 SQClassDef<NewTestObj> sqClass(_T("NewTestObj")); sqClass.func(NewTestObj::newtestR1,_T("newtestR1")); sqClass.var(&NewTestObj::val,_T("val")); sqClass.var(&NewTestObj::s1,_T("s1")); sqClass.var(&NewTestObj::s2,_T("s2")); sqClass.var(&NewTestObj::c1,_T("c1"),VAR_ACCESS_READ_ONLY); sqClass.var(&NewTestObj::c2,_T("c2"),VAR_ACCESS_READ_ONLY); sqClass.funcVarArgs(NewTestObj::multiArgs,_T("multiArgs")); #else SQClassDef<NewTestObj>(_T("NewTestObj")). // If a special constructor+destructor are not needed, the auto-generated versions can be used. // Example methods for custom constructors: staticFuncVarArgs(constructNewTestObj,_T("constructor"),_T("*")). // Using a global constructor: useful in cases where a custom constructor/destructor are required and the original class is not to be modified. // staticFunc(constructNewTestObjFixedArgs,_T("constructor")). // Using a global constructor: useful in cases where a custom constructor/destructor are required and the original class is not to be modified. // staticFuncVarArgs(NewTestObj::construct,_T("constructor")). // Using a static member constructor. staticFunc(globalFunc,_T("globalFunc")). // Any global function can be registered in a class namespace (no 'this' pointer will be passed to the function). staticFunc(globalClass,&GlobalClass::func,_T("globalClassFunc")). func(&NewTestObj::newtestR1,_T("newtestR1")). var(&NewTestObj::val,_T("val")). var(&NewTestObj::s1,_T("s1")). var(&NewTestObj::s2,_T("s2")). var(&NewTestObj::c1,_T("c1"),VAR_ACCESS_READ_ONLY). var(&NewTestObj::c2,_T("c2"),VAR_ACCESS_READ_ONLY). funcVarArgs(&NewTestObj::multiArgs,_T("multiArgs")); #define SQ_10 10 #define SQ_E 2.71828182845904523536f #define SQ_PI 3.14159265358979323846264338327950288f #define SQ_CONST_STRING _T("A constant string") const int intConstant = 7; const float floatConstant = 8.765f; const bool boolConstant = true; #if 1 SQClassDef<Vector3>(_T("Vector3")). var(&Vector3::x,_T("x")). var(&Vector3::y,_T("y")). var(&Vector3::z,_T("z")). func(&Vector3::Inc,_T("Inc")). func(&Vector3::operator+,_T("_add")). staticFunc(&Add2,_T("Add2")). staticFuncVarArgs(&Add,_T("Add")). #if 1 staticVar(&Vector3::staticVar,_T("staticVar")). #else staticVar(&Vector3::staticVar,_T("staticVar"),VAR_ACCESS_READ_ONLY). #endif staticVar(&globalVar,_T("globalVar")). constant(SQ_10,_T("SQ_10")). constant(SQ_E,_T("SQ_E")). constant(SQ_PI,_T("SQ_PI")). constant(SQ_CONST_STRING,_T("SQ_CONST_STRING")). enumInt(SQ_ENUM_TEST,_T("SQ_ENUM_TEST")). constant(intConstant,_T("intConstant")). constant(floatConstant,_T("floatConstant")). constant(true,_T("boolTrue")). constant(false,_T("boolFalse")). constant(boolConstant,_T("boolConstant")); #endif #endif testSquirrelObjectSetGet(); // Uses Vector3(). BindConstant(SQ_PI*2,_T("SQ_PI_2")); BindConstant(SQ_10*2,_T("SQ_10_2")); BindConstant(_T("Global String"),_T("GLOBAL_STRING")); SquirrelObject testStaticVars = SquirrelVM::CompileBuffer(_T(" local v = Vector3(); local v2 = Vector3(); local v3 = v+v2; v3 += v2; print(\"v3.x: \"+v3.x); print(\"Vector3::staticVar: \"+v.staticVar+\" Vector3::globalVar: \"+v.globalVar); v.staticVar = 0; ")); SquirrelVM::RunScript(testStaticVars); SquirrelObject testConstants0 = SquirrelVM::CompileBuffer(_T(" print(\"SQ_PI*2: \"+SQ_PI_2+\" SQ_10_2: \"+SQ_10_2+\" GLOBAL_STRING: \"+GLOBAL_STRING); ")); SquirrelVM::RunScript(testConstants0); SquirrelObject testConstants1 = SquirrelVM::CompileBuffer(_T("local v = Vector3(); print(\"SQ_10: \"+v.SQ_10+\" SQ_E: \"+v.SQ_E+\" SQ_PI: \"+v.SQ_PI+\" SQ_CONST_STRING: \"+v.SQ_CONST_STRING+\" SQ_ENUM_TEST: \"+v.SQ_ENUM_TEST);" )); SquirrelVM::RunScript(testConstants1); SquirrelObject testConstants2 = SquirrelVM::CompileBuffer(_T("local v = Vector3(); print(\"intConstant: \"+v.intConstant+\" floatConstant: \"+v.floatConstant+\" boolTrue: \"+(v.boolTrue?\"True\":\"False\")+\" boolFalse: \"+(v.boolFalse?\"True\":\"False\")+\" boolConstant: \"+(v.boolConstant?\"True\":\"False\"));" )); SquirrelVM::RunScript(testConstants2); SquirrelObject scriptedBase = SquirrelVM::CompileBuffer(_T(" class ScriptedBase { sbval = 5551212; function multiArgs(a,...) { print(\"SBase: \"+a+val); } \n } \n ")); // Note val does not exist in base. SquirrelVM::RunScript(scriptedBase); // === BEGIN Instance Test === SQClassDef<PlayerManager::Player>(_T("PlayerManager::Player")). func(&PlayerManager::Player::printName,_T("printName")). var(&PlayerManager::Player::name,_T("name")); SQClassDef<PlayerManager>(_T("PlayerManager")). func(&PlayerManager::GetPlayer,_T("GetPlayer")). var(&PlayerManager::playerVar,_T("playerVar")); RegisterGlobal(getPlayerManager,_T("getPlayerManager")); BindVariable(&playerManager,_T("playerManagerVar")); SquirrelObject testGetInstance = SquirrelVM::CompileBuffer(_T("\ local PlayerManager = getPlayerManager(); \n\ local oPlayer = PlayerManager.GetPlayer(0); \n\ print(typeof oPlayer); \n\ oPlayer.printName(); \n\ PlayerManager.playerVar.printName(); \n\ print(PlayerManager.playerVar.name); \n\ oPlayer = PlayerManager.playerVar; \n\ oPlayer.name = \"New_Name1\"; \n\ playerManagerVar.playerVar.printName(); \n\ oPlayer.name = \"New_Name2\"; \n\ ")); SquirrelVM::RunScript(testGetInstance); scprintf(_T("playerManager.playerVar.name: %s\n"),playerManager.playerVar.name.s); // === END Instance Test === // === BEGIN example from forum post === SQClassDef<Creature>(_T("Creature")). func(&Creature::GetMaxHealth,_T("GetMaxHealth")). func(&Creature::GetHealth,_T("GetHealth")). func(&Creature::SetHealth,_T("SetHealth")); SquirrelObject testClass = SquirrelVM::CompileBuffer( _T("function HealthPotionUse(Target) { \n\ local curHealth = Target.GetHealth(); \n\ local maxHealth = Target.GetMaxHealth(); \n\ if ((maxHealth - curHealth) > 15) { \n\ curHealth += 15; \n\ } else { \n\ curHealth = maxHealth; \n\ } \n\ Target.SetHealth(curHealth); \n\ print(typeof Target); \n\ return Target; \n\ }")); Creature frodo; frodo.SetHealth(frodo.GetMaxHealth()/2); SquirrelVM::RunScript(testClass); Creature newFrodo = SquirrelFunction<Creature &>(_T("HealthPotionUse"))(frodo); // Pass by value and return a copy (Must return by reference due to template system design). SquirrelFunction<void>(_T("HealthPotionUse"))(&frodo); // Pass the address to directly modify frodo. scprintf(_T("Frodo's health: %d %d\n"),frodo.GetHealth(),newFrodo.GetHealth()); // === END example from forum post === #ifdef SQ_USE_CLASS_INHERITANCE // Base class constructors, if registered, must use this form: static int construct(HSQUIRRELVM v). // SQClassDef<CustomTestObj> customClass(_T("CustomTestObj")); SQClassDef<CustomTestObj> customClass(_T("CustomTestObj"),_T("ScriptedBase")); // SQClassDef<CustomTestObj> customClass(_T("CustomTestObj"),_T("NewTestObj")); customClass.staticFuncVarArgs(&CustomTestObj::construct,_T("constructor"),_T("*")); // MUST use this form (or no args) if CustomTestObj will be used as a base class. // Using the "*" form will allow a single constructor to be used for all cases. // customClass.staticFuncVarArgs(CustomTestObj::construct,_T("constructor")); // (this form is also OK if used as a base class) customClass.funcVarArgs(&CustomTestObj::varArgTypesAndCount,_T("multiArgs"),_T("*")); // "*": no type or count checking. customClass.funcVarArgs(&CustomTestObj::varArgTypesAndCount,_T("varArgTypesAndCount"),_T("*")); // "*": no type or count checking. #else SQClassDef<CustomTestObj> customClass(_T("CustomTestObj")); customClass.staticFuncVarArgs(&CustomTestObj::construct,_T("constructor"),_T("snb")); // string, number, bool (all types must match). customClass.funcVarArgs(&CustomTestObj::varArgTypesAndCount,_T("varArgTypesAndCount"),_T("*")); // "*": no type or count checking. #endif customClass.funcVarArgs(&CustomTestObj::varArgTypes,_T("varArgTypes"),_T("s|ns|ns|ns|n")); // string or number + string or number. customClass.funcVarArgs(&CustomTestObj::noArgsVariableReturn,_T("noArgsVariableReturn")); // No type string means no arguments allowed. customClass.func(&CustomTestObj::variableArgsFixedReturnType,_T("variableArgsFixedReturnType")); // Variables args, fixed return type. customClass.func(&CustomTestObj::manyArgs,_T("manyArgs")); // Many args, type checked. customClass.func(&CustomTestObj::manyArgsR1,_T("manyArgsR1")); // Many args, type checked, one return value. #ifdef SQ_USE_CLASS_INHERITANCE // SquirrelObject testInheritance = SquirrelVM::CompileBuffer(_T(" class Derived extends NewTestObj { s1 = 123; \n constructor() { NewTestObj.constructor(this); }; function getParentS2() return s2; \n }; \n local t = Derived(); \n print(\"DerS2: \"+t.getParentS2()); t.multiArgs(); //t.newtestR1(\"R1in\"); ")); // SquirrelObject testInheritance = SquirrelVM::CompileBuffer(_T(" local t = CustomTestObj(\"sa\",321,true); \n t.val = 444; print(t.val); t.variableArgsFixedReturnType(4,5.5); t.multiArgs(1,2,3); t.newtestR1(\"R1in\"); ")); // SquirrelObject testInheritance = SquirrelVM::CompileBuffer(_T(" class Derived extends CustomTestObj { val = 888; \n function func(a) print(a+dVal);\n } \n local x = Derived(); print(\"x.val \"+x.val); local t = CustomTestObj(\"sa\",321,true); \n t.val = 444; print(t.val); t.variableArgsFixedReturnType(4,5.5); t.multiArgs(1,2,3); t.newtestR1(\"R1in\"); ")); SquirrelObject testInheritance = SquirrelVM::CompileBuffer(_T(" class Derived extends CustomTestObj { val = 888; \n function multiArgs(a,...) { print(a+val); \n print(sbval); ::CustomTestObj.multiArgs(4); ::ScriptedBase.multiArgs(5,6,7); \n }\n } \n local x = Derived(); print(\"x.val \"+x.val); x.multiArgs(1,2,3); ")); // SquirrelObject testInheritance = SquirrelVM::CompileBuffer(_T(" class Derived extends CustomTestObj { val = 888; \n function multiArgs(a,...) print(a+val);\n } \n local x = Derived(); print(\"x.val \"+x.val); x.multiArgs(1,2,3); //local t = CustomTestObj(); \n t.val = 444; print(t.val); t.variableArgsFixedReturnType(4,5.5); t.multiArgs(1,2,3); t.newtestR1(\"R1in\"); ")); printf("=== BEGIN INHERITANCE ===\n"); testInhertianceCase(); SquirrelVM::RunScript(testInheritance); printf("=== END INHERITANCE ===\n"); #endif SquirrelObject testRegV = SquirrelVM::CompileBuffer(_T(" local vec = Vector3(); print(vec.x); vec = vec.Add(vec); print(vec.x); vec = vec.Add(vec); print(vec.x); vec = vec.Add2(vec,vec); print(vec.x); local v2 = Vector3(); vec = v2.Inc(vec); print(vec.x); print(v2.x); ")); SquirrelVM::RunScript(testRegV); #ifdef SQ_USE_CLASS_INHERITANCE SquirrelObject testReg0 = SquirrelVM::CompileBuffer(_T(" co <- CustomTestObj(\"hello\",123,true); co.varArgTypes(\"str\",123,123,\"str\"); co.varArgTypes(123,\"str\",\"str\",123); ")); SquirrelVM::RunScript(testReg0); SquirrelObject testReg0a = SquirrelVM::CompileBuffer(_T(" print(co.varArgTypesAndCount(1,true)); print(co.varArgTypesAndCount(2,false,3.)); print(\"\\n\"); ")); SquirrelVM::RunScript(testReg0a); SquirrelObject testReg0b = SquirrelVM::CompileBuffer(_T(" print(co.noArgsVariableReturn()); print(co.noArgsVariableReturn()); print(co.noArgsVariableReturn()); print(\"\\n\"); ")); SquirrelVM::RunScript(testReg0b); SquirrelObject testReg0c = SquirrelVM::CompileBuffer(_T(" print(co.variableArgsFixedReturnType(1)); print(co.variableArgsFixedReturnType(1,2)); print(co.variableArgsFixedReturnType(1,2,3)); print(\"\\n\"); ")); SquirrelVM::RunScript(testReg0c); SquirrelObject testReg0d = SquirrelVM::CompileBuffer(_T(" co.manyArgs(111,222.2,true,\"Hello\"); print(co.manyArgsR1(333,444.3,false,\"World\")); print(\"\\n\"); ")); SquirrelVM::RunScript(testReg0d); SquirrelObject testReg1a = SquirrelVM::CompileBuffer(_T(" co <- CustomTestObj(\"hello\",123,true); co.noArgsVariableReturn(); local t = NewTestObj(\"S1in\",369,true); print(\"C1: \"+t.c1); print(\"C2: \"+t.c2); // t.c1 = 123; ")); SquirrelVM::RunScript(testReg1a); // Constant test (read only var). Var can change on C++ side, but not on script side. try { SquirrelObject testRegConstant = SquirrelVM::CompileBuffer(_T(" local t = NewTestObj(); t.c1 = 123; ")); SquirrelVM::RunScript(testRegConstant); } // try catch (SquirrelError & e) { scprintf(_T("Error: %s, %s\n"),e.desc,_T("Squirrel::TestConstant")); } // catch SquirrelObject testReg1 = SquirrelVM::CompileBuffer(_T(" local t = NewTestObj(); t.newtestR1(\"Hello\"); t.val = 789; print(t.val); print(t.s1); print(t.s2); t.s1 = \"New S1\"; print(t.s1); ")); SquirrelVM::RunScript(testReg1); SquirrelObject testReg2 = SquirrelVM::CompileBuffer(_T(" local t = NewTestObj(); t.val = 789; print(t.val); t.val = 876; print(t.val); t.multiArgs(1,2,3); t.multiArgs(1,2,3,4); t.globalFunc(\"Hola\",5150,false); t.globalClassFunc(\"Bueno\",5151,true); ")); SquirrelVM::RunScript(testReg2); SquirrelObject testReg3 = SquirrelVM::CompileBuffer(_T(" test(); local rv = testR1(\"Hello\"); print(rv); ")); SquirrelVM::RunScript(testReg3); SquirrelObject testReg4 = SquirrelVM::CompileBuffer(_T(" print(\"\\nMembers:\"); testObj_newtest1(); testObj_newtest2(); print(testObj_newtestR1(\"Hello Again\")); ")); SquirrelVM::RunScript(testReg4); SquirrelObject defCallFunc = SquirrelVM::CompileBuffer(_T(" function callMe(var) { print(\"I was called by: \"+var); return 123; }")); SquirrelVM::RunScript(defCallFunc); SquirrelObject defCallFuncStrRet = SquirrelVM::CompileBuffer(_T(" function callMeStrRet(var) { print(\"I was called by: \"+var); return var; }")); SquirrelVM::RunScript(defCallFuncStrRet); SquirrelFunction<void>(_T("callMe"))(_T("Squirrel 1")); // Get a function from the root table and call it. #if 1 SquirrelFunction<int> callFunc(_T("callMe")); int ival = callFunc(_T("Squirrel")); scprintf(_T("IVal: %d\n"),ival); SquirrelFunction<const SQChar *> callFuncStrRet(_T("callMeStrRet")); const SQChar * sval = callFuncStrRet(_T("Squirrel StrRet")); scprintf(_T("SVal: %s\n"),sval); #endif ival = 0; // Get a function from any table. SquirrelFunction<int> callFunc2(root.GetObjectHandle(),_T("callMe")); ival = callFunc(456); // Argument count is checked; type is not. // === END Class Instance tests === SquirrelObject main = SquirrelVM::CompileBuffer(_T("table1 <- {key1=\"keyVal\",key2 = 123};\n if (\"key1\" in table1)\n print(\"Sq: Found it\");\n else\n print(\"Sq: Not found\");")); SquirrelVM::RunScript(main); SquirrelObject table1 = root.GetValue(_T("table1")); if (table1.Exists(_T("key1"))) { scprintf(_T("C++: Found it.\n")); } else { scprintf(_T("C++: Did not find it.\n")); } // if // === BEGIN Simple variable binding tests === int iVar = 777; float fVar = 88.99f; bool bVar = true; BindVariable(root,&iVar,_T("iVar")); BindVariable(root,&fVar,_T("fVar")); BindVariable(root,&bVar,_T("bVar")); static ScriptStringVar128 testString; scsprintf(testString,_T("This is a test string")); BindVariable(root,&testString,_T("testString")); // === END Simple variable binding tests === // === BEGIN Array Tests === SquirrelObject array = SquirrelVM::CreateArray(10); int i; for (i = 0; i < 10; i++) array.SetValue(i,i); array.ArrayAppend(123); // int array.ArrayAppend(true); // bool (must use bool and not SQBool (SQBool is treated as INT by compiler). array.ArrayAppend(false); // bool (must use bool and not SQBool (SQBool is treated as INT by compiler). array.ArrayAppend(123.456f); // float array.ArrayAppend(_T("string")); // string array.ArrayAppend(456); // Will be popped and thrown away (below). array.ArrayAppend((SQUserPointer)0); // Pop 3 items from array: array.ArrayPop(SQFalse); // Don't retrieve the popped value (int:123). SquirrelObject so1 = array.ArrayPop(); // Retrieve the popped value. const SQChar * val1 = so1.ToString(); // Get string. float val2 = array.ArrayPop().ToFloat(); // Pop and get float. scprintf(_T("[Popped values] Val1: %s, Val2: %f\n"),val1,val2); int startIndex = array.Len(); array.ArrayExtend(10); // Implemented as: ArrayResize(Len()+amount). for (i = startIndex; i < array.Len(); i++) array.SetValue(i,i*10); root.SetValue(_T("array"),array); SquirrelObject arrayr = array.Clone(); // Get a copy as opposed to another reference. arrayr.ArrayReverse(); root.SetValue(_T("arrayr"),arrayr); // === END Array Tests === SquirrelObject define_printArray = SquirrelVM::CompileBuffer(_T(" function printArray(name,array) { print(name+\".len() = \"+array.len()); foreach(i, v in array) if (v != null) { if (typeof v == \"bool\") v = v ? \"true\" : \"false\"; print(\"[\"+i+\"]: \"+v); } } ")); SquirrelVM::RunScript(define_printArray); SquirrelObject test = SquirrelVM::CompileBuffer(_T(" printArray(\"array\",array); printArray(\"arrayr\",arrayr); ")); SquirrelVM::RunScript(test); #endif } // try catch (SquirrelError & e) { scprintf(_T("Error: %s, in %s\n"),e.desc,_T("TestSqPlus")); } // catch } ~TestSqPlus() { SquirrelVM::Shutdown(); } }; void doTest(void) { TestSqPlus testSqPlus; } // doTest int main(int argc,char * argv[]) { // Run twice to make sure cleanup/shutdown works OK. SCPUTS(_T("Start Pass 1\n")); doTest(); #if 0 SCPUTS(_T("Start Pass 2\n")); doTest(); #endif SCPUTS(_T("Done.\n")); scprintf(_T("Press RETURN to exit.")); getchar(); return 0; }
true
77020014dabefeabaf2a3c83cb2504eb8d347eb2
C++
CoreRobotics/CoreRobotics
/src/noise/Gmm.cpp
UTF-8
3,541
2.515625
3
[ "BSD-3-Clause" ]
permissive
/* * Copyright (c) 2017-2019, CoreRobotics. All rights reserved. * Licensed under BSD-3, https://opensource.org/licenses/BSD-3-Clause * http://www.corerobotics.org */ #define _USE_MATH_DEFINES #include "Gmm.hpp" #include "Eigen/Dense" #include "math/Matrix.hpp" #include "math/Probability.hpp" #include <cmath> namespace cr { namespace noise { //------------------------------------------------------------------------------ /*! This method performs the regression y = f(x) + e using by conditioning on the learned Gaussian Mixture Model.\n \param[in] i_x - the input vector \param[in] i_inputIndices - a vector of indices of the GMM means that defines the input. Note the size of i_inputIndices must match the size of i_x. \param[in] i_outputIndices - a vector of indices of the GMM means that defines the output. Note the size of i_outputIndices will correspond to the number of rows and columns in the output mean and covariance. \param[out] o_mean - the predicted mean \param[out] o_covariance - the predicted covariance */ //------------------------------------------------------------------------------ void Gmm::regression(Eigen::VectorXd i_x, Eigen::VectorXi i_inputIndices, Eigen::VectorXi i_outputIndices, Eigen::VectorXd &o_mean, Eigen::MatrixXd &o_covariance) { // Define the smallest number of double precision double realmin = sqrt(2.225073858507202e-308); // Get cluster/input/output dimensions int NK = m_parameters.models.size(); // Zero out the outputs o_mean.setZero(i_outputIndices.size()); o_covariance.setZero(i_outputIndices.size(), i_outputIndices.size()); // Init the intermediate variables double cweight = realmin; // initialize to smallest double so we don't ever divide by zero double weight = 0; Eigen::MatrixXd c1; c1.setZero(i_outputIndices.size(), i_outputIndices.size()); // For each Gaussian dist for (int k = 0; k < NK; k++) { // Get matrices we need Eigen::MatrixXd SigmaYY = math::Matrix::reducedMatrix( m_parameters.models.at(k)->getParameters().cov(), i_outputIndices, i_outputIndices); Eigen::MatrixXd SigmaYX = math::Matrix::reducedMatrix( m_parameters.models.at(k)->getParameters().cov(), i_outputIndices, i_inputIndices); Eigen::MatrixXd SigmaXY = math::Matrix::reducedMatrix( m_parameters.models.at(k)->getParameters().cov(), i_inputIndices, i_outputIndices); Eigen::MatrixXd SigmaXX = math::Matrix::reducedMatrix( m_parameters.models.at(k)->getParameters().cov(), i_inputIndices, i_inputIndices); Eigen::MatrixXd SigmaXXInv = SigmaXX.inverse(); Eigen::VectorXd MuY = math::Matrix::reducedVector( m_parameters.models.at(k)->getParameters().mean(), i_outputIndices); Eigen::VectorXd MuX = math::Matrix::reducedVector( m_parameters.models.at(k)->getParameters().mean(), i_inputIndices); // Return the mean, covariance, and weight Eigen::VectorXd Mu = MuY + SigmaYX * SigmaXXInv * (i_x - MuX); Eigen::MatrixXd Sigma = SigmaYY - SigmaYX * SigmaXXInv * SigmaXY; weight = m_parameters.weights.at(k) * math::Probability::mvnpdf(i_x, MuX, SigmaXX); cweight += weight; // compute the mean & covariance o_mean += weight * Mu; o_covariance += pow(weight, 2.0) * Sigma; } // Normalize o_mean = o_mean / cweight; o_covariance = o_covariance / pow(cweight, 2.0); } } // namespace noise } // namespace cr
true
30b0776b3f850dac78fe6601c5d08246630b606c
C++
faxinwang/DataStructure
/cpp/Matrixs/SparseMatrix_Tests.cpp
UTF-8
2,593
3.0625
3
[]
no_license
#include <iostream> #include "SparseMatrix.hpp" #include "Matrix.hpp" using namespace std; using namespace wfx; template<typename T> void print(Matrix<T>& m, string str=""){ int row = m.row(), col = m.column(); cout<<"//"<<str<<endl; printf("[%d X %d]:\n", row,col); for(int i=0; i<row; ++i){ for(int j=0; j<col; ++j) cout<<m[i][j]<<"\t"; cout<<endl; } cout<<endl; } int main(){ Matrix<int> m1(3,5); m1[0][1] = 1; m1[1][2] = 2; m1[1][3] = 3; m1[2][3] = 4; m1[2][4] = 5; print(m1, "m1 after create and assigned some values:"); /* //m1 after create and assigned some values: [3 X 5]: 0 1 0 0 0 0 0 2 3 0 0 0 0 4 5 */ MatrixTriple<int> mt1(m1); mt1.printMatrix("mt1 created from m1:"); /* mt1 created from m1: size:5 [3 X 5] 0 1 0 0 0 0 0 2 3 0 0 0 0 4 5 */ m1[0][1] = -1; MatrixTriple<int> mt2(m1); mt2.printMatrix("m1[0][1]=-1, mt2 created from m1:"); /* m1[0][1]=-1, mt2 created from m1: size:5 [3 X 5] 0 -1 0 0 0 0 0 2 3 0 0 0 0 4 5 */ mt1 += mt2; mt1.printMatrix("mt1 += mt2; mt1:"); /* mt1 += mt2; mt1: size:4 [3 X 5] 0 0 0 0 0 0 0 4 6 0 0 0 0 8 10 */ mt1 = mt1 + mt2; mt1.printMatrix("mt1 = mt1 + mt2; mt1:"); /* mt1 = mt1 + mt2; mt1: size:5 [3 X 5] 0 -1 0 0 0 0 0 6 9 0 0 0 0 12 15 */ MatrixTriple<int> mt3 = mt2.transpose(); mt3.printMatrix("mt3 = mt2.transpose(); mt3:"); /* mt3 = mt2.transpose(); mt3: size:5 [5 X 3] 0 0 0 -1 0 0 0 2 0 0 3 4 0 0 5 */ Matrix<int> m4 = mt1.toMatrix(); Matrix<int> m5 = mt3.toMatrix(); mt3 = mt3 * mt1; mt3.printMatrix("mt3 = mt3 * mt1; mt3:"); /* mt3 = mt3 * mt1; mt3: size:8 [5 X 5] 0 0 0 0 0 0 1 0 0 0 0 0 12 18 0 0 0 18 75 60 0 0 0 60 75 */ Matrix<int> m6 = m5 * m4; print(m6, "m6 = m5 * m4; m6:"); /* //m6 = m5 * m4; m6: [5 X 5]: 0 0 0 0 0 0 1 0 0 0 0 0 12 18 0 0 0 18 75 60 0 0 0 60 75 */ return 0; }
true
a6c50684fa12b72713837b3a9f3683d8ada68d16
C++
adnanlari/OOP-Lab-4thsem-2019
/matrix_complex.cpp
UTF-8
3,354
3.21875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; class comp { public: int real,imag; comp(int r=0,int i=0) { real=r; imag=i; } comp(comp const &x) { real=x.real; imag=x.imag; } friend comp operator + (comp const &x,comp const &y) { return comp(x.real+y.real,x.imag+y.imag); } friend comp operator - (comp const &x,comp const &y) { return comp(x.real-y.real,x.imag-y.imag); } friend comp operator * (comp const &x,comp const &y) { return comp(x.real*y.real-x.imag*y.imag,x.imag*y.real+x.real*y.imag); } friend comp operator ++ (comp &x) { x.real=x.real+1; x.imag=x.imag+1; } friend comp operator -- (comp &x) { x.real=x.real-1; x.imag=x.imag-1; } friend comp operator - (comp const &x) { return comp(-x.real,-x.imag); } friend float operator ~ (comp const &x) { return sqrt(x.real*x.real+x.imag*x.imag); } void dikhao() { cout<<real; if(imag>=0) cout<<"+"; cout<<imag<<"i"; } }; class mat { public: int size; comp **A; mat(int s=0) { size=s; A=new comp* [size]; for(int i=0;i<size;i++) *(A+i)=new comp[size]; cout<<"Input "<<size<<"*"<<size<<" complex elements : \n"; for(int i=0;i<size;i++) { for(int j=0;j<size;j++) { int x,y; cout<<"Real : "; cin>>x; cout<<"Imaginary : "; cin>>y; comp c(x,y); (*(*(A+j)+i))=c; } } } mat(mat const &x) { size=x.size; A=new comp* [size]; for(int i=0;i<size;i++) *(A+i)=new comp[size]; for(int i=0;i<size;i++) { for(int j=0;j<size;j++) *(*(A+j)+i)=*(*(x.A+j)+i); } } friend mat operator + (mat const &a,mat const &b) { mat c=a; for(int i=0;i<c.size;i++) { for(int j=0;j<c.size;j++) *(*(c.A+j)+i)=*(*(c.A+j)+i)+*(*(b.A+j)+i); } return c; } friend mat operator - (mat const &a,mat const &b) { mat c=a; for(int i=0;i<c.size;i++) { for(int j=0;j<c.size;j++) *(*(c.A+j)+i)=*(*(c.A+j)+i)-*(*(b.A+j)+i); } return c; } friend mat operator * (mat const &a,mat const &b) { mat c=a; for(int i=0;i<c.size;i++) { for(int j=0;j<c.size;j++) { comp x; for(int k=0;k<c.size;k++) x=x+(*(*(a.A+k)+i))*(*(*(b.A+j)+k)); *(*(c.A+j)+i)=x; } } return c; } friend void operator ++ (mat &a) { for(int i=0;i<a.size;i++) { for(int j=0;j<a.size;j++) { ++(*(*(a.A+j)+i)); } } } friend void operator -- (mat &a) { for(int i=0;i<a.size;i++) { for(int j=0;j<a.size;j++) { --(*(*(a.A+j)+i)); } } } friend mat operator - (mat const &a) { mat c=a; for(int i=0;i<a.size;i++) { for(int j=0;j<a.size;j++) { *(*(c.A+j)+i)=-(*(*(a.A+j)+i)); } } return c; } friend mat operator ~ (mat const &a) { mat c=a; for(int i=0;i<a.size;i++) { for(int j=0;j<a.size;j++) { *(*(c.A+i)+j)=(*(*(a.A+j)+i)); } } return c; } void dikha() { cout<<"Size : "<<size<<"\n"; for(int i=0;i<size;i++) { for(int j=0;j<size;j++) { (*(*(A+j)+i)).dikhao(); cout<<" "; } cout<<"\n"; } } }; int main() { mat a(2),b(2); mat c=a+b; a.dikha(); cout<<"\n\n"; b.dikha(); cout<<"\n\n"; c.dikha(); cout<<"\n\n"; c=a-b; c.dikha(); cout<<"\n\n"; c=a*b; c.dikha(); cout<<"\n\n"; ++c; c.dikha(); cout<<"\n\n"; --c; c.dikha(); cout<<"\n\n"; c=-c; c.dikha(); cout<<"\n\n"; c=~c; c.dikha(); cout<<"\n\n"; }
true
00e4388511477ce29ffd80969f5e91e3a26fd340
C++
chicolismo/Cesar
/program_table.cpp
UTF-8
2,243
2.84375
3
[]
no_license
#include "program_table.h" ProgramTable::ProgramTable(wxWindow *parent, wxWindowID id) : wxListCtrl(parent, id, wxDefaultPosition, wxSize(380, 500), wxLC_REPORT | wxLC_VIRTUAL | wxLC_HRULES | wxLC_VRULES) { show_decimal = false; #ifdef _WIN32 long list_style = wxLIST_FORMAT_LEFT; int font_size = 10; #else long list_style = wxLIST_FORMAT_RIGHT; int font_size = 12; #endif SetBackgroundColour(wxColour("#ffffff")); SetFont(wxFont(font_size, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, 0, wxT(""))); InsertColumn(0, wxT("PC"), list_style, wxLIST_AUTOSIZE); InsertColumn(1, wxT("Endereço"), list_style, wxLIST_AUTOSIZE); InsertColumn(2, wxT("Valor"), list_style, wxLIST_AUTOSIZE); InsertColumn(3, wxT("Mnemônico"), wxLIST_FORMAT_LEFT, wxLIST_AUTOSIZE); // Remove a barra de rolagem horizontal SetScrollbar(wxHORIZONTAL, 0, 0, 0, true); SetItemCount(0); ResizeCols(); } wxString ProgramTable::OnGetItemText(long item, long col) const { wxString buffer; switch (col) { case 0: buffer.Printf(" "); break; case 1: buffer.Printf("%ld", item); break; case 2: if (show_decimal) { buffer.Printf("%d", 0xFF & data[item]); } else { buffer.Printf("%02x", 0xFF & data[item]); } break; case 3: buffer.Printf(" Não implementado"); break; } return buffer; } Byte *ProgramTable::GetData() { return data; } void ProgramTable::SetData(Byte *data, size_t size) { this->data = data; this->size = size; SetItemCount(size); RefreshItems(0, size - 1); } void ProgramTable::SetItem(long item, long col, Byte value) { data[item] = value; RefreshItem(item); } void ProgramTable::Refresh() { RefreshItems(0, size - 1); } void ProgramTable::ResizeCols() { int scrollbar_width = 10; double q = (static_cast<double>(GetSize().GetWidth()) - 20.0) / 4 - scrollbar_width; SetColumnWidth(0, 20); SetColumnWidth(3, std::ceil(q)); SetColumnWidth(3, std::ceil(q)); SetColumnWidth(3, std::ceil(2 * q)); SetScrollbar(wxHORIZONTAL, 0, 0, 0, true); }
true
5b55b7c509d4c2bb9c9794354231bb83f0ccd7a9
C++
ashishnegi/Process-Scheduling-Algo-Implemented
/memory/Memory.cpp
UTF-8
1,240
2.6875
3
[]
no_license
#ifndef MEMORY_H #define MEMORY_H class Memory; #include "FindEmptyAlgo.cpp" #include "Process.cpp" #include <list> #include <vector> using namespace std; class Memory { FindEmptyAlgo * findAlgo; list<Process> procList; list<int> startPos; list<int> endPos; int totalSize; int nProcess; public: Memory( FindEmptyAlgo *f, int t): findAlgo(f), totalSize(t){ f->setMemory(this); } virtual void insert(Process) = 0; virtual void deleteP(int pid){ int i=0; list<Process> :: iterator pit; pit = procList.begin(); int nProcess = procList.size(); list<int> :: iterator sit = startPos.begin(); list<int> :: iterator eit = endPos.begin(); for( i=0; i<nProcess; ++i, ++pit, ++sit){ if( pit->getPid() == pid){ procList.erase(pit); startPos.erase(sit); endPos.erase(eit); break; } } } virtual void display() = 0; list<int> getStartPos(){ return startPos; } list<Process> getProcList(){ return procList; } }; #endif
true
7176652fe5a86d247bc5cb1dfa5ee89e1bedb6fc
C++
Armandur/Hnefatafl
/Hnefatafl/BoardEntity.hpp
UTF-8
1,103
3.46875
3
[]
no_license
/*! * \file BoardEntity.hpp * * \author Rasmus Pettersson Vik * \date juni 2013 * * Declaration of the abstract baseclass BoardEntity */ #ifndef BOARDENTITY_H #define BOARDENTITY_H #include <SFML/System.hpp> /*! * \class BoardEntity * * \brief Abstract baseclass for an entity with a position on the gameboard. * \author Rasmus Pettersson Vik * \date juni 2013 */ class BoardEntity { public: /*! * \brief Default BoardEntity Constructor * Runs _init() and initialises _position to (-1, -1) */ BoardEntity(void); //! Virtual BoardEntity destructor virtual ~BoardEntity(void); /*! * \brief Sets the position of the BoardEntity * \param[in] pos The position to set. */ void position(const sf::Vector2<int>& pos); /*! * \brief Gets the position of the BoardEntity * \return Gets the position of the BoardEntity. */ const sf::Vector2<int>& position() const; protected: /*! Initializing function * \note Should be run in every constructor! */ virtual void _init() =0; //! Holds the current position of the BoardEntity sf::Vector2<int> _position; }; #endif
true
cd10345a9a0d3713a193aed007318fc65b70a4ff
C++
mike-tr/CommunicationsFinal
/src/NodeRelay.cpp
UTF-8
5,687
2.78125
3
[ "MIT" ]
permissive
#include "headers/Utilities.hpp" #include <iostream> #include <string> #include <unistd.h> #include "headers/Node.hpp" using namespace std; using namespace Utilities; void Node::send_message(vector<string> userinput) { // here we handle sending message // in general we break it into send directly or send via relay. if (userinput.size() < 4) { ulog << "Nack : invalid arguments" << endl; plog << "Nack" << endl; } int len = std::atoi(&userinput[2][0]); string message = userinput[3]; for (uint i = 4; i < userinput.size(); i++) { message += "," + userinput[i]; } int target_id = std::atoi(&userinput[1][0]); if (target_id == this->node_id) { plog << "\nAck, message from my self :" << endl; plog << message << endl; return; } if (this->socketToNodeData.size() == 0) { ulog << "Nack : No connections!" << endl; plog << "Nack" << endl; return; } // BUILD MESSAGE NodeMessage nm; nm.source_id = this->node_id; nm.destination_id = target_id; nm.function_id = net_fid::send; nm.msg_id = this->createUniqueMsgID(); *(int *)nm.payload = len; nm.setPayload(message, 4); // SEND TRAILING MESSAGE int other_sock = idToSocket[target_id]; if (other_sock == 0) { // send via relay idToSocket.erase(target_id); this->send_relay(nm); return; } this->send_netm(other_sock, nm); } void Node::send_relay(const NodeMessage &send_message) { // if we need to send via relay // we first calculate the raute then send via that raute // if said raute doesnt exist we conclude the given node id is invalid ( no such node ) int target_id = send_message.destination_id; this->find_route_user(target_id); const auto route = this->routes[target_id]; if (route.status == discover_status::empty) { ulog << "Nack : target node is not connected to the network" << endl; plog << "Nack" << endl; return; } // here we send all messages one after another. NodeMessage relay_message; relay_message.source_id = this->node_id; relay_message.function_id = net_fid::relay; int sock = this->idToSocket[route.path[0]]; int size = route.path.size() - 1; for (int i = 0; i < size; i++) { relay_message.trailing_msg = size - i; relay_message.destination_id = route.path[i]; relay_message.msg_id = this->createUniqueMsgID(); *(int *)relay_message.payload = route.path[i + 1]; *((int *)relay_message.payload + 1) = size - 1; if (i == 0) { this->add_funcID_by_MessageID(relay_message); this->msgIdToRelayTarget[relay_message.msg_id] = target_id; } ulog << "send ::\n" << relay_message << endl; send(sock, &relay_message, sizeof(relay_message), 0); } ulog << "send ::\n" << send_message << endl; send(sock, &send_message, sizeof(send_message), 0); //cout << "send all to " << sock << " , id : " << route //cout << "sent all relay messages waiting for response..." << endl; } void Node::handle_relay(int sock, const NodeMessage &incoming_message) { // this method gets non reference because it uses buff with might change incoming_message indirectly. // opsy. uint num_trailing = incoming_message.trailing_msg; int next = *(int *)incoming_message.payload; int next_sock = this->idToSocket[next]; slog << "got trailing message, cupturing the next " << num_trailing << " messages..." << endl; slog << "messages are from " << this->socketToNodeData[sock].node_id << endl; this->coutLog(slog); // for simlicity when i get route message i wait for all the messages at once // sure that needs to have timeout but i was short on time here // i.e i assume that nodes are not going to "trick" me into a relay. // that assumption is not that good. map<int, NodeMessage> relays; while (relays.size() < num_trailing) { // cupture all trailing messages then resend them. memset(this->buff_server, 0, this->buff_size); this->msg_size = read(sock, buff_server, buff_size); if (this->msg_size == 0) { slog << "disconnected..." << endl; this->remove_sock(sock); return; } auto msg = *(NodeMessage *)this->buff_server; relays[num_trailing - msg.trailing_msg - 1] = msg; } // we check with is the target we wish to send the other messages too // if we are not connected to the next node // we conclude that the route was wrong anyway we return NACK if (next_sock == 0) { slog << "cant relay messages as this node is not connected to target..." << endl; this->idToSocket.erase(next); this->send_nack(sock, incoming_message); return; } // otherwise send all messages as they are to the next target // notice that we "save" the data of the message, so we can then send ack back to the sender // when we recive the ack or nack. slog << "cuptured all messages, sending them to the next node." << endl; for (uint i = 0; i < num_trailing; i++) { if (i == 0) { //incoming_message.function_id = net_fid::relay; auto &cup = this->add_funcID_by_MessageID(relays[i]); cup.prev = new message_id_saver{}; cup.prev->dest_id = this->socketToNodeData[sock].node_id; cup.prev->save_data = incoming_message.msg_id; cup.save_data = net_fid::relay; } send(next_sock, &relays[i], sizeof(relays[i]), 0); } }
true
cf5b02d13fe29f7dbd1ee983e8561781b8b767a6
C++
SamuelWeiss/150IDS-RPC
/RPC.samples/simplefunction.stub.cpp
UTF-8
1,848
2.609375
3
[]
no_license
#include "simplefunction.idl" #include "rpcstubhelper.h" #include "data_packing.h" #include <cstdio> #include <cstring> #include "c150debug.h" using namespace C150NETWORK; void __func3(){ func3(); string output = "Done"; RPCSTUBSOCKET->write(output.c_str(), output.length()+1); } void __func2(){ func2(); string output = "Done"; RPCSTUBSOCKET->write(output.c_str(), output.length()+1); } void __cur_time(){ string output = serialize_int(cur_time()); RPCSTUBSOCKET->write(output.c_str(), output.length()+1); } void __func1(){ func1(); string output = "Done"; RPCSTUBSOCKET->write(output.c_str(), output.length()+1); } string read_stream_to_string(){ string output; char buffer[2]; ssize_t readlen; do{ readlen = readlen = RPCSTUBSOCKET-> read(buffer, 1); output += buffer[0]; }while(readlen > 0); return output; } string get_name_from_message(string message){ if(message.at(0) != '{'){ cerr << "I unno, raise an error or soemthing"<< endl; exit(1); } for(int i = 1; i < message.length(); i++){ if(message.at(i) == '-'){ return message.substr(1, i - 1); } } } string get_arguments_from_message(string message){ if(message.at(0) != '{'){ cerr << "I unno, raise an error or soemthing"<< endl; exit(1); } for(int i = 1; i < message.length(); i++){ if(message.at(i) == '-'){ return message.substr(i+1, message.length() - (i+2)); } } } void dispatchFunction() { string message = read_stream_to_string(); string name = get_name_from_message(message); string args = get_arguments_from_message(message); if(strcmp( name, "func3") == 0){ __func3(args); } else if(strcmp( name, "func2") == 0){ __func2(args); } else if(strcmp( name, "cur_time") == 0){ __cur_time(args); } else if(strcmp( name, "func1") == 0){ __func1(args); } }
true
b784a3548a8cd08fb7d3038d4b40758134a406b8
C++
Lososin/OGLEngine
/include/CameraManager.hpp
UTF-8
764
3
3
[]
no_license
#pragma once #include <vector> #include "Camera.hpp" class CameraManager { public: unsigned long CreateCamera() { Cameras.push_back(new Camera()); return Cameras.size(); } void NextCamera() { CurrentCameraIndex++; if (CurrentCameraIndex == Cameras.size()) { CurrentCameraIndex = 0; } } Camera* GetCurrentCamera() { return Cameras[CurrentCameraIndex]; } static CameraManager* Get() { if(!ManagerInstance) ManagerInstance = new CameraManager(); return ManagerInstance; } std::vector<Camera*> Cameras; unsigned long CurrentCameraIndex = 0; static CameraManager* ManagerInstance; };
true
950f1489b3f2c9faed428b188f74550bcd1304bc
C++
Anthima/Hack-CP-DSA
/InterviewBit/Number of 1 bits/solution.cpp
UTF-8
180
2.5625
3
[ "MIT" ]
permissive
int Solution::numSetBits(unsigned int A) { int rem,count = 0; while(A) { A= A&(A-1); //this finds the next 1 position count++; } return count; }
true
a47b4949462d1d5730788bacf571089bdfb40256
C++
dotnfc/arducleo
/scripts/samples/ticker/ticker_main.cpp
UTF-8
529
2.75
3
[ "MIT" ]
permissive
// Basic example of how to blink a led using the Ticker object. // https://developer.mbed.org/teams/ST/code/Nucleo_ticker/ // // Assembled by dotnfc as Arducleo Sample // 2016/08/23 #include "mbed.h" Ticker toggle_led_ticker; DigitalOut led1(LED1); void toggle_led() { led1 = !led1; } int main() { // Init the ticker with the address of the function (toggle_led) to be attached and the interval (100 ms) toggle_led_ticker.attach(&toggle_led, 0.1); while (true) { // Do other things... } }
true
2d81a5123a1ce7a1d6f952e846b19e30ac1001c6
C++
chenx/oj
/leetcode/LongestPalindromicSubstring.cpp
UTF-8
5,000
3.265625
3
[]
no_license
// // http://www.leetcode.com/onlinejudge# // @Author: Xin Chen // @Created on: 12/20/2012 // @Last modified: 1/20/2013 // /* * Note: * 1) change string abc to #a#b#c#, at each position, search toward two sides. * 2) can't use: t += s[i] + "#"; * This is O(n^2). * For O(n) solution, see http://www.akalin.cx/longest-palindrome-linear-time */ #include <iostream> #include <string> using namespace std; // This works too. Clean. 2/4/2016. class Solution5 { public: string longestPalindrome(string s) { int n = s.length(), maxLen = 0, pos = -1; for (int i = 0; i < n; ++ i) { getMLen(s, i, i, maxLen, pos); if (i < n - 1 && s[i] == s[i+1]) { getMLen(s, i, i+1, maxLen, pos); } } return s.substr(pos, maxLen); } void getMLen(string s, int L, int R, int &maxLen, int &pos) { while (true) { if (L == 0 || R == s.length() - 1) break; if (s[L - 1] != s[R + 1]) break; -- L; ++ R; } int len = R - L + 1; if (maxLen < len) { maxLen = len; pos = L; } } }; // This works too. 11/18/2015 class Solution4 { public: string longestPalindrome(string s) { int n = s.length(), v; if (n <= 1) return s; L = R = maxLen = 0; for (int i = 0; i < n-1; ++ i) { getMaxLen(s, n, i, i); if (s[i] == s[i+1]) { getMaxLen(s, n, i, i + 1); } } return s.substr(L, R - L + 1); // note substring(start, end), end exclusive. } private: void getMaxLen(string s, int n, int a, int b) { int len = b - a + 1; for (-- a, ++ b; a >= 0 && b < n && s[a] == s[b]; -- a, ++ b) { len += 2; } if (len > maxLen) { L = a + 1; R = b - 1; maxLen = len; } } int L, R, maxLen; }; // This works too. Seems most clean. 11/7/2014 class Solution3 { public: string longestPalindrome(string s) { int len = s.length(); if (len == 0) return ""; int mlen = 1; // max palindrome length. int mL = 0; // start position (L) of max palindrome. for (int i = 0; i < len; ++ i) { check(s, i, i, mlen, mL); check(s, i, i+1, mlen, mL); } return s.substr(mL, mlen); } void check(string &s, int L, int R, int &mlen, int &mL) { while (L >= 0 && R < s.length() && s[L] == s[R]) { -- L; ++ R; } ++ L; -- R; if (R - L + 1 > mlen) { mlen = R - L + 1; mL = L; } } }; // This works too. class Solution2 { public: string longestPalindrome(string s) { int n = s.length(); if (n == 1) return s; int len, L0, maxlen = 0; for (int i = 0; i <= n-2; ++ i) { len = findP(s, i, i); if (len > maxlen) { maxlen = len, L0 = i - (len-1)/2; } if (s[i] == s[i+1]) { len = findP(s, i, i+1); if (len > maxlen) { maxlen = len, L0 = i - (len-2)/2; // Note: +1! } } } return s.substr(L0, maxlen); } // return length of palindrome, L/R is the range. int findP(string &s, int L, int R) { int n = R - L + 1, len = s.length() - 1; while (L > 0 && R < len) { if (s[-- L] != s[++ R]) break; n += 2; } return n; } }; class Solution { public: string longestPalindrome(string s) { if (s.length() == 0) return ""; string p = ""; string t = "#"; // assume # does not exist in s. int i, j; for (i = 0; i < s.length(); i ++) { t += s[i]; t += "#"; } int p_len = 0, p_pos; for (i = 1; i < t.length() - 1; i ++) { // search 2 sides from center t[i]. for (j = 1; i - j >= 0 && i + j <= t.length() - 1; j ++) { if (t[i - j] != t[i + j]) break; } // length of palingdrome: 2*(j-1) + 1 if (p_len < j - 1) { p_len = j - 1; p_pos = i; } } // Note: be care for of the offset here. if (p_pos % 2 == 1) p_pos = (p_pos - 1) / 2; else p_pos = (p_pos) / 2; p = s.substr(p_pos - p_len / 2, p_len); return p; } }; int main() { Solution s; string x = "bb"; cout << s.longestPalindrome(x) << endl; return 0; }
true
a2744935c11465e18d04020ea657580229b2d7fc
C++
Arturjssln/project_prog_wolf_sheep
/partie3/src/Random/Random.cpp
UTF-8
618
2.890625
3
[]
no_license
/* * prjsv 2015, 2016 * 2014, 2016 * Marco Antognini */ #include <Random/Random.hpp> bool bernoulli(double p) { std::bernoulli_distribution dist(p); return dist(getRandomGenerator()); } double normal(double mu, double sigma2) { std::normal_distribution<double> dist(mu, std::sqrt(sigma2)); return dist(getRandomGenerator()); } double exponential(double lambda) { std::exponential_distribution<double> dist(lambda); return dist(getRandomGenerator()); } double gamma(double alpha, double beta) { std::gamma_distribution<double> dist(alpha, beta); return dist(getRandomGenerator()); }
true
b10a7e1294316511bbb8dffef20bb52ed416757e
C++
bitlucky/cpp
/Array/11.cpp
UTF-8
839
3.96875
4
[]
no_license
Given an unsorted array arr[] and two numbers x and y, find the minimum distance between x and y in arr[]. Create a variable m = INT_MAX Run a nested loop, the outer loop runs from start to end (loop counter i), the inner loop runs from i+1 to end (loop counter j). If the ith element is x and jth element is y or vice versa, update m as m = min(m,j-i) Print the value of m as minimum distance int minDist(int arr[], int n, int x, int y) { int i, j; int min_dist = INT_MAX; for (i = 0; i < n; i++) { for (j = i+1; j < n; j++) { if( (x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && min_dist > abs(i-j)) { min_dist = abs(i-j); } } } return min_dist; }
true
29b142bf85e650c045cdf3336ca549abe7ee34d4
C++
alela/bombertux
/bonus.cpp
UTF-8
893
2.921875
3
[]
no_license
#include "bonus.h" #include <vector> #include <string> #include <random> #include <ctime> Bonus::Bonus(int _x, int _y, int _tile):x(_x), y(_y), tile(_tile){ choose_bonus_type(); init(); } void Bonus::choose_bonus_type(){ std::default_random_engine generator; std::uniform_int_distribution<int> distribution(-5,1); generator.seed(std::clock()); type = distribution(generator); } void Bonus::init(){ if(type <= -1) return ; std::vector<std::string> images{"resources/bomb2.png", "resources/fire3.png"}; texture.loadFromFile(images[type], sf::IntRect(0, 0, 32, 32)); sprite.setTexture(texture); sprite.setPosition(x,y); } void Bonus::set_bonus(std::shared_ptr<Player> player){ typedef void (Player::*fun)(); std::vector<fun>bonuses {&Player::increment_bomb_ammo, &Player::increment_bomb_range}; ((*player).*bonuses[type])(); }
true
9be53eef5ea56fea590f6be130ae6fbc903c9fd4
C++
Amazing168/My-free-code-repo
/clo_code/test/test.cpp
UTF-8
716
2.71875
3
[]
no_license
#include <iostream> using namespace std; int main() { int a[100][100]={0}, n, i, j, r, c, rows=0, columns=0; cin >> n; for (i=1; i<=n; i++) for (j=1; j<=n; j++){ cin >> a[i][j]; a[0][j] = (a[0][j]+a[i][j])%2; a[i][0] = (a[i][0]+a[i][j])%2; } for (i=1; i<=n; i++){ if (a[i][0] > 0){ r = i; rows++; } } for (j=1; j<=n; j++){ if (a[0][j] > 0){ c = j; columns++; } } if (rows==0 && columns==0) cout << "OK" << endl; else if (rows==1 && columns==1) cout << r << " " << c << endl; else cout << "Corrupt" << endl; return 0; } // t=pow(10,d);
true
e2497db229dbd416a1b868770fcb777e779c4bc4
C++
Lang4/LDBase
/LDBase.h
GB18030
6,432
3.015625
3
[]
no_license
#pragma once /** * ݳ־û Author jijinlong * email jjl_2009_hi@163.com */ #include <stdio.h> #include <string.h> #define IDLES_BLOCK_SIZE 1024 #pragma pack(1) /** * ƫֵ */ class LDPos{ public: unsigned long value; // ļеλ void *pointer; // ڴ LDPos(unsigned long value) { this->value = value; pointer = NULL; } LDPos() { memset(this,0,sizeof(*this)); } LDPos & operator=(const LDPos &pos) { this->value = pos.value; this->pointer = pos.pointer; return *this; } }; /** * С **/ class LDSmallBlock{ public: enum{ STREAM = 0, BASE = 1, }; short index; // void* value; // ֵ short tag; // ֵ LDSmallBlock() { memset(this,0,sizeof(*this)); } template<typename object> void write(object& o) { value = (void*)o; } unsigned long getValue() { return (unsigned long) value; } unsigned long getNowPos() { return index * sizeof(LDSmallBlock); } bool equal(const LDSmallBlock &block) { if (index == block.index && value == block.value && tag == block.tag) return true; return false; } }; /** * */ class LDBigBlock{ public: LDPos pre; // ǰһ unsigned long endSmallPos; // ǰβ unsigned long offset; // ƫ unsigned long index; // ǰ LDSmallBlock blocks[1024]; // ÿ1024 С LDPos next; // һ char idleSpace[2]; // бʾ LDBigBlock() { memset(this,0,sizeof(*this)); offset = 0; } /** * ȡС */ LDSmallBlock * getSmallBlock(unsigned long tag) { if (checkTag(tag)) { return & blocks[tag - offset]; } return NULL; } /** * 鵱ǰTag ֵ */ bool checkTag(unsigned long tag) { if (tag >= offset && tag < offset + 1024) { return true; } return false; } template<typename object> void write(object& o,unsigned long tag) { LDSmallBlock *b = getSmallBlock(tag); if (b) { b->write(o); b->index = tag % IDLES_BLOCK_SIZE; b->tag = LDSmallBlock::BASE; } } unsigned long getNowPos(); }; /** * дʾ **/ class LDBigIdlesBlock{ public: char value[IDLES_BLOCK_SIZE]; // ʾĿϢ 1λӦһ һʾ ֻ 1024 * 8 Ĵ LDPos next; // һʾ LDPos pre; // һʾ LDPos now;// ǰλ char hadIdle; // Ƿп LDBigIdlesBlock() { memset(this,0,sizeof(*this)); } unsigned long getNowPos(); }; /** * ǰд¼ **/ class LDBWriteSingal{ public: LDBWriteSingal(){ tag = 0; } LDPos bigBlock; // ǰϢ LDPos oldBigBlock; // һεĴ LDSmallBlock oldSmallBlock; // µС鱸 int tag; // ǰʾ ~LDBWriteSingal(){} enum{ WRITE = 0, WRITE_IDLE = 1, WRITE_BIG = 2, WRITE_SMALL = 3, }; void start(int w) { tag |= 1 << w; } void close(int w) { tag &= ~(1 << w); } void clear() { tag = 0; } bool isDirty() { return tag != 0; } }; struct LDBHead{ char tag[2]; // ʾ LDBigIdlesBlock idleBlockHead; // ʼ LDBigBlock bigBlock; // ʼ LDBWriteSingal signal; // дϢ char version[4]; // "ldb1" LDBHead() { reset(); } void reset() { clear(); tag[0] = 'L'; tag[1] = 'D'; version[0] = 'L'; version[1] = 'D'; version[2] = 'B'; version[3] = '1'; } void clear() { memset(this,0,sizeof(*this)); } unsigned long getWriteSignalPos() { return sizeof(tag) + sizeof(idleBlockHead) + sizeof(bigBlock); } void clearSingal() { memset(&signal,0,sizeof(signal)); } }; #pragma pack() /** * ļ ȷд */ class LDBFile{ public: LDBFile(const char *fileName); /** * ʽ */ bool format(); /** * Ƿݿļ */ bool isDB(); /** * ͷ */ void readHead(); /** * ļ */ bool open(bool withFormat = false); /** * дļ */ bool writeBlock(void *content,unsigned int len); /** * ȡļ */ bool readBlock(void *content,unsigned int len); /** * ƶij */ void moveTo(const unsigned long &pos); ~LDBFile(); /** * DB ͷ */ LDBHead head; /** * ȡλ */ LDPos getIdlePos(); /** * ÿλ */ void resetIdle(unsigned long index); /** * ȡλ */ char* getIdleChar(unsigned long index); /** * ÿλ */ void setIdle(unsigned long index); /** * һλ */ LDBigIdlesBlock * newNextIdleBlock(LDBigIdlesBlock *nowBlock); /** * дź */ void updateWirteSignal(); /** * д */ void writeIdles(); private: FILE *handle; }; /** * ļ * 顢տ */ class LDBStream{ public: LDBStream() { _file = NULL; head = NULL; } LDBStream(const char *fileName) { _file = new LDBFile(fileName); } LDBStream(LDBStream &stream) { } /** * ļ */ bool open(bool withFormat = false) { if (!_file) return false; if (_file->open(withFormat)) { head = &_file->head.bigBlock; return true; } return false; } /** * д */ template<typename type> void write_base(type a,unsigned long tag) { LDBigBlock *nowBlock = head; LDBigBlock *pre = head; // ȡӿ while (nowBlock && !nowBlock->checkTag(tag)) { pre = nowBlock; nowBlock = getNext(nowBlock); } if (!nowBlock) { nowBlock = newNextBlock(pre); nowBlock->offset = tag / IDLES_BLOCK_SIZE; } if (nowBlock) { nowBlock->write(a,tag); } } /** * д */ template<typename object> void write(object& o,unsigned long tag) { LDBStream ss; ss.head = newNextBlock(head); ss.setTag(OUT); ss & a; write(ss,tag); } /** * д **/ void write(LDBStream& ss,unsigned long tag); /** * ݵǰȡһ * ڴУڴǷļ,ļλ */ LDBigBlock * getNext(LDBigBlock * block); /** * һ */ LDBigBlock * newNextBlock(LDBigBlock *nowBlock); LDBigBlock *head; // ǰͷ /** * Ϊtag */ void save(int tag); /** * д * */ void writeBigBlock(LDBigBlock *block); /** * дС */ void writeSmallBlock(LDSmallBlock *small,const unsigned long &dest); private: LDBFile *_file; };
true
90fdacc79f4ad7ae1320e340381b1fc1ad791d72
C++
moevm/oop
/8381/Pochaev_Nikita/code/Units/CompositeUnit.cpp
UTF-8
4,474
2.921875
3
[]
no_license
#include <iostream> #include "CompositeUnit.h" #include "AuxiliaryFunctionality/TextColoring.h" size_t CompositeUnit::getHealth() const { size_t total = 0; for(const auto & unit : units) { total += unit->getMeleeAttackStrength(); } return total; } size_t CompositeUnit::getArmor() const { size_t total = 0; for(const auto & unit : units) { total += unit->getArmor(); } return total; } size_t CompositeUnit::getMeleeAttackStrength() const { size_t total = 0; for(const auto & unit : units) { total += unit->getMeleeAttackStrength(); } return total; } void CompositeUnit::describeYourself() { std::cout << ANSIColor::coloredString("I'm composite unit!", ANSIColor::FG_GREEN) << std::endl; std::cout << "Position: X = " << position.x << "; Y = " << position.y << std::endl; std::cout << "Includes:" << std::endl << std::endl; for(auto const& instance : units) { instance->describeYourself(); } } std::string CompositeUnit::getUnitInf() { std::string result; result = "I'm composite unit!\nPosition: X = " + std::to_string(position.x) + "; Y = " + std::to_string(position.y) + "\nIncludes:\n"; for(auto const& instance : units) { result += instance->getUnitInf(); } return result; } void CompositeUnit::reallocation(size_t new_x, size_t new_y) { Unit::reallocation(new_x, new_y); for(const auto &curr : units) { curr->reallocation(new_x, new_y); } } CompositeUnit *CompositeUnit::isComposite() { return this; } Unit *CompositeUnit::clone() const { return new CompositeUnit(*this); } void CompositeUnit::addUnit(std::shared_ptr<Unit> unit) { units.push_back(unit); } size_t CompositeUnit::getUnitQuantity() const { return units.size(); } void CompositeUnit::initCurrPar() { health = getHealth(); armor = getArmor(); meleeAttackStrength = getMeleeAttackStrength(); movementRange = COMPOSITE_UNIT_MOVEMENT_RANGE; actionTokens = COMPOSITE_UNIT_ACTION_TOKENS; } std::map<eUnitsType, size_t> CompositeUnit::getComposition() { std::map<eUnitsType, size_t> result; for (const auto& curr : units) { if(result.find(curr->getType()) != result.end()) { result[curr->getType()]++; } else { result.insert(std::pair<eUnitsType, size_t>(curr->getType(), 1)); } } return result; } eUnitsType CompositeUnit::getType() { return eUnitsType::COMPOSITE_UNIT; } /** * If members of composite unit have enough armor - it's okey, * they take it and go next without loosing a health * (damage is distributed to all). * * If it's not: count death factor - if it's < then affordable * health -> take damage for all armor and health (make it == 1). * Other possible cure in army ;) * * If > -> unit die. * @param damageSize */ void CompositeUnit::takeDamage(size_t damageSize) { if(getArmor() >= damageSize) { size_t i = 0; while(damageSize > 0) { if(units[i]->getArmor() > 0) { units[i]->takeDamage(1); damageSize--; } i++; if(i + 1 == units.size()) i = 0; } return; } else { damageSize -= getArmor(); if(damageSize > static_cast<size_t >(COMPOSITE_UNIT_DEATH_FACTOR * damageSize)) { notifyObserversAboutDeath(); } else { size_t i = 0; while(damageSize > 0) { if(units[i]->getHealth() > 1) { units[i]->takeDamage(1); damageSize--; } else { if(i + 1 == units.size()) break; } i++; if(i + 1 == units.size()) i = 0; } } } } void CompositeUnit::setMeleeAttackBoost(size_t boost) { size_t i = 0; for( ; boost > 0; i++) { units[i]->setMeleeAttackBoost(1); boost--; if(i + 1 == boost) i = 0; } } void CompositeUnit::setArmorBoost(size_t boost) { size_t i = 0; for( ; boost > 0; i++) { units[i]->setArmorBoost(1); boost--; if(i + 1 == boost) i = 0; } }
true
a7e7bd6083a441961da552494ad2b51856e14e3a
C++
Qazwar/MemoryHandler
/MemoryHandler/src/MemoryHandler.cpp
WINDOWS-1252
2,859
2.65625
3
[ "MIT" ]
permissive
/*******************************************************************/ /* Original File Name: MemoryHandler.cpp */ /* Date: 07-07-2018 */ /* Developer: Dionysus Benstein */ /* Copyright 2018 Dionysus Benstein. All rights reserved. */ /* Description: A class implementation represents the basic functional. /*******************************************************************/ #include "MemoryHandler.h" MemoryHandler::MemoryHandler(char* procName, size_t bufferSize) : procID(NULL), bufferSize(bufferSize) { int len = strlen(procName) + 1; this->procName = new char[len]; strcpy_s(this->procName, len, procName); this->buffer = new byte[bufferSize]; } MemoryHandler::~MemoryHandler() { delete[] this->procName; delete[] this->buffer; } void MemoryHandler::fingProcID() { HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); PROCESSENTRY32 procInfo; //Structure that stores data about process procInfo.dwSize = sizeof(PROCESSENTRY32); if (Process32First(snapshot, &procInfo)) { while (Process32Next(snapshot, &procInfo)) { if (_stricmp(this->procName, procInfo.szExeFile) == 0) { this->procID = procInfo.th32ProcessID; CloseHandle(snapshot); return; } } } else { CloseHandle(snapshot); this->procID = NULL; return; } } void MemoryHandler::open(DWORD accessRights) { fingProcID(); this->hProc = OpenProcess(accessRights, false, this->procID); } void MemoryHandler::close() { CloseHandle(this->hProc); } void MemoryHandler::write(void* ptr, DWORD to, size_t size) { WriteProcessMemory(hProc, (LPVOID)to, ptr, size, NULL); } void MemoryHandler::write(void* ptr, DWORD to, size_t size, DWORD memProtect) { DWORD oldMemProtect = NULL; VirtualProtectEx(hProc, (LPVOID)to, size, memProtect, &oldMemProtect); //need check on size WriteProcessMemory(hProc, (LPVOID)to, ptr, size, NULL); VirtualProtectEx(hProc, (LPVOID)to, size, oldMemProtect, &oldMemProtect); } MemoryHandler& MemoryHandler::read(DWORD from, size_t size) { memset(this->buffer, 0, this->bufferSize); ReadProcessMemory(hProc, (LPVOID)from, buffer, size, NULL); return *this; } MemoryHandler& MemoryHandler::read(DWORD from, size_t size, DWORD memProtect) { DWORD oldMemProtect = NULL; memset(this->buffer, 0, this->bufferSize); VirtualProtectEx(hProc, (LPVOID)from, size, memProtect, &oldMemProtect); //need check on size ReadProcessMemory(hProc, (LPVOID)from, buffer, size, NULL); VirtualProtectEx(hProc, (LPVOID)from, size, oldMemProtect, &oldMemProtect); return *this; } char* MemoryHandler::toStringA() { return (char*)buffer; } wchar_t* MemoryHandler::toStringU() { return (wchar_t*)buffer; } DWORD MemoryHandler::getProcID() { return this->procID; }
true
5333580444153f52ee02e6ae5f00fb0705555347
C++
Batyan/Eliminator
/iteration 2/Prototype/gestionMap/personnage.h
UTF-8
690
2.78125
3
[]
no_license
#ifndef PERSONNAGE_H #define PERSONNAGE_H #include "elementmap.h" class personnage : public elementMap { public: personnage(personnage const& cp); personnage(int x, int y,int type,int vie); personnage(); // info sur l'objet QString print(); // serial de l'objet QVariant serial(); public: int m_vie; }; Q_DECLARE_METATYPE(personnage); /* on redéfinit les operateurs de flux pour l'object QDataStream * cela nous permet de sotcker et recuperer les objets serialisés dans un fihier */ QDataStream & operator << (QDataStream & out, const personnage & Valeur); QDataStream & operator >> (QDataStream & in, personnage & Valeur); #endif // PERSONNAGE_H
true
7e637071a5b77db2d97ec40784737246fc62d1a9
C++
jhpy1024/Mazel
/Source/Game.cpp
UTF-8
5,116
2.703125
3
[ "MIT" ]
permissive
#include "Game.hpp" #include <iostream> #include <memory> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "Utils.hpp" #include "Shader.hpp" #include "MenuState.hpp" #include "PlayState.hpp" #include "WinGameState.hpp" #include "FinishLevelState.hpp" #include <GL/freeglut.h> Game::Game(int width, int height) : m_Width(width) , m_Height(height) , m_CurrentMap(1) , m_NumMaps(3) , m_TestMap("Maps/map" + util::toString(m_CurrentMap) + ".txt", this) , m_PlayerStartPosition(32.f * 1.5f) , m_PlayerSize(32.f) { } void Game::init() { loadShaders(); setupMatrices(); m_TestMap.init(); createTestEntity(m_PlayerStartPosition, m_PlayerSize); m_CurrentState = std::make_shared<MenuState>(this); } void Game::createTestEntity(glm::vec2 position, glm::vec2 size) { auto testEntity = std::make_shared<TestEntity>(this, position, size); testEntity->init(); m_EntitiesToAdd.push_back(testEntity); m_TestEntity = testEntity; } void Game::createProjectile(glm::vec2 position, glm::vec2 size, float angle) { auto projectile = std::make_shared<Projectile>(this, position, size, angle); projectile->init(); m_EntitiesToAdd.push_back(projectile); m_Projectiles.push_back(projectile); } void Game::startPlaying() { changeState(std::make_shared<PlayState>(this)); } void Game::restartGame() { resetEntities(); m_CurrentMap = 0; changeMapToNextLevel(); startPlaying(); } void Game::quit() { glutLeaveMainLoop(); } void Game::finishedLevel() { if (m_CurrentMap == m_NumMaps) changeState(std::make_shared<WinGameState>(this)); else changeState(std::make_shared<FinishLevelState>(this)); } void Game::nextLevel() { resetEntities(); changeMapToNextLevel(); changeState(std::make_shared<PlayState>(this)); } void Game::changeMapToNextLevel() { ++m_CurrentMap; assert(m_CurrentMap <= m_NumMaps); m_TestMap = Map("Maps/map" + util::toString(m_CurrentMap) + ".txt", this); m_TestMap.init(); } void Game::resetEntities() { m_Entities.clear(); m_Projectiles.clear(); createTestEntity(m_PlayerStartPosition, m_PlayerSize); } void Game::loadShaders() { m_ShaderManager.addShader("Simple", std::make_shared<Shader>("Shaders/simple.vert", "Shaders/simple.frag")); m_ShaderManager.addShader("Texture", std::make_shared<Shader>("Shaders/texture.vert", "Shaders/texture.frag")); } void Game::setupMatrices() { m_ProjMatrix = glm::mat4 ( glm::vec4(2.f / m_Width, 0.f, 0.f, 0.f), glm::vec4(0, 2.f / m_Height, 0.f, 0.f), glm::vec4(0.f, 0.f, 0.f, 0.f), glm::vec4(-1.f, -1.f, 0.f, 1.f) ); m_ViewMatrix = glm::mat4(1.f); m_ModelMatrix = glm::mat4(1.f); m_MvpMatrix = m_ProjMatrix * m_ViewMatrix * m_ModelMatrix; } void Game::changeState(std::shared_ptr<GameState> state) { m_CurrentState = state; } void Game::keyPressed(unsigned char key, int x, int y) { m_CurrentState->keyPressed(key, x, y); } void Game::keyReleased(unsigned char key, int x, int y) { m_CurrentState->keyReleased(key, x, y); } void Game::mouseEvent(int button, int state, int x, int y) { m_CurrentState->mouseEvent(button, state, x, y); } void Game::specialKeyPressed(int key, int x, int y) { m_CurrentState->specialKeyPressed(key, x, y); } void Game::specialKeyReleased(int key, int x, int y) { m_CurrentState->specialKeyReleased(key, x, y); } void Game::update(int delta) { addNewEntities(); m_CurrentState->update(delta); passPlayerPosToShader(); } void Game::passPlayerPosToShader() { auto playerPos = m_TestEntity->getPosition(); m_ShaderManager.useShader("Simple"); auto posUniformLocation = m_ShaderManager.getShader("Simple")->getUniformLocation("in_PlayerPosition"); glUniform2fv(posUniformLocation, 1, glm::value_ptr(playerPos)); m_ViewMatrix = glm::translate(glm::mat4(1.f), glm::vec3(m_Width / 2.f - playerPos.x, m_Height / 2.f - playerPos.y, 0.f)); m_MvpMatrix = m_ProjMatrix * m_ViewMatrix * m_ModelMatrix; auto mvpLocation = m_ShaderManager.getShader("Simple")->getUniformLocation("in_MvpMatrix"); glUniformMatrix4fv(mvpLocation, 1, GL_FALSE, glm::value_ptr(m_MvpMatrix)); } void Game::addNewEntities() { for (auto newEntity : m_EntitiesToAdd) { m_Entities.push_back(newEntity); } m_EntitiesToAdd.clear(); } void Game::display() { m_CurrentState->display(); } void Game::resize(int width, int height) { m_Width = width; m_Height = height; } std::shared_ptr<TestEntity>& Game::getPlayer() { return m_TestEntity; } std::vector<std::shared_ptr<Entity>>& Game::getEntities() { return m_Entities; } std::vector<std::shared_ptr<Projectile>>& Game::getProjectiles() { return m_Projectiles; } glm::mat4 Game::getProjectionMatrix() const { return m_ProjMatrix; } glm::mat4 Game::getViewMatrix() const { return m_ViewMatrix; } Map& Game::getMap() { return m_TestMap; } ShaderManager& Game::getShaderManager() { return m_ShaderManager; }
true
3fd84aa318a5d4ae29487a1cd0b51ee1af178bb7
C++
OpenVE/scripts
/Cpp/BasicExamples/FILE21.cpp
UTF-8
1,971
4.125
4
[]
no_license
/* In the context of programming, polymorphism allows you to refer to objects of different classes by means of the same program item and to perform the same operation in different ways, depending on which object is being referred to. In C++, one way polymorphism is implemented is through the use of virtual functions. When virtual functions are used, the system makes the decision of which method to actually call based on which object the pointer is pointing to. The decision of which function to call is not made during the time when the code is compiled but when the code is executed. This is dynamic binding and can be very useful in some programming situations. In the program below we will see how virtual functions are used. We will use a protected data member in the base class and publicly derive two classes from the base class. The base class will have a virtual member function that is redefined in the derived classes. */ #include <iostream> using namespace std; class Person { protected: const char* name; public: Person(string n) { name=n.c_str(); } virtual void print() { cout << "My name is " << name << endl; } }; class Foreigner:public Person { public: Foreigner(string f):Person(f){} void print() { cout << "IL mio nome e " << name << endl; } }; class Alien:public Person { public: Alien(string s):Person(s){} void print() { cout << "##$&(<@$%@!#@$%~~***@## " << name << endl; cout << "Sorry, there is a communication problem" << endl; } }; int main() { Person* person1; person1 = new Person("Jack"); cout << "Introducing a Person: " << endl; person1->print(); Person* person2; person2 = new Foreigner("Maria"); cout << "Introducing a Foreigner: " << endl; person2->print(); person1 = new Foreigner("Al Pacino"); cout << "Reintroducing the Person: " << endl; person1->print(); Person* person3; person3 = new Alien("Martian"); cout << "Introducing the Alien: " << endl; person3->print(); return 0; }
true
8eb4c09faee7d8de2fa6674acc99a42ed0e771ff
C++
Gast91/Pacman
/src/Tile.h
UTF-8
1,047
2.984375
3
[ "MIT" ]
permissive
#pragma once #include "Config.h" class Level; struct Node { sf::Vector2i gridPosition; int f = 0, g = 0, h = 0; // score, cost, heuristic Node* parent = nullptr; Node() {} Node(const sf::Vector2i pos, Node* p = nullptr) : gridPosition(pos), parent(p) {} Node(const Node* other) : gridPosition(other->gridPosition), parent(other->parent), f(other->f), g(other->g), h(other->h) {} inline bool operator== (const Node& rhs) { return gridPosition.x == rhs.gridPosition.x && gridPosition.y == rhs.gridPosition.y; } }; class Tile : public sf::Drawable { private: friend Level; const TileType type; bool eaten = false; bool intersection = false; bool checked = false; Node node; const std::unique_ptr<sf::CircleShape> dotSprite; void reset(); public: Tile(sf::Vector2i gridCoords, sf::Vector2f pos, int type, Node* p = nullptr); bool hasADot() const; int getValue() const; void setEaten(); void draw(sf::RenderTarget &target, sf::RenderStates states) const; };
true
24499b87c0df1d4462e1b258fe63d804964a11e3
C++
TylerTheFox/CS260-Project-4
/CS260 Proj 4/vendor.cpp
UTF-8
3,304
3.375
3
[]
no_license
/* * File: vendor.cpp * Author: Brandan Tyler Lasley * * Created on November 15, 2014, 10:51 AM */ #include "vendor.hpp" vendor::vendor() { this->phone = NULL; this->name = NULL; this->event = NULL; this->product = NULL; } vendor::vendor(const vendor& obj) { this->phone = NULL; this->name = NULL; this->event = NULL; this->product = NULL; this->setEvent(obj.getEvent()); this->setName(obj.getName()); this->setPhone(obj.getPhone()); this->setProduct(obj.getProduct()); } vendor::~vendor() { if (this->event) { delete [] this->event; } if (this->name) { delete [] this->name; } if (this->product) { delete [] this->product; } if (this->phone) { delete [] this->phone; } this->phone = 0; } void vendor::setName(const char * _name) { if (this->name) { delete [] this->name; } if (_name) { this->name = new char[strlen(_name) + 1]; strcpy(this->name, _name); } else { throw std::invalid_argument("Name CANNOT be NULL"); // FATAL ERROR: We don't know what to do if this occurs!? We don't want to corrupt collection.cpp } } void vendor::setProduct(const char * _product) { if (this->product) { delete [] this->product; } if (_product) { this->product = new char[strlen(_product) + 1]; strcpy(this->product, _product); } else { throw std::invalid_argument("Product CANNOT be NULL"); // FATAL ERROR: We don't know what to do if this occurs!? We don't want to corrupt collection.cpp } } void vendor::setEvent(const char * _event) { if (this->event) { delete [] this->event; } if (_event) { this->event = new char[strlen(_event) + 1]; strcpy(this->event, _event); } else { this->event = NULL; } } void vendor::setPhone(const char * _phone) { if (this->phone) { delete [] this->phone; } if (_phone) { this->phone = new char[strlen(_phone) + 1]; strcpy(this->phone, _phone); } else { this->phone = NULL; } } char * vendor::getName() const { if (this->name) { return this->name; } return NULL; } char * vendor::getProduct() const { if (this->product) { return this->product; } return NULL; } char * vendor::getEvent() const { if (this->event) { return this->event; } return NULL; } char * vendor::getPhone() const { if (this->phone) { return this->phone; } return NULL; } bool vendor::operator==(const vendor& obj) const { if (strcmp(obj.getName(), this->name) == 0) { return true; } return false; } const vendor& vendor::operator=(const vendor& obj) { if (this == &obj) { return *this; } else { this->phone = NULL; this->name = NULL; this->event = NULL; this->product = NULL; this->setEvent(obj.getEvent()); this->setName(obj.getName()); this->setPhone(obj.getPhone()); this->setProduct(obj.getProduct()); return *this; } } bool vendor::operator<(const vendor& obj) const { if (strcmp(obj.getName(), this->name) < 0) { return true; } else { return false; } }
true
5b32eb000f24a96ac3d5c162650e51809ae28e03
C++
kvanderlaag/CSC_305_Ray_Tracer
/CSC_305_Ray_Tracer/Triangle.cpp
UTF-8
1,505
3.09375
3
[]
no_license
#include "Triangle.h" #include "Plane.h" #include "Lambertian.h" #include <cfloat> #include <cmath> #include <cstdio> /* Triangle.cpp Defines functionality for computing intersection between a ray and a triangle, and barycentric coordinates on that triangle. */ void Triangle::Barycentric(const Vector3& p, double &u, double &v, double &w) const { Vector3 vv0 = v2 - v1; Vector3 vv1 = v3 - v1; Vector3 vv2 = p - v1; double d00 = vv0.Dot(vv0); double d01 = vv0.Dot(vv1); double d11 = vv1.Dot(vv1); double d20 = vv2.Dot(vv0); double d21 = vv2.Dot(vv1); double invDenom = 1.0 / (d00 * d11 - d01 * d01); v = (d11 * d20 - d01 * d21) * invDenom; w = (d00 * d21 - d01 * d20) * invDenom; u = 1.0f - v - w; } Vector3 Triangle::Normal() const { return normal; return (v2 - v1).Cross(v3 - v1); } bool Triangle::Hit(const Ray& r, double t_min, double t_max, hit_record& hit) const { bool hit_triangle = false; if (r.direction.Dot(Normal()) > 0) { return hit_triangle; } hit_record temp_rec; if (p->Hit(r, t_min, t_max, temp_rec)) { Barycentric(temp_rec.point, temp_rec.barycentric.x, temp_rec.barycentric.y, temp_rec.barycentric.z); if (temp_rec.barycentric.x < 0.0f || temp_rec.barycentric.y < 0.0f || temp_rec.barycentric.z < 0.0f) { } else { hit = temp_rec; //hit.point = temp_rec.point; hit.normal = normal.Normalized(); //hit.t = temp_rec.t; //hit.barycentric = temp_rec.barycentric; hit.mat = mat; hit_triangle = true; } } return hit_triangle; }
true
3f72883b4987fd7cce302594e5403e89e69bc3dc
C++
MosheGroot/Fund_Algorithms_4sem
/lab01/headers/matrix_nn.hpp
UTF-8
1,809
2.859375
3
[]
no_license
#pragma once #include <iostream> #include <initializer_list> #include <exception> #include <algorithm> #include <memory> #include "tex_convertible.hpp" #define EPS 1e-6 class Matrix_NN : public TeX_convertible { private: std::vector<std::vector<double>> data; size_t N; void alloc_memory(size_t N); void free_memory(); void copy_memory(const std::vector<std::vector<double>> &src); void copy_value(double value); public: Matrix_NN() : N(0) {} Matrix_NN(size_t n, double value=0.); Matrix_NN(const Matrix_NN &copy); Matrix_NN(const std::initializer_list<double> &list); ~Matrix_NN(); Matrix_NN& operator=(const Matrix_NN &b); Matrix_NN& operator=(const std::initializer_list<double> &list); std::vector<double>& operator[](const size_t i); bool operator==(const Matrix_NN &b) const; bool operator!=(const Matrix_NN &b) const; Matrix_NN operator+(const Matrix_NN &b) const; Matrix_NN operator-(const Matrix_NN &b) const; Matrix_NN operator*(const Matrix_NN &b) const; Matrix_NN operator*(const double l) const; friend Matrix_NN operator*(const double l, const Matrix_NN& dt); Matrix_NN operator/(const double l) const; Matrix_NN& operator+=(const Matrix_NN &b); Matrix_NN& operator-=(const Matrix_NN &b); Matrix_NN& operator*=(const Matrix_NN &b); Matrix_NN& operator*=(const double l); Matrix_NN& operator/=(const double l); friend std::ostream& operator<<(std::ostream& os, const Matrix_NN& m); friend std::istream& operator>>(std::istream& is, Matrix_NN& m); friend double det(const Matrix_NN& m); friend Matrix_NN invert(const Matrix_NN &m); friend Matrix_NN transp(const Matrix_NN &m); friend double trace(const Matrix_NN &m); friend Matrix_NN exp(const Matrix_NN &m, size_t k); size_t size() const { return N; } std::string convert() const override; };
true
572bf88378132b0086a81459394246d3f8e94b1f
C++
kris-Git11/3TG
/Rekurzivne_funkcije_6_Ispisuje_broj_unatrag.cpp
UTF-8
278
2.71875
3
[]
no_license
#include <iostream> using namespace std; int BrojUnatrag ( int x ) { cout << x % 10; if ( x / 10 > 0 ) return BrojUnatrag ( x / 10 ); } int main() { int iBroj; cout << "Unesite broj: "; cin >> iBroj; BrojUnatrag ( iBroj ); }
true
14b9d7eab16308f4a42867b6c819d5bef9eab04e
C++
pr0g/cpp-sky-down-example
/drawing.hpp
UTF-8
613
2.640625
3
[ "Apache-2.0", "MIT" ]
permissive
#pragma once #include "polymorphic.hpp" #include <vector> struct Draw {}; using DrawSignature = void(Draw) const; struct Update {}; using UpdateSignature = void(Update); using Drawable = polymorphic::object<DrawSignature>; using DrawableRef = polymorphic::ref<DrawSignature>; using Updatable = polymorphic::object<UpdateSignature>; using UpdatableRef = polymorphic::ref<UpdateSignature>; void draw(DrawableRef drawable); void update(UpdatableRef updatable); template<typename T> void poly_extend(Draw, const T& t) { t.draw(); } template<typename T> void poly_extend(Update, T& t) { t.update(); }
true
2c988577613b2ea9462c18f32cbf48ab1351252d
C++
rezwanh001/LightOj-Solutions-in-Cpp
/1166 - Old Sorting/main.cpp
UTF-8
495
2.671875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int T; scanf("%d", &T); for(int cas = 1; cas <= T; cas++){ int n; scanf("%d", &n); vector <int> v(n); for(int i = 0; i < n; i++){ cin >> v[i]; } int cnt = 0; for(int i = 0; i < n; i++){ int j = i; while(j < n && v[j] != (i + 1)){ j++; } if(i != j){ swap(v[i], v[j]); cnt ++ ; } } printf("Case %d: %d\n", cas, cnt); v.clear(); } return 0; } /** 3 4 4 2 3 1 4 4 3 2 1 4 1 2 3 4 */
true
7de9dd331d655240540e21f449c01a3d98bd21e1
C++
seokwoongchoi/GameEngine
/Framework/BehaviorTree/BehaviorTree.h
GB18030
1,889
2.828125
3
[]
no_license
#pragma once #include<stack> #include "Behavior.h" //namespace BT enum class EActionMode { Attack, Patrol, Runaway, }; enum class EConditionMode { IsSeeEnemy, IsHealthLow, IsEnemyDead, }; class BehaviorTree { public: explicit BehaviorTree(Behavior* InRoot) :Root(InRoot) {} BehaviorTree(const BehaviorTree&) = delete; BehaviorTree& operator=(const BehaviorTree&) = delete; void SetActorData(const uint& index); inline void Tick(const uint& actorIndex) { Root->Tick(actorIndex); } bool HaveRoot() { return Root ? true : false; } void SetRoot(Behavior* InNode) { Root = InNode; } void Release() { Root->Release(); } public: inline void SetIsSeeEnemy(bool condition) { Root->SetIsSeeEnemy(condition); } inline void SetIsHealthLow(bool condition) { Root->SetIsHealthLow(condition); } inline void SetIsEnemyDead(bool condition) { Root->SetIsEnemyDead(condition); } private: Behavior* Root; }; //ΪһΪ,ͨǰʽBack()End()й class BehaviorTreeBuilder { public: BehaviorTreeBuilder() {} ~BehaviorTreeBuilder() { } BehaviorTreeBuilder* Sequence(); BehaviorTreeBuilder* Action(EActionMode ActionModes); BehaviorTreeBuilder* Condition(EConditionMode ConditionMode, bool IsNegation); BehaviorTreeBuilder* Selector(); BehaviorTreeBuilder* Repeat(int RepeatNum); BehaviorTreeBuilder* ActiveSelector(); BehaviorTreeBuilder* Filter(); BehaviorTreeBuilder* Parallel(EPolicy InSucess, EPolicy InFailure); BehaviorTreeBuilder* Monitor(EPolicy InSucess, EPolicy InFailure); BehaviorTreeBuilder* Back(); BehaviorTree* End(); private: void AddBehavior(Behavior* NewBehavior); private: Behavior* TreeRoot = nullptr; //ڴ洢ڵĶջ std::stack<Behavior*> NodeStack; };
true
1f38155aa52b986f0d9aef5d4a391bd23b18703f
C++
sntwr/UVa-Solved-Problems
/solved/UVa11364/11364.cpp
UTF-8
947
2.703125
3
[]
no_license
#include <bits/stdc++.h> #define MAXN 30 int main () { int T; for (scanf ("%d", &T); T--;) { int N; int store[MAXN]; scanf ("%d", &N); for (int i = 0; i < N; i++) scanf ("%d", store + i); if (N <= 1) { printf ("0\n"); continue; } int max_st, min_st; if (store[0] > store[1]) { max_st = store[0]; min_st = store[1]; } else { max_st = store[1]; min_st = store[0]; } int lim; if (N % 2) { lim = N - 1; if (store[lim] > max_st) max_st = store[lim]; else if (store[lim] < min_st) min_st = store[lim]; } else lim = N; for (int i = 2; i < lim; i += 2) { int max_i, min_i; if (store[i] > store[i+1]) { max_i = store[i]; min_i = store[i+1]; } else { max_i = store[i+1]; min_i = store[i]; } if (max_i > max_st) max_st = max_i; if (min_i < min_st) min_st = min_i; } printf ("%d\n", 2 * (max_st - min_st)); } return 0; }
true
0be6b6ddc380e8e437a92ec0b02695b5796a73eb
C++
Thecatkiller/AN.DE-ALGOR.Y-ESTRAT.-DE-PROG
/Semana 05/main.cpp
UTF-8
1,544
3.46875
3
[]
no_license
#include <iostream> using namespace std; #define OPC_SUMAR '1' #define OPC_PROMEDIO '2' #define OPC_MAYOR '3' #define OPC_SALIR '9' char menuPrincipal(); int sumar(int lista[],int n); double promedio(int lista[],int n); int mayor(int lista[], int inicio, int fin); int main() { char mopc; int lista[] = {15,25,13,18,14}; int tam = sizeof(lista) / sizeof(*lista); do{ mopc = menuPrincipal(); switch(mopc){ case OPC_SUMAR: cout << "Sumar" << endl; cout << sumar(lista,tam) << endl; break; case OPC_PROMEDIO: cout << promedio(lista,tam) << endl; break; case OPC_MAYOR: cout << mayor(lista,0,tam - 1) << endl; break; } system("pause"); }while(mopc != OPC_SALIR); return 0; } char menuPrincipal(){ system("cls"); cout << "Menu Principal" << endl; cout << "[1] Sumar " << endl; cout << "[2] Promedio " << endl; cout << "[3] Mayor " << endl; cout << "[9] Salir " << endl; cout << "Seleccione: "; fflush(stdin); char opc = getchar(); return opc; } int sumar(int lista[],int n){ if (n <= 0) return 0; return (sumar(lista, n - 1) + lista[n - 1]); } double promedio(int lista[],int n){ int suma = sumar(lista,n); return suma / (double) n; } int mayor(int lista[], int inicio, int fin){ if(inicio == fin) return lista[inicio]; int medio = (inicio + fin) / 2; int izq = mayor(lista,inicio, medio); int der = mayor(lista,medio + 1, fin); return max(izq,der); }
true
02088ace1bc2c98d5e61fb08231e9940e79e3732
C++
zhaoxing-zstar/Quantnet-C
/Level_3/2.3/2.3.5/Point.cpp
UTF-8
1,344
3.78125
4
[]
no_license
/* Point.cpp Implement member functions for Point class */ #include "Point.hpp" #include <sstream> #include <iostream> #include <cmath> using namespace std; // Initialize with 0 Point::Point() : x(0), y(0) { cout << "Point created\n" << endl; } // a constructor with x-y coordinates Point::Point(double xval,double yval) : x(xval), y(yval) { cout << "Point created with given values" << endl; } // copy constructor Point::Point(const Point &p) { x=p.x; y=p.y; cout << "Point copied"<< endl; } // Destrcutor Point::~Point() { cout << "Point destroyed" << endl; } //Get the x-coordinate double Point::X() const { return x; } //Get the y-coordinate double Point::Y() const { return y; } //modify the x-coordinate void Point::X(double new_X) { x = new_X; } //modify the y-coordinate void Point::Y(double new_Y) { y = new_Y; } //string description of the point string Point::ToString() const { stringstream descrip; descrip << "Point(" << x << ", " << y << ")"<<endl; return descrip.str(); } // the distance to the origin(0,0) double Point::Distance() const { return sqrt(pow(x,2)+pow(y,2)); } // distance between two points (call by reference) double Point::Distance(const Point &p) const { return sqrt(pow((x-p.x),2)+pow((y-p.y),2)); }
true
61444ad1fe1fb1aac39cae4b5e8a385baee94667
C++
qyb225/LeetCode
/Problem-004/P4.cpp
UTF-8
683
3.1875
3
[]
no_license
#include <vector> using namespace std; class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2); }; double Solution::findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { vector<int> v; int i = 0, j = 0; while (i < nums1.size() && j < nums2.size()) { if (nums1[i] < nums2[j]) v.push_back(nums1[i++]); else v.push_back(nums2[j++]); } while (i < nums1.size()) v.push_back(nums1[i++]); while (j < nums2.size()) v.push_back(nums2[j++]); if (v.size() % 2 == 0) return (v[v.size() / 2] + v[v.size() / 2 - 1]) / 2.0; else return v[v.size() / 2]; }
true
723eb532c9f55b164e25a9770d24cb3fc09e6f01
C++
battisq/OOPLabs
/Lab4/Fraction.h
WINDOWS-1251
1,564
3.078125
3
[]
no_license
#pragma once #include <ostream> namespace Mathematics { class Fraction { private: int numerator; int denominator; void reduce(void); public: Fraction(int _numerator = 0, int _denominator = 1); int getNumerator(void) const; int getDenominator(void) const; std::pair<int, Fraction> toProper(void); Fraction & toImproper(int _integerPart); Fraction & operator += (const Fraction &_a); Fraction & operator -= (const Fraction &_a); Fraction & operator *= (const Fraction &_a); Fraction & operator /= (const Fraction &_a); friend bool operator == (const Fraction &_a, const Fraction &_b); friend bool operator != (const Fraction &_a, const Fraction &_b); friend bool operator ! (const Fraction &_a); friend bool operator > (const Fraction &_a, const Fraction &_b); friend bool operator >= (const Fraction &_a, const Fraction &_b); friend bool operator < (const Fraction &_a, const Fraction &_b); friend bool operator <= (const Fraction &_a, const Fraction &_b); friend Fraction operator + (const Fraction &_a, const Fraction &_b); friend Fraction operator - (const Fraction &_a, const Fraction &_b); friend Fraction operator * (const Fraction &_a, const Fraction &_b); friend Fraction operator / (const Fraction &_a, const Fraction &_b); friend std::ostream & operator << (std::ostream &_out, const Fraction &_a); }; int nok(int _firstEl, int _secondEl); // int nod(int _firstEl, int _secondEl); // }
true
365e37278199c1cfd0533debc1ef21e234199e81
C++
bobrippling/alleged
/client/netobj.cpp
UTF-8
232
2.546875
3
[]
no_license
#include <string.h> #include <arpa/inet.h> #include "netobj.h" NetObj::NetObj(struct sockaddr_in *addr) : addr() { if(addr) memcpy(&this->addr, addr, sizeof this->addr); else memset(&this->addr, '\0', sizeof this->addr); }
true
f14d321f3c529c9541211606d307c61ddab69faa
C++
romeoyacobs/HackerRank
/30Days/C++/day8.cpp
UTF-8
696
2.9375
3
[]
no_license
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; int main() { int N; cin >> N; unordered_map<string, long long> phoneBook; while (N--) { long long number; string name; cin >> name; cin >> number; phoneBook[name] = number; } string query; while (cin >> query) { auto itFound = phoneBook.find(query); if (itFound == phoneBook.end()) { cout << "Not found" << endl; } else { cout << query << "=" << itFound->second << endl; } } return 0; }
true
46af1564d816f53868de549cd2082d86d47f38f0
C++
linhanyu/ACM
/acm_practice_1/acm_practice_1/File_2.cpp
UTF-8
871
3.15625
3
[]
no_license
#include <cstdio> #include <iostream> #include <cstdlib> #define NUM 101 using namespace std; template<class T> void Insert_Sort(T * a, int size) { int i, j; T temp; for ( i = 1; i < size; i++) { temp = a[i]; for (j = i;j>0 && temp < a[j-1]; j--) { a[j] = a[j - 1]; } a[j] = temp; } } struct T_v { int end; int begin; bool operator<(T_v & b) { return end < b.end; } }; istream & operator>>(istream & is, T_v & tv) { is >> tv.begin >> tv.end; return is; } // int main() { // // int n; // T_v prog[NUM]; // while (cin >> n && n!=0) // { // for (int i = 0; i < n; i++) // { // cin >> prog[i]; // } // // Insert_Sort(prog, n); // // int max = 0,sum=0; // for (int i = 0; i < n; i++) // { // if (prog[i].begin >= max) // { // sum++; // max = prog[i].end; // } // } // // cout << sum << endl; // } // }
true
b72512952bb49e460c0fe6421776c94547930c24
C++
algrandjean1/CST316Embedded
/airAutomation/embeddedSystems/Methane/.build/uno/src/mq4Code.cpp
UTF-8
1,217
2.734375
3
[]
no_license
#include <Arduino.h> void setup(); void loop(); #line 1 "src/mq4Code.ino" /** * Original author found at * http://arduinotronics.blogspot.com/2012/03/gas-sensor-tutorial.html * Code used and modified by 316 Air project team **/ // to the pins used: const int analogInPin = A0; // Analog input pin that the potentiometer is attached to const int ledPin = 13; // LED connected to digital pin 13 int sensorValue = 0; // value read from the sensor void setup() { // initialize serial communications at 9600 bps: Serial.begin(9600); pinMode(ledPin, OUTPUT); // sets the digital pin as output } void loop() { // read the analog in value: sensorValue = analogRead(analogInPin); // determine alarm status if (sensorValue >= 750) { digitalWrite(ledPin, HIGH); // sets the LED on } else { digitalWrite(ledPin, LOW); // sets the LED off } // print the results to the serial monitor: Serial.print("sensor = " ); Serial.println(sensorValue); // wait 10 milliseconds before the next loop // for the analog-to-digital converter to settle // after the last reading: delay(10); }
true
eb6e8cd3306390a6b603614bbf895db8052b310f
C++
kipdec/ArduinoConductanceProject
/ArduinoResistanceOhmExperiment/OhmVolt/OhmVolt.ino
UTF-8
1,376
3.234375
3
[]
no_license
// Arduino Ohm Voltage Experiment // Kip DeCastro // July 18th // // This program is designed to compare the equations gleaned from the Arduino // ohm voltage experiment to each other. // Initialize variables... double a = 0; // Our value read from the arduino double va = 0; // Arduino to volt double ra = 0; // Arduino to resistance double rv = 0; // va to resistance double rt = 0; // Tim's resistance equation void setup(){ // Set up our baud signal Serial.begin(9600); // Get the first analog pin ready to read data. pinMode(A0, INPUT); // Set up the header for our data. NOTE: This data is much easier if imported // into excel. // Value = Arduino 5 bit value // Volts = Volts calculated by the VA equation // Resistance 1 = Resistance calculated by the RA equation // Resistance 2 = Resistance calculated by combining VA + RV // Resistance 3 = Tim's Resistance equation Serial.println("Value, Volts, Resistance 1 (MOhm), Resistance 2 (MOhm), Resistance 3 (MOhm)"); } void loop(){ a = analogRead(A0); va = 1.1742*(log(a)) - 2.8236; double ma = a/100; ra = 0.8633*(pow(ma, -1.202)); rv = 0.1828*(pow(va, 2)) - 1.7136*va + 4.1463; rt = ((0.1*1024)/a)-0.1; Serial.print(a); Serial.print(", "); Serial.print(va); Serial.print(", "); Serial.print(ra); Serial.print(", "); Serial.print(rv); Serial.print(", "); Serial.println(rt); delay(2000); }
true
b2aac1ceacc13259436d3d6c8184e253b354531b
C++
TuanAnhNguyen69/MegamanX3
/MegamanX3/MegamanX3/HelitFlying.cpp
UTF-8
2,577
2.609375
3
[]
no_license
#include "pch.h" #include "HelitFlying.h" #include "Roof.h" HelitFlying::HelitFlying(HelitStateHandler *handler, Entity *entity) : HelitState(handler, entity) { sprite = new AnimatedSprite(15, 1, true); sprite->Initialize(Engine::GetEngine()->GetGraphics()->GetDevice(), "helit", 0, 4, 5, 50, 50); } HelitFlying::~HelitFlying() { if (handler->GetCurrentStateName() != HelitStateHandler::StateName::Flying) { if (sprite) { delete sprite; sprite = nullptr; } } } void HelitFlying::Load() { entity->SetSprite(sprite); entity->SetVelocity(0, 0); } void HelitFlying::Update() { if (handler->GetHadShootState()) { entity->AddVelocityY(-10.0f); } else { if (!handler->GetLeftTarget()) { entity->SetReverse(true); if (!handler->GetAboveTarget()) { entity->AddVelocityY(10.0f); } else { entity->AddVelocityY(-10.0f); handler->ChangeState(HelitStateHandler::StateName::Shooting); } } else { entity->SetReverse(false); if (!handler->GetAboveTarget()) { entity->AddVelocityY(10.0f); } else { entity->AddVelocityY(-10.0f); handler->ChangeState(HelitStateHandler::StateName::Shooting); } } } } void HelitFlying::OnCollision(Entity * impactor, Entity::CollisionSide side, Entity::CollisionReturn data) { if (impactor->GetEntityId() == EntityId::Platform_ID || impactor->GetEntityId() == EntityId::Megaman_ID ) { switch (side) { case Entity::Left: { break; } case Entity::Right: { break; } case Entity::TopRight: case Entity::TopLeft: case Entity::Top: { /*entity->AddPosition(0, data.RegionCollision.bottom - data.RegionCollision.top + 1); entity->SetVelocity(0, 0); */ entity->AddVelocityY(+20.0f); break; } case Entity::BottomRight: case Entity::BottomLeft: case Entity::Bottom: { entity->AddVelocityY(-20.0f); break; } } } if ( impactor->GetEntityId() == EntityId::Roof_ID) { switch (side) { case Entity::Left: { break; } case Entity::Right: { break; } case Entity::TopRight: case Entity::TopLeft: case Entity::Top: { /*entity->AddPosition(0, data.RegionCollision.bottom - data.RegionCollision.top + 1); entity->SetVelocity(0, 0); */ entity->AddVelocityY(+20.0f); break; } case Entity::BottomRight: case Entity::BottomLeft: case Entity::Bottom: { entity->SetPosition(entity->GetPosition().x, ((Roof *)impactor)->GetCollidePosition(entity) - entity->GetWidth() / 2); entity->AddVelocityY(-20.0f); break; } } } }
true
ef02c0b884d555335df9cd3c3738d2a423a9ea88
C++
yleblanc/opencine
/Source/OpenCine/Model/MediaExplorerModel.cpp
UTF-8
1,745
2.515625
3
[]
no_license
#include "MediaExplorerModel.h" #include <QDir> /*ClipInfo::ClipInfo(QObject *parent) : QObject(parent) { }*/ ClipInfo::ClipInfo(const QString &path, const QString &name, const unsigned int& width, const unsigned int& height, const unsigned int& fps, QObject *parent): QObject(parent), _path(path), _name(name), _width(width), _height(height), _fps(fps) { _name = path; } QString ClipInfo::Path() const { return _path; } QString ClipInfo::Name() const { return _name; } unsigned int ClipInfo::Width() const { return _width; } unsigned int ClipInfo::Height() const { return _height; } unsigned int ClipInfo::FPS() const { return _fps; } bool MediaExplorerModel::EnumerateAvailableData(std::string folderPath, ClipInfo** clipData) { QDir dir(QString::fromStdString(folderPath)); QStringList filters; filters << "*.dng"; dir.setNameFilters(filters); dir.setFilter(QDir::NoDotAndDotDot | QDir::Files); if(dir.count() == 0) { return false; } //Get metadata for the first file, no error checks available atm std::string fileName = dir.entryList().at(0).toStdString(); OCFrame* imageData = _dataProvider->GetMetadataFromFile(folderPath + "/" + fileName); if(imageData) { *clipData = new ClipInfo(QString::fromStdString(folderPath), dir.dirName(), imageData->GetWidth(), imageData->GetHeight(), 0); _availableData.push_back(*clipData); delete imageData; return true; } //if(imageData != nullptr) //{ // emit NewDataAdded(imageData); // return true; // } return false; } ClipInfo* MediaExplorerModel::GetClipByID(unsigned int clipID) { if(clipID < _availableData.size()) { return _availableData.at(clipID); } return nullptr; }
true
760bbf41c6de2a615b8c062ea38205f66de4b34b
C++
sajidhasanapon/URI-Solutions
/Codes/URI 1217.cpp
UTF-8
655
3.03125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; double total_money = 0, total_weight = 0; for ( int i = 1; i <= t; i++ ) { double v; cin >> v; total_money += v; getchar(); int cnt = 0; string str; getline ( cin, str ); stringstream ss ( str ); string buf; while ( ss >> buf ) { cnt++; total_weight++; } cout << "day " << i << ": " << cnt << " kg" << endl; } cout << fixed << setprecision ( 2 ) << total_weight / t << " kg by day" << endl; cout << "R$ " << fixed << setprecision ( 2 ) << total_money / t << " by day" << endl; return 0; }
true
ea7a23f1c2e59b23733d4e05a66fa8cfd1c67a18
C++
yzq986/cntt2016-hw1
/TC-SRM-568-div1-250/Remilia.cpp
UTF-8
963
2.6875
3
[]
no_license
#include<bits/stdc++.h> #define rep(x,a,b) for (int x=a;x<=(int)b;x++) #define drp(x,a,b) for (int x=a;x>=(int)b;x--) #define cross(x,a) for (int x=hd[a];~x;x=nx[x]) #define ll long long #define inf (1<<29) #define PII pair<int,int> #define PDD pair<double,double> #define mk(a,b) make_pair(a,b) #define fs first #define sc second #define pb push_back #define VI vector<int> using namespace std; const int maxn=55; int f[maxn][8]; void upd(int &x,int y){ if (x==-1||y<x) x=y; } /* 决定每个盒子放什么颜色。 有解就是每种颜色都有盒子,xjbDP就O(n)了。 */ struct BallsSeparating{ int minOperations(vector<int>R,vector<int>G,vector<int>B){ int n=R.size(); memset(f,-1,sizeof f); f[0][0]=0; rep(i,0,n-1){ int sum=R[i]+G[i]+B[i]; rep(j,0,7){ if (f[i][j]==-1) continue; upd(f[i+1][j|1],f[i][j]+sum-R[i]); upd(f[i+1][j|2],f[i][j]+sum-G[i]); upd(f[i+1][j|4],f[i][j]+sum-B[i]); } } return f[n][7]; } };
true
f1fa21859d0f7ec65b9b7c6eb7256944cad1bbd5
C++
JinRLuo/solution-of-algorithm
/acwing/算法基础课/基础算法/801 二进制中1的个数.cpp
UTF-8
209
2.609375
3
[]
no_license
#include <iostream> using namespace std; int n; int main(){ cin>>n; int a,res; for(int i=0;i<n;i++){ res=0; cin>>a; while(a){ if(a&1){ res++; } a>>=1; } cout << res << " "; } }
true
79cb12dc6f10e5df7ff9d63c45bb2fd3af17332b
C++
ysonggit/roschat
/src/rostalker/src/rostalker.h
UTF-8
1,029
2.71875
3
[]
no_license
#ifndef ROS_TALKER_H #define ROS_TALKER_H #include <ros/ros.h> #include "std_msgs/String.h" #include <sstream> #include <string> #include <unordered_map> using namespace std; struct ListenerAgent{ ListenerAgent(int i){ id = i; stringstream ss; ss<<id; string topic_name = "listener"+ss.str(); res_sub = nh.subscribe(topic_name, 1000, &ListenerAgent::getResponse, this); } int id; ros::NodeHandle nh; ros::Subscriber res_sub; void getResponse(const std_msgs::String & res); }; class RosTalker{ public: RosTalker(){ msg_pub = nh.advertise<std_msgs::String>("talker_msg", 1000); ros::param::get("listener_num", listener_num); for(int i=1; i<=listener_num; i++){ ListenerAgent * agent = new ListenerAgent(i); agents[i] = agent; } } int listener_num; unordered_map<int, ListenerAgent*> agents; ros::NodeHandle nh; ros::Publisher msg_pub; void talk(); int add(int, int); }; #endif
true
4ed34eb034cc28d94a7ed51b979cb7aeac8e660a
C++
KraftOreo/Bilevel-Differential-Grasp-Optimization
/Utils/internal/SOSPolynomialNrVar.h
UTF-8
2,117
2.703125
3
[]
no_license
//meta-template function to count max number of variables template <typename T,char LABEL,char LABEL2> struct NrVar { static sizeType nrVar(const SOSPolynomial<T,LABEL>& s) { if(LABEL==LABEL2) { sizeType nrVar=0; for(sizeType i=0; i<(sizeType)s._terms.size(); i++) nrVar=std::max<sizeType>(nrVar,s._terms[i].nrVar()); return nrVar; } else return 0; } static sizeType order(const SOSPolynomial<T,LABEL>& s) { if(LABEL==LABEL2) return orderAll(s); else return 0; } static sizeType orderAll(const SOSPolynomial<T,LABEL>& s) { sizeType order=0; for(sizeType i=0; i<(sizeType)s._terms.size(); i++) order=std::max<sizeType>(order,s._terms[i].order()); return order; } }; template <typename T,char LABEL3,char LABEL,char LABEL2> struct NrVar<SOSPolynomial<T,LABEL3>,LABEL,LABEL2> { static sizeType nrVar(const SOSPolynomial<SOSPolynomial<T,LABEL3>,LABEL>& s) { if(LABEL==LABEL2) { sizeType nrVar=0; for(sizeType i=0; i<(sizeType)s._terms.size(); i++) nrVar=std::max<sizeType>(nrVar,s._terms[i].nrVar()); return nrVar; } else { sizeType nrVar=0; for(sizeType i=0; i<(sizeType)s._terms.size(); i++) nrVar=std::max<sizeType>(nrVar,NrVar<T,LABEL3,LABEL2>::nrVar(s._terms[i]._coef)); return nrVar; } } static sizeType order(const SOSPolynomial<SOSPolynomial<T,LABEL3>,LABEL>& s) { if(LABEL==LABEL2) { sizeType order=0; for(sizeType i=0; i<(sizeType)s._terms.size(); i++) order=std::max<sizeType>(order,s._terms[i].order()); return order; } else { sizeType order=0; for(sizeType i=0; i<(sizeType)s._terms.size(); i++) order=std::max<sizeType>(order,NrVar<T,LABEL3,LABEL2>::order(s._terms[i]._coef)); return order; } } static sizeType orderAll(const SOSPolynomial<SOSPolynomial<T,LABEL3>,LABEL>& s) { sizeType order=0; for(sizeType i=0; i<(sizeType)s._terms.size(); i++) order=std::max<sizeType>(order,s._terms[i].order()+NrVar<T,LABEL3,LABEL2>::orderAll(s._terms[i]._coef)); return order; } };
true
3d0b201d9986883e60f9f8a90f551583e3c2b2cc
C++
rahuljain/playground_CPlusPlus
/high_school/Extra programs/Z.CPP
UTF-8
262
2.5625
3
[]
no_license
#include<iostream.h> #include<conio.h> void main() { int n; cin>>n; for(int i=1;i<=n;i++) cout<<"*"; cout<<endl; for(int j=n-2;j>0;j--) { for(int k=j;k>0;k--) cout<<" "; cout<<"*"; cout<<endl; } for(i=1;i<=n;i++) cout<<"*"; }
true
dd87666ad609e81bb64054951d8122f55ebd94be
C++
filipeguimaraes/CG1920
/engine/structs/transformation.cpp
UTF-8
6,047
2.90625
3
[]
no_license
#include <stdlib.h> #include <GL/glut.h> #include <stdio.h> #include <vector> #include <math.h> #include "transformation.h" #include "catmull.h" struct transformacao_3d { float var[4][4]; float time; std::vector<float> * pontos; }; float * invert_order_matrix(float m[4][4]){ static float r[4*4]; for (int i = 0; i < 4*4; ++i) { r[i] = m[i%4][i/4]; } return r; } float to_radial(float angle) { return angle / 360.f * M_PI * 2; } float * calc_rotation_time(TRANSFORMACAO t) { float x = t->var[0][0]; float y = t->var[0][1]; float z = t->var[0][2]; float angle = to_radial(glutGet(GLUT_ELAPSED_TIME) * 360.f / t->time); float aux[4][4]; for (int i = 0; i < 4; ++i) for (int j = 0; j < 4; ++j) aux[i][j] = i == j ? 1 : 0; aux[0][0] = pow(x,2) + (1 - pow(x,2)) * cos(angle); aux[0][1] = x * y * (1 - cos(angle)) - z * sin(angle); aux[0][2] = x * z * (1 - cos(angle)) + y * sin(angle); aux[1][0] = x * y * (1 - cos(angle)) + z * sin(angle); aux[1][1] = pow(y,2) + (1 - pow(y,2)) * cos(angle); aux[1][2] = y * z * (1 - cos(angle)) - x * sin(angle); aux[2][0] = x * z * (1 - cos(angle)) - y * sin(angle); aux[2][1] = y * z * (1 - cos(angle)) + x * sin(angle); aux[2][2] = pow(z,2) + (1 - pow(z,2)) * cos(angle); return invert_order_matrix(aux); } float * calc_curve(TRANSFORMACAO t) { float * r; if (t->pontos) r = calc_catmull(t->time,t->pontos); else r = calc_rotation_time(t); return r; } float * get_matrix(TRANSFORMACAO t) { if (t->time > 0) return calc_curve(t); else return invert_order_matrix(t->var); } void add_vertice_translate(TRANSFORMACAO t, double x, double y, double z){ t->pontos->push_back(x); t->pontos->push_back(y); t->pontos->push_back(z); } void set_matriz_id(TRANSFORMACAO mat) { for (int i = 0; i < 4; ++i) for (int j = 0; j < 4; ++j) mat->var[i][j] = i == j ? 1 : 0; } TRANSFORMACAO init_transform(){ TRANSFORMACAO t = static_cast<TRANSFORMACAO>(malloc(sizeof(struct transformacao_3d))); set_matriz_id(t); t->time = 0; t->pontos = nullptr; return t; } TRANSFORMACAO scale(double x, double y, double z){ TRANSFORMACAO t = init_transform(); t->var[0][0] = x; t->var[1][1] = y; t->var[2][2] = z; return t; } TRANSFORMACAO rotation_time(double x, double y, double z, double time){ TRANSFORMACAO t = init_transform(); t->time = time; t->var[0][0] = x; t->var[0][1] = y; t->var[0][2] = z; return t; } TRANSFORMACAO rotation(double x, double y, double z, double alfa){ float angle = to_radial(alfa); TRANSFORMACAO t = init_transform(); t->var[0][0] = pow(x,2) + (1 - pow(x,2)) * cos(angle); t->var[0][1] = x * y * (1 - cos(angle)) - z * sin(angle); t->var[0][2] = x * z * (1 - cos(angle)) + y * sin(angle); t->var[1][0] = x * y * (1 - cos(angle)) + z * sin(angle); t->var[1][1] = pow(y,2) + (1 - pow(y,2)) * cos(angle); t->var[1][2] = y * z * (1 - cos(angle)) - x * sin(angle); t->var[2][0] = x * z * (1 - cos(angle)) - y * sin(angle); t->var[2][1] = y * z * (1 - cos(angle)) + x * sin(angle); t->var[2][2] = pow(z,2) + (1 - pow(z,2)) * cos(angle); return t; } TRANSFORMACAO translate_time(double time){ TRANSFORMACAO t = init_transform(); t->time = time; t->pontos = new std::vector<float>(); return t; } TRANSFORMACAO translate(double x, double y, double z){ TRANSFORMACAO t = init_transform(); t->var[0][3] = x; t->var[1][3] = y; t->var[2][3] = z; return t; } //DEBUG PRINTS void print_vectors(std::vector<int> * historico, std::vector<TRANSFORMACAO> * transformacoes) { printf("||||| trans: %zu --- hist: %zu |||||", transformacoes->size(), historico->size()); printf("\n"); } void print_matriz(TRANSFORMACAO t){ for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { printf("%f ||",t->var[i][j]); } puts(" "); } } void update_transform(TRANSFORMACAO agregado, TRANSFORMACAO transform) { float agreg[4][4]; for (int i = 0; i < 4; ++i) for (int j = 0; j < 4; ++j) agreg[i][j] = 0; for (int i = 0; i < 4; ++i) for (int j = 0; j < 4; ++j) for (int k = 0; k < 4; ++k) agreg[i][j] += agregado->var[i][k] * transform->var[k][j]; for (int i = 0; i < 4; ++i) for (int j = 0; j < 4; ++j) agregado->var[i][j] = agreg[i][j]; } void set_ponto(PONTO * p, float x, float y, float z) { p->var[0] = x; p->var[1] = y; p->var[2] = z; p->var[3] = 1; } void reset_transfromations(std::vector<TRANSFORMACAO> * transformacoes, TRANSFORMACAO agregado) { set_matriz_id(agregado); for (int i = 0; i < transformacoes->size(); ++i) update_transform(agregado,(*transformacoes)[i]); } void open_group(std::vector<int> * historico, std::vector<TRANSFORMACAO> * transformacoes, TRANSFORMACAO agregado) { if(transformacoes->empty()) set_matriz_id(agregado); historico->push_back(transformacoes->size()); } void close_group(std::vector<int> * historico, std::vector<TRANSFORMACAO> * transformacoes, TRANSFORMACAO agregado) { while (!historico->empty() && (*historico)[historico->size() - 1] < transformacoes->size()) transformacoes->pop_back(); historico->pop_back(); reset_transfromations(transformacoes,agregado); } void add_transform(std::vector<TRANSFORMACAO> * transformacoes, TRANSFORMACAO agregado, TRANSFORMACAO transformacao) { transformacoes->push_back(transformacao); update_transform(agregado,transformacao); } void point_transforms_total(PONTO * p, TRANSFORMACAO agregado) { PONTO np; np.var[0] = np.var[1] = np.var[2] = np.var[3] = 0; for (int l = 0; l < 4; ++l) for (int c = 0; c < 4; ++c) np.var[l] += agregado->var[l][c] * p->var[c]; for (int i = 0; i < 4; ++i) p->var[i] = np.var[i]; }
true
2bc952e590d36f163e14b318d0122dad6d9eeeb6
C++
RomanArzumanyan/Rustling
/main.cpp
UTF-8
1,689
2.734375
3
[ "Apache-2.0" ]
permissive
#include <iostream> #include <vector> #include "Rustling.hpp" using namespace rustling; using namespace std; int main() { PlatformMgr plt_mgr; Platform my = plt_mgr.makePlatform(CL_DEVICE_TYPE_GPU); cout << my.getExtensions() << endl << my.getID() << endl << my.getName() << endl << my.getProfile() << endl << my.getVendor() << endl << my.getVersion() << endl; DeviceMgr dev_mgr; Device gpu = dev_mgr.makeDevice(CL_DEVICE_TYPE_GPU); cout << gpu.getName() << endl; Device cpu = dev_mgr.makeDevice(CL_DEVICE_TYPE_CPU); cout << cpu.getName() << endl; Context ctx({cpu, gpu}); CmdQueue queue(ctx, gpu); try { queue << rustling::flush << rustling::finish; rustling::flush(queue); } catch (SException &e) { cout << e.what() << endl; } vector<int> vec({0, 1, 2, 3, 4}); Event evt; Buffer<int> buf(ctx, vec.size(), CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, &vec[0]); queue << (buf.map() >> evt); evt.Wait(); cout << buf[0] << "\t" << buf[1] << "\t" << buf[2] << "\t" << buf[3] << endl; cout << evt.getTime() << endl; cout << evt.isUsed() << endl; try { queue << buf.read(&vec[0])(true) << buf.write(&vec[0])(true); Event evt1; queue << (buf.unmap() >> evt1); evt1.Wait(); cout << evt1.getTime() << endl; Event evt2; Kernel my_kernel(ctx, gpu, "My", "/home/roman/kernel.cl"); queue << (my_kernel({32, 1}, {}, {}) >> evt2); evt2.Wait(); } catch (SException &e) { cout << e.what() << endl; } return 0; }
true
7200cbf4918f0b28fd7a017106dab1dc04ccd166
C++
dean11/NoEdge
/source/Game/GameLogic/PickupSystem/Pickup.h
UTF-8
837
2.515625
3
[]
no_license
#ifndef PICKUP_H #define PICKUP_H #include "../StaticObject.h" #include "../Player.h" #include "WinTimer.h" typedef void (*EventOnCollision)(Oyster::Physics::ICustomBody *proto,Oyster::Physics::ICustomBody *deuter,Oyster::Math::Float kineticEnergyLoss); namespace GameLogic { class Pickup : public StaticObject { public: Pickup(Oyster::Physics::ICustomBody *rigidBody, EventOnCollision collisionFunc, ObjectSpecialType type, int objectID, Oyster::Math::Float spawnTime); virtual ~Pickup(); virtual void Update(); bool IsActive(); virtual void OnCollision(Player *player) = 0; static void PickupCollision(Oyster::Physics::ICustomBody *rigidBodyCrate, Oyster::Physics::ICustomBody *obj, Oyster::Math::Float kineticEnergyLoss); protected: bool active; Utility::WinTimer timer; double spawnTime; }; } #endif
true
24b322ebfc99962d3a04efafc187b82c0505b581
C++
zvanjak/MiscProjects
/CSharp/Code Plagiarism Detector/OLD Code/astdiff+c2ast/c2ast/ast.h
UTF-8
3,759
2.59375
3
[]
no_license
#ifndef _AST_ #define _AST_ #include "stdafx.h" #include "source.h" #include "ast_alloc.h" typedef enum { ASTnt_block = 0, ASTnt_function, ASTnt_function_code, ASTnt_if, ASTnt_if_true, ASTnt_if_false, ASTnt_for, ASTnt_while, ASTnt_do, ASTnt_root, ASTnt_switch, ASTnt_label, ASTnt_undefined } AST_node_type; struct c_type { string name; string type; }; struct c_decl { string name; string type; source value; }; struct c_func_data { string name; string type; }; typedef vector<c_type> c_type_list; typedef vector<c_decl> c_decl_list; #define FOREACHASTCTYPE(node, itm) for (c_type_list::iterator itm = \ (node).types.begin(); \ itm != (node).types.end(); \ ++itm) #define FOREACHASTCCTYPE(node, itm) for (c_type_list::const_iterator itm = \ (node).types.begin(); \ itm != (node).types.end(); \ ++itm) #define FOREACHASTCDECL(node, itm) for (c_decl_list::iterator irm = \ (node).declarations.begin(); \ itm != (node).declarations.end(); \ ++itm) #define FOREACHASTCCDECL(node, itm) for (c_decl_list::const_iterator itm = \ (node).declarations.begin(); \ itm != (node).declarations.end(); \ ++itm) class AST_ncore { public: AST_node_type type; ///< tip cvora c_type_list types; ///< tipovi deklarirani u cvoru c_decl_list declarations; ///< deklaracije u cvoru c_func_data function_data; ///< podaci od funkcije ako je cvor tipa fja (name se koristi i za labelu!) source src; ///< sors u cvoru (blok); kod if, while, ... je to uvjet AST_ncore *parent; AST_ncore(AST_node_type type = ASTnt_undefined, AST_ncore *parent = NULL); void Clear(); bool IsType(const string &sfc); void AddType(const c_type &ct); void AddDeclaration(const c_decl &cd); void Dump(int level = 0) const; string GetNodePath() const; void ThrowError(const string &errstr) const; static string TypeToString(AST_node_type type); friend class AST; }; class AST_anode : public AST_ncore { public: AST_anode() {} AST_anode(const AST_ncore &nc) : AST_ncore(nc) {} AST_anode(AST_node_type t) : AST_ncore(t) {} virtual ~AST_anode() {} virtual void Dump(int level=0) const; void Clear(); AST_anode& AddNode(AST_node_type t = ASTnt_undefined); // Ove apstraktne funkcije ispunjava AST_alloc virtual void ClearChildren() = 0; virtual AST_anode& AddNode(const AST_ncore &an) = 0; virtual unsigned int GetNKids() const = 0; virtual AST_anode& operator[] (unsigned int id) = 0; virtual const AST_anode& operator[] (unsigned int id) const = 0; // virtual bool RemoveNode(const AST_ncore &rn); }; class AST_snode : public AST_anode { public: AST_ALLOCATOR(AST_snode); AST_snode() : AST_anode(ASTnt_undefined) {} AST_snode(const AST_ncore &an) : AST_anode(an) {} }; class AST { public: AST_snode root; AST(); void Dump() const; const AST & operator = (source &src); static void Dump(const AST_snode &root); static void FillCustomAST(AST_anode &root, source &src); private: static bool ProcessTypes(AST_anode &parent, source &src); static void ProcessRootBlock(AST_anode &root, source &src); static bool ProcessRootCode(AST_anode &root, source &src); static void ProcessBlock(AST_anode &parent, source &src); static void ProcessLabel(AST_anode &parent, source &src); static void ProcessSwitch(AST_anode &parent, source &src); static bool ProcessDeclarations(AST_ncore &parent, source &src, bool arguments = false, bool force = false); static bool GetTypeString(AST_ncore &parent, source &src, string &typestring); static bool GetArrayString(source &src, string &arraystring); static bool FindFunction(const AST_anode &root, const string &name, unsigned int *pos); }; #endif
true
6badeff6efab21257d3efed2c93af70e046ae8a9
C++
Javanaise/mrboom-libretro
/ai/bt/composites/Sequence.hpp
UTF-8
1,006
3.515625
4
[ "MIT" ]
permissive
#pragma once #include "../Composite.hpp" namespace bt { /* * The Sequence composite ticks each child node in order. * If a child fails or runs, the sequence returns the same status. * In the next tick, it will try to run each child in order again. * If all children succeeds, only then does the sequence succeed. */ class Sequence : public Composite { public: void Initialize() { index = 0; } Status Update() { if (HasNoChildren()) { return(Success); } // Keep going until a child behavior says it's running. while (1) { bt::Node * child = children.at(index); bt::Status status = child->Tick(); // If the child fails, or keeps running, do the same. if (status != Success) { return(status); } // Hit the end of the array, job done! if (++index == (signed)children.size()) { return(Success); } } } }; }
true
190dd88de8883fdf378026b4fd22b2893f799d3e
C++
mshah12/cs225-sp20
/mp_stickers/main.cpp
UTF-8
589
2.96875
3
[]
no_license
#include "Image.h" #include "StickerSheet.h" int main() { // // Reminder: // Before exiting main, save your creation to disk as myImage.png // Image baseImage, corn, ramchip, computer; baseImage.readFromFile("illinois.png"); computer.readFromFile("computer.png"); ramchip.readFromFile("ramchip.png"); corn.readFromFile("corn.png"); StickerSheet sheet(baseImage, 4); sheet.addSticker(computer, 200, 300); sheet.addSticker(ramchip, 1200, 300); sheet.addSticker(corn, 1900, 300); Image final = sheet.render(); final.writeToFile("myImage.png"); return 0; }
true
0b49c06b01b8c36105c990872a5f0999712cab26
C++
ADDD0/C-
/C++面向对象程序设计(第2版) 谭浩强/第3章 怎样使用类和对象/习题/5.cpp
UTF-8
873
4.15625
4
[]
no_license
/** * 建立一个对象数组,内放5个学生的数据(学号、成绩),设立一个函数max,用指向 * 对象的指针作函数参数,在max函数中找出5个学生中成绩最高者,并输出其学号。 */ #include <iostream> using namespace std; class Student { public: Student(int n, float s): sno(n), score(s) {} void showSno(); int sno; float score; }; void Student::showSno() { cout << "sno:" << sno << endl; } int main() { Student max(Student *); Student arr[] = { Student(101, 78.5), Student(102, 85.5), Student(103, 98.5), Student(104, 100.0), Student(105, 95.5) }; max(arr).showSno(); return 0; } Student max(Student *p) { Student *max=p; for (int i=0; i < 5; ++i) if (max->score < (p + i)->score) max = p + i; return *max; }
true
b5df90702f0ca9529ff11ace90afd3876969155b
C++
shuhaowu/nottetris2
/original/love2d072/src/modules/image/devil/ImageData.cpp
UTF-8
8,926
2.703125
3
[ "Zlib" ]
permissive
/** * Copyright (c) 2006-2011 LOVE Development Team * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. **/ #include "ImageData.h" // STD #include <iostream> // LOVE #include <common/Exception.h> namespace love { namespace image { namespace devil { void ImageData::load(Data * data) { // Generate DevIL image. ilGenImages(1, &image); // Bind the image. ilBindImage(image); // Try to load the image. ILboolean success = ilLoadL(IL_TYPE_UNKNOWN, (void*)data->getData(), data->getSize()); // Check for errors if(!success) { throw love::Exception("Could not decode image!"); return; } width = ilGetInteger(IL_IMAGE_WIDTH); height = ilGetInteger(IL_IMAGE_HEIGHT); origin = ilGetInteger(IL_IMAGE_ORIGIN); // Make sure the image is in RGBA format. ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE); // This should always be four. bpp = ilGetInteger(IL_IMAGE_BPP); if(bpp != 4) { std::cerr << "Bits per pixel != 4" << std::endl; return; } } ImageData::ImageData(Data * data) { load(data); } ImageData::ImageData(filesystem::File * file) { Data * data = file->read(); load(data); data->release(); } ImageData::ImageData(int width, int height) : width(width), height(height), origin(IL_ORIGIN_UPPER_LEFT), bpp(4) { // Generate DevIL image. ilGenImages(1, &image); // Bind the image. ilBindImage(image); bool success = (ilTexImage(width, height, 1, bpp, IL_RGBA, IL_UNSIGNED_BYTE, 0) == IL_TRUE); if(!success) { int err = ilGetError(); if (err != IL_NO_ERROR){ switch (err) { case IL_ILLEGAL_OPERATION: throw love::Exception("Error: Illegal operation"); break; case IL_INVALID_PARAM: throw love::Exception("Error: invalid parameters"); break; case IL_OUT_OF_MEMORY: throw love::Exception("Error: out of memory"); break; default: throw love::Exception("Error: unknown error"); break; } } throw love::Exception("Could not decode image data."); } // Set to black. memset((void*)ilGetData(), 0, width*height*4); } ImageData::ImageData(int width, int height, void *data) : width(width), height(height), origin(IL_ORIGIN_UPPER_LEFT), bpp(4) { // Generate DevIL image. ilGenImages(1, &image); // Bind the image. ilBindImage(image); // Try to load the data. bool success = (ilTexImage(width, height, 1, bpp, IL_RGBA, IL_UNSIGNED_BYTE, data) == IL_TRUE); if(!success) { int err = ilGetError(); if (err != IL_NO_ERROR){ switch (err) { case IL_ILLEGAL_OPERATION: throw love::Exception("Error: Illegal operation"); break; case IL_INVALID_PARAM: throw love::Exception("Error: invalid parameters"); break; case IL_OUT_OF_MEMORY: throw love::Exception("Error: out of memory"); break; default: throw love::Exception("Error: unknown error"); break; } } throw love::Exception("Could not decode image data."); } } ImageData::~ImageData() { ilDeleteImages(1, &image); } int ImageData::getWidth() const { return width; } int ImageData::getHeight() const { return height; } void * ImageData::getData() const { ilBindImage(image); return ilGetData(); } int ImageData::getSize() const { return width*height*bpp; } void ImageData::setPixel(int x, int y, pixel c) { //int tx = x > width-1 ? width-1 : x; //int ty = y > height-1 ? height-1 : y; // not using these seems to not break anything if (x > width-1 || y > height-1 || x < 0 || y < 0) throw love::Exception("Attempt to set out-of-range pixel!"); pixel * pixels = (pixel *)getData(); pixels[y*width+x] = c; } pixel ImageData::getPixel(int x, int y) const { //int tx = x > width-1 ? width-1 : x; //int ty = y > height-1 ? height-1 : y; // not using these seems to not break anything if (x > width-1 || y > height-1 || x < 0 || y < 0) throw love::Exception("Attempt to get out-of-range pixel!"); pixel * pixels = (pixel *)getData(); return pixels[y*width+x]; } EncodedImageData * ImageData::encode(EncodedImageData::Format f) { ilBindImage(image); ILubyte * data; ILuint w = getWidth(); int h = getHeight(); // has to be a signed int so we can make it negative for BMPs int headerLen, bpp, row, size, padding, filesize; switch (f) { case EncodedImageData::FORMAT_BMP: headerLen = 54; bpp = 3; row = w * bpp; padding = row & 3; size = h * (row + padding); filesize = size + headerLen; data = new ILubyte[filesize]; // Here's the header for the BMP file format. data[0] = 66; // "B" data[1] = 77; // "M" data[2] = filesize & 255; // size of the file data[3] = (filesize >> 8) & 255; data[4] = (filesize >> 16) & 255; data[5] = (filesize >> 24) & 255; data[6] = data[7] = data[8] = data[9] = 0; // useless reserved values data[10] = headerLen; // offset where pixel data begins data[11] = (headerLen >> 8) & 255; data[12] = (headerLen >> 16) & 255; data[13] = (headerLen >> 24) & 255; data[14] = headerLen - 14; // length of this part of the header data[15] = ((headerLen - 14) >> 8) & 255; data[16] = ((headerLen - 14) >> 16) & 255; data[17] = ((headerLen - 14) >> 24) & 255; data[18] = w & 255; // width of the bitmap data[19] = (w >> 8) & 255; data[20] = (w >> 16) & 255; data[21] = (w >> 24) & 255; data[22] = -h & 255; // negative height of the bitmap - used so we don't have to flip the data data[23] = ((-h) >> 8) & 255; data[24] = ((-h) >> 16) & 255; data[25] = ((-h) >> 24) & 255; data[26] = 1; // number of color planes data[27] = 0; data[28] = bpp * 8; // bits per pixel data[29] = 0; data[30] = data[31] = data[32] = data[33] = 0; // RGB - no compression data[34] = (row + padding) * h; // length of the pixel data data[35] = (((row + padding) * h) >> 8) & 255; data[36] = (((row + padding) * h) >> 16) & 255; data[37] = (((row + padding) * h) >> 24) & 255; data[38] = 2835 & 255; // horizontal pixels per meter data[39] = (2835 >> 8) & 255; data[40] = (2835 >> 16) & 255; data[41] = (2835 >> 24) & 255; data[42] = 2835 & 255; // vertical pixels per meter data[43] = data[39]; data[44] = data[40]; data[45] = data[41]; data[46] = data[47] = data[48] = data[49] = 0; // number of colors in the palette data[50] = data[51] = data[52] = data[53] = 0; // all colors are important! // Okay, header's done! Now for the pixel data... data += headerLen; for (int i = 0; i < h; i++) { // we've got to loop through the rows, adding the pixel data plus padding ilCopyPixels(0,i,0,w,1,1,IL_BGR,IL_UNSIGNED_BYTE,data); data += row; } data -= filesize; break; case EncodedImageData::FORMAT_TGA: default: // TGA is the default format headerLen = 18; bpp = 4; size = h * w * bpp; data = new ILubyte[size + headerLen]; // here's the header for the Targa file format. data[0] = 0; // ID field size data[1] = 0; // colormap type data[2] = 2; // image type data[3] = data[4] = 0; // colormap start data[5] = data[6] = 0; // colormap length data[7] = 32; // colormap bits data[8] = data[9] = 0; // x origin data[10] = data[11] = 0; // y origin // Targa is little endian, so: data[12] = w & 255; // least significant byte of width data[13] = w >> 8; // most significant byte of width data[14] = h & 255; // least significant byte of height data[15] = h >> 8; // most significant byte of height data[16] = bpp * 8; // bits per pixel data[17] = 0x20; // descriptor bits (flip bits: 0x10 horizontal, 0x20 vertical) // header done. write the pixel data to TGA: data += headerLen; ilCopyPixels(0,0,0,w,h,1,IL_BGRA,IL_UNSIGNED_BYTE,data); // convert the pixels to BGRA (remember, little-endian) and copy them to data data -= headerLen; } return new EncodedImageData(data, f, size + headerLen, freeData); } void ImageData::freeData(void *data) { delete[] (ILubyte*) data; } } // devil } // image } // love
true
7093084f4a57d9aae6016efafa608e87e66943d5
C++
edweenie123/competitive-programming-solutions
/CF/519D-A-and-B-and-Interesting-Substrings.cpp
UTF-8
1,792
3.265625
3
[]
no_license
/* ~~~ 519D - A and B and Interesting Substrings ~~~ Key Concepts: PSA, Map, Insight? Weird problem Let's contructs a PSA for the values of the string The condition for an interesting subarray is as follows: Let the subarray be defined as [i, j] The subarray is interesting if: 1. s[i] = s[j] AND 2. psa[j-1] - psa[i] = 0 -> psa[j-1] = psa[i] With this in mind lets try to find the number of interesting subsequences that end at index p => x For this p, we want to find the number of starting indices k such that s[p] = s[k] and psa[p-1] = psa[k] (these are the condiction for interesting array) also k < p How do we find the # of k efficiently? We use a map to store the frequency of each prefix sum If we iterate through the indices in order -> it gurantees that k < p My explanation is pretty bad */ #include<bits/stdc++.h> using namespace std; typedef long long ll; const int MAXN = 1e5 + 5; int val[26]; long long psa[MAXN]; vector<int> idx[26]; map<ll, int> psaFreq; int main() { cin.sync_with_stdio(0); cin.tie(0); int v; for (int i=0;i<26;i++) { cin>>val[i]; } string s; cin>>s; s = ' ' + s; // build psa for s for (int i=1;i<s.length();i++) { psa[i] = psa[i-1] + val[s[i] - 'a']; } for (int i=1;i<s.length();i++) { idx[s[i]-'a'].push_back(i); // get idx of each char type } ll ans = 0; for (int i=0;i<26;i++) { psaFreq.clear(); for (auto p : idx[i]) { // want to find # of k such that // psa[p-1] - psa[k] = 0 -> psa[p-1] = psa[k] int numK = psaFreq[psa[p-1]]; ans += numK; psaFreq[psa[p]]++; } } cout<<ans<<"\n"; }
true
6d3b334a65643d899ca82a6261f3e8f1537760b1
C++
cstrainge/basically
/source.cpp
UTF-8
2,197
3.21875
3
[]
no_license
#include "basically.h" namespace basically::source { void Location::next() noexcept { ++column; } void Location::next_line() noexcept { ++line; column = 1; } std::ostream& operator <<(std::ostream& stream, Location const& location) { stream << location.path.string() << "(" << location.line << ", " << location.column << ")"; return stream; } Buffer::Buffer(std::string const& new_text, std::fs::path const& new_path) : text(new_text), index(0), location({ .path = new_path }) { } Buffer::Buffer(std::istream& stream, std::fs::path const& new_path) : Buffer(read_from(stream), new_path) { } Buffer::Buffer(std::fs::path const& new_path) : Buffer(read_from(new_path), new_path) { } Buffer::operator bool() const noexcept { return !text.empty() && index < text.size(); } OptionalChar Buffer::peek_next(size_t lookahead) const noexcept { auto next_index = index + lookahead; if (next_index >= text.size()) { return {}; } return text[next_index]; } OptionalChar Buffer::next() noexcept { auto next_char = peek_next(); if (!next_char) { return next_char; } ++index; if (next_char.value() == '\n') { location.next_line(); } else { location.next(); } return next_char; } Location const& Buffer::current_location() const noexcept { return location; } std::string Buffer::read_from(std::istream& stream) const { auto begin = std::istreambuf_iterator<char>(stream); auto end = std::istreambuf_iterator<char>(); return std::string(begin, end); } std::string Buffer::read_from(std::fs::path const& path) const { auto file = std::ifstream(path.string()); if (!file.is_open()) { throw std::runtime_error("Could not open source file " + path.string() + "."); } return read_from(file); } }
true
129d01e34329d6feebf3559b25c9a19d877fa9ea
C++
Redleaf23477/ojcodes
/acmicpc/2015-Singapore/A.cpp
UTF-8
1,748
2.5625
3
[]
no_license
// #include <bits/stdc++.h> #define endl '\n' using namespace std; typedef long long int ll; const int N = 220; struct Node { int r, c, idx; }; bool operator < (const Node &lhs, const Node &rhs) { if(lhs.r != rhs.r) return lhs.r < rhs.r; if(lhs.c != rhs.c) return lhs.c < rhs.c; return lhs.idx < rhs.idx; } int n, sr, sc, len; int dr[N], dc[N]; string str; char grid[N][N]; void init(); void process(); int main() { ios::sync_with_stdio(false); cin.tie(0); init(); process(); cout.flush(); return 0; } void init() { cin >> n >> str; len = str.size(); // cout << "len = " << len << endl; for(int r = 0; r < n; r++) for(int c = 0; c < n; c++) { cin >> grid[r][c]; if(grid[r][c] == 'R') sr = r, sc = c; } for(size_t i = 0; i < str.size(); i++) { if(str[i] == '<') dr[i] = 0, dc[i] = -1; else if(str[i] == '>') dr[i] = 0, dc[i] = 1; else if(str[i] == '^') dr[i] = -1, dc[i] = 0; else dr[i] = 1, dc[i] = 0; } } void process() { map<Node, int> mp; int r = sr, c = sc, nr, nc, idx = 0, tim = 0; while(true) { // skip for(int cnt = 0; ; cnt++, idx = (idx+1)%len) { if(cnt == len) { cout << 1 << endl; return; } nr = r+dr[idx], nc = c+dc[idx]; if(grid[nr][nc] == '#') continue; break; } // cout << ".." << r << " " << c << " " << idx << " " << tim << endl; Node cur = (Node){r,c,idx}; // check if(mp.count(cur) != 0) { cout << tim - mp[cur] << endl; return; } mp[cur] = tim++; r = nr, c = nc, idx = (idx+1)%len; } }
true
9ba236efec6ba17849588471bc1e1e7718402645
C++
Prateek4658/ACM-ICPC-Algorithms
/Data Structures/Stack/BalancedParanthesis/BalancedParanthesisStack.cpp
UTF-8
736
2.734375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { stack<string>s1,s2; int n,i; string s; cin>>n; for(i=1;i<=n;i++) { cin>>s; for(i=0;s[i]!='/0';i++) { if(s[i]=='[' || s[i]=='(' || s[i]='{') s1.push(s[i]); else { while(!s1.isEmpty()){ if(s[i]==')' && s1.top()=='(' || s[i]==']' && s1.top()=='['|| s[i]=='}' && s1.top()=='{' ) s1.pop(); if(s1.isEmpty()){ cout<<"Yes"<<endl; break; } else cout<<"No"<<endl; } } } } return 0; }
true
c37625b7243053e77815f84147b76a95f62ad80d
C++
quyang19/Mytest
/link/link/link/link1.cpp
UTF-8
1,500
2.578125
3
[]
no_license
// // link1.cpp // link // // Created by 李应鹏 on 2018/11/13. // Copyright © 2018 李应鹏. All rights reserved. // #include "link1.hpp" #include <stack> #include <iostream> using namespace std; typedef struct LinkNode { int value; struct LinkNode *pNext; }LinkNode, *Link; typedef struct doubleLink { int value; doubleLink *pre; doubleLink *next; }; typedef struct doubleLink { int value; doubleLink *pre; doubleLink *next; }; typedef struct { Node *pre; Node *next; }Node; typedef struct { Node node; int mvlan; int group; }igmp_st; typedef struct { Node node; int count; }List; insert(List) { List } void recurse(Link head) { if(head==NULL) { return; } else { recurse(head->pNext); } printf("%d\n",head->value); } int main(int argc, const char * argv[]) { Link head = (Link)malloc(sizeof(LinkNode)); Link pNew; Link tail = head; Link pNode; Link hhh = new LinkNode; int a[5]; int i = 0; stack<Link> first; List head; head = for( i=0; i<5; i++) { pNew = (Link)malloc(sizeof(LinkNode)); pNew->value = i; pNew->pNext = NULL; tail->pNext = pNew; tail = pNew; first.push(pNew); } recurse(head); #if 0 while (!first.empty()) { pNode = first.top(); cout << pNode->value << " "; first.pop(); } #endif return 0; }
true
59e0be59c33cbc7a2981b73ba8d382fd08f82926
C++
TBueter/CS328_Final_Project
/test_symmetricalMatrix.cpp
UTF-8
3,162
3.453125
3
[]
no_license
/************************************************************ Filename: test_SymmetricalMatrix.cpp Programmer: Paul Sites Class: CS5201 Assignment: 6 - An Abstract Matrix Class w/ More Derivatives Date: 2015.04.22 Desc: This is the SymmetricalMatrix unit-test file. It contains methods to test the SymmetricalMatrix class. ************************************************************/ #if google_test_enabled #include <cmath> #include <iostream> #include <gtest/gtest.h> #include "SymmetricalMatrix.h" using std::cout; using std::endl; using std::log; TEST(SymmetricalMatrixTest, Print) { /* This one is just a visual test to make sure * that the matrix is printing out as expected. */ SymmetricalMatrix<int> sym(4); int z = 0; for(int i=0; i<4; i++) for(int j=0; j<4; j++) sym(i, j) = z++; //cout<<sym<<endl; ASSERT_EQ(true,true); } TEST(SymmetricalMatrixTest, Operator_Assignment) { SymmetricalMatrix<int> orignal(4); SymmetricalMatrix<int> copy; int z = 0; for(int i=0; i<4; i++) for(int j=0; j<4; j++) orignal(i, j) = z++; copy = orignal; ASSERT_EQ(orignal,copy); } TEST(SymmetricalMatrixTest, Operator_MatrixAssignment) { SymmetricalMatrix<int> expected(4); SymmetricalMatrix<int> copy; int z = 0; for(int i=0; i<4; i++) for(int j=0; j<4; j++){ expected(i, j) = z++; } Matrix<int> original(expected); copy = original; ASSERT_EQ(expected,copy); } TEST(SymmetricalMatrixTest, Symmetric_Verify) { SymmetricalMatrix<int> sym(5); int z = 0; for(int i=0; i<5; i++) for(int j=0; j<5; j++){ sym(i, j) = z++; } for(int i=0; i<5; i++) for(int j=0; j<5; j++){ ASSERT_EQ(sym(i, j),sym(j, i)); } } TEST(SymmetricalMatrixTest, Operator_Add) { SymmetricalMatrix<int> sym1(4); SymmetricalMatrix<int> sym2(4); sym1.SetAll(10); sym2.SetAll(15); SymmetricalMatrix<int> result(sym1 + sym2); SymmetricalMatrix<int> expected(4); expected.SetAll(25); ASSERT_EQ(result,expected); } TEST(SymmetricalMatrixTest, Operator_AddEquals) { SymmetricalMatrix<int> sym1(4); SymmetricalMatrix<int> sym2(4); sym1.SetAll(10); sym2.SetAll(15); sym1 += sym2; SymmetricalMatrix<int> expected(4); expected.SetAll(25); ASSERT_EQ(sym1,expected); } TEST(SymmetricalMatrixTest, Operator_Sub) { SymmetricalMatrix<int> sym1(4); SymmetricalMatrix<int> sym2(4); sym1.SetAll(10); sym2.SetAll(15); SymmetricalMatrix<int> result(sym1-sym2); SymmetricalMatrix<int> expected(4); expected.SetAll(-5); ASSERT_EQ(result,expected); } TEST(SymmetricalMatrixTest, Operator_SubEquals) { SymmetricalMatrix<int> sym1(4); SymmetricalMatrix<int> sym2(4); sym1.SetAll(10); sym2.SetAll(15); sym1 -= sym2; SymmetricalMatrix<int> expected(4); expected.SetAll(-5); ASSERT_EQ(sym1,expected); } TEST(SymmetricalMatrixTest, Operator_VectorMult) { SymmetricalMatrix<int> A(3); A.SetAll(4); Vector<int> x(3); x[0] = 2; x[1] = 2; x[2] = 2; Vector<int> b = A*x; Vector<int> expect(3); expect[0] = 24; expect[1] = 24; expect[2] = 24; ASSERT_EQ(expect, b); } #endif
true
550cfeefa40fc54eac1f404482b6268280416aea
C++
minhquanym/SlidingPuzzle
/RandomStart.cpp
UTF-8
2,280
2.515625
3
[]
no_license
namespace RandomStart { const int limitTimeSwap = 1e6; int h[4] = { 0, -1, 1, 0 }; int c[4] = { -1, 0, 0, 1 }; void randomStart(Board &board) { srand(time(NULL)); int TimeSwap = limitTimeSwap + 1, preDir = -1; for (int i = 1; i <= TimeSwap; ++i) { int x = board.Space_location.first, y = board.Space_location.second; int dir = rand() % 4; while (true) { dir = (dir + 1) % 4; if ( dir == 3-preDir ) continue; int u = x + h[dir], v = y + c[dir]; if ( !board.inBoard(u, v) ) continue; break; } preDir = dir; int u = x + h[dir], v = y + c[dir]; assert( board.inBoard(u, v) ); std::swap( board.a[u][v], board.a[x][y] ); std::swap( board.TilePos[ board.a[u][v] ].x, board.TilePos[ board.a[x][y] ].x ); std::swap( board.TilePos[ board.a[u][v] ].y, board.TilePos[ board.a[x][y] ].y ); board.Space_location = std::make_pair(u, v); } while ( board.Space_location.first != (int) board.a.size() - 1 ) { int dir = 2; int x = board.Space_location.first, y = board.Space_location.second; int u = x + h[dir], v = y + c[dir]; assert( board.inBoard(u, v) ); std::swap( board.a[u][v], board.a[x][y] ); std::swap( board.TilePos[ board.a[u][v] ].x, board.TilePos[ board.a[x][y] ].x ); std::swap( board.TilePos[ board.a[u][v] ].y, board.TilePos[ board.a[x][y] ].y ); board.Space_location = std::make_pair(u, v); } while ( board.Space_location.second != (int) board.a.size() - 1 ) { int dir = 3; int x = board.Space_location.first, y = board.Space_location.second; int u = x + h[dir], v = y + c[dir]; assert( board.inBoard(u, v) ); std::swap( board.a[u][v], board.a[x][y] ); std::swap( board.TilePos[ board.a[u][v] ].x, board.TilePos[ board.a[x][y] ].x ); std::swap( board.TilePos[ board.a[u][v] ].y, board.TilePos[ board.a[x][y] ].y ); board.Space_location = std::make_pair(u, v); } } }
true
4e919d8c49bd32fbe478f2377e250b3ebf26578c
C++
snikk/Junk
/test/glfw/engine/actor/Actor.h
UTF-8
1,247
2.671875
3
[]
no_license
#ifndef __ACTOR_H__ #define __ACTOR_H__ #include "../common.h" #include "ActorComponent.h" typedef unsigned int ActorId; class Actor { friend class ActorFactory; public: typedef std::map<ComponentId, StrongActorComponentPtr> ActorComponents; private: ActorId m_id; ActorComponents m_components; std::string m_type; public: explicit Actor(ActorId id); ~Actor(void); bool Init(const rapidjson::Value& val); void PostInit(void); void Destroy(void); void Update(int deltaMs); ActorId GetId(void) const { return m_id; } template <class ComponentType> std::weak_ptr<ComponentType> GetComponent(ComponentId id) { ActorComponents::iterator findIt = m_components.find(id); if (findIt != m_components.end()) { StrongActorComponentPtr pBase(findIt->second); std::shared_ptr<ComponentType> pSub(std::static_pointer_cast<ComponentType>(pBase)); std::weak_ptr<ComponentType> pWeakSub(pSub); return pWeakSub; } else { return std::weak_ptr<ComponentType>(); } } const ActorComponents* GetComponents() { return &m_components; } void AddComponent(StrongActorComponentPtr pComponent); }; #endif
true