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
2d522baf43293a7e39cb56abb915aa7d883b6bbf
C++
OscarMeyer/DD2380-Artificial-Intelligence
/HMM1/matrix_pre/matrix_start.cpp
UTF-8
602
3.421875
3
[]
no_license
#include <iostream> using namespace std; int main() { /*Test matrix*/ int m[3][3] = { {1,2,3}, {4,5,6}, {7,8,9} }; int i; cout << "Please enter int: "; cin >> i; cout << "Value: " << i << "\n"; cout << "Double: " << i*2 << "\n"; cout << "mat: " << m[3][3] << "\n"; int b[2][3] = {{1,2,3}, {7,8,9}}; for(int row=0; row<2; row++){ for(int column=0; column<3; column++){ cout << b[row][column] << " "; } cout << endl; } return 0; }
true
7f270a6f703e1965711822ec2ffa8d5091e2e691
C++
EXPmaster/CouseProjectC
/task8/7.cpp
UTF-8
1,966
3.03125
3
[]
no_license
#if 0 #include <stdio.h> #include <stdlib.h> #include <string.h> void fun(char *str, int *number, char *target); char *s_gets(char *); int main() { int number = 0; char str[100], target[100]; s_gets(str); fun(str, &number, target); printf("%s\n%d\n", target, number); return 0; } char *s_gets(char *str) { char *ret_val, *find; puts("请输入单词,以空格结束"); ret_val = fgets(str, 100, stdin); if (ret_val) { find = strchr(str, '\n'); if (*(find - 1) != ' ') { puts("错误格式!"); exit(1); } if (find) *find = '\0'; else while (getchar() != '\n'); } return ret_val; } void fun(char *str, int *number, char *target) { char *begin, *end; char data[50][20] = {'\0'}; int i = 0, j = 0, k = 0; begin = str; end = strstr(begin, " "); while (end) { for (j = 0; begin <= end; begin++, j++) data[i][j] = *begin; begin = end + 1; end = strstr(begin, " "); i++; } char max[20] = "0"; for (int key = 0; key < i; key++) { if (strcmp(data[key], max) > 0) strcpy(max, data[key]); } //printf("%s\n%s\n",max,data[0]); //printf("k=%d\n",k); while (strcmp(max, data[k]) == 0 && k < i) { k++; } if (k == i) { puts("nothing in the array now!"); exit(0); } if (data[k][0] >= 'a' && data[k][0] <= 'z') { data[k][0] = data[k][0] - ('a' - 'A'); } for (int index = k; index < i; index++) { if (strcmp(max, data[index]) != 0) { if (data[index][0] >= 'a' && data[index][0] <= 'z') { data[index][0] = data[index][0] - ('a' - 'A'); } strcat(target, data[index]); (*number)++; } } //printf("%s\n",data[k]); } #endif
true
5009ab3a0f3c968dd9db43dfc86b15c3d35d5c75
C++
AnabaenaQing/Source-Code_ShaderX_GPU-Pro_GPU-Zen
/GPU Pro4/02_Rendering/06_Progressive Screen-space Multi-channel Surface Voxelization/src/cglib/utils.cpp
UTF-8
242
3.328125
3
[ "MIT" ]
permissive
#include <math.h> int exp2i (int val) { int i, p2 = 1; for (i = 0; i < val; i++) p2 <<= 1; return p2; } int getPowerOfTwo (int val) { int p2 = 1; while (p2 < val) p2 <<= 1; return p2; }
true
05bdba0722ef454528872cabe6ed67c304e49508
C++
divyagar/SportsQuiz
/sports_quiz.cpp
UTF-8
3,171
2.84375
3
[]
no_license
#include <iostream> using namespace std; #include <string> #include <algorithm> #include <bits/stdc++.h> #include <stdio.h> #include <conio.h> #include <thread> #include <chrono> #include <mutex> #include <condition_variable> class countries{ string country; vector<string> sports; int total_sports; public: void getInfo(string coun, queue<string> q, int totalSps){ country = coun; total_sports = totalSps; for(int i=0; i<totalSps; i++){ sports.push_back(q.front()); q.pop(); } } void display(){ cout << country << " "; vector<string>::iterator starting = sports.begin(); vector<string>::iterator end = sports.end(); for(starting; starting != end; starting++){ cout << *starting << "\n"; } } void showAns(){ vector<string>::iterator starting = sports.begin(); vector<string>::iterator index = sports.begin(); vector<string>::iterator end = sports.end(); while(index != end){ if(index != starting){ cout << " , "; } cout << *index; index++; } } void displayCountry(){ cout << country; } string getSport(){ srand((unsigned int)time(NULL)); int random = (rand() % total_sports); return sports[random]; } bool compareSports(string sport){ transform(sport.begin(), sport.end(), sport.begin(), ::tolower); vector<string>::iterator starting = sports.begin(); vector<string>::iterator end = sports.end(); for(starting; starting != end; starting++){ transform((*starting).begin(), (*starting).end(), (*starting).begin(), ::tolower); if(*starting == sport) return true; } } }; // global variables countries * couns; string * sportsList; vector<int> previousRandoms; vector<string> users; int total_sports=0, total_countries=0, previousScores, totalPoints=0; bool userExists = false, breaking = false; string ans; char mcq_ans; condition_variable cv; #include "functions.cpp" int main(){ // displaying rules and getting username int method; string username; method = displayRules(&username); // displaying rules and username ends here ifstream infile, sportsFile; // getting informations about countries and sports from country.txt and sports.txt openFiles(&infile, &sportsFile, &total_countries, &total_sports); couns = new countries[total_countries]; sportsList = new string[total_sports]; infile.seekg(0, ios::beg); sportsFile.seekg(0, ios::beg); getInfos(&infile, &sportsFile); infile.close(); sportsFile.close(); // getting file infos ends here if(method == 1) mcqQuestionsMain(); else oneWordQuestionsMain(); cout << "-------------------------------------------------Game Over-----------------------------------------------\n\n"; cout << "Your Score : " << totalPoints << "\n"; addUsers(&username, totalPoints); showFeedback(totalPoints); return 0; }
true
0e6865574755f5143a0293548fa8c0b27d7d5d4b
C++
novikov-ilia-softdev/thinking_cpp
/tom_1/chapter_03/13/printbinary.cpp
UTF-8
180
3.09375
3
[]
no_license
#include <iostream> void printBinary( const unsigned char val) { for( int i = 7; i >= 0; i--) { if( val bitand (1 << i)) std::cout << "1"; else std::cout << "0"; } }
true
5e8bcd6d4e4eb75a6ff88ce9c7acd3abdd10ebad
C++
IGME-RIT/VkHitboxes
/Code/Texture.h
UTF-8
529
2.84375
3
[]
no_license
#pragma once #include "BufferCPU.h" #include "TextureGPU.h" #include "Demo.h" // forward declaration class Demo; class Texture { public: int width; int height; // Texture data BufferCPU* textureCPU; TextureGPU* textureGPU; Texture(char* file); ~Texture(); static uint32_t CountMips(uint32_t width, uint32_t height) { if (width == 0 || height == 0 || width != height) return 0; uint32_t count = 1; while (width > 1 && height > 1) { width >>= 1; height >>= 1; count++; } return count; } };
true
6b4a872cbd938b39f28076f0711f267a55c1d934
C++
Jorgitou98/Acepta-el-Reto
/Soluciones/AceptaElReto583EncuestaComprometedora.cpp
UTF-8
364
2.5625
3
[]
no_license
#include <iostream> using namespace std; int main() { cin.sync_with_stdio(false); cin.tie(nullptr); int num_casos; cin >> num_casos; for (int i = 0; i < num_casos; ++i) { int comp, no_comp; cin >> comp >> no_comp; int mitad = (comp + no_comp) / 2; comp -= mitad; cout << ((long long int)comp * 100)/ mitad << '\n'; } return 0; }
true
125c9d8be3c67a33f2dcf110ca9ecafade1591fe
C++
alexandervanrenen/Gamera-Database
/src/external_sort/MergeSort.hpp
UTF-8
8,414
2.515625
3
[]
no_license
#pragma once #include <iostream> #include <algorithm> #include <sys/stat.h> #include "common/Config.hpp" #include "SortIterator.hpp" #include "btree/IndexKeyComparator.hpp" #include "btree/IndexKeySchema.hpp" #include "btree/IndexKey.hpp" #include "TempFile.hpp" #include "Chunk.hpp" namespace dbi { uint64_t filesize(fstream* f) { f->seekg(0, f->end); uint64_t length = f->tellg(); f->seekg(0, f->beg); return length; } class MergeSort { private: IndexKeySchema schema; IndexKeyComparator c; uint64_t bytes; uint64_t memsize; uint64_t pagesize; char* buffer; TempFile* tf; public: MergeSort(uint64_t pagesize, uint64_t memsize, IndexKeySchema schema, IndexKeyComparator c) : schema(schema), c(c), bytes(schema.bytes()), memsize(memsize - memsize%schema.bytes()), pagesize(pagesize) { assert(memsize % pagesize == 0); buffer = new char[memsize]; } ~MergeSort() { delete[] buffer; } Chunk* sortchunk(fstream *infile, fstream* outfile, uint64_t pos, uint64_t bufsize) { assert(bufsize > 0 && bufsize <= memsize); SortIterator ibuf = SortIterator(buffer, bytes); SortIterator ibufend = SortIterator(buffer+bufsize-bytes, bytes); infile->seekg(pos); infile->read(buffer, bufsize); assert((uint64_t)infile->gcount() == bufsize); dbi::sort(ibuf, ibufend, c, bytes); // For testing char* bufp1 = buffer; char* bufp2 = buffer+bytes; for (uint64_t i=bytes; i < bufsize; i+=bytes) { //std::cout << *((int32_t*)bufp2) << std::endl; assert(c.less(bufp1, bufp2)); bufp1 += bytes; bufp2 += bytes; } outfile->seekp(0); outfile->write(buffer, bufsize); return new Chunk{outfile, 0, bufsize, bytes}; } Chunk* mergesingle(fstream* outfile, vector<Chunk*> chunks) { //std::cout << "Mergesingle, pagesize: " << pagesize << std::endl; assert(chunks.size() * pagesize <= (memsize-pagesize)); int i = 0; // assign each chunk a part of the buffer for (auto chunk : chunks) { //std::cout << "Chunk " << i << " setting pagesize " << pagesize << std::endl; chunk->setbuffer(buffer+pagesize*i, pagesize); i++; } // prepare output buffer char* outbuf = buffer+pagesize*i;//new char[PAGESIZE]; char* saveoutbuf = outbuf; uint64_t size = 0; char* minval = new char[bytes]; bool invalid = false; std::memcpy(minval, chunks[0]->value(), bytes); while(true) { int i = 0; int minindex = 0; // find smallest value in currently loaded chunk parts for (auto chunk : chunks) { if (chunk->value() != nullptr && (c.less(chunk->value(), minval) || invalid)) { invalid = false; minindex = i; std::memcpy(minval, chunk->value(), bytes); } //std::cout << *((uint32_t*)chunk->value()) << std::endl; //if (chunk->value() != nullptr && chunks[minindex]->value() != nullptr && c.less(chunk->value(), chunks[minindex]->value())) { // minindex = i; //} i++; } if (chunks[minindex]->value() == nullptr || invalid) break; // no more values //std::memcpy(outbuf, chunks[minindex]->value(), bytes); std::memcpy(outbuf, minval, bytes); invalid = true; //std::cout << *((int32_t*)minval) << std::endl; chunks[minindex]->next(); outbuf += bytes; size += bytes; // if output buffer is full, write it to disk if (outbuf >= saveoutbuf+pagesize) { outfile->write(saveoutbuf, pagesize); outbuf = saveoutbuf; } } // if output buffer is not empty, write it to disk if (outbuf != saveoutbuf) { outfile->write(saveoutbuf, (char*)outbuf - saveoutbuf); } outfile->flush(); //std::cout << "Size of outfile: " << filesize(outfile) << std::endl; outfile->seekg(0, outfile->beg); assert(size > 0); delete[] minval; return new Chunk(outfile, 0, size, bytes); } Chunk* mergechunks(fstream* out, vector<Chunk*> chunks) { //std::cout << "mergechunks aufruf\n"; vector<Chunk*> secondrun; // Merge as many chunks as possible at once while ((memsize-pagesize) / chunks.size() < pagesize && chunks.size() > 1) { secondrun.push_back(chunks.back()); chunks.pop_back(); } assert(chunks.size() > 1); //std::cout << "Chunks in first run: " << chunks.size() << std::endl; //std::cout << "Chunks in second run: " << secondrun.size() << std::endl; Chunk* mergechunk1 = mergesingle(secondrun.size() != 0 ? tf->getStream() : out, chunks); Chunk* mergechunk2; // Merge the remaining chunks and then merge the two result chunks if (secondrun.size() > 0) { if (secondrun.size() > 1) mergechunk2 = mergechunks(tf->getStream(), secondrun); else mergechunk2 = secondrun.back(); vector<Chunk*> finalrun = {mergechunk1, mergechunk2}; Chunk* finalchunk = mergesingle(out, finalrun); mergechunk1->close(tf); mergechunk2->close(tf); delete mergechunk1; if (secondrun.size() != 1) delete mergechunk2; return finalchunk; } else { return mergechunk1; } } int externalsort(string in, string out) { tf = new TempFile(out); struct stat st; if (stat(in.c_str(), &st) != 0) return 1; uint length = st.st_size; //std::cout << "Length of file: " << length << ", buffersize: " << memsize << std::endl; fstream infile; fstream* infilep = new fstream(); infile.open(in.c_str(), ios::binary | ios::in | ios::out); if (!infile.is_open()) // io error return 1; infilep->open(in.c_str(), ios::binary | ios::in | ios::out); assert(infilep->is_open()); //infile.exceptions ( std::ifstream::failbit | std::ifstream::badbit ); fstream outfile; outfile.open(out.c_str(), ios::binary | ios::out); if (!outfile.is_open()) return 1; vector<Chunk*> chunks; Chunk* finalchunk; // Entire file fits into memory if (length <= memsize) { finalchunk = sortchunk(&infile, &outfile, 0, length); } else { // split input file into chunks and sort them individually for (uint64_t i = 0; i < length; i+=memsize) { chunks.push_back(sortchunk(&infile, tf->getStream(), i, i+memsize > length ? length - i: memsize)); } // do a merge on the chunks finalchunk = mergechunks(&outfile, chunks); } // cleanup infile.close(); infilep->close(); delete infilep; for (auto chunk: chunks) delete chunk; outfile.flush(); outfile.close(); delete finalchunk; delete tf; return 0; } bool checksort(const char* filename) { ifstream file; file.open(filename, ios::binary | ios::in); file.seekg (0, file.end); uint64_t length = file.tellg(); //std::cout << "Length of file: " << length << std::endl; file.seekg (0, file.beg); char* buf = new char[length]; file.read(buf, length); char* bufp1 = buf; char* bufp2 = buf+bytes; for (uint64_t i=bytes; i < length; i+=bytes) { //std::cout << *((uint32_t*)bufp2) << std::endl; if (c.less(bufp2, bufp1)) { //std::cout << *((int32_t*)bufp1) << std::endl; //std::cout << *((int32_t*)bufp2) << std::endl; //std::cout << "Wrong number at " << i << std::endl; return false; } bufp1 += bytes; bufp2 += bytes; } delete[] buf; file.close(); return true; } }; }
true
4db404c98d4db4f411697db7ec004d34896f0a88
C++
eliasm2/problem-solving
/Treinos/2011-07-13-MidAtlantic2007/not AC/G-Bulls.cpp
UTF-8
725
2.53125
3
[]
no_license
#include <string> #include <set> #include <sstream> #include <iostream> #include <vector> using namespace std; vector<vector<int> > vet; vector<vector<int> > pos; int N, L; int solve(int pos = 0) { int bulls = vet[pos][N-2]; int cows = vet[pos][N-1]; } int main() { ios::sync_with_stdio(false); cin >> N; int x; while (N) { pos.clear(); vet.clear(); cin >> x; L = 0; while (x != -1) { vet[L].push_back(x); for (int i = 1; i < N+2; ++i) { cin >> x; vet[L].push_back(x); } L++; } for (int i = 1; i < N+2; ++i) cin >> x; pos.resize(N); for (int i = 0; i < N; ++i) { for (int j = 0; j < 10; ++j) pos[i].push_back(j); } solve(); cin >> N; } return 0; }
true
971bad0c73cdf57d86f6dc2fec9a7ecf3a06743c
C++
professor-oats/majo_raytracer
/vec3.h
UTF-8
4,240
3.65625
4
[]
no_license
#ifndef VEC3_H #define VEC3_H #include <cmath> #include <iostream> using std::sqrt; using std::fabs; // Will be using double cause low end specs class vec3 { public: vec3() : e{0,0,0} {} //creating vec3 constructor for a vector e... vec3(double e0, double e1, double e2) : e{e0, e1, e2} {} //initializing vec3 constructor telling it to take doubleed vector parameters from vector e double x() const { return e[0]; } //for x return position 0 e vector double y() const { return e[1]; } //for y return position 1 e vector double z() const { return e[2]; } //for z return position 2 e vector //now they correspond to a classical 3D system. vec3 operator-() const { return vec3(-e[0], -e[1], -e[2]); } //defining when using operator- so the negative value in each x y z to be returned double operator[](int i) const { return e[i]; } //when using operator[] define it as array with position i. double& operator[](int i) { return e[i]; } //when using operator[] with memory reference, return array value of position i. vec3& operator+=(const vec3 &v) { //when using operator+= on memory referenced vector v e[0] += v.e[0]; e[1] += v.e[1]; e[2] += v.e[2]; return *this; } vec3& operator*=(const double t) { e[0] *= t; e[1] *= t; e[2] *= t; return *this; } vec3& operator/=(const double t) { return *this *= 1/t; } double length() const { //calculating vector length return sqrt(length_squared()); } double length_squared() const { //vector length squared return e[0]*e[0] + e[1]*e[1] + e[2]*e[2]; } inline static vec3 random() { return vec3(random_double(), random_double(), random_double()); } inline static vec3 random(double min, double max) { return vec3(random_double(min,max), random_double(min,max), random_double(min,max)); } bool near_zero() const { // Return true if the vector is close to zero in all dimensions. const auto s = 1e-8; return (fabs(e[0]) < s) && (fabs(e[1]) < s) && (fabs(e[2]) < s); } public: double e[3]; }; // Type aliases for vec3 using point3 = vec3; //3D point using color = vec3; //RGB color // vec3 Utility Functions //making operator<< outputting vector correctly from memory reference inline std::ostream& operator<<(std::ostream &out, const vec3 &v) { return out << v.e[0] << ' ' << v.e[1] << ' ' << v.e[2]; } //just simple vector addition on vectors in memory reference inline vec3 operator+(const vec3 &u, const vec3 &v) { return vec3(u.e[0] + v.e[0], u.e[1] + v.e[1], u.e[2] + v.e[2]); } //vector substraction inline vec3 operator-(const vec3 &u, const vec3 &v) { return vec3(u.e[0] - v.e[0], u.e[1] - v.e[1], u.e[2] - v.e[2]); } inline vec3 operator*(const vec3 &u, const vec3 &v) { return vec3(u.e[0] * v.e[0], u.e[1] * v.e[1], u.e[2] * v.e[2]); } inline vec3 operator*(double t, const vec3 &v) { return vec3(t*v.e[0], t*v.e[1], t*v.e[2]); } inline vec3 operator*(const vec3 &v, double t) { return t * v; } inline vec3 operator/(vec3 v, double t) { return (1/t) * v; } //dotproduct inline double dot(const vec3 &u, const vec3 &v) { return u.e[0] * v.e[0] + u.e[1] * v.e[1] + u.e[2] * v.e[2]; } //crossproduct inline vec3 cross(const vec3 &u, const vec3 &v) { return vec3(u.e[1] * v.e[2] - u.e[2] * v.e[1], u.e[2] * v.e[0] - u.e[0] * v.e[2], u.e[0] * v.e[1] - u.e[1] * v.e[0]); } inline vec3 unit_vector(vec3 v) { return v / v.length(); } vec3 random_in_unit_sphere() { while(true) { auto p = vec3::random(-1,1); if (p.length_squared() >= 1) continue; return p; } } vec3 random_unit_vector() { return unit_vector(random_in_unit_sphere()); } vec3 reflect(const vec3& v, const vec3& n) { return v - 2*dot(v,n)*n; } vec3 refract(const vec3& uv, const vec3& n, double etai_over_etat) { auto cos_theta = fmin(dot(-uv, n), 1.0); vec3 r_out_perp = etai_over_etat * (uv + cos_theta*n); vec3 r_out_parallel = -sqrt(fabs(1.0 - r_out_perp.length_squared())) * n; return r_out_perp + r_out_parallel; } vec3 random_in_unit_disk() { while (true) { auto p = vec3(random_double(-1,1), random_double(-1,1), 0); if (p.length_squared() >= 1) continue; return p; } } #endif
true
6e5d73c1b0de278dc21eca18ad48862ad17c5781
C++
CDOTAD/ArrowShoot
/Classes/ArrowShoot/PauseLayer.cpp
UTF-8
3,934
2.5625
3
[]
no_license
#include"PauseLayer.h" #include"MainScene.h" int PauseLayer::step = 1; Scene* PauseLayer::CreateScene(){ auto scene = Scene::create(); auto layer = PauseLayer::create(); scene->addChild(layer); return scene; } bool PauseLayer::init(){ if (!Layer::create()){ return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); this->background = Sprite::createWithSpriteFrameName("pausebackground.png"); background->setPosition(visibleSize / 2); this->addChild(background, 1); auto pauseSprite = Sprite::createWithSpriteFrameName("pause.png"); pauseSprite->setPosition(visibleSize / 2); this->addChild(pauseSprite, 1); auto againButton = MenuItemSprite::create( Sprite::createWithSpriteFrameName("again.png"), Sprite::createWithSpriteFrameName("againOn.png"), CC_CALLBACK_1(PauseLayer::menuAgainCallBack, this)); auto resumeButton = MenuItemSprite::create( Sprite::createWithSpriteFrameName("continue.png"), Sprite::createWithSpriteFrameName("continueOn.png"), CC_CALLBACK_1(PauseLayer::menuResumeCallBack, this)); auto exitButton = MenuItemSprite::create( Sprite::createWithSpriteFrameName("exit.png"), Sprite::createWithSpriteFrameName("exitOn.png"), CC_CALLBACK_1(PauseLayer::menuExitCallBack, this)); auto menu = Menu::create(resumeButton,againButton,exitButton, NULL); menu->setPosition(visibleSize / 2); menu->alignItemsVertically(); this->addChild(menu, 1); return true; } void PauseLayer::menuResumeCallBack(Ref* pSender){ if (this->mainPlayLayer != NULL){ this->mainPlayLayer->flagPressed = false; if (this->mainPlayLayer->arrow->isflying == true){ this->mainPlayLayer->arrow->getArrowSprite()->getPhysicsBody()->setVelocity(this->mainPlayLayer->getSpeed()); this->mainPlayLayer->arrow->getArrowSprite()->getPhysicsBody()->setGravityEnable(true); } this->removeFromParentAndCleanup(true); Director::getInstance()->resume(); } else if (this->mainStep2Layer != NULL){ this->mainStep2Layer->flagPressed = false; if (this->mainStep2Layer->arrow->isflying == true){ this->mainStep2Layer->arrow->getArrowSprite()->getPhysicsBody()->setVelocity(this->mainStep2Layer->getSpeed()); this->mainStep2Layer->arrow->getArrowSprite()->getPhysicsBody()->setGravityEnable(true); } this->removeFromParentAndCleanup(true); Director::getInstance()->resume(); } else if (this->mainStep3Layer != NULL){ this->mainStep2Layer->flagPressed = false; if (this->mainStep3Layer->arrow->isflying == true){ this->mainStep3Layer->arrow->getArrowSprite()->getPhysicsBody()->setVelocity(this->mainStep3Layer->getSpeed()); this->mainStep3Layer->arrow->getArrowSprite()->getPhysicsBody()->setGravityEnable(true); } } } void PauseLayer::menuAgainCallBack(Ref* pSender){ if (this->mainPlayLayer != NULL){ this->removeFromParentAndCleanup(true); Director::getInstance()->resume(); Director::getInstance()->replaceScene( TransitionSplitRows::create(3.0f, MainScene::CreateScene())); } else if (this->mainStep2Layer != NULL){ this->removeFromParentAndCleanup(true); Director::getInstance()->resume(); Director::getInstance()->replaceScene( TransitionSplitRows::create(3.0f, MainStep2Scene::CreateScene())); } else if (this->mainStep3Layer != NULL){ this->removeFromParentAndCleanup(true); Director::getInstance()->resume(); Director::getInstance()->replaceScene( TransitionSplitRows::create(3.0f, MainStep3Scene::CreateScene())); } } void PauseLayer::menuExitCallBack(Ref* pSender){ #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.", "Alert"); return; #endif Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif }
true
89e66c22641070eb007de3aecd34e81ad98dac0b
C++
Slava/competitiveProgramming
/more-source/cycle/loop/ave(undef2).cpp
UTF-8
352
2.859375
3
[]
no_license
#include <iostream.h> int main () { int nrMark,mark,total; float ave; //cout<<"Enter first mark [0-100] : "; //cin>>mark; total=0; nrMark=0; while (mark!=0){ cout<<"Enter next mark [1-100] or 0 to finish : "; cin>>mark; total=total+mark; nrMark++; } nrMark--; ave=(float)total/nrMark; cout<<"Average is : "<<ave; return 0; }
true
620d511a56ae2882dfae330d6c2e00a65b120209
C++
Nauja/ue4-richtextblocktooltip-sample
/Source/Sample/SampleRichTextBlockTooltipDecorator.cpp
UTF-8
1,974
2.71875
3
[ "MIT" ]
permissive
#include "SampleRichTextBlockTooltipDecorator.h" #include "Widgets/SToolTip.h" #include "Widgets/Text/STextBlock.h" // Class charged of creating the inline tooltip class FSampleRichInlineTooltip : public FRichTextDecorator { public: FSampleRichInlineTooltip(URichTextBlock* InOwner, const FTextBlockStyle& InTextStyle, const FTextBlockStyle& InTooltipTextStyle) : FRichTextDecorator(InOwner) , TextStyle(InTextStyle) , TooltipTextStyle(InTooltipTextStyle) { } // Only valid if text is: <tooltip text="Some infos">Some text</> virtual bool Supports(const FTextRunParseResults& RunParseResult, const FString& Text) const override { return RunParseResult.Name == TEXT("tooltip") && RunParseResult.MetaData.Contains(TEXT("text")); } protected: /** * Create a STextBlock with a tooltip text. * * For <tooltip text="Some infos">Some text</>: * - RunInfo.Content is "Some text" * - RunInfo.MetaData[TEXT("text")] is "Some infos" */ virtual TSharedPtr<SWidget> CreateDecoratorWidget(const FTextRunInfo& InRunInfo, const FTextBlockStyle& InTextStyle) const override { return SNew(STextBlock) .Text(InRunInfo.Content) .TextStyle(&TextStyle) .ToolTip(SNew(SToolTip) [ SNew(STextBlock) .Text(FText::FromString(InRunInfo.MetaData[TEXT("text")])) .TextStyle(&TooltipTextStyle) ]); } private: FTextBlockStyle TextStyle; FTextBlockStyle TooltipTextStyle; }; ///////////////////////////////////////////////////// // USampleRichTextBlockTooltipDecorator USampleRichTextBlockTooltipDecorator::USampleRichTextBlockTooltipDecorator(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } // Return our custom class for creating the inline widget TSharedPtr<ITextDecorator> USampleRichTextBlockTooltipDecorator::CreateDecorator(URichTextBlock* InOwner) { return MakeShareable(new FSampleRichInlineTooltip(InOwner, TextStyle, TooltipTextStyle)); } /////////////////////////////////////////////////////
true
5e86f9eb38673855bb2323831bbfec745519bd7e
C++
Siwwyy/MY_PROJECTS
/!C++/Sorting/sortingg/sorting/Single_Element.h
UTF-8
2,024
2.984375
3
[]
no_license
// _SINGLE_ELEMENT_H_ standard header /* * Copyright (c) by Damian Andrysiak. All rights reserved. * *** WERSJA FINALNA *** * *** Koniec: 2/12/2018 *** * Klasa ma za zadanie: * 1. */ #ifndef _SINGLE_ELEMENT_H_ #define _SINGLE_ELEMENT_H_ #pragma once /* SPACE FOR INCLUDING */ //Compiler files #include <string> #include <iostream> #include <vector> #include <iomanip> #include <windows.h> /////////////////////////// //User files /////////////////////////// class Single_Element { private: /* PRIVATE VARIABLES */ std::vector<char> elements; uint8_t height; char element_view; static uint8_t max_height; ////////////////////////////////////////////////////////////////////////////// protected: /* PROTECTED VARIABLES */ ////////////////////////////////////////////////////////////////////////////// public: /* KONSTRUKTORY */ Single_Element(); //konstruktor bezparametrowy Single_Element(const Single_Element & object); //konstruktor kopiujacy ////////////////////////////////////////////////////////////////////////////// /* FUNKCJE PUBLIC */ void Write_Element() const; void Fill_Vector(); ////////////////////////////////////////////////////////////////////////////// /* SETTERY */ void Set_Height(const int Y); void Set_Vector_Element_View(const char element_view); ////////////////////////////////////////////////////////////////////////////// /* GETTERY */ uint8_t get_height() const; uint8_t get_max_height() const; size_t get_vector_size() const; ////////////////////////////////////////////////////////////////////////////// /* OPERATORY */ //JEDNOARGUMENTOWE Single_Element & operator=(const Single_Element & Object); //DWUARGUMENTOWE ////////////////////////////////////////////////////////////////////////////// /* DESTRUKTOR */ ~Single_Element(); //destruktor wirtualny na wypadek dziedziczenia ////////////////////////////////////////////////////////////////////////////// }; #endif /* _SINGLE_ELEMENT_H_ */
true
7163c30a8edae1795203d5834f06bef40727198f
C++
REPOmAN2v2/Cursed-engine
/engine/Menu/Items/MenuItemList.cpp
UTF-8
1,195
2.796875
3
[ "MIT" ]
permissive
#include <utility> #include "engine/Config/Globals.hpp" #include "engine/Keys.hpp" #include "engine/Menu/Items/MenuItemList.hpp" #include "engine/window.hpp" MenuItemList::MenuItemList( const char *label, unsigned id, MenuItem::Type type, std::vector<std::string> list, std::string def): MenuItem(label, id, type), list(std::move(list)), def(std::move(def)), index(0) { reset(); } using namespace Globals; void MenuItemList::draw(Window *window, bool cur, int w, int y, int x) { std::string opt = list[index]; window->print(label.substr(0, w - opt.size()), y, x, cur ? Globals::text["highlight"] : Globals::text["normal"]); window->print(opt, y, w - opt.size(), cur ? Globals::text["highlight"] : Globals::text["normal"]); } void MenuItemList::update(Key key) { if (key.val == Key::LEFT) { if (index != 0) { --index; } else { index = list.size() - 1; } } else if (key.val == Key::RIGHT) { if ((index + 1) < list.size()){ ++index; } else { index = 0; } } } std::string MenuItemList::getValue() { return list[index]; } void MenuItemList::reset() { for (size_t i = 0; i < list.size(); ++i) { if (list[i] == def) { index = i; break; } } }
true
7d70a46dfca8364fa63d8697836bc9cf5d60ec2a
C++
Taka-Kazu/spline_interpolation
/src/test.cpp
UTF-8
610
2.59375
3
[ "MIT" ]
permissive
#include "spline_interpolation/b_spline.h" int main(void) { spline_interpolation::BSpline bs; std::vector<Eigen::VectorXd> points; points.push_back(Eigen::Vector2d(0, 0)); points.push_back(Eigen::Vector2d(1, 0)); points.push_back(Eigen::Vector2d(1, 1)); points.push_back(Eigen::Vector2d(0, 1)); bs.set_degree(2); bs.set_control_points(points, spline_interpolation::BSpline::KnotType::OPEN_UNIFORM); for(double t=0.0;t<1.0;t+=0.01){ const auto v = bs.get_vector(t); std::cout << "t=" << t << ": " << v(0) << ", " << v(1) << std::endl; } return 0; }
true
71e909ed60fba14dbd40066b605d62e77823a5ce
C++
caballeto/mcc
/src/TypeChecker.cc
UTF-8
33,102
2.96875
3
[]
no_license
// // Created by vladyslav on 03.02.20. // #include "ErrorReporter.h" #include "TypeChecker.h" #include "Visitor.h" namespace mcc { // Rewrite ErrorReporter to support different error reporting // Implement type checking for new types (short, int, long, void) // Implement code generation for new types // testing routines + tests with gtest bool TypeChecker::IsPointer(Expr* expr) { if (expr == nullptr) return false; return expr->type_.IsPointer(); } bool TypeChecker::IsIntegerType(Expr* expr) { if (expr == nullptr) return false; return expr->type_.IsPrimitive() && !expr->type_.IsVoid(); } // #TODO: assign of structs bool TypeChecker::MatchTypeInit(const Type& type, Expr* init) { if (init->type_.type_ == TokenType::T_NONE) return false; if (!type.IsPointer()) { return IsPointer(init) ? true : (int) type.type_ >= (int) init->type_.type_; } else { if (type.type_ != init->type()|| type.ind != init->ind()) reporter_.Warning("Assign of different type to pointer without a cast ", type, init, init->op_); return true; } } // #TODO: build type hierarchy as a separate structure and provide API for type casting // assuming types are not void bool TypeChecker::MatchTypes(Expr* e1, Expr* e2, bool to_left, Expr* expr) { if (e1->type_.IsVoid() || e2->type_.IsVoid()) { reporter_.Error("Invalid operands types in binary expression, 'void' is not allowed", e1, e2, expr->op_); return false; } if (IsPointer(e1) && IsPointer(e2)) { return MatchPointers(e1, e2, to_left, expr); } else if (!IsPointer(e1) && !IsPointer(e2)) { return MatchPrimitives(e1, e2, to_left, expr); } else { return MatchMixed(e1, e2, to_left, expr); } } bool TypeChecker::MatchPointers(Expr* e1, Expr* e2, bool to_left, Expr* binary) { if (to_left && binary->op_->GetType() == TokenType::T_ASSIGN) { // FIXME: issue warnings on incompatible pointer casts binary->type_ = e1->type_; return true; } if (e1->type() != e2->type() || e1->ind() != e2->ind()) { reporter_.Error("Invalid operands types in binary expression", e1, e2, binary->op_); } else if (binary->op_->GetType() != TokenType::T_MINUS) { reporter_.Error("Invalid binary operation for types", e1, e2, binary->op_); } else { binary->type_.type_ = TokenType::T_LONG; // pointer subtraction yields long binary->type_.ind = 0; return true; } return false; } bool TypeChecker::MatchPrimitives(Expr* e1, Expr* e2, bool to_left, Expr* binary) { if (e1->type() == e2->type()) { binary->type_ = e1->type_; return true; } // FIXME: fix for structs if (!IsIntegerType(e1) || !IsIntegerType(e2)) { reporter_.Error("Invalid operands types in binary expression", e1, e2, binary->op_); return false; } binary->type_ = to_left ? PromoteToLeft(e1, e2) : PromotePrim(e1, e2); return true; } bool TypeChecker::MatchMixed(Expr* e1, Expr* e2, bool to_left, Expr* binary) { if (binary->op_->GetType() == TokenType::T_ASSIGN) { // assign binary->type_ = e1->type_; reporter_.Warning("Assignment with pointer/integer without a cast ", e1, e2, binary->op_); } else if (IsComparison(binary->op_->GetType())) { // comparison binary->type_.type_ = TokenType::T_INT; binary->type_.ind = 0; reporter_.Warning("Comparison between pointer and integer ", e1, e2, binary->op_); } else if (binary->op_->GetType() != TokenType::T_PLUS && binary->op_->GetType() != TokenType::T_MINUS) { reporter_.Error("Invalid operand for pointer arithmetic, only '+' and '-' allowed", e1, e2, binary->op_); return false; } else if (IsIntegerType(e1) && IsPointer(e2)) { // +, - for (int + pointer) if (binary->op_->GetType() == TokenType::T_MINUS) { // #TODO: check if can (x - ptr) reporter_.Error("Invalid operand for pointer arithmetic, only '+' allowed (int + ptr)", e1, e2, binary->op_); return false; } binary->type_ = e2->type_; e1->to_scale_ = true; } else if (IsIntegerType(e2) && IsPointer(e1)) { // +, - for (pointer + int) binary->type_ = e1->type_; e2->to_scale_ = true; } else { reporter_.Error("Invalid types for pointer arithmetic in binary expression", e1, e2, binary->op_); return false; } return true; } Type& TypeChecker::PromoteToLeft(Expr* e1, Expr* e2) { int t1 = (int) e1->type_.type_, t2 = (int) e2->type_.type_; if (t1 < t2) { reporter_.Error("Could not cast right expression ", e1, e2, e1->op_); e1->type_.type_ = TokenType::T_NONE; return e1->type_; } return e1->type_; } Type& TypeChecker::PromotePrim(Expr* e1, Expr* e2) { int t1 = (int) e1->type_.type_, t2 = (int) e2->type_.type_; return t1 > t2 ? e1->type_ : e2->type_; } // #FIXME: code gen of conditions with '!' void TypeChecker::Visit(Unary& unary) { if (unary.expr_ != nullptr) { unary.expr_->is_const_ = unary.is_const_; } switch (unary.op_->GetType()) { case TokenType::T_PLUS: case TokenType::T_MINUS: case TokenType::T_NOT: case TokenType::T_NEG: { unary.expr_->Accept(*this); unary.type_ = unary.expr_->type_; return; } case TokenType::T_SIZEOF: { // GetOffset gets type of value if (unary.expr_ == nullptr) { int size = GetSizeOf(unary.type_); unary.op_->SetInt(size); } else { unary.expr_->Accept(*this); int size = GetSizeOf(unary.expr_->type_); unary.op_->SetInt(size); } unary.type_.name = nullptr; unary.type_.type_ = TokenType::T_INT; unary.type_.ind = 0; unary.type_.len = 0; unary.expr_ = nullptr; break; } case TokenType::T_INC: case TokenType::T_DEC: case TokenType::T_BIT_AND: { unary.expr_->return_ptr_ = true; unary.expr_->Accept(*this); if (!unary.expr_->IsLvalue()) { reporter_.Report("Lvalue required for prefix operand", unary.op_); return; } // inc/dec on array is invalid if ((unary.op_->GetType() == TokenType::T_INC || unary.op_->GetType() == TokenType::T_DEC) && unary.expr_->is_indexable_) { reporter_.Report("Increment or decrement operations are invalid for arrays", unary.op_); return; } unary.to_scale_ = unary.expr_->type_.IsPointer(); unary.type_ = unary.expr_->type_; if (unary.op_->GetType() == TokenType::T_BIT_AND) unary.type_.ind++; return; } case TokenType::T_STAR: { unary.expr_->Accept(*this); // dereferencing not a pointer if (!IsPointer(unary.expr_.get())) { reporter_.Report("Expression to '*' must be a pointer", unary.op_); return; } // dereferencing void pointer if (unary.expr_->type_.IsVoid()) { reporter_.Report("Dereferencing 'void' pointer is invalid", unary.op_); return; } unary.is_lvalue_ = true; unary.type_ = unary.expr_->type_; unary.type_.len = 0; unary.type_.ind = std::max(unary.type_.ind - 1, 0); return; } default: { reporter_.Report("Invalid operator in 'unary' expression", unary.op_); return; } } } void TypeChecker::Visit(Access& access) { access.name_->return_ptr_ = true; access.name_->Accept(*this); if (!access.name_->type_.IsStruct() && !access.name_->type_.IsUnion()) { reporter_.Report("Only struct/union fields can be accessed via '.' or '->' operator", access.op_); } if (access.op_->GetType() == TokenType::T_DOT && access.name_->type_.ind != 0) { reporter_.Report("Struct variable expected, but got pointer", access.op_); } if (access.op_->GetType() == TokenType::T_ARROW && access.name_->type_.ind != 1) { reporter_.Report("Pointer to struct expected", access.op_); } if (!access.field_->IsVariable()) { reporter_.Report("Only string fields are supported", access.field_->op_); } access.is_lvalue_ = true; const std::shared_ptr<Literal>& field = std::static_pointer_cast<Literal>(access.field_); Entry* field_ = symbol_table_.GetField(access.name_->type_, field->op_->String()); if (field_ == nullptr) { reporter_.Report("Undefined field", field->op_); return; } access.type_ = *field_->type; field->type_ = *field_->type; field->offset_ = field_->offset; // annotate node with offset value } void TypeChecker::Visit(Logical &logical) { logical.left_->is_const_ = logical.is_const_; logical.right_->is_const_ = logical.is_const_; logical.left_->Accept(*this); logical.right_->Accept(*this); const Type& left = logical.left_->type_, right = logical.right_->type_; if ((!left.IsPrimitive() && !left.IsPointer()) || (!right.IsPrimitive() && !right.IsPointer())) { reporter_.Report("non-scalar expression where scalar is required", logical.op_); return; } logical.type_.type_ = TokenType::T_INT; } void TypeChecker::Visit(Binary& binary) { binary.left_->is_const_ = binary.is_const_; binary.right_->is_const_ = binary.is_const_; binary.left_->Accept(*this); binary.right_->Accept(*this); MatchTypes(binary.left_.get(), binary.right_.get(), false, &binary); } void TypeChecker::Visit(Assign& assign) { assign.left_->is_const_ = assign.is_const_; assign.right_->is_const_ = assign.is_const_; assign.left_->return_ptr_ = true; assign.left_->Accept(*this); if (!assign.left_->IsLvalue()) { reporter_.Report("Assign to rvalue is not allowed", assign.op_); return; } assign.right_->Accept(*this); MatchTypes(assign.left_.get(), assign.right_.get(), true, &assign); } void TypeChecker::TypeCheck(const std::vector<std::shared_ptr<Stmt>>& stmts) { symbol_table_.ClearTypes(); for (const auto& stmt : stmts) { stmt->Accept(*this); } } void TypeChecker::Visit(Literal& literal) { if (literal.op_->GetType() == TokenType::T_IDENTIFIER) { Entry* var = symbol_table_.Get(literal.op_->String()); if (var == nullptr) { reporter_.Report("Variable '" + literal.op_->String() + "' has not been declared", literal.op_); return; } // enum if (var->type->type_ == TokenType::T_ENUM) { literal.type_.type_ = TokenType::T_INT; literal.op_->SetType(TokenType::T_INT_LIT); literal.op_->SetString(""); literal.op_->SetInt(var->offset); // enum value is stored in offset return; } if (literal.is_const_) { reporter_.Report("Variables initializers '" + literal.op_->String() + "' must be constant", literal.op_); return; } if (literal.is_function_ && var->func == nullptr) { reporter_.Report("'" + literal.op_->String() + "' is not a function", literal.op_); return; } if (literal.is_indexable_ && !var->type->IsArray() && !var->type->IsPointer()) { reporter_.Report("Invalid type for index operation, pointer or array expected", literal.op_); return; } literal.type_ = *var->type; literal.is_local_ = var->is_local; literal.offset_ = var->offset; // usage of array as pointer, literal->is_indexable_ is false, set to true // so usage *(array + 5) = 10, will return pointer to array if (!literal.is_indexable_ && var->type->IsArray()) { literal.is_indexable_ = true; literal.type_.ind++; } } else if (literal.op_->GetType() == TokenType::T_STR_LIT) { literal.type_.type_ = TokenType::T_CHAR; literal.type_.ind = 1; code_gen_.strings_[literal.op_->String()] = -1; } else { // integer int val = literal.op_->Int(); literal.type_.type_ = (val <= 255 && val >= -256) ? TokenType::T_CHAR : TokenType::T_INT; } } // #TODO: fix error reporting void TypeChecker::Visit(Print& print) { print.expr_->Accept(*this); if (!IsIntegerType(print.expr_.get())) { reporter_.Report("'print' statement expects integer", print.token_); } } void TypeChecker::Visit(ExpressionStmt& expr_stmt) { expr_stmt.expr_->Accept(*this); } void TypeChecker::Visit(Conditional& cond_stmt) { cond_stmt.condition_->Accept(*this); if (!IsIntegerType(cond_stmt.condition_.get()) && !IsPointer(cond_stmt.condition_.get())) { reporter_.Report("Used not-scalar where scalar is required", cond_stmt.token_); return; } cond_stmt.then_block_->Accept(*this); if (cond_stmt.else_block_ != nullptr) { cond_stmt.else_block_->Accept(*this); } } void TypeChecker::Visit(Block& block_stmt) { symbol_table_.NewScope(); if (gen_params_) { // parameter generation for functions int param_offset = 8; for (int i = 0; i < curr_func_->signature_->var_decl_list_.size(); i++) { const auto& decl = curr_func_->signature_->var_decl_list_[i]; int offset = (i < 6) ? GetLocalOffset(decl->var_type_, 1) : (param_offset += 8); decl->offset_ = offset; symbol_table_.PutLocal(decl->name_->String(), &decl->var_type_, offset); } gen_params_ = false; } for (const auto& stmt : block_stmt.stmts_) stmt->Accept(*this); symbol_table_.EndScope(); } void TypeChecker::Visit(While& while_stmt) { while_stmt.condition_->Accept(*this); if (!IsIntegerType(while_stmt.condition_.get()) && !IsPointer(while_stmt.condition_.get())) { reporter_.Report("Used not-scalar where scalar is required", while_stmt.token_); return; } while_stmt.loop_block_->Accept(*this); } // for tomorrow : big refactoring // parser synchronization on errors // error reporter to print tokens, line number, character counts // support for pointers of different types void TypeChecker::Visit(Switch& switch_stmt) { switch_stmt.expr_->Accept(*this); if (!IsIntegerType(switch_stmt.expr_.get())) { reporter_.Report("Used not-scalar where scalar is required", switch_stmt.token_); return; } for (const auto& pair : switch_stmt.cases_) { pair.second->Accept(*this); // check switch branches } } void TypeChecker::Visit(For& for_stmt) { symbol_table_.NewScope(); for_stmt.init_->Accept(*this); if (for_stmt.condition_ != nullptr) { for_stmt.condition_->Accept(*this); } if (for_stmt.condition_ != nullptr && !IsIntegerType(for_stmt.condition_.get()) && !IsPointer(for_stmt.condition_.get())) { reporter_.Report("Used not-scalar where scalar is required", for_stmt.token_); return; } for_stmt.loop_block_->Accept(*this); for_stmt.update_->Accept(*this); symbol_table_.EndScope(); } void TypeChecker::Visit(DeclList& decl_list) { for (const auto& var_decl : decl_list.var_decl_list_) var_decl->Accept(*this); } void TypeChecker::Visit(ExprList& expr_list) { for (const auto& expr : expr_list.expr_list_) expr->Accept(*this); } void TypeChecker::Visit(ControlFlow& flow_stmt) { } // #FIXME: add support for `return;` void TypeChecker::Visit(Return& return_stmt) { return_stmt.expr_->Accept(*this); if (curr_func_->return_type_.IsVoid()) { reporter_.Error("Declared return type is 'void', but return statement found", curr_func_->return_type_, return_stmt.expr_.get(), return_stmt.token_); return; } if (!MatchTypeInit(curr_func_->return_type_, return_stmt.expr_.get())) { reporter_.Error("Declared type of init expression does not correspond to inferred type ", curr_func_->return_type_, return_stmt.expr_.get(), return_stmt.token_); } } void TypeChecker::RevertOffsets(Entry *fields, int size) { while (fields != nullptr) { fields->offset += size; fields = fields->next; } } void TypeChecker::Visit(Enum& decl) { if (decl.type_.name != nullptr) { if (symbol_table_.ContainsType(decl.type_.name->String())) { reporter_.Report("Type has already been defined", decl.type_.name); return; } else { symbol_table_.PutType(decl.type_.name->String(), 0, nullptr); } } for (const auto& enum_val : decl.values_) { if (symbol_table_.Contains(enum_val->op_->String())) { reporter_.Report("Enumerator symbol redefinition", enum_val->op_); return; } enum_val->type_.type_ = TokenType::T_ENUM; symbol_table_.PutLocal(enum_val->op_->String(), &enum_val->type_, enum_val->op_->Int()); // enum decls are global only } if (decl.var_name_ != nullptr && symbol_table_.Contains(decl.var_name_->String())) { reporter_.Report("Variable '" + decl.var_name_->String() + "' has already been defined", decl.var_name_); return; } if (decl.var_name_ != nullptr) { decl.type_.type_ = TokenType::T_INT; symbol_table_.PutGlobal(decl.var_name_->String(), &decl.type_, nullptr, 0); } } void TypeChecker::Visit(TypeCast& type_cast) { type_cast.expr_->Accept(*this); if (type_cast.type_.type_ == TokenType::T_IDENTIFIER) TypedefChange(type_cast.type_); if (type_cast.type_.IsPrimitive() || type_cast.type_.IsPointer()) { if (!type_cast.expr_->type_.IsPrimitive() && !type_cast.expr_->type_.IsPointer()) reporter_.Report("Casting expression of non-scalar type", type_cast.expr_->op_); } else { reporter_.Report("Casting to non-scalar type requested", type_cast.op_); } // warning: cast to struct from primitive type if (type_cast.type_.IsPointer() && (type_cast.type_.IsStruct() || type_cast.type_.IsUnion()) && type_cast.expr_->type_.IsPrimitive()) { reporter_.Warning("Casting to composite pointer from primitive type ", type_cast.type_, type_cast.expr_.get(), type_cast.op_); } } void TypeChecker::Visit(Typedef& typedef_stmt) { const std::string& name = typedef_stmt.name_->String(); if (symbol_table_.ContainsType(name) || symbol_table_.Contains(name)) { reporter_.Report("Symbol '" + name + "' has already been defined", typedef_stmt.name_); return; } if (typedef_stmt.stmt_ != nullptr) { if (typedef_stmt.stmt_->IsStruct()) { const auto& stmt = std::static_pointer_cast<Struct>(typedef_stmt.stmt_); stmt->is_typedef_ = true; stmt->Accept(*this); Entry *fields = symbol_table_.GetType(stmt->type_.name->String())->next; symbol_table_.PutType(name, &stmt->type_, fields); } else if (typedef_stmt.stmt_->IsUnion()) { const auto& stmt = std::static_pointer_cast<Union>(typedef_stmt.stmt_); stmt->is_typedef_ = true; stmt->Accept(*this); symbol_table_.PutType(name, &stmt->type_, stmt->fields_); } } else { if (typedef_stmt.type_.type_ == TokenType::T_IDENTIFIER) TypedefChange(typedef_stmt.type_); // recursive typedef symbol_table_.PutType(name, &typedef_stmt.type_, nullptr); } } // #TODO: functional decomposition void TypeChecker::Visit(Union& decl) { if (!decl.is_typedef_ && decl.type_.name == nullptr && decl.var_name_ == nullptr) { reporter_.Warning("Unnamed union declarations are not supported", decl.token_); return; } // create a linked list of field declarations and validate them std::unordered_map<std::string, int> offsets; Entry *fields = new Entry, *head = fields; int offset = 0; for (const auto& var_decl : decl.body_->var_decl_list_) { if (var_decl->var_type_.type_ == TokenType::T_IDENTIFIER) // typedef in unions TypedefChange(var_decl->var_type_); auto *field = new Entry; const std::string& name = var_decl->name_->String(); int len = var_decl->var_type_.len; // #FIXME: arrays in unions (array indexing is broken) if (offsets.count(name) != 0) { reporter_.Report("Redefinition of field in struct", var_decl->name_); FreeEntries(head); return; } offset = std::min(GetOffset(var_decl->var_type_, len), offset); // find max offset (min, as offsets are negative) offsets[name] = offset; *field = {&var_decl->var_type_, false, 0, nullptr, nullptr, name}; fields->next = field; fields = fields->next; } fields->next = nullptr; decl.size = (head == fields) ? 0 : std::abs(offset); fields = head; head = head->next; free(fields); std::string name; if (decl.type_.name == nullptr) { name = "__unnamed_union__" + std::to_string(unnamed++); decl.type_.name = std::make_shared<Token>(); decl.type_.name->SetString(name); } else { name = decl.type_.name->String(); } if (symbol_table_.ContainsType(name)) { reporter_.Report("Union has already been declared", decl.type_.name); return; } symbol_table_.PutType(name, decl.size, head); if (decl.var_name_ != nullptr && symbol_table_.Contains(decl.var_name_->String())) { reporter_.Report("Variable '" + decl.var_name_->String() + "' has already been defined", decl.var_name_); return; } if (decl.var_name_ != nullptr && symbol_table_.ContainsType(decl.var_name_->String())) { reporter_.Report("Symbol '" + decl.var_name_->String() + "' has already been defined", decl.var_name_); return; } if (decl.var_name_ != nullptr) { symbol_table_.PutGlobal(decl.var_name_->String(), &decl.type_, nullptr, 0); } } void TypeChecker::Visit(Struct& decl) { // 1. unnamed struct `struct { int x; };` // 2. named struct `struct Book { int length; char* title; };` // 3. named struct with var decl `struct Book { int length; char* title; } book; if (!decl.is_typedef_ && decl.type_.name == nullptr && decl.var_name_ == nullptr) { reporter_.Warning("Unnamed struct declarations are not supported", decl.token_); return; } // create a linked list of field declarations and validate them std::unordered_map<std::string, int> offsets; Entry *fields = new Entry, *head = fields; int offset = 0; for (const auto& var_decl : decl.body_->var_decl_list_) { if (var_decl->var_type_.type_ == TokenType::T_IDENTIFIER) // typedef in structs TypedefChange(var_decl->var_type_); auto *field = new Entry; const std::string& name = var_decl->name_->String(); int len = var_decl->var_type_.len; // #FIXME: arrays in structs if (offsets.count(name) != 0) { reporter_.Report("Redefinition of field in struct", var_decl->name_); FreeEntries(head); return; } offset += GetOffset(var_decl->var_type_, len); offsets[name] = offset; *field = {&var_decl->var_type_, false, offset, nullptr, nullptr, name}; fields->next = field; fields = fields->next; } fields->next = nullptr; decl.size = (head == fields) ? 0 : std::abs(offset); fields = head; head = head->next; free(fields); RevertOffsets(head, decl.size); // offset shows the last address, revert fields offsets to be positive std::string name; if (decl.type_.name == nullptr) { name = "__unnamed_struct__" + std::to_string(unnamed++); decl.type_.name = std::make_shared<Token>(); decl.type_.name->SetString(name); } else { name = decl.type_.name->String(); } if (symbol_table_.ContainsType(name)) { reporter_.Report("Struct has already been declared", decl.type_.name); return; } symbol_table_.PutType(name, decl.size, head); if (decl.var_name_ != nullptr && symbol_table_.Contains(decl.var_name_->String())) { reporter_.Report("Variable '" + decl.var_name_->String() + "' has already been defined", decl.var_name_); return; } if (decl.var_name_ != nullptr && symbol_table_.ContainsType(decl.var_name_->String())) { reporter_.Report("Symbol '" + decl.var_name_->String() + "' has already been defined", decl.var_name_); return; } if (decl.var_name_ != nullptr) { symbol_table_.PutGlobal(decl.var_name_->String(), &decl.type_, nullptr, 0); } } void TypeChecker::TypedefChange(Type& type) { if (type.type_ == TokenType::T_IDENTIFIER && type.name != nullptr) { TypeEntry *entry = symbol_table_.GetType(type.name->String()); type.type_ = entry->type->type_; type.ind += entry->type->ind; type.name = entry->type->name; // type.len += entry->type->len; #TODO: typedef for arrays } } void TypeChecker::Visit(FuncDecl& func_decl) { ResetLocals(); if (func_decl.return_type_.type_ == TokenType::T_IDENTIFIER) // typedef return type TypedefChange(func_decl.return_type_); for (const auto& param : func_decl.signature_->var_decl_list_) // typedef param types if (param->var_type_.type_ == TokenType::T_IDENTIFIER) TypedefChange(param->var_type_); Entry* func = symbol_table_.Get(func_decl.name_->String()); if (func == nullptr) { symbol_table_.Put(func_decl); } else { reporter_.Report("Function '" + func_decl.name_->String() + "' redefinition", func_decl.name_); return; } if (func_decl.body_ != nullptr) { // not prototype NewLabelScope(func_decl); curr_func_ = &func_decl; gen_params_ = true; func_decl.body_->Accept(*this); func_decl.local_offset_ = local_offset_; curr_func_ = nullptr; CheckLabelScope(func_decl); } } void TypeChecker::Visit(VarDecl& decl) { Entry* var = symbol_table_.GetLocal(decl.name_->String()); // void variable check if (decl.var_type_.IsVoid() && !decl.var_type_.IsPointer()) { reporter_.Report("Variable '" + decl.name_->String() + "' has unallowable type 'void'", decl.name_); return; } // redefinition check if (var != nullptr) { reporter_.Report("Variable '" + decl.name_->String() + "' has already been declared", decl.name_); return; } // check extern in local var declarations if (decl.is_local_ && decl.var_type_.storage == S_EXTERN) { reporter_.Report("'extern' in local declarations is not supported", decl.token_); } // typedef if (decl.var_type_.type_ == TokenType::T_IDENTIFIER) { TypedefChange(decl.var_type_); } // enum if (decl.var_type_.type_ == TokenType::T_ENUM) { decl.var_type_.type_ = TokenType::T_INT; } if (decl.var_type_.IsStruct() || decl.var_type_.IsUnion()) { if (!symbol_table_.ContainsType(decl.var_type_.name->String())) { reporter_.Report("undefined type", decl.var_type_.name); return;; } else { TypeEntry *entry = symbol_table_.GetType(decl.var_type_.name->String()); if (entry->type != nullptr) { // struct Type, where `Type` is typedef type reporter_.Report("struct usage with typedef type", decl.var_type_.name); return; } } } if (decl.init_ != nullptr) { // #TODO: reconsider const initializer and code gen for them decl.init_->is_const_ = decl.is_const_init_; decl.init_->Accept(*this); if (!MatchTypeInit(decl.var_type_, decl.init_.get())) { reporter_.Error("The type of init expression does not match the declared type of the variable ", decl.var_type_, decl.init_.get(), decl.name_); } // if no semantic errors if (decl.is_const_init_ && reporter_.errors_ == 0) { decl.init_val_ = decl.init_->Accept(evaluator_); } } // space allocation if (decl.is_local_) { int len = decl.var_type_.len == 0 ? 1 : decl.var_type_.len; int offset = GetLocalOffset(decl.var_type_, len); decl.offset_ = offset; symbol_table_.PutLocal(decl.name_->String(), &decl.var_type_, offset); } else { symbol_table_.PutGlobal(decl.name_->String(), &decl.var_type_, nullptr, decl.init_val_); if (decl.var_type_.IsStruct() || decl.var_type_.IsUnion()) { const std::string& st_name = decl.var_type_.name->String(); if (!symbol_table_.ContainsType(st_name)) { reporter_.Report("Composite (union/struct/enum) '" + decl.var_type_.name->String() + "' has not been declared", decl.var_type_.name); return; } } } } void TypeChecker::Visit(Call& call) { call.name_->is_const_ = call.is_const_; call.name_->is_function_ = true; call.name_->Accept(*this); call.type_ = call.name_->type_; const std::shared_ptr<Literal>& literal = std::static_pointer_cast<Literal>(call.name_); Entry* descr = symbol_table_.Get(literal->op_->String()); if (descr == nullptr) return; FuncDecl* func = descr->func; // no num arguments checks //if (call->args_->expr_list_.size() != func->signature_->var_decl_list_.size()) { // reporter_.Report("Number of arguments does not correspond to declared number of parameters", literal->op_); // return; //} for (int i = 0; i < call.args_->expr_list_.size(); i++) { const auto& arg = call.args_->expr_list_[i]; arg->Accept(*this); if (i >= func->signature_->var_decl_list_.size()) continue; const auto& param = func->signature_->var_decl_list_[i]; if (!MatchTypeInit(param->var_type_, arg.get())) { reporter_.Error("Declared type of parameter does not correspond to inferred argument type ", param->var_type_, arg.get(), arg->op_); } } } void TypeChecker::Visit(Index& index) { index.name_->is_const_ = index.is_const_; index.index_->is_const_ = index.is_const_; index.name_->is_indexable_ = true; index.name_->Accept(*this); index.index_->Accept(*this); index.index_->to_scale_ = true; index.is_lvalue_ = true; if (!IsIntegerType(index.index_.get())) { // #FIXME: could pointers be used as index? reporter_.Report("Index must be an integer type", index.name_->op_); return; } index.type_= index.name_->type_; index.type_.ind += index.name_->type_.IsArray() ? 0 : -1; // fix for pointer indexing index.type_.len = 0; } void TypeChecker::Visit(Grouping& grouping) { grouping.expr_->is_const_ = grouping.is_const_; grouping.expr_->return_ptr_ = grouping.return_ptr_; grouping.expr_->Accept(*this); grouping.is_lvalue_ = grouping.expr_->is_lvalue_; grouping.type_ = grouping.expr_->type_; } void TypeChecker::Visit(Ternary& ternary) { ternary.condition_->is_const_ = ternary.is_const_; ternary.then_->is_const_ = ternary.is_const_; ternary.else_->is_const_ = ternary.is_const_; ternary.condition_->Accept(*this); ternary.then_->Accept(*this); ternary.else_->Accept(*this); MatchTypes(ternary.then_.get(), ternary.else_.get(), false, &ternary); } void TypeChecker::Visit(Label& label) { label.label_ = code_gen_.GetLabel(); const std::string& name = label.token_->String(); if (code_gen_.labels_.count(name) > 0) { reporter_.Report("Label redefinition", label.token_); return; } code_gen_.labels_[curr_func_->name_->String()][label.token_->String()] = label.label_; } void TypeChecker::Visit(GoTo& go_to) { const std::string& name = go_to.token_->String(); if (code_gen_.labels_[curr_func_->name_->String()].count(name) == 0) code_gen_.labels_[curr_func_->name_->String()][go_to.token_->String()] = -1; } void TypeChecker::NewLabelScope(FuncDecl& func_decl) { code_gen_.labels_[func_decl.name_->String()] = {}; } void TypeChecker::CheckLabelScope(FuncDecl& func_decl) { const std::string& name = func_decl.name_->String(); for (const auto& pair : code_gen_.labels_[name]) { if (pair.second == -1) { reporter_.Report("Label '" + pair.first + "' used, but not declared, in function", func_decl.name_); } } } void TypeChecker::Visit(Postfix& postfix) { postfix.expr_->is_const_ = postfix.is_const_; // #FIXME: throw error immediately, as postfix is lvalue? postfix.expr_->return_ptr_ = true; postfix.expr_->Accept(*this); if (!postfix.expr_->IsLvalue()) { reporter_.Report("Lvalue required for postfix operand", postfix.op_); return; } // inc/dec on array is invalid if ((postfix.op_->GetType() == TokenType::T_INC || postfix.op_->GetType() == TokenType::T_DEC) && postfix.expr_->is_indexable_) { reporter_.Report("Increment or decrement operations are invalid for arrays", postfix.op_); return; } postfix.to_scale_ = postfix.expr_->type_.IsPointer(); // scale for pointer postfix.is_lvalue_ = false; postfix.type_ = postfix.expr_->type_; } bool TypeChecker::IsComparison(TokenType type) { return type == TokenType::T_EQUALS || type == TokenType::T_NOT_EQUALS || type == TokenType::T_LESS || type == TokenType::T_LESS_EQUAL || type == TokenType::T_GREATER || type == TokenType::T_GREATER_EQUAL; } void TypeChecker::FreeEntries(Entry *entry) { while (entry != nullptr) { Entry *curr = entry; entry = entry->next; free(curr); } } int TypeChecker::GetSizeOf(const Type& type) { if (type.IsArray()) { return type.len * (type.ind > 1 ? 8 : GetTypeSize(type)); } else if (type.IsPointer()) { return 8; } else { return GetTypeSize(type); } } int TypeChecker::GetOffset(const Type& type, int len) { len = len == 0 ? 1 : len; if (type.IsPointer()) return - len * 8; return - len * GetTypeSize(type); } int TypeChecker::GetLocalOffset(const Type& type, int len) { if (type.IsPointer()) return - (local_offset_ += 8 * len); local_offset_ += len * (GetTypeSize(type) > 4 ? GetTypeSize(type) : 4); return - local_offset_; } int TypeChecker::GetTypeSize(const Type& type) { if (type.IsStruct() || type.IsUnion()) return symbol_table_.GetType(type.name->String())->size; switch (type.type_) { case TokenType::T_CHAR: return 1; case TokenType::T_SHORT: return 2; case TokenType::T_INT: return 4; case TokenType::T_LONG: return 8; default: { std::cerr << "Internal error: invalid type." << std::endl; exit(1); } } } void TypeChecker::ResetLocals() { local_offset_ = 0; } } // namespace mcc
true
b65d02798fc5c52f366bb7e21322cae7d5981e3c
C++
Gacaar/Tradutor-Ligador-IA32
/src/pre_processador.cpp
UTF-8
10,454
2.671875
3
[]
no_license
/* Passagem zero do montador, retira espacos, tabs e quebras de linha desnecessarios. Processa as diretivas de pre-processamento EQU e IF e MACRO Recebe o arquivo <nome>.asm contendo o codigo do usuario. Gera um arquivo pre-processado <nome>.pre salvo em /out Erros detectados (somente relacionados com diretivas de pre processamento): -- Nome de rotulo invalido -- Rotulo nao definido (todo IF deve ter um EQU antes) -- Rotulo repetido -- Diretiva sem argumento -- Diretiva com argumento invalido' */ #include "../inc/pre_processador.hpp" MNDT novaMacro(string simbolo, int valor, string def){ MNDT macro; macro.nome = simbolo; macro.arg = valor; macro.def = def; return macro; } void equ(const string& label, string arg, list<TS>& tab, int line){ if(arg == "/n" || !validConst(arg) || !validLabel(label)){ errLex(line); //argumento ausente ou argumento invalido ou label invalida } else{ if(inList(label,tab)) errSem(line); else tab.push_back(novoSimbolo((label), stoi(arg))); } } bool ifd(string label, list<TS>& tab, int line){ bool b; TS simbol; if(label == "\n" || !validLabel(label)){ errLex(line); //label ausente ou invalida b = true; }else{ if(inList(label,tab,simbol)){ if(simbol.valor == 0) b = false; else b = true; }else{ errSem(line); b = true; } } return b; } void writeLine(string& labelAnt, vector<string> &tokens, ofstream &fw){ int t; if(labelAnt != ""){ fw << labelAnt << ": "; labelAnt = ""; } fw << tokens[0]; for(t=1;t<tokens.size()-1;t++){ fw << " " << tokens[t]; } } void writeMacroDef(MNDT* macroElem, vector<string> tokens){ macroElem->def += tokens[0]; for(int t=1;t<tokens.size()-1;t++){ macroElem->def += " "; macroElem->def += tokens[t]; } } void subArgsMacro(const vector<string> &argMacro, vector<string> &tokens){ char ic; for(int t = 0; t<tokens.size();t++){ ic = '1'; for(int i=0;i<argMacro.size();i++){ if(tokens[t] == argMacro[i]){ tokens[t] = "#"; tokens[t] += ic; }else if(tokens[t] == argMacro[i]+","){ tokens[t] = "#"; tokens[t] += ic; tokens[t] += ","; } ic++; } } } string preProc(string fileIn){ bool wMacro = false, macroErr = false, theEnd; int lineCount = 0; string line, labelEqu = "", nomeLabel = "", labelAnt = ""; list<TS> tabelaDeEqus; list<TD> tabelaDirPre = inicializarTDPre(); vector<string> tokens; vector<MNDT> macros; MNDT* macroElem; MNDT macElem; ifstream fr(fileIn); string fileName = takeFName(fileIn); ofstream fw(fileName+".pre"); fstream macroF; string nameMacro, macroWrite; int numParamMacro, tm; vector<string> argMacro, argMacroIn; theEnd = !getline(fr,line); while(!theEnd){ split(line,tokens); if(!wMacro){ lineCount++; //No modo macro nao conta linha }else{ //substitui args na macro for(int t=0;t<tokens.size();t++){ if(tokens[t].front()=='#'){ if(tokens[t].back() == ','){ tokens[t] = argMacro[stoi(tokens[t].substr(1,2))-1]; tokens[t] += ','; }else{ tokens[t] = argMacro[stoi(tokens[t].substr(1,2))-1]; } } } } if(tokens[0] != "\n"){ nomeLabel = ""; for(int t=0;t<tokens.size();t++){ //LABEL if(isLabel(tokens[t])){ if(nomeLabel == "" && labelAnt == ""){ nomeLabel = (tokens[t]); nomeLabel = nomeLabel.substr(0,nomeLabel.size()-1); }else{ //+ de 1 label na linha: ignora, escreve a linha e vai pra proxima writeLine(labelAnt, tokens, fw); if(!fr.eof()) fw << "\n"; break; } } else if(inList(upCase(tokens[t]),tabelaDirPre)){ if(upCase(tokens[t]) == "EQU"){ if(nomeLabel != "") labelEqu = nomeLabel; else if(labelAnt != ""){ labelEqu = labelAnt; labelAnt = ""; }else{ errSin(lineCount); //label ausente } if(labelEqu != ""){ equ(upCase(labelEqu), tokens[t+1], tabelaDeEqus, lineCount); nomeLabel = "/0"; } }else if(upCase(tokens[t]) == "IF"){ if(!ifd(upCase(tokens[t+1]), tabelaDeEqus, lineCount)){ if(wMacro){ if(!getline(macroF,line)){ wMacro = false; macroF.close(); } } else{ lineCount++; if(!getline(fr,line)){ theEnd = true; } } } } // //Se MACRO else if(upCase(tokens[t]) == "MACRO"){ macroErr = false; if(wMacro){ break; } //Verifica nome if(nomeLabel != ""){ nameMacro = nomeLabel; labelAnt = ""; }else if(labelAnt != ""){ nameMacro = labelAnt; labelAnt = ""; // nameMacro = nameMacro.substr(0,nameMacro.size()-1); }else{ errSin(lineCount); macroErr = true; nameMacro = ":"; } if(!validLabel(nameMacro)){ errLex(lineCount); macroErr = true; } //Verifica duplicidade if(inList(nameMacro, macros)){ errSem(lineCount); macroErr = true; } //Verifica argumentos argMacro.clear(); tm = t+1; while(tokens[tm] != "\n"){ if(tokens[tm].back() != ',' && tokens[tm+1] != "\n"){ errSin(lineCount); macroErr = true; break; }else if(tokens[tm].back() == ','){ tokens[tm].substr(0,tokens[tm].size()-1).swap(tokens[tm]); }else if(tokens[tm].front() != '&' || tm-t>3){ errSin(lineCount); macroErr = true; break; } argMacro.push_back(tokens[tm]); tm++; } //Pula a macro em caso de erro if(macroErr){ macroErr = false; do{ lineCount++; getline(fr,line); split(line,tokens); }while(upCase(tokens[0]) != "END"); break; } // Grava a macro na tabela macros.push_back(novaMacro("", argMacro.size(), "")); macroElem = &macros.back(); lineCount++; getline(fr,line); split(line,tokens); while(upCase(tokens[0]) != "END"){ if(inList(upCase(tokens[0]), macros, macElem)){ macroErr = false; //Expandir macro na macro //Verificar args argMacroIn.clear(); tm = 1; while(tokens[tm] != "\n"){ if(tokens[tm].back() != ',' && tokens[tm+1] != "\n"){ errSin(lineCount); macroErr = true; break; }else if(tokens[tm].back() == ','){ tokens[tm].substr(0,tokens[tm].size()-1).swap(tokens[tm]); } argMacroIn.push_back(tokens[tm]); tokens[tm] = ""; tm++; } if(tm>4){ errSin(lineCount); macroErr = true; }else if(tm != macElem.arg+1){ errSem(lineCount); macroErr = true; } //Substituir args if(!macroErr){ tokens[0] = ""; for(int t=0;t<macElem.def.size();t++){ if(macElem.def[t]=='#'){ t++; tokens[0] += argMacroIn[(int)(macElem.def[t]-'0')-1]; }else{ tokens[0] += macElem.def[t]; } } } } subArgsMacro(argMacro, tokens); writeMacroDef(macroElem, tokens); //Macro sem END if(fr.eof()){ errSem(lineCount); break; } lineCount++; getline(fr,line); split(line,tokens); if(upCase(tokens[0]) != "END"){ macroElem->def += '\n'; } } macros.back().nome = nameMacro; } break; } else if(inList(tokens[t],macros,macElem) && !wMacro){ //verificar argumentos argMacro.clear(); tm = t+1; while(tokens[tm] != "\n"){ if(tokens[tm].back() != ',' && tokens[tm+1] != "\n"){ tm = 100; //joga erro sintatico break; }else if(tokens[tm].back() == ','){ tokens[tm].substr(0,tokens[tm].size()-1).swap(tokens[tm]); } argMacro.push_back(tokens[tm]); tm++; } if(tm-t>4){ errSin(lineCount); }else if(tm-t != macElem.arg+1){ errSem(lineCount); }else{ wMacro = true; macroF.open("mac.txt",std::ofstream::trunc | std::ofstream::out); macroF << macElem.def; macroF.close(); macroF.open("mac.txt"); break; } } else if(tokens[t]=="\n"){ if(nomeLabel != "\0") labelAnt=nomeLabel; } else{ writeLine(labelAnt, tokens, fw); if(!fr.eof()) fw << "\n"; break; } } } if(wMacro){ if(!getline(macroF,line)){ wMacro = false; macroF.close(); remove("mac.txt"); } } if(!wMacro){ if(!getline(fr,line)){ theEnd = true; } } } return fileName+".pre"; } /* Ler a linha, incrementar counter e separar nomeLabel = ""; Procurar Labels ou diretivas de pre-processamento na lista Se elemento 0 for NULL, proxima linha Se achou label, verifica validade, verifica se nomeLabel = "" e guarda em nomeLabel Se achou diretiva (nao le mais essa linha): Se EQU, verifica se nomeLabel != "" (se for, verifica labelAnt), verifica se existe argumento e se eh valido Procura label L na tabela e, se nao achar, salvar nomeLabel = "\0" (a label foi usada) SE IF, verifica se existe argumento e eh valido, verifica na tab, incrementa e pula se true SE MACRO, verifica nome valido e num de arg Salvar nome e numero de variaveis na MNDT, ativar wMacro. Se labelAnt!="" guarda em labelAntMacro SE END, verifica se esta em modo macro Desativa wMacro e recupera labelAntMacro se !="" Se fim da linha Se nomeLabel != "\0" -> labelAnt = nomeLabel Se nao Verifica se ha labelAnt nao usada (perde a linha que a label apareceu, mas como ja eh verificado se ha erro na label aqui entao nao importa mais) Copia linha, salva o numero da linha e prox linha */ /* Se MACRO, verifica nome, verifica duplicidade e num de args (Em caso de erro tem que pular a macro) Salva labelAnt Salva os args Salva a definicao: (conta linhas, ate END, mas erro se nao tem END) Se nomeMacro Expande macro (nao como abaixo, so copia mesmo) Se arg Substitui por # Se label, diretiva ou outro: faz nada Salva o nome e num de args (tem que ser depois pra evitar recursao) Se nomeMacro, verifica nome, se existe, num de args wMacro = true (nao conta linhas) Salva os args Processa as linhas normalmentte (como aproveitar oq ja existe?) Se END volta labelAnt wMacro = false */
true
f74b42f7b2f1767b1ddd769756721d9d95244191
C++
fayeseh/G4Project_Pacman
/Pacman AI/DNA.cpp
UTF-8
2,317
3.0625
3
[]
no_license
#include <iostream> #include <vector> #include "DNA.h" #include "Network.h" #include "Neuron.h" using namespace std; DNA::DNA(vector<unsigned> &topo) { neuralNetwork = new Network(topo); } //function to get network from weights Network* DNA::weightsToNetwork(vector<double> weights, vector<unsigned>topology) { int i = 0; Network* net = new Network(topology); vector<Layer> tempNetwork; for(unsigned layerNum = 0; layerNum < net->NW_layers.size(); layerNum++) { //cout<<"Layer " <<layerNum <<endl; Layer tempLayer; for(unsigned neuronNum = 0; neuronNum < net->NW_layers.at(layerNum).size(); neuronNum++) { //cout<<"Neuron " <<neuronNum <<endl; Neuron tempNeuron(net->NW_layers.at(layerNum).at(neuronNum).N_weights.size(), neuronNum); vector<double> tempWeights; for(unsigned weightNum = 0; weightNum < net->NW_layers.at(layerNum).at(neuronNum).N_weights.size(); weightNum++ ) { //cout<<"Weight " <<weightNum <<endl; tempWeights.push_back(weights[i]); i++; } tempNeuron.N_weights = tempWeights; tempLayer.push_back(tempNeuron); } tempNetwork.push_back(tempLayer); } net->NW_layers = tempNetwork; return net; } //function to get weights from network vector<double> DNA::networkToWeights(Network* net) { vector<double> temp; for(unsigned layerNum = 0; layerNum < net->NW_layers.size(); layerNum++) { //cout<<net->NW_layers.size() <<endl; //cout<<"Layer " <<layerNum <<endl; for(unsigned neuronNum = 0; neuronNum < net->NW_layers.at(layerNum).size(); neuronNum++) { //cout<<net->NW_layers.at(layerNum).size() <<endl; //cout<<"Neuron " <<neuronNum <<endl; for(unsigned weightNum = 0; weightNum < net->NW_layers.at(layerNum).at(neuronNum).N_weights.size(); weightNum++ ) { //cout<<net->NW_layers.at(layerNum).at(neuronNum).N_weights.size() <<endl; //cout<<"Weight " <<weightNum <<endl; temp.push_back(net->NW_layers.at(layerNum).at(neuronNum).N_weights.at(weightNum)); } } } //cout<<"Returned" <<endl; return temp; }
true
5da9c8b9fa0ce9ba017c450bc0dc48057f884abc
C++
andres-fernandez-fuks/taller_wolfenstein3D
/server_src/game/colission_handler.cpp
UTF-8
3,587
2.546875
3
[]
no_license
#include "server/game/colission_handler.h" #include <iostream> #include <cmath> #include "server/utils/positions_calculator.h" #include <set> #define UNITS_TO_CHECK 45 #define DISTANCE_TO_DOOR 110 ColissionHandler::ColissionHandler(Map& _map) : map(_map) {} Coordinate ColissionHandler::moveToPosition(const Coordinate& actual_pos, double angle) { int x_move = std::round(cos(angle) * move_size); int y_move = std::round(sin(angle) * move_size * -1); int x_factor = (x_move < 0) ? -1 : 1; int y_factor = (y_move < 0) ? -1 : 1; int i = 0; int j = 0; bool is_y = abs(x_move) <= abs(y_move); int for_limit = (is_y) ? abs(y_move) : abs(x_move); int for_limit_oposite = (is_y) ? abs(x_move) : abs(y_move); int coord_base = (is_y) ? actual_pos.y : actual_pos.x; int coord_oposite = (is_y) ? actual_pos.x : actual_pos.y; int factor = (is_y) ? y_factor : x_factor; int factor_oposite = (is_y) ? x_factor : y_factor; for (; i < for_limit; i++) { int move_temp = coord_base + factor * safe_distance + factor * i; Coordinate new_position(-1, -1); if (is_y) { new_position.x = coord_oposite; new_position.y = move_temp; } else { new_position.x = move_temp; new_position.y = coord_oposite; } if (!map.isABlockingItemAt(new_position)) continue; else { i--; break; } } for (; j < for_limit_oposite && j < i; j++) { int move_temp = coord_oposite + factor_oposite * safe_distance + factor_oposite * j; Coordinate new_position(-1, -1); if (is_y) { new_position.x = move_temp; new_position.y = coord_base; } else { new_position.x = coord_base; new_position.y = move_temp; } if (!map.isABlockingItemAt(new_position)) continue; else { j--; break; } } Coordinate position(-1, -1); if (is_y) { position.x = actual_pos.x + j * x_factor; position.y = actual_pos.y + i * y_factor; } else { position.x = actual_pos.x + i * x_factor; position.y = actual_pos.y + j * y_factor; } return position; } std::vector<std::pair<Coordinate, Positionable>> ColissionHandler::getCloseItems(const Coordinate& old_pos, const Coordinate& new_pos) { std::vector<std::pair<Coordinate, Positionable>> positionables; std::set<Coordinate> found_positionables; Coordinate no_item_pos(0, 0); Coordinate item_in_pos(-1, -1); PositionsCalculator ph; std::vector<Coordinate> walked_positions = ph.straightLine(old_pos, new_pos); for (auto& pos : walked_positions) { Coordinate item_pos_aux = map.closePositionable(UNITS_TO_CHECK, pos, found_positionables); item_in_pos.x = item_pos_aux.x; item_in_pos.y = item_pos_aux.y; if (item_in_pos != no_item_pos && map.getPositionableAt(item_in_pos).getType() != "water_puddle") { std::pair<Coordinate, Positionable> item_to_pickup(item_in_pos, map.getPositionableAt(item_in_pos)); positionables.push_back(item_to_pickup); } } return positionables; } /* Verifica en linea recta hacia donde mira el jugador una cantidad * move size + safe distance de distancia total si existe una pared */ Coordinate ColissionHandler::getCloseBlocking(const Coordinate& pos, double angle, const std::string& category) { Coordinate blocking_pos = map.closeBlocking(DISTANCE_TO_DOOR, pos, angle); if (!blocking_pos.isValid()) return blocking_pos; if (map.isABlockingItemAt(blocking_pos) && map.getBlockingItemAt(blocking_pos).getCategory() == category) return blocking_pos; return Coordinate(-1, -1); }
true
c3df035e547a691afdf2eb948d7690b7c024d2ae
C++
stoneageartisans/tbw
/src/properties.cpp
UTF-8
538
2.890625
3
[]
no_license
#include "properties.h" Properties::Properties() { initialize(); } Properties::~Properties() { // TODO } void Properties::clear() { for(int i = 0; i < size; i ++) { values[i] = 0; } } int Properties::getValue(int KEY) { return values[KEY]; } int Properties::getSize() { return size; } void Properties::initialize() { size = TOTAL_KEYS; for(int i = 0; i < size; i ++) { values[i] = 0; } } void Properties::setProperty(int KEY, int VALUE) { values[KEY] = VALUE; }
true
d495bae122bfb65e54b84593816133679a33b014
C++
Duisterhof/swarmulator
/sw/simulation/controllers/PSO/PSO.h
UTF-8
3,955
2.625
3
[]
no_license
#ifndef PSO_H #define PSO_H #include <stdio.h> #include <iostream> #include "controller.h" #include "auxiliary.h" #include "omniscient_observer.h" class laser_ray { public: int num_walls; //number of walls that the laser ray intersects with float heading; //heading in ENU frame Point start_pos; //start position of the ray std::vector<std::vector<float>> walls; //all walls that the laser ray intersects with std::vector<Point> intersection_points; //intersection points with walls std::vector<float> distances;//distances to walls of intersection std::vector<std::vector<float>> intersecting_walls; //the walls it's intersecting with std::vector<float> intersect_wall; //the wall that it's intersecting with float range = 0.0 ; //final outcome, the measured range bool wall_following = false; // wall following params float heading_kp = 4.0; float heading_kd = 0.0; float heading_ki = 0.05; float heading_error = 0.0; float old_heading_error = 0.0; float heading_error_d = 0.0; float heading_error_i = 0.0; float heading_accumulator = 0.0; // what is finally added to heading float desired_laser_distance = 2.0; // desired minimal laser distance when following a wall float critical_laser_distance = 0.5; // when this point is reached we should be really really careful float engage_laser_distance = 2.5; // the end of the wall following zone, get more than this clearance to get out float old_accumulator = 0.0; // old accumulator used to limit the change in accumulation }; class PSO: public Controller { public: PSO():Controller(){}; virtual void get_velocity_command(const uint16_t ID, float &psi, float &v_x); virtual void animation(const uint16_t ID); laser_ray get_laser_reads(laser_ray ray, const uint16_t ID); float get_ray_control(laser_ray ray, float dt); float get_heading_to_point(Point agent, Point goal); bool get_follow_direction(std::vector<float> ranges, float desired_heading, float agent_heading); bool get_safe_direction(std::vector<float> ranges, float desired_heading, float threshold, float agent_heading); float get_agent_dist(const uint16_t ID1, const uint16_t ID2); float laser_headings[4] = {0,M_PI_2,M_PI,3*M_PI_2}; OmniscientObserver o; float old_accumulator = 0.0; // old accumulators of rays float diff_accumulator = 0.0; // difference with old accumulator float max_accumulator_increase = 0.1; //max [rad] increase in vector, to avoid unstable behavior float iteration_start_time = 0.0; float local_vx, local_vy; float local_psi = 0.0; // configuration parameters for PSO float rand_p = 1.4; float omega = 0.1; float phi_p = 0.5; float phi_g = 3.5; float yaw_incr = 0.1; float update_time = 40.0; float dist_reached_goal = 0.5; bool follow_left = false; bool started_agent_avoid = false; float swarm_rerout_time = 3.0; float started_swarm_avoid_time = 0.0; float swarm_avoidance_thres = 2.0; // // wall following params // float heading_kp = 3.0; // float heading_kd = 30.0; // float heading_k_i = 0.05; // float heading_error = 0.0; // float old_heading_error = 0.0; // float heading_error_d = 0.0; // float heading_error_i = 0.0; // float heading_accumulator = 0.0; // what is finally added to heading // wall avoiding parameters float desired_velocity = 0.5; float desired_laser_distance = 1.0; // desired minimal laser distance when following a wall float critical_laser_distance = 0.5; // when this point is reached we should be really really careful float engage_laser_distance = 1.5; // the end of the wall following zone, get more than this clearance to get out float min_laser = desired_laser_distance; //the minimum found laser distance int min_laser_idx = 0; // the idx (hence direction) of the laser with lowest value float heading_accumulator = 0.0; bool wall_following = false; Point agent_pos, goal, random_point, other_agent_pos; std::vector<laser_ray> laser_rays; }; #endif /*PSO_H*/
true
9509c8f1a4cbc96e78b0e145bda6b6191e361dbb
C++
IgorL123/clab3
/Set.hpp
UTF-8
2,587
3.296875
3
[]
no_license
#ifndef SET_HPP #define SET_HPP #include <iostream> #include <vector> #include "BST.hpp" template <typename Type> class set // хыуеъ { private: BinarySearchTree<Type> item; public: set() { item = BinarySearchTree<Type>(); } void add(Type value) { if (!search(value)){ item.insert(value); } } void remove(Type value) {item.deleteNode(item.findNode(item.getRoot(), value)); } bool search(Type value) { return item.search(value); } size_t size() { return item.getSize(); } void clear() { item = BinarySearchTree<Type>(); } bool isContain(set<Type> &set) { return item.findSubTree(set.item); } void unionSet(set<Type> &list) { std::vector<Type> a = list.item.get2D(); for (int i = 0 ;i < a.size(); i++){ if (!search(a[i])){ add(a[i]); } } } void intersection(set<Type> &list) { std::vector<Type> a = list.item.get2D(); std::vector<Type> b; for (int i = 0; i < a.size(); i++) { if (search(a[i])) b.push_back(a[i]); } clear(); for (int i = 0; i < b.size(); i++){ add(b[i]); } } void difference(set<Type> &list) { std::vector<Type> a = list.item.get2D(); for (int i = 0; i < a.size(); i++){ if (search(a[i])){ remove(a[i]); } } } void map(Type (*func)(Type)) { if (func == nullptr){ throw std::invalid_argument{"Wrong function"}; } item.map(func); } Type reduceSet(Type (*func)(Type, Type), const Type &value) { if (func == nullptr){ throw std::invalid_argument{"Wrong function"}; } Type res = item.reduce(func, value); return res; } void where( bool(*func)(Type) ) { if (func == nullptr){ throw std::invalid_argument{"Wrong function"}; } item = item.where(func); } bool operator==(set<Type> &list) { return item.isEquals(item.getRoot(), list.item.getRoot()); } set<Type> operator+(set<Type> &list) { return unionSet(list); } set<Type> operator*(set<Type> &list) { return intersection(list); } set<Type> operator-(set<Type> &list) { return difference(list); } void print(){ std::vector<Type> a = item.get2D(); for(int i = 0; i < size(); i++){ std::cout << a[i] << ' '; } } }; #endif //SET_HPP
true
b83a76c2b079f459e568f188d277bd07155238c7
C++
FaiScofield/learn_dsa
/dsa/core/UniPrint/UniPrint.cc
UTF-8
21,683
2.734375
3
[]
no_license
#include "UniPrint.h" /****************************************************************************************** * 基本类型 ******************************************************************************************/ //template <typename T> //void UniPrint::p(const Vector<T>& V) //{ // if (V.empty()) // return; // for (int i = 0; i < V.size(); ++i) // cout << V[i] << " "; // cout << endl; //} //template <typename T> //void UniPrint::p(const List<T>& L) //{ // if (L.empty()) // return; // for (auto p = L.first(); p != L.last(); p = p->succ) // cout << p->data << " <--> "; // cout << L.last()->data << endl; //} // template <typename T> // void UniPrint::p(const Stack<T>& S) //{ // if (S.empty()) // return; // for (int i = 0; i < S.size(); ++i) // cout << S[i] << " "; // cout << endl; //} // template <typename T> // void UniPrint::p(const Queue<T>& Q) //{ // if (Q.empty()) // return; // for (auto p = Q.first(); p != Q.last(); p = p->succ) // cout << p->data << " <--> "; // cout << Q.last()->data << endl; //} // void UniPrint::p(VStatus e) { // switch (e) { // case UNDISCOVERED: printf("U"); break; // case DISCOVERED: printf("D"); break; // case VISITED: printf("V"); break; // default: printf("X"); break; // } //} // void UniPrint::p(EType e) { // switch (e) { // case UNDETERMINED: printf("U"); break; // case TREE: printf("T"); break; // case CROSS: printf("C"); break; // case BACKWARD: printf("B"); break; // case FORWARD: printf("F"); break; // default: printf("X"); break; // } //} /**************************************************************************************** * BinTree节点 ****************************************************************************************/ //template <typename T> //void UniPrint::p(BinNode<T>& node) //{ // p(node.data); //数值 // /************************************************************************************** // * height & NPL // *************************************************************************************/ //#if defined(DSA_LEFTHEAP) // printf("(%-2d)", node.npl); // NPL //#elif defined(DSA_BST) // printf("(%-2d)", node.height); //高度 //#elif defined(DSA_AVL) // printf("(%-2d)", node.height); //高度 //#elif defined(DSA_REDBLACK) // printf("(%-2d)", node.height); //高度 //#elif defined(DSA_SPLAY) // printf("(%-2d)", node.height); //高度 //#endif // /****************************************************************************************** // * 父子链接指针 // ******************************************************************************************/ // printf(((node.lc && &node != node.lc->parent) || (node.rc && &node != node.rc->parent)) ? "@" : " "); // /****************************************************************************************** // * 节点颜色 // ******************************************************************************************/ //#if defined(DSA_REDBLACK) // printf(node.color == RB_BLACK ? "B" : " "); //(忽略红节点) //#endif // /****************************************************************************************** // * 父子(黑)高度、NPL匹配 // ******************************************************************************************/ //#if defined(DSA_PQ_COMPLHEAP) // //高度不必匹配 //#elif defined(DSA_PQ_LEFTHEAP) // printf( // NPL // (node.rc && node.npl != 1 + node.rc->npl) || (node.lc && node.npl > 1 + node.lc->npl) ? // "%%" : // " "); //#elif defined(DSA_REDBLACK) // printf(BlackHeightUpdated(node) ? " " : "!"); //黑高度 //#else // printf(HeightUpdated(node) ? " " : "!"); //(常规)高度 //#endif // /****************************************************************************************** // * 左右平衡 // ******************************************************************************************/ //#if defined(DSA_AVL) // if (!AvlBalanced(node)) // printf("X"); // AVL平衡 // else if (0 < BalFac(node)) // printf("\\"); // AVL平衡 // else if (BalFac(node) < 0) // printf("/"); // AVL平衡 // else // printf("-"); // AVL平衡 //#elif defined(DSA_REDBLACK) // if (!Balanced(node)) // printf("X"); // RB平衡 // else if (0 < BalFac(node)) // printf("\\"); // RB平衡 // else if (BalFac(node) < 0) // printf("/"); // RB平衡 // else // printf("-"); // RB平衡 //#else // //平衡无所谓 //#endif //} /****************************************************************************************** * 二叉树输出打印 ******************************************************************************************/ /****************************************************************************************** * 基础BinTree ******************************************************************************************/ //template <typename T> //元素类型 //void UniPrint::p(BinTree<T>& bt) //{ // 引用 // printf("%s[%d]*%d:\n", typeid(bt).name(), &bt, bt.size()); // 基本信息 // Bitmap* branchType = new Bitmap; // 记录当前节点祖先的方向 // printBinTree(bt.root(), -1, ROOT, branchType); // 树状结构 // release(branchType); // printf("\n"); //} /****************************************************************************************** * 基于BinTree实现的BST ******************************************************************************************/ //template <typename T> //元素类型 //void UniPrint::p(BST<T>& bt) //{ //引用 // printf("%s[%d]*%d:\n", typeid(bt).name(), &bt, bt.size()); //基本信息 // Bitmap* branchType = new Bitmap; //记录当前节点祖先的方向 // printBinTree(bt.root(), -1, ROOT, branchType); //树状结构 // release(branchType); // printf("\n"); //} ///****************************************************************************************** // * 基于BST实现的AVL // * 其中调用的BinNode的打印例程,可以显示BF状态 // ******************************************************************************************/ // template <typename T> //元素类型 // void UniPrint::p(AVL<T> & avl) { //引用 // printf("%s[%d]*%d:\n", typeid (avl).name(), &avl, avl.size()); //基本信息 // Bitmap* branchType = new Bitmap; //记录当前节点祖先的方向 // printBinTree (avl.root(), -1, ROOT, branchType); //树状结构 // release (branchType); printf("\n"); //} ///****************************************************************************************** // * 基于BST实现的RedBlack // * 其中调用的BinNode的打印例程,可以显示BF状态 // ******************************************************************************************/ // template <typename T> //元素类型 // void UniPrint::p(RedBlack<T> & rb) { //引用 // printf("%s[%d]*%d:\n", typeid (rb).name(), &rb, rb.size()); //基本信息 // Bitmap* branchType = new Bitmap; //记录当前节点祖先的方向 // printBinTree (rb.root(), -1, ROOT, branchType); //树状结构 // release (branchType); printf("\n"); //} ///****************************************************************************************** // * 基于BST实现的Splay // * 鉴于Splay不必设置bf之类的附加标识,其打印例程与BST完全一致 // ******************************************************************************************/ // template <typename T> //元素类型 // void UniPrint::p(Splay<T> & bt) { //引用 // printf("%s[%d]*%d:\n", typeid (bt).name(), &bt, bt.size()); //基本信息 // Bitmap* branchType = new Bitmap; //记录当前节点祖先的方向 // printBinTree (bt.root(), -1, ROOT, branchType); //树状结构 // release (branchType); printf("\n"); //} /****************************************************************************************** * 二叉树各种派生类的统一打印 ******************************************************************************************/ //template <typename T> //元素类型 //static void printBinTree(BinNodePosi(T) bt, int depth, int type, Bitmap* bType) //{ // if (!bt) // return; // if (-1 < depth) //设置当前层的拐向标志 // R_CHILD == type ? bType->set(depth) : bType->clear(depth); // printBinTree(bt->rc, depth + 1, R_CHILD, bType); //右子树(在上) // print(bt); // printf(" *"); // for (int i = -1; i < depth; i++) //根据相邻各层 // if ((0 > i) || bType->test(i) == bType->test(i + 1)) //的拐向是否一致,即可确定 // printf(" "); //是否应该 // else // printf("│ "); //打印横线 // switch (type) { // case R_CHILD: // printf("┌─"); // break; // case L_CHILD: // printf("└─"); // break; // default: // printf("──"); // break; // root // } // print(bt); //#if defined(DSA_HUFFMAN) // if (IsLeaf(*bt)) // bType->print(depth + 1); //输出Huffman编码 //#endif // printf("\n"); // printBinTree(bt->lc, depth + 1, L_CHILD, bType); //左子树(在下) //} /****************************************************************************************** * BTree打印(入口) ******************************************************************************************/ //template <typename T> //元素类型 //void UniPrint::p(BTree<T>& bt) //{ //引用 // printf("%s[%d]*%d:\n", typeid(bt).name(), &bt, bt.size()); //基本信息 // Bitmap* leftmosts = new Bitmap; //记录当前节点祖先的方向 // Bitmap* rightmosts = new Bitmap; //记录当前节点祖先的方向 // printBTree(bt.root(), 0, true, true, leftmosts, rightmosts); //输出树状结构 // release(leftmosts); // release(rightmosts); // printf("\n"); //} /****************************************************************************************** * BTree打印(递归) ******************************************************************************************/ //template <typename T> //元素类型 //static void printBTree(BTNodePosi(T) bt, int depth, bool isLeftmost, bool isRightmost, // Bitmap* leftmosts, Bitmap* rightmosts) //{ // if (!bt) // return; // isLeftmost ? leftmosts->set(depth) : leftmosts->clear(depth); //设置或清除当前层的拐向标志 // isRightmost ? rightmosts->set(depth) : rightmosts->clear(depth); //设置或清除当前层的拐向标志 // int k = bt->child.size() - 1; //找到当前节点的最右侧孩子,并 // printBTree(bt->child[k], depth + 1, false, true, leftmosts, rightmosts); //递归输出之 // bool parentOK = false; // BTNodePosi(T) p = bt->parent; // if (!p) // parentOK = true; // else // for (int i = 0; i < p->child.size(); i++) // if (p->child[i] == bt) // parentOK = true; // while (0 < k--) { //自右向左,输出各子树及其右侧的关键码 // printf(parentOK ? " " : "X"); // print(bt->key[k]); // printf(" *>"); // for (int i = 0; i < depth; i++) //根据相邻各层 // (leftmosts->test(i) && leftmosts->test(i + 1) || // rightmosts->test(i) && rightmosts->test(i + 1)) ? //的拐向是否一致,即可确定 // printf(" ") : // printf("│ "); //是否应该打印横向联接线 // if (((0 == depth && 1 < bt->key.size()) || !isLeftmost && isRightmost) && bt->key.size() - 1 == k) // printf("┌─"); // else if (((0 == depth && 1 < bt->key.size()) || isLeftmost && !isRightmost) && 0 == k) // printf("└─"); // else // printf("├─"); // print(bt->key[k]); // printf("\n"); // printBTree(bt->child[k], depth + 1, 0 == k, false, leftmosts, rightmosts); //递归输出子树 // } //} ///****************************************************************************************** // * Entry // ******************************************************************************************/ // template <typename K, typename V> // void UniPrint::p(Entry<K, V>& e) //引用 //{ printf("-<"); print(e.key); printf(":"); print(e.value); printf(">-"); } /****************************************************************************************** * 图Graph ******************************************************************************************/ //template <typename Tv, typename Te> //顶点类型、边类型 //void UniPrint::p(GraphMatrix<Tv, Te>& s) //{ //引用 // int inD = 0; // for (int i = 0; i < s.n; i++) // inD += s.inDegree(i); // int outD = 0; // for (int i = 0; i < s.n; i++) // outD += s.outDegree(i); // printf("%s[%d]*(%d, %d):\n", typeid(s).name(), &s, s.n, s.e); //基本信息 // // 标题行 // print(s.n); // printf(" "); // print(inD); // printf("|"); // for (int i = 0; i < s.n; i++) { // print(s.vertex(i)); // printf("["); // print(s.status(i)); // printf("] "); // } // printf("\n"); // // 标题行(续) // print(outD); // printf(" "); // print(s.e); // printf("|"); // for (int i = 0; i < s.n; i++) { // print(s.inDegree(i)); // printf(" "); // } // printf("| dTime fTime Parent Weight\n"); // // 水平分隔线 // printf("-----------+"); // for (int i = 0; i < s.n; i++) // printf("------"); // printf("+----------------------------\n"); // // 逐行输出各顶点 // for (int i = 0; i < s.n; i++) { // print(s.vertex(i)); // printf("["); // print(s.status(i)); // printf("] "); // print(s.outDegree(i)); // printf("|"); // for (int j = 0; j < s.n; j++) // if (s.exists(i, j)) { // print(s.edge(i, j)); // print(s.type(i, j)); // } else // printf(" ."); // printf("| "); // print(s.dTime(i)); // printf(" "); // print(s.fTime(i)); // printf(" "); // if (0 > s.parent(i)) // print("^"); // else // print(s.vertex(s.parent(i))); // printf(" "); // if (INT_MAX > s.priority(i)) // print(s.priority(i)); // else // print(" INF"); // printf("\n"); // } // printf("\n"); //} /****************************************************************************************** * Hashtable ******************************************************************************************/ //template <typename K, typename V> // e、value //void UniPrint::p(Hashtable<K, V>& ht) //{ //引用 // printf("%s[%d]*%d/%d:\n", typeid(ht).name(), &ht, ht.N, ht.M); //基本信息 // for (int i = 0; i < ht.M; i++) //输出桶编号 // printf(" %4d ", i); // printf("\n"); // for (int i = 0; i < ht.M; i++) //输出所有元素 // if (ht.ht[i]) // printf("-<%04d>-", ht.ht[i]->key); //演示用,仅适用于int // else if (ht.lazyRemoval->test(i)) // printf("-<xxxx>-"); // else // printf("--------"); // printf("\n"); // for (int i = 0; i < ht.M; i++) //输出所有元素 // if (ht.ht[i]) // printf(" %c ", ht.ht[i]->value); //演示用,仅适用于char // // if (ht.ht[i]) printf("%8s", ht.ht[i]->value); //针对Huffman编码中使用的散列表 // else if (ht.lazyRemoval->test(i)) // printf(" <xxxx> "); // else // printf(" "); // printf("\n"); //} ///****************************************************************************************** // * Huffman(超)字符 // ******************************************************************************************/ // void UniPrint::p(HuffChar& e) { printf("[%c]:%-5d", e.ch, e.weight); } //#define ROOT 0 //#define L_CHILD 1 //#define R_CHILD -1*L_CHILD ///****************************************************************************************** // * 打印输出PQ_ComplHeap // ******************************************************************************************/ // template <typename T> //元素类型 // void UniPrint::p(PQ_ComplHeap<T> & pq) { //引用 // printf("%s[%d]*%d:\n", typeid (pq).name(), &pq, pq.size()); //基本信息 // int branchType[256]; //最深256层 <= 2^256 = 1.16*10^77 // printComplHeap((Vector<T> &) pq, pq.size(), 0, 0, ROOT, branchType); //树状结构 // printf("\n"); //} ///****************************************************************************************** // * 递归打印输出 // ******************************************************************************************/ // template <typename T> //元素类型 // static void printComplHeap(Vector<T>& elem, int n, int k, int depth, int type, int* bType) { // if (k >= n) return; //递归基 // bType[depth] = type; // printComplHeap(elem, n, RChild (k), depth + 1, R_CHILD, bType); //右子树(在上) // print(elem[k]); ParentValid (k) && (elem[Parent (k) ] < elem[k]) ? printf("X") : printf(" "); // printf("*"); for (int i = 0; i < depth; i++) //根据相邻各层 // if (bType[i] + bType[i+1]) //的拐向是否一致,即可确定 // printf(" "); //是否应该 // else printf("│ "); //打印横线 // switch (type) { // case R_CHILD : printf("┌─"); break; // case L_CHILD : printf("└─"); break; // default : printf("──"); break; //root // } // print(elem[k]); ParentValid (k) && (elem[Parent (k) ] < elem[k]) ? printf("X") : printf(" "); // printf("\n"); printComplHeap(elem, n, LChild (k), depth + 1, L_CHILD, bType); //左子树(在下) //} ///****************************************************************************************** // * 打印输出PQ_LeftHeap // ******************************************************************************************/ // template <typename T> //元素类型 // void UniPrint::p(PQ_LeftHeap<T> & lh) { //引用 // p((BinTree<T>&) lh); //} ///****************************************************************************************** // * 打印输出PQ_List // ******************************************************************************************/ // template <typename T> //元素类型 // void UniPrint::p(PQ_List<T> & pq) { //引用 // printf("%s*%d:\n", typeid (pq).name(), pq.size()); //基本信息 // p((List<T> &) pq); printf("\n"); //} ///****************************************************************************************** // * Quadlist // ******************************************************************************************/ // template <typename T> //元素类型 // void UniPrint::p(Quadlist<T>& q) { //引用 // printf("%s[%d]*%03d: ", typeid (q).name(), &q, q.size()); //基本信息 // if (q.size() <= 0) { printf("\n"); return; } // QuadlistNode<T>* curr = q.first()->pred; //当前层之header // QuadlistNode<T>* base = q.first(); //当前节点所在 // while (base->below) base = base->below; //塔底 // while (base->pred) base = base->pred; //底层之header // for (int i = 0; i < q.size(); i++) { //对于当前层的每一节点 // curr = curr->succ; //curr // QuadlistNode<T>* proj = curr; //找到与curr对应的 // while (proj->below) proj = proj->below; //塔底节点(投影) // while ((base = base->succ) != proj) //移动base直到proj,期间不断 // printf("------------"); //延长水平联接线 // print(curr->entry); //最后,输出当前层的当前词条 // } // printf("\n"); //} ///****************************************************************************************** // * Skiplist // ******************************************************************************************/ // template <typename K, typename V> //e、value // void UniPrint::p(Skiplist<K, V>& s) { //引用 // printf("%s[%d]*%d*%d:\n", typeid (s).name(), &s, s.level(), s.size()); //基本信息 // s.traverse (print); //通过print()遍历输出所有元素 // printf("\n"); //} /****************************************************************************************** * 向量、列表等支持traverse()遍历操作的线性结构 ******************************************************************************************/ // template <typename T> // void UniPrint::p(T& s) { // printf("%s[%d]*%d:\n", typeid(s).name(), &s, s.size()); // 基本信息 // s.traverse(print); // 通过print()遍历输出所有元素 // printf("\n"); //}
true
c6975ab6b1613a14eb9f505bdf3bf341cfa07c11
C++
ASquaredM/2D-Snake-Game
/src/startMenu.cpp
UTF-8
617
2.578125
3
[]
no_license
#include <iostream> #include <thread> #include "startMenu.h" #include "SDL.h" StartMenu::StartMenu(std::size_t grid_width, std::size_t grid_height) : grid_width(grid_width), grid_height(grid_height) {} std::unique_ptr<Game> StartMenu::Run(Renderer &renderer, std::size_t target_frame_duration){ renderer.RenderMenu(); Game::Mode mode = Game::Mode::kWait; while (mode == Game::Mode::kWait){ std::this_thread::sleep_for(std::chrono::milliseconds(1)); mode = menucontroller.HandleInput(); } game = std::make_unique<Game>(grid_width,grid_height,mode); return std::move(game); }
true
40a560c3dba893a681b9bbcc68f23443c717332d
C++
ThomasCorcoral/Smart-Pointers
/testPointers.cc
UTF-8
5,181
3.046875
3
[]
no_license
#include <gtest/gtest.h> #include "Shared.h" #include "Weak.h" #include "Unique.h" namespace{ struct test_vec{ int x; int y; }; } TEST(UniqueTests, DefaultCreation){ sp::Unique<int> unique; EXPECT_FALSE(unique.exists()); } TEST(UniqueTests, CreationWithValue){ sp::Unique<int> unique(new int(42)); EXPECT_TRUE(unique.exists()); } TEST(UniqueTests, Incrementation){ sp::Unique<int> unique(new int(42)); EXPECT_TRUE(unique.exists()); EXPECT_EQ(*unique, 42); ++(*unique); EXPECT_EQ(*unique, 43); } TEST(UniqueTests, Displacement){ sp::Unique<int> unique(new int(42)); EXPECT_TRUE(unique.exists()); EXPECT_EQ(*unique, 42); sp::Unique<int> tmp = std::move(unique); EXPECT_FALSE(unique.exists()); EXPECT_TRUE(tmp.exists()); EXPECT_EQ(*tmp, 42); } TEST(UniqueTests, GoodMove){ sp::Unique<int> unique(new int(42)); sp::Unique<int> tmp(new int(24)); EXPECT_TRUE(unique.exists()); EXPECT_TRUE(tmp.exists()); EXPECT_EQ(*unique, 42); EXPECT_EQ(*tmp, 24); tmp = std::move(unique); EXPECT_TRUE(unique.exists()); EXPECT_TRUE(tmp.exists()); EXPECT_EQ(*tmp, 42); EXPECT_EQ(*unique, 24); } TEST(UniqueTests, OverloadedMethods){ sp::Unique<int> unique(new int(42)); EXPECT_EQ(*unique, 42); EXPECT_NE(&unique, nullptr); sp::Unique<test_vec> unique_vec = new test_vec; unique_vec->x = 42; EXPECT_EQ(unique_vec->x, 42); } TEST(SharedTests, DefaultCreation){ sp::Shared<int> shared; EXPECT_FALSE(shared.exists()); } TEST(SharedTests, CreationWithValue){ sp::Shared<int> shared(new int(42)); EXPECT_TRUE(shared.exists()); } TEST(SharedTests, Incrementation){ sp::Shared<int> shared(new int(42)); EXPECT_TRUE(shared.exists()); EXPECT_EQ(*shared, 42); ++(*shared); EXPECT_EQ(*shared, 43); } TEST(SharedTests, Copy){ sp::Shared<int> shared(new int(42)); sp::Shared<int> tmp; EXPECT_TRUE(shared.exists()); EXPECT_FALSE(tmp.exists()); EXPECT_EQ(*shared, 42); tmp = shared; EXPECT_TRUE(shared.exists()); EXPECT_TRUE(tmp.exists()); EXPECT_EQ(*shared, 42); EXPECT_EQ(*tmp, 42); EXPECT_EQ(*shared, *tmp); } TEST(SharedTests, Displacement){ sp::Shared<int> shared(new int(42)); EXPECT_TRUE(shared.exists()); EXPECT_EQ(*shared, 42); sp::Shared<int> tmp = std::move(shared); EXPECT_FALSE(shared.exists()); EXPECT_TRUE(tmp.exists()); EXPECT_EQ(*tmp, 42); } TEST(WeakTests, CreationWithValue){ sp::Shared<int> shared(new int(42)); sp::Weak<int> weak(shared); EXPECT_TRUE(shared.exists()); } TEST(WeakTests, DoubleCreation) { int* object = new int(42); sp::Shared<int> shared(object); sp::Weak<int> weak(shared); sp::Weak<int> weak2(shared); } TEST(WeakTests, Division){ sp::Shared<int>shared(new int(42)); EXPECT_EQ(*shared, 42); sp::Weak<int>weak1(shared); auto tmp = weak1.lock(); EXPECT_TRUE(tmp.exists()); (*tmp) /= 2; EXPECT_EQ(*tmp, 21); } TEST(WeakTests, Copy){ sp::Shared<int> shared(new int(42)); sp::Weak<int> weak(shared); sp::Weak<int> weak2; weak2 = weak; auto tmp = weak.lock(); EXPECT_TRUE(tmp.exists()); auto tmp2 = weak2.lock(); EXPECT_TRUE(tmp.exists()); EXPECT_EQ(*tmp, *tmp2); } TEST(WeakTests, Displacement){ sp::Shared<int> shared(new int(42)); EXPECT_TRUE(shared.exists()); EXPECT_EQ(*shared, 42); sp::Weak<int> weak; weak = shared; auto tmp = weak.lock(); EXPECT_TRUE(shared.exists()); EXPECT_TRUE(tmp.exists()); EXPECT_EQ(*tmp, 42); sp::Weak<int> weak2; weak2 = std::move(weak); auto tmp2 = weak2.lock(); EXPECT_TRUE(tmp.exists()); EXPECT_TRUE(tmp2.exists()); EXPECT_EQ(*tmp2, 42); } TEST(WeakTests, CopyInitialisation){ sp::Shared<int> shared(new int(42)); sp::Weak<int> weak(shared); sp::Weak<int> weak2; weak2 = weak; auto tmp = weak.lock(); EXPECT_TRUE(tmp.exists()); auto tmp2 = weak2.lock(); EXPECT_TRUE(tmp.exists()); EXPECT_EQ(*tmp, *tmp2); } TEST(WeakTests, MoveInitialisation){ sp::Shared<int> shared(new int(42)); sp::Weak<int> weak(shared); sp::Weak<int> weak2; weak2 = std::move(weak); auto tmp2 = weak2.lock(); EXPECT_TRUE(tmp2.exists()); EXPECT_EQ(*tmp2, 42); } TEST(WeakTests, AssignmentFromShared){ sp::Shared<int> shared(new int(42)); sp::Shared<int> shared1(new int(24)); sp::Weak<int> weak(shared); sp::Weak<int> weak1; auto tmp = weak.lock(); EXPECT_EQ(*tmp, 42); EXPECT_TRUE(tmp.exists()); weak1 = shared1; auto tmp1 = weak1.lock(); tmp1 = weak1.lock(); auto tmp2 = weak1.lock(); EXPECT_TRUE(tmp1.exists()); EXPECT_EQ(*tmp1, 24); } TEST(WeakTests, Uninitialized){ sp::Weak<int> weak; auto tmp = weak.lock(); EXPECT_FALSE(tmp.exists()); } TEST(WeakTests, DoubleFree){ sp::Shared<int>shared(new int(42)); EXPECT_EQ(*shared, 42); sp::Weak<int>weak1(shared); { auto tmp = weak1.lock(); EXPECT_TRUE(tmp.exists()); (*tmp) /= 2; EXPECT_EQ(*tmp, 21); } shared = sp::Shared<int>(new int (1337)); sp::Weak<int>weak2(shared); { auto tmp = weak1.lock(); EXPECT_TRUE(tmp.exists()); tmp = weak2.lock(); EXPECT_EQ(*tmp, 1337); } } int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
true
323dc9b2a2dce4886d48614f9797202abf6228aa
C++
deeepeshthakur/CodeFiles
/HackerRank/Strings/DnaModified.cpp
UTF-8
2,934
2.921875
3
[]
no_license
#include <string> #include <cstdio> #include <vector> #include <iostream> #include <climits> using namespace std; int main(){ int n; cin >> n; vector<string> raw_genes(n); for(int genes_i = 0; genes_i < n; genes_i++){ cin >> raw_genes[genes_i]; } vector<int> raw_health(n); for(int health_i = 0; health_i < n; health_i++){ cin >> raw_health[health_i]; } std::vector < int > modified_index (n); std::vector < std::string > genes{}; std::vector < int > health {}; genes.push_back(raw_genes[0]); health.push_back(raw_health[0]); for(int index = 1; index < n; index++) { int curr_size = genes.size(); bool check = true; for(int inner_index = 0; inner_index < curr_size && check; inner_index++) { if(genes[inner_index] == raw_genes[index]) { health[inner_index] += raw_health[index]; modified_index[index] = inner_index; check = false; } } if(check) { modified_index[index] = curr_size; genes.push_back(raw_genes[index]); health.push_back(raw_health[index]); } } std::cout << genes.size() << " NN " << endl; long max = 0, min = LONG_MAX; int s; cin >> s; for(int a0 = 0; a0 < s; a0++) { std::cout << a0 << " "; int first; int last; long curr_health = 0; string d; cin >> first >> last >> d; // your code goes here first = modified_index[first]; last = modified_index[last]; int len = d.length(); for(int index = 0; index < len; index++) { for( int inner = first; inner <= last; inner++) { if(d[index] == genes[inner][0]) { int curr_len = genes[inner].length(); bool check_point = true; if(index + curr_len <= len) { for( int i = 0; i < curr_len && check_point; i++) { if(d[index + i] != genes[inner][i]); check_point = false; } } else check_point = false; if(check_point) { curr_health += health[inner]; } } } } if(max < curr_health) max = curr_health; if(min > curr_health) min = curr_health; //std::cout << endl; } std::cout << endl; std::cout << min << " " << max << endl; return 0; }
true
013f6cfd37b3410d93f331b6774644a1ff23693f
C++
cloudsangwon/programmers
/백준/2493_탑.cpp
UTF-8
562
2.546875
3
[]
no_license
#include<iostream> #include<stack> #include<vector> #include<string> #include<algorithm> #include<cstring> #include<queue> #include<set> #include<cmath> using namespace std; int val; stack<pair<int, int>> st; int main(void) { cin.tie(0); ios_base::sync_with_stdio(false); int N; cin >> N; for (int i = 1; i <= N; i++) { cin >> val; while (!st.empty()) { if (st.top().second > val) { cout << st.top().first << " "; break; } st.pop(); } if (st.empty()) { cout << 0 << " "; } st.push(make_pair(i, val)); } return 0; }
true
9ac9d05e2955ac72e607df1a6422fc63be92f08c
C++
better-712/Compilers-project
/spl_project2/information.hpp
UTF-8
861
2.609375
3
[]
no_license
// // Created by 10578 on 2019/11/17. // #ifndef __INFORMATION_HPP__ #define __INFORMATION_HPP__ namespace SPL { /* Forward Declaration */ class Type; class Scan_Info { public: std::string lexeme; int line_no; Scan_Info(std::string lexeme, int line) : lexeme{lexeme}, line_no{line} {}; }; class Exp_Info { public: Exp_Info() : m_is_rvalue{false}, exp_type{nullptr} {} Exp_Info(Type *exp_type, bool t_is_rvalue); explicit Exp_Info(bool is_known); bool is_rvalue(); bool is_lvalue(); virtual bool is_known(); bool compassionate(Exp_Info *other); bool m_is_rvalue = false; Type *exp_type = nullptr; }; class Unknown_Exp_Info : public Exp_Info { bool is_known() override; }; } #endif //__INFORMATION_HPP__
true
0fc780427fae5fe539b5312fd89638cdc4409b74
C++
sency90/allCode
/jongmanbook/divide-edges.cc
UTF-8
1,115
2.75
3
[]
no_license
#include <cstdio> #include <vector> #include <string> #define TREE 0 #define FORD 1 #define BACK 2 #define CROSS 3 using namespace std; typedef pair<int,int> pii; const int inf = 0x3f3f3f3f; vector<pii> ed[4]; vector<int> v[7], discov(7); bool fin[7]; string s[4]={"Tree Edges", "Forward Edges", "Back Edges", "Cross Edges"}; int cnt=0; void dfs(int x) { discov[x]=++cnt; for(int y: v[x]) { if(discov[y]) { if(!fin[y]) ed[BACK].push_back({x,y}); else if(discov[y]<discov[x]) ed[CROSS].push_back({x,y}); else ed[FORD].push_back({x,y}); } else { ed[TREE].push_back({x,y}); dfs(y); } } fin[x]=true; } void mkedge(int x, int y) { v[x].push_back(y); } int main() { mkedge(0,1); mkedge(0,4); mkedge(0,5); mkedge(0,6); mkedge(1,2); mkedge(4,2); mkedge(5,3); mkedge(5,6); mkedge(2,0); mkedge(6,3); dfs(0); for(int i=0; i<4; i++) { printf("%s: ",s[i].c_str()); for(auto &p: ed[i]) printf("(%d,%d) ",p.first, p.second); puts(""); } return 0; }
true
4223887d042310fa944d54d92b978744ff6c7892
C++
1998factorial/leetcode
/weekly contest/contest115/prisonsByDays.cpp
UTF-8
509
2.671875
3
[]
no_license
class Solution { public: vector<int> prisonAfterNDays(vector<int>& cells, int N) { vector<int> ans; ans = cells; int mod = ((N-1) % 14) + 1; for(int i = 0; i < mod; i++){ for(int j = 0; j < 8; j++){ if(j == 0 || j == 7)ans[j] = 0; else{ if(cells[j-1] == cells[j+1])ans[j] = 1; else ans[j] = 0; } } cells = ans; } return ans; } };
true
5fc54f0b03c6f861ad9d7d03926fb9df371bd067
C++
Svxy/The-Simpsons-Hit-and-Run
/game/code/input/RealController.h
UTF-8
4,555
2.703125
3
[]
no_license
/****************************************************************************** File: RealController.h Desc: Interface for the RealController class. - RealController essentially is a physical controller class. - a wrapper around IRadController. Date: May 16, 2003 History: *****************************************************************************/ #ifndef REALCONTROLLER_H #define REALCONTROLLER_H //======================================== // System Includes //======================================== #include <radcontroller.hpp> #include <list> using namespace std; //======================================== // Nested Includes //======================================== #include <input/controller.h> #include <input/mapper.h> #include <input/virtualinputs.hpp> class UserController; /***************************************** Some typedefs for convienince ****************************************/ typedef ref< IRadController > RADCONTROLLER; typedef list< IRadControllerInputPoint* > RADINPUTPOINTLIST; typedef list< IRadControllerInputPoint* >::iterator INPUTPOINTITER; //============================================================================= // Enumerations //============================================================================= // Types of real controllers. enum eControllerType { GAMEPAD = 0, // gamepad/joystick KEYBOARD, MOUSE, STEERINGWHEEL, NUM_CONTROLLERTYPES }; // Directions which inputs can process. enum eDirectionType { DIR_UP = 0, DIR_DOWN, DIR_RIGHT, DIR_LEFT, NUM_DIRTYPES }; //============================================================================= // Class: RealController //============================================================================= // // Description: The base class for every device plugged in to receive input // from the user. There is one instance for each keyboard, mouse, // gamepad... // //============================================================================= class RealController { public: RealController( eControllerType type ); virtual ~RealController(); RADCONTROLLER getController() const { return m_radController; } bool IsConnected() const { return m_bConnected; } void Connect() { m_bConnected = true; } void Disconnect() { m_bConnected = false; } eControllerType ControllerType() const { return m_eControllerType; } void Init( IRadController* pController ); void Release(); // Return true if the dxKey is one of the following types of inputs. virtual bool IsInputAxis( int dxKey ) const; virtual bool IsMouseAxis( int dxKey ) const; virtual bool IsPovHat( int dxKey ) const; // Returns true if this is a valid input for the controller. virtual bool IsValidInput( int dxKey ) const = 0; // Returns true if the key is banned for mapping. virtual bool IsBannedInput( int dxKey ) const; // Sets up a mapping from a dxkey/direction to a virtual button virtual bool SetMap( int dxKey, eDirectionType dir, int virtualButton ) = 0; // Retrieves the virtual button of the given type mapped to a dxKey, direction virtual int GetMap( int dxKey, eDirectionType dir, eMapType map ) const = 0; // Clears the specified mapping so it no longer exists. virtual void ClearMap( int dxKey, eDirectionType dir, int virtualButton ) = 0; // Clears all the cached mappings. virtual void ClearMappedButtons() = 0; // Returns the name of the input. const char* GetInputName( int dxKey ) const; // Store & release registered input points. void AddInputPoints( IRadControllerInputPoint* pInputPoint ); void ReleaseInputPoints( UserController* parent ); // Returns the direct input code representing a given input point for // the controller, or Input::INVALID_CONTROLLERID if the i.p. doesn't exist. int GetDICode( int inputpoint ) const; protected: // Sets up an input point index -> direct input keycode map for the // controller in m_InputToDICode. Called automatically by Init(). virtual void MapInputToDICode() = 0; protected: RADCONTROLLER m_radController; bool m_bConnected; eControllerType m_eControllerType; RADINPUTPOINTLIST m_inputPointList; int* m_InputToDICode; int m_numInputPoints; }; #endif
true
33d0edee86a0c1e42eee9ab090a0c783c0011d1a
C++
zhouhuahui/OSExperiment
/1_1.cpp
UTF-8
1,761
3.234375
3
[]
no_license
/*基于fork()系统调用,实现两个生产者和两个消费者的程序 */ #include "sys/types.h" #include "sys/file.h" #include "sys/wait.h" #include "unistd.h" #include "stdio.h" #include "string.h" #include "stdlib.h" using namespace std; char r_buf[4]; /*读缓冲*/ char w_buf[4]; /*写缓冲*/ int pipe_fd[2]; /*pipe_fd[0]是读,pipe_fd[1]是写*/ pid_t pid1, pid2, pid3, pid4; int producer(int id); int consumer(int id); int main(int argc, char **argv) { //创建管道文件 if(pipe(pipe_fd) < 0){ printf("pipe create error \n"); exit(-1); } else{ printf("pipe is created successfully! \n"); //创建子进程 if((pid1 = fork()) == 0) producer(1); if((pid2 = fork()) == 0) producer(2); if((pid3 = fork()) == 0) consumer(1); if((pid4 = fork()) == 0) consumer(2); } close(pipe_fd[0]); close(pipe_fd[1]); int pid, status; for(int i=0; i<4; i++) pid = wait(&status); exit(0); } int producer(int id) { printf("producer %d is running! \n", id); close(pipe_fd[0]); for(int i=1; i<10; i++){ sleep(10); if(id == 1) strcpy(w_buf, "aaa\0"); else strcpy(w_buf, "bbb\0"); if(write(pipe_fd[1], w_buf, 4) == -1) printf("write to pipe error! \n"); else printf("producer %d write to pipe! \n", id); } close(pipe_fd[1]); printf("producer %d is over! \n", id); exit(id); } int consumer(int id) { close(pipe_fd[1]); printf("consumer %d is running! \n", id); if(id == 1) strcpy(w_buf, "ccc\0"); else strcpy(w_buf, "ddd\0"); while(1){ sleep(1); strcpy(r_buf, "eee\0"); if(read(pipe_fd[0], r_buf, 4) == 0) break; printf("consumer %d get %s, while the w_buf is %s\n", id, r_buf, w_buf); } close(pipe_fd[0]); printf("consumer %d is over! \n", id); exit(id); }
true
4c7bfc8d99c076c5105cbd7778a26f30d2a5203f
C++
WOWO5/Code_Wearhouse
/Experiment/6/1.cpp
UTF-8
247
3.125
3
[]
no_license
#include <iostream> using namespace std; int main() { int a[10] = { 0,1,2,3,4,5,6,7,8,9 }; int *p = &a[0], *q = &a[9]; cout << *p << ' '; cout << *(++p) << endl; cout << *q << ' '; cout << *(--q) << endl; cout << q - p << endl; return 0; }
true
f1ba77807c242fa06aff3f2a5a807e1f05279178
C++
fusion809/CSC2402_Revision
/ODE.h
UTF-8
14,337
3.390625
3
[]
no_license
// Used to write to file #include <fstream> // Required for system call later #include <stdio.h> #include <stdlib.h> #include <sstream> #include <vecOps.h> #include <input.h> // Load required namespace using namespace std; /** * Solution object class. */ class solClass { public: // Simplest constructor solClass(vector<double>, vector<vector<double>>); // RKF45 constructor solClass(vector<double>(*f)(double, vector<double>, vector<double>), vector<double>, double, double, vector<double>, double, int, double); // Constructor that uses other methods solClass(vector<double>(*f)(double, vector<double>, vector<double>), vector<double>, vector<double>, vector<double>, string); // Write to CSV void writeToCSV(int, string, vector<string>); private: // Solution variables. // No compelling reason they need to be private, but they can be. vector<double> t; vector<vector<double>> X; }; /** * Write solution to CSV file. * * @param prec Precision to which the solution should be written to the * CSV file. * @param filename Filename (including file extension) of file that solution * is to be written to. * @param headings Vector containing headings for each variable to be written * to the file. */ void solClass::writeToCSV(int prec, string filename, vector<string> headings) { if (headings.size() != X[0].size() + 1) { cout << "There should be a heading for t and each variable in the"; cout << " separate columns of X" << endl; throw; } int N = t.size(); // Open file ofstream file; file.open(filename); // Write headings to file for (int i = 0 ; i < headings.size(); i++) { if (i != headings.size()-1) { file << headings[i] << ","; } else { file << headings[i] << endl; } } // Write solution to file for (int i = 0; i < N; i++) { file << t[i] << setprecision(prec) << ","; for (int j = 1 ; j < headings.size()-1; j++) { file << X[i][j-1] << ","; } file << X[i][headings.size()-2] << endl; } } /** * Constructor for solClass. * * @param tInput t vector that the t member variable is to be set to. * @param XInput X vector that the X member variable is to be set to. */ solClass::solClass(vector<double> tInput, vector<vector<double>> XInput) { t = tInput; X = XInput; } /** * Applies Euler's method to solving the ODE: * dX/dt = f(t, X, params) * where X(t[0]) = X0. * * @param f Function that takes the arguments time value (scalar), * corresponding X array and params and returns dX/dt. * @param X0 X at t[0]. * @param t Vector of type double consisting of time values we want * the solution at. * @param params Vector of type double consisting of parameter values. * @return 2d array of X values; rows correspond to different t values. */ vector<vector<double>> Euler(vector<double>(*f)(double, vector<double>, vector<double>), vector<double> X0, vector<double> t, vector<double> params) { // Initializing variables double dt; int N = t.size()-1; vector<vector<double>> X; vector<double> nextX; // First entry should be X0 X.push_back(X0); // Loop over time values for (int i = 0; i < N; i++) { dt = t[i+1]-t[i]; nextX = vecAdd(X[i], scalMult(dt, f(t[i], X[i], params))); X.push_back(nextX); } return X; } /** * Applies Modified Euler's method to solving the ODE: * dX/dt = f(t, X, params) * where X(t[0]) = X0. * * @param f Function that takes the arguments time value (scalar), * corresponding X array and params and returns dX/dt. * @param X0 X at t[0]. * @param t Vector of type double consisting of time values we want * the solution at. * @param params Vector of type double consisting of parameter values. * @return 2d array of X values; rows correspond to different t values. */ vector<vector<double>> ModEuler(vector<double>(*f)(double, vector<double>, vector<double>), vector<double> X0, vector<double> t, vector<double> params) { // Initializing variables double dt; int N = t.size()-1; int sysSize = X0.size(); vector<vector<double>> X; vector<double> nextX(sysSize), k1(sysSize), k2(sysSize); // First entry should be X0 X.push_back(X0); // Loop over time values for (int i = 0; i < N; i++) { dt = t[i+1]-t[i]; k1 = scalMult(dt, f(t[i], X[i], params)); k2 = scalMult(dt, f(t[i+1], vecAdd(X[i], k1), params)); nextX = vecAdd(X[i], scalMult(0.5, vecAdd(k1, k2))); X.push_back(nextX); } return X; } /** * Applies Runge-Kutta fourth-order method to solving the ODE: * dX/dt = f(t, X, params) * where X(t[0]) = X0. * * @param f Function that takes the arguments time value (scalar), * corresponding X array and params and returns dX/dt. * @param X0 X at t[0]. * @param t Vector of type double consisting of time values we want * the solution at. * @param params Vector of type double consisting of parameter values. * @return 2d array of X values; rows correspond to different t values. */ vector<vector<double>> RK4(vector<double>(*f)(double, vector<double>, vector<double>), vector<double> X0, vector<double> t, vector<double> params) { // Initializing variables double dt; int N = t.size()-1; int sysSize = X0.size(); vector<vector<double>> X; vector<double> nextX(sysSize), k1(sysSize), k2(sysSize), k3(sysSize); vector<double> k4(sysSize); // First entry should be X0 X.push_back(X0); // Loop over time values for (int i = 0; i < N; i++) { dt = t[i+1]-t[i]; k1 = scalMult(dt, f(t[i], X[i], params)); k2 = scalMult(dt, f(t[i]+dt/2, vecAdd(X[i], scalMult(0.5, k1)), params)); k3 = scalMult(dt, f(t[i]+dt/2, vecAdd(X[i], scalMult(0.5, k2)), params)); k4 = scalMult(dt, f(t[i]+dt, vecAdd(X[i], k3), params)); nextX = vecAdd(X[i], scalMult(1.0/6.0, vecAdd(vecAdd(vecAdd(k1, scalMult(2, k2)), scalMult(2, k3)), k4))); X.push_back(nextX); } return X; } /** * Applies the Runge-Kutta-Fehlberg 4/5th order method to solving the ODE: * dX/dt = f(t, X, params) * where X(t0) = X0. * * @param f Function that takes the arguments time value (scalar), * corresponding X array and params and returns dX/dt. * @param X0 X at t0. * @param t0 Starting t value. * @param tf Final t value. * @param params Vector of type double consisting of parameter values. * @param tol A double representing the error tolerance to be used * (default=1e-9). * @param itMax An integer representing the maximum number of iterations * allowable. * @param dtInit Initial guess for dt. * @return Object of type solClass containing computed t and X values. */ solClass RKF45(vector<double>(*f)(double, vector<double>, vector<double>), vector<double> X0, double t0, double tf, vector<double> params, double tol=1e-9, int itMax=1000000, double dtInit=1e-1) { // Initialize required vectors vector<double> t; vector<vector<double>> X; vector<double> k1, k2X, k2, k3X, k3, k4X, k4, k5X, k5, k6X, k6, X1, X2, RX; // Add first entries to t and X t.push_back(t0); X.push_back(X0); // Initialize scalar variables double R; int i = 0; double s; double dt = dtInit; // Loop over time until either t[i] = tf is reached or we exceed the // maximum number of iterations. while ( ( t[i] < tf ) && (i < itMax)) { dt = std::min(dt, tf-t[i]); // Predictor-correctors k1 = scalMult(dt, f(t[i], X[i], params)); k2X = vecAdd(X[i], scalMult(1.0/4.0, k1)); k2 = scalMult(dt, f(t[i] + dt/4.0, k2X, params)); k3X = vecAdd(vecAdd(X[i], scalMult(3.0/32.0, k1)), scalMult(9.0/32.0, k2)); k3 = scalMult(dt, f(t[i] + 3.0*dt/8.0, k3X, params)); k4X = vecAdd(vecAdd(vecAdd(X[i], scalMult(1932.0/2197.0, k1)), scalMult(-7200.0/2197.0, k2)), scalMult(7296.0/2197.0, k3)); k4 = scalMult(dt, f(t[i] + 12.0*dt/13.0, k4X, params)); k5X = vecAdd(vecAdd(vecAdd(vecAdd(X[i], scalMult(439.0/216.0, k1)), scalMult(-8.0, k2)), scalMult(3680.0/513.0, k3)), scalMult(-845.0/4104.0, k4)); k5 = scalMult(dt, f(t[i]+dt, k5X, params)); k6X = vecAdd(vecAdd(vecAdd(vecAdd(vecAdd(X[i], scalMult(-8.0/27.0, k1)), scalMult(2.0, k2)), scalMult(-3544.0/2565.0, k3)), scalMult(1859.0/4104.0, k4)), scalMult(-11.0/40.0, k5)); k6 = scalMult(dt, f(t[i]+dt/2.0, k6X, params)); // 4th and 5th order approximation to X[i+1] X1 = vecAdd(vecAdd(vecAdd(vecAdd(X[i], scalMult(25.0/216.0, k1)), scalMult(1408.0/2565.0, k3)), scalMult(2197.0/4104.0, k4)), scalMult(-1.0/5.0, k5)); X2 = vecAdd(vecAdd(vecAdd(vecAdd(vecAdd(X[i], scalMult(16.0/135.0, k1)), scalMult(6656.0/12825.0, k3)), scalMult(28561.0/56430.0, k4)), scalMult(-9.0/50.0, k5)), scalMult(2.0/55.0, k6)); // Measure of error in X1 RX = scalMult(pow(dt, -1), vecAbs(vecAdd(X1, scalMult(-1.0, X2)))); R = *max_element(RX.begin(), RX.end()); // Adjust step size scaling factor according to R if (R != 0) { s = pow(tol/(2.0*R), 0.25); } else { s = 1.0; } // If R is below error tolerance move on to next step if (R <= tol) { t.push_back(t[i]+dt); X.push_back(X1); i++; } // Adjust step size by scaling factor dt *= s; } // Write to solution object solClass solution(t, X); return solution; } /** * Constructor for solClass that uses specified method to solve ODE for * specified t values with specified initial condition and writes t and X to * solClass object. * * @param f Function that takes the arguments time value (scalar), * corresponding X array and params and returns dX/dt. * @param X0 X at tInput[0]. * @param tInput Vector of type double consisting of time values we want * the solution at. * @param params Vector of type double consisting of parameter values. * @param method Non-adaptive method to be used to integrate ODE. Accepted * @return N/A. */ solClass::solClass(vector<double>(*f)(double, vector<double>, vector<double>), vector<double> X0, vector<double> tInput, vector<double> params, string method="RK4") { t = tInput; if (method == "RK4") { X = RK4(f, X0, tInput, params); } else if (method == "Euler") { X = Euler(f, X0, tInput, params); } else if (method == "ModEuler") { X = ModEuler(f, X0, tInput, params); } else { cout << "No method called " << method << " is callable by this"; cout << " constructor." << endl; } } /** * Constructor for solClass that uses RKF45 to initialize t and X. * * @param f Function that takes the arguments time value (scalar), * corresponding X array and params and returns dX/dt. * @param X0 X at t0. * @param t0 Starting t value. * @param tf Final t value. * @param params Vector of type double consisting of parameter values. * @param tol A double representing the error tolerance to be used * (default=1e-9). * @param itMax An integer representing the maximum number of iterations * allowable. * @param dtInit Initial guess for dt. * @return N/A. */ solClass::solClass(vector<double>(*f)(double, vector<double>, vector<double>), vector<double> X0, double t0, double tf, vector<double> params, double tol=1e-9, int itMax=1000000, double dtInit=1e-1) { *this = RKF45(f, X0, t0, tf, params, tol, itMax, dtInit); } /** * Solve the ODE using the four algorithms implemented in ODE.h and produce * plots in SVG using Python's Matplotlib. * * @param f Function that returns dX/dt from the arguments t, X and * params. * @param X0 Initial condition. * @param t0 Initial time. * @param tf Final time. * @param tol Error tolerance. * @param N Number of steps to be used; t array for Euler, ModEuler * and RK4 will have N+1 elements. * @param prec The precision solution is to be written to CSV files at. * @param params A vector of parameters for f. * @param prob String containing problem name. * @param headings Vector of headings to be used in CSV file. * @param pyScript Python script file name (including file extension). * @return Nothing. */ void solveProblem(vector<double> (*f)(double, vector<double>, vector<double>), vector<double> X0, double t0, double tf, double tol, int N, int prec, vector<double> params, string prob, vector<string> headings, string pyScript) { // This makes t equivalent to np.linspace(t0, tf, num=N+1) vector<double> t = linspace(t0, tf, N); // Initialize solution objects solClass EulerSol(f, X0, t, params, "Euler"); solClass ModEulerSol(f, X0, t, params, "ModEuler"); solClass RK4Sol(f, X0, t, params, "RK4"); solClass solution(f, X0, t0, tf, params, tol); // Write solution data to CSV file (easiest to import into Python) EulerSol.writeToCSV(prec, "ODE_Euler.csv", headings); ModEulerSol.writeToCSV(prec, "ODE_ModEuler.csv", headings); RK4Sol.writeToCSV(prec, "ODE_RK4.csv", headings); solution.writeToCSV(prec, "ODE_RKF45.csv", headings); // Write prob to file so Python script can use it ofstream file; file.open("ODE_prob.txt"); file << prob; file.close(); // Use Python to generate relevant plots and save as svgs stringstream cmd; cmd << "python "; cmd << pyScript; system(cmd.str().c_str()); } /** * Writes tolerances to file so that it can be read by Python script. * * @param tol Error tolerance to be written to ODE_tolerance.txt */ void writeTol(double tol) { // Write to tolerance file ofstream file; file.open("ODE_tolerance.txt"); file << tol << endl; file.close(); }
true
77066e211ed9b53e4ee7ae16a544b228dd749499
C++
nya3jp/icfpc2015
/simulator/game.h
UTF-8
5,747
2.71875
3
[]
no_license
#ifndef GAME_H_ #define GAME_H_ #include <iostream> #include <vector> #include <glog/logging.h> #include "board.h" #include "common.h" #include "unit.h" #include "rand_generator.h" struct Bound { int top, bottom, left, right; }; class GameData { public: GameData(); int id() const { return id_; } const std::vector<Unit>& units() const { return units_; } const std::vector<HexPoint>& spawn_position() const { return spawn_position_; } const Board& board() const { return board_; } int source_length() const { return source_length_; } const std::vector<int>& source_seeds() const { return source_seeds_; } const std::vector<Bound>& unit_pivot_bounds() const { return unit_pivot_bounds_; } void Load(const picojson::value& parsed); void Dump(std::ostream* os) const; private: int id_; // TODO: do not copy units_. std::vector<Unit> units_; std::vector<HexPoint> spawn_position_; Board board_; int source_length_; std::vector<int> source_seeds_; std::vector<Bound> unit_pivot_bounds_; }; inline std::ostream& operator<<(std::ostream& os, const GameData& data) { data.Dump(&os); return os; } class Game { public: Game(); ~Game(); int id() const { return data_->id(); } int score() const { return score_; } int current_index() const { return current_index_; } int units_remaining() const { return data_->source_length() - current_index_; } bool is_finished() const { return is_finished_; } bool error() const { return error_; } void Init(const GameData* data, int rand_seed_index); void Dump(std::ostream* os) const; const Board& GetBoard() const { return board_; } // Find a new unit, and put it to the source. bool SpawnNewUnit(); enum class Command { E, W, SE, SW, CW, CCW, IGNORED, }; static const char command_char_map_[7][7]; static Command Char2Command(char code); static const char* Command2Chars(Command com); // Converts command sequence to string, ignoring power phrase stuff. static std::string Commands2SimpleString( const std::vector<Command>& commands); // Given the current position and the op command, returns the next position. static UnitLocation NextUnit(const UnitLocation& prev_unit, Command command); bool Run(Command action); bool RunSequence(const std::vector<Command>& actions); // Given the current unit position, returns a command to lock the unit // at the position, or returns IGNORED if it's impossible to lock it. Command GetLockCommand(const UnitLocation& current) const; // Returns whether the unit is lockable at the given position. bool IsLockable(const UnitLocation& current) const; // Returns whether it is lockable by the given command. bool IsLockableBy(const UnitLocation& current, Command cmd) const; typedef std::pair<UnitLocation, std::vector<Command>> SearchResult; // Does BFS search from current_unit_ to return the list of lockable locations // with the command sequence to reach there. void ReachableUnits(std::vector<SearchResult>* result) const; const Board& board() const { return board_; } const UnitLocation& current_unit() const { return current_unit_; } UnitLocation GetUnitAtSpawnPosition(size_t index) const { return UnitLocation(&data_->units()[index], data_->spawn_position()[index]); } size_t GetNumberOfUnits() const { return data_->units().size(); } const std::vector<Unit>& units() const { return data_->units(); } const int prev_cleared_lines() const { return prev_cleared_lines_; } private: const GameData* data_; Board board_; RandGenerator rand_; UnitLocation current_unit_; int current_index_; std::vector<UnitLocation> history_; int score_; int prev_cleared_lines_; bool is_finished_; bool error_; }; inline Game::Command operator++( Game::Command& x ) { return x = (Game::Command)(((int)(x) + 1)); } inline std::ostream& operator<<(std::ostream& os, const Game& game) { game.Dump(&os); return os; } struct CurrentState { CurrentState(const Game& game) : game_(game) { } const Game& game_; }; inline std::ostream& operator<<(std::ostream& os, const CurrentState& state) { state.game_.Dump(&os); return os; } inline Game::Command ParseCommand(char c) { switch(c) { case 'p': case '\'': case '!': case '.': case '0': case '3': return Game::Command::W; case 'b': case 'c': case 'e': case 'f': case 'y': case '2': return Game::Command::E; case 'a': case 'g': case 'h': case 'i': case 'j': case '4': return Game::Command::SW; case 'l': case 'm': case 'n': case 'o': case ' ': case '5': return Game::Command::SE; case 'd': case 'q': case 'r': case 'v': case 'z': case '1': return Game::Command::CW; case 'k': case 's': case 't': case 'u': case 'w': case 'x': return Game::Command::CCW; case '\t': case '\n': case '\r': return Game::Command::IGNORED; defult: LOG(FATAL) << "Unknown Character: " << c << "(" << (int) c << ")"; } } inline std::ostream& operator<<(std::ostream& os, Game::Command command) { switch (command) { case Game::Command::W: os << "W"; break; case Game::Command::E: os << "E"; break; case Game::Command::SW: os << "SW"; break; case Game::Command::SE: os << "SE"; break; case Game::Command::CW: os << "CW"; break; case Game::Command::CCW: os << "CCW"; break; case Game::Command::IGNORED: os << "IGNORED"; break; default: LOG(FATAL) << "Unknown command"; } return os; } inline Game::Command Game::Char2Command(char code) { return ParseCommand(code); } #endif // GAME_H_
true
8b42e8fa4f84ab8c382dacc0035c7e5697e96990
C++
jer22/OI
/hdu/bestcoder64div1/B/b.cpp
UTF-8
951
2.625
3
[]
no_license
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include <vector> using namespace std; int T; long long n; long long t[60]; void init() { t[1] = 1; int id = 1; long long j = 2; while (j < 10000000000000000ll) { j <<= 1; id++; t[id] = (t[id - 1] << 1) + (j >> 1); } } int get(long long x) { int id = 1; long long j = 2; while (j - 1 <= x) { j <<= 1; id++; } return id - 1; } int main() { freopen("b.in", "r", stdin); scanf("%d", &T); init(); while (T--) { cin >> n; // if (n == 1) { // printf("1\n"); // return 0; // } else if (n == 2) { // printf("2\n"); // return 0; // } else if (n == 3) { // printf("4\n"); // return 0; // } long long ans = 0; int tmp = get(n); ans += t[tmp]; n -= (1ll << tmp) - 1; ans += n; while (n) { n--; tmp = get(n); ans += t[tmp]; n -= (1ll << tmp) - 1; ans += n; } cout << ans << endl; } return 0; }
true
9af866a5253716bca9a12c2870df4e872e7f383d
C++
mikolalysenko/Ludum-Dare-21
/src/menu.cc
UTF-8
2,393
2.875
3
[]
no_license
#include "menu.h" #include "text.h" #include "sound.h" #include <GL/glfw.h> Menu::Menu(const char* t) { title = t; } void Menu::set_esc_option(int i) { escoption = i; } void Menu::activate_esc_option() { curoption = escoption; select_option(); } void Menu::next_option() { curoption++; if(curoption >= options.size()) curoption = options.size() - 1; else play_sound_from_group(SOUND_GROUP_MENU_CHANGE); } void Menu::prev_option() { curoption--; if(curoption < 0) curoption = 0; else play_sound_from_group(SOUND_GROUP_MENU_CHANGE); } void Menu::select_option() { //don't do anything out of bounds if(curoption < 0 || curoption > options.size()) return; if(options[curoption].cb != NULL) { play_sound_from_group(SOUND_GROUP_MENU_SELECT); options[curoption].cb(options[curoption].data); } } void Menu::reset() { curoption = 0; } void Menu::render() { //this block of code is dedicated to darkening the background so that the menu is more easily visible. I have no idea if this is the best way to do this. glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(0, 1, 0, 1); //we just want to put a quad over the whole screen, so set up simple 0-1 bounds glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); //GL_COLOR_BUFFER_BIT may be enough here, but I'm not sure if the glEnable will get popped, so I am pushing all attrib bits glPushAttrib(GL_ALL_ATTRIB_BITS); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(0, 0, 0, .5); glBegin(GL_QUADS); glVertex2i(0, 1); glVertex2i(1, 1); glVertex2i(1, 0); glVertex2i(0, 0); glEnd(); glPopAttrib(); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); float xp = .3; float yp = .7; float size = .05; float padding = 0.01; float optx, opty; show_text(title, xp, yp, size, TEXT_STYLE_BOLD); yp -= size + padding; for(int x = 0; x < options.size(); x++) { if(x == curoption) { optx = xp; opty = yp; } show_text(options[x].option, xp, yp, size); yp -= size + padding; } show_text(">", optx - .05, opty, size); } void Menu::add_option(const char* text, void (*func)(void*), void* data) { MenuOption o; o.option = text; o.cb = func; o.data = data; options.push_back(o); }
true
884c8ab97ebcbbb681fe1ed7a98c1c4912d4dfb3
C++
justkrismanohar/TA_Tools
/COMP2603Marker/comp1602-copiers/Lauryn_Micoo_213949_assignsubmission_file_.cpp
UTF-8
3,766
2.8125
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; bool isPerfectNum(int n){ int i, sum=0; for(i=1;i<n;i=i+1){ if(n%i==0) sum=sum+i; } if(sum==n) return true; else return false; } bool isPrime(int n){ int i; for(i=2;i<=n/2;i=i=i+1){ if(n%i==0) return false; } return true; } bool isPerfectSq(int n){ int i,sq; for(i=1;i<=n/2;i=i+1){ sq=i*i; if(sq==n) return true; } return false; } bool isSphenic(int n){ int i,prod=1,count=0; for(i=2;i<=n/2;i=i+1){ if((n%i==0)&&(isPrime(i))){ prod=prod*i; count=count+1; } } if((count==3)&&(prod==n)) return true; else return false; } void Deter(bool n){ if(n==true) cout<<"Y"; else cout<<"N"; } void BinaryEq(int n){ int binary,i=0,bin[7]; while(n>0){ binary=n%2; bin[i]=binary; n=n/2; i=i+1; } for(int j=i-1;j>=0;j=j-1){ cout<<bin[j];} } void Range(int n){ int i=1; for(i=1;i<=n;i=i+1){ if(i%5==0) cout<<"*"; } } int main(){ ifstream inputFile; int num,validfav=0,invalidfav=0,i=1,m,inval[1000], tracknum[101]; int countA=0,countB=0,countC=0,countD=0,countE=0,countF=0,countG=0,countH=0,countI=0,countJ=0; inputFile.open("numbers.txt"); if(!inputFile.is_open()){ cout<<"Could not open numbers.txt"<<endl; return 1; } for(m=0;m<101;m=m+1) tracknum[m]=0; cout<<"Numbers"<<"\t\t"<<"Perfect?"<<"\t"<<"Prime?"<<"\t\t"<<"Perfect Square?"<<"\t\t"<<"Sphenic?"<<"\t"<<"Binary Equiv."<<endl; cout<<"======"<<"\t\t"<<"======="<<"\t\t"<<"========"<<"\t"<<"============="<<"\t\t"<<"========"<<"\t"<<"============="<<endl; inputFile>>num; while(num!=-1){ if((num>=0)&&(num<=100)){ tracknum[num]=tracknum[num]+1; if(num!=0){ cout<<num<<"\t\t";Deter(isPerfectNum(num));cout<<"\t\t";Deter(isPrime(num));cout<<"\t\t\t";Deter(isPerfectSq(num));cout<<"\t\t";Deter(isSphenic(num));cout<<"\t\t"; BinaryEq(num); cout<<endl; validfav=validfav+1; if((num>=1)&&(num<=10)) countA=countA+1; if((num>=11)&&(num<=20)) countB=countB+1; if((num>=21)&&(num<=30)) countC=countC+1; if((num>=31)&&(num<=40)) countD=countD+1; if((num>=41)&&(num<=50)) countE=countE+1; if((num>=51)&&(num<=60)) countF=countF+1; if((num>=61)&&(num<=70)) countG=countG+1; if((num>=71)&&(num<=80)) countH=countH+1; if((num>=81)&&(num<=90)) countI=countI+1; if((num>=91)&&(num<=100)) countJ=countJ+1;} } else{ inval[invalidfav]=num; invalidfav=invalidfav+1; } inputFile>>num; } inputFile.close(); int j; cout<<"The invalid numbers are:"<<endl; for(j=0;j<invalidfav;j=j+1){ cout<<inval[j]<<","; if((j+1)%5==0) cout<<endl; } cout<<endl; cout<<"Range"<<"\t"<<"Histogram"<<endl; cout<<"===================================="<<endl; cout<<"1-10"<<"\t";Range(countA);cout<<endl; cout<<"11-20"<<"\t";Range(countB);cout<<endl; cout<<"21-30"<<"\t";Range(countC);cout<<endl; cout<<"31-40"<<"\t";Range(countD);cout<<endl; cout<<"41-50"<<"\t";Range(countE);cout<<endl; cout<<"51-60"<<"\t";Range(countF);cout<<endl; cout<<"61-70"<<"\t";Range(countG);cout<<endl; cout<<"71-80"<<"\t";Range(countH);cout<<endl; cout<<"81-90"<<"\t";Range(countI);cout<<endl; cout<<"91-100"<<"\t";Range(countJ);cout<<endl; cout<<"Amount of students who specified valid favourite numbers:"<<validfav<<endl; cout<<"Amount of students who specified invalid favourite numbers:"<<invalidfav<<endl; cout<<"Amount of students who did not reveal their favourite number:"<<tracknum[0]<<endl; int n; cout<<"The number/s that was/were chosen the most by the students is/are:"<<endl; for(n=1;n<=100;n=n+1){ if(tracknum[n]>=2) cout<<n<<","; } cout<<endl; int l; cout<<"The number/s that was/chosen the least by the students is/are:"<<endl; for(l=1;l<=100;l=l+1){ if(tracknum[l]==1) cout<<l<<","; } cout<<endl; return 0; }
true
a8675b82fb78f8621aa4249715d752792aa39c0d
C++
RedRyanD/Shapes
/inc/Shape.h
UTF-8
608
2.96875
3
[]
no_license
#ifndef SHAPE_H #define SHAPE_H class Shape { protected: //acess granted to chidren double Height; double Width; private: //no access public: //access to everyone static int NumOfShapes; //static makes value the same for all instances Shape(double lenght); Shape(double height, double width); Shape(); virtual ~Shape(); void SetHeight(double height); double GetHeight(); void SetWidth(double width); double GetWidth(); static int GetNumOfShapes(); virtual double Area(); //virtual as each instance will override / have its own area function }; #endif
true
cb33cc067fb9e825d6cc03e2aa6368ea652c9079
C++
aryan619348/DataStructures
/stacks_infix_postfix/evaluate_postfix.cpp
UTF-8
2,956
3.734375
4
[]
no_license
#include <iostream> #include <stack> #include <math.h> #include "convert_prefix.h" #define MAX 10 using namespace std; string question(string detect); int num_variables_postfix(string postfix); float compute_postfix(string postfix, float variable_values[]); float calc(float top, float below_top, char op); int main() { string detect; string postfix; int num_variables; cout << "Type CONVERT to convert infix to postfix/ Type CALC to directly calculate postfix \n"; cin >> detect; postfix = question(detect); cout << "Postfix = " << postfix << endl; num_variables = num_variables_postfix(postfix); cout << "Number of variables = " << num_variables << endl; float variables[num_variables]; cout << "Enter the values of variables in order : \n"; for (int i = 0; i < num_variables; i++) { cin >> variables[i]; } float result = compute_postfix(postfix, variables); cout << " answer = " << result << endl; return 0; } float compute_postfix(string postfix, float variable_values[]) { float top, below_top, push, answer; int var = 0; stack<char> evaluation; for (int i = 0; i < postfix.size(); i++) { if ((postfix[i] >= 'a' && postfix[i] <= 'z') || (postfix[i] >= 'A' && postfix[i] <= 'Z')) { evaluation.push(variable_values[var]); var += 1; } else if (postfix[i] == '+' || postfix[i] == '-' || postfix[i] == '*' || postfix[i] == '/' || postfix[i] == '^') { top = evaluation.top(); evaluation.pop(); // cout << top << endl; below_top = evaluation.top(); evaluation.pop(); // cout << below_top << endl; push = calc(top, below_top, postfix[i]); // cout << push << endl; evaluation.push(push); } } answer = evaluation.top(); return answer; } string question(string detect) { string infix; string post; stack<char> conversion; if (detect == "CONVERT") { cout << "Enter an infix to convert to postfix: \n"; cin >> infix; post = convert(infix, conversion); } else if (detect == "CALC") { cout << "Enter a postfix to calculate \n"; cin >> post; } return post; } int num_variables_postfix(string postfix) { int count = 0; for (int i = 0; i < postfix.size(); i++) { if ((postfix[i] >= 'a' && postfix[i] <= 'z') || (postfix[i] >= 'A' && postfix[i] <= 'Z')) { count += 1; } } return count; } float calc(float top, float below_top, char op) { if (op == '+') return below_top + top; else if (op == '-') return below_top - top; else if (op == '^') return pow(below_top, top); else if (op == '*') return below_top * top; else if (op == '/') return below_top / top; else return 0; }
true
3687a23b481a77fd96bb13abda47bd05b371bf23
C++
algoriddle/cp
/uva/11727.cc
UTF-8
423
3.078125
3
[ "MIT" ]
permissive
#include <iostream> #include <utility> using namespace std; int main() { ios::sync_with_stdio(false); int t; cin >> t; for (int i = 1; i <= t; i++) { int a, b, c; cin >> a >> b >> c; if (a > b) { swap(a, b); } cout << "Case " << i << ": "; if (c < a) { cout << a; } else if (c > b) { cout << b; } else { cout << c; } cout << endl; } return 0; }
true
7df4ff57fdc8afce620910869d5c27c64bba1581
C++
atafoa/oopSamples
/Homework 7/bonus_1/aaa2575_Extendable_Arm.h
UTF-8
466
2.71875
3
[]
no_license
#ifndef EXTENDABLE_ARM_H #define EXTENDABLE_ARM_H #include "aaa2575_Arm_Robot.h" using namespace std; class Extendable_Arm : public virtual Arm_Robot { public: Extendable_Arm(int mn, string n, int bl, int l, int wl, int el, robotType t) : extend_length(el), is_extended(false), Robot(mn, n, bl, t), Arm_Robot(mn, n, bl, el + l, wl, t) {}; bool move(int x, int y); protected: int extend_length; bool is_extended; bool extend(); bool retract(); }; #endif
true
67b42838314d0a5a4fa4680605caff2de11f64f7
C++
hennesseyr14/EECS-183
/Project 1/Project 1/cupcakes.cpp
UTF-8
6,499
3.703125
4
[]
no_license
/** * cupcakes.cpp * * Ryan Hennessey * rjhenn * * EECS 183: Project 1 * Fall 2017 * * Calculates the number of batches of cupcakes, ingredient amounts, and cost. */ #include <iostream> #include <cmath> #include <string> using namespace std; /** * Pluralizes a word if needed. * * Requires: singular is the singular form of the word. * plural is the plural form of the word. * number determines how many things there are; must be >= 1. * Modifies: Nothing. * Effects: Returns return the singular form of the word if number == 1. * Otherwise, returns the plural form. * Examples: * // prints "bag" * cout << pluralize("bag", "bags", 1); * * // prints "pounds" * string temp = pluralize("pound", "pounds", 3); * cout << temp; */ string pluralize(string singular, string plural, int number); int main() { int numPeople; const int NUM_CUPCAKES_IN_BATCH = 12; int numBatches; // Batter ingredients per batch const double CUPS_FLOUR_PER_BATCH = 1.5; const double CUPS_GRANULATED_SUGAR_PER_BATCH = 1.0; const double TSP_BAKING_POWDER_PER_BATCH = 1.5; const double TSP_SALT_PER_BATCH = 0.5; const double CUPS_BUTTER_PER_BATCH_BATTER = 0.5; const double CUPS_SOUR_CREAM_PER_BATCH = 0.5; const int NUM_WHOLE_EGGS_PER_BATCH = 1; const int NUM_EGG_YOLKS_PER_BATCH = 2; const double TSP_VANILLA_PER_BATCH_BATTER = 1.5; // Frosting ingredients per batch const double CUPS_BUTTER_PER_BATCH_FROSTING = 1.0; const double CUPS_POWDERED_SUGAR_PER_BATCH = 2.5; const double TSP_VANILLA_PER_BATCH_FROSTING = 3.0; // Ingredient costs const double COST_BAG_FLOUR = 3.09; const double COST_BAG_GRANULATED_SUGAR = 2.98; const double COST_LB_BUTTER = 2.50; const double COST_CONTAINER_SOUR_CREAM = 1.29; const double COST_DOZEN_EGGS = 2.68; const double COST_BAG_POWDERED_SUGAR = 1.18; const double COST_BOTTLE_VANILLA = 4.12; // Conversions const double CUPS_PER_BAG_FLOUR = 20.0; const double CUPS_PER_BAG_GRANULATED_SUGAR = 10.0; const double CUPS_PER_LB_BUTTER = 2.0; const double CUPS_PER_CONTAINER_SOUR_CREAM = 1.0; const int NUM_EGGS_PER_DOZEN = 12; const double CUPS_PER_BAG_POWDERED_SUGAR = 5.5; const double TSP_PER_BOTTLE_VANILLA = 12.0; // Total ingredient amounts needed int numBagsFlour; int numBagsGranulatedSugar; int numLbButter; int numContainersSourCream; int numDozenEggs; int numBagsPowderedSugar; int numBottlesVanilla; // Total cost of ingredients double totalCost = 0.00; // Prompt user for number of people, calculate number of batches cout << "How many people do you need to serve? "; cin >> numPeople; numBatches = ceil(static_cast<double>(numPeople) / NUM_CUPCAKES_IN_BATCH); cout << endl << endl << "You need to make: " << numBatches << " " << pluralize("batch", "batches", numBatches) << " of cupcakes" << endl << endl; // Ingredient list cout << "Shopping List for \"Best Ever\" Vanilla Cupcakes" << endl << "----------------------------------------------" << endl; // Calculate, print number of bags of flour; update total cost numBagsFlour = ceil(numBatches * CUPS_FLOUR_PER_BATCH / CUPS_PER_BAG_FLOUR); cout << " " << numBagsFlour << " " << pluralize("bag", "bags", numBagsFlour) << " of flour" << endl; totalCost += numBagsFlour * COST_BAG_FLOUR; // Calculate, print number of bags of granulated sugar; update total cost numBagsGranulatedSugar = ceil(numBatches * CUPS_GRANULATED_SUGAR_PER_BATCH / CUPS_PER_BAG_GRANULATED_SUGAR); cout << " " << numBagsGranulatedSugar << " " << pluralize("bag", "bags", numBagsGranulatedSugar) << " of granulated sugar" << endl; totalCost += numBagsGranulatedSugar * COST_BAG_GRANULATED_SUGAR; // Calculate, print number of pounds of butter; update total cost numLbButter = ceil(numBatches * (CUPS_BUTTER_PER_BATCH_BATTER + CUPS_BUTTER_PER_BATCH_FROSTING) / CUPS_PER_LB_BUTTER); cout << " " << numLbButter << " " << pluralize("pound", "pounds", numLbButter) << " of butter" << endl; totalCost += numLbButter * COST_LB_BUTTER; // Calculate, print number of containers of sour cream; update total cost numContainersSourCream = ceil(numBatches * CUPS_SOUR_CREAM_PER_BATCH / CUPS_PER_CONTAINER_SOUR_CREAM); cout << " " << numContainersSourCream << " " << pluralize("container", "containers", numContainersSourCream) << " of sour cream" << endl; totalCost += numContainersSourCream * COST_CONTAINER_SOUR_CREAM; // Calculate, print number of dozen eggs; update total cost numDozenEggs = ceil(static_cast<double>(numBatches) * (NUM_WHOLE_EGGS_PER_BATCH + NUM_EGG_YOLKS_PER_BATCH) / NUM_EGGS_PER_DOZEN); cout << " " << numDozenEggs << " dozen eggs" << endl; totalCost += numDozenEggs * COST_DOZEN_EGGS; // Calculate, print number of bags of powdered sugar; update total cost numBagsPowderedSugar = ceil(numBatches * CUPS_POWDERED_SUGAR_PER_BATCH / CUPS_PER_BAG_POWDERED_SUGAR); cout << " " << numBagsPowderedSugar << " " << pluralize("bag", "bags", numBagsPowderedSugar) << " of powdered sugar" << endl; totalCost += numBagsPowderedSugar * COST_BAG_POWDERED_SUGAR; // Calculate, print number of bottles of vanilla; update total cost numBottlesVanilla = ceil(numBatches * (TSP_VANILLA_PER_BATCH_BATTER + TSP_VANILLA_PER_BATCH_FROSTING) / TSP_PER_BOTTLE_VANILLA); cout << " " << numBottlesVanilla << " " << pluralize("bottle", "bottles", numBottlesVanilla) << " of vanilla" << endl; totalCost += numBottlesVanilla * COST_BOTTLE_VANILLA; // Print total cost and goodbye message cout << endl << "Total expected cost of ingredients: $" << totalCost << endl << endl << "Have a great party!"; return 0; } string pluralize(string singular, string plural, int number) { if (number == 1) { return singular; } return plural; }
true
9b2615d0a35d345155e3524f9d16d4cf895212b5
C++
AdityaAgarwal436/daa-lab
/Week-5/Ques-1/counting_sort.cpp
UTF-8
675
2.546875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int t,n; cin>>t; while(t--) { cin>>n; char a[n]; int freq[26]={0}; for(int i=0;i<n;i++) { cin>>a[i]; } for(int i=0;i<n;i++) { freq[a[i]-'a']++; } int max=0, e; for(int i=0;i<n;i++) { if(max<freq[i]) { max=freq[i]; e=i; } } if(max > 1) cout<<(char)(e+97)<<"-"<<max<<endl; else cout<<"No Duplicates Found"<<endl; } return 0; }
true
307d4edc23dbad5f56f03477ca6cff0dc45b980e
C++
arpawar/RayTracer
/src/RayTracer.h
UTF-8
2,128
3.40625
3
[ "BSD-3-Clause" ]
permissive
/* This code performs point membership of 3D structured grid points that embed the geometry. For the 3D structured grid we perform test to check which grid points lie inside/outside the geometry. For each point in the grid a ray starts from the grid point and in the x-direction to check for intersection with the geometry. If the points are inside, the number of intersections are odd, else the number of intersections are even. This header file defines the variables and functions in the mesh object */ #ifndef RAYTRACER_H #define RAYTRACER_H #include <vector> #include <array> #include <cmath> #include "omp.h" #include "basic_datastructure.h" using namespace std; class Meshio { public: Meshio(); //constructor for the mesh object int flag; // flag to define successfully creating the mesh object int nvert, nface, ngrid; //nvert defines the number of vertices in the mesh and nface defines the number of faces in the mesh, ngrid determines the number of grid points in the structured grid float x_min, x_max, y_min, y_max, z_min, z_max; // the minimum and maximum values of the 3D structured grid in x, y and z direction int ndivx, ndivy, ndivz; // number of grid points in x, y and z direction respectively vector<vertex3D> vertex; // vertex object vector<tri> face; // face object vector<int> bbox_flag; // this variable denotes whether each point is inside or outside the geometry void read_raw_file(const char * fn, vector<vertex3D> &vertex_out, vector<tri> &face_out); // this function reads the mesh file void set_bounding_box(int nx, int ny, int nz, float pm); // this function constructs the bounding box to embed the geometry void calculate_grid(vector<vertex3D> &origin_out); // this function stores the coordinates of the grid points of the structured grid void calculate_normal(); //this function calculates the normals of the surface mesh void point_membership(); // this function performs ray tracing and assign point membership to each grid point void display_result(char* filename_out,int* bbox_flag_host); //this function writes the output to a vtk file for visualization }; #endif
true
187e4a08af0eb0ce46d6a19d692652e49aa5af2f
C++
dianatalpos/Object-Oriented-Programming
/Examen/Model.cpp
UTF-8
824
2.546875
3
[]
no_license
#include "Model.h" #include <QBrush> Model::Model(Repository& repo) : repo{repo} { } void Model::notify() { emit layoutChanged(); } QVariant Model::data(const QModelIndex & index, int role) const { int row = index.row(); int column = index.column(); if (role == Qt::DisplayRole) { if (column == 0) { return QString::fromStdString(this->repo.getTeam()[row]->getName()); } } if (role == Qt::BackgroundRole) { if (column == 1) { if (this->repo.getTeam()[row]->getFiles() == 0) { QBrush q{ "blue" }; return q; } } } return QVariant(); } int Model::rowCount(const QModelIndex & parent) const { return this->repo.getTeam().size(); } int Model::columnCount(const QModelIndex & parent) const { return 2; } Model::~Model() { }
true
a34f83cbfd8e2c4c73256df5657e43b001d9534c
C++
ammyblabla/practicumProject
/piezo/piezo.ino
UTF-8
447
2.734375
3
[]
no_license
void setup() { pinMode(PIN_PC3, INPUT); pinMode(PIN_PC4, INPUT); Serial.begin(9600*2); } void loop() { printf("accelero: "); Serial.println(accel()); printf("piezo: "); Serial.println(piezo()); } int accel() { return analogRead(PIN_PC3); } float piezo() { int piezoADC = analogRead(PIN_PC4); return piezoADC * 5 / 1023.0 ; } int findMax(int input) { static max; if(input>0) { if(input>max) { } } }
true
11f83747f6a369f371aa5139b0c1b99853f34a51
C++
nocro/plot
/global/hist.hpp
UTF-8
811
2.53125
3
[]
no_license
#pragma once #include "settings.hpp" #include <time.h> class Hist { public: Hist(std::vector<std::vector<double>> datas, std::vector<std::string> labels, std::vector<std::string> clusters = std::vector<std::string>()); // Hist(std::vector<int> datas); // Hist(std::vector<double> datas, std::vector<std::string> labels); Hist(std::vector<double> datas,unsigned int n=0);// ce constructeur est pour les histograme dans un espace dense, n'as pas de cluster ni de label HistSettings settings; std::vector<std::vector<double> > m_data; //les datas ou chaque vecteur est un cluster et chaque element corestpond a un des label std::vector<std::string> m_labels; // les labels qui sont les nom de chaque elmeent std::vector<std::string> m_clusters; // nom des cluster };
true
ad481d191f297410ce03739ac25d3f5cea4161c6
C++
midiway/Shared-WTL
/CoreEngine/GUI/Manager.h
UTF-8
2,809
2.546875
3
[]
no_license
#pragma once #include "Worker.h" #include "Adapter.h" #include "EngineController.h" // Manager base - no adapter class CManager : public CWorker { protected: CManager(); bool PrinterFilter(Log::LogLine&); // Interface protected: // static ones - these checks can be made at ANY place static void ASSERT_ThreadUI(); //is DirectWork() or direct call from the main thread static void ASSERT_WorkGuarded(); //is running through the Worker interface static void ASSERT_WorkThreaded(); //is running through a Worker thread // Overrides protected: virtual void OnErrorReport( const Err::sErrorData& source_err, Log::LogList& chks_list ) override; }; // Manager linked - has adapter template<class TAdapter> class CManagerLinked : public CManager, protected CManagerSignaler { public: typedef TAdapter tdAdapter; TAdapter* m_linked_adapter; private: typedef void(TAdapter::*tdSignalFunc)(); tdSignalFunc m_signal_callback; void OnSignal() override { (m_linked_adapter->*m_signal_callback)(); } // Interface public: void SetAdapter(TAdapter* adapter) { m_linked_adapter = adapter; } void SendSignal(tdSignalFunc func) { m_signal_callback = func; if( ::GetCurrentThreadId() != CWorker::g_dwMainThread ) SendEngineSignal(); else ASSERT(false);// consider calling the function directly, so no SendSignal() right! } }; template<class TAdapter> class CManagerLinkedN : public CManager, protected CManagerSignaler { public: typedef TAdapter tdAdapter; CAtlArray<TAdapter*> m_linked_adapters; private: typedef void(TAdapter::*tdSignalFunc)(); tdSignalFunc m_signal_callback; void OnSignal() override { for( UINT i=0; i<m_linked_adapters.GetCount(); ++i ) (m_linked_adapters[i]->*m_signal_callback)(); } // Interface public: void AddAdapter(TAdapter* adapter) { m_linked_adapters.Add(adapter); } void SendSignal(tdSignalFunc func) { m_signal_callback = func; if( ::GetCurrentThreadId() != CWorker::g_dwMainThread ) SendEngineSignal(); else OnSignal(); } }; // --------------------------------------------------------------------------------------------------------- class CManagerSignaler // What if we allow non-managers classes to also be able to have adapters? { protected: void SendEngineSignal() { ASSERT( ::GetCurrentThreadId() != CWorker::g_dwMainThread );//only for threaded work else will cause a dead-lock! CEngineSignalWnd::s_msgwnd.SendMessage( WMU_SIGNAL_SEND, (WPARAM) this );// here the pointer type is correct, so no static_cast<CManagerSignaler*>(this) } void PostEngineSignal()// NYI { ASSERT( false ); CEngineSignalWnd::s_msgwnd.PostMessage( WMU_SIGNAL_POST );// yes, its survives system inner-loops } public: // Derived receives the signal through this pure virtual virtual void OnSignal() = 0; };
true
a27137d6f3fa343b556bec71e0b0fa9f03b6199e
C++
CS6/myArduino
/IP_W5100/IP_W5100.ino
UTF-8
2,671
2.953125
3
[]
no_license
/* OpenJumper WebServer Example 建立一個顯示傳感器信息的Arduino服務器 [url= http://www.openjumper.com/ ] http://www.openjumper.com/ [/url] [url= http://x.openjumper.com/ethernet/ ] http://x.openjumper.com/ethernet/[/url] */ #include <SPI.h> #include <Ethernet.h> // 設定MAC地址、IP地址 // IP地址需要參考你的本地網絡設置 byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; IPAddress ip(192,168,1,177); // 初始化Ethernet庫 // HTTP默認端口為80 EthernetServer server(80); void setup() { // 初始化串口通信 Serial.begin(9600); // 開始ethernet連接,並作為服務器初始化 Ethernet.begin(mac, ip); server.begin(); Serial.print( "server is at " ); Serial.println(Ethernet.localIP()); } void loop() { // 監聽客戶端傳來的數據 EthernetClient client = server.available(); if (client) { Serial.println( "new client" ); // 一個Http請求結尾必須帶有回車換行 boolean currentLineIsBlank = true ; while (client.connected()) { if (client.available()) { char c = client.read(); Serial.write(c); // 如果收到空白行,說明http請求結束,並發送響應消息 if (c == '\n' && currentLineIsBlank) { // 發送標準的HTTP響應 client.println( "HTTP/1.1 200 OK" ); client.println( "Content-Type: text/html" ); client.println( "Connection: close" ); client.println(); client.println( "<!DOCTYPE HTML>" ); client.println( "<html>" ); // 添加一個meta刷新標籤, 瀏覽器會每5秒刷新一次 // 如果此處刷新頻率設置過高,可能會出現網頁的卡死的狀況 client.println( "<meta http-equiv=\"refresh\" content=\"5\">" ); // 輸出每個模擬口讀到的值 for ( int analogChannel = 0; analogChannel < 6; analogChannel++) { int sensorReading = analogRead(analogChannel); client.print( "analog input " ); client.print(analogChannel); client.print( " is " ); client.print(sensorReading); client.println( "<br />" ); } client.println( "</html>" ); break ; } if (c == '\n' ) { // 已經開始一個新行 currentLineIsBlank = true ; } else if (c != '\r' ) { // 在當前行已經得到一個字符 currentLineIsBlank = false ; } } } // 等待瀏覽器接收數據 delay(1); // 斷開連接 client.stop(); Serial.println( "client disonnected" ); } }
true
d776a8d53402a2b2ea9843703e02f123e96e0da9
C++
orh92/TextEditorAdvancedCPP
/Document.cpp
UTF-8
3,981
3.328125
3
[]
no_license
#include "Document.h" #include <iostream> using namespace std; Document::Document() { this->documentLines = vector<string>(); this->currentLineIndex = 0; } Document::~Document() {} void Document::printLineByNum(int num) { if (!documentLines.empty()) { cout << num << "\t" << documentLines.at(num - 1) << endl; this->currentLineIndex = num; } } void Document::printAll() { if (documentLines.empty()) { return; } else { vector<string>::iterator iter; for (iter = this->documentLines.begin(); iter < this->documentLines.end(); iter++) { cout << *iter << endl; } } } void Document::addAfterTheLine() { string str; getline(cin, str); while (!(str.compare(".") == 0)) { auto insertPositionLine = this->documentLines.begin() + this->currentLineIndex; this->documentLines.insert(insertPositionLine, str); this->currentLineIndex++; getline(cin, str); } } void Document::addBeforTheLine() { string str; getline(cin, str); while (!(str.compare(".") == 0)) { auto insertPositionLine = this->documentLines.begin() + this->currentLineIndex - 1; this->documentLines.insert(insertPositionLine, str); this->currentLineIndex++; getline(cin, str); } } void Document::overrideLine() { if (currentLineIndex > 0) { string str; getline(cin, str); this->documentLines.at(currentLineIndex - 1) = str; this->addAfterTheLine(); } else { string str; getline(cin, str); this->documentLines.at(currentLineIndex) = str; this->addAfterTheLine(); } } void Document::deleteLine(int num) { if (this->currentLineIndex > 0) { this->documentLines.erase(documentLines.begin() +num -1); this->currentLineIndex=num-1; } } void Document::searchForward(string strToSearch) { vector<string>::iterator iter; int offset= 1; for (iter = documentLines.begin() + this->currentLineIndex; iter < documentLines.end(); iter++) { if ((*iter).find(strToSearch) != string::npos) { cout << (*iter) <<endl; this->currentLineIndex += offset; return; } offset++; } offset = 1; for (iter = documentLines.begin(); iter < documentLines.begin() + this->currentLineIndex; iter++) { if ((*iter).find(strToSearch) != string::npos) { cout << (*iter) << endl; this->currentLineIndex = offset; return; } offset++; } cout << "?" << endl; } void Document::searchBackward(string strToSearch) { vector<string>::iterator iter; int offset = 1; for (iter= documentLines.begin() + this->currentLineIndex - 2; iter >= documentLines.begin(); iter--) { if ((*iter).find(strToSearch) != string::npos) { cout << (*iter) << endl; this->currentLineIndex -= offset; return; } if (iter == documentLines.begin()) { break; } offset++; } offset = documentLines.size(); for (iter = documentLines.end() - 1; iter >= documentLines.begin() + this->currentLineIndex - 1; iter--) { if ((*iter).find(strToSearch) != string::npos) { cout << (*iter) <<endl; this->currentLineIndex += (offset - this->currentLineIndex); return; } offset--; } cout << "?" << endl; } void Document::swapWord(string oldStr, string newStr) { size_t index = 0; while (true) { index = documentLines.at(currentLineIndex - 1).find(oldStr, index); if (index == string::npos) return; documentLines.at(this->currentLineIndex - 1).replace(index, oldStr.length(), newStr); index = index + newStr.length(); } } void Document::appendLines(int num1, int num2) { documentLines.at(num1-1)=documentLines.at(num1-1) + documentLines.at(num2-1); documentLines.erase(documentLines.begin() + num2 -1 ); currentLineIndex = num1; }
true
1af2454e695f6b11c2021a6dd8474bd9769792b6
C++
lihao814386741/TeamWork
/LeetCode/Liang/260SingleNumberIII.cpp
UTF-8
591
2.9375
3
[]
no_license
class Solution { public: vector<int> singleNumber(vector<int>& nums) { assert(nums.size() >= 2); int aXORb = 0; // Use 0 is fine. for (int i = 0; i < nums.size(); ++i) { aXORb ^= nums.at(i); } int lastDiff = (aXORb & (aXORb - 1)) ^ aXORb; int first = 0, second = 0; for (int i = 0; i < nums.size(); ++i) { if (lastDiff & nums.at(i)) { first ^= nums.at(i); } else { second ^= nums.at(i); } } return vector<int>{first, second}; } };
true
079e016e928d9ed036d0995206a8627914b81446
C++
Myway3D/Myway3D
/ThirdParty/EMotionFX/Source/MeshDeformer.h
UTF-8
3,368
2.75
3
[]
no_license
/* * EMotion FX 2 - Character Animation System * Copyright (c) 2001-2004 Mystic Game Development - http://www.mysticgd.com * All Rights Reserved. */ #ifndef __MESHDEFORMER_H #define __MESHDEFORMER_H // include the Core system #include "../Core/Source/MCore.h" #include "MemoryCategories.h" namespace EMotionFX { // forward declarations class Mesh; class Actor; class Node; /** * The mesh deformer base class. * A mesh deformer can deform (apply modifications) on a given mesh. * Examples of deformers could be a TwistDeformer, SoftSkinDeformer, MorphDeformer, etc. * Every deformer has its own unique type ID number and the MeshDeformerStack contains a list of * deformers which are executed in the specified order. */ class MeshDeformer { DECLARE_CLASS(MeshDeformer); MEMORYOBJECTCATEGORY(MeshDeformer, EMFX_DEFAULT_ALIGNMENT, MEMCATEGORY_GEOMETRY_DEFORMERS); public: /** * Default constructor. * @param mesh A pointer to the mesh to deform. */ MeshDeformer(Mesh* mesh); /** * Destructor. */ virtual ~MeshDeformer(); /** * Update the mesh deformer. * @param actor The actor to use for the update. So the actor where the mesh belongs to during this update. * @param node The node to use for the update, so the node where the mesh belongs to during this update. * @param timeDelta The time (in seconds) passed since the last call. */ virtual void Update(Actor* actor, Node* node, const double timeDelta) = 0; /** * Reinitialize the mesh deformer. */ virtual void ReInitialize(); /** * Creates an exact clone (copy) of this deformer, and returns a pointer to it. * @param mesh The mesh to apply the cloned deformer on. * @param actor The actor to apply the cloned deformer on. * @result A pointer to the newly created clone of this deformer. */ virtual MeshDeformer* Clone(Mesh* mesh, Actor* actor) = 0; /** * Returns the type identification number of the deformer class. * @result The type identification number. */ virtual int GetType() const = 0; /** * Returns the sub type identification number. * This number is used to identify special specilizations of a given deformer, like the same type of deformer, but with P4 optimizations. * In that case the type will be the same, but the subtype will be different for each specialization. * @result The unique subtype identification number. */ virtual int GetSubType() const = 0; /** * Check if the controller is enabled or not. * @result Returns true when the controller is active (enabled) or false when the controller is inactive (disabled). */ bool IsEnabled() const; /** * Enable or disable the controller. * Disabling a controller just results in the Update method of the controller not being called during the Actor::Update() call. * @param enabled Set to true when you want to enable the controller or to false when you want to disable the controller. */ void SetEnabled(const bool enabled); protected: Mesh* mMesh; /**< Pointer to the mesh to which the deformer belongs to.*/ bool mIsEnabled; /**< When set to true, this mesh deformer will be processed, otherwise it will be skipped during update. */ }; } // namespace EMotionFX #endif
true
99bef536169d19f7bc0e80cb701d5f68cbdfee69
C++
lucas54neves/gcc224-ialg
/Lista de desafios/Questão 01/exercicio1.cpp
UTF-8
481
3.40625
3
[]
no_license
#include <iostream> using namespace std; int main () { int largura, altura, xMouse, yMouse; float xConvertido, yConvertido, larguraCentro, alturaCentro; cin >> largura; cin >> altura; cin >> xMouse; cin >> yMouse; larguraCentro = largura / 2.0; alturaCentro = altura / 2.0; xConvertido = (xMouse - larguraCentro) / larguraCentro; yConvertido = (double)(alturaCentro - yMouse) / alturaCentro; cout << xConvertido << endl; cout << yConvertido << endl; return 0; }
true
0d92dc4ae125f8c3f3ef4b9e2aac8b5989976b14
C++
Malpp/zombie_game
/zombie/collidable.h
UTF-8
894
2.828125
3
[]
no_license
#pragma once #include "stdafx.h" #include "drawable.h" class Collidable : public Drawable { public: Collidable(sf::Vector2f& pos, float angle, sf::Texture* texture, float collide_size_radius) : Drawable(pos, angle, texture) { collide_radius = collide_size_radius; debug_circle_collision = sf::CircleShape( collide_size_radius ); debug_circle_collision.setFillColor( sf::Color::Transparent ); debug_circle_collision.setOutlineColor( sf::Color::Red ); debug_circle_collision.setOutlineThickness( 3 ); debug_circle_collision.setOrigin( collide_size_radius, collide_size_radius ); } float getCollideRadius() const; bool checkCollision(Collidable* collidable, bool should_handle = true); void draw(sf::RenderTarget& window) override; protected: virtual void handleCollision( Collidable* entity ) = 0; private: float collide_radius; sf::CircleShape debug_circle_collision; };
true
870b062c5cd187fc8bbb9721bed4f18e5fc8819d
C++
CodeSquadPie/Lost-castle
/Lost castle/Lost castle/map.cpp
UTF-8
4,656
2.96875
3
[]
no_license
#include "map.h" map::map() { std::cout << "Created map object." << std::endl; } map::~map() { std::cout << "Destroyed map object." << std::endl; } std::string map::file_location_concatination(char* file_dirrectory, const char *file_name_char) { std::string file_location_string = file_dirrectory; std::string file_name = file_name_char; std::string concatenated_string = file_location_string + file_name; return concatenated_string; } void map::load_map(char* file_location) { std::string file_location_string = file_location_concatination(file_location, "map.tmx"); const char *file_location_char = file_location_string.c_str(); XMLDocument map_file; map_file.LoadFile(file_location_char); XMLElement* map_info = map_file.FirstChildElement(); map_info->QueryIntAttribute("width", &map_size_x); map_info->QueryIntAttribute("height", &map_size_y); map_info->QueryIntAttribute("tilewidth", &tile_size_x); map_info->QueryIntAttribute("tileheight", &tile_size_y); XMLElement* tileset_info = map_info->FirstChildElement(); XMLElement* layer_info = tileset_info->NextSiblingElement(); XMLElement* data_info = layer_info->FirstChildElement(); char* map_string = (char*)data_info->GetText(); char* str_context = NULL; int* map_array_temp = new int[map_size_x * map_size_y]; char* char_current; int number; char_current = strtok_s(map_string, ",", &str_context); int i = 0; while (char_current != NULL) { sscanf_s(char_current, "%d", &number); char_current = strtok_s(NULL, ",", &str_context); map_array_temp[i] = number; i++; } this->current_tile_map = map_array_temp; } void map::change_map(char* file_location) { } int map::querry_tile_on_map(int x, int y) { return this->current_tile_map[y * map_size_x + x]; } void map::load_map_tileset(char *file_location) { std::string file_location_string = file_location_concatination(file_location,"tileset.tsx"); const char* file_location_char = file_location_string.c_str(); XMLDocument tileset_file; tileset_file.LoadFile(file_location_char); XMLElement* tileset_info = tileset_file.FirstChildElement(); tileset_info->QueryIntAttribute("tilecount", &tilecount); tileset_info->QueryIntAttribute("columns", &columns); XMLElement* image_info = tileset_info->FirstChildElement(); const char* tileset_image_filename = image_info->Attribute("source"); std::string image_location_string = file_location_concatination(file_location,"tileset.jpg"); const char* image_location_char = image_location_string.c_str(); this->tileset_image.loadFromFile(image_location_char); } Vector2i map::tile_index_to_texture_coordinate(int type) { int index = type - 1; Vector2i coord_temp; coord_temp.x = index % columns * tile_size_x; coord_temp.y = index / columns * tile_size_y; //std::cout << "temp_x: " << coord_temp.x << " temp_y: " << coord_temp.y << " index: " << index << std::endl; return coord_temp; } void map::render_tile_brute_force(int x, int y, int type) { Vector2i temp = tile_index_to_texture_coordinate(type); //std::cout<<"temp_x: " << temp.x <<" temp_y: "<<temp.y<<std::endl; map_brush.setTexture(tileset_image); map_brush.setTextureRect(IntRect(temp.x, temp.y, tile_size_x, tile_size_y)); map_brush.setPosition(x * tile_size_x, y * tile_size_y); render_target->draw(map_brush); } void map::reference_render_target(RenderWindow *window) { this->render_target = window; } void map::reference_view(View *view) { this->view_reference = view; } void map::render() { Vector2f size = view_reference->getSize(); Vector2f center = view_reference->getCenter(); Vector2f up_left_corner(center.x - size.x/2, center.y - size.y/2); Vector2f down_right_corner(center.x + size.x/2, center.y + size.y/2); int x1 = (int)up_left_corner.x / tile_size_x; if (x1 < 0) { x1 = 0; } int y1 = (int)up_left_corner.y / tile_size_y; if (y1 < 0) { y1 = 0; } int x2 = (int)down_right_corner.x / tile_size_x + ADDITIONAL_DRAW_AREA; if (x2 > map_size_x) { x2 = map_size_x; } int y2 = (int)down_right_corner.y / tile_size_y + ADDITIONAL_DRAW_AREA; if (y2 > map_size_y) { y2 = map_size_y; } //std::cout << "X1: " << x1 << " Y2: " << y1 << " X2: " << x2 << " Y2: " << y2 << " center_x: " << center.x << " center_y: " << center.y << std::endl; for (int i = y1; i < y2; i++) { for (int j = x1; j < x2; j++) { render_tile_brute_force(j, i, querry_tile_on_map(j, i)); } } }
true
afcc59ec1447689a17eb767ed23f5372d573494c
C++
muuuuuua/leetcode
/hIndexII.cpp
UTF-8
830
3.734375
4
[]
no_license
/** * 275. H-Index II */ #include "inc/common.h" int binaryFind(vector<int>& citations, int l, int r) { if(l == r) { if(citations[l] >= citations.size()-l) return l; else return citations.size(); } int mid = (l+r)/2; if(citations[mid] >= citations.size()-mid) { if(mid-1 >= 0 && citations[mid-1] >= citations.size()-mid+1) return binaryFind(citations, l, mid-1); else return mid; } else return binaryFind(citations, mid+1, r); } int hIndex(vector<int>& citations) { if(citations.size() == 0) return 0; return citations.size() - binaryFind(citations, 0, citations.size()-1); } int main() { int a[] = {0,1,3,5,6}; vector<int> c = arrayToVector(a); cout<<hIndex(c)<<endl; return 0; }
true
6f5c8cb3f8b756d5ec590f29aa194adaac703f94
C++
wlddxxmmsg/hello-world
/超级楼梯.cpp
UTF-8
222
2.578125
3
[]
no_license
#include <stdio.h> int d[41]; int main() { int a,n; d[2] = 1; d[3] = 2; for(int i = 4 ; i <= 40 ; i++) d[i] += d[i-1]+d[i-2]; scanf("%d",&a); while(a--) { scanf("%d",&n); printf("%d\n",d[n]); } }
true
2fd69d74011d9f95a2dd2e6f7eb5228852fcf334
C++
turtle11311/Codes
/Accepted/NPSC/b222. A. 犯人的編號.cpp
UTF-8
477
2.859375
3
[]
no_license
#include <iostream> using namespace std; int main () { char a1, a2, a3, a4, g1, g2, g3, g4; int n, A, B; while (cin >> a1 >> a2 >> a3 >> a4) { cin >> n; while (n--) { cin >> g1 >> g2 >> g3 >> g4; A = (a1==g1) + (a2==g2) + (a3==g3) + (a4==g4); B = (a1==g2) + (a1==g3) + (a1==g4) + (a2==g1) + (a2==g3) + (a2==g4) + (a3==g1) + (a3==g2) + (a3==g4) + (a4==g1) + (a4==g2) + (a4==g3); cout << A << 'A' << B << 'B' << endl; } } }
true
274456f402a4b982deb21ca3eeeac5f62ee2cbad
C++
ITblueboy/C-
/String2.h
UTF-8
667
2.953125
3
[]
no_license
#pragma once #include<unistd.h> #include<string.h> class String { public: String(const char* str) :_str(new char[strlen(str)+1]) { strcpy(_str,str); } String(const String& s) { _str=new char[strlen(s._str)+1]; strcpy(_str,s._str); } String& operator=(const String& s) { if(this!=&s) { delete[] _str; _str=new char[strlen(s._str)+1]; strcpy(_str,s._str); } return *this; } ~String() { if(_str) { delete[] _str; _str=NULL; } } const char* C_str() { return _str; } private: char* _str; };
true
74f44fbf7d393da5458bf5402693da5d34f1517e
C++
liuyaqiu/LeetCode-Solution
/304-Range-Sum-Query-2D-Immutable.cpp
UTF-8
2,028
3.875
4
[]
no_license
#include <iostream> #include <vector> using namespace std; /* * Range Sum Query 2D - Immutable * Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). * * Range Sum Query 2D * The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8. * * Example: * Given matrix = [ * [3, 0, 1, 4, 2], * [5, 6, 3, 2, 1], * [1, 2, 0, 1, 5], * [4, 1, 0, 1, 7], * [1, 0, 3, 0, 5] * ] * * sumRegion(2, 1, 4, 3) -> 8 * sumRegion(1, 1, 2, 2) -> 11 * sumRegion(1, 2, 2, 4) -> 12 * Note: * You may assume that the matrix does not change. * There are many calls to sumRegion function. * You may assume that row1 ≤ row2 and col1 ≤ col2. * * */ class NumMatrix { private: vector<vector<int>> res; public: NumMatrix(vector<vector<int>> matrix) { int m = matrix.size(); int n = matrix[0].size(); res = vector<vector<int>>(m, vector<int>(n, 0)); int sum = 0; for(int i = 0; i < m; i++) { sum += matrix[i][0]; res[i][0] = sum; } sum = 0; for(int j = 0; j < n; j++) { sum += matrix[0][j]; res[0][j] = sum; } for(int i = 1; i < m; i++) { for(int j = 1; j < n; j++) { res[i][j] = res[i - 1][j] + res[i][j - 1] - res[i - 1][j - 1] + matrix[i][j]; } } } int sumRegion(int row1, int col1, int row2, int col2) { if(row1 > 0) { if(col1 > 0) return res[row2][col2] - res[row1 - 1][col2] - res[row2][col1 - 1] + res[row1 - 1][col1 - 1]; else return res[row2][col2] - res[row1 - 1][col2]; } else { if(col1 > 0) return res[row2][col2] - res[row2][col1 - 1]; else return res[row2][col2]; } } };
true
a530ce4c26e2f17683a815c53a6245471b0b14a5
C++
GDMiao/Class8
/Class8Online/CNetwork/Protocols/UserEnter.h
UTF-8
1,542
2.546875
3
[ "MIT" ]
permissive
#ifndef __GNET_USERENTER_H #define __GNET_USERENTER_H #include "rpcdefs.h" #include "state.hxx" #include "UserInfo.h" namespace GNET { class UserEnter : public GNET::Protocol { public: enum { PROTOCOL_TYPE = 1001 }; int64_t receiver; int64_t cid; int64_t classid; int device; char netisp; UserInfo userinfo; public: UserEnter() { type = PROTOCOL_TYPE; } UserEnter(void*) : Protocol(PROTOCOL_TYPE) { } UserEnter (int64_t l_receiver, int64_t l_cid, int64_t l_classid, int l_device, char l_netisp, const UserInfo& l_userinfo) : receiver(l_receiver), cid(l_cid), classid(l_classid), device(l_device), netisp(l_netisp), userinfo(l_userinfo) { type = PROTOCOL_TYPE; } UserEnter(const UserEnter &rhs) : Protocol(rhs), receiver(rhs.receiver), cid(rhs.cid), classid(rhs.classid), device(rhs.device), netisp(rhs.netisp), userinfo(rhs.userinfo){ } OctetsStream& marshal(OctetsStream& os) const { os << receiver; os << cid; os << classid; os << device; os << netisp; os << userinfo; return os; } const OctetsStream& unmarshal(const OctetsStream& os) { os >> receiver; os >> cid; os >> classid; os >> device; os >> netisp; os >> userinfo; return os; } virtual Protocol* Clone() const { return new UserEnter(*this); } int PriorPolicy( ) const { return 1; } bool SizePolicy(size_t size) const { return size <= 1024; } void Process(Manager *manager, Manager::Session::ID sid) { // TODO } }; } #endif
true
b71eab15ba3c261782865a651e8a177b3b82fd01
C++
ooici/port_agent
/src/network/tcp_comm_listener.cxx
UTF-8
14,201
2.59375
3
[]
no_license
/******************************************************************************* * Class: TcpCommListener * Filename: tcp_comm_listener.cxx * Author: Bill French (wfrench@ucsd.edu) * License: Apache 2.0 * * Manage a TCP listener. * * Usage: * * TCPCommListener ts; * * // Statically assign the port. If not assigned then us a random port. * ts.setPort(1024); * * // Enable blocking connections. Default is non-blocking * ts.setBlocking(true); * * // Initialize the server * ts.initalize(); * * // Get the port the server is actually listening on. Useful when using * // random ports. * uint16_t port = ts.getListenPort(); * * // Accept client connections * ts.acceptClient(); * * // Read data from the client. Honors the blocking flag set earlier. * char buffer[128]; * int bytes_read = ts.readData(buffer, 128); * * // Write data to the client. * int bytes_written = ts.writeData("Hello World", strlen("Hello World")); * * // When using non-blocking you may want to use a select read loop to monitor * // the file descriptors. They are exposed via accessors * int serverFD = ts.getServerFD(); * int clientFD = ts.getServerFD(); ******************************************************************************/ #include "tcp_comm_listener.h" #include "common/util.h" #include "common/logger.h" #include "common/exception.h" #include "common/timestamp.h" #include <netinet/in.h> #include <netdb.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> using namespace std; using namespace logger; using namespace network; /****************************************************************************** * PUBLIC METHODS ******************************************************************************/ /****************************************************************************** * Method: Constructor * Description: Default constructor. ******************************************************************************/ TCPCommListener::TCPCommListener() : CommBase() { m_iPort = 0; m_pServerFD = 0; m_pClientFD = 0; } /****************************************************************************** * Method: Copy Constructor * Description: Copy constructor. ******************************************************************************/ TCPCommListener::TCPCommListener(const TCPCommListener &rhs) : CommBase(rhs) { LOG(DEBUG) << "TCPCommListener Copy CTOR!!"; m_iPort = rhs.m_iPort; m_pServerFD = rhs.m_pServerFD; m_pClientFD = rhs.m_pClientFD; } /****************************************************************************** * Method: Destructor * Description: destructor. ******************************************************************************/ TCPCommListener::~TCPCommListener() { LOG(DEBUG) << "TCPCommListener DTOR"; disconnect(); } /****************************************************************************** * Method: copy * Description: return a new object deep copied. ******************************************************************************/ CommBase * TCPCommListener::copy() { return new TCPCommListener(*this); } /****************************************************************************** * Method: assignment operator * Description: overloaded assignment operator. ******************************************************************************/ TCPCommListener & TCPCommListener::operator=(const TCPCommListener &rhs) { return *this; } /****************************************************************************** * Method: equality operator * Description: overloaded equality operator. ******************************************************************************/ bool TCPCommListener::operator==(TCPCommListener &rhs) { return compare(&rhs); } /****************************************************************************** * Method: compare * Description: compare objects ******************************************************************************/ bool TCPCommListener::compare(CommBase *rhs) { if(rhs->type() != COMM_TCP_LISTENER) return false; return m_iPort == ((TCPCommListener *)rhs)->m_iPort; } /****************************************************************************** * Method: isConfigured * Description: Nothing to do here. ******************************************************************************/ bool TCPCommListener::isConfigured() { return true; } /****************************************************************************** * Method: disconnect * Description: Disconnect a client and server * Exceptions: * SocketMissingConfig ******************************************************************************/ bool TCPCommListener::disconnect() { LOG(DEBUG) << "Shutdown server"; disconnectClient(true); disconnectServer(); return true; } /****************************************************************************** * Method: disconnectClient * Description: Disconnect a client ******************************************************************************/ bool TCPCommListener::disconnectClient(bool server_shutdown) { if(connected()) { LOG(DEBUG2) << "Disconnecting client"; //shutdown(m_pClientFD,2); close(m_pClientFD); m_pClientFD = 0; } if(!server_shutdown) { LOG(DEBUG) << "Re-initalize tcp listener"; initialize(); } return true; } /****************************************************************************** * Method: disconnectServer * Description: Disconnect a server ******************************************************************************/ bool TCPCommListener::disconnectServer() { if(listening()) { LOG(DEBUG2) << "Closing server connection"; //shutdown(m_pServerFD,2); close(m_pServerFD); m_pServerFD = 0; } return true; } /****************************************************************************** * Method: acceptClient * Description: Accept a client connection and create a new FD * Exceptions: * SocketNotInitialized * SocketAlreadyConnected ******************************************************************************/ bool TCPCommListener::acceptClient() { socklen_t clilen; struct sockaddr_in cli_addr; int newsockfd; if(!listening()) throw SocketNotInitialized(); if(connected()) { clilen = sizeof(cli_addr); newsockfd = accept(m_pServerFD, (struct sockaddr *) &cli_addr, &clilen); if(newsockfd) close(newsockfd); throw SocketAlreadyConnected(); } LOG(DEBUG) << "accepting client connection."; clilen = sizeof(cli_addr); newsockfd = accept(m_pServerFD, (struct sockaddr *) &cli_addr, &clilen); LOG(DEBUG) << "client FD: " << newsockfd; if (newsockfd < 0) { if(errno == EAGAIN || errno == EWOULDBLOCK) { LOG(DEBUG) << "Non-blocking error ignored: " << strerror(errno) << "(" << errno << ")"; return false; } else { throw SocketConnectFailure(strerror(errno)); } } // Set the client to non blocking if needed if(! blocking()) { LOG(DEBUG) << "set client non-blocking"; fcntl(newsockfd, F_SETFL, O_NONBLOCK); LOG(DEBUG) << "Set to non-blocking"; } LOG(DEBUG) << "Storing new FD: " << newsockfd; m_pClientFD = newsockfd; LOG(DEBUG) << "Disconnect server"; disconnectServer(); return true; } /****************************************************************************** * Method: getListenPort * Description: Return the port the server is actually listening on. * Exceptions: * SocketNotInitialized ******************************************************************************/ uint16_t TCPCommListener::getListenPort() { struct sockaddr_in sin; socklen_t len = sizeof(sin); LOG(DEBUG) << "Fetch listen port"; if(!listening()) return 0; LOG(DEBUG2) << "get port from FD " << m_pServerFD; if (getsockname(m_pServerFD, (struct sockaddr *)&sin, &len) == -1) throw SocketConnectFailure(strerror(errno)); return ntohs(sin.sin_port); } /****************************************************************************** * Method: initalize * Description: Setup a TCP listener * Exceptions: * SocketMissingConfig * SocketConnectFailure ******************************************************************************/ bool TCPCommListener::initialize() { int fflags; int optval; struct sockaddr_in serv_addr; struct hostent *server; int retval; int newsock; Timestamp ts; int bind_result = -1; LOG(DEBUG) << "TCP Listener initialize()"; if(!isConfigured()) throw SocketMissingConfig("missing inet port"); LOG(DEBUG2) << "Creating INET socket"; newsock = socket(AF_INET, SOCK_STREAM, 0); if(!newsock) throw SocketCreateFailure("socket create failure"); optval = 1; if (setsockopt(newsock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval) == -1) { throw SocketCreateFailure("setsockopt SO_REUSADDR failure"); } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(m_iPort); LOG(DEBUG2) << "bind to port " << m_iPort; while (bind_result < 0) { bind_result = bind(newsock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)); if(bind_result < 0) { LOG(ERROR) << "Failed to bind: " << strerror(errno) << "(" << errno << ")"; // Retry on address in use errors if we haven't exceeded timeout. Otherwise // raise an exception. if(errno == EADDRINUSE && ts.elapseTime() < TCP_BIND_TIMEOUT) { LOG(INFO) << "Waiting for port to freeup. retrying bind."; } else { throw SocketConnectFailure(strerror(errno)); } sleep(1); } } LOG(DEBUG2) << "Starting server"; retval = listen(newsock, 0); LOG(DEBUG3) << "listen return value: " << retval; if (retval < 0) if(errno != EINPROGRESS ) // ignore EINPROGRESS error because we are NON-Blocking throw(SocketConnectFailure(strerror(errno))); if(! blocking()) { LOG(DEBUG3) << "set server socket non-blocking"; fcntl(newsock, F_SETFL, O_NONBLOCK); int opts = fcntl(newsock, F_GETFL); LOG(DEBUG3) << "fd: " << hex << newsock << " " << "sock opts: " << hex << opts << " " << "non block flag: " << hex << O_NONBLOCK; } LOG(DEBUG2) << "storing new fd: " << newsock; m_pServerFD = newsock; // Fail if we tried to bind to a specific port, but it gave us a random // port instead. if(m_iPort && getListenPort() != m_iPort) throw SocketConnectFailure("bind to port failed"); LOG(DEBUG2) << "startup complete. host port " << getListenPort(); return true; } /****************************************************************************** * Method: write * Description: write a number of bytes to the socket connection. Currently we * try to write three times before we fail. We might want to update this retry * so that it keeps retrying if it see progress being made? * * Parameters: * buffer - the data to write * size - the size of the buffer array * Return: * returns the actual number of bytes written. * Exceptions: * SocketNotInitialized * SocketNotConnected * SocketWriteFailure ******************************************************************************/ uint32_t TCPCommListener::writeData(const char *buffer, const uint32_t size) { int bytesWritten = 0; int bytesRemaining = size; int count; if(! connected()) { LOG(DEBUG) << "Socket (FD: " << m_pClientFD << ") not connected"; return 0; } while( bytesRemaining > 0 ) { LOG(DEBUG) << "WRITE DEVICE: " << buffer << "FD: " << m_pClientFD; count = write(m_pClientFD, buffer + bytesWritten, bytesRemaining ); LOG(DEBUG1) << "bytes written: " << count << " remaining: " << bytesRemaining; if(count < 0) { LOG(ERROR) << strerror(errno) << "(errno: " << errno << ")"; throw(SocketWriteFailure(strerror(errno))); } bytesWritten += count; bytesRemaining -= count; LOG(DEBUG2) << "wrote bytes: " << count << " bytes remaining: " << bytesRemaining; } return bytesWritten; } /****************************************************************************** * Method: read * Description: read a number of bytes to the socket connection. * * Parameters: * buffer - where to store the read data * size - max number of bytes to read * Return: * returns the actual number of bytes read. * Exceptions: * SocketNotInitialized * SocketNotConnected * SocketReadFailure ******************************************************************************/ uint32_t TCPCommListener::readData(char *buffer, const uint32_t size) { int bytesRead = 0; if(! connected()) { LOG(ERROR) << "Socket Not Connected in readData"; throw(SocketNotConnected("in TCPCommListener readData")); } if ((bytesRead = read(m_pClientFD, buffer, size)) < 0) { if (errno == EAGAIN || errno == EINPROGRESS) { LOG(DEBUG2) << "Error Ignored: " << strerror(errno); } else if( errno == ETIMEDOUT ) { LOG(DEBUG) << " -- socket read timeout. disconnecting client FD:" << m_pClientFD; disconnectClient(); } else { LOG(ERROR) << "bytes read: " << bytesRead << " read_device: " << strerror(errno) << "(errno: " << errno << ")"; throw(SocketReadFailure(strerror(errno))); } LOG(DEBUG2) << "read bytes: " << bytesRead; } else if(bytesRead == 0) { LOG(INFO) << " -- Device connection closed; zero bytes received. port: " << m_iPort; disconnectClient(); } else LOG(DEBUG) << "READ DEVICE: " << buffer; return bytesRead < 0 ? 0 : bytesRead; }
true
648217af0240111cecc981ce8e2abbf5ddc32495
C++
Shibabrat/Tutorials
/10-days-statistics/least-sq-reg.cpp
UTF-8
1,096
2.8125
3
[]
no_license
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <iomanip> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int n = 5; int tempMath, tempStat; double b, a; // coefficients for linear regression double xiyiSum = 0; double xisqrdSum = 0; double xiSum = 0; double yiSum = 0; double xHat = 80; double yHat; vector<double> xi; vector<double> yi; for ( int i = 0; i < n; i++ ){ cin >> tempMath >> tempStat; xi.push_back(tempMath); yi.push_back(tempStat); } // computation of b for ( int i = 0; i < n; i++ ){ xiyiSum += xi[i]*yi[i]; xiSum += xi[i]; yiSum += yi[i]; xisqrdSum += pow(xi[i],2); } double bNum = n*xiyiSum - xiSum*yiSum; double bDen = n*xisqrdSum - pow(xiSum,2); b = bNum / bDen; // computation of a a = yiSum/n - b*(xiSum/n); yHat = a + b*xHat; cout << fixed << setprecision(3) << yHat << endl; return 0; }
true
19000a76b0f1e4277bc31a4b67bc2446bfa0d658
C++
Progsapien/CourseWork
/data/vegetable.cpp
UTF-8
683
2.921875
3
[]
no_license
#include "data/vegetable.h" Vegetable::Vegetable() { this->_weight = 0; this->_calories = 0; this->_title = ""; } // get double Vegetable::weight() { return this->_weight; } double Vegetable::calories() { return this->_calories; } QString Vegetable::title() { return this->_title; } // set void Vegetable::setCalories(double calories) { this->_calories = calories > -1 ? calories : 0; } void Vegetable::setWeight(double weight) { this->_weight = weight > -1 ? weight : 0; } void Vegetable::setTitle(QString title) { this->_title = !title.isEmpty() ? title : ""; } Vegetable::~Vegetable() { }
true
5e4bd8781083fee73b2c175408e5fd5194a15e0c
C++
gregkrsak/unlib
/unlib/scaling.hpp
UTF-8
8,428
2.90625
3
[ "BSL-1.0" ]
permissive
#ifndef UNLIB_SCALING_HPP #define UNLIB_SCALING_HPP /* * scaling.hpp * * Copyright sbi http://stackoverflow.com/users/140719 * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * */ #include <cstdint> #include <unlib/unlib/ratio.hpp> namespace unlib { /** * @brief Quantity scale * * A scale is a rational fraction. Quantities have a scaling for their value * that is part of their type. Common scalings are the ones SI provides (kilo, * milli, etc.), but time spans are measured in weird scales which need their * own definitions. * * There are meta functions to scale by and to different scalings. */ template< std::intmax_t Num , std::intmax_t Den = 1 > using scale_t = ratio_t<Num,Den>; /** an unscaled value */ using no_scaling = scale_t<1>; /** * @{ * import std ratios so they are available in the unlib namespace */ using atto_scaling = std:: atto; using femto_scaling = std::femto; using pico_scaling = std:: pico; using nano_scaling = std:: nano; using micro_scaling = std::micro; using milli_scaling = std::milli; using centi_scaling = std::centi; using deci_scaling = std:: deci; using deca_scaling = std:: deca; using hecto_scaling = std::hecto; using kilo_scaling = std:: kilo; using mega_scaling = std:: mega; using giga_scaling = std:: giga; using tera_scaling = std:: tera; using peta_scaling = std:: peta; using exa_scaling = std:: exa; /** @} */ /** * @{ * humans measure time in Babylonian multiples of seconds */ using nano_second_scaling = nano_scaling; using micro_second_scaling = micro_scaling; using milli_second_scaling = milli_scaling; using second_scaling = no_scaling; using minute_scaling = scale_t<60>; using hour_scaling = std::ratio_multiply<minute_scaling, scale_t<60>>; using day_scaling = std::ratio_multiply< hour_scaling, scale_t<24>>; using week_scaling = std::ratio_multiply< day_scaling, scale_t< 7>>; /** @} */ namespace detail { template<typename NewScale, typename T> struct scale_by; template<typename NewScale, typename T> struct scale_to; /* note Providing the implementations for scales here, allowing for other * implementations for other types to be added to the detail namespace * elsewhere. */ template<typename NewScale, std::intmax_t Num, std::intmax_t Den > struct scale_by<NewScale, std::ratio<Num,Den>> {using type = std::ratio_multiply<NewScale,std::ratio<Num,Den>>;}; template<typename NewScale, std::intmax_t Num, std::intmax_t Den > struct scale_to<NewScale, std::ratio<Num,Den>> {using type = NewScale;}; } template<typename NewScale, typename T> using scale_by_t = typename detail::scale_by<NewScale,T>::type; template<typename NewScale, typename T> using scale_to_t = typename detail::scale_to<NewScale,T>::type; /** * @{ * * Meta functions to get the type of a specific scalingy. * * @note micro<kilo<meter>> will result in milli<meter>, whereas * to_micro<kilo<no_scaling>> and to_micro<to_kilo<no_scaling>> will * result in micro<no_scaling>. * * @note With other implementations ("overloads) of detail::scale_by and * detail::scale_to provided, these meta functions can be used to scale * types other than scales, too. */ template<typename T> using atto = scale_by_t< atto_scaling,T>; template<typename T> using femto = scale_by_t< femto_scaling,T>; template<typename T> using pico = scale_by_t< pico_scaling,T>; template<typename T> using nano = scale_by_t< nano_scaling,T>; template<typename T> using micro = scale_by_t< micro_scaling,T>; template<typename T> using milli = scale_by_t< milli_scaling,T>; template<typename T> using centi = scale_by_t< centi_scaling,T>; template<typename T> using deci = scale_by_t< deci_scaling,T>; template<typename T> using no_scale = T; template<typename T> using deca = scale_by_t< deca_scaling,T>; template<typename T> using hecto = scale_by_t< hecto_scaling,T>; template<typename T> using kilo = scale_by_t< kilo_scaling,T>; template<typename T> using mega = scale_by_t< mega_scaling,T>; template<typename T> using giga = scale_by_t< giga_scaling,T>; template<typename T> using tera = scale_by_t< tera_scaling,T>; template<typename T> using peta = scale_by_t< peta_scaling,T>; template<typename T> using exa = scale_by_t< exa_scaling,T>; template<typename T> using nano_second_scale = scale_by_t< nano_second_scaling,T>; template<typename T> using micro_second_scale = scale_by_t<micro_second_scaling,T>; template<typename T> using milli_second_scale = scale_by_t<milli_second_scaling,T>; template<typename T> using second_scale = no_scale<T>; template<typename T> using minute_scale = scale_by_t< minute_scaling,T>; template<typename T> using hour_scale = scale_by_t< hour_scaling,T>; template<typename T> using day_scale = scale_by_t< day_scaling,T>; template<typename T> using week_scale = scale_by_t< week_scaling,T>; template<typename T> using to_atto = scale_to_t< atto_scaling,T>; template<typename T> using to_femto = scale_to_t< femto_scaling,T>; template<typename T> using to_pico = scale_to_t< pico_scaling,T>; template<typename T> using to_nano = scale_to_t< nano_scaling,T>; template<typename T> using to_micro = scale_to_t< micro_scaling,T>; template<typename T> using to_milli = scale_to_t< milli_scaling,T>; template<typename T> using to_centi = scale_to_t< centi_scaling,T>; template<typename T> using to_deci = scale_to_t< deci_scaling,T>; template<typename T> using to_no_scale = no_scale<T>; template<typename T> using to_deca = scale_to_t< deca_scaling,T>; template<typename T> using to_hecto = scale_to_t< hecto_scaling,T>; template<typename T> using to_kilo = scale_to_t< kilo_scaling,T>; template<typename T> using to_mega = scale_to_t< mega_scaling,T>; template<typename T> using to_giga = scale_to_t< giga_scaling,T>; template<typename T> using to_tera = scale_to_t< tera_scaling,T>; template<typename T> using to_peta = scale_to_t< peta_scaling,T>; template<typename T> using to_exa = scale_to_t< exa_scaling,T>; template<typename T> using to_nano_second_scale = scale_to_t< nano_second_scaling,T>; template<typename T> using to_micro_second_scale = scale_to_t<micro_second_scaling,T>; template<typename T> using to_milli_second_scale = scale_to_t<milli_second_scaling,T>; template<typename T> using to_second_scale = to_no_scale<T>; template<typename T> using to_minute_scale = scale_to_t< minute_scaling,T>; template<typename T> using to_hour_scale = scale_to_t< hour_scaling,T>; template<typename T> using to_day_scale = scale_to_t< day_scaling,T>; template<typename T> using to_week_scale = scale_to_t< week_scaling,T>; /** @} */ /** * @{ * * @brief Multiply and divide scale types */ template<typename Scale1, typename Scale2> using mul_scale_t = std::ratio_multiply<Scale1,Scale2>; template<typename Scale1, typename Scale2> using div_scale_t = std::ratio_divide <Scale1,Scale2>; template<typename Scale , typename Ratio > using pow_scale_t = ratio_root_t< ratio_pow_t< Scale , abs_t<Ratio>::num > , abs_t<Ratio>::den >; template<typename Scale > using sqrt_scale_t = ratio_root_t<Scale, 2>; template<typename Scale > using cbrt_scale_t = ratio_root_t<Scale, 3>; /** @} */ } #endif //UNLIB_SCALING_HPP
true
a87c4ef76d08f1351f2af200f332e4f3aeab0d33
C++
ferasalsabaa/programmiersprachen-aufgabenblatt-3
/source/circle.cpp
UTF-8
1,814
3.203125
3
[ "MIT" ]
permissive
#define CATCH_CONFIG_RUNNER #include "circle.hpp" #include "vec2.hpp" #include <cmath> #include <iostream> Circle::Circle() : radius_{0.0f} , center_{0.0f,0.0f} , name_{"circle"} , color_circle_{0.0f,0.0f,0.0f} {} Circle::Circle(float radius , Vec2 const& center , Color const& color_circle) : radius_{radius}, center_{center}, name_{" "}, color_circle_{color_circle} {} Circle::Circle(float radius , Vec2 const& center , string const& name,Color const& color_circle) : radius_{radius}, center_{center}, name_{name} ,color_circle_{color_circle} {} Circle::Circle(string const& name) : radius_{0.0f} , center_{0.0f,0.0f}, name_{name}, color_circle_{0.0f,0.0f,0.0f} {} Circle::Circle(float radius) : radius_{radius} , center_{0.0f,0.0f} , name_{" "},color_circle_{0.0f,0.0f,0.0f} {} Vec2 Circle::get_center() { return center_ ; } float Circle::get_radius() const { return radius_ ; } float Circle::circumference() const { return 2*M_PI*radius_; } Color Circle::get_color_circle() { return color_circle_ ; } bool Circle::is_inside(Vec2 punct) const { float distance; distance = (punct.x_- center_.x_)*(punct.x_- center_.x_) + (punct.y_- center_.y_)*(punct.y_- center_.y_); if(distance <= radius_ * radius_) { return true ; } else { return false ; } } string Circle::get_name() const { return name_; } std::ostream& Circle::print(std::ostream& os) const { os << "radius : "<<radius_ <<" center :(" << center_.x_ << ", "<< center_.y_ <<")" << " name: "<<name_ <<" color"<<"( "<<color_circle_.r<<" , "<<color_circle_.g<<" , "<<color_circle_.b<<" )"<<"\n"; return os; } std::ostream& operator<<(std::ostream& os, Circle const& c) { std::ostream::sentry const ostream_sentry(os); return ostream_sentry ? c.print(os) : os; }
true
55a3f14e3891f3876a87f9829dbcdd3f78072ef8
C++
mariored22/SEGroupProject
/RandomTests/obstack.cpp
UTF-8
1,923
3.4375
3
[]
no_license
#include<vector> #include<iostream> using namespace std; class IntStack{ public: vector<int> stack; int upper; int SIZE=16; int minimumsize =1<<(SIZE-1); IntStack(){ IntStack(SIZE); } IntStack(int SIZE){ stack.reserve(SIZE); clear(); } int getupper() { return upper; } int setupper(int upper) { return this->upper = upper; } void clear() { upper = -1; } bool isEmpty() { return upper < 0; } void push(int x){ if(++upper >=stack.size()) expand(); stack[upper]=x; } int pop(){ int r=stack[upper--]; shrink(); return r; } int get(int x){ return stack[x]; } void set(int x,int val){ stack[x]=val; } int size(){ return upper+1; } void expand(){ int l=stack.size(); stack.resize(l*4); } void shrink(){ int l=stack.size(); if(l<=minimumsize || upper<<2 >=1) return; l=1+(upper<< 1); if(upper <minimumsize) l=minimumsize; stack.resize(l); } vector<int> toArray(){ vector<int> array; if(size() > 0) array=stack; return array; } void reverse(){ int l=size(); int h=l>>1; for(int x=0;x<h;x++){ int temp=stack[x]; stack[x]=stack[l-x-1]; stack[l-x-1]=temp; } } }; int * randomsdq(int Seed){ static int value[5];int random; for (int x=100,y=0;y<5;x=x*Seed,y++){ random=x*Seed+Seed*(x-Seed); value[y]=random; } return value; } int main() { int* string1;int Seed; cout<<"insert seed value "; cin>>Seed; string1=randomsdq(Seed); IntStack s(string1[0]); s.push(string1[0]); s.push(string1[1]); s.push(string1[2]); s.push(string1[3]); s.push(string1[4]); cout<<string1[0]<<" is pushed"<<endl; cout<<string1[1]<<" is pushed"<<endl; cout<<string1[2]<<" is pushed"<<endl; cout<<string1[3]<<" is pushed"<<endl; cout<<string1[4]<<" is pushed"<<endl; cout<<"Total stack size:"; cout<<s.getupper()+1<<endl; }
true
36cae729d6e8a8935378afb7af03980f4c7e66a5
C++
AnujKumarsla/C-
/Cpp/C++/Sort_Algo/04MergeSortTest.cpp
UTF-8
1,642
3.578125
4
[]
no_license
#include<iostream> #include<conio.h> using namespace std; void swap(int *a, int *b){ int temp=*a; *a=*b; *b=temp; } void merge(int arr[], int left[], int right[], int start, int Lend, int Rend){ int Aindex=0, Lindex=0, Rindex=0; while(Lindex <= Lend && Rindex <= Rend){ if(left[Lindex]<right[Rindex]){ arr[start]=left[Lindex]; Lindex++; } else{ arr[start]=right[Rindex]; Rindex++; } start++; } while (Lindex<=Lend) { arr[start]=left[Lindex]; start++; Lindex++; } while (Rindex<=Rend) { arr[start]=right[Rindex]; start++; Rindex++; } } void merge_sort(int arr[], int start, int end){ if(start<end){ int len=end-start+1; int mid=len/2; int left[mid], right[len-mid]; for(int i=0;i<=mid-1; i++) left[i]=arr[start+i]; for(int i=0;i<=len-mid-1;i++) right[i]=arr[mid+i]; merge_sort(left, 0, mid-1); merge_sort(right, 0, len-mid-1); merge(arr, left, right, start, mid-1, len-mid-1); } } void printArray(int a[], int len){ for(int i=0; i<len ; i++) cout<<a[i]<<" "; // cout<<"a["<<i<<"] : "<<a[i]<<"\t"; cout<<endl; } int main(){ int a[]={4,9,8,6,5,7,2,8,3,4,6}; int len=sizeof(a)/sizeof(a[0]); cout<<"Size of the array : "<<len<<endl; cout<<"before :\n"; printArray(a, len); // merge_sort1(a, 0, len-1); merge_sort(a, 0, len-1); cout<<"after :\n"; printArray(a, len); return 0; }
true
dc5a4df60e2aadf4bae85de9844b8bd12a66c42e
C++
Soukhya7834/Coding-LeetCode-
/824. Goat Latin.cpp
UTF-8
829
3.046875
3
[]
no_license
class Solution { public: string toGoatLatin(string S) { unordered_set<char> vowel({'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}); istringstream iss(S); string res, w; int i=0, j; while(iss >> w){ res += ' ' + ( vowel.count(w[0]) == 1 ? w : w.substr(1) + w[0] ) + "ma"; ++i; for (int j = 0; j < i; ++j){ res += 'a'; //i begins from 0, so ++i not i++ } } return res.substr(1); } }; /* ( vowel.count(w[0]) == 1 ? w : w.substr(1) + w[0] ) if vowel.count(w[0]) == 1 ie w begins with vowel, :w = then just w as it is; else = ie w begins with consonant, w.substr(1) + w[0] ie make sunstring from w[1]. skipping w[0] later append w[0] in end; */
true
2b1514213de7f1017fc6f8a6256d76bc995cbc40
C++
loreStefani/ArkanoidClone
/Engine/Mesh.h
UTF-8
5,169
3.171875
3
[ "MIT" ]
permissive
#pragma once #include <vector> #include <utility> #include "MathCommon.h" #include <cassert> namespace ArkanoidEngine { class Mesh { public: //ctors explicit Mesh() = default; //dtor ~Mesh() = default; //copy Mesh(const Mesh&) = default; Mesh& operator=(const Mesh&) = default; //move Mesh(Mesh&&) = default; Mesh& operator=(Mesh&&) = default; using PositionType = XMFLOAT3; using NormalType = XMFLOAT3; using TextCoordType = XMFLOAT2; void setPositions(PositionType* positions, size_t count); void setIndices(uint64_t* indices, size_t count); void setNormals(NormalType* normals, size_t count); void setTextCoords(TextCoordType* textCoords, size_t count); void setPositions(std::vector<PositionType>&& positions); void setIndices(std::vector<uint64_t>&& indices); void setNormals(std::vector<NormalType>&& normals); void setTextCoords(std::vector<TextCoordType>&& textCoords); template<typename It> void setPositions(It beg, It end); template<typename It> void setIndices(It beg, It end); template<typename It> void setNormals(It beg, It end); template<typename It> void setTextCoords(It beg, It end); std::vector<PositionType>& getPositions(); std::vector<uint64_t>& getIndices(); std::vector<NormalType>& getNormals(); std::vector<TextCoordType>& getTextCoords(); const std::vector<PositionType>& getPositions() const; const std::vector<uint64_t>& getIndices() const; const std::vector<NormalType>& getNormals() const; const std::vector<TextCoordType>& getTextCoords() const; bool hasPositions()const; bool hasTextCoords()const; bool hasNormals()const; bool hasIndices()const; size_t vertexCount()const; size_t indexCount()const; //removes all vertices, texture coordinates, normals and indices void clear(); private: template<typename T, typename It> void set(std::vector<T>& dest, It beg, It end); template<typename T> void set(std::vector<T>& dest, T* src, size_t count); std::vector<uint64_t> m_indices{}; std::vector<PositionType> m_positions{}; std::vector<NormalType> m_normals{}; std::vector<TextCoordType> m_textCoords{}; }; template<typename It> inline void Mesh::setPositions(It beg, It end) { set(m_positions, beg, end); } template<typename It> inline void Mesh::setIndices(It beg, It end) { set(m_indices, beg, end); } template<typename It> inline void Mesh::setNormals(It beg, It end) { set(m_normals, beg, end); } template<typename It> inline void Mesh::setTextCoords(It beg, It end) { set(m_textCoords, beg, end); } inline void Mesh::setPositions(PositionType* positions, size_t count) { set(m_positions, positions, count); } inline void Mesh::setIndices(uint64_t* indices, size_t count) { set(m_indices, indices, count); } inline void Mesh::setNormals(NormalType* normals, size_t count) { set(m_normals, normals, count); } inline void Mesh::setTextCoords(TextCoordType* textCoords, size_t count) { set(m_textCoords, textCoords, count); } inline void Mesh::setPositions(std::vector<PositionType>&& positions) { m_positions = std::move(positions); } inline void Mesh::setIndices(std::vector<uint64_t>&& indices) { m_indices = std::move(indices); } inline void Mesh::setNormals(std::vector<NormalType>&& normals) { m_normals = std::move(normals); } inline void Mesh::setTextCoords(std::vector<TextCoordType>&& textCoords) { m_textCoords = std::move(textCoords); } inline std::vector<Mesh::PositionType>& Mesh::getPositions() { return m_positions; } inline const std::vector<Mesh::PositionType>& Mesh::getPositions() const { return m_positions; } inline std::vector<uint64_t>& Mesh::getIndices() { return m_indices; } inline const std::vector<uint64_t>& Mesh::getIndices() const { return m_indices; } inline std::vector<Mesh::NormalType>& Mesh::getNormals() { return m_normals; } inline const std::vector<Mesh::NormalType>& Mesh::getNormals() const { return m_normals; } inline std::vector<Mesh::TextCoordType>& Mesh::getTextCoords() { return m_textCoords; } inline const std::vector<Mesh::TextCoordType>& Mesh::getTextCoords() const { return m_textCoords; } inline void Mesh::clear() { m_positions.clear(); m_indices.clear(); m_normals.clear(); } inline bool Mesh::hasPositions()const { return m_positions.size() > 0; } inline bool Mesh::hasTextCoords()const { return m_textCoords.size() > 0; } inline bool Mesh::hasNormals()const { return m_normals.size() > 0; } inline bool Mesh::hasIndices()const { return m_indices.size() > 0; } inline size_t Mesh::vertexCount()const { return m_positions.size(); } inline size_t Mesh::indexCount()const { return m_indices.size(); } template<typename T, typename It> inline void Mesh::set(std::vector<T>& dest, It beg, It end) { dest.clear(); dest.assign(beg, end); } template<typename T> inline void Mesh::set(std::vector<T>& dest, T* src, size_t count) { assert(src != nullptr); dest.clear(); dest.reserve(count); for (size_t i = 0; i < count; ++i) { dest.push_back(src[i]); } } }
true
f08030dd0f25165be04d1d00e751f46f9aa6de9b
C++
respu/caney
/components/std/include/caney/std/enum_helper.hpp
UTF-8
1,724
3.703125
4
[ "MIT" ]
permissive
#pragma once #include <type_traits> namespace caney { inline namespace stdv1 { /* * convert enum value to underlying integer type * * unless given in enum declaration the underlying type is implementation * defined */ template<typename Enum> constexpr typename std::underlying_type<Enum>::type from_enum(Enum val) { return static_cast<typename std::underlying_type<Enum>::type>(val); } /* * convert integer value to given enum type; requires that the value * is implicitly convertible to the underlying type */ template<typename Enum> constexpr Enum to_enum(typename std::underlying_type<Enum>::type val) { return static_cast<Enum>(val); } namespace impl { template<typename Integral> class to_enum_wrapper { public: constexpr explicit to_enum_wrapper(Integral value) : m_value(value) { } // implicit cast operator! template<typename Enum> operator Enum() { return to_enum<Enum>(m_value); } private: Integral m_value; }; } /* * if you have the correct underlying type (integer literals might not work, you want an explicit type!), * this variant doesn't need the enum type as template parameter if the returned value * is converted into the wanted enum type automatically. * * Example: * enum class MyEnum : uint32_t { ... }; * uint32_t i = 0; // e.g. deserialize from somewhere, sql query result, ... * MyEnum t = to_enum(i); */ template<typename Integral, std::enable_if_t<std::is_integral<Integral>::value>* = nullptr> constexpr impl::to_enum_wrapper<Integral> to_enum(Integral value) { return impl::to_enum_wrapper<Integral>(value); } } } // namespace caney
true
9225ac75c3aaaa9dd534c2a1c8d9e14635a521ff
C++
kejdikopaci/CardGame
/src/SpellCard.hpp
UTF-8
1,889
2.90625
3
[]
no_license
//------------------------------------------------------------------------------ // SpellCard.hpp //------------------------------------------------------------------------------ #ifndef SPELLCARD_HPP #define SPELLCARD_HPP #include "Card.hpp" #include "string" //------------------------------------------------------------------------------ namespace Oop { class Game; //---------------------------------------------------------------------------- // SpellCard Class // Represent the Spell Cards with it's attributes // It's a Subclass of Card Class // Don't land in Graveyard after use, instead they are destroyed // class SpellCard : public Card { public: // Spell Type Mana Amount const static int HEALER_MANA; const static int RELIEF_MANA; const static int REBIRTH_MANA; const static int DRACULA_MANA; //-------------------------------------------------------------------------- /// Enumeration of Spell Types of Spell Card // enum SpellType {HEALER, RELIEF, REBIRTH, DRACULA}; //-------------------------------------------------------------------------- /// Args constructor // SpellCard(SpellType type); //-------------------------------------------------------------------------- /// Destructor // ~SpellCard(); //---------------------------------------------------------------------------- /// Method to get the Spell Type /// @return SpellType The type of the Spell // virtual SpellType getSpellType() const; private: SpellType spell_type_; //-------------------------------------------------------------------------- /// Method to check if a Spell Action can be executed /// @param game Ref to a game obj /// @return True if Spell Action can be executed // bool action(Game& game); }; } #endif //ASSIGNMENT_5758_SPELLCARD_HPP
true
229b5a72b8814cdf1e162787f25bebf04d434923
C++
WonseokLee/danhobak
/GAssn2/GAssn1/GameObject.cpp
UTF-8
2,498
2.84375
3
[ "Apache-2.0" ]
permissive
#include "GameObject.h" #include <GL/freeglut.h> GameObject::GameObject( GameObject* parent, Vector2& position, double rotation, Vector2& scale ) : parent( parent ), position( position ), rotation( rotation ), scale( scale ) { } GameObject::~GameObject() { for each( auto child in children ) { delete child; } } void GameObject::updateAll() { this->update(); for( auto objectIter = children.begin(); objectIter != children.end(); ++objectIter ) { GameObject* object = *objectIter; object->updateAll(); } } void GameObject::drawAll() { glMatrixMode( GL_MODELVIEW ); glPushMatrix(); glTranslated( pos().x, pos().y, 0 ); glRotated( rotation, 0, 0, -1 ); glScaled( scale.x, scale.y, 0 ); this->draw(); for( auto objectIter = children.begin(); objectIter != children.end(); ++objectIter ) { GameObject* object = *objectIter; object->drawAll(); } glMatrixMode( GL_MODELVIEW ); glPopMatrix(); } void GameObject::addChild( GameObject* child ) { children.push_back( child ); } GameObject* GameObject::popChild( GameObject* child ) { for( auto objectIter = children.begin(); objectIter != children.end(); ++objectIter ) { GameObject* object = *objectIter; if( object == child ) { children.erase( objectIter ); return object; break; } } return NULL; } void GameObject::deleteChild( GameObject* child ) { if( popChild( child ) != NULL ) delete child; } void GameObject::deleteChildren() { for( auto objectIter = children.begin(); objectIter != children.end(); ++objectIter ) { GameObject* object = *objectIter; delete object; } children.clear(); } GameObject* GameObject::getParent() { return parent; } GameObject* GameObject::getAncestor() { GameObject* object = this; while( object->getParent() != NULL ) object = object->parent; return object; } std::vector<GameObject*>* GameObject::getChildren() { return &children; } Vector2& GameObject::pos() { return position; } Vector2 GameObject::absPos() { Vector2 abs = position; if( parent != NULL ) abs += parent->absPos(); return abs; } double& GameObject::rot() { return rotation; } double GameObject::absRot() { double abs = rotation; if( parent != NULL ) abs += parent->absRot(); return abs; } Vector2& GameObject::sc() { return scale; } Vector2 GameObject::absSc() { Vector2 abs = scale; if( parent != NULL ) abs += parent->absSc(); return abs; }
true
df56e7d7c0ed7c42f3c4b237a00598b73baf6ee2
C++
SarthakBhatia2018/topicwisegfg
/Arrays/arr_pair.cpp
UTF-8
412
3.109375
3
[]
no_license
#include <iostream> #include <map> using namespace std; int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7}; int n = sizeof(arr) / sizeof(arr[0]); int k = 13; map<int, int> m; for (int i = 0; i < n; ++i) { if (m.find(k - arr[i]) != m.end()) { cout << "Found"; return 0; } m[arr[i]] += 1; } cout << "Not found!"; return 0; }
true
508b4444368aed91fff271b30d76b7fde3260aaa
C++
SakritiDixit/ProgrammingHub
/nth_fibonacci_number.cpp
UTF-8
238
3.03125
3
[ "MIT" ]
permissive
#include<iostream> using namespace std; int fib(int n) { int i; f[0] = 0; f[1] = 1; for (i = 2; i <= n; i++) { f[i] = f[i-1] + f[i-2]; } return f[n]; } int main () { int n; cin>>n; cout<< fib(n)<<endl; return 0; }
true
970d90b491904445545618553188d4e254c4db53
C++
minaminao/algorithms
/DataStructures/SparseTable.cpp
UTF-8
699
2.640625
3
[]
no_license
// Verified: https://codeforces.com/contest/689/submission/62583075 struct SparseTable { int n; int lg_n; vector<int> a; vector<vector<int>> mini; vector<int> lg; // O(n log n) SparseTable(const vector<int> &a) :a(a), n(a.size()), lg(n + 1), lg_n(log2(n) + 1), mini(lg_n, vector<int>(n)) { for (int i = 2; i <= n; i++) lg[i] = lg[i >> 1] + 1; for (int i = 0; i < n; i++) mini[0][i] = a[i]; for (int k = 0; k + 1 < lg_n; k++) for (int i = 0; i + (1 << k) < n; i++) mini[k + 1][i] = min(mini[k][i], mini[k][i + (1 << k)]); } // O(1) [l,r) int query(int l, int r) { if (r - l <= 0)return INF; int k = lg[r - l]; return min(mini[k][l], mini[k][r - (1 << k)]); } };
true
3c61df0771a57ecedbd045d35678ac35e260b3a9
C++
ajalsingh/PFMS-A2020
/tutorials/week07/examples/ex03/radar.cpp
UTF-8
1,681
3.203125
3
[]
no_license
#include <iostream> #include <stdlib.h> #include "radar.h" #include <vector> #include <chrono> #include <thread> Radar::Radar(): scanningTime_(100),ready_(false){ //Generate first random value std::random_device rd; generator_= new std::mt19937(rd()); value_ = new std::uniform_real_distribution<double>(0.1,maxDistance_); data_.resize(numTarget_); } void Radar::start(){ while(true){ generateData(); } } void Radar::generateData(){ //generate random number of targets for each target (N) create Target containing random range and bearing between ^stored values // Info on dereferecing pointer https://stackoverflow.com/questions/27081035/why-should-i-dereference-a-pointer-before-calling-the-operator-in-c/27081074#27081074 //We can now create a wait which will behave like a real sensor if we lock the mutex std::unique_lock<std::mutex> lck(mtx_); for (unsigned int i=0; i < numTarget_; i++){ data_.at(i)=value_->operator()(*generator_); } ready_=true; lck.unlock(); cv_.notify_all(); std::this_thread::sleep_for (std::chrono::milliseconds(static_cast<int>(scanningTime_))); } std::vector<double> Radar::getData(){ //! We wait for the convar to release us, unless data is already ready std::unique_lock<std::mutex> lck(mtx_); while (!ready_) cv_.wait(lck); std::vector<double> data = data_; ready_=false; lck.unlock(); //The below piece of code emulates a real sensor blocking call return data; } void Radar::setScanningTime(double scanningTime){ scanningTime_ = scanningTime; } double Radar::getScanningTime(void){ return scanningTime_; } double Radar::getMaxDistance(void){ return maxDistance_; }
true
8751835a421d3c0a51ae922433e6396044546cb5
C++
Jinxiaohai/DataStructureAndAlgorithm
/old/hanoiUseRecursive/towersofhanoi.cpp
UTF-8
335
2.6875
3
[]
no_license
#include <iostream> #include "functionhead.h" long int totalStep = 0; void towersOfHanoi(int n, int x, int y, int z) { if (n > 0) { towersOfHanoi(n - 1, x, z, y); std::cout << "Move top disk from tower " << x << " to top of tower" << y << std::endl; ++totalStep; towersOfHanoi(n - 1, z, y, x); } }
true
1855f6fc5912d483f53bc8ad5ae60bd19c283305
C++
smiegrin/Splunk
/MainMenu.cpp
UTF-8
2,000
2.546875
3
[]
no_license
#include "MainMenu.h" #include "Button.h" #include "ResourceManager.h" #include "GameScreen.h" #include <math.h> MainMenu::MainMenu() { playButton = Button(325,400,150,50,sf::Color(97,56,11),"New"); loadButton = Button(325,280,150,50,sf::Color(97,56,11),"Load"); title = sf::Text(); title.setString("Splunk"); title.setCharacterSize(50); title.setFont(ResourceManager::PixelFont); } int MainMenu::open(sf::RenderWindow* window) { int anim = 0; bool load = false; sf::RectangleShape fadeOverlay = sf::RectangleShape(sf::Vector2f(800,500)); fadeOverlay.setFillColor(sf::Color(0,0,0,0)); window->setView(window->getDefaultView()); while (window->isOpen()) { sf::Event event; while(window->pollEvent(event)) { if(event.type == sf::Event::Closed) window->close(); if(event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::Escape) window->close(); } if(event.type == sf::Event::MouseButtonPressed) { if(playButton.pointOnBox(event.mouseButton.x, event.mouseButton.y)) anim = 121; if(loadButton.pointOnBox(event.mouseButton.x, event.mouseButton.y)) load = true, anim = 121; } if(event.type == sf::Event::Resized) window->setView(sf::View(sf::Vector2f(window->getSize().x/2,window->getSize().y/2), sf::Vector2f(window->getSize()))); } if(anim < 120) title.setPosition(5,pow((float)(anim - 120),3)/-1728), anim++; if(anim == 120) title.setPosition(5,0); if(anim >= 121) fadeOverlay.setFillColor(sf::Color(0,0,0,255*(anim-120)/60)), anim++; if(anim == 180) { GameScreen(load).open(window); anim = 120; } window->clear(sf::Color(0,0,0,255)); window->draw(playButton); window->draw(loadButton); window->draw(title); window->draw(fadeOverlay); window->display(); } return 0; }
true
b78ef82fd94474f7a55b257b30ee5b58ade3321b
C++
anas-01/PointersAndAddress
/PointersAndAddress/main.cpp
UTF-8
1,243
3.71875
4
[]
no_license
#include<iostream> #include<string> using namespace std; int main() { int givenInt = 32; float givenFloat = 64.212; double givenDouble = 4.76545; string givenString = "Hey look at me! I know pointers!"; char givenChar = '*'; int* pointerToInt = &givenInt; float* pointerToFloat = &givenFloat; double* pointerToDouble = &givenDouble; string* pointerToString = &givenString; char* pointerToChar = &givenChar; cout << "Pointers and Address Memory Location" << '\n'; cout << "\n"; cout << "Value of givenInt: " << *pointerToInt << '\n'; cout << "Address location of givenInt: " << pointerToInt << '\n'; cout << "\n"; cout << "Value of givenFloat: " << *pointerToFloat << '\n'; cout << "Address location of givenFloat: " << pointerToFloat << '\n'; cout << "\n"; cout << "Value of givenDouble: " << *pointerToDouble << '\n'; cout << "Address location of givenDouble: " << pointerToDouble << '\n'; cout << "\n"; cout << "Value of givenString: " << *pointerToString << '\n'; cout << "Address location of givenString: " << pointerToString << '\n'; cout << "\n"; cout << "Value of givenChar: " << *pointerToChar << '\n'; cout << "Address location of givenChar: " << pointerToChar << '\n'; cout << "\n"; return 0; }
true
f9215502e67739c1250eb77b2b3054cdca231b95
C++
Masters-Akt/CS_codes
/DSA/patterns/p4.cpp
UTF-8
352
2.515625
3
[]
no_license
//Halp Pyramid after 180 degrees rotation /* * * * * * * * * * * * * * * * */ #include<bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(j<=n-i) cout<<" "; else cout<<"* "; } cout<<endl; } return 0; }
true
85df5bc028d9190813eb29c1d251ef88571d84df
C++
antoinechalifour/Cpp_TP2
/Point.h
ISO-8859-2
576
3.3125
3
[]
no_license
#ifndef POINT_H_INCLUDED #define POINT_H_INCLUDED class Point{ private : double x; double y; double z; char* label; public: //Constructeurs Point(); Point(double x, double y, double z, char* label); Point(const Point& p); ~Point(); //Operateurs Point& operator=(const Point& p); //Getters const double getX() const; const double getY() const; const double getZ() const; char* getLabel() const; //Autres mthodes static double distance(Point& p1, Point& p2); }; #endif // POINT_H_INCLUDED
true
3745ef2f720a5844a18481414bd4148651caff09
C++
ankurshaswat/Starlings
/boids_examples/flocking/flocking/src/engineUtils.cpp
UTF-8
2,767
2.734375
3
[ "MIT" ]
permissive
/******************************************************************** * @file engineUtils.cpp * @author Erik Larsson * @version 1.0 * @section DESCRIPTION * *********************************************************************/ #include "engineUtils.h" using namespace std; GLuint loadShader(const char* vertexFile, const char* fragmentFile) { GLuint vertexShaderID = glCreateShader(GL_VERTEX_SHADER); GLuint fragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); std::string vertexCode; std::ifstream vertexShaderStream(vertexFile, std::ios::in); if(vertexShaderStream.is_open()) { std::string line = ""; while(getline(vertexShaderStream, line)) { vertexCode += "\n" + line; } vertexShaderStream.close(); } else { printf("Could not read Vertex shader file"); return 0; } std::string fragmentCode; std::ifstream fragmentShaderStream (fragmentFile, std::ios::in); if(fragmentShaderStream.is_open()) { std::string line = ""; while(getline(fragmentShaderStream, line)) { fragmentCode += "\n" + line; } fragmentShaderStream.close(); } else { printf("Could not read Fragment shader file"); return 0; } GLint result = GL_FALSE; int infoLog; printf("Compiling Shader file"); char const *vertexSource = vertexCode.c_str(); glShaderSource(vertexShaderID, 1, &vertexSource, NULL); glCompileShader(vertexShaderID); glGetShaderiv(vertexShaderID, GL_COMPILE_STATUS, &result); glGetShaderiv(vertexShaderID, GL_INFO_LOG_LENGTH, &infoLog); if(infoLog > 0) { std::vector<char> vertexError(infoLog+1); glGetShaderInfoLog(vertexShaderID, infoLog, NULL, &vertexError[0]); //printf("%s\n", vertexError); } printf("Compiling Fragment file"); char const *fragmentSource = fragmentCode.c_str(); glShaderSource(fragmentShaderID, 1, &fragmentSource, NULL); glCompileShader(fragmentShaderID); glGetShaderiv(fragmentShaderID, GL_COMPILE_STATUS, &result); glGetShaderiv(fragmentShaderID, GL_INFO_LOG_LENGTH, &infoLog); if(infoLog > 0) { std::vector<char> fragmentError(infoLog+1); glGetShaderInfoLog(fragmentShaderID, infoLog, NULL, &fragmentError[0]); //printf("%s\n", fragmentError); } printf("Linking program\n"); GLuint programID = glCreateProgram(); glAttachShader(programID, vertexShaderID); glAttachShader(programID, fragmentShaderID); glLinkProgram(programID); glGetProgramiv(programID, GL_LINK_STATUS, &result); glGetProgramiv(programID, GL_INFO_LOG_LENGTH, &infoLog); if(infoLog > 0) { std::vector<char> linkingError(infoLog+1); glGetProgramInfoLog(programID, infoLog, NULL, &linkingError[0]); printf("%s\n", &linkingError[0]); } glDeleteShader(vertexShaderID); glDeleteShader(fragmentShaderID); return programID; } double getRand() { return rand()/(double)RAND_MAX; }
true
81de0b8e4fb6dc846353a44943c1dd4b2db0a7ea
C++
xmil9/towers
/deps/spiel/lap_clock.h
UTF-8
1,405
3.09375
3
[ "MIT" ]
permissive
// // Nov-2020, Michael Lindner // MIT license // #pragma once #include <chrono> namespace sp { /////////////////// // Clock to measure repeated events. template <typename T, typename Unit = std::chrono::milliseconds> class LapClock { public: using TimePoint = std::chrono::steady_clock::time_point; using UnitType = Unit; using ValueType = T; public: // Starts a new lap. TimePoint nextLap(); // Returns the length of the last full lap. T lapLength(float factor = 1.0f) const; // Returns the length of time passed since the current lap started. T elapsedInLap(float factor = 1.0f) const; private: std::chrono::steady_clock m_clock; TimePoint m_lastLap; Unit m_lapLength{0}; }; template <typename T, typename Duration> typename LapClock<T, Duration>::TimePoint LapClock<T, Duration>::nextLap() { const TimePoint now = m_clock.now(); m_lapLength = std::chrono::duration_cast<Duration>(now - m_lastLap); m_lastLap = now; return now; } template <typename T, typename Duration> T LapClock<T, Duration>::lapLength(float factor) const { return static_cast<T>(m_lapLength.count() * factor); } template <typename T, typename Duration> T LapClock<T, Duration>::elapsedInLap(float factor) const { const auto elapsed = std::chrono::duration_cast<Duration>(m_clock.now() - m_lastLap); return static_cast<T>(elapsed.count() * factor); } } // namespace sp
true
3ec01c1a8364d9e885ad3fe8c1cdea6b6759c3d9
C++
RolandQuest/CppGLEngine
/includes/core/camera/camera.h
UTF-8
663
2.65625
3
[]
no_license
#pragma once #include "glm/glm.hpp" namespace fml { class camera { private: glm::vec3 _position; glm::vec3 _direction; glm::vec3 _up; glm::vec3 _right; public: camera() = default; camera( const glm::vec3& position, const glm::vec3& direction ); virtual ~camera() = default; glm::mat4 getViewMat(); void setPosition( const glm::vec3& position ); void setDirection( const glm::vec3& direction ); void setTarget( const glm::vec3& target ); void setUp( const glm::vec3& up ); void movePosition( const glm::vec3& distance ); void movePosition( float distance ); //zoom in/out }; }
true
6a36458bea10b858ad5e073570cc00d00dd5602e
C++
machavesperez/-articleStoreManagement
/Chaves_Perez_MiguelAngel/P1/fecha.hpp
UTF-8
1,433
2.875
3
[]
no_license
#ifndef Fecha_H_ #define Fecha_H_ #include <iostream> #include <cstdlib> #include <cstdio> #include <ctime> class Fecha { public: class Invalida { public: Invalida(const char* error): error_(error){} const char* por_que()const {return error_;} private: const char* error_; }; explicit Fecha(int dia=0, int mes=0, int anno=0); Fecha(const char* cadenaFecha); static const int AnnoMinimo = 1902; static const int AnnoMaximo = 2037; int dia()const; int mes()const; int anno()const; Fecha operator ++(int);//POST INC Fecha& operator ++();//PRE INC Fecha operator --(int);// POST DEC Fecha& operator --();// PRE INC Fecha& operator +=(int numDia); Fecha& operator -=(int numDia); Fecha operator +(int numDia) const; Fecha operator -(int numDia) const; const char* cadena()const; private: int dia_; int mes_; int anno_; bool valida()const; }; long int operator -(const Fecha& fecha1, const Fecha& fecha2); bool operator <(const Fecha& fecha1, const Fecha& fecha2); bool operator <=(const Fecha& fecha1, const Fecha& fecha2); bool operator >=(const Fecha& fecha1, const Fecha& fecha2); bool operator ==(const Fecha& fecha1, const Fecha& fecha2); bool operator >(const Fecha& fecha1, const Fecha& fecha2); bool operator !=(const Fecha& fecha1, const Fecha& fecha2); std::istream& operator>>(std::istream& is, Fecha& fecha); std::ostream& operator<<(std::ostream& os, const Fecha& fecha); #endif
true
10db88299f446f5572ccfe0d16ec4955b22533d4
C++
adi-g15/DiskArray
/example/main.cpp
UTF-8
1,669
3.125
3
[ "Unlicense" ]
permissive
#define DISKARRAY_DEBUG #define DISKARRAY_KEEP_FILES #define DISKARRAY_LOG_SAVES // "Above defines not needed; Include order doesn;t matter" #include <DiskArray/diskarray.hpp> #include "bigobject.pb.h" using namespace diskarray; int main() { DiskArray<bigobject> arr; for (auto i = 0; i < 3; i++) { bigobject obj; obj.set_name("Aditya"); obj.set_id(40); obj.add_data(std::rand()); arr.push_back(obj); } bigobject fourth_object; fourth_object.set_name("Hidden King"); fourth_object.set_id(15035); fourth_object.add_data(1); fourth_object.add_data(5); // fourth_object.add_data(4); // works fine fourth_object.add_data(0); // zeroes out all next elements too (Read comment at main.cpp:55) fourth_object.add_data(3); fourth_object.add_data(5); auto encoded = fourth_object.SerializeAsString(); std::cout << "Encoded length is: " << encoded.size() << "\n"; arr.push_back(fourth_object); for (auto i = 0; i < 999996; i++) { bigobject obj; obj.set_name("Aditya"); obj.set_id(40); obj.add_data(std::rand()); arr.push_back(obj); } using std::cout, std::endl; auto parsed_obj = arr.at( 3 ); bigobject& reborn_fourth = parsed_obj; cout << reborn_fourth.name() << endl; cout << reborn_fourth.id() << endl; /* * A problem here: * It seems the data was restored, reborn_fourth.data() also shows 5 elements, but the elements after the 0 are all zero, ie. 3, 5 * */ for (const auto& i: reborn_fourth.data()) { cout << i << ", "; } cout << endl; }
true
9e76037f44e3c178d41225299eede9c62a9e8973
C++
nkryuchkov/matrix_simple
/matrix.h
UTF-8
5,125
2.96875
3
[]
no_license
#ifndef MATRIX_H #define MATRIX_H #include <fstream> #include <sstream> #include <string> #include <iomanip> #include <cmath> #include <cstdlib> #define OUT_WIDTH 1 using namespace std; template <class T, int M, int N = M> class Matrix { public: Matrix() { p_ = new T*[M]; for (int i = 0; i < M; i++) { p_[i] = new T[N]; } } Matrix(const Matrix<T, M, N>& copy) { for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { p_[i][j] = copy.p_[i][j]; } } } ~Matrix() { for (int i = 0; i < M; i++) { delete[] p_[i]; } delete[] p_; } T* operator[](int i) { return p_[i]; } Matrix<T, M, N> operator- () { Matrix<T, M, N> c; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { c[i][j] = -(*this)[i][j]; } } return c; } Matrix<T, M, N>& operator= (Matrix<T, M, N> a) { if (&a == this) { return *this; } for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { (*this)[i][j] = a[i][j]; } } return *this; } Matrix<T, M, N>& operator+= (Matrix<T, M, N>& a) { for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { (*this)[i][j] += a[i][j]; } } return *this; } Matrix<T, M, N>& operator-= (Matrix<T, M, N>& a) { for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { (*this)[i][j] += a[i][j]; } } return *this; } Matrix<T, M, N>& operator*= (Matrix<T, M, N>& a) { return *this = (operator* (*this, a)); } Matrix<T, M, N>& operator*= (int b) { for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { (*this)[i][j] *= b; } } return *this; } template<class T1, int M1, int N1> friend ofstream& operator<< (ofstream& os, Matrix<T, M, N>& a); template<class T1, int M1, int N1> friend ifstream& operator>> (ifstream& is, Matrix<T, M, N>& a); template<class T1, int M1, int N1> friend Matrix<T, M, N> operator+ (Matrix<T, M, N>& a, Matrix<T, M, N>& b); template<class T1, int M1, int N1> friend Matrix<T, M, N> operator- (Matrix<T, M, N>& a, Matrix<T, M, N>& b); template<class T1, int M1, int N1, int K1> friend Matrix<T, M, N> operator* (Matrix<T, M, N>& a, Matrix<T, M, N>& b); template<class T1, int M1, int N1> friend Matrix<T, M, N> operator* (Matrix<T, M, N>& a, T b); template<class T1, int M1, int N1> friend Matrix<T, M, N> operator* (T b, Matrix<T, M, N>& a); template<class T1, int M1, int N1> friend bool operator== (Matrix<T, M, N>& a, Matrix<T, M, N>& b); template<class T1, int M1, int N1> friend bool operator!= (Matrix<T, M, N>& a, Matrix<T, M, N>& b); private: T** p_; }; template<class T, int M, int N = M> ofstream& operator<< (ofstream& os, Matrix<T, M, N>& a) { for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { os << setw(OUT_WIDTH) << a[i][j] << " "; } os << endl; } return os; } template <class T, int M, int N = M> ifstream& operator>> (ifstream &is, Matrix<T, M, N>& a) { string line; for (int i = 0; i < M; i++) { getline(is, line); stringstream ss(line); for (int j = 0; j < N; j++) { ss >> a[i][j]; } } return is; } template<class T, int M, int N = M> ostream& operator<< (ostream& os, Matrix<T, M, N>& a) { for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { os << setw(OUT_WIDTH) << a[i][j] << " "; } os << endl; } return os; } template <class T, int M, int N = M> istream& operator>> (istream &is, Matrix<T, M, N>& a) { string line; for (int i = 0; i < M; i++) { getline(is, line); stringstream ss(line); for (int j = 0; j < N; j++) { ss >> a[i][j]; } } return is; } template <class T, int M, int N = M> Matrix<T, M, N> operator+ (Matrix<T, M, N>& a, Matrix<T, M, N>& b) { Matrix<T, M, N> c; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { c[i][j] = a[i][j] + b[i][j]; } } return c; } template <class T, int M, int N = M> Matrix<T, M, N> operator- (Matrix<T, M, N>& a, Matrix<T, M, N>& b) { Matrix<T, M, N> c; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { c[i][j] = a[i][j] - b[i][j]; } } return c; } template<class T, int M, int N = M, int K> Matrix<T, M, K> operator* (Matrix<T, M, N>& a, Matrix<T, N, K>& b) { Matrix<T, M, K> c; for (int i = 0; i < M; i++) { for (int j = 0; j < K; j++) { c[i][j] = 0; for (int k = 0; k < N; k++) { c[i][j] += a[i][k] * b[k][j]; } } } return c; } template<class T, int M, int N = M> Matrix<T, M, N> operator* (Matrix<T, M, N>& a, T b) { Matrix<T, M, N> c; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { c[i][j] = a[i][j] *b; } } return c; } template<class T, int M, int N = M> Matrix<T, M, N> operator* (T b, Matrix<T, M, N>& a) { return a * b; } template<class T, int M, int N = M> bool operator== (Matrix<T, M, N>& a, Matrix<T, M, N>& b) { for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { if (a[i][j] != b[i][j]) { return false; } } } return true; } template<class T, int M, int N = M> bool operator!= (Matrix<T, M, N>& a, Matrix<T, M, N>& b) { return !(a == b); } #endif
true
0a916e96bfa0c711a9f3124fd3a6943758056215
C++
ParadoxGameConverters/CK2ToEU4
/CK2ToEU4/Source/Mappers/RegionMapper/Area.h
UTF-8
646
2.71875
3
[ "MIT" ]
permissive
#ifndef EU4_AREA_H #define EU4_AREA_H #include "Parser.h" #include <map> #include <memory> namespace EU4 { class Province; } namespace mappers { class Area: commonItems::parser { public: explicit Area(std::istream& theStream); [[nodiscard]] const auto& getProvinces() const { return provinces; } [[nodiscard]] bool areaContainsProvince(int province) const; void linkProvince(const std::pair<int, std::shared_ptr<EU4::Province>>& theProvince) { provinces[theProvince.first] = theProvince.second; } private: void registerKeys(); std::map<int, std::shared_ptr<EU4::Province>> provinces; }; } // namespace mappers #endif // EU4_AREA_H
true
561b0e6589f74435ebb0a60ccfa866388013325d
C++
gwgrisk/msc-hull-snowglobe
/Snowglobe/Snowglobe/InputMgr.h
UTF-8
4,313
2.6875
3
[]
no_license
#pragma once #include <AntiMatter\precision.h> #include <AntiMatter\Singleton.h> class KeyData { public: enum KeyState { KeyUp, KeyDown }; private: KeyState m_Up; KeyState m_Down; KeyState m_Forward; KeyState m_Back; KeyState m_Left; KeyState m_Right; KeyState m_Use; KeyState m_Space; KeyState m_Shift; KeyState m_Ctrl; KeyState m_Alt; KeyState m_Escape; KeyState m_F1; KeyState m_F2; KeyState m_F3; KeyState m_F4; KeyState m_F5; KeyState m_F6; KeyState m_F7; KeyState m_F8; KeyState m_F9; KeyState m_F10; KeyState m_F11; KeyState m_F12; public: KeyData(); void Reset() { m_Up = KeyUp; m_Down = KeyUp; m_Forward = KeyUp; m_Back = KeyUp; m_Left = KeyUp; m_Right = KeyUp; m_Use = KeyUp; m_Space = KeyUp; m_Shift = KeyUp; m_Ctrl = KeyUp; m_Alt = KeyUp; m_Escape = KeyUp; } // gets const KeyState Up() const { return m_Up; } const KeyState Down() const { return m_Down; } const KeyState Forward() const { return m_Forward; } const KeyState Back() const { return m_Back; } const KeyState Left() const { return m_Left; } const KeyState Right() const { return m_Right; } const KeyState Use() const { return m_Use; } const KeyState Space() const { return m_Space; } const KeyState Shift() const { return m_Shift; } const KeyState Ctrl() const { return m_Ctrl; } const KeyState Alt() const { return m_Alt; } const KeyState Escape() const { return m_Escape; } const KeyState F1() const { return m_F1; } const KeyState F2() const { return m_F2; } const KeyState F3() const { return m_F3; } const KeyState F4() const { return m_F4; } const KeyState F5() const { return m_F5; } const KeyState F6() const { return m_F6; } const KeyState F7() const { return m_F7; } const KeyState F8() const { return m_F8; } const KeyState F9() const { return m_F9; } const KeyState F10() const { return m_F10; } const KeyState F11() const { return m_F11; } const KeyState F12() const { return m_F12; } // sets void Up( const KeyState n ) { m_Up = n; } void Down( const KeyState n ) { m_Down = n; } void Forward( const KeyState n ){ m_Forward = n; } void Back( const KeyState n ) { m_Back = n; } void Left( const KeyState n ) { m_Left = n; } void Right( const KeyState n ) { m_Right = n; } void Use( const KeyState n ) { m_Use = n; } void Space( const KeyState n ) { m_Space = n; } void Shift( const KeyState n ) { m_Shift = n; } void Ctrl( const KeyState n ) { m_Ctrl = n; } void Alt( const KeyState n ) { m_Alt = n; } void Escape( const KeyState n ) { m_Escape = n; } void F1( const KeyState n ) { m_F1 = n; } void F2( const KeyState n ) { m_F2 = n; } void F3( const KeyState n ) { m_F3 = n; } void F4( const KeyState n ) { m_F4 = n; } void F5( const KeyState n ) { m_F5 = n; } void F6( const KeyState n ) { m_F6 = n; } void F7( const KeyState n ) { m_F7 = n; } void F8( const KeyState n ) { m_F8 = n; } void F9( const KeyState n ) { m_F9 = n; } void F10( const KeyState n ) { m_F10 = n; } void F11( const KeyState n ) { m_F11 = n; } void F12( const KeyState n ) { m_F12 = n; } }; class MouseData { public: enum MouseBtn { MBtnUp, MBtnDown }; private: int m_nXPosition; int m_nYPosition; real m_rMouseSpeed; MouseBtn m_LButton; MouseBtn m_RButton; real m_rWheelDelta; public: MouseData(); MouseData( int x, int y, real rSpeed ); // gets const int x() const { return m_nXPosition; } const int y() const { return m_nYPosition; } const real speed() const { return m_rMouseSpeed; } const MouseBtn LBtn() const { return m_LButton; } const MouseBtn RBtn() const { return m_RButton; } // sets void x( const int & x ) { m_nXPosition = x; } void y( const int & y ) { m_nYPosition = y; } void speed( const real & r ) { m_rMouseSpeed = r; } void LBtn( const MouseBtn & n ) { m_LButton = n; } void RBtn( const MouseBtn & n ) { m_RButton = n; } }; class InputMgr : public Singleton<InputMgr> { friend class Singleton <InputMgr>; private: KeyData m_keyboard; MouseData m_mouse; public: KeyData & Keybd() { return m_keyboard; } MouseData & Mouse() { return m_mouse; } };
true
6eb7b54a8486013c3ac55b4206a8f59f45fdb614
C++
zxch3n/Leetcode
/93/main.cpp
UTF-8
1,373
2.953125
3
[]
no_license
class Solution { private: bool isValid(string s){ if (s.size() == 0 || (s[0] == '0' && s.size() != 1)) return false; if (s.size() < 3) return true; if (s[0] < '2') return true; if (s[0] > '2') return false; if (s[1] < '5') return true; if (s[1] > '5') return false; if (s[2] > '5') return false; return true; } void _restoreIp(string s, int leftField, string tempAns, vector<string>& ans){ if (leftField == 1 && isValid(s) ){ ans.push_back(tempAns + '.' + s); return; } if (s.size() > leftField * 3){ return; } int maxLength = min(3, int(s.size() - leftField + 1)); if (s[0] == '0'){ maxLength = 1; } for (int length = max(1, int(s.size() - (leftField - 1)*3)); length <= maxLength; length++){ if (length < 3 || isValid(s)){ string sub = s.substr(0, length); _restoreIp(s.substr(length), leftField-1, tempAns.size()==0?sub:tempAns+"."+sub, ans); } } } public: vector<string> restoreIpAddresses(string s) { vector<string> ans; _restoreIp(s, 4, "", ans); return ans; } };
true
6df01b1d24c9dabe2fe90b8b27f57d82ed8ee07f
C++
correderadiego/robotBipedFirmwareTest
/test/plenLibrary/logic/controller/parser/ParserControllerControllerCommandTest.cpp
UTF-8
8,232
2.640625
3
[]
no_license
/* * ParserControllerControllerCommandTest.h * * Created on: 22 abr. 2020 * Author: Diego */ #ifndef TEST_PLENLIBRARY_LOGIC_CONTROLLER_PARSER_PARSERCONTROLLERCONTROLLERCOMMANDTEST_CPP_ #define TEST_PLENLIBRARY_LOGIC_CONTROLLER_PARSER_PARSERCONTROLLERCONTROLLERCOMMANDTEST_CPP_ #include "gtest/gtest.h" #include "logic/bean/hardware/Buffer.h" #include <logic/bean/commands/CommandInterface.h> #include <logic/controller/parser/ParserControllerControllerCommand.h> #include <logic/bean/commands/controllerCommands/ControllerCommand.h> #include <logic/bean/commands/controllerCommands/ApplyNativeValueCommand.h> namespace { class ParserControllerControllerCommandTest : public ::testing::Test{ protected: Buffer* buffer; CommandInterface* command = 0; ParserControllerControllerCommand* parserControllerControllerCommand = new ParserControllerControllerCommand(); void populateBuffer(char message[]){ for (int i = 0; i < (int)strlen(message); i++) { buffer->addChar(message[i]); } } void SetUp(){ buffer = new Buffer(); } void TearDown() { buffer->clearBuffer(); delete buffer; delete command; delete parserControllerControllerCommand; } }; TEST_F(ParserControllerControllerCommandTest, correctMatch){ char message [] = "$AN\r"; populateBuffer(message); ASSERT_TRUE(parserControllerControllerCommand->match(buffer)); } TEST_F(ParserControllerControllerCommandTest, wrongMatch){ char message [] = "<AN\r"; populateBuffer(message); ASSERT_FALSE(parserControllerControllerCommand->match(buffer)); } TEST_F(ParserControllerControllerCommandTest, applyNativeValueCommandType){ char message [] = "$AN0a3e8\r"; populateBuffer(message); parserControllerControllerCommand->parse(buffer, &command); ASSERT_EQ(command->getCommandType(), CommandInterface::CONTROLLER_COMMAND); } TEST_F(ParserControllerControllerCommandTest, applyNativeValueSubCommandType){ char message [] = "$AN0a3e8\r"; populateBuffer(message); parserControllerControllerCommand->parse(buffer, &command); ASSERT_EQ(((ApplyNativeValueCommand*)command)->getSubCommandType(), ControllerCommand::APPY_NATIVE_VALUE); } TEST_F(ParserControllerControllerCommandTest, applyNativeValueWrongCommandLengthLess){ char message [] = "$AN0a3e\r"; populateBuffer(message); ASSERT_EQ(parserControllerControllerCommand->parse(buffer, &command), ParserInterface::WRONG_LENGHT_COMMAND_ERROR); } TEST_F(ParserControllerControllerCommandTest, applyNativeValueWrongCommandLengthMore){ char message [] = "$AN0a3e333\r"; populateBuffer(message); ASSERT_EQ(parserControllerControllerCommand->parse(buffer, &command), ParserInterface::WRONG_LENGHT_COMMAND_ERROR); } TEST_F(ParserControllerControllerCommandTest, applyNativeValueDeviceId){ char message [] = "$AN0a3e8\r"; populateBuffer(message); parserControllerControllerCommand->parse(buffer, &command); int deviceIdInt = ((ApplyNativeValueCommand*)command)->getDeviceId(); ASSERT_EQ(deviceIdInt, 10); } TEST_F(ParserControllerControllerCommandTest, applyNativeValueValue){ char message [] = "$AN0a3e8\r"; populateBuffer(message); parserControllerControllerCommand->parse(buffer, &command); int value = ((ApplyNativeValueCommand*)command)->getValue(); ASSERT_EQ(value, 1000); } TEST_F(ParserControllerControllerCommandTest, applyDiffValueCommandType){ char message [] = "$AD0a3e8\r"; populateBuffer(message); parserControllerControllerCommand->parse(buffer, &command); ASSERT_EQ(command->getCommandType(), CommandInterface::CONTROLLER_COMMAND); } TEST_F(ParserControllerControllerCommandTest, applyDiffValueSubCommandType){ char message [] = "$AD0a3e8\r"; populateBuffer(message); parserControllerControllerCommand->parse(buffer, &command); ASSERT_EQ(((ApplyDiffValueCommand *)command)->getSubCommandType(), ControllerCommand::APPLY_DIFF_VALUE); } TEST_F(ParserControllerControllerCommandTest, applyDiffValueWrongCommandLengthLess){ char message [] = "$AD0a3e\r"; populateBuffer(message); ASSERT_EQ(parserControllerControllerCommand->parse(buffer, &command), ParserInterface::WRONG_LENGHT_COMMAND_ERROR); } TEST_F(ParserControllerControllerCommandTest, applyDiffValueWrongCommandLengthMore){ char message [] = "$AD0a3e333\r"; populateBuffer(message); ASSERT_EQ(parserControllerControllerCommand->parse(buffer, &command), ParserInterface::WRONG_LENGHT_COMMAND_ERROR); } TEST_F(ParserControllerControllerCommandTest, applyDiffValueDeviceId){ char message [] = "$AD0a3e8\r"; populateBuffer(message); parserControllerControllerCommand->parse(buffer, &command); int deviceIdInt = ((ApplyDiffValueCommand*)command)->getDeviceId(); ASSERT_EQ(deviceIdInt, 10); } TEST_F(ParserControllerControllerCommandTest, applyDiffValueValue){ char message [] = "$AN0a3e8\r"; populateBuffer(message); parserControllerControllerCommand->parse(buffer, &command); int value = ((ApplyDiffValueCommand*)command)->getValue(); ASSERT_EQ(value, 1000); } TEST_F(ParserControllerControllerCommandTest, playAMotionCommandType){ char message [] = "$PM04\r"; populateBuffer(message); parserControllerControllerCommand->parse(buffer, &command); ASSERT_EQ(command->getCommandType(), CommandInterface::CONTROLLER_COMMAND); } TEST_F(ParserControllerControllerCommandTest, playAMotionSubCommandType){ char message [] = "$PM04\r"; populateBuffer(message); parserControllerControllerCommand->parse(buffer, &command); ASSERT_EQ(((PlayAMotionCommand *)command)->getSubCommandType(), ControllerCommand::PLAY_A_MOTION); } TEST_F(ParserControllerControllerCommandTest, playAMotionWrongCommandLengthLess){ char message [] = "$PM0\r"; populateBuffer(message); ASSERT_EQ(parserControllerControllerCommand->parse(buffer, &command), ParserInterface::WRONG_LENGHT_COMMAND_ERROR); } TEST_F(ParserControllerControllerCommandTest, playAMotionWrongCommandLengthMore){ char message [] = "$PM04555\r"; populateBuffer(message); ASSERT_EQ(parserControllerControllerCommand->parse(buffer, &command), ParserInterface::WRONG_LENGHT_COMMAND_ERROR); } TEST_F(ParserControllerControllerCommandTest, playAMotionSlot){ char message [] = "$PM04\r"; populateBuffer(message); parserControllerControllerCommand->parse(buffer, &command); int slot = ((PlayAMotionCommand*)command)->getPosition(); ASSERT_EQ(slot, 4); } TEST_F(ParserControllerControllerCommandTest, stopAMotionCommandType){ char message [] = "$SM\r"; populateBuffer(message); parserControllerControllerCommand->parse(buffer, &command); ASSERT_EQ(command->getCommandType(), CommandInterface::CONTROLLER_COMMAND); } TEST_F(ParserControllerControllerCommandTest, stopAMotionSubCommandType){ char message [] = "$SM\r"; populateBuffer(message); parserControllerControllerCommand->parse(buffer, &command); ASSERT_EQ(((PlayAMotionCommand *)command)->getSubCommandType(), ControllerCommand::STOP_A_MOTION); } TEST_F(ParserControllerControllerCommandTest, stopAMotionWrongCommandLengthMore){ char message [] = "$SM04\r"; populateBuffer(message); ASSERT_EQ(parserControllerControllerCommand->parse(buffer, &command), ParserInterface::WRONG_LENGHT_COMMAND_ERROR); } TEST_F(ParserControllerControllerCommandTest, applyHomeCommandType){ char message [] = "$HP\r"; populateBuffer(message); parserControllerControllerCommand->parse(buffer, &command); ASSERT_EQ(command->getCommandType(), CommandInterface::CONTROLLER_COMMAND); } TEST_F(ParserControllerControllerCommandTest, applyHomenSubCommandType){ char message [] = "$HP\r"; populateBuffer(message); parserControllerControllerCommand->parse(buffer, &command); ASSERT_EQ(((PlayAMotionCommand *)command)->getSubCommandType(), ControllerCommand::APPLY_HOME_POSITION); } TEST_F(ParserControllerControllerCommandTest, applyHomeWrongCommandLengthMore){ char message [] = "$HP04\r"; populateBuffer(message); ASSERT_EQ(parserControllerControllerCommand->parse(buffer, &command), ParserInterface::WRONG_LENGHT_COMMAND_ERROR); } } #endif /* TEST_PLENLIBRARY_LOGIC_CONTROLLER_PARSER_PARSERCONTROLLERCONTROLLERCOMMANDTEST_CPP_ */
true
a9e62b75750026a1b43bec86d3f2ee7c438f326e
C++
GuelorEmanuel/Team-Tech-Support
/D4/cupid/Storage/project.h
UTF-8
840
2.734375
3
[]
no_license
#ifndef PROJECT_H #define PROJECT_H #include "storage.h" #include <QString> #include <vector> class Student; class Project { public: virtual ~Project()=0; virtual int getId() const = 0; virtual void setId(int value) = 0; virtual int getMinTeamSize() const = 0; virtual void setMinTeamSize(int value) = 0; virtual int getMaxTeamSize() const = 0; virtual void setMaxTeamSize(int value) = 0; virtual QString getName() const = 0; virtual void setName(QString value) = 0; virtual QString getDescription() const = 0; virtual void setDescription(QString value) = 0; virtual storage::StudentList getStudents() = 0; virtual void setStudents(storage::StudentList students) = 0; virtual void registerStudent(storage::StudentPtr student) = 0; protected: Project(); }; #endif // PROJECT_H
true
db0b887f5f2c904121d9d68e16144bd88ec1951d
C++
elishatofunmi/miscellaneous
/c++ programs/recursion.cpp
UTF-8
299
3.65625
4
[]
no_license
#include <iostream> #include <cmath> using namespace std; int factorial_final(int x){ if (x==1){ return 1; }else{ return x*factorial_final(x-1); } } int main() { int solution; solution = factorial_final(5); cout << "Answer of this is: "<<solution<<endl; }
true
610b9b66d3cb644058d671afbeef2b3fa2b3c4f4
C++
neuralfirings/flashbutton
/flash_arduino/flash_arduino.ino
UTF-8
2,217
2.8125
3
[]
no_license
/* * Simple HTTP get webclient test */ #include <ESP8266WiFi.h> // Your Settings const char* ssids[] = {"Superplexus", "Guest", "Nancy's iPhone"}; const char* passwords[] = {"WolfBabyDog", "", "WolfBabyDog"}; const char* host = "www.nyl.io"; const char* url = "/espbuttonpress.php"; // The program void setup() { int max_try = 5; // number of seconds to try connecting to a network before giving up Serial.begin(115200); delay(100); // We start by connecting to a WiFi network for (int i = 0; i < sizeof(ssids); i++) { if (WiFi.status() != WL_CONNECTED) { WiFi.begin(ssids[i], passwords[i]); Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(ssids[i]); int ctr = 0; while (WiFi.status() != WL_CONNECTED && ctr <= max_try) { delay(1000); Serial.print(ctr); ctr++; if (ctr == max_try) { WiFi.disconnect(); } } // Infinite cycles through SSIDs if (WiFi.status() != WL_CONNECTED && i == sizeof(ssids)-1) { i = 0; } } } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } int value = 0; void loop() { delay(5000); ++value; Serial.print("connecting to "); Serial.println(host); // Use WiFiClient class to create TCP connections WiFiClient client; const int httpPort = 80; if (!client.connect(host, httpPort)) { Serial.println("connection failed"); return; } // We now create a URI for the request Serial.print("Requesting URL: "); Serial.println(url); // This will send the request to the server client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"); delay(500); // Read all the lines of the reply from server and print them to Serial // while(client.available()){ // String line = client.readStringUntil('\r'); // Serial.print(line); // } Serial.println(); Serial.println("closing connection"); ESP.deepSleep(0,WAKE_RF_DEFAULT); delay(2000); Serial.println("shouldn't see this"); }
true
7047d8e9c1ce20c0b158ec7732b338985257ab45
C++
cubeman99/SEAL
/src/utilities/FileUtility.cpp
UTF-8
805
3.15625
3
[ "MIT" ]
permissive
#include "FileUtility.h" bool FileUtility::OpenAndGetContents(const std::string& fileName, std::string& outContents) { // Open the file. FILE* m_file = fopen(fileName.c_str(), "r"); if (m_file == nullptr) return false; // Determine the file size. if (fseek(m_file, 0, SEEK_END) != 0) return false; long fileSize = ftell(m_file); if (fileSize < 0) return false; rewind(m_file); // Read the entire file into a character buffer. const size_t fileSizeInclNull = fileSize + 1; char* buffer = new char[fileSizeInclNull]; size_t result = fread(buffer, 1, fileSizeInclNull, m_file); if (result == 0) { delete buffer; return false; } // Finalize the buffer as the output string. buffer[result] = '\0'; outContents.assign(buffer, buffer + result); delete buffer; return true; }
true
00c0b91839aa24b6957f4566920a003b2fca2327
C++
fadal2002/Weather-Smart-Device
/SSDCourseWork17068266/weatherData.h
UTF-8
829
2.828125
3
[]
no_license
#ifndef OBSERVER_PATTERN_WEATHERDATA #define OBSERVER_PATTERN_WEATHERDATA #include <vector> #include <algorithm> #include <iostream> #include "subject.h" #include "Observer.h" class WeatherData : public Subject { private: vector<Observer *> observers; //vector that will store all the observers float temperature = 0.0f; float humidity = 0.0f; float airPressure = 0.0f; public: float getTemp(void) { return temperature; } float getHumidity(void) { return humidity; } float getAirPressure(void) { return airPressure; } void registerObserver(Observer *observer) override; void removeObserver(Observer *observer) override; void notifyObservers() override; //create the new state of the weather station void setState(void); void getLiveData(void); }; #endif // !OBSERVER_PATTERN_WEATHERDATA
true
0a00d718fa2a227de082324dbbf7edfb4925a237
C++
Sujay-Shah/Eggnapped
/TetraiderEngine/Source/SpawnOnHealthZero.h
UTF-8
2,113
2.875
3
[]
no_license
/* Start Header ------------------------------------------------------- Copyright (C) 2018 DigiPen Institute of Technology. Reproduction or disclosure of this file or its contents without the prior written consent of DigiPen Institute of Technology is prohibited. Author: <Moodie Ghaddar> - End Header --------------------------------------------------------*/ #pragma once #ifndef SPAWN_ONHEALTH_ZERO_H #define SPAWN_ONHEALTH_ZERO_H struct RandomDrop { RandomDrop(std::string name, int weight) : m_prefabName(name), m_weight(weight) {} std::string m_prefabName; int m_weight; }; enum DropType { PREFAB_ONLY = 0, RANDOM_ONLY, BOTH_TYPES }; class SpawnOnHealthZero : public Component { private: std::vector<std::string> m_prefabs; DropType m_dropType; std::vector<RandomDrop> m_randomDrops; int RandomDropIndex(); // For a given prefab name, will call the GOM to spawn it and set it's position accordingly void _SpawnPrefab(std::string prefab); // Will spawn either predetermined prefabs, random prefabs, or both depending on this // component's DropType void _SpawnPrefabs(); public: SpawnOnHealthZero(); ~SpawnOnHealthZero(); static Component* CreateInstance() { return new SpawnOnHealthZero(); } virtual void Deactivate(); virtual void Update(float dt); virtual void Serialize(const json& j); virtual void LateInitialize(); virtual void LateUpdate(float dt) {} virtual void HandleEvent(Event* pEvent); virtual void Override(const json& j); // Adds the new prefab to the prefab list void AddSpawnObject(std::string prefab); // Sets this component to only spawn prefabs within the prefab list, if any inline void DisableRandom() { m_dropType = DropType::PREFAB_ONLY; } // Sets this component to only spawn random prefabs from within the randomDrops list, if any inline void EnableOnlyRandom() { m_dropType = DropType::RANDOM_ONLY; } // Enables this component to spawn both predetermined prefabs within the prefab list as // well as random prefabs from within the randomDrops list, if any inline void EnableRandomAndPrefab() { m_dropType = DropType::BOTH_TYPES; } }; #endif
true